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