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