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