xref: /freebsd/sys/kern/uipc_sockbuf.c (revision 62a52c15422470f97fc7b311d89c83f910bcc1b1)
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 /*
512  * Do we need to notify the other side when I/O is possible?
513  */
514 static __always_inline bool
515 sb_notify(const struct sockbuf *sb)
516 {
517 	return ((sb->sb_flags & (SB_WAIT | SB_SEL | SB_ASYNC |
518 	    SB_UPCALL | SB_AIO | SB_KNOTE)) != 0);
519 }
520 
521 void
522 sorwakeup_locked(struct socket *so)
523 {
524 	SOCK_RECVBUF_LOCK_ASSERT(so);
525 	if (sb_notify(&so->so_rcv))
526 		sowakeup(so, SO_RCV);
527 	else
528 		SOCK_RECVBUF_UNLOCK(so);
529 }
530 
531 void
532 sowwakeup_locked(struct socket *so)
533 {
534 	SOCK_SENDBUF_LOCK_ASSERT(so);
535 	if (sb_notify(&so->so_snd))
536 		sowakeup(so, SO_SND);
537 	else
538 		SOCK_SENDBUF_UNLOCK(so);
539 }
540 
541 /*
542  * Socket buffer (struct sockbuf) utility routines.
543  *
544  * Each socket contains two socket buffers: one for sending data and one for
545  * receiving data.  Each buffer contains a queue of mbufs, information about
546  * the number of mbufs and amount of data in the queue, and other fields
547  * allowing select() statements and notification on data availability to be
548  * implemented.
549  *
550  * Data stored in a socket buffer is maintained as a list of records.  Each
551  * record is a list of mbufs chained together with the m_next field.  Records
552  * are chained together with the m_nextpkt field. The upper level routine
553  * soreceive() expects the following conventions to be observed when placing
554  * information in the receive buffer:
555  *
556  * 1. If the protocol requires each message be preceded by the sender's name,
557  *    then a record containing that name must be present before any
558  *    associated data (mbuf's must be of type MT_SONAME).
559  * 2. If the protocol supports the exchange of ``access rights'' (really just
560  *    additional data associated with the message), and there are ``rights''
561  *    to be received, then a record containing this data should be present
562  *    (mbuf's must be of type MT_RIGHTS).
563  * 3. If a name or rights record exists, then it must be followed by a data
564  *    record, perhaps of zero length.
565  *
566  * Before using a new socket structure it is first necessary to reserve
567  * buffer space to the socket, by calling sbreserve().  This should commit
568  * some of the available buffer space in the system buffer pool for the
569  * socket (currently, it does nothing but enforce limits).  The space should
570  * be released by calling sbrelease() when the socket is destroyed.
571  */
572 int
573 soreserve(struct socket *so, u_long sndcc, u_long rcvcc)
574 {
575 	struct thread *td = curthread;
576 
577 	SOCK_SENDBUF_LOCK(so);
578 	SOCK_RECVBUF_LOCK(so);
579 	if (sbreserve_locked(so, SO_SND, sndcc, td) == 0)
580 		goto bad;
581 	if (sbreserve_locked(so, SO_RCV, rcvcc, td) == 0)
582 		goto bad2;
583 	if (so->so_rcv.sb_lowat == 0)
584 		so->so_rcv.sb_lowat = 1;
585 	if (so->so_snd.sb_lowat == 0)
586 		so->so_snd.sb_lowat = MCLBYTES;
587 	if (so->so_snd.sb_lowat > so->so_snd.sb_hiwat)
588 		so->so_snd.sb_lowat = so->so_snd.sb_hiwat;
589 	SOCK_RECVBUF_UNLOCK(so);
590 	SOCK_SENDBUF_UNLOCK(so);
591 	return (0);
592 bad2:
593 	sbrelease_locked(so, SO_SND);
594 bad:
595 	SOCK_RECVBUF_UNLOCK(so);
596 	SOCK_SENDBUF_UNLOCK(so);
597 	return (ENOBUFS);
598 }
599 
600 static int
601 sysctl_handle_sb_max(SYSCTL_HANDLER_ARGS)
602 {
603 	int error = 0;
604 	u_long tmp_sb_max = sb_max;
605 
606 	error = sysctl_handle_long(oidp, &tmp_sb_max, arg2, req);
607 	if (error || !req->newptr)
608 		return (error);
609 	if (tmp_sb_max < MSIZE + MCLBYTES)
610 		return (EINVAL);
611 	sb_max = tmp_sb_max;
612 	sb_max_adj = BUF_MAX_ADJ(sb_max);
613 	return (0);
614 }
615 
616 /*
617  * Allot mbufs to a sockbuf.  Attempt to scale mbmax so that mbcnt doesn't
618  * become limiting if buffering efficiency is near the normal case.
619  */
620 bool
621 sbreserve_locked_limit(struct socket *so, sb_which which, u_long cc,
622     u_long buf_max, struct thread *td)
623 {
624 	struct sockbuf *sb = sobuf(so, which);
625 	rlim_t sbsize_limit;
626 
627 	SOCK_BUF_LOCK_ASSERT(so, which);
628 
629 	/*
630 	 * When a thread is passed, we take into account the thread's socket
631 	 * buffer size limit.  The caller will generally pass curthread, but
632 	 * in the TCP input path, NULL will be passed to indicate that no
633 	 * appropriate thread resource limits are available.  In that case,
634 	 * we don't apply a process limit.
635 	 */
636 	if (cc > BUF_MAX_ADJ(buf_max))
637 		return (false);
638 	if (td != NULL) {
639 		sbsize_limit = lim_cur(td, RLIMIT_SBSIZE);
640 	} else
641 		sbsize_limit = RLIM_INFINITY;
642 	if (!chgsbsize(so->so_cred->cr_uidinfo, &sb->sb_hiwat, cc,
643 	    sbsize_limit))
644 		return (false);
645 	sb->sb_mbmax = min(cc * sb_efficiency, buf_max);
646 	if (sb->sb_lowat > sb->sb_hiwat)
647 		sb->sb_lowat = sb->sb_hiwat;
648 	return (true);
649 }
650 
651 bool
652 sbreserve_locked(struct socket *so, sb_which which, u_long cc,
653     struct thread *td)
654 {
655 	return (sbreserve_locked_limit(so, which, cc, sb_max, td));
656 }
657 
658 int
659 sbsetopt(struct socket *so, struct sockopt *sopt)
660 {
661 	struct sockbuf *sb;
662 	sb_which wh;
663 	short *flags;
664 	u_int cc, *hiwat, *lowat;
665 	int error, optval;
666 
667 	error = sooptcopyin(sopt, &optval, sizeof optval, sizeof optval);
668 	if (error != 0)
669 		return (error);
670 
671 	/*
672 	 * Values < 1 make no sense for any of these options,
673 	 * so disallow them.
674 	 */
675 	if (optval < 1)
676 		return (EINVAL);
677 	cc = optval;
678 
679 	sb = NULL;
680 	SOCK_LOCK(so);
681 	if (SOLISTENING(so)) {
682 		switch (sopt->sopt_name) {
683 			case SO_SNDLOWAT:
684 			case SO_SNDBUF:
685 				lowat = &so->sol_sbsnd_lowat;
686 				hiwat = &so->sol_sbsnd_hiwat;
687 				flags = &so->sol_sbsnd_flags;
688 				break;
689 			case SO_RCVLOWAT:
690 			case SO_RCVBUF:
691 				lowat = &so->sol_sbrcv_lowat;
692 				hiwat = &so->sol_sbrcv_hiwat;
693 				flags = &so->sol_sbrcv_flags;
694 				break;
695 		}
696 	} else {
697 		switch (sopt->sopt_name) {
698 			case SO_SNDLOWAT:
699 			case SO_SNDBUF:
700 				sb = &so->so_snd;
701 				wh = SO_SND;
702 				break;
703 			case SO_RCVLOWAT:
704 			case SO_RCVBUF:
705 				sb = &so->so_rcv;
706 				wh = SO_RCV;
707 				break;
708 		}
709 		flags = &sb->sb_flags;
710 		hiwat = &sb->sb_hiwat;
711 		lowat = &sb->sb_lowat;
712 		SOCK_BUF_LOCK(so, wh);
713 	}
714 
715 	error = 0;
716 	switch (sopt->sopt_name) {
717 	case SO_SNDBUF:
718 	case SO_RCVBUF:
719 		if (SOLISTENING(so)) {
720 			if (cc > sb_max_adj) {
721 				error = ENOBUFS;
722 				break;
723 			}
724 			*hiwat = cc;
725 			if (*lowat > *hiwat)
726 				*lowat = *hiwat;
727 		} else {
728 			if (!sbreserve_locked(so, wh, cc, curthread))
729 				error = ENOBUFS;
730 		}
731 		if (error == 0)
732 			*flags &= ~SB_AUTOSIZE;
733 		break;
734 	case SO_SNDLOWAT:
735 	case SO_RCVLOWAT:
736 		/*
737 		 * Make sure the low-water is never greater than the
738 		 * high-water.
739 		 */
740 		*lowat = (cc > *hiwat) ? *hiwat : cc;
741 		break;
742 	}
743 
744 	if (!SOLISTENING(so))
745 		SOCK_BUF_UNLOCK(so, wh);
746 	SOCK_UNLOCK(so);
747 	return (error);
748 }
749 
750 /*
751  * Free mbufs held by a socket, and reserved mbuf space.
752  */
753 static void
754 sbrelease_internal(struct socket *so, sb_which which)
755 {
756 	struct sockbuf *sb = sobuf(so, which);
757 
758 	sbflush_internal(sb);
759 	(void)chgsbsize(so->so_cred->cr_uidinfo, &sb->sb_hiwat, 0,
760 	    RLIM_INFINITY);
761 	sb->sb_mbmax = 0;
762 }
763 
764 void
765 sbrelease_locked(struct socket *so, sb_which which)
766 {
767 
768 	SOCK_BUF_LOCK_ASSERT(so, which);
769 
770 	sbrelease_internal(so, which);
771 }
772 
773 void
774 sbrelease(struct socket *so, sb_which which)
775 {
776 
777 	SOCK_BUF_LOCK(so, which);
778 	sbrelease_locked(so, which);
779 	SOCK_BUF_UNLOCK(so, which);
780 }
781 
782 void
783 sbdestroy(struct socket *so, sb_which which)
784 {
785 #ifdef KERN_TLS
786 	struct sockbuf *sb = sobuf(so, which);
787 
788 	if (sb->sb_tls_info != NULL)
789 		ktls_free(sb->sb_tls_info);
790 	sb->sb_tls_info = NULL;
791 #endif
792 	sbrelease_internal(so, which);
793 }
794 
795 /*
796  * Routines to add and remove data from an mbuf queue.
797  *
798  * The routines sbappend() or sbappendrecord() are normally called to append
799  * new mbufs to a socket buffer, after checking that adequate space is
800  * available, comparing the function sbspace() with the amount of data to be
801  * added.  sbappendrecord() differs from sbappend() in that data supplied is
802  * treated as the beginning of a new record.  To place a sender's address,
803  * optional access rights, and data in a socket receive buffer,
804  * sbappendaddr() should be used.  To place access rights and data in a
805  * socket receive buffer, sbappendrights() should be used.  In either case,
806  * the new data begins a new record.  Note that unlike sbappend() and
807  * sbappendrecord(), these routines check for the caller that there will be
808  * enough space to store the data.  Each fails if there is not enough space,
809  * or if it cannot find mbufs to store additional information in.
810  *
811  * Reliable protocols may use the socket send buffer to hold data awaiting
812  * acknowledgement.  Data is normally copied from a socket send buffer in a
813  * protocol with m_copy for output to a peer, and then removing the data from
814  * the socket buffer with sbdrop() or sbdroprecord() when the data is
815  * acknowledged by the peer.
816  */
817 #ifdef SOCKBUF_DEBUG
818 void
819 sblastrecordchk(struct sockbuf *sb, const char *file, int line)
820 {
821 	struct mbuf *m = sb->sb_mb;
822 
823 	SOCKBUF_LOCK_ASSERT(sb);
824 
825 	while (m && m->m_nextpkt)
826 		m = m->m_nextpkt;
827 
828 	if (m != sb->sb_lastrecord) {
829 		printf("%s: sb_mb %p sb_lastrecord %p last %p\n",
830 			__func__, sb->sb_mb, sb->sb_lastrecord, m);
831 		printf("packet chain:\n");
832 		for (m = sb->sb_mb; m != NULL; m = m->m_nextpkt)
833 			printf("\t%p\n", m);
834 		panic("%s from %s:%u", __func__, file, line);
835 	}
836 }
837 
838 void
839 sblastmbufchk(struct sockbuf *sb, const char *file, int line)
840 {
841 	struct mbuf *m = sb->sb_mb;
842 	struct mbuf *n;
843 
844 	SOCKBUF_LOCK_ASSERT(sb);
845 
846 	while (m && m->m_nextpkt)
847 		m = m->m_nextpkt;
848 
849 	while (m && m->m_next)
850 		m = m->m_next;
851 
852 	if (m != sb->sb_mbtail) {
853 		printf("%s: sb_mb %p sb_mbtail %p last %p\n",
854 			__func__, sb->sb_mb, sb->sb_mbtail, m);
855 		printf("packet tree:\n");
856 		for (m = sb->sb_mb; m != NULL; m = m->m_nextpkt) {
857 			printf("\t");
858 			for (n = m; n != NULL; n = n->m_next)
859 				printf("%p ", n);
860 			printf("\n");
861 		}
862 		panic("%s from %s:%u", __func__, file, line);
863 	}
864 
865 #ifdef KERN_TLS
866 	m = sb->sb_mtls;
867 	while (m && m->m_next)
868 		m = m->m_next;
869 
870 	if (m != sb->sb_mtlstail) {
871 		printf("%s: sb_mtls %p sb_mtlstail %p last %p\n",
872 			__func__, sb->sb_mtls, sb->sb_mtlstail, m);
873 		printf("TLS packet tree:\n");
874 		printf("\t");
875 		for (m = sb->sb_mtls; m != NULL; m = m->m_next) {
876 			printf("%p ", m);
877 		}
878 		printf("\n");
879 		panic("%s from %s:%u", __func__, file, line);
880 	}
881 #endif
882 }
883 #endif /* SOCKBUF_DEBUG */
884 
885 #define SBLINKRECORD(sb, m0) do {					\
886 	SOCKBUF_LOCK_ASSERT(sb);					\
887 	if ((sb)->sb_lastrecord != NULL)				\
888 		(sb)->sb_lastrecord->m_nextpkt = (m0);			\
889 	else								\
890 		(sb)->sb_mb = (m0);					\
891 	(sb)->sb_lastrecord = (m0);					\
892 } while (/*CONSTCOND*/0)
893 
894 /*
895  * Append mbuf chain m to the last record in the socket buffer sb.  The
896  * additional space associated the mbuf chain is recorded in sb.  Empty mbufs
897  * are discarded and mbufs are compacted where possible.
898  */
899 void
900 sbappend_locked(struct sockbuf *sb, struct mbuf *m, int flags)
901 {
902 	struct mbuf *n;
903 
904 	SOCKBUF_LOCK_ASSERT(sb);
905 
906 	if (m == NULL)
907 		return;
908 	kmsan_check_mbuf(m, "sbappend");
909 	sbm_clrprotoflags(m, flags);
910 	SBLASTRECORDCHK(sb);
911 	n = sb->sb_mb;
912 	if (n) {
913 		while (n->m_nextpkt)
914 			n = n->m_nextpkt;
915 		do {
916 			if (n->m_flags & M_EOR) {
917 				sbappendrecord_locked(sb, m); /* XXXXXX!!!! */
918 				return;
919 			}
920 		} while (n->m_next && (n = n->m_next));
921 	} else {
922 		/*
923 		 * XXX Would like to simply use sb_mbtail here, but
924 		 * XXX I need to verify that I won't miss an EOR that
925 		 * XXX way.
926 		 */
927 		if ((n = sb->sb_lastrecord) != NULL) {
928 			do {
929 				if (n->m_flags & M_EOR) {
930 					sbappendrecord_locked(sb, m); /* XXXXXX!!!! */
931 					return;
932 				}
933 			} while (n->m_next && (n = n->m_next));
934 		} else {
935 			/*
936 			 * If this is the first record in the socket buffer,
937 			 * it's also the last record.
938 			 */
939 			sb->sb_lastrecord = m;
940 		}
941 	}
942 	sbcompress(sb, m, n);
943 	SBLASTRECORDCHK(sb);
944 }
945 
946 /*
947  * Append mbuf chain m to the last record in the socket buffer sb.  The
948  * additional space associated the mbuf chain is recorded in sb.  Empty mbufs
949  * are discarded and mbufs are compacted where possible.
950  */
951 void
952 sbappend(struct sockbuf *sb, struct mbuf *m, int flags)
953 {
954 
955 	SOCKBUF_LOCK(sb);
956 	sbappend_locked(sb, m, flags);
957 	SOCKBUF_UNLOCK(sb);
958 }
959 
960 #ifdef KERN_TLS
961 /*
962  * Append an mbuf containing encrypted TLS data.  The data
963  * is marked M_NOTREADY until it has been decrypted and
964  * stored as a TLS record.
965  */
966 static void
967 sbappend_ktls_rx(struct sockbuf *sb, struct mbuf *m)
968 {
969 	struct ifnet *ifp;
970 	struct mbuf *n;
971 	int flags;
972 
973 	ifp = NULL;
974 	flags = M_NOTREADY;
975 
976 	SBLASTMBUFCHK(sb);
977 
978 	/* Mbuf chain must start with a packet header. */
979 	MPASS((m->m_flags & M_PKTHDR) != 0);
980 
981 	/* Remove all packet headers and mbuf tags to get a pure data chain. */
982 	for (n = m; n != NULL; n = n->m_next) {
983 		if (n->m_flags & M_PKTHDR) {
984 			ifp = m->m_pkthdr.leaf_rcvif;
985 			if ((n->m_pkthdr.csum_flags & CSUM_TLS_MASK) ==
986 			    CSUM_TLS_DECRYPTED) {
987 				/* Mark all mbufs in this packet decrypted. */
988 				flags = M_NOTREADY | M_DECRYPTED;
989 			} else {
990 				flags = M_NOTREADY;
991 			}
992 			m_demote_pkthdr(n);
993 		}
994 
995 		n->m_flags &= M_DEMOTEFLAGS;
996 		n->m_flags |= flags;
997 
998 		MPASS((n->m_flags & M_NOTREADY) != 0);
999 	}
1000 
1001 	sbcompress_ktls_rx(sb, m, sb->sb_mtlstail);
1002 	ktls_check_rx(sb);
1003 
1004 	/* Check for incoming packet route changes: */
1005 	if (ifp != NULL && sb->sb_tls_info->rx_ifp != NULL &&
1006 	    sb->sb_tls_info->rx_ifp != ifp)
1007 		ktls_input_ifp_mismatch(sb, ifp);
1008 }
1009 #endif
1010 
1011 /*
1012  * This version of sbappend() should only be used when the caller absolutely
1013  * knows that there will never be more than one record in the socket buffer,
1014  * that is, a stream protocol (such as TCP).
1015  */
1016 void
1017 sbappendstream_locked(struct sockbuf *sb, struct mbuf *m, int flags)
1018 {
1019 	SOCKBUF_LOCK_ASSERT(sb);
1020 
1021 	KASSERT(m->m_nextpkt == NULL,("sbappendstream 0"));
1022 
1023 	kmsan_check_mbuf(m, "sbappend");
1024 
1025 #ifdef KERN_TLS
1026 	/*
1027 	 * Decrypted TLS records are appended as records via
1028 	 * sbappendrecord().  TCP passes encrypted TLS records to this
1029 	 * function which must be scheduled for decryption.
1030 	 */
1031 	if (sb->sb_flags & SB_TLS_RX) {
1032 		sbappend_ktls_rx(sb, m);
1033 		return;
1034 	}
1035 #endif
1036 
1037 	KASSERT(sb->sb_mb == sb->sb_lastrecord,("sbappendstream 1"));
1038 
1039 	SBLASTMBUFCHK(sb);
1040 
1041 #ifdef KERN_TLS
1042 	if (sb->sb_tls_info != NULL)
1043 		ktls_seq(sb, m);
1044 #endif
1045 
1046 	/* Remove all packet headers and mbuf tags to get a pure data chain. */
1047 	m_demote(m, 1, flags & PRUS_NOTREADY ? M_NOTREADY : 0);
1048 
1049 	sbcompress(sb, m, sb->sb_mbtail);
1050 
1051 	sb->sb_lastrecord = sb->sb_mb;
1052 	SBLASTRECORDCHK(sb);
1053 }
1054 
1055 /*
1056  * This version of sbappend() should only be used when the caller absolutely
1057  * knows that there will never be more than one record in the socket buffer,
1058  * that is, a stream protocol (such as TCP).
1059  */
1060 void
1061 sbappendstream(struct sockbuf *sb, struct mbuf *m, int flags)
1062 {
1063 
1064 	SOCKBUF_LOCK(sb);
1065 	sbappendstream_locked(sb, m, flags);
1066 	SOCKBUF_UNLOCK(sb);
1067 }
1068 
1069 #ifdef SOCKBUF_DEBUG
1070 void
1071 sbcheck(struct sockbuf *sb, const char *file, int line)
1072 {
1073 	struct mbuf *m, *n, *fnrdy;
1074 	u_long acc, ccc, mbcnt;
1075 #ifdef KERN_TLS
1076 	u_long tlscc;
1077 #endif
1078 
1079 	SOCKBUF_LOCK_ASSERT(sb);
1080 
1081 	acc = ccc = mbcnt = 0;
1082 	fnrdy = NULL;
1083 
1084 	for (m = sb->sb_mb; m; m = n) {
1085 	    n = m->m_nextpkt;
1086 	    for (; m; m = m->m_next) {
1087 		if (m->m_len == 0) {
1088 			printf("sb %p empty mbuf %p\n", sb, m);
1089 			goto fail;
1090 		}
1091 		if ((m->m_flags & M_NOTREADY) && fnrdy == NULL) {
1092 			if (m != sb->sb_fnrdy) {
1093 				printf("sb %p: fnrdy %p != m %p\n",
1094 				    sb, sb->sb_fnrdy, m);
1095 				goto fail;
1096 			}
1097 			fnrdy = m;
1098 		}
1099 		if (fnrdy) {
1100 			if (!(m->m_flags & M_NOTAVAIL)) {
1101 				printf("sb %p: fnrdy %p, m %p is avail\n",
1102 				    sb, sb->sb_fnrdy, m);
1103 				goto fail;
1104 			}
1105 		} else
1106 			acc += m->m_len;
1107 		ccc += m->m_len;
1108 		mbcnt += MSIZE;
1109 		if (m->m_flags & M_EXT) /*XXX*/ /* pretty sure this is bogus */
1110 			mbcnt += m->m_ext.ext_size;
1111 	    }
1112 	}
1113 #ifdef KERN_TLS
1114 	/*
1115 	 * Account for mbufs "detached" by ktls_detach_record() while
1116 	 * they are decrypted by ktls_decrypt().  tlsdcc gives a count
1117 	 * of the detached bytes that are included in ccc.  The mbufs
1118 	 * and clusters are not included in the socket buffer
1119 	 * accounting.
1120 	 */
1121 	ccc += sb->sb_tlsdcc;
1122 
1123 	tlscc = 0;
1124 	for (m = sb->sb_mtls; m; m = m->m_next) {
1125 		if (m->m_nextpkt != NULL) {
1126 			printf("sb %p TLS mbuf %p with nextpkt\n", sb, m);
1127 			goto fail;
1128 		}
1129 		if ((m->m_flags & M_NOTREADY) == 0) {
1130 			printf("sb %p TLS mbuf %p ready\n", sb, m);
1131 			goto fail;
1132 		}
1133 		tlscc += m->m_len;
1134 		ccc += m->m_len;
1135 		mbcnt += MSIZE;
1136 		if (m->m_flags & M_EXT) /*XXX*/ /* pretty sure this is bogus */
1137 			mbcnt += m->m_ext.ext_size;
1138 	}
1139 
1140 	if (sb->sb_tlscc != tlscc) {
1141 		printf("tlscc %ld/%u dcc %u\n", tlscc, sb->sb_tlscc,
1142 		    sb->sb_tlsdcc);
1143 		goto fail;
1144 	}
1145 #endif
1146 	if (acc != sb->sb_acc || ccc != sb->sb_ccc || mbcnt != sb->sb_mbcnt) {
1147 		printf("acc %ld/%u ccc %ld/%u mbcnt %ld/%u\n",
1148 		    acc, sb->sb_acc, ccc, sb->sb_ccc, mbcnt, sb->sb_mbcnt);
1149 #ifdef KERN_TLS
1150 		printf("tlscc %ld/%u dcc %u\n", tlscc, sb->sb_tlscc,
1151 		    sb->sb_tlsdcc);
1152 #endif
1153 		goto fail;
1154 	}
1155 	return;
1156 fail:
1157 	panic("%s from %s:%u", __func__, file, line);
1158 }
1159 #endif
1160 
1161 /*
1162  * As above, except the mbuf chain begins a new record.
1163  */
1164 void
1165 sbappendrecord_locked(struct sockbuf *sb, struct mbuf *m0)
1166 {
1167 	struct mbuf *m;
1168 
1169 	SOCKBUF_LOCK_ASSERT(sb);
1170 
1171 	if (m0 == NULL)
1172 		return;
1173 
1174 	kmsan_check_mbuf(m0, "sbappend");
1175 	m_clrprotoflags(m0);
1176 
1177 	/*
1178 	 * Put the first mbuf on the queue.  Note this permits zero length
1179 	 * records.
1180 	 */
1181 	sballoc(sb, m0);
1182 	SBLASTRECORDCHK(sb);
1183 	SBLINKRECORD(sb, m0);
1184 	sb->sb_mbtail = m0;
1185 	m = m0->m_next;
1186 	m0->m_next = 0;
1187 	if (m && (m0->m_flags & M_EOR)) {
1188 		m0->m_flags &= ~M_EOR;
1189 		m->m_flags |= M_EOR;
1190 	}
1191 	/* always call sbcompress() so it can do SBLASTMBUFCHK() */
1192 	sbcompress(sb, m, m0);
1193 }
1194 
1195 /*
1196  * As above, except the mbuf chain begins a new record.
1197  */
1198 void
1199 sbappendrecord(struct sockbuf *sb, struct mbuf *m0)
1200 {
1201 
1202 	SOCKBUF_LOCK(sb);
1203 	sbappendrecord_locked(sb, m0);
1204 	SOCKBUF_UNLOCK(sb);
1205 }
1206 
1207 /* Helper routine that appends data, control, and address to a sockbuf. */
1208 static int
1209 sbappendaddr_locked_internal(struct sockbuf *sb, const struct sockaddr *asa,
1210     struct mbuf *m0, struct mbuf *control, struct mbuf *ctrl_last)
1211 {
1212 	struct mbuf *m, *n, *nlast;
1213 
1214 	if (m0 != NULL)
1215 		kmsan_check_mbuf(m0, "sbappend");
1216 	if (control != NULL)
1217 		kmsan_check_mbuf(control, "sbappend");
1218 
1219 #if MSIZE <= 256
1220 	if (asa->sa_len > MLEN)
1221 		return (0);
1222 #endif
1223 	m = m_get(M_NOWAIT, MT_SONAME);
1224 	if (m == NULL)
1225 		return (0);
1226 	m->m_len = asa->sa_len;
1227 	bcopy(asa, mtod(m, caddr_t), asa->sa_len);
1228 	if (m0) {
1229 		M_ASSERT_NO_SND_TAG(m0);
1230 		m_clrprotoflags(m0);
1231 		m_tag_delete_chain(m0, NULL);
1232 		/*
1233 		 * Clear some persistent info from pkthdr.
1234 		 * We don't use m_demote(), because some netgraph consumers
1235 		 * expect M_PKTHDR presence.
1236 		 */
1237 		m0->m_pkthdr.rcvif = NULL;
1238 		m0->m_pkthdr.flowid = 0;
1239 		m0->m_pkthdr.csum_flags = 0;
1240 		m0->m_pkthdr.fibnum = 0;
1241 		m0->m_pkthdr.rsstype = 0;
1242 	}
1243 	if (ctrl_last)
1244 		ctrl_last->m_next = m0;	/* concatenate data to control */
1245 	else
1246 		control = m0;
1247 	m->m_next = control;
1248 	for (n = m; n->m_next != NULL; n = n->m_next)
1249 		sballoc(sb, n);
1250 	sballoc(sb, n);
1251 	nlast = n;
1252 	SBLINKRECORD(sb, m);
1253 
1254 	sb->sb_mbtail = nlast;
1255 	SBLASTMBUFCHK(sb);
1256 
1257 	SBLASTRECORDCHK(sb);
1258 	return (1);
1259 }
1260 
1261 /*
1262  * Append address and data, and optionally, control (ancillary) data to the
1263  * receive queue of a socket.  If present, m0 must include a packet header
1264  * with total length.  Returns 0 if no space in sockbuf or insufficient
1265  * mbufs.
1266  */
1267 int
1268 sbappendaddr_locked(struct sockbuf *sb, const struct sockaddr *asa,
1269     struct mbuf *m0, struct mbuf *control)
1270 {
1271 	struct mbuf *ctrl_last;
1272 	int space = asa->sa_len;
1273 
1274 	SOCKBUF_LOCK_ASSERT(sb);
1275 
1276 	if (m0 && (m0->m_flags & M_PKTHDR) == 0)
1277 		panic("sbappendaddr_locked");
1278 	if (m0)
1279 		space += m0->m_pkthdr.len;
1280 	space += m_length(control, &ctrl_last);
1281 
1282 	if (space > sbspace(sb))
1283 		return (0);
1284 	return (sbappendaddr_locked_internal(sb, asa, m0, control, ctrl_last));
1285 }
1286 
1287 /*
1288  * Append address and data, and optionally, control (ancillary) data to the
1289  * receive queue of a socket.  If present, m0 must include a packet header
1290  * with total length.  Returns 0 if insufficient mbufs.  Does not validate space
1291  * on the receiving sockbuf.
1292  */
1293 int
1294 sbappendaddr_nospacecheck_locked(struct sockbuf *sb, const struct sockaddr *asa,
1295     struct mbuf *m0, struct mbuf *control)
1296 {
1297 	struct mbuf *ctrl_last;
1298 
1299 	SOCKBUF_LOCK_ASSERT(sb);
1300 
1301 	ctrl_last = (control == NULL) ? NULL : m_last(control);
1302 	return (sbappendaddr_locked_internal(sb, asa, m0, control, ctrl_last));
1303 }
1304 
1305 /*
1306  * Append address and data, and optionally, control (ancillary) data to the
1307  * receive queue of a socket.  If present, m0 must include a packet header
1308  * with total length.  Returns 0 if no space in sockbuf or insufficient
1309  * mbufs.
1310  */
1311 int
1312 sbappendaddr(struct sockbuf *sb, const struct sockaddr *asa,
1313     struct mbuf *m0, struct mbuf *control)
1314 {
1315 	int retval;
1316 
1317 	SOCKBUF_LOCK(sb);
1318 	retval = sbappendaddr_locked(sb, asa, m0, control);
1319 	SOCKBUF_UNLOCK(sb);
1320 	return (retval);
1321 }
1322 
1323 void
1324 sbappendcontrol_locked(struct sockbuf *sb, struct mbuf *m0,
1325     struct mbuf *control, int flags)
1326 {
1327 	struct mbuf *m, *mlast;
1328 
1329 	if (m0 != NULL)
1330 		kmsan_check_mbuf(m0, "sbappend");
1331 	kmsan_check_mbuf(control, "sbappend");
1332 
1333 	sbm_clrprotoflags(m0, flags);
1334 	m_last(control)->m_next = m0;
1335 
1336 	SBLASTRECORDCHK(sb);
1337 
1338 	for (m = control; m->m_next; m = m->m_next)
1339 		sballoc(sb, m);
1340 	sballoc(sb, m);
1341 	mlast = m;
1342 	SBLINKRECORD(sb, control);
1343 
1344 	sb->sb_mbtail = mlast;
1345 	SBLASTMBUFCHK(sb);
1346 
1347 	SBLASTRECORDCHK(sb);
1348 }
1349 
1350 void
1351 sbappendcontrol(struct sockbuf *sb, struct mbuf *m0, struct mbuf *control,
1352     int flags)
1353 {
1354 
1355 	SOCKBUF_LOCK(sb);
1356 	sbappendcontrol_locked(sb, m0, control, flags);
1357 	SOCKBUF_UNLOCK(sb);
1358 }
1359 
1360 /*
1361  * Append the data in mbuf chain (m) into the socket buffer sb following mbuf
1362  * (n).  If (n) is NULL, the buffer is presumed empty.
1363  *
1364  * When the data is compressed, mbufs in the chain may be handled in one of
1365  * three ways:
1366  *
1367  * (1) The mbuf may simply be dropped, if it contributes nothing (no data, no
1368  *     record boundary, and no change in data type).
1369  *
1370  * (2) The mbuf may be coalesced -- i.e., data in the mbuf may be copied into
1371  *     an mbuf already in the socket buffer.  This can occur if an
1372  *     appropriate mbuf exists, there is room, both mbufs are not marked as
1373  *     not ready, and no merging of data types will occur.
1374  *
1375  * (3) The mbuf may be appended to the end of the existing mbuf chain.
1376  *
1377  * If any of the new mbufs is marked as M_EOR, mark the last mbuf appended as
1378  * end-of-record.
1379  */
1380 void
1381 sbcompress(struct sockbuf *sb, struct mbuf *m, struct mbuf *n)
1382 {
1383 	int eor = 0;
1384 	struct mbuf *o;
1385 
1386 	SOCKBUF_LOCK_ASSERT(sb);
1387 
1388 	while (m) {
1389 		eor |= m->m_flags & M_EOR;
1390 		if (m->m_len == 0 &&
1391 		    (eor == 0 ||
1392 		     (((o = m->m_next) || (o = n)) &&
1393 		      o->m_type == m->m_type))) {
1394 			if (sb->sb_lastrecord == m)
1395 				sb->sb_lastrecord = m->m_next;
1396 			m = m_free(m);
1397 			continue;
1398 		}
1399 		if (n && (n->m_flags & M_EOR) == 0 &&
1400 		    M_WRITABLE(n) &&
1401 		    ((sb->sb_flags & SB_NOCOALESCE) == 0) &&
1402 		    !(m->m_flags & M_NOTREADY) &&
1403 		    !(n->m_flags & (M_NOTREADY | M_EXTPG)) &&
1404 		    !mbuf_has_tls_session(m) &&
1405 		    !mbuf_has_tls_session(n) &&
1406 		    m->m_len <= MCLBYTES / 4 && /* XXX: Don't copy too much */
1407 		    m->m_len <= M_TRAILINGSPACE(n) &&
1408 		    n->m_type == m->m_type) {
1409 			m_copydata(m, 0, m->m_len, mtodo(n, n->m_len));
1410 			n->m_len += m->m_len;
1411 			sb->sb_ccc += m->m_len;
1412 			if (sb->sb_fnrdy == NULL)
1413 				sb->sb_acc += m->m_len;
1414 			if (m->m_type != MT_DATA && m->m_type != MT_OOBDATA)
1415 				/* XXX: Probably don't need.*/
1416 				sb->sb_ctl += m->m_len;
1417 			m = m_free(m);
1418 			continue;
1419 		}
1420 		if (m->m_len <= MLEN && (m->m_flags & M_EXTPG) &&
1421 		    (m->m_flags & M_NOTREADY) == 0 &&
1422 		    !mbuf_has_tls_session(m))
1423 			(void)mb_unmapped_compress(m);
1424 		if (n)
1425 			n->m_next = m;
1426 		else
1427 			sb->sb_mb = m;
1428 		sb->sb_mbtail = m;
1429 		sballoc(sb, m);
1430 		n = m;
1431 		m->m_flags &= ~M_EOR;
1432 		m = m->m_next;
1433 		n->m_next = 0;
1434 	}
1435 	if (eor) {
1436 		KASSERT(n != NULL, ("sbcompress: eor && n == NULL"));
1437 		n->m_flags |= eor;
1438 	}
1439 	SBLASTMBUFCHK(sb);
1440 }
1441 
1442 #ifdef KERN_TLS
1443 /*
1444  * A version of sbcompress() for encrypted TLS RX mbufs.  These mbufs
1445  * are appended to the 'sb_mtls' chain instead of 'sb_mb' and are also
1446  * a bit simpler (no EOR markers, always MT_DATA, etc.).
1447  */
1448 static void
1449 sbcompress_ktls_rx(struct sockbuf *sb, struct mbuf *m, struct mbuf *n)
1450 {
1451 
1452 	SOCKBUF_LOCK_ASSERT(sb);
1453 
1454 	while (m) {
1455 		KASSERT((m->m_flags & M_EOR) == 0,
1456 		    ("TLS RX mbuf %p with EOR", m));
1457 		KASSERT(m->m_type == MT_DATA,
1458 		    ("TLS RX mbuf %p is not MT_DATA", m));
1459 		KASSERT((m->m_flags & M_NOTREADY) != 0,
1460 		    ("TLS RX mbuf %p ready", m));
1461 		KASSERT((m->m_flags & M_EXTPG) == 0,
1462 		    ("TLS RX mbuf %p unmapped", m));
1463 
1464 		if (m->m_len == 0) {
1465 			m = m_free(m);
1466 			continue;
1467 		}
1468 
1469 		/*
1470 		 * Even though both 'n' and 'm' are NOTREADY, it's ok
1471 		 * to coalesce the data.
1472 		 */
1473 		if (n &&
1474 		    M_WRITABLE(n) &&
1475 		    ((sb->sb_flags & SB_NOCOALESCE) == 0) &&
1476 		    !((m->m_flags ^ n->m_flags) & M_DECRYPTED) &&
1477 		    !(n->m_flags & M_EXTPG) &&
1478 		    m->m_len <= MCLBYTES / 4 && /* XXX: Don't copy too much */
1479 		    m->m_len <= M_TRAILINGSPACE(n)) {
1480 			m_copydata(m, 0, m->m_len, mtodo(n, n->m_len));
1481 			n->m_len += m->m_len;
1482 			sb->sb_ccc += m->m_len;
1483 			sb->sb_tlscc += m->m_len;
1484 			m = m_free(m);
1485 			continue;
1486 		}
1487 		if (n)
1488 			n->m_next = m;
1489 		else
1490 			sb->sb_mtls = m;
1491 		sb->sb_mtlstail = m;
1492 		sballoc_ktls_rx(sb, m);
1493 		n = m;
1494 		m = m->m_next;
1495 		n->m_next = NULL;
1496 	}
1497 	SBLASTMBUFCHK(sb);
1498 }
1499 #endif
1500 
1501 /*
1502  * Free all mbufs in a sockbuf.  Check that all resources are reclaimed.
1503  */
1504 static void
1505 sbflush_internal(struct sockbuf *sb)
1506 {
1507 
1508 	while (sb->sb_mbcnt || sb->sb_tlsdcc) {
1509 		/*
1510 		 * Don't call sbcut(sb, 0) if the leading mbuf is non-empty:
1511 		 * we would loop forever. Panic instead.
1512 		 */
1513 		if (sb->sb_ccc == 0 && (sb->sb_mb == NULL || sb->sb_mb->m_len))
1514 			break;
1515 		m_freem(sbcut_internal(sb, (int)sb->sb_ccc));
1516 	}
1517 	KASSERT(sb->sb_ccc == 0 && sb->sb_mb == 0 && sb->sb_mbcnt == 0,
1518 	    ("%s: ccc %u mb %p mbcnt %u", __func__,
1519 	    sb->sb_ccc, (void *)sb->sb_mb, sb->sb_mbcnt));
1520 }
1521 
1522 void
1523 sbflush_locked(struct sockbuf *sb)
1524 {
1525 
1526 	SOCKBUF_LOCK_ASSERT(sb);
1527 	sbflush_internal(sb);
1528 }
1529 
1530 void
1531 sbflush(struct sockbuf *sb)
1532 {
1533 
1534 	SOCKBUF_LOCK(sb);
1535 	sbflush_locked(sb);
1536 	SOCKBUF_UNLOCK(sb);
1537 }
1538 
1539 /*
1540  * Cut data from (the front of) a sockbuf.
1541  */
1542 static struct mbuf *
1543 sbcut_internal(struct sockbuf *sb, int len)
1544 {
1545 	struct mbuf *m, *next, *mfree;
1546 	bool is_tls;
1547 
1548 	KASSERT(len >= 0, ("%s: len is %d but it is supposed to be >= 0",
1549 	    __func__, len));
1550 	KASSERT(len <= sb->sb_ccc, ("%s: len: %d is > ccc: %u",
1551 	    __func__, len, sb->sb_ccc));
1552 
1553 	next = (m = sb->sb_mb) ? m->m_nextpkt : 0;
1554 	is_tls = false;
1555 	mfree = NULL;
1556 
1557 	while (len > 0) {
1558 		if (m == NULL) {
1559 #ifdef KERN_TLS
1560 			if (next == NULL && !is_tls) {
1561 				if (sb->sb_tlsdcc != 0) {
1562 					MPASS(len >= sb->sb_tlsdcc);
1563 					len -= sb->sb_tlsdcc;
1564 					sb->sb_ccc -= sb->sb_tlsdcc;
1565 					sb->sb_tlsdcc = 0;
1566 					if (len == 0)
1567 						break;
1568 				}
1569 				next = sb->sb_mtls;
1570 				is_tls = true;
1571 			}
1572 #endif
1573 			KASSERT(next, ("%s: no next, len %d", __func__, len));
1574 			m = next;
1575 			next = m->m_nextpkt;
1576 		}
1577 		if (m->m_len > len) {
1578 			KASSERT(!(m->m_flags & M_NOTAVAIL),
1579 			    ("%s: m %p M_NOTAVAIL", __func__, m));
1580 			m->m_len -= len;
1581 			m->m_data += len;
1582 			sb->sb_ccc -= len;
1583 			sb->sb_acc -= len;
1584 			if (sb->sb_sndptroff != 0)
1585 				sb->sb_sndptroff -= len;
1586 			if (m->m_type != MT_DATA && m->m_type != MT_OOBDATA)
1587 				sb->sb_ctl -= len;
1588 			break;
1589 		}
1590 		len -= m->m_len;
1591 #ifdef KERN_TLS
1592 		if (is_tls)
1593 			sbfree_ktls_rx(sb, m);
1594 		else
1595 #endif
1596 			sbfree(sb, m);
1597 		/*
1598 		 * Do not put M_NOTREADY buffers to the free list, they
1599 		 * are referenced from outside.
1600 		 */
1601 		if (m->m_flags & M_NOTREADY && !is_tls)
1602 			m = m->m_next;
1603 		else {
1604 			struct mbuf *n;
1605 
1606 			n = m->m_next;
1607 			m->m_next = mfree;
1608 			mfree = m;
1609 			m = n;
1610 		}
1611 	}
1612 	/*
1613 	 * Free any zero-length mbufs from the buffer.
1614 	 * For SOCK_DGRAM sockets such mbufs represent empty records.
1615 	 * XXX: For SOCK_STREAM sockets such mbufs can appear in the buffer,
1616 	 * when sosend_generic() needs to send only control data.
1617 	 */
1618 	while (m && m->m_len == 0) {
1619 		struct mbuf *n;
1620 
1621 		sbfree(sb, m);
1622 		n = m->m_next;
1623 		m->m_next = mfree;
1624 		mfree = m;
1625 		m = n;
1626 	}
1627 #ifdef KERN_TLS
1628 	if (is_tls) {
1629 		sb->sb_mb = NULL;
1630 		sb->sb_mtls = m;
1631 		if (m == NULL)
1632 			sb->sb_mtlstail = NULL;
1633 	} else
1634 #endif
1635 	if (m) {
1636 		sb->sb_mb = m;
1637 		m->m_nextpkt = next;
1638 	} else
1639 		sb->sb_mb = next;
1640 	/*
1641 	 * First part is an inline SB_EMPTY_FIXUP().  Second part makes sure
1642 	 * sb_lastrecord is up-to-date if we dropped part of the last record.
1643 	 */
1644 	m = sb->sb_mb;
1645 	if (m == NULL) {
1646 		sb->sb_mbtail = NULL;
1647 		sb->sb_lastrecord = NULL;
1648 	} else if (m->m_nextpkt == NULL) {
1649 		sb->sb_lastrecord = m;
1650 	}
1651 
1652 	return (mfree);
1653 }
1654 
1655 /*
1656  * Drop data from (the front of) a sockbuf.
1657  */
1658 void
1659 sbdrop_locked(struct sockbuf *sb, int len)
1660 {
1661 
1662 	SOCKBUF_LOCK_ASSERT(sb);
1663 	m_freem(sbcut_internal(sb, len));
1664 }
1665 
1666 /*
1667  * Drop data from (the front of) a sockbuf,
1668  * and return it to caller.
1669  */
1670 struct mbuf *
1671 sbcut_locked(struct sockbuf *sb, int len)
1672 {
1673 
1674 	SOCKBUF_LOCK_ASSERT(sb);
1675 	return (sbcut_internal(sb, len));
1676 }
1677 
1678 void
1679 sbdrop(struct sockbuf *sb, int len)
1680 {
1681 	struct mbuf *mfree;
1682 
1683 	SOCKBUF_LOCK(sb);
1684 	mfree = sbcut_internal(sb, len);
1685 	SOCKBUF_UNLOCK(sb);
1686 
1687 	m_freem(mfree);
1688 }
1689 
1690 struct mbuf *
1691 sbsndptr_noadv(struct sockbuf *sb, uint32_t off, uint32_t *moff)
1692 {
1693 	struct mbuf *m;
1694 
1695 	KASSERT(sb->sb_mb != NULL, ("%s: sb_mb is NULL", __func__));
1696 	if (sb->sb_sndptr == NULL || sb->sb_sndptroff > off) {
1697 		*moff = off;
1698 		if (sb->sb_sndptr == NULL) {
1699 			sb->sb_sndptr = sb->sb_mb;
1700 			sb->sb_sndptroff = 0;
1701 		}
1702 		return (sb->sb_mb);
1703 	} else {
1704 		m = sb->sb_sndptr;
1705 		off -= sb->sb_sndptroff;
1706 	}
1707 	*moff = off;
1708 	return (m);
1709 }
1710 
1711 void
1712 sbsndptr_adv(struct sockbuf *sb, struct mbuf *mb, uint32_t len)
1713 {
1714 	/*
1715 	 * A small copy was done, advance forward the sb_sbsndptr to cover
1716 	 * it.
1717 	 */
1718 	struct mbuf *m;
1719 
1720 	if (mb != sb->sb_sndptr) {
1721 		/* Did not copyout at the same mbuf */
1722 		return;
1723 	}
1724 	m = mb;
1725 	while (m && (len > 0)) {
1726 		if (len >= m->m_len) {
1727 			len -= m->m_len;
1728 			if (m->m_next) {
1729 				sb->sb_sndptroff += m->m_len;
1730 				sb->sb_sndptr = m->m_next;
1731 			}
1732 			m = m->m_next;
1733 		} else {
1734 			len = 0;
1735 		}
1736 	}
1737 }
1738 
1739 /*
1740  * Return the first mbuf and the mbuf data offset for the provided
1741  * send offset without changing the "sb_sndptroff" field.
1742  */
1743 struct mbuf *
1744 sbsndmbuf(struct sockbuf *sb, u_int off, u_int *moff)
1745 {
1746 	struct mbuf *m;
1747 
1748 	KASSERT(sb->sb_mb != NULL, ("%s: sb_mb is NULL", __func__));
1749 
1750 	/*
1751 	 * If the "off" is below the stored offset, which happens on
1752 	 * retransmits, just use "sb_mb":
1753 	 */
1754 	if (sb->sb_sndptr == NULL || sb->sb_sndptroff > off) {
1755 		m = sb->sb_mb;
1756 	} else {
1757 		m = sb->sb_sndptr;
1758 		off -= sb->sb_sndptroff;
1759 	}
1760 	while (off > 0 && m != NULL) {
1761 		if (off < m->m_len)
1762 			break;
1763 		off -= m->m_len;
1764 		m = m->m_next;
1765 	}
1766 	*moff = off;
1767 	return (m);
1768 }
1769 
1770 /*
1771  * Drop a record off the front of a sockbuf and move the next record to the
1772  * front.
1773  */
1774 void
1775 sbdroprecord_locked(struct sockbuf *sb)
1776 {
1777 	struct mbuf *m;
1778 
1779 	SOCKBUF_LOCK_ASSERT(sb);
1780 
1781 	m = sb->sb_mb;
1782 	if (m) {
1783 		sb->sb_mb = m->m_nextpkt;
1784 		do {
1785 			sbfree(sb, m);
1786 			m = m_free(m);
1787 		} while (m);
1788 	}
1789 	SB_EMPTY_FIXUP(sb);
1790 }
1791 
1792 /*
1793  * Drop a record off the front of a sockbuf and move the next record to the
1794  * front.
1795  */
1796 void
1797 sbdroprecord(struct sockbuf *sb)
1798 {
1799 
1800 	SOCKBUF_LOCK(sb);
1801 	sbdroprecord_locked(sb);
1802 	SOCKBUF_UNLOCK(sb);
1803 }
1804 
1805 /*
1806  * Create a "control" mbuf containing the specified data with the specified
1807  * type for presentation on a socket buffer.
1808  */
1809 struct mbuf *
1810 sbcreatecontrol(const void *p, u_int size, int type, int level, int wait)
1811 {
1812 	struct cmsghdr *cp;
1813 	struct mbuf *m;
1814 
1815 	MBUF_CHECKSLEEP(wait);
1816 
1817 	if (wait == M_NOWAIT) {
1818 		if (CMSG_SPACE(size) > MCLBYTES)
1819 			return (NULL);
1820 	} else
1821 		KASSERT(CMSG_SPACE(size) <= MCLBYTES,
1822 		    ("%s: passed CMSG_SPACE(%u) > MCLBYTES", __func__, size));
1823 
1824 	if (CMSG_SPACE(size) > MLEN)
1825 		m = m_getcl(wait, MT_CONTROL, 0);
1826 	else
1827 		m = m_get(wait, MT_CONTROL);
1828 	if (m == NULL)
1829 		return (NULL);
1830 
1831 	KASSERT(CMSG_SPACE(size) <= M_TRAILINGSPACE(m),
1832 	    ("sbcreatecontrol: short mbuf"));
1833 	/*
1834 	 * Don't leave the padding between the msg header and the
1835 	 * cmsg data and the padding after the cmsg data un-initialized.
1836 	 */
1837 	cp = mtod(m, struct cmsghdr *);
1838 	bzero(cp, CMSG_SPACE(size));
1839 	if (p != NULL)
1840 		(void)memcpy(CMSG_DATA(cp), p, size);
1841 	m->m_len = CMSG_SPACE(size);
1842 	cp->cmsg_len = CMSG_LEN(size);
1843 	cp->cmsg_level = level;
1844 	cp->cmsg_type = type;
1845 	return (m);
1846 }
1847 
1848 /*
1849  * This does the same for socket buffers that sotoxsocket does for sockets:
1850  * generate an user-format data structure describing the socket buffer.  Note
1851  * that the xsockbuf structure, since it is always embedded in a socket, does
1852  * not include a self pointer nor a length.  We make this entry point public
1853  * in case some other mechanism needs it.
1854  */
1855 void
1856 sbtoxsockbuf(struct sockbuf *sb, struct xsockbuf *xsb)
1857 {
1858 
1859 	xsb->sb_cc = sb->sb_ccc;
1860 	xsb->sb_hiwat = sb->sb_hiwat;
1861 	xsb->sb_mbcnt = sb->sb_mbcnt;
1862 	xsb->sb_mbmax = sb->sb_mbmax;
1863 	xsb->sb_lowat = sb->sb_lowat;
1864 	xsb->sb_flags = sb->sb_flags;
1865 	xsb->sb_timeo = sb->sb_timeo;
1866 }
1867 
1868 /* This takes the place of kern.maxsockbuf, which moved to kern.ipc. */
1869 static int dummy;
1870 SYSCTL_INT(_kern, KERN_DUMMY, dummy, CTLFLAG_RW | CTLFLAG_SKIP, &dummy, 0, "");
1871 SYSCTL_OID(_kern_ipc, KIPC_MAXSOCKBUF, maxsockbuf,
1872     CTLTYPE_ULONG | CTLFLAG_RW | CTLFLAG_MPSAFE, &sb_max, 0,
1873     sysctl_handle_sb_max, "LU",
1874     "Maximum socket buffer size");
1875 SYSCTL_ULONG(_kern_ipc, KIPC_SOCKBUF_WASTE, sockbuf_waste_factor, CTLFLAG_RW,
1876     &sb_efficiency, 0, "Socket buffer size waste factor");
1877