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