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