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