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