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