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