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