uipc_socket.c revision 1.134.2.5 1 /* $NetBSD: uipc_socket.c,v 1.134.2.5 2007/09/01 12:56:49 ad Exp $ */
2
3 /*-
4 * Copyright (c) 2002, 2007 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 * 3. All advertising materials mentioning features or use of this software
19 * must display the following acknowledgement:
20 * This product includes software developed by the NetBSD
21 * Foundation, Inc. and its contributors.
22 * 4. Neither the name of The NetBSD Foundation nor the names of its
23 * contributors may be used to endorse or promote products derived
24 * from this software without specific prior written permission.
25 *
26 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
27 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
28 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
29 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
30 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
31 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
32 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
33 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
34 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
35 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
36 * POSSIBILITY OF SUCH DAMAGE.
37 */
38
39 /*
40 * Copyright (c) 1982, 1986, 1988, 1990, 1993
41 * The Regents of the University of California. All rights reserved.
42 *
43 * Redistribution and use in source and binary forms, with or without
44 * modification, are permitted provided that the following conditions
45 * are met:
46 * 1. Redistributions of source code must retain the above copyright
47 * notice, this list of conditions and the following disclaimer.
48 * 2. Redistributions in binary form must reproduce the above copyright
49 * notice, this list of conditions and the following disclaimer in the
50 * documentation and/or other materials provided with the distribution.
51 * 3. Neither the name of the University nor the names of its contributors
52 * may be used to endorse or promote products derived from this software
53 * without specific prior written permission.
54 *
55 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
56 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
57 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
58 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
59 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
60 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
61 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
62 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
63 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
64 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
65 * SUCH DAMAGE.
66 *
67 * @(#)uipc_socket.c 8.6 (Berkeley) 5/2/95
68 */
69
70 #include <sys/cdefs.h>
71 __KERNEL_RCSID(0, "$NetBSD: uipc_socket.c,v 1.134.2.5 2007/09/01 12:56:49 ad Exp $");
72
73 #include "opt_sock_counters.h"
74 #include "opt_sosend_loan.h"
75 #include "opt_mbuftrace.h"
76 #include "opt_somaxkva.h"
77
78 #include <sys/param.h>
79 #include <sys/systm.h>
80 #include <sys/proc.h>
81 #include <sys/file.h>
82 #include <sys/malloc.h>
83 #include <sys/mbuf.h>
84 #include <sys/domain.h>
85 #include <sys/kernel.h>
86 #include <sys/protosw.h>
87 #include <sys/socket.h>
88 #include <sys/socketvar.h>
89 #include <sys/signalvar.h>
90 #include <sys/resourcevar.h>
91 #include <sys/pool.h>
92 #include <sys/event.h>
93 #include <sys/poll.h>
94 #include <sys/kauth.h>
95 #include <sys/mutex.h>
96 #include <sys/condvar.h>
97
98 #include <uvm/uvm.h>
99
100 POOL_INIT(socket_pool, sizeof(struct socket), 0, 0, 0, "sockpl", NULL,
101 IPL_SOFTNET);
102
103 MALLOC_DEFINE(M_SOOPTS, "soopts", "socket options");
104 MALLOC_DEFINE(M_SONAME, "soname", "socket name");
105
106 extern int somaxconn; /* patchable (XXX sysctl) */
107 int somaxconn = SOMAXCONN;
108
109 #ifdef SOSEND_COUNTERS
110 #include <sys/device.h>
111
112 static struct evcnt sosend_loan_big = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
113 NULL, "sosend", "loan big");
114 static struct evcnt sosend_copy_big = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
115 NULL, "sosend", "copy big");
116 static struct evcnt sosend_copy_small = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
117 NULL, "sosend", "copy small");
118 static struct evcnt sosend_kvalimit = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
119 NULL, "sosend", "kva limit");
120
121 #define SOSEND_COUNTER_INCR(ev) (ev)->ev_count++
122
123 EVCNT_ATTACH_STATIC(sosend_loan_big);
124 EVCNT_ATTACH_STATIC(sosend_copy_big);
125 EVCNT_ATTACH_STATIC(sosend_copy_small);
126 EVCNT_ATTACH_STATIC(sosend_kvalimit);
127 #else
128
129 #define SOSEND_COUNTER_INCR(ev) /* nothing */
130
131 #endif /* SOSEND_COUNTERS */
132
133 static struct callback_entry sokva_reclaimerentry;
134
135 #ifdef SOSEND_NO_LOAN
136 int sock_loan_thresh = -1;
137 #else
138 int sock_loan_thresh = 4096;
139 #endif
140
141 static kmutex_t so_pendfree_lock;
142 static struct mbuf *so_pendfree;
143
144 #ifndef SOMAXKVA
145 #define SOMAXKVA (16 * 1024 * 1024)
146 #endif
147 int somaxkva = SOMAXKVA;
148 static int socurkva;
149 static kcondvar_t socurkva_cv;
150
151 #define SOCK_LOAN_CHUNK 65536
152
153 static size_t sodopendfree(void);
154 static size_t sodopendfreel(void);
155
156 static vsize_t
157 sokvareserve(struct socket *so, vsize_t len)
158 {
159 int error;
160
161 mutex_enter(&so_pendfree_lock);
162 while (socurkva + len > somaxkva) {
163 size_t freed;
164
165 /*
166 * try to do pendfree.
167 */
168
169 freed = sodopendfreel();
170
171 /*
172 * if some kva was freed, try again.
173 */
174
175 if (freed)
176 continue;
177
178 SOSEND_COUNTER_INCR(&sosend_kvalimit);
179 error = cv_wait_sig(&socurkva_cv, &so_pendfree_lock);
180 if (error) {
181 len = 0;
182 break;
183 }
184 }
185 socurkva += len;
186 mutex_exit(&so_pendfree_lock);
187 return len;
188 }
189
190 static void
191 sokvaunreserve(vsize_t len)
192 {
193
194 mutex_enter(&so_pendfree_lock);
195 socurkva -= len;
196 cv_broadcast(&socurkva_cv);
197 mutex_exit(&so_pendfree_lock);
198 }
199
200 /*
201 * sokvaalloc: allocate kva for loan.
202 */
203
204 vaddr_t
205 sokvaalloc(vsize_t len, struct socket *so)
206 {
207 vaddr_t lva;
208
209 /*
210 * reserve kva.
211 */
212
213 if (sokvareserve(so, len) == 0)
214 return 0;
215
216 /*
217 * allocate kva.
218 */
219
220 lva = uvm_km_alloc(kernel_map, len, 0, UVM_KMF_VAONLY | UVM_KMF_WAITVA);
221 if (lva == 0) {
222 sokvaunreserve(len);
223 return (0);
224 }
225
226 return lva;
227 }
228
229 /*
230 * sokvafree: free kva for loan.
231 */
232
233 void
234 sokvafree(vaddr_t sva, vsize_t len)
235 {
236
237 /*
238 * free kva.
239 */
240
241 uvm_km_free(kernel_map, sva, len, UVM_KMF_VAONLY);
242
243 /*
244 * unreserve kva.
245 */
246
247 sokvaunreserve(len);
248 }
249
250 static void
251 sodoloanfree(struct vm_page **pgs, void *buf, size_t size)
252 {
253 vaddr_t va, sva, eva;
254 vsize_t len;
255 paddr_t pa;
256 int i, npgs;
257
258 eva = round_page((vaddr_t) buf + size);
259 sva = trunc_page((vaddr_t) buf);
260 len = eva - sva;
261 npgs = len >> PAGE_SHIFT;
262
263 if (__predict_false(pgs == NULL)) {
264 pgs = alloca(npgs * sizeof(*pgs));
265
266 for (i = 0, va = sva; va < eva; i++, va += PAGE_SIZE) {
267 if (pmap_extract(pmap_kernel(), va, &pa) == false)
268 panic("sodoloanfree: va 0x%lx not mapped", va);
269 pgs[i] = PHYS_TO_VM_PAGE(pa);
270 }
271 }
272
273 pmap_kremove(sva, len);
274 pmap_update(pmap_kernel());
275 uvm_unloan(pgs, npgs, UVM_LOAN_TOPAGE);
276 sokvafree(sva, len);
277 }
278
279 static size_t
280 sodopendfree()
281 {
282 size_t rv;
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()
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
314 rv += m->m_ext.ext_size;
315 sodoloanfree((m->m_flags & M_EXT_PAGES) ?
316 m->m_ext.ext_pgs : NULL, m->m_ext.ext_buf,
317 m->m_ext.ext_size);
318 pool_cache_put(mb_cache, m);
319 }
320
321 mutex_enter(&so_pendfree_lock);
322 }
323
324 return (rv);
325 }
326
327 void
328 soloanfree(struct mbuf *m, void *buf, size_t size, void *arg)
329 {
330
331 if (m == NULL) {
332
333 /*
334 * called from MEXTREMOVE.
335 */
336
337 sodoloanfree(NULL, buf, size);
338 return;
339 }
340
341 /*
342 * postpone freeing mbuf.
343 *
344 * we can't do it in interrupt context
345 * because we need to put kva back to kernel_map.
346 */
347
348 mutex_enter(&so_pendfree_lock);
349 m->m_next = so_pendfree;
350 so_pendfree = m;
351 cv_broadcast(&socurkva_cv);
352 mutex_exit(&so_pendfree_lock);
353 }
354
355 static long
356 sosend_loan(struct socket *so, struct uio *uio, struct mbuf *m, long space)
357 {
358 struct iovec *iov = uio->uio_iov;
359 vaddr_t sva, eva;
360 vsize_t len;
361 vaddr_t lva, va;
362 int npgs, i, error;
363
364 if (VMSPACE_IS_KERNEL_P(uio->uio_vmspace))
365 return (0);
366
367 if (iov->iov_len < (size_t) space)
368 space = iov->iov_len;
369 if (space > SOCK_LOAN_CHUNK)
370 space = SOCK_LOAN_CHUNK;
371
372 eva = round_page((vaddr_t) iov->iov_base + space);
373 sva = trunc_page((vaddr_t) iov->iov_base);
374 len = eva - sva;
375 npgs = len >> PAGE_SHIFT;
376
377 /* XXX KDASSERT */
378 KASSERT(npgs <= M_EXT_MAXPAGES);
379
380 lva = sokvaalloc(len, so);
381 if (lva == 0)
382 return 0;
383
384 error = uvm_loan(&uio->uio_vmspace->vm_map, sva, len,
385 m->m_ext.ext_pgs, UVM_LOAN_TOPAGE);
386 if (error) {
387 sokvafree(lva, len);
388 return (0);
389 }
390
391 for (i = 0, va = lva; i < npgs; i++, va += PAGE_SIZE)
392 pmap_kenter_pa(va, VM_PAGE_TO_PHYS(m->m_ext.ext_pgs[i]),
393 VM_PROT_READ);
394 pmap_update(pmap_kernel());
395
396 lva += (vaddr_t) iov->iov_base & PAGE_MASK;
397
398 MEXTADD(m, (void *) lva, space, M_MBUF, soloanfree, so);
399 m->m_flags |= M_EXT_PAGES | M_EXT_ROMAP;
400
401 uio->uio_resid -= space;
402 /* uio_offset not updated, not set/used for write(2) */
403 uio->uio_iov->iov_base = (char *)uio->uio_iov->iov_base + space;
404 uio->uio_iov->iov_len -= space;
405 if (uio->uio_iov->iov_len == 0) {
406 uio->uio_iov++;
407 uio->uio_iovcnt--;
408 }
409
410 return (space);
411 }
412
413 static int
414 sokva_reclaim_callback(struct callback_entry *ce, void *obj, void *arg)
415 {
416
417 KASSERT(ce == &sokva_reclaimerentry);
418 KASSERT(obj == NULL);
419
420 sodopendfree();
421 if (!vm_map_starved_p(kernel_map)) {
422 return CALLBACK_CHAIN_ABORT;
423 }
424 return CALLBACK_CHAIN_CONTINUE;
425 }
426
427 void
428 soinit(void)
429 {
430
431 mutex_init(&so_pendfree_lock, MUTEX_DRIVER, IPL_VM);
432 cv_init(&socurkva_cv, "sokva");
433
434 /* Set the initial adjusted socket buffer size. */
435 if (sb_max_set(sb_max))
436 panic("bad initial sb_max value: %lu", sb_max);
437
438 callback_register(&vm_map_to_kernel(kernel_map)->vmk_reclaim_callback,
439 &sokva_reclaimerentry, NULL, sokva_reclaim_callback);
440 }
441
442 /*
443 * Socket operation routines.
444 * These routines are called by the routines in
445 * sys_socket.c or from a system process, and
446 * implement the semantics of socket operations by
447 * switching out to the protocol specific routines.
448 */
449 /*ARGSUSED*/
450 int
451 socreate(int dom, struct socket **aso, int type, int proto, struct lwp *l)
452 {
453 const struct protosw *prp;
454 struct socket *so;
455 uid_t uid;
456 int error, s;
457
458 error = kauth_authorize_network(l->l_cred, KAUTH_NETWORK_SOCKET,
459 KAUTH_REQ_NETWORK_SOCKET_OPEN, KAUTH_ARG(dom), KAUTH_ARG(type),
460 KAUTH_ARG(proto));
461 if (error != 0)
462 return error;
463
464 if (proto)
465 prp = pffindproto(dom, proto, type);
466 else
467 prp = pffindtype(dom, type);
468 if (prp == NULL) {
469 /* no support for domain */
470 if (pffinddomain(dom) == 0)
471 return EAFNOSUPPORT;
472 /* no support for socket type */
473 if (proto == 0 && type != 0)
474 return EPROTOTYPE;
475 return EPROTONOSUPPORT;
476 }
477 if (prp->pr_usrreq == NULL)
478 return EPROTONOSUPPORT;
479 if (prp->pr_type != type)
480 return EPROTOTYPE;
481 s = splsoftnet();
482 so = pool_get(&socket_pool, PR_WAITOK);
483 memset(so, 0, sizeof(*so));
484 TAILQ_INIT(&so->so_q0);
485 TAILQ_INIT(&so->so_q);
486 so->so_type = type;
487 so->so_proto = prp;
488 so->so_send = sosend;
489 so->so_receive = soreceive;
490 #ifdef MBUFTRACE
491 so->so_rcv.sb_mowner = &prp->pr_domain->dom_mowner;
492 so->so_snd.sb_mowner = &prp->pr_domain->dom_mowner;
493 so->so_mowner = &prp->pr_domain->dom_mowner;
494 #endif
495 uid = kauth_cred_geteuid(l->l_cred);
496 so->so_uidinfo = uid_find(uid);
497 error = (*prp->pr_usrreq)(so, PRU_ATTACH, NULL,
498 (struct mbuf *)(long)proto, NULL, l);
499 if (error != 0) {
500 so->so_state |= SS_NOFDREF;
501 sofree(so);
502 splx(s);
503 return error;
504 }
505 splx(s);
506 *aso = so;
507 return 0;
508 }
509
510 int
511 sobind(struct socket *so, struct mbuf *nam, struct lwp *l)
512 {
513 int s, error;
514
515 s = splsoftnet();
516 error = (*so->so_proto->pr_usrreq)(so, PRU_BIND, NULL, nam, NULL, l);
517 splx(s);
518 return error;
519 }
520
521 int
522 solisten(struct socket *so, int backlog)
523 {
524 int s, error;
525
526 s = splsoftnet();
527 error = (*so->so_proto->pr_usrreq)(so, PRU_LISTEN, NULL,
528 NULL, NULL, NULL);
529 if (error != 0) {
530 splx(s);
531 return error;
532 }
533 if (TAILQ_EMPTY(&so->so_q))
534 so->so_options |= SO_ACCEPTCONN;
535 if (backlog < 0)
536 backlog = 0;
537 so->so_qlimit = min(backlog, somaxconn);
538 splx(s);
539 return 0;
540 }
541
542 void
543 sofree(struct socket *so)
544 {
545
546 if (so->so_pcb || (so->so_state & SS_NOFDREF) == 0)
547 return;
548 if (so->so_head) {
549 /*
550 * We must not decommission a socket that's on the accept(2)
551 * queue. If we do, then accept(2) may hang after select(2)
552 * indicated that the listening socket was ready.
553 */
554 if (!soqremque(so, 0))
555 return;
556 }
557 if (so->so_rcv.sb_hiwat)
558 (void)chgsbsize(so->so_uidinfo, &so->so_rcv.sb_hiwat, 0,
559 RLIM_INFINITY);
560 if (so->so_snd.sb_hiwat)
561 (void)chgsbsize(so->so_uidinfo, &so->so_snd.sb_hiwat, 0,
562 RLIM_INFINITY);
563 sbrelease(&so->so_snd, so);
564 sorflush(so);
565 pool_put(&socket_pool, so);
566 }
567
568 /*
569 * Close a socket on last file table reference removal.
570 * Initiate disconnect if connected.
571 * Free socket when disconnect complete.
572 */
573 int
574 soclose(struct socket *so)
575 {
576 struct socket *so2;
577 int s, error;
578
579 error = 0;
580 s = splsoftnet(); /* conservative */
581 if (so->so_options & SO_ACCEPTCONN) {
582 while ((so2 = TAILQ_FIRST(&so->so_q0)) != 0) {
583 (void) soqremque(so2, 0);
584 (void) soabort(so2);
585 }
586 while ((so2 = TAILQ_FIRST(&so->so_q)) != 0) {
587 (void) soqremque(so2, 1);
588 (void) soabort(so2);
589 }
590 }
591 if (so->so_pcb == 0)
592 goto discard;
593 if (so->so_state & SS_ISCONNECTED) {
594 if ((so->so_state & SS_ISDISCONNECTING) == 0) {
595 error = sodisconnect(so);
596 if (error)
597 goto drop;
598 }
599 if (so->so_options & SO_LINGER) {
600 if ((so->so_state & SS_ISDISCONNECTING) &&
601 (so->so_state & SS_NBIO))
602 goto drop;
603 while (so->so_state & SS_ISCONNECTED) {
604 error = tsleep((void *)&so->so_timeo,
605 PSOCK | PCATCH, netcls,
606 so->so_linger * hz);
607 if (error)
608 break;
609 }
610 }
611 }
612 drop:
613 if (so->so_pcb) {
614 int error2 = (*so->so_proto->pr_usrreq)(so, PRU_DETACH,
615 NULL, NULL, NULL, NULL);
616 if (error == 0)
617 error = error2;
618 }
619 discard:
620 if (so->so_state & SS_NOFDREF)
621 panic("soclose: NOFDREF");
622 so->so_state |= SS_NOFDREF;
623 sofree(so);
624 splx(s);
625 return (error);
626 }
627
628 /*
629 * Must be called at splsoftnet...
630 */
631 int
632 soabort(struct socket *so)
633 {
634 int error;
635
636 KASSERT(so->so_head == NULL);
637 error = (*so->so_proto->pr_usrreq)(so, PRU_ABORT, NULL,
638 NULL, NULL, NULL);
639 if (error) {
640 sofree(so);
641 }
642 return error;
643 }
644
645 int
646 soaccept(struct socket *so, struct mbuf *nam)
647 {
648 int s, error;
649
650 error = 0;
651 s = splsoftnet();
652 if ((so->so_state & SS_NOFDREF) == 0)
653 panic("soaccept: !NOFDREF");
654 so->so_state &= ~SS_NOFDREF;
655 if ((so->so_state & SS_ISDISCONNECTED) == 0 ||
656 (so->so_proto->pr_flags & PR_ABRTACPTDIS) == 0)
657 error = (*so->so_proto->pr_usrreq)(so, PRU_ACCEPT,
658 NULL, nam, NULL, NULL);
659 else
660 error = ECONNABORTED;
661
662 splx(s);
663 return (error);
664 }
665
666 int
667 soconnect(struct socket *so, struct mbuf *nam, struct lwp *l)
668 {
669 int s, error;
670
671 if (so->so_options & SO_ACCEPTCONN)
672 return (EOPNOTSUPP);
673 s = splsoftnet();
674 /*
675 * If protocol is connection-based, can only connect once.
676 * Otherwise, if connected, try to disconnect first.
677 * This allows user to disconnect by connecting to, e.g.,
678 * a null address.
679 */
680 if (so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING) &&
681 ((so->so_proto->pr_flags & PR_CONNREQUIRED) ||
682 (error = sodisconnect(so))))
683 error = EISCONN;
684 else
685 error = (*so->so_proto->pr_usrreq)(so, PRU_CONNECT,
686 NULL, nam, NULL, l);
687 splx(s);
688 return (error);
689 }
690
691 int
692 soconnect2(struct socket *so1, struct socket *so2)
693 {
694 int s, error;
695
696 s = splsoftnet();
697 error = (*so1->so_proto->pr_usrreq)(so1, PRU_CONNECT2,
698 NULL, (struct mbuf *)so2, NULL, NULL);
699 splx(s);
700 return (error);
701 }
702
703 int
704 sodisconnect(struct socket *so)
705 {
706 int s, error;
707
708 s = splsoftnet();
709 if ((so->so_state & SS_ISCONNECTED) == 0) {
710 error = ENOTCONN;
711 goto bad;
712 }
713 if (so->so_state & SS_ISDISCONNECTING) {
714 error = EALREADY;
715 goto bad;
716 }
717 error = (*so->so_proto->pr_usrreq)(so, PRU_DISCONNECT,
718 NULL, NULL, NULL, NULL);
719 bad:
720 splx(s);
721 sodopendfree();
722 return (error);
723 }
724
725 #define SBLOCKWAIT(f) (((f) & MSG_DONTWAIT) ? M_NOWAIT : M_WAITOK)
726 /*
727 * Send on a socket.
728 * If send must go all at once and message is larger than
729 * send buffering, then hard error.
730 * Lock against other senders.
731 * If must go all at once and not enough room now, then
732 * inform user that this would block and do nothing.
733 * Otherwise, if nonblocking, send as much as possible.
734 * The data to be sent is described by "uio" if nonzero,
735 * otherwise by the mbuf chain "top" (which must be null
736 * if uio is not). Data provided in mbuf chain must be small
737 * enough to send all at once.
738 *
739 * Returns nonzero on error, timeout or signal; callers
740 * must check for short counts if EINTR/ERESTART are returned.
741 * Data and control buffers are freed on return.
742 */
743 int
744 sosend(struct socket *so, struct mbuf *addr, struct uio *uio, struct mbuf *top,
745 struct mbuf *control, int flags, struct lwp *l)
746 {
747 struct mbuf **mp, *m;
748 struct proc *p;
749 long space, len, resid, clen, mlen;
750 int error, s, dontroute, atomic;
751
752 p = l->l_proc;
753 sodopendfree();
754
755 clen = 0;
756 atomic = sosendallatonce(so) || top;
757 if (uio)
758 resid = uio->uio_resid;
759 else
760 resid = top->m_pkthdr.len;
761 /*
762 * In theory resid should be unsigned.
763 * However, space must be signed, as it might be less than 0
764 * if we over-committed, and we must use a signed comparison
765 * of space and resid. On the other hand, a negative resid
766 * causes us to loop sending 0-length segments to the protocol.
767 */
768 if (resid < 0) {
769 error = EINVAL;
770 goto out;
771 }
772 dontroute =
773 (flags & MSG_DONTROUTE) && (so->so_options & SO_DONTROUTE) == 0 &&
774 (so->so_proto->pr_flags & PR_ATOMIC);
775 if (p)
776 p->p_stats->p_ru.ru_msgsnd++;
777 if (control)
778 clen = control->m_len;
779 #define snderr(errno) { error = errno; splx(s); goto release; }
780
781 restart:
782 if ((error = sblock(&so->so_snd, SBLOCKWAIT(flags))) != 0)
783 goto out;
784 do {
785 s = splsoftnet();
786 if (so->so_state & SS_CANTSENDMORE)
787 snderr(EPIPE);
788 if (so->so_error) {
789 error = so->so_error;
790 so->so_error = 0;
791 splx(s);
792 goto release;
793 }
794 if ((so->so_state & SS_ISCONNECTED) == 0) {
795 if (so->so_proto->pr_flags & PR_CONNREQUIRED) {
796 if ((so->so_state & SS_ISCONFIRMING) == 0 &&
797 !(resid == 0 && clen != 0))
798 snderr(ENOTCONN);
799 } else if (addr == 0)
800 snderr(EDESTADDRREQ);
801 }
802 space = sbspace(&so->so_snd);
803 if (flags & MSG_OOB)
804 space += 1024;
805 if ((atomic && resid > so->so_snd.sb_hiwat) ||
806 clen > so->so_snd.sb_hiwat)
807 snderr(EMSGSIZE);
808 if (space < resid + clen &&
809 (atomic || space < so->so_snd.sb_lowat || space < clen)) {
810 if (so->so_state & SS_NBIO)
811 snderr(EWOULDBLOCK);
812 sbunlock(&so->so_snd);
813 error = sbwait(&so->so_snd);
814 splx(s);
815 if (error)
816 goto out;
817 goto restart;
818 }
819 splx(s);
820 mp = ⊤
821 space -= clen;
822 do {
823 if (uio == NULL) {
824 /*
825 * Data is prepackaged in "top".
826 */
827 resid = 0;
828 if (flags & MSG_EOR)
829 top->m_flags |= M_EOR;
830 } else do {
831 if (top == 0) {
832 m = m_gethdr(M_WAIT, MT_DATA);
833 mlen = MHLEN;
834 m->m_pkthdr.len = 0;
835 m->m_pkthdr.rcvif = NULL;
836 } else {
837 m = m_get(M_WAIT, MT_DATA);
838 mlen = MLEN;
839 }
840 MCLAIM(m, so->so_snd.sb_mowner);
841 if (sock_loan_thresh >= 0 &&
842 uio->uio_iov->iov_len >= sock_loan_thresh &&
843 space >= sock_loan_thresh &&
844 (len = sosend_loan(so, uio, m,
845 space)) != 0) {
846 SOSEND_COUNTER_INCR(&sosend_loan_big);
847 space -= len;
848 goto have_data;
849 }
850 if (resid >= MINCLSIZE && space >= MCLBYTES) {
851 SOSEND_COUNTER_INCR(&sosend_copy_big);
852 m_clget(m, M_WAIT);
853 if ((m->m_flags & M_EXT) == 0)
854 goto nopages;
855 mlen = MCLBYTES;
856 if (atomic && top == 0) {
857 len = lmin(MCLBYTES - max_hdr,
858 resid);
859 m->m_data += max_hdr;
860 } else
861 len = lmin(MCLBYTES, resid);
862 space -= len;
863 } else {
864 nopages:
865 SOSEND_COUNTER_INCR(&sosend_copy_small);
866 len = lmin(lmin(mlen, resid), space);
867 space -= len;
868 /*
869 * For datagram protocols, leave room
870 * for protocol headers in first mbuf.
871 */
872 if (atomic && top == 0 && len < mlen)
873 MH_ALIGN(m, len);
874 }
875 error = uiomove(mtod(m, void *), (int)len,
876 uio);
877 have_data:
878 resid = uio->uio_resid;
879 m->m_len = len;
880 *mp = m;
881 top->m_pkthdr.len += len;
882 if (error)
883 goto release;
884 mp = &m->m_next;
885 if (resid <= 0) {
886 if (flags & MSG_EOR)
887 top->m_flags |= M_EOR;
888 break;
889 }
890 } while (space > 0 && atomic);
891
892 s = splsoftnet();
893
894 if (so->so_state & SS_CANTSENDMORE)
895 snderr(EPIPE);
896
897 if (dontroute)
898 so->so_options |= SO_DONTROUTE;
899 if (resid > 0)
900 so->so_state |= SS_MORETOCOME;
901 error = (*so->so_proto->pr_usrreq)(so,
902 (flags & MSG_OOB) ? PRU_SENDOOB : PRU_SEND,
903 top, addr, control, curlwp); /* XXX */
904 if (dontroute)
905 so->so_options &= ~SO_DONTROUTE;
906 if (resid > 0)
907 so->so_state &= ~SS_MORETOCOME;
908 splx(s);
909
910 clen = 0;
911 control = 0;
912 top = 0;
913 mp = ⊤
914 if (error)
915 goto release;
916 } while (resid && space > 0);
917 } while (resid);
918
919 release:
920 sbunlock(&so->so_snd);
921 out:
922 if (top)
923 m_freem(top);
924 if (control)
925 m_freem(control);
926 return (error);
927 }
928
929 /*
930 * Implement receive operations on a socket.
931 * We depend on the way that records are added to the sockbuf
932 * by sbappend*. In particular, each record (mbufs linked through m_next)
933 * must begin with an address if the protocol so specifies,
934 * followed by an optional mbuf or mbufs containing ancillary data,
935 * and then zero or more mbufs of data.
936 * In order to avoid blocking network interrupts for the entire time here,
937 * we splx() while doing the actual copy to user space.
938 * Although the sockbuf is locked, new data may still be appended,
939 * and thus we must maintain consistency of the sockbuf during that time.
940 *
941 * The caller may receive the data as a single mbuf chain by supplying
942 * an mbuf **mp0 for use in returning the chain. The uio is then used
943 * only for the count in uio_resid.
944 */
945 int
946 soreceive(struct socket *so, struct mbuf **paddr, struct uio *uio,
947 struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
948 {
949 struct lwp *l = curlwp;
950 struct mbuf *m, **mp;
951 int flags, len, error, s, offset, moff, type, orig_resid;
952 const struct protosw *pr;
953 struct mbuf *nextrecord;
954 int mbuf_removed = 0;
955
956 pr = so->so_proto;
957 mp = mp0;
958 type = 0;
959 orig_resid = uio->uio_resid;
960
961 if (paddr)
962 *paddr = 0;
963 if (controlp)
964 *controlp = 0;
965 if (flagsp)
966 flags = *flagsp &~ MSG_EOR;
967 else
968 flags = 0;
969
970 if ((flags & MSG_DONTWAIT) == 0)
971 sodopendfree();
972
973 if (flags & MSG_OOB) {
974 m = m_get(M_WAIT, MT_DATA);
975 error = (*pr->pr_usrreq)(so, PRU_RCVOOB, m,
976 (struct mbuf *)(long)(flags & MSG_PEEK), NULL, l);
977 if (error)
978 goto bad;
979 do {
980 error = uiomove(mtod(m, void *),
981 (int) min(uio->uio_resid, m->m_len), uio);
982 m = m_free(m);
983 } while (uio->uio_resid && error == 0 && m);
984 bad:
985 if (m)
986 m_freem(m);
987 return (error);
988 }
989 if (mp)
990 *mp = NULL;
991 if (so->so_state & SS_ISCONFIRMING && uio->uio_resid)
992 (*pr->pr_usrreq)(so, PRU_RCVD, NULL, NULL, NULL, l);
993
994 restart:
995 if ((error = sblock(&so->so_rcv, SBLOCKWAIT(flags))) != 0)
996 return (error);
997 s = splsoftnet();
998
999 m = so->so_rcv.sb_mb;
1000 /*
1001 * If we have less data than requested, block awaiting more
1002 * (subject to any timeout) if:
1003 * 1. the current count is less than the low water mark,
1004 * 2. MSG_WAITALL is set, and it is possible to do the entire
1005 * receive operation at once if we block (resid <= hiwat), or
1006 * 3. MSG_DONTWAIT is not set.
1007 * If MSG_WAITALL is set but resid is larger than the receive buffer,
1008 * we have to do the receive in sections, and thus risk returning
1009 * a short count if a timeout or signal occurs after we start.
1010 */
1011 if (m == 0 || (((flags & MSG_DONTWAIT) == 0 &&
1012 so->so_rcv.sb_cc < uio->uio_resid) &&
1013 (so->so_rcv.sb_cc < so->so_rcv.sb_lowat ||
1014 ((flags & MSG_WAITALL) && uio->uio_resid <= so->so_rcv.sb_hiwat)) &&
1015 m->m_nextpkt == 0 && (pr->pr_flags & PR_ATOMIC) == 0)) {
1016 #ifdef DIAGNOSTIC
1017 if (m == 0 && so->so_rcv.sb_cc)
1018 panic("receive 1");
1019 #endif
1020 if (so->so_error) {
1021 if (m)
1022 goto dontblock;
1023 error = so->so_error;
1024 if ((flags & MSG_PEEK) == 0)
1025 so->so_error = 0;
1026 goto release;
1027 }
1028 if (so->so_state & SS_CANTRCVMORE) {
1029 if (m)
1030 goto dontblock;
1031 else
1032 goto release;
1033 }
1034 for (; m; m = m->m_next)
1035 if (m->m_type == MT_OOBDATA || (m->m_flags & M_EOR)) {
1036 m = so->so_rcv.sb_mb;
1037 goto dontblock;
1038 }
1039 if ((so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING)) == 0 &&
1040 (so->so_proto->pr_flags & PR_CONNREQUIRED)) {
1041 error = ENOTCONN;
1042 goto release;
1043 }
1044 if (uio->uio_resid == 0)
1045 goto release;
1046 if ((so->so_state & SS_NBIO) || (flags & MSG_DONTWAIT)) {
1047 error = EWOULDBLOCK;
1048 goto release;
1049 }
1050 SBLASTRECORDCHK(&so->so_rcv, "soreceive sbwait 1");
1051 SBLASTMBUFCHK(&so->so_rcv, "soreceive sbwait 1");
1052 sbunlock(&so->so_rcv);
1053 error = sbwait(&so->so_rcv);
1054 splx(s);
1055 if (error)
1056 return (error);
1057 goto restart;
1058 }
1059 dontblock:
1060 /*
1061 * On entry here, m points to the first record of the socket buffer.
1062 * While we process the initial mbufs containing address and control
1063 * info, we save a copy of m->m_nextpkt into nextrecord.
1064 */
1065 if (l)
1066 l->l_proc->p_stats->p_ru.ru_msgrcv++;
1067 KASSERT(m == so->so_rcv.sb_mb);
1068 SBLASTRECORDCHK(&so->so_rcv, "soreceive 1");
1069 SBLASTMBUFCHK(&so->so_rcv, "soreceive 1");
1070 nextrecord = m->m_nextpkt;
1071 if (pr->pr_flags & PR_ADDR) {
1072 #ifdef DIAGNOSTIC
1073 if (m->m_type != MT_SONAME)
1074 panic("receive 1a");
1075 #endif
1076 orig_resid = 0;
1077 if (flags & MSG_PEEK) {
1078 if (paddr)
1079 *paddr = m_copy(m, 0, m->m_len);
1080 m = m->m_next;
1081 } else {
1082 sbfree(&so->so_rcv, m);
1083 mbuf_removed = 1;
1084 if (paddr) {
1085 *paddr = m;
1086 so->so_rcv.sb_mb = m->m_next;
1087 m->m_next = 0;
1088 m = so->so_rcv.sb_mb;
1089 } else {
1090 MFREE(m, so->so_rcv.sb_mb);
1091 m = so->so_rcv.sb_mb;
1092 }
1093 }
1094 }
1095 while (m && m->m_type == MT_CONTROL && error == 0) {
1096 if (flags & MSG_PEEK) {
1097 if (controlp)
1098 *controlp = m_copy(m, 0, m->m_len);
1099 m = m->m_next;
1100 } else {
1101 sbfree(&so->so_rcv, m);
1102 mbuf_removed = 1;
1103 if (controlp) {
1104 struct domain *dom = pr->pr_domain;
1105 if (dom->dom_externalize && l &&
1106 mtod(m, struct cmsghdr *)->cmsg_type ==
1107 SCM_RIGHTS)
1108 error = (*dom->dom_externalize)(m, l);
1109 *controlp = m;
1110 so->so_rcv.sb_mb = m->m_next;
1111 m->m_next = 0;
1112 m = so->so_rcv.sb_mb;
1113 } else {
1114 /*
1115 * Dispose of any SCM_RIGHTS message that went
1116 * through the read path rather than recv.
1117 */
1118 if (pr->pr_domain->dom_dispose &&
1119 mtod(m, struct cmsghdr *)->cmsg_type == SCM_RIGHTS)
1120 (*pr->pr_domain->dom_dispose)(m);
1121 MFREE(m, so->so_rcv.sb_mb);
1122 m = so->so_rcv.sb_mb;
1123 }
1124 }
1125 if (controlp) {
1126 orig_resid = 0;
1127 controlp = &(*controlp)->m_next;
1128 }
1129 }
1130
1131 /*
1132 * If m is non-NULL, we have some data to read. From now on,
1133 * make sure to keep sb_lastrecord consistent when working on
1134 * the last packet on the chain (nextrecord == NULL) and we
1135 * change m->m_nextpkt.
1136 */
1137 if (m) {
1138 if ((flags & MSG_PEEK) == 0) {
1139 m->m_nextpkt = nextrecord;
1140 /*
1141 * If nextrecord == NULL (this is a single chain),
1142 * then sb_lastrecord may not be valid here if m
1143 * was changed earlier.
1144 */
1145 if (nextrecord == NULL) {
1146 KASSERT(so->so_rcv.sb_mb == m);
1147 so->so_rcv.sb_lastrecord = m;
1148 }
1149 }
1150 type = m->m_type;
1151 if (type == MT_OOBDATA)
1152 flags |= MSG_OOB;
1153 } else {
1154 if ((flags & MSG_PEEK) == 0) {
1155 KASSERT(so->so_rcv.sb_mb == m);
1156 so->so_rcv.sb_mb = nextrecord;
1157 SB_EMPTY_FIXUP(&so->so_rcv);
1158 }
1159 }
1160 SBLASTRECORDCHK(&so->so_rcv, "soreceive 2");
1161 SBLASTMBUFCHK(&so->so_rcv, "soreceive 2");
1162
1163 moff = 0;
1164 offset = 0;
1165 while (m && uio->uio_resid > 0 && error == 0) {
1166 if (m->m_type == MT_OOBDATA) {
1167 if (type != MT_OOBDATA)
1168 break;
1169 } else if (type == MT_OOBDATA)
1170 break;
1171 #ifdef DIAGNOSTIC
1172 else if (m->m_type != MT_DATA && m->m_type != MT_HEADER)
1173 panic("receive 3");
1174 #endif
1175 so->so_state &= ~SS_RCVATMARK;
1176 len = uio->uio_resid;
1177 if (so->so_oobmark && len > so->so_oobmark - offset)
1178 len = so->so_oobmark - offset;
1179 if (len > m->m_len - moff)
1180 len = m->m_len - moff;
1181 /*
1182 * If mp is set, just pass back the mbufs.
1183 * Otherwise copy them out via the uio, then free.
1184 * Sockbuf must be consistent here (points to current mbuf,
1185 * it points to next record) when we drop priority;
1186 * we must note any additions to the sockbuf when we
1187 * block interrupts again.
1188 */
1189 if (mp == 0) {
1190 SBLASTRECORDCHK(&so->so_rcv, "soreceive uiomove");
1191 SBLASTMBUFCHK(&so->so_rcv, "soreceive uiomove");
1192 splx(s);
1193 error = uiomove(mtod(m, char *) + moff, (int)len, uio);
1194 s = splsoftnet();
1195 if (error) {
1196 /*
1197 * If any part of the record has been removed
1198 * (such as the MT_SONAME mbuf, which will
1199 * happen when PR_ADDR, and thus also
1200 * PR_ATOMIC, is set), then drop the entire
1201 * record to maintain the atomicity of the
1202 * receive operation.
1203 *
1204 * This avoids a later panic("receive 1a")
1205 * when compiled with DIAGNOSTIC.
1206 */
1207 if (m && mbuf_removed
1208 && (pr->pr_flags & PR_ATOMIC))
1209 (void) sbdroprecord(&so->so_rcv);
1210
1211 goto release;
1212 }
1213 } else
1214 uio->uio_resid -= len;
1215 if (len == m->m_len - moff) {
1216 if (m->m_flags & M_EOR)
1217 flags |= MSG_EOR;
1218 if (flags & MSG_PEEK) {
1219 m = m->m_next;
1220 moff = 0;
1221 } else {
1222 nextrecord = m->m_nextpkt;
1223 sbfree(&so->so_rcv, m);
1224 if (mp) {
1225 *mp = m;
1226 mp = &m->m_next;
1227 so->so_rcv.sb_mb = m = m->m_next;
1228 *mp = NULL;
1229 } else {
1230 MFREE(m, so->so_rcv.sb_mb);
1231 m = so->so_rcv.sb_mb;
1232 }
1233 /*
1234 * If m != NULL, we also know that
1235 * so->so_rcv.sb_mb != NULL.
1236 */
1237 KASSERT(so->so_rcv.sb_mb == m);
1238 if (m) {
1239 m->m_nextpkt = nextrecord;
1240 if (nextrecord == NULL)
1241 so->so_rcv.sb_lastrecord = m;
1242 } else {
1243 so->so_rcv.sb_mb = nextrecord;
1244 SB_EMPTY_FIXUP(&so->so_rcv);
1245 }
1246 SBLASTRECORDCHK(&so->so_rcv, "soreceive 3");
1247 SBLASTMBUFCHK(&so->so_rcv, "soreceive 3");
1248 }
1249 } else {
1250 if (flags & MSG_PEEK)
1251 moff += len;
1252 else {
1253 if (mp)
1254 *mp = m_copym(m, 0, len, M_WAIT);
1255 m->m_data += len;
1256 m->m_len -= len;
1257 so->so_rcv.sb_cc -= len;
1258 }
1259 }
1260 if (so->so_oobmark) {
1261 if ((flags & MSG_PEEK) == 0) {
1262 so->so_oobmark -= len;
1263 if (so->so_oobmark == 0) {
1264 so->so_state |= SS_RCVATMARK;
1265 break;
1266 }
1267 } else {
1268 offset += len;
1269 if (offset == so->so_oobmark)
1270 break;
1271 }
1272 }
1273 if (flags & MSG_EOR)
1274 break;
1275 /*
1276 * If the MSG_WAITALL flag is set (for non-atomic socket),
1277 * we must not quit until "uio->uio_resid == 0" or an error
1278 * termination. If a signal/timeout occurs, return
1279 * with a short count but without error.
1280 * Keep sockbuf locked against other readers.
1281 */
1282 while (flags & MSG_WAITALL && m == 0 && uio->uio_resid > 0 &&
1283 !sosendallatonce(so) && !nextrecord) {
1284 if (so->so_error || so->so_state & SS_CANTRCVMORE)
1285 break;
1286 /*
1287 * If we are peeking and the socket receive buffer is
1288 * full, stop since we can't get more data to peek at.
1289 */
1290 if ((flags & MSG_PEEK) && sbspace(&so->so_rcv) <= 0)
1291 break;
1292 /*
1293 * If we've drained the socket buffer, tell the
1294 * protocol in case it needs to do something to
1295 * get it filled again.
1296 */
1297 if ((pr->pr_flags & PR_WANTRCVD) && so->so_pcb)
1298 (*pr->pr_usrreq)(so, PRU_RCVD,
1299 NULL, (struct mbuf *)(long)flags, NULL, l);
1300 SBLASTRECORDCHK(&so->so_rcv, "soreceive sbwait 2");
1301 SBLASTMBUFCHK(&so->so_rcv, "soreceive sbwait 2");
1302 error = sbwait(&so->so_rcv);
1303 if (error) {
1304 sbunlock(&so->so_rcv);
1305 splx(s);
1306 return (0);
1307 }
1308 if ((m = so->so_rcv.sb_mb) != NULL)
1309 nextrecord = m->m_nextpkt;
1310 }
1311 }
1312
1313 if (m && pr->pr_flags & PR_ATOMIC) {
1314 flags |= MSG_TRUNC;
1315 if ((flags & MSG_PEEK) == 0)
1316 (void) sbdroprecord(&so->so_rcv);
1317 }
1318 if ((flags & MSG_PEEK) == 0) {
1319 if (m == 0) {
1320 /*
1321 * First part is an inline SB_EMPTY_FIXUP(). Second
1322 * part makes sure sb_lastrecord is up-to-date if
1323 * there is still data in the socket buffer.
1324 */
1325 so->so_rcv.sb_mb = nextrecord;
1326 if (so->so_rcv.sb_mb == NULL) {
1327 so->so_rcv.sb_mbtail = NULL;
1328 so->so_rcv.sb_lastrecord = NULL;
1329 } else if (nextrecord->m_nextpkt == NULL)
1330 so->so_rcv.sb_lastrecord = nextrecord;
1331 }
1332 SBLASTRECORDCHK(&so->so_rcv, "soreceive 4");
1333 SBLASTMBUFCHK(&so->so_rcv, "soreceive 4");
1334 if (pr->pr_flags & PR_WANTRCVD && so->so_pcb)
1335 (*pr->pr_usrreq)(so, PRU_RCVD, NULL,
1336 (struct mbuf *)(long)flags, NULL, l);
1337 }
1338 if (orig_resid == uio->uio_resid && orig_resid &&
1339 (flags & MSG_EOR) == 0 && (so->so_state & SS_CANTRCVMORE) == 0) {
1340 sbunlock(&so->so_rcv);
1341 splx(s);
1342 goto restart;
1343 }
1344
1345 if (flagsp)
1346 *flagsp |= flags;
1347 release:
1348 sbunlock(&so->so_rcv);
1349 splx(s);
1350 return (error);
1351 }
1352
1353 int
1354 soshutdown(struct socket *so, int how)
1355 {
1356 const struct protosw *pr;
1357
1358 pr = so->so_proto;
1359 if (!(how == SHUT_RD || how == SHUT_WR || how == SHUT_RDWR))
1360 return (EINVAL);
1361
1362 if (how == SHUT_RD || how == SHUT_RDWR)
1363 sorflush(so);
1364 if (how == SHUT_WR || how == SHUT_RDWR)
1365 return (*pr->pr_usrreq)(so, PRU_SHUTDOWN, NULL,
1366 NULL, NULL, NULL);
1367 return (0);
1368 }
1369
1370 void
1371 sorflush(struct socket *so)
1372 {
1373 struct sockbuf *sb, asb;
1374 const struct protosw *pr;
1375 int s;
1376
1377 sb = &so->so_rcv;
1378 pr = so->so_proto;
1379 sb->sb_flags |= SB_NOINTR;
1380 (void) sblock(sb, M_WAITOK);
1381 s = splnet();
1382 socantrcvmore(so);
1383 sbunlock(sb);
1384 asb = *sb;
1385 /*
1386 * Clear most of the sockbuf structure, but leave some of the
1387 * fields valid.
1388 */
1389 memset(&sb->sb_startzero, 0,
1390 sizeof(*sb) - offsetof(struct sockbuf, sb_startzero));
1391 splx(s);
1392 if (pr->pr_flags & PR_RIGHTS && pr->pr_domain->dom_dispose)
1393 (*pr->pr_domain->dom_dispose)(asb.sb_mb);
1394 sbrelease(&asb, so);
1395 }
1396
1397 int
1398 sosetopt(struct socket *so, int level, int optname, struct mbuf *m0)
1399 {
1400 int error;
1401 struct mbuf *m;
1402 struct linger *l;
1403 struct sockbuf *sb;
1404
1405 error = 0;
1406 m = m0;
1407 if (level != SOL_SOCKET) {
1408 if (so->so_proto && so->so_proto->pr_ctloutput)
1409 return ((*so->so_proto->pr_ctloutput)
1410 (PRCO_SETOPT, so, level, optname, &m0));
1411 error = ENOPROTOOPT;
1412 } else {
1413 switch (optname) {
1414
1415 case SO_LINGER:
1416 if (m == NULL || m->m_len != sizeof(struct linger)) {
1417 error = EINVAL;
1418 goto bad;
1419 }
1420 l = mtod(m, struct linger *);
1421 if (l->l_linger < 0 || l->l_linger > USHRT_MAX ||
1422 l->l_linger > (INT_MAX / hz)) {
1423 error = EDOM;
1424 goto bad;
1425 }
1426 so->so_linger = l->l_linger;
1427 if (l->l_onoff)
1428 so->so_options |= SO_LINGER;
1429 else
1430 so->so_options &= ~SO_LINGER;
1431 break;
1432
1433 case SO_DEBUG:
1434 case SO_KEEPALIVE:
1435 case SO_DONTROUTE:
1436 case SO_USELOOPBACK:
1437 case SO_BROADCAST:
1438 case SO_REUSEADDR:
1439 case SO_REUSEPORT:
1440 case SO_OOBINLINE:
1441 case SO_TIMESTAMP:
1442 if (m == NULL || m->m_len < sizeof(int)) {
1443 error = EINVAL;
1444 goto bad;
1445 }
1446 if (*mtod(m, int *))
1447 so->so_options |= optname;
1448 else
1449 so->so_options &= ~optname;
1450 break;
1451
1452 case SO_SNDBUF:
1453 case SO_RCVBUF:
1454 case SO_SNDLOWAT:
1455 case SO_RCVLOWAT:
1456 {
1457 int optval;
1458
1459 if (m == NULL || m->m_len < sizeof(int)) {
1460 error = EINVAL;
1461 goto bad;
1462 }
1463
1464 /*
1465 * Values < 1 make no sense for any of these
1466 * options, so disallow them.
1467 */
1468 optval = *mtod(m, int *);
1469 if (optval < 1) {
1470 error = EINVAL;
1471 goto bad;
1472 }
1473
1474 switch (optname) {
1475
1476 case SO_SNDBUF:
1477 case SO_RCVBUF:
1478 sb = (optname == SO_SNDBUF) ?
1479 &so->so_snd : &so->so_rcv;
1480 if (sbreserve(sb, (u_long)optval, so) == 0) {
1481 error = ENOBUFS;
1482 goto bad;
1483 }
1484 sb->sb_flags &= ~SB_AUTOSIZE;
1485 break;
1486
1487 /*
1488 * Make sure the low-water is never greater than
1489 * the high-water.
1490 */
1491 case SO_SNDLOWAT:
1492 so->so_snd.sb_lowat =
1493 (optval > so->so_snd.sb_hiwat) ?
1494 so->so_snd.sb_hiwat : optval;
1495 break;
1496 case SO_RCVLOWAT:
1497 so->so_rcv.sb_lowat =
1498 (optval > so->so_rcv.sb_hiwat) ?
1499 so->so_rcv.sb_hiwat : optval;
1500 break;
1501 }
1502 break;
1503 }
1504
1505 case SO_SNDTIMEO:
1506 case SO_RCVTIMEO:
1507 {
1508 struct timeval *tv;
1509 int val;
1510
1511 if (m == NULL || m->m_len < sizeof(*tv)) {
1512 error = EINVAL;
1513 goto bad;
1514 }
1515 tv = mtod(m, struct timeval *);
1516 if (tv->tv_sec > (INT_MAX - tv->tv_usec / tick) / hz) {
1517 error = EDOM;
1518 goto bad;
1519 }
1520 val = tv->tv_sec * hz + tv->tv_usec / tick;
1521 if (val == 0 && tv->tv_usec != 0)
1522 val = 1;
1523
1524 switch (optname) {
1525
1526 case SO_SNDTIMEO:
1527 so->so_snd.sb_timeo = val;
1528 break;
1529 case SO_RCVTIMEO:
1530 so->so_rcv.sb_timeo = val;
1531 break;
1532 }
1533 break;
1534 }
1535
1536 default:
1537 error = ENOPROTOOPT;
1538 break;
1539 }
1540 if (error == 0 && so->so_proto && so->so_proto->pr_ctloutput) {
1541 (void) ((*so->so_proto->pr_ctloutput)
1542 (PRCO_SETOPT, so, level, optname, &m0));
1543 m = NULL; /* freed by protocol */
1544 }
1545 }
1546 bad:
1547 if (m)
1548 (void) m_free(m);
1549 return (error);
1550 }
1551
1552 int
1553 sogetopt(struct socket *so, int level, int optname, struct mbuf **mp)
1554 {
1555 struct mbuf *m;
1556
1557 if (level != SOL_SOCKET) {
1558 if (so->so_proto && so->so_proto->pr_ctloutput) {
1559 return ((*so->so_proto->pr_ctloutput)
1560 (PRCO_GETOPT, so, level, optname, mp));
1561 } else
1562 return (ENOPROTOOPT);
1563 } else {
1564 m = m_get(M_WAIT, MT_SOOPTS);
1565 m->m_len = sizeof(int);
1566
1567 switch (optname) {
1568
1569 case SO_LINGER:
1570 m->m_len = sizeof(struct linger);
1571 mtod(m, struct linger *)->l_onoff =
1572 (so->so_options & SO_LINGER) ? 1 : 0;
1573 mtod(m, struct linger *)->l_linger = so->so_linger;
1574 break;
1575
1576 case SO_USELOOPBACK:
1577 case SO_DONTROUTE:
1578 case SO_DEBUG:
1579 case SO_KEEPALIVE:
1580 case SO_REUSEADDR:
1581 case SO_REUSEPORT:
1582 case SO_BROADCAST:
1583 case SO_OOBINLINE:
1584 case SO_TIMESTAMP:
1585 *mtod(m, int *) = (so->so_options & optname) ? 1 : 0;
1586 break;
1587
1588 case SO_TYPE:
1589 *mtod(m, int *) = so->so_type;
1590 break;
1591
1592 case SO_ERROR:
1593 *mtod(m, int *) = so->so_error;
1594 so->so_error = 0;
1595 break;
1596
1597 case SO_SNDBUF:
1598 *mtod(m, int *) = so->so_snd.sb_hiwat;
1599 break;
1600
1601 case SO_RCVBUF:
1602 *mtod(m, int *) = so->so_rcv.sb_hiwat;
1603 break;
1604
1605 case SO_SNDLOWAT:
1606 *mtod(m, int *) = so->so_snd.sb_lowat;
1607 break;
1608
1609 case SO_RCVLOWAT:
1610 *mtod(m, int *) = so->so_rcv.sb_lowat;
1611 break;
1612
1613 case SO_SNDTIMEO:
1614 case SO_RCVTIMEO:
1615 {
1616 int val = (optname == SO_SNDTIMEO ?
1617 so->so_snd.sb_timeo : so->so_rcv.sb_timeo);
1618
1619 m->m_len = sizeof(struct timeval);
1620 mtod(m, struct timeval *)->tv_sec = val / hz;
1621 mtod(m, struct timeval *)->tv_usec =
1622 (val % hz) * tick;
1623 break;
1624 }
1625
1626 case SO_OVERFLOWED:
1627 *mtod(m, int *) = so->so_rcv.sb_overflowed;
1628 break;
1629
1630 default:
1631 (void)m_free(m);
1632 return (ENOPROTOOPT);
1633 }
1634 *mp = m;
1635 return (0);
1636 }
1637 }
1638
1639 void
1640 sohasoutofband(struct socket *so)
1641 {
1642 fownsignal(so->so_pgid, SIGURG, POLL_PRI, POLLPRI|POLLRDBAND, so);
1643 selwakeup(&so->so_rcv.sb_sel);
1644 }
1645
1646 static void
1647 filt_sordetach(struct knote *kn)
1648 {
1649 struct socket *so;
1650
1651 so = (struct socket *)kn->kn_fp->f_data;
1652 SLIST_REMOVE(&so->so_rcv.sb_sel.sel_klist, kn, knote, kn_selnext);
1653 if (SLIST_EMPTY(&so->so_rcv.sb_sel.sel_klist))
1654 so->so_rcv.sb_flags &= ~SB_KNOTE;
1655 }
1656
1657 /*ARGSUSED*/
1658 static int
1659 filt_soread(struct knote *kn, long hint)
1660 {
1661 struct socket *so;
1662
1663 so = (struct socket *)kn->kn_fp->f_data;
1664 kn->kn_data = so->so_rcv.sb_cc;
1665 if (so->so_state & SS_CANTRCVMORE) {
1666 kn->kn_flags |= EV_EOF;
1667 kn->kn_fflags = so->so_error;
1668 return (1);
1669 }
1670 if (so->so_error) /* temporary udp error */
1671 return (1);
1672 if (kn->kn_sfflags & NOTE_LOWAT)
1673 return (kn->kn_data >= kn->kn_sdata);
1674 return (kn->kn_data >= so->so_rcv.sb_lowat);
1675 }
1676
1677 static void
1678 filt_sowdetach(struct knote *kn)
1679 {
1680 struct socket *so;
1681
1682 so = (struct socket *)kn->kn_fp->f_data;
1683 SLIST_REMOVE(&so->so_snd.sb_sel.sel_klist, kn, knote, kn_selnext);
1684 if (SLIST_EMPTY(&so->so_snd.sb_sel.sel_klist))
1685 so->so_snd.sb_flags &= ~SB_KNOTE;
1686 }
1687
1688 /*ARGSUSED*/
1689 static int
1690 filt_sowrite(struct knote *kn, long hint)
1691 {
1692 struct socket *so;
1693
1694 so = (struct socket *)kn->kn_fp->f_data;
1695 kn->kn_data = sbspace(&so->so_snd);
1696 if (so->so_state & SS_CANTSENDMORE) {
1697 kn->kn_flags |= EV_EOF;
1698 kn->kn_fflags = so->so_error;
1699 return (1);
1700 }
1701 if (so->so_error) /* temporary udp error */
1702 return (1);
1703 if (((so->so_state & SS_ISCONNECTED) == 0) &&
1704 (so->so_proto->pr_flags & PR_CONNREQUIRED))
1705 return (0);
1706 if (kn->kn_sfflags & NOTE_LOWAT)
1707 return (kn->kn_data >= kn->kn_sdata);
1708 return (kn->kn_data >= so->so_snd.sb_lowat);
1709 }
1710
1711 /*ARGSUSED*/
1712 static int
1713 filt_solisten(struct knote *kn, long hint)
1714 {
1715 struct socket *so;
1716
1717 so = (struct socket *)kn->kn_fp->f_data;
1718
1719 /*
1720 * Set kn_data to number of incoming connections, not
1721 * counting partial (incomplete) connections.
1722 */
1723 kn->kn_data = so->so_qlen;
1724 return (kn->kn_data > 0);
1725 }
1726
1727 static const struct filterops solisten_filtops =
1728 { 1, NULL, filt_sordetach, filt_solisten };
1729 static const struct filterops soread_filtops =
1730 { 1, NULL, filt_sordetach, filt_soread };
1731 static const struct filterops sowrite_filtops =
1732 { 1, NULL, filt_sowdetach, filt_sowrite };
1733
1734 int
1735 soo_kqfilter(struct file *fp, struct knote *kn)
1736 {
1737 struct socket *so;
1738 struct sockbuf *sb;
1739
1740 so = (struct socket *)kn->kn_fp->f_data;
1741 switch (kn->kn_filter) {
1742 case EVFILT_READ:
1743 if (so->so_options & SO_ACCEPTCONN)
1744 kn->kn_fop = &solisten_filtops;
1745 else
1746 kn->kn_fop = &soread_filtops;
1747 sb = &so->so_rcv;
1748 break;
1749 case EVFILT_WRITE:
1750 kn->kn_fop = &sowrite_filtops;
1751 sb = &so->so_snd;
1752 break;
1753 default:
1754 return (1);
1755 }
1756 SLIST_INSERT_HEAD(&sb->sb_sel.sel_klist, kn, kn_selnext);
1757 sb->sb_flags |= SB_KNOTE;
1758 return (0);
1759 }
1760
1761 #include <sys/sysctl.h>
1762
1763 static int sysctl_kern_somaxkva(SYSCTLFN_PROTO);
1764
1765 /*
1766 * sysctl helper routine for kern.somaxkva. ensures that the given
1767 * value is not too small.
1768 * (XXX should we maybe make sure it's not too large as well?)
1769 */
1770 static int
1771 sysctl_kern_somaxkva(SYSCTLFN_ARGS)
1772 {
1773 int error, new_somaxkva;
1774 struct sysctlnode node;
1775
1776 new_somaxkva = somaxkva;
1777 node = *rnode;
1778 node.sysctl_data = &new_somaxkva;
1779 error = sysctl_lookup(SYSCTLFN_CALL(&node));
1780 if (error || newp == NULL)
1781 return (error);
1782
1783 if (new_somaxkva < (16 * 1024 * 1024)) /* sanity */
1784 return (EINVAL);
1785
1786 mutex_enter(&so_pendfree_lock);
1787 somaxkva = new_somaxkva;
1788 cv_broadcast(&socurkva_cv);
1789 mutex_exit(&so_pendfree_lock);
1790
1791 return (error);
1792 }
1793
1794 SYSCTL_SETUP(sysctl_kern_somaxkva_setup, "sysctl kern.somaxkva setup")
1795 {
1796
1797 sysctl_createv(clog, 0, NULL, NULL,
1798 CTLFLAG_PERMANENT,
1799 CTLTYPE_NODE, "kern", NULL,
1800 NULL, 0, NULL, 0,
1801 CTL_KERN, CTL_EOL);
1802
1803 sysctl_createv(clog, 0, NULL, NULL,
1804 CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
1805 CTLTYPE_INT, "somaxkva",
1806 SYSCTL_DESCR("Maximum amount of kernel memory to be "
1807 "used for socket buffers"),
1808 sysctl_kern_somaxkva, 0, NULL, 0,
1809 CTL_KERN, KERN_SOMAXKVA, CTL_EOL);
1810 }
1811