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