2 * SPDX-License-Identifier: BSD-3-Clause
4 * Copyright (c) 1982, 1986, 1988, 1990, 1993
5 * The Regents of the University of California. All rights reserved.
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 * 3. Neither the name of the University nor the names of its contributors
16 * may be used to endorse or promote products derived from this software
17 * without specific prior written permission.
19 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 * @(#)uipc_socket2.c 8.1 (Berkeley) 6/10/93
34 #include <sys/cdefs.h>
35 __FBSDID("$FreeBSD$");
37 #include "opt_param.h"
39 #include <sys/param.h>
40 #include <sys/aio.h> /* for aio_swake proto */
41 #include <sys/kernel.h>
43 #include <sys/malloc.h>
45 #include <sys/mutex.h>
47 #include <sys/protosw.h>
48 #include <sys/resourcevar.h>
49 #include <sys/signalvar.h>
50 #include <sys/socket.h>
51 #include <sys/socketvar.h>
53 #include <sys/sysctl.h>
56 * Function pointer set by the AIO routines so that the socket buffer code
57 * can call back into the AIO module if it is loaded.
59 void (*aio_swake)(struct socket *, struct sockbuf *);
62 * Primitive routines for operating on socket buffers
65 u_long sb_max = SB_MAX;
67 (quad_t)SB_MAX * MCLBYTES / (MSIZE + MCLBYTES); /* adjusted sb_max */
69 static u_long sb_efficiency = 8; /* parameter for sbreserve() */
71 static struct mbuf *sbcut_internal(struct sockbuf *sb, int len);
72 static void sbflush_internal(struct sockbuf *sb);
75 * Our own version of m_clrprotoflags(), that can preserve M_NOTREADY.
78 sbm_clrprotoflags(struct mbuf *m, int flags)
83 if (flags & PRUS_NOTREADY)
92 * Compress M_NOTREADY mbufs after they have been readied by sbready().
94 * sbcompress() skips M_NOTREADY mbufs since the data is not available to
95 * be copied at the time of sbcompress(). This function combines small
96 * mbufs similar to sbcompress() once mbufs are ready. 'm0' is the first
97 * mbuf sbready() marked ready, and 'end' is the first mbuf still not
101 sbready_compress(struct sockbuf *sb, struct mbuf *m0, struct mbuf *end)
106 SOCKBUF_LOCK_ASSERT(sb);
108 if ((sb->sb_flags & SB_NOCOALESCE) != 0)
111 for (m = m0; m != end; m = m->m_next) {
112 MPASS((m->m_flags & M_NOTREADY) == 0);
114 /* Compress small unmapped mbufs into plain mbufs. */
115 if ((m->m_flags & M_NOMAP) && m->m_len <= MLEN) {
116 MPASS(m->m_flags & M_EXT);
117 ext_size = m->m_ext.ext_size;
118 if (mb_unmapped_compress(m) == 0) {
119 sb->sb_mbcnt -= ext_size;
125 * NB: In sbcompress(), 'n' is the last mbuf in the
126 * socket buffer and 'm' is the new mbuf being copied
127 * into the trailing space of 'n'. Here, the roles
128 * are reversed and 'n' is the next mbuf after 'm'
129 * that is being copied into the trailing space of
133 while ((n != NULL) && (n != end) && (m->m_flags & M_EOR) == 0 &&
135 (m->m_flags & M_NOMAP) == 0 &&
136 n->m_len <= MCLBYTES / 4 && /* XXX: Don't copy too much */
137 n->m_len <= M_TRAILINGSPACE(m) &&
138 m->m_type == n->m_type) {
139 KASSERT(sb->sb_lastrecord != n,
140 ("%s: merging start of record (%p) into previous mbuf (%p)",
142 m_copydata(n, 0, n->m_len, mtodo(m, m->m_len));
143 m->m_len += n->m_len;
144 m->m_next = n->m_next;
145 m->m_flags |= n->m_flags & M_EOR;
146 if (sb->sb_mbtail == n)
149 sb->sb_mbcnt -= MSIZE;
151 if (n->m_flags & M_EXT) {
152 sb->sb_mbcnt -= n->m_ext.ext_size;
164 * Mark ready "count" units of I/O starting with "m". Most mbufs
165 * count as a single unit of I/O except for EXT_PGS-backed mbufs which
166 * can be backed by multiple pages.
169 sbready(struct sockbuf *sb, struct mbuf *m0, int count)
174 SOCKBUF_LOCK_ASSERT(sb);
175 KASSERT(sb->sb_fnrdy != NULL, ("%s: sb %p NULL fnrdy", __func__, sb));
176 KASSERT(count > 0, ("%s: invalid count %d", __func__, count));
179 blocker = (sb->sb_fnrdy == m) ? M_BLOCKED : 0;
182 KASSERT(m->m_flags & M_NOTREADY,
183 ("%s: m %p !M_NOTREADY", __func__, m));
184 if ((m->m_flags & M_EXT) != 0 &&
185 m->m_ext.ext_type == EXT_PGS) {
186 if (count < m->m_ext.ext_pgs->nrdy) {
187 m->m_ext.ext_pgs->nrdy -= count;
191 count -= m->m_ext.ext_pgs->nrdy;
192 m->m_ext.ext_pgs->nrdy = 0;
196 m->m_flags &= ~(M_NOTREADY | blocker);
198 sb->sb_acc += m->m_len;
203 * If the first mbuf is still not fully ready because only
204 * some of its backing pages were readied, no further progress
208 MPASS(m->m_flags & M_NOTREADY);
209 return (EINPROGRESS);
213 sbready_compress(sb, m0, m);
214 return (EINPROGRESS);
217 /* This one was blocking all the queue. */
218 for (; m && (m->m_flags & M_NOTREADY) == 0; m = m->m_next) {
219 KASSERT(m->m_flags & M_BLOCKED,
220 ("%s: m %p !M_BLOCKED", __func__, m));
221 m->m_flags &= ~M_BLOCKED;
222 sb->sb_acc += m->m_len;
226 sbready_compress(sb, m0, m);
232 * Adjust sockbuf state reflecting allocation of m.
235 sballoc(struct sockbuf *sb, struct mbuf *m)
238 SOCKBUF_LOCK_ASSERT(sb);
240 sb->sb_ccc += m->m_len;
242 if (sb->sb_fnrdy == NULL) {
243 if (m->m_flags & M_NOTREADY)
246 sb->sb_acc += m->m_len;
248 m->m_flags |= M_BLOCKED;
250 if (m->m_type != MT_DATA && m->m_type != MT_OOBDATA)
251 sb->sb_ctl += m->m_len;
253 sb->sb_mbcnt += MSIZE;
256 if (m->m_flags & M_EXT) {
257 sb->sb_mbcnt += m->m_ext.ext_size;
263 * Adjust sockbuf state reflecting freeing of m.
266 sbfree(struct sockbuf *sb, struct mbuf *m)
269 #if 0 /* XXX: not yet: soclose() call path comes here w/o lock. */
270 SOCKBUF_LOCK_ASSERT(sb);
273 sb->sb_ccc -= m->m_len;
275 if (!(m->m_flags & M_NOTAVAIL))
276 sb->sb_acc -= m->m_len;
278 if (m == sb->sb_fnrdy) {
281 KASSERT(m->m_flags & M_NOTREADY,
282 ("%s: m %p !M_NOTREADY", __func__, m));
285 while (n != NULL && !(n->m_flags & M_NOTREADY)) {
286 n->m_flags &= ~M_BLOCKED;
287 sb->sb_acc += n->m_len;
293 if (m->m_type != MT_DATA && m->m_type != MT_OOBDATA)
294 sb->sb_ctl -= m->m_len;
296 sb->sb_mbcnt -= MSIZE;
298 if (m->m_flags & M_EXT) {
299 sb->sb_mbcnt -= m->m_ext.ext_size;
303 if (sb->sb_sndptr == m) {
304 sb->sb_sndptr = NULL;
305 sb->sb_sndptroff = 0;
307 if (sb->sb_sndptroff != 0)
308 sb->sb_sndptroff -= m->m_len;
312 * Socantsendmore indicates that no more data will be sent on the socket; it
313 * would normally be applied to a socket when the user informs the system
314 * that no more data is to be sent, by the protocol code (in case
315 * PRU_SHUTDOWN). Socantrcvmore indicates that no more data will be
316 * received, and will normally be applied to the socket by a protocol when it
317 * detects that the peer will send no more data. Data queued for reading in
318 * the socket may yet be read.
321 socantsendmore_locked(struct socket *so)
324 SOCKBUF_LOCK_ASSERT(&so->so_snd);
326 so->so_snd.sb_state |= SBS_CANTSENDMORE;
327 sowwakeup_locked(so);
328 mtx_assert(SOCKBUF_MTX(&so->so_snd), MA_NOTOWNED);
332 socantsendmore(struct socket *so)
335 SOCKBUF_LOCK(&so->so_snd);
336 socantsendmore_locked(so);
337 mtx_assert(SOCKBUF_MTX(&so->so_snd), MA_NOTOWNED);
341 socantrcvmore_locked(struct socket *so)
344 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
346 so->so_rcv.sb_state |= SBS_CANTRCVMORE;
347 sorwakeup_locked(so);
348 mtx_assert(SOCKBUF_MTX(&so->so_rcv), MA_NOTOWNED);
352 socantrcvmore(struct socket *so)
355 SOCKBUF_LOCK(&so->so_rcv);
356 socantrcvmore_locked(so);
357 mtx_assert(SOCKBUF_MTX(&so->so_rcv), MA_NOTOWNED);
361 * Wait for data to arrive at/drain from a socket buffer.
364 sbwait(struct sockbuf *sb)
367 SOCKBUF_LOCK_ASSERT(sb);
369 sb->sb_flags |= SB_WAIT;
370 return (msleep_sbt(&sb->sb_acc, &sb->sb_mtx,
371 (sb->sb_flags & SB_NOINTR) ? PSOCK : PSOCK | PCATCH, "sbwait",
372 sb->sb_timeo, 0, 0));
376 sblock(struct sockbuf *sb, int flags)
379 KASSERT((flags & SBL_VALID) == flags,
380 ("sblock: flags invalid (0x%x)", flags));
382 if (flags & SBL_WAIT) {
383 if ((sb->sb_flags & SB_NOINTR) ||
384 (flags & SBL_NOINTR)) {
385 sx_xlock(&sb->sb_sx);
388 return (sx_xlock_sig(&sb->sb_sx));
390 if (sx_try_xlock(&sb->sb_sx) == 0)
391 return (EWOULDBLOCK);
397 sbunlock(struct sockbuf *sb)
400 sx_xunlock(&sb->sb_sx);
404 * Wakeup processes waiting on a socket buffer. Do asynchronous notification
405 * via SIGIO if the socket has the SS_ASYNC flag set.
407 * Called with the socket buffer lock held; will release the lock by the end
408 * of the function. This allows the caller to acquire the socket buffer lock
409 * while testing for the need for various sorts of wakeup and hold it through
410 * to the point where it's no longer required. We currently hold the lock
411 * through calls out to other subsystems (with the exception of kqueue), and
412 * then release it to avoid lock order issues. It's not clear that's
416 sowakeup(struct socket *so, struct sockbuf *sb)
420 SOCKBUF_LOCK_ASSERT(sb);
422 selwakeuppri(sb->sb_sel, PSOCK);
423 if (!SEL_WAITING(sb->sb_sel))
424 sb->sb_flags &= ~SB_SEL;
425 if (sb->sb_flags & SB_WAIT) {
426 sb->sb_flags &= ~SB_WAIT;
429 KNOTE_LOCKED(&sb->sb_sel->si_note, 0);
430 if (sb->sb_upcall != NULL) {
431 ret = sb->sb_upcall(so, sb->sb_upcallarg, M_NOWAIT);
432 if (ret == SU_ISCONNECTED) {
433 KASSERT(sb == &so->so_rcv,
434 ("SO_SND upcall returned SU_ISCONNECTED"));
435 soupcall_clear(so, SO_RCV);
439 if (sb->sb_flags & SB_AIO)
440 sowakeup_aio(so, sb);
442 if (ret == SU_ISCONNECTED)
444 if ((so->so_state & SS_ASYNC) && so->so_sigio != NULL)
445 pgsigio(&so->so_sigio, SIGIO, 0);
446 mtx_assert(SOCKBUF_MTX(sb), MA_NOTOWNED);
450 * Socket buffer (struct sockbuf) utility routines.
452 * Each socket contains two socket buffers: one for sending data and one for
453 * receiving data. Each buffer contains a queue of mbufs, information about
454 * the number of mbufs and amount of data in the queue, and other fields
455 * allowing select() statements and notification on data availability to be
458 * Data stored in a socket buffer is maintained as a list of records. Each
459 * record is a list of mbufs chained together with the m_next field. Records
460 * are chained together with the m_nextpkt field. The upper level routine
461 * soreceive() expects the following conventions to be observed when placing
462 * information in the receive buffer:
464 * 1. If the protocol requires each message be preceded by the sender's name,
465 * then a record containing that name must be present before any
466 * associated data (mbuf's must be of type MT_SONAME).
467 * 2. If the protocol supports the exchange of ``access rights'' (really just
468 * additional data associated with the message), and there are ``rights''
469 * to be received, then a record containing this data should be present
470 * (mbuf's must be of type MT_RIGHTS).
471 * 3. If a name or rights record exists, then it must be followed by a data
472 * record, perhaps of zero length.
474 * Before using a new socket structure it is first necessary to reserve
475 * buffer space to the socket, by calling sbreserve(). This should commit
476 * some of the available buffer space in the system buffer pool for the
477 * socket (currently, it does nothing but enforce limits). The space should
478 * be released by calling sbrelease() when the socket is destroyed.
481 soreserve(struct socket *so, u_long sndcc, u_long rcvcc)
483 struct thread *td = curthread;
485 SOCKBUF_LOCK(&so->so_snd);
486 SOCKBUF_LOCK(&so->so_rcv);
487 if (sbreserve_locked(&so->so_snd, sndcc, so, td) == 0)
489 if (sbreserve_locked(&so->so_rcv, rcvcc, so, td) == 0)
491 if (so->so_rcv.sb_lowat == 0)
492 so->so_rcv.sb_lowat = 1;
493 if (so->so_snd.sb_lowat == 0)
494 so->so_snd.sb_lowat = MCLBYTES;
495 if (so->so_snd.sb_lowat > so->so_snd.sb_hiwat)
496 so->so_snd.sb_lowat = so->so_snd.sb_hiwat;
497 SOCKBUF_UNLOCK(&so->so_rcv);
498 SOCKBUF_UNLOCK(&so->so_snd);
501 sbrelease_locked(&so->so_snd, so);
503 SOCKBUF_UNLOCK(&so->so_rcv);
504 SOCKBUF_UNLOCK(&so->so_snd);
509 sysctl_handle_sb_max(SYSCTL_HANDLER_ARGS)
512 u_long tmp_sb_max = sb_max;
514 error = sysctl_handle_long(oidp, &tmp_sb_max, arg2, req);
515 if (error || !req->newptr)
517 if (tmp_sb_max < MSIZE + MCLBYTES)
520 sb_max_adj = (u_quad_t)sb_max * MCLBYTES / (MSIZE + MCLBYTES);
525 * Allot mbufs to a sockbuf. Attempt to scale mbmax so that mbcnt doesn't
526 * become limiting if buffering efficiency is near the normal case.
529 sbreserve_locked(struct sockbuf *sb, u_long cc, struct socket *so,
534 SOCKBUF_LOCK_ASSERT(sb);
537 * When a thread is passed, we take into account the thread's socket
538 * buffer size limit. The caller will generally pass curthread, but
539 * in the TCP input path, NULL will be passed to indicate that no
540 * appropriate thread resource limits are available. In that case,
541 * we don't apply a process limit.
546 sbsize_limit = lim_cur(td, RLIMIT_SBSIZE);
548 sbsize_limit = RLIM_INFINITY;
549 if (!chgsbsize(so->so_cred->cr_uidinfo, &sb->sb_hiwat, cc,
552 sb->sb_mbmax = min(cc * sb_efficiency, sb_max);
553 if (sb->sb_lowat > sb->sb_hiwat)
554 sb->sb_lowat = sb->sb_hiwat;
559 sbsetopt(struct socket *so, int cmd, u_long cc)
563 u_int *hiwat, *lowat;
568 if (SOLISTENING(so)) {
572 lowat = &so->sol_sbsnd_lowat;
573 hiwat = &so->sol_sbsnd_hiwat;
574 flags = &so->sol_sbsnd_flags;
578 lowat = &so->sol_sbrcv_lowat;
579 hiwat = &so->sol_sbrcv_hiwat;
580 flags = &so->sol_sbrcv_flags;
594 flags = &sb->sb_flags;
595 hiwat = &sb->sb_hiwat;
596 lowat = &sb->sb_lowat;
604 if (SOLISTENING(so)) {
605 if (cc > sb_max_adj) {
613 if (!sbreserve_locked(sb, cc, so, curthread))
617 *flags &= ~SB_AUTOSIZE;
622 * Make sure the low-water is never greater than the
625 *lowat = (cc > *hiwat) ? *hiwat : cc;
629 if (!SOLISTENING(so))
636 * Free mbufs held by a socket, and reserved mbuf space.
639 sbrelease_internal(struct sockbuf *sb, struct socket *so)
642 sbflush_internal(sb);
643 (void)chgsbsize(so->so_cred->cr_uidinfo, &sb->sb_hiwat, 0,
649 sbrelease_locked(struct sockbuf *sb, struct socket *so)
652 SOCKBUF_LOCK_ASSERT(sb);
654 sbrelease_internal(sb, so);
658 sbrelease(struct sockbuf *sb, struct socket *so)
662 sbrelease_locked(sb, so);
667 sbdestroy(struct sockbuf *sb, struct socket *so)
670 sbrelease_internal(sb, so);
674 * Routines to add and remove data from an mbuf queue.
676 * The routines sbappend() or sbappendrecord() are normally called to append
677 * new mbufs to a socket buffer, after checking that adequate space is
678 * available, comparing the function sbspace() with the amount of data to be
679 * added. sbappendrecord() differs from sbappend() in that data supplied is
680 * treated as the beginning of a new record. To place a sender's address,
681 * optional access rights, and data in a socket receive buffer,
682 * sbappendaddr() should be used. To place access rights and data in a
683 * socket receive buffer, sbappendrights() should be used. In either case,
684 * the new data begins a new record. Note that unlike sbappend() and
685 * sbappendrecord(), these routines check for the caller that there will be
686 * enough space to store the data. Each fails if there is not enough space,
687 * or if it cannot find mbufs to store additional information in.
689 * Reliable protocols may use the socket send buffer to hold data awaiting
690 * acknowledgement. Data is normally copied from a socket send buffer in a
691 * protocol with m_copy for output to a peer, and then removing the data from
692 * the socket buffer with sbdrop() or sbdroprecord() when the data is
693 * acknowledged by the peer.
697 sblastrecordchk(struct sockbuf *sb, const char *file, int line)
699 struct mbuf *m = sb->sb_mb;
701 SOCKBUF_LOCK_ASSERT(sb);
703 while (m && m->m_nextpkt)
706 if (m != sb->sb_lastrecord) {
707 printf("%s: sb_mb %p sb_lastrecord %p last %p\n",
708 __func__, sb->sb_mb, sb->sb_lastrecord, m);
709 printf("packet chain:\n");
710 for (m = sb->sb_mb; m != NULL; m = m->m_nextpkt)
712 panic("%s from %s:%u", __func__, file, line);
717 sblastmbufchk(struct sockbuf *sb, const char *file, int line)
719 struct mbuf *m = sb->sb_mb;
722 SOCKBUF_LOCK_ASSERT(sb);
724 while (m && m->m_nextpkt)
727 while (m && m->m_next)
730 if (m != sb->sb_mbtail) {
731 printf("%s: sb_mb %p sb_mbtail %p last %p\n",
732 __func__, sb->sb_mb, sb->sb_mbtail, m);
733 printf("packet tree:\n");
734 for (m = sb->sb_mb; m != NULL; m = m->m_nextpkt) {
736 for (n = m; n != NULL; n = n->m_next)
740 panic("%s from %s:%u", __func__, file, line);
743 #endif /* SOCKBUF_DEBUG */
745 #define SBLINKRECORD(sb, m0) do { \
746 SOCKBUF_LOCK_ASSERT(sb); \
747 if ((sb)->sb_lastrecord != NULL) \
748 (sb)->sb_lastrecord->m_nextpkt = (m0); \
750 (sb)->sb_mb = (m0); \
751 (sb)->sb_lastrecord = (m0); \
752 } while (/*CONSTCOND*/0)
755 * Append mbuf chain m to the last record in the socket buffer sb. The
756 * additional space associated the mbuf chain is recorded in sb. Empty mbufs
757 * are discarded and mbufs are compacted where possible.
760 sbappend_locked(struct sockbuf *sb, struct mbuf *m, int flags)
764 SOCKBUF_LOCK_ASSERT(sb);
768 sbm_clrprotoflags(m, flags);
775 if (n->m_flags & M_EOR) {
776 sbappendrecord_locked(sb, m); /* XXXXXX!!!! */
779 } while (n->m_next && (n = n->m_next));
782 * XXX Would like to simply use sb_mbtail here, but
783 * XXX I need to verify that I won't miss an EOR that
786 if ((n = sb->sb_lastrecord) != NULL) {
788 if (n->m_flags & M_EOR) {
789 sbappendrecord_locked(sb, m); /* XXXXXX!!!! */
792 } while (n->m_next && (n = n->m_next));
795 * If this is the first record in the socket buffer,
796 * it's also the last record.
798 sb->sb_lastrecord = m;
801 sbcompress(sb, m, n);
806 * Append mbuf chain m to the last record in the socket buffer sb. The
807 * additional space associated the mbuf chain is recorded in sb. Empty mbufs
808 * are discarded and mbufs are compacted where possible.
811 sbappend(struct sockbuf *sb, struct mbuf *m, int flags)
815 sbappend_locked(sb, m, flags);
820 * This version of sbappend() should only be used when the caller absolutely
821 * knows that there will never be more than one record in the socket buffer,
822 * that is, a stream protocol (such as TCP).
825 sbappendstream_locked(struct sockbuf *sb, struct mbuf *m, int flags)
827 SOCKBUF_LOCK_ASSERT(sb);
829 KASSERT(m->m_nextpkt == NULL,("sbappendstream 0"));
830 KASSERT(sb->sb_mb == sb->sb_lastrecord,("sbappendstream 1"));
834 /* Remove all packet headers and mbuf tags to get a pure data chain. */
835 m_demote(m, 1, flags & PRUS_NOTREADY ? M_NOTREADY : 0);
837 sbcompress(sb, m, sb->sb_mbtail);
839 sb->sb_lastrecord = sb->sb_mb;
844 * This version of sbappend() should only be used when the caller absolutely
845 * knows that there will never be more than one record in the socket buffer,
846 * that is, a stream protocol (such as TCP).
849 sbappendstream(struct sockbuf *sb, struct mbuf *m, int flags)
853 sbappendstream_locked(sb, m, flags);
859 sbcheck(struct sockbuf *sb, const char *file, int line)
861 struct mbuf *m, *n, *fnrdy;
862 u_long acc, ccc, mbcnt;
864 SOCKBUF_LOCK_ASSERT(sb);
866 acc = ccc = mbcnt = 0;
869 for (m = sb->sb_mb; m; m = n) {
871 for (; m; m = m->m_next) {
873 printf("sb %p empty mbuf %p\n", sb, m);
876 if ((m->m_flags & M_NOTREADY) && fnrdy == NULL) {
877 if (m != sb->sb_fnrdy) {
878 printf("sb %p: fnrdy %p != m %p\n",
879 sb, sb->sb_fnrdy, m);
885 if (!(m->m_flags & M_NOTAVAIL)) {
886 printf("sb %p: fnrdy %p, m %p is avail\n",
887 sb, sb->sb_fnrdy, m);
894 if (m->m_flags & M_EXT) /*XXX*/ /* pretty sure this is bogus */
895 mbcnt += m->m_ext.ext_size;
898 if (acc != sb->sb_acc || ccc != sb->sb_ccc || mbcnt != sb->sb_mbcnt) {
899 printf("acc %ld/%u ccc %ld/%u mbcnt %ld/%u\n",
900 acc, sb->sb_acc, ccc, sb->sb_ccc, mbcnt, sb->sb_mbcnt);
905 panic("%s from %s:%u", __func__, file, line);
910 * As above, except the mbuf chain begins a new record.
913 sbappendrecord_locked(struct sockbuf *sb, struct mbuf *m0)
917 SOCKBUF_LOCK_ASSERT(sb);
923 * Put the first mbuf on the queue. Note this permits zero length
928 SBLINKRECORD(sb, m0);
932 if (m && (m0->m_flags & M_EOR)) {
933 m0->m_flags &= ~M_EOR;
936 /* always call sbcompress() so it can do SBLASTMBUFCHK() */
937 sbcompress(sb, m, m0);
941 * As above, except the mbuf chain begins a new record.
944 sbappendrecord(struct sockbuf *sb, struct mbuf *m0)
948 sbappendrecord_locked(sb, m0);
952 /* Helper routine that appends data, control, and address to a sockbuf. */
954 sbappendaddr_locked_internal(struct sockbuf *sb, const struct sockaddr *asa,
955 struct mbuf *m0, struct mbuf *control, struct mbuf *ctrl_last)
957 struct mbuf *m, *n, *nlast;
959 if (asa->sa_len > MLEN)
962 m = m_get(M_NOWAIT, MT_SONAME);
965 m->m_len = asa->sa_len;
966 bcopy(asa, mtod(m, caddr_t), asa->sa_len);
969 m_tag_delete_chain(m0, NULL);
971 * Clear some persistent info from pkthdr.
972 * We don't use m_demote(), because some netgraph consumers
973 * expect M_PKTHDR presence.
975 m0->m_pkthdr.rcvif = NULL;
976 m0->m_pkthdr.flowid = 0;
977 m0->m_pkthdr.csum_flags = 0;
978 m0->m_pkthdr.fibnum = 0;
979 m0->m_pkthdr.rsstype = 0;
982 ctrl_last->m_next = m0; /* concatenate data to control */
986 for (n = m; n->m_next != NULL; n = n->m_next)
992 sb->sb_mbtail = nlast;
1000 * Append address and data, and optionally, control (ancillary) data to the
1001 * receive queue of a socket. If present, m0 must include a packet header
1002 * with total length. Returns 0 if no space in sockbuf or insufficient
1006 sbappendaddr_locked(struct sockbuf *sb, const struct sockaddr *asa,
1007 struct mbuf *m0, struct mbuf *control)
1009 struct mbuf *ctrl_last;
1010 int space = asa->sa_len;
1012 SOCKBUF_LOCK_ASSERT(sb);
1014 if (m0 && (m0->m_flags & M_PKTHDR) == 0)
1015 panic("sbappendaddr_locked");
1017 space += m0->m_pkthdr.len;
1018 space += m_length(control, &ctrl_last);
1020 if (space > sbspace(sb))
1022 return (sbappendaddr_locked_internal(sb, asa, m0, control, ctrl_last));
1026 * Append address and data, and optionally, control (ancillary) data to the
1027 * receive queue of a socket. If present, m0 must include a packet header
1028 * with total length. Returns 0 if insufficient mbufs. Does not validate space
1029 * on the receiving sockbuf.
1032 sbappendaddr_nospacecheck_locked(struct sockbuf *sb, const struct sockaddr *asa,
1033 struct mbuf *m0, struct mbuf *control)
1035 struct mbuf *ctrl_last;
1037 SOCKBUF_LOCK_ASSERT(sb);
1039 ctrl_last = (control == NULL) ? NULL : m_last(control);
1040 return (sbappendaddr_locked_internal(sb, asa, m0, control, ctrl_last));
1044 * Append address and data, and optionally, control (ancillary) data to the
1045 * receive queue of a socket. If present, m0 must include a packet header
1046 * with total length. Returns 0 if no space in sockbuf or insufficient
1050 sbappendaddr(struct sockbuf *sb, const struct sockaddr *asa,
1051 struct mbuf *m0, struct mbuf *control)
1056 retval = sbappendaddr_locked(sb, asa, m0, control);
1062 sbappendcontrol_locked(struct sockbuf *sb, struct mbuf *m0,
1063 struct mbuf *control)
1065 struct mbuf *m, *mlast;
1067 m_clrprotoflags(m0);
1068 m_last(control)->m_next = m0;
1070 SBLASTRECORDCHK(sb);
1072 for (m = control; m->m_next; m = m->m_next)
1076 SBLINKRECORD(sb, control);
1078 sb->sb_mbtail = mlast;
1081 SBLASTRECORDCHK(sb);
1085 sbappendcontrol(struct sockbuf *sb, struct mbuf *m0, struct mbuf *control)
1089 sbappendcontrol_locked(sb, m0, control);
1094 * Append the data in mbuf chain (m) into the socket buffer sb following mbuf
1095 * (n). If (n) is NULL, the buffer is presumed empty.
1097 * When the data is compressed, mbufs in the chain may be handled in one of
1100 * (1) The mbuf may simply be dropped, if it contributes nothing (no data, no
1101 * record boundary, and no change in data type).
1103 * (2) The mbuf may be coalesced -- i.e., data in the mbuf may be copied into
1104 * an mbuf already in the socket buffer. This can occur if an
1105 * appropriate mbuf exists, there is room, both mbufs are not marked as
1106 * not ready, and no merging of data types will occur.
1108 * (3) The mbuf may be appended to the end of the existing mbuf chain.
1110 * If any of the new mbufs is marked as M_EOR, mark the last mbuf appended as
1114 sbcompress(struct sockbuf *sb, struct mbuf *m, struct mbuf *n)
1119 SOCKBUF_LOCK_ASSERT(sb);
1122 eor |= m->m_flags & M_EOR;
1123 if (m->m_len == 0 &&
1125 (((o = m->m_next) || (o = n)) &&
1126 o->m_type == m->m_type))) {
1127 if (sb->sb_lastrecord == m)
1128 sb->sb_lastrecord = m->m_next;
1132 if (n && (n->m_flags & M_EOR) == 0 &&
1134 ((sb->sb_flags & SB_NOCOALESCE) == 0) &&
1135 !(m->m_flags & M_NOTREADY) &&
1136 !(n->m_flags & (M_NOTREADY | M_NOMAP)) &&
1137 m->m_len <= MCLBYTES / 4 && /* XXX: Don't copy too much */
1138 m->m_len <= M_TRAILINGSPACE(n) &&
1139 n->m_type == m->m_type) {
1140 m_copydata(m, 0, m->m_len, mtodo(n, n->m_len));
1141 n->m_len += m->m_len;
1142 sb->sb_ccc += m->m_len;
1143 if (sb->sb_fnrdy == NULL)
1144 sb->sb_acc += m->m_len;
1145 if (m->m_type != MT_DATA && m->m_type != MT_OOBDATA)
1146 /* XXX: Probably don't need.*/
1147 sb->sb_ctl += m->m_len;
1151 if (m->m_len <= MLEN && (m->m_flags & M_NOMAP) &&
1152 (m->m_flags & M_NOTREADY) == 0)
1153 (void)mb_unmapped_compress(m);
1161 m->m_flags &= ~M_EOR;
1166 KASSERT(n != NULL, ("sbcompress: eor && n == NULL"));
1173 * Free all mbufs in a sockbuf. Check that all resources are reclaimed.
1176 sbflush_internal(struct sockbuf *sb)
1179 while (sb->sb_mbcnt) {
1181 * Don't call sbcut(sb, 0) if the leading mbuf is non-empty:
1182 * we would loop forever. Panic instead.
1184 if (sb->sb_ccc == 0 && (sb->sb_mb == NULL || sb->sb_mb->m_len))
1186 m_freem(sbcut_internal(sb, (int)sb->sb_ccc));
1188 KASSERT(sb->sb_ccc == 0 && sb->sb_mb == 0 && sb->sb_mbcnt == 0,
1189 ("%s: ccc %u mb %p mbcnt %u", __func__,
1190 sb->sb_ccc, (void *)sb->sb_mb, sb->sb_mbcnt));
1194 sbflush_locked(struct sockbuf *sb)
1197 SOCKBUF_LOCK_ASSERT(sb);
1198 sbflush_internal(sb);
1202 sbflush(struct sockbuf *sb)
1211 * Cut data from (the front of) a sockbuf.
1213 static struct mbuf *
1214 sbcut_internal(struct sockbuf *sb, int len)
1216 struct mbuf *m, *next, *mfree;
1218 KASSERT(len >= 0, ("%s: len is %d but it is supposed to be >= 0",
1220 KASSERT(len <= sb->sb_ccc, ("%s: len: %d is > ccc: %u",
1221 __func__, len, sb->sb_ccc));
1223 next = (m = sb->sb_mb) ? m->m_nextpkt : 0;
1228 KASSERT(next, ("%s: no next, len %d", __func__, len));
1230 next = m->m_nextpkt;
1232 if (m->m_len > len) {
1233 KASSERT(!(m->m_flags & M_NOTAVAIL),
1234 ("%s: m %p M_NOTAVAIL", __func__, m));
1239 if (sb->sb_sndptroff != 0)
1240 sb->sb_sndptroff -= len;
1241 if (m->m_type != MT_DATA && m->m_type != MT_OOBDATA)
1248 * Do not put M_NOTREADY buffers to the free list, they
1249 * are referenced from outside.
1251 if (m->m_flags & M_NOTREADY)
1263 * Free any zero-length mbufs from the buffer.
1264 * For SOCK_DGRAM sockets such mbufs represent empty records.
1265 * XXX: For SOCK_STREAM sockets such mbufs can appear in the buffer,
1266 * when sosend_generic() needs to send only control data.
1268 while (m && m->m_len == 0) {
1279 m->m_nextpkt = next;
1283 * First part is an inline SB_EMPTY_FIXUP(). Second part makes sure
1284 * sb_lastrecord is up-to-date if we dropped part of the last record.
1288 sb->sb_mbtail = NULL;
1289 sb->sb_lastrecord = NULL;
1290 } else if (m->m_nextpkt == NULL) {
1291 sb->sb_lastrecord = m;
1298 * Drop data from (the front of) a sockbuf.
1301 sbdrop_locked(struct sockbuf *sb, int len)
1304 SOCKBUF_LOCK_ASSERT(sb);
1305 m_freem(sbcut_internal(sb, len));
1309 * Drop data from (the front of) a sockbuf,
1310 * and return it to caller.
1313 sbcut_locked(struct sockbuf *sb, int len)
1316 SOCKBUF_LOCK_ASSERT(sb);
1317 return (sbcut_internal(sb, len));
1321 sbdrop(struct sockbuf *sb, int len)
1326 mfree = sbcut_internal(sb, len);
1333 sbsndptr_noadv(struct sockbuf *sb, uint32_t off, uint32_t *moff)
1337 KASSERT(sb->sb_mb != NULL, ("%s: sb_mb is NULL", __func__));
1338 if (sb->sb_sndptr == NULL || sb->sb_sndptroff > off) {
1340 if (sb->sb_sndptr == NULL) {
1341 sb->sb_sndptr = sb->sb_mb;
1342 sb->sb_sndptroff = 0;
1347 off -= sb->sb_sndptroff;
1354 sbsndptr_adv(struct sockbuf *sb, struct mbuf *mb, uint32_t len)
1357 * A small copy was done, advance forward the sb_sbsndptr to cover
1362 if (mb != sb->sb_sndptr) {
1363 /* Did not copyout at the same mbuf */
1367 while (m && (len > 0)) {
1368 if (len >= m->m_len) {
1371 sb->sb_sndptroff += m->m_len;
1372 sb->sb_sndptr = m->m_next;
1382 * Return the first mbuf and the mbuf data offset for the provided
1383 * send offset without changing the "sb_sndptroff" field.
1386 sbsndmbuf(struct sockbuf *sb, u_int off, u_int *moff)
1390 KASSERT(sb->sb_mb != NULL, ("%s: sb_mb is NULL", __func__));
1393 * If the "off" is below the stored offset, which happens on
1394 * retransmits, just use "sb_mb":
1396 if (sb->sb_sndptr == NULL || sb->sb_sndptroff > off) {
1400 off -= sb->sb_sndptroff;
1402 while (off > 0 && m != NULL) {
1413 * Drop a record off the front of a sockbuf and move the next record to the
1417 sbdroprecord_locked(struct sockbuf *sb)
1421 SOCKBUF_LOCK_ASSERT(sb);
1425 sb->sb_mb = m->m_nextpkt;
1435 * Drop a record off the front of a sockbuf and move the next record to the
1439 sbdroprecord(struct sockbuf *sb)
1443 sbdroprecord_locked(sb);
1448 * Create a "control" mbuf containing the specified data with the specified
1449 * type for presentation on a socket buffer.
1452 sbcreatecontrol(caddr_t p, int size, int type, int level)
1457 if (CMSG_SPACE((u_int)size) > MCLBYTES)
1458 return ((struct mbuf *) NULL);
1459 if (CMSG_SPACE((u_int)size) > MLEN)
1460 m = m_getcl(M_NOWAIT, MT_CONTROL, 0);
1462 m = m_get(M_NOWAIT, MT_CONTROL);
1464 return ((struct mbuf *) NULL);
1465 cp = mtod(m, struct cmsghdr *);
1467 KASSERT(CMSG_SPACE((u_int)size) <= M_TRAILINGSPACE(m),
1468 ("sbcreatecontrol: short mbuf"));
1470 * Don't leave the padding between the msg header and the
1471 * cmsg data and the padding after the cmsg data un-initialized.
1473 bzero(cp, CMSG_SPACE((u_int)size));
1475 (void)memcpy(CMSG_DATA(cp), p, size);
1476 m->m_len = CMSG_SPACE(size);
1477 cp->cmsg_len = CMSG_LEN(size);
1478 cp->cmsg_level = level;
1479 cp->cmsg_type = type;
1484 * This does the same for socket buffers that sotoxsocket does for sockets:
1485 * generate an user-format data structure describing the socket buffer. Note
1486 * that the xsockbuf structure, since it is always embedded in a socket, does
1487 * not include a self pointer nor a length. We make this entry point public
1488 * in case some other mechanism needs it.
1491 sbtoxsockbuf(struct sockbuf *sb, struct xsockbuf *xsb)
1494 xsb->sb_cc = sb->sb_ccc;
1495 xsb->sb_hiwat = sb->sb_hiwat;
1496 xsb->sb_mbcnt = sb->sb_mbcnt;
1497 xsb->sb_mcnt = sb->sb_mcnt;
1498 xsb->sb_ccnt = sb->sb_ccnt;
1499 xsb->sb_mbmax = sb->sb_mbmax;
1500 xsb->sb_lowat = sb->sb_lowat;
1501 xsb->sb_flags = sb->sb_flags;
1502 xsb->sb_timeo = sb->sb_timeo;
1505 /* This takes the place of kern.maxsockbuf, which moved to kern.ipc. */
1507 SYSCTL_INT(_kern, KERN_DUMMY, dummy, CTLFLAG_RW, &dummy, 0, "");
1508 SYSCTL_OID(_kern_ipc, KIPC_MAXSOCKBUF, maxsockbuf, CTLTYPE_ULONG|CTLFLAG_RW,
1509 &sb_max, 0, sysctl_handle_sb_max, "LU", "Maximum socket buffer size");
1510 SYSCTL_ULONG(_kern_ipc, KIPC_SOCKBUF_WASTE, sockbuf_waste_factor, CTLFLAG_RW,
1511 &sb_efficiency, 0, "Socket buffer size waste factor");