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
32 #include <sys/param.h>
33 #include <sys/systm.h>
35 #include <sys/domain.h>
37 #include <sys/filedesc.h>
38 #include <sys/kernel.h>
39 #include <sys/kthread.h>
40 #include <sys/malloc.h>
42 #include <sys/protosw.h>
43 #include <sys/sigio.h>
44 #include <sys/signal.h>
45 #include <sys/signalvar.h>
46 #include <sys/socket.h>
47 #include <sys/socketvar.h>
48 #include <sys/filio.h> /* XXX */
49 #include <sys/sockio.h>
51 #include <sys/sysctl.h>
52 #include <sys/sysproto.h>
53 #include <sys/taskqueue.h>
55 #include <sys/ucred.h>
57 #include <sys/unpcb.h>
61 #include <net/if_var.h>
62 #include <net/route.h>
65 #include <netinet/in.h>
66 #include <netinet/in_pcb.h>
68 #include <security/mac/mac_framework.h>
72 #include <vm/vm_extern.h>
73 #include <vm/vm_map.h>
75 static SYSCTL_NODE(_kern_ipc, OID_AUTO, aio, CTLFLAG_RD | CTLFLAG_MPSAFE, NULL,
78 static int empty_results;
79 SYSCTL_INT(_kern_ipc_aio, OID_AUTO, empty_results, CTLFLAG_RD, &empty_results,
80 0, "socket operation returned EAGAIN");
82 static int empty_retries;
83 SYSCTL_INT(_kern_ipc_aio, OID_AUTO, empty_retries, CTLFLAG_RD, &empty_retries,
84 0, "socket operation retries");
86 static fo_rdwr_t soo_read;
87 static fo_rdwr_t soo_write;
88 static fo_ioctl_t soo_ioctl;
89 static fo_poll_t soo_poll;
90 extern fo_kqfilter_t soo_kqfilter;
91 static fo_stat_t soo_stat;
92 static fo_close_t soo_close;
93 static fo_fill_kinfo_t soo_fill_kinfo;
94 static fo_aio_queue_t soo_aio_queue;
96 static void soo_aio_cancel(struct kaiocb *job);
98 struct fileops socketops = {
100 .fo_write = soo_write,
101 .fo_truncate = invfo_truncate,
102 .fo_ioctl = soo_ioctl,
104 .fo_kqfilter = soo_kqfilter,
106 .fo_close = soo_close,
107 .fo_chmod = invfo_chmod,
108 .fo_chown = invfo_chown,
109 .fo_sendfile = invfo_sendfile,
110 .fo_fill_kinfo = soo_fill_kinfo,
111 .fo_aio_queue = soo_aio_queue,
112 .fo_flags = DFLAG_PASSABLE
116 soo_read(struct file *fp, struct uio *uio, struct ucred *active_cred,
117 int flags, struct thread *td)
119 struct socket *so = fp->f_data;
123 error = mac_socket_check_receive(active_cred, so);
127 error = soreceive(so, 0, uio, 0, 0, 0);
132 soo_write(struct file *fp, struct uio *uio, struct ucred *active_cred,
133 int flags, struct thread *td)
135 struct socket *so = fp->f_data;
139 error = mac_socket_check_send(active_cred, so);
143 error = sousrsend(so, NULL, uio, NULL, 0, NULL);
148 soo_ioctl(struct file *fp, u_long cmd, void *data, struct ucred *active_cred,
151 struct socket *so = fp->f_data;
158 so->so_state |= SS_NBIO;
160 so->so_state &= ~SS_NBIO;
167 so->so_state |= SS_ASYNC;
168 if (SOLISTENING(so)) {
169 so->sol_sbrcv_flags |= SB_ASYNC;
170 so->sol_sbsnd_flags |= SB_ASYNC;
172 SOCK_RECVBUF_LOCK(so);
173 so->so_rcv.sb_flags |= SB_ASYNC;
174 SOCK_RECVBUF_UNLOCK(so);
175 SOCK_SENDBUF_LOCK(so);
176 so->so_snd.sb_flags |= SB_ASYNC;
177 SOCK_SENDBUF_UNLOCK(so);
182 so->so_state &= ~SS_ASYNC;
183 if (SOLISTENING(so)) {
184 so->sol_sbrcv_flags &= ~SB_ASYNC;
185 so->sol_sbsnd_flags &= ~SB_ASYNC;
187 SOCK_RECVBUF_LOCK(so);
188 so->so_rcv.sb_flags &= ~SB_ASYNC;
189 SOCK_RECVBUF_UNLOCK(so);
190 SOCK_SENDBUF_LOCK(so);
191 so->so_snd.sb_flags &= ~SB_ASYNC;
192 SOCK_SENDBUF_UNLOCK(so);
199 SOCK_RECVBUF_LOCK(so);
200 if (SOLISTENING(so)) {
203 *(int *)data = sbavail(&so->so_rcv) - so->so_rcv.sb_ctl;
205 SOCK_RECVBUF_UNLOCK(so);
210 if (SOLISTENING(so)) {
213 *(int *)data = sbavail(&so->so_snd);
219 if (SOLISTENING(so)) {
222 if ((so->so_snd.sb_hiwat < sbused(&so->so_snd)) ||
223 (so->so_snd.sb_mbmax < so->so_snd.sb_mbcnt)) {
226 *(int *)data = sbspace(&so->so_snd);
232 error = fsetown(*(int *)data, &so->so_sigio);
236 *(int *)data = fgetown(&so->so_sigio);
240 error = fsetown(-(*(int *)data), &so->so_sigio);
244 *(int *)data = -fgetown(&so->so_sigio);
249 if (SOLISTENING(so)) {
252 *(int *)data = (so->so_rcv.sb_state & SBS_RCVATMARK) != 0;
257 * Interface/routing/protocol specific ioctls: interface and
258 * routing ioctls should have a different entry since a
259 * socket is unnecessary.
261 if (IOCGROUP(cmd) == 'i')
262 error = ifioctl(so, cmd, data, td);
263 else if (IOCGROUP(cmd) == 'r') {
264 CURVNET_SET(so->so_vnet);
265 error = rtioctl_fib(cmd, data, so->so_fibnum);
268 CURVNET_SET(so->so_vnet);
269 error = so->so_proto->pr_control(so, cmd, data, 0, td);
278 soo_poll(struct file *fp, int events, struct ucred *active_cred,
281 struct socket *so = fp->f_data;
285 error = mac_socket_check_poll(active_cred, so);
289 return (sopoll(so, events, fp->f_cred, td));
293 soo_stat(struct file *fp, struct stat *ub, struct ucred *active_cred)
295 struct socket *so = fp->f_data;
298 bzero((caddr_t)ub, sizeof (*ub));
299 ub->st_mode = S_IFSOCK;
301 error = mac_socket_check_stat(active_cred, so);
306 if (!SOLISTENING(so)) {
310 * If SBS_CANTRCVMORE is set, but there's still data left
311 * in the receive buffer, the socket is still readable.
314 SOCK_RECVBUF_LOCK(so);
315 if ((sb->sb_state & SBS_CANTRCVMORE) == 0 || sbavail(sb))
316 ub->st_mode |= S_IRUSR | S_IRGRP | S_IROTH;
317 ub->st_size = sbavail(sb) - sb->sb_ctl;
318 SOCK_RECVBUF_UNLOCK(so);
321 SOCK_SENDBUF_LOCK(so);
322 if ((sb->sb_state & SBS_CANTSENDMORE) == 0)
323 ub->st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
324 SOCK_SENDBUF_UNLOCK(so);
326 ub->st_uid = so->so_cred->cr_uid;
327 ub->st_gid = so->so_cred->cr_gid;
328 if (so->so_proto->pr_sense)
329 error = so->so_proto->pr_sense(so, ub);
335 * API socket close on file pointer. We call soclose() to close the socket
336 * (including initiating closing protocols). soclose() will sorele() the
337 * file reference but the actual socket will not go away until the socket's
341 soo_close(struct file *fp, struct thread *td)
347 fp->f_ops = &badfileops;
356 soo_fill_kinfo(struct file *fp, struct kinfo_file *kif, struct filedesc *fdp)
358 struct sockaddr_storage ss = { .ss_len = sizeof(ss) };
364 kif->kf_type = KF_TYPE_SOCKET;
366 CURVNET_SET(so->so_vnet);
367 kif->kf_un.kf_sock.kf_sock_domain0 =
368 so->so_proto->pr_domain->dom_family;
369 kif->kf_un.kf_sock.kf_sock_type0 = so->so_type;
370 kif->kf_un.kf_sock.kf_sock_protocol0 = so->so_proto->pr_protocol;
371 kif->kf_un.kf_sock.kf_sock_pcb = (uintptr_t)so->so_pcb;
372 switch (kif->kf_un.kf_sock.kf_sock_domain0) {
375 if (so->so_pcb != NULL) {
376 inpcb = (struct inpcb *)(so->so_pcb);
377 kif->kf_un.kf_sock.kf_sock_inpcb =
378 (uintptr_t)inpcb->inp_ppcb;
380 kif->kf_un.kf_sock.kf_sock_rcv_sb_state =
382 kif->kf_un.kf_sock.kf_sock_snd_sb_state =
384 kif->kf_un.kf_sock.kf_sock_sendq =
386 kif->kf_un.kf_sock.kf_sock_recvq =
390 if (so->so_pcb != NULL) {
391 unpcb = (struct unpcb *)(so->so_pcb);
392 if (unpcb->unp_conn) {
393 kif->kf_un.kf_sock.kf_sock_unpconn =
394 (uintptr_t)unpcb->unp_conn;
395 kif->kf_un.kf_sock.kf_sock_rcv_sb_state =
397 kif->kf_un.kf_sock.kf_sock_snd_sb_state =
399 kif->kf_un.kf_sock.kf_sock_sendq =
401 kif->kf_un.kf_sock.kf_sock_recvq =
407 error = sosockaddr(so, (struct sockaddr *)&ss);
409 ss.ss_len <= sizeof(kif->kf_un.kf_sock.kf_sa_local)) {
410 bcopy(&ss, &kif->kf_un.kf_sock.kf_sa_local, ss.ss_len);
412 ss.ss_len = sizeof(ss);
413 error = sopeeraddr(so, (struct sockaddr *)&ss);
415 ss.ss_len <= sizeof(kif->kf_un.kf_sock.kf_sa_peer)) {
416 bcopy(&ss, &kif->kf_un.kf_sock.kf_sa_peer, ss.ss_len);
418 strncpy(kif->kf_path, so->so_proto->pr_domain->dom_name,
419 sizeof(kif->kf_path));
425 * Use the 'backend3' field in AIO jobs to store the amount of data
426 * completed by the AIO job so far.
428 #define aio_done backend3
430 static STAILQ_HEAD(, task) soaio_jobs;
431 static struct mtx soaio_jobs_lock;
432 static struct task soaio_kproc_task;
433 static int soaio_starting, soaio_idle, soaio_queued;
434 static struct unrhdr *soaio_kproc_unr;
436 static int soaio_max_procs = MAX_AIO_PROCS;
437 SYSCTL_INT(_kern_ipc_aio, OID_AUTO, max_procs, CTLFLAG_RW, &soaio_max_procs, 0,
438 "Maximum number of kernel processes to use for async socket IO");
440 static int soaio_num_procs;
441 SYSCTL_INT(_kern_ipc_aio, OID_AUTO, num_procs, CTLFLAG_RD, &soaio_num_procs, 0,
442 "Number of active kernel processes for async socket IO");
444 static int soaio_target_procs = TARGET_AIO_PROCS;
445 SYSCTL_INT(_kern_ipc_aio, OID_AUTO, target_procs, CTLFLAG_RD,
446 &soaio_target_procs, 0,
447 "Preferred number of ready kernel processes for async socket IO");
449 static int soaio_lifetime;
450 SYSCTL_INT(_kern_ipc_aio, OID_AUTO, lifetime, CTLFLAG_RW, &soaio_lifetime, 0,
451 "Maximum lifetime for idle aiod");
454 soaio_kproc_loop(void *arg)
457 struct vmspace *myvm;
459 int error, id, pending;
464 * Grab an extra reference on the daemon's vmspace so that it
465 * doesn't get freed by jobs that switch to a different
469 myvm = vmspace_acquire_ref(p);
471 mtx_lock(&soaio_jobs_lock);
472 MPASS(soaio_starting > 0);
475 while (!STAILQ_EMPTY(&soaio_jobs)) {
476 task = STAILQ_FIRST(&soaio_jobs);
477 STAILQ_REMOVE_HEAD(&soaio_jobs, ta_link);
479 pending = task->ta_pending;
480 task->ta_pending = 0;
481 mtx_unlock(&soaio_jobs_lock);
483 task->ta_func(task->ta_context, pending);
485 mtx_lock(&soaio_jobs_lock);
487 MPASS(soaio_queued == 0);
489 if (p->p_vmspace != myvm) {
490 mtx_unlock(&soaio_jobs_lock);
491 vmspace_switch_aio(myvm);
492 mtx_lock(&soaio_jobs_lock);
497 error = mtx_sleep(&soaio_idle, &soaio_jobs_lock, 0, "-",
500 if (error == EWOULDBLOCK && STAILQ_EMPTY(&soaio_jobs) &&
501 soaio_num_procs > soaio_target_procs)
505 mtx_unlock(&soaio_jobs_lock);
506 free_unr(soaio_kproc_unr, id);
511 soaio_kproc_create(void *context, int pending)
516 mtx_lock(&soaio_jobs_lock);
518 if (soaio_num_procs < soaio_target_procs) {
520 } else if (soaio_num_procs >= soaio_max_procs) {
522 * Hit the limit on kernel processes, don't
523 * create another one.
526 } else if (soaio_queued <= soaio_idle + soaio_starting) {
528 * No more AIO jobs waiting for a process to be
534 mtx_unlock(&soaio_jobs_lock);
536 id = alloc_unr(soaio_kproc_unr);
537 error = kproc_create(soaio_kproc_loop, (void *)(intptr_t)id,
538 &p, 0, 0, "soaiod%d", id);
540 free_unr(soaio_kproc_unr, id);
541 mtx_lock(&soaio_jobs_lock);
546 mtx_lock(&soaio_jobs_lock);
549 mtx_unlock(&soaio_jobs_lock);
553 soaio_enqueue(struct task *task)
556 mtx_lock(&soaio_jobs_lock);
557 MPASS(task->ta_pending == 0);
559 STAILQ_INSERT_TAIL(&soaio_jobs, task, ta_link);
561 if (soaio_queued <= soaio_idle)
562 wakeup_one(&soaio_idle);
563 else if (soaio_num_procs < soaio_max_procs)
564 taskqueue_enqueue(taskqueue_thread, &soaio_kproc_task);
565 mtx_unlock(&soaio_jobs_lock);
572 soaio_lifetime = AIOD_LIFETIME_DEFAULT;
573 STAILQ_INIT(&soaio_jobs);
574 mtx_init(&soaio_jobs_lock, "soaio jobs", NULL, MTX_DEF);
575 soaio_kproc_unr = new_unrhdr(1, INT_MAX, NULL);
576 TASK_INIT(&soaio_kproc_task, 0, soaio_kproc_create, NULL);
578 SYSINIT(soaio, SI_SUB_VFS, SI_ORDER_ANY, soaio_init, NULL);
581 soaio_ready(struct socket *so, struct sockbuf *sb)
583 return (sb == &so->so_rcv ? soreadable(so) : sowriteable(so));
587 soaio_process_job(struct socket *so, sb_which which, struct kaiocb *job)
589 struct ucred *td_savedcred;
591 struct sockbuf *sb = sobuf(so, which);
593 struct file *fp = job->fd_file;
595 size_t cnt, done, job_total_nbytes __diagused;
599 SOCK_BUF_UNLOCK(so, which);
600 aio_switch_vmspace(job);
603 td_savedcred = td->td_ucred;
604 td->td_ucred = job->cred;
606 job_total_nbytes = job->uiop->uio_resid + job->aio_done;
607 done = job->aio_done;
608 cnt = job->uiop->uio_resid;
609 job->uiop->uio_offset = 0;
610 job->uiop->uio_td = td;
614 * For resource usage accounting, only count a completed request
615 * as a single message to avoid counting multiple calls to
616 * sosend/soreceive on a blocking socket.
619 if (sb == &so->so_rcv) {
620 ru_before = td->td_ru.ru_msgrcv;
622 error = mac_socket_check_receive(fp->f_cred, so);
626 error = soreceive(so, NULL, job->uiop, NULL, NULL,
628 if (td->td_ru.ru_msgrcv != ru_before)
631 if (!TAILQ_EMPTY(&sb->sb_aiojobq))
632 flags |= MSG_MORETOCOME;
633 ru_before = td->td_ru.ru_msgsnd;
635 error = mac_socket_check_send(fp->f_cred, so);
638 error = sousrsend(so, NULL, job->uiop, NULL, flags,
640 if (td->td_ru.ru_msgsnd != ru_before)
644 done += cnt - job->uiop->uio_resid;
645 job->aio_done = done;
646 td->td_ucred = td_savedcred;
648 if (error == EWOULDBLOCK) {
650 * The request was either partially completed or not
651 * completed at all due to racing with a read() or
652 * write() on the socket. If the socket is
653 * non-blocking, return with any partial completion.
654 * If the socket is blocking or if no progress has
655 * been made, requeue this request at the head of the
656 * queue to try again when the socket is ready.
658 MPASS(done != job_total_nbytes);
659 SOCK_BUF_LOCK(so, which);
660 if (done == 0 || !(so->so_state & SS_NBIO)) {
662 if (soaio_ready(so, sb)) {
664 SOCK_BUF_UNLOCK(so, which);
668 if (!aio_set_cancel_function(job, soo_aio_cancel)) {
669 SOCK_BUF_UNLOCK(so, which);
671 aio_complete(job, done, 0);
674 SOCK_BUF_LOCK(so, which);
676 TAILQ_INSERT_HEAD(&sb->sb_aiojobq, job, list);
680 SOCK_BUF_UNLOCK(so, which);
682 if (done != 0 && (error == ERESTART || error == EINTR ||
683 error == EWOULDBLOCK))
686 aio_complete(job, -1, error);
688 aio_complete(job, done, 0);
689 SOCK_BUF_LOCK(so, which);
693 soaio_process_sb(struct socket *so, sb_which which)
696 struct sockbuf *sb = sobuf(so, which);
698 CURVNET_SET(so->so_vnet);
699 SOCK_BUF_LOCK(so, which);
700 while (!TAILQ_EMPTY(&sb->sb_aiojobq) && soaio_ready(so, sb)) {
701 job = TAILQ_FIRST(&sb->sb_aiojobq);
702 TAILQ_REMOVE(&sb->sb_aiojobq, job, list);
703 if (!aio_clear_cancel_function(job))
706 soaio_process_job(so, which, job);
710 * If there are still pending requests, the socket must not be
711 * ready so set SB_AIO to request a wakeup when the socket
714 if (!TAILQ_EMPTY(&sb->sb_aiojobq))
715 sb->sb_flags |= SB_AIO;
716 sb->sb_flags &= ~SB_AIO_RUNNING;
717 SOCK_BUF_UNLOCK(so, which);
724 soaio_rcv(void *context, int pending)
729 soaio_process_sb(so, SO_RCV);
733 soaio_snd(void *context, int pending)
738 soaio_process_sb(so, SO_SND);
742 sowakeup_aio(struct socket *so, sb_which which)
744 struct sockbuf *sb = sobuf(so, which);
746 SOCK_BUF_LOCK_ASSERT(so, which);
748 sb->sb_flags &= ~SB_AIO;
749 if (sb->sb_flags & SB_AIO_RUNNING)
751 sb->sb_flags |= SB_AIO_RUNNING;
753 soaio_enqueue(&sb->sb_aiotask);
757 soo_aio_cancel(struct kaiocb *job)
765 so = job->fd_file->f_data;
766 opcode = job->uaiocb.aio_lio_opcode;
767 if (opcode & LIO_READ) {
771 MPASS(opcode & LIO_WRITE);
776 SOCK_BUF_LOCK(so, which);
777 if (!aio_cancel_cleared(job))
778 TAILQ_REMOVE(&sb->sb_aiojobq, job, list);
779 if (TAILQ_EMPTY(&sb->sb_aiojobq))
780 sb->sb_flags &= ~SB_AIO;
781 SOCK_BUF_UNLOCK(so, which);
783 done = job->aio_done;
785 aio_complete(job, done, 0);
791 soo_aio_queue(struct file *fp, struct kaiocb *job)
799 error = so->so_proto->pr_aio_queue(so, job);
803 /* Lock through the socket, since this may be a listening socket. */
804 switch (job->uaiocb.aio_lio_opcode & (LIO_WRITE | LIO_READ)) {
806 SOCK_RECVBUF_LOCK(so);
811 SOCK_SENDBUF_LOCK(so);
819 if (SOLISTENING(so)) {
820 SOCK_BUF_UNLOCK(so, which);
824 if (!aio_set_cancel_function(job, soo_aio_cancel))
825 panic("new job was cancelled");
826 TAILQ_INSERT_TAIL(&sb->sb_aiojobq, job, list);
827 if (!(sb->sb_flags & SB_AIO_RUNNING)) {
828 if (soaio_ready(so, sb))
829 sowakeup_aio(so, which);
831 sb->sb_flags |= SB_AIO;
833 SOCK_BUF_UNLOCK(so, which);