uipc_socket.c revision 177232
1/*-
2 * Copyright (c) 1982, 1986, 1988, 1990, 1993
3 *	The Regents of the University of California.
4 * Copyright (c) 2004 The FreeBSD Foundation
5 * Copyright (c) 2004-2007 Robert N. M. Watson
6 * All rights reserved.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 * 1. Redistributions of source code must retain the above copyright
12 *    notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 *    notice, this list of conditions and the following disclaimer in the
15 *    documentation and/or other materials provided with the distribution.
16 * 4. Neither the name of the University nor the names of its contributors
17 *    may be used to endorse or promote products derived from this software
18 *    without specific prior written permission.
19 *
20 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30 * SUCH DAMAGE.
31 *
32 *	@(#)uipc_socket.c	8.3 (Berkeley) 4/15/94
33 */
34
35/*
36 * Comments on the socket life cycle:
37 *
38 * soalloc() sets of socket layer state for a socket, called only by
39 * socreate() and sonewconn().  Socket layer private.
40 *
41 * sodealloc() tears down socket layer state for a socket, called only by
42 * sofree() and sonewconn().  Socket layer private.
43 *
44 * pru_attach() associates protocol layer state with an allocated socket;
45 * called only once, may fail, aborting socket allocation.  This is called
46 * from socreate() and sonewconn().  Socket layer private.
47 *
48 * pru_detach() disassociates protocol layer state from an attached socket,
49 * and will be called exactly once for sockets in which pru_attach() has
50 * been successfully called.  If pru_attach() returned an error,
51 * pru_detach() will not be called.  Socket layer private.
52 *
53 * pru_abort() and pru_close() notify the protocol layer that the last
54 * consumer of a socket is starting to tear down the socket, and that the
55 * protocol should terminate the connection.  Historically, pru_abort() also
56 * detached protocol state from the socket state, but this is no longer the
57 * case.
58 *
59 * socreate() creates a socket and attaches protocol state.  This is a public
60 * interface that may be used by socket layer consumers to create new
61 * sockets.
62 *
63 * sonewconn() creates a socket and attaches protocol state.  This is a
64 * public interface  that may be used by protocols to create new sockets when
65 * a new connection is received and will be available for accept() on a
66 * listen socket.
67 *
68 * soclose() destroys a socket after possibly waiting for it to disconnect.
69 * This is a public interface that socket consumers should use to close and
70 * release a socket when done with it.
71 *
72 * soabort() destroys a socket without waiting for it to disconnect (used
73 * only for incoming connections that are already partially or fully
74 * connected).  This is used internally by the socket layer when clearing
75 * listen socket queues (due to overflow or close on the listen socket), but
76 * is also a public interface protocols may use to abort connections in
77 * their incomplete listen queues should they no longer be required.  Sockets
78 * placed in completed connection listen queues should not be aborted for
79 * reasons described in the comment above the soclose() implementation.  This
80 * is not a general purpose close routine, and except in the specific
81 * circumstances described here, should not be used.
82 *
83 * sofree() will free a socket and its protocol state if all references on
84 * the socket have been released, and is the public interface to attempt to
85 * free a socket when a reference is removed.  This is a socket layer private
86 * interface.
87 *
88 * NOTE: In addition to socreate() and soclose(), which provide a single
89 * socket reference to the consumer to be managed as required, there are two
90 * calls to explicitly manage socket references, soref(), and sorele().
91 * Currently, these are generally required only when transitioning a socket
92 * from a listen queue to a file descriptor, in order to prevent garbage
93 * collection of the socket at an untimely moment.  For a number of reasons,
94 * these interfaces are not preferred, and should be avoided.
95 */
96
97#include <sys/cdefs.h>
98__FBSDID("$FreeBSD: head/sys/kern/uipc_socket.c 177232 2008-03-16 06:21:30Z sobomax $");
99
100#include "opt_inet.h"
101#include "opt_mac.h"
102#include "opt_zero.h"
103#include "opt_compat.h"
104
105#include <sys/param.h>
106#include <sys/systm.h>
107#include <sys/fcntl.h>
108#include <sys/limits.h>
109#include <sys/lock.h>
110#include <sys/mac.h>
111#include <sys/malloc.h>
112#include <sys/mbuf.h>
113#include <sys/mutex.h>
114#include <sys/domain.h>
115#include <sys/file.h>			/* for struct knote */
116#include <sys/kernel.h>
117#include <sys/event.h>
118#include <sys/eventhandler.h>
119#include <sys/poll.h>
120#include <sys/proc.h>
121#include <sys/protosw.h>
122#include <sys/socket.h>
123#include <sys/socketvar.h>
124#include <sys/resourcevar.h>
125#include <sys/signalvar.h>
126#include <sys/stat.h>
127#include <sys/sx.h>
128#include <sys/sysctl.h>
129#include <sys/uio.h>
130#include <sys/jail.h>
131
132#include <security/mac/mac_framework.h>
133
134#include <vm/uma.h>
135
136#ifdef COMPAT_IA32
137#include <sys/mount.h>
138#include <compat/freebsd32/freebsd32.h>
139
140extern struct sysentvec ia32_freebsd_sysvec;
141#endif
142
143static int	soreceive_rcvoob(struct socket *so, struct uio *uio,
144		    int flags);
145
146static void	filt_sordetach(struct knote *kn);
147static int	filt_soread(struct knote *kn, long hint);
148static void	filt_sowdetach(struct knote *kn);
149static int	filt_sowrite(struct knote *kn, long hint);
150static int	filt_solisten(struct knote *kn, long hint);
151
152static struct filterops solisten_filtops =
153	{ 1, NULL, filt_sordetach, filt_solisten };
154static struct filterops soread_filtops =
155	{ 1, NULL, filt_sordetach, filt_soread };
156static struct filterops sowrite_filtops =
157	{ 1, NULL, filt_sowdetach, filt_sowrite };
158
159uma_zone_t socket_zone;
160so_gen_t	so_gencnt;	/* generation count for sockets */
161
162int	maxsockets;
163
164MALLOC_DEFINE(M_SONAME, "soname", "socket name");
165MALLOC_DEFINE(M_PCB, "pcb", "protocol control block");
166
167static int somaxconn = SOMAXCONN;
168static int sysctl_somaxconn(SYSCTL_HANDLER_ARGS);
169/* XXX: we dont have SYSCTL_USHORT */
170SYSCTL_PROC(_kern_ipc, KIPC_SOMAXCONN, somaxconn, CTLTYPE_UINT | CTLFLAG_RW,
171    0, sizeof(int), sysctl_somaxconn, "I", "Maximum pending socket connection "
172    "queue size");
173static int numopensockets;
174SYSCTL_INT(_kern_ipc, OID_AUTO, numopensockets, CTLFLAG_RD,
175    &numopensockets, 0, "Number of open sockets");
176#ifdef ZERO_COPY_SOCKETS
177/* These aren't static because they're used in other files. */
178int so_zero_copy_send = 1;
179int so_zero_copy_receive = 1;
180SYSCTL_NODE(_kern_ipc, OID_AUTO, zero_copy, CTLFLAG_RD, 0,
181    "Zero copy controls");
182SYSCTL_INT(_kern_ipc_zero_copy, OID_AUTO, receive, CTLFLAG_RW,
183    &so_zero_copy_receive, 0, "Enable zero copy receive");
184SYSCTL_INT(_kern_ipc_zero_copy, OID_AUTO, send, CTLFLAG_RW,
185    &so_zero_copy_send, 0, "Enable zero copy send");
186#endif /* ZERO_COPY_SOCKETS */
187
188/*
189 * accept_mtx locks down per-socket fields relating to accept queues.  See
190 * socketvar.h for an annotation of the protected fields of struct socket.
191 */
192struct mtx accept_mtx;
193MTX_SYSINIT(accept_mtx, &accept_mtx, "accept", MTX_DEF);
194
195/*
196 * so_global_mtx protects so_gencnt, numopensockets, and the per-socket
197 * so_gencnt field.
198 */
199static struct mtx so_global_mtx;
200MTX_SYSINIT(so_global_mtx, &so_global_mtx, "so_glabel", MTX_DEF);
201
202/*
203 * General IPC sysctl name space, used by sockets and a variety of other IPC
204 * types.
205 */
206SYSCTL_NODE(_kern, KERN_IPC, ipc, CTLFLAG_RW, 0, "IPC");
207
208/*
209 * Sysctl to get and set the maximum global sockets limit.  Notify protocols
210 * of the change so that they can update their dependent limits as required.
211 */
212static int
213sysctl_maxsockets(SYSCTL_HANDLER_ARGS)
214{
215	int error, newmaxsockets;
216
217	newmaxsockets = maxsockets;
218	error = sysctl_handle_int(oidp, &newmaxsockets, 0, req);
219	if (error == 0 && req->newptr) {
220		if (newmaxsockets > maxsockets) {
221			maxsockets = newmaxsockets;
222			if (maxsockets > ((maxfiles / 4) * 3)) {
223				maxfiles = (maxsockets * 5) / 4;
224				maxfilesperproc = (maxfiles * 9) / 10;
225				EVENTHANDLER_INVOKE(maxfiles_change);
226			}
227			EVENTHANDLER_INVOKE(maxsockets_change);
228		} else
229			error = EINVAL;
230	}
231	return (error);
232}
233
234SYSCTL_PROC(_kern_ipc, OID_AUTO, maxsockets, CTLTYPE_INT|CTLFLAG_RW,
235    &maxsockets, 0, sysctl_maxsockets, "IU",
236    "Maximum number of sockets avaliable");
237
238/*
239 * Initialise maxsockets.
240 */
241static void init_maxsockets(void *ignored)
242{
243	TUNABLE_INT_FETCH("kern.ipc.maxsockets", &maxsockets);
244	maxsockets = imax(maxsockets, imax(maxfiles, nmbclusters));
245}
246SYSINIT(param, SI_SUB_TUNABLES, SI_ORDER_ANY, init_maxsockets, NULL);
247
248/*
249 * Socket operation routines.  These routines are called by the routines in
250 * sys_socket.c or from a system process, and implement the semantics of
251 * socket operations by switching out to the protocol specific routines.
252 */
253
254/*
255 * Get a socket structure from our zone, and initialize it.  Note that it
256 * would probably be better to allocate socket and PCB at the same time, but
257 * I'm not convinced that all the protocols can be easily modified to do
258 * this.
259 *
260 * soalloc() returns a socket with a ref count of 0.
261 */
262static struct socket *
263soalloc(void)
264{
265	struct socket *so;
266
267	so = uma_zalloc(socket_zone, M_NOWAIT | M_ZERO);
268	if (so == NULL)
269		return (NULL);
270#ifdef MAC
271	if (mac_socket_init(so, M_NOWAIT) != 0) {
272		uma_zfree(socket_zone, so);
273		return (NULL);
274	}
275#endif
276	SOCKBUF_LOCK_INIT(&so->so_snd, "so_snd");
277	SOCKBUF_LOCK_INIT(&so->so_rcv, "so_rcv");
278	sx_init(&so->so_snd.sb_sx, "so_snd_sx");
279	sx_init(&so->so_rcv.sb_sx, "so_rcv_sx");
280	TAILQ_INIT(&so->so_aiojobq);
281	mtx_lock(&so_global_mtx);
282	so->so_gencnt = ++so_gencnt;
283	++numopensockets;
284	mtx_unlock(&so_global_mtx);
285	return (so);
286}
287
288/*
289 * Free the storage associated with a socket at the socket layer, tear down
290 * locks, labels, etc.  All protocol state is assumed already to have been
291 * torn down (and possibly never set up) by the caller.
292 */
293static void
294sodealloc(struct socket *so)
295{
296
297	KASSERT(so->so_count == 0, ("sodealloc(): so_count %d", so->so_count));
298	KASSERT(so->so_pcb == NULL, ("sodealloc(): so_pcb != NULL"));
299
300	mtx_lock(&so_global_mtx);
301	so->so_gencnt = ++so_gencnt;
302	--numopensockets;	/* Could be below, but faster here. */
303	mtx_unlock(&so_global_mtx);
304	if (so->so_rcv.sb_hiwat)
305		(void)chgsbsize(so->so_cred->cr_uidinfo,
306		    &so->so_rcv.sb_hiwat, 0, RLIM_INFINITY);
307	if (so->so_snd.sb_hiwat)
308		(void)chgsbsize(so->so_cred->cr_uidinfo,
309		    &so->so_snd.sb_hiwat, 0, RLIM_INFINITY);
310#ifdef INET
311	/* remove acccept filter if one is present. */
312	if (so->so_accf != NULL)
313		do_setopt_accept_filter(so, NULL);
314#endif
315#ifdef MAC
316	mac_socket_destroy(so);
317#endif
318	crfree(so->so_cred);
319	sx_destroy(&so->so_snd.sb_sx);
320	sx_destroy(&so->so_rcv.sb_sx);
321	SOCKBUF_LOCK_DESTROY(&so->so_snd);
322	SOCKBUF_LOCK_DESTROY(&so->so_rcv);
323	uma_zfree(socket_zone, so);
324}
325
326/*
327 * socreate returns a socket with a ref count of 1.  The socket should be
328 * closed with soclose().
329 */
330int
331socreate(int dom, struct socket **aso, int type, int proto,
332    struct ucred *cred, struct thread *td)
333{
334	struct protosw *prp;
335	struct socket *so;
336	int error;
337
338	if (proto)
339		prp = pffindproto(dom, proto, type);
340	else
341		prp = pffindtype(dom, type);
342
343	if (prp == NULL || prp->pr_usrreqs->pru_attach == NULL ||
344	    prp->pr_usrreqs->pru_attach == pru_attach_notsupp)
345		return (EPROTONOSUPPORT);
346
347	if (jailed(cred) && jail_socket_unixiproute_only &&
348	    prp->pr_domain->dom_family != PF_LOCAL &&
349	    prp->pr_domain->dom_family != PF_INET &&
350	    prp->pr_domain->dom_family != PF_ROUTE) {
351		return (EPROTONOSUPPORT);
352	}
353
354	if (prp->pr_type != type)
355		return (EPROTOTYPE);
356	so = soalloc();
357	if (so == NULL)
358		return (ENOBUFS);
359
360	TAILQ_INIT(&so->so_incomp);
361	TAILQ_INIT(&so->so_comp);
362	so->so_type = type;
363	so->so_cred = crhold(cred);
364	so->so_proto = prp;
365#ifdef MAC
366	mac_socket_create(cred, so);
367#endif
368	knlist_init(&so->so_rcv.sb_sel.si_note, SOCKBUF_MTX(&so->so_rcv),
369	    NULL, NULL, NULL);
370	knlist_init(&so->so_snd.sb_sel.si_note, SOCKBUF_MTX(&so->so_snd),
371	    NULL, NULL, NULL);
372	so->so_count = 1;
373	/*
374	 * Auto-sizing of socket buffers is managed by the protocols and
375	 * the appropriate flags must be set in the pru_attach function.
376	 */
377	error = (*prp->pr_usrreqs->pru_attach)(so, proto, td);
378	if (error) {
379		KASSERT(so->so_count == 1, ("socreate: so_count %d",
380		    so->so_count));
381		so->so_count = 0;
382		sodealloc(so);
383		return (error);
384	}
385	*aso = so;
386	return (0);
387}
388
389#ifdef REGRESSION
390static int regression_sonewconn_earlytest = 1;
391SYSCTL_INT(_regression, OID_AUTO, sonewconn_earlytest, CTLFLAG_RW,
392    &regression_sonewconn_earlytest, 0, "Perform early sonewconn limit test");
393#endif
394
395/*
396 * When an attempt at a new connection is noted on a socket which accepts
397 * connections, sonewconn is called.  If the connection is possible (subject
398 * to space constraints, etc.) then we allocate a new structure, propoerly
399 * linked into the data structure of the original socket, and return this.
400 * Connstatus may be 0, or SO_ISCONFIRMING, or SO_ISCONNECTED.
401 *
402 * Note: the ref count on the socket is 0 on return.
403 */
404struct socket *
405sonewconn(struct socket *head, int connstatus)
406{
407	struct socket *so;
408	int over;
409
410	ACCEPT_LOCK();
411	over = (head->so_qlen > 3 * head->so_qlimit / 2);
412	ACCEPT_UNLOCK();
413#ifdef REGRESSION
414	if (regression_sonewconn_earlytest && over)
415#else
416	if (over)
417#endif
418		return (NULL);
419	so = soalloc();
420	if (so == NULL)
421		return (NULL);
422	if ((head->so_options & SO_ACCEPTFILTER) != 0)
423		connstatus = 0;
424	so->so_head = head;
425	so->so_type = head->so_type;
426	so->so_options = head->so_options &~ SO_ACCEPTCONN;
427	so->so_linger = head->so_linger;
428	so->so_state = head->so_state | SS_NOFDREF;
429	so->so_proto = head->so_proto;
430	so->so_cred = crhold(head->so_cred);
431#ifdef MAC
432	SOCK_LOCK(head);
433	mac_socket_newconn(head, so);
434	SOCK_UNLOCK(head);
435#endif
436	knlist_init(&so->so_rcv.sb_sel.si_note, SOCKBUF_MTX(&so->so_rcv),
437	    NULL, NULL, NULL);
438	knlist_init(&so->so_snd.sb_sel.si_note, SOCKBUF_MTX(&so->so_snd),
439	    NULL, NULL, NULL);
440	if (soreserve(so, head->so_snd.sb_hiwat, head->so_rcv.sb_hiwat) ||
441	    (*so->so_proto->pr_usrreqs->pru_attach)(so, 0, NULL)) {
442		sodealloc(so);
443		return (NULL);
444	}
445	so->so_rcv.sb_lowat = head->so_rcv.sb_lowat;
446	so->so_snd.sb_lowat = head->so_snd.sb_lowat;
447	so->so_rcv.sb_timeo = head->so_rcv.sb_timeo;
448	so->so_snd.sb_timeo = head->so_snd.sb_timeo;
449	so->so_rcv.sb_flags |= head->so_rcv.sb_flags & SB_AUTOSIZE;
450	so->so_snd.sb_flags |= head->so_snd.sb_flags & SB_AUTOSIZE;
451	so->so_state |= connstatus;
452	ACCEPT_LOCK();
453	if (connstatus) {
454		TAILQ_INSERT_TAIL(&head->so_comp, so, so_list);
455		so->so_qstate |= SQ_COMP;
456		head->so_qlen++;
457	} else {
458		/*
459		 * Keep removing sockets from the head until there's room for
460		 * us to insert on the tail.  In pre-locking revisions, this
461		 * was a simple if(), but as we could be racing with other
462		 * threads and soabort() requires dropping locks, we must
463		 * loop waiting for the condition to be true.
464		 */
465		while (head->so_incqlen > head->so_qlimit) {
466			struct socket *sp;
467			sp = TAILQ_FIRST(&head->so_incomp);
468			TAILQ_REMOVE(&head->so_incomp, sp, so_list);
469			head->so_incqlen--;
470			sp->so_qstate &= ~SQ_INCOMP;
471			sp->so_head = NULL;
472			ACCEPT_UNLOCK();
473			soabort(sp);
474			ACCEPT_LOCK();
475		}
476		TAILQ_INSERT_TAIL(&head->so_incomp, so, so_list);
477		so->so_qstate |= SQ_INCOMP;
478		head->so_incqlen++;
479	}
480	ACCEPT_UNLOCK();
481	if (connstatus) {
482		sorwakeup(head);
483		wakeup_one(&head->so_timeo);
484	}
485	return (so);
486}
487
488int
489sobind(struct socket *so, struct sockaddr *nam, struct thread *td)
490{
491
492	return ((*so->so_proto->pr_usrreqs->pru_bind)(so, nam, td));
493}
494
495/*
496 * solisten() transitions a socket from a non-listening state to a listening
497 * state, but can also be used to update the listen queue depth on an
498 * existing listen socket.  The protocol will call back into the sockets
499 * layer using solisten_proto_check() and solisten_proto() to check and set
500 * socket-layer listen state.  Call backs are used so that the protocol can
501 * acquire both protocol and socket layer locks in whatever order is required
502 * by the protocol.
503 *
504 * Protocol implementors are advised to hold the socket lock across the
505 * socket-layer test and set to avoid races at the socket layer.
506 */
507int
508solisten(struct socket *so, int backlog, struct thread *td)
509{
510
511	return ((*so->so_proto->pr_usrreqs->pru_listen)(so, backlog, td));
512}
513
514int
515solisten_proto_check(struct socket *so)
516{
517
518	SOCK_LOCK_ASSERT(so);
519
520	if (so->so_state & (SS_ISCONNECTED | SS_ISCONNECTING |
521	    SS_ISDISCONNECTING))
522		return (EINVAL);
523	return (0);
524}
525
526void
527solisten_proto(struct socket *so, int backlog)
528{
529
530	SOCK_LOCK_ASSERT(so);
531
532	if (backlog < 0 || backlog > somaxconn)
533		backlog = somaxconn;
534	so->so_qlimit = backlog;
535	so->so_options |= SO_ACCEPTCONN;
536}
537
538/*
539 * Attempt to free a socket.  This should really be sotryfree().
540 *
541 * sofree() will succeed if:
542 *
543 * - There are no outstanding file descriptor references or related consumers
544 *   (so_count == 0).
545 *
546 * - The socket has been closed by user space, if ever open (SS_NOFDREF).
547 *
548 * - The protocol does not have an outstanding strong reference on the socket
549 *   (SS_PROTOREF).
550 *
551 * - The socket is not in a completed connection queue, so a process has been
552 *   notified that it is present.  If it is removed, the user process may
553 *   block in accept() despite select() saying the socket was ready.
554 *
555 * Otherwise, it will quietly abort so that a future call to sofree(), when
556 * conditions are right, can succeed.
557 */
558void
559sofree(struct socket *so)
560{
561	struct protosw *pr = so->so_proto;
562	struct socket *head;
563
564	ACCEPT_LOCK_ASSERT();
565	SOCK_LOCK_ASSERT(so);
566
567	if ((so->so_state & SS_NOFDREF) == 0 || so->so_count != 0 ||
568	    (so->so_state & SS_PROTOREF) || (so->so_qstate & SQ_COMP)) {
569		SOCK_UNLOCK(so);
570		ACCEPT_UNLOCK();
571		return;
572	}
573
574	head = so->so_head;
575	if (head != NULL) {
576		KASSERT((so->so_qstate & SQ_COMP) != 0 ||
577		    (so->so_qstate & SQ_INCOMP) != 0,
578		    ("sofree: so_head != NULL, but neither SQ_COMP nor "
579		    "SQ_INCOMP"));
580		KASSERT((so->so_qstate & SQ_COMP) == 0 ||
581		    (so->so_qstate & SQ_INCOMP) == 0,
582		    ("sofree: so->so_qstate is SQ_COMP and also SQ_INCOMP"));
583		TAILQ_REMOVE(&head->so_incomp, so, so_list);
584		head->so_incqlen--;
585		so->so_qstate &= ~SQ_INCOMP;
586		so->so_head = NULL;
587	}
588	KASSERT((so->so_qstate & SQ_COMP) == 0 &&
589	    (so->so_qstate & SQ_INCOMP) == 0,
590	    ("sofree: so_head == NULL, but still SQ_COMP(%d) or SQ_INCOMP(%d)",
591	    so->so_qstate & SQ_COMP, so->so_qstate & SQ_INCOMP));
592	if (so->so_options & SO_ACCEPTCONN) {
593		KASSERT((TAILQ_EMPTY(&so->so_comp)), ("sofree: so_comp populated"));
594		KASSERT((TAILQ_EMPTY(&so->so_incomp)), ("sofree: so_comp populated"));
595	}
596	SOCK_UNLOCK(so);
597	ACCEPT_UNLOCK();
598
599	if (pr->pr_flags & PR_RIGHTS && pr->pr_domain->dom_dispose != NULL)
600		(*pr->pr_domain->dom_dispose)(so->so_rcv.sb_mb);
601	if (pr->pr_usrreqs->pru_detach != NULL)
602		(*pr->pr_usrreqs->pru_detach)(so);
603
604	/*
605	 * From this point on, we assume that no other references to this
606	 * socket exist anywhere else in the stack.  Therefore, no locks need
607	 * to be acquired or held.
608	 *
609	 * We used to do a lot of socket buffer and socket locking here, as
610	 * well as invoke sorflush() and perform wakeups.  The direct call to
611	 * dom_dispose() and sbrelease_internal() are an inlining of what was
612	 * necessary from sorflush().
613	 *
614	 * Notice that the socket buffer and kqueue state are torn down
615	 * before calling pru_detach.  This means that protocols shold not
616	 * assume they can perform socket wakeups, etc, in their detach code.
617	 */
618	sbdestroy(&so->so_snd, so);
619	sbdestroy(&so->so_rcv, so);
620	knlist_destroy(&so->so_rcv.sb_sel.si_note);
621	knlist_destroy(&so->so_snd.sb_sel.si_note);
622	sodealloc(so);
623}
624
625/*
626 * Close a socket on last file table reference removal.  Initiate disconnect
627 * if connected.  Free socket when disconnect complete.
628 *
629 * This function will sorele() the socket.  Note that soclose() may be called
630 * prior to the ref count reaching zero.  The actual socket structure will
631 * not be freed until the ref count reaches zero.
632 */
633int
634soclose(struct socket *so)
635{
636	int error = 0;
637
638	KASSERT(!(so->so_state & SS_NOFDREF), ("soclose: SS_NOFDREF on enter"));
639
640	funsetown(&so->so_sigio);
641	if (so->so_state & SS_ISCONNECTED) {
642		if ((so->so_state & SS_ISDISCONNECTING) == 0) {
643			error = sodisconnect(so);
644			if (error)
645				goto drop;
646		}
647		if (so->so_options & SO_LINGER) {
648			if ((so->so_state & SS_ISDISCONNECTING) &&
649			    (so->so_state & SS_NBIO))
650				goto drop;
651			while (so->so_state & SS_ISCONNECTED) {
652				error = tsleep(&so->so_timeo,
653				    PSOCK | PCATCH, "soclos", so->so_linger * hz);
654				if (error)
655					break;
656			}
657		}
658	}
659
660drop:
661	if (so->so_proto->pr_usrreqs->pru_close != NULL)
662		(*so->so_proto->pr_usrreqs->pru_close)(so);
663	if (so->so_options & SO_ACCEPTCONN) {
664		struct socket *sp;
665		ACCEPT_LOCK();
666		while ((sp = TAILQ_FIRST(&so->so_incomp)) != NULL) {
667			TAILQ_REMOVE(&so->so_incomp, sp, so_list);
668			so->so_incqlen--;
669			sp->so_qstate &= ~SQ_INCOMP;
670			sp->so_head = NULL;
671			ACCEPT_UNLOCK();
672			soabort(sp);
673			ACCEPT_LOCK();
674		}
675		while ((sp = TAILQ_FIRST(&so->so_comp)) != NULL) {
676			TAILQ_REMOVE(&so->so_comp, sp, so_list);
677			so->so_qlen--;
678			sp->so_qstate &= ~SQ_COMP;
679			sp->so_head = NULL;
680			ACCEPT_UNLOCK();
681			soabort(sp);
682			ACCEPT_LOCK();
683		}
684		ACCEPT_UNLOCK();
685	}
686	ACCEPT_LOCK();
687	SOCK_LOCK(so);
688	KASSERT((so->so_state & SS_NOFDREF) == 0, ("soclose: NOFDREF"));
689	so->so_state |= SS_NOFDREF;
690	sorele(so);
691	return (error);
692}
693
694/*
695 * soabort() is used to abruptly tear down a connection, such as when a
696 * resource limit is reached (listen queue depth exceeded), or if a listen
697 * socket is closed while there are sockets waiting to be accepted.
698 *
699 * This interface is tricky, because it is called on an unreferenced socket,
700 * and must be called only by a thread that has actually removed the socket
701 * from the listen queue it was on, or races with other threads are risked.
702 *
703 * This interface will call into the protocol code, so must not be called
704 * with any socket locks held.  Protocols do call it while holding their own
705 * recursible protocol mutexes, but this is something that should be subject
706 * to review in the future.
707 */
708void
709soabort(struct socket *so)
710{
711
712	/*
713	 * In as much as is possible, assert that no references to this
714	 * socket are held.  This is not quite the same as asserting that the
715	 * current thread is responsible for arranging for no references, but
716	 * is as close as we can get for now.
717	 */
718	KASSERT(so->so_count == 0, ("soabort: so_count"));
719	KASSERT((so->so_state & SS_PROTOREF) == 0, ("soabort: SS_PROTOREF"));
720	KASSERT(so->so_state & SS_NOFDREF, ("soabort: !SS_NOFDREF"));
721	KASSERT((so->so_state & SQ_COMP) == 0, ("soabort: SQ_COMP"));
722	KASSERT((so->so_state & SQ_INCOMP) == 0, ("soabort: SQ_INCOMP"));
723
724	if (so->so_proto->pr_usrreqs->pru_abort != NULL)
725		(*so->so_proto->pr_usrreqs->pru_abort)(so);
726	ACCEPT_LOCK();
727	SOCK_LOCK(so);
728	sofree(so);
729}
730
731int
732soaccept(struct socket *so, struct sockaddr **nam)
733{
734	int error;
735
736	SOCK_LOCK(so);
737	KASSERT((so->so_state & SS_NOFDREF) != 0, ("soaccept: !NOFDREF"));
738	so->so_state &= ~SS_NOFDREF;
739	SOCK_UNLOCK(so);
740	error = (*so->so_proto->pr_usrreqs->pru_accept)(so, nam);
741	return (error);
742}
743
744int
745soconnect(struct socket *so, struct sockaddr *nam, struct thread *td)
746{
747	int error;
748
749	if (so->so_options & SO_ACCEPTCONN)
750		return (EOPNOTSUPP);
751	/*
752	 * If protocol is connection-based, can only connect once.
753	 * Otherwise, if connected, try to disconnect first.  This allows
754	 * user to disconnect by connecting to, e.g., a null address.
755	 */
756	if (so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING) &&
757	    ((so->so_proto->pr_flags & PR_CONNREQUIRED) ||
758	    (error = sodisconnect(so)))) {
759		error = EISCONN;
760	} else {
761		/*
762		 * Prevent accumulated error from previous connection from
763		 * biting us.
764		 */
765		so->so_error = 0;
766		error = (*so->so_proto->pr_usrreqs->pru_connect)(so, nam, td);
767	}
768
769	return (error);
770}
771
772int
773soconnect2(struct socket *so1, struct socket *so2)
774{
775
776	return ((*so1->so_proto->pr_usrreqs->pru_connect2)(so1, so2));
777}
778
779int
780sodisconnect(struct socket *so)
781{
782	int error;
783
784	if ((so->so_state & SS_ISCONNECTED) == 0)
785		return (ENOTCONN);
786	if (so->so_state & SS_ISDISCONNECTING)
787		return (EALREADY);
788	error = (*so->so_proto->pr_usrreqs->pru_disconnect)(so);
789	return (error);
790}
791
792#ifdef ZERO_COPY_SOCKETS
793struct so_zerocopy_stats{
794	int size_ok;
795	int align_ok;
796	int found_ifp;
797};
798struct so_zerocopy_stats so_zerocp_stats = {0,0,0};
799#include <netinet/in.h>
800#include <net/route.h>
801#include <netinet/in_pcb.h>
802#include <vm/vm.h>
803#include <vm/vm_page.h>
804#include <vm/vm_object.h>
805
806/*
807 * sosend_copyin() is only used if zero copy sockets are enabled.  Otherwise
808 * sosend_dgram() and sosend_generic() use m_uiotombuf().
809 *
810 * sosend_copyin() accepts a uio and prepares an mbuf chain holding part or
811 * all of the data referenced by the uio.  If desired, it uses zero-copy.
812 * *space will be updated to reflect data copied in.
813 *
814 * NB: If atomic I/O is requested, the caller must already have checked that
815 * space can hold resid bytes.
816 *
817 * NB: In the event of an error, the caller may need to free the partial
818 * chain pointed to by *mpp.  The contents of both *uio and *space may be
819 * modified even in the case of an error.
820 */
821static int
822sosend_copyin(struct uio *uio, struct mbuf **retmp, int atomic, long *space,
823    int flags)
824{
825	struct mbuf *m, **mp, *top;
826	long len, resid;
827	int error;
828#ifdef ZERO_COPY_SOCKETS
829	int cow_send;
830#endif
831
832	*retmp = top = NULL;
833	mp = &top;
834	len = 0;
835	resid = uio->uio_resid;
836	error = 0;
837	do {
838#ifdef ZERO_COPY_SOCKETS
839		cow_send = 0;
840#endif /* ZERO_COPY_SOCKETS */
841		if (resid >= MINCLSIZE) {
842#ifdef ZERO_COPY_SOCKETS
843			if (top == NULL) {
844				m = m_gethdr(M_WAITOK, MT_DATA);
845				m->m_pkthdr.len = 0;
846				m->m_pkthdr.rcvif = NULL;
847			} else
848				m = m_get(M_WAITOK, MT_DATA);
849			if (so_zero_copy_send &&
850			    resid>=PAGE_SIZE &&
851			    *space>=PAGE_SIZE &&
852			    uio->uio_iov->iov_len>=PAGE_SIZE) {
853				so_zerocp_stats.size_ok++;
854				so_zerocp_stats.align_ok++;
855				cow_send = socow_setup(m, uio);
856				len = cow_send;
857			}
858			if (!cow_send) {
859				m_clget(m, M_WAITOK);
860				len = min(min(MCLBYTES, resid), *space);
861			}
862#else /* ZERO_COPY_SOCKETS */
863			if (top == NULL) {
864				m = m_getcl(M_TRYWAIT, MT_DATA, M_PKTHDR);
865				m->m_pkthdr.len = 0;
866				m->m_pkthdr.rcvif = NULL;
867			} else
868				m = m_getcl(M_TRYWAIT, MT_DATA, 0);
869			len = min(min(MCLBYTES, resid), *space);
870#endif /* ZERO_COPY_SOCKETS */
871		} else {
872			if (top == NULL) {
873				m = m_gethdr(M_TRYWAIT, MT_DATA);
874				m->m_pkthdr.len = 0;
875				m->m_pkthdr.rcvif = NULL;
876
877				len = min(min(MHLEN, resid), *space);
878				/*
879				 * For datagram protocols, leave room
880				 * for protocol headers in first mbuf.
881				 */
882				if (atomic && m && len < MHLEN)
883					MH_ALIGN(m, len);
884			} else {
885				m = m_get(M_TRYWAIT, MT_DATA);
886				len = min(min(MLEN, resid), *space);
887			}
888		}
889		if (m == NULL) {
890			error = ENOBUFS;
891			goto out;
892		}
893
894		*space -= len;
895#ifdef ZERO_COPY_SOCKETS
896		if (cow_send)
897			error = 0;
898		else
899#endif /* ZERO_COPY_SOCKETS */
900		error = uiomove(mtod(m, void *), (int)len, uio);
901		resid = uio->uio_resid;
902		m->m_len = len;
903		*mp = m;
904		top->m_pkthdr.len += len;
905		if (error)
906			goto out;
907		mp = &m->m_next;
908		if (resid <= 0) {
909			if (flags & MSG_EOR)
910				top->m_flags |= M_EOR;
911			break;
912		}
913	} while (*space > 0 && atomic);
914out:
915	*retmp = top;
916	return (error);
917}
918#endif /*ZERO_COPY_SOCKETS*/
919
920#define	SBLOCKWAIT(f)	(((f) & MSG_DONTWAIT) ? 0 : SBL_WAIT)
921
922int
923sosend_dgram(struct socket *so, struct sockaddr *addr, struct uio *uio,
924    struct mbuf *top, struct mbuf *control, int flags, struct thread *td)
925{
926	long space, resid;
927	int clen = 0, error, dontroute;
928#ifdef ZERO_COPY_SOCKETS
929	int atomic = sosendallatonce(so) || top;
930#endif
931
932	KASSERT(so->so_type == SOCK_DGRAM, ("sodgram_send: !SOCK_DGRAM"));
933	KASSERT(so->so_proto->pr_flags & PR_ATOMIC,
934	    ("sodgram_send: !PR_ATOMIC"));
935
936	if (uio != NULL)
937		resid = uio->uio_resid;
938	else
939		resid = top->m_pkthdr.len;
940	/*
941	 * In theory resid should be unsigned.  However, space must be
942	 * signed, as it might be less than 0 if we over-committed, and we
943	 * must use a signed comparison of space and resid.  On the other
944	 * hand, a negative resid causes us to loop sending 0-length
945	 * segments to the protocol.
946	 *
947	 * Also check to make sure that MSG_EOR isn't used on SOCK_STREAM
948	 * type sockets since that's an error.
949	 */
950	if (resid < 0) {
951		error = EINVAL;
952		goto out;
953	}
954
955	dontroute =
956	    (flags & MSG_DONTROUTE) && (so->so_options & SO_DONTROUTE) == 0;
957	if (td != NULL)
958		td->td_ru.ru_msgsnd++;
959	if (control != NULL)
960		clen = control->m_len;
961
962	SOCKBUF_LOCK(&so->so_snd);
963	if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
964		SOCKBUF_UNLOCK(&so->so_snd);
965		error = EPIPE;
966		goto out;
967	}
968	if (so->so_error) {
969		error = so->so_error;
970		so->so_error = 0;
971		SOCKBUF_UNLOCK(&so->so_snd);
972		goto out;
973	}
974	if ((so->so_state & SS_ISCONNECTED) == 0) {
975		/*
976		 * `sendto' and `sendmsg' is allowed on a connection-based
977		 * socket if it supports implied connect.  Return ENOTCONN if
978		 * not connected and no address is supplied.
979		 */
980		if ((so->so_proto->pr_flags & PR_CONNREQUIRED) &&
981		    (so->so_proto->pr_flags & PR_IMPLOPCL) == 0) {
982			if ((so->so_state & SS_ISCONFIRMING) == 0 &&
983			    !(resid == 0 && clen != 0)) {
984				SOCKBUF_UNLOCK(&so->so_snd);
985				error = ENOTCONN;
986				goto out;
987			}
988		} else if (addr == NULL) {
989			if (so->so_proto->pr_flags & PR_CONNREQUIRED)
990				error = ENOTCONN;
991			else
992				error = EDESTADDRREQ;
993			SOCKBUF_UNLOCK(&so->so_snd);
994			goto out;
995		}
996	}
997
998	/*
999	 * Do we need MSG_OOB support in SOCK_DGRAM?  Signs here may be a
1000	 * problem and need fixing.
1001	 */
1002	space = sbspace(&so->so_snd);
1003	if (flags & MSG_OOB)
1004		space += 1024;
1005	space -= clen;
1006	SOCKBUF_UNLOCK(&so->so_snd);
1007	if (resid > space) {
1008		error = EMSGSIZE;
1009		goto out;
1010	}
1011	if (uio == NULL) {
1012		resid = 0;
1013		if (flags & MSG_EOR)
1014			top->m_flags |= M_EOR;
1015	} else {
1016#ifdef ZERO_COPY_SOCKETS
1017		error = sosend_copyin(uio, &top, atomic, &space, flags);
1018		if (error)
1019			goto out;
1020#else
1021		/*
1022		 * Copy the data from userland into a mbuf chain.
1023		 * If no data is to be copied in, a single empty mbuf
1024		 * is returned.
1025		 */
1026		top = m_uiotombuf(uio, M_WAITOK, space, max_hdr,
1027		    (M_PKTHDR | ((flags & MSG_EOR) ? M_EOR : 0)));
1028		if (top == NULL) {
1029			error = EFAULT;	/* only possible error */
1030			goto out;
1031		}
1032		space -= resid - uio->uio_resid;
1033#endif
1034		resid = uio->uio_resid;
1035	}
1036	KASSERT(resid == 0, ("sosend_dgram: resid != 0"));
1037	/*
1038	 * XXXRW: Frobbing SO_DONTROUTE here is even worse without sblock
1039	 * than with.
1040	 */
1041	if (dontroute) {
1042		SOCK_LOCK(so);
1043		so->so_options |= SO_DONTROUTE;
1044		SOCK_UNLOCK(so);
1045	}
1046	/*
1047	 * XXX all the SBS_CANTSENDMORE checks previously done could be out
1048	 * of date.  We could have recieved a reset packet in an interrupt or
1049	 * maybe we slept while doing page faults in uiomove() etc.  We could
1050	 * probably recheck again inside the locking protection here, but
1051	 * there are probably other places that this also happens.  We must
1052	 * rethink this.
1053	 */
1054	error = (*so->so_proto->pr_usrreqs->pru_send)(so,
1055	    (flags & MSG_OOB) ? PRUS_OOB :
1056	/*
1057	 * If the user set MSG_EOF, the protocol understands this flag and
1058	 * nothing left to send then use PRU_SEND_EOF instead of PRU_SEND.
1059	 */
1060	    ((flags & MSG_EOF) &&
1061	     (so->so_proto->pr_flags & PR_IMPLOPCL) &&
1062	     (resid <= 0)) ?
1063		PRUS_EOF :
1064		/* If there is more to send set PRUS_MORETOCOME */
1065		(resid > 0 && space > 0) ? PRUS_MORETOCOME : 0,
1066		top, addr, control, td);
1067	if (dontroute) {
1068		SOCK_LOCK(so);
1069		so->so_options &= ~SO_DONTROUTE;
1070		SOCK_UNLOCK(so);
1071	}
1072	clen = 0;
1073	control = NULL;
1074	top = NULL;
1075out:
1076	if (top != NULL)
1077		m_freem(top);
1078	if (control != NULL)
1079		m_freem(control);
1080	return (error);
1081}
1082
1083/*
1084 * Send on a socket.  If send must go all at once and message is larger than
1085 * send buffering, then hard error.  Lock against other senders.  If must go
1086 * all at once and not enough room now, then inform user that this would
1087 * block and do nothing.  Otherwise, if nonblocking, send as much as
1088 * possible.  The data to be sent is described by "uio" if nonzero, otherwise
1089 * by the mbuf chain "top" (which must be null if uio is not).  Data provided
1090 * in mbuf chain must be small enough to send all at once.
1091 *
1092 * Returns nonzero on error, timeout or signal; callers must check for short
1093 * counts if EINTR/ERESTART are returned.  Data and control buffers are freed
1094 * on return.
1095 */
1096int
1097sosend_generic(struct socket *so, struct sockaddr *addr, struct uio *uio,
1098    struct mbuf *top, struct mbuf *control, int flags, struct thread *td)
1099{
1100	long space, resid;
1101	int clen = 0, error, dontroute;
1102	int atomic = sosendallatonce(so) || top;
1103
1104	if (uio != NULL)
1105		resid = uio->uio_resid;
1106	else
1107		resid = top->m_pkthdr.len;
1108	/*
1109	 * In theory resid should be unsigned.  However, space must be
1110	 * signed, as it might be less than 0 if we over-committed, and we
1111	 * must use a signed comparison of space and resid.  On the other
1112	 * hand, a negative resid causes us to loop sending 0-length
1113	 * segments to the protocol.
1114	 *
1115	 * Also check to make sure that MSG_EOR isn't used on SOCK_STREAM
1116	 * type sockets since that's an error.
1117	 */
1118	if (resid < 0 || (so->so_type == SOCK_STREAM && (flags & MSG_EOR))) {
1119		error = EINVAL;
1120		goto out;
1121	}
1122
1123	dontroute =
1124	    (flags & MSG_DONTROUTE) && (so->so_options & SO_DONTROUTE) == 0 &&
1125	    (so->so_proto->pr_flags & PR_ATOMIC);
1126	if (td != NULL)
1127		td->td_ru.ru_msgsnd++;
1128	if (control != NULL)
1129		clen = control->m_len;
1130
1131	error = sblock(&so->so_snd, SBLOCKWAIT(flags));
1132	if (error)
1133		goto out;
1134
1135restart:
1136	do {
1137		SOCKBUF_LOCK(&so->so_snd);
1138		if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
1139			SOCKBUF_UNLOCK(&so->so_snd);
1140			error = EPIPE;
1141			goto release;
1142		}
1143		if (so->so_error) {
1144			error = so->so_error;
1145			so->so_error = 0;
1146			SOCKBUF_UNLOCK(&so->so_snd);
1147			goto release;
1148		}
1149		if ((so->so_state & SS_ISCONNECTED) == 0) {
1150			/*
1151			 * `sendto' and `sendmsg' is allowed on a connection-
1152			 * based socket if it supports implied connect.
1153			 * Return ENOTCONN if not connected and no address is
1154			 * supplied.
1155			 */
1156			if ((so->so_proto->pr_flags & PR_CONNREQUIRED) &&
1157			    (so->so_proto->pr_flags & PR_IMPLOPCL) == 0) {
1158				if ((so->so_state & SS_ISCONFIRMING) == 0 &&
1159				    !(resid == 0 && clen != 0)) {
1160					SOCKBUF_UNLOCK(&so->so_snd);
1161					error = ENOTCONN;
1162					goto release;
1163				}
1164			} else if (addr == NULL) {
1165				SOCKBUF_UNLOCK(&so->so_snd);
1166				if (so->so_proto->pr_flags & PR_CONNREQUIRED)
1167					error = ENOTCONN;
1168				else
1169					error = EDESTADDRREQ;
1170				goto release;
1171			}
1172		}
1173		space = sbspace(&so->so_snd);
1174		if (flags & MSG_OOB)
1175			space += 1024;
1176		if ((atomic && resid > so->so_snd.sb_hiwat) ||
1177		    clen > so->so_snd.sb_hiwat) {
1178			SOCKBUF_UNLOCK(&so->so_snd);
1179			error = EMSGSIZE;
1180			goto release;
1181		}
1182		if (space < resid + clen &&
1183		    (atomic || space < so->so_snd.sb_lowat || space < clen)) {
1184			if ((so->so_state & SS_NBIO) || (flags & MSG_NBIO)) {
1185				SOCKBUF_UNLOCK(&so->so_snd);
1186				error = EWOULDBLOCK;
1187				goto release;
1188			}
1189			error = sbwait(&so->so_snd);
1190			SOCKBUF_UNLOCK(&so->so_snd);
1191			if (error)
1192				goto release;
1193			goto restart;
1194		}
1195		SOCKBUF_UNLOCK(&so->so_snd);
1196		space -= clen;
1197		do {
1198			if (uio == NULL) {
1199				resid = 0;
1200				if (flags & MSG_EOR)
1201					top->m_flags |= M_EOR;
1202			} else {
1203#ifdef ZERO_COPY_SOCKETS
1204				error = sosend_copyin(uio, &top, atomic,
1205				    &space, flags);
1206				if (error != 0)
1207					goto release;
1208#else
1209				/*
1210				 * Copy the data from userland into a mbuf
1211				 * chain.  If no data is to be copied in,
1212				 * a single empty mbuf is returned.
1213				 */
1214				top = m_uiotombuf(uio, M_WAITOK, space,
1215				    (atomic ? max_hdr : 0),
1216				    (atomic ? M_PKTHDR : 0) |
1217				    ((flags & MSG_EOR) ? M_EOR : 0));
1218				if (top == NULL) {
1219					error = EFAULT; /* only possible error */
1220					goto release;
1221				}
1222				space -= resid - uio->uio_resid;
1223#endif
1224				resid = uio->uio_resid;
1225			}
1226			if (dontroute) {
1227				SOCK_LOCK(so);
1228				so->so_options |= SO_DONTROUTE;
1229				SOCK_UNLOCK(so);
1230			}
1231			/*
1232			 * XXX all the SBS_CANTSENDMORE checks previously
1233			 * done could be out of date.  We could have recieved
1234			 * a reset packet in an interrupt or maybe we slept
1235			 * while doing page faults in uiomove() etc.  We
1236			 * could probably recheck again inside the locking
1237			 * protection here, but there are probably other
1238			 * places that this also happens.  We must rethink
1239			 * this.
1240			 */
1241			error = (*so->so_proto->pr_usrreqs->pru_send)(so,
1242			    (flags & MSG_OOB) ? PRUS_OOB :
1243			/*
1244			 * If the user set MSG_EOF, the protocol understands
1245			 * this flag and nothing left to send then use
1246			 * PRU_SEND_EOF instead of PRU_SEND.
1247			 */
1248			    ((flags & MSG_EOF) &&
1249			     (so->so_proto->pr_flags & PR_IMPLOPCL) &&
1250			     (resid <= 0)) ?
1251				PRUS_EOF :
1252			/* If there is more to send set PRUS_MORETOCOME. */
1253			    (resid > 0 && space > 0) ? PRUS_MORETOCOME : 0,
1254			    top, addr, control, td);
1255			if (dontroute) {
1256				SOCK_LOCK(so);
1257				so->so_options &= ~SO_DONTROUTE;
1258				SOCK_UNLOCK(so);
1259			}
1260			clen = 0;
1261			control = NULL;
1262			top = NULL;
1263			if (error)
1264				goto release;
1265		} while (resid && space > 0);
1266	} while (resid);
1267
1268release:
1269	sbunlock(&so->so_snd);
1270out:
1271	if (top != NULL)
1272		m_freem(top);
1273	if (control != NULL)
1274		m_freem(control);
1275	return (error);
1276}
1277
1278int
1279sosend(struct socket *so, struct sockaddr *addr, struct uio *uio,
1280    struct mbuf *top, struct mbuf *control, int flags, struct thread *td)
1281{
1282
1283	/* XXXRW: Temporary debugging. */
1284	KASSERT(so->so_proto->pr_usrreqs->pru_sosend != sosend,
1285	    ("sosend: protocol calls sosend"));
1286
1287	return (so->so_proto->pr_usrreqs->pru_sosend(so, addr, uio, top,
1288	    control, flags, td));
1289}
1290
1291/*
1292 * The part of soreceive() that implements reading non-inline out-of-band
1293 * data from a socket.  For more complete comments, see soreceive(), from
1294 * which this code originated.
1295 *
1296 * Note that soreceive_rcvoob(), unlike the remainder of soreceive(), is
1297 * unable to return an mbuf chain to the caller.
1298 */
1299static int
1300soreceive_rcvoob(struct socket *so, struct uio *uio, int flags)
1301{
1302	struct protosw *pr = so->so_proto;
1303	struct mbuf *m;
1304	int error;
1305
1306	KASSERT(flags & MSG_OOB, ("soreceive_rcvoob: (flags & MSG_OOB) == 0"));
1307
1308	m = m_get(M_TRYWAIT, MT_DATA);
1309	if (m == NULL)
1310		return (ENOBUFS);
1311	error = (*pr->pr_usrreqs->pru_rcvoob)(so, m, flags & MSG_PEEK);
1312	if (error)
1313		goto bad;
1314	do {
1315#ifdef ZERO_COPY_SOCKETS
1316		if (so_zero_copy_receive) {
1317			int disposable;
1318
1319			if ((m->m_flags & M_EXT)
1320			 && (m->m_ext.ext_type == EXT_DISPOSABLE))
1321				disposable = 1;
1322			else
1323				disposable = 0;
1324
1325			error = uiomoveco(mtod(m, void *),
1326					  min(uio->uio_resid, m->m_len),
1327					  uio, disposable);
1328		} else
1329#endif /* ZERO_COPY_SOCKETS */
1330		error = uiomove(mtod(m, void *),
1331		    (int) min(uio->uio_resid, m->m_len), uio);
1332		m = m_free(m);
1333	} while (uio->uio_resid && error == 0 && m);
1334bad:
1335	if (m != NULL)
1336		m_freem(m);
1337	return (error);
1338}
1339
1340/*
1341 * Following replacement or removal of the first mbuf on the first mbuf chain
1342 * of a socket buffer, push necessary state changes back into the socket
1343 * buffer so that other consumers see the values consistently.  'nextrecord'
1344 * is the callers locally stored value of the original value of
1345 * sb->sb_mb->m_nextpkt which must be restored when the lead mbuf changes.
1346 * NOTE: 'nextrecord' may be NULL.
1347 */
1348static __inline void
1349sockbuf_pushsync(struct sockbuf *sb, struct mbuf *nextrecord)
1350{
1351
1352	SOCKBUF_LOCK_ASSERT(sb);
1353	/*
1354	 * First, update for the new value of nextrecord.  If necessary, make
1355	 * it the first record.
1356	 */
1357	if (sb->sb_mb != NULL)
1358		sb->sb_mb->m_nextpkt = nextrecord;
1359	else
1360		sb->sb_mb = nextrecord;
1361
1362        /*
1363         * Now update any dependent socket buffer fields to reflect the new
1364         * state.  This is an expanded inline of SB_EMPTY_FIXUP(), with the
1365	 * addition of a second clause that takes care of the case where
1366	 * sb_mb has been updated, but remains the last record.
1367         */
1368        if (sb->sb_mb == NULL) {
1369                sb->sb_mbtail = NULL;
1370                sb->sb_lastrecord = NULL;
1371        } else if (sb->sb_mb->m_nextpkt == NULL)
1372                sb->sb_lastrecord = sb->sb_mb;
1373}
1374
1375
1376/*
1377 * Implement receive operations on a socket.  We depend on the way that
1378 * records are added to the sockbuf by sbappend.  In particular, each record
1379 * (mbufs linked through m_next) must begin with an address if the protocol
1380 * so specifies, followed by an optional mbuf or mbufs containing ancillary
1381 * data, and then zero or more mbufs of data.  In order to allow parallelism
1382 * between network receive and copying to user space, as well as avoid
1383 * sleeping with a mutex held, we release the socket buffer mutex during the
1384 * user space copy.  Although the sockbuf is locked, new data may still be
1385 * appended, and thus we must maintain consistency of the sockbuf during that
1386 * time.
1387 *
1388 * The caller may receive the data as a single mbuf chain by supplying an
1389 * mbuf **mp0 for use in returning the chain.  The uio is then used only for
1390 * the count in uio_resid.
1391 */
1392int
1393soreceive_generic(struct socket *so, struct sockaddr **psa, struct uio *uio,
1394    struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
1395{
1396	struct mbuf *m, **mp;
1397	int flags, len, error, offset;
1398	struct protosw *pr = so->so_proto;
1399	struct mbuf *nextrecord;
1400	int moff, type = 0;
1401	int orig_resid = uio->uio_resid;
1402
1403	mp = mp0;
1404	if (psa != NULL)
1405		*psa = NULL;
1406	if (controlp != NULL)
1407		*controlp = NULL;
1408	if (flagsp != NULL)
1409		flags = *flagsp &~ MSG_EOR;
1410	else
1411		flags = 0;
1412	if (flags & MSG_OOB)
1413		return (soreceive_rcvoob(so, uio, flags));
1414	if (mp != NULL)
1415		*mp = NULL;
1416	if ((pr->pr_flags & PR_WANTRCVD) && (so->so_state & SS_ISCONFIRMING)
1417	    && uio->uio_resid)
1418		(*pr->pr_usrreqs->pru_rcvd)(so, 0);
1419
1420	error = sblock(&so->so_rcv, SBLOCKWAIT(flags));
1421	if (error)
1422		return (error);
1423
1424restart:
1425	SOCKBUF_LOCK(&so->so_rcv);
1426	m = so->so_rcv.sb_mb;
1427	/*
1428	 * If we have less data than requested, block awaiting more (subject
1429	 * to any timeout) if:
1430	 *   1. the current count is less than the low water mark, or
1431	 *   2. MSG_WAITALL is set, and it is possible to do the entire
1432	 *	receive operation at once if we block (resid <= hiwat).
1433	 *   3. MSG_DONTWAIT is not set
1434	 * If MSG_WAITALL is set but resid is larger than the receive buffer,
1435	 * we have to do the receive in sections, and thus risk returning a
1436	 * short count if a timeout or signal occurs after we start.
1437	 */
1438	if (m == NULL || (((flags & MSG_DONTWAIT) == 0 &&
1439	    so->so_rcv.sb_cc < uio->uio_resid) &&
1440	    (so->so_rcv.sb_cc < so->so_rcv.sb_lowat ||
1441	    ((flags & MSG_WAITALL) && uio->uio_resid <= so->so_rcv.sb_hiwat)) &&
1442	    m->m_nextpkt == NULL && (pr->pr_flags & PR_ATOMIC) == 0)) {
1443		KASSERT(m != NULL || !so->so_rcv.sb_cc,
1444		    ("receive: m == %p so->so_rcv.sb_cc == %u",
1445		    m, so->so_rcv.sb_cc));
1446		if (so->so_error) {
1447			if (m != NULL)
1448				goto dontblock;
1449			error = so->so_error;
1450			if ((flags & MSG_PEEK) == 0)
1451				so->so_error = 0;
1452			SOCKBUF_UNLOCK(&so->so_rcv);
1453			goto release;
1454		}
1455		SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1456		if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
1457			if (m == NULL) {
1458				SOCKBUF_UNLOCK(&so->so_rcv);
1459				goto release;
1460			} else
1461				goto dontblock;
1462		}
1463		for (; m != NULL; m = m->m_next)
1464			if (m->m_type == MT_OOBDATA  || (m->m_flags & M_EOR)) {
1465				m = so->so_rcv.sb_mb;
1466				goto dontblock;
1467			}
1468		if ((so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING)) == 0 &&
1469		    (so->so_proto->pr_flags & PR_CONNREQUIRED)) {
1470			SOCKBUF_UNLOCK(&so->so_rcv);
1471			error = ENOTCONN;
1472			goto release;
1473		}
1474		if (uio->uio_resid == 0) {
1475			SOCKBUF_UNLOCK(&so->so_rcv);
1476			goto release;
1477		}
1478		if ((so->so_state & SS_NBIO) ||
1479		    (flags & (MSG_DONTWAIT|MSG_NBIO))) {
1480			SOCKBUF_UNLOCK(&so->so_rcv);
1481			error = EWOULDBLOCK;
1482			goto release;
1483		}
1484		SBLASTRECORDCHK(&so->so_rcv);
1485		SBLASTMBUFCHK(&so->so_rcv);
1486		error = sbwait(&so->so_rcv);
1487		SOCKBUF_UNLOCK(&so->so_rcv);
1488		if (error)
1489			goto release;
1490		goto restart;
1491	}
1492dontblock:
1493	/*
1494	 * From this point onward, we maintain 'nextrecord' as a cache of the
1495	 * pointer to the next record in the socket buffer.  We must keep the
1496	 * various socket buffer pointers and local stack versions of the
1497	 * pointers in sync, pushing out modifications before dropping the
1498	 * socket buffer mutex, and re-reading them when picking it up.
1499	 *
1500	 * Otherwise, we will race with the network stack appending new data
1501	 * or records onto the socket buffer by using inconsistent/stale
1502	 * versions of the field, possibly resulting in socket buffer
1503	 * corruption.
1504	 *
1505	 * By holding the high-level sblock(), we prevent simultaneous
1506	 * readers from pulling off the front of the socket buffer.
1507	 */
1508	SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1509	if (uio->uio_td)
1510		uio->uio_td->td_ru.ru_msgrcv++;
1511	KASSERT(m == so->so_rcv.sb_mb, ("soreceive: m != so->so_rcv.sb_mb"));
1512	SBLASTRECORDCHK(&so->so_rcv);
1513	SBLASTMBUFCHK(&so->so_rcv);
1514	nextrecord = m->m_nextpkt;
1515	if (pr->pr_flags & PR_ADDR) {
1516		KASSERT(m->m_type == MT_SONAME,
1517		    ("m->m_type == %d", m->m_type));
1518		orig_resid = 0;
1519		if (psa != NULL)
1520			*psa = sodupsockaddr(mtod(m, struct sockaddr *),
1521			    M_NOWAIT);
1522		if (flags & MSG_PEEK) {
1523			m = m->m_next;
1524		} else {
1525			sbfree(&so->so_rcv, m);
1526			so->so_rcv.sb_mb = m_free(m);
1527			m = so->so_rcv.sb_mb;
1528			sockbuf_pushsync(&so->so_rcv, nextrecord);
1529		}
1530	}
1531
1532	/*
1533	 * Process one or more MT_CONTROL mbufs present before any data mbufs
1534	 * in the first mbuf chain on the socket buffer.  If MSG_PEEK, we
1535	 * just copy the data; if !MSG_PEEK, we call into the protocol to
1536	 * perform externalization (or freeing if controlp == NULL).
1537	 */
1538	if (m != NULL && m->m_type == MT_CONTROL) {
1539		struct mbuf *cm = NULL, *cmn;
1540		struct mbuf **cme = &cm;
1541
1542		do {
1543			if (flags & MSG_PEEK) {
1544				if (controlp != NULL) {
1545					*controlp = m_copy(m, 0, m->m_len);
1546					controlp = &(*controlp)->m_next;
1547				}
1548				m = m->m_next;
1549			} else {
1550				sbfree(&so->so_rcv, m);
1551				so->so_rcv.sb_mb = m->m_next;
1552				m->m_next = NULL;
1553				*cme = m;
1554				cme = &(*cme)->m_next;
1555				m = so->so_rcv.sb_mb;
1556			}
1557		} while (m != NULL && m->m_type == MT_CONTROL);
1558		if ((flags & MSG_PEEK) == 0)
1559			sockbuf_pushsync(&so->so_rcv, nextrecord);
1560		while (cm != NULL) {
1561			cmn = cm->m_next;
1562			cm->m_next = NULL;
1563			if (pr->pr_domain->dom_externalize != NULL) {
1564				SOCKBUF_UNLOCK(&so->so_rcv);
1565				error = (*pr->pr_domain->dom_externalize)
1566				    (cm, controlp);
1567				SOCKBUF_LOCK(&so->so_rcv);
1568			} else if (controlp != NULL)
1569				*controlp = cm;
1570			else
1571				m_freem(cm);
1572			if (controlp != NULL) {
1573				orig_resid = 0;
1574				while (*controlp != NULL)
1575					controlp = &(*controlp)->m_next;
1576			}
1577			cm = cmn;
1578		}
1579		if (m != NULL)
1580			nextrecord = so->so_rcv.sb_mb->m_nextpkt;
1581		else
1582			nextrecord = so->so_rcv.sb_mb;
1583		orig_resid = 0;
1584	}
1585	if (m != NULL) {
1586		if ((flags & MSG_PEEK) == 0) {
1587			KASSERT(m->m_nextpkt == nextrecord,
1588			    ("soreceive: post-control, nextrecord !sync"));
1589			if (nextrecord == NULL) {
1590				KASSERT(so->so_rcv.sb_mb == m,
1591				    ("soreceive: post-control, sb_mb!=m"));
1592				KASSERT(so->so_rcv.sb_lastrecord == m,
1593				    ("soreceive: post-control, lastrecord!=m"));
1594			}
1595		}
1596		type = m->m_type;
1597		if (type == MT_OOBDATA)
1598			flags |= MSG_OOB;
1599	} else {
1600		if ((flags & MSG_PEEK) == 0) {
1601			KASSERT(so->so_rcv.sb_mb == nextrecord,
1602			    ("soreceive: sb_mb != nextrecord"));
1603			if (so->so_rcv.sb_mb == NULL) {
1604				KASSERT(so->so_rcv.sb_lastrecord == NULL,
1605				    ("soreceive: sb_lastercord != NULL"));
1606			}
1607		}
1608	}
1609	SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1610	SBLASTRECORDCHK(&so->so_rcv);
1611	SBLASTMBUFCHK(&so->so_rcv);
1612
1613	/*
1614	 * Now continue to read any data mbufs off of the head of the socket
1615	 * buffer until the read request is satisfied.  Note that 'type' is
1616	 * used to store the type of any mbuf reads that have happened so far
1617	 * such that soreceive() can stop reading if the type changes, which
1618	 * causes soreceive() to return only one of regular data and inline
1619	 * out-of-band data in a single socket receive operation.
1620	 */
1621	moff = 0;
1622	offset = 0;
1623	while (m != NULL && uio->uio_resid > 0 && error == 0) {
1624		/*
1625		 * If the type of mbuf has changed since the last mbuf
1626		 * examined ('type'), end the receive operation.
1627	 	 */
1628		SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1629		if (m->m_type == MT_OOBDATA) {
1630			if (type != MT_OOBDATA)
1631				break;
1632		} else if (type == MT_OOBDATA)
1633			break;
1634		else
1635		    KASSERT(m->m_type == MT_DATA,
1636			("m->m_type == %d", m->m_type));
1637		so->so_rcv.sb_state &= ~SBS_RCVATMARK;
1638		len = uio->uio_resid;
1639		if (so->so_oobmark && len > so->so_oobmark - offset)
1640			len = so->so_oobmark - offset;
1641		if (len > m->m_len - moff)
1642			len = m->m_len - moff;
1643		/*
1644		 * If mp is set, just pass back the mbufs.  Otherwise copy
1645		 * them out via the uio, then free.  Sockbuf must be
1646		 * consistent here (points to current mbuf, it points to next
1647		 * record) when we drop priority; we must note any additions
1648		 * to the sockbuf when we block interrupts again.
1649		 */
1650		if (mp == NULL) {
1651			SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1652			SBLASTRECORDCHK(&so->so_rcv);
1653			SBLASTMBUFCHK(&so->so_rcv);
1654			SOCKBUF_UNLOCK(&so->so_rcv);
1655#ifdef ZERO_COPY_SOCKETS
1656			if (so_zero_copy_receive) {
1657				int disposable;
1658
1659				if ((m->m_flags & M_EXT)
1660				 && (m->m_ext.ext_type == EXT_DISPOSABLE))
1661					disposable = 1;
1662				else
1663					disposable = 0;
1664
1665				error = uiomoveco(mtod(m, char *) + moff,
1666						  (int)len, uio,
1667						  disposable);
1668			} else
1669#endif /* ZERO_COPY_SOCKETS */
1670			error = uiomove(mtod(m, char *) + moff, (int)len, uio);
1671			SOCKBUF_LOCK(&so->so_rcv);
1672			if (error) {
1673				/*
1674				 * The MT_SONAME mbuf has already been removed
1675				 * from the record, so it is necessary to
1676				 * remove the data mbufs, if any, to preserve
1677				 * the invariant in the case of PR_ADDR that
1678				 * requires MT_SONAME mbufs at the head of
1679				 * each record.
1680				 */
1681				if (m && pr->pr_flags & PR_ATOMIC &&
1682				    ((flags & MSG_PEEK) == 0))
1683					(void)sbdroprecord_locked(&so->so_rcv);
1684				SOCKBUF_UNLOCK(&so->so_rcv);
1685				goto release;
1686			}
1687		} else
1688			uio->uio_resid -= len;
1689		SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1690		if (len == m->m_len - moff) {
1691			if (m->m_flags & M_EOR)
1692				flags |= MSG_EOR;
1693			if (flags & MSG_PEEK) {
1694				m = m->m_next;
1695				moff = 0;
1696			} else {
1697				nextrecord = m->m_nextpkt;
1698				sbfree(&so->so_rcv, m);
1699				if (mp != NULL) {
1700					*mp = m;
1701					mp = &m->m_next;
1702					so->so_rcv.sb_mb = m = m->m_next;
1703					*mp = NULL;
1704				} else {
1705					so->so_rcv.sb_mb = m_free(m);
1706					m = so->so_rcv.sb_mb;
1707				}
1708				sockbuf_pushsync(&so->so_rcv, nextrecord);
1709				SBLASTRECORDCHK(&so->so_rcv);
1710				SBLASTMBUFCHK(&so->so_rcv);
1711			}
1712		} else {
1713			if (flags & MSG_PEEK)
1714				moff += len;
1715			else {
1716				if (mp != NULL) {
1717					int copy_flag;
1718
1719					if (flags & MSG_DONTWAIT)
1720						copy_flag = M_DONTWAIT;
1721					else
1722						copy_flag = M_TRYWAIT;
1723					if (copy_flag == M_TRYWAIT)
1724						SOCKBUF_UNLOCK(&so->so_rcv);
1725					*mp = m_copym(m, 0, len, copy_flag);
1726					if (copy_flag == M_TRYWAIT)
1727						SOCKBUF_LOCK(&so->so_rcv);
1728 					if (*mp == NULL) {
1729 						/*
1730 						 * m_copym() couldn't
1731						 * allocate an mbuf.  Adjust
1732						 * uio_resid back (it was
1733						 * adjusted down by len
1734						 * bytes, which we didn't end
1735						 * up "copying" over).
1736 						 */
1737 						uio->uio_resid += len;
1738 						break;
1739 					}
1740				}
1741				m->m_data += len;
1742				m->m_len -= len;
1743				so->so_rcv.sb_cc -= len;
1744			}
1745		}
1746		SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1747		if (so->so_oobmark) {
1748			if ((flags & MSG_PEEK) == 0) {
1749				so->so_oobmark -= len;
1750				if (so->so_oobmark == 0) {
1751					so->so_rcv.sb_state |= SBS_RCVATMARK;
1752					break;
1753				}
1754			} else {
1755				offset += len;
1756				if (offset == so->so_oobmark)
1757					break;
1758			}
1759		}
1760		if (flags & MSG_EOR)
1761			break;
1762		/*
1763		 * If the MSG_WAITALL flag is set (for non-atomic socket), we
1764		 * must not quit until "uio->uio_resid == 0" or an error
1765		 * termination.  If a signal/timeout occurs, return with a
1766		 * short count but without error.  Keep sockbuf locked
1767		 * against other readers.
1768		 */
1769		while (flags & MSG_WAITALL && m == NULL && uio->uio_resid > 0 &&
1770		    !sosendallatonce(so) && nextrecord == NULL) {
1771			SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1772			if (so->so_error || so->so_rcv.sb_state & SBS_CANTRCVMORE)
1773				break;
1774			/*
1775			 * Notify the protocol that some data has been
1776			 * drained before blocking.
1777			 */
1778			if (pr->pr_flags & PR_WANTRCVD) {
1779				SOCKBUF_UNLOCK(&so->so_rcv);
1780				(*pr->pr_usrreqs->pru_rcvd)(so, flags);
1781				SOCKBUF_LOCK(&so->so_rcv);
1782			}
1783			SBLASTRECORDCHK(&so->so_rcv);
1784			SBLASTMBUFCHK(&so->so_rcv);
1785			error = sbwait(&so->so_rcv);
1786			if (error) {
1787				SOCKBUF_UNLOCK(&so->so_rcv);
1788				goto release;
1789			}
1790			m = so->so_rcv.sb_mb;
1791			if (m != NULL)
1792				nextrecord = m->m_nextpkt;
1793		}
1794	}
1795
1796	SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1797	if (m != NULL && pr->pr_flags & PR_ATOMIC) {
1798		flags |= MSG_TRUNC;
1799		if ((flags & MSG_PEEK) == 0)
1800			(void) sbdroprecord_locked(&so->so_rcv);
1801	}
1802	if ((flags & MSG_PEEK) == 0) {
1803		if (m == NULL) {
1804			/*
1805			 * First part is an inline SB_EMPTY_FIXUP().  Second
1806			 * part makes sure sb_lastrecord is up-to-date if
1807			 * there is still data in the socket buffer.
1808			 */
1809			so->so_rcv.sb_mb = nextrecord;
1810			if (so->so_rcv.sb_mb == NULL) {
1811				so->so_rcv.sb_mbtail = NULL;
1812				so->so_rcv.sb_lastrecord = NULL;
1813			} else if (nextrecord->m_nextpkt == NULL)
1814				so->so_rcv.sb_lastrecord = nextrecord;
1815		}
1816		SBLASTRECORDCHK(&so->so_rcv);
1817		SBLASTMBUFCHK(&so->so_rcv);
1818		/*
1819		 * If soreceive() is being done from the socket callback,
1820		 * then don't need to generate ACK to peer to update window,
1821		 * since ACK will be generated on return to TCP.
1822		 */
1823		if (!(flags & MSG_SOCALLBCK) &&
1824		    (pr->pr_flags & PR_WANTRCVD)) {
1825			SOCKBUF_UNLOCK(&so->so_rcv);
1826			(*pr->pr_usrreqs->pru_rcvd)(so, flags);
1827			SOCKBUF_LOCK(&so->so_rcv);
1828		}
1829	}
1830	SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1831	if (orig_resid == uio->uio_resid && orig_resid &&
1832	    (flags & MSG_EOR) == 0 && (so->so_rcv.sb_state & SBS_CANTRCVMORE) == 0) {
1833		SOCKBUF_UNLOCK(&so->so_rcv);
1834		goto restart;
1835	}
1836	SOCKBUF_UNLOCK(&so->so_rcv);
1837
1838	if (flagsp != NULL)
1839		*flagsp |= flags;
1840release:
1841	sbunlock(&so->so_rcv);
1842	return (error);
1843}
1844
1845int
1846soreceive(struct socket *so, struct sockaddr **psa, struct uio *uio,
1847    struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
1848{
1849
1850	/* XXXRW: Temporary debugging. */
1851	KASSERT(so->so_proto->pr_usrreqs->pru_soreceive != soreceive,
1852	    ("soreceive: protocol calls soreceive"));
1853
1854	return (so->so_proto->pr_usrreqs->pru_soreceive(so, psa, uio, mp0,
1855	    controlp, flagsp));
1856}
1857
1858int
1859soshutdown(struct socket *so, int how)
1860{
1861	struct protosw *pr = so->so_proto;
1862
1863	if (!(how == SHUT_RD || how == SHUT_WR || how == SHUT_RDWR))
1864		return (EINVAL);
1865
1866	if (how != SHUT_WR)
1867		sorflush(so);
1868	if (how != SHUT_RD)
1869		return ((*pr->pr_usrreqs->pru_shutdown)(so));
1870	return (0);
1871}
1872
1873void
1874sorflush(struct socket *so)
1875{
1876	struct sockbuf *sb = &so->so_rcv;
1877	struct protosw *pr = so->so_proto;
1878	struct sockbuf asb;
1879
1880	/*
1881	 * In order to avoid calling dom_dispose with the socket buffer mutex
1882	 * held, and in order to generally avoid holding the lock for a long
1883	 * time, we make a copy of the socket buffer and clear the original
1884	 * (except locks, state).  The new socket buffer copy won't have
1885	 * initialized locks so we can only call routines that won't use or
1886	 * assert those locks.
1887	 *
1888	 * Dislodge threads currently blocked in receive and wait to acquire
1889	 * a lock against other simultaneous readers before clearing the
1890	 * socket buffer.  Don't let our acquire be interrupted by a signal
1891	 * despite any existing socket disposition on interruptable waiting.
1892	 */
1893	socantrcvmore(so);
1894	(void) sblock(sb, SBL_WAIT | SBL_NOINTR);
1895
1896	/*
1897	 * Invalidate/clear most of the sockbuf structure, but leave selinfo
1898	 * and mutex data unchanged.
1899	 */
1900	SOCKBUF_LOCK(sb);
1901	bzero(&asb, offsetof(struct sockbuf, sb_startzero));
1902	bcopy(&sb->sb_startzero, &asb.sb_startzero,
1903	    sizeof(*sb) - offsetof(struct sockbuf, sb_startzero));
1904	bzero(&sb->sb_startzero,
1905	    sizeof(*sb) - offsetof(struct sockbuf, sb_startzero));
1906	SOCKBUF_UNLOCK(sb);
1907	sbunlock(sb);
1908
1909	/*
1910	 * Dispose of special rights and flush the socket buffer.  Don't call
1911	 * any unsafe routines (that rely on locks being initialized) on asb.
1912	 */
1913	if (pr->pr_flags & PR_RIGHTS && pr->pr_domain->dom_dispose != NULL)
1914		(*pr->pr_domain->dom_dispose)(asb.sb_mb);
1915	sbrelease_internal(&asb, so);
1916}
1917
1918/*
1919 * Perhaps this routine, and sooptcopyout(), below, ought to come in an
1920 * additional variant to handle the case where the option value needs to be
1921 * some kind of integer, but not a specific size.  In addition to their use
1922 * here, these functions are also called by the protocol-level pr_ctloutput()
1923 * routines.
1924 */
1925int
1926sooptcopyin(struct sockopt *sopt, void *buf, size_t len, size_t minlen)
1927{
1928	size_t	valsize;
1929
1930	/*
1931	 * If the user gives us more than we wanted, we ignore it, but if we
1932	 * don't get the minimum length the caller wants, we return EINVAL.
1933	 * On success, sopt->sopt_valsize is set to however much we actually
1934	 * retrieved.
1935	 */
1936	if ((valsize = sopt->sopt_valsize) < minlen)
1937		return EINVAL;
1938	if (valsize > len)
1939		sopt->sopt_valsize = valsize = len;
1940
1941	if (sopt->sopt_td != NULL)
1942		return (copyin(sopt->sopt_val, buf, valsize));
1943
1944	bcopy(sopt->sopt_val, buf, valsize);
1945	return (0);
1946}
1947
1948/*
1949 * Kernel version of setsockopt(2).
1950 *
1951 * XXX: optlen is size_t, not socklen_t
1952 */
1953int
1954so_setsockopt(struct socket *so, int level, int optname, void *optval,
1955    size_t optlen)
1956{
1957	struct sockopt sopt;
1958
1959	sopt.sopt_level = level;
1960	sopt.sopt_name = optname;
1961	sopt.sopt_dir = SOPT_SET;
1962	sopt.sopt_val = optval;
1963	sopt.sopt_valsize = optlen;
1964	sopt.sopt_td = NULL;
1965	return (sosetopt(so, &sopt));
1966}
1967
1968int
1969sosetopt(struct socket *so, struct sockopt *sopt)
1970{
1971	int	error, optval;
1972	struct	linger l;
1973	struct	timeval tv;
1974	u_long  val;
1975#ifdef MAC
1976	struct mac extmac;
1977#endif
1978
1979	error = 0;
1980	if (sopt->sopt_level != SOL_SOCKET) {
1981		if (so->so_proto && so->so_proto->pr_ctloutput)
1982			return ((*so->so_proto->pr_ctloutput)
1983				  (so, sopt));
1984		error = ENOPROTOOPT;
1985	} else {
1986		switch (sopt->sopt_name) {
1987#ifdef INET
1988		case SO_ACCEPTFILTER:
1989			error = do_setopt_accept_filter(so, sopt);
1990			if (error)
1991				goto bad;
1992			break;
1993#endif
1994		case SO_LINGER:
1995			error = sooptcopyin(sopt, &l, sizeof l, sizeof l);
1996			if (error)
1997				goto bad;
1998
1999			SOCK_LOCK(so);
2000			so->so_linger = l.l_linger;
2001			if (l.l_onoff)
2002				so->so_options |= SO_LINGER;
2003			else
2004				so->so_options &= ~SO_LINGER;
2005			SOCK_UNLOCK(so);
2006			break;
2007
2008		case SO_DEBUG:
2009		case SO_KEEPALIVE:
2010		case SO_DONTROUTE:
2011		case SO_USELOOPBACK:
2012		case SO_BROADCAST:
2013		case SO_REUSEADDR:
2014		case SO_REUSEPORT:
2015		case SO_OOBINLINE:
2016		case SO_TIMESTAMP:
2017		case SO_BINTIME:
2018		case SO_NOSIGPIPE:
2019			error = sooptcopyin(sopt, &optval, sizeof optval,
2020					    sizeof optval);
2021			if (error)
2022				goto bad;
2023			SOCK_LOCK(so);
2024			if (optval)
2025				so->so_options |= sopt->sopt_name;
2026			else
2027				so->so_options &= ~sopt->sopt_name;
2028			SOCK_UNLOCK(so);
2029			break;
2030
2031		case SO_SNDBUF:
2032		case SO_RCVBUF:
2033		case SO_SNDLOWAT:
2034		case SO_RCVLOWAT:
2035			error = sooptcopyin(sopt, &optval, sizeof optval,
2036					    sizeof optval);
2037			if (error)
2038				goto bad;
2039
2040			/*
2041			 * Values < 1 make no sense for any of these options,
2042			 * so disallow them.
2043			 */
2044			if (optval < 1) {
2045				error = EINVAL;
2046				goto bad;
2047			}
2048
2049			switch (sopt->sopt_name) {
2050			case SO_SNDBUF:
2051			case SO_RCVBUF:
2052				if (sbreserve(sopt->sopt_name == SO_SNDBUF ?
2053				    &so->so_snd : &so->so_rcv, (u_long)optval,
2054				    so, curthread) == 0) {
2055					error = ENOBUFS;
2056					goto bad;
2057				}
2058				(sopt->sopt_name == SO_SNDBUF ? &so->so_snd :
2059				    &so->so_rcv)->sb_flags &= ~SB_AUTOSIZE;
2060				break;
2061
2062			/*
2063			 * Make sure the low-water is never greater than the
2064			 * high-water.
2065			 */
2066			case SO_SNDLOWAT:
2067				SOCKBUF_LOCK(&so->so_snd);
2068				so->so_snd.sb_lowat =
2069				    (optval > so->so_snd.sb_hiwat) ?
2070				    so->so_snd.sb_hiwat : optval;
2071				SOCKBUF_UNLOCK(&so->so_snd);
2072				break;
2073			case SO_RCVLOWAT:
2074				SOCKBUF_LOCK(&so->so_rcv);
2075				so->so_rcv.sb_lowat =
2076				    (optval > so->so_rcv.sb_hiwat) ?
2077				    so->so_rcv.sb_hiwat : optval;
2078				SOCKBUF_UNLOCK(&so->so_rcv);
2079				break;
2080			}
2081			break;
2082
2083		case SO_SNDTIMEO:
2084		case SO_RCVTIMEO:
2085#ifdef COMPAT_IA32
2086			if (curthread->td_proc->p_sysent == &ia32_freebsd_sysvec) {
2087				struct timeval32 tv32;
2088
2089				error = sooptcopyin(sopt, &tv32, sizeof tv32,
2090				    sizeof tv32);
2091				CP(tv32, tv, tv_sec);
2092				CP(tv32, tv, tv_usec);
2093			} else
2094#endif
2095				error = sooptcopyin(sopt, &tv, sizeof tv,
2096				    sizeof tv);
2097			if (error)
2098				goto bad;
2099
2100			/* assert(hz > 0); */
2101			if (tv.tv_sec < 0 || tv.tv_sec > INT_MAX / hz ||
2102			    tv.tv_usec < 0 || tv.tv_usec >= 1000000) {
2103				error = EDOM;
2104				goto bad;
2105			}
2106			/* assert(tick > 0); */
2107			/* assert(ULONG_MAX - INT_MAX >= 1000000); */
2108			val = (u_long)(tv.tv_sec * hz) + tv.tv_usec / tick;
2109			if (val > INT_MAX) {
2110				error = EDOM;
2111				goto bad;
2112			}
2113			if (val == 0 && tv.tv_usec != 0)
2114				val = 1;
2115
2116			switch (sopt->sopt_name) {
2117			case SO_SNDTIMEO:
2118				so->so_snd.sb_timeo = val;
2119				break;
2120			case SO_RCVTIMEO:
2121				so->so_rcv.sb_timeo = val;
2122				break;
2123			}
2124			break;
2125
2126		case SO_LABEL:
2127#ifdef MAC
2128			error = sooptcopyin(sopt, &extmac, sizeof extmac,
2129			    sizeof extmac);
2130			if (error)
2131				goto bad;
2132			error = mac_setsockopt_label(sopt->sopt_td->td_ucred,
2133			    so, &extmac);
2134#else
2135			error = EOPNOTSUPP;
2136#endif
2137			break;
2138
2139		default:
2140			error = ENOPROTOOPT;
2141			break;
2142		}
2143		if (error == 0 && so->so_proto != NULL &&
2144		    so->so_proto->pr_ctloutput != NULL) {
2145			(void) ((*so->so_proto->pr_ctloutput)
2146				  (so, sopt));
2147		}
2148	}
2149bad:
2150	return (error);
2151}
2152
2153/*
2154 * Helper routine for getsockopt.
2155 */
2156int
2157sooptcopyout(struct sockopt *sopt, const void *buf, size_t len)
2158{
2159	int	error;
2160	size_t	valsize;
2161
2162	error = 0;
2163
2164	/*
2165	 * Documented get behavior is that we always return a value, possibly
2166	 * truncated to fit in the user's buffer.  Traditional behavior is
2167	 * that we always tell the user precisely how much we copied, rather
2168	 * than something useful like the total amount we had available for
2169	 * her.  Note that this interface is not idempotent; the entire
2170	 * answer must generated ahead of time.
2171	 */
2172	valsize = min(len, sopt->sopt_valsize);
2173	sopt->sopt_valsize = valsize;
2174	if (sopt->sopt_val != NULL) {
2175		if (sopt->sopt_td != NULL)
2176			error = copyout(buf, sopt->sopt_val, valsize);
2177		else
2178			bcopy(buf, sopt->sopt_val, valsize);
2179	}
2180	return (error);
2181}
2182
2183int
2184sogetopt(struct socket *so, struct sockopt *sopt)
2185{
2186	int	error, optval;
2187	struct	linger l;
2188	struct	timeval tv;
2189#ifdef MAC
2190	struct mac extmac;
2191#endif
2192
2193	error = 0;
2194	if (sopt->sopt_level != SOL_SOCKET) {
2195		if (so->so_proto && so->so_proto->pr_ctloutput) {
2196			return ((*so->so_proto->pr_ctloutput)
2197				  (so, sopt));
2198		} else
2199			return (ENOPROTOOPT);
2200	} else {
2201		switch (sopt->sopt_name) {
2202#ifdef INET
2203		case SO_ACCEPTFILTER:
2204			error = do_getopt_accept_filter(so, sopt);
2205			break;
2206#endif
2207		case SO_LINGER:
2208			SOCK_LOCK(so);
2209			l.l_onoff = so->so_options & SO_LINGER;
2210			l.l_linger = so->so_linger;
2211			SOCK_UNLOCK(so);
2212			error = sooptcopyout(sopt, &l, sizeof l);
2213			break;
2214
2215		case SO_USELOOPBACK:
2216		case SO_DONTROUTE:
2217		case SO_DEBUG:
2218		case SO_KEEPALIVE:
2219		case SO_REUSEADDR:
2220		case SO_REUSEPORT:
2221		case SO_BROADCAST:
2222		case SO_OOBINLINE:
2223		case SO_ACCEPTCONN:
2224		case SO_TIMESTAMP:
2225		case SO_BINTIME:
2226		case SO_NOSIGPIPE:
2227			optval = so->so_options & sopt->sopt_name;
2228integer:
2229			error = sooptcopyout(sopt, &optval, sizeof optval);
2230			break;
2231
2232		case SO_TYPE:
2233			optval = so->so_type;
2234			goto integer;
2235
2236		case SO_ERROR:
2237			SOCK_LOCK(so);
2238			optval = so->so_error;
2239			so->so_error = 0;
2240			SOCK_UNLOCK(so);
2241			goto integer;
2242
2243		case SO_SNDBUF:
2244			optval = so->so_snd.sb_hiwat;
2245			goto integer;
2246
2247		case SO_RCVBUF:
2248			optval = so->so_rcv.sb_hiwat;
2249			goto integer;
2250
2251		case SO_SNDLOWAT:
2252			optval = so->so_snd.sb_lowat;
2253			goto integer;
2254
2255		case SO_RCVLOWAT:
2256			optval = so->so_rcv.sb_lowat;
2257			goto integer;
2258
2259		case SO_SNDTIMEO:
2260		case SO_RCVTIMEO:
2261			optval = (sopt->sopt_name == SO_SNDTIMEO ?
2262				  so->so_snd.sb_timeo : so->so_rcv.sb_timeo);
2263
2264			tv.tv_sec = optval / hz;
2265			tv.tv_usec = (optval % hz) * tick;
2266#ifdef COMPAT_IA32
2267			if (curthread->td_proc->p_sysent == &ia32_freebsd_sysvec) {
2268				struct timeval32 tv32;
2269
2270				CP(tv, tv32, tv_sec);
2271				CP(tv, tv32, tv_usec);
2272				error = sooptcopyout(sopt, &tv32, sizeof tv32);
2273			} else
2274#endif
2275				error = sooptcopyout(sopt, &tv, sizeof tv);
2276			break;
2277
2278		case SO_LABEL:
2279#ifdef MAC
2280			error = sooptcopyin(sopt, &extmac, sizeof(extmac),
2281			    sizeof(extmac));
2282			if (error)
2283				return (error);
2284			error = mac_getsockopt_label(sopt->sopt_td->td_ucred,
2285			    so, &extmac);
2286			if (error)
2287				return (error);
2288			error = sooptcopyout(sopt, &extmac, sizeof extmac);
2289#else
2290			error = EOPNOTSUPP;
2291#endif
2292			break;
2293
2294		case SO_PEERLABEL:
2295#ifdef MAC
2296			error = sooptcopyin(sopt, &extmac, sizeof(extmac),
2297			    sizeof(extmac));
2298			if (error)
2299				return (error);
2300			error = mac_getsockopt_peerlabel(
2301			    sopt->sopt_td->td_ucred, so, &extmac);
2302			if (error)
2303				return (error);
2304			error = sooptcopyout(sopt, &extmac, sizeof extmac);
2305#else
2306			error = EOPNOTSUPP;
2307#endif
2308			break;
2309
2310		case SO_LISTENQLIMIT:
2311			optval = so->so_qlimit;
2312			goto integer;
2313
2314		case SO_LISTENQLEN:
2315			optval = so->so_qlen;
2316			goto integer;
2317
2318		case SO_LISTENINCQLEN:
2319			optval = so->so_incqlen;
2320			goto integer;
2321
2322		default:
2323			error = ENOPROTOOPT;
2324			break;
2325		}
2326		return (error);
2327	}
2328}
2329
2330/* XXX; prepare mbuf for (__FreeBSD__ < 3) routines. */
2331int
2332soopt_getm(struct sockopt *sopt, struct mbuf **mp)
2333{
2334	struct mbuf *m, *m_prev;
2335	int sopt_size = sopt->sopt_valsize;
2336
2337	MGET(m, sopt->sopt_td ? M_TRYWAIT : M_DONTWAIT, MT_DATA);
2338	if (m == NULL)
2339		return ENOBUFS;
2340	if (sopt_size > MLEN) {
2341		MCLGET(m, sopt->sopt_td ? M_TRYWAIT : M_DONTWAIT);
2342		if ((m->m_flags & M_EXT) == 0) {
2343			m_free(m);
2344			return ENOBUFS;
2345		}
2346		m->m_len = min(MCLBYTES, sopt_size);
2347	} else {
2348		m->m_len = min(MLEN, sopt_size);
2349	}
2350	sopt_size -= m->m_len;
2351	*mp = m;
2352	m_prev = m;
2353
2354	while (sopt_size) {
2355		MGET(m, sopt->sopt_td ? M_TRYWAIT : M_DONTWAIT, MT_DATA);
2356		if (m == NULL) {
2357			m_freem(*mp);
2358			return ENOBUFS;
2359		}
2360		if (sopt_size > MLEN) {
2361			MCLGET(m, sopt->sopt_td != NULL ? M_TRYWAIT :
2362			    M_DONTWAIT);
2363			if ((m->m_flags & M_EXT) == 0) {
2364				m_freem(m);
2365				m_freem(*mp);
2366				return ENOBUFS;
2367			}
2368			m->m_len = min(MCLBYTES, sopt_size);
2369		} else {
2370			m->m_len = min(MLEN, sopt_size);
2371		}
2372		sopt_size -= m->m_len;
2373		m_prev->m_next = m;
2374		m_prev = m;
2375	}
2376	return (0);
2377}
2378
2379/* XXX; copyin sopt data into mbuf chain for (__FreeBSD__ < 3) routines. */
2380int
2381soopt_mcopyin(struct sockopt *sopt, struct mbuf *m)
2382{
2383	struct mbuf *m0 = m;
2384
2385	if (sopt->sopt_val == NULL)
2386		return (0);
2387	while (m != NULL && sopt->sopt_valsize >= m->m_len) {
2388		if (sopt->sopt_td != NULL) {
2389			int error;
2390
2391			error = copyin(sopt->sopt_val, mtod(m, char *),
2392				       m->m_len);
2393			if (error != 0) {
2394				m_freem(m0);
2395				return(error);
2396			}
2397		} else
2398			bcopy(sopt->sopt_val, mtod(m, char *), m->m_len);
2399		sopt->sopt_valsize -= m->m_len;
2400		sopt->sopt_val = (char *)sopt->sopt_val + m->m_len;
2401		m = m->m_next;
2402	}
2403	if (m != NULL) /* should be allocated enoughly at ip6_sooptmcopyin() */
2404		panic("ip6_sooptmcopyin");
2405	return (0);
2406}
2407
2408/* XXX; copyout mbuf chain data into soopt for (__FreeBSD__ < 3) routines. */
2409int
2410soopt_mcopyout(struct sockopt *sopt, struct mbuf *m)
2411{
2412	struct mbuf *m0 = m;
2413	size_t valsize = 0;
2414
2415	if (sopt->sopt_val == NULL)
2416		return (0);
2417	while (m != NULL && sopt->sopt_valsize >= m->m_len) {
2418		if (sopt->sopt_td != NULL) {
2419			int error;
2420
2421			error = copyout(mtod(m, char *), sopt->sopt_val,
2422				       m->m_len);
2423			if (error != 0) {
2424				m_freem(m0);
2425				return(error);
2426			}
2427		} else
2428			bcopy(mtod(m, char *), sopt->sopt_val, m->m_len);
2429	       sopt->sopt_valsize -= m->m_len;
2430	       sopt->sopt_val = (char *)sopt->sopt_val + m->m_len;
2431	       valsize += m->m_len;
2432	       m = m->m_next;
2433	}
2434	if (m != NULL) {
2435		/* enough soopt buffer should be given from user-land */
2436		m_freem(m0);
2437		return(EINVAL);
2438	}
2439	sopt->sopt_valsize = valsize;
2440	return (0);
2441}
2442
2443/*
2444 * sohasoutofband(): protocol notifies socket layer of the arrival of new
2445 * out-of-band data, which will then notify socket consumers.
2446 */
2447void
2448sohasoutofband(struct socket *so)
2449{
2450
2451	if (so->so_sigio != NULL)
2452		pgsigio(&so->so_sigio, SIGURG, 0);
2453	selwakeuppri(&so->so_rcv.sb_sel, PSOCK);
2454}
2455
2456int
2457sopoll(struct socket *so, int events, struct ucred *active_cred,
2458    struct thread *td)
2459{
2460
2461	/* XXXRW: Temporary debugging. */
2462	KASSERT(so->so_proto->pr_usrreqs->pru_sopoll != sopoll,
2463	    ("sopoll: protocol calls sopoll"));
2464
2465	return (so->so_proto->pr_usrreqs->pru_sopoll(so, events, active_cred,
2466	    td));
2467}
2468
2469int
2470sopoll_generic(struct socket *so, int events, struct ucred *active_cred,
2471    struct thread *td)
2472{
2473	int revents = 0;
2474
2475	SOCKBUF_LOCK(&so->so_snd);
2476	SOCKBUF_LOCK(&so->so_rcv);
2477	if (events & (POLLIN | POLLRDNORM))
2478		if (soreadable(so))
2479			revents |= events & (POLLIN | POLLRDNORM);
2480
2481	if (events & POLLINIGNEOF)
2482		if (so->so_rcv.sb_cc >= so->so_rcv.sb_lowat ||
2483		    !TAILQ_EMPTY(&so->so_comp) || so->so_error)
2484			revents |= POLLINIGNEOF;
2485
2486	if (events & (POLLOUT | POLLWRNORM))
2487		if (sowriteable(so))
2488			revents |= events & (POLLOUT | POLLWRNORM);
2489
2490	if (events & (POLLPRI | POLLRDBAND))
2491		if (so->so_oobmark || (so->so_rcv.sb_state & SBS_RCVATMARK))
2492			revents |= events & (POLLPRI | POLLRDBAND);
2493
2494	if (revents == 0) {
2495		if (events &
2496		    (POLLIN | POLLINIGNEOF | POLLPRI | POLLRDNORM |
2497		     POLLRDBAND)) {
2498			selrecord(td, &so->so_rcv.sb_sel);
2499			so->so_rcv.sb_flags |= SB_SEL;
2500		}
2501
2502		if (events & (POLLOUT | POLLWRNORM)) {
2503			selrecord(td, &so->so_snd.sb_sel);
2504			so->so_snd.sb_flags |= SB_SEL;
2505		}
2506	}
2507
2508	SOCKBUF_UNLOCK(&so->so_rcv);
2509	SOCKBUF_UNLOCK(&so->so_snd);
2510	return (revents);
2511}
2512
2513int
2514soo_kqfilter(struct file *fp, struct knote *kn)
2515{
2516	struct socket *so = kn->kn_fp->f_data;
2517	struct sockbuf *sb;
2518
2519	switch (kn->kn_filter) {
2520	case EVFILT_READ:
2521		if (so->so_options & SO_ACCEPTCONN)
2522			kn->kn_fop = &solisten_filtops;
2523		else
2524			kn->kn_fop = &soread_filtops;
2525		sb = &so->so_rcv;
2526		break;
2527	case EVFILT_WRITE:
2528		kn->kn_fop = &sowrite_filtops;
2529		sb = &so->so_snd;
2530		break;
2531	default:
2532		return (EINVAL);
2533	}
2534
2535	SOCKBUF_LOCK(sb);
2536	knlist_add(&sb->sb_sel.si_note, kn, 1);
2537	sb->sb_flags |= SB_KNOTE;
2538	SOCKBUF_UNLOCK(sb);
2539	return (0);
2540}
2541
2542/*
2543 * Some routines that return EOPNOTSUPP for entry points that are not
2544 * supported by a protocol.  Fill in as needed.
2545 */
2546int
2547pru_accept_notsupp(struct socket *so, struct sockaddr **nam)
2548{
2549
2550	return EOPNOTSUPP;
2551}
2552
2553int
2554pru_attach_notsupp(struct socket *so, int proto, struct thread *td)
2555{
2556
2557	return EOPNOTSUPP;
2558}
2559
2560int
2561pru_bind_notsupp(struct socket *so, struct sockaddr *nam, struct thread *td)
2562{
2563
2564	return EOPNOTSUPP;
2565}
2566
2567int
2568pru_connect_notsupp(struct socket *so, struct sockaddr *nam, struct thread *td)
2569{
2570
2571	return EOPNOTSUPP;
2572}
2573
2574int
2575pru_connect2_notsupp(struct socket *so1, struct socket *so2)
2576{
2577
2578	return EOPNOTSUPP;
2579}
2580
2581int
2582pru_control_notsupp(struct socket *so, u_long cmd, caddr_t data,
2583    struct ifnet *ifp, struct thread *td)
2584{
2585
2586	return EOPNOTSUPP;
2587}
2588
2589int
2590pru_disconnect_notsupp(struct socket *so)
2591{
2592
2593	return EOPNOTSUPP;
2594}
2595
2596int
2597pru_listen_notsupp(struct socket *so, int backlog, struct thread *td)
2598{
2599
2600	return EOPNOTSUPP;
2601}
2602
2603int
2604pru_peeraddr_notsupp(struct socket *so, struct sockaddr **nam)
2605{
2606
2607	return EOPNOTSUPP;
2608}
2609
2610int
2611pru_rcvd_notsupp(struct socket *so, int flags)
2612{
2613
2614	return EOPNOTSUPP;
2615}
2616
2617int
2618pru_rcvoob_notsupp(struct socket *so, struct mbuf *m, int flags)
2619{
2620
2621	return EOPNOTSUPP;
2622}
2623
2624int
2625pru_send_notsupp(struct socket *so, int flags, struct mbuf *m,
2626    struct sockaddr *addr, struct mbuf *control, struct thread *td)
2627{
2628
2629	return EOPNOTSUPP;
2630}
2631
2632/*
2633 * This isn't really a ``null'' operation, but it's the default one and
2634 * doesn't do anything destructive.
2635 */
2636int
2637pru_sense_null(struct socket *so, struct stat *sb)
2638{
2639
2640	sb->st_blksize = so->so_snd.sb_hiwat;
2641	return 0;
2642}
2643
2644int
2645pru_shutdown_notsupp(struct socket *so)
2646{
2647
2648	return EOPNOTSUPP;
2649}
2650
2651int
2652pru_sockaddr_notsupp(struct socket *so, struct sockaddr **nam)
2653{
2654
2655	return EOPNOTSUPP;
2656}
2657
2658int
2659pru_sosend_notsupp(struct socket *so, struct sockaddr *addr, struct uio *uio,
2660    struct mbuf *top, struct mbuf *control, int flags, struct thread *td)
2661{
2662
2663	return EOPNOTSUPP;
2664}
2665
2666int
2667pru_soreceive_notsupp(struct socket *so, struct sockaddr **paddr,
2668    struct uio *uio, struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
2669{
2670
2671	return EOPNOTSUPP;
2672}
2673
2674int
2675pru_sopoll_notsupp(struct socket *so, int events, struct ucred *cred,
2676    struct thread *td)
2677{
2678
2679	return EOPNOTSUPP;
2680}
2681
2682static void
2683filt_sordetach(struct knote *kn)
2684{
2685	struct socket *so = kn->kn_fp->f_data;
2686
2687	SOCKBUF_LOCK(&so->so_rcv);
2688	knlist_remove(&so->so_rcv.sb_sel.si_note, kn, 1);
2689	if (knlist_empty(&so->so_rcv.sb_sel.si_note))
2690		so->so_rcv.sb_flags &= ~SB_KNOTE;
2691	SOCKBUF_UNLOCK(&so->so_rcv);
2692}
2693
2694/*ARGSUSED*/
2695static int
2696filt_soread(struct knote *kn, long hint)
2697{
2698	struct socket *so;
2699
2700	so = kn->kn_fp->f_data;
2701	SOCKBUF_LOCK_ASSERT(&so->so_rcv);
2702
2703	kn->kn_data = so->so_rcv.sb_cc - so->so_rcv.sb_ctl;
2704	if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
2705		kn->kn_flags |= EV_EOF;
2706		kn->kn_fflags = so->so_error;
2707		return (1);
2708	} else if (so->so_error)	/* temporary udp error */
2709		return (1);
2710	else if (kn->kn_sfflags & NOTE_LOWAT)
2711		return (kn->kn_data >= kn->kn_sdata);
2712	else
2713		return (so->so_rcv.sb_cc >= so->so_rcv.sb_lowat);
2714}
2715
2716static void
2717filt_sowdetach(struct knote *kn)
2718{
2719	struct socket *so = kn->kn_fp->f_data;
2720
2721	SOCKBUF_LOCK(&so->so_snd);
2722	knlist_remove(&so->so_snd.sb_sel.si_note, kn, 1);
2723	if (knlist_empty(&so->so_snd.sb_sel.si_note))
2724		so->so_snd.sb_flags &= ~SB_KNOTE;
2725	SOCKBUF_UNLOCK(&so->so_snd);
2726}
2727
2728/*ARGSUSED*/
2729static int
2730filt_sowrite(struct knote *kn, long hint)
2731{
2732	struct socket *so;
2733
2734	so = kn->kn_fp->f_data;
2735	SOCKBUF_LOCK_ASSERT(&so->so_snd);
2736	kn->kn_data = sbspace(&so->so_snd);
2737	if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
2738		kn->kn_flags |= EV_EOF;
2739		kn->kn_fflags = so->so_error;
2740		return (1);
2741	} else if (so->so_error)	/* temporary udp error */
2742		return (1);
2743	else if (((so->so_state & SS_ISCONNECTED) == 0) &&
2744	    (so->so_proto->pr_flags & PR_CONNREQUIRED))
2745		return (0);
2746	else if (kn->kn_sfflags & NOTE_LOWAT)
2747		return (kn->kn_data >= kn->kn_sdata);
2748	else
2749		return (kn->kn_data >= so->so_snd.sb_lowat);
2750}
2751
2752/*ARGSUSED*/
2753static int
2754filt_solisten(struct knote *kn, long hint)
2755{
2756	struct socket *so = kn->kn_fp->f_data;
2757
2758	kn->kn_data = so->so_qlen;
2759	return (! TAILQ_EMPTY(&so->so_comp));
2760}
2761
2762int
2763socheckuid(struct socket *so, uid_t uid)
2764{
2765
2766	if (so == NULL)
2767		return (EPERM);
2768	if (so->so_cred->cr_uid != uid)
2769		return (EPERM);
2770	return (0);
2771}
2772
2773static int
2774sysctl_somaxconn(SYSCTL_HANDLER_ARGS)
2775{
2776	int error;
2777	int val;
2778
2779	val = somaxconn;
2780	error = sysctl_handle_int(oidp, &val, 0, req);
2781	if (error || !req->newptr )
2782		return (error);
2783
2784	if (val < 1 || val > USHRT_MAX)
2785		return (EINVAL);
2786
2787	somaxconn = val;
2788	return (0);
2789}
2790
2791/*
2792 * These functions are used by protocols to notify the socket layer (and its
2793 * consumers) of state changes in the sockets driven by protocol-side events.
2794 */
2795
2796/*
2797 * Procedures to manipulate state flags of socket and do appropriate wakeups.
2798 *
2799 * Normal sequence from the active (originating) side is that
2800 * soisconnecting() is called during processing of connect() call, resulting
2801 * in an eventual call to soisconnected() if/when the connection is
2802 * established.  When the connection is torn down soisdisconnecting() is
2803 * called during processing of disconnect() call, and soisdisconnected() is
2804 * called when the connection to the peer is totally severed.  The semantics
2805 * of these routines are such that connectionless protocols can call
2806 * soisconnected() and soisdisconnected() only, bypassing the in-progress
2807 * calls when setting up a ``connection'' takes no time.
2808 *
2809 * From the passive side, a socket is created with two queues of sockets:
2810 * so_incomp for connections in progress and so_comp for connections already
2811 * made and awaiting user acceptance.  As a protocol is preparing incoming
2812 * connections, it creates a socket structure queued on so_incomp by calling
2813 * sonewconn().  When the connection is established, soisconnected() is
2814 * called, and transfers the socket structure to so_comp, making it available
2815 * to accept().
2816 *
2817 * If a socket is closed with sockets on either so_incomp or so_comp, these
2818 * sockets are dropped.
2819 *
2820 * If higher-level protocols are implemented in the kernel, the wakeups done
2821 * here will sometimes cause software-interrupt process scheduling.
2822 */
2823void
2824soisconnecting(struct socket *so)
2825{
2826
2827	SOCK_LOCK(so);
2828	so->so_state &= ~(SS_ISCONNECTED|SS_ISDISCONNECTING);
2829	so->so_state |= SS_ISCONNECTING;
2830	SOCK_UNLOCK(so);
2831}
2832
2833void
2834soisconnected(struct socket *so)
2835{
2836	struct socket *head;
2837
2838	ACCEPT_LOCK();
2839	SOCK_LOCK(so);
2840	so->so_state &= ~(SS_ISCONNECTING|SS_ISDISCONNECTING|SS_ISCONFIRMING);
2841	so->so_state |= SS_ISCONNECTED;
2842	head = so->so_head;
2843	if (head != NULL && (so->so_qstate & SQ_INCOMP)) {
2844		if ((so->so_options & SO_ACCEPTFILTER) == 0) {
2845			SOCK_UNLOCK(so);
2846			TAILQ_REMOVE(&head->so_incomp, so, so_list);
2847			head->so_incqlen--;
2848			so->so_qstate &= ~SQ_INCOMP;
2849			TAILQ_INSERT_TAIL(&head->so_comp, so, so_list);
2850			head->so_qlen++;
2851			so->so_qstate |= SQ_COMP;
2852			ACCEPT_UNLOCK();
2853			sorwakeup(head);
2854			wakeup_one(&head->so_timeo);
2855		} else {
2856			ACCEPT_UNLOCK();
2857			so->so_upcall =
2858			    head->so_accf->so_accept_filter->accf_callback;
2859			so->so_upcallarg = head->so_accf->so_accept_filter_arg;
2860			so->so_rcv.sb_flags |= SB_UPCALL;
2861			so->so_options &= ~SO_ACCEPTFILTER;
2862			SOCK_UNLOCK(so);
2863			so->so_upcall(so, so->so_upcallarg, M_DONTWAIT);
2864		}
2865		return;
2866	}
2867	SOCK_UNLOCK(so);
2868	ACCEPT_UNLOCK();
2869	wakeup(&so->so_timeo);
2870	sorwakeup(so);
2871	sowwakeup(so);
2872}
2873
2874void
2875soisdisconnecting(struct socket *so)
2876{
2877
2878	/*
2879	 * Note: This code assumes that SOCK_LOCK(so) and
2880	 * SOCKBUF_LOCK(&so->so_rcv) are the same.
2881	 */
2882	SOCKBUF_LOCK(&so->so_rcv);
2883	so->so_state &= ~SS_ISCONNECTING;
2884	so->so_state |= SS_ISDISCONNECTING;
2885	so->so_rcv.sb_state |= SBS_CANTRCVMORE;
2886	sorwakeup_locked(so);
2887	SOCKBUF_LOCK(&so->so_snd);
2888	so->so_snd.sb_state |= SBS_CANTSENDMORE;
2889	sowwakeup_locked(so);
2890	wakeup(&so->so_timeo);
2891}
2892
2893void
2894soisdisconnected(struct socket *so)
2895{
2896
2897	/*
2898	 * Note: This code assumes that SOCK_LOCK(so) and
2899	 * SOCKBUF_LOCK(&so->so_rcv) are the same.
2900	 */
2901	SOCKBUF_LOCK(&so->so_rcv);
2902	so->so_state &= ~(SS_ISCONNECTING|SS_ISCONNECTED|SS_ISDISCONNECTING);
2903	so->so_state |= SS_ISDISCONNECTED;
2904	so->so_rcv.sb_state |= SBS_CANTRCVMORE;
2905	sorwakeup_locked(so);
2906	SOCKBUF_LOCK(&so->so_snd);
2907	so->so_snd.sb_state |= SBS_CANTSENDMORE;
2908	sbdrop_locked(&so->so_snd, so->so_snd.sb_cc);
2909	sowwakeup_locked(so);
2910	wakeup(&so->so_timeo);
2911}
2912
2913/*
2914 * Make a copy of a sockaddr in a malloced buffer of type M_SONAME.
2915 */
2916struct sockaddr *
2917sodupsockaddr(const struct sockaddr *sa, int mflags)
2918{
2919	struct sockaddr *sa2;
2920
2921	sa2 = malloc(sa->sa_len, M_SONAME, mflags);
2922	if (sa2)
2923		bcopy(sa, sa2, sa->sa_len);
2924	return sa2;
2925}
2926
2927/*
2928 * Create an external-format (``xsocket'') structure using the information in
2929 * the kernel-format socket structure pointed to by so.  This is done to
2930 * reduce the spew of irrelevant information over this interface, to isolate
2931 * user code from changes in the kernel structure, and potentially to provide
2932 * information-hiding if we decide that some of this information should be
2933 * hidden from users.
2934 */
2935void
2936sotoxsocket(struct socket *so, struct xsocket *xso)
2937{
2938
2939	xso->xso_len = sizeof *xso;
2940	xso->xso_so = so;
2941	xso->so_type = so->so_type;
2942	xso->so_options = so->so_options;
2943	xso->so_linger = so->so_linger;
2944	xso->so_state = so->so_state;
2945	xso->so_pcb = so->so_pcb;
2946	xso->xso_protocol = so->so_proto->pr_protocol;
2947	xso->xso_family = so->so_proto->pr_domain->dom_family;
2948	xso->so_qlen = so->so_qlen;
2949	xso->so_incqlen = so->so_incqlen;
2950	xso->so_qlimit = so->so_qlimit;
2951	xso->so_timeo = so->so_timeo;
2952	xso->so_error = so->so_error;
2953	xso->so_pgid = so->so_sigio ? so->so_sigio->sio_pgid : 0;
2954	xso->so_oobmark = so->so_oobmark;
2955	sbtoxsockbuf(&so->so_snd, &xso->so_snd);
2956	sbtoxsockbuf(&so->so_rcv, &xso->so_rcv);
2957	xso->so_uid = so->so_cred->cr_uid;
2958}
2959