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