uipc_socket.c revision 1.281.2.3 1 /* $NetBSD: uipc_socket.c,v 1.281.2.3 2020/09/22 18:39:01 martin Exp $ */
2
3 /*
4 * Copyright (c) 2002, 2007, 2008, 2009 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, and by Andrew Doran.
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 *
19 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
21 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
23 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29 * POSSIBILITY OF SUCH DAMAGE.
30 */
31
32 /*
33 * Copyright (c) 2004 The FreeBSD Foundation
34 * Copyright (c) 2004 Robert Watson
35 * Copyright (c) 1982, 1986, 1988, 1990, 1993
36 * The Regents of the University of California. All rights reserved.
37 *
38 * Redistribution and use in source and binary forms, with or without
39 * modification, are permitted provided that the following conditions
40 * are met:
41 * 1. Redistributions of source code must retain the above copyright
42 * notice, this list of conditions and the following disclaimer.
43 * 2. Redistributions in binary form must reproduce the above copyright
44 * notice, this list of conditions and the following disclaimer in the
45 * documentation and/or other materials provided with the distribution.
46 * 3. Neither the name of the University nor the names of its contributors
47 * may be used to endorse or promote products derived from this software
48 * without specific prior written permission.
49 *
50 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
51 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
52 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
53 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
54 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
55 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
56 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
57 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
58 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
59 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
60 * SUCH DAMAGE.
61 *
62 * @(#)uipc_socket.c 8.6 (Berkeley) 5/2/95
63 */
64
65 /*
66 * Socket operation routines.
67 *
68 * These routines are called by the routines in sys_socket.c or from a
69 * system process, and implement the semantics of socket operations by
70 * switching out to the protocol specific routines.
71 */
72
73 #include <sys/cdefs.h>
74 __KERNEL_RCSID(0, "$NetBSD: uipc_socket.c,v 1.281.2.3 2020/09/22 18:39:01 martin Exp $");
75
76 #ifdef _KERNEL_OPT
77 #include "opt_compat_netbsd.h"
78 #include "opt_sock_counters.h"
79 #include "opt_sosend_loan.h"
80 #include "opt_mbuftrace.h"
81 #include "opt_somaxkva.h"
82 #include "opt_multiprocessor.h" /* XXX */
83 #include "opt_sctp.h"
84 #endif
85
86 #include <sys/param.h>
87 #include <sys/systm.h>
88 #include <sys/proc.h>
89 #include <sys/file.h>
90 #include <sys/filedesc.h>
91 #include <sys/kmem.h>
92 #include <sys/mbuf.h>
93 #include <sys/domain.h>
94 #include <sys/kernel.h>
95 #include <sys/protosw.h>
96 #include <sys/socket.h>
97 #include <sys/socketvar.h>
98 #include <sys/signalvar.h>
99 #include <sys/resourcevar.h>
100 #include <sys/uidinfo.h>
101 #include <sys/event.h>
102 #include <sys/poll.h>
103 #include <sys/kauth.h>
104 #include <sys/mutex.h>
105 #include <sys/condvar.h>
106 #include <sys/kthread.h>
107 #include <sys/compat_stub.h>
108
109 #include <compat/sys/time.h>
110 #include <compat/sys/socket.h>
111
112 #include <uvm/uvm_extern.h>
113 #include <uvm/uvm_loan.h>
114 #include <uvm/uvm_page.h>
115
116 #ifdef SCTP
117 #include <netinet/sctp_route.h>
118 #endif
119
120 MALLOC_DEFINE(M_SONAME, "soname", "socket name");
121
122 extern const struct fileops socketops;
123
124 static int sooptions;
125 extern int somaxconn; /* patchable (XXX sysctl) */
126 int somaxconn = SOMAXCONN;
127 kmutex_t *softnet_lock;
128
129 #ifdef SOSEND_COUNTERS
130 #include <sys/device.h>
131
132 static struct evcnt sosend_loan_big = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
133 NULL, "sosend", "loan big");
134 static struct evcnt sosend_copy_big = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
135 NULL, "sosend", "copy big");
136 static struct evcnt sosend_copy_small = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
137 NULL, "sosend", "copy small");
138 static struct evcnt sosend_kvalimit = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
139 NULL, "sosend", "kva limit");
140
141 #define SOSEND_COUNTER_INCR(ev) (ev)->ev_count++
142
143 EVCNT_ATTACH_STATIC(sosend_loan_big);
144 EVCNT_ATTACH_STATIC(sosend_copy_big);
145 EVCNT_ATTACH_STATIC(sosend_copy_small);
146 EVCNT_ATTACH_STATIC(sosend_kvalimit);
147 #else
148
149 #define SOSEND_COUNTER_INCR(ev) /* nothing */
150
151 #endif /* SOSEND_COUNTERS */
152
153 #if defined(SOSEND_NO_LOAN) || defined(MULTIPROCESSOR)
154 int sock_loan_thresh = -1;
155 #else
156 int sock_loan_thresh = 4096;
157 #endif
158
159 static kmutex_t so_pendfree_lock;
160 static struct mbuf *so_pendfree = NULL;
161
162 #ifndef SOMAXKVA
163 #define SOMAXKVA (16 * 1024 * 1024)
164 #endif
165 int somaxkva = SOMAXKVA;
166 static int socurkva;
167 static kcondvar_t socurkva_cv;
168
169 static kauth_listener_t socket_listener;
170
171 #define SOCK_LOAN_CHUNK 65536
172
173 static void sopendfree_thread(void *);
174 static kcondvar_t pendfree_thread_cv;
175 static lwp_t *sopendfree_lwp;
176
177 static void sysctl_kern_socket_setup(void);
178 static struct sysctllog *socket_sysctllog;
179
180 static vsize_t
181 sokvareserve(struct socket *so, vsize_t len)
182 {
183 int error;
184
185 mutex_enter(&so_pendfree_lock);
186 while (socurkva + len > somaxkva) {
187 SOSEND_COUNTER_INCR(&sosend_kvalimit);
188 error = cv_wait_sig(&socurkva_cv, &so_pendfree_lock);
189 if (error) {
190 len = 0;
191 break;
192 }
193 }
194 socurkva += len;
195 mutex_exit(&so_pendfree_lock);
196 return len;
197 }
198
199 static void
200 sokvaunreserve(vsize_t len)
201 {
202
203 mutex_enter(&so_pendfree_lock);
204 socurkva -= len;
205 cv_broadcast(&socurkva_cv);
206 mutex_exit(&so_pendfree_lock);
207 }
208
209 /*
210 * sokvaalloc: allocate kva for loan.
211 */
212 vaddr_t
213 sokvaalloc(vaddr_t sva, vsize_t len, struct socket *so)
214 {
215 vaddr_t lva;
216
217 if (sokvareserve(so, len) == 0)
218 return 0;
219
220 lva = uvm_km_alloc(kernel_map, len, atop(sva) & uvmexp.colormask,
221 UVM_KMF_COLORMATCH | UVM_KMF_VAONLY | UVM_KMF_WAITVA);
222 if (lva == 0) {
223 sokvaunreserve(len);
224 return 0;
225 }
226
227 return lva;
228 }
229
230 /*
231 * sokvafree: free kva for loan.
232 */
233 void
234 sokvafree(vaddr_t sva, vsize_t len)
235 {
236
237 uvm_km_free(kernel_map, sva, len, UVM_KMF_VAONLY);
238 sokvaunreserve(len);
239 }
240
241 static void
242 sodoloanfree(struct vm_page **pgs, void *buf, size_t size)
243 {
244 vaddr_t sva, eva;
245 vsize_t len;
246 int npgs;
247
248 KASSERT(pgs != NULL);
249
250 eva = round_page((vaddr_t) buf + size);
251 sva = trunc_page((vaddr_t) buf);
252 len = eva - sva;
253 npgs = len >> PAGE_SHIFT;
254
255 pmap_kremove(sva, len);
256 pmap_update(pmap_kernel());
257 uvm_unloan(pgs, npgs, UVM_LOAN_TOPAGE);
258 sokvafree(sva, len);
259 }
260
261 /*
262 * sopendfree_thread: free mbufs on "pendfree" list. Unlock and relock
263 * so_pendfree_lock when freeing mbufs.
264 */
265 static void
266 sopendfree_thread(void *v)
267 {
268 struct mbuf *m, *next;
269 size_t rv;
270
271 mutex_enter(&so_pendfree_lock);
272
273 for (;;) {
274 rv = 0;
275 while (so_pendfree != NULL) {
276 m = so_pendfree;
277 so_pendfree = NULL;
278 mutex_exit(&so_pendfree_lock);
279
280 for (; m != NULL; m = next) {
281 next = m->m_next;
282 KASSERT((~m->m_flags & (M_EXT|M_EXT_PAGES)) ==
283 0);
284 KASSERT(m->m_ext.ext_refcnt == 0);
285
286 rv += m->m_ext.ext_size;
287 sodoloanfree(m->m_ext.ext_pgs, m->m_ext.ext_buf,
288 m->m_ext.ext_size);
289 pool_cache_put(mb_cache, m);
290 }
291
292 mutex_enter(&so_pendfree_lock);
293 }
294 if (rv)
295 cv_broadcast(&socurkva_cv);
296 cv_wait(&pendfree_thread_cv, &so_pendfree_lock);
297 }
298 panic("sopendfree_thread");
299 /* NOTREACHED */
300 }
301
302 void
303 soloanfree(struct mbuf *m, void *buf, size_t size, void *arg)
304 {
305
306 KASSERT(m != NULL);
307
308 /*
309 * postpone freeing mbuf.
310 *
311 * we can't do it in interrupt context
312 * because we need to put kva back to kernel_map.
313 */
314
315 mutex_enter(&so_pendfree_lock);
316 m->m_next = so_pendfree;
317 so_pendfree = m;
318 cv_signal(&pendfree_thread_cv);
319 mutex_exit(&so_pendfree_lock);
320 }
321
322 static long
323 sosend_loan(struct socket *so, struct uio *uio, struct mbuf *m, long space)
324 {
325 struct iovec *iov = uio->uio_iov;
326 vaddr_t sva, eva;
327 vsize_t len;
328 vaddr_t lva;
329 int npgs, error;
330 vaddr_t va;
331 int i;
332
333 if (VMSPACE_IS_KERNEL_P(uio->uio_vmspace))
334 return 0;
335
336 if (iov->iov_len < (size_t) space)
337 space = iov->iov_len;
338 if (space > SOCK_LOAN_CHUNK)
339 space = SOCK_LOAN_CHUNK;
340
341 eva = round_page((vaddr_t) iov->iov_base + space);
342 sva = trunc_page((vaddr_t) iov->iov_base);
343 len = eva - sva;
344 npgs = len >> PAGE_SHIFT;
345
346 KASSERT(npgs <= M_EXT_MAXPAGES);
347
348 lva = sokvaalloc(sva, len, so);
349 if (lva == 0)
350 return 0;
351
352 error = uvm_loan(&uio->uio_vmspace->vm_map, sva, len,
353 m->m_ext.ext_pgs, UVM_LOAN_TOPAGE);
354 if (error) {
355 sokvafree(lva, len);
356 return 0;
357 }
358
359 for (i = 0, va = lva; i < npgs; i++, va += PAGE_SIZE)
360 pmap_kenter_pa(va, VM_PAGE_TO_PHYS(m->m_ext.ext_pgs[i]),
361 VM_PROT_READ, 0);
362 pmap_update(pmap_kernel());
363
364 lva += (vaddr_t) iov->iov_base & PAGE_MASK;
365
366 MEXTADD(m, (void *) lva, space, M_MBUF, soloanfree, so);
367 m->m_flags |= M_EXT_PAGES | M_EXT_ROMAP;
368
369 uio->uio_resid -= space;
370 /* uio_offset not updated, not set/used for write(2) */
371 uio->uio_iov->iov_base = (char *)uio->uio_iov->iov_base + space;
372 uio->uio_iov->iov_len -= space;
373 if (uio->uio_iov->iov_len == 0) {
374 uio->uio_iov++;
375 uio->uio_iovcnt--;
376 }
377
378 return space;
379 }
380
381 static int
382 socket_listener_cb(kauth_cred_t cred, kauth_action_t action, void *cookie,
383 void *arg0, void *arg1, void *arg2, void *arg3)
384 {
385 int result;
386 enum kauth_network_req req;
387
388 result = KAUTH_RESULT_DEFER;
389 req = (enum kauth_network_req)arg0;
390
391 if ((action != KAUTH_NETWORK_SOCKET) &&
392 (action != KAUTH_NETWORK_BIND))
393 return result;
394
395 switch (req) {
396 case KAUTH_REQ_NETWORK_BIND_PORT:
397 result = KAUTH_RESULT_ALLOW;
398 break;
399
400 case KAUTH_REQ_NETWORK_SOCKET_DROP: {
401 /* Normal users can only drop their own connections. */
402 struct socket *so = (struct socket *)arg1;
403
404 if (so->so_cred && proc_uidmatch(cred, so->so_cred) == 0)
405 result = KAUTH_RESULT_ALLOW;
406
407 break;
408 }
409
410 case KAUTH_REQ_NETWORK_SOCKET_OPEN:
411 /* We allow "raw" routing/bluetooth sockets to anyone. */
412 switch ((u_long)arg1) {
413 case PF_ROUTE:
414 case PF_OROUTE:
415 case PF_BLUETOOTH:
416 case PF_CAN:
417 result = KAUTH_RESULT_ALLOW;
418 break;
419 default:
420 /* Privileged, let secmodel handle this. */
421 if ((u_long)arg2 == SOCK_RAW)
422 break;
423 result = KAUTH_RESULT_ALLOW;
424 break;
425 }
426 break;
427
428 case KAUTH_REQ_NETWORK_SOCKET_CANSEE:
429 result = KAUTH_RESULT_ALLOW;
430
431 break;
432
433 default:
434 break;
435 }
436
437 return result;
438 }
439
440 void
441 soinit(void)
442 {
443
444 sysctl_kern_socket_setup();
445
446 #ifdef SCTP
447 /* Update the SCTP function hooks if necessary*/
448
449 vec_sctp_add_ip_address = sctp_add_ip_address;
450 vec_sctp_delete_ip_address = sctp_delete_ip_address;
451 #endif
452
453 mutex_init(&so_pendfree_lock, MUTEX_DEFAULT, IPL_VM);
454 softnet_lock = mutex_obj_alloc(MUTEX_DEFAULT, IPL_NONE);
455 cv_init(&socurkva_cv, "sokva");
456 cv_init(&pendfree_thread_cv, "sopendfr");
457 soinit2();
458
459 /* Set the initial adjusted socket buffer size. */
460 if (sb_max_set(sb_max))
461 panic("bad initial sb_max value: %lu", sb_max);
462
463 socket_listener = kauth_listen_scope(KAUTH_SCOPE_NETWORK,
464 socket_listener_cb, NULL);
465 }
466
467 void
468 soinit1(void)
469 {
470 int error = kthread_create(PRI_NONE, KTHREAD_MPSAFE, NULL,
471 sopendfree_thread, NULL, &sopendfree_lwp, "sopendfree");
472 if (error)
473 panic("soinit1 %d", error);
474 }
475
476 /*
477 * socreate: create a new socket of the specified type and the protocol.
478 *
479 * => Caller may specify another socket for lock sharing (must not be held).
480 * => Returns the new socket without lock held.
481 */
482 int
483 socreate(int dom, struct socket **aso, int type, int proto, struct lwp *l,
484 struct socket *lockso)
485 {
486 const struct protosw *prp;
487 struct socket *so;
488 uid_t uid;
489 int error;
490 kmutex_t *lock;
491
492 error = kauth_authorize_network(l->l_cred, KAUTH_NETWORK_SOCKET,
493 KAUTH_REQ_NETWORK_SOCKET_OPEN, KAUTH_ARG(dom), KAUTH_ARG(type),
494 KAUTH_ARG(proto));
495 if (error != 0)
496 return error;
497
498 if (proto)
499 prp = pffindproto(dom, proto, type);
500 else
501 prp = pffindtype(dom, type);
502 if (prp == NULL) {
503 /* no support for domain */
504 if (pffinddomain(dom) == 0)
505 return EAFNOSUPPORT;
506 /* no support for socket type */
507 if (proto == 0 && type != 0)
508 return EPROTOTYPE;
509 return EPROTONOSUPPORT;
510 }
511 if (prp->pr_usrreqs == NULL)
512 return EPROTONOSUPPORT;
513 if (prp->pr_type != type)
514 return EPROTOTYPE;
515
516 so = soget(true);
517 so->so_type = type;
518 so->so_proto = prp;
519 so->so_send = sosend;
520 so->so_receive = soreceive;
521 so->so_options = sooptions;
522 #ifdef MBUFTRACE
523 so->so_rcv.sb_mowner = &prp->pr_domain->dom_mowner;
524 so->so_snd.sb_mowner = &prp->pr_domain->dom_mowner;
525 so->so_mowner = &prp->pr_domain->dom_mowner;
526 #endif
527 uid = kauth_cred_geteuid(l->l_cred);
528 so->so_uidinfo = uid_find(uid);
529 so->so_egid = kauth_cred_getegid(l->l_cred);
530 so->so_cpid = l->l_proc->p_pid;
531
532 /*
533 * Lock assigned and taken during PCB attach, unless we share
534 * the lock with another socket, e.g. socketpair(2) case.
535 */
536 if (lockso) {
537 lock = lockso->so_lock;
538 so->so_lock = lock;
539 mutex_obj_hold(lock);
540 mutex_enter(lock);
541 }
542
543 /* Attach the PCB (returns with the socket lock held). */
544 error = (*prp->pr_usrreqs->pr_attach)(so, proto);
545 KASSERT(solocked(so));
546
547 if (error) {
548 KASSERT(so->so_pcb == NULL);
549 so->so_state |= SS_NOFDREF;
550 sofree(so);
551 return error;
552 }
553 so->so_cred = kauth_cred_dup(l->l_cred);
554 sounlock(so);
555
556 *aso = so;
557 return 0;
558 }
559
560 /*
561 * fsocreate: create a socket and a file descriptor associated with it.
562 *
563 * => On success, write file descriptor to fdout and return zero.
564 * => On failure, return non-zero; *fdout will be undefined.
565 */
566 int
567 fsocreate(int domain, struct socket **sop, int type, int proto, int *fdout)
568 {
569 lwp_t *l = curlwp;
570 int error, fd, flags;
571 struct socket *so;
572 struct file *fp;
573
574 if ((error = fd_allocfile(&fp, &fd)) != 0) {
575 return error;
576 }
577 flags = type & SOCK_FLAGS_MASK;
578 fd_set_exclose(l, fd, (flags & SOCK_CLOEXEC) != 0);
579 fp->f_flag = FREAD|FWRITE|((flags & SOCK_NONBLOCK) ? FNONBLOCK : 0)|
580 ((flags & SOCK_NOSIGPIPE) ? FNOSIGPIPE : 0);
581 fp->f_type = DTYPE_SOCKET;
582 fp->f_ops = &socketops;
583
584 type &= ~SOCK_FLAGS_MASK;
585 error = socreate(domain, &so, type, proto, l, NULL);
586 if (error) {
587 fd_abort(curproc, fp, fd);
588 return error;
589 }
590 if (flags & SOCK_NONBLOCK) {
591 so->so_state |= SS_NBIO;
592 }
593 fp->f_socket = so;
594 fd_affix(curproc, fp, fd);
595
596 if (sop != NULL) {
597 *sop = so;
598 }
599 *fdout = fd;
600 return error;
601 }
602
603 int
604 sofamily(const struct socket *so)
605 {
606 const struct protosw *pr;
607 const struct domain *dom;
608
609 if ((pr = so->so_proto) == NULL)
610 return AF_UNSPEC;
611 if ((dom = pr->pr_domain) == NULL)
612 return AF_UNSPEC;
613 return dom->dom_family;
614 }
615
616 int
617 sobind(struct socket *so, struct sockaddr *nam, struct lwp *l)
618 {
619 int error;
620
621 solock(so);
622 if (nam->sa_family != so->so_proto->pr_domain->dom_family) {
623 sounlock(so);
624 return EAFNOSUPPORT;
625 }
626 error = (*so->so_proto->pr_usrreqs->pr_bind)(so, nam, l);
627 sounlock(so);
628 return error;
629 }
630
631 int
632 solisten(struct socket *so, int backlog, struct lwp *l)
633 {
634 int error;
635 short oldopt, oldqlimit;
636
637 solock(so);
638 if ((so->so_state & (SS_ISCONNECTED | SS_ISCONNECTING |
639 SS_ISDISCONNECTING)) != 0) {
640 sounlock(so);
641 return EINVAL;
642 }
643 oldopt = so->so_options;
644 oldqlimit = so->so_qlimit;
645 if (TAILQ_EMPTY(&so->so_q))
646 so->so_options |= SO_ACCEPTCONN;
647 if (backlog < 0)
648 backlog = 0;
649 so->so_qlimit = uimin(backlog, somaxconn);
650
651 error = (*so->so_proto->pr_usrreqs->pr_listen)(so, l);
652 if (error != 0) {
653 so->so_options = oldopt;
654 so->so_qlimit = oldqlimit;
655 sounlock(so);
656 return error;
657 }
658 sounlock(so);
659 return 0;
660 }
661
662 void
663 sofree(struct socket *so)
664 {
665 u_int refs;
666
667 KASSERT(solocked(so));
668
669 if (so->so_pcb || (so->so_state & SS_NOFDREF) == 0) {
670 sounlock(so);
671 return;
672 }
673 if (so->so_head) {
674 /*
675 * We must not decommission a socket that's on the accept(2)
676 * queue. If we do, then accept(2) may hang after select(2)
677 * indicated that the listening socket was ready.
678 */
679 if (!soqremque(so, 0)) {
680 sounlock(so);
681 return;
682 }
683 }
684 if (so->so_rcv.sb_hiwat)
685 (void)chgsbsize(so->so_uidinfo, &so->so_rcv.sb_hiwat, 0,
686 RLIM_INFINITY);
687 if (so->so_snd.sb_hiwat)
688 (void)chgsbsize(so->so_uidinfo, &so->so_snd.sb_hiwat, 0,
689 RLIM_INFINITY);
690 sbrelease(&so->so_snd, so);
691 KASSERT(!cv_has_waiters(&so->so_cv));
692 KASSERT(!cv_has_waiters(&so->so_rcv.sb_cv));
693 KASSERT(!cv_has_waiters(&so->so_snd.sb_cv));
694 sorflush(so);
695 refs = so->so_aborting; /* XXX */
696 /* Remove acccept filter if one is present. */
697 if (so->so_accf != NULL)
698 (void)accept_filt_clear(so);
699 sounlock(so);
700 if (refs == 0) /* XXX */
701 soput(so);
702 }
703
704 /*
705 * soclose: close a socket on last file table reference removal.
706 * Initiate disconnect if connected. Free socket when disconnect complete.
707 */
708 int
709 soclose(struct socket *so)
710 {
711 struct socket *so2;
712 int error = 0;
713
714 solock(so);
715 if (so->so_options & SO_ACCEPTCONN) {
716 for (;;) {
717 if ((so2 = TAILQ_FIRST(&so->so_q0)) != 0) {
718 KASSERT(solocked2(so, so2));
719 (void) soqremque(so2, 0);
720 /* soabort drops the lock. */
721 (void) soabort(so2);
722 solock(so);
723 continue;
724 }
725 if ((so2 = TAILQ_FIRST(&so->so_q)) != 0) {
726 KASSERT(solocked2(so, so2));
727 (void) soqremque(so2, 1);
728 /* soabort drops the lock. */
729 (void) soabort(so2);
730 solock(so);
731 continue;
732 }
733 break;
734 }
735 }
736 if (so->so_pcb == NULL)
737 goto discard;
738 if (so->so_state & SS_ISCONNECTED) {
739 if ((so->so_state & SS_ISDISCONNECTING) == 0) {
740 error = sodisconnect(so);
741 if (error)
742 goto drop;
743 }
744 if (so->so_options & SO_LINGER) {
745 if ((so->so_state & (SS_ISDISCONNECTING|SS_NBIO)) ==
746 (SS_ISDISCONNECTING|SS_NBIO))
747 goto drop;
748 while (so->so_state & SS_ISCONNECTED) {
749 error = sowait(so, true, so->so_linger * hz);
750 if (error)
751 break;
752 }
753 }
754 }
755 drop:
756 if (so->so_pcb) {
757 KASSERT(solocked(so));
758 (*so->so_proto->pr_usrreqs->pr_detach)(so);
759 }
760 discard:
761 KASSERT((so->so_state & SS_NOFDREF) == 0);
762 kauth_cred_free(so->so_cred);
763 so->so_cred = NULL;
764 so->so_state |= SS_NOFDREF;
765 sofree(so);
766 return error;
767 }
768
769 /*
770 * Must be called with the socket locked.. Will return with it unlocked.
771 */
772 int
773 soabort(struct socket *so)
774 {
775 u_int refs;
776 int error;
777
778 KASSERT(solocked(so));
779 KASSERT(so->so_head == NULL);
780
781 so->so_aborting++; /* XXX */
782 error = (*so->so_proto->pr_usrreqs->pr_abort)(so);
783 refs = --so->so_aborting; /* XXX */
784 if (error || (refs == 0)) {
785 sofree(so);
786 } else {
787 sounlock(so);
788 }
789 return error;
790 }
791
792 int
793 soaccept(struct socket *so, struct sockaddr *nam)
794 {
795 int error;
796
797 KASSERT(solocked(so));
798 KASSERT((so->so_state & SS_NOFDREF) != 0);
799
800 so->so_state &= ~SS_NOFDREF;
801 if ((so->so_state & SS_ISDISCONNECTED) == 0 ||
802 (so->so_proto->pr_flags & PR_ABRTACPTDIS) == 0)
803 error = (*so->so_proto->pr_usrreqs->pr_accept)(so, nam);
804 else
805 error = ECONNABORTED;
806
807 return error;
808 }
809
810 int
811 soconnect(struct socket *so, struct sockaddr *nam, struct lwp *l)
812 {
813 int error;
814
815 KASSERT(solocked(so));
816
817 if (so->so_options & SO_ACCEPTCONN)
818 return EOPNOTSUPP;
819 /*
820 * If protocol is connection-based, can only connect once.
821 * Otherwise, if connected, try to disconnect first.
822 * This allows user to disconnect by connecting to, e.g.,
823 * a null address.
824 */
825 if (so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING) &&
826 ((so->so_proto->pr_flags & PR_CONNREQUIRED) ||
827 (error = sodisconnect(so)))) {
828 error = EISCONN;
829 } else {
830 if (nam->sa_family != so->so_proto->pr_domain->dom_family) {
831 return EAFNOSUPPORT;
832 }
833 error = (*so->so_proto->pr_usrreqs->pr_connect)(so, nam, l);
834 }
835
836 return error;
837 }
838
839 int
840 soconnect2(struct socket *so1, struct socket *so2)
841 {
842 KASSERT(solocked2(so1, so2));
843
844 return (*so1->so_proto->pr_usrreqs->pr_connect2)(so1, so2);
845 }
846
847 int
848 sodisconnect(struct socket *so)
849 {
850 int error;
851
852 KASSERT(solocked(so));
853
854 if ((so->so_state & SS_ISCONNECTED) == 0) {
855 error = ENOTCONN;
856 } else if (so->so_state & SS_ISDISCONNECTING) {
857 error = EALREADY;
858 } else {
859 error = (*so->so_proto->pr_usrreqs->pr_disconnect)(so);
860 }
861 return error;
862 }
863
864 #define SBLOCKWAIT(f) (((f) & MSG_DONTWAIT) ? M_NOWAIT : M_WAITOK)
865 /*
866 * Send on a socket.
867 * If send must go all at once and message is larger than
868 * send buffering, then hard error.
869 * Lock against other senders.
870 * If must go all at once and not enough room now, then
871 * inform user that this would block and do nothing.
872 * Otherwise, if nonblocking, send as much as possible.
873 * The data to be sent is described by "uio" if nonzero,
874 * otherwise by the mbuf chain "top" (which must be null
875 * if uio is not). Data provided in mbuf chain must be small
876 * enough to send all at once.
877 *
878 * Returns nonzero on error, timeout or signal; callers
879 * must check for short counts if EINTR/ERESTART are returned.
880 * Data and control buffers are freed on return.
881 */
882 int
883 sosend(struct socket *so, struct sockaddr *addr, struct uio *uio,
884 struct mbuf *top, struct mbuf *control, int flags, struct lwp *l)
885 {
886 struct mbuf **mp, *m;
887 long space, len, resid, clen, mlen;
888 int error, s, dontroute, atomic;
889 short wakeup_state = 0;
890
891 clen = 0;
892
893 /*
894 * solock() provides atomicity of access. splsoftnet() prevents
895 * protocol processing soft interrupts from interrupting us and
896 * blocking (expensive).
897 */
898 s = splsoftnet();
899 solock(so);
900 atomic = sosendallatonce(so) || top;
901 if (uio)
902 resid = uio->uio_resid;
903 else
904 resid = top->m_pkthdr.len;
905 /*
906 * In theory resid should be unsigned.
907 * However, space must be signed, as it might be less than 0
908 * if we over-committed, and we must use a signed comparison
909 * of space and resid. On the other hand, a negative resid
910 * causes us to loop sending 0-length segments to the protocol.
911 */
912 if (resid < 0) {
913 error = EINVAL;
914 goto out;
915 }
916 dontroute =
917 (flags & MSG_DONTROUTE) && (so->so_options & SO_DONTROUTE) == 0 &&
918 (so->so_proto->pr_flags & PR_ATOMIC);
919 l->l_ru.ru_msgsnd++;
920 if (control)
921 clen = control->m_len;
922 restart:
923 if ((error = sblock(&so->so_snd, SBLOCKWAIT(flags))) != 0)
924 goto out;
925 do {
926 if (so->so_state & SS_CANTSENDMORE) {
927 error = EPIPE;
928 goto release;
929 }
930 if (so->so_error) {
931 error = so->so_error;
932 so->so_error = 0;
933 goto release;
934 }
935 if ((so->so_state & SS_ISCONNECTED) == 0) {
936 if (so->so_proto->pr_flags & PR_CONNREQUIRED) {
937 if (resid || clen == 0) {
938 error = ENOTCONN;
939 goto release;
940 }
941 } else if (addr == NULL) {
942 error = EDESTADDRREQ;
943 goto release;
944 }
945 }
946 space = sbspace(&so->so_snd);
947 if (flags & MSG_OOB)
948 space += 1024;
949 if ((atomic && resid > so->so_snd.sb_hiwat) ||
950 clen > so->so_snd.sb_hiwat) {
951 error = EMSGSIZE;
952 goto release;
953 }
954 if (space < resid + clen &&
955 (atomic || space < so->so_snd.sb_lowat || space < clen)) {
956 if ((so->so_state & SS_NBIO) || (flags & MSG_NBIO)) {
957 error = EWOULDBLOCK;
958 goto release;
959 }
960 sbunlock(&so->so_snd);
961 if (wakeup_state & SS_RESTARTSYS) {
962 error = ERESTART;
963 goto out;
964 }
965 error = sbwait(&so->so_snd);
966 if (error)
967 goto out;
968 wakeup_state = so->so_state;
969 goto restart;
970 }
971 wakeup_state = 0;
972 mp = ⊤
973 space -= clen;
974 do {
975 if (uio == NULL) {
976 /*
977 * Data is prepackaged in "top".
978 */
979 resid = 0;
980 if (flags & MSG_EOR)
981 top->m_flags |= M_EOR;
982 } else do {
983 sounlock(so);
984 splx(s);
985 if (top == NULL) {
986 m = m_gethdr(M_WAIT, MT_DATA);
987 mlen = MHLEN;
988 m->m_pkthdr.len = 0;
989 m_reset_rcvif(m);
990 } else {
991 m = m_get(M_WAIT, MT_DATA);
992 mlen = MLEN;
993 }
994 MCLAIM(m, so->so_snd.sb_mowner);
995 if (sock_loan_thresh >= 0 &&
996 uio->uio_iov->iov_len >= sock_loan_thresh &&
997 space >= sock_loan_thresh &&
998 (len = sosend_loan(so, uio, m,
999 space)) != 0) {
1000 SOSEND_COUNTER_INCR(&sosend_loan_big);
1001 space -= len;
1002 goto have_data;
1003 }
1004 if (resid >= MINCLSIZE && space >= MCLBYTES) {
1005 SOSEND_COUNTER_INCR(&sosend_copy_big);
1006 m_clget(m, M_DONTWAIT);
1007 if ((m->m_flags & M_EXT) == 0)
1008 goto nopages;
1009 mlen = MCLBYTES;
1010 if (atomic && top == 0) {
1011 len = lmin(MCLBYTES - max_hdr,
1012 resid);
1013 m->m_data += max_hdr;
1014 } else
1015 len = lmin(MCLBYTES, resid);
1016 space -= len;
1017 } else {
1018 nopages:
1019 SOSEND_COUNTER_INCR(&sosend_copy_small);
1020 len = lmin(lmin(mlen, resid), space);
1021 space -= len;
1022 /*
1023 * For datagram protocols, leave room
1024 * for protocol headers in first mbuf.
1025 */
1026 if (atomic && top == 0 && len < mlen)
1027 m_align(m, len);
1028 }
1029 error = uiomove(mtod(m, void *), (int)len, uio);
1030 have_data:
1031 resid = uio->uio_resid;
1032 m->m_len = len;
1033 *mp = m;
1034 top->m_pkthdr.len += len;
1035 s = splsoftnet();
1036 solock(so);
1037 if (error != 0)
1038 goto release;
1039 mp = &m->m_next;
1040 if (resid <= 0) {
1041 if (flags & MSG_EOR)
1042 top->m_flags |= M_EOR;
1043 break;
1044 }
1045 } while (space > 0 && atomic);
1046
1047 if (so->so_state & SS_CANTSENDMORE) {
1048 error = EPIPE;
1049 goto release;
1050 }
1051 if (dontroute)
1052 so->so_options |= SO_DONTROUTE;
1053 if (resid > 0)
1054 so->so_state |= SS_MORETOCOME;
1055 if (flags & MSG_OOB) {
1056 error = (*so->so_proto->pr_usrreqs->pr_sendoob)(
1057 so, top, control);
1058 } else {
1059 error = (*so->so_proto->pr_usrreqs->pr_send)(so,
1060 top, addr, control, l);
1061 }
1062 if (dontroute)
1063 so->so_options &= ~SO_DONTROUTE;
1064 if (resid > 0)
1065 so->so_state &= ~SS_MORETOCOME;
1066 clen = 0;
1067 control = NULL;
1068 top = NULL;
1069 mp = ⊤
1070 if (error != 0)
1071 goto release;
1072 } while (resid && space > 0);
1073 } while (resid);
1074
1075 release:
1076 sbunlock(&so->so_snd);
1077 out:
1078 sounlock(so);
1079 splx(s);
1080 if (top)
1081 m_freem(top);
1082 if (control)
1083 m_freem(control);
1084 return error;
1085 }
1086
1087 /*
1088 * Following replacement or removal of the first mbuf on the first
1089 * mbuf chain of a socket buffer, push necessary state changes back
1090 * into the socket buffer so that other consumers see the values
1091 * consistently. 'nextrecord' is the caller's locally stored value of
1092 * the original value of sb->sb_mb->m_nextpkt which must be restored
1093 * when the lead mbuf changes. NOTE: 'nextrecord' may be NULL.
1094 */
1095 static void
1096 sbsync(struct sockbuf *sb, struct mbuf *nextrecord)
1097 {
1098
1099 KASSERT(solocked(sb->sb_so));
1100
1101 /*
1102 * First, update for the new value of nextrecord. If necessary,
1103 * make it the first record.
1104 */
1105 if (sb->sb_mb != NULL)
1106 sb->sb_mb->m_nextpkt = nextrecord;
1107 else
1108 sb->sb_mb = nextrecord;
1109
1110 /*
1111 * Now update any dependent socket buffer fields to reflect
1112 * the new state. This is an inline of SB_EMPTY_FIXUP, with
1113 * the addition of a second clause that takes care of the
1114 * case where sb_mb has been updated, but remains the last
1115 * record.
1116 */
1117 if (sb->sb_mb == NULL) {
1118 sb->sb_mbtail = NULL;
1119 sb->sb_lastrecord = NULL;
1120 } else if (sb->sb_mb->m_nextpkt == NULL)
1121 sb->sb_lastrecord = sb->sb_mb;
1122 }
1123
1124 /*
1125 * Implement receive operations on a socket.
1126 *
1127 * We depend on the way that records are added to the sockbuf by sbappend*. In
1128 * particular, each record (mbufs linked through m_next) must begin with an
1129 * address if the protocol so specifies, followed by an optional mbuf or mbufs
1130 * containing ancillary data, and then zero or more mbufs of data.
1131 *
1132 * In order to avoid blocking network interrupts for the entire time here, we
1133 * splx() while doing the actual copy to user space. Although the sockbuf is
1134 * locked, new data may still be appended, and thus we must maintain
1135 * consistency of the sockbuf during that time.
1136 *
1137 * The caller may receive the data as a single mbuf chain by supplying an mbuf
1138 * **mp0 for use in returning the chain. The uio is then used only for the
1139 * count in uio_resid.
1140 */
1141 int
1142 soreceive(struct socket *so, struct mbuf **paddr, struct uio *uio,
1143 struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
1144 {
1145 struct lwp *l = curlwp;
1146 struct mbuf *m, **mp, *mt;
1147 size_t len, offset, moff, orig_resid;
1148 int atomic, flags, error, s, type;
1149 const struct protosw *pr;
1150 struct mbuf *nextrecord;
1151 int mbuf_removed = 0;
1152 const struct domain *dom;
1153 short wakeup_state = 0;
1154
1155 pr = so->so_proto;
1156 atomic = pr->pr_flags & PR_ATOMIC;
1157 dom = pr->pr_domain;
1158 mp = mp0;
1159 type = 0;
1160 orig_resid = uio->uio_resid;
1161
1162 if (paddr != NULL)
1163 *paddr = NULL;
1164 if (controlp != NULL)
1165 *controlp = NULL;
1166 if (flagsp != NULL)
1167 flags = *flagsp &~ MSG_EOR;
1168 else
1169 flags = 0;
1170
1171 if (flags & MSG_OOB) {
1172 m = m_get(M_WAIT, MT_DATA);
1173 solock(so);
1174 error = (*pr->pr_usrreqs->pr_recvoob)(so, m, flags & MSG_PEEK);
1175 sounlock(so);
1176 if (error)
1177 goto bad;
1178 do {
1179 error = uiomove(mtod(m, void *),
1180 MIN(uio->uio_resid, m->m_len), uio);
1181 m = m_free(m);
1182 } while (uio->uio_resid > 0 && error == 0 && m);
1183 bad:
1184 if (m != NULL)
1185 m_freem(m);
1186 return error;
1187 }
1188 if (mp != NULL)
1189 *mp = NULL;
1190
1191 /*
1192 * solock() provides atomicity of access. splsoftnet() prevents
1193 * protocol processing soft interrupts from interrupting us and
1194 * blocking (expensive).
1195 */
1196 s = splsoftnet();
1197 solock(so);
1198 restart:
1199 if ((error = sblock(&so->so_rcv, SBLOCKWAIT(flags))) != 0) {
1200 sounlock(so);
1201 splx(s);
1202 return error;
1203 }
1204 m = so->so_rcv.sb_mb;
1205
1206 /*
1207 * If we have less data than requested, block awaiting more
1208 * (subject to any timeout) if:
1209 * 1. the current count is less than the low water mark,
1210 * 2. MSG_WAITALL is set, and it is possible to do the entire
1211 * receive operation at once if we block (resid <= hiwat), or
1212 * 3. MSG_DONTWAIT is not set.
1213 * If MSG_WAITALL is set but resid is larger than the receive buffer,
1214 * we have to do the receive in sections, and thus risk returning
1215 * a short count if a timeout or signal occurs after we start.
1216 */
1217 if (m == NULL ||
1218 ((flags & MSG_DONTWAIT) == 0 &&
1219 so->so_rcv.sb_cc < uio->uio_resid &&
1220 (so->so_rcv.sb_cc < so->so_rcv.sb_lowat ||
1221 ((flags & MSG_WAITALL) &&
1222 uio->uio_resid <= so->so_rcv.sb_hiwat)) &&
1223 m->m_nextpkt == NULL && !atomic)) {
1224 #ifdef DIAGNOSTIC
1225 if (m == NULL && so->so_rcv.sb_cc)
1226 panic("receive 1");
1227 #endif
1228 if (so->so_error || so->so_rerror) {
1229 if (m != NULL)
1230 goto dontblock;
1231 if (so->so_error) {
1232 error = so->so_error;
1233 so->so_error = 0;
1234 } else {
1235 error = so->so_rerror;
1236 so->so_rerror = 0;
1237 }
1238 goto release;
1239 }
1240 if (so->so_state & SS_CANTRCVMORE) {
1241 if (m != NULL)
1242 goto dontblock;
1243 else
1244 goto release;
1245 }
1246 for (; m != NULL; m = m->m_next)
1247 if (m->m_type == MT_OOBDATA || (m->m_flags & M_EOR)) {
1248 m = so->so_rcv.sb_mb;
1249 goto dontblock;
1250 }
1251 if ((so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING)) == 0 &&
1252 (so->so_proto->pr_flags & PR_CONNREQUIRED)) {
1253 error = ENOTCONN;
1254 goto release;
1255 }
1256 if (uio->uio_resid == 0)
1257 goto release;
1258 if ((so->so_state & SS_NBIO) ||
1259 (flags & (MSG_DONTWAIT|MSG_NBIO))) {
1260 error = EWOULDBLOCK;
1261 goto release;
1262 }
1263 SBLASTRECORDCHK(&so->so_rcv, "soreceive sbwait 1");
1264 SBLASTMBUFCHK(&so->so_rcv, "soreceive sbwait 1");
1265 sbunlock(&so->so_rcv);
1266 if (wakeup_state & SS_RESTARTSYS)
1267 error = ERESTART;
1268 else
1269 error = sbwait(&so->so_rcv);
1270 if (error != 0) {
1271 sounlock(so);
1272 splx(s);
1273 return error;
1274 }
1275 wakeup_state = so->so_state;
1276 goto restart;
1277 }
1278
1279 dontblock:
1280 /*
1281 * On entry here, m points to the first record of the socket buffer.
1282 * From this point onward, we maintain 'nextrecord' as a cache of the
1283 * pointer to the next record in the socket buffer. We must keep the
1284 * various socket buffer pointers and local stack versions of the
1285 * pointers in sync, pushing out modifications before dropping the
1286 * socket lock, and re-reading them when picking it up.
1287 *
1288 * Otherwise, we will race with the network stack appending new data
1289 * or records onto the socket buffer by using inconsistent/stale
1290 * versions of the field, possibly resulting in socket buffer
1291 * corruption.
1292 *
1293 * By holding the high-level sblock(), we prevent simultaneous
1294 * readers from pulling off the front of the socket buffer.
1295 */
1296 if (l != NULL)
1297 l->l_ru.ru_msgrcv++;
1298 KASSERT(m == so->so_rcv.sb_mb);
1299 SBLASTRECORDCHK(&so->so_rcv, "soreceive 1");
1300 SBLASTMBUFCHK(&so->so_rcv, "soreceive 1");
1301 nextrecord = m->m_nextpkt;
1302
1303 if (pr->pr_flags & PR_ADDR) {
1304 KASSERT(m->m_type == MT_SONAME);
1305 orig_resid = 0;
1306 if (flags & MSG_PEEK) {
1307 if (paddr)
1308 *paddr = m_copym(m, 0, m->m_len, M_DONTWAIT);
1309 m = m->m_next;
1310 } else {
1311 sbfree(&so->so_rcv, m);
1312 mbuf_removed = 1;
1313 if (paddr != NULL) {
1314 *paddr = m;
1315 so->so_rcv.sb_mb = m->m_next;
1316 m->m_next = NULL;
1317 m = so->so_rcv.sb_mb;
1318 } else {
1319 m = so->so_rcv.sb_mb = m_free(m);
1320 }
1321 sbsync(&so->so_rcv, nextrecord);
1322 }
1323 }
1324
1325 if (pr->pr_flags & PR_ADDR_OPT) {
1326 /*
1327 * For SCTP we may be getting a whole message OR a partial
1328 * delivery.
1329 */
1330 if (m->m_type == MT_SONAME) {
1331 orig_resid = 0;
1332 if (flags & MSG_PEEK) {
1333 if (paddr)
1334 *paddr = m_copym(m, 0, m->m_len, M_DONTWAIT);
1335 m = m->m_next;
1336 } else {
1337 sbfree(&so->so_rcv, m);
1338 /* XXX XXX XXX: should set mbuf_removed? */
1339 if (paddr) {
1340 *paddr = m;
1341 so->so_rcv.sb_mb = m->m_next;
1342 m->m_next = 0;
1343 m = so->so_rcv.sb_mb;
1344 } else {
1345 m = so->so_rcv.sb_mb = m_free(m);
1346 }
1347 /* XXX XXX XXX: isn't there an sbsync()
1348 * missing here? */
1349 }
1350 }
1351 }
1352
1353 /*
1354 * Process one or more MT_CONTROL mbufs present before any data mbufs
1355 * in the first mbuf chain on the socket buffer. If MSG_PEEK, we
1356 * just copy the data; if !MSG_PEEK, we call into the protocol to
1357 * perform externalization (or freeing if controlp == NULL).
1358 */
1359 if (__predict_false(m != NULL && m->m_type == MT_CONTROL)) {
1360 struct mbuf *cm = NULL, *cmn;
1361 struct mbuf **cme = &cm;
1362
1363 do {
1364 if (flags & MSG_PEEK) {
1365 if (controlp != NULL) {
1366 *controlp = m_copym(m, 0, m->m_len, M_DONTWAIT);
1367 controlp = &(*controlp)->m_next;
1368 }
1369 m = m->m_next;
1370 } else {
1371 sbfree(&so->so_rcv, m);
1372 so->so_rcv.sb_mb = m->m_next;
1373 m->m_next = NULL;
1374 *cme = m;
1375 cme = &(*cme)->m_next;
1376 m = so->so_rcv.sb_mb;
1377 }
1378 } while (m != NULL && m->m_type == MT_CONTROL);
1379 if ((flags & MSG_PEEK) == 0)
1380 sbsync(&so->so_rcv, nextrecord);
1381
1382 for (; cm != NULL; cm = cmn) {
1383 cmn = cm->m_next;
1384 cm->m_next = NULL;
1385 type = mtod(cm, struct cmsghdr *)->cmsg_type;
1386 if (controlp != NULL) {
1387 if (dom->dom_externalize != NULL &&
1388 type == SCM_RIGHTS) {
1389 sounlock(so);
1390 splx(s);
1391 error = (*dom->dom_externalize)(cm, l,
1392 (flags & MSG_CMSG_CLOEXEC) ?
1393 O_CLOEXEC : 0);
1394 s = splsoftnet();
1395 solock(so);
1396 }
1397 *controlp = cm;
1398 while (*controlp != NULL)
1399 controlp = &(*controlp)->m_next;
1400 } else {
1401 /*
1402 * Dispose of any SCM_RIGHTS message that went
1403 * through the read path rather than recv.
1404 */
1405 if (dom->dom_dispose != NULL &&
1406 type == SCM_RIGHTS) {
1407 sounlock(so);
1408 (*dom->dom_dispose)(cm);
1409 solock(so);
1410 }
1411 m_freem(cm);
1412 }
1413 }
1414 if (m != NULL)
1415 nextrecord = so->so_rcv.sb_mb->m_nextpkt;
1416 else
1417 nextrecord = so->so_rcv.sb_mb;
1418 orig_resid = 0;
1419 }
1420
1421 /* If m is non-NULL, we have some data to read. */
1422 if (__predict_true(m != NULL)) {
1423 type = m->m_type;
1424 if (type == MT_OOBDATA)
1425 flags |= MSG_OOB;
1426 }
1427 SBLASTRECORDCHK(&so->so_rcv, "soreceive 2");
1428 SBLASTMBUFCHK(&so->so_rcv, "soreceive 2");
1429
1430 moff = 0;
1431 offset = 0;
1432 while (m != NULL && uio->uio_resid > 0 && error == 0) {
1433 /*
1434 * If the type of mbuf has changed, end the receive
1435 * operation and do a short read.
1436 */
1437 if (m->m_type == MT_OOBDATA) {
1438 if (type != MT_OOBDATA)
1439 break;
1440 } else if (type == MT_OOBDATA) {
1441 break;
1442 } else if (m->m_type == MT_CONTROL) {
1443 break;
1444 }
1445 #ifdef DIAGNOSTIC
1446 else if (m->m_type != MT_DATA && m->m_type != MT_HEADER) {
1447 panic("%s: m_type=%d", __func__, m->m_type);
1448 }
1449 #endif
1450
1451 so->so_state &= ~SS_RCVATMARK;
1452 wakeup_state = 0;
1453 len = uio->uio_resid;
1454 if (so->so_oobmark && len > so->so_oobmark - offset)
1455 len = so->so_oobmark - offset;
1456 if (len > m->m_len - moff)
1457 len = m->m_len - moff;
1458
1459 /*
1460 * If mp is set, just pass back the mbufs.
1461 * Otherwise copy them out via the uio, then free.
1462 * Sockbuf must be consistent here (points to current mbuf,
1463 * it points to next record) when we drop priority;
1464 * we must note any additions to the sockbuf when we
1465 * block interrupts again.
1466 */
1467 if (mp == NULL) {
1468 SBLASTRECORDCHK(&so->so_rcv, "soreceive uiomove");
1469 SBLASTMBUFCHK(&so->so_rcv, "soreceive uiomove");
1470 sounlock(so);
1471 splx(s);
1472 error = uiomove(mtod(m, char *) + moff, len, uio);
1473 s = splsoftnet();
1474 solock(so);
1475 if (error != 0) {
1476 /*
1477 * If any part of the record has been removed
1478 * (such as the MT_SONAME mbuf, which will
1479 * happen when PR_ADDR, and thus also
1480 * PR_ATOMIC, is set), then drop the entire
1481 * record to maintain the atomicity of the
1482 * receive operation.
1483 *
1484 * This avoids a later panic("receive 1a")
1485 * when compiled with DIAGNOSTIC.
1486 */
1487 if (m && mbuf_removed && atomic)
1488 (void) sbdroprecord(&so->so_rcv);
1489
1490 goto release;
1491 }
1492 } else {
1493 uio->uio_resid -= len;
1494 }
1495
1496 if (len == m->m_len - moff) {
1497 if (m->m_flags & M_EOR)
1498 flags |= MSG_EOR;
1499 #ifdef SCTP
1500 if (m->m_flags & M_NOTIFICATION)
1501 flags |= MSG_NOTIFICATION;
1502 #endif
1503 if (flags & MSG_PEEK) {
1504 m = m->m_next;
1505 moff = 0;
1506 } else {
1507 nextrecord = m->m_nextpkt;
1508 sbfree(&so->so_rcv, m);
1509 if (mp) {
1510 *mp = m;
1511 mp = &m->m_next;
1512 so->so_rcv.sb_mb = m = m->m_next;
1513 *mp = NULL;
1514 } else {
1515 m = so->so_rcv.sb_mb = m_free(m);
1516 }
1517 /*
1518 * If m != NULL, we also know that
1519 * so->so_rcv.sb_mb != NULL.
1520 */
1521 KASSERT(so->so_rcv.sb_mb == m);
1522 if (m) {
1523 m->m_nextpkt = nextrecord;
1524 if (nextrecord == NULL)
1525 so->so_rcv.sb_lastrecord = m;
1526 } else {
1527 so->so_rcv.sb_mb = nextrecord;
1528 SB_EMPTY_FIXUP(&so->so_rcv);
1529 }
1530 SBLASTRECORDCHK(&so->so_rcv, "soreceive 3");
1531 SBLASTMBUFCHK(&so->so_rcv, "soreceive 3");
1532 }
1533 } else if (flags & MSG_PEEK) {
1534 moff += len;
1535 } else {
1536 if (mp != NULL) {
1537 mt = m_copym(m, 0, len, M_NOWAIT);
1538 if (__predict_false(mt == NULL)) {
1539 sounlock(so);
1540 mt = m_copym(m, 0, len, M_WAIT);
1541 solock(so);
1542 }
1543 *mp = mt;
1544 }
1545 m->m_data += len;
1546 m->m_len -= len;
1547 so->so_rcv.sb_cc -= len;
1548 }
1549
1550 if (so->so_oobmark) {
1551 if ((flags & MSG_PEEK) == 0) {
1552 so->so_oobmark -= len;
1553 if (so->so_oobmark == 0) {
1554 so->so_state |= SS_RCVATMARK;
1555 break;
1556 }
1557 } else {
1558 offset += len;
1559 if (offset == so->so_oobmark)
1560 break;
1561 }
1562 }
1563 if (flags & MSG_EOR)
1564 break;
1565
1566 /*
1567 * If the MSG_WAITALL flag is set (for non-atomic socket),
1568 * we must not quit until "uio->uio_resid == 0" or an error
1569 * termination. If a signal/timeout occurs, return
1570 * with a short count but without error.
1571 * Keep sockbuf locked against other readers.
1572 */
1573 while (flags & MSG_WAITALL && m == NULL && uio->uio_resid > 0 &&
1574 !sosendallatonce(so) && !nextrecord) {
1575 if (so->so_error || so->so_rerror ||
1576 so->so_state & SS_CANTRCVMORE)
1577 break;
1578 /*
1579 * If we are peeking and the socket receive buffer is
1580 * full, stop since we can't get more data to peek at.
1581 */
1582 if ((flags & MSG_PEEK) && sbspace(&so->so_rcv) <= 0)
1583 break;
1584 /*
1585 * If we've drained the socket buffer, tell the
1586 * protocol in case it needs to do something to
1587 * get it filled again.
1588 */
1589 if ((pr->pr_flags & PR_WANTRCVD) && so->so_pcb)
1590 (*pr->pr_usrreqs->pr_rcvd)(so, flags, l);
1591 SBLASTRECORDCHK(&so->so_rcv, "soreceive sbwait 2");
1592 SBLASTMBUFCHK(&so->so_rcv, "soreceive sbwait 2");
1593 if (wakeup_state & SS_RESTARTSYS)
1594 error = ERESTART;
1595 else
1596 error = sbwait(&so->so_rcv);
1597 if (error != 0) {
1598 sbunlock(&so->so_rcv);
1599 sounlock(so);
1600 splx(s);
1601 return 0;
1602 }
1603 if ((m = so->so_rcv.sb_mb) != NULL)
1604 nextrecord = m->m_nextpkt;
1605 wakeup_state = so->so_state;
1606 }
1607 }
1608
1609 if (m && atomic) {
1610 flags |= MSG_TRUNC;
1611 if ((flags & MSG_PEEK) == 0)
1612 (void) sbdroprecord(&so->so_rcv);
1613 }
1614 if ((flags & MSG_PEEK) == 0) {
1615 if (m == NULL) {
1616 /*
1617 * First part is an inline SB_EMPTY_FIXUP(). Second
1618 * part makes sure sb_lastrecord is up-to-date if
1619 * there is still data in the socket buffer.
1620 */
1621 so->so_rcv.sb_mb = nextrecord;
1622 if (so->so_rcv.sb_mb == NULL) {
1623 so->so_rcv.sb_mbtail = NULL;
1624 so->so_rcv.sb_lastrecord = NULL;
1625 } else if (nextrecord->m_nextpkt == NULL)
1626 so->so_rcv.sb_lastrecord = nextrecord;
1627 }
1628 SBLASTRECORDCHK(&so->so_rcv, "soreceive 4");
1629 SBLASTMBUFCHK(&so->so_rcv, "soreceive 4");
1630 if (pr->pr_flags & PR_WANTRCVD && so->so_pcb)
1631 (*pr->pr_usrreqs->pr_rcvd)(so, flags, l);
1632 }
1633 if (orig_resid == uio->uio_resid && orig_resid &&
1634 (flags & MSG_EOR) == 0 && (so->so_state & SS_CANTRCVMORE) == 0) {
1635 sbunlock(&so->so_rcv);
1636 goto restart;
1637 }
1638
1639 if (flagsp != NULL)
1640 *flagsp |= flags;
1641 release:
1642 sbunlock(&so->so_rcv);
1643 sounlock(so);
1644 splx(s);
1645 return error;
1646 }
1647
1648 int
1649 soshutdown(struct socket *so, int how)
1650 {
1651 const struct protosw *pr;
1652 int error;
1653
1654 KASSERT(solocked(so));
1655
1656 pr = so->so_proto;
1657 if (!(how == SHUT_RD || how == SHUT_WR || how == SHUT_RDWR))
1658 return EINVAL;
1659
1660 if (how == SHUT_RD || how == SHUT_RDWR) {
1661 sorflush(so);
1662 error = 0;
1663 }
1664 if (how == SHUT_WR || how == SHUT_RDWR)
1665 error = (*pr->pr_usrreqs->pr_shutdown)(so);
1666
1667 return error;
1668 }
1669
1670 void
1671 sorestart(struct socket *so)
1672 {
1673 /*
1674 * An application has called close() on an fd on which another
1675 * of its threads has called a socket system call.
1676 * Mark this and wake everyone up, and code that would block again
1677 * instead returns ERESTART.
1678 * On system call re-entry the fd is validated and EBADF returned.
1679 * Any other fd will block again on the 2nd syscall.
1680 */
1681 solock(so);
1682 so->so_state |= SS_RESTARTSYS;
1683 cv_broadcast(&so->so_cv);
1684 cv_broadcast(&so->so_snd.sb_cv);
1685 cv_broadcast(&so->so_rcv.sb_cv);
1686 sounlock(so);
1687 }
1688
1689 void
1690 sorflush(struct socket *so)
1691 {
1692 struct sockbuf *sb, asb;
1693 const struct protosw *pr;
1694
1695 KASSERT(solocked(so));
1696
1697 sb = &so->so_rcv;
1698 pr = so->so_proto;
1699 socantrcvmore(so);
1700 sb->sb_flags |= SB_NOINTR;
1701 (void )sblock(sb, M_WAITOK);
1702 sbunlock(sb);
1703 asb = *sb;
1704 /*
1705 * Clear most of the sockbuf structure, but leave some of the
1706 * fields valid.
1707 */
1708 memset(&sb->sb_startzero, 0,
1709 sizeof(*sb) - offsetof(struct sockbuf, sb_startzero));
1710 if (pr->pr_flags & PR_RIGHTS && pr->pr_domain->dom_dispose) {
1711 sounlock(so);
1712 (*pr->pr_domain->dom_dispose)(asb.sb_mb);
1713 solock(so);
1714 }
1715 sbrelease(&asb, so);
1716 }
1717
1718 /*
1719 * internal set SOL_SOCKET options
1720 */
1721 static int
1722 sosetopt1(struct socket *so, const struct sockopt *sopt)
1723 {
1724 int error, opt;
1725 int optval = 0; /* XXX: gcc */
1726 struct linger l;
1727 struct timeval tv;
1728
1729 opt = sopt->sopt_name;
1730
1731 switch (opt) {
1732
1733 case SO_ACCEPTFILTER:
1734 error = accept_filt_setopt(so, sopt);
1735 KASSERT(solocked(so));
1736 break;
1737
1738 case SO_LINGER:
1739 error = sockopt_get(sopt, &l, sizeof(l));
1740 solock(so);
1741 if (error)
1742 break;
1743 if (l.l_linger < 0 || l.l_linger > USHRT_MAX ||
1744 l.l_linger > (INT_MAX / hz)) {
1745 error = EDOM;
1746 break;
1747 }
1748 so->so_linger = l.l_linger;
1749 if (l.l_onoff)
1750 so->so_options |= SO_LINGER;
1751 else
1752 so->so_options &= ~SO_LINGER;
1753 break;
1754
1755 case SO_DEBUG:
1756 case SO_KEEPALIVE:
1757 case SO_DONTROUTE:
1758 case SO_USELOOPBACK:
1759 case SO_BROADCAST:
1760 case SO_REUSEADDR:
1761 case SO_REUSEPORT:
1762 case SO_OOBINLINE:
1763 case SO_TIMESTAMP:
1764 case SO_NOSIGPIPE:
1765 case SO_RERROR:
1766 error = sockopt_getint(sopt, &optval);
1767 solock(so);
1768 if (error)
1769 break;
1770 if (optval)
1771 so->so_options |= opt;
1772 else
1773 so->so_options &= ~opt;
1774 break;
1775
1776 case SO_SNDBUF:
1777 case SO_RCVBUF:
1778 case SO_SNDLOWAT:
1779 case SO_RCVLOWAT:
1780 error = sockopt_getint(sopt, &optval);
1781 solock(so);
1782 if (error)
1783 break;
1784
1785 /*
1786 * Values < 1 make no sense for any of these
1787 * options, so disallow them.
1788 */
1789 if (optval < 1) {
1790 error = EINVAL;
1791 break;
1792 }
1793
1794 switch (opt) {
1795 case SO_SNDBUF:
1796 if (sbreserve(&so->so_snd, (u_long)optval, so) == 0) {
1797 error = ENOBUFS;
1798 break;
1799 }
1800 so->so_snd.sb_flags &= ~SB_AUTOSIZE;
1801 break;
1802
1803 case SO_RCVBUF:
1804 if (sbreserve(&so->so_rcv, (u_long)optval, so) == 0) {
1805 error = ENOBUFS;
1806 break;
1807 }
1808 so->so_rcv.sb_flags &= ~SB_AUTOSIZE;
1809 break;
1810
1811 /*
1812 * Make sure the low-water is never greater than
1813 * the high-water.
1814 */
1815 case SO_SNDLOWAT:
1816 if (optval > so->so_snd.sb_hiwat)
1817 optval = so->so_snd.sb_hiwat;
1818
1819 so->so_snd.sb_lowat = optval;
1820 break;
1821
1822 case SO_RCVLOWAT:
1823 if (optval > so->so_rcv.sb_hiwat)
1824 optval = so->so_rcv.sb_hiwat;
1825
1826 so->so_rcv.sb_lowat = optval;
1827 break;
1828 }
1829 break;
1830
1831 case SO_SNDTIMEO:
1832 case SO_RCVTIMEO:
1833 solock(so);
1834 error = sockopt_get(sopt, &tv, sizeof(tv));
1835 if (error)
1836 break;
1837
1838 if (tv.tv_sec < 0 || tv.tv_usec < 0 || tv.tv_usec >= 1000000) {
1839 error = EDOM;
1840 break;
1841 }
1842 if (tv.tv_sec > (INT_MAX - tv.tv_usec / tick) / hz) {
1843 error = EDOM;
1844 break;
1845 }
1846
1847 optval = tv.tv_sec * hz + tv.tv_usec / tick;
1848 if (optval == 0 && tv.tv_usec != 0)
1849 optval = 1;
1850
1851 switch (opt) {
1852 case SO_SNDTIMEO:
1853 so->so_snd.sb_timeo = optval;
1854 break;
1855 case SO_RCVTIMEO:
1856 so->so_rcv.sb_timeo = optval;
1857 break;
1858 }
1859 break;
1860
1861 default:
1862 MODULE_HOOK_CALL(uipc_socket_50_setopt1_hook,
1863 (opt, so, sopt), enosys(), error);
1864 if (error == ENOSYS || error == EPASSTHROUGH) {
1865 solock(so);
1866 error = ENOPROTOOPT;
1867 }
1868 break;
1869 }
1870 KASSERT(solocked(so));
1871 return error;
1872 }
1873
1874 int
1875 sosetopt(struct socket *so, struct sockopt *sopt)
1876 {
1877 int error, prerr;
1878
1879 if (sopt->sopt_level == SOL_SOCKET) {
1880 error = sosetopt1(so, sopt);
1881 KASSERT(solocked(so));
1882 } else {
1883 error = ENOPROTOOPT;
1884 solock(so);
1885 }
1886
1887 if ((error == 0 || error == ENOPROTOOPT) &&
1888 so->so_proto != NULL && so->so_proto->pr_ctloutput != NULL) {
1889 /* give the protocol stack a shot */
1890 prerr = (*so->so_proto->pr_ctloutput)(PRCO_SETOPT, so, sopt);
1891 if (prerr == 0)
1892 error = 0;
1893 else if (prerr != ENOPROTOOPT)
1894 error = prerr;
1895 }
1896 sounlock(so);
1897 return error;
1898 }
1899
1900 /*
1901 * so_setsockopt() is a wrapper providing a sockopt structure for sosetopt()
1902 */
1903 int
1904 so_setsockopt(struct lwp *l, struct socket *so, int level, int name,
1905 const void *val, size_t valsize)
1906 {
1907 struct sockopt sopt;
1908 int error;
1909
1910 KASSERT(valsize == 0 || val != NULL);
1911
1912 sockopt_init(&sopt, level, name, valsize);
1913 sockopt_set(&sopt, val, valsize);
1914
1915 error = sosetopt(so, &sopt);
1916
1917 sockopt_destroy(&sopt);
1918
1919 return error;
1920 }
1921
1922 /*
1923 * internal get SOL_SOCKET options
1924 */
1925 static int
1926 sogetopt1(struct socket *so, struct sockopt *sopt)
1927 {
1928 int error, optval, opt;
1929 struct linger l;
1930 struct timeval tv;
1931
1932 switch ((opt = sopt->sopt_name)) {
1933
1934 case SO_ACCEPTFILTER:
1935 error = accept_filt_getopt(so, sopt);
1936 break;
1937
1938 case SO_LINGER:
1939 l.l_onoff = (so->so_options & SO_LINGER) ? 1 : 0;
1940 l.l_linger = so->so_linger;
1941
1942 error = sockopt_set(sopt, &l, sizeof(l));
1943 break;
1944
1945 case SO_USELOOPBACK:
1946 case SO_DONTROUTE:
1947 case SO_DEBUG:
1948 case SO_KEEPALIVE:
1949 case SO_REUSEADDR:
1950 case SO_REUSEPORT:
1951 case SO_BROADCAST:
1952 case SO_OOBINLINE:
1953 case SO_TIMESTAMP:
1954 case SO_NOSIGPIPE:
1955 case SO_RERROR:
1956 case SO_ACCEPTCONN:
1957 error = sockopt_setint(sopt, (so->so_options & opt) ? 1 : 0);
1958 break;
1959
1960 case SO_TYPE:
1961 error = sockopt_setint(sopt, so->so_type);
1962 break;
1963
1964 case SO_ERROR:
1965 if (so->so_error == 0) {
1966 so->so_error = so->so_rerror;
1967 so->so_rerror = 0;
1968 }
1969 error = sockopt_setint(sopt, so->so_error);
1970 so->so_error = 0;
1971 break;
1972
1973 case SO_SNDBUF:
1974 error = sockopt_setint(sopt, so->so_snd.sb_hiwat);
1975 break;
1976
1977 case SO_RCVBUF:
1978 error = sockopt_setint(sopt, so->so_rcv.sb_hiwat);
1979 break;
1980
1981 case SO_SNDLOWAT:
1982 error = sockopt_setint(sopt, so->so_snd.sb_lowat);
1983 break;
1984
1985 case SO_RCVLOWAT:
1986 error = sockopt_setint(sopt, so->so_rcv.sb_lowat);
1987 break;
1988
1989 case SO_SNDTIMEO:
1990 case SO_RCVTIMEO:
1991 optval = (opt == SO_SNDTIMEO ?
1992 so->so_snd.sb_timeo : so->so_rcv.sb_timeo);
1993
1994 memset(&tv, 0, sizeof(tv));
1995 tv.tv_sec = optval / hz;
1996 tv.tv_usec = (optval % hz) * tick;
1997
1998 error = sockopt_set(sopt, &tv, sizeof(tv));
1999 break;
2000
2001 case SO_OVERFLOWED:
2002 error = sockopt_setint(sopt, so->so_rcv.sb_overflowed);
2003 break;
2004
2005 default:
2006 MODULE_HOOK_CALL(uipc_socket_50_getopt1_hook,
2007 (opt, so, sopt), enosys(), error);
2008 if (error)
2009 error = ENOPROTOOPT;
2010 break;
2011 }
2012
2013 return error;
2014 }
2015
2016 int
2017 sogetopt(struct socket *so, struct sockopt *sopt)
2018 {
2019 int error;
2020
2021 solock(so);
2022 if (sopt->sopt_level != SOL_SOCKET) {
2023 if (so->so_proto && so->so_proto->pr_ctloutput) {
2024 error = ((*so->so_proto->pr_ctloutput)
2025 (PRCO_GETOPT, so, sopt));
2026 } else
2027 error = (ENOPROTOOPT);
2028 } else {
2029 error = sogetopt1(so, sopt);
2030 }
2031 sounlock(so);
2032 return error;
2033 }
2034
2035 /*
2036 * alloc sockopt data buffer buffer
2037 * - will be released at destroy
2038 */
2039 static int
2040 sockopt_alloc(struct sockopt *sopt, size_t len, km_flag_t kmflag)
2041 {
2042
2043 KASSERT(sopt->sopt_size == 0);
2044
2045 if (len > sizeof(sopt->sopt_buf)) {
2046 sopt->sopt_data = kmem_zalloc(len, kmflag);
2047 if (sopt->sopt_data == NULL)
2048 return ENOMEM;
2049 } else
2050 sopt->sopt_data = sopt->sopt_buf;
2051
2052 sopt->sopt_size = len;
2053 return 0;
2054 }
2055
2056 /*
2057 * initialise sockopt storage
2058 * - MAY sleep during allocation
2059 */
2060 void
2061 sockopt_init(struct sockopt *sopt, int level, int name, size_t size)
2062 {
2063
2064 memset(sopt, 0, sizeof(*sopt));
2065
2066 sopt->sopt_level = level;
2067 sopt->sopt_name = name;
2068 (void)sockopt_alloc(sopt, size, KM_SLEEP);
2069 }
2070
2071 /*
2072 * destroy sockopt storage
2073 * - will release any held memory references
2074 */
2075 void
2076 sockopt_destroy(struct sockopt *sopt)
2077 {
2078
2079 if (sopt->sopt_data != sopt->sopt_buf)
2080 kmem_free(sopt->sopt_data, sopt->sopt_size);
2081
2082 memset(sopt, 0, sizeof(*sopt));
2083 }
2084
2085 /*
2086 * set sockopt value
2087 * - value is copied into sockopt
2088 * - memory is allocated when necessary, will not sleep
2089 */
2090 int
2091 sockopt_set(struct sockopt *sopt, const void *buf, size_t len)
2092 {
2093 int error;
2094
2095 if (sopt->sopt_size == 0) {
2096 error = sockopt_alloc(sopt, len, KM_NOSLEEP);
2097 if (error)
2098 return error;
2099 }
2100
2101 sopt->sopt_retsize = MIN(sopt->sopt_size, len);
2102 memcpy(sopt->sopt_data, buf, sopt->sopt_retsize);
2103
2104 return 0;
2105 }
2106
2107 /*
2108 * common case of set sockopt integer value
2109 */
2110 int
2111 sockopt_setint(struct sockopt *sopt, int val)
2112 {
2113
2114 return sockopt_set(sopt, &val, sizeof(int));
2115 }
2116
2117 /*
2118 * get sockopt value
2119 * - correct size must be given
2120 */
2121 int
2122 sockopt_get(const struct sockopt *sopt, void *buf, size_t len)
2123 {
2124
2125 if (sopt->sopt_size != len)
2126 return EINVAL;
2127
2128 memcpy(buf, sopt->sopt_data, len);
2129 return 0;
2130 }
2131
2132 /*
2133 * common case of get sockopt integer value
2134 */
2135 int
2136 sockopt_getint(const struct sockopt *sopt, int *valp)
2137 {
2138
2139 return sockopt_get(sopt, valp, sizeof(int));
2140 }
2141
2142 /*
2143 * set sockopt value from mbuf
2144 * - ONLY for legacy code
2145 * - mbuf is released by sockopt
2146 * - will not sleep
2147 */
2148 int
2149 sockopt_setmbuf(struct sockopt *sopt, struct mbuf *m)
2150 {
2151 size_t len;
2152 int error;
2153
2154 len = m_length(m);
2155
2156 if (sopt->sopt_size == 0) {
2157 error = sockopt_alloc(sopt, len, KM_NOSLEEP);
2158 if (error)
2159 return error;
2160 }
2161
2162 sopt->sopt_retsize = MIN(sopt->sopt_size, len);
2163 m_copydata(m, 0, sopt->sopt_retsize, sopt->sopt_data);
2164 m_freem(m);
2165
2166 return 0;
2167 }
2168
2169 /*
2170 * get sockopt value into mbuf
2171 * - ONLY for legacy code
2172 * - mbuf to be released by the caller
2173 * - will not sleep
2174 */
2175 struct mbuf *
2176 sockopt_getmbuf(const struct sockopt *sopt)
2177 {
2178 struct mbuf *m;
2179
2180 if (sopt->sopt_size > MCLBYTES)
2181 return NULL;
2182
2183 m = m_get(M_DONTWAIT, MT_SOOPTS);
2184 if (m == NULL)
2185 return NULL;
2186
2187 if (sopt->sopt_size > MLEN) {
2188 MCLGET(m, M_DONTWAIT);
2189 if ((m->m_flags & M_EXT) == 0) {
2190 m_free(m);
2191 return NULL;
2192 }
2193 }
2194
2195 memcpy(mtod(m, void *), sopt->sopt_data, sopt->sopt_size);
2196 m->m_len = sopt->sopt_size;
2197
2198 return m;
2199 }
2200
2201 void
2202 sohasoutofband(struct socket *so)
2203 {
2204
2205 fownsignal(so->so_pgid, SIGURG, POLL_PRI, POLLPRI|POLLRDBAND, so);
2206 selnotify(&so->so_rcv.sb_sel, POLLPRI | POLLRDBAND, NOTE_SUBMIT);
2207 }
2208
2209 static void
2210 filt_sordetach(struct knote *kn)
2211 {
2212 struct socket *so;
2213
2214 so = ((file_t *)kn->kn_obj)->f_socket;
2215 solock(so);
2216 SLIST_REMOVE(&so->so_rcv.sb_sel.sel_klist, kn, knote, kn_selnext);
2217 if (SLIST_EMPTY(&so->so_rcv.sb_sel.sel_klist))
2218 so->so_rcv.sb_flags &= ~SB_KNOTE;
2219 sounlock(so);
2220 }
2221
2222 /*ARGSUSED*/
2223 static int
2224 filt_soread(struct knote *kn, long hint)
2225 {
2226 struct socket *so;
2227 int rv;
2228
2229 so = ((file_t *)kn->kn_obj)->f_socket;
2230 if (hint != NOTE_SUBMIT)
2231 solock(so);
2232 kn->kn_data = so->so_rcv.sb_cc;
2233 if (so->so_state & SS_CANTRCVMORE) {
2234 kn->kn_flags |= EV_EOF;
2235 kn->kn_fflags = so->so_error;
2236 rv = 1;
2237 } else if (so->so_error || so->so_rerror)
2238 rv = 1;
2239 else if (kn->kn_sfflags & NOTE_LOWAT)
2240 rv = (kn->kn_data >= kn->kn_sdata);
2241 else
2242 rv = (kn->kn_data >= so->so_rcv.sb_lowat);
2243 if (hint != NOTE_SUBMIT)
2244 sounlock(so);
2245 return rv;
2246 }
2247
2248 static void
2249 filt_sowdetach(struct knote *kn)
2250 {
2251 struct socket *so;
2252
2253 so = ((file_t *)kn->kn_obj)->f_socket;
2254 solock(so);
2255 SLIST_REMOVE(&so->so_snd.sb_sel.sel_klist, kn, knote, kn_selnext);
2256 if (SLIST_EMPTY(&so->so_snd.sb_sel.sel_klist))
2257 so->so_snd.sb_flags &= ~SB_KNOTE;
2258 sounlock(so);
2259 }
2260
2261 /*ARGSUSED*/
2262 static int
2263 filt_sowrite(struct knote *kn, long hint)
2264 {
2265 struct socket *so;
2266 int rv;
2267
2268 so = ((file_t *)kn->kn_obj)->f_socket;
2269 if (hint != NOTE_SUBMIT)
2270 solock(so);
2271 kn->kn_data = sbspace(&so->so_snd);
2272 if (so->so_state & SS_CANTSENDMORE) {
2273 kn->kn_flags |= EV_EOF;
2274 kn->kn_fflags = so->so_error;
2275 rv = 1;
2276 } else if (so->so_error)
2277 rv = 1;
2278 else if (((so->so_state & SS_ISCONNECTED) == 0) &&
2279 (so->so_proto->pr_flags & PR_CONNREQUIRED))
2280 rv = 0;
2281 else if (kn->kn_sfflags & NOTE_LOWAT)
2282 rv = (kn->kn_data >= kn->kn_sdata);
2283 else
2284 rv = (kn->kn_data >= so->so_snd.sb_lowat);
2285 if (hint != NOTE_SUBMIT)
2286 sounlock(so);
2287 return rv;
2288 }
2289
2290 /*ARGSUSED*/
2291 static int
2292 filt_solisten(struct knote *kn, long hint)
2293 {
2294 struct socket *so;
2295 int rv;
2296
2297 so = ((file_t *)kn->kn_obj)->f_socket;
2298
2299 /*
2300 * Set kn_data to number of incoming connections, not
2301 * counting partial (incomplete) connections.
2302 */
2303 if (hint != NOTE_SUBMIT)
2304 solock(so);
2305 kn->kn_data = so->so_qlen;
2306 rv = (kn->kn_data > 0);
2307 if (hint != NOTE_SUBMIT)
2308 sounlock(so);
2309 return rv;
2310 }
2311
2312 static const struct filterops solisten_filtops = {
2313 .f_isfd = 1,
2314 .f_attach = NULL,
2315 .f_detach = filt_sordetach,
2316 .f_event = filt_solisten,
2317 };
2318
2319 static const struct filterops soread_filtops = {
2320 .f_isfd = 1,
2321 .f_attach = NULL,
2322 .f_detach = filt_sordetach,
2323 .f_event = filt_soread,
2324 };
2325
2326 static const struct filterops sowrite_filtops = {
2327 .f_isfd = 1,
2328 .f_attach = NULL,
2329 .f_detach = filt_sowdetach,
2330 .f_event = filt_sowrite,
2331 };
2332
2333 int
2334 soo_kqfilter(struct file *fp, struct knote *kn)
2335 {
2336 struct socket *so;
2337 struct sockbuf *sb;
2338
2339 so = ((file_t *)kn->kn_obj)->f_socket;
2340 solock(so);
2341 switch (kn->kn_filter) {
2342 case EVFILT_READ:
2343 if (so->so_options & SO_ACCEPTCONN)
2344 kn->kn_fop = &solisten_filtops;
2345 else
2346 kn->kn_fop = &soread_filtops;
2347 sb = &so->so_rcv;
2348 break;
2349 case EVFILT_WRITE:
2350 kn->kn_fop = &sowrite_filtops;
2351 sb = &so->so_snd;
2352 break;
2353 default:
2354 sounlock(so);
2355 return EINVAL;
2356 }
2357 SLIST_INSERT_HEAD(&sb->sb_sel.sel_klist, kn, kn_selnext);
2358 sb->sb_flags |= SB_KNOTE;
2359 sounlock(so);
2360 return 0;
2361 }
2362
2363 static int
2364 sodopoll(struct socket *so, int events)
2365 {
2366 int revents;
2367
2368 revents = 0;
2369
2370 if (events & (POLLIN | POLLRDNORM))
2371 if (soreadable(so))
2372 revents |= events & (POLLIN | POLLRDNORM);
2373
2374 if (events & (POLLOUT | POLLWRNORM))
2375 if (sowritable(so))
2376 revents |= events & (POLLOUT | POLLWRNORM);
2377
2378 if (events & (POLLPRI | POLLRDBAND))
2379 if (so->so_oobmark || (so->so_state & SS_RCVATMARK))
2380 revents |= events & (POLLPRI | POLLRDBAND);
2381
2382 return revents;
2383 }
2384
2385 int
2386 sopoll(struct socket *so, int events)
2387 {
2388 int revents = 0;
2389
2390 #ifndef DIAGNOSTIC
2391 /*
2392 * Do a quick, unlocked check in expectation that the socket
2393 * will be ready for I/O. Don't do this check if DIAGNOSTIC,
2394 * as the solocked() assertions will fail.
2395 */
2396 if ((revents = sodopoll(so, events)) != 0)
2397 return revents;
2398 #endif
2399
2400 solock(so);
2401 if ((revents = sodopoll(so, events)) == 0) {
2402 if (events & (POLLIN | POLLPRI | POLLRDNORM | POLLRDBAND)) {
2403 selrecord(curlwp, &so->so_rcv.sb_sel);
2404 so->so_rcv.sb_flags |= SB_NOTIFY;
2405 }
2406
2407 if (events & (POLLOUT | POLLWRNORM)) {
2408 selrecord(curlwp, &so->so_snd.sb_sel);
2409 so->so_snd.sb_flags |= SB_NOTIFY;
2410 }
2411 }
2412 sounlock(so);
2413
2414 return revents;
2415 }
2416
2417 struct mbuf **
2418 sbsavetimestamp(int opt, struct mbuf **mp)
2419 {
2420 struct timeval tv;
2421 int error;
2422
2423 microtime(&tv);
2424
2425 MODULE_HOOK_CALL(uipc_socket_50_sbts_hook, (opt, &mp), enosys(), error);
2426 if (error == 0)
2427 return mp;
2428
2429 if (opt & SO_TIMESTAMP) {
2430 *mp = sbcreatecontrol(&tv, sizeof(tv),
2431 SCM_TIMESTAMP, SOL_SOCKET);
2432 if (*mp)
2433 mp = &(*mp)->m_next;
2434 }
2435 return mp;
2436 }
2437
2438
2439 #include <sys/sysctl.h>
2440
2441 static int sysctl_kern_somaxkva(SYSCTLFN_PROTO);
2442 static int sysctl_kern_sbmax(SYSCTLFN_PROTO);
2443
2444 /*
2445 * sysctl helper routine for kern.somaxkva. ensures that the given
2446 * value is not too small.
2447 * (XXX should we maybe make sure it's not too large as well?)
2448 */
2449 static int
2450 sysctl_kern_somaxkva(SYSCTLFN_ARGS)
2451 {
2452 int error, new_somaxkva;
2453 struct sysctlnode node;
2454
2455 new_somaxkva = somaxkva;
2456 node = *rnode;
2457 node.sysctl_data = &new_somaxkva;
2458 error = sysctl_lookup(SYSCTLFN_CALL(&node));
2459 if (error || newp == NULL)
2460 return error;
2461
2462 if (new_somaxkva < (16 * 1024 * 1024)) /* sanity */
2463 return EINVAL;
2464
2465 mutex_enter(&so_pendfree_lock);
2466 somaxkva = new_somaxkva;
2467 cv_broadcast(&socurkva_cv);
2468 mutex_exit(&so_pendfree_lock);
2469
2470 return error;
2471 }
2472
2473 /*
2474 * sysctl helper routine for kern.sbmax. Basically just ensures that
2475 * any new value is not too small.
2476 */
2477 static int
2478 sysctl_kern_sbmax(SYSCTLFN_ARGS)
2479 {
2480 int error, new_sbmax;
2481 struct sysctlnode node;
2482
2483 new_sbmax = sb_max;
2484 node = *rnode;
2485 node.sysctl_data = &new_sbmax;
2486 error = sysctl_lookup(SYSCTLFN_CALL(&node));
2487 if (error || newp == NULL)
2488 return error;
2489
2490 KERNEL_LOCK(1, NULL);
2491 error = sb_max_set(new_sbmax);
2492 KERNEL_UNLOCK_ONE(NULL);
2493
2494 return error;
2495 }
2496
2497 /*
2498 * sysctl helper routine for kern.sooptions. Ensures that only allowed
2499 * options can be set.
2500 */
2501 static int
2502 sysctl_kern_sooptions(SYSCTLFN_ARGS)
2503 {
2504 int error, new_options;
2505 struct sysctlnode node;
2506
2507 new_options = sooptions;
2508 node = *rnode;
2509 node.sysctl_data = &new_options;
2510 error = sysctl_lookup(SYSCTLFN_CALL(&node));
2511 if (error || newp == NULL)
2512 return error;
2513
2514 if (new_options & ~SO_DEFOPTS)
2515 return EINVAL;
2516
2517 sooptions = new_options;
2518
2519 return 0;
2520 }
2521
2522 static void
2523 sysctl_kern_socket_setup(void)
2524 {
2525
2526 KASSERT(socket_sysctllog == NULL);
2527
2528 sysctl_createv(&socket_sysctllog, 0, NULL, NULL,
2529 CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
2530 CTLTYPE_INT, "somaxkva",
2531 SYSCTL_DESCR("Maximum amount of kernel memory to be "
2532 "used for socket buffers"),
2533 sysctl_kern_somaxkva, 0, NULL, 0,
2534 CTL_KERN, KERN_SOMAXKVA, CTL_EOL);
2535
2536 sysctl_createv(&socket_sysctllog, 0, NULL, NULL,
2537 CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
2538 CTLTYPE_INT, "sbmax",
2539 SYSCTL_DESCR("Maximum socket buffer size"),
2540 sysctl_kern_sbmax, 0, NULL, 0,
2541 CTL_KERN, KERN_SBMAX, CTL_EOL);
2542
2543 sysctl_createv(&socket_sysctllog, 0, NULL, NULL,
2544 CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
2545 CTLTYPE_INT, "sooptions",
2546 SYSCTL_DESCR("Default socket options"),
2547 sysctl_kern_sooptions, 0, NULL, 0,
2548 CTL_KERN, CTL_CREATE, CTL_EOL);
2549 }
2550