xref: /freebsd/sys/kern/uipc_sockbuf.c (revision d056fa046c6a91b90cd98165face0e42a33a5173)
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/domain.h>
40 #include <sys/event.h>
41 #include <sys/eventhandler.h>
42 #include <sys/file.h>	/* for maxfiles */
43 #include <sys/kernel.h>
44 #include <sys/lock.h>
45 #include <sys/malloc.h>
46 #include <sys/mbuf.h>
47 #include <sys/mutex.h>
48 #include <sys/proc.h>
49 #include <sys/protosw.h>
50 #include <sys/resourcevar.h>
51 #include <sys/signalvar.h>
52 #include <sys/socket.h>
53 #include <sys/socketvar.h>
54 #include <sys/stat.h>
55 #include <sys/sysctl.h>
56 #include <sys/systm.h>
57 
58 void (*aio_swake)(struct socket *, struct sockbuf *);
59 
60 /*
61  * Primitive routines for operating on sockets and socket buffers
62  */
63 
64 u_long	sb_max = SB_MAX;
65 static	u_long sb_max_adj =
66     SB_MAX * MCLBYTES / (MSIZE + MCLBYTES); /* adjusted sb_max */
67 
68 static	u_long sb_efficiency = 8;	/* parameter for sbreserve() */
69 
70 /*
71  * Procedures to manipulate state flags of socket
72  * and do appropriate wakeups.  Normal sequence from the
73  * active (originating) side is that soisconnecting() is
74  * called during processing of connect() call,
75  * resulting in an eventual call to soisconnected() if/when the
76  * connection is established.  When the connection is torn down
77  * soisdisconnecting() is called during processing of disconnect() call,
78  * and soisdisconnected() is called when the connection to the peer
79  * is totally severed.  The semantics of these routines are such that
80  * connectionless protocols can call soisconnected() and soisdisconnected()
81  * only, bypassing the in-progress calls when setting up a ``connection''
82  * takes no time.
83  *
84  * From the passive side, a socket is created with
85  * two queues of sockets: so_incomp for connections in progress
86  * and so_comp for connections already made and awaiting user acceptance.
87  * As a protocol is preparing incoming connections, it creates a socket
88  * structure queued on so_incomp by calling sonewconn().  When the connection
89  * is established, soisconnected() is called, and transfers the
90  * socket structure to so_comp, making it available to accept().
91  *
92  * If a socket is closed with sockets on either
93  * so_incomp or so_comp, these sockets are dropped.
94  *
95  * If higher level protocols are implemented in
96  * the kernel, the wakeups done here will sometimes
97  * cause software-interrupt process scheduling.
98  */
99 
100 void
101 soisconnecting(so)
102 	register struct socket *so;
103 {
104 
105 	SOCK_LOCK(so);
106 	so->so_state &= ~(SS_ISCONNECTED|SS_ISDISCONNECTING);
107 	so->so_state |= SS_ISCONNECTING;
108 	SOCK_UNLOCK(so);
109 }
110 
111 void
112 soisconnected(so)
113 	struct socket *so;
114 {
115 	struct socket *head;
116 
117 	ACCEPT_LOCK();
118 	SOCK_LOCK(so);
119 	so->so_state &= ~(SS_ISCONNECTING|SS_ISDISCONNECTING|SS_ISCONFIRMING);
120 	so->so_state |= SS_ISCONNECTED;
121 	head = so->so_head;
122 	if (head != NULL && (so->so_qstate & SQ_INCOMP)) {
123 		if ((so->so_options & SO_ACCEPTFILTER) == 0) {
124 			SOCK_UNLOCK(so);
125 			TAILQ_REMOVE(&head->so_incomp, so, so_list);
126 			head->so_incqlen--;
127 			so->so_qstate &= ~SQ_INCOMP;
128 			TAILQ_INSERT_TAIL(&head->so_comp, so, so_list);
129 			head->so_qlen++;
130 			so->so_qstate |= SQ_COMP;
131 			ACCEPT_UNLOCK();
132 			sorwakeup(head);
133 			wakeup_one(&head->so_timeo);
134 		} else {
135 			ACCEPT_UNLOCK();
136 			so->so_upcall =
137 			    head->so_accf->so_accept_filter->accf_callback;
138 			so->so_upcallarg = head->so_accf->so_accept_filter_arg;
139 			so->so_rcv.sb_flags |= SB_UPCALL;
140 			so->so_options &= ~SO_ACCEPTFILTER;
141 			SOCK_UNLOCK(so);
142 			so->so_upcall(so, so->so_upcallarg, M_DONTWAIT);
143 		}
144 		return;
145 	}
146 	SOCK_UNLOCK(so);
147 	ACCEPT_UNLOCK();
148 	wakeup(&so->so_timeo);
149 	sorwakeup(so);
150 	sowwakeup(so);
151 }
152 
153 void
154 soisdisconnecting(so)
155 	register struct socket *so;
156 {
157 
158 	/*
159 	 * XXXRW: This code assumes that SOCK_LOCK(so) and
160 	 * SOCKBUF_LOCK(&so->so_rcv) are the same.
161 	 */
162 	SOCKBUF_LOCK(&so->so_rcv);
163 	so->so_state &= ~SS_ISCONNECTING;
164 	so->so_state |= SS_ISDISCONNECTING;
165 	so->so_rcv.sb_state |= SBS_CANTRCVMORE;
166 	sorwakeup_locked(so);
167 	SOCKBUF_LOCK(&so->so_snd);
168 	so->so_snd.sb_state |= SBS_CANTSENDMORE;
169 	sowwakeup_locked(so);
170 	wakeup(&so->so_timeo);
171 }
172 
173 void
174 soisdisconnected(so)
175 	register struct socket *so;
176 {
177 
178 	/*
179 	 * XXXRW: This code assumes that SOCK_LOCK(so) and
180 	 * SOCKBUF_LOCK(&so->so_rcv) are the same.
181 	 */
182 	SOCKBUF_LOCK(&so->so_rcv);
183 	so->so_state &= ~(SS_ISCONNECTING|SS_ISCONNECTED|SS_ISDISCONNECTING);
184 	so->so_state |= SS_ISDISCONNECTED;
185 	so->so_rcv.sb_state |= SBS_CANTRCVMORE;
186 	sorwakeup_locked(so);
187 	SOCKBUF_LOCK(&so->so_snd);
188 	so->so_snd.sb_state |= SBS_CANTSENDMORE;
189 	sbdrop_locked(&so->so_snd, so->so_snd.sb_cc);
190 	sowwakeup_locked(so);
191 	wakeup(&so->so_timeo);
192 }
193 
194 /*
195  * Socantsendmore indicates that no more data will be sent on the
196  * socket; it would normally be applied to a socket when the user
197  * informs the system that no more data is to be sent, by the protocol
198  * code (in case PRU_SHUTDOWN).  Socantrcvmore indicates that no more data
199  * will be received, and will normally be applied to the socket by a
200  * protocol when it detects that the peer will send no more data.
201  * Data queued for reading in the socket may yet be read.
202  */
203 void
204 socantsendmore_locked(so)
205 	struct socket *so;
206 {
207 
208 	SOCKBUF_LOCK_ASSERT(&so->so_snd);
209 
210 	so->so_snd.sb_state |= SBS_CANTSENDMORE;
211 	sowwakeup_locked(so);
212 	mtx_assert(SOCKBUF_MTX(&so->so_snd), MA_NOTOWNED);
213 }
214 
215 void
216 socantsendmore(so)
217 	struct socket *so;
218 {
219 
220 	SOCKBUF_LOCK(&so->so_snd);
221 	socantsendmore_locked(so);
222 	mtx_assert(SOCKBUF_MTX(&so->so_snd), MA_NOTOWNED);
223 }
224 
225 void
226 socantrcvmore_locked(so)
227 	struct socket *so;
228 {
229 
230 	SOCKBUF_LOCK_ASSERT(&so->so_rcv);
231 
232 	so->so_rcv.sb_state |= SBS_CANTRCVMORE;
233 	sorwakeup_locked(so);
234 	mtx_assert(SOCKBUF_MTX(&so->so_rcv), MA_NOTOWNED);
235 }
236 
237 void
238 socantrcvmore(so)
239 	struct socket *so;
240 {
241 
242 	SOCKBUF_LOCK(&so->so_rcv);
243 	socantrcvmore_locked(so);
244 	mtx_assert(SOCKBUF_MTX(&so->so_rcv), MA_NOTOWNED);
245 }
246 
247 /*
248  * Wait for data to arrive at/drain from a socket buffer.
249  */
250 int
251 sbwait(sb)
252 	struct sockbuf *sb;
253 {
254 
255 	SOCKBUF_LOCK_ASSERT(sb);
256 
257 	sb->sb_flags |= SB_WAIT;
258 	return (msleep(&sb->sb_cc, &sb->sb_mtx,
259 	    (sb->sb_flags & SB_NOINTR) ? PSOCK : PSOCK | PCATCH, "sbwait",
260 	    sb->sb_timeo));
261 }
262 
263 /*
264  * Lock a sockbuf already known to be locked;
265  * return any error returned from sleep (EINTR).
266  */
267 int
268 sb_lock(sb)
269 	register struct sockbuf *sb;
270 {
271 	int error;
272 
273 	SOCKBUF_LOCK_ASSERT(sb);
274 
275 	while (sb->sb_flags & SB_LOCK) {
276 		sb->sb_flags |= SB_WANT;
277 		error = msleep(&sb->sb_flags, &sb->sb_mtx,
278 		    (sb->sb_flags & SB_NOINTR) ? PSOCK : PSOCK|PCATCH,
279 		    "sblock", 0);
280 		if (error)
281 			return (error);
282 	}
283 	sb->sb_flags |= SB_LOCK;
284 	return (0);
285 }
286 
287 /*
288  * Wakeup processes waiting on a socket buffer.  Do asynchronous
289  * notification via SIGIO if the socket has the SS_ASYNC flag set.
290  *
291  * Called with the socket buffer lock held; will release the lock by the end
292  * of the function.  This allows the caller to acquire the socket buffer lock
293  * while testing for the need for various sorts of wakeup and hold it through
294  * to the point where it's no longer required.  We currently hold the lock
295  * through calls out to other subsystems (with the exception of kqueue), and
296  * then release it to avoid lock order issues.  It's not clear that's
297  * correct.
298  */
299 void
300 sowakeup(so, sb)
301 	register struct socket *so;
302 	register struct sockbuf *sb;
303 {
304 
305 	SOCKBUF_LOCK_ASSERT(sb);
306 
307 	selwakeuppri(&sb->sb_sel, PSOCK);
308 	sb->sb_flags &= ~SB_SEL;
309 	if (sb->sb_flags & SB_WAIT) {
310 		sb->sb_flags &= ~SB_WAIT;
311 		wakeup(&sb->sb_cc);
312 	}
313 	KNOTE_LOCKED(&sb->sb_sel.si_note, 0);
314 	SOCKBUF_UNLOCK(sb);
315 	if ((so->so_state & SS_ASYNC) && so->so_sigio != NULL)
316 		pgsigio(&so->so_sigio, SIGIO, 0);
317 	if (sb->sb_flags & SB_UPCALL)
318 		(*so->so_upcall)(so, so->so_upcallarg, M_DONTWAIT);
319 	if (sb->sb_flags & SB_AIO)
320 		aio_swake(so, sb);
321 	mtx_assert(SOCKBUF_MTX(sb), MA_NOTOWNED);
322 }
323 
324 /*
325  * Socket buffer (struct sockbuf) utility routines.
326  *
327  * Each socket contains two socket buffers: one for sending data and
328  * one for receiving data.  Each buffer contains a queue of mbufs,
329  * information about the number of mbufs and amount of data in the
330  * queue, and other fields allowing select() statements and notification
331  * on data availability to be implemented.
332  *
333  * Data stored in a socket buffer is maintained as a list of records.
334  * Each record is a list of mbufs chained together with the m_next
335  * field.  Records are chained together with the m_nextpkt field. The upper
336  * level routine soreceive() expects the following conventions to be
337  * observed when placing information in the receive buffer:
338  *
339  * 1. If the protocol requires each message be preceded by the sender's
340  *    name, then a record containing that name must be present before
341  *    any associated data (mbuf's must be of type MT_SONAME).
342  * 2. If the protocol supports the exchange of ``access rights'' (really
343  *    just additional data associated with the message), and there are
344  *    ``rights'' to be received, then a record containing this data
345  *    should be present (mbuf's must be of type MT_RIGHTS).
346  * 3. If a name or rights record exists, then it must be followed by
347  *    a data record, perhaps of zero length.
348  *
349  * Before using a new socket structure it is first necessary to reserve
350  * buffer space to the socket, by calling sbreserve().  This should commit
351  * some of the available buffer space in the system buffer pool for the
352  * socket (currently, it does nothing but enforce limits).  The space
353  * should be released by calling sbrelease() when the socket is destroyed.
354  */
355 
356 int
357 soreserve(so, sndcc, rcvcc)
358 	register struct socket *so;
359 	u_long sndcc, rcvcc;
360 {
361 	struct thread *td = curthread;
362 
363 	SOCKBUF_LOCK(&so->so_snd);
364 	SOCKBUF_LOCK(&so->so_rcv);
365 	if (sbreserve_locked(&so->so_snd, sndcc, so, td) == 0)
366 		goto bad;
367 	if (sbreserve_locked(&so->so_rcv, rcvcc, so, td) == 0)
368 		goto bad2;
369 	if (so->so_rcv.sb_lowat == 0)
370 		so->so_rcv.sb_lowat = 1;
371 	if (so->so_snd.sb_lowat == 0)
372 		so->so_snd.sb_lowat = MCLBYTES;
373 	if (so->so_snd.sb_lowat > so->so_snd.sb_hiwat)
374 		so->so_snd.sb_lowat = so->so_snd.sb_hiwat;
375 	SOCKBUF_UNLOCK(&so->so_rcv);
376 	SOCKBUF_UNLOCK(&so->so_snd);
377 	return (0);
378 bad2:
379 	sbrelease_locked(&so->so_snd, so);
380 bad:
381 	SOCKBUF_UNLOCK(&so->so_rcv);
382 	SOCKBUF_UNLOCK(&so->so_snd);
383 	return (ENOBUFS);
384 }
385 
386 static int
387 sysctl_handle_sb_max(SYSCTL_HANDLER_ARGS)
388 {
389 	int error = 0;
390 	u_long old_sb_max = sb_max;
391 
392 	error = SYSCTL_OUT(req, arg1, sizeof(u_long));
393 	if (error || !req->newptr)
394 		return (error);
395 	error = SYSCTL_IN(req, arg1, sizeof(u_long));
396 	if (error)
397 		return (error);
398 	if (sb_max < MSIZE + MCLBYTES) {
399 		sb_max = old_sb_max;
400 		return (EINVAL);
401 	}
402 	sb_max_adj = (u_quad_t)sb_max * MCLBYTES / (MSIZE + MCLBYTES);
403 	return (0);
404 }
405 
406 /*
407  * Allot mbufs to a sockbuf.
408  * Attempt to scale mbmax so that mbcnt doesn't become limiting
409  * if buffering efficiency is near the normal case.
410  */
411 int
412 sbreserve_locked(sb, cc, so, td)
413 	struct sockbuf *sb;
414 	u_long cc;
415 	struct socket *so;
416 	struct thread *td;
417 {
418 	rlim_t sbsize_limit;
419 
420 	SOCKBUF_LOCK_ASSERT(sb);
421 
422 	/*
423 	 * td will only be NULL when we're in an interrupt
424 	 * (e.g. in tcp_input())
425 	 */
426 	if (cc > sb_max_adj)
427 		return (0);
428 	if (td != NULL) {
429 		PROC_LOCK(td->td_proc);
430 		sbsize_limit = lim_cur(td->td_proc, RLIMIT_SBSIZE);
431 		PROC_UNLOCK(td->td_proc);
432 	} else
433 		sbsize_limit = RLIM_INFINITY;
434 	if (!chgsbsize(so->so_cred->cr_uidinfo, &sb->sb_hiwat, cc,
435 	    sbsize_limit))
436 		return (0);
437 	sb->sb_mbmax = min(cc * sb_efficiency, sb_max);
438 	if (sb->sb_lowat > sb->sb_hiwat)
439 		sb->sb_lowat = sb->sb_hiwat;
440 	return (1);
441 }
442 
443 int
444 sbreserve(sb, cc, so, td)
445 	struct sockbuf *sb;
446 	u_long cc;
447 	struct socket *so;
448 	struct thread *td;
449 {
450 	int error;
451 
452 	SOCKBUF_LOCK(sb);
453 	error = sbreserve_locked(sb, cc, so, td);
454 	SOCKBUF_UNLOCK(sb);
455 	return (error);
456 }
457 
458 /*
459  * Free mbufs held by a socket, and reserved mbuf space.
460  */
461 void
462 sbrelease_locked(sb, so)
463 	struct sockbuf *sb;
464 	struct socket *so;
465 {
466 
467 	SOCKBUF_LOCK_ASSERT(sb);
468 
469 	sbflush_locked(sb);
470 	(void)chgsbsize(so->so_cred->cr_uidinfo, &sb->sb_hiwat, 0,
471 	    RLIM_INFINITY);
472 	sb->sb_mbmax = 0;
473 }
474 
475 void
476 sbrelease(sb, so)
477 	struct sockbuf *sb;
478 	struct socket *so;
479 {
480 
481 	SOCKBUF_LOCK(sb);
482 	sbrelease_locked(sb, so);
483 	SOCKBUF_UNLOCK(sb);
484 }
485 /*
486  * Routines to add and remove
487  * data from an mbuf queue.
488  *
489  * The routines sbappend() or sbappendrecord() are normally called to
490  * append new mbufs to a socket buffer, after checking that adequate
491  * space is available, comparing the function sbspace() with the amount
492  * of data to be added.  sbappendrecord() differs from sbappend() in
493  * that data supplied is treated as the beginning of a new record.
494  * To place a sender's address, optional access rights, and data in a
495  * socket receive buffer, sbappendaddr() should be used.  To place
496  * access rights and data in a socket receive buffer, sbappendrights()
497  * should be used.  In either case, the new data begins a new record.
498  * Note that unlike sbappend() and sbappendrecord(), these routines check
499  * for the caller that there will be enough space to store the data.
500  * Each fails if there is not enough space, or if it cannot find mbufs
501  * to store additional information in.
502  *
503  * Reliable protocols may use the socket send buffer to hold data
504  * awaiting acknowledgement.  Data is normally copied from a socket
505  * send buffer in a protocol with m_copy for output to a peer,
506  * and then removing the data from the socket buffer with sbdrop()
507  * or sbdroprecord() when the data is acknowledged by the peer.
508  */
509 
510 #ifdef SOCKBUF_DEBUG
511 void
512 sblastrecordchk(struct sockbuf *sb, const char *file, int line)
513 {
514 	struct mbuf *m = sb->sb_mb;
515 
516 	SOCKBUF_LOCK_ASSERT(sb);
517 
518 	while (m && m->m_nextpkt)
519 		m = m->m_nextpkt;
520 
521 	if (m != sb->sb_lastrecord) {
522 		printf("%s: sb_mb %p sb_lastrecord %p last %p\n",
523 			__func__, sb->sb_mb, sb->sb_lastrecord, m);
524 		printf("packet chain:\n");
525 		for (m = sb->sb_mb; m != NULL; m = m->m_nextpkt)
526 			printf("\t%p\n", m);
527 		panic("%s from %s:%u", __func__, file, line);
528 	}
529 }
530 
531 void
532 sblastmbufchk(struct sockbuf *sb, const char *file, int line)
533 {
534 	struct mbuf *m = sb->sb_mb;
535 	struct mbuf *n;
536 
537 	SOCKBUF_LOCK_ASSERT(sb);
538 
539 	while (m && m->m_nextpkt)
540 		m = m->m_nextpkt;
541 
542 	while (m && m->m_next)
543 		m = m->m_next;
544 
545 	if (m != sb->sb_mbtail) {
546 		printf("%s: sb_mb %p sb_mbtail %p last %p\n",
547 			__func__, sb->sb_mb, sb->sb_mbtail, m);
548 		printf("packet tree:\n");
549 		for (m = sb->sb_mb; m != NULL; m = m->m_nextpkt) {
550 			printf("\t");
551 			for (n = m; n != NULL; n = n->m_next)
552 				printf("%p ", n);
553 			printf("\n");
554 		}
555 		panic("%s from %s:%u", __func__, file, line);
556 	}
557 }
558 #endif /* SOCKBUF_DEBUG */
559 
560 #define SBLINKRECORD(sb, m0) do {					\
561 	SOCKBUF_LOCK_ASSERT(sb);					\
562 	if ((sb)->sb_lastrecord != NULL)				\
563 		(sb)->sb_lastrecord->m_nextpkt = (m0);			\
564 	else								\
565 		(sb)->sb_mb = (m0);					\
566 	(sb)->sb_lastrecord = (m0);					\
567 } while (/*CONSTCOND*/0)
568 
569 /*
570  * Append mbuf chain m to the last record in the
571  * socket buffer sb.  The additional space associated
572  * the mbuf chain is recorded in sb.  Empty mbufs are
573  * discarded and mbufs are compacted where possible.
574  */
575 void
576 sbappend_locked(sb, m)
577 	struct sockbuf *sb;
578 	struct mbuf *m;
579 {
580 	register struct mbuf *n;
581 
582 	SOCKBUF_LOCK_ASSERT(sb);
583 
584 	if (m == 0)
585 		return;
586 
587 	SBLASTRECORDCHK(sb);
588 	n = sb->sb_mb;
589 	if (n) {
590 		while (n->m_nextpkt)
591 			n = n->m_nextpkt;
592 		do {
593 			if (n->m_flags & M_EOR) {
594 				sbappendrecord_locked(sb, m); /* XXXXXX!!!! */
595 				return;
596 			}
597 		} while (n->m_next && (n = n->m_next));
598 	} else {
599 		/*
600 		 * XXX Would like to simply use sb_mbtail here, but
601 		 * XXX I need to verify that I won't miss an EOR that
602 		 * XXX way.
603 		 */
604 		if ((n = sb->sb_lastrecord) != NULL) {
605 			do {
606 				if (n->m_flags & M_EOR) {
607 					sbappendrecord_locked(sb, m); /* XXXXXX!!!! */
608 					return;
609 				}
610 			} while (n->m_next && (n = n->m_next));
611 		} else {
612 			/*
613 			 * If this is the first record in the socket buffer,
614 			 * it's also the last record.
615 			 */
616 			sb->sb_lastrecord = m;
617 		}
618 	}
619 	sbcompress(sb, m, n);
620 	SBLASTRECORDCHK(sb);
621 }
622 
623 /*
624  * Append mbuf chain m to the last record in the
625  * socket buffer sb.  The additional space associated
626  * the mbuf chain is recorded in sb.  Empty mbufs are
627  * discarded and mbufs are compacted where possible.
628  */
629 void
630 sbappend(sb, m)
631 	struct sockbuf *sb;
632 	struct mbuf *m;
633 {
634 
635 	SOCKBUF_LOCK(sb);
636 	sbappend_locked(sb, m);
637 	SOCKBUF_UNLOCK(sb);
638 }
639 
640 /*
641  * This version of sbappend() should only be used when the caller
642  * absolutely knows that there will never be more than one record
643  * in the socket buffer, that is, a stream protocol (such as TCP).
644  */
645 void
646 sbappendstream_locked(struct sockbuf *sb, struct mbuf *m)
647 {
648 	SOCKBUF_LOCK_ASSERT(sb);
649 
650 	KASSERT(m->m_nextpkt == NULL,("sbappendstream 0"));
651 	KASSERT(sb->sb_mb == sb->sb_lastrecord,("sbappendstream 1"));
652 
653 	SBLASTMBUFCHK(sb);
654 
655 	sbcompress(sb, m, sb->sb_mbtail);
656 
657 	sb->sb_lastrecord = sb->sb_mb;
658 	SBLASTRECORDCHK(sb);
659 }
660 
661 /*
662  * This version of sbappend() should only be used when the caller
663  * absolutely knows that there will never be more than one record
664  * in the socket buffer, that is, a stream protocol (such as TCP).
665  */
666 void
667 sbappendstream(struct sockbuf *sb, struct mbuf *m)
668 {
669 
670 	SOCKBUF_LOCK(sb);
671 	sbappendstream_locked(sb, m);
672 	SOCKBUF_UNLOCK(sb);
673 }
674 
675 #ifdef SOCKBUF_DEBUG
676 void
677 sbcheck(sb)
678 	struct sockbuf *sb;
679 {
680 	struct mbuf *m;
681 	struct mbuf *n = 0;
682 	u_long len = 0, mbcnt = 0;
683 
684 	SOCKBUF_LOCK_ASSERT(sb);
685 
686 	for (m = sb->sb_mb; m; m = n) {
687 	    n = m->m_nextpkt;
688 	    for (; m; m = m->m_next) {
689 		len += m->m_len;
690 		mbcnt += MSIZE;
691 		if (m->m_flags & M_EXT) /*XXX*/ /* pretty sure this is bogus */
692 			mbcnt += m->m_ext.ext_size;
693 	    }
694 	}
695 	if (len != sb->sb_cc || mbcnt != sb->sb_mbcnt) {
696 		printf("cc %ld != %u || mbcnt %ld != %u\n", len, sb->sb_cc,
697 		    mbcnt, sb->sb_mbcnt);
698 		panic("sbcheck");
699 	}
700 }
701 #endif
702 
703 /*
704  * As above, except the mbuf chain
705  * begins a new record.
706  */
707 void
708 sbappendrecord_locked(sb, m0)
709 	register struct sockbuf *sb;
710 	register struct mbuf *m0;
711 {
712 	register struct mbuf *m;
713 
714 	SOCKBUF_LOCK_ASSERT(sb);
715 
716 	if (m0 == 0)
717 		return;
718 	m = sb->sb_mb;
719 	if (m)
720 		while (m->m_nextpkt)
721 			m = m->m_nextpkt;
722 	/*
723 	 * Put the first mbuf on the queue.
724 	 * Note this permits zero length records.
725 	 */
726 	sballoc(sb, m0);
727 	SBLASTRECORDCHK(sb);
728 	SBLINKRECORD(sb, m0);
729 	if (m)
730 		m->m_nextpkt = m0;
731 	else
732 		sb->sb_mb = m0;
733 	m = m0->m_next;
734 	m0->m_next = 0;
735 	if (m && (m0->m_flags & M_EOR)) {
736 		m0->m_flags &= ~M_EOR;
737 		m->m_flags |= M_EOR;
738 	}
739 	sbcompress(sb, m, m0);
740 }
741 
742 /*
743  * As above, except the mbuf chain
744  * begins a new record.
745  */
746 void
747 sbappendrecord(sb, m0)
748 	register struct sockbuf *sb;
749 	register struct mbuf *m0;
750 {
751 
752 	SOCKBUF_LOCK(sb);
753 	sbappendrecord_locked(sb, m0);
754 	SOCKBUF_UNLOCK(sb);
755 }
756 
757 /*
758  * Append address and data, and optionally, control (ancillary) data
759  * to the receive queue of a socket.  If present,
760  * m0 must include a packet header with total length.
761  * Returns 0 if no space in sockbuf or insufficient mbufs.
762  */
763 int
764 sbappendaddr_locked(sb, asa, m0, control)
765 	struct sockbuf *sb;
766 	const struct sockaddr *asa;
767 	struct mbuf *m0, *control;
768 {
769 	struct mbuf *m, *n, *nlast;
770 	int space = asa->sa_len;
771 
772 	SOCKBUF_LOCK_ASSERT(sb);
773 
774 	if (m0 && (m0->m_flags & M_PKTHDR) == 0)
775 		panic("sbappendaddr_locked");
776 	if (m0)
777 		space += m0->m_pkthdr.len;
778 	space += m_length(control, &n);
779 
780 	if (space > sbspace(sb))
781 		return (0);
782 #if MSIZE <= 256
783 	if (asa->sa_len > MLEN)
784 		return (0);
785 #endif
786 	MGET(m, M_DONTWAIT, MT_SONAME);
787 	if (m == 0)
788 		return (0);
789 	m->m_len = asa->sa_len;
790 	bcopy(asa, mtod(m, caddr_t), asa->sa_len);
791 	if (n)
792 		n->m_next = m0;		/* concatenate data to control */
793 	else
794 		control = m0;
795 	m->m_next = control;
796 	for (n = m; n->m_next != NULL; n = n->m_next)
797 		sballoc(sb, n);
798 	sballoc(sb, n);
799 	nlast = n;
800 	SBLINKRECORD(sb, m);
801 
802 	sb->sb_mbtail = nlast;
803 	SBLASTMBUFCHK(sb);
804 
805 	SBLASTRECORDCHK(sb);
806 	return (1);
807 }
808 
809 /*
810  * Append address and data, and optionally, control (ancillary) data
811  * to the receive queue of a socket.  If present,
812  * m0 must include a packet header with total length.
813  * Returns 0 if no space in sockbuf or insufficient mbufs.
814  */
815 int
816 sbappendaddr(sb, asa, m0, control)
817 	struct sockbuf *sb;
818 	const struct sockaddr *asa;
819 	struct mbuf *m0, *control;
820 {
821 	int retval;
822 
823 	SOCKBUF_LOCK(sb);
824 	retval = sbappendaddr_locked(sb, asa, m0, control);
825 	SOCKBUF_UNLOCK(sb);
826 	return (retval);
827 }
828 
829 int
830 sbappendcontrol_locked(sb, m0, control)
831 	struct sockbuf *sb;
832 	struct mbuf *control, *m0;
833 {
834 	struct mbuf *m, *n, *mlast;
835 	int space;
836 
837 	SOCKBUF_LOCK_ASSERT(sb);
838 
839 	if (control == 0)
840 		panic("sbappendcontrol_locked");
841 	space = m_length(control, &n) + m_length(m0, NULL);
842 
843 	if (space > sbspace(sb))
844 		return (0);
845 	n->m_next = m0;			/* concatenate data to control */
846 
847 	SBLASTRECORDCHK(sb);
848 
849 	for (m = control; m->m_next; m = m->m_next)
850 		sballoc(sb, m);
851 	sballoc(sb, m);
852 	mlast = m;
853 	SBLINKRECORD(sb, control);
854 
855 	sb->sb_mbtail = mlast;
856 	SBLASTMBUFCHK(sb);
857 
858 	SBLASTRECORDCHK(sb);
859 	return (1);
860 }
861 
862 int
863 sbappendcontrol(sb, m0, control)
864 	struct sockbuf *sb;
865 	struct mbuf *control, *m0;
866 {
867 	int retval;
868 
869 	SOCKBUF_LOCK(sb);
870 	retval = sbappendcontrol_locked(sb, m0, control);
871 	SOCKBUF_UNLOCK(sb);
872 	return (retval);
873 }
874 
875 /*
876  * Append the data in mbuf chain (m) into the socket buffer sb following mbuf
877  * (n).  If (n) is NULL, the buffer is presumed empty.
878  *
879  * When the data is compressed, mbufs in the chain may be handled in one of
880  * three ways:
881  *
882  * (1) The mbuf may simply be dropped, if it contributes nothing (no data, no
883  *     record boundary, and no change in data type).
884  *
885  * (2) The mbuf may be coalesced -- i.e., data in the mbuf may be copied into
886  *     an mbuf already in the socket buffer.  This can occur if an
887  *     appropriate mbuf exists, there is room, and no merging of data types
888  *     will occur.
889  *
890  * (3) The mbuf may be appended to the end of the existing mbuf chain.
891  *
892  * If any of the new mbufs is marked as M_EOR, mark the last mbuf appended as
893  * end-of-record.
894  */
895 void
896 sbcompress(sb, m, n)
897 	register struct sockbuf *sb;
898 	register struct mbuf *m, *n;
899 {
900 	register int eor = 0;
901 	register struct mbuf *o;
902 
903 	SOCKBUF_LOCK_ASSERT(sb);
904 
905 	while (m) {
906 		eor |= m->m_flags & M_EOR;
907 		if (m->m_len == 0 &&
908 		    (eor == 0 ||
909 		     (((o = m->m_next) || (o = n)) &&
910 		      o->m_type == m->m_type))) {
911 			if (sb->sb_lastrecord == m)
912 				sb->sb_lastrecord = m->m_next;
913 			m = m_free(m);
914 			continue;
915 		}
916 		if (n && (n->m_flags & M_EOR) == 0 &&
917 		    M_WRITABLE(n) &&
918 		    m->m_len <= MCLBYTES / 4 && /* XXX: Don't copy too much */
919 		    m->m_len <= M_TRAILINGSPACE(n) &&
920 		    n->m_type == m->m_type) {
921 			bcopy(mtod(m, caddr_t), mtod(n, caddr_t) + n->m_len,
922 			    (unsigned)m->m_len);
923 			n->m_len += m->m_len;
924 			sb->sb_cc += m->m_len;
925 			if (m->m_type != MT_DATA && m->m_type != MT_OOBDATA)
926 				/* XXX: Probably don't need.*/
927 				sb->sb_ctl += m->m_len;
928 			m = m_free(m);
929 			continue;
930 		}
931 		if (n)
932 			n->m_next = m;
933 		else
934 			sb->sb_mb = m;
935 		sb->sb_mbtail = m;
936 		sballoc(sb, m);
937 		n = m;
938 		m->m_flags &= ~M_EOR;
939 		m = m->m_next;
940 		n->m_next = 0;
941 	}
942 	if (eor) {
943 		KASSERT(n != NULL, ("sbcompress: eor && n == NULL"));
944 		n->m_flags |= eor;
945 	}
946 	SBLASTMBUFCHK(sb);
947 }
948 
949 /*
950  * Free all mbufs in a sockbuf.
951  * Check that all resources are reclaimed.
952  */
953 void
954 sbflush_locked(sb)
955 	register struct sockbuf *sb;
956 {
957 
958 	SOCKBUF_LOCK_ASSERT(sb);
959 
960 	if (sb->sb_flags & SB_LOCK)
961 		panic("sbflush_locked: locked");
962 	while (sb->sb_mbcnt) {
963 		/*
964 		 * Don't call sbdrop(sb, 0) if the leading mbuf is non-empty:
965 		 * we would loop forever. Panic instead.
966 		 */
967 		if (!sb->sb_cc && (sb->sb_mb == NULL || sb->sb_mb->m_len))
968 			break;
969 		sbdrop_locked(sb, (int)sb->sb_cc);
970 	}
971 	if (sb->sb_cc || sb->sb_mb || sb->sb_mbcnt)
972 		panic("sbflush_locked: cc %u || mb %p || mbcnt %u", sb->sb_cc, (void *)sb->sb_mb, sb->sb_mbcnt);
973 }
974 
975 void
976 sbflush(sb)
977 	register struct sockbuf *sb;
978 {
979 
980 	SOCKBUF_LOCK(sb);
981 	sbflush_locked(sb);
982 	SOCKBUF_UNLOCK(sb);
983 }
984 
985 /*
986  * Drop data from (the front of) a sockbuf.
987  */
988 void
989 sbdrop_locked(sb, len)
990 	register struct sockbuf *sb;
991 	register int len;
992 {
993 	register struct mbuf *m;
994 	struct mbuf *next;
995 
996 	SOCKBUF_LOCK_ASSERT(sb);
997 
998 	next = (m = sb->sb_mb) ? m->m_nextpkt : 0;
999 	while (len > 0) {
1000 		if (m == 0) {
1001 			if (next == 0)
1002 				panic("sbdrop");
1003 			m = next;
1004 			next = m->m_nextpkt;
1005 			continue;
1006 		}
1007 		if (m->m_len > len) {
1008 			m->m_len -= len;
1009 			m->m_data += len;
1010 			sb->sb_cc -= len;
1011 			if (m->m_type != MT_DATA && m->m_type != MT_OOBDATA)
1012 				sb->sb_ctl -= len;
1013 			break;
1014 		}
1015 		len -= m->m_len;
1016 		sbfree(sb, m);
1017 		m = m_free(m);
1018 	}
1019 	while (m && m->m_len == 0) {
1020 		sbfree(sb, m);
1021 		m = m_free(m);
1022 	}
1023 	if (m) {
1024 		sb->sb_mb = m;
1025 		m->m_nextpkt = next;
1026 	} else
1027 		sb->sb_mb = next;
1028 	/*
1029 	 * First part is an inline SB_EMPTY_FIXUP().  Second part
1030 	 * makes sure sb_lastrecord is up-to-date if we dropped
1031 	 * part of the last record.
1032 	 */
1033 	m = sb->sb_mb;
1034 	if (m == NULL) {
1035 		sb->sb_mbtail = NULL;
1036 		sb->sb_lastrecord = NULL;
1037 	} else if (m->m_nextpkt == NULL) {
1038 		sb->sb_lastrecord = m;
1039 	}
1040 }
1041 
1042 /*
1043  * Drop data from (the front of) a sockbuf.
1044  */
1045 void
1046 sbdrop(sb, len)
1047 	register struct sockbuf *sb;
1048 	register int len;
1049 {
1050 
1051 	SOCKBUF_LOCK(sb);
1052 	sbdrop_locked(sb, len);
1053 	SOCKBUF_UNLOCK(sb);
1054 }
1055 
1056 /*
1057  * Drop a record off the front of a sockbuf
1058  * and move the next record to the front.
1059  */
1060 void
1061 sbdroprecord_locked(sb)
1062 	register struct sockbuf *sb;
1063 {
1064 	register struct mbuf *m;
1065 
1066 	SOCKBUF_LOCK_ASSERT(sb);
1067 
1068 	m = sb->sb_mb;
1069 	if (m) {
1070 		sb->sb_mb = m->m_nextpkt;
1071 		do {
1072 			sbfree(sb, m);
1073 			m = m_free(m);
1074 		} while (m);
1075 	}
1076 	SB_EMPTY_FIXUP(sb);
1077 }
1078 
1079 /*
1080  * Drop a record off the front of a sockbuf
1081  * and move the next record to the front.
1082  */
1083 void
1084 sbdroprecord(sb)
1085 	register struct sockbuf *sb;
1086 {
1087 
1088 	SOCKBUF_LOCK(sb);
1089 	sbdroprecord_locked(sb);
1090 	SOCKBUF_UNLOCK(sb);
1091 }
1092 
1093 /*
1094  * Create a "control" mbuf containing the specified data
1095  * with the specified type for presentation on a socket buffer.
1096  */
1097 struct mbuf *
1098 sbcreatecontrol(p, size, type, level)
1099 	caddr_t p;
1100 	register int size;
1101 	int type, level;
1102 {
1103 	register struct cmsghdr *cp;
1104 	struct mbuf *m;
1105 
1106 	if (CMSG_SPACE((u_int)size) > MCLBYTES)
1107 		return ((struct mbuf *) NULL);
1108 	if (CMSG_SPACE((u_int)size) > MLEN)
1109 		m = m_getcl(M_DONTWAIT, MT_CONTROL, 0);
1110 	else
1111 		m = m_get(M_DONTWAIT, MT_CONTROL);
1112 	if (m == NULL)
1113 		return ((struct mbuf *) NULL);
1114 	cp = mtod(m, struct cmsghdr *);
1115 	m->m_len = 0;
1116 	KASSERT(CMSG_SPACE((u_int)size) <= M_TRAILINGSPACE(m),
1117 	    ("sbcreatecontrol: short mbuf"));
1118 	if (p != NULL)
1119 		(void)memcpy(CMSG_DATA(cp), p, size);
1120 	m->m_len = CMSG_SPACE(size);
1121 	cp->cmsg_len = CMSG_LEN(size);
1122 	cp->cmsg_level = level;
1123 	cp->cmsg_type = type;
1124 	return (m);
1125 }
1126 
1127 /*
1128  * Some routines that return EOPNOTSUPP for entry points that are not
1129  * supported by a protocol.  Fill in as needed.
1130  */
1131 int
1132 pru_accept_notsupp(struct socket *so, struct sockaddr **nam)
1133 {
1134 	return EOPNOTSUPP;
1135 }
1136 
1137 int
1138 pru_attach_notsupp(struct socket *so, int proto, struct thread *td)
1139 {
1140 	return EOPNOTSUPP;
1141 }
1142 
1143 int
1144 pru_bind_notsupp(struct socket *so, struct sockaddr *nam, struct thread *td)
1145 {
1146 	return EOPNOTSUPP;
1147 }
1148 
1149 int
1150 pru_connect_notsupp(struct socket *so, struct sockaddr *nam, struct thread *td)
1151 {
1152 	return EOPNOTSUPP;
1153 }
1154 
1155 int
1156 pru_connect2_notsupp(struct socket *so1, struct socket *so2)
1157 {
1158 	return EOPNOTSUPP;
1159 }
1160 
1161 int
1162 pru_control_notsupp(struct socket *so, u_long cmd, caddr_t data,
1163 	struct ifnet *ifp, struct thread *td)
1164 {
1165 	return EOPNOTSUPP;
1166 }
1167 
1168 int
1169 pru_disconnect_notsupp(struct socket *so)
1170 {
1171 	return EOPNOTSUPP;
1172 }
1173 
1174 int
1175 pru_listen_notsupp(struct socket *so, int backlog, struct thread *td)
1176 {
1177 	return EOPNOTSUPP;
1178 }
1179 
1180 int
1181 pru_peeraddr_notsupp(struct socket *so, struct sockaddr **nam)
1182 {
1183 	return EOPNOTSUPP;
1184 }
1185 
1186 int
1187 pru_rcvd_notsupp(struct socket *so, int flags)
1188 {
1189 	return EOPNOTSUPP;
1190 }
1191 
1192 int
1193 pru_rcvoob_notsupp(struct socket *so, struct mbuf *m, int flags)
1194 {
1195 	return EOPNOTSUPP;
1196 }
1197 
1198 int
1199 pru_send_notsupp(struct socket *so, int flags, struct mbuf *m,
1200 	struct sockaddr *addr, struct mbuf *control, struct thread *td)
1201 {
1202 	return EOPNOTSUPP;
1203 }
1204 
1205 /*
1206  * This isn't really a ``null'' operation, but it's the default one
1207  * and doesn't do anything destructive.
1208  */
1209 int
1210 pru_sense_null(struct socket *so, struct stat *sb)
1211 {
1212 	sb->st_blksize = so->so_snd.sb_hiwat;
1213 	return 0;
1214 }
1215 
1216 int
1217 pru_shutdown_notsupp(struct socket *so)
1218 {
1219 	return EOPNOTSUPP;
1220 }
1221 
1222 int
1223 pru_sockaddr_notsupp(struct socket *so, struct sockaddr **nam)
1224 {
1225 	return EOPNOTSUPP;
1226 }
1227 
1228 int
1229 pru_sosend_notsupp(struct socket *so, struct sockaddr *addr, struct uio *uio,
1230 	struct mbuf *top, struct mbuf *control, int flags, struct thread *td)
1231 {
1232 	return EOPNOTSUPP;
1233 }
1234 
1235 int
1236 pru_soreceive_notsupp(struct socket *so, struct sockaddr **paddr,
1237 	struct uio *uio, struct mbuf **mp0, struct mbuf **controlp,
1238 	int *flagsp)
1239 {
1240 	return EOPNOTSUPP;
1241 }
1242 
1243 int
1244 pru_sopoll_notsupp(struct socket *so, int events, struct ucred *cred,
1245 	struct thread *td)
1246 {
1247 	return EOPNOTSUPP;
1248 }
1249 
1250 /*
1251  * Make a copy of a sockaddr in a malloced buffer of type M_SONAME.
1252  */
1253 struct sockaddr *
1254 sodupsockaddr(const struct sockaddr *sa, int mflags)
1255 {
1256 	struct sockaddr *sa2;
1257 
1258 	sa2 = malloc(sa->sa_len, M_SONAME, mflags);
1259 	if (sa2)
1260 		bcopy(sa, sa2, sa->sa_len);
1261 	return sa2;
1262 }
1263 
1264 /*
1265  * Create an external-format (``xsocket'') structure using the information
1266  * in the kernel-format socket structure pointed to by so.  This is done
1267  * to reduce the spew of irrelevant information over this interface,
1268  * to isolate user code from changes in the kernel structure, and
1269  * potentially to provide information-hiding if we decide that
1270  * some of this information should be hidden from users.
1271  */
1272 void
1273 sotoxsocket(struct socket *so, struct xsocket *xso)
1274 {
1275 	xso->xso_len = sizeof *xso;
1276 	xso->xso_so = so;
1277 	xso->so_type = so->so_type;
1278 	xso->so_options = so->so_options;
1279 	xso->so_linger = so->so_linger;
1280 	xso->so_state = so->so_state;
1281 	xso->so_pcb = so->so_pcb;
1282 	xso->xso_protocol = so->so_proto->pr_protocol;
1283 	xso->xso_family = so->so_proto->pr_domain->dom_family;
1284 	xso->so_qlen = so->so_qlen;
1285 	xso->so_incqlen = so->so_incqlen;
1286 	xso->so_qlimit = so->so_qlimit;
1287 	xso->so_timeo = so->so_timeo;
1288 	xso->so_error = so->so_error;
1289 	xso->so_pgid = so->so_sigio ? so->so_sigio->sio_pgid : 0;
1290 	xso->so_oobmark = so->so_oobmark;
1291 	sbtoxsockbuf(&so->so_snd, &xso->so_snd);
1292 	sbtoxsockbuf(&so->so_rcv, &xso->so_rcv);
1293 	xso->so_uid = so->so_cred->cr_uid;
1294 }
1295 
1296 /*
1297  * This does the same for sockbufs.  Note that the xsockbuf structure,
1298  * since it is always embedded in a socket, does not include a self
1299  * pointer nor a length.  We make this entry point public in case
1300  * some other mechanism needs it.
1301  */
1302 void
1303 sbtoxsockbuf(struct sockbuf *sb, struct xsockbuf *xsb)
1304 {
1305 	xsb->sb_cc = sb->sb_cc;
1306 	xsb->sb_hiwat = sb->sb_hiwat;
1307 	xsb->sb_mbcnt = sb->sb_mbcnt;
1308 	xsb->sb_mbmax = sb->sb_mbmax;
1309 	xsb->sb_lowat = sb->sb_lowat;
1310 	xsb->sb_flags = sb->sb_flags;
1311 	xsb->sb_timeo = sb->sb_timeo;
1312 }
1313 
1314 /* This takes the place of kern.maxsockbuf, which moved to kern.ipc. */
1315 static int dummy;
1316 SYSCTL_INT(_kern, KERN_DUMMY, dummy, CTLFLAG_RW, &dummy, 0, "");
1317 SYSCTL_OID(_kern_ipc, KIPC_MAXSOCKBUF, maxsockbuf, CTLTYPE_ULONG|CTLFLAG_RW,
1318     &sb_max, 0, sysctl_handle_sb_max, "LU", "Maximum socket buffer size");
1319 SYSCTL_ULONG(_kern_ipc, KIPC_SOCKBUF_WASTE, sockbuf_waste_factor, CTLFLAG_RW,
1320     &sb_efficiency, 0, "");
1321