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