xref: /freebsd/sys/kern/uipc_sockbuf.c (revision 1e413cf93298b5b97441a21d9a50fdcd0ee9945e)
1 /*-
2  * Copyright (c) 1982, 1986, 1988, 1990, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 4. Neither the name of the University nor the names of its contributors
14  *    may be used to endorse or promote products derived from this software
15  *    without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  *
29  *	@(#)uipc_socket2.c	8.1 (Berkeley) 6/10/93
30  */
31 
32 #include <sys/cdefs.h>
33 __FBSDID("$FreeBSD$");
34 
35 #include "opt_param.h"
36 
37 #include <sys/param.h>
38 #include <sys/aio.h> /* for aio_swake proto */
39 #include <sys/kernel.h>
40 #include <sys/lock.h>
41 #include <sys/mbuf.h>
42 #include <sys/mutex.h>
43 #include <sys/proc.h>
44 #include <sys/protosw.h>
45 #include <sys/resourcevar.h>
46 #include <sys/signalvar.h>
47 #include <sys/socket.h>
48 #include <sys/socketvar.h>
49 #include <sys/sx.h>
50 #include <sys/sysctl.h>
51 
52 /*
53  * Function pointer set by the AIO routines so that the socket buffer code
54  * can call back into the AIO module if it is loaded.
55  */
56 void	(*aio_swake)(struct socket *, struct sockbuf *);
57 
58 /*
59  * Primitive routines for operating on socket buffers
60  */
61 
62 u_long	sb_max = SB_MAX;
63 u_long sb_max_adj =
64        SB_MAX * MCLBYTES / (MSIZE + MCLBYTES); /* adjusted sb_max */
65 
66 static	u_long sb_efficiency = 8;	/* parameter for sbreserve() */
67 
68 static void	sbdrop_internal(struct sockbuf *sb, int len);
69 static void	sbflush_internal(struct sockbuf *sb);
70 static void	sbrelease_internal(struct sockbuf *sb, struct socket *so);
71 
72 /*
73  * Socantsendmore indicates that no more data will be sent on the socket; it
74  * would normally be applied to a socket when the user informs the system
75  * that no more data is to be sent, by the protocol code (in case
76  * PRU_SHUTDOWN).  Socantrcvmore indicates that no more data will be
77  * received, and will normally be applied to the socket by a protocol when it
78  * detects that the peer will send no more data.  Data queued for reading in
79  * the socket may yet be read.
80  */
81 void
82 socantsendmore_locked(struct socket *so)
83 {
84 
85 	SOCKBUF_LOCK_ASSERT(&so->so_snd);
86 
87 	so->so_snd.sb_state |= SBS_CANTSENDMORE;
88 	sowwakeup_locked(so);
89 	mtx_assert(SOCKBUF_MTX(&so->so_snd), MA_NOTOWNED);
90 }
91 
92 void
93 socantsendmore(struct socket *so)
94 {
95 
96 	SOCKBUF_LOCK(&so->so_snd);
97 	socantsendmore_locked(so);
98 	mtx_assert(SOCKBUF_MTX(&so->so_snd), MA_NOTOWNED);
99 }
100 
101 void
102 socantrcvmore_locked(struct socket *so)
103 {
104 
105 	SOCKBUF_LOCK_ASSERT(&so->so_rcv);
106 
107 	so->so_rcv.sb_state |= SBS_CANTRCVMORE;
108 	sorwakeup_locked(so);
109 	mtx_assert(SOCKBUF_MTX(&so->so_rcv), MA_NOTOWNED);
110 }
111 
112 void
113 socantrcvmore(struct socket *so)
114 {
115 
116 	SOCKBUF_LOCK(&so->so_rcv);
117 	socantrcvmore_locked(so);
118 	mtx_assert(SOCKBUF_MTX(&so->so_rcv), MA_NOTOWNED);
119 }
120 
121 /*
122  * Wait for data to arrive at/drain from a socket buffer.
123  */
124 int
125 sbwait(struct sockbuf *sb)
126 {
127 
128 	SOCKBUF_LOCK_ASSERT(sb);
129 
130 	sb->sb_flags |= SB_WAIT;
131 	return (msleep(&sb->sb_cc, &sb->sb_mtx,
132 	    (sb->sb_flags & SB_NOINTR) ? PSOCK : PSOCK | PCATCH, "sbwait",
133 	    sb->sb_timeo));
134 }
135 
136 int
137 sblock(struct sockbuf *sb, int flags)
138 {
139 
140 	if (flags == M_WAITOK) {
141 		if (sb->sb_flags & SB_NOINTR) {
142 			sx_xlock(&sb->sb_sx);
143 			return (0);
144 		}
145 		return (sx_xlock_sig(&sb->sb_sx));
146 	} else {
147 		if (sx_try_xlock(&sb->sb_sx) == 0)
148 			return (EWOULDBLOCK);
149 		return (0);
150 	}
151 }
152 
153 void
154 sbunlock(struct sockbuf *sb)
155 {
156 
157 	sx_xunlock(&sb->sb_sx);
158 }
159 
160 /*
161  * Wakeup processes waiting on a socket buffer.  Do asynchronous notification
162  * via SIGIO if the socket has the SS_ASYNC flag set.
163  *
164  * Called with the socket buffer lock held; will release the lock by the end
165  * of the function.  This allows the caller to acquire the socket buffer lock
166  * while testing for the need for various sorts of wakeup and hold it through
167  * to the point where it's no longer required.  We currently hold the lock
168  * through calls out to other subsystems (with the exception of kqueue), and
169  * then release it to avoid lock order issues.  It's not clear that's
170  * correct.
171  */
172 void
173 sowakeup(struct socket *so, struct sockbuf *sb)
174 {
175 
176 	SOCKBUF_LOCK_ASSERT(sb);
177 
178 	selwakeuppri(&sb->sb_sel, PSOCK);
179 	if (!SEL_WAITING(&sb->sb_sel))
180 		sb->sb_flags &= ~SB_SEL;
181 	if (sb->sb_flags & SB_WAIT) {
182 		sb->sb_flags &= ~SB_WAIT;
183 		wakeup(&sb->sb_cc);
184 	}
185 	KNOTE_LOCKED(&sb->sb_sel.si_note, 0);
186 	SOCKBUF_UNLOCK(sb);
187 	if ((so->so_state & SS_ASYNC) && so->so_sigio != NULL)
188 		pgsigio(&so->so_sigio, SIGIO, 0);
189 	if (sb->sb_flags & SB_UPCALL)
190 		(*so->so_upcall)(so, so->so_upcallarg, M_DONTWAIT);
191 	if (sb->sb_flags & SB_AIO)
192 		aio_swake(so, sb);
193 	mtx_assert(SOCKBUF_MTX(sb), MA_NOTOWNED);
194 }
195 
196 /*
197  * Socket buffer (struct sockbuf) utility routines.
198  *
199  * Each socket contains two socket buffers: one for sending data and one for
200  * receiving data.  Each buffer contains a queue of mbufs, information about
201  * the number of mbufs and amount of data in the queue, and other fields
202  * allowing select() statements and notification on data availability to be
203  * implemented.
204  *
205  * Data stored in a socket buffer is maintained as a list of records.  Each
206  * record is a list of mbufs chained together with the m_next field.  Records
207  * are chained together with the m_nextpkt field. The upper level routine
208  * soreceive() expects the following conventions to be observed when placing
209  * information in the receive buffer:
210  *
211  * 1. If the protocol requires each message be preceded by the sender's name,
212  *    then a record containing that name must be present before any
213  *    associated data (mbuf's must be of type MT_SONAME).
214  * 2. If the protocol supports the exchange of ``access rights'' (really just
215  *    additional data associated with the message), and there are ``rights''
216  *    to be received, then a record containing this data should be present
217  *    (mbuf's must be of type MT_RIGHTS).
218  * 3. If a name or rights record exists, then it must be followed by a data
219  *    record, perhaps of zero length.
220  *
221  * Before using a new socket structure it is first necessary to reserve
222  * buffer space to the socket, by calling sbreserve().  This should commit
223  * some of the available buffer space in the system buffer pool for the
224  * socket (currently, it does nothing but enforce limits).  The space should
225  * be released by calling sbrelease() when the socket is destroyed.
226  */
227 int
228 soreserve(struct socket *so, u_long sndcc, u_long rcvcc)
229 {
230 	struct thread *td = curthread;
231 
232 	SOCKBUF_LOCK(&so->so_snd);
233 	SOCKBUF_LOCK(&so->so_rcv);
234 	if (sbreserve_locked(&so->so_snd, sndcc, so, td) == 0)
235 		goto bad;
236 	if (sbreserve_locked(&so->so_rcv, rcvcc, so, td) == 0)
237 		goto bad2;
238 	if (so->so_rcv.sb_lowat == 0)
239 		so->so_rcv.sb_lowat = 1;
240 	if (so->so_snd.sb_lowat == 0)
241 		so->so_snd.sb_lowat = MCLBYTES;
242 	if (so->so_snd.sb_lowat > so->so_snd.sb_hiwat)
243 		so->so_snd.sb_lowat = so->so_snd.sb_hiwat;
244 	SOCKBUF_UNLOCK(&so->so_rcv);
245 	SOCKBUF_UNLOCK(&so->so_snd);
246 	return (0);
247 bad2:
248 	sbrelease_locked(&so->so_snd, so);
249 bad:
250 	SOCKBUF_UNLOCK(&so->so_rcv);
251 	SOCKBUF_UNLOCK(&so->so_snd);
252 	return (ENOBUFS);
253 }
254 
255 static int
256 sysctl_handle_sb_max(SYSCTL_HANDLER_ARGS)
257 {
258 	int error = 0;
259 	u_long tmp_sb_max = sb_max;
260 
261 	error = sysctl_handle_long(oidp, &tmp_sb_max, arg2, req);
262 	if (error || !req->newptr)
263 		return (error);
264 	if (tmp_sb_max < MSIZE + MCLBYTES)
265 		return (EINVAL);
266 	sb_max = tmp_sb_max;
267 	sb_max_adj = (u_quad_t)sb_max * MCLBYTES / (MSIZE + MCLBYTES);
268 	return (0);
269 }
270 
271 /*
272  * Allot mbufs to a sockbuf.  Attempt to scale mbmax so that mbcnt doesn't
273  * become limiting if buffering efficiency is near the normal case.
274  */
275 int
276 sbreserve_locked(struct sockbuf *sb, u_long cc, struct socket *so,
277     struct thread *td)
278 {
279 	rlim_t sbsize_limit;
280 
281 	SOCKBUF_LOCK_ASSERT(sb);
282 
283 	/*
284 	 * td will only be NULL when we're in an interrupt (e.g. in
285 	 * tcp_input()).
286 	 *
287 	 * XXXRW: This comment needs updating, as might the code.
288 	 */
289 	if (cc > sb_max_adj)
290 		return (0);
291 	if (td != NULL) {
292 		PROC_LOCK(td->td_proc);
293 		sbsize_limit = lim_cur(td->td_proc, RLIMIT_SBSIZE);
294 		PROC_UNLOCK(td->td_proc);
295 	} else
296 		sbsize_limit = RLIM_INFINITY;
297 	if (!chgsbsize(so->so_cred->cr_uidinfo, &sb->sb_hiwat, cc,
298 	    sbsize_limit))
299 		return (0);
300 	sb->sb_mbmax = min(cc * sb_efficiency, sb_max);
301 	if (sb->sb_lowat > sb->sb_hiwat)
302 		sb->sb_lowat = sb->sb_hiwat;
303 	return (1);
304 }
305 
306 int
307 sbreserve(struct sockbuf *sb, u_long cc, struct socket *so,
308     struct thread *td)
309 {
310 	int error;
311 
312 	SOCKBUF_LOCK(sb);
313 	error = sbreserve_locked(sb, cc, so, td);
314 	SOCKBUF_UNLOCK(sb);
315 	return (error);
316 }
317 
318 /*
319  * Free mbufs held by a socket, and reserved mbuf space.
320  */
321 static void
322 sbrelease_internal(struct sockbuf *sb, struct socket *so)
323 {
324 
325 	sbflush_internal(sb);
326 	(void)chgsbsize(so->so_cred->cr_uidinfo, &sb->sb_hiwat, 0,
327 	    RLIM_INFINITY);
328 	sb->sb_mbmax = 0;
329 }
330 
331 void
332 sbrelease_locked(struct sockbuf *sb, struct socket *so)
333 {
334 
335 	SOCKBUF_LOCK_ASSERT(sb);
336 
337 	sbrelease_internal(sb, so);
338 }
339 
340 void
341 sbrelease(struct sockbuf *sb, struct socket *so)
342 {
343 
344 	SOCKBUF_LOCK(sb);
345 	sbrelease_locked(sb, so);
346 	SOCKBUF_UNLOCK(sb);
347 }
348 
349 void
350 sbdestroy(struct sockbuf *sb, struct socket *so)
351 {
352 
353 	sbrelease_internal(sb, so);
354 }
355 
356 /*
357  * Routines to add and remove data from an mbuf queue.
358  *
359  * The routines sbappend() or sbappendrecord() are normally called to append
360  * new mbufs to a socket buffer, after checking that adequate space is
361  * available, comparing the function sbspace() with the amount of data to be
362  * added.  sbappendrecord() differs from sbappend() in that data supplied is
363  * treated as the beginning of a new record.  To place a sender's address,
364  * optional access rights, and data in a socket receive buffer,
365  * sbappendaddr() should be used.  To place access rights and data in a
366  * socket receive buffer, sbappendrights() should be used.  In either case,
367  * the new data begins a new record.  Note that unlike sbappend() and
368  * sbappendrecord(), these routines check for the caller that there will be
369  * enough space to store the data.  Each fails if there is not enough space,
370  * or if it cannot find mbufs to store additional information in.
371  *
372  * Reliable protocols may use the socket send buffer to hold data awaiting
373  * acknowledgement.  Data is normally copied from a socket send buffer in a
374  * protocol with m_copy for output to a peer, and then removing the data from
375  * the socket buffer with sbdrop() or sbdroprecord() when the data is
376  * acknowledged by the peer.
377  */
378 #ifdef SOCKBUF_DEBUG
379 void
380 sblastrecordchk(struct sockbuf *sb, const char *file, int line)
381 {
382 	struct mbuf *m = sb->sb_mb;
383 
384 	SOCKBUF_LOCK_ASSERT(sb);
385 
386 	while (m && m->m_nextpkt)
387 		m = m->m_nextpkt;
388 
389 	if (m != sb->sb_lastrecord) {
390 		printf("%s: sb_mb %p sb_lastrecord %p last %p\n",
391 			__func__, sb->sb_mb, sb->sb_lastrecord, m);
392 		printf("packet chain:\n");
393 		for (m = sb->sb_mb; m != NULL; m = m->m_nextpkt)
394 			printf("\t%p\n", m);
395 		panic("%s from %s:%u", __func__, file, line);
396 	}
397 }
398 
399 void
400 sblastmbufchk(struct sockbuf *sb, const char *file, int line)
401 {
402 	struct mbuf *m = sb->sb_mb;
403 	struct mbuf *n;
404 
405 	SOCKBUF_LOCK_ASSERT(sb);
406 
407 	while (m && m->m_nextpkt)
408 		m = m->m_nextpkt;
409 
410 	while (m && m->m_next)
411 		m = m->m_next;
412 
413 	if (m != sb->sb_mbtail) {
414 		printf("%s: sb_mb %p sb_mbtail %p last %p\n",
415 			__func__, sb->sb_mb, sb->sb_mbtail, m);
416 		printf("packet tree:\n");
417 		for (m = sb->sb_mb; m != NULL; m = m->m_nextpkt) {
418 			printf("\t");
419 			for (n = m; n != NULL; n = n->m_next)
420 				printf("%p ", n);
421 			printf("\n");
422 		}
423 		panic("%s from %s:%u", __func__, file, line);
424 	}
425 }
426 #endif /* SOCKBUF_DEBUG */
427 
428 #define SBLINKRECORD(sb, m0) do {					\
429 	SOCKBUF_LOCK_ASSERT(sb);					\
430 	if ((sb)->sb_lastrecord != NULL)				\
431 		(sb)->sb_lastrecord->m_nextpkt = (m0);			\
432 	else								\
433 		(sb)->sb_mb = (m0);					\
434 	(sb)->sb_lastrecord = (m0);					\
435 } while (/*CONSTCOND*/0)
436 
437 /*
438  * Append mbuf chain m to the last record in the socket buffer sb.  The
439  * additional space associated the mbuf chain is recorded in sb.  Empty mbufs
440  * are discarded and mbufs are compacted where possible.
441  */
442 void
443 sbappend_locked(struct sockbuf *sb, struct mbuf *m)
444 {
445 	struct mbuf *n;
446 
447 	SOCKBUF_LOCK_ASSERT(sb);
448 
449 	if (m == 0)
450 		return;
451 
452 	SBLASTRECORDCHK(sb);
453 	n = sb->sb_mb;
454 	if (n) {
455 		while (n->m_nextpkt)
456 			n = n->m_nextpkt;
457 		do {
458 			if (n->m_flags & M_EOR) {
459 				sbappendrecord_locked(sb, m); /* XXXXXX!!!! */
460 				return;
461 			}
462 		} while (n->m_next && (n = n->m_next));
463 	} else {
464 		/*
465 		 * XXX Would like to simply use sb_mbtail here, but
466 		 * XXX I need to verify that I won't miss an EOR that
467 		 * XXX way.
468 		 */
469 		if ((n = sb->sb_lastrecord) != NULL) {
470 			do {
471 				if (n->m_flags & M_EOR) {
472 					sbappendrecord_locked(sb, m); /* XXXXXX!!!! */
473 					return;
474 				}
475 			} while (n->m_next && (n = n->m_next));
476 		} else {
477 			/*
478 			 * If this is the first record in the socket buffer,
479 			 * it's also the last record.
480 			 */
481 			sb->sb_lastrecord = m;
482 		}
483 	}
484 	sbcompress(sb, m, n);
485 	SBLASTRECORDCHK(sb);
486 }
487 
488 /*
489  * Append mbuf chain m to the last record in the socket buffer sb.  The
490  * additional space associated the mbuf chain is recorded in sb.  Empty mbufs
491  * are discarded and mbufs are compacted where possible.
492  */
493 void
494 sbappend(struct sockbuf *sb, struct mbuf *m)
495 {
496 
497 	SOCKBUF_LOCK(sb);
498 	sbappend_locked(sb, m);
499 	SOCKBUF_UNLOCK(sb);
500 }
501 
502 /*
503  * This version of sbappend() should only be used when the caller absolutely
504  * knows that there will never be more than one record in the socket buffer,
505  * that is, a stream protocol (such as TCP).
506  */
507 void
508 sbappendstream_locked(struct sockbuf *sb, struct mbuf *m)
509 {
510 	SOCKBUF_LOCK_ASSERT(sb);
511 
512 	KASSERT(m->m_nextpkt == NULL,("sbappendstream 0"));
513 	KASSERT(sb->sb_mb == sb->sb_lastrecord,("sbappendstream 1"));
514 
515 	SBLASTMBUFCHK(sb);
516 
517 	sbcompress(sb, m, sb->sb_mbtail);
518 
519 	sb->sb_lastrecord = sb->sb_mb;
520 	SBLASTRECORDCHK(sb);
521 }
522 
523 /*
524  * This version of sbappend() should only be used when the caller absolutely
525  * knows that there will never be more than one record in the socket buffer,
526  * that is, a stream protocol (such as TCP).
527  */
528 void
529 sbappendstream(struct sockbuf *sb, struct mbuf *m)
530 {
531 
532 	SOCKBUF_LOCK(sb);
533 	sbappendstream_locked(sb, m);
534 	SOCKBUF_UNLOCK(sb);
535 }
536 
537 #ifdef SOCKBUF_DEBUG
538 void
539 sbcheck(struct sockbuf *sb)
540 {
541 	struct mbuf *m;
542 	struct mbuf *n = 0;
543 	u_long len = 0, mbcnt = 0;
544 
545 	SOCKBUF_LOCK_ASSERT(sb);
546 
547 	for (m = sb->sb_mb; m; m = n) {
548 	    n = m->m_nextpkt;
549 	    for (; m; m = m->m_next) {
550 		len += m->m_len;
551 		mbcnt += MSIZE;
552 		if (m->m_flags & M_EXT) /*XXX*/ /* pretty sure this is bogus */
553 			mbcnt += m->m_ext.ext_size;
554 	    }
555 	}
556 	if (len != sb->sb_cc || mbcnt != sb->sb_mbcnt) {
557 		printf("cc %ld != %u || mbcnt %ld != %u\n", len, sb->sb_cc,
558 		    mbcnt, sb->sb_mbcnt);
559 		panic("sbcheck");
560 	}
561 }
562 #endif
563 
564 /*
565  * As above, except the mbuf chain begins a new record.
566  */
567 void
568 sbappendrecord_locked(struct sockbuf *sb, struct mbuf *m0)
569 {
570 	struct mbuf *m;
571 
572 	SOCKBUF_LOCK_ASSERT(sb);
573 
574 	if (m0 == 0)
575 		return;
576 	m = sb->sb_mb;
577 	if (m)
578 		while (m->m_nextpkt)
579 			m = m->m_nextpkt;
580 	/*
581 	 * Put the first mbuf on the queue.  Note this permits zero length
582 	 * records.
583 	 */
584 	sballoc(sb, m0);
585 	SBLASTRECORDCHK(sb);
586 	SBLINKRECORD(sb, m0);
587 	if (m)
588 		m->m_nextpkt = m0;
589 	else
590 		sb->sb_mb = m0;
591 	m = m0->m_next;
592 	m0->m_next = 0;
593 	if (m && (m0->m_flags & M_EOR)) {
594 		m0->m_flags &= ~M_EOR;
595 		m->m_flags |= M_EOR;
596 	}
597 	sbcompress(sb, m, m0);
598 }
599 
600 /*
601  * As above, except the mbuf chain begins a new record.
602  */
603 void
604 sbappendrecord(struct sockbuf *sb, struct mbuf *m0)
605 {
606 
607 	SOCKBUF_LOCK(sb);
608 	sbappendrecord_locked(sb, m0);
609 	SOCKBUF_UNLOCK(sb);
610 }
611 
612 /*
613  * Append address and data, and optionally, control (ancillary) data to the
614  * receive queue of a socket.  If present, m0 must include a packet header
615  * with total length.  Returns 0 if no space in sockbuf or insufficient
616  * mbufs.
617  */
618 int
619 sbappendaddr_locked(struct sockbuf *sb, const struct sockaddr *asa,
620     struct mbuf *m0, struct mbuf *control)
621 {
622 	struct mbuf *m, *n, *nlast;
623 	int space = asa->sa_len;
624 
625 	SOCKBUF_LOCK_ASSERT(sb);
626 
627 	if (m0 && (m0->m_flags & M_PKTHDR) == 0)
628 		panic("sbappendaddr_locked");
629 	if (m0)
630 		space += m0->m_pkthdr.len;
631 	space += m_length(control, &n);
632 
633 	if (space > sbspace(sb))
634 		return (0);
635 #if MSIZE <= 256
636 	if (asa->sa_len > MLEN)
637 		return (0);
638 #endif
639 	MGET(m, M_DONTWAIT, MT_SONAME);
640 	if (m == 0)
641 		return (0);
642 	m->m_len = asa->sa_len;
643 	bcopy(asa, mtod(m, caddr_t), asa->sa_len);
644 	if (n)
645 		n->m_next = m0;		/* concatenate data to control */
646 	else
647 		control = m0;
648 	m->m_next = control;
649 	for (n = m; n->m_next != NULL; n = n->m_next)
650 		sballoc(sb, n);
651 	sballoc(sb, n);
652 	nlast = n;
653 	SBLINKRECORD(sb, m);
654 
655 	sb->sb_mbtail = nlast;
656 	SBLASTMBUFCHK(sb);
657 
658 	SBLASTRECORDCHK(sb);
659 	return (1);
660 }
661 
662 /*
663  * Append address and data, and optionally, control (ancillary) data to the
664  * receive queue of a socket.  If present, m0 must include a packet header
665  * with total length.  Returns 0 if no space in sockbuf or insufficient
666  * mbufs.
667  */
668 int
669 sbappendaddr(struct sockbuf *sb, const struct sockaddr *asa,
670     struct mbuf *m0, struct mbuf *control)
671 {
672 	int retval;
673 
674 	SOCKBUF_LOCK(sb);
675 	retval = sbappendaddr_locked(sb, asa, m0, control);
676 	SOCKBUF_UNLOCK(sb);
677 	return (retval);
678 }
679 
680 int
681 sbappendcontrol_locked(struct sockbuf *sb, struct mbuf *m0,
682     struct mbuf *control)
683 {
684 	struct mbuf *m, *n, *mlast;
685 	int space;
686 
687 	SOCKBUF_LOCK_ASSERT(sb);
688 
689 	if (control == 0)
690 		panic("sbappendcontrol_locked");
691 	space = m_length(control, &n) + m_length(m0, NULL);
692 
693 	if (space > sbspace(sb))
694 		return (0);
695 	n->m_next = m0;			/* concatenate data to control */
696 
697 	SBLASTRECORDCHK(sb);
698 
699 	for (m = control; m->m_next; m = m->m_next)
700 		sballoc(sb, m);
701 	sballoc(sb, m);
702 	mlast = m;
703 	SBLINKRECORD(sb, control);
704 
705 	sb->sb_mbtail = mlast;
706 	SBLASTMBUFCHK(sb);
707 
708 	SBLASTRECORDCHK(sb);
709 	return (1);
710 }
711 
712 int
713 sbappendcontrol(struct sockbuf *sb, struct mbuf *m0, struct mbuf *control)
714 {
715 	int retval;
716 
717 	SOCKBUF_LOCK(sb);
718 	retval = sbappendcontrol_locked(sb, m0, control);
719 	SOCKBUF_UNLOCK(sb);
720 	return (retval);
721 }
722 
723 /*
724  * Append the data in mbuf chain (m) into the socket buffer sb following mbuf
725  * (n).  If (n) is NULL, the buffer is presumed empty.
726  *
727  * When the data is compressed, mbufs in the chain may be handled in one of
728  * three ways:
729  *
730  * (1) The mbuf may simply be dropped, if it contributes nothing (no data, no
731  *     record boundary, and no change in data type).
732  *
733  * (2) The mbuf may be coalesced -- i.e., data in the mbuf may be copied into
734  *     an mbuf already in the socket buffer.  This can occur if an
735  *     appropriate mbuf exists, there is room, and no merging of data types
736  *     will occur.
737  *
738  * (3) The mbuf may be appended to the end of the existing mbuf chain.
739  *
740  * If any of the new mbufs is marked as M_EOR, mark the last mbuf appended as
741  * end-of-record.
742  */
743 void
744 sbcompress(struct sockbuf *sb, struct mbuf *m, struct mbuf *n)
745 {
746 	int eor = 0;
747 	struct mbuf *o;
748 
749 	SOCKBUF_LOCK_ASSERT(sb);
750 
751 	while (m) {
752 		eor |= m->m_flags & M_EOR;
753 		if (m->m_len == 0 &&
754 		    (eor == 0 ||
755 		     (((o = m->m_next) || (o = n)) &&
756 		      o->m_type == m->m_type))) {
757 			if (sb->sb_lastrecord == m)
758 				sb->sb_lastrecord = m->m_next;
759 			m = m_free(m);
760 			continue;
761 		}
762 		if (n && (n->m_flags & M_EOR) == 0 &&
763 		    M_WRITABLE(n) &&
764 		    ((sb->sb_flags & SB_NOCOALESCE) == 0) &&
765 		    m->m_len <= MCLBYTES / 4 && /* XXX: Don't copy too much */
766 		    m->m_len <= M_TRAILINGSPACE(n) &&
767 		    n->m_type == m->m_type) {
768 			bcopy(mtod(m, caddr_t), mtod(n, caddr_t) + n->m_len,
769 			    (unsigned)m->m_len);
770 			n->m_len += m->m_len;
771 			sb->sb_cc += m->m_len;
772 			if (m->m_type != MT_DATA && m->m_type != MT_OOBDATA)
773 				/* XXX: Probably don't need.*/
774 				sb->sb_ctl += m->m_len;
775 			m = m_free(m);
776 			continue;
777 		}
778 		if (n)
779 			n->m_next = m;
780 		else
781 			sb->sb_mb = m;
782 		sb->sb_mbtail = m;
783 		sballoc(sb, m);
784 		n = m;
785 		m->m_flags &= ~M_EOR;
786 		m = m->m_next;
787 		n->m_next = 0;
788 	}
789 	if (eor) {
790 		KASSERT(n != NULL, ("sbcompress: eor && n == NULL"));
791 		n->m_flags |= eor;
792 	}
793 	SBLASTMBUFCHK(sb);
794 }
795 
796 /*
797  * Free all mbufs in a sockbuf.  Check that all resources are reclaimed.
798  */
799 static void
800 sbflush_internal(struct sockbuf *sb)
801 {
802 
803 	while (sb->sb_mbcnt) {
804 		/*
805 		 * Don't call sbdrop(sb, 0) if the leading mbuf is non-empty:
806 		 * we would loop forever. Panic instead.
807 		 */
808 		if (!sb->sb_cc && (sb->sb_mb == NULL || sb->sb_mb->m_len))
809 			break;
810 		sbdrop_internal(sb, (int)sb->sb_cc);
811 	}
812 	if (sb->sb_cc || sb->sb_mb || sb->sb_mbcnt)
813 		panic("sbflush_internal: cc %u || mb %p || mbcnt %u",
814 		    sb->sb_cc, (void *)sb->sb_mb, sb->sb_mbcnt);
815 }
816 
817 void
818 sbflush_locked(struct sockbuf *sb)
819 {
820 
821 	SOCKBUF_LOCK_ASSERT(sb);
822 	sbflush_internal(sb);
823 }
824 
825 void
826 sbflush(struct sockbuf *sb)
827 {
828 
829 	SOCKBUF_LOCK(sb);
830 	sbflush_locked(sb);
831 	SOCKBUF_UNLOCK(sb);
832 }
833 
834 /*
835  * Drop data from (the front of) a sockbuf.
836  */
837 static void
838 sbdrop_internal(struct sockbuf *sb, int len)
839 {
840 	struct mbuf *m;
841 	struct mbuf *next;
842 
843 	next = (m = sb->sb_mb) ? m->m_nextpkt : 0;
844 	while (len > 0) {
845 		if (m == 0) {
846 			if (next == 0)
847 				panic("sbdrop");
848 			m = next;
849 			next = m->m_nextpkt;
850 			continue;
851 		}
852 		if (m->m_len > len) {
853 			m->m_len -= len;
854 			m->m_data += len;
855 			sb->sb_cc -= len;
856 			if (sb->sb_sndptroff != 0)
857 				sb->sb_sndptroff -= len;
858 			if (m->m_type != MT_DATA && m->m_type != MT_OOBDATA)
859 				sb->sb_ctl -= len;
860 			break;
861 		}
862 		len -= m->m_len;
863 		sbfree(sb, m);
864 		m = m_free(m);
865 	}
866 	while (m && m->m_len == 0) {
867 		sbfree(sb, m);
868 		m = m_free(m);
869 	}
870 	if (m) {
871 		sb->sb_mb = m;
872 		m->m_nextpkt = next;
873 	} else
874 		sb->sb_mb = next;
875 	/*
876 	 * First part is an inline SB_EMPTY_FIXUP().  Second part makes sure
877 	 * sb_lastrecord is up-to-date if we dropped part of the last record.
878 	 */
879 	m = sb->sb_mb;
880 	if (m == NULL) {
881 		sb->sb_mbtail = NULL;
882 		sb->sb_lastrecord = NULL;
883 	} else if (m->m_nextpkt == NULL) {
884 		sb->sb_lastrecord = m;
885 	}
886 }
887 
888 /*
889  * Drop data from (the front of) a sockbuf.
890  */
891 void
892 sbdrop_locked(struct sockbuf *sb, int len)
893 {
894 
895 	SOCKBUF_LOCK_ASSERT(sb);
896 
897 	sbdrop_internal(sb, len);
898 }
899 
900 void
901 sbdrop(struct sockbuf *sb, int len)
902 {
903 
904 	SOCKBUF_LOCK(sb);
905 	sbdrop_locked(sb, len);
906 	SOCKBUF_UNLOCK(sb);
907 }
908 
909 /*
910  * Maintain a pointer and offset pair into the socket buffer mbuf chain to
911  * avoid traversal of the entire socket buffer for larger offsets.
912  */
913 struct mbuf *
914 sbsndptr(struct sockbuf *sb, u_int off, u_int len, u_int *moff)
915 {
916 	struct mbuf *m, *ret;
917 
918 	KASSERT(sb->sb_mb != NULL, ("%s: sb_mb is NULL", __func__));
919 	KASSERT(off + len <= sb->sb_cc, ("%s: beyond sb", __func__));
920 	KASSERT(sb->sb_sndptroff <= sb->sb_cc, ("%s: sndptroff broken", __func__));
921 
922 	/*
923 	 * Is off below stored offset? Happens on retransmits.
924 	 * Just return, we can't help here.
925 	 */
926 	if (sb->sb_sndptroff > off) {
927 		*moff = off;
928 		return (sb->sb_mb);
929 	}
930 
931 	/* Return closest mbuf in chain for current offset. */
932 	*moff = off - sb->sb_sndptroff;
933 	m = ret = sb->sb_sndptr ? sb->sb_sndptr : sb->sb_mb;
934 
935 	/* Advance by len to be as close as possible for the next transmit. */
936 	for (off = off - sb->sb_sndptroff + len - 1;
937 	     off > 0 && off >= m->m_len;
938 	     m = m->m_next) {
939 		sb->sb_sndptroff += m->m_len;
940 		off -= m->m_len;
941 	}
942 	sb->sb_sndptr = m;
943 
944 	return (ret);
945 }
946 
947 /*
948  * Drop a record off the front of a sockbuf and move the next record to the
949  * front.
950  */
951 void
952 sbdroprecord_locked(struct sockbuf *sb)
953 {
954 	struct mbuf *m;
955 
956 	SOCKBUF_LOCK_ASSERT(sb);
957 
958 	m = sb->sb_mb;
959 	if (m) {
960 		sb->sb_mb = m->m_nextpkt;
961 		do {
962 			sbfree(sb, m);
963 			m = m_free(m);
964 		} while (m);
965 	}
966 	SB_EMPTY_FIXUP(sb);
967 }
968 
969 /*
970  * Drop a record off the front of a sockbuf and move the next record to the
971  * front.
972  */
973 void
974 sbdroprecord(struct sockbuf *sb)
975 {
976 
977 	SOCKBUF_LOCK(sb);
978 	sbdroprecord_locked(sb);
979 	SOCKBUF_UNLOCK(sb);
980 }
981 
982 /*
983  * Create a "control" mbuf containing the specified data with the specified
984  * type for presentation on a socket buffer.
985  */
986 struct mbuf *
987 sbcreatecontrol(caddr_t p, int size, int type, int level)
988 {
989 	struct cmsghdr *cp;
990 	struct mbuf *m;
991 
992 	if (CMSG_SPACE((u_int)size) > MCLBYTES)
993 		return ((struct mbuf *) NULL);
994 	if (CMSG_SPACE((u_int)size) > MLEN)
995 		m = m_getcl(M_DONTWAIT, MT_CONTROL, 0);
996 	else
997 		m = m_get(M_DONTWAIT, MT_CONTROL);
998 	if (m == NULL)
999 		return ((struct mbuf *) NULL);
1000 	cp = mtod(m, struct cmsghdr *);
1001 	m->m_len = 0;
1002 	KASSERT(CMSG_SPACE((u_int)size) <= M_TRAILINGSPACE(m),
1003 	    ("sbcreatecontrol: short mbuf"));
1004 	if (p != NULL)
1005 		(void)memcpy(CMSG_DATA(cp), p, size);
1006 	m->m_len = CMSG_SPACE(size);
1007 	cp->cmsg_len = CMSG_LEN(size);
1008 	cp->cmsg_level = level;
1009 	cp->cmsg_type = type;
1010 	return (m);
1011 }
1012 
1013 /*
1014  * This does the same for socket buffers that sotoxsocket does for sockets:
1015  * generate an user-format data structure describing the socket buffer.  Note
1016  * that the xsockbuf structure, since it is always embedded in a socket, does
1017  * not include a self pointer nor a length.  We make this entry point public
1018  * in case some other mechanism needs it.
1019  */
1020 void
1021 sbtoxsockbuf(struct sockbuf *sb, struct xsockbuf *xsb)
1022 {
1023 
1024 	xsb->sb_cc = sb->sb_cc;
1025 	xsb->sb_hiwat = sb->sb_hiwat;
1026 	xsb->sb_mbcnt = sb->sb_mbcnt;
1027 	xsb->sb_mbmax = sb->sb_mbmax;
1028 	xsb->sb_lowat = sb->sb_lowat;
1029 	xsb->sb_flags = sb->sb_flags;
1030 	xsb->sb_timeo = sb->sb_timeo;
1031 }
1032 
1033 /* This takes the place of kern.maxsockbuf, which moved to kern.ipc. */
1034 static int dummy;
1035 SYSCTL_INT(_kern, KERN_DUMMY, dummy, CTLFLAG_RW, &dummy, 0, "");
1036 SYSCTL_OID(_kern_ipc, KIPC_MAXSOCKBUF, maxsockbuf, CTLTYPE_ULONG|CTLFLAG_RW,
1037     &sb_max, 0, sysctl_handle_sb_max, "LU", "Maximum socket buffer size");
1038 SYSCTL_ULONG(_kern_ipc, KIPC_SOCKBUF_WASTE, sockbuf_waste_factor, CTLFLAG_RW,
1039     &sb_efficiency, 0, "");
1040