// Must be write-locked prior to calling.
423759
func (c *requestCache) gc() {
	now := c.clock.Now()
	for c.ll.Len() > 0 {
		oldest := c.ll.Back()
		entry := oldest.Value.(*cacheEntry)
		if !now.After(entry.expireTime) {
			return
		}

		// Oldest value is expired; remove it.
		c.ll.Remove(oldest)
		delete(c.tokens, entry.token)
	}
}
1051445
func (t *throttledWriteCloser) Write(data []byte) (int, error) {

	// Write must either write len(data) bytes or return an error
	allocation := Bandwidth(0)

	for allocation < Bandwidth(len(data)) {
		// Get some bandwidth
		thisAllocation, ok := <-t.pool.bandwidthAllocatorChan
		if !ok {
			// Pool has been released
			return 0, errors.New("Pool has been released")
		}
		allocation += thisAllocation
	}

	// Do the write
	n, err := t.origWriteCloser.Write(data)

	// Free up what we didn't use
	if Bandwidth(n) < allocation && allocation != Unlimited {
		t.pool.bandwidthFreeChan <- allocation - Bandwidth(n)
	}

	return n, err
}
609747
func isWriteEvent(event notify.Event) bool {
	for _, ev := range eventWrite {
		if event&ev != 0 {
			return true
		}
	}
	return false
}
1023603
func (db *DB) writeLocked(batch, ourBatch *Batch, merge, sync bool) error {
	// Try to flush memdb. This method would also trying to throttle writes
	// if it is too fast and compaction cannot catch-up.
	mdb, mdbFree, err := db.flush(batch.internalLen)
	if err != nil {
		db.unlockWrite(false, 0, err)
		return err
	}
	defer mdb.decref()

	var (
		overflow bool
		merged   int
		batches  = []*Batch{batch}
	)

	if merge {
		// Merge limit.
		var mergeLimit int
		if batch.internalLen > 128<<10 {
			mergeLimit = (1 << 20) - batch.internalLen
		} else {
			mergeLimit = 128 << 10
		}
		mergeCap := mdbFree - batch.internalLen
		if mergeLimit > mergeCap {
			mergeLimit = mergeCap
		}

	merge:
		for mergeLimit > 0 {
			select {
			case incoming := <-db.writeMergeC:
				if incoming.batch != nil {
					// Merge batch.
					if incoming.batch.internalLen > mergeLimit {
						overflow = true
						break merge
					}
					batches = append(batches, incoming.batch)
					mergeLimit -= incoming.batch.internalLen
				} else {
					// Merge put.
					internalLen := len(incoming.key) + len(incoming.value) + 8
					if internalLen > mergeLimit {
						overflow = true
						break merge
					}
					if ourBatch == nil {
						ourBatch = db.batchPool.Get().(*Batch)
						ourBatch.Reset()
						batches = append(batches, ourBatch)
					}
					// We can use same batch since concurrent write doesn't
					// guarantee write order.
					ourBatch.appendRec(incoming.keyType, incoming.key, incoming.value)
					mergeLimit -= internalLen
				}
				sync = sync || incoming.sync
				merged++
				db.writeMergedC <- true

			default:
				break merge
			}
		}
	}

	// Release ourBatch if any.
	if ourBatch != nil {
		defer db.batchPool.Put(ourBatch)
	}

	// Seq number.
	seq := db.seq + 1

	// Write journal.
	if err := db.writeJournal(batches, seq, sync); err != nil {
		db.unlockWrite(overflow, merged, err)
		return err
	}

	// Put batches.
	for _, batch := range batches {
		if err := batch.putMem(seq, mdb.DB); err != nil {
			panic(err)
		}
		seq += uint64(batch.Len())
	}

	// Incr seq number.
	db.addSeq(uint64(batchesLen(batches)))

	// Rotate memdb if it's reach the threshold.
	if batch.internalLen >= mdbFree {
		db.rotateMem(0, false)
	}

	db.unlockWrite(overflow, merged, nil)
	return nil
}
459443
func (f *PrefetchFile) Write(ctx context.Context, req *fuse.WriteRequest,
	resp *fuse.WriteResponse) (err error) {
	f.fs.log.CDebugf(ctx, "PrefetchFile (enable: %t) Write", f.enable)
	defer func() { err = f.fs.processError(ctx, libkbfs.WriteMode, err) }()
	if len(req.Data) == 0 {
		return nil
	}

	f.fs.config.BlockOps().TogglePrefetcher(f.enable)

	resp.Size = len(req.Data)
	return nil
}
517741
func (ctx *rtmCtx) trywrite(e *Event) error {
	tctx, cancel := context.WithTimeout(ctx, ctx.writeTimeout)
	defer cancel()

	select {
	case <-tctx.Done():
		switch err := tctx.Err(); err {
		case context.DeadlineExceeded:
			return errors.New("write timeout")
		default:
			return err
		}
	case ctx.outbuf <- e:
		return nil
	}

	return errors.New("unreachable")
}
138432
func (fc *DocumentsWriterFlushControl) waitIfStalled() {
	if fc.infoStream.IsEnabled("DWFC") {
		fc.infoStream.Message(
			"DWFC", "waitIfStalled: numFlushesPending: %v netBytes: %v flushingBytes: %v fullFlush: %v",
			fc.flushQueue.Len(), fc.netBytes(), fc.flushBytes(), fc.fullFlush)
	}
	fc.DocumentsWriterStallControl.waitIfStalled()
}
582585
func (m *RWMutex) Lock() {
	var caller string
	if _, file, line, ok := runtime.Caller(1); ok {
		caller = fmt.Sprintf("%s:%d", file, line)
	}
	if m.log {
		astilog.Debugf("Requesting lock for %s at %s", m.name, caller)
	}
	m.mutex.Lock()
	if m.log {
		astilog.Debugf("Lock acquired for %s at %s", m.name, caller)
	}
	m.lastSuccessfulLockCaller = caller
}
923525
func (c *Client) writeBlock(data []byte) (int, error) {
	ss, err := c.streamSizes()
	if err != nil {
		return 0, err
	}
	// TODO: maybe make this buffer (and header and trailer buffers) part of Context struct
	var b [4]sspi.SecBuffer
	b[0].Set(sspi.SECBUFFER_STREAM_HEADER, make([]byte, ss.Header))
	b[1].Set(sspi.SECBUFFER_DATA, data)
	b[2].Set(sspi.SECBUFFER_STREAM_TRAILER, make([]byte, ss.Trailer))
	b[3].Set(sspi.SECBUFFER_EMPTY, nil)
	ret := sspi.EncryptMessage(c.ctx.Handle, 0, sspi.NewSecBufferDesc(b[:]), 0)
	switch ret {
	case sspi.SEC_E_OK:
	case sspi.SEC_E_CONTEXT_EXPIRED:
		// TODO: handle this
		panic("writeBlock: SEC_E_CONTEXT_EXPIRED")
	default:
		return 0, ret
	}
	n1, err := b[0].WriteAll(c.conn)
	if err != nil {
		return n1, err
	}
	n2, err := b[1].WriteAll(c.conn)
	if err != nil {
		return n1 + n2, err
	}
	n3, err := b[2].WriteAll(c.conn)
	return n1 + n2 + n3, err
}
887526
func (c *cacheControlResponseWriter) WriteHeader(statusCode int) {
	c.statusCode = statusCode
	c.ResponseWriter.WriteHeader(statusCode)
}
383647
func WriteWait(writeWait time.Duration) func(*WSClient) {
	return func(c *WSClient) {
		c.writeWait = writeWait
	}
}
477448
func (w *ByteWriter) MustWriteInt64(val int64, offset int) int {
	return w.MustWriteVal(val, offset)
}
1233542
func (w *responseWriter) SetWritten(n int) {
	if n >= NoWritten && n <= StatusCodeWritten {
		w.written = n
	}
}
315789
func FSWriteLock(f *os.File) error {
	if err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX); err != nil {
		return trace.ConvertSystemError(err)
	}
	return nil
}
396958
func (l *WAL) LastWriteTime() time.Time {
	l.mu.RLock()
	defer l.mu.RUnlock()
	return l.lastWriteTime
}
630588
func (p *printer) cachedWriteError() error {
	_, err := p.Write(nil)
	return err
}
346113
func (w *ByteWriter) MustWriteInt32(val int32, offset int) int {
	return w.MustWriteVal(val, offset)
}