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