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