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 "opt_kern_tls.h"
31
32 #include <sys/param.h>
33 #include <sys/systm.h>
34 #include <sys/capsicum.h>
35 #include <sys/inotify.h>
36 #include <sys/kernel.h>
37 #include <sys/lock.h>
38 #include <sys/ktls.h>
39 #include <sys/mutex.h>
40 #include <sys/malloc.h>
41 #include <sys/mman.h>
42 #include <sys/mount.h>
43 #include <sys/mbuf.h>
44 #include <sys/proc.h>
45 #include <sys/protosw.h>
46 #include <sys/rwlock.h>
47 #include <sys/sf_buf.h>
48 #include <sys/socket.h>
49 #include <sys/socketvar.h>
50 #include <sys/syscallsubr.h>
51 #include <sys/sysctl.h>
52 #include <sys/sysproto.h>
53 #include <sys/vnode.h>
54
55 #include <net/vnet.h>
56 #include <netinet/in.h>
57 #include <netinet/tcp.h>
58 #include <netinet/in_pcb.h>
59 #include <netinet/tcp_var.h>
60 #include <netinet/tcp_log_buf.h>
61
62 #include <security/audit/audit.h>
63 #include <security/mac/mac_framework.h>
64
65 #include <vm/vm.h>
66 #include <vm/vm_object.h>
67 #include <vm/vm_pager.h>
68
69 static MALLOC_DEFINE(M_SENDFILE, "sendfile", "sendfile dynamic memory");
70
71 #define EXT_FLAG_NOCACHE EXT_FLAG_VENDOR2
72 #define EXT_FLAG_CACHE_LAST EXT_FLAG_VENDOR3
73
74 /*
75 * Structure describing a single sendfile(2) I/O, which may consist of
76 * several underlying pager I/Os.
77 *
78 * The syscall context allocates the structure and initializes 'nios'
79 * to 1. As sendfile_swapin() runs through pages and starts asynchronous
80 * paging operations, it increments 'nios'.
81 *
82 * Every I/O completion calls sendfile_iodone(), which decrements the 'nios',
83 * and the syscall also calls sendfile_iodone() after allocating all mbufs,
84 * linking them and sending to socket. Whoever reaches zero 'nios' is
85 * responsible to call pr_ready() on the socket, to notify it of readyness
86 * of the data.
87 */
88 struct sf_io {
89 volatile u_int nios;
90 u_int error;
91 int npages;
92 struct socket *so;
93 struct mbuf *m;
94 vm_object_t obj;
95 vm_pindex_t pindex0;
96 #ifdef KERN_TLS
97 struct ktls_session *tls;
98 #endif
99 vm_page_t pa[];
100 };
101
102 counter_u64_t sfstat[sizeof(struct sfstat) / sizeof(uint64_t)];
103
104 static void
sfstat_init(const void * unused)105 sfstat_init(const void *unused)
106 {
107
108 COUNTER_ARRAY_ALLOC(sfstat, sizeof(struct sfstat) / sizeof(uint64_t),
109 M_WAITOK);
110 }
111 SYSINIT(sfstat, SI_SUB_MBUF, SI_ORDER_FIRST, sfstat_init, NULL);
112
113 static int
sfstat_sysctl(SYSCTL_HANDLER_ARGS)114 sfstat_sysctl(SYSCTL_HANDLER_ARGS)
115 {
116 struct sfstat s;
117
118 COUNTER_ARRAY_COPY(sfstat, &s, sizeof(s) / sizeof(uint64_t));
119 if (req->newptr)
120 COUNTER_ARRAY_ZERO(sfstat, sizeof(s) / sizeof(uint64_t));
121 return (SYSCTL_OUT(req, &s, sizeof(s)));
122 }
123 SYSCTL_PROC(_kern_ipc, OID_AUTO, sfstat,
124 CTLTYPE_OPAQUE | CTLFLAG_RW | CTLFLAG_MPSAFE, NULL, 0,
125 sfstat_sysctl, "I",
126 "sendfile statistics");
127
128 static void
sendfile_free_mext(struct mbuf * m)129 sendfile_free_mext(struct mbuf *m)
130 {
131 struct sf_buf *sf;
132 vm_page_t pg;
133 int flags;
134
135 KASSERT(m->m_flags & M_EXT && m->m_ext.ext_type == EXT_SFBUF,
136 ("%s: m %p !M_EXT or !EXT_SFBUF", __func__, m));
137
138 sf = m->m_ext.ext_arg1;
139 pg = sf_buf_page(sf);
140 flags = (m->m_ext.ext_flags & EXT_FLAG_NOCACHE) != 0 ? VPR_TRYFREE : 0;
141
142 sf_buf_free(sf);
143 vm_page_release(pg, flags);
144 }
145
146 static void
sendfile_free_mext_pg(struct mbuf * m)147 sendfile_free_mext_pg(struct mbuf *m)
148 {
149 vm_page_t pg;
150 int flags, i;
151 bool cache_last;
152
153 M_ASSERTEXTPG(m);
154
155 cache_last = m->m_ext.ext_flags & EXT_FLAG_CACHE_LAST;
156 flags = (m->m_ext.ext_flags & EXT_FLAG_NOCACHE) != 0 ? VPR_TRYFREE : 0;
157
158 for (i = 0; i < m->m_epg_npgs; i++) {
159 if (cache_last && i == m->m_epg_npgs - 1)
160 flags = 0;
161 pg = PHYS_TO_VM_PAGE(m->m_epg_pa[i]);
162 vm_page_release(pg, flags);
163 }
164 }
165
166 /*
167 * Helper function to calculate how much data to put into page i of n.
168 * Only first and last pages are special.
169 */
170 static inline off_t
xfsize(int i,int n,off_t off,off_t len)171 xfsize(int i, int n, off_t off, off_t len)
172 {
173
174 if (i == 0)
175 return (omin(PAGE_SIZE - (off & PAGE_MASK), len));
176
177 if (i == n - 1 && ((off + len) & PAGE_MASK) > 0)
178 return ((off + len) & PAGE_MASK);
179
180 return (PAGE_SIZE);
181 }
182
183 /*
184 * Helper function to get offset within object for i page.
185 */
186 static inline vm_ooffset_t
vmoff(int i,off_t off)187 vmoff(int i, off_t off)
188 {
189
190 if (i == 0)
191 return ((vm_ooffset_t)off);
192
193 return (trunc_page(off + i * PAGE_SIZE));
194 }
195
196 /*
197 * Helper function used when allocation of a page or sf_buf failed.
198 * Pretend as if we don't have enough space, subtract xfsize() of
199 * all pages that failed.
200 */
201 static inline void
fixspace(int old,int new,off_t off,int * space)202 fixspace(int old, int new, off_t off, int *space)
203 {
204
205 KASSERT(old > new, ("%s: old %d new %d", __func__, old, new));
206
207 /* Subtract last one. */
208 *space -= xfsize(old - 1, old, off, *space);
209 old--;
210
211 if (new == old)
212 /* There was only one page. */
213 return;
214
215 /* Subtract first one. */
216 if (new == 0) {
217 *space -= xfsize(0, old, off, *space);
218 new++;
219 }
220
221 /* Rest of pages are full sized. */
222 *space -= (old - new) * PAGE_SIZE;
223
224 KASSERT(*space >= 0, ("%s: space went backwards", __func__));
225 }
226
227 /*
228 * Wait for all in-flight ios to complete, we must not unwire pages
229 * under them.
230 */
231 static void
sendfile_iowait(struct sf_io * sfio,const char * wmesg)232 sendfile_iowait(struct sf_io *sfio, const char *wmesg)
233 {
234 while (atomic_load_int(&sfio->nios) != 1)
235 pause(wmesg, 1);
236 }
237
238 /*
239 * I/O completion callback.
240 *
241 * When called via I/O path, the curvnet is not set and should be obtained
242 * from the socket. When called synchronously from vn_sendfile(), usually
243 * to report error or just release the reference (all pages are valid), then
244 * curvnet shall be already set.
245 */
246 static void
sendfile_iodone(void * arg,vm_page_t * pa,int count,int error)247 sendfile_iodone(void *arg, vm_page_t *pa, int count, int error)
248 {
249 struct sf_io *sfio = arg;
250 struct socket *so;
251 int i;
252
253 if (error != 0)
254 sfio->error = error;
255
256 /*
257 * Restore the valid page pointers. They are already
258 * unbusied, but still wired.
259 *
260 * XXXKIB since pages are only wired, and we do not
261 * own the object lock, other users might have
262 * invalidated them in meantime. Similarly, after we
263 * unbusied the swapped-in pages, they can become
264 * invalid under us.
265 */
266 MPASS(count == 0 || pa[0] != bogus_page);
267 for (i = 0; i < count; i++) {
268 if (pa[i] == bogus_page) {
269 sfio->pa[(pa[0]->pindex - sfio->pindex0) + i] =
270 pa[i] = vm_page_relookup(sfio->obj,
271 pa[0]->pindex + i);
272 KASSERT(pa[i] != NULL,
273 ("%s: page %p[%d] disappeared",
274 __func__, pa, i));
275 } else {
276 vm_page_xunbusy_unchecked(pa[i]);
277 }
278 }
279
280 if (!refcount_release(&sfio->nios))
281 return;
282
283 #ifdef INVARIANTS
284 for (i = 1; i < sfio->npages; i++) {
285 if (sfio->pa[i] == NULL)
286 break;
287 KASSERT(vm_page_wired(sfio->pa[i]),
288 ("sfio %p page %d %p not wired", sfio, i, sfio->pa[i]));
289 if (i == 0)
290 continue;
291 KASSERT(sfio->pa[0]->object == sfio->pa[i]->object,
292 ("sfio %p page %d %p wrong owner %p %p", sfio, i,
293 sfio->pa[i], sfio->pa[0]->object, sfio->pa[i]->object));
294 KASSERT(sfio->pa[0]->pindex + i == sfio->pa[i]->pindex,
295 ("sfio %p page %d %p wrong index %jx %jx", sfio, i,
296 sfio->pa[i], (uintmax_t)sfio->pa[0]->pindex,
297 (uintmax_t)sfio->pa[i]->pindex));
298 }
299 #endif
300
301 vm_object_pip_wakeup(sfio->obj);
302
303 if (sfio->m == NULL) {
304 /*
305 * Either I/O operation failed, or we failed to allocate
306 * buffers, or we bailed out on first busy page, or we
307 * succeeded filling the request without any I/Os. Anyway,
308 * pr_send() hadn't been executed - nothing had been sent
309 * to the socket yet.
310 */
311 MPASS((curthread->td_pflags & TDP_KTHREAD) == 0);
312 free(sfio, M_SENDFILE);
313 return;
314 }
315
316 #if defined(KERN_TLS) && defined(INVARIANTS)
317 if ((sfio->m->m_flags & M_EXTPG) != 0)
318 KASSERT(sfio->tls == sfio->m->m_epg_tls,
319 ("TLS session mismatch"));
320 else
321 KASSERT(sfio->tls == NULL,
322 ("non-ext_pgs mbuf with TLS session"));
323 #endif
324 so = sfio->so;
325 CURVNET_SET_QUIET(so->so_vnet);
326 if (__predict_false(sfio->error)) {
327 /*
328 * I/O operation failed. The state of data in the socket
329 * is now inconsistent, and all what we can do is to tear
330 * it down. Protocol abort method would tear down protocol
331 * state, free all ready mbufs and detach not ready ones.
332 * We will free the mbufs corresponding to this I/O manually.
333 *
334 * The socket would be marked with EIO and made available
335 * for read, so that application receives EIO on next
336 * syscall and eventually closes the socket.
337 */
338 so->so_proto->pr_abort(so);
339 so->so_error = EIO;
340
341 mb_free_notready(sfio->m, sfio->npages);
342 #ifdef KERN_TLS
343 } else if (sfio->tls != NULL && sfio->tls->mode == TCP_TLS_MODE_SW) {
344 /*
345 * I/O operation is complete, but we still need to
346 * encrypt. We cannot do this in the interrupt thread
347 * of the disk controller, so forward the mbufs to a
348 * different thread.
349 *
350 * Donate the socket reference from sfio to rather
351 * than explicitly invoking soref().
352 */
353 ktls_enqueue(sfio->m, so, sfio->npages);
354 goto out_with_ref;
355 #endif
356 } else
357 (void)so->so_proto->pr_ready(so, sfio->m, sfio->npages);
358
359 sorele(so);
360 #ifdef KERN_TLS
361 out_with_ref:
362 #endif
363 CURVNET_RESTORE();
364 free(sfio, M_SENDFILE);
365 }
366
367 /*
368 * Iterate through pages vector and request paging for non-valid pages.
369 */
370 static int
sendfile_swapin(vm_object_t obj,struct sf_io * sfio,int * nios,off_t off,off_t len,int rhpages,int flags)371 sendfile_swapin(vm_object_t obj, struct sf_io *sfio, int *nios, off_t off,
372 off_t len, int rhpages, int flags)
373 {
374 vm_page_t *pa;
375 int a, count, count1, grabbed, i, j, npages, rv;
376
377 pa = sfio->pa;
378 npages = sfio->npages;
379 *nios = 0;
380 flags = (flags & SF_NODISKIO) ? VM_ALLOC_NOWAIT : 0;
381 sfio->pindex0 = OFF_TO_IDX(off);
382
383 /*
384 * First grab all the pages and wire them. Note that we grab
385 * only required pages. Readahead pages are dealt with later.
386 */
387 grabbed = vm_page_grab_pages_unlocked(obj, OFF_TO_IDX(off),
388 VM_ALLOC_NORMAL | VM_ALLOC_WIRED | flags, pa, npages);
389 if (grabbed < npages) {
390 for (int i = grabbed; i < npages; i++)
391 pa[i] = NULL;
392 npages = grabbed;
393 rhpages = 0;
394 }
395
396 for (i = 0; i < npages;) {
397 /* Skip valid pages. */
398 if (vm_page_is_valid(pa[i], vmoff(i, off) & PAGE_MASK,
399 xfsize(i, npages, off, len))) {
400 vm_page_xunbusy(pa[i]);
401 SFSTAT_INC(sf_pages_valid);
402 i++;
403 continue;
404 }
405
406 /*
407 * Next page is invalid. Check if it belongs to pager. It
408 * may not be there, which is a regular situation for shmem
409 * pager. For vnode pager this happens only in case of
410 * a sparse file.
411 *
412 * Important feature of vm_pager_has_page() is the hint
413 * stored in 'a', about how many pages we can pagein after
414 * this page in a single I/O.
415 */
416 VM_OBJECT_RLOCK(obj);
417 if (!vm_pager_has_page(obj, OFF_TO_IDX(vmoff(i, off)), NULL,
418 &a)) {
419 VM_OBJECT_RUNLOCK(obj);
420 pmap_zero_page(pa[i]);
421 vm_page_valid(pa[i]);
422 MPASS(pa[i]->dirty == 0);
423 vm_page_xunbusy(pa[i]);
424 i++;
425 continue;
426 }
427 VM_OBJECT_RUNLOCK(obj);
428
429 /*
430 * We want to pagein as many pages as possible, limited only
431 * by the 'a' hint and actual request.
432 */
433 count = min(a + 1, npages - i);
434
435 /*
436 * We should not pagein into a valid page because
437 * there might be still unfinished write tracked by
438 * e.g. a buffer, thus we substitute any valid pages
439 * with the bogus one.
440 *
441 * We must not leave around xbusy pages which are not
442 * part of the run passed to vm_pager_getpages(),
443 * otherwise pager might deadlock waiting for the busy
444 * status of the page, e.g. if it constitues the
445 * buffer needed to validate other page.
446 *
447 * First trim the end of the run consisting of the
448 * valid pages, then replace the rest of the valid
449 * with bogus.
450 */
451 count1 = count;
452 for (j = i + count - 1; j > i; j--) {
453 if (vm_page_is_valid(pa[j], vmoff(j, off) & PAGE_MASK,
454 xfsize(j, npages, off, len))) {
455 vm_page_xunbusy(pa[j]);
456 SFSTAT_INC(sf_pages_valid);
457 count--;
458 } else {
459 break;
460 }
461 }
462
463 /*
464 * The last page in the run pa[i + count - 1] is
465 * guaranteed to be invalid by the trim above, so it
466 * is not replaced with bogus, thus -1 in the loop end
467 * condition.
468 */
469 MPASS(pa[i + count - 1]->valid != VM_PAGE_BITS_ALL);
470 for (j = i + 1; j < i + count - 1; j++) {
471 if (vm_page_is_valid(pa[j], vmoff(j, off) & PAGE_MASK,
472 xfsize(j, npages, off, len))) {
473 vm_page_xunbusy(pa[j]);
474 SFSTAT_INC(sf_pages_valid);
475 SFSTAT_INC(sf_pages_bogus);
476 pa[j] = bogus_page;
477 }
478 }
479
480 refcount_acquire(&sfio->nios);
481 rv = vm_pager_get_pages_async(obj, pa + i, count, NULL,
482 i + count == npages ? &rhpages : NULL,
483 &sendfile_iodone, sfio);
484 if (__predict_false(rv != VM_PAGER_OK)) {
485 sendfile_iowait(sfio, "sferrio");
486
487 /*
488 * Do remaining pages recovery before returning EIO.
489 * Pages from 0 to npages are wired.
490 * Pages from (i + count1) to npages are busied.
491 */
492 for (j = 0; j < npages; j++) {
493 if (j >= i + count1)
494 vm_page_xunbusy(pa[j]);
495 KASSERT(pa[j] != NULL && pa[j] != bogus_page,
496 ("%s: page %p[%d] I/O recovery failure",
497 __func__, pa, j));
498 vm_page_unwire(pa[j], PQ_INACTIVE);
499 pa[j] = NULL;
500 }
501 return (EIO);
502 }
503
504 SFSTAT_INC(sf_iocnt);
505 SFSTAT_ADD(sf_pages_read, count);
506 if (i + count == npages)
507 SFSTAT_ADD(sf_rhpages_read, rhpages);
508
509 i += count1;
510 (*nios)++;
511 }
512
513 if (*nios == 0 && npages != 0)
514 SFSTAT_INC(sf_noiocnt);
515
516 return (0);
517 }
518
519 static int
sendfile_getobj(struct thread * td,struct file * fp,vm_object_t * obj_res,struct vnode ** vp_res,struct shmfd ** shmfd_res,off_t * obj_size)520 sendfile_getobj(struct thread *td, struct file *fp, vm_object_t *obj_res,
521 struct vnode **vp_res, struct shmfd **shmfd_res, off_t *obj_size)
522 {
523 vm_object_t obj;
524 struct vnode *vp;
525 struct shmfd *shmfd;
526 int error;
527
528 error = 0;
529 vp = *vp_res = NULL;
530 obj = NULL;
531 shmfd = *shmfd_res = NULL;
532
533 /*
534 * The file descriptor must be a regular file and have a
535 * backing VM object.
536 */
537 if (fp->f_type == DTYPE_VNODE) {
538 vp = fp->f_vnode;
539 vn_lock(vp, LK_SHARED | LK_RETRY);
540 if (vp->v_type != VREG) {
541 error = EINVAL;
542 goto out;
543 }
544 obj = vp->v_object;
545 if (obj == NULL) {
546 error = EINVAL;
547 goto out;
548 }
549
550 /*
551 * Use the pager size when available to simplify synchronization
552 * with filesystems, which otherwise must atomically update both
553 * the vnode pager size and file size.
554 */
555 if (obj->type == OBJT_VNODE) {
556 VM_OBJECT_RLOCK(obj);
557 *obj_size = obj->un_pager.vnp.vnp_size;
558 } else {
559 error = vn_getsize_locked(vp, obj_size, td->td_ucred);
560 if (error != 0)
561 goto out;
562 VM_OBJECT_RLOCK(obj);
563 }
564 } else if (fp->f_type == DTYPE_SHM) {
565 shmfd = fp->f_data;
566 obj = shmfd->shm_object;
567 VM_OBJECT_RLOCK(obj);
568 *obj_size = shmfd->shm_size;
569 } else {
570 error = EINVAL;
571 goto out;
572 }
573
574 if ((obj->flags & OBJ_DEAD) != 0) {
575 VM_OBJECT_RUNLOCK(obj);
576 error = EBADF;
577 goto out;
578 }
579
580 /*
581 * Temporarily increase the backing VM object's reference
582 * count so that a forced reclamation of its vnode does not
583 * immediately destroy it.
584 */
585 vm_object_reference_locked(obj);
586 VM_OBJECT_RUNLOCK(obj);
587 *obj_res = obj;
588 *vp_res = vp;
589 *shmfd_res = shmfd;
590
591 out:
592 if (vp != NULL)
593 VOP_UNLOCK(vp);
594 return (error);
595 }
596
597 static int
sendfile_getsock(struct thread * td,int s,struct file ** sock_fp,struct socket ** so)598 sendfile_getsock(struct thread *td, int s, struct file **sock_fp,
599 struct socket **so)
600 {
601 int error;
602
603 *sock_fp = NULL;
604 *so = NULL;
605
606 /*
607 * The socket must be a stream socket and connected.
608 */
609 error = getsock(td, s, &cap_send_rights, sock_fp);
610 if (error != 0)
611 return (error);
612 *so = (*sock_fp)->f_data;
613 if ((*so)->so_type != SOCK_STREAM)
614 return (EINVAL);
615 /*
616 * SCTP one-to-one style sockets currently don't work with
617 * sendfile(). So indicate EINVAL for now.
618 */
619 if ((*so)->so_proto->pr_protocol == IPPROTO_SCTP)
620 return (EINVAL);
621 return (0);
622 }
623
624 /*
625 * Check socket state and wait (or EAGAIN) for needed amount of space.
626 */
627 int
sendfile_wait_generic(struct socket * so,off_t need,int * space)628 sendfile_wait_generic(struct socket *so, off_t need, int *space)
629 {
630 int error;
631
632 MPASS(need > 0);
633 MPASS(space != NULL);
634
635 /*
636 * XXXGL: the hack with sb_lowat originates from d99b0dd2c5297. To
637 * achieve high performance sending with sendfile(2) a non-blocking
638 * socket needs a fairly high low watermark. Otherwise, the socket
639 * will be reported as writable too early, and sendfile(2) will send
640 * just a few bytes each time. It is important to understand that
641 * we are changing sb_lowat not for the current invocation of the
642 * syscall, but for the *next* syscall. So there is no way to
643 * workaround the problem, e.g. provide a special version of sbspace().
644 * Since this hack has been in the kernel for a long time, we
645 * anticipate that there is a lot of software that will suffer if we
646 * remove it. See also b21104487324.
647 */
648 error = 0;
649 SOCK_SENDBUF_LOCK(so);
650 if (so->so_snd.sb_flags & SB_AUTOLOWAT) {
651 if (so->so_snd.sb_lowat < so->so_snd.sb_hiwat / 2)
652 so->so_snd.sb_lowat = so->so_snd.sb_hiwat / 2;
653 if (so->so_snd.sb_lowat < PAGE_SIZE &&
654 so->so_snd.sb_hiwat >= PAGE_SIZE)
655 so->so_snd.sb_lowat = PAGE_SIZE;
656 }
657 retry_space:
658 if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
659 error = EPIPE;
660 goto done;
661 } else if (so->so_error) {
662 error = so->so_error;
663 so->so_error = 0;
664 goto done;
665 }
666 if ((so->so_state & SS_ISCONNECTED) == 0) {
667 error = ENOTCONN;
668 goto done;
669 }
670
671 *space = sbspace(&so->so_snd);
672 if (*space < need && (*space <= 0 || *space < so->so_snd.sb_lowat)) {
673 if (so->so_state & SS_NBIO) {
674 error = EAGAIN;
675 goto done;
676 }
677 /*
678 * sbwait() drops the lock while sleeping. When we loop back
679 * to retry_space the state may have changed and we retest
680 * for it.
681 */
682 error = sbwait(so, SO_SND);
683 /*
684 * An error from sbwait() usually indicates that we've been
685 * interrupted by a signal. If we've sent anything then return
686 * bytes sent, otherwise return the error.
687 */
688 if (error != 0)
689 goto done;
690 goto retry_space;
691 }
692 done:
693 SOCK_SENDBUF_UNLOCK(so);
694
695 return (error);
696 }
697
698 int
vn_sendfile(struct file * fp,int sockfd,struct uio * hdr_uio,struct uio * trl_uio,off_t offset,size_t nbytes,off_t * sent,int flags,struct thread * td)699 vn_sendfile(struct file *fp, int sockfd, struct uio *hdr_uio,
700 struct uio *trl_uio, off_t offset, size_t nbytes, off_t *sent, int flags,
701 struct thread *td)
702 {
703 struct file *sock_fp;
704 struct vnode *vp;
705 struct vm_object *obj;
706 vm_page_t pga;
707 struct socket *so;
708 const struct protosw *pr;
709 #ifdef KERN_TLS
710 struct ktls_session *tls;
711 #endif
712 struct mbuf *m, *mh, *mhtail;
713 struct sf_buf *sf;
714 struct shmfd *shmfd;
715 struct vattr va;
716 off_t off, sbytes, rem, obj_size, nobj_size;
717 int error, ext_pgs_idx, hdrlen, max_pgs, softerr;
718 #ifdef KERN_TLS
719 int tls_enq_cnt;
720 #endif
721 bool use_ext_pgs;
722
723 obj = NULL;
724 so = NULL;
725 m = mh = NULL;
726 #ifdef KERN_TLS
727 tls = NULL;
728 #endif
729 hdrlen = sbytes = 0;
730 softerr = 0;
731 use_ext_pgs = false;
732
733 error = sendfile_getobj(td, fp, &obj, &vp, &shmfd, &obj_size);
734 if (error != 0)
735 goto out;
736
737 error = sendfile_getsock(td, sockfd, &sock_fp, &so);
738 if (error != 0)
739 goto out;
740 pr = so->so_proto;
741
742 #ifdef MAC
743 error = mac_socket_check_send(td->td_ucred, so);
744 if (error != 0)
745 goto out;
746 #endif
747
748 SFSTAT_INC(sf_syscalls);
749 SFSTAT_ADD(sf_rhpages_requested, SF_READAHEAD(flags));
750
751 rem = nbytes ? omin(nbytes, obj_size - offset) : obj_size - offset;
752
753 /*
754 * Protect against multiple writers to the socket.
755 *
756 * XXXRW: Historically this has assumed non-interruptibility, so now
757 * we implement that, but possibly shouldn't.
758 */
759 error = SOCK_IO_SEND_LOCK(so, SBL_WAIT | SBL_NOINTR);
760 if (error != 0)
761 goto out;
762 CURVNET_SET(so->so_vnet);
763 #ifdef KERN_TLS
764 tls = ktls_hold(so->so_snd.sb_tls_info);
765 #endif
766
767 /*
768 * Loop through the pages of the file, starting with the requested
769 * offset. Get a file page (do I/O if necessary), map the file page
770 * into an sf_buf, attach an mbuf header to the sf_buf, and queue
771 * it on the socket.
772 * This is done in two loops. The inner loop turns as many pages
773 * as it can, up to available socket buffer space, without blocking
774 * into mbufs to have it bulk delivered into the socket send buffer.
775 * The outer loop checks the state and available space of the socket
776 * and takes care of the overall progress.
777 */
778 for (off = offset; rem > 0; ) {
779 struct sf_io *sfio;
780 vm_page_t *pa;
781 struct mbuf *m0, *mtail;
782 int nios, space, npages, rhpages;
783
784 mtail = NULL;
785 if ((error = pr->pr_sendfile_wait(so, rem, &space)) != 0)
786 goto done;
787 /*
788 * At the beginning of the first loop check if any headers
789 * are specified and copy them into mbufs. Reduce space in
790 * the socket buffer by the size of the header mbuf chain.
791 * Clear hdr_uio here and hdrlen at the end of the first loop.
792 */
793 if (hdr_uio != NULL && hdr_uio->uio_resid > 0) {
794 hdr_uio->uio_td = td;
795 hdr_uio->uio_rw = UIO_WRITE;
796 #ifdef KERN_TLS
797 if (tls != NULL)
798 mh = m_uiotombuf(hdr_uio, M_WAITOK, space,
799 tls->params.max_frame_len, M_EXTPG);
800 else
801 #endif
802 mh = m_uiotombuf(hdr_uio, M_WAITOK,
803 space, 0, 0);
804 hdrlen = m_length(mh, &mhtail);
805 space -= hdrlen;
806 /*
807 * If header consumed all the socket buffer space,
808 * don't waste CPU cycles and jump to the end.
809 */
810 if (space == 0) {
811 sfio = NULL;
812 nios = 0;
813 goto prepend_header;
814 }
815 hdr_uio = NULL;
816 }
817
818 if (vp != NULL) {
819 error = vn_lock(vp, LK_SHARED);
820 if (error != 0)
821 goto done;
822
823 /*
824 * Check to see if the file size has changed.
825 */
826 if (obj->type == OBJT_VNODE) {
827 VM_OBJECT_RLOCK(obj);
828 nobj_size = obj->un_pager.vnp.vnp_size;
829 VM_OBJECT_RUNLOCK(obj);
830 } else {
831 error = VOP_GETATTR(vp, &va, td->td_ucred);
832 if (error != 0) {
833 VOP_UNLOCK(vp);
834 goto done;
835 }
836 nobj_size = va.va_size;
837 }
838 if (off >= nobj_size) {
839 VOP_UNLOCK(vp);
840 goto done;
841 }
842 if (nobj_size != obj_size) {
843 obj_size = nobj_size;
844 rem = nbytes ? omin(nbytes + offset, obj_size) :
845 obj_size;
846 rem -= off;
847 }
848 }
849
850 if (space > rem)
851 space = rem;
852 else if (space > PAGE_SIZE) {
853 /*
854 * Use page boundaries when possible for large
855 * requests.
856 */
857 if (off & PAGE_MASK)
858 space -= (PAGE_SIZE - (off & PAGE_MASK));
859 space = trunc_page(space);
860 if (off & PAGE_MASK)
861 space += (PAGE_SIZE - (off & PAGE_MASK));
862 }
863
864 npages = howmany(space + (off & PAGE_MASK), PAGE_SIZE);
865
866 /*
867 * Calculate maximum allowed number of pages for readahead
868 * at this iteration. If SF_USER_READAHEAD was set, we don't
869 * do any heuristics and use exactly the value supplied by
870 * application. Otherwise, we allow readahead up to "rem".
871 * If application wants more, let it be, but there is no
872 * reason to go above maxphys. Also check against "obj_size",
873 * since vm_pager_has_page() can hint beyond EOF.
874 */
875 if (flags & SF_USER_READAHEAD) {
876 rhpages = SF_READAHEAD(flags);
877 } else {
878 rhpages = howmany(rem + (off & PAGE_MASK), PAGE_SIZE) -
879 npages;
880 rhpages += SF_READAHEAD(flags);
881 }
882 rhpages = min(howmany(maxphys, PAGE_SIZE), rhpages);
883 rhpages = min(howmany(obj_size - trunc_page(off), PAGE_SIZE) -
884 npages, rhpages);
885
886 sfio = malloc(sizeof(struct sf_io) +
887 npages * sizeof(vm_page_t), M_SENDFILE, M_WAITOK);
888 refcount_init(&sfio->nios, 1);
889 sfio->obj = obj;
890 sfio->error = 0;
891 sfio->m = NULL;
892 sfio->npages = npages;
893 #ifdef KERN_TLS
894 /*
895 * This doesn't use ktls_hold() because sfio->m will
896 * also have a reference on 'tls' that will be valid
897 * for all of sfio's lifetime.
898 */
899 sfio->tls = tls;
900 #endif
901 vm_object_pip_add(obj, 1);
902 error = sendfile_swapin(obj, sfio, &nios, off, space, rhpages,
903 flags);
904 if (error != 0) {
905 if (vp != NULL)
906 VOP_UNLOCK(vp);
907 sendfile_iodone(sfio, NULL, 0, error);
908 goto done;
909 }
910
911 /*
912 * Loop and construct maximum sized mbuf chain to be bulk
913 * dumped into socket buffer.
914 */
915 pa = sfio->pa;
916
917 /*
918 * Use unmapped mbufs if enabled for TCP. Unmapped
919 * bufs are restricted to TCP as that is what has been
920 * tested. In particular, unmapped mbufs have not
921 * been tested with UNIX-domain sockets.
922 *
923 * TLS frames always require unmapped mbufs.
924 */
925 if ((mb_use_ext_pgs && pr->pr_protocol == IPPROTO_TCP)
926 #ifdef KERN_TLS
927 || tls != NULL
928 #endif
929 ) {
930 use_ext_pgs = true;
931 #ifdef KERN_TLS
932 if (tls != NULL)
933 max_pgs = num_pages(tls->params.max_frame_len);
934 else
935 #endif
936 max_pgs = MBUF_PEXT_MAX_PGS;
937
938 /* Start at last index, to wrap on first use. */
939 ext_pgs_idx = max_pgs - 1;
940 }
941
942 for (int i = 0; i < npages; i++) {
943 /*
944 * If a page wasn't grabbed successfully, then
945 * trim the array. Can happen only with SF_NODISKIO.
946 */
947 if (pa[i] == NULL) {
948 SFSTAT_INC(sf_busy);
949 fixspace(npages, i, off, &space);
950 sfio->npages = i;
951 softerr = EBUSY;
952 break;
953 }
954 pga = pa[i];
955 if (pga == bogus_page)
956 pga = vm_page_relookup(obj, sfio->pindex0 + i);
957
958 if (use_ext_pgs) {
959 off_t xfs;
960
961 ext_pgs_idx++;
962 if (ext_pgs_idx == max_pgs) {
963 m0 = mb_alloc_ext_pgs(M_WAITOK,
964 sendfile_free_mext_pg, M_RDONLY);
965
966 if (flags & SF_NOCACHE) {
967 m0->m_ext.ext_flags |=
968 EXT_FLAG_NOCACHE;
969
970 /*
971 * See comment below regarding
972 * ignoring SF_NOCACHE for the
973 * last page.
974 */
975 if ((npages - i <= max_pgs) &&
976 ((off + space) & PAGE_MASK) &&
977 (rem > space || rhpages > 0))
978 m0->m_ext.ext_flags |=
979 EXT_FLAG_CACHE_LAST;
980 }
981 ext_pgs_idx = 0;
982
983 /* Append to mbuf chain. */
984 if (mtail != NULL)
985 mtail->m_next = m0;
986 else
987 m = m0;
988 mtail = m0;
989 m0->m_epg_1st_off =
990 vmoff(i, off) & PAGE_MASK;
991 }
992 if (nios) {
993 mtail->m_flags |= M_NOTREADY;
994 m0->m_epg_nrdy++;
995 }
996
997 m0->m_epg_pa[ext_pgs_idx] = VM_PAGE_TO_PHYS(pga);
998 m0->m_epg_npgs++;
999 xfs = xfsize(i, npages, off, space);
1000 m0->m_epg_last_len = xfs;
1001 MBUF_EXT_PGS_ASSERT_SANITY(m0);
1002 mtail->m_len += xfs;
1003 mtail->m_ext.ext_size += PAGE_SIZE;
1004 continue;
1005 }
1006
1007 /*
1008 * Get a sendfile buf. When allocating the
1009 * first buffer for mbuf chain, we usually
1010 * wait as long as necessary, but this wait
1011 * can be interrupted. For consequent
1012 * buffers, do not sleep, since several
1013 * threads might exhaust the buffers and then
1014 * deadlock.
1015 */
1016 sf = sf_buf_alloc(pga,
1017 m != NULL ? SFB_NOWAIT : SFB_CATCH);
1018 if (sf == NULL) {
1019 SFSTAT_INC(sf_allocfail);
1020 sendfile_iowait(sfio, "sfnosf");
1021 for (int j = i; j < npages; j++) {
1022 vm_page_unwire(pa[j], PQ_INACTIVE);
1023 pa[j] = NULL;
1024 }
1025 if (m == NULL)
1026 softerr = ENOBUFS;
1027 fixspace(npages, i, off, &space);
1028 sfio->npages = i;
1029 break;
1030 }
1031
1032 m0 = m_get(M_WAITOK, MT_DATA);
1033 m0->m_ext.ext_buf = (char *)sf_buf_kva(sf);
1034 m0->m_ext.ext_size = PAGE_SIZE;
1035 m0->m_ext.ext_arg1 = sf;
1036 m0->m_ext.ext_type = EXT_SFBUF;
1037 m0->m_ext.ext_flags = EXT_FLAG_EMBREF;
1038 m0->m_ext.ext_free = sendfile_free_mext;
1039 /*
1040 * SF_NOCACHE sets the page as being freed upon send.
1041 * However, we ignore it for the last page in 'space',
1042 * if the page is truncated, and we got more data to
1043 * send (rem > space), or if we have readahead
1044 * configured (rhpages > 0).
1045 */
1046 if ((flags & SF_NOCACHE) &&
1047 (i != npages - 1 ||
1048 !((off + space) & PAGE_MASK) ||
1049 !(rem > space || rhpages > 0)))
1050 m0->m_ext.ext_flags |= EXT_FLAG_NOCACHE;
1051 m0->m_ext.ext_count = 1;
1052 m0->m_flags |= (M_EXT | M_RDONLY);
1053 if (nios)
1054 m0->m_flags |= M_NOTREADY;
1055 m0->m_data = (char *)sf_buf_kva(sf) +
1056 (vmoff(i, off) & PAGE_MASK);
1057 m0->m_len = xfsize(i, npages, off, space);
1058
1059 /* Append to mbuf chain. */
1060 if (mtail != NULL)
1061 mtail->m_next = m0;
1062 else
1063 m = m0;
1064 mtail = m0;
1065 }
1066
1067 if (vp != NULL)
1068 VOP_UNLOCK(vp);
1069
1070 /* Keep track of bytes processed. */
1071 off += space;
1072 rem -= space;
1073
1074 /*
1075 * Prepend header, if any. Save pointer to first mbuf
1076 * with a page.
1077 */
1078 if (hdrlen) {
1079 prepend_header:
1080 m0 = mhtail->m_next = m;
1081 m = mh;
1082 mh = NULL;
1083 } else
1084 m0 = m;
1085
1086 if (m == NULL) {
1087 KASSERT(softerr, ("%s: m NULL, no error", __func__));
1088 error = softerr;
1089 sendfile_iodone(sfio, NULL, 0, 0);
1090 goto done;
1091 }
1092
1093 /* Add the buffer chain to the socket buffer. */
1094 KASSERT(m_length(m, NULL) == space + hdrlen,
1095 ("%s: mlen %u space %d hdrlen %d",
1096 __func__, m_length(m, NULL), space, hdrlen));
1097
1098 #ifdef KERN_TLS
1099 if (tls != NULL)
1100 ktls_frame(m, tls, &tls_enq_cnt, TLS_RLTYPE_APP);
1101 #endif
1102 if (nios == 0) {
1103 /*
1104 * If sendfile_swapin() didn't initiate any I/Os,
1105 * which happens if all data is cached in VM, or if
1106 * the header consumed all socket buffer space and
1107 * sfio is NULL, then we can send data right now
1108 * without the PRUS_NOTREADY flag.
1109 */
1110 if (sfio != NULL)
1111 sendfile_iodone(sfio, NULL, 0, 0);
1112 #ifdef KERN_TLS
1113 if (tls != NULL && tls->mode == TCP_TLS_MODE_SW) {
1114 error = pr->pr_send(so, PRUS_NOTREADY, m, NULL,
1115 NULL, td);
1116 if (error != 0) {
1117 m_freem(m);
1118 } else {
1119 soref(so);
1120 ktls_enqueue(m, so, tls_enq_cnt);
1121 }
1122 } else
1123 #endif
1124 error = pr->pr_send(so, 0, m, NULL, NULL, td);
1125 } else {
1126 sfio->so = so;
1127 sfio->m = m0;
1128 soref(so);
1129 error = pr->pr_send(so, PRUS_NOTREADY, m, NULL, NULL,
1130 td);
1131 sendfile_iodone(sfio, NULL, 0, error);
1132 }
1133 #ifdef TCP_REQUEST_TRK
1134 if (so->so_proto->pr_protocol == IPPROTO_TCP) {
1135 /* log the sendfile call to the TCP log, if enabled */
1136 tcp_log_sendfile(so, offset, nbytes, flags);
1137 }
1138 #endif
1139 m = NULL;
1140 if (error)
1141 goto done;
1142 sbytes += space + hdrlen;
1143 if (hdrlen)
1144 hdrlen = 0;
1145 if (softerr) {
1146 error = softerr;
1147 goto done;
1148 }
1149 }
1150
1151 /*
1152 * Send trailers. Wimp out and use writev(2).
1153 */
1154 if (trl_uio != NULL) {
1155 SOCK_IO_SEND_UNLOCK(so);
1156 CURVNET_RESTORE();
1157 error = kern_writev(td, sockfd, trl_uio);
1158 if (error == 0)
1159 sbytes += td->td_retval[0];
1160 goto out;
1161 }
1162
1163 done:
1164 SOCK_IO_SEND_UNLOCK(so);
1165 CURVNET_RESTORE();
1166 out:
1167 /*
1168 * If there was no error we have to clear td->td_retval[0]
1169 * because it may have been set by writev.
1170 */
1171 if (error == 0) {
1172 td->td_retval[0] = 0;
1173 if (sbytes > 0 && vp != NULL)
1174 INOTIFY(vp, IN_ACCESS);
1175 }
1176 if (sent != NULL) {
1177 (*sent) = sbytes;
1178 }
1179 if (obj != NULL)
1180 vm_object_deallocate(obj);
1181 if (so)
1182 fdrop(sock_fp, td);
1183 if (m)
1184 m_freem(m);
1185 if (mh)
1186 m_freem(mh);
1187 #ifdef KERN_TLS
1188 if (tls != NULL)
1189 ktls_free(tls);
1190 #endif
1191 if (error == ERESTART)
1192 error = EINTR;
1193
1194 return (error);
1195 }
1196
1197 static int
sendfile(struct thread * td,struct sendfile_args * uap,int compat)1198 sendfile(struct thread *td, struct sendfile_args *uap, int compat)
1199 {
1200 struct sf_hdtr hdtr;
1201 struct uio *hdr_uio, *trl_uio;
1202 struct file *fp;
1203 off_t sbytes;
1204 int error;
1205
1206 /*
1207 * File offset must be positive. If it goes beyond EOF
1208 * we send only the header/trailer and no payload data.
1209 */
1210 if (uap->offset < 0)
1211 return (EINVAL);
1212
1213 sbytes = 0;
1214 hdr_uio = trl_uio = NULL;
1215
1216 if (uap->hdtr != NULL) {
1217 error = copyin(uap->hdtr, &hdtr, sizeof(hdtr));
1218 if (error != 0)
1219 goto out;
1220 if (hdtr.headers != NULL) {
1221 error = copyinuio(hdtr.headers, hdtr.hdr_cnt,
1222 &hdr_uio);
1223 if (error != 0)
1224 goto out;
1225 #ifdef COMPAT_FREEBSD4
1226 /*
1227 * In FreeBSD < 5.0 the nbytes to send also included
1228 * the header. If compat is specified subtract the
1229 * header size from nbytes.
1230 */
1231 if (compat) {
1232 if (uap->nbytes > hdr_uio->uio_resid)
1233 uap->nbytes -= hdr_uio->uio_resid;
1234 else
1235 uap->nbytes = 0;
1236 }
1237 #endif
1238 }
1239 if (hdtr.trailers != NULL) {
1240 error = copyinuio(hdtr.trailers, hdtr.trl_cnt,
1241 &trl_uio);
1242 if (error != 0)
1243 goto out;
1244 }
1245 }
1246
1247 AUDIT_ARG_FD(uap->fd);
1248
1249 /*
1250 * sendfile(2) can start at any offset within a file so we require
1251 * CAP_READ+CAP_SEEK = CAP_PREAD.
1252 */
1253 if ((error = fget_read(td, uap->fd, &cap_pread_rights, &fp)) != 0)
1254 goto out;
1255
1256 error = fo_sendfile(fp, uap->s, hdr_uio, trl_uio, uap->offset,
1257 uap->nbytes, &sbytes, uap->flags, td);
1258 fdrop(fp, td);
1259
1260 if (uap->sbytes != NULL)
1261 (void)copyout(&sbytes, uap->sbytes, sizeof(off_t));
1262
1263 out:
1264 freeuio(hdr_uio);
1265 freeuio(trl_uio);
1266 return (error);
1267 }
1268
1269 /*
1270 * sendfile(2)
1271 *
1272 * int sendfile(int fd, int s, off_t offset, size_t nbytes,
1273 * struct sf_hdtr *hdtr, off_t *sbytes, int flags)
1274 *
1275 * Send a file specified by 'fd' and starting at 'offset' to a socket
1276 * specified by 's'. Send only 'nbytes' of the file or until EOF if nbytes ==
1277 * 0. Optionally add a header and/or trailer to the socket output. If
1278 * specified, write the total number of bytes sent into *sbytes.
1279 */
1280 int
sys_sendfile(struct thread * td,struct sendfile_args * uap)1281 sys_sendfile(struct thread *td, struct sendfile_args *uap)
1282 {
1283
1284 return (sendfile(td, uap, 0));
1285 }
1286
1287 #ifdef COMPAT_FREEBSD4
1288 int
freebsd4_sendfile(struct thread * td,struct freebsd4_sendfile_args * uap)1289 freebsd4_sendfile(struct thread *td, struct freebsd4_sendfile_args *uap)
1290 {
1291 struct sendfile_args args;
1292
1293 args.fd = uap->fd;
1294 args.s = uap->s;
1295 args.offset = uap->offset;
1296 args.nbytes = uap->nbytes;
1297 args.hdtr = uap->hdtr;
1298 args.sbytes = uap->sbytes;
1299 args.flags = uap->flags;
1300
1301 return (sendfile(td, &args, 1));
1302 }
1303 #endif /* COMPAT_FREEBSD4 */
1304