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