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