// BlockingPoll is just a stub function that forwards to the poll() system call
// on non-amd64 platforms.
16486
func BlockingPoll(fds *PollEvent, nfds int, timeout int64) (int, syscall.Errno) {
	n, _, e := syscall.Syscall(syscall.SYS_POLL, uintptr(unsafe.Pointer(fds)), uintptr(nfds), uintptr(timeout))
	return int(n), e
}
271605
func (t *Thread) Blocked() bool {
	regs, err := t.Registers(false)
	if err != nil {
		return false
	}
	pc := regs.PC()
	f, ln, fn := t.BinInfo().PCToLine(pc)
	if fn == nil {
		if f == "" && ln == 0 {
			return true
		}
		return false
	}
	switch fn.Name {
	case "runtime.futex", "runtime.usleep", "runtime.clone":
		return true
	case "runtime.kevent":
		return true
	case "runtime.mach_semaphore_wait", "runtime.mach_semaphore_timedwait":
		return true
	default:
		return strings.HasPrefix(fn.Name, "syscall.Syscall") || strings.HasPrefix(fn.Name, "syscall.RawSyscall")
	}
}
489417
func (p *MiddlewarePoller) Poll(b *Bot, dest chan Update, stop chan struct{}) {
	cap := 1
	if p.Capacity > 1 {
		cap = p.Capacity
	}

	middle := make(chan Update, cap)
	stopPoller := make(chan struct{})

	go p.Poller.Poll(b, middle, stopPoller)

	for {
		select {
		// call to stop
		case <-stop:
			stopPoller <- struct{}{}

		// poller is done
		case <-stopPoller:
			close(stop)
			return

		case upd := <-middle:
			if p.Filter(&upd) {
				dest <- upd
			}
		}
	}
}
340111
func (p *Peer) stallHandler() {
	// These variables are used to adjust the deadline times forward by the
	// time it takes callbacks to execute.  This is done because new
	// messages aren't read until the previous one is finished processing
	// (which includes callbacks), so the deadline for receiving a response
	// for a given message must account for the processing time as well.
	var handlerActive bool
	var handlersStartTime time.Time
	var deadlineOffset time.Duration

	// pendingResponses tracks the expected response deadline times.
	pendingResponses := make(map[string]time.Time)

	// stallTicker is used to periodically check pending responses that have
	// exceeded the expected deadline and disconnect the peer due to
	// stalling.
	stallTicker := time.NewTicker(stallTickInterval)
	defer stallTicker.Stop()

	// ioStopped is used to detect when both the input and output handler
	// goroutines are done.
	var ioStopped bool
out:
	for {
		select {
		case msg := <-p.stallControl:
			switch msg.command {
			case sccSendMessage:
				// Add a deadline for the expected response
				// message if needed.
				p.maybeAddDeadline(pendingResponses,
					msg.message.Command())

			case sccReceiveMessage:
				// Remove received messages from the expected
				// response map.  Since certain commands expect
				// one of a group of responses, remove
				// everything in the expected group accordingly.
				switch msgCmd := msg.message.Command(); msgCmd {
				case wire.CmdBlock:
					fallthrough
				case wire.CmdMerkleBlock:
					fallthrough
				case wire.CmdTx:
					fallthrough
				case wire.CmdNotFound:
					delete(pendingResponses, wire.CmdBlock)
					delete(pendingResponses, wire.CmdMerkleBlock)
					delete(pendingResponses, wire.CmdTx)
					delete(pendingResponses, wire.CmdNotFound)

				default:
					delete(pendingResponses, msgCmd)
				}

			case sccHandlerStart:
				// Warn on unbalanced callback signalling.
				if handlerActive {
					log.Warn("Received handler start " +
						"control command while a " +
						"handler is already active")
					continue
				}

				handlerActive = true
				handlersStartTime = time.Now()

			case sccHandlerDone:
				// Warn on unbalanced callback signalling.
				if !handlerActive {
					log.Warn("Received handler done " +
						"control command when a " +
						"handler is not already active")
					continue
				}

				// Extend active deadlines by the time it took
				// to execute the callback.
				duration := time.Since(handlersStartTime)
				deadlineOffset += duration
				handlerActive = false

			default:
				log.Warnf("Unsupported message command %v",
					msg.command)
			}

		case <-stallTicker.C:
			// Calculate the offset to apply to the deadline based
			// on how long the handlers have taken to execute since
			// the last tick.
			now := time.Now()
			offset := deadlineOffset
			if handlerActive {
				offset += now.Sub(handlersStartTime)
			}

			// Disconnect the peer if any of the pending responses
			// don't arrive by their adjusted deadline.
			for command, deadline := range pendingResponses {
				if now.Before(deadline.Add(offset)) {
					continue
				}

				log.Debugf("Peer %s appears to be stalled or "+
					"misbehaving, %s timeout -- "+
					"disconnecting", p, command)
				p.Disconnect()
				break
			}

			// Reset the deadline offset for the next tick.
			deadlineOffset = 0

		case <-p.inQuit:
			// The stall handler can exit once both the input and
			// output handler goroutines are done.
			if ioStopped {
				break out
			}
			ioStopped = true

		case <-p.outQuit:
			// The stall handler can exit once both the input and
			// output handler goroutines are done.
			if ioStopped {
				break out
			}
			ioStopped = true
		}
	}

	// Drain any wait channels before going away so there is nothing left
	// waiting on this goroutine.
cleanup:
	for {
		select {
		case <-p.stallControl:
		default:
			break cleanup
		}
	}
	log.Tracef("Peer stall handler done for %s", p)
}
633473
func (c *Peer) Block(f func(*Writer)) {
	c.mu.Lock()
	defer c.mu.Unlock()
	f(&Writer{c.w})
}
424947
func (a *API) SwitchBlockOn(args params.BlockSwitchParams) params.ErrorResult {
	if err := a.checkCanWrite(); err != nil {
		return params.ErrorResult{Error: common.ServerError(err)}
	}

	err := a.access.SwitchBlockOn(state.ParseBlockType(args.Type), args.Message)
	return params.ErrorResult{Error: common.ServerError(err)}
}
327492
func (t *Termbox) PollEvent(ctx context.Context) chan termbox.Event {
	// XXX termbox.PollEvent() can get stuck on unexpected signal
	// handling cases. We still would like to wait until the user
	// (termbox) has some event for us to process, but we don't
	// want to allow termbox to control/block our input loop.
	//
	// Solution: put termbox polling in a separate goroutine,
	// and we just watch for a channel. The loop can now
	// safely be implemented in terms of select {} which is
	// safe from being stuck.
	evCh := make(chan termbox.Event)

	go func() {
		// keep listening to suspend requests here
		for {
			select {
			case <-ctx.Done():
				return
			case <-t.suspendCh:
				if pdebug.Enabled {
					pdebug.Printf("poll event suspended!")
				}
				t.Close()
			}
		}
	}()

	go func() {
		defer func() { recover() }()
		defer func() { close(evCh) }()

		for {
			ev := termbox.PollEvent()
			if ev.Type != termbox.EventInterrupt {
				evCh <- ev
				continue
			}

			select {
			case <-ctx.Done():
				return
			case replyCh := <-t.resumeCh:
				t.Init()
				close(replyCh)
			}
		}
	}()
	return evCh

}
1361645
func (c *pollChangeManager) pollChangeWithBackoff() {
	// has been launched before
	if atomic.SwapInt32(c.isLaunched, 1) == int32(1) {
		log.Error("pollChangeManager: pollChangeWithBackoff() has been launched before")
		return
	}

	log.Debug("pollChangeManager: pollChangeWithBackoff() started pollWithBackoff")
	go pollWithBackoff(c.quitChan, c.pollChangeAgent, c.handleChangeServerError)

}
1314360
func (m UnblockingMutex) TryLock() (result bool) {
	select {
	case m.C <- true:
		return true
	default:
		return false
	}
}
1059937
func (p *PollerShutdownManager) StopPollers() {
	log.Printf("component=PollerShutdownManager at=stop-pollers")
	for _, r := range p.registeredPollers {
		log.Printf("component=PollerShutdownManager at=sending-stop name=%s", r.name)
		r.stopChannel <- true
	}
	for _, r := range p.registeredPollers {
		log.Printf("component=PollerShutdownManager at=awaiting-stop-ack name=%s", r.name)
		<-r.stopAckChannel
		log.Printf("component=PollerShutdownManager at=stop-ack name=%s", r.name)
	}
}
928639
func (opts *IngestExternalFileOptions) SetAllowBlockingFlush(flag bool) {
	C.rocksdb_ingestexternalfileoptions_set_allow_blocking_flush(opts.c, boolToChar(flag))
}
707995
func (c *Collector) RunPoller() {
	for {
		c.pollHost()
		for _, m := range c.transform() {
			c.MetricsChan <- m
		}
		time.Sleep(c.PollPeriod)
	}
}
992815
func WithPollingInterval(interval time.Duration) PollerConfigOption {
	return PollerConfigOption(func(c *Poller) {
		c.interval = interval
	})
}
1016498
func (s *Subscription) Poll(timeout time.Duration) (Event, error) {
	dl.Debugln("poll", timeout)

	s.timeout.Reset(timeout)

	select {
	case e, ok := <-s.events:
		if !ok {
			return e, ErrClosed
		}
		if runningTests {
			// Make the behavior stable when running tests to avoid randomly
			// varying test coverage. This ensures, in practice if not in
			// theory, that the timer fires and we take the true branch of
			// the next if.
			s.timeout.Reset(0)
			runtime.Gosched()
		}
		if !s.timeout.Stop() {
			// The timeout must be stopped and possibly drained to be ready
			// for reuse in the next call.
			<-s.timeout.C
		}
		return e, nil
	case <-s.timeout.C:
		return Event{}, ErrTimeout
	}
}
304217
func (c *ConfigLocal) BlockServer() BlockServer {
	c.lock.RLock()
	defer c.lock.RUnlock()
	return c.bserv
}
1350145
func (pgb *ChainDB) BlockMissedVotes(blockHash string) ([]string, error) {
	ctx, cancel := context.WithTimeout(pgb.ctx, pgb.queryTimeout)
	defer cancel()
	mv, err := RetrieveMissedVotesInBlock(ctx, pgb.db, blockHash)
	return mv, pgb.replaceCancelError(err)
}
67606
func (m *Manager) HandleHTTPLongPolling(pattern string) {
	log.Infof("workflow Manager listening to web traffic at %v/{create,poll,delete}", pattern)
	lpm := newLongPollingManager(m)

	handleAPI(pattern+"/create", func(w http.ResponseWriter, r *http.Request) error {
		result, i, err := lpm.create(r.URL)
		if err != nil {
			return fmt.Errorf("longPollingManager.create failed: %v", err)
		}

		w.Header().Set("Content-Type", jsonContentType)
		w.Header().Set("Content-Length", fmt.Sprintf("%v", len(result)))
		if _, err := w.Write(result); err != nil {
			lpm.remove(i)
		}
		return nil
	})

	handleAPI(pattern+"/poll/", func(w http.ResponseWriter, r *http.Request) error {
		i, err := getID(r.URL.Path, pattern+"/poll/")
		if err != nil {
			return err
		}

		result, err := lpm.poll(i)
		if err != nil {
			return fmt.Errorf("longPollingManager.poll failed: %v", err)
		}

		w.Header().Set("Content-Type", jsonContentType)
		w.Header().Set("Content-Length", fmt.Sprintf("%v", len(result)))
		if _, err := w.Write(result); err != nil {
			lpm.remove(i)
		}
		return nil
	})

	handleAPI(pattern+"/remove/", func(w http.ResponseWriter, r *http.Request) error {
		i, err := getID(r.URL.Path, pattern+"/remove/")
		if err != nil {
			return err
		}

		lpm.remove(i)
		http.Error(w, "", http.StatusOK)
		return nil
	})

	handleAPI(pattern+"/action/", func(w http.ResponseWriter, r *http.Request) error {
		_, err := getID(r.URL.Path, pattern+"/action/")
		if err != nil {
			return err
		}

		data, err := ioutil.ReadAll(r.Body)
		if err != nil {
			return err
		}

		ap := &ActionParameters{}
		if err := json.Unmarshal(data, ap); err != nil {
			return err
		}

		ctx := context.TODO()
		if err := m.NodeManager().Action(ctx, ap); err != nil {
			return fmt.Errorf("Action failed: %v", err)
		}
		http.Error(w, "", http.StatusOK)
		return nil
	})
}