xref: /freebsd/sys/kern/uipc_sockbuf.c (revision 7fdf597e96a02165cfe22ff357b857d5fa15ed8a)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1982, 1986, 1988, 1990, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
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.
18  *
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
29  * SUCH DAMAGE.
30  */
31 
32 #include <sys/cdefs.h>
33 #include "opt_kern_tls.h"
34 #include "opt_param.h"
35 
36 #include <sys/param.h>
37 #include <sys/aio.h> /* for aio_swake proto */
38 #include <sys/kernel.h>
39 #include <sys/ktls.h>
40 #include <sys/lock.h>
41 #include <sys/malloc.h>
42 #include <sys/mbuf.h>
43 #include <sys/msan.h>
44 #include <sys/mutex.h>
45 #include <sys/proc.h>
46 #include <sys/protosw.h>
47 #include <sys/resourcevar.h>
48 #include <sys/signalvar.h>
49 #include <sys/socket.h>
50 #include <sys/socketvar.h>
51 #include <sys/sx.h>
52 #include <sys/sysctl.h>
53 
54 #include <netinet/in.h>
55 
56 /*
57  * Function pointer set by the AIO routines so that the socket buffer code
58  * can call back into the AIO module if it is loaded.
59  */
60 void	(*aio_swake)(struct socket *, struct sockbuf *);
61 
62 /*
63  * Primitive routines for operating on socket buffers
64  */
65 
66 #define	BUF_MAX_ADJ(_sz)	(((u_quad_t)(_sz)) * MCLBYTES / (MSIZE + MCLBYTES))
67 
68 u_long	sb_max = SB_MAX;
69 u_long sb_max_adj = BUF_MAX_ADJ(SB_MAX);
70 
71 static	u_long sb_efficiency = 8;	/* parameter for sbreserve() */
72 
73 #ifdef KERN_TLS
74 static void	sbcompress_ktls_rx(struct sockbuf *sb, struct mbuf *m,
75     struct mbuf *n);
76 #endif
77 static struct mbuf	*sbcut_internal(struct sockbuf *sb, int len);
78 static void	sbflush_internal(struct sockbuf *sb);
79 
80 /*
81  * Our own version of m_clrprotoflags(), that can preserve M_NOTREADY.
82  */
83 static void
84 sbm_clrprotoflags(struct mbuf *m, int flags)
85 {
86 	int mask;
87 
88 	mask = ~M_PROTOFLAGS;
89 	if (flags & PRUS_NOTREADY)
90 		mask |= M_NOTREADY;
91 	while (m) {
92 		m->m_flags &= mask;
93 		m = m->m_next;
94 	}
95 }
96 
97 /*
98  * Compress M_NOTREADY mbufs after they have been readied by sbready().
99  *
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
104  * ready.
105  */
106 static void
107 sbready_compress(struct sockbuf *sb, struct mbuf *m0, struct mbuf *end)
108 {
109 	struct mbuf *m, *n;
110 	int ext_size;
111 
112 	SOCKBUF_LOCK_ASSERT(sb);
113 
114 	if ((sb->sb_flags & SB_NOCOALESCE) != 0)
115 		return;
116 
117 	for (m = m0; m != end; m = m->m_next) {
118 		MPASS((m->m_flags & M_NOTREADY) == 0);
119 		/*
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
125 		 * 'm'.
126 		 */
127 		n = m->m_next;
128 #ifdef KERN_TLS
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;
136 
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;
145 				m->m_len += hdr_len;
146 				n->m_epg_hdrlen = 0;
147 				n->m_len -= hdr_len;
148 			}
149 		}
150 #endif
151 
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;
158 		}
159 
160 		while ((n != NULL) && (n != end) && (m->m_flags & M_EOR) == 0 &&
161 		    M_WRITABLE(m) &&
162 		    (m->m_flags & M_EXTPG) == 0 &&
163 		    !mbuf_has_tls_session(n) &&
164 		    !mbuf_has_tls_session(m) &&
165 		    n->m_len <= MCLBYTES / 4 && /* XXX: Don't copy too much */
166 		    n->m_len <= M_TRAILINGSPACE(m) &&
167 		    m->m_type == n->m_type) {
168 			KASSERT(sb->sb_lastrecord != n,
169 		    ("%s: merging start of record (%p) into previous mbuf (%p)",
170 			    __func__, n, m));
171 			m_copydata(n, 0, n->m_len, mtodo(m, m->m_len));
172 			m->m_len += n->m_len;
173 			m->m_next = n->m_next;
174 			m->m_flags |= n->m_flags & M_EOR;
175 			if (sb->sb_mbtail == n)
176 				sb->sb_mbtail = m;
177 
178 			sb->sb_mbcnt -= MSIZE;
179 			if (n->m_flags & M_EXT)
180 				sb->sb_mbcnt -= n->m_ext.ext_size;
181 			m_free(n);
182 			n = m->m_next;
183 		}
184 	}
185 	SBLASTRECORDCHK(sb);
186 	SBLASTMBUFCHK(sb);
187 }
188 
189 /*
190  * Mark ready "count" units of I/O starting with "m".  Most mbufs
191  * count as a single unit of I/O except for M_EXTPG mbufs which
192  * are backed by multiple pages.
193  */
194 int
195 sbready(struct sockbuf *sb, struct mbuf *m0, int count)
196 {
197 	struct mbuf *m;
198 	u_int blocker;
199 
200 	SOCKBUF_LOCK_ASSERT(sb);
201 	KASSERT(sb->sb_fnrdy != NULL, ("%s: sb %p NULL fnrdy", __func__, sb));
202 	KASSERT(count > 0, ("%s: invalid count %d", __func__, count));
203 
204 	m = m0;
205 	blocker = (sb->sb_fnrdy == m) ? M_BLOCKED : 0;
206 
207 	while (count > 0) {
208 		KASSERT(m->m_flags & M_NOTREADY,
209 		    ("%s: m %p !M_NOTREADY", __func__, m));
210 		if ((m->m_flags & M_EXTPG) != 0 && m->m_epg_npgs != 0) {
211 			if (count < m->m_epg_nrdy) {
212 				m->m_epg_nrdy -= count;
213 				count = 0;
214 				break;
215 			}
216 			count -= m->m_epg_nrdy;
217 			m->m_epg_nrdy = 0;
218 		} else
219 			count--;
220 
221 		m->m_flags &= ~(M_NOTREADY | blocker);
222 		if (blocker)
223 			sb->sb_acc += m->m_len;
224 		m = m->m_next;
225 	}
226 
227 	/*
228 	 * If the first mbuf is still not fully ready because only
229 	 * some of its backing pages were readied, no further progress
230 	 * can be made.
231 	 */
232 	if (m0 == m) {
233 		MPASS(m->m_flags & M_NOTREADY);
234 		return (EINPROGRESS);
235 	}
236 
237 	if (!blocker) {
238 		sbready_compress(sb, m0, m);
239 		return (EINPROGRESS);
240 	}
241 
242 	/* This one was blocking all the queue. */
243 	for (; m && (m->m_flags & M_NOTREADY) == 0; m = m->m_next) {
244 		KASSERT(m->m_flags & M_BLOCKED,
245 		    ("%s: m %p !M_BLOCKED", __func__, m));
246 		m->m_flags &= ~M_BLOCKED;
247 		sb->sb_acc += m->m_len;
248 	}
249 
250 	sb->sb_fnrdy = m;
251 	sbready_compress(sb, m0, m);
252 
253 	return (0);
254 }
255 
256 /*
257  * Adjust sockbuf state reflecting allocation of m.
258  */
259 void
260 sballoc(struct sockbuf *sb, struct mbuf *m)
261 {
262 
263 	SOCKBUF_LOCK_ASSERT(sb);
264 
265 	sb->sb_ccc += m->m_len;
266 
267 	if (sb->sb_fnrdy == NULL) {
268 		if (m->m_flags & M_NOTREADY)
269 			sb->sb_fnrdy = m;
270 		else
271 			sb->sb_acc += m->m_len;
272 	} else
273 		m->m_flags |= M_BLOCKED;
274 
275 	if (m->m_type != MT_DATA && m->m_type != MT_OOBDATA)
276 		sb->sb_ctl += m->m_len;
277 
278 	sb->sb_mbcnt += MSIZE;
279 
280 	if (m->m_flags & M_EXT)
281 		sb->sb_mbcnt += m->m_ext.ext_size;
282 }
283 
284 /*
285  * Adjust sockbuf state reflecting freeing of m.
286  */
287 void
288 sbfree(struct sockbuf *sb, struct mbuf *m)
289 {
290 
291 #if 0	/* XXX: not yet: soclose() call path comes here w/o lock. */
292 	SOCKBUF_LOCK_ASSERT(sb);
293 #endif
294 
295 	sb->sb_ccc -= m->m_len;
296 
297 	if (!(m->m_flags & M_NOTAVAIL))
298 		sb->sb_acc -= m->m_len;
299 
300 	if (m == sb->sb_fnrdy) {
301 		struct mbuf *n;
302 
303 		KASSERT(m->m_flags & M_NOTREADY,
304 		    ("%s: m %p !M_NOTREADY", __func__, m));
305 
306 		n = m->m_next;
307 		while (n != NULL && !(n->m_flags & M_NOTREADY)) {
308 			n->m_flags &= ~M_BLOCKED;
309 			sb->sb_acc += n->m_len;
310 			n = n->m_next;
311 		}
312 		sb->sb_fnrdy = n;
313 	}
314 
315 	if (m->m_type != MT_DATA && m->m_type != MT_OOBDATA)
316 		sb->sb_ctl -= m->m_len;
317 
318 	sb->sb_mbcnt -= MSIZE;
319 	if (m->m_flags & M_EXT)
320 		sb->sb_mbcnt -= m->m_ext.ext_size;
321 
322 	if (sb->sb_sndptr == m) {
323 		sb->sb_sndptr = NULL;
324 		sb->sb_sndptroff = 0;
325 	}
326 	if (sb->sb_sndptroff != 0)
327 		sb->sb_sndptroff -= m->m_len;
328 }
329 
330 #ifdef KERN_TLS
331 /*
332  * Similar to sballoc/sbfree but does not adjust state associated with
333  * the sb_mb chain such as sb_fnrdy or sb_sndptr*.  Also assumes mbufs
334  * are not ready.
335  */
336 void
337 sballoc_ktls_rx(struct sockbuf *sb, struct mbuf *m)
338 {
339 
340 	SOCKBUF_LOCK_ASSERT(sb);
341 
342 	sb->sb_ccc += m->m_len;
343 	sb->sb_tlscc += m->m_len;
344 
345 	sb->sb_mbcnt += MSIZE;
346 
347 	if (m->m_flags & M_EXT)
348 		sb->sb_mbcnt += m->m_ext.ext_size;
349 }
350 
351 void
352 sbfree_ktls_rx(struct sockbuf *sb, struct mbuf *m)
353 {
354 
355 #if 0	/* XXX: not yet: soclose() call path comes here w/o lock. */
356 	SOCKBUF_LOCK_ASSERT(sb);
357 #endif
358 
359 	sb->sb_ccc -= m->m_len;
360 	sb->sb_tlscc -= m->m_len;
361 
362 	sb->sb_mbcnt -= MSIZE;
363 
364 	if (m->m_flags & M_EXT)
365 		sb->sb_mbcnt -= m->m_ext.ext_size;
366 }
367 #endif
368 
369 /*
370  * Socantsendmore indicates that no more data will be sent on the socket; it
371  * would normally be applied to a socket when the user informs the system
372  * that no more data is to be sent, by the protocol code (in case
373  * PRU_SHUTDOWN).  Socantrcvmore indicates that no more data will be
374  * received, and will normally be applied to the socket by a protocol when it
375  * detects that the peer will send no more data.  Data queued for reading in
376  * the socket may yet be read.
377  */
378 void
379 socantsendmore_locked(struct socket *so)
380 {
381 
382 	SOCK_SENDBUF_LOCK_ASSERT(so);
383 
384 	so->so_snd.sb_state |= SBS_CANTSENDMORE;
385 	sowwakeup_locked(so);
386 	SOCK_SENDBUF_UNLOCK_ASSERT(so);
387 }
388 
389 void
390 socantsendmore(struct socket *so)
391 {
392 
393 	SOCK_SENDBUF_LOCK(so);
394 	socantsendmore_locked(so);
395 	SOCK_SENDBUF_UNLOCK_ASSERT(so);
396 }
397 
398 void
399 socantrcvmore_locked(struct socket *so)
400 {
401 
402 	SOCK_RECVBUF_LOCK_ASSERT(so);
403 
404 	so->so_rcv.sb_state |= SBS_CANTRCVMORE;
405 #ifdef KERN_TLS
406 	if (so->so_rcv.sb_flags & SB_TLS_RX)
407 		ktls_check_rx(&so->so_rcv);
408 #endif
409 	sorwakeup_locked(so);
410 	SOCK_RECVBUF_UNLOCK_ASSERT(so);
411 }
412 
413 void
414 socantrcvmore(struct socket *so)
415 {
416 
417 	SOCK_RECVBUF_LOCK(so);
418 	socantrcvmore_locked(so);
419 	SOCK_RECVBUF_UNLOCK_ASSERT(so);
420 }
421 
422 void
423 soroverflow_locked(struct socket *so)
424 {
425 
426 	SOCK_RECVBUF_LOCK_ASSERT(so);
427 
428 	if (so->so_options & SO_RERROR) {
429 		so->so_rerror = ENOBUFS;
430 		sorwakeup_locked(so);
431 	} else
432 		SOCK_RECVBUF_UNLOCK(so);
433 
434 	SOCK_RECVBUF_UNLOCK_ASSERT(so);
435 }
436 
437 void
438 soroverflow(struct socket *so)
439 {
440 
441 	SOCK_RECVBUF_LOCK(so);
442 	soroverflow_locked(so);
443 	SOCK_RECVBUF_UNLOCK_ASSERT(so);
444 }
445 
446 /*
447  * Wait for data to arrive at/drain from a socket buffer.
448  */
449 int
450 sbwait(struct socket *so, sb_which which)
451 {
452 	struct sockbuf *sb;
453 
454 	SOCK_BUF_LOCK_ASSERT(so, which);
455 
456 	sb = sobuf(so, which);
457 	sb->sb_flags |= SB_WAIT;
458 	return (msleep_sbt(&sb->sb_acc, soeventmtx(so, which),
459 	    (sb->sb_flags & SB_NOINTR) ? PSOCK : PSOCK | PCATCH, "sbwait",
460 	    sb->sb_timeo, 0, 0));
461 }
462 
463 /*
464  * Wakeup processes waiting on a socket buffer.  Do asynchronous notification
465  * via SIGIO if the socket has the SS_ASYNC flag set.
466  *
467  * Called with the socket buffer lock held; will release the lock by the end
468  * of the function.  This allows the caller to acquire the socket buffer lock
469  * while testing for the need for various sorts of wakeup and hold it through
470  * to the point where it's no longer required.  We currently hold the lock
471  * through calls out to other subsystems (with the exception of kqueue), and
472  * then release it to avoid lock order issues.  It's not clear that's
473  * correct.
474  */
475 static __always_inline void
476 sowakeup(struct socket *so, const sb_which which)
477 {
478 	struct sockbuf *sb;
479 	int ret;
480 
481 	SOCK_BUF_LOCK_ASSERT(so, which);
482 
483 	sb = sobuf(so, which);
484 	selwakeuppri(sb->sb_sel, PSOCK);
485 	if (!SEL_WAITING(sb->sb_sel))
486 		sb->sb_flags &= ~SB_SEL;
487 	if (sb->sb_flags & SB_WAIT) {
488 		sb->sb_flags &= ~SB_WAIT;
489 		wakeup(&sb->sb_acc);
490 	}
491 	KNOTE_LOCKED(&sb->sb_sel->si_note, 0);
492 	if (sb->sb_upcall != NULL) {
493 		ret = sb->sb_upcall(so, sb->sb_upcallarg, M_NOWAIT);
494 		if (ret == SU_ISCONNECTED) {
495 			KASSERT(sb == &so->so_rcv,
496 			    ("SO_SND upcall returned SU_ISCONNECTED"));
497 			soupcall_clear(so, SO_RCV);
498 		}
499 	} else
500 		ret = SU_OK;
501 	if (sb->sb_flags & SB_AIO)
502 		sowakeup_aio(so, which);
503 	SOCK_BUF_UNLOCK(so, which);
504 	if (ret == SU_ISCONNECTED)
505 		soisconnected(so);
506 	if ((so->so_state & SS_ASYNC) && so->so_sigio != NULL)
507 		pgsigio(&so->so_sigio, SIGIO, 0);
508 	SOCK_BUF_UNLOCK_ASSERT(so, which);
509 }
510 
511 static void
512 splice_push(struct socket *so)
513 {
514 	struct so_splice *sp;
515 
516 	SOCK_RECVBUF_LOCK_ASSERT(so);
517 
518 	sp = so->so_splice;
519 	mtx_lock(&sp->mtx);
520 	SOCK_RECVBUF_UNLOCK(so);
521 	so_splice_dispatch(sp);
522 }
523 
524 static void
525 splice_pull(struct socket *so)
526 {
527 	struct so_splice *sp;
528 
529 	SOCK_SENDBUF_LOCK_ASSERT(so);
530 
531 	sp = so->so_splice_back;
532 	mtx_lock(&sp->mtx);
533 	SOCK_SENDBUF_UNLOCK(so);
534 	so_splice_dispatch(sp);
535 }
536 
537 /*
538  * Do we need to notify the other side when I/O is possible?
539  */
540 static __always_inline bool
541 sb_notify(const struct sockbuf *sb)
542 {
543 	return ((sb->sb_flags & (SB_WAIT | SB_SEL | SB_ASYNC |
544 	    SB_UPCALL | SB_AIO | SB_KNOTE)) != 0);
545 }
546 
547 void
548 sorwakeup_locked(struct socket *so)
549 {
550 	SOCK_RECVBUF_LOCK_ASSERT(so);
551 	if (so->so_rcv.sb_flags & SB_SPLICED)
552 		splice_push(so);
553 	else if (sb_notify(&so->so_rcv))
554 		sowakeup(so, SO_RCV);
555 	else
556 		SOCK_RECVBUF_UNLOCK(so);
557 }
558 
559 void
560 sowwakeup_locked(struct socket *so)
561 {
562 	SOCK_SENDBUF_LOCK_ASSERT(so);
563 	if (so->so_snd.sb_flags & SB_SPLICED)
564 		splice_pull(so);
565 	else if (sb_notify(&so->so_snd))
566 		sowakeup(so, SO_SND);
567 	else
568 		SOCK_SENDBUF_UNLOCK(so);
569 }
570 
571 /*
572  * Socket buffer (struct sockbuf) utility routines.
573  *
574  * Each socket contains two socket buffers: one for sending data and one for
575  * receiving data.  Each buffer contains a queue of mbufs, information about
576  * the number of mbufs and amount of data in the queue, and other fields
577  * allowing select() statements and notification on data availability to be
578  * implemented.
579  *
580  * Data stored in a socket buffer is maintained as a list of records.  Each
581  * record is a list of mbufs chained together with the m_next field.  Records
582  * are chained together with the m_nextpkt field. The upper level routine
583  * soreceive() expects the following conventions to be observed when placing
584  * information in the receive buffer:
585  *
586  * 1. If the protocol requires each message be preceded by the sender's name,
587  *    then a record containing that name must be present before any
588  *    associated data (mbuf's must be of type MT_SONAME).
589  * 2. If the protocol supports the exchange of ``access rights'' (really just
590  *    additional data associated with the message), and there are ``rights''
591  *    to be received, then a record containing this data should be present
592  *    (mbuf's must be of type MT_RIGHTS).
593  * 3. If a name or rights record exists, then it must be followed by a data
594  *    record, perhaps of zero length.
595  *
596  * Before using a new socket structure it is first necessary to reserve
597  * buffer space to the socket, by calling sbreserve().  This should commit
598  * some of the available buffer space in the system buffer pool for the
599  * socket (currently, it does nothing but enforce limits).  The space should
600  * be released by calling sbrelease() when the socket is destroyed.
601  */
602 int
603 soreserve(struct socket *so, u_long sndcc, u_long rcvcc)
604 {
605 	struct thread *td = curthread;
606 
607 	SOCK_SENDBUF_LOCK(so);
608 	SOCK_RECVBUF_LOCK(so);
609 	if (sbreserve_locked(so, SO_SND, sndcc, td) == 0)
610 		goto bad;
611 	if (sbreserve_locked(so, SO_RCV, rcvcc, td) == 0)
612 		goto bad2;
613 	if (so->so_rcv.sb_lowat == 0)
614 		so->so_rcv.sb_lowat = 1;
615 	if (so->so_snd.sb_lowat == 0)
616 		so->so_snd.sb_lowat = MCLBYTES;
617 	if (so->so_snd.sb_lowat > so->so_snd.sb_hiwat)
618 		so->so_snd.sb_lowat = so->so_snd.sb_hiwat;
619 	SOCK_RECVBUF_UNLOCK(so);
620 	SOCK_SENDBUF_UNLOCK(so);
621 	return (0);
622 bad2:
623 	sbrelease_locked(so, SO_SND);
624 bad:
625 	SOCK_RECVBUF_UNLOCK(so);
626 	SOCK_SENDBUF_UNLOCK(so);
627 	return (ENOBUFS);
628 }
629 
630 static int
631 sysctl_handle_sb_max(SYSCTL_HANDLER_ARGS)
632 {
633 	int error = 0;
634 	u_long tmp_sb_max = sb_max;
635 
636 	error = sysctl_handle_long(oidp, &tmp_sb_max, arg2, req);
637 	if (error || !req->newptr)
638 		return (error);
639 	if (tmp_sb_max < MSIZE + MCLBYTES)
640 		return (EINVAL);
641 	sb_max = tmp_sb_max;
642 	sb_max_adj = BUF_MAX_ADJ(sb_max);
643 	return (0);
644 }
645 
646 /*
647  * Allot mbufs to a sockbuf.  Attempt to scale mbmax so that mbcnt doesn't
648  * become limiting if buffering efficiency is near the normal case.
649  */
650 bool
651 sbreserve_locked_limit(struct socket *so, sb_which which, u_long cc,
652     u_long buf_max, struct thread *td)
653 {
654 	struct sockbuf *sb = sobuf(so, which);
655 	rlim_t sbsize_limit;
656 
657 	SOCK_BUF_LOCK_ASSERT(so, which);
658 
659 	/*
660 	 * When a thread is passed, we take into account the thread's socket
661 	 * buffer size limit.  The caller will generally pass curthread, but
662 	 * in the TCP input path, NULL will be passed to indicate that no
663 	 * appropriate thread resource limits are available.  In that case,
664 	 * we don't apply a process limit.
665 	 */
666 	if (cc > BUF_MAX_ADJ(buf_max))
667 		return (false);
668 	if (td != NULL) {
669 		sbsize_limit = lim_cur(td, RLIMIT_SBSIZE);
670 	} else
671 		sbsize_limit = RLIM_INFINITY;
672 	if (!chgsbsize(so->so_cred->cr_uidinfo, &sb->sb_hiwat, cc,
673 	    sbsize_limit))
674 		return (false);
675 	sb->sb_mbmax = min(cc * sb_efficiency, buf_max);
676 	if (sb->sb_lowat > sb->sb_hiwat)
677 		sb->sb_lowat = sb->sb_hiwat;
678 	return (true);
679 }
680 
681 bool
682 sbreserve_locked(struct socket *so, sb_which which, u_long cc,
683     struct thread *td)
684 {
685 	return (sbreserve_locked_limit(so, which, cc, sb_max, td));
686 }
687 
688 int
689 sbsetopt(struct socket *so, struct sockopt *sopt)
690 {
691 	struct sockbuf *sb;
692 	sb_which wh;
693 	short *flags;
694 	u_int cc, *hiwat, *lowat;
695 	int error, optval;
696 
697 	error = sooptcopyin(sopt, &optval, sizeof optval, sizeof optval);
698 	if (error != 0)
699 		return (error);
700 
701 	/*
702 	 * Values < 1 make no sense for any of these options,
703 	 * so disallow them.
704 	 */
705 	if (optval < 1)
706 		return (EINVAL);
707 	cc = optval;
708 
709 	sb = NULL;
710 	SOCK_LOCK(so);
711 	if (SOLISTENING(so)) {
712 		switch (sopt->sopt_name) {
713 			case SO_SNDLOWAT:
714 			case SO_SNDBUF:
715 				lowat = &so->sol_sbsnd_lowat;
716 				hiwat = &so->sol_sbsnd_hiwat;
717 				flags = &so->sol_sbsnd_flags;
718 				break;
719 			case SO_RCVLOWAT:
720 			case SO_RCVBUF:
721 				lowat = &so->sol_sbrcv_lowat;
722 				hiwat = &so->sol_sbrcv_hiwat;
723 				flags = &so->sol_sbrcv_flags;
724 				break;
725 		}
726 	} else {
727 		switch (sopt->sopt_name) {
728 			case SO_SNDLOWAT:
729 			case SO_SNDBUF:
730 				sb = &so->so_snd;
731 				wh = SO_SND;
732 				break;
733 			case SO_RCVLOWAT:
734 			case SO_RCVBUF:
735 				sb = &so->so_rcv;
736 				wh = SO_RCV;
737 				break;
738 		}
739 		flags = &sb->sb_flags;
740 		hiwat = &sb->sb_hiwat;
741 		lowat = &sb->sb_lowat;
742 		SOCK_BUF_LOCK(so, wh);
743 	}
744 
745 	error = 0;
746 	switch (sopt->sopt_name) {
747 	case SO_SNDBUF:
748 	case SO_RCVBUF:
749 		if (SOLISTENING(so)) {
750 			if (cc > sb_max_adj) {
751 				error = ENOBUFS;
752 				break;
753 			}
754 			*hiwat = cc;
755 			if (*lowat > *hiwat)
756 				*lowat = *hiwat;
757 		} else {
758 			if (!sbreserve_locked(so, wh, cc, curthread))
759 				error = ENOBUFS;
760 		}
761 		if (error == 0)
762 			*flags &= ~SB_AUTOSIZE;
763 		break;
764 	case SO_SNDLOWAT:
765 	case SO_RCVLOWAT:
766 		/*
767 		 * Make sure the low-water is never greater than the
768 		 * high-water.
769 		 */
770 		*lowat = (cc > *hiwat) ? *hiwat : cc;
771 		break;
772 	}
773 
774 	if (!SOLISTENING(so))
775 		SOCK_BUF_UNLOCK(so, wh);
776 	SOCK_UNLOCK(so);
777 	return (error);
778 }
779 
780 /*
781  * Free mbufs held by a socket, and reserved mbuf space.
782  */
783 static void
784 sbrelease_internal(struct socket *so, sb_which which)
785 {
786 	struct sockbuf *sb = sobuf(so, which);
787 
788 	sbflush_internal(sb);
789 	(void)chgsbsize(so->so_cred->cr_uidinfo, &sb->sb_hiwat, 0,
790 	    RLIM_INFINITY);
791 	sb->sb_mbmax = 0;
792 }
793 
794 void
795 sbrelease_locked(struct socket *so, sb_which which)
796 {
797 
798 	SOCK_BUF_LOCK_ASSERT(so, which);
799 
800 	sbrelease_internal(so, which);
801 }
802 
803 void
804 sbrelease(struct socket *so, sb_which which)
805 {
806 
807 	SOCK_BUF_LOCK(so, which);
808 	sbrelease_locked(so, which);
809 	SOCK_BUF_UNLOCK(so, which);
810 }
811 
812 void
813 sbdestroy(struct socket *so, sb_which which)
814 {
815 #ifdef KERN_TLS
816 	struct sockbuf *sb = sobuf(so, which);
817 
818 	if (sb->sb_tls_info != NULL)
819 		ktls_free(sb->sb_tls_info);
820 	sb->sb_tls_info = NULL;
821 #endif
822 	sbrelease_internal(so, which);
823 }
824 
825 /*
826  * Routines to add and remove data from an mbuf queue.
827  *
828  * The routines sbappend() or sbappendrecord() are normally called to append
829  * new mbufs to a socket buffer, after checking that adequate space is
830  * available, comparing the function sbspace() with the amount of data to be
831  * added.  sbappendrecord() differs from sbappend() in that data supplied is
832  * treated as the beginning of a new record.  To place a sender's address,
833  * optional access rights, and data in a socket receive buffer,
834  * sbappendaddr() should be used.  To place access rights and data in a
835  * socket receive buffer, sbappendrights() should be used.  In either case,
836  * the new data begins a new record.  Note that unlike sbappend() and
837  * sbappendrecord(), these routines check for the caller that there will be
838  * enough space to store the data.  Each fails if there is not enough space,
839  * or if it cannot find mbufs to store additional information in.
840  *
841  * Reliable protocols may use the socket send buffer to hold data awaiting
842  * acknowledgement.  Data is normally copied from a socket send buffer in a
843  * protocol with m_copy for output to a peer, and then removing the data from
844  * the socket buffer with sbdrop() or sbdroprecord() when the data is
845  * acknowledged by the peer.
846  */
847 #ifdef SOCKBUF_DEBUG
848 void
849 sblastrecordchk(struct sockbuf *sb, const char *file, int line)
850 {
851 	struct mbuf *m = sb->sb_mb;
852 
853 	SOCKBUF_LOCK_ASSERT(sb);
854 
855 	while (m && m->m_nextpkt)
856 		m = m->m_nextpkt;
857 
858 	if (m != sb->sb_lastrecord) {
859 		printf("%s: sb_mb %p sb_lastrecord %p last %p\n",
860 			__func__, sb->sb_mb, sb->sb_lastrecord, m);
861 		printf("packet chain:\n");
862 		for (m = sb->sb_mb; m != NULL; m = m->m_nextpkt)
863 			printf("\t%p\n", m);
864 		panic("%s from %s:%u", __func__, file, line);
865 	}
866 }
867 
868 void
869 sblastmbufchk(struct sockbuf *sb, const char *file, int line)
870 {
871 	struct mbuf *m = sb->sb_mb;
872 	struct mbuf *n;
873 
874 	SOCKBUF_LOCK_ASSERT(sb);
875 
876 	while (m && m->m_nextpkt)
877 		m = m->m_nextpkt;
878 
879 	while (m && m->m_next)
880 		m = m->m_next;
881 
882 	if (m != sb->sb_mbtail) {
883 		printf("%s: sb_mb %p sb_mbtail %p last %p\n",
884 			__func__, sb->sb_mb, sb->sb_mbtail, m);
885 		printf("packet tree:\n");
886 		for (m = sb->sb_mb; m != NULL; m = m->m_nextpkt) {
887 			printf("\t");
888 			for (n = m; n != NULL; n = n->m_next)
889 				printf("%p ", n);
890 			printf("\n");
891 		}
892 		panic("%s from %s:%u", __func__, file, line);
893 	}
894 
895 #ifdef KERN_TLS
896 	m = sb->sb_mtls;
897 	while (m && m->m_next)
898 		m = m->m_next;
899 
900 	if (m != sb->sb_mtlstail) {
901 		printf("%s: sb_mtls %p sb_mtlstail %p last %p\n",
902 			__func__, sb->sb_mtls, sb->sb_mtlstail, m);
903 		printf("TLS packet tree:\n");
904 		printf("\t");
905 		for (m = sb->sb_mtls; m != NULL; m = m->m_next) {
906 			printf("%p ", m);
907 		}
908 		printf("\n");
909 		panic("%s from %s:%u", __func__, file, line);
910 	}
911 #endif
912 }
913 #endif /* SOCKBUF_DEBUG */
914 
915 #define SBLINKRECORD(sb, m0) do {					\
916 	SOCKBUF_LOCK_ASSERT(sb);					\
917 	if ((sb)->sb_lastrecord != NULL)				\
918 		(sb)->sb_lastrecord->m_nextpkt = (m0);			\
919 	else								\
920 		(sb)->sb_mb = (m0);					\
921 	(sb)->sb_lastrecord = (m0);					\
922 } while (/*CONSTCOND*/0)
923 
924 /*
925  * Append mbuf chain m to the last record in the socket buffer sb.  The
926  * additional space associated the mbuf chain is recorded in sb.  Empty mbufs
927  * are discarded and mbufs are compacted where possible.
928  */
929 void
930 sbappend_locked(struct sockbuf *sb, struct mbuf *m, int flags)
931 {
932 	struct mbuf *n;
933 
934 	SOCKBUF_LOCK_ASSERT(sb);
935 
936 	if (m == NULL)
937 		return;
938 	kmsan_check_mbuf(m, "sbappend");
939 	sbm_clrprotoflags(m, flags);
940 	SBLASTRECORDCHK(sb);
941 	n = sb->sb_mb;
942 	if (n) {
943 		while (n->m_nextpkt)
944 			n = n->m_nextpkt;
945 		do {
946 			if (n->m_flags & M_EOR) {
947 				sbappendrecord_locked(sb, m); /* XXXXXX!!!! */
948 				return;
949 			}
950 		} while (n->m_next && (n = n->m_next));
951 	} else {
952 		/*
953 		 * XXX Would like to simply use sb_mbtail here, but
954 		 * XXX I need to verify that I won't miss an EOR that
955 		 * XXX way.
956 		 */
957 		if ((n = sb->sb_lastrecord) != NULL) {
958 			do {
959 				if (n->m_flags & M_EOR) {
960 					sbappendrecord_locked(sb, m); /* XXXXXX!!!! */
961 					return;
962 				}
963 			} while (n->m_next && (n = n->m_next));
964 		} else {
965 			/*
966 			 * If this is the first record in the socket buffer,
967 			 * it's also the last record.
968 			 */
969 			sb->sb_lastrecord = m;
970 		}
971 	}
972 	sbcompress(sb, m, n);
973 	SBLASTRECORDCHK(sb);
974 }
975 
976 /*
977  * Append mbuf chain m to the last record in the socket buffer sb.  The
978  * additional space associated the mbuf chain is recorded in sb.  Empty mbufs
979  * are discarded and mbufs are compacted where possible.
980  */
981 void
982 sbappend(struct sockbuf *sb, struct mbuf *m, int flags)
983 {
984 
985 	SOCKBUF_LOCK(sb);
986 	sbappend_locked(sb, m, flags);
987 	SOCKBUF_UNLOCK(sb);
988 }
989 
990 #ifdef KERN_TLS
991 /*
992  * Append an mbuf containing encrypted TLS data.  The data
993  * is marked M_NOTREADY until it has been decrypted and
994  * stored as a TLS record.
995  */
996 static void
997 sbappend_ktls_rx(struct sockbuf *sb, struct mbuf *m)
998 {
999 	struct ifnet *ifp;
1000 	struct mbuf *n;
1001 	int flags;
1002 
1003 	ifp = NULL;
1004 	flags = M_NOTREADY;
1005 
1006 	SBLASTMBUFCHK(sb);
1007 
1008 	/* Mbuf chain must start with a packet header. */
1009 	MPASS((m->m_flags & M_PKTHDR) != 0);
1010 
1011 	/* Remove all packet headers and mbuf tags to get a pure data chain. */
1012 	for (n = m; n != NULL; n = n->m_next) {
1013 		if (n->m_flags & M_PKTHDR) {
1014 			ifp = m->m_pkthdr.leaf_rcvif;
1015 			if ((n->m_pkthdr.csum_flags & CSUM_TLS_MASK) ==
1016 			    CSUM_TLS_DECRYPTED) {
1017 				/* Mark all mbufs in this packet decrypted. */
1018 				flags = M_NOTREADY | M_DECRYPTED;
1019 			} else {
1020 				flags = M_NOTREADY;
1021 			}
1022 			m_demote_pkthdr(n);
1023 		}
1024 
1025 		n->m_flags &= M_DEMOTEFLAGS;
1026 		n->m_flags |= flags;
1027 
1028 		MPASS((n->m_flags & M_NOTREADY) != 0);
1029 	}
1030 
1031 	sbcompress_ktls_rx(sb, m, sb->sb_mtlstail);
1032 	ktls_check_rx(sb);
1033 
1034 	/* Check for incoming packet route changes: */
1035 	if (ifp != NULL && sb->sb_tls_info->rx_ifp != NULL &&
1036 	    sb->sb_tls_info->rx_ifp != ifp)
1037 		ktls_input_ifp_mismatch(sb, ifp);
1038 }
1039 #endif
1040 
1041 /*
1042  * This version of sbappend() should only be used when the caller absolutely
1043  * knows that there will never be more than one record in the socket buffer,
1044  * that is, a stream protocol (such as TCP).
1045  */
1046 void
1047 sbappendstream_locked(struct sockbuf *sb, struct mbuf *m, int flags)
1048 {
1049 	SOCKBUF_LOCK_ASSERT(sb);
1050 
1051 	KASSERT(m->m_nextpkt == NULL,("sbappendstream 0"));
1052 
1053 	kmsan_check_mbuf(m, "sbappend");
1054 
1055 #ifdef KERN_TLS
1056 	/*
1057 	 * Decrypted TLS records are appended as records via
1058 	 * sbappendrecord().  TCP passes encrypted TLS records to this
1059 	 * function which must be scheduled for decryption.
1060 	 */
1061 	if (sb->sb_flags & SB_TLS_RX) {
1062 		sbappend_ktls_rx(sb, m);
1063 		return;
1064 	}
1065 #endif
1066 
1067 	KASSERT(sb->sb_mb == sb->sb_lastrecord,("sbappendstream 1"));
1068 
1069 	SBLASTMBUFCHK(sb);
1070 
1071 #ifdef KERN_TLS
1072 	if (sb->sb_tls_info != NULL)
1073 		ktls_seq(sb, m);
1074 #endif
1075 
1076 	/* Remove all packet headers and mbuf tags to get a pure data chain. */
1077 	m_demote(m, 1, flags & PRUS_NOTREADY ? M_NOTREADY : 0);
1078 
1079 	sbcompress(sb, m, sb->sb_mbtail);
1080 
1081 	sb->sb_lastrecord = sb->sb_mb;
1082 	SBLASTRECORDCHK(sb);
1083 }
1084 
1085 /*
1086  * This version of sbappend() should only be used when the caller absolutely
1087  * knows that there will never be more than one record in the socket buffer,
1088  * that is, a stream protocol (such as TCP).
1089  */
1090 void
1091 sbappendstream(struct sockbuf *sb, struct mbuf *m, int flags)
1092 {
1093 
1094 	SOCKBUF_LOCK(sb);
1095 	sbappendstream_locked(sb, m, flags);
1096 	SOCKBUF_UNLOCK(sb);
1097 }
1098 
1099 #ifdef SOCKBUF_DEBUG
1100 void
1101 sbcheck(struct sockbuf *sb, const char *file, int line)
1102 {
1103 	struct mbuf *m, *n, *fnrdy;
1104 	u_long acc, ccc, mbcnt;
1105 #ifdef KERN_TLS
1106 	u_long tlscc;
1107 #endif
1108 
1109 	SOCKBUF_LOCK_ASSERT(sb);
1110 
1111 	acc = ccc = mbcnt = 0;
1112 	fnrdy = NULL;
1113 
1114 	for (m = sb->sb_mb; m; m = n) {
1115 	    n = m->m_nextpkt;
1116 	    for (; m; m = m->m_next) {
1117 		if (m->m_len == 0) {
1118 			printf("sb %p empty mbuf %p\n", sb, m);
1119 			goto fail;
1120 		}
1121 		if ((m->m_flags & M_NOTREADY) && fnrdy == NULL) {
1122 			if (m != sb->sb_fnrdy) {
1123 				printf("sb %p: fnrdy %p != m %p\n",
1124 				    sb, sb->sb_fnrdy, m);
1125 				goto fail;
1126 			}
1127 			fnrdy = m;
1128 		}
1129 		if (fnrdy) {
1130 			if (!(m->m_flags & M_NOTAVAIL)) {
1131 				printf("sb %p: fnrdy %p, m %p is avail\n",
1132 				    sb, sb->sb_fnrdy, m);
1133 				goto fail;
1134 			}
1135 		} else
1136 			acc += m->m_len;
1137 		ccc += m->m_len;
1138 		mbcnt += MSIZE;
1139 		if (m->m_flags & M_EXT) /*XXX*/ /* pretty sure this is bogus */
1140 			mbcnt += m->m_ext.ext_size;
1141 	    }
1142 	}
1143 #ifdef KERN_TLS
1144 	/*
1145 	 * Account for mbufs "detached" by ktls_detach_record() while
1146 	 * they are decrypted by ktls_decrypt().  tlsdcc gives a count
1147 	 * of the detached bytes that are included in ccc.  The mbufs
1148 	 * and clusters are not included in the socket buffer
1149 	 * accounting.
1150 	 */
1151 	ccc += sb->sb_tlsdcc;
1152 
1153 	tlscc = 0;
1154 	for (m = sb->sb_mtls; m; m = m->m_next) {
1155 		if (m->m_nextpkt != NULL) {
1156 			printf("sb %p TLS mbuf %p with nextpkt\n", sb, m);
1157 			goto fail;
1158 		}
1159 		if ((m->m_flags & M_NOTREADY) == 0) {
1160 			printf("sb %p TLS mbuf %p ready\n", sb, m);
1161 			goto fail;
1162 		}
1163 		tlscc += m->m_len;
1164 		ccc += m->m_len;
1165 		mbcnt += MSIZE;
1166 		if (m->m_flags & M_EXT) /*XXX*/ /* pretty sure this is bogus */
1167 			mbcnt += m->m_ext.ext_size;
1168 	}
1169 
1170 	if (sb->sb_tlscc != tlscc) {
1171 		printf("tlscc %ld/%u dcc %u\n", tlscc, sb->sb_tlscc,
1172 		    sb->sb_tlsdcc);
1173 		goto fail;
1174 	}
1175 #endif
1176 	if (acc != sb->sb_acc || ccc != sb->sb_ccc || mbcnt != sb->sb_mbcnt) {
1177 		printf("acc %ld/%u ccc %ld/%u mbcnt %ld/%u\n",
1178 		    acc, sb->sb_acc, ccc, sb->sb_ccc, mbcnt, sb->sb_mbcnt);
1179 #ifdef KERN_TLS
1180 		printf("tlscc %ld/%u dcc %u\n", tlscc, sb->sb_tlscc,
1181 		    sb->sb_tlsdcc);
1182 #endif
1183 		goto fail;
1184 	}
1185 	return;
1186 fail:
1187 	panic("%s from %s:%u", __func__, file, line);
1188 }
1189 #endif
1190 
1191 /*
1192  * As above, except the mbuf chain begins a new record.
1193  */
1194 void
1195 sbappendrecord_locked(struct sockbuf *sb, struct mbuf *m0)
1196 {
1197 	struct mbuf *m;
1198 
1199 	SOCKBUF_LOCK_ASSERT(sb);
1200 
1201 	if (m0 == NULL)
1202 		return;
1203 
1204 	kmsan_check_mbuf(m0, "sbappend");
1205 	m_clrprotoflags(m0);
1206 
1207 	/*
1208 	 * Put the first mbuf on the queue.  Note this permits zero length
1209 	 * records.
1210 	 */
1211 	sballoc(sb, m0);
1212 	SBLASTRECORDCHK(sb);
1213 	SBLINKRECORD(sb, m0);
1214 	sb->sb_mbtail = m0;
1215 	m = m0->m_next;
1216 	m0->m_next = 0;
1217 	if (m && (m0->m_flags & M_EOR)) {
1218 		m0->m_flags &= ~M_EOR;
1219 		m->m_flags |= M_EOR;
1220 	}
1221 	/* always call sbcompress() so it can do SBLASTMBUFCHK() */
1222 	sbcompress(sb, m, m0);
1223 }
1224 
1225 /*
1226  * As above, except the mbuf chain begins a new record.
1227  */
1228 void
1229 sbappendrecord(struct sockbuf *sb, struct mbuf *m0)
1230 {
1231 
1232 	SOCKBUF_LOCK(sb);
1233 	sbappendrecord_locked(sb, m0);
1234 	SOCKBUF_UNLOCK(sb);
1235 }
1236 
1237 /* Helper routine that appends data, control, and address to a sockbuf. */
1238 static int
1239 sbappendaddr_locked_internal(struct sockbuf *sb, const struct sockaddr *asa,
1240     struct mbuf *m0, struct mbuf *control, struct mbuf *ctrl_last)
1241 {
1242 	struct mbuf *m, *n, *nlast;
1243 
1244 	if (m0 != NULL)
1245 		kmsan_check_mbuf(m0, "sbappend");
1246 	if (control != NULL)
1247 		kmsan_check_mbuf(control, "sbappend");
1248 
1249 #if MSIZE <= 256
1250 	if (asa->sa_len > MLEN)
1251 		return (0);
1252 #endif
1253 	m = m_get(M_NOWAIT, MT_SONAME);
1254 	if (m == NULL)
1255 		return (0);
1256 	m->m_len = asa->sa_len;
1257 	bcopy(asa, mtod(m, caddr_t), asa->sa_len);
1258 	if (m0) {
1259 		M_ASSERT_NO_SND_TAG(m0);
1260 		m_clrprotoflags(m0);
1261 		m_tag_delete_chain(m0, NULL);
1262 		/*
1263 		 * Clear some persistent info from pkthdr.
1264 		 * We don't use m_demote(), because some netgraph consumers
1265 		 * expect M_PKTHDR presence.
1266 		 */
1267 		m0->m_pkthdr.rcvif = NULL;
1268 		m0->m_pkthdr.flowid = 0;
1269 		m0->m_pkthdr.csum_flags = 0;
1270 		m0->m_pkthdr.fibnum = 0;
1271 		m0->m_pkthdr.rsstype = 0;
1272 	}
1273 	if (ctrl_last)
1274 		ctrl_last->m_next = m0;	/* concatenate data to control */
1275 	else
1276 		control = m0;
1277 	m->m_next = control;
1278 	for (n = m; n->m_next != NULL; n = n->m_next)
1279 		sballoc(sb, n);
1280 	sballoc(sb, n);
1281 	nlast = n;
1282 	SBLINKRECORD(sb, m);
1283 
1284 	sb->sb_mbtail = nlast;
1285 	SBLASTMBUFCHK(sb);
1286 
1287 	SBLASTRECORDCHK(sb);
1288 	return (1);
1289 }
1290 
1291 /*
1292  * Append address and data, and optionally, control (ancillary) data to the
1293  * receive queue of a socket.  If present, m0 must include a packet header
1294  * with total length.  Returns 0 if no space in sockbuf or insufficient
1295  * mbufs.
1296  */
1297 int
1298 sbappendaddr_locked(struct sockbuf *sb, const struct sockaddr *asa,
1299     struct mbuf *m0, struct mbuf *control)
1300 {
1301 	struct mbuf *ctrl_last;
1302 	int space = asa->sa_len;
1303 
1304 	SOCKBUF_LOCK_ASSERT(sb);
1305 
1306 	if (m0 && (m0->m_flags & M_PKTHDR) == 0)
1307 		panic("sbappendaddr_locked");
1308 	if (m0)
1309 		space += m0->m_pkthdr.len;
1310 	space += m_length(control, &ctrl_last);
1311 
1312 	if (space > sbspace(sb))
1313 		return (0);
1314 	return (sbappendaddr_locked_internal(sb, asa, m0, control, ctrl_last));
1315 }
1316 
1317 /*
1318  * Append address and data, and optionally, control (ancillary) data to the
1319  * receive queue of a socket.  If present, m0 must include a packet header
1320  * with total length.  Returns 0 if insufficient mbufs.  Does not validate space
1321  * on the receiving sockbuf.
1322  */
1323 int
1324 sbappendaddr_nospacecheck_locked(struct sockbuf *sb, const struct sockaddr *asa,
1325     struct mbuf *m0, struct mbuf *control)
1326 {
1327 	struct mbuf *ctrl_last;
1328 
1329 	SOCKBUF_LOCK_ASSERT(sb);
1330 
1331 	ctrl_last = (control == NULL) ? NULL : m_last(control);
1332 	return (sbappendaddr_locked_internal(sb, asa, m0, control, ctrl_last));
1333 }
1334 
1335 /*
1336  * Append address and data, and optionally, control (ancillary) data to the
1337  * receive queue of a socket.  If present, m0 must include a packet header
1338  * with total length.  Returns 0 if no space in sockbuf or insufficient
1339  * mbufs.
1340  */
1341 int
1342 sbappendaddr(struct sockbuf *sb, const struct sockaddr *asa,
1343     struct mbuf *m0, struct mbuf *control)
1344 {
1345 	int retval;
1346 
1347 	SOCKBUF_LOCK(sb);
1348 	retval = sbappendaddr_locked(sb, asa, m0, control);
1349 	SOCKBUF_UNLOCK(sb);
1350 	return (retval);
1351 }
1352 
1353 void
1354 sbappendcontrol_locked(struct sockbuf *sb, struct mbuf *m0,
1355     struct mbuf *control, int flags)
1356 {
1357 	struct mbuf *m, *mlast;
1358 
1359 	if (m0 != NULL)
1360 		kmsan_check_mbuf(m0, "sbappend");
1361 	kmsan_check_mbuf(control, "sbappend");
1362 
1363 	sbm_clrprotoflags(m0, flags);
1364 	m_last(control)->m_next = m0;
1365 
1366 	SBLASTRECORDCHK(sb);
1367 
1368 	for (m = control; m->m_next; m = m->m_next)
1369 		sballoc(sb, m);
1370 	sballoc(sb, m);
1371 	mlast = m;
1372 	SBLINKRECORD(sb, control);
1373 
1374 	sb->sb_mbtail = mlast;
1375 	SBLASTMBUFCHK(sb);
1376 
1377 	SBLASTRECORDCHK(sb);
1378 }
1379 
1380 void
1381 sbappendcontrol(struct sockbuf *sb, struct mbuf *m0, struct mbuf *control,
1382     int flags)
1383 {
1384 
1385 	SOCKBUF_LOCK(sb);
1386 	sbappendcontrol_locked(sb, m0, control, flags);
1387 	SOCKBUF_UNLOCK(sb);
1388 }
1389 
1390 /*
1391  * Append the data in mbuf chain (m) into the socket buffer sb following mbuf
1392  * (n).  If (n) is NULL, the buffer is presumed empty.
1393  *
1394  * When the data is compressed, mbufs in the chain may be handled in one of
1395  * three ways:
1396  *
1397  * (1) The mbuf may simply be dropped, if it contributes nothing (no data, no
1398  *     record boundary, and no change in data type).
1399  *
1400  * (2) The mbuf may be coalesced -- i.e., data in the mbuf may be copied into
1401  *     an mbuf already in the socket buffer.  This can occur if an
1402  *     appropriate mbuf exists, there is room, both mbufs are not marked as
1403  *     not ready, and no merging of data types will occur.
1404  *
1405  * (3) The mbuf may be appended to the end of the existing mbuf chain.
1406  *
1407  * If any of the new mbufs is marked as M_EOR, mark the last mbuf appended as
1408  * end-of-record.
1409  */
1410 void
1411 sbcompress(struct sockbuf *sb, struct mbuf *m, struct mbuf *n)
1412 {
1413 	int eor = 0;
1414 	struct mbuf *o;
1415 
1416 	SOCKBUF_LOCK_ASSERT(sb);
1417 
1418 	while (m) {
1419 		eor |= m->m_flags & M_EOR;
1420 		if (m->m_len == 0 &&
1421 		    (eor == 0 ||
1422 		     (((o = m->m_next) || (o = n)) &&
1423 		      o->m_type == m->m_type))) {
1424 			if (sb->sb_lastrecord == m)
1425 				sb->sb_lastrecord = m->m_next;
1426 			m = m_free(m);
1427 			continue;
1428 		}
1429 		if (n && (n->m_flags & M_EOR) == 0 &&
1430 		    M_WRITABLE(n) &&
1431 		    ((sb->sb_flags & SB_NOCOALESCE) == 0) &&
1432 		    !(m->m_flags & M_NOTREADY) &&
1433 		    !(n->m_flags & (M_NOTREADY | M_EXTPG)) &&
1434 		    !mbuf_has_tls_session(m) &&
1435 		    !mbuf_has_tls_session(n) &&
1436 		    m->m_len <= MCLBYTES / 4 && /* XXX: Don't copy too much */
1437 		    m->m_len <= M_TRAILINGSPACE(n) &&
1438 		    n->m_type == m->m_type) {
1439 			m_copydata(m, 0, m->m_len, mtodo(n, n->m_len));
1440 			n->m_len += m->m_len;
1441 			sb->sb_ccc += m->m_len;
1442 			if (sb->sb_fnrdy == NULL)
1443 				sb->sb_acc += m->m_len;
1444 			if (m->m_type != MT_DATA && m->m_type != MT_OOBDATA)
1445 				/* XXX: Probably don't need.*/
1446 				sb->sb_ctl += m->m_len;
1447 			m = m_free(m);
1448 			continue;
1449 		}
1450 		if (m->m_len <= MLEN && (m->m_flags & M_EXTPG) &&
1451 		    (m->m_flags & M_NOTREADY) == 0 &&
1452 		    !mbuf_has_tls_session(m))
1453 			(void)mb_unmapped_compress(m);
1454 		if (n)
1455 			n->m_next = m;
1456 		else
1457 			sb->sb_mb = m;
1458 		sb->sb_mbtail = m;
1459 		sballoc(sb, m);
1460 		n = m;
1461 		m->m_flags &= ~M_EOR;
1462 		m = m->m_next;
1463 		n->m_next = 0;
1464 	}
1465 	if (eor) {
1466 		KASSERT(n != NULL, ("sbcompress: eor && n == NULL"));
1467 		n->m_flags |= eor;
1468 	}
1469 	SBLASTMBUFCHK(sb);
1470 }
1471 
1472 #ifdef KERN_TLS
1473 /*
1474  * A version of sbcompress() for encrypted TLS RX mbufs.  These mbufs
1475  * are appended to the 'sb_mtls' chain instead of 'sb_mb' and are also
1476  * a bit simpler (no EOR markers, always MT_DATA, etc.).
1477  */
1478 static void
1479 sbcompress_ktls_rx(struct sockbuf *sb, struct mbuf *m, struct mbuf *n)
1480 {
1481 
1482 	SOCKBUF_LOCK_ASSERT(sb);
1483 
1484 	while (m) {
1485 		KASSERT((m->m_flags & M_EOR) == 0,
1486 		    ("TLS RX mbuf %p with EOR", m));
1487 		KASSERT(m->m_type == MT_DATA,
1488 		    ("TLS RX mbuf %p is not MT_DATA", m));
1489 		KASSERT((m->m_flags & M_NOTREADY) != 0,
1490 		    ("TLS RX mbuf %p ready", m));
1491 		KASSERT((m->m_flags & M_EXTPG) == 0,
1492 		    ("TLS RX mbuf %p unmapped", m));
1493 
1494 		if (m->m_len == 0) {
1495 			m = m_free(m);
1496 			continue;
1497 		}
1498 
1499 		/*
1500 		 * Even though both 'n' and 'm' are NOTREADY, it's ok
1501 		 * to coalesce the data.
1502 		 */
1503 		if (n &&
1504 		    M_WRITABLE(n) &&
1505 		    ((sb->sb_flags & SB_NOCOALESCE) == 0) &&
1506 		    !((m->m_flags ^ n->m_flags) & M_DECRYPTED) &&
1507 		    !(n->m_flags & M_EXTPG) &&
1508 		    m->m_len <= MCLBYTES / 4 && /* XXX: Don't copy too much */
1509 		    m->m_len <= M_TRAILINGSPACE(n)) {
1510 			m_copydata(m, 0, m->m_len, mtodo(n, n->m_len));
1511 			n->m_len += m->m_len;
1512 			sb->sb_ccc += m->m_len;
1513 			sb->sb_tlscc += m->m_len;
1514 			m = m_free(m);
1515 			continue;
1516 		}
1517 		if (n)
1518 			n->m_next = m;
1519 		else
1520 			sb->sb_mtls = m;
1521 		sb->sb_mtlstail = m;
1522 		sballoc_ktls_rx(sb, m);
1523 		n = m;
1524 		m = m->m_next;
1525 		n->m_next = NULL;
1526 	}
1527 	SBLASTMBUFCHK(sb);
1528 }
1529 #endif
1530 
1531 /*
1532  * Free all mbufs in a sockbuf.  Check that all resources are reclaimed.
1533  */
1534 static void
1535 sbflush_internal(struct sockbuf *sb)
1536 {
1537 
1538 	while (sb->sb_mbcnt || sb->sb_tlsdcc) {
1539 		/*
1540 		 * Don't call sbcut(sb, 0) if the leading mbuf is non-empty:
1541 		 * we would loop forever. Panic instead.
1542 		 */
1543 		if (sb->sb_ccc == 0 && (sb->sb_mb == NULL || sb->sb_mb->m_len))
1544 			break;
1545 		m_freem(sbcut_internal(sb, (int)sb->sb_ccc));
1546 	}
1547 	KASSERT(sb->sb_ccc == 0 && sb->sb_mb == 0 && sb->sb_mbcnt == 0,
1548 	    ("%s: ccc %u mb %p mbcnt %u", __func__,
1549 	    sb->sb_ccc, (void *)sb->sb_mb, sb->sb_mbcnt));
1550 }
1551 
1552 void
1553 sbflush_locked(struct sockbuf *sb)
1554 {
1555 
1556 	SOCKBUF_LOCK_ASSERT(sb);
1557 	sbflush_internal(sb);
1558 }
1559 
1560 void
1561 sbflush(struct sockbuf *sb)
1562 {
1563 
1564 	SOCKBUF_LOCK(sb);
1565 	sbflush_locked(sb);
1566 	SOCKBUF_UNLOCK(sb);
1567 }
1568 
1569 /*
1570  * Cut data from (the front of) a sockbuf.
1571  */
1572 static struct mbuf *
1573 sbcut_internal(struct sockbuf *sb, int len)
1574 {
1575 	struct mbuf *m, *next, *mfree;
1576 	bool is_tls;
1577 
1578 	KASSERT(len >= 0, ("%s: len is %d but it is supposed to be >= 0",
1579 	    __func__, len));
1580 	KASSERT(len <= sb->sb_ccc, ("%s: len: %d is > ccc: %u",
1581 	    __func__, len, sb->sb_ccc));
1582 
1583 	next = (m = sb->sb_mb) ? m->m_nextpkt : 0;
1584 	is_tls = false;
1585 	mfree = NULL;
1586 
1587 	while (len > 0) {
1588 		if (m == NULL) {
1589 #ifdef KERN_TLS
1590 			if (next == NULL && !is_tls) {
1591 				if (sb->sb_tlsdcc != 0) {
1592 					MPASS(len >= sb->sb_tlsdcc);
1593 					len -= sb->sb_tlsdcc;
1594 					sb->sb_ccc -= sb->sb_tlsdcc;
1595 					sb->sb_tlsdcc = 0;
1596 					if (len == 0)
1597 						break;
1598 				}
1599 				next = sb->sb_mtls;
1600 				is_tls = true;
1601 			}
1602 #endif
1603 			KASSERT(next, ("%s: no next, len %d", __func__, len));
1604 			m = next;
1605 			next = m->m_nextpkt;
1606 		}
1607 		if (m->m_len > len) {
1608 			KASSERT(!(m->m_flags & M_NOTAVAIL),
1609 			    ("%s: m %p M_NOTAVAIL", __func__, m));
1610 			m->m_len -= len;
1611 			m->m_data += len;
1612 			sb->sb_ccc -= len;
1613 			sb->sb_acc -= len;
1614 			if (sb->sb_sndptroff != 0)
1615 				sb->sb_sndptroff -= len;
1616 			if (m->m_type != MT_DATA && m->m_type != MT_OOBDATA)
1617 				sb->sb_ctl -= len;
1618 			break;
1619 		}
1620 		len -= m->m_len;
1621 #ifdef KERN_TLS
1622 		if (is_tls)
1623 			sbfree_ktls_rx(sb, m);
1624 		else
1625 #endif
1626 			sbfree(sb, m);
1627 		/*
1628 		 * Do not put M_NOTREADY buffers to the free list, they
1629 		 * are referenced from outside.
1630 		 */
1631 		if (m->m_flags & M_NOTREADY && !is_tls)
1632 			m = m->m_next;
1633 		else {
1634 			struct mbuf *n;
1635 
1636 			n = m->m_next;
1637 			m->m_next = mfree;
1638 			mfree = m;
1639 			m = n;
1640 		}
1641 	}
1642 	/*
1643 	 * Free any zero-length mbufs from the buffer.
1644 	 * For SOCK_DGRAM sockets such mbufs represent empty records.
1645 	 * XXX: For SOCK_STREAM sockets such mbufs can appear in the buffer,
1646 	 * when sosend_generic() needs to send only control data.
1647 	 */
1648 	while (m && m->m_len == 0) {
1649 		struct mbuf *n;
1650 
1651 		sbfree(sb, m);
1652 		n = m->m_next;
1653 		m->m_next = mfree;
1654 		mfree = m;
1655 		m = n;
1656 	}
1657 #ifdef KERN_TLS
1658 	if (is_tls) {
1659 		sb->sb_mb = NULL;
1660 		sb->sb_mtls = m;
1661 		if (m == NULL)
1662 			sb->sb_mtlstail = NULL;
1663 	} else
1664 #endif
1665 	if (m) {
1666 		sb->sb_mb = m;
1667 		m->m_nextpkt = next;
1668 	} else
1669 		sb->sb_mb = next;
1670 	/*
1671 	 * First part is an inline SB_EMPTY_FIXUP().  Second part makes sure
1672 	 * sb_lastrecord is up-to-date if we dropped part of the last record.
1673 	 */
1674 	m = sb->sb_mb;
1675 	if (m == NULL) {
1676 		sb->sb_mbtail = NULL;
1677 		sb->sb_lastrecord = NULL;
1678 	} else if (m->m_nextpkt == NULL) {
1679 		sb->sb_lastrecord = m;
1680 	}
1681 
1682 	return (mfree);
1683 }
1684 
1685 /*
1686  * Drop data from (the front of) a sockbuf.
1687  */
1688 void
1689 sbdrop_locked(struct sockbuf *sb, int len)
1690 {
1691 
1692 	SOCKBUF_LOCK_ASSERT(sb);
1693 	m_freem(sbcut_internal(sb, len));
1694 }
1695 
1696 /*
1697  * Drop data from (the front of) a sockbuf,
1698  * and return it to caller.
1699  */
1700 struct mbuf *
1701 sbcut_locked(struct sockbuf *sb, int len)
1702 {
1703 
1704 	SOCKBUF_LOCK_ASSERT(sb);
1705 	return (sbcut_internal(sb, len));
1706 }
1707 
1708 void
1709 sbdrop(struct sockbuf *sb, int len)
1710 {
1711 	struct mbuf *mfree;
1712 
1713 	SOCKBUF_LOCK(sb);
1714 	mfree = sbcut_internal(sb, len);
1715 	SOCKBUF_UNLOCK(sb);
1716 
1717 	m_freem(mfree);
1718 }
1719 
1720 struct mbuf *
1721 sbsndptr_noadv(struct sockbuf *sb, uint32_t off, uint32_t *moff)
1722 {
1723 	struct mbuf *m;
1724 
1725 	KASSERT(sb->sb_mb != NULL, ("%s: sb_mb is NULL", __func__));
1726 	if (sb->sb_sndptr == NULL || sb->sb_sndptroff > off) {
1727 		*moff = off;
1728 		if (sb->sb_sndptr == NULL) {
1729 			sb->sb_sndptr = sb->sb_mb;
1730 			sb->sb_sndptroff = 0;
1731 		}
1732 		return (sb->sb_mb);
1733 	} else {
1734 		m = sb->sb_sndptr;
1735 		off -= sb->sb_sndptroff;
1736 	}
1737 	*moff = off;
1738 	return (m);
1739 }
1740 
1741 void
1742 sbsndptr_adv(struct sockbuf *sb, struct mbuf *mb, uint32_t len)
1743 {
1744 	/*
1745 	 * A small copy was done, advance forward the sb_sbsndptr to cover
1746 	 * it.
1747 	 */
1748 	struct mbuf *m;
1749 
1750 	if (mb != sb->sb_sndptr) {
1751 		/* Did not copyout at the same mbuf */
1752 		return;
1753 	}
1754 	m = mb;
1755 	while (m && (len > 0)) {
1756 		if (len >= m->m_len) {
1757 			len -= m->m_len;
1758 			if (m->m_next) {
1759 				sb->sb_sndptroff += m->m_len;
1760 				sb->sb_sndptr = m->m_next;
1761 			}
1762 			m = m->m_next;
1763 		} else {
1764 			len = 0;
1765 		}
1766 	}
1767 }
1768 
1769 /*
1770  * Return the first mbuf and the mbuf data offset for the provided
1771  * send offset without changing the "sb_sndptroff" field.
1772  */
1773 struct mbuf *
1774 sbsndmbuf(struct sockbuf *sb, u_int off, u_int *moff)
1775 {
1776 	struct mbuf *m;
1777 
1778 	KASSERT(sb->sb_mb != NULL, ("%s: sb_mb is NULL", __func__));
1779 
1780 	/*
1781 	 * If the "off" is below the stored offset, which happens on
1782 	 * retransmits, just use "sb_mb":
1783 	 */
1784 	if (sb->sb_sndptr == NULL || sb->sb_sndptroff > off) {
1785 		m = sb->sb_mb;
1786 	} else {
1787 		m = sb->sb_sndptr;
1788 		off -= sb->sb_sndptroff;
1789 	}
1790 	while (off > 0 && m != NULL) {
1791 		if (off < m->m_len)
1792 			break;
1793 		off -= m->m_len;
1794 		m = m->m_next;
1795 	}
1796 	*moff = off;
1797 	return (m);
1798 }
1799 
1800 /*
1801  * Drop a record off the front of a sockbuf and move the next record to the
1802  * front.
1803  */
1804 void
1805 sbdroprecord_locked(struct sockbuf *sb)
1806 {
1807 	struct mbuf *m;
1808 
1809 	SOCKBUF_LOCK_ASSERT(sb);
1810 
1811 	m = sb->sb_mb;
1812 	if (m) {
1813 		sb->sb_mb = m->m_nextpkt;
1814 		do {
1815 			sbfree(sb, m);
1816 			m = m_free(m);
1817 		} while (m);
1818 	}
1819 	SB_EMPTY_FIXUP(sb);
1820 }
1821 
1822 /*
1823  * Drop a record off the front of a sockbuf and move the next record to the
1824  * front.
1825  */
1826 void
1827 sbdroprecord(struct sockbuf *sb)
1828 {
1829 
1830 	SOCKBUF_LOCK(sb);
1831 	sbdroprecord_locked(sb);
1832 	SOCKBUF_UNLOCK(sb);
1833 }
1834 
1835 /*
1836  * Create a "control" mbuf containing the specified data with the specified
1837  * type for presentation on a socket buffer.
1838  */
1839 struct mbuf *
1840 sbcreatecontrol(const void *p, u_int size, int type, int level, int wait)
1841 {
1842 	struct cmsghdr *cp;
1843 	struct mbuf *m;
1844 
1845 	MBUF_CHECKSLEEP(wait);
1846 
1847 	if (wait == M_NOWAIT) {
1848 		if (CMSG_SPACE(size) > MCLBYTES)
1849 			return (NULL);
1850 	} else
1851 		KASSERT(CMSG_SPACE(size) <= MCLBYTES,
1852 		    ("%s: passed CMSG_SPACE(%u) > MCLBYTES", __func__, size));
1853 
1854 	if (CMSG_SPACE(size) > MLEN)
1855 		m = m_getcl(wait, MT_CONTROL, 0);
1856 	else
1857 		m = m_get(wait, MT_CONTROL);
1858 	if (m == NULL)
1859 		return (NULL);
1860 
1861 	KASSERT(CMSG_SPACE(size) <= M_TRAILINGSPACE(m),
1862 	    ("sbcreatecontrol: short mbuf"));
1863 	/*
1864 	 * Don't leave the padding between the msg header and the
1865 	 * cmsg data and the padding after the cmsg data un-initialized.
1866 	 */
1867 	cp = mtod(m, struct cmsghdr *);
1868 	bzero(cp, CMSG_SPACE(size));
1869 	if (p != NULL)
1870 		(void)memcpy(CMSG_DATA(cp), p, size);
1871 	m->m_len = CMSG_SPACE(size);
1872 	cp->cmsg_len = CMSG_LEN(size);
1873 	cp->cmsg_level = level;
1874 	cp->cmsg_type = type;
1875 	return (m);
1876 }
1877 
1878 /*
1879  * This does the same for socket buffers that sotoxsocket does for sockets:
1880  * generate an user-format data structure describing the socket buffer.  Note
1881  * that the xsockbuf structure, since it is always embedded in a socket, does
1882  * not include a self pointer nor a length.  We make this entry point public
1883  * in case some other mechanism needs it.
1884  */
1885 void
1886 sbtoxsockbuf(struct sockbuf *sb, struct xsockbuf *xsb)
1887 {
1888 
1889 	xsb->sb_cc = sb->sb_ccc;
1890 	xsb->sb_hiwat = sb->sb_hiwat;
1891 	xsb->sb_mbcnt = sb->sb_mbcnt;
1892 	xsb->sb_mbmax = sb->sb_mbmax;
1893 	xsb->sb_lowat = sb->sb_lowat;
1894 	xsb->sb_flags = sb->sb_flags;
1895 	xsb->sb_timeo = sb->sb_timeo;
1896 }
1897 
1898 /* This takes the place of kern.maxsockbuf, which moved to kern.ipc. */
1899 static int dummy;
1900 SYSCTL_INT(_kern, KERN_DUMMY, dummy, CTLFLAG_RW | CTLFLAG_SKIP, &dummy, 0, "");
1901 SYSCTL_OID(_kern_ipc, KIPC_MAXSOCKBUF, maxsockbuf,
1902     CTLTYPE_ULONG | CTLFLAG_RW | CTLFLAG_MPSAFE, &sb_max, 0,
1903     sysctl_handle_sb_max, "LU",
1904     "Maximum socket buffer size");
1905 SYSCTL_ULONG(_kern_ipc, KIPC_SOCKBUF_WASTE, sockbuf_waste_factor, CTLFLAG_RW,
1906     &sb_efficiency, 0, "Socket buffer size waste factor");
1907