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