Register keyword removal
[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.6 2003/07/26 18:12:44 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->lmsg.u.ms_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->lmsg.u.ms_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         register struct iovec *iov;
501         register 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                         register 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->lmsg.u.ms_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->lmsg.u.ms_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->lmsg.u.ms_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->lmsg.u.ms_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         register struct iovec *iov;
730         register 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 #ifndef MIN
796 #define MIN(a,b) ((a)>(b)?(b):(a))
797 #endif
798                         /* save sa_len before it is destroyed by MSG_COMPAT */
799                         len = MIN(len, fromsa->sa_len);
800 #ifdef COMPAT_OLDSOCK
801                         if (mp->msg_flags & MSG_COMPAT)
802                                 ((struct osockaddr *)fromsa)->sa_family =
803                                     fromsa->sa_family;
804 #endif
805                         error = copyout(fromsa,
806                             (caddr_t)mp->msg_name, (unsigned)len);
807                         if (error)
808                                 goto out;
809                 }
810                 mp->msg_namelen = len;
811                 if (namelenp &&
812                     (error = copyout((caddr_t)&len, namelenp, sizeof (int)))) {
813 #ifdef COMPAT_OLDSOCK
814                         if (mp->msg_flags & MSG_COMPAT)
815                                 error = 0;      /* old recvfrom didn't check */
816                         else
817 #endif
818                         goto out;
819                 }
820         }
821         if (mp->msg_control) {
822 #ifdef COMPAT_OLDSOCK
823                 /*
824                  * We assume that old recvmsg calls won't receive access
825                  * rights and other control info, esp. as control info
826                  * is always optional and those options didn't exist in 4.3.
827                  * If we receive rights, trim the cmsghdr; anything else
828                  * is tossed.
829                  */
830                 if (control && mp->msg_flags & MSG_COMPAT) {
831                         if (mtod(control, struct cmsghdr *)->cmsg_level !=
832                             SOL_SOCKET ||
833                             mtod(control, struct cmsghdr *)->cmsg_type !=
834                             SCM_RIGHTS) {
835                                 mp->msg_controllen = 0;
836                                 goto out;
837                         }
838                         control->m_len -= sizeof (struct cmsghdr);
839                         control->m_data += sizeof (struct cmsghdr);
840                 }
841 #endif
842                 len = mp->msg_controllen;
843                 m = control;
844                 mp->msg_controllen = 0;
845                 ctlbuf = (caddr_t) mp->msg_control;
846
847                 while (m && len > 0) {
848                         unsigned int tocopy;
849
850                         if (len >= m->m_len) 
851                                 tocopy = m->m_len;
852                         else {
853                                 mp->msg_flags |= MSG_CTRUNC;
854                                 tocopy = len;
855                         }
856                 
857                         if ((error = copyout((caddr_t)mtod(m, caddr_t),
858                                         ctlbuf, tocopy)) != 0)
859                                 goto out;
860
861                         ctlbuf += tocopy;
862                         len -= tocopy;
863                         m = m->m_next;
864                 }
865                 mp->msg_controllen = ctlbuf - (caddr_t)mp->msg_control;
866         }
867 out:
868         fdrop(fp, td);
869         if (fromsa)
870                 FREE(fromsa, M_SONAME);
871         if (control)
872                 m_freem(control);
873         return (error);
874 }
875
876 /*
877  * recvfrom_args(int s, caddr_t buf, size_t len, int flags, 
878  *                      caddr_t from, int *fromlenaddr)
879  */
880 int
881 recvfrom(struct recvfrom_args *uap)
882 {
883         struct msghdr msg;
884         struct iovec aiov;
885         int error;
886
887         if (uap->fromlenaddr) {
888                 error = copyin((caddr_t)uap->fromlenaddr,
889                     (caddr_t)&msg.msg_namelen, sizeof (msg.msg_namelen));
890                 if (error)
891                         return (error);
892         } else
893                 msg.msg_namelen = 0;
894         msg.msg_name = uap->from;
895         msg.msg_iov = &aiov;
896         msg.msg_iovlen = 1;
897         aiov.iov_base = uap->buf;
898         aiov.iov_len = uap->len;
899         msg.msg_control = 0;
900         msg.msg_flags = uap->flags;
901         return (recvit(uap->s, &msg, (caddr_t)uap->fromlenaddr, &uap->lmsg.u.ms_result));
902 }
903
904 #ifdef COMPAT_OLDSOCK
905 int
906 orecvfrom(struct recvfrom_args *uap)
907 {
908         uap->flags |= MSG_COMPAT;
909         return (recvfrom(uap));
910 }
911 #endif
912
913 #ifdef COMPAT_OLDSOCK
914 /*
915  * struct orecv_args(int s, caddr_t buf, int len, int flags)
916  */
917 int
918 orecv(struct orecv_args *uap)
919 {
920         struct msghdr msg;
921         struct iovec aiov;
922
923         msg.msg_name = 0;
924         msg.msg_namelen = 0;
925         msg.msg_iov = &aiov;
926         msg.msg_iovlen = 1;
927         aiov.iov_base = uap->buf;
928         aiov.iov_len = uap->len;
929         msg.msg_control = 0;
930         msg.msg_flags = uap->flags;
931         return (recvit(uap->s, &msg, (caddr_t)0, &uap->lmsg.u.ms_result));
932 }
933
934 /*
935  * Old recvmsg.  This code takes advantage of the fact that the old msghdr
936  * overlays the new one, missing only the flags, and with the (old) access
937  * rights where the control fields are now.
938  *
939  * orecvmsg_args(int s, struct omsghdr *msg, int flags)
940  */
941 int
942 orecvmsg(struct orecvmsg_args *uap)
943 {
944         struct msghdr msg;
945         struct iovec aiov[UIO_SMALLIOV], *iov;
946         int error;
947
948         error = copyin((caddr_t)uap->msg, (caddr_t)&msg,
949             sizeof (struct omsghdr));
950         if (error)
951                 return (error);
952         if ((u_int)msg.msg_iovlen >= UIO_SMALLIOV) {
953                 if ((u_int)msg.msg_iovlen >= UIO_MAXIOV)
954                         return (EMSGSIZE);
955                 MALLOC(iov, struct iovec *,
956                       sizeof(struct iovec) * (u_int)msg.msg_iovlen, M_IOV,
957                       M_WAITOK);
958         } else
959                 iov = aiov;
960         msg.msg_flags = uap->flags | MSG_COMPAT;
961         error = copyin((caddr_t)msg.msg_iov, (caddr_t)iov,
962             (unsigned)(msg.msg_iovlen * sizeof (struct iovec)));
963         if (error)
964                 goto done;
965         msg.msg_iov = iov;
966         error = recvit(uap->s, &msg, (caddr_t)&uap->msg->msg_namelen, &uap->lmsg.u.ms_result);
967
968         if (msg.msg_controllen && error == 0)
969                 error = copyout((caddr_t)&msg.msg_controllen,
970                     (caddr_t)&uap->msg->msg_accrightslen, sizeof (int));
971 done:
972         if (iov != aiov)
973                 FREE(iov, M_IOV);
974         return (error);
975 }
976 #endif
977
978 /*
979  * recvmsg_args(int s, struct msghdr *msg, int flags)
980  */
981 int
982 recvmsg(struct recvmsg_args *uap)
983 {
984         struct msghdr msg;
985         struct iovec aiov[UIO_SMALLIOV], *uiov, *iov;
986         int error;
987
988         error = copyin((caddr_t)uap->msg, (caddr_t)&msg, sizeof (msg));
989         if (error)
990                 return (error);
991         if ((u_int)msg.msg_iovlen >= UIO_SMALLIOV) {
992                 if ((u_int)msg.msg_iovlen >= UIO_MAXIOV)
993                         return (EMSGSIZE);
994                 MALLOC(iov, struct iovec *,
995                        sizeof(struct iovec) * (u_int)msg.msg_iovlen, M_IOV,
996                        M_WAITOK);
997         } else
998                 iov = aiov;
999 #ifdef COMPAT_OLDSOCK
1000         msg.msg_flags = uap->flags &~ MSG_COMPAT;
1001 #else
1002         msg.msg_flags = uap->flags;
1003 #endif
1004         uiov = msg.msg_iov;
1005         msg.msg_iov = iov;
1006         error = copyin((caddr_t)uiov, (caddr_t)iov,
1007             (unsigned)(msg.msg_iovlen * sizeof (struct iovec)));
1008         if (error)
1009                 goto done;
1010         error = recvit(uap->s, &msg, (caddr_t)0, &uap->lmsg.u.ms_result);
1011         if (!error) {
1012                 msg.msg_iov = uiov;
1013                 error = copyout((caddr_t)&msg, (caddr_t)uap->msg, sizeof(msg));
1014         }
1015 done:
1016         if (iov != aiov)
1017                 FREE(iov, M_IOV);
1018         return (error);
1019 }
1020
1021 /*
1022  * shutdown_args(int s, int how)
1023  */
1024 /* ARGSUSED */
1025 int
1026 shutdown(struct shutdown_args *uap)
1027 {
1028         struct thread *td = curthread;
1029         struct proc *p = td->td_proc;
1030         struct file *fp;
1031         int error;
1032
1033         KKASSERT(p);
1034         error = holdsock(p->p_fd, uap->s, &fp);
1035         if (error)
1036                 return (error);
1037         error = soshutdown((struct socket *)fp->f_data, uap->how);
1038         fdrop(fp, td);
1039         return(error);
1040 }
1041
1042 /*
1043  * setsockopt_args(int s, int level, int name, caddr_t val, int valsize)
1044  */
1045 /* ARGSUSED */
1046 int
1047 setsockopt(struct setsockopt_args *uap)
1048 {
1049         struct thread *td = curthread;
1050         struct proc *p = td->td_proc;
1051         struct file *fp;
1052         struct sockopt sopt;
1053         int error;
1054
1055         if (uap->val == 0 && uap->valsize != 0)
1056                 return (EFAULT);
1057         if (uap->valsize < 0)
1058                 return (EINVAL);
1059
1060         error = holdsock(p->p_fd, uap->s, &fp);
1061         if (error)
1062                 return (error);
1063
1064         sopt.sopt_dir = SOPT_SET;
1065         sopt.sopt_level = uap->level;
1066         sopt.sopt_name = uap->name;
1067         sopt.sopt_val = uap->val;
1068         sopt.sopt_valsize = uap->valsize;
1069         sopt.sopt_td = td;
1070         error = sosetopt((struct socket *)fp->f_data, &sopt);
1071         fdrop(fp, td);
1072         return(error);
1073 }
1074
1075 /*
1076  * getsockopt_Args(int s, int level, int name, caddr_t val, int *avalsize)
1077  */
1078 /* ARGSUSED */
1079 int
1080 getsockopt(struct getsockopt_args *uap)
1081 {
1082         struct thread *td = curthread;
1083         struct proc *p = td->td_proc;
1084         int     valsize, error;
1085         struct  file *fp;
1086         struct  sockopt sopt;
1087
1088         error = holdsock(p->p_fd, uap->s, &fp);
1089         if (error)
1090                 return (error);
1091         if (uap->val) {
1092                 error = copyin((caddr_t)uap->avalsize, (caddr_t)&valsize,
1093                     sizeof (valsize));
1094                 if (error) {
1095                         fdrop(fp, td);
1096                         return (error);
1097                 }
1098                 if (valsize < 0) {
1099                         fdrop(fp, td);
1100                         return (EINVAL);
1101                 }
1102         } else {
1103                 valsize = 0;
1104         }
1105
1106         sopt.sopt_dir = SOPT_GET;
1107         sopt.sopt_level = uap->level;
1108         sopt.sopt_name = uap->name;
1109         sopt.sopt_val = uap->val;
1110         sopt.sopt_valsize = (size_t)valsize; /* checked non-negative above */
1111         sopt.sopt_td = td;
1112
1113         error = sogetopt((struct socket *)fp->f_data, &sopt);
1114         if (error == 0) {
1115                 valsize = sopt.sopt_valsize;
1116                 error = copyout((caddr_t)&valsize,
1117                                 (caddr_t)uap->avalsize, sizeof (valsize));
1118         }
1119         fdrop(fp, td);
1120         return (error);
1121 }
1122
1123 /*
1124  * getsockname_args(int fdes, caddr_t asa, int *alen)
1125  *
1126  * Get socket name.
1127  */
1128 /* ARGSUSED */
1129 static int
1130 getsockname1(struct getsockname_args *uap, int compat)
1131 {
1132         struct thread *td = curthread;
1133         struct proc *p = td->td_proc;
1134         struct file *fp;
1135         struct socket *so;
1136         struct sockaddr *sa;
1137         int len, error;
1138
1139         error = holdsock(p->p_fd, uap->fdes, &fp);
1140         if (error)
1141                 return (error);
1142         error = copyin((caddr_t)uap->alen, (caddr_t)&len, sizeof (len));
1143         if (error) {
1144                 fdrop(fp, td);
1145                 return (error);
1146         }
1147         if (len < 0) {
1148                 fdrop(fp, td);
1149                 return (EINVAL);
1150         }
1151         so = (struct socket *)fp->f_data;
1152         sa = 0;
1153         error = (*so->so_proto->pr_usrreqs->pru_sockaddr)(so, &sa);
1154         if (error)
1155                 goto bad;
1156         if (sa == 0) {
1157                 len = 0;
1158                 goto gotnothing;
1159         }
1160
1161         len = MIN(len, sa->sa_len);
1162 #ifdef COMPAT_OLDSOCK
1163         if (compat)
1164                 ((struct osockaddr *)sa)->sa_family = sa->sa_family;
1165 #endif
1166         error = copyout(sa, (caddr_t)uap->asa, (u_int)len);
1167         if (error == 0)
1168 gotnothing:
1169                 error = copyout((caddr_t)&len, (caddr_t)uap->alen,
1170                     sizeof (len));
1171 bad:
1172         if (sa)
1173                 FREE(sa, M_SONAME);
1174         fdrop(fp, td);
1175         return (error);
1176 }
1177
1178 int
1179 getsockname(struct getsockname_args *uap)
1180 {
1181
1182         return (getsockname1(uap, 0));
1183 }
1184
1185 #ifdef COMPAT_OLDSOCK
1186 int
1187 ogetsockname(struct getsockname_args *uap)
1188 {
1189
1190         return (getsockname1(uap, 1));
1191 }
1192 #endif /* COMPAT_OLDSOCK */
1193
1194 /*
1195  * getpeername_args(int fdes, caddr_t asa, int *alen)
1196  *
1197  * Get name of peer for connected socket.
1198  */
1199 /* ARGSUSED */
1200 static int
1201 getpeername1(struct getpeername_args *uap, int compat)
1202 {
1203         struct thread *td = curthread;
1204         struct proc *p = td->td_proc;
1205         struct file *fp;
1206         struct socket *so;
1207         struct sockaddr *sa;
1208         int len, error;
1209
1210         error = holdsock(p->p_fd, uap->fdes, &fp);
1211         if (error)
1212                 return (error);
1213         so = (struct socket *)fp->f_data;
1214         if ((so->so_state & (SS_ISCONNECTED|SS_ISCONFIRMING)) == 0) {
1215                 fdrop(fp, td);
1216                 return (ENOTCONN);
1217         }
1218         error = copyin((caddr_t)uap->alen, (caddr_t)&len, sizeof (len));
1219         if (error) {
1220                 fdrop(fp, td);
1221                 return (error);
1222         }
1223         if (len < 0) {
1224                 fdrop(fp, td);
1225                 return (EINVAL);
1226         }
1227         sa = 0;
1228         error = (*so->so_proto->pr_usrreqs->pru_peeraddr)(so, &sa);
1229         if (error)
1230                 goto bad;
1231         if (sa == 0) {
1232                 len = 0;
1233                 goto gotnothing;
1234         }
1235         len = MIN(len, sa->sa_len);
1236 #ifdef COMPAT_OLDSOCK
1237         if (compat)
1238                 ((struct osockaddr *)sa)->sa_family =
1239                     sa->sa_family;
1240 #endif
1241         error = copyout(sa, (caddr_t)uap->asa, (u_int)len);
1242         if (error)
1243                 goto bad;
1244 gotnothing:
1245         error = copyout((caddr_t)&len, (caddr_t)uap->alen, sizeof (len));
1246 bad:
1247         if (sa)
1248                 FREE(sa, M_SONAME);
1249         fdrop(fp, td);
1250         return (error);
1251 }
1252
1253 int
1254 getpeername(struct getpeername_args *uap)
1255 {
1256         return (getpeername1(uap, 0));
1257 }
1258
1259 #ifdef COMPAT_OLDSOCK
1260 int
1261 ogetpeername(struct ogetpeername_args *uap)
1262 {
1263         /* XXX uap should have type `getpeername_args *' to begin with. */
1264         return (getpeername1((struct getpeername_args *)uap, 1));
1265 }
1266 #endif /* COMPAT_OLDSOCK */
1267
1268 int
1269 sockargs(mp, buf, buflen, type)
1270         struct mbuf **mp;
1271         caddr_t buf;
1272         int buflen, type;
1273 {
1274         register struct sockaddr *sa;
1275         register struct mbuf *m;
1276         int error;
1277
1278         if ((u_int)buflen > MLEN) {
1279 #ifdef COMPAT_OLDSOCK
1280                 if (type == MT_SONAME && (u_int)buflen <= 112)
1281                         buflen = MLEN;          /* unix domain compat. hack */
1282                 else
1283 #endif
1284                 return (EINVAL);
1285         }
1286         m = m_get(M_WAIT, type);
1287         if (m == NULL)
1288                 return (ENOBUFS);
1289         m->m_len = buflen;
1290         error = copyin(buf, mtod(m, caddr_t), (u_int)buflen);
1291         if (error)
1292                 (void) m_free(m);
1293         else {
1294                 *mp = m;
1295                 if (type == MT_SONAME) {
1296                         sa = mtod(m, struct sockaddr *);
1297
1298 #if defined(COMPAT_OLDSOCK) && BYTE_ORDER != BIG_ENDIAN
1299                         if (sa->sa_family == 0 && sa->sa_len < AF_MAX)
1300                                 sa->sa_family = sa->sa_len;
1301 #endif
1302                         sa->sa_len = buflen;
1303                 }
1304         }
1305         return (error);
1306 }
1307
1308 int
1309 getsockaddr(namp, uaddr, len)
1310         struct sockaddr **namp;
1311         caddr_t uaddr;
1312         size_t len;
1313 {
1314         struct sockaddr *sa;
1315         int error;
1316
1317         if (len > SOCK_MAXADDRLEN)
1318                 return ENAMETOOLONG;
1319         MALLOC(sa, struct sockaddr *, len, M_SONAME, M_WAITOK);
1320         error = copyin(uaddr, sa, len);
1321         if (error) {
1322                 FREE(sa, M_SONAME);
1323         } else {
1324 #if defined(COMPAT_OLDSOCK) && BYTE_ORDER != BIG_ENDIAN
1325                 if (sa->sa_family == 0 && sa->sa_len < AF_MAX)
1326                         sa->sa_family = sa->sa_len;
1327 #endif
1328                 sa->sa_len = len;
1329                 *namp = sa;
1330         }
1331         return error;
1332 }
1333
1334 /*
1335  * holdsock() - load the struct file pointer associated
1336  * with a socket into *fpp.  If an error occurs, non-zero
1337  * will be returned and *fpp will be set to NULL.
1338  */
1339 int
1340 holdsock(fdp, fdes, fpp)
1341         struct filedesc *fdp;
1342         int fdes;
1343         struct file **fpp;
1344 {
1345         register struct file *fp = NULL;
1346         int error = 0;
1347
1348         if ((unsigned)fdes >= fdp->fd_nfiles ||
1349             (fp = fdp->fd_ofiles[fdes]) == NULL) {
1350                 error = EBADF;
1351         } else if (fp->f_type != DTYPE_SOCKET) {
1352                 error = ENOTSOCK;
1353                 fp = NULL;
1354         } else {
1355                 fhold(fp);
1356         }
1357         *fpp = fp;
1358         return(error);
1359 }
1360
1361 /*
1362  * Allocate a pool of sf_bufs (sendfile(2) or "super-fast" if you prefer. :-))
1363  */
1364 static void
1365 sf_buf_init(void *arg)
1366 {
1367         int i;
1368
1369         SLIST_INIT(&sf_freelist);
1370         sf_base = kmem_alloc_pageable(kernel_map, nsfbufs * PAGE_SIZE);
1371         sf_bufs = malloc(nsfbufs * sizeof(struct sf_buf), M_TEMP, M_NOWAIT);
1372         bzero(sf_bufs, nsfbufs * sizeof(struct sf_buf));
1373         for (i = 0; i < nsfbufs; i++) {
1374                 sf_bufs[i].kva = sf_base + i * PAGE_SIZE;
1375                 SLIST_INSERT_HEAD(&sf_freelist, &sf_bufs[i], free_list);
1376         }
1377 }
1378
1379 /*
1380  * Get an sf_buf from the freelist. Will block if none are available.
1381  */
1382 struct sf_buf *
1383 sf_buf_alloc()
1384 {
1385         struct sf_buf *sf;
1386         int s;
1387         int error;
1388
1389         s = splimp();
1390         while ((sf = SLIST_FIRST(&sf_freelist)) == NULL) {
1391                 sf_buf_alloc_want = 1;
1392                 error = tsleep(&sf_freelist, PCATCH, "sfbufa", 0);
1393                 if (error)
1394                         break;
1395         }
1396         if (sf != NULL) {
1397                 SLIST_REMOVE_HEAD(&sf_freelist, free_list);
1398                 sf->refcnt = 1;
1399         }
1400         splx(s);
1401         return (sf);
1402 }
1403
1404 #define dtosf(x)        (&sf_bufs[((uintptr_t)(x) - (uintptr_t)sf_base) >> PAGE_SHIFT])
1405 void
1406 sf_buf_ref(caddr_t addr, u_int size)
1407 {
1408         struct sf_buf *sf;
1409
1410         sf = dtosf(addr);
1411         if (sf->refcnt == 0)
1412                 panic("sf_buf_ref: referencing a free sf_buf");
1413         sf->refcnt++;
1414 }
1415
1416 /*
1417  * Lose a reference to an sf_buf. When none left, detach mapped page
1418  * and release resources back to the system.
1419  *
1420  * Must be called at splimp.
1421  */
1422 void
1423 sf_buf_free(caddr_t addr, u_int size)
1424 {
1425         struct sf_buf *sf;
1426         struct vm_page *m;
1427         int s;
1428
1429         sf = dtosf(addr);
1430         if (sf->refcnt == 0)
1431                 panic("sf_buf_free: freeing free sf_buf");
1432         sf->refcnt--;
1433         if (sf->refcnt == 0) {
1434                 pmap_qremove((vm_offset_t)addr, 1);
1435                 m = sf->m;
1436                 s = splvm();
1437                 vm_page_unwire(m, 0);
1438                 /*
1439                  * Check for the object going away on us. This can
1440                  * happen since we don't hold a reference to it.
1441                  * If so, we're responsible for freeing the page.
1442                  */
1443                 if (m->wire_count == 0 && m->object == NULL)
1444                         vm_page_free(m);
1445                 splx(s);
1446                 sf->m = NULL;
1447                 SLIST_INSERT_HEAD(&sf_freelist, sf, free_list);
1448                 if (sf_buf_alloc_want) {
1449                         sf_buf_alloc_want = 0;
1450                         wakeup(&sf_freelist);
1451                 }
1452         }
1453 }
1454
1455 /*
1456  * sendfile(2).
1457  * int sendfile(int fd, int s, off_t offset, size_t nbytes,
1458  *       struct sf_hdtr *hdtr, off_t *sbytes, int flags)
1459  *
1460  * Send a file specified by 'fd' and starting at 'offset' to a socket
1461  * specified by 's'. Send only 'nbytes' of the file or until EOF if
1462  * nbytes == 0. Optionally add a header and/or trailer to the socket
1463  * output. If specified, write the total number of bytes sent into *sbytes.
1464  */
1465 int
1466 sendfile(struct sendfile_args *uap)
1467 {
1468         return (do_sendfile(uap, 0));
1469 }
1470
1471 #ifdef COMPAT_43
1472 int
1473 osendfile(struct osendfile_args *uap)
1474 {
1475         struct sendfile_args args;
1476
1477         args.fd = uap->fd;
1478         args.s = uap->s;
1479         args.offset = uap->offset;
1480         args.nbytes = uap->nbytes;
1481         args.hdtr = uap->hdtr;
1482         args.sbytes = uap->sbytes;
1483         args.flags = uap->flags;
1484
1485         return (do_sendfile(&args, 1));
1486 }
1487 #endif
1488
1489 int
1490 do_sendfile(struct sendfile_args *uap, int compat)
1491 {
1492         struct thread *td = curthread;
1493         struct proc *p = td->td_proc;
1494         struct file *fp;
1495         struct filedesc *fdp;
1496         struct vnode *vp;
1497         struct vm_object *obj;
1498         struct socket *so;
1499         struct mbuf *m;
1500         struct sf_buf *sf;
1501         struct vm_page *pg;
1502         struct writev_args nuap;
1503         struct sf_hdtr hdtr;
1504         off_t off, xfsize, hdtr_size, sbytes = 0;
1505         int error = 0, s;
1506
1507         KKASSERT(p);
1508         fdp = p->p_fd;
1509
1510         vp = NULL;
1511         hdtr_size = 0;
1512         /*
1513          * Do argument checking. Must be a regular file in, stream
1514          * type and connected socket out, positive offset.
1515          */
1516         fp = holdfp(fdp, uap->fd, FREAD);
1517         if (fp == NULL) {
1518                 error = EBADF;
1519                 goto done;
1520         }
1521         if (fp->f_type != DTYPE_VNODE) {
1522                 error = EINVAL;
1523                 goto done;
1524         }
1525         vp = (struct vnode *)fp->f_data;
1526         vref(vp);
1527         if (vp->v_type != VREG || VOP_GETVOBJECT(vp, &obj) != 0) {
1528                 error = EINVAL;
1529                 goto done;
1530         }
1531         fdrop(fp, td);
1532         error = holdsock(p->p_fd, uap->s, &fp);
1533         if (error)
1534                 goto done;
1535         so = (struct socket *)fp->f_data;
1536         if (so->so_type != SOCK_STREAM) {
1537                 error = EINVAL;
1538                 goto done;
1539         }
1540         if ((so->so_state & SS_ISCONNECTED) == 0) {
1541                 error = ENOTCONN;
1542                 goto done;
1543         }
1544         if (uap->offset < 0) {
1545                 error = EINVAL;
1546                 goto done;
1547         }
1548
1549         /*
1550          * If specified, get the pointer to the sf_hdtr struct for
1551          * any headers/trailers.
1552          */
1553         if (uap->hdtr != NULL) {
1554                 error = copyin(uap->hdtr, &hdtr, sizeof(hdtr));
1555                 if (error)
1556                         goto done;
1557                 /*
1558                  * Send any headers. Wimp out and use writev(2).
1559                  */
1560                 if (hdtr.headers != NULL) {
1561                         nuap.fd = uap->s;
1562                         nuap.iovp = hdtr.headers;
1563                         nuap.iovcnt = hdtr.hdr_cnt;
1564                         error = writev(&nuap);
1565                         if (error)
1566                                 goto done;
1567                         if (compat)
1568                                 sbytes += uap->lmsg.u.ms_result;
1569                         else
1570                                 hdtr_size += uap->lmsg.u.ms_result;
1571                 }
1572         }
1573
1574         /*
1575          * Protect against multiple writers to the socket.
1576          */
1577         (void) sblock(&so->so_snd, M_WAITOK);
1578
1579         /*
1580          * Loop through the pages in the file, starting with the requested
1581          * offset. Get a file page (do I/O if necessary), map the file page
1582          * into an sf_buf, attach an mbuf header to the sf_buf, and queue
1583          * it on the socket.
1584          */
1585         for (off = uap->offset; ; off += xfsize, sbytes += xfsize) {
1586                 vm_pindex_t pindex;
1587                 vm_offset_t pgoff;
1588
1589                 pindex = OFF_TO_IDX(off);
1590 retry_lookup:
1591                 /*
1592                  * Calculate the amount to transfer. Not to exceed a page,
1593                  * the EOF, or the passed in nbytes.
1594                  */
1595                 xfsize = obj->un_pager.vnp.vnp_size - off;
1596                 if (xfsize > PAGE_SIZE)
1597                         xfsize = PAGE_SIZE;
1598                 pgoff = (vm_offset_t)(off & PAGE_MASK);
1599                 if (PAGE_SIZE - pgoff < xfsize)
1600                         xfsize = PAGE_SIZE - pgoff;
1601                 if (uap->nbytes && xfsize > (uap->nbytes - sbytes))
1602                         xfsize = uap->nbytes - sbytes;
1603                 if (xfsize <= 0)
1604                         break;
1605                 /*
1606                  * Optimize the non-blocking case by looking at the socket space
1607                  * before going to the extra work of constituting the sf_buf.
1608                  */
1609                 if ((so->so_state & SS_NBIO) && sbspace(&so->so_snd) <= 0) {
1610                         if (so->so_state & SS_CANTSENDMORE)
1611                                 error = EPIPE;
1612                         else
1613                                 error = EAGAIN;
1614                         sbunlock(&so->so_snd);
1615                         goto done;
1616                 }
1617                 /*
1618                  * Attempt to look up the page.  
1619                  *
1620                  *      Allocate if not found
1621                  *
1622                  *      Wait and loop if busy.
1623                  */
1624                 pg = vm_page_lookup(obj, pindex);
1625
1626                 if (pg == NULL) {
1627                         pg = vm_page_alloc(obj, pindex, VM_ALLOC_NORMAL);
1628                         if (pg == NULL) {
1629                                 VM_WAIT;
1630                                 goto retry_lookup;
1631                         }
1632                         vm_page_wakeup(pg);
1633                 } else if (vm_page_sleep_busy(pg, TRUE, "sfpbsy")) {
1634                         goto retry_lookup;
1635                 }
1636
1637                 /*
1638                  * Wire the page so it does not get ripped out from under
1639                  * us. 
1640                  */
1641
1642                 vm_page_wire(pg);
1643
1644                 /*
1645                  * If page is not valid for what we need, initiate I/O
1646                  */
1647
1648                 if (!pg->valid || !vm_page_is_valid(pg, pgoff, xfsize)) {
1649                         struct uio auio;
1650                         struct iovec aiov;
1651                         int bsize;
1652
1653                         /*
1654                          * Ensure that our page is still around when the I/O 
1655                          * completes.
1656                          */
1657                         vm_page_io_start(pg);
1658
1659                         /*
1660                          * Get the page from backing store.
1661                          */
1662                         bsize = vp->v_mount->mnt_stat.f_iosize;
1663                         auio.uio_iov = &aiov;
1664                         auio.uio_iovcnt = 1;
1665                         aiov.iov_base = 0;
1666                         aiov.iov_len = MAXBSIZE;
1667                         auio.uio_resid = MAXBSIZE;
1668                         auio.uio_offset = trunc_page(off);
1669                         auio.uio_segflg = UIO_NOCOPY;
1670                         auio.uio_rw = UIO_READ;
1671                         auio.uio_td = td;
1672                         vn_lock(vp, LK_SHARED | LK_NOPAUSE | LK_RETRY, td);
1673                         error = VOP_READ(vp, &auio, 
1674                                     IO_VMIO | ((MAXBSIZE / bsize) << 16),
1675                                     p->p_ucred);
1676                         VOP_UNLOCK(vp, 0, td);
1677                         vm_page_flag_clear(pg, PG_ZERO);
1678                         vm_page_io_finish(pg);
1679                         if (error) {
1680                                 vm_page_unwire(pg, 0);
1681                                 /*
1682                                  * See if anyone else might know about this page.
1683                                  * If not and it is not valid, then free it.
1684                                  */
1685                                 if (pg->wire_count == 0 && pg->valid == 0 &&
1686                                     pg->busy == 0 && !(pg->flags & PG_BUSY) &&
1687                                     pg->hold_count == 0) {
1688                                         vm_page_busy(pg);
1689                                         vm_page_free(pg);
1690                                 }
1691                                 sbunlock(&so->so_snd);
1692                                 goto done;
1693                         }
1694                 }
1695
1696
1697                 /*
1698                  * Get a sendfile buf. We usually wait as long as necessary,
1699                  * but this wait can be interrupted.
1700                  */
1701                 if ((sf = sf_buf_alloc()) == NULL) {
1702                         s = splvm();
1703                         vm_page_unwire(pg, 0);
1704                         if (pg->wire_count == 0 && pg->object == NULL)
1705                                 vm_page_free(pg);
1706                         splx(s);
1707                         sbunlock(&so->so_snd);
1708                         error = EINTR;
1709                         goto done;
1710                 }
1711
1712
1713                 /*
1714                  * Allocate a kernel virtual page and insert the physical page
1715                  * into it.
1716                  */
1717
1718                 sf->m = pg;
1719                 pmap_qenter(sf->kva, &pg, 1);
1720                 /*
1721                  * Get an mbuf header and set it up as having external storage.
1722                  */
1723                 MGETHDR(m, M_WAIT, MT_DATA);
1724                 if (m == NULL) {
1725                         error = ENOBUFS;
1726                         sf_buf_free((void *)sf->kva, PAGE_SIZE);
1727                         sbunlock(&so->so_snd);
1728                         goto done;
1729                 }
1730                 m->m_ext.ext_free = sf_buf_free;
1731                 m->m_ext.ext_ref = sf_buf_ref;
1732                 m->m_ext.ext_buf = (void *)sf->kva;
1733                 m->m_ext.ext_size = PAGE_SIZE;
1734                 m->m_data = (char *) sf->kva + pgoff;
1735                 m->m_flags |= M_EXT;
1736                 m->m_pkthdr.len = m->m_len = xfsize;
1737                 /*
1738                  * Add the buffer to the socket buffer chain.
1739                  */
1740                 s = splnet();
1741 retry_space:
1742                 /*
1743                  * Make sure that the socket is still able to take more data.
1744                  * CANTSENDMORE being true usually means that the connection
1745                  * was closed. so_error is true when an error was sensed after
1746                  * a previous send.
1747                  * The state is checked after the page mapping and buffer
1748                  * allocation above since those operations may block and make
1749                  * any socket checks stale. From this point forward, nothing
1750                  * blocks before the pru_send (or more accurately, any blocking
1751                  * results in a loop back to here to re-check).
1752                  */
1753                 if ((so->so_state & SS_CANTSENDMORE) || so->so_error) {
1754                         if (so->so_state & SS_CANTSENDMORE) {
1755                                 error = EPIPE;
1756                         } else {
1757                                 error = so->so_error;
1758                                 so->so_error = 0;
1759                         }
1760                         m_freem(m);
1761                         sbunlock(&so->so_snd);
1762                         splx(s);
1763                         goto done;
1764                 }
1765                 /*
1766                  * Wait for socket space to become available. We do this just
1767                  * after checking the connection state above in order to avoid
1768                  * a race condition with sbwait().
1769                  */
1770                 if (sbspace(&so->so_snd) < so->so_snd.sb_lowat) {
1771                         if (so->so_state & SS_NBIO) {
1772                                 m_freem(m);
1773                                 sbunlock(&so->so_snd);
1774                                 splx(s);
1775                                 error = EAGAIN;
1776                                 goto done;
1777                         }
1778                         error = sbwait(&so->so_snd);
1779                         /*
1780                          * An error from sbwait usually indicates that we've
1781                          * been interrupted by a signal. If we've sent anything
1782                          * then return bytes sent, otherwise return the error.
1783                          */
1784                         if (error) {
1785                                 m_freem(m);
1786                                 sbunlock(&so->so_snd);
1787                                 splx(s);
1788                                 goto done;
1789                         }
1790                         goto retry_space;
1791                 }
1792                 error = 
1793                     (*so->so_proto->pr_usrreqs->pru_send)(so, 0, m, 0, 0, td);
1794                 splx(s);
1795                 if (error) {
1796                         sbunlock(&so->so_snd);
1797                         goto done;
1798                 }
1799         }
1800         sbunlock(&so->so_snd);
1801
1802         /*
1803          * Send trailers. Wimp out and use writev(2).
1804          */
1805         if (uap->hdtr != NULL && hdtr.trailers != NULL) {
1806                         nuap.fd = uap->s;
1807                         nuap.iovp = hdtr.trailers;
1808                         nuap.iovcnt = hdtr.trl_cnt;
1809                         error = writev(&nuap);
1810                         if (error)
1811                                 goto done;
1812                         if (compat)
1813                                 sbytes += uap->lmsg.u.ms_result;
1814                         else
1815                                 hdtr_size += uap->lmsg.u.ms_result;
1816         }
1817
1818 done:
1819         if (uap->sbytes != NULL) {
1820                 if (compat == 0)
1821                         sbytes += hdtr_size;
1822                 copyout(&sbytes, uap->sbytes, sizeof(off_t));
1823         }
1824         if (vp)
1825                 vrele(vp);
1826         if (fp)
1827                 fdrop(fp, td);
1828         return (error);
1829 }