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 /* Compress small unmapped mbufs into plain mbufs. */
117 if ((m->m_flags & M_NOMAP) && m->m_len <= MLEN &&
118 !mbuf_has_tls_session(m)) {
119 MPASS(m->m_flags & M_EXT);
120 ext_size = m->m_ext.ext_size;
121 if (mb_unmapped_compress(m) == 0) {
122 sb->sb_mbcnt -= ext_size;
128 * NB: In sbcompress(), 'n' is the last mbuf in the
129 * socket buffer and 'm' is the new mbuf being copied
130 * into the trailing space of 'n'. Here, the roles
131 * are reversed and 'n' is the next mbuf after 'm'
132 * that is being copied into the trailing space of
136 while ((n != NULL) && (n != end) && (m->m_flags & M_EOR) == 0 &&
138 (m->m_flags & M_NOMAP) == 0 &&
139 !mbuf_has_tls_session(n) &&
140 !mbuf_has_tls_session(m) &&
141 n->m_len <= MCLBYTES / 4 && /* XXX: Don't copy too much */
142 n->m_len <= M_TRAILINGSPACE(m) &&
143 m->m_type == n->m_type) {
144 KASSERT(sb->sb_lastrecord != n,
145 ("%s: merging start of record (%p) into previous mbuf (%p)",
147 m_copydata(n, 0, n->m_len, mtodo(m, m->m_len));
148 m->m_len += n->m_len;
149 m->m_next = n->m_next;
150 m->m_flags |= n->m_flags & M_EOR;
151 if (sb->sb_mbtail == n)
154 sb->sb_mbcnt -= MSIZE;
156 if (n->m_flags & M_EXT) {
157 sb->sb_mbcnt -= n->m_ext.ext_size;
169 * Mark ready "count" units of I/O starting with "m". Most mbufs
170 * count as a single unit of I/O except for EXT_PGS-backed mbufs which
171 * can be backed by multiple pages.
174 sbready(struct sockbuf *sb, struct mbuf *m0, int count)
179 SOCKBUF_LOCK_ASSERT(sb);
180 KASSERT(sb->sb_fnrdy != NULL, ("%s: sb %p NULL fnrdy", __func__, sb));
181 KASSERT(count > 0, ("%s: invalid count %d", __func__, count));
184 blocker = (sb->sb_fnrdy == m) ? M_BLOCKED : 0;
187 KASSERT(m->m_flags & M_NOTREADY,
188 ("%s: m %p !M_NOTREADY", __func__, m));
189 if ((m->m_flags & M_EXT) != 0 &&
190 m->m_ext.ext_type == EXT_PGS) {
191 if (count < m->m_ext.ext_pgs->nrdy) {
192 m->m_ext.ext_pgs->nrdy -= count;
196 count -= m->m_ext.ext_pgs->nrdy;
197 m->m_ext.ext_pgs->nrdy = 0;
201 m->m_flags &= ~(M_NOTREADY | blocker);
203 sb->sb_acc += m->m_len;
208 * If the first mbuf is still not fully ready because only
209 * some of its backing pages were readied, no further progress
213 MPASS(m->m_flags & M_NOTREADY);
214 return (EINPROGRESS);
218 sbready_compress(sb, m0, m);
219 return (EINPROGRESS);
222 /* This one was blocking all the queue. */
223 for (; m && (m->m_flags & M_NOTREADY) == 0; m = m->m_next) {
224 KASSERT(m->m_flags & M_BLOCKED,
225 ("%s: m %p !M_BLOCKED", __func__, m));
226 m->m_flags &= ~M_BLOCKED;
227 sb->sb_acc += m->m_len;
231 sbready_compress(sb, m0, m);
237 * Adjust sockbuf state reflecting allocation of m.
240 sballoc(struct sockbuf *sb, struct mbuf *m)
243 SOCKBUF_LOCK_ASSERT(sb);
245 sb->sb_ccc += m->m_len;
247 if (sb->sb_fnrdy == NULL) {
248 if (m->m_flags & M_NOTREADY)
251 sb->sb_acc += m->m_len;
253 m->m_flags |= M_BLOCKED;
255 if (m->m_type != MT_DATA && m->m_type != MT_OOBDATA)
256 sb->sb_ctl += m->m_len;
258 sb->sb_mbcnt += MSIZE;
261 if (m->m_flags & M_EXT) {
262 sb->sb_mbcnt += m->m_ext.ext_size;
268 * Adjust sockbuf state reflecting freeing of m.
271 sbfree(struct sockbuf *sb, struct mbuf *m)
274 #if 0 /* XXX: not yet: soclose() call path comes here w/o lock. */
275 SOCKBUF_LOCK_ASSERT(sb);
278 sb->sb_ccc -= m->m_len;
280 if (!(m->m_flags & M_NOTAVAIL))
281 sb->sb_acc -= m->m_len;
283 if (m == sb->sb_fnrdy) {
286 KASSERT(m->m_flags & M_NOTREADY,
287 ("%s: m %p !M_NOTREADY", __func__, m));
290 while (n != NULL && !(n->m_flags & M_NOTREADY)) {
291 n->m_flags &= ~M_BLOCKED;
292 sb->sb_acc += n->m_len;
298 if (m->m_type != MT_DATA && m->m_type != MT_OOBDATA)
299 sb->sb_ctl -= m->m_len;
301 sb->sb_mbcnt -= MSIZE;
303 if (m->m_flags & M_EXT) {
304 sb->sb_mbcnt -= m->m_ext.ext_size;
308 if (sb->sb_sndptr == m) {
309 sb->sb_sndptr = NULL;
310 sb->sb_sndptroff = 0;
312 if (sb->sb_sndptroff != 0)
313 sb->sb_sndptroff -= m->m_len;
317 * Socantsendmore indicates that no more data will be sent on the socket; it
318 * would normally be applied to a socket when the user informs the system
319 * that no more data is to be sent, by the protocol code (in case
320 * PRU_SHUTDOWN). Socantrcvmore indicates that no more data will be
321 * received, and will normally be applied to the socket by a protocol when it
322 * detects that the peer will send no more data. Data queued for reading in
323 * the socket may yet be read.
326 socantsendmore_locked(struct socket *so)
329 SOCKBUF_LOCK_ASSERT(&so->so_snd);
331 so->so_snd.sb_state |= SBS_CANTSENDMORE;
332 sowwakeup_locked(so);
333 mtx_assert(SOCKBUF_MTX(&so->so_snd), MA_NOTOWNED);
337 socantsendmore(struct socket *so)
340 SOCKBUF_LOCK(&so->so_snd);
341 socantsendmore_locked(so);
342 mtx_assert(SOCKBUF_MTX(&so->so_snd), MA_NOTOWNED);
346 socantrcvmore_locked(struct socket *so)
349 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
351 so->so_rcv.sb_state |= SBS_CANTRCVMORE;
352 sorwakeup_locked(so);
353 mtx_assert(SOCKBUF_MTX(&so->so_rcv), MA_NOTOWNED);
357 socantrcvmore(struct socket *so)
360 SOCKBUF_LOCK(&so->so_rcv);
361 socantrcvmore_locked(so);
362 mtx_assert(SOCKBUF_MTX(&so->so_rcv), MA_NOTOWNED);
366 * Wait for data to arrive at/drain from a socket buffer.
369 sbwait(struct sockbuf *sb)
372 SOCKBUF_LOCK_ASSERT(sb);
374 sb->sb_flags |= SB_WAIT;
375 return (msleep_sbt(&sb->sb_acc, &sb->sb_mtx,
376 (sb->sb_flags & SB_NOINTR) ? PSOCK : PSOCK | PCATCH, "sbwait",
377 sb->sb_timeo, 0, 0));
381 sblock(struct sockbuf *sb, int flags)
384 KASSERT((flags & SBL_VALID) == flags,
385 ("sblock: flags invalid (0x%x)", flags));
387 if (flags & SBL_WAIT) {
388 if ((sb->sb_flags & SB_NOINTR) ||
389 (flags & SBL_NOINTR)) {
390 sx_xlock(&sb->sb_sx);
393 return (sx_xlock_sig(&sb->sb_sx));
395 if (sx_try_xlock(&sb->sb_sx) == 0)
396 return (EWOULDBLOCK);
402 sbunlock(struct sockbuf *sb)
405 sx_xunlock(&sb->sb_sx);
409 * Wakeup processes waiting on a socket buffer. Do asynchronous notification
410 * via SIGIO if the socket has the SS_ASYNC flag set.
412 * Called with the socket buffer lock held; will release the lock by the end
413 * of the function. This allows the caller to acquire the socket buffer lock
414 * while testing for the need for various sorts of wakeup and hold it through
415 * to the point where it's no longer required. We currently hold the lock
416 * through calls out to other subsystems (with the exception of kqueue), and
417 * then release it to avoid lock order issues. It's not clear that's
421 sowakeup(struct socket *so, struct sockbuf *sb)
425 SOCKBUF_LOCK_ASSERT(sb);
427 selwakeuppri(sb->sb_sel, PSOCK);
428 if (!SEL_WAITING(sb->sb_sel))
429 sb->sb_flags &= ~SB_SEL;
430 if (sb->sb_flags & SB_WAIT) {
431 sb->sb_flags &= ~SB_WAIT;
434 KNOTE_LOCKED(&sb->sb_sel->si_note, 0);
435 if (sb->sb_upcall != NULL) {
436 ret = sb->sb_upcall(so, sb->sb_upcallarg, M_NOWAIT);
437 if (ret == SU_ISCONNECTED) {
438 KASSERT(sb == &so->so_rcv,
439 ("SO_SND upcall returned SU_ISCONNECTED"));
440 soupcall_clear(so, SO_RCV);
444 if (sb->sb_flags & SB_AIO)
445 sowakeup_aio(so, sb);
447 if (ret == SU_ISCONNECTED)
449 if ((so->so_state & SS_ASYNC) && so->so_sigio != NULL)
450 pgsigio(&so->so_sigio, SIGIO, 0);
451 mtx_assert(SOCKBUF_MTX(sb), MA_NOTOWNED);
455 * Socket buffer (struct sockbuf) utility routines.
457 * Each socket contains two socket buffers: one for sending data and one for
458 * receiving data. Each buffer contains a queue of mbufs, information about
459 * the number of mbufs and amount of data in the queue, and other fields
460 * allowing select() statements and notification on data availability to be
463 * Data stored in a socket buffer is maintained as a list of records. Each
464 * record is a list of mbufs chained together with the m_next field. Records
465 * are chained together with the m_nextpkt field. The upper level routine
466 * soreceive() expects the following conventions to be observed when placing
467 * information in the receive buffer:
469 * 1. If the protocol requires each message be preceded by the sender's name,
470 * then a record containing that name must be present before any
471 * associated data (mbuf's must be of type MT_SONAME).
472 * 2. If the protocol supports the exchange of ``access rights'' (really just
473 * additional data associated with the message), and there are ``rights''
474 * to be received, then a record containing this data should be present
475 * (mbuf's must be of type MT_RIGHTS).
476 * 3. If a name or rights record exists, then it must be followed by a data
477 * record, perhaps of zero length.
479 * Before using a new socket structure it is first necessary to reserve
480 * buffer space to the socket, by calling sbreserve(). This should commit
481 * some of the available buffer space in the system buffer pool for the
482 * socket (currently, it does nothing but enforce limits). The space should
483 * be released by calling sbrelease() when the socket is destroyed.
486 soreserve(struct socket *so, u_long sndcc, u_long rcvcc)
488 struct thread *td = curthread;
490 SOCKBUF_LOCK(&so->so_snd);
491 SOCKBUF_LOCK(&so->so_rcv);
492 if (sbreserve_locked(&so->so_snd, sndcc, so, td) == 0)
494 if (sbreserve_locked(&so->so_rcv, rcvcc, so, td) == 0)
496 if (so->so_rcv.sb_lowat == 0)
497 so->so_rcv.sb_lowat = 1;
498 if (so->so_snd.sb_lowat == 0)
499 so->so_snd.sb_lowat = MCLBYTES;
500 if (so->so_snd.sb_lowat > so->so_snd.sb_hiwat)
501 so->so_snd.sb_lowat = so->so_snd.sb_hiwat;
502 SOCKBUF_UNLOCK(&so->so_rcv);
503 SOCKBUF_UNLOCK(&so->so_snd);
506 sbrelease_locked(&so->so_snd, so);
508 SOCKBUF_UNLOCK(&so->so_rcv);
509 SOCKBUF_UNLOCK(&so->so_snd);
514 sysctl_handle_sb_max(SYSCTL_HANDLER_ARGS)
517 u_long tmp_sb_max = sb_max;
519 error = sysctl_handle_long(oidp, &tmp_sb_max, arg2, req);
520 if (error || !req->newptr)
522 if (tmp_sb_max < MSIZE + MCLBYTES)
525 sb_max_adj = (u_quad_t)sb_max * MCLBYTES / (MSIZE + MCLBYTES);
530 * Allot mbufs to a sockbuf. Attempt to scale mbmax so that mbcnt doesn't
531 * become limiting if buffering efficiency is near the normal case.
534 sbreserve_locked(struct sockbuf *sb, u_long cc, struct socket *so,
539 SOCKBUF_LOCK_ASSERT(sb);
542 * When a thread is passed, we take into account the thread's socket
543 * buffer size limit. The caller will generally pass curthread, but
544 * in the TCP input path, NULL will be passed to indicate that no
545 * appropriate thread resource limits are available. In that case,
546 * we don't apply a process limit.
551 sbsize_limit = lim_cur(td, RLIMIT_SBSIZE);
553 sbsize_limit = RLIM_INFINITY;
554 if (!chgsbsize(so->so_cred->cr_uidinfo, &sb->sb_hiwat, cc,
557 sb->sb_mbmax = min(cc * sb_efficiency, sb_max);
558 if (sb->sb_lowat > sb->sb_hiwat)
559 sb->sb_lowat = sb->sb_hiwat;
564 sbsetopt(struct socket *so, int cmd, u_long cc)
568 u_int *hiwat, *lowat;
573 if (SOLISTENING(so)) {
577 lowat = &so->sol_sbsnd_lowat;
578 hiwat = &so->sol_sbsnd_hiwat;
579 flags = &so->sol_sbsnd_flags;
583 lowat = &so->sol_sbrcv_lowat;
584 hiwat = &so->sol_sbrcv_hiwat;
585 flags = &so->sol_sbrcv_flags;
599 flags = &sb->sb_flags;
600 hiwat = &sb->sb_hiwat;
601 lowat = &sb->sb_lowat;
609 if (SOLISTENING(so)) {
610 if (cc > sb_max_adj) {
618 if (!sbreserve_locked(sb, cc, so, curthread))
622 *flags &= ~SB_AUTOSIZE;
627 * Make sure the low-water is never greater than the
630 *lowat = (cc > *hiwat) ? *hiwat : cc;
634 if (!SOLISTENING(so))
641 * Free mbufs held by a socket, and reserved mbuf space.
644 sbrelease_internal(struct sockbuf *sb, struct socket *so)
647 sbflush_internal(sb);
648 (void)chgsbsize(so->so_cred->cr_uidinfo, &sb->sb_hiwat, 0,
654 sbrelease_locked(struct sockbuf *sb, struct socket *so)
657 SOCKBUF_LOCK_ASSERT(sb);
659 sbrelease_internal(sb, so);
663 sbrelease(struct sockbuf *sb, struct socket *so)
667 sbrelease_locked(sb, so);
672 sbdestroy(struct sockbuf *sb, struct socket *so)
675 sbrelease_internal(sb, so);
677 if (sb->sb_tls_info != NULL)
678 ktls_free(sb->sb_tls_info);
679 sb->sb_tls_info = NULL;
684 * Routines to add and remove data from an mbuf queue.
686 * The routines sbappend() or sbappendrecord() are normally called to append
687 * new mbufs to a socket buffer, after checking that adequate space is
688 * available, comparing the function sbspace() with the amount of data to be
689 * added. sbappendrecord() differs from sbappend() in that data supplied is
690 * treated as the beginning of a new record. To place a sender's address,
691 * optional access rights, and data in a socket receive buffer,
692 * sbappendaddr() should be used. To place access rights and data in a
693 * socket receive buffer, sbappendrights() should be used. In either case,
694 * the new data begins a new record. Note that unlike sbappend() and
695 * sbappendrecord(), these routines check for the caller that there will be
696 * enough space to store the data. Each fails if there is not enough space,
697 * or if it cannot find mbufs to store additional information in.
699 * Reliable protocols may use the socket send buffer to hold data awaiting
700 * acknowledgement. Data is normally copied from a socket send buffer in a
701 * protocol with m_copy for output to a peer, and then removing the data from
702 * the socket buffer with sbdrop() or sbdroprecord() when the data is
703 * acknowledged by the peer.
707 sblastrecordchk(struct sockbuf *sb, const char *file, int line)
709 struct mbuf *m = sb->sb_mb;
711 SOCKBUF_LOCK_ASSERT(sb);
713 while (m && m->m_nextpkt)
716 if (m != sb->sb_lastrecord) {
717 printf("%s: sb_mb %p sb_lastrecord %p last %p\n",
718 __func__, sb->sb_mb, sb->sb_lastrecord, m);
719 printf("packet chain:\n");
720 for (m = sb->sb_mb; m != NULL; m = m->m_nextpkt)
722 panic("%s from %s:%u", __func__, file, line);
727 sblastmbufchk(struct sockbuf *sb, const char *file, int line)
729 struct mbuf *m = sb->sb_mb;
732 SOCKBUF_LOCK_ASSERT(sb);
734 while (m && m->m_nextpkt)
737 while (m && m->m_next)
740 if (m != sb->sb_mbtail) {
741 printf("%s: sb_mb %p sb_mbtail %p last %p\n",
742 __func__, sb->sb_mb, sb->sb_mbtail, m);
743 printf("packet tree:\n");
744 for (m = sb->sb_mb; m != NULL; m = m->m_nextpkt) {
746 for (n = m; n != NULL; n = n->m_next)
750 panic("%s from %s:%u", __func__, file, line);
753 #endif /* SOCKBUF_DEBUG */
755 #define SBLINKRECORD(sb, m0) do { \
756 SOCKBUF_LOCK_ASSERT(sb); \
757 if ((sb)->sb_lastrecord != NULL) \
758 (sb)->sb_lastrecord->m_nextpkt = (m0); \
760 (sb)->sb_mb = (m0); \
761 (sb)->sb_lastrecord = (m0); \
762 } while (/*CONSTCOND*/0)
765 * Append mbuf chain m to the last record in the socket buffer sb. The
766 * additional space associated the mbuf chain is recorded in sb. Empty mbufs
767 * are discarded and mbufs are compacted where possible.
770 sbappend_locked(struct sockbuf *sb, struct mbuf *m, int flags)
774 SOCKBUF_LOCK_ASSERT(sb);
778 sbm_clrprotoflags(m, flags);
785 if (n->m_flags & M_EOR) {
786 sbappendrecord_locked(sb, m); /* XXXXXX!!!! */
789 } while (n->m_next && (n = n->m_next));
792 * XXX Would like to simply use sb_mbtail here, but
793 * XXX I need to verify that I won't miss an EOR that
796 if ((n = sb->sb_lastrecord) != NULL) {
798 if (n->m_flags & M_EOR) {
799 sbappendrecord_locked(sb, m); /* XXXXXX!!!! */
802 } while (n->m_next && (n = n->m_next));
805 * If this is the first record in the socket buffer,
806 * it's also the last record.
808 sb->sb_lastrecord = m;
811 sbcompress(sb, m, n);
816 * Append mbuf chain m to the last record in the socket buffer sb. The
817 * additional space associated the mbuf chain is recorded in sb. Empty mbufs
818 * are discarded and mbufs are compacted where possible.
821 sbappend(struct sockbuf *sb, struct mbuf *m, int flags)
825 sbappend_locked(sb, m, flags);
830 * This version of sbappend() should only be used when the caller absolutely
831 * knows that there will never be more than one record in the socket buffer,
832 * that is, a stream protocol (such as TCP).
835 sbappendstream_locked(struct sockbuf *sb, struct mbuf *m, int flags)
837 SOCKBUF_LOCK_ASSERT(sb);
839 KASSERT(m->m_nextpkt == NULL,("sbappendstream 0"));
840 KASSERT(sb->sb_mb == sb->sb_lastrecord,("sbappendstream 1"));
845 if (sb->sb_tls_info != NULL)
849 /* Remove all packet headers and mbuf tags to get a pure data chain. */
850 m_demote(m, 1, flags & PRUS_NOTREADY ? M_NOTREADY : 0);
852 sbcompress(sb, m, sb->sb_mbtail);
854 sb->sb_lastrecord = sb->sb_mb;
859 * This version of sbappend() should only be used when the caller absolutely
860 * knows that there will never be more than one record in the socket buffer,
861 * that is, a stream protocol (such as TCP).
864 sbappendstream(struct sockbuf *sb, struct mbuf *m, int flags)
868 sbappendstream_locked(sb, m, flags);
874 sbcheck(struct sockbuf *sb, const char *file, int line)
876 struct mbuf *m, *n, *fnrdy;
877 u_long acc, ccc, mbcnt;
879 SOCKBUF_LOCK_ASSERT(sb);
881 acc = ccc = mbcnt = 0;
884 for (m = sb->sb_mb; m; m = n) {
886 for (; m; m = m->m_next) {
888 printf("sb %p empty mbuf %p\n", sb, m);
891 if ((m->m_flags & M_NOTREADY) && fnrdy == NULL) {
892 if (m != sb->sb_fnrdy) {
893 printf("sb %p: fnrdy %p != m %p\n",
894 sb, sb->sb_fnrdy, m);
900 if (!(m->m_flags & M_NOTAVAIL)) {
901 printf("sb %p: fnrdy %p, m %p is avail\n",
902 sb, sb->sb_fnrdy, m);
909 if (m->m_flags & M_EXT) /*XXX*/ /* pretty sure this is bogus */
910 mbcnt += m->m_ext.ext_size;
913 if (acc != sb->sb_acc || ccc != sb->sb_ccc || mbcnt != sb->sb_mbcnt) {
914 printf("acc %ld/%u ccc %ld/%u mbcnt %ld/%u\n",
915 acc, sb->sb_acc, ccc, sb->sb_ccc, mbcnt, sb->sb_mbcnt);
920 panic("%s from %s:%u", __func__, file, line);
925 * As above, except the mbuf chain begins a new record.
928 sbappendrecord_locked(struct sockbuf *sb, struct mbuf *m0)
932 SOCKBUF_LOCK_ASSERT(sb);
938 * Put the first mbuf on the queue. Note this permits zero length
943 SBLINKRECORD(sb, m0);
947 if (m && (m0->m_flags & M_EOR)) {
948 m0->m_flags &= ~M_EOR;
951 /* always call sbcompress() so it can do SBLASTMBUFCHK() */
952 sbcompress(sb, m, m0);
956 * As above, except the mbuf chain begins a new record.
959 sbappendrecord(struct sockbuf *sb, struct mbuf *m0)
963 sbappendrecord_locked(sb, m0);
967 /* Helper routine that appends data, control, and address to a sockbuf. */
969 sbappendaddr_locked_internal(struct sockbuf *sb, const struct sockaddr *asa,
970 struct mbuf *m0, struct mbuf *control, struct mbuf *ctrl_last)
972 struct mbuf *m, *n, *nlast;
974 if (asa->sa_len > MLEN)
977 m = m_get(M_NOWAIT, MT_SONAME);
980 m->m_len = asa->sa_len;
981 bcopy(asa, mtod(m, caddr_t), asa->sa_len);
984 m_tag_delete_chain(m0, NULL);
986 * Clear some persistent info from pkthdr.
987 * We don't use m_demote(), because some netgraph consumers
988 * expect M_PKTHDR presence.
990 m0->m_pkthdr.rcvif = NULL;
991 m0->m_pkthdr.flowid = 0;
992 m0->m_pkthdr.csum_flags = 0;
993 m0->m_pkthdr.fibnum = 0;
994 m0->m_pkthdr.rsstype = 0;
997 ctrl_last->m_next = m0; /* concatenate data to control */
1000 m->m_next = control;
1001 for (n = m; n->m_next != NULL; n = n->m_next)
1005 SBLINKRECORD(sb, m);
1007 sb->sb_mbtail = nlast;
1010 SBLASTRECORDCHK(sb);
1015 * Append address and data, and optionally, control (ancillary) data to the
1016 * receive queue of a socket. If present, m0 must include a packet header
1017 * with total length. Returns 0 if no space in sockbuf or insufficient
1021 sbappendaddr_locked(struct sockbuf *sb, const struct sockaddr *asa,
1022 struct mbuf *m0, struct mbuf *control)
1024 struct mbuf *ctrl_last;
1025 int space = asa->sa_len;
1027 SOCKBUF_LOCK_ASSERT(sb);
1029 if (m0 && (m0->m_flags & M_PKTHDR) == 0)
1030 panic("sbappendaddr_locked");
1032 space += m0->m_pkthdr.len;
1033 space += m_length(control, &ctrl_last);
1035 if (space > sbspace(sb))
1037 return (sbappendaddr_locked_internal(sb, asa, m0, control, ctrl_last));
1041 * Append address and data, and optionally, control (ancillary) data to the
1042 * receive queue of a socket. If present, m0 must include a packet header
1043 * with total length. Returns 0 if insufficient mbufs. Does not validate space
1044 * on the receiving sockbuf.
1047 sbappendaddr_nospacecheck_locked(struct sockbuf *sb, const struct sockaddr *asa,
1048 struct mbuf *m0, struct mbuf *control)
1050 struct mbuf *ctrl_last;
1052 SOCKBUF_LOCK_ASSERT(sb);
1054 ctrl_last = (control == NULL) ? NULL : m_last(control);
1055 return (sbappendaddr_locked_internal(sb, asa, m0, control, ctrl_last));
1059 * Append address and data, and optionally, control (ancillary) data to the
1060 * receive queue of a socket. If present, m0 must include a packet header
1061 * with total length. Returns 0 if no space in sockbuf or insufficient
1065 sbappendaddr(struct sockbuf *sb, const struct sockaddr *asa,
1066 struct mbuf *m0, struct mbuf *control)
1071 retval = sbappendaddr_locked(sb, asa, m0, control);
1077 sbappendcontrol_locked(struct sockbuf *sb, struct mbuf *m0,
1078 struct mbuf *control)
1080 struct mbuf *m, *mlast;
1082 m_clrprotoflags(m0);
1083 m_last(control)->m_next = m0;
1085 SBLASTRECORDCHK(sb);
1087 for (m = control; m->m_next; m = m->m_next)
1091 SBLINKRECORD(sb, control);
1093 sb->sb_mbtail = mlast;
1096 SBLASTRECORDCHK(sb);
1100 sbappendcontrol(struct sockbuf *sb, struct mbuf *m0, struct mbuf *control)
1104 sbappendcontrol_locked(sb, m0, control);
1109 * Append the data in mbuf chain (m) into the socket buffer sb following mbuf
1110 * (n). If (n) is NULL, the buffer is presumed empty.
1112 * When the data is compressed, mbufs in the chain may be handled in one of
1115 * (1) The mbuf may simply be dropped, if it contributes nothing (no data, no
1116 * record boundary, and no change in data type).
1118 * (2) The mbuf may be coalesced -- i.e., data in the mbuf may be copied into
1119 * an mbuf already in the socket buffer. This can occur if an
1120 * appropriate mbuf exists, there is room, both mbufs are not marked as
1121 * not ready, and no merging of data types will occur.
1123 * (3) The mbuf may be appended to the end of the existing mbuf chain.
1125 * If any of the new mbufs is marked as M_EOR, mark the last mbuf appended as
1129 sbcompress(struct sockbuf *sb, struct mbuf *m, struct mbuf *n)
1134 SOCKBUF_LOCK_ASSERT(sb);
1137 eor |= m->m_flags & M_EOR;
1138 if (m->m_len == 0 &&
1140 (((o = m->m_next) || (o = n)) &&
1141 o->m_type == m->m_type))) {
1142 if (sb->sb_lastrecord == m)
1143 sb->sb_lastrecord = m->m_next;
1147 if (n && (n->m_flags & M_EOR) == 0 &&
1149 ((sb->sb_flags & SB_NOCOALESCE) == 0) &&
1150 !(m->m_flags & M_NOTREADY) &&
1151 !(n->m_flags & (M_NOTREADY | M_NOMAP)) &&
1152 !mbuf_has_tls_session(m) &&
1153 !mbuf_has_tls_session(n) &&
1154 m->m_len <= MCLBYTES / 4 && /* XXX: Don't copy too much */
1155 m->m_len <= M_TRAILINGSPACE(n) &&
1156 n->m_type == m->m_type) {
1157 m_copydata(m, 0, m->m_len, mtodo(n, n->m_len));
1158 n->m_len += m->m_len;
1159 sb->sb_ccc += m->m_len;
1160 if (sb->sb_fnrdy == NULL)
1161 sb->sb_acc += m->m_len;
1162 if (m->m_type != MT_DATA && m->m_type != MT_OOBDATA)
1163 /* XXX: Probably don't need.*/
1164 sb->sb_ctl += m->m_len;
1168 if (m->m_len <= MLEN && (m->m_flags & M_NOMAP) &&
1169 (m->m_flags & M_NOTREADY) == 0 &&
1170 !mbuf_has_tls_session(m))
1171 (void)mb_unmapped_compress(m);
1179 m->m_flags &= ~M_EOR;
1184 KASSERT(n != NULL, ("sbcompress: eor && n == NULL"));
1191 * Free all mbufs in a sockbuf. Check that all resources are reclaimed.
1194 sbflush_internal(struct sockbuf *sb)
1197 while (sb->sb_mbcnt) {
1199 * Don't call sbcut(sb, 0) if the leading mbuf is non-empty:
1200 * we would loop forever. Panic instead.
1202 if (sb->sb_ccc == 0 && (sb->sb_mb == NULL || sb->sb_mb->m_len))
1204 m_freem(sbcut_internal(sb, (int)sb->sb_ccc));
1206 KASSERT(sb->sb_ccc == 0 && sb->sb_mb == 0 && sb->sb_mbcnt == 0,
1207 ("%s: ccc %u mb %p mbcnt %u", __func__,
1208 sb->sb_ccc, (void *)sb->sb_mb, sb->sb_mbcnt));
1212 sbflush_locked(struct sockbuf *sb)
1215 SOCKBUF_LOCK_ASSERT(sb);
1216 sbflush_internal(sb);
1220 sbflush(struct sockbuf *sb)
1229 * Cut data from (the front of) a sockbuf.
1231 static struct mbuf *
1232 sbcut_internal(struct sockbuf *sb, int len)
1234 struct mbuf *m, *next, *mfree;
1236 KASSERT(len >= 0, ("%s: len is %d but it is supposed to be >= 0",
1238 KASSERT(len <= sb->sb_ccc, ("%s: len: %d is > ccc: %u",
1239 __func__, len, sb->sb_ccc));
1241 next = (m = sb->sb_mb) ? m->m_nextpkt : 0;
1246 KASSERT(next, ("%s: no next, len %d", __func__, len));
1248 next = m->m_nextpkt;
1250 if (m->m_len > len) {
1251 KASSERT(!(m->m_flags & M_NOTAVAIL),
1252 ("%s: m %p M_NOTAVAIL", __func__, m));
1257 if (sb->sb_sndptroff != 0)
1258 sb->sb_sndptroff -= len;
1259 if (m->m_type != MT_DATA && m->m_type != MT_OOBDATA)
1266 * Do not put M_NOTREADY buffers to the free list, they
1267 * are referenced from outside.
1269 if (m->m_flags & M_NOTREADY)
1281 * Free any zero-length mbufs from the buffer.
1282 * For SOCK_DGRAM sockets such mbufs represent empty records.
1283 * XXX: For SOCK_STREAM sockets such mbufs can appear in the buffer,
1284 * when sosend_generic() needs to send only control data.
1286 while (m && m->m_len == 0) {
1297 m->m_nextpkt = next;
1301 * First part is an inline SB_EMPTY_FIXUP(). Second part makes sure
1302 * sb_lastrecord is up-to-date if we dropped part of the last record.
1306 sb->sb_mbtail = NULL;
1307 sb->sb_lastrecord = NULL;
1308 } else if (m->m_nextpkt == NULL) {
1309 sb->sb_lastrecord = m;
1316 * Drop data from (the front of) a sockbuf.
1319 sbdrop_locked(struct sockbuf *sb, int len)
1322 SOCKBUF_LOCK_ASSERT(sb);
1323 m_freem(sbcut_internal(sb, len));
1327 * Drop data from (the front of) a sockbuf,
1328 * and return it to caller.
1331 sbcut_locked(struct sockbuf *sb, int len)
1334 SOCKBUF_LOCK_ASSERT(sb);
1335 return (sbcut_internal(sb, len));
1339 sbdrop(struct sockbuf *sb, int len)
1344 mfree = sbcut_internal(sb, len);
1351 sbsndptr_noadv(struct sockbuf *sb, uint32_t off, uint32_t *moff)
1355 KASSERT(sb->sb_mb != NULL, ("%s: sb_mb is NULL", __func__));
1356 if (sb->sb_sndptr == NULL || sb->sb_sndptroff > off) {
1358 if (sb->sb_sndptr == NULL) {
1359 sb->sb_sndptr = sb->sb_mb;
1360 sb->sb_sndptroff = 0;
1365 off -= sb->sb_sndptroff;
1372 sbsndptr_adv(struct sockbuf *sb, struct mbuf *mb, uint32_t len)
1375 * A small copy was done, advance forward the sb_sbsndptr to cover
1380 if (mb != sb->sb_sndptr) {
1381 /* Did not copyout at the same mbuf */
1385 while (m && (len > 0)) {
1386 if (len >= m->m_len) {
1389 sb->sb_sndptroff += m->m_len;
1390 sb->sb_sndptr = m->m_next;
1400 * Return the first mbuf and the mbuf data offset for the provided
1401 * send offset without changing the "sb_sndptroff" field.
1404 sbsndmbuf(struct sockbuf *sb, u_int off, u_int *moff)
1408 KASSERT(sb->sb_mb != NULL, ("%s: sb_mb is NULL", __func__));
1411 * If the "off" is below the stored offset, which happens on
1412 * retransmits, just use "sb_mb":
1414 if (sb->sb_sndptr == NULL || sb->sb_sndptroff > off) {
1418 off -= sb->sb_sndptroff;
1420 while (off > 0 && m != NULL) {
1431 * Drop a record off the front of a sockbuf and move the next record to the
1435 sbdroprecord_locked(struct sockbuf *sb)
1439 SOCKBUF_LOCK_ASSERT(sb);
1443 sb->sb_mb = m->m_nextpkt;
1453 * Drop a record off the front of a sockbuf and move the next record to the
1457 sbdroprecord(struct sockbuf *sb)
1461 sbdroprecord_locked(sb);
1466 * Create a "control" mbuf containing the specified data with the specified
1467 * type for presentation on a socket buffer.
1470 sbcreatecontrol(caddr_t p, int size, int type, int level)
1475 if (CMSG_SPACE((u_int)size) > MCLBYTES)
1476 return ((struct mbuf *) NULL);
1477 if (CMSG_SPACE((u_int)size) > MLEN)
1478 m = m_getcl(M_NOWAIT, MT_CONTROL, 0);
1480 m = m_get(M_NOWAIT, MT_CONTROL);
1482 return ((struct mbuf *) NULL);
1483 cp = mtod(m, struct cmsghdr *);
1485 KASSERT(CMSG_SPACE((u_int)size) <= M_TRAILINGSPACE(m),
1486 ("sbcreatecontrol: short mbuf"));
1488 * Don't leave the padding between the msg header and the
1489 * cmsg data and the padding after the cmsg data un-initialized.
1491 bzero(cp, CMSG_SPACE((u_int)size));
1493 (void)memcpy(CMSG_DATA(cp), p, size);
1494 m->m_len = CMSG_SPACE(size);
1495 cp->cmsg_len = CMSG_LEN(size);
1496 cp->cmsg_level = level;
1497 cp->cmsg_type = type;
1502 * This does the same for socket buffers that sotoxsocket does for sockets:
1503 * generate an user-format data structure describing the socket buffer. Note
1504 * that the xsockbuf structure, since it is always embedded in a socket, does
1505 * not include a self pointer nor a length. We make this entry point public
1506 * in case some other mechanism needs it.
1509 sbtoxsockbuf(struct sockbuf *sb, struct xsockbuf *xsb)
1512 xsb->sb_cc = sb->sb_ccc;
1513 xsb->sb_hiwat = sb->sb_hiwat;
1514 xsb->sb_mbcnt = sb->sb_mbcnt;
1515 xsb->sb_mcnt = sb->sb_mcnt;
1516 xsb->sb_ccnt = sb->sb_ccnt;
1517 xsb->sb_mbmax = sb->sb_mbmax;
1518 xsb->sb_lowat = sb->sb_lowat;
1519 xsb->sb_flags = sb->sb_flags;
1520 xsb->sb_timeo = sb->sb_timeo;
1523 /* This takes the place of kern.maxsockbuf, which moved to kern.ipc. */
1525 SYSCTL_INT(_kern, KERN_DUMMY, dummy, CTLFLAG_RW, &dummy, 0, "");
1526 SYSCTL_OID(_kern_ipc, KIPC_MAXSOCKBUF, maxsockbuf, CTLTYPE_ULONG|CTLFLAG_RW,
1527 &sb_max, 0, sysctl_handle_sb_max, "LU", "Maximum socket buffer size");
1528 SYSCTL_ULONG(_kern_ipc, KIPC_SOCKBUF_WASTE, sockbuf_waste_factor, CTLFLAG_RW,
1529 &sb_efficiency, 0, "Socket buffer size waste factor");