Home | History | Annotate | Line # | Download | only in kern
uipc_socket2.c revision 1.84
      1 /*	$NetBSD: uipc_socket2.c,v 1.84 2007/07/04 07:17:11 tls Exp $	*/
      2 
      3 /*
      4  * Copyright (c) 1982, 1986, 1988, 1990, 1993
      5  *	The Regents of the University of California.  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  * 3. Neither the name of the University nor the names of its contributors
     16  *    may be used to endorse or promote products derived from this software
     17  *    without specific prior written permission.
     18  *
     19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     29  * SUCH DAMAGE.
     30  *
     31  *	@(#)uipc_socket2.c	8.2 (Berkeley) 2/14/95
     32  */
     33 
     34 #include <sys/cdefs.h>
     35 __KERNEL_RCSID(0, "$NetBSD: uipc_socket2.c,v 1.84 2007/07/04 07:17:11 tls Exp $");
     36 
     37 #include "opt_mbuftrace.h"
     38 #include "opt_sb_max.h"
     39 
     40 #include <sys/param.h>
     41 #include <sys/systm.h>
     42 #include <sys/proc.h>
     43 #include <sys/file.h>
     44 #include <sys/buf.h>
     45 #include <sys/malloc.h>
     46 #include <sys/mbuf.h>
     47 #include <sys/protosw.h>
     48 #include <sys/poll.h>
     49 #include <sys/socket.h>
     50 #include <sys/socketvar.h>
     51 #include <sys/signalvar.h>
     52 #include <sys/kauth.h>
     53 
     54 /*
     55  * Primitive routines for operating on sockets and socket buffers
     56  */
     57 
     58 /* strings for sleep message: */
     59 const char	netcon[] = "netcon";
     60 const char	netcls[] = "netcls";
     61 const char	netio[] = "netio";
     62 const char	netlck[] = "netlck";
     63 
     64 u_long	sb_max = SB_MAX;	/* maximum socket buffer size */
     65 static u_long sb_max_adj;	/* adjusted sb_max */
     66 
     67 /*
     68  * Procedures to manipulate state flags of socket
     69  * and do appropriate wakeups.  Normal sequence from the
     70  * active (originating) side is that soisconnecting() is
     71  * called during processing of connect() call,
     72  * resulting in an eventual call to soisconnected() if/when the
     73  * connection is established.  When the connection is torn down
     74  * soisdisconnecting() is called during processing of disconnect() call,
     75  * and soisdisconnected() is called when the connection to the peer
     76  * is totally severed.  The semantics of these routines are such that
     77  * connectionless protocols can call soisconnected() and soisdisconnected()
     78  * only, bypassing the in-progress calls when setting up a ``connection''
     79  * takes no time.
     80  *
     81  * From the passive side, a socket is created with
     82  * two queues of sockets: so_q0 for connections in progress
     83  * and so_q for connections already made and awaiting user acceptance.
     84  * As a protocol is preparing incoming connections, it creates a socket
     85  * structure queued on so_q0 by calling sonewconn().  When the connection
     86  * is established, soisconnected() is called, and transfers the
     87  * socket structure to so_q, making it available to accept().
     88  *
     89  * If a socket is closed with sockets on either
     90  * so_q0 or so_q, these sockets are dropped.
     91  *
     92  * If higher level protocols are implemented in
     93  * the kernel, the wakeups done here will sometimes
     94  * cause software-interrupt process scheduling.
     95  */
     96 
     97 void
     98 soisconnecting(struct socket *so)
     99 {
    100 
    101 	so->so_state &= ~(SS_ISCONNECTED|SS_ISDISCONNECTING);
    102 	so->so_state |= SS_ISCONNECTING;
    103 }
    104 
    105 void
    106 soisconnected(struct socket *so)
    107 {
    108 	struct socket	*head;
    109 
    110 	head = so->so_head;
    111 	so->so_state &= ~(SS_ISCONNECTING|SS_ISDISCONNECTING|SS_ISCONFIRMING);
    112 	so->so_state |= SS_ISCONNECTED;
    113 	if (head && soqremque(so, 0)) {
    114 		soqinsque(head, so, 1);
    115 		sorwakeup(head);
    116 		wakeup((void *)&head->so_timeo);
    117 	} else {
    118 		wakeup((void *)&so->so_timeo);
    119 		sorwakeup(so);
    120 		sowwakeup(so);
    121 	}
    122 }
    123 
    124 void
    125 soisdisconnecting(struct socket *so)
    126 {
    127 
    128 	so->so_state &= ~SS_ISCONNECTING;
    129 	so->so_state |= (SS_ISDISCONNECTING|SS_CANTRCVMORE|SS_CANTSENDMORE);
    130 	wakeup((void *)&so->so_timeo);
    131 	sowwakeup(so);
    132 	sorwakeup(so);
    133 }
    134 
    135 void
    136 soisdisconnected(struct socket *so)
    137 {
    138 
    139 	so->so_state &= ~(SS_ISCONNECTING|SS_ISCONNECTED|SS_ISDISCONNECTING);
    140 	so->so_state |= (SS_CANTRCVMORE|SS_CANTSENDMORE|SS_ISDISCONNECTED);
    141 	wakeup((void *)&so->so_timeo);
    142 	sowwakeup(so);
    143 	sorwakeup(so);
    144 }
    145 
    146 /*
    147  * When an attempt at a new connection is noted on a socket
    148  * which accepts connections, sonewconn is called.  If the
    149  * connection is possible (subject to space constraints, etc.)
    150  * then we allocate a new structure, propoerly linked into the
    151  * data structure of the original socket, and return this.
    152  * Connstatus may be 0, SS_ISCONFIRMING, or SS_ISCONNECTED.
    153  */
    154 struct socket *
    155 sonewconn(struct socket *head, int connstatus)
    156 {
    157 	struct socket	*so;
    158 	int		soqueue;
    159 
    160 	soqueue = connstatus ? 1 : 0;
    161 	if (head->so_qlen + head->so_q0len > 3 * head->so_qlimit / 2)
    162 		return ((struct socket *)0);
    163 	so = pool_get(&socket_pool, PR_NOWAIT);
    164 	if (so == NULL)
    165 		return (NULL);
    166 	memset((void *)so, 0, sizeof(*so));
    167 	so->so_type = head->so_type;
    168 	so->so_options = head->so_options &~ SO_ACCEPTCONN;
    169 	so->so_linger = head->so_linger;
    170 	so->so_state = head->so_state | SS_NOFDREF;
    171 	so->so_proto = head->so_proto;
    172 	so->so_timeo = head->so_timeo;
    173 	so->so_pgid = head->so_pgid;
    174 	so->so_send = head->so_send;
    175 	so->so_receive = head->so_receive;
    176 	so->so_uidinfo = head->so_uidinfo;
    177 #ifdef MBUFTRACE
    178 	so->so_mowner = head->so_mowner;
    179 	so->so_rcv.sb_mowner = head->so_rcv.sb_mowner;
    180 	so->so_snd.sb_mowner = head->so_snd.sb_mowner;
    181 #endif
    182 	(void) soreserve(so, head->so_snd.sb_hiwat, head->so_rcv.sb_hiwat);
    183 	so->so_snd.sb_lowat = head->so_snd.sb_lowat;
    184 	so->so_rcv.sb_lowat = head->so_rcv.sb_lowat;
    185 	so->so_rcv.sb_timeo = head->so_rcv.sb_timeo;
    186 	so->so_snd.sb_timeo = head->so_snd.sb_timeo;
    187 	soqinsque(head, so, soqueue);
    188 	if ((*so->so_proto->pr_usrreq)(so, PRU_ATTACH,
    189 	    (struct mbuf *)0, (struct mbuf *)0, (struct mbuf *)0,
    190 	    (struct lwp *)0)) {
    191 		(void) soqremque(so, soqueue);
    192 		pool_put(&socket_pool, so);
    193 		return (NULL);
    194 	}
    195 	if (connstatus) {
    196 		sorwakeup(head);
    197 		wakeup((void *)&head->so_timeo);
    198 		so->so_state |= connstatus;
    199 	}
    200 	return (so);
    201 }
    202 
    203 void
    204 soqinsque(struct socket *head, struct socket *so, int q)
    205 {
    206 
    207 #ifdef DIAGNOSTIC
    208 	if (so->so_onq != NULL)
    209 		panic("soqinsque");
    210 #endif
    211 
    212 	so->so_head = head;
    213 	if (q == 0) {
    214 		head->so_q0len++;
    215 		so->so_onq = &head->so_q0;
    216 	} else {
    217 		head->so_qlen++;
    218 		so->so_onq = &head->so_q;
    219 	}
    220 	TAILQ_INSERT_TAIL(so->so_onq, so, so_qe);
    221 }
    222 
    223 int
    224 soqremque(struct socket *so, int q)
    225 {
    226 	struct socket	*head;
    227 
    228 	head = so->so_head;
    229 	if (q == 0) {
    230 		if (so->so_onq != &head->so_q0)
    231 			return (0);
    232 		head->so_q0len--;
    233 	} else {
    234 		if (so->so_onq != &head->so_q)
    235 			return (0);
    236 		head->so_qlen--;
    237 	}
    238 	TAILQ_REMOVE(so->so_onq, so, so_qe);
    239 	so->so_onq = NULL;
    240 	so->so_head = NULL;
    241 	return (1);
    242 }
    243 
    244 /*
    245  * Socantsendmore indicates that no more data will be sent on the
    246  * socket; it would normally be applied to a socket when the user
    247  * informs the system that no more data is to be sent, by the protocol
    248  * code (in case PRU_SHUTDOWN).  Socantrcvmore indicates that no more data
    249  * will be received, and will normally be applied to the socket by a
    250  * protocol when it detects that the peer will send no more data.
    251  * Data queued for reading in the socket may yet be read.
    252  */
    253 
    254 void
    255 socantsendmore(struct socket *so)
    256 {
    257 
    258 	so->so_state |= SS_CANTSENDMORE;
    259 	sowwakeup(so);
    260 }
    261 
    262 void
    263 socantrcvmore(struct socket *so)
    264 {
    265 
    266 	so->so_state |= SS_CANTRCVMORE;
    267 	sorwakeup(so);
    268 }
    269 
    270 /*
    271  * Wait for data to arrive at/drain from a socket buffer.
    272  */
    273 int
    274 sbwait(struct sockbuf *sb)
    275 {
    276 
    277 	sb->sb_flags |= SB_WAIT;
    278 	return (tsleep((void *)&sb->sb_cc,
    279 	    (sb->sb_flags & SB_NOINTR) ? PSOCK : PSOCK | PCATCH, netio,
    280 	    sb->sb_timeo));
    281 }
    282 
    283 /*
    284  * Lock a sockbuf already known to be locked;
    285  * return any error returned from sleep (EINTR).
    286  */
    287 int
    288 sb_lock(struct sockbuf *sb)
    289 {
    290 	int	error;
    291 
    292 	while (sb->sb_flags & SB_LOCK) {
    293 		sb->sb_flags |= SB_WANT;
    294 		error = tsleep((void *)&sb->sb_flags,
    295 		    (sb->sb_flags & SB_NOINTR) ?  PSOCK : PSOCK|PCATCH,
    296 		    netlck, 0);
    297 		if (error)
    298 			return (error);
    299 	}
    300 	sb->sb_flags |= SB_LOCK;
    301 	return (0);
    302 }
    303 
    304 /*
    305  * Wakeup processes waiting on a socket buffer.
    306  * Do asynchronous notification via SIGIO
    307  * if the socket buffer has the SB_ASYNC flag set.
    308  */
    309 void
    310 sowakeup(struct socket *so, struct sockbuf *sb, int code)
    311 {
    312 	selnotify(&sb->sb_sel, 0);
    313 	sb->sb_flags &= ~SB_SEL;
    314 	if (sb->sb_flags & SB_WAIT) {
    315 		sb->sb_flags &= ~SB_WAIT;
    316 		wakeup((void *)&sb->sb_cc);
    317 	}
    318 	if (sb->sb_flags & SB_ASYNC) {
    319 		int band;
    320 		if (code == POLL_IN)
    321 			band = POLLIN|POLLRDNORM;
    322 		else
    323 			band = POLLOUT|POLLWRNORM;
    324 		fownsignal(so->so_pgid, SIGIO, code, band, so);
    325 	}
    326 	if (sb->sb_flags & SB_UPCALL)
    327 		(*so->so_upcall)(so, so->so_upcallarg, M_DONTWAIT);
    328 }
    329 
    330 /*
    331  * Socket buffer (struct sockbuf) utility routines.
    332  *
    333  * Each socket contains two socket buffers: one for sending data and
    334  * one for receiving data.  Each buffer contains a queue of mbufs,
    335  * information about the number of mbufs and amount of data in the
    336  * queue, and other fields allowing poll() statements and notification
    337  * on data availability to be implemented.
    338  *
    339  * Data stored in a socket buffer is maintained as a list of records.
    340  * Each record is a list of mbufs chained together with the m_next
    341  * field.  Records are chained together with the m_nextpkt field. The upper
    342  * level routine soreceive() expects the following conventions to be
    343  * observed when placing information in the receive buffer:
    344  *
    345  * 1. If the protocol requires each message be preceded by the sender's
    346  *    name, then a record containing that name must be present before
    347  *    any associated data (mbuf's must be of type MT_SONAME).
    348  * 2. If the protocol supports the exchange of ``access rights'' (really
    349  *    just additional data associated with the message), and there are
    350  *    ``rights'' to be received, then a record containing this data
    351  *    should be present (mbuf's must be of type MT_CONTROL).
    352  * 3. If a name or rights record exists, then it must be followed by
    353  *    a data record, perhaps of zero length.
    354  *
    355  * Before using a new socket structure it is first necessary to reserve
    356  * buffer space to the socket, by calling sbreserve().  This should commit
    357  * some of the available buffer space in the system buffer pool for the
    358  * socket (currently, it does nothing but enforce limits).  The space
    359  * should be released by calling sbrelease() when the socket is destroyed.
    360  */
    361 
    362 int
    363 sb_max_set(u_long new_sbmax)
    364 {
    365 	int s;
    366 
    367 	if (new_sbmax < (16 * 1024))
    368 		return (EINVAL);
    369 
    370 	s = splsoftnet();
    371 	sb_max = new_sbmax;
    372 	sb_max_adj = (u_quad_t)new_sbmax * MCLBYTES / (MSIZE + MCLBYTES);
    373 	splx(s);
    374 
    375 	return (0);
    376 }
    377 
    378 int
    379 soreserve(struct socket *so, u_long sndcc, u_long rcvcc)
    380 {
    381 	/*
    382 	 * there's at least one application (a configure script of screen)
    383 	 * which expects a fifo is writable even if it has "some" bytes
    384 	 * in its buffer.
    385 	 * so we want to make sure (hiwat - lowat) >= (some bytes).
    386 	 *
    387 	 * PIPE_BUF here is an arbitrary value chosen as (some bytes) above.
    388 	 * we expect it's large enough for such applications.
    389 	 */
    390 	u_long  lowat = MAX(sock_loan_thresh, MCLBYTES);
    391 	u_long  hiwat = lowat + PIPE_BUF;
    392 
    393 	if (sndcc < hiwat)
    394 		sndcc = hiwat;
    395 	if (sbreserve(&so->so_snd, sndcc, so) == 0)
    396 		goto bad;
    397 	if (sbreserve(&so->so_rcv, rcvcc, so) == 0)
    398 		goto bad2;
    399 	if (so->so_rcv.sb_lowat == 0)
    400 		so->so_rcv.sb_lowat = 1;
    401 	if (so->so_snd.sb_lowat == 0)
    402 		so->so_snd.sb_lowat = lowat;
    403 	if (so->so_snd.sb_lowat > so->so_snd.sb_hiwat)
    404 		so->so_snd.sb_lowat = so->so_snd.sb_hiwat;
    405 	return (0);
    406  bad2:
    407 	sbrelease(&so->so_snd, so);
    408  bad:
    409 	return (ENOBUFS);
    410 }
    411 
    412 /*
    413  * Allot mbufs to a sockbuf.
    414  * Attempt to scale mbmax so that mbcnt doesn't become limiting
    415  * if buffering efficiency is near the normal case.
    416  */
    417 int
    418 sbreserve(struct sockbuf *sb, u_long cc, struct socket *so)
    419 {
    420 	struct lwp *l = curlwp; /* XXX */
    421 	rlim_t maxcc;
    422 	struct uidinfo *uidinfo;
    423 
    424 	KDASSERT(sb_max_adj != 0);
    425 	if (cc == 0 || cc > sb_max_adj)
    426 		return (0);
    427 	if (so) {
    428 		if (l && kauth_cred_geteuid(l->l_cred) == so->so_uidinfo->ui_uid)
    429 			maxcc = l->l_proc->p_rlimit[RLIMIT_SBSIZE].rlim_cur;
    430 		else
    431 			maxcc = RLIM_INFINITY;
    432 		uidinfo = so->so_uidinfo;
    433 	} else {
    434 		uidinfo = uid_find(0);	/* XXX: nothing better */
    435 		maxcc = RLIM_INFINITY;
    436 	}
    437 	if (!chgsbsize(uidinfo, &sb->sb_hiwat, cc, maxcc))
    438 		return 0;
    439 	sb->sb_mbmax = min(cc * 2, sb_max);
    440 	if (sb->sb_lowat > sb->sb_hiwat)
    441 		sb->sb_lowat = sb->sb_hiwat;
    442 	return (1);
    443 }
    444 
    445 /*
    446  * Free mbufs held by a socket, and reserved mbuf space.
    447  */
    448 void
    449 sbrelease(struct sockbuf *sb, struct socket *so)
    450 {
    451 
    452 	sbflush(sb);
    453 	(void)chgsbsize(so->so_uidinfo, &sb->sb_hiwat, 0,
    454 	    RLIM_INFINITY);
    455 	sb->sb_mbmax = 0;
    456 }
    457 
    458 /*
    459  * Routines to add and remove
    460  * data from an mbuf queue.
    461  *
    462  * The routines sbappend() or sbappendrecord() are normally called to
    463  * append new mbufs to a socket buffer, after checking that adequate
    464  * space is available, comparing the function sbspace() with the amount
    465  * of data to be added.  sbappendrecord() differs from sbappend() in
    466  * that data supplied is treated as the beginning of a new record.
    467  * To place a sender's address, optional access rights, and data in a
    468  * socket receive buffer, sbappendaddr() should be used.  To place
    469  * access rights and data in a socket receive buffer, sbappendrights()
    470  * should be used.  In either case, the new data begins a new record.
    471  * Note that unlike sbappend() and sbappendrecord(), these routines check
    472  * for the caller that there will be enough space to store the data.
    473  * Each fails if there is not enough space, or if it cannot find mbufs
    474  * to store additional information in.
    475  *
    476  * Reliable protocols may use the socket send buffer to hold data
    477  * awaiting acknowledgement.  Data is normally copied from a socket
    478  * send buffer in a protocol with m_copy for output to a peer,
    479  * and then removing the data from the socket buffer with sbdrop()
    480  * or sbdroprecord() when the data is acknowledged by the peer.
    481  */
    482 
    483 #ifdef SOCKBUF_DEBUG
    484 void
    485 sblastrecordchk(struct sockbuf *sb, const char *where)
    486 {
    487 	struct mbuf *m = sb->sb_mb;
    488 
    489 	while (m && m->m_nextpkt)
    490 		m = m->m_nextpkt;
    491 
    492 	if (m != sb->sb_lastrecord) {
    493 		printf("sblastrecordchk: sb_mb %p sb_lastrecord %p last %p\n",
    494 		    sb->sb_mb, sb->sb_lastrecord, m);
    495 		printf("packet chain:\n");
    496 		for (m = sb->sb_mb; m != NULL; m = m->m_nextpkt)
    497 			printf("\t%p\n", m);
    498 		panic("sblastrecordchk from %s", where);
    499 	}
    500 }
    501 
    502 void
    503 sblastmbufchk(struct sockbuf *sb, const char *where)
    504 {
    505 	struct mbuf *m = sb->sb_mb;
    506 	struct mbuf *n;
    507 
    508 	while (m && m->m_nextpkt)
    509 		m = m->m_nextpkt;
    510 
    511 	while (m && m->m_next)
    512 		m = m->m_next;
    513 
    514 	if (m != sb->sb_mbtail) {
    515 		printf("sblastmbufchk: sb_mb %p sb_mbtail %p last %p\n",
    516 		    sb->sb_mb, sb->sb_mbtail, m);
    517 		printf("packet tree:\n");
    518 		for (m = sb->sb_mb; m != NULL; m = m->m_nextpkt) {
    519 			printf("\t");
    520 			for (n = m; n != NULL; n = n->m_next)
    521 				printf("%p ", n);
    522 			printf("\n");
    523 		}
    524 		panic("sblastmbufchk from %s", where);
    525 	}
    526 }
    527 #endif /* SOCKBUF_DEBUG */
    528 
    529 /*
    530  * Link a chain of records onto a socket buffer
    531  */
    532 #define	SBLINKRECORDCHAIN(sb, m0, mlast)				\
    533 do {									\
    534 	if ((sb)->sb_lastrecord != NULL)				\
    535 		(sb)->sb_lastrecord->m_nextpkt = (m0);			\
    536 	else								\
    537 		(sb)->sb_mb = (m0);					\
    538 	(sb)->sb_lastrecord = (mlast);					\
    539 } while (/*CONSTCOND*/0)
    540 
    541 
    542 #define	SBLINKRECORD(sb, m0)						\
    543     SBLINKRECORDCHAIN(sb, m0, m0)
    544 
    545 /*
    546  * Append mbuf chain m to the last record in the
    547  * socket buffer sb.  The additional space associated
    548  * the mbuf chain is recorded in sb.  Empty mbufs are
    549  * discarded and mbufs are compacted where possible.
    550  */
    551 void
    552 sbappend(struct sockbuf *sb, struct mbuf *m)
    553 {
    554 	struct mbuf	*n;
    555 
    556 	if (m == 0)
    557 		return;
    558 
    559 #ifdef MBUFTRACE
    560 	m_claimm(m, sb->sb_mowner);
    561 #endif
    562 
    563 	SBLASTRECORDCHK(sb, "sbappend 1");
    564 
    565 	if ((n = sb->sb_lastrecord) != NULL) {
    566 		/*
    567 		 * XXX Would like to simply use sb_mbtail here, but
    568 		 * XXX I need to verify that I won't miss an EOR that
    569 		 * XXX way.
    570 		 */
    571 		do {
    572 			if (n->m_flags & M_EOR) {
    573 				sbappendrecord(sb, m); /* XXXXXX!!!! */
    574 				return;
    575 			}
    576 		} while (n->m_next && (n = n->m_next));
    577 	} else {
    578 		/*
    579 		 * If this is the first record in the socket buffer, it's
    580 		 * also the last record.
    581 		 */
    582 		sb->sb_lastrecord = m;
    583 	}
    584 	sbcompress(sb, m, n);
    585 	SBLASTRECORDCHK(sb, "sbappend 2");
    586 }
    587 
    588 /*
    589  * This version of sbappend() should only be used when the caller
    590  * absolutely knows that there will never be more than one record
    591  * in the socket buffer, that is, a stream protocol (such as TCP).
    592  */
    593 void
    594 sbappendstream(struct sockbuf *sb, struct mbuf *m)
    595 {
    596 
    597 	KDASSERT(m->m_nextpkt == NULL);
    598 	KASSERT(sb->sb_mb == sb->sb_lastrecord);
    599 
    600 	SBLASTMBUFCHK(sb, __func__);
    601 
    602 #ifdef MBUFTRACE
    603 	m_claimm(m, sb->sb_mowner);
    604 #endif
    605 
    606 	sbcompress(sb, m, sb->sb_mbtail);
    607 
    608 	sb->sb_lastrecord = sb->sb_mb;
    609 	SBLASTRECORDCHK(sb, __func__);
    610 }
    611 
    612 #ifdef SOCKBUF_DEBUG
    613 void
    614 sbcheck(struct sockbuf *sb)
    615 {
    616 	struct mbuf	*m;
    617 	u_long		len, mbcnt;
    618 
    619 	len = 0;
    620 	mbcnt = 0;
    621 	for (m = sb->sb_mb; m; m = m->m_next) {
    622 		len += m->m_len;
    623 		mbcnt += MSIZE;
    624 		if (m->m_flags & M_EXT)
    625 			mbcnt += m->m_ext.ext_size;
    626 		if (m->m_nextpkt)
    627 			panic("sbcheck nextpkt");
    628 	}
    629 	if (len != sb->sb_cc || mbcnt != sb->sb_mbcnt) {
    630 		printf("cc %lu != %lu || mbcnt %lu != %lu\n", len, sb->sb_cc,
    631 		    mbcnt, sb->sb_mbcnt);
    632 		panic("sbcheck");
    633 	}
    634 }
    635 #endif
    636 
    637 /*
    638  * As above, except the mbuf chain
    639  * begins a new record.
    640  */
    641 void
    642 sbappendrecord(struct sockbuf *sb, struct mbuf *m0)
    643 {
    644 	struct mbuf	*m;
    645 
    646 	if (m0 == 0)
    647 		return;
    648 
    649 #ifdef MBUFTRACE
    650 	m_claimm(m0, sb->sb_mowner);
    651 #endif
    652 	/*
    653 	 * Put the first mbuf on the queue.
    654 	 * Note this permits zero length records.
    655 	 */
    656 	sballoc(sb, m0);
    657 	SBLASTRECORDCHK(sb, "sbappendrecord 1");
    658 	SBLINKRECORD(sb, m0);
    659 	m = m0->m_next;
    660 	m0->m_next = 0;
    661 	if (m && (m0->m_flags & M_EOR)) {
    662 		m0->m_flags &= ~M_EOR;
    663 		m->m_flags |= M_EOR;
    664 	}
    665 	sbcompress(sb, m, m0);
    666 	SBLASTRECORDCHK(sb, "sbappendrecord 2");
    667 }
    668 
    669 /*
    670  * As above except that OOB data
    671  * is inserted at the beginning of the sockbuf,
    672  * but after any other OOB data.
    673  */
    674 void
    675 sbinsertoob(struct sockbuf *sb, struct mbuf *m0)
    676 {
    677 	struct mbuf	*m, **mp;
    678 
    679 	if (m0 == 0)
    680 		return;
    681 
    682 	SBLASTRECORDCHK(sb, "sbinsertoob 1");
    683 
    684 	for (mp = &sb->sb_mb; (m = *mp) != NULL; mp = &((*mp)->m_nextpkt)) {
    685 	    again:
    686 		switch (m->m_type) {
    687 
    688 		case MT_OOBDATA:
    689 			continue;		/* WANT next train */
    690 
    691 		case MT_CONTROL:
    692 			if ((m = m->m_next) != NULL)
    693 				goto again;	/* inspect THIS train further */
    694 		}
    695 		break;
    696 	}
    697 	/*
    698 	 * Put the first mbuf on the queue.
    699 	 * Note this permits zero length records.
    700 	 */
    701 	sballoc(sb, m0);
    702 	m0->m_nextpkt = *mp;
    703 	if (*mp == NULL) {
    704 		/* m0 is actually the new tail */
    705 		sb->sb_lastrecord = m0;
    706 	}
    707 	*mp = m0;
    708 	m = m0->m_next;
    709 	m0->m_next = 0;
    710 	if (m && (m0->m_flags & M_EOR)) {
    711 		m0->m_flags &= ~M_EOR;
    712 		m->m_flags |= M_EOR;
    713 	}
    714 	sbcompress(sb, m, m0);
    715 	SBLASTRECORDCHK(sb, "sbinsertoob 2");
    716 }
    717 
    718 /*
    719  * Append address and data, and optionally, control (ancillary) data
    720  * to the receive queue of a socket.  If present,
    721  * m0 must include a packet header with total length.
    722  * Returns 0 if no space in sockbuf or insufficient mbufs.
    723  */
    724 int
    725 sbappendaddr(struct sockbuf *sb, const struct sockaddr *asa, struct mbuf *m0,
    726 	struct mbuf *control)
    727 {
    728 	struct mbuf	*m, *n, *nlast;
    729 	int		space, len;
    730 
    731 	space = asa->sa_len;
    732 
    733 	if (m0 != NULL) {
    734 		if ((m0->m_flags & M_PKTHDR) == 0)
    735 			panic("sbappendaddr");
    736 		space += m0->m_pkthdr.len;
    737 #ifdef MBUFTRACE
    738 		m_claimm(m0, sb->sb_mowner);
    739 #endif
    740 	}
    741 	for (n = control; n; n = n->m_next) {
    742 		space += n->m_len;
    743 		MCLAIM(n, sb->sb_mowner);
    744 		if (n->m_next == 0)	/* keep pointer to last control buf */
    745 			break;
    746 	}
    747 	if (space > sbspace(sb))
    748 		return (0);
    749 	MGET(m, M_DONTWAIT, MT_SONAME);
    750 	if (m == 0)
    751 		return (0);
    752 	MCLAIM(m, sb->sb_mowner);
    753 	/*
    754 	 * XXX avoid 'comparison always true' warning which isn't easily
    755 	 * avoided.
    756 	 */
    757 	len = asa->sa_len;
    758 	if (len > MLEN) {
    759 		MEXTMALLOC(m, asa->sa_len, M_NOWAIT);
    760 		if ((m->m_flags & M_EXT) == 0) {
    761 			m_free(m);
    762 			return (0);
    763 		}
    764 	}
    765 	m->m_len = asa->sa_len;
    766 	memcpy(mtod(m, void *), asa, asa->sa_len);
    767 	if (n)
    768 		n->m_next = m0;		/* concatenate data to control */
    769 	else
    770 		control = m0;
    771 	m->m_next = control;
    772 
    773 	SBLASTRECORDCHK(sb, "sbappendaddr 1");
    774 
    775 	for (n = m; n->m_next != NULL; n = n->m_next)
    776 		sballoc(sb, n);
    777 	sballoc(sb, n);
    778 	nlast = n;
    779 	SBLINKRECORD(sb, m);
    780 
    781 	sb->sb_mbtail = nlast;
    782 	SBLASTMBUFCHK(sb, "sbappendaddr");
    783 
    784 	SBLASTRECORDCHK(sb, "sbappendaddr 2");
    785 
    786 	return (1);
    787 }
    788 
    789 /*
    790  * Helper for sbappendchainaddr: prepend a struct sockaddr* to
    791  * an mbuf chain.
    792  */
    793 static inline struct mbuf *
    794 m_prepend_sockaddr(struct sockbuf *sb, struct mbuf *m0,
    795 		   const struct sockaddr *asa)
    796 {
    797 	struct mbuf *m;
    798 	const int salen = asa->sa_len;
    799 
    800 	/* only the first in each chain need be a pkthdr */
    801 	MGETHDR(m, M_DONTWAIT, MT_SONAME);
    802 	if (m == 0)
    803 		return (0);
    804 	MCLAIM(m, sb->sb_mowner);
    805 #ifdef notyet
    806 	if (salen > MHLEN) {
    807 		MEXTMALLOC(m, salen, M_NOWAIT);
    808 		if ((m->m_flags & M_EXT) == 0) {
    809 			m_free(m);
    810 			return (0);
    811 		}
    812 	}
    813 #else
    814 	KASSERT(salen <= MHLEN);
    815 #endif
    816 	m->m_len = salen;
    817 	memcpy(mtod(m, void *), asa, salen);
    818 	m->m_next = m0;
    819 	m->m_pkthdr.len = salen + m0->m_pkthdr.len;
    820 
    821 	return m;
    822 }
    823 
    824 int
    825 sbappendaddrchain(struct sockbuf *sb, const struct sockaddr *asa,
    826 		  struct mbuf *m0, int sbprio)
    827 {
    828 	int space;
    829 	struct mbuf *m, *n, *n0, *nlast;
    830 	int error;
    831 
    832 	/*
    833 	 * XXX sbprio reserved for encoding priority of this* request:
    834 	 *  SB_PRIO_NONE --> honour normal sb limits
    835 	 *  SB_PRIO_ONESHOT_OVERFLOW --> if socket has any space,
    836 	 *	take whole chain. Intended for large requests
    837 	 *      that should be delivered atomically (all, or none).
    838 	 * SB_PRIO_OVERDRAFT -- allow a small (2*MLEN) overflow
    839 	 *       over normal socket limits, for messages indicating
    840 	 *       buffer overflow in earlier normal/lower-priority messages
    841 	 * SB_PRIO_BESTEFFORT -->  ignore limits entirely.
    842 	 *       Intended for  kernel-generated messages only.
    843 	 *        Up to generator to avoid total mbuf resource exhaustion.
    844 	 */
    845 	(void)sbprio;
    846 
    847 	if (m0 && (m0->m_flags & M_PKTHDR) == 0)
    848 		panic("sbappendaddrchain");
    849 
    850 	space = sbspace(sb);
    851 
    852 #ifdef notyet
    853 	/*
    854 	 * Enforce SB_PRIO_* limits as described above.
    855 	 */
    856 #endif
    857 
    858 	n0 = NULL;
    859 	nlast = NULL;
    860 	for (m = m0; m; m = m->m_nextpkt) {
    861 		struct mbuf *np;
    862 
    863 #ifdef MBUFTRACE
    864 		m_claimm(m, sb->sb_mowner);
    865 #endif
    866 
    867 		/* Prepend sockaddr to this record (m) of input chain m0 */
    868 	  	n = m_prepend_sockaddr(sb, m, asa);
    869 		if (n == NULL) {
    870 			error = ENOBUFS;
    871 			goto bad;
    872 		}
    873 
    874 		/* Append record (asa+m) to end of new chain n0 */
    875 		if (n0 == NULL) {
    876 			n0 = n;
    877 		} else {
    878 			nlast->m_nextpkt = n;
    879 		}
    880 		/* Keep track of last record on new chain */
    881 		nlast = n;
    882 
    883 		for (np = n; np; np = np->m_next)
    884 			sballoc(sb, np);
    885 	}
    886 
    887 	SBLASTRECORDCHK(sb, "sbappendaddrchain 1");
    888 
    889 	/* Drop the entire chain of (asa+m) records onto the socket */
    890 	SBLINKRECORDCHAIN(sb, n0, nlast);
    891 
    892 	SBLASTRECORDCHK(sb, "sbappendaddrchain 2");
    893 
    894 	for (m = nlast; m->m_next; m = m->m_next)
    895 		;
    896 	sb->sb_mbtail = m;
    897 	SBLASTMBUFCHK(sb, "sbappendaddrchain");
    898 
    899 	return (1);
    900 
    901 bad:
    902 	/*
    903 	 * On error, free the prepended addreseses. For consistency
    904 	 * with sbappendaddr(), leave it to our caller to free
    905 	 * the input record chain passed to us as m0.
    906 	 */
    907 	while ((n = n0) != NULL) {
    908 	  	struct mbuf *np;
    909 
    910 		/* Undo the sballoc() of this record */
    911 		for (np = n; np; np = np->m_next)
    912 			sbfree(sb, np);
    913 
    914 		n0 = n->m_nextpkt;	/* iterate at next prepended address */
    915 		MFREE(n, np);		/* free prepended address (not data) */
    916 	}
    917 	return 0;
    918 }
    919 
    920 
    921 int
    922 sbappendcontrol(struct sockbuf *sb, struct mbuf *m0, struct mbuf *control)
    923 {
    924 	struct mbuf	*m, *mlast, *n;
    925 	int		space;
    926 
    927 	space = 0;
    928 	if (control == 0)
    929 		panic("sbappendcontrol");
    930 	for (m = control; ; m = m->m_next) {
    931 		space += m->m_len;
    932 		MCLAIM(m, sb->sb_mowner);
    933 		if (m->m_next == 0)
    934 			break;
    935 	}
    936 	n = m;			/* save pointer to last control buffer */
    937 	for (m = m0; m; m = m->m_next) {
    938 		MCLAIM(m, sb->sb_mowner);
    939 		space += m->m_len;
    940 	}
    941 	if (space > sbspace(sb))
    942 		return (0);
    943 	n->m_next = m0;			/* concatenate data to control */
    944 
    945 	SBLASTRECORDCHK(sb, "sbappendcontrol 1");
    946 
    947 	for (m = control; m->m_next != NULL; m = m->m_next)
    948 		sballoc(sb, m);
    949 	sballoc(sb, m);
    950 	mlast = m;
    951 	SBLINKRECORD(sb, control);
    952 
    953 	sb->sb_mbtail = mlast;
    954 	SBLASTMBUFCHK(sb, "sbappendcontrol");
    955 
    956 	SBLASTRECORDCHK(sb, "sbappendcontrol 2");
    957 
    958 	return (1);
    959 }
    960 
    961 /*
    962  * Compress mbuf chain m into the socket
    963  * buffer sb following mbuf n.  If n
    964  * is null, the buffer is presumed empty.
    965  */
    966 void
    967 sbcompress(struct sockbuf *sb, struct mbuf *m, struct mbuf *n)
    968 {
    969 	int		eor;
    970 	struct mbuf	*o;
    971 
    972 	eor = 0;
    973 	while (m) {
    974 		eor |= m->m_flags & M_EOR;
    975 		if (m->m_len == 0 &&
    976 		    (eor == 0 ||
    977 		     (((o = m->m_next) || (o = n)) &&
    978 		      o->m_type == m->m_type))) {
    979 			if (sb->sb_lastrecord == m)
    980 				sb->sb_lastrecord = m->m_next;
    981 			m = m_free(m);
    982 			continue;
    983 		}
    984 		if (n && (n->m_flags & M_EOR) == 0 &&
    985 		    /* M_TRAILINGSPACE() checks buffer writeability */
    986 		    m->m_len <= MCLBYTES / 4 && /* XXX Don't copy too much */
    987 		    m->m_len <= M_TRAILINGSPACE(n) &&
    988 		    n->m_type == m->m_type) {
    989 			memcpy(mtod(n, char *) + n->m_len, mtod(m, void *),
    990 			    (unsigned)m->m_len);
    991 			n->m_len += m->m_len;
    992 			sb->sb_cc += m->m_len;
    993 			m = m_free(m);
    994 			continue;
    995 		}
    996 		if (n)
    997 			n->m_next = m;
    998 		else
    999 			sb->sb_mb = m;
   1000 		sb->sb_mbtail = m;
   1001 		sballoc(sb, m);
   1002 		n = m;
   1003 		m->m_flags &= ~M_EOR;
   1004 		m = m->m_next;
   1005 		n->m_next = 0;
   1006 	}
   1007 	if (eor) {
   1008 		if (n)
   1009 			n->m_flags |= eor;
   1010 		else
   1011 			printf("semi-panic: sbcompress\n");
   1012 	}
   1013 	SBLASTMBUFCHK(sb, __func__);
   1014 }
   1015 
   1016 /*
   1017  * Free all mbufs in a sockbuf.
   1018  * Check that all resources are reclaimed.
   1019  */
   1020 void
   1021 sbflush(struct sockbuf *sb)
   1022 {
   1023 
   1024 	KASSERT((sb->sb_flags & SB_LOCK) == 0);
   1025 
   1026 	while (sb->sb_mbcnt)
   1027 		sbdrop(sb, (int)sb->sb_cc);
   1028 
   1029 	KASSERT(sb->sb_cc == 0);
   1030 	KASSERT(sb->sb_mb == NULL);
   1031 	KASSERT(sb->sb_mbtail == NULL);
   1032 	KASSERT(sb->sb_lastrecord == NULL);
   1033 }
   1034 
   1035 /*
   1036  * Drop data from (the front of) a sockbuf.
   1037  */
   1038 void
   1039 sbdrop(struct sockbuf *sb, int len)
   1040 {
   1041 	struct mbuf	*m, *mn, *next;
   1042 
   1043 	next = (m = sb->sb_mb) ? m->m_nextpkt : 0;
   1044 	while (len > 0) {
   1045 		if (m == 0) {
   1046 			if (next == 0)
   1047 				panic("sbdrop");
   1048 			m = next;
   1049 			next = m->m_nextpkt;
   1050 			continue;
   1051 		}
   1052 		if (m->m_len > len) {
   1053 			m->m_len -= len;
   1054 			m->m_data += len;
   1055 			sb->sb_cc -= len;
   1056 			break;
   1057 		}
   1058 		len -= m->m_len;
   1059 		sbfree(sb, m);
   1060 		MFREE(m, mn);
   1061 		m = mn;
   1062 	}
   1063 	while (m && m->m_len == 0) {
   1064 		sbfree(sb, m);
   1065 		MFREE(m, mn);
   1066 		m = mn;
   1067 	}
   1068 	if (m) {
   1069 		sb->sb_mb = m;
   1070 		m->m_nextpkt = next;
   1071 	} else
   1072 		sb->sb_mb = next;
   1073 	/*
   1074 	 * First part is an inline SB_EMPTY_FIXUP().  Second part
   1075 	 * makes sure sb_lastrecord is up-to-date if we dropped
   1076 	 * part of the last record.
   1077 	 */
   1078 	m = sb->sb_mb;
   1079 	if (m == NULL) {
   1080 		sb->sb_mbtail = NULL;
   1081 		sb->sb_lastrecord = NULL;
   1082 	} else if (m->m_nextpkt == NULL)
   1083 		sb->sb_lastrecord = m;
   1084 }
   1085 
   1086 /*
   1087  * Drop a record off the front of a sockbuf
   1088  * and move the next record to the front.
   1089  */
   1090 void
   1091 sbdroprecord(struct sockbuf *sb)
   1092 {
   1093 	struct mbuf	*m, *mn;
   1094 
   1095 	m = sb->sb_mb;
   1096 	if (m) {
   1097 		sb->sb_mb = m->m_nextpkt;
   1098 		do {
   1099 			sbfree(sb, m);
   1100 			MFREE(m, mn);
   1101 		} while ((m = mn) != NULL);
   1102 	}
   1103 	SB_EMPTY_FIXUP(sb);
   1104 }
   1105 
   1106 /*
   1107  * Create a "control" mbuf containing the specified data
   1108  * with the specified type for presentation on a socket buffer.
   1109  */
   1110 struct mbuf *
   1111 sbcreatecontrol(void *p, int size, int type, int level)
   1112 {
   1113 	struct cmsghdr	*cp;
   1114 	struct mbuf	*m;
   1115 
   1116 	if (CMSG_SPACE(size) > MCLBYTES) {
   1117 		printf("sbcreatecontrol: message too large %d\n", size);
   1118 		return NULL;
   1119 	}
   1120 
   1121 	if ((m = m_get(M_DONTWAIT, MT_CONTROL)) == NULL)
   1122 		return ((struct mbuf *) NULL);
   1123 	if (CMSG_SPACE(size) > MLEN) {
   1124 		MCLGET(m, M_DONTWAIT);
   1125 		if ((m->m_flags & M_EXT) == 0) {
   1126 			m_free(m);
   1127 			return NULL;
   1128 		}
   1129 	}
   1130 	cp = mtod(m, struct cmsghdr *);
   1131 	memcpy(CMSG_DATA(cp), p, size);
   1132 	m->m_len = CMSG_SPACE(size);
   1133 	cp->cmsg_len = CMSG_LEN(size);
   1134 	cp->cmsg_level = level;
   1135 	cp->cmsg_type = type;
   1136 	return (m);
   1137 }
   1138