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