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