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