7b1a698d46760d74000f30d6ce19a27cf6607c93
[dragonfly.git] / sys / kern / uipc_syscalls.c
1 /*
2  * Copyright (c) 1982, 1986, 1989, 1990, 1993
3  *      The Regents of the University of California.  All rights reserved.
4  *
5  * sendfile(2) and related extensions:
6  * Copyright (c) 1998, David Greenman. All rights reserved. 
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. Neither the name of the University nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  *
32  *      @(#)uipc_syscalls.c     8.4 (Berkeley) 2/21/94
33  * $FreeBSD: src/sys/kern/uipc_syscalls.c,v 1.65.2.17 2003/04/04 17:11:16 tegge Exp $
34  */
35
36 #include "opt_ktrace.h"
37 #include "opt_sctp.h"
38
39 #include <sys/param.h>
40 #include <sys/systm.h>
41 #include <sys/kernel.h>
42 #include <sys/sysproto.h>
43 #include <sys/malloc.h>
44 #include <sys/filedesc.h>
45 #include <sys/event.h>
46 #include <sys/proc.h>
47 #include <sys/fcntl.h>
48 #include <sys/file.h>
49 #include <sys/filio.h>
50 #include <sys/kern_syscall.h>
51 #include <sys/mbuf.h>
52 #include <sys/protosw.h>
53 #include <sys/sfbuf.h>
54 #include <sys/socket.h>
55 #include <sys/socketvar.h>
56 #include <sys/socketops.h>
57 #include <sys/uio.h>
58 #include <sys/vnode.h>
59 #include <sys/lock.h>
60 #include <sys/mount.h>
61 #ifdef KTRACE
62 #include <sys/ktrace.h>
63 #endif
64 #include <vm/vm.h>
65 #include <vm/vm_object.h>
66 #include <vm/vm_page.h>
67 #include <vm/vm_pageout.h>
68 #include <vm/vm_kern.h>
69 #include <vm/vm_extern.h>
70 #include <sys/file2.h>
71 #include <sys/signalvar.h>
72 #include <sys/serialize.h>
73
74 #include <sys/thread2.h>
75 #include <sys/msgport2.h>
76 #include <sys/socketvar2.h>
77 #include <net/netmsg2.h>
78
79 #ifdef SCTP
80 #include <netinet/sctp_peeloff.h>
81 #endif /* SCTP */
82
83 extern int use_soaccept_pred_fast;
84 extern int use_sendfile_async;
85 extern int use_soconnect_async;
86
87 /*
88  * System call interface to the socket abstraction.
89  */
90
91 extern  struct fileops socketops;
92
93 /*
94  * socket_args(int domain, int type, int protocol)
95  */
96 int
97 kern_socket(int domain, int type, int protocol, int *res)
98 {
99         struct thread *td = curthread;
100         struct filedesc *fdp = td->td_proc->p_fd;
101         struct socket *so;
102         struct file *fp;
103         int fd, error;
104
105         KKASSERT(td->td_lwp);
106
107         error = falloc(td->td_lwp, &fp, &fd);
108         if (error)
109                 return (error);
110         error = socreate(domain, &so, type, protocol, td);
111         if (error) {
112                 fsetfd(fdp, NULL, fd);
113         } else {
114                 fp->f_type = DTYPE_SOCKET;
115                 fp->f_flag = FREAD | FWRITE;
116                 fp->f_ops = &socketops;
117                 fp->f_data = so;
118                 *res = fd;
119                 fsetfd(fdp, fp, fd);
120         }
121         fdrop(fp);
122         return (error);
123 }
124
125 /*
126  * MPALMOSTSAFE
127  */
128 int
129 sys_socket(struct socket_args *uap)
130 {
131         int error;
132
133         error = kern_socket(uap->domain, uap->type, uap->protocol,
134                             &uap->sysmsg_iresult);
135
136         return (error);
137 }
138
139 int
140 kern_bind(int s, struct sockaddr *sa)
141 {
142         struct thread *td = curthread;
143         struct proc *p = td->td_proc;
144         struct file *fp;
145         int error;
146
147         KKASSERT(p);
148         error = holdsock(p->p_fd, s, &fp);
149         if (error)
150                 return (error);
151         error = sobind((struct socket *)fp->f_data, sa, td);
152         fdrop(fp);
153         return (error);
154 }
155
156 /*
157  * bind_args(int s, caddr_t name, int namelen)
158  *
159  * MPALMOSTSAFE
160  */
161 int
162 sys_bind(struct bind_args *uap)
163 {
164         struct sockaddr *sa;
165         int error;
166
167         error = getsockaddr(&sa, uap->name, uap->namelen);
168         if (error)
169                 return (error);
170         error = kern_bind(uap->s, sa);
171         kfree(sa, M_SONAME);
172
173         return (error);
174 }
175
176 int
177 kern_listen(int s, int backlog)
178 {
179         struct thread *td = curthread;
180         struct proc *p = td->td_proc;
181         struct file *fp;
182         int error;
183
184         KKASSERT(p);
185         error = holdsock(p->p_fd, s, &fp);
186         if (error)
187                 return (error);
188         error = solisten((struct socket *)fp->f_data, backlog, td);
189         fdrop(fp);
190         return(error);
191 }
192
193 /*
194  * listen_args(int s, int backlog)
195  *
196  * MPALMOSTSAFE
197  */
198 int
199 sys_listen(struct listen_args *uap)
200 {
201         int error;
202
203         error = kern_listen(uap->s, uap->backlog);
204         return (error);
205 }
206
207 /*
208  * Returns the accepted socket as well.
209  *
210  * NOTE!  The sockets sitting on so_comp/so_incomp might have 0 refs, the
211  *        pool token is absolutely required to avoid a sofree() race,
212  *        as well as to avoid tailq handling races.
213  */
214 static boolean_t
215 soaccept_predicate(struct netmsg_so_notify *msg)
216 {
217         struct socket *head = msg->base.nm_so;
218         struct socket *so;
219
220         if (head->so_error != 0) {
221                 msg->base.lmsg.ms_error = head->so_error;
222                 return (TRUE);
223         }
224         lwkt_getpooltoken(head);
225         if (!TAILQ_EMPTY(&head->so_comp)) {
226                 /* Abuse nm_so field as copy in/copy out parameter. XXX JH */
227                 so = TAILQ_FIRST(&head->so_comp);
228                 TAILQ_REMOVE(&head->so_comp, so, so_list);
229                 head->so_qlen--;
230                 soclrstate(so, SS_COMP);
231                 so->so_head = NULL;
232                 soreference(so);
233
234                 lwkt_relpooltoken(head);
235
236                 msg->base.lmsg.ms_error = 0;
237                 msg->base.nm_so = so;
238                 return (TRUE);
239         }
240         lwkt_relpooltoken(head);
241         if (head->so_state & SS_CANTRCVMORE) {
242                 msg->base.lmsg.ms_error = ECONNABORTED;
243                 return (TRUE);
244         }
245         if (msg->nm_fflags & FNONBLOCK) {
246                 msg->base.lmsg.ms_error = EWOULDBLOCK;
247                 return (TRUE);
248         }
249
250         return (FALSE);
251 }
252
253 /*
254  * The second argument to kern_accept() is a handle to a struct sockaddr.
255  * This allows kern_accept() to return a pointer to an allocated struct
256  * sockaddr which must be freed later with FREE().  The caller must
257  * initialize *name to NULL.
258  */
259 int
260 kern_accept(int s, int fflags, struct sockaddr **name, int *namelen, int *res)
261 {
262         struct thread *td = curthread;
263         struct filedesc *fdp = td->td_proc->p_fd;
264         struct file *lfp = NULL;
265         struct file *nfp = NULL;
266         struct sockaddr *sa;
267         struct socket *head, *so;
268         struct netmsg_so_notify msg;
269         int fd;
270         u_int fflag;            /* type must match fp->f_flag */
271         int error, tmp;
272
273         *res = -1;
274         if (name && namelen && *namelen < 0)
275                 return (EINVAL);
276
277         error = holdsock(td->td_proc->p_fd, s, &lfp);
278         if (error)
279                 return (error);
280
281         error = falloc(td->td_lwp, &nfp, &fd);
282         if (error) {            /* Probably ran out of file descriptors. */
283                 fdrop(lfp);
284                 return (error);
285         }
286         head = (struct socket *)lfp->f_data;
287         if ((head->so_options & SO_ACCEPTCONN) == 0) {
288                 error = EINVAL;
289                 goto done;
290         }
291
292         if (fflags & O_FBLOCKING)
293                 fflags |= lfp->f_flag & ~FNONBLOCK;
294         else if (fflags & O_FNONBLOCKING)
295                 fflags |= lfp->f_flag | FNONBLOCK;
296         else
297                 fflags = lfp->f_flag;
298
299         if (use_soaccept_pred_fast) {
300                 boolean_t pred;
301
302                 /* Initialize necessary parts for soaccept_predicate() */
303                 netmsg_init(&msg.base, head, &netisr_apanic_rport, 0, NULL);
304                 msg.nm_fflags = fflags;
305
306                 lwkt_getpooltoken(head);
307                 pred = soaccept_predicate(&msg);
308                 lwkt_relpooltoken(head);
309
310                 if (pred) {
311                         error = msg.base.lmsg.ms_error;
312                         if (error)
313                                 goto done;
314                         else
315                                 goto accepted;
316                 }
317         }
318
319         /* optimize for uniprocessor case later XXX JH */
320         netmsg_init_abortable(&msg.base, head, &curthread->td_msgport,
321                               0, netmsg_so_notify, netmsg_so_notify_doabort);
322         msg.nm_predicate = soaccept_predicate;
323         msg.nm_fflags = fflags;
324         msg.nm_etype = NM_REVENT;
325         error = lwkt_domsg(head->so_port, &msg.base.lmsg, PCATCH);
326         if (error)
327                 goto done;
328
329 accepted:
330         /*
331          * At this point we have the connection that's ready to be accepted.
332          *
333          * NOTE! soaccept_predicate() ref'd so for us, and soaccept() expects
334          *       to eat the ref and turn it into a descriptor.
335          */
336         so = msg.base.nm_so;
337
338         fflag = lfp->f_flag;
339
340         /* connection has been removed from the listen queue */
341         KNOTE(&head->so_rcv.ssb_kq.ki_note, 0);
342
343         if (head->so_sigio != NULL)
344                 fsetown(fgetown(&head->so_sigio), &so->so_sigio);
345
346         nfp->f_type = DTYPE_SOCKET;
347         nfp->f_flag = fflag;
348         nfp->f_ops = &socketops;
349         nfp->f_data = so;
350         /* Sync socket nonblocking/async state with file flags */
351         tmp = fflag & FNONBLOCK;
352         fo_ioctl(nfp, FIONBIO, (caddr_t)&tmp, td->td_ucred, NULL);
353         tmp = fflag & FASYNC;
354         fo_ioctl(nfp, FIOASYNC, (caddr_t)&tmp, td->td_ucred, NULL);
355
356         sa = NULL;
357         if (so->so_faddr != NULL) {
358                 sa = so->so_faddr;
359                 so->so_faddr = NULL;
360
361                 soaccept_generic(so);
362                 error = 0;
363         } else {
364                 error = soaccept(so, &sa);
365         }
366
367         /*
368          * Set the returned name and namelen as applicable.  Set the returned
369          * namelen to 0 for older code which might ignore the return value
370          * from accept.
371          */
372         if (error == 0) {
373                 if (sa && name && namelen) {
374                         if (*namelen > sa->sa_len)
375                                 *namelen = sa->sa_len;
376                         *name = sa;
377                 } else {
378                         if (sa)
379                                 kfree(sa, M_SONAME);
380                 }
381         }
382
383 done:
384         /*
385          * If an error occured clear the reserved descriptor, else associate
386          * nfp with it.
387          *
388          * Note that *res is normally ignored if an error is returned but
389          * a syscall message will still have access to the result code.
390          */
391         if (error) {
392                 fsetfd(fdp, NULL, fd);
393         } else {
394                 *res = fd;
395                 fsetfd(fdp, nfp, fd);
396         }
397         fdrop(nfp);
398         fdrop(lfp);
399         return (error);
400 }
401
402 /*
403  * accept(int s, caddr_t name, int *anamelen)
404  *
405  * MPALMOSTSAFE
406  */
407 int
408 sys_accept(struct accept_args *uap)
409 {
410         struct sockaddr *sa = NULL;
411         int sa_len;
412         int error;
413
414         if (uap->name) {
415                 error = copyin(uap->anamelen, &sa_len, sizeof(sa_len));
416                 if (error)
417                         return (error);
418
419                 error = kern_accept(uap->s, 0, &sa, &sa_len,
420                                     &uap->sysmsg_iresult);
421
422                 if (error == 0)
423                         error = copyout(sa, uap->name, sa_len);
424                 if (error == 0) {
425                         error = copyout(&sa_len, uap->anamelen,
426                             sizeof(*uap->anamelen));
427                 }
428                 if (sa)
429                         kfree(sa, M_SONAME);
430         } else {
431                 error = kern_accept(uap->s, 0, NULL, 0,
432                                     &uap->sysmsg_iresult);
433         }
434         return (error);
435 }
436
437 /*
438  * extaccept(int s, int fflags, caddr_t name, int *anamelen)
439  *
440  * MPALMOSTSAFE
441  */
442 int
443 sys_extaccept(struct extaccept_args *uap)
444 {
445         struct sockaddr *sa = NULL;
446         int sa_len;
447         int error;
448         int fflags = uap->flags & O_FMASK;
449
450         if (uap->name) {
451                 error = copyin(uap->anamelen, &sa_len, sizeof(sa_len));
452                 if (error)
453                         return (error);
454
455                 error = kern_accept(uap->s, fflags, &sa, &sa_len,
456                                     &uap->sysmsg_iresult);
457
458                 if (error == 0)
459                         error = copyout(sa, uap->name, sa_len);
460                 if (error == 0) {
461                         error = copyout(&sa_len, uap->anamelen,
462                             sizeof(*uap->anamelen));
463                 }
464                 if (sa)
465                         kfree(sa, M_SONAME);
466         } else {
467                 error = kern_accept(uap->s, fflags, NULL, 0,
468                                     &uap->sysmsg_iresult);
469         }
470         return (error);
471 }
472
473
474 /*
475  * Returns TRUE if predicate satisfied.
476  */
477 static boolean_t
478 soconnected_predicate(struct netmsg_so_notify *msg)
479 {
480         struct socket *so = msg->base.nm_so;
481
482         /* check predicate */
483         if (!(so->so_state & SS_ISCONNECTING) || so->so_error != 0) {
484                 msg->base.lmsg.ms_error = so->so_error;
485                 return (TRUE);
486         }
487
488         return (FALSE);
489 }
490
491 int
492 kern_connect(int s, int fflags, struct sockaddr *sa)
493 {
494         struct thread *td = curthread;
495         struct proc *p = td->td_proc;
496         struct file *fp;
497         struct socket *so;
498         int error, interrupted = 0;
499
500         error = holdsock(p->p_fd, s, &fp);
501         if (error)
502                 return (error);
503         so = (struct socket *)fp->f_data;
504
505         if (fflags & O_FBLOCKING)
506                 /* fflags &= ~FNONBLOCK; */;
507         else if (fflags & O_FNONBLOCKING)
508                 fflags |= FNONBLOCK;
509         else
510                 fflags = fp->f_flag;
511
512         if (so->so_state & SS_ISCONNECTING) {
513                 error = EALREADY;
514                 goto done;
515         }
516         error = soconnect(so, sa, td, use_soconnect_async ? FALSE : TRUE);
517         if (error)
518                 goto bad;
519         if ((fflags & FNONBLOCK) && (so->so_state & SS_ISCONNECTING)) {
520                 error = EINPROGRESS;
521                 goto done;
522         }
523         if ((so->so_state & SS_ISCONNECTING) && so->so_error == 0) {
524                 struct netmsg_so_notify msg;
525
526                 netmsg_init_abortable(&msg.base, so,
527                                       &curthread->td_msgport,
528                                       0,
529                                       netmsg_so_notify,
530                                       netmsg_so_notify_doabort);
531                 msg.nm_predicate = soconnected_predicate;
532                 msg.nm_etype = NM_REVENT;
533                 error = lwkt_domsg(so->so_port, &msg.base.lmsg, PCATCH);
534                 if (error == EINTR || error == ERESTART)
535                         interrupted = 1;
536         }
537         if (error == 0) {
538                 error = so->so_error;
539                 so->so_error = 0;
540         }
541 bad:
542         if (!interrupted)
543                 soclrstate(so, SS_ISCONNECTING);
544         if (error == ERESTART)
545                 error = EINTR;
546 done:
547         fdrop(fp);
548         return (error);
549 }
550
551 /*
552  * connect_args(int s, caddr_t name, int namelen)
553  *
554  * MPALMOSTSAFE
555  */
556 int
557 sys_connect(struct connect_args *uap)
558 {
559         struct sockaddr *sa;
560         int error;
561
562         error = getsockaddr(&sa, uap->name, uap->namelen);
563         if (error)
564                 return (error);
565         error = kern_connect(uap->s, 0, sa);
566         kfree(sa, M_SONAME);
567
568         return (error);
569 }
570
571 /*
572  * connect_args(int s, int fflags, caddr_t name, int namelen)
573  *
574  * MPALMOSTSAFE
575  */
576 int
577 sys_extconnect(struct extconnect_args *uap)
578 {
579         struct sockaddr *sa;
580         int error;
581         int fflags = uap->flags & O_FMASK;
582
583         error = getsockaddr(&sa, uap->name, uap->namelen);
584         if (error)
585                 return (error);
586         error = kern_connect(uap->s, fflags, sa);
587         kfree(sa, M_SONAME);
588
589         return (error);
590 }
591
592 int
593 kern_socketpair(int domain, int type, int protocol, int *sv)
594 {
595         struct thread *td = curthread;
596         struct filedesc *fdp;
597         struct file *fp1, *fp2;
598         struct socket *so1, *so2;
599         int fd1, fd2, error;
600
601         fdp = td->td_proc->p_fd;
602         error = socreate(domain, &so1, type, protocol, td);
603         if (error)
604                 return (error);
605         error = socreate(domain, &so2, type, protocol, td);
606         if (error)
607                 goto free1;
608         error = falloc(td->td_lwp, &fp1, &fd1);
609         if (error)
610                 goto free2;
611         sv[0] = fd1;
612         fp1->f_data = so1;
613         error = falloc(td->td_lwp, &fp2, &fd2);
614         if (error)
615                 goto free3;
616         fp2->f_data = so2;
617         sv[1] = fd2;
618         error = soconnect2(so1, so2);
619         if (error)
620                 goto free4;
621         if (type == SOCK_DGRAM) {
622                 /*
623                  * Datagram socket connection is asymmetric.
624                  */
625                  error = soconnect2(so2, so1);
626                  if (error)
627                         goto free4;
628         }
629         fp1->f_type = fp2->f_type = DTYPE_SOCKET;
630         fp1->f_flag = fp2->f_flag = FREAD|FWRITE;
631         fp1->f_ops = fp2->f_ops = &socketops;
632         fsetfd(fdp, fp1, fd1);
633         fsetfd(fdp, fp2, fd2);
634         fdrop(fp1);
635         fdrop(fp2);
636         return (error);
637 free4:
638         fsetfd(fdp, NULL, fd2);
639         fdrop(fp2);
640 free3:
641         fsetfd(fdp, NULL, fd1);
642         fdrop(fp1);
643 free2:
644         (void)soclose(so2, 0);
645 free1:
646         (void)soclose(so1, 0);
647         return (error);
648 }
649
650 /*
651  * socketpair(int domain, int type, int protocol, int *rsv)
652  */
653 int
654 sys_socketpair(struct socketpair_args *uap)
655 {
656         int error, sockv[2];
657
658         error = kern_socketpair(uap->domain, uap->type, uap->protocol, sockv);
659
660         if (error == 0) {
661                 error = copyout(sockv, uap->rsv, sizeof(sockv));
662
663                 if (error != 0) {
664                         kern_close(sockv[0]);
665                         kern_close(sockv[1]);
666                 }
667         }
668
669         return (error);
670 }
671
672 int
673 kern_sendmsg(int s, struct sockaddr *sa, struct uio *auio,
674              struct mbuf *control, int flags, size_t *res)
675 {
676         struct thread *td = curthread;
677         struct lwp *lp = td->td_lwp;
678         struct proc *p = td->td_proc;
679         struct file *fp;
680         size_t len;
681         int error;
682         struct socket *so;
683 #ifdef KTRACE
684         struct iovec *ktriov = NULL;
685         struct uio ktruio;
686 #endif
687
688         error = holdsock(p->p_fd, s, &fp);
689         if (error)
690                 return (error);
691 #ifdef KTRACE
692         if (KTRPOINT(td, KTR_GENIO)) {
693                 int iovlen = auio->uio_iovcnt * sizeof (struct iovec);
694
695                 ktriov = kmalloc(iovlen, M_TEMP, M_WAITOK);
696                 bcopy((caddr_t)auio->uio_iov, (caddr_t)ktriov, iovlen);
697                 ktruio = *auio;
698         }
699 #endif
700         len = auio->uio_resid;
701         so = (struct socket *)fp->f_data;
702         if ((flags & (MSG_FNONBLOCKING|MSG_FBLOCKING)) == 0) {
703                 if (fp->f_flag & FNONBLOCK)
704                         flags |= MSG_FNONBLOCKING;
705         }
706         error = so_pru_sosend(so, sa, auio, NULL, control, flags, td);
707         if (error) {
708                 if (auio->uio_resid != len && (error == ERESTART ||
709                     error == EINTR || error == EWOULDBLOCK))
710                         error = 0;
711                 if (error == EPIPE && !(flags & MSG_NOSIGNAL) &&
712                     !(so->so_options & SO_NOSIGPIPE))
713                         lwpsignal(p, lp, SIGPIPE);
714         }
715 #ifdef KTRACE
716         if (ktriov != NULL) {
717                 if (error == 0) {
718                         ktruio.uio_iov = ktriov;
719                         ktruio.uio_resid = len - auio->uio_resid;
720                         ktrgenio(lp, s, UIO_WRITE, &ktruio, error);
721                 }
722                 kfree(ktriov, M_TEMP);
723         }
724 #endif
725         if (error == 0)
726                 *res  = len - auio->uio_resid;
727         fdrop(fp);
728         return (error);
729 }
730
731 /*
732  * sendto_args(int s, caddr_t buf, size_t len, int flags, caddr_t to, int tolen)
733  *
734  * MPALMOSTSAFE
735  */
736 int
737 sys_sendto(struct sendto_args *uap)
738 {
739         struct thread *td = curthread;
740         struct uio auio;
741         struct iovec aiov;
742         struct sockaddr *sa = NULL;
743         int error;
744
745         if (uap->to) {
746                 error = getsockaddr(&sa, uap->to, uap->tolen);
747                 if (error)
748                         return (error);
749         }
750         aiov.iov_base = uap->buf;
751         aiov.iov_len = uap->len;
752         auio.uio_iov = &aiov;
753         auio.uio_iovcnt = 1;
754         auio.uio_offset = 0;
755         auio.uio_resid = uap->len;
756         auio.uio_segflg = UIO_USERSPACE;
757         auio.uio_rw = UIO_WRITE;
758         auio.uio_td = td;
759
760         error = kern_sendmsg(uap->s, sa, &auio, NULL, uap->flags,
761                              &uap->sysmsg_szresult);
762
763         if (sa)
764                 kfree(sa, M_SONAME);
765         return (error);
766 }
767
768 /*
769  * sendmsg_args(int s, caddr_t msg, int flags)
770  *
771  * MPALMOSTSAFE
772  */
773 int
774 sys_sendmsg(struct sendmsg_args *uap)
775 {
776         struct thread *td = curthread;
777         struct msghdr msg;
778         struct uio auio;
779         struct iovec aiov[UIO_SMALLIOV], *iov = NULL;
780         struct sockaddr *sa = NULL;
781         struct mbuf *control = NULL;
782         int error;
783
784         error = copyin(uap->msg, (caddr_t)&msg, sizeof(msg));
785         if (error)
786                 return (error);
787
788         /*
789          * Conditionally copyin msg.msg_name.
790          */
791         if (msg.msg_name) {
792                 error = getsockaddr(&sa, msg.msg_name, msg.msg_namelen);
793                 if (error)
794                         return (error);
795         }
796
797         /*
798          * Populate auio.
799          */
800         error = iovec_copyin(msg.msg_iov, &iov, aiov, msg.msg_iovlen,
801                              &auio.uio_resid);
802         if (error)
803                 goto cleanup2;
804         auio.uio_iov = iov;
805         auio.uio_iovcnt = msg.msg_iovlen;
806         auio.uio_offset = 0;
807         auio.uio_segflg = UIO_USERSPACE;
808         auio.uio_rw = UIO_WRITE;
809         auio.uio_td = td;
810
811         /*
812          * Conditionally copyin msg.msg_control.
813          */
814         if (msg.msg_control) {
815                 if (msg.msg_controllen < sizeof(struct cmsghdr) ||
816                     msg.msg_controllen > MLEN) {
817                         error = EINVAL;
818                         goto cleanup;
819                 }
820                 control = m_get(MB_WAIT, MT_CONTROL);
821                 if (control == NULL) {
822                         error = ENOBUFS;
823                         goto cleanup;
824                 }
825                 control->m_len = msg.msg_controllen;
826                 error = copyin(msg.msg_control, mtod(control, caddr_t),
827                                msg.msg_controllen);
828                 if (error) {
829                         m_free(control);
830                         goto cleanup;
831                 }
832         }
833
834         error = kern_sendmsg(uap->s, sa, &auio, control, uap->flags,
835                              &uap->sysmsg_szresult);
836
837 cleanup:
838         iovec_free(&iov, aiov);
839 cleanup2:
840         if (sa)
841                 kfree(sa, M_SONAME);
842         return (error);
843 }
844
845 /*
846  * kern_recvmsg() takes a handle to sa and control.  If the handle is non-
847  * null, it returns a dynamically allocated struct sockaddr and an mbuf.
848  * Don't forget to FREE() and m_free() these if they are returned.
849  */
850 int
851 kern_recvmsg(int s, struct sockaddr **sa, struct uio *auio,
852              struct mbuf **control, int *flags, size_t *res)
853 {
854         struct thread *td = curthread;
855         struct proc *p = td->td_proc;
856         struct file *fp;
857         size_t len;
858         int error;
859         int lflags;
860         struct socket *so;
861 #ifdef KTRACE
862         struct iovec *ktriov = NULL;
863         struct uio ktruio;
864 #endif
865
866         error = holdsock(p->p_fd, s, &fp);
867         if (error)
868                 return (error);
869 #ifdef KTRACE
870         if (KTRPOINT(td, KTR_GENIO)) {
871                 int iovlen = auio->uio_iovcnt * sizeof (struct iovec);
872
873                 ktriov = kmalloc(iovlen, M_TEMP, M_WAITOK);
874                 bcopy(auio->uio_iov, ktriov, iovlen);
875                 ktruio = *auio;
876         }
877 #endif
878         len = auio->uio_resid;
879         so = (struct socket *)fp->f_data;
880
881         if (flags == NULL || (*flags & (MSG_FNONBLOCKING|MSG_FBLOCKING)) == 0) {
882                 if (fp->f_flag & FNONBLOCK) {
883                         if (flags) {
884                                 *flags |= MSG_FNONBLOCKING;
885                         } else {
886                                 lflags = MSG_FNONBLOCKING;
887                                 flags = &lflags;
888                         }
889                 }
890         }
891
892         error = so_pru_soreceive(so, sa, auio, NULL, control, flags);
893         if (error) {
894                 if (auio->uio_resid != len && (error == ERESTART ||
895                     error == EINTR || error == EWOULDBLOCK))
896                         error = 0;
897         }
898 #ifdef KTRACE
899         if (ktriov != NULL) {
900                 if (error == 0) {
901                         ktruio.uio_iov = ktriov;
902                         ktruio.uio_resid = len - auio->uio_resid;
903                         ktrgenio(td->td_lwp, s, UIO_READ, &ktruio, error);
904                 }
905                 kfree(ktriov, M_TEMP);
906         }
907 #endif
908         if (error == 0)
909                 *res = len - auio->uio_resid;
910         fdrop(fp);
911         return (error);
912 }
913
914 /*
915  * recvfrom_args(int s, caddr_t buf, size_t len, int flags, 
916  *                      caddr_t from, int *fromlenaddr)
917  *
918  * MPALMOSTSAFE
919  */
920 int
921 sys_recvfrom(struct recvfrom_args *uap)
922 {
923         struct thread *td = curthread;
924         struct uio auio;
925         struct iovec aiov;
926         struct sockaddr *sa = NULL;
927         int error, fromlen;
928
929         if (uap->from && uap->fromlenaddr) {
930                 error = copyin(uap->fromlenaddr, &fromlen, sizeof(fromlen));
931                 if (error)
932                         return (error);
933                 if (fromlen < 0)
934                         return (EINVAL);
935         } else {
936                 fromlen = 0;
937         }
938         aiov.iov_base = uap->buf;
939         aiov.iov_len = uap->len;
940         auio.uio_iov = &aiov;
941         auio.uio_iovcnt = 1;
942         auio.uio_offset = 0;
943         auio.uio_resid = uap->len;
944         auio.uio_segflg = UIO_USERSPACE;
945         auio.uio_rw = UIO_READ;
946         auio.uio_td = td;
947
948         error = kern_recvmsg(uap->s, uap->from ? &sa : NULL, &auio, NULL,
949                              &uap->flags, &uap->sysmsg_szresult);
950
951         if (error == 0 && uap->from) {
952                 /* note: sa may still be NULL */
953                 if (sa) {
954                         fromlen = MIN(fromlen, sa->sa_len);
955                         error = copyout(sa, uap->from, fromlen);
956                 } else {
957                         fromlen = 0;
958                 }
959                 if (error == 0) {
960                         error = copyout(&fromlen, uap->fromlenaddr,
961                                         sizeof(fromlen));
962                 }
963         }
964         if (sa)
965                 kfree(sa, M_SONAME);
966
967         return (error);
968 }
969
970 /*
971  * recvmsg_args(int s, struct msghdr *msg, int flags)
972  *
973  * MPALMOSTSAFE
974  */
975 int
976 sys_recvmsg(struct recvmsg_args *uap)
977 {
978         struct thread *td = curthread;
979         struct msghdr msg;
980         struct uio auio;
981         struct iovec aiov[UIO_SMALLIOV], *iov = NULL;
982         struct mbuf *m, *control = NULL;
983         struct sockaddr *sa = NULL;
984         caddr_t ctlbuf;
985         socklen_t *ufromlenp, *ucontrollenp;
986         int error, fromlen, controllen, len, flags, *uflagsp;
987
988         /*
989          * This copyin handles everything except the iovec.
990          */
991         error = copyin(uap->msg, &msg, sizeof(msg));
992         if (error)
993                 return (error);
994
995         if (msg.msg_name && msg.msg_namelen < 0)
996                 return (EINVAL);
997         if (msg.msg_control && msg.msg_controllen < 0)
998                 return (EINVAL);
999
1000         ufromlenp = (socklen_t *)((caddr_t)uap->msg + offsetof(struct msghdr,
1001                     msg_namelen));
1002         ucontrollenp = (socklen_t *)((caddr_t)uap->msg + offsetof(struct msghdr,
1003                        msg_controllen));
1004         uflagsp = (int *)((caddr_t)uap->msg + offsetof(struct msghdr,
1005                                                         msg_flags));
1006
1007         /*
1008          * Populate auio.
1009          */
1010         error = iovec_copyin(msg.msg_iov, &iov, aiov, msg.msg_iovlen,
1011                              &auio.uio_resid);
1012         if (error)
1013                 return (error);
1014         auio.uio_iov = iov;
1015         auio.uio_iovcnt = msg.msg_iovlen;
1016         auio.uio_offset = 0;
1017         auio.uio_segflg = UIO_USERSPACE;
1018         auio.uio_rw = UIO_READ;
1019         auio.uio_td = td;
1020
1021         flags = uap->flags;
1022
1023         error = kern_recvmsg(uap->s,
1024                              (msg.msg_name ? &sa : NULL), &auio,
1025                              (msg.msg_control ? &control : NULL), &flags,
1026                              &uap->sysmsg_szresult);
1027
1028         /*
1029          * Conditionally copyout the name and populate the namelen field.
1030          */
1031         if (error == 0 && msg.msg_name) {
1032                 /* note: sa may still be NULL */
1033                 if (sa != NULL) {
1034                         fromlen = MIN(msg.msg_namelen, sa->sa_len);
1035                         error = copyout(sa, msg.msg_name, fromlen);
1036                 } else {
1037                         fromlen = 0;
1038                 }
1039                 if (error == 0)
1040                         error = copyout(&fromlen, ufromlenp,
1041                             sizeof(*ufromlenp));
1042         }
1043
1044         /*
1045          * Copyout msg.msg_control and msg.msg_controllen.
1046          */
1047         if (error == 0 && msg.msg_control) {
1048                 len = msg.msg_controllen;
1049                 m = control;
1050                 ctlbuf = (caddr_t)msg.msg_control;
1051
1052                 while(m && len > 0) {
1053                         unsigned int tocopy;
1054
1055                         if (len >= m->m_len) {
1056                                 tocopy = m->m_len;
1057                         } else {
1058                                 msg.msg_flags |= MSG_CTRUNC;
1059                                 tocopy = len;
1060                         }
1061
1062                         error = copyout(mtod(m, caddr_t), ctlbuf, tocopy);
1063                         if (error)
1064                                 goto cleanup;
1065
1066                         ctlbuf += tocopy;
1067                         len -= tocopy;
1068                         m = m->m_next;
1069                 }
1070                 controllen = ctlbuf - (caddr_t)msg.msg_control;
1071                 error = copyout(&controllen, ucontrollenp,
1072                     sizeof(*ucontrollenp));
1073         }
1074
1075         if (error == 0)
1076                 error = copyout(&flags, uflagsp, sizeof(*uflagsp));
1077
1078 cleanup:
1079         if (sa)
1080                 kfree(sa, M_SONAME);
1081         iovec_free(&iov, aiov);
1082         if (control)
1083                 m_freem(control);
1084         return (error);
1085 }
1086
1087 /*
1088  * If sopt->sopt_td == NULL, then sopt->sopt_val is treated as an
1089  * in kernel pointer instead of a userland pointer.  This allows us
1090  * to manipulate socket options in the emulation code.
1091  */
1092 int
1093 kern_setsockopt(int s, struct sockopt *sopt)
1094 {
1095         struct thread *td = curthread;
1096         struct proc *p = td->td_proc;
1097         struct file *fp;
1098         int error;
1099
1100         if (sopt->sopt_val == NULL && sopt->sopt_valsize != 0)
1101                 return (EFAULT);
1102         if (sopt->sopt_val != NULL && sopt->sopt_valsize == 0)
1103                 return (EINVAL);
1104         if (sopt->sopt_valsize > SOMAXOPT_SIZE) /* unsigned */
1105                 return (EINVAL);
1106
1107         error = holdsock(p->p_fd, s, &fp);
1108         if (error)
1109                 return (error);
1110
1111         error = sosetopt((struct socket *)fp->f_data, sopt);
1112         fdrop(fp);
1113         return (error);
1114 }
1115
1116 /*
1117  * setsockopt_args(int s, int level, int name, caddr_t val, int valsize)
1118  *
1119  * MPALMOSTSAFE
1120  */
1121 int
1122 sys_setsockopt(struct setsockopt_args *uap)
1123 {
1124         struct thread *td = curthread;
1125         struct sockopt sopt;
1126         int error;
1127
1128         sopt.sopt_level = uap->level;
1129         sopt.sopt_name = uap->name;
1130         sopt.sopt_valsize = uap->valsize;
1131         sopt.sopt_td = td;
1132         sopt.sopt_val = NULL;
1133
1134         if (sopt.sopt_valsize > SOMAXOPT_SIZE) /* unsigned */
1135                 return (EINVAL);
1136         if (uap->val) {
1137                 sopt.sopt_val = kmalloc(sopt.sopt_valsize, M_TEMP, M_WAITOK);
1138                 error = copyin(uap->val, sopt.sopt_val, sopt.sopt_valsize);
1139                 if (error)
1140                         goto out;
1141         }
1142
1143         error = kern_setsockopt(uap->s, &sopt);
1144 out:
1145         if (uap->val)
1146                 kfree(sopt.sopt_val, M_TEMP);
1147         return(error);
1148 }
1149
1150 /*
1151  * If sopt->sopt_td == NULL, then sopt->sopt_val is treated as an
1152  * in kernel pointer instead of a userland pointer.  This allows us
1153  * to manipulate socket options in the emulation code.
1154  */
1155 int
1156 kern_getsockopt(int s, struct sockopt *sopt)
1157 {
1158         struct thread *td = curthread;
1159         struct proc *p = td->td_proc;
1160         struct file *fp;
1161         int error;
1162
1163         if (sopt->sopt_val == NULL && sopt->sopt_valsize != 0)
1164                 return (EFAULT);
1165         if (sopt->sopt_val != NULL && sopt->sopt_valsize == 0)
1166                 return (EINVAL);
1167         if (sopt->sopt_valsize > SOMAXOPT_SIZE) /* unsigned */
1168                 return (EINVAL);
1169
1170         error = holdsock(p->p_fd, s, &fp);
1171         if (error)
1172                 return (error);
1173
1174         error = sogetopt((struct socket *)fp->f_data, sopt);
1175         fdrop(fp);
1176         return (error);
1177 }
1178
1179 /*
1180  * getsockopt_args(int s, int level, int name, caddr_t val, int *avalsize)
1181  *
1182  * MPALMOSTSAFE
1183  */
1184 int
1185 sys_getsockopt(struct getsockopt_args *uap)
1186 {
1187         struct thread *td = curthread;
1188         struct  sockopt sopt;
1189         int     error, valsize;
1190
1191         if (uap->val) {
1192                 error = copyin(uap->avalsize, &valsize, sizeof(valsize));
1193                 if (error)
1194                         return (error);
1195         } else {
1196                 valsize = 0;
1197         }
1198
1199         sopt.sopt_level = uap->level;
1200         sopt.sopt_name = uap->name;
1201         sopt.sopt_valsize = valsize;
1202         sopt.sopt_td = td;
1203         sopt.sopt_val = NULL;
1204
1205         if (sopt.sopt_valsize > SOMAXOPT_SIZE) /* unsigned */
1206                 return (EINVAL);
1207         if (uap->val) {
1208                 sopt.sopt_val = kmalloc(sopt.sopt_valsize, M_TEMP, M_WAITOK);
1209                 error = copyin(uap->val, sopt.sopt_val, sopt.sopt_valsize);
1210                 if (error)
1211                         goto out;
1212         }
1213
1214         error = kern_getsockopt(uap->s, &sopt);
1215         if (error)
1216                 goto out;
1217         valsize = sopt.sopt_valsize;
1218         error = copyout(&valsize, uap->avalsize, sizeof(valsize));
1219         if (error)
1220                 goto out;
1221         if (uap->val)
1222                 error = copyout(sopt.sopt_val, uap->val, sopt.sopt_valsize);
1223 out:
1224         if (uap->val)
1225                 kfree(sopt.sopt_val, M_TEMP);
1226         return (error);
1227 }
1228
1229 /*
1230  * The second argument to kern_getsockname() is a handle to a struct sockaddr.
1231  * This allows kern_getsockname() to return a pointer to an allocated struct
1232  * sockaddr which must be freed later with FREE().  The caller must
1233  * initialize *name to NULL.
1234  */
1235 int
1236 kern_getsockname(int s, struct sockaddr **name, int *namelen)
1237 {
1238         struct thread *td = curthread;
1239         struct proc *p = td->td_proc;
1240         struct file *fp;
1241         struct socket *so;
1242         struct sockaddr *sa = NULL;
1243         int error;
1244
1245         error = holdsock(p->p_fd, s, &fp);
1246         if (error)
1247                 return (error);
1248         if (*namelen < 0) {
1249                 fdrop(fp);
1250                 return (EINVAL);
1251         }
1252         so = (struct socket *)fp->f_data;
1253         error = so_pru_sockaddr(so, &sa);
1254         if (error == 0) {
1255                 if (sa == NULL) {
1256                         *namelen = 0;
1257                 } else {
1258                         *namelen = MIN(*namelen, sa->sa_len);
1259                         *name = sa;
1260                 }
1261         }
1262
1263         fdrop(fp);
1264         return (error);
1265 }
1266
1267 /*
1268  * getsockname_args(int fdes, caddr_t asa, int *alen)
1269  *
1270  * Get socket name.
1271  *
1272  * MPALMOSTSAFE
1273  */
1274 int
1275 sys_getsockname(struct getsockname_args *uap)
1276 {
1277         struct sockaddr *sa = NULL;
1278         int error, sa_len;
1279
1280         error = copyin(uap->alen, &sa_len, sizeof(sa_len));
1281         if (error)
1282                 return (error);
1283
1284         error = kern_getsockname(uap->fdes, &sa, &sa_len);
1285
1286         if (error == 0)
1287                 error = copyout(sa, uap->asa, sa_len);
1288         if (error == 0)
1289                 error = copyout(&sa_len, uap->alen, sizeof(*uap->alen));
1290         if (sa)
1291                 kfree(sa, M_SONAME);
1292         return (error);
1293 }
1294
1295 /*
1296  * The second argument to kern_getpeername() is a handle to a struct sockaddr.
1297  * This allows kern_getpeername() to return a pointer to an allocated struct
1298  * sockaddr which must be freed later with FREE().  The caller must
1299  * initialize *name to NULL.
1300  */
1301 int
1302 kern_getpeername(int s, struct sockaddr **name, int *namelen)
1303 {
1304         struct thread *td = curthread;
1305         struct proc *p = td->td_proc;
1306         struct file *fp;
1307         struct socket *so;
1308         struct sockaddr *sa = NULL;
1309         int error;
1310
1311         error = holdsock(p->p_fd, s, &fp);
1312         if (error)
1313                 return (error);
1314         if (*namelen < 0) {
1315                 fdrop(fp);
1316                 return (EINVAL);
1317         }
1318         so = (struct socket *)fp->f_data;
1319         if ((so->so_state & (SS_ISCONNECTED|SS_ISCONFIRMING)) == 0) {
1320                 fdrop(fp);
1321                 return (ENOTCONN);
1322         }
1323         error = so_pru_peeraddr(so, &sa);
1324         if (error == 0) {
1325                 if (sa == NULL) {
1326                         *namelen = 0;
1327                 } else {
1328                         *namelen = MIN(*namelen, sa->sa_len);
1329                         *name = sa;
1330                 }
1331         }
1332
1333         fdrop(fp);
1334         return (error);
1335 }
1336
1337 /*
1338  * getpeername_args(int fdes, caddr_t asa, int *alen)
1339  *
1340  * Get name of peer for connected socket.
1341  *
1342  * MPALMOSTSAFE
1343  */
1344 int
1345 sys_getpeername(struct getpeername_args *uap)
1346 {
1347         struct sockaddr *sa = NULL;
1348         int error, sa_len;
1349
1350         error = copyin(uap->alen, &sa_len, sizeof(sa_len));
1351         if (error)
1352                 return (error);
1353
1354         error = kern_getpeername(uap->fdes, &sa, &sa_len);
1355
1356         if (error == 0)
1357                 error = copyout(sa, uap->asa, sa_len);
1358         if (error == 0)
1359                 error = copyout(&sa_len, uap->alen, sizeof(*uap->alen));
1360         if (sa)
1361                 kfree(sa, M_SONAME);
1362         return (error);
1363 }
1364
1365 int
1366 getsockaddr(struct sockaddr **namp, caddr_t uaddr, size_t len)
1367 {
1368         struct sockaddr *sa;
1369         int error;
1370
1371         *namp = NULL;
1372         if (len > SOCK_MAXADDRLEN)
1373                 return ENAMETOOLONG;
1374         if (len < offsetof(struct sockaddr, sa_data[0]))
1375                 return EDOM;
1376         sa = kmalloc(len, M_SONAME, M_WAITOK);
1377         error = copyin(uaddr, sa, len);
1378         if (error) {
1379                 kfree(sa, M_SONAME);
1380         } else {
1381 #if BYTE_ORDER != BIG_ENDIAN
1382                 /*
1383                  * The bind(), connect(), and sendto() syscalls were not
1384                  * versioned for COMPAT_43.  Thus, this check must stay.
1385                  */
1386                 if (sa->sa_family == 0 && sa->sa_len < AF_MAX)
1387                         sa->sa_family = sa->sa_len;
1388 #endif
1389                 sa->sa_len = len;
1390                 *namp = sa;
1391         }
1392         return error;
1393 }
1394
1395 /*
1396  * Detach a mapped page and release resources back to the system.
1397  * We must release our wiring and if the object is ripped out
1398  * from under the vm_page we become responsible for freeing the
1399  * page.
1400  *
1401  * MPSAFE
1402  */
1403 static void
1404 sf_buf_mfree(void *arg)
1405 {
1406         struct sf_buf *sf = arg;
1407         vm_page_t m;
1408
1409         m = sf_buf_page(sf);
1410         if (sf_buf_free(sf)) {
1411                 /* sf invalid now */
1412                 vm_page_busy_wait(m, FALSE, "sockpgf");
1413                 vm_page_unwire(m, 0);
1414                 if (m->object == NULL &&
1415                     m->wire_count == 0 &&
1416                     (m->flags & PG_NEED_COMMIT) == 0) {
1417                         vm_page_free(m);
1418                 } else {
1419                         vm_page_wakeup(m);
1420                 }
1421         }
1422 }
1423
1424 /*
1425  * sendfile(2).
1426  * int sendfile(int fd, int s, off_t offset, size_t nbytes,
1427  *       struct sf_hdtr *hdtr, off_t *sbytes, int flags)
1428  *
1429  * Send a file specified by 'fd' and starting at 'offset' to a socket
1430  * specified by 's'. Send only 'nbytes' of the file or until EOF if
1431  * nbytes == 0. Optionally add a header and/or trailer to the socket
1432  * output. If specified, write the total number of bytes sent into *sbytes.
1433  *
1434  * In FreeBSD kern/uipc_syscalls.c,v 1.103, a bug was fixed that caused
1435  * the headers to count against the remaining bytes to be sent from
1436  * the file descriptor.  We may wish to implement a compatibility syscall
1437  * in the future.
1438  *
1439  * MPALMOSTSAFE
1440  */
1441 int
1442 sys_sendfile(struct sendfile_args *uap)
1443 {
1444         struct thread *td = curthread;
1445         struct proc *p = td->td_proc;
1446         struct file *fp;
1447         struct vnode *vp = NULL;
1448         struct sf_hdtr hdtr;
1449         struct iovec aiov[UIO_SMALLIOV], *iov = NULL;
1450         struct uio auio;
1451         struct mbuf *mheader = NULL;
1452         size_t hbytes = 0;
1453         size_t tbytes;
1454         off_t hdtr_size = 0;
1455         off_t sbytes;
1456         int error;
1457
1458         KKASSERT(p);
1459
1460         /*
1461          * Do argument checking. Must be a regular file in, stream
1462          * type and connected socket out, positive offset.
1463          */
1464         fp = holdfp(p->p_fd, uap->fd, FREAD);
1465         if (fp == NULL) {
1466                 return (EBADF);
1467         }
1468         if (fp->f_type != DTYPE_VNODE) {
1469                 fdrop(fp);
1470                 return (EINVAL);
1471         }
1472         vp = (struct vnode *)fp->f_data;
1473         vref(vp);
1474         fdrop(fp);
1475
1476         /*
1477          * If specified, get the pointer to the sf_hdtr struct for
1478          * any headers/trailers.
1479          */
1480         if (uap->hdtr) {
1481                 error = copyin(uap->hdtr, &hdtr, sizeof(hdtr));
1482                 if (error)
1483                         goto done;
1484                 /*
1485                  * Send any headers.
1486                  */
1487                 if (hdtr.headers) {
1488                         error = iovec_copyin(hdtr.headers, &iov, aiov,
1489                                              hdtr.hdr_cnt, &hbytes);
1490                         if (error)
1491                                 goto done;
1492                         auio.uio_iov = iov;
1493                         auio.uio_iovcnt = hdtr.hdr_cnt;
1494                         auio.uio_offset = 0;
1495                         auio.uio_segflg = UIO_USERSPACE;
1496                         auio.uio_rw = UIO_WRITE;
1497                         auio.uio_td = td;
1498                         auio.uio_resid = hbytes;
1499
1500                         mheader = m_uiomove(&auio);
1501
1502                         iovec_free(&iov, aiov);
1503                         if (mheader == NULL)
1504                                 goto done;
1505                 }
1506         }
1507
1508         error = kern_sendfile(vp, uap->s, uap->offset, uap->nbytes, mheader,
1509                               &sbytes, uap->flags);
1510         if (error)
1511                 goto done;
1512
1513         /*
1514          * Send trailers. Wimp out and use writev(2).
1515          */
1516         if (uap->hdtr != NULL && hdtr.trailers != NULL) {
1517                 error = iovec_copyin(hdtr.trailers, &iov, aiov,
1518                                      hdtr.trl_cnt, &auio.uio_resid);
1519                 if (error)
1520                         goto done;
1521                 auio.uio_iov = iov;
1522                 auio.uio_iovcnt = hdtr.trl_cnt;
1523                 auio.uio_offset = 0;
1524                 auio.uio_segflg = UIO_USERSPACE;
1525                 auio.uio_rw = UIO_WRITE;
1526                 auio.uio_td = td;
1527
1528                 error = kern_sendmsg(uap->s, NULL, &auio, NULL, 0, &tbytes);
1529
1530                 iovec_free(&iov, aiov);
1531                 if (error)
1532                         goto done;
1533                 hdtr_size += tbytes;    /* trailer bytes successfully sent */
1534         }
1535
1536 done:
1537         if (vp)
1538                 vrele(vp);
1539         if (uap->sbytes != NULL) {
1540                 sbytes += hdtr_size;
1541                 copyout(&sbytes, uap->sbytes, sizeof(off_t));
1542         }
1543         return (error);
1544 }
1545
1546 int
1547 kern_sendfile(struct vnode *vp, int sfd, off_t offset, size_t nbytes,
1548               struct mbuf *mheader, off_t *sbytes, int flags)
1549 {
1550         struct thread *td = curthread;
1551         struct proc *p = td->td_proc;
1552         struct vm_object *obj;
1553         struct socket *so;
1554         struct file *fp;
1555         struct mbuf *m, *mp;
1556         struct sf_buf *sf;
1557         struct vm_page *pg;
1558         off_t off, xfsize;
1559         off_t hbytes = 0;
1560         int error = 0;
1561
1562         if (vp->v_type != VREG) {
1563                 error = EINVAL;
1564                 goto done0;
1565         }
1566         if ((obj = vp->v_object) == NULL) {
1567                 error = EINVAL;
1568                 goto done0;
1569         }
1570         error = holdsock(p->p_fd, sfd, &fp);
1571         if (error)
1572                 goto done0;
1573         so = (struct socket *)fp->f_data;
1574         if (so->so_type != SOCK_STREAM) {
1575                 error = EINVAL;
1576                 goto done;
1577         }
1578         if ((so->so_state & SS_ISCONNECTED) == 0) {
1579                 error = ENOTCONN;
1580                 goto done;
1581         }
1582         if (offset < 0) {
1583                 error = EINVAL;
1584                 goto done;
1585         }
1586
1587         *sbytes = 0;
1588         /*
1589          * Protect against multiple writers to the socket.
1590          */
1591         ssb_lock(&so->so_snd, M_WAITOK);
1592
1593         /*
1594          * Loop through the pages in the file, starting with the requested
1595          * offset. Get a file page (do I/O if necessary), map the file page
1596          * into an sf_buf, attach an mbuf header to the sf_buf, and queue
1597          * it on the socket.
1598          */
1599         for (off = offset; ; off += xfsize, *sbytes += xfsize + hbytes) {
1600                 vm_pindex_t pindex;
1601                 vm_offset_t pgoff;
1602                 int space;
1603
1604                 pindex = OFF_TO_IDX(off);
1605 retry_lookup:
1606                 /*
1607                  * Calculate the amount to transfer. Not to exceed a page,
1608                  * the EOF, or the passed in nbytes.
1609                  */
1610                 xfsize = vp->v_filesize - off;
1611                 if (xfsize > PAGE_SIZE)
1612                         xfsize = PAGE_SIZE;
1613                 pgoff = (vm_offset_t)(off & PAGE_MASK);
1614                 if (PAGE_SIZE - pgoff < xfsize)
1615                         xfsize = PAGE_SIZE - pgoff;
1616                 if (nbytes && xfsize > (nbytes - *sbytes))
1617                         xfsize = nbytes - *sbytes;
1618                 if (xfsize <= 0)
1619                         break;
1620                 /*
1621                  * Optimize the non-blocking case by looking at the socket space
1622                  * before going to the extra work of constituting the sf_buf.
1623                  */
1624                 if ((fp->f_flag & FNONBLOCK) &&
1625                     ssb_space_prealloc(&so->so_snd) <= 0) {
1626                         if (so->so_state & SS_CANTSENDMORE)
1627                                 error = EPIPE;
1628                         else
1629                                 error = EAGAIN;
1630                         ssb_unlock(&so->so_snd);
1631                         goto done;
1632                 }
1633                 /*
1634                  * Attempt to look up the page.  
1635                  *
1636                  *      Allocate if not found, wait and loop if busy, then
1637                  *      wire the page.  critical section protection is
1638                  *      required to maintain the object association (an
1639                  *      interrupt can free the page) through to the
1640                  *      vm_page_wire() call.
1641                  */
1642                 vm_object_hold(obj);
1643                 pg = vm_page_lookup_busy_try(obj, pindex, TRUE, &error);
1644                 if (error) {
1645                         vm_page_sleep_busy(pg, TRUE, "sfpbsy");
1646                         vm_object_drop(obj);
1647                         goto retry_lookup;
1648                 }
1649                 if (pg == NULL) {
1650                         pg = vm_page_alloc(obj, pindex, VM_ALLOC_NORMAL |
1651                                                         VM_ALLOC_NULL_OK);
1652                         if (pg == NULL) {
1653                                 vm_wait(0);
1654                                 vm_object_drop(obj);
1655                                 goto retry_lookup;
1656                         }
1657                 }
1658                 vm_page_wire(pg);
1659                 vm_object_drop(obj);
1660
1661                 /*
1662                  * If page is not valid for what we need, initiate I/O
1663                  */
1664
1665                 if (!pg->valid || !vm_page_is_valid(pg, pgoff, xfsize)) {
1666                         struct uio auio;
1667                         struct iovec aiov;
1668                         int bsize;
1669
1670                         /*
1671                          * Ensure that our page is still around when the I/O 
1672                          * completes.
1673                          *
1674                          * Ensure that our page is not modified while part of
1675                          * a mbuf as this could mess up tcp checksums, DMA,
1676                          * etc (XXX NEEDS WORK).  The softbusy is supposed to
1677                          * help here but it actually doesn't.
1678                          *
1679                          * XXX THIS HAS MULTIPLE PROBLEMS.  The underlying
1680                          *     VM pages are not protected by the soft-busy
1681                          *     unless we vm_page_protect... READ them, and
1682                          *     they STILL aren't protected against
1683                          *     modification via the buffer cache (VOP_WRITE).
1684                          *
1685                          *     Fixing the second issue is particularly
1686                          *     difficult.
1687                          *
1688                          * XXX We also can't soft-busy anyway because it can
1689                          *     deadlock against the syncer doing a vfs_msync(),
1690                          *     vfs_msync->vmntvnodesca->vfs_msync_scan2->
1691                          *     vm_object_page_clean->(scan)-> ... page
1692                          *     busy-wait.
1693                          */
1694                         /*vm_page_io_start(pg);*/
1695                         vm_page_wakeup(pg);
1696
1697                         /*
1698                          * Get the page from backing store.
1699                          */
1700                         bsize = vp->v_mount->mnt_stat.f_iosize;
1701                         auio.uio_iov = &aiov;
1702                         auio.uio_iovcnt = 1;
1703                         aiov.iov_base = 0;
1704                         aiov.iov_len = MAXBSIZE;
1705                         auio.uio_resid = MAXBSIZE;
1706                         auio.uio_offset = trunc_page(off);
1707                         auio.uio_segflg = UIO_NOCOPY;
1708                         auio.uio_rw = UIO_READ;
1709                         auio.uio_td = td;
1710                         vn_lock(vp, LK_SHARED | LK_RETRY);
1711                         error = VOP_READ(vp, &auio, 
1712                                     IO_VMIO | ((MAXBSIZE / bsize) << 16),
1713                                     td->td_ucred);
1714                         vn_unlock(vp);
1715                         vm_page_flag_clear(pg, PG_ZERO);
1716                         vm_page_busy_wait(pg, FALSE, "sockpg");
1717                         /*vm_page_io_finish(pg);*/
1718                         if (error) {
1719                                 vm_page_unwire(pg, 0);
1720                                 vm_page_wakeup(pg);
1721                                 vm_page_try_to_free(pg);
1722                                 ssb_unlock(&so->so_snd);
1723                                 goto done;
1724                         }
1725                 }
1726
1727
1728                 /*
1729                  * Get a sendfile buf. We usually wait as long as necessary,
1730                  * but this wait can be interrupted.
1731                  */
1732                 if ((sf = sf_buf_alloc(pg)) == NULL) {
1733                         vm_page_unwire(pg, 0);
1734                         vm_page_wakeup(pg);
1735                         vm_page_try_to_free(pg);
1736                         ssb_unlock(&so->so_snd);
1737                         error = EINTR;
1738                         goto done;
1739                 }
1740                 vm_page_wakeup(pg);
1741
1742                 /*
1743                  * Get an mbuf header and set it up as having external storage.
1744                  */
1745                 MGETHDR(m, MB_WAIT, MT_DATA);
1746                 if (m == NULL) {
1747                         error = ENOBUFS;
1748                         sf_buf_free(sf);
1749                         ssb_unlock(&so->so_snd);
1750                         goto done;
1751                 }
1752
1753                 m->m_ext.ext_free = sf_buf_mfree;
1754                 m->m_ext.ext_ref = sf_buf_ref;
1755                 m->m_ext.ext_arg = sf;
1756                 m->m_ext.ext_buf = (void *)sf_buf_kva(sf);
1757                 m->m_ext.ext_size = PAGE_SIZE;
1758                 m->m_data = (char *)sf_buf_kva(sf) + pgoff;
1759                 m->m_flags |= M_EXT;
1760                 m->m_pkthdr.len = m->m_len = xfsize;
1761                 KKASSERT((m->m_flags & (M_EXT_CLUSTER)) == 0);
1762
1763                 if (mheader != NULL) {
1764                         hbytes = mheader->m_pkthdr.len;
1765                         mheader->m_pkthdr.len += m->m_pkthdr.len;
1766                         m_cat(mheader, m);
1767                         m = mheader;
1768                         mheader = NULL;
1769                 } else
1770                         hbytes = 0;
1771
1772                 /*
1773                  * Add the buffer to the socket buffer chain.
1774                  */
1775                 crit_enter();
1776 retry_space:
1777                 /*
1778                  * Make sure that the socket is still able to take more data.
1779                  * CANTSENDMORE being true usually means that the connection
1780                  * was closed. so_error is true when an error was sensed after
1781                  * a previous send.
1782                  * The state is checked after the page mapping and buffer
1783                  * allocation above since those operations may block and make
1784                  * any socket checks stale. From this point forward, nothing
1785                  * blocks before the pru_send (or more accurately, any blocking
1786                  * results in a loop back to here to re-check).
1787                  */
1788                 if ((so->so_state & SS_CANTSENDMORE) || so->so_error) {
1789                         if (so->so_state & SS_CANTSENDMORE) {
1790                                 error = EPIPE;
1791                         } else {
1792                                 error = so->so_error;
1793                                 so->so_error = 0;
1794                         }
1795                         m_freem(m);
1796                         ssb_unlock(&so->so_snd);
1797                         crit_exit();
1798                         goto done;
1799                 }
1800                 /*
1801                  * Wait for socket space to become available. We do this just
1802                  * after checking the connection state above in order to avoid
1803                  * a race condition with ssb_wait().
1804                  */
1805                 space = ssb_space_prealloc(&so->so_snd);
1806                 if (space < m->m_pkthdr.len && space < so->so_snd.ssb_lowat) {
1807                         if (fp->f_flag & FNONBLOCK) {
1808                                 m_freem(m);
1809                                 ssb_unlock(&so->so_snd);
1810                                 crit_exit();
1811                                 error = EAGAIN;
1812                                 goto done;
1813                         }
1814                         error = ssb_wait(&so->so_snd);
1815                         /*
1816                          * An error from ssb_wait usually indicates that we've
1817                          * been interrupted by a signal. If we've sent anything
1818                          * then return bytes sent, otherwise return the error.
1819                          */
1820                         if (error) {
1821                                 m_freem(m);
1822                                 ssb_unlock(&so->so_snd);
1823                                 crit_exit();
1824                                 goto done;
1825                         }
1826                         goto retry_space;
1827                 }
1828
1829                 for (mp = m; mp != NULL; mp = mp->m_next)
1830                         ssb_preallocstream(&so->so_snd, mp);
1831                 if (use_sendfile_async)
1832                         error = so_pru_senda(so, 0, m, NULL, NULL, td);
1833                 else
1834                         error = so_pru_send(so, 0, m, NULL, NULL, td);
1835
1836                 crit_exit();
1837                 if (error) {
1838                         ssb_unlock(&so->so_snd);
1839                         goto done;
1840                 }
1841         }
1842         if (mheader != NULL) {
1843                 *sbytes += mheader->m_pkthdr.len;
1844
1845                 for (mp = mheader; mp != NULL; mp = mp->m_next)
1846                         ssb_preallocstream(&so->so_snd, mp);
1847                 if (use_sendfile_async)
1848                         error = so_pru_senda(so, 0, mheader, NULL, NULL, td);
1849                 else
1850                         error = so_pru_send(so, 0, mheader, NULL, NULL, td);
1851
1852                 mheader = NULL;
1853         }
1854         ssb_unlock(&so->so_snd);
1855
1856 done:
1857         fdrop(fp);
1858 done0:
1859         if (mheader != NULL)
1860                 m_freem(mheader);
1861         return (error);
1862 }
1863
1864 /*
1865  * MPALMOSTSAFE
1866  */
1867 int
1868 sys_sctp_peeloff(struct sctp_peeloff_args *uap)
1869 {
1870 #ifdef SCTP
1871         struct thread *td = curthread;
1872         struct filedesc *fdp = td->td_proc->p_fd;
1873         struct file *lfp = NULL;
1874         struct file *nfp = NULL;
1875         int error;
1876         struct socket *head, *so;
1877         caddr_t assoc_id;
1878         int fd;
1879         short fflag;            /* type must match fp->f_flag */
1880
1881         assoc_id = uap->name;
1882         error = holdsock(td->td_proc->p_fd, uap->sd, &lfp);
1883         if (error)
1884                 return (error);
1885
1886         crit_enter();
1887         head = (struct socket *)lfp->f_data;
1888         error = sctp_can_peel_off(head, assoc_id);
1889         if (error) {
1890                 crit_exit();
1891                 goto done;
1892         }
1893         /*
1894          * At this point we know we do have a assoc to pull
1895          * we proceed to get the fd setup. This may block
1896          * but that is ok.
1897          */
1898
1899         fflag = lfp->f_flag;
1900         error = falloc(td->td_lwp, &nfp, &fd);
1901         if (error) {
1902                 /*
1903                  * Probably ran out of file descriptors. Put the
1904                  * unaccepted connection back onto the queue and
1905                  * do another wakeup so some other process might
1906                  * have a chance at it.
1907                  */
1908                 crit_exit();
1909                 goto done;
1910         }
1911         uap->sysmsg_iresult = fd;
1912
1913         so = sctp_get_peeloff(head, assoc_id, &error);
1914         if (so == NULL) {
1915                 /*
1916                  * Either someone else peeled it off OR
1917                  * we can't get a socket.
1918                  */
1919                 goto noconnection;
1920         }
1921         soreference(so);                        /* reference needed */
1922         soclrstate(so, SS_NOFDREF | SS_COMP);   /* when clearing NOFDREF */
1923         so->so_head = NULL;
1924         if (head->so_sigio != NULL)
1925                 fsetown(fgetown(&head->so_sigio), &so->so_sigio);
1926
1927         nfp->f_type = DTYPE_SOCKET;
1928         nfp->f_flag = fflag;
1929         nfp->f_ops = &socketops;
1930         nfp->f_data = so;
1931
1932 noconnection:
1933         /*
1934          * Assign the file pointer to the reserved descriptor, or clear
1935          * the reserved descriptor if an error occured.
1936          */
1937         if (error)
1938                 fsetfd(fdp, NULL, fd);
1939         else
1940                 fsetfd(fdp, nfp, fd);
1941         crit_exit();
1942         /*
1943          * Release explicitly held references before returning.
1944          */
1945 done:
1946         if (nfp != NULL)
1947                 fdrop(nfp);
1948         fdrop(lfp);
1949         return (error);
1950 #else /* SCTP */
1951         return(EOPNOTSUPP);
1952 #endif /* SCTP */
1953 }