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