xref: /openbsd-src/sys/kern/uipc_socket2.c (revision 43003dfe3ad45d1698bed8a37f2b0f5b14f20d4f)
1 /*	$OpenBSD: uipc_socket2.c,v 1.49 2009/08/10 16:49:39 thib 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 	KNOTE(&sb->sb_sel.si_note, 0);
322 }
323 
324 /*
325  * Socket buffer (struct sockbuf) utility routines.
326  *
327  * Each socket contains two socket buffers: one for sending data and
328  * one for receiving data.  Each buffer contains a queue of mbufs,
329  * information about the number of mbufs and amount of data in the
330  * queue, and other fields allowing select() statements and notification
331  * on data availability to be implemented.
332  *
333  * Data stored in a socket buffer is maintained as a list of records.
334  * Each record is a list of mbufs chained together with the m_next
335  * field.  Records are chained together with the m_nextpkt field. The upper
336  * level routine soreceive() expects the following conventions to be
337  * observed when placing information in the receive buffer:
338  *
339  * 1. If the protocol requires each message be preceded by the sender's
340  *    name, then a record containing that name must be present before
341  *    any associated data (mbuf's must be of type MT_SONAME).
342  * 2. If the protocol supports the exchange of ``access rights'' (really
343  *    just additional data associated with the message), and there are
344  *    ``rights'' to be received, then a record containing this data
345  *    should be present (mbuf's must be of type MT_CONTROL).
346  * 3. If a name or rights record exists, then it must be followed by
347  *    a data record, perhaps of zero length.
348  *
349  * Before using a new socket structure it is first necessary to reserve
350  * buffer space to the socket, by calling sbreserve().  This should commit
351  * some of the available buffer space in the system buffer pool for the
352  * socket (currently, it does nothing but enforce limits).  The space
353  * should be released by calling sbrelease() when the socket is destroyed.
354  */
355 
356 int
357 soreserve(struct socket *so, u_long sndcc, u_long rcvcc)
358 {
359 
360 	if (sbreserve(&so->so_snd, sndcc))
361 		goto bad;
362 	if (sbreserve(&so->so_rcv, rcvcc))
363 		goto bad2;
364 	if (so->so_rcv.sb_lowat == 0)
365 		so->so_rcv.sb_lowat = 1;
366 	if (so->so_snd.sb_lowat == 0)
367 		so->so_snd.sb_lowat = MCLBYTES;
368 	if (so->so_snd.sb_lowat > so->so_snd.sb_hiwat)
369 		so->so_snd.sb_lowat = so->so_snd.sb_hiwat;
370 	return (0);
371 bad2:
372 	sbrelease(&so->so_snd);
373 bad:
374 	return (ENOBUFS);
375 }
376 
377 /*
378  * Allot mbufs to a sockbuf.
379  * Attempt to scale mbmax so that mbcnt doesn't become limiting
380  * if buffering efficiency is near the normal case.
381  */
382 int
383 sbreserve(struct sockbuf *sb, u_long cc)
384 {
385 
386 	if (cc == 0 || cc > sb_max)
387 		return (1);
388 	sb->sb_hiwat = cc;
389 	sb->sb_mbmax = min(cc * 2, sb_max + (sb_max / MCLBYTES) * MSIZE);
390 	if (sb->sb_lowat > sb->sb_hiwat)
391 		sb->sb_lowat = sb->sb_hiwat;
392 	return (0);
393 }
394 
395 /*
396  * If over 50% of mbuf clusters in use, do not accept any
397  * greater than normal request.
398  */
399 int
400 sbcheckreserve(u_long cnt, u_long defcnt)
401 {
402 	if (cnt > defcnt &&
403 	    mclpools[0].pr_nout> mclpools[0].pr_hardlimit / 2)
404 		return (ENOBUFS);
405 	return (0);
406 }
407 
408 /*
409  * Free mbufs held by a socket, and reserved mbuf space.
410  */
411 void
412 sbrelease(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 #ifdef SOCKBUF_DEBUG
445 void
446 sblastrecordchk(struct sockbuf *sb, const char *where)
447 {
448 	struct mbuf *m = sb->sb_mb;
449 
450 	while (m && m->m_nextpkt)
451 		m = m->m_nextpkt;
452 
453 	if (m != sb->sb_lastrecord) {
454 		printf("sblastrecordchk: sb_mb %p sb_lastrecord %p last %p\n",
455 		    sb->sb_mb, sb->sb_lastrecord, m);
456 		printf("packet chain:\n");
457 		for (m = sb->sb_mb; m != NULL; m = m->m_nextpkt)
458 			printf("\t%p\n", m);
459 		panic("sblastrecordchk from %s", where);
460 	}
461 }
462 
463 void
464 sblastmbufchk(struct sockbuf *sb, const char *where)
465 {
466 	struct mbuf *m = sb->sb_mb;
467 	struct mbuf *n;
468 
469 	while (m && m->m_nextpkt)
470 		m = m->m_nextpkt;
471 
472 	while (m && m->m_next)
473 		m = m->m_next;
474 
475 	if (m != sb->sb_mbtail) {
476 		printf("sblastmbufchk: sb_mb %p sb_mbtail %p last %p\n",
477 		    sb->sb_mb, sb->sb_mbtail, m);
478 		printf("packet tree:\n");
479 		for (m = sb->sb_mb; m != NULL; m = m->m_nextpkt) {
480 			printf("\t");
481 			for (n = m; n != NULL; n = n->m_next)
482 				printf("%p ", n);
483 			printf("\n");
484 		}
485 		panic("sblastmbufchk from %s", where);
486 	}
487 }
488 #endif /* SOCKBUF_DEBUG */
489 
490 #define	SBLINKRECORD(sb, m0)						\
491 do {									\
492 	if ((sb)->sb_lastrecord != NULL)				\
493 		(sb)->sb_lastrecord->m_nextpkt = (m0);			\
494 	else								\
495 		(sb)->sb_mb = (m0);					\
496 	(sb)->sb_lastrecord = (m0);					\
497 } while (/*CONSTCOND*/0)
498 
499 /*
500  * Append mbuf chain m to the last record in the
501  * socket buffer sb.  The additional space associated
502  * the mbuf chain is recorded in sb.  Empty mbufs are
503  * discarded and mbufs are compacted where possible.
504  */
505 void
506 sbappend(struct sockbuf *sb, struct mbuf *m)
507 {
508 	struct mbuf *n;
509 
510 	if (m == NULL)
511 		return;
512 
513 	SBLASTRECORDCHK(sb, "sbappend 1");
514 
515 	if ((n = sb->sb_lastrecord) != NULL) {
516 		/*
517 		 * XXX Would like to simply use sb_mbtail here, but
518 		 * XXX I need to verify that I won't miss an EOR that
519 		 * XXX way.
520 		 */
521 		do {
522 			if (n->m_flags & M_EOR) {
523 				sbappendrecord(sb, m); /* XXXXXX!!!! */
524 				return;
525 			}
526 		} while (n->m_next && (n = n->m_next));
527 	} else {
528 		/*
529 		 * If this is the first record in the socket buffer, it's
530 		 * also the last record.
531 		 */
532 		sb->sb_lastrecord = m;
533 	}
534 	sbcompress(sb, m, n);
535 	SBLASTRECORDCHK(sb, "sbappend 2");
536 }
537 
538 /*
539  * This version of sbappend() should only be used when the caller
540  * absolutely knows that there will never be more than one record
541  * in the socket buffer, that is, a stream protocol (such as TCP).
542  */
543 void
544 sbappendstream(struct sockbuf *sb, struct mbuf *m)
545 {
546 
547 	KDASSERT(m->m_nextpkt == NULL);
548 	KASSERT(sb->sb_mb == sb->sb_lastrecord);
549 
550 	SBLASTMBUFCHK(sb, __func__);
551 
552 	sbcompress(sb, m, sb->sb_mbtail);
553 
554 	sb->sb_lastrecord = sb->sb_mb;
555 	SBLASTRECORDCHK(sb, __func__);
556 }
557 
558 #ifdef SOCKBUF_DEBUG
559 void
560 sbcheck(struct sockbuf *sb)
561 {
562 	struct mbuf *m;
563 	u_long len = 0, mbcnt = 0;
564 
565 	for (m = sb->sb_mb; m; m = m->m_next) {
566 		len += m->m_len;
567 		mbcnt += MSIZE;
568 		if (m->m_flags & M_EXT)
569 			mbcnt += m->m_ext.ext_size;
570 		if (m->m_nextpkt)
571 			panic("sbcheck nextpkt");
572 	}
573 	if (len != sb->sb_cc || mbcnt != sb->sb_mbcnt) {
574 		printf("cc %lu != %lu || mbcnt %lu != %lu\n", len, sb->sb_cc,
575 		    mbcnt, sb->sb_mbcnt);
576 		panic("sbcheck");
577 	}
578 }
579 #endif
580 
581 /*
582  * As above, except the mbuf chain
583  * begins a new record.
584  */
585 void
586 sbappendrecord(struct sockbuf *sb, struct mbuf *m0)
587 {
588 	struct mbuf *m;
589 
590 	if (m0 == NULL)
591 		return;
592 
593 	/*
594 	 * Put the first mbuf on the queue.
595 	 * Note this permits zero length records.
596 	 */
597 	sballoc(sb, m0);
598 	SBLASTRECORDCHK(sb, "sbappendrecord 1");
599 	SBLINKRECORD(sb, m0);
600 	m = m0->m_next;
601 	m0->m_next = NULL;
602 	if (m && (m0->m_flags & M_EOR)) {
603 		m0->m_flags &= ~M_EOR;
604 		m->m_flags |= M_EOR;
605 	}
606 	sbcompress(sb, m, m0);
607 	SBLASTRECORDCHK(sb, "sbappendrecord 2");
608 }
609 
610 /*
611  * As above except that OOB data
612  * is inserted at the beginning of the sockbuf,
613  * but after any other OOB data.
614  */
615 void
616 sbinsertoob(struct sockbuf *sb, struct mbuf *m0)
617 {
618 	struct mbuf *m, **mp;
619 
620 	if (m0 == NULL)
621 		return;
622 
623 	SBLASTRECORDCHK(sb, "sbinsertoob 1");
624 
625 	for (mp = &sb->sb_mb; (m = *mp) != NULL; mp = &((*mp)->m_nextpkt)) {
626 	    again:
627 		switch (m->m_type) {
628 
629 		case MT_OOBDATA:
630 			continue;		/* WANT next train */
631 
632 		case MT_CONTROL:
633 			if ((m = m->m_next) != NULL)
634 				goto again;	/* inspect THIS train further */
635 		}
636 		break;
637 	}
638 	/*
639 	 * Put the first mbuf on the queue.
640 	 * Note this permits zero length records.
641 	 */
642 	sballoc(sb, m0);
643 	m0->m_nextpkt = *mp;
644 	if (*mp == NULL) {
645 		/* m0 is actually the new tail */
646 		sb->sb_lastrecord = m0;
647 	}
648 	*mp = m0;
649 	m = m0->m_next;
650 	m0->m_next = NULL;
651 	if (m && (m0->m_flags & M_EOR)) {
652 		m0->m_flags &= ~M_EOR;
653 		m->m_flags |= M_EOR;
654 	}
655 	sbcompress(sb, m, m0);
656 	SBLASTRECORDCHK(sb, "sbinsertoob 2");
657 }
658 
659 /*
660  * Append address and data, and optionally, control (ancillary) data
661  * to the receive queue of a socket.  If present,
662  * m0 must include a packet header with total length.
663  * Returns 0 if no space in sockbuf or insufficient mbufs.
664  */
665 int
666 sbappendaddr(struct sockbuf *sb, struct sockaddr *asa, struct mbuf *m0,
667     struct mbuf *control)
668 {
669 	struct mbuf *m, *n, *nlast;
670 	int space = asa->sa_len;
671 
672 	if (m0 && (m0->m_flags & M_PKTHDR) == 0)
673 		panic("sbappendaddr");
674 	if (m0)
675 		space += m0->m_pkthdr.len;
676 	for (n = control; n; n = n->m_next) {
677 		space += n->m_len;
678 		if (n->m_next == NULL)	/* keep pointer to last control buf */
679 			break;
680 	}
681 	if (space > sbspace(sb))
682 		return (0);
683 	if (asa->sa_len > MLEN)
684 		return (0);
685 	MGET(m, M_DONTWAIT, MT_SONAME);
686 	if (m == NULL)
687 		return (0);
688 	m->m_len = asa->sa_len;
689 	bcopy(asa, mtod(m, caddr_t), asa->sa_len);
690 	if (n)
691 		n->m_next = m0;		/* concatenate data to control */
692 	else
693 		control = m0;
694 	m->m_next = control;
695 
696 	SBLASTRECORDCHK(sb, "sbappendaddr 1");
697 
698 	for (n = m; n->m_next != NULL; n = n->m_next)
699 		sballoc(sb, n);
700 	sballoc(sb, n);
701 	nlast = n;
702 	SBLINKRECORD(sb, m);
703 
704 	sb->sb_mbtail = nlast;
705 	SBLASTMBUFCHK(sb, "sbappendaddr");
706 
707 	SBLASTRECORDCHK(sb, "sbappendaddr 2");
708 
709 	return (1);
710 }
711 
712 int
713 sbappendcontrol(struct sockbuf *sb, struct mbuf *m0, struct mbuf *control)
714 {
715 	struct mbuf *m, *mlast, *n;
716 	int space = 0;
717 
718 	if (control == NULL)
719 		panic("sbappendcontrol");
720 	for (m = control; ; m = m->m_next) {
721 		space += m->m_len;
722 		if (m->m_next == NULL)
723 			break;
724 	}
725 	n = m;			/* save pointer to last control buffer */
726 	for (m = m0; m; m = m->m_next)
727 		space += m->m_len;
728 	if (space > sbspace(sb))
729 		return (0);
730 	n->m_next = m0;			/* concatenate data to control */
731 
732 	SBLASTRECORDCHK(sb, "sbappendcontrol 1");
733 
734 	for (m = control; m->m_next != NULL; m = m->m_next)
735 		sballoc(sb, m);
736 	sballoc(sb, m);
737 	mlast = m;
738 	SBLINKRECORD(sb, control);
739 
740 	sb->sb_mbtail = mlast;
741 	SBLASTMBUFCHK(sb, "sbappendcontrol");
742 
743 	SBLASTRECORDCHK(sb, "sbappendcontrol 2");
744 
745 	return (1);
746 }
747 
748 /*
749  * Compress mbuf chain m into the socket
750  * buffer sb following mbuf n.  If n
751  * is null, the buffer is presumed empty.
752  */
753 void
754 sbcompress(struct sockbuf *sb, struct mbuf *m, struct mbuf *n)
755 {
756 	int eor = 0;
757 	struct mbuf *o;
758 
759 	while (m) {
760 		eor |= m->m_flags & M_EOR;
761 		if (m->m_len == 0 &&
762 		    (eor == 0 ||
763 		    (((o = m->m_next) || (o = n)) &&
764 		    o->m_type == m->m_type))) {
765 			if (sb->sb_lastrecord == m)
766 				sb->sb_lastrecord = m->m_next;
767 			m = m_free(m);
768 			continue;
769 		}
770 		if (n && (n->m_flags & M_EOR) == 0 &&
771 		    /* M_TRAILINGSPACE() checks buffer writeability */
772 		    m->m_len <= MCLBYTES / 4 && /* XXX Don't copy too much */
773 		    m->m_len <= M_TRAILINGSPACE(n) &&
774 		    n->m_type == m->m_type) {
775 			bcopy(mtod(m, caddr_t), mtod(n, caddr_t) + n->m_len,
776 			    (unsigned)m->m_len);
777 			n->m_len += m->m_len;
778 			sb->sb_cc += m->m_len;
779 			if (m->m_type != MT_CONTROL && m->m_type != MT_SONAME)
780 				sb->sb_datacc += m->m_len;
781 			m = m_free(m);
782 			continue;
783 		}
784 		if (n)
785 			n->m_next = m;
786 		else
787 			sb->sb_mb = m;
788 		sb->sb_mbtail = m;
789 		sballoc(sb, m);
790 		n = m;
791 		m->m_flags &= ~M_EOR;
792 		m = m->m_next;
793 		n->m_next = NULL;
794 	}
795 	if (eor) {
796 		if (n)
797 			n->m_flags |= eor;
798 		else
799 			printf("semi-panic: sbcompress");
800 	}
801 	SBLASTMBUFCHK(sb, __func__);
802 }
803 
804 /*
805  * Free all mbufs in a sockbuf.
806  * Check that all resources are reclaimed.
807  */
808 void
809 sbflush(struct sockbuf *sb)
810 {
811 
812 	KASSERT((sb->sb_flags & SB_LOCK) == 0);
813 
814 	while (sb->sb_mbcnt)
815 		sbdrop(sb, (int)sb->sb_cc);
816 
817 	KASSERT(sb->sb_cc == 0);
818 	KASSERT(sb->sb_datacc == 0);
819 	KASSERT(sb->sb_mb == NULL);
820 	KASSERT(sb->sb_mbtail == NULL);
821 	KASSERT(sb->sb_lastrecord == NULL);
822 }
823 
824 /*
825  * Drop data from (the front of) a sockbuf.
826  */
827 void
828 sbdrop(struct sockbuf *sb, int len)
829 {
830 	struct mbuf *m, *mn;
831 	struct mbuf *next;
832 
833 	next = (m = sb->sb_mb) ? m->m_nextpkt : 0;
834 	while (len > 0) {
835 		if (m == NULL) {
836 			if (next == NULL)
837 				panic("sbdrop");
838 			m = next;
839 			next = m->m_nextpkt;
840 			continue;
841 		}
842 		if (m->m_len > len) {
843 			m->m_len -= len;
844 			m->m_data += len;
845 			sb->sb_cc -= len;
846 			if (m->m_type != MT_CONTROL && m->m_type != MT_SONAME)
847 				sb->sb_datacc -= len;
848 			break;
849 		}
850 		len -= m->m_len;
851 		sbfree(sb, m);
852 		MFREE(m, mn);
853 		m = mn;
854 	}
855 	while (m && m->m_len == 0) {
856 		sbfree(sb, m);
857 		MFREE(m, mn);
858 		m = mn;
859 	}
860 	if (m) {
861 		sb->sb_mb = m;
862 		m->m_nextpkt = next;
863 	} else
864 		sb->sb_mb = next;
865 	/*
866 	 * First part is an inline SB_EMPTY_FIXUP().  Second part
867 	 * makes sure sb_lastrecord is up-to-date if we dropped
868 	 * part of the last record.
869 	 */
870 	m = sb->sb_mb;
871 	if (m == NULL) {
872 		sb->sb_mbtail = NULL;
873 		sb->sb_lastrecord = NULL;
874 	} else if (m->m_nextpkt == NULL)
875 		sb->sb_lastrecord = m;
876 }
877 
878 /*
879  * Drop a record off the front of a sockbuf
880  * and move the next record to the front.
881  */
882 void
883 sbdroprecord(struct sockbuf *sb)
884 {
885 	struct mbuf *m, *mn;
886 
887 	m = sb->sb_mb;
888 	if (m) {
889 		sb->sb_mb = m->m_nextpkt;
890 		do {
891 			sbfree(sb, m);
892 			MFREE(m, mn);
893 		} while ((m = mn) != NULL);
894 	}
895 	SB_EMPTY_FIXUP(sb);
896 }
897 
898 /*
899  * Create a "control" mbuf containing the specified data
900  * with the specified type for presentation on a socket buffer.
901  */
902 struct mbuf *
903 sbcreatecontrol(caddr_t p, int size, int type, int level)
904 {
905 	struct cmsghdr *cp;
906 	struct mbuf *m;
907 
908 	if (CMSG_SPACE(size) > MCLBYTES) {
909 		printf("sbcreatecontrol: message too large %d\n", size);
910 		return NULL;
911 	}
912 
913 	if ((m = m_get(M_DONTWAIT, MT_CONTROL)) == NULL)
914 		return ((struct mbuf *) NULL);
915 	if (CMSG_SPACE(size) > MLEN) {
916 		MCLGET(m, M_DONTWAIT);
917 		if ((m->m_flags & M_EXT) == 0) {
918 			m_free(m);
919 			return NULL;
920 		}
921 	}
922 	cp = mtod(m, struct cmsghdr *);
923 	bcopy(p, CMSG_DATA(cp), size);
924 	m->m_len = CMSG_SPACE(size);
925 	cp->cmsg_len = CMSG_LEN(size);
926 	cp->cmsg_level = level;
927 	cp->cmsg_type = type;
928 	return (m);
929 }
930