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