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