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