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