xref: /freebsd/sys/kern/uipc_socket.c (revision 098ca2bda93c701c5331d4e6aace072495b4caaa)
1 /*
2  * Copyright (c) 2004 The FreeBSD Foundation
3  * Copyright (c) 2004 Robert Watson
4  * Copyright (c) 1982, 1986, 1988, 1990, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 4. Neither the name of the University nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  *
31  *	@(#)uipc_socket.c	8.3 (Berkeley) 4/15/94
32  */
33 
34 #include <sys/cdefs.h>
35 __FBSDID("$FreeBSD$");
36 
37 #include "opt_inet.h"
38 #include "opt_mac.h"
39 #include "opt_zero.h"
40 
41 #include <sys/param.h>
42 #include <sys/systm.h>
43 #include <sys/fcntl.h>
44 #include <sys/limits.h>
45 #include <sys/lock.h>
46 #include <sys/mac.h>
47 #include <sys/malloc.h>
48 #include <sys/mbuf.h>
49 #include <sys/mutex.h>
50 #include <sys/domain.h>
51 #include <sys/file.h>			/* for struct knote */
52 #include <sys/kernel.h>
53 #include <sys/event.h>
54 #include <sys/poll.h>
55 #include <sys/proc.h>
56 #include <sys/protosw.h>
57 #include <sys/socket.h>
58 #include <sys/socketvar.h>
59 #include <sys/resourcevar.h>
60 #include <sys/signalvar.h>
61 #include <sys/sysctl.h>
62 #include <sys/uio.h>
63 #include <sys/jail.h>
64 
65 #include <vm/uma.h>
66 
67 
68 static int	soreceive_rcvoob(struct socket *so, struct uio *uio,
69 		    int flags);
70 
71 #ifdef INET
72 static int	 do_setopt_accept_filter(struct socket *so, struct sockopt *sopt);
73 #endif
74 
75 static void	filt_sordetach(struct knote *kn);
76 static int	filt_soread(struct knote *kn, long hint);
77 static void	filt_sowdetach(struct knote *kn);
78 static int	filt_sowrite(struct knote *kn, long hint);
79 static int	filt_solisten(struct knote *kn, long hint);
80 
81 static struct filterops solisten_filtops =
82 	{ 1, NULL, filt_sordetach, filt_solisten };
83 static struct filterops soread_filtops =
84 	{ 1, NULL, filt_sordetach, filt_soread };
85 static struct filterops sowrite_filtops =
86 	{ 1, NULL, filt_sowdetach, filt_sowrite };
87 
88 uma_zone_t socket_zone;
89 so_gen_t	so_gencnt;	/* generation count for sockets */
90 
91 MALLOC_DEFINE(M_SONAME, "soname", "socket name");
92 MALLOC_DEFINE(M_PCB, "pcb", "protocol control block");
93 
94 SYSCTL_DECL(_kern_ipc);
95 
96 static int somaxconn = SOMAXCONN;
97 SYSCTL_INT(_kern_ipc, KIPC_SOMAXCONN, somaxconn, CTLFLAG_RW,
98     &somaxconn, 0, "Maximum pending socket connection queue size");
99 static int numopensockets;
100 SYSCTL_INT(_kern_ipc, OID_AUTO, numopensockets, CTLFLAG_RD,
101     &numopensockets, 0, "Number of open sockets");
102 #ifdef ZERO_COPY_SOCKETS
103 /* These aren't static because they're used in other files. */
104 int so_zero_copy_send = 1;
105 int so_zero_copy_receive = 1;
106 SYSCTL_NODE(_kern_ipc, OID_AUTO, zero_copy, CTLFLAG_RD, 0,
107     "Zero copy controls");
108 SYSCTL_INT(_kern_ipc_zero_copy, OID_AUTO, receive, CTLFLAG_RW,
109     &so_zero_copy_receive, 0, "Enable zero copy receive");
110 SYSCTL_INT(_kern_ipc_zero_copy, OID_AUTO, send, CTLFLAG_RW,
111     &so_zero_copy_send, 0, "Enable zero copy send");
112 #endif /* ZERO_COPY_SOCKETS */
113 
114 /*
115  * accept_mtx locks down per-socket fields relating to accept queues.  See
116  * socketvar.h for an annotation of the protected fields of struct socket.
117  */
118 struct mtx accept_mtx;
119 MTX_SYSINIT(accept_mtx, &accept_mtx, "accept", MTX_DEF);
120 
121 /*
122  * so_global_mtx protects so_gencnt, numopensockets, and the per-socket
123  * so_gencnt field.
124  */
125 static struct mtx so_global_mtx;
126 MTX_SYSINIT(so_global_mtx, &so_global_mtx, "so_glabel", MTX_DEF);
127 
128 /*
129  * Socket operation routines.
130  * These routines are called by the routines in
131  * sys_socket.c or from a system process, and
132  * implement the semantics of socket operations by
133  * switching out to the protocol specific routines.
134  */
135 
136 /*
137  * Get a socket structure from our zone, and initialize it.
138  * Note that it would probably be better to allocate socket
139  * and PCB at the same time, but I'm not convinced that all
140  * the protocols can be easily modified to do this.
141  *
142  * soalloc() returns a socket with a ref count of 0.
143  */
144 struct socket *
145 soalloc(int mflags)
146 {
147 	struct socket *so;
148 
149 	so = uma_zalloc(socket_zone, mflags | M_ZERO);
150 	if (so != NULL) {
151 #ifdef MAC
152 		if (mac_init_socket(so, mflags) != 0) {
153 			uma_zfree(socket_zone, so);
154 			return (NULL);
155 		}
156 #endif
157 		SOCKBUF_LOCK_INIT(&so->so_snd, "so_snd");
158 		SOCKBUF_LOCK_INIT(&so->so_rcv, "so_rcv");
159 		/* sx_init(&so->so_sxlock, "socket sxlock"); */
160 		TAILQ_INIT(&so->so_aiojobq);
161 		mtx_lock(&so_global_mtx);
162 		so->so_gencnt = ++so_gencnt;
163 		++numopensockets;
164 		mtx_unlock(&so_global_mtx);
165 	}
166 	return (so);
167 }
168 
169 /*
170  * socreate returns a socket with a ref count of 1.  The socket should be
171  * closed with soclose().
172  */
173 int
174 socreate(dom, aso, type, proto, cred, td)
175 	int dom;
176 	struct socket **aso;
177 	int type;
178 	int proto;
179 	struct ucred *cred;
180 	struct thread *td;
181 {
182 	struct protosw *prp;
183 	struct socket *so;
184 	int error;
185 
186 	if (proto)
187 		prp = pffindproto(dom, proto, type);
188 	else
189 		prp = pffindtype(dom, type);
190 
191 	if (prp == NULL || prp->pr_usrreqs->pru_attach == NULL ||
192 	    prp->pr_usrreqs->pru_attach == pru_attach_notsupp)
193 		return (EPROTONOSUPPORT);
194 
195 	if (jailed(cred) && jail_socket_unixiproute_only &&
196 	    prp->pr_domain->dom_family != PF_LOCAL &&
197 	    prp->pr_domain->dom_family != PF_INET &&
198 	    prp->pr_domain->dom_family != PF_ROUTE) {
199 		return (EPROTONOSUPPORT);
200 	}
201 
202 	if (prp->pr_type != type)
203 		return (EPROTOTYPE);
204 	so = soalloc(M_WAITOK);
205 	if (so == NULL)
206 		return (ENOBUFS);
207 
208 	TAILQ_INIT(&so->so_incomp);
209 	TAILQ_INIT(&so->so_comp);
210 	so->so_type = type;
211 	so->so_cred = crhold(cred);
212 	so->so_proto = prp;
213 #ifdef MAC
214 	mac_create_socket(cred, so);
215 #endif
216 	SOCK_LOCK(so);
217 	knlist_init(&so->so_rcv.sb_sel.si_note, SOCKBUF_MTX(&so->so_rcv));
218 	knlist_init(&so->so_snd.sb_sel.si_note, SOCKBUF_MTX(&so->so_snd));
219 	soref(so);
220 	SOCK_UNLOCK(so);
221 	error = (*prp->pr_usrreqs->pru_attach)(so, proto, td);
222 	if (error) {
223 		ACCEPT_LOCK();
224 		SOCK_LOCK(so);
225 		so->so_state |= SS_NOFDREF;
226 		sorele(so);
227 		return (error);
228 	}
229 	*aso = so;
230 	return (0);
231 }
232 
233 int
234 sobind(so, nam, td)
235 	struct socket *so;
236 	struct sockaddr *nam;
237 	struct thread *td;
238 {
239 
240 	return ((*so->so_proto->pr_usrreqs->pru_bind)(so, nam, td));
241 }
242 
243 void
244 sodealloc(struct socket *so)
245 {
246 
247 	KASSERT(so->so_count == 0, ("sodealloc(): so_count %d", so->so_count));
248 	mtx_lock(&so_global_mtx);
249 	so->so_gencnt = ++so_gencnt;
250 	mtx_unlock(&so_global_mtx);
251 	if (so->so_rcv.sb_hiwat)
252 		(void)chgsbsize(so->so_cred->cr_uidinfo,
253 		    &so->so_rcv.sb_hiwat, 0, RLIM_INFINITY);
254 	if (so->so_snd.sb_hiwat)
255 		(void)chgsbsize(so->so_cred->cr_uidinfo,
256 		    &so->so_snd.sb_hiwat, 0, RLIM_INFINITY);
257 #ifdef INET
258 	/* remove acccept filter if one is present. */
259 	if (so->so_accf != NULL)
260 		do_setopt_accept_filter(so, NULL);
261 #endif
262 #ifdef MAC
263 	mac_destroy_socket(so);
264 #endif
265 	crfree(so->so_cred);
266 	SOCKBUF_LOCK_DESTROY(&so->so_snd);
267 	SOCKBUF_LOCK_DESTROY(&so->so_rcv);
268 	/* sx_destroy(&so->so_sxlock); */
269 	uma_zfree(socket_zone, so);
270 	mtx_lock(&so_global_mtx);
271 	--numopensockets;
272 	mtx_unlock(&so_global_mtx);
273 }
274 
275 int
276 solisten(so, backlog, td)
277 	struct socket *so;
278 	int backlog;
279 	struct thread *td;
280 {
281 	int error;
282 
283 	/*
284 	 * XXXRW: Ordering issue here -- perhaps we need to set
285 	 * SO_ACCEPTCONN before the call to pru_listen()?
286 	 * XXXRW: General atomic test-and-set concerns here also.
287 	 */
288 	if (so->so_state & (SS_ISCONNECTED | SS_ISCONNECTING |
289 			    SS_ISDISCONNECTING))
290 		return (EINVAL);
291 	error = (*so->so_proto->pr_usrreqs->pru_listen)(so, td);
292 	if (error)
293 		return (error);
294 	ACCEPT_LOCK();
295 	if (TAILQ_EMPTY(&so->so_comp)) {
296 		SOCK_LOCK(so);
297 		so->so_options |= SO_ACCEPTCONN;
298 		SOCK_UNLOCK(so);
299 	}
300 	if (backlog < 0 || backlog > somaxconn)
301 		backlog = somaxconn;
302 	so->so_qlimit = backlog;
303 	ACCEPT_UNLOCK();
304 	return (0);
305 }
306 
307 /*
308  * Attempt to free a socket.  This should really be sotryfree().
309  *
310  * We free the socket if the protocol is no longer interested in the socket,
311  * there's no file descriptor reference, and the refcount is 0.  While the
312  * calling macro sotryfree() tests the refcount, sofree() has to test it
313  * again as it's possible to race with an accept()ing thread if the socket is
314  * in an listen queue of a listen socket, as being in the listen queue
315  * doesn't elevate the reference count.  sofree() acquires the accept mutex
316  * early for this test in order to avoid that race.
317  */
318 void
319 sofree(so)
320 	struct socket *so;
321 {
322 	struct socket *head;
323 
324 	ACCEPT_LOCK_ASSERT();
325 	SOCK_LOCK_ASSERT(so);
326 
327 	if (so->so_pcb != NULL || (so->so_state & SS_NOFDREF) == 0 ||
328 	    so->so_count != 0) {
329 		SOCK_UNLOCK(so);
330 		ACCEPT_UNLOCK();
331 		return;
332 	}
333 
334 	head = so->so_head;
335 	if (head != NULL) {
336 		KASSERT((so->so_qstate & SQ_COMP) != 0 ||
337 		    (so->so_qstate & SQ_INCOMP) != 0,
338 		    ("sofree: so_head != NULL, but neither SQ_COMP nor "
339 		    "SQ_INCOMP"));
340 		KASSERT((so->so_qstate & SQ_COMP) == 0 ||
341 		    (so->so_qstate & SQ_INCOMP) == 0,
342 		    ("sofree: so->so_qstate is SQ_COMP and also SQ_INCOMP"));
343 		/*
344 		 * accept(2) is responsible draining the completed
345 		 * connection queue and freeing those sockets, so
346 		 * we just return here if this socket is currently
347 		 * on the completed connection queue.  Otherwise,
348 		 * accept(2) may hang after select(2) has indicating
349 		 * that a listening socket was ready.  If it's an
350 		 * incomplete connection, we remove it from the queue
351 		 * and free it; otherwise, it won't be released until
352 		 * the listening socket is closed.
353 		 */
354 		if ((so->so_qstate & SQ_COMP) != 0) {
355 			SOCK_UNLOCK(so);
356 			ACCEPT_UNLOCK();
357 			return;
358 		}
359 		TAILQ_REMOVE(&head->so_incomp, so, so_list);
360 		head->so_incqlen--;
361 		so->so_qstate &= ~SQ_INCOMP;
362 		so->so_head = NULL;
363 	}
364 	KASSERT((so->so_qstate & SQ_COMP) == 0 &&
365 	    (so->so_qstate & SQ_INCOMP) == 0,
366 	    ("sofree: so_head == NULL, but still SQ_COMP(%d) or SQ_INCOMP(%d)",
367 	    so->so_qstate & SQ_COMP, so->so_qstate & SQ_INCOMP));
368 	SOCK_UNLOCK(so);
369 	ACCEPT_UNLOCK();
370 	SOCKBUF_LOCK(&so->so_snd);
371 	so->so_snd.sb_flags |= SB_NOINTR;
372 	(void)sblock(&so->so_snd, M_WAITOK);
373 	/*
374 	 * socantsendmore_locked() drops the socket buffer mutex so that it
375 	 * can safely perform wakeups.  Re-acquire the mutex before
376 	 * continuing.
377 	 */
378 	socantsendmore_locked(so);
379 	SOCKBUF_LOCK(&so->so_snd);
380 	sbunlock(&so->so_snd);
381 	sbrelease_locked(&so->so_snd, so);
382 	SOCKBUF_UNLOCK(&so->so_snd);
383 	sorflush(so);
384 	knlist_destroy(&so->so_rcv.sb_sel.si_note);
385 	knlist_destroy(&so->so_snd.sb_sel.si_note);
386 	sodealloc(so);
387 }
388 
389 /*
390  * Close a socket on last file table reference removal.
391  * Initiate disconnect if connected.
392  * Free socket when disconnect complete.
393  *
394  * This function will sorele() the socket.  Note that soclose() may be
395  * called prior to the ref count reaching zero.  The actual socket
396  * structure will not be freed until the ref count reaches zero.
397  */
398 int
399 soclose(so)
400 	struct socket *so;
401 {
402 	int error = 0;
403 
404 	KASSERT(!(so->so_state & SS_NOFDREF), ("soclose: SS_NOFDREF on enter"));
405 
406 	funsetown(&so->so_sigio);
407 	if (so->so_options & SO_ACCEPTCONN) {
408 		struct socket *sp;
409 		ACCEPT_LOCK();
410 		while ((sp = TAILQ_FIRST(&so->so_incomp)) != NULL) {
411 			TAILQ_REMOVE(&so->so_incomp, sp, so_list);
412 			so->so_incqlen--;
413 			sp->so_qstate &= ~SQ_INCOMP;
414 			sp->so_head = NULL;
415 			ACCEPT_UNLOCK();
416 			(void) soabort(sp);
417 			ACCEPT_LOCK();
418 		}
419 		while ((sp = TAILQ_FIRST(&so->so_comp)) != NULL) {
420 			TAILQ_REMOVE(&so->so_comp, sp, so_list);
421 			so->so_qlen--;
422 			sp->so_qstate &= ~SQ_COMP;
423 			sp->so_head = NULL;
424 			ACCEPT_UNLOCK();
425 			(void) soabort(sp);
426 			ACCEPT_LOCK();
427 		}
428 		ACCEPT_UNLOCK();
429 	}
430 	if (so->so_pcb == NULL)
431 		goto discard;
432 	if (so->so_state & SS_ISCONNECTED) {
433 		if ((so->so_state & SS_ISDISCONNECTING) == 0) {
434 			error = sodisconnect(so);
435 			if (error)
436 				goto drop;
437 		}
438 		if (so->so_options & SO_LINGER) {
439 			if ((so->so_state & SS_ISDISCONNECTING) &&
440 			    (so->so_state & SS_NBIO))
441 				goto drop;
442 			while (so->so_state & SS_ISCONNECTED) {
443 				error = tsleep(&so->so_timeo,
444 				    PSOCK | PCATCH, "soclos", so->so_linger * hz);
445 				if (error)
446 					break;
447 			}
448 		}
449 	}
450 drop:
451 	if (so->so_pcb != NULL) {
452 		int error2 = (*so->so_proto->pr_usrreqs->pru_detach)(so);
453 		if (error == 0)
454 			error = error2;
455 	}
456 discard:
457 	ACCEPT_LOCK();
458 	SOCK_LOCK(so);
459 	KASSERT((so->so_state & SS_NOFDREF) == 0, ("soclose: NOFDREF"));
460 	so->so_state |= SS_NOFDREF;
461 	sorele(so);
462 	return (error);
463 }
464 
465 /*
466  * soabort() must not be called with any socket locks held, as it calls
467  * into the protocol, which will call back into the socket code causing
468  * it to acquire additional socket locks that may cause recursion or lock
469  * order reversals.
470  */
471 int
472 soabort(so)
473 	struct socket *so;
474 {
475 	int error;
476 
477 	error = (*so->so_proto->pr_usrreqs->pru_abort)(so);
478 	if (error) {
479 		ACCEPT_LOCK();
480 		SOCK_LOCK(so);
481 		sotryfree(so);	/* note: does not decrement the ref count */
482 		return error;
483 	}
484 	return (0);
485 }
486 
487 int
488 soaccept(so, nam)
489 	struct socket *so;
490 	struct sockaddr **nam;
491 {
492 	int error;
493 
494 	SOCK_LOCK(so);
495 	KASSERT((so->so_state & SS_NOFDREF) != 0, ("soaccept: !NOFDREF"));
496 	so->so_state &= ~SS_NOFDREF;
497 	SOCK_UNLOCK(so);
498 	error = (*so->so_proto->pr_usrreqs->pru_accept)(so, nam);
499 	return (error);
500 }
501 
502 int
503 soconnect(so, nam, td)
504 	struct socket *so;
505 	struct sockaddr *nam;
506 	struct thread *td;
507 {
508 	int error;
509 
510 	if (so->so_options & SO_ACCEPTCONN)
511 		return (EOPNOTSUPP);
512 	/*
513 	 * If protocol is connection-based, can only connect once.
514 	 * Otherwise, if connected, try to disconnect first.
515 	 * This allows user to disconnect by connecting to, e.g.,
516 	 * a null address.
517 	 */
518 	if (so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING) &&
519 	    ((so->so_proto->pr_flags & PR_CONNREQUIRED) ||
520 	    (error = sodisconnect(so))))
521 		error = EISCONN;
522 	else
523 		error = (*so->so_proto->pr_usrreqs->pru_connect)(so, nam, td);
524 	return (error);
525 }
526 
527 int
528 soconnect2(so1, so2)
529 	struct socket *so1;
530 	struct socket *so2;
531 {
532 
533 	return ((*so1->so_proto->pr_usrreqs->pru_connect2)(so1, so2));
534 }
535 
536 int
537 sodisconnect(so)
538 	struct socket *so;
539 {
540 	int error;
541 
542 	if ((so->so_state & SS_ISCONNECTED) == 0)
543 		return (ENOTCONN);
544 	if (so->so_state & SS_ISDISCONNECTING)
545 		return (EALREADY);
546 	error = (*so->so_proto->pr_usrreqs->pru_disconnect)(so);
547 	return (error);
548 }
549 
550 #define	SBLOCKWAIT(f)	(((f) & MSG_DONTWAIT) ? M_NOWAIT : M_WAITOK)
551 /*
552  * Send on a socket.
553  * If send must go all at once and message is larger than
554  * send buffering, then hard error.
555  * Lock against other senders.
556  * If must go all at once and not enough room now, then
557  * inform user that this would block and do nothing.
558  * Otherwise, if nonblocking, send as much as possible.
559  * The data to be sent is described by "uio" if nonzero,
560  * otherwise by the mbuf chain "top" (which must be null
561  * if uio is not).  Data provided in mbuf chain must be small
562  * enough to send all at once.
563  *
564  * Returns nonzero on error, timeout or signal; callers
565  * must check for short counts if EINTR/ERESTART are returned.
566  * Data and control buffers are freed on return.
567  */
568 
569 #ifdef ZERO_COPY_SOCKETS
570 struct so_zerocopy_stats{
571 	int size_ok;
572 	int align_ok;
573 	int found_ifp;
574 };
575 struct so_zerocopy_stats so_zerocp_stats = {0,0,0};
576 #include <netinet/in.h>
577 #include <net/route.h>
578 #include <netinet/in_pcb.h>
579 #include <vm/vm.h>
580 #include <vm/vm_page.h>
581 #include <vm/vm_object.h>
582 #endif /*ZERO_COPY_SOCKETS*/
583 
584 int
585 sosend(so, addr, uio, top, control, flags, td)
586 	struct socket *so;
587 	struct sockaddr *addr;
588 	struct uio *uio;
589 	struct mbuf *top;
590 	struct mbuf *control;
591 	int flags;
592 	struct thread *td;
593 {
594 	struct mbuf **mp;
595 	struct mbuf *m;
596 	long space, len = 0, resid;
597 	int clen = 0, error, dontroute;
598 	int atomic = sosendallatonce(so) || top;
599 #ifdef ZERO_COPY_SOCKETS
600 	int cow_send;
601 #endif /* ZERO_COPY_SOCKETS */
602 
603 	if (uio != NULL)
604 		resid = uio->uio_resid;
605 	else
606 		resid = top->m_pkthdr.len;
607 	/*
608 	 * In theory resid should be unsigned.
609 	 * However, space must be signed, as it might be less than 0
610 	 * if we over-committed, and we must use a signed comparison
611 	 * of space and resid.  On the other hand, a negative resid
612 	 * causes us to loop sending 0-length segments to the protocol.
613 	 *
614 	 * Also check to make sure that MSG_EOR isn't used on SOCK_STREAM
615 	 * type sockets since that's an error.
616 	 */
617 	if (resid < 0 || (so->so_type == SOCK_STREAM && (flags & MSG_EOR))) {
618 		error = EINVAL;
619 		goto out;
620 	}
621 
622 	dontroute =
623 	    (flags & MSG_DONTROUTE) && (so->so_options & SO_DONTROUTE) == 0 &&
624 	    (so->so_proto->pr_flags & PR_ATOMIC);
625 	if (td != NULL)
626 		td->td_proc->p_stats->p_ru.ru_msgsnd++;
627 	if (control != NULL)
628 		clen = control->m_len;
629 #define	snderr(errno)	{ error = (errno); goto release; }
630 
631 	SOCKBUF_LOCK(&so->so_snd);
632 restart:
633 	SOCKBUF_LOCK_ASSERT(&so->so_snd);
634 	error = sblock(&so->so_snd, SBLOCKWAIT(flags));
635 	if (error)
636 		goto out_locked;
637 	do {
638 		SOCKBUF_LOCK_ASSERT(&so->so_snd);
639 		if (so->so_snd.sb_state & SBS_CANTSENDMORE)
640 			snderr(EPIPE);
641 		if (so->so_error) {
642 			error = so->so_error;
643 			so->so_error = 0;
644 			goto release;
645 		}
646 		if ((so->so_state & SS_ISCONNECTED) == 0) {
647 			/*
648 			 * `sendto' and `sendmsg' is allowed on a connection-
649 			 * based socket if it supports implied connect.
650 			 * Return ENOTCONN if not connected and no address is
651 			 * supplied.
652 			 */
653 			if ((so->so_proto->pr_flags & PR_CONNREQUIRED) &&
654 			    (so->so_proto->pr_flags & PR_IMPLOPCL) == 0) {
655 				if ((so->so_state & SS_ISCONFIRMING) == 0 &&
656 				    !(resid == 0 && clen != 0))
657 					snderr(ENOTCONN);
658 			} else if (addr == NULL)
659 			    snderr(so->so_proto->pr_flags & PR_CONNREQUIRED ?
660 				   ENOTCONN : EDESTADDRREQ);
661 		}
662 		space = sbspace(&so->so_snd);
663 		if (flags & MSG_OOB)
664 			space += 1024;
665 		if ((atomic && resid > so->so_snd.sb_hiwat) ||
666 		    clen > so->so_snd.sb_hiwat)
667 			snderr(EMSGSIZE);
668 		if (space < resid + clen &&
669 		    (atomic || space < so->so_snd.sb_lowat || space < clen)) {
670 			if ((so->so_state & SS_NBIO) || (flags & MSG_NBIO))
671 				snderr(EWOULDBLOCK);
672 			sbunlock(&so->so_snd);
673 			error = sbwait(&so->so_snd);
674 			if (error)
675 				goto out_locked;
676 			goto restart;
677 		}
678 		SOCKBUF_UNLOCK(&so->so_snd);
679 		mp = &top;
680 		space -= clen;
681 		do {
682 		    if (uio == NULL) {
683 			/*
684 			 * Data is prepackaged in "top".
685 			 */
686 			resid = 0;
687 			if (flags & MSG_EOR)
688 				top->m_flags |= M_EOR;
689 		    } else do {
690 #ifdef ZERO_COPY_SOCKETS
691 			cow_send = 0;
692 #endif /* ZERO_COPY_SOCKETS */
693 			if (resid >= MINCLSIZE) {
694 #ifdef ZERO_COPY_SOCKETS
695 				if (top == NULL) {
696 					MGETHDR(m, M_TRYWAIT, MT_DATA);
697 					if (m == NULL) {
698 						error = ENOBUFS;
699 						SOCKBUF_LOCK(&so->so_snd);
700 						goto release;
701 					}
702 					m->m_pkthdr.len = 0;
703 					m->m_pkthdr.rcvif = (struct ifnet *)0;
704 				} else {
705 					MGET(m, M_TRYWAIT, MT_DATA);
706 					if (m == NULL) {
707 						error = ENOBUFS;
708 						SOCKBUF_LOCK(&so->so_snd);
709 						goto release;
710 					}
711 				}
712 				if (so_zero_copy_send &&
713 				    resid>=PAGE_SIZE &&
714 				    space>=PAGE_SIZE &&
715 				    uio->uio_iov->iov_len>=PAGE_SIZE) {
716 					so_zerocp_stats.size_ok++;
717 					if (!((vm_offset_t)
718 					  uio->uio_iov->iov_base & PAGE_MASK)){
719 						so_zerocp_stats.align_ok++;
720 						cow_send = socow_setup(m, uio);
721 					}
722 				}
723 				if (!cow_send) {
724 					MCLGET(m, M_TRYWAIT);
725 					if ((m->m_flags & M_EXT) == 0) {
726 						m_free(m);
727 						m = NULL;
728 					} else {
729 						len = min(min(MCLBYTES, resid), space);
730 					}
731 				} else
732 					len = PAGE_SIZE;
733 #else /* ZERO_COPY_SOCKETS */
734 				if (top == NULL) {
735 					m = m_getcl(M_TRYWAIT, MT_DATA, M_PKTHDR);
736 					m->m_pkthdr.len = 0;
737 					m->m_pkthdr.rcvif = (struct ifnet *)0;
738 				} else
739 					m = m_getcl(M_TRYWAIT, MT_DATA, 0);
740 				len = min(min(MCLBYTES, resid), space);
741 #endif /* ZERO_COPY_SOCKETS */
742 			} else {
743 				if (top == NULL) {
744 					m = m_gethdr(M_TRYWAIT, MT_DATA);
745 					m->m_pkthdr.len = 0;
746 					m->m_pkthdr.rcvif = (struct ifnet *)0;
747 
748 					len = min(min(MHLEN, resid), space);
749 					/*
750 					 * For datagram protocols, leave room
751 					 * for protocol headers in first mbuf.
752 					 */
753 					if (atomic && m && len < MHLEN)
754 						MH_ALIGN(m, len);
755 				} else {
756 					m = m_get(M_TRYWAIT, MT_DATA);
757 					len = min(min(MLEN, resid), space);
758 				}
759 			}
760 			if (m == NULL) {
761 				error = ENOBUFS;
762 				SOCKBUF_LOCK(&so->so_snd);
763 				goto release;
764 			}
765 
766 			space -= len;
767 #ifdef ZERO_COPY_SOCKETS
768 			if (cow_send)
769 				error = 0;
770 			else
771 #endif /* ZERO_COPY_SOCKETS */
772 			error = uiomove(mtod(m, void *), (int)len, uio);
773 			resid = uio->uio_resid;
774 			m->m_len = len;
775 			*mp = m;
776 			top->m_pkthdr.len += len;
777 			if (error) {
778 				SOCKBUF_LOCK(&so->so_snd);
779 				goto release;
780 			}
781 			mp = &m->m_next;
782 			if (resid <= 0) {
783 				if (flags & MSG_EOR)
784 					top->m_flags |= M_EOR;
785 				break;
786 			}
787 		    } while (space > 0 && atomic);
788 		    if (dontroute) {
789 			    SOCK_LOCK(so);
790 			    so->so_options |= SO_DONTROUTE;
791 			    SOCK_UNLOCK(so);
792 		    }
793 		    /*
794 		     * XXX all the SBS_CANTSENDMORE checks previously
795 		     * done could be out of date.  We could have recieved
796 		     * a reset packet in an interrupt or maybe we slept
797 		     * while doing page faults in uiomove() etc. We could
798 		     * probably recheck again inside the locking protection
799 		     * here, but there are probably other places that this
800 		     * also happens.  We must rethink this.
801 		     */
802 		    error = (*so->so_proto->pr_usrreqs->pru_send)(so,
803 			(flags & MSG_OOB) ? PRUS_OOB :
804 			/*
805 			 * If the user set MSG_EOF, the protocol
806 			 * understands this flag and nothing left to
807 			 * send then use PRU_SEND_EOF instead of PRU_SEND.
808 			 */
809 			((flags & MSG_EOF) &&
810 			 (so->so_proto->pr_flags & PR_IMPLOPCL) &&
811 			 (resid <= 0)) ?
812 				PRUS_EOF :
813 			/* If there is more to send set PRUS_MORETOCOME */
814 			(resid > 0 && space > 0) ? PRUS_MORETOCOME : 0,
815 			top, addr, control, td);
816 		    if (dontroute) {
817 			    SOCK_LOCK(so);
818 			    so->so_options &= ~SO_DONTROUTE;
819 			    SOCK_UNLOCK(so);
820 		    }
821 		    clen = 0;
822 		    control = NULL;
823 		    top = NULL;
824 		    mp = &top;
825 		    if (error) {
826 			SOCKBUF_LOCK(&so->so_snd);
827 			goto release;
828 		    }
829 		} while (resid && space > 0);
830 		SOCKBUF_LOCK(&so->so_snd);
831 	} while (resid);
832 
833 release:
834 	SOCKBUF_LOCK_ASSERT(&so->so_snd);
835 	sbunlock(&so->so_snd);
836 out_locked:
837 	SOCKBUF_LOCK_ASSERT(&so->so_snd);
838 	SOCKBUF_UNLOCK(&so->so_snd);
839 out:
840 	if (top != NULL)
841 		m_freem(top);
842 	if (control != NULL)
843 		m_freem(control);
844 	return (error);
845 }
846 
847 /*
848  * The part of soreceive() that implements reading non-inline out-of-band
849  * data from a socket.  For more complete comments, see soreceive(), from
850  * which this code originated.
851  *
852  * Note that soreceive_rcvoob(), unlike the remainder of soreiceve(), is
853  * unable to return an mbuf chain to the caller.
854  */
855 static int
856 soreceive_rcvoob(so, uio, flags)
857 	struct socket *so;
858 	struct uio *uio;
859 	int flags;
860 {
861 	struct protosw *pr = so->so_proto;
862 	struct mbuf *m;
863 	int error;
864 
865 	KASSERT(flags & MSG_OOB, ("soreceive_rcvoob: (flags & MSG_OOB) == 0"));
866 
867 	m = m_get(M_TRYWAIT, MT_DATA);
868 	if (m == NULL)
869 		return (ENOBUFS);
870 	error = (*pr->pr_usrreqs->pru_rcvoob)(so, m, flags & MSG_PEEK);
871 	if (error)
872 		goto bad;
873 	do {
874 #ifdef ZERO_COPY_SOCKETS
875 		if (so_zero_copy_receive) {
876 			int disposable;
877 
878 			if ((m->m_flags & M_EXT)
879 			 && (m->m_ext.ext_type == EXT_DISPOSABLE))
880 				disposable = 1;
881 			else
882 				disposable = 0;
883 
884 			error = uiomoveco(mtod(m, void *),
885 					  min(uio->uio_resid, m->m_len),
886 					  uio, disposable);
887 		} else
888 #endif /* ZERO_COPY_SOCKETS */
889 		error = uiomove(mtod(m, void *),
890 		    (int) min(uio->uio_resid, m->m_len), uio);
891 		m = m_free(m);
892 	} while (uio->uio_resid && error == 0 && m);
893 bad:
894 	if (m != NULL)
895 		m_freem(m);
896 	return (error);
897 }
898 
899 /*
900  * Following replacement or removal of the first mbuf on the first mbuf chain
901  * of a socket buffer, push necessary state changes back into the socket
902  * buffer so that other consumers see the values consistently.  'nextrecord'
903  * is the callers locally stored value of the original value of
904  * sb->sb_mb->m_nextpkt which must be restored when the lead mbuf changes.
905  * NOTE: 'nextrecord' may be NULL.
906  */
907 static __inline void
908 sockbuf_pushsync(struct sockbuf *sb, struct mbuf *nextrecord)
909 {
910 
911 	SOCKBUF_LOCK_ASSERT(sb);
912 	/*
913 	 * First, update for the new value of nextrecord.  If necessary, make
914 	 * it the first record.
915 	 */
916 	if (sb->sb_mb != NULL)
917 		sb->sb_mb->m_nextpkt = nextrecord;
918 	else
919 		sb->sb_mb = nextrecord;
920 
921         /*
922          * Now update any dependent socket buffer fields to reflect the new
923          * state.  This is an expanded inline of SB_EMPTY_FIXUP(), with the
924 	 * addition of a second clause that takes care of the case where
925 	 * sb_mb has been updated, but remains the last record.
926          */
927         if (sb->sb_mb == NULL) {
928                 sb->sb_mbtail = NULL;
929                 sb->sb_lastrecord = NULL;
930         } else if (sb->sb_mb->m_nextpkt == NULL)
931                 sb->sb_lastrecord = sb->sb_mb;
932 }
933 
934 
935 /*
936  * Implement receive operations on a socket.
937  * We depend on the way that records are added to the sockbuf
938  * by sbappend*.  In particular, each record (mbufs linked through m_next)
939  * must begin with an address if the protocol so specifies,
940  * followed by an optional mbuf or mbufs containing ancillary data,
941  * and then zero or more mbufs of data.
942  * In order to avoid blocking network interrupts for the entire time here,
943  * we splx() while doing the actual copy to user space.
944  * Although the sockbuf is locked, new data may still be appended,
945  * and thus we must maintain consistency of the sockbuf during that time.
946  *
947  * The caller may receive the data as a single mbuf chain by supplying
948  * an mbuf **mp0 for use in returning the chain.  The uio is then used
949  * only for the count in uio_resid.
950  */
951 int
952 soreceive(so, psa, uio, mp0, controlp, flagsp)
953 	struct socket *so;
954 	struct sockaddr **psa;
955 	struct uio *uio;
956 	struct mbuf **mp0;
957 	struct mbuf **controlp;
958 	int *flagsp;
959 {
960 	struct mbuf *m, **mp;
961 	int flags, len, error, offset;
962 	struct protosw *pr = so->so_proto;
963 	struct mbuf *nextrecord;
964 	int moff, type = 0;
965 	int orig_resid = uio->uio_resid;
966 
967 	mp = mp0;
968 	if (psa != NULL)
969 		*psa = NULL;
970 	if (controlp != NULL)
971 		*controlp = NULL;
972 	if (flagsp != NULL)
973 		flags = *flagsp &~ MSG_EOR;
974 	else
975 		flags = 0;
976 	if (flags & MSG_OOB)
977 		return (soreceive_rcvoob(so, uio, flags));
978 	if (mp != NULL)
979 		*mp = NULL;
980 	if (so->so_state & SS_ISCONFIRMING && uio->uio_resid)
981 		(*pr->pr_usrreqs->pru_rcvd)(so, 0);
982 
983 	SOCKBUF_LOCK(&so->so_rcv);
984 restart:
985 	SOCKBUF_LOCK_ASSERT(&so->so_rcv);
986 	error = sblock(&so->so_rcv, SBLOCKWAIT(flags));
987 	if (error)
988 		goto out;
989 
990 	m = so->so_rcv.sb_mb;
991 	/*
992 	 * If we have less data than requested, block awaiting more
993 	 * (subject to any timeout) if:
994 	 *   1. the current count is less than the low water mark, or
995 	 *   2. MSG_WAITALL is set, and it is possible to do the entire
996 	 *	receive operation at once if we block (resid <= hiwat).
997 	 *   3. MSG_DONTWAIT is not set
998 	 * If MSG_WAITALL is set but resid is larger than the receive buffer,
999 	 * we have to do the receive in sections, and thus risk returning
1000 	 * a short count if a timeout or signal occurs after we start.
1001 	 */
1002 	if (m == NULL || (((flags & MSG_DONTWAIT) == 0 &&
1003 	    so->so_rcv.sb_cc < uio->uio_resid) &&
1004 	    (so->so_rcv.sb_cc < so->so_rcv.sb_lowat ||
1005 	    ((flags & MSG_WAITALL) && uio->uio_resid <= so->so_rcv.sb_hiwat)) &&
1006 	    m->m_nextpkt == NULL && (pr->pr_flags & PR_ATOMIC) == 0)) {
1007 		KASSERT(m != NULL || !so->so_rcv.sb_cc,
1008 		    ("receive: m == %p so->so_rcv.sb_cc == %u",
1009 		    m, so->so_rcv.sb_cc));
1010 		if (so->so_error) {
1011 			if (m != NULL)
1012 				goto dontblock;
1013 			error = so->so_error;
1014 			if ((flags & MSG_PEEK) == 0)
1015 				so->so_error = 0;
1016 			goto release;
1017 		}
1018 		SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1019 		if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
1020 			if (m)
1021 				goto dontblock;
1022 			else
1023 				goto release;
1024 		}
1025 		for (; m != NULL; m = m->m_next)
1026 			if (m->m_type == MT_OOBDATA  || (m->m_flags & M_EOR)) {
1027 				m = so->so_rcv.sb_mb;
1028 				goto dontblock;
1029 			}
1030 		if ((so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING)) == 0 &&
1031 		    (so->so_proto->pr_flags & PR_CONNREQUIRED)) {
1032 			error = ENOTCONN;
1033 			goto release;
1034 		}
1035 		if (uio->uio_resid == 0)
1036 			goto release;
1037 		if ((so->so_state & SS_NBIO) ||
1038 		    (flags & (MSG_DONTWAIT|MSG_NBIO))) {
1039 			error = EWOULDBLOCK;
1040 			goto release;
1041 		}
1042 		SBLASTRECORDCHK(&so->so_rcv);
1043 		SBLASTMBUFCHK(&so->so_rcv);
1044 		sbunlock(&so->so_rcv);
1045 		error = sbwait(&so->so_rcv);
1046 		if (error)
1047 			goto out;
1048 		goto restart;
1049 	}
1050 dontblock:
1051 	/*
1052 	 * From this point onward, we maintain 'nextrecord' as a cache of the
1053 	 * pointer to the next record in the socket buffer.  We must keep the
1054 	 * various socket buffer pointers and local stack versions of the
1055 	 * pointers in sync, pushing out modifications before dropping the
1056 	 * socket buffer mutex, and re-reading them when picking it up.
1057 	 *
1058 	 * Otherwise, we will race with the network stack appending new data
1059 	 * or records onto the socket buffer by using inconsistent/stale
1060 	 * versions of the field, possibly resulting in socket buffer
1061 	 * corruption.
1062 	 *
1063 	 * By holding the high-level sblock(), we prevent simultaneous
1064 	 * readers from pulling off the front of the socket buffer.
1065 	 */
1066 	SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1067 	if (uio->uio_td)
1068 		uio->uio_td->td_proc->p_stats->p_ru.ru_msgrcv++;
1069 	KASSERT(m == so->so_rcv.sb_mb, ("soreceive: m != so->so_rcv.sb_mb"));
1070 	SBLASTRECORDCHK(&so->so_rcv);
1071 	SBLASTMBUFCHK(&so->so_rcv);
1072 	nextrecord = m->m_nextpkt;
1073 	if (pr->pr_flags & PR_ADDR) {
1074 		KASSERT(m->m_type == MT_SONAME,
1075 		    ("m->m_type == %d", m->m_type));
1076 		orig_resid = 0;
1077 		if (psa != NULL)
1078 			*psa = sodupsockaddr(mtod(m, struct sockaddr *),
1079 			    M_NOWAIT);
1080 		if (flags & MSG_PEEK) {
1081 			m = m->m_next;
1082 		} else {
1083 			sbfree(&so->so_rcv, m);
1084 			so->so_rcv.sb_mb = m_free(m);
1085 			m = so->so_rcv.sb_mb;
1086 			sockbuf_pushsync(&so->so_rcv, nextrecord);
1087 		}
1088 	}
1089 
1090 	/*
1091 	 * Process one or more MT_CONTROL mbufs present before any data mbufs
1092 	 * in the first mbuf chain on the socket buffer.  If MSG_PEEK, we
1093 	 * just copy the data; if !MSG_PEEK, we call into the protocol to
1094 	 * perform externalization (or freeing if controlp == NULL).
1095 	 */
1096 	if (m != NULL && m->m_type == MT_CONTROL) {
1097 		struct mbuf *cm = NULL, *cmn;
1098 		struct mbuf **cme = &cm;
1099 
1100 		do {
1101 			if (flags & MSG_PEEK) {
1102 				if (controlp != NULL) {
1103 					*controlp = m_copy(m, 0, m->m_len);
1104 					controlp = &(*controlp)->m_next;
1105 				}
1106 				m = m->m_next;
1107 			} else {
1108 				sbfree(&so->so_rcv, m);
1109 				so->so_rcv.sb_mb = m->m_next;
1110 				m->m_next = NULL;
1111 				*cme = m;
1112 				cme = &(*cme)->m_next;
1113 				m = so->so_rcv.sb_mb;
1114 			}
1115 		} while (m != NULL && m->m_type == MT_CONTROL);
1116 		if ((flags & MSG_PEEK) == 0)
1117 			sockbuf_pushsync(&so->so_rcv, nextrecord);
1118 		while (cm != NULL) {
1119 			cmn = cm->m_next;
1120 			cm->m_next = NULL;
1121 			if (pr->pr_domain->dom_externalize != NULL) {
1122 				SOCKBUF_UNLOCK(&so->so_rcv);
1123 				error = (*pr->pr_domain->dom_externalize)
1124 				    (cm, controlp);
1125 				SOCKBUF_LOCK(&so->so_rcv);
1126 			} else if (controlp != NULL)
1127 				*controlp = cm;
1128 			else
1129 				m_freem(cm);
1130 			if (controlp != NULL) {
1131 				orig_resid = 0;
1132 				while (*controlp != NULL)
1133 					controlp = &(*controlp)->m_next;
1134 			}
1135 			cm = cmn;
1136 		}
1137 		nextrecord = so->so_rcv.sb_mb->m_nextpkt;
1138 		orig_resid = 0;
1139 	}
1140 	if (m != NULL) {
1141 		if ((flags & MSG_PEEK) == 0) {
1142 			KASSERT(m->m_nextpkt == nextrecord,
1143 			    ("soreceive: post-control, nextrecord !sync"));
1144 			if (nextrecord == NULL) {
1145 				KASSERT(so->so_rcv.sb_mb == m,
1146 				    ("soreceive: post-control, sb_mb!=m"));
1147 				KASSERT(so->so_rcv.sb_lastrecord == m,
1148 				    ("soreceive: post-control, lastrecord!=m"));
1149 			}
1150 		}
1151 		type = m->m_type;
1152 		if (type == MT_OOBDATA)
1153 			flags |= MSG_OOB;
1154 	} else {
1155 		if ((flags & MSG_PEEK) == 0) {
1156 			KASSERT(so->so_rcv.sb_mb == nextrecord,
1157 			    ("soreceive: sb_mb != nextrecord"));
1158 			if (so->so_rcv.sb_mb == NULL) {
1159 				KASSERT(so->so_rcv.sb_lastrecord == NULL,
1160 				    ("soreceive: sb_lastercord != NULL"));
1161 			}
1162 		}
1163 	}
1164 	SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1165 	SBLASTRECORDCHK(&so->so_rcv);
1166 	SBLASTMBUFCHK(&so->so_rcv);
1167 
1168 	/*
1169 	 * Now continue to read any data mbufs off of the head of the socket
1170 	 * buffer until the read request is satisfied.  Note that 'type' is
1171 	 * used to store the type of any mbuf reads that have happened so far
1172 	 * such that soreceive() can stop reading if the type changes, which
1173 	 * causes soreceive() to return only one of regular data and inline
1174 	 * out-of-band data in a single socket receive operation.
1175 	 */
1176 	moff = 0;
1177 	offset = 0;
1178 	while (m != NULL && uio->uio_resid > 0 && error == 0) {
1179 		/*
1180 		 * If the type of mbuf has changed since the last mbuf
1181 		 * examined ('type'), end the receive operation.
1182 	 	 */
1183 		SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1184 		if (m->m_type == MT_OOBDATA) {
1185 			if (type != MT_OOBDATA)
1186 				break;
1187 		} else if (type == MT_OOBDATA)
1188 			break;
1189 		else
1190 		    KASSERT(m->m_type == MT_DATA || m->m_type == MT_HEADER,
1191 			("m->m_type == %d", m->m_type));
1192 		so->so_rcv.sb_state &= ~SBS_RCVATMARK;
1193 		len = uio->uio_resid;
1194 		if (so->so_oobmark && len > so->so_oobmark - offset)
1195 			len = so->so_oobmark - offset;
1196 		if (len > m->m_len - moff)
1197 			len = m->m_len - moff;
1198 		/*
1199 		 * If mp is set, just pass back the mbufs.
1200 		 * Otherwise copy them out via the uio, then free.
1201 		 * Sockbuf must be consistent here (points to current mbuf,
1202 		 * it points to next record) when we drop priority;
1203 		 * we must note any additions to the sockbuf when we
1204 		 * block interrupts again.
1205 		 */
1206 		if (mp == NULL) {
1207 			SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1208 			SBLASTRECORDCHK(&so->so_rcv);
1209 			SBLASTMBUFCHK(&so->so_rcv);
1210 			SOCKBUF_UNLOCK(&so->so_rcv);
1211 #ifdef ZERO_COPY_SOCKETS
1212 			if (so_zero_copy_receive) {
1213 				int disposable;
1214 
1215 				if ((m->m_flags & M_EXT)
1216 				 && (m->m_ext.ext_type == EXT_DISPOSABLE))
1217 					disposable = 1;
1218 				else
1219 					disposable = 0;
1220 
1221 				error = uiomoveco(mtod(m, char *) + moff,
1222 						  (int)len, uio,
1223 						  disposable);
1224 			} else
1225 #endif /* ZERO_COPY_SOCKETS */
1226 			error = uiomove(mtod(m, char *) + moff, (int)len, uio);
1227 			SOCKBUF_LOCK(&so->so_rcv);
1228 			if (error)
1229 				goto release;
1230 		} else
1231 			uio->uio_resid -= len;
1232 		SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1233 		if (len == m->m_len - moff) {
1234 			if (m->m_flags & M_EOR)
1235 				flags |= MSG_EOR;
1236 			if (flags & MSG_PEEK) {
1237 				m = m->m_next;
1238 				moff = 0;
1239 			} else {
1240 				nextrecord = m->m_nextpkt;
1241 				sbfree(&so->so_rcv, m);
1242 				if (mp != NULL) {
1243 					*mp = m;
1244 					mp = &m->m_next;
1245 					so->so_rcv.sb_mb = m = m->m_next;
1246 					*mp = NULL;
1247 				} else {
1248 					so->so_rcv.sb_mb = m_free(m);
1249 					m = so->so_rcv.sb_mb;
1250 				}
1251 				if (m != NULL) {
1252 					m->m_nextpkt = nextrecord;
1253 					if (nextrecord == NULL)
1254 						so->so_rcv.sb_lastrecord = m;
1255 				} else {
1256 					so->so_rcv.sb_mb = nextrecord;
1257 					SB_EMPTY_FIXUP(&so->so_rcv);
1258 				}
1259 				SBLASTRECORDCHK(&so->so_rcv);
1260 				SBLASTMBUFCHK(&so->so_rcv);
1261 			}
1262 		} else {
1263 			if (flags & MSG_PEEK)
1264 				moff += len;
1265 			else {
1266 				if (mp != NULL) {
1267 					int copy_flag;
1268 
1269 					if (flags & MSG_DONTWAIT)
1270 						copy_flag = M_DONTWAIT;
1271 					else
1272 						copy_flag = M_TRYWAIT;
1273 					if (copy_flag == M_TRYWAIT)
1274 						SOCKBUF_UNLOCK(&so->so_rcv);
1275 					*mp = m_copym(m, 0, len, copy_flag);
1276 					if (copy_flag == M_TRYWAIT)
1277 						SOCKBUF_LOCK(&so->so_rcv);
1278  					if (*mp == NULL) {
1279  						/*
1280  						 * m_copym() couldn't allocate an mbuf.
1281 						 * Adjust uio_resid back (it was adjusted
1282 						 * down by len bytes, which we didn't end
1283 						 * up "copying" over).
1284  						 */
1285  						uio->uio_resid += len;
1286  						break;
1287  					}
1288 				}
1289 				m->m_data += len;
1290 				m->m_len -= len;
1291 				so->so_rcv.sb_cc -= len;
1292 			}
1293 		}
1294 		SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1295 		if (so->so_oobmark) {
1296 			if ((flags & MSG_PEEK) == 0) {
1297 				so->so_oobmark -= len;
1298 				if (so->so_oobmark == 0) {
1299 					so->so_rcv.sb_state |= SBS_RCVATMARK;
1300 					break;
1301 				}
1302 			} else {
1303 				offset += len;
1304 				if (offset == so->so_oobmark)
1305 					break;
1306 			}
1307 		}
1308 		if (flags & MSG_EOR)
1309 			break;
1310 		/*
1311 		 * If the MSG_WAITALL flag is set (for non-atomic socket),
1312 		 * we must not quit until "uio->uio_resid == 0" or an error
1313 		 * termination.  If a signal/timeout occurs, return
1314 		 * with a short count but without error.
1315 		 * Keep sockbuf locked against other readers.
1316 		 */
1317 		while (flags & MSG_WAITALL && m == NULL && uio->uio_resid > 0 &&
1318 		    !sosendallatonce(so) && nextrecord == NULL) {
1319 			SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1320 			if (so->so_error || so->so_rcv.sb_state & SBS_CANTRCVMORE)
1321 				break;
1322 			/*
1323 			 * Notify the protocol that some data has been
1324 			 * drained before blocking.
1325 			 */
1326 			if (pr->pr_flags & PR_WANTRCVD && so->so_pcb != NULL) {
1327 				SOCKBUF_UNLOCK(&so->so_rcv);
1328 				(*pr->pr_usrreqs->pru_rcvd)(so, flags);
1329 				SOCKBUF_LOCK(&so->so_rcv);
1330 			}
1331 			SBLASTRECORDCHK(&so->so_rcv);
1332 			SBLASTMBUFCHK(&so->so_rcv);
1333 			error = sbwait(&so->so_rcv);
1334 			if (error)
1335 				goto release;
1336 			m = so->so_rcv.sb_mb;
1337 			if (m != NULL)
1338 				nextrecord = m->m_nextpkt;
1339 		}
1340 	}
1341 
1342 	SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1343 	if (m != NULL && pr->pr_flags & PR_ATOMIC) {
1344 		flags |= MSG_TRUNC;
1345 		if ((flags & MSG_PEEK) == 0)
1346 			(void) sbdroprecord_locked(&so->so_rcv);
1347 	}
1348 	if ((flags & MSG_PEEK) == 0) {
1349 		if (m == NULL) {
1350 			/*
1351 			 * First part is an inline SB_EMPTY_FIXUP().  Second
1352 			 * part makes sure sb_lastrecord is up-to-date if
1353 			 * there is still data in the socket buffer.
1354 			 */
1355 			so->so_rcv.sb_mb = nextrecord;
1356 			if (so->so_rcv.sb_mb == NULL) {
1357 				so->so_rcv.sb_mbtail = NULL;
1358 				so->so_rcv.sb_lastrecord = NULL;
1359 			} else if (nextrecord->m_nextpkt == NULL)
1360 				so->so_rcv.sb_lastrecord = nextrecord;
1361 		}
1362 		SBLASTRECORDCHK(&so->so_rcv);
1363 		SBLASTMBUFCHK(&so->so_rcv);
1364 		/*
1365 		 * If soreceive() is being done from the socket callback, then
1366 		 * don't need to generate ACK to peer to update window, since
1367 		 * ACK will be generated on return to TCP.
1368 		 */
1369 		if (!(flags & MSG_SOCALLBCK) &&
1370 		    (pr->pr_flags & PR_WANTRCVD) && so->so_pcb) {
1371 			SOCKBUF_UNLOCK(&so->so_rcv);
1372 			(*pr->pr_usrreqs->pru_rcvd)(so, flags);
1373 			SOCKBUF_LOCK(&so->so_rcv);
1374 		}
1375 	}
1376 	SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1377 	if (orig_resid == uio->uio_resid && orig_resid &&
1378 	    (flags & MSG_EOR) == 0 && (so->so_rcv.sb_state & SBS_CANTRCVMORE) == 0) {
1379 		sbunlock(&so->so_rcv);
1380 		goto restart;
1381 	}
1382 
1383 	if (flagsp != NULL)
1384 		*flagsp |= flags;
1385 release:
1386 	SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1387 	sbunlock(&so->so_rcv);
1388 out:
1389 	SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1390 	SOCKBUF_UNLOCK(&so->so_rcv);
1391 	return (error);
1392 }
1393 
1394 int
1395 soshutdown(so, how)
1396 	struct socket *so;
1397 	int how;
1398 {
1399 	struct protosw *pr = so->so_proto;
1400 
1401 	if (!(how == SHUT_RD || how == SHUT_WR || how == SHUT_RDWR))
1402 		return (EINVAL);
1403 
1404 	if (how != SHUT_WR)
1405 		sorflush(so);
1406 	if (how != SHUT_RD)
1407 		return ((*pr->pr_usrreqs->pru_shutdown)(so));
1408 	return (0);
1409 }
1410 
1411 void
1412 sorflush(so)
1413 	struct socket *so;
1414 {
1415 	struct sockbuf *sb = &so->so_rcv;
1416 	struct protosw *pr = so->so_proto;
1417 	struct sockbuf asb;
1418 
1419 	/*
1420 	 * XXXRW: This is quite ugly.  Previously, this code made a copy of
1421 	 * the socket buffer, then zero'd the original to clear the buffer
1422 	 * fields.  However, with mutexes in the socket buffer, this causes
1423 	 * problems.  We only clear the zeroable bits of the original;
1424 	 * however, we have to initialize and destroy the mutex in the copy
1425 	 * so that dom_dispose() and sbrelease() can lock t as needed.
1426 	 */
1427 	SOCKBUF_LOCK(sb);
1428 	sb->sb_flags |= SB_NOINTR;
1429 	(void) sblock(sb, M_WAITOK);
1430 	/*
1431 	 * socantrcvmore_locked() drops the socket buffer mutex so that it
1432 	 * can safely perform wakeups.  Re-acquire the mutex before
1433 	 * continuing.
1434 	 */
1435 	socantrcvmore_locked(so);
1436 	SOCKBUF_LOCK(sb);
1437 	sbunlock(sb);
1438 	/*
1439 	 * Invalidate/clear most of the sockbuf structure, but leave
1440 	 * selinfo and mutex data unchanged.
1441 	 */
1442 	bzero(&asb, offsetof(struct sockbuf, sb_startzero));
1443 	bcopy(&sb->sb_startzero, &asb.sb_startzero,
1444 	    sizeof(*sb) - offsetof(struct sockbuf, sb_startzero));
1445 	bzero(&sb->sb_startzero,
1446 	    sizeof(*sb) - offsetof(struct sockbuf, sb_startzero));
1447 	SOCKBUF_UNLOCK(sb);
1448 
1449 	SOCKBUF_LOCK_INIT(&asb, "so_rcv");
1450 	if (pr->pr_flags & PR_RIGHTS && pr->pr_domain->dom_dispose != NULL)
1451 		(*pr->pr_domain->dom_dispose)(asb.sb_mb);
1452 	sbrelease(&asb, so);
1453 	SOCKBUF_LOCK_DESTROY(&asb);
1454 }
1455 
1456 #ifdef INET
1457 static int
1458 do_setopt_accept_filter(so, sopt)
1459 	struct	socket *so;
1460 	struct	sockopt *sopt;
1461 {
1462 	struct accept_filter_arg	*afap;
1463 	struct accept_filter	*afp;
1464 	struct so_accf	*newaf;
1465 	int	error = 0;
1466 
1467 	newaf = NULL;
1468 	afap = NULL;
1469 
1470 	/*
1471 	 * XXXRW: Configuring accept filters should be an atomic test-and-set
1472 	 * operation to prevent races during setup and attach.  There may be
1473 	 * more general issues of racing and ordering here that are not yet
1474 	 * addressed by locking.
1475 	 */
1476 	/* do not set/remove accept filters on non listen sockets */
1477 	SOCK_LOCK(so);
1478 	if ((so->so_options & SO_ACCEPTCONN) == 0) {
1479 		SOCK_UNLOCK(so);
1480 		return (EINVAL);
1481 	}
1482 
1483 	/* removing the filter */
1484 	if (sopt == NULL) {
1485 		if (so->so_accf != NULL) {
1486 			struct so_accf *af = so->so_accf;
1487 			if (af->so_accept_filter != NULL &&
1488 				af->so_accept_filter->accf_destroy != NULL) {
1489 				af->so_accept_filter->accf_destroy(so);
1490 			}
1491 			if (af->so_accept_filter_str != NULL) {
1492 				FREE(af->so_accept_filter_str, M_ACCF);
1493 			}
1494 			FREE(af, M_ACCF);
1495 			so->so_accf = NULL;
1496 		}
1497 		so->so_options &= ~SO_ACCEPTFILTER;
1498 		SOCK_UNLOCK(so);
1499 		return (0);
1500 	}
1501 	SOCK_UNLOCK(so);
1502 
1503 	/*-
1504 	 * Adding a filter.
1505 	 *
1506 	 * Do memory allocation, copyin, and filter lookup now while we're
1507 	 * not holding any locks.  Avoids sleeping with a mutex, as well as
1508 	 * introducing a lock order between accept filter locks and socket
1509 	 * locks here.
1510 	 */
1511 	MALLOC(afap, struct accept_filter_arg *, sizeof(*afap), M_TEMP,
1512 	    M_WAITOK);
1513 	/* don't put large objects on the kernel stack */
1514 	error = sooptcopyin(sopt, afap, sizeof *afap, sizeof *afap);
1515 	afap->af_name[sizeof(afap->af_name)-1] = '\0';
1516 	afap->af_arg[sizeof(afap->af_arg)-1] = '\0';
1517 	if (error) {
1518 		FREE(afap, M_TEMP);
1519 		return (error);
1520 	}
1521 	afp = accept_filt_get(afap->af_name);
1522 	if (afp == NULL) {
1523 		FREE(afap, M_TEMP);
1524 		return (ENOENT);
1525 	}
1526 
1527 	/*
1528 	 * Allocate the new accept filter instance storage.  We may have to
1529 	 * free it again later if we fail to attach it.  If attached
1530 	 * properly, 'newaf' is NULLed to avoid a free() while in use.
1531 	 */
1532 	MALLOC(newaf, struct so_accf *, sizeof(*newaf), M_ACCF, M_WAITOK |
1533 	    M_ZERO);
1534 	if (afp->accf_create != NULL && afap->af_name[0] != '\0') {
1535 		int len = strlen(afap->af_name) + 1;
1536 		MALLOC(newaf->so_accept_filter_str, char *, len, M_ACCF,
1537 		    M_WAITOK);
1538 		strcpy(newaf->so_accept_filter_str, afap->af_name);
1539 	}
1540 
1541 	SOCK_LOCK(so);
1542 	/* must remove previous filter first */
1543 	if (so->so_accf != NULL) {
1544 		error = EINVAL;
1545 		goto out;
1546 	}
1547 	/*
1548 	 * Invoke the accf_create() method of the filter if required.
1549 	 * XXXRW: the socket mutex is held over this call, so the create
1550 	 * method cannot block.  This may be something we have to change, but
1551 	 * it would require addressing possible races.
1552 	 */
1553 	if (afp->accf_create != NULL) {
1554 		newaf->so_accept_filter_arg =
1555 		    afp->accf_create(so, afap->af_arg);
1556 		if (newaf->so_accept_filter_arg == NULL) {
1557 			error = EINVAL;
1558 			goto out;
1559 		}
1560 	}
1561 	newaf->so_accept_filter = afp;
1562 	so->so_accf = newaf;
1563 	so->so_options |= SO_ACCEPTFILTER;
1564 	newaf = NULL;
1565 out:
1566 	SOCK_UNLOCK(so);
1567 	if (newaf != NULL) {
1568 		if (newaf->so_accept_filter_str != NULL)
1569 			FREE(newaf->so_accept_filter_str, M_ACCF);
1570 		FREE(newaf, M_ACCF);
1571 	}
1572 	if (afap != NULL)
1573 		FREE(afap, M_TEMP);
1574 	return (error);
1575 }
1576 #endif /* INET */
1577 
1578 /*
1579  * Perhaps this routine, and sooptcopyout(), below, ought to come in
1580  * an additional variant to handle the case where the option value needs
1581  * to be some kind of integer, but not a specific size.
1582  * In addition to their use here, these functions are also called by the
1583  * protocol-level pr_ctloutput() routines.
1584  */
1585 int
1586 sooptcopyin(sopt, buf, len, minlen)
1587 	struct	sockopt *sopt;
1588 	void	*buf;
1589 	size_t	len;
1590 	size_t	minlen;
1591 {
1592 	size_t	valsize;
1593 
1594 	/*
1595 	 * If the user gives us more than we wanted, we ignore it,
1596 	 * but if we don't get the minimum length the caller
1597 	 * wants, we return EINVAL.  On success, sopt->sopt_valsize
1598 	 * is set to however much we actually retrieved.
1599 	 */
1600 	if ((valsize = sopt->sopt_valsize) < minlen)
1601 		return EINVAL;
1602 	if (valsize > len)
1603 		sopt->sopt_valsize = valsize = len;
1604 
1605 	if (sopt->sopt_td != NULL)
1606 		return (copyin(sopt->sopt_val, buf, valsize));
1607 
1608 	bcopy(sopt->sopt_val, buf, valsize);
1609 	return 0;
1610 }
1611 
1612 /*
1613  * Kernel version of setsockopt(2)/
1614  * XXX: optlen is size_t, not socklen_t
1615  */
1616 int
1617 so_setsockopt(struct socket *so, int level, int optname, void *optval,
1618     size_t optlen)
1619 {
1620 	struct sockopt sopt;
1621 
1622 	sopt.sopt_level = level;
1623 	sopt.sopt_name = optname;
1624 	sopt.sopt_dir = SOPT_SET;
1625 	sopt.sopt_val = optval;
1626 	sopt.sopt_valsize = optlen;
1627 	sopt.sopt_td = NULL;
1628 	return (sosetopt(so, &sopt));
1629 }
1630 
1631 int
1632 sosetopt(so, sopt)
1633 	struct socket *so;
1634 	struct sockopt *sopt;
1635 {
1636 	int	error, optval;
1637 	struct	linger l;
1638 	struct	timeval tv;
1639 	u_long  val;
1640 #ifdef MAC
1641 	struct mac extmac;
1642 #endif
1643 
1644 	error = 0;
1645 	if (sopt->sopt_level != SOL_SOCKET) {
1646 		if (so->so_proto && so->so_proto->pr_ctloutput)
1647 			return ((*so->so_proto->pr_ctloutput)
1648 				  (so, sopt));
1649 		error = ENOPROTOOPT;
1650 	} else {
1651 		switch (sopt->sopt_name) {
1652 #ifdef INET
1653 		case SO_ACCEPTFILTER:
1654 			error = do_setopt_accept_filter(so, sopt);
1655 			if (error)
1656 				goto bad;
1657 			break;
1658 #endif
1659 		case SO_LINGER:
1660 			error = sooptcopyin(sopt, &l, sizeof l, sizeof l);
1661 			if (error)
1662 				goto bad;
1663 
1664 			SOCK_LOCK(so);
1665 			so->so_linger = l.l_linger;
1666 			if (l.l_onoff)
1667 				so->so_options |= SO_LINGER;
1668 			else
1669 				so->so_options &= ~SO_LINGER;
1670 			SOCK_UNLOCK(so);
1671 			break;
1672 
1673 		case SO_DEBUG:
1674 		case SO_KEEPALIVE:
1675 		case SO_DONTROUTE:
1676 		case SO_USELOOPBACK:
1677 		case SO_BROADCAST:
1678 		case SO_REUSEADDR:
1679 		case SO_REUSEPORT:
1680 		case SO_OOBINLINE:
1681 		case SO_TIMESTAMP:
1682 		case SO_BINTIME:
1683 		case SO_NOSIGPIPE:
1684 			error = sooptcopyin(sopt, &optval, sizeof optval,
1685 					    sizeof optval);
1686 			if (error)
1687 				goto bad;
1688 			SOCK_LOCK(so);
1689 			if (optval)
1690 				so->so_options |= sopt->sopt_name;
1691 			else
1692 				so->so_options &= ~sopt->sopt_name;
1693 			SOCK_UNLOCK(so);
1694 			break;
1695 
1696 		case SO_SNDBUF:
1697 		case SO_RCVBUF:
1698 		case SO_SNDLOWAT:
1699 		case SO_RCVLOWAT:
1700 			error = sooptcopyin(sopt, &optval, sizeof optval,
1701 					    sizeof optval);
1702 			if (error)
1703 				goto bad;
1704 
1705 			/*
1706 			 * Values < 1 make no sense for any of these
1707 			 * options, so disallow them.
1708 			 */
1709 			if (optval < 1) {
1710 				error = EINVAL;
1711 				goto bad;
1712 			}
1713 
1714 			switch (sopt->sopt_name) {
1715 			case SO_SNDBUF:
1716 			case SO_RCVBUF:
1717 				if (sbreserve(sopt->sopt_name == SO_SNDBUF ?
1718 				    &so->so_snd : &so->so_rcv, (u_long)optval,
1719 				    so, curthread) == 0) {
1720 					error = ENOBUFS;
1721 					goto bad;
1722 				}
1723 				break;
1724 
1725 			/*
1726 			 * Make sure the low-water is never greater than
1727 			 * the high-water.
1728 			 */
1729 			case SO_SNDLOWAT:
1730 				SOCKBUF_LOCK(&so->so_snd);
1731 				so->so_snd.sb_lowat =
1732 				    (optval > so->so_snd.sb_hiwat) ?
1733 				    so->so_snd.sb_hiwat : optval;
1734 				SOCKBUF_UNLOCK(&so->so_snd);
1735 				break;
1736 			case SO_RCVLOWAT:
1737 				SOCKBUF_LOCK(&so->so_rcv);
1738 				so->so_rcv.sb_lowat =
1739 				    (optval > so->so_rcv.sb_hiwat) ?
1740 				    so->so_rcv.sb_hiwat : optval;
1741 				SOCKBUF_UNLOCK(&so->so_rcv);
1742 				break;
1743 			}
1744 			break;
1745 
1746 		case SO_SNDTIMEO:
1747 		case SO_RCVTIMEO:
1748 			error = sooptcopyin(sopt, &tv, sizeof tv,
1749 					    sizeof tv);
1750 			if (error)
1751 				goto bad;
1752 
1753 			/* assert(hz > 0); */
1754 			if (tv.tv_sec < 0 || tv.tv_sec > INT_MAX / hz ||
1755 			    tv.tv_usec < 0 || tv.tv_usec >= 1000000) {
1756 				error = EDOM;
1757 				goto bad;
1758 			}
1759 			/* assert(tick > 0); */
1760 			/* assert(ULONG_MAX - INT_MAX >= 1000000); */
1761 			val = (u_long)(tv.tv_sec * hz) + tv.tv_usec / tick;
1762 			if (val > INT_MAX) {
1763 				error = EDOM;
1764 				goto bad;
1765 			}
1766 			if (val == 0 && tv.tv_usec != 0)
1767 				val = 1;
1768 
1769 			switch (sopt->sopt_name) {
1770 			case SO_SNDTIMEO:
1771 				so->so_snd.sb_timeo = val;
1772 				break;
1773 			case SO_RCVTIMEO:
1774 				so->so_rcv.sb_timeo = val;
1775 				break;
1776 			}
1777 			break;
1778 		case SO_LABEL:
1779 #ifdef MAC
1780 			error = sooptcopyin(sopt, &extmac, sizeof extmac,
1781 			    sizeof extmac);
1782 			if (error)
1783 				goto bad;
1784 			error = mac_setsockopt_label(sopt->sopt_td->td_ucred,
1785 			    so, &extmac);
1786 #else
1787 			error = EOPNOTSUPP;
1788 #endif
1789 			break;
1790 		default:
1791 			error = ENOPROTOOPT;
1792 			break;
1793 		}
1794 		if (error == 0 && so->so_proto != NULL &&
1795 		    so->so_proto->pr_ctloutput != NULL) {
1796 			(void) ((*so->so_proto->pr_ctloutput)
1797 				  (so, sopt));
1798 		}
1799 	}
1800 bad:
1801 	return (error);
1802 }
1803 
1804 /* Helper routine for getsockopt */
1805 int
1806 sooptcopyout(struct sockopt *sopt, const void *buf, size_t len)
1807 {
1808 	int	error;
1809 	size_t	valsize;
1810 
1811 	error = 0;
1812 
1813 	/*
1814 	 * Documented get behavior is that we always return a value,
1815 	 * possibly truncated to fit in the user's buffer.
1816 	 * Traditional behavior is that we always tell the user
1817 	 * precisely how much we copied, rather than something useful
1818 	 * like the total amount we had available for her.
1819 	 * Note that this interface is not idempotent; the entire answer must
1820 	 * generated ahead of time.
1821 	 */
1822 	valsize = min(len, sopt->sopt_valsize);
1823 	sopt->sopt_valsize = valsize;
1824 	if (sopt->sopt_val != NULL) {
1825 		if (sopt->sopt_td != NULL)
1826 			error = copyout(buf, sopt->sopt_val, valsize);
1827 		else
1828 			bcopy(buf, sopt->sopt_val, valsize);
1829 	}
1830 	return error;
1831 }
1832 
1833 int
1834 sogetopt(so, sopt)
1835 	struct socket *so;
1836 	struct sockopt *sopt;
1837 {
1838 	int	error, optval;
1839 	struct	linger l;
1840 	struct	timeval tv;
1841 #ifdef INET
1842 	struct accept_filter_arg *afap;
1843 #endif
1844 #ifdef MAC
1845 	struct mac extmac;
1846 #endif
1847 
1848 	error = 0;
1849 	if (sopt->sopt_level != SOL_SOCKET) {
1850 		if (so->so_proto && so->so_proto->pr_ctloutput) {
1851 			return ((*so->so_proto->pr_ctloutput)
1852 				  (so, sopt));
1853 		} else
1854 			return (ENOPROTOOPT);
1855 	} else {
1856 		switch (sopt->sopt_name) {
1857 #ifdef INET
1858 		case SO_ACCEPTFILTER:
1859 			/* Unlocked read. */
1860 			if ((so->so_options & SO_ACCEPTCONN) == 0)
1861 				return (EINVAL);
1862 			MALLOC(afap, struct accept_filter_arg *, sizeof(*afap),
1863 				M_TEMP, M_WAITOK | M_ZERO);
1864 			SOCK_LOCK(so);
1865 			if ((so->so_options & SO_ACCEPTFILTER) != 0) {
1866 				strcpy(afap->af_name, so->so_accf->so_accept_filter->accf_name);
1867 				if (so->so_accf->so_accept_filter_str != NULL)
1868 					strcpy(afap->af_arg, so->so_accf->so_accept_filter_str);
1869 			}
1870 			SOCK_UNLOCK(so);
1871 			error = sooptcopyout(sopt, afap, sizeof(*afap));
1872 			FREE(afap, M_TEMP);
1873 			break;
1874 #endif
1875 
1876 		case SO_LINGER:
1877 			SOCK_LOCK(so);
1878 			l.l_onoff = so->so_options & SO_LINGER;
1879 			l.l_linger = so->so_linger;
1880 			SOCK_UNLOCK(so);
1881 			error = sooptcopyout(sopt, &l, sizeof l);
1882 			break;
1883 
1884 		case SO_USELOOPBACK:
1885 		case SO_DONTROUTE:
1886 		case SO_DEBUG:
1887 		case SO_KEEPALIVE:
1888 		case SO_REUSEADDR:
1889 		case SO_REUSEPORT:
1890 		case SO_BROADCAST:
1891 		case SO_OOBINLINE:
1892 		case SO_TIMESTAMP:
1893 		case SO_BINTIME:
1894 		case SO_NOSIGPIPE:
1895 			optval = so->so_options & sopt->sopt_name;
1896 integer:
1897 			error = sooptcopyout(sopt, &optval, sizeof optval);
1898 			break;
1899 
1900 		case SO_TYPE:
1901 			optval = so->so_type;
1902 			goto integer;
1903 
1904 		case SO_ERROR:
1905 			optval = so->so_error;
1906 			so->so_error = 0;
1907 			goto integer;
1908 
1909 		case SO_SNDBUF:
1910 			optval = so->so_snd.sb_hiwat;
1911 			goto integer;
1912 
1913 		case SO_RCVBUF:
1914 			optval = so->so_rcv.sb_hiwat;
1915 			goto integer;
1916 
1917 		case SO_SNDLOWAT:
1918 			optval = so->so_snd.sb_lowat;
1919 			goto integer;
1920 
1921 		case SO_RCVLOWAT:
1922 			optval = so->so_rcv.sb_lowat;
1923 			goto integer;
1924 
1925 		case SO_SNDTIMEO:
1926 		case SO_RCVTIMEO:
1927 			optval = (sopt->sopt_name == SO_SNDTIMEO ?
1928 				  so->so_snd.sb_timeo : so->so_rcv.sb_timeo);
1929 
1930 			tv.tv_sec = optval / hz;
1931 			tv.tv_usec = (optval % hz) * tick;
1932 			error = sooptcopyout(sopt, &tv, sizeof tv);
1933 			break;
1934 		case SO_LABEL:
1935 #ifdef MAC
1936 			error = sooptcopyin(sopt, &extmac, sizeof(extmac),
1937 			    sizeof(extmac));
1938 			if (error)
1939 				return (error);
1940 			error = mac_getsockopt_label(sopt->sopt_td->td_ucred,
1941 			    so, &extmac);
1942 			if (error)
1943 				return (error);
1944 			error = sooptcopyout(sopt, &extmac, sizeof extmac);
1945 #else
1946 			error = EOPNOTSUPP;
1947 #endif
1948 			break;
1949 		case SO_PEERLABEL:
1950 #ifdef MAC
1951 			error = sooptcopyin(sopt, &extmac, sizeof(extmac),
1952 			    sizeof(extmac));
1953 			if (error)
1954 				return (error);
1955 			error = mac_getsockopt_peerlabel(
1956 			    sopt->sopt_td->td_ucred, so, &extmac);
1957 			if (error)
1958 				return (error);
1959 			error = sooptcopyout(sopt, &extmac, sizeof extmac);
1960 #else
1961 			error = EOPNOTSUPP;
1962 #endif
1963 			break;
1964 		default:
1965 			error = ENOPROTOOPT;
1966 			break;
1967 		}
1968 		return (error);
1969 	}
1970 }
1971 
1972 /* XXX; prepare mbuf for (__FreeBSD__ < 3) routines. */
1973 int
1974 soopt_getm(struct sockopt *sopt, struct mbuf **mp)
1975 {
1976 	struct mbuf *m, *m_prev;
1977 	int sopt_size = sopt->sopt_valsize;
1978 
1979 	MGET(m, sopt->sopt_td ? M_TRYWAIT : M_DONTWAIT, MT_DATA);
1980 	if (m == NULL)
1981 		return ENOBUFS;
1982 	if (sopt_size > MLEN) {
1983 		MCLGET(m, sopt->sopt_td ? M_TRYWAIT : M_DONTWAIT);
1984 		if ((m->m_flags & M_EXT) == 0) {
1985 			m_free(m);
1986 			return ENOBUFS;
1987 		}
1988 		m->m_len = min(MCLBYTES, sopt_size);
1989 	} else {
1990 		m->m_len = min(MLEN, sopt_size);
1991 	}
1992 	sopt_size -= m->m_len;
1993 	*mp = m;
1994 	m_prev = m;
1995 
1996 	while (sopt_size) {
1997 		MGET(m, sopt->sopt_td ? M_TRYWAIT : M_DONTWAIT, MT_DATA);
1998 		if (m == NULL) {
1999 			m_freem(*mp);
2000 			return ENOBUFS;
2001 		}
2002 		if (sopt_size > MLEN) {
2003 			MCLGET(m, sopt->sopt_td != NULL ? M_TRYWAIT :
2004 			    M_DONTWAIT);
2005 			if ((m->m_flags & M_EXT) == 0) {
2006 				m_freem(m);
2007 				m_freem(*mp);
2008 				return ENOBUFS;
2009 			}
2010 			m->m_len = min(MCLBYTES, sopt_size);
2011 		} else {
2012 			m->m_len = min(MLEN, sopt_size);
2013 		}
2014 		sopt_size -= m->m_len;
2015 		m_prev->m_next = m;
2016 		m_prev = m;
2017 	}
2018 	return 0;
2019 }
2020 
2021 /* XXX; copyin sopt data into mbuf chain for (__FreeBSD__ < 3) routines. */
2022 int
2023 soopt_mcopyin(struct sockopt *sopt, struct mbuf *m)
2024 {
2025 	struct mbuf *m0 = m;
2026 
2027 	if (sopt->sopt_val == NULL)
2028 		return 0;
2029 	while (m != NULL && sopt->sopt_valsize >= m->m_len) {
2030 		if (sopt->sopt_td != NULL) {
2031 			int error;
2032 
2033 			error = copyin(sopt->sopt_val, mtod(m, char *),
2034 				       m->m_len);
2035 			if (error != 0) {
2036 				m_freem(m0);
2037 				return(error);
2038 			}
2039 		} else
2040 			bcopy(sopt->sopt_val, mtod(m, char *), m->m_len);
2041 		sopt->sopt_valsize -= m->m_len;
2042 		sopt->sopt_val = (char *)sopt->sopt_val + m->m_len;
2043 		m = m->m_next;
2044 	}
2045 	if (m != NULL) /* should be allocated enoughly at ip6_sooptmcopyin() */
2046 		panic("ip6_sooptmcopyin");
2047 	return 0;
2048 }
2049 
2050 /* XXX; copyout mbuf chain data into soopt for (__FreeBSD__ < 3) routines. */
2051 int
2052 soopt_mcopyout(struct sockopt *sopt, struct mbuf *m)
2053 {
2054 	struct mbuf *m0 = m;
2055 	size_t valsize = 0;
2056 
2057 	if (sopt->sopt_val == NULL)
2058 		return 0;
2059 	while (m != NULL && sopt->sopt_valsize >= m->m_len) {
2060 		if (sopt->sopt_td != NULL) {
2061 			int error;
2062 
2063 			error = copyout(mtod(m, char *), sopt->sopt_val,
2064 				       m->m_len);
2065 			if (error != 0) {
2066 				m_freem(m0);
2067 				return(error);
2068 			}
2069 		} else
2070 			bcopy(mtod(m, char *), sopt->sopt_val, m->m_len);
2071 	       sopt->sopt_valsize -= m->m_len;
2072 	       sopt->sopt_val = (char *)sopt->sopt_val + m->m_len;
2073 	       valsize += m->m_len;
2074 	       m = m->m_next;
2075 	}
2076 	if (m != NULL) {
2077 		/* enough soopt buffer should be given from user-land */
2078 		m_freem(m0);
2079 		return(EINVAL);
2080 	}
2081 	sopt->sopt_valsize = valsize;
2082 	return 0;
2083 }
2084 
2085 void
2086 sohasoutofband(so)
2087 	struct socket *so;
2088 {
2089 	if (so->so_sigio != NULL)
2090 		pgsigio(&so->so_sigio, SIGURG, 0);
2091 	selwakeuppri(&so->so_rcv.sb_sel, PSOCK);
2092 }
2093 
2094 int
2095 sopoll(struct socket *so, int events, struct ucred *active_cred,
2096     struct thread *td)
2097 {
2098 	int revents = 0;
2099 
2100 	SOCKBUF_LOCK(&so->so_snd);
2101 	SOCKBUF_LOCK(&so->so_rcv);
2102 	if (events & (POLLIN | POLLRDNORM))
2103 		if (soreadable(so))
2104 			revents |= events & (POLLIN | POLLRDNORM);
2105 
2106 	if (events & POLLINIGNEOF)
2107 		if (so->so_rcv.sb_cc >= so->so_rcv.sb_lowat ||
2108 		    !TAILQ_EMPTY(&so->so_comp) || so->so_error)
2109 			revents |= POLLINIGNEOF;
2110 
2111 	if (events & (POLLOUT | POLLWRNORM))
2112 		if (sowriteable(so))
2113 			revents |= events & (POLLOUT | POLLWRNORM);
2114 
2115 	if (events & (POLLPRI | POLLRDBAND))
2116 		if (so->so_oobmark || (so->so_rcv.sb_state & SBS_RCVATMARK))
2117 			revents |= events & (POLLPRI | POLLRDBAND);
2118 
2119 	if (revents == 0) {
2120 		if (events &
2121 		    (POLLIN | POLLINIGNEOF | POLLPRI | POLLRDNORM |
2122 		     POLLRDBAND)) {
2123 			selrecord(td, &so->so_rcv.sb_sel);
2124 			so->so_rcv.sb_flags |= SB_SEL;
2125 		}
2126 
2127 		if (events & (POLLOUT | POLLWRNORM)) {
2128 			selrecord(td, &so->so_snd.sb_sel);
2129 			so->so_snd.sb_flags |= SB_SEL;
2130 		}
2131 	}
2132 
2133 	SOCKBUF_UNLOCK(&so->so_rcv);
2134 	SOCKBUF_UNLOCK(&so->so_snd);
2135 	return (revents);
2136 }
2137 
2138 int
2139 soo_kqfilter(struct file *fp, struct knote *kn)
2140 {
2141 	struct socket *so = kn->kn_fp->f_data;
2142 	struct sockbuf *sb;
2143 
2144 	switch (kn->kn_filter) {
2145 	case EVFILT_READ:
2146 		if (so->so_options & SO_ACCEPTCONN)
2147 			kn->kn_fop = &solisten_filtops;
2148 		else
2149 			kn->kn_fop = &soread_filtops;
2150 		sb = &so->so_rcv;
2151 		break;
2152 	case EVFILT_WRITE:
2153 		kn->kn_fop = &sowrite_filtops;
2154 		sb = &so->so_snd;
2155 		break;
2156 	default:
2157 		return (EINVAL);
2158 	}
2159 
2160 	SOCKBUF_LOCK(sb);
2161 	knlist_add(&sb->sb_sel.si_note, kn, 1);
2162 	sb->sb_flags |= SB_KNOTE;
2163 	SOCKBUF_UNLOCK(sb);
2164 	return (0);
2165 }
2166 
2167 static void
2168 filt_sordetach(struct knote *kn)
2169 {
2170 	struct socket *so = kn->kn_fp->f_data;
2171 
2172 	SOCKBUF_LOCK(&so->so_rcv);
2173 	knlist_remove(&so->so_rcv.sb_sel.si_note, kn, 1);
2174 	if (knlist_empty(&so->so_rcv.sb_sel.si_note))
2175 		so->so_rcv.sb_flags &= ~SB_KNOTE;
2176 	SOCKBUF_UNLOCK(&so->so_rcv);
2177 }
2178 
2179 /*ARGSUSED*/
2180 static int
2181 filt_soread(struct knote *kn, long hint)
2182 {
2183 	struct socket *so;
2184 
2185 	so = kn->kn_fp->f_data;
2186 	SOCKBUF_LOCK_ASSERT(&so->so_rcv);
2187 
2188 	kn->kn_data = so->so_rcv.sb_cc - so->so_rcv.sb_ctl;
2189 	if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
2190 		kn->kn_flags |= EV_EOF;
2191 		kn->kn_fflags = so->so_error;
2192 		return (1);
2193 	} else if (so->so_error)	/* temporary udp error */
2194 		return (1);
2195 	else if (kn->kn_sfflags & NOTE_LOWAT)
2196 		return (kn->kn_data >= kn->kn_sdata);
2197 	else
2198 		return (so->so_rcv.sb_cc >= so->so_rcv.sb_lowat);
2199 }
2200 
2201 static void
2202 filt_sowdetach(struct knote *kn)
2203 {
2204 	struct socket *so = kn->kn_fp->f_data;
2205 
2206 	SOCKBUF_LOCK(&so->so_snd);
2207 	knlist_remove(&so->so_snd.sb_sel.si_note, kn, 1);
2208 	if (knlist_empty(&so->so_snd.sb_sel.si_note))
2209 		so->so_snd.sb_flags &= ~SB_KNOTE;
2210 	SOCKBUF_UNLOCK(&so->so_snd);
2211 }
2212 
2213 /*ARGSUSED*/
2214 static int
2215 filt_sowrite(struct knote *kn, long hint)
2216 {
2217 	struct socket *so;
2218 
2219 	so = kn->kn_fp->f_data;
2220 	SOCKBUF_LOCK_ASSERT(&so->so_snd);
2221 	kn->kn_data = sbspace(&so->so_snd);
2222 	if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
2223 		kn->kn_flags |= EV_EOF;
2224 		kn->kn_fflags = so->so_error;
2225 		return (1);
2226 	} else if (so->so_error)	/* temporary udp error */
2227 		return (1);
2228 	else if (((so->so_state & SS_ISCONNECTED) == 0) &&
2229 	    (so->so_proto->pr_flags & PR_CONNREQUIRED))
2230 		return (0);
2231 	else if (kn->kn_sfflags & NOTE_LOWAT)
2232 		return (kn->kn_data >= kn->kn_sdata);
2233 	else
2234 		return (kn->kn_data >= so->so_snd.sb_lowat);
2235 }
2236 
2237 /*ARGSUSED*/
2238 static int
2239 filt_solisten(struct knote *kn, long hint)
2240 {
2241 	struct socket *so = kn->kn_fp->f_data;
2242 
2243 	kn->kn_data = so->so_qlen;
2244 	return (! TAILQ_EMPTY(&so->so_comp));
2245 }
2246 
2247 int
2248 socheckuid(struct socket *so, uid_t uid)
2249 {
2250 
2251 	if (so == NULL)
2252 		return (EPERM);
2253 	if (so->so_cred->cr_uid == uid)
2254 		return (0);
2255 	return (EPERM);
2256 }
2257