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