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