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