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