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