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_kern_tls.h"
38 #include "opt_param.h"
40 #include <sys/param.h>
41 #include <sys/aio.h> /* for aio_swake proto */
42 #include <sys/kernel.h>
45 #include <sys/malloc.h>
47 #include <sys/mutex.h>
49 #include <sys/protosw.h>
50 #include <sys/resourcevar.h>
51 #include <sys/signalvar.h>
52 #include <sys/socket.h>
53 #include <sys/socketvar.h>
55 #include <sys/sysctl.h>
58 * Function pointer set by the AIO routines so that the socket buffer code
59 * can call back into the AIO module if it is loaded.
61 void (*aio_swake)(struct socket *, struct sockbuf *);
64 * Primitive routines for operating on socket buffers
67 u_long sb_max = SB_MAX;
69 (quad_t)SB_MAX * MCLBYTES / (MSIZE + MCLBYTES); /* adjusted sb_max */
71 static u_long sb_efficiency = 8; /* parameter for sbreserve() */
73 static struct mbuf *sbcut_internal(struct sockbuf *sb, int len);
74 static void sbflush_internal(struct sockbuf *sb);
77 * Our own version of m_clrprotoflags(), that can preserve M_NOTREADY.
80 sbm_clrprotoflags(struct mbuf *m, int flags)
85 if (flags & PRUS_NOTREADY)
94 * Compress M_NOTREADY mbufs after they have been readied by sbready().
96 * sbcompress() skips M_NOTREADY mbufs since the data is not available to
97 * be copied at the time of sbcompress(). This function combines small
98 * mbufs similar to sbcompress() once mbufs are ready. 'm0' is the first
99 * mbuf sbready() marked ready, and 'end' is the first mbuf still not
103 sbready_compress(struct sockbuf *sb, struct mbuf *m0, struct mbuf *end)
108 SOCKBUF_LOCK_ASSERT(sb);
110 if ((sb->sb_flags & SB_NOCOALESCE) != 0)
113 for (m = m0; m != end; m = m->m_next) {
114 MPASS((m->m_flags & M_NOTREADY) == 0);
116 * NB: In sbcompress(), 'n' is the last mbuf in the
117 * socket buffer and 'm' is the new mbuf being copied
118 * into the trailing space of 'n'. Here, the roles
119 * are reversed and 'n' is the next mbuf after 'm'
120 * that is being copied into the trailing space of
125 /* Try to coalesce adjacent ktls mbuf hdr/trailers. */
126 if ((n != NULL) && (n != end) && (m->m_flags & M_EOR) == 0 &&
127 (m->m_flags & M_EXTPG) &&
128 (n->m_flags & M_EXTPG) &&
129 !mbuf_has_tls_session(m) &&
130 !mbuf_has_tls_session(n)) {
131 int hdr_len, trail_len;
133 hdr_len = n->m_epg_hdrlen;
134 trail_len = m->m_epg_trllen;
135 if (trail_len != 0 && hdr_len != 0 &&
136 trail_len + hdr_len <= MBUF_PEXT_TRAIL_LEN) {
137 /* copy n's header to m's trailer */
138 memcpy(&m->m_epg_trail[trail_len],
139 n->m_epg_hdr, hdr_len);
140 m->m_epg_trllen += hdr_len;
148 /* Compress small unmapped mbufs into plain mbufs. */
149 if ((m->m_flags & M_EXTPG) && m->m_len <= MLEN &&
150 !mbuf_has_tls_session(m)) {
151 ext_size = m->m_ext.ext_size;
152 if (mb_unmapped_compress(m) == 0) {
153 sb->sb_mbcnt -= ext_size;
158 while ((n != NULL) && (n != end) && (m->m_flags & M_EOR) == 0 &&
160 (m->m_flags & M_EXTPG) == 0 &&
161 !mbuf_has_tls_session(n) &&
162 !mbuf_has_tls_session(m) &&
163 n->m_len <= MCLBYTES / 4 && /* XXX: Don't copy too much */
164 n->m_len <= M_TRAILINGSPACE(m) &&
165 m->m_type == n->m_type) {
166 KASSERT(sb->sb_lastrecord != n,
167 ("%s: merging start of record (%p) into previous mbuf (%p)",
169 m_copydata(n, 0, n->m_len, mtodo(m, m->m_len));
170 m->m_len += n->m_len;
171 m->m_next = n->m_next;
172 m->m_flags |= n->m_flags & M_EOR;
173 if (sb->sb_mbtail == n)
176 sb->sb_mbcnt -= MSIZE;
178 if (n->m_flags & M_EXT) {
179 sb->sb_mbcnt -= n->m_ext.ext_size;
191 * Mark ready "count" units of I/O starting with "m". Most mbufs
192 * count as a single unit of I/O except for M_EXTPG mbufs which
193 * are backed by multiple pages.
196 sbready(struct sockbuf *sb, struct mbuf *m0, int count)
201 SOCKBUF_LOCK_ASSERT(sb);
202 KASSERT(sb->sb_fnrdy != NULL, ("%s: sb %p NULL fnrdy", __func__, sb));
203 KASSERT(count > 0, ("%s: invalid count %d", __func__, count));
206 blocker = (sb->sb_fnrdy == m) ? M_BLOCKED : 0;
209 KASSERT(m->m_flags & M_NOTREADY,
210 ("%s: m %p !M_NOTREADY", __func__, m));
211 if ((m->m_flags & M_EXTPG) != 0) {
212 if (count < m->m_epg_nrdy) {
213 m->m_epg_nrdy -= count;
217 count -= m->m_epg_nrdy;
222 m->m_flags &= ~(M_NOTREADY | blocker);
224 sb->sb_acc += m->m_len;
229 * If the first mbuf is still not fully ready because only
230 * some of its backing pages were readied, no further progress
234 MPASS(m->m_flags & M_NOTREADY);
235 return (EINPROGRESS);
239 sbready_compress(sb, m0, m);
240 return (EINPROGRESS);
243 /* This one was blocking all the queue. */
244 for (; m && (m->m_flags & M_NOTREADY) == 0; m = m->m_next) {
245 KASSERT(m->m_flags & M_BLOCKED,
246 ("%s: m %p !M_BLOCKED", __func__, m));
247 m->m_flags &= ~M_BLOCKED;
248 sb->sb_acc += m->m_len;
252 sbready_compress(sb, m0, m);
258 * Adjust sockbuf state reflecting allocation of m.
261 sballoc(struct sockbuf *sb, struct mbuf *m)
264 SOCKBUF_LOCK_ASSERT(sb);
266 sb->sb_ccc += m->m_len;
268 if (sb->sb_fnrdy == NULL) {
269 if (m->m_flags & M_NOTREADY)
272 sb->sb_acc += m->m_len;
274 m->m_flags |= M_BLOCKED;
276 if (m->m_type != MT_DATA && m->m_type != MT_OOBDATA)
277 sb->sb_ctl += m->m_len;
279 sb->sb_mbcnt += MSIZE;
282 if (m->m_flags & M_EXT) {
283 sb->sb_mbcnt += m->m_ext.ext_size;
289 * Adjust sockbuf state reflecting freeing of m.
292 sbfree(struct sockbuf *sb, struct mbuf *m)
295 #if 0 /* XXX: not yet: soclose() call path comes here w/o lock. */
296 SOCKBUF_LOCK_ASSERT(sb);
299 sb->sb_ccc -= m->m_len;
301 if (!(m->m_flags & M_NOTAVAIL))
302 sb->sb_acc -= m->m_len;
304 if (m == sb->sb_fnrdy) {
307 KASSERT(m->m_flags & M_NOTREADY,
308 ("%s: m %p !M_NOTREADY", __func__, m));
311 while (n != NULL && !(n->m_flags & M_NOTREADY)) {
312 n->m_flags &= ~M_BLOCKED;
313 sb->sb_acc += n->m_len;
319 if (m->m_type != MT_DATA && m->m_type != MT_OOBDATA)
320 sb->sb_ctl -= m->m_len;
322 sb->sb_mbcnt -= MSIZE;
324 if (m->m_flags & M_EXT) {
325 sb->sb_mbcnt -= m->m_ext.ext_size;
329 if (sb->sb_sndptr == m) {
330 sb->sb_sndptr = NULL;
331 sb->sb_sndptroff = 0;
333 if (sb->sb_sndptroff != 0)
334 sb->sb_sndptroff -= m->m_len;
338 * Socantsendmore indicates that no more data will be sent on the socket; it
339 * would normally be applied to a socket when the user informs the system
340 * that no more data is to be sent, by the protocol code (in case
341 * PRU_SHUTDOWN). Socantrcvmore indicates that no more data will be
342 * received, and will normally be applied to the socket by a protocol when it
343 * detects that the peer will send no more data. Data queued for reading in
344 * the socket may yet be read.
347 socantsendmore_locked(struct socket *so)
350 SOCKBUF_LOCK_ASSERT(&so->so_snd);
352 so->so_snd.sb_state |= SBS_CANTSENDMORE;
353 sowwakeup_locked(so);
354 mtx_assert(SOCKBUF_MTX(&so->so_snd), MA_NOTOWNED);
358 socantsendmore(struct socket *so)
361 SOCKBUF_LOCK(&so->so_snd);
362 socantsendmore_locked(so);
363 mtx_assert(SOCKBUF_MTX(&so->so_snd), MA_NOTOWNED);
367 socantrcvmore_locked(struct socket *so)
370 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
372 so->so_rcv.sb_state |= SBS_CANTRCVMORE;
373 sorwakeup_locked(so);
374 mtx_assert(SOCKBUF_MTX(&so->so_rcv), MA_NOTOWNED);
378 socantrcvmore(struct socket *so)
381 SOCKBUF_LOCK(&so->so_rcv);
382 socantrcvmore_locked(so);
383 mtx_assert(SOCKBUF_MTX(&so->so_rcv), MA_NOTOWNED);
387 * Wait for data to arrive at/drain from a socket buffer.
390 sbwait(struct sockbuf *sb)
393 SOCKBUF_LOCK_ASSERT(sb);
395 sb->sb_flags |= SB_WAIT;
396 return (msleep_sbt(&sb->sb_acc, &sb->sb_mtx,
397 (sb->sb_flags & SB_NOINTR) ? PSOCK : PSOCK | PCATCH, "sbwait",
398 sb->sb_timeo, 0, 0));
402 sblock(struct sockbuf *sb, int flags)
405 KASSERT((flags & SBL_VALID) == flags,
406 ("sblock: flags invalid (0x%x)", flags));
408 if (flags & SBL_WAIT) {
409 if ((sb->sb_flags & SB_NOINTR) ||
410 (flags & SBL_NOINTR)) {
411 sx_xlock(&sb->sb_sx);
414 return (sx_xlock_sig(&sb->sb_sx));
416 if (sx_try_xlock(&sb->sb_sx) == 0)
417 return (EWOULDBLOCK);
423 sbunlock(struct sockbuf *sb)
426 sx_xunlock(&sb->sb_sx);
430 * Wakeup processes waiting on a socket buffer. Do asynchronous notification
431 * via SIGIO if the socket has the SS_ASYNC flag set.
433 * Called with the socket buffer lock held; will release the lock by the end
434 * of the function. This allows the caller to acquire the socket buffer lock
435 * while testing for the need for various sorts of wakeup and hold it through
436 * to the point where it's no longer required. We currently hold the lock
437 * through calls out to other subsystems (with the exception of kqueue), and
438 * then release it to avoid lock order issues. It's not clear that's
442 sowakeup(struct socket *so, struct sockbuf *sb)
446 SOCKBUF_LOCK_ASSERT(sb);
448 selwakeuppri(sb->sb_sel, PSOCK);
449 if (!SEL_WAITING(sb->sb_sel))
450 sb->sb_flags &= ~SB_SEL;
451 if (sb->sb_flags & SB_WAIT) {
452 sb->sb_flags &= ~SB_WAIT;
455 KNOTE_LOCKED(&sb->sb_sel->si_note, 0);
456 if (sb->sb_upcall != NULL) {
457 ret = sb->sb_upcall(so, sb->sb_upcallarg, M_NOWAIT);
458 if (ret == SU_ISCONNECTED) {
459 KASSERT(sb == &so->so_rcv,
460 ("SO_SND upcall returned SU_ISCONNECTED"));
461 soupcall_clear(so, SO_RCV);
465 if (sb->sb_flags & SB_AIO)
466 sowakeup_aio(so, sb);
468 if (ret == SU_ISCONNECTED)
470 if ((so->so_state & SS_ASYNC) && so->so_sigio != NULL)
471 pgsigio(&so->so_sigio, SIGIO, 0);
472 mtx_assert(SOCKBUF_MTX(sb), MA_NOTOWNED);
476 * Socket buffer (struct sockbuf) utility routines.
478 * Each socket contains two socket buffers: one for sending data and one for
479 * receiving data. Each buffer contains a queue of mbufs, information about
480 * the number of mbufs and amount of data in the queue, and other fields
481 * allowing select() statements and notification on data availability to be
484 * Data stored in a socket buffer is maintained as a list of records. Each
485 * record is a list of mbufs chained together with the m_next field. Records
486 * are chained together with the m_nextpkt field. The upper level routine
487 * soreceive() expects the following conventions to be observed when placing
488 * information in the receive buffer:
490 * 1. If the protocol requires each message be preceded by the sender's name,
491 * then a record containing that name must be present before any
492 * associated data (mbuf's must be of type MT_SONAME).
493 * 2. If the protocol supports the exchange of ``access rights'' (really just
494 * additional data associated with the message), and there are ``rights''
495 * to be received, then a record containing this data should be present
496 * (mbuf's must be of type MT_RIGHTS).
497 * 3. If a name or rights record exists, then it must be followed by a data
498 * record, perhaps of zero length.
500 * Before using a new socket structure it is first necessary to reserve
501 * buffer space to the socket, by calling sbreserve(). This should commit
502 * some of the available buffer space in the system buffer pool for the
503 * socket (currently, it does nothing but enforce limits). The space should
504 * be released by calling sbrelease() when the socket is destroyed.
507 soreserve(struct socket *so, u_long sndcc, u_long rcvcc)
509 struct thread *td = curthread;
511 SOCKBUF_LOCK(&so->so_snd);
512 SOCKBUF_LOCK(&so->so_rcv);
513 if (sbreserve_locked(&so->so_snd, sndcc, so, td) == 0)
515 if (sbreserve_locked(&so->so_rcv, rcvcc, so, td) == 0)
517 if (so->so_rcv.sb_lowat == 0)
518 so->so_rcv.sb_lowat = 1;
519 if (so->so_snd.sb_lowat == 0)
520 so->so_snd.sb_lowat = MCLBYTES;
521 if (so->so_snd.sb_lowat > so->so_snd.sb_hiwat)
522 so->so_snd.sb_lowat = so->so_snd.sb_hiwat;
523 SOCKBUF_UNLOCK(&so->so_rcv);
524 SOCKBUF_UNLOCK(&so->so_snd);
527 sbrelease_locked(&so->so_snd, so);
529 SOCKBUF_UNLOCK(&so->so_rcv);
530 SOCKBUF_UNLOCK(&so->so_snd);
535 sysctl_handle_sb_max(SYSCTL_HANDLER_ARGS)
538 u_long tmp_sb_max = sb_max;
540 error = sysctl_handle_long(oidp, &tmp_sb_max, arg2, req);
541 if (error || !req->newptr)
543 if (tmp_sb_max < MSIZE + MCLBYTES)
546 sb_max_adj = (u_quad_t)sb_max * MCLBYTES / (MSIZE + MCLBYTES);
551 * Allot mbufs to a sockbuf. Attempt to scale mbmax so that mbcnt doesn't
552 * become limiting if buffering efficiency is near the normal case.
555 sbreserve_locked(struct sockbuf *sb, u_long cc, struct socket *so,
560 SOCKBUF_LOCK_ASSERT(sb);
563 * When a thread is passed, we take into account the thread's socket
564 * buffer size limit. The caller will generally pass curthread, but
565 * in the TCP input path, NULL will be passed to indicate that no
566 * appropriate thread resource limits are available. In that case,
567 * we don't apply a process limit.
572 sbsize_limit = lim_cur(td, RLIMIT_SBSIZE);
574 sbsize_limit = RLIM_INFINITY;
575 if (!chgsbsize(so->so_cred->cr_uidinfo, &sb->sb_hiwat, cc,
578 sb->sb_mbmax = min(cc * sb_efficiency, sb_max);
579 if (sb->sb_lowat > sb->sb_hiwat)
580 sb->sb_lowat = sb->sb_hiwat;
585 sbsetopt(struct socket *so, int cmd, u_long cc)
589 u_int *hiwat, *lowat;
594 if (SOLISTENING(so)) {
598 lowat = &so->sol_sbsnd_lowat;
599 hiwat = &so->sol_sbsnd_hiwat;
600 flags = &so->sol_sbsnd_flags;
604 lowat = &so->sol_sbrcv_lowat;
605 hiwat = &so->sol_sbrcv_hiwat;
606 flags = &so->sol_sbrcv_flags;
620 flags = &sb->sb_flags;
621 hiwat = &sb->sb_hiwat;
622 lowat = &sb->sb_lowat;
630 if (SOLISTENING(so)) {
631 if (cc > sb_max_adj) {
639 if (!sbreserve_locked(sb, cc, so, curthread))
643 *flags &= ~SB_AUTOSIZE;
648 * Make sure the low-water is never greater than the
651 *lowat = (cc > *hiwat) ? *hiwat : cc;
655 if (!SOLISTENING(so))
662 * Free mbufs held by a socket, and reserved mbuf space.
665 sbrelease_internal(struct sockbuf *sb, struct socket *so)
668 sbflush_internal(sb);
669 (void)chgsbsize(so->so_cred->cr_uidinfo, &sb->sb_hiwat, 0,
675 sbrelease_locked(struct sockbuf *sb, struct socket *so)
678 SOCKBUF_LOCK_ASSERT(sb);
680 sbrelease_internal(sb, so);
684 sbrelease(struct sockbuf *sb, struct socket *so)
688 sbrelease_locked(sb, so);
693 sbdestroy(struct sockbuf *sb, struct socket *so)
696 sbrelease_internal(sb, so);
698 if (sb->sb_tls_info != NULL)
699 ktls_free(sb->sb_tls_info);
700 sb->sb_tls_info = NULL;
705 * Routines to add and remove data from an mbuf queue.
707 * The routines sbappend() or sbappendrecord() are normally called to append
708 * new mbufs to a socket buffer, after checking that adequate space is
709 * available, comparing the function sbspace() with the amount of data to be
710 * added. sbappendrecord() differs from sbappend() in that data supplied is
711 * treated as the beginning of a new record. To place a sender's address,
712 * optional access rights, and data in a socket receive buffer,
713 * sbappendaddr() should be used. To place access rights and data in a
714 * socket receive buffer, sbappendrights() should be used. In either case,
715 * the new data begins a new record. Note that unlike sbappend() and
716 * sbappendrecord(), these routines check for the caller that there will be
717 * enough space to store the data. Each fails if there is not enough space,
718 * or if it cannot find mbufs to store additional information in.
720 * Reliable protocols may use the socket send buffer to hold data awaiting
721 * acknowledgement. Data is normally copied from a socket send buffer in a
722 * protocol with m_copy for output to a peer, and then removing the data from
723 * the socket buffer with sbdrop() or sbdroprecord() when the data is
724 * acknowledged by the peer.
728 sblastrecordchk(struct sockbuf *sb, const char *file, int line)
730 struct mbuf *m = sb->sb_mb;
732 SOCKBUF_LOCK_ASSERT(sb);
734 while (m && m->m_nextpkt)
737 if (m != sb->sb_lastrecord) {
738 printf("%s: sb_mb %p sb_lastrecord %p last %p\n",
739 __func__, sb->sb_mb, sb->sb_lastrecord, m);
740 printf("packet chain:\n");
741 for (m = sb->sb_mb; m != NULL; m = m->m_nextpkt)
743 panic("%s from %s:%u", __func__, file, line);
748 sblastmbufchk(struct sockbuf *sb, const char *file, int line)
750 struct mbuf *m = sb->sb_mb;
753 SOCKBUF_LOCK_ASSERT(sb);
755 while (m && m->m_nextpkt)
758 while (m && m->m_next)
761 if (m != sb->sb_mbtail) {
762 printf("%s: sb_mb %p sb_mbtail %p last %p\n",
763 __func__, sb->sb_mb, sb->sb_mbtail, m);
764 printf("packet tree:\n");
765 for (m = sb->sb_mb; m != NULL; m = m->m_nextpkt) {
767 for (n = m; n != NULL; n = n->m_next)
771 panic("%s from %s:%u", __func__, file, line);
774 #endif /* SOCKBUF_DEBUG */
776 #define SBLINKRECORD(sb, m0) do { \
777 SOCKBUF_LOCK_ASSERT(sb); \
778 if ((sb)->sb_lastrecord != NULL) \
779 (sb)->sb_lastrecord->m_nextpkt = (m0); \
781 (sb)->sb_mb = (m0); \
782 (sb)->sb_lastrecord = (m0); \
783 } while (/*CONSTCOND*/0)
786 * Append mbuf chain m to the last record in the socket buffer sb. The
787 * additional space associated the mbuf chain is recorded in sb. Empty mbufs
788 * are discarded and mbufs are compacted where possible.
791 sbappend_locked(struct sockbuf *sb, struct mbuf *m, int flags)
795 SOCKBUF_LOCK_ASSERT(sb);
799 sbm_clrprotoflags(m, flags);
806 if (n->m_flags & M_EOR) {
807 sbappendrecord_locked(sb, m); /* XXXXXX!!!! */
810 } while (n->m_next && (n = n->m_next));
813 * XXX Would like to simply use sb_mbtail here, but
814 * XXX I need to verify that I won't miss an EOR that
817 if ((n = sb->sb_lastrecord) != NULL) {
819 if (n->m_flags & M_EOR) {
820 sbappendrecord_locked(sb, m); /* XXXXXX!!!! */
823 } while (n->m_next && (n = n->m_next));
826 * If this is the first record in the socket buffer,
827 * it's also the last record.
829 sb->sb_lastrecord = m;
832 sbcompress(sb, m, n);
837 * Append mbuf chain m to the last record in the socket buffer sb. The
838 * additional space associated the mbuf chain is recorded in sb. Empty mbufs
839 * are discarded and mbufs are compacted where possible.
842 sbappend(struct sockbuf *sb, struct mbuf *m, int flags)
846 sbappend_locked(sb, m, flags);
851 * This version of sbappend() should only be used when the caller absolutely
852 * knows that there will never be more than one record in the socket buffer,
853 * that is, a stream protocol (such as TCP).
856 sbappendstream_locked(struct sockbuf *sb, struct mbuf *m, int flags)
858 SOCKBUF_LOCK_ASSERT(sb);
860 KASSERT(m->m_nextpkt == NULL,("sbappendstream 0"));
861 KASSERT(sb->sb_mb == sb->sb_lastrecord,("sbappendstream 1"));
866 if (sb->sb_tls_info != NULL)
870 /* Remove all packet headers and mbuf tags to get a pure data chain. */
871 m_demote(m, 1, flags & PRUS_NOTREADY ? M_NOTREADY : 0);
873 sbcompress(sb, m, sb->sb_mbtail);
875 sb->sb_lastrecord = sb->sb_mb;
880 * This version of sbappend() should only be used when the caller absolutely
881 * knows that there will never be more than one record in the socket buffer,
882 * that is, a stream protocol (such as TCP).
885 sbappendstream(struct sockbuf *sb, struct mbuf *m, int flags)
889 sbappendstream_locked(sb, m, flags);
895 sbcheck(struct sockbuf *sb, const char *file, int line)
897 struct mbuf *m, *n, *fnrdy;
898 u_long acc, ccc, mbcnt;
900 SOCKBUF_LOCK_ASSERT(sb);
902 acc = ccc = mbcnt = 0;
905 for (m = sb->sb_mb; m; m = n) {
907 for (; m; m = m->m_next) {
909 printf("sb %p empty mbuf %p\n", sb, m);
912 if ((m->m_flags & M_NOTREADY) && fnrdy == NULL) {
913 if (m != sb->sb_fnrdy) {
914 printf("sb %p: fnrdy %p != m %p\n",
915 sb, sb->sb_fnrdy, m);
921 if (!(m->m_flags & M_NOTAVAIL)) {
922 printf("sb %p: fnrdy %p, m %p is avail\n",
923 sb, sb->sb_fnrdy, m);
930 if (m->m_flags & M_EXT) /*XXX*/ /* pretty sure this is bogus */
931 mbcnt += m->m_ext.ext_size;
934 if (acc != sb->sb_acc || ccc != sb->sb_ccc || mbcnt != sb->sb_mbcnt) {
935 printf("acc %ld/%u ccc %ld/%u mbcnt %ld/%u\n",
936 acc, sb->sb_acc, ccc, sb->sb_ccc, mbcnt, sb->sb_mbcnt);
941 panic("%s from %s:%u", __func__, file, line);
946 * As above, except the mbuf chain begins a new record.
949 sbappendrecord_locked(struct sockbuf *sb, struct mbuf *m0)
953 SOCKBUF_LOCK_ASSERT(sb);
959 * Put the first mbuf on the queue. Note this permits zero length
964 SBLINKRECORD(sb, m0);
968 if (m && (m0->m_flags & M_EOR)) {
969 m0->m_flags &= ~M_EOR;
972 /* always call sbcompress() so it can do SBLASTMBUFCHK() */
973 sbcompress(sb, m, m0);
977 * As above, except the mbuf chain begins a new record.
980 sbappendrecord(struct sockbuf *sb, struct mbuf *m0)
984 sbappendrecord_locked(sb, m0);
988 /* Helper routine that appends data, control, and address to a sockbuf. */
990 sbappendaddr_locked_internal(struct sockbuf *sb, const struct sockaddr *asa,
991 struct mbuf *m0, struct mbuf *control, struct mbuf *ctrl_last)
993 struct mbuf *m, *n, *nlast;
995 if (asa->sa_len > MLEN)
998 m = m_get(M_NOWAIT, MT_SONAME);
1001 m->m_len = asa->sa_len;
1002 bcopy(asa, mtod(m, caddr_t), asa->sa_len);
1004 m_clrprotoflags(m0);
1005 m_tag_delete_chain(m0, NULL);
1007 * Clear some persistent info from pkthdr.
1008 * We don't use m_demote(), because some netgraph consumers
1009 * expect M_PKTHDR presence.
1011 m0->m_pkthdr.rcvif = NULL;
1012 m0->m_pkthdr.flowid = 0;
1013 m0->m_pkthdr.csum_flags = 0;
1014 m0->m_pkthdr.fibnum = 0;
1015 m0->m_pkthdr.rsstype = 0;
1018 ctrl_last->m_next = m0; /* concatenate data to control */
1021 m->m_next = control;
1022 for (n = m; n->m_next != NULL; n = n->m_next)
1026 SBLINKRECORD(sb, m);
1028 sb->sb_mbtail = nlast;
1031 SBLASTRECORDCHK(sb);
1036 * Append address and data, and optionally, control (ancillary) data to the
1037 * receive queue of a socket. If present, m0 must include a packet header
1038 * with total length. Returns 0 if no space in sockbuf or insufficient
1042 sbappendaddr_locked(struct sockbuf *sb, const struct sockaddr *asa,
1043 struct mbuf *m0, struct mbuf *control)
1045 struct mbuf *ctrl_last;
1046 int space = asa->sa_len;
1048 SOCKBUF_LOCK_ASSERT(sb);
1050 if (m0 && (m0->m_flags & M_PKTHDR) == 0)
1051 panic("sbappendaddr_locked");
1053 space += m0->m_pkthdr.len;
1054 space += m_length(control, &ctrl_last);
1056 if (space > sbspace(sb))
1058 return (sbappendaddr_locked_internal(sb, asa, m0, control, ctrl_last));
1062 * Append address and data, and optionally, control (ancillary) data to the
1063 * receive queue of a socket. If present, m0 must include a packet header
1064 * with total length. Returns 0 if insufficient mbufs. Does not validate space
1065 * on the receiving sockbuf.
1068 sbappendaddr_nospacecheck_locked(struct sockbuf *sb, const struct sockaddr *asa,
1069 struct mbuf *m0, struct mbuf *control)
1071 struct mbuf *ctrl_last;
1073 SOCKBUF_LOCK_ASSERT(sb);
1075 ctrl_last = (control == NULL) ? NULL : m_last(control);
1076 return (sbappendaddr_locked_internal(sb, asa, m0, control, ctrl_last));
1080 * Append address and data, and optionally, control (ancillary) data to the
1081 * receive queue of a socket. If present, m0 must include a packet header
1082 * with total length. Returns 0 if no space in sockbuf or insufficient
1086 sbappendaddr(struct sockbuf *sb, const struct sockaddr *asa,
1087 struct mbuf *m0, struct mbuf *control)
1092 retval = sbappendaddr_locked(sb, asa, m0, control);
1098 sbappendcontrol_locked(struct sockbuf *sb, struct mbuf *m0,
1099 struct mbuf *control, int flags)
1101 struct mbuf *m, *mlast;
1103 sbm_clrprotoflags(m0, flags);
1104 m_last(control)->m_next = m0;
1106 SBLASTRECORDCHK(sb);
1108 for (m = control; m->m_next; m = m->m_next)
1112 SBLINKRECORD(sb, control);
1114 sb->sb_mbtail = mlast;
1117 SBLASTRECORDCHK(sb);
1121 sbappendcontrol(struct sockbuf *sb, struct mbuf *m0, struct mbuf *control,
1126 sbappendcontrol_locked(sb, m0, control, flags);
1131 * Append the data in mbuf chain (m) into the socket buffer sb following mbuf
1132 * (n). If (n) is NULL, the buffer is presumed empty.
1134 * When the data is compressed, mbufs in the chain may be handled in one of
1137 * (1) The mbuf may simply be dropped, if it contributes nothing (no data, no
1138 * record boundary, and no change in data type).
1140 * (2) The mbuf may be coalesced -- i.e., data in the mbuf may be copied into
1141 * an mbuf already in the socket buffer. This can occur if an
1142 * appropriate mbuf exists, there is room, both mbufs are not marked as
1143 * not ready, and no merging of data types will occur.
1145 * (3) The mbuf may be appended to the end of the existing mbuf chain.
1147 * If any of the new mbufs is marked as M_EOR, mark the last mbuf appended as
1151 sbcompress(struct sockbuf *sb, struct mbuf *m, struct mbuf *n)
1156 SOCKBUF_LOCK_ASSERT(sb);
1159 eor |= m->m_flags & M_EOR;
1160 if (m->m_len == 0 &&
1162 (((o = m->m_next) || (o = n)) &&
1163 o->m_type == m->m_type))) {
1164 if (sb->sb_lastrecord == m)
1165 sb->sb_lastrecord = m->m_next;
1169 if (n && (n->m_flags & M_EOR) == 0 &&
1171 ((sb->sb_flags & SB_NOCOALESCE) == 0) &&
1172 !(m->m_flags & M_NOTREADY) &&
1173 !(n->m_flags & (M_NOTREADY | M_EXTPG)) &&
1174 !mbuf_has_tls_session(m) &&
1175 !mbuf_has_tls_session(n) &&
1176 m->m_len <= MCLBYTES / 4 && /* XXX: Don't copy too much */
1177 m->m_len <= M_TRAILINGSPACE(n) &&
1178 n->m_type == m->m_type) {
1179 m_copydata(m, 0, m->m_len, mtodo(n, n->m_len));
1180 n->m_len += m->m_len;
1181 sb->sb_ccc += m->m_len;
1182 if (sb->sb_fnrdy == NULL)
1183 sb->sb_acc += m->m_len;
1184 if (m->m_type != MT_DATA && m->m_type != MT_OOBDATA)
1185 /* XXX: Probably don't need.*/
1186 sb->sb_ctl += m->m_len;
1190 if (m->m_len <= MLEN && (m->m_flags & M_EXTPG) &&
1191 (m->m_flags & M_NOTREADY) == 0 &&
1192 !mbuf_has_tls_session(m))
1193 (void)mb_unmapped_compress(m);
1201 m->m_flags &= ~M_EOR;
1206 KASSERT(n != NULL, ("sbcompress: eor && n == NULL"));
1213 * Free all mbufs in a sockbuf. Check that all resources are reclaimed.
1216 sbflush_internal(struct sockbuf *sb)
1219 while (sb->sb_mbcnt) {
1221 * Don't call sbcut(sb, 0) if the leading mbuf is non-empty:
1222 * we would loop forever. Panic instead.
1224 if (sb->sb_ccc == 0 && (sb->sb_mb == NULL || sb->sb_mb->m_len))
1226 m_freem(sbcut_internal(sb, (int)sb->sb_ccc));
1228 KASSERT(sb->sb_ccc == 0 && sb->sb_mb == 0 && sb->sb_mbcnt == 0,
1229 ("%s: ccc %u mb %p mbcnt %u", __func__,
1230 sb->sb_ccc, (void *)sb->sb_mb, sb->sb_mbcnt));
1234 sbflush_locked(struct sockbuf *sb)
1237 SOCKBUF_LOCK_ASSERT(sb);
1238 sbflush_internal(sb);
1242 sbflush(struct sockbuf *sb)
1251 * Cut data from (the front of) a sockbuf.
1253 static struct mbuf *
1254 sbcut_internal(struct sockbuf *sb, int len)
1256 struct mbuf *m, *next, *mfree;
1258 KASSERT(len >= 0, ("%s: len is %d but it is supposed to be >= 0",
1260 KASSERT(len <= sb->sb_ccc, ("%s: len: %d is > ccc: %u",
1261 __func__, len, sb->sb_ccc));
1263 next = (m = sb->sb_mb) ? m->m_nextpkt : 0;
1268 KASSERT(next, ("%s: no next, len %d", __func__, len));
1270 next = m->m_nextpkt;
1272 if (m->m_len > len) {
1273 KASSERT(!(m->m_flags & M_NOTAVAIL),
1274 ("%s: m %p M_NOTAVAIL", __func__, m));
1279 if (sb->sb_sndptroff != 0)
1280 sb->sb_sndptroff -= len;
1281 if (m->m_type != MT_DATA && m->m_type != MT_OOBDATA)
1288 * Do not put M_NOTREADY buffers to the free list, they
1289 * are referenced from outside.
1291 if (m->m_flags & M_NOTREADY)
1303 * Free any zero-length mbufs from the buffer.
1304 * For SOCK_DGRAM sockets such mbufs represent empty records.
1305 * XXX: For SOCK_STREAM sockets such mbufs can appear in the buffer,
1306 * when sosend_generic() needs to send only control data.
1308 while (m && m->m_len == 0) {
1319 m->m_nextpkt = next;
1323 * First part is an inline SB_EMPTY_FIXUP(). Second part makes sure
1324 * sb_lastrecord is up-to-date if we dropped part of the last record.
1328 sb->sb_mbtail = NULL;
1329 sb->sb_lastrecord = NULL;
1330 } else if (m->m_nextpkt == NULL) {
1331 sb->sb_lastrecord = m;
1338 * Drop data from (the front of) a sockbuf.
1341 sbdrop_locked(struct sockbuf *sb, int len)
1344 SOCKBUF_LOCK_ASSERT(sb);
1345 m_freem(sbcut_internal(sb, len));
1349 * Drop data from (the front of) a sockbuf,
1350 * and return it to caller.
1353 sbcut_locked(struct sockbuf *sb, int len)
1356 SOCKBUF_LOCK_ASSERT(sb);
1357 return (sbcut_internal(sb, len));
1361 sbdrop(struct sockbuf *sb, int len)
1366 mfree = sbcut_internal(sb, len);
1373 sbsndptr_noadv(struct sockbuf *sb, uint32_t off, uint32_t *moff)
1377 KASSERT(sb->sb_mb != NULL, ("%s: sb_mb is NULL", __func__));
1378 if (sb->sb_sndptr == NULL || sb->sb_sndptroff > off) {
1380 if (sb->sb_sndptr == NULL) {
1381 sb->sb_sndptr = sb->sb_mb;
1382 sb->sb_sndptroff = 0;
1387 off -= sb->sb_sndptroff;
1394 sbsndptr_adv(struct sockbuf *sb, struct mbuf *mb, uint32_t len)
1397 * A small copy was done, advance forward the sb_sbsndptr to cover
1402 if (mb != sb->sb_sndptr) {
1403 /* Did not copyout at the same mbuf */
1407 while (m && (len > 0)) {
1408 if (len >= m->m_len) {
1411 sb->sb_sndptroff += m->m_len;
1412 sb->sb_sndptr = m->m_next;
1422 * Return the first mbuf and the mbuf data offset for the provided
1423 * send offset without changing the "sb_sndptroff" field.
1426 sbsndmbuf(struct sockbuf *sb, u_int off, u_int *moff)
1430 KASSERT(sb->sb_mb != NULL, ("%s: sb_mb is NULL", __func__));
1433 * If the "off" is below the stored offset, which happens on
1434 * retransmits, just use "sb_mb":
1436 if (sb->sb_sndptr == NULL || sb->sb_sndptroff > off) {
1440 off -= sb->sb_sndptroff;
1442 while (off > 0 && m != NULL) {
1453 * Drop a record off the front of a sockbuf and move the next record to the
1457 sbdroprecord_locked(struct sockbuf *sb)
1461 SOCKBUF_LOCK_ASSERT(sb);
1465 sb->sb_mb = m->m_nextpkt;
1475 * Drop a record off the front of a sockbuf and move the next record to the
1479 sbdroprecord(struct sockbuf *sb)
1483 sbdroprecord_locked(sb);
1488 * Create a "control" mbuf containing the specified data with the specified
1489 * type for presentation on a socket buffer.
1492 sbcreatecontrol(caddr_t p, int size, int type, int level)
1497 if (CMSG_SPACE((u_int)size) > MCLBYTES)
1498 return ((struct mbuf *) NULL);
1499 if (CMSG_SPACE((u_int)size) > MLEN)
1500 m = m_getcl(M_NOWAIT, MT_CONTROL, 0);
1502 m = m_get(M_NOWAIT, MT_CONTROL);
1504 return ((struct mbuf *) NULL);
1505 cp = mtod(m, struct cmsghdr *);
1507 KASSERT(CMSG_SPACE((u_int)size) <= M_TRAILINGSPACE(m),
1508 ("sbcreatecontrol: short mbuf"));
1510 * Don't leave the padding between the msg header and the
1511 * cmsg data and the padding after the cmsg data un-initialized.
1513 bzero(cp, CMSG_SPACE((u_int)size));
1515 (void)memcpy(CMSG_DATA(cp), p, size);
1516 m->m_len = CMSG_SPACE(size);
1517 cp->cmsg_len = CMSG_LEN(size);
1518 cp->cmsg_level = level;
1519 cp->cmsg_type = type;
1524 * This does the same for socket buffers that sotoxsocket does for sockets:
1525 * generate an user-format data structure describing the socket buffer. Note
1526 * that the xsockbuf structure, since it is always embedded in a socket, does
1527 * not include a self pointer nor a length. We make this entry point public
1528 * in case some other mechanism needs it.
1531 sbtoxsockbuf(struct sockbuf *sb, struct xsockbuf *xsb)
1534 xsb->sb_cc = sb->sb_ccc;
1535 xsb->sb_hiwat = sb->sb_hiwat;
1536 xsb->sb_mbcnt = sb->sb_mbcnt;
1537 xsb->sb_mcnt = sb->sb_mcnt;
1538 xsb->sb_ccnt = sb->sb_ccnt;
1539 xsb->sb_mbmax = sb->sb_mbmax;
1540 xsb->sb_lowat = sb->sb_lowat;
1541 xsb->sb_flags = sb->sb_flags;
1542 xsb->sb_timeo = sb->sb_timeo;
1545 /* This takes the place of kern.maxsockbuf, which moved to kern.ipc. */
1547 SYSCTL_INT(_kern, KERN_DUMMY, dummy, CTLFLAG_RW | CTLFLAG_SKIP, &dummy, 0, "");
1548 SYSCTL_OID(_kern_ipc, KIPC_MAXSOCKBUF, maxsockbuf,
1549 CTLTYPE_ULONG | CTLFLAG_RW | CTLFLAG_NEEDGIANT, &sb_max, 0,
1550 sysctl_handle_sb_max, "LU",
1551 "Maximum socket buffer size");
1552 SYSCTL_ULONG(_kern_ipc, KIPC_SOCKBUF_WASTE, sockbuf_waste_factor, CTLFLAG_RW,
1553 &sb_efficiency, 0, "Socket buffer size waste factor");