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