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