Merge remote-tracking branch 'linus/master' into testing
[cascardo/linux.git] / fs / ceph / addr.c
1 #include <linux/ceph/ceph_debug.h>
2
3 #include <linux/backing-dev.h>
4 #include <linux/fs.h>
5 #include <linux/mm.h>
6 #include <linux/pagemap.h>
7 #include <linux/writeback.h>    /* generic_writepages */
8 #include <linux/slab.h>
9 #include <linux/pagevec.h>
10 #include <linux/task_io_accounting_ops.h>
11
12 #include "super.h"
13 #include "mds_client.h"
14 #include <linux/ceph/osd_client.h>
15
16 /*
17  * Ceph address space ops.
18  *
19  * There are a few funny things going on here.
20  *
21  * The page->private field is used to reference a struct
22  * ceph_snap_context for _every_ dirty page.  This indicates which
23  * snapshot the page was logically dirtied in, and thus which snap
24  * context needs to be associated with the osd write during writeback.
25  *
26  * Similarly, struct ceph_inode_info maintains a set of counters to
27  * count dirty pages on the inode.  In the absence of snapshots,
28  * i_wrbuffer_ref == i_wrbuffer_ref_head == the dirty page count.
29  *
30  * When a snapshot is taken (that is, when the client receives
31  * notification that a snapshot was taken), each inode with caps and
32  * with dirty pages (dirty pages implies there is a cap) gets a new
33  * ceph_cap_snap in the i_cap_snaps list (which is sorted in ascending
34  * order, new snaps go to the tail).  The i_wrbuffer_ref_head count is
35  * moved to capsnap->dirty. (Unless a sync write is currently in
36  * progress.  In that case, the capsnap is said to be "pending", new
37  * writes cannot start, and the capsnap isn't "finalized" until the
38  * write completes (or fails) and a final size/mtime for the inode for
39  * that snap can be settled upon.)  i_wrbuffer_ref_head is reset to 0.
40  *
41  * On writeback, we must submit writes to the osd IN SNAP ORDER.  So,
42  * we look for the first capsnap in i_cap_snaps and write out pages in
43  * that snap context _only_.  Then we move on to the next capsnap,
44  * eventually reaching the "live" or "head" context (i.e., pages that
45  * are not yet snapped) and are writing the most recently dirtied
46  * pages.
47  *
48  * Invalidate and so forth must take care to ensure the dirty page
49  * accounting is preserved.
50  */
51
52 #define CONGESTION_ON_THRESH(congestion_kb) (congestion_kb >> (PAGE_SHIFT-10))
53 #define CONGESTION_OFF_THRESH(congestion_kb)                            \
54         (CONGESTION_ON_THRESH(congestion_kb) -                          \
55          (CONGESTION_ON_THRESH(congestion_kb) >> 2))
56
57 static inline struct ceph_snap_context *page_snap_context(struct page *page)
58 {
59         if (PagePrivate(page))
60                 return (void *)page->private;
61         return NULL;
62 }
63
64 /*
65  * Dirty a page.  Optimistically adjust accounting, on the assumption
66  * that we won't race with invalidate.  If we do, readjust.
67  */
68 static int ceph_set_page_dirty(struct page *page)
69 {
70         struct address_space *mapping = page->mapping;
71         struct inode *inode;
72         struct ceph_inode_info *ci;
73         int undo = 0;
74         struct ceph_snap_context *snapc;
75
76         if (unlikely(!mapping))
77                 return !TestSetPageDirty(page);
78
79         if (TestSetPageDirty(page)) {
80                 dout("%p set_page_dirty %p idx %lu -- already dirty\n",
81                      mapping->host, page, page->index);
82                 return 0;
83         }
84
85         inode = mapping->host;
86         ci = ceph_inode(inode);
87
88         /*
89          * Note that we're grabbing a snapc ref here without holding
90          * any locks!
91          */
92         snapc = ceph_get_snap_context(ci->i_snap_realm->cached_context);
93
94         /* dirty the head */
95         spin_lock(&ci->i_ceph_lock);
96         if (ci->i_head_snapc == NULL)
97                 ci->i_head_snapc = ceph_get_snap_context(snapc);
98         ++ci->i_wrbuffer_ref_head;
99         if (ci->i_wrbuffer_ref == 0)
100                 ihold(inode);
101         ++ci->i_wrbuffer_ref;
102         dout("%p set_page_dirty %p idx %lu head %d/%d -> %d/%d "
103              "snapc %p seq %lld (%d snaps)\n",
104              mapping->host, page, page->index,
105              ci->i_wrbuffer_ref-1, ci->i_wrbuffer_ref_head-1,
106              ci->i_wrbuffer_ref, ci->i_wrbuffer_ref_head,
107              snapc, snapc->seq, snapc->num_snaps);
108         spin_unlock(&ci->i_ceph_lock);
109
110         /* now adjust page */
111         spin_lock_irq(&mapping->tree_lock);
112         if (page->mapping) {    /* Race with truncate? */
113                 WARN_ON_ONCE(!PageUptodate(page));
114                 account_page_dirtied(page, page->mapping);
115                 radix_tree_tag_set(&mapping->page_tree,
116                                 page_index(page), PAGECACHE_TAG_DIRTY);
117
118                 /*
119                  * Reference snap context in page->private.  Also set
120                  * PagePrivate so that we get invalidatepage callback.
121                  */
122                 page->private = (unsigned long)snapc;
123                 SetPagePrivate(page);
124         } else {
125                 dout("ANON set_page_dirty %p (raced truncate?)\n", page);
126                 undo = 1;
127         }
128
129         spin_unlock_irq(&mapping->tree_lock);
130
131         if (undo)
132                 /* whoops, we failed to dirty the page */
133                 ceph_put_wrbuffer_cap_refs(ci, 1, snapc);
134
135         __mark_inode_dirty(mapping->host, I_DIRTY_PAGES);
136
137         BUG_ON(!PageDirty(page));
138         return 1;
139 }
140
141 /*
142  * If we are truncating the full page (i.e. offset == 0), adjust the
143  * dirty page counters appropriately.  Only called if there is private
144  * data on the page.
145  */
146 static void ceph_invalidatepage(struct page *page, unsigned int offset,
147                                 unsigned int length)
148 {
149         struct inode *inode;
150         struct ceph_inode_info *ci;
151         struct ceph_snap_context *snapc = page_snap_context(page);
152
153         inode = page->mapping->host;
154
155         /*
156          * We can get non-dirty pages here due to races between
157          * set_page_dirty and truncate_complete_page; just spit out a
158          * warning, in case we end up with accounting problems later.
159          */
160         if (!PageDirty(page))
161                 pr_err("%p invalidatepage %p page not dirty\n", inode, page);
162
163         if (offset == 0 && length == PAGE_CACHE_SIZE)
164                 ClearPageChecked(page);
165
166         ci = ceph_inode(inode);
167         if (offset == 0 && length == PAGE_CACHE_SIZE) {
168                 dout("%p invalidatepage %p idx %lu full dirty page\n",
169                      inode, page, page->index);
170                 ceph_put_wrbuffer_cap_refs(ci, 1, snapc);
171                 ceph_put_snap_context(snapc);
172                 page->private = 0;
173                 ClearPagePrivate(page);
174         } else {
175                 dout("%p invalidatepage %p idx %lu partial dirty page %u(%u)\n",
176                      inode, page, page->index, offset, length);
177         }
178 }
179
180 /* just a sanity check */
181 static int ceph_releasepage(struct page *page, gfp_t g)
182 {
183         struct inode *inode = page->mapping ? page->mapping->host : NULL;
184         dout("%p releasepage %p idx %lu\n", inode, page, page->index);
185         WARN_ON(PageDirty(page));
186         WARN_ON(PagePrivate(page));
187         return 0;
188 }
189
190 /*
191  * read a single page, without unlocking it.
192  */
193 static int readpage_nounlock(struct file *filp, struct page *page)
194 {
195         struct inode *inode = file_inode(filp);
196         struct ceph_inode_info *ci = ceph_inode(inode);
197         struct ceph_osd_client *osdc = 
198                 &ceph_inode_to_client(inode)->client->osdc;
199         int err = 0;
200         u64 len = PAGE_CACHE_SIZE;
201
202         dout("readpage inode %p file %p page %p index %lu\n",
203              inode, filp, page, page->index);
204         err = ceph_osdc_readpages(osdc, ceph_vino(inode), &ci->i_layout,
205                                   (u64) page_offset(page), &len,
206                                   ci->i_truncate_seq, ci->i_truncate_size,
207                                   &page, 1, 0);
208         if (err == -ENOENT)
209                 err = 0;
210         if (err < 0) {
211                 SetPageError(page);
212                 goto out;
213         } else if (err < PAGE_CACHE_SIZE) {
214                 /* zero fill remainder of page */
215                 zero_user_segment(page, err, PAGE_CACHE_SIZE);
216         }
217         SetPageUptodate(page);
218
219 out:
220         return err < 0 ? err : 0;
221 }
222
223 static int ceph_readpage(struct file *filp, struct page *page)
224 {
225         int r = readpage_nounlock(filp, page);
226         unlock_page(page);
227         return r;
228 }
229
230 /*
231  * Finish an async read(ahead) op.
232  */
233 static void finish_read(struct ceph_osd_request *req, struct ceph_msg *msg)
234 {
235         struct inode *inode = req->r_inode;
236         struct ceph_osd_data *osd_data;
237         int rc = req->r_result;
238         int bytes = le32_to_cpu(msg->hdr.data_len);
239         int num_pages;
240         int i;
241
242         dout("finish_read %p req %p rc %d bytes %d\n", inode, req, rc, bytes);
243
244         /* unlock all pages, zeroing any data we didn't read */
245         osd_data = osd_req_op_extent_osd_data(req, 0);
246         BUG_ON(osd_data->type != CEPH_OSD_DATA_TYPE_PAGES);
247         num_pages = calc_pages_for((u64)osd_data->alignment,
248                                         (u64)osd_data->length);
249         for (i = 0; i < num_pages; i++) {
250                 struct page *page = osd_data->pages[i];
251
252                 if (bytes < (int)PAGE_CACHE_SIZE) {
253                         /* zero (remainder of) page */
254                         int s = bytes < 0 ? 0 : bytes;
255                         zero_user_segment(page, s, PAGE_CACHE_SIZE);
256                 }
257                 dout("finish_read %p uptodate %p idx %lu\n", inode, page,
258                      page->index);
259                 flush_dcache_page(page);
260                 SetPageUptodate(page);
261                 unlock_page(page);
262                 page_cache_release(page);
263                 bytes -= PAGE_CACHE_SIZE;
264         }
265         kfree(osd_data->pages);
266 }
267
268 static void ceph_unlock_page_vector(struct page **pages, int num_pages)
269 {
270         int i;
271
272         for (i = 0; i < num_pages; i++)
273                 unlock_page(pages[i]);
274 }
275
276 /*
277  * start an async read(ahead) operation.  return nr_pages we submitted
278  * a read for on success, or negative error code.
279  */
280 static int start_read(struct inode *inode, struct list_head *page_list, int max)
281 {
282         struct ceph_osd_client *osdc =
283                 &ceph_inode_to_client(inode)->client->osdc;
284         struct ceph_inode_info *ci = ceph_inode(inode);
285         struct page *page = list_entry(page_list->prev, struct page, lru);
286         struct ceph_vino vino;
287         struct ceph_osd_request *req;
288         u64 off;
289         u64 len;
290         int i;
291         struct page **pages;
292         pgoff_t next_index;
293         int nr_pages = 0;
294         int ret;
295
296         off = (u64) page_offset(page);
297
298         /* count pages */
299         next_index = page->index;
300         list_for_each_entry_reverse(page, page_list, lru) {
301                 if (page->index != next_index)
302                         break;
303                 nr_pages++;
304                 next_index++;
305                 if (max && nr_pages == max)
306                         break;
307         }
308         len = nr_pages << PAGE_CACHE_SHIFT;
309         dout("start_read %p nr_pages %d is %lld~%lld\n", inode, nr_pages,
310              off, len);
311         vino = ceph_vino(inode);
312         req = ceph_osdc_new_request(osdc, &ci->i_layout, vino, off, &len,
313                                     1, CEPH_OSD_OP_READ,
314                                     CEPH_OSD_FLAG_READ, NULL,
315                                     ci->i_truncate_seq, ci->i_truncate_size,
316                                     false);
317         if (IS_ERR(req))
318                 return PTR_ERR(req);
319
320         /* build page vector */
321         nr_pages = calc_pages_for(0, len);
322         pages = kmalloc(sizeof(*pages) * nr_pages, GFP_NOFS);
323         ret = -ENOMEM;
324         if (!pages)
325                 goto out;
326         for (i = 0; i < nr_pages; ++i) {
327                 page = list_entry(page_list->prev, struct page, lru);
328                 BUG_ON(PageLocked(page));
329                 list_del(&page->lru);
330                 
331                 dout("start_read %p adding %p idx %lu\n", inode, page,
332                      page->index);
333                 if (add_to_page_cache_lru(page, &inode->i_data, page->index,
334                                           GFP_NOFS)) {
335                         page_cache_release(page);
336                         dout("start_read %p add_to_page_cache failed %p\n",
337                              inode, page);
338                         nr_pages = i;
339                         goto out_pages;
340                 }
341                 pages[i] = page;
342         }
343         osd_req_op_extent_osd_data_pages(req, 0, pages, len, 0, false, false);
344         req->r_callback = finish_read;
345         req->r_inode = inode;
346
347         ceph_osdc_build_request(req, off, NULL, vino.snap, NULL);
348
349         dout("start_read %p starting %p %lld~%lld\n", inode, req, off, len);
350         ret = ceph_osdc_start_request(osdc, req, false);
351         if (ret < 0)
352                 goto out_pages;
353         ceph_osdc_put_request(req);
354         return nr_pages;
355
356 out_pages:
357         ceph_unlock_page_vector(pages, nr_pages);
358         ceph_release_page_vector(pages, nr_pages);
359 out:
360         ceph_osdc_put_request(req);
361         return ret;
362 }
363
364
365 /*
366  * Read multiple pages.  Leave pages we don't read + unlock in page_list;
367  * the caller (VM) cleans them up.
368  */
369 static int ceph_readpages(struct file *file, struct address_space *mapping,
370                           struct list_head *page_list, unsigned nr_pages)
371 {
372         struct inode *inode = file_inode(file);
373         struct ceph_fs_client *fsc = ceph_inode_to_client(inode);
374         int rc = 0;
375         int max = 0;
376
377         if (fsc->mount_options->rsize >= PAGE_CACHE_SIZE)
378                 max = (fsc->mount_options->rsize + PAGE_CACHE_SIZE - 1)
379                         >> PAGE_SHIFT;
380
381         dout("readpages %p file %p nr_pages %d max %d\n", inode,
382                 file, nr_pages,
383              max);
384         while (!list_empty(page_list)) {
385                 rc = start_read(inode, page_list, max);
386                 if (rc < 0)
387                         goto out;
388                 BUG_ON(rc == 0);
389         }
390 out:
391         dout("readpages %p file %p ret %d\n", inode, file, rc);
392         return rc;
393 }
394
395 /*
396  * Get ref for the oldest snapc for an inode with dirty data... that is, the
397  * only snap context we are allowed to write back.
398  */
399 static struct ceph_snap_context *get_oldest_context(struct inode *inode,
400                                                     u64 *snap_size)
401 {
402         struct ceph_inode_info *ci = ceph_inode(inode);
403         struct ceph_snap_context *snapc = NULL;
404         struct ceph_cap_snap *capsnap = NULL;
405
406         spin_lock(&ci->i_ceph_lock);
407         list_for_each_entry(capsnap, &ci->i_cap_snaps, ci_item) {
408                 dout(" cap_snap %p snapc %p has %d dirty pages\n", capsnap,
409                      capsnap->context, capsnap->dirty_pages);
410                 if (capsnap->dirty_pages) {
411                         snapc = ceph_get_snap_context(capsnap->context);
412                         if (snap_size)
413                                 *snap_size = capsnap->size;
414                         break;
415                 }
416         }
417         if (!snapc && ci->i_wrbuffer_ref_head) {
418                 snapc = ceph_get_snap_context(ci->i_head_snapc);
419                 dout(" head snapc %p has %d dirty pages\n",
420                      snapc, ci->i_wrbuffer_ref_head);
421         }
422         spin_unlock(&ci->i_ceph_lock);
423         return snapc;
424 }
425
426 /*
427  * Write a single page, but leave the page locked.
428  *
429  * If we get a write error, set the page error bit, but still adjust the
430  * dirty page accounting (i.e., page is no longer dirty).
431  */
432 static int writepage_nounlock(struct page *page, struct writeback_control *wbc)
433 {
434         struct inode *inode;
435         struct ceph_inode_info *ci;
436         struct ceph_fs_client *fsc;
437         struct ceph_osd_client *osdc;
438         struct ceph_snap_context *snapc, *oldest;
439         loff_t page_off = page_offset(page);
440         long writeback_stat;
441         u64 truncate_size, snap_size = 0;
442         u32 truncate_seq;
443         int err = 0, len = PAGE_CACHE_SIZE;
444
445         dout("writepage %p idx %lu\n", page, page->index);
446
447         if (!page->mapping || !page->mapping->host) {
448                 dout("writepage %p - no mapping\n", page);
449                 return -EFAULT;
450         }
451         inode = page->mapping->host;
452         ci = ceph_inode(inode);
453         fsc = ceph_inode_to_client(inode);
454         osdc = &fsc->client->osdc;
455
456         /* verify this is a writeable snap context */
457         snapc = page_snap_context(page);
458         if (snapc == NULL) {
459                 dout("writepage %p page %p not dirty?\n", inode, page);
460                 goto out;
461         }
462         oldest = get_oldest_context(inode, &snap_size);
463         if (snapc->seq > oldest->seq) {
464                 dout("writepage %p page %p snapc %p not writeable - noop\n",
465                      inode, page, snapc);
466                 /* we should only noop if called by kswapd */
467                 WARN_ON((current->flags & PF_MEMALLOC) == 0);
468                 ceph_put_snap_context(oldest);
469                 goto out;
470         }
471         ceph_put_snap_context(oldest);
472
473         spin_lock(&ci->i_ceph_lock);
474         truncate_seq = ci->i_truncate_seq;
475         truncate_size = ci->i_truncate_size;
476         if (!snap_size)
477                 snap_size = i_size_read(inode);
478         spin_unlock(&ci->i_ceph_lock);
479
480         /* is this a partial page at end of file? */
481         if (page_off >= snap_size) {
482                 dout("%p page eof %llu\n", page, snap_size);
483                 goto out;
484         }
485         if (snap_size < page_off + len)
486                 len = snap_size - page_off;
487
488         dout("writepage %p page %p index %lu on %llu~%u snapc %p\n",
489              inode, page, page->index, page_off, len, snapc);
490
491         writeback_stat = atomic_long_inc_return(&fsc->writeback_count);
492         if (writeback_stat >
493             CONGESTION_ON_THRESH(fsc->mount_options->congestion_kb))
494                 set_bdi_congested(&fsc->backing_dev_info, BLK_RW_ASYNC);
495
496         set_page_writeback(page);
497         err = ceph_osdc_writepages(osdc, ceph_vino(inode),
498                                    &ci->i_layout, snapc,
499                                    page_off, len,
500                                    truncate_seq, truncate_size,
501                                    &inode->i_mtime, &page, 1);
502         if (err < 0) {
503                 dout("writepage setting page/mapping error %d %p\n", err, page);
504                 SetPageError(page);
505                 mapping_set_error(&inode->i_data, err);
506                 if (wbc)
507                         wbc->pages_skipped++;
508         } else {
509                 dout("writepage cleaned page %p\n", page);
510                 err = 0;  /* vfs expects us to return 0 */
511         }
512         page->private = 0;
513         ClearPagePrivate(page);
514         end_page_writeback(page);
515         ceph_put_wrbuffer_cap_refs(ci, 1, snapc);
516         ceph_put_snap_context(snapc);  /* page's reference */
517 out:
518         return err;
519 }
520
521 static int ceph_writepage(struct page *page, struct writeback_control *wbc)
522 {
523         int err;
524         struct inode *inode = page->mapping->host;
525         BUG_ON(!inode);
526         ihold(inode);
527         err = writepage_nounlock(page, wbc);
528         unlock_page(page);
529         iput(inode);
530         return err;
531 }
532
533
534 /*
535  * lame release_pages helper.  release_pages() isn't exported to
536  * modules.
537  */
538 static void ceph_release_pages(struct page **pages, int num)
539 {
540         struct pagevec pvec;
541         int i;
542
543         pagevec_init(&pvec, 0);
544         for (i = 0; i < num; i++) {
545                 if (pagevec_add(&pvec, pages[i]) == 0)
546                         pagevec_release(&pvec);
547         }
548         pagevec_release(&pvec);
549 }
550
551
552 /*
553  * async writeback completion handler.
554  *
555  * If we get an error, set the mapping error bit, but not the individual
556  * page error bits.
557  */
558 static void writepages_finish(struct ceph_osd_request *req,
559                               struct ceph_msg *msg)
560 {
561         struct inode *inode = req->r_inode;
562         struct ceph_inode_info *ci = ceph_inode(inode);
563         struct ceph_osd_data *osd_data;
564         unsigned wrote;
565         struct page *page;
566         int num_pages;
567         int i;
568         struct ceph_snap_context *snapc = req->r_snapc;
569         struct address_space *mapping = inode->i_mapping;
570         int rc = req->r_result;
571         u64 bytes = req->r_ops[0].extent.length;
572         struct ceph_fs_client *fsc = ceph_inode_to_client(inode);
573         long writeback_stat;
574         unsigned issued = ceph_caps_issued(ci);
575
576         osd_data = osd_req_op_extent_osd_data(req, 0);
577         BUG_ON(osd_data->type != CEPH_OSD_DATA_TYPE_PAGES);
578         num_pages = calc_pages_for((u64)osd_data->alignment,
579                                         (u64)osd_data->length);
580         if (rc >= 0) {
581                 /*
582                  * Assume we wrote the pages we originally sent.  The
583                  * osd might reply with fewer pages if our writeback
584                  * raced with a truncation and was adjusted at the osd,
585                  * so don't believe the reply.
586                  */
587                 wrote = num_pages;
588         } else {
589                 wrote = 0;
590                 mapping_set_error(mapping, rc);
591         }
592         dout("writepages_finish %p rc %d bytes %llu wrote %d (pages)\n",
593              inode, rc, bytes, wrote);
594
595         /* clean all pages */
596         for (i = 0; i < num_pages; i++) {
597                 page = osd_data->pages[i];
598                 BUG_ON(!page);
599                 WARN_ON(!PageUptodate(page));
600
601                 writeback_stat =
602                         atomic_long_dec_return(&fsc->writeback_count);
603                 if (writeback_stat <
604                     CONGESTION_OFF_THRESH(fsc->mount_options->congestion_kb))
605                         clear_bdi_congested(&fsc->backing_dev_info,
606                                             BLK_RW_ASYNC);
607
608                 ceph_put_snap_context(page_snap_context(page));
609                 page->private = 0;
610                 ClearPagePrivate(page);
611                 dout("unlocking %d %p\n", i, page);
612                 end_page_writeback(page);
613
614                 /*
615                  * We lost the cache cap, need to truncate the page before
616                  * it is unlocked, otherwise we'd truncate it later in the
617                  * page truncation thread, possibly losing some data that
618                  * raced its way in
619                  */
620                 if ((issued & (CEPH_CAP_FILE_CACHE|CEPH_CAP_FILE_LAZYIO)) == 0)
621                         generic_error_remove_page(inode->i_mapping, page);
622
623                 unlock_page(page);
624         }
625         dout("%p wrote+cleaned %d pages\n", inode, wrote);
626         ceph_put_wrbuffer_cap_refs(ci, num_pages, snapc);
627
628         ceph_release_pages(osd_data->pages, num_pages);
629         if (osd_data->pages_from_pool)
630                 mempool_free(osd_data->pages,
631                              ceph_sb_to_client(inode->i_sb)->wb_pagevec_pool);
632         else
633                 kfree(osd_data->pages);
634         ceph_osdc_put_request(req);
635 }
636
637 /*
638  * initiate async writeback
639  */
640 static int ceph_writepages_start(struct address_space *mapping,
641                                  struct writeback_control *wbc)
642 {
643         struct inode *inode = mapping->host;
644         struct ceph_inode_info *ci = ceph_inode(inode);
645         struct ceph_fs_client *fsc = ceph_inode_to_client(inode);
646         struct ceph_vino vino = ceph_vino(inode);
647         pgoff_t index, start, end;
648         int range_whole = 0;
649         int should_loop = 1;
650         pgoff_t max_pages = 0, max_pages_ever = 0;
651         struct ceph_snap_context *snapc = NULL, *last_snapc = NULL, *pgsnapc;
652         struct pagevec pvec;
653         int done = 0;
654         int rc = 0;
655         unsigned wsize = 1 << inode->i_blkbits;
656         struct ceph_osd_request *req = NULL;
657         int do_sync;
658         u64 truncate_size, snap_size;
659         u32 truncate_seq;
660
661         /*
662          * Include a 'sync' in the OSD request if this is a data
663          * integrity write (e.g., O_SYNC write or fsync()), or if our
664          * cap is being revoked.
665          */
666         if ((wbc->sync_mode == WB_SYNC_ALL) ||
667                 ceph_caps_revoking(ci, CEPH_CAP_FILE_BUFFER))
668                 do_sync = 1;
669         dout("writepages_start %p dosync=%d (mode=%s)\n",
670              inode, do_sync,
671              wbc->sync_mode == WB_SYNC_NONE ? "NONE" :
672              (wbc->sync_mode == WB_SYNC_ALL ? "ALL" : "HOLD"));
673
674         if (fsc->mount_state == CEPH_MOUNT_SHUTDOWN) {
675                 pr_warning("writepage_start %p on forced umount\n", inode);
676                 return -EIO; /* we're in a forced umount, don't write! */
677         }
678         if (fsc->mount_options->wsize && fsc->mount_options->wsize < wsize)
679                 wsize = fsc->mount_options->wsize;
680         if (wsize < PAGE_CACHE_SIZE)
681                 wsize = PAGE_CACHE_SIZE;
682         max_pages_ever = wsize >> PAGE_CACHE_SHIFT;
683
684         pagevec_init(&pvec, 0);
685
686         /* where to start/end? */
687         if (wbc->range_cyclic) {
688                 start = mapping->writeback_index; /* Start from prev offset */
689                 end = -1;
690                 dout(" cyclic, start at %lu\n", start);
691         } else {
692                 start = wbc->range_start >> PAGE_CACHE_SHIFT;
693                 end = wbc->range_end >> PAGE_CACHE_SHIFT;
694                 if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
695                         range_whole = 1;
696                 should_loop = 0;
697                 dout(" not cyclic, %lu to %lu\n", start, end);
698         }
699         index = start;
700
701 retry:
702         /* find oldest snap context with dirty data */
703         ceph_put_snap_context(snapc);
704         snap_size = 0;
705         snapc = get_oldest_context(inode, &snap_size);
706         if (!snapc) {
707                 /* hmm, why does writepages get called when there
708                    is no dirty data? */
709                 dout(" no snap context with dirty data?\n");
710                 goto out;
711         }
712         if (snap_size == 0)
713                 snap_size = i_size_read(inode);
714         dout(" oldest snapc is %p seq %lld (%d snaps)\n",
715              snapc, snapc->seq, snapc->num_snaps);
716
717         spin_lock(&ci->i_ceph_lock);
718         truncate_seq = ci->i_truncate_seq;
719         truncate_size = ci->i_truncate_size;
720         if (!snap_size)
721                 snap_size = i_size_read(inode);
722         spin_unlock(&ci->i_ceph_lock);
723
724         if (last_snapc && snapc != last_snapc) {
725                 /* if we switched to a newer snapc, restart our scan at the
726                  * start of the original file range. */
727                 dout("  snapc differs from last pass, restarting at %lu\n",
728                      index);
729                 index = start;
730         }
731         last_snapc = snapc;
732
733         while (!done && index <= end) {
734                 int num_ops = do_sync ? 2 : 1;
735                 unsigned i;
736                 int first;
737                 pgoff_t next;
738                 int pvec_pages, locked_pages;
739                 struct page **pages = NULL;
740                 mempool_t *pool = NULL; /* Becomes non-null if mempool used */
741                 struct page *page;
742                 int want;
743                 u64 offset, len;
744                 long writeback_stat;
745
746                 next = 0;
747                 locked_pages = 0;
748                 max_pages = max_pages_ever;
749
750 get_more_pages:
751                 first = -1;
752                 want = min(end - index,
753                            min((pgoff_t)PAGEVEC_SIZE,
754                                max_pages - (pgoff_t)locked_pages) - 1)
755                         + 1;
756                 pvec_pages = pagevec_lookup_tag(&pvec, mapping, &index,
757                                                 PAGECACHE_TAG_DIRTY,
758                                                 want);
759                 dout("pagevec_lookup_tag got %d\n", pvec_pages);
760                 if (!pvec_pages && !locked_pages)
761                         break;
762                 for (i = 0; i < pvec_pages && locked_pages < max_pages; i++) {
763                         page = pvec.pages[i];
764                         dout("? %p idx %lu\n", page, page->index);
765                         if (locked_pages == 0)
766                                 lock_page(page);  /* first page */
767                         else if (!trylock_page(page))
768                                 break;
769
770                         /* only dirty pages, or our accounting breaks */
771                         if (unlikely(!PageDirty(page)) ||
772                             unlikely(page->mapping != mapping)) {
773                                 dout("!dirty or !mapping %p\n", page);
774                                 unlock_page(page);
775                                 break;
776                         }
777                         if (!wbc->range_cyclic && page->index > end) {
778                                 dout("end of range %p\n", page);
779                                 done = 1;
780                                 unlock_page(page);
781                                 break;
782                         }
783                         if (next && (page->index != next)) {
784                                 dout("not consecutive %p\n", page);
785                                 unlock_page(page);
786                                 break;
787                         }
788                         if (wbc->sync_mode != WB_SYNC_NONE) {
789                                 dout("waiting on writeback %p\n", page);
790                                 wait_on_page_writeback(page);
791                         }
792                         if (page_offset(page) >= snap_size) {
793                                 dout("%p page eof %llu\n", page, snap_size);
794                                 done = 1;
795                                 unlock_page(page);
796                                 break;
797                         }
798                         if (PageWriteback(page)) {
799                                 dout("%p under writeback\n", page);
800                                 unlock_page(page);
801                                 break;
802                         }
803
804                         /* only if matching snap context */
805                         pgsnapc = page_snap_context(page);
806                         if (pgsnapc->seq > snapc->seq) {
807                                 dout("page snapc %p %lld > oldest %p %lld\n",
808                                      pgsnapc, pgsnapc->seq, snapc, snapc->seq);
809                                 unlock_page(page);
810                                 if (!locked_pages)
811                                         continue; /* keep looking for snap */
812                                 break;
813                         }
814
815                         if (!clear_page_dirty_for_io(page)) {
816                                 dout("%p !clear_page_dirty_for_io\n", page);
817                                 unlock_page(page);
818                                 break;
819                         }
820
821                         /*
822                          * We have something to write.  If this is
823                          * the first locked page this time through,
824                          * allocate an osd request and a page array
825                          * that it will use.
826                          */
827                         if (locked_pages == 0) {
828                                 BUG_ON(pages);
829                                 /* prepare async write request */
830                                 offset = (u64)page_offset(page);
831                                 len = wsize;
832                                 req = ceph_osdc_new_request(&fsc->client->osdc,
833                                                         &ci->i_layout, vino,
834                                                         offset, &len, num_ops,
835                                                         CEPH_OSD_OP_WRITE,
836                                                         CEPH_OSD_FLAG_WRITE |
837                                                         CEPH_OSD_FLAG_ONDISK,
838                                                         snapc, truncate_seq,
839                                                         truncate_size, true);
840                                 if (IS_ERR(req)) {
841                                         rc = PTR_ERR(req);
842                                         unlock_page(page);
843                                         break;
844                                 }
845
846                                 req->r_callback = writepages_finish;
847                                 req->r_inode = inode;
848
849                                 max_pages = calc_pages_for(0, (u64)len);
850                                 pages = kmalloc(max_pages * sizeof (*pages),
851                                                 GFP_NOFS);
852                                 if (!pages) {
853                                         pool = fsc->wb_pagevec_pool;
854                                         pages = mempool_alloc(pool, GFP_NOFS);
855                                         BUG_ON(!pages);
856                                 }
857                         }
858
859                         /* note position of first page in pvec */
860                         if (first < 0)
861                                 first = i;
862                         dout("%p will write page %p idx %lu\n",
863                              inode, page, page->index);
864
865                         writeback_stat =
866                                atomic_long_inc_return(&fsc->writeback_count);
867                         if (writeback_stat > CONGESTION_ON_THRESH(
868                                     fsc->mount_options->congestion_kb)) {
869                                 set_bdi_congested(&fsc->backing_dev_info,
870                                                   BLK_RW_ASYNC);
871                         }
872
873                         set_page_writeback(page);
874                         pages[locked_pages] = page;
875                         locked_pages++;
876                         next = page->index + 1;
877                 }
878
879                 /* did we get anything? */
880                 if (!locked_pages)
881                         goto release_pvec_pages;
882                 if (i) {
883                         int j;
884                         BUG_ON(!locked_pages || first < 0);
885
886                         if (pvec_pages && i == pvec_pages &&
887                             locked_pages < max_pages) {
888                                 dout("reached end pvec, trying for more\n");
889                                 pagevec_reinit(&pvec);
890                                 goto get_more_pages;
891                         }
892
893                         /* shift unused pages over in the pvec...  we
894                          * will need to release them below. */
895                         for (j = i; j < pvec_pages; j++) {
896                                 dout(" pvec leftover page %p\n",
897                                      pvec.pages[j]);
898                                 pvec.pages[j-i+first] = pvec.pages[j];
899                         }
900                         pvec.nr -= i-first;
901                 }
902
903                 /* Format the osd request message and submit the write */
904
905                 offset = page_offset(pages[0]);
906                 len = min(snap_size - offset,
907                           (u64)locked_pages << PAGE_CACHE_SHIFT);
908                 dout("writepages got %d pages at %llu~%llu\n",
909                      locked_pages, offset, len);
910
911                 osd_req_op_extent_osd_data_pages(req, 0, pages, len, 0,
912                                                         !!pool, false);
913
914                 pages = NULL;   /* request message now owns the pages array */
915                 pool = NULL;
916
917                 /* Update the write op length in case we changed it */
918
919                 osd_req_op_extent_update(req, 0, len);
920
921                 vino = ceph_vino(inode);
922                 ceph_osdc_build_request(req, offset, snapc, vino.snap,
923                                         &inode->i_mtime);
924
925                 rc = ceph_osdc_start_request(&fsc->client->osdc, req, true);
926                 BUG_ON(rc);
927                 req = NULL;
928
929                 /* continue? */
930                 index = next;
931                 wbc->nr_to_write -= locked_pages;
932                 if (wbc->nr_to_write <= 0)
933                         done = 1;
934
935 release_pvec_pages:
936                 dout("pagevec_release on %d pages (%p)\n", (int)pvec.nr,
937                      pvec.nr ? pvec.pages[0] : NULL);
938                 pagevec_release(&pvec);
939
940                 if (locked_pages && !done)
941                         goto retry;
942         }
943
944         if (should_loop && !done) {
945                 /* more to do; loop back to beginning of file */
946                 dout("writepages looping back to beginning of file\n");
947                 should_loop = 0;
948                 index = 0;
949                 goto retry;
950         }
951
952         if (wbc->range_cyclic || (range_whole && wbc->nr_to_write > 0))
953                 mapping->writeback_index = index;
954
955 out:
956         if (req)
957                 ceph_osdc_put_request(req);
958         ceph_put_snap_context(snapc);
959         dout("writepages done, rc = %d\n", rc);
960         return rc;
961 }
962
963
964
965 /*
966  * See if a given @snapc is either writeable, or already written.
967  */
968 static int context_is_writeable_or_written(struct inode *inode,
969                                            struct ceph_snap_context *snapc)
970 {
971         struct ceph_snap_context *oldest = get_oldest_context(inode, NULL);
972         int ret = !oldest || snapc->seq <= oldest->seq;
973
974         ceph_put_snap_context(oldest);
975         return ret;
976 }
977
978 /*
979  * We are only allowed to write into/dirty the page if the page is
980  * clean, or already dirty within the same snap context.
981  *
982  * called with page locked.
983  * return success with page locked,
984  * or any failure (incl -EAGAIN) with page unlocked.
985  */
986 static int ceph_update_writeable_page(struct file *file,
987                             loff_t pos, unsigned len,
988                             struct page *page)
989 {
990         struct inode *inode = file_inode(file);
991         struct ceph_inode_info *ci = ceph_inode(inode);
992         struct ceph_mds_client *mdsc = ceph_inode_to_client(inode)->mdsc;
993         loff_t page_off = pos & PAGE_CACHE_MASK;
994         int pos_in_page = pos & ~PAGE_CACHE_MASK;
995         int end_in_page = pos_in_page + len;
996         loff_t i_size;
997         int r;
998         struct ceph_snap_context *snapc, *oldest;
999
1000 retry_locked:
1001         /* writepages currently holds page lock, but if we change that later, */
1002         wait_on_page_writeback(page);
1003
1004         /* check snap context */
1005         BUG_ON(!ci->i_snap_realm);
1006         down_read(&mdsc->snap_rwsem);
1007         BUG_ON(!ci->i_snap_realm->cached_context);
1008         snapc = page_snap_context(page);
1009         if (snapc && snapc != ci->i_head_snapc) {
1010                 /*
1011                  * this page is already dirty in another (older) snap
1012                  * context!  is it writeable now?
1013                  */
1014                 oldest = get_oldest_context(inode, NULL);
1015                 up_read(&mdsc->snap_rwsem);
1016
1017                 if (snapc->seq > oldest->seq) {
1018                         ceph_put_snap_context(oldest);
1019                         dout(" page %p snapc %p not current or oldest\n",
1020                              page, snapc);
1021                         /*
1022                          * queue for writeback, and wait for snapc to
1023                          * be writeable or written
1024                          */
1025                         snapc = ceph_get_snap_context(snapc);
1026                         unlock_page(page);
1027                         ceph_queue_writeback(inode);
1028                         r = wait_event_interruptible(ci->i_cap_wq,
1029                                context_is_writeable_or_written(inode, snapc));
1030                         ceph_put_snap_context(snapc);
1031                         if (r == -ERESTARTSYS)
1032                                 return r;
1033                         return -EAGAIN;
1034                 }
1035                 ceph_put_snap_context(oldest);
1036
1037                 /* yay, writeable, do it now (without dropping page lock) */
1038                 dout(" page %p snapc %p not current, but oldest\n",
1039                      page, snapc);
1040                 if (!clear_page_dirty_for_io(page))
1041                         goto retry_locked;
1042                 r = writepage_nounlock(page, NULL);
1043                 if (r < 0)
1044                         goto fail_nosnap;
1045                 goto retry_locked;
1046         }
1047
1048         if (PageUptodate(page)) {
1049                 dout(" page %p already uptodate\n", page);
1050                 return 0;
1051         }
1052
1053         /* full page? */
1054         if (pos_in_page == 0 && len == PAGE_CACHE_SIZE)
1055                 return 0;
1056
1057         /* past end of file? */
1058         i_size = inode->i_size;   /* caller holds i_mutex */
1059
1060         if (i_size + len > inode->i_sb->s_maxbytes) {
1061                 /* file is too big */
1062                 r = -EINVAL;
1063                 goto fail;
1064         }
1065
1066         if (page_off >= i_size ||
1067             (pos_in_page == 0 && (pos+len) >= i_size &&
1068              end_in_page - pos_in_page != PAGE_CACHE_SIZE)) {
1069                 dout(" zeroing %p 0 - %d and %d - %d\n",
1070                      page, pos_in_page, end_in_page, (int)PAGE_CACHE_SIZE);
1071                 zero_user_segments(page,
1072                                    0, pos_in_page,
1073                                    end_in_page, PAGE_CACHE_SIZE);
1074                 return 0;
1075         }
1076
1077         /* we need to read it. */
1078         up_read(&mdsc->snap_rwsem);
1079         r = readpage_nounlock(file, page);
1080         if (r < 0)
1081                 goto fail_nosnap;
1082         goto retry_locked;
1083
1084 fail:
1085         up_read(&mdsc->snap_rwsem);
1086 fail_nosnap:
1087         unlock_page(page);
1088         return r;
1089 }
1090
1091 /*
1092  * We are only allowed to write into/dirty the page if the page is
1093  * clean, or already dirty within the same snap context.
1094  */
1095 static int ceph_write_begin(struct file *file, struct address_space *mapping,
1096                             loff_t pos, unsigned len, unsigned flags,
1097                             struct page **pagep, void **fsdata)
1098 {
1099         struct inode *inode = file_inode(file);
1100         struct page *page;
1101         pgoff_t index = pos >> PAGE_CACHE_SHIFT;
1102         int r;
1103
1104         do {
1105                 /* get a page */
1106                 page = grab_cache_page_write_begin(mapping, index, 0);
1107                 if (!page)
1108                         return -ENOMEM;
1109                 *pagep = page;
1110
1111                 dout("write_begin file %p inode %p page %p %d~%d\n", file,
1112                      inode, page, (int)pos, (int)len);
1113
1114                 r = ceph_update_writeable_page(file, pos, len, page);
1115         } while (r == -EAGAIN);
1116
1117         return r;
1118 }
1119
1120 /*
1121  * we don't do anything in here that simple_write_end doesn't do
1122  * except adjust dirty page accounting and drop read lock on
1123  * mdsc->snap_rwsem.
1124  */
1125 static int ceph_write_end(struct file *file, struct address_space *mapping,
1126                           loff_t pos, unsigned len, unsigned copied,
1127                           struct page *page, void *fsdata)
1128 {
1129         struct inode *inode = file_inode(file);
1130         struct ceph_fs_client *fsc = ceph_inode_to_client(inode);
1131         struct ceph_mds_client *mdsc = fsc->mdsc;
1132         unsigned from = pos & (PAGE_CACHE_SIZE - 1);
1133         int check_cap = 0;
1134
1135         dout("write_end file %p inode %p page %p %d~%d (%d)\n", file,
1136              inode, page, (int)pos, (int)copied, (int)len);
1137
1138         /* zero the stale part of the page if we did a short copy */
1139         if (copied < len)
1140                 zero_user_segment(page, from+copied, len);
1141
1142         /* did file size increase? */
1143         /* (no need for i_size_read(); we caller holds i_mutex */
1144         if (pos+copied > inode->i_size)
1145                 check_cap = ceph_inode_set_size(inode, pos+copied);
1146
1147         if (!PageUptodate(page))
1148                 SetPageUptodate(page);
1149
1150         set_page_dirty(page);
1151
1152         unlock_page(page);
1153         up_read(&mdsc->snap_rwsem);
1154         page_cache_release(page);
1155
1156         if (check_cap)
1157                 ceph_check_caps(ceph_inode(inode), CHECK_CAPS_AUTHONLY, NULL);
1158
1159         return copied;
1160 }
1161
1162 /*
1163  * we set .direct_IO to indicate direct io is supported, but since we
1164  * intercept O_DIRECT reads and writes early, this function should
1165  * never get called.
1166  */
1167 static ssize_t ceph_direct_io(int rw, struct kiocb *iocb,
1168                               const struct iovec *iov,
1169                               loff_t pos, unsigned long nr_segs)
1170 {
1171         WARN_ON(1);
1172         return -EINVAL;
1173 }
1174
1175 const struct address_space_operations ceph_aops = {
1176         .readpage = ceph_readpage,
1177         .readpages = ceph_readpages,
1178         .writepage = ceph_writepage,
1179         .writepages = ceph_writepages_start,
1180         .write_begin = ceph_write_begin,
1181         .write_end = ceph_write_end,
1182         .set_page_dirty = ceph_set_page_dirty,
1183         .invalidatepage = ceph_invalidatepage,
1184         .releasepage = ceph_releasepage,
1185         .direct_IO = ceph_direct_io,
1186 };
1187
1188
1189 /*
1190  * vm ops
1191  */
1192
1193 /*
1194  * Reuse write_begin here for simplicity.
1195  */
1196 static int ceph_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf)
1197 {
1198         struct inode *inode = file_inode(vma->vm_file);
1199         struct page *page = vmf->page;
1200         struct ceph_mds_client *mdsc = ceph_inode_to_client(inode)->mdsc;
1201         loff_t off = page_offset(page);
1202         loff_t size, len;
1203         int ret;
1204
1205         /* Update time before taking page lock */
1206         file_update_time(vma->vm_file);
1207
1208         size = i_size_read(inode);
1209         if (off + PAGE_CACHE_SIZE <= size)
1210                 len = PAGE_CACHE_SIZE;
1211         else
1212                 len = size & ~PAGE_CACHE_MASK;
1213
1214         dout("page_mkwrite %p %llu~%llu page %p idx %lu\n", inode,
1215              off, len, page, page->index);
1216
1217         lock_page(page);
1218
1219         ret = VM_FAULT_NOPAGE;
1220         if ((off > size) ||
1221             (page->mapping != inode->i_mapping))
1222                 goto out;
1223
1224         ret = ceph_update_writeable_page(vma->vm_file, off, len, page);
1225         if (ret == 0) {
1226                 /* success.  we'll keep the page locked. */
1227                 set_page_dirty(page);
1228                 up_read(&mdsc->snap_rwsem);
1229                 ret = VM_FAULT_LOCKED;
1230         } else {
1231                 if (ret == -ENOMEM)
1232                         ret = VM_FAULT_OOM;
1233                 else
1234                         ret = VM_FAULT_SIGBUS;
1235         }
1236 out:
1237         dout("page_mkwrite %p %llu~%llu = %d\n", inode, off, len, ret);
1238         if (ret != VM_FAULT_LOCKED)
1239                 unlock_page(page);
1240         return ret;
1241 }
1242
1243 static struct vm_operations_struct ceph_vmops = {
1244         .fault          = filemap_fault,
1245         .page_mkwrite   = ceph_page_mkwrite,
1246         .remap_pages    = generic_file_remap_pages,
1247 };
1248
1249 int ceph_mmap(struct file *file, struct vm_area_struct *vma)
1250 {
1251         struct address_space *mapping = file->f_mapping;
1252
1253         if (!mapping->a_ops->readpage)
1254                 return -ENOEXEC;
1255         file_accessed(file);
1256         vma->vm_ops = &ceph_vmops;
1257         return 0;
1258 }