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