xref: /openbsd-src/sys/kern/uipc_socket2.c (revision 25c4e8bd056e974b28f4a0ffd39d76c190a56013)
1 /*	$OpenBSD: uipc_socket2.c,v 1.125 2022/07/01 09:56:17 mvs 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/malloc.h>
38 #include <sys/mbuf.h>
39 #include <sys/protosw.h>
40 #include <sys/domain.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 	soassertlocked(so);
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 	soassertlocked(so);
100 	so->so_state &= ~(SS_ISCONNECTING|SS_ISDISCONNECTING);
101 	so->so_state |= SS_ISCONNECTED;
102 
103 	if (head != NULL && so->so_onq == &head->so_q0) {
104 		int persocket = solock_persocket(so);
105 
106 		if (persocket) {
107 			soref(so);
108 			soref(head);
109 
110 			sounlock(so);
111 			solock(head);
112 			solock(so);
113 
114 			if (so->so_onq != &head->so_q0) {
115 				sounlock(head);
116 				sorele(head);
117 				sorele(so);
118 
119 				return;
120 			}
121 
122 			sorele(head);
123 			sorele(so);
124 		}
125 
126 		soqremque(so, 0);
127 		soqinsque(head, so, 1);
128 		sorwakeup(head);
129 		wakeup_one(&head->so_timeo);
130 
131 		if (persocket)
132 			sounlock(head);
133 	} else {
134 		wakeup(&so->so_timeo);
135 		sorwakeup(so);
136 		sowwakeup(so);
137 	}
138 }
139 
140 void
141 soisdisconnecting(struct socket *so)
142 {
143 	soassertlocked(so);
144 	so->so_state &= ~SS_ISCONNECTING;
145 	so->so_state |= (SS_ISDISCONNECTING|SS_CANTRCVMORE|SS_CANTSENDMORE);
146 	wakeup(&so->so_timeo);
147 	sowwakeup(so);
148 	sorwakeup(so);
149 }
150 
151 void
152 soisdisconnected(struct socket *so)
153 {
154 	soassertlocked(so);
155 	so->so_state &= ~(SS_ISCONNECTING|SS_ISCONNECTED|SS_ISDISCONNECTING);
156 	so->so_state |= (SS_CANTRCVMORE|SS_CANTSENDMORE|SS_ISDISCONNECTED);
157 	wakeup(&so->so_timeo);
158 	sowwakeup(so);
159 	sorwakeup(so);
160 }
161 
162 /*
163  * When an attempt at a new connection is noted on a socket
164  * which accepts connections, sonewconn is called.  If the
165  * connection is possible (subject to space constraints, etc.)
166  * then we allocate a new structure, properly linked into the
167  * data structure of the original socket, and return this.
168  * Connstatus may be 0 or SS_ISCONNECTED.
169  */
170 struct socket *
171 sonewconn(struct socket *head, int connstatus)
172 {
173 	struct socket *so;
174 	int persocket = solock_persocket(head);
175 	int error;
176 
177 	/*
178 	 * XXXSMP as long as `so' and `head' share the same lock, we
179 	 * can call soreserve() and pr_attach() below w/o explicitly
180 	 * locking `so'.
181 	 */
182 	soassertlocked(head);
183 
184 	if (m_pool_used() > 95)
185 		return (NULL);
186 	if (head->so_qlen + head->so_q0len > head->so_qlimit * 3)
187 		return (NULL);
188 	so = soalloc(PR_NOWAIT | PR_ZERO);
189 	if (so == NULL)
190 		return (NULL);
191 	so->so_type = head->so_type;
192 	so->so_options = head->so_options &~ SO_ACCEPTCONN;
193 	so->so_linger = head->so_linger;
194 	so->so_state = head->so_state | SS_NOFDREF;
195 	so->so_proto = head->so_proto;
196 	so->so_timeo = head->so_timeo;
197 	so->so_euid = head->so_euid;
198 	so->so_ruid = head->so_ruid;
199 	so->so_egid = head->so_egid;
200 	so->so_rgid = head->so_rgid;
201 	so->so_cpid = head->so_cpid;
202 
203 	/*
204 	 * Lock order will be `head' -> `so' while these sockets are linked.
205 	 */
206 	if (persocket)
207 		solock(so);
208 
209 	/*
210 	 * Inherit watermarks but those may get clamped in low mem situations.
211 	 */
212 	if (soreserve(so, head->so_snd.sb_hiwat, head->so_rcv.sb_hiwat)) {
213 		if (persocket)
214 			sounlock(so);
215 		pool_put(&socket_pool, so);
216 		return (NULL);
217 	}
218 	so->so_snd.sb_wat = head->so_snd.sb_wat;
219 	so->so_snd.sb_lowat = head->so_snd.sb_lowat;
220 	so->so_snd.sb_timeo_nsecs = head->so_snd.sb_timeo_nsecs;
221 	so->so_rcv.sb_wat = head->so_rcv.sb_wat;
222 	so->so_rcv.sb_lowat = head->so_rcv.sb_lowat;
223 	so->so_rcv.sb_timeo_nsecs = head->so_rcv.sb_timeo_nsecs;
224 
225 	klist_init(&so->so_rcv.sb_sel.si_note, &socket_klistops, so);
226 	klist_init(&so->so_snd.sb_sel.si_note, &socket_klistops, so);
227 	sigio_init(&so->so_sigio);
228 	sigio_copy(&so->so_sigio, &head->so_sigio);
229 
230 	soqinsque(head, so, 0);
231 
232 	/*
233 	 * We need to unlock `head' because PCB layer could release
234 	 * solock() to enforce desired lock order.
235 	 */
236 	if (persocket) {
237 		head->so_newconn++;
238 		sounlock(head);
239 	}
240 
241 	error = (*so->so_proto->pr_attach)(so, 0);
242 
243 	if (persocket) {
244 		sounlock(so);
245 		solock(head);
246 		solock(so);
247 
248 		if ((head->so_newconn--) == 0) {
249 			if ((head->so_state & SS_NEWCONN_WAIT) != 0) {
250 				head->so_state &= ~SS_NEWCONN_WAIT;
251 				wakeup(&head->so_newconn);
252 			}
253 		}
254 	}
255 
256 	if (error) {
257 		soqremque(so, 0);
258 		if (persocket)
259 			sounlock(so);
260 		sigio_free(&so->so_sigio);
261 		klist_free(&so->so_rcv.sb_sel.si_note);
262 		klist_free(&so->so_snd.sb_sel.si_note);
263 		pool_put(&socket_pool, so);
264 		return (NULL);
265 	}
266 
267 	if (connstatus) {
268 		so->so_state |= connstatus;
269 		soqremque(so, 0);
270 		soqinsque(head, so, 1);
271 		sorwakeup(head);
272 		wakeup(&head->so_timeo);
273 	}
274 
275 	if (persocket)
276 		sounlock(so);
277 
278 	return (so);
279 }
280 
281 void
282 soqinsque(struct socket *head, struct socket *so, int q)
283 {
284 	soassertlocked(head);
285 	soassertlocked(so);
286 
287 	KASSERT(so->so_onq == NULL);
288 
289 	so->so_head = head;
290 	if (q == 0) {
291 		head->so_q0len++;
292 		so->so_onq = &head->so_q0;
293 	} else {
294 		head->so_qlen++;
295 		so->so_onq = &head->so_q;
296 	}
297 	TAILQ_INSERT_TAIL(so->so_onq, so, so_qe);
298 }
299 
300 int
301 soqremque(struct socket *so, int q)
302 {
303 	struct socket *head = so->so_head;
304 
305 	soassertlocked(so);
306 	soassertlocked(head);
307 
308 	if (q == 0) {
309 		if (so->so_onq != &head->so_q0)
310 			return (0);
311 		head->so_q0len--;
312 	} else {
313 		if (so->so_onq != &head->so_q)
314 			return (0);
315 		head->so_qlen--;
316 	}
317 	TAILQ_REMOVE(so->so_onq, so, so_qe);
318 	so->so_onq = NULL;
319 	so->so_head = NULL;
320 	return (1);
321 }
322 
323 /*
324  * Socantsendmore indicates that no more data will be sent on the
325  * socket; it would normally be applied to a socket when the user
326  * informs the system that no more data is to be sent, by the protocol
327  * code (in case PRU_SHUTDOWN).  Socantrcvmore indicates that no more data
328  * will be received, and will normally be applied to the socket by a
329  * protocol when it detects that the peer will send no more data.
330  * Data queued for reading in the socket may yet be read.
331  */
332 
333 void
334 socantsendmore(struct socket *so)
335 {
336 	soassertlocked(so);
337 	so->so_state |= SS_CANTSENDMORE;
338 	sowwakeup(so);
339 }
340 
341 void
342 socantrcvmore(struct socket *so)
343 {
344 	soassertlocked(so);
345 	so->so_state |= SS_CANTRCVMORE;
346 	sorwakeup(so);
347 }
348 
349 void
350 solock(struct socket *so)
351 {
352 	switch (so->so_proto->pr_domain->dom_family) {
353 	case PF_INET:
354 	case PF_INET6:
355 		NET_LOCK();
356 		break;
357 	default:
358 		rw_enter_write(&so->so_lock);
359 		break;
360 	}
361 }
362 
363 int
364 solock_persocket(struct socket *so)
365 {
366 	switch (so->so_proto->pr_domain->dom_family) {
367 	case PF_INET:
368 	case PF_INET6:
369 		return 0;
370 	default:
371 		return 1;
372 	}
373 }
374 
375 void
376 solock_pair(struct socket *so1, struct socket *so2)
377 {
378 	KASSERT(so1 != so2);
379 	KASSERT(so1->so_type == so2->so_type);
380 	KASSERT(solock_persocket(so1));
381 
382 	if (so1 < so2) {
383 		solock(so1);
384 		solock(so2);
385 	} else {
386 		solock(so2);
387 		solock(so1);
388 	}
389 }
390 
391 void
392 sounlock(struct socket *so)
393 {
394 	switch (so->so_proto->pr_domain->dom_family) {
395 	case PF_INET:
396 	case PF_INET6:
397 		NET_UNLOCK();
398 		break;
399 	default:
400 		rw_exit_write(&so->so_lock);
401 		break;
402 	}
403 }
404 
405 void
406 soassertlocked(struct socket *so)
407 {
408 	switch (so->so_proto->pr_domain->dom_family) {
409 	case PF_INET:
410 	case PF_INET6:
411 		NET_ASSERT_LOCKED();
412 		break;
413 	default:
414 		rw_assert_wrlock(&so->so_lock);
415 		break;
416 	}
417 }
418 
419 int
420 sosleep_nsec(struct socket *so, void *ident, int prio, const char *wmesg,
421     uint64_t nsecs)
422 {
423 	int ret;
424 
425 	switch (so->so_proto->pr_domain->dom_family) {
426 	case PF_INET:
427 	case PF_INET6:
428 		ret = rwsleep_nsec(ident, &netlock, prio, wmesg, nsecs);
429 		break;
430 	default:
431 		ret = rwsleep_nsec(ident, &so->so_lock, prio, wmesg, nsecs);
432 		break;
433 	}
434 
435 	return ret;
436 }
437 
438 /*
439  * Wait for data to arrive at/drain from a socket buffer.
440  */
441 int
442 sbwait(struct socket *so, struct sockbuf *sb)
443 {
444 	int prio = (sb->sb_flags & SB_NOINTR) ? PSOCK : PSOCK | PCATCH;
445 
446 	soassertlocked(so);
447 
448 	sb->sb_flags |= SB_WAIT;
449 	return sosleep_nsec(so, &sb->sb_cc, prio, "netio", sb->sb_timeo_nsecs);
450 }
451 
452 int
453 sblock(struct socket *so, struct sockbuf *sb, int wait)
454 {
455 	int error, prio = (sb->sb_flags & SB_NOINTR) ? PSOCK : PSOCK | PCATCH;
456 
457 	soassertlocked(so);
458 
459 	if ((sb->sb_flags & SB_LOCK) == 0) {
460 		sb->sb_flags |= SB_LOCK;
461 		return (0);
462 	}
463 	if (wait & M_NOWAIT)
464 		return (EWOULDBLOCK);
465 
466 	while (sb->sb_flags & SB_LOCK) {
467 		sb->sb_flags |= SB_WANT;
468 		error = sosleep_nsec(so, &sb->sb_flags, prio, "netlck", INFSLP);
469 		if (error)
470 			return (error);
471 	}
472 	sb->sb_flags |= SB_LOCK;
473 	return (0);
474 }
475 
476 void
477 sbunlock(struct socket *so, struct sockbuf *sb)
478 {
479 	soassertlocked(so);
480 
481 	sb->sb_flags &= ~SB_LOCK;
482 	if (sb->sb_flags & SB_WANT) {
483 		sb->sb_flags &= ~SB_WANT;
484 		wakeup(&sb->sb_flags);
485 	}
486 }
487 
488 /*
489  * Wakeup processes waiting on a socket buffer.
490  * Do asynchronous notification via SIGIO
491  * if the socket buffer has the SB_ASYNC flag set.
492  */
493 void
494 sowakeup(struct socket *so, struct sockbuf *sb)
495 {
496 	soassertlocked(so);
497 
498 	if (sb->sb_flags & SB_WAIT) {
499 		sb->sb_flags &= ~SB_WAIT;
500 		wakeup(&sb->sb_cc);
501 	}
502 	if (sb->sb_flags & SB_ASYNC)
503 		pgsigio(&so->so_sigio, SIGIO, 0);
504 	selwakeup(&sb->sb_sel);
505 }
506 
507 /*
508  * Socket buffer (struct sockbuf) utility routines.
509  *
510  * Each socket contains two socket buffers: one for sending data and
511  * one for receiving data.  Each buffer contains a queue of mbufs,
512  * information about the number of mbufs and amount of data in the
513  * queue, and other fields allowing select() statements and notification
514  * on data availability to be implemented.
515  *
516  * Data stored in a socket buffer is maintained as a list of records.
517  * Each record is a list of mbufs chained together with the m_next
518  * field.  Records are chained together with the m_nextpkt field. The upper
519  * level routine soreceive() expects the following conventions to be
520  * observed when placing information in the receive buffer:
521  *
522  * 1. If the protocol requires each message be preceded by the sender's
523  *    name, then a record containing that name must be present before
524  *    any associated data (mbuf's must be of type MT_SONAME).
525  * 2. If the protocol supports the exchange of ``access rights'' (really
526  *    just additional data associated with the message), and there are
527  *    ``rights'' to be received, then a record containing this data
528  *    should be present (mbuf's must be of type MT_CONTROL).
529  * 3. If a name or rights record exists, then it must be followed by
530  *    a data record, perhaps of zero length.
531  *
532  * Before using a new socket structure it is first necessary to reserve
533  * buffer space to the socket, by calling sbreserve().  This should commit
534  * some of the available buffer space in the system buffer pool for the
535  * socket (currently, it does nothing but enforce limits).  The space
536  * should be released by calling sbrelease() when the socket is destroyed.
537  */
538 
539 int
540 soreserve(struct socket *so, u_long sndcc, u_long rcvcc)
541 {
542 	soassertlocked(so);
543 
544 	if (sbreserve(so, &so->so_snd, sndcc))
545 		goto bad;
546 	if (sbreserve(so, &so->so_rcv, rcvcc))
547 		goto bad2;
548 	so->so_snd.sb_wat = sndcc;
549 	so->so_rcv.sb_wat = rcvcc;
550 	if (so->so_rcv.sb_lowat == 0)
551 		so->so_rcv.sb_lowat = 1;
552 	if (so->so_snd.sb_lowat == 0)
553 		so->so_snd.sb_lowat = MCLBYTES;
554 	if (so->so_snd.sb_lowat > so->so_snd.sb_hiwat)
555 		so->so_snd.sb_lowat = so->so_snd.sb_hiwat;
556 	return (0);
557 bad2:
558 	sbrelease(so, &so->so_snd);
559 bad:
560 	return (ENOBUFS);
561 }
562 
563 /*
564  * Allot mbufs to a sockbuf.
565  * Attempt to scale mbmax so that mbcnt doesn't become limiting
566  * if buffering efficiency is near the normal case.
567  */
568 int
569 sbreserve(struct socket *so, struct sockbuf *sb, u_long cc)
570 {
571 	KASSERT(sb == &so->so_rcv || sb == &so->so_snd);
572 	soassertlocked(so);
573 
574 	if (cc == 0 || cc > sb_max)
575 		return (1);
576 	sb->sb_hiwat = cc;
577 	sb->sb_mbmax = max(3 * MAXMCLBYTES, cc * 8);
578 	if (sb->sb_lowat > sb->sb_hiwat)
579 		sb->sb_lowat = sb->sb_hiwat;
580 	return (0);
581 }
582 
583 /*
584  * In low memory situation, do not accept any greater than normal request.
585  */
586 int
587 sbcheckreserve(u_long cnt, u_long defcnt)
588 {
589 	if (cnt > defcnt && sbchecklowmem())
590 		return (ENOBUFS);
591 	return (0);
592 }
593 
594 int
595 sbchecklowmem(void)
596 {
597 	static int sblowmem;
598 	unsigned int used = m_pool_used();
599 
600 	if (used < 60)
601 		sblowmem = 0;
602 	else if (used > 80)
603 		sblowmem = 1;
604 
605 	return (sblowmem);
606 }
607 
608 /*
609  * Free mbufs held by a socket, and reserved mbuf space.
610  */
611 void
612 sbrelease(struct socket *so, struct sockbuf *sb)
613 {
614 
615 	sbflush(so, sb);
616 	sb->sb_hiwat = sb->sb_mbmax = 0;
617 }
618 
619 /*
620  * Routines to add and remove
621  * data from an mbuf queue.
622  *
623  * The routines sbappend() or sbappendrecord() are normally called to
624  * append new mbufs to a socket buffer, after checking that adequate
625  * space is available, comparing the function sbspace() with the amount
626  * of data to be added.  sbappendrecord() differs from sbappend() in
627  * that data supplied is treated as the beginning of a new record.
628  * To place a sender's address, optional access rights, and data in a
629  * socket receive buffer, sbappendaddr() should be used.  To place
630  * access rights and data in a socket receive buffer, sbappendrights()
631  * should be used.  In either case, the new data begins a new record.
632  * Note that unlike sbappend() and sbappendrecord(), these routines check
633  * for the caller that there will be enough space to store the data.
634  * Each fails if there is not enough space, or if it cannot find mbufs
635  * to store additional information in.
636  *
637  * Reliable protocols may use the socket send buffer to hold data
638  * awaiting acknowledgement.  Data is normally copied from a socket
639  * send buffer in a protocol with m_copym for output to a peer,
640  * and then removing the data from the socket buffer with sbdrop()
641  * or sbdroprecord() when the data is acknowledged by the peer.
642  */
643 
644 #ifdef SOCKBUF_DEBUG
645 void
646 sblastrecordchk(struct sockbuf *sb, const char *where)
647 {
648 	struct mbuf *m = sb->sb_mb;
649 
650 	while (m && m->m_nextpkt)
651 		m = m->m_nextpkt;
652 
653 	if (m != sb->sb_lastrecord) {
654 		printf("sblastrecordchk: sb_mb %p sb_lastrecord %p last %p\n",
655 		    sb->sb_mb, sb->sb_lastrecord, m);
656 		printf("packet chain:\n");
657 		for (m = sb->sb_mb; m != NULL; m = m->m_nextpkt)
658 			printf("\t%p\n", m);
659 		panic("sblastrecordchk from %s", where);
660 	}
661 }
662 
663 void
664 sblastmbufchk(struct sockbuf *sb, const char *where)
665 {
666 	struct mbuf *m = sb->sb_mb;
667 	struct mbuf *n;
668 
669 	while (m && m->m_nextpkt)
670 		m = m->m_nextpkt;
671 
672 	while (m && m->m_next)
673 		m = m->m_next;
674 
675 	if (m != sb->sb_mbtail) {
676 		printf("sblastmbufchk: sb_mb %p sb_mbtail %p last %p\n",
677 		    sb->sb_mb, sb->sb_mbtail, m);
678 		printf("packet tree:\n");
679 		for (m = sb->sb_mb; m != NULL; m = m->m_nextpkt) {
680 			printf("\t");
681 			for (n = m; n != NULL; n = n->m_next)
682 				printf("%p ", n);
683 			printf("\n");
684 		}
685 		panic("sblastmbufchk from %s", where);
686 	}
687 }
688 #endif /* SOCKBUF_DEBUG */
689 
690 #define	SBLINKRECORD(sb, m0)						\
691 do {									\
692 	if ((sb)->sb_lastrecord != NULL)				\
693 		(sb)->sb_lastrecord->m_nextpkt = (m0);			\
694 	else								\
695 		(sb)->sb_mb = (m0);					\
696 	(sb)->sb_lastrecord = (m0);					\
697 } while (/*CONSTCOND*/0)
698 
699 /*
700  * Append mbuf chain m to the last record in the
701  * socket buffer sb.  The additional space associated
702  * the mbuf chain is recorded in sb.  Empty mbufs are
703  * discarded and mbufs are compacted where possible.
704  */
705 void
706 sbappend(struct socket *so, struct sockbuf *sb, struct mbuf *m)
707 {
708 	struct mbuf *n;
709 
710 	if (m == NULL)
711 		return;
712 
713 	soassertlocked(so);
714 	SBLASTRECORDCHK(sb, "sbappend 1");
715 
716 	if ((n = sb->sb_lastrecord) != NULL) {
717 		/*
718 		 * XXX Would like to simply use sb_mbtail here, but
719 		 * XXX I need to verify that I won't miss an EOR that
720 		 * XXX way.
721 		 */
722 		do {
723 			if (n->m_flags & M_EOR) {
724 				sbappendrecord(so, sb, m); /* XXXXXX!!!! */
725 				return;
726 			}
727 		} while (n->m_next && (n = n->m_next));
728 	} else {
729 		/*
730 		 * If this is the first record in the socket buffer, it's
731 		 * also the last record.
732 		 */
733 		sb->sb_lastrecord = m;
734 	}
735 	sbcompress(so, sb, m, n);
736 	SBLASTRECORDCHK(sb, "sbappend 2");
737 }
738 
739 /*
740  * This version of sbappend() should only be used when the caller
741  * absolutely knows that there will never be more than one record
742  * in the socket buffer, that is, a stream protocol (such as TCP).
743  */
744 void
745 sbappendstream(struct socket *so, struct sockbuf *sb, struct mbuf *m)
746 {
747 	KASSERT(sb == &so->so_rcv || sb == &so->so_snd);
748 	soassertlocked(so);
749 	KDASSERT(m->m_nextpkt == NULL);
750 	KASSERT(sb->sb_mb == sb->sb_lastrecord);
751 
752 	SBLASTMBUFCHK(sb, __func__);
753 
754 	sbcompress(so, sb, m, sb->sb_mbtail);
755 
756 	sb->sb_lastrecord = sb->sb_mb;
757 	SBLASTRECORDCHK(sb, __func__);
758 }
759 
760 #ifdef SOCKBUF_DEBUG
761 void
762 sbcheck(struct socket *so, struct sockbuf *sb)
763 {
764 	struct mbuf *m, *n;
765 	u_long len = 0, mbcnt = 0;
766 
767 	for (m = sb->sb_mb; m; m = m->m_nextpkt) {
768 		for (n = m; n; n = n->m_next) {
769 			len += n->m_len;
770 			mbcnt += MSIZE;
771 			if (n->m_flags & M_EXT)
772 				mbcnt += n->m_ext.ext_size;
773 			if (m != n && n->m_nextpkt)
774 				panic("sbcheck nextpkt");
775 		}
776 	}
777 	if (len != sb->sb_cc || mbcnt != sb->sb_mbcnt) {
778 		printf("cc %lu != %lu || mbcnt %lu != %lu\n", len, sb->sb_cc,
779 		    mbcnt, sb->sb_mbcnt);
780 		panic("sbcheck");
781 	}
782 }
783 #endif
784 
785 /*
786  * As above, except the mbuf chain
787  * begins a new record.
788  */
789 void
790 sbappendrecord(struct socket *so, struct sockbuf *sb, struct mbuf *m0)
791 {
792 	struct mbuf *m;
793 
794 	KASSERT(sb == &so->so_rcv || sb == &so->so_snd);
795 	soassertlocked(so);
796 
797 	if (m0 == NULL)
798 		return;
799 
800 	/*
801 	 * Put the first mbuf on the queue.
802 	 * Note this permits zero length records.
803 	 */
804 	sballoc(so, sb, m0);
805 	SBLASTRECORDCHK(sb, "sbappendrecord 1");
806 	SBLINKRECORD(sb, m0);
807 	m = m0->m_next;
808 	m0->m_next = NULL;
809 	if (m && (m0->m_flags & M_EOR)) {
810 		m0->m_flags &= ~M_EOR;
811 		m->m_flags |= M_EOR;
812 	}
813 	sbcompress(so, sb, m, m0);
814 	SBLASTRECORDCHK(sb, "sbappendrecord 2");
815 }
816 
817 /*
818  * Append address and data, and optionally, control (ancillary) data
819  * to the receive queue of a socket.  If present,
820  * m0 must include a packet header with total length.
821  * Returns 0 if no space in sockbuf or insufficient mbufs.
822  */
823 int
824 sbappendaddr(struct socket *so, struct sockbuf *sb, const struct sockaddr *asa,
825     struct mbuf *m0, struct mbuf *control)
826 {
827 	struct mbuf *m, *n, *nlast;
828 	int space = asa->sa_len;
829 
830 	soassertlocked(so);
831 
832 	if (m0 && (m0->m_flags & M_PKTHDR) == 0)
833 		panic("sbappendaddr");
834 	if (m0)
835 		space += m0->m_pkthdr.len;
836 	for (n = control; n; n = n->m_next) {
837 		space += n->m_len;
838 		if (n->m_next == NULL)	/* keep pointer to last control buf */
839 			break;
840 	}
841 	if (space > sbspace(so, sb))
842 		return (0);
843 	if (asa->sa_len > MLEN)
844 		return (0);
845 	MGET(m, M_DONTWAIT, MT_SONAME);
846 	if (m == NULL)
847 		return (0);
848 	m->m_len = asa->sa_len;
849 	memcpy(mtod(m, caddr_t), asa, asa->sa_len);
850 	if (n)
851 		n->m_next = m0;		/* concatenate data to control */
852 	else
853 		control = m0;
854 	m->m_next = control;
855 
856 	SBLASTRECORDCHK(sb, "sbappendaddr 1");
857 
858 	for (n = m; n->m_next != NULL; n = n->m_next)
859 		sballoc(so, sb, n);
860 	sballoc(so, sb, n);
861 	nlast = n;
862 	SBLINKRECORD(sb, m);
863 
864 	sb->sb_mbtail = nlast;
865 	SBLASTMBUFCHK(sb, "sbappendaddr");
866 
867 	SBLASTRECORDCHK(sb, "sbappendaddr 2");
868 
869 	return (1);
870 }
871 
872 int
873 sbappendcontrol(struct socket *so, struct sockbuf *sb, struct mbuf *m0,
874     struct mbuf *control)
875 {
876 	struct mbuf *m, *mlast, *n;
877 	int space = 0;
878 
879 	if (control == NULL)
880 		panic("sbappendcontrol");
881 	for (m = control; ; m = m->m_next) {
882 		space += m->m_len;
883 		if (m->m_next == NULL)
884 			break;
885 	}
886 	n = m;			/* save pointer to last control buffer */
887 	for (m = m0; m; m = m->m_next)
888 		space += m->m_len;
889 	if (space > sbspace(so, sb))
890 		return (0);
891 	n->m_next = m0;			/* concatenate data to control */
892 
893 	SBLASTRECORDCHK(sb, "sbappendcontrol 1");
894 
895 	for (m = control; m->m_next != NULL; m = m->m_next)
896 		sballoc(so, sb, m);
897 	sballoc(so, sb, m);
898 	mlast = m;
899 	SBLINKRECORD(sb, control);
900 
901 	sb->sb_mbtail = mlast;
902 	SBLASTMBUFCHK(sb, "sbappendcontrol");
903 
904 	SBLASTRECORDCHK(sb, "sbappendcontrol 2");
905 
906 	return (1);
907 }
908 
909 /*
910  * Compress mbuf chain m into the socket
911  * buffer sb following mbuf n.  If n
912  * is null, the buffer is presumed empty.
913  */
914 void
915 sbcompress(struct socket *so, struct sockbuf *sb, struct mbuf *m,
916     struct mbuf *n)
917 {
918 	int eor = 0;
919 	struct mbuf *o;
920 
921 	while (m) {
922 		eor |= m->m_flags & M_EOR;
923 		if (m->m_len == 0 &&
924 		    (eor == 0 ||
925 		    (((o = m->m_next) || (o = n)) &&
926 		    o->m_type == m->m_type))) {
927 			if (sb->sb_lastrecord == m)
928 				sb->sb_lastrecord = m->m_next;
929 			m = m_free(m);
930 			continue;
931 		}
932 		if (n && (n->m_flags & M_EOR) == 0 &&
933 		    /* m_trailingspace() checks buffer writeability */
934 		    m->m_len <= ((n->m_flags & M_EXT)? n->m_ext.ext_size :
935 		       MCLBYTES) / 4 && /* XXX Don't copy too much */
936 		    m->m_len <= m_trailingspace(n) &&
937 		    n->m_type == m->m_type) {
938 			memcpy(mtod(n, caddr_t) + n->m_len, mtod(m, caddr_t),
939 			    m->m_len);
940 			n->m_len += m->m_len;
941 			sb->sb_cc += m->m_len;
942 			if (m->m_type != MT_CONTROL && m->m_type != MT_SONAME)
943 				sb->sb_datacc += m->m_len;
944 			m = m_free(m);
945 			continue;
946 		}
947 		if (n)
948 			n->m_next = m;
949 		else
950 			sb->sb_mb = m;
951 		sb->sb_mbtail = m;
952 		sballoc(so, sb, m);
953 		n = m;
954 		m->m_flags &= ~M_EOR;
955 		m = m->m_next;
956 		n->m_next = NULL;
957 	}
958 	if (eor) {
959 		if (n)
960 			n->m_flags |= eor;
961 		else
962 			printf("semi-panic: sbcompress");
963 	}
964 	SBLASTMBUFCHK(sb, __func__);
965 }
966 
967 /*
968  * Free all mbufs in a sockbuf.
969  * Check that all resources are reclaimed.
970  */
971 void
972 sbflush(struct socket *so, struct sockbuf *sb)
973 {
974 	KASSERT(sb == &so->so_rcv || sb == &so->so_snd);
975 	KASSERT((sb->sb_flags & SB_LOCK) == 0);
976 
977 	while (sb->sb_mbcnt)
978 		sbdrop(so, sb, (int)sb->sb_cc);
979 
980 	KASSERT(sb->sb_cc == 0);
981 	KASSERT(sb->sb_datacc == 0);
982 	KASSERT(sb->sb_mb == NULL);
983 	KASSERT(sb->sb_mbtail == NULL);
984 	KASSERT(sb->sb_lastrecord == NULL);
985 }
986 
987 /*
988  * Drop data from (the front of) a sockbuf.
989  */
990 void
991 sbdrop(struct socket *so, struct sockbuf *sb, int len)
992 {
993 	struct mbuf *m, *mn;
994 	struct mbuf *next;
995 
996 	KASSERT(sb == &so->so_rcv || sb == &so->so_snd);
997 	soassertlocked(so);
998 
999 	next = (m = sb->sb_mb) ? m->m_nextpkt : NULL;
1000 	while (len > 0) {
1001 		if (m == NULL) {
1002 			if (next == NULL)
1003 				panic("sbdrop");
1004 			m = next;
1005 			next = m->m_nextpkt;
1006 			continue;
1007 		}
1008 		if (m->m_len > len) {
1009 			m->m_len -= len;
1010 			m->m_data += len;
1011 			sb->sb_cc -= len;
1012 			if (m->m_type != MT_CONTROL && m->m_type != MT_SONAME)
1013 				sb->sb_datacc -= len;
1014 			break;
1015 		}
1016 		len -= m->m_len;
1017 		sbfree(so, sb, m);
1018 		mn = m_free(m);
1019 		m = mn;
1020 	}
1021 	while (m && m->m_len == 0) {
1022 		sbfree(so, sb, m);
1023 		mn = m_free(m);
1024 		m = mn;
1025 	}
1026 	if (m) {
1027 		sb->sb_mb = m;
1028 		m->m_nextpkt = next;
1029 	} else
1030 		sb->sb_mb = next;
1031 	/*
1032 	 * First part is an inline SB_EMPTY_FIXUP().  Second part
1033 	 * makes sure sb_lastrecord is up-to-date if we dropped
1034 	 * part of the last record.
1035 	 */
1036 	m = sb->sb_mb;
1037 	if (m == NULL) {
1038 		sb->sb_mbtail = NULL;
1039 		sb->sb_lastrecord = NULL;
1040 	} else if (m->m_nextpkt == NULL)
1041 		sb->sb_lastrecord = m;
1042 }
1043 
1044 /*
1045  * Drop a record off the front of a sockbuf
1046  * and move the next record to the front.
1047  */
1048 void
1049 sbdroprecord(struct socket *so, struct sockbuf *sb)
1050 {
1051 	struct mbuf *m, *mn;
1052 
1053 	m = sb->sb_mb;
1054 	if (m) {
1055 		sb->sb_mb = m->m_nextpkt;
1056 		do {
1057 			sbfree(so, sb, m);
1058 			mn = m_free(m);
1059 		} while ((m = mn) != NULL);
1060 	}
1061 	SB_EMPTY_FIXUP(sb);
1062 }
1063 
1064 /*
1065  * Create a "control" mbuf containing the specified data
1066  * with the specified type for presentation on a socket buffer.
1067  */
1068 struct mbuf *
1069 sbcreatecontrol(const void *p, size_t size, int type, int level)
1070 {
1071 	struct cmsghdr *cp;
1072 	struct mbuf *m;
1073 
1074 	if (CMSG_SPACE(size) > MCLBYTES) {
1075 		printf("sbcreatecontrol: message too large %zu\n", size);
1076 		return (NULL);
1077 	}
1078 
1079 	if ((m = m_get(M_DONTWAIT, MT_CONTROL)) == NULL)
1080 		return (NULL);
1081 	if (CMSG_SPACE(size) > MLEN) {
1082 		MCLGET(m, M_DONTWAIT);
1083 		if ((m->m_flags & M_EXT) == 0) {
1084 			m_free(m);
1085 			return NULL;
1086 		}
1087 	}
1088 	cp = mtod(m, struct cmsghdr *);
1089 	memset(cp, 0, CMSG_SPACE(size));
1090 	memcpy(CMSG_DATA(cp), p, size);
1091 	m->m_len = CMSG_SPACE(size);
1092 	cp->cmsg_len = CMSG_LEN(size);
1093 	cp->cmsg_level = level;
1094 	cp->cmsg_type = type;
1095 	return (m);
1096 }
1097