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