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