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