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() */
74 static void sbcompress_ktls_rx(struct sockbuf *sb, struct mbuf *m,
77 static struct mbuf *sbcut_internal(struct sockbuf *sb, int len);
78 static void sbflush_internal(struct sockbuf *sb);
81 * Our own version of m_clrprotoflags(), that can preserve M_NOTREADY.
84 sbm_clrprotoflags(struct mbuf *m, int flags)
89 if (flags & PRUS_NOTREADY)
98 * Compress M_NOTREADY mbufs after they have been readied by sbready().
100 * sbcompress() skips M_NOTREADY mbufs since the data is not available to
101 * be copied at the time of sbcompress(). This function combines small
102 * mbufs similar to sbcompress() once mbufs are ready. 'm0' is the first
103 * mbuf sbready() marked ready, and 'end' is the first mbuf still not
107 sbready_compress(struct sockbuf *sb, struct mbuf *m0, struct mbuf *end)
112 SOCKBUF_LOCK_ASSERT(sb);
114 if ((sb->sb_flags & SB_NOCOALESCE) != 0)
117 for (m = m0; m != end; m = m->m_next) {
118 MPASS((m->m_flags & M_NOTREADY) == 0);
120 * NB: In sbcompress(), 'n' is the last mbuf in the
121 * socket buffer and 'm' is the new mbuf being copied
122 * into the trailing space of 'n'. Here, the roles
123 * are reversed and 'n' is the next mbuf after 'm'
124 * that is being copied into the trailing space of
129 /* Try to coalesce adjacent ktls mbuf hdr/trailers. */
130 if ((n != NULL) && (n != end) && (m->m_flags & M_EOR) == 0 &&
131 (m->m_flags & M_EXTPG) &&
132 (n->m_flags & M_EXTPG) &&
133 !mbuf_has_tls_session(m) &&
134 !mbuf_has_tls_session(n)) {
135 int hdr_len, trail_len;
137 hdr_len = n->m_epg_hdrlen;
138 trail_len = m->m_epg_trllen;
139 if (trail_len != 0 && hdr_len != 0 &&
140 trail_len + hdr_len <= MBUF_PEXT_TRAIL_LEN) {
141 /* copy n's header to m's trailer */
142 memcpy(&m->m_epg_trail[trail_len],
143 n->m_epg_hdr, hdr_len);
144 m->m_epg_trllen += hdr_len;
152 /* Compress small unmapped mbufs into plain mbufs. */
153 if ((m->m_flags & M_EXTPG) && m->m_len <= MLEN &&
154 !mbuf_has_tls_session(m)) {
155 ext_size = m->m_ext.ext_size;
156 if (mb_unmapped_compress(m) == 0) {
157 sb->sb_mbcnt -= ext_size;
162 while ((n != NULL) && (n != end) && (m->m_flags & M_EOR) == 0 &&
164 (m->m_flags & M_EXTPG) == 0 &&
165 !mbuf_has_tls_session(n) &&
166 !mbuf_has_tls_session(m) &&
167 n->m_len <= MCLBYTES / 4 && /* XXX: Don't copy too much */
168 n->m_len <= M_TRAILINGSPACE(m) &&
169 m->m_type == n->m_type) {
170 KASSERT(sb->sb_lastrecord != n,
171 ("%s: merging start of record (%p) into previous mbuf (%p)",
173 m_copydata(n, 0, n->m_len, mtodo(m, m->m_len));
174 m->m_len += n->m_len;
175 m->m_next = n->m_next;
176 m->m_flags |= n->m_flags & M_EOR;
177 if (sb->sb_mbtail == n)
180 sb->sb_mbcnt -= MSIZE;
182 if (n->m_flags & M_EXT) {
183 sb->sb_mbcnt -= n->m_ext.ext_size;
195 * Mark ready "count" units of I/O starting with "m". Most mbufs
196 * count as a single unit of I/O except for M_EXTPG mbufs which
197 * are backed by multiple pages.
200 sbready(struct sockbuf *sb, struct mbuf *m0, int count)
205 SOCKBUF_LOCK_ASSERT(sb);
206 KASSERT(sb->sb_fnrdy != NULL, ("%s: sb %p NULL fnrdy", __func__, sb));
207 KASSERT(count > 0, ("%s: invalid count %d", __func__, count));
210 blocker = (sb->sb_fnrdy == m) ? M_BLOCKED : 0;
213 KASSERT(m->m_flags & M_NOTREADY,
214 ("%s: m %p !M_NOTREADY", __func__, m));
215 if ((m->m_flags & M_EXTPG) != 0 && m->m_epg_npgs != 0) {
216 if (count < m->m_epg_nrdy) {
217 m->m_epg_nrdy -= count;
221 count -= m->m_epg_nrdy;
226 m->m_flags &= ~(M_NOTREADY | blocker);
228 sb->sb_acc += m->m_len;
233 * If the first mbuf is still not fully ready because only
234 * some of its backing pages were readied, no further progress
238 MPASS(m->m_flags & M_NOTREADY);
239 return (EINPROGRESS);
243 sbready_compress(sb, m0, m);
244 return (EINPROGRESS);
247 /* This one was blocking all the queue. */
248 for (; m && (m->m_flags & M_NOTREADY) == 0; m = m->m_next) {
249 KASSERT(m->m_flags & M_BLOCKED,
250 ("%s: m %p !M_BLOCKED", __func__, m));
251 m->m_flags &= ~M_BLOCKED;
252 sb->sb_acc += m->m_len;
256 sbready_compress(sb, m0, m);
262 * Adjust sockbuf state reflecting allocation of m.
265 sballoc(struct sockbuf *sb, struct mbuf *m)
268 SOCKBUF_LOCK_ASSERT(sb);
270 sb->sb_ccc += m->m_len;
272 if (sb->sb_fnrdy == NULL) {
273 if (m->m_flags & M_NOTREADY)
276 sb->sb_acc += m->m_len;
278 m->m_flags |= M_BLOCKED;
280 if (m->m_type != MT_DATA && m->m_type != MT_OOBDATA)
281 sb->sb_ctl += m->m_len;
283 sb->sb_mbcnt += MSIZE;
286 if (m->m_flags & M_EXT) {
287 sb->sb_mbcnt += m->m_ext.ext_size;
293 * Adjust sockbuf state reflecting freeing of m.
296 sbfree(struct sockbuf *sb, struct mbuf *m)
299 #if 0 /* XXX: not yet: soclose() call path comes here w/o lock. */
300 SOCKBUF_LOCK_ASSERT(sb);
303 sb->sb_ccc -= m->m_len;
305 if (!(m->m_flags & M_NOTAVAIL))
306 sb->sb_acc -= m->m_len;
308 if (m == sb->sb_fnrdy) {
311 KASSERT(m->m_flags & M_NOTREADY,
312 ("%s: m %p !M_NOTREADY", __func__, m));
315 while (n != NULL && !(n->m_flags & M_NOTREADY)) {
316 n->m_flags &= ~M_BLOCKED;
317 sb->sb_acc += n->m_len;
323 if (m->m_type != MT_DATA && m->m_type != MT_OOBDATA)
324 sb->sb_ctl -= m->m_len;
326 sb->sb_mbcnt -= MSIZE;
328 if (m->m_flags & M_EXT) {
329 sb->sb_mbcnt -= m->m_ext.ext_size;
333 if (sb->sb_sndptr == m) {
334 sb->sb_sndptr = NULL;
335 sb->sb_sndptroff = 0;
337 if (sb->sb_sndptroff != 0)
338 sb->sb_sndptroff -= m->m_len;
343 * Similar to sballoc/sbfree but does not adjust state associated with
344 * the sb_mb chain such as sb_fnrdy or sb_sndptr*. Also assumes mbufs
348 sballoc_ktls_rx(struct sockbuf *sb, struct mbuf *m)
351 SOCKBUF_LOCK_ASSERT(sb);
353 sb->sb_ccc += m->m_len;
354 sb->sb_tlscc += m->m_len;
356 sb->sb_mbcnt += MSIZE;
359 if (m->m_flags & M_EXT) {
360 sb->sb_mbcnt += m->m_ext.ext_size;
366 sbfree_ktls_rx(struct sockbuf *sb, struct mbuf *m)
369 #if 0 /* XXX: not yet: soclose() call path comes here w/o lock. */
370 SOCKBUF_LOCK_ASSERT(sb);
373 sb->sb_ccc -= m->m_len;
374 sb->sb_tlscc -= m->m_len;
376 sb->sb_mbcnt -= MSIZE;
379 if (m->m_flags & M_EXT) {
380 sb->sb_mbcnt -= m->m_ext.ext_size;
387 * Socantsendmore indicates that no more data will be sent on the socket; it
388 * would normally be applied to a socket when the user informs the system
389 * that no more data is to be sent, by the protocol code (in case
390 * PRU_SHUTDOWN). Socantrcvmore indicates that no more data will be
391 * received, and will normally be applied to the socket by a protocol when it
392 * detects that the peer will send no more data. Data queued for reading in
393 * the socket may yet be read.
396 socantsendmore_locked(struct socket *so)
399 SOCKBUF_LOCK_ASSERT(&so->so_snd);
401 so->so_snd.sb_state |= SBS_CANTSENDMORE;
402 sowwakeup_locked(so);
403 mtx_assert(SOCKBUF_MTX(&so->so_snd), MA_NOTOWNED);
407 socantsendmore(struct socket *so)
410 SOCKBUF_LOCK(&so->so_snd);
411 socantsendmore_locked(so);
412 mtx_assert(SOCKBUF_MTX(&so->so_snd), MA_NOTOWNED);
416 socantrcvmore_locked(struct socket *so)
419 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
421 so->so_rcv.sb_state |= SBS_CANTRCVMORE;
423 if (so->so_rcv.sb_flags & SB_TLS_RX)
424 ktls_check_rx(&so->so_rcv);
426 sorwakeup_locked(so);
427 mtx_assert(SOCKBUF_MTX(&so->so_rcv), MA_NOTOWNED);
431 socantrcvmore(struct socket *so)
434 SOCKBUF_LOCK(&so->so_rcv);
435 socantrcvmore_locked(so);
436 mtx_assert(SOCKBUF_MTX(&so->so_rcv), MA_NOTOWNED);
440 soroverflow_locked(struct socket *so)
443 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
445 if (so->so_options & SO_RERROR) {
446 so->so_rerror = ENOBUFS;
447 sorwakeup_locked(so);
449 SOCKBUF_UNLOCK(&so->so_rcv);
451 mtx_assert(SOCKBUF_MTX(&so->so_rcv), MA_NOTOWNED);
455 soroverflow(struct socket *so)
458 SOCKBUF_LOCK(&so->so_rcv);
459 soroverflow_locked(so);
460 mtx_assert(SOCKBUF_MTX(&so->so_rcv), MA_NOTOWNED);
464 * Wait for data to arrive at/drain from a socket buffer.
467 sbwait(struct sockbuf *sb)
470 SOCKBUF_LOCK_ASSERT(sb);
472 sb->sb_flags |= SB_WAIT;
473 return (msleep_sbt(&sb->sb_acc, SOCKBUF_MTX(sb),
474 (sb->sb_flags & SB_NOINTR) ? PSOCK : PSOCK | PCATCH, "sbwait",
475 sb->sb_timeo, 0, 0));
479 * Wakeup processes waiting on a socket buffer. Do asynchronous notification
480 * via SIGIO if the socket has the SS_ASYNC flag set.
482 * Called with the socket buffer lock held; will release the lock by the end
483 * of the function. This allows the caller to acquire the socket buffer lock
484 * while testing for the need for various sorts of wakeup and hold it through
485 * to the point where it's no longer required. We currently hold the lock
486 * through calls out to other subsystems (with the exception of kqueue), and
487 * then release it to avoid lock order issues. It's not clear that's
491 sowakeup(struct socket *so, struct sockbuf *sb)
495 SOCKBUF_LOCK_ASSERT(sb);
497 selwakeuppri(sb->sb_sel, PSOCK);
498 if (!SEL_WAITING(sb->sb_sel))
499 sb->sb_flags &= ~SB_SEL;
500 if (sb->sb_flags & SB_WAIT) {
501 sb->sb_flags &= ~SB_WAIT;
504 KNOTE_LOCKED(&sb->sb_sel->si_note, 0);
505 if (sb->sb_upcall != NULL) {
506 ret = sb->sb_upcall(so, sb->sb_upcallarg, M_NOWAIT);
507 if (ret == SU_ISCONNECTED) {
508 KASSERT(sb == &so->so_rcv,
509 ("SO_SND upcall returned SU_ISCONNECTED"));
510 soupcall_clear(so, SO_RCV);
514 if (sb->sb_flags & SB_AIO)
515 sowakeup_aio(so, sb);
517 if (ret == SU_ISCONNECTED)
519 if ((so->so_state & SS_ASYNC) && so->so_sigio != NULL)
520 pgsigio(&so->so_sigio, SIGIO, 0);
521 mtx_assert(SOCKBUF_MTX(sb), MA_NOTOWNED);
525 * Socket buffer (struct sockbuf) utility routines.
527 * Each socket contains two socket buffers: one for sending data and one for
528 * receiving data. Each buffer contains a queue of mbufs, information about
529 * the number of mbufs and amount of data in the queue, and other fields
530 * allowing select() statements and notification on data availability to be
533 * Data stored in a socket buffer is maintained as a list of records. Each
534 * record is a list of mbufs chained together with the m_next field. Records
535 * are chained together with the m_nextpkt field. The upper level routine
536 * soreceive() expects the following conventions to be observed when placing
537 * information in the receive buffer:
539 * 1. If the protocol requires each message be preceded by the sender's name,
540 * then a record containing that name must be present before any
541 * associated data (mbuf's must be of type MT_SONAME).
542 * 2. If the protocol supports the exchange of ``access rights'' (really just
543 * additional data associated with the message), and there are ``rights''
544 * to be received, then a record containing this data should be present
545 * (mbuf's must be of type MT_RIGHTS).
546 * 3. If a name or rights record exists, then it must be followed by a data
547 * record, perhaps of zero length.
549 * Before using a new socket structure it is first necessary to reserve
550 * buffer space to the socket, by calling sbreserve(). This should commit
551 * some of the available buffer space in the system buffer pool for the
552 * socket (currently, it does nothing but enforce limits). The space should
553 * be released by calling sbrelease() when the socket is destroyed.
556 soreserve(struct socket *so, u_long sndcc, u_long rcvcc)
558 struct thread *td = curthread;
560 SOCKBUF_LOCK(&so->so_snd);
561 SOCKBUF_LOCK(&so->so_rcv);
562 if (sbreserve_locked(&so->so_snd, sndcc, so, td) == 0)
564 if (sbreserve_locked(&so->so_rcv, rcvcc, so, td) == 0)
566 if (so->so_rcv.sb_lowat == 0)
567 so->so_rcv.sb_lowat = 1;
568 if (so->so_snd.sb_lowat == 0)
569 so->so_snd.sb_lowat = MCLBYTES;
570 if (so->so_snd.sb_lowat > so->so_snd.sb_hiwat)
571 so->so_snd.sb_lowat = so->so_snd.sb_hiwat;
572 SOCKBUF_UNLOCK(&so->so_rcv);
573 SOCKBUF_UNLOCK(&so->so_snd);
576 sbrelease_locked(&so->so_snd, so);
578 SOCKBUF_UNLOCK(&so->so_rcv);
579 SOCKBUF_UNLOCK(&so->so_snd);
584 sysctl_handle_sb_max(SYSCTL_HANDLER_ARGS)
587 u_long tmp_sb_max = sb_max;
589 error = sysctl_handle_long(oidp, &tmp_sb_max, arg2, req);
590 if (error || !req->newptr)
592 if (tmp_sb_max < MSIZE + MCLBYTES)
595 sb_max_adj = (u_quad_t)sb_max * MCLBYTES / (MSIZE + MCLBYTES);
600 * Allot mbufs to a sockbuf. Attempt to scale mbmax so that mbcnt doesn't
601 * become limiting if buffering efficiency is near the normal case.
604 sbreserve_locked(struct sockbuf *sb, u_long cc, struct socket *so,
609 SOCKBUF_LOCK_ASSERT(sb);
612 * When a thread is passed, we take into account the thread's socket
613 * buffer size limit. The caller will generally pass curthread, but
614 * in the TCP input path, NULL will be passed to indicate that no
615 * appropriate thread resource limits are available. In that case,
616 * we don't apply a process limit.
621 sbsize_limit = lim_cur(td, RLIMIT_SBSIZE);
623 sbsize_limit = RLIM_INFINITY;
624 if (!chgsbsize(so->so_cred->cr_uidinfo, &sb->sb_hiwat, cc,
627 sb->sb_mbmax = min(cc * sb_efficiency, sb_max);
628 if (sb->sb_lowat > sb->sb_hiwat)
629 sb->sb_lowat = sb->sb_hiwat;
634 sbsetopt(struct socket *so, int cmd, u_long cc)
638 u_int *hiwat, *lowat;
643 if (SOLISTENING(so)) {
647 lowat = &so->sol_sbsnd_lowat;
648 hiwat = &so->sol_sbsnd_hiwat;
649 flags = &so->sol_sbsnd_flags;
653 lowat = &so->sol_sbrcv_lowat;
654 hiwat = &so->sol_sbrcv_hiwat;
655 flags = &so->sol_sbrcv_flags;
669 flags = &sb->sb_flags;
670 hiwat = &sb->sb_hiwat;
671 lowat = &sb->sb_lowat;
679 if (SOLISTENING(so)) {
680 if (cc > sb_max_adj) {
688 if (!sbreserve_locked(sb, cc, so, curthread))
692 *flags &= ~SB_AUTOSIZE;
697 * Make sure the low-water is never greater than the
700 *lowat = (cc > *hiwat) ? *hiwat : cc;
704 if (!SOLISTENING(so))
711 * Free mbufs held by a socket, and reserved mbuf space.
714 sbrelease_internal(struct sockbuf *sb, struct socket *so)
717 sbflush_internal(sb);
718 (void)chgsbsize(so->so_cred->cr_uidinfo, &sb->sb_hiwat, 0,
724 sbrelease_locked(struct sockbuf *sb, struct socket *so)
727 SOCKBUF_LOCK_ASSERT(sb);
729 sbrelease_internal(sb, so);
733 sbrelease(struct sockbuf *sb, struct socket *so)
737 sbrelease_locked(sb, so);
742 sbdestroy(struct sockbuf *sb, struct socket *so)
745 sbrelease_internal(sb, so);
747 if (sb->sb_tls_info != NULL)
748 ktls_free(sb->sb_tls_info);
749 sb->sb_tls_info = NULL;
754 * Routines to add and remove data from an mbuf queue.
756 * The routines sbappend() or sbappendrecord() are normally called to append
757 * new mbufs to a socket buffer, after checking that adequate space is
758 * available, comparing the function sbspace() with the amount of data to be
759 * added. sbappendrecord() differs from sbappend() in that data supplied is
760 * treated as the beginning of a new record. To place a sender's address,
761 * optional access rights, and data in a socket receive buffer,
762 * sbappendaddr() should be used. To place access rights and data in a
763 * socket receive buffer, sbappendrights() should be used. In either case,
764 * the new data begins a new record. Note that unlike sbappend() and
765 * sbappendrecord(), these routines check for the caller that there will be
766 * enough space to store the data. Each fails if there is not enough space,
767 * or if it cannot find mbufs to store additional information in.
769 * Reliable protocols may use the socket send buffer to hold data awaiting
770 * acknowledgement. Data is normally copied from a socket send buffer in a
771 * protocol with m_copy for output to a peer, and then removing the data from
772 * the socket buffer with sbdrop() or sbdroprecord() when the data is
773 * acknowledged by the peer.
777 sblastrecordchk(struct sockbuf *sb, const char *file, int line)
779 struct mbuf *m = sb->sb_mb;
781 SOCKBUF_LOCK_ASSERT(sb);
783 while (m && m->m_nextpkt)
786 if (m != sb->sb_lastrecord) {
787 printf("%s: sb_mb %p sb_lastrecord %p last %p\n",
788 __func__, sb->sb_mb, sb->sb_lastrecord, m);
789 printf("packet chain:\n");
790 for (m = sb->sb_mb; m != NULL; m = m->m_nextpkt)
792 panic("%s from %s:%u", __func__, file, line);
797 sblastmbufchk(struct sockbuf *sb, const char *file, int line)
799 struct mbuf *m = sb->sb_mb;
802 SOCKBUF_LOCK_ASSERT(sb);
804 while (m && m->m_nextpkt)
807 while (m && m->m_next)
810 if (m != sb->sb_mbtail) {
811 printf("%s: sb_mb %p sb_mbtail %p last %p\n",
812 __func__, sb->sb_mb, sb->sb_mbtail, m);
813 printf("packet tree:\n");
814 for (m = sb->sb_mb; m != NULL; m = m->m_nextpkt) {
816 for (n = m; n != NULL; n = n->m_next)
820 panic("%s from %s:%u", __func__, file, line);
825 while (m && m->m_next)
828 if (m != sb->sb_mtlstail) {
829 printf("%s: sb_mtls %p sb_mtlstail %p last %p\n",
830 __func__, sb->sb_mtls, sb->sb_mtlstail, m);
831 printf("TLS packet tree:\n");
833 for (m = sb->sb_mtls; m != NULL; m = m->m_next) {
837 panic("%s from %s:%u", __func__, file, line);
841 #endif /* SOCKBUF_DEBUG */
843 #define SBLINKRECORD(sb, m0) do { \
844 SOCKBUF_LOCK_ASSERT(sb); \
845 if ((sb)->sb_lastrecord != NULL) \
846 (sb)->sb_lastrecord->m_nextpkt = (m0); \
848 (sb)->sb_mb = (m0); \
849 (sb)->sb_lastrecord = (m0); \
850 } while (/*CONSTCOND*/0)
853 * Append mbuf chain m to the last record in the socket buffer sb. The
854 * additional space associated the mbuf chain is recorded in sb. Empty mbufs
855 * are discarded and mbufs are compacted where possible.
858 sbappend_locked(struct sockbuf *sb, struct mbuf *m, int flags)
862 SOCKBUF_LOCK_ASSERT(sb);
866 sbm_clrprotoflags(m, flags);
873 if (n->m_flags & M_EOR) {
874 sbappendrecord_locked(sb, m); /* XXXXXX!!!! */
877 } while (n->m_next && (n = n->m_next));
880 * XXX Would like to simply use sb_mbtail here, but
881 * XXX I need to verify that I won't miss an EOR that
884 if ((n = sb->sb_lastrecord) != NULL) {
886 if (n->m_flags & M_EOR) {
887 sbappendrecord_locked(sb, m); /* XXXXXX!!!! */
890 } while (n->m_next && (n = n->m_next));
893 * If this is the first record in the socket buffer,
894 * it's also the last record.
896 sb->sb_lastrecord = m;
899 sbcompress(sb, m, n);
904 * Append mbuf chain m to the last record in the socket buffer sb. The
905 * additional space associated the mbuf chain is recorded in sb. Empty mbufs
906 * are discarded and mbufs are compacted where possible.
909 sbappend(struct sockbuf *sb, struct mbuf *m, int flags)
913 sbappend_locked(sb, m, flags);
919 * Append an mbuf containing encrypted TLS data. The data
920 * is marked M_NOTREADY until it has been decrypted and
921 * stored as a TLS record.
924 sbappend_ktls_rx(struct sockbuf *sb, struct mbuf *m)
930 /* Remove all packet headers and mbuf tags to get a pure data chain. */
933 for (n = m; n != NULL; n = n->m_next)
934 n->m_flags |= M_NOTREADY;
935 sbcompress_ktls_rx(sb, m, sb->sb_mtlstail);
941 * This version of sbappend() should only be used when the caller absolutely
942 * knows that there will never be more than one record in the socket buffer,
943 * that is, a stream protocol (such as TCP).
946 sbappendstream_locked(struct sockbuf *sb, struct mbuf *m, int flags)
948 SOCKBUF_LOCK_ASSERT(sb);
950 KASSERT(m->m_nextpkt == NULL,("sbappendstream 0"));
954 * Decrypted TLS records are appended as records via
955 * sbappendrecord(). TCP passes encrypted TLS records to this
956 * function which must be scheduled for decryption.
958 if (sb->sb_flags & SB_TLS_RX) {
959 sbappend_ktls_rx(sb, m);
964 KASSERT(sb->sb_mb == sb->sb_lastrecord,("sbappendstream 1"));
969 if (sb->sb_tls_info != NULL)
973 /* Remove all packet headers and mbuf tags to get a pure data chain. */
974 m_demote(m, 1, flags & PRUS_NOTREADY ? M_NOTREADY : 0);
976 sbcompress(sb, m, sb->sb_mbtail);
978 sb->sb_lastrecord = sb->sb_mb;
983 * This version of sbappend() should only be used when the caller absolutely
984 * knows that there will never be more than one record in the socket buffer,
985 * that is, a stream protocol (such as TCP).
988 sbappendstream(struct sockbuf *sb, struct mbuf *m, int flags)
992 sbappendstream_locked(sb, m, flags);
998 sbcheck(struct sockbuf *sb, const char *file, int line)
1000 struct mbuf *m, *n, *fnrdy;
1001 u_long acc, ccc, mbcnt;
1006 SOCKBUF_LOCK_ASSERT(sb);
1008 acc = ccc = mbcnt = 0;
1011 for (m = sb->sb_mb; m; m = n) {
1013 for (; m; m = m->m_next) {
1014 if (m->m_len == 0) {
1015 printf("sb %p empty mbuf %p\n", sb, m);
1018 if ((m->m_flags & M_NOTREADY) && fnrdy == NULL) {
1019 if (m != sb->sb_fnrdy) {
1020 printf("sb %p: fnrdy %p != m %p\n",
1021 sb, sb->sb_fnrdy, m);
1027 if (!(m->m_flags & M_NOTAVAIL)) {
1028 printf("sb %p: fnrdy %p, m %p is avail\n",
1029 sb, sb->sb_fnrdy, m);
1036 if (m->m_flags & M_EXT) /*XXX*/ /* pretty sure this is bogus */
1037 mbcnt += m->m_ext.ext_size;
1042 * Account for mbufs "detached" by ktls_detach_record() while
1043 * they are decrypted by ktls_decrypt(). tlsdcc gives a count
1044 * of the detached bytes that are included in ccc. The mbufs
1045 * and clusters are not included in the socket buffer
1048 ccc += sb->sb_tlsdcc;
1051 for (m = sb->sb_mtls; m; m = m->m_next) {
1052 if (m->m_nextpkt != NULL) {
1053 printf("sb %p TLS mbuf %p with nextpkt\n", sb, m);
1056 if ((m->m_flags & M_NOTREADY) == 0) {
1057 printf("sb %p TLS mbuf %p ready\n", sb, m);
1063 if (m->m_flags & M_EXT) /*XXX*/ /* pretty sure this is bogus */
1064 mbcnt += m->m_ext.ext_size;
1067 if (sb->sb_tlscc != tlscc) {
1068 printf("tlscc %ld/%u dcc %u\n", tlscc, sb->sb_tlscc,
1073 if (acc != sb->sb_acc || ccc != sb->sb_ccc || mbcnt != sb->sb_mbcnt) {
1074 printf("acc %ld/%u ccc %ld/%u mbcnt %ld/%u\n",
1075 acc, sb->sb_acc, ccc, sb->sb_ccc, mbcnt, sb->sb_mbcnt);
1077 printf("tlscc %ld/%u dcc %u\n", tlscc, sb->sb_tlscc,
1084 panic("%s from %s:%u", __func__, file, line);
1089 * As above, except the mbuf chain begins a new record.
1092 sbappendrecord_locked(struct sockbuf *sb, struct mbuf *m0)
1096 SOCKBUF_LOCK_ASSERT(sb);
1100 m_clrprotoflags(m0);
1102 * Put the first mbuf on the queue. Note this permits zero length
1106 SBLASTRECORDCHK(sb);
1107 SBLINKRECORD(sb, m0);
1111 if (m && (m0->m_flags & M_EOR)) {
1112 m0->m_flags &= ~M_EOR;
1113 m->m_flags |= M_EOR;
1115 /* always call sbcompress() so it can do SBLASTMBUFCHK() */
1116 sbcompress(sb, m, m0);
1120 * As above, except the mbuf chain begins a new record.
1123 sbappendrecord(struct sockbuf *sb, struct mbuf *m0)
1127 sbappendrecord_locked(sb, m0);
1131 /* Helper routine that appends data, control, and address to a sockbuf. */
1133 sbappendaddr_locked_internal(struct sockbuf *sb, const struct sockaddr *asa,
1134 struct mbuf *m0, struct mbuf *control, struct mbuf *ctrl_last)
1136 struct mbuf *m, *n, *nlast;
1138 if (asa->sa_len > MLEN)
1141 m = m_get(M_NOWAIT, MT_SONAME);
1144 m->m_len = asa->sa_len;
1145 bcopy(asa, mtod(m, caddr_t), asa->sa_len);
1147 m_clrprotoflags(m0);
1148 m_tag_delete_chain(m0, NULL);
1150 * Clear some persistent info from pkthdr.
1151 * We don't use m_demote(), because some netgraph consumers
1152 * expect M_PKTHDR presence.
1154 m0->m_pkthdr.rcvif = NULL;
1155 m0->m_pkthdr.flowid = 0;
1156 m0->m_pkthdr.csum_flags = 0;
1157 m0->m_pkthdr.fibnum = 0;
1158 m0->m_pkthdr.rsstype = 0;
1161 ctrl_last->m_next = m0; /* concatenate data to control */
1164 m->m_next = control;
1165 for (n = m; n->m_next != NULL; n = n->m_next)
1169 SBLINKRECORD(sb, m);
1171 sb->sb_mbtail = nlast;
1174 SBLASTRECORDCHK(sb);
1179 * Append address and data, and optionally, control (ancillary) data to the
1180 * receive queue of a socket. If present, m0 must include a packet header
1181 * with total length. Returns 0 if no space in sockbuf or insufficient
1185 sbappendaddr_locked(struct sockbuf *sb, const struct sockaddr *asa,
1186 struct mbuf *m0, struct mbuf *control)
1188 struct mbuf *ctrl_last;
1189 int space = asa->sa_len;
1191 SOCKBUF_LOCK_ASSERT(sb);
1193 if (m0 && (m0->m_flags & M_PKTHDR) == 0)
1194 panic("sbappendaddr_locked");
1196 space += m0->m_pkthdr.len;
1197 space += m_length(control, &ctrl_last);
1199 if (space > sbspace(sb))
1201 return (sbappendaddr_locked_internal(sb, asa, m0, control, ctrl_last));
1205 * Append address and data, and optionally, control (ancillary) data to the
1206 * receive queue of a socket. If present, m0 must include a packet header
1207 * with total length. Returns 0 if insufficient mbufs. Does not validate space
1208 * on the receiving sockbuf.
1211 sbappendaddr_nospacecheck_locked(struct sockbuf *sb, const struct sockaddr *asa,
1212 struct mbuf *m0, struct mbuf *control)
1214 struct mbuf *ctrl_last;
1216 SOCKBUF_LOCK_ASSERT(sb);
1218 ctrl_last = (control == NULL) ? NULL : m_last(control);
1219 return (sbappendaddr_locked_internal(sb, asa, m0, control, ctrl_last));
1223 * Append address and data, and optionally, control (ancillary) data to the
1224 * receive queue of a socket. If present, m0 must include a packet header
1225 * with total length. Returns 0 if no space in sockbuf or insufficient
1229 sbappendaddr(struct sockbuf *sb, const struct sockaddr *asa,
1230 struct mbuf *m0, struct mbuf *control)
1235 retval = sbappendaddr_locked(sb, asa, m0, control);
1241 sbappendcontrol_locked(struct sockbuf *sb, struct mbuf *m0,
1242 struct mbuf *control, int flags)
1244 struct mbuf *m, *mlast;
1246 sbm_clrprotoflags(m0, flags);
1247 m_last(control)->m_next = m0;
1249 SBLASTRECORDCHK(sb);
1251 for (m = control; m->m_next; m = m->m_next)
1255 SBLINKRECORD(sb, control);
1257 sb->sb_mbtail = mlast;
1260 SBLASTRECORDCHK(sb);
1264 sbappendcontrol(struct sockbuf *sb, struct mbuf *m0, struct mbuf *control,
1269 sbappendcontrol_locked(sb, m0, control, flags);
1274 * Append the data in mbuf chain (m) into the socket buffer sb following mbuf
1275 * (n). If (n) is NULL, the buffer is presumed empty.
1277 * When the data is compressed, mbufs in the chain may be handled in one of
1280 * (1) The mbuf may simply be dropped, if it contributes nothing (no data, no
1281 * record boundary, and no change in data type).
1283 * (2) The mbuf may be coalesced -- i.e., data in the mbuf may be copied into
1284 * an mbuf already in the socket buffer. This can occur if an
1285 * appropriate mbuf exists, there is room, both mbufs are not marked as
1286 * not ready, and no merging of data types will occur.
1288 * (3) The mbuf may be appended to the end of the existing mbuf chain.
1290 * If any of the new mbufs is marked as M_EOR, mark the last mbuf appended as
1294 sbcompress(struct sockbuf *sb, struct mbuf *m, struct mbuf *n)
1299 SOCKBUF_LOCK_ASSERT(sb);
1302 eor |= m->m_flags & M_EOR;
1303 if (m->m_len == 0 &&
1305 (((o = m->m_next) || (o = n)) &&
1306 o->m_type == m->m_type))) {
1307 if (sb->sb_lastrecord == m)
1308 sb->sb_lastrecord = m->m_next;
1312 if (n && (n->m_flags & M_EOR) == 0 &&
1314 ((sb->sb_flags & SB_NOCOALESCE) == 0) &&
1315 !(m->m_flags & M_NOTREADY) &&
1316 !(n->m_flags & (M_NOTREADY | M_EXTPG)) &&
1317 !mbuf_has_tls_session(m) &&
1318 !mbuf_has_tls_session(n) &&
1319 m->m_len <= MCLBYTES / 4 && /* XXX: Don't copy too much */
1320 m->m_len <= M_TRAILINGSPACE(n) &&
1321 n->m_type == m->m_type) {
1322 m_copydata(m, 0, m->m_len, mtodo(n, n->m_len));
1323 n->m_len += m->m_len;
1324 sb->sb_ccc += m->m_len;
1325 if (sb->sb_fnrdy == NULL)
1326 sb->sb_acc += m->m_len;
1327 if (m->m_type != MT_DATA && m->m_type != MT_OOBDATA)
1328 /* XXX: Probably don't need.*/
1329 sb->sb_ctl += m->m_len;
1333 if (m->m_len <= MLEN && (m->m_flags & M_EXTPG) &&
1334 (m->m_flags & M_NOTREADY) == 0 &&
1335 !mbuf_has_tls_session(m))
1336 (void)mb_unmapped_compress(m);
1344 m->m_flags &= ~M_EOR;
1349 KASSERT(n != NULL, ("sbcompress: eor && n == NULL"));
1357 * A version of sbcompress() for encrypted TLS RX mbufs. These mbufs
1358 * are appended to the 'sb_mtls' chain instead of 'sb_mb' and are also
1359 * a bit simpler (no EOR markers, always MT_DATA, etc.).
1362 sbcompress_ktls_rx(struct sockbuf *sb, struct mbuf *m, struct mbuf *n)
1365 SOCKBUF_LOCK_ASSERT(sb);
1368 KASSERT((m->m_flags & M_EOR) == 0,
1369 ("TLS RX mbuf %p with EOR", m));
1370 KASSERT(m->m_type == MT_DATA,
1371 ("TLS RX mbuf %p is not MT_DATA", m));
1372 KASSERT((m->m_flags & M_NOTREADY) != 0,
1373 ("TLS RX mbuf %p ready", m));
1374 KASSERT((m->m_flags & M_EXTPG) == 0,
1375 ("TLS RX mbuf %p unmapped", m));
1377 if (m->m_len == 0) {
1383 * Even though both 'n' and 'm' are NOTREADY, it's ok
1384 * to coalesce the data.
1388 ((sb->sb_flags & SB_NOCOALESCE) == 0) &&
1389 !(n->m_flags & (M_EXTPG)) &&
1390 m->m_len <= MCLBYTES / 4 && /* XXX: Don't copy too much */
1391 m->m_len <= M_TRAILINGSPACE(n)) {
1392 m_copydata(m, 0, m->m_len, mtodo(n, n->m_len));
1393 n->m_len += m->m_len;
1394 sb->sb_ccc += m->m_len;
1395 sb->sb_tlscc += m->m_len;
1403 sb->sb_mtlstail = m;
1404 sballoc_ktls_rx(sb, m);
1414 * Free all mbufs in a sockbuf. Check that all resources are reclaimed.
1417 sbflush_internal(struct sockbuf *sb)
1420 while (sb->sb_mbcnt || sb->sb_tlsdcc) {
1422 * Don't call sbcut(sb, 0) if the leading mbuf is non-empty:
1423 * we would loop forever. Panic instead.
1425 if (sb->sb_ccc == 0 && (sb->sb_mb == NULL || sb->sb_mb->m_len))
1427 m_freem(sbcut_internal(sb, (int)sb->sb_ccc));
1429 KASSERT(sb->sb_ccc == 0 && sb->sb_mb == 0 && sb->sb_mbcnt == 0,
1430 ("%s: ccc %u mb %p mbcnt %u", __func__,
1431 sb->sb_ccc, (void *)sb->sb_mb, sb->sb_mbcnt));
1435 sbflush_locked(struct sockbuf *sb)
1438 SOCKBUF_LOCK_ASSERT(sb);
1439 sbflush_internal(sb);
1443 sbflush(struct sockbuf *sb)
1452 * Cut data from (the front of) a sockbuf.
1454 static struct mbuf *
1455 sbcut_internal(struct sockbuf *sb, int len)
1457 struct mbuf *m, *next, *mfree;
1460 KASSERT(len >= 0, ("%s: len is %d but it is supposed to be >= 0",
1462 KASSERT(len <= sb->sb_ccc, ("%s: len: %d is > ccc: %u",
1463 __func__, len, sb->sb_ccc));
1465 next = (m = sb->sb_mb) ? m->m_nextpkt : 0;
1472 if (next == NULL && !is_tls) {
1473 if (sb->sb_tlsdcc != 0) {
1474 MPASS(len >= sb->sb_tlsdcc);
1475 len -= sb->sb_tlsdcc;
1476 sb->sb_ccc -= sb->sb_tlsdcc;
1485 KASSERT(next, ("%s: no next, len %d", __func__, len));
1487 next = m->m_nextpkt;
1489 if (m->m_len > len) {
1490 KASSERT(!(m->m_flags & M_NOTAVAIL),
1491 ("%s: m %p M_NOTAVAIL", __func__, m));
1496 if (sb->sb_sndptroff != 0)
1497 sb->sb_sndptroff -= len;
1498 if (m->m_type != MT_DATA && m->m_type != MT_OOBDATA)
1505 sbfree_ktls_rx(sb, m);
1510 * Do not put M_NOTREADY buffers to the free list, they
1511 * are referenced from outside.
1513 if (m->m_flags & M_NOTREADY && !is_tls)
1525 * Free any zero-length mbufs from the buffer.
1526 * For SOCK_DGRAM sockets such mbufs represent empty records.
1527 * XXX: For SOCK_STREAM sockets such mbufs can appear in the buffer,
1528 * when sosend_generic() needs to send only control data.
1530 while (m && m->m_len == 0) {
1544 sb->sb_mtlstail = NULL;
1549 m->m_nextpkt = next;
1553 * First part is an inline SB_EMPTY_FIXUP(). Second part makes sure
1554 * sb_lastrecord is up-to-date if we dropped part of the last record.
1558 sb->sb_mbtail = NULL;
1559 sb->sb_lastrecord = NULL;
1560 } else if (m->m_nextpkt == NULL) {
1561 sb->sb_lastrecord = m;
1568 * Drop data from (the front of) a sockbuf.
1571 sbdrop_locked(struct sockbuf *sb, int len)
1574 SOCKBUF_LOCK_ASSERT(sb);
1575 m_freem(sbcut_internal(sb, len));
1579 * Drop data from (the front of) a sockbuf,
1580 * and return it to caller.
1583 sbcut_locked(struct sockbuf *sb, int len)
1586 SOCKBUF_LOCK_ASSERT(sb);
1587 return (sbcut_internal(sb, len));
1591 sbdrop(struct sockbuf *sb, int len)
1596 mfree = sbcut_internal(sb, len);
1603 sbsndptr_noadv(struct sockbuf *sb, uint32_t off, uint32_t *moff)
1607 KASSERT(sb->sb_mb != NULL, ("%s: sb_mb is NULL", __func__));
1608 if (sb->sb_sndptr == NULL || sb->sb_sndptroff > off) {
1610 if (sb->sb_sndptr == NULL) {
1611 sb->sb_sndptr = sb->sb_mb;
1612 sb->sb_sndptroff = 0;
1617 off -= sb->sb_sndptroff;
1624 sbsndptr_adv(struct sockbuf *sb, struct mbuf *mb, uint32_t len)
1627 * A small copy was done, advance forward the sb_sbsndptr to cover
1632 if (mb != sb->sb_sndptr) {
1633 /* Did not copyout at the same mbuf */
1637 while (m && (len > 0)) {
1638 if (len >= m->m_len) {
1641 sb->sb_sndptroff += m->m_len;
1642 sb->sb_sndptr = m->m_next;
1652 * Return the first mbuf and the mbuf data offset for the provided
1653 * send offset without changing the "sb_sndptroff" field.
1656 sbsndmbuf(struct sockbuf *sb, u_int off, u_int *moff)
1660 KASSERT(sb->sb_mb != NULL, ("%s: sb_mb is NULL", __func__));
1663 * If the "off" is below the stored offset, which happens on
1664 * retransmits, just use "sb_mb":
1666 if (sb->sb_sndptr == NULL || sb->sb_sndptroff > off) {
1670 off -= sb->sb_sndptroff;
1672 while (off > 0 && m != NULL) {
1683 * Drop a record off the front of a sockbuf and move the next record to the
1687 sbdroprecord_locked(struct sockbuf *sb)
1691 SOCKBUF_LOCK_ASSERT(sb);
1695 sb->sb_mb = m->m_nextpkt;
1705 * Drop a record off the front of a sockbuf and move the next record to the
1709 sbdroprecord(struct sockbuf *sb)
1713 sbdroprecord_locked(sb);
1718 * Create a "control" mbuf containing the specified data with the specified
1719 * type for presentation on a socket buffer.
1722 sbcreatecontrol_how(void *p, int size, int type, int level, int wait)
1727 MBUF_CHECKSLEEP(wait);
1728 if (CMSG_SPACE((u_int)size) > MCLBYTES)
1729 return ((struct mbuf *) NULL);
1730 if (CMSG_SPACE((u_int)size) > MLEN)
1731 m = m_getcl(wait, MT_CONTROL, 0);
1733 m = m_get(wait, MT_CONTROL);
1735 return ((struct mbuf *) NULL);
1736 cp = mtod(m, struct cmsghdr *);
1738 KASSERT(CMSG_SPACE((u_int)size) <= M_TRAILINGSPACE(m),
1739 ("sbcreatecontrol: short mbuf"));
1741 * Don't leave the padding between the msg header and the
1742 * cmsg data and the padding after the cmsg data un-initialized.
1744 bzero(cp, CMSG_SPACE((u_int)size));
1746 (void)memcpy(CMSG_DATA(cp), p, size);
1747 m->m_len = CMSG_SPACE(size);
1748 cp->cmsg_len = CMSG_LEN(size);
1749 cp->cmsg_level = level;
1750 cp->cmsg_type = type;
1755 sbcreatecontrol(caddr_t p, int size, int type, int level)
1758 return (sbcreatecontrol_how(p, size, type, level, M_NOWAIT));
1762 * This does the same for socket buffers that sotoxsocket does for sockets:
1763 * generate an user-format data structure describing the socket buffer. Note
1764 * that the xsockbuf structure, since it is always embedded in a socket, does
1765 * not include a self pointer nor a length. We make this entry point public
1766 * in case some other mechanism needs it.
1769 sbtoxsockbuf(struct sockbuf *sb, struct xsockbuf *xsb)
1772 xsb->sb_cc = sb->sb_ccc;
1773 xsb->sb_hiwat = sb->sb_hiwat;
1774 xsb->sb_mbcnt = sb->sb_mbcnt;
1775 xsb->sb_mcnt = sb->sb_mcnt;
1776 xsb->sb_ccnt = sb->sb_ccnt;
1777 xsb->sb_mbmax = sb->sb_mbmax;
1778 xsb->sb_lowat = sb->sb_lowat;
1779 xsb->sb_flags = sb->sb_flags;
1780 xsb->sb_timeo = sb->sb_timeo;
1783 /* This takes the place of kern.maxsockbuf, which moved to kern.ipc. */
1785 SYSCTL_INT(_kern, KERN_DUMMY, dummy, CTLFLAG_RW | CTLFLAG_SKIP, &dummy, 0, "");
1786 SYSCTL_OID(_kern_ipc, KIPC_MAXSOCKBUF, maxsockbuf,
1787 CTLTYPE_ULONG | CTLFLAG_RW | CTLFLAG_MPSAFE, &sb_max, 0,
1788 sysctl_handle_sb_max, "LU",
1789 "Maximum socket buffer size");
1790 SYSCTL_ULONG(_kern_ipc, KIPC_SOCKBUF_WASTE, sockbuf_waste_factor, CTLFLAG_RW,
1791 &sb_efficiency, 0, "Socket buffer size waste factor");