xref: /netbsd-src/sys/kern/uipc_socket.c (revision 500db002748d9818288e46e10f026a2b09548086)
1 /*	$NetBSD: uipc_socket.c,v 1.187 2009/03/15 17:14:40 cegger Exp $	*/
2 
3 /*-
4  * Copyright (c) 2002, 2007, 2008 The NetBSD Foundation, Inc.
5  * All rights reserved.
6  *
7  * This code is derived from software contributed to The NetBSD Foundation
8  * by Jason R. Thorpe of Wasabi Systems, Inc.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
20  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
21  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
23  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29  * POSSIBILITY OF SUCH DAMAGE.
30  */
31 
32 /*
33  * Copyright (c) 2004 The FreeBSD Foundation
34  * Copyright (c) 2004 Robert Watson
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. Neither the name of the University nor the names of its contributors
47  *    may be used to endorse or promote products derived from this software
48  *    without specific prior written permission.
49  *
50  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
51  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
52  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
53  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
54  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
55  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
56  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
57  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
58  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
59  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
60  * SUCH DAMAGE.
61  *
62  *	@(#)uipc_socket.c	8.6 (Berkeley) 5/2/95
63  */
64 
65 #include <sys/cdefs.h>
66 __KERNEL_RCSID(0, "$NetBSD: uipc_socket.c,v 1.187 2009/03/15 17:14:40 cegger Exp $");
67 
68 #include "opt_compat_netbsd.h"
69 #include "opt_sock_counters.h"
70 #include "opt_sosend_loan.h"
71 #include "opt_mbuftrace.h"
72 #include "opt_somaxkva.h"
73 #include "opt_multiprocessor.h"	/* XXX */
74 
75 #include <sys/param.h>
76 #include <sys/systm.h>
77 #include <sys/proc.h>
78 #include <sys/file.h>
79 #include <sys/filedesc.h>
80 #include <sys/kmem.h>
81 #include <sys/mbuf.h>
82 #include <sys/domain.h>
83 #include <sys/kernel.h>
84 #include <sys/protosw.h>
85 #include <sys/socket.h>
86 #include <sys/socketvar.h>
87 #include <sys/signalvar.h>
88 #include <sys/resourcevar.h>
89 #include <sys/uidinfo.h>
90 #include <sys/event.h>
91 #include <sys/poll.h>
92 #include <sys/kauth.h>
93 #include <sys/mutex.h>
94 #include <sys/condvar.h>
95 
96 #ifdef COMPAT_50
97 #include <compat/sys/time.h>
98 #include <compat/sys/socket.h>
99 #endif
100 
101 #include <uvm/uvm.h>
102 
103 MALLOC_DEFINE(M_SOOPTS, "soopts", "socket options");
104 MALLOC_DEFINE(M_SONAME, "soname", "socket name");
105 
106 extern const struct fileops socketops;
107 
108 extern int	somaxconn;			/* patchable (XXX sysctl) */
109 int		somaxconn = SOMAXCONN;
110 kmutex_t	*softnet_lock;
111 
112 #ifdef SOSEND_COUNTERS
113 #include <sys/device.h>
114 
115 static struct evcnt sosend_loan_big = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
116     NULL, "sosend", "loan big");
117 static struct evcnt sosend_copy_big = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
118     NULL, "sosend", "copy big");
119 static struct evcnt sosend_copy_small = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
120     NULL, "sosend", "copy small");
121 static struct evcnt sosend_kvalimit = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
122     NULL, "sosend", "kva limit");
123 
124 #define	SOSEND_COUNTER_INCR(ev)		(ev)->ev_count++
125 
126 EVCNT_ATTACH_STATIC(sosend_loan_big);
127 EVCNT_ATTACH_STATIC(sosend_copy_big);
128 EVCNT_ATTACH_STATIC(sosend_copy_small);
129 EVCNT_ATTACH_STATIC(sosend_kvalimit);
130 #else
131 
132 #define	SOSEND_COUNTER_INCR(ev)		/* nothing */
133 
134 #endif /* SOSEND_COUNTERS */
135 
136 static struct callback_entry sokva_reclaimerentry;
137 
138 #if defined(SOSEND_NO_LOAN) || defined(MULTIPROCESSOR)
139 int sock_loan_thresh = -1;
140 #else
141 int sock_loan_thresh = 4096;
142 #endif
143 
144 static kmutex_t so_pendfree_lock;
145 static struct mbuf *so_pendfree;
146 
147 #ifndef SOMAXKVA
148 #define	SOMAXKVA (16 * 1024 * 1024)
149 #endif
150 int somaxkva = SOMAXKVA;
151 static int socurkva;
152 static kcondvar_t socurkva_cv;
153 
154 #define	SOCK_LOAN_CHUNK		65536
155 
156 static size_t sodopendfree(void);
157 static size_t sodopendfreel(void);
158 
159 static void sysctl_kern_somaxkva_setup(void);
160 static struct sysctllog *socket_sysctllog;
161 
162 static vsize_t
163 sokvareserve(struct socket *so, vsize_t len)
164 {
165 	int error;
166 
167 	mutex_enter(&so_pendfree_lock);
168 	while (socurkva + len > somaxkva) {
169 		size_t freed;
170 
171 		/*
172 		 * try to do pendfree.
173 		 */
174 
175 		freed = sodopendfreel();
176 
177 		/*
178 		 * if some kva was freed, try again.
179 		 */
180 
181 		if (freed)
182 			continue;
183 
184 		SOSEND_COUNTER_INCR(&sosend_kvalimit);
185 		error = cv_wait_sig(&socurkva_cv, &so_pendfree_lock);
186 		if (error) {
187 			len = 0;
188 			break;
189 		}
190 	}
191 	socurkva += len;
192 	mutex_exit(&so_pendfree_lock);
193 	return len;
194 }
195 
196 static void
197 sokvaunreserve(vsize_t len)
198 {
199 
200 	mutex_enter(&so_pendfree_lock);
201 	socurkva -= len;
202 	cv_broadcast(&socurkva_cv);
203 	mutex_exit(&so_pendfree_lock);
204 }
205 
206 /*
207  * sokvaalloc: allocate kva for loan.
208  */
209 
210 vaddr_t
211 sokvaalloc(vsize_t len, struct socket *so)
212 {
213 	vaddr_t lva;
214 
215 	/*
216 	 * reserve kva.
217 	 */
218 
219 	if (sokvareserve(so, len) == 0)
220 		return 0;
221 
222 	/*
223 	 * allocate kva.
224 	 */
225 
226 	lva = uvm_km_alloc(kernel_map, len, 0, UVM_KMF_VAONLY | UVM_KMF_WAITVA);
227 	if (lva == 0) {
228 		sokvaunreserve(len);
229 		return (0);
230 	}
231 
232 	return lva;
233 }
234 
235 /*
236  * sokvafree: free kva for loan.
237  */
238 
239 void
240 sokvafree(vaddr_t sva, vsize_t len)
241 {
242 
243 	/*
244 	 * free kva.
245 	 */
246 
247 	uvm_km_free(kernel_map, sva, len, UVM_KMF_VAONLY);
248 
249 	/*
250 	 * unreserve kva.
251 	 */
252 
253 	sokvaunreserve(len);
254 }
255 
256 static void
257 sodoloanfree(struct vm_page **pgs, void *buf, size_t size)
258 {
259 	vaddr_t sva, eva;
260 	vsize_t len;
261 	int npgs;
262 
263 	KASSERT(pgs != NULL);
264 
265 	eva = round_page((vaddr_t) buf + size);
266 	sva = trunc_page((vaddr_t) buf);
267 	len = eva - sva;
268 	npgs = len >> PAGE_SHIFT;
269 
270 	pmap_kremove(sva, len);
271 	pmap_update(pmap_kernel());
272 	uvm_unloan(pgs, npgs, UVM_LOAN_TOPAGE);
273 	sokvafree(sva, len);
274 }
275 
276 static size_t
277 sodopendfree(void)
278 {
279 	size_t rv;
280 
281 	if (__predict_true(so_pendfree == NULL))
282 		return 0;
283 
284 	mutex_enter(&so_pendfree_lock);
285 	rv = sodopendfreel();
286 	mutex_exit(&so_pendfree_lock);
287 
288 	return rv;
289 }
290 
291 /*
292  * sodopendfreel: free mbufs on "pendfree" list.
293  * unlock and relock so_pendfree_lock when freeing mbufs.
294  *
295  * => called with so_pendfree_lock held.
296  */
297 
298 static size_t
299 sodopendfreel(void)
300 {
301 	struct mbuf *m, *next;
302 	size_t rv = 0;
303 
304 	KASSERT(mutex_owned(&so_pendfree_lock));
305 
306 	while (so_pendfree != NULL) {
307 		m = so_pendfree;
308 		so_pendfree = NULL;
309 		mutex_exit(&so_pendfree_lock);
310 
311 		for (; m != NULL; m = next) {
312 			next = m->m_next;
313 			KASSERT((~m->m_flags & (M_EXT|M_EXT_PAGES)) == 0);
314 			KASSERT(m->m_ext.ext_refcnt == 0);
315 
316 			rv += m->m_ext.ext_size;
317 			sodoloanfree(m->m_ext.ext_pgs, m->m_ext.ext_buf,
318 			    m->m_ext.ext_size);
319 			pool_cache_put(mb_cache, m);
320 		}
321 
322 		mutex_enter(&so_pendfree_lock);
323 	}
324 
325 	return (rv);
326 }
327 
328 void
329 soloanfree(struct mbuf *m, void *buf, size_t size, void *arg)
330 {
331 
332 	KASSERT(m != NULL);
333 
334 	/*
335 	 * postpone freeing mbuf.
336 	 *
337 	 * we can't do it in interrupt context
338 	 * because we need to put kva back to kernel_map.
339 	 */
340 
341 	mutex_enter(&so_pendfree_lock);
342 	m->m_next = so_pendfree;
343 	so_pendfree = m;
344 	cv_broadcast(&socurkva_cv);
345 	mutex_exit(&so_pendfree_lock);
346 }
347 
348 static long
349 sosend_loan(struct socket *so, struct uio *uio, struct mbuf *m, long space)
350 {
351 	struct iovec *iov = uio->uio_iov;
352 	vaddr_t sva, eva;
353 	vsize_t len;
354 	vaddr_t lva;
355 	int npgs, error;
356 	vaddr_t va;
357 	int i;
358 
359 	if (VMSPACE_IS_KERNEL_P(uio->uio_vmspace))
360 		return (0);
361 
362 	if (iov->iov_len < (size_t) space)
363 		space = iov->iov_len;
364 	if (space > SOCK_LOAN_CHUNK)
365 		space = SOCK_LOAN_CHUNK;
366 
367 	eva = round_page((vaddr_t) iov->iov_base + space);
368 	sva = trunc_page((vaddr_t) iov->iov_base);
369 	len = eva - sva;
370 	npgs = len >> PAGE_SHIFT;
371 
372 	KASSERT(npgs <= M_EXT_MAXPAGES);
373 
374 	lva = sokvaalloc(len, so);
375 	if (lva == 0)
376 		return 0;
377 
378 	error = uvm_loan(&uio->uio_vmspace->vm_map, sva, len,
379 	    m->m_ext.ext_pgs, UVM_LOAN_TOPAGE);
380 	if (error) {
381 		sokvafree(lva, len);
382 		return (0);
383 	}
384 
385 	for (i = 0, va = lva; i < npgs; i++, va += PAGE_SIZE)
386 		pmap_kenter_pa(va, VM_PAGE_TO_PHYS(m->m_ext.ext_pgs[i]),
387 		    VM_PROT_READ);
388 	pmap_update(pmap_kernel());
389 
390 	lva += (vaddr_t) iov->iov_base & PAGE_MASK;
391 
392 	MEXTADD(m, (void *) lva, space, M_MBUF, soloanfree, so);
393 	m->m_flags |= M_EXT_PAGES | M_EXT_ROMAP;
394 
395 	uio->uio_resid -= space;
396 	/* uio_offset not updated, not set/used for write(2) */
397 	uio->uio_iov->iov_base = (char *)uio->uio_iov->iov_base + space;
398 	uio->uio_iov->iov_len -= space;
399 	if (uio->uio_iov->iov_len == 0) {
400 		uio->uio_iov++;
401 		uio->uio_iovcnt--;
402 	}
403 
404 	return (space);
405 }
406 
407 static int
408 sokva_reclaim_callback(struct callback_entry *ce, void *obj, void *arg)
409 {
410 
411 	KASSERT(ce == &sokva_reclaimerentry);
412 	KASSERT(obj == NULL);
413 
414 	sodopendfree();
415 	if (!vm_map_starved_p(kernel_map)) {
416 		return CALLBACK_CHAIN_ABORT;
417 	}
418 	return CALLBACK_CHAIN_CONTINUE;
419 }
420 
421 struct mbuf *
422 getsombuf(struct socket *so, int type)
423 {
424 	struct mbuf *m;
425 
426 	m = m_get(M_WAIT, type);
427 	MCLAIM(m, so->so_mowner);
428 	return m;
429 }
430 
431 void
432 soinit(void)
433 {
434 
435 	sysctl_kern_somaxkva_setup();
436 
437 	mutex_init(&so_pendfree_lock, MUTEX_DEFAULT, IPL_VM);
438 	softnet_lock = mutex_obj_alloc(MUTEX_DEFAULT, IPL_NONE);
439 	cv_init(&socurkva_cv, "sokva");
440 	soinit2();
441 
442 	/* Set the initial adjusted socket buffer size. */
443 	if (sb_max_set(sb_max))
444 		panic("bad initial sb_max value: %lu", sb_max);
445 
446 	callback_register(&vm_map_to_kernel(kernel_map)->vmk_reclaim_callback,
447 	    &sokva_reclaimerentry, NULL, sokva_reclaim_callback);
448 }
449 
450 /*
451  * Socket operation routines.
452  * These routines are called by the routines in
453  * sys_socket.c or from a system process, and
454  * implement the semantics of socket operations by
455  * switching out to the protocol specific routines.
456  */
457 /*ARGSUSED*/
458 int
459 socreate(int dom, struct socket **aso, int type, int proto, struct lwp *l,
460 	 struct socket *lockso)
461 {
462 	const struct protosw	*prp;
463 	struct socket	*so;
464 	uid_t		uid;
465 	int		error;
466 	kmutex_t	*lock;
467 
468 	error = kauth_authorize_network(l->l_cred, KAUTH_NETWORK_SOCKET,
469 	    KAUTH_REQ_NETWORK_SOCKET_OPEN, KAUTH_ARG(dom), KAUTH_ARG(type),
470 	    KAUTH_ARG(proto));
471 	if (error != 0)
472 		return error;
473 
474 	if (proto)
475 		prp = pffindproto(dom, proto, type);
476 	else
477 		prp = pffindtype(dom, type);
478 	if (prp == NULL) {
479 		/* no support for domain */
480 		if (pffinddomain(dom) == 0)
481 			return EAFNOSUPPORT;
482 		/* no support for socket type */
483 		if (proto == 0 && type != 0)
484 			return EPROTOTYPE;
485 		return EPROTONOSUPPORT;
486 	}
487 	if (prp->pr_usrreq == NULL)
488 		return EPROTONOSUPPORT;
489 	if (prp->pr_type != type)
490 		return EPROTOTYPE;
491 
492 	so = soget(true);
493 	so->so_type = type;
494 	so->so_proto = prp;
495 	so->so_send = sosend;
496 	so->so_receive = soreceive;
497 #ifdef MBUFTRACE
498 	so->so_rcv.sb_mowner = &prp->pr_domain->dom_mowner;
499 	so->so_snd.sb_mowner = &prp->pr_domain->dom_mowner;
500 	so->so_mowner = &prp->pr_domain->dom_mowner;
501 #endif
502 	uid = kauth_cred_geteuid(l->l_cred);
503 	so->so_uidinfo = uid_find(uid);
504 	so->so_egid = kauth_cred_getegid(l->l_cred);
505 	so->so_cpid = l->l_proc->p_pid;
506 	if (lockso != NULL) {
507 		/* Caller wants us to share a lock. */
508 		lock = lockso->so_lock;
509 		so->so_lock = lock;
510 		mutex_obj_hold(lock);
511 		mutex_enter(lock);
512 	} else {
513 		/* Lock assigned and taken during PRU_ATTACH. */
514 	}
515 	error = (*prp->pr_usrreq)(so, PRU_ATTACH, NULL,
516 	    (struct mbuf *)(long)proto, NULL, l);
517 	KASSERT(solocked(so));
518 	if (error != 0) {
519 		so->so_state |= SS_NOFDREF;
520 		sofree(so);
521 		return error;
522 	}
523 	sounlock(so);
524 	*aso = so;
525 	return 0;
526 }
527 
528 /* On success, write file descriptor to fdout and return zero.  On
529  * failure, return non-zero; *fdout will be undefined.
530  */
531 int
532 fsocreate(int domain, struct socket **sop, int type, int protocol,
533     struct lwp *l, int *fdout)
534 {
535 	struct socket	*so;
536 	struct file	*fp;
537 	int		fd, error;
538 
539 	if ((error = fd_allocfile(&fp, &fd)) != 0)
540 		return (error);
541 	fp->f_flag = FREAD|FWRITE;
542 	fp->f_type = DTYPE_SOCKET;
543 	fp->f_ops = &socketops;
544 	error = socreate(domain, &so, type, protocol, l, NULL);
545 	if (error != 0) {
546 		fd_abort(curproc, fp, fd);
547 	} else {
548 		if (sop != NULL)
549 			*sop = so;
550 		fp->f_data = so;
551 		fd_affix(curproc, fp, fd);
552 		*fdout = fd;
553 	}
554 	return error;
555 }
556 
557 int
558 sobind(struct socket *so, struct mbuf *nam, struct lwp *l)
559 {
560 	int	error;
561 
562 	solock(so);
563 	error = (*so->so_proto->pr_usrreq)(so, PRU_BIND, NULL, nam, NULL, l);
564 	sounlock(so);
565 	return error;
566 }
567 
568 int
569 solisten(struct socket *so, int backlog, struct lwp *l)
570 {
571 	int	error;
572 
573 	solock(so);
574 	if ((so->so_state & (SS_ISCONNECTED | SS_ISCONNECTING |
575 	    SS_ISDISCONNECTING)) != 0) {
576 	    	sounlock(so);
577 		return (EOPNOTSUPP);
578 	}
579 	error = (*so->so_proto->pr_usrreq)(so, PRU_LISTEN, NULL,
580 	    NULL, NULL, l);
581 	if (error != 0) {
582 		sounlock(so);
583 		return error;
584 	}
585 	if (TAILQ_EMPTY(&so->so_q))
586 		so->so_options |= SO_ACCEPTCONN;
587 	if (backlog < 0)
588 		backlog = 0;
589 	so->so_qlimit = min(backlog, somaxconn);
590 	sounlock(so);
591 	return 0;
592 }
593 
594 void
595 sofree(struct socket *so)
596 {
597 	u_int refs;
598 
599 	KASSERT(solocked(so));
600 
601 	if (so->so_pcb || (so->so_state & SS_NOFDREF) == 0) {
602 		sounlock(so);
603 		return;
604 	}
605 	if (so->so_head) {
606 		/*
607 		 * We must not decommission a socket that's on the accept(2)
608 		 * queue.  If we do, then accept(2) may hang after select(2)
609 		 * indicated that the listening socket was ready.
610 		 */
611 		if (!soqremque(so, 0)) {
612 			sounlock(so);
613 			return;
614 		}
615 	}
616 	if (so->so_rcv.sb_hiwat)
617 		(void)chgsbsize(so->so_uidinfo, &so->so_rcv.sb_hiwat, 0,
618 		    RLIM_INFINITY);
619 	if (so->so_snd.sb_hiwat)
620 		(void)chgsbsize(so->so_uidinfo, &so->so_snd.sb_hiwat, 0,
621 		    RLIM_INFINITY);
622 	sbrelease(&so->so_snd, so);
623 	KASSERT(!cv_has_waiters(&so->so_cv));
624 	KASSERT(!cv_has_waiters(&so->so_rcv.sb_cv));
625 	KASSERT(!cv_has_waiters(&so->so_snd.sb_cv));
626 	sorflush(so);
627 	refs = so->so_aborting;	/* XXX */
628 	/* Remove acccept filter if one is present. */
629 	if (so->so_accf != NULL)
630 		(void)accept_filt_clear(so);
631 	sounlock(so);
632 	if (refs == 0)		/* XXX */
633 		soput(so);
634 }
635 
636 /*
637  * Close a socket on last file table reference removal.
638  * Initiate disconnect if connected.
639  * Free socket when disconnect complete.
640  */
641 int
642 soclose(struct socket *so)
643 {
644 	struct socket	*so2;
645 	int		error;
646 	int		error2;
647 
648 	error = 0;
649 	solock(so);
650 	if (so->so_options & SO_ACCEPTCONN) {
651 		for (;;) {
652 			if ((so2 = TAILQ_FIRST(&so->so_q0)) != 0) {
653 				KASSERT(solocked2(so, so2));
654 				(void) soqremque(so2, 0);
655 				/* soabort drops the lock. */
656 				(void) soabort(so2);
657 				solock(so);
658 				continue;
659 			}
660 			if ((so2 = TAILQ_FIRST(&so->so_q)) != 0) {
661 				KASSERT(solocked2(so, so2));
662 				(void) soqremque(so2, 1);
663 				/* soabort drops the lock. */
664 				(void) soabort(so2);
665 				solock(so);
666 				continue;
667 			}
668 			break;
669 		}
670 	}
671 	if (so->so_pcb == 0)
672 		goto discard;
673 	if (so->so_state & SS_ISCONNECTED) {
674 		if ((so->so_state & SS_ISDISCONNECTING) == 0) {
675 			error = sodisconnect(so);
676 			if (error)
677 				goto drop;
678 		}
679 		if (so->so_options & SO_LINGER) {
680 			if ((so->so_state & SS_ISDISCONNECTING) && so->so_nbio)
681 				goto drop;
682 			while (so->so_state & SS_ISCONNECTED) {
683 				error = sowait(so, true, so->so_linger * hz);
684 				if (error)
685 					break;
686 			}
687 		}
688 	}
689  drop:
690 	if (so->so_pcb) {
691 		error2 = (*so->so_proto->pr_usrreq)(so, PRU_DETACH,
692 		    NULL, NULL, NULL, NULL);
693 		if (error == 0)
694 			error = error2;
695 	}
696  discard:
697 	if (so->so_state & SS_NOFDREF)
698 		panic("soclose: NOFDREF");
699 	so->so_state |= SS_NOFDREF;
700 	sofree(so);
701 	return (error);
702 }
703 
704 /*
705  * Must be called with the socket locked..  Will return with it unlocked.
706  */
707 int
708 soabort(struct socket *so)
709 {
710 	u_int refs;
711 	int error;
712 
713 	KASSERT(solocked(so));
714 	KASSERT(so->so_head == NULL);
715 
716 	so->so_aborting++;		/* XXX */
717 	error = (*so->so_proto->pr_usrreq)(so, PRU_ABORT, NULL,
718 	    NULL, NULL, NULL);
719 	refs = --so->so_aborting;	/* XXX */
720 	if (error || (refs == 0)) {
721 		sofree(so);
722 	} else {
723 		sounlock(so);
724 	}
725 	return error;
726 }
727 
728 int
729 soaccept(struct socket *so, struct mbuf *nam)
730 {
731 	int	error;
732 
733 	KASSERT(solocked(so));
734 
735 	error = 0;
736 	if ((so->so_state & SS_NOFDREF) == 0)
737 		panic("soaccept: !NOFDREF");
738 	so->so_state &= ~SS_NOFDREF;
739 	if ((so->so_state & SS_ISDISCONNECTED) == 0 ||
740 	    (so->so_proto->pr_flags & PR_ABRTACPTDIS) == 0)
741 		error = (*so->so_proto->pr_usrreq)(so, PRU_ACCEPT,
742 		    NULL, nam, NULL, NULL);
743 	else
744 		error = ECONNABORTED;
745 
746 	return (error);
747 }
748 
749 int
750 soconnect(struct socket *so, struct mbuf *nam, struct lwp *l)
751 {
752 	int		error;
753 
754 	KASSERT(solocked(so));
755 
756 	if (so->so_options & SO_ACCEPTCONN)
757 		return (EOPNOTSUPP);
758 	/*
759 	 * If protocol is connection-based, can only connect once.
760 	 * Otherwise, if connected, try to disconnect first.
761 	 * This allows user to disconnect by connecting to, e.g.,
762 	 * a null address.
763 	 */
764 	if (so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING) &&
765 	    ((so->so_proto->pr_flags & PR_CONNREQUIRED) ||
766 	    (error = sodisconnect(so))))
767 		error = EISCONN;
768 	else
769 		error = (*so->so_proto->pr_usrreq)(so, PRU_CONNECT,
770 		    NULL, nam, NULL, l);
771 	return (error);
772 }
773 
774 int
775 soconnect2(struct socket *so1, struct socket *so2)
776 {
777 	int	error;
778 
779 	KASSERT(solocked2(so1, so2));
780 
781 	error = (*so1->so_proto->pr_usrreq)(so1, PRU_CONNECT2,
782 	    NULL, (struct mbuf *)so2, NULL, NULL);
783 	return (error);
784 }
785 
786 int
787 sodisconnect(struct socket *so)
788 {
789 	int	error;
790 
791 	KASSERT(solocked(so));
792 
793 	if ((so->so_state & SS_ISCONNECTED) == 0) {
794 		error = ENOTCONN;
795 	} else if (so->so_state & SS_ISDISCONNECTING) {
796 		error = EALREADY;
797 	} else {
798 		error = (*so->so_proto->pr_usrreq)(so, PRU_DISCONNECT,
799 		    NULL, NULL, NULL, NULL);
800 	}
801 	sodopendfree();
802 	return (error);
803 }
804 
805 #define	SBLOCKWAIT(f)	(((f) & MSG_DONTWAIT) ? M_NOWAIT : M_WAITOK)
806 /*
807  * Send on a socket.
808  * If send must go all at once and message is larger than
809  * send buffering, then hard error.
810  * Lock against other senders.
811  * If must go all at once and not enough room now, then
812  * inform user that this would block and do nothing.
813  * Otherwise, if nonblocking, send as much as possible.
814  * The data to be sent is described by "uio" if nonzero,
815  * otherwise by the mbuf chain "top" (which must be null
816  * if uio is not).  Data provided in mbuf chain must be small
817  * enough to send all at once.
818  *
819  * Returns nonzero on error, timeout or signal; callers
820  * must check for short counts if EINTR/ERESTART are returned.
821  * Data and control buffers are freed on return.
822  */
823 int
824 sosend(struct socket *so, struct mbuf *addr, struct uio *uio, struct mbuf *top,
825 	struct mbuf *control, int flags, struct lwp *l)
826 {
827 	struct mbuf	**mp, *m;
828 	struct proc	*p;
829 	long		space, len, resid, clen, mlen;
830 	int		error, s, dontroute, atomic;
831 
832 	p = l->l_proc;
833 	sodopendfree();
834 	clen = 0;
835 
836 	/*
837 	 * solock() provides atomicity of access.  splsoftnet() prevents
838 	 * protocol processing soft interrupts from interrupting us and
839 	 * blocking (expensive).
840 	 */
841 	s = splsoftnet();
842 	solock(so);
843 	atomic = sosendallatonce(so) || top;
844 	if (uio)
845 		resid = uio->uio_resid;
846 	else
847 		resid = top->m_pkthdr.len;
848 	/*
849 	 * In theory resid should be unsigned.
850 	 * However, space must be signed, as it might be less than 0
851 	 * if we over-committed, and we must use a signed comparison
852 	 * of space and resid.  On the other hand, a negative resid
853 	 * causes us to loop sending 0-length segments to the protocol.
854 	 */
855 	if (resid < 0) {
856 		error = EINVAL;
857 		goto out;
858 	}
859 	dontroute =
860 	    (flags & MSG_DONTROUTE) && (so->so_options & SO_DONTROUTE) == 0 &&
861 	    (so->so_proto->pr_flags & PR_ATOMIC);
862 	l->l_ru.ru_msgsnd++;
863 	if (control)
864 		clen = control->m_len;
865  restart:
866 	if ((error = sblock(&so->so_snd, SBLOCKWAIT(flags))) != 0)
867 		goto out;
868 	do {
869 		if (so->so_state & SS_CANTSENDMORE) {
870 			error = EPIPE;
871 			goto release;
872 		}
873 		if (so->so_error) {
874 			error = so->so_error;
875 			so->so_error = 0;
876 			goto release;
877 		}
878 		if ((so->so_state & SS_ISCONNECTED) == 0) {
879 			if (so->so_proto->pr_flags & PR_CONNREQUIRED) {
880 				if ((so->so_state & SS_ISCONFIRMING) == 0 &&
881 				    !(resid == 0 && clen != 0)) {
882 					error = ENOTCONN;
883 					goto release;
884 				}
885 			} else if (addr == 0) {
886 				error = EDESTADDRREQ;
887 				goto release;
888 			}
889 		}
890 		space = sbspace(&so->so_snd);
891 		if (flags & MSG_OOB)
892 			space += 1024;
893 		if ((atomic && resid > so->so_snd.sb_hiwat) ||
894 		    clen > so->so_snd.sb_hiwat) {
895 			error = EMSGSIZE;
896 			goto release;
897 		}
898 		if (space < resid + clen &&
899 		    (atomic || space < so->so_snd.sb_lowat || space < clen)) {
900 			if (so->so_nbio) {
901 				error = EWOULDBLOCK;
902 				goto release;
903 			}
904 			sbunlock(&so->so_snd);
905 			error = sbwait(&so->so_snd);
906 			if (error)
907 				goto out;
908 			goto restart;
909 		}
910 		mp = &top;
911 		space -= clen;
912 		do {
913 			if (uio == NULL) {
914 				/*
915 				 * Data is prepackaged in "top".
916 				 */
917 				resid = 0;
918 				if (flags & MSG_EOR)
919 					top->m_flags |= M_EOR;
920 			} else do {
921 				sounlock(so);
922 				splx(s);
923 				if (top == NULL) {
924 					m = m_gethdr(M_WAIT, MT_DATA);
925 					mlen = MHLEN;
926 					m->m_pkthdr.len = 0;
927 					m->m_pkthdr.rcvif = NULL;
928 				} else {
929 					m = m_get(M_WAIT, MT_DATA);
930 					mlen = MLEN;
931 				}
932 				MCLAIM(m, so->so_snd.sb_mowner);
933 				if (sock_loan_thresh >= 0 &&
934 				    uio->uio_iov->iov_len >= sock_loan_thresh &&
935 				    space >= sock_loan_thresh &&
936 				    (len = sosend_loan(so, uio, m,
937 						       space)) != 0) {
938 					SOSEND_COUNTER_INCR(&sosend_loan_big);
939 					space -= len;
940 					goto have_data;
941 				}
942 				if (resid >= MINCLSIZE && space >= MCLBYTES) {
943 					SOSEND_COUNTER_INCR(&sosend_copy_big);
944 					m_clget(m, M_WAIT);
945 					if ((m->m_flags & M_EXT) == 0)
946 						goto nopages;
947 					mlen = MCLBYTES;
948 					if (atomic && top == 0) {
949 						len = lmin(MCLBYTES - max_hdr,
950 						    resid);
951 						m->m_data += max_hdr;
952 					} else
953 						len = lmin(MCLBYTES, resid);
954 					space -= len;
955 				} else {
956  nopages:
957 					SOSEND_COUNTER_INCR(&sosend_copy_small);
958 					len = lmin(lmin(mlen, resid), space);
959 					space -= len;
960 					/*
961 					 * For datagram protocols, leave room
962 					 * for protocol headers in first mbuf.
963 					 */
964 					if (atomic && top == 0 && len < mlen)
965 						MH_ALIGN(m, len);
966 				}
967 				error = uiomove(mtod(m, void *), (int)len, uio);
968  have_data:
969 				resid = uio->uio_resid;
970 				m->m_len = len;
971 				*mp = m;
972 				top->m_pkthdr.len += len;
973 				s = splsoftnet();
974 				solock(so);
975 				if (error != 0)
976 					goto release;
977 				mp = &m->m_next;
978 				if (resid <= 0) {
979 					if (flags & MSG_EOR)
980 						top->m_flags |= M_EOR;
981 					break;
982 				}
983 			} while (space > 0 && atomic);
984 
985 			if (so->so_state & SS_CANTSENDMORE) {
986 				error = EPIPE;
987 				goto release;
988 			}
989 			if (dontroute)
990 				so->so_options |= SO_DONTROUTE;
991 			if (resid > 0)
992 				so->so_state |= SS_MORETOCOME;
993 			error = (*so->so_proto->pr_usrreq)(so,
994 			    (flags & MSG_OOB) ? PRU_SENDOOB : PRU_SEND,
995 			    top, addr, control, curlwp);
996 			if (dontroute)
997 				so->so_options &= ~SO_DONTROUTE;
998 			if (resid > 0)
999 				so->so_state &= ~SS_MORETOCOME;
1000 			clen = 0;
1001 			control = NULL;
1002 			top = NULL;
1003 			mp = &top;
1004 			if (error != 0)
1005 				goto release;
1006 		} while (resid && space > 0);
1007 	} while (resid);
1008 
1009  release:
1010 	sbunlock(&so->so_snd);
1011  out:
1012 	sounlock(so);
1013 	splx(s);
1014 	if (top)
1015 		m_freem(top);
1016 	if (control)
1017 		m_freem(control);
1018 	return (error);
1019 }
1020 
1021 /*
1022  * Following replacement or removal of the first mbuf on the first
1023  * mbuf chain of a socket buffer, push necessary state changes back
1024  * into the socket buffer so that other consumers see the values
1025  * consistently.  'nextrecord' is the callers locally stored value of
1026  * the original value of sb->sb_mb->m_nextpkt which must be restored
1027  * when the lead mbuf changes.  NOTE: 'nextrecord' may be NULL.
1028  */
1029 static void
1030 sbsync(struct sockbuf *sb, struct mbuf *nextrecord)
1031 {
1032 
1033 	KASSERT(solocked(sb->sb_so));
1034 
1035 	/*
1036 	 * First, update for the new value of nextrecord.  If necessary,
1037 	 * make it the first record.
1038 	 */
1039 	if (sb->sb_mb != NULL)
1040 		sb->sb_mb->m_nextpkt = nextrecord;
1041 	else
1042 		sb->sb_mb = nextrecord;
1043 
1044         /*
1045          * Now update any dependent socket buffer fields to reflect
1046          * the new state.  This is an inline of SB_EMPTY_FIXUP, with
1047          * the addition of a second clause that takes care of the
1048          * case where sb_mb has been updated, but remains the last
1049          * record.
1050          */
1051         if (sb->sb_mb == NULL) {
1052                 sb->sb_mbtail = NULL;
1053                 sb->sb_lastrecord = NULL;
1054         } else if (sb->sb_mb->m_nextpkt == NULL)
1055                 sb->sb_lastrecord = sb->sb_mb;
1056 }
1057 
1058 /*
1059  * Implement receive operations on a socket.
1060  * We depend on the way that records are added to the sockbuf
1061  * by sbappend*.  In particular, each record (mbufs linked through m_next)
1062  * must begin with an address if the protocol so specifies,
1063  * followed by an optional mbuf or mbufs containing ancillary data,
1064  * and then zero or more mbufs of data.
1065  * In order to avoid blocking network interrupts for the entire time here,
1066  * we splx() while doing the actual copy to user space.
1067  * Although the sockbuf is locked, new data may still be appended,
1068  * and thus we must maintain consistency of the sockbuf during that time.
1069  *
1070  * The caller may receive the data as a single mbuf chain by supplying
1071  * an mbuf **mp0 for use in returning the chain.  The uio is then used
1072  * only for the count in uio_resid.
1073  */
1074 int
1075 soreceive(struct socket *so, struct mbuf **paddr, struct uio *uio,
1076 	struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
1077 {
1078 	struct lwp *l = curlwp;
1079 	struct mbuf	*m, **mp, *mt;
1080 	int atomic, flags, len, error, s, offset, moff, type, orig_resid;
1081 	const struct protosw	*pr;
1082 	struct mbuf	*nextrecord;
1083 	int		mbuf_removed = 0;
1084 	const struct domain *dom;
1085 
1086 	pr = so->so_proto;
1087 	atomic = pr->pr_flags & PR_ATOMIC;
1088 	dom = pr->pr_domain;
1089 	mp = mp0;
1090 	type = 0;
1091 	orig_resid = uio->uio_resid;
1092 
1093 	if (paddr != NULL)
1094 		*paddr = NULL;
1095 	if (controlp != NULL)
1096 		*controlp = NULL;
1097 	if (flagsp != NULL)
1098 		flags = *flagsp &~ MSG_EOR;
1099 	else
1100 		flags = 0;
1101 
1102 	if ((flags & MSG_DONTWAIT) == 0)
1103 		sodopendfree();
1104 
1105 	if (flags & MSG_OOB) {
1106 		m = m_get(M_WAIT, MT_DATA);
1107 		solock(so);
1108 		error = (*pr->pr_usrreq)(so, PRU_RCVOOB, m,
1109 		    (struct mbuf *)(long)(flags & MSG_PEEK), NULL, l);
1110 		sounlock(so);
1111 		if (error)
1112 			goto bad;
1113 		do {
1114 			error = uiomove(mtod(m, void *),
1115 			    (int) min(uio->uio_resid, m->m_len), uio);
1116 			m = m_free(m);
1117 		} while (uio->uio_resid > 0 && error == 0 && m);
1118  bad:
1119 		if (m != NULL)
1120 			m_freem(m);
1121 		return error;
1122 	}
1123 	if (mp != NULL)
1124 		*mp = NULL;
1125 
1126 	/*
1127 	 * solock() provides atomicity of access.  splsoftnet() prevents
1128 	 * protocol processing soft interrupts from interrupting us and
1129 	 * blocking (expensive).
1130 	 */
1131 	s = splsoftnet();
1132 	solock(so);
1133 	if (so->so_state & SS_ISCONFIRMING && uio->uio_resid)
1134 		(*pr->pr_usrreq)(so, PRU_RCVD, NULL, NULL, NULL, l);
1135 
1136  restart:
1137 	if ((error = sblock(&so->so_rcv, SBLOCKWAIT(flags))) != 0) {
1138 		sounlock(so);
1139 		splx(s);
1140 		return error;
1141 	}
1142 
1143 	m = so->so_rcv.sb_mb;
1144 	/*
1145 	 * If we have less data than requested, block awaiting more
1146 	 * (subject to any timeout) if:
1147 	 *   1. the current count is less than the low water mark,
1148 	 *   2. MSG_WAITALL is set, and it is possible to do the entire
1149 	 *	receive operation at once if we block (resid <= hiwat), or
1150 	 *   3. MSG_DONTWAIT is not set.
1151 	 * If MSG_WAITALL is set but resid is larger than the receive buffer,
1152 	 * we have to do the receive in sections, and thus risk returning
1153 	 * a short count if a timeout or signal occurs after we start.
1154 	 */
1155 	if (m == NULL ||
1156 	    ((flags & MSG_DONTWAIT) == 0 &&
1157 	     so->so_rcv.sb_cc < uio->uio_resid &&
1158 	     (so->so_rcv.sb_cc < so->so_rcv.sb_lowat ||
1159 	      ((flags & MSG_WAITALL) &&
1160 	       uio->uio_resid <= so->so_rcv.sb_hiwat)) &&
1161 	     m->m_nextpkt == NULL && !atomic)) {
1162 #ifdef DIAGNOSTIC
1163 		if (m == NULL && so->so_rcv.sb_cc)
1164 			panic("receive 1");
1165 #endif
1166 		if (so->so_error) {
1167 			if (m != NULL)
1168 				goto dontblock;
1169 			error = so->so_error;
1170 			if ((flags & MSG_PEEK) == 0)
1171 				so->so_error = 0;
1172 			goto release;
1173 		}
1174 		if (so->so_state & SS_CANTRCVMORE) {
1175 			if (m != NULL)
1176 				goto dontblock;
1177 			else
1178 				goto release;
1179 		}
1180 		for (; m != NULL; m = m->m_next)
1181 			if (m->m_type == MT_OOBDATA  || (m->m_flags & M_EOR)) {
1182 				m = so->so_rcv.sb_mb;
1183 				goto dontblock;
1184 			}
1185 		if ((so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING)) == 0 &&
1186 		    (so->so_proto->pr_flags & PR_CONNREQUIRED)) {
1187 			error = ENOTCONN;
1188 			goto release;
1189 		}
1190 		if (uio->uio_resid == 0)
1191 			goto release;
1192 		if (so->so_nbio || (flags & MSG_DONTWAIT)) {
1193 			error = EWOULDBLOCK;
1194 			goto release;
1195 		}
1196 		SBLASTRECORDCHK(&so->so_rcv, "soreceive sbwait 1");
1197 		SBLASTMBUFCHK(&so->so_rcv, "soreceive sbwait 1");
1198 		sbunlock(&so->so_rcv);
1199 		error = sbwait(&so->so_rcv);
1200 		if (error != 0) {
1201 			sounlock(so);
1202 			splx(s);
1203 			return error;
1204 		}
1205 		goto restart;
1206 	}
1207  dontblock:
1208 	/*
1209 	 * On entry here, m points to the first record of the socket buffer.
1210 	 * From this point onward, we maintain 'nextrecord' as a cache of the
1211 	 * pointer to the next record in the socket buffer.  We must keep the
1212 	 * various socket buffer pointers and local stack versions of the
1213 	 * pointers in sync, pushing out modifications before dropping the
1214 	 * socket lock, and re-reading them when picking it up.
1215 	 *
1216 	 * Otherwise, we will race with the network stack appending new data
1217 	 * or records onto the socket buffer by using inconsistent/stale
1218 	 * versions of the field, possibly resulting in socket buffer
1219 	 * corruption.
1220 	 *
1221 	 * By holding the high-level sblock(), we prevent simultaneous
1222 	 * readers from pulling off the front of the socket buffer.
1223 	 */
1224 	if (l != NULL)
1225 		l->l_ru.ru_msgrcv++;
1226 	KASSERT(m == so->so_rcv.sb_mb);
1227 	SBLASTRECORDCHK(&so->so_rcv, "soreceive 1");
1228 	SBLASTMBUFCHK(&so->so_rcv, "soreceive 1");
1229 	nextrecord = m->m_nextpkt;
1230 	if (pr->pr_flags & PR_ADDR) {
1231 #ifdef DIAGNOSTIC
1232 		if (m->m_type != MT_SONAME)
1233 			panic("receive 1a");
1234 #endif
1235 		orig_resid = 0;
1236 		if (flags & MSG_PEEK) {
1237 			if (paddr)
1238 				*paddr = m_copy(m, 0, m->m_len);
1239 			m = m->m_next;
1240 		} else {
1241 			sbfree(&so->so_rcv, m);
1242 			mbuf_removed = 1;
1243 			if (paddr != NULL) {
1244 				*paddr = m;
1245 				so->so_rcv.sb_mb = m->m_next;
1246 				m->m_next = NULL;
1247 				m = so->so_rcv.sb_mb;
1248 			} else {
1249 				MFREE(m, so->so_rcv.sb_mb);
1250 				m = so->so_rcv.sb_mb;
1251 			}
1252 			sbsync(&so->so_rcv, nextrecord);
1253 		}
1254 	}
1255 
1256 	/*
1257 	 * Process one or more MT_CONTROL mbufs present before any data mbufs
1258 	 * in the first mbuf chain on the socket buffer.  If MSG_PEEK, we
1259 	 * just copy the data; if !MSG_PEEK, we call into the protocol to
1260 	 * perform externalization (or freeing if controlp == NULL).
1261 	 */
1262 	if (__predict_false(m != NULL && m->m_type == MT_CONTROL)) {
1263 		struct mbuf *cm = NULL, *cmn;
1264 		struct mbuf **cme = &cm;
1265 
1266 		do {
1267 			if (flags & MSG_PEEK) {
1268 				if (controlp != NULL) {
1269 					*controlp = m_copy(m, 0, m->m_len);
1270 					controlp = &(*controlp)->m_next;
1271 				}
1272 				m = m->m_next;
1273 			} else {
1274 				sbfree(&so->so_rcv, m);
1275 				so->so_rcv.sb_mb = m->m_next;
1276 				m->m_next = NULL;
1277 				*cme = m;
1278 				cme = &(*cme)->m_next;
1279 				m = so->so_rcv.sb_mb;
1280 			}
1281 		} while (m != NULL && m->m_type == MT_CONTROL);
1282 		if ((flags & MSG_PEEK) == 0)
1283 			sbsync(&so->so_rcv, nextrecord);
1284 		for (; cm != NULL; cm = cmn) {
1285 			cmn = cm->m_next;
1286 			cm->m_next = NULL;
1287 			type = mtod(cm, struct cmsghdr *)->cmsg_type;
1288 			if (controlp != NULL) {
1289 				if (dom->dom_externalize != NULL &&
1290 				    type == SCM_RIGHTS) {
1291 					sounlock(so);
1292 					splx(s);
1293 					error = (*dom->dom_externalize)(cm, l);
1294 					s = splsoftnet();
1295 					solock(so);
1296 				}
1297 				*controlp = cm;
1298 				while (*controlp != NULL)
1299 					controlp = &(*controlp)->m_next;
1300 			} else {
1301 				/*
1302 				 * Dispose of any SCM_RIGHTS message that went
1303 				 * through the read path rather than recv.
1304 				 */
1305 				if (dom->dom_dispose != NULL &&
1306 				    type == SCM_RIGHTS) {
1307 				    	sounlock(so);
1308 					(*dom->dom_dispose)(cm);
1309 					solock(so);
1310 				}
1311 				m_freem(cm);
1312 			}
1313 		}
1314 		if (m != NULL)
1315 			nextrecord = so->so_rcv.sb_mb->m_nextpkt;
1316 		else
1317 			nextrecord = so->so_rcv.sb_mb;
1318 		orig_resid = 0;
1319 	}
1320 
1321 	/* If m is non-NULL, we have some data to read. */
1322 	if (__predict_true(m != NULL)) {
1323 		type = m->m_type;
1324 		if (type == MT_OOBDATA)
1325 			flags |= MSG_OOB;
1326 	}
1327 	SBLASTRECORDCHK(&so->so_rcv, "soreceive 2");
1328 	SBLASTMBUFCHK(&so->so_rcv, "soreceive 2");
1329 
1330 	moff = 0;
1331 	offset = 0;
1332 	while (m != NULL && uio->uio_resid > 0 && error == 0) {
1333 		if (m->m_type == MT_OOBDATA) {
1334 			if (type != MT_OOBDATA)
1335 				break;
1336 		} else if (type == MT_OOBDATA)
1337 			break;
1338 #ifdef DIAGNOSTIC
1339 		else if (m->m_type != MT_DATA && m->m_type != MT_HEADER)
1340 			panic("receive 3");
1341 #endif
1342 		so->so_state &= ~SS_RCVATMARK;
1343 		len = uio->uio_resid;
1344 		if (so->so_oobmark && len > so->so_oobmark - offset)
1345 			len = so->so_oobmark - offset;
1346 		if (len > m->m_len - moff)
1347 			len = m->m_len - moff;
1348 		/*
1349 		 * If mp is set, just pass back the mbufs.
1350 		 * Otherwise copy them out via the uio, then free.
1351 		 * Sockbuf must be consistent here (points to current mbuf,
1352 		 * it points to next record) when we drop priority;
1353 		 * we must note any additions to the sockbuf when we
1354 		 * block interrupts again.
1355 		 */
1356 		if (mp == NULL) {
1357 			SBLASTRECORDCHK(&so->so_rcv, "soreceive uiomove");
1358 			SBLASTMBUFCHK(&so->so_rcv, "soreceive uiomove");
1359 			sounlock(so);
1360 			splx(s);
1361 			error = uiomove(mtod(m, char *) + moff, (int)len, uio);
1362 			s = splsoftnet();
1363 			solock(so);
1364 			if (error != 0) {
1365 				/*
1366 				 * If any part of the record has been removed
1367 				 * (such as the MT_SONAME mbuf, which will
1368 				 * happen when PR_ADDR, and thus also
1369 				 * PR_ATOMIC, is set), then drop the entire
1370 				 * record to maintain the atomicity of the
1371 				 * receive operation.
1372 				 *
1373 				 * This avoids a later panic("receive 1a")
1374 				 * when compiled with DIAGNOSTIC.
1375 				 */
1376 				if (m && mbuf_removed && atomic)
1377 					(void) sbdroprecord(&so->so_rcv);
1378 
1379 				goto release;
1380 			}
1381 		} else
1382 			uio->uio_resid -= len;
1383 		if (len == m->m_len - moff) {
1384 			if (m->m_flags & M_EOR)
1385 				flags |= MSG_EOR;
1386 			if (flags & MSG_PEEK) {
1387 				m = m->m_next;
1388 				moff = 0;
1389 			} else {
1390 				nextrecord = m->m_nextpkt;
1391 				sbfree(&so->so_rcv, m);
1392 				if (mp) {
1393 					*mp = m;
1394 					mp = &m->m_next;
1395 					so->so_rcv.sb_mb = m = m->m_next;
1396 					*mp = NULL;
1397 				} else {
1398 					MFREE(m, so->so_rcv.sb_mb);
1399 					m = so->so_rcv.sb_mb;
1400 				}
1401 				/*
1402 				 * If m != NULL, we also know that
1403 				 * so->so_rcv.sb_mb != NULL.
1404 				 */
1405 				KASSERT(so->so_rcv.sb_mb == m);
1406 				if (m) {
1407 					m->m_nextpkt = nextrecord;
1408 					if (nextrecord == NULL)
1409 						so->so_rcv.sb_lastrecord = m;
1410 				} else {
1411 					so->so_rcv.sb_mb = nextrecord;
1412 					SB_EMPTY_FIXUP(&so->so_rcv);
1413 				}
1414 				SBLASTRECORDCHK(&so->so_rcv, "soreceive 3");
1415 				SBLASTMBUFCHK(&so->so_rcv, "soreceive 3");
1416 			}
1417 		} else if (flags & MSG_PEEK)
1418 			moff += len;
1419 		else {
1420 			if (mp != NULL) {
1421 				mt = m_copym(m, 0, len, M_NOWAIT);
1422 				if (__predict_false(mt == NULL)) {
1423 					sounlock(so);
1424 					mt = m_copym(m, 0, len, M_WAIT);
1425 					solock(so);
1426 				}
1427 				*mp = mt;
1428 			}
1429 			m->m_data += len;
1430 			m->m_len -= len;
1431 			so->so_rcv.sb_cc -= len;
1432 		}
1433 		if (so->so_oobmark) {
1434 			if ((flags & MSG_PEEK) == 0) {
1435 				so->so_oobmark -= len;
1436 				if (so->so_oobmark == 0) {
1437 					so->so_state |= SS_RCVATMARK;
1438 					break;
1439 				}
1440 			} else {
1441 				offset += len;
1442 				if (offset == so->so_oobmark)
1443 					break;
1444 			}
1445 		}
1446 		if (flags & MSG_EOR)
1447 			break;
1448 		/*
1449 		 * If the MSG_WAITALL flag is set (for non-atomic socket),
1450 		 * we must not quit until "uio->uio_resid == 0" or an error
1451 		 * termination.  If a signal/timeout occurs, return
1452 		 * with a short count but without error.
1453 		 * Keep sockbuf locked against other readers.
1454 		 */
1455 		while (flags & MSG_WAITALL && m == NULL && uio->uio_resid > 0 &&
1456 		    !sosendallatonce(so) && !nextrecord) {
1457 			if (so->so_error || so->so_state & SS_CANTRCVMORE)
1458 				break;
1459 			/*
1460 			 * If we are peeking and the socket receive buffer is
1461 			 * full, stop since we can't get more data to peek at.
1462 			 */
1463 			if ((flags & MSG_PEEK) && sbspace(&so->so_rcv) <= 0)
1464 				break;
1465 			/*
1466 			 * If we've drained the socket buffer, tell the
1467 			 * protocol in case it needs to do something to
1468 			 * get it filled again.
1469 			 */
1470 			if ((pr->pr_flags & PR_WANTRCVD) && so->so_pcb)
1471 				(*pr->pr_usrreq)(so, PRU_RCVD,
1472 				    NULL, (struct mbuf *)(long)flags, NULL, l);
1473 			SBLASTRECORDCHK(&so->so_rcv, "soreceive sbwait 2");
1474 			SBLASTMBUFCHK(&so->so_rcv, "soreceive sbwait 2");
1475 			error = sbwait(&so->so_rcv);
1476 			if (error != 0) {
1477 				sbunlock(&so->so_rcv);
1478 				sounlock(so);
1479 				splx(s);
1480 				return 0;
1481 			}
1482 			if ((m = so->so_rcv.sb_mb) != NULL)
1483 				nextrecord = m->m_nextpkt;
1484 		}
1485 	}
1486 
1487 	if (m && atomic) {
1488 		flags |= MSG_TRUNC;
1489 		if ((flags & MSG_PEEK) == 0)
1490 			(void) sbdroprecord(&so->so_rcv);
1491 	}
1492 	if ((flags & MSG_PEEK) == 0) {
1493 		if (m == NULL) {
1494 			/*
1495 			 * First part is an inline SB_EMPTY_FIXUP().  Second
1496 			 * part makes sure sb_lastrecord is up-to-date if
1497 			 * there is still data in the socket buffer.
1498 			 */
1499 			so->so_rcv.sb_mb = nextrecord;
1500 			if (so->so_rcv.sb_mb == NULL) {
1501 				so->so_rcv.sb_mbtail = NULL;
1502 				so->so_rcv.sb_lastrecord = NULL;
1503 			} else if (nextrecord->m_nextpkt == NULL)
1504 				so->so_rcv.sb_lastrecord = nextrecord;
1505 		}
1506 		SBLASTRECORDCHK(&so->so_rcv, "soreceive 4");
1507 		SBLASTMBUFCHK(&so->so_rcv, "soreceive 4");
1508 		if (pr->pr_flags & PR_WANTRCVD && so->so_pcb)
1509 			(*pr->pr_usrreq)(so, PRU_RCVD, NULL,
1510 			    (struct mbuf *)(long)flags, NULL, l);
1511 	}
1512 	if (orig_resid == uio->uio_resid && orig_resid &&
1513 	    (flags & MSG_EOR) == 0 && (so->so_state & SS_CANTRCVMORE) == 0) {
1514 		sbunlock(&so->so_rcv);
1515 		goto restart;
1516 	}
1517 
1518 	if (flagsp != NULL)
1519 		*flagsp |= flags;
1520  release:
1521 	sbunlock(&so->so_rcv);
1522 	sounlock(so);
1523 	splx(s);
1524 	return error;
1525 }
1526 
1527 int
1528 soshutdown(struct socket *so, int how)
1529 {
1530 	const struct protosw	*pr;
1531 	int	error;
1532 
1533 	KASSERT(solocked(so));
1534 
1535 	pr = so->so_proto;
1536 	if (!(how == SHUT_RD || how == SHUT_WR || how == SHUT_RDWR))
1537 		return (EINVAL);
1538 
1539 	if (how == SHUT_RD || how == SHUT_RDWR) {
1540 		sorflush(so);
1541 		error = 0;
1542 	}
1543 	if (how == SHUT_WR || how == SHUT_RDWR)
1544 		error = (*pr->pr_usrreq)(so, PRU_SHUTDOWN, NULL,
1545 		    NULL, NULL, NULL);
1546 
1547 	return error;
1548 }
1549 
1550 void
1551 sorflush(struct socket *so)
1552 {
1553 	struct sockbuf	*sb, asb;
1554 	const struct protosw	*pr;
1555 
1556 	KASSERT(solocked(so));
1557 
1558 	sb = &so->so_rcv;
1559 	pr = so->so_proto;
1560 	socantrcvmore(so);
1561 	sb->sb_flags |= SB_NOINTR;
1562 	(void )sblock(sb, M_WAITOK);
1563 	sbunlock(sb);
1564 	asb = *sb;
1565 	/*
1566 	 * Clear most of the sockbuf structure, but leave some of the
1567 	 * fields valid.
1568 	 */
1569 	memset(&sb->sb_startzero, 0,
1570 	    sizeof(*sb) - offsetof(struct sockbuf, sb_startzero));
1571 	if (pr->pr_flags & PR_RIGHTS && pr->pr_domain->dom_dispose) {
1572 		sounlock(so);
1573 		(*pr->pr_domain->dom_dispose)(asb.sb_mb);
1574 		solock(so);
1575 	}
1576 	sbrelease(&asb, so);
1577 }
1578 
1579 /*
1580  * internal set SOL_SOCKET options
1581  */
1582 static int
1583 sosetopt1(struct socket *so, const struct sockopt *sopt)
1584 {
1585 	int error = EINVAL, optval, opt;
1586 	struct linger l;
1587 	struct timeval tv;
1588 
1589 	switch ((opt = sopt->sopt_name)) {
1590 
1591 	case SO_ACCEPTFILTER:
1592 		error = accept_filt_setopt(so, sopt);
1593 		KASSERT(solocked(so));
1594 		break;
1595 
1596   	case SO_LINGER:
1597  		error = sockopt_get(sopt, &l, sizeof(l));
1598 		solock(so);
1599  		if (error)
1600  			break;
1601  		if (l.l_linger < 0 || l.l_linger > USHRT_MAX ||
1602  		    l.l_linger > (INT_MAX / hz)) {
1603 			error = EDOM;
1604 			break;
1605 		}
1606  		so->so_linger = l.l_linger;
1607  		if (l.l_onoff)
1608  			so->so_options |= SO_LINGER;
1609  		else
1610  			so->so_options &= ~SO_LINGER;
1611    		break;
1612 
1613 	case SO_DEBUG:
1614 	case SO_KEEPALIVE:
1615 	case SO_DONTROUTE:
1616 	case SO_USELOOPBACK:
1617 	case SO_BROADCAST:
1618 	case SO_REUSEADDR:
1619 	case SO_REUSEPORT:
1620 	case SO_OOBINLINE:
1621 	case SO_TIMESTAMP:
1622 #ifdef SO_OTIMESTAMP
1623 	case SO_OTIMESTAMP:
1624 #endif
1625 		error = sockopt_getint(sopt, &optval);
1626 		solock(so);
1627 		if (error)
1628 			break;
1629 		if (optval)
1630 			so->so_options |= opt;
1631 		else
1632 			so->so_options &= ~opt;
1633 		break;
1634 
1635 	case SO_SNDBUF:
1636 	case SO_RCVBUF:
1637 	case SO_SNDLOWAT:
1638 	case SO_RCVLOWAT:
1639 		error = sockopt_getint(sopt, &optval);
1640 		solock(so);
1641 		if (error)
1642 			break;
1643 
1644 		/*
1645 		 * Values < 1 make no sense for any of these
1646 		 * options, so disallow them.
1647 		 */
1648 		if (optval < 1) {
1649 			error = EINVAL;
1650 			break;
1651 		}
1652 
1653 		switch (opt) {
1654 		case SO_SNDBUF:
1655 			if (sbreserve(&so->so_snd, (u_long)optval, so) == 0) {
1656 				error = ENOBUFS;
1657 				break;
1658 			}
1659 			so->so_snd.sb_flags &= ~SB_AUTOSIZE;
1660 			break;
1661 
1662 		case SO_RCVBUF:
1663 			if (sbreserve(&so->so_rcv, (u_long)optval, so) == 0) {
1664 				error = ENOBUFS;
1665 				break;
1666 			}
1667 			so->so_rcv.sb_flags &= ~SB_AUTOSIZE;
1668 			break;
1669 
1670 		/*
1671 		 * Make sure the low-water is never greater than
1672 		 * the high-water.
1673 		 */
1674 		case SO_SNDLOWAT:
1675 			if (optval > so->so_snd.sb_hiwat)
1676 				optval = so->so_snd.sb_hiwat;
1677 
1678 			so->so_snd.sb_lowat = optval;
1679 			break;
1680 
1681 		case SO_RCVLOWAT:
1682 			if (optval > so->so_rcv.sb_hiwat)
1683 				optval = so->so_rcv.sb_hiwat;
1684 
1685 			so->so_rcv.sb_lowat = optval;
1686 			break;
1687 		}
1688 		break;
1689 
1690 #ifdef COMPAT_50
1691 	case SO_OSNDTIMEO:
1692 	case SO_ORCVTIMEO: {
1693 		struct timeval50 otv;
1694 		error = sockopt_get(sopt, &otv, sizeof(otv));
1695 		if (error) {
1696 			solock(so);
1697 			break;
1698 		}
1699 		timeval50_to_timeval(&otv, &tv);
1700 		opt = opt == SO_OSNDTIMEO ? SO_SNDTIMEO : SO_RCVTIMEO;
1701 		error = 0;
1702 		/*FALLTHROUGH*/
1703 	}
1704 #endif /* COMPAT_50 */
1705 
1706 	case SO_SNDTIMEO:
1707 	case SO_RCVTIMEO:
1708 		if (error)
1709 			error = sockopt_get(sopt, &tv, sizeof(tv));
1710 		solock(so);
1711 		if (error)
1712 			break;
1713 
1714 		if (tv.tv_sec > (INT_MAX - tv.tv_usec / tick) / hz) {
1715 			error = EDOM;
1716 			break;
1717 		}
1718 
1719 		optval = tv.tv_sec * hz + tv.tv_usec / tick;
1720 		if (optval == 0 && tv.tv_usec != 0)
1721 			optval = 1;
1722 
1723 		switch (opt) {
1724 		case SO_SNDTIMEO:
1725 			so->so_snd.sb_timeo = optval;
1726 			break;
1727 		case SO_RCVTIMEO:
1728 			so->so_rcv.sb_timeo = optval;
1729 			break;
1730 		}
1731 		break;
1732 
1733 	default:
1734 		solock(so);
1735 		error = ENOPROTOOPT;
1736 		break;
1737 	}
1738 	KASSERT(solocked(so));
1739 	return error;
1740 }
1741 
1742 int
1743 sosetopt(struct socket *so, struct sockopt *sopt)
1744 {
1745 	int error, prerr;
1746 
1747 	if (sopt->sopt_level == SOL_SOCKET) {
1748 		error = sosetopt1(so, sopt);
1749 		KASSERT(solocked(so));
1750 	} else {
1751 		error = ENOPROTOOPT;
1752 		solock(so);
1753 	}
1754 
1755 	if ((error == 0 || error == ENOPROTOOPT) &&
1756 	    so->so_proto != NULL && so->so_proto->pr_ctloutput != NULL) {
1757 		/* give the protocol stack a shot */
1758 		prerr = (*so->so_proto->pr_ctloutput)(PRCO_SETOPT, so, sopt);
1759 		if (prerr == 0)
1760 			error = 0;
1761 		else if (prerr != ENOPROTOOPT)
1762 			error = prerr;
1763 	}
1764 	sounlock(so);
1765 	return error;
1766 }
1767 
1768 /*
1769  * so_setsockopt() is a wrapper providing a sockopt structure for sosetopt()
1770  */
1771 int
1772 so_setsockopt(struct lwp *l, struct socket *so, int level, int name,
1773     const void *val, size_t valsize)
1774 {
1775 	struct sockopt sopt;
1776 	int error;
1777 
1778 	KASSERT(valsize == 0 || val != NULL);
1779 
1780 	sockopt_init(&sopt, level, name, valsize);
1781 	sockopt_set(&sopt, val, valsize);
1782 
1783 	error = sosetopt(so, &sopt);
1784 
1785 	sockopt_destroy(&sopt);
1786 
1787 	return error;
1788 }
1789 
1790 /*
1791  * internal get SOL_SOCKET options
1792  */
1793 static int
1794 sogetopt1(struct socket *so, struct sockopt *sopt)
1795 {
1796 	int error, optval, opt;
1797 	struct linger l;
1798 	struct timeval tv;
1799 
1800 	switch ((opt = sopt->sopt_name)) {
1801 
1802 	case SO_ACCEPTFILTER:
1803 		error = accept_filt_getopt(so, sopt);
1804 		break;
1805 
1806 	case SO_LINGER:
1807 		l.l_onoff = (so->so_options & SO_LINGER) ? 1 : 0;
1808 		l.l_linger = so->so_linger;
1809 
1810 		error = sockopt_set(sopt, &l, sizeof(l));
1811 		break;
1812 
1813 	case SO_USELOOPBACK:
1814 	case SO_DONTROUTE:
1815 	case SO_DEBUG:
1816 	case SO_KEEPALIVE:
1817 	case SO_REUSEADDR:
1818 	case SO_REUSEPORT:
1819 	case SO_BROADCAST:
1820 	case SO_OOBINLINE:
1821 	case SO_TIMESTAMP:
1822 #ifdef SO_OTIMESTAMP
1823 	case SO_OTIMESTAMP:
1824 #endif
1825 		error = sockopt_setint(sopt, (so->so_options & opt) ? 1 : 0);
1826 		break;
1827 
1828 	case SO_TYPE:
1829 		error = sockopt_setint(sopt, so->so_type);
1830 		break;
1831 
1832 	case SO_ERROR:
1833 		error = sockopt_setint(sopt, so->so_error);
1834 		so->so_error = 0;
1835 		break;
1836 
1837 	case SO_SNDBUF:
1838 		error = sockopt_setint(sopt, so->so_snd.sb_hiwat);
1839 		break;
1840 
1841 	case SO_RCVBUF:
1842 		error = sockopt_setint(sopt, so->so_rcv.sb_hiwat);
1843 		break;
1844 
1845 	case SO_SNDLOWAT:
1846 		error = sockopt_setint(sopt, so->so_snd.sb_lowat);
1847 		break;
1848 
1849 	case SO_RCVLOWAT:
1850 		error = sockopt_setint(sopt, so->so_rcv.sb_lowat);
1851 		break;
1852 
1853 #ifdef COMPAT_50
1854 	case SO_OSNDTIMEO:
1855 	case SO_ORCVTIMEO: {
1856 		struct timeval50 otv;
1857 
1858 		optval = (opt == SO_OSNDTIMEO ?
1859 		     so->so_snd.sb_timeo : so->so_rcv.sb_timeo);
1860 
1861 		otv.tv_sec = optval / hz;
1862 		otv.tv_usec = (optval % hz) * tick;
1863 
1864 		error = sockopt_set(sopt, &otv, sizeof(otv));
1865 		break;
1866 	}
1867 #endif /* COMPAT_50 */
1868 
1869 	case SO_SNDTIMEO:
1870 	case SO_RCVTIMEO:
1871 		optval = (opt == SO_SNDTIMEO ?
1872 		     so->so_snd.sb_timeo : so->so_rcv.sb_timeo);
1873 
1874 		tv.tv_sec = optval / hz;
1875 		tv.tv_usec = (optval % hz) * tick;
1876 
1877 		error = sockopt_set(sopt, &tv, sizeof(tv));
1878 		break;
1879 
1880 	case SO_OVERFLOWED:
1881 		error = sockopt_setint(sopt, so->so_rcv.sb_overflowed);
1882 		break;
1883 
1884 	default:
1885 		error = ENOPROTOOPT;
1886 		break;
1887 	}
1888 
1889 	return (error);
1890 }
1891 
1892 int
1893 sogetopt(struct socket *so, struct sockopt *sopt)
1894 {
1895 	int		error;
1896 
1897 	solock(so);
1898 	if (sopt->sopt_level != SOL_SOCKET) {
1899 		if (so->so_proto && so->so_proto->pr_ctloutput) {
1900 			error = ((*so->so_proto->pr_ctloutput)
1901 			    (PRCO_GETOPT, so, sopt));
1902 		} else
1903 			error = (ENOPROTOOPT);
1904 	} else {
1905 		error = sogetopt1(so, sopt);
1906 	}
1907 	sounlock(so);
1908 	return (error);
1909 }
1910 
1911 /*
1912  * alloc sockopt data buffer buffer
1913  *	- will be released at destroy
1914  */
1915 static int
1916 sockopt_alloc(struct sockopt *sopt, size_t len, km_flag_t kmflag)
1917 {
1918 
1919 	KASSERT(sopt->sopt_size == 0);
1920 
1921 	if (len > sizeof(sopt->sopt_buf)) {
1922 		sopt->sopt_data = kmem_zalloc(len, kmflag);
1923 		if (sopt->sopt_data == NULL)
1924 			return ENOMEM;
1925 	} else
1926 		sopt->sopt_data = sopt->sopt_buf;
1927 
1928 	sopt->sopt_size = len;
1929 	return 0;
1930 }
1931 
1932 /*
1933  * initialise sockopt storage
1934  *	- MAY sleep during allocation
1935  */
1936 void
1937 sockopt_init(struct sockopt *sopt, int level, int name, size_t size)
1938 {
1939 
1940 	memset(sopt, 0, sizeof(*sopt));
1941 
1942 	sopt->sopt_level = level;
1943 	sopt->sopt_name = name;
1944 	(void)sockopt_alloc(sopt, size, KM_SLEEP);
1945 }
1946 
1947 /*
1948  * destroy sockopt storage
1949  *	- will release any held memory references
1950  */
1951 void
1952 sockopt_destroy(struct sockopt *sopt)
1953 {
1954 
1955 	if (sopt->sopt_data != sopt->sopt_buf)
1956 		kmem_free(sopt->sopt_data, sopt->sopt_size);
1957 
1958 	memset(sopt, 0, sizeof(*sopt));
1959 }
1960 
1961 /*
1962  * set sockopt value
1963  *	- value is copied into sockopt
1964  * 	- memory is allocated when necessary, will not sleep
1965  */
1966 int
1967 sockopt_set(struct sockopt *sopt, const void *buf, size_t len)
1968 {
1969 	int error;
1970 
1971 	if (sopt->sopt_size == 0) {
1972 		error = sockopt_alloc(sopt, len, KM_NOSLEEP);
1973 		if (error)
1974 			return error;
1975 	}
1976 
1977 	KASSERT(sopt->sopt_size == len);
1978 	memcpy(sopt->sopt_data, buf, len);
1979 	return 0;
1980 }
1981 
1982 /*
1983  * common case of set sockopt integer value
1984  */
1985 int
1986 sockopt_setint(struct sockopt *sopt, int val)
1987 {
1988 
1989 	return sockopt_set(sopt, &val, sizeof(int));
1990 }
1991 
1992 /*
1993  * get sockopt value
1994  *	- correct size must be given
1995  */
1996 int
1997 sockopt_get(const struct sockopt *sopt, void *buf, size_t len)
1998 {
1999 
2000 	if (sopt->sopt_size != len)
2001 		return EINVAL;
2002 
2003 	memcpy(buf, sopt->sopt_data, len);
2004 	return 0;
2005 }
2006 
2007 /*
2008  * common case of get sockopt integer value
2009  */
2010 int
2011 sockopt_getint(const struct sockopt *sopt, int *valp)
2012 {
2013 
2014 	return sockopt_get(sopt, valp, sizeof(int));
2015 }
2016 
2017 /*
2018  * set sockopt value from mbuf
2019  *	- ONLY for legacy code
2020  *	- mbuf is released by sockopt
2021  *	- will not sleep
2022  */
2023 int
2024 sockopt_setmbuf(struct sockopt *sopt, struct mbuf *m)
2025 {
2026 	size_t len;
2027 	int error;
2028 
2029 	len = m_length(m);
2030 
2031 	if (sopt->sopt_size == 0) {
2032 		error = sockopt_alloc(sopt, len, KM_NOSLEEP);
2033 		if (error)
2034 			return error;
2035 	}
2036 
2037 	KASSERT(sopt->sopt_size == len);
2038 	m_copydata(m, 0, len, sopt->sopt_data);
2039 	m_freem(m);
2040 
2041 	return 0;
2042 }
2043 
2044 /*
2045  * get sockopt value into mbuf
2046  *	- ONLY for legacy code
2047  *	- mbuf to be released by the caller
2048  *	- will not sleep
2049  */
2050 struct mbuf *
2051 sockopt_getmbuf(const struct sockopt *sopt)
2052 {
2053 	struct mbuf *m;
2054 
2055 	if (sopt->sopt_size > MCLBYTES)
2056 		return NULL;
2057 
2058 	m = m_get(M_DONTWAIT, MT_SOOPTS);
2059 	if (m == NULL)
2060 		return NULL;
2061 
2062 	if (sopt->sopt_size > MLEN) {
2063 		MCLGET(m, M_DONTWAIT);
2064 		if ((m->m_flags & M_EXT) == 0) {
2065 			m_free(m);
2066 			return NULL;
2067 		}
2068 	}
2069 
2070 	memcpy(mtod(m, void *), sopt->sopt_data, sopt->sopt_size);
2071 	m->m_len = sopt->sopt_size;
2072 
2073 	return m;
2074 }
2075 
2076 void
2077 sohasoutofband(struct socket *so)
2078 {
2079 
2080 	fownsignal(so->so_pgid, SIGURG, POLL_PRI, POLLPRI|POLLRDBAND, so);
2081 	selnotify(&so->so_rcv.sb_sel, POLLPRI | POLLRDBAND, 0);
2082 }
2083 
2084 static void
2085 filt_sordetach(struct knote *kn)
2086 {
2087 	struct socket	*so;
2088 
2089 	so = ((file_t *)kn->kn_obj)->f_data;
2090 	solock(so);
2091 	SLIST_REMOVE(&so->so_rcv.sb_sel.sel_klist, kn, knote, kn_selnext);
2092 	if (SLIST_EMPTY(&so->so_rcv.sb_sel.sel_klist))
2093 		so->so_rcv.sb_flags &= ~SB_KNOTE;
2094 	sounlock(so);
2095 }
2096 
2097 /*ARGSUSED*/
2098 static int
2099 filt_soread(struct knote *kn, long hint)
2100 {
2101 	struct socket	*so;
2102 	int rv;
2103 
2104 	so = ((file_t *)kn->kn_obj)->f_data;
2105 	if (hint != NOTE_SUBMIT)
2106 		solock(so);
2107 	kn->kn_data = so->so_rcv.sb_cc;
2108 	if (so->so_state & SS_CANTRCVMORE) {
2109 		kn->kn_flags |= EV_EOF;
2110 		kn->kn_fflags = so->so_error;
2111 		rv = 1;
2112 	} else if (so->so_error)	/* temporary udp error */
2113 		rv = 1;
2114 	else if (kn->kn_sfflags & NOTE_LOWAT)
2115 		rv = (kn->kn_data >= kn->kn_sdata);
2116 	else
2117 		rv = (kn->kn_data >= so->so_rcv.sb_lowat);
2118 	if (hint != NOTE_SUBMIT)
2119 		sounlock(so);
2120 	return rv;
2121 }
2122 
2123 static void
2124 filt_sowdetach(struct knote *kn)
2125 {
2126 	struct socket	*so;
2127 
2128 	so = ((file_t *)kn->kn_obj)->f_data;
2129 	solock(so);
2130 	SLIST_REMOVE(&so->so_snd.sb_sel.sel_klist, kn, knote, kn_selnext);
2131 	if (SLIST_EMPTY(&so->so_snd.sb_sel.sel_klist))
2132 		so->so_snd.sb_flags &= ~SB_KNOTE;
2133 	sounlock(so);
2134 }
2135 
2136 /*ARGSUSED*/
2137 static int
2138 filt_sowrite(struct knote *kn, long hint)
2139 {
2140 	struct socket	*so;
2141 	int rv;
2142 
2143 	so = ((file_t *)kn->kn_obj)->f_data;
2144 	if (hint != NOTE_SUBMIT)
2145 		solock(so);
2146 	kn->kn_data = sbspace(&so->so_snd);
2147 	if (so->so_state & SS_CANTSENDMORE) {
2148 		kn->kn_flags |= EV_EOF;
2149 		kn->kn_fflags = so->so_error;
2150 		rv = 1;
2151 	} else if (so->so_error)	/* temporary udp error */
2152 		rv = 1;
2153 	else if (((so->so_state & SS_ISCONNECTED) == 0) &&
2154 	    (so->so_proto->pr_flags & PR_CONNREQUIRED))
2155 		rv = 0;
2156 	else if (kn->kn_sfflags & NOTE_LOWAT)
2157 		rv = (kn->kn_data >= kn->kn_sdata);
2158 	else
2159 		rv = (kn->kn_data >= so->so_snd.sb_lowat);
2160 	if (hint != NOTE_SUBMIT)
2161 		sounlock(so);
2162 	return rv;
2163 }
2164 
2165 /*ARGSUSED*/
2166 static int
2167 filt_solisten(struct knote *kn, long hint)
2168 {
2169 	struct socket	*so;
2170 	int rv;
2171 
2172 	so = ((file_t *)kn->kn_obj)->f_data;
2173 
2174 	/*
2175 	 * Set kn_data to number of incoming connections, not
2176 	 * counting partial (incomplete) connections.
2177 	 */
2178 	if (hint != NOTE_SUBMIT)
2179 		solock(so);
2180 	kn->kn_data = so->so_qlen;
2181 	rv = (kn->kn_data > 0);
2182 	if (hint != NOTE_SUBMIT)
2183 		sounlock(so);
2184 	return rv;
2185 }
2186 
2187 static const struct filterops solisten_filtops =
2188 	{ 1, NULL, filt_sordetach, filt_solisten };
2189 static const struct filterops soread_filtops =
2190 	{ 1, NULL, filt_sordetach, filt_soread };
2191 static const struct filterops sowrite_filtops =
2192 	{ 1, NULL, filt_sowdetach, filt_sowrite };
2193 
2194 int
2195 soo_kqfilter(struct file *fp, struct knote *kn)
2196 {
2197 	struct socket	*so;
2198 	struct sockbuf	*sb;
2199 
2200 	so = ((file_t *)kn->kn_obj)->f_data;
2201 	solock(so);
2202 	switch (kn->kn_filter) {
2203 	case EVFILT_READ:
2204 		if (so->so_options & SO_ACCEPTCONN)
2205 			kn->kn_fop = &solisten_filtops;
2206 		else
2207 			kn->kn_fop = &soread_filtops;
2208 		sb = &so->so_rcv;
2209 		break;
2210 	case EVFILT_WRITE:
2211 		kn->kn_fop = &sowrite_filtops;
2212 		sb = &so->so_snd;
2213 		break;
2214 	default:
2215 		sounlock(so);
2216 		return (EINVAL);
2217 	}
2218 	SLIST_INSERT_HEAD(&sb->sb_sel.sel_klist, kn, kn_selnext);
2219 	sb->sb_flags |= SB_KNOTE;
2220 	sounlock(so);
2221 	return (0);
2222 }
2223 
2224 static int
2225 sodopoll(struct socket *so, int events)
2226 {
2227 	int revents;
2228 
2229 	revents = 0;
2230 
2231 	if (events & (POLLIN | POLLRDNORM))
2232 		if (soreadable(so))
2233 			revents |= events & (POLLIN | POLLRDNORM);
2234 
2235 	if (events & (POLLOUT | POLLWRNORM))
2236 		if (sowritable(so))
2237 			revents |= events & (POLLOUT | POLLWRNORM);
2238 
2239 	if (events & (POLLPRI | POLLRDBAND))
2240 		if (so->so_oobmark || (so->so_state & SS_RCVATMARK))
2241 			revents |= events & (POLLPRI | POLLRDBAND);
2242 
2243 	return revents;
2244 }
2245 
2246 int
2247 sopoll(struct socket *so, int events)
2248 {
2249 	int revents = 0;
2250 
2251 #ifndef DIAGNOSTIC
2252 	/*
2253 	 * Do a quick, unlocked check in expectation that the socket
2254 	 * will be ready for I/O.  Don't do this check if DIAGNOSTIC,
2255 	 * as the solocked() assertions will fail.
2256 	 */
2257 	if ((revents = sodopoll(so, events)) != 0)
2258 		return revents;
2259 #endif
2260 
2261 	solock(so);
2262 	if ((revents = sodopoll(so, events)) == 0) {
2263 		if (events & (POLLIN | POLLPRI | POLLRDNORM | POLLRDBAND)) {
2264 			selrecord(curlwp, &so->so_rcv.sb_sel);
2265 			so->so_rcv.sb_flags |= SB_NOTIFY;
2266 		}
2267 
2268 		if (events & (POLLOUT | POLLWRNORM)) {
2269 			selrecord(curlwp, &so->so_snd.sb_sel);
2270 			so->so_snd.sb_flags |= SB_NOTIFY;
2271 		}
2272 	}
2273 	sounlock(so);
2274 
2275 	return revents;
2276 }
2277 
2278 
2279 #include <sys/sysctl.h>
2280 
2281 static int sysctl_kern_somaxkva(SYSCTLFN_PROTO);
2282 
2283 /*
2284  * sysctl helper routine for kern.somaxkva.  ensures that the given
2285  * value is not too small.
2286  * (XXX should we maybe make sure it's not too large as well?)
2287  */
2288 static int
2289 sysctl_kern_somaxkva(SYSCTLFN_ARGS)
2290 {
2291 	int error, new_somaxkva;
2292 	struct sysctlnode node;
2293 
2294 	new_somaxkva = somaxkva;
2295 	node = *rnode;
2296 	node.sysctl_data = &new_somaxkva;
2297 	error = sysctl_lookup(SYSCTLFN_CALL(&node));
2298 	if (error || newp == NULL)
2299 		return (error);
2300 
2301 	if (new_somaxkva < (16 * 1024 * 1024)) /* sanity */
2302 		return (EINVAL);
2303 
2304 	mutex_enter(&so_pendfree_lock);
2305 	somaxkva = new_somaxkva;
2306 	cv_broadcast(&socurkva_cv);
2307 	mutex_exit(&so_pendfree_lock);
2308 
2309 	return (error);
2310 }
2311 
2312 static void
2313 sysctl_kern_somaxkva_setup(void)
2314 {
2315 
2316 	KASSERT(socket_sysctllog == NULL);
2317 	sysctl_createv(&socket_sysctllog, 0, NULL, NULL,
2318 		       CTLFLAG_PERMANENT,
2319 		       CTLTYPE_NODE, "kern", NULL,
2320 		       NULL, 0, NULL, 0,
2321 		       CTL_KERN, CTL_EOL);
2322 
2323 	sysctl_createv(&socket_sysctllog, 0, NULL, NULL,
2324 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
2325 		       CTLTYPE_INT, "somaxkva",
2326 		       SYSCTL_DESCR("Maximum amount of kernel memory to be "
2327 				    "used for socket buffers"),
2328 		       sysctl_kern_somaxkva, 0, NULL, 0,
2329 		       CTL_KERN, KERN_SOMAXKVA, CTL_EOL);
2330 }
2331