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