xref: /netbsd-src/sys/kern/uipc_socket2.c (revision 2718af68c3efc72c9769069b5c7f9ed36f6b9def)
1 /*	$NetBSD: uipc_socket2.c,v 1.141 2022/04/09 23:52:23 riastradh Exp $	*/
2 
3 /*-
4  * Copyright (c) 2008 The NetBSD Foundation, Inc.
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
17  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
18  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
19  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
20  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26  * POSSIBILITY OF SUCH DAMAGE.
27  */
28 
29 /*
30  * Copyright (c) 1982, 1986, 1988, 1990, 1993
31  *	The Regents of the University of California.  All rights reserved.
32  *
33  * Redistribution and use in source and binary forms, with or without
34  * modification, are permitted provided that the following conditions
35  * are met:
36  * 1. Redistributions of source code must retain the above copyright
37  *    notice, this list of conditions and the following disclaimer.
38  * 2. Redistributions in binary form must reproduce the above copyright
39  *    notice, this list of conditions and the following disclaimer in the
40  *    documentation and/or other materials provided with the distribution.
41  * 3. Neither the name of the University nor the names of its contributors
42  *    may be used to endorse or promote products derived from this software
43  *    without specific prior written permission.
44  *
45  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
46  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
47  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
48  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
49  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
50  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
51  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
52  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
53  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
54  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
55  * SUCH DAMAGE.
56  *
57  *	@(#)uipc_socket2.c	8.2 (Berkeley) 2/14/95
58  */
59 
60 #include <sys/cdefs.h>
61 __KERNEL_RCSID(0, "$NetBSD: uipc_socket2.c,v 1.141 2022/04/09 23:52:23 riastradh Exp $");
62 
63 #ifdef _KERNEL_OPT
64 #include "opt_ddb.h"
65 #include "opt_inet.h"
66 #include "opt_mbuftrace.h"
67 #include "opt_sb_max.h"
68 #endif
69 
70 #include <sys/param.h>
71 #include <sys/systm.h>
72 #include <sys/proc.h>
73 #include <sys/file.h>
74 #include <sys/buf.h>
75 #include <sys/mbuf.h>
76 #include <sys/protosw.h>
77 #include <sys/domain.h>
78 #include <sys/poll.h>
79 #include <sys/socket.h>
80 #include <sys/socketvar.h>
81 #include <sys/signalvar.h>
82 #include <sys/kauth.h>
83 #include <sys/pool.h>
84 #include <sys/uidinfo.h>
85 
86 #ifdef DDB
87 #include <sys/filedesc.h>
88 #endif
89 
90 /*
91  * Primitive routines for operating on sockets and socket buffers.
92  *
93  * Connection life-cycle:
94  *
95  *	Normal sequence from the active (originating) side:
96  *
97  *	- soisconnecting() is called during processing of connect() call,
98  *	- resulting in an eventual call to soisconnected() if/when the
99  *	  connection is established.
100  *
101  *	When the connection is torn down during processing of disconnect():
102  *
103  *	- soisdisconnecting() is called and,
104  *	- soisdisconnected() is called when the connection to the peer
105  *	  is totally severed.
106  *
107  *	The semantics of these routines are such that connectionless protocols
108  *	can call soisconnected() and soisdisconnected() only, bypassing the
109  *	in-progress calls when setting up a ``connection'' takes no time.
110  *
111  *	From the passive side, a socket is created with two queues of sockets:
112  *
113  *	- so_q0 (0) for partial connections (i.e. connections in progress)
114  *	- so_q (1) for connections already made and awaiting user acceptance.
115  *
116  *	As a protocol is preparing incoming connections, it creates a socket
117  *	structure queued on so_q0 by calling sonewconn().  When the connection
118  *	is established, soisconnected() is called, and transfers the
119  *	socket structure to so_q, making it available to accept().
120  *
121  *	If a socket is closed with sockets on either so_q0 or so_q, these
122  *	sockets are dropped.
123  *
124  * Locking rules and assumptions:
125  *
126  * o socket::so_lock can change on the fly.  The low level routines used
127  *   to lock sockets are aware of this.  When so_lock is acquired, the
128  *   routine locking must check to see if so_lock still points to the
129  *   lock that was acquired.  If so_lock has changed in the meantime, the
130  *   now irrelevant lock that was acquired must be dropped and the lock
131  *   operation retried.  Although not proven here, this is completely safe
132  *   on a multiprocessor system, even with relaxed memory ordering, given
133  *   the next two rules:
134  *
135  * o In order to mutate so_lock, the lock pointed to by the current value
136  *   of so_lock must be held: i.e., the socket must be held locked by the
137  *   changing thread.  The thread must issue membar_release() to prevent
138  *   memory accesses being reordered, and can set so_lock to the desired
139  *   value.  If the lock pointed to by the new value of so_lock is not
140  *   held by the changing thread, the socket must then be considered
141  *   unlocked.
142  *
143  * o If so_lock is mutated, and the previous lock referred to by so_lock
144  *   could still be visible to other threads in the system (e.g. via file
145  *   descriptor or protocol-internal reference), then the old lock must
146  *   remain valid until the socket and/or protocol control block has been
147  *   torn down.
148  *
149  * o If a socket has a non-NULL so_head value (i.e. is in the process of
150  *   connecting), then locking the socket must also lock the socket pointed
151  *   to by so_head: their lock pointers must match.
152  *
153  * o If a socket has connections in progress (so_q, so_q0 not empty) then
154  *   locking the socket must also lock the sockets attached to both queues.
155  *   Again, their lock pointers must match.
156  *
157  * o Beyond the initial lock assignment in socreate(), assigning locks to
158  *   sockets is the responsibility of the individual protocols / protocol
159  *   domains.
160  */
161 
162 static pool_cache_t	socket_cache;
163 u_long			sb_max = SB_MAX;/* maximum socket buffer size */
164 static u_long		sb_max_adj;	/* adjusted sb_max */
165 
166 void
167 soisconnecting(struct socket *so)
168 {
169 
170 	KASSERT(solocked(so));
171 
172 	so->so_state &= ~(SS_ISCONNECTED|SS_ISDISCONNECTING);
173 	so->so_state |= SS_ISCONNECTING;
174 }
175 
176 void
177 soisconnected(struct socket *so)
178 {
179 	struct socket	*head;
180 
181 	head = so->so_head;
182 
183 	KASSERT(solocked(so));
184 	KASSERT(head == NULL || solocked2(so, head));
185 
186 	so->so_state &= ~(SS_ISCONNECTING | SS_ISDISCONNECTING);
187 	so->so_state |= SS_ISCONNECTED;
188 	if (head && so->so_onq == &head->so_q0) {
189 		if ((so->so_options & SO_ACCEPTFILTER) == 0) {
190 			/*
191 			 * Re-enqueue and wake up any waiters, e.g.
192 			 * processes blocking on accept().
193 			 */
194 			soqremque(so, 0);
195 			soqinsque(head, so, 1);
196 			sorwakeup(head);
197 			cv_broadcast(&head->so_cv);
198 		} else {
199 			so->so_upcall =
200 			    head->so_accf->so_accept_filter->accf_callback;
201 			so->so_upcallarg = head->so_accf->so_accept_filter_arg;
202 			so->so_rcv.sb_flags |= SB_UPCALL;
203 			so->so_options &= ~SO_ACCEPTFILTER;
204 			(*so->so_upcall)(so, so->so_upcallarg,
205 					 POLLIN|POLLRDNORM, M_DONTWAIT);
206 		}
207 	} else {
208 		cv_broadcast(&so->so_cv);
209 		sorwakeup(so);
210 		sowwakeup(so);
211 	}
212 }
213 
214 void
215 soisdisconnecting(struct socket *so)
216 {
217 
218 	KASSERT(solocked(so));
219 
220 	so->so_state &= ~SS_ISCONNECTING;
221 	so->so_state |= (SS_ISDISCONNECTING|SS_CANTRCVMORE|SS_CANTSENDMORE);
222 	cv_broadcast(&so->so_cv);
223 	sowwakeup(so);
224 	sorwakeup(so);
225 }
226 
227 void
228 soisdisconnected(struct socket *so)
229 {
230 
231 	KASSERT(solocked(so));
232 
233 	so->so_state &= ~(SS_ISCONNECTING|SS_ISCONNECTED|SS_ISDISCONNECTING);
234 	so->so_state |= (SS_CANTRCVMORE|SS_CANTSENDMORE|SS_ISDISCONNECTED);
235 	cv_broadcast(&so->so_cv);
236 	sowwakeup(so);
237 	sorwakeup(so);
238 }
239 
240 void
241 soinit2(void)
242 {
243 
244 	socket_cache = pool_cache_init(sizeof(struct socket), 0, 0, 0,
245 	    "socket", NULL, IPL_SOFTNET, NULL, NULL, NULL);
246 }
247 
248 /*
249  * sonewconn: accept a new connection.
250  *
251  * When an attempt at a new connection is noted on a socket which accepts
252  * connections, sonewconn(9) is called.  If the connection is possible
253  * (subject to space constraints, etc) then we allocate a new structure,
254  * properly linked into the data structure of the original socket.
255  *
256  * => If 'soready' is true, then socket will become ready for accept() i.e.
257  *    inserted into the so_q queue, SS_ISCONNECTED set and waiters awoken.
258  * => May be called from soft-interrupt context.
259  * => Listening socket should be locked.
260  * => Returns the new socket locked.
261  */
262 struct socket *
263 sonewconn(struct socket *head, bool soready)
264 {
265 	struct socket *so;
266 	int soqueue, error;
267 
268 	KASSERT(solocked(head));
269 
270 	if (head->so_qlen + head->so_q0len > 3 * head->so_qlimit / 2) {
271 		/*
272 		 * Listen queue overflow.  If there is an accept filter
273 		 * active, pass through the oldest cxn it's handling.
274 		 */
275 		if (head->so_accf == NULL) {
276 			return NULL;
277 		} else {
278 			struct socket *so2, *next;
279 
280 			/* Pass the oldest connection waiting in the
281 			   accept filter */
282 			for (so2 = TAILQ_FIRST(&head->so_q0);
283 			     so2 != NULL; so2 = next) {
284 				next = TAILQ_NEXT(so2, so_qe);
285 				if (so2->so_upcall == NULL) {
286 					continue;
287 				}
288 				so2->so_upcall = NULL;
289 				so2->so_upcallarg = NULL;
290 				so2->so_options &= ~SO_ACCEPTFILTER;
291 				so2->so_rcv.sb_flags &= ~SB_UPCALL;
292 				soisconnected(so2);
293 				break;
294 			}
295 
296 			/* If nothing was nudged out of the acept filter, bail
297 			 * out; otherwise proceed allocating the socket. */
298 			if (so2 == NULL) {
299 				return NULL;
300 			}
301 		}
302 	}
303 	if ((head->so_options & SO_ACCEPTFILTER) != 0) {
304 		soready = false;
305 	}
306 	soqueue = soready ? 1 : 0;
307 
308 	if ((so = soget(false)) == NULL) {
309 		return NULL;
310 	}
311 	so->so_type = head->so_type;
312 	so->so_options = head->so_options & ~SO_ACCEPTCONN;
313 	so->so_linger = head->so_linger;
314 	so->so_state = head->so_state | SS_NOFDREF;
315 	so->so_proto = head->so_proto;
316 	so->so_timeo = head->so_timeo;
317 	so->so_pgid = head->so_pgid;
318 	so->so_send = head->so_send;
319 	so->so_receive = head->so_receive;
320 	so->so_uidinfo = head->so_uidinfo;
321 	so->so_egid = head->so_egid;
322 	so->so_cpid = head->so_cpid;
323 
324 	/*
325 	 * Share the lock with the listening-socket, it may get unshared
326 	 * once the connection is complete.
327 	 *
328 	 * so_lock is stable while we hold the socket locked, so no
329 	 * need for atomic_load_* here.
330 	 */
331 	mutex_obj_hold(head->so_lock);
332 	so->so_lock = head->so_lock;
333 
334 	/*
335 	 * Reserve the space for socket buffers.
336 	 */
337 #ifdef MBUFTRACE
338 	so->so_mowner = head->so_mowner;
339 	so->so_rcv.sb_mowner = head->so_rcv.sb_mowner;
340 	so->so_snd.sb_mowner = head->so_snd.sb_mowner;
341 #endif
342 	if (soreserve(so, head->so_snd.sb_hiwat, head->so_rcv.sb_hiwat)) {
343 		goto out;
344 	}
345 	so->so_snd.sb_lowat = head->so_snd.sb_lowat;
346 	so->so_rcv.sb_lowat = head->so_rcv.sb_lowat;
347 	so->so_rcv.sb_timeo = head->so_rcv.sb_timeo;
348 	so->so_snd.sb_timeo = head->so_snd.sb_timeo;
349 	so->so_rcv.sb_flags |= head->so_rcv.sb_flags & (SB_AUTOSIZE | SB_ASYNC);
350 	so->so_snd.sb_flags |= head->so_snd.sb_flags & (SB_AUTOSIZE | SB_ASYNC);
351 
352 	/*
353 	 * Finally, perform the protocol attach.  Note: a new socket
354 	 * lock may be assigned at this point (if so, it will be held).
355 	 */
356 	error = (*so->so_proto->pr_usrreqs->pr_attach)(so, 0);
357 	if (error) {
358 out:
359 		KASSERT(solocked(so));
360 		KASSERT(so->so_accf == NULL);
361 		soput(so);
362 
363 		/* Note: the listening socket shall stay locked. */
364 		KASSERT(solocked(head));
365 		return NULL;
366 	}
367 	KASSERT(solocked2(head, so));
368 
369 	/*
370 	 * Insert into the queue.  If ready, update the connection status
371 	 * and wake up any waiters, e.g. processes blocking on accept().
372 	 */
373 	soqinsque(head, so, soqueue);
374 	if (soready) {
375 		so->so_state |= SS_ISCONNECTED;
376 		sorwakeup(head);
377 		cv_broadcast(&head->so_cv);
378 	}
379 	return so;
380 }
381 
382 struct socket *
383 soget(bool waitok)
384 {
385 	struct socket *so;
386 
387 	so = pool_cache_get(socket_cache, (waitok ? PR_WAITOK : PR_NOWAIT));
388 	if (__predict_false(so == NULL))
389 		return (NULL);
390 	memset(so, 0, sizeof(*so));
391 	TAILQ_INIT(&so->so_q0);
392 	TAILQ_INIT(&so->so_q);
393 	cv_init(&so->so_cv, "socket");
394 	cv_init(&so->so_rcv.sb_cv, "netio");
395 	cv_init(&so->so_snd.sb_cv, "netio");
396 	selinit(&so->so_rcv.sb_sel);
397 	selinit(&so->so_snd.sb_sel);
398 	so->so_rcv.sb_so = so;
399 	so->so_snd.sb_so = so;
400 	return so;
401 }
402 
403 void
404 soput(struct socket *so)
405 {
406 
407 	KASSERT(!cv_has_waiters(&so->so_cv));
408 	KASSERT(!cv_has_waiters(&so->so_rcv.sb_cv));
409 	KASSERT(!cv_has_waiters(&so->so_snd.sb_cv));
410 	seldestroy(&so->so_rcv.sb_sel);
411 	seldestroy(&so->so_snd.sb_sel);
412 	mutex_obj_free(so->so_lock);
413 	cv_destroy(&so->so_cv);
414 	cv_destroy(&so->so_rcv.sb_cv);
415 	cv_destroy(&so->so_snd.sb_cv);
416 	pool_cache_put(socket_cache, so);
417 }
418 
419 /*
420  * soqinsque: insert socket of a new connection into the specified
421  * accept queue of the listening socket (head).
422  *
423  *	q = 0: queue of partial connections
424  *	q = 1: queue of incoming connections
425  */
426 void
427 soqinsque(struct socket *head, struct socket *so, int q)
428 {
429 	KASSERT(q == 0 || q == 1);
430 	KASSERT(solocked2(head, so));
431 	KASSERT(so->so_onq == NULL);
432 	KASSERT(so->so_head == NULL);
433 
434 	so->so_head = head;
435 	if (q == 0) {
436 		head->so_q0len++;
437 		so->so_onq = &head->so_q0;
438 	} else {
439 		head->so_qlen++;
440 		so->so_onq = &head->so_q;
441 	}
442 	TAILQ_INSERT_TAIL(so->so_onq, so, so_qe);
443 }
444 
445 /*
446  * soqremque: remove socket from the specified queue.
447  *
448  * => Returns true if socket was removed from the specified queue.
449  * => False if socket was not removed (because it was in other queue).
450  */
451 bool
452 soqremque(struct socket *so, int q)
453 {
454 	struct socket *head = so->so_head;
455 
456 	KASSERT(q == 0 || q == 1);
457 	KASSERT(solocked(so));
458 	KASSERT(so->so_onq != NULL);
459 	KASSERT(head != NULL);
460 
461 	if (q == 0) {
462 		if (so->so_onq != &head->so_q0)
463 			return false;
464 		head->so_q0len--;
465 	} else {
466 		if (so->so_onq != &head->so_q)
467 			return false;
468 		head->so_qlen--;
469 	}
470 	KASSERT(solocked2(so, head));
471 	TAILQ_REMOVE(so->so_onq, so, so_qe);
472 	so->so_onq = NULL;
473 	so->so_head = NULL;
474 	return true;
475 }
476 
477 /*
478  * socantsendmore: indicates that no more data will be sent on the
479  * socket; it would normally be applied to a socket when the user
480  * informs the system that no more data is to be sent, by the protocol
481  * code (in case pr_shutdown()).
482  */
483 void
484 socantsendmore(struct socket *so)
485 {
486 	KASSERT(solocked(so));
487 
488 	so->so_state |= SS_CANTSENDMORE;
489 	sowwakeup(so);
490 }
491 
492 /*
493  * socantrcvmore(): indicates that no more data will be received and
494  * will normally be applied to the socket by a protocol when it detects
495  * that the peer will send no more data.  Data queued for reading in
496  * the socket may yet be read.
497  */
498 void
499 socantrcvmore(struct socket *so)
500 {
501 	KASSERT(solocked(so));
502 
503 	so->so_state |= SS_CANTRCVMORE;
504 	sorwakeup(so);
505 }
506 
507 /*
508  * soroverflow(): indicates that data was attempted to be sent
509  * but the receiving buffer overflowed.
510  */
511 void
512 soroverflow(struct socket *so)
513 {
514 	KASSERT(solocked(so));
515 
516 	so->so_rcv.sb_overflowed++;
517 	if (so->so_options & SO_RERROR)  {
518 		so->so_rerror = ENOBUFS;
519 		sorwakeup(so);
520 	}
521 }
522 
523 /*
524  * Wait for data to arrive at/drain from a socket buffer.
525  */
526 int
527 sbwait(struct sockbuf *sb)
528 {
529 	struct socket *so;
530 	kmutex_t *lock;
531 	int error;
532 
533 	so = sb->sb_so;
534 
535 	KASSERT(solocked(so));
536 
537 	sb->sb_flags |= SB_NOTIFY;
538 	lock = so->so_lock;
539 	if ((sb->sb_flags & SB_NOINTR) != 0)
540 		error = cv_timedwait(&sb->sb_cv, lock, sb->sb_timeo);
541 	else
542 		error = cv_timedwait_sig(&sb->sb_cv, lock, sb->sb_timeo);
543 	if (__predict_false(lock != atomic_load_relaxed(&so->so_lock)))
544 		solockretry(so, lock);
545 	return error;
546 }
547 
548 /*
549  * Wakeup processes waiting on a socket buffer.
550  * Do asynchronous notification via SIGIO
551  * if the socket buffer has the SB_ASYNC flag set.
552  */
553 void
554 sowakeup(struct socket *so, struct sockbuf *sb, int code)
555 {
556 	int band;
557 
558 	KASSERT(solocked(so));
559 	KASSERT(sb->sb_so == so);
560 
561 	switch (code) {
562 	case POLL_IN:
563 		band = POLLIN|POLLRDNORM;
564 		break;
565 
566 	case POLL_OUT:
567 		band = POLLOUT|POLLWRNORM;
568 		break;
569 
570 	case POLL_HUP:
571 		band = POLLHUP;
572 		break;
573 
574 	default:
575 		band = 0;
576 #ifdef DIAGNOSTIC
577 		printf("bad siginfo code %d in socket notification.\n", code);
578 #endif
579 		break;
580 	}
581 
582 	sb->sb_flags &= ~SB_NOTIFY;
583 	selnotify(&sb->sb_sel, band, NOTE_SUBMIT);
584 	cv_broadcast(&sb->sb_cv);
585 	if (sb->sb_flags & SB_ASYNC)
586 		fownsignal(so->so_pgid, SIGIO, code, band, so);
587 	if (sb->sb_flags & SB_UPCALL)
588 		(*so->so_upcall)(so, so->so_upcallarg, band, M_DONTWAIT);
589 }
590 
591 /*
592  * Reset a socket's lock pointer.  Wake all threads waiting on the
593  * socket's condition variables so that they can restart their waits
594  * using the new lock.  The existing lock must be held.
595  *
596  * Caller must have issued membar_release before this.
597  */
598 void
599 solockreset(struct socket *so, kmutex_t *lock)
600 {
601 
602 	KASSERT(solocked(so));
603 
604 	so->so_lock = lock;
605 	cv_broadcast(&so->so_snd.sb_cv);
606 	cv_broadcast(&so->so_rcv.sb_cv);
607 	cv_broadcast(&so->so_cv);
608 }
609 
610 /*
611  * Socket buffer (struct sockbuf) utility routines.
612  *
613  * Each socket contains two socket buffers: one for sending data and
614  * one for receiving data.  Each buffer contains a queue of mbufs,
615  * information about the number of mbufs and amount of data in the
616  * queue, and other fields allowing poll() statements and notification
617  * on data availability to be implemented.
618  *
619  * Data stored in a socket buffer is maintained as a list of records.
620  * Each record is a list of mbufs chained together with the m_next
621  * field.  Records are chained together with the m_nextpkt field. The upper
622  * level routine soreceive() expects the following conventions to be
623  * observed when placing information in the receive buffer:
624  *
625  * 1. If the protocol requires each message be preceded by the sender's
626  *    name, then a record containing that name must be present before
627  *    any associated data (mbuf's must be of type MT_SONAME).
628  * 2. If the protocol supports the exchange of ``access rights'' (really
629  *    just additional data associated with the message), and there are
630  *    ``rights'' to be received, then a record containing this data
631  *    should be present (mbuf's must be of type MT_CONTROL).
632  * 3. If a name or rights record exists, then it must be followed by
633  *    a data record, perhaps of zero length.
634  *
635  * Before using a new socket structure it is first necessary to reserve
636  * buffer space to the socket, by calling sbreserve().  This should commit
637  * some of the available buffer space in the system buffer pool for the
638  * socket (currently, it does nothing but enforce limits).  The space
639  * should be released by calling sbrelease() when the socket is destroyed.
640  */
641 
642 int
643 sb_max_set(u_long new_sbmax)
644 {
645 	int s;
646 
647 	if (new_sbmax < (16 * 1024))
648 		return (EINVAL);
649 
650 	s = splsoftnet();
651 	sb_max = new_sbmax;
652 	sb_max_adj = (u_quad_t)new_sbmax * MCLBYTES / (MSIZE + MCLBYTES);
653 	splx(s);
654 
655 	return (0);
656 }
657 
658 int
659 soreserve(struct socket *so, u_long sndcc, u_long rcvcc)
660 {
661 	KASSERT(so->so_pcb == NULL || solocked(so));
662 
663 	/*
664 	 * there's at least one application (a configure script of screen)
665 	 * which expects a fifo is writable even if it has "some" bytes
666 	 * in its buffer.
667 	 * so we want to make sure (hiwat - lowat) >= (some bytes).
668 	 *
669 	 * PIPE_BUF here is an arbitrary value chosen as (some bytes) above.
670 	 * we expect it's large enough for such applications.
671 	 */
672 	u_long  lowat = MAX(sock_loan_thresh, MCLBYTES);
673 	u_long  hiwat = lowat + PIPE_BUF;
674 
675 	if (sndcc < hiwat)
676 		sndcc = hiwat;
677 	if (sbreserve(&so->so_snd, sndcc, so) == 0)
678 		goto bad;
679 	if (sbreserve(&so->so_rcv, rcvcc, so) == 0)
680 		goto bad2;
681 	if (so->so_rcv.sb_lowat == 0)
682 		so->so_rcv.sb_lowat = 1;
683 	if (so->so_snd.sb_lowat == 0)
684 		so->so_snd.sb_lowat = lowat;
685 	if (so->so_snd.sb_lowat > so->so_snd.sb_hiwat)
686 		so->so_snd.sb_lowat = so->so_snd.sb_hiwat;
687 	return (0);
688  bad2:
689 	sbrelease(&so->so_snd, so);
690  bad:
691 	return (ENOBUFS);
692 }
693 
694 /*
695  * Allot mbufs to a sockbuf.
696  * Attempt to scale mbmax so that mbcnt doesn't become limiting
697  * if buffering efficiency is near the normal case.
698  */
699 int
700 sbreserve(struct sockbuf *sb, u_long cc, struct socket *so)
701 {
702 	struct lwp *l = curlwp; /* XXX */
703 	rlim_t maxcc;
704 	struct uidinfo *uidinfo;
705 
706 	KASSERT(so->so_pcb == NULL || solocked(so));
707 	KASSERT(sb->sb_so == so);
708 	KASSERT(sb_max_adj != 0);
709 
710 	if (cc == 0 || cc > sb_max_adj)
711 		return (0);
712 
713 	maxcc = l->l_proc->p_rlimit[RLIMIT_SBSIZE].rlim_cur;
714 
715 	uidinfo = so->so_uidinfo;
716 	if (!chgsbsize(uidinfo, &sb->sb_hiwat, cc, maxcc))
717 		return 0;
718 	sb->sb_mbmax = uimin(cc * 2, sb_max);
719 	if (sb->sb_lowat > sb->sb_hiwat)
720 		sb->sb_lowat = sb->sb_hiwat;
721 
722 	return (1);
723 }
724 
725 /*
726  * Free mbufs held by a socket, and reserved mbuf space.  We do not assert
727  * that the socket is held locked here: see sorflush().
728  */
729 void
730 sbrelease(struct sockbuf *sb, struct socket *so)
731 {
732 
733 	KASSERT(sb->sb_so == so);
734 
735 	sbflush(sb);
736 	(void)chgsbsize(so->so_uidinfo, &sb->sb_hiwat, 0, RLIM_INFINITY);
737 	sb->sb_mbmax = 0;
738 }
739 
740 /*
741  * Routines to add and remove
742  * data from an mbuf queue.
743  *
744  * The routines sbappend() or sbappendrecord() are normally called to
745  * append new mbufs to a socket buffer, after checking that adequate
746  * space is available, comparing the function sbspace() with the amount
747  * of data to be added.  sbappendrecord() differs from sbappend() in
748  * that data supplied is treated as the beginning of a new record.
749  * To place a sender's address, optional access rights, and data in a
750  * socket receive buffer, sbappendaddr() should be used.  To place
751  * access rights and data in a socket receive buffer, sbappendrights()
752  * should be used.  In either case, the new data begins a new record.
753  * Note that unlike sbappend() and sbappendrecord(), these routines check
754  * for the caller that there will be enough space to store the data.
755  * Each fails if there is not enough space, or if it cannot find mbufs
756  * to store additional information in.
757  *
758  * Reliable protocols may use the socket send buffer to hold data
759  * awaiting acknowledgement.  Data is normally copied from a socket
760  * send buffer in a protocol with m_copym for output to a peer,
761  * and then removing the data from the socket buffer with sbdrop()
762  * or sbdroprecord() when the data is acknowledged by the peer.
763  */
764 
765 #ifdef SOCKBUF_DEBUG
766 void
767 sblastrecordchk(struct sockbuf *sb, const char *where)
768 {
769 	struct mbuf *m = sb->sb_mb;
770 
771 	KASSERT(solocked(sb->sb_so));
772 
773 	while (m && m->m_nextpkt)
774 		m = m->m_nextpkt;
775 
776 	if (m != sb->sb_lastrecord) {
777 		printf("sblastrecordchk: sb_mb %p sb_lastrecord %p last %p\n",
778 		    sb->sb_mb, sb->sb_lastrecord, m);
779 		printf("packet chain:\n");
780 		for (m = sb->sb_mb; m != NULL; m = m->m_nextpkt)
781 			printf("\t%p\n", m);
782 		panic("sblastrecordchk from %s", where);
783 	}
784 }
785 
786 void
787 sblastmbufchk(struct sockbuf *sb, const char *where)
788 {
789 	struct mbuf *m = sb->sb_mb;
790 	struct mbuf *n;
791 
792 	KASSERT(solocked(sb->sb_so));
793 
794 	while (m && m->m_nextpkt)
795 		m = m->m_nextpkt;
796 
797 	while (m && m->m_next)
798 		m = m->m_next;
799 
800 	if (m != sb->sb_mbtail) {
801 		printf("sblastmbufchk: sb_mb %p sb_mbtail %p last %p\n",
802 		    sb->sb_mb, sb->sb_mbtail, m);
803 		printf("packet tree:\n");
804 		for (m = sb->sb_mb; m != NULL; m = m->m_nextpkt) {
805 			printf("\t");
806 			for (n = m; n != NULL; n = n->m_next)
807 				printf("%p ", n);
808 			printf("\n");
809 		}
810 		panic("sblastmbufchk from %s", where);
811 	}
812 }
813 #endif /* SOCKBUF_DEBUG */
814 
815 /*
816  * Link a chain of records onto a socket buffer
817  */
818 #define	SBLINKRECORDCHAIN(sb, m0, mlast)				\
819 do {									\
820 	if ((sb)->sb_lastrecord != NULL)				\
821 		(sb)->sb_lastrecord->m_nextpkt = (m0);			\
822 	else								\
823 		(sb)->sb_mb = (m0);					\
824 	(sb)->sb_lastrecord = (mlast);					\
825 } while (/*CONSTCOND*/0)
826 
827 
828 #define	SBLINKRECORD(sb, m0)						\
829     SBLINKRECORDCHAIN(sb, m0, m0)
830 
831 /*
832  * Append mbuf chain m to the last record in the
833  * socket buffer sb.  The additional space associated
834  * the mbuf chain is recorded in sb.  Empty mbufs are
835  * discarded and mbufs are compacted where possible.
836  */
837 void
838 sbappend(struct sockbuf *sb, struct mbuf *m)
839 {
840 	struct mbuf	*n;
841 
842 	KASSERT(solocked(sb->sb_so));
843 
844 	if (m == NULL)
845 		return;
846 
847 #ifdef MBUFTRACE
848 	m_claimm(m, sb->sb_mowner);
849 #endif
850 
851 	SBLASTRECORDCHK(sb, "sbappend 1");
852 
853 	if ((n = sb->sb_lastrecord) != NULL) {
854 		/*
855 		 * XXX Would like to simply use sb_mbtail here, but
856 		 * XXX I need to verify that I won't miss an EOR that
857 		 * XXX way.
858 		 */
859 		do {
860 			if (n->m_flags & M_EOR) {
861 				sbappendrecord(sb, m); /* XXXXXX!!!! */
862 				return;
863 			}
864 		} while (n->m_next && (n = n->m_next));
865 	} else {
866 		/*
867 		 * If this is the first record in the socket buffer, it's
868 		 * also the last record.
869 		 */
870 		sb->sb_lastrecord = m;
871 	}
872 	sbcompress(sb, m, n);
873 	SBLASTRECORDCHK(sb, "sbappend 2");
874 }
875 
876 /*
877  * This version of sbappend() should only be used when the caller
878  * absolutely knows that there will never be more than one record
879  * in the socket buffer, that is, a stream protocol (such as TCP).
880  */
881 void
882 sbappendstream(struct sockbuf *sb, struct mbuf *m)
883 {
884 
885 	KASSERT(solocked(sb->sb_so));
886 	KDASSERT(m->m_nextpkt == NULL);
887 	KASSERT(sb->sb_mb == sb->sb_lastrecord);
888 
889 	SBLASTMBUFCHK(sb, __func__);
890 
891 #ifdef MBUFTRACE
892 	m_claimm(m, sb->sb_mowner);
893 #endif
894 
895 	sbcompress(sb, m, sb->sb_mbtail);
896 
897 	sb->sb_lastrecord = sb->sb_mb;
898 	SBLASTRECORDCHK(sb, __func__);
899 }
900 
901 #ifdef SOCKBUF_DEBUG
902 void
903 sbcheck(struct sockbuf *sb)
904 {
905 	struct mbuf	*m, *m2;
906 	u_long		len, mbcnt;
907 
908 	KASSERT(solocked(sb->sb_so));
909 
910 	len = 0;
911 	mbcnt = 0;
912 	for (m = sb->sb_mb; m; m = m->m_nextpkt) {
913 		for (m2 = m; m2 != NULL; m2 = m2->m_next) {
914 			len += m2->m_len;
915 			mbcnt += MSIZE;
916 			if (m2->m_flags & M_EXT)
917 				mbcnt += m2->m_ext.ext_size;
918 			if (m2->m_nextpkt != NULL)
919 				panic("sbcheck nextpkt");
920 		}
921 	}
922 	if (len != sb->sb_cc || mbcnt != sb->sb_mbcnt) {
923 		printf("cc %lu != %lu || mbcnt %lu != %lu\n", len, sb->sb_cc,
924 		    mbcnt, sb->sb_mbcnt);
925 		panic("sbcheck");
926 	}
927 }
928 #endif
929 
930 /*
931  * As above, except the mbuf chain
932  * begins a new record.
933  */
934 void
935 sbappendrecord(struct sockbuf *sb, struct mbuf *m0)
936 {
937 	struct mbuf	*m;
938 
939 	KASSERT(solocked(sb->sb_so));
940 
941 	if (m0 == NULL)
942 		return;
943 
944 #ifdef MBUFTRACE
945 	m_claimm(m0, sb->sb_mowner);
946 #endif
947 	/*
948 	 * Put the first mbuf on the queue.
949 	 * Note this permits zero length records.
950 	 */
951 	sballoc(sb, m0);
952 	SBLASTRECORDCHK(sb, "sbappendrecord 1");
953 	SBLINKRECORD(sb, m0);
954 	m = m0->m_next;
955 	m0->m_next = 0;
956 	if (m && (m0->m_flags & M_EOR)) {
957 		m0->m_flags &= ~M_EOR;
958 		m->m_flags |= M_EOR;
959 	}
960 	sbcompress(sb, m, m0);
961 	SBLASTRECORDCHK(sb, "sbappendrecord 2");
962 }
963 
964 /*
965  * As above except that OOB data
966  * is inserted at the beginning of the sockbuf,
967  * but after any other OOB data.
968  */
969 void
970 sbinsertoob(struct sockbuf *sb, struct mbuf *m0)
971 {
972 	struct mbuf	*m, **mp;
973 
974 	KASSERT(solocked(sb->sb_so));
975 
976 	if (m0 == NULL)
977 		return;
978 
979 	SBLASTRECORDCHK(sb, "sbinsertoob 1");
980 
981 	for (mp = &sb->sb_mb; (m = *mp) != NULL; mp = &((*mp)->m_nextpkt)) {
982 	    again:
983 		switch (m->m_type) {
984 
985 		case MT_OOBDATA:
986 			continue;		/* WANT next train */
987 
988 		case MT_CONTROL:
989 			if ((m = m->m_next) != NULL)
990 				goto again;	/* inspect THIS train further */
991 		}
992 		break;
993 	}
994 	/*
995 	 * Put the first mbuf on the queue.
996 	 * Note this permits zero length records.
997 	 */
998 	sballoc(sb, m0);
999 	m0->m_nextpkt = *mp;
1000 	if (*mp == NULL) {
1001 		/* m0 is actually the new tail */
1002 		sb->sb_lastrecord = m0;
1003 	}
1004 	*mp = m0;
1005 	m = m0->m_next;
1006 	m0->m_next = 0;
1007 	if (m && (m0->m_flags & M_EOR)) {
1008 		m0->m_flags &= ~M_EOR;
1009 		m->m_flags |= M_EOR;
1010 	}
1011 	sbcompress(sb, m, m0);
1012 	SBLASTRECORDCHK(sb, "sbinsertoob 2");
1013 }
1014 
1015 /*
1016  * Append address and data, and optionally, control (ancillary) data
1017  * to the receive queue of a socket.  If present,
1018  * m0 must include a packet header with total length.
1019  * Returns 0 if no space in sockbuf or insufficient mbufs.
1020  */
1021 int
1022 sbappendaddr(struct sockbuf *sb, const struct sockaddr *asa, struct mbuf *m0,
1023 	struct mbuf *control)
1024 {
1025 	struct mbuf	*m, *n, *nlast;
1026 	int		space, len;
1027 
1028 	KASSERT(solocked(sb->sb_so));
1029 
1030 	space = asa->sa_len;
1031 
1032 	if (m0 != NULL) {
1033 		if ((m0->m_flags & M_PKTHDR) == 0)
1034 			panic("sbappendaddr");
1035 		space += m0->m_pkthdr.len;
1036 #ifdef MBUFTRACE
1037 		m_claimm(m0, sb->sb_mowner);
1038 #endif
1039 	}
1040 	for (n = control; n; n = n->m_next) {
1041 		space += n->m_len;
1042 		MCLAIM(n, sb->sb_mowner);
1043 		if (n->m_next == NULL)	/* keep pointer to last control buf */
1044 			break;
1045 	}
1046 	if (space > sbspace(sb))
1047 		return (0);
1048 	m = m_get(M_DONTWAIT, MT_SONAME);
1049 	if (m == NULL)
1050 		return (0);
1051 	MCLAIM(m, sb->sb_mowner);
1052 	/*
1053 	 * XXX avoid 'comparison always true' warning which isn't easily
1054 	 * avoided.
1055 	 */
1056 	len = asa->sa_len;
1057 	if (len > MLEN) {
1058 		MEXTMALLOC(m, asa->sa_len, M_NOWAIT);
1059 		if ((m->m_flags & M_EXT) == 0) {
1060 			m_free(m);
1061 			return (0);
1062 		}
1063 	}
1064 	m->m_len = asa->sa_len;
1065 	memcpy(mtod(m, void *), asa, asa->sa_len);
1066 	if (n)
1067 		n->m_next = m0;		/* concatenate data to control */
1068 	else
1069 		control = m0;
1070 	m->m_next = control;
1071 
1072 	SBLASTRECORDCHK(sb, "sbappendaddr 1");
1073 
1074 	for (n = m; n->m_next != NULL; n = n->m_next)
1075 		sballoc(sb, n);
1076 	sballoc(sb, n);
1077 	nlast = n;
1078 	SBLINKRECORD(sb, m);
1079 
1080 	sb->sb_mbtail = nlast;
1081 	SBLASTMBUFCHK(sb, "sbappendaddr");
1082 	SBLASTRECORDCHK(sb, "sbappendaddr 2");
1083 
1084 	return (1);
1085 }
1086 
1087 /*
1088  * Helper for sbappendchainaddr: prepend a struct sockaddr* to
1089  * an mbuf chain.
1090  */
1091 static inline struct mbuf *
1092 m_prepend_sockaddr(struct sockbuf *sb, struct mbuf *m0,
1093 		   const struct sockaddr *asa)
1094 {
1095 	struct mbuf *m;
1096 	const int salen = asa->sa_len;
1097 
1098 	KASSERT(solocked(sb->sb_so));
1099 
1100 	/* only the first in each chain need be a pkthdr */
1101 	m = m_gethdr(M_DONTWAIT, MT_SONAME);
1102 	if (m == NULL)
1103 		return NULL;
1104 	MCLAIM(m, sb->sb_mowner);
1105 #ifdef notyet
1106 	if (salen > MHLEN) {
1107 		MEXTMALLOC(m, salen, M_NOWAIT);
1108 		if ((m->m_flags & M_EXT) == 0) {
1109 			m_free(m);
1110 			return NULL;
1111 		}
1112 	}
1113 #else
1114 	KASSERT(salen <= MHLEN);
1115 #endif
1116 	m->m_len = salen;
1117 	memcpy(mtod(m, void *), asa, salen);
1118 	m->m_next = m0;
1119 	m->m_pkthdr.len = salen + m0->m_pkthdr.len;
1120 
1121 	return m;
1122 }
1123 
1124 int
1125 sbappendaddrchain(struct sockbuf *sb, const struct sockaddr *asa,
1126 		  struct mbuf *m0, int sbprio)
1127 {
1128 	struct mbuf *m, *n, *n0, *nlast;
1129 	int error;
1130 
1131 	KASSERT(solocked(sb->sb_so));
1132 
1133 	/*
1134 	 * XXX sbprio reserved for encoding priority of this* request:
1135 	 *  SB_PRIO_NONE --> honour normal sb limits
1136 	 *  SB_PRIO_ONESHOT_OVERFLOW --> if socket has any space,
1137 	 *	take whole chain. Intended for large requests
1138 	 *      that should be delivered atomically (all, or none).
1139 	 * SB_PRIO_OVERDRAFT -- allow a small (2*MLEN) overflow
1140 	 *       over normal socket limits, for messages indicating
1141 	 *       buffer overflow in earlier normal/lower-priority messages
1142 	 * SB_PRIO_BESTEFFORT -->  ignore limits entirely.
1143 	 *       Intended for  kernel-generated messages only.
1144 	 *        Up to generator to avoid total mbuf resource exhaustion.
1145 	 */
1146 	(void)sbprio;
1147 
1148 	if (m0 && (m0->m_flags & M_PKTHDR) == 0)
1149 		panic("sbappendaddrchain");
1150 
1151 #ifdef notyet
1152 	space = sbspace(sb);
1153 
1154 	/*
1155 	 * Enforce SB_PRIO_* limits as described above.
1156 	 */
1157 #endif
1158 
1159 	n0 = NULL;
1160 	nlast = NULL;
1161 	for (m = m0; m; m = m->m_nextpkt) {
1162 		struct mbuf *np;
1163 
1164 #ifdef MBUFTRACE
1165 		m_claimm(m, sb->sb_mowner);
1166 #endif
1167 
1168 		/* Prepend sockaddr to this record (m) of input chain m0 */
1169 	  	n = m_prepend_sockaddr(sb, m, asa);
1170 		if (n == NULL) {
1171 			error = ENOBUFS;
1172 			goto bad;
1173 		}
1174 
1175 		/* Append record (asa+m) to end of new chain n0 */
1176 		if (n0 == NULL) {
1177 			n0 = n;
1178 		} else {
1179 			nlast->m_nextpkt = n;
1180 		}
1181 		/* Keep track of last record on new chain */
1182 		nlast = n;
1183 
1184 		for (np = n; np; np = np->m_next)
1185 			sballoc(sb, np);
1186 	}
1187 
1188 	SBLASTRECORDCHK(sb, "sbappendaddrchain 1");
1189 
1190 	/* Drop the entire chain of (asa+m) records onto the socket */
1191 	SBLINKRECORDCHAIN(sb, n0, nlast);
1192 
1193 	SBLASTRECORDCHK(sb, "sbappendaddrchain 2");
1194 
1195 	for (m = nlast; m->m_next; m = m->m_next)
1196 		;
1197 	sb->sb_mbtail = m;
1198 	SBLASTMBUFCHK(sb, "sbappendaddrchain");
1199 
1200 	return (1);
1201 
1202 bad:
1203 	/*
1204 	 * On error, free the prepended addreseses. For consistency
1205 	 * with sbappendaddr(), leave it to our caller to free
1206 	 * the input record chain passed to us as m0.
1207 	 */
1208 	while ((n = n0) != NULL) {
1209 	  	struct mbuf *np;
1210 
1211 		/* Undo the sballoc() of this record */
1212 		for (np = n; np; np = np->m_next)
1213 			sbfree(sb, np);
1214 
1215 		n0 = n->m_nextpkt;	/* iterate at next prepended address */
1216 		np = m_free(n);		/* free prepended address (not data) */
1217 	}
1218 	return error;
1219 }
1220 
1221 
1222 int
1223 sbappendcontrol(struct sockbuf *sb, struct mbuf *m0, struct mbuf *control)
1224 {
1225 	struct mbuf	*m, *mlast, *n;
1226 	int		space;
1227 
1228 	KASSERT(solocked(sb->sb_so));
1229 
1230 	space = 0;
1231 	if (control == NULL)
1232 		panic("sbappendcontrol");
1233 	for (m = control; ; m = m->m_next) {
1234 		space += m->m_len;
1235 		MCLAIM(m, sb->sb_mowner);
1236 		if (m->m_next == NULL)
1237 			break;
1238 	}
1239 	n = m;			/* save pointer to last control buffer */
1240 	for (m = m0; m; m = m->m_next) {
1241 		MCLAIM(m, sb->sb_mowner);
1242 		space += m->m_len;
1243 	}
1244 	if (space > sbspace(sb))
1245 		return (0);
1246 	n->m_next = m0;			/* concatenate data to control */
1247 
1248 	SBLASTRECORDCHK(sb, "sbappendcontrol 1");
1249 
1250 	for (m = control; m->m_next != NULL; m = m->m_next)
1251 		sballoc(sb, m);
1252 	sballoc(sb, m);
1253 	mlast = m;
1254 	SBLINKRECORD(sb, control);
1255 
1256 	sb->sb_mbtail = mlast;
1257 	SBLASTMBUFCHK(sb, "sbappendcontrol");
1258 	SBLASTRECORDCHK(sb, "sbappendcontrol 2");
1259 
1260 	return (1);
1261 }
1262 
1263 /*
1264  * Compress mbuf chain m into the socket
1265  * buffer sb following mbuf n.  If n
1266  * is null, the buffer is presumed empty.
1267  */
1268 void
1269 sbcompress(struct sockbuf *sb, struct mbuf *m, struct mbuf *n)
1270 {
1271 	int		eor;
1272 	struct mbuf	*o;
1273 
1274 	KASSERT(solocked(sb->sb_so));
1275 
1276 	eor = 0;
1277 	while (m) {
1278 		eor |= m->m_flags & M_EOR;
1279 		if (m->m_len == 0 &&
1280 		    (eor == 0 ||
1281 		     (((o = m->m_next) || (o = n)) &&
1282 		      o->m_type == m->m_type))) {
1283 			if (sb->sb_lastrecord == m)
1284 				sb->sb_lastrecord = m->m_next;
1285 			m = m_free(m);
1286 			continue;
1287 		}
1288 		if (n && (n->m_flags & M_EOR) == 0 &&
1289 		    /* M_TRAILINGSPACE() checks buffer writeability */
1290 		    m->m_len <= MCLBYTES / 4 && /* XXX Don't copy too much */
1291 		    m->m_len <= M_TRAILINGSPACE(n) &&
1292 		    n->m_type == m->m_type) {
1293 			memcpy(mtod(n, char *) + n->m_len, mtod(m, void *),
1294 			    (unsigned)m->m_len);
1295 			n->m_len += m->m_len;
1296 			sb->sb_cc += m->m_len;
1297 			m = m_free(m);
1298 			continue;
1299 		}
1300 		if (n)
1301 			n->m_next = m;
1302 		else
1303 			sb->sb_mb = m;
1304 		sb->sb_mbtail = m;
1305 		sballoc(sb, m);
1306 		n = m;
1307 		m->m_flags &= ~M_EOR;
1308 		m = m->m_next;
1309 		n->m_next = 0;
1310 	}
1311 	if (eor) {
1312 		if (n)
1313 			n->m_flags |= eor;
1314 		else
1315 			printf("semi-panic: sbcompress\n");
1316 	}
1317 	SBLASTMBUFCHK(sb, __func__);
1318 }
1319 
1320 /*
1321  * Free all mbufs in a sockbuf.
1322  * Check that all resources are reclaimed.
1323  */
1324 void
1325 sbflush(struct sockbuf *sb)
1326 {
1327 
1328 	KASSERT(solocked(sb->sb_so));
1329 	KASSERT((sb->sb_flags & SB_LOCK) == 0);
1330 
1331 	while (sb->sb_mbcnt)
1332 		sbdrop(sb, (int)sb->sb_cc);
1333 
1334 	KASSERT(sb->sb_cc == 0);
1335 	KASSERT(sb->sb_mb == NULL);
1336 	KASSERT(sb->sb_mbtail == NULL);
1337 	KASSERT(sb->sb_lastrecord == NULL);
1338 }
1339 
1340 /*
1341  * Drop data from (the front of) a sockbuf.
1342  */
1343 void
1344 sbdrop(struct sockbuf *sb, int len)
1345 {
1346 	struct mbuf	*m, *next;
1347 
1348 	KASSERT(solocked(sb->sb_so));
1349 
1350 	next = (m = sb->sb_mb) ? m->m_nextpkt : NULL;
1351 	while (len > 0) {
1352 		if (m == NULL) {
1353 			if (next == NULL)
1354 				panic("sbdrop(%p,%d): cc=%lu",
1355 				    sb, len, sb->sb_cc);
1356 			m = next;
1357 			next = m->m_nextpkt;
1358 			continue;
1359 		}
1360 		if (m->m_len > len) {
1361 			m->m_len -= len;
1362 			m->m_data += len;
1363 			sb->sb_cc -= len;
1364 			break;
1365 		}
1366 		len -= m->m_len;
1367 		sbfree(sb, m);
1368 		m = m_free(m);
1369 	}
1370 	while (m && m->m_len == 0) {
1371 		sbfree(sb, m);
1372 		m = m_free(m);
1373 	}
1374 	if (m) {
1375 		sb->sb_mb = m;
1376 		m->m_nextpkt = next;
1377 	} else
1378 		sb->sb_mb = next;
1379 	/*
1380 	 * First part is an inline SB_EMPTY_FIXUP().  Second part
1381 	 * makes sure sb_lastrecord is up-to-date if we dropped
1382 	 * part of the last record.
1383 	 */
1384 	m = sb->sb_mb;
1385 	if (m == NULL) {
1386 		sb->sb_mbtail = NULL;
1387 		sb->sb_lastrecord = NULL;
1388 	} else if (m->m_nextpkt == NULL)
1389 		sb->sb_lastrecord = m;
1390 }
1391 
1392 /*
1393  * Drop a record off the front of a sockbuf
1394  * and move the next record to the front.
1395  */
1396 void
1397 sbdroprecord(struct sockbuf *sb)
1398 {
1399 	struct mbuf	*m, *mn;
1400 
1401 	KASSERT(solocked(sb->sb_so));
1402 
1403 	m = sb->sb_mb;
1404 	if (m) {
1405 		sb->sb_mb = m->m_nextpkt;
1406 		do {
1407 			sbfree(sb, m);
1408 			mn = m_free(m);
1409 		} while ((m = mn) != NULL);
1410 	}
1411 	SB_EMPTY_FIXUP(sb);
1412 }
1413 
1414 /*
1415  * Create a "control" mbuf containing the specified data
1416  * with the specified type for presentation on a socket buffer.
1417  */
1418 struct mbuf *
1419 sbcreatecontrol1(void **p, int size, int type, int level, int flags)
1420 {
1421 	struct cmsghdr	*cp;
1422 	struct mbuf	*m;
1423 	int space = CMSG_SPACE(size);
1424 
1425 	if ((flags & M_DONTWAIT) && space > MCLBYTES) {
1426 		printf("%s: message too large %d\n", __func__, space);
1427 		return NULL;
1428 	}
1429 
1430 	if ((m = m_get(flags, MT_CONTROL)) == NULL)
1431 		return NULL;
1432 	if (space > MLEN) {
1433 		if (space > MCLBYTES)
1434 			MEXTMALLOC(m, space, M_WAITOK);
1435 		else
1436 			MCLGET(m, flags);
1437 		if ((m->m_flags & M_EXT) == 0) {
1438 			m_free(m);
1439 			return NULL;
1440 		}
1441 	}
1442 	cp = mtod(m, struct cmsghdr *);
1443 	*p = CMSG_DATA(cp);
1444 	m->m_len = space;
1445 	cp->cmsg_len = CMSG_LEN(size);
1446 	cp->cmsg_level = level;
1447 	cp->cmsg_type = type;
1448 
1449 	memset(cp + 1, 0, CMSG_LEN(0) - sizeof(*cp));
1450 	memset((uint8_t *)*p + size, 0, CMSG_ALIGN(size) - size);
1451 
1452 	return m;
1453 }
1454 
1455 struct mbuf *
1456 sbcreatecontrol(void *p, int size, int type, int level)
1457 {
1458 	struct mbuf *m;
1459 	void *v;
1460 
1461 	m = sbcreatecontrol1(&v, size, type, level, M_DONTWAIT);
1462 	if (m == NULL)
1463 		return NULL;
1464 	memcpy(v, p, size);
1465 	return m;
1466 }
1467 
1468 void
1469 solockretry(struct socket *so, kmutex_t *lock)
1470 {
1471 
1472 	while (lock != atomic_load_relaxed(&so->so_lock)) {
1473 		mutex_exit(lock);
1474 		lock = atomic_load_consume(&so->so_lock);
1475 		mutex_enter(lock);
1476 	}
1477 }
1478 
1479 bool
1480 solocked(const struct socket *so)
1481 {
1482 
1483 	/*
1484 	 * Used only for diagnostic assertions, so so_lock should be
1485 	 * stable at this point, hence on need for atomic_load_*.
1486 	 */
1487 	return mutex_owned(so->so_lock);
1488 }
1489 
1490 bool
1491 solocked2(const struct socket *so1, const struct socket *so2)
1492 {
1493 	const kmutex_t *lock;
1494 
1495 	/*
1496 	 * Used only for diagnostic assertions, so so_lock should be
1497 	 * stable at this point, hence on need for atomic_load_*.
1498 	 */
1499 	lock = so1->so_lock;
1500 	if (lock != so2->so_lock)
1501 		return false;
1502 	return mutex_owned(lock);
1503 }
1504 
1505 /*
1506  * sosetlock: assign a default lock to a new socket.
1507  */
1508 void
1509 sosetlock(struct socket *so)
1510 {
1511 	if (so->so_lock == NULL) {
1512 		kmutex_t *lock = softnet_lock;
1513 
1514 		so->so_lock = lock;
1515 		mutex_obj_hold(lock);
1516 		mutex_enter(lock);
1517 	}
1518 	KASSERT(solocked(so));
1519 }
1520 
1521 /*
1522  * Set lock on sockbuf sb; sleep if lock is already held.
1523  * Unless SB_NOINTR is set on sockbuf, sleep is interruptible.
1524  * Returns error without lock if sleep is interrupted.
1525  */
1526 int
1527 sblock(struct sockbuf *sb, int wf)
1528 {
1529 	struct socket *so;
1530 	kmutex_t *lock;
1531 	int error;
1532 
1533 	KASSERT(solocked(sb->sb_so));
1534 
1535 	for (;;) {
1536 		if (__predict_true((sb->sb_flags & SB_LOCK) == 0)) {
1537 			sb->sb_flags |= SB_LOCK;
1538 			return 0;
1539 		}
1540 		if (wf != M_WAITOK)
1541 			return EWOULDBLOCK;
1542 		so = sb->sb_so;
1543 		lock = so->so_lock;
1544 		if ((sb->sb_flags & SB_NOINTR) != 0) {
1545 			cv_wait(&so->so_cv, lock);
1546 			error = 0;
1547 		} else
1548 			error = cv_wait_sig(&so->so_cv, lock);
1549 		if (__predict_false(lock != atomic_load_relaxed(&so->so_lock)))
1550 			solockretry(so, lock);
1551 		if (error != 0)
1552 			return error;
1553 	}
1554 }
1555 
1556 void
1557 sbunlock(struct sockbuf *sb)
1558 {
1559 	struct socket *so;
1560 
1561 	so = sb->sb_so;
1562 
1563 	KASSERT(solocked(so));
1564 	KASSERT((sb->sb_flags & SB_LOCK) != 0);
1565 
1566 	sb->sb_flags &= ~SB_LOCK;
1567 	cv_broadcast(&so->so_cv);
1568 }
1569 
1570 int
1571 sowait(struct socket *so, bool catch_p, int timo)
1572 {
1573 	kmutex_t *lock;
1574 	int error;
1575 
1576 	KASSERT(solocked(so));
1577 	KASSERT(catch_p || timo != 0);
1578 
1579 	lock = so->so_lock;
1580 	if (catch_p)
1581 		error = cv_timedwait_sig(&so->so_cv, lock, timo);
1582 	else
1583 		error = cv_timedwait(&so->so_cv, lock, timo);
1584 	if (__predict_false(lock != atomic_load_relaxed(&so->so_lock)))
1585 		solockretry(so, lock);
1586 	return error;
1587 }
1588 
1589 #ifdef DDB
1590 
1591 /*
1592  * Currently, sofindproc() is used only from DDB. It could be used from others
1593  * by using db_mutex_enter()
1594  */
1595 
1596 static inline int
1597 db_mutex_enter(kmutex_t *mtx)
1598 {
1599 	extern int db_active;
1600 	int rv;
1601 
1602 	if (!db_active) {
1603 		mutex_enter(mtx);
1604 		rv = 1;
1605 	} else
1606 		rv = mutex_tryenter(mtx);
1607 
1608 	return rv;
1609 }
1610 
1611 int
1612 sofindproc(struct socket *so, int all, void (*pr)(const char *, ...))
1613 {
1614 	proc_t *p;
1615 	filedesc_t *fdp;
1616 	fdtab_t *dt;
1617 	fdfile_t *ff;
1618 	file_t *fp = NULL;
1619 	int found = 0;
1620 	int i, t;
1621 
1622 	if (so == NULL)
1623 		return 0;
1624 
1625 	t = db_mutex_enter(&proc_lock);
1626 	if (!t) {
1627 		pr("could not acquire proc_lock mutex\n");
1628 		return 0;
1629 	}
1630 	PROCLIST_FOREACH(p, &allproc) {
1631 		if (p->p_stat == SIDL)
1632 			continue;
1633 		fdp = p->p_fd;
1634 		t = db_mutex_enter(&fdp->fd_lock);
1635 		if (!t) {
1636 			pr("could not acquire fd_lock mutex\n");
1637 			continue;
1638 		}
1639 		dt = atomic_load_consume(&fdp->fd_dt);
1640 		for (i = 0; i < dt->dt_nfiles; i++) {
1641 			ff = dt->dt_ff[i];
1642 			if (ff == NULL)
1643 				continue;
1644 
1645 			fp = atomic_load_consume(&ff->ff_file);
1646 			if (fp == NULL)
1647 				continue;
1648 
1649 			t = db_mutex_enter(&fp->f_lock);
1650 			if (!t) {
1651 				pr("could not acquire f_lock mutex\n");
1652 				continue;
1653 			}
1654 			if ((struct socket *)fp->f_data != so) {
1655 				mutex_exit(&fp->f_lock);
1656 				continue;
1657 			}
1658 			found++;
1659 			if (pr)
1660 				pr("socket %p: owner %s(pid=%d)\n",
1661 				    so, p->p_comm, p->p_pid);
1662 			mutex_exit(&fp->f_lock);
1663 			if (all == 0)
1664 				break;
1665 		}
1666 		mutex_exit(&fdp->fd_lock);
1667 		if (all == 0 && found != 0)
1668 			break;
1669 	}
1670 	mutex_exit(&proc_lock);
1671 
1672 	return found;
1673 }
1674 
1675 void
1676 socket_print(const char *modif, void (*pr)(const char *, ...))
1677 {
1678 	file_t *fp;
1679 	struct socket *so;
1680 	struct sockbuf *sb_snd, *sb_rcv;
1681 	struct mbuf *m_rec, *m;
1682 	bool opt_v = false;
1683 	bool opt_m = false;
1684 	bool opt_a = false;
1685 	bool opt_p = false;
1686 	int nrecs, nmbufs;
1687 	char ch;
1688 	const char *family;
1689 
1690 	while ( (ch = *(modif++)) != '\0') {
1691 		switch (ch) {
1692 		case 'v':
1693 			opt_v = true;
1694 			break;
1695 		case 'm':
1696 			opt_m = true;
1697 			break;
1698 		case 'a':
1699 			opt_a = true;
1700 			break;
1701 		case 'p':
1702 			opt_p = true;
1703 			break;
1704 		}
1705 	}
1706 	if (opt_v == false && pr)
1707 		(pr)("Ignore empty sockets. use /v to print all.\n");
1708 	if (opt_p == true && pr)
1709 		(pr)("Don't search owner process.\n");
1710 
1711 	LIST_FOREACH(fp, &filehead, f_list) {
1712 		if (fp->f_type != DTYPE_SOCKET)
1713 			continue;
1714 		so = (struct socket *)fp->f_data;
1715 		if (so == NULL)
1716 			continue;
1717 
1718 		if (so->so_proto->pr_domain->dom_family == AF_INET)
1719 			family = "INET";
1720 #ifdef INET6
1721 		else if (so->so_proto->pr_domain->dom_family == AF_INET6)
1722 			family = "INET6";
1723 #endif
1724 		else if (so->so_proto->pr_domain->dom_family == pseudo_AF_KEY)
1725 			family = "KEY";
1726 		else if (so->so_proto->pr_domain->dom_family == AF_ROUTE)
1727 			family = "ROUTE";
1728 		else
1729 			continue;
1730 
1731 		sb_snd = &so->so_snd;
1732 		sb_rcv = &so->so_rcv;
1733 
1734 		if (opt_v != true &&
1735 		    sb_snd->sb_cc == 0 && sb_rcv->sb_cc == 0)
1736 			continue;
1737 
1738 		pr("---SOCKET %p: type %s\n", so, family);
1739 		if (opt_p != true)
1740 			sofindproc(so, opt_a == true ? 1 : 0, pr);
1741 		pr("Send Buffer Bytes: %d [bytes]\n", sb_snd->sb_cc);
1742 		pr("Send Buffer mbufs:\n");
1743 		m_rec = m = sb_snd->sb_mb;
1744 		nrecs = 0;
1745 		nmbufs = 0;
1746 		while (m_rec) {
1747 			nrecs++;
1748 			if (opt_m == true)
1749 				pr(" mbuf chain %p\n", m_rec);
1750 			while (m) {
1751 				nmbufs++;
1752 				m = m->m_next;
1753 			}
1754 			m_rec = m = m_rec->m_nextpkt;
1755 		}
1756 		pr(" Total %d records, %d mbufs.\n", nrecs, nmbufs);
1757 
1758 		pr("Recv Buffer Usage: %d [bytes]\n", sb_rcv->sb_cc);
1759 		pr("Recv Buffer mbufs:\n");
1760 		m_rec = m = sb_rcv->sb_mb;
1761 		nrecs = 0;
1762 		nmbufs = 0;
1763 		while (m_rec) {
1764 			nrecs++;
1765 			if (opt_m == true)
1766 				pr(" mbuf chain %p\n", m_rec);
1767 			while (m) {
1768 				nmbufs++;
1769 				m = m->m_next;
1770 			}
1771 			m_rec = m = m_rec->m_nextpkt;
1772 		}
1773 		pr(" Total %d records, %d mbufs.\n", nrecs, nmbufs);
1774 	}
1775 }
1776 #endif /* DDB */
1777