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