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