1/*-
2 * SPDX-License-Identifier: BSD-3-Clause
3 *
4 * Copyright (c) 1982, 1986, 1990, 1993
5 *	The Regents of the University of California.  All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
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.
18 *
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
29 * SUCH DAMAGE.
30 *
31 *	@(#)sys_socket.c	8.1 (Berkeley) 6/10/93
32 */
33
34#include <sys/cdefs.h>
35__FBSDID("$FreeBSD$");
36
37#include <sys/param.h>
38#include <sys/systm.h>
39#include <sys/aio.h>
40#include <sys/domain.h>
41#include <sys/file.h>
42#include <sys/filedesc.h>
43#include <sys/kernel.h>
44#include <sys/kthread.h>
45#include <sys/malloc.h>
46#include <sys/proc.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>
55#include <sys/stat.h>
56#include <sys/sysctl.h>
57#include <sys/sysproto.h>
58#include <sys/taskqueue.h>
59#include <sys/uio.h>
60#include <sys/ucred.h>
61#include <sys/un.h>
62#include <sys/unpcb.h>
63#include <sys/user.h>
64
65#include <net/if.h>
66#include <net/if_var.h>
67#include <net/route.h>
68#include <net/vnet.h>
69
70#include <netinet/in.h>
71#include <netinet/in_pcb.h>
72
73#include <security/mac/mac_framework.h>
74
75#include <vm/vm.h>
76#include <vm/pmap.h>
77#include <vm/vm_extern.h>
78#include <vm/vm_map.h>
79
80static SYSCTL_NODE(_kern_ipc, OID_AUTO, aio, CTLFLAG_RD, NULL,
81    "socket AIO stats");
82
83static int empty_results;
84SYSCTL_INT(_kern_ipc_aio, OID_AUTO, empty_results, CTLFLAG_RD, &empty_results,
85    0, "socket operation returned EAGAIN");
86
87static int empty_retries;
88SYSCTL_INT(_kern_ipc_aio, OID_AUTO, empty_retries, CTLFLAG_RD, &empty_retries,
89    0, "socket operation retries");
90
91static fo_rdwr_t soo_read;
92static fo_rdwr_t soo_write;
93static fo_ioctl_t soo_ioctl;
94static fo_poll_t soo_poll;
95extern fo_kqfilter_t soo_kqfilter;
96static fo_stat_t soo_stat;
97static fo_close_t soo_close;
98static fo_fill_kinfo_t soo_fill_kinfo;
99static fo_aio_queue_t soo_aio_queue;
100
101static void	soo_aio_cancel(struct kaiocb *job);
102
103struct fileops	socketops = {
104	.fo_read = soo_read,
105	.fo_write = soo_write,
106	.fo_truncate = invfo_truncate,
107	.fo_ioctl = soo_ioctl,
108	.fo_poll = soo_poll,
109	.fo_kqfilter = soo_kqfilter,
110	.fo_stat = soo_stat,
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
118};
119
120static int
121soo_read(struct file *fp, struct uio *uio, struct ucred *active_cred,
122    int flags, struct thread *td)
123{
124	struct socket *so = fp->f_data;
125	int error;
126
127#ifdef MAC
128	error = mac_socket_check_receive(active_cred, so);
129	if (error)
130		return (error);
131#endif
132	error = soreceive(so, 0, uio, 0, 0, 0);
133	return (error);
134}
135
136static int
137soo_write(struct file *fp, struct uio *uio, struct ucred *active_cred,
138    int flags, struct thread *td)
139{
140	struct socket *so = fp->f_data;
141	int error;
142
143#ifdef MAC
144	error = mac_socket_check_send(active_cred, so);
145	if (error)
146		return (error);
147#endif
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);
153	}
154	return (error);
155}
156
157static int
158soo_ioctl(struct file *fp, u_long cmd, void *data, struct ucred *active_cred,
159    struct thread *td)
160{
161	struct socket *so = fp->f_data;
162	int error = 0;
163
164	switch (cmd) {
165	case FIONBIO:
166		SOCK_LOCK(so);
167		if (*(int *)data)
168			so->so_state |= SS_NBIO;
169		else
170			so->so_state &= ~SS_NBIO;
171		SOCK_UNLOCK(so);
172		break;
173
174	case FIOASYNC:
175		if (*(int *)data) {
176			SOCK_LOCK(so);
177			so->so_state |= SS_ASYNC;
178			if (SOLISTENING(so)) {
179				so->sol_sbrcv_flags |= SB_ASYNC;
180				so->sol_sbsnd_flags |= SB_ASYNC;
181			} else {
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);
188			}
189			SOCK_UNLOCK(so);
190		} else {
191			SOCK_LOCK(so);
192			so->so_state &= ~SS_ASYNC;
193			if (SOLISTENING(so)) {
194				so->sol_sbrcv_flags &= ~SB_ASYNC;
195				so->sol_sbsnd_flags &= ~SB_ASYNC;
196			} else {
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);
203			}
204			SOCK_UNLOCK(so);
205		}
206		break;
207
208	case FIONREAD:
209		/* Unlocked read. */
210		if (SOLISTENING(so)) {
211			error = EINVAL;
212		} else {
213			*(int *)data = sbavail(&so->so_rcv);
214		}
215		break;
216
217	case FIONWRITE:
218		/* Unlocked read. */
219		if (SOLISTENING(so)) {
220			error = EINVAL;
221		} else {
222			*(int *)data = sbavail(&so->so_snd);
223		}
224		break;
225
226	case FIONSPACE:
227		/* Unlocked read. */
228		if (SOLISTENING(so)) {
229			error = EINVAL;
230		} else {
231			if ((so->so_snd.sb_hiwat < sbused(&so->so_snd)) ||
232			    (so->so_snd.sb_mbmax < so->so_snd.sb_mbcnt)) {
233				*(int *)data = 0;
234			} else {
235				*(int *)data = sbspace(&so->so_snd);
236			}
237		}
238		break;
239
240	case FIOSETOWN:
241		error = fsetown(*(int *)data, &so->so_sigio);
242		break;
243
244	case FIOGETOWN:
245		*(int *)data = fgetown(&so->so_sigio);
246		break;
247
248	case SIOCSPGRP:
249		error = fsetown(-(*(int *)data), &so->so_sigio);
250		break;
251
252	case SIOCGPGRP:
253		*(int *)data = -fgetown(&so->so_sigio);
254		break;
255
256	case SIOCATMARK:
257		/* Unlocked read. */
258		if (SOLISTENING(so)) {
259			error = EINVAL;
260		} else {
261			*(int *)data = (so->so_rcv.sb_state & SBS_RCVATMARK) != 0;
262		}
263		break;
264	default:
265		/*
266		 * Interface/routing/protocol specific ioctls: interface and
267		 * routing ioctls should have a different entry since a
268		 * socket is unnecessary.
269		 */
270		if (IOCGROUP(cmd) == 'i')
271			error = ifioctl(so, cmd, data, td);
272		else if (IOCGROUP(cmd) == 'r') {
273			CURVNET_SET(so->so_vnet);
274			error = rtioctl_fib(cmd, data, so->so_fibnum);
275			CURVNET_RESTORE();
276		} else {
277			CURVNET_SET(so->so_vnet);
278			error = ((*so->so_proto->pr_usrreqs->pru_control)
279			    (so, cmd, data, 0, td));
280			CURVNET_RESTORE();
281		}
282		break;
283	}
284	return (error);
285}
286
287static int
288soo_poll(struct file *fp, int events, struct ucred *active_cred,
289    struct thread *td)
290{
291	struct socket *so = fp->f_data;
292#ifdef MAC
293	int error;
294
295	error = mac_socket_check_poll(active_cred, so);
296	if (error)
297		return (error);
298#endif
299	return (sopoll(so, events, fp->f_cred, td));
300}
301
302static int
303soo_stat(struct file *fp, struct stat *ub, struct ucred *active_cred,
304    struct thread *td)
305{
306	struct socket *so = fp->f_data;
307	int error;
308
309	bzero((caddr_t)ub, sizeof (*ub));
310	ub->st_mode = S_IFSOCK;
311#ifdef MAC
312	error = mac_socket_check_stat(active_cred, so);
313	if (error)
314		return (error);
315#endif
316	SOCK_LOCK(so);
317	if (!SOLISTENING(so)) {
318		struct sockbuf *sb;
319
320		/*
321		 * If SBS_CANTRCVMORE is set, but there's still data left
322		 * in the receive buffer, the socket is still readable.
323		 */
324		sb = &so->so_rcv;
325		SOCKBUF_LOCK(sb);
326		if ((sb->sb_state & SBS_CANTRCVMORE) == 0 || sbavail(sb))
327			ub->st_mode |= S_IRUSR | S_IRGRP | S_IROTH;
328		ub->st_size = sbavail(sb) - sb->sb_ctl;
329		SOCKBUF_UNLOCK(sb);
330
331		sb = &so->so_snd;
332		SOCKBUF_LOCK(sb);
333		if ((sb->sb_state & SBS_CANTSENDMORE) == 0)
334			ub->st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
335		SOCKBUF_UNLOCK(sb);
336	}
337	ub->st_uid = so->so_cred->cr_uid;
338	ub->st_gid = so->so_cred->cr_gid;
339	error = so->so_proto->pr_usrreqs->pru_sense(so, ub);
340	SOCK_UNLOCK(so);
341	return (error);
342}
343
344/*
345 * API socket close on file pointer.  We call soclose() to close the socket
346 * (including initiating closing protocols).  soclose() will sorele() the
347 * file reference but the actual socket will not go away until the socket's
348 * ref count hits 0.
349 */
350static int
351soo_close(struct file *fp, struct thread *td)
352{
353	int error = 0;
354	struct socket *so;
355
356	so = fp->f_data;
357	fp->f_ops = &badfileops;
358	fp->f_data = NULL;
359
360	if (so)
361		error = soclose(so);
362	return (error);
363}
364
365static int
366soo_fill_kinfo(struct file *fp, struct kinfo_file *kif, struct filedesc *fdp)
367{
368	struct sockaddr *sa;
369	struct inpcb *inpcb;
370	struct unpcb *unpcb;
371	struct socket *so;
372	int error;
373
374	kif->kf_type = KF_TYPE_SOCKET;
375	so = fp->f_data;
376	CURVNET_SET(so->so_vnet);
377	kif->kf_un.kf_sock.kf_sock_domain0 =
378	    so->so_proto->pr_domain->dom_family;
379	kif->kf_un.kf_sock.kf_sock_type0 = so->so_type;
380	kif->kf_un.kf_sock.kf_sock_protocol0 = so->so_proto->pr_protocol;
381	kif->kf_un.kf_sock.kf_sock_pcb = (uintptr_t)so->so_pcb;
382	switch (kif->kf_un.kf_sock.kf_sock_domain0) {
383	case AF_INET:
384	case AF_INET6:
385		if (kif->kf_un.kf_sock.kf_sock_protocol0 == IPPROTO_TCP) {
386			if (so->so_pcb != NULL) {
387				inpcb = (struct inpcb *)(so->so_pcb);
388				kif->kf_un.kf_sock.kf_sock_inpcb =
389				    (uintptr_t)inpcb->inp_ppcb;
390				kif->kf_un.kf_sock.kf_sock_sendq =
391				    sbused(&so->so_snd);
392				kif->kf_un.kf_sock.kf_sock_recvq =
393				    sbused(&so->so_rcv);
394			}
395		}
396		break;
397	case AF_UNIX:
398		if (so->so_pcb != NULL) {
399			unpcb = (struct unpcb *)(so->so_pcb);
400			if (unpcb->unp_conn) {
401				kif->kf_un.kf_sock.kf_sock_unpconn =
402				    (uintptr_t)unpcb->unp_conn;
403				kif->kf_un.kf_sock.kf_sock_rcv_sb_state =
404				    so->so_rcv.sb_state;
405				kif->kf_un.kf_sock.kf_sock_snd_sb_state =
406				    so->so_snd.sb_state;
407				kif->kf_un.kf_sock.kf_sock_sendq =
408				    sbused(&so->so_snd);
409				kif->kf_un.kf_sock.kf_sock_recvq =
410				    sbused(&so->so_rcv);
411			}
412		}
413		break;
414	}
415	error = so->so_proto->pr_usrreqs->pru_sockaddr(so, &sa);
416	if (error == 0 &&
417	    sa->sa_len <= sizeof(kif->kf_un.kf_sock.kf_sa_local)) {
418		bcopy(sa, &kif->kf_un.kf_sock.kf_sa_local, sa->sa_len);
419		free(sa, M_SONAME);
420	}
421	error = so->so_proto->pr_usrreqs->pru_peeraddr(so, &sa);
422	if (error == 0 &&
423	    sa->sa_len <= sizeof(kif->kf_un.kf_sock.kf_sa_peer)) {
424		bcopy(sa, &kif->kf_un.kf_sock.kf_sa_peer, sa->sa_len);
425		free(sa, M_SONAME);
426	}
427	strncpy(kif->kf_path, so->so_proto->pr_domain->dom_name,
428	    sizeof(kif->kf_path));
429	CURVNET_RESTORE();
430	return (0);
431}
432
433/*
434 * Use the 'backend3' field in AIO jobs to store the amount of data
435 * completed by the AIO job so far.
436 */
437#define	aio_done	backend3
438
439static STAILQ_HEAD(, task) soaio_jobs;
440static struct mtx soaio_jobs_lock;
441static struct task soaio_kproc_task;
442static int soaio_starting, soaio_idle, soaio_queued;
443static struct unrhdr *soaio_kproc_unr;
444
445static int soaio_max_procs = MAX_AIO_PROCS;
446SYSCTL_INT(_kern_ipc_aio, OID_AUTO, max_procs, CTLFLAG_RW, &soaio_max_procs, 0,
447    "Maximum number of kernel processes to use for async socket IO");
448
449static int soaio_num_procs;
450SYSCTL_INT(_kern_ipc_aio, OID_AUTO, num_procs, CTLFLAG_RD, &soaio_num_procs, 0,
451    "Number of active kernel processes for async socket IO");
452
453static int soaio_target_procs = TARGET_AIO_PROCS;
454SYSCTL_INT(_kern_ipc_aio, OID_AUTO, target_procs, CTLFLAG_RD,
455    &soaio_target_procs, 0,
456    "Preferred number of ready kernel processes for async socket IO");
457
458static int soaio_lifetime;
459SYSCTL_INT(_kern_ipc_aio, OID_AUTO, lifetime, CTLFLAG_RW, &soaio_lifetime, 0,
460    "Maximum lifetime for idle aiod");
461
462static void
463soaio_kproc_loop(void *arg)
464{
465	struct proc *p;
466	struct vmspace *myvm;
467	struct task *task;
468	int error, id, pending;
469
470	id = (intptr_t)arg;
471
472	/*
473	 * Grab an extra reference on the daemon's vmspace so that it
474	 * doesn't get freed by jobs that switch to a different
475	 * vmspace.
476	 */
477	p = curproc;
478	myvm = vmspace_acquire_ref(p);
479
480	mtx_lock(&soaio_jobs_lock);
481	MPASS(soaio_starting > 0);
482	soaio_starting--;
483	for (;;) {
484		while (!STAILQ_EMPTY(&soaio_jobs)) {
485			task = STAILQ_FIRST(&soaio_jobs);
486			STAILQ_REMOVE_HEAD(&soaio_jobs, ta_link);
487			soaio_queued--;
488			pending = task->ta_pending;
489			task->ta_pending = 0;
490			mtx_unlock(&soaio_jobs_lock);
491
492			task->ta_func(task->ta_context, pending);
493
494			mtx_lock(&soaio_jobs_lock);
495		}
496		MPASS(soaio_queued == 0);
497
498		if (p->p_vmspace != myvm) {
499			mtx_unlock(&soaio_jobs_lock);
500			vmspace_switch_aio(myvm);
501			mtx_lock(&soaio_jobs_lock);
502			continue;
503		}
504
505		soaio_idle++;
506		error = mtx_sleep(&soaio_idle, &soaio_jobs_lock, 0, "-",
507		    soaio_lifetime);
508		soaio_idle--;
509		if (error == EWOULDBLOCK && STAILQ_EMPTY(&soaio_jobs) &&
510		    soaio_num_procs > soaio_target_procs)
511			break;
512	}
513	soaio_num_procs--;
514	mtx_unlock(&soaio_jobs_lock);
515	free_unr(soaio_kproc_unr, id);
516	kproc_exit(0);
517}
518
519static void
520soaio_kproc_create(void *context, int pending)
521{
522	struct proc *p;
523	int error, id;
524
525	mtx_lock(&soaio_jobs_lock);
526	for (;;) {
527		if (soaio_num_procs < soaio_target_procs) {
528			/* Must create */
529		} else if (soaio_num_procs >= soaio_max_procs) {
530			/*
531			 * Hit the limit on kernel processes, don't
532			 * create another one.
533			 */
534			break;
535		} else if (soaio_queued <= soaio_idle + soaio_starting) {
536			/*
537			 * No more AIO jobs waiting for a process to be
538			 * created, so stop.
539			 */
540			break;
541		}
542		soaio_starting++;
543		mtx_unlock(&soaio_jobs_lock);
544
545		id = alloc_unr(soaio_kproc_unr);
546		error = kproc_create(soaio_kproc_loop, (void *)(intptr_t)id,
547		    &p, 0, 0, "soaiod%d", id);
548		if (error != 0) {
549			free_unr(soaio_kproc_unr, id);
550			mtx_lock(&soaio_jobs_lock);
551			soaio_starting--;
552			break;
553		}
554
555		mtx_lock(&soaio_jobs_lock);
556		soaio_num_procs++;
557	}
558	mtx_unlock(&soaio_jobs_lock);
559}
560
561void
562soaio_enqueue(struct task *task)
563{
564
565	mtx_lock(&soaio_jobs_lock);
566	MPASS(task->ta_pending == 0);
567	task->ta_pending++;
568	STAILQ_INSERT_TAIL(&soaio_jobs, task, ta_link);
569	soaio_queued++;
570	if (soaio_queued <= soaio_idle)
571		wakeup_one(&soaio_idle);
572	else if (soaio_num_procs < soaio_max_procs)
573		taskqueue_enqueue(taskqueue_thread, &soaio_kproc_task);
574	mtx_unlock(&soaio_jobs_lock);
575}
576
577static void
578soaio_init(void)
579{
580
581	soaio_lifetime = AIOD_LIFETIME_DEFAULT;
582	STAILQ_INIT(&soaio_jobs);
583	mtx_init(&soaio_jobs_lock, "soaio jobs", NULL, MTX_DEF);
584	soaio_kproc_unr = new_unrhdr(1, INT_MAX, NULL);
585	TASK_INIT(&soaio_kproc_task, 0, soaio_kproc_create, NULL);
586	if (soaio_target_procs > 0)
587		taskqueue_enqueue(taskqueue_thread, &soaio_kproc_task);
588}
589SYSINIT(soaio, SI_SUB_VFS, SI_ORDER_ANY, soaio_init, NULL);
590
591static __inline int
592soaio_ready(struct socket *so, struct sockbuf *sb)
593{
594	return (sb == &so->so_rcv ? soreadable(so) : sowriteable(so));
595}
596
597static void
598soaio_process_job(struct socket *so, struct sockbuf *sb, struct kaiocb *job)
599{
600	struct ucred *td_savedcred;
601	struct thread *td;
602	struct file *fp;
603	struct uio uio;
604	struct iovec iov;
605	size_t cnt, done;
606	long ru_before;
607	int error, flags;
608
609	SOCKBUF_UNLOCK(sb);
610	aio_switch_vmspace(job);
611	td = curthread;
612	fp = job->fd_file;
613retry:
614	td_savedcred = td->td_ucred;
615	td->td_ucred = job->cred;
616
617	done = job->aio_done;
618	cnt = job->uaiocb.aio_nbytes - done;
619	iov.iov_base = (void *)((uintptr_t)job->uaiocb.aio_buf + done);
620	iov.iov_len = cnt;
621	uio.uio_iov = &iov;
622	uio.uio_iovcnt = 1;
623	uio.uio_offset = 0;
624	uio.uio_resid = cnt;
625	uio.uio_segflg = UIO_USERSPACE;
626	uio.uio_td = td;
627	flags = MSG_NBIO;
628
629	/*
630	 * For resource usage accounting, only count a completed request
631	 * as a single message to avoid counting multiple calls to
632	 * sosend/soreceive on a blocking socket.
633	 */
634
635	if (sb == &so->so_rcv) {
636		uio.uio_rw = UIO_READ;
637		ru_before = td->td_ru.ru_msgrcv;
638#ifdef MAC
639		error = mac_socket_check_receive(fp->f_cred, so);
640		if (error == 0)
641
642#endif
643			error = soreceive(so, NULL, &uio, NULL, NULL, &flags);
644		if (td->td_ru.ru_msgrcv != ru_before)
645			job->msgrcv = 1;
646	} else {
647		if (!TAILQ_EMPTY(&sb->sb_aiojobq))
648			flags |= MSG_MORETOCOME;
649		uio.uio_rw = UIO_WRITE;
650		ru_before = td->td_ru.ru_msgsnd;
651#ifdef MAC
652		error = mac_socket_check_send(fp->f_cred, so);
653		if (error == 0)
654#endif
655			error = sosend(so, NULL, &uio, NULL, NULL, flags, td);
656		if (td->td_ru.ru_msgsnd != ru_before)
657			job->msgsnd = 1;
658		if (error == EPIPE && (so->so_options & SO_NOSIGPIPE) == 0) {
659			PROC_LOCK(job->userproc);
660			kern_psignal(job->userproc, SIGPIPE);
661			PROC_UNLOCK(job->userproc);
662		}
663	}
664
665	done += cnt - uio.uio_resid;
666	job->aio_done = done;
667	td->td_ucred = td_savedcred;
668
669	if (error == EWOULDBLOCK) {
670		/*
671		 * The request was either partially completed or not
672		 * completed at all due to racing with a read() or
673		 * write() on the socket.  If the socket is
674		 * non-blocking, return with any partial completion.
675		 * If the socket is blocking or if no progress has
676		 * been made, requeue this request at the head of the
677		 * queue to try again when the socket is ready.
678		 */
679		MPASS(done != job->uaiocb.aio_nbytes);
680		SOCKBUF_LOCK(sb);
681		if (done == 0 || !(so->so_state & SS_NBIO)) {
682			empty_results++;
683			if (soaio_ready(so, sb)) {
684				empty_retries++;
685				SOCKBUF_UNLOCK(sb);
686				goto retry;
687			}
688
689			if (!aio_set_cancel_function(job, soo_aio_cancel)) {
690				SOCKBUF_UNLOCK(sb);
691				if (done != 0)
692					aio_complete(job, done, 0);
693				else
694					aio_cancel(job);
695				SOCKBUF_LOCK(sb);
696			} else {
697				TAILQ_INSERT_HEAD(&sb->sb_aiojobq, job, list);
698			}
699			return;
700		}
701		SOCKBUF_UNLOCK(sb);
702	}
703	if (done != 0 && (error == ERESTART || error == EINTR ||
704	    error == EWOULDBLOCK))
705		error = 0;
706	if (error)
707		aio_complete(job, -1, error);
708	else
709		aio_complete(job, done, 0);
710	SOCKBUF_LOCK(sb);
711}
712
713static void
714soaio_process_sb(struct socket *so, struct sockbuf *sb)
715{
716	struct kaiocb *job;
717
718	CURVNET_SET(so->so_vnet);
719	SOCKBUF_LOCK(sb);
720	while (!TAILQ_EMPTY(&sb->sb_aiojobq) && soaio_ready(so, sb)) {
721		job = TAILQ_FIRST(&sb->sb_aiojobq);
722		TAILQ_REMOVE(&sb->sb_aiojobq, job, list);
723		if (!aio_clear_cancel_function(job))
724			continue;
725
726		soaio_process_job(so, sb, job);
727	}
728
729	/*
730	 * If there are still pending requests, the socket must not be
731	 * ready so set SB_AIO to request a wakeup when the socket
732	 * becomes ready.
733	 */
734	if (!TAILQ_EMPTY(&sb->sb_aiojobq))
735		sb->sb_flags |= SB_AIO;
736	sb->sb_flags &= ~SB_AIO_RUNNING;
737	SOCKBUF_UNLOCK(sb);
738
739	SOCK_LOCK(so);
740	sorele(so);
741	CURVNET_RESTORE();
742}
743
744void
745soaio_rcv(void *context, int pending)
746{
747	struct socket *so;
748
749	so = context;
750	soaio_process_sb(so, &so->so_rcv);
751}
752
753void
754soaio_snd(void *context, int pending)
755{
756	struct socket *so;
757
758	so = context;
759	soaio_process_sb(so, &so->so_snd);
760}
761
762void
763sowakeup_aio(struct socket *so, struct sockbuf *sb)
764{
765
766	SOCKBUF_LOCK_ASSERT(sb);
767	sb->sb_flags &= ~SB_AIO;
768	if (sb->sb_flags & SB_AIO_RUNNING)
769		return;
770	sb->sb_flags |= SB_AIO_RUNNING;
771	soref(so);
772	soaio_enqueue(&sb->sb_aiotask);
773}
774
775static void
776soo_aio_cancel(struct kaiocb *job)
777{
778	struct socket *so;
779	struct sockbuf *sb;
780	long done;
781	int opcode;
782
783	so = job->fd_file->f_data;
784	opcode = job->uaiocb.aio_lio_opcode;
785	if (opcode == LIO_READ)
786		sb = &so->so_rcv;
787	else {
788		MPASS(opcode == LIO_WRITE);
789		sb = &so->so_snd;
790	}
791
792	SOCKBUF_LOCK(sb);
793	if (!aio_cancel_cleared(job))
794		TAILQ_REMOVE(&sb->sb_aiojobq, job, list);
795	if (TAILQ_EMPTY(&sb->sb_aiojobq))
796		sb->sb_flags &= ~SB_AIO;
797	SOCKBUF_UNLOCK(sb);
798
799	done = job->aio_done;
800	if (done != 0)
801		aio_complete(job, done, 0);
802	else
803		aio_cancel(job);
804}
805
806static int
807soo_aio_queue(struct file *fp, struct kaiocb *job)
808{
809	struct socket *so;
810	struct sockbuf *sb;
811	int error;
812
813	so = fp->f_data;
814	error = (*so->so_proto->pr_usrreqs->pru_aio_queue)(so, job);
815	if (error == 0)
816		return (0);
817
818	switch (job->uaiocb.aio_lio_opcode) {
819	case LIO_READ:
820		sb = &so->so_rcv;
821		break;
822	case LIO_WRITE:
823		sb = &so->so_snd;
824		break;
825	default:
826		return (EINVAL);
827	}
828
829	SOCKBUF_LOCK(sb);
830	if (!aio_set_cancel_function(job, soo_aio_cancel))
831		panic("new job was cancelled");
832	TAILQ_INSERT_TAIL(&sb->sb_aiojobq, job, list);
833	if (!(sb->sb_flags & SB_AIO_RUNNING)) {
834		if (soaio_ready(so, sb))
835			sowakeup_aio(so, sb);
836		else
837			sb->sb_flags |= SB_AIO;
838	}
839	SOCKBUF_UNLOCK(sb);
840	return (0);
841}
842