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