xref: /freebsd/sys/kern/uipc_socket.c (revision 7660b554bc59a07be0431c17e0e33815818baa69)
1 /*
2  * Copyright (c) 1982, 1986, 1988, 1990, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. All advertising materials mentioning features or use of this software
14  *    must display the following acknowledgement:
15  *	This product includes software developed by the University of
16  *	California, Berkeley and its contributors.
17  * 4. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  *	@(#)uipc_socket.c	8.3 (Berkeley) 4/15/94
34  */
35 
36 #include <sys/cdefs.h>
37 __FBSDID("$FreeBSD$");
38 
39 #include "opt_inet.h"
40 #include "opt_mac.h"
41 #include "opt_zero.h"
42 
43 #include <sys/param.h>
44 #include <sys/systm.h>
45 #include <sys/fcntl.h>
46 #include <sys/limits.h>
47 #include <sys/lock.h>
48 #include <sys/mac.h>
49 #include <sys/malloc.h>
50 #include <sys/mbuf.h>
51 #include <sys/mutex.h>
52 #include <sys/domain.h>
53 #include <sys/file.h>			/* for struct knote */
54 #include <sys/kernel.h>
55 #include <sys/event.h>
56 #include <sys/poll.h>
57 #include <sys/proc.h>
58 #include <sys/protosw.h>
59 #include <sys/socket.h>
60 #include <sys/socketvar.h>
61 #include <sys/resourcevar.h>
62 #include <sys/signalvar.h>
63 #include <sys/sysctl.h>
64 #include <sys/uio.h>
65 #include <sys/jail.h>
66 
67 #include <vm/uma.h>
68 
69 
70 #ifdef INET
71 static int	 do_setopt_accept_filter(struct socket *so, struct sockopt *sopt);
72 #endif
73 
74 static void	filt_sordetach(struct knote *kn);
75 static int	filt_soread(struct knote *kn, long hint);
76 static void	filt_sowdetach(struct knote *kn);
77 static int	filt_sowrite(struct knote *kn, long hint);
78 static int	filt_solisten(struct knote *kn, long hint);
79 
80 static struct filterops solisten_filtops =
81 	{ 1, NULL, filt_sordetach, filt_solisten };
82 static struct filterops soread_filtops =
83 	{ 1, NULL, filt_sordetach, filt_soread };
84 static struct filterops sowrite_filtops =
85 	{ 1, NULL, filt_sowdetach, filt_sowrite };
86 
87 uma_zone_t socket_zone;
88 so_gen_t	so_gencnt;	/* generation count for sockets */
89 
90 MALLOC_DEFINE(M_SONAME, "soname", "socket name");
91 MALLOC_DEFINE(M_PCB, "pcb", "protocol control block");
92 
93 SYSCTL_DECL(_kern_ipc);
94 
95 static int somaxconn = SOMAXCONN;
96 SYSCTL_INT(_kern_ipc, KIPC_SOMAXCONN, somaxconn, CTLFLAG_RW,
97     &somaxconn, 0, "Maximum pending socket connection queue size");
98 static int numopensockets;
99 SYSCTL_INT(_kern_ipc, OID_AUTO, numopensockets, CTLFLAG_RD,
100     &numopensockets, 0, "Number of open sockets");
101 #ifdef ZERO_COPY_SOCKETS
102 /* These aren't static because they're used in other files. */
103 int so_zero_copy_send = 1;
104 int so_zero_copy_receive = 1;
105 SYSCTL_NODE(_kern_ipc, OID_AUTO, zero_copy, CTLFLAG_RD, 0,
106     "Zero copy controls");
107 SYSCTL_INT(_kern_ipc_zero_copy, OID_AUTO, receive, CTLFLAG_RW,
108     &so_zero_copy_receive, 0, "Enable zero copy receive");
109 SYSCTL_INT(_kern_ipc_zero_copy, OID_AUTO, send, CTLFLAG_RW,
110     &so_zero_copy_send, 0, "Enable zero copy send");
111 #endif /* ZERO_COPY_SOCKETS */
112 
113 
114 /*
115  * Socket operation routines.
116  * These routines are called by the routines in
117  * sys_socket.c or from a system process, and
118  * implement the semantics of socket operations by
119  * switching out to the protocol specific routines.
120  */
121 
122 /*
123  * Get a socket structure from our zone, and initialize it.
124  * Note that it would probably be better to allocate socket
125  * and PCB at the same time, but I'm not convinced that all
126  * the protocols can be easily modified to do this.
127  *
128  * soalloc() returns a socket with a ref count of 0.
129  */
130 struct socket *
131 soalloc(waitok)
132 	int waitok;
133 {
134 	struct socket *so;
135 #ifdef MAC
136 	int error;
137 #endif
138 	int flag;
139 
140 	if (waitok == 1)
141 		flag = M_WAITOK;
142 	else
143 		flag = M_NOWAIT;
144 	flag |= M_ZERO;
145 	so = uma_zalloc(socket_zone, flag);
146 	if (so) {
147 #ifdef MAC
148 		error = mac_init_socket(so, flag);
149 		if (error != 0) {
150 			uma_zfree(socket_zone, so);
151 			so = NULL;
152 			return so;
153 		}
154 #endif
155 		/* XXX race condition for reentrant kernel */
156 		so->so_gencnt = ++so_gencnt;
157 		/* sx_init(&so->so_sxlock, "socket sxlock"); */
158 		TAILQ_INIT(&so->so_aiojobq);
159 		++numopensockets;
160 	}
161 	return so;
162 }
163 
164 /*
165  * socreate returns a socket with a ref count of 1.  The socket should be
166  * closed with soclose().
167  */
168 int
169 socreate(dom, aso, type, proto, cred, td)
170 	int dom;
171 	struct socket **aso;
172 	int type;
173 	int proto;
174 	struct ucred *cred;
175 	struct thread *td;
176 {
177 	struct protosw *prp;
178 	struct socket *so;
179 	int error;
180 
181 	if (proto)
182 		prp = pffindproto(dom, proto, type);
183 	else
184 		prp = pffindtype(dom, type);
185 
186 	if (prp == 0 || prp->pr_usrreqs->pru_attach == 0)
187 		return (EPROTONOSUPPORT);
188 
189 	if (jailed(cred) && jail_socket_unixiproute_only &&
190 	    prp->pr_domain->dom_family != PF_LOCAL &&
191 	    prp->pr_domain->dom_family != PF_INET &&
192 	    prp->pr_domain->dom_family != PF_ROUTE) {
193 		return (EPROTONOSUPPORT);
194 	}
195 
196 	if (prp->pr_type != type)
197 		return (EPROTOTYPE);
198 	so = soalloc(1);
199 	if (so == NULL)
200 		return (ENOBUFS);
201 
202 	TAILQ_INIT(&so->so_incomp);
203 	TAILQ_INIT(&so->so_comp);
204 	so->so_type = type;
205 	so->so_cred = crhold(cred);
206 	so->so_proto = prp;
207 #ifdef MAC
208 	mac_create_socket(cred, so);
209 #endif
210 	soref(so);
211 	error = (*prp->pr_usrreqs->pru_attach)(so, proto, td);
212 	if (error) {
213 		so->so_state |= SS_NOFDREF;
214 		sorele(so);
215 		return (error);
216 	}
217 	*aso = so;
218 	return (0);
219 }
220 
221 int
222 sobind(so, nam, td)
223 	struct socket *so;
224 	struct sockaddr *nam;
225 	struct thread *td;
226 {
227 	int s = splnet();
228 	int error;
229 
230 	error = (*so->so_proto->pr_usrreqs->pru_bind)(so, nam, td);
231 	splx(s);
232 	return (error);
233 }
234 
235 void
236 sodealloc(struct socket *so)
237 {
238 
239 	KASSERT(so->so_count == 0, ("sodealloc(): so_count %d", so->so_count));
240 	so->so_gencnt = ++so_gencnt;
241 	if (so->so_rcv.sb_hiwat)
242 		(void)chgsbsize(so->so_cred->cr_uidinfo,
243 		    &so->so_rcv.sb_hiwat, 0, RLIM_INFINITY);
244 	if (so->so_snd.sb_hiwat)
245 		(void)chgsbsize(so->so_cred->cr_uidinfo,
246 		    &so->so_snd.sb_hiwat, 0, RLIM_INFINITY);
247 #ifdef INET
248 	/* remove acccept filter if one is present. */
249 	if (so->so_accf != NULL)
250 		do_setopt_accept_filter(so, NULL);
251 #endif
252 #ifdef MAC
253 	mac_destroy_socket(so);
254 #endif
255 	crfree(so->so_cred);
256 	/* sx_destroy(&so->so_sxlock); */
257 	uma_zfree(socket_zone, so);
258 	--numopensockets;
259 }
260 
261 int
262 solisten(so, backlog, td)
263 	struct socket *so;
264 	int backlog;
265 	struct thread *td;
266 {
267 	int s, error;
268 
269 	s = splnet();
270 	if (so->so_state & (SS_ISCONNECTED | SS_ISCONNECTING)) {
271 		splx(s);
272 		return (EINVAL);
273 	}
274 	error = (*so->so_proto->pr_usrreqs->pru_listen)(so, td);
275 	if (error) {
276 		splx(s);
277 		return (error);
278 	}
279 	if (TAILQ_EMPTY(&so->so_comp))
280 		so->so_options |= SO_ACCEPTCONN;
281 	if (backlog < 0 || backlog > somaxconn)
282 		backlog = somaxconn;
283 	so->so_qlimit = backlog;
284 	splx(s);
285 	return (0);
286 }
287 
288 void
289 sofree(so)
290 	struct socket *so;
291 {
292 	struct socket *head = so->so_head;
293 
294 	KASSERT(so->so_count == 0, ("socket %p so_count not 0", so));
295 
296 	if (so->so_pcb || (so->so_state & SS_NOFDREF) == 0)
297 		return;
298 	if (head != NULL) {
299 		if (so->so_state & SS_INCOMP) {
300 			TAILQ_REMOVE(&head->so_incomp, so, so_list);
301 			head->so_incqlen--;
302 		} else if (so->so_state & SS_COMP) {
303 			/*
304 			 * We must not decommission a socket that's
305 			 * on the accept(2) queue.  If we do, then
306 			 * accept(2) may hang after select(2) indicated
307 			 * that the listening socket was ready.
308 			 */
309 			return;
310 		} else {
311 			panic("sofree: not queued");
312 		}
313 		so->so_state &= ~SS_INCOMP;
314 		so->so_head = NULL;
315 	}
316 	sbrelease(&so->so_snd, so);
317 	sorflush(so);
318 	sodealloc(so);
319 }
320 
321 /*
322  * Close a socket on last file table reference removal.
323  * Initiate disconnect if connected.
324  * Free socket when disconnect complete.
325  *
326  * This function will sorele() the socket.  Note that soclose() may be
327  * called prior to the ref count reaching zero.  The actual socket
328  * structure will not be freed until the ref count reaches zero.
329  */
330 int
331 soclose(so)
332 	struct socket *so;
333 {
334 	int s = splnet();		/* conservative */
335 	int error = 0;
336 
337 	funsetown(&so->so_sigio);
338 	if (so->so_options & SO_ACCEPTCONN) {
339 		struct socket *sp, *sonext;
340 
341 		sp = TAILQ_FIRST(&so->so_incomp);
342 		for (; sp != NULL; sp = sonext) {
343 			sonext = TAILQ_NEXT(sp, so_list);
344 			(void) soabort(sp);
345 		}
346 		for (sp = TAILQ_FIRST(&so->so_comp); sp != NULL; sp = sonext) {
347 			sonext = TAILQ_NEXT(sp, so_list);
348 			/* Dequeue from so_comp since sofree() won't do it */
349 			TAILQ_REMOVE(&so->so_comp, sp, so_list);
350 			so->so_qlen--;
351 			sp->so_state &= ~SS_COMP;
352 			sp->so_head = NULL;
353 			(void) soabort(sp);
354 		}
355 	}
356 	if (so->so_pcb == 0)
357 		goto discard;
358 	if (so->so_state & SS_ISCONNECTED) {
359 		if ((so->so_state & SS_ISDISCONNECTING) == 0) {
360 			error = sodisconnect(so);
361 			if (error)
362 				goto drop;
363 		}
364 		if (so->so_options & SO_LINGER) {
365 			if ((so->so_state & SS_ISDISCONNECTING) &&
366 			    (so->so_state & SS_NBIO))
367 				goto drop;
368 			while (so->so_state & SS_ISCONNECTED) {
369 				error = tsleep(&so->so_timeo,
370 				    PSOCK | PCATCH, "soclos", so->so_linger * hz);
371 				if (error)
372 					break;
373 			}
374 		}
375 	}
376 drop:
377 	if (so->so_pcb) {
378 		int error2 = (*so->so_proto->pr_usrreqs->pru_detach)(so);
379 		if (error == 0)
380 			error = error2;
381 	}
382 discard:
383 	if (so->so_state & SS_NOFDREF)
384 		panic("soclose: NOFDREF");
385 	so->so_state |= SS_NOFDREF;
386 	sorele(so);
387 	splx(s);
388 	return (error);
389 }
390 
391 /*
392  * Must be called at splnet...
393  */
394 int
395 soabort(so)
396 	struct socket *so;
397 {
398 	int error;
399 
400 	error = (*so->so_proto->pr_usrreqs->pru_abort)(so);
401 	if (error) {
402 		sotryfree(so);	/* note: does not decrement the ref count */
403 		return error;
404 	}
405 	return (0);
406 }
407 
408 int
409 soaccept(so, nam)
410 	struct socket *so;
411 	struct sockaddr **nam;
412 {
413 	int s = splnet();
414 	int error;
415 
416 	if ((so->so_state & SS_NOFDREF) == 0)
417 		panic("soaccept: !NOFDREF");
418 	so->so_state &= ~SS_NOFDREF;
419 	error = (*so->so_proto->pr_usrreqs->pru_accept)(so, nam);
420 	splx(s);
421 	return (error);
422 }
423 
424 int
425 soconnect(so, nam, td)
426 	struct socket *so;
427 	struct sockaddr *nam;
428 	struct thread *td;
429 {
430 	int s;
431 	int error;
432 
433 	if (so->so_options & SO_ACCEPTCONN)
434 		return (EOPNOTSUPP);
435 	s = splnet();
436 	/*
437 	 * If protocol is connection-based, can only connect once.
438 	 * Otherwise, if connected, try to disconnect first.
439 	 * This allows user to disconnect by connecting to, e.g.,
440 	 * a null address.
441 	 */
442 	if (so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING) &&
443 	    ((so->so_proto->pr_flags & PR_CONNREQUIRED) ||
444 	    (error = sodisconnect(so))))
445 		error = EISCONN;
446 	else
447 		error = (*so->so_proto->pr_usrreqs->pru_connect)(so, nam, td);
448 	splx(s);
449 	return (error);
450 }
451 
452 int
453 soconnect2(so1, so2)
454 	struct socket *so1;
455 	struct socket *so2;
456 {
457 	int s = splnet();
458 	int error;
459 
460 	error = (*so1->so_proto->pr_usrreqs->pru_connect2)(so1, so2);
461 	splx(s);
462 	return (error);
463 }
464 
465 int
466 sodisconnect(so)
467 	struct socket *so;
468 {
469 	int s = splnet();
470 	int error;
471 
472 	if ((so->so_state & SS_ISCONNECTED) == 0) {
473 		error = ENOTCONN;
474 		goto bad;
475 	}
476 	if (so->so_state & SS_ISDISCONNECTING) {
477 		error = EALREADY;
478 		goto bad;
479 	}
480 	error = (*so->so_proto->pr_usrreqs->pru_disconnect)(so);
481 bad:
482 	splx(s);
483 	return (error);
484 }
485 
486 #define	SBLOCKWAIT(f)	(((f) & MSG_DONTWAIT) ? M_NOWAIT : M_WAITOK)
487 /*
488  * Send on a socket.
489  * If send must go all at once and message is larger than
490  * send buffering, then hard error.
491  * Lock against other senders.
492  * If must go all at once and not enough room now, then
493  * inform user that this would block and do nothing.
494  * Otherwise, if nonblocking, send as much as possible.
495  * The data to be sent is described by "uio" if nonzero,
496  * otherwise by the mbuf chain "top" (which must be null
497  * if uio is not).  Data provided in mbuf chain must be small
498  * enough to send all at once.
499  *
500  * Returns nonzero on error, timeout or signal; callers
501  * must check for short counts if EINTR/ERESTART are returned.
502  * Data and control buffers are freed on return.
503  */
504 
505 #ifdef ZERO_COPY_SOCKETS
506 struct so_zerocopy_stats{
507 	int size_ok;
508 	int align_ok;
509 	int found_ifp;
510 };
511 struct so_zerocopy_stats so_zerocp_stats = {0,0,0};
512 #include <netinet/in.h>
513 #include <net/route.h>
514 #include <netinet/in_pcb.h>
515 #include <vm/vm.h>
516 #include <vm/vm_page.h>
517 #include <vm/vm_object.h>
518 #endif /*ZERO_COPY_SOCKETS*/
519 
520 int
521 sosend(so, addr, uio, top, control, flags, td)
522 	struct socket *so;
523 	struct sockaddr *addr;
524 	struct uio *uio;
525 	struct mbuf *top;
526 	struct mbuf *control;
527 	int flags;
528 	struct thread *td;
529 {
530 	struct mbuf **mp;
531 	struct mbuf *m;
532 	long space, len, resid;
533 	int clen = 0, error, s, dontroute, mlen;
534 	int atomic = sosendallatonce(so) || top;
535 #ifdef ZERO_COPY_SOCKETS
536 	int cow_send;
537 #endif /* ZERO_COPY_SOCKETS */
538 
539 	if (uio)
540 		resid = uio->uio_resid;
541 	else
542 		resid = top->m_pkthdr.len;
543 	/*
544 	 * In theory resid should be unsigned.
545 	 * However, space must be signed, as it might be less than 0
546 	 * if we over-committed, and we must use a signed comparison
547 	 * of space and resid.  On the other hand, a negative resid
548 	 * causes us to loop sending 0-length segments to the protocol.
549 	 *
550 	 * Also check to make sure that MSG_EOR isn't used on SOCK_STREAM
551 	 * type sockets since that's an error.
552 	 */
553 	if (resid < 0 || (so->so_type == SOCK_STREAM && (flags & MSG_EOR))) {
554 		error = EINVAL;
555 		goto out;
556 	}
557 
558 	dontroute =
559 	    (flags & MSG_DONTROUTE) && (so->so_options & SO_DONTROUTE) == 0 &&
560 	    (so->so_proto->pr_flags & PR_ATOMIC);
561 	if (td)
562 		td->td_proc->p_stats->p_ru.ru_msgsnd++;
563 	if (control)
564 		clen = control->m_len;
565 #define	snderr(errno)	{ error = (errno); splx(s); goto release; }
566 
567 restart:
568 	error = sblock(&so->so_snd, SBLOCKWAIT(flags));
569 	if (error)
570 		goto out;
571 	do {
572 		s = splnet();
573 		if (so->so_state & SS_CANTSENDMORE)
574 			snderr(EPIPE);
575 		if (so->so_error) {
576 			error = so->so_error;
577 			so->so_error = 0;
578 			splx(s);
579 			goto release;
580 		}
581 		if ((so->so_state & SS_ISCONNECTED) == 0) {
582 			/*
583 			 * `sendto' and `sendmsg' is allowed on a connection-
584 			 * based socket if it supports implied connect.
585 			 * Return ENOTCONN if not connected and no address is
586 			 * supplied.
587 			 */
588 			if ((so->so_proto->pr_flags & PR_CONNREQUIRED) &&
589 			    (so->so_proto->pr_flags & PR_IMPLOPCL) == 0) {
590 				if ((so->so_state & SS_ISCONFIRMING) == 0 &&
591 				    !(resid == 0 && clen != 0))
592 					snderr(ENOTCONN);
593 			} else if (addr == 0)
594 			    snderr(so->so_proto->pr_flags & PR_CONNREQUIRED ?
595 				   ENOTCONN : EDESTADDRREQ);
596 		}
597 		space = sbspace(&so->so_snd);
598 		if (flags & MSG_OOB)
599 			space += 1024;
600 		if ((atomic && resid > so->so_snd.sb_hiwat) ||
601 		    clen > so->so_snd.sb_hiwat)
602 			snderr(EMSGSIZE);
603 		if (space < resid + clen &&
604 		    (atomic || space < so->so_snd.sb_lowat || space < clen)) {
605 			if (so->so_state & SS_NBIO)
606 				snderr(EWOULDBLOCK);
607 			sbunlock(&so->so_snd);
608 			error = sbwait(&so->so_snd);
609 			splx(s);
610 			if (error)
611 				goto out;
612 			goto restart;
613 		}
614 		splx(s);
615 		mp = &top;
616 		space -= clen;
617 		do {
618 		    if (uio == NULL) {
619 			/*
620 			 * Data is prepackaged in "top".
621 			 */
622 			resid = 0;
623 			if (flags & MSG_EOR)
624 				top->m_flags |= M_EOR;
625 		    } else do {
626 #ifdef ZERO_COPY_SOCKETS
627 			cow_send = 0;
628 #endif /* ZERO_COPY_SOCKETS */
629 			if (top == 0) {
630 				MGETHDR(m, M_TRYWAIT, MT_DATA);
631 				if (m == NULL) {
632 					error = ENOBUFS;
633 					goto release;
634 				}
635 				mlen = MHLEN;
636 				m->m_pkthdr.len = 0;
637 				m->m_pkthdr.rcvif = (struct ifnet *)0;
638 			} else {
639 				MGET(m, M_TRYWAIT, MT_DATA);
640 				if (m == NULL) {
641 					error = ENOBUFS;
642 					goto release;
643 				}
644 				mlen = MLEN;
645 			}
646 			if (resid >= MINCLSIZE) {
647 #ifdef ZERO_COPY_SOCKETS
648 				if (so_zero_copy_send &&
649 				    resid>=PAGE_SIZE &&
650 				    space>=PAGE_SIZE &&
651 				    uio->uio_iov->iov_len>=PAGE_SIZE) {
652 					so_zerocp_stats.size_ok++;
653 					if (!((vm_offset_t)
654 					  uio->uio_iov->iov_base & PAGE_MASK)){
655 						so_zerocp_stats.align_ok++;
656 						cow_send = socow_setup(m, uio);
657 					}
658 				}
659 				if (!cow_send){
660 #endif /* ZERO_COPY_SOCKETS */
661 				MCLGET(m, M_TRYWAIT);
662 				if ((m->m_flags & M_EXT) == 0)
663 					goto nopages;
664 				mlen = MCLBYTES;
665 				len = min(min(mlen, resid), space);
666 			} else {
667 #ifdef ZERO_COPY_SOCKETS
668 					len = PAGE_SIZE;
669 				}
670 
671 			} else {
672 #endif /* ZERO_COPY_SOCKETS */
673 nopages:
674 				len = min(min(mlen, resid), space);
675 				/*
676 				 * For datagram protocols, leave room
677 				 * for protocol headers in first mbuf.
678 				 */
679 				if (atomic && top == 0 && len < mlen)
680 					MH_ALIGN(m, len);
681 			}
682 			space -= len;
683 #ifdef ZERO_COPY_SOCKETS
684 			if (cow_send)
685 				error = 0;
686 			else
687 #endif /* ZERO_COPY_SOCKETS */
688 			error = uiomove(mtod(m, void *), (int)len, uio);
689 			resid = uio->uio_resid;
690 			m->m_len = len;
691 			*mp = m;
692 			top->m_pkthdr.len += len;
693 			if (error)
694 				goto release;
695 			mp = &m->m_next;
696 			if (resid <= 0) {
697 				if (flags & MSG_EOR)
698 					top->m_flags |= M_EOR;
699 				break;
700 			}
701 		    } while (space > 0 && atomic);
702 		    if (dontroute)
703 			    so->so_options |= SO_DONTROUTE;
704 		    s = splnet();				/* XXX */
705 		    /*
706 		     * XXX all the SS_CANTSENDMORE checks previously
707 		     * done could be out of date.  We could have recieved
708 		     * a reset packet in an interrupt or maybe we slept
709 		     * while doing page faults in uiomove() etc. We could
710 		     * probably recheck again inside the splnet() protection
711 		     * here, but there are probably other places that this
712 		     * also happens.  We must rethink this.
713 		     */
714 		    error = (*so->so_proto->pr_usrreqs->pru_send)(so,
715 			(flags & MSG_OOB) ? PRUS_OOB :
716 			/*
717 			 * If the user set MSG_EOF, the protocol
718 			 * understands this flag and nothing left to
719 			 * send then use PRU_SEND_EOF instead of PRU_SEND.
720 			 */
721 			((flags & MSG_EOF) &&
722 			 (so->so_proto->pr_flags & PR_IMPLOPCL) &&
723 			 (resid <= 0)) ?
724 				PRUS_EOF :
725 			/* If there is more to send set PRUS_MORETOCOME */
726 			(resid > 0 && space > 0) ? PRUS_MORETOCOME : 0,
727 			top, addr, control, td);
728 		    splx(s);
729 		    if (dontroute)
730 			    so->so_options &= ~SO_DONTROUTE;
731 		    clen = 0;
732 		    control = 0;
733 		    top = 0;
734 		    mp = &top;
735 		    if (error)
736 			goto release;
737 		} while (resid && space > 0);
738 	} while (resid);
739 
740 release:
741 	sbunlock(&so->so_snd);
742 out:
743 	if (top)
744 		m_freem(top);
745 	if (control)
746 		m_freem(control);
747 	return (error);
748 }
749 
750 /*
751  * Implement receive operations on a socket.
752  * We depend on the way that records are added to the sockbuf
753  * by sbappend*.  In particular, each record (mbufs linked through m_next)
754  * must begin with an address if the protocol so specifies,
755  * followed by an optional mbuf or mbufs containing ancillary data,
756  * and then zero or more mbufs of data.
757  * In order to avoid blocking network interrupts for the entire time here,
758  * we splx() while doing the actual copy to user space.
759  * Although the sockbuf is locked, new data may still be appended,
760  * and thus we must maintain consistency of the sockbuf during that time.
761  *
762  * The caller may receive the data as a single mbuf chain by supplying
763  * an mbuf **mp0 for use in returning the chain.  The uio is then used
764  * only for the count in uio_resid.
765  */
766 int
767 soreceive(so, psa, uio, mp0, controlp, flagsp)
768 	struct socket *so;
769 	struct sockaddr **psa;
770 	struct uio *uio;
771 	struct mbuf **mp0;
772 	struct mbuf **controlp;
773 	int *flagsp;
774 {
775 	struct mbuf *m, **mp;
776 	int flags, len, error, s, offset;
777 	struct protosw *pr = so->so_proto;
778 	struct mbuf *nextrecord;
779 	int moff, type = 0;
780 	int orig_resid = uio->uio_resid;
781 
782 	mp = mp0;
783 	if (psa)
784 		*psa = 0;
785 	if (controlp)
786 		*controlp = 0;
787 	if (flagsp)
788 		flags = *flagsp &~ MSG_EOR;
789 	else
790 		flags = 0;
791 	if (flags & MSG_OOB) {
792 		m = m_get(M_TRYWAIT, MT_DATA);
793 		if (m == NULL)
794 			return (ENOBUFS);
795 		error = (*pr->pr_usrreqs->pru_rcvoob)(so, m, flags & MSG_PEEK);
796 		if (error)
797 			goto bad;
798 		do {
799 #ifdef ZERO_COPY_SOCKETS
800 			if (so_zero_copy_receive) {
801 				vm_page_t pg;
802 				int disposable;
803 
804 				if ((m->m_flags & M_EXT)
805 				 && (m->m_ext.ext_type == EXT_DISPOSABLE))
806 					disposable = 1;
807 				else
808 					disposable = 0;
809 
810 				pg = PHYS_TO_VM_PAGE(vtophys(mtod(m, caddr_t)));
811 				if (uio->uio_offset == -1)
812 					uio->uio_offset =IDX_TO_OFF(pg->pindex);
813 
814 				error = uiomoveco(mtod(m, void *),
815 						  min(uio->uio_resid, m->m_len),
816 						  uio, pg->object,
817 						  disposable);
818 			} else
819 #endif /* ZERO_COPY_SOCKETS */
820 			error = uiomove(mtod(m, void *),
821 			    (int) min(uio->uio_resid, m->m_len), uio);
822 			m = m_free(m);
823 		} while (uio->uio_resid && error == 0 && m);
824 bad:
825 		if (m)
826 			m_freem(m);
827 		return (error);
828 	}
829 	if (mp)
830 		*mp = (struct mbuf *)0;
831 	if (so->so_state & SS_ISCONFIRMING && uio->uio_resid)
832 		(*pr->pr_usrreqs->pru_rcvd)(so, 0);
833 
834 restart:
835 	error = sblock(&so->so_rcv, SBLOCKWAIT(flags));
836 	if (error)
837 		return (error);
838 	s = splnet();
839 
840 	m = so->so_rcv.sb_mb;
841 	/*
842 	 * If we have less data than requested, block awaiting more
843 	 * (subject to any timeout) if:
844 	 *   1. the current count is less than the low water mark, or
845 	 *   2. MSG_WAITALL is set, and it is possible to do the entire
846 	 *	receive operation at once if we block (resid <= hiwat).
847 	 *   3. MSG_DONTWAIT is not set
848 	 * If MSG_WAITALL is set but resid is larger than the receive buffer,
849 	 * we have to do the receive in sections, and thus risk returning
850 	 * a short count if a timeout or signal occurs after we start.
851 	 */
852 	if (m == 0 || (((flags & MSG_DONTWAIT) == 0 &&
853 	    so->so_rcv.sb_cc < uio->uio_resid) &&
854 	    (so->so_rcv.sb_cc < so->so_rcv.sb_lowat ||
855 	    ((flags & MSG_WAITALL) && uio->uio_resid <= so->so_rcv.sb_hiwat)) &&
856 	    m->m_nextpkt == 0 && (pr->pr_flags & PR_ATOMIC) == 0)) {
857 		KASSERT(m != 0 || !so->so_rcv.sb_cc,
858 		    ("receive: m == %p so->so_rcv.sb_cc == %u",
859 		    m, so->so_rcv.sb_cc));
860 		if (so->so_error) {
861 			if (m)
862 				goto dontblock;
863 			error = so->so_error;
864 			if ((flags & MSG_PEEK) == 0)
865 				so->so_error = 0;
866 			goto release;
867 		}
868 		if (so->so_state & SS_CANTRCVMORE) {
869 			if (m)
870 				goto dontblock;
871 			else
872 				goto release;
873 		}
874 		for (; m; m = m->m_next)
875 			if (m->m_type == MT_OOBDATA  || (m->m_flags & M_EOR)) {
876 				m = so->so_rcv.sb_mb;
877 				goto dontblock;
878 			}
879 		if ((so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING)) == 0 &&
880 		    (so->so_proto->pr_flags & PR_CONNREQUIRED)) {
881 			error = ENOTCONN;
882 			goto release;
883 		}
884 		if (uio->uio_resid == 0)
885 			goto release;
886 		if ((so->so_state & SS_NBIO) || (flags & MSG_DONTWAIT)) {
887 			error = EWOULDBLOCK;
888 			goto release;
889 		}
890 		sbunlock(&so->so_rcv);
891 		error = sbwait(&so->so_rcv);
892 		splx(s);
893 		if (error)
894 			return (error);
895 		goto restart;
896 	}
897 dontblock:
898 	if (uio->uio_td)
899 		uio->uio_td->td_proc->p_stats->p_ru.ru_msgrcv++;
900 	nextrecord = m->m_nextpkt;
901 	if (pr->pr_flags & PR_ADDR) {
902 		KASSERT(m->m_type == MT_SONAME,
903 		    ("m->m_type == %d", m->m_type));
904 		orig_resid = 0;
905 		if (psa)
906 			*psa = dup_sockaddr(mtod(m, struct sockaddr *),
907 					    mp0 == 0);
908 		if (flags & MSG_PEEK) {
909 			m = m->m_next;
910 		} else {
911 			sbfree(&so->so_rcv, m);
912 			so->so_rcv.sb_mb = m_free(m);
913 			m = so->so_rcv.sb_mb;
914 		}
915 	}
916 	while (m && m->m_type == MT_CONTROL && error == 0) {
917 		if (flags & MSG_PEEK) {
918 			if (controlp)
919 				*controlp = m_copy(m, 0, m->m_len);
920 			m = m->m_next;
921 		} else {
922 			sbfree(&so->so_rcv, m);
923 			so->so_rcv.sb_mb = m->m_next;
924 			m->m_next = NULL;
925 			if (pr->pr_domain->dom_externalize)
926 				error =
927 				(*pr->pr_domain->dom_externalize)(m, controlp);
928 			else if (controlp)
929 				*controlp = m;
930 			else
931 				m_freem(m);
932 			m = so->so_rcv.sb_mb;
933 		}
934 		if (controlp) {
935 			orig_resid = 0;
936 			while (*controlp != NULL)
937 				controlp = &(*controlp)->m_next;
938 		}
939 	}
940 	if (m) {
941 		if ((flags & MSG_PEEK) == 0)
942 			m->m_nextpkt = nextrecord;
943 		type = m->m_type;
944 		if (type == MT_OOBDATA)
945 			flags |= MSG_OOB;
946 	}
947 	moff = 0;
948 	offset = 0;
949 	while (m && uio->uio_resid > 0 && error == 0) {
950 		if (m->m_type == MT_OOBDATA) {
951 			if (type != MT_OOBDATA)
952 				break;
953 		} else if (type == MT_OOBDATA)
954 			break;
955 		else
956 		    KASSERT(m->m_type == MT_DATA || m->m_type == MT_HEADER,
957 			("m->m_type == %d", m->m_type));
958 		so->so_state &= ~SS_RCVATMARK;
959 		len = uio->uio_resid;
960 		if (so->so_oobmark && len > so->so_oobmark - offset)
961 			len = so->so_oobmark - offset;
962 		if (len > m->m_len - moff)
963 			len = m->m_len - moff;
964 		/*
965 		 * If mp is set, just pass back the mbufs.
966 		 * Otherwise copy them out via the uio, then free.
967 		 * Sockbuf must be consistent here (points to current mbuf,
968 		 * it points to next record) when we drop priority;
969 		 * we must note any additions to the sockbuf when we
970 		 * block interrupts again.
971 		 */
972 		if (mp == 0) {
973 			splx(s);
974 #ifdef ZERO_COPY_SOCKETS
975 			if (so_zero_copy_receive) {
976 				vm_page_t pg;
977 				int disposable;
978 
979 				if ((m->m_flags & M_EXT)
980 				 && (m->m_ext.ext_type == EXT_DISPOSABLE))
981 					disposable = 1;
982 				else
983 					disposable = 0;
984 
985 				pg = PHYS_TO_VM_PAGE(vtophys(mtod(m, caddr_t) +
986 					moff));
987 
988 				if (uio->uio_offset == -1)
989 					uio->uio_offset =IDX_TO_OFF(pg->pindex);
990 
991 				error = uiomoveco(mtod(m, char *) + moff,
992 						  (int)len, uio,pg->object,
993 						  disposable);
994 			} else
995 #endif /* ZERO_COPY_SOCKETS */
996 			error = uiomove(mtod(m, char *) + moff, (int)len, uio);
997 			s = splnet();
998 			if (error)
999 				goto release;
1000 		} else
1001 			uio->uio_resid -= len;
1002 		if (len == m->m_len - moff) {
1003 			if (m->m_flags & M_EOR)
1004 				flags |= MSG_EOR;
1005 			if (flags & MSG_PEEK) {
1006 				m = m->m_next;
1007 				moff = 0;
1008 			} else {
1009 				nextrecord = m->m_nextpkt;
1010 				sbfree(&so->so_rcv, m);
1011 				if (mp) {
1012 					*mp = m;
1013 					mp = &m->m_next;
1014 					so->so_rcv.sb_mb = m = m->m_next;
1015 					*mp = (struct mbuf *)0;
1016 				} else {
1017 					so->so_rcv.sb_mb = m_free(m);
1018 					m = so->so_rcv.sb_mb;
1019 				}
1020 				if (m)
1021 					m->m_nextpkt = nextrecord;
1022 			}
1023 		} else {
1024 			if (flags & MSG_PEEK)
1025 				moff += len;
1026 			else {
1027 				if (mp)
1028 					*mp = m_copym(m, 0, len, M_TRYWAIT);
1029 				m->m_data += len;
1030 				m->m_len -= len;
1031 				so->so_rcv.sb_cc -= len;
1032 			}
1033 		}
1034 		if (so->so_oobmark) {
1035 			if ((flags & MSG_PEEK) == 0) {
1036 				so->so_oobmark -= len;
1037 				if (so->so_oobmark == 0) {
1038 					so->so_state |= SS_RCVATMARK;
1039 					break;
1040 				}
1041 			} else {
1042 				offset += len;
1043 				if (offset == so->so_oobmark)
1044 					break;
1045 			}
1046 		}
1047 		if (flags & MSG_EOR)
1048 			break;
1049 		/*
1050 		 * If the MSG_WAITALL flag is set (for non-atomic socket),
1051 		 * we must not quit until "uio->uio_resid == 0" or an error
1052 		 * termination.  If a signal/timeout occurs, return
1053 		 * with a short count but without error.
1054 		 * Keep sockbuf locked against other readers.
1055 		 */
1056 		while (flags & MSG_WAITALL && m == 0 && uio->uio_resid > 0 &&
1057 		    !sosendallatonce(so) && !nextrecord) {
1058 			if (so->so_error || so->so_state & SS_CANTRCVMORE)
1059 				break;
1060 			/*
1061 			 * Notify the protocol that some data has been
1062 			 * drained before blocking.
1063 			 */
1064 			if (pr->pr_flags & PR_WANTRCVD && so->so_pcb)
1065 				(*pr->pr_usrreqs->pru_rcvd)(so, flags);
1066 			error = sbwait(&so->so_rcv);
1067 			if (error) {
1068 				sbunlock(&so->so_rcv);
1069 				splx(s);
1070 				return (0);
1071 			}
1072 			m = so->so_rcv.sb_mb;
1073 			if (m)
1074 				nextrecord = m->m_nextpkt;
1075 		}
1076 	}
1077 
1078 	if (m && pr->pr_flags & PR_ATOMIC) {
1079 		flags |= MSG_TRUNC;
1080 		if ((flags & MSG_PEEK) == 0)
1081 			(void) sbdroprecord(&so->so_rcv);
1082 	}
1083 	if ((flags & MSG_PEEK) == 0) {
1084 		if (m == 0)
1085 			so->so_rcv.sb_mb = nextrecord;
1086 		if (pr->pr_flags & PR_WANTRCVD && so->so_pcb)
1087 			(*pr->pr_usrreqs->pru_rcvd)(so, flags);
1088 	}
1089 	if (orig_resid == uio->uio_resid && orig_resid &&
1090 	    (flags & MSG_EOR) == 0 && (so->so_state & SS_CANTRCVMORE) == 0) {
1091 		sbunlock(&so->so_rcv);
1092 		splx(s);
1093 		goto restart;
1094 	}
1095 
1096 	if (flagsp)
1097 		*flagsp |= flags;
1098 release:
1099 	sbunlock(&so->so_rcv);
1100 	splx(s);
1101 	return (error);
1102 }
1103 
1104 int
1105 soshutdown(so, how)
1106 	struct socket *so;
1107 	int how;
1108 {
1109 	struct protosw *pr = so->so_proto;
1110 
1111 	if (!(how == SHUT_RD || how == SHUT_WR || how == SHUT_RDWR))
1112 		return (EINVAL);
1113 
1114 	if (how != SHUT_WR)
1115 		sorflush(so);
1116 	if (how != SHUT_RD)
1117 		return ((*pr->pr_usrreqs->pru_shutdown)(so));
1118 	return (0);
1119 }
1120 
1121 void
1122 sorflush(so)
1123 	struct socket *so;
1124 {
1125 	struct sockbuf *sb = &so->so_rcv;
1126 	struct protosw *pr = so->so_proto;
1127 	int s;
1128 	struct sockbuf asb;
1129 
1130 	sb->sb_flags |= SB_NOINTR;
1131 	(void) sblock(sb, M_WAITOK);
1132 	s = splimp();
1133 	socantrcvmore(so);
1134 	sbunlock(sb);
1135 	asb = *sb;
1136 	/*
1137 	 * Invalidate/clear most of the sockbuf structure, but keep
1138 	 * its selinfo structure valid.
1139 	 */
1140 	bzero(&sb->sb_startzero,
1141 	    sizeof(*sb) - offsetof(struct sockbuf, sb_startzero));
1142 	splx(s);
1143 
1144 	if (pr->pr_flags & PR_RIGHTS && pr->pr_domain->dom_dispose)
1145 		(*pr->pr_domain->dom_dispose)(asb.sb_mb);
1146 	sbrelease(&asb, so);
1147 }
1148 
1149 #ifdef INET
1150 static int
1151 do_setopt_accept_filter(so, sopt)
1152 	struct	socket *so;
1153 	struct	sockopt *sopt;
1154 {
1155 	struct accept_filter_arg	*afap = NULL;
1156 	struct accept_filter	*afp;
1157 	struct so_accf	*af = so->so_accf;
1158 	int	error = 0;
1159 
1160 	/* do not set/remove accept filters on non listen sockets */
1161 	if ((so->so_options & SO_ACCEPTCONN) == 0) {
1162 		error = EINVAL;
1163 		goto out;
1164 	}
1165 
1166 	/* removing the filter */
1167 	if (sopt == NULL) {
1168 		if (af != NULL) {
1169 			if (af->so_accept_filter != NULL &&
1170 				af->so_accept_filter->accf_destroy != NULL) {
1171 				af->so_accept_filter->accf_destroy(so);
1172 			}
1173 			if (af->so_accept_filter_str != NULL) {
1174 				FREE(af->so_accept_filter_str, M_ACCF);
1175 			}
1176 			FREE(af, M_ACCF);
1177 			so->so_accf = NULL;
1178 		}
1179 		so->so_options &= ~SO_ACCEPTFILTER;
1180 		return (0);
1181 	}
1182 	/* adding a filter */
1183 	/* must remove previous filter first */
1184 	if (af != NULL) {
1185 		error = EINVAL;
1186 		goto out;
1187 	}
1188 	/* don't put large objects on the kernel stack */
1189 	MALLOC(afap, struct accept_filter_arg *, sizeof(*afap), M_TEMP, M_WAITOK);
1190 	error = sooptcopyin(sopt, afap, sizeof *afap, sizeof *afap);
1191 	afap->af_name[sizeof(afap->af_name)-1] = '\0';
1192 	afap->af_arg[sizeof(afap->af_arg)-1] = '\0';
1193 	if (error)
1194 		goto out;
1195 	afp = accept_filt_get(afap->af_name);
1196 	if (afp == NULL) {
1197 		error = ENOENT;
1198 		goto out;
1199 	}
1200 	MALLOC(af, struct so_accf *, sizeof(*af), M_ACCF, M_WAITOK | M_ZERO);
1201 	if (afp->accf_create != NULL) {
1202 		if (afap->af_name[0] != '\0') {
1203 			int len = strlen(afap->af_name) + 1;
1204 
1205 			MALLOC(af->so_accept_filter_str, char *, len, M_ACCF, M_WAITOK);
1206 			strcpy(af->so_accept_filter_str, afap->af_name);
1207 		}
1208 		af->so_accept_filter_arg = afp->accf_create(so, afap->af_arg);
1209 		if (af->so_accept_filter_arg == NULL) {
1210 			FREE(af->so_accept_filter_str, M_ACCF);
1211 			FREE(af, M_ACCF);
1212 			so->so_accf = NULL;
1213 			error = EINVAL;
1214 			goto out;
1215 		}
1216 	}
1217 	af->so_accept_filter = afp;
1218 	so->so_accf = af;
1219 	so->so_options |= SO_ACCEPTFILTER;
1220 out:
1221 	if (afap != NULL)
1222 		FREE(afap, M_TEMP);
1223 	return (error);
1224 }
1225 #endif /* INET */
1226 
1227 /*
1228  * Perhaps this routine, and sooptcopyout(), below, ought to come in
1229  * an additional variant to handle the case where the option value needs
1230  * to be some kind of integer, but not a specific size.
1231  * In addition to their use here, these functions are also called by the
1232  * protocol-level pr_ctloutput() routines.
1233  */
1234 int
1235 sooptcopyin(sopt, buf, len, minlen)
1236 	struct	sockopt *sopt;
1237 	void	*buf;
1238 	size_t	len;
1239 	size_t	minlen;
1240 {
1241 	size_t	valsize;
1242 
1243 	/*
1244 	 * If the user gives us more than we wanted, we ignore it,
1245 	 * but if we don't get the minimum length the caller
1246 	 * wants, we return EINVAL.  On success, sopt->sopt_valsize
1247 	 * is set to however much we actually retrieved.
1248 	 */
1249 	if ((valsize = sopt->sopt_valsize) < minlen)
1250 		return EINVAL;
1251 	if (valsize > len)
1252 		sopt->sopt_valsize = valsize = len;
1253 
1254 	if (sopt->sopt_td != 0)
1255 		return (copyin(sopt->sopt_val, buf, valsize));
1256 
1257 	bcopy(sopt->sopt_val, buf, valsize);
1258 	return 0;
1259 }
1260 
1261 int
1262 sosetopt(so, sopt)
1263 	struct socket *so;
1264 	struct sockopt *sopt;
1265 {
1266 	int	error, optval;
1267 	struct	linger l;
1268 	struct	timeval tv;
1269 	u_long  val;
1270 #ifdef MAC
1271 	struct mac extmac;
1272 #endif
1273 
1274 	error = 0;
1275 	if (sopt->sopt_level != SOL_SOCKET) {
1276 		if (so->so_proto && so->so_proto->pr_ctloutput)
1277 			return ((*so->so_proto->pr_ctloutput)
1278 				  (so, sopt));
1279 		error = ENOPROTOOPT;
1280 	} else {
1281 		switch (sopt->sopt_name) {
1282 #ifdef INET
1283 		case SO_ACCEPTFILTER:
1284 			error = do_setopt_accept_filter(so, sopt);
1285 			if (error)
1286 				goto bad;
1287 			break;
1288 #endif
1289 		case SO_LINGER:
1290 			error = sooptcopyin(sopt, &l, sizeof l, sizeof l);
1291 			if (error)
1292 				goto bad;
1293 
1294 			so->so_linger = l.l_linger;
1295 			if (l.l_onoff)
1296 				so->so_options |= SO_LINGER;
1297 			else
1298 				so->so_options &= ~SO_LINGER;
1299 			break;
1300 
1301 		case SO_DEBUG:
1302 		case SO_KEEPALIVE:
1303 		case SO_DONTROUTE:
1304 		case SO_USELOOPBACK:
1305 		case SO_BROADCAST:
1306 		case SO_REUSEADDR:
1307 		case SO_REUSEPORT:
1308 		case SO_OOBINLINE:
1309 		case SO_TIMESTAMP:
1310 		case SO_NOSIGPIPE:
1311 			error = sooptcopyin(sopt, &optval, sizeof optval,
1312 					    sizeof optval);
1313 			if (error)
1314 				goto bad;
1315 			if (optval)
1316 				so->so_options |= sopt->sopt_name;
1317 			else
1318 				so->so_options &= ~sopt->sopt_name;
1319 			break;
1320 
1321 		case SO_SNDBUF:
1322 		case SO_RCVBUF:
1323 		case SO_SNDLOWAT:
1324 		case SO_RCVLOWAT:
1325 			error = sooptcopyin(sopt, &optval, sizeof optval,
1326 					    sizeof optval);
1327 			if (error)
1328 				goto bad;
1329 
1330 			/*
1331 			 * Values < 1 make no sense for any of these
1332 			 * options, so disallow them.
1333 			 */
1334 			if (optval < 1) {
1335 				error = EINVAL;
1336 				goto bad;
1337 			}
1338 
1339 			switch (sopt->sopt_name) {
1340 			case SO_SNDBUF:
1341 			case SO_RCVBUF:
1342 				if (sbreserve(sopt->sopt_name == SO_SNDBUF ?
1343 				    &so->so_snd : &so->so_rcv, (u_long)optval,
1344 				    so, curthread) == 0) {
1345 					error = ENOBUFS;
1346 					goto bad;
1347 				}
1348 				break;
1349 
1350 			/*
1351 			 * Make sure the low-water is never greater than
1352 			 * the high-water.
1353 			 */
1354 			case SO_SNDLOWAT:
1355 				so->so_snd.sb_lowat =
1356 				    (optval > so->so_snd.sb_hiwat) ?
1357 				    so->so_snd.sb_hiwat : optval;
1358 				break;
1359 			case SO_RCVLOWAT:
1360 				so->so_rcv.sb_lowat =
1361 				    (optval > so->so_rcv.sb_hiwat) ?
1362 				    so->so_rcv.sb_hiwat : optval;
1363 				break;
1364 			}
1365 			break;
1366 
1367 		case SO_SNDTIMEO:
1368 		case SO_RCVTIMEO:
1369 			error = sooptcopyin(sopt, &tv, sizeof tv,
1370 					    sizeof tv);
1371 			if (error)
1372 				goto bad;
1373 
1374 			/* assert(hz > 0); */
1375 			if (tv.tv_sec < 0 || tv.tv_sec > SHRT_MAX / hz ||
1376 			    tv.tv_usec < 0 || tv.tv_usec >= 1000000) {
1377 				error = EDOM;
1378 				goto bad;
1379 			}
1380 			/* assert(tick > 0); */
1381 			/* assert(ULONG_MAX - SHRT_MAX >= 1000000); */
1382 			val = (u_long)(tv.tv_sec * hz) + tv.tv_usec / tick;
1383 			if (val > SHRT_MAX) {
1384 				error = EDOM;
1385 				goto bad;
1386 			}
1387 			if (val == 0 && tv.tv_usec != 0)
1388 				val = 1;
1389 
1390 			switch (sopt->sopt_name) {
1391 			case SO_SNDTIMEO:
1392 				so->so_snd.sb_timeo = val;
1393 				break;
1394 			case SO_RCVTIMEO:
1395 				so->so_rcv.sb_timeo = val;
1396 				break;
1397 			}
1398 			break;
1399 		case SO_LABEL:
1400 #ifdef MAC
1401 			error = sooptcopyin(sopt, &extmac, sizeof extmac,
1402 			    sizeof extmac);
1403 			if (error)
1404 				goto bad;
1405 
1406 			error = mac_setsockopt_label_set(
1407 			    sopt->sopt_td->td_ucred, so, &extmac);
1408 
1409 #else
1410 			error = EOPNOTSUPP;
1411 #endif
1412 			break;
1413 		default:
1414 			error = ENOPROTOOPT;
1415 			break;
1416 		}
1417 		if (error == 0 && so->so_proto && so->so_proto->pr_ctloutput) {
1418 			(void) ((*so->so_proto->pr_ctloutput)
1419 				  (so, sopt));
1420 		}
1421 	}
1422 bad:
1423 	return (error);
1424 }
1425 
1426 /* Helper routine for getsockopt */
1427 int
1428 sooptcopyout(struct sockopt *sopt, const void *buf, size_t len)
1429 {
1430 	int	error;
1431 	size_t	valsize;
1432 
1433 	error = 0;
1434 
1435 	/*
1436 	 * Documented get behavior is that we always return a value,
1437 	 * possibly truncated to fit in the user's buffer.
1438 	 * Traditional behavior is that we always tell the user
1439 	 * precisely how much we copied, rather than something useful
1440 	 * like the total amount we had available for her.
1441 	 * Note that this interface is not idempotent; the entire answer must
1442 	 * generated ahead of time.
1443 	 */
1444 	valsize = min(len, sopt->sopt_valsize);
1445 	sopt->sopt_valsize = valsize;
1446 	if (sopt->sopt_val != 0) {
1447 		if (sopt->sopt_td != 0)
1448 			error = copyout(buf, sopt->sopt_val, valsize);
1449 		else
1450 			bcopy(buf, sopt->sopt_val, valsize);
1451 	}
1452 	return error;
1453 }
1454 
1455 int
1456 sogetopt(so, sopt)
1457 	struct socket *so;
1458 	struct sockopt *sopt;
1459 {
1460 	int	error, optval;
1461 	struct	linger l;
1462 	struct	timeval tv;
1463 #ifdef INET
1464 	struct accept_filter_arg *afap;
1465 #endif
1466 #ifdef MAC
1467 	struct mac extmac;
1468 #endif
1469 
1470 	error = 0;
1471 	if (sopt->sopt_level != SOL_SOCKET) {
1472 		if (so->so_proto && so->so_proto->pr_ctloutput) {
1473 			return ((*so->so_proto->pr_ctloutput)
1474 				  (so, sopt));
1475 		} else
1476 			return (ENOPROTOOPT);
1477 	} else {
1478 		switch (sopt->sopt_name) {
1479 #ifdef INET
1480 		case SO_ACCEPTFILTER:
1481 			if ((so->so_options & SO_ACCEPTCONN) == 0)
1482 				return (EINVAL);
1483 			MALLOC(afap, struct accept_filter_arg *, sizeof(*afap),
1484 				M_TEMP, M_WAITOK | M_ZERO);
1485 			if ((so->so_options & SO_ACCEPTFILTER) != 0) {
1486 				strcpy(afap->af_name, so->so_accf->so_accept_filter->accf_name);
1487 				if (so->so_accf->so_accept_filter_str != NULL)
1488 					strcpy(afap->af_arg, so->so_accf->so_accept_filter_str);
1489 			}
1490 			error = sooptcopyout(sopt, afap, sizeof(*afap));
1491 			FREE(afap, M_TEMP);
1492 			break;
1493 #endif
1494 
1495 		case SO_LINGER:
1496 			l.l_onoff = so->so_options & SO_LINGER;
1497 			l.l_linger = so->so_linger;
1498 			error = sooptcopyout(sopt, &l, sizeof l);
1499 			break;
1500 
1501 		case SO_USELOOPBACK:
1502 		case SO_DONTROUTE:
1503 		case SO_DEBUG:
1504 		case SO_KEEPALIVE:
1505 		case SO_REUSEADDR:
1506 		case SO_REUSEPORT:
1507 		case SO_BROADCAST:
1508 		case SO_OOBINLINE:
1509 		case SO_TIMESTAMP:
1510 		case SO_NOSIGPIPE:
1511 			optval = so->so_options & sopt->sopt_name;
1512 integer:
1513 			error = sooptcopyout(sopt, &optval, sizeof optval);
1514 			break;
1515 
1516 		case SO_TYPE:
1517 			optval = so->so_type;
1518 			goto integer;
1519 
1520 		case SO_ERROR:
1521 			optval = so->so_error;
1522 			so->so_error = 0;
1523 			goto integer;
1524 
1525 		case SO_SNDBUF:
1526 			optval = so->so_snd.sb_hiwat;
1527 			goto integer;
1528 
1529 		case SO_RCVBUF:
1530 			optval = so->so_rcv.sb_hiwat;
1531 			goto integer;
1532 
1533 		case SO_SNDLOWAT:
1534 			optval = so->so_snd.sb_lowat;
1535 			goto integer;
1536 
1537 		case SO_RCVLOWAT:
1538 			optval = so->so_rcv.sb_lowat;
1539 			goto integer;
1540 
1541 		case SO_SNDTIMEO:
1542 		case SO_RCVTIMEO:
1543 			optval = (sopt->sopt_name == SO_SNDTIMEO ?
1544 				  so->so_snd.sb_timeo : so->so_rcv.sb_timeo);
1545 
1546 			tv.tv_sec = optval / hz;
1547 			tv.tv_usec = (optval % hz) * tick;
1548 			error = sooptcopyout(sopt, &tv, sizeof tv);
1549 			break;
1550 		case SO_LABEL:
1551 #ifdef MAC
1552 			error = mac_getsockopt_label_get(
1553 			    sopt->sopt_td->td_ucred, so, &extmac);
1554 			if (error)
1555 				return (error);
1556 			error = sooptcopyout(sopt, &extmac, sizeof extmac);
1557 #else
1558 			error = EOPNOTSUPP;
1559 #endif
1560 			break;
1561 		case SO_PEERLABEL:
1562 #ifdef MAC
1563 			error = mac_getsockopt_peerlabel_get(
1564 			    sopt->sopt_td->td_ucred, so, &extmac);
1565 			if (error)
1566 				return (error);
1567 			error = sooptcopyout(sopt, &extmac, sizeof extmac);
1568 #else
1569 			error = EOPNOTSUPP;
1570 #endif
1571 			break;
1572 		default:
1573 			error = ENOPROTOOPT;
1574 			break;
1575 		}
1576 		return (error);
1577 	}
1578 }
1579 
1580 /* XXX; prepare mbuf for (__FreeBSD__ < 3) routines. */
1581 int
1582 soopt_getm(struct sockopt *sopt, struct mbuf **mp)
1583 {
1584 	struct mbuf *m, *m_prev;
1585 	int sopt_size = sopt->sopt_valsize;
1586 
1587 	MGET(m, sopt->sopt_td ? M_TRYWAIT : M_DONTWAIT, MT_DATA);
1588 	if (m == 0)
1589 		return ENOBUFS;
1590 	if (sopt_size > MLEN) {
1591 		MCLGET(m, sopt->sopt_td ? M_TRYWAIT : M_DONTWAIT);
1592 		if ((m->m_flags & M_EXT) == 0) {
1593 			m_free(m);
1594 			return ENOBUFS;
1595 		}
1596 		m->m_len = min(MCLBYTES, sopt_size);
1597 	} else {
1598 		m->m_len = min(MLEN, sopt_size);
1599 	}
1600 	sopt_size -= m->m_len;
1601 	*mp = m;
1602 	m_prev = m;
1603 
1604 	while (sopt_size) {
1605 		MGET(m, sopt->sopt_td ? M_TRYWAIT : M_DONTWAIT, MT_DATA);
1606 		if (m == 0) {
1607 			m_freem(*mp);
1608 			return ENOBUFS;
1609 		}
1610 		if (sopt_size > MLEN) {
1611 			MCLGET(m, sopt->sopt_td ? M_TRYWAIT : M_DONTWAIT);
1612 			if ((m->m_flags & M_EXT) == 0) {
1613 				m_freem(*mp);
1614 				return ENOBUFS;
1615 			}
1616 			m->m_len = min(MCLBYTES, sopt_size);
1617 		} else {
1618 			m->m_len = min(MLEN, sopt_size);
1619 		}
1620 		sopt_size -= m->m_len;
1621 		m_prev->m_next = m;
1622 		m_prev = m;
1623 	}
1624 	return 0;
1625 }
1626 
1627 /* XXX; copyin sopt data into mbuf chain for (__FreeBSD__ < 3) routines. */
1628 int
1629 soopt_mcopyin(struct sockopt *sopt, struct mbuf *m)
1630 {
1631 	struct mbuf *m0 = m;
1632 
1633 	if (sopt->sopt_val == NULL)
1634 		return 0;
1635 	while (m != NULL && sopt->sopt_valsize >= m->m_len) {
1636 		if (sopt->sopt_td != NULL) {
1637 			int error;
1638 
1639 			error = copyin(sopt->sopt_val, mtod(m, char *),
1640 				       m->m_len);
1641 			if (error != 0) {
1642 				m_freem(m0);
1643 				return(error);
1644 			}
1645 		} else
1646 			bcopy(sopt->sopt_val, mtod(m, char *), m->m_len);
1647 		sopt->sopt_valsize -= m->m_len;
1648 		(caddr_t)sopt->sopt_val += m->m_len;
1649 		m = m->m_next;
1650 	}
1651 	if (m != NULL) /* should be allocated enoughly at ip6_sooptmcopyin() */
1652 		panic("ip6_sooptmcopyin");
1653 	return 0;
1654 }
1655 
1656 /* XXX; copyout mbuf chain data into soopt for (__FreeBSD__ < 3) routines. */
1657 int
1658 soopt_mcopyout(struct sockopt *sopt, struct mbuf *m)
1659 {
1660 	struct mbuf *m0 = m;
1661 	size_t valsize = 0;
1662 
1663 	if (sopt->sopt_val == NULL)
1664 		return 0;
1665 	while (m != NULL && sopt->sopt_valsize >= m->m_len) {
1666 		if (sopt->sopt_td != NULL) {
1667 			int error;
1668 
1669 			error = copyout(mtod(m, char *), sopt->sopt_val,
1670 				       m->m_len);
1671 			if (error != 0) {
1672 				m_freem(m0);
1673 				return(error);
1674 			}
1675 		} else
1676 			bcopy(mtod(m, char *), sopt->sopt_val, m->m_len);
1677 	       sopt->sopt_valsize -= m->m_len;
1678 	       (caddr_t)sopt->sopt_val += m->m_len;
1679 	       valsize += m->m_len;
1680 	       m = m->m_next;
1681 	}
1682 	if (m != NULL) {
1683 		/* enough soopt buffer should be given from user-land */
1684 		m_freem(m0);
1685 		return(EINVAL);
1686 	}
1687 	sopt->sopt_valsize = valsize;
1688 	return 0;
1689 }
1690 
1691 void
1692 sohasoutofband(so)
1693 	struct socket *so;
1694 {
1695 	if (so->so_sigio != NULL)
1696 		pgsigio(&so->so_sigio, SIGURG, 0);
1697 	selwakeup(&so->so_rcv.sb_sel);
1698 }
1699 
1700 int
1701 sopoll(struct socket *so, int events, struct ucred *active_cred,
1702     struct thread *td)
1703 {
1704 	int revents = 0;
1705 	int s = splnet();
1706 
1707 	if (events & (POLLIN | POLLRDNORM))
1708 		if (soreadable(so))
1709 			revents |= events & (POLLIN | POLLRDNORM);
1710 
1711 	if (events & POLLINIGNEOF)
1712 		if (so->so_rcv.sb_cc >= so->so_rcv.sb_lowat ||
1713 		    !TAILQ_EMPTY(&so->so_comp) || so->so_error)
1714 			revents |= POLLINIGNEOF;
1715 
1716 	if (events & (POLLOUT | POLLWRNORM))
1717 		if (sowriteable(so))
1718 			revents |= events & (POLLOUT | POLLWRNORM);
1719 
1720 	if (events & (POLLPRI | POLLRDBAND))
1721 		if (so->so_oobmark || (so->so_state & SS_RCVATMARK))
1722 			revents |= events & (POLLPRI | POLLRDBAND);
1723 
1724 	if (revents == 0) {
1725 		if (events &
1726 		    (POLLIN | POLLINIGNEOF | POLLPRI | POLLRDNORM |
1727 		     POLLRDBAND)) {
1728 			selrecord(td, &so->so_rcv.sb_sel);
1729 			so->so_rcv.sb_flags |= SB_SEL;
1730 		}
1731 
1732 		if (events & (POLLOUT | POLLWRNORM)) {
1733 			selrecord(td, &so->so_snd.sb_sel);
1734 			so->so_snd.sb_flags |= SB_SEL;
1735 		}
1736 	}
1737 
1738 	splx(s);
1739 	return (revents);
1740 }
1741 
1742 int
1743 soo_kqfilter(struct file *fp, struct knote *kn)
1744 {
1745 	struct socket *so = kn->kn_fp->f_data;
1746 	struct sockbuf *sb;
1747 	int s;
1748 
1749 	switch (kn->kn_filter) {
1750 	case EVFILT_READ:
1751 		if (so->so_options & SO_ACCEPTCONN)
1752 			kn->kn_fop = &solisten_filtops;
1753 		else
1754 			kn->kn_fop = &soread_filtops;
1755 		sb = &so->so_rcv;
1756 		break;
1757 	case EVFILT_WRITE:
1758 		kn->kn_fop = &sowrite_filtops;
1759 		sb = &so->so_snd;
1760 		break;
1761 	default:
1762 		return (1);
1763 	}
1764 
1765 	s = splnet();
1766 	SLIST_INSERT_HEAD(&sb->sb_sel.si_note, kn, kn_selnext);
1767 	sb->sb_flags |= SB_KNOTE;
1768 	splx(s);
1769 	return (0);
1770 }
1771 
1772 static void
1773 filt_sordetach(struct knote *kn)
1774 {
1775 	struct socket *so = kn->kn_fp->f_data;
1776 	int s = splnet();
1777 
1778 	SLIST_REMOVE(&so->so_rcv.sb_sel.si_note, kn, knote, kn_selnext);
1779 	if (SLIST_EMPTY(&so->so_rcv.sb_sel.si_note))
1780 		so->so_rcv.sb_flags &= ~SB_KNOTE;
1781 	splx(s);
1782 }
1783 
1784 /*ARGSUSED*/
1785 static int
1786 filt_soread(struct knote *kn, long hint)
1787 {
1788 	struct socket *so = kn->kn_fp->f_data;
1789 
1790 	kn->kn_data = so->so_rcv.sb_cc - so->so_rcv.sb_ctl;
1791 	if (so->so_state & SS_CANTRCVMORE) {
1792 		kn->kn_flags |= EV_EOF;
1793 		kn->kn_fflags = so->so_error;
1794 		return (1);
1795 	}
1796 	if (so->so_error)	/* temporary udp error */
1797 		return (1);
1798 	if (kn->kn_sfflags & NOTE_LOWAT)
1799 		return (kn->kn_data >= kn->kn_sdata);
1800 	return (so->so_rcv.sb_cc >= so->so_rcv.sb_lowat);
1801 }
1802 
1803 static void
1804 filt_sowdetach(struct knote *kn)
1805 {
1806 	struct socket *so = kn->kn_fp->f_data;
1807 	int s = splnet();
1808 
1809 	SLIST_REMOVE(&so->so_snd.sb_sel.si_note, kn, knote, kn_selnext);
1810 	if (SLIST_EMPTY(&so->so_snd.sb_sel.si_note))
1811 		so->so_snd.sb_flags &= ~SB_KNOTE;
1812 	splx(s);
1813 }
1814 
1815 /*ARGSUSED*/
1816 static int
1817 filt_sowrite(struct knote *kn, long hint)
1818 {
1819 	struct socket *so = kn->kn_fp->f_data;
1820 
1821 	kn->kn_data = sbspace(&so->so_snd);
1822 	if (so->so_state & SS_CANTSENDMORE) {
1823 		kn->kn_flags |= EV_EOF;
1824 		kn->kn_fflags = so->so_error;
1825 		return (1);
1826 	}
1827 	if (so->so_error)	/* temporary udp error */
1828 		return (1);
1829 	if (((so->so_state & SS_ISCONNECTED) == 0) &&
1830 	    (so->so_proto->pr_flags & PR_CONNREQUIRED))
1831 		return (0);
1832 	if (kn->kn_sfflags & NOTE_LOWAT)
1833 		return (kn->kn_data >= kn->kn_sdata);
1834 	return (kn->kn_data >= so->so_snd.sb_lowat);
1835 }
1836 
1837 /*ARGSUSED*/
1838 static int
1839 filt_solisten(struct knote *kn, long hint)
1840 {
1841 	struct socket *so = kn->kn_fp->f_data;
1842 
1843 	kn->kn_data = so->so_qlen;
1844 	return (! TAILQ_EMPTY(&so->so_comp));
1845 }
1846 
1847 int
1848 socheckuid(struct socket *so, uid_t uid)
1849 {
1850 
1851 	if (so == NULL)
1852 		return (EPERM);
1853 	if (so->so_cred->cr_uid == uid)
1854 		return (0);
1855 	return (EPERM);
1856 }
1857