uipc_socket.c revision 1.134.2.1 1 /* $NetBSD: uipc_socket.c,v 1.134.2.1 2007/03/13 16:51:58 ad 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.134.2.1 2007/03/13 16:51:58 ad Exp $");
72
73 #include "opt_sock_counters.h"
74 #include "opt_sosend_loan.h"
75 #include "opt_mbuftrace.h"
76 #include "opt_somaxkva.h"
77
78 #include <sys/param.h>
79 #include <sys/systm.h>
80 #include <sys/proc.h>
81 #include <sys/file.h>
82 #include <sys/malloc.h>
83 #include <sys/mbuf.h>
84 #include <sys/domain.h>
85 #include <sys/kernel.h>
86 #include <sys/protosw.h>
87 #include <sys/socket.h>
88 #include <sys/socketvar.h>
89 #include <sys/signalvar.h>
90 #include <sys/resourcevar.h>
91 #include <sys/pool.h>
92 #include <sys/event.h>
93 #include <sys/poll.h>
94 #include <sys/kauth.h>
95 #include <sys/mutex.h>
96 #include <sys/condvar.h>
97
98 #include <uvm/uvm.h>
99
100 POOL_INIT(socket_pool, sizeof(struct socket), 0, 0, 0, "sockpl", NULL,
101 IPL_SOFTNET);
102
103 MALLOC_DEFINE(M_SOOPTS, "soopts", "socket options");
104 MALLOC_DEFINE(M_SONAME, "soname", "socket name");
105
106 extern int somaxconn; /* patchable (XXX sysctl) */
107 int somaxconn = SOMAXCONN;
108
109 #ifdef SOSEND_COUNTERS
110 #include <sys/device.h>
111
112 static struct evcnt sosend_loan_big = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
113 NULL, "sosend", "loan big");
114 static struct evcnt sosend_copy_big = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
115 NULL, "sosend", "copy big");
116 static struct evcnt sosend_copy_small = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
117 NULL, "sosend", "copy small");
118 static struct evcnt sosend_kvalimit = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
119 NULL, "sosend", "kva limit");
120
121 #define SOSEND_COUNTER_INCR(ev) (ev)->ev_count++
122
123 EVCNT_ATTACH_STATIC(sosend_loan_big);
124 EVCNT_ATTACH_STATIC(sosend_copy_big);
125 EVCNT_ATTACH_STATIC(sosend_copy_small);
126 EVCNT_ATTACH_STATIC(sosend_kvalimit);
127 #else
128
129 #define SOSEND_COUNTER_INCR(ev) /* nothing */
130
131 #endif /* SOSEND_COUNTERS */
132
133 static struct callback_entry sokva_reclaimerentry;
134
135 #ifdef SOSEND_NO_LOAN
136 int sock_loan_thresh = -1;
137 #else
138 int sock_loan_thresh = 4096;
139 #endif
140
141 static kmutex_t so_pendfree_lock;
142 static struct mbuf *so_pendfree;
143
144 #ifndef SOMAXKVA
145 #define SOMAXKVA (16 * 1024 * 1024)
146 #endif
147 int somaxkva = SOMAXKVA;
148 static int socurkva;
149 static kcondvar_t socurkva_cv;
150
151 #define SOCK_LOAN_CHUNK 65536
152
153 static size_t sodopendfree(void);
154 static size_t sodopendfreel(void);
155
156 static vsize_t
157 sokvareserve(struct socket *so, vsize_t len)
158 {
159 int error;
160
161 mutex_enter(&so_pendfree_lock);
162 while (socurkva + len > somaxkva) {
163 size_t freed;
164
165 /*
166 * try to do pendfree.
167 */
168
169 freed = sodopendfreel();
170
171 /*
172 * if some kva was freed, try again.
173 */
174
175 if (freed)
176 continue;
177
178 SOSEND_COUNTER_INCR(&sosend_kvalimit);
179 error = cv_wait_sig(&socurkva_cv, &so_pendfree_lock);
180 if (error) {
181 len = 0;
182 break;
183 }
184 }
185 socurkva += len;
186 mutex_exit(&so_pendfree_lock);
187 return len;
188 }
189
190 static void
191 sokvaunreserve(vsize_t len)
192 {
193
194 mutex_enter(&so_pendfree_lock);
195 socurkva -= len;
196 cv_broadcast(&socurkva_cv);
197 mutex_exit(&so_pendfree_lock);
198 }
199
200 /*
201 * sokvaalloc: allocate kva for loan.
202 */
203
204 vaddr_t
205 sokvaalloc(vsize_t len, struct socket *so)
206 {
207 vaddr_t lva;
208
209 /*
210 * reserve kva.
211 */
212
213 if (sokvareserve(so, len) == 0)
214 return 0;
215
216 /*
217 * allocate kva.
218 */
219
220 lva = uvm_km_alloc(kernel_map, len, 0, UVM_KMF_VAONLY | UVM_KMF_WAITVA);
221 if (lva == 0) {
222 sokvaunreserve(len);
223 return (0);
224 }
225
226 return lva;
227 }
228
229 /*
230 * sokvafree: free kva for loan.
231 */
232
233 void
234 sokvafree(vaddr_t sva, vsize_t len)
235 {
236
237 /*
238 * free kva.
239 */
240
241 uvm_km_free(kernel_map, sva, len, UVM_KMF_VAONLY);
242
243 /*
244 * unreserve kva.
245 */
246
247 sokvaunreserve(len);
248 }
249
250 static void
251 sodoloanfree(struct vm_page **pgs, void *buf, size_t size)
252 {
253 vaddr_t va, sva, eva;
254 vsize_t len;
255 paddr_t pa;
256 int i, npgs;
257
258 eva = round_page((vaddr_t) buf + size);
259 sva = trunc_page((vaddr_t) buf);
260 len = eva - sva;
261 npgs = len >> PAGE_SHIFT;
262
263 if (__predict_false(pgs == NULL)) {
264 pgs = alloca(npgs * sizeof(*pgs));
265
266 for (i = 0, va = sva; va < eva; i++, va += PAGE_SIZE) {
267 if (pmap_extract(pmap_kernel(), va, &pa) == false)
268 panic("sodoloanfree: va 0x%lx not mapped", va);
269 pgs[i] = PHYS_TO_VM_PAGE(pa);
270 }
271 }
272
273 pmap_kremove(sva, len);
274 pmap_update(pmap_kernel());
275 uvm_unloan(pgs, npgs, UVM_LOAN_TOPAGE);
276 sokvafree(sva, len);
277 }
278
279 static size_t
280 sodopendfree()
281 {
282 size_t rv;
283
284 mutex_enter(&so_pendfree_lock);
285 rv = sodopendfreel();
286 mutex_exit(&so_pendfree_lock);
287
288 return rv;
289 }
290
291 /*
292 * sodopendfreel: free mbufs on "pendfree" list.
293 * unlock and relock so_pendfree_lock when freeing mbufs.
294 *
295 * => called with so_pendfree_lock held.
296 */
297
298 static size_t
299 sodopendfreel()
300 {
301 size_t rv = 0;
302
303 KASSERT(mutex_owned(&so_pendfree_lock));
304
305 for (;;) {
306 struct mbuf *m;
307 struct mbuf *next;
308
309 m = so_pendfree;
310 if (m == NULL)
311 break;
312 so_pendfree = NULL;
313 mutex_exit(&so_pendfree_lock);
314
315 for (; m != NULL; m = next) {
316 next = m->m_next;
317
318 rv += m->m_ext.ext_size;
319 sodoloanfree((m->m_flags & M_EXT_PAGES) ?
320 m->m_ext.ext_pgs : NULL, m->m_ext.ext_buf,
321 m->m_ext.ext_size);
322 pool_cache_put(&mbpool_cache, m);
323 }
324
325 mutex_enter(&so_pendfree_lock);
326 }
327
328 return (rv);
329 }
330
331 void
332 soloanfree(struct mbuf *m, void *buf, size_t size, void *arg)
333 {
334
335 if (m == NULL) {
336
337 /*
338 * called from MEXTREMOVE.
339 */
340
341 sodoloanfree(NULL, buf, size);
342 return;
343 }
344
345 /*
346 * postpone freeing mbuf.
347 *
348 * we can't do it in interrupt context
349 * because we need to put kva back to kernel_map.
350 */
351
352 mutex_enter(&so_pendfree_lock);
353 m->m_next = so_pendfree;
354 so_pendfree = m;
355 cv_broadcast(&socurkva_cv);
356 mutex_exit(&so_pendfree_lock);
357 }
358
359 static long
360 sosend_loan(struct socket *so, struct uio *uio, struct mbuf *m, long space)
361 {
362 struct iovec *iov = uio->uio_iov;
363 vaddr_t sva, eva;
364 vsize_t len;
365 vaddr_t lva, va;
366 int npgs, i, error;
367
368 if (VMSPACE_IS_KERNEL_P(uio->uio_vmspace))
369 return (0);
370
371 if (iov->iov_len < (size_t) space)
372 space = iov->iov_len;
373 if (space > SOCK_LOAN_CHUNK)
374 space = SOCK_LOAN_CHUNK;
375
376 eva = round_page((vaddr_t) iov->iov_base + space);
377 sva = trunc_page((vaddr_t) iov->iov_base);
378 len = eva - sva;
379 npgs = len >> PAGE_SHIFT;
380
381 /* XXX KDASSERT */
382 KASSERT(npgs <= M_EXT_MAXPAGES);
383
384 lva = sokvaalloc(len, so);
385 if (lva == 0)
386 return 0;
387
388 error = uvm_loan(&uio->uio_vmspace->vm_map, sva, len,
389 m->m_ext.ext_pgs, UVM_LOAN_TOPAGE);
390 if (error) {
391 sokvafree(lva, len);
392 return (0);
393 }
394
395 for (i = 0, va = lva; i < npgs; i++, va += PAGE_SIZE)
396 pmap_kenter_pa(va, VM_PAGE_TO_PHYS(m->m_ext.ext_pgs[i]),
397 VM_PROT_READ);
398 pmap_update(pmap_kernel());
399
400 lva += (vaddr_t) iov->iov_base & PAGE_MASK;
401
402 MEXTADD(m, (void *) lva, space, M_MBUF, soloanfree, so);
403 m->m_flags |= M_EXT_PAGES | M_EXT_ROMAP;
404
405 uio->uio_resid -= space;
406 /* uio_offset not updated, not set/used for write(2) */
407 uio->uio_iov->iov_base = (char *)uio->uio_iov->iov_base + space;
408 uio->uio_iov->iov_len -= space;
409 if (uio->uio_iov->iov_len == 0) {
410 uio->uio_iov++;
411 uio->uio_iovcnt--;
412 }
413
414 return (space);
415 }
416
417 static int
418 sokva_reclaim_callback(struct callback_entry *ce, void *obj, void *arg)
419 {
420
421 KASSERT(ce == &sokva_reclaimerentry);
422 KASSERT(obj == NULL);
423
424 sodopendfree();
425 if (!vm_map_starved_p(kernel_map)) {
426 return CALLBACK_CHAIN_ABORT;
427 }
428 return CALLBACK_CHAIN_CONTINUE;
429 }
430
431 void
432 soinit(void)
433 {
434
435 mutex_init(&so_pendfree_lock, MUTEX_DRIVER, IPL_VM);
436 cv_init(&socurkva_cv, "sokva");
437
438 /* Set the initial adjusted socket buffer size. */
439 if (sb_max_set(sb_max))
440 panic("bad initial sb_max value: %lu", sb_max);
441
442 callback_register(&vm_map_to_kernel(kernel_map)->vmk_reclaim_callback,
443 &sokva_reclaimerentry, NULL, sokva_reclaim_callback);
444 }
445
446 /*
447 * Socket operation routines.
448 * These routines are called by the routines in
449 * sys_socket.c or from a system process, and
450 * implement the semantics of socket operations by
451 * switching out to the protocol specific routines.
452 */
453 /*ARGSUSED*/
454 int
455 socreate(int dom, struct socket **aso, int type, int proto, struct lwp *l)
456 {
457 const struct protosw *prp;
458 struct socket *so;
459 uid_t uid;
460 int error, s;
461
462 error = kauth_authorize_network(l->l_cred, KAUTH_NETWORK_SOCKET,
463 KAUTH_REQ_NETWORK_SOCKET_OPEN, KAUTH_ARG(dom), KAUTH_ARG(type),
464 KAUTH_ARG(proto));
465 if (error)
466 return (error);
467
468 if (proto)
469 prp = pffindproto(dom, proto, type);
470 else
471 prp = pffindtype(dom, type);
472 if (prp == 0) {
473 /* no support for domain */
474 if (pffinddomain(dom) == 0)
475 return (EAFNOSUPPORT);
476 /* no support for socket type */
477 if (proto == 0 && type != 0)
478 return (EPROTOTYPE);
479 return (EPROTONOSUPPORT);
480 }
481 if (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((void *)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_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((void *)&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 (sock_loan_thresh >= 0 &&
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, void *), (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, void *),
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, char *) + 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 struct linger *l;
1413
1414 error = 0;
1415 m = m0;
1416 if (level != SOL_SOCKET) {
1417 if (so->so_proto && so->so_proto->pr_ctloutput)
1418 return ((*so->so_proto->pr_ctloutput)
1419 (PRCO_SETOPT, so, level, optname, &m0));
1420 error = ENOPROTOOPT;
1421 } else {
1422 switch (optname) {
1423
1424 case SO_LINGER:
1425 if (m == NULL || m->m_len != sizeof(struct linger)) {
1426 error = EINVAL;
1427 goto bad;
1428 }
1429 l = mtod(m, struct linger *);
1430 if (l->l_linger < 0 || l->l_linger > USHRT_MAX ||
1431 l->l_linger > (INT_MAX / hz)) {
1432 error = EDOM;
1433 goto bad;
1434 }
1435 so->so_linger = l->l_linger;
1436 if (l->l_onoff)
1437 so->so_options |= SO_LINGER;
1438 else
1439 so->so_options &= ~SO_LINGER;
1440 break;
1441
1442 case SO_DEBUG:
1443 case SO_KEEPALIVE:
1444 case SO_DONTROUTE:
1445 case SO_USELOOPBACK:
1446 case SO_BROADCAST:
1447 case SO_REUSEADDR:
1448 case SO_REUSEPORT:
1449 case SO_OOBINLINE:
1450 case SO_TIMESTAMP:
1451 if (m == NULL || m->m_len < sizeof(int)) {
1452 error = EINVAL;
1453 goto bad;
1454 }
1455 if (*mtod(m, int *))
1456 so->so_options |= optname;
1457 else
1458 so->so_options &= ~optname;
1459 break;
1460
1461 case SO_SNDBUF:
1462 case SO_RCVBUF:
1463 case SO_SNDLOWAT:
1464 case SO_RCVLOWAT:
1465 {
1466 int optval;
1467
1468 if (m == NULL || m->m_len < sizeof(int)) {
1469 error = EINVAL;
1470 goto bad;
1471 }
1472
1473 /*
1474 * Values < 1 make no sense for any of these
1475 * options, so disallow them.
1476 */
1477 optval = *mtod(m, int *);
1478 if (optval < 1) {
1479 error = EINVAL;
1480 goto bad;
1481 }
1482
1483 switch (optname) {
1484
1485 case SO_SNDBUF:
1486 case SO_RCVBUF:
1487 if (sbreserve(optname == SO_SNDBUF ?
1488 &so->so_snd : &so->so_rcv,
1489 (u_long) optval, so) == 0) {
1490 error = ENOBUFS;
1491 goto bad;
1492 }
1493 break;
1494
1495 /*
1496 * Make sure the low-water is never greater than
1497 * the high-water.
1498 */
1499 case SO_SNDLOWAT:
1500 so->so_snd.sb_lowat =
1501 (optval > so->so_snd.sb_hiwat) ?
1502 so->so_snd.sb_hiwat : optval;
1503 break;
1504 case SO_RCVLOWAT:
1505 so->so_rcv.sb_lowat =
1506 (optval > so->so_rcv.sb_hiwat) ?
1507 so->so_rcv.sb_hiwat : optval;
1508 break;
1509 }
1510 break;
1511 }
1512
1513 case SO_SNDTIMEO:
1514 case SO_RCVTIMEO:
1515 {
1516 struct timeval *tv;
1517 int val;
1518
1519 if (m == NULL || m->m_len < sizeof(*tv)) {
1520 error = EINVAL;
1521 goto bad;
1522 }
1523 tv = mtod(m, struct timeval *);
1524 if (tv->tv_sec > (INT_MAX - tv->tv_usec / tick) / hz) {
1525 error = EDOM;
1526 goto bad;
1527 }
1528 val = tv->tv_sec * hz + tv->tv_usec / tick;
1529 if (val == 0 && tv->tv_usec != 0)
1530 val = 1;
1531
1532 switch (optname) {
1533
1534 case SO_SNDTIMEO:
1535 so->so_snd.sb_timeo = val;
1536 break;
1537 case SO_RCVTIMEO:
1538 so->so_rcv.sb_timeo = val;
1539 break;
1540 }
1541 break;
1542 }
1543
1544 default:
1545 error = ENOPROTOOPT;
1546 break;
1547 }
1548 if (error == 0 && so->so_proto && so->so_proto->pr_ctloutput) {
1549 (void) ((*so->so_proto->pr_ctloutput)
1550 (PRCO_SETOPT, so, level, optname, &m0));
1551 m = NULL; /* freed by protocol */
1552 }
1553 }
1554 bad:
1555 if (m)
1556 (void) m_free(m);
1557 return (error);
1558 }
1559
1560 int
1561 sogetopt(struct socket *so, int level, int optname, struct mbuf **mp)
1562 {
1563 struct mbuf *m;
1564
1565 if (level != SOL_SOCKET) {
1566 if (so->so_proto && so->so_proto->pr_ctloutput) {
1567 return ((*so->so_proto->pr_ctloutput)
1568 (PRCO_GETOPT, so, level, optname, mp));
1569 } else
1570 return (ENOPROTOOPT);
1571 } else {
1572 m = m_get(M_WAIT, MT_SOOPTS);
1573 m->m_len = sizeof(int);
1574
1575 switch (optname) {
1576
1577 case SO_LINGER:
1578 m->m_len = sizeof(struct linger);
1579 mtod(m, struct linger *)->l_onoff =
1580 (so->so_options & SO_LINGER) ? 1 : 0;
1581 mtod(m, struct linger *)->l_linger = so->so_linger;
1582 break;
1583
1584 case SO_USELOOPBACK:
1585 case SO_DONTROUTE:
1586 case SO_DEBUG:
1587 case SO_KEEPALIVE:
1588 case SO_REUSEADDR:
1589 case SO_REUSEPORT:
1590 case SO_BROADCAST:
1591 case SO_OOBINLINE:
1592 case SO_TIMESTAMP:
1593 *mtod(m, int *) = (so->so_options & optname) ? 1 : 0;
1594 break;
1595
1596 case SO_TYPE:
1597 *mtod(m, int *) = so->so_type;
1598 break;
1599
1600 case SO_ERROR:
1601 *mtod(m, int *) = so->so_error;
1602 so->so_error = 0;
1603 break;
1604
1605 case SO_SNDBUF:
1606 *mtod(m, int *) = so->so_snd.sb_hiwat;
1607 break;
1608
1609 case SO_RCVBUF:
1610 *mtod(m, int *) = so->so_rcv.sb_hiwat;
1611 break;
1612
1613 case SO_SNDLOWAT:
1614 *mtod(m, int *) = so->so_snd.sb_lowat;
1615 break;
1616
1617 case SO_RCVLOWAT:
1618 *mtod(m, int *) = so->so_rcv.sb_lowat;
1619 break;
1620
1621 case SO_SNDTIMEO:
1622 case SO_RCVTIMEO:
1623 {
1624 int val = (optname == SO_SNDTIMEO ?
1625 so->so_snd.sb_timeo : so->so_rcv.sb_timeo);
1626
1627 m->m_len = sizeof(struct timeval);
1628 mtod(m, struct timeval *)->tv_sec = val / hz;
1629 mtod(m, struct timeval *)->tv_usec =
1630 (val % hz) * tick;
1631 break;
1632 }
1633
1634 case SO_OVERFLOWED:
1635 *mtod(m, int *) = so->so_rcv.sb_overflowed;
1636 break;
1637
1638 default:
1639 (void)m_free(m);
1640 return (ENOPROTOOPT);
1641 }
1642 *mp = m;
1643 return (0);
1644 }
1645 }
1646
1647 void
1648 sohasoutofband(struct socket *so)
1649 {
1650 fownsignal(so->so_pgid, SIGURG, POLL_PRI, POLLPRI|POLLRDBAND, so);
1651 selwakeup(&so->so_rcv.sb_sel);
1652 }
1653
1654 static void
1655 filt_sordetach(struct knote *kn)
1656 {
1657 struct socket *so;
1658
1659 so = (struct socket *)kn->kn_fp->f_data;
1660 SLIST_REMOVE(&so->so_rcv.sb_sel.sel_klist, kn, knote, kn_selnext);
1661 if (SLIST_EMPTY(&so->so_rcv.sb_sel.sel_klist))
1662 so->so_rcv.sb_flags &= ~SB_KNOTE;
1663 }
1664
1665 /*ARGSUSED*/
1666 static int
1667 filt_soread(struct knote *kn, long hint)
1668 {
1669 struct socket *so;
1670
1671 so = (struct socket *)kn->kn_fp->f_data;
1672 kn->kn_data = so->so_rcv.sb_cc;
1673 if (so->so_state & SS_CANTRCVMORE) {
1674 kn->kn_flags |= EV_EOF;
1675 kn->kn_fflags = so->so_error;
1676 return (1);
1677 }
1678 if (so->so_error) /* temporary udp error */
1679 return (1);
1680 if (kn->kn_sfflags & NOTE_LOWAT)
1681 return (kn->kn_data >= kn->kn_sdata);
1682 return (kn->kn_data >= so->so_rcv.sb_lowat);
1683 }
1684
1685 static void
1686 filt_sowdetach(struct knote *kn)
1687 {
1688 struct socket *so;
1689
1690 so = (struct socket *)kn->kn_fp->f_data;
1691 SLIST_REMOVE(&so->so_snd.sb_sel.sel_klist, kn, knote, kn_selnext);
1692 if (SLIST_EMPTY(&so->so_snd.sb_sel.sel_klist))
1693 so->so_snd.sb_flags &= ~SB_KNOTE;
1694 }
1695
1696 /*ARGSUSED*/
1697 static int
1698 filt_sowrite(struct knote *kn, long hint)
1699 {
1700 struct socket *so;
1701
1702 so = (struct socket *)kn->kn_fp->f_data;
1703 kn->kn_data = sbspace(&so->so_snd);
1704 if (so->so_state & SS_CANTSENDMORE) {
1705 kn->kn_flags |= EV_EOF;
1706 kn->kn_fflags = so->so_error;
1707 return (1);
1708 }
1709 if (so->so_error) /* temporary udp error */
1710 return (1);
1711 if (((so->so_state & SS_ISCONNECTED) == 0) &&
1712 (so->so_proto->pr_flags & PR_CONNREQUIRED))
1713 return (0);
1714 if (kn->kn_sfflags & NOTE_LOWAT)
1715 return (kn->kn_data >= kn->kn_sdata);
1716 return (kn->kn_data >= so->so_snd.sb_lowat);
1717 }
1718
1719 /*ARGSUSED*/
1720 static int
1721 filt_solisten(struct knote *kn, long hint)
1722 {
1723 struct socket *so;
1724
1725 so = (struct socket *)kn->kn_fp->f_data;
1726
1727 /*
1728 * Set kn_data to number of incoming connections, not
1729 * counting partial (incomplete) connections.
1730 */
1731 kn->kn_data = so->so_qlen;
1732 return (kn->kn_data > 0);
1733 }
1734
1735 static const struct filterops solisten_filtops =
1736 { 1, NULL, filt_sordetach, filt_solisten };
1737 static const struct filterops soread_filtops =
1738 { 1, NULL, filt_sordetach, filt_soread };
1739 static const struct filterops sowrite_filtops =
1740 { 1, NULL, filt_sowdetach, filt_sowrite };
1741
1742 int
1743 soo_kqfilter(struct file *fp, struct knote *kn)
1744 {
1745 struct socket *so;
1746 struct sockbuf *sb;
1747
1748 so = (struct socket *)kn->kn_fp->f_data;
1749 switch (kn->kn_filter) {
1750 case EVFILT_READ:
1751 if (so->so_options & SO_ACCEPTCONN)
1752 kn->kn_fop = &solisten_filtops;
1753 else
1754 kn->kn_fop = &soread_filtops;
1755 sb = &so->so_rcv;
1756 break;
1757 case EVFILT_WRITE:
1758 kn->kn_fop = &sowrite_filtops;
1759 sb = &so->so_snd;
1760 break;
1761 default:
1762 return (1);
1763 }
1764 SLIST_INSERT_HEAD(&sb->sb_sel.sel_klist, kn, kn_selnext);
1765 sb->sb_flags |= SB_KNOTE;
1766 return (0);
1767 }
1768
1769 #include <sys/sysctl.h>
1770
1771 static int sysctl_kern_somaxkva(SYSCTLFN_PROTO);
1772
1773 /*
1774 * sysctl helper routine for kern.somaxkva. ensures that the given
1775 * value is not too small.
1776 * (XXX should we maybe make sure it's not too large as well?)
1777 */
1778 static int
1779 sysctl_kern_somaxkva(SYSCTLFN_ARGS)
1780 {
1781 int error, new_somaxkva;
1782 struct sysctlnode node;
1783
1784 new_somaxkva = somaxkva;
1785 node = *rnode;
1786 node.sysctl_data = &new_somaxkva;
1787 error = sysctl_lookup(SYSCTLFN_CALL(&node));
1788 if (error || newp == NULL)
1789 return (error);
1790
1791 if (new_somaxkva < (16 * 1024 * 1024)) /* sanity */
1792 return (EINVAL);
1793
1794 mutex_enter(&so_pendfree_lock);
1795 somaxkva = new_somaxkva;
1796 cv_broadcast(&socurkva_cv);
1797 mutex_exit(&so_pendfree_lock);
1798
1799 return (error);
1800 }
1801
1802 SYSCTL_SETUP(sysctl_kern_somaxkva_setup, "sysctl kern.somaxkva setup")
1803 {
1804
1805 sysctl_createv(clog, 0, NULL, NULL,
1806 CTLFLAG_PERMANENT,
1807 CTLTYPE_NODE, "kern", NULL,
1808 NULL, 0, NULL, 0,
1809 CTL_KERN, CTL_EOL);
1810
1811 sysctl_createv(clog, 0, NULL, NULL,
1812 CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
1813 CTLTYPE_INT, "somaxkva",
1814 SYSCTL_DESCR("Maximum amount of kernel memory to be "
1815 "used for socket buffers"),
1816 sysctl_kern_somaxkva, 0, NULL, 0,
1817 CTL_KERN, KERN_SOMAXKVA, CTL_EOL);
1818 }
1819