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