Implement an upcall mechanism to support userland LWKT. This mechanism will
[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.20 2003/10/15 08:43:37 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         if (auio->uio_resid < 0) {
538                 error = EINVAL;
539                 goto done;
540         }
541 #ifdef KTRACE
542         if (KTRPOINT(td, KTR_GENIO)) {
543                 int iovlen = auio->uio_iovcnt * sizeof (struct iovec);
544
545                 MALLOC(ktriov, struct iovec *, iovlen, M_TEMP, M_WAITOK);
546                 bcopy((caddr_t)auio->uio_iov, (caddr_t)ktriov, iovlen);
547                 ktruio = *auio;
548         }
549 #endif
550         len = auio->uio_resid;
551         so = (struct socket *)fp->f_data;
552         error = so->so_proto->pr_usrreqs->pru_sosend(so, sa, auio, NULL,
553             control, flags, td);
554         if (error) {
555                 if (auio->uio_resid != len && (error == ERESTART ||
556                     error == EINTR || error == EWOULDBLOCK))
557                         error = 0;
558                 if (error == EPIPE)
559                         psignal(p, SIGPIPE);
560         }
561 #ifdef KTRACE
562         if (ktriov != NULL) {
563                 if (error == 0) {
564                         ktruio.uio_iov = ktriov;
565                         ktruio.uio_resid = len - auio->uio_resid;
566                         ktrgenio(p->p_tracep, s, UIO_WRITE, &ktruio, error);
567                 }
568                 FREE(ktriov, M_TEMP);
569         }
570 #endif
571         if (error == 0)
572                 *res  = len - auio->uio_resid;
573 done:
574         fdrop(fp, td);
575         return (error);
576 }
577
578 /*
579  * sendto_args(int s, caddr_t buf, size_t len, int flags, caddr_t to, int tolen)
580  */
581 int
582 sendto(struct sendto_args *uap)
583 {
584         struct thread *td = curthread;
585         struct uio auio;
586         struct iovec aiov;
587         struct sockaddr *sa = NULL;
588         int error;
589
590         if (uap->to) {
591                 error = getsockaddr(&sa, uap->to, uap->tolen);
592                 if (error)
593                         return (error);
594         }
595         aiov.iov_base = uap->buf;
596         aiov.iov_len = uap->len;
597         auio.uio_iov = &aiov;
598         auio.uio_iovcnt = 1;
599         auio.uio_offset = 0;
600         auio.uio_resid = uap->len;
601         auio.uio_segflg = UIO_USERSPACE;
602         auio.uio_rw = UIO_WRITE;
603         auio.uio_td = td;
604
605         error = kern_sendmsg(uap->s, sa, &auio, NULL, uap->flags,
606             &uap->sysmsg_result);
607
608         if (sa)
609                 FREE(sa, M_SONAME);
610         return (error);
611 }
612
613 /*
614  * sendmsg_args(int s, caddr_t msg, int flags)
615  */
616 int
617 sendmsg(struct sendmsg_args *uap)
618 {
619         struct thread *td = curthread;
620         struct msghdr msg;
621         struct uio auio;
622         struct iovec aiov[UIO_SMALLIOV], *iov = NULL;
623         struct sockaddr *sa = NULL;
624         struct mbuf *control = NULL;
625         int error;
626
627         error = copyin(uap->msg, (caddr_t)&msg, sizeof(msg));
628         if (error)
629                 return (error);
630
631         /*
632          * Conditionally copyin msg.msg_name.
633          */
634         if (msg.msg_name) {
635                 error = getsockaddr(&sa, msg.msg_name, msg.msg_namelen);
636                 if (error)
637                         return (error);
638         }
639
640         /*
641          * Populate auio.
642          */
643         error = iovec_copyin(msg.msg_iov, &iov, aiov, msg.msg_iovlen,
644             &auio.uio_resid);
645         if (error)
646                 goto cleanup;
647         auio.uio_iov = iov;
648         auio.uio_iovcnt = msg.msg_iovlen;
649         auio.uio_offset = 0;
650         auio.uio_segflg = UIO_USERSPACE;
651         auio.uio_rw = UIO_WRITE;
652         auio.uio_td = td;
653
654         /*
655          * Conditionally copyin msg.msg_control.
656          */
657         if (msg.msg_control) {
658                 if (msg.msg_controllen < sizeof(struct cmsghdr) ||
659                     msg.msg_controllen > MLEN) {
660                         error = EINVAL;
661                         goto cleanup;
662                 }
663                 control = m_get(M_WAIT, MT_CONTROL);
664                 if (control == NULL) {
665                         error = ENOBUFS;
666                         goto cleanup;
667                 }
668                 control->m_len = msg.msg_controllen;
669                 error = copyin(msg.msg_control, mtod(control, caddr_t),
670                     msg.msg_controllen);
671                 if (error) {
672                         m_free(control);
673                         goto cleanup;
674                 }
675         }
676
677         error = kern_sendmsg(uap->s, sa, &auio, control, uap->flags,
678             &uap->sysmsg_result);
679
680 cleanup:
681         if (sa)
682                 FREE(sa, M_SONAME);
683         iovec_free(&iov, aiov);
684         return (error);
685 }
686
687 /*
688  * kern_recvmsg() takes a handle to sa and control.  If the handle is non-
689  * null, it returns a dynamically allocated struct sockaddr and an mbuf.
690  * Don't forget to FREE() and m_free() these if they are returned.
691  */
692 int
693 kern_recvmsg(int s, struct sockaddr **sa, struct uio *auio,
694     struct mbuf **control, int *flags, int *res)
695 {
696         struct thread *td = curthread;
697         struct proc *p = td->td_proc;
698         struct file *fp;
699         int len, error;
700         struct socket *so;
701 #ifdef KTRACE
702         struct iovec *ktriov = NULL;
703         struct uio ktruio;
704 #endif
705
706         error = holdsock(p->p_fd, s, &fp);
707         if (error)
708                 return (error);
709         if (auio->uio_resid < 0) {
710                 error = EINVAL;
711                 goto done;
712         }
713 #ifdef KTRACE
714         if (KTRPOINT(td, KTR_GENIO)) {
715                 int iovlen = auio->uio_iovcnt * sizeof (struct iovec);
716
717                 MALLOC(ktriov, struct iovec *, iovlen, M_TEMP, M_WAITOK);
718                 bcopy(auio->uio_iov, ktriov, iovlen);
719                 ktruio = *auio;
720         }
721 #endif
722         len = auio->uio_resid;
723         so = (struct socket *)fp->f_data;
724         error = so->so_proto->pr_usrreqs->pru_soreceive(so, sa, auio, NULL,
725             control, flags);
726         if (error) {
727                 if (auio->uio_resid != len && (error == ERESTART ||
728                     error == EINTR || error == EWOULDBLOCK))
729                         error = 0;
730         }
731 #ifdef KTRACE
732         if (ktriov != NULL) {
733                 if (error == 0) {
734                         ktruio.uio_iov = ktriov;
735                         ktruio.uio_resid = len - auio->uio_resid;
736                         ktrgenio(p->p_tracep, s, UIO_READ, &ktruio, error);
737                 }
738                 FREE(ktriov, M_TEMP);
739         }
740 #endif
741         if (error == 0)
742                 *res = len - auio->uio_resid;
743 done:
744         fdrop(fp, td);
745         return (error);
746 }
747
748 /*
749  * recvfrom_args(int s, caddr_t buf, size_t len, int flags, 
750  *                      caddr_t from, int *fromlenaddr)
751  */
752 int
753 recvfrom(struct recvfrom_args *uap)
754 {
755         struct thread *td = curthread;
756         struct uio auio;
757         struct iovec aiov;
758         struct sockaddr *sa = NULL;
759         int error, fromlen;
760
761         if (uap->from && uap->fromlenaddr) {
762                 error = copyin(uap->fromlenaddr, &fromlen, sizeof(fromlen));
763                 if (error)
764                         return (error);
765                 if (fromlen < 0)
766                         return (EINVAL);
767         } else {
768                 fromlen = 0;
769         }
770         aiov.iov_base = uap->buf;
771         aiov.iov_len = uap->len;
772         auio.uio_iov = &aiov;
773         auio.uio_iovcnt = 1;
774         auio.uio_offset = 0;
775         auio.uio_resid = uap->len;
776         auio.uio_segflg = UIO_USERSPACE;
777         auio.uio_rw = UIO_READ;
778         auio.uio_td = td;
779
780         error = kern_recvmsg(uap->s, uap->from ? &sa : NULL, &auio, NULL,
781             &uap->flags, &uap->sysmsg_result);
782
783         if (error == 0 && uap->from) {
784                 fromlen = MIN(fromlen, sa->sa_len);
785                 error = copyout(sa, uap->from, fromlen);
786                 if (error == 0)
787                         error = copyout(&fromlen, uap->fromlenaddr,
788                             sizeof(fromlen));
789         }
790         if (sa)
791                 FREE(sa, M_SONAME);
792
793         return (error);
794 }
795
796 /*
797  * recvmsg_args(int s, struct msghdr *msg, int flags)
798  */
799 int
800 recvmsg(struct recvmsg_args *uap)
801 {
802         struct thread *td = curthread;
803         struct msghdr msg;
804         struct uio auio;
805         struct iovec aiov[UIO_SMALLIOV], *iov = NULL;
806         struct mbuf *m, *control = NULL;
807         struct sockaddr *sa = NULL;
808         caddr_t ctlbuf;
809         socklen_t *ufromlenp, *ucontrollenp;
810         int error, fromlen, controllen, len, flags, *uflagsp;
811
812         /*
813          * This copyin handles everything except the iovec.
814          */
815         error = copyin(uap->msg, &msg, sizeof(msg));
816         if (error)
817                 return (error);
818
819         if (msg.msg_name && msg.msg_namelen < 0)
820                 return (EINVAL);
821         if (msg.msg_control && msg.msg_controllen < 0)
822                 return (EINVAL);
823
824         ufromlenp = (socklen_t *)((caddr_t)uap->msg + offsetof(struct msghdr,
825             msg_namelen));
826         ucontrollenp = (socklen_t *)((caddr_t)uap->msg + offsetof(struct msghdr,
827             msg_controllen));
828         uflagsp = (int *)((caddr_t)uap->msg + offsetof(struct msghdr,
829             msg_flags));
830
831         /*
832          * Populate auio.
833          */
834         error = iovec_copyin(msg.msg_iov, &iov, aiov, msg.msg_iovlen,
835             &auio.uio_resid);
836         if (error)
837                 return (error);
838         auio.uio_iov = iov;
839         auio.uio_iovcnt = msg.msg_iovlen;
840         auio.uio_offset = 0;
841         auio.uio_segflg = UIO_USERSPACE;
842         auio.uio_rw = UIO_READ;
843         auio.uio_td = td;
844
845         flags = msg.msg_flags;
846
847         error = kern_recvmsg(uap->s, msg.msg_name ? &sa : NULL, &auio,
848             msg.msg_control ? &control : NULL, &flags, &uap->sysmsg_result);
849
850         /*
851          * Conditionally copyout the name and populate the namelen field.
852          */
853         if (error == 0 && msg.msg_name) {
854                 fromlen = MIN(msg.msg_namelen, sa->sa_len);
855                 error = copyout(sa, msg.msg_name, fromlen);
856                 if (error == 0)
857                         error = copyout(&fromlen, ufromlenp,
858                             sizeof(*ufromlenp));
859         }
860
861         /*
862          * Copyout msg.msg_control and msg.msg_controllen.
863          */
864         if (error == 0 && msg.msg_control) {
865                 len = msg.msg_controllen;
866                 m = control;
867                 ctlbuf = (caddr_t)msg.msg_control;
868
869                 while(m && len > 0) {
870                         unsigned int tocopy;
871
872                         if (len >= m->m_len) {
873                                 tocopy = m->m_len;
874                         } else {
875                                 msg.msg_flags |= MSG_CTRUNC;
876                                 tocopy = len;
877                         }
878
879                         error = copyout(mtod(m, caddr_t), ctlbuf, tocopy);
880                         if (error)
881                                 goto cleanup;
882
883                         ctlbuf += tocopy;
884                         len -= tocopy;
885                         m = m->m_next;
886                 }
887                 controllen = ctlbuf - (caddr_t)msg.msg_control;
888                 error = copyout(&controllen, ucontrollenp,
889                     sizeof(*ucontrollenp));
890         }
891
892         if (error == 0)
893                 error = copyout(&flags, uflagsp, sizeof(*uflagsp));
894
895 cleanup:
896         if (sa)
897                 FREE(sa, M_SONAME);
898         iovec_free(&iov, aiov);
899         if (control)
900                 m_freem(control);
901         return (error);
902 }
903
904 /*
905  * shutdown_args(int s, int how)
906  */
907 int
908 kern_shutdown(int s, int how)
909 {
910         struct thread *td = curthread;
911         struct proc *p = td->td_proc;
912         struct file *fp;
913         int error;
914
915         KKASSERT(p);
916         error = holdsock(p->p_fd, s, &fp);
917         if (error)
918                 return (error);
919         error = soshutdown((struct socket *)fp->f_data, how);
920         fdrop(fp, td);
921         return(error);
922 }
923
924 int
925 shutdown(struct shutdown_args *uap)
926 {
927         int error;
928
929         error = kern_shutdown(uap->s, uap->how);
930
931         return (error);
932 }
933
934 /*
935  * If sopt->sopt_td == NULL, then sopt->sopt_val is treated as an
936  * in kernel pointer instead of a userland pointer.  This allows us
937  * to manipulate socket options in the emulation code.
938  */
939 int
940 kern_setsockopt(int s, struct sockopt *sopt)
941 {
942         struct thread *td = curthread;
943         struct proc *p = td->td_proc;
944         struct file *fp;
945         int error;
946
947         if (sopt->sopt_val == 0 && sopt->sopt_valsize != 0)
948                 return (EFAULT);
949         if (sopt->sopt_valsize < 0)
950                 return (EINVAL);
951
952         error = holdsock(p->p_fd, s, &fp);
953         if (error)
954                 return (error);
955
956         error = sosetopt((struct socket *)fp->f_data, sopt);
957         fdrop(fp, td);
958         return (error);
959 }
960
961 /*
962  * setsockopt_args(int s, int level, int name, caddr_t val, int valsize)
963  */
964 int
965 setsockopt(struct setsockopt_args *uap)
966 {
967         struct thread *td = curthread;
968         struct sockopt sopt;
969         int error;
970
971         sopt.sopt_dir = SOPT_SET;
972         sopt.sopt_level = uap->level;
973         sopt.sopt_name = uap->name;
974         sopt.sopt_val = uap->val;
975         sopt.sopt_valsize = uap->valsize;
976         sopt.sopt_td = td;
977
978         error = kern_setsockopt(uap->s, &sopt);
979         return(error);
980 }
981
982 /*
983  * If sopt->sopt_td == NULL, then sopt->sopt_val is treated as an
984  * in kernel pointer instead of a userland pointer.  This allows us
985  * to manipulate socket options in the emulation code.
986  */
987 int
988 kern_getsockopt(int s, struct sockopt *sopt)
989 {
990         struct thread *td = curthread;
991         struct proc *p = td->td_proc;
992         struct file *fp;
993         int error;
994
995         if (sopt->sopt_val == 0 && sopt->sopt_valsize != 0)
996                 return (EFAULT);
997         if (sopt->sopt_valsize < 0)
998                 return (EINVAL);
999
1000         error = holdsock(p->p_fd, s, &fp);
1001         if (error)
1002                 return (error);
1003
1004         error = sogetopt((struct socket *)fp->f_data, sopt);
1005         fdrop(fp, td);
1006         return (error);
1007 }
1008
1009 /*
1010  * getsockopt_Args(int s, int level, int name, caddr_t val, int *avalsize)
1011  */
1012 int
1013 getsockopt(struct getsockopt_args *uap)
1014 {
1015         struct thread *td = curthread;
1016         struct  sockopt sopt;
1017         int     error, valsize;
1018
1019         if (uap->val) {
1020                 error = copyin(uap->avalsize, &valsize, sizeof(valsize));
1021                 if (error)
1022                         return (error);
1023                 if (valsize < 0)
1024                         return (EINVAL);
1025         } else {
1026                 valsize = 0;
1027         }
1028
1029         sopt.sopt_dir = SOPT_GET;
1030         sopt.sopt_level = uap->level;
1031         sopt.sopt_name = uap->name;
1032         sopt.sopt_val = uap->val;
1033         sopt.sopt_valsize = valsize;
1034         sopt.sopt_td = td;
1035
1036         error = kern_getsockopt(uap->s, &sopt);
1037         if (error == 0) {
1038                 valsize = sopt.sopt_valsize;
1039                 error = copyout(&valsize, uap->avalsize, sizeof(valsize));
1040         }
1041         return (error);
1042 }
1043
1044 /*
1045  * The second argument to kern_getsockname() is a handle to a struct sockaddr.
1046  * This allows kern_getsockname() to return a pointer to an allocated struct
1047  * sockaddr which must be freed later with FREE().  The caller must
1048  * initialize *name to NULL.
1049  */
1050 int
1051 kern_getsockname(int s, struct sockaddr **name, int *namelen)
1052 {
1053         struct thread *td = curthread;
1054         struct proc *p = td->td_proc;
1055         struct file *fp;
1056         struct socket *so;
1057         struct sockaddr *sa = NULL;
1058         int error;
1059
1060         error = holdsock(p->p_fd, s, &fp);
1061         if (error)
1062                 return (error);
1063         if (*namelen < 0) {
1064                 fdrop(fp, td);
1065                 return (EINVAL);
1066         }
1067         so = (struct socket *)fp->f_data;
1068         error = (*so->so_proto->pr_usrreqs->pru_sockaddr)(so, &sa);
1069         if (error == 0) {
1070                 if (sa == 0) {
1071                         *namelen = 0;
1072                 } else {
1073                         *namelen = MIN(*namelen, sa->sa_len);
1074                         *name = sa;
1075                 }
1076         }
1077
1078         fdrop(fp, td);
1079         return (error);
1080 }
1081
1082 /*
1083  * getsockname_args(int fdes, caddr_t asa, int *alen)
1084  *
1085  * Get socket name.
1086  */
1087 int
1088 getsockname(struct getsockname_args *uap)
1089 {
1090         struct sockaddr *sa = NULL;
1091         int error, sa_len;
1092
1093         error = copyin(uap->alen, &sa_len, sizeof(sa_len));
1094         if (error)
1095                 return (error);
1096
1097         error = kern_getsockname(uap->fdes, &sa, &sa_len);
1098
1099         if (error == 0)
1100                 error = copyout(sa, uap->asa, sa_len);
1101         if (error == 0)
1102                 error = copyout(&sa_len, uap->alen, sizeof(*uap->alen));
1103         if (sa)
1104                 FREE(sa, M_SONAME);
1105         return (error);
1106 }
1107
1108 /*
1109  * The second argument to kern_getpeername() is a handle to a struct sockaddr.
1110  * This allows kern_getpeername() to return a pointer to an allocated struct
1111  * sockaddr which must be freed later with FREE().  The caller must
1112  * initialize *name to NULL.
1113  */
1114 int
1115 kern_getpeername(int s, struct sockaddr **name, int *namelen)
1116 {
1117         struct thread *td = curthread;
1118         struct proc *p = td->td_proc;
1119         struct file *fp;
1120         struct socket *so;
1121         struct sockaddr *sa = NULL;
1122         int error;
1123
1124         error = holdsock(p->p_fd, s, &fp);
1125         if (error)
1126                 return (error);
1127         if (*namelen < 0) {
1128                 fdrop(fp, td);
1129                 return (EINVAL);
1130         }
1131         so = (struct socket *)fp->f_data;
1132         if ((so->so_state & (SS_ISCONNECTED|SS_ISCONFIRMING)) == 0) {
1133                 fdrop(fp, td);
1134                 return (ENOTCONN);
1135         }
1136         error = (*so->so_proto->pr_usrreqs->pru_peeraddr)(so, &sa);
1137         if (error == 0) {
1138                 if (sa == 0) {
1139                         *namelen = 0;
1140                 } else {
1141                         *namelen = MIN(*namelen, sa->sa_len);
1142                         *name = sa;
1143                 }
1144         }
1145
1146         fdrop(fp, td);
1147         return (error);
1148 }
1149
1150 /*
1151  * getpeername_args(int fdes, caddr_t asa, int *alen)
1152  *
1153  * Get name of peer for connected socket.
1154  */
1155 int
1156 getpeername(struct getpeername_args *uap)
1157 {
1158         struct sockaddr *sa = NULL;
1159         int error, sa_len;
1160
1161         error = copyin(uap->alen, &sa_len, sizeof(sa_len));
1162         if (error)
1163                 return (error);
1164
1165         error = kern_getpeername(uap->fdes, &sa, &sa_len);
1166
1167         if (error == 0)
1168                 error = copyout(sa, uap->asa, sa_len);
1169         if (error == 0)
1170                 error = copyout(&sa_len, uap->alen, sizeof(*uap->alen));
1171         if (sa)
1172                 FREE(sa, M_SONAME);
1173         return (error);
1174 }
1175
1176 int
1177 getsockaddr(struct sockaddr **namp, caddr_t uaddr, size_t len)
1178 {
1179         struct sockaddr *sa;
1180         int error;
1181
1182         *namp = NULL;
1183         if (len > SOCK_MAXADDRLEN)
1184                 return ENAMETOOLONG;
1185         if (len < offsetof(struct sockaddr, sa_data[0]))
1186                 return EDOM;
1187         MALLOC(sa, struct sockaddr *, len, M_SONAME, M_WAITOK);
1188         error = copyin(uaddr, sa, len);
1189         if (error) {
1190                 FREE(sa, M_SONAME);
1191         } else {
1192 #if BYTE_ORDER != BIG_ENDIAN
1193                 /*
1194                  * The bind(), connect(), and sendto() syscalls were not
1195                  * versioned for COMPAT_43.  Thus, this check must stay.
1196                  */
1197                 if (sa->sa_family == 0 && sa->sa_len < AF_MAX)
1198                         sa->sa_family = sa->sa_len;
1199 #endif
1200                 sa->sa_len = len;
1201                 *namp = sa;
1202         }
1203         return error;
1204 }
1205
1206 /*
1207  * holdsock() - load the struct file pointer associated
1208  * with a socket into *fpp.  If an error occurs, non-zero
1209  * will be returned and *fpp will be set to NULL.
1210  */
1211 int
1212 holdsock(fdp, fdes, fpp)
1213         struct filedesc *fdp;
1214         int fdes;
1215         struct file **fpp;
1216 {
1217         struct file *fp = NULL;
1218         int error = 0;
1219
1220         if ((unsigned)fdes >= fdp->fd_nfiles ||
1221             (fp = fdp->fd_ofiles[fdes]) == NULL) {
1222                 error = EBADF;
1223         } else if (fp->f_type != DTYPE_SOCKET) {
1224                 error = ENOTSOCK;
1225                 fp = NULL;
1226         } else {
1227                 fhold(fp);
1228         }
1229         *fpp = fp;
1230         return(error);
1231 }
1232
1233 /*
1234  * Allocate a pool of sf_bufs (sendfile(2) or "super-fast" if you prefer. :-))
1235  */
1236 static void
1237 sf_buf_init(void *arg)
1238 {
1239         int i;
1240
1241         SLIST_INIT(&sf_freelist);
1242         sf_base = kmem_alloc_pageable(kernel_map, nsfbufs * PAGE_SIZE);
1243         sf_bufs = malloc(nsfbufs * sizeof(struct sf_buf), M_TEMP, M_NOWAIT);
1244         bzero(sf_bufs, nsfbufs * sizeof(struct sf_buf));
1245         for (i = 0; i < nsfbufs; i++) {
1246                 sf_bufs[i].kva = sf_base + i * PAGE_SIZE;
1247                 SLIST_INSERT_HEAD(&sf_freelist, &sf_bufs[i], free_list);
1248         }
1249 }
1250
1251 /*
1252  * Get an sf_buf from the freelist. Will block if none are available.
1253  */
1254 struct sf_buf *
1255 sf_buf_alloc()
1256 {
1257         struct sf_buf *sf;
1258         int s;
1259         int error;
1260
1261         s = splimp();
1262         while ((sf = SLIST_FIRST(&sf_freelist)) == NULL) {
1263                 sf_buf_alloc_want = 1;
1264                 error = tsleep(&sf_freelist, PCATCH, "sfbufa", 0);
1265                 if (error)
1266                         break;
1267         }
1268         if (sf != NULL) {
1269                 SLIST_REMOVE_HEAD(&sf_freelist, free_list);
1270                 sf->refcnt = 1;
1271         }
1272         splx(s);
1273         return (sf);
1274 }
1275
1276 #define dtosf(x)        (&sf_bufs[((uintptr_t)(x) - (uintptr_t)sf_base) >> PAGE_SHIFT])
1277 void
1278 sf_buf_ref(caddr_t addr, u_int size)
1279 {
1280         struct sf_buf *sf;
1281
1282         sf = dtosf(addr);
1283         if (sf->refcnt == 0)
1284                 panic("sf_buf_ref: referencing a free sf_buf");
1285         sf->refcnt++;
1286 }
1287
1288 /*
1289  * Lose a reference to an sf_buf. When none left, detach mapped page
1290  * and release resources back to the system.
1291  *
1292  * Must be called at splimp.
1293  */
1294 void
1295 sf_buf_free(caddr_t addr, u_int size)
1296 {
1297         struct sf_buf *sf;
1298         struct vm_page *m;
1299         int s;
1300
1301         sf = dtosf(addr);
1302         if (sf->refcnt == 0)
1303                 panic("sf_buf_free: freeing free sf_buf");
1304         sf->refcnt--;
1305         if (sf->refcnt == 0) {
1306                 pmap_qremove((vm_offset_t)addr, 1);
1307                 m = sf->m;
1308                 s = splvm();
1309                 vm_page_unwire(m, 0);
1310                 /*
1311                  * Check for the object going away on us. This can
1312                  * happen since we don't hold a reference to it.
1313                  * If so, we're responsible for freeing the page.
1314                  */
1315                 if (m->wire_count == 0 && m->object == NULL)
1316                         vm_page_free(m);
1317                 splx(s);
1318                 sf->m = NULL;
1319                 SLIST_INSERT_HEAD(&sf_freelist, sf, free_list);
1320                 if (sf_buf_alloc_want) {
1321                         sf_buf_alloc_want = 0;
1322                         wakeup(&sf_freelist);
1323                 }
1324         }
1325 }
1326
1327 /*
1328  * sendfile(2).
1329  * int sendfile(int fd, int s, off_t offset, size_t nbytes,
1330  *       struct sf_hdtr *hdtr, off_t *sbytes, int flags)
1331  *
1332  * Send a file specified by 'fd' and starting at 'offset' to a socket
1333  * specified by 's'. Send only 'nbytes' of the file or until EOF if
1334  * nbytes == 0. Optionally add a header and/or trailer to the socket
1335  * output. If specified, write the total number of bytes sent into *sbytes.
1336  *
1337  * In FreeBSD kern/uipc_syscalls.c,v 1.103, a bug was fixed that caused
1338  * the headers to count against the remaining bytes to be sent from
1339  * the file descriptor.  We may wish to implement a compatibility syscall
1340  * in the future.
1341  */
1342 int
1343 sendfile(struct sendfile_args *uap)
1344 {
1345         struct thread *td = curthread;
1346         struct proc *p = td->td_proc;
1347         struct file *fp;
1348         struct filedesc *fdp;
1349         struct vnode *vp = NULL;
1350         struct sf_hdtr hdtr;
1351         struct iovec aiov[UIO_SMALLIOV], *iov = NULL;
1352         struct uio auio;
1353         off_t hdtr_size = 0, sbytes;
1354         int error, res;
1355
1356         KKASSERT(p);
1357         fdp = p->p_fd;
1358
1359         /*
1360          * Do argument checking. Must be a regular file in, stream
1361          * type and connected socket out, positive offset.
1362          */
1363         fp = holdfp(fdp, uap->fd, FREAD);
1364         if (fp == NULL) {
1365                 return (EBADF);
1366         }
1367         if (fp->f_type != DTYPE_VNODE) {
1368                 fdrop(fp, td);
1369                 return (EINVAL);
1370         }
1371         vp = (struct vnode *)fp->f_data;
1372         vref(vp);
1373         fdrop(fp, td);
1374
1375         /*
1376          * If specified, get the pointer to the sf_hdtr struct for
1377          * any headers/trailers.
1378          */
1379         if (uap->hdtr) {
1380                 error = copyin(uap->hdtr, &hdtr, sizeof(hdtr));
1381                 if (error)
1382                         goto done;
1383                 /*
1384                  * Send any headers.
1385                  */
1386                 if (hdtr.headers) {
1387                         error = iovec_copyin(hdtr.headers, &iov, aiov,
1388                             hdtr.hdr_cnt, &auio.uio_resid);
1389                         if (error)
1390                                 goto done;
1391                         auio.uio_iov = iov;
1392                         auio.uio_iovcnt = hdtr.hdr_cnt;
1393                         auio.uio_offset = 0;
1394                         auio.uio_segflg = UIO_USERSPACE;
1395                         auio.uio_rw = UIO_WRITE;
1396                         auio.uio_td = td;
1397
1398                         error = kern_sendmsg(uap->s, NULL, &auio, NULL, 0,
1399                             &res);
1400
1401                         iovec_free(&iov, aiov);
1402                         if (error)
1403                                 goto done;
1404                         hdtr_size += res;
1405                 }
1406         }
1407
1408         error = kern_sendfile(vp, uap->s, uap->offset, uap->nbytes,
1409             &sbytes, uap->flags);
1410         if (error)
1411                 goto done;
1412
1413         /*
1414          * Send trailers. Wimp out and use writev(2).
1415          */
1416         if (uap->hdtr != NULL && hdtr.trailers != NULL) {
1417                 error = iovec_copyin(hdtr.trailers, &iov, aiov,
1418                     hdtr.trl_cnt, &auio.uio_resid);
1419                 if (error)
1420                         goto done;
1421                 auio.uio_iov = iov;
1422                 auio.uio_iovcnt = hdtr.trl_cnt;
1423                 auio.uio_offset = 0;
1424                 auio.uio_segflg = UIO_USERSPACE;
1425                 auio.uio_rw = UIO_WRITE;
1426                 auio.uio_td = td;
1427
1428                 error = kern_sendmsg(uap->s, NULL, &auio, NULL, 0, &res);
1429
1430                 iovec_free(&iov, aiov);
1431                 if (error)
1432                         goto done;
1433                 hdtr_size += res;
1434         }
1435
1436 done:
1437         if (uap->sbytes != NULL) {
1438                 sbytes += hdtr_size;
1439                 copyout(&sbytes, uap->sbytes, sizeof(off_t));
1440         }
1441         if (vp)
1442                 vrele(vp);
1443         return (error);
1444 }
1445
1446 int
1447 kern_sendfile(struct vnode *vp, int s, off_t offset, size_t nbytes,
1448     off_t *sbytes, int flags)
1449 {
1450         struct thread *td = curthread;
1451         struct proc *p = td->td_proc;
1452         struct vm_object *obj;
1453         struct socket *so;
1454         struct file *fp;
1455         struct mbuf *m;
1456         struct sf_buf *sf;
1457         struct vm_page *pg;
1458         off_t off, xfsize;
1459         int error = 0;
1460
1461         if (vp->v_type != VREG || VOP_GETVOBJECT(vp, &obj) != 0) {
1462                 error = EINVAL;
1463                 goto done;
1464         }
1465         error = holdsock(p->p_fd, s, &fp);
1466         if (error)
1467                 goto done;
1468         so = (struct socket *)fp->f_data;
1469         if (so->so_type != SOCK_STREAM) {
1470                 error = EINVAL;
1471                 goto done;
1472         }
1473         if ((so->so_state & SS_ISCONNECTED) == 0) {
1474                 error = ENOTCONN;
1475                 goto done;
1476         }
1477         if (offset < 0) {
1478                 error = EINVAL;
1479                 goto done;
1480         }
1481
1482         *sbytes = 0;
1483         /*
1484          * Protect against multiple writers to the socket.
1485          */
1486         (void) sblock(&so->so_snd, M_WAITOK);
1487
1488         /*
1489          * Loop through the pages in the file, starting with the requested
1490          * offset. Get a file page (do I/O if necessary), map the file page
1491          * into an sf_buf, attach an mbuf header to the sf_buf, and queue
1492          * it on the socket.
1493          */
1494         for (off = offset; ; off += xfsize, *sbytes += xfsize) {
1495                 vm_pindex_t pindex;
1496                 vm_offset_t pgoff;
1497
1498                 pindex = OFF_TO_IDX(off);
1499 retry_lookup:
1500                 /*
1501                  * Calculate the amount to transfer. Not to exceed a page,
1502                  * the EOF, or the passed in nbytes.
1503                  */
1504                 xfsize = obj->un_pager.vnp.vnp_size - off;
1505                 if (xfsize > PAGE_SIZE)
1506                         xfsize = PAGE_SIZE;
1507                 pgoff = (vm_offset_t)(off & PAGE_MASK);
1508                 if (PAGE_SIZE - pgoff < xfsize)
1509                         xfsize = PAGE_SIZE - pgoff;
1510                 if (nbytes && xfsize > (nbytes - *sbytes))
1511                         xfsize = nbytes - *sbytes;
1512                 if (xfsize <= 0)
1513                         break;
1514                 /*
1515                  * Optimize the non-blocking case by looking at the socket space
1516                  * before going to the extra work of constituting the sf_buf.
1517                  */
1518                 if ((so->so_state & SS_NBIO) && sbspace(&so->so_snd) <= 0) {
1519                         if (so->so_state & SS_CANTSENDMORE)
1520                                 error = EPIPE;
1521                         else
1522                                 error = EAGAIN;
1523                         sbunlock(&so->so_snd);
1524                         goto done;
1525                 }
1526                 /*
1527                  * Attempt to look up the page.  
1528                  *
1529                  *      Allocate if not found
1530                  *
1531                  *      Wait and loop if busy.
1532                  */
1533                 pg = vm_page_lookup(obj, pindex);
1534
1535                 if (pg == NULL) {
1536                         pg = vm_page_alloc(obj, pindex, VM_ALLOC_NORMAL);
1537                         if (pg == NULL) {
1538                                 VM_WAIT;
1539                                 goto retry_lookup;
1540                         }
1541                         vm_page_wakeup(pg);
1542                 } else if (vm_page_sleep_busy(pg, TRUE, "sfpbsy")) {
1543                         goto retry_lookup;
1544                 }
1545
1546                 /*
1547                  * Wire the page so it does not get ripped out from under
1548                  * us. 
1549                  */
1550
1551                 vm_page_wire(pg);
1552
1553                 /*
1554                  * If page is not valid for what we need, initiate I/O
1555                  */
1556
1557                 if (!pg->valid || !vm_page_is_valid(pg, pgoff, xfsize)) {
1558                         struct uio auio;
1559                         struct iovec aiov;
1560                         int bsize;
1561
1562                         /*
1563                          * Ensure that our page is still around when the I/O 
1564                          * completes.
1565                          */
1566                         vm_page_io_start(pg);
1567
1568                         /*
1569                          * Get the page from backing store.
1570                          */
1571                         bsize = vp->v_mount->mnt_stat.f_iosize;
1572                         auio.uio_iov = &aiov;
1573                         auio.uio_iovcnt = 1;
1574                         aiov.iov_base = 0;
1575                         aiov.iov_len = MAXBSIZE;
1576                         auio.uio_resid = MAXBSIZE;
1577                         auio.uio_offset = trunc_page(off);
1578                         auio.uio_segflg = UIO_NOCOPY;
1579                         auio.uio_rw = UIO_READ;
1580                         auio.uio_td = td;
1581                         vn_lock(vp, LK_SHARED | LK_NOPAUSE | LK_RETRY, td);
1582                         error = VOP_READ(vp, &auio, 
1583                                     IO_VMIO | ((MAXBSIZE / bsize) << 16),
1584                                     p->p_ucred);
1585                         VOP_UNLOCK(vp, 0, td);
1586                         vm_page_flag_clear(pg, PG_ZERO);
1587                         vm_page_io_finish(pg);
1588                         if (error) {
1589                                 vm_page_unwire(pg, 0);
1590                                 /*
1591                                  * See if anyone else might know about this page.
1592                                  * If not and it is not valid, then free it.
1593                                  */
1594                                 if (pg->wire_count == 0 && pg->valid == 0 &&
1595                                     pg->busy == 0 && !(pg->flags & PG_BUSY) &&
1596                                     pg->hold_count == 0) {
1597                                         vm_page_busy(pg);
1598                                         vm_page_free(pg);
1599                                 }
1600                                 sbunlock(&so->so_snd);
1601                                 goto done;
1602                         }
1603                 }
1604
1605
1606                 /*
1607                  * Get a sendfile buf. We usually wait as long as necessary,
1608                  * but this wait can be interrupted.
1609                  */
1610                 if ((sf = sf_buf_alloc()) == NULL) {
1611                         s = splvm();
1612                         vm_page_unwire(pg, 0);
1613                         if (pg->wire_count == 0 && pg->object == NULL)
1614                                 vm_page_free(pg);
1615                         splx(s);
1616                         sbunlock(&so->so_snd);
1617                         error = EINTR;
1618                         goto done;
1619                 }
1620
1621
1622                 /*
1623                  * Allocate a kernel virtual page and insert the physical page
1624                  * into it.
1625                  */
1626
1627                 sf->m = pg;
1628                 pmap_qenter(sf->kva, &pg, 1);
1629                 /*
1630                  * Get an mbuf header and set it up as having external storage.
1631                  */
1632                 MGETHDR(m, M_WAIT, MT_DATA);
1633                 if (m == NULL) {
1634                         error = ENOBUFS;
1635                         sf_buf_free((void *)sf->kva, PAGE_SIZE);
1636                         sbunlock(&so->so_snd);
1637                         goto done;
1638                 }
1639                 m->m_ext.ext_free = sf_buf_free;
1640                 m->m_ext.ext_ref = sf_buf_ref;
1641                 m->m_ext.ext_buf = (void *)sf->kva;
1642                 m->m_ext.ext_size = PAGE_SIZE;
1643                 m->m_data = (char *) sf->kva + pgoff;
1644                 m->m_flags |= M_EXT;
1645                 m->m_pkthdr.len = m->m_len = xfsize;
1646                 /*
1647                  * Add the buffer to the socket buffer chain.
1648                  */
1649                 s = splnet();
1650 retry_space:
1651                 /*
1652                  * Make sure that the socket is still able to take more data.
1653                  * CANTSENDMORE being true usually means that the connection
1654                  * was closed. so_error is true when an error was sensed after
1655                  * a previous send.
1656                  * The state is checked after the page mapping and buffer
1657                  * allocation above since those operations may block and make
1658                  * any socket checks stale. From this point forward, nothing
1659                  * blocks before the pru_send (or more accurately, any blocking
1660                  * results in a loop back to here to re-check).
1661                  */
1662                 if ((so->so_state & SS_CANTSENDMORE) || so->so_error) {
1663                         if (so->so_state & SS_CANTSENDMORE) {
1664                                 error = EPIPE;
1665                         } else {
1666                                 error = so->so_error;
1667                                 so->so_error = 0;
1668                         }
1669                         m_freem(m);
1670                         sbunlock(&so->so_snd);
1671                         splx(s);
1672                         goto done;
1673                 }
1674                 /*
1675                  * Wait for socket space to become available. We do this just
1676                  * after checking the connection state above in order to avoid
1677                  * a race condition with sbwait().
1678                  */
1679                 if (sbspace(&so->so_snd) < so->so_snd.sb_lowat) {
1680                         if (so->so_state & SS_NBIO) {
1681                                 m_freem(m);
1682                                 sbunlock(&so->so_snd);
1683                                 splx(s);
1684                                 error = EAGAIN;
1685                                 goto done;
1686                         }
1687                         error = sbwait(&so->so_snd);
1688                         /*
1689                          * An error from sbwait usually indicates that we've
1690                          * been interrupted by a signal. If we've sent anything
1691                          * then return bytes sent, otherwise return the error.
1692                          */
1693                         if (error) {
1694                                 m_freem(m);
1695                                 sbunlock(&so->so_snd);
1696                                 splx(s);
1697                                 goto done;
1698                         }
1699                         goto retry_space;
1700                 }
1701                 error = 
1702                     (*so->so_proto->pr_usrreqs->pru_send)(so, 0, m, 0, 0, td);
1703                 splx(s);
1704                 if (error) {
1705                         sbunlock(&so->so_snd);
1706                         goto done;
1707                 }
1708         }
1709         sbunlock(&so->so_snd);
1710
1711 done:
1712         if (fp)
1713                 fdrop(fp, td);
1714         return (error);
1715 }