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