xref: /freebsd/sys/kern/uipc_sockbuf.c (revision c8e7f78a3d28ff6e6223ed136ada8e1e2f34965e)
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 	kmsan_check_mbuf(m0, "sbappend");
1330 	kmsan_check_mbuf(control, "sbappend");
1331 
1332 	sbm_clrprotoflags(m0, flags);
1333 	m_last(control)->m_next = m0;
1334 
1335 	SBLASTRECORDCHK(sb);
1336 
1337 	for (m = control; m->m_next; m = m->m_next)
1338 		sballoc(sb, m);
1339 	sballoc(sb, m);
1340 	mlast = m;
1341 	SBLINKRECORD(sb, control);
1342 
1343 	sb->sb_mbtail = mlast;
1344 	SBLASTMBUFCHK(sb);
1345 
1346 	SBLASTRECORDCHK(sb);
1347 }
1348 
1349 void
1350 sbappendcontrol(struct sockbuf *sb, struct mbuf *m0, struct mbuf *control,
1351     int flags)
1352 {
1353 
1354 	SOCKBUF_LOCK(sb);
1355 	sbappendcontrol_locked(sb, m0, control, flags);
1356 	SOCKBUF_UNLOCK(sb);
1357 }
1358 
1359 /*
1360  * Append the data in mbuf chain (m) into the socket buffer sb following mbuf
1361  * (n).  If (n) is NULL, the buffer is presumed empty.
1362  *
1363  * When the data is compressed, mbufs in the chain may be handled in one of
1364  * three ways:
1365  *
1366  * (1) The mbuf may simply be dropped, if it contributes nothing (no data, no
1367  *     record boundary, and no change in data type).
1368  *
1369  * (2) The mbuf may be coalesced -- i.e., data in the mbuf may be copied into
1370  *     an mbuf already in the socket buffer.  This can occur if an
1371  *     appropriate mbuf exists, there is room, both mbufs are not marked as
1372  *     not ready, and no merging of data types will occur.
1373  *
1374  * (3) The mbuf may be appended to the end of the existing mbuf chain.
1375  *
1376  * If any of the new mbufs is marked as M_EOR, mark the last mbuf appended as
1377  * end-of-record.
1378  */
1379 void
1380 sbcompress(struct sockbuf *sb, struct mbuf *m, struct mbuf *n)
1381 {
1382 	int eor = 0;
1383 	struct mbuf *o;
1384 
1385 	SOCKBUF_LOCK_ASSERT(sb);
1386 
1387 	while (m) {
1388 		eor |= m->m_flags & M_EOR;
1389 		if (m->m_len == 0 &&
1390 		    (eor == 0 ||
1391 		     (((o = m->m_next) || (o = n)) &&
1392 		      o->m_type == m->m_type))) {
1393 			if (sb->sb_lastrecord == m)
1394 				sb->sb_lastrecord = m->m_next;
1395 			m = m_free(m);
1396 			continue;
1397 		}
1398 		if (n && (n->m_flags & M_EOR) == 0 &&
1399 		    M_WRITABLE(n) &&
1400 		    ((sb->sb_flags & SB_NOCOALESCE) == 0) &&
1401 		    !(m->m_flags & M_NOTREADY) &&
1402 		    !(n->m_flags & (M_NOTREADY | M_EXTPG)) &&
1403 		    !mbuf_has_tls_session(m) &&
1404 		    !mbuf_has_tls_session(n) &&
1405 		    m->m_len <= MCLBYTES / 4 && /* XXX: Don't copy too much */
1406 		    m->m_len <= M_TRAILINGSPACE(n) &&
1407 		    n->m_type == m->m_type) {
1408 			m_copydata(m, 0, m->m_len, mtodo(n, n->m_len));
1409 			n->m_len += m->m_len;
1410 			sb->sb_ccc += m->m_len;
1411 			if (sb->sb_fnrdy == NULL)
1412 				sb->sb_acc += m->m_len;
1413 			if (m->m_type != MT_DATA && m->m_type != MT_OOBDATA)
1414 				/* XXX: Probably don't need.*/
1415 				sb->sb_ctl += m->m_len;
1416 			m = m_free(m);
1417 			continue;
1418 		}
1419 		if (m->m_len <= MLEN && (m->m_flags & M_EXTPG) &&
1420 		    (m->m_flags & M_NOTREADY) == 0 &&
1421 		    !mbuf_has_tls_session(m))
1422 			(void)mb_unmapped_compress(m);
1423 		if (n)
1424 			n->m_next = m;
1425 		else
1426 			sb->sb_mb = m;
1427 		sb->sb_mbtail = m;
1428 		sballoc(sb, m);
1429 		n = m;
1430 		m->m_flags &= ~M_EOR;
1431 		m = m->m_next;
1432 		n->m_next = 0;
1433 	}
1434 	if (eor) {
1435 		KASSERT(n != NULL, ("sbcompress: eor && n == NULL"));
1436 		n->m_flags |= eor;
1437 	}
1438 	SBLASTMBUFCHK(sb);
1439 }
1440 
1441 #ifdef KERN_TLS
1442 /*
1443  * A version of sbcompress() for encrypted TLS RX mbufs.  These mbufs
1444  * are appended to the 'sb_mtls' chain instead of 'sb_mb' and are also
1445  * a bit simpler (no EOR markers, always MT_DATA, etc.).
1446  */
1447 static void
1448 sbcompress_ktls_rx(struct sockbuf *sb, struct mbuf *m, struct mbuf *n)
1449 {
1450 
1451 	SOCKBUF_LOCK_ASSERT(sb);
1452 
1453 	while (m) {
1454 		KASSERT((m->m_flags & M_EOR) == 0,
1455 		    ("TLS RX mbuf %p with EOR", m));
1456 		KASSERT(m->m_type == MT_DATA,
1457 		    ("TLS RX mbuf %p is not MT_DATA", m));
1458 		KASSERT((m->m_flags & M_NOTREADY) != 0,
1459 		    ("TLS RX mbuf %p ready", m));
1460 		KASSERT((m->m_flags & M_EXTPG) == 0,
1461 		    ("TLS RX mbuf %p unmapped", m));
1462 
1463 		if (m->m_len == 0) {
1464 			m = m_free(m);
1465 			continue;
1466 		}
1467 
1468 		/*
1469 		 * Even though both 'n' and 'm' are NOTREADY, it's ok
1470 		 * to coalesce the data.
1471 		 */
1472 		if (n &&
1473 		    M_WRITABLE(n) &&
1474 		    ((sb->sb_flags & SB_NOCOALESCE) == 0) &&
1475 		    !((m->m_flags ^ n->m_flags) & M_DECRYPTED) &&
1476 		    !(n->m_flags & M_EXTPG) &&
1477 		    m->m_len <= MCLBYTES / 4 && /* XXX: Don't copy too much */
1478 		    m->m_len <= M_TRAILINGSPACE(n)) {
1479 			m_copydata(m, 0, m->m_len, mtodo(n, n->m_len));
1480 			n->m_len += m->m_len;
1481 			sb->sb_ccc += m->m_len;
1482 			sb->sb_tlscc += m->m_len;
1483 			m = m_free(m);
1484 			continue;
1485 		}
1486 		if (n)
1487 			n->m_next = m;
1488 		else
1489 			sb->sb_mtls = m;
1490 		sb->sb_mtlstail = m;
1491 		sballoc_ktls_rx(sb, m);
1492 		n = m;
1493 		m = m->m_next;
1494 		n->m_next = NULL;
1495 	}
1496 	SBLASTMBUFCHK(sb);
1497 }
1498 #endif
1499 
1500 /*
1501  * Free all mbufs in a sockbuf.  Check that all resources are reclaimed.
1502  */
1503 static void
1504 sbflush_internal(struct sockbuf *sb)
1505 {
1506 
1507 	while (sb->sb_mbcnt || sb->sb_tlsdcc) {
1508 		/*
1509 		 * Don't call sbcut(sb, 0) if the leading mbuf is non-empty:
1510 		 * we would loop forever. Panic instead.
1511 		 */
1512 		if (sb->sb_ccc == 0 && (sb->sb_mb == NULL || sb->sb_mb->m_len))
1513 			break;
1514 		m_freem(sbcut_internal(sb, (int)sb->sb_ccc));
1515 	}
1516 	KASSERT(sb->sb_ccc == 0 && sb->sb_mb == 0 && sb->sb_mbcnt == 0,
1517 	    ("%s: ccc %u mb %p mbcnt %u", __func__,
1518 	    sb->sb_ccc, (void *)sb->sb_mb, sb->sb_mbcnt));
1519 }
1520 
1521 void
1522 sbflush_locked(struct sockbuf *sb)
1523 {
1524 
1525 	SOCKBUF_LOCK_ASSERT(sb);
1526 	sbflush_internal(sb);
1527 }
1528 
1529 void
1530 sbflush(struct sockbuf *sb)
1531 {
1532 
1533 	SOCKBUF_LOCK(sb);
1534 	sbflush_locked(sb);
1535 	SOCKBUF_UNLOCK(sb);
1536 }
1537 
1538 /*
1539  * Cut data from (the front of) a sockbuf.
1540  */
1541 static struct mbuf *
1542 sbcut_internal(struct sockbuf *sb, int len)
1543 {
1544 	struct mbuf *m, *next, *mfree;
1545 	bool is_tls;
1546 
1547 	KASSERT(len >= 0, ("%s: len is %d but it is supposed to be >= 0",
1548 	    __func__, len));
1549 	KASSERT(len <= sb->sb_ccc, ("%s: len: %d is > ccc: %u",
1550 	    __func__, len, sb->sb_ccc));
1551 
1552 	next = (m = sb->sb_mb) ? m->m_nextpkt : 0;
1553 	is_tls = false;
1554 	mfree = NULL;
1555 
1556 	while (len > 0) {
1557 		if (m == NULL) {
1558 #ifdef KERN_TLS
1559 			if (next == NULL && !is_tls) {
1560 				if (sb->sb_tlsdcc != 0) {
1561 					MPASS(len >= sb->sb_tlsdcc);
1562 					len -= sb->sb_tlsdcc;
1563 					sb->sb_ccc -= sb->sb_tlsdcc;
1564 					sb->sb_tlsdcc = 0;
1565 					if (len == 0)
1566 						break;
1567 				}
1568 				next = sb->sb_mtls;
1569 				is_tls = true;
1570 			}
1571 #endif
1572 			KASSERT(next, ("%s: no next, len %d", __func__, len));
1573 			m = next;
1574 			next = m->m_nextpkt;
1575 		}
1576 		if (m->m_len > len) {
1577 			KASSERT(!(m->m_flags & M_NOTAVAIL),
1578 			    ("%s: m %p M_NOTAVAIL", __func__, m));
1579 			m->m_len -= len;
1580 			m->m_data += len;
1581 			sb->sb_ccc -= len;
1582 			sb->sb_acc -= len;
1583 			if (sb->sb_sndptroff != 0)
1584 				sb->sb_sndptroff -= len;
1585 			if (m->m_type != MT_DATA && m->m_type != MT_OOBDATA)
1586 				sb->sb_ctl -= len;
1587 			break;
1588 		}
1589 		len -= m->m_len;
1590 #ifdef KERN_TLS
1591 		if (is_tls)
1592 			sbfree_ktls_rx(sb, m);
1593 		else
1594 #endif
1595 			sbfree(sb, m);
1596 		/*
1597 		 * Do not put M_NOTREADY buffers to the free list, they
1598 		 * are referenced from outside.
1599 		 */
1600 		if (m->m_flags & M_NOTREADY && !is_tls)
1601 			m = m->m_next;
1602 		else {
1603 			struct mbuf *n;
1604 
1605 			n = m->m_next;
1606 			m->m_next = mfree;
1607 			mfree = m;
1608 			m = n;
1609 		}
1610 	}
1611 	/*
1612 	 * Free any zero-length mbufs from the buffer.
1613 	 * For SOCK_DGRAM sockets such mbufs represent empty records.
1614 	 * XXX: For SOCK_STREAM sockets such mbufs can appear in the buffer,
1615 	 * when sosend_generic() needs to send only control data.
1616 	 */
1617 	while (m && m->m_len == 0) {
1618 		struct mbuf *n;
1619 
1620 		sbfree(sb, m);
1621 		n = m->m_next;
1622 		m->m_next = mfree;
1623 		mfree = m;
1624 		m = n;
1625 	}
1626 #ifdef KERN_TLS
1627 	if (is_tls) {
1628 		sb->sb_mb = NULL;
1629 		sb->sb_mtls = m;
1630 		if (m == NULL)
1631 			sb->sb_mtlstail = NULL;
1632 	} else
1633 #endif
1634 	if (m) {
1635 		sb->sb_mb = m;
1636 		m->m_nextpkt = next;
1637 	} else
1638 		sb->sb_mb = next;
1639 	/*
1640 	 * First part is an inline SB_EMPTY_FIXUP().  Second part makes sure
1641 	 * sb_lastrecord is up-to-date if we dropped part of the last record.
1642 	 */
1643 	m = sb->sb_mb;
1644 	if (m == NULL) {
1645 		sb->sb_mbtail = NULL;
1646 		sb->sb_lastrecord = NULL;
1647 	} else if (m->m_nextpkt == NULL) {
1648 		sb->sb_lastrecord = m;
1649 	}
1650 
1651 	return (mfree);
1652 }
1653 
1654 /*
1655  * Drop data from (the front of) a sockbuf.
1656  */
1657 void
1658 sbdrop_locked(struct sockbuf *sb, int len)
1659 {
1660 
1661 	SOCKBUF_LOCK_ASSERT(sb);
1662 	m_freem(sbcut_internal(sb, len));
1663 }
1664 
1665 /*
1666  * Drop data from (the front of) a sockbuf,
1667  * and return it to caller.
1668  */
1669 struct mbuf *
1670 sbcut_locked(struct sockbuf *sb, int len)
1671 {
1672 
1673 	SOCKBUF_LOCK_ASSERT(sb);
1674 	return (sbcut_internal(sb, len));
1675 }
1676 
1677 void
1678 sbdrop(struct sockbuf *sb, int len)
1679 {
1680 	struct mbuf *mfree;
1681 
1682 	SOCKBUF_LOCK(sb);
1683 	mfree = sbcut_internal(sb, len);
1684 	SOCKBUF_UNLOCK(sb);
1685 
1686 	m_freem(mfree);
1687 }
1688 
1689 struct mbuf *
1690 sbsndptr_noadv(struct sockbuf *sb, uint32_t off, uint32_t *moff)
1691 {
1692 	struct mbuf *m;
1693 
1694 	KASSERT(sb->sb_mb != NULL, ("%s: sb_mb is NULL", __func__));
1695 	if (sb->sb_sndptr == NULL || sb->sb_sndptroff > off) {
1696 		*moff = off;
1697 		if (sb->sb_sndptr == NULL) {
1698 			sb->sb_sndptr = sb->sb_mb;
1699 			sb->sb_sndptroff = 0;
1700 		}
1701 		return (sb->sb_mb);
1702 	} else {
1703 		m = sb->sb_sndptr;
1704 		off -= sb->sb_sndptroff;
1705 	}
1706 	*moff = off;
1707 	return (m);
1708 }
1709 
1710 void
1711 sbsndptr_adv(struct sockbuf *sb, struct mbuf *mb, uint32_t len)
1712 {
1713 	/*
1714 	 * A small copy was done, advance forward the sb_sbsndptr to cover
1715 	 * it.
1716 	 */
1717 	struct mbuf *m;
1718 
1719 	if (mb != sb->sb_sndptr) {
1720 		/* Did not copyout at the same mbuf */
1721 		return;
1722 	}
1723 	m = mb;
1724 	while (m && (len > 0)) {
1725 		if (len >= m->m_len) {
1726 			len -= m->m_len;
1727 			if (m->m_next) {
1728 				sb->sb_sndptroff += m->m_len;
1729 				sb->sb_sndptr = m->m_next;
1730 			}
1731 			m = m->m_next;
1732 		} else {
1733 			len = 0;
1734 		}
1735 	}
1736 }
1737 
1738 /*
1739  * Return the first mbuf and the mbuf data offset for the provided
1740  * send offset without changing the "sb_sndptroff" field.
1741  */
1742 struct mbuf *
1743 sbsndmbuf(struct sockbuf *sb, u_int off, u_int *moff)
1744 {
1745 	struct mbuf *m;
1746 
1747 	KASSERT(sb->sb_mb != NULL, ("%s: sb_mb is NULL", __func__));
1748 
1749 	/*
1750 	 * If the "off" is below the stored offset, which happens on
1751 	 * retransmits, just use "sb_mb":
1752 	 */
1753 	if (sb->sb_sndptr == NULL || sb->sb_sndptroff > off) {
1754 		m = sb->sb_mb;
1755 	} else {
1756 		m = sb->sb_sndptr;
1757 		off -= sb->sb_sndptroff;
1758 	}
1759 	while (off > 0 && m != NULL) {
1760 		if (off < m->m_len)
1761 			break;
1762 		off -= m->m_len;
1763 		m = m->m_next;
1764 	}
1765 	*moff = off;
1766 	return (m);
1767 }
1768 
1769 /*
1770  * Drop a record off the front of a sockbuf and move the next record to the
1771  * front.
1772  */
1773 void
1774 sbdroprecord_locked(struct sockbuf *sb)
1775 {
1776 	struct mbuf *m;
1777 
1778 	SOCKBUF_LOCK_ASSERT(sb);
1779 
1780 	m = sb->sb_mb;
1781 	if (m) {
1782 		sb->sb_mb = m->m_nextpkt;
1783 		do {
1784 			sbfree(sb, m);
1785 			m = m_free(m);
1786 		} while (m);
1787 	}
1788 	SB_EMPTY_FIXUP(sb);
1789 }
1790 
1791 /*
1792  * Drop a record off the front of a sockbuf and move the next record to the
1793  * front.
1794  */
1795 void
1796 sbdroprecord(struct sockbuf *sb)
1797 {
1798 
1799 	SOCKBUF_LOCK(sb);
1800 	sbdroprecord_locked(sb);
1801 	SOCKBUF_UNLOCK(sb);
1802 }
1803 
1804 /*
1805  * Create a "control" mbuf containing the specified data with the specified
1806  * type for presentation on a socket buffer.
1807  */
1808 struct mbuf *
1809 sbcreatecontrol(const void *p, u_int size, int type, int level, int wait)
1810 {
1811 	struct cmsghdr *cp;
1812 	struct mbuf *m;
1813 
1814 	MBUF_CHECKSLEEP(wait);
1815 
1816 	if (wait == M_NOWAIT) {
1817 		if (CMSG_SPACE(size) > MCLBYTES)
1818 			return (NULL);
1819 	} else
1820 		KASSERT(CMSG_SPACE(size) <= MCLBYTES,
1821 		    ("%s: passed CMSG_SPACE(%u) > MCLBYTES", __func__, size));
1822 
1823 	if (CMSG_SPACE(size) > MLEN)
1824 		m = m_getcl(wait, MT_CONTROL, 0);
1825 	else
1826 		m = m_get(wait, MT_CONTROL);
1827 	if (m == NULL)
1828 		return (NULL);
1829 
1830 	KASSERT(CMSG_SPACE(size) <= M_TRAILINGSPACE(m),
1831 	    ("sbcreatecontrol: short mbuf"));
1832 	/*
1833 	 * Don't leave the padding between the msg header and the
1834 	 * cmsg data and the padding after the cmsg data un-initialized.
1835 	 */
1836 	cp = mtod(m, struct cmsghdr *);
1837 	bzero(cp, CMSG_SPACE(size));
1838 	if (p != NULL)
1839 		(void)memcpy(CMSG_DATA(cp), p, size);
1840 	m->m_len = CMSG_SPACE(size);
1841 	cp->cmsg_len = CMSG_LEN(size);
1842 	cp->cmsg_level = level;
1843 	cp->cmsg_type = type;
1844 	return (m);
1845 }
1846 
1847 /*
1848  * This does the same for socket buffers that sotoxsocket does for sockets:
1849  * generate an user-format data structure describing the socket buffer.  Note
1850  * that the xsockbuf structure, since it is always embedded in a socket, does
1851  * not include a self pointer nor a length.  We make this entry point public
1852  * in case some other mechanism needs it.
1853  */
1854 void
1855 sbtoxsockbuf(struct sockbuf *sb, struct xsockbuf *xsb)
1856 {
1857 
1858 	xsb->sb_cc = sb->sb_ccc;
1859 	xsb->sb_hiwat = sb->sb_hiwat;
1860 	xsb->sb_mbcnt = sb->sb_mbcnt;
1861 	xsb->sb_mbmax = sb->sb_mbmax;
1862 	xsb->sb_lowat = sb->sb_lowat;
1863 	xsb->sb_flags = sb->sb_flags;
1864 	xsb->sb_timeo = sb->sb_timeo;
1865 }
1866 
1867 /* This takes the place of kern.maxsockbuf, which moved to kern.ipc. */
1868 static int dummy;
1869 SYSCTL_INT(_kern, KERN_DUMMY, dummy, CTLFLAG_RW | CTLFLAG_SKIP, &dummy, 0, "");
1870 SYSCTL_OID(_kern_ipc, KIPC_MAXSOCKBUF, maxsockbuf,
1871     CTLTYPE_ULONG | CTLFLAG_RW | CTLFLAG_MPSAFE, &sb_max, 0,
1872     sysctl_handle_sb_max, "LU",
1873     "Maximum socket buffer size");
1874 SYSCTL_ULONG(_kern_ipc, KIPC_SOCKBUF_WASTE, sockbuf_waste_factor, CTLFLAG_RW,
1875     &sb_efficiency, 0, "Socket buffer size waste factor");
1876