xref: /freebsd/sys/kern/kern_sendfile.c (revision e9b148a3185f41e3a09e91ea75cae7828d908845)
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_kern_tls.h"
34 
35 #include <sys/param.h>
36 #include <sys/systm.h>
37 #include <sys/capsicum.h>
38 #include <sys/kernel.h>
39 #include <netinet/in.h>
40 #include <sys/lock.h>
41 #include <sys/ktls.h>
42 #include <sys/mutex.h>
43 #include <sys/sysproto.h>
44 #include <sys/malloc.h>
45 #include <sys/proc.h>
46 #include <sys/mman.h>
47 #include <sys/mount.h>
48 #include <sys/mbuf.h>
49 #include <sys/protosw.h>
50 #include <sys/rwlock.h>
51 #include <sys/sf_buf.h>
52 #include <sys/socket.h>
53 #include <sys/socketvar.h>
54 #include <sys/syscallsubr.h>
55 #include <sys/sysctl.h>
56 #include <sys/vnode.h>
57 
58 #include <net/vnet.h>
59 #include <netinet/tcp.h>
60 
61 #include <security/audit/audit.h>
62 #include <security/mac/mac_framework.h>
63 
64 #include <vm/vm.h>
65 #include <vm/vm_object.h>
66 #include <vm/vm_pager.h>
67 
68 #define	EXT_FLAG_SYNC		EXT_FLAG_VENDOR1
69 #define	EXT_FLAG_NOCACHE	EXT_FLAG_VENDOR2
70 #define	EXT_FLAG_CACHE_LAST	EXT_FLAG_VENDOR3
71 
72 /*
73  * Structure describing a single sendfile(2) I/O, which may consist of
74  * several underlying pager I/Os.
75  *
76  * The syscall context allocates the structure and initializes 'nios'
77  * to 1.  As sendfile_swapin() runs through pages and starts asynchronous
78  * paging operations, it increments 'nios'.
79  *
80  * Every I/O completion calls sendfile_iodone(), which decrements the 'nios',
81  * and the syscall also calls sendfile_iodone() after allocating all mbufs,
82  * linking them and sending to socket.  Whoever reaches zero 'nios' is
83  * responsible to * call pru_ready on the socket, to notify it of readyness
84  * of the data.
85  */
86 struct sf_io {
87 	volatile u_int	nios;
88 	u_int		error;
89 	int		npages;
90 	struct socket	*so;
91 	struct mbuf	*m;
92 #ifdef KERN_TLS
93 	struct ktls_session *tls;
94 #endif
95 	vm_page_t	pa[];
96 };
97 
98 /*
99  * Structure used to track requests with SF_SYNC flag.
100  */
101 struct sendfile_sync {
102 	struct mtx	mtx;
103 	struct cv	cv;
104 	unsigned	count;
105 };
106 
107 counter_u64_t sfstat[sizeof(struct sfstat) / sizeof(uint64_t)];
108 
109 static void
110 sfstat_init(const void *unused)
111 {
112 
113 	COUNTER_ARRAY_ALLOC(sfstat, sizeof(struct sfstat) / sizeof(uint64_t),
114 	    M_WAITOK);
115 }
116 SYSINIT(sfstat, SI_SUB_MBUF, SI_ORDER_FIRST, sfstat_init, NULL);
117 
118 static int
119 sfstat_sysctl(SYSCTL_HANDLER_ARGS)
120 {
121 	struct sfstat s;
122 
123 	COUNTER_ARRAY_COPY(sfstat, &s, sizeof(s) / sizeof(uint64_t));
124 	if (req->newptr)
125 		COUNTER_ARRAY_ZERO(sfstat, sizeof(s) / sizeof(uint64_t));
126 	return (SYSCTL_OUT(req, &s, sizeof(s)));
127 }
128 SYSCTL_PROC(_kern_ipc, OID_AUTO, sfstat, CTLTYPE_OPAQUE | CTLFLAG_RW,
129     NULL, 0, sfstat_sysctl, "I", "sendfile statistics");
130 
131 static void
132 sendfile_free_mext(struct mbuf *m)
133 {
134 	struct sf_buf *sf;
135 	vm_page_t pg;
136 	int flags;
137 
138 	KASSERT(m->m_flags & M_EXT && m->m_ext.ext_type == EXT_SFBUF,
139 	    ("%s: m %p !M_EXT or !EXT_SFBUF", __func__, m));
140 
141 	sf = m->m_ext.ext_arg1;
142 	pg = sf_buf_page(sf);
143 	flags = (m->m_ext.ext_flags & EXT_FLAG_NOCACHE) != 0 ? VPR_TRYFREE : 0;
144 
145 	sf_buf_free(sf);
146 	vm_page_release(pg, flags);
147 
148 	if (m->m_ext.ext_flags & EXT_FLAG_SYNC) {
149 		struct sendfile_sync *sfs = m->m_ext.ext_arg2;
150 
151 		mtx_lock(&sfs->mtx);
152 		KASSERT(sfs->count > 0, ("Sendfile sync botchup count == 0"));
153 		if (--sfs->count == 0)
154 			cv_signal(&sfs->cv);
155 		mtx_unlock(&sfs->mtx);
156 	}
157 }
158 
159 static void
160 sendfile_free_mext_pg(struct mbuf *m)
161 {
162 	struct mbuf_ext_pgs *ext_pgs;
163 	vm_page_t pg;
164 	int flags, i;
165 	bool cache_last;
166 
167 	KASSERT(m->m_flags & M_EXT && m->m_ext.ext_type == EXT_PGS,
168 	    ("%s: m %p !M_EXT or !EXT_PGS", __func__, m));
169 
170 	cache_last = m->m_ext.ext_flags & EXT_FLAG_CACHE_LAST;
171 	ext_pgs = m->m_ext.ext_pgs;
172 	flags = (m->m_ext.ext_flags & EXT_FLAG_NOCACHE) != 0 ? VPR_TRYFREE : 0;
173 
174 	for (i = 0; i < ext_pgs->npgs; i++) {
175 		if (cache_last && i == ext_pgs->npgs - 1)
176 			flags = 0;
177 		pg = PHYS_TO_VM_PAGE(ext_pgs->pa[i]);
178 		vm_page_release(pg, flags);
179 	}
180 
181 	if (m->m_ext.ext_flags & EXT_FLAG_SYNC) {
182 		struct sendfile_sync *sfs = m->m_ext.ext_arg2;
183 
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_ooffset_t
213 vmoff(int i, off_t off)
214 {
215 
216 	if (i == 0)
217 		return ((vm_ooffset_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 = sfio->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 #if defined(KERN_TLS) && defined(INVARIANTS)
273 	if ((sfio->m->m_flags & M_EXT) != 0 &&
274 	    sfio->m->m_ext.ext_type == EXT_PGS)
275 		KASSERT(sfio->tls == sfio->m->m_ext.ext_pgs->tls,
276 		    ("TLS session mismatch"));
277 	else
278 		KASSERT(sfio->tls == NULL,
279 		    ("non-ext_pgs mbuf with TLS session"));
280 #endif
281 	CURVNET_SET(so->so_vnet);
282 	if (sfio->error) {
283 		/*
284 		 * I/O operation failed.  The state of data in the socket
285 		 * is now inconsistent, and all what we can do is to tear
286 		 * it down. Protocol abort method would tear down protocol
287 		 * state, free all ready mbufs and detach not ready ones.
288 		 * We will free the mbufs corresponding to this I/O manually.
289 		 *
290 		 * The socket would be marked with EIO and made available
291 		 * for read, so that application receives EIO on next
292 		 * syscall and eventually closes the socket.
293 		 */
294 		so->so_proto->pr_usrreqs->pru_abort(so);
295 		so->so_error = EIO;
296 
297 		mb_free_notready(sfio->m, sfio->npages);
298 #ifdef KERN_TLS
299 	} else if (sfio->tls != NULL && sfio->tls->mode == TCP_TLS_MODE_SW) {
300 		/*
301 		 * I/O operation is complete, but we still need to
302 		 * encrypt.  We cannot do this in the interrupt thread
303 		 * of the disk controller, so forward the mbufs to a
304 		 * different thread.
305 		 *
306 		 * Donate the socket reference from sfio to rather
307 		 * than explicitly invoking soref().
308 		 */
309 		ktls_enqueue(sfio->m, so, sfio->npages);
310 		goto out_with_ref;
311 #endif
312 	} else
313 		(void)(so->so_proto->pr_usrreqs->pru_ready)(so, sfio->m,
314 		    sfio->npages);
315 
316 	SOCK_LOCK(so);
317 	sorele(so);
318 #ifdef KERN_TLS
319 out_with_ref:
320 #endif
321 	CURVNET_RESTORE();
322 	free(sfio, M_TEMP);
323 }
324 
325 /*
326  * Iterate through pages vector and request paging for non-valid pages.
327  */
328 static int
329 sendfile_swapin(vm_object_t obj, struct sf_io *sfio, int *nios, off_t off,
330     off_t len, int npages, int rhpages, int flags)
331 {
332 	vm_page_t *pa = sfio->pa;
333 	int grabbed;
334 
335 	*nios = 0;
336 	flags = (flags & SF_NODISKIO) ? VM_ALLOC_NOWAIT : 0;
337 
338 	/*
339 	 * First grab all the pages and wire them.  Note that we grab
340 	 * only required pages.  Readahead pages are dealt with later.
341 	 */
342 	VM_OBJECT_WLOCK(obj);
343 
344 	grabbed = vm_page_grab_pages(obj, OFF_TO_IDX(off),
345 	    VM_ALLOC_NORMAL | VM_ALLOC_WIRED | flags, pa, npages);
346 	if (grabbed < npages) {
347 		for (int i = grabbed; i < npages; i++)
348 			pa[i] = NULL;
349 		npages = grabbed;
350 		rhpages = 0;
351 	}
352 
353 	for (int i = 0; i < npages;) {
354 		int j, a, count, rv;
355 
356 		/* Skip valid pages. */
357 		if (vm_page_is_valid(pa[i], vmoff(i, off) & PAGE_MASK,
358 		    xfsize(i, npages, off, len))) {
359 			vm_page_xunbusy(pa[i]);
360 			SFSTAT_INC(sf_pages_valid);
361 			i++;
362 			continue;
363 		}
364 
365 		/*
366 		 * Next page is invalid.  Check if it belongs to pager.  It
367 		 * may not be there, which is a regular situation for shmem
368 		 * pager.  For vnode pager this happens only in case of
369 		 * a sparse file.
370 		 *
371 		 * Important feature of vm_pager_has_page() is the hint
372 		 * stored in 'a', about how many pages we can pagein after
373 		 * this page in a single I/O.
374 		 */
375 		if (!vm_pager_has_page(obj, OFF_TO_IDX(vmoff(i, off)), NULL,
376 		    &a)) {
377 			pmap_zero_page(pa[i]);
378 			pa[i]->valid = VM_PAGE_BITS_ALL;
379 			MPASS(pa[i]->dirty == 0);
380 			vm_page_xunbusy(pa[i]);
381 			i++;
382 			continue;
383 		}
384 
385 		/*
386 		 * We want to pagein as many pages as possible, limited only
387 		 * by the 'a' hint and actual request.
388 		 */
389 		count = min(a + 1, npages - i);
390 
391 		/*
392 		 * We should not pagein into a valid page, thus we first trim
393 		 * any valid pages off the end of request, and substitute
394 		 * to bogus_page those, that are in the middle.
395 		 */
396 		for (j = i + count - 1; j > i; j--) {
397 			if (vm_page_is_valid(pa[j], vmoff(j, off) & PAGE_MASK,
398 			    xfsize(j, npages, off, len))) {
399 				count--;
400 				rhpages = 0;
401 			} else
402 				break;
403 		}
404 		for (j = i + 1; j < i + count - 1; j++)
405 			if (vm_page_is_valid(pa[j], vmoff(j, off) & PAGE_MASK,
406 			    xfsize(j, npages, off, len))) {
407 				vm_page_xunbusy(pa[j]);
408 				SFSTAT_INC(sf_pages_valid);
409 				SFSTAT_INC(sf_pages_bogus);
410 				pa[j] = bogus_page;
411 			}
412 
413 		refcount_acquire(&sfio->nios);
414 		rv = vm_pager_get_pages_async(obj, pa + i, count, NULL,
415 		    i + count == npages ? &rhpages : NULL,
416 		    &sendfile_iodone, sfio);
417 		if (rv != VM_PAGER_OK) {
418 			for (j = i; j < i + count; j++) {
419 				if (pa[j] != bogus_page)
420 					vm_page_unwire(pa[j], PQ_INACTIVE);
421 			}
422 			VM_OBJECT_WUNLOCK(obj);
423 			return (EIO);
424 		}
425 
426 		SFSTAT_INC(sf_iocnt);
427 		SFSTAT_ADD(sf_pages_read, count);
428 		if (i + count == npages)
429 			SFSTAT_ADD(sf_rhpages_read, rhpages);
430 
431 		/*
432 		 * Restore the valid page pointers.  They are already
433 		 * unbusied, but still wired.
434 		 */
435 		for (j = i; j < i + count; j++)
436 			if (pa[j] == bogus_page) {
437 				pa[j] = vm_page_lookup(obj,
438 				    OFF_TO_IDX(vmoff(j, off)));
439 				KASSERT(pa[j], ("%s: page %p[%d] disappeared",
440 				    __func__, pa, j));
441 
442 			}
443 		i += count;
444 		(*nios)++;
445 	}
446 
447 	VM_OBJECT_WUNLOCK(obj);
448 
449 	if (*nios == 0 && npages != 0)
450 		SFSTAT_INC(sf_noiocnt);
451 
452 	return (0);
453 }
454 
455 static int
456 sendfile_getobj(struct thread *td, struct file *fp, vm_object_t *obj_res,
457     struct vnode **vp_res, struct shmfd **shmfd_res, off_t *obj_size,
458     int *bsize)
459 {
460 	struct vattr va;
461 	vm_object_t obj;
462 	struct vnode *vp;
463 	struct shmfd *shmfd;
464 	int error;
465 
466 	vp = *vp_res = NULL;
467 	obj = NULL;
468 	shmfd = *shmfd_res = NULL;
469 	*bsize = 0;
470 
471 	/*
472 	 * The file descriptor must be a regular file and have a
473 	 * backing VM object.
474 	 */
475 	if (fp->f_type == DTYPE_VNODE) {
476 		vp = fp->f_vnode;
477 		vn_lock(vp, LK_SHARED | LK_RETRY);
478 		if (vp->v_type != VREG) {
479 			error = EINVAL;
480 			goto out;
481 		}
482 		*bsize = vp->v_mount->mnt_stat.f_iosize;
483 		error = VOP_GETATTR(vp, &va, td->td_ucred);
484 		if (error != 0)
485 			goto out;
486 		*obj_size = va.va_size;
487 		obj = vp->v_object;
488 		if (obj == NULL) {
489 			error = EINVAL;
490 			goto out;
491 		}
492 	} else if (fp->f_type == DTYPE_SHM) {
493 		error = 0;
494 		shmfd = fp->f_data;
495 		obj = shmfd->shm_object;
496 		*obj_size = shmfd->shm_size;
497 	} else {
498 		error = EINVAL;
499 		goto out;
500 	}
501 
502 	VM_OBJECT_WLOCK(obj);
503 	if ((obj->flags & OBJ_DEAD) != 0) {
504 		VM_OBJECT_WUNLOCK(obj);
505 		error = EBADF;
506 		goto out;
507 	}
508 
509 	/*
510 	 * Temporarily increase the backing VM object's reference
511 	 * count so that a forced reclamation of its vnode does not
512 	 * immediately destroy it.
513 	 */
514 	vm_object_reference_locked(obj);
515 	VM_OBJECT_WUNLOCK(obj);
516 	*obj_res = obj;
517 	*vp_res = vp;
518 	*shmfd_res = shmfd;
519 
520 out:
521 	if (vp != NULL)
522 		VOP_UNLOCK(vp, 0);
523 	return (error);
524 }
525 
526 static int
527 sendfile_getsock(struct thread *td, int s, struct file **sock_fp,
528     struct socket **so)
529 {
530 	int error;
531 
532 	*sock_fp = NULL;
533 	*so = NULL;
534 
535 	/*
536 	 * The socket must be a stream socket and connected.
537 	 */
538 	error = getsock_cap(td, s, &cap_send_rights,
539 	    sock_fp, NULL, NULL);
540 	if (error != 0)
541 		return (error);
542 	*so = (*sock_fp)->f_data;
543 	if ((*so)->so_type != SOCK_STREAM)
544 		return (EINVAL);
545 	if (SOLISTENING(*so))
546 		return (ENOTCONN);
547 	return (0);
548 }
549 
550 int
551 vn_sendfile(struct file *fp, int sockfd, struct uio *hdr_uio,
552     struct uio *trl_uio, off_t offset, size_t nbytes, off_t *sent, int flags,
553     struct thread *td)
554 {
555 	struct file *sock_fp;
556 	struct vnode *vp;
557 	struct vm_object *obj;
558 	struct socket *so;
559 #ifdef KERN_TLS
560 	struct ktls_session *tls;
561 #endif
562 	struct mbuf_ext_pgs *ext_pgs;
563 	struct mbuf *m, *mh, *mhtail;
564 	struct sf_buf *sf;
565 	struct shmfd *shmfd;
566 	struct sendfile_sync *sfs;
567 	struct vattr va;
568 	off_t off, sbytes, rem, obj_size;
569 	int bsize, error, ext_pgs_idx, hdrlen, max_pgs, softerr;
570 #ifdef KERN_TLS
571 	int tls_enq_cnt;
572 #endif
573 	bool use_ext_pgs;
574 
575 	obj = NULL;
576 	so = NULL;
577 	m = mh = NULL;
578 	sfs = NULL;
579 #ifdef KERN_TLS
580 	tls = NULL;
581 #endif
582 	hdrlen = sbytes = 0;
583 	softerr = 0;
584 	use_ext_pgs = false;
585 
586 	error = sendfile_getobj(td, fp, &obj, &vp, &shmfd, &obj_size, &bsize);
587 	if (error != 0)
588 		return (error);
589 
590 	error = sendfile_getsock(td, sockfd, &sock_fp, &so);
591 	if (error != 0)
592 		goto out;
593 
594 #ifdef MAC
595 	error = mac_socket_check_send(td->td_ucred, so);
596 	if (error != 0)
597 		goto out;
598 #endif
599 
600 	SFSTAT_INC(sf_syscalls);
601 	SFSTAT_ADD(sf_rhpages_requested, SF_READAHEAD(flags));
602 
603 	if (flags & SF_SYNC) {
604 		sfs = malloc(sizeof *sfs, M_TEMP, M_WAITOK | M_ZERO);
605 		mtx_init(&sfs->mtx, "sendfile", NULL, MTX_DEF);
606 		cv_init(&sfs->cv, "sendfile");
607 	}
608 
609 	rem = nbytes ? omin(nbytes, obj_size - offset) : obj_size - offset;
610 
611 	/*
612 	 * Protect against multiple writers to the socket.
613 	 *
614 	 * XXXRW: Historically this has assumed non-interruptibility, so now
615 	 * we implement that, but possibly shouldn't.
616 	 */
617 	(void)sblock(&so->so_snd, SBL_WAIT | SBL_NOINTR);
618 #ifdef KERN_TLS
619 	tls = ktls_hold(so->so_snd.sb_tls_info);
620 #endif
621 
622 	/*
623 	 * Loop through the pages of the file, starting with the requested
624 	 * offset. Get a file page (do I/O if necessary), map the file page
625 	 * into an sf_buf, attach an mbuf header to the sf_buf, and queue
626 	 * it on the socket.
627 	 * This is done in two loops.  The inner loop turns as many pages
628 	 * as it can, up to available socket buffer space, without blocking
629 	 * into mbufs to have it bulk delivered into the socket send buffer.
630 	 * The outer loop checks the state and available space of the socket
631 	 * and takes care of the overall progress.
632 	 */
633 	for (off = offset; rem > 0; ) {
634 		struct sf_io *sfio;
635 		vm_page_t *pa;
636 		struct mbuf *mtail;
637 		int nios, space, npages, rhpages;
638 
639 		mtail = NULL;
640 		/*
641 		 * Check the socket state for ongoing connection,
642 		 * no errors and space in socket buffer.
643 		 * If space is low allow for the remainder of the
644 		 * file to be processed if it fits the socket buffer.
645 		 * Otherwise block in waiting for sufficient space
646 		 * to proceed, or if the socket is nonblocking, return
647 		 * to userland with EAGAIN while reporting how far
648 		 * we've come.
649 		 * We wait until the socket buffer has significant free
650 		 * space to do bulk sends.  This makes good use of file
651 		 * system read ahead and allows packet segmentation
652 		 * offloading hardware to take over lots of work.  If
653 		 * we were not careful here we would send off only one
654 		 * sfbuf at a time.
655 		 */
656 		SOCKBUF_LOCK(&so->so_snd);
657 		if (so->so_snd.sb_lowat < so->so_snd.sb_hiwat / 2)
658 			so->so_snd.sb_lowat = so->so_snd.sb_hiwat / 2;
659 retry_space:
660 		if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
661 			error = EPIPE;
662 			SOCKBUF_UNLOCK(&so->so_snd);
663 			goto done;
664 		} else if (so->so_error) {
665 			error = so->so_error;
666 			so->so_error = 0;
667 			SOCKBUF_UNLOCK(&so->so_snd);
668 			goto done;
669 		}
670 		if ((so->so_state & SS_ISCONNECTED) == 0) {
671 			SOCKBUF_UNLOCK(&so->so_snd);
672 			error = ENOTCONN;
673 			goto done;
674 		}
675 
676 		space = sbspace(&so->so_snd);
677 		if (space < rem &&
678 		    (space <= 0 ||
679 		     space < so->so_snd.sb_lowat)) {
680 			if (so->so_state & SS_NBIO) {
681 				SOCKBUF_UNLOCK(&so->so_snd);
682 				error = EAGAIN;
683 				goto done;
684 			}
685 			/*
686 			 * sbwait drops the lock while sleeping.
687 			 * When we loop back to retry_space the
688 			 * state may have changed and we retest
689 			 * for it.
690 			 */
691 			error = sbwait(&so->so_snd);
692 			/*
693 			 * An error from sbwait usually indicates that we've
694 			 * been interrupted by a signal. If we've sent anything
695 			 * then return bytes sent, otherwise return the error.
696 			 */
697 			if (error != 0) {
698 				SOCKBUF_UNLOCK(&so->so_snd);
699 				goto done;
700 			}
701 			goto retry_space;
702 		}
703 		SOCKBUF_UNLOCK(&so->so_snd);
704 
705 		/*
706 		 * At the beginning of the first loop check if any headers
707 		 * are specified and copy them into mbufs.  Reduce space in
708 		 * the socket buffer by the size of the header mbuf chain.
709 		 * Clear hdr_uio here and hdrlen at the end of the first loop.
710 		 */
711 		if (hdr_uio != NULL && hdr_uio->uio_resid > 0) {
712 			hdr_uio->uio_td = td;
713 			hdr_uio->uio_rw = UIO_WRITE;
714 #ifdef KERN_TLS
715 			if (tls != NULL)
716 				mh = m_uiotombuf(hdr_uio, M_WAITOK, space,
717 				    tls->params.max_frame_len, M_NOMAP);
718 			else
719 #endif
720 				mh = m_uiotombuf(hdr_uio, M_WAITOK,
721 				    space, 0, 0);
722 			hdrlen = m_length(mh, &mhtail);
723 			space -= hdrlen;
724 			/*
725 			 * If header consumed all the socket buffer space,
726 			 * don't waste CPU cycles and jump to the end.
727 			 */
728 			if (space == 0) {
729 				sfio = NULL;
730 				nios = 0;
731 				goto prepend_header;
732 			}
733 			hdr_uio = NULL;
734 		}
735 
736 		if (vp != NULL) {
737 			error = vn_lock(vp, LK_SHARED);
738 			if (error != 0)
739 				goto done;
740 			error = VOP_GETATTR(vp, &va, td->td_ucred);
741 			if (error != 0 || off >= va.va_size) {
742 				VOP_UNLOCK(vp, 0);
743 				goto done;
744 			}
745 			if (va.va_size != obj_size) {
746 				obj_size = va.va_size;
747 				rem = nbytes ?
748 				    omin(nbytes + offset, obj_size) : obj_size;
749 				rem -= off;
750 			}
751 		}
752 
753 		if (space > rem)
754 			space = rem;
755 		else if (space > PAGE_SIZE) {
756 			/*
757 			 * Use page boundaries when possible for large
758 			 * requests.
759 			 */
760 			if (off & PAGE_MASK)
761 				space -= (PAGE_SIZE - (off & PAGE_MASK));
762 			space = trunc_page(space);
763 			if (off & PAGE_MASK)
764 				space += (PAGE_SIZE - (off & PAGE_MASK));
765 		}
766 
767 		npages = howmany(space + (off & PAGE_MASK), PAGE_SIZE);
768 
769 		/*
770 		 * Calculate maximum allowed number of pages for readahead
771 		 * at this iteration.  If SF_USER_READAHEAD was set, we don't
772 		 * do any heuristics and use exactly the value supplied by
773 		 * application.  Otherwise, we allow readahead up to "rem".
774 		 * If application wants more, let it be, but there is no
775 		 * reason to go above MAXPHYS.  Also check against "obj_size",
776 		 * since vm_pager_has_page() can hint beyond EOF.
777 		 */
778 		if (flags & SF_USER_READAHEAD) {
779 			rhpages = SF_READAHEAD(flags);
780 		} else {
781 			rhpages = howmany(rem + (off & PAGE_MASK), PAGE_SIZE) -
782 			    npages;
783 			rhpages += SF_READAHEAD(flags);
784 		}
785 		rhpages = min(howmany(MAXPHYS, PAGE_SIZE), rhpages);
786 		rhpages = min(howmany(obj_size - trunc_page(off), PAGE_SIZE) -
787 		    npages, rhpages);
788 
789 		sfio = malloc(sizeof(struct sf_io) +
790 		    npages * sizeof(vm_page_t), M_TEMP, M_WAITOK);
791 		refcount_init(&sfio->nios, 1);
792 		sfio->so = so;
793 		sfio->error = 0;
794 
795 #ifdef KERN_TLS
796 		/*
797 		 * This doesn't use ktls_hold() because sfio->m will
798 		 * also have a reference on 'tls' that will be valid
799 		 * for all of sfio's lifetime.
800 		 */
801 		sfio->tls = tls;
802 #endif
803 
804 		error = sendfile_swapin(obj, sfio, &nios, off, space, npages,
805 		    rhpages, flags);
806 		if (error != 0) {
807 			if (vp != NULL)
808 				VOP_UNLOCK(vp, 0);
809 			free(sfio, M_TEMP);
810 			goto done;
811 		}
812 
813 		/*
814 		 * Loop and construct maximum sized mbuf chain to be bulk
815 		 * dumped into socket buffer.
816 		 */
817 		pa = sfio->pa;
818 
819 		/*
820 		 * Use unmapped mbufs if enabled for TCP.  Unmapped
821 		 * bufs are restricted to TCP as that is what has been
822 		 * tested.  In particular, unmapped mbufs have not
823 		 * been tested with UNIX-domain sockets.
824 		 *
825 		 * TLS frames always require unmapped mbufs.
826 		 */
827 		if ((mb_use_ext_pgs &&
828 		    so->so_proto->pr_protocol == IPPROTO_TCP)
829 #ifdef KERN_TLS
830 		    || tls != NULL
831 #endif
832 		    ) {
833 			use_ext_pgs = true;
834 #ifdef KERN_TLS
835 			if (tls != NULL)
836 				max_pgs = num_pages(tls->params.max_frame_len);
837 			else
838 #endif
839 				max_pgs = MBUF_PEXT_MAX_PGS;
840 
841 			/* Start at last index, to wrap on first use. */
842 			ext_pgs_idx = max_pgs - 1;
843 		}
844 
845 		for (int i = 0; i < npages; i++) {
846 			struct mbuf *m0;
847 
848 			/*
849 			 * If a page wasn't grabbed successfully, then
850 			 * trim the array. Can happen only with SF_NODISKIO.
851 			 */
852 			if (pa[i] == NULL) {
853 				SFSTAT_INC(sf_busy);
854 				fixspace(npages, i, off, &space);
855 				npages = i;
856 				softerr = EBUSY;
857 				break;
858 			}
859 
860 			if (use_ext_pgs) {
861 				off_t xfs;
862 
863 				ext_pgs_idx++;
864 				if (ext_pgs_idx == max_pgs) {
865 					m0 = mb_alloc_ext_pgs(M_WAITOK, false,
866 					    sendfile_free_mext_pg);
867 
868 					if (flags & SF_NOCACHE) {
869 						m0->m_ext.ext_flags |=
870 						    EXT_FLAG_NOCACHE;
871 
872 						/*
873 						 * See comment below regarding
874 						 * ignoring SF_NOCACHE for the
875 						 * last page.
876 						 */
877 						if ((npages - i <= max_pgs) &&
878 						    ((off + space) & PAGE_MASK) &&
879 						    (rem > space || rhpages > 0))
880 							m0->m_ext.ext_flags |=
881 							    EXT_FLAG_CACHE_LAST;
882 					}
883 					if (sfs != NULL) {
884 						m0->m_ext.ext_flags |=
885 						    EXT_FLAG_SYNC;
886 						m0->m_ext.ext_arg2 = sfs;
887 						mtx_lock(&sfs->mtx);
888 						sfs->count++;
889 						mtx_unlock(&sfs->mtx);
890 					}
891 					ext_pgs = m0->m_ext.ext_pgs;
892 					if (i == 0)
893 						sfio->m = m0;
894 					ext_pgs_idx = 0;
895 
896 					/* Append to mbuf chain. */
897 					if (mtail != NULL)
898 						mtail->m_next = m0;
899 					else
900 						m = m0;
901 					mtail = m0;
902 					ext_pgs->first_pg_off =
903 					    vmoff(i, off) & PAGE_MASK;
904 				}
905 				if (nios) {
906 					mtail->m_flags |= M_NOTREADY;
907 					ext_pgs->nrdy++;
908 				}
909 
910 				ext_pgs->pa[ext_pgs_idx] = VM_PAGE_TO_PHYS(pa[i]);
911 				ext_pgs->npgs++;
912 				xfs = xfsize(i, npages, off, space);
913 				ext_pgs->last_pg_len = xfs;
914 				MBUF_EXT_PGS_ASSERT_SANITY(ext_pgs);
915 				mtail->m_len += xfs;
916 				mtail->m_ext.ext_size += PAGE_SIZE;
917 				continue;
918 			}
919 
920 			/*
921 			 * Get a sendfile buf.  When allocating the
922 			 * first buffer for mbuf chain, we usually
923 			 * wait as long as necessary, but this wait
924 			 * can be interrupted.  For consequent
925 			 * buffers, do not sleep, since several
926 			 * threads might exhaust the buffers and then
927 			 * deadlock.
928 			 */
929 			sf = sf_buf_alloc(pa[i],
930 			    m != NULL ? SFB_NOWAIT : SFB_CATCH);
931 			if (sf == NULL) {
932 				SFSTAT_INC(sf_allocfail);
933 				for (int j = i; j < npages; j++)
934 					vm_page_unwire(pa[j], PQ_INACTIVE);
935 				if (m == NULL)
936 					softerr = ENOBUFS;
937 				fixspace(npages, i, off, &space);
938 				npages = i;
939 				break;
940 			}
941 
942 			m0 = m_get(M_WAITOK, MT_DATA);
943 			m0->m_ext.ext_buf = (char *)sf_buf_kva(sf);
944 			m0->m_ext.ext_size = PAGE_SIZE;
945 			m0->m_ext.ext_arg1 = sf;
946 			m0->m_ext.ext_type = EXT_SFBUF;
947 			m0->m_ext.ext_flags = EXT_FLAG_EMBREF;
948 			m0->m_ext.ext_free = sendfile_free_mext;
949 			/*
950 			 * SF_NOCACHE sets the page as being freed upon send.
951 			 * However, we ignore it for the last page in 'space',
952 			 * if the page is truncated, and we got more data to
953 			 * send (rem > space), or if we have readahead
954 			 * configured (rhpages > 0).
955 			 */
956 			if ((flags & SF_NOCACHE) &&
957 			    (i != npages - 1 ||
958 			    !((off + space) & PAGE_MASK) ||
959 			    !(rem > space || rhpages > 0)))
960 				m0->m_ext.ext_flags |= EXT_FLAG_NOCACHE;
961 			if (sfs != NULL) {
962 				m0->m_ext.ext_flags |= EXT_FLAG_SYNC;
963 				m0->m_ext.ext_arg2 = sfs;
964 				mtx_lock(&sfs->mtx);
965 				sfs->count++;
966 				mtx_unlock(&sfs->mtx);
967 			}
968 			m0->m_ext.ext_count = 1;
969 			m0->m_flags |= (M_EXT | M_RDONLY);
970 			if (nios)
971 				m0->m_flags |= M_NOTREADY;
972 			m0->m_data = (char *)sf_buf_kva(sf) +
973 			    (vmoff(i, off) & PAGE_MASK);
974 			m0->m_len = xfsize(i, npages, off, space);
975 
976 			if (i == 0)
977 				sfio->m = m0;
978 
979 			/* Append to mbuf chain. */
980 			if (mtail != NULL)
981 				mtail->m_next = m0;
982 			else
983 				m = m0;
984 			mtail = m0;
985 		}
986 
987 		if (vp != NULL)
988 			VOP_UNLOCK(vp, 0);
989 
990 		/* Keep track of bytes processed. */
991 		off += space;
992 		rem -= space;
993 
994 		/* Prepend header, if any. */
995 		if (hdrlen) {
996 prepend_header:
997 			mhtail->m_next = m;
998 			m = mh;
999 			mh = NULL;
1000 		}
1001 
1002 		if (m == NULL) {
1003 			KASSERT(softerr, ("%s: m NULL, no error", __func__));
1004 			error = softerr;
1005 			free(sfio, M_TEMP);
1006 			goto done;
1007 		}
1008 
1009 		/* Add the buffer chain to the socket buffer. */
1010 		KASSERT(m_length(m, NULL) == space + hdrlen,
1011 		    ("%s: mlen %u space %d hdrlen %d",
1012 		    __func__, m_length(m, NULL), space, hdrlen));
1013 
1014 		CURVNET_SET(so->so_vnet);
1015 #ifdef KERN_TLS
1016 		if (tls != NULL) {
1017 			error = ktls_frame(m, tls, &tls_enq_cnt,
1018 			    TLS_RLTYPE_APP);
1019 			if (error != 0)
1020 				goto done;
1021 		}
1022 #endif
1023 		if (nios == 0) {
1024 			/*
1025 			 * If sendfile_swapin() didn't initiate any I/Os,
1026 			 * which happens if all data is cached in VM, then
1027 			 * we can send data right now without the
1028 			 * PRUS_NOTREADY flag.
1029 			 */
1030 			free(sfio, M_TEMP);
1031 #ifdef KERN_TLS
1032 			if (tls != NULL && tls->mode == TCP_TLS_MODE_SW) {
1033 				error = (*so->so_proto->pr_usrreqs->pru_send)
1034 				    (so, PRUS_NOTREADY, m, NULL, NULL, td);
1035 				soref(so);
1036 				ktls_enqueue(m, so, tls_enq_cnt);
1037 			} else
1038 #endif
1039 				error = (*so->so_proto->pr_usrreqs->pru_send)
1040 				    (so, 0, m, NULL, NULL, td);
1041 		} else {
1042 			sfio->npages = npages;
1043 			soref(so);
1044 			error = (*so->so_proto->pr_usrreqs->pru_send)
1045 			    (so, PRUS_NOTREADY, m, NULL, NULL, td);
1046 			sendfile_iodone(sfio, NULL, 0, 0);
1047 		}
1048 		CURVNET_RESTORE();
1049 
1050 		m = NULL;	/* pru_send always consumes */
1051 		if (error)
1052 			goto done;
1053 		sbytes += space + hdrlen;
1054 		if (hdrlen)
1055 			hdrlen = 0;
1056 		if (softerr) {
1057 			error = softerr;
1058 			goto done;
1059 		}
1060 	}
1061 
1062 	/*
1063 	 * Send trailers. Wimp out and use writev(2).
1064 	 */
1065 	if (trl_uio != NULL) {
1066 		sbunlock(&so->so_snd);
1067 		error = kern_writev(td, sockfd, trl_uio);
1068 		if (error == 0)
1069 			sbytes += td->td_retval[0];
1070 		goto out;
1071 	}
1072 
1073 done:
1074 	sbunlock(&so->so_snd);
1075 out:
1076 	/*
1077 	 * If there was no error we have to clear td->td_retval[0]
1078 	 * because it may have been set by writev.
1079 	 */
1080 	if (error == 0) {
1081 		td->td_retval[0] = 0;
1082 	}
1083 	if (sent != NULL) {
1084 		(*sent) = sbytes;
1085 	}
1086 	if (obj != NULL)
1087 		vm_object_deallocate(obj);
1088 	if (so)
1089 		fdrop(sock_fp, td);
1090 	if (m)
1091 		m_freem(m);
1092 	if (mh)
1093 		m_freem(mh);
1094 
1095 	if (sfs != NULL) {
1096 		mtx_lock(&sfs->mtx);
1097 		if (sfs->count != 0)
1098 			cv_wait(&sfs->cv, &sfs->mtx);
1099 		KASSERT(sfs->count == 0, ("sendfile sync still busy"));
1100 		cv_destroy(&sfs->cv);
1101 		mtx_destroy(&sfs->mtx);
1102 		free(sfs, M_TEMP);
1103 	}
1104 #ifdef KERN_TLS
1105 	if (tls != NULL)
1106 		ktls_free(tls);
1107 #endif
1108 
1109 	if (error == ERESTART)
1110 		error = EINTR;
1111 
1112 	return (error);
1113 }
1114 
1115 static int
1116 sendfile(struct thread *td, struct sendfile_args *uap, int compat)
1117 {
1118 	struct sf_hdtr hdtr;
1119 	struct uio *hdr_uio, *trl_uio;
1120 	struct file *fp;
1121 	off_t sbytes;
1122 	int error;
1123 
1124 	/*
1125 	 * File offset must be positive.  If it goes beyond EOF
1126 	 * we send only the header/trailer and no payload data.
1127 	 */
1128 	if (uap->offset < 0)
1129 		return (EINVAL);
1130 
1131 	sbytes = 0;
1132 	hdr_uio = trl_uio = NULL;
1133 
1134 	if (uap->hdtr != NULL) {
1135 		error = copyin(uap->hdtr, &hdtr, sizeof(hdtr));
1136 		if (error != 0)
1137 			goto out;
1138 		if (hdtr.headers != NULL) {
1139 			error = copyinuio(hdtr.headers, hdtr.hdr_cnt,
1140 			    &hdr_uio);
1141 			if (error != 0)
1142 				goto out;
1143 #ifdef COMPAT_FREEBSD4
1144 			/*
1145 			 * In FreeBSD < 5.0 the nbytes to send also included
1146 			 * the header.  If compat is specified subtract the
1147 			 * header size from nbytes.
1148 			 */
1149 			if (compat) {
1150 				if (uap->nbytes > hdr_uio->uio_resid)
1151 					uap->nbytes -= hdr_uio->uio_resid;
1152 				else
1153 					uap->nbytes = 0;
1154 			}
1155 #endif
1156 		}
1157 		if (hdtr.trailers != NULL) {
1158 			error = copyinuio(hdtr.trailers, hdtr.trl_cnt,
1159 			    &trl_uio);
1160 			if (error != 0)
1161 				goto out;
1162 		}
1163 	}
1164 
1165 	AUDIT_ARG_FD(uap->fd);
1166 
1167 	/*
1168 	 * sendfile(2) can start at any offset within a file so we require
1169 	 * CAP_READ+CAP_SEEK = CAP_PREAD.
1170 	 */
1171 	if ((error = fget_read(td, uap->fd, &cap_pread_rights, &fp)) != 0)
1172 		goto out;
1173 
1174 	error = fo_sendfile(fp, uap->s, hdr_uio, trl_uio, uap->offset,
1175 	    uap->nbytes, &sbytes, uap->flags, td);
1176 	fdrop(fp, td);
1177 
1178 	if (uap->sbytes != NULL)
1179 		copyout(&sbytes, uap->sbytes, sizeof(off_t));
1180 
1181 out:
1182 	free(hdr_uio, M_IOV);
1183 	free(trl_uio, M_IOV);
1184 	return (error);
1185 }
1186 
1187 /*
1188  * sendfile(2)
1189  *
1190  * int sendfile(int fd, int s, off_t offset, size_t nbytes,
1191  *       struct sf_hdtr *hdtr, off_t *sbytes, int flags)
1192  *
1193  * Send a file specified by 'fd' and starting at 'offset' to a socket
1194  * specified by 's'. Send only 'nbytes' of the file or until EOF if nbytes ==
1195  * 0.  Optionally add a header and/or trailer to the socket output.  If
1196  * specified, write the total number of bytes sent into *sbytes.
1197  */
1198 int
1199 sys_sendfile(struct thread *td, struct sendfile_args *uap)
1200 {
1201 
1202 	return (sendfile(td, uap, 0));
1203 }
1204 
1205 #ifdef COMPAT_FREEBSD4
1206 int
1207 freebsd4_sendfile(struct thread *td, struct freebsd4_sendfile_args *uap)
1208 {
1209 	struct sendfile_args args;
1210 
1211 	args.fd = uap->fd;
1212 	args.s = uap->s;
1213 	args.offset = uap->offset;
1214 	args.nbytes = uap->nbytes;
1215 	args.hdtr = uap->hdtr;
1216 	args.sbytes = uap->sbytes;
1217 	args.flags = uap->flags;
1218 
1219 	return (sendfile(td, &args, 1));
1220 }
1221 #endif /* COMPAT_FREEBSD4 */
1222