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