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