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_NOMAP) &&
128 (n->m_flags & M_NOMAP) &&
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_NOMAP) && m->m_len <= MLEN &&
150 !mbuf_has_tls_session(m)) {
151 MPASS(m->m_flags & M_EXT);
152 ext_size = m->m_ext.ext_size;
153 if (mb_unmapped_compress(m) == 0) {
154 sb->sb_mbcnt -= ext_size;
159 while ((n != NULL) && (n != end) && (m->m_flags & M_EOR) == 0 &&
161 (m->m_flags & M_NOMAP) == 0 &&
162 !mbuf_has_tls_session(n) &&
163 !mbuf_has_tls_session(m) &&
164 n->m_len <= MCLBYTES / 4 && /* XXX: Don't copy too much */
165 n->m_len <= M_TRAILINGSPACE(m) &&
166 m->m_type == n->m_type) {
167 KASSERT(sb->sb_lastrecord != n,
168 ("%s: merging start of record (%p) into previous mbuf (%p)",
170 m_copydata(n, 0, n->m_len, mtodo(m, m->m_len));
171 m->m_len += n->m_len;
172 m->m_next = n->m_next;
173 m->m_flags |= n->m_flags & M_EOR;
174 if (sb->sb_mbtail == n)
177 sb->sb_mbcnt -= MSIZE;
179 if (n->m_flags & M_EXT) {
180 sb->sb_mbcnt -= n->m_ext.ext_size;
192 * Mark ready "count" units of I/O starting with "m". Most mbufs
193 * count as a single unit of I/O except for EXT_PGS-backed mbufs which
194 * can be backed by multiple pages.
197 sbready(struct sockbuf *sb, struct mbuf *m0, int count)
202 SOCKBUF_LOCK_ASSERT(sb);
203 KASSERT(sb->sb_fnrdy != NULL, ("%s: sb %p NULL fnrdy", __func__, sb));
204 KASSERT(count > 0, ("%s: invalid count %d", __func__, count));
207 blocker = (sb->sb_fnrdy == m) ? M_BLOCKED : 0;
210 KASSERT(m->m_flags & M_NOTREADY,
211 ("%s: m %p !M_NOTREADY", __func__, m));
212 if ((m->m_flags & M_EXT) != 0 &&
213 m->m_ext.ext_type == EXT_PGS) {
214 if (count < m->m_epg_nrdy) {
215 m->m_epg_nrdy -= count;
219 count -= m->m_epg_nrdy;
224 m->m_flags &= ~(M_NOTREADY | blocker);
226 sb->sb_acc += m->m_len;
231 * If the first mbuf is still not fully ready because only
232 * some of its backing pages were readied, no further progress
236 MPASS(m->m_flags & M_NOTREADY);
237 return (EINPROGRESS);
241 sbready_compress(sb, m0, m);
242 return (EINPROGRESS);
245 /* This one was blocking all the queue. */
246 for (; m && (m->m_flags & M_NOTREADY) == 0; m = m->m_next) {
247 KASSERT(m->m_flags & M_BLOCKED,
248 ("%s: m %p !M_BLOCKED", __func__, m));
249 m->m_flags &= ~M_BLOCKED;
250 sb->sb_acc += m->m_len;
254 sbready_compress(sb, m0, m);
260 * Adjust sockbuf state reflecting allocation of m.
263 sballoc(struct sockbuf *sb, struct mbuf *m)
266 SOCKBUF_LOCK_ASSERT(sb);
268 sb->sb_ccc += m->m_len;
270 if (sb->sb_fnrdy == NULL) {
271 if (m->m_flags & M_NOTREADY)
274 sb->sb_acc += m->m_len;
276 m->m_flags |= M_BLOCKED;
278 if (m->m_type != MT_DATA && m->m_type != MT_OOBDATA)
279 sb->sb_ctl += m->m_len;
281 sb->sb_mbcnt += MSIZE;
284 if (m->m_flags & M_EXT) {
285 sb->sb_mbcnt += m->m_ext.ext_size;
291 * Adjust sockbuf state reflecting freeing of m.
294 sbfree(struct sockbuf *sb, struct mbuf *m)
297 #if 0 /* XXX: not yet: soclose() call path comes here w/o lock. */
298 SOCKBUF_LOCK_ASSERT(sb);
301 sb->sb_ccc -= m->m_len;
303 if (!(m->m_flags & M_NOTAVAIL))
304 sb->sb_acc -= m->m_len;
306 if (m == sb->sb_fnrdy) {
309 KASSERT(m->m_flags & M_NOTREADY,
310 ("%s: m %p !M_NOTREADY", __func__, m));
313 while (n != NULL && !(n->m_flags & M_NOTREADY)) {
314 n->m_flags &= ~M_BLOCKED;
315 sb->sb_acc += n->m_len;
321 if (m->m_type != MT_DATA && m->m_type != MT_OOBDATA)
322 sb->sb_ctl -= m->m_len;
324 sb->sb_mbcnt -= MSIZE;
326 if (m->m_flags & M_EXT) {
327 sb->sb_mbcnt -= m->m_ext.ext_size;
331 if (sb->sb_sndptr == m) {
332 sb->sb_sndptr = NULL;
333 sb->sb_sndptroff = 0;
335 if (sb->sb_sndptroff != 0)
336 sb->sb_sndptroff -= m->m_len;
340 * Socantsendmore indicates that no more data will be sent on the socket; it
341 * would normally be applied to a socket when the user informs the system
342 * that no more data is to be sent, by the protocol code (in case
343 * PRU_SHUTDOWN). Socantrcvmore indicates that no more data will be
344 * received, and will normally be applied to the socket by a protocol when it
345 * detects that the peer will send no more data. Data queued for reading in
346 * the socket may yet be read.
349 socantsendmore_locked(struct socket *so)
352 SOCKBUF_LOCK_ASSERT(&so->so_snd);
354 so->so_snd.sb_state |= SBS_CANTSENDMORE;
355 sowwakeup_locked(so);
356 mtx_assert(SOCKBUF_MTX(&so->so_snd), MA_NOTOWNED);
360 socantsendmore(struct socket *so)
363 SOCKBUF_LOCK(&so->so_snd);
364 socantsendmore_locked(so);
365 mtx_assert(SOCKBUF_MTX(&so->so_snd), MA_NOTOWNED);
369 socantrcvmore_locked(struct socket *so)
372 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
374 so->so_rcv.sb_state |= SBS_CANTRCVMORE;
375 sorwakeup_locked(so);
376 mtx_assert(SOCKBUF_MTX(&so->so_rcv), MA_NOTOWNED);
380 socantrcvmore(struct socket *so)
383 SOCKBUF_LOCK(&so->so_rcv);
384 socantrcvmore_locked(so);
385 mtx_assert(SOCKBUF_MTX(&so->so_rcv), MA_NOTOWNED);
389 * Wait for data to arrive at/drain from a socket buffer.
392 sbwait(struct sockbuf *sb)
395 SOCKBUF_LOCK_ASSERT(sb);
397 sb->sb_flags |= SB_WAIT;
398 return (msleep_sbt(&sb->sb_acc, &sb->sb_mtx,
399 (sb->sb_flags & SB_NOINTR) ? PSOCK : PSOCK | PCATCH, "sbwait",
400 sb->sb_timeo, 0, 0));
404 sblock(struct sockbuf *sb, int flags)
407 KASSERT((flags & SBL_VALID) == flags,
408 ("sblock: flags invalid (0x%x)", flags));
410 if (flags & SBL_WAIT) {
411 if ((sb->sb_flags & SB_NOINTR) ||
412 (flags & SBL_NOINTR)) {
413 sx_xlock(&sb->sb_sx);
416 return (sx_xlock_sig(&sb->sb_sx));
418 if (sx_try_xlock(&sb->sb_sx) == 0)
419 return (EWOULDBLOCK);
425 sbunlock(struct sockbuf *sb)
428 sx_xunlock(&sb->sb_sx);
432 * Wakeup processes waiting on a socket buffer. Do asynchronous notification
433 * via SIGIO if the socket has the SS_ASYNC flag set.
435 * Called with the socket buffer lock held; will release the lock by the end
436 * of the function. This allows the caller to acquire the socket buffer lock
437 * while testing for the need for various sorts of wakeup and hold it through
438 * to the point where it's no longer required. We currently hold the lock
439 * through calls out to other subsystems (with the exception of kqueue), and
440 * then release it to avoid lock order issues. It's not clear that's
444 sowakeup(struct socket *so, struct sockbuf *sb)
448 SOCKBUF_LOCK_ASSERT(sb);
450 selwakeuppri(sb->sb_sel, PSOCK);
451 if (!SEL_WAITING(sb->sb_sel))
452 sb->sb_flags &= ~SB_SEL;
453 if (sb->sb_flags & SB_WAIT) {
454 sb->sb_flags &= ~SB_WAIT;
457 KNOTE_LOCKED(&sb->sb_sel->si_note, 0);
458 if (sb->sb_upcall != NULL) {
459 ret = sb->sb_upcall(so, sb->sb_upcallarg, M_NOWAIT);
460 if (ret == SU_ISCONNECTED) {
461 KASSERT(sb == &so->so_rcv,
462 ("SO_SND upcall returned SU_ISCONNECTED"));
463 soupcall_clear(so, SO_RCV);
467 if (sb->sb_flags & SB_AIO)
468 sowakeup_aio(so, sb);
470 if (ret == SU_ISCONNECTED)
472 if ((so->so_state & SS_ASYNC) && so->so_sigio != NULL)
473 pgsigio(&so->so_sigio, SIGIO, 0);
474 mtx_assert(SOCKBUF_MTX(sb), MA_NOTOWNED);
478 * Socket buffer (struct sockbuf) utility routines.
480 * Each socket contains two socket buffers: one for sending data and one for
481 * receiving data. Each buffer contains a queue of mbufs, information about
482 * the number of mbufs and amount of data in the queue, and other fields
483 * allowing select() statements and notification on data availability to be
486 * Data stored in a socket buffer is maintained as a list of records. Each
487 * record is a list of mbufs chained together with the m_next field. Records
488 * are chained together with the m_nextpkt field. The upper level routine
489 * soreceive() expects the following conventions to be observed when placing
490 * information in the receive buffer:
492 * 1. If the protocol requires each message be preceded by the sender's name,
493 * then a record containing that name must be present before any
494 * associated data (mbuf's must be of type MT_SONAME).
495 * 2. If the protocol supports the exchange of ``access rights'' (really just
496 * additional data associated with the message), and there are ``rights''
497 * to be received, then a record containing this data should be present
498 * (mbuf's must be of type MT_RIGHTS).
499 * 3. If a name or rights record exists, then it must be followed by a data
500 * record, perhaps of zero length.
502 * Before using a new socket structure it is first necessary to reserve
503 * buffer space to the socket, by calling sbreserve(). This should commit
504 * some of the available buffer space in the system buffer pool for the
505 * socket (currently, it does nothing but enforce limits). The space should
506 * be released by calling sbrelease() when the socket is destroyed.
509 soreserve(struct socket *so, u_long sndcc, u_long rcvcc)
511 struct thread *td = curthread;
513 SOCKBUF_LOCK(&so->so_snd);
514 SOCKBUF_LOCK(&so->so_rcv);
515 if (sbreserve_locked(&so->so_snd, sndcc, so, td) == 0)
517 if (sbreserve_locked(&so->so_rcv, rcvcc, so, td) == 0)
519 if (so->so_rcv.sb_lowat == 0)
520 so->so_rcv.sb_lowat = 1;
521 if (so->so_snd.sb_lowat == 0)
522 so->so_snd.sb_lowat = MCLBYTES;
523 if (so->so_snd.sb_lowat > so->so_snd.sb_hiwat)
524 so->so_snd.sb_lowat = so->so_snd.sb_hiwat;
525 SOCKBUF_UNLOCK(&so->so_rcv);
526 SOCKBUF_UNLOCK(&so->so_snd);
529 sbrelease_locked(&so->so_snd, so);
531 SOCKBUF_UNLOCK(&so->so_rcv);
532 SOCKBUF_UNLOCK(&so->so_snd);
537 sysctl_handle_sb_max(SYSCTL_HANDLER_ARGS)
540 u_long tmp_sb_max = sb_max;
542 error = sysctl_handle_long(oidp, &tmp_sb_max, arg2, req);
543 if (error || !req->newptr)
545 if (tmp_sb_max < MSIZE + MCLBYTES)
548 sb_max_adj = (u_quad_t)sb_max * MCLBYTES / (MSIZE + MCLBYTES);
553 * Allot mbufs to a sockbuf. Attempt to scale mbmax so that mbcnt doesn't
554 * become limiting if buffering efficiency is near the normal case.
557 sbreserve_locked(struct sockbuf *sb, u_long cc, struct socket *so,
562 SOCKBUF_LOCK_ASSERT(sb);
565 * When a thread is passed, we take into account the thread's socket
566 * buffer size limit. The caller will generally pass curthread, but
567 * in the TCP input path, NULL will be passed to indicate that no
568 * appropriate thread resource limits are available. In that case,
569 * we don't apply a process limit.
574 sbsize_limit = lim_cur(td, RLIMIT_SBSIZE);
576 sbsize_limit = RLIM_INFINITY;
577 if (!chgsbsize(so->so_cred->cr_uidinfo, &sb->sb_hiwat, cc,
580 sb->sb_mbmax = min(cc * sb_efficiency, sb_max);
581 if (sb->sb_lowat > sb->sb_hiwat)
582 sb->sb_lowat = sb->sb_hiwat;
587 sbsetopt(struct socket *so, int cmd, u_long cc)
591 u_int *hiwat, *lowat;
596 if (SOLISTENING(so)) {
600 lowat = &so->sol_sbsnd_lowat;
601 hiwat = &so->sol_sbsnd_hiwat;
602 flags = &so->sol_sbsnd_flags;
606 lowat = &so->sol_sbrcv_lowat;
607 hiwat = &so->sol_sbrcv_hiwat;
608 flags = &so->sol_sbrcv_flags;
622 flags = &sb->sb_flags;
623 hiwat = &sb->sb_hiwat;
624 lowat = &sb->sb_lowat;
632 if (SOLISTENING(so)) {
633 if (cc > sb_max_adj) {
641 if (!sbreserve_locked(sb, cc, so, curthread))
645 *flags &= ~SB_AUTOSIZE;
650 * Make sure the low-water is never greater than the
653 *lowat = (cc > *hiwat) ? *hiwat : cc;
657 if (!SOLISTENING(so))
664 * Free mbufs held by a socket, and reserved mbuf space.
667 sbrelease_internal(struct sockbuf *sb, struct socket *so)
670 sbflush_internal(sb);
671 (void)chgsbsize(so->so_cred->cr_uidinfo, &sb->sb_hiwat, 0,
677 sbrelease_locked(struct sockbuf *sb, struct socket *so)
680 SOCKBUF_LOCK_ASSERT(sb);
682 sbrelease_internal(sb, so);
686 sbrelease(struct sockbuf *sb, struct socket *so)
690 sbrelease_locked(sb, so);
695 sbdestroy(struct sockbuf *sb, struct socket *so)
698 sbrelease_internal(sb, so);
700 if (sb->sb_tls_info != NULL)
701 ktls_free(sb->sb_tls_info);
702 sb->sb_tls_info = NULL;
707 * Routines to add and remove data from an mbuf queue.
709 * The routines sbappend() or sbappendrecord() are normally called to append
710 * new mbufs to a socket buffer, after checking that adequate space is
711 * available, comparing the function sbspace() with the amount of data to be
712 * added. sbappendrecord() differs from sbappend() in that data supplied is
713 * treated as the beginning of a new record. To place a sender's address,
714 * optional access rights, and data in a socket receive buffer,
715 * sbappendaddr() should be used. To place access rights and data in a
716 * socket receive buffer, sbappendrights() should be used. In either case,
717 * the new data begins a new record. Note that unlike sbappend() and
718 * sbappendrecord(), these routines check for the caller that there will be
719 * enough space to store the data. Each fails if there is not enough space,
720 * or if it cannot find mbufs to store additional information in.
722 * Reliable protocols may use the socket send buffer to hold data awaiting
723 * acknowledgement. Data is normally copied from a socket send buffer in a
724 * protocol with m_copy for output to a peer, and then removing the data from
725 * the socket buffer with sbdrop() or sbdroprecord() when the data is
726 * acknowledged by the peer.
730 sblastrecordchk(struct sockbuf *sb, const char *file, int line)
732 struct mbuf *m = sb->sb_mb;
734 SOCKBUF_LOCK_ASSERT(sb);
736 while (m && m->m_nextpkt)
739 if (m != sb->sb_lastrecord) {
740 printf("%s: sb_mb %p sb_lastrecord %p last %p\n",
741 __func__, sb->sb_mb, sb->sb_lastrecord, m);
742 printf("packet chain:\n");
743 for (m = sb->sb_mb; m != NULL; m = m->m_nextpkt)
745 panic("%s from %s:%u", __func__, file, line);
750 sblastmbufchk(struct sockbuf *sb, const char *file, int line)
752 struct mbuf *m = sb->sb_mb;
755 SOCKBUF_LOCK_ASSERT(sb);
757 while (m && m->m_nextpkt)
760 while (m && m->m_next)
763 if (m != sb->sb_mbtail) {
764 printf("%s: sb_mb %p sb_mbtail %p last %p\n",
765 __func__, sb->sb_mb, sb->sb_mbtail, m);
766 printf("packet tree:\n");
767 for (m = sb->sb_mb; m != NULL; m = m->m_nextpkt) {
769 for (n = m; n != NULL; n = n->m_next)
773 panic("%s from %s:%u", __func__, file, line);
776 #endif /* SOCKBUF_DEBUG */
778 #define SBLINKRECORD(sb, m0) do { \
779 SOCKBUF_LOCK_ASSERT(sb); \
780 if ((sb)->sb_lastrecord != NULL) \
781 (sb)->sb_lastrecord->m_nextpkt = (m0); \
783 (sb)->sb_mb = (m0); \
784 (sb)->sb_lastrecord = (m0); \
785 } while (/*CONSTCOND*/0)
788 * Append mbuf chain m to the last record in the socket buffer sb. The
789 * additional space associated the mbuf chain is recorded in sb. Empty mbufs
790 * are discarded and mbufs are compacted where possible.
793 sbappend_locked(struct sockbuf *sb, struct mbuf *m, int flags)
797 SOCKBUF_LOCK_ASSERT(sb);
801 sbm_clrprotoflags(m, flags);
808 if (n->m_flags & M_EOR) {
809 sbappendrecord_locked(sb, m); /* XXXXXX!!!! */
812 } while (n->m_next && (n = n->m_next));
815 * XXX Would like to simply use sb_mbtail here, but
816 * XXX I need to verify that I won't miss an EOR that
819 if ((n = sb->sb_lastrecord) != NULL) {
821 if (n->m_flags & M_EOR) {
822 sbappendrecord_locked(sb, m); /* XXXXXX!!!! */
825 } while (n->m_next && (n = n->m_next));
828 * If this is the first record in the socket buffer,
829 * it's also the last record.
831 sb->sb_lastrecord = m;
834 sbcompress(sb, m, n);
839 * Append mbuf chain m to the last record in the socket buffer sb. The
840 * additional space associated the mbuf chain is recorded in sb. Empty mbufs
841 * are discarded and mbufs are compacted where possible.
844 sbappend(struct sockbuf *sb, struct mbuf *m, int flags)
848 sbappend_locked(sb, m, flags);
853 * This version of sbappend() should only be used when the caller absolutely
854 * knows that there will never be more than one record in the socket buffer,
855 * that is, a stream protocol (such as TCP).
858 sbappendstream_locked(struct sockbuf *sb, struct mbuf *m, int flags)
860 SOCKBUF_LOCK_ASSERT(sb);
862 KASSERT(m->m_nextpkt == NULL,("sbappendstream 0"));
863 KASSERT(sb->sb_mb == sb->sb_lastrecord,("sbappendstream 1"));
868 if (sb->sb_tls_info != NULL)
872 /* Remove all packet headers and mbuf tags to get a pure data chain. */
873 m_demote(m, 1, flags & PRUS_NOTREADY ? M_NOTREADY : 0);
875 sbcompress(sb, m, sb->sb_mbtail);
877 sb->sb_lastrecord = sb->sb_mb;
882 * This version of sbappend() should only be used when the caller absolutely
883 * knows that there will never be more than one record in the socket buffer,
884 * that is, a stream protocol (such as TCP).
887 sbappendstream(struct sockbuf *sb, struct mbuf *m, int flags)
891 sbappendstream_locked(sb, m, flags);
897 sbcheck(struct sockbuf *sb, const char *file, int line)
899 struct mbuf *m, *n, *fnrdy;
900 u_long acc, ccc, mbcnt;
902 SOCKBUF_LOCK_ASSERT(sb);
904 acc = ccc = mbcnt = 0;
907 for (m = sb->sb_mb; m; m = n) {
909 for (; m; m = m->m_next) {
911 printf("sb %p empty mbuf %p\n", sb, m);
914 if ((m->m_flags & M_NOTREADY) && fnrdy == NULL) {
915 if (m != sb->sb_fnrdy) {
916 printf("sb %p: fnrdy %p != m %p\n",
917 sb, sb->sb_fnrdy, m);
923 if (!(m->m_flags & M_NOTAVAIL)) {
924 printf("sb %p: fnrdy %p, m %p is avail\n",
925 sb, sb->sb_fnrdy, m);
932 if (m->m_flags & M_EXT) /*XXX*/ /* pretty sure this is bogus */
933 mbcnt += m->m_ext.ext_size;
936 if (acc != sb->sb_acc || ccc != sb->sb_ccc || mbcnt != sb->sb_mbcnt) {
937 printf("acc %ld/%u ccc %ld/%u mbcnt %ld/%u\n",
938 acc, sb->sb_acc, ccc, sb->sb_ccc, mbcnt, sb->sb_mbcnt);
943 panic("%s from %s:%u", __func__, file, line);
948 * As above, except the mbuf chain begins a new record.
951 sbappendrecord_locked(struct sockbuf *sb, struct mbuf *m0)
955 SOCKBUF_LOCK_ASSERT(sb);
961 * Put the first mbuf on the queue. Note this permits zero length
966 SBLINKRECORD(sb, m0);
970 if (m && (m0->m_flags & M_EOR)) {
971 m0->m_flags &= ~M_EOR;
974 /* always call sbcompress() so it can do SBLASTMBUFCHK() */
975 sbcompress(sb, m, m0);
979 * As above, except the mbuf chain begins a new record.
982 sbappendrecord(struct sockbuf *sb, struct mbuf *m0)
986 sbappendrecord_locked(sb, m0);
990 /* Helper routine that appends data, control, and address to a sockbuf. */
992 sbappendaddr_locked_internal(struct sockbuf *sb, const struct sockaddr *asa,
993 struct mbuf *m0, struct mbuf *control, struct mbuf *ctrl_last)
995 struct mbuf *m, *n, *nlast;
997 if (asa->sa_len > MLEN)
1000 m = m_get(M_NOWAIT, MT_SONAME);
1003 m->m_len = asa->sa_len;
1004 bcopy(asa, mtod(m, caddr_t), asa->sa_len);
1006 m_clrprotoflags(m0);
1007 m_tag_delete_chain(m0, NULL);
1009 * Clear some persistent info from pkthdr.
1010 * We don't use m_demote(), because some netgraph consumers
1011 * expect M_PKTHDR presence.
1013 m0->m_pkthdr.rcvif = NULL;
1014 m0->m_pkthdr.flowid = 0;
1015 m0->m_pkthdr.csum_flags = 0;
1016 m0->m_pkthdr.fibnum = 0;
1017 m0->m_pkthdr.rsstype = 0;
1020 ctrl_last->m_next = m0; /* concatenate data to control */
1023 m->m_next = control;
1024 for (n = m; n->m_next != NULL; n = n->m_next)
1028 SBLINKRECORD(sb, m);
1030 sb->sb_mbtail = nlast;
1033 SBLASTRECORDCHK(sb);
1038 * Append address and data, and optionally, control (ancillary) data to the
1039 * receive queue of a socket. If present, m0 must include a packet header
1040 * with total length. Returns 0 if no space in sockbuf or insufficient
1044 sbappendaddr_locked(struct sockbuf *sb, const struct sockaddr *asa,
1045 struct mbuf *m0, struct mbuf *control)
1047 struct mbuf *ctrl_last;
1048 int space = asa->sa_len;
1050 SOCKBUF_LOCK_ASSERT(sb);
1052 if (m0 && (m0->m_flags & M_PKTHDR) == 0)
1053 panic("sbappendaddr_locked");
1055 space += m0->m_pkthdr.len;
1056 space += m_length(control, &ctrl_last);
1058 if (space > sbspace(sb))
1060 return (sbappendaddr_locked_internal(sb, asa, m0, control, ctrl_last));
1064 * Append address and data, and optionally, control (ancillary) data to the
1065 * receive queue of a socket. If present, m0 must include a packet header
1066 * with total length. Returns 0 if insufficient mbufs. Does not validate space
1067 * on the receiving sockbuf.
1070 sbappendaddr_nospacecheck_locked(struct sockbuf *sb, const struct sockaddr *asa,
1071 struct mbuf *m0, struct mbuf *control)
1073 struct mbuf *ctrl_last;
1075 SOCKBUF_LOCK_ASSERT(sb);
1077 ctrl_last = (control == NULL) ? NULL : m_last(control);
1078 return (sbappendaddr_locked_internal(sb, asa, m0, control, ctrl_last));
1082 * Append address and data, and optionally, control (ancillary) data to the
1083 * receive queue of a socket. If present, m0 must include a packet header
1084 * with total length. Returns 0 if no space in sockbuf or insufficient
1088 sbappendaddr(struct sockbuf *sb, const struct sockaddr *asa,
1089 struct mbuf *m0, struct mbuf *control)
1094 retval = sbappendaddr_locked(sb, asa, m0, control);
1100 sbappendcontrol_locked(struct sockbuf *sb, struct mbuf *m0,
1101 struct mbuf *control, int flags)
1103 struct mbuf *m, *mlast;
1105 sbm_clrprotoflags(m0, flags);
1106 m_last(control)->m_next = m0;
1108 SBLASTRECORDCHK(sb);
1110 for (m = control; m->m_next; m = m->m_next)
1114 SBLINKRECORD(sb, control);
1116 sb->sb_mbtail = mlast;
1119 SBLASTRECORDCHK(sb);
1123 sbappendcontrol(struct sockbuf *sb, struct mbuf *m0, struct mbuf *control,
1128 sbappendcontrol_locked(sb, m0, control, flags);
1133 * Append the data in mbuf chain (m) into the socket buffer sb following mbuf
1134 * (n). If (n) is NULL, the buffer is presumed empty.
1136 * When the data is compressed, mbufs in the chain may be handled in one of
1139 * (1) The mbuf may simply be dropped, if it contributes nothing (no data, no
1140 * record boundary, and no change in data type).
1142 * (2) The mbuf may be coalesced -- i.e., data in the mbuf may be copied into
1143 * an mbuf already in the socket buffer. This can occur if an
1144 * appropriate mbuf exists, there is room, both mbufs are not marked as
1145 * not ready, and no merging of data types will occur.
1147 * (3) The mbuf may be appended to the end of the existing mbuf chain.
1149 * If any of the new mbufs is marked as M_EOR, mark the last mbuf appended as
1153 sbcompress(struct sockbuf *sb, struct mbuf *m, struct mbuf *n)
1158 SOCKBUF_LOCK_ASSERT(sb);
1161 eor |= m->m_flags & M_EOR;
1162 if (m->m_len == 0 &&
1164 (((o = m->m_next) || (o = n)) &&
1165 o->m_type == m->m_type))) {
1166 if (sb->sb_lastrecord == m)
1167 sb->sb_lastrecord = m->m_next;
1171 if (n && (n->m_flags & M_EOR) == 0 &&
1173 ((sb->sb_flags & SB_NOCOALESCE) == 0) &&
1174 !(m->m_flags & M_NOTREADY) &&
1175 !(n->m_flags & (M_NOTREADY | M_NOMAP)) &&
1176 !mbuf_has_tls_session(m) &&
1177 !mbuf_has_tls_session(n) &&
1178 m->m_len <= MCLBYTES / 4 && /* XXX: Don't copy too much */
1179 m->m_len <= M_TRAILINGSPACE(n) &&
1180 n->m_type == m->m_type) {
1181 m_copydata(m, 0, m->m_len, mtodo(n, n->m_len));
1182 n->m_len += m->m_len;
1183 sb->sb_ccc += m->m_len;
1184 if (sb->sb_fnrdy == NULL)
1185 sb->sb_acc += m->m_len;
1186 if (m->m_type != MT_DATA && m->m_type != MT_OOBDATA)
1187 /* XXX: Probably don't need.*/
1188 sb->sb_ctl += m->m_len;
1192 if (m->m_len <= MLEN && (m->m_flags & M_NOMAP) &&
1193 (m->m_flags & M_NOTREADY) == 0 &&
1194 !mbuf_has_tls_session(m))
1195 (void)mb_unmapped_compress(m);
1203 m->m_flags &= ~M_EOR;
1208 KASSERT(n != NULL, ("sbcompress: eor && n == NULL"));
1215 * Free all mbufs in a sockbuf. Check that all resources are reclaimed.
1218 sbflush_internal(struct sockbuf *sb)
1221 while (sb->sb_mbcnt) {
1223 * Don't call sbcut(sb, 0) if the leading mbuf is non-empty:
1224 * we would loop forever. Panic instead.
1226 if (sb->sb_ccc == 0 && (sb->sb_mb == NULL || sb->sb_mb->m_len))
1228 m_freem(sbcut_internal(sb, (int)sb->sb_ccc));
1230 KASSERT(sb->sb_ccc == 0 && sb->sb_mb == 0 && sb->sb_mbcnt == 0,
1231 ("%s: ccc %u mb %p mbcnt %u", __func__,
1232 sb->sb_ccc, (void *)sb->sb_mb, sb->sb_mbcnt));
1236 sbflush_locked(struct sockbuf *sb)
1239 SOCKBUF_LOCK_ASSERT(sb);
1240 sbflush_internal(sb);
1244 sbflush(struct sockbuf *sb)
1253 * Cut data from (the front of) a sockbuf.
1255 static struct mbuf *
1256 sbcut_internal(struct sockbuf *sb, int len)
1258 struct mbuf *m, *next, *mfree;
1260 KASSERT(len >= 0, ("%s: len is %d but it is supposed to be >= 0",
1262 KASSERT(len <= sb->sb_ccc, ("%s: len: %d is > ccc: %u",
1263 __func__, len, sb->sb_ccc));
1265 next = (m = sb->sb_mb) ? m->m_nextpkt : 0;
1270 KASSERT(next, ("%s: no next, len %d", __func__, len));
1272 next = m->m_nextpkt;
1274 if (m->m_len > len) {
1275 KASSERT(!(m->m_flags & M_NOTAVAIL),
1276 ("%s: m %p M_NOTAVAIL", __func__, m));
1281 if (sb->sb_sndptroff != 0)
1282 sb->sb_sndptroff -= len;
1283 if (m->m_type != MT_DATA && m->m_type != MT_OOBDATA)
1290 * Do not put M_NOTREADY buffers to the free list, they
1291 * are referenced from outside.
1293 if (m->m_flags & M_NOTREADY)
1305 * Free any zero-length mbufs from the buffer.
1306 * For SOCK_DGRAM sockets such mbufs represent empty records.
1307 * XXX: For SOCK_STREAM sockets such mbufs can appear in the buffer,
1308 * when sosend_generic() needs to send only control data.
1310 while (m && m->m_len == 0) {
1321 m->m_nextpkt = next;
1325 * First part is an inline SB_EMPTY_FIXUP(). Second part makes sure
1326 * sb_lastrecord is up-to-date if we dropped part of the last record.
1330 sb->sb_mbtail = NULL;
1331 sb->sb_lastrecord = NULL;
1332 } else if (m->m_nextpkt == NULL) {
1333 sb->sb_lastrecord = m;
1340 * Drop data from (the front of) a sockbuf.
1343 sbdrop_locked(struct sockbuf *sb, int len)
1346 SOCKBUF_LOCK_ASSERT(sb);
1347 m_freem(sbcut_internal(sb, len));
1351 * Drop data from (the front of) a sockbuf,
1352 * and return it to caller.
1355 sbcut_locked(struct sockbuf *sb, int len)
1358 SOCKBUF_LOCK_ASSERT(sb);
1359 return (sbcut_internal(sb, len));
1363 sbdrop(struct sockbuf *sb, int len)
1368 mfree = sbcut_internal(sb, len);
1375 sbsndptr_noadv(struct sockbuf *sb, uint32_t off, uint32_t *moff)
1379 KASSERT(sb->sb_mb != NULL, ("%s: sb_mb is NULL", __func__));
1380 if (sb->sb_sndptr == NULL || sb->sb_sndptroff > off) {
1382 if (sb->sb_sndptr == NULL) {
1383 sb->sb_sndptr = sb->sb_mb;
1384 sb->sb_sndptroff = 0;
1389 off -= sb->sb_sndptroff;
1396 sbsndptr_adv(struct sockbuf *sb, struct mbuf *mb, uint32_t len)
1399 * A small copy was done, advance forward the sb_sbsndptr to cover
1404 if (mb != sb->sb_sndptr) {
1405 /* Did not copyout at the same mbuf */
1409 while (m && (len > 0)) {
1410 if (len >= m->m_len) {
1413 sb->sb_sndptroff += m->m_len;
1414 sb->sb_sndptr = m->m_next;
1424 * Return the first mbuf and the mbuf data offset for the provided
1425 * send offset without changing the "sb_sndptroff" field.
1428 sbsndmbuf(struct sockbuf *sb, u_int off, u_int *moff)
1432 KASSERT(sb->sb_mb != NULL, ("%s: sb_mb is NULL", __func__));
1435 * If the "off" is below the stored offset, which happens on
1436 * retransmits, just use "sb_mb":
1438 if (sb->sb_sndptr == NULL || sb->sb_sndptroff > off) {
1442 off -= sb->sb_sndptroff;
1444 while (off > 0 && m != NULL) {
1455 * Drop a record off the front of a sockbuf and move the next record to the
1459 sbdroprecord_locked(struct sockbuf *sb)
1463 SOCKBUF_LOCK_ASSERT(sb);
1467 sb->sb_mb = m->m_nextpkt;
1477 * Drop a record off the front of a sockbuf and move the next record to the
1481 sbdroprecord(struct sockbuf *sb)
1485 sbdroprecord_locked(sb);
1490 * Create a "control" mbuf containing the specified data with the specified
1491 * type for presentation on a socket buffer.
1494 sbcreatecontrol(caddr_t p, int size, int type, int level)
1499 if (CMSG_SPACE((u_int)size) > MCLBYTES)
1500 return ((struct mbuf *) NULL);
1501 if (CMSG_SPACE((u_int)size) > MLEN)
1502 m = m_getcl(M_NOWAIT, MT_CONTROL, 0);
1504 m = m_get(M_NOWAIT, MT_CONTROL);
1506 return ((struct mbuf *) NULL);
1507 cp = mtod(m, struct cmsghdr *);
1509 KASSERT(CMSG_SPACE((u_int)size) <= M_TRAILINGSPACE(m),
1510 ("sbcreatecontrol: short mbuf"));
1512 * Don't leave the padding between the msg header and the
1513 * cmsg data and the padding after the cmsg data un-initialized.
1515 bzero(cp, CMSG_SPACE((u_int)size));
1517 (void)memcpy(CMSG_DATA(cp), p, size);
1518 m->m_len = CMSG_SPACE(size);
1519 cp->cmsg_len = CMSG_LEN(size);
1520 cp->cmsg_level = level;
1521 cp->cmsg_type = type;
1526 * This does the same for socket buffers that sotoxsocket does for sockets:
1527 * generate an user-format data structure describing the socket buffer. Note
1528 * that the xsockbuf structure, since it is always embedded in a socket, does
1529 * not include a self pointer nor a length. We make this entry point public
1530 * in case some other mechanism needs it.
1533 sbtoxsockbuf(struct sockbuf *sb, struct xsockbuf *xsb)
1536 xsb->sb_cc = sb->sb_ccc;
1537 xsb->sb_hiwat = sb->sb_hiwat;
1538 xsb->sb_mbcnt = sb->sb_mbcnt;
1539 xsb->sb_mcnt = sb->sb_mcnt;
1540 xsb->sb_ccnt = sb->sb_ccnt;
1541 xsb->sb_mbmax = sb->sb_mbmax;
1542 xsb->sb_lowat = sb->sb_lowat;
1543 xsb->sb_flags = sb->sb_flags;
1544 xsb->sb_timeo = sb->sb_timeo;
1547 /* This takes the place of kern.maxsockbuf, which moved to kern.ipc. */
1549 SYSCTL_INT(_kern, KERN_DUMMY, dummy, CTLFLAG_RW | CTLFLAG_SKIP, &dummy, 0, "");
1550 SYSCTL_OID(_kern_ipc, KIPC_MAXSOCKBUF, maxsockbuf,
1551 CTLTYPE_ULONG | CTLFLAG_RW | CTLFLAG_NEEDGIANT, &sb_max, 0,
1552 sysctl_handle_sb_max, "LU",
1553 "Maximum socket buffer size");
1554 SYSCTL_ULONG(_kern_ipc, KIPC_SOCKBUF_WASTE, sockbuf_waste_factor, CTLFLAG_RW,
1555 &sb_efficiency, 0, "Socket buffer size waste factor");