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