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