2 * SPDX-License-Identifier: BSD-3-Clause
4 * Copyright (c) 1982, 1986, 1990, 1993
5 * The Regents of the University of California. All rights reserved.
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 * 3. Neither the name of the University nor the names of its contributors
16 * may be used to endorse or promote products derived from this software
17 * without specific prior written permission.
19 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 * @(#)sys_socket.c 8.1 (Berkeley) 6/10/93
34 #include <sys/cdefs.h>
35 __FBSDID("$FreeBSD$");
37 #include <sys/param.h>
38 #include <sys/systm.h>
40 #include <sys/domain.h>
42 #include <sys/filedesc.h>
43 #include <sys/kernel.h>
44 #include <sys/kthread.h>
45 #include <sys/malloc.h>
47 #include <sys/protosw.h>
48 #include <sys/sigio.h>
49 #include <sys/signal.h>
50 #include <sys/signalvar.h>
51 #include <sys/socket.h>
52 #include <sys/socketvar.h>
53 #include <sys/filio.h> /* XXX */
54 #include <sys/sockio.h>
56 #include <sys/sysctl.h>
57 #include <sys/sysproto.h>
58 #include <sys/taskqueue.h>
60 #include <sys/ucred.h>
62 #include <sys/unpcb.h>
66 #include <net/if_var.h>
67 #include <net/route.h>
70 #include <netinet/in.h>
71 #include <netinet/in_pcb.h>
73 #include <security/mac/mac_framework.h>
77 #include <vm/vm_extern.h>
78 #include <vm/vm_map.h>
80 static SYSCTL_NODE(_kern_ipc, OID_AUTO, aio, CTLFLAG_RD | CTLFLAG_MPSAFE, NULL,
83 static int empty_results;
84 SYSCTL_INT(_kern_ipc_aio, OID_AUTO, empty_results, CTLFLAG_RD, &empty_results,
85 0, "socket operation returned EAGAIN");
87 static int empty_retries;
88 SYSCTL_INT(_kern_ipc_aio, OID_AUTO, empty_retries, CTLFLAG_RD, &empty_retries,
89 0, "socket operation retries");
91 static fo_rdwr_t soo_read;
92 static fo_rdwr_t soo_write;
93 static fo_ioctl_t soo_ioctl;
94 static fo_poll_t soo_poll;
95 extern fo_kqfilter_t soo_kqfilter;
96 static fo_stat_t soo_stat;
97 static fo_close_t soo_close;
98 static fo_fill_kinfo_t soo_fill_kinfo;
99 static fo_aio_queue_t soo_aio_queue;
101 static void soo_aio_cancel(struct kaiocb *job);
103 struct fileops socketops = {
105 .fo_write = soo_write,
106 .fo_truncate = invfo_truncate,
107 .fo_ioctl = soo_ioctl,
109 .fo_kqfilter = soo_kqfilter,
111 .fo_close = soo_close,
112 .fo_chmod = invfo_chmod,
113 .fo_chown = invfo_chown,
114 .fo_sendfile = invfo_sendfile,
115 .fo_fill_kinfo = soo_fill_kinfo,
116 .fo_aio_queue = soo_aio_queue,
117 .fo_flags = DFLAG_PASSABLE
121 soo_read(struct file *fp, struct uio *uio, struct ucred *active_cred,
122 int flags, struct thread *td)
124 struct socket *so = fp->f_data;
128 error = mac_socket_check_receive(active_cred, so);
132 error = soreceive(so, 0, uio, 0, 0, 0);
137 soo_write(struct file *fp, struct uio *uio, struct ucred *active_cred,
138 int flags, struct thread *td)
140 struct socket *so = fp->f_data;
144 error = mac_socket_check_send(active_cred, so);
148 error = sosend(so, 0, uio, 0, 0, 0, uio->uio_td);
149 if (error == EPIPE && (so->so_options & SO_NOSIGPIPE) == 0) {
150 PROC_LOCK(uio->uio_td->td_proc);
151 tdsignal(uio->uio_td, SIGPIPE);
152 PROC_UNLOCK(uio->uio_td->td_proc);
158 soo_ioctl(struct file *fp, u_long cmd, void *data, struct ucred *active_cred,
161 struct socket *so = fp->f_data;
168 so->so_state |= SS_NBIO;
170 so->so_state &= ~SS_NBIO;
177 so->so_state |= SS_ASYNC;
178 if (SOLISTENING(so)) {
179 so->sol_sbrcv_flags |= SB_ASYNC;
180 so->sol_sbsnd_flags |= SB_ASYNC;
182 SOCKBUF_LOCK(&so->so_rcv);
183 so->so_rcv.sb_flags |= SB_ASYNC;
184 SOCKBUF_UNLOCK(&so->so_rcv);
185 SOCKBUF_LOCK(&so->so_snd);
186 so->so_snd.sb_flags |= SB_ASYNC;
187 SOCKBUF_UNLOCK(&so->so_snd);
192 so->so_state &= ~SS_ASYNC;
193 if (SOLISTENING(so)) {
194 so->sol_sbrcv_flags &= ~SB_ASYNC;
195 so->sol_sbsnd_flags &= ~SB_ASYNC;
197 SOCKBUF_LOCK(&so->so_rcv);
198 so->so_rcv.sb_flags &= ~SB_ASYNC;
199 SOCKBUF_UNLOCK(&so->so_rcv);
200 SOCKBUF_LOCK(&so->so_snd);
201 so->so_snd.sb_flags &= ~SB_ASYNC;
202 SOCKBUF_UNLOCK(&so->so_snd);
210 *(int *)data = sbavail(&so->so_rcv);
215 *(int *)data = sbavail(&so->so_snd);
220 if ((so->so_snd.sb_hiwat < sbused(&so->so_snd)) ||
221 (so->so_snd.sb_mbmax < so->so_snd.sb_mbcnt))
224 *(int *)data = sbspace(&so->so_snd);
228 error = fsetown(*(int *)data, &so->so_sigio);
232 *(int *)data = fgetown(&so->so_sigio);
236 error = fsetown(-(*(int *)data), &so->so_sigio);
240 *(int *)data = -fgetown(&so->so_sigio);
245 *(int *)data = (so->so_rcv.sb_state & SBS_RCVATMARK) != 0;
249 * Interface/routing/protocol specific ioctls: interface and
250 * routing ioctls should have a different entry since a
251 * socket is unnecessary.
253 if (IOCGROUP(cmd) == 'i')
254 error = ifioctl(so, cmd, data, td);
255 else if (IOCGROUP(cmd) == 'r') {
256 CURVNET_SET(so->so_vnet);
257 error = rtioctl_fib(cmd, data, so->so_fibnum);
260 CURVNET_SET(so->so_vnet);
261 error = ((*so->so_proto->pr_usrreqs->pru_control)
262 (so, cmd, data, 0, td));
271 soo_poll(struct file *fp, int events, struct ucred *active_cred,
274 struct socket *so = fp->f_data;
278 error = mac_socket_check_poll(active_cred, so);
282 return (sopoll(so, events, fp->f_cred, td));
286 soo_stat(struct file *fp, struct stat *ub, struct ucred *active_cred,
289 struct socket *so = fp->f_data;
292 bzero((caddr_t)ub, sizeof (*ub));
293 ub->st_mode = S_IFSOCK;
295 error = mac_socket_check_stat(active_cred, so);
300 if (!SOLISTENING(so)) {
304 * If SBS_CANTRCVMORE is set, but there's still data left
305 * in the receive buffer, the socket is still readable.
309 if ((sb->sb_state & SBS_CANTRCVMORE) == 0 || sbavail(sb))
310 ub->st_mode |= S_IRUSR | S_IRGRP | S_IROTH;
311 ub->st_size = sbavail(sb) - sb->sb_ctl;
316 if ((sb->sb_state & SBS_CANTSENDMORE) == 0)
317 ub->st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
320 ub->st_uid = so->so_cred->cr_uid;
321 ub->st_gid = so->so_cred->cr_gid;
322 error = so->so_proto->pr_usrreqs->pru_sense(so, ub);
328 * API socket close on file pointer. We call soclose() to close the socket
329 * (including initiating closing protocols). soclose() will sorele() the
330 * file reference but the actual socket will not go away until the socket's
334 soo_close(struct file *fp, struct thread *td)
340 fp->f_ops = &badfileops;
349 soo_fill_kinfo(struct file *fp, struct kinfo_file *kif, struct filedesc *fdp)
357 kif->kf_type = KF_TYPE_SOCKET;
359 CURVNET_SET(so->so_vnet);
360 kif->kf_un.kf_sock.kf_sock_domain0 =
361 so->so_proto->pr_domain->dom_family;
362 kif->kf_un.kf_sock.kf_sock_type0 = so->so_type;
363 kif->kf_un.kf_sock.kf_sock_protocol0 = so->so_proto->pr_protocol;
364 kif->kf_un.kf_sock.kf_sock_pcb = (uintptr_t)so->so_pcb;
365 switch (kif->kf_un.kf_sock.kf_sock_domain0) {
368 if (kif->kf_un.kf_sock.kf_sock_protocol0 == IPPROTO_TCP) {
369 if (so->so_pcb != NULL) {
370 inpcb = (struct inpcb *)(so->so_pcb);
371 kif->kf_un.kf_sock.kf_sock_inpcb =
372 (uintptr_t)inpcb->inp_ppcb;
373 kif->kf_un.kf_sock.kf_sock_sendq =
375 kif->kf_un.kf_sock.kf_sock_recvq =
381 if (so->so_pcb != NULL) {
382 unpcb = (struct unpcb *)(so->so_pcb);
383 if (unpcb->unp_conn) {
384 kif->kf_un.kf_sock.kf_sock_unpconn =
385 (uintptr_t)unpcb->unp_conn;
386 kif->kf_un.kf_sock.kf_sock_rcv_sb_state =
388 kif->kf_un.kf_sock.kf_sock_snd_sb_state =
390 kif->kf_un.kf_sock.kf_sock_sendq =
392 kif->kf_un.kf_sock.kf_sock_recvq =
398 error = so->so_proto->pr_usrreqs->pru_sockaddr(so, &sa);
400 sa->sa_len <= sizeof(kif->kf_un.kf_sock.kf_sa_local)) {
401 bcopy(sa, &kif->kf_un.kf_sock.kf_sa_local, sa->sa_len);
404 error = so->so_proto->pr_usrreqs->pru_peeraddr(so, &sa);
406 sa->sa_len <= sizeof(kif->kf_un.kf_sock.kf_sa_peer)) {
407 bcopy(sa, &kif->kf_un.kf_sock.kf_sa_peer, sa->sa_len);
410 strncpy(kif->kf_path, so->so_proto->pr_domain->dom_name,
411 sizeof(kif->kf_path));
417 * Use the 'backend3' field in AIO jobs to store the amount of data
418 * completed by the AIO job so far.
420 #define aio_done backend3
422 static STAILQ_HEAD(, task) soaio_jobs;
423 static struct mtx soaio_jobs_lock;
424 static struct task soaio_kproc_task;
425 static int soaio_starting, soaio_idle, soaio_queued;
426 static struct unrhdr *soaio_kproc_unr;
428 static int soaio_max_procs = MAX_AIO_PROCS;
429 SYSCTL_INT(_kern_ipc_aio, OID_AUTO, max_procs, CTLFLAG_RW, &soaio_max_procs, 0,
430 "Maximum number of kernel processes to use for async socket IO");
432 static int soaio_num_procs;
433 SYSCTL_INT(_kern_ipc_aio, OID_AUTO, num_procs, CTLFLAG_RD, &soaio_num_procs, 0,
434 "Number of active kernel processes for async socket IO");
436 static int soaio_target_procs = TARGET_AIO_PROCS;
437 SYSCTL_INT(_kern_ipc_aio, OID_AUTO, target_procs, CTLFLAG_RD,
438 &soaio_target_procs, 0,
439 "Preferred number of ready kernel processes for async socket IO");
441 static int soaio_lifetime;
442 SYSCTL_INT(_kern_ipc_aio, OID_AUTO, lifetime, CTLFLAG_RW, &soaio_lifetime, 0,
443 "Maximum lifetime for idle aiod");
446 soaio_kproc_loop(void *arg)
449 struct vmspace *myvm;
451 int error, id, pending;
456 * Grab an extra reference on the daemon's vmspace so that it
457 * doesn't get freed by jobs that switch to a different
461 myvm = vmspace_acquire_ref(p);
463 mtx_lock(&soaio_jobs_lock);
464 MPASS(soaio_starting > 0);
467 while (!STAILQ_EMPTY(&soaio_jobs)) {
468 task = STAILQ_FIRST(&soaio_jobs);
469 STAILQ_REMOVE_HEAD(&soaio_jobs, ta_link);
471 pending = task->ta_pending;
472 task->ta_pending = 0;
473 mtx_unlock(&soaio_jobs_lock);
475 task->ta_func(task->ta_context, pending);
477 mtx_lock(&soaio_jobs_lock);
479 MPASS(soaio_queued == 0);
481 if (p->p_vmspace != myvm) {
482 mtx_unlock(&soaio_jobs_lock);
483 vmspace_switch_aio(myvm);
484 mtx_lock(&soaio_jobs_lock);
489 error = mtx_sleep(&soaio_idle, &soaio_jobs_lock, 0, "-",
492 if (error == EWOULDBLOCK && STAILQ_EMPTY(&soaio_jobs) &&
493 soaio_num_procs > soaio_target_procs)
497 mtx_unlock(&soaio_jobs_lock);
498 free_unr(soaio_kproc_unr, id);
503 soaio_kproc_create(void *context, int pending)
508 mtx_lock(&soaio_jobs_lock);
510 if (soaio_num_procs < soaio_target_procs) {
512 } else if (soaio_num_procs >= soaio_max_procs) {
514 * Hit the limit on kernel processes, don't
515 * create another one.
518 } else if (soaio_queued <= soaio_idle + soaio_starting) {
520 * No more AIO jobs waiting for a process to be
526 mtx_unlock(&soaio_jobs_lock);
528 id = alloc_unr(soaio_kproc_unr);
529 error = kproc_create(soaio_kproc_loop, (void *)(intptr_t)id,
530 &p, 0, 0, "soaiod%d", id);
532 free_unr(soaio_kproc_unr, id);
533 mtx_lock(&soaio_jobs_lock);
538 mtx_lock(&soaio_jobs_lock);
541 mtx_unlock(&soaio_jobs_lock);
545 soaio_enqueue(struct task *task)
548 mtx_lock(&soaio_jobs_lock);
549 MPASS(task->ta_pending == 0);
551 STAILQ_INSERT_TAIL(&soaio_jobs, task, ta_link);
553 if (soaio_queued <= soaio_idle)
554 wakeup_one(&soaio_idle);
555 else if (soaio_num_procs < soaio_max_procs)
556 taskqueue_enqueue(taskqueue_thread, &soaio_kproc_task);
557 mtx_unlock(&soaio_jobs_lock);
564 soaio_lifetime = AIOD_LIFETIME_DEFAULT;
565 STAILQ_INIT(&soaio_jobs);
566 mtx_init(&soaio_jobs_lock, "soaio jobs", NULL, MTX_DEF);
567 soaio_kproc_unr = new_unrhdr(1, INT_MAX, NULL);
568 TASK_INIT(&soaio_kproc_task, 0, soaio_kproc_create, NULL);
569 if (soaio_target_procs > 0)
570 taskqueue_enqueue(taskqueue_thread, &soaio_kproc_task);
572 SYSINIT(soaio, SI_SUB_VFS, SI_ORDER_ANY, soaio_init, NULL);
575 soaio_ready(struct socket *so, struct sockbuf *sb)
577 return (sb == &so->so_rcv ? soreadable(so) : sowriteable(so));
581 soaio_process_job(struct socket *so, struct sockbuf *sb, struct kaiocb *job)
583 struct ucred *td_savedcred;
593 aio_switch_vmspace(job);
597 td_savedcred = td->td_ucred;
598 td->td_ucred = job->cred;
600 done = job->aio_done;
601 cnt = job->uaiocb.aio_nbytes - done;
602 iov.iov_base = (void *)((uintptr_t)job->uaiocb.aio_buf + done);
608 uio.uio_segflg = UIO_USERSPACE;
613 * For resource usage accounting, only count a completed request
614 * as a single message to avoid counting multiple calls to
615 * sosend/soreceive on a blocking socket.
618 if (sb == &so->so_rcv) {
619 uio.uio_rw = UIO_READ;
620 ru_before = td->td_ru.ru_msgrcv;
622 error = mac_socket_check_receive(fp->f_cred, so);
626 error = soreceive(so, NULL, &uio, NULL, NULL, &flags);
627 if (td->td_ru.ru_msgrcv != ru_before)
630 if (!TAILQ_EMPTY(&sb->sb_aiojobq))
631 flags |= MSG_MORETOCOME;
632 uio.uio_rw = UIO_WRITE;
633 ru_before = td->td_ru.ru_msgsnd;
635 error = mac_socket_check_send(fp->f_cred, so);
638 error = sosend(so, NULL, &uio, NULL, NULL, flags, td);
639 if (td->td_ru.ru_msgsnd != ru_before)
641 if (error == EPIPE && (so->so_options & SO_NOSIGPIPE) == 0) {
642 PROC_LOCK(job->userproc);
643 kern_psignal(job->userproc, SIGPIPE);
644 PROC_UNLOCK(job->userproc);
648 done += cnt - uio.uio_resid;
649 job->aio_done = done;
650 td->td_ucred = td_savedcred;
652 if (error == EWOULDBLOCK) {
654 * The request was either partially completed or not
655 * completed at all due to racing with a read() or
656 * write() on the socket. If the socket is
657 * non-blocking, return with any partial completion.
658 * If the socket is blocking or if no progress has
659 * been made, requeue this request at the head of the
660 * queue to try again when the socket is ready.
662 MPASS(done != job->uaiocb.aio_nbytes);
664 if (done == 0 || !(so->so_state & SS_NBIO)) {
666 if (soaio_ready(so, sb)) {
672 if (!aio_set_cancel_function(job, soo_aio_cancel)) {
675 aio_complete(job, done, 0);
680 TAILQ_INSERT_HEAD(&sb->sb_aiojobq, job, list);
686 if (done != 0 && (error == ERESTART || error == EINTR ||
687 error == EWOULDBLOCK))
690 aio_complete(job, -1, error);
692 aio_complete(job, done, 0);
697 soaio_process_sb(struct socket *so, struct sockbuf *sb)
701 CURVNET_SET(so->so_vnet);
703 while (!TAILQ_EMPTY(&sb->sb_aiojobq) && soaio_ready(so, sb)) {
704 job = TAILQ_FIRST(&sb->sb_aiojobq);
705 TAILQ_REMOVE(&sb->sb_aiojobq, job, list);
706 if (!aio_clear_cancel_function(job))
709 soaio_process_job(so, sb, job);
713 * If there are still pending requests, the socket must not be
714 * ready so set SB_AIO to request a wakeup when the socket
717 if (!TAILQ_EMPTY(&sb->sb_aiojobq))
718 sb->sb_flags |= SB_AIO;
719 sb->sb_flags &= ~SB_AIO_RUNNING;
728 soaio_rcv(void *context, int pending)
733 soaio_process_sb(so, &so->so_rcv);
737 soaio_snd(void *context, int pending)
742 soaio_process_sb(so, &so->so_snd);
746 sowakeup_aio(struct socket *so, struct sockbuf *sb)
749 SOCKBUF_LOCK_ASSERT(sb);
750 sb->sb_flags &= ~SB_AIO;
751 if (sb->sb_flags & SB_AIO_RUNNING)
753 sb->sb_flags |= SB_AIO_RUNNING;
755 soaio_enqueue(&sb->sb_aiotask);
759 soo_aio_cancel(struct kaiocb *job)
766 so = job->fd_file->f_data;
767 opcode = job->uaiocb.aio_lio_opcode;
768 if (opcode == LIO_READ)
771 MPASS(opcode == LIO_WRITE);
776 if (!aio_cancel_cleared(job))
777 TAILQ_REMOVE(&sb->sb_aiojobq, job, list);
778 if (TAILQ_EMPTY(&sb->sb_aiojobq))
779 sb->sb_flags &= ~SB_AIO;
782 done = job->aio_done;
784 aio_complete(job, done, 0);
790 soo_aio_queue(struct file *fp, struct kaiocb *job)
797 error = (*so->so_proto->pr_usrreqs->pru_aio_queue)(so, job);
801 switch (job->uaiocb.aio_lio_opcode) {
813 if (!aio_set_cancel_function(job, soo_aio_cancel))
814 panic("new job was cancelled");
815 TAILQ_INSERT_TAIL(&sb->sb_aiojobq, job, list);
816 if (!(sb->sb_flags & SB_AIO_RUNNING)) {
817 if (soaio_ready(so, sb))
818 sowakeup_aio(so, sb);
820 sb->sb_flags |= SB_AIO;