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