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