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