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