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