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