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