uipc_socket.c revision 1.177.2.1 1 /* $NetBSD: uipc_socket.c,v 1.177.2.1 2009/01/19 13:19:40 skrll 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.177.2.1 2009/01/19 13:19:40 skrll 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, 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 = ⊤
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 = ⊤
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 break;
1697 timeval50_to_timeval(&otv, &tv);
1698 opt = opt == SO_OSNDTIMEO ? SO_SNDTIMEO : SO_RCVTIMEO;
1699 error = 0;
1700 /*FALLTHROUGH*/
1701 }
1702 #endif /* COMPAT_50 */
1703
1704 case SO_SNDTIMEO:
1705 case SO_RCVTIMEO:
1706 if (error)
1707 error = sockopt_get(sopt, &tv, sizeof(tv));
1708 solock(so);
1709 if (error)
1710 break;
1711
1712 if (tv.tv_sec > (INT_MAX - tv.tv_usec / tick) / hz) {
1713 error = EDOM;
1714 break;
1715 }
1716
1717 optval = tv.tv_sec * hz + tv.tv_usec / tick;
1718 if (optval == 0 && tv.tv_usec != 0)
1719 optval = 1;
1720
1721 switch (opt) {
1722 case SO_SNDTIMEO:
1723 so->so_snd.sb_timeo = optval;
1724 break;
1725 case SO_RCVTIMEO:
1726 so->so_rcv.sb_timeo = optval;
1727 break;
1728 }
1729 break;
1730
1731 default:
1732 solock(so);
1733 error = ENOPROTOOPT;
1734 break;
1735 }
1736 KASSERT(solocked(so));
1737 return error;
1738 }
1739
1740 int
1741 sosetopt(struct socket *so, struct sockopt *sopt)
1742 {
1743 int error, prerr;
1744
1745 if (sopt->sopt_level == SOL_SOCKET) {
1746 error = sosetopt1(so, sopt);
1747 KASSERT(solocked(so));
1748 } else {
1749 error = ENOPROTOOPT;
1750 solock(so);
1751 }
1752
1753 if ((error == 0 || error == ENOPROTOOPT) &&
1754 so->so_proto != NULL && so->so_proto->pr_ctloutput != NULL) {
1755 /* give the protocol stack a shot */
1756 prerr = (*so->so_proto->pr_ctloutput)(PRCO_SETOPT, so, sopt);
1757 if (prerr == 0)
1758 error = 0;
1759 else if (prerr != ENOPROTOOPT)
1760 error = prerr;
1761 }
1762 sounlock(so);
1763 return error;
1764 }
1765
1766 /*
1767 * so_setsockopt() is a wrapper providing a sockopt structure for sosetopt()
1768 */
1769 int
1770 so_setsockopt(struct lwp *l, struct socket *so, int level, int name,
1771 const void *val, size_t valsize)
1772 {
1773 struct sockopt sopt;
1774 int error;
1775
1776 KASSERT(valsize == 0 || val != NULL);
1777
1778 sockopt_init(&sopt, level, name, valsize);
1779 sockopt_set(&sopt, val, valsize);
1780
1781 error = sosetopt(so, &sopt);
1782
1783 sockopt_destroy(&sopt);
1784
1785 return error;
1786 }
1787
1788 /*
1789 * internal get SOL_SOCKET options
1790 */
1791 static int
1792 sogetopt1(struct socket *so, struct sockopt *sopt)
1793 {
1794 int error, optval, opt;
1795 struct linger l;
1796 struct timeval tv;
1797
1798 switch ((opt = sopt->sopt_name)) {
1799
1800 case SO_ACCEPTFILTER:
1801 error = accept_filt_getopt(so, sopt);
1802 break;
1803
1804 case SO_LINGER:
1805 l.l_onoff = (so->so_options & SO_LINGER) ? 1 : 0;
1806 l.l_linger = so->so_linger;
1807
1808 error = sockopt_set(sopt, &l, sizeof(l));
1809 break;
1810
1811 case SO_USELOOPBACK:
1812 case SO_DONTROUTE:
1813 case SO_DEBUG:
1814 case SO_KEEPALIVE:
1815 case SO_REUSEADDR:
1816 case SO_REUSEPORT:
1817 case SO_BROADCAST:
1818 case SO_OOBINLINE:
1819 case SO_TIMESTAMP:
1820 #ifdef SO_OTIMESTAMP
1821 case SO_OTIMESTAMP:
1822 #endif
1823 error = sockopt_setint(sopt, (so->so_options & opt) ? 1 : 0);
1824 break;
1825
1826 case SO_TYPE:
1827 error = sockopt_setint(sopt, so->so_type);
1828 break;
1829
1830 case SO_ERROR:
1831 error = sockopt_setint(sopt, so->so_error);
1832 so->so_error = 0;
1833 break;
1834
1835 case SO_SNDBUF:
1836 error = sockopt_setint(sopt, so->so_snd.sb_hiwat);
1837 break;
1838
1839 case SO_RCVBUF:
1840 error = sockopt_setint(sopt, so->so_rcv.sb_hiwat);
1841 break;
1842
1843 case SO_SNDLOWAT:
1844 error = sockopt_setint(sopt, so->so_snd.sb_lowat);
1845 break;
1846
1847 case SO_RCVLOWAT:
1848 error = sockopt_setint(sopt, so->so_rcv.sb_lowat);
1849 break;
1850
1851 #ifdef COMPAT_50
1852 case SO_OSNDTIMEO:
1853 case SO_ORCVTIMEO: {
1854 struct timeval50 otv;
1855
1856 optval = (opt == SO_OSNDTIMEO ?
1857 so->so_snd.sb_timeo : so->so_rcv.sb_timeo);
1858
1859 otv.tv_sec = optval / hz;
1860 otv.tv_usec = (optval % hz) * tick;
1861
1862 error = sockopt_set(sopt, &otv, sizeof(otv));
1863 break;
1864 }
1865 #endif /* COMPAT_50 */
1866
1867 case SO_SNDTIMEO:
1868 case SO_RCVTIMEO:
1869 optval = (opt == SO_SNDTIMEO ?
1870 so->so_snd.sb_timeo : so->so_rcv.sb_timeo);
1871
1872 tv.tv_sec = optval / hz;
1873 tv.tv_usec = (optval % hz) * tick;
1874
1875 error = sockopt_set(sopt, &tv, sizeof(tv));
1876 break;
1877
1878 case SO_OVERFLOWED:
1879 error = sockopt_setint(sopt, so->so_rcv.sb_overflowed);
1880 break;
1881
1882 default:
1883 error = ENOPROTOOPT;
1884 break;
1885 }
1886
1887 return (error);
1888 }
1889
1890 int
1891 sogetopt(struct socket *so, struct sockopt *sopt)
1892 {
1893 int error;
1894
1895 solock(so);
1896 if (sopt->sopt_level != SOL_SOCKET) {
1897 if (so->so_proto && so->so_proto->pr_ctloutput) {
1898 error = ((*so->so_proto->pr_ctloutput)
1899 (PRCO_GETOPT, so, sopt));
1900 } else
1901 error = (ENOPROTOOPT);
1902 } else {
1903 error = sogetopt1(so, sopt);
1904 }
1905 sounlock(so);
1906 return (error);
1907 }
1908
1909 /*
1910 * alloc sockopt data buffer buffer
1911 * - will be released at destroy
1912 */
1913 static int
1914 sockopt_alloc(struct sockopt *sopt, size_t len, km_flag_t kmflag)
1915 {
1916
1917 KASSERT(sopt->sopt_size == 0);
1918
1919 if (len > sizeof(sopt->sopt_buf)) {
1920 sopt->sopt_data = kmem_zalloc(len, kmflag);
1921 if (sopt->sopt_data == NULL)
1922 return ENOMEM;
1923 } else
1924 sopt->sopt_data = sopt->sopt_buf;
1925
1926 sopt->sopt_size = len;
1927 return 0;
1928 }
1929
1930 /*
1931 * initialise sockopt storage
1932 * - MAY sleep during allocation
1933 */
1934 void
1935 sockopt_init(struct sockopt *sopt, int level, int name, size_t size)
1936 {
1937
1938 memset(sopt, 0, sizeof(*sopt));
1939
1940 sopt->sopt_level = level;
1941 sopt->sopt_name = name;
1942 (void)sockopt_alloc(sopt, size, KM_SLEEP);
1943 }
1944
1945 /*
1946 * destroy sockopt storage
1947 * - will release any held memory references
1948 */
1949 void
1950 sockopt_destroy(struct sockopt *sopt)
1951 {
1952
1953 if (sopt->sopt_data != sopt->sopt_buf)
1954 kmem_free(sopt->sopt_data, sopt->sopt_size);
1955
1956 memset(sopt, 0, sizeof(*sopt));
1957 }
1958
1959 /*
1960 * set sockopt value
1961 * - value is copied into sockopt
1962 * - memory is allocated when necessary, will not sleep
1963 */
1964 int
1965 sockopt_set(struct sockopt *sopt, const void *buf, size_t len)
1966 {
1967 int error;
1968
1969 if (sopt->sopt_size == 0) {
1970 error = sockopt_alloc(sopt, len, KM_NOSLEEP);
1971 if (error)
1972 return error;
1973 }
1974
1975 KASSERT(sopt->sopt_size == len);
1976 memcpy(sopt->sopt_data, buf, len);
1977 return 0;
1978 }
1979
1980 /*
1981 * common case of set sockopt integer value
1982 */
1983 int
1984 sockopt_setint(struct sockopt *sopt, int val)
1985 {
1986
1987 return sockopt_set(sopt, &val, sizeof(int));
1988 }
1989
1990 /*
1991 * get sockopt value
1992 * - correct size must be given
1993 */
1994 int
1995 sockopt_get(const struct sockopt *sopt, void *buf, size_t len)
1996 {
1997
1998 if (sopt->sopt_size != len)
1999 return EINVAL;
2000
2001 memcpy(buf, sopt->sopt_data, len);
2002 return 0;
2003 }
2004
2005 /*
2006 * common case of get sockopt integer value
2007 */
2008 int
2009 sockopt_getint(const struct sockopt *sopt, int *valp)
2010 {
2011
2012 return sockopt_get(sopt, valp, sizeof(int));
2013 }
2014
2015 /*
2016 * set sockopt value from mbuf
2017 * - ONLY for legacy code
2018 * - mbuf is released by sockopt
2019 * - will not sleep
2020 */
2021 int
2022 sockopt_setmbuf(struct sockopt *sopt, struct mbuf *m)
2023 {
2024 size_t len;
2025 int error;
2026
2027 len = m_length(m);
2028
2029 if (sopt->sopt_size == 0) {
2030 error = sockopt_alloc(sopt, len, KM_NOSLEEP);
2031 if (error)
2032 return error;
2033 }
2034
2035 KASSERT(sopt->sopt_size == len);
2036 m_copydata(m, 0, len, sopt->sopt_data);
2037 m_freem(m);
2038
2039 return 0;
2040 }
2041
2042 /*
2043 * get sockopt value into mbuf
2044 * - ONLY for legacy code
2045 * - mbuf to be released by the caller
2046 * - will not sleep
2047 */
2048 struct mbuf *
2049 sockopt_getmbuf(const struct sockopt *sopt)
2050 {
2051 struct mbuf *m;
2052
2053 if (sopt->sopt_size > MCLBYTES)
2054 return NULL;
2055
2056 m = m_get(M_DONTWAIT, MT_SOOPTS);
2057 if (m == NULL)
2058 return NULL;
2059
2060 if (sopt->sopt_size > MLEN) {
2061 MCLGET(m, M_DONTWAIT);
2062 if ((m->m_flags & M_EXT) == 0) {
2063 m_free(m);
2064 return NULL;
2065 }
2066 }
2067
2068 memcpy(mtod(m, void *), sopt->sopt_data, sopt->sopt_size);
2069 m->m_len = sopt->sopt_size;
2070
2071 return m;
2072 }
2073
2074 void
2075 sohasoutofband(struct socket *so)
2076 {
2077
2078 fownsignal(so->so_pgid, SIGURG, POLL_PRI, POLLPRI|POLLRDBAND, so);
2079 selnotify(&so->so_rcv.sb_sel, POLLPRI | POLLRDBAND, 0);
2080 }
2081
2082 static void
2083 filt_sordetach(struct knote *kn)
2084 {
2085 struct socket *so;
2086
2087 so = ((file_t *)kn->kn_obj)->f_data;
2088 solock(so);
2089 SLIST_REMOVE(&so->so_rcv.sb_sel.sel_klist, kn, knote, kn_selnext);
2090 if (SLIST_EMPTY(&so->so_rcv.sb_sel.sel_klist))
2091 so->so_rcv.sb_flags &= ~SB_KNOTE;
2092 sounlock(so);
2093 }
2094
2095 /*ARGSUSED*/
2096 static int
2097 filt_soread(struct knote *kn, long hint)
2098 {
2099 struct socket *so;
2100 int rv;
2101
2102 so = ((file_t *)kn->kn_obj)->f_data;
2103 if (hint != NOTE_SUBMIT)
2104 solock(so);
2105 kn->kn_data = so->so_rcv.sb_cc;
2106 if (so->so_state & SS_CANTRCVMORE) {
2107 kn->kn_flags |= EV_EOF;
2108 kn->kn_fflags = so->so_error;
2109 rv = 1;
2110 } else if (so->so_error) /* temporary udp error */
2111 rv = 1;
2112 else if (kn->kn_sfflags & NOTE_LOWAT)
2113 rv = (kn->kn_data >= kn->kn_sdata);
2114 else
2115 rv = (kn->kn_data >= so->so_rcv.sb_lowat);
2116 if (hint != NOTE_SUBMIT)
2117 sounlock(so);
2118 return rv;
2119 }
2120
2121 static void
2122 filt_sowdetach(struct knote *kn)
2123 {
2124 struct socket *so;
2125
2126 so = ((file_t *)kn->kn_obj)->f_data;
2127 solock(so);
2128 SLIST_REMOVE(&so->so_snd.sb_sel.sel_klist, kn, knote, kn_selnext);
2129 if (SLIST_EMPTY(&so->so_snd.sb_sel.sel_klist))
2130 so->so_snd.sb_flags &= ~SB_KNOTE;
2131 sounlock(so);
2132 }
2133
2134 /*ARGSUSED*/
2135 static int
2136 filt_sowrite(struct knote *kn, long hint)
2137 {
2138 struct socket *so;
2139 int rv;
2140
2141 so = ((file_t *)kn->kn_obj)->f_data;
2142 if (hint != NOTE_SUBMIT)
2143 solock(so);
2144 kn->kn_data = sbspace(&so->so_snd);
2145 if (so->so_state & SS_CANTSENDMORE) {
2146 kn->kn_flags |= EV_EOF;
2147 kn->kn_fflags = so->so_error;
2148 rv = 1;
2149 } else if (so->so_error) /* temporary udp error */
2150 rv = 1;
2151 else if (((so->so_state & SS_ISCONNECTED) == 0) &&
2152 (so->so_proto->pr_flags & PR_CONNREQUIRED))
2153 rv = 0;
2154 else if (kn->kn_sfflags & NOTE_LOWAT)
2155 rv = (kn->kn_data >= kn->kn_sdata);
2156 else
2157 rv = (kn->kn_data >= so->so_snd.sb_lowat);
2158 if (hint != NOTE_SUBMIT)
2159 sounlock(so);
2160 return rv;
2161 }
2162
2163 /*ARGSUSED*/
2164 static int
2165 filt_solisten(struct knote *kn, long hint)
2166 {
2167 struct socket *so;
2168 int rv;
2169
2170 so = ((file_t *)kn->kn_obj)->f_data;
2171
2172 /*
2173 * Set kn_data to number of incoming connections, not
2174 * counting partial (incomplete) connections.
2175 */
2176 if (hint != NOTE_SUBMIT)
2177 solock(so);
2178 kn->kn_data = so->so_qlen;
2179 rv = (kn->kn_data > 0);
2180 if (hint != NOTE_SUBMIT)
2181 sounlock(so);
2182 return rv;
2183 }
2184
2185 static const struct filterops solisten_filtops =
2186 { 1, NULL, filt_sordetach, filt_solisten };
2187 static const struct filterops soread_filtops =
2188 { 1, NULL, filt_sordetach, filt_soread };
2189 static const struct filterops sowrite_filtops =
2190 { 1, NULL, filt_sowdetach, filt_sowrite };
2191
2192 int
2193 soo_kqfilter(struct file *fp, struct knote *kn)
2194 {
2195 struct socket *so;
2196 struct sockbuf *sb;
2197
2198 so = ((file_t *)kn->kn_obj)->f_data;
2199 solock(so);
2200 switch (kn->kn_filter) {
2201 case EVFILT_READ:
2202 if (so->so_options & SO_ACCEPTCONN)
2203 kn->kn_fop = &solisten_filtops;
2204 else
2205 kn->kn_fop = &soread_filtops;
2206 sb = &so->so_rcv;
2207 break;
2208 case EVFILT_WRITE:
2209 kn->kn_fop = &sowrite_filtops;
2210 sb = &so->so_snd;
2211 break;
2212 default:
2213 sounlock(so);
2214 return (EINVAL);
2215 }
2216 SLIST_INSERT_HEAD(&sb->sb_sel.sel_klist, kn, kn_selnext);
2217 sb->sb_flags |= SB_KNOTE;
2218 sounlock(so);
2219 return (0);
2220 }
2221
2222 static int
2223 sodopoll(struct socket *so, int events)
2224 {
2225 int revents;
2226
2227 revents = 0;
2228
2229 if (events & (POLLIN | POLLRDNORM))
2230 if (soreadable(so))
2231 revents |= events & (POLLIN | POLLRDNORM);
2232
2233 if (events & (POLLOUT | POLLWRNORM))
2234 if (sowritable(so))
2235 revents |= events & (POLLOUT | POLLWRNORM);
2236
2237 if (events & (POLLPRI | POLLRDBAND))
2238 if (so->so_oobmark || (so->so_state & SS_RCVATMARK))
2239 revents |= events & (POLLPRI | POLLRDBAND);
2240
2241 return revents;
2242 }
2243
2244 int
2245 sopoll(struct socket *so, int events)
2246 {
2247 int revents = 0;
2248
2249 #ifndef DIAGNOSTIC
2250 /*
2251 * Do a quick, unlocked check in expectation that the socket
2252 * will be ready for I/O. Don't do this check if DIAGNOSTIC,
2253 * as the solocked() assertions will fail.
2254 */
2255 if ((revents = sodopoll(so, events)) != 0)
2256 return revents;
2257 #endif
2258
2259 solock(so);
2260 if ((revents = sodopoll(so, events)) == 0) {
2261 if (events & (POLLIN | POLLPRI | POLLRDNORM | POLLRDBAND)) {
2262 selrecord(curlwp, &so->so_rcv.sb_sel);
2263 so->so_rcv.sb_flags |= SB_NOTIFY;
2264 }
2265
2266 if (events & (POLLOUT | POLLWRNORM)) {
2267 selrecord(curlwp, &so->so_snd.sb_sel);
2268 so->so_snd.sb_flags |= SB_NOTIFY;
2269 }
2270 }
2271 sounlock(so);
2272
2273 return revents;
2274 }
2275
2276
2277 #include <sys/sysctl.h>
2278
2279 static int sysctl_kern_somaxkva(SYSCTLFN_PROTO);
2280
2281 /*
2282 * sysctl helper routine for kern.somaxkva. ensures that the given
2283 * value is not too small.
2284 * (XXX should we maybe make sure it's not too large as well?)
2285 */
2286 static int
2287 sysctl_kern_somaxkva(SYSCTLFN_ARGS)
2288 {
2289 int error, new_somaxkva;
2290 struct sysctlnode node;
2291
2292 new_somaxkva = somaxkva;
2293 node = *rnode;
2294 node.sysctl_data = &new_somaxkva;
2295 error = sysctl_lookup(SYSCTLFN_CALL(&node));
2296 if (error || newp == NULL)
2297 return (error);
2298
2299 if (new_somaxkva < (16 * 1024 * 1024)) /* sanity */
2300 return (EINVAL);
2301
2302 mutex_enter(&so_pendfree_lock);
2303 somaxkva = new_somaxkva;
2304 cv_broadcast(&socurkva_cv);
2305 mutex_exit(&so_pendfree_lock);
2306
2307 return (error);
2308 }
2309
2310 static void
2311 sysctl_kern_somaxkva_setup()
2312 {
2313
2314 KASSERT(socket_sysctllog == NULL);
2315 sysctl_createv(&socket_sysctllog, 0, NULL, NULL,
2316 CTLFLAG_PERMANENT,
2317 CTLTYPE_NODE, "kern", NULL,
2318 NULL, 0, NULL, 0,
2319 CTL_KERN, CTL_EOL);
2320
2321 sysctl_createv(&socket_sysctllog, 0, NULL, NULL,
2322 CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
2323 CTLTYPE_INT, "somaxkva",
2324 SYSCTL_DESCR("Maximum amount of kernel memory to be "
2325 "used for socket buffers"),
2326 sysctl_kern_somaxkva, 0, NULL, 0,
2327 CTL_KERN, KERN_SOMAXKVA, CTL_EOL);
2328 }
2329