Create an emulation/43bsd directory and move the recently modified
[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. All advertising materials mentioning features or use of this software
17  *    must display the following acknowledgement:
18  *      This product includes software developed by the University of
19  *      California, Berkeley and its contributors.
20  * 4. Neither the name of the University nor the names of its contributors
21  *    may be used to endorse or promote products derived from this software
22  *    without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  *
36  *      @(#)uipc_syscalls.c     8.4 (Berkeley) 2/21/94
37  * $FreeBSD: src/sys/kern/uipc_syscalls.c,v 1.65.2.17 2003/04/04 17:11:16 tegge Exp $
38  * $DragonFly: src/sys/kern/uipc_syscalls.c,v 1.14 2003/09/12 00:43:30 daver Exp $
39  */
40
41 #include "opt_compat.h"
42 #include "opt_ktrace.h"
43
44 #include <sys/param.h>
45 #include <sys/systm.h>
46 #include <sys/kernel.h>
47 #include <sys/sysproto.h>
48 #include <sys/malloc.h>
49 #include <sys/filedesc.h>
50 #include <sys/event.h>
51 #include <sys/proc.h>
52 #include <sys/fcntl.h>
53 #include <sys/file.h>
54 #include <sys/filio.h>
55 #include <sys/kern_syscall.h>
56 #include <sys/mbuf.h>
57 #include <sys/protosw.h>
58 #include <sys/socket.h>
59 #include <sys/socketvar.h>
60 #include <sys/signalvar.h>
61 #include <sys/uio.h>
62 #include <sys/vnode.h>
63 #include <sys/lock.h>
64 #include <sys/mount.h>
65 #ifdef KTRACE
66 #include <sys/ktrace.h>
67 #endif
68 #include <vm/vm.h>
69 #include <vm/vm_object.h>
70 #include <vm/vm_page.h>
71 #include <vm/vm_pageout.h>
72 #include <vm/vm_kern.h>
73 #include <vm/vm_extern.h>
74 #include <sys/file2.h>
75
76 #if defined(COMPAT_43)
77 #include <emulation/43bsd/43bsd_socket.h>
78 #endif /* COMPAT_43 */
79
80 static void sf_buf_init(void *arg);
81 SYSINIT(sock_sf, SI_SUB_MBUF, SI_ORDER_ANY, sf_buf_init, NULL)
82
83 static int sendit(int s, struct msghdr *mp, int flags, int *res);
84 static int recvit(int s, struct msghdr *mp, caddr_t namelenp, int *res);
85   
86 static int do_sendfile(struct sendfile_args *uap, int compat);
87
88 static SLIST_HEAD(, sf_buf) sf_freelist;
89 static vm_offset_t sf_base;
90 static struct sf_buf *sf_bufs;
91 static int sf_buf_alloc_want;
92
93 /*
94  * System call interface to the socket abstraction.
95  */
96 #if defined(COMPAT_43) || defined(COMPAT_SUNOS)
97 #define COMPAT_OLDSOCK
98 #endif
99
100 extern  struct fileops socketops;
101
102 /*
103  * socket_args(int domain, int type, int protocol)
104  */
105 int
106 socket(struct socket_args *uap)
107 {
108         struct thread *td = curthread;
109         struct proc *p = td->td_proc;
110         struct filedesc *fdp;
111         struct socket *so;
112         struct file *fp;
113         int fd, error;
114
115         KKASSERT(p);
116         fdp = p->p_fd;
117
118         error = falloc(p, &fp, &fd);
119         if (error)
120                 return (error);
121         fhold(fp);
122         error = socreate(uap->domain, &so, uap->type, uap->protocol, td);
123         if (error) {
124                 if (fdp->fd_ofiles[fd] == fp) {
125                         fdp->fd_ofiles[fd] = NULL;
126                         fdrop(fp, td);
127                 }
128         } else {
129                 fp->f_data = (caddr_t)so;
130                 fp->f_flag = FREAD|FWRITE;
131                 fp->f_ops = &socketops;
132                 fp->f_type = DTYPE_SOCKET;
133                 uap->sysmsg_result = fd;
134         }
135         fdrop(fp, td);
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, td);
153         return (error);
154 }
155
156 /*
157  * bind_args(int s, caddr_t name, int namelen)
158  */
159 int
160 bind(struct bind_args *uap)
161 {
162         struct sockaddr *sa;
163         int error;
164
165         error = getsockaddr(&sa, uap->name, uap->namelen);
166         if (error)
167                 return (error);
168         error = kern_bind(uap->s, sa);
169         FREE(sa, M_SONAME);
170
171         return (error);
172 }
173
174 int
175 kern_listen(int s, int backlog)
176 {
177         struct thread *td = curthread;
178         struct proc *p = td->td_proc;
179         struct file *fp;
180         int error;
181
182         KKASSERT(p);
183         error = holdsock(p->p_fd, s, &fp);
184         if (error)
185                 return (error);
186         error = solisten((struct socket *)fp->f_data, backlog, td);
187         fdrop(fp, td);
188         return(error);
189 }
190
191 /*
192  * listen_args(int s, int backlog)
193  */
194 int
195 listen(struct listen_args *uap)
196 {
197         int error;
198
199         error = kern_listen(uap->s, uap->backlog);
200         return (error);
201 }
202
203 /*
204  * The second argument to kern_accept() is a handle to a struct sockaddr.
205  * This allows kern_accept() to return a pointer to an allocated struct
206  * sockaddr which must be freed later with FREE().  The caller must
207  * initialize *name to NULL.
208  */
209 int
210 kern_accept(int s, struct sockaddr **name, int *namelen, int *res)
211 {
212         struct thread *td = curthread;
213         struct proc *p = td->td_proc;
214         struct filedesc *fdp = p->p_fd;
215         struct file *lfp = NULL;
216         struct file *nfp = NULL;
217         struct sockaddr *sa;
218         int error, s1;
219         struct socket *head, *so;
220         int fd;
221         u_int fflag;            /* type must match fp->f_flag */
222         int tmp;
223
224         if (name && namelen && *namelen < 0)
225                 return (EINVAL);
226
227         error = holdsock(fdp, s, &lfp);
228         if (error)
229                 return (error);
230         s1 = splnet();
231         head = (struct socket *)lfp->f_data;
232         if ((head->so_options & SO_ACCEPTCONN) == 0) {
233                 splx(s1);
234                 error = EINVAL;
235                 goto done;
236         }
237         while (TAILQ_EMPTY(&head->so_comp) && head->so_error == 0) {
238                 if (head->so_state & SS_CANTRCVMORE) {
239                         head->so_error = ECONNABORTED;
240                         break;
241                 }
242                 if ((head->so_state & SS_NBIO) != 0) {
243                         head->so_error = EWOULDBLOCK;
244                         break;
245                 }
246                 error = tsleep((caddr_t)&head->so_timeo, PCATCH, "accept", 0);
247                 if (error) {
248                         splx(s1);
249                         goto done;
250                 }
251         }
252         if (head->so_error) {
253                 error = head->so_error;
254                 head->so_error = 0;
255                 splx(s1);
256                 goto done;
257         }
258
259         /*
260          * At this point we know that there is at least one connection
261          * ready to be accepted. Remove it from the queue prior to
262          * allocating the file descriptor for it since falloc() may
263          * block allowing another process to accept the connection
264          * instead.
265          */
266         so = TAILQ_FIRST(&head->so_comp);
267         TAILQ_REMOVE(&head->so_comp, so, so_list);
268         head->so_qlen--;
269
270         fflag = lfp->f_flag;
271         error = falloc(p, &nfp, &fd);
272         if (error) {
273                 /*
274                  * Probably ran out of file descriptors. Put the
275                  * unaccepted connection back onto the queue and
276                  * do another wakeup so some other process might
277                  * have a chance at it.
278                  */
279                 TAILQ_INSERT_HEAD(&head->so_comp, so, so_list);
280                 head->so_qlen++;
281                 wakeup_one(&head->so_timeo);
282                 splx(s1);
283                 goto done;
284         }
285         fhold(nfp);
286         *res = fd;
287
288         /* connection has been removed from the listen queue */
289         KNOTE(&head->so_rcv.sb_sel.si_note, 0);
290
291         so->so_state &= ~SS_COMP;
292         so->so_head = NULL;
293         if (head->so_sigio != NULL)
294                 fsetown(fgetown(head->so_sigio), &so->so_sigio);
295
296         nfp->f_data = (caddr_t)so;
297         nfp->f_flag = fflag;
298         nfp->f_ops = &socketops;
299         nfp->f_type = DTYPE_SOCKET;
300         /* Sync socket nonblocking/async state with file flags */
301         tmp = fflag & FNONBLOCK;
302         (void) fo_ioctl(nfp, FIONBIO, (caddr_t)&tmp, td);
303         tmp = fflag & FASYNC;
304         (void) fo_ioctl(nfp, FIOASYNC, (caddr_t)&tmp, td);
305
306         sa = NULL;
307         error = soaccept(so, &sa);
308
309         /*
310          * Set the returned name and namelen as applicable.  Set the returned
311          * namelen to 0 for older code which might ignore the return value
312          * from accept.
313          */
314         if (error == 0) {
315                 if (sa && name && namelen) {
316                         if (*namelen > sa->sa_len)
317                                 *namelen = sa->sa_len;
318                         *name = sa;
319                 } else {
320                         if (sa)
321                                 FREE(sa, M_SONAME);
322                 }
323         }
324
325         /*
326          * close the new descriptor, assuming someone hasn't ripped it
327          * out from under us.  Note that *res is normally ignored if an
328          * error is returned but a syscall message will still have access
329          * to the result code.
330          */
331         if (error) {
332                 *res = -1;
333                 if (fdp->fd_ofiles[fd] == nfp) {
334                         fdp->fd_ofiles[fd] = NULL;
335                         fdrop(nfp, td);
336                 }
337         }
338         splx(s1);
339
340         /*
341          * Release explicitly held references before returning.
342          */
343 done:
344         if (nfp != NULL)
345                 fdrop(nfp, td);
346         fdrop(lfp, td);
347         return (error);
348 }
349
350 /*
351  * accept_args(int s, caddr_t name, int *anamelen)
352  */
353 int
354 accept(struct accept_args *uap)
355 {
356         struct sockaddr *sa = NULL;
357         int sa_len;
358         int error;
359
360         if (uap->name) {
361                 error = copyin(uap->anamelen, &sa_len, sizeof(sa_len));
362                 if (error)
363                         return (error);
364
365                 error = kern_accept(uap->s, &sa, &sa_len, &uap->sysmsg_result);
366
367                 if (error == 0)
368                         error = copyout(sa, uap->name, sa_len);
369                 if (error == 0) {
370                         error = copyout(&sa_len, uap->anamelen,
371                             sizeof(*uap->anamelen));
372                 }
373                 if (sa)
374                         FREE(sa, M_SONAME);
375         } else {
376                 error = kern_accept(uap->s, NULL, 0, &uap->sysmsg_result);
377         }
378         return (error);
379 }
380
381 int
382 kern_connect(int s, struct sockaddr *sa)
383 {
384         struct thread *td = curthread;
385         struct proc *p = td->td_proc;
386         struct file *fp;
387         struct socket *so;
388         int error;
389
390         error = holdsock(p->p_fd, s, &fp);
391         if (error)
392                 return (error);
393         so = (struct socket *)fp->f_data;
394         if ((so->so_state & SS_NBIO) && (so->so_state & SS_ISCONNECTING)) {
395                 error = EALREADY;
396                 goto done;
397         }
398         error = soconnect(so, sa, td);
399         if (error)
400                 goto bad;
401         if ((so->so_state & SS_NBIO) && (so->so_state & SS_ISCONNECTING)) {
402                 error = EINPROGRESS;
403                 goto done;
404         }
405         s = splnet();
406         while ((so->so_state & SS_ISCONNECTING) && so->so_error == 0) {
407                 error = tsleep((caddr_t)&so->so_timeo, PCATCH, "connec", 0);
408                 if (error)
409                         break;
410         }
411         if (error == 0) {
412                 error = so->so_error;
413                 so->so_error = 0;
414         }
415         splx(s);
416 bad:
417         so->so_state &= ~SS_ISCONNECTING;
418         if (error == ERESTART)
419                 error = EINTR;
420 done:
421         fdrop(fp, td);
422         return (error);
423 }
424
425 /*
426  * connect_args(int s, caddr_t name, int namelen)
427  */
428 int
429 connect(struct connect_args *uap)
430 {
431         struct sockaddr *sa;
432         int error;
433
434         error = getsockaddr(&sa, uap->name, uap->namelen);
435         if (error)
436                 return (error);
437         error = kern_connect(uap->s, sa);
438         FREE(sa, M_SONAME);
439
440         return (error);
441 }
442
443 int
444 kern_socketpair(int domain, int type, int protocol, int *sv)
445 {
446         struct thread *td = curthread;
447         struct proc *p = td->td_proc;
448         struct filedesc *fdp;
449         struct file *fp1, *fp2;
450         struct socket *so1, *so2;
451         int fd, error;
452
453         KKASSERT(p);
454         fdp = p->p_fd;
455         error = socreate(domain, &so1, type, protocol, td);
456         if (error)
457                 return (error);
458         error = socreate(domain, &so2, type, protocol, td);
459         if (error)
460                 goto free1;
461         error = falloc(p, &fp1, &fd);
462         if (error)
463                 goto free2;
464         fhold(fp1);
465         sv[0] = fd;
466         fp1->f_data = (caddr_t)so1;
467         error = falloc(p, &fp2, &fd);
468         if (error)
469                 goto free3;
470         fhold(fp2);
471         fp2->f_data = (caddr_t)so2;
472         sv[1] = fd;
473         error = soconnect2(so1, so2);
474         if (error)
475                 goto free4;
476         if (type == SOCK_DGRAM) {
477                 /*
478                  * Datagram socket connection is asymmetric.
479                  */
480                  error = soconnect2(so2, so1);
481                  if (error)
482                         goto free4;
483         }
484         fp1->f_flag = fp2->f_flag = FREAD|FWRITE;
485         fp1->f_ops = fp2->f_ops = &socketops;
486         fp1->f_type = fp2->f_type = DTYPE_SOCKET;
487         fdrop(fp1, td);
488         fdrop(fp2, td);
489         return (error);
490 free4:
491         if (fdp->fd_ofiles[sv[1]] == fp2) {
492                 fdp->fd_ofiles[sv[1]] = NULL;
493                 fdrop(fp2, td);
494         }
495         fdrop(fp2, td);
496 free3:
497         if (fdp->fd_ofiles[sv[0]] == fp1) {
498                 fdp->fd_ofiles[sv[0]] = NULL;
499                 fdrop(fp1, td);
500         }
501         fdrop(fp1, td);
502 free2:
503         (void)soclose(so2);
504 free1:
505         (void)soclose(so1);
506         return (error);
507 }
508
509 /*
510  * socketpair(int domain, int type, int protocol, int *rsv)
511  */
512 int
513 socketpair(struct socketpair_args *uap)
514 {
515         int error, sockv[2];
516
517         error = kern_socketpair(uap->domain, uap->type, uap->protocol, sockv);
518
519         if (error == 0)
520                 error = copyout(sockv, uap->rsv, sizeof(sockv));
521         return (error);
522 }
523
524 static int
525 sendit(int s, struct msghdr *mp, int flags, int *res)
526 {
527         struct thread *td = curthread;
528         struct proc *p = td->td_proc;
529         struct file *fp;
530         struct uio auio;
531         struct iovec *iov;
532         int i;
533         struct mbuf *control;
534         struct sockaddr *to;
535         int len, error;
536         struct socket *so;
537 #ifdef KTRACE
538         struct iovec *ktriov = NULL;
539         struct uio ktruio;
540 #endif
541
542         error = holdsock(p->p_fd, s, &fp);
543         if (error)
544                 return (error);
545         auio.uio_iov = mp->msg_iov;
546         auio.uio_iovcnt = mp->msg_iovlen;
547         auio.uio_segflg = UIO_USERSPACE;
548         auio.uio_rw = UIO_WRITE;
549         auio.uio_td = td;
550         auio.uio_offset = 0;                    /* XXX */
551         auio.uio_resid = 0;
552         iov = mp->msg_iov;
553         for (i = 0; i < mp->msg_iovlen; i++, iov++) {
554                 if ((auio.uio_resid += iov->iov_len) < 0) {
555                         fdrop(fp, td);
556                         return (EINVAL);
557                 }
558         }
559         if (mp->msg_name) {
560                 error = getsockaddr(&to, mp->msg_name, mp->msg_namelen);
561                 if (error) {
562                         fdrop(fp, td);
563                         return (error);
564                 }
565         } else {
566                 to = 0;
567         }
568         if (mp->msg_control) {
569                 if (mp->msg_controllen < sizeof(struct cmsghdr)
570 #ifdef COMPAT_OLDSOCK
571                     && mp->msg_flags != MSG_COMPAT
572 #endif
573                 ) {
574                         error = EINVAL;
575                         goto bad;
576                 }
577                 error = sockargs(&control, mp->msg_control,
578                     mp->msg_controllen, MT_CONTROL);
579                 if (error)
580                         goto bad;
581 #ifdef COMPAT_OLDSOCK
582                 if (mp->msg_flags == MSG_COMPAT) {
583                         struct cmsghdr *cm;
584
585                         M_PREPEND(control, sizeof(*cm), M_WAIT);
586                         if (control == 0) {
587                                 error = ENOBUFS;
588                                 goto bad;
589                         } else {
590                                 cm = mtod(control, struct cmsghdr *);
591                                 cm->cmsg_len = control->m_len;
592                                 cm->cmsg_level = SOL_SOCKET;
593                                 cm->cmsg_type = SCM_RIGHTS;
594                         }
595                 }
596 #endif
597         } else {
598                 control = 0;
599         }
600 #ifdef KTRACE
601         if (KTRPOINT(td, KTR_GENIO)) {
602                 int iovlen = auio.uio_iovcnt * sizeof (struct iovec);
603
604                 MALLOC(ktriov, struct iovec *, iovlen, M_TEMP, M_WAITOK);
605                 bcopy((caddr_t)auio.uio_iov, (caddr_t)ktriov, iovlen);
606                 ktruio = auio;
607         }
608 #endif
609         len = auio.uio_resid;
610         so = (struct socket *)fp->f_data;
611         error = so->so_proto->pr_usrreqs->pru_sosend(so, to, &auio, 0, control,
612                                                      flags, td);
613         if (error) {
614                 if (auio.uio_resid != len && (error == ERESTART ||
615                     error == EINTR || error == EWOULDBLOCK))
616                         error = 0;
617                 if (error == EPIPE)
618                         psignal(p, SIGPIPE);
619         }
620         if (error == 0)
621                 *res  = len - auio.uio_resid;
622 #ifdef KTRACE
623         if (ktriov != NULL) {
624                 if (error == 0) {
625                         ktruio.uio_iov = ktriov;
626                         ktruio.uio_resid = *res;
627                         ktrgenio(p->p_tracep, s, UIO_WRITE, &ktruio, error);
628                 }
629                 FREE(ktriov, M_TEMP);
630         }
631 #endif
632 bad:
633         fdrop(fp, td);
634         if (to)
635                 FREE(to, M_SONAME);
636         return (error);
637 }
638
639 /*
640  * sendto_args(int s, caddr_t buf, size_t len, int flags, caddr_t to, int tolen)
641  */
642 int
643 sendto(struct sendto_args *uap)
644 {
645         struct msghdr msg;
646         struct iovec aiov;
647
648         msg.msg_name = uap->to;
649         msg.msg_namelen = uap->tolen;
650         msg.msg_iov = &aiov;
651         msg.msg_iovlen = 1;
652         msg.msg_control = 0;
653 #ifdef COMPAT_OLDSOCK
654         msg.msg_flags = 0;
655 #endif
656         aiov.iov_base = uap->buf;
657         aiov.iov_len = uap->len;
658         return (sendit(uap->s, &msg, uap->flags, &uap->sysmsg_result));
659 }
660
661 #ifdef COMPAT_OLDSOCK
662 /*
663  * osend_args(int s, caddr_t buf, int len, int flags)
664  */
665 int
666 osend(struct osend_args *uap)
667 {
668         struct msghdr msg;
669         struct iovec aiov;
670
671         msg.msg_name = 0;
672         msg.msg_namelen = 0;
673         msg.msg_iov = &aiov;
674         msg.msg_iovlen = 1;
675         aiov.iov_base = uap->buf;
676         aiov.iov_len = uap->len;
677         msg.msg_control = 0;
678         msg.msg_flags = 0;
679         return (sendit(uap->s, &msg, uap->flags, &uap->sysmsg_result));
680 }
681
682 /*
683  * osendmsg_args(int s, caddr_t msg, int flags)
684  */
685 int
686 osendmsg(struct osendmsg_args *uap)
687 {
688         struct msghdr msg;
689         struct iovec aiov[UIO_SMALLIOV], *iov;
690         int error;
691
692         error = copyin(uap->msg, (caddr_t)&msg, sizeof (struct omsghdr));
693         if (error)
694                 return (error);
695         if ((u_int)msg.msg_iovlen >= UIO_SMALLIOV) {
696                 if ((u_int)msg.msg_iovlen >= UIO_MAXIOV)
697                         return (EMSGSIZE);
698                 MALLOC(iov, struct iovec *,
699                       sizeof(struct iovec) * (u_int)msg.msg_iovlen, M_IOV,
700                       M_WAITOK);
701         } else
702                 iov = aiov;
703         error = copyin((caddr_t)msg.msg_iov, (caddr_t)iov,
704             (unsigned)(msg.msg_iovlen * sizeof (struct iovec)));
705         if (error)
706                 goto done;
707         msg.msg_flags = MSG_COMPAT;
708         msg.msg_iov = iov;
709         error = sendit(uap->s, &msg, uap->flags, &uap->sysmsg_result);
710 done:
711         if (iov != aiov)
712                 FREE(iov, M_IOV);
713         return (error);
714 }
715 #endif
716
717 /*
718  * sendmsg_args(int s, caddr_t msg, int flags)
719  */
720 int
721 sendmsg(struct sendmsg_args *uap)
722 {
723         struct msghdr msg;
724         struct iovec aiov[UIO_SMALLIOV], *iov;
725         int error;
726
727         error = copyin(uap->msg, (caddr_t)&msg, sizeof (msg));
728         if (error)
729                 return (error);
730         if ((u_int)msg.msg_iovlen >= UIO_SMALLIOV) {
731                 if ((u_int)msg.msg_iovlen >= UIO_MAXIOV)
732                         return (EMSGSIZE);
733                 MALLOC(iov, struct iovec *,
734                        sizeof(struct iovec) * (u_int)msg.msg_iovlen, M_IOV,
735                        M_WAITOK);
736         } else
737                 iov = aiov;
738         if (msg.msg_iovlen &&
739             (error = copyin((caddr_t)msg.msg_iov, (caddr_t)iov,
740             (unsigned)(msg.msg_iovlen * sizeof (struct iovec)))))
741                 goto done;
742         msg.msg_iov = iov;
743 #ifdef COMPAT_OLDSOCK
744         msg.msg_flags = 0;
745 #endif
746         error = sendit(uap->s, &msg, uap->flags, &uap->sysmsg_result);
747 done:
748         if (iov != aiov)
749                 FREE(iov, M_IOV);
750         return (error);
751 }
752
753 static int
754 recvit(int s, struct msghdr *mp, caddr_t namelenp, int *res)
755 {
756         struct thread *td = curthread;
757         struct proc *p = td->td_proc;
758         struct file *fp;
759         struct uio auio;
760         struct iovec *iov;
761         int i;
762         int len, error;
763         struct mbuf *m, *control = 0;
764         caddr_t ctlbuf;
765         struct socket *so;
766         struct sockaddr *fromsa = 0;
767 #ifdef KTRACE
768         struct iovec *ktriov = NULL;
769         struct uio ktruio;
770 #endif
771
772         error = holdsock(p->p_fd, s, &fp);
773         if (error)
774                 return (error);
775         auio.uio_iov = mp->msg_iov;
776         auio.uio_iovcnt = mp->msg_iovlen;
777         auio.uio_segflg = UIO_USERSPACE;
778         auio.uio_rw = UIO_READ;
779         auio.uio_td = td;
780         auio.uio_offset = 0;                    /* XXX */
781         auio.uio_resid = 0;
782         iov = mp->msg_iov;
783         for (i = 0; i < mp->msg_iovlen; i++, iov++) {
784                 if ((auio.uio_resid += iov->iov_len) < 0) {
785                         fdrop(fp, td);
786                         return (EINVAL);
787                 }
788         }
789 #ifdef KTRACE
790         if (KTRPOINT(td, KTR_GENIO)) {
791                 int iovlen = auio.uio_iovcnt * sizeof (struct iovec);
792
793                 MALLOC(ktriov, struct iovec *, iovlen, M_TEMP, M_WAITOK);
794                 bcopy((caddr_t)auio.uio_iov, (caddr_t)ktriov, iovlen);
795                 ktruio = auio;
796         }
797 #endif
798         len = auio.uio_resid;
799         so = (struct socket *)fp->f_data;
800         error = so->so_proto->pr_usrreqs->pru_soreceive(so, &fromsa, &auio,
801             (struct mbuf **)0, mp->msg_control ? &control : (struct mbuf **)0,
802             &mp->msg_flags);
803         if (error) {
804                 if (auio.uio_resid != len && (error == ERESTART ||
805                     error == EINTR || error == EWOULDBLOCK))
806                         error = 0;
807         }
808 #ifdef KTRACE
809         if (ktriov != NULL) {
810                 if (error == 0) {
811                         ktruio.uio_iov = ktriov;
812                         ktruio.uio_resid = len - auio.uio_resid;
813                         ktrgenio(p->p_tracep, s, UIO_READ, &ktruio, error);
814                 }
815                 FREE(ktriov, M_TEMP);
816         }
817 #endif
818         if (error)
819                 goto out;
820         *res = len - auio.uio_resid;
821         if (mp->msg_name) {
822                 len = mp->msg_namelen;
823                 if (len <= 0 || fromsa == 0)
824                         len = 0;
825                 else {
826                         /* save sa_len before it is destroyed by MSG_COMPAT */
827                         len = MIN(len, fromsa->sa_len);
828 #ifdef COMPAT_OLDSOCK
829                         if (mp->msg_flags & MSG_COMPAT)
830                                 ((struct osockaddr *)fromsa)->sa_family =
831                                     fromsa->sa_family;
832 #endif
833                         error = copyout(fromsa,
834                             (caddr_t)mp->msg_name, (unsigned)len);
835                         if (error)
836                                 goto out;
837                 }
838                 mp->msg_namelen = len;
839                 if (namelenp &&
840                     (error = copyout((caddr_t)&len, namelenp, sizeof (int)))) {
841 #ifdef COMPAT_OLDSOCK
842                         if (mp->msg_flags & MSG_COMPAT)
843                                 error = 0;      /* old recvfrom didn't check */
844                         else
845 #endif
846                         goto out;
847                 }
848         }
849         if (mp->msg_control) {
850 #ifdef COMPAT_OLDSOCK
851                 /*
852                  * We assume that old recvmsg calls won't receive access
853                  * rights and other control info, esp. as control info
854                  * is always optional and those options didn't exist in 4.3.
855                  * If we receive rights, trim the cmsghdr; anything else
856                  * is tossed.
857                  */
858                 if (control && mp->msg_flags & MSG_COMPAT) {
859                         if (mtod(control, struct cmsghdr *)->cmsg_level !=
860                             SOL_SOCKET ||
861                             mtod(control, struct cmsghdr *)->cmsg_type !=
862                             SCM_RIGHTS) {
863                                 mp->msg_controllen = 0;
864                                 goto out;
865                         }
866                         control->m_len -= sizeof (struct cmsghdr);
867                         control->m_data += sizeof (struct cmsghdr);
868                 }
869 #endif
870                 len = mp->msg_controllen;
871                 m = control;
872                 mp->msg_controllen = 0;
873                 ctlbuf = (caddr_t) mp->msg_control;
874
875                 while (m && len > 0) {
876                         unsigned int tocopy;
877
878                         if (len >= m->m_len) 
879                                 tocopy = m->m_len;
880                         else {
881                                 mp->msg_flags |= MSG_CTRUNC;
882                                 tocopy = len;
883                         }
884                 
885                         if ((error = copyout((caddr_t)mtod(m, caddr_t),
886                                         ctlbuf, tocopy)) != 0)
887                                 goto out;
888
889                         ctlbuf += tocopy;
890                         len -= tocopy;
891                         m = m->m_next;
892                 }
893                 mp->msg_controllen = ctlbuf - (caddr_t)mp->msg_control;
894         }
895 out:
896         fdrop(fp, td);
897         if (fromsa)
898                 FREE(fromsa, M_SONAME);
899         if (control)
900                 m_freem(control);
901         return (error);
902 }
903
904 /*
905  * recvfrom_args(int s, caddr_t buf, size_t len, int flags, 
906  *                      caddr_t from, int *fromlenaddr)
907  */
908 int
909 recvfrom(struct recvfrom_args *uap)
910 {
911         struct msghdr msg;
912         struct iovec aiov;
913         int error;
914
915         if (uap->fromlenaddr) {
916                 error = copyin((caddr_t)uap->fromlenaddr,
917                     (caddr_t)&msg.msg_namelen, sizeof (msg.msg_namelen));
918                 if (error)
919                         return (error);
920         } else
921                 msg.msg_namelen = 0;
922         msg.msg_name = uap->from;
923         msg.msg_iov = &aiov;
924         msg.msg_iovlen = 1;
925         aiov.iov_base = uap->buf;
926         aiov.iov_len = uap->len;
927         msg.msg_control = 0;
928         msg.msg_flags = uap->flags;
929         return (recvit(uap->s, &msg, (caddr_t)uap->fromlenaddr, &uap->sysmsg_result));
930 }
931
932 #ifdef COMPAT_OLDSOCK
933 int
934 orecvfrom(struct recvfrom_args *uap)
935 {
936         uap->flags |= MSG_COMPAT;
937         return (recvfrom(uap));
938 }
939 #endif
940
941 #ifdef COMPAT_OLDSOCK
942 /*
943  * struct orecv_args(int s, caddr_t buf, int len, int flags)
944  */
945 int
946 orecv(struct orecv_args *uap)
947 {
948         struct msghdr msg;
949         struct iovec aiov;
950
951         msg.msg_name = 0;
952         msg.msg_namelen = 0;
953         msg.msg_iov = &aiov;
954         msg.msg_iovlen = 1;
955         aiov.iov_base = uap->buf;
956         aiov.iov_len = uap->len;
957         msg.msg_control = 0;
958         msg.msg_flags = uap->flags;
959         return (recvit(uap->s, &msg, (caddr_t)0, &uap->sysmsg_result));
960 }
961
962 /*
963  * Old recvmsg.  This code takes advantage of the fact that the old msghdr
964  * overlays the new one, missing only the flags, and with the (old) access
965  * rights where the control fields are now.
966  *
967  * orecvmsg_args(int s, struct omsghdr *msg, int flags)
968  */
969 int
970 orecvmsg(struct orecvmsg_args *uap)
971 {
972         struct msghdr msg;
973         struct iovec aiov[UIO_SMALLIOV], *iov;
974         int error;
975
976         error = copyin((caddr_t)uap->msg, (caddr_t)&msg,
977             sizeof (struct omsghdr));
978         if (error)
979                 return (error);
980         if ((u_int)msg.msg_iovlen >= UIO_SMALLIOV) {
981                 if ((u_int)msg.msg_iovlen >= UIO_MAXIOV)
982                         return (EMSGSIZE);
983                 MALLOC(iov, struct iovec *,
984                       sizeof(struct iovec) * (u_int)msg.msg_iovlen, M_IOV,
985                       M_WAITOK);
986         } else
987                 iov = aiov;
988         msg.msg_flags = uap->flags | MSG_COMPAT;
989         error = copyin((caddr_t)msg.msg_iov, (caddr_t)iov,
990             (unsigned)(msg.msg_iovlen * sizeof (struct iovec)));
991         if (error)
992                 goto done;
993         msg.msg_iov = iov;
994         error = recvit(uap->s, &msg, (caddr_t)&uap->msg->msg_namelen, &uap->sysmsg_result);
995
996         if (msg.msg_controllen && error == 0)
997                 error = copyout((caddr_t)&msg.msg_controllen,
998                     (caddr_t)&uap->msg->msg_accrightslen, sizeof (int));
999 done:
1000         if (iov != aiov)
1001                 FREE(iov, M_IOV);
1002         return (error);
1003 }
1004 #endif
1005
1006 /*
1007  * recvmsg_args(int s, struct msghdr *msg, int flags)
1008  */
1009 int
1010 recvmsg(struct recvmsg_args *uap)
1011 {
1012         struct msghdr msg;
1013         struct iovec aiov[UIO_SMALLIOV], *uiov, *iov;
1014         int error;
1015
1016         error = copyin((caddr_t)uap->msg, (caddr_t)&msg, sizeof (msg));
1017         if (error)
1018                 return (error);
1019         if ((u_int)msg.msg_iovlen >= UIO_SMALLIOV) {
1020                 if ((u_int)msg.msg_iovlen >= UIO_MAXIOV)
1021                         return (EMSGSIZE);
1022                 MALLOC(iov, struct iovec *,
1023                        sizeof(struct iovec) * (u_int)msg.msg_iovlen, M_IOV,
1024                        M_WAITOK);
1025         } else
1026                 iov = aiov;
1027 #ifdef COMPAT_OLDSOCK
1028         msg.msg_flags = uap->flags &~ MSG_COMPAT;
1029 #else
1030         msg.msg_flags = uap->flags;
1031 #endif
1032         uiov = msg.msg_iov;
1033         msg.msg_iov = iov;
1034         error = copyin((caddr_t)uiov, (caddr_t)iov,
1035             (unsigned)(msg.msg_iovlen * sizeof (struct iovec)));
1036         if (error)
1037                 goto done;
1038         error = recvit(uap->s, &msg, (caddr_t)0, &uap->sysmsg_result);
1039         if (!error) {
1040                 msg.msg_iov = uiov;
1041                 error = copyout((caddr_t)&msg, (caddr_t)uap->msg, sizeof(msg));
1042         }
1043 done:
1044         if (iov != aiov)
1045                 FREE(iov, M_IOV);
1046         return (error);
1047 }
1048
1049 /*
1050  * shutdown_args(int s, int how)
1051  */
1052 /* ARGSUSED */
1053 int
1054 shutdown(struct shutdown_args *uap)
1055 {
1056         struct thread *td = curthread;
1057         struct proc *p = td->td_proc;
1058         struct file *fp;
1059         int error;
1060
1061         KKASSERT(p);
1062         error = holdsock(p->p_fd, uap->s, &fp);
1063         if (error)
1064                 return (error);
1065         error = soshutdown((struct socket *)fp->f_data, uap->how);
1066         fdrop(fp, td);
1067         return(error);
1068 }
1069
1070 /*
1071  * setsockopt_args(int s, int level, int name, caddr_t val, int valsize)
1072  */
1073 /* ARGSUSED */
1074 int
1075 setsockopt(struct setsockopt_args *uap)
1076 {
1077         struct thread *td = curthread;
1078         struct proc *p = td->td_proc;
1079         struct file *fp;
1080         struct sockopt sopt;
1081         int error;
1082
1083         if (uap->val == 0 && uap->valsize != 0)
1084                 return (EFAULT);
1085         if (uap->valsize < 0)
1086                 return (EINVAL);
1087
1088         error = holdsock(p->p_fd, uap->s, &fp);
1089         if (error)
1090                 return (error);
1091
1092         sopt.sopt_dir = SOPT_SET;
1093         sopt.sopt_level = uap->level;
1094         sopt.sopt_name = uap->name;
1095         sopt.sopt_val = uap->val;
1096         sopt.sopt_valsize = uap->valsize;
1097         sopt.sopt_td = td;
1098         error = sosetopt((struct socket *)fp->f_data, &sopt);
1099         fdrop(fp, td);
1100         return(error);
1101 }
1102
1103 /*
1104  * getsockopt_Args(int s, int level, int name, caddr_t val, int *avalsize)
1105  */
1106 /* ARGSUSED */
1107 int
1108 getsockopt(struct getsockopt_args *uap)
1109 {
1110         struct thread *td = curthread;
1111         struct proc *p = td->td_proc;
1112         int     valsize, error;
1113         struct  file *fp;
1114         struct  sockopt sopt;
1115
1116         error = holdsock(p->p_fd, uap->s, &fp);
1117         if (error)
1118                 return (error);
1119         if (uap->val) {
1120                 error = copyin((caddr_t)uap->avalsize, (caddr_t)&valsize,
1121                     sizeof (valsize));
1122                 if (error) {
1123                         fdrop(fp, td);
1124                         return (error);
1125                 }
1126                 if (valsize < 0) {
1127                         fdrop(fp, td);
1128                         return (EINVAL);
1129                 }
1130         } else {
1131                 valsize = 0;
1132         }
1133
1134         sopt.sopt_dir = SOPT_GET;
1135         sopt.sopt_level = uap->level;
1136         sopt.sopt_name = uap->name;
1137         sopt.sopt_val = uap->val;
1138         sopt.sopt_valsize = (size_t)valsize; /* checked non-negative above */
1139         sopt.sopt_td = td;
1140
1141         error = sogetopt((struct socket *)fp->f_data, &sopt);
1142         if (error == 0) {
1143                 valsize = sopt.sopt_valsize;
1144                 error = copyout((caddr_t)&valsize,
1145                                 (caddr_t)uap->avalsize, sizeof (valsize));
1146         }
1147         fdrop(fp, td);
1148         return (error);
1149 }
1150
1151 /*
1152  * The second argument to kern_getsockname() is a handle to a struct sockaddr.
1153  * This allows kern_getsockname() to return a pointer to an allocated struct
1154  * sockaddr which must be freed later with FREE().  The caller must
1155  * initialize *name to NULL.
1156  */
1157 int
1158 kern_getsockname(int s, struct sockaddr **name, int *namelen)
1159 {
1160         struct thread *td = curthread;
1161         struct proc *p = td->td_proc;
1162         struct file *fp;
1163         struct socket *so;
1164         struct sockaddr *sa = NULL;
1165         int error;
1166
1167         error = holdsock(p->p_fd, s, &fp);
1168         if (error)
1169                 return (error);
1170         if (*namelen < 0) {
1171                 fdrop(fp, td);
1172                 return (EINVAL);
1173         }
1174         so = (struct socket *)fp->f_data;
1175         error = (*so->so_proto->pr_usrreqs->pru_sockaddr)(so, &sa);
1176         if (error == 0) {
1177                 if (sa == 0) {
1178                         *namelen = 0;
1179                 } else {
1180                         *namelen = MIN(*namelen, sa->sa_len);
1181                         *name = sa;
1182                 }
1183         }
1184
1185         fdrop(fp, td);
1186         return (error);
1187 }
1188
1189 /*
1190  * getsockname_args(int fdes, caddr_t asa, int *alen)
1191  *
1192  * Get socket name.
1193  */
1194 int
1195 getsockname(struct getsockname_args *uap)
1196 {
1197         struct sockaddr *sa = NULL;
1198         int error, sa_len;
1199
1200         error = copyin(uap->alen, &sa_len, sizeof(sa_len));
1201         if (error)
1202                 return (error);
1203
1204         error = kern_getsockname(uap->fdes, &sa, &sa_len);
1205
1206         if (error == 0)
1207                 error = copyout(sa, uap->asa, sa_len);
1208         if (error == 0)
1209                 error = copyout(&sa_len, uap->alen, sizeof(*uap->alen));
1210         if (sa)
1211                 FREE(sa, M_SONAME);
1212         return (error);
1213 }
1214
1215 /*
1216  * The second argument to kern_getpeername() is a handle to a struct sockaddr.
1217  * This allows kern_getpeername() to return a pointer to an allocated struct
1218  * sockaddr which must be freed later with FREE().  The caller must
1219  * initialize *name to NULL.
1220  */
1221 int
1222 kern_getpeername(int s, struct sockaddr **name, int *namelen)
1223 {
1224         struct thread *td = curthread;
1225         struct proc *p = td->td_proc;
1226         struct file *fp;
1227         struct socket *so;
1228         struct sockaddr *sa = NULL;
1229         int error;
1230
1231         error = holdsock(p->p_fd, s, &fp);
1232         if (error)
1233                 return (error);
1234         if (*namelen < 0) {
1235                 fdrop(fp, td);
1236                 return (EINVAL);
1237         }
1238         so = (struct socket *)fp->f_data;
1239         if ((so->so_state & (SS_ISCONNECTED|SS_ISCONFIRMING)) == 0) {
1240                 fdrop(fp, td);
1241                 return (ENOTCONN);
1242         }
1243         error = (*so->so_proto->pr_usrreqs->pru_peeraddr)(so, &sa);
1244         if (error == 0) {
1245                 if (sa == 0) {
1246                         *namelen = 0;
1247                 } else {
1248                         *namelen = MIN(*namelen, sa->sa_len);
1249                         *name = sa;
1250                 }
1251         }
1252
1253         fdrop(fp, td);
1254         return (error);
1255 }
1256
1257 /*
1258  * getpeername_args(int fdes, caddr_t asa, int *alen)
1259  *
1260  * Get name of peer for connected socket.
1261  */
1262 int
1263 getpeername(struct getpeername_args *uap)
1264 {
1265         struct sockaddr *sa = NULL;
1266         int error, sa_len;
1267
1268         error = copyin(uap->alen, &sa_len, sizeof(sa_len));
1269         if (error)
1270                 return (error);
1271
1272         error = kern_getpeername(uap->fdes, &sa, &sa_len);
1273
1274         if (error == 0)
1275                 error = copyout(sa, uap->asa, sa_len);
1276         if (error == 0)
1277                 error = copyout(&sa_len, uap->alen, sizeof(*uap->alen));
1278         if (sa)
1279                 FREE(sa, M_SONAME);
1280         return (error);
1281 }
1282
1283 int
1284 sockargs(mp, buf, buflen, type)
1285         struct mbuf **mp;
1286         caddr_t buf;
1287         int buflen, type;
1288 {
1289         struct sockaddr *sa;
1290         struct mbuf *m;
1291         int error;
1292
1293         if ((u_int)buflen > MLEN) {
1294 #ifdef COMPAT_OLDSOCK
1295                 if (type == MT_SONAME && (u_int)buflen <= 112)
1296                         buflen = MLEN;          /* unix domain compat. hack */
1297                 else
1298 #endif
1299                 return (EINVAL);
1300         }
1301         m = m_get(M_WAIT, type);
1302         if (m == NULL)
1303                 return (ENOBUFS);
1304         m->m_len = buflen;
1305         error = copyin(buf, mtod(m, caddr_t), (u_int)buflen);
1306         if (error)
1307                 (void) m_free(m);
1308         else {
1309                 *mp = m;
1310                 if (type == MT_SONAME) {
1311                         sa = mtod(m, struct sockaddr *);
1312
1313 #if defined(COMPAT_OLDSOCK) && BYTE_ORDER != BIG_ENDIAN
1314                         if (sa->sa_family == 0 && sa->sa_len < AF_MAX)
1315                                 sa->sa_family = sa->sa_len;
1316 #endif
1317                         sa->sa_len = buflen;
1318                 }
1319         }
1320         return (error);
1321 }
1322
1323 int
1324 getsockaddr(struct sockaddr **namp, caddr_t uaddr, size_t len)
1325 {
1326         struct sockaddr *sa;
1327         int error;
1328
1329         *namp = NULL;
1330         if (len > SOCK_MAXADDRLEN)
1331                 return ENAMETOOLONG;
1332         if (len < offsetof(struct sockaddr, sa_data[0]))
1333                 return EDOM;
1334         MALLOC(sa, struct sockaddr *, len, M_SONAME, M_WAITOK);
1335         error = copyin(uaddr, sa, len);
1336         if (error) {
1337                 FREE(sa, M_SONAME);
1338         } else {
1339 #if defined(COMPAT_OLDSOCK) && BYTE_ORDER != BIG_ENDIAN
1340                 if (sa->sa_family == 0 && sa->sa_len < AF_MAX)
1341                         sa->sa_family = sa->sa_len;
1342 #endif
1343                 sa->sa_len = len;
1344                 *namp = sa;
1345         }
1346         return error;
1347 }
1348
1349 /*
1350  * holdsock() - load the struct file pointer associated
1351  * with a socket into *fpp.  If an error occurs, non-zero
1352  * will be returned and *fpp will be set to NULL.
1353  */
1354 int
1355 holdsock(fdp, fdes, fpp)
1356         struct filedesc *fdp;
1357         int fdes;
1358         struct file **fpp;
1359 {
1360         struct file *fp = NULL;
1361         int error = 0;
1362
1363         if ((unsigned)fdes >= fdp->fd_nfiles ||
1364             (fp = fdp->fd_ofiles[fdes]) == NULL) {
1365                 error = EBADF;
1366         } else if (fp->f_type != DTYPE_SOCKET) {
1367                 error = ENOTSOCK;
1368                 fp = NULL;
1369         } else {
1370                 fhold(fp);
1371         }
1372         *fpp = fp;
1373         return(error);
1374 }
1375
1376 /*
1377  * Allocate a pool of sf_bufs (sendfile(2) or "super-fast" if you prefer. :-))
1378  */
1379 static void
1380 sf_buf_init(void *arg)
1381 {
1382         int i;
1383
1384         SLIST_INIT(&sf_freelist);
1385         sf_base = kmem_alloc_pageable(kernel_map, nsfbufs * PAGE_SIZE);
1386         sf_bufs = malloc(nsfbufs * sizeof(struct sf_buf), M_TEMP, M_NOWAIT);
1387         bzero(sf_bufs, nsfbufs * sizeof(struct sf_buf));
1388         for (i = 0; i < nsfbufs; i++) {
1389                 sf_bufs[i].kva = sf_base + i * PAGE_SIZE;
1390                 SLIST_INSERT_HEAD(&sf_freelist, &sf_bufs[i], free_list);
1391         }
1392 }
1393
1394 /*
1395  * Get an sf_buf from the freelist. Will block if none are available.
1396  */
1397 struct sf_buf *
1398 sf_buf_alloc()
1399 {
1400         struct sf_buf *sf;
1401         int s;
1402         int error;
1403
1404         s = splimp();
1405         while ((sf = SLIST_FIRST(&sf_freelist)) == NULL) {
1406                 sf_buf_alloc_want = 1;
1407                 error = tsleep(&sf_freelist, PCATCH, "sfbufa", 0);
1408                 if (error)
1409                         break;
1410         }
1411         if (sf != NULL) {
1412                 SLIST_REMOVE_HEAD(&sf_freelist, free_list);
1413                 sf->refcnt = 1;
1414         }
1415         splx(s);
1416         return (sf);
1417 }
1418
1419 #define dtosf(x)        (&sf_bufs[((uintptr_t)(x) - (uintptr_t)sf_base) >> PAGE_SHIFT])
1420 void
1421 sf_buf_ref(caddr_t addr, u_int size)
1422 {
1423         struct sf_buf *sf;
1424
1425         sf = dtosf(addr);
1426         if (sf->refcnt == 0)
1427                 panic("sf_buf_ref: referencing a free sf_buf");
1428         sf->refcnt++;
1429 }
1430
1431 /*
1432  * Lose a reference to an sf_buf. When none left, detach mapped page
1433  * and release resources back to the system.
1434  *
1435  * Must be called at splimp.
1436  */
1437 void
1438 sf_buf_free(caddr_t addr, u_int size)
1439 {
1440         struct sf_buf *sf;
1441         struct vm_page *m;
1442         int s;
1443
1444         sf = dtosf(addr);
1445         if (sf->refcnt == 0)
1446                 panic("sf_buf_free: freeing free sf_buf");
1447         sf->refcnt--;
1448         if (sf->refcnt == 0) {
1449                 pmap_qremove((vm_offset_t)addr, 1);
1450                 m = sf->m;
1451                 s = splvm();
1452                 vm_page_unwire(m, 0);
1453                 /*
1454                  * Check for the object going away on us. This can
1455                  * happen since we don't hold a reference to it.
1456                  * If so, we're responsible for freeing the page.
1457                  */
1458                 if (m->wire_count == 0 && m->object == NULL)
1459                         vm_page_free(m);
1460                 splx(s);
1461                 sf->m = NULL;
1462                 SLIST_INSERT_HEAD(&sf_freelist, sf, free_list);
1463                 if (sf_buf_alloc_want) {
1464                         sf_buf_alloc_want = 0;
1465                         wakeup(&sf_freelist);
1466                 }
1467         }
1468 }
1469
1470 /*
1471  * sendfile(2).
1472  * int sendfile(int fd, int s, off_t offset, size_t nbytes,
1473  *       struct sf_hdtr *hdtr, off_t *sbytes, int flags)
1474  *
1475  * Send a file specified by 'fd' and starting at 'offset' to a socket
1476  * specified by 's'. Send only 'nbytes' of the file or until EOF if
1477  * nbytes == 0. Optionally add a header and/or trailer to the socket
1478  * output. If specified, write the total number of bytes sent into *sbytes.
1479  */
1480 int
1481 sendfile(struct sendfile_args *uap)
1482 {
1483         return (do_sendfile(uap, 0));
1484 }
1485
1486 #ifdef COMPAT_43
1487 int
1488 osendfile(struct osendfile_args *uap)
1489 {
1490         struct sendfile_args args;
1491
1492         args.fd = uap->fd;
1493         args.s = uap->s;
1494         args.offset = uap->offset;
1495         args.nbytes = uap->nbytes;
1496         args.hdtr = uap->hdtr;
1497         args.sbytes = uap->sbytes;
1498         args.flags = uap->flags;
1499
1500         return (do_sendfile(&args, 1));
1501 }
1502 #endif
1503
1504 int
1505 do_sendfile(struct sendfile_args *uap, int compat)
1506 {
1507         struct thread *td = curthread;
1508         struct proc *p = td->td_proc;
1509         struct file *fp;
1510         struct filedesc *fdp;
1511         struct vnode *vp;
1512         struct vm_object *obj;
1513         struct socket *so;
1514         struct mbuf *m;
1515         struct sf_buf *sf;
1516         struct vm_page *pg;
1517         struct writev_args nuap;
1518         struct sf_hdtr hdtr;
1519         off_t off, xfsize, hdtr_size, sbytes = 0;
1520         int error = 0, s;
1521
1522         KKASSERT(p);
1523         fdp = p->p_fd;
1524
1525         vp = NULL;
1526         hdtr_size = 0;
1527         /*
1528          * Do argument checking. Must be a regular file in, stream
1529          * type and connected socket out, positive offset.
1530          */
1531         fp = holdfp(fdp, uap->fd, FREAD);
1532         if (fp == NULL) {
1533                 error = EBADF;
1534                 goto done;
1535         }
1536         if (fp->f_type != DTYPE_VNODE) {
1537                 error = EINVAL;
1538                 goto done;
1539         }
1540         vp = (struct vnode *)fp->f_data;
1541         vref(vp);
1542         if (vp->v_type != VREG || VOP_GETVOBJECT(vp, &obj) != 0) {
1543                 error = EINVAL;
1544                 goto done;
1545         }
1546         fdrop(fp, td);
1547         error = holdsock(p->p_fd, uap->s, &fp);
1548         if (error)
1549                 goto done;
1550         so = (struct socket *)fp->f_data;
1551         if (so->so_type != SOCK_STREAM) {
1552                 error = EINVAL;
1553                 goto done;
1554         }
1555         if ((so->so_state & SS_ISCONNECTED) == 0) {
1556                 error = ENOTCONN;
1557                 goto done;
1558         }
1559         if (uap->offset < 0) {
1560                 error = EINVAL;
1561                 goto done;
1562         }
1563
1564         /*
1565          * If specified, get the pointer to the sf_hdtr struct for
1566          * any headers/trailers.
1567          */
1568         if (uap->hdtr != NULL) {
1569                 error = copyin(uap->hdtr, &hdtr, sizeof(hdtr));
1570                 if (error)
1571                         goto done;
1572                 /*
1573                  * Send any headers. Wimp out and use writev(2).
1574                  */
1575                 if (hdtr.headers != NULL) {
1576                         nuap.fd = uap->s;
1577                         nuap.iovp = hdtr.headers;
1578                         nuap.iovcnt = hdtr.hdr_cnt;
1579                         error = writev(&nuap);
1580                         if (error)
1581                                 goto done;
1582                         if (compat)
1583                                 sbytes += nuap.sysmsg_result;
1584                         else
1585                                 hdtr_size += nuap.sysmsg_result;
1586                 }
1587         }
1588
1589         /*
1590          * Protect against multiple writers to the socket.
1591          */
1592         (void) sblock(&so->so_snd, M_WAITOK);
1593
1594         /*
1595          * Loop through the pages in the file, starting with the requested
1596          * offset. Get a file page (do I/O if necessary), map the file page
1597          * into an sf_buf, attach an mbuf header to the sf_buf, and queue
1598          * it on the socket.
1599          */
1600         for (off = uap->offset; ; off += xfsize, sbytes += xfsize) {
1601                 vm_pindex_t pindex;
1602                 vm_offset_t pgoff;
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 = obj->un_pager.vnp.vnp_size - 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 (uap->nbytes && xfsize > (uap->nbytes - sbytes))
1617                         xfsize = uap->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 ((so->so_state & SS_NBIO) && sbspace(&so->so_snd) <= 0) {
1625                         if (so->so_state & SS_CANTSENDMORE)
1626                                 error = EPIPE;
1627                         else
1628                                 error = EAGAIN;
1629                         sbunlock(&so->so_snd);
1630                         goto done;
1631                 }
1632                 /*
1633                  * Attempt to look up the page.  
1634                  *
1635                  *      Allocate if not found
1636                  *
1637                  *      Wait and loop if busy.
1638                  */
1639                 pg = vm_page_lookup(obj, pindex);
1640
1641                 if (pg == NULL) {
1642                         pg = vm_page_alloc(obj, pindex, VM_ALLOC_NORMAL);
1643                         if (pg == NULL) {
1644                                 VM_WAIT;
1645                                 goto retry_lookup;
1646                         }
1647                         vm_page_wakeup(pg);
1648                 } else if (vm_page_sleep_busy(pg, TRUE, "sfpbsy")) {
1649                         goto retry_lookup;
1650                 }
1651
1652                 /*
1653                  * Wire the page so it does not get ripped out from under
1654                  * us. 
1655                  */
1656
1657                 vm_page_wire(pg);
1658
1659                 /*
1660                  * If page is not valid for what we need, initiate I/O
1661                  */
1662
1663                 if (!pg->valid || !vm_page_is_valid(pg, pgoff, xfsize)) {
1664                         struct uio auio;
1665                         struct iovec aiov;
1666                         int bsize;
1667
1668                         /*
1669                          * Ensure that our page is still around when the I/O 
1670                          * completes.
1671                          */
1672                         vm_page_io_start(pg);
1673
1674                         /*
1675                          * Get the page from backing store.
1676                          */
1677                         bsize = vp->v_mount->mnt_stat.f_iosize;
1678                         auio.uio_iov = &aiov;
1679                         auio.uio_iovcnt = 1;
1680                         aiov.iov_base = 0;
1681                         aiov.iov_len = MAXBSIZE;
1682                         auio.uio_resid = MAXBSIZE;
1683                         auio.uio_offset = trunc_page(off);
1684                         auio.uio_segflg = UIO_NOCOPY;
1685                         auio.uio_rw = UIO_READ;
1686                         auio.uio_td = td;
1687                         vn_lock(vp, LK_SHARED | LK_NOPAUSE | LK_RETRY, td);
1688                         error = VOP_READ(vp, &auio, 
1689                                     IO_VMIO | ((MAXBSIZE / bsize) << 16),
1690                                     p->p_ucred);
1691                         VOP_UNLOCK(vp, 0, td);
1692                         vm_page_flag_clear(pg, PG_ZERO);
1693                         vm_page_io_finish(pg);
1694                         if (error) {
1695                                 vm_page_unwire(pg, 0);
1696                                 /*
1697                                  * See if anyone else might know about this page.
1698                                  * If not and it is not valid, then free it.
1699                                  */
1700                                 if (pg->wire_count == 0 && pg->valid == 0 &&
1701                                     pg->busy == 0 && !(pg->flags & PG_BUSY) &&
1702                                     pg->hold_count == 0) {
1703                                         vm_page_busy(pg);
1704                                         vm_page_free(pg);
1705                                 }
1706                                 sbunlock(&so->so_snd);
1707                                 goto done;
1708                         }
1709                 }
1710
1711
1712                 /*
1713                  * Get a sendfile buf. We usually wait as long as necessary,
1714                  * but this wait can be interrupted.
1715                  */
1716                 if ((sf = sf_buf_alloc()) == NULL) {
1717                         s = splvm();
1718                         vm_page_unwire(pg, 0);
1719                         if (pg->wire_count == 0 && pg->object == NULL)
1720                                 vm_page_free(pg);
1721                         splx(s);
1722                         sbunlock(&so->so_snd);
1723                         error = EINTR;
1724                         goto done;
1725                 }
1726
1727
1728                 /*
1729                  * Allocate a kernel virtual page and insert the physical page
1730                  * into it.
1731                  */
1732
1733                 sf->m = pg;
1734                 pmap_qenter(sf->kva, &pg, 1);
1735                 /*
1736                  * Get an mbuf header and set it up as having external storage.
1737                  */
1738                 MGETHDR(m, M_WAIT, MT_DATA);
1739                 if (m == NULL) {
1740                         error = ENOBUFS;
1741                         sf_buf_free((void *)sf->kva, PAGE_SIZE);
1742                         sbunlock(&so->so_snd);
1743                         goto done;
1744                 }
1745                 m->m_ext.ext_free = sf_buf_free;
1746                 m->m_ext.ext_ref = sf_buf_ref;
1747                 m->m_ext.ext_buf = (void *)sf->kva;
1748                 m->m_ext.ext_size = PAGE_SIZE;
1749                 m->m_data = (char *) sf->kva + pgoff;
1750                 m->m_flags |= M_EXT;
1751                 m->m_pkthdr.len = m->m_len = xfsize;
1752                 /*
1753                  * Add the buffer to the socket buffer chain.
1754                  */
1755                 s = splnet();
1756 retry_space:
1757                 /*
1758                  * Make sure that the socket is still able to take more data.
1759                  * CANTSENDMORE being true usually means that the connection
1760                  * was closed. so_error is true when an error was sensed after
1761                  * a previous send.
1762                  * The state is checked after the page mapping and buffer
1763                  * allocation above since those operations may block and make
1764                  * any socket checks stale. From this point forward, nothing
1765                  * blocks before the pru_send (or more accurately, any blocking
1766                  * results in a loop back to here to re-check).
1767                  */
1768                 if ((so->so_state & SS_CANTSENDMORE) || so->so_error) {
1769                         if (so->so_state & SS_CANTSENDMORE) {
1770                                 error = EPIPE;
1771                         } else {
1772                                 error = so->so_error;
1773                                 so->so_error = 0;
1774                         }
1775                         m_freem(m);
1776                         sbunlock(&so->so_snd);
1777                         splx(s);
1778                         goto done;
1779                 }
1780                 /*
1781                  * Wait for socket space to become available. We do this just
1782                  * after checking the connection state above in order to avoid
1783                  * a race condition with sbwait().
1784                  */
1785                 if (sbspace(&so->so_snd) < so->so_snd.sb_lowat) {
1786                         if (so->so_state & SS_NBIO) {
1787                                 m_freem(m);
1788                                 sbunlock(&so->so_snd);
1789                                 splx(s);
1790                                 error = EAGAIN;
1791                                 goto done;
1792                         }
1793                         error = sbwait(&so->so_snd);
1794                         /*
1795                          * An error from sbwait usually indicates that we've
1796                          * been interrupted by a signal. If we've sent anything
1797                          * then return bytes sent, otherwise return the error.
1798                          */
1799                         if (error) {
1800                                 m_freem(m);
1801                                 sbunlock(&so->so_snd);
1802                                 splx(s);
1803                                 goto done;
1804                         }
1805                         goto retry_space;
1806                 }
1807                 error = 
1808                     (*so->so_proto->pr_usrreqs->pru_send)(so, 0, m, 0, 0, td);
1809                 splx(s);
1810                 if (error) {
1811                         sbunlock(&so->so_snd);
1812                         goto done;
1813                 }
1814         }
1815         sbunlock(&so->so_snd);
1816
1817         /*
1818          * Send trailers. Wimp out and use writev(2).
1819          */
1820         if (uap->hdtr != NULL && hdtr.trailers != NULL) {
1821                         nuap.fd = uap->s;
1822                         nuap.iovp = hdtr.trailers;
1823                         nuap.iovcnt = hdtr.trl_cnt;
1824                         error = writev(&nuap);
1825                         if (error)
1826                                 goto done;
1827                         if (compat)
1828                                 sbytes += nuap.sysmsg_result;
1829                         else
1830                                 hdtr_size += nuap.sysmsg_result;
1831         }
1832
1833 done:
1834         if (uap->sbytes != NULL) {
1835                 if (compat == 0)
1836                         sbytes += hdtr_size;
1837                 copyout(&sbytes, uap->sbytes, sizeof(off_t));
1838         }
1839         if (vp)
1840                 vrele(vp);
1841         if (fp)
1842                 fdrop(fp, td);
1843         return (error);
1844 }