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