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