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