uipc_socket.c revision 1.83.2.3 1 /* $NetBSD: uipc_socket.c,v 1.83.2.3 2004/08/25 06:58:58 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.3 2004/08/25 06:58:58 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 if (p)
1060 p->p_stats->p_ru.ru_msgrcv++;
1061 KASSERT(m == so->so_rcv.sb_mb);
1062 SBLASTRECORDCHK(&so->so_rcv, "soreceive 1");
1063 SBLASTMBUFCHK(&so->so_rcv, "soreceive 1");
1064 nextrecord = m->m_nextpkt;
1065 if (pr->pr_flags & PR_ADDR) {
1066 #ifdef DIAGNOSTIC
1067 if (m->m_type != MT_SONAME)
1068 panic("receive 1a");
1069 #endif
1070 orig_resid = 0;
1071 if (flags & MSG_PEEK) {
1072 if (paddr)
1073 *paddr = m_copy(m, 0, m->m_len);
1074 m = m->m_next;
1075 } else {
1076 sbfree(&so->so_rcv, m);
1077 mbuf_removed = 1;
1078 if (paddr) {
1079 *paddr = m;
1080 so->so_rcv.sb_mb = m->m_next;
1081 m->m_next = 0;
1082 m = so->so_rcv.sb_mb;
1083 } else {
1084 MFREE(m, so->so_rcv.sb_mb);
1085 m = so->so_rcv.sb_mb;
1086 }
1087 }
1088 }
1089 while (m && m->m_type == MT_CONTROL && error == 0) {
1090 if (flags & MSG_PEEK) {
1091 if (controlp)
1092 *controlp = m_copy(m, 0, m->m_len);
1093 m = m->m_next;
1094 } else {
1095 sbfree(&so->so_rcv, m);
1096 mbuf_removed = 1;
1097 if (controlp) {
1098 struct domain *dom = pr->pr_domain;
1099 if (dom->dom_externalize && p &&
1100 mtod(m, struct cmsghdr *)->cmsg_type ==
1101 SCM_RIGHTS)
1102 error = (*dom->dom_externalize)(m, l);
1103 *controlp = m;
1104 so->so_rcv.sb_mb = m->m_next;
1105 m->m_next = 0;
1106 m = so->so_rcv.sb_mb;
1107 } else {
1108 MFREE(m, so->so_rcv.sb_mb);
1109 m = so->so_rcv.sb_mb;
1110 }
1111 }
1112 if (controlp) {
1113 orig_resid = 0;
1114 controlp = &(*controlp)->m_next;
1115 }
1116 }
1117
1118 /*
1119 * If m is non-NULL, we have some data to read. From now on,
1120 * make sure to keep sb_lastrecord consistent when working on
1121 * the last packet on the chain (nextrecord == NULL) and we
1122 * change m->m_nextpkt.
1123 */
1124 if (m) {
1125 if ((flags & MSG_PEEK) == 0) {
1126 m->m_nextpkt = nextrecord;
1127 /*
1128 * If nextrecord == NULL (this is a single chain),
1129 * then sb_lastrecord may not be valid here if m
1130 * was changed earlier.
1131 */
1132 if (nextrecord == NULL) {
1133 KASSERT(so->so_rcv.sb_mb == m);
1134 so->so_rcv.sb_lastrecord = m;
1135 }
1136 }
1137 type = m->m_type;
1138 if (type == MT_OOBDATA)
1139 flags |= MSG_OOB;
1140 } else {
1141 if ((flags & MSG_PEEK) == 0) {
1142 KASSERT(so->so_rcv.sb_mb == m);
1143 so->so_rcv.sb_mb = nextrecord;
1144 SB_EMPTY_FIXUP(&so->so_rcv);
1145 }
1146 }
1147 SBLASTRECORDCHK(&so->so_rcv, "soreceive 2");
1148 SBLASTMBUFCHK(&so->so_rcv, "soreceive 2");
1149
1150 moff = 0;
1151 offset = 0;
1152 while (m && uio->uio_resid > 0 && error == 0) {
1153 if (m->m_type == MT_OOBDATA) {
1154 if (type != MT_OOBDATA)
1155 break;
1156 } else if (type == MT_OOBDATA)
1157 break;
1158 #ifdef DIAGNOSTIC
1159 else if (m->m_type != MT_DATA && m->m_type != MT_HEADER)
1160 panic("receive 3");
1161 #endif
1162 so->so_state &= ~SS_RCVATMARK;
1163 len = uio->uio_resid;
1164 if (so->so_oobmark && len > so->so_oobmark - offset)
1165 len = so->so_oobmark - offset;
1166 if (len > m->m_len - moff)
1167 len = m->m_len - moff;
1168 /*
1169 * If mp is set, just pass back the mbufs.
1170 * Otherwise copy them out via the uio, then free.
1171 * Sockbuf must be consistent here (points to current mbuf,
1172 * it points to next record) when we drop priority;
1173 * we must note any additions to the sockbuf when we
1174 * block interrupts again.
1175 */
1176 if (mp == 0) {
1177 SBLASTRECORDCHK(&so->so_rcv, "soreceive uiomove");
1178 SBLASTMBUFCHK(&so->so_rcv, "soreceive uiomove");
1179 splx(s);
1180 error = uiomove(mtod(m, caddr_t) + moff, (int)len, uio);
1181 s = splsoftnet();
1182 if (error) {
1183 /*
1184 * If any part of the record has been removed
1185 * (such as the MT_SONAME mbuf, which will
1186 * happen when PR_ADDR, and thus also
1187 * PR_ATOMIC, is set), then drop the entire
1188 * record to maintain the atomicity of the
1189 * receive operation.
1190 *
1191 * This avoids a later panic("receive 1a")
1192 * when compiled with DIAGNOSTIC.
1193 */
1194 if (m && mbuf_removed
1195 && (pr->pr_flags & PR_ATOMIC))
1196 (void) sbdroprecord(&so->so_rcv);
1197
1198 goto release;
1199 }
1200 } else
1201 uio->uio_resid -= len;
1202 if (len == m->m_len - moff) {
1203 if (m->m_flags & M_EOR)
1204 flags |= MSG_EOR;
1205 if (flags & MSG_PEEK) {
1206 m = m->m_next;
1207 moff = 0;
1208 } else {
1209 nextrecord = m->m_nextpkt;
1210 sbfree(&so->so_rcv, m);
1211 if (mp) {
1212 *mp = m;
1213 mp = &m->m_next;
1214 so->so_rcv.sb_mb = m = m->m_next;
1215 *mp = (struct mbuf *)0;
1216 } else {
1217 MFREE(m, so->so_rcv.sb_mb);
1218 m = so->so_rcv.sb_mb;
1219 }
1220 /*
1221 * If m != NULL, we also know that
1222 * so->so_rcv.sb_mb != NULL.
1223 */
1224 KASSERT(so->so_rcv.sb_mb == m);
1225 if (m) {
1226 m->m_nextpkt = nextrecord;
1227 if (nextrecord == NULL)
1228 so->so_rcv.sb_lastrecord = m;
1229 } else {
1230 so->so_rcv.sb_mb = nextrecord;
1231 SB_EMPTY_FIXUP(&so->so_rcv);
1232 }
1233 SBLASTRECORDCHK(&so->so_rcv, "soreceive 3");
1234 SBLASTMBUFCHK(&so->so_rcv, "soreceive 3");
1235 }
1236 } else {
1237 if (flags & MSG_PEEK)
1238 moff += len;
1239 else {
1240 if (mp)
1241 *mp = m_copym(m, 0, len, M_WAIT);
1242 m->m_data += len;
1243 m->m_len -= len;
1244 so->so_rcv.sb_cc -= len;
1245 }
1246 }
1247 if (so->so_oobmark) {
1248 if ((flags & MSG_PEEK) == 0) {
1249 so->so_oobmark -= len;
1250 if (so->so_oobmark == 0) {
1251 so->so_state |= SS_RCVATMARK;
1252 break;
1253 }
1254 } else {
1255 offset += len;
1256 if (offset == so->so_oobmark)
1257 break;
1258 }
1259 }
1260 if (flags & MSG_EOR)
1261 break;
1262 /*
1263 * If the MSG_WAITALL flag is set (for non-atomic socket),
1264 * we must not quit until "uio->uio_resid == 0" or an error
1265 * termination. If a signal/timeout occurs, return
1266 * with a short count but without error.
1267 * Keep sockbuf locked against other readers.
1268 */
1269 while (flags & MSG_WAITALL && m == 0 && uio->uio_resid > 0 &&
1270 !sosendallatonce(so) && !nextrecord) {
1271 if (so->so_error || so->so_state & SS_CANTRCVMORE)
1272 break;
1273 /*
1274 * If we are peeking and the socket receive buffer is
1275 * full, stop since we can't get more data to peek at.
1276 */
1277 if ((flags & MSG_PEEK) && sbspace(&so->so_rcv) <= 0)
1278 break;
1279 /*
1280 * If we've drained the socket buffer, tell the
1281 * protocol in case it needs to do something to
1282 * get it filled again.
1283 */
1284 if ((pr->pr_flags & PR_WANTRCVD) && so->so_pcb)
1285 (*pr->pr_usrreq)(so, PRU_RCVD,
1286 (struct mbuf *)0,
1287 (struct mbuf *)(long)flags,
1288 (struct mbuf *)0, l);
1289 SBLASTRECORDCHK(&so->so_rcv, "soreceive sbwait 2");
1290 SBLASTMBUFCHK(&so->so_rcv, "soreceive sbwait 2");
1291 error = sbwait(&so->so_rcv);
1292 if (error) {
1293 sbunlock(&so->so_rcv);
1294 splx(s);
1295 return (0);
1296 }
1297 if ((m = so->so_rcv.sb_mb) != NULL)
1298 nextrecord = m->m_nextpkt;
1299 }
1300 }
1301
1302 if (m && pr->pr_flags & PR_ATOMIC) {
1303 flags |= MSG_TRUNC;
1304 if ((flags & MSG_PEEK) == 0)
1305 (void) sbdroprecord(&so->so_rcv);
1306 }
1307 if ((flags & MSG_PEEK) == 0) {
1308 if (m == 0) {
1309 /*
1310 * First part is an inline SB_EMPTY_FIXUP(). Second
1311 * part makes sure sb_lastrecord is up-to-date if
1312 * there is still data in the socket buffer.
1313 */
1314 so->so_rcv.sb_mb = nextrecord;
1315 if (so->so_rcv.sb_mb == NULL) {
1316 so->so_rcv.sb_mbtail = NULL;
1317 so->so_rcv.sb_lastrecord = NULL;
1318 } else if (nextrecord->m_nextpkt == NULL)
1319 so->so_rcv.sb_lastrecord = nextrecord;
1320 }
1321 SBLASTRECORDCHK(&so->so_rcv, "soreceive 4");
1322 SBLASTMBUFCHK(&so->so_rcv, "soreceive 4");
1323 if (pr->pr_flags & PR_WANTRCVD && so->so_pcb)
1324 (*pr->pr_usrreq)(so, PRU_RCVD, (struct mbuf *)0,
1325 (struct mbuf *)(long)flags, (struct mbuf *)0, l);
1326 }
1327 if (orig_resid == uio->uio_resid && orig_resid &&
1328 (flags & MSG_EOR) == 0 && (so->so_state & SS_CANTRCVMORE) == 0) {
1329 sbunlock(&so->so_rcv);
1330 splx(s);
1331 goto restart;
1332 }
1333
1334 if (flagsp)
1335 *flagsp |= flags;
1336 release:
1337 sbunlock(&so->so_rcv);
1338 splx(s);
1339 return (error);
1340 }
1341
1342 int
1343 soshutdown(struct socket *so, int how)
1344 {
1345 const struct protosw *pr;
1346
1347 pr = so->so_proto;
1348 if (!(how == SHUT_RD || how == SHUT_WR || how == SHUT_RDWR))
1349 return (EINVAL);
1350
1351 if (how == SHUT_RD || how == SHUT_RDWR)
1352 sorflush(so);
1353 if (how == SHUT_WR || how == SHUT_RDWR)
1354 return (*pr->pr_usrreq)(so, PRU_SHUTDOWN, (struct mbuf *)0,
1355 (struct mbuf *)0, (struct mbuf *)0, (struct lwp *)0);
1356 return (0);
1357 }
1358
1359 void
1360 sorflush(struct socket *so)
1361 {
1362 struct sockbuf *sb, asb;
1363 const struct protosw *pr;
1364 int s;
1365
1366 sb = &so->so_rcv;
1367 pr = so->so_proto;
1368 sb->sb_flags |= SB_NOINTR;
1369 (void) sblock(sb, M_WAITOK);
1370 s = splnet();
1371 socantrcvmore(so);
1372 sbunlock(sb);
1373 asb = *sb;
1374 /*
1375 * Clear most of the sockbuf structure, but leave some of the
1376 * fields valid.
1377 */
1378 memset(&sb->sb_startzero, 0,
1379 sizeof(*sb) - offsetof(struct sockbuf, sb_startzero));
1380 splx(s);
1381 if (pr->pr_flags & PR_RIGHTS && pr->pr_domain->dom_dispose)
1382 (*pr->pr_domain->dom_dispose)(asb.sb_mb);
1383 sbrelease(&asb, so);
1384 }
1385
1386 int
1387 sosetopt(struct socket *so, int level, int optname, struct mbuf *m0)
1388 {
1389 int error;
1390 struct mbuf *m;
1391
1392 error = 0;
1393 m = m0;
1394 if (level != SOL_SOCKET) {
1395 if (so->so_proto && so->so_proto->pr_ctloutput)
1396 return ((*so->so_proto->pr_ctloutput)
1397 (PRCO_SETOPT, so, level, optname, &m0));
1398 error = ENOPROTOOPT;
1399 } else {
1400 switch (optname) {
1401
1402 case SO_LINGER:
1403 if (m == NULL || m->m_len != sizeof(struct linger)) {
1404 error = EINVAL;
1405 goto bad;
1406 }
1407 so->so_linger = mtod(m, struct linger *)->l_linger;
1408 /* fall thru... */
1409
1410 case SO_DEBUG:
1411 case SO_KEEPALIVE:
1412 case SO_DONTROUTE:
1413 case SO_USELOOPBACK:
1414 case SO_BROADCAST:
1415 case SO_REUSEADDR:
1416 case SO_REUSEPORT:
1417 case SO_OOBINLINE:
1418 case SO_TIMESTAMP:
1419 if (m == NULL || m->m_len < sizeof(int)) {
1420 error = EINVAL;
1421 goto bad;
1422 }
1423 if (*mtod(m, int *))
1424 so->so_options |= optname;
1425 else
1426 so->so_options &= ~optname;
1427 break;
1428
1429 case SO_SNDBUF:
1430 case SO_RCVBUF:
1431 case SO_SNDLOWAT:
1432 case SO_RCVLOWAT:
1433 {
1434 int optval;
1435
1436 if (m == NULL || m->m_len < sizeof(int)) {
1437 error = EINVAL;
1438 goto bad;
1439 }
1440
1441 /*
1442 * Values < 1 make no sense for any of these
1443 * options, so disallow them.
1444 */
1445 optval = *mtod(m, int *);
1446 if (optval < 1) {
1447 error = EINVAL;
1448 goto bad;
1449 }
1450
1451 switch (optname) {
1452
1453 case SO_SNDBUF:
1454 case SO_RCVBUF:
1455 if (sbreserve(optname == SO_SNDBUF ?
1456 &so->so_snd : &so->so_rcv,
1457 (u_long) optval, so) == 0) {
1458 error = ENOBUFS;
1459 goto bad;
1460 }
1461 break;
1462
1463 /*
1464 * Make sure the low-water is never greater than
1465 * the high-water.
1466 */
1467 case SO_SNDLOWAT:
1468 so->so_snd.sb_lowat =
1469 (optval > so->so_snd.sb_hiwat) ?
1470 so->so_snd.sb_hiwat : optval;
1471 break;
1472 case SO_RCVLOWAT:
1473 so->so_rcv.sb_lowat =
1474 (optval > so->so_rcv.sb_hiwat) ?
1475 so->so_rcv.sb_hiwat : optval;
1476 break;
1477 }
1478 break;
1479 }
1480
1481 case SO_SNDTIMEO:
1482 case SO_RCVTIMEO:
1483 {
1484 struct timeval *tv;
1485 int val;
1486
1487 if (m == NULL || m->m_len < sizeof(*tv)) {
1488 error = EINVAL;
1489 goto bad;
1490 }
1491 tv = mtod(m, struct timeval *);
1492 if (tv->tv_sec > (INT_MAX - tv->tv_usec / tick) / hz) {
1493 error = EDOM;
1494 goto bad;
1495 }
1496 val = tv->tv_sec * hz + tv->tv_usec / tick;
1497 if (val == 0 && tv->tv_usec != 0)
1498 val = 1;
1499
1500 switch (optname) {
1501
1502 case SO_SNDTIMEO:
1503 so->so_snd.sb_timeo = val;
1504 break;
1505 case SO_RCVTIMEO:
1506 so->so_rcv.sb_timeo = val;
1507 break;
1508 }
1509 break;
1510 }
1511
1512 default:
1513 error = ENOPROTOOPT;
1514 break;
1515 }
1516 if (error == 0 && so->so_proto && so->so_proto->pr_ctloutput) {
1517 (void) ((*so->so_proto->pr_ctloutput)
1518 (PRCO_SETOPT, so, level, optname, &m0));
1519 m = NULL; /* freed by protocol */
1520 }
1521 }
1522 bad:
1523 if (m)
1524 (void) m_free(m);
1525 return (error);
1526 }
1527
1528 int
1529 sogetopt(struct socket *so, int level, int optname, struct mbuf **mp)
1530 {
1531 struct mbuf *m;
1532
1533 if (level != SOL_SOCKET) {
1534 if (so->so_proto && so->so_proto->pr_ctloutput) {
1535 return ((*so->so_proto->pr_ctloutput)
1536 (PRCO_GETOPT, so, level, optname, mp));
1537 } else
1538 return (ENOPROTOOPT);
1539 } else {
1540 m = m_get(M_WAIT, MT_SOOPTS);
1541 m->m_len = sizeof(int);
1542
1543 switch (optname) {
1544
1545 case SO_LINGER:
1546 m->m_len = sizeof(struct linger);
1547 mtod(m, struct linger *)->l_onoff =
1548 so->so_options & SO_LINGER;
1549 mtod(m, struct linger *)->l_linger = so->so_linger;
1550 break;
1551
1552 case SO_USELOOPBACK:
1553 case SO_DONTROUTE:
1554 case SO_DEBUG:
1555 case SO_KEEPALIVE:
1556 case SO_REUSEADDR:
1557 case SO_REUSEPORT:
1558 case SO_BROADCAST:
1559 case SO_OOBINLINE:
1560 case SO_TIMESTAMP:
1561 *mtod(m, int *) = so->so_options & optname;
1562 break;
1563
1564 case SO_TYPE:
1565 *mtod(m, int *) = so->so_type;
1566 break;
1567
1568 case SO_ERROR:
1569 *mtod(m, int *) = so->so_error;
1570 so->so_error = 0;
1571 break;
1572
1573 case SO_SNDBUF:
1574 *mtod(m, int *) = so->so_snd.sb_hiwat;
1575 break;
1576
1577 case SO_RCVBUF:
1578 *mtod(m, int *) = so->so_rcv.sb_hiwat;
1579 break;
1580
1581 case SO_SNDLOWAT:
1582 *mtod(m, int *) = so->so_snd.sb_lowat;
1583 break;
1584
1585 case SO_RCVLOWAT:
1586 *mtod(m, int *) = so->so_rcv.sb_lowat;
1587 break;
1588
1589 case SO_SNDTIMEO:
1590 case SO_RCVTIMEO:
1591 {
1592 int val = (optname == SO_SNDTIMEO ?
1593 so->so_snd.sb_timeo : so->so_rcv.sb_timeo);
1594
1595 m->m_len = sizeof(struct timeval);
1596 mtod(m, struct timeval *)->tv_sec = val / hz;
1597 mtod(m, struct timeval *)->tv_usec =
1598 (val % hz) * tick;
1599 break;
1600 }
1601
1602 default:
1603 (void)m_free(m);
1604 return (ENOPROTOOPT);
1605 }
1606 *mp = m;
1607 return (0);
1608 }
1609 }
1610
1611 void
1612 sohasoutofband(struct socket *so)
1613 {
1614 fownsignal(so->so_pgid, SIGURG, POLL_PRI, POLLPRI|POLLRDBAND, so);
1615 selwakeup(&so->so_rcv.sb_sel);
1616 }
1617
1618 static void
1619 filt_sordetach(struct knote *kn)
1620 {
1621 struct socket *so;
1622
1623 so = (struct socket *)kn->kn_fp->f_data;
1624 SLIST_REMOVE(&so->so_rcv.sb_sel.sel_klist, kn, knote, kn_selnext);
1625 if (SLIST_EMPTY(&so->so_rcv.sb_sel.sel_klist))
1626 so->so_rcv.sb_flags &= ~SB_KNOTE;
1627 }
1628
1629 /*ARGSUSED*/
1630 static int
1631 filt_soread(struct knote *kn, long hint)
1632 {
1633 struct socket *so;
1634
1635 so = (struct socket *)kn->kn_fp->f_data;
1636 kn->kn_data = so->so_rcv.sb_cc;
1637 if (so->so_state & SS_CANTRCVMORE) {
1638 kn->kn_flags |= EV_EOF;
1639 kn->kn_fflags = so->so_error;
1640 return (1);
1641 }
1642 if (so->so_error) /* temporary udp error */
1643 return (1);
1644 if (kn->kn_sfflags & NOTE_LOWAT)
1645 return (kn->kn_data >= kn->kn_sdata);
1646 return (kn->kn_data >= so->so_rcv.sb_lowat);
1647 }
1648
1649 static void
1650 filt_sowdetach(struct knote *kn)
1651 {
1652 struct socket *so;
1653
1654 so = (struct socket *)kn->kn_fp->f_data;
1655 SLIST_REMOVE(&so->so_snd.sb_sel.sel_klist, kn, knote, kn_selnext);
1656 if (SLIST_EMPTY(&so->so_snd.sb_sel.sel_klist))
1657 so->so_snd.sb_flags &= ~SB_KNOTE;
1658 }
1659
1660 /*ARGSUSED*/
1661 static int
1662 filt_sowrite(struct knote *kn, long hint)
1663 {
1664 struct socket *so;
1665
1666 so = (struct socket *)kn->kn_fp->f_data;
1667 kn->kn_data = sbspace(&so->so_snd);
1668 if (so->so_state & SS_CANTSENDMORE) {
1669 kn->kn_flags |= EV_EOF;
1670 kn->kn_fflags = so->so_error;
1671 return (1);
1672 }
1673 if (so->so_error) /* temporary udp error */
1674 return (1);
1675 if (((so->so_state & SS_ISCONNECTED) == 0) &&
1676 (so->so_proto->pr_flags & PR_CONNREQUIRED))
1677 return (0);
1678 if (kn->kn_sfflags & NOTE_LOWAT)
1679 return (kn->kn_data >= kn->kn_sdata);
1680 return (kn->kn_data >= so->so_snd.sb_lowat);
1681 }
1682
1683 /*ARGSUSED*/
1684 static int
1685 filt_solisten(struct knote *kn, long hint)
1686 {
1687 struct socket *so;
1688
1689 so = (struct socket *)kn->kn_fp->f_data;
1690
1691 /*
1692 * Set kn_data to number of incoming connections, not
1693 * counting partial (incomplete) connections.
1694 */
1695 kn->kn_data = so->so_qlen;
1696 return (kn->kn_data > 0);
1697 }
1698
1699 static const struct filterops solisten_filtops =
1700 { 1, NULL, filt_sordetach, filt_solisten };
1701 static const struct filterops soread_filtops =
1702 { 1, NULL, filt_sordetach, filt_soread };
1703 static const struct filterops sowrite_filtops =
1704 { 1, NULL, filt_sowdetach, filt_sowrite };
1705
1706 int
1707 soo_kqfilter(struct file *fp, struct knote *kn)
1708 {
1709 struct socket *so;
1710 struct sockbuf *sb;
1711
1712 so = (struct socket *)kn->kn_fp->f_data;
1713 switch (kn->kn_filter) {
1714 case EVFILT_READ:
1715 if (so->so_options & SO_ACCEPTCONN)
1716 kn->kn_fop = &solisten_filtops;
1717 else
1718 kn->kn_fop = &soread_filtops;
1719 sb = &so->so_rcv;
1720 break;
1721 case EVFILT_WRITE:
1722 kn->kn_fop = &sowrite_filtops;
1723 sb = &so->so_snd;
1724 break;
1725 default:
1726 return (1);
1727 }
1728 SLIST_INSERT_HEAD(&sb->sb_sel.sel_klist, kn, kn_selnext);
1729 sb->sb_flags |= SB_KNOTE;
1730 return (0);
1731 }
1732
1733 #include <sys/sysctl.h>
1734
1735 static int sysctl_kern_somaxkva(SYSCTLFN_PROTO);
1736
1737 /*
1738 * sysctl helper routine for kern.somaxkva. ensures that the given
1739 * value is not too small.
1740 * (XXX should we maybe make sure it's not too large as well?)
1741 */
1742 static int
1743 sysctl_kern_somaxkva(SYSCTLFN_ARGS)
1744 {
1745 int error, new_somaxkva;
1746 struct sysctlnode node;
1747 int s;
1748
1749 new_somaxkva = somaxkva;
1750 node = *rnode;
1751 node.sysctl_data = &new_somaxkva;
1752 error = sysctl_lookup(SYSCTLFN_CALL(&node));
1753 if (error || newp == NULL)
1754 return (error);
1755
1756 if (new_somaxkva < (16 * 1024 * 1024)) /* sanity */
1757 return (EINVAL);
1758
1759 s = splvm();
1760 simple_lock(&so_pendfree_slock);
1761 somaxkva = new_somaxkva;
1762 wakeup(&socurkva);
1763 simple_unlock(&so_pendfree_slock);
1764 splx(s);
1765
1766 return (error);
1767 }
1768
1769 SYSCTL_SETUP(sysctl_kern_somaxkva_setup, "sysctl kern.somaxkva setup")
1770 {
1771
1772 sysctl_createv(clog, 0, NULL, NULL,
1773 CTLFLAG_PERMANENT,
1774 CTLTYPE_NODE, "kern", NULL,
1775 NULL, 0, NULL, 0,
1776 CTL_KERN, CTL_EOL);
1777
1778 sysctl_createv(clog, 0, NULL, NULL,
1779 CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
1780 CTLTYPE_INT, "somaxkva",
1781 SYSCTL_DESCR("Maximum amount of kernel memory to be "
1782 "used for socket buffers"),
1783 sysctl_kern_somaxkva, 0, NULL, 0,
1784 CTL_KERN, KERN_SOMAXKVA, CTL_EOL);
1785 }
1786