xref: /openbsd/sys/kern/uipc_socket2.c (revision 898184e3)
1 /*	$OpenBSD: uipc_socket2.c,v 1.55 2013/01/15 11:12:57 bluhm Exp $	*/
2 /*	$NetBSD: uipc_socket2.c,v 1.11 1996/02/04 02:17:55 christos Exp $	*/
3 
4 /*
5  * Copyright (c) 1982, 1986, 1988, 1990, 1993
6  *	The Regents of the University of California.  All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. Neither the name of the University nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  *
32  *	@(#)uipc_socket2.c	8.1 (Berkeley) 6/10/93
33  */
34 
35 #include <sys/param.h>
36 #include <sys/systm.h>
37 #include <sys/proc.h>
38 #include <sys/file.h>
39 #include <sys/buf.h>
40 #include <sys/malloc.h>
41 #include <sys/mbuf.h>
42 #include <sys/protosw.h>
43 #include <sys/socket.h>
44 #include <sys/socketvar.h>
45 #include <sys/signalvar.h>
46 #include <sys/event.h>
47 #include <sys/pool.h>
48 
49 /*
50  * Primitive routines for operating on sockets and socket buffers
51  */
52 
53 u_long	sb_max = SB_MAX;		/* patchable */
54 
55 extern struct pool mclpools[];
56 extern struct pool mbpool;
57 
58 /*
59  * Procedures to manipulate state flags of socket
60  * and do appropriate wakeups.  Normal sequence from the
61  * active (originating) side is that soisconnecting() is
62  * called during processing of connect() call,
63  * resulting in an eventual call to soisconnected() if/when the
64  * connection is established.  When the connection is torn down
65  * soisdisconnecting() is called during processing of disconnect() call,
66  * and soisdisconnected() is called when the connection to the peer
67  * is totally severed.  The semantics of these routines are such that
68  * connectionless protocols can call soisconnected() and soisdisconnected()
69  * only, bypassing the in-progress calls when setting up a ``connection''
70  * takes no time.
71  *
72  * From the passive side, a socket is created with
73  * two queues of sockets: so_q0 for connections in progress
74  * and so_q for connections already made and awaiting user acceptance.
75  * As a protocol is preparing incoming connections, it creates a socket
76  * structure queued on so_q0 by calling sonewconn().  When the connection
77  * is established, soisconnected() is called, and transfers the
78  * socket structure to so_q, making it available to accept().
79  *
80  * If a socket is closed with sockets on either
81  * so_q0 or so_q, these sockets are dropped.
82  *
83  * If higher level protocols are implemented in
84  * the kernel, the wakeups done here will sometimes
85  * cause software-interrupt process scheduling.
86  */
87 
88 void
89 soisconnecting(struct socket *so)
90 {
91 
92 	so->so_state &= ~(SS_ISCONNECTED|SS_ISDISCONNECTING);
93 	so->so_state |= SS_ISCONNECTING;
94 }
95 
96 void
97 soisconnected(struct socket *so)
98 {
99 	struct socket *head = so->so_head;
100 
101 	so->so_state &= ~(SS_ISCONNECTING|SS_ISDISCONNECTING|SS_ISCONFIRMING);
102 	so->so_state |= SS_ISCONNECTED;
103 	if (head && soqremque(so, 0)) {
104 		soqinsque(head, so, 1);
105 		sorwakeup(head);
106 		wakeup_one(&head->so_timeo);
107 	} else {
108 		wakeup(&so->so_timeo);
109 		sorwakeup(so);
110 		sowwakeup(so);
111 	}
112 }
113 
114 void
115 soisdisconnecting(struct socket *so)
116 {
117 
118 	so->so_state &= ~SS_ISCONNECTING;
119 	so->so_state |= (SS_ISDISCONNECTING|SS_CANTRCVMORE|SS_CANTSENDMORE);
120 	wakeup(&so->so_timeo);
121 	sowwakeup(so);
122 	sorwakeup(so);
123 }
124 
125 void
126 soisdisconnected(struct socket *so)
127 {
128 
129 	so->so_state &= ~(SS_ISCONNECTING|SS_ISCONNECTED|SS_ISDISCONNECTING);
130 	so->so_state |= (SS_CANTRCVMORE|SS_CANTSENDMORE|SS_ISDISCONNECTED);
131 	wakeup(&so->so_timeo);
132 	sowwakeup(so);
133 	sorwakeup(so);
134 }
135 
136 /*
137  * When an attempt at a new connection is noted on a socket
138  * which accepts connections, sonewconn is called.  If the
139  * connection is possible (subject to space constraints, etc.)
140  * then we allocate a new structure, properly linked into the
141  * data structure of the original socket, and return this.
142  * Connstatus may be 0, or SS_ISCONFIRMING, or SS_ISCONNECTED.
143  *
144  * Must be called at splsoftnet()
145  */
146 struct socket *
147 sonewconn(struct socket *head, int connstatus)
148 {
149 	struct socket *so;
150 	int soqueue = connstatus ? 1 : 0;
151 
152 	splsoftassert(IPL_SOFTNET);
153 
154 	if (mclpools[0].pr_nout > mclpools[0].pr_hardlimit * 95 / 100)
155 		return ((struct socket *)0);
156 	if (head->so_qlen + head->so_q0len > head->so_qlimit * 3)
157 		return ((struct socket *)0);
158 	so = pool_get(&socket_pool, PR_NOWAIT|PR_ZERO);
159 	if (so == NULL)
160 		return ((struct socket *)0);
161 	so->so_type = head->so_type;
162 	so->so_options = head->so_options &~ SO_ACCEPTCONN;
163 	so->so_linger = head->so_linger;
164 	so->so_state = head->so_state | SS_NOFDREF;
165 	so->so_proto = head->so_proto;
166 	so->so_timeo = head->so_timeo;
167 	so->so_pgid = head->so_pgid;
168 	so->so_euid = head->so_euid;
169 	so->so_ruid = head->so_ruid;
170 	so->so_egid = head->so_egid;
171 	so->so_rgid = head->so_rgid;
172 	so->so_cpid = head->so_cpid;
173 	so->so_siguid = head->so_siguid;
174 	so->so_sigeuid = head->so_sigeuid;
175 
176 	/*
177 	 * Inherit watermarks but those may get clamped in low mem situations.
178 	 */
179 	if (soreserve(so, head->so_snd.sb_hiwat, head->so_rcv.sb_hiwat)) {
180 		pool_put(&socket_pool, so);
181 		return ((struct socket *)0);
182 	}
183 	so->so_snd.sb_wat = head->so_snd.sb_wat;
184 	so->so_snd.sb_lowat = head->so_snd.sb_lowat;
185 	so->so_snd.sb_timeo = head->so_snd.sb_timeo;
186 	so->so_rcv.sb_wat = head->so_rcv.sb_wat;
187 	so->so_rcv.sb_lowat = head->so_rcv.sb_lowat;
188 	so->so_rcv.sb_timeo = head->so_rcv.sb_timeo;
189 
190 	soqinsque(head, so, soqueue);
191 	if ((*so->so_proto->pr_usrreq)(so, PRU_ATTACH, NULL, NULL, NULL,
192 	    curproc)) {
193 		(void) soqremque(so, soqueue);
194 		pool_put(&socket_pool, so);
195 		return ((struct socket *)0);
196 	}
197 	if (connstatus) {
198 		sorwakeup(head);
199 		wakeup(&head->so_timeo);
200 		so->so_state |= connstatus;
201 	}
202 	return (so);
203 }
204 
205 void
206 soqinsque(struct socket *head, struct socket *so, int q)
207 {
208 
209 #ifdef DIAGNOSTIC
210 	if (so->so_onq != NULL)
211 		panic("soqinsque");
212 #endif
213 
214 	so->so_head = head;
215 	if (q == 0) {
216 		head->so_q0len++;
217 		so->so_onq = &head->so_q0;
218 	} else {
219 		head->so_qlen++;
220 		so->so_onq = &head->so_q;
221 	}
222 	TAILQ_INSERT_TAIL(so->so_onq, so, so_qe);
223 }
224 
225 int
226 soqremque(struct socket *so, int q)
227 {
228 	struct socket *head;
229 
230 	head = so->so_head;
231 	if (q == 0) {
232 		if (so->so_onq != &head->so_q0)
233 			return (0);
234 		head->so_q0len--;
235 	} else {
236 		if (so->so_onq != &head->so_q)
237 			return (0);
238 		head->so_qlen--;
239 	}
240 	TAILQ_REMOVE(so->so_onq, so, so_qe);
241 	so->so_onq = NULL;
242 	so->so_head = NULL;
243 	return (1);
244 }
245 
246 /*
247  * Socantsendmore indicates that no more data will be sent on the
248  * socket; it would normally be applied to a socket when the user
249  * informs the system that no more data is to be sent, by the protocol
250  * code (in case PRU_SHUTDOWN).  Socantrcvmore indicates that no more data
251  * will be received, and will normally be applied to the socket by a
252  * protocol when it detects that the peer will send no more data.
253  * Data queued for reading in the socket may yet be read.
254  */
255 
256 void
257 socantsendmore(struct socket *so)
258 {
259 
260 	so->so_state |= SS_CANTSENDMORE;
261 	sowwakeup(so);
262 }
263 
264 void
265 socantrcvmore(struct socket *so)
266 {
267 
268 	so->so_state |= SS_CANTRCVMORE;
269 	sorwakeup(so);
270 }
271 
272 /*
273  * Wait for data to arrive at/drain from a socket buffer.
274  */
275 int
276 sbwait(struct sockbuf *sb)
277 {
278 	splsoftassert(IPL_SOFTNET);
279 
280 	sb->sb_flagsintr |= SB_WAIT;
281 	return (tsleep(&sb->sb_cc,
282 	    (sb->sb_flags & SB_NOINTR) ? PSOCK : PSOCK | PCATCH, "netio",
283 	    sb->sb_timeo));
284 }
285 
286 /*
287  * Lock a sockbuf already known to be locked;
288  * return any error returned from sleep (EINTR).
289  */
290 int
291 sb_lock(struct sockbuf *sb)
292 {
293 	int error;
294 
295 	while (sb->sb_flags & SB_LOCK) {
296 		sb->sb_flags |= SB_WANT;
297 		error = tsleep(&sb->sb_flags,
298 		    (sb->sb_flags & SB_NOINTR) ?
299 		    PSOCK : PSOCK|PCATCH, "netlck", 0);
300 		if (error)
301 			return (error);
302 	}
303 	sb->sb_flags |= SB_LOCK;
304 	return (0);
305 }
306 
307 /*
308  * Wakeup processes waiting on a socket buffer.
309  * Do asynchronous notification via SIGIO
310  * if the socket has the SS_ASYNC flag set.
311  */
312 void
313 sowakeup(struct socket *so, struct sockbuf *sb)
314 {
315 	int s = splsoftnet();
316 
317 	selwakeup(&sb->sb_sel);
318 	sb->sb_flagsintr &= ~SB_SEL;
319 	if (sb->sb_flagsintr & SB_WAIT) {
320 		sb->sb_flagsintr &= ~SB_WAIT;
321 		wakeup(&sb->sb_cc);
322 	}
323 	splx(s);
324 	if (so->so_state & SS_ASYNC)
325 		csignal(so->so_pgid, SIGIO, so->so_siguid, so->so_sigeuid);
326 }
327 
328 /*
329  * Socket buffer (struct sockbuf) utility routines.
330  *
331  * Each socket contains two socket buffers: one for sending data and
332  * one for receiving data.  Each buffer contains a queue of mbufs,
333  * information about the number of mbufs and amount of data in the
334  * queue, and other fields allowing select() statements and notification
335  * on data availability to be implemented.
336  *
337  * Data stored in a socket buffer is maintained as a list of records.
338  * Each record is a list of mbufs chained together with the m_next
339  * field.  Records are chained together with the m_nextpkt field. The upper
340  * level routine soreceive() expects the following conventions to be
341  * observed when placing information in the receive buffer:
342  *
343  * 1. If the protocol requires each message be preceded by the sender's
344  *    name, then a record containing that name must be present before
345  *    any associated data (mbuf's must be of type MT_SONAME).
346  * 2. If the protocol supports the exchange of ``access rights'' (really
347  *    just additional data associated with the message), and there are
348  *    ``rights'' to be received, then a record containing this data
349  *    should be present (mbuf's must be of type MT_CONTROL).
350  * 3. If a name or rights record exists, then it must be followed by
351  *    a data record, perhaps of zero length.
352  *
353  * Before using a new socket structure it is first necessary to reserve
354  * buffer space to the socket, by calling sbreserve().  This should commit
355  * some of the available buffer space in the system buffer pool for the
356  * socket (currently, it does nothing but enforce limits).  The space
357  * should be released by calling sbrelease() when the socket is destroyed.
358  */
359 
360 int
361 soreserve(struct socket *so, u_long sndcc, u_long rcvcc)
362 {
363 
364 	if (sbreserve(&so->so_snd, sndcc))
365 		goto bad;
366 	if (sbreserve(&so->so_rcv, rcvcc))
367 		goto bad2;
368 	so->so_snd.sb_wat = sndcc;
369 	so->so_rcv.sb_wat = rcvcc;
370 	if (so->so_rcv.sb_lowat == 0)
371 		so->so_rcv.sb_lowat = 1;
372 	if (so->so_snd.sb_lowat == 0)
373 		so->so_snd.sb_lowat = MCLBYTES;
374 	if (so->so_snd.sb_lowat > so->so_snd.sb_hiwat)
375 		so->so_snd.sb_lowat = so->so_snd.sb_hiwat;
376 	return (0);
377 bad2:
378 	sbrelease(&so->so_snd);
379 bad:
380 	return (ENOBUFS);
381 }
382 
383 /*
384  * Allot mbufs to a sockbuf.
385  * Attempt to scale mbmax so that mbcnt doesn't become limiting
386  * if buffering efficiency is near the normal case.
387  */
388 int
389 sbreserve(struct sockbuf *sb, u_long cc)
390 {
391 
392 	if (cc == 0 || cc > sb_max)
393 		return (1);
394 	sb->sb_hiwat = cc;
395 	sb->sb_mbmax = min(cc * 2, sb_max + (sb_max / MCLBYTES) * MSIZE);
396 	if (sb->sb_lowat > sb->sb_hiwat)
397 		sb->sb_lowat = sb->sb_hiwat;
398 	return (0);
399 }
400 
401 /*
402  * In low memory situation, do not accept any greater than normal request.
403  */
404 int
405 sbcheckreserve(u_long cnt, u_long defcnt)
406 {
407 	if (cnt > defcnt && sbchecklowmem())
408 		return (ENOBUFS);
409 	return (0);
410 }
411 
412 int
413 sbchecklowmem(void)
414 {
415 	static int sblowmem;
416 
417 	if (mclpools[0].pr_nout < mclpools[0].pr_hardlimit * 60 / 100 ||
418 	    mbpool.pr_nout < mbpool.pr_hardlimit * 60 / 100)
419 		sblowmem = 0;
420 	if (mclpools[0].pr_nout > mclpools[0].pr_hardlimit * 80 / 100 ||
421 	    mbpool.pr_nout > mbpool.pr_hardlimit * 80 / 100)
422 		sblowmem = 1;
423 	return (sblowmem);
424 }
425 
426 /*
427  * Free mbufs held by a socket, and reserved mbuf space.
428  */
429 void
430 sbrelease(struct sockbuf *sb)
431 {
432 
433 	sbflush(sb);
434 	sb->sb_hiwat = sb->sb_mbmax = 0;
435 }
436 
437 /*
438  * Routines to add and remove
439  * data from an mbuf queue.
440  *
441  * The routines sbappend() or sbappendrecord() are normally called to
442  * append new mbufs to a socket buffer, after checking that adequate
443  * space is available, comparing the function sbspace() with the amount
444  * of data to be added.  sbappendrecord() differs from sbappend() in
445  * that data supplied is treated as the beginning of a new record.
446  * To place a sender's address, optional access rights, and data in a
447  * socket receive buffer, sbappendaddr() should be used.  To place
448  * access rights and data in a socket receive buffer, sbappendrights()
449  * should be used.  In either case, the new data begins a new record.
450  * Note that unlike sbappend() and sbappendrecord(), these routines check
451  * for the caller that there will be enough space to store the data.
452  * Each fails if there is not enough space, or if it cannot find mbufs
453  * to store additional information in.
454  *
455  * Reliable protocols may use the socket send buffer to hold data
456  * awaiting acknowledgement.  Data is normally copied from a socket
457  * send buffer in a protocol with m_copy for output to a peer,
458  * and then removing the data from the socket buffer with sbdrop()
459  * or sbdroprecord() when the data is acknowledged by the peer.
460  */
461 
462 #ifdef SOCKBUF_DEBUG
463 void
464 sblastrecordchk(struct sockbuf *sb, const char *where)
465 {
466 	struct mbuf *m = sb->sb_mb;
467 
468 	while (m && m->m_nextpkt)
469 		m = m->m_nextpkt;
470 
471 	if (m != sb->sb_lastrecord) {
472 		printf("sblastrecordchk: sb_mb %p sb_lastrecord %p last %p\n",
473 		    sb->sb_mb, sb->sb_lastrecord, m);
474 		printf("packet chain:\n");
475 		for (m = sb->sb_mb; m != NULL; m = m->m_nextpkt)
476 			printf("\t%p\n", m);
477 		panic("sblastrecordchk from %s", where);
478 	}
479 }
480 
481 void
482 sblastmbufchk(struct sockbuf *sb, const char *where)
483 {
484 	struct mbuf *m = sb->sb_mb;
485 	struct mbuf *n;
486 
487 	while (m && m->m_nextpkt)
488 		m = m->m_nextpkt;
489 
490 	while (m && m->m_next)
491 		m = m->m_next;
492 
493 	if (m != sb->sb_mbtail) {
494 		printf("sblastmbufchk: sb_mb %p sb_mbtail %p last %p\n",
495 		    sb->sb_mb, sb->sb_mbtail, m);
496 		printf("packet tree:\n");
497 		for (m = sb->sb_mb; m != NULL; m = m->m_nextpkt) {
498 			printf("\t");
499 			for (n = m; n != NULL; n = n->m_next)
500 				printf("%p ", n);
501 			printf("\n");
502 		}
503 		panic("sblastmbufchk from %s", where);
504 	}
505 }
506 #endif /* SOCKBUF_DEBUG */
507 
508 #define	SBLINKRECORD(sb, m0)						\
509 do {									\
510 	if ((sb)->sb_lastrecord != NULL)				\
511 		(sb)->sb_lastrecord->m_nextpkt = (m0);			\
512 	else								\
513 		(sb)->sb_mb = (m0);					\
514 	(sb)->sb_lastrecord = (m0);					\
515 } while (/*CONSTCOND*/0)
516 
517 /*
518  * Append mbuf chain m to the last record in the
519  * socket buffer sb.  The additional space associated
520  * the mbuf chain is recorded in sb.  Empty mbufs are
521  * discarded and mbufs are compacted where possible.
522  */
523 void
524 sbappend(struct sockbuf *sb, struct mbuf *m)
525 {
526 	struct mbuf *n;
527 
528 	if (m == NULL)
529 		return;
530 
531 	SBLASTRECORDCHK(sb, "sbappend 1");
532 
533 	if ((n = sb->sb_lastrecord) != NULL) {
534 		/*
535 		 * XXX Would like to simply use sb_mbtail here, but
536 		 * XXX I need to verify that I won't miss an EOR that
537 		 * XXX way.
538 		 */
539 		do {
540 			if (n->m_flags & M_EOR) {
541 				sbappendrecord(sb, m); /* XXXXXX!!!! */
542 				return;
543 			}
544 		} while (n->m_next && (n = n->m_next));
545 	} else {
546 		/*
547 		 * If this is the first record in the socket buffer, it's
548 		 * also the last record.
549 		 */
550 		sb->sb_lastrecord = m;
551 	}
552 	sbcompress(sb, m, n);
553 	SBLASTRECORDCHK(sb, "sbappend 2");
554 }
555 
556 /*
557  * This version of sbappend() should only be used when the caller
558  * absolutely knows that there will never be more than one record
559  * in the socket buffer, that is, a stream protocol (such as TCP).
560  */
561 void
562 sbappendstream(struct sockbuf *sb, struct mbuf *m)
563 {
564 
565 	KDASSERT(m->m_nextpkt == NULL);
566 	KASSERT(sb->sb_mb == sb->sb_lastrecord);
567 
568 	SBLASTMBUFCHK(sb, __func__);
569 
570 	sbcompress(sb, m, sb->sb_mbtail);
571 
572 	sb->sb_lastrecord = sb->sb_mb;
573 	SBLASTRECORDCHK(sb, __func__);
574 }
575 
576 #ifdef SOCKBUF_DEBUG
577 void
578 sbcheck(struct sockbuf *sb)
579 {
580 	struct mbuf *m, *n;
581 	u_long len = 0, mbcnt = 0;
582 
583 	for (m = sb->sb_mb; m; m = m->m_nextpkt) {
584 		for (n = m; n; n = n->m_next) {
585 			len += n->m_len;
586 			mbcnt += MSIZE;
587 			if (n->m_flags & M_EXT)
588 				mbcnt += n->m_ext.ext_size;
589 			if (m != n && n->m_nextpkt)
590 				panic("sbcheck nextpkt");
591 		}
592 	}
593 	if (len != sb->sb_cc || mbcnt != sb->sb_mbcnt) {
594 		printf("cc %lu != %lu || mbcnt %lu != %lu\n", len, sb->sb_cc,
595 		    mbcnt, sb->sb_mbcnt);
596 		panic("sbcheck");
597 	}
598 }
599 #endif
600 
601 /*
602  * As above, except the mbuf chain
603  * begins a new record.
604  */
605 void
606 sbappendrecord(struct sockbuf *sb, struct mbuf *m0)
607 {
608 	struct mbuf *m;
609 
610 	if (m0 == NULL)
611 		return;
612 
613 	/*
614 	 * Put the first mbuf on the queue.
615 	 * Note this permits zero length records.
616 	 */
617 	sballoc(sb, m0);
618 	SBLASTRECORDCHK(sb, "sbappendrecord 1");
619 	SBLINKRECORD(sb, m0);
620 	m = m0->m_next;
621 	m0->m_next = NULL;
622 	if (m && (m0->m_flags & M_EOR)) {
623 		m0->m_flags &= ~M_EOR;
624 		m->m_flags |= M_EOR;
625 	}
626 	sbcompress(sb, m, m0);
627 	SBLASTRECORDCHK(sb, "sbappendrecord 2");
628 }
629 
630 /*
631  * As above except that OOB data
632  * is inserted at the beginning of the sockbuf,
633  * but after any other OOB data.
634  */
635 void
636 sbinsertoob(struct sockbuf *sb, struct mbuf *m0)
637 {
638 	struct mbuf *m, **mp;
639 
640 	if (m0 == NULL)
641 		return;
642 
643 	SBLASTRECORDCHK(sb, "sbinsertoob 1");
644 
645 	for (mp = &sb->sb_mb; (m = *mp) != NULL; mp = &((*mp)->m_nextpkt)) {
646 	    again:
647 		switch (m->m_type) {
648 
649 		case MT_OOBDATA:
650 			continue;		/* WANT next train */
651 
652 		case MT_CONTROL:
653 			if ((m = m->m_next) != NULL)
654 				goto again;	/* inspect THIS train further */
655 		}
656 		break;
657 	}
658 	/*
659 	 * Put the first mbuf on the queue.
660 	 * Note this permits zero length records.
661 	 */
662 	sballoc(sb, m0);
663 	m0->m_nextpkt = *mp;
664 	if (*mp == NULL) {
665 		/* m0 is actually the new tail */
666 		sb->sb_lastrecord = m0;
667 	}
668 	*mp = m0;
669 	m = m0->m_next;
670 	m0->m_next = NULL;
671 	if (m && (m0->m_flags & M_EOR)) {
672 		m0->m_flags &= ~M_EOR;
673 		m->m_flags |= M_EOR;
674 	}
675 	sbcompress(sb, m, m0);
676 	SBLASTRECORDCHK(sb, "sbinsertoob 2");
677 }
678 
679 /*
680  * Append address and data, and optionally, control (ancillary) data
681  * to the receive queue of a socket.  If present,
682  * m0 must include a packet header with total length.
683  * Returns 0 if no space in sockbuf or insufficient mbufs.
684  */
685 int
686 sbappendaddr(struct sockbuf *sb, struct sockaddr *asa, struct mbuf *m0,
687     struct mbuf *control)
688 {
689 	struct mbuf *m, *n, *nlast;
690 	int space = asa->sa_len;
691 
692 	if (m0 && (m0->m_flags & M_PKTHDR) == 0)
693 		panic("sbappendaddr");
694 	if (m0)
695 		space += m0->m_pkthdr.len;
696 	for (n = control; n; n = n->m_next) {
697 		space += n->m_len;
698 		if (n->m_next == NULL)	/* keep pointer to last control buf */
699 			break;
700 	}
701 	if (space > sbspace(sb))
702 		return (0);
703 	if (asa->sa_len > MLEN)
704 		return (0);
705 	MGET(m, M_DONTWAIT, MT_SONAME);
706 	if (m == NULL)
707 		return (0);
708 	m->m_len = asa->sa_len;
709 	bcopy(asa, mtod(m, caddr_t), asa->sa_len);
710 	if (n)
711 		n->m_next = m0;		/* concatenate data to control */
712 	else
713 		control = m0;
714 	m->m_next = control;
715 
716 	SBLASTRECORDCHK(sb, "sbappendaddr 1");
717 
718 	for (n = m; n->m_next != NULL; n = n->m_next)
719 		sballoc(sb, n);
720 	sballoc(sb, n);
721 	nlast = n;
722 	SBLINKRECORD(sb, m);
723 
724 	sb->sb_mbtail = nlast;
725 	SBLASTMBUFCHK(sb, "sbappendaddr");
726 
727 	SBLASTRECORDCHK(sb, "sbappendaddr 2");
728 
729 	return (1);
730 }
731 
732 int
733 sbappendcontrol(struct sockbuf *sb, struct mbuf *m0, struct mbuf *control)
734 {
735 	struct mbuf *m, *mlast, *n;
736 	int space = 0;
737 
738 	if (control == NULL)
739 		panic("sbappendcontrol");
740 	for (m = control; ; m = m->m_next) {
741 		space += m->m_len;
742 		if (m->m_next == NULL)
743 			break;
744 	}
745 	n = m;			/* save pointer to last control buffer */
746 	for (m = m0; m; m = m->m_next)
747 		space += m->m_len;
748 	if (space > sbspace(sb))
749 		return (0);
750 	n->m_next = m0;			/* concatenate data to control */
751 
752 	SBLASTRECORDCHK(sb, "sbappendcontrol 1");
753 
754 	for (m = control; m->m_next != NULL; m = m->m_next)
755 		sballoc(sb, m);
756 	sballoc(sb, m);
757 	mlast = m;
758 	SBLINKRECORD(sb, control);
759 
760 	sb->sb_mbtail = mlast;
761 	SBLASTMBUFCHK(sb, "sbappendcontrol");
762 
763 	SBLASTRECORDCHK(sb, "sbappendcontrol 2");
764 
765 	return (1);
766 }
767 
768 /*
769  * Compress mbuf chain m into the socket
770  * buffer sb following mbuf n.  If n
771  * is null, the buffer is presumed empty.
772  */
773 void
774 sbcompress(struct sockbuf *sb, struct mbuf *m, struct mbuf *n)
775 {
776 	int eor = 0;
777 	struct mbuf *o;
778 
779 	while (m) {
780 		eor |= m->m_flags & M_EOR;
781 		if (m->m_len == 0 &&
782 		    (eor == 0 ||
783 		    (((o = m->m_next) || (o = n)) &&
784 		    o->m_type == m->m_type))) {
785 			if (sb->sb_lastrecord == m)
786 				sb->sb_lastrecord = m->m_next;
787 			m = m_free(m);
788 			continue;
789 		}
790 		if (n && (n->m_flags & M_EOR) == 0 &&
791 		    /* M_TRAILINGSPACE() checks buffer writeability */
792 		    m->m_len <= MCLBYTES / 4 && /* XXX Don't copy too much */
793 		    m->m_len <= M_TRAILINGSPACE(n) &&
794 		    n->m_type == m->m_type) {
795 			bcopy(mtod(m, caddr_t), mtod(n, caddr_t) + n->m_len,
796 			    m->m_len);
797 			n->m_len += m->m_len;
798 			sb->sb_cc += m->m_len;
799 			if (m->m_type != MT_CONTROL && m->m_type != MT_SONAME)
800 				sb->sb_datacc += m->m_len;
801 			m = m_free(m);
802 			continue;
803 		}
804 		if (n)
805 			n->m_next = m;
806 		else
807 			sb->sb_mb = m;
808 		sb->sb_mbtail = m;
809 		sballoc(sb, m);
810 		n = m;
811 		m->m_flags &= ~M_EOR;
812 		m = m->m_next;
813 		n->m_next = NULL;
814 	}
815 	if (eor) {
816 		if (n)
817 			n->m_flags |= eor;
818 		else
819 			printf("semi-panic: sbcompress");
820 	}
821 	SBLASTMBUFCHK(sb, __func__);
822 }
823 
824 /*
825  * Free all mbufs in a sockbuf.
826  * Check that all resources are reclaimed.
827  */
828 void
829 sbflush(struct sockbuf *sb)
830 {
831 
832 	KASSERT((sb->sb_flags & SB_LOCK) == 0);
833 
834 	while (sb->sb_mbcnt)
835 		sbdrop(sb, (int)sb->sb_cc);
836 
837 	KASSERT(sb->sb_cc == 0);
838 	KASSERT(sb->sb_datacc == 0);
839 	KASSERT(sb->sb_mb == NULL);
840 	KASSERT(sb->sb_mbtail == NULL);
841 	KASSERT(sb->sb_lastrecord == NULL);
842 }
843 
844 /*
845  * Drop data from (the front of) a sockbuf.
846  */
847 void
848 sbdrop(struct sockbuf *sb, int len)
849 {
850 	struct mbuf *m, *mn;
851 	struct mbuf *next;
852 
853 	next = (m = sb->sb_mb) ? m->m_nextpkt : 0;
854 	while (len > 0) {
855 		if (m == NULL) {
856 			if (next == NULL)
857 				panic("sbdrop");
858 			m = next;
859 			next = m->m_nextpkt;
860 			continue;
861 		}
862 		if (m->m_len > len) {
863 			m->m_len -= len;
864 			m->m_data += len;
865 			sb->sb_cc -= len;
866 			if (m->m_type != MT_CONTROL && m->m_type != MT_SONAME)
867 				sb->sb_datacc -= len;
868 			break;
869 		}
870 		len -= m->m_len;
871 		sbfree(sb, m);
872 		MFREE(m, mn);
873 		m = mn;
874 	}
875 	while (m && m->m_len == 0) {
876 		sbfree(sb, m);
877 		MFREE(m, mn);
878 		m = mn;
879 	}
880 	if (m) {
881 		sb->sb_mb = m;
882 		m->m_nextpkt = next;
883 	} else
884 		sb->sb_mb = next;
885 	/*
886 	 * First part is an inline SB_EMPTY_FIXUP().  Second part
887 	 * makes sure sb_lastrecord is up-to-date if we dropped
888 	 * part of the last record.
889 	 */
890 	m = sb->sb_mb;
891 	if (m == NULL) {
892 		sb->sb_mbtail = NULL;
893 		sb->sb_lastrecord = NULL;
894 	} else if (m->m_nextpkt == NULL)
895 		sb->sb_lastrecord = m;
896 }
897 
898 /*
899  * Drop a record off the front of a sockbuf
900  * and move the next record to the front.
901  */
902 void
903 sbdroprecord(struct sockbuf *sb)
904 {
905 	struct mbuf *m, *mn;
906 
907 	m = sb->sb_mb;
908 	if (m) {
909 		sb->sb_mb = m->m_nextpkt;
910 		do {
911 			sbfree(sb, m);
912 			MFREE(m, mn);
913 		} while ((m = mn) != NULL);
914 	}
915 	SB_EMPTY_FIXUP(sb);
916 }
917 
918 /*
919  * Create a "control" mbuf containing the specified data
920  * with the specified type for presentation on a socket buffer.
921  */
922 struct mbuf *
923 sbcreatecontrol(caddr_t p, int size, int type, int level)
924 {
925 	struct cmsghdr *cp;
926 	struct mbuf *m;
927 
928 	if (CMSG_SPACE(size) > MCLBYTES) {
929 		printf("sbcreatecontrol: message too large %d\n", size);
930 		return NULL;
931 	}
932 
933 	if ((m = m_get(M_DONTWAIT, MT_CONTROL)) == NULL)
934 		return ((struct mbuf *) NULL);
935 	if (CMSG_SPACE(size) > MLEN) {
936 		MCLGET(m, M_DONTWAIT);
937 		if ((m->m_flags & M_EXT) == 0) {
938 			m_free(m);
939 			return NULL;
940 		}
941 	}
942 	cp = mtod(m, struct cmsghdr *);
943 	bcopy(p, CMSG_DATA(cp), size);
944 	m->m_len = CMSG_SPACE(size);
945 	cp->cmsg_len = CMSG_LEN(size);
946 	cp->cmsg_level = level;
947 	cp->cmsg_type = type;
948 	return (m);
949 }
950