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