xref: /freebsd-14-stable/sys/kern/sys_socket.c (revision 48155c983c4ba7158e738bd1d4b3144751bd1d86)
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 #include <sys/param.h>
36 #include <sys/systm.h>
37 #include <sys/aio.h>
38 #include <sys/domain.h>
39 #include <sys/file.h>
40 #include <sys/filedesc.h>
41 #include <sys/kernel.h>
42 #include <sys/kthread.h>
43 #include <sys/malloc.h>
44 #include <sys/proc.h>
45 #include <sys/protosw.h>
46 #include <sys/sigio.h>
47 #include <sys/signal.h>
48 #include <sys/signalvar.h>
49 #include <sys/socket.h>
50 #include <sys/socketvar.h>
51 #include <sys/filio.h>			/* XXX */
52 #include <sys/sockio.h>
53 #include <sys/stat.h>
54 #include <sys/sysctl.h>
55 #include <sys/sysproto.h>
56 #include <sys/taskqueue.h>
57 #include <sys/uio.h>
58 #include <sys/ucred.h>
59 #include <sys/un.h>
60 #include <sys/unpcb.h>
61 #include <sys/user.h>
62 
63 #include <net/if.h>
64 #include <net/if_var.h>
65 #include <net/route.h>
66 #include <net/vnet.h>
67 
68 #include <netinet/in.h>
69 #include <netinet/in_pcb.h>
70 
71 #include <security/mac/mac_framework.h>
72 
73 #include <vm/vm.h>
74 #include <vm/pmap.h>
75 #include <vm/vm_extern.h>
76 #include <vm/vm_map.h>
77 
78 static SYSCTL_NODE(_kern_ipc, OID_AUTO, aio, CTLFLAG_RD | CTLFLAG_MPSAFE, NULL,
79     "socket AIO stats");
80 
81 static int empty_results;
82 SYSCTL_INT(_kern_ipc_aio, OID_AUTO, empty_results, CTLFLAG_RD, &empty_results,
83     0, "socket operation returned EAGAIN");
84 
85 static int empty_retries;
86 SYSCTL_INT(_kern_ipc_aio, OID_AUTO, empty_retries, CTLFLAG_RD, &empty_retries,
87     0, "socket operation retries");
88 
89 static fo_rdwr_t soo_read;
90 static fo_rdwr_t soo_write;
91 static fo_ioctl_t soo_ioctl;
92 static fo_poll_t soo_poll;
93 extern fo_kqfilter_t soo_kqfilter;
94 static fo_stat_t soo_stat;
95 static fo_close_t soo_close;
96 static fo_chmod_t soo_chmod;
97 static fo_fill_kinfo_t soo_fill_kinfo;
98 static fo_aio_queue_t soo_aio_queue;
99 
100 static void	soo_aio_cancel(struct kaiocb *job);
101 
102 const struct fileops socketops = {
103 	.fo_read = soo_read,
104 	.fo_write = soo_write,
105 	.fo_truncate = invfo_truncate,
106 	.fo_ioctl = soo_ioctl,
107 	.fo_poll = soo_poll,
108 	.fo_kqfilter = soo_kqfilter,
109 	.fo_stat = soo_stat,
110 	.fo_close = soo_close,
111 	.fo_chmod = soo_chmod,
112 	.fo_chown = invfo_chown,
113 	.fo_sendfile = invfo_sendfile,
114 	.fo_fill_kinfo = soo_fill_kinfo,
115 	.fo_aio_queue = soo_aio_queue,
116 	.fo_cmp = file_kcmp_generic,
117 	.fo_flags = DFLAG_PASSABLE
118 };
119 
120 static int
soo_read(struct file * fp,struct uio * uio,struct ucred * active_cred,int flags,struct thread * td)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
soo_write(struct file * fp,struct uio * uio,struct ucred * active_cred,int flags,struct thread * td)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
soo_ioctl(struct file * fp,u_long cmd,void * data,struct ucred * active_cred,struct thread * td)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
soo_poll(struct file * fp,int events,struct ucred * active_cred,struct thread * td)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
soo_stat(struct file * fp,struct stat * ub,struct ucred * active_cred)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
soo_close(struct file * fp,struct thread * td)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
soo_chmod(struct file * fp,mode_t mode,struct ucred * cred,struct thread * td)361 soo_chmod(struct file *fp, mode_t mode, struct ucred *cred, struct thread *td)
362 {
363 	struct socket *so;
364 	int error;
365 
366 	so = fp->f_data;
367 	if (so->so_proto->pr_chmod != NULL)
368 		error = so->so_proto->pr_chmod(so, mode, cred, td);
369 	else
370 		error = EINVAL;
371 	return (error);
372 }
373 
374 static int
soo_fill_kinfo(struct file * fp,struct kinfo_file * kif,struct filedesc * fdp)375 soo_fill_kinfo(struct file *fp, struct kinfo_file *kif, struct filedesc *fdp)
376 {
377 	struct sockaddr *sa;
378 	struct inpcb *inpcb;
379 	struct unpcb *unpcb;
380 	struct socket *so;
381 	int error;
382 
383 	kif->kf_type = KF_TYPE_SOCKET;
384 	so = fp->f_data;
385 	CURVNET_SET(so->so_vnet);
386 	kif->kf_un.kf_sock.kf_sock_domain0 =
387 	    so->so_proto->pr_domain->dom_family;
388 	kif->kf_un.kf_sock.kf_sock_type0 = so->so_type;
389 	kif->kf_un.kf_sock.kf_sock_protocol0 = so->so_proto->pr_protocol;
390 	kif->kf_un.kf_sock.kf_sock_pcb = (uintptr_t)so->so_pcb;
391 	switch (kif->kf_un.kf_sock.kf_sock_domain0) {
392 	case AF_INET:
393 	case AF_INET6:
394 		if (so->so_pcb != NULL) {
395 			inpcb = (struct inpcb *)(so->so_pcb);
396 			kif->kf_un.kf_sock.kf_sock_inpcb =
397 			    (uintptr_t)inpcb->inp_ppcb;
398 		}
399 		kif->kf_un.kf_sock.kf_sock_rcv_sb_state =
400 		    so->so_rcv.sb_state;
401 		kif->kf_un.kf_sock.kf_sock_snd_sb_state =
402 		    so->so_snd.sb_state;
403 		kif->kf_un.kf_sock.kf_sock_sendq =
404 		    sbused(&so->so_snd);
405 		kif->kf_un.kf_sock.kf_sock_recvq =
406 		    sbused(&so->so_rcv);
407 		break;
408 	case AF_UNIX:
409 		if (so->so_pcb != NULL) {
410 			unpcb = (struct unpcb *)(so->so_pcb);
411 			if (unpcb->unp_conn) {
412 				kif->kf_un.kf_sock.kf_sock_unpconn =
413 				    (uintptr_t)unpcb->unp_conn;
414 				kif->kf_un.kf_sock.kf_sock_rcv_sb_state =
415 				    so->so_rcv.sb_state;
416 				kif->kf_un.kf_sock.kf_sock_snd_sb_state =
417 				    so->so_snd.sb_state;
418 				kif->kf_un.kf_sock.kf_sock_sendq =
419 				    sbused(&so->so_snd);
420 				kif->kf_un.kf_sock.kf_sock_recvq =
421 				    sbused(&so->so_rcv);
422 			}
423 		}
424 		break;
425 	}
426 	error = so->so_proto->pr_sockaddr(so, &sa);
427 	if (error == 0 &&
428 	    sa->sa_len <= sizeof(kif->kf_un.kf_sock.kf_sa_local)) {
429 		bcopy(sa, &kif->kf_un.kf_sock.kf_sa_local, sa->sa_len);
430 		free(sa, M_SONAME);
431 	}
432 	error = so->so_proto->pr_peeraddr(so, &sa);
433 	if (error == 0 &&
434 	    sa->sa_len <= sizeof(kif->kf_un.kf_sock.kf_sa_peer)) {
435 		bcopy(sa, &kif->kf_un.kf_sock.kf_sa_peer, sa->sa_len);
436 		free(sa, M_SONAME);
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;
814 	struct sockbuf *sb;
815 	sb_which which;
816 	int error;
817 
818 	so = fp->f_data;
819 	error = so->so_proto->pr_aio_queue(so, job);
820 	if (error == 0)
821 		return (0);
822 
823 	/* Lock through the socket, since this may be a listening socket. */
824 	switch (job->uaiocb.aio_lio_opcode & (LIO_WRITE | LIO_READ)) {
825 	case LIO_READ:
826 		SOCK_RECVBUF_LOCK(so);
827 		sb = &so->so_rcv;
828 		which = SO_RCV;
829 		break;
830 	case LIO_WRITE:
831 		SOCK_SENDBUF_LOCK(so);
832 		sb = &so->so_snd;
833 		which = SO_SND;
834 		break;
835 	default:
836 		return (EINVAL);
837 	}
838 
839 	if (SOLISTENING(so)) {
840 		SOCK_BUF_UNLOCK(so, which);
841 		return (EINVAL);
842 	}
843 
844 	if (!aio_set_cancel_function(job, soo_aio_cancel))
845 		panic("new job was cancelled");
846 	TAILQ_INSERT_TAIL(&sb->sb_aiojobq, job, list);
847 	if (!(sb->sb_flags & SB_AIO_RUNNING)) {
848 		if (soaio_ready(so, sb))
849 			sowakeup_aio(so, which);
850 		else
851 			sb->sb_flags |= SB_AIO;
852 	}
853 	SOCK_BUF_UNLOCK(so, which);
854 	return (0);
855 }
856