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