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