PageRenderTime 222ms CodeModel.GetById 4ms app.highlight 193ms RepoModel.GetById 1ms app.codeStats 1ms

/sys/kern/uipc_socket.c

https://github.com/brauceunix/libuinet
C | 3902 lines | 2830 code | 357 blank | 715 comment | 768 complexity | 567e0eb2b3bb65b01dd0a33ff9a26120 MD5 | raw file
   1/*-
   2 * Copyright (c) 1982, 1986, 1988, 1990, 1993
   3 *	The Regents of the University of California.
   4 * Copyright (c) 2004 The FreeBSD Foundation
   5 * Copyright (c) 2004-2008 Robert N. M. Watson
   6 * All rights reserved.
   7 *
   8 * Redistribution and use in source and binary forms, with or without
   9 * modification, are permitted provided that the following conditions
  10 * are met:
  11 * 1. Redistributions of source code must retain the above copyright
  12 *    notice, this list of conditions and the following disclaimer.
  13 * 2. Redistributions in binary form must reproduce the above copyright
  14 *    notice, this list of conditions and the following disclaimer in the
  15 *    documentation and/or other materials provided with the distribution.
  16 * 4. Neither the name of the University nor the names of its contributors
  17 *    may be used to endorse or promote products derived from this software
  18 *    without specific prior written permission.
  19 *
  20 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
  21 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  23 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
  24 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  25 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  26 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  28 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  29 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  30 * SUCH DAMAGE.
  31 *
  32 *	@(#)uipc_socket.c	8.3 (Berkeley) 4/15/94
  33 */
  34
  35/*
  36 * Comments on the socket life cycle:
  37 *
  38 * soalloc() sets of socket layer state for a socket, called only by
  39 * socreate() and sonewconn().  Socket layer private.
  40 *
  41 * sodealloc() tears down socket layer state for a socket, called only by
  42 * sofree() and sonewconn().  Socket layer private.
  43 *
  44 * pru_attach() associates protocol layer state with an allocated socket;
  45 * called only once, may fail, aborting socket allocation.  This is called
  46 * from socreate() and sonewconn().  Socket layer private.
  47 *
  48 * pru_detach() disassociates protocol layer state from an attached socket,
  49 * and will be called exactly once for sockets in which pru_attach() has
  50 * been successfully called.  If pru_attach() returned an error,
  51 * pru_detach() will not be called.  Socket layer private.
  52 *
  53 * pru_abort() and pru_close() notify the protocol layer that the last
  54 * consumer of a socket is starting to tear down the socket, and that the
  55 * protocol should terminate the connection.  Historically, pru_abort() also
  56 * detached protocol state from the socket state, but this is no longer the
  57 * case.
  58 *
  59 * socreate() creates a socket and attaches protocol state.  This is a public
  60 * interface that may be used by socket layer consumers to create new
  61 * sockets.
  62 *
  63 * sonewconn() creates a socket and attaches protocol state.  This is a
  64 * public interface  that may be used by protocols to create new sockets when
  65 * a new connection is received and will be available for accept() on a
  66 * listen socket.
  67 *
  68 * soclose() destroys a socket after possibly waiting for it to disconnect.
  69 * This is a public interface that socket consumers should use to close and
  70 * release a socket when done with it.
  71 *
  72 * soabort() destroys a socket without waiting for it to disconnect (used
  73 * only for incoming connections that are already partially or fully
  74 * connected).  This is used internally by the socket layer when clearing
  75 * listen socket queues (due to overflow or close on the listen socket), but
  76 * is also a public interface protocols may use to abort connections in
  77 * their incomplete listen queues should they no longer be required.  Sockets
  78 * placed in completed connection listen queues should not be aborted for
  79 * reasons described in the comment above the soclose() implementation.  This
  80 * is not a general purpose close routine, and except in the specific
  81 * circumstances described here, should not be used.
  82 *
  83 * sofree() will free a socket and its protocol state if all references on
  84 * the socket have been released, and is the public interface to attempt to
  85 * free a socket when a reference is removed.  This is a socket layer private
  86 * interface.
  87 *
  88 * NOTE: In addition to socreate() and soclose(), which provide a single
  89 * socket reference to the consumer to be managed as required, there are two
  90 * calls to explicitly manage socket references, soref(), and sorele().
  91 * Currently, these are generally required only when transitioning a socket
  92 * from a listen queue to a file descriptor, in order to prevent garbage
  93 * collection of the socket at an untimely moment.  For a number of reasons,
  94 * these interfaces are not preferred, and should be avoided.
  95 * 
  96 * NOTE: With regard to VNETs the general rule is that callers do not set
  97 * curvnet. Exceptions to this rule include soabort(), sodisconnect(),
  98 * sofree() (and with that sorele(), sotryfree()), as well as sonewconn()
  99 * and sorflush(), which are usually called from a pre-set VNET context.
 100 * sopoll() currently does not need a VNET context to be set.
 101 */
 102
 103#include <sys/cdefs.h>
 104__FBSDID("$FreeBSD: release/9.1.0/sys/kern/uipc_socket.c 233353 2012-03-23 11:26:54Z kib $");
 105
 106#include "opt_inet.h"
 107#include "opt_inet6.h"
 108#include "opt_zero.h"
 109#include "opt_compat.h"
 110#include "opt_passiveinet.h"
 111#include "opt_promiscinet.h"
 112
 113#include <sys/param.h>
 114#include <sys/systm.h>
 115#include <sys/fcntl.h>
 116#include <sys/limits.h>
 117#include <sys/lock.h>
 118#include <sys/mac.h>
 119#include <sys/malloc.h>
 120#include <sys/mbuf.h>
 121#include <sys/mutex.h>
 122#include <sys/domain.h>
 123#include <sys/file.h>			/* for struct knote */
 124#include <sys/kernel.h>
 125#include <sys/event.h>
 126#include <sys/eventhandler.h>
 127#include <sys/poll.h>
 128#include <sys/proc.h>
 129#include <sys/protosw.h>
 130#include <sys/socket.h>
 131#include <sys/socketvar.h>
 132#include <sys/resourcevar.h>
 133#include <net/route.h>
 134#include <sys/signalvar.h>
 135#include <sys/stat.h>
 136#include <sys/sx.h>
 137#include <sys/sysctl.h>
 138#include <sys/uio.h>
 139#include <sys/jail.h>
 140
 141#include <net/vnet.h>
 142
 143#ifdef MAC
 144#include <security/mac/mac_framework.h>
 145#endif /* MAC */
 146
 147#ifdef PROMISCUOUS_INET
 148#include <netinet/in_promisc.h>
 149#endif
 150
 151#include <vm/uma.h>
 152
 153#ifdef COMPAT_FREEBSD32
 154#include <sys/mount.h>
 155#include <sys/sysent.h>
 156#include <compat/freebsd32/freebsd32.h>
 157#endif
 158
 159static int	soreceive_rcvoob(struct socket *so, struct uio *uio,
 160		    int flags);
 161
 162static void	filt_sordetach(struct knote *kn);
 163static int	filt_soread(struct knote *kn, long hint);
 164static void	filt_sowdetach(struct knote *kn);
 165static int	filt_sowrite(struct knote *kn, long hint);
 166static int	filt_solisten(struct knote *kn, long hint);
 167
 168static struct filterops solisten_filtops = {
 169	.f_isfd = 1,
 170	.f_detach = filt_sordetach,
 171	.f_event = filt_solisten,
 172};
 173static struct filterops soread_filtops = {
 174	.f_isfd = 1,
 175	.f_detach = filt_sordetach,
 176	.f_event = filt_soread,
 177};
 178static struct filterops sowrite_filtops = {
 179	.f_isfd = 1,
 180	.f_detach = filt_sowdetach,
 181	.f_event = filt_sowrite,
 182};
 183
 184uma_zone_t socket_zone;
 185so_gen_t	so_gencnt;	/* generation count for sockets */
 186
 187int	maxsockets;
 188
 189MALLOC_DEFINE(M_SONAME, "soname", "socket name");
 190MALLOC_DEFINE(M_PCB, "pcb", "protocol control block");
 191
 192#define	VNET_SO_ASSERT(so)						\
 193	VNET_ASSERT(curvnet != NULL,					\
 194	    ("%s:%d curvnet is NULL, so=%p", __func__, __LINE__, (so)));
 195
 196static int somaxconn = SOMAXCONN;
 197static int sysctl_somaxconn(SYSCTL_HANDLER_ARGS);
 198/* XXX: we dont have SYSCTL_USHORT */
 199SYSCTL_PROC(_kern_ipc, KIPC_SOMAXCONN, somaxconn, CTLTYPE_UINT | CTLFLAG_RW,
 200    0, sizeof(int), sysctl_somaxconn, "I", "Maximum pending socket connection "
 201    "queue size");
 202static int numopensockets;
 203SYSCTL_INT(_kern_ipc, OID_AUTO, numopensockets, CTLFLAG_RD,
 204    &numopensockets, 0, "Number of open sockets");
 205#ifdef ZERO_COPY_SOCKETS
 206/* These aren't static because they're used in other files. */
 207int so_zero_copy_send = 1;
 208int so_zero_copy_receive = 1;
 209SYSCTL_NODE(_kern_ipc, OID_AUTO, zero_copy, CTLFLAG_RD, 0,
 210    "Zero copy controls");
 211SYSCTL_INT(_kern_ipc_zero_copy, OID_AUTO, receive, CTLFLAG_RW,
 212    &so_zero_copy_receive, 0, "Enable zero copy receive");
 213SYSCTL_INT(_kern_ipc_zero_copy, OID_AUTO, send, CTLFLAG_RW,
 214    &so_zero_copy_send, 0, "Enable zero copy send");
 215#endif /* ZERO_COPY_SOCKETS */
 216
 217/*
 218 * accept_mtx locks down per-socket fields relating to accept queues.  See
 219 * socketvar.h for an annotation of the protected fields of struct socket.
 220 */
 221struct mtx accept_mtx;
 222MTX_SYSINIT(accept_mtx, &accept_mtx, "accept", MTX_DEF);
 223
 224/*
 225 * so_global_mtx protects so_gencnt, numopensockets, and the per-socket
 226 * so_gencnt field.
 227 */
 228static struct mtx so_global_mtx;
 229MTX_SYSINIT(so_global_mtx, &so_global_mtx, "so_glabel", MTX_DEF);
 230
 231/*
 232 * General IPC sysctl name space, used by sockets and a variety of other IPC
 233 * types.
 234 */
 235SYSCTL_NODE(_kern, KERN_IPC, ipc, CTLFLAG_RW, 0, "IPC");
 236
 237/*
 238 * Sysctl to get and set the maximum global sockets limit.  Notify protocols
 239 * of the change so that they can update their dependent limits as required.
 240 */
 241static int
 242sysctl_maxsockets(SYSCTL_HANDLER_ARGS)
 243{
 244	int error, newmaxsockets;
 245
 246	newmaxsockets = maxsockets;
 247	error = sysctl_handle_int(oidp, &newmaxsockets, 0, req);
 248	if (error == 0 && req->newptr) {
 249		if (newmaxsockets > maxsockets) {
 250			maxsockets = newmaxsockets;
 251			if (maxsockets > ((maxfiles / 4) * 3)) {
 252				maxfiles = (maxsockets * 5) / 4;
 253				maxfilesperproc = (maxfiles * 9) / 10;
 254			}
 255			EVENTHANDLER_INVOKE(maxsockets_change);
 256		} else
 257			error = EINVAL;
 258	}
 259	return (error);
 260}
 261
 262SYSCTL_PROC(_kern_ipc, OID_AUTO, maxsockets, CTLTYPE_INT|CTLFLAG_RW,
 263    &maxsockets, 0, sysctl_maxsockets, "IU",
 264    "Maximum number of sockets avaliable");
 265
 266/*
 267 * Initialise maxsockets.  This SYSINIT must be run after
 268 * tunable_mbinit().
 269 */
 270static void
 271init_maxsockets(void *ignored)
 272{
 273
 274	TUNABLE_INT_FETCH("kern.ipc.maxsockets", &maxsockets);
 275	maxsockets = imax(maxsockets, imax(maxfiles, nmbclusters));
 276}
 277SYSINIT(param, SI_SUB_TUNABLES, SI_ORDER_ANY, init_maxsockets, NULL);
 278
 279/*
 280 * Socket operation routines.  These routines are called by the routines in
 281 * sys_socket.c or from a system process, and implement the semantics of
 282 * socket operations by switching out to the protocol specific routines.
 283 */
 284
 285/*
 286 * Get a socket structure from our zone, and initialize it.  Note that it
 287 * would probably be better to allocate socket and PCB at the same time, but
 288 * I'm not convinced that all the protocols can be easily modified to do
 289 * this.
 290 *
 291 * soalloc() returns a socket with a ref count of 0.
 292 */
 293static struct socket *
 294soalloc(struct vnet *vnet)
 295{
 296	struct socket *so;
 297
 298	so = uma_zalloc(socket_zone, M_NOWAIT | M_ZERO);
 299	if (so == NULL)
 300		return (NULL);
 301#ifdef MAC
 302	if (mac_socket_init(so, M_NOWAIT) != 0) {
 303		uma_zfree(socket_zone, so);
 304		return (NULL);
 305	}
 306#endif
 307#ifdef PROMISCUOUS_INET
 308	if (in_promisc_socket_init(so, M_NOWAIT) != 0) {
 309#ifdef MAC
 310		mac_socket_destroy(so);
 311#endif
 312		uma_zfree(socket_zone, so);
 313		return (NULL);
 314	}
 315#endif /* PROMISCUOUS_INET */
 316	SOCKBUF_LOCK_INIT(&so->so_snd, "so_snd");
 317	SOCKBUF_LOCK_INIT(&so->so_rcv, "so_rcv");
 318	sx_init(&so->so_snd.sb_sx, "so_snd_sx");
 319	sx_init(&so->so_rcv.sb_sx, "so_rcv_sx");
 320	TAILQ_INIT(&so->so_aiojobq);
 321	mtx_lock(&so_global_mtx);
 322	so->so_gencnt = ++so_gencnt;
 323	++numopensockets;
 324#ifdef VIMAGE
 325	VNET_ASSERT(vnet != NULL, ("%s:%d vnet is NULL, so=%p",
 326	    __func__, __LINE__, so));
 327	vnet->vnet_sockcnt++;
 328	so->so_vnet = vnet;
 329#endif
 330	mtx_unlock(&so_global_mtx);
 331	return (so);
 332}
 333
 334/*
 335 * Free the storage associated with a socket at the socket layer, tear down
 336 * locks, labels, etc.  All protocol state is assumed already to have been
 337 * torn down (and possibly never set up) by the caller.
 338 */
 339static void
 340sodealloc(struct socket *so)
 341{
 342
 343	KASSERT(so->so_count == 0, ("sodealloc(): so_count %d", so->so_count));
 344	KASSERT(so->so_pcb == NULL, ("sodealloc(): so_pcb != NULL"));
 345
 346	mtx_lock(&so_global_mtx);
 347	so->so_gencnt = ++so_gencnt;
 348	--numopensockets;	/* Could be below, but faster here. */
 349#ifdef VIMAGE
 350	VNET_ASSERT(so->so_vnet != NULL, ("%s:%d so_vnet is NULL, so=%p",
 351	    __func__, __LINE__, so));
 352	so->so_vnet->vnet_sockcnt--;
 353#endif
 354	mtx_unlock(&so_global_mtx);
 355	if (so->so_rcv.sb_hiwat)
 356		(void)chgsbsize(so->so_cred->cr_uidinfo,
 357		    &so->so_rcv.sb_hiwat, 0, RLIM_INFINITY);
 358	if (so->so_snd.sb_hiwat)
 359		(void)chgsbsize(so->so_cred->cr_uidinfo,
 360		    &so->so_snd.sb_hiwat, 0, RLIM_INFINITY);
 361#ifdef INET
 362	/* remove acccept filter if one is present. */
 363	if (so->so_accf != NULL)
 364		do_setopt_accept_filter(so, NULL);
 365#endif
 366#ifdef PROMISCUOUS_INET
 367	in_promisc_socket_destroy(so);
 368#endif
 369#ifdef MAC
 370	mac_socket_destroy(so);
 371#endif
 372	crfree(so->so_cred);
 373	sx_destroy(&so->so_snd.sb_sx);
 374	sx_destroy(&so->so_rcv.sb_sx);
 375	SOCKBUF_LOCK_DESTROY(&so->so_snd);
 376	SOCKBUF_LOCK_DESTROY(&so->so_rcv);
 377	uma_zfree(socket_zone, so);
 378}
 379
 380/*
 381 * socreate returns a socket with a ref count of 1.  The socket should be
 382 * closed with soclose().
 383 */
 384int
 385socreate(int dom, struct socket **aso, int type, int proto,
 386    struct ucred *cred, struct thread *td)
 387{
 388	struct protosw *prp;
 389	struct socket *so;
 390	int error;
 391
 392	if (proto)
 393		prp = pffindproto(dom, proto, type);
 394	else
 395		prp = pffindtype(dom, type);
 396
 397	if (prp == NULL || prp->pr_usrreqs->pru_attach == NULL ||
 398	    prp->pr_usrreqs->pru_attach == pru_attach_notsupp)
 399		return (EPROTONOSUPPORT);
 400
 401	if (prison_check_af(cred, prp->pr_domain->dom_family) != 0)
 402		return (EPROTONOSUPPORT);
 403
 404	if (prp->pr_type != type)
 405		return (EPROTOTYPE);
 406	so = soalloc(CRED_TO_VNET(cred));
 407	if (so == NULL)
 408		return (ENOBUFS);
 409
 410	TAILQ_INIT(&so->so_incomp);
 411	TAILQ_INIT(&so->so_comp);
 412	so->so_type = type;
 413	so->so_cred = crhold(cred);
 414	if ((prp->pr_domain->dom_family == PF_INET) ||
 415	    (prp->pr_domain->dom_family == PF_INET6) ||
 416	    (prp->pr_domain->dom_family == PF_ROUTE))
 417		so->so_fibnum = td->td_proc->p_fibnum;
 418	else
 419		so->so_fibnum = 0;
 420	so->so_proto = prp;
 421#ifdef MAC
 422	mac_socket_create(cred, so);
 423#endif
 424	knlist_init_mtx(&so->so_rcv.sb_sel.si_note, SOCKBUF_MTX(&so->so_rcv));
 425	knlist_init_mtx(&so->so_snd.sb_sel.si_note, SOCKBUF_MTX(&so->so_snd));
 426	so->so_count = 1;
 427	/*
 428	 * Auto-sizing of socket buffers is managed by the protocols and
 429	 * the appropriate flags must be set in the pru_attach function.
 430	 */
 431	CURVNET_SET(so->so_vnet);
 432	error = (*prp->pr_usrreqs->pru_attach)(so, proto, td);
 433	CURVNET_RESTORE();
 434	if (error) {
 435		KASSERT(so->so_count == 1, ("socreate: so_count %d",
 436		    so->so_count));
 437		so->so_count = 0;
 438		sodealloc(so);
 439		return (error);
 440	}
 441	*aso = so;
 442	return (0);
 443}
 444
 445#ifdef REGRESSION
 446static int regression_sonewconn_earlytest = 1;
 447SYSCTL_INT(_regression, OID_AUTO, sonewconn_earlytest, CTLFLAG_RW,
 448    &regression_sonewconn_earlytest, 0, "Perform early sonewconn limit test");
 449#endif
 450
 451/*
 452 * When an attempt at a new connection is noted on a socket which accepts
 453 * connections, sonewconn is called.  If the connection is possible (subject
 454 * to space constraints, etc.) then we allocate a new structure, properly
 455 * linked into the data structure of the original socket, and return this.
 456 * Connstatus may be 0, or SO_ISCONFIRMING, or SO_ISCONNECTED.
 457 *
 458 * Note: the ref count on the socket is 0 on return.
 459 */
 460struct socket *
 461sonewconn(struct socket *head, int connstatus)
 462{
 463	struct socket *so;
 464	int over;
 465
 466	ACCEPT_LOCK();
 467	over = (head->so_qlen > 3 * head->so_qlimit / 2);
 468	ACCEPT_UNLOCK();
 469#ifdef REGRESSION
 470	if (regression_sonewconn_earlytest && over)
 471#else
 472	if (over)
 473#endif
 474		return (NULL);
 475	VNET_ASSERT(head->so_vnet != NULL, ("%s:%d so_vnet is NULL, head=%p",
 476	    __func__, __LINE__, head));
 477	so = soalloc(head->so_vnet);
 478	if (so == NULL)
 479		return (NULL);
 480	if ((head->so_options & SO_ACCEPTFILTER) != 0)
 481		connstatus = 0;
 482	so->so_head = head;
 483	so->so_type = head->so_type;
 484	so->so_options = head->so_options &~ SO_ACCEPTCONN;
 485	so->so_linger = head->so_linger;
 486	so->so_state = head->so_state | SS_NOFDREF;
 487	so->so_fibnum = head->so_fibnum;
 488	so->so_proto = head->so_proto;
 489	so->so_cred = crhold(head->so_cred);
 490#ifdef MAC
 491	mac_socket_newconn(head, so);
 492#endif
 493#ifdef PROMISCUOUS_INET
 494	in_promisc_socket_newconn(head, so);
 495#endif
 496	knlist_init_mtx(&so->so_rcv.sb_sel.si_note, SOCKBUF_MTX(&so->so_rcv));
 497	knlist_init_mtx(&so->so_snd.sb_sel.si_note, SOCKBUF_MTX(&so->so_snd));
 498	VNET_SO_ASSERT(head);
 499	if (soreserve(so, head->so_snd.sb_hiwat, head->so_rcv.sb_hiwat) ||
 500	    (*so->so_proto->pr_usrreqs->pru_attach)(so, 0, NULL)) {
 501		sodealloc(so);
 502		return (NULL);
 503	}
 504	so->so_rcv.sb_lowat = head->so_rcv.sb_lowat;
 505	so->so_snd.sb_lowat = head->so_snd.sb_lowat;
 506	so->so_rcv.sb_timeo = head->so_rcv.sb_timeo;
 507	so->so_snd.sb_timeo = head->so_snd.sb_timeo;
 508	so->so_rcv.sb_flags |= head->so_rcv.sb_flags & SB_AUTOSIZE;
 509	so->so_snd.sb_flags |= head->so_snd.sb_flags & SB_AUTOSIZE;
 510	so->so_state |= connstatus;
 511	ACCEPT_LOCK();
 512	if (connstatus) {
 513		TAILQ_INSERT_TAIL(&head->so_comp, so, so_list);
 514		so->so_qstate |= SQ_COMP;
 515		head->so_qlen++;
 516	} else {
 517		/*
 518		 * Keep removing sockets from the head until there's room for
 519		 * us to insert on the tail.  In pre-locking revisions, this
 520		 * was a simple if(), but as we could be racing with other
 521		 * threads and soabort() requires dropping locks, we must
 522		 * loop waiting for the condition to be true.
 523		 */
 524		while (head->so_incqlen > head->so_qlimit) {
 525			struct socket *sp;
 526			sp = TAILQ_FIRST(&head->so_incomp);
 527			TAILQ_REMOVE(&head->so_incomp, sp, so_list);
 528			head->so_incqlen--;
 529			sp->so_qstate &= ~SQ_INCOMP;
 530			sp->so_head = NULL;
 531			ACCEPT_UNLOCK();
 532			soabort(sp);
 533			ACCEPT_LOCK();
 534		}
 535		TAILQ_INSERT_TAIL(&head->so_incomp, so, so_list);
 536		so->so_qstate |= SQ_INCOMP;
 537		head->so_incqlen++;
 538	}
 539	ACCEPT_UNLOCK();
 540	if (connstatus) {
 541		sorwakeup(head);
 542		wakeup_one(&head->so_timeo);
 543	}
 544	return (so);
 545}
 546
 547#ifdef PASSIVE_INET
 548/*
 549 * When a new connection is completed on a listening socket that is
 550 * configured for passive reassembly, sonewconn_passive_client is called to
 551 * create a socket representing the client side of the reassembled
 552 * connection.  We allocate a new structure, inherit configuration from the
 553 * listening socket, and return this.
 554 * Connstatus may be 0, or SO_ISCONFIRMING, or SO_ISCONNECTING.
 555 *
 556 * Note: the ref count on the socket is 1 on return.
 557 */
 558struct socket *
 559sonewconn_passive_client(struct socket *head, int connstatus)
 560{
 561	struct socket *so;
 562
 563	VNET_ASSERT(head->so_vnet != NULL, ("%s:%d so_vnet is NULL, head=%p",
 564	    __func__, __LINE__, head));
 565	so = soalloc(head->so_vnet);
 566	if (so == NULL)
 567		return (NULL);
 568	so->so_head = NULL; /* just inheriting from head, not otherwise associating */
 569	so->so_type = head->so_type;
 570	so->so_options = head->so_options &~ SO_ACCEPTCONN;
 571	so->so_linger = head->so_linger;
 572	so->so_state = head->so_state | SS_NOFDREF;
 573	so->so_fibnum = head->so_fibnum;
 574	so->so_proto = head->so_proto;
 575	so->so_cred = crhold(head->so_cred);
 576#ifdef MAC
 577	mac_socket_newconn(head, so);
 578#endif
 579#ifdef PROMISCUOUS_INET
 580	in_promisc_socket_newconn(head, so);
 581#endif
 582	knlist_init_mtx(&so->so_rcv.sb_sel.si_note, SOCKBUF_MTX(&so->so_rcv));
 583	knlist_init_mtx(&so->so_snd.sb_sel.si_note, SOCKBUF_MTX(&so->so_snd));
 584	VNET_SO_ASSERT(head);
 585	if (soreserve(so, head->so_snd.sb_hiwat, head->so_rcv.sb_hiwat) ||
 586	    (*so->so_proto->pr_usrreqs->pru_attach)(so, 0, NULL)) {
 587		sodealloc(so);
 588		return (NULL);
 589	}
 590	so->so_rcv.sb_lowat = head->so_rcv.sb_lowat;
 591	so->so_snd.sb_lowat = head->so_snd.sb_lowat;
 592	so->so_rcv.sb_timeo = head->so_rcv.sb_timeo;
 593	so->so_snd.sb_timeo = head->so_snd.sb_timeo;
 594	so->so_rcv.sb_flags |= head->so_rcv.sb_flags & SB_AUTOSIZE;
 595	so->so_snd.sb_flags |= head->so_snd.sb_flags & SB_AUTOSIZE;
 596	so->so_state |= connstatus;
 597
 598	return (so);
 599}
 600#endif /* PASSIVE_INET */
 601
 602int
 603sobind(struct socket *so, struct sockaddr *nam, struct thread *td)
 604{
 605	int error;
 606
 607	CURVNET_SET(so->so_vnet);
 608	error = (*so->so_proto->pr_usrreqs->pru_bind)(so, nam, td);
 609	CURVNET_RESTORE();
 610	return error;
 611}
 612
 613/*
 614 * solisten() transitions a socket from a non-listening state to a listening
 615 * state, but can also be used to update the listen queue depth on an
 616 * existing listen socket.  The protocol will call back into the sockets
 617 * layer using solisten_proto_check() and solisten_proto() to check and set
 618 * socket-layer listen state.  Call backs are used so that the protocol can
 619 * acquire both protocol and socket layer locks in whatever order is required
 620 * by the protocol.
 621 *
 622 * Protocol implementors are advised to hold the socket lock across the
 623 * socket-layer test and set to avoid races at the socket layer.
 624 */
 625int
 626solisten(struct socket *so, int backlog, struct thread *td)
 627{
 628	int error;
 629
 630	CURVNET_SET(so->so_vnet);
 631	error = (*so->so_proto->pr_usrreqs->pru_listen)(so, backlog, td);
 632	CURVNET_RESTORE();
 633	return error;
 634}
 635
 636int
 637solisten_proto_check(struct socket *so)
 638{
 639
 640	SOCK_LOCK_ASSERT(so);
 641
 642	if (so->so_state & (SS_ISCONNECTED | SS_ISCONNECTING |
 643	    SS_ISDISCONNECTING))
 644		return (EINVAL);
 645	return (0);
 646}
 647
 648void
 649solisten_proto(struct socket *so, int backlog)
 650{
 651
 652	SOCK_LOCK_ASSERT(so);
 653
 654	if (backlog < 0 || backlog > somaxconn)
 655		backlog = somaxconn;
 656	so->so_qlimit = backlog;
 657	so->so_options |= SO_ACCEPTCONN;
 658}
 659
 660/*
 661 * Evaluate the reference count and named references on a socket; if no
 662 * references remain, free it.  This should be called whenever a reference is
 663 * released, such as in sorele(), but also when named reference flags are
 664 * cleared in socket or protocol code.
 665 *
 666 * sofree() will free the socket if:
 667 *
 668 * - There are no outstanding file descriptor references or related consumers
 669 *   (so_count == 0).
 670 *
 671 * - The socket has been closed by user space, if ever open (SS_NOFDREF).
 672 *
 673 * - The protocol does not have an outstanding strong reference on the socket
 674 *   (SS_PROTOREF).
 675 *
 676 * - The socket is not in a completed connection queue, so a process has been
 677 *   notified that it is present.  If it is removed, the user process may
 678 *   block in accept() despite select() saying the socket was ready.
 679 */
 680void
 681sofree(struct socket *so)
 682{
 683	struct protosw *pr = so->so_proto;
 684	struct socket *head;
 685
 686	ACCEPT_LOCK_ASSERT();
 687	SOCK_LOCK_ASSERT(so);
 688
 689	if ((so->so_state & SS_NOFDREF) == 0 || so->so_count != 0 ||
 690	    (so->so_state & SS_PROTOREF) || (so->so_qstate & SQ_COMP)) {
 691		SOCK_UNLOCK(so);
 692		ACCEPT_UNLOCK();
 693		return;
 694	}
 695
 696	head = so->so_head;
 697	if (head != NULL) {
 698		KASSERT((so->so_qstate & SQ_COMP) != 0 ||
 699		    (so->so_qstate & SQ_INCOMP) != 0,
 700		    ("sofree: so_head != NULL, but neither SQ_COMP nor "
 701		    "SQ_INCOMP"));
 702		KASSERT((so->so_qstate & SQ_COMP) == 0 ||
 703		    (so->so_qstate & SQ_INCOMP) == 0,
 704		    ("sofree: so->so_qstate is SQ_COMP and also SQ_INCOMP"));
 705		TAILQ_REMOVE(&head->so_incomp, so, so_list);
 706		head->so_incqlen--;
 707		so->so_qstate &= ~SQ_INCOMP;
 708		so->so_head = NULL;
 709	}
 710	KASSERT((so->so_qstate & SQ_COMP) == 0 &&
 711	    (so->so_qstate & SQ_INCOMP) == 0,
 712	    ("sofree: so_head == NULL, but still SQ_COMP(%d) or SQ_INCOMP(%d)",
 713	    so->so_qstate & SQ_COMP, so->so_qstate & SQ_INCOMP));
 714	if (so->so_options & SO_ACCEPTCONN) {
 715		KASSERT((TAILQ_EMPTY(&so->so_comp)), ("sofree: so_comp populated"));
 716		KASSERT((TAILQ_EMPTY(&so->so_incomp)), ("sofree: so_comp populated"));
 717	}
 718	SOCK_UNLOCK(so);
 719	ACCEPT_UNLOCK();
 720
 721	VNET_SO_ASSERT(so);
 722	if (pr->pr_flags & PR_RIGHTS && pr->pr_domain->dom_dispose != NULL)
 723		(*pr->pr_domain->dom_dispose)(so->so_rcv.sb_mb);
 724	if (pr->pr_usrreqs->pru_detach != NULL)
 725		(*pr->pr_usrreqs->pru_detach)(so);
 726
 727	/*
 728	 * From this point on, we assume that no other references to this
 729	 * socket exist anywhere else in the stack.  Therefore, no locks need
 730	 * to be acquired or held.
 731	 *
 732	 * We used to do a lot of socket buffer and socket locking here, as
 733	 * well as invoke sorflush() and perform wakeups.  The direct call to
 734	 * dom_dispose() and sbrelease_internal() are an inlining of what was
 735	 * necessary from sorflush().
 736	 *
 737	 * Notice that the socket buffer and kqueue state are torn down
 738	 * before calling pru_detach.  This means that protocols shold not
 739	 * assume they can perform socket wakeups, etc, in their detach code.
 740	 */
 741	sbdestroy(&so->so_snd, so);
 742	sbdestroy(&so->so_rcv, so);
 743	seldrain(&so->so_snd.sb_sel);
 744	seldrain(&so->so_rcv.sb_sel);
 745	knlist_destroy(&so->so_rcv.sb_sel.si_note);
 746	knlist_destroy(&so->so_snd.sb_sel.si_note);
 747	sodealloc(so);
 748}
 749
 750/*
 751 * Close a socket on last file table reference removal.  Initiate disconnect
 752 * if connected.  Free socket when disconnect complete.
 753 *
 754 * This function will sorele() the socket.  Note that soclose() may be called
 755 * prior to the ref count reaching zero.  The actual socket structure will
 756 * not be freed until the ref count reaches zero.
 757 */
 758int
 759soclose(struct socket *so)
 760{
 761	int error = 0;
 762
 763	KASSERT(!(so->so_state & SS_NOFDREF), ("soclose: SS_NOFDREF on enter"));
 764
 765	CURVNET_SET(so->so_vnet);
 766	funsetown(&so->so_sigio);
 767	if (so->so_state & SS_ISCONNECTED) {
 768		if ((so->so_state & SS_ISDISCONNECTING) == 0) {
 769			error = sodisconnect(so);
 770			if (error) {
 771				if (error == ENOTCONN)
 772					error = 0;
 773				goto drop;
 774			}
 775		}
 776		if (so->so_options & SO_LINGER) {
 777			if ((so->so_state & SS_ISDISCONNECTING) &&
 778			    (so->so_state & SS_NBIO))
 779				goto drop;
 780			while (so->so_state & SS_ISCONNECTED) {
 781				error = tsleep(&so->so_timeo,
 782				    PSOCK | PCATCH, "soclos", so->so_linger * hz);
 783				if (error)
 784					break;
 785			}
 786		}
 787	}
 788
 789drop:
 790	if (so->so_proto->pr_usrreqs->pru_close != NULL)
 791		(*so->so_proto->pr_usrreqs->pru_close)(so);
 792	if (so->so_options & SO_ACCEPTCONN) {
 793		struct socket *sp;
 794		ACCEPT_LOCK();
 795		while ((sp = TAILQ_FIRST(&so->so_incomp)) != NULL) {
 796			TAILQ_REMOVE(&so->so_incomp, sp, so_list);
 797			so->so_incqlen--;
 798			sp->so_qstate &= ~SQ_INCOMP;
 799			sp->so_head = NULL;
 800			ACCEPT_UNLOCK();
 801			soabort(sp);
 802			ACCEPT_LOCK();
 803		}
 804		while ((sp = TAILQ_FIRST(&so->so_comp)) != NULL) {
 805			TAILQ_REMOVE(&so->so_comp, sp, so_list);
 806			so->so_qlen--;
 807			sp->so_qstate &= ~SQ_COMP;
 808			sp->so_head = NULL;
 809			ACCEPT_UNLOCK();
 810			soabort(sp);
 811			ACCEPT_LOCK();
 812		}
 813		ACCEPT_UNLOCK();
 814	}
 815	ACCEPT_LOCK();
 816	SOCK_LOCK(so);
 817	KASSERT((so->so_state & SS_NOFDREF) == 0, ("soclose: NOFDREF"));
 818	so->so_state |= SS_NOFDREF;
 819	sorele(so);
 820	CURVNET_RESTORE();
 821	return (error);
 822}
 823
 824/*
 825 * soabort() is used to abruptly tear down a connection, such as when a
 826 * resource limit is reached (listen queue depth exceeded), or if a listen
 827 * socket is closed while there are sockets waiting to be accepted.
 828 *
 829 * This interface is tricky, because it is called on an unreferenced socket,
 830 * and must be called only by a thread that has actually removed the socket
 831 * from the listen queue it was on, or races with other threads are risked.
 832 *
 833 * This interface will call into the protocol code, so must not be called
 834 * with any socket locks held.  Protocols do call it while holding their own
 835 * recursible protocol mutexes, but this is something that should be subject
 836 * to review in the future.
 837 */
 838void
 839soabort(struct socket *so)
 840{
 841
 842	/*
 843	 * In as much as is possible, assert that no references to this
 844	 * socket are held.  This is not quite the same as asserting that the
 845	 * current thread is responsible for arranging for no references, but
 846	 * is as close as we can get for now.
 847	 */
 848	KASSERT(so->so_count == 0, ("soabort: so_count"));
 849	KASSERT((so->so_state & SS_PROTOREF) == 0, ("soabort: SS_PROTOREF"));
 850	KASSERT(so->so_state & SS_NOFDREF, ("soabort: !SS_NOFDREF"));
 851	KASSERT((so->so_state & SQ_COMP) == 0, ("soabort: SQ_COMP"));
 852	KASSERT((so->so_state & SQ_INCOMP) == 0, ("soabort: SQ_INCOMP"));
 853	VNET_SO_ASSERT(so);
 854
 855	if (so->so_proto->pr_usrreqs->pru_abort != NULL)
 856		(*so->so_proto->pr_usrreqs->pru_abort)(so);
 857	ACCEPT_LOCK();
 858	SOCK_LOCK(so);
 859	sofree(so);
 860}
 861
 862int
 863soaccept(struct socket *so, struct sockaddr **nam)
 864{
 865	int error;
 866
 867	SOCK_LOCK(so);
 868	KASSERT((so->so_state & SS_NOFDREF) != 0, ("soaccept: !NOFDREF"));
 869	so->so_state &= ~SS_NOFDREF;
 870	SOCK_UNLOCK(so);
 871
 872	CURVNET_SET(so->so_vnet);
 873	error = (*so->so_proto->pr_usrreqs->pru_accept)(so, nam);
 874	CURVNET_RESTORE();
 875	return (error);
 876}
 877
 878int
 879soconnect(struct socket *so, struct sockaddr *nam, struct thread *td)
 880{
 881	int error;
 882
 883	if (so->so_options & SO_ACCEPTCONN)
 884		return (EOPNOTSUPP);
 885
 886	CURVNET_SET(so->so_vnet);
 887	/*
 888	 * If protocol is connection-based, can only connect once.
 889	 * Otherwise, if connected, try to disconnect first.  This allows
 890	 * user to disconnect by connecting to, e.g., a null address.
 891	 */
 892	if (so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING) &&
 893	    ((so->so_proto->pr_flags & PR_CONNREQUIRED) ||
 894	    (error = sodisconnect(so)))) {
 895		error = EISCONN;
 896	} else {
 897		/*
 898		 * Prevent accumulated error from previous connection from
 899		 * biting us.
 900		 */
 901		so->so_error = 0;
 902		error = (*so->so_proto->pr_usrreqs->pru_connect)(so, nam, td);
 903	}
 904	CURVNET_RESTORE();
 905
 906	return (error);
 907}
 908
 909int
 910soconnect2(struct socket *so1, struct socket *so2)
 911{
 912	int error;
 913
 914	CURVNET_SET(so1->so_vnet);
 915	error = (*so1->so_proto->pr_usrreqs->pru_connect2)(so1, so2);
 916	CURVNET_RESTORE();
 917	return (error);
 918}
 919
 920int
 921sodisconnect(struct socket *so)
 922{
 923	int error;
 924
 925	if ((so->so_state & SS_ISCONNECTED) == 0)
 926		return (ENOTCONN);
 927	if (so->so_state & SS_ISDISCONNECTING)
 928		return (EALREADY);
 929	VNET_SO_ASSERT(so);
 930	error = (*so->so_proto->pr_usrreqs->pru_disconnect)(so);
 931	return (error);
 932}
 933
 934#ifdef ZERO_COPY_SOCKETS
 935struct so_zerocopy_stats{
 936	int size_ok;
 937	int align_ok;
 938	int found_ifp;
 939};
 940struct so_zerocopy_stats so_zerocp_stats = {0,0,0};
 941#include <netinet/in.h>
 942#include <net/route.h>
 943#include <netinet/in_pcb.h>
 944#include <vm/vm.h>
 945#include <vm/vm_page.h>
 946#include <vm/vm_object.h>
 947
 948/*
 949 * sosend_copyin() is only used if zero copy sockets are enabled.  Otherwise
 950 * sosend_dgram() and sosend_generic() use m_uiotombuf().
 951 * 
 952 * sosend_copyin() accepts a uio and prepares an mbuf chain holding part or
 953 * all of the data referenced by the uio.  If desired, it uses zero-copy.
 954 * *space will be updated to reflect data copied in.
 955 *
 956 * NB: If atomic I/O is requested, the caller must already have checked that
 957 * space can hold resid bytes.
 958 *
 959 * NB: In the event of an error, the caller may need to free the partial
 960 * chain pointed to by *mpp.  The contents of both *uio and *space may be
 961 * modified even in the case of an error.
 962 */
 963static int
 964sosend_copyin(struct uio *uio, struct mbuf **retmp, int atomic, long *space,
 965    int flags)
 966{
 967	struct mbuf *m, **mp, *top;
 968	long len;
 969	ssize_t resid;
 970	int error;
 971#ifdef ZERO_COPY_SOCKETS
 972	int cow_send;
 973#endif
 974
 975	*retmp = top = NULL;
 976	mp = &top;
 977	len = 0;
 978	resid = uio->uio_resid;
 979	error = 0;
 980	do {
 981#ifdef ZERO_COPY_SOCKETS
 982		cow_send = 0;
 983#endif /* ZERO_COPY_SOCKETS */
 984		if (resid >= MINCLSIZE) {
 985#ifdef ZERO_COPY_SOCKETS
 986			if (top == NULL) {
 987				m = m_gethdr(M_WAITOK, MT_DATA);
 988				m->m_pkthdr.len = 0;
 989				m->m_pkthdr.rcvif = NULL;
 990			} else
 991				m = m_get(M_WAITOK, MT_DATA);
 992			if (so_zero_copy_send &&
 993			    resid>=PAGE_SIZE &&
 994			    *space>=PAGE_SIZE &&
 995			    uio->uio_iov->iov_len>=PAGE_SIZE) {
 996				so_zerocp_stats.size_ok++;
 997				so_zerocp_stats.align_ok++;
 998				cow_send = socow_setup(m, uio);
 999				len = cow_send;
1000			}
1001			if (!cow_send) {
1002				m_clget(m, M_WAITOK);
1003				len = min(min(MCLBYTES, resid), *space);
1004			}
1005#else /* ZERO_COPY_SOCKETS */
1006			if (top == NULL) {
1007				m = m_getcl(M_WAIT, MT_DATA, M_PKTHDR);
1008				m->m_pkthdr.len = 0;
1009				m->m_pkthdr.rcvif = NULL;
1010			} else
1011				m = m_getcl(M_WAIT, MT_DATA, 0);
1012			len = min(min(MCLBYTES, resid), *space);
1013#endif /* ZERO_COPY_SOCKETS */
1014		} else {
1015			if (top == NULL) {
1016				m = m_gethdr(M_WAIT, MT_DATA);
1017				m->m_pkthdr.len = 0;
1018				m->m_pkthdr.rcvif = NULL;
1019
1020				len = min(min(MHLEN, resid), *space);
1021				/*
1022				 * For datagram protocols, leave room
1023				 * for protocol headers in first mbuf.
1024				 */
1025				if (atomic && m && len < MHLEN)
1026					MH_ALIGN(m, len);
1027			} else {
1028				m = m_get(M_WAIT, MT_DATA);
1029				len = min(min(MLEN, resid), *space);
1030			}
1031		}
1032		if (m == NULL) {
1033			error = ENOBUFS;
1034			goto out;
1035		}
1036
1037		*space -= len;
1038#ifdef ZERO_COPY_SOCKETS
1039		if (cow_send)
1040			error = 0;
1041		else
1042#endif /* ZERO_COPY_SOCKETS */
1043		error = uiomove(mtod(m, void *), (int)len, uio);
1044		resid = uio->uio_resid;
1045		m->m_len = len;
1046		*mp = m;
1047		top->m_pkthdr.len += len;
1048		if (error)
1049			goto out;
1050		mp = &m->m_next;
1051		if (resid <= 0) {
1052			if (flags & MSG_EOR)
1053				top->m_flags |= M_EOR;
1054			break;
1055		}
1056	} while (*space > 0 && atomic);
1057out:
1058	*retmp = top;
1059	return (error);
1060}
1061#endif /*ZERO_COPY_SOCKETS*/
1062
1063#define	SBLOCKWAIT(f)	(((f) & MSG_DONTWAIT) ? 0 : SBL_WAIT)
1064
1065int
1066sosend_dgram(struct socket *so, struct sockaddr *addr, struct uio *uio,
1067    struct mbuf *top, struct mbuf *control, int flags, struct thread *td)
1068{
1069	long space;
1070	ssize_t resid;
1071	int clen = 0, error, dontroute;
1072#ifdef ZERO_COPY_SOCKETS
1073	int atomic = sosendallatonce(so) || top;
1074#endif
1075
1076	KASSERT(so->so_type == SOCK_DGRAM, ("sodgram_send: !SOCK_DGRAM"));
1077	KASSERT(so->so_proto->pr_flags & PR_ATOMIC,
1078	    ("sodgram_send: !PR_ATOMIC"));
1079
1080	if (uio != NULL)
1081		resid = uio->uio_resid;
1082	else
1083		resid = top->m_pkthdr.len;
1084	/*
1085	 * In theory resid should be unsigned.  However, space must be
1086	 * signed, as it might be less than 0 if we over-committed, and we
1087	 * must use a signed comparison of space and resid.  On the other
1088	 * hand, a negative resid causes us to loop sending 0-length
1089	 * segments to the protocol.
1090	 */
1091	if (resid < 0) {
1092		error = EINVAL;
1093		goto out;
1094	}
1095
1096	dontroute =
1097	    (flags & MSG_DONTROUTE) && (so->so_options & SO_DONTROUTE) == 0;
1098	if (td != NULL)
1099		td->td_ru.ru_msgsnd++;
1100	if (control != NULL)
1101		clen = control->m_len;
1102
1103	SOCKBUF_LOCK(&so->so_snd);
1104	if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
1105		SOCKBUF_UNLOCK(&so->so_snd);
1106		error = EPIPE;
1107		goto out;
1108	}
1109	if (so->so_error) {
1110		error = so->so_error;
1111		so->so_error = 0;
1112		SOCKBUF_UNLOCK(&so->so_snd);
1113		goto out;
1114	}
1115	if ((so->so_state & SS_ISCONNECTED) == 0) {
1116		/*
1117		 * `sendto' and `sendmsg' is allowed on a connection-based
1118		 * socket if it supports implied connect.  Return ENOTCONN if
1119		 * not connected and no address is supplied.
1120		 */
1121		if ((so->so_proto->pr_flags & PR_CONNREQUIRED) &&
1122		    (so->so_proto->pr_flags & PR_IMPLOPCL) == 0) {
1123			if ((so->so_state & SS_ISCONFIRMING) == 0 &&
1124			    !(resid == 0 && clen != 0)) {
1125				SOCKBUF_UNLOCK(&so->so_snd);
1126				error = ENOTCONN;
1127				goto out;
1128			}
1129		} else if (addr == NULL) {
1130			if (so->so_proto->pr_flags & PR_CONNREQUIRED)
1131				error = ENOTCONN;
1132			else
1133				error = EDESTADDRREQ;
1134			SOCKBUF_UNLOCK(&so->so_snd);
1135			goto out;
1136		}
1137	}
1138
1139	/*
1140	 * Do we need MSG_OOB support in SOCK_DGRAM?  Signs here may be a
1141	 * problem and need fixing.
1142	 */
1143	space = sbspace(&so->so_snd);
1144	if (flags & MSG_OOB)
1145		space += 1024;
1146	space -= clen;
1147	SOCKBUF_UNLOCK(&so->so_snd);
1148	if (resid > space) {
1149		error = EMSGSIZE;
1150		goto out;
1151	}
1152	if (uio == NULL) {
1153		resid = 0;
1154		if (flags & MSG_EOR)
1155			top->m_flags |= M_EOR;
1156	} else {
1157#ifdef ZERO_COPY_SOCKETS
1158		error = sosend_copyin(uio, &top, atomic, &space, flags);
1159		if (error)
1160			goto out;
1161#else
1162		/*
1163		 * Copy the data from userland into a mbuf chain.
1164		 * If no data is to be copied in, a single empty mbuf
1165		 * is returned.
1166		 */
1167		top = m_uiotombuf(uio, M_WAITOK, space, max_hdr,
1168		    (M_PKTHDR | ((flags & MSG_EOR) ? M_EOR : 0)));
1169		if (top == NULL) {
1170			error = EFAULT;	/* only possible error */
1171			goto out;
1172		}
1173		space -= resid - uio->uio_resid;
1174#endif
1175		resid = uio->uio_resid;
1176	}
1177	KASSERT(resid == 0, ("sosend_dgram: resid != 0"));
1178	/*
1179	 * XXXRW: Frobbing SO_DONTROUTE here is even worse without sblock
1180	 * than with.
1181	 */
1182	if (dontroute) {
1183		SOCK_LOCK(so);
1184		so->so_options |= SO_DONTROUTE;
1185		SOCK_UNLOCK(so);
1186	}
1187	/*
1188	 * XXX all the SBS_CANTSENDMORE checks previously done could be out
1189	 * of date.  We could have recieved a reset packet in an interrupt or
1190	 * maybe we slept while doing page faults in uiomove() etc.  We could
1191	 * probably recheck again inside the locking protection here, but
1192	 * there are probably other places that this also happens.  We must
1193	 * rethink this.
1194	 */
1195	VNET_SO_ASSERT(so);
1196	error = (*so->so_proto->pr_usrreqs->pru_send)(so,
1197	    (flags & MSG_OOB) ? PRUS_OOB :
1198	/*
1199	 * If the user set MSG_EOF, the protocol understands this flag and
1200	 * nothing left to send then use PRU_SEND_EOF instead of PRU_SEND.
1201	 */
1202	    ((flags & MSG_EOF) &&
1203	     (so->so_proto->pr_flags & PR_IMPLOPCL) &&
1204	     (resid <= 0)) ?
1205		PRUS_EOF :
1206		/* If there is more to send set PRUS_MORETOCOME */
1207		(resid > 0 && space > 0) ? PRUS_MORETOCOME : 0,
1208		top, addr, control, td);
1209	if (dontroute) {
1210		SOCK_LOCK(so);
1211		so->so_options &= ~SO_DONTROUTE;
1212		SOCK_UNLOCK(so);
1213	}
1214	clen = 0;
1215	control = NULL;
1216	top = NULL;
1217out:
1218	if (top != NULL)
1219		m_freem(top);
1220	if (control != NULL)
1221		m_freem(control);
1222	return (error);
1223}
1224
1225/*
1226 * Send on a socket.  If send must go all at once and message is larger than
1227 * send buffering, then hard error.  Lock against other senders.  If must go
1228 * all at once and not enough room now, then inform user that this would
1229 * block and do nothing.  Otherwise, if nonblocking, send as much as
1230 * possible.  The data to be sent is described by "uio" if nonzero, otherwise
1231 * by the mbuf chain "top" (which must be null if uio is not).  Data provided
1232 * in mbuf chain must be small enough to send all at once.
1233 *
1234 * Returns nonzero on error, timeout or signal; callers must check for short
1235 * counts if EINTR/ERESTART are returned.  Data and control buffers are freed
1236 * on return.
1237 */
1238int
1239sosend_generic(struct socket *so, struct sockaddr *addr, struct uio *uio,
1240    struct mbuf *top, struct mbuf *control, int flags, struct thread *td)
1241{
1242	long space;
1243	ssize_t resid;
1244	int clen = 0, error, dontroute;
1245	int atomic = sosendallatonce(so) || top;
1246
1247	if (uio != NULL)
1248		resid = uio->uio_resid;
1249	else
1250		resid = top->m_pkthdr.len;
1251	/*
1252	 * In theory resid should be unsigned.  However, space must be
1253	 * signed, as it might be less than 0 if we over-committed, and we
1254	 * must use a signed comparison of space and resid.  On the other
1255	 * hand, a negative resid causes us to loop sending 0-length
1256	 * segments to the protocol.
1257	 *
1258	 * Also check to make sure that MSG_EOR isn't used on SOCK_STREAM
1259	 * type sockets since that's an error.
1260	 */
1261	if (resid < 0 || (so->so_type == SOCK_STREAM && (flags & MSG_EOR))) {
1262		error = EINVAL;
1263		goto out;
1264	}
1265
1266	dontroute =
1267	    (flags & MSG_DONTROUTE) && (so->so_options & SO_DONTROUTE) == 0 &&
1268	    (so->so_proto->pr_flags & PR_ATOMIC);
1269	if (td != NULL)
1270		td->td_ru.ru_msgsnd++;
1271	if (control != NULL)
1272		clen = control->m_len;
1273
1274	error = sblock(&so->so_snd, SBLOCKWAIT(flags));
1275	if (error)
1276		goto out;
1277
1278restart:
1279	do {
1280		SOCKBUF_LOCK(&so->so_snd);
1281		if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
1282			SOCKBUF_UNLOCK(&so->so_snd);
1283			error = EPIPE;
1284			goto release;
1285		}
1286		if (so->so_error) {
1287			error = so->so_error;
1288			so->so_error = 0;
1289			SOCKBUF_UNLOCK(&so->so_snd);
1290			goto release;
1291		}
1292		if ((so->so_state & SS_ISCONNECTED) == 0) {
1293			/*
1294			 * `sendto' and `sendmsg' is allowed on a connection-
1295			 * based socket if it supports implied connect.
1296			 * Return ENOTCONN if not connected and no address is
1297			 * supplied.
1298			 */
1299			if ((so->so_proto->pr_flags & PR_CONNREQUIRED) &&
1300			    (so->so_proto->pr_flags & PR_IMPLOPCL) == 0) {
1301				if ((so->so_state & SS_ISCONFIRMING) == 0 &&
1302				    !(resid == 0 && clen != 0)) {
1303					SOCKBUF_UNLOCK(&so->so_snd);
1304					error = ENOTCONN;
1305					goto release;
1306				}
1307			} else if (addr == NULL) {
1308				SOCKBUF_UNLOCK(&so->so_snd);
1309				if (so->so_proto->pr_flags & PR_CONNREQUIRED)
1310					error = ENOTCONN;
1311				else
1312					error = EDESTADDRREQ;
1313				goto release;
1314			}
1315		}
1316		space = sbspace(&so->so_snd);
1317		if (flags & MSG_OOB)
1318			space += 1024;
1319		if ((atomic && resid > so->so_snd.sb_hiwat) ||
1320		    clen > so->so_snd.sb_hiwat) {
1321			SOCKBUF_UNLOCK(&so->so_snd);
1322			error = EMSGSIZE;
1323			goto release;
1324		}
1325		if (space < resid + clen &&
1326		    (atomic || space < so->so_snd.sb_lowat || space < clen)) {
1327			if ((so->so_state & SS_NBIO) || (flags & MSG_NBIO)) {
1328				if (so->so_upcallprep.soup_send) {
1329					so->so_upcallprep.soup_send(so,
1330						so->so_upcallprep.soup_send_arg,
1331						resid);
1332				}
1333				SOCKBUF_UNLOCK(&so->so_snd);
1334				error = EWOULDBLOCK;
1335				goto release;
1336			}
1337			error = sbwait(&so->so_snd);
1338			SOCKBUF_UNLOCK(&so->so_snd);
1339			if (error)
1340				goto release;
1341			goto restart;
1342		}
1343		SOCKBUF_UNLOCK(&so->so_snd);
1344		space -= clen;
1345		do {
1346			if (uio == NULL) {
1347				resid = 0;
1348				if (flags & MSG_EOR)
1349					top->m_flags |= M_EOR;
1350			} else {
1351#ifdef ZERO_COPY_SOCKETS
1352				error = sosend_copyin(uio, &top, atomic,
1353				    &space, flags);
1354				if (error != 0)
1355					goto release;
1356#else
1357				/*
1358				 * Copy the data from userland into a mbuf
1359				 * chain.  If no data is to be copied in,
1360				 * a single empty mbuf is returned.
1361				 */
1362				top = m_uiotombuf(uio, M_WAITOK, space,
1363				    (atomic ? max_hdr : 0),
1364				    (atomic ? M_PKTHDR : 0) |
1365				    ((flags & MSG_EOR) ? M_EOR : 0));
1366				if (top == NULL) {
1367					error = EFAULT; /* only possible error */
1368					goto release;
1369				}
1370				space -= resid - uio->uio_resid;
1371#endif
1372				resid = uio->uio_resid;
1373			}
1374			if (dontroute) {
1375				SOCK_LOCK(so);
1376				so->so_options |= SO_DONTROUTE;
1377				SOCK_UNLOCK(so);
1378			}
1379			/*
1380			 * XXX all the SBS_CANTSENDMORE checks previously
1381			 * done could be out of date.  We could have recieved
1382			 * a reset packet in an interrupt or maybe we slept
1383			 * while doing page faults in uiomove() etc.  We
1384			 * could probably recheck again inside the locking
1385			 * protection here, but there are probably other
1386			 * places that this also happens.  We must rethink
1387			 * this.
1388			 */
1389			VNET_SO_ASSERT(so);
1390			error = (*so->so_proto->pr_usrreqs->pru_send)(so,
1391			    (flags & MSG_OOB) ? PRUS_OOB :
1392			/*
1393			 * If the user set MSG_EOF, the protocol understands
1394			 * this flag and nothing left to send then use
1395			 * PRU_SEND_EOF instead of PRU_SEND.
1396			 */
1397			    ((flags & MSG_EOF) &&
1398			     (so->so_proto->pr_flags & PR_IMPLOPCL) &&
1399			     (resid <= 0)) ?
1400				PRUS_EOF :
1401			/* If there is more to send set PRUS_MORETOCOME. */
1402			    (resid > 0 && space > 0) ? PRUS_MORETOCOME : 0,
1403			    top, addr, control, td);
1404			if (dontroute) {
1405				SOCK_LOCK(so);
1406				so->so_options &= ~SO_DONTROUTE;
1407				SOCK_UNLOCK(so);
1408			}
1409			clen = 0;
1410			control = NULL;
1411			top = NULL;
1412			if (error)
1413				goto release;
1414		} while (resid && space > 0);
1415	} while (resid);
1416
1417release:
1418	sbunlock(&so->so_snd);
1419out:
1420	if (top != NULL)
1421		m_freem(top);
1422	if (control != NULL)
1423		m_freem(control);
1424	return (error);
1425}
1426
1427int
1428sosend(struct socket *so, struct sockaddr *addr, struct uio *uio,
1429    struct mbuf *top, struct mbuf *control, int flags, struct thread *td)
1430{
1431	int error;
1432
1433	CURVNET_SET(so->so_vnet);
1434	error = so->so_proto->pr_usrreqs->pru_sosend(so, addr, uio, top,
1435	    control, flags, td);
1436	CURVNET_RESTORE();
1437	return (error);
1438}
1439
1440/*
1441 * The part of soreceive() that implements reading non-inline out-of-band
1442 * data from a socket.  For more complete comments, see soreceive(), from
1443 * which this code originated.
1444 *
1445 * Note that soreceive_rcvoob(), unlike the remainder of soreceive(), is
1446 * unable to return an mbuf chain to the caller.
1447 */
1448static int
1449soreceive_rcvoob(struct socket *so, struct uio *uio, int flags)
1450{
1451	struct protosw *pr = so->so_proto;
1452	struct mbuf *m;
1453	int error;
1454
1455	KASSERT(flags & MSG_OOB, ("soreceive_rcvoob: (flags & MSG_OOB) == 0"));
1456	VNET_SO_ASSERT(so);
1457
1458	m = m_get(M_WAIT, MT_DATA);
1459	error = (*pr->pr_usrreqs->pru_rcvoob)(so, m, flags & MSG_PEEK);
1460	if (error)
1461		goto bad;
1462	do {
1463#ifdef ZERO_COPY_SOCKETS
1464		if (so_zero_copy_receive) {
1465			int disposable;
1466
1467			if ((m->m_flags & M_EXT)
1468			 && (m->m_ext.ext_type == EXT_DISPOSABLE))
1469				disposable = 1;
1470			else
1471				disposable = 0;
1472
1473			error = uiomoveco(mtod(m, void *),
1474					  min(uio->uio_resid, m->m_len),
1475					  uio, disposable);
1476		} else
1477#endif /* ZERO_COPY_SOCKETS */
1478		error = uiomove(mtod(m, void *),
1479		    (int) min(uio->uio_resid, m->m_len), uio);
1480		m = m_free(m);
1481	} while (uio->uio_resid && error == 0 && m);
1482bad:
1483	if (m != NULL)
1484		m_freem(m);
1485	return (error);
1486}
1487
1488/*
1489 * Following replacement or removal of the first mbuf on the first mbuf chain
1490 * of a socket buffer, push necessary state changes back into the socket
1491 * buffer so that other consumers see the values consistently.  'nextrecord'
1492 * is the callers locally stored value of the original value of
1493 * sb->sb_mb->m_nextpkt which must be restored when the lead mbuf changes.
1494 * NOTE: 'nextrecord' may be NULL.
1495 */
1496static __inline void
1497sockbuf_pushsync(struct sockbuf *sb, struct mbuf *nextrecord)
1498{
1499
1500	SOCKBUF_LOCK_ASSERT(sb);
1501	/*
1502	 * First, update for the new value of nextrecord.  If necessary, make
1503	 * it the first record.
1504	 */
1505	if (sb->sb_mb != NULL)
1506		sb->sb_mb->m_nextpkt = nextrecord;
1507	else
1508		sb->sb_mb = nextrecord;
1509
1510        /*
1511         * Now update any dependent socket buffer fields to reflect the new
1512         * state.  This is an expanded inline of SB_EMPTY_FIXUP(), with the
1513	 * addition of a second clause that takes care of the case where
1514	 * sb_mb has been updated, but remains the last record.
1515         */
1516        if (sb->sb_mb == NULL) {
1517                sb->sb_mbtail = NULL;
1518                sb->sb_lastrecord = NULL;
1519        } else if (sb->sb_mb->m_nextpkt == NULL)
1520                sb->sb_lastrecord = sb->sb_mb;
1521}
1522
1523
1524/*
1525 * Implement receive operations on a socket.  We depend on the way that
1526 * records are added to the sockbuf by sbappend.  In particular, each record
1527 * (mbufs linked through m_next) must begin with an address if the protocol
1528 * so specifies, followed by an optional mbuf or mbufs containing ancillary
1529 * data, and then zero or more mbufs of data.  In order to allow parallelism
1530 * between network receive and copying to user space, as well as avoid
1531 * sleeping with a mutex held, we release the socket buffer mutex during the
1532 * user space copy.  Although the sockbuf is locked, new data may still be
1533 * appended, and thus we must maintain consistency of the sockbuf during that
1534 * time.
1535 *
1536 * The caller may receive the data as a single mbuf chain by supplying an
1537 * mbuf **mp0 for use in returning the chain.  The uio is then used only for
1538 * the count in uio_resid.
1539 */
1540int
1541soreceive_generic(struct socket *so, struct sockaddr **psa, struct uio *uio,
1542    struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
1543{
1544	struct mbuf *m, **mp;
1545	int flags, error, offset;
1546	ssize_t len;
1547	struct protosw *pr = so->so_proto;
1548	struct mbuf *nextrecord;
1549	int moff, type = 0, last_m_flags, hole_break = 0;
1550	ssize_t orig_resid = uio->uio_resid;
1551
1552	mp = mp0;
1553	if (psa != NULL)
1554		*psa = NULL;
1555	if (controlp != NULL)
1556		*controlp = NULL;
1557	if (flagsp != NULL) {
1558		hole_break = *flagsp & MSG_HOLE_BREAK;
1559		*flagsp &= ~MSG_HOLE_BREAK;
1560		flags = *flagsp &~ MSG_EOR;
1561	} else
1562		flags = 0;
1563	if (flags & MSG_OOB)
1564		return (soreceive_rcvoob(so, uio, flags));
1565	if (mp != NULL)
1566		*mp = NULL;
1567	if ((pr->pr_flags & PR_WANTRCVD) && (so->so_state & SS_ISCONFIRMING)
1568	    && uio->uio_resid) {
1569		VNET_SO_ASSERT(so);
1570		(*pr->pr_usrreqs->pru_rcvd)(so, 0);
1571	}
1572
1573	error = sblock(&so->so_rcv, SBLOCKWAIT(flags));
1574	if (error)
1575		return (error);
1576
1577restart:
1578	SOCKBUF_LOCK(&so->so_rcv);
1579	m = so->so_rcv.sb_mb;
1580	/*
1581	 * If we have less data than requested, block awaiting more (subject
1582	 * to any timeout) if:
1583	 *   1. the current count is less than the low water mark, or
1584	 *   2. MSG_WAITALL is set, and it is possible to do the entire
1585	 *	receive operation at once if we block (resid <= hiwat).
1586	 *   3. MSG_DONTWAIT is not set
1587	 * If MSG_WAITALL is set but resid is larger than the receive buffer,
1588	 * we have to do the receive in sections, and thus risk returning a
1589	 * short count if a timeout or signal occurs after we start.
1590	 */
1591	if (m == NULL || (((flags & MSG_DONTWAIT) == 0 &&
1592	    so->so_rcv.sb_cc < uio->uio_resid) &&
1593	    (so->so_rcv.sb_cc < so->so_rcv.sb_lowat ||
1594	    ((flags & MSG_WAITALL) && uio->uio_resid <= so->so_rcv.sb_hiwat)) &&
1595	    m->m_nextpkt == NULL && (pr->pr_flags & PR_ATOMIC) == 0)) {
1596		KASSERT(m != NULL || !so->so_rcv.sb_cc,
1597		    ("receive: m == %p so->so_rcv.sb_cc == %u",
1598		    m, so->so_rcv.sb_cc));
1599		if (so->so_error) {
1600			if (m != NULL)
1601				goto dontblock;
1602			error = so->so_error;
1603			if ((flags & MSG_PEEK) == 0)
1604				so->so_error = 0;
1605			SOCKBUF_UNLOCK(&so->so_rcv);
1606			goto release;
1607		}
1608		SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1609		if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
1610			if (m == NULL) {
1611				SOCKBUF_UNLOCK(&so->so_rcv);
1612				goto release;
1613			} else
1614				goto dontblock;
1615		}
1616		for (; m != NULL; m = m->m_next)
1617			if (m->m_type == MT_OOBDATA  || (m->m_flags & M_EOR)) {
1618				m = so->so_rcv.sb_mb;
1619				goto dontblock;
1620			}
1621		if ((so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING)) == 0 &&
1622		    (so->so_proto->pr_flags & PR_CONNREQUIRED)) {
1623			SOCKBUF_UNLOCK(&so->so_rcv);
1624			error = ENOTCONN;
1625			goto release;
1626		}
1627		if (uio->uio_resid == 0) {
1628			SOCKBUF_UNLOCK(&so->so_rcv);
1629			goto release;
1630		}
1631		if ((so->so_state & SS_NBIO) ||
1632		    (flags & (MSG_DONTWAIT|MSG_NBIO))) {
1633			if (so->so_upcallprep.soup_receive != NULL) {
1634				so->so_upcallprep.soup_receive(so,
1635					so->so_upcallprep.soup_receive_arg,
1636					orig_resid - uio->uio_resid, uio->uio_resid);
1637			}
1638			SOCKBUF_UNLOCK(&so->so_rcv);
1639			error = EWOULDBLOCK;
1640			goto release;
1641		}
1642		SBLASTRECORDCHK(&so->so_rcv);
1643		SBLASTMBUFCHK(&so->so_rcv);
1644		error = sbwait(&so->so_rcv);
1645		SOCKBUF_UNLOCK(&so->so_rcv);
1646		if (error)
1647			goto release;
1648		goto restart;
1649	}
1650dontblock:
1651	/*
1652	 * From this point onward, we maintain 'nextrecord' as a cache of the
1653	 * pointer to the next record in the socket buffer.  We must keep the
1654	 * various socket buffer pointers and local stack versions of the
1655	 * pointers in sync, pushing out modifications before dropping the
1656	 * socket buffer mutex, and re-reading them when picking it up.
1657	 *
1658	 * Otherwise, we will race with the network stack appending new data
1659	 * or records onto the socket buffer by using inconsistent/stale
1660	 * versions of the field, possibly resulting in socket buffer
1661	 * corruption.
1662	 *
1663	 * By holding the high-level sblock(), we prevent simultaneous
1664	 * readers from pulling off the front of the socket buffer.
1665	 */
1666	SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1667	if (uio->uio_td)
1668		uio->uio_td->td_ru.ru_msgrcv++;
1669	KASSERT(m == so->so_rcv.sb_mb, ("soreceive: m != so->so_rcv.sb_mb"));
1670	SBLASTRECORDCHK(&so->so_rcv);
1671	SBLASTMBUFCHK(&so->so_rcv);
1672	nextrecord = m->m_nextpkt;
1673	if (pr->pr_flags & PR_ADDR) {
1674		KASSERT(m->m_type == MT_SONAME,
1675		    ("m->m_type == %d", m->m_type));
1676		orig_resid = 0;
1677		if (psa != NULL)
1678			*psa = sodupsockaddr(mtod(m, struct sockaddr *),
1679			    M_NOWAIT);
1680		if (flags & MSG_PEEK) {
1681			m = m->m_next;
1682		} else {
1683			sbfree(&so->so_rcv, m);
1684			so->so_rcv.sb_mb = m_free(m);
1685			m = so->so_rcv.sb_mb;
1686			sockbuf_pushsync(&so->so_rcv, nextrecord);
1687		}
1688	}
1689
1690	/*
1691	 * Process one or more MT_CONTROL mbufs present before any data mbufs
1692	 * in the first mbuf chain on the socket buffer.  If MSG_PEEK, we
1693	 * just copy the data; if !MSG_PEEK, we call into the protocol to
1694	 * perform externalization (or freeing if controlp == NULL).
1695	 */
1696	if (m != NULL && m->m_type == MT_CONTROL) {
1697		struct mbuf *cm = NULL, *cmn;
1698		struct mbuf **cme = &cm;
1699
1700		do {
1701			if (flags & MSG_PEEK) {
1702				if (controlp != NULL) {
1703					*controlp = m_copy(m, 0, m->m_len);
1704					controlp = &(*controlp)->m_next;
1705				}
1706				m = m->m_next;
1707			} else {
1708				sbfree(&so->so_rcv, m);
1709				so->so_rcv.sb_mb = m->m_next;
1710				m->m_next = NULL;
1711				*cme = m;
1712				cme = &(*cme)->m_next;
1713				m = so->so_rcv.sb_mb;
1714			}
1715		} while (m != NULL && m->m_type == MT_CONTROL);
1716		if ((flags & MSG_PEEK) == 0)
1717			sockbuf_pushsync(&so->so_rcv, nextrecord);
1718		while (cm != NULL) {
1719			cmn = cm->m_next;
1720			cm->m_next = NULL;
1721			if (pr->pr_domain->dom_externalize != NULL) {
1722				SOCKBUF_UNLOCK(&so->so_rcv);
1723				VNET_SO_ASSERT(so);
1724				error = (*pr->pr_domain->dom_externalize)
1725				    (cm, controlp);
1726				SOCKBUF_LOCK(&so->so_rcv);
1727			} else if (controlp != NULL)
1728				*controlp = cm;
1729			else
1730				m_freem(cm);
1731			if (controlp != NULL) {
1732				orig_resid = 0;
1733				while (*controlp != NULL)
1734					controlp = &(*controlp)->m_next;
1735			}
1736			cm = cmn;
1737		}
1738		if (m != NULL)
1739			nextrecord = so->so_rcv.sb_mb->m_nextpkt;
1740		else
1741			nextrecord = so->so_rcv.sb_mb;
1742		orig_resid = 0;
1743	}
1744	if (m != NULL) {
1745		if ((flags & MSG_PEEK) == 0) {
1746			KASSERT(m->m_nextpkt == nextrecord,
1747			    ("soreceive: post-control, nextrecord !sync"));
1748			if (nextrecord == NULL) {
1749				KASSERT(so->so_rcv.sb_mb == m,
1750				    ("soreceive: post-control, sb_mb!=m"));
1751				KASSERT(so->so_rcv.sb_lastrecord == m,
1752				    ("soreceive: post-control, lastrecord!=m"));
1753			}
1754		}
1755		type = m->m_type;
1756		if (type == MT_OOBDATA)
1757			flags |= MSG_OOB;
1758		last_m_flags = m->m_flags;
1759		if (hole_break && (m->m_flags & M_HOLE))
1760			flags |= MSG_HOLE_BREAK;
1761	} else {
1762		if ((flags & MSG_PEEK) == 0) {
1763			KASSERT(so->so_rcv.sb_mb == nextrecord,
1764			    ("soreceive: sb_mb != nextrecord"));
1765			if (so->so_rcv.sb_mb == NULL) {
1766				KASSERT(so->so_rcv.sb_lastrecord == NULL,
1767				    ("soreceive: sb_lastercord != NULL"));
1768			}
1769		}
1770	}
1771	SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1772	SBLASTRECORDCHK(&so->so_rcv);
1773	SBLASTMBUFCHK(&so->so_rcv);
1774
1775	/*
1776	 * Now continue to read any data mbufs off of the head of the socket
1777	 * buffer until the read request is satisfied.  Note that 'type' is
1778	 * used to store the type of any mbuf reads that have happened so far
1779	 * such that soreceive() can stop reading if the type changes, which
1780	 * causes soreceive() to return only one of regular data and inline
1781	 * out-of-band data in a single socket receive operation.
1782	 */
1783	moff = 0;
1784	offset = 0;
1785	while (m != NULL && uio->uio_resid > 0 && error == 0) {
1786		/*
1787		 * If the type of mbuf has changed since the last mbuf
1788		 * examined ('type'), end the receive operation.
1789	 	 */
1790		SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1791		if (hole_break && 
1792		    ((m->m_flags ^ last_m_flags) & M_HOLE))
1793			break;
1794		last_m_flags = m->m_flags;
1795		if (m->m_type == MT_OOBDATA) {
1796			if (type != MT_OOBDATA)
1797				break;
1798		} else if (type == MT_OOBDATA)
1799			break;
1800		else
1801		    KASSERT(m->m_type == MT_DATA,
1802			("m->m_type == %d", m->m_type));
1803		so->so_rcv.sb_state &= ~SBS_RCVATMARK;
1804		len = uio->uio_resid;
1805		if (so->so_oobmark && len > so->so_oobmark - offset)
1806			len = so->so_oobmark - offset;
1807		if (len > m->m_len - moff)
1808			len = m->m_len - moff;
1809		/*
1810		 * If mp is set, just pass back the mbufs.  Otherwise copy
1811		 * them out via the uio, then free.  Sockbuf must be
1812		 * consistent here (points to current mbuf, it points to next
1813		 * record) when we drop priority; we must note any additions
1814		 * to the sockbuf when we block interrupts again.
1815		 */
1816		if (mp == NULL) {
1817			SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1818			SBLASTRECORDCHK(&so->so_rcv);
1819			SBLASTMBUFCHK(&so->so_rcv);
1820			SOCKBUF_UNLOCK(&so->so_rcv);
1821#ifdef ZERO_COPY_SOCKETS
1822			if (so_zero_copy_receive) {
1823				int disposable;
1824
1825				if ((m->m_flags & M_EXT)
1826				 && (m->m_ext.ext_type == EXT_DISPOSABLE))
1827					disposable = 1;
1828				else
1829					disposable = 0;
1830
1831				error = uiomoveco(mtod(m, char *) + moff,
1832						  (int)len, uio,
1833						  disposable);
1834			} else
1835#endif /* ZERO_COPY_SOCKETS */
1836			if (m->m_flags & M_HOLE)
1837				error = uiofill(0, (int)len, uio);
1838			else
1839				error = uiomove(mtod(m, char *) + moff, (int)len, uio);
1840			SOCKBUF_LOCK(&so->so_rcv);
1841			if (error) {
1842				/*
1843				 * The MT_SONAME mbuf has already been removed
1844				 * from the record, so it is necessary to
1845				 * remove the data mbufs, if any, to preserve
1846				 * the invariant in the case of PR_ADDR that
1847				 * requires MT_SONAME mbufs at the head of
1848				 * each record.
1849				 */
1850				if (m && pr->pr_flags & PR_ATOMIC &&
1851				    ((flags & MSG_PEEK) == 0))
1852					(void)sbdroprecord_locked(&so->so_rcv);
1853				SOCKBUF_UNLOCK(&so->so_rcv);
1854				goto release;
1855			}
1856		} else
1857			uio->uio_resid -= len;
1858		SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1859		if (len == m->m_len - moff) {
1860			if (m->m_flags & M_EOR)
1861				flags |= MSG_EOR;
1862			if (flags & MSG_PEEK) {
1863				m = m->m_next;
1864				moff = 0;
1865			} else {
1866				nextrecord = m->m_nextpkt;
1867				sbfree(&so->so_rcv, m);
1868				if (mp != NULL) {
1869					*mp = m;
1870					mp = &m->m_next;
1871					so->so_rcv.sb_mb = m = m->m_next;
1872					*mp = NULL;
1873				} else {
1874					so->so_rcv.sb_mb = m_free(m);
1875					m = so->so_rcv.sb_mb;
1876				}
1877				sockbuf_pushsync(&so->so_rcv, nextrecord);
1878				SBLASTRECORDCHK(&so->so_rcv);
1879				SBLASTMBUFCHK(&so->so_rcv);
1880			}
1881		} else {
1882			if (flags & MSG_PEEK)
1883				moff += len;
1884			else {
1885				if (mp != NULL) {
1886					int copy_flag;
1887
1888					if (flags & MSG_DONTWAIT)
1889						copy_flag = M_DONTWAIT;
1890					else
1891						copy_flag = M_WAIT;
1892					if (copy_flag == M_WAIT)
1893						SOCKBUF_UNLOCK(&so->so_rcv);
1894					*mp = m_copym2(m, 0, len, copy_flag,
1895						       hole_break);
1896					if (copy_flag == M_WAIT)
1897						SOCKBUF_LOCK(&so->so_rcv);
1898 					if (*mp == NULL) {
1899 						/*
1900 						 * m_copym() couldn't
1901						 * allocate an mbuf.  Adjust
1902						 * uio_resid back (it was
1903						 * adjusted down by len
1904						 * bytes, which we didn't end
1905						 * up "copying" over).
1906 						 */
1907 						uio->uio_resid += len;
1908 						break;
1909 					}
1910				}
1911				if ((m->m_flags & M_HOLE) == 0)
1912					m->m_data += len;
1913				m->m_len -= len;
1914				so->so_rcv.sb_cc -= len;
1915			}
1916		}
1917		SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1918		if (so->so_oobmark) {
1919			if ((flags & MSG_PEEK) == 0) {
1920				so->so_oobmark -= len;
1921				if (so->so_oobmark == 0) {
1922					so->so_rcv.sb_state |= SBS_RCVATMARK;
1923					break;
1924				}
1925			} else {
1926				offset += len;
1927				if (offset == so->so_oobmark)
1928					break;
1929			}
1930		}
1931		if (flags & MSG_EOR)
1932			break;
1933		/*
1934		 * If the MSG_WAITALL flag is set (for non-atomic socket), we
1935		 * must not quit until "uio->uio_resid == 0" or an error
1936		 * termination.  If a signal/timeout occurs, return with a
1937		 * short count but without error.  Keep sockbuf locked
1938		 * against other readers.
1939		 */
1940		while (flags & MSG_WAITALL && m == NULL && uio->uio_resid > 0 &&
1941		    !sosendallatonce(so) && nextrecord == NULL) {
1942			SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1943			if (so->so_error || so->so_rcv.sb_state & SBS_CANTRCVMORE)
1944				break;
1945			/*
1946			 * Notify the protocol that some data has been
1947			 * drained before blocking.
1948			 */
1949			if (pr->pr_flags & PR_WANTRCVD) {
1950				SOCKBUF_UNLOCK(&so->so_rcv);
1951				VNET_SO_ASSERT(so);
1952				(*pr->pr_usrreqs->pru_rcvd)(so, flags);
1953				SOCKBUF_LOCK(&so->so_rcv);
1954			}
1955			SBLASTRECORDCHK(&so->so_rcv);
1956			SBLASTMBUFCHK(&so->so_rcv);
1957			/*
1958			 * We could receive some data while was notifying
1959			 * the protocol. Skip blocking in this case.
1960			 */
1961			if (so->so_rcv.sb_mb == NULL) {
1962				error = sbwait(&so->so_rcv);
1963				if (error) {
1964					SOCKBUF_UNLOCK(&so->so_rcv);
1965					goto release;
1966				}
1967			}
1968			m = so->so_rcv.sb_mb;
1969			if (m != NULL)
1970				nextrecord = m->m_nextpkt;
1971		}
1972	}
1973
1974	SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1975	if (m != NULL && pr->pr_flags & PR_ATOMIC) {
1976		flags |= MSG_TRUNC;
1977		if ((flags & MSG_PEEK) == 0)
1978			(void) sbdroprecord_locked(&so->so_rcv);
1979	}
1980	if ((flags & MSG_PEEK) == 0) {
1981		if (m == NULL) {
1982			/*
1983			 * First part is an inline SB_EMPTY_FIXUP().  Second
1984			 * part makes sure sb_lastrecord is up-to-date if
1985			 * there is still data in the socket buffer.
1986			 */
1987			so->so_rcv.sb_mb = nextrecord;
1988			if (so->so_rcv.sb_mb == NULL) {
1989				so->so_rcv.sb_mbtail = NULL;
1990				so->so_rcv.sb_lastrecord = NULL;
1991			} else if (nextrecord->m_nextpkt == NULL)
1992				so->so_rcv.sb_lastrecord = nextrecord;
1993
1994			if (uio->uio_resid > 0 && orig_resid != uio->uio_resid
1995			    && !sosendallatonce(so) && nextrecord == NULL) {
1996				if (so->so_upcallprep.soup_receive != NULL) {
1997					so->so_upcallprep.soup_receive(so,
1998					       so->so_upcallprep.soup_receive_arg,
1999					       orig_resid - uio->uio_resid, uio->uio_resid);
2000				}
2001			}
2002		}
2003		SBLASTRECORDCHK(&so->so_rcv);
2004		SBLASTMBUFCHK(&so->so_rcv);
2005		/*
2006		 * If soreceive() is being done from the socket callback,
2007		 * then don't need to generate ACK to peer to update window,
2008		 * since ACK will be generated on return to TCP.
2009		 */
2010		if (!(flags & MSG_SOCALLBCK) &&
2011		    (pr->pr_flags & PR_WANTRCVD)) {
2012			SOCKBUF_UNLOCK(&so->so_rcv);
2013			VNET_SO_ASSERT(so);
2014			(*pr->pr_usrreqs->pru_rcvd)(so, flags);
2015			SOCKBUF_LOCK(&so->so_rcv);
2016		}
2017	}
2018	SOCKBUF_LOCK_ASSERT(&so->so_rcv);
2019	if (orig_resid == uio->uio_resid && orig_resid &&
2020	    (flags & MSG_EOR) == 0 && (so->so_rcv.sb_state & SBS_CANTRCVMORE) == 0) {
2021		SOCKBUF_UNLOCK(&so->so_rcv);
2022		goto restart;
2023	}
2024	SOCKBUF_UNLOCK(&so->so_rcv);
2025
2026	if (flagsp != NULL)
2027		*flagsp |= flags;
2028release:
2029	sbunlock(&so->so_rcv);
2030	return (error);
2031}
2032
2033/*
2034 * Optimized version of soreceive() for stream (TCP) sockets.
2035 */
2036int
2037soreceive_stream(struct socket *so, struct sockaddr **psa, struct uio *uio,
2038    struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
2039{
2040	int len = 0, error = 0, flags, oresid, hole_break = 0;
2041	struct sockbuf *sb;
2042	struct mbuf *m, *n = NULL;
2043
2044	/* We only do stream sockets. */
2045	if (so->so_type != SOCK_STREAM)
2046		return (EINVAL);
2047	if (psa != NULL)
2048		*psa = NULL;
2049	if (controlp != NULL)
2050		return (EINVAL);
2051	if (flagsp != NULL) {
2052		hole_break = *flagsp & MSG_HOLE_BREAK;
2053		*flagsp &= ~MSG_HOLE_BREAK;
2054		flags = *flagsp &~ MSG_EOR;
2055	} else
2056		flags = 0;
2057	if (flags & MSG_OOB)
2058		return (soreceive_rcvoob(so, uio, flags));
2059	if (mp0 != NULL)
2060		*mp0 = NULL;
2061
2062	sb = &so->so_rcv;
2063
2064	/* Prevent other readers from entering the socket. */
2065	error = sblock(sb, SBLOCKWAIT(flags));
2066	if (error)
2067		goto out;
2068	SOCKBUF_LOCK(sb);
2069
2070	/* Easy one, no space to copyout anything. */
2071	if (uio->uio_resid == 0) {
2072		error = EINVAL;
2073		goto out;
2074	}
2075	oresid = uio->uio_resid;
2076
2077	/* We will never ever get anything unless we are or were connected. */
2078	if (!(so->so_state & (SS_ISCONNECTED|SS_ISDISCONNECTED))) {
2079		error = ENOTCONN;
2080		goto out;
2081	}
2082
2083restart:
2084	SOCKBUF_LOCK_ASSERT(&so->so_rcv);
2085
2086	/* Abort if socket has reported problems. */
2087	if (so->so_error) {
2088		if (sb->sb_cc > 0)
2089			goto deliver;
2090		if (oresid > uio->uio_resid)
2091			goto out;
2092		error = so->so_error;
2093		if (!(flags & MSG_PEEK))
2094			so->so_error = 0;
2095		goto out;
2096	}
2097
2098	/* Door is closed.  Deliver what is left, if any. */
2099	if (sb->sb_state & SBS_CANTRCVMORE) {
2100		if (sb->sb_cc > 0)
2101			goto deliver;
2102		else
2103			goto out;
2104	}
2105
2106	/* Socket buffer is empty and we shall not block. */
2107	if (sb->sb_cc == 0 &&
2108	    ((so->so_state & SS_NBIO) || (flags & (MSG_DONTWAIT|MSG_NBIO)))) {
2109		error = EAGAIN;
2110		goto out;
2111	}
2112
2113	/* Socket buffer got some data that we shall deliver now. */
2114	if (sb->sb_cc > 0 && !(flags & MSG_WAITALL) &&
2115	    ((sb->sb_flags & SS_NBIO) ||
2116	     (flags & (MSG_DONTWAIT|MSG_NBIO)) ||
2117	     sb->sb_cc >= sb->sb_lowat ||
2118	     sb->sb_cc >= uio->uio_resid ||
2119	     sb->sb_cc >= sb->sb_hiwat) ) {
2120		goto deliver;
2121	}
2122
2123	/* On MSG_WAITALL we must wait until all data or error arrives. */
2124	if ((flags & MSG_WAITALL) &&
2125	    (sb->sb_cc >= uio->uio_resid || sb->sb_cc >= sb->sb_lowat))
2126		goto deliver;
2127
2128	/*
2129	 * Wait and block until (more) data comes in.
2130	 * NB: Drops the sockbuf lock during wait.
2131	 */
2132	error = sbwait(sb);
2133	if (error)
2134		goto out;
2135	goto restart;
2136
2137deliver:
2138	SOCKBUF_LOCK_ASSERT(&so->so_rcv);
2139	KASSERT(sb->sb_cc > 0, ("%s: sockbuf empty", __func__));
2140	KASSERT(sb->sb_mb != NULL, ("%s: sb_mb == NULL", __func__));
2141
2142	/* Statistics. */
2143	if (uio->uio_td)
2144		uio->uio_td->td_ru.ru_msgrcv++;
2145
2146	/* Fill uio until full or current end of socket buffer is reached. */
2147	len = min(uio->uio_resid, sb->sb_cc);
2148	if (hole_break && (sb->sb_mb->m_flags & M_HOLE))
2149		flags |= MSG_HOLE_BREAK;
2150	if (mp0 != NULL) {
2151		/* Dequeue as many mbufs as possible. */
2152		if (!(flags & MSG_PEEK) && len >= sb->sb_mb->m_len) {
2153			for (*mp0 = m = sb->sb_mb;
2154			     m != NULL && m->m_len <= len;
2155			     m = m->m_next) {
2156				len -= m->m_len;
2157				uio->uio_resid -= m->m_len;
2158				sbfree(sb, m);
2159				n = m;
2160			}
2161			sb->sb_mb = m;
2162			if (sb->sb_mb == NULL)
2163				SB_EMPTY_FIXUP(sb);
2164			n->m_next = NULL;
2165		}
2166		/* Copy the remainder. */
2167		if (len > 0) {
2168			KASSERT(sb->sb_mb != NULL,
2169			    ("%s: len > 0 && sb->sb_mb empty", __func__));
2170
2171			m = m_copym2(sb->sb_mb, 0, len, M_DONTWAIT, hole_break);
2172			if (m == NULL)
2173				len = 0;	/* Don't flush data from sockbuf. */
2174			else
2175				uio->uio_resid -= m->m_len;
2176			if (*mp0 != NULL)
2177				n->m_next = m;
2178			else
2179				*mp0 = m;
2180			if (*mp0 == NULL) {
2181				error = ENOBUFS;
2182				goto out;
2183			}
2184		}
2185	} else {
2186		/* NB: Must unlock socket buffer as uiomove may sleep. */
2187		SOCKBUF_UNLOCK(sb);
2188		error = m_mbuftouio(uio, sb->sb_mb, len, hole_break);
2189		SOCKBUF_LOCK(sb);
2190		if (error)
2191			goto out;
2192	}
2193	SBLASTRECORDCHK(sb);
2194	SBLASTMBUFCHK(sb);
2195
2196	/*
2197	 * Remove the delivered data from the socket buffer unless we
2198	 * were only peeking.
2199	 */
2200	if (!(flags & MSG_PEEK)) {
2201		if (len > 0)
2202			sbdrop_locked(sb, len);
2203
2204		/* Notify protocol that we drained some data. */
2205		if ((so->so_proto->pr_flags & PR_WANTRCVD) &&
2206		    (((flags & MSG_WAITALL) && uio->uio_resid > 0) ||
2207		     !(flags & MSG_SOCALLBCK))) {
2208			SOCKBUF_UNLOCK(sb);
2209			VNET_SO_ASSERT(so);
2210			(*so->so_proto->pr_usrreqs->pru_rcvd)(so, flags);
2211			SOCKBUF_LOCK(sb);
2212		}
2213	}
2214
2215	/*
2216	 * For MSG_WAITALL we may have to loop again and wait for
2217	 * more data to come in.
2218	 */
2219	if ((flags & MSG_WAITALL) && uio->uio_resid > 0)
2220		goto restart;
2221out:
2222	if (flagsp != NULL)
2223		*flagsp |= flags;
2224
2225	SOCKBUF_LOCK_ASSERT(sb);
2226	SBLASTRECORDCHK(sb);
2227	SBLASTMBUFCHK(sb);
2228	SOCKBUF_UNLOCK(sb);
2229	sbunlock(sb);
2230	return (error);
2231}
2232
2233/*
2234 * Optimized version of soreceive() for simple datagram cases from userspace.
2235 * Unlike in the stream case, we're able to drop a datagram if copyout()
2236 * fails, and because we handle datagrams atomically, we don't need to use a
2237 * sleep lock to prevent I/O interlacing.
2238 */
2239int
2240soreceive_dgram(struct socket *so, struct sockaddr **psa, struct uio *uio,
2241    struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
2242{
2243	struct mbuf *m, *m2;
2244	int flags, error;
2245	ssize_t len;
2246	struct protosw *pr = so->so_proto;
2247	struct mbuf *nextrecord;
2248
2249	if (psa != NULL)
2250		*psa = NULL;
2251	if (controlp != NULL)
2252		*controlp = NULL;
2253	if (flagsp != NULL)
2254		flags = *flagsp &~ MSG_EOR;
2255	else
2256		flags = 0;
2257
2258	/*
2259	 * For any complicated cases, fall back to the full
2260	 * soreceive_generic().
2261	 */
2262	if (mp0 != NULL || (flags & MSG_PEEK) || (flags & MSG_OOB))
2263		return (soreceive_generic(so, psa, uio, mp0, controlp,
2264		    flagsp));
2265
2266	/*
2267	 * Enforce restrictions on use.
2268	 */
2269	KASSERT((pr->pr_flags & PR_WANTRCVD) == 0,
2270	    ("soreceive_dgram: wantrcvd"));
2271	KASSERT(pr->pr_flags & PR_ATOMIC, ("soreceive_dgram: !atomic"));
2272	KASSERT((so->so_rcv.sb_state & SBS_RCVATMARK) == 0,
2273	    ("soreceive_dgram: SBS_RCVATMARK"));
2274	KASSERT((so->so_proto->pr_flags & PR_CONNREQUIRED) == 0,
2275	    ("soreceive_dgram: P_CONNREQUIRED"));
2276
2277	/*
2278	 * Loop blocking while waiting for a datagram.
2279	 */
2280	SOCKBUF_LOCK(&so->so_rcv);
2281	while ((m = so->so_rcv.sb_mb) == NULL) {
2282		KASSERT(so->so_rcv.sb_cc == 0,
2283		    ("soreceive_dgram: sb_mb NULL but sb_cc %u",
2284		    so->so_rcv.sb_cc));
2285		if (so->so_error) {
2286			error = so->so_error;
2287			so->so_error = 0;
2288			SOCKBUF_UNLOCK(&so->so_rcv);
2289			return (error);
2290		}
2291		if (so->so_rcv.sb_state & SBS_CANTRCVMORE ||
2292		    uio->uio_resid == 0) {
2293			SOCKBUF_UNLOCK(&so->so_rcv);
2294			return (0);
2295		}
2296		if ((so->so_state & SS_NBIO) ||
2297		    (flags & (MSG_DONTWAIT|MSG_NBIO))) {
2298			SOCKBUF_UNLOCK(&so->so_rcv);
2299			return (EWOULDBLOCK);
2300		}
2301		SBLASTRECORDCHK(&so->so_rcv);
2302		SBLASTMBUFCHK(&so->so_rcv);
2303		error = sbwait(&so->so_rcv);
2304		if (error) {
2305			SOCKBUF_UNLOCK(&so->so_rcv);
2306			return (error);
2307		}
2308	}
2309	SOCKBUF_LOCK_ASSERT(&so->so_rcv);
2310
2311	if (uio->uio_td)
2312		uio->uio_td->td_ru.ru_msgrcv++;
2313	SBLASTRECORDCHK(&so->so_rcv);
2314	SBLASTMBUFCHK(&so->so_rcv);
2315	nextrecord = m->m_nextpkt;
2316	if (nextrecord == NULL) {
2317		KASSERT(so->so_rcv.sb_lastrecord == m,
2318		    ("soreceive_dgram: lastrecord != m"));
2319	}
2320
2321	KASSERT(so->so_rcv.sb_mb->m_nextpkt == nextrecord,
2322	    ("soreceive_dgram: m_nextpkt != nextrecord"));
2323
2324	/*
2325	 * Pull 'm' and its chain off the front of the packet queue.
2326	 */
2327	so->so_rcv.sb_mb = NULL;
2328	sockbuf_pushsync(&so->so_rcv, nextrecord);
2329
2330	/*
2331	 * Walk 'm's chain and free that many bytes from the socket buffer.
2332	 */
2333	for (m2 = m; m2 != NULL; m2 = m2->m_next)
2334		sbfree(&so->so_rcv, m2);
2335
2336	/*
2337	 * Do a few last checks before we let go of the lock.
2338	 */
2339	SBLASTRECORDCHK(&so->so_rcv);
2340	SBLASTMBUFCHK(&so->so_rcv);
2341	SOCKBUF_UNLOCK(&so->so_rcv);
2342
2343	if (pr->pr_flags & PR_ADDR) {
2344		KASSERT(m->m_type == MT_SONAME,
2345		    ("m->m_type == %d", m->m_type));
2346		if (psa != NULL)
2347			*psa = sodupsockaddr(mtod(m, struct sockaddr *),
2348			    M_NOWAIT);
2349		m = m_free(m);
2350	}
2351	if (m == NULL) {
2352		/* XXXRW: Can this happen? */
2353		return (0);
2354	}
2355
2356	/*
2357	 * Packet to copyout() is now in 'm' and it is disconnected from the
2358	 * queue.
2359	 *
2360	 * Process one or more MT_CONTROL mbufs present before any data mbufs
2361	 * in the first mbuf chain on the socket buffer.  We call into the
2362	 * protocol to perform externalization (or freeing if controlp ==
2363	 * NULL).
2364	 */
2365	if (m->m_type == MT_CONTROL) {
2366		struct mbuf *cm = NULL, *cmn;
2367		struct mbuf **cme = &cm;
2368
2369		do {
2370			m2 = m->m_next;
2371			m->m_next = NULL;
2372			*cme = m;
2373			cme = &(*cme)->m_next;
2374			m = m2;
2375		} while (m != NULL && m->m_type == MT_CONTROL);
2376		while (cm != NULL) {
2377			cmn = cm->m_next;
2378			cm->m_next = NULL;
2379			if (pr->pr_domain->dom_externalize != NULL) {
2380				error = (*pr->pr_domain->dom_externalize)
2381				    (cm, controlp);
2382			} else if (controlp != NULL)
2383				*controlp = cm;
2384			else
2385				m_freem(cm);
2386			if (controlp != NULL) {
2387				while (*controlp != NULL)
2388					controlp = &(*controlp)->m_next;
2389			}
2390			cm = cmn;
2391		}
2392	}
2393	KASSERT(m->m_type == MT_DATA, ("soreceive_dgram: !data"));
2394
2395	while (m != NULL && uio->uio_resid > 0) {
2396		len = uio->uio_resid;
2397		if (len > m->m_len)
2398			len = m->m_len;
2399		error = uiomove(mtod(m, char *), (int)len, uio);
2400		if (error) {
2401			m_freem(m);
2402			return (error);
2403		}
2404		if (len == m->m_len)
2405			m = m_free(m);
2406		else {
2407			m->m_data += len;
2408			m->m_len -= len;
2409		}
2410	}
2411	if (m != NULL)
2412		flags |= MSG_TRUNC;
2413	m_freem(m);
2414	if (flagsp != NULL)
2415		*flagsp |= flags;
2416	return (0);
2417}
2418
2419int
2420soreceive(struct socket *so, struct sockaddr **psa, struct uio *uio,
2421    struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
2422{
2423	int error;
2424
2425	CURVNET_SET(so->so_vnet);
2426	error = (so->so_proto->pr_usrreqs->pru_soreceive(so, psa, uio, mp0,
2427	    controlp, flagsp));
2428	CURVNET_RESTORE();
2429	return (error);
2430}
2431
2432int
2433soshutdown(struct socket *so, int how)
2434{
2435	struct protosw *pr = so->so_proto;
2436	int error;
2437
2438	if (!(how == SHUT_RD || how == SHUT_WR || how == SHUT_RDWR))
2439		return (EINVAL);
2440
2441	CURVNET_SET(so->so_vnet);
2442	if (pr->pr_usrreqs->pru_flush != NULL) {
2443	        (*pr->pr_usrreqs->pru_flush)(so, how);
2444	}
2445	if (how != SHUT_WR)
2446		sorflush(so);
2447	if (how != SHUT_RD) {
2448		error = (*pr->pr_usrreqs->pru_shutdown)(so);
2449		CURVNET_RESTORE();
2450		return (error);
2451	}
2452	CURVNET_RESTORE();
2453	return (0);
2454}
2455
2456void
2457sorflush(struct socket *so)
2458{
2459	struct sockbuf *sb = &so->so_rcv;
2460	struct protosw *pr = so->so_proto;
2461	struct sockbuf asb;
2462
2463	VNET_SO_ASSERT(so);
2464
2465	/*
2466	 * In order to avoid calling dom_dispose with the socket buffer mutex
2467	 * held, and in order to generally avoid holding the lock for a long
2468	 * time, we make a copy of the socket buffer and clear the original
2469	 * (except locks, state).  The new socket buffer copy won't have
2470	 * initialized locks so we can only call routines that won't use or
2471	 * assert those locks.
2472	 *
2473	 * Dislodge threads currently blocked in receive and wait to acquire
2474	 * a lock against other simultaneous readers before clearing the
2475	 * socket buffer.  Don't let our acquire be interrupted by a signal
2476	 * despite any existing socket disposition on interruptable waiting.
2477	 */
2478	socantrcvmore(so);
2479	(void) sblock(sb, SBL_WAIT | SBL_NOINTR);
2480
2481	/*
2482	 * Invalidate/clear most of the sockbuf structure, but leave selinfo
2483	 * and mutex data unchanged.
2484	 */
2485	SOCKBUF_LOCK(sb);
2486	bzero(&asb, offsetof(struct sockbuf, sb_startzero));
2487	bcopy(&sb->sb_startzero, &asb.sb_startzero,
2488	    sizeof(*sb) - offsetof(struct sockbuf, sb_startzero));
2489	bzero(&sb->sb_startzero,
2490	    sizeof(*sb) - offsetof(struct sockbuf, sb_startzero));
2491	SOCKBUF_UNLOCK(sb);
2492	sbunlock(sb);
2493
2494	/*
2495	 * Dispose of special rights and flush the socket buffer.  Don't call
2496	 * any unsafe routines (that rely on locks being initialized) on asb.
2497	 */
2498	if (pr->pr_flags & PR_RIGHTS && pr->pr_domain->dom_dispose != NULL)
2499		(*pr->pr_domain->dom_dispose)(asb.sb_mb);
2500	sbrelease_internal(&asb, so);
2501}
2502
2503/*
2504 * Perhaps this routine, and sooptcopyout(), below, ought to come in an
2505 * additional variant to handle the case where the option value needs to be
2506 * some kind of integer, but not a specific size.  In addition to their use
2507 * here, these functions are also called by the protocol-level pr_ctloutput()
2508 * routines.
2509 */
2510int
2511sooptcopyin(struct sockopt *sopt, void *buf, size_t len, size_t minlen)
2512{
2513	size_t	valsize;
2514
2515	/*
2516	 * If the user gives us more than we wanted, we ignore it, but if we
2517	 * don't get the minimum length the caller wants, we return EINVAL.
2518	 * On success, sopt->sopt_valsize is set to however much we actually
2519	 * retrieved.
2520	 */
2521	if ((valsize = sopt->sopt_valsize) < minlen)
2522		return EINVAL;
2523	if (valsize > len)
2524		sopt->sopt_valsize = valsize = len;
2525
2526	if (sopt->sopt_td != NULL)
2527		return (copyin(sopt->sopt_val, buf, valsize));
2528
2529	bcopy(sopt->sopt_val, buf, valsize);
2530	return (0);
2531}
2532
2533/*
2534 * Kernel version of setsockopt(2).
2535 *
2536 * XXX: optlen is size_t, not socklen_t
2537 */
2538int
2539so_setsockopt(struct socket *so, int level, int optname, void *optval,
2540    size_t optlen)
2541{
2542	struct sockopt sopt;
2543
2544	sopt.sopt_level = level;
2545	sopt.sopt_name = optname;
2546	sopt.sopt_dir = SOPT_SET;
2547	sopt.sopt_val = optval;
2548	sopt.sopt_valsize = optlen;
2549	sopt.sopt_td = NULL;
2550	return (sosetopt(so, &sopt));
2551}
2552
2553int
2554sosetopt(struct socket *so, struct sockopt *sopt)
2555{
2556	int	error, optval;
2557	struct	linger l;
2558	struct	timeval tv;
2559	u_long  val;
2560	uint32_t val32;
2561#ifdef MAC
2562	struct mac extmac;
2563#endif
2564#ifdef PROMISCUOUS_INET
2565	struct in_l2info l2info;
2566#endif
2567
2568	CURVNET_SET(so->so_vnet);
2569	error = 0;
2570	if (sopt->sopt_level != SOL_SOCKET) {
2571		if (so->so_proto->pr_ctloutput != NULL) {
2572			error = (*so->so_proto->pr_ctloutput)(so, sopt);
2573			CURVNET_RESTORE();
2574			return (error);
2575		}
2576		error = ENOPROTOOPT;
2577	} else {
2578		switch (sopt->sopt_name) {
2579#ifdef INET
2580		case SO_ACCEPTFILTER:
2581			error = do_setopt_accept_filter(so, sopt);
2582			if (error)
2583				goto bad;
2584			break;
2585#endif
2586		case SO_LINGER:
2587			error = sooptcopyin(sopt, &l, sizeof l, sizeof l);
2588			if (error)
2589				goto bad;
2590
2591			SOCK_LOCK(so);
2592			so->so_linger = l.l_linger;
2593			if (l.l_onoff)
2594				so->so_options |= SO_LINGER;
2595			else
2596				so->so_options &= ~SO_LINGER;
2597			SOCK_UNLOCK(so);
2598			break;
2599
2600		case SO_DEBUG:
2601		case SO_KEEPALIVE:
2602		case SO_DONTROUTE:
2603		case SO_USELOOPBACK:
2604		case SO_BROADCAST:
2605		case SO_REUSEADDR:
2606		case SO_REUSEPORT:
2607		case SO_OOBINLINE:
2608		case SO_TIMESTAMP:
2609		case SO_BINTIME:
2610		case SO_NOSIGPIPE:
2611		case SO_NO_DDP:
2612		case SO_NO_OFFLOAD:
2613			error = sooptcopyin(sopt, &optval, sizeof optval,
2614					    sizeof optval);
2615			if (error)
2616				goto bad;
2617			SOCK_LOCK(so);
2618			if (optval)
2619				so->so_options |= sopt->sopt_name;
2620			else
2621				so->so_options &= ~sopt->sopt_name;
2622			SOCK_UNLOCK(so);
2623			break;
2624
2625		case SO_SETFIB:
2626			error = sooptcopyin(sopt, &optval, sizeof optval,
2627					    sizeof optval);
2628			if (optval < 0 || optval >= rt_numfibs) {
2629				error = EINVAL;
2630				goto bad;
2631			}
2632			if (((so->so_proto->pr_domain->dom_family == PF_INET) ||
2633			   (so->so_proto->pr_domain->dom_family == PF_INET6) ||
2634			   (so->so_proto->pr_domain->dom_family == PF_ROUTE))) {
2635				so->so_fibnum = optval;
2636				/* Note: ignore error */
2637				if (so->so_proto->pr_ctloutput)
2638					(*so->so_proto->pr_ctloutput)(so, sopt);
2639			} else {
2640				so->so_fibnum = 0;
2641			}
2642			break;
2643
2644		case SO_USER_COOKIE:
2645			error = sooptcopyin(sopt, &val32, sizeof val32,
2646					    sizeof val32);
2647			if (error)
2648				goto bad;
2649			so->so_user_cookie = val32;
2650			break;
2651
2652		case SO_L2INFO:
2653#ifdef PROMISCUOUS_INET
2654			error = sooptcopyin(sopt, &l2info, sizeof l2info,
2655					    sizeof l2info);
2656			if (error)
2657				goto bad;
2658
2659			if ((so->so_proto->pr_domain->dom_family == PF_INET) ||
2660			    (so->so_proto->pr_domain->dom_family == PF_INET6)) {
2661				
2662				if (l2info.inl2i_tagstack.inl2t_cnt >
2663				    IN_L2INFO_MAX_TAGS) {
2664					error = EINVAL;
2665					goto bad;
2666				}
2667				
2668				SOCK_LOCK(so);
2669				in_promisc_l2info_copy(so->so_l2info, &l2info);
2670
2671				/* Note: ignore error */
2672				if (so->so_proto->pr_ctloutput)
2673					(*so->so_proto->pr_ctloutput)(so, sopt);
2674				SOCK_UNLOCK(so);
2675			} else {
2676				error = ENOPROTOOPT;
2677			}
2678#else
2679			error = EOPNOTSUPP;
2680#endif /* PROMISCUOUS_INET */
2681			break;
2682
2683		case SO_PASSIVE:
2684		case SO_PROMISC:
2685#if defined(PROMISCUOUS_INET) || defined(PASSIVE_INET)
2686			error = sooptcopyin(sopt, &optval, sizeof optval,
2687					    sizeof optval);
2688			if (error) {
2689				goto bad;
2690			}
2691			SOCK_LOCK(so);
2692			if (optval)
2693				so->so_options |= sopt->sopt_name;
2694			else
2695				so->so_options &= ~sopt->sopt_name;
2696			SOCK_UNLOCK(so);
2697
2698			if ((so->so_proto->pr_domain->dom_family == PF_INET) ||
2699			    (so->so_proto->pr_domain->dom_family == PF_INET6)) {
2700				/* Note: ignore error */
2701				if (so->so_proto->pr_ctloutput)
2702					(*so->so_proto->pr_ctloutput)(so, sopt);
2703			}
2704#else
2705			error = EOPNOTSUPP;
2706#endif
2707			break;
2708
2709		case SO_SNDBUF:
2710		case SO_RCVBUF:
2711		case SO_SNDLOWAT:
2712		case SO_RCVLOWAT:
2713			error = sooptcopyin(sopt, &optval, sizeof optval,
2714					    sizeof optval);
2715			if (error)
2716				goto bad;
2717
2718			/*
2719			 * Values < 1 make no sense for any of these options,
2720			 * so disallow them.
2721			 */
2722			if (optval < 1) {
2723				error = EINVAL;
2724				goto bad;
2725			}
2726
2727			switch (sopt->sopt_name) {
2728			case SO_SNDBUF:
2729			case SO_RCVBUF:
2730				if (sbreserve(sopt->sopt_name == SO_SNDBUF ?
2731				    &so->so_snd : &so->so_rcv, (u_long)optval,
2732				    so, curthread) == 0) {
2733					error = ENOBUFS;
2734					goto bad;
2735				}
2736				(sopt->sopt_name == SO_SNDBUF ? &so->so_snd :
2737				    &so->so_rcv)->sb_flags &= ~SB_AUTOSIZE;
2738				break;
2739
2740			/*
2741			 * Make sure the low-water is never greater than the
2742			 * high-water.
2743			 */
2744			case SO_SNDLOWAT:
2745				SOCKBUF_LOCK(&so->so_snd);
2746				so->so_snd.sb_lowat =
2747				    (optval > so->so_snd.sb_hiwat) ?
2748				    so->so_snd.sb_hiwat : optval;
2749				SOCKBUF_UNLOCK(&so->so_snd);
2750				break;
2751			case SO_RCVLOWAT:
2752				SOCKBUF_LOCK(&so->so_rcv);
2753				so->so_rcv.sb_lowat =
2754				    (optval > so->so_rcv.sb_hiwat) ?
2755				    so->so_rcv.sb_hiwat : optval;
2756				SOCKBUF_UNLOCK(&so->so_rcv);
2757				break;
2758			}
2759			break;
2760
2761		case SO_SNDTIMEO:
2762		case SO_RCVTIMEO:
2763#ifdef COMPAT_FREEBSD32
2764			if (SV_CURPROC_FLAG(SV_ILP32)) {
2765				struct timeval32 tv32;
2766
2767				error = sooptcopyin(sopt, &tv32, sizeof tv32,
2768				    sizeof tv32);
2769				CP(tv32, tv, tv_sec);
2770				CP(tv32, tv, tv_usec);
2771			} else
2772#endif
2773				error = sooptcopyin(sopt, &tv, sizeof tv,
2774				    sizeof tv);
2775			if (error)
2776				goto bad;
2777
2778			/* assert(hz > 0); */
2779			if (tv.tv_sec < 0 || tv.tv_sec > INT_MAX / hz ||
2780			    tv.tv_usec < 0 || tv.tv_usec >= 1000000) {
2781				error = EDOM;
2782				goto bad;
2783			}
2784			/* assert(tick > 0); */
2785			/* assert(ULONG_MAX - INT_MAX >= 1000000); */
2786			val = (u_long)(tv.tv_sec * hz) + tv.tv_usec / tick;
2787			if (val > INT_MAX) {
2788				error = EDOM;
2789				goto bad;
2790			}
2791			if (val == 0 && tv.tv_usec != 0)
2792				val = 1;
2793
2794			switch (sopt->sopt_name) {
2795			case SO_SNDTIMEO:
2796				so->so_snd.sb_timeo = val;
2797				break;
2798			case SO_RCVTIMEO:
2799				so->so_rcv.sb_timeo = val;
2800				break;
2801			}
2802			break;
2803
2804		case SO_LABEL:
2805#ifdef MAC
2806			error = sooptcopyin(sopt, &extmac, sizeof extmac,
2807			    sizeof extmac);
2808			if (error)
2809				goto bad;
2810			error = mac_setsockopt_label(sopt->sopt_td->td_ucred,
2811			    so, &extmac);
2812#else
2813			error = EOPNOTSUPP;
2814#endif
2815			break;
2816
2817		default:
2818			error = ENOPROTOOPT;
2819			break;
2820		}
2821		if (error == 0 && so->so_proto->pr_ctloutput != NULL)
2822			(void)(*so->so_proto->pr_ctloutput)(so, sopt);
2823	}
2824bad:
2825	CURVNET_RESTORE();
2826	return (error);
2827}
2828
2829/*
2830 * Helper routine for getsockopt.
2831 */
2832int
2833sooptcopyout(struct sockopt *sopt, const void *buf, size_t len)
2834{
2835	int	error;
2836	size_t	valsize;
2837
2838	error = 0;
2839
2840	/*
2841	 * Documented get behavior is that we always return a value, possibly
2842	 * truncated to fit in the user's buffer.  Traditional behavior is
2843	 * that we always tell the user precisely how much we copied, rather
2844	 * than something useful like the total amount we had available for
2845	 * her.  Note that this interface is not idempotent; the entire
2846	 * answer must generated ahead of time.
2847	 */
2848	valsize = min(len, sopt->sopt_valsize);
2849	sopt->sopt_valsize = valsize;
2850	if (sopt->sopt_val != NULL) {
2851		if (sopt->sopt_td != NULL)
2852			error = copyout(buf, sopt->sopt_val, valsize);
2853		else
2854			bcopy(buf, sopt->sopt_val, valsize);
2855	}
2856	return (error);
2857}
2858
2859/*
2860 * Kernel version of getsockopt(2).
2861 *
2862 * XXX: optlen is size_t, not socklen_t
2863 */
2864int
2865so_getsockopt(struct socket *so, int level, int optname, void *optval,
2866    size_t *optlen)
2867{
2868	struct sockopt sopt;
2869	int error;
2870
2871	sopt.sopt_level = level;
2872	sopt.sopt_name = optname;
2873	sopt.sopt_dir = SOPT_GET;
2874	sopt.sopt_val = optval;
2875	sopt.sopt_valsize = *optlen;
2876	sopt.sopt_td = NULL;
2877
2878	error = sogetopt(so, &sopt);
2879
2880	*optlen = sopt.sopt_valsize;
2881
2882	return (error);
2883}
2884
2885int
2886sogetopt(struct socket *so, struct sockopt *sopt)
2887{
2888	int	error, optval;
2889	struct	linger l;
2890	struct	timeval tv;
2891#ifdef MAC
2892	struct mac extmac;
2893#endif
2894#ifdef PROMISCUOUS_INET
2895	struct in_l2info l2info;
2896#endif
2897
2898	CURVNET_SET(so->so_vnet);
2899	error = 0;
2900	if (sopt->sopt_level != SOL_SOCKET) {
2901		if (so->so_proto->pr_ctloutput != NULL)
2902			error = (*so->so_proto->pr_ctloutput)(so, sopt);
2903		else
2904			error = ENOPROTOOPT;
2905		CURVNET_RESTORE();
2906		return (error);
2907	} else {
2908		switch (sopt->sopt_name) {
2909#ifdef INET
2910		case SO_ACCEPTFILTER:
2911			error = do_getopt_accept_filter(so, sopt);
2912			break;
2913#endif
2914		case SO_LINGER:
2915			SOCK_LOCK(so);
2916			l.l_onoff = so->so_options & SO_LINGER;
2917			l.l_linger = so->so_linger;
2918			SOCK_UNLOCK(so);
2919			error = sooptcopyout(sopt, &l, sizeof l);
2920			break;
2921
2922		case SO_USELOOPBACK:
2923		case SO_DONTROUTE:
2924		case SO_DEBUG:
2925		case SO_KEEPALIVE:
2926		case SO_REUSEADDR:
2927		case SO_REUSEPORT:
2928		case SO_BROADCAST:
2929		case SO_OOBINLINE:
2930		case SO_ACCEPTCONN:
2931		case SO_TIMESTAMP:
2932		case SO_BINTIME:
2933		case SO_NOSIGPIPE:
2934			optval = so->so_options & sopt->sopt_name;
2935integer:
2936			error = sooptcopyout(sopt, &optval, sizeof optval);
2937			break;
2938
2939		case SO_TYPE:
2940			optval = so->so_type;
2941			goto integer;
2942
2943		case SO_PROTOCOL:
2944			optval = so->so_proto->pr_protocol;
2945			goto integer;
2946
2947		case SO_ERROR:
2948			SOCK_LOCK(so);
2949			optval = so->so_error;
2950			so->so_error = 0;
2951			SOCK_UNLOCK(so);
2952			goto integer;
2953
2954		case SO_L2INFO:
2955#ifdef PROMISCUOUS_INET
2956			if ((so->so_proto->pr_domain->dom_family == PF_INET) ||
2957			    (so->so_proto->pr_domain->dom_family == PF_INET6)) {
2958				SOCK_LOCK(so);
2959				in_promisc_l2info_copy(&l2info, so->so_l2info);
2960				SOCK_UNLOCK(so);
2961
2962				error = sooptcopyout(sopt, &l2info, sizeof l2info);
2963			} else {
2964				error = ENOPROTOOPT;
2965			}
2966#else
2967			error = EOPNOTSUPP;
2968#endif
2969			break;
2970
2971		case SO_SNDBUF:
2972			optval = so->so_snd.sb_hiwat;
2973			goto integer;
2974
2975		case SO_RCVBUF:
2976			optval = so->so_rcv.sb_hiwat;
2977			goto integer;
2978
2979		case SO_SNDLOWAT:
2980			optval = so->so_snd.sb_lowat;
2981			goto integer;
2982
2983		case SO_RCVLOWAT:
2984			optval = so->so_rcv.sb_lowat;
2985			goto integer;
2986
2987		case SO_SNDTIMEO:
2988		case SO_RCVTIMEO:
2989			optval = (sopt->sopt_name == SO_SNDTIMEO ?
2990				  so->so_snd.sb_timeo : so->so_rcv.sb_timeo);
2991
2992			tv.tv_sec = optval / hz;
2993			tv.tv_usec = (optval % hz) * tick;
2994#ifdef COMPAT_FREEBSD32
2995			if (SV_CURPROC_FLAG(SV_ILP32)) {
2996				struct timeval32 tv32;
2997
2998				CP(tv, tv32, tv_sec);
2999				CP(tv, tv32, tv_usec);
3000				error = sooptcopyout(sopt, &tv32, sizeof tv32);
3001			} else
3002#endif
3003				error = sooptcopyout(sopt, &tv, sizeof tv);
3004			break;
3005
3006		case SO_LABEL:
3007#ifdef MAC
3008			error = sooptcopyin(sopt, &extmac, sizeof(extmac),
3009			    sizeof(extmac));
3010			if (error)
3011				goto bad;
3012			error = mac_getsockopt_label(sopt->sopt_td->td_ucred,
3013			    so, &extmac);
3014			if (error)
3015				goto bad;
3016			error = sooptcopyout(sopt, &extmac, sizeof extmac);
3017#else
3018			error = EOPNOTSUPP;
3019#endif
3020			break;
3021
3022		case SO_PEERLABEL:
3023#ifdef MAC
3024			error = sooptcopyin(sopt, &extmac, sizeof(extmac),
3025			    sizeof(extmac));
3026			if (error)
3027				goto bad;
3028			error = mac_getsockopt_peerlabel(
3029			    sopt->sopt_td->td_ucred, so, &extmac);
3030			if (error)
3031				goto bad;
3032			error = sooptcopyout(sopt, &extmac, sizeof extmac);
3033#else
3034			error = EOPNOTSUPP;
3035#endif
3036			break;
3037
3038		case SO_LISTENQLIMIT:
3039			optval = so->so_qlimit;
3040			goto integer;
3041
3042		case SO_LISTENQLEN:
3043			optval = so->so_qlen;
3044			goto integer;
3045
3046		case SO_LISTENINCQLEN:
3047			optval = so->so_incqlen;
3048			goto integer;
3049
3050		default:
3051			error = ENOPROTOOPT;
3052			break;
3053		}
3054	}
3055#ifdef MAC
3056bad:
3057#endif
3058	CURVNET_RESTORE();
3059	return (error);
3060}
3061
3062/* XXX; prepare mbuf for (__FreeBSD__ < 3) routines. */
3063int
3064soopt_getm(struct sockopt *sopt, struct mbuf **mp)
3065{
3066	struct mbuf *m, *m_prev;
3067	int sopt_size = sopt->sopt_valsize;
3068
3069	MGET(m, sopt->sopt_td ? M_WAIT : M_DONTWAIT, MT_DATA);
3070	if (m == NULL)
3071		return ENOBUFS;
3072	if (sopt_size > MLEN) {
3073		MCLGET(m, sopt->sopt_td ? M_WAIT : M_DONTWAIT);
3074		if ((m->m_flags & M_EXT) == 0) {
3075			m_free(m);
3076			return ENOBUFS;
3077		}
3078		m->m_len = min(MCLBYTES, sopt_size);
3079	} else {
3080		m->m_len = min(MLEN, sopt_size);
3081	}
3082	sopt_size -= m->m_len;
3083	*mp = m;
3084	m_prev = m;
3085
3086	while (sopt_size) {
3087		MGET(m, sopt->sopt_td ? M_WAIT : M_DONTWAIT, MT_DATA);
3088		if (m == NULL) {
3089			m_freem(*mp);
3090			return ENOBUFS;
3091		}
3092		if (sopt_size > MLEN) {
3093			MCLGET(m, sopt->sopt_td != NULL ? M_WAIT :
3094			    M_DONTWAIT);
3095			if ((m->m_flags & M_EXT) == 0) {
3096				m_freem(m);
3097				m_freem(*mp);
3098				return ENOBUFS;
3099			}
3100			m->m_len = min(MCLBYTES, sopt_size);
3101		} else {
3102			m->m_len = min(MLEN, sopt_size);
3103		}
3104		sopt_size -= m->m_len;
3105		m_prev->m_next = m;
3106		m_prev = m;
3107	}
3108	return (0);
3109}
3110
3111/* XXX; copyin sopt data into mbuf chain for (__FreeBSD__ < 3) routines. */
3112int
3113soopt_mcopyin(struct sockopt *sopt, struct mbuf *m)
3114{
3115	struct mbuf *m0 = m;
3116
3117	if (sopt->sopt_val == NULL)
3118		return (0);
3119	while (m != NULL && sopt->sopt_valsize >= m->m_len) {
3120		if (sopt->sopt_td != NULL) {
3121			int error;
3122
3123			error = copyin(sopt->sopt_val, mtod(m, char *),
3124				       m->m_len);
3125			if (error != 0) {
3126				m_freem(m0);
3127				return(error);
3128			}
3129		} else
3130			bcopy(sopt->sopt_val, mtod(m, char *), m->m_len);
3131		sopt->sopt_valsize -= m->m_len;
3132		sopt->sopt_val = (char *)sopt->sopt_val + m->m_len;
3133		m = m->m_next;
3134	}
3135	if (m != NULL) /* should be allocated enoughly at ip6_sooptmcopyin() */
3136		panic("ip6_sooptmcopyin");
3137	return (0);
3138}
3139
3140/* XXX; copyout mbuf chain data into soopt for (__FreeBSD__ < 3) routines. */
3141int
3142soopt_mcopyout(struct sockopt *sopt, struct mbuf *m)
3143{
3144	struct mbuf *m0 = m;
3145	size_t valsize = 0;
3146
3147	if (sopt->sopt_val == NULL)
3148		return (0);
3149	while (m != NULL && sopt->sopt_valsize >= m->m_len) {
3150		if (sopt->sopt_td != NULL) {
3151			int error;
3152
3153			error = copyout(mtod(m, char *), sopt->sopt_val,
3154				       m->m_len);
3155			if (error != 0) {
3156				m_freem(m0);
3157				return(error);
3158			}
3159		} else
3160			bcopy(mtod(m, char *), sopt->sopt_val, m->m_len);
3161	       sopt->sopt_valsize -= m->m_len;
3162	       sopt->sopt_val = (char *)sopt->sopt_val + m->m_len;
3163	       valsize += m->m_len;
3164	       m = m->m_next;
3165	}
3166	if (m != NULL) {
3167		/* enough soopt buffer should be given from user-land */
3168		m_freem(m0);
3169		return(EINVAL);
3170	}
3171	sopt->sopt_valsize = valsize;
3172	return (0);
3173}
3174
3175/*
3176 * sohasoutofband(): protocol notifies socket layer of the arrival of new
3177 * out-of-band data, which will then notify socket consumers.
3178 */
3179void
3180sohasoutofband(struct socket *so)
3181{
3182
3183	if (so->so_sigio != NULL)
3184		pgsigio(&so->so_sigio, SIGURG, 0);
3185	selwakeuppri(&so->so_rcv.sb_sel, PSOCK);
3186}
3187
3188int
3189sopoll(struct socket *so, int events, struct ucred *active_cred,
3190    struct thread *td)
3191{
3192
3193	/*
3194	 * We do not need to set or assert curvnet as long as everyone uses
3195	 * sopoll_generic().
3196	 */
3197	return (so->so_proto->pr_usrreqs->pru_sopoll(so, events, active_cred,
3198	    td));
3199}
3200
3201int
3202sopoll_generic(struct socket *so, int events, struct ucred *active_cred,
3203    struct thread *td)
3204{
3205	int revents = 0;
3206
3207	SOCKBUF_LOCK(&so->so_snd);
3208	SOCKBUF_LOCK(&so->so_rcv);
3209	if (events & (POLLIN | POLLRDNORM))
3210		if (soreadabledata(so))
3211			revents |= events & (POLLIN | POLLRDNORM);
3212
3213	if (events & (POLLOUT | POLLWRNORM))
3214		if (sowriteable(so))
3215			revents |= events & (POLLOUT | POLLWRNORM);
3216
3217	if (events & (POLLPRI | POLLRDBAND))
3218		if (so->so_oobmark || (so->so_rcv.sb_state & SBS_RCVATMARK))
3219			revents |= events & (POLLPRI | POLLRDBAND);
3220
3221	if ((events & POLLINIGNEOF) == 0) {
3222		if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
3223			revents |= events & (POLLIN | POLLRDNORM);
3224			if (so->so_snd.sb_state & SBS_CANTSENDMORE)
3225				revents |= POLLHUP;
3226		}
3227	}
3228
3229	if (revents == 0) {
3230		if (events & (POLLIN | POLLPRI | POLLRDNORM | POLLRDBAND)) {
3231			selrecord(td, &so->so_rcv.sb_sel);
3232			so->so_rcv.sb_flags |= SB_SEL;
3233		}
3234
3235		if (events & (POLLOUT | POLLWRNORM)) {
3236			selrecord(td, &so->so_snd.sb_sel);
3237			so->so_snd.sb_flags |= SB_SEL;
3238		}
3239	}
3240
3241	SOCKBUF_UNLOCK(&so->so_rcv);
3242	SOCKBUF_UNLOCK(&so->so_snd);
3243	return (revents);
3244}
3245
3246int
3247soo_kqfilter(struct file *fp, struct knote *kn)
3248{
3249	struct socket *so = kn->kn_fp->f_data;
3250	struct sockbuf *sb;
3251
3252	switch (kn->kn_filter) {
3253	case EVFILT_READ:
3254		if (so->so_options & SO_ACCEPTCONN)
3255			kn->kn_fop = &solisten_filtops;
3256		else
3257			kn->kn_fop = &soread_filtops;
3258		sb = &so->so_rcv;
3259		break;
3260	case EVFILT_WRITE:
3261		kn->kn_fop = &sowrite_filtops;
3262		sb = &so->so_snd;
3263		break;
3264	default:
3265		return (EINVAL);
3266	}
3267
3268	SOCKBUF_LOCK(sb);
3269	knlist_add(&sb->sb_sel.si_note, kn, 1);
3270	sb->sb_flags |= SB_KNOTE;
3271	SOCKBUF_UNLOCK(sb);
3272	return (0);
3273}
3274
3275/*
3276 * Some routines that return EOPNOTSUPP for entry points that are not
3277 * supported by a protocol.  Fill in as needed.
3278 */
3279int
3280pru_accept_notsupp(struct socket *so, struct sockaddr **nam)
3281{
3282
3283	return EOPNOTSUPP;
3284}
3285
3286int
3287pru_attach_notsupp(struct socket *so, int proto, struct thread *td)
3288{
3289
3290	return EOPNOTSUPP;
3291}
3292
3293int
3294pru_bind_notsupp(struct socket *so, struct sockaddr *nam, struct thread *td)
3295{
3296
3297	return EOPNOTSUPP;
3298}
3299
3300int
3301pru_connect_notsupp(struct socket *so, struct sockaddr *nam, struct thread *td)
3302{
3303
3304	return EOPNOTSUPP;
3305}
3306
3307int
3308pru_connect2_notsupp(struct socket *so1, struct socket *so2)
3309{
3310
3311	return EOPNOTSUPP;
3312}
3313
3314int
3315pru_control_notsupp(struct socket *so, u_long cmd, caddr_t data,
3316    struct ifnet *ifp, struct thread *td)
3317{
3318
3319	return EOPNOTSUPP;
3320}
3321
3322int
3323pru_disconnect_notsupp(struct socket *so)
3324{
3325
3326	return EOPNOTSUPP;
3327}
3328
3329int
3330pru_listen_notsupp(struct socket *so, int backlog, struct thread *td)
3331{
3332
3333	return EOPNOTSUPP;
3334}
3335
3336int
3337pru_peeraddr_notsupp(struct socket *so, struct sockaddr **nam)
3338{
3339
3340	return EOPNOTSUPP;
3341}
3342
3343int
3344pru_rcvd_notsupp(struct socket *so, int flags)
3345{
3346
3347	return EOPNOTSUPP;
3348}
3349
3350int
3351pru_rcvoob_notsupp(struct socket *so, struct mbuf *m, int flags)
3352{
3353
3354	return EOPNOTSUPP;
3355}
3356
3357int
3358pru_send_notsupp(struct socket *so, int flags, struct mbuf *m,
3359    struct sockaddr *addr, struct mbuf *control, struct thread *td)
3360{
3361
3362	return EOPNOTSUPP;
3363}
3364
3365/*
3366 * This isn't really a ``null'' operation, but it's the default one and
3367 * doesn't do anything destructive.
3368 */
3369int
3370pru_sense_null(struct socket *so, struct stat *sb)
3371{
3372
3373	sb->st_blksize = so->so_snd.sb_hiwat;
3374	return 0;
3375}
3376
3377int
3378pru_shutdown_notsupp(struct socket *so)
3379{
3380
3381	return EOPNOTSUPP;
3382}
3383
3384int
3385pru_sockaddr_notsupp(struct socket *so, struct sockaddr **nam)
3386{
3387
3388	return EOPNOTSUPP;
3389}
3390
3391int
3392pru_sosend_notsupp(struct socket *so, struct sockaddr *addr, struct uio *uio,
3393    struct mbuf *top, struct mbuf *control, int flags, struct thread *td)
3394{
3395
3396	return EOPNOTSUPP;
3397}
3398
3399int
3400pru_soreceive_notsupp(struct socket *so, struct sockaddr **paddr,
3401    struct uio *uio, struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
3402{
3403
3404	return EOPNOTSUPP;
3405}
3406
3407int
3408pru_sopoll_notsupp(struct socket *so, int events, struct ucred *cred,
3409    struct thread *td)
3410{
3411
3412	return EOPNOTSUPP;
3413}
3414
3415static void
3416filt_sordetach(struct knote *kn)
3417{
3418	struct socket *so = kn->kn_fp->f_data;
3419
3420	SOCKBUF_LOCK(&so->so_rcv);
3421	knlist_remove(&so->so_rcv.sb_sel.si_note, kn, 1);
3422	if (knlist_empty(&so->so_rcv.sb_sel.si_note))
3423		so->so_rcv.sb_flags &= ~SB_KNOTE;
3424	SOCKBUF_UNLOCK(&so->so_rcv);
3425}
3426
3427/*ARGSUSED*/
3428static int
3429filt_soread(struct knote *kn, long hint)
3430{
3431	struct socket *so;
3432
3433	so = kn->kn_fp->f_data;
3434	SOCKBUF_LOCK_ASSERT(&so->so_rcv);
3435
3436	kn->kn_data = so->so_rcv.sb_cc - so->so_rcv.sb_ctl;
3437	if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
3438		kn->kn_flags |= EV_EOF;
3439		kn->kn_fflags = so->so_error;
3440		return (1);
3441	} else if (so->so_error)	/* temporary udp error */
3442		return (1);
3443	else if (kn->kn_sfflags & NOTE_LOWAT)
3444		return (kn->kn_data >= kn->kn_sdata);
3445	else
3446		return (so->so_rcv.sb_cc >= so->so_rcv.sb_lowat);
3447}
3448
3449static void
3450filt_sowdetach(struct knote *kn)
3451{
3452	struct socket *so = kn->kn_fp->f_data;
3453
3454	SOCKBUF_LOCK(&so->so_snd);
3455	knlist_remove(&so->so_snd.sb_sel.si_note, kn, 1);
3456	if (knlist_empty(&so->so_snd.sb_sel.si_note))
3457		so->so_snd.sb_flags &= ~SB_KNOTE;
3458	SOCKBUF_UNLOCK(&so->so_snd);
3459}
3460
3461/*ARGSUSED*/
3462static int
3463filt_sowrite(struct knote *kn, long hint)
3464{
3465	struct socket *so;
3466
3467	so = kn->kn_fp->f_data;
3468	SOCKBUF_LOCK_ASSERT(&so->so_snd);
3469	kn->kn_data = sbspace(&so->so_snd);
3470	if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
3471		kn->kn_flags |= EV_EOF;
3472		kn->kn_fflags = so->so_error;
3473		return (1);
3474	} else if (so->so_error)	/* temporary udp error */
3475		return (1);
3476	else if (((so->so_state & SS_ISCONNECTED) == 0) &&
3477	    (so->so_proto->pr_flags & PR_CONNREQUIRED))
3478		return (0);
3479	else if (kn->kn_sfflags & NOTE_LOWAT)
3480		return (kn->kn_data >= kn->kn_sdata);
3481	else
3482		return (kn->kn_data >= so->so_snd.sb_lowat);
3483}
3484
3485/*ARGSUSED*/
3486static int
3487filt_solisten(struct knote *kn, long hint)
3488{
3489	struct socket *so = kn->kn_fp->f_data;
3490
3491	kn->kn_data = so->so_qlen;
3492	return (! TAILQ_EMPTY(&so->so_comp));
3493}
3494
3495int
3496socheckuid(struct socket *so, uid_t uid)
3497{
3498
3499	if (so == NULL)
3500		return (EPERM);
3501	if (so->so_cred->cr_uid != uid)
3502		return (EPERM);
3503	return (0);
3504}
3505
3506static int
3507sysctl_somaxconn(SYSCTL_HANDLER_ARGS)
3508{
3509	int error;
3510	int val;
3511
3512	val = somaxconn;
3513	error = sysctl_handle_int(oidp, &val, 0, req);
3514	if (error || !req->newptr )
3515		return (error);
3516
3517	if (val < 1 || val > USHRT_MAX)
3518		return (EINVAL);
3519
3520	somaxconn = val;
3521	return (0);
3522}
3523
3524/*
3525 * These functions are used by protocols to notify the socket layer (and its
3526 * consumers) of state changes in the sockets driven by protocol-side events.
3527 */
3528
3529/*
3530 * Procedures to manipulate state flags of socket and do appropriate wakeups.
3531 *
3532 * Normal sequence from the active (originating) side is that
3533 * soisconnecting() is called during processing of connect() call, resulting
3534 * in an eventual call to soisconnected() if/when the connection is
3535 * established.  When the connection is torn down soisdisconnecting() is
3536 * called during processing of disconnect() call, and soisdisconnected() is
3537 * called when the connection to the peer is totally severed.  The semantics
3538 * of these routines are such that connectionless protocols can call
3539 * soisconnected() and soisdisconnected() only, bypassing the in-progress
3540 * calls when setting up a ``connection'' takes no time.
3541 *
3542 * From the passive side, a socket is created with two queues of sockets:
3543 * so_incomp for connections in progress and so_comp for connections already
3544 * made and awaiting user acceptance.  As a protocol is preparing incoming
3545 * connections, it creates a socket structure queued on so_incomp by calling
3546 * sonewconn().  When the connection is established, soisconnected() is
3547 * called, and transfers the socket structure to so_comp, making it available
3548 * to accept().
3549 *
3550 * If a socket is closed with sockets on either so_incomp or so_comp, these
3551 * sockets are dropped.
3552 *
3553 * If higher-level protocols are implemented in the kernel, the wakeups done
3554 * here will sometimes cause software-interrupt process scheduling.
3555 */
3556void
3557soisconnecting(struct socket *so)
3558{
3559
3560	SOCK_LOCK(so);
3561	so->so_state &= ~(SS_ISCONNECTED|SS_ISDISCONNECTING);
3562	so->so_state |= SS_ISCONNECTING;
3563	SOCK_UNLOCK(so);
3564}
3565
3566void
3567soisconnected(struct socket *so)
3568{
3569	struct socket *head;	
3570	int ret;
3571
3572restart:
3573	ACCEPT_LOCK();
3574	SOCK_LOCK(so);
3575	so->so_state &= ~(SS_ISCONNECTING|SS_ISDISCONNECTING|SS_ISCONFIRMING);
3576	so->so_state |= SS_ISCONNECTED;
3577	head = so->so_head;
3578	if (head != NULL && (so->so_qstate & SQ_INCOMP)) {
3579		if ((so->so_options & SO_ACCEPTFILTER) == 0) {
3580			SOCK_UNLOCK(so);
3581			TAILQ_REMOVE(&head->so_incomp, so, so_list);
3582			head->so_incqlen--;
3583			so->so_qstate &= ~SQ_INCOMP;
3584			TAILQ_INSERT_TAIL(&head->so_comp, so, so_list);
3585			head->so_qlen++;
3586			so->so_qstate |= SQ_COMP;
3587			ACCEPT_UNLOCK();
3588			sorwakeup(head);
3589			wakeup_one(&head->so_timeo);
3590		} else {
3591			ACCEPT_UNLOCK();
3592			soupcall_set(so, SO_RCV,
3593			    head->so_accf->so_accept_filter->accf_callback,
3594			    head->so_accf->so_accept_filter_arg);
3595			so->so_options &= ~SO_ACCEPTFILTER;
3596			ret = head->so_accf->so_accept_filter->accf_callback(so,
3597			    head->so_accf->so_accept_filter_arg, M_DONTWAIT);
3598			if (ret == SU_ISCONNECTED)
3599				soupcall_clear(so, SO_RCV);
3600			SOCK_UNLOCK(so);
3601			if (ret == SU_ISCONNECTED)
3602				goto restart;
3603		}
3604		return;
3605	}
3606	SOCK_UNLOCK(so);
3607	ACCEPT_UNLOCK();
3608	wakeup(&so->so_timeo);
3609	sorwakeup(so);
3610	sowwakeup(so);
3611}
3612
3613void
3614soisdisconnecting(struct socket *so)
3615{
3616
3617	/*
3618	 * Note: This code assumes that SOCK_LOCK(so) and
3619	 * SOCKBUF_LOCK(&so->so_rcv) are the same.
3620	 */
3621	SOCKBUF_LOCK(&so->so_rcv);
3622	so->so_state &= ~SS_ISCONNECTING;
3623	so->so_state |= SS_ISDISCONNECTING;
3624	so->so_rcv.sb_state |= SBS_CANTRCVMORE;
3625	sorwakeup_locked(so);
3626	SOCKBUF_LOCK(&so->so_snd);
3627	so->so_snd.sb_state |= SBS_CANTSENDMORE;
3628	sowwakeup_locked(so);
3629	wakeup(&so->so_timeo);
3630}
3631
3632void
3633soisdisconnected(struct socket *so)
3634{
3635
3636	/*
3637	 * Note: This code assumes that SOCK_LOCK(so) and
3638	 * SOCKBUF_LOCK(&so->so_rcv) are the same.
3639	 */
3640	SOCKBUF_LOCK(&so->so_rcv);
3641	so->so_state &= ~(SS_ISCONNECTING|SS_ISCONNECTED|SS_ISDISCONNECTING);
3642	so->so_state |= SS_ISDISCONNECTED;
3643	so->so_rcv.sb_state |= SBS_CANTRCVMORE;
3644	sorwakeup_locked(so);
3645	SOCKBUF_LOCK(&so->so_snd);
3646	so->so_snd.sb_state |= SBS_CANTSENDMORE;
3647	sbdrop_locked(&so->so_snd, so->so_snd.sb_cc);
3648	sowwakeup_locked(so);
3649	wakeup(&so->so_timeo);
3650}
3651
3652/*
3653 * Make a copy of a sockaddr in a malloced buffer of type M_SONAME.
3654 */
3655struct sockaddr *
3656sodupsockaddr(const struct sockaddr *sa, int mflags)
3657{
3658	struct sockaddr *sa2;
3659
3660	sa2 = malloc(sa->sa_len, M_SONAME, mflags);
3661	if (sa2)
3662		bcopy(sa, sa2, sa->sa_len);
3663	return sa2;
3664}
3665
3666/*
3667 * Register per-socket buffer upcalls.
3668 */
3669void
3670soupcall_set(struct socket *so, int which,
3671    int (*func)(struct socket *, void *, int), void *arg)
3672{
3673	struct sockbuf *sb;
3674	
3675	switch (which) {
3676	case SO_RCV:
3677		sb = &so->so_rcv;
3678		break;
3679	case SO_SND:
3680		sb = &so->so_snd;
3681		break;
3682	default:
3683		panic("soupcall_set: bad which");
3684	}
3685	SOCKBUF_LOCK_ASSERT(sb);
3686#if 0
3687	/* XXX: accf_http actually wants to do this on purpose. */
3688	KASSERT(sb->sb_upcall == NULL, ("soupcall_set: overwriting upcall"));
3689#endif
3690	sb->sb_upcall = func;
3691	sb->sb_upcallarg = arg;
3692	sb->sb_flags |= SB_UPCALL;
3693}
3694
3695void
3696soupcall_clear(struct socket *so, int which)
3697{
3698	struct sockbuf *sb;
3699
3700	switch (which) {
3701	case SO_RCV:
3702		sb = &so->so_rcv;
3703		break;
3704	case SO_SND:
3705		sb = &so->so_snd;
3706		break;
3707	default:
3708		panic("soupcall_clear: bad which");
3709	}
3710	SOCKBUF_LOCK_ASSERT(sb);
3711	KASSERT(sb->sb_upcall != NULL, ("soupcall_clear: no upcall to clear"));
3712	sb->sb_upcall = NULL;
3713	sb->sb_upcallarg = NULL;
3714	sb->sb_flags &= ~SB_UPCALL;
3715}
3716
3717int
3718souserctx_alloc(struct socket *so)
3719{
3720	int result;
3721
3722	SOCK_LOCK(so);
3723	if (SOMAXUSERCTX == so->so_user_ctx_count)
3724		result = -1;
3725	else
3726		result = so->so_user_ctx_count++;
3727	SOCK_UNLOCK(so);
3728
3729	return (result);
3730}
3731
3732/*
3733 * Create an external-format (``xsocket'') structure using the information in
3734 * the kernel-format socket structure pointed to by so.  This is done to
3735 * reduce the spew of irrelevant information over this interface, to isolate
3736 * user code from changes in the kernel structure, and potentially to provide
3737 * information-hiding if we decide that some of this information should be
3738 * hidden from users.
3739 */
3740void
3741sotoxsocket(struct socket *so, struct xsocket *xso)
3742{
3743
3744	xso->xso_len = sizeof *xso;
3745	xso->xso_so = so;
3746	xso->so_type = so->so_type;
3747	xso->so_options = so->so_options;
3748	xso->so_linger = so->so_linger;
3749	xso->so_state = so->so_state;
3750	xso->so_pcb = so->so_pcb;
3751	xso->xso_protocol = so->so_proto->pr_protocol;
3752	xso->xso_family = so->so_proto->pr_domain->dom_family;
3753	xso->so_qlen = so->so_qlen;
3754	xso->so_incqlen = so->so_incqlen;
3755	xso->so_qlimit = so->so_qlimit;
3756	xso->so_timeo = so->so_timeo;
3757	xso->so_error = so->so_error;
3758	xso->so_pgid = so->so_sigio ? so->so_sigio->sio_pgid : 0;
3759	xso->so_oobmark = so->so_oobmark;
3760	sbtoxsockbuf(&so->so_snd, &xso->so_snd);
3761	sbtoxsockbuf(&so->so_rcv, &xso->so_rcv);
3762	xso->so_uid = so->so_cred->cr_uid;
3763}
3764
3765
3766/*
3767 * Socket accessor functions to provide external consumers with
3768 * a safe interface to socket state
3769 *
3770 */
3771
3772void
3773so_listeners_apply_all(struct socket *so, void (*func)(struct socket *, void *), void *arg)
3774{
3775	
3776	TAILQ_FOREACH(so, &so->so_comp, so_list)
3777		func(so, arg);
3778}
3779
3780struct sockbuf *
3781so_sockbuf_rcv(struct socket *so)
3782{
3783
3784	return (&so->so_rcv);
3785}
3786
3787struct sockbuf *
3788so_sockbuf_snd(struct socket *so)
3789{
3790
3791	return (&so->so_snd);
3792}
3793
3794int
3795so_state_get(const struct socket *so)
3796{
3797
3798	return (so->so_state);
3799}
3800
3801void
3802so_state_set(struct socket *so, int val)
3803{
3804
3805	so->so_state = val;
3806}
3807
3808int
3809so_options_get(const struct socket *so)
3810{
3811
3812	return (so->so_options);
3813}
3814
3815void
3816so_options_set(struct socket *so, int val)
3817{
3818
3819	so->so_options = val;
3820}
3821
3822int
3823so_error_get(const struct socket *so)
3824{
3825
3826	return (so->so_error);
3827}
3828
3829void
3830so_error_set(struct socket *so, int val)
3831{
3832
3833	so->so_error = val;
3834}
3835
3836int
3837so_linger_get(const struct socket *so)
3838{
3839
3840	return (so->so_linger);
3841}
3842
3843void
3844so_linger_set(struct socket *so, int val)
3845{
3846
3847	so->so_linger = val;
3848}
3849
3850struct protosw *
3851so_protosw_get(const struct socket *so)
3852{
3853
3854	return (so->so_proto);
3855}
3856
3857void
3858so_protosw_set(struct socket *so, struct protosw *val)
3859{
3860
3861	so->so_proto = val;
3862}
3863
3864void
3865so_sorwakeup(struct socket *so)
3866{
3867
3868	sorwakeup(so);
3869}
3870
3871void
3872so_sowwakeup(struct socket *so)
3873{
3874
3875	sowwakeup(so);
3876}
3877
3878void
3879so_sorwakeup_locked(struct socket *so)
3880{
3881
3882	sorwakeup_locked(so);
3883}
3884
3885void
3886so_sowwakeup_locked(struct socket *so)
3887{
3888
3889	sowwakeup_locked(so);
3890}
3891
3892void
3893so_lock(struct socket *so)
3894{
3895	SOCK_LOCK(so);
3896}
3897
3898void
3899so_unlock(struct socket *so)
3900{
3901	SOCK_UNLOCK(so);
3902}