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