1 /* Copyright © 1994-1999 Lucent Technologies Inc. All rights reserved.
2 * Portions Copyright © 1997-1999 Vita Nuova Limited
3 * Portions Copyright © 2000-2007 Vita Nuova Holdings Limited
5 * Revisions Copyright © 2000-2007 Lucent Technologies Inc. and others
7 * Modified for the Akaros operating system:
8 * Copyright (c) 2013-2014 The Regents of the University of California
9 * Copyright (c) 2013-2015 Google Inc.
11 * Permission is hereby granted, free of charge, to any person obtaining a copy
12 * of this software and associated documentation files (the "Software"), to deal
13 * in the Software without restriction, including without limitation the rights
14 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
15 * copies of the Software, and to permit persons to whom the Software is
16 * furnished to do so, subject to the following conditions:
18 * The above copyright notice and this permission notice shall be included in
19 * all copies or substantial portions of the Software.
21 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
22 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
23 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
24 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
25 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
26 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
43 #define PANIC_EXTRA(b) \
45 if ((b)->extra_len) { \
48 panic("%s doesn't handle extra_data", __FUNCTION__); \
52 static uint32_t padblockcnt;
53 static uint32_t concatblockcnt;
54 static uint32_t pullupblockcnt;
55 static uint32_t copyblockcnt;
56 static uint32_t consumecnt;
57 static uint32_t producecnt;
58 static uint32_t qcopycnt;
71 struct block *bfirst; /* buffer */
74 int len; /* bytes allocated to queue */
75 int dlen; /* data bytes in queue */
76 int limit; /* max bytes in queue */
77 int inilim; /* initial limit */
79 int eof; /* number of eofs read by user */
81 void (*kick) (void *); /* restart output */
82 void (*bypass) (void *, struct block *); /* bypass queue altogether */
83 void *arg; /* argument to kick */
85 struct rendez rr; /* process waiting to read */
86 struct rendez wr; /* process waiting to write */
87 qio_wake_cb_t wake_cb; /* callbacks for qio wakeups */
94 Maxatomic = 64 * 1024,
95 QIO_CAN_ERR_SLEEP = (1 << 0), /* can throw errors or block/sleep */
96 QIO_LIMIT = (1 << 1), /* respect q->limit */
97 QIO_DROP_OVERFLOW = (1 << 2), /* alternative to setting qdropoverflow */
98 QIO_JUST_ONE_BLOCK = (1 << 3), /* when qbreading, just get one block */
99 QIO_NON_BLOCK = (1 << 4), /* throw EAGAIN instead of blocking */
100 QIO_DONT_KICK = (1 << 5), /* don't kick when waking */
103 unsigned int qiomaxatomic = Maxatomic;
105 static size_t copy_to_block_body(struct block *to, void *from, size_t copy_amt);
106 static ssize_t __qbwrite(struct queue *q, struct block *b, int flags);
107 static struct block *__qbread(struct queue *q, size_t len, int qio_flags,
109 static bool qwait_and_ilock(struct queue *q, int qio_flags);
111 /* Helper: fires a wake callback, sending 'filter' */
112 static void qwake_cb(struct queue *q, int filter)
115 q->wake_cb(q, q->wake_data, filter);
121 printd("pad %lu, concat %lu, pullup %lu, copy %lu\n",
122 padblockcnt, concatblockcnt, pullupblockcnt, copyblockcnt);
123 printd("consume %lu, produce %lu, qcopy %lu\n",
124 consumecnt, producecnt, qcopycnt);
128 * pad a block to the front (or the back if size is negative)
130 struct block *padblock(struct block *bp, int size)
134 uint8_t bcksum = bp->flag & BCKSUM_FLAGS;
135 uint16_t checksum_start = bp->checksum_start;
136 uint16_t checksum_offset = bp->checksum_offset;
137 uint16_t mss = bp->mss;
139 QDEBUG checkb(bp, "padblock 1");
141 if (bp->rp - bp->base >= size) {
142 bp->checksum_start += size;
149 panic("padblock %p", getcallerpc(&bp));
152 nbp = block_alloc(size + n, MEM_WAIT);
155 memmove(nbp->wp, bp->rp, n);
165 panic("padblock %p", getcallerpc(&bp));
167 if (bp->lim - bp->wp >= size)
172 nbp = block_alloc(size + n, MEM_WAIT);
173 memmove(nbp->wp, bp->rp, n);
179 nbp->checksum_start = checksum_start;
180 nbp->checksum_offset = checksum_offset;
183 QDEBUG checkb(nbp, "padblock 1");
188 * return count of bytes in a string of blocks
190 int blocklen(struct block *bp)
203 * return count of space in blocks
205 int blockalloclen(struct block *bp)
218 * copy the string of blocks into
219 * a single block and free the string
221 struct block *concatblock(struct block *bp)
224 struct block *nb, *f;
229 /* probably use parts of qclone */
231 nb = block_alloc(blocklen(bp), MEM_WAIT);
232 for (f = bp; f; f = f->next) {
234 memmove(nb->wp, f->rp, len);
237 concatblockcnt += BLEN(nb);
239 QDEBUG checkb(nb, "concatblock 1");
243 /* Makes an identical copy of the block, collapsing all the data into the block
244 * body. It does not point to the contents of the original, it is a copy
245 * (unlike qclone). Since we're copying, we might as well put the memory into
246 * one contiguous chunk. */
247 struct block *copyblock(struct block *bp, int mem_flags)
250 struct extra_bdata *ebd;
253 QDEBUG checkb(bp, "copyblock 0");
254 newb = block_alloc(BLEN(bp), mem_flags);
257 amt = copy_to_block_body(newb, bp->rp, BHLEN(bp));
258 assert(amt == BHLEN(bp));
259 for (int i = 0; i < bp->nr_extra_bufs; i++) {
260 ebd = &bp->extra_data[i];
261 if (!ebd->base || !ebd->len)
263 amt = copy_to_block_body(newb, (void*)ebd->base + ebd->off, ebd->len);
264 assert(amt == ebd->len);
266 /* TODO: any other flags that need copied over? */
267 if (bp->flag & BCKSUM_FLAGS) {
268 newb->flag |= (bp->flag & BCKSUM_FLAGS);
269 newb->checksum_start = bp->checksum_start;
270 newb->checksum_offset = bp->checksum_offset;
274 QDEBUG checkb(newb, "copyblock 1");
278 /* Returns a block with the remaining contents of b all in the main body of the
279 * returned block. Replace old references to b with the returned value (which
280 * may still be 'b', if no change was needed. */
281 struct block *linearizeblock(struct block *b)
287 newb = copyblock(b, MEM_WAIT);
292 /* Make sure the first block has at least n bytes in its main body. Pulls up
293 * data from the *list* of blocks. Returns 0 if there is not enough data in the
295 struct block *pullupblock(struct block *bp, int n)
299 struct extra_bdata *ebd;
302 * this should almost always be true, it's
303 * just to avoid every caller checking.
308 /* If there's no chance, just bail out now. This might be slightly wasteful
309 * if there's a long blist that does have enough data. */
310 if (n > blocklen(bp))
312 /* a start at explicit main-body / header management */
314 if (n > bp->lim - bp->rp) {
315 /* would need to realloc a new block and copy everything over. */
316 panic("can't pullup %d bytes, no place to put it: bp->lim %p, bp->rp %p, bp->lim-bp->rp %d\n",
317 n, bp->lim, bp->rp, bp->lim-bp->rp);
320 /* Would need to recursively call this, or otherwise pull from later
321 * blocks and put chunks of their data into the block we're building. */
322 if (len > bp->extra_len)
323 panic("pullup more than extra (%d, %d, %d)\n",
324 n, BHLEN(bp), bp->extra_len);
325 QDEBUG checkb(bp, "before pullup");
326 for (int i = 0; (i < bp->nr_extra_bufs) && len; i++) {
327 ebd = &bp->extra_data[i];
328 if (!ebd->base || !ebd->len)
330 seglen = MIN(ebd->len, len);
331 memcpy(bp->wp, (void*)(ebd->base + ebd->off), seglen);
336 bp->extra_len -= seglen;
338 kfree((void *)ebd->base);
343 /* maybe just call pullupblock recursively here */
345 panic("pullup %d bytes overdrawn\n", len);
346 QDEBUG checkb(bp, "after pullup");
351 * if not enough room in the first block,
352 * add another to the front of the list.
354 if (bp->lim - bp->rp < n) {
355 nbp = block_alloc(n, MEM_WAIT);
361 * copy bytes from the trailing blocks into the first
364 while ((nbp = bp->next)) {
367 memmove(bp->wp, nbp->rp, n);
371 QDEBUG checkb(bp, "pullupblock 1");
374 memmove(bp->wp, nbp->rp, i);
377 bp->next = nbp->next;
382 QDEBUG checkb(bp, "pullupblock 2");
392 * make sure the first block has at least n bytes in its main body
394 struct block *pullupqueue(struct queue *q, int n)
398 /* TODO: lock to protect the queue links? */
399 if ((BHLEN(q->bfirst) >= n))
401 q->bfirst = pullupblock(q->bfirst, n);
402 for (b = q->bfirst; b != NULL && b->next != NULL; b = b->next) ;
407 /* throw away count bytes from the front of
408 * block's extradata. Returns count of bytes
412 static int pullext(struct block *bp, int count)
414 struct extra_bdata *ed;
415 int i, rem, bytes = 0;
417 for (i = 0; bp->extra_len && count && i < bp->nr_extra_bufs; i++) {
418 ed = &bp->extra_data[i];
419 rem = MIN(count, ed->len);
420 bp->extra_len -= rem;
426 kfree((void *)ed->base);
434 /* throw away count bytes from the end of a
435 * block's extradata. Returns count of bytes
439 static int dropext(struct block *bp, int count)
441 struct extra_bdata *ed;
442 int i, rem, bytes = 0;
444 for (i = bp->nr_extra_bufs - 1; bp->extra_len && count && i >= 0; i--) {
445 ed = &bp->extra_data[i];
446 rem = MIN(count, ed->len);
447 bp->extra_len -= rem;
452 kfree((void *)ed->base);
461 * throw away up to count bytes from a
462 * list of blocks. Return count of bytes
465 static int _pullblock(struct block **bph, int count, int free)
474 while (*bph != NULL && count != 0) {
477 n = MIN(BHLEN(bp), count);
481 n = pullext(bp, count);
484 QDEBUG checkb(bp, "pullblock ");
485 if (BLEN(bp) == 0 && (free || count)) {
494 int pullblock(struct block **bph, int count)
496 return _pullblock(bph, count, 1);
500 * trim to len bytes starting at offset
502 struct block *trimblock(struct block *bp, int offset, int len)
507 QDEBUG checkb(bp, "trimblock 1");
508 if (blocklen(bp) < offset + len) {
513 l =_pullblock(&bp, offset, 0);
521 while ((l = BLEN(bp)) < len) {
526 trim = BLEN(bp) - len;
527 trim -= dropext(bp, trim);
537 /* Adjust block @bp so that its size is exactly @len.
538 * If the size is increased, fill in the new contents with zeros.
539 * If the size is decreased, discard some of the old contents at the tail. */
540 struct block *adjustblock(struct block *bp, int len)
542 struct extra_bdata *ebd;
554 /* Shrink within block main body. */
555 if (len <= BHLEN(bp)) {
556 free_block_extra(bp);
557 bp->wp = bp->rp + len;
558 QDEBUG checkb(bp, "adjustblock 1");
563 if (len > BLEN(bp)) {
564 /* Grow within block main body. */
565 if (bp->extra_len == 0 && bp->rp + len <= bp->lim) {
566 memset(bp->wp, 0, len - BLEN(bp));
567 bp->wp = bp->rp + len;
568 QDEBUG checkb(bp, "adjustblock 2");
571 /* Grow with extra data buffers. */
572 buf = kzmalloc(len - BLEN(bp), MEM_WAIT);
573 block_append_extra(bp, (uintptr_t)buf, 0, len - BLEN(bp), MEM_WAIT);
574 QDEBUG checkb(bp, "adjustblock 3");
578 /* Shrink extra data buffers.
579 * len is how much of ebd we need to keep.
580 * extra_len is re-accumulated. */
581 assert(bp->extra_len > 0);
584 for (i = 0; i < bp->nr_extra_bufs; i++) {
585 ebd = &bp->extra_data[i];
589 bp->extra_len += ebd->len;
591 /* If len becomes zero, extra_data[i] should be freed. */
593 ebd = &bp->extra_data[i];
595 bp->extra_len += ebd->len;
598 for (; i < bp->nr_extra_bufs; i++) {
599 ebd = &bp->extra_data[i];
601 kfree((void*)ebd->base);
602 ebd->base = ebd->off = ebd->len = 0;
604 QDEBUG checkb(bp, "adjustblock 4");
608 /* Helper: removes and returns the first block from q */
609 static struct block *pop_first_block(struct queue *q)
611 struct block *b = q->bfirst;
613 q->len -= BALLOC(b); // XXX all usages of q->len with extra_data are fucked
620 /* Helper: copies up to copy_amt from a buf to a block's main body (b->wp) */
621 static size_t copy_to_block_body(struct block *to, void *from, size_t copy_amt)
623 copy_amt = MIN(to->lim - to->wp, copy_amt);
624 memcpy(to->wp, from, copy_amt);
629 /* Accounting helper. Block b in q lost amt extra_data */
630 static void block_and_q_lost_extra(struct block *b, struct queue *q, size_t amt)
637 /* Helper: moves ebd from a block (in from_q) to another block. The *ebd is
638 * fixed in 'from', so we move its contents and zero it out in 'from'.
640 * Returns the length moved (0 on failure). */
641 static size_t move_ebd(struct extra_bdata *ebd, struct block *to,
642 struct block *from, struct queue *from_q)
644 size_t ret = ebd->len;
646 if (block_append_extra(to, ebd->base, ebd->off, ebd->len, MEM_ATOMIC))
648 block_and_q_lost_extra(from, from_q, ebd->len);
649 ebd->base = ebd->len = ebd->off = 0;
653 /* Copy up to len bytes from q->bfirst to @to, leaving the block in place. May
654 * return with less than len, but greater than 0, even if there is more
657 * At any moment that we have copied anything and things are tricky, we can just
658 * return. The trickiness comes from a bunch of variables: is the main body
659 * empty? How do we split the ebd? If our alloc fails, then we can fall back
660 * to @to's main body, but only if we haven't used it yet. */
661 static size_t copy_from_first_block(struct queue *q, struct block *to,
664 struct block *from = q->bfirst;
665 size_t copy_amt, amt;
666 struct extra_bdata *ebd;
668 assert(len < BLEN(from)); /* sanity */
669 /* Try to extract from the main body */
670 copy_amt = MIN(BHLEN(from), len);
672 copy_amt = copy_to_block_body(to, from->rp, copy_amt);
673 from->rp += copy_amt;
674 /* We only change dlen, (data len), not q->len, since the q still has
675 * the same block memory allocation (no kfrees happened) */
678 /* Try to extract the remainder from the extra data */
680 for (int i = 0; (i < from->nr_extra_bufs) && len; i++) {
681 ebd = &from->extra_data[i];
682 if (!ebd->base || !ebd->len)
684 if (len >= ebd->len) {
685 amt = move_ebd(ebd, to, from, q);
687 /* our internal alloc could have failed. this ebd is now the
688 * last one we'll consider. let's handle it separately and put
689 * it in the main body. */
692 copy_amt = copy_to_block_body(to, (void*)ebd->base + ebd->off,
694 block_and_q_lost_extra(from, q, copy_amt);
701 /* If we're here, we reached our final ebd, which we'll need to
702 * split to get anything from it. */
705 copy_amt = copy_to_block_body(to, (void*)ebd->base + ebd->off,
707 ebd->off += copy_amt;
708 ebd->len -= copy_amt;
709 block_and_q_lost_extra(from, q, copy_amt);
714 assert(copy_amt); /* sanity */
718 /* Return codes for __qbread and __try_qbread. */
722 QBR_SPARE, /* we need a spare block */
723 QBR_AGAIN, /* do it again, we are coalescing blocks */
726 /* Helper and back-end for __qbread: extracts and returns a list of blocks
727 * containing up to len bytes. It may contain less than len even if q has more
730 * Returns a code interpreted by __qbread, and the returned blist in ret. */
731 static int __try_qbread(struct queue *q, size_t len, int qio_flags,
732 struct block **real_ret, struct block *spare)
734 struct block *ret, *ret_last, *first;
736 bool was_unwritable = FALSE;
739 if (qio_flags & QIO_CAN_ERR_SLEEP) {
740 if (!qwait_and_ilock(q, qio_flags)) {
741 spin_unlock_irqsave(&q->lock);
744 /* we qwaited and still hold the lock, so the q is not empty */
747 spin_lock_irqsave(&q->lock);
750 spin_unlock_irqsave(&q->lock);
754 was_unwritable = !qwritable(q);
756 if ((q->state & Qcoalesce) && (blen == 0)) {
757 freeb(pop_first_block(q));
758 spin_unlock_irqsave(&q->lock);
759 /* Need to retry to make sure we have a first block */
762 /* Qmsg: just return the first block. Be careful, since our caller might
763 * not read all of the block and thus drop bytes. Similar to SOCK_DGRAM. */
764 if (q->state & Qmsg) {
765 ret = pop_first_block(q);
768 /* Let's get at least something first - makes the code easier. This way,
769 * we'll only ever split the block once. */
771 ret = pop_first_block(q);
774 /* need to split the block. we won't actually take the first block out
775 * of the queue - we're just extracting a little bit. */
777 /* We have nothing and need a spare block. Retry! */
778 spin_unlock_irqsave(&q->lock);
781 copy_from_first_block(q, spare, len);
785 /* At this point, we just grabbed the first block. We can try to grab some
786 * more, up to len (if they want). */
787 if (qio_flags & QIO_JUST_ONE_BLOCK)
790 while (q->bfirst && (len > 0)) {
791 blen = BLEN(q->bfirst);
792 if ((q->state & Qcoalesce) && (blen == 0)) {
793 /* remove the intermediate 0 blocks */
794 freeb(pop_first_block(q));
798 /* We could try to split the block, but that's a huge pain. For
799 * instance, we might need to move the main body of b into an
800 * extra_data of ret_last. lots of ways for that to fail, and lots
801 * of cases to consider. Easier to just bail out. This is why I
802 * did the first block above: we don't need to worry about this. */
805 ret_last->next = pop_first_block(q);
806 ret_last = ret_last->next;
811 * if writer flow controlled, restart
814 * q->len < q->limit/2
815 * but it slows down tcp too much for certain write sizes.
816 * I really don't understand it completely. It may be
817 * due to the queue draining so fast that the transmission
818 * stalls waiting for the app to produce more data. - presotto
820 if ((q->state & Qflow) && q->len < q->limit) {
824 spin_unlock_irqsave(&q->lock);
825 /* wakeup flow controlled writers */
827 if (q->kick && !(qio_flags & QIO_DONT_KICK))
829 rendez_wakeup(&q->wr);
832 qwake_cb(q, FDTAP_FILT_WRITABLE);
837 /* Helper and front-end for __try_qbread: extracts and returns a list of blocks
838 * containing up to len bytes. It may contain less than len even if q has more
841 * Returns 0 if the q is closed or would require blocking and !CAN_BLOCK.
843 * Technically, there's a weird corner case with !Qcoalesce and Qmsg where you
844 * could get a zero length block back. */
845 static struct block *__qbread(struct queue *q, size_t len, int qio_flags,
848 struct block *ret = 0;
849 struct block *spare = 0;
852 switch (__try_qbread(q, len, qio_flags, &ret, spare)) {
855 if (spare && (ret != spare))
860 /* Due to some nastiness, we need a fresh block so we can read out
861 * anything from the queue. 'len' seems like a reasonable amount.
862 * Maybe we can get away with less. */
863 spare = block_alloc(len, mem_flags);
868 /* if the first block is 0 and we are Qcoalesce, then we'll need to
869 * try again. We bounce out of __try so we can perform the "is
870 * there a block" logic again from the top. */
877 * get next block from a queue, return null if nothing there
879 struct block *qget(struct queue *q)
881 /* since len == SIZE_MAX, we should never need to do a mem alloc */
882 return __qbread(q, SIZE_MAX, QIO_JUST_ONE_BLOCK, MEM_ATOMIC);
885 /* Throw away the next 'len' bytes in the queue returning the number actually
888 * If the bytes are in the queue, then they must be discarded. The only time to
889 * return less than len is if the q itself has less than len bytes.
891 * This won't trigger a kick when waking up any sleepers. This seems to be Plan
892 * 9's intent, since the TCP stack will deadlock if qdiscard kicks. */
893 size_t qdiscard(struct queue *q, size_t len)
899 /* This is racy. There could be multiple qdiscarders or other consumers,
900 * where the consumption could be interleaved. */
901 while (qlen(q) && len) {
902 blist = __qbread(q, len, QIO_DONT_KICK, MEM_WAIT);
903 removed_amt = freeblist(blist);
904 sofar += removed_amt;
910 ssize_t qpass(struct queue *q, struct block *b)
912 return __qbwrite(q, b, QIO_LIMIT | QIO_DROP_OVERFLOW);
915 ssize_t qpassnolim(struct queue *q, struct block *b)
917 return __qbwrite(q, b, 0);
921 * if the allocated space is way out of line with the used
922 * space, reallocate to a smaller block
924 struct block *packblock(struct block *bp)
926 struct block **l, *nbp;
931 for (l = &bp; *l; l = &(*l)->next) {
934 if ((n << 2) < BALLOC(nbp)) {
935 *l = block_alloc(n, MEM_WAIT);
936 memmove((*l)->wp, nbp->rp, n);
938 (*l)->next = nbp->next;
946 /* Add an extra_data entry to newb at newb_idx pointing to b's body, starting at
947 * body_rp, for up to len. Returns the len consumed.
949 * The base is 'b', so that we can kfree it later. This currently ties us to
950 * using kfree for the release method for all extra_data.
952 * It is possible to have a body size that is 0, if there is no offset, and
953 * b->wp == b->rp. This will have an extra data entry of 0 length. */
954 static size_t point_to_body(struct block *b, uint8_t *body_rp,
955 struct block *newb, unsigned int newb_idx,
958 struct extra_bdata *ebd = &newb->extra_data[newb_idx];
960 assert(newb_idx < newb->nr_extra_bufs);
963 ebd->base = (uintptr_t)b;
964 ebd->off = (uint32_t)(body_rp - (uint8_t*)b);
965 ebd->len = MIN(b->wp - body_rp, len); /* think of body_rp as b->rp */
966 assert((int)ebd->len >= 0);
967 newb->extra_len += ebd->len;
971 /* Add an extra_data entry to newb at newb_idx pointing to b's b_idx'th
972 * extra_data buf, at b_off within that buffer, for up to len. Returns the len
975 * We can have blocks with 0 length, but they are still refcnt'd. See above. */
976 static size_t point_to_buf(struct block *b, unsigned int b_idx, uint32_t b_off,
977 struct block *newb, unsigned int newb_idx,
980 struct extra_bdata *n_ebd = &newb->extra_data[newb_idx];
981 struct extra_bdata *b_ebd = &b->extra_data[b_idx];
983 assert(b_idx < b->nr_extra_bufs);
984 assert(newb_idx < newb->nr_extra_bufs);
986 kmalloc_incref((void*)b_ebd->base);
987 n_ebd->base = b_ebd->base;
988 n_ebd->off = b_ebd->off + b_off;
989 n_ebd->len = MIN(b_ebd->len - b_off, len);
990 newb->extra_len += n_ebd->len;
994 /* given a string of blocks, sets up the new block's extra_data such that it
995 * *points* to the contents of the blist [offset, len + offset). This does not
996 * make a separate copy of the contents of the blist.
998 * returns 0 on success. the only failure is if the extra_data array was too
999 * small, so this returns a positive integer saying how big the extra_data needs
1002 * callers are responsible for protecting the list structure. */
1003 static int __blist_clone_to(struct block *blist, struct block *newb, int len,
1006 struct block *b, *first;
1007 unsigned int nr_bufs = 0;
1008 unsigned int b_idx, newb_idx = 0;
1009 uint8_t *first_main_body = 0;
1011 /* find the first block; keep offset relative to the latest b in the list */
1012 for (b = blist; b; b = b->next) {
1013 if (BLEN(b) > offset)
1017 /* qcopy semantics: if you asked for an offset outside the block list, you
1018 * get an empty block back */
1022 /* upper bound for how many buffers we'll need in newb */
1023 for (/* b is set*/; b; b = b->next) {
1024 nr_bufs += 1 + b->nr_extra_bufs; /* 1 for the main body */
1026 /* we might be holding a spinlock here, so we won't wait for kmalloc */
1027 if (block_add_extd(newb, nr_bufs, 0) != 0) {
1028 /* caller will need to alloc these, then re-call us */
1031 for (b = first; b && len; b = b->next) {
1034 if (offset < BHLEN(b)) {
1035 /* off is in the main body */
1036 len -= point_to_body(b, b->rp + offset, newb, newb_idx, len);
1039 /* off is in one of the buffers (or just past the last one).
1040 * we're not going to point to b's main body at all. */
1042 assert(b->extra_data);
1043 /* assuming these extrabufs are packed, or at least that len
1044 * isn't gibberish */
1045 while (b->extra_data[b_idx].len <= offset) {
1046 offset -= b->extra_data[b_idx].len;
1049 /* now offset is set to our offset in the b_idx'th buf */
1050 len -= point_to_buf(b, b_idx, offset, newb, newb_idx, len);
1056 len -= point_to_body(b, b->rp, newb, newb_idx, len);
1059 /* knock out all remaining bufs. we only did one point_to_ op by now,
1060 * and any point_to_ could be our last if it consumed all of len. */
1061 for (int i = b_idx; (i < b->nr_extra_bufs) && len; i++) {
1062 len -= point_to_buf(b, i, 0, newb, newb_idx, len);
1069 struct block *blist_clone(struct block *blist, int header_len, int len,
1073 struct block *newb = block_alloc(header_len, MEM_WAIT);
1075 ret = __blist_clone_to(blist, newb, len, offset);
1077 block_add_extd(newb, ret, MEM_WAIT);
1082 /* given a queue, makes a single block with header_len reserved space in the
1083 * block main body, and the contents of [offset, len + offset) pointed to in the
1084 * new blocks ext_data. This does not make a copy of the q's contents, though
1085 * you do have a ref count on the memory. */
1086 struct block *qclone(struct queue *q, int header_len, int len, uint32_t offset)
1089 struct block *newb = block_alloc(header_len, MEM_WAIT);
1090 /* the while loop should rarely be used: it would require someone
1091 * concurrently adding to the queue. */
1093 /* TODO: RCU: protecting the q list (b->next) (need read lock) */
1094 spin_lock_irqsave(&q->lock);
1095 ret = __blist_clone_to(q->bfirst, newb, len, offset);
1096 spin_unlock_irqsave(&q->lock);
1098 block_add_extd(newb, ret, MEM_WAIT);
1104 * copy from offset in the queue
1106 struct block *qcopy_old(struct queue *q, int len, uint32_t offset)
1110 struct block *b, *nb;
1113 nb = block_alloc(len, MEM_WAIT);
1115 spin_lock_irqsave(&q->lock);
1119 for (sofar = 0;; sofar += n) {
1121 spin_unlock_irqsave(&q->lock);
1125 if (sofar + n > offset) {
1126 p = b->rp + offset - sofar;
1127 n -= offset - sofar;
1130 QDEBUG checkb(b, "qcopy");
1134 /* copy bytes from there */
1135 for (sofar = 0; sofar < len;) {
1136 if (n > len - sofar)
1139 memmove(nb->wp, p, n);
1149 spin_unlock_irqsave(&q->lock);
1154 struct block *qcopy(struct queue *q, int len, uint32_t offset)
1156 #ifdef CONFIG_BLOCK_EXTRAS
1157 return qclone(q, 0, len, offset);
1159 return qcopy_old(q, len, offset);
1163 static void qinit_common(struct queue *q)
1165 spinlock_init_irqsave(&q->lock);
1166 rendez_init(&q->rr);
1167 rendez_init(&q->wr);
1171 * called by non-interrupt code
1173 struct queue *qopen(int limit, int msg, void (*kick) (void *), void *arg)
1177 q = kzmalloc(sizeof(struct queue), 0);
1182 q->limit = q->inilim = limit;
1186 q->state |= Qstarve;
1192 /* open a queue to be bypassed */
1193 struct queue *qbypass(void (*bypass) (void *, struct block *), void *arg)
1197 q = kzmalloc(sizeof(struct queue), 0);
1210 static int notempty(void *a)
1212 struct queue *q = a;
1214 return (q->state & Qclosed) || q->bfirst != 0;
1217 /* Block, waiting for the queue to be non-empty or closed. Returns with
1218 * the spinlock held. Returns TRUE when there queue is not empty, FALSE if it
1219 * was naturally closed. Throws an error o/w. */
1220 static bool qwait_and_ilock(struct queue *q, int qio_flags)
1223 spin_lock_irqsave(&q->lock);
1224 if (q->bfirst != NULL)
1226 if (q->state & Qclosed) {
1228 spin_unlock_irqsave(&q->lock);
1229 error(EPIPE, "multiple reads on a closed queue");
1232 spin_unlock_irqsave(&q->lock);
1233 error(EPIPE, q->err);
1237 /* We set Qstarve regardless of whether we are non-blocking or not.
1238 * Qstarve tracks the edge detection of the queue being empty. */
1239 q->state |= Qstarve;
1240 if (qio_flags & QIO_NON_BLOCK) {
1241 spin_unlock_irqsave(&q->lock);
1242 error(EAGAIN, "queue empty");
1244 spin_unlock_irqsave(&q->lock);
1245 /* may throw an error() */
1246 rendez_sleep(&q->rr, notempty, q);
1251 * add a block list to a queue
1252 * XXX basically the same as enqueue blist, and has no locking!
1254 void qaddlist(struct queue *q, struct block *b)
1257 /* queue the block */
1262 q->len += blockalloclen(b);
1263 q->dlen += blocklen(b);
1269 static size_t read_from_block(struct block *b, uint8_t *to, size_t amt)
1271 size_t copy_amt, retval = 0;
1272 struct extra_bdata *ebd;
1274 copy_amt = MIN(BHLEN(b), amt);
1275 memcpy(to, b->rp, copy_amt);
1276 /* advance the rp, since this block not be completely consumed and future
1277 * reads need to know where to pick up from */
1282 for (int i = 0; (i < b->nr_extra_bufs) && amt; i++) {
1283 ebd = &b->extra_data[i];
1284 /* skip empty entires. if we track this in the struct block, we can
1285 * just start the for loop early */
1286 if (!ebd->base || !ebd->len)
1288 copy_amt = MIN(ebd->len, amt);
1289 memcpy(to, (void*)(ebd->base + ebd->off), copy_amt);
1290 /* we're actually consuming the entries, just like how we advance rp up
1291 * above, and might only consume part of one. */
1292 ebd->len -= copy_amt;
1293 ebd->off += copy_amt;
1294 b->extra_len -= copy_amt;
1296 /* we don't actually have to decref here. it's also done in
1297 * freeb(). this is the earliest we can free. */
1298 kfree((void*)ebd->base);
1299 ebd->base = ebd->off = 0;
1309 * copy the contents of a string of blocks into
1310 * memory. emptied blocks are freed. return
1311 * pointer to first unconsumed block.
1313 struct block *bl2mem(uint8_t * p, struct block *b, int n)
1318 /* could be slicker here, since read_from_block is smart */
1319 for (; b != NULL; b = next) {
1322 /* partial block, consume some */
1323 read_from_block(b, p, n);
1326 /* full block, consume all and move on */
1327 i = read_from_block(b, p, i);
1336 /* Extract the contents of all blocks and copy to va, up to len. Returns the
1337 * actual amount copied. */
1338 static size_t read_all_blocks(struct block *b, void *va, size_t len)
1344 /* We should be draining every block completely. */
1345 assert(BLEN(b) <= len - sofar);
1349 sofar += read_from_block(b, va + sofar, len - sofar);
1358 * copy the contents of memory into a string of blocks.
1359 * return NULL on error.
1361 struct block *mem2bl(uint8_t * p, int len)
1365 struct block *b, *first, **l;
1378 *l = b = block_alloc(n, MEM_WAIT);
1379 /* TODO consider extra_data */
1380 memmove(b->wp, p, n);
1392 * put a block back to the front of the queue
1393 * called with q ilocked
1395 void qputback(struct queue *q, struct block *b)
1397 b->next = q->bfirst;
1398 if (q->bfirst == NULL)
1401 q->len += BALLOC(b);
1406 * get next block from a queue (up to a limit)
1409 struct block *qbread(struct queue *q, size_t len)
1411 return __qbread(q, len, QIO_JUST_ONE_BLOCK | QIO_CAN_ERR_SLEEP, MEM_WAIT);
1414 struct block *qbread_nonblock(struct queue *q, size_t len)
1416 return __qbread(q, len, QIO_JUST_ONE_BLOCK | QIO_CAN_ERR_SLEEP |
1417 QIO_NON_BLOCK, MEM_WAIT);
1420 /* read up to len from a queue into vp. */
1421 size_t qread(struct queue *q, void *va, size_t len)
1423 struct block *blist = __qbread(q, len, QIO_CAN_ERR_SLEEP, MEM_WAIT);
1427 return read_all_blocks(blist, va, len);
1430 size_t qread_nonblock(struct queue *q, void *va, size_t len)
1432 struct block *blist = __qbread(q, len, QIO_CAN_ERR_SLEEP | QIO_NON_BLOCK,
1437 return read_all_blocks(blist, va, len);
1440 static int qnotfull(void *a)
1442 struct queue *q = a;
1444 return q->len < q->limit || (q->state & Qclosed);
1447 /* Helper: enqueues a list of blocks to a queue. Returns the total length. */
1448 static size_t enqueue_blist(struct queue *q, struct block *b)
1469 /* Adds block (which can be a list of blocks) to the queue, subject to
1470 * qio_flags. Returns the length written on success or -1 on non-throwable
1471 * error. Adjust qio_flags to control the value-added features!. */
1472 static ssize_t __qbwrite(struct queue *q, struct block *b, int qio_flags)
1475 bool dowakeup = FALSE;
1480 (*q->bypass) (q->arg, b);
1483 spin_lock_irqsave(&q->lock);
1484 was_empty = q->len == 0;
1485 if (q->state & Qclosed) {
1486 spin_unlock_irqsave(&q->lock);
1488 if (!(qio_flags & QIO_CAN_ERR_SLEEP))
1491 error(EPIPE, q->err);
1493 error(EPIPE, "connection closed");
1495 if ((qio_flags & QIO_LIMIT) && (q->len >= q->limit)) {
1496 /* drop overflow takes priority over regular non-blocking */
1497 if ((qio_flags & QIO_DROP_OVERFLOW) || (q->state & Qdropoverflow)) {
1498 spin_unlock_irqsave(&q->lock);
1502 /* People shouldn't set NON_BLOCK without CAN_ERR, but we can be nice
1504 if ((qio_flags & QIO_CAN_ERR_SLEEP) && (qio_flags & QIO_NON_BLOCK)) {
1505 spin_unlock_irqsave(&q->lock);
1507 error(EAGAIN, "queue full");
1510 ret = enqueue_blist(q, b);
1511 QDEBUG checkb(b, "__qbwrite");
1512 /* make sure other end gets awakened */
1513 if (q->state & Qstarve) {
1514 q->state &= ~Qstarve;
1517 spin_unlock_irqsave(&q->lock);
1518 /* TODO: not sure if the usage of a kick is mutually exclusive with a
1519 * wakeup, meaning that actual users either want a kick or have qreaders. */
1520 if (q->kick && (dowakeup || (q->state & Qkick)))
1523 rendez_wakeup(&q->rr);
1525 qwake_cb(q, FDTAP_FILT_READABLE);
1527 * flow control, wait for queue to get below the limit
1528 * before allowing the process to continue and queue
1529 * more. We do this here so that postnote can only
1530 * interrupt us after the data has been queued. This
1531 * means that things like 9p flushes and ssl messages
1532 * will not be disrupted by software interrupts.
1534 * Note - this is moderately dangerous since a process
1535 * that keeps getting interrupted and rewriting will
1536 * queue infinite crud.
1538 if ((qio_flags & QIO_CAN_ERR_SLEEP) &&
1539 !(q->state & Qdropoverflow) && !(qio_flags & QIO_NON_BLOCK)) {
1540 /* This is a racy peek at the q status. If we accidentally block, we
1541 * set Qflow, so someone should wake us. If we accidentally don't
1542 * block, we just returned to the user and let them slip a block past
1544 while (!qnotfull(q)) {
1545 spin_lock_irqsave(&q->lock);
1547 spin_unlock_irqsave(&q->lock);
1548 rendez_sleep(&q->wr, qnotfull, q);
1555 * add a block to a queue obeying flow control
1557 ssize_t qbwrite(struct queue *q, struct block *b)
1559 return __qbwrite(q, b, QIO_CAN_ERR_SLEEP | QIO_LIMIT);
1562 ssize_t qbwrite_nonblock(struct queue *q, struct block *b)
1564 return __qbwrite(q, b, QIO_CAN_ERR_SLEEP | QIO_LIMIT | QIO_NON_BLOCK);
1567 ssize_t qibwrite(struct queue *q, struct block *b)
1569 return __qbwrite(q, b, 0);
1572 /* Helper, allocs a block and copies [from, from + len) into it. Returns the
1573 * block on success, 0 on failure. */
1574 static struct block *build_block(void *from, size_t len, int mem_flags)
1579 /* If len is small, we don't need to bother with the extra_data. But until
1580 * the whole stack can handle extd blocks, we'll use them unconditionally.
1582 #ifdef CONFIG_BLOCK_EXTRAS
1583 /* allocb builds in 128 bytes of header space to all blocks, but this is
1584 * only available via padblock (to the left). we also need some space
1585 * for pullupblock for some basic headers (like icmp) that get written
1587 b = block_alloc(64, mem_flags);
1590 ext_buf = kmalloc(len, mem_flags);
1595 memcpy(ext_buf, from, len);
1596 if (block_add_extd(b, 1, mem_flags)) {
1601 b->extra_data[0].base = (uintptr_t)ext_buf;
1602 b->extra_data[0].off = 0;
1603 b->extra_data[0].len = len;
1604 b->extra_len += len;
1606 b = block_alloc(len, mem_flags);
1609 memmove(b->wp, from, len);
1615 static ssize_t __qwrite(struct queue *q, void *vp, size_t len, int mem_flags,
1626 /* This is 64K, the max amount per single block. Still a good value? */
1629 b = build_block(p + sofar, n, mem_flags);
1632 if (__qbwrite(q, b, qio_flags) < 0)
1635 } while ((sofar < len) && (q->state & Qmsg) == 0);
1639 ssize_t qwrite(struct queue *q, void *vp, int len)
1641 return __qwrite(q, vp, len, MEM_WAIT, QIO_CAN_ERR_SLEEP | QIO_LIMIT);
1644 ssize_t qwrite_nonblock(struct queue *q, void *vp, int len)
1646 return __qwrite(q, vp, len, MEM_WAIT, QIO_CAN_ERR_SLEEP | QIO_LIMIT |
1650 ssize_t qiwrite(struct queue *q, void *vp, int len)
1652 return __qwrite(q, vp, len, MEM_ATOMIC, 0);
1656 * be extremely careful when calling this,
1657 * as there is no reference accounting
1659 void qfree(struct queue *q)
1666 * Mark a queue as closed. No further IO is permitted.
1667 * All blocks are released.
1669 void qclose(struct queue *q)
1671 struct block *bfirst;
1677 spin_lock_irqsave(&q->lock);
1678 q->state |= Qclosed;
1679 q->state &= ~(Qflow | Qstarve | Qdropoverflow);
1685 spin_unlock_irqsave(&q->lock);
1687 /* free queued blocks */
1690 /* wake up readers/writers */
1691 rendez_wakeup(&q->rr);
1692 rendez_wakeup(&q->wr);
1693 qwake_cb(q, FDTAP_FILT_HANGUP);
1696 /* Mark a queue as closed. Wakeup any readers. Don't remove queued blocks.
1698 * msg will be the errstr received by any waiters (qread, qbread, etc). If
1699 * there is no message, which is what also happens during a natural qclose(),
1700 * those waiters will simply return 0. qwriters will always error() on a
1701 * closed/hungup queue. */
1702 void qhangup(struct queue *q, char *msg)
1705 spin_lock_irqsave(&q->lock);
1706 q->state |= Qclosed;
1707 if (msg == 0 || *msg == 0)
1710 strlcpy(q->err, msg, ERRMAX);
1711 spin_unlock_irqsave(&q->lock);
1713 /* wake up readers/writers */
1714 rendez_wakeup(&q->rr);
1715 rendez_wakeup(&q->wr);
1716 qwake_cb(q, FDTAP_FILT_HANGUP);
1720 * return non-zero if the q is hungup
1722 int qisclosed(struct queue *q)
1724 return q->state & Qclosed;
1728 * mark a queue as no longer hung up. resets the wake_cb.
1730 void qreopen(struct queue *q)
1732 spin_lock_irqsave(&q->lock);
1733 q->state &= ~Qclosed;
1734 q->state |= Qstarve;
1736 q->limit = q->inilim;
1739 spin_unlock_irqsave(&q->lock);
1743 * return bytes queued
1745 int qlen(struct queue *q)
1751 * return space remaining before flow control
1753 int qwindow(struct queue *q)
1757 l = q->limit - q->len;
1764 * return true if we can read without blocking
1766 int qcanread(struct queue *q)
1768 return q->bfirst != 0;
1772 * change queue limit
1774 void qsetlimit(struct queue *q, int limit)
1780 * set whether writes drop overflowing blocks, or if we sleep
1782 void qdropoverflow(struct queue *q, bool onoff)
1784 spin_lock_irqsave(&q->lock);
1786 q->state |= Qdropoverflow;
1788 q->state &= ~Qdropoverflow;
1789 spin_unlock_irqsave(&q->lock);
1792 /* Be careful: this can affect concurrent reads/writes and code that might have
1793 * built-in expectations of the q's type. */
1794 void q_toggle_qmsg(struct queue *q, bool onoff)
1796 spin_lock_irqsave(&q->lock);
1801 spin_unlock_irqsave(&q->lock);
1804 /* Be careful: this can affect concurrent reads/writes and code that might have
1805 * built-in expectations of the q's type. */
1806 void q_toggle_qcoalesce(struct queue *q, bool onoff)
1808 spin_lock_irqsave(&q->lock);
1810 q->state |= Qcoalesce;
1812 q->state &= ~Qcoalesce;
1813 spin_unlock_irqsave(&q->lock);
1817 * flush the output queue
1819 void qflush(struct queue *q)
1821 struct block *bfirst;
1824 spin_lock_irqsave(&q->lock);
1829 spin_unlock_irqsave(&q->lock);
1831 /* free queued blocks */
1834 /* wake up writers */
1835 rendez_wakeup(&q->wr);
1836 qwake_cb(q, FDTAP_FILT_WRITABLE);
1839 int qfull(struct queue *q)
1841 return q->len >= q->limit;
1844 int qstate(struct queue *q)
1849 void qdump(struct queue *q)
1852 printk("q=%p bfirst=%p blast=%p len=%d dlen=%d limit=%d state=#%x\n",
1853 q, q->bfirst, q->blast, q->len, q->dlen, q->limit, q->state);
1856 /* On certain wakeup events, qio will call func(q, data, filter), where filter
1857 * marks the type of wakeup event (flags from FDTAP).
1859 * There's no sync protection. If you change the CB while the qio is running,
1860 * you might get a CB with the data or func from a previous set_wake_cb. You
1861 * should set this once per queue and forget it.
1863 * You can remove the CB by passing in 0 for the func. Alternatively, you can
1864 * just make sure that the func(data) pair are valid until the queue is freed or
1866 void qio_set_wake_cb(struct queue *q, qio_wake_cb_t func, void *data)
1868 q->wake_data = data;
1869 wmb(); /* if we see func, we'll also see the data for it */
1873 /* Helper for detecting whether we'll block on a read at this instant. */
1874 bool qreadable(struct queue *q)
1879 /* Helper for detecting whether we'll block on a write at this instant. */
1880 bool qwritable(struct queue *q)
1882 return qwindow(q) > 0;