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