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