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