xref: /freebsd/sys/kern/sys_socket.c (revision bfd03046d18776ea70785ca1ef36dfc60822de3b)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1982, 1986, 1990, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of the University nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  */
31 
32 #include <sys/param.h>
33 #include <sys/systm.h>
34 #include <sys/aio.h>
35 #include <sys/domain.h>
36 #include <sys/file.h>
37 #include <sys/filedesc.h>
38 #include <sys/kernel.h>
39 #include <sys/kthread.h>
40 #include <sys/malloc.h>
41 #include <sys/proc.h>
42 #include <sys/protosw.h>
43 #include <sys/sigio.h>
44 #include <sys/signal.h>
45 #include <sys/signalvar.h>
46 #include <sys/socket.h>
47 #include <sys/socketvar.h>
48 #include <sys/filio.h>			/* XXX */
49 #include <sys/sockio.h>
50 #include <sys/stat.h>
51 #include <sys/sysctl.h>
52 #include <sys/sysproto.h>
53 #include <sys/taskqueue.h>
54 #include <sys/uio.h>
55 #include <sys/ucred.h>
56 #include <sys/un.h>
57 #include <sys/unpcb.h>
58 #include <sys/user.h>
59 
60 #include <net/if.h>
61 #include <net/if_var.h>
62 #include <net/route.h>
63 #include <net/vnet.h>
64 
65 #include <netinet/in.h>
66 #include <netinet/in_pcb.h>
67 
68 #include <security/mac/mac_framework.h>
69 
70 #include <vm/vm.h>
71 #include <vm/pmap.h>
72 #include <vm/vm_extern.h>
73 #include <vm/vm_map.h>
74 
75 static SYSCTL_NODE(_kern_ipc, OID_AUTO, aio, CTLFLAG_RD | CTLFLAG_MPSAFE, NULL,
76     "socket AIO stats");
77 
78 static int empty_results;
79 SYSCTL_INT(_kern_ipc_aio, OID_AUTO, empty_results, CTLFLAG_RD, &empty_results,
80     0, "socket operation returned EAGAIN");
81 
82 static int empty_retries;
83 SYSCTL_INT(_kern_ipc_aio, OID_AUTO, empty_retries, CTLFLAG_RD, &empty_retries,
84     0, "socket operation retries");
85 
86 static fo_rdwr_t soo_read;
87 static fo_rdwr_t soo_write;
88 static fo_ioctl_t soo_ioctl;
89 static fo_poll_t soo_poll;
90 extern fo_kqfilter_t soo_kqfilter;
91 static fo_stat_t soo_stat;
92 static fo_close_t soo_close;
93 static fo_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 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 (sopoll(so, events, fp->f_cred, td));
292 }
293 
294 static int
soo_stat(struct file * fp,struct stat * ub,struct ucred * active_cred)295 soo_stat(struct file *fp, struct stat *ub, struct ucred *active_cred)
296 {
297 	struct socket *so = fp->f_data;
298 	int error = 0;
299 
300 	bzero((caddr_t)ub, sizeof (*ub));
301 	ub->st_mode = S_IFSOCK;
302 #ifdef MAC
303 	error = mac_socket_check_stat(active_cred, so);
304 	if (error)
305 		return (error);
306 #endif
307 	SOCK_LOCK(so);
308 	if (!SOLISTENING(so)) {
309 		struct sockbuf *sb;
310 
311 		/*
312 		 * If SBS_CANTRCVMORE is set, but there's still data left
313 		 * in the receive buffer, the socket is still readable.
314 		 */
315 		sb = &so->so_rcv;
316 		SOCK_RECVBUF_LOCK(so);
317 		if ((sb->sb_state & SBS_CANTRCVMORE) == 0 || sbavail(sb))
318 			ub->st_mode |= S_IRUSR | S_IRGRP | S_IROTH;
319 		ub->st_size = sbavail(sb) - sb->sb_ctl;
320 		SOCK_RECVBUF_UNLOCK(so);
321 
322 		sb = &so->so_snd;
323 		SOCK_SENDBUF_LOCK(so);
324 		if ((sb->sb_state & SBS_CANTSENDMORE) == 0)
325 			ub->st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
326 		SOCK_SENDBUF_UNLOCK(so);
327 	}
328 	ub->st_uid = so->so_cred->cr_uid;
329 	ub->st_gid = so->so_cred->cr_gid;
330 	if (so->so_proto->pr_sense)
331 		error = so->so_proto->pr_sense(so, ub);
332 	SOCK_UNLOCK(so);
333 	return (error);
334 }
335 
336 /*
337  * API socket close on file pointer.  We call soclose() to close the socket
338  * (including initiating closing protocols).  soclose() will sorele() the
339  * file reference but the actual socket will not go away until the socket's
340  * ref count hits 0.
341  */
342 static int
soo_close(struct file * fp,struct thread * td)343 soo_close(struct file *fp, struct thread *td)
344 {
345 	int error = 0;
346 	struct socket *so;
347 
348 	so = fp->f_data;
349 	fp->f_ops = &badfileops;
350 	fp->f_data = NULL;
351 
352 	if (so)
353 		error = soclose(so);
354 	return (error);
355 }
356 
357 static int
soo_chmod(struct file * fp,mode_t mode,struct ucred * cred,struct thread * td)358 soo_chmod(struct file *fp, mode_t mode, struct ucred *cred, struct thread *td)
359 {
360 	struct socket *so;
361 	int error;
362 
363 	so = fp->f_data;
364 	if (so->so_proto->pr_chmod != NULL)
365 		error = so->so_proto->pr_chmod(so, mode, cred, td);
366 	else
367 		error = EINVAL;
368 	return (error);
369 }
370 
371 static int
soo_fill_kinfo(struct file * fp,struct kinfo_file * kif,struct filedesc * fdp)372 soo_fill_kinfo(struct file *fp, struct kinfo_file *kif, struct filedesc *fdp)
373 {
374 	struct sockaddr_storage ss = { .ss_len = sizeof(ss) };
375 	struct unpcb *unpcb;
376 	struct socket *so;
377 	int error;
378 
379 	kif->kf_type = KF_TYPE_SOCKET;
380 	so = fp->f_data;
381 	CURVNET_SET(so->so_vnet);
382 	kif->kf_un.kf_sock.kf_sock_domain0 =
383 	    so->so_proto->pr_domain->dom_family;
384 	kif->kf_un.kf_sock.kf_sock_type0 = so->so_type;
385 	kif->kf_un.kf_sock.kf_sock_protocol0 = so->so_proto->pr_protocol;
386 	kif->kf_un.kf_sock.kf_sock_pcb = (uintptr_t)so->so_pcb;
387 	switch (kif->kf_un.kf_sock.kf_sock_domain0) {
388 	case AF_INET:
389 	case AF_INET6:
390 		/* XXX: kf_sock_inpcb is obsolete.  It may be removed. */
391 		kif->kf_un.kf_sock.kf_sock_inpcb = (uintptr_t)so->so_pcb;
392 		kif->kf_un.kf_sock.kf_sock_rcv_sb_state =
393 		    so->so_rcv.sb_state;
394 		kif->kf_un.kf_sock.kf_sock_snd_sb_state =
395 		    so->so_snd.sb_state;
396 		kif->kf_un.kf_sock.kf_sock_sendq =
397 		    sbused(&so->so_snd);
398 		kif->kf_un.kf_sock.kf_sock_recvq =
399 		    sbused(&so->so_rcv);
400 		break;
401 	case AF_UNIX:
402 		if (so->so_pcb != NULL) {
403 			unpcb = (struct unpcb *)(so->so_pcb);
404 			if (unpcb->unp_conn) {
405 				kif->kf_un.kf_sock.kf_sock_unpconn =
406 				    (uintptr_t)unpcb->unp_conn;
407 				kif->kf_un.kf_sock.kf_sock_rcv_sb_state =
408 				    so->so_rcv.sb_state;
409 				kif->kf_un.kf_sock.kf_sock_snd_sb_state =
410 				    so->so_snd.sb_state;
411 				kif->kf_un.kf_sock.kf_sock_sendq =
412 				    sbused(&so->so_snd);
413 				kif->kf_un.kf_sock.kf_sock_recvq =
414 				    sbused(&so->so_rcv);
415 			}
416 		}
417 		break;
418 	}
419 	error = sosockaddr(so, (struct sockaddr *)&ss);
420 	if (error == 0 &&
421 	    ss.ss_len <= sizeof(kif->kf_un.kf_sock.kf_sa_local)) {
422 		bcopy(&ss, &kif->kf_un.kf_sock.kf_sa_local, ss.ss_len);
423 	}
424 	ss.ss_len = sizeof(ss);
425 	error = sopeeraddr(so, (struct sockaddr *)&ss);
426 	if (error == 0 &&
427 	    ss.ss_len <= sizeof(kif->kf_un.kf_sock.kf_sa_peer)) {
428 		bcopy(&ss, &kif->kf_un.kf_sock.kf_sa_peer, ss.ss_len);
429 	}
430 	strncpy(kif->kf_path, so->so_proto->pr_domain->dom_name,
431 	    sizeof(kif->kf_path));
432 	CURVNET_RESTORE();
433 	return (0);
434 }
435 
436 /*
437  * Use the 'backend3' field in AIO jobs to store the amount of data
438  * completed by the AIO job so far.
439  */
440 #define	aio_done	backend3
441 
442 static STAILQ_HEAD(, task) soaio_jobs;
443 static struct mtx soaio_jobs_lock;
444 static struct task soaio_kproc_task;
445 static int soaio_starting, soaio_idle, soaio_queued;
446 static struct unrhdr *soaio_kproc_unr;
447 
448 static int soaio_max_procs = MAX_AIO_PROCS;
449 SYSCTL_INT(_kern_ipc_aio, OID_AUTO, max_procs, CTLFLAG_RW, &soaio_max_procs, 0,
450     "Maximum number of kernel processes to use for async socket IO");
451 
452 static int soaio_num_procs;
453 SYSCTL_INT(_kern_ipc_aio, OID_AUTO, num_procs, CTLFLAG_RD, &soaio_num_procs, 0,
454     "Number of active kernel processes for async socket IO");
455 
456 static int soaio_target_procs = TARGET_AIO_PROCS;
457 SYSCTL_INT(_kern_ipc_aio, OID_AUTO, target_procs, CTLFLAG_RD,
458     &soaio_target_procs, 0,
459     "Preferred number of ready kernel processes for async socket IO");
460 
461 static int soaio_lifetime;
462 SYSCTL_INT(_kern_ipc_aio, OID_AUTO, lifetime, CTLFLAG_RW, &soaio_lifetime, 0,
463     "Maximum lifetime for idle aiod");
464 
465 static void
soaio_kproc_loop(void * arg)466 soaio_kproc_loop(void *arg)
467 {
468 	struct proc *p;
469 	struct vmspace *myvm;
470 	struct task *task;
471 	int error, id, pending;
472 
473 	id = (intptr_t)arg;
474 
475 	/*
476 	 * Grab an extra reference on the daemon's vmspace so that it
477 	 * doesn't get freed by jobs that switch to a different
478 	 * vmspace.
479 	 */
480 	p = curproc;
481 	myvm = vmspace_acquire_ref(p);
482 
483 	mtx_lock(&soaio_jobs_lock);
484 	MPASS(soaio_starting > 0);
485 	soaio_starting--;
486 	for (;;) {
487 		while (!STAILQ_EMPTY(&soaio_jobs)) {
488 			task = STAILQ_FIRST(&soaio_jobs);
489 			STAILQ_REMOVE_HEAD(&soaio_jobs, ta_link);
490 			soaio_queued--;
491 			pending = task->ta_pending;
492 			task->ta_pending = 0;
493 			mtx_unlock(&soaio_jobs_lock);
494 
495 			task->ta_func(task->ta_context, pending);
496 
497 			mtx_lock(&soaio_jobs_lock);
498 		}
499 		MPASS(soaio_queued == 0);
500 
501 		if (p->p_vmspace != myvm) {
502 			mtx_unlock(&soaio_jobs_lock);
503 			vmspace_switch_aio(myvm);
504 			mtx_lock(&soaio_jobs_lock);
505 			continue;
506 		}
507 
508 		soaio_idle++;
509 		error = mtx_sleep(&soaio_idle, &soaio_jobs_lock, 0, "-",
510 		    soaio_lifetime);
511 		soaio_idle--;
512 		if (error == EWOULDBLOCK && STAILQ_EMPTY(&soaio_jobs) &&
513 		    soaio_num_procs > soaio_target_procs)
514 			break;
515 	}
516 	soaio_num_procs--;
517 	mtx_unlock(&soaio_jobs_lock);
518 	free_unr(soaio_kproc_unr, id);
519 	kproc_exit(0);
520 }
521 
522 static void
soaio_kproc_create(void * context,int pending)523 soaio_kproc_create(void *context, int pending)
524 {
525 	struct proc *p;
526 	int error, id;
527 
528 	mtx_lock(&soaio_jobs_lock);
529 	for (;;) {
530 		if (soaio_num_procs < soaio_target_procs) {
531 			/* Must create */
532 		} else if (soaio_num_procs >= soaio_max_procs) {
533 			/*
534 			 * Hit the limit on kernel processes, don't
535 			 * create another one.
536 			 */
537 			break;
538 		} else if (soaio_queued <= soaio_idle + soaio_starting) {
539 			/*
540 			 * No more AIO jobs waiting for a process to be
541 			 * created, so stop.
542 			 */
543 			break;
544 		}
545 		soaio_starting++;
546 		mtx_unlock(&soaio_jobs_lock);
547 
548 		id = alloc_unr(soaio_kproc_unr);
549 		error = kproc_create(soaio_kproc_loop, (void *)(intptr_t)id,
550 		    &p, 0, 0, "soaiod%d", id);
551 		if (error != 0) {
552 			free_unr(soaio_kproc_unr, id);
553 			mtx_lock(&soaio_jobs_lock);
554 			soaio_starting--;
555 			break;
556 		}
557 
558 		mtx_lock(&soaio_jobs_lock);
559 		soaio_num_procs++;
560 	}
561 	mtx_unlock(&soaio_jobs_lock);
562 }
563 
564 void
soaio_enqueue(struct task * task)565 soaio_enqueue(struct task *task)
566 {
567 
568 	mtx_lock(&soaio_jobs_lock);
569 	MPASS(task->ta_pending == 0);
570 	task->ta_pending++;
571 	STAILQ_INSERT_TAIL(&soaio_jobs, task, ta_link);
572 	soaio_queued++;
573 	if (soaio_queued <= soaio_idle)
574 		wakeup_one(&soaio_idle);
575 	else if (soaio_num_procs < soaio_max_procs)
576 		taskqueue_enqueue(taskqueue_thread, &soaio_kproc_task);
577 	mtx_unlock(&soaio_jobs_lock);
578 }
579 
580 static void
soaio_init(void)581 soaio_init(void)
582 {
583 
584 	soaio_lifetime = AIOD_LIFETIME_DEFAULT;
585 	STAILQ_INIT(&soaio_jobs);
586 	mtx_init(&soaio_jobs_lock, "soaio jobs", NULL, MTX_DEF);
587 	soaio_kproc_unr = new_unrhdr(1, INT_MAX, NULL);
588 	TASK_INIT(&soaio_kproc_task, 0, soaio_kproc_create, NULL);
589 }
590 SYSINIT(soaio, SI_SUB_VFS, SI_ORDER_ANY, soaio_init, NULL);
591 
592 static __inline int
soaio_ready(struct socket * so,struct sockbuf * sb)593 soaio_ready(struct socket *so, struct sockbuf *sb)
594 {
595 	return (sb == &so->so_rcv ? soreadable(so) : sowriteable(so));
596 }
597 
598 static void
soaio_process_job(struct socket * so,sb_which which,struct kaiocb * job)599 soaio_process_job(struct socket *so, sb_which which, struct kaiocb *job)
600 {
601 	struct ucred *td_savedcred;
602 	struct thread *td;
603 	struct sockbuf *sb = sobuf(so, which);
604 #ifdef MAC
605 	struct file *fp = job->fd_file;
606 #endif
607 	size_t cnt, done, job_total_nbytes __diagused;
608 	long ru_before;
609 	int error, flags;
610 
611 	SOCK_BUF_UNLOCK(so, which);
612 	aio_switch_vmspace(job);
613 	td = curthread;
614 retry:
615 	td_savedcred = td->td_ucred;
616 	td->td_ucred = job->cred;
617 
618 	job_total_nbytes = job->uiop->uio_resid + job->aio_done;
619 	done = job->aio_done;
620 	cnt = job->uiop->uio_resid;
621 	job->uiop->uio_offset = 0;
622 	job->uiop->uio_td = td;
623 	flags = MSG_NBIO;
624 
625 	/*
626 	 * For resource usage accounting, only count a completed request
627 	 * as a single message to avoid counting multiple calls to
628 	 * sosend/soreceive on a blocking socket.
629 	 */
630 
631 	if (sb == &so->so_rcv) {
632 		ru_before = td->td_ru.ru_msgrcv;
633 #ifdef MAC
634 		error = mac_socket_check_receive(fp->f_cred, so);
635 		if (error == 0)
636 
637 #endif
638 			error = soreceive(so, NULL, job->uiop, NULL, NULL,
639 			    &flags);
640 		if (td->td_ru.ru_msgrcv != ru_before)
641 			job->msgrcv = 1;
642 	} else {
643 		if (!TAILQ_EMPTY(&sb->sb_aiojobq))
644 			flags |= MSG_MORETOCOME;
645 		ru_before = td->td_ru.ru_msgsnd;
646 #ifdef MAC
647 		error = mac_socket_check_send(fp->f_cred, so);
648 		if (error == 0)
649 #endif
650 			error = sousrsend(so, NULL, job->uiop, NULL, flags,
651 			    job->userproc);
652 		if (td->td_ru.ru_msgsnd != ru_before)
653 			job->msgsnd = 1;
654 	}
655 
656 	done += cnt - job->uiop->uio_resid;
657 	job->aio_done = done;
658 	td->td_ucred = td_savedcred;
659 
660 	if (error == EWOULDBLOCK) {
661 		/*
662 		 * The request was either partially completed or not
663 		 * completed at all due to racing with a read() or
664 		 * write() on the socket.  If the socket is
665 		 * non-blocking, return with any partial completion.
666 		 * If the socket is blocking or if no progress has
667 		 * been made, requeue this request at the head of the
668 		 * queue to try again when the socket is ready.
669 		 */
670 		MPASS(done != job_total_nbytes);
671 		SOCK_BUF_LOCK(so, which);
672 		if (done == 0 || !(so->so_state & SS_NBIO)) {
673 			empty_results++;
674 			if (soaio_ready(so, sb)) {
675 				empty_retries++;
676 				SOCK_BUF_UNLOCK(so, which);
677 				goto retry;
678 			}
679 
680 			if (!aio_set_cancel_function(job, soo_aio_cancel)) {
681 				SOCK_BUF_UNLOCK(so, which);
682 				if (done != 0)
683 					aio_complete(job, done, 0);
684 				else
685 					aio_cancel(job);
686 				SOCK_BUF_LOCK(so, which);
687 			} else {
688 				TAILQ_INSERT_HEAD(&sb->sb_aiojobq, job, list);
689 			}
690 			return;
691 		}
692 		SOCK_BUF_UNLOCK(so, which);
693 	}
694 	if (done != 0 && (error == ERESTART || error == EINTR ||
695 	    error == EWOULDBLOCK))
696 		error = 0;
697 	if (error)
698 		aio_complete(job, -1, error);
699 	else
700 		aio_complete(job, done, 0);
701 	SOCK_BUF_LOCK(so, which);
702 }
703 
704 static void
soaio_process_sb(struct socket * so,sb_which which)705 soaio_process_sb(struct socket *so, sb_which which)
706 {
707 	struct kaiocb *job;
708 	struct sockbuf *sb = sobuf(so, which);
709 
710 	CURVNET_SET(so->so_vnet);
711 	SOCK_BUF_LOCK(so, which);
712 	while (!TAILQ_EMPTY(&sb->sb_aiojobq) && soaio_ready(so, sb)) {
713 		job = TAILQ_FIRST(&sb->sb_aiojobq);
714 		TAILQ_REMOVE(&sb->sb_aiojobq, job, list);
715 		if (!aio_clear_cancel_function(job))
716 			continue;
717 
718 		soaio_process_job(so, which, job);
719 	}
720 
721 	/*
722 	 * If there are still pending requests, the socket must not be
723 	 * ready so set SB_AIO to request a wakeup when the socket
724 	 * becomes ready.
725 	 */
726 	if (!TAILQ_EMPTY(&sb->sb_aiojobq))
727 		sb->sb_flags |= SB_AIO;
728 	sb->sb_flags &= ~SB_AIO_RUNNING;
729 	SOCK_BUF_UNLOCK(so, which);
730 
731 	sorele(so);
732 	CURVNET_RESTORE();
733 }
734 
735 void
soaio_rcv(void * context,int pending)736 soaio_rcv(void *context, int pending)
737 {
738 	struct socket *so;
739 
740 	so = context;
741 	soaio_process_sb(so, SO_RCV);
742 }
743 
744 void
soaio_snd(void * context,int pending)745 soaio_snd(void *context, int pending)
746 {
747 	struct socket *so;
748 
749 	so = context;
750 	soaio_process_sb(so, SO_SND);
751 }
752 
753 void
sowakeup_aio(struct socket * so,sb_which which)754 sowakeup_aio(struct socket *so, sb_which which)
755 {
756 	struct sockbuf *sb = sobuf(so, which);
757 
758 	SOCK_BUF_LOCK_ASSERT(so, which);
759 
760 	sb->sb_flags &= ~SB_AIO;
761 	if (sb->sb_flags & SB_AIO_RUNNING)
762 		return;
763 	sb->sb_flags |= SB_AIO_RUNNING;
764 	soref(so);
765 	soaio_enqueue(&sb->sb_aiotask);
766 }
767 
768 static void
soo_aio_cancel(struct kaiocb * job)769 soo_aio_cancel(struct kaiocb *job)
770 {
771 	struct socket *so;
772 	struct sockbuf *sb;
773 	long done;
774 	int opcode;
775 	sb_which which;
776 
777 	so = job->fd_file->f_data;
778 	opcode = job->uaiocb.aio_lio_opcode;
779 	if (opcode & LIO_READ) {
780 		sb = &so->so_rcv;
781 		which = SO_RCV;
782 	} else {
783 		MPASS(opcode & LIO_WRITE);
784 		sb = &so->so_snd;
785 		which = SO_SND;
786 	}
787 
788 	SOCK_BUF_LOCK(so, which);
789 	if (!aio_cancel_cleared(job))
790 		TAILQ_REMOVE(&sb->sb_aiojobq, job, list);
791 	if (TAILQ_EMPTY(&sb->sb_aiojobq))
792 		sb->sb_flags &= ~SB_AIO;
793 	SOCK_BUF_UNLOCK(so, which);
794 
795 	done = job->aio_done;
796 	if (done != 0)
797 		aio_complete(job, done, 0);
798 	else
799 		aio_cancel(job);
800 }
801 
802 static int
soo_aio_queue(struct file * fp,struct kaiocb * job)803 soo_aio_queue(struct file *fp, struct kaiocb *job)
804 {
805 	struct socket *so;
806 	struct sockbuf *sb;
807 	sb_which which;
808 	int error;
809 
810 	so = fp->f_data;
811 	error = so->so_proto->pr_aio_queue(so, job);
812 	if (error == 0)
813 		return (0);
814 
815 	/* Lock through the socket, since this may be a listening socket. */
816 	switch (job->uaiocb.aio_lio_opcode & (LIO_WRITE | LIO_READ)) {
817 	case LIO_READ:
818 		SOCK_RECVBUF_LOCK(so);
819 		sb = &so->so_rcv;
820 		which = SO_RCV;
821 		break;
822 	case LIO_WRITE:
823 		SOCK_SENDBUF_LOCK(so);
824 		sb = &so->so_snd;
825 		which = SO_SND;
826 		break;
827 	default:
828 		return (EINVAL);
829 	}
830 
831 	if (SOLISTENING(so)) {
832 		SOCK_BUF_UNLOCK(so, which);
833 		return (EINVAL);
834 	}
835 
836 	if (!aio_set_cancel_function(job, soo_aio_cancel))
837 		panic("new job was cancelled");
838 	TAILQ_INSERT_TAIL(&sb->sb_aiojobq, job, list);
839 	if (!(sb->sb_flags & SB_AIO_RUNNING)) {
840 		if (soaio_ready(so, sb))
841 			sowakeup_aio(so, which);
842 		else
843 			sb->sb_flags |= SB_AIO;
844 	}
845 	SOCK_BUF_UNLOCK(so, which);
846 	return (0);
847 }
848