xref: /freebsd/sys/kern/kern_sendfile.c (revision 7f9dff23d3092aa33ad45b2b63e52469b3c13a6e)
1 /*-
2  * Copyright (c) 2013-2015 Gleb Smirnoff <glebius@FreeBSD.org>
3  * Copyright (c) 1998, David Greenman. All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. Neither the name of the University nor the names of its contributors
14  *    may be used to endorse or promote products derived from this software
15  *    without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  */
29 
30 #include <sys/cdefs.h>
31 __FBSDID("$FreeBSD$");
32 
33 #include "opt_compat.h"
34 
35 #include <sys/param.h>
36 #include <sys/systm.h>
37 #include <sys/capsicum.h>
38 #include <sys/kernel.h>
39 #include <sys/lock.h>
40 #include <sys/mutex.h>
41 #include <sys/sysproto.h>
42 #include <sys/malloc.h>
43 #include <sys/proc.h>
44 #include <sys/mman.h>
45 #include <sys/mount.h>
46 #include <sys/mbuf.h>
47 #include <sys/protosw.h>
48 #include <sys/rwlock.h>
49 #include <sys/sf_buf.h>
50 #include <sys/socket.h>
51 #include <sys/socketvar.h>
52 #include <sys/syscallsubr.h>
53 #include <sys/sysctl.h>
54 #include <sys/vnode.h>
55 
56 #include <net/vnet.h>
57 
58 #include <security/audit/audit.h>
59 #include <security/mac/mac_framework.h>
60 
61 #include <vm/vm.h>
62 #include <vm/vm_object.h>
63 #include <vm/vm_pager.h>
64 
65 extern vm_page_t bogus_page;
66 
67 /*
68  * Structure describing a single sendfile(2) I/O, which may consist of
69  * several underlying pager I/Os.
70  *
71  * The syscall context allocates the structure and initializes 'nios'
72  * to 1.  As sendfile_swapin() runs through pages and starts asynchronous
73  * paging operations, it increments 'nios'.
74  *
75  * Every I/O completion calls sendfile_iodone(), which decrements the 'nios',
76  * and the syscall also calls sendfile_iodone() after allocating all mbufs,
77  * linking them and sending to socket.  Whoever reaches zero 'nios' is
78  * responsible to * call pru_ready on the socket, to notify it of readyness
79  * of the data.
80  */
81 struct sf_io {
82 	volatile u_int	nios;
83 	u_int		error;
84 	int		npages;
85 	struct file	*sock_fp;
86 	struct mbuf	*m;
87 	vm_page_t	pa[];
88 };
89 
90 /*
91  * Structure used to track requests with SF_SYNC flag.
92  */
93 struct sendfile_sync {
94 	struct mtx	mtx;
95 	struct cv	cv;
96 	unsigned	count;
97 };
98 
99 counter_u64_t sfstat[sizeof(struct sfstat) / sizeof(uint64_t)];
100 
101 static void
102 sfstat_init(const void *unused)
103 {
104 
105 	COUNTER_ARRAY_ALLOC(sfstat, sizeof(struct sfstat) / sizeof(uint64_t),
106 	    M_WAITOK);
107 }
108 SYSINIT(sfstat, SI_SUB_MBUF, SI_ORDER_FIRST, sfstat_init, NULL);
109 
110 static int
111 sfstat_sysctl(SYSCTL_HANDLER_ARGS)
112 {
113 	struct sfstat s;
114 
115 	COUNTER_ARRAY_COPY(sfstat, &s, sizeof(s) / sizeof(uint64_t));
116 	if (req->newptr)
117 		COUNTER_ARRAY_ZERO(sfstat, sizeof(s) / sizeof(uint64_t));
118 	return (SYSCTL_OUT(req, &s, sizeof(s)));
119 }
120 SYSCTL_PROC(_kern_ipc, OID_AUTO, sfstat, CTLTYPE_OPAQUE | CTLFLAG_RW,
121     NULL, 0, sfstat_sysctl, "I", "sendfile statistics");
122 
123 /*
124  * Detach mapped page and release resources back to the system.  Called
125  * by mbuf(9) code when last reference to a page is freed.
126  */
127 void
128 sf_ext_free(void *arg1, void *arg2)
129 {
130 	struct sf_buf *sf = arg1;
131 	struct sendfile_sync *sfs = arg2;
132 	vm_page_t pg = sf_buf_page(sf);
133 
134 	sf_buf_free(sf);
135 
136 	vm_page_lock(pg);
137 	/*
138 	 * Check for the object going away on us. This can
139 	 * happen since we don't hold a reference to it.
140 	 * If so, we're responsible for freeing the page.
141 	 */
142 	if (vm_page_unwire(pg, PQ_INACTIVE) && pg->object == NULL)
143 		vm_page_free(pg);
144 	vm_page_unlock(pg);
145 
146 	if (sfs != NULL) {
147 		mtx_lock(&sfs->mtx);
148 		KASSERT(sfs->count > 0, ("Sendfile sync botchup count == 0"));
149 		if (--sfs->count == 0)
150 			cv_signal(&sfs->cv);
151 		mtx_unlock(&sfs->mtx);
152 	}
153 }
154 
155 /*
156  * Same as above, but forces the page to be detached from the object
157  * and go into free pool.
158  */
159 void
160 sf_ext_free_nocache(void *arg1, void *arg2)
161 {
162 	struct sf_buf *sf = arg1;
163 	struct sendfile_sync *sfs = arg2;
164 	vm_page_t pg = sf_buf_page(sf);
165 
166 	sf_buf_free(sf);
167 
168 	vm_page_lock(pg);
169 	if (vm_page_unwire(pg, PQ_NONE)) {
170 		vm_object_t obj;
171 
172 		/* Try to free the page, but only if it is cheap to. */
173 		if ((obj = pg->object) == NULL)
174 			vm_page_free(pg);
175 		else if (!vm_page_xbusied(pg) && VM_OBJECT_TRYWLOCK(obj)) {
176 			vm_page_free(pg);
177 			VM_OBJECT_WUNLOCK(obj);
178 		} else
179 			vm_page_deactivate(pg);
180 	}
181 	vm_page_unlock(pg);
182 
183 	if (sfs != NULL) {
184 		mtx_lock(&sfs->mtx);
185 		KASSERT(sfs->count > 0, ("Sendfile sync botchup count == 0"));
186 		if (--sfs->count == 0)
187 			cv_signal(&sfs->cv);
188 		mtx_unlock(&sfs->mtx);
189 	}
190 }
191 
192 /*
193  * Helper function to calculate how much data to put into page i of n.
194  * Only first and last pages are special.
195  */
196 static inline off_t
197 xfsize(int i, int n, off_t off, off_t len)
198 {
199 
200 	if (i == 0)
201 		return (omin(PAGE_SIZE - (off & PAGE_MASK), len));
202 
203 	if (i == n - 1 && ((off + len) & PAGE_MASK) > 0)
204 		return ((off + len) & PAGE_MASK);
205 
206 	return (PAGE_SIZE);
207 }
208 
209 /*
210  * Helper function to get offset within object for i page.
211  */
212 static inline vm_offset_t
213 vmoff(int i, off_t off)
214 {
215 
216 	if (i == 0)
217 		return ((vm_offset_t)off);
218 
219 	return (trunc_page(off + i * PAGE_SIZE));
220 }
221 
222 /*
223  * Helper function used when allocation of a page or sf_buf failed.
224  * Pretend as if we don't have enough space, subtract xfsize() of
225  * all pages that failed.
226  */
227 static inline void
228 fixspace(int old, int new, off_t off, int *space)
229 {
230 
231 	KASSERT(old > new, ("%s: old %d new %d", __func__, old, new));
232 
233 	/* Subtract last one. */
234 	*space -= xfsize(old - 1, old, off, *space);
235 	old--;
236 
237 	if (new == old)
238 		/* There was only one page. */
239 		return;
240 
241 	/* Subtract first one. */
242 	if (new == 0) {
243 		*space -= xfsize(0, old, off, *space);
244 		new++;
245 	}
246 
247 	/* Rest of pages are full sized. */
248 	*space -= (old - new) * PAGE_SIZE;
249 
250 	KASSERT(*space >= 0, ("%s: space went backwards", __func__));
251 }
252 
253 /*
254  * I/O completion callback.
255  */
256 static void
257 sendfile_iodone(void *arg, vm_page_t *pg, int count, int error)
258 {
259 	struct sf_io *sfio = arg;
260 	struct socket *so;
261 
262 	for (int i = 0; i < count; i++)
263 		if (pg[i] != bogus_page)
264 			vm_page_xunbusy(pg[i]);
265 
266 	if (error)
267 		sfio->error = error;
268 
269 	if (!refcount_release(&sfio->nios))
270 		return;
271 
272 	so = sfio->sock_fp->f_data;
273 
274 	if (sfio->error) {
275 		struct mbuf *m;
276 
277 		/*
278 		 * I/O operation failed.  The state of data in the socket
279 		 * is now inconsistent, and all what we can do is to tear
280 		 * it down. Protocol abort method would tear down protocol
281 		 * state, free all ready mbufs and detach not ready ones.
282 		 * We will free the mbufs corresponding to this I/O manually.
283 		 *
284 		 * The socket would be marked with EIO and made available
285 		 * for read, so that application receives EIO on next
286 		 * syscall and eventually closes the socket.
287 		 */
288 		so->so_proto->pr_usrreqs->pru_abort(so);
289 		so->so_error = EIO;
290 
291 		m = sfio->m;
292 		for (int i = 0; i < sfio->npages; i++)
293 			m = m_free(m);
294 	} else {
295 		CURVNET_SET(so->so_vnet);
296 		(void )(so->so_proto->pr_usrreqs->pru_ready)(so, sfio->m,
297 		    sfio->npages);
298 		CURVNET_RESTORE();
299 	}
300 
301 	/* XXXGL: curthread */
302 	fdrop(sfio->sock_fp, curthread);
303 	free(sfio, M_TEMP);
304 }
305 
306 /*
307  * Iterate through pages vector and request paging for non-valid pages.
308  */
309 static int
310 sendfile_swapin(vm_object_t obj, struct sf_io *sfio, off_t off, off_t len,
311     int npages, int rhpages, int flags)
312 {
313 	vm_page_t *pa = sfio->pa;
314 	int nios;
315 
316 	nios = 0;
317 	flags = (flags & SF_NODISKIO) ? VM_ALLOC_NOWAIT : 0;
318 
319 	/*
320 	 * First grab all the pages and wire them.  Note that we grab
321 	 * only required pages.  Readahead pages are dealt with later.
322 	 */
323 	VM_OBJECT_WLOCK(obj);
324 	for (int i = 0; i < npages; i++) {
325 		pa[i] = vm_page_grab(obj, OFF_TO_IDX(vmoff(i, off)),
326 		    VM_ALLOC_WIRED | VM_ALLOC_NORMAL | flags);
327 		if (pa[i] == NULL) {
328 			npages = i;
329 			rhpages = 0;
330 			break;
331 		}
332 	}
333 
334 	for (int i = 0; i < npages;) {
335 		int j, a, count, rv;
336 
337 		/* Skip valid pages. */
338 		if (vm_page_is_valid(pa[i], vmoff(i, off) & PAGE_MASK,
339 		    xfsize(i, npages, off, len))) {
340 			vm_page_xunbusy(pa[i]);
341 			SFSTAT_INC(sf_pages_valid);
342 			i++;
343 			continue;
344 		}
345 
346 		/*
347 		 * Next page is invalid.  Check if it belongs to pager.  It
348 		 * may not be there, which is a regular situation for shmem
349 		 * pager.  For vnode pager this happens only in case of
350 		 * a sparse file.
351 		 *
352 		 * Important feature of vm_pager_has_page() is the hint
353 		 * stored in 'a', about how many pages we can pagein after
354 		 * this page in a single I/O.
355 		 */
356 		if (!vm_pager_has_page(obj, OFF_TO_IDX(vmoff(i, off)), NULL,
357 		    &a)) {
358 			pmap_zero_page(pa[i]);
359 			pa[i]->valid = VM_PAGE_BITS_ALL;
360 			pa[i]->dirty = 0;
361 			vm_page_xunbusy(pa[i]);
362 			i++;
363 			continue;
364 		}
365 
366 		/*
367 		 * We want to pagein as many pages as possible, limited only
368 		 * by the 'a' hint and actual request.
369 		 */
370 		count = min(a + 1, npages - i);
371 
372 		/*
373 		 * We should not pagein into a valid page, thus we first trim
374 		 * any valid pages off the end of request, and substitute
375 		 * to bogus_page those, that are in the middle.
376 		 */
377 		for (j = i + count - 1; j > i; j--) {
378 			if (vm_page_is_valid(pa[j], vmoff(j, off) & PAGE_MASK,
379 			    xfsize(j, npages, off, len))) {
380 				count--;
381 				rhpages = 0;
382 			} else
383 				break;
384 		}
385 		for (j = i + 1; j < i + count - 1; j++)
386 			if (vm_page_is_valid(pa[j], vmoff(j, off) & PAGE_MASK,
387 			    xfsize(j, npages, off, len))) {
388 				vm_page_xunbusy(pa[j]);
389 				SFSTAT_INC(sf_pages_valid);
390 				SFSTAT_INC(sf_pages_bogus);
391 				pa[j] = bogus_page;
392 			}
393 
394 		refcount_acquire(&sfio->nios);
395 		rv = vm_pager_get_pages_async(obj, pa + i, count, NULL,
396 		    i + count == npages ? &rhpages : NULL,
397 		    &sendfile_iodone, sfio);
398 		KASSERT(rv == VM_PAGER_OK, ("%s: pager fail obj %p page %p",
399 		    __func__, obj, pa[i]));
400 
401 		SFSTAT_INC(sf_iocnt);
402 		SFSTAT_ADD(sf_pages_read, count);
403 		if (i + count == npages)
404 			SFSTAT_ADD(sf_rhpages_read, rhpages);
405 
406 		/*
407 		 * Restore the valid page pointers.  They are already
408 		 * unbusied, but still wired.
409 		 */
410 		for (j = i; j < i + count; j++)
411 			if (pa[j] == bogus_page) {
412 				pa[j] = vm_page_lookup(obj,
413 				    OFF_TO_IDX(vmoff(j, off)));
414 				KASSERT(pa[j], ("%s: page %p[%d] disappeared",
415 				    __func__, pa, j));
416 
417 			}
418 		i += count;
419 		nios++;
420 	}
421 
422 	VM_OBJECT_WUNLOCK(obj);
423 
424 	if (nios == 0 && npages != 0)
425 		SFSTAT_INC(sf_noiocnt);
426 
427 	return (nios);
428 }
429 
430 static int
431 sendfile_getobj(struct thread *td, struct file *fp, vm_object_t *obj_res,
432     struct vnode **vp_res, struct shmfd **shmfd_res, off_t *obj_size,
433     int *bsize)
434 {
435 	struct vattr va;
436 	vm_object_t obj;
437 	struct vnode *vp;
438 	struct shmfd *shmfd;
439 	int error;
440 
441 	vp = *vp_res = NULL;
442 	obj = NULL;
443 	shmfd = *shmfd_res = NULL;
444 	*bsize = 0;
445 
446 	/*
447 	 * The file descriptor must be a regular file and have a
448 	 * backing VM object.
449 	 */
450 	if (fp->f_type == DTYPE_VNODE) {
451 		vp = fp->f_vnode;
452 		vn_lock(vp, LK_SHARED | LK_RETRY);
453 		if (vp->v_type != VREG) {
454 			error = EINVAL;
455 			goto out;
456 		}
457 		*bsize = vp->v_mount->mnt_stat.f_iosize;
458 		error = VOP_GETATTR(vp, &va, td->td_ucred);
459 		if (error != 0)
460 			goto out;
461 		*obj_size = va.va_size;
462 		obj = vp->v_object;
463 		if (obj == NULL) {
464 			error = EINVAL;
465 			goto out;
466 		}
467 	} else if (fp->f_type == DTYPE_SHM) {
468 		error = 0;
469 		shmfd = fp->f_data;
470 		obj = shmfd->shm_object;
471 		*obj_size = shmfd->shm_size;
472 	} else {
473 		error = EINVAL;
474 		goto out;
475 	}
476 
477 	VM_OBJECT_WLOCK(obj);
478 	if ((obj->flags & OBJ_DEAD) != 0) {
479 		VM_OBJECT_WUNLOCK(obj);
480 		error = EBADF;
481 		goto out;
482 	}
483 
484 	/*
485 	 * Temporarily increase the backing VM object's reference
486 	 * count so that a forced reclamation of its vnode does not
487 	 * immediately destroy it.
488 	 */
489 	vm_object_reference_locked(obj);
490 	VM_OBJECT_WUNLOCK(obj);
491 	*obj_res = obj;
492 	*vp_res = vp;
493 	*shmfd_res = shmfd;
494 
495 out:
496 	if (vp != NULL)
497 		VOP_UNLOCK(vp, 0);
498 	return (error);
499 }
500 
501 static int
502 sendfile_getsock(struct thread *td, int s, struct file **sock_fp,
503     struct socket **so)
504 {
505 	cap_rights_t rights;
506 	int error;
507 
508 	*sock_fp = NULL;
509 	*so = NULL;
510 
511 	/*
512 	 * The socket must be a stream socket and connected.
513 	 */
514 	error = getsock_cap(td, s, cap_rights_init(&rights, CAP_SEND),
515 	    sock_fp, NULL, NULL);
516 	if (error != 0)
517 		return (error);
518 	*so = (*sock_fp)->f_data;
519 	if ((*so)->so_type != SOCK_STREAM)
520 		return (EINVAL);
521 	if (((*so)->so_state & SS_ISCONNECTED) == 0)
522 		return (ENOTCONN);
523 	return (0);
524 }
525 
526 int
527 vn_sendfile(struct file *fp, int sockfd, struct uio *hdr_uio,
528     struct uio *trl_uio, off_t offset, size_t nbytes, off_t *sent, int flags,
529     struct thread *td)
530 {
531 	struct file *sock_fp;
532 	struct vnode *vp;
533 	struct vm_object *obj;
534 	struct socket *so;
535 	struct mbuf *m, *mh, *mhtail;
536 	struct sf_buf *sf;
537 	struct shmfd *shmfd;
538 	struct sendfile_sync *sfs;
539 	struct vattr va;
540 	off_t off, sbytes, rem, obj_size;
541 	int error, softerr, bsize, hdrlen;
542 
543 	obj = NULL;
544 	so = NULL;
545 	m = mh = NULL;
546 	sfs = NULL;
547 	hdrlen = sbytes = 0;
548 	softerr = 0;
549 
550 	error = sendfile_getobj(td, fp, &obj, &vp, &shmfd, &obj_size, &bsize);
551 	if (error != 0)
552 		return (error);
553 
554 	error = sendfile_getsock(td, sockfd, &sock_fp, &so);
555 	if (error != 0)
556 		goto out;
557 
558 #ifdef MAC
559 	error = mac_socket_check_send(td->td_ucred, so);
560 	if (error != 0)
561 		goto out;
562 #endif
563 
564 	SFSTAT_INC(sf_syscalls);
565 	SFSTAT_ADD(sf_rhpages_requested, SF_READAHEAD(flags));
566 
567 	if (flags & SF_SYNC) {
568 		sfs = malloc(sizeof *sfs, M_TEMP, M_WAITOK | M_ZERO);
569 		mtx_init(&sfs->mtx, "sendfile", NULL, MTX_DEF);
570 		cv_init(&sfs->cv, "sendfile");
571 	}
572 
573 	rem = nbytes ? omin(nbytes, obj_size - offset) : obj_size - offset;
574 
575 	/*
576 	 * Protect against multiple writers to the socket.
577 	 *
578 	 * XXXRW: Historically this has assumed non-interruptibility, so now
579 	 * we implement that, but possibly shouldn't.
580 	 */
581 	(void)sblock(&so->so_snd, SBL_WAIT | SBL_NOINTR);
582 
583 	/*
584 	 * Loop through the pages of the file, starting with the requested
585 	 * offset. Get a file page (do I/O if necessary), map the file page
586 	 * into an sf_buf, attach an mbuf header to the sf_buf, and queue
587 	 * it on the socket.
588 	 * This is done in two loops.  The inner loop turns as many pages
589 	 * as it can, up to available socket buffer space, without blocking
590 	 * into mbufs to have it bulk delivered into the socket send buffer.
591 	 * The outer loop checks the state and available space of the socket
592 	 * and takes care of the overall progress.
593 	 */
594 	for (off = offset; rem > 0; ) {
595 		struct sf_io *sfio;
596 		vm_page_t *pa;
597 		struct mbuf *mtail;
598 		int nios, space, npages, rhpages;
599 
600 		mtail = NULL;
601 		/*
602 		 * Check the socket state for ongoing connection,
603 		 * no errors and space in socket buffer.
604 		 * If space is low allow for the remainder of the
605 		 * file to be processed if it fits the socket buffer.
606 		 * Otherwise block in waiting for sufficient space
607 		 * to proceed, or if the socket is nonblocking, return
608 		 * to userland with EAGAIN while reporting how far
609 		 * we've come.
610 		 * We wait until the socket buffer has significant free
611 		 * space to do bulk sends.  This makes good use of file
612 		 * system read ahead and allows packet segmentation
613 		 * offloading hardware to take over lots of work.  If
614 		 * we were not careful here we would send off only one
615 		 * sfbuf at a time.
616 		 */
617 		SOCKBUF_LOCK(&so->so_snd);
618 		if (so->so_snd.sb_lowat < so->so_snd.sb_hiwat / 2)
619 			so->so_snd.sb_lowat = so->so_snd.sb_hiwat / 2;
620 retry_space:
621 		if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
622 			error = EPIPE;
623 			SOCKBUF_UNLOCK(&so->so_snd);
624 			goto done;
625 		} else if (so->so_error) {
626 			error = so->so_error;
627 			so->so_error = 0;
628 			SOCKBUF_UNLOCK(&so->so_snd);
629 			goto done;
630 		}
631 		space = sbspace(&so->so_snd);
632 		if (space < rem &&
633 		    (space <= 0 ||
634 		     space < so->so_snd.sb_lowat)) {
635 			if (so->so_state & SS_NBIO) {
636 				SOCKBUF_UNLOCK(&so->so_snd);
637 				error = EAGAIN;
638 				goto done;
639 			}
640 			/*
641 			 * sbwait drops the lock while sleeping.
642 			 * When we loop back to retry_space the
643 			 * state may have changed and we retest
644 			 * for it.
645 			 */
646 			error = sbwait(&so->so_snd);
647 			/*
648 			 * An error from sbwait usually indicates that we've
649 			 * been interrupted by a signal. If we've sent anything
650 			 * then return bytes sent, otherwise return the error.
651 			 */
652 			if (error != 0) {
653 				SOCKBUF_UNLOCK(&so->so_snd);
654 				goto done;
655 			}
656 			goto retry_space;
657 		}
658 		SOCKBUF_UNLOCK(&so->so_snd);
659 
660 		/*
661 		 * At the beginning of the first loop check if any headers
662 		 * are specified and copy them into mbufs.  Reduce space in
663 		 * the socket buffer by the size of the header mbuf chain.
664 		 * Clear hdr_uio here and hdrlen at the end of the first loop.
665 		 */
666 		if (hdr_uio != NULL && hdr_uio->uio_resid > 0) {
667 			hdr_uio->uio_td = td;
668 			hdr_uio->uio_rw = UIO_WRITE;
669 			mh = m_uiotombuf(hdr_uio, M_WAITOK, space, 0, 0);
670 			hdrlen = m_length(mh, &mhtail);
671 			space -= hdrlen;
672 			/*
673 			 * If header consumed all the socket buffer space,
674 			 * don't waste CPU cycles and jump to the end.
675 			 */
676 			if (space == 0) {
677 				sfio = NULL;
678 				nios = 0;
679 				goto prepend_header;
680 			}
681 			hdr_uio = NULL;
682 		}
683 
684 		if (vp != NULL) {
685 			error = vn_lock(vp, LK_SHARED);
686 			if (error != 0)
687 				goto done;
688 			error = VOP_GETATTR(vp, &va, td->td_ucred);
689 			if (error != 0 || off >= va.va_size) {
690 				VOP_UNLOCK(vp, 0);
691 				goto done;
692 			}
693 			if (va.va_size != obj_size) {
694 				if (nbytes == 0)
695 					rem += va.va_size - obj_size;
696 				else if (offset + nbytes > va.va_size)
697 					rem -= (offset + nbytes - va.va_size);
698 				obj_size = va.va_size;
699 			}
700 		}
701 
702 		if (space > rem)
703 			space = rem;
704 
705 		npages = howmany(space + (off & PAGE_MASK), PAGE_SIZE);
706 
707 		/*
708 		 * Calculate maximum allowed number of pages for readahead
709 		 * at this iteration.  If SF_USER_READAHEAD was set, we don't
710 		 * do any heuristics and use exactly the value supplied by
711 		 * application.  Otherwise, we allow readahead up to "rem".
712 		 * If application wants more, let it be, but there is no
713 		 * reason to go above MAXPHYS.  Also check against "obj_size",
714 		 * since vm_pager_has_page() can hint beyond EOF.
715 		 */
716 		if (flags & SF_USER_READAHEAD) {
717 			rhpages = SF_READAHEAD(flags);
718 		} else {
719 			rhpages = howmany(rem + (off & PAGE_MASK), PAGE_SIZE) -
720 			    npages;
721 			rhpages += SF_READAHEAD(flags);
722 		}
723 		rhpages = min(howmany(MAXPHYS, PAGE_SIZE), rhpages);
724 		rhpages = min(howmany(obj_size - trunc_page(off), PAGE_SIZE) -
725 		    npages, rhpages);
726 
727 		sfio = malloc(sizeof(struct sf_io) +
728 		    npages * sizeof(vm_page_t), M_TEMP, M_WAITOK);
729 		refcount_init(&sfio->nios, 1);
730 		sfio->error = 0;
731 
732 		nios = sendfile_swapin(obj, sfio, off, space, npages, rhpages,
733 		    flags);
734 
735 		/*
736 		 * Loop and construct maximum sized mbuf chain to be bulk
737 		 * dumped into socket buffer.
738 		 */
739 		pa = sfio->pa;
740 		for (int i = 0; i < npages; i++) {
741 			struct mbuf *m0;
742 
743 			/*
744 			 * If a page wasn't grabbed successfully, then
745 			 * trim the array. Can happen only with SF_NODISKIO.
746 			 */
747 			if (pa[i] == NULL) {
748 				SFSTAT_INC(sf_busy);
749 				fixspace(npages, i, off, &space);
750 				npages = i;
751 				softerr = EBUSY;
752 				break;
753 			}
754 
755 			/*
756 			 * Get a sendfile buf.  When allocating the
757 			 * first buffer for mbuf chain, we usually
758 			 * wait as long as necessary, but this wait
759 			 * can be interrupted.  For consequent
760 			 * buffers, do not sleep, since several
761 			 * threads might exhaust the buffers and then
762 			 * deadlock.
763 			 */
764 			sf = sf_buf_alloc(pa[i],
765 			    m != NULL ? SFB_NOWAIT : SFB_CATCH);
766 			if (sf == NULL) {
767 				SFSTAT_INC(sf_allocfail);
768 				for (int j = i; j < npages; j++) {
769 					vm_page_lock(pa[j]);
770 					vm_page_unwire(pa[j], PQ_INACTIVE);
771 					vm_page_unlock(pa[j]);
772 				}
773 				if (m == NULL)
774 					softerr = ENOBUFS;
775 				fixspace(npages, i, off, &space);
776 				npages = i;
777 				break;
778 			}
779 
780 			m0 = m_get(M_WAITOK, MT_DATA);
781 			m0->m_ext.ext_buf = (char *)sf_buf_kva(sf);
782 			m0->m_ext.ext_size = PAGE_SIZE;
783 			m0->m_ext.ext_arg1 = sf;
784 			m0->m_ext.ext_arg2 = sfs;
785 			/*
786 			 * SF_NOCACHE sets the page as being freed upon send.
787 			 * However, we ignore it for the last page in 'space',
788 			 * if the page is truncated, and we got more data to
789 			 * send (rem > space), or if we have readahead
790 			 * configured (rhpages > 0).
791 			 */
792 			if ((flags & SF_NOCACHE) == 0 ||
793 			    (i == npages - 1 &&
794 			    ((off + space) & PAGE_MASK) &&
795 			    (rem > space || rhpages > 0)))
796 				m0->m_ext.ext_type = EXT_SFBUF;
797 			else
798 				m0->m_ext.ext_type = EXT_SFBUF_NOCACHE;
799 			m0->m_ext.ext_flags = EXT_FLAG_EMBREF;
800 			m0->m_ext.ext_count = 1;
801 			m0->m_flags |= (M_EXT | M_RDONLY);
802 			if (nios)
803 				m0->m_flags |= M_NOTREADY;
804 			m0->m_data = (char *)sf_buf_kva(sf) +
805 			    (vmoff(i, off) & PAGE_MASK);
806 			m0->m_len = xfsize(i, npages, off, space);
807 
808 			if (i == 0)
809 				sfio->m = m0;
810 
811 			/* Append to mbuf chain. */
812 			if (mtail != NULL)
813 				mtail->m_next = m0;
814 			else
815 				m = m0;
816 			mtail = m0;
817 
818 			if (sfs != NULL) {
819 				mtx_lock(&sfs->mtx);
820 				sfs->count++;
821 				mtx_unlock(&sfs->mtx);
822 			}
823 		}
824 
825 		if (vp != NULL)
826 			VOP_UNLOCK(vp, 0);
827 
828 		/* Keep track of bytes processed. */
829 		off += space;
830 		rem -= space;
831 
832 		/* Prepend header, if any. */
833 		if (hdrlen) {
834 prepend_header:
835 			mhtail->m_next = m;
836 			m = mh;
837 			mh = NULL;
838 		}
839 
840 		if (m == NULL) {
841 			KASSERT(softerr, ("%s: m NULL, no error", __func__));
842 			error = softerr;
843 			free(sfio, M_TEMP);
844 			goto done;
845 		}
846 
847 		/* Add the buffer chain to the socket buffer. */
848 		KASSERT(m_length(m, NULL) == space + hdrlen,
849 		    ("%s: mlen %u space %d hdrlen %d",
850 		    __func__, m_length(m, NULL), space, hdrlen));
851 
852 		CURVNET_SET(so->so_vnet);
853 		if (nios == 0) {
854 			/*
855 			 * If sendfile_swapin() didn't initiate any I/Os,
856 			 * which happens if all data is cached in VM, then
857 			 * we can send data right now without the
858 			 * PRUS_NOTREADY flag.
859 			 */
860 			free(sfio, M_TEMP);
861 			error = (*so->so_proto->pr_usrreqs->pru_send)
862 			    (so, 0, m, NULL, NULL, td);
863 		} else {
864 			sfio->sock_fp = sock_fp;
865 			sfio->npages = npages;
866 			fhold(sock_fp);
867 			error = (*so->so_proto->pr_usrreqs->pru_send)
868 			    (so, PRUS_NOTREADY, m, NULL, NULL, td);
869 			sendfile_iodone(sfio, NULL, 0, 0);
870 		}
871 		CURVNET_RESTORE();
872 
873 		m = NULL;	/* pru_send always consumes */
874 		if (error)
875 			goto done;
876 		sbytes += space + hdrlen;
877 		if (hdrlen)
878 			hdrlen = 0;
879 		if (softerr) {
880 			error = softerr;
881 			goto done;
882 		}
883 	}
884 
885 	/*
886 	 * Send trailers. Wimp out and use writev(2).
887 	 */
888 	if (trl_uio != NULL) {
889 		sbunlock(&so->so_snd);
890 		error = kern_writev(td, sockfd, trl_uio);
891 		if (error == 0)
892 			sbytes += td->td_retval[0];
893 		goto out;
894 	}
895 
896 done:
897 	sbunlock(&so->so_snd);
898 out:
899 	/*
900 	 * If there was no error we have to clear td->td_retval[0]
901 	 * because it may have been set by writev.
902 	 */
903 	if (error == 0) {
904 		td->td_retval[0] = 0;
905 	}
906 	if (sent != NULL) {
907 		(*sent) = sbytes;
908 	}
909 	if (obj != NULL)
910 		vm_object_deallocate(obj);
911 	if (so)
912 		fdrop(sock_fp, td);
913 	if (m)
914 		m_freem(m);
915 	if (mh)
916 		m_freem(mh);
917 
918 	if (sfs != NULL) {
919 		mtx_lock(&sfs->mtx);
920 		if (sfs->count != 0)
921 			cv_wait(&sfs->cv, &sfs->mtx);
922 		KASSERT(sfs->count == 0, ("sendfile sync still busy"));
923 		cv_destroy(&sfs->cv);
924 		mtx_destroy(&sfs->mtx);
925 		free(sfs, M_TEMP);
926 	}
927 
928 	if (error == ERESTART)
929 		error = EINTR;
930 
931 	return (error);
932 }
933 
934 static int
935 sendfile(struct thread *td, struct sendfile_args *uap, int compat)
936 {
937 	struct sf_hdtr hdtr;
938 	struct uio *hdr_uio, *trl_uio;
939 	struct file *fp;
940 	cap_rights_t rights;
941 	off_t sbytes;
942 	int error;
943 
944 	/*
945 	 * File offset must be positive.  If it goes beyond EOF
946 	 * we send only the header/trailer and no payload data.
947 	 */
948 	if (uap->offset < 0)
949 		return (EINVAL);
950 
951 	hdr_uio = trl_uio = NULL;
952 
953 	if (uap->hdtr != NULL) {
954 		error = copyin(uap->hdtr, &hdtr, sizeof(hdtr));
955 		if (error != 0)
956 			goto out;
957 		if (hdtr.headers != NULL) {
958 			error = copyinuio(hdtr.headers, hdtr.hdr_cnt,
959 			    &hdr_uio);
960 			if (error != 0)
961 				goto out;
962 #ifdef COMPAT_FREEBSD4
963 			/*
964 			 * In FreeBSD < 5.0 the nbytes to send also included
965 			 * the header.  If compat is specified subtract the
966 			 * header size from nbytes.
967 			 */
968 			if (compat) {
969 				if (uap->nbytes > hdr_uio->uio_resid)
970 					uap->nbytes -= hdr_uio->uio_resid;
971 				else
972 					uap->nbytes = 0;
973 			}
974 #endif
975 		}
976 		if (hdtr.trailers != NULL) {
977 			error = copyinuio(hdtr.trailers, hdtr.trl_cnt,
978 			    &trl_uio);
979 			if (error != 0)
980 				goto out;
981 		}
982 	}
983 
984 	AUDIT_ARG_FD(uap->fd);
985 
986 	/*
987 	 * sendfile(2) can start at any offset within a file so we require
988 	 * CAP_READ+CAP_SEEK = CAP_PREAD.
989 	 */
990 	if ((error = fget_read(td, uap->fd,
991 	    cap_rights_init(&rights, CAP_PREAD), &fp)) != 0) {
992 		goto out;
993 	}
994 
995 	error = fo_sendfile(fp, uap->s, hdr_uio, trl_uio, uap->offset,
996 	    uap->nbytes, &sbytes, uap->flags, td);
997 	fdrop(fp, td);
998 
999 	if (uap->sbytes != NULL)
1000 		copyout(&sbytes, uap->sbytes, sizeof(off_t));
1001 
1002 out:
1003 	free(hdr_uio, M_IOV);
1004 	free(trl_uio, M_IOV);
1005 	return (error);
1006 }
1007 
1008 /*
1009  * sendfile(2)
1010  *
1011  * int sendfile(int fd, int s, off_t offset, size_t nbytes,
1012  *       struct sf_hdtr *hdtr, off_t *sbytes, int flags)
1013  *
1014  * Send a file specified by 'fd' and starting at 'offset' to a socket
1015  * specified by 's'. Send only 'nbytes' of the file or until EOF if nbytes ==
1016  * 0.  Optionally add a header and/or trailer to the socket output.  If
1017  * specified, write the total number of bytes sent into *sbytes.
1018  */
1019 int
1020 sys_sendfile(struct thread *td, struct sendfile_args *uap)
1021 {
1022 
1023 	return (sendfile(td, uap, 0));
1024 }
1025 
1026 #ifdef COMPAT_FREEBSD4
1027 int
1028 freebsd4_sendfile(struct thread *td, struct freebsd4_sendfile_args *uap)
1029 {
1030 	struct sendfile_args args;
1031 
1032 	args.fd = uap->fd;
1033 	args.s = uap->s;
1034 	args.offset = uap->offset;
1035 	args.nbytes = uap->nbytes;
1036 	args.hdtr = uap->hdtr;
1037 	args.sbytes = uap->sbytes;
1038 	args.flags = uap->flags;
1039 
1040 	return (sendfile(td, &args, 1));
1041 }
1042 #endif /* COMPAT_FREEBSD4 */
1043