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