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