xref: /f-stack/freebsd/kern/sys_socket.c (revision 33d130f7)
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  * 4. 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 #ifndef FSTACK
97 static fo_fill_kinfo_t soo_fill_kinfo;
98 static fo_aio_queue_t soo_aio_queue;
99 
100 static void	soo_aio_cancel(struct kaiocb *job);
101 #endif
102 
103 struct 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 #ifndef FSTACK
116 	.fo_fill_kinfo = soo_fill_kinfo,
117 	.fo_aio_queue = soo_aio_queue,
118 #endif
119 	.fo_flags = DFLAG_PASSABLE
120 };
121 
122 static int
123 soo_read(struct file *fp, struct uio *uio, struct ucred *active_cred,
124     int flags, struct thread *td)
125 {
126 	struct socket *so = fp->f_data;
127 	int error;
128 
129 #ifdef MAC
130 	error = mac_socket_check_receive(active_cred, so);
131 	if (error)
132 		return (error);
133 #endif
134 	error = soreceive(so, 0, uio, 0, 0, 0);
135 	return (error);
136 }
137 
138 static int
139 soo_write(struct file *fp, struct uio *uio, struct ucred *active_cred,
140     int flags, struct thread *td)
141 {
142 	struct socket *so = fp->f_data;
143 	int error;
144 
145 #ifdef MAC
146 	error = mac_socket_check_send(active_cred, so);
147 	if (error)
148 		return (error);
149 #endif
150 	error = sosend(so, 0, uio, 0, 0, 0, uio->uio_td);
151 	if (error == EPIPE && (so->so_options & SO_NOSIGPIPE) == 0) {
152 		PROC_LOCK(uio->uio_td->td_proc);
153 		tdsignal(uio->uio_td, SIGPIPE);
154 		PROC_UNLOCK(uio->uio_td->td_proc);
155 	}
156 	return (error);
157 }
158 
159 static int
160 soo_ioctl(struct file *fp, u_long cmd, void *data, struct ucred *active_cred,
161     struct thread *td)
162 {
163 	struct socket *so = fp->f_data;
164 	int error = 0;
165 
166 	switch (cmd) {
167 	case FIONBIO:
168 		SOCK_LOCK(so);
169 		if (*(int *)data)
170 			so->so_state |= SS_NBIO;
171 		else
172 			so->so_state &= ~SS_NBIO;
173 		SOCK_UNLOCK(so);
174 		break;
175 
176 	case FIOASYNC:
177 		/*
178 		 * XXXRW: This code separately acquires SOCK_LOCK(so) and
179 		 * SOCKBUF_LOCK(&so->so_rcv) even though they are the same
180 		 * mutex to avoid introducing the assumption that they are
181 		 * the same.
182 		 */
183 		if (*(int *)data) {
184 			SOCK_LOCK(so);
185 			so->so_state |= SS_ASYNC;
186 			SOCK_UNLOCK(so);
187 			SOCKBUF_LOCK(&so->so_rcv);
188 			so->so_rcv.sb_flags |= SB_ASYNC;
189 			SOCKBUF_UNLOCK(&so->so_rcv);
190 			SOCKBUF_LOCK(&so->so_snd);
191 			so->so_snd.sb_flags |= SB_ASYNC;
192 			SOCKBUF_UNLOCK(&so->so_snd);
193 		} else {
194 			SOCK_LOCK(so);
195 			so->so_state &= ~SS_ASYNC;
196 			SOCK_UNLOCK(so);
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 		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 	struct sockbuf *sb;
289 #ifdef MAC
290 	int error;
291 #endif
292 
293 	bzero((caddr_t)ub, sizeof (*ub));
294 	ub->st_mode = S_IFSOCK;
295 #ifdef MAC
296 	error = mac_socket_check_stat(active_cred, so);
297 	if (error)
298 		return (error);
299 #endif
300 	/*
301 	 * If SBS_CANTRCVMORE is set, but there's still data left in the
302 	 * receive buffer, the socket is still readable.
303 	 */
304 	sb = &so->so_rcv;
305 	SOCKBUF_LOCK(sb);
306 	if ((sb->sb_state & SBS_CANTRCVMORE) == 0 || sbavail(sb))
307 		ub->st_mode |= S_IRUSR | S_IRGRP | S_IROTH;
308 	ub->st_size = sbavail(sb) - sb->sb_ctl;
309 	SOCKBUF_UNLOCK(sb);
310 
311 	sb = &so->so_snd;
312 	SOCKBUF_LOCK(sb);
313 	if ((sb->sb_state & SBS_CANTSENDMORE) == 0)
314 		ub->st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
315 	SOCKBUF_UNLOCK(sb);
316 	ub->st_uid = so->so_cred->cr_uid;
317 	ub->st_gid = so->so_cred->cr_gid;
318 	return (*so->so_proto->pr_usrreqs->pru_sense)(so, ub);
319 }
320 
321 /*
322  * API socket close on file pointer.  We call soclose() to close the socket
323  * (including initiating closing protocols).  soclose() will sorele() the
324  * file reference but the actual socket will not go away until the socket's
325  * ref count hits 0.
326  */
327 static int
328 soo_close(struct file *fp, struct thread *td)
329 {
330 	int error = 0;
331 	struct socket *so;
332 
333 	so = fp->f_data;
334 	fp->f_ops = &badfileops;
335 	fp->f_data = NULL;
336 
337 	if (so)
338 		error = soclose(so);
339 	return (error);
340 }
341 
342 #ifndef FSTACK
343 static int
344 soo_fill_kinfo(struct file *fp, struct kinfo_file *kif, struct filedesc *fdp)
345 {
346 	struct sockaddr *sa;
347 	struct inpcb *inpcb;
348 	struct unpcb *unpcb;
349 	struct socket *so;
350 	int error;
351 
352 	kif->kf_type = KF_TYPE_SOCKET;
353 	so = fp->f_data;
354 	kif->kf_sock_domain = so->so_proto->pr_domain->dom_family;
355 	kif->kf_sock_type = so->so_type;
356 	kif->kf_sock_protocol = so->so_proto->pr_protocol;
357 	kif->kf_un.kf_sock.kf_sock_pcb = (uintptr_t)so->so_pcb;
358 	switch (kif->kf_sock_domain) {
359 	case AF_INET:
360 	case AF_INET6:
361 		if (kif->kf_sock_protocol == IPPROTO_TCP) {
362 			if (so->so_pcb != NULL) {
363 				inpcb = (struct inpcb *)(so->so_pcb);
364 				kif->kf_un.kf_sock.kf_sock_inpcb =
365 				    (uintptr_t)inpcb->inp_ppcb;
366 			}
367 		}
368 		break;
369 	case AF_UNIX:
370 		if (so->so_pcb != NULL) {
371 			unpcb = (struct unpcb *)(so->so_pcb);
372 			if (unpcb->unp_conn) {
373 				kif->kf_un.kf_sock.kf_sock_unpconn =
374 				    (uintptr_t)unpcb->unp_conn;
375 				kif->kf_un.kf_sock.kf_sock_rcv_sb_state =
376 				    so->so_rcv.sb_state;
377 				kif->kf_un.kf_sock.kf_sock_snd_sb_state =
378 				    so->so_snd.sb_state;
379 			}
380 		}
381 		break;
382 	}
383 	error = so->so_proto->pr_usrreqs->pru_sockaddr(so, &sa);
384 	if (error == 0 && sa->sa_len <= sizeof(kif->kf_sa_local)) {
385 		bcopy(sa, &kif->kf_sa_local, sa->sa_len);
386 		free(sa, M_SONAME);
387 	}
388 	error = so->so_proto->pr_usrreqs->pru_peeraddr(so, &sa);
389 	if (error == 0 && sa->sa_len <= sizeof(kif->kf_sa_peer)) {
390 		bcopy(sa, &kif->kf_sa_peer, sa->sa_len);
391 		free(sa, M_SONAME);
392 	}
393 	strncpy(kif->kf_path, so->so_proto->pr_domain->dom_name,
394 	    sizeof(kif->kf_path));
395 	return (0);
396 }
397 
398 /*
399  * Use the 'backend3' field in AIO jobs to store the amount of data
400  * completed by the AIO job so far.
401  */
402 #define	aio_done	backend3
403 
404 static STAILQ_HEAD(, task) soaio_jobs;
405 static struct mtx soaio_jobs_lock;
406 static struct task soaio_kproc_task;
407 static int soaio_starting, soaio_idle, soaio_queued;
408 static struct unrhdr *soaio_kproc_unr;
409 
410 static int soaio_max_procs = MAX_AIO_PROCS;
411 SYSCTL_INT(_kern_ipc_aio, OID_AUTO, max_procs, CTLFLAG_RW, &soaio_max_procs, 0,
412     "Maximum number of kernel processes to use for async socket IO");
413 
414 static int soaio_num_procs;
415 SYSCTL_INT(_kern_ipc_aio, OID_AUTO, num_procs, CTLFLAG_RD, &soaio_num_procs, 0,
416     "Number of active kernel processes for async socket IO");
417 
418 static int soaio_target_procs = TARGET_AIO_PROCS;
419 SYSCTL_INT(_kern_ipc_aio, OID_AUTO, target_procs, CTLFLAG_RD,
420     &soaio_target_procs, 0,
421     "Preferred number of ready kernel processes for async socket IO");
422 
423 static int soaio_lifetime;
424 SYSCTL_INT(_kern_ipc_aio, OID_AUTO, lifetime, CTLFLAG_RW, &soaio_lifetime, 0,
425     "Maximum lifetime for idle aiod");
426 
427 static void
428 soaio_kproc_loop(void *arg)
429 {
430 	struct proc *p;
431 	struct vmspace *myvm;
432 	struct task *task;
433 	int error, id, pending;
434 
435 	id = (intptr_t)arg;
436 
437 	/*
438 	 * Grab an extra reference on the daemon's vmspace so that it
439 	 * doesn't get freed by jobs that switch to a different
440 	 * vmspace.
441 	 */
442 	p = curproc;
443 	myvm = vmspace_acquire_ref(p);
444 
445 	mtx_lock(&soaio_jobs_lock);
446 	MPASS(soaio_starting > 0);
447 	soaio_starting--;
448 	for (;;) {
449 		while (!STAILQ_EMPTY(&soaio_jobs)) {
450 			task = STAILQ_FIRST(&soaio_jobs);
451 			STAILQ_REMOVE_HEAD(&soaio_jobs, ta_link);
452 			soaio_queued--;
453 			pending = task->ta_pending;
454 			task->ta_pending = 0;
455 			mtx_unlock(&soaio_jobs_lock);
456 
457 			task->ta_func(task->ta_context, pending);
458 
459 			mtx_lock(&soaio_jobs_lock);
460 		}
461 		MPASS(soaio_queued == 0);
462 
463 		if (p->p_vmspace != myvm) {
464 			mtx_unlock(&soaio_jobs_lock);
465 			vmspace_switch_aio(myvm);
466 			mtx_lock(&soaio_jobs_lock);
467 			continue;
468 		}
469 
470 		soaio_idle++;
471 		error = mtx_sleep(&soaio_idle, &soaio_jobs_lock, 0, "-",
472 		    soaio_lifetime);
473 		soaio_idle--;
474 		if (error == EWOULDBLOCK && STAILQ_EMPTY(&soaio_jobs) &&
475 		    soaio_num_procs > soaio_target_procs)
476 			break;
477 	}
478 	soaio_num_procs--;
479 	mtx_unlock(&soaio_jobs_lock);
480 	free_unr(soaio_kproc_unr, id);
481 	kproc_exit(0);
482 }
483 
484 static void
485 soaio_kproc_create(void *context, int pending)
486 {
487 	struct proc *p;
488 	int error, id;
489 
490 	mtx_lock(&soaio_jobs_lock);
491 	for (;;) {
492 		if (soaio_num_procs < soaio_target_procs) {
493 			/* Must create */
494 		} else if (soaio_num_procs >= soaio_max_procs) {
495 			/*
496 			 * Hit the limit on kernel processes, don't
497 			 * create another one.
498 			 */
499 			break;
500 		} else if (soaio_queued <= soaio_idle + soaio_starting) {
501 			/*
502 			 * No more AIO jobs waiting for a process to be
503 			 * created, so stop.
504 			 */
505 			break;
506 		}
507 		soaio_starting++;
508 		mtx_unlock(&soaio_jobs_lock);
509 
510 		id = alloc_unr(soaio_kproc_unr);
511 		error = kproc_create(soaio_kproc_loop, (void *)(intptr_t)id,
512 		    &p, 0, 0, "soaiod%d", id);
513 		if (error != 0) {
514 			free_unr(soaio_kproc_unr, id);
515 			mtx_lock(&soaio_jobs_lock);
516 			soaio_starting--;
517 			break;
518 		}
519 
520 		mtx_lock(&soaio_jobs_lock);
521 		soaio_num_procs++;
522 	}
523 	mtx_unlock(&soaio_jobs_lock);
524 }
525 
526 void
527 soaio_enqueue(struct task *task)
528 {
529 
530 	mtx_lock(&soaio_jobs_lock);
531 	MPASS(task->ta_pending == 0);
532 	task->ta_pending++;
533 	STAILQ_INSERT_TAIL(&soaio_jobs, task, ta_link);
534 	soaio_queued++;
535 	if (soaio_queued <= soaio_idle)
536 		wakeup_one(&soaio_idle);
537 	else if (soaio_num_procs < soaio_max_procs)
538 		taskqueue_enqueue(taskqueue_thread, &soaio_kproc_task);
539 	mtx_unlock(&soaio_jobs_lock);
540 }
541 
542 static void
543 soaio_init(void)
544 {
545 
546 	soaio_lifetime = AIOD_LIFETIME_DEFAULT;
547 	STAILQ_INIT(&soaio_jobs);
548 	mtx_init(&soaio_jobs_lock, "soaio jobs", NULL, MTX_DEF);
549 	soaio_kproc_unr = new_unrhdr(1, INT_MAX, NULL);
550 	TASK_INIT(&soaio_kproc_task, 0, soaio_kproc_create, NULL);
551 	if (soaio_target_procs > 0)
552 		taskqueue_enqueue(taskqueue_thread, &soaio_kproc_task);
553 }
554 SYSINIT(soaio, SI_SUB_VFS, SI_ORDER_ANY, soaio_init, NULL);
555 
556 static __inline int
557 soaio_ready(struct socket *so, struct sockbuf *sb)
558 {
559 	return (sb == &so->so_rcv ? soreadable(so) : sowriteable(so));
560 }
561 
562 static void
563 soaio_process_job(struct socket *so, struct sockbuf *sb, struct kaiocb *job)
564 {
565 	struct ucred *td_savedcred;
566 	struct thread *td;
567 	struct file *fp;
568 	struct uio uio;
569 	struct iovec iov;
570 	size_t cnt, done;
571 	long ru_before;
572 	int error, flags;
573 
574 	SOCKBUF_UNLOCK(sb);
575 	aio_switch_vmspace(job);
576 	td = curthread;
577 	fp = job->fd_file;
578 retry:
579 	td_savedcred = td->td_ucred;
580 	td->td_ucred = job->cred;
581 
582 	done = job->aio_done;
583 	cnt = job->uaiocb.aio_nbytes - done;
584 	iov.iov_base = (void *)((uintptr_t)job->uaiocb.aio_buf + done);
585 	iov.iov_len = cnt;
586 	uio.uio_iov = &iov;
587 	uio.uio_iovcnt = 1;
588 	uio.uio_offset = 0;
589 	uio.uio_resid = cnt;
590 	uio.uio_segflg = UIO_USERSPACE;
591 	uio.uio_td = td;
592 	flags = MSG_NBIO;
593 
594 	/*
595 	 * For resource usage accounting, only count a completed request
596 	 * as a single message to avoid counting multiple calls to
597 	 * sosend/soreceive on a blocking socket.
598 	 */
599 
600 	if (sb == &so->so_rcv) {
601 		uio.uio_rw = UIO_READ;
602 		ru_before = td->td_ru.ru_msgrcv;
603 #ifdef MAC
604 		error = mac_socket_check_receive(fp->f_cred, so);
605 		if (error == 0)
606 
607 #endif
608 			error = soreceive(so, NULL, &uio, NULL, NULL, &flags);
609 		if (td->td_ru.ru_msgrcv != ru_before)
610 			job->msgrcv = 1;
611 	} else {
612 		uio.uio_rw = UIO_WRITE;
613 		ru_before = td->td_ru.ru_msgsnd;
614 #ifdef MAC
615 		error = mac_socket_check_send(fp->f_cred, so);
616 		if (error == 0)
617 #endif
618 			error = sosend(so, NULL, &uio, NULL, NULL, flags, td);
619 		if (td->td_ru.ru_msgsnd != ru_before)
620 			job->msgsnd = 1;
621 		if (error == EPIPE && (so->so_options & SO_NOSIGPIPE) == 0) {
622 			PROC_LOCK(job->userproc);
623 			kern_psignal(job->userproc, SIGPIPE);
624 			PROC_UNLOCK(job->userproc);
625 		}
626 	}
627 
628 	done += cnt - uio.uio_resid;
629 	job->aio_done = done;
630 	td->td_ucred = td_savedcred;
631 
632 	if (error == EWOULDBLOCK) {
633 		/*
634 		 * The request was either partially completed or not
635 		 * completed at all due to racing with a read() or
636 		 * write() on the socket.  If the socket is
637 		 * non-blocking, return with any partial completion.
638 		 * If the socket is blocking or if no progress has
639 		 * been made, requeue this request at the head of the
640 		 * queue to try again when the socket is ready.
641 		 */
642 		MPASS(done != job->uaiocb.aio_nbytes);
643 		SOCKBUF_LOCK(sb);
644 		if (done == 0 || !(so->so_state & SS_NBIO)) {
645 			empty_results++;
646 			if (soaio_ready(so, sb)) {
647 				empty_retries++;
648 				SOCKBUF_UNLOCK(sb);
649 				goto retry;
650 			}
651 
652 			if (!aio_set_cancel_function(job, soo_aio_cancel)) {
653 				SOCKBUF_UNLOCK(sb);
654 				if (done != 0)
655 					aio_complete(job, done, 0);
656 				else
657 					aio_cancel(job);
658 				SOCKBUF_LOCK(sb);
659 			} else {
660 				TAILQ_INSERT_HEAD(&sb->sb_aiojobq, job, list);
661 			}
662 			return;
663 		}
664 		SOCKBUF_UNLOCK(sb);
665 	}
666 	if (done != 0 && (error == ERESTART || error == EINTR ||
667 	    error == EWOULDBLOCK))
668 		error = 0;
669 	if (error)
670 		aio_complete(job, -1, error);
671 	else
672 		aio_complete(job, done, 0);
673 	SOCKBUF_LOCK(sb);
674 }
675 
676 static void
677 soaio_process_sb(struct socket *so, struct sockbuf *sb)
678 {
679 	struct kaiocb *job;
680 
681 	CURVNET_SET(so->so_vnet);
682 	SOCKBUF_LOCK(sb);
683 	while (!TAILQ_EMPTY(&sb->sb_aiojobq) && soaio_ready(so, sb)) {
684 		job = TAILQ_FIRST(&sb->sb_aiojobq);
685 		TAILQ_REMOVE(&sb->sb_aiojobq, job, list);
686 		if (!aio_clear_cancel_function(job))
687 			continue;
688 
689 		soaio_process_job(so, sb, job);
690 	}
691 
692 	/*
693 	 * If there are still pending requests, the socket must not be
694 	 * ready so set SB_AIO to request a wakeup when the socket
695 	 * becomes ready.
696 	 */
697 	if (!TAILQ_EMPTY(&sb->sb_aiojobq))
698 		sb->sb_flags |= SB_AIO;
699 	sb->sb_flags &= ~SB_AIO_RUNNING;
700 	SOCKBUF_UNLOCK(sb);
701 
702 	ACCEPT_LOCK();
703 	SOCK_LOCK(so);
704 	sorele(so);
705 	CURVNET_RESTORE();
706 }
707 
708 void
709 soaio_rcv(void *context, int pending)
710 {
711 	struct socket *so;
712 
713 	so = context;
714 	soaio_process_sb(so, &so->so_rcv);
715 }
716 
717 void
718 soaio_snd(void *context, int pending)
719 {
720 	struct socket *so;
721 
722 	so = context;
723 	soaio_process_sb(so, &so->so_snd);
724 }
725 
726 void
727 sowakeup_aio(struct socket *so, struct sockbuf *sb)
728 {
729 
730 	SOCKBUF_LOCK_ASSERT(sb);
731 	sb->sb_flags &= ~SB_AIO;
732 	if (sb->sb_flags & SB_AIO_RUNNING)
733 		return;
734 	sb->sb_flags |= SB_AIO_RUNNING;
735 	if (sb == &so->so_snd)
736 		SOCK_LOCK(so);
737 	soref(so);
738 	if (sb == &so->so_snd)
739 		SOCK_UNLOCK(so);
740 	soaio_enqueue(&sb->sb_aiotask);
741 }
742 
743 static void
744 soo_aio_cancel(struct kaiocb *job)
745 {
746 	struct socket *so;
747 	struct sockbuf *sb;
748 	long done;
749 	int opcode;
750 
751 	so = job->fd_file->f_data;
752 	opcode = job->uaiocb.aio_lio_opcode;
753 	if (opcode == LIO_READ)
754 		sb = &so->so_rcv;
755 	else {
756 		MPASS(opcode == LIO_WRITE);
757 		sb = &so->so_snd;
758 	}
759 
760 	SOCKBUF_LOCK(sb);
761 	if (!aio_cancel_cleared(job))
762 		TAILQ_REMOVE(&sb->sb_aiojobq, job, list);
763 	if (TAILQ_EMPTY(&sb->sb_aiojobq))
764 		sb->sb_flags &= ~SB_AIO;
765 	SOCKBUF_UNLOCK(sb);
766 
767 	done = job->aio_done;
768 	if (done != 0)
769 		aio_complete(job, done, 0);
770 	else
771 		aio_cancel(job);
772 }
773 
774 static int
775 soo_aio_queue(struct file *fp, struct kaiocb *job)
776 {
777 	struct socket *so;
778 	struct sockbuf *sb;
779 	int error;
780 
781 	so = fp->f_data;
782 	error = (*so->so_proto->pr_usrreqs->pru_aio_queue)(so, job);
783 	if (error == 0)
784 		return (0);
785 
786 	switch (job->uaiocb.aio_lio_opcode) {
787 	case LIO_READ:
788 		sb = &so->so_rcv;
789 		break;
790 	case LIO_WRITE:
791 		sb = &so->so_snd;
792 		break;
793 	default:
794 		return (EINVAL);
795 	}
796 
797 	SOCKBUF_LOCK(sb);
798 	if (!aio_set_cancel_function(job, soo_aio_cancel))
799 		panic("new job was cancelled");
800 	TAILQ_INSERT_TAIL(&sb->sb_aiojobq, job, list);
801 	if (!(sb->sb_flags & SB_AIO_RUNNING)) {
802 		if (soaio_ready(so, sb))
803 			sowakeup_aio(so, sb);
804 		else
805 			sb->sb_flags |= SB_AIO;
806 	}
807 	SOCKBUF_UNLOCK(sb);
808 	return (0);
809 }
810 #endif
811