kern_sendfile.c revision 101842
1/*
2 * Copyright (c) 1982, 1986, 1989, 1990, 1993
3 *	The Regents of the University of California.  All rights reserved.
4 *
5 * sendfile(2) and related extensions:
6 * Copyright (c) 1998, David Greenman. All rights reserved.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 * 1. Redistributions of source code must retain the above copyright
12 *    notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 *    notice, this list of conditions and the following disclaimer in the
15 *    documentation and/or other materials provided with the distribution.
16 * 3. All advertising materials mentioning features or use of this software
17 *    must display the following acknowledgement:
18 *	This product includes software developed by the University of
19 *	California, Berkeley and its contributors.
20 * 4. Neither the name of the University nor the names of its contributors
21 *    may be used to endorse or promote products derived from this software
22 *    without specific prior written permission.
23 *
24 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 * SUCH DAMAGE.
35 *
36 *	@(#)uipc_syscalls.c	8.4 (Berkeley) 2/21/94
37 * $FreeBSD: head/sys/kern/uipc_syscalls.c 101842 2002-08-13 19:03:19Z dg $
38 */
39
40#include "opt_compat.h"
41#include "opt_ktrace.h"
42#include "opt_mac.h"
43
44#include <sys/param.h>
45#include <sys/systm.h>
46#include <sys/kernel.h>
47#include <sys/lock.h>
48#include <sys/mac.h>
49#include <sys/mutex.h>
50#include <sys/sysproto.h>
51#include <sys/malloc.h>
52#include <sys/filedesc.h>
53#include <sys/event.h>
54#include <sys/proc.h>
55#include <sys/fcntl.h>
56#include <sys/file.h>
57#include <sys/lock.h>
58#include <sys/mount.h>
59#include <sys/mbuf.h>
60#include <sys/protosw.h>
61#include <sys/socket.h>
62#include <sys/socketvar.h>
63#include <sys/signalvar.h>
64#include <sys/uio.h>
65#include <sys/vnode.h>
66#ifdef KTRACE
67#include <sys/ktrace.h>
68#endif
69
70#include <vm/vm.h>
71#include <vm/vm_object.h>
72#include <vm/vm_page.h>
73#include <vm/vm_pageout.h>
74#include <vm/vm_kern.h>
75#include <vm/vm_extern.h>
76
77static void sf_buf_init(void *arg);
78SYSINIT(sock_sf, SI_SUB_MBUF, SI_ORDER_ANY, sf_buf_init, NULL)
79
80static int sendit(struct thread *td, int s, struct msghdr *mp, int flags);
81static int recvit(struct thread *td, int s, struct msghdr *mp, void *namelenp);
82
83static int accept1(struct thread *td, struct accept_args *uap, int compat);
84static int do_sendfile(struct thread *td, struct sendfile_args *uap, int compat);
85static int getsockname1(struct thread *td, struct getsockname_args *uap,
86			int compat);
87static int getpeername1(struct thread *td, struct getpeername_args *uap,
88			int compat);
89
90/*
91 * Expanded sf_freelist head. Really an SLIST_HEAD() in disguise, with the
92 * sf_freelist head with the sf_lock mutex.
93 */
94static struct {
95	SLIST_HEAD(, sf_buf) sf_head;
96	struct mtx sf_lock;
97} sf_freelist;
98
99vm_offset_t sf_base;
100struct sf_buf *sf_bufs;
101u_int sf_buf_alloc_want;
102
103/*
104 * System call interface to the socket abstraction.
105 */
106#if defined(COMPAT_43) || defined(COMPAT_SUNOS)
107#define COMPAT_OLDSOCK
108#endif
109
110extern	struct fileops socketops;
111
112/*
113 * MPSAFE
114 */
115int
116socket(td, uap)
117	struct thread *td;
118	register struct socket_args /* {
119		int	domain;
120		int	type;
121		int	protocol;
122	} */ *uap;
123{
124	struct filedesc *fdp;
125	struct socket *so;
126	struct file *fp;
127	int fd, error;
128
129	mtx_lock(&Giant);
130	fdp = td->td_proc->p_fd;
131	error = falloc(td, &fp, &fd);
132	if (error)
133		goto done2;
134	fhold(fp);
135	error = socreate(uap->domain, &so, uap->type, uap->protocol,
136	    td->td_ucred, td);
137	FILEDESC_LOCK(fdp);
138	if (error) {
139		if (fdp->fd_ofiles[fd] == fp) {
140			fdp->fd_ofiles[fd] = NULL;
141			FILEDESC_UNLOCK(fdp);
142			fdrop(fp, td);
143		} else
144			FILEDESC_UNLOCK(fdp);
145	} else {
146		fp->f_data = so;	/* already has ref count */
147		fp->f_flag = FREAD|FWRITE;
148		fp->f_ops = &socketops;
149		fp->f_type = DTYPE_SOCKET;
150		FILEDESC_UNLOCK(fdp);
151		td->td_retval[0] = fd;
152	}
153	fdrop(fp, td);
154done2:
155	mtx_unlock(&Giant);
156	return (error);
157}
158
159/*
160 * MPSAFE
161 */
162/* ARGSUSED */
163int
164bind(td, uap)
165	struct thread *td;
166	register struct bind_args /* {
167		int	s;
168		caddr_t	name;
169		int	namelen;
170	} */ *uap;
171{
172	struct socket *so;
173	struct sockaddr *sa;
174	int error;
175
176	mtx_lock(&Giant);
177	if ((error = fgetsock(td, uap->s, &so, NULL)) != 0)
178		goto done2;
179	if ((error = getsockaddr(&sa, uap->name, uap->namelen)) != 0)
180		goto done1;
181#ifdef MAC
182	error = mac_check_socket_bind(td->td_ucred, so, sa);
183	if (error) {
184		FREE(sa, M_SONAME);
185		goto done1;
186	}
187#endif
188	error = sobind(so, sa, td);
189	FREE(sa, M_SONAME);
190done1:
191	fputsock(so);
192done2:
193	mtx_unlock(&Giant);
194	return (error);
195}
196
197/*
198 * MPSAFE
199 */
200/* ARGSUSED */
201int
202listen(td, uap)
203	struct thread *td;
204	register struct listen_args /* {
205		int	s;
206		int	backlog;
207	} */ *uap;
208{
209	struct socket *so;
210	int error;
211
212	mtx_lock(&Giant);
213	if ((error = fgetsock(td, uap->s, &so, NULL)) == 0) {
214#ifdef MAC
215		error = mac_check_socket_listen(td->td_ucred, so);
216		if (error)
217			goto done;
218#endif
219		error = solisten(so, uap->backlog, td);
220#ifdef MAC
221done:
222#endif
223		fputsock(so);
224	}
225	mtx_unlock(&Giant);
226	return(error);
227}
228
229/*
230 * accept1()
231 * MPSAFE
232 */
233static int
234accept1(td, uap, compat)
235	struct thread *td;
236	register struct accept_args /* {
237		int	s;
238		caddr_t	name;
239		int	*anamelen;
240	} */ *uap;
241	int compat;
242{
243	struct filedesc *fdp;
244	struct file *nfp = NULL;
245	struct sockaddr *sa;
246	int namelen, error, s;
247	struct socket *head, *so;
248	int fd;
249	u_int fflag;
250
251	mtx_lock(&Giant);
252	fdp = td->td_proc->p_fd;
253	if (uap->name) {
254		error = copyin(uap->anamelen, &namelen, sizeof (namelen));
255		if(error)
256			goto done2;
257		if (namelen < 0)
258			return (EINVAL);
259	}
260	error = fgetsock(td, uap->s, &head, &fflag);
261	if (error)
262		goto done2;
263	s = splnet();
264	if ((head->so_options & SO_ACCEPTCONN) == 0) {
265		splx(s);
266		error = EINVAL;
267		goto done;
268	}
269	if ((head->so_state & SS_NBIO) && TAILQ_EMPTY(&head->so_comp)) {
270		splx(s);
271		error = EWOULDBLOCK;
272		goto done;
273	}
274	while (TAILQ_EMPTY(&head->so_comp) && head->so_error == 0) {
275		if (head->so_state & SS_CANTRCVMORE) {
276			head->so_error = ECONNABORTED;
277			break;
278		}
279		error = tsleep(&head->so_timeo, PSOCK | PCATCH,
280		    "accept", 0);
281		if (error) {
282			splx(s);
283			goto done;
284		}
285	}
286	if (head->so_error) {
287		error = head->so_error;
288		head->so_error = 0;
289		splx(s);
290		goto done;
291	}
292
293	/*
294	 * At this point we know that there is at least one connection
295	 * ready to be accepted. Remove it from the queue prior to
296	 * allocating the file descriptor for it since falloc() may
297	 * block allowing another process to accept the connection
298	 * instead.
299	 */
300	so = TAILQ_FIRST(&head->so_comp);
301	TAILQ_REMOVE(&head->so_comp, so, so_list);
302	head->so_qlen--;
303
304	error = falloc(td, &nfp, &fd);
305	if (error) {
306		/*
307		 * Probably ran out of file descriptors. Put the
308		 * unaccepted connection back onto the queue and
309		 * do another wakeup so some other process might
310		 * have a chance at it.
311		 */
312		TAILQ_INSERT_HEAD(&head->so_comp, so, so_list);
313		head->so_qlen++;
314		wakeup_one(&head->so_timeo);
315		splx(s);
316		goto done;
317	}
318	fhold(nfp);
319	td->td_retval[0] = fd;
320
321	/* connection has been removed from the listen queue */
322	KNOTE(&head->so_rcv.sb_sel.si_note, 0);
323
324	so->so_state &= ~SS_COMP;
325	so->so_head = NULL;
326	if (head->so_sigio != NULL)
327		fsetown(fgetown(head->so_sigio), &so->so_sigio);
328
329	FILE_LOCK(nfp);
330	soref(so);			/* file descriptor reference */
331	nfp->f_data = so;		/* nfp has ref count from falloc */
332	nfp->f_flag = fflag;
333	nfp->f_ops = &socketops;
334	nfp->f_type = DTYPE_SOCKET;
335	FILE_UNLOCK(nfp);
336	sa = 0;
337	error = soaccept(so, &sa);
338	if (error) {
339		/*
340		 * return a namelen of zero for older code which might
341	 	 * ignore the return value from accept.
342		 */
343		if (uap->name != NULL) {
344			namelen = 0;
345			(void) copyout(&namelen,
346			    uap->anamelen, sizeof(*uap->anamelen));
347		}
348		goto noconnection;
349	}
350	if (sa == NULL) {
351		namelen = 0;
352		if (uap->name)
353			goto gotnoname;
354		splx(s);
355		error = 0;
356		goto done;
357	}
358	if (uap->name) {
359		/* check sa_len before it is destroyed */
360		if (namelen > sa->sa_len)
361			namelen = sa->sa_len;
362#ifdef COMPAT_OLDSOCK
363		if (compat)
364			((struct osockaddr *)sa)->sa_family =
365			    sa->sa_family;
366#endif
367		error = copyout(sa, uap->name, (u_int)namelen);
368		if (!error)
369gotnoname:
370			error = copyout(&namelen,
371			    uap->anamelen, sizeof (*uap->anamelen));
372	}
373noconnection:
374	if (sa)
375		FREE(sa, M_SONAME);
376
377	/*
378	 * close the new descriptor, assuming someone hasn't ripped it
379	 * out from under us.
380	 */
381	if (error) {
382		FILEDESC_LOCK(fdp);
383		if (fdp->fd_ofiles[fd] == nfp) {
384			fdp->fd_ofiles[fd] = NULL;
385			FILEDESC_UNLOCK(fdp);
386			fdrop(nfp, td);
387		} else {
388			FILEDESC_UNLOCK(fdp);
389		}
390	}
391	splx(s);
392
393	/*
394	 * Release explicitly held references before returning.
395	 */
396done:
397	if (nfp != NULL)
398		fdrop(nfp, td);
399	fputsock(head);
400done2:
401	mtx_unlock(&Giant);
402	return (error);
403}
404
405/*
406 * MPSAFE (accept1() is MPSAFE)
407 */
408int
409accept(td, uap)
410	struct thread *td;
411	struct accept_args *uap;
412{
413
414	return (accept1(td, uap, 0));
415}
416
417#ifdef COMPAT_OLDSOCK
418/*
419 * MPSAFE (accept1() is MPSAFE)
420 */
421int
422oaccept(td, uap)
423	struct thread *td;
424	struct accept_args *uap;
425{
426
427	return (accept1(td, uap, 1));
428}
429#endif /* COMPAT_OLDSOCK */
430
431/*
432 * MPSAFE
433 */
434/* ARGSUSED */
435int
436connect(td, uap)
437	struct thread *td;
438	register struct connect_args /* {
439		int	s;
440		caddr_t	name;
441		int	namelen;
442	} */ *uap;
443{
444	struct socket *so;
445	struct sockaddr *sa;
446	int error, s;
447
448	mtx_lock(&Giant);
449	if ((error = fgetsock(td, uap->s, &so, NULL)) != 0)
450		goto done2;
451	if ((so->so_state & SS_NBIO) && (so->so_state & SS_ISCONNECTING)) {
452		error = EALREADY;
453		goto done1;
454	}
455	error = getsockaddr(&sa, uap->name, uap->namelen);
456	if (error)
457		goto done1;
458#ifdef MAC
459	error = mac_check_socket_connect(td->td_ucred, so, sa);
460	if (error)
461		goto bad;
462#endif
463	error = soconnect(so, sa, td);
464	if (error)
465		goto bad;
466	if ((so->so_state & SS_NBIO) && (so->so_state & SS_ISCONNECTING)) {
467		FREE(sa, M_SONAME);
468		error = EINPROGRESS;
469		goto done1;
470	}
471	s = splnet();
472	while ((so->so_state & SS_ISCONNECTING) && so->so_error == 0) {
473		error = tsleep(&so->so_timeo, PSOCK | PCATCH, "connec", 0);
474		if (error)
475			break;
476	}
477	if (error == 0) {
478		error = so->so_error;
479		so->so_error = 0;
480	}
481	splx(s);
482bad:
483	so->so_state &= ~SS_ISCONNECTING;
484	FREE(sa, M_SONAME);
485	if (error == ERESTART)
486		error = EINTR;
487done1:
488	fputsock(so);
489done2:
490	mtx_unlock(&Giant);
491	return (error);
492}
493
494/*
495 * MPSAFE
496 */
497int
498socketpair(td, uap)
499	struct thread *td;
500	register struct socketpair_args /* {
501		int	domain;
502		int	type;
503		int	protocol;
504		int	*rsv;
505	} */ *uap;
506{
507	register struct filedesc *fdp = td->td_proc->p_fd;
508	struct file *fp1, *fp2;
509	struct socket *so1, *so2;
510	int fd, error, sv[2];
511
512	mtx_lock(&Giant);
513	error = socreate(uap->domain, &so1, uap->type, uap->protocol,
514	    td->td_ucred, td);
515	if (error)
516		goto done2;
517	error = socreate(uap->domain, &so2, uap->type, uap->protocol,
518	    td->td_ucred, td);
519	if (error)
520		goto free1;
521	error = falloc(td, &fp1, &fd);
522	if (error)
523		goto free2;
524	fhold(fp1);
525	sv[0] = fd;
526	fp1->f_data = so1;		/* so1 already has ref count */
527	error = falloc(td, &fp2, &fd);
528	if (error)
529		goto free3;
530	fhold(fp2);
531	fp2->f_data = so2;		/* so2 already has ref count */
532	sv[1] = fd;
533	error = soconnect2(so1, so2);
534	if (error)
535		goto free4;
536	if (uap->type == SOCK_DGRAM) {
537		/*
538		 * Datagram socket connection is asymmetric.
539		 */
540		 error = soconnect2(so2, so1);
541		 if (error)
542			goto free4;
543	}
544	FILE_LOCK(fp1);
545	fp1->f_flag = FREAD|FWRITE;
546	fp1->f_ops = &socketops;
547	fp1->f_type = DTYPE_SOCKET;
548	FILE_UNLOCK(fp1);
549	FILE_LOCK(fp2);
550	fp2->f_flag = FREAD|FWRITE;
551	fp2->f_ops = &socketops;
552	fp2->f_type = DTYPE_SOCKET;
553	FILE_UNLOCK(fp2);
554	error = copyout(sv, uap->rsv, 2 * sizeof (int));
555	fdrop(fp1, td);
556	fdrop(fp2, td);
557	goto done2;
558free4:
559	FILEDESC_LOCK(fdp);
560	if (fdp->fd_ofiles[sv[1]] == fp2) {
561		fdp->fd_ofiles[sv[1]] = NULL;
562		FILEDESC_UNLOCK(fdp);
563		fdrop(fp2, td);
564	} else
565		FILEDESC_UNLOCK(fdp);
566	fdrop(fp2, td);
567free3:
568	FILEDESC_LOCK(fdp);
569	if (fdp->fd_ofiles[sv[0]] == fp1) {
570		fdp->fd_ofiles[sv[0]] = NULL;
571		FILEDESC_UNLOCK(fdp);
572		fdrop(fp1, td);
573	} else
574		FILEDESC_UNLOCK(fdp);
575	fdrop(fp1, td);
576free2:
577	(void)soclose(so2);
578free1:
579	(void)soclose(so1);
580done2:
581	mtx_unlock(&Giant);
582	return (error);
583}
584
585static int
586sendit(td, s, mp, flags)
587	register struct thread *td;
588	int s;
589	register struct msghdr *mp;
590	int flags;
591{
592	struct uio auio;
593	register struct iovec *iov;
594	register int i;
595	struct mbuf *control;
596	struct sockaddr *to = NULL;
597	int len, error;
598	struct socket *so;
599#ifdef KTRACE
600	struct iovec *ktriov = NULL;
601	struct uio ktruio;
602	int iovlen;
603#endif
604
605	if ((error = fgetsock(td, s, &so, NULL)) != 0)
606		return (error);
607	auio.uio_iov = mp->msg_iov;
608	auio.uio_iovcnt = mp->msg_iovlen;
609	auio.uio_segflg = UIO_USERSPACE;
610	auio.uio_rw = UIO_WRITE;
611	auio.uio_td = td;
612	auio.uio_offset = 0;			/* XXX */
613	auio.uio_resid = 0;
614	iov = mp->msg_iov;
615	for (i = 0; i < mp->msg_iovlen; i++, iov++) {
616		if ((auio.uio_resid += iov->iov_len) < 0) {
617			error = EINVAL;
618			goto bad;
619		}
620	}
621	if (mp->msg_name) {
622		error = getsockaddr(&to, mp->msg_name, mp->msg_namelen);
623		if (error)
624			goto bad;
625	}
626	if (mp->msg_control) {
627		if (mp->msg_controllen < sizeof(struct cmsghdr)
628#ifdef COMPAT_OLDSOCK
629		    && mp->msg_flags != MSG_COMPAT
630#endif
631		) {
632			error = EINVAL;
633			goto bad;
634		}
635		error = sockargs(&control, mp->msg_control,
636		    mp->msg_controllen, MT_CONTROL);
637		if (error)
638			goto bad;
639#ifdef COMPAT_OLDSOCK
640		if (mp->msg_flags == MSG_COMPAT) {
641			register struct cmsghdr *cm;
642
643			M_PREPEND(control, sizeof(*cm), M_TRYWAIT);
644			if (control == 0) {
645				error = ENOBUFS;
646				goto bad;
647			} else {
648				cm = mtod(control, struct cmsghdr *);
649				cm->cmsg_len = control->m_len;
650				cm->cmsg_level = SOL_SOCKET;
651				cm->cmsg_type = SCM_RIGHTS;
652			}
653		}
654#endif
655	} else {
656		control = 0;
657	}
658#ifdef KTRACE
659	if (KTRPOINT(td, KTR_GENIO)) {
660		iovlen = auio.uio_iovcnt * sizeof (struct iovec);
661		MALLOC(ktriov, struct iovec *, iovlen, M_TEMP, M_WAITOK);
662		bcopy(auio.uio_iov, ktriov, iovlen);
663		ktruio = auio;
664	}
665#endif
666	len = auio.uio_resid;
667	error = so->so_proto->pr_usrreqs->pru_sosend(so, to, &auio, 0, control,
668						     flags, td);
669	if (error) {
670		if (auio.uio_resid != len && (error == ERESTART ||
671		    error == EINTR || error == EWOULDBLOCK))
672			error = 0;
673		/* Generation of SIGPIPE can be controlled per socket */
674		if (error == EPIPE && !(so->so_options & SO_NOSIGPIPE)) {
675			PROC_LOCK(td->td_proc);
676			psignal(td->td_proc, SIGPIPE);
677			PROC_UNLOCK(td->td_proc);
678		}
679	}
680	if (error == 0)
681		td->td_retval[0] = len - auio.uio_resid;
682#ifdef KTRACE
683	if (ktriov != NULL) {
684		if (error == 0) {
685			ktruio.uio_iov = ktriov;
686			ktruio.uio_resid = td->td_retval[0];
687			ktrgenio(s, UIO_WRITE, &ktruio, error);
688		}
689		FREE(ktriov, M_TEMP);
690	}
691#endif
692bad:
693	fputsock(so);
694	if (to)
695		FREE(to, M_SONAME);
696	return (error);
697}
698
699/*
700 * MPSAFE
701 */
702int
703sendto(td, uap)
704	struct thread *td;
705	register struct sendto_args /* {
706		int	s;
707		caddr_t	buf;
708		size_t	len;
709		int	flags;
710		caddr_t	to;
711		int	tolen;
712	} */ *uap;
713{
714	struct msghdr msg;
715	struct iovec aiov;
716	int error;
717
718	msg.msg_name = uap->to;
719	msg.msg_namelen = uap->tolen;
720	msg.msg_iov = &aiov;
721	msg.msg_iovlen = 1;
722	msg.msg_control = 0;
723#ifdef COMPAT_OLDSOCK
724	msg.msg_flags = 0;
725#endif
726	aiov.iov_base = uap->buf;
727	aiov.iov_len = uap->len;
728	mtx_lock(&Giant);
729	error = sendit(td, uap->s, &msg, uap->flags);
730	mtx_unlock(&Giant);
731	return (error);
732}
733
734#ifdef COMPAT_OLDSOCK
735/*
736 * MPSAFE
737 */
738int
739osend(td, uap)
740	struct thread *td;
741	register struct osend_args /* {
742		int	s;
743		caddr_t	buf;
744		int	len;
745		int	flags;
746	} */ *uap;
747{
748	struct msghdr msg;
749	struct iovec aiov;
750	int error;
751
752	msg.msg_name = 0;
753	msg.msg_namelen = 0;
754	msg.msg_iov = &aiov;
755	msg.msg_iovlen = 1;
756	aiov.iov_base = uap->buf;
757	aiov.iov_len = uap->len;
758	msg.msg_control = 0;
759	msg.msg_flags = 0;
760	mtx_lock(&Giant);
761	error = sendit(td, uap->s, &msg, uap->flags);
762	mtx_unlock(&Giant);
763	return (error);
764}
765
766/*
767 * MPSAFE
768 */
769int
770osendmsg(td, uap)
771	struct thread *td;
772	register struct osendmsg_args /* {
773		int	s;
774		caddr_t	msg;
775		int	flags;
776	} */ *uap;
777{
778	struct msghdr msg;
779	struct iovec aiov[UIO_SMALLIOV], *iov;
780	int error;
781
782	mtx_lock(&Giant);
783	error = copyin(uap->msg, &msg, sizeof (struct omsghdr));
784	if (error)
785		goto done2;
786	if ((u_int)msg.msg_iovlen >= UIO_SMALLIOV) {
787		if ((u_int)msg.msg_iovlen >= UIO_MAXIOV) {
788			error = EMSGSIZE;
789			goto done2;
790		}
791		MALLOC(iov, struct iovec *,
792		      sizeof(struct iovec) * (u_int)msg.msg_iovlen, M_IOV,
793		      M_WAITOK);
794	} else {
795		iov = aiov;
796	}
797	error = copyin(msg.msg_iov, iov,
798	    (unsigned)(msg.msg_iovlen * sizeof (struct iovec)));
799	if (error)
800		goto done;
801	msg.msg_flags = MSG_COMPAT;
802	msg.msg_iov = iov;
803	error = sendit(td, uap->s, &msg, uap->flags);
804done:
805	if (iov != aiov)
806		FREE(iov, M_IOV);
807done2:
808	mtx_unlock(&Giant);
809	return (error);
810}
811#endif
812
813/*
814 * MPSAFE
815 */
816int
817sendmsg(td, uap)
818	struct thread *td;
819	register struct sendmsg_args /* {
820		int	s;
821		caddr_t	msg;
822		int	flags;
823	} */ *uap;
824{
825	struct msghdr msg;
826	struct iovec aiov[UIO_SMALLIOV], *iov;
827	int error;
828
829	mtx_lock(&Giant);
830	error = copyin(uap->msg, &msg, sizeof (msg));
831	if (error)
832		goto done2;
833	if ((u_int)msg.msg_iovlen >= UIO_SMALLIOV) {
834		if ((u_int)msg.msg_iovlen >= UIO_MAXIOV) {
835			error = EMSGSIZE;
836			goto done2;
837		}
838		MALLOC(iov, struct iovec *,
839		       sizeof(struct iovec) * (u_int)msg.msg_iovlen, M_IOV,
840		       M_WAITOK);
841	} else {
842		iov = aiov;
843	}
844	if (msg.msg_iovlen &&
845	    (error = copyin(msg.msg_iov, iov,
846	    (unsigned)(msg.msg_iovlen * sizeof (struct iovec)))))
847		goto done;
848	msg.msg_iov = iov;
849#ifdef COMPAT_OLDSOCK
850	msg.msg_flags = 0;
851#endif
852	error = sendit(td, uap->s, &msg, uap->flags);
853done:
854	if (iov != aiov)
855		FREE(iov, M_IOV);
856done2:
857	mtx_unlock(&Giant);
858	return (error);
859}
860
861static int
862recvit(td, s, mp, namelenp)
863	register struct thread *td;
864	int s;
865	register struct msghdr *mp;
866	void *namelenp;
867{
868	struct uio auio;
869	register struct iovec *iov;
870	register int i;
871	int len, error;
872	struct mbuf *m, *control = 0;
873	caddr_t ctlbuf;
874	struct socket *so;
875	struct sockaddr *fromsa = 0;
876#ifdef KTRACE
877	struct iovec *ktriov = NULL;
878	struct uio ktruio;
879	int iovlen;
880#endif
881
882	if ((error = fgetsock(td, s, &so, NULL)) != 0)
883		return (error);
884	auio.uio_iov = mp->msg_iov;
885	auio.uio_iovcnt = mp->msg_iovlen;
886	auio.uio_segflg = UIO_USERSPACE;
887	auio.uio_rw = UIO_READ;
888	auio.uio_td = td;
889	auio.uio_offset = 0;			/* XXX */
890	auio.uio_resid = 0;
891	iov = mp->msg_iov;
892	for (i = 0; i < mp->msg_iovlen; i++, iov++) {
893		if ((auio.uio_resid += iov->iov_len) < 0) {
894			fputsock(so);
895			return (EINVAL);
896		}
897	}
898#ifdef KTRACE
899	if (KTRPOINT(td, KTR_GENIO)) {
900		iovlen = auio.uio_iovcnt * sizeof (struct iovec);
901		MALLOC(ktriov, struct iovec *, iovlen, M_TEMP, M_WAITOK);
902		bcopy(auio.uio_iov, ktriov, iovlen);
903		ktruio = auio;
904	}
905#endif
906	len = auio.uio_resid;
907	error = so->so_proto->pr_usrreqs->pru_soreceive(so, &fromsa, &auio,
908	    (struct mbuf **)0, mp->msg_control ? &control : (struct mbuf **)0,
909	    &mp->msg_flags);
910	if (error) {
911		if (auio.uio_resid != len && (error == ERESTART ||
912		    error == EINTR || error == EWOULDBLOCK))
913			error = 0;
914	}
915#ifdef KTRACE
916	if (ktriov != NULL) {
917		if (error == 0) {
918			ktruio.uio_iov = ktriov;
919			ktruio.uio_resid = len - auio.uio_resid;
920			ktrgenio(s, UIO_READ, &ktruio, error);
921		}
922		FREE(ktriov, M_TEMP);
923	}
924#endif
925	if (error)
926		goto out;
927	td->td_retval[0] = len - auio.uio_resid;
928	if (mp->msg_name) {
929		len = mp->msg_namelen;
930		if (len <= 0 || fromsa == 0)
931			len = 0;
932		else {
933#ifndef MIN
934#define MIN(a,b) ((a)>(b)?(b):(a))
935#endif
936			/* save sa_len before it is destroyed by MSG_COMPAT */
937			len = MIN(len, fromsa->sa_len);
938#ifdef COMPAT_OLDSOCK
939			if (mp->msg_flags & MSG_COMPAT)
940				((struct osockaddr *)fromsa)->sa_family =
941				    fromsa->sa_family;
942#endif
943			error = copyout(fromsa, mp->msg_name, (unsigned)len);
944			if (error)
945				goto out;
946		}
947		mp->msg_namelen = len;
948		if (namelenp &&
949		    (error = copyout(&len, namelenp, sizeof (int)))) {
950#ifdef COMPAT_OLDSOCK
951			if (mp->msg_flags & MSG_COMPAT)
952				error = 0;	/* old recvfrom didn't check */
953			else
954#endif
955			goto out;
956		}
957	}
958	if (mp->msg_control) {
959#ifdef COMPAT_OLDSOCK
960		/*
961		 * We assume that old recvmsg calls won't receive access
962		 * rights and other control info, esp. as control info
963		 * is always optional and those options didn't exist in 4.3.
964		 * If we receive rights, trim the cmsghdr; anything else
965		 * is tossed.
966		 */
967		if (control && mp->msg_flags & MSG_COMPAT) {
968			if (mtod(control, struct cmsghdr *)->cmsg_level !=
969			    SOL_SOCKET ||
970			    mtod(control, struct cmsghdr *)->cmsg_type !=
971			    SCM_RIGHTS) {
972				mp->msg_controllen = 0;
973				goto out;
974			}
975			control->m_len -= sizeof (struct cmsghdr);
976			control->m_data += sizeof (struct cmsghdr);
977		}
978#endif
979		len = mp->msg_controllen;
980		m = control;
981		mp->msg_controllen = 0;
982		ctlbuf = mp->msg_control;
983
984		while (m && len > 0) {
985			unsigned int tocopy;
986
987			if (len >= m->m_len)
988				tocopy = m->m_len;
989			else {
990				mp->msg_flags |= MSG_CTRUNC;
991				tocopy = len;
992			}
993
994			if ((error = copyout(mtod(m, caddr_t),
995					ctlbuf, tocopy)) != 0)
996				goto out;
997
998			ctlbuf += tocopy;
999			len -= tocopy;
1000			m = m->m_next;
1001		}
1002		mp->msg_controllen = ctlbuf - (caddr_t)mp->msg_control;
1003	}
1004out:
1005	fputsock(so);
1006	if (fromsa)
1007		FREE(fromsa, M_SONAME);
1008	if (control)
1009		m_freem(control);
1010	return (error);
1011}
1012
1013/*
1014 * MPSAFE
1015 */
1016int
1017recvfrom(td, uap)
1018	struct thread *td;
1019	register struct recvfrom_args /* {
1020		int	s;
1021		caddr_t	buf;
1022		size_t	len;
1023		int	flags;
1024		caddr_t	from;
1025		int	*fromlenaddr;
1026	} */ *uap;
1027{
1028	struct msghdr msg;
1029	struct iovec aiov;
1030	int error;
1031
1032	mtx_lock(&Giant);
1033	if (uap->fromlenaddr) {
1034		error = copyin(uap->fromlenaddr,
1035		    &msg.msg_namelen, sizeof (msg.msg_namelen));
1036		if (error)
1037			goto done2;
1038	} else {
1039		msg.msg_namelen = 0;
1040	}
1041	msg.msg_name = uap->from;
1042	msg.msg_iov = &aiov;
1043	msg.msg_iovlen = 1;
1044	aiov.iov_base = uap->buf;
1045	aiov.iov_len = uap->len;
1046	msg.msg_control = 0;
1047	msg.msg_flags = uap->flags;
1048	error = recvit(td, uap->s, &msg, uap->fromlenaddr);
1049done2:
1050	mtx_unlock(&Giant);
1051	return(error);
1052}
1053
1054#ifdef COMPAT_OLDSOCK
1055/*
1056 * MPSAFE
1057 */
1058int
1059orecvfrom(td, uap)
1060	struct thread *td;
1061	struct recvfrom_args *uap;
1062{
1063
1064	uap->flags |= MSG_COMPAT;
1065	return (recvfrom(td, uap));
1066}
1067#endif
1068
1069
1070#ifdef COMPAT_OLDSOCK
1071/*
1072 * MPSAFE
1073 */
1074int
1075orecv(td, uap)
1076	struct thread *td;
1077	register struct orecv_args /* {
1078		int	s;
1079		caddr_t	buf;
1080		int	len;
1081		int	flags;
1082	} */ *uap;
1083{
1084	struct msghdr msg;
1085	struct iovec aiov;
1086	int error;
1087
1088	mtx_lock(&Giant);
1089	msg.msg_name = 0;
1090	msg.msg_namelen = 0;
1091	msg.msg_iov = &aiov;
1092	msg.msg_iovlen = 1;
1093	aiov.iov_base = uap->buf;
1094	aiov.iov_len = uap->len;
1095	msg.msg_control = 0;
1096	msg.msg_flags = uap->flags;
1097	error = recvit(td, uap->s, &msg, NULL);
1098	mtx_unlock(&Giant);
1099	return (error);
1100}
1101
1102/*
1103 * Old recvmsg.  This code takes advantage of the fact that the old msghdr
1104 * overlays the new one, missing only the flags, and with the (old) access
1105 * rights where the control fields are now.
1106 *
1107 * MPSAFE
1108 */
1109int
1110orecvmsg(td, uap)
1111	struct thread *td;
1112	register struct orecvmsg_args /* {
1113		int	s;
1114		struct	omsghdr *msg;
1115		int	flags;
1116	} */ *uap;
1117{
1118	struct msghdr msg;
1119	struct iovec aiov[UIO_SMALLIOV], *iov;
1120	int error;
1121
1122	error = copyin(uap->msg, &msg, sizeof (struct omsghdr));
1123	if (error)
1124		return (error);
1125
1126	mtx_lock(&Giant);
1127	if ((u_int)msg.msg_iovlen >= UIO_SMALLIOV) {
1128		if ((u_int)msg.msg_iovlen >= UIO_MAXIOV) {
1129			error = EMSGSIZE;
1130			goto done2;
1131		}
1132		MALLOC(iov, struct iovec *,
1133		      sizeof(struct iovec) * (u_int)msg.msg_iovlen, M_IOV,
1134		      M_WAITOK);
1135	} else {
1136		iov = aiov;
1137	}
1138	msg.msg_flags = uap->flags | MSG_COMPAT;
1139	error = copyin(msg.msg_iov, iov,
1140	    (unsigned)(msg.msg_iovlen * sizeof (struct iovec)));
1141	if (error)
1142		goto done;
1143	msg.msg_iov = iov;
1144	error = recvit(td, uap->s, &msg, &uap->msg->msg_namelen);
1145
1146	if (msg.msg_controllen && error == 0)
1147		error = copyout(&msg.msg_controllen,
1148		    &uap->msg->msg_accrightslen, sizeof (int));
1149done:
1150	if (iov != aiov)
1151		FREE(iov, M_IOV);
1152done2:
1153	mtx_unlock(&Giant);
1154	return (error);
1155}
1156#endif
1157
1158/*
1159 * MPSAFE
1160 */
1161int
1162recvmsg(td, uap)
1163	struct thread *td;
1164	register struct recvmsg_args /* {
1165		int	s;
1166		struct	msghdr *msg;
1167		int	flags;
1168	} */ *uap;
1169{
1170	struct msghdr msg;
1171	struct iovec aiov[UIO_SMALLIOV], *uiov, *iov;
1172	register int error;
1173
1174	mtx_lock(&Giant);
1175	error = copyin(uap->msg, &msg, sizeof (msg));
1176	if (error)
1177		goto done2;
1178	if ((u_int)msg.msg_iovlen >= UIO_SMALLIOV) {
1179		if ((u_int)msg.msg_iovlen >= UIO_MAXIOV) {
1180			error = EMSGSIZE;
1181			goto done2;
1182		}
1183		MALLOC(iov, struct iovec *,
1184		       sizeof(struct iovec) * (u_int)msg.msg_iovlen, M_IOV,
1185		       M_WAITOK);
1186	} else {
1187		iov = aiov;
1188	}
1189#ifdef COMPAT_OLDSOCK
1190	msg.msg_flags = uap->flags &~ MSG_COMPAT;
1191#else
1192	msg.msg_flags = uap->flags;
1193#endif
1194	uiov = msg.msg_iov;
1195	msg.msg_iov = iov;
1196	error = copyin(uiov, iov,
1197	    (unsigned)(msg.msg_iovlen * sizeof (struct iovec)));
1198	if (error)
1199		goto done;
1200	error = recvit(td, uap->s, &msg, NULL);
1201	if (!error) {
1202		msg.msg_iov = uiov;
1203		error = copyout(&msg, uap->msg, sizeof(msg));
1204	}
1205done:
1206	if (iov != aiov)
1207		FREE(iov, M_IOV);
1208done2:
1209	mtx_unlock(&Giant);
1210	return (error);
1211}
1212
1213/*
1214 * MPSAFE
1215 */
1216/* ARGSUSED */
1217int
1218shutdown(td, uap)
1219	struct thread *td;
1220	register struct shutdown_args /* {
1221		int	s;
1222		int	how;
1223	} */ *uap;
1224{
1225	struct socket *so;
1226	int error;
1227
1228	mtx_lock(&Giant);
1229	if ((error = fgetsock(td, uap->s, &so, NULL)) == 0) {
1230		error = soshutdown(so, uap->how);
1231		fputsock(so);
1232	}
1233	mtx_unlock(&Giant);
1234	return(error);
1235}
1236
1237/*
1238 * MPSAFE
1239 */
1240/* ARGSUSED */
1241int
1242setsockopt(td, uap)
1243	struct thread *td;
1244	register struct setsockopt_args /* {
1245		int	s;
1246		int	level;
1247		int	name;
1248		caddr_t	val;
1249		int	valsize;
1250	} */ *uap;
1251{
1252	struct socket *so;
1253	struct sockopt sopt;
1254	int error;
1255
1256	if (uap->val == 0 && uap->valsize != 0)
1257		return (EFAULT);
1258	if (uap->valsize < 0)
1259		return (EINVAL);
1260
1261	mtx_lock(&Giant);
1262	if ((error = fgetsock(td, uap->s, &so, NULL)) == 0) {
1263		sopt.sopt_dir = SOPT_SET;
1264		sopt.sopt_level = uap->level;
1265		sopt.sopt_name = uap->name;
1266		sopt.sopt_val = uap->val;
1267		sopt.sopt_valsize = uap->valsize;
1268		sopt.sopt_td = td;
1269		error = sosetopt(so, &sopt);
1270		fputsock(so);
1271	}
1272	mtx_unlock(&Giant);
1273	return(error);
1274}
1275
1276/*
1277 * MPSAFE
1278 */
1279/* ARGSUSED */
1280int
1281getsockopt(td, uap)
1282	struct thread *td;
1283	register struct getsockopt_args /* {
1284		int	s;
1285		int	level;
1286		int	name;
1287		caddr_t	val;
1288		int	*avalsize;
1289	} */ *uap;
1290{
1291	int	valsize, error;
1292	struct  socket *so;
1293	struct	sockopt sopt;
1294
1295	mtx_lock(&Giant);
1296	if ((error = fgetsock(td, uap->s, &so, NULL)) != 0)
1297		goto done2;
1298	if (uap->val) {
1299		error = copyin(uap->avalsize, &valsize, sizeof (valsize));
1300		if (error)
1301			goto done1;
1302		if (valsize < 0) {
1303			error = EINVAL;
1304			goto done1;
1305		}
1306	} else {
1307		valsize = 0;
1308	}
1309
1310	sopt.sopt_dir = SOPT_GET;
1311	sopt.sopt_level = uap->level;
1312	sopt.sopt_name = uap->name;
1313	sopt.sopt_val = uap->val;
1314	sopt.sopt_valsize = (size_t)valsize; /* checked non-negative above */
1315	sopt.sopt_td = td;
1316
1317	error = sogetopt(so, &sopt);
1318	if (error == 0) {
1319		valsize = sopt.sopt_valsize;
1320		error = copyout(&valsize, uap->avalsize, sizeof (valsize));
1321	}
1322done1:
1323	fputsock(so);
1324done2:
1325	mtx_unlock(&Giant);
1326	return (error);
1327}
1328
1329/*
1330 * getsockname1() - Get socket name.
1331 *
1332 * MPSAFE
1333 */
1334/* ARGSUSED */
1335static int
1336getsockname1(td, uap, compat)
1337	struct thread *td;
1338	register struct getsockname_args /* {
1339		int	fdes;
1340		caddr_t	asa;
1341		int	*alen;
1342	} */ *uap;
1343	int compat;
1344{
1345	struct socket *so;
1346	struct sockaddr *sa;
1347	int len, error;
1348
1349	mtx_lock(&Giant);
1350	if ((error = fgetsock(td, uap->fdes, &so, NULL)) != 0)
1351		goto done2;
1352	error = copyin(uap->alen, &len, sizeof (len));
1353	if (error)
1354		goto done1;
1355	if (len < 0) {
1356		error = EINVAL;
1357		goto done1;
1358	}
1359	sa = 0;
1360	error = (*so->so_proto->pr_usrreqs->pru_sockaddr)(so, &sa);
1361	if (error)
1362		goto bad;
1363	if (sa == 0) {
1364		len = 0;
1365		goto gotnothing;
1366	}
1367
1368	len = MIN(len, sa->sa_len);
1369#ifdef COMPAT_OLDSOCK
1370	if (compat)
1371		((struct osockaddr *)sa)->sa_family = sa->sa_family;
1372#endif
1373	error = copyout(sa, uap->asa, (u_int)len);
1374	if (error == 0)
1375gotnothing:
1376		error = copyout(&len, uap->alen, sizeof (len));
1377bad:
1378	if (sa)
1379		FREE(sa, M_SONAME);
1380done1:
1381	fputsock(so);
1382done2:
1383	mtx_unlock(&Giant);
1384	return (error);
1385}
1386
1387/*
1388 * MPSAFE
1389 */
1390int
1391getsockname(td, uap)
1392	struct thread *td;
1393	struct getsockname_args *uap;
1394{
1395
1396	return (getsockname1(td, uap, 0));
1397}
1398
1399#ifdef COMPAT_OLDSOCK
1400/*
1401 * MPSAFE
1402 */
1403int
1404ogetsockname(td, uap)
1405	struct thread *td;
1406	struct getsockname_args *uap;
1407{
1408
1409	return (getsockname1(td, uap, 1));
1410}
1411#endif /* COMPAT_OLDSOCK */
1412
1413/*
1414 * getpeername1() - Get name of peer for connected socket.
1415 *
1416 * MPSAFE
1417 */
1418/* ARGSUSED */
1419static int
1420getpeername1(td, uap, compat)
1421	struct thread *td;
1422	register struct getpeername_args /* {
1423		int	fdes;
1424		caddr_t	asa;
1425		int	*alen;
1426	} */ *uap;
1427	int compat;
1428{
1429	struct socket *so;
1430	struct sockaddr *sa;
1431	int len, error;
1432
1433	mtx_lock(&Giant);
1434	if ((error = fgetsock(td, uap->fdes, &so, NULL)) != 0)
1435		goto done2;
1436	if ((so->so_state & (SS_ISCONNECTED|SS_ISCONFIRMING)) == 0) {
1437		error = ENOTCONN;
1438		goto done1;
1439	}
1440	error = copyin(uap->alen, &len, sizeof (len));
1441	if (error)
1442		goto done1;
1443	if (len < 0) {
1444		error = EINVAL;
1445		goto done1;
1446	}
1447	sa = 0;
1448	error = (*so->so_proto->pr_usrreqs->pru_peeraddr)(so, &sa);
1449	if (error)
1450		goto bad;
1451	if (sa == 0) {
1452		len = 0;
1453		goto gotnothing;
1454	}
1455	len = MIN(len, sa->sa_len);
1456#ifdef COMPAT_OLDSOCK
1457	if (compat)
1458		((struct osockaddr *)sa)->sa_family =
1459		    sa->sa_family;
1460#endif
1461	error = copyout(sa, uap->asa, (u_int)len);
1462	if (error)
1463		goto bad;
1464gotnothing:
1465	error = copyout(&len, uap->alen, sizeof (len));
1466bad:
1467	if (sa)
1468		FREE(sa, M_SONAME);
1469done1:
1470	fputsock(so);
1471done2:
1472	mtx_unlock(&Giant);
1473	return (error);
1474}
1475
1476/*
1477 * MPSAFE
1478 */
1479int
1480getpeername(td, uap)
1481	struct thread *td;
1482	struct getpeername_args *uap;
1483{
1484
1485	return (getpeername1(td, uap, 0));
1486}
1487
1488#ifdef COMPAT_OLDSOCK
1489/*
1490 * MPSAFE
1491 */
1492int
1493ogetpeername(td, uap)
1494	struct thread *td;
1495	struct ogetpeername_args *uap;
1496{
1497
1498	/* XXX uap should have type `getpeername_args *' to begin with. */
1499	return (getpeername1(td, (struct getpeername_args *)uap, 1));
1500}
1501#endif /* COMPAT_OLDSOCK */
1502
1503int
1504sockargs(mp, buf, buflen, type)
1505	struct mbuf **mp;
1506	caddr_t buf;
1507	int buflen, type;
1508{
1509	register struct sockaddr *sa;
1510	register struct mbuf *m;
1511	int error;
1512
1513	if ((u_int)buflen > MLEN) {
1514#ifdef COMPAT_OLDSOCK
1515		if (type == MT_SONAME && (u_int)buflen <= 112)
1516			buflen = MLEN;		/* unix domain compat. hack */
1517		else
1518#endif
1519		return (EINVAL);
1520	}
1521	m = m_get(M_TRYWAIT, type);
1522	if (m == NULL)
1523		return (ENOBUFS);
1524	m->m_len = buflen;
1525	error = copyin(buf, mtod(m, caddr_t), (u_int)buflen);
1526	if (error)
1527		(void) m_free(m);
1528	else {
1529		*mp = m;
1530		if (type == MT_SONAME) {
1531			sa = mtod(m, struct sockaddr *);
1532
1533#if defined(COMPAT_OLDSOCK) && BYTE_ORDER != BIG_ENDIAN
1534			if (sa->sa_family == 0 && sa->sa_len < AF_MAX)
1535				sa->sa_family = sa->sa_len;
1536#endif
1537			sa->sa_len = buflen;
1538		}
1539	}
1540	return (error);
1541}
1542
1543int
1544getsockaddr(namp, uaddr, len)
1545	struct sockaddr **namp;
1546	caddr_t uaddr;
1547	size_t len;
1548{
1549	struct sockaddr *sa;
1550	int error;
1551
1552	if (len > SOCK_MAXADDRLEN)
1553		return ENAMETOOLONG;
1554	MALLOC(sa, struct sockaddr *, len, M_SONAME, M_WAITOK);
1555	error = copyin(uaddr, sa, len);
1556	if (error) {
1557		FREE(sa, M_SONAME);
1558	} else {
1559#if defined(COMPAT_OLDSOCK) && BYTE_ORDER != BIG_ENDIAN
1560		if (sa->sa_family == 0 && sa->sa_len < AF_MAX)
1561			sa->sa_family = sa->sa_len;
1562#endif
1563		sa->sa_len = len;
1564		*namp = sa;
1565	}
1566	return error;
1567}
1568
1569/*
1570 * Allocate a pool of sf_bufs (sendfile(2) or "super-fast" if you prefer. :-))
1571 */
1572static void
1573sf_buf_init(void *arg)
1574{
1575	int i;
1576
1577	mtx_init(&sf_freelist.sf_lock, "sf_bufs list lock", NULL, MTX_DEF);
1578	mtx_lock(&sf_freelist.sf_lock);
1579	SLIST_INIT(&sf_freelist.sf_head);
1580	sf_base = kmem_alloc_pageable(kernel_map, nsfbufs * PAGE_SIZE);
1581	sf_bufs = malloc(nsfbufs * sizeof(struct sf_buf), M_TEMP,
1582	    M_NOWAIT | M_ZERO);
1583	for (i = 0; i < nsfbufs; i++) {
1584		sf_bufs[i].kva = sf_base + i * PAGE_SIZE;
1585		SLIST_INSERT_HEAD(&sf_freelist.sf_head, &sf_bufs[i], free_list);
1586	}
1587	sf_buf_alloc_want = 0;
1588	mtx_unlock(&sf_freelist.sf_lock);
1589}
1590
1591/*
1592 * Get an sf_buf from the freelist. Will block if none are available.
1593 */
1594struct sf_buf *
1595sf_buf_alloc()
1596{
1597	struct sf_buf *sf;
1598	int error;
1599
1600	mtx_lock(&sf_freelist.sf_lock);
1601	while ((sf = SLIST_FIRST(&sf_freelist.sf_head)) == NULL) {
1602		sf_buf_alloc_want++;
1603		error = msleep(&sf_freelist, &sf_freelist.sf_lock, PVM|PCATCH,
1604		    "sfbufa", 0);
1605		sf_buf_alloc_want--;
1606
1607		/*
1608		 * If we got a signal, don't risk going back to sleep.
1609		 */
1610		if (error)
1611			break;
1612	}
1613	if (sf != NULL)
1614		SLIST_REMOVE_HEAD(&sf_freelist.sf_head, free_list);
1615	mtx_unlock(&sf_freelist.sf_lock);
1616	return (sf);
1617}
1618
1619#define dtosf(x)	(&sf_bufs[((uintptr_t)(x) - (uintptr_t)sf_base) >> PAGE_SHIFT])
1620
1621/*
1622 * Detatch mapped page and release resources back to the system.
1623 */
1624void
1625sf_buf_free(void *addr, void *args)
1626{
1627	struct sf_buf *sf;
1628	struct vm_page *m;
1629
1630	GIANT_REQUIRED;
1631
1632	sf = dtosf(addr);
1633	pmap_qremove((vm_offset_t)addr, 1);
1634	m = sf->m;
1635	vm_page_lock_queues();
1636	vm_page_unwire(m, 0);
1637	/*
1638	 * Check for the object going away on us. This can
1639	 * happen since we don't hold a reference to it.
1640	 * If so, we're responsible for freeing the page.
1641	 */
1642	if (m->wire_count == 0 && m->object == NULL)
1643		vm_page_free(m);
1644	vm_page_unlock_queues();
1645	sf->m = NULL;
1646	mtx_lock(&sf_freelist.sf_lock);
1647	SLIST_INSERT_HEAD(&sf_freelist.sf_head, sf, free_list);
1648	if (sf_buf_alloc_want > 0)
1649		wakeup_one(&sf_freelist);
1650	mtx_unlock(&sf_freelist.sf_lock);
1651}
1652
1653/*
1654 * sendfile(2)
1655 *
1656 * MPSAFE
1657 *
1658 * int sendfile(int fd, int s, off_t offset, size_t nbytes,
1659 *	 struct sf_hdtr *hdtr, off_t *sbytes, int flags)
1660 *
1661 * Send a file specified by 'fd' and starting at 'offset' to a socket
1662 * specified by 's'. Send only 'nbytes' of the file or until EOF if
1663 * nbytes == 0. Optionally add a header and/or trailer to the socket
1664 * output. If specified, write the total number of bytes sent into *sbytes.
1665 *
1666 */
1667int
1668sendfile(struct thread *td, struct sendfile_args *uap)
1669{
1670
1671	return (do_sendfile(td, uap, 0));
1672}
1673
1674#ifdef COMPAT_FREEBSD4
1675int
1676freebsd4_sendfile(struct thread *td, struct freebsd4_sendfile_args *uap)
1677{
1678	struct sendfile_args args;
1679
1680	args.fd = uap->fd;
1681	args.s = uap->s;
1682	args.offset = uap->offset;
1683	args.nbytes = uap->nbytes;
1684	args.hdtr = uap->hdtr;
1685	args.sbytes = uap->sbytes;
1686	args.flags = uap->flags;
1687
1688	return (do_sendfile(td, &args, 1));
1689}
1690#endif /* COMPAT_FREEBSD4 */
1691
1692static int
1693do_sendfile(struct thread *td, struct sendfile_args *uap, int compat)
1694{
1695	struct vnode *vp;
1696	struct vm_object *obj;
1697	struct socket *so = NULL;
1698	struct mbuf *m;
1699	struct sf_buf *sf;
1700	struct vm_page *pg;
1701	struct writev_args nuap;
1702	struct sf_hdtr hdtr;
1703	off_t off, xfsize, hdtr_size, sbytes = 0;
1704	int error, s;
1705
1706	mtx_lock(&Giant);
1707
1708	hdtr_size = 0;
1709
1710	/*
1711	 * The descriptor must be a regular file and have a backing VM object.
1712	 */
1713	if ((error = fgetvp_read(td, uap->fd, &vp)) != 0)
1714		goto done;
1715	if (vp->v_type != VREG || VOP_GETVOBJECT(vp, &obj) != 0) {
1716		error = EINVAL;
1717		goto done;
1718	}
1719	if ((error = fgetsock(td, uap->s, &so, NULL)) != 0)
1720		goto done;
1721	if (so->so_type != SOCK_STREAM) {
1722		error = EINVAL;
1723		goto done;
1724	}
1725	if ((so->so_state & SS_ISCONNECTED) == 0) {
1726		error = ENOTCONN;
1727		goto done;
1728	}
1729	if (uap->offset < 0) {
1730		error = EINVAL;
1731		goto done;
1732	}
1733
1734	/*
1735	 * If specified, get the pointer to the sf_hdtr struct for
1736	 * any headers/trailers.
1737	 */
1738	if (uap->hdtr != NULL) {
1739		error = copyin(uap->hdtr, &hdtr, sizeof(hdtr));
1740		if (error)
1741			goto done;
1742		/*
1743		 * Send any headers. Wimp out and use writev(2).
1744		 */
1745		if (hdtr.headers != NULL) {
1746			nuap.fd = uap->s;
1747			nuap.iovp = hdtr.headers;
1748			nuap.iovcnt = hdtr.hdr_cnt;
1749			error = writev(td, &nuap);
1750			if (error)
1751				goto done;
1752			if (compat)
1753				sbytes += td->td_retval[0];
1754			else
1755				hdtr_size += td->td_retval[0];
1756		}
1757	}
1758
1759	/*
1760	 * Protect against multiple writers to the socket.
1761	 */
1762	(void) sblock(&so->so_snd, M_WAITOK);
1763
1764	/*
1765	 * Loop through the pages in the file, starting with the requested
1766	 * offset. Get a file page (do I/O if necessary), map the file page
1767	 * into an sf_buf, attach an mbuf header to the sf_buf, and queue
1768	 * it on the socket.
1769	 */
1770	for (off = uap->offset; ; off += xfsize, sbytes += xfsize) {
1771		vm_pindex_t pindex;
1772		vm_offset_t pgoff;
1773
1774		pindex = OFF_TO_IDX(off);
1775retry_lookup:
1776		/*
1777		 * Calculate the amount to transfer. Not to exceed a page,
1778		 * the EOF, or the passed in nbytes.
1779		 */
1780		xfsize = obj->un_pager.vnp.vnp_size - off;
1781		if (xfsize > PAGE_SIZE)
1782			xfsize = PAGE_SIZE;
1783		pgoff = (vm_offset_t)(off & PAGE_MASK);
1784		if (PAGE_SIZE - pgoff < xfsize)
1785			xfsize = PAGE_SIZE - pgoff;
1786		if (uap->nbytes && xfsize > (uap->nbytes - sbytes))
1787			xfsize = uap->nbytes - sbytes;
1788		if (xfsize <= 0)
1789			break;
1790		/*
1791		 * Optimize the non-blocking case by looking at the socket space
1792		 * before going to the extra work of constituting the sf_buf.
1793		 */
1794		if ((so->so_state & SS_NBIO) && sbspace(&so->so_snd) <= 0) {
1795			if (so->so_state & SS_CANTSENDMORE)
1796				error = EPIPE;
1797			else
1798				error = EAGAIN;
1799			sbunlock(&so->so_snd);
1800			goto done;
1801		}
1802		/*
1803		 * Attempt to look up the page.
1804		 *
1805		 *	Allocate if not found
1806		 *
1807		 *	Wait and loop if busy.
1808		 */
1809		pg = vm_page_lookup(obj, pindex);
1810
1811		if (pg == NULL) {
1812			pg = vm_page_alloc(obj, pindex,
1813			    VM_ALLOC_NORMAL | VM_ALLOC_WIRED);
1814			if (pg == NULL) {
1815				VM_WAIT;
1816				goto retry_lookup;
1817			}
1818			vm_page_lock_queues();
1819			vm_page_wakeup(pg);
1820		} else {
1821			vm_page_lock_queues();
1822			if (vm_page_sleep_if_busy(pg, TRUE, "sfpbsy"))
1823				goto retry_lookup;
1824			/*
1825		 	 * Wire the page so it does not get ripped out from
1826			 * under us.
1827			 */
1828			vm_page_wire(pg);
1829		}
1830
1831		/*
1832		 * If page is not valid for what we need, initiate I/O
1833		 */
1834
1835		if (!pg->valid || !vm_page_is_valid(pg, pgoff, xfsize)) {
1836			int bsize, resid;
1837
1838			/*
1839			 * Ensure that our page is still around when the I/O
1840			 * completes.
1841			 */
1842			vm_page_io_start(pg);
1843			vm_page_unlock_queues();
1844
1845			/*
1846			 * Get the page from backing store.
1847			 */
1848			bsize = vp->v_mount->mnt_stat.f_iosize;
1849			vn_lock(vp, LK_SHARED | LK_NOPAUSE | LK_RETRY, td);
1850			error = vn_rdwr(UIO_READ, vp, NULL, MAXBSIZE,
1851			    trunc_page(off), UIO_NOCOPY, IO_NODELOCKED |
1852			    IO_VMIO | ((MAXBSIZE / bsize) << 16),
1853			    td->td_ucred, &resid, td);
1854			VOP_UNLOCK(vp, 0, td);
1855			vm_page_lock_queues();
1856			vm_page_flag_clear(pg, PG_ZERO);
1857			vm_page_io_finish(pg);
1858			if (error) {
1859				vm_page_unwire(pg, 0);
1860				/*
1861				 * See if anyone else might know about this page.
1862				 * If not and it is not valid, then free it.
1863				 */
1864				if (pg->wire_count == 0 && pg->valid == 0 &&
1865				    pg->busy == 0 && !(pg->flags & PG_BUSY) &&
1866				    pg->hold_count == 0) {
1867					vm_page_busy(pg);
1868					vm_page_free(pg);
1869				}
1870				vm_page_unlock_queues();
1871				sbunlock(&so->so_snd);
1872				goto done;
1873			}
1874		}
1875		vm_page_unlock_queues();
1876
1877		/*
1878		 * Get a sendfile buf. We usually wait as long as necessary,
1879		 * but this wait can be interrupted.
1880		 */
1881		if ((sf = sf_buf_alloc()) == NULL) {
1882			vm_page_lock_queues();
1883			vm_page_unwire(pg, 0);
1884			if (pg->wire_count == 0 && pg->object == NULL)
1885				vm_page_free(pg);
1886			vm_page_unlock_queues();
1887			sbunlock(&so->so_snd);
1888			error = EINTR;
1889			goto done;
1890		}
1891
1892		/*
1893		 * Allocate a kernel virtual page and insert the physical page
1894		 * into it.
1895		 */
1896		sf->m = pg;
1897		pmap_qenter(sf->kva, &pg, 1);
1898		/*
1899		 * Get an mbuf header and set it up as having external storage.
1900		 */
1901		MGETHDR(m, M_TRYWAIT, MT_DATA);
1902		if (m == NULL) {
1903			error = ENOBUFS;
1904			sf_buf_free((void *)sf->kva, NULL);
1905			sbunlock(&so->so_snd);
1906			goto done;
1907		}
1908		/*
1909		 * Setup external storage for mbuf.
1910		 */
1911		MEXTADD(m, sf->kva, PAGE_SIZE, sf_buf_free, NULL, M_RDONLY,
1912		    EXT_SFBUF);
1913		m->m_data = (char *) sf->kva + pgoff;
1914		m->m_pkthdr.len = m->m_len = xfsize;
1915		/*
1916		 * Add the buffer to the socket buffer chain.
1917		 */
1918		s = splnet();
1919retry_space:
1920		/*
1921		 * Make sure that the socket is still able to take more data.
1922		 * CANTSENDMORE being true usually means that the connection
1923		 * was closed. so_error is true when an error was sensed after
1924		 * a previous send.
1925		 * The state is checked after the page mapping and buffer
1926		 * allocation above since those operations may block and make
1927		 * any socket checks stale. From this point forward, nothing
1928		 * blocks before the pru_send (or more accurately, any blocking
1929		 * results in a loop back to here to re-check).
1930		 */
1931		if ((so->so_state & SS_CANTSENDMORE) || so->so_error) {
1932			if (so->so_state & SS_CANTSENDMORE) {
1933				error = EPIPE;
1934			} else {
1935				error = so->so_error;
1936				so->so_error = 0;
1937			}
1938			m_freem(m);
1939			sbunlock(&so->so_snd);
1940			splx(s);
1941			goto done;
1942		}
1943		/*
1944		 * Wait for socket space to become available. We do this just
1945		 * after checking the connection state above in order to avoid
1946		 * a race condition with sbwait().
1947		 */
1948		if (sbspace(&so->so_snd) < so->so_snd.sb_lowat) {
1949			if (so->so_state & SS_NBIO) {
1950				m_freem(m);
1951				sbunlock(&so->so_snd);
1952				splx(s);
1953				error = EAGAIN;
1954				goto done;
1955			}
1956			error = sbwait(&so->so_snd);
1957			/*
1958			 * An error from sbwait usually indicates that we've
1959			 * been interrupted by a signal. If we've sent anything
1960			 * then return bytes sent, otherwise return the error.
1961			 */
1962			if (error) {
1963				m_freem(m);
1964				sbunlock(&so->so_snd);
1965				splx(s);
1966				goto done;
1967			}
1968			goto retry_space;
1969		}
1970		error = (*so->so_proto->pr_usrreqs->pru_send)(so, 0, m, 0, 0, td);
1971		splx(s);
1972		if (error) {
1973			sbunlock(&so->so_snd);
1974			goto done;
1975		}
1976	}
1977	sbunlock(&so->so_snd);
1978
1979	/*
1980	 * Send trailers. Wimp out and use writev(2).
1981	 */
1982	if (uap->hdtr != NULL && hdtr.trailers != NULL) {
1983			nuap.fd = uap->s;
1984			nuap.iovp = hdtr.trailers;
1985			nuap.iovcnt = hdtr.trl_cnt;
1986			error = writev(td, &nuap);
1987			if (error)
1988				goto done;
1989			if (compat)
1990				sbytes += td->td_retval[0];
1991			else
1992				hdtr_size += td->td_retval[0];
1993	}
1994
1995done:
1996	/*
1997	 * If there was no error we have to clear td->td_retval[0]
1998	 * because it may have been set by writev.
1999	 */
2000	if (error == 0) {
2001		td->td_retval[0] = 0;
2002	}
2003	if (uap->sbytes != NULL) {
2004		if (!compat)
2005			sbytes += hdtr_size;
2006		copyout(&sbytes, uap->sbytes, sizeof(off_t));
2007	}
2008	if (vp)
2009		vrele(vp);
2010	if (so)
2011		fputsock(so);
2012	mtx_unlock(&Giant);
2013	return (error);
2014}
2015