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