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