xref: /freebsd/sys/kern/uipc_socket.c (revision 6e0da4f753ed6b5d26395001a6194b4fdea70177)
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 		SOCK_LOCK(so);
524 		/*
525 		 * Prevent accumulated error from previous connection
526 		 * from biting us.
527 		 */
528 		so->so_error = 0;
529 		SOCK_UNLOCK(so);
530 		error = (*so->so_proto->pr_usrreqs->pru_connect)(so, nam, td);
531 	}
532 
533 	return (error);
534 }
535 
536 int
537 soconnect2(so1, so2)
538 	struct socket *so1;
539 	struct socket *so2;
540 {
541 
542 	return ((*so1->so_proto->pr_usrreqs->pru_connect2)(so1, so2));
543 }
544 
545 int
546 sodisconnect(so)
547 	struct socket *so;
548 {
549 	int error;
550 
551 	if ((so->so_state & SS_ISCONNECTED) == 0)
552 		return (ENOTCONN);
553 	if (so->so_state & SS_ISDISCONNECTING)
554 		return (EALREADY);
555 	error = (*so->so_proto->pr_usrreqs->pru_disconnect)(so);
556 	return (error);
557 }
558 
559 #define	SBLOCKWAIT(f)	(((f) & MSG_DONTWAIT) ? M_NOWAIT : M_WAITOK)
560 /*
561  * Send on a socket.
562  * If send must go all at once and message is larger than
563  * send buffering, then hard error.
564  * Lock against other senders.
565  * If must go all at once and not enough room now, then
566  * inform user that this would block and do nothing.
567  * Otherwise, if nonblocking, send as much as possible.
568  * The data to be sent is described by "uio" if nonzero,
569  * otherwise by the mbuf chain "top" (which must be null
570  * if uio is not).  Data provided in mbuf chain must be small
571  * enough to send all at once.
572  *
573  * Returns nonzero on error, timeout or signal; callers
574  * must check for short counts if EINTR/ERESTART are returned.
575  * Data and control buffers are freed on return.
576  */
577 
578 #ifdef ZERO_COPY_SOCKETS
579 struct so_zerocopy_stats{
580 	int size_ok;
581 	int align_ok;
582 	int found_ifp;
583 };
584 struct so_zerocopy_stats so_zerocp_stats = {0,0,0};
585 #include <netinet/in.h>
586 #include <net/route.h>
587 #include <netinet/in_pcb.h>
588 #include <vm/vm.h>
589 #include <vm/vm_page.h>
590 #include <vm/vm_object.h>
591 #endif /*ZERO_COPY_SOCKETS*/
592 
593 int
594 sosend(so, addr, uio, top, control, flags, td)
595 	struct socket *so;
596 	struct sockaddr *addr;
597 	struct uio *uio;
598 	struct mbuf *top;
599 	struct mbuf *control;
600 	int flags;
601 	struct thread *td;
602 {
603 	struct mbuf **mp;
604 	struct mbuf *m;
605 	long space, len = 0, resid;
606 	int clen = 0, error, dontroute;
607 	int atomic = sosendallatonce(so) || top;
608 #ifdef ZERO_COPY_SOCKETS
609 	int cow_send;
610 #endif /* ZERO_COPY_SOCKETS */
611 
612 	if (uio != NULL)
613 		resid = uio->uio_resid;
614 	else
615 		resid = top->m_pkthdr.len;
616 	/*
617 	 * In theory resid should be unsigned.
618 	 * However, space must be signed, as it might be less than 0
619 	 * if we over-committed, and we must use a signed comparison
620 	 * of space and resid.  On the other hand, a negative resid
621 	 * causes us to loop sending 0-length segments to the protocol.
622 	 *
623 	 * Also check to make sure that MSG_EOR isn't used on SOCK_STREAM
624 	 * type sockets since that's an error.
625 	 */
626 	if (resid < 0 || (so->so_type == SOCK_STREAM && (flags & MSG_EOR))) {
627 		error = EINVAL;
628 		goto out;
629 	}
630 
631 	dontroute =
632 	    (flags & MSG_DONTROUTE) && (so->so_options & SO_DONTROUTE) == 0 &&
633 	    (so->so_proto->pr_flags & PR_ATOMIC);
634 	if (td != NULL)
635 		td->td_proc->p_stats->p_ru.ru_msgsnd++;
636 	if (control != NULL)
637 		clen = control->m_len;
638 #define	snderr(errno)	{ error = (errno); goto release; }
639 
640 	SOCKBUF_LOCK(&so->so_snd);
641 restart:
642 	SOCKBUF_LOCK_ASSERT(&so->so_snd);
643 	error = sblock(&so->so_snd, SBLOCKWAIT(flags));
644 	if (error)
645 		goto out_locked;
646 	do {
647 		SOCKBUF_LOCK_ASSERT(&so->so_snd);
648 		if (so->so_snd.sb_state & SBS_CANTSENDMORE)
649 			snderr(EPIPE);
650 		if (so->so_error) {
651 			error = so->so_error;
652 			so->so_error = 0;
653 			goto release;
654 		}
655 		if ((so->so_state & SS_ISCONNECTED) == 0) {
656 			/*
657 			 * `sendto' and `sendmsg' is allowed on a connection-
658 			 * based socket if it supports implied connect.
659 			 * Return ENOTCONN if not connected and no address is
660 			 * supplied.
661 			 */
662 			if ((so->so_proto->pr_flags & PR_CONNREQUIRED) &&
663 			    (so->so_proto->pr_flags & PR_IMPLOPCL) == 0) {
664 				if ((so->so_state & SS_ISCONFIRMING) == 0 &&
665 				    !(resid == 0 && clen != 0))
666 					snderr(ENOTCONN);
667 			} else if (addr == NULL)
668 			    snderr(so->so_proto->pr_flags & PR_CONNREQUIRED ?
669 				   ENOTCONN : EDESTADDRREQ);
670 		}
671 		space = sbspace(&so->so_snd);
672 		if (flags & MSG_OOB)
673 			space += 1024;
674 		if ((atomic && resid > so->so_snd.sb_hiwat) ||
675 		    clen > so->so_snd.sb_hiwat)
676 			snderr(EMSGSIZE);
677 		if (space < resid + clen &&
678 		    (atomic || space < so->so_snd.sb_lowat || space < clen)) {
679 			if ((so->so_state & SS_NBIO) || (flags & MSG_NBIO))
680 				snderr(EWOULDBLOCK);
681 			sbunlock(&so->so_snd);
682 			error = sbwait(&so->so_snd);
683 			if (error)
684 				goto out_locked;
685 			goto restart;
686 		}
687 		SOCKBUF_UNLOCK(&so->so_snd);
688 		mp = &top;
689 		space -= clen;
690 		do {
691 		    if (uio == NULL) {
692 			/*
693 			 * Data is prepackaged in "top".
694 			 */
695 			resid = 0;
696 			if (flags & MSG_EOR)
697 				top->m_flags |= M_EOR;
698 		    } else do {
699 #ifdef ZERO_COPY_SOCKETS
700 			cow_send = 0;
701 #endif /* ZERO_COPY_SOCKETS */
702 			if (resid >= MINCLSIZE) {
703 #ifdef ZERO_COPY_SOCKETS
704 				if (top == NULL) {
705 					MGETHDR(m, M_TRYWAIT, MT_DATA);
706 					if (m == NULL) {
707 						error = ENOBUFS;
708 						SOCKBUF_LOCK(&so->so_snd);
709 						goto release;
710 					}
711 					m->m_pkthdr.len = 0;
712 					m->m_pkthdr.rcvif = (struct ifnet *)0;
713 				} else {
714 					MGET(m, M_TRYWAIT, MT_DATA);
715 					if (m == NULL) {
716 						error = ENOBUFS;
717 						SOCKBUF_LOCK(&so->so_snd);
718 						goto release;
719 					}
720 				}
721 				if (so_zero_copy_send &&
722 				    resid>=PAGE_SIZE &&
723 				    space>=PAGE_SIZE &&
724 				    uio->uio_iov->iov_len>=PAGE_SIZE) {
725 					so_zerocp_stats.size_ok++;
726 					if (!((vm_offset_t)
727 					  uio->uio_iov->iov_base & PAGE_MASK)){
728 						so_zerocp_stats.align_ok++;
729 						cow_send = socow_setup(m, uio);
730 					}
731 				}
732 				if (!cow_send) {
733 					MCLGET(m, M_TRYWAIT);
734 					if ((m->m_flags & M_EXT) == 0) {
735 						m_free(m);
736 						m = NULL;
737 					} else {
738 						len = min(min(MCLBYTES, resid), space);
739 					}
740 				} else
741 					len = PAGE_SIZE;
742 #else /* ZERO_COPY_SOCKETS */
743 				if (top == NULL) {
744 					m = m_getcl(M_TRYWAIT, MT_DATA, M_PKTHDR);
745 					m->m_pkthdr.len = 0;
746 					m->m_pkthdr.rcvif = (struct ifnet *)0;
747 				} else
748 					m = m_getcl(M_TRYWAIT, MT_DATA, 0);
749 				len = min(min(MCLBYTES, resid), space);
750 #endif /* ZERO_COPY_SOCKETS */
751 			} else {
752 				if (top == NULL) {
753 					m = m_gethdr(M_TRYWAIT, MT_DATA);
754 					m->m_pkthdr.len = 0;
755 					m->m_pkthdr.rcvif = (struct ifnet *)0;
756 
757 					len = min(min(MHLEN, resid), space);
758 					/*
759 					 * For datagram protocols, leave room
760 					 * for protocol headers in first mbuf.
761 					 */
762 					if (atomic && m && len < MHLEN)
763 						MH_ALIGN(m, len);
764 				} else {
765 					m = m_get(M_TRYWAIT, MT_DATA);
766 					len = min(min(MLEN, resid), space);
767 				}
768 			}
769 			if (m == NULL) {
770 				error = ENOBUFS;
771 				SOCKBUF_LOCK(&so->so_snd);
772 				goto release;
773 			}
774 
775 			space -= len;
776 #ifdef ZERO_COPY_SOCKETS
777 			if (cow_send)
778 				error = 0;
779 			else
780 #endif /* ZERO_COPY_SOCKETS */
781 			error = uiomove(mtod(m, void *), (int)len, uio);
782 			resid = uio->uio_resid;
783 			m->m_len = len;
784 			*mp = m;
785 			top->m_pkthdr.len += len;
786 			if (error) {
787 				SOCKBUF_LOCK(&so->so_snd);
788 				goto release;
789 			}
790 			mp = &m->m_next;
791 			if (resid <= 0) {
792 				if (flags & MSG_EOR)
793 					top->m_flags |= M_EOR;
794 				break;
795 			}
796 		    } while (space > 0 && atomic);
797 		    if (dontroute) {
798 			    SOCK_LOCK(so);
799 			    so->so_options |= SO_DONTROUTE;
800 			    SOCK_UNLOCK(so);
801 		    }
802 		    /*
803 		     * XXX all the SBS_CANTSENDMORE checks previously
804 		     * done could be out of date.  We could have recieved
805 		     * a reset packet in an interrupt or maybe we slept
806 		     * while doing page faults in uiomove() etc. We could
807 		     * probably recheck again inside the locking protection
808 		     * here, but there are probably other places that this
809 		     * also happens.  We must rethink this.
810 		     */
811 		    error = (*so->so_proto->pr_usrreqs->pru_send)(so,
812 			(flags & MSG_OOB) ? PRUS_OOB :
813 			/*
814 			 * If the user set MSG_EOF, the protocol
815 			 * understands this flag and nothing left to
816 			 * send then use PRU_SEND_EOF instead of PRU_SEND.
817 			 */
818 			((flags & MSG_EOF) &&
819 			 (so->so_proto->pr_flags & PR_IMPLOPCL) &&
820 			 (resid <= 0)) ?
821 				PRUS_EOF :
822 			/* If there is more to send set PRUS_MORETOCOME */
823 			(resid > 0 && space > 0) ? PRUS_MORETOCOME : 0,
824 			top, addr, control, td);
825 		    if (dontroute) {
826 			    SOCK_LOCK(so);
827 			    so->so_options &= ~SO_DONTROUTE;
828 			    SOCK_UNLOCK(so);
829 		    }
830 		    clen = 0;
831 		    control = NULL;
832 		    top = NULL;
833 		    mp = &top;
834 		    if (error) {
835 			SOCKBUF_LOCK(&so->so_snd);
836 			goto release;
837 		    }
838 		} while (resid && space > 0);
839 		SOCKBUF_LOCK(&so->so_snd);
840 	} while (resid);
841 
842 release:
843 	SOCKBUF_LOCK_ASSERT(&so->so_snd);
844 	sbunlock(&so->so_snd);
845 out_locked:
846 	SOCKBUF_LOCK_ASSERT(&so->so_snd);
847 	SOCKBUF_UNLOCK(&so->so_snd);
848 out:
849 	if (top != NULL)
850 		m_freem(top);
851 	if (control != NULL)
852 		m_freem(control);
853 	return (error);
854 }
855 
856 /*
857  * The part of soreceive() that implements reading non-inline out-of-band
858  * data from a socket.  For more complete comments, see soreceive(), from
859  * which this code originated.
860  *
861  * Note that soreceive_rcvoob(), unlike the remainder of soreiceve(), is
862  * unable to return an mbuf chain to the caller.
863  */
864 static int
865 soreceive_rcvoob(so, uio, flags)
866 	struct socket *so;
867 	struct uio *uio;
868 	int flags;
869 {
870 	struct protosw *pr = so->so_proto;
871 	struct mbuf *m;
872 	int error;
873 
874 	KASSERT(flags & MSG_OOB, ("soreceive_rcvoob: (flags & MSG_OOB) == 0"));
875 
876 	m = m_get(M_TRYWAIT, MT_DATA);
877 	if (m == NULL)
878 		return (ENOBUFS);
879 	error = (*pr->pr_usrreqs->pru_rcvoob)(so, m, flags & MSG_PEEK);
880 	if (error)
881 		goto bad;
882 	do {
883 #ifdef ZERO_COPY_SOCKETS
884 		if (so_zero_copy_receive) {
885 			int disposable;
886 
887 			if ((m->m_flags & M_EXT)
888 			 && (m->m_ext.ext_type == EXT_DISPOSABLE))
889 				disposable = 1;
890 			else
891 				disposable = 0;
892 
893 			error = uiomoveco(mtod(m, void *),
894 					  min(uio->uio_resid, m->m_len),
895 					  uio, disposable);
896 		} else
897 #endif /* ZERO_COPY_SOCKETS */
898 		error = uiomove(mtod(m, void *),
899 		    (int) min(uio->uio_resid, m->m_len), uio);
900 		m = m_free(m);
901 	} while (uio->uio_resid && error == 0 && m);
902 bad:
903 	if (m != NULL)
904 		m_freem(m);
905 	return (error);
906 }
907 
908 /*
909  * Following replacement or removal of the first mbuf on the first mbuf chain
910  * of a socket buffer, push necessary state changes back into the socket
911  * buffer so that other consumers see the values consistently.  'nextrecord'
912  * is the callers locally stored value of the original value of
913  * sb->sb_mb->m_nextpkt which must be restored when the lead mbuf changes.
914  * NOTE: 'nextrecord' may be NULL.
915  */
916 static __inline void
917 sockbuf_pushsync(struct sockbuf *sb, struct mbuf *nextrecord)
918 {
919 
920 	SOCKBUF_LOCK_ASSERT(sb);
921 	/*
922 	 * First, update for the new value of nextrecord.  If necessary, make
923 	 * it the first record.
924 	 */
925 	if (sb->sb_mb != NULL)
926 		sb->sb_mb->m_nextpkt = nextrecord;
927 	else
928 		sb->sb_mb = nextrecord;
929 
930         /*
931          * Now update any dependent socket buffer fields to reflect the new
932          * state.  This is an expanded inline of SB_EMPTY_FIXUP(), with the
933 	 * addition of a second clause that takes care of the case where
934 	 * sb_mb has been updated, but remains the last record.
935          */
936         if (sb->sb_mb == NULL) {
937                 sb->sb_mbtail = NULL;
938                 sb->sb_lastrecord = NULL;
939         } else if (sb->sb_mb->m_nextpkt == NULL)
940                 sb->sb_lastrecord = sb->sb_mb;
941 }
942 
943 
944 /*
945  * Implement receive operations on a socket.
946  * We depend on the way that records are added to the sockbuf
947  * by sbappend*.  In particular, each record (mbufs linked through m_next)
948  * must begin with an address if the protocol so specifies,
949  * followed by an optional mbuf or mbufs containing ancillary data,
950  * and then zero or more mbufs of data.
951  * In order to avoid blocking network interrupts for the entire time here,
952  * we splx() while doing the actual copy to user space.
953  * Although the sockbuf is locked, new data may still be appended,
954  * and thus we must maintain consistency of the sockbuf during that time.
955  *
956  * The caller may receive the data as a single mbuf chain by supplying
957  * an mbuf **mp0 for use in returning the chain.  The uio is then used
958  * only for the count in uio_resid.
959  */
960 int
961 soreceive(so, psa, uio, mp0, controlp, flagsp)
962 	struct socket *so;
963 	struct sockaddr **psa;
964 	struct uio *uio;
965 	struct mbuf **mp0;
966 	struct mbuf **controlp;
967 	int *flagsp;
968 {
969 	struct mbuf *m, **mp;
970 	int flags, len, error, offset;
971 	struct protosw *pr = so->so_proto;
972 	struct mbuf *nextrecord;
973 	int moff, type = 0;
974 	int orig_resid = uio->uio_resid;
975 
976 	mp = mp0;
977 	if (psa != NULL)
978 		*psa = NULL;
979 	if (controlp != NULL)
980 		*controlp = NULL;
981 	if (flagsp != NULL)
982 		flags = *flagsp &~ MSG_EOR;
983 	else
984 		flags = 0;
985 	if (flags & MSG_OOB)
986 		return (soreceive_rcvoob(so, uio, flags));
987 	if (mp != NULL)
988 		*mp = NULL;
989 	if (so->so_state & SS_ISCONFIRMING && uio->uio_resid)
990 		(*pr->pr_usrreqs->pru_rcvd)(so, 0);
991 
992 	SOCKBUF_LOCK(&so->so_rcv);
993 restart:
994 	SOCKBUF_LOCK_ASSERT(&so->so_rcv);
995 	error = sblock(&so->so_rcv, SBLOCKWAIT(flags));
996 	if (error)
997 		goto out;
998 
999 	m = so->so_rcv.sb_mb;
1000 	/*
1001 	 * If we have less data than requested, block awaiting more
1002 	 * (subject to any timeout) if:
1003 	 *   1. the current count is less than the low water mark, or
1004 	 *   2. MSG_WAITALL is set, and it is possible to do the entire
1005 	 *	receive operation at once if we block (resid <= hiwat).
1006 	 *   3. MSG_DONTWAIT is not set
1007 	 * If MSG_WAITALL is set but resid is larger than the receive buffer,
1008 	 * we have to do the receive in sections, and thus risk returning
1009 	 * a short count if a timeout or signal occurs after we start.
1010 	 */
1011 	if (m == NULL || (((flags & MSG_DONTWAIT) == 0 &&
1012 	    so->so_rcv.sb_cc < uio->uio_resid) &&
1013 	    (so->so_rcv.sb_cc < so->so_rcv.sb_lowat ||
1014 	    ((flags & MSG_WAITALL) && uio->uio_resid <= so->so_rcv.sb_hiwat)) &&
1015 	    m->m_nextpkt == NULL && (pr->pr_flags & PR_ATOMIC) == 0)) {
1016 		KASSERT(m != NULL || !so->so_rcv.sb_cc,
1017 		    ("receive: m == %p so->so_rcv.sb_cc == %u",
1018 		    m, so->so_rcv.sb_cc));
1019 		if (so->so_error) {
1020 			if (m != NULL)
1021 				goto dontblock;
1022 			error = so->so_error;
1023 			if ((flags & MSG_PEEK) == 0)
1024 				so->so_error = 0;
1025 			goto release;
1026 		}
1027 		SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1028 		if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
1029 			if (m)
1030 				goto dontblock;
1031 			else
1032 				goto release;
1033 		}
1034 		for (; m != NULL; m = m->m_next)
1035 			if (m->m_type == MT_OOBDATA  || (m->m_flags & M_EOR)) {
1036 				m = so->so_rcv.sb_mb;
1037 				goto dontblock;
1038 			}
1039 		if ((so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING)) == 0 &&
1040 		    (so->so_proto->pr_flags & PR_CONNREQUIRED)) {
1041 			error = ENOTCONN;
1042 			goto release;
1043 		}
1044 		if (uio->uio_resid == 0)
1045 			goto release;
1046 		if ((so->so_state & SS_NBIO) ||
1047 		    (flags & (MSG_DONTWAIT|MSG_NBIO))) {
1048 			error = EWOULDBLOCK;
1049 			goto release;
1050 		}
1051 		SBLASTRECORDCHK(&so->so_rcv);
1052 		SBLASTMBUFCHK(&so->so_rcv);
1053 		sbunlock(&so->so_rcv);
1054 		error = sbwait(&so->so_rcv);
1055 		if (error)
1056 			goto out;
1057 		goto restart;
1058 	}
1059 dontblock:
1060 	/*
1061 	 * From this point onward, we maintain 'nextrecord' as a cache of the
1062 	 * pointer to the next record in the socket buffer.  We must keep the
1063 	 * various socket buffer pointers and local stack versions of the
1064 	 * pointers in sync, pushing out modifications before dropping the
1065 	 * socket buffer mutex, and re-reading them when picking it up.
1066 	 *
1067 	 * Otherwise, we will race with the network stack appending new data
1068 	 * or records onto the socket buffer by using inconsistent/stale
1069 	 * versions of the field, possibly resulting in socket buffer
1070 	 * corruption.
1071 	 *
1072 	 * By holding the high-level sblock(), we prevent simultaneous
1073 	 * readers from pulling off the front of the socket buffer.
1074 	 */
1075 	SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1076 	if (uio->uio_td)
1077 		uio->uio_td->td_proc->p_stats->p_ru.ru_msgrcv++;
1078 	KASSERT(m == so->so_rcv.sb_mb, ("soreceive: m != so->so_rcv.sb_mb"));
1079 	SBLASTRECORDCHK(&so->so_rcv);
1080 	SBLASTMBUFCHK(&so->so_rcv);
1081 	nextrecord = m->m_nextpkt;
1082 	if (pr->pr_flags & PR_ADDR) {
1083 		KASSERT(m->m_type == MT_SONAME,
1084 		    ("m->m_type == %d", m->m_type));
1085 		orig_resid = 0;
1086 		if (psa != NULL)
1087 			*psa = sodupsockaddr(mtod(m, struct sockaddr *),
1088 			    M_NOWAIT);
1089 		if (flags & MSG_PEEK) {
1090 			m = m->m_next;
1091 		} else {
1092 			sbfree(&so->so_rcv, m);
1093 			so->so_rcv.sb_mb = m_free(m);
1094 			m = so->so_rcv.sb_mb;
1095 			sockbuf_pushsync(&so->so_rcv, nextrecord);
1096 		}
1097 	}
1098 
1099 	/*
1100 	 * Process one or more MT_CONTROL mbufs present before any data mbufs
1101 	 * in the first mbuf chain on the socket buffer.  If MSG_PEEK, we
1102 	 * just copy the data; if !MSG_PEEK, we call into the protocol to
1103 	 * perform externalization (or freeing if controlp == NULL).
1104 	 */
1105 	if (m != NULL && m->m_type == MT_CONTROL) {
1106 		struct mbuf *cm = NULL, *cmn;
1107 		struct mbuf **cme = &cm;
1108 
1109 		do {
1110 			if (flags & MSG_PEEK) {
1111 				if (controlp != NULL) {
1112 					*controlp = m_copy(m, 0, m->m_len);
1113 					controlp = &(*controlp)->m_next;
1114 				}
1115 				m = m->m_next;
1116 			} else {
1117 				sbfree(&so->so_rcv, m);
1118 				so->so_rcv.sb_mb = m->m_next;
1119 				m->m_next = NULL;
1120 				*cme = m;
1121 				cme = &(*cme)->m_next;
1122 				m = so->so_rcv.sb_mb;
1123 			}
1124 		} while (m != NULL && m->m_type == MT_CONTROL);
1125 		if ((flags & MSG_PEEK) == 0)
1126 			sockbuf_pushsync(&so->so_rcv, nextrecord);
1127 		while (cm != NULL) {
1128 			cmn = cm->m_next;
1129 			cm->m_next = NULL;
1130 			if (pr->pr_domain->dom_externalize != NULL) {
1131 				SOCKBUF_UNLOCK(&so->so_rcv);
1132 				error = (*pr->pr_domain->dom_externalize)
1133 				    (cm, controlp);
1134 				SOCKBUF_LOCK(&so->so_rcv);
1135 			} else if (controlp != NULL)
1136 				*controlp = cm;
1137 			else
1138 				m_freem(cm);
1139 			if (controlp != NULL) {
1140 				orig_resid = 0;
1141 				while (*controlp != NULL)
1142 					controlp = &(*controlp)->m_next;
1143 			}
1144 			cm = cmn;
1145 		}
1146 		nextrecord = so->so_rcv.sb_mb->m_nextpkt;
1147 		orig_resid = 0;
1148 	}
1149 	if (m != NULL) {
1150 		if ((flags & MSG_PEEK) == 0) {
1151 			KASSERT(m->m_nextpkt == nextrecord,
1152 			    ("soreceive: post-control, nextrecord !sync"));
1153 			if (nextrecord == NULL) {
1154 				KASSERT(so->so_rcv.sb_mb == m,
1155 				    ("soreceive: post-control, sb_mb!=m"));
1156 				KASSERT(so->so_rcv.sb_lastrecord == m,
1157 				    ("soreceive: post-control, lastrecord!=m"));
1158 			}
1159 		}
1160 		type = m->m_type;
1161 		if (type == MT_OOBDATA)
1162 			flags |= MSG_OOB;
1163 	} else {
1164 		if ((flags & MSG_PEEK) == 0) {
1165 			KASSERT(so->so_rcv.sb_mb == nextrecord,
1166 			    ("soreceive: sb_mb != nextrecord"));
1167 			if (so->so_rcv.sb_mb == NULL) {
1168 				KASSERT(so->so_rcv.sb_lastrecord == NULL,
1169 				    ("soreceive: sb_lastercord != NULL"));
1170 			}
1171 		}
1172 	}
1173 	SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1174 	SBLASTRECORDCHK(&so->so_rcv);
1175 	SBLASTMBUFCHK(&so->so_rcv);
1176 
1177 	/*
1178 	 * Now continue to read any data mbufs off of the head of the socket
1179 	 * buffer until the read request is satisfied.  Note that 'type' is
1180 	 * used to store the type of any mbuf reads that have happened so far
1181 	 * such that soreceive() can stop reading if the type changes, which
1182 	 * causes soreceive() to return only one of regular data and inline
1183 	 * out-of-band data in a single socket receive operation.
1184 	 */
1185 	moff = 0;
1186 	offset = 0;
1187 	while (m != NULL && uio->uio_resid > 0 && error == 0) {
1188 		/*
1189 		 * If the type of mbuf has changed since the last mbuf
1190 		 * examined ('type'), end the receive operation.
1191 	 	 */
1192 		SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1193 		if (m->m_type == MT_OOBDATA) {
1194 			if (type != MT_OOBDATA)
1195 				break;
1196 		} else if (type == MT_OOBDATA)
1197 			break;
1198 		else
1199 		    KASSERT(m->m_type == MT_DATA || m->m_type == MT_HEADER,
1200 			("m->m_type == %d", m->m_type));
1201 		so->so_rcv.sb_state &= ~SBS_RCVATMARK;
1202 		len = uio->uio_resid;
1203 		if (so->so_oobmark && len > so->so_oobmark - offset)
1204 			len = so->so_oobmark - offset;
1205 		if (len > m->m_len - moff)
1206 			len = m->m_len - moff;
1207 		/*
1208 		 * If mp is set, just pass back the mbufs.
1209 		 * Otherwise copy them out via the uio, then free.
1210 		 * Sockbuf must be consistent here (points to current mbuf,
1211 		 * it points to next record) when we drop priority;
1212 		 * we must note any additions to the sockbuf when we
1213 		 * block interrupts again.
1214 		 */
1215 		if (mp == NULL) {
1216 			SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1217 			SBLASTRECORDCHK(&so->so_rcv);
1218 			SBLASTMBUFCHK(&so->so_rcv);
1219 			SOCKBUF_UNLOCK(&so->so_rcv);
1220 #ifdef ZERO_COPY_SOCKETS
1221 			if (so_zero_copy_receive) {
1222 				int disposable;
1223 
1224 				if ((m->m_flags & M_EXT)
1225 				 && (m->m_ext.ext_type == EXT_DISPOSABLE))
1226 					disposable = 1;
1227 				else
1228 					disposable = 0;
1229 
1230 				error = uiomoveco(mtod(m, char *) + moff,
1231 						  (int)len, uio,
1232 						  disposable);
1233 			} else
1234 #endif /* ZERO_COPY_SOCKETS */
1235 			error = uiomove(mtod(m, char *) + moff, (int)len, uio);
1236 			SOCKBUF_LOCK(&so->so_rcv);
1237 			if (error)
1238 				goto release;
1239 		} else
1240 			uio->uio_resid -= len;
1241 		SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1242 		if (len == m->m_len - moff) {
1243 			if (m->m_flags & M_EOR)
1244 				flags |= MSG_EOR;
1245 			if (flags & MSG_PEEK) {
1246 				m = m->m_next;
1247 				moff = 0;
1248 			} else {
1249 				nextrecord = m->m_nextpkt;
1250 				sbfree(&so->so_rcv, m);
1251 				if (mp != NULL) {
1252 					*mp = m;
1253 					mp = &m->m_next;
1254 					so->so_rcv.sb_mb = m = m->m_next;
1255 					*mp = NULL;
1256 				} else {
1257 					so->so_rcv.sb_mb = m_free(m);
1258 					m = so->so_rcv.sb_mb;
1259 				}
1260 				if (m != NULL) {
1261 					m->m_nextpkt = nextrecord;
1262 					if (nextrecord == NULL)
1263 						so->so_rcv.sb_lastrecord = m;
1264 				} else {
1265 					so->so_rcv.sb_mb = nextrecord;
1266 					SB_EMPTY_FIXUP(&so->so_rcv);
1267 				}
1268 				SBLASTRECORDCHK(&so->so_rcv);
1269 				SBLASTMBUFCHK(&so->so_rcv);
1270 			}
1271 		} else {
1272 			if (flags & MSG_PEEK)
1273 				moff += len;
1274 			else {
1275 				if (mp != NULL) {
1276 					int copy_flag;
1277 
1278 					if (flags & MSG_DONTWAIT)
1279 						copy_flag = M_DONTWAIT;
1280 					else
1281 						copy_flag = M_TRYWAIT;
1282 					if (copy_flag == M_TRYWAIT)
1283 						SOCKBUF_UNLOCK(&so->so_rcv);
1284 					*mp = m_copym(m, 0, len, copy_flag);
1285 					if (copy_flag == M_TRYWAIT)
1286 						SOCKBUF_LOCK(&so->so_rcv);
1287  					if (*mp == NULL) {
1288  						/*
1289  						 * m_copym() couldn't allocate an mbuf.
1290 						 * Adjust uio_resid back (it was adjusted
1291 						 * down by len bytes, which we didn't end
1292 						 * up "copying" over).
1293  						 */
1294  						uio->uio_resid += len;
1295  						break;
1296  					}
1297 				}
1298 				m->m_data += len;
1299 				m->m_len -= len;
1300 				so->so_rcv.sb_cc -= len;
1301 			}
1302 		}
1303 		SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1304 		if (so->so_oobmark) {
1305 			if ((flags & MSG_PEEK) == 0) {
1306 				so->so_oobmark -= len;
1307 				if (so->so_oobmark == 0) {
1308 					so->so_rcv.sb_state |= SBS_RCVATMARK;
1309 					break;
1310 				}
1311 			} else {
1312 				offset += len;
1313 				if (offset == so->so_oobmark)
1314 					break;
1315 			}
1316 		}
1317 		if (flags & MSG_EOR)
1318 			break;
1319 		/*
1320 		 * If the MSG_WAITALL flag is set (for non-atomic socket),
1321 		 * we must not quit until "uio->uio_resid == 0" or an error
1322 		 * termination.  If a signal/timeout occurs, return
1323 		 * with a short count but without error.
1324 		 * Keep sockbuf locked against other readers.
1325 		 */
1326 		while (flags & MSG_WAITALL && m == NULL && uio->uio_resid > 0 &&
1327 		    !sosendallatonce(so) && nextrecord == NULL) {
1328 			SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1329 			if (so->so_error || so->so_rcv.sb_state & SBS_CANTRCVMORE)
1330 				break;
1331 			/*
1332 			 * Notify the protocol that some data has been
1333 			 * drained before blocking.
1334 			 */
1335 			if (pr->pr_flags & PR_WANTRCVD && so->so_pcb != NULL) {
1336 				SOCKBUF_UNLOCK(&so->so_rcv);
1337 				(*pr->pr_usrreqs->pru_rcvd)(so, flags);
1338 				SOCKBUF_LOCK(&so->so_rcv);
1339 			}
1340 			SBLASTRECORDCHK(&so->so_rcv);
1341 			SBLASTMBUFCHK(&so->so_rcv);
1342 			error = sbwait(&so->so_rcv);
1343 			if (error)
1344 				goto release;
1345 			m = so->so_rcv.sb_mb;
1346 			if (m != NULL)
1347 				nextrecord = m->m_nextpkt;
1348 		}
1349 	}
1350 
1351 	SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1352 	if (m != NULL && pr->pr_flags & PR_ATOMIC) {
1353 		flags |= MSG_TRUNC;
1354 		if ((flags & MSG_PEEK) == 0)
1355 			(void) sbdroprecord_locked(&so->so_rcv);
1356 	}
1357 	if ((flags & MSG_PEEK) == 0) {
1358 		if (m == NULL) {
1359 			/*
1360 			 * First part is an inline SB_EMPTY_FIXUP().  Second
1361 			 * part makes sure sb_lastrecord is up-to-date if
1362 			 * there is still data in the socket buffer.
1363 			 */
1364 			so->so_rcv.sb_mb = nextrecord;
1365 			if (so->so_rcv.sb_mb == NULL) {
1366 				so->so_rcv.sb_mbtail = NULL;
1367 				so->so_rcv.sb_lastrecord = NULL;
1368 			} else if (nextrecord->m_nextpkt == NULL)
1369 				so->so_rcv.sb_lastrecord = nextrecord;
1370 		}
1371 		SBLASTRECORDCHK(&so->so_rcv);
1372 		SBLASTMBUFCHK(&so->so_rcv);
1373 		/*
1374 		 * If soreceive() is being done from the socket callback, then
1375 		 * don't need to generate ACK to peer to update window, since
1376 		 * ACK will be generated on return to TCP.
1377 		 */
1378 		if (!(flags & MSG_SOCALLBCK) &&
1379 		    (pr->pr_flags & PR_WANTRCVD) && so->so_pcb) {
1380 			SOCKBUF_UNLOCK(&so->so_rcv);
1381 			(*pr->pr_usrreqs->pru_rcvd)(so, flags);
1382 			SOCKBUF_LOCK(&so->so_rcv);
1383 		}
1384 	}
1385 	SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1386 	if (orig_resid == uio->uio_resid && orig_resid &&
1387 	    (flags & MSG_EOR) == 0 && (so->so_rcv.sb_state & SBS_CANTRCVMORE) == 0) {
1388 		sbunlock(&so->so_rcv);
1389 		goto restart;
1390 	}
1391 
1392 	if (flagsp != NULL)
1393 		*flagsp |= flags;
1394 release:
1395 	SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1396 	sbunlock(&so->so_rcv);
1397 out:
1398 	SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1399 	SOCKBUF_UNLOCK(&so->so_rcv);
1400 	return (error);
1401 }
1402 
1403 int
1404 soshutdown(so, how)
1405 	struct socket *so;
1406 	int how;
1407 {
1408 	struct protosw *pr = so->so_proto;
1409 
1410 	if (!(how == SHUT_RD || how == SHUT_WR || how == SHUT_RDWR))
1411 		return (EINVAL);
1412 
1413 	if (how != SHUT_WR)
1414 		sorflush(so);
1415 	if (how != SHUT_RD)
1416 		return ((*pr->pr_usrreqs->pru_shutdown)(so));
1417 	return (0);
1418 }
1419 
1420 void
1421 sorflush(so)
1422 	struct socket *so;
1423 {
1424 	struct sockbuf *sb = &so->so_rcv;
1425 	struct protosw *pr = so->so_proto;
1426 	struct sockbuf asb;
1427 
1428 	/*
1429 	 * XXXRW: This is quite ugly.  Previously, this code made a copy of
1430 	 * the socket buffer, then zero'd the original to clear the buffer
1431 	 * fields.  However, with mutexes in the socket buffer, this causes
1432 	 * problems.  We only clear the zeroable bits of the original;
1433 	 * however, we have to initialize and destroy the mutex in the copy
1434 	 * so that dom_dispose() and sbrelease() can lock t as needed.
1435 	 */
1436 	SOCKBUF_LOCK(sb);
1437 	sb->sb_flags |= SB_NOINTR;
1438 	(void) sblock(sb, M_WAITOK);
1439 	/*
1440 	 * socantrcvmore_locked() drops the socket buffer mutex so that it
1441 	 * can safely perform wakeups.  Re-acquire the mutex before
1442 	 * continuing.
1443 	 */
1444 	socantrcvmore_locked(so);
1445 	SOCKBUF_LOCK(sb);
1446 	sbunlock(sb);
1447 	/*
1448 	 * Invalidate/clear most of the sockbuf structure, but leave
1449 	 * selinfo and mutex data unchanged.
1450 	 */
1451 	bzero(&asb, offsetof(struct sockbuf, sb_startzero));
1452 	bcopy(&sb->sb_startzero, &asb.sb_startzero,
1453 	    sizeof(*sb) - offsetof(struct sockbuf, sb_startzero));
1454 	bzero(&sb->sb_startzero,
1455 	    sizeof(*sb) - offsetof(struct sockbuf, sb_startzero));
1456 	SOCKBUF_UNLOCK(sb);
1457 
1458 	SOCKBUF_LOCK_INIT(&asb, "so_rcv");
1459 	if (pr->pr_flags & PR_RIGHTS && pr->pr_domain->dom_dispose != NULL)
1460 		(*pr->pr_domain->dom_dispose)(asb.sb_mb);
1461 	sbrelease(&asb, so);
1462 	SOCKBUF_LOCK_DESTROY(&asb);
1463 }
1464 
1465 #ifdef INET
1466 static int
1467 do_setopt_accept_filter(so, sopt)
1468 	struct	socket *so;
1469 	struct	sockopt *sopt;
1470 {
1471 	struct accept_filter_arg	*afap;
1472 	struct accept_filter	*afp;
1473 	struct so_accf	*newaf;
1474 	int	error = 0;
1475 
1476 	newaf = NULL;
1477 	afap = NULL;
1478 
1479 	/*
1480 	 * XXXRW: Configuring accept filters should be an atomic test-and-set
1481 	 * operation to prevent races during setup and attach.  There may be
1482 	 * more general issues of racing and ordering here that are not yet
1483 	 * addressed by locking.
1484 	 */
1485 	/* do not set/remove accept filters on non listen sockets */
1486 	SOCK_LOCK(so);
1487 	if ((so->so_options & SO_ACCEPTCONN) == 0) {
1488 		SOCK_UNLOCK(so);
1489 		return (EINVAL);
1490 	}
1491 
1492 	/* removing the filter */
1493 	if (sopt == NULL) {
1494 		if (so->so_accf != NULL) {
1495 			struct so_accf *af = so->so_accf;
1496 			if (af->so_accept_filter != NULL &&
1497 				af->so_accept_filter->accf_destroy != NULL) {
1498 				af->so_accept_filter->accf_destroy(so);
1499 			}
1500 			if (af->so_accept_filter_str != NULL) {
1501 				FREE(af->so_accept_filter_str, M_ACCF);
1502 			}
1503 			FREE(af, M_ACCF);
1504 			so->so_accf = NULL;
1505 		}
1506 		so->so_options &= ~SO_ACCEPTFILTER;
1507 		SOCK_UNLOCK(so);
1508 		return (0);
1509 	}
1510 	SOCK_UNLOCK(so);
1511 
1512 	/*-
1513 	 * Adding a filter.
1514 	 *
1515 	 * Do memory allocation, copyin, and filter lookup now while we're
1516 	 * not holding any locks.  Avoids sleeping with a mutex, as well as
1517 	 * introducing a lock order between accept filter locks and socket
1518 	 * locks here.
1519 	 */
1520 	MALLOC(afap, struct accept_filter_arg *, sizeof(*afap), M_TEMP,
1521 	    M_WAITOK);
1522 	/* don't put large objects on the kernel stack */
1523 	error = sooptcopyin(sopt, afap, sizeof *afap, sizeof *afap);
1524 	afap->af_name[sizeof(afap->af_name)-1] = '\0';
1525 	afap->af_arg[sizeof(afap->af_arg)-1] = '\0';
1526 	if (error) {
1527 		FREE(afap, M_TEMP);
1528 		return (error);
1529 	}
1530 	afp = accept_filt_get(afap->af_name);
1531 	if (afp == NULL) {
1532 		FREE(afap, M_TEMP);
1533 		return (ENOENT);
1534 	}
1535 
1536 	/*
1537 	 * Allocate the new accept filter instance storage.  We may have to
1538 	 * free it again later if we fail to attach it.  If attached
1539 	 * properly, 'newaf' is NULLed to avoid a free() while in use.
1540 	 */
1541 	MALLOC(newaf, struct so_accf *, sizeof(*newaf), M_ACCF, M_WAITOK |
1542 	    M_ZERO);
1543 	if (afp->accf_create != NULL && afap->af_name[0] != '\0') {
1544 		int len = strlen(afap->af_name) + 1;
1545 		MALLOC(newaf->so_accept_filter_str, char *, len, M_ACCF,
1546 		    M_WAITOK);
1547 		strcpy(newaf->so_accept_filter_str, afap->af_name);
1548 	}
1549 
1550 	SOCK_LOCK(so);
1551 	/* must remove previous filter first */
1552 	if (so->so_accf != NULL) {
1553 		error = EINVAL;
1554 		goto out;
1555 	}
1556 	/*
1557 	 * Invoke the accf_create() method of the filter if required.
1558 	 * XXXRW: the socket mutex is held over this call, so the create
1559 	 * method cannot block.  This may be something we have to change, but
1560 	 * it would require addressing possible races.
1561 	 */
1562 	if (afp->accf_create != NULL) {
1563 		newaf->so_accept_filter_arg =
1564 		    afp->accf_create(so, afap->af_arg);
1565 		if (newaf->so_accept_filter_arg == NULL) {
1566 			error = EINVAL;
1567 			goto out;
1568 		}
1569 	}
1570 	newaf->so_accept_filter = afp;
1571 	so->so_accf = newaf;
1572 	so->so_options |= SO_ACCEPTFILTER;
1573 	newaf = NULL;
1574 out:
1575 	SOCK_UNLOCK(so);
1576 	if (newaf != NULL) {
1577 		if (newaf->so_accept_filter_str != NULL)
1578 			FREE(newaf->so_accept_filter_str, M_ACCF);
1579 		FREE(newaf, M_ACCF);
1580 	}
1581 	if (afap != NULL)
1582 		FREE(afap, M_TEMP);
1583 	return (error);
1584 }
1585 #endif /* INET */
1586 
1587 /*
1588  * Perhaps this routine, and sooptcopyout(), below, ought to come in
1589  * an additional variant to handle the case where the option value needs
1590  * to be some kind of integer, but not a specific size.
1591  * In addition to their use here, these functions are also called by the
1592  * protocol-level pr_ctloutput() routines.
1593  */
1594 int
1595 sooptcopyin(sopt, buf, len, minlen)
1596 	struct	sockopt *sopt;
1597 	void	*buf;
1598 	size_t	len;
1599 	size_t	minlen;
1600 {
1601 	size_t	valsize;
1602 
1603 	/*
1604 	 * If the user gives us more than we wanted, we ignore it,
1605 	 * but if we don't get the minimum length the caller
1606 	 * wants, we return EINVAL.  On success, sopt->sopt_valsize
1607 	 * is set to however much we actually retrieved.
1608 	 */
1609 	if ((valsize = sopt->sopt_valsize) < minlen)
1610 		return EINVAL;
1611 	if (valsize > len)
1612 		sopt->sopt_valsize = valsize = len;
1613 
1614 	if (sopt->sopt_td != NULL)
1615 		return (copyin(sopt->sopt_val, buf, valsize));
1616 
1617 	bcopy(sopt->sopt_val, buf, valsize);
1618 	return 0;
1619 }
1620 
1621 /*
1622  * Kernel version of setsockopt(2)/
1623  * XXX: optlen is size_t, not socklen_t
1624  */
1625 int
1626 so_setsockopt(struct socket *so, int level, int optname, void *optval,
1627     size_t optlen)
1628 {
1629 	struct sockopt sopt;
1630 
1631 	sopt.sopt_level = level;
1632 	sopt.sopt_name = optname;
1633 	sopt.sopt_dir = SOPT_SET;
1634 	sopt.sopt_val = optval;
1635 	sopt.sopt_valsize = optlen;
1636 	sopt.sopt_td = NULL;
1637 	return (sosetopt(so, &sopt));
1638 }
1639 
1640 int
1641 sosetopt(so, sopt)
1642 	struct socket *so;
1643 	struct sockopt *sopt;
1644 {
1645 	int	error, optval;
1646 	struct	linger l;
1647 	struct	timeval tv;
1648 	u_long  val;
1649 #ifdef MAC
1650 	struct mac extmac;
1651 #endif
1652 
1653 	error = 0;
1654 	if (sopt->sopt_level != SOL_SOCKET) {
1655 		if (so->so_proto && so->so_proto->pr_ctloutput)
1656 			return ((*so->so_proto->pr_ctloutput)
1657 				  (so, sopt));
1658 		error = ENOPROTOOPT;
1659 	} else {
1660 		switch (sopt->sopt_name) {
1661 #ifdef INET
1662 		case SO_ACCEPTFILTER:
1663 			error = do_setopt_accept_filter(so, sopt);
1664 			if (error)
1665 				goto bad;
1666 			break;
1667 #endif
1668 		case SO_LINGER:
1669 			error = sooptcopyin(sopt, &l, sizeof l, sizeof l);
1670 			if (error)
1671 				goto bad;
1672 
1673 			SOCK_LOCK(so);
1674 			so->so_linger = l.l_linger;
1675 			if (l.l_onoff)
1676 				so->so_options |= SO_LINGER;
1677 			else
1678 				so->so_options &= ~SO_LINGER;
1679 			SOCK_UNLOCK(so);
1680 			break;
1681 
1682 		case SO_DEBUG:
1683 		case SO_KEEPALIVE:
1684 		case SO_DONTROUTE:
1685 		case SO_USELOOPBACK:
1686 		case SO_BROADCAST:
1687 		case SO_REUSEADDR:
1688 		case SO_REUSEPORT:
1689 		case SO_OOBINLINE:
1690 		case SO_TIMESTAMP:
1691 		case SO_BINTIME:
1692 		case SO_NOSIGPIPE:
1693 			error = sooptcopyin(sopt, &optval, sizeof optval,
1694 					    sizeof optval);
1695 			if (error)
1696 				goto bad;
1697 			SOCK_LOCK(so);
1698 			if (optval)
1699 				so->so_options |= sopt->sopt_name;
1700 			else
1701 				so->so_options &= ~sopt->sopt_name;
1702 			SOCK_UNLOCK(so);
1703 			break;
1704 
1705 		case SO_SNDBUF:
1706 		case SO_RCVBUF:
1707 		case SO_SNDLOWAT:
1708 		case SO_RCVLOWAT:
1709 			error = sooptcopyin(sopt, &optval, sizeof optval,
1710 					    sizeof optval);
1711 			if (error)
1712 				goto bad;
1713 
1714 			/*
1715 			 * Values < 1 make no sense for any of these
1716 			 * options, so disallow them.
1717 			 */
1718 			if (optval < 1) {
1719 				error = EINVAL;
1720 				goto bad;
1721 			}
1722 
1723 			switch (sopt->sopt_name) {
1724 			case SO_SNDBUF:
1725 			case SO_RCVBUF:
1726 				if (sbreserve(sopt->sopt_name == SO_SNDBUF ?
1727 				    &so->so_snd : &so->so_rcv, (u_long)optval,
1728 				    so, curthread) == 0) {
1729 					error = ENOBUFS;
1730 					goto bad;
1731 				}
1732 				break;
1733 
1734 			/*
1735 			 * Make sure the low-water is never greater than
1736 			 * the high-water.
1737 			 */
1738 			case SO_SNDLOWAT:
1739 				SOCKBUF_LOCK(&so->so_snd);
1740 				so->so_snd.sb_lowat =
1741 				    (optval > so->so_snd.sb_hiwat) ?
1742 				    so->so_snd.sb_hiwat : optval;
1743 				SOCKBUF_UNLOCK(&so->so_snd);
1744 				break;
1745 			case SO_RCVLOWAT:
1746 				SOCKBUF_LOCK(&so->so_rcv);
1747 				so->so_rcv.sb_lowat =
1748 				    (optval > so->so_rcv.sb_hiwat) ?
1749 				    so->so_rcv.sb_hiwat : optval;
1750 				SOCKBUF_UNLOCK(&so->so_rcv);
1751 				break;
1752 			}
1753 			break;
1754 
1755 		case SO_SNDTIMEO:
1756 		case SO_RCVTIMEO:
1757 			error = sooptcopyin(sopt, &tv, sizeof tv,
1758 					    sizeof tv);
1759 			if (error)
1760 				goto bad;
1761 
1762 			/* assert(hz > 0); */
1763 			if (tv.tv_sec < 0 || tv.tv_sec > INT_MAX / hz ||
1764 			    tv.tv_usec < 0 || tv.tv_usec >= 1000000) {
1765 				error = EDOM;
1766 				goto bad;
1767 			}
1768 			/* assert(tick > 0); */
1769 			/* assert(ULONG_MAX - INT_MAX >= 1000000); */
1770 			val = (u_long)(tv.tv_sec * hz) + tv.tv_usec / tick;
1771 			if (val > INT_MAX) {
1772 				error = EDOM;
1773 				goto bad;
1774 			}
1775 			if (val == 0 && tv.tv_usec != 0)
1776 				val = 1;
1777 
1778 			switch (sopt->sopt_name) {
1779 			case SO_SNDTIMEO:
1780 				so->so_snd.sb_timeo = val;
1781 				break;
1782 			case SO_RCVTIMEO:
1783 				so->so_rcv.sb_timeo = val;
1784 				break;
1785 			}
1786 			break;
1787 		case SO_LABEL:
1788 #ifdef MAC
1789 			error = sooptcopyin(sopt, &extmac, sizeof extmac,
1790 			    sizeof extmac);
1791 			if (error)
1792 				goto bad;
1793 			error = mac_setsockopt_label(sopt->sopt_td->td_ucred,
1794 			    so, &extmac);
1795 #else
1796 			error = EOPNOTSUPP;
1797 #endif
1798 			break;
1799 		default:
1800 			error = ENOPROTOOPT;
1801 			break;
1802 		}
1803 		if (error == 0 && so->so_proto != NULL &&
1804 		    so->so_proto->pr_ctloutput != NULL) {
1805 			(void) ((*so->so_proto->pr_ctloutput)
1806 				  (so, sopt));
1807 		}
1808 	}
1809 bad:
1810 	return (error);
1811 }
1812 
1813 /* Helper routine for getsockopt */
1814 int
1815 sooptcopyout(struct sockopt *sopt, const void *buf, size_t len)
1816 {
1817 	int	error;
1818 	size_t	valsize;
1819 
1820 	error = 0;
1821 
1822 	/*
1823 	 * Documented get behavior is that we always return a value,
1824 	 * possibly truncated to fit in the user's buffer.
1825 	 * Traditional behavior is that we always tell the user
1826 	 * precisely how much we copied, rather than something useful
1827 	 * like the total amount we had available for her.
1828 	 * Note that this interface is not idempotent; the entire answer must
1829 	 * generated ahead of time.
1830 	 */
1831 	valsize = min(len, sopt->sopt_valsize);
1832 	sopt->sopt_valsize = valsize;
1833 	if (sopt->sopt_val != NULL) {
1834 		if (sopt->sopt_td != NULL)
1835 			error = copyout(buf, sopt->sopt_val, valsize);
1836 		else
1837 			bcopy(buf, sopt->sopt_val, valsize);
1838 	}
1839 	return error;
1840 }
1841 
1842 int
1843 sogetopt(so, sopt)
1844 	struct socket *so;
1845 	struct sockopt *sopt;
1846 {
1847 	int	error, optval;
1848 	struct	linger l;
1849 	struct	timeval tv;
1850 #ifdef INET
1851 	struct accept_filter_arg *afap;
1852 #endif
1853 #ifdef MAC
1854 	struct mac extmac;
1855 #endif
1856 
1857 	error = 0;
1858 	if (sopt->sopt_level != SOL_SOCKET) {
1859 		if (so->so_proto && so->so_proto->pr_ctloutput) {
1860 			return ((*so->so_proto->pr_ctloutput)
1861 				  (so, sopt));
1862 		} else
1863 			return (ENOPROTOOPT);
1864 	} else {
1865 		switch (sopt->sopt_name) {
1866 #ifdef INET
1867 		case SO_ACCEPTFILTER:
1868 			/* Unlocked read. */
1869 			if ((so->so_options & SO_ACCEPTCONN) == 0)
1870 				return (EINVAL);
1871 			MALLOC(afap, struct accept_filter_arg *, sizeof(*afap),
1872 				M_TEMP, M_WAITOK | M_ZERO);
1873 			SOCK_LOCK(so);
1874 			if ((so->so_options & SO_ACCEPTFILTER) != 0) {
1875 				strcpy(afap->af_name, so->so_accf->so_accept_filter->accf_name);
1876 				if (so->so_accf->so_accept_filter_str != NULL)
1877 					strcpy(afap->af_arg, so->so_accf->so_accept_filter_str);
1878 			}
1879 			SOCK_UNLOCK(so);
1880 			error = sooptcopyout(sopt, afap, sizeof(*afap));
1881 			FREE(afap, M_TEMP);
1882 			break;
1883 #endif
1884 
1885 		case SO_LINGER:
1886 			SOCK_LOCK(so);
1887 			l.l_onoff = so->so_options & SO_LINGER;
1888 			l.l_linger = so->so_linger;
1889 			SOCK_UNLOCK(so);
1890 			error = sooptcopyout(sopt, &l, sizeof l);
1891 			break;
1892 
1893 		case SO_USELOOPBACK:
1894 		case SO_DONTROUTE:
1895 		case SO_DEBUG:
1896 		case SO_KEEPALIVE:
1897 		case SO_REUSEADDR:
1898 		case SO_REUSEPORT:
1899 		case SO_BROADCAST:
1900 		case SO_OOBINLINE:
1901 		case SO_TIMESTAMP:
1902 		case SO_BINTIME:
1903 		case SO_NOSIGPIPE:
1904 			optval = so->so_options & sopt->sopt_name;
1905 integer:
1906 			error = sooptcopyout(sopt, &optval, sizeof optval);
1907 			break;
1908 
1909 		case SO_TYPE:
1910 			optval = so->so_type;
1911 			goto integer;
1912 
1913 		case SO_ERROR:
1914 			optval = so->so_error;
1915 			so->so_error = 0;
1916 			goto integer;
1917 
1918 		case SO_SNDBUF:
1919 			optval = so->so_snd.sb_hiwat;
1920 			goto integer;
1921 
1922 		case SO_RCVBUF:
1923 			optval = so->so_rcv.sb_hiwat;
1924 			goto integer;
1925 
1926 		case SO_SNDLOWAT:
1927 			optval = so->so_snd.sb_lowat;
1928 			goto integer;
1929 
1930 		case SO_RCVLOWAT:
1931 			optval = so->so_rcv.sb_lowat;
1932 			goto integer;
1933 
1934 		case SO_SNDTIMEO:
1935 		case SO_RCVTIMEO:
1936 			optval = (sopt->sopt_name == SO_SNDTIMEO ?
1937 				  so->so_snd.sb_timeo : so->so_rcv.sb_timeo);
1938 
1939 			tv.tv_sec = optval / hz;
1940 			tv.tv_usec = (optval % hz) * tick;
1941 			error = sooptcopyout(sopt, &tv, sizeof tv);
1942 			break;
1943 		case SO_LABEL:
1944 #ifdef MAC
1945 			error = sooptcopyin(sopt, &extmac, sizeof(extmac),
1946 			    sizeof(extmac));
1947 			if (error)
1948 				return (error);
1949 			error = mac_getsockopt_label(sopt->sopt_td->td_ucred,
1950 			    so, &extmac);
1951 			if (error)
1952 				return (error);
1953 			error = sooptcopyout(sopt, &extmac, sizeof extmac);
1954 #else
1955 			error = EOPNOTSUPP;
1956 #endif
1957 			break;
1958 		case SO_PEERLABEL:
1959 #ifdef MAC
1960 			error = sooptcopyin(sopt, &extmac, sizeof(extmac),
1961 			    sizeof(extmac));
1962 			if (error)
1963 				return (error);
1964 			error = mac_getsockopt_peerlabel(
1965 			    sopt->sopt_td->td_ucred, so, &extmac);
1966 			if (error)
1967 				return (error);
1968 			error = sooptcopyout(sopt, &extmac, sizeof extmac);
1969 #else
1970 			error = EOPNOTSUPP;
1971 #endif
1972 			break;
1973 		default:
1974 			error = ENOPROTOOPT;
1975 			break;
1976 		}
1977 		return (error);
1978 	}
1979 }
1980 
1981 /* XXX; prepare mbuf for (__FreeBSD__ < 3) routines. */
1982 int
1983 soopt_getm(struct sockopt *sopt, struct mbuf **mp)
1984 {
1985 	struct mbuf *m, *m_prev;
1986 	int sopt_size = sopt->sopt_valsize;
1987 
1988 	MGET(m, sopt->sopt_td ? M_TRYWAIT : M_DONTWAIT, MT_DATA);
1989 	if (m == NULL)
1990 		return ENOBUFS;
1991 	if (sopt_size > MLEN) {
1992 		MCLGET(m, sopt->sopt_td ? M_TRYWAIT : M_DONTWAIT);
1993 		if ((m->m_flags & M_EXT) == 0) {
1994 			m_free(m);
1995 			return ENOBUFS;
1996 		}
1997 		m->m_len = min(MCLBYTES, sopt_size);
1998 	} else {
1999 		m->m_len = min(MLEN, sopt_size);
2000 	}
2001 	sopt_size -= m->m_len;
2002 	*mp = m;
2003 	m_prev = m;
2004 
2005 	while (sopt_size) {
2006 		MGET(m, sopt->sopt_td ? M_TRYWAIT : M_DONTWAIT, MT_DATA);
2007 		if (m == NULL) {
2008 			m_freem(*mp);
2009 			return ENOBUFS;
2010 		}
2011 		if (sopt_size > MLEN) {
2012 			MCLGET(m, sopt->sopt_td != NULL ? M_TRYWAIT :
2013 			    M_DONTWAIT);
2014 			if ((m->m_flags & M_EXT) == 0) {
2015 				m_freem(m);
2016 				m_freem(*mp);
2017 				return ENOBUFS;
2018 			}
2019 			m->m_len = min(MCLBYTES, sopt_size);
2020 		} else {
2021 			m->m_len = min(MLEN, sopt_size);
2022 		}
2023 		sopt_size -= m->m_len;
2024 		m_prev->m_next = m;
2025 		m_prev = m;
2026 	}
2027 	return 0;
2028 }
2029 
2030 /* XXX; copyin sopt data into mbuf chain for (__FreeBSD__ < 3) routines. */
2031 int
2032 soopt_mcopyin(struct sockopt *sopt, struct mbuf *m)
2033 {
2034 	struct mbuf *m0 = m;
2035 
2036 	if (sopt->sopt_val == NULL)
2037 		return 0;
2038 	while (m != NULL && sopt->sopt_valsize >= m->m_len) {
2039 		if (sopt->sopt_td != NULL) {
2040 			int error;
2041 
2042 			error = copyin(sopt->sopt_val, mtod(m, char *),
2043 				       m->m_len);
2044 			if (error != 0) {
2045 				m_freem(m0);
2046 				return(error);
2047 			}
2048 		} else
2049 			bcopy(sopt->sopt_val, mtod(m, char *), m->m_len);
2050 		sopt->sopt_valsize -= m->m_len;
2051 		sopt->sopt_val = (char *)sopt->sopt_val + m->m_len;
2052 		m = m->m_next;
2053 	}
2054 	if (m != NULL) /* should be allocated enoughly at ip6_sooptmcopyin() */
2055 		panic("ip6_sooptmcopyin");
2056 	return 0;
2057 }
2058 
2059 /* XXX; copyout mbuf chain data into soopt for (__FreeBSD__ < 3) routines. */
2060 int
2061 soopt_mcopyout(struct sockopt *sopt, struct mbuf *m)
2062 {
2063 	struct mbuf *m0 = m;
2064 	size_t valsize = 0;
2065 
2066 	if (sopt->sopt_val == NULL)
2067 		return 0;
2068 	while (m != NULL && sopt->sopt_valsize >= m->m_len) {
2069 		if (sopt->sopt_td != NULL) {
2070 			int error;
2071 
2072 			error = copyout(mtod(m, char *), sopt->sopt_val,
2073 				       m->m_len);
2074 			if (error != 0) {
2075 				m_freem(m0);
2076 				return(error);
2077 			}
2078 		} else
2079 			bcopy(mtod(m, char *), sopt->sopt_val, m->m_len);
2080 	       sopt->sopt_valsize -= m->m_len;
2081 	       sopt->sopt_val = (char *)sopt->sopt_val + m->m_len;
2082 	       valsize += m->m_len;
2083 	       m = m->m_next;
2084 	}
2085 	if (m != NULL) {
2086 		/* enough soopt buffer should be given from user-land */
2087 		m_freem(m0);
2088 		return(EINVAL);
2089 	}
2090 	sopt->sopt_valsize = valsize;
2091 	return 0;
2092 }
2093 
2094 void
2095 sohasoutofband(so)
2096 	struct socket *so;
2097 {
2098 	if (so->so_sigio != NULL)
2099 		pgsigio(&so->so_sigio, SIGURG, 0);
2100 	selwakeuppri(&so->so_rcv.sb_sel, PSOCK);
2101 }
2102 
2103 int
2104 sopoll(struct socket *so, int events, struct ucred *active_cred,
2105     struct thread *td)
2106 {
2107 	int revents = 0;
2108 
2109 	SOCKBUF_LOCK(&so->so_snd);
2110 	SOCKBUF_LOCK(&so->so_rcv);
2111 	if (events & (POLLIN | POLLRDNORM))
2112 		if (soreadable(so))
2113 			revents |= events & (POLLIN | POLLRDNORM);
2114 
2115 	if (events & POLLINIGNEOF)
2116 		if (so->so_rcv.sb_cc >= so->so_rcv.sb_lowat ||
2117 		    !TAILQ_EMPTY(&so->so_comp) || so->so_error)
2118 			revents |= POLLINIGNEOF;
2119 
2120 	if (events & (POLLOUT | POLLWRNORM))
2121 		if (sowriteable(so))
2122 			revents |= events & (POLLOUT | POLLWRNORM);
2123 
2124 	if (events & (POLLPRI | POLLRDBAND))
2125 		if (so->so_oobmark || (so->so_rcv.sb_state & SBS_RCVATMARK))
2126 			revents |= events & (POLLPRI | POLLRDBAND);
2127 
2128 	if (revents == 0) {
2129 		if (events &
2130 		    (POLLIN | POLLINIGNEOF | POLLPRI | POLLRDNORM |
2131 		     POLLRDBAND)) {
2132 			selrecord(td, &so->so_rcv.sb_sel);
2133 			so->so_rcv.sb_flags |= SB_SEL;
2134 		}
2135 
2136 		if (events & (POLLOUT | POLLWRNORM)) {
2137 			selrecord(td, &so->so_snd.sb_sel);
2138 			so->so_snd.sb_flags |= SB_SEL;
2139 		}
2140 	}
2141 
2142 	SOCKBUF_UNLOCK(&so->so_rcv);
2143 	SOCKBUF_UNLOCK(&so->so_snd);
2144 	return (revents);
2145 }
2146 
2147 int
2148 soo_kqfilter(struct file *fp, struct knote *kn)
2149 {
2150 	struct socket *so = kn->kn_fp->f_data;
2151 	struct sockbuf *sb;
2152 
2153 	switch (kn->kn_filter) {
2154 	case EVFILT_READ:
2155 		if (so->so_options & SO_ACCEPTCONN)
2156 			kn->kn_fop = &solisten_filtops;
2157 		else
2158 			kn->kn_fop = &soread_filtops;
2159 		sb = &so->so_rcv;
2160 		break;
2161 	case EVFILT_WRITE:
2162 		kn->kn_fop = &sowrite_filtops;
2163 		sb = &so->so_snd;
2164 		break;
2165 	default:
2166 		return (EINVAL);
2167 	}
2168 
2169 	SOCKBUF_LOCK(sb);
2170 	knlist_add(&sb->sb_sel.si_note, kn, 1);
2171 	sb->sb_flags |= SB_KNOTE;
2172 	SOCKBUF_UNLOCK(sb);
2173 	return (0);
2174 }
2175 
2176 static void
2177 filt_sordetach(struct knote *kn)
2178 {
2179 	struct socket *so = kn->kn_fp->f_data;
2180 
2181 	SOCKBUF_LOCK(&so->so_rcv);
2182 	knlist_remove(&so->so_rcv.sb_sel.si_note, kn, 1);
2183 	if (knlist_empty(&so->so_rcv.sb_sel.si_note))
2184 		so->so_rcv.sb_flags &= ~SB_KNOTE;
2185 	SOCKBUF_UNLOCK(&so->so_rcv);
2186 }
2187 
2188 /*ARGSUSED*/
2189 static int
2190 filt_soread(struct knote *kn, long hint)
2191 {
2192 	struct socket *so;
2193 
2194 	so = kn->kn_fp->f_data;
2195 	SOCKBUF_LOCK_ASSERT(&so->so_rcv);
2196 
2197 	kn->kn_data = so->so_rcv.sb_cc - so->so_rcv.sb_ctl;
2198 	if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
2199 		kn->kn_flags |= EV_EOF;
2200 		kn->kn_fflags = so->so_error;
2201 		return (1);
2202 	} else if (so->so_error)	/* temporary udp error */
2203 		return (1);
2204 	else if (kn->kn_sfflags & NOTE_LOWAT)
2205 		return (kn->kn_data >= kn->kn_sdata);
2206 	else
2207 		return (so->so_rcv.sb_cc >= so->so_rcv.sb_lowat);
2208 }
2209 
2210 static void
2211 filt_sowdetach(struct knote *kn)
2212 {
2213 	struct socket *so = kn->kn_fp->f_data;
2214 
2215 	SOCKBUF_LOCK(&so->so_snd);
2216 	knlist_remove(&so->so_snd.sb_sel.si_note, kn, 1);
2217 	if (knlist_empty(&so->so_snd.sb_sel.si_note))
2218 		so->so_snd.sb_flags &= ~SB_KNOTE;
2219 	SOCKBUF_UNLOCK(&so->so_snd);
2220 }
2221 
2222 /*ARGSUSED*/
2223 static int
2224 filt_sowrite(struct knote *kn, long hint)
2225 {
2226 	struct socket *so;
2227 
2228 	so = kn->kn_fp->f_data;
2229 	SOCKBUF_LOCK_ASSERT(&so->so_snd);
2230 	kn->kn_data = sbspace(&so->so_snd);
2231 	if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
2232 		kn->kn_flags |= EV_EOF;
2233 		kn->kn_fflags = so->so_error;
2234 		return (1);
2235 	} else if (so->so_error)	/* temporary udp error */
2236 		return (1);
2237 	else if (((so->so_state & SS_ISCONNECTED) == 0) &&
2238 	    (so->so_proto->pr_flags & PR_CONNREQUIRED))
2239 		return (0);
2240 	else if (kn->kn_sfflags & NOTE_LOWAT)
2241 		return (kn->kn_data >= kn->kn_sdata);
2242 	else
2243 		return (kn->kn_data >= so->so_snd.sb_lowat);
2244 }
2245 
2246 /*ARGSUSED*/
2247 static int
2248 filt_solisten(struct knote *kn, long hint)
2249 {
2250 	struct socket *so = kn->kn_fp->f_data;
2251 
2252 	kn->kn_data = so->so_qlen;
2253 	return (! TAILQ_EMPTY(&so->so_comp));
2254 }
2255 
2256 int
2257 socheckuid(struct socket *so, uid_t uid)
2258 {
2259 
2260 	if (so == NULL)
2261 		return (EPERM);
2262 	if (so->so_cred->cr_uid == uid)
2263 		return (0);
2264 	return (EPERM);
2265 }
2266