ceph: have ceph_writepages_start call pagevec_lookup_range_tag
[linux-2.6-microblaze.git] / fs / ceph / addr.c
1 // SPDX-License-Identifier: GPL-2.0
2 #include <linux/ceph/ceph_debug.h>
3
4 #include <linux/backing-dev.h>
5 #include <linux/fs.h>
6 #include <linux/mm.h>
7 #include <linux/pagemap.h>
8 #include <linux/writeback.h>    /* generic_writepages */
9 #include <linux/slab.h>
10 #include <linux/pagevec.h>
11 #include <linux/task_io_accounting_ops.h>
12 #include <linux/signal.h>
13 #include <linux/iversion.h>
14 #include <linux/ktime.h>
15
16 #include "super.h"
17 #include "mds_client.h"
18 #include "cache.h"
19 #include "metric.h"
20 #include <linux/ceph/osd_client.h>
21 #include <linux/ceph/striper.h>
22
23 /*
24  * Ceph address space ops.
25  *
26  * There are a few funny things going on here.
27  *
28  * The page->private field is used to reference a struct
29  * ceph_snap_context for _every_ dirty page.  This indicates which
30  * snapshot the page was logically dirtied in, and thus which snap
31  * context needs to be associated with the osd write during writeback.
32  *
33  * Similarly, struct ceph_inode_info maintains a set of counters to
34  * count dirty pages on the inode.  In the absence of snapshots,
35  * i_wrbuffer_ref == i_wrbuffer_ref_head == the dirty page count.
36  *
37  * When a snapshot is taken (that is, when the client receives
38  * notification that a snapshot was taken), each inode with caps and
39  * with dirty pages (dirty pages implies there is a cap) gets a new
40  * ceph_cap_snap in the i_cap_snaps list (which is sorted in ascending
41  * order, new snaps go to the tail).  The i_wrbuffer_ref_head count is
42  * moved to capsnap->dirty. (Unless a sync write is currently in
43  * progress.  In that case, the capsnap is said to be "pending", new
44  * writes cannot start, and the capsnap isn't "finalized" until the
45  * write completes (or fails) and a final size/mtime for the inode for
46  * that snap can be settled upon.)  i_wrbuffer_ref_head is reset to 0.
47  *
48  * On writeback, we must submit writes to the osd IN SNAP ORDER.  So,
49  * we look for the first capsnap in i_cap_snaps and write out pages in
50  * that snap context _only_.  Then we move on to the next capsnap,
51  * eventually reaching the "live" or "head" context (i.e., pages that
52  * are not yet snapped) and are writing the most recently dirtied
53  * pages.
54  *
55  * Invalidate and so forth must take care to ensure the dirty page
56  * accounting is preserved.
57  */
58
59 #define CONGESTION_ON_THRESH(congestion_kb) (congestion_kb >> (PAGE_SHIFT-10))
60 #define CONGESTION_OFF_THRESH(congestion_kb)                            \
61         (CONGESTION_ON_THRESH(congestion_kb) -                          \
62          (CONGESTION_ON_THRESH(congestion_kb) >> 2))
63
64 static inline struct ceph_snap_context *page_snap_context(struct page *page)
65 {
66         if (PagePrivate(page))
67                 return (void *)page->private;
68         return NULL;
69 }
70
71 /*
72  * Dirty a page.  Optimistically adjust accounting, on the assumption
73  * that we won't race with invalidate.  If we do, readjust.
74  */
75 static int ceph_set_page_dirty(struct page *page)
76 {
77         struct address_space *mapping = page->mapping;
78         struct inode *inode;
79         struct ceph_inode_info *ci;
80         struct ceph_snap_context *snapc;
81         int ret;
82
83         if (unlikely(!mapping))
84                 return !TestSetPageDirty(page);
85
86         if (PageDirty(page)) {
87                 dout("%p set_page_dirty %p idx %lu -- already dirty\n",
88                      mapping->host, page, page->index);
89                 BUG_ON(!PagePrivate(page));
90                 return 0;
91         }
92
93         inode = mapping->host;
94         ci = ceph_inode(inode);
95
96         /* dirty the head */
97         spin_lock(&ci->i_ceph_lock);
98         BUG_ON(ci->i_wr_ref == 0); // caller should hold Fw reference
99         if (__ceph_have_pending_cap_snap(ci)) {
100                 struct ceph_cap_snap *capsnap =
101                                 list_last_entry(&ci->i_cap_snaps,
102                                                 struct ceph_cap_snap,
103                                                 ci_item);
104                 snapc = ceph_get_snap_context(capsnap->context);
105                 capsnap->dirty_pages++;
106         } else {
107                 BUG_ON(!ci->i_head_snapc);
108                 snapc = ceph_get_snap_context(ci->i_head_snapc);
109                 ++ci->i_wrbuffer_ref_head;
110         }
111         if (ci->i_wrbuffer_ref == 0)
112                 ihold(inode);
113         ++ci->i_wrbuffer_ref;
114         dout("%p set_page_dirty %p idx %lu head %d/%d -> %d/%d "
115              "snapc %p seq %lld (%d snaps)\n",
116              mapping->host, page, page->index,
117              ci->i_wrbuffer_ref-1, ci->i_wrbuffer_ref_head-1,
118              ci->i_wrbuffer_ref, ci->i_wrbuffer_ref_head,
119              snapc, snapc->seq, snapc->num_snaps);
120         spin_unlock(&ci->i_ceph_lock);
121
122         /*
123          * Reference snap context in page->private.  Also set
124          * PagePrivate so that we get invalidatepage callback.
125          */
126         BUG_ON(PagePrivate(page));
127         page->private = (unsigned long)snapc;
128         SetPagePrivate(page);
129
130         ret = __set_page_dirty_nobuffers(page);
131         WARN_ON(!PageLocked(page));
132         WARN_ON(!page->mapping);
133
134         return ret;
135 }
136
137 /*
138  * If we are truncating the full page (i.e. offset == 0), adjust the
139  * dirty page counters appropriately.  Only called if there is private
140  * data on the page.
141  */
142 static void ceph_invalidatepage(struct page *page, unsigned int offset,
143                                 unsigned int length)
144 {
145         struct inode *inode;
146         struct ceph_inode_info *ci;
147         struct ceph_snap_context *snapc = page_snap_context(page);
148
149         inode = page->mapping->host;
150         ci = ceph_inode(inode);
151
152         if (offset != 0 || length != PAGE_SIZE) {
153                 dout("%p invalidatepage %p idx %lu partial dirty page %u~%u\n",
154                      inode, page, page->index, offset, length);
155                 return;
156         }
157
158         ceph_invalidate_fscache_page(inode, page);
159
160         WARN_ON(!PageLocked(page));
161         if (!PagePrivate(page))
162                 return;
163
164         dout("%p invalidatepage %p idx %lu full dirty page\n",
165              inode, page, page->index);
166
167         ceph_put_wrbuffer_cap_refs(ci, 1, snapc);
168         ceph_put_snap_context(snapc);
169         page->private = 0;
170         ClearPagePrivate(page);
171 }
172
173 static int ceph_releasepage(struct page *page, gfp_t g)
174 {
175         dout("%p releasepage %p idx %lu (%sdirty)\n", page->mapping->host,
176              page, page->index, PageDirty(page) ? "" : "not ");
177
178         /* Can we release the page from the cache? */
179         if (!ceph_release_fscache_page(page, g))
180                 return 0;
181
182         return !PagePrivate(page);
183 }
184
185 /*
186  * Read some contiguous pages.  If we cross a stripe boundary, shorten
187  * *plen.  Return number of bytes read, or error.
188  */
189 static int ceph_sync_readpages(struct ceph_fs_client *fsc,
190                                struct ceph_vino vino,
191                                struct ceph_file_layout *layout,
192                                u64 off, u64 *plen,
193                                u32 truncate_seq, u64 truncate_size,
194                                struct page **pages, int num_pages,
195                                int page_align)
196 {
197         struct ceph_osd_client *osdc = &fsc->client->osdc;
198         struct ceph_osd_request *req;
199         int rc = 0;
200
201         dout("readpages on ino %llx.%llx on %llu~%llu\n", vino.ino,
202              vino.snap, off, *plen);
203         req = ceph_osdc_new_request(osdc, layout, vino, off, plen, 0, 1,
204                                     CEPH_OSD_OP_READ, CEPH_OSD_FLAG_READ,
205                                     NULL, truncate_seq, truncate_size,
206                                     false);
207         if (IS_ERR(req))
208                 return PTR_ERR(req);
209
210         /* it may be a short read due to an object boundary */
211         osd_req_op_extent_osd_data_pages(req, 0,
212                                 pages, *plen, page_align, false, false);
213
214         dout("readpages  final extent is %llu~%llu (%llu bytes align %d)\n",
215              off, *plen, *plen, page_align);
216
217         rc = ceph_osdc_start_request(osdc, req, false);
218         if (!rc)
219                 rc = ceph_osdc_wait_request(osdc, req);
220
221         ceph_update_read_latency(&fsc->mdsc->metric, req->r_start_latency,
222                                  req->r_end_latency, rc);
223
224         ceph_osdc_put_request(req);
225         dout("readpages result %d\n", rc);
226         return rc;
227 }
228
229 /*
230  * read a single page, without unlocking it.
231  */
232 static int ceph_do_readpage(struct file *filp, struct page *page)
233 {
234         struct inode *inode = file_inode(filp);
235         struct ceph_inode_info *ci = ceph_inode(inode);
236         struct ceph_fs_client *fsc = ceph_inode_to_client(inode);
237         int err = 0;
238         u64 off = page_offset(page);
239         u64 len = PAGE_SIZE;
240
241         if (off >= i_size_read(inode)) {
242                 zero_user_segment(page, 0, PAGE_SIZE);
243                 SetPageUptodate(page);
244                 return 0;
245         }
246
247         if (ci->i_inline_version != CEPH_INLINE_NONE) {
248                 /*
249                  * Uptodate inline data should have been added
250                  * into page cache while getting Fcr caps.
251                  */
252                 if (off == 0)
253                         return -EINVAL;
254                 zero_user_segment(page, 0, PAGE_SIZE);
255                 SetPageUptodate(page);
256                 return 0;
257         }
258
259         err = ceph_readpage_from_fscache(inode, page);
260         if (err == 0)
261                 return -EINPROGRESS;
262
263         dout("readpage inode %p file %p page %p index %lu\n",
264              inode, filp, page, page->index);
265         err = ceph_sync_readpages(fsc, ceph_vino(inode),
266                                   &ci->i_layout, off, &len,
267                                   ci->i_truncate_seq, ci->i_truncate_size,
268                                   &page, 1, 0);
269         if (err == -ENOENT)
270                 err = 0;
271         if (err < 0) {
272                 SetPageError(page);
273                 ceph_fscache_readpage_cancel(inode, page);
274                 if (err == -EBLACKLISTED)
275                         fsc->blacklisted = true;
276                 goto out;
277         }
278         if (err < PAGE_SIZE)
279                 /* zero fill remainder of page */
280                 zero_user_segment(page, err, PAGE_SIZE);
281         else
282                 flush_dcache_page(page);
283
284         SetPageUptodate(page);
285         ceph_readpage_to_fscache(inode, page);
286
287 out:
288         return err < 0 ? err : 0;
289 }
290
291 static int ceph_readpage(struct file *filp, struct page *page)
292 {
293         int r = ceph_do_readpage(filp, page);
294         if (r != -EINPROGRESS)
295                 unlock_page(page);
296         else
297                 r = 0;
298         return r;
299 }
300
301 /*
302  * Finish an async read(ahead) op.
303  */
304 static void finish_read(struct ceph_osd_request *req)
305 {
306         struct inode *inode = req->r_inode;
307         struct ceph_fs_client *fsc = ceph_inode_to_client(inode);
308         struct ceph_osd_data *osd_data;
309         int rc = req->r_result <= 0 ? req->r_result : 0;
310         int bytes = req->r_result >= 0 ? req->r_result : 0;
311         int num_pages;
312         int i;
313
314         dout("finish_read %p req %p rc %d bytes %d\n", inode, req, rc, bytes);
315         if (rc == -EBLACKLISTED)
316                 ceph_inode_to_client(inode)->blacklisted = true;
317
318         /* unlock all pages, zeroing any data we didn't read */
319         osd_data = osd_req_op_extent_osd_data(req, 0);
320         BUG_ON(osd_data->type != CEPH_OSD_DATA_TYPE_PAGES);
321         num_pages = calc_pages_for((u64)osd_data->alignment,
322                                         (u64)osd_data->length);
323         for (i = 0; i < num_pages; i++) {
324                 struct page *page = osd_data->pages[i];
325
326                 if (rc < 0 && rc != -ENOENT) {
327                         ceph_fscache_readpage_cancel(inode, page);
328                         goto unlock;
329                 }
330                 if (bytes < (int)PAGE_SIZE) {
331                         /* zero (remainder of) page */
332                         int s = bytes < 0 ? 0 : bytes;
333                         zero_user_segment(page, s, PAGE_SIZE);
334                 }
335                 dout("finish_read %p uptodate %p idx %lu\n", inode, page,
336                      page->index);
337                 flush_dcache_page(page);
338                 SetPageUptodate(page);
339                 ceph_readpage_to_fscache(inode, page);
340 unlock:
341                 unlock_page(page);
342                 put_page(page);
343                 bytes -= PAGE_SIZE;
344         }
345
346         ceph_update_read_latency(&fsc->mdsc->metric, req->r_start_latency,
347                                  req->r_end_latency, rc);
348
349         kfree(osd_data->pages);
350 }
351
352 /*
353  * start an async read(ahead) operation.  return nr_pages we submitted
354  * a read for on success, or negative error code.
355  */
356 static int start_read(struct inode *inode, struct ceph_rw_context *rw_ctx,
357                       struct list_head *page_list, int max)
358 {
359         struct ceph_osd_client *osdc =
360                 &ceph_inode_to_client(inode)->client->osdc;
361         struct ceph_inode_info *ci = ceph_inode(inode);
362         struct page *page = lru_to_page(page_list);
363         struct ceph_vino vino;
364         struct ceph_osd_request *req;
365         u64 off;
366         u64 len;
367         int i;
368         struct page **pages;
369         pgoff_t next_index;
370         int nr_pages = 0;
371         int got = 0;
372         int ret = 0;
373
374         if (!rw_ctx) {
375                 /* caller of readpages does not hold buffer and read caps
376                  * (fadvise, madvise and readahead cases) */
377                 int want = CEPH_CAP_FILE_CACHE;
378                 ret = ceph_try_get_caps(inode, CEPH_CAP_FILE_RD, want,
379                                         true, &got);
380                 if (ret < 0) {
381                         dout("start_read %p, error getting cap\n", inode);
382                 } else if (!(got & want)) {
383                         dout("start_read %p, no cache cap\n", inode);
384                         ret = 0;
385                 }
386                 if (ret <= 0) {
387                         if (got)
388                                 ceph_put_cap_refs(ci, got);
389                         while (!list_empty(page_list)) {
390                                 page = lru_to_page(page_list);
391                                 list_del(&page->lru);
392                                 put_page(page);
393                         }
394                         return ret;
395                 }
396         }
397
398         off = (u64) page_offset(page);
399
400         /* count pages */
401         next_index = page->index;
402         list_for_each_entry_reverse(page, page_list, lru) {
403                 if (page->index != next_index)
404                         break;
405                 nr_pages++;
406                 next_index++;
407                 if (max && nr_pages == max)
408                         break;
409         }
410         len = nr_pages << PAGE_SHIFT;
411         dout("start_read %p nr_pages %d is %lld~%lld\n", inode, nr_pages,
412              off, len);
413         vino = ceph_vino(inode);
414         req = ceph_osdc_new_request(osdc, &ci->i_layout, vino, off, &len,
415                                     0, 1, CEPH_OSD_OP_READ,
416                                     CEPH_OSD_FLAG_READ, NULL,
417                                     ci->i_truncate_seq, ci->i_truncate_size,
418                                     false);
419         if (IS_ERR(req)) {
420                 ret = PTR_ERR(req);
421                 goto out;
422         }
423
424         /* build page vector */
425         nr_pages = calc_pages_for(0, len);
426         pages = kmalloc_array(nr_pages, sizeof(*pages), GFP_KERNEL);
427         if (!pages) {
428                 ret = -ENOMEM;
429                 goto out_put;
430         }
431         for (i = 0; i < nr_pages; ++i) {
432                 page = list_entry(page_list->prev, struct page, lru);
433                 BUG_ON(PageLocked(page));
434                 list_del(&page->lru);
435
436                 dout("start_read %p adding %p idx %lu\n", inode, page,
437                      page->index);
438                 if (add_to_page_cache_lru(page, &inode->i_data, page->index,
439                                           GFP_KERNEL)) {
440                         ceph_fscache_uncache_page(inode, page);
441                         put_page(page);
442                         dout("start_read %p add_to_page_cache failed %p\n",
443                              inode, page);
444                         nr_pages = i;
445                         if (nr_pages > 0) {
446                                 len = nr_pages << PAGE_SHIFT;
447                                 osd_req_op_extent_update(req, 0, len);
448                                 break;
449                         }
450                         goto out_pages;
451                 }
452                 pages[i] = page;
453         }
454         osd_req_op_extent_osd_data_pages(req, 0, pages, len, 0, false, false);
455         req->r_callback = finish_read;
456         req->r_inode = inode;
457
458         dout("start_read %p starting %p %lld~%lld\n", inode, req, off, len);
459         ret = ceph_osdc_start_request(osdc, req, false);
460         if (ret < 0)
461                 goto out_pages;
462         ceph_osdc_put_request(req);
463
464         /* After adding locked pages to page cache, the inode holds cache cap.
465          * So we can drop our cap refs. */
466         if (got)
467                 ceph_put_cap_refs(ci, got);
468
469         return nr_pages;
470
471 out_pages:
472         for (i = 0; i < nr_pages; ++i) {
473                 ceph_fscache_readpage_cancel(inode, pages[i]);
474                 unlock_page(pages[i]);
475         }
476         ceph_put_page_vector(pages, nr_pages, false);
477 out_put:
478         ceph_osdc_put_request(req);
479 out:
480         if (got)
481                 ceph_put_cap_refs(ci, got);
482         return ret;
483 }
484
485
486 /*
487  * Read multiple pages.  Leave pages we don't read + unlock in page_list;
488  * the caller (VM) cleans them up.
489  */
490 static int ceph_readpages(struct file *file, struct address_space *mapping,
491                           struct list_head *page_list, unsigned nr_pages)
492 {
493         struct inode *inode = file_inode(file);
494         struct ceph_fs_client *fsc = ceph_inode_to_client(inode);
495         struct ceph_file_info *fi = file->private_data;
496         struct ceph_rw_context *rw_ctx;
497         int rc = 0;
498         int max = 0;
499
500         if (ceph_inode(inode)->i_inline_version != CEPH_INLINE_NONE)
501                 return -EINVAL;
502
503         rc = ceph_readpages_from_fscache(mapping->host, mapping, page_list,
504                                          &nr_pages);
505
506         if (rc == 0)
507                 goto out;
508
509         rw_ctx = ceph_find_rw_context(fi);
510         max = fsc->mount_options->rsize >> PAGE_SHIFT;
511         dout("readpages %p file %p ctx %p nr_pages %d max %d\n",
512              inode, file, rw_ctx, nr_pages, max);
513         while (!list_empty(page_list)) {
514                 rc = start_read(inode, rw_ctx, page_list, max);
515                 if (rc < 0)
516                         goto out;
517         }
518 out:
519         ceph_fscache_readpages_cancel(inode, page_list);
520
521         dout("readpages %p file %p ret %d\n", inode, file, rc);
522         return rc;
523 }
524
525 struct ceph_writeback_ctl
526 {
527         loff_t i_size;
528         u64 truncate_size;
529         u32 truncate_seq;
530         bool size_stable;
531         bool head_snapc;
532 };
533
534 /*
535  * Get ref for the oldest snapc for an inode with dirty data... that is, the
536  * only snap context we are allowed to write back.
537  */
538 static struct ceph_snap_context *
539 get_oldest_context(struct inode *inode, struct ceph_writeback_ctl *ctl,
540                    struct ceph_snap_context *page_snapc)
541 {
542         struct ceph_inode_info *ci = ceph_inode(inode);
543         struct ceph_snap_context *snapc = NULL;
544         struct ceph_cap_snap *capsnap = NULL;
545
546         spin_lock(&ci->i_ceph_lock);
547         list_for_each_entry(capsnap, &ci->i_cap_snaps, ci_item) {
548                 dout(" cap_snap %p snapc %p has %d dirty pages\n", capsnap,
549                      capsnap->context, capsnap->dirty_pages);
550                 if (!capsnap->dirty_pages)
551                         continue;
552
553                 /* get i_size, truncate_{seq,size} for page_snapc? */
554                 if (snapc && capsnap->context != page_snapc)
555                         continue;
556
557                 if (ctl) {
558                         if (capsnap->writing) {
559                                 ctl->i_size = i_size_read(inode);
560                                 ctl->size_stable = false;
561                         } else {
562                                 ctl->i_size = capsnap->size;
563                                 ctl->size_stable = true;
564                         }
565                         ctl->truncate_size = capsnap->truncate_size;
566                         ctl->truncate_seq = capsnap->truncate_seq;
567                         ctl->head_snapc = false;
568                 }
569
570                 if (snapc)
571                         break;
572
573                 snapc = ceph_get_snap_context(capsnap->context);
574                 if (!page_snapc ||
575                     page_snapc == snapc ||
576                     page_snapc->seq > snapc->seq)
577                         break;
578         }
579         if (!snapc && ci->i_wrbuffer_ref_head) {
580                 snapc = ceph_get_snap_context(ci->i_head_snapc);
581                 dout(" head snapc %p has %d dirty pages\n",
582                      snapc, ci->i_wrbuffer_ref_head);
583                 if (ctl) {
584                         ctl->i_size = i_size_read(inode);
585                         ctl->truncate_size = ci->i_truncate_size;
586                         ctl->truncate_seq = ci->i_truncate_seq;
587                         ctl->size_stable = false;
588                         ctl->head_snapc = true;
589                 }
590         }
591         spin_unlock(&ci->i_ceph_lock);
592         return snapc;
593 }
594
595 static u64 get_writepages_data_length(struct inode *inode,
596                                       struct page *page, u64 start)
597 {
598         struct ceph_inode_info *ci = ceph_inode(inode);
599         struct ceph_snap_context *snapc = page_snap_context(page);
600         struct ceph_cap_snap *capsnap = NULL;
601         u64 end = i_size_read(inode);
602
603         if (snapc != ci->i_head_snapc) {
604                 bool found = false;
605                 spin_lock(&ci->i_ceph_lock);
606                 list_for_each_entry(capsnap, &ci->i_cap_snaps, ci_item) {
607                         if (capsnap->context == snapc) {
608                                 if (!capsnap->writing)
609                                         end = capsnap->size;
610                                 found = true;
611                                 break;
612                         }
613                 }
614                 spin_unlock(&ci->i_ceph_lock);
615                 WARN_ON(!found);
616         }
617         if (end > page_offset(page) + PAGE_SIZE)
618                 end = page_offset(page) + PAGE_SIZE;
619         return end > start ? end - start : 0;
620 }
621
622 /*
623  * do a synchronous write on N pages
624  */
625 static int ceph_sync_writepages(struct ceph_fs_client *fsc,
626                                 struct ceph_vino vino,
627                                 struct ceph_file_layout *layout,
628                                 struct ceph_snap_context *snapc,
629                                 u64 off, u64 len,
630                                 u32 truncate_seq, u64 truncate_size,
631                                 struct timespec64 *mtime,
632                                 struct page **pages, int num_pages)
633 {
634         struct ceph_osd_client *osdc = &fsc->client->osdc;
635         struct ceph_osd_request *req;
636         int rc = 0;
637         int page_align = off & ~PAGE_MASK;
638
639         req = ceph_osdc_new_request(osdc, layout, vino, off, &len, 0, 1,
640                                     CEPH_OSD_OP_WRITE, CEPH_OSD_FLAG_WRITE,
641                                     snapc, truncate_seq, truncate_size,
642                                     true);
643         if (IS_ERR(req))
644                 return PTR_ERR(req);
645
646         /* it may be a short write due to an object boundary */
647         osd_req_op_extent_osd_data_pages(req, 0, pages, len, page_align,
648                                 false, false);
649         dout("writepages %llu~%llu (%llu bytes)\n", off, len, len);
650
651         req->r_mtime = *mtime;
652         rc = ceph_osdc_start_request(osdc, req, true);
653         if (!rc)
654                 rc = ceph_osdc_wait_request(osdc, req);
655
656         ceph_update_write_latency(&fsc->mdsc->metric, req->r_start_latency,
657                                   req->r_end_latency, rc);
658
659         ceph_osdc_put_request(req);
660         if (rc == 0)
661                 rc = len;
662         dout("writepages result %d\n", rc);
663         return rc;
664 }
665
666 /*
667  * Write a single page, but leave the page locked.
668  *
669  * If we get a write error, mark the mapping for error, but still adjust the
670  * dirty page accounting (i.e., page is no longer dirty).
671  */
672 static int writepage_nounlock(struct page *page, struct writeback_control *wbc)
673 {
674         struct inode *inode;
675         struct ceph_inode_info *ci;
676         struct ceph_fs_client *fsc;
677         struct ceph_snap_context *snapc, *oldest;
678         loff_t page_off = page_offset(page);
679         int err, len = PAGE_SIZE;
680         struct ceph_writeback_ctl ceph_wbc;
681
682         dout("writepage %p idx %lu\n", page, page->index);
683
684         inode = page->mapping->host;
685         ci = ceph_inode(inode);
686         fsc = ceph_inode_to_client(inode);
687
688         /* verify this is a writeable snap context */
689         snapc = page_snap_context(page);
690         if (!snapc) {
691                 dout("writepage %p page %p not dirty?\n", inode, page);
692                 return 0;
693         }
694         oldest = get_oldest_context(inode, &ceph_wbc, snapc);
695         if (snapc->seq > oldest->seq) {
696                 dout("writepage %p page %p snapc %p not writeable - noop\n",
697                      inode, page, snapc);
698                 /* we should only noop if called by kswapd */
699                 WARN_ON(!(current->flags & PF_MEMALLOC));
700                 ceph_put_snap_context(oldest);
701                 redirty_page_for_writepage(wbc, page);
702                 return 0;
703         }
704         ceph_put_snap_context(oldest);
705
706         /* is this a partial page at end of file? */
707         if (page_off >= ceph_wbc.i_size) {
708                 dout("%p page eof %llu\n", page, ceph_wbc.i_size);
709                 page->mapping->a_ops->invalidatepage(page, 0, PAGE_SIZE);
710                 return 0;
711         }
712
713         if (ceph_wbc.i_size < page_off + len)
714                 len = ceph_wbc.i_size - page_off;
715
716         dout("writepage %p page %p index %lu on %llu~%u snapc %p seq %lld\n",
717              inode, page, page->index, page_off, len, snapc, snapc->seq);
718
719         if (atomic_long_inc_return(&fsc->writeback_count) >
720             CONGESTION_ON_THRESH(fsc->mount_options->congestion_kb))
721                 set_bdi_congested(inode_to_bdi(inode), BLK_RW_ASYNC);
722
723         set_page_writeback(page);
724         err = ceph_sync_writepages(fsc, ceph_vino(inode),
725                                    &ci->i_layout, snapc, page_off, len,
726                                    ceph_wbc.truncate_seq,
727                                    ceph_wbc.truncate_size,
728                                    &inode->i_mtime, &page, 1);
729         if (err < 0) {
730                 struct writeback_control tmp_wbc;
731                 if (!wbc)
732                         wbc = &tmp_wbc;
733                 if (err == -ERESTARTSYS) {
734                         /* killed by SIGKILL */
735                         dout("writepage interrupted page %p\n", page);
736                         redirty_page_for_writepage(wbc, page);
737                         end_page_writeback(page);
738                         return err;
739                 }
740                 if (err == -EBLACKLISTED)
741                         fsc->blacklisted = true;
742                 dout("writepage setting page/mapping error %d %p\n",
743                      err, page);
744                 mapping_set_error(&inode->i_data, err);
745                 wbc->pages_skipped++;
746         } else {
747                 dout("writepage cleaned page %p\n", page);
748                 err = 0;  /* vfs expects us to return 0 */
749         }
750         page->private = 0;
751         ClearPagePrivate(page);
752         end_page_writeback(page);
753         ceph_put_wrbuffer_cap_refs(ci, 1, snapc);
754         ceph_put_snap_context(snapc);  /* page's reference */
755
756         if (atomic_long_dec_return(&fsc->writeback_count) <
757             CONGESTION_OFF_THRESH(fsc->mount_options->congestion_kb))
758                 clear_bdi_congested(inode_to_bdi(inode), BLK_RW_ASYNC);
759
760         return err;
761 }
762
763 static int ceph_writepage(struct page *page, struct writeback_control *wbc)
764 {
765         int err;
766         struct inode *inode = page->mapping->host;
767         BUG_ON(!inode);
768         ihold(inode);
769         err = writepage_nounlock(page, wbc);
770         if (err == -ERESTARTSYS) {
771                 /* direct memory reclaimer was killed by SIGKILL. return 0
772                  * to prevent caller from setting mapping/page error */
773                 err = 0;
774         }
775         unlock_page(page);
776         iput(inode);
777         return err;
778 }
779
780 /*
781  * async writeback completion handler.
782  *
783  * If we get an error, set the mapping error bit, but not the individual
784  * page error bits.
785  */
786 static void writepages_finish(struct ceph_osd_request *req)
787 {
788         struct inode *inode = req->r_inode;
789         struct ceph_inode_info *ci = ceph_inode(inode);
790         struct ceph_osd_data *osd_data;
791         struct page *page;
792         int num_pages, total_pages = 0;
793         int i, j;
794         int rc = req->r_result;
795         struct ceph_snap_context *snapc = req->r_snapc;
796         struct address_space *mapping = inode->i_mapping;
797         struct ceph_fs_client *fsc = ceph_inode_to_client(inode);
798         bool remove_page;
799
800         dout("writepages_finish %p rc %d\n", inode, rc);
801         if (rc < 0) {
802                 mapping_set_error(mapping, rc);
803                 ceph_set_error_write(ci);
804                 if (rc == -EBLACKLISTED)
805                         fsc->blacklisted = true;
806         } else {
807                 ceph_clear_error_write(ci);
808         }
809
810         ceph_update_write_latency(&fsc->mdsc->metric, req->r_start_latency,
811                                   req->r_end_latency, rc);
812
813         /*
814          * We lost the cache cap, need to truncate the page before
815          * it is unlocked, otherwise we'd truncate it later in the
816          * page truncation thread, possibly losing some data that
817          * raced its way in
818          */
819         remove_page = !(ceph_caps_issued(ci) &
820                         (CEPH_CAP_FILE_CACHE|CEPH_CAP_FILE_LAZYIO));
821
822         /* clean all pages */
823         for (i = 0; i < req->r_num_ops; i++) {
824                 if (req->r_ops[i].op != CEPH_OSD_OP_WRITE)
825                         break;
826
827                 osd_data = osd_req_op_extent_osd_data(req, i);
828                 BUG_ON(osd_data->type != CEPH_OSD_DATA_TYPE_PAGES);
829                 num_pages = calc_pages_for((u64)osd_data->alignment,
830                                            (u64)osd_data->length);
831                 total_pages += num_pages;
832                 for (j = 0; j < num_pages; j++) {
833                         page = osd_data->pages[j];
834                         BUG_ON(!page);
835                         WARN_ON(!PageUptodate(page));
836
837                         if (atomic_long_dec_return(&fsc->writeback_count) <
838                              CONGESTION_OFF_THRESH(
839                                         fsc->mount_options->congestion_kb))
840                                 clear_bdi_congested(inode_to_bdi(inode),
841                                                     BLK_RW_ASYNC);
842
843                         ceph_put_snap_context(page_snap_context(page));
844                         page->private = 0;
845                         ClearPagePrivate(page);
846                         dout("unlocking %p\n", page);
847                         end_page_writeback(page);
848
849                         if (remove_page)
850                                 generic_error_remove_page(inode->i_mapping,
851                                                           page);
852
853                         unlock_page(page);
854                 }
855                 dout("writepages_finish %p wrote %llu bytes cleaned %d pages\n",
856                      inode, osd_data->length, rc >= 0 ? num_pages : 0);
857
858                 release_pages(osd_data->pages, num_pages);
859         }
860
861         ceph_put_wrbuffer_cap_refs(ci, total_pages, snapc);
862
863         osd_data = osd_req_op_extent_osd_data(req, 0);
864         if (osd_data->pages_from_pool)
865                 mempool_free(osd_data->pages, ceph_wb_pagevec_pool);
866         else
867                 kfree(osd_data->pages);
868         ceph_osdc_put_request(req);
869 }
870
871 /*
872  * initiate async writeback
873  */
874 static int ceph_writepages_start(struct address_space *mapping,
875                                  struct writeback_control *wbc)
876 {
877         struct inode *inode = mapping->host;
878         struct ceph_inode_info *ci = ceph_inode(inode);
879         struct ceph_fs_client *fsc = ceph_inode_to_client(inode);
880         struct ceph_vino vino = ceph_vino(inode);
881         pgoff_t index, start_index, end = -1;
882         struct ceph_snap_context *snapc = NULL, *last_snapc = NULL, *pgsnapc;
883         struct pagevec pvec;
884         int rc = 0;
885         unsigned int wsize = i_blocksize(inode);
886         struct ceph_osd_request *req = NULL;
887         struct ceph_writeback_ctl ceph_wbc;
888         bool should_loop, range_whole = false;
889         bool done = false;
890
891         dout("writepages_start %p (mode=%s)\n", inode,
892              wbc->sync_mode == WB_SYNC_NONE ? "NONE" :
893              (wbc->sync_mode == WB_SYNC_ALL ? "ALL" : "HOLD"));
894
895         if (READ_ONCE(fsc->mount_state) == CEPH_MOUNT_SHUTDOWN) {
896                 if (ci->i_wrbuffer_ref > 0) {
897                         pr_warn_ratelimited(
898                                 "writepage_start %p %lld forced umount\n",
899                                 inode, ceph_ino(inode));
900                 }
901                 mapping_set_error(mapping, -EIO);
902                 return -EIO; /* we're in a forced umount, don't write! */
903         }
904         if (fsc->mount_options->wsize < wsize)
905                 wsize = fsc->mount_options->wsize;
906
907         pagevec_init(&pvec);
908
909         start_index = wbc->range_cyclic ? mapping->writeback_index : 0;
910         index = start_index;
911
912 retry:
913         /* find oldest snap context with dirty data */
914         snapc = get_oldest_context(inode, &ceph_wbc, NULL);
915         if (!snapc) {
916                 /* hmm, why does writepages get called when there
917                    is no dirty data? */
918                 dout(" no snap context with dirty data?\n");
919                 goto out;
920         }
921         dout(" oldest snapc is %p seq %lld (%d snaps)\n",
922              snapc, snapc->seq, snapc->num_snaps);
923
924         should_loop = false;
925         if (ceph_wbc.head_snapc && snapc != last_snapc) {
926                 /* where to start/end? */
927                 if (wbc->range_cyclic) {
928                         index = start_index;
929                         end = -1;
930                         if (index > 0)
931                                 should_loop = true;
932                         dout(" cyclic, start at %lu\n", index);
933                 } else {
934                         index = wbc->range_start >> PAGE_SHIFT;
935                         end = wbc->range_end >> PAGE_SHIFT;
936                         if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
937                                 range_whole = true;
938                         dout(" not cyclic, %lu to %lu\n", index, end);
939                 }
940         } else if (!ceph_wbc.head_snapc) {
941                 /* Do not respect wbc->range_{start,end}. Dirty pages
942                  * in that range can be associated with newer snapc.
943                  * They are not writeable until we write all dirty pages
944                  * associated with 'snapc' get written */
945                 if (index > 0)
946                         should_loop = true;
947                 dout(" non-head snapc, range whole\n");
948         }
949
950         ceph_put_snap_context(last_snapc);
951         last_snapc = snapc;
952
953         while (!done && index <= end) {
954                 int num_ops = 0, op_idx;
955                 unsigned i, pvec_pages, max_pages, locked_pages = 0;
956                 struct page **pages = NULL, **data_pages;
957                 struct page *page;
958                 pgoff_t strip_unit_end = 0;
959                 u64 offset = 0, len = 0;
960                 bool from_pool = false;
961
962                 max_pages = wsize >> PAGE_SHIFT;
963
964 get_more_pages:
965                 pvec_pages = pagevec_lookup_range_tag(&pvec, mapping, &index,
966                                                 end, PAGECACHE_TAG_DIRTY);
967                 dout("pagevec_lookup_range_tag got %d\n", pvec_pages);
968                 if (!pvec_pages && !locked_pages)
969                         break;
970                 for (i = 0; i < pvec_pages && locked_pages < max_pages; i++) {
971                         page = pvec.pages[i];
972                         dout("? %p idx %lu\n", page, page->index);
973                         if (locked_pages == 0)
974                                 lock_page(page);  /* first page */
975                         else if (!trylock_page(page))
976                                 break;
977
978                         /* only dirty pages, or our accounting breaks */
979                         if (unlikely(!PageDirty(page)) ||
980                             unlikely(page->mapping != mapping)) {
981                                 dout("!dirty or !mapping %p\n", page);
982                                 unlock_page(page);
983                                 continue;
984                         }
985                         /* only if matching snap context */
986                         pgsnapc = page_snap_context(page);
987                         if (pgsnapc != snapc) {
988                                 dout("page snapc %p %lld != oldest %p %lld\n",
989                                      pgsnapc, pgsnapc->seq, snapc, snapc->seq);
990                                 if (!should_loop &&
991                                     !ceph_wbc.head_snapc &&
992                                     wbc->sync_mode != WB_SYNC_NONE)
993                                         should_loop = true;
994                                 unlock_page(page);
995                                 continue;
996                         }
997                         if (page_offset(page) >= ceph_wbc.i_size) {
998                                 dout("%p page eof %llu\n",
999                                      page, ceph_wbc.i_size);
1000                                 if ((ceph_wbc.size_stable ||
1001                                     page_offset(page) >= i_size_read(inode)) &&
1002                                     clear_page_dirty_for_io(page))
1003                                         mapping->a_ops->invalidatepage(page,
1004                                                                 0, PAGE_SIZE);
1005                                 unlock_page(page);
1006                                 continue;
1007                         }
1008                         if (strip_unit_end && (page->index > strip_unit_end)) {
1009                                 dout("end of strip unit %p\n", page);
1010                                 unlock_page(page);
1011                                 break;
1012                         }
1013                         if (PageWriteback(page)) {
1014                                 if (wbc->sync_mode == WB_SYNC_NONE) {
1015                                         dout("%p under writeback\n", page);
1016                                         unlock_page(page);
1017                                         continue;
1018                                 }
1019                                 dout("waiting on writeback %p\n", page);
1020                                 wait_on_page_writeback(page);
1021                         }
1022
1023                         if (!clear_page_dirty_for_io(page)) {
1024                                 dout("%p !clear_page_dirty_for_io\n", page);
1025                                 unlock_page(page);
1026                                 continue;
1027                         }
1028
1029                         /*
1030                          * We have something to write.  If this is
1031                          * the first locked page this time through,
1032                          * calculate max possinle write size and
1033                          * allocate a page array
1034                          */
1035                         if (locked_pages == 0) {
1036                                 u64 objnum;
1037                                 u64 objoff;
1038                                 u32 xlen;
1039
1040                                 /* prepare async write request */
1041                                 offset = (u64)page_offset(page);
1042                                 ceph_calc_file_object_mapping(&ci->i_layout,
1043                                                               offset, wsize,
1044                                                               &objnum, &objoff,
1045                                                               &xlen);
1046                                 len = xlen;
1047
1048                                 num_ops = 1;
1049                                 strip_unit_end = page->index +
1050                                         ((len - 1) >> PAGE_SHIFT);
1051
1052                                 BUG_ON(pages);
1053                                 max_pages = calc_pages_for(0, (u64)len);
1054                                 pages = kmalloc_array(max_pages,
1055                                                       sizeof(*pages),
1056                                                       GFP_NOFS);
1057                                 if (!pages) {
1058                                         from_pool = true;
1059                                         pages = mempool_alloc(ceph_wb_pagevec_pool, GFP_NOFS);
1060                                         BUG_ON(!pages);
1061                                 }
1062
1063                                 len = 0;
1064                         } else if (page->index !=
1065                                    (offset + len) >> PAGE_SHIFT) {
1066                                 if (num_ops >= (from_pool ?  CEPH_OSD_SLAB_OPS :
1067                                                              CEPH_OSD_MAX_OPS)) {
1068                                         redirty_page_for_writepage(wbc, page);
1069                                         unlock_page(page);
1070                                         break;
1071                                 }
1072
1073                                 num_ops++;
1074                                 offset = (u64)page_offset(page);
1075                                 len = 0;
1076                         }
1077
1078                         /* note position of first page in pvec */
1079                         dout("%p will write page %p idx %lu\n",
1080                              inode, page, page->index);
1081
1082                         if (atomic_long_inc_return(&fsc->writeback_count) >
1083                             CONGESTION_ON_THRESH(
1084                                     fsc->mount_options->congestion_kb)) {
1085                                 set_bdi_congested(inode_to_bdi(inode),
1086                                                   BLK_RW_ASYNC);
1087                         }
1088
1089
1090                         pages[locked_pages++] = page;
1091                         pvec.pages[i] = NULL;
1092
1093                         len += PAGE_SIZE;
1094                 }
1095
1096                 /* did we get anything? */
1097                 if (!locked_pages)
1098                         goto release_pvec_pages;
1099                 if (i) {
1100                         unsigned j, n = 0;
1101                         /* shift unused page to beginning of pvec */
1102                         for (j = 0; j < pvec_pages; j++) {
1103                                 if (!pvec.pages[j])
1104                                         continue;
1105                                 if (n < j)
1106                                         pvec.pages[n] = pvec.pages[j];
1107                                 n++;
1108                         }
1109                         pvec.nr = n;
1110
1111                         if (pvec_pages && i == pvec_pages &&
1112                             locked_pages < max_pages) {
1113                                 dout("reached end pvec, trying for more\n");
1114                                 pagevec_release(&pvec);
1115                                 goto get_more_pages;
1116                         }
1117                 }
1118
1119 new_request:
1120                 offset = page_offset(pages[0]);
1121                 len = wsize;
1122
1123                 req = ceph_osdc_new_request(&fsc->client->osdc,
1124                                         &ci->i_layout, vino,
1125                                         offset, &len, 0, num_ops,
1126                                         CEPH_OSD_OP_WRITE, CEPH_OSD_FLAG_WRITE,
1127                                         snapc, ceph_wbc.truncate_seq,
1128                                         ceph_wbc.truncate_size, false);
1129                 if (IS_ERR(req)) {
1130                         req = ceph_osdc_new_request(&fsc->client->osdc,
1131                                                 &ci->i_layout, vino,
1132                                                 offset, &len, 0,
1133                                                 min(num_ops,
1134                                                     CEPH_OSD_SLAB_OPS),
1135                                                 CEPH_OSD_OP_WRITE,
1136                                                 CEPH_OSD_FLAG_WRITE,
1137                                                 snapc, ceph_wbc.truncate_seq,
1138                                                 ceph_wbc.truncate_size, true);
1139                         BUG_ON(IS_ERR(req));
1140                 }
1141                 BUG_ON(len < page_offset(pages[locked_pages - 1]) +
1142                              PAGE_SIZE - offset);
1143
1144                 req->r_callback = writepages_finish;
1145                 req->r_inode = inode;
1146
1147                 /* Format the osd request message and submit the write */
1148                 len = 0;
1149                 data_pages = pages;
1150                 op_idx = 0;
1151                 for (i = 0; i < locked_pages; i++) {
1152                         u64 cur_offset = page_offset(pages[i]);
1153                         if (offset + len != cur_offset) {
1154                                 if (op_idx + 1 == req->r_num_ops)
1155                                         break;
1156                                 osd_req_op_extent_dup_last(req, op_idx,
1157                                                            cur_offset - offset);
1158                                 dout("writepages got pages at %llu~%llu\n",
1159                                      offset, len);
1160                                 osd_req_op_extent_osd_data_pages(req, op_idx,
1161                                                         data_pages, len, 0,
1162                                                         from_pool, false);
1163                                 osd_req_op_extent_update(req, op_idx, len);
1164
1165                                 len = 0;
1166                                 offset = cur_offset; 
1167                                 data_pages = pages + i;
1168                                 op_idx++;
1169                         }
1170
1171                         set_page_writeback(pages[i]);
1172                         len += PAGE_SIZE;
1173                 }
1174
1175                 if (ceph_wbc.size_stable) {
1176                         len = min(len, ceph_wbc.i_size - offset);
1177                 } else if (i == locked_pages) {
1178                         /* writepages_finish() clears writeback pages
1179                          * according to the data length, so make sure
1180                          * data length covers all locked pages */
1181                         u64 min_len = len + 1 - PAGE_SIZE;
1182                         len = get_writepages_data_length(inode, pages[i - 1],
1183                                                          offset);
1184                         len = max(len, min_len);
1185                 }
1186                 dout("writepages got pages at %llu~%llu\n", offset, len);
1187
1188                 osd_req_op_extent_osd_data_pages(req, op_idx, data_pages, len,
1189                                                  0, from_pool, false);
1190                 osd_req_op_extent_update(req, op_idx, len);
1191
1192                 BUG_ON(op_idx + 1 != req->r_num_ops);
1193
1194                 from_pool = false;
1195                 if (i < locked_pages) {
1196                         BUG_ON(num_ops <= req->r_num_ops);
1197                         num_ops -= req->r_num_ops;
1198                         locked_pages -= i;
1199
1200                         /* allocate new pages array for next request */
1201                         data_pages = pages;
1202                         pages = kmalloc_array(locked_pages, sizeof(*pages),
1203                                               GFP_NOFS);
1204                         if (!pages) {
1205                                 from_pool = true;
1206                                 pages = mempool_alloc(ceph_wb_pagevec_pool, GFP_NOFS);
1207                                 BUG_ON(!pages);
1208                         }
1209                         memcpy(pages, data_pages + i,
1210                                locked_pages * sizeof(*pages));
1211                         memset(data_pages + i, 0,
1212                                locked_pages * sizeof(*pages));
1213                 } else {
1214                         BUG_ON(num_ops != req->r_num_ops);
1215                         index = pages[i - 1]->index + 1;
1216                         /* request message now owns the pages array */
1217                         pages = NULL;
1218                 }
1219
1220                 req->r_mtime = inode->i_mtime;
1221                 rc = ceph_osdc_start_request(&fsc->client->osdc, req, true);
1222                 BUG_ON(rc);
1223                 req = NULL;
1224
1225                 wbc->nr_to_write -= i;
1226                 if (pages)
1227                         goto new_request;
1228
1229                 /*
1230                  * We stop writing back only if we are not doing
1231                  * integrity sync. In case of integrity sync we have to
1232                  * keep going until we have written all the pages
1233                  * we tagged for writeback prior to entering this loop.
1234                  */
1235                 if (wbc->nr_to_write <= 0 && wbc->sync_mode == WB_SYNC_NONE)
1236                         done = true;
1237
1238 release_pvec_pages:
1239                 dout("pagevec_release on %d pages (%p)\n", (int)pvec.nr,
1240                      pvec.nr ? pvec.pages[0] : NULL);
1241                 pagevec_release(&pvec);
1242         }
1243
1244         if (should_loop && !done) {
1245                 /* more to do; loop back to beginning of file */
1246                 dout("writepages looping back to beginning of file\n");
1247                 end = start_index - 1; /* OK even when start_index == 0 */
1248
1249                 /* to write dirty pages associated with next snapc,
1250                  * we need to wait until current writes complete */
1251                 if (wbc->sync_mode != WB_SYNC_NONE &&
1252                     start_index == 0 && /* all dirty pages were checked */
1253                     !ceph_wbc.head_snapc) {
1254                         struct page *page;
1255                         unsigned i, nr;
1256                         index = 0;
1257                         while ((index <= end) &&
1258                                (nr = pagevec_lookup_tag(&pvec, mapping, &index,
1259                                                 PAGECACHE_TAG_WRITEBACK))) {
1260                                 for (i = 0; i < nr; i++) {
1261                                         page = pvec.pages[i];
1262                                         if (page_snap_context(page) != snapc)
1263                                                 continue;
1264                                         wait_on_page_writeback(page);
1265                                 }
1266                                 pagevec_release(&pvec);
1267                                 cond_resched();
1268                         }
1269                 }
1270
1271                 start_index = 0;
1272                 index = 0;
1273                 goto retry;
1274         }
1275
1276         if (wbc->range_cyclic || (range_whole && wbc->nr_to_write > 0))
1277                 mapping->writeback_index = index;
1278
1279 out:
1280         ceph_osdc_put_request(req);
1281         ceph_put_snap_context(last_snapc);
1282         dout("writepages dend - startone, rc = %d\n", rc);
1283         return rc;
1284 }
1285
1286
1287
1288 /*
1289  * See if a given @snapc is either writeable, or already written.
1290  */
1291 static int context_is_writeable_or_written(struct inode *inode,
1292                                            struct ceph_snap_context *snapc)
1293 {
1294         struct ceph_snap_context *oldest = get_oldest_context(inode, NULL, NULL);
1295         int ret = !oldest || snapc->seq <= oldest->seq;
1296
1297         ceph_put_snap_context(oldest);
1298         return ret;
1299 }
1300
1301 /*
1302  * We are only allowed to write into/dirty the page if the page is
1303  * clean, or already dirty within the same snap context.
1304  *
1305  * called with page locked.
1306  * return success with page locked,
1307  * or any failure (incl -EAGAIN) with page unlocked.
1308  */
1309 static int ceph_update_writeable_page(struct file *file,
1310                             loff_t pos, unsigned len,
1311                             struct page *page)
1312 {
1313         struct inode *inode = file_inode(file);
1314         struct ceph_fs_client *fsc = ceph_inode_to_client(inode);
1315         struct ceph_inode_info *ci = ceph_inode(inode);
1316         loff_t page_off = pos & PAGE_MASK;
1317         int pos_in_page = pos & ~PAGE_MASK;
1318         int end_in_page = pos_in_page + len;
1319         loff_t i_size;
1320         int r;
1321         struct ceph_snap_context *snapc, *oldest;
1322
1323         if (READ_ONCE(fsc->mount_state) == CEPH_MOUNT_SHUTDOWN) {
1324                 dout(" page %p forced umount\n", page);
1325                 unlock_page(page);
1326                 return -EIO;
1327         }
1328
1329 retry_locked:
1330         /* writepages currently holds page lock, but if we change that later, */
1331         wait_on_page_writeback(page);
1332
1333         snapc = page_snap_context(page);
1334         if (snapc && snapc != ci->i_head_snapc) {
1335                 /*
1336                  * this page is already dirty in another (older) snap
1337                  * context!  is it writeable now?
1338                  */
1339                 oldest = get_oldest_context(inode, NULL, NULL);
1340                 if (snapc->seq > oldest->seq) {
1341                         ceph_put_snap_context(oldest);
1342                         dout(" page %p snapc %p not current or oldest\n",
1343                              page, snapc);
1344                         /*
1345                          * queue for writeback, and wait for snapc to
1346                          * be writeable or written
1347                          */
1348                         snapc = ceph_get_snap_context(snapc);
1349                         unlock_page(page);
1350                         ceph_queue_writeback(inode);
1351                         r = wait_event_killable(ci->i_cap_wq,
1352                                context_is_writeable_or_written(inode, snapc));
1353                         ceph_put_snap_context(snapc);
1354                         if (r == -ERESTARTSYS)
1355                                 return r;
1356                         return -EAGAIN;
1357                 }
1358                 ceph_put_snap_context(oldest);
1359
1360                 /* yay, writeable, do it now (without dropping page lock) */
1361                 dout(" page %p snapc %p not current, but oldest\n",
1362                      page, snapc);
1363                 if (!clear_page_dirty_for_io(page))
1364                         goto retry_locked;
1365                 r = writepage_nounlock(page, NULL);
1366                 if (r < 0)
1367                         goto fail_unlock;
1368                 goto retry_locked;
1369         }
1370
1371         if (PageUptodate(page)) {
1372                 dout(" page %p already uptodate\n", page);
1373                 return 0;
1374         }
1375
1376         /* full page? */
1377         if (pos_in_page == 0 && len == PAGE_SIZE)
1378                 return 0;
1379
1380         /* past end of file? */
1381         i_size = i_size_read(inode);
1382
1383         if (page_off >= i_size ||
1384             (pos_in_page == 0 && (pos+len) >= i_size &&
1385              end_in_page - pos_in_page != PAGE_SIZE)) {
1386                 dout(" zeroing %p 0 - %d and %d - %d\n",
1387                      page, pos_in_page, end_in_page, (int)PAGE_SIZE);
1388                 zero_user_segments(page,
1389                                    0, pos_in_page,
1390                                    end_in_page, PAGE_SIZE);
1391                 return 0;
1392         }
1393
1394         /* we need to read it. */
1395         r = ceph_do_readpage(file, page);
1396         if (r < 0) {
1397                 if (r == -EINPROGRESS)
1398                         return -EAGAIN;
1399                 goto fail_unlock;
1400         }
1401         goto retry_locked;
1402 fail_unlock:
1403         unlock_page(page);
1404         return r;
1405 }
1406
1407 /*
1408  * We are only allowed to write into/dirty the page if the page is
1409  * clean, or already dirty within the same snap context.
1410  */
1411 static int ceph_write_begin(struct file *file, struct address_space *mapping,
1412                             loff_t pos, unsigned len, unsigned flags,
1413                             struct page **pagep, void **fsdata)
1414 {
1415         struct inode *inode = file_inode(file);
1416         struct page *page;
1417         pgoff_t index = pos >> PAGE_SHIFT;
1418         int r;
1419
1420         do {
1421                 /* get a page */
1422                 page = grab_cache_page_write_begin(mapping, index, 0);
1423                 if (!page)
1424                         return -ENOMEM;
1425
1426                 dout("write_begin file %p inode %p page %p %d~%d\n", file,
1427                      inode, page, (int)pos, (int)len);
1428
1429                 r = ceph_update_writeable_page(file, pos, len, page);
1430                 if (r < 0)
1431                         put_page(page);
1432                 else
1433                         *pagep = page;
1434         } while (r == -EAGAIN);
1435
1436         return r;
1437 }
1438
1439 /*
1440  * we don't do anything in here that simple_write_end doesn't do
1441  * except adjust dirty page accounting
1442  */
1443 static int ceph_write_end(struct file *file, struct address_space *mapping,
1444                           loff_t pos, unsigned len, unsigned copied,
1445                           struct page *page, void *fsdata)
1446 {
1447         struct inode *inode = file_inode(file);
1448         bool check_cap = false;
1449
1450         dout("write_end file %p inode %p page %p %d~%d (%d)\n", file,
1451              inode, page, (int)pos, (int)copied, (int)len);
1452
1453         /* zero the stale part of the page if we did a short copy */
1454         if (!PageUptodate(page)) {
1455                 if (copied < len) {
1456                         copied = 0;
1457                         goto out;
1458                 }
1459                 SetPageUptodate(page);
1460         }
1461
1462         /* did file size increase? */
1463         if (pos+copied > i_size_read(inode))
1464                 check_cap = ceph_inode_set_size(inode, pos+copied);
1465
1466         set_page_dirty(page);
1467
1468 out:
1469         unlock_page(page);
1470         put_page(page);
1471
1472         if (check_cap)
1473                 ceph_check_caps(ceph_inode(inode), CHECK_CAPS_AUTHONLY, NULL);
1474
1475         return copied;
1476 }
1477
1478 /*
1479  * we set .direct_IO to indicate direct io is supported, but since we
1480  * intercept O_DIRECT reads and writes early, this function should
1481  * never get called.
1482  */
1483 static ssize_t ceph_direct_io(struct kiocb *iocb, struct iov_iter *iter)
1484 {
1485         WARN_ON(1);
1486         return -EINVAL;
1487 }
1488
1489 const struct address_space_operations ceph_aops = {
1490         .readpage = ceph_readpage,
1491         .readpages = ceph_readpages,
1492         .writepage = ceph_writepage,
1493         .writepages = ceph_writepages_start,
1494         .write_begin = ceph_write_begin,
1495         .write_end = ceph_write_end,
1496         .set_page_dirty = ceph_set_page_dirty,
1497         .invalidatepage = ceph_invalidatepage,
1498         .releasepage = ceph_releasepage,
1499         .direct_IO = ceph_direct_io,
1500 };
1501
1502 static void ceph_block_sigs(sigset_t *oldset)
1503 {
1504         sigset_t mask;
1505         siginitsetinv(&mask, sigmask(SIGKILL));
1506         sigprocmask(SIG_BLOCK, &mask, oldset);
1507 }
1508
1509 static void ceph_restore_sigs(sigset_t *oldset)
1510 {
1511         sigprocmask(SIG_SETMASK, oldset, NULL);
1512 }
1513
1514 /*
1515  * vm ops
1516  */
1517 static vm_fault_t ceph_filemap_fault(struct vm_fault *vmf)
1518 {
1519         struct vm_area_struct *vma = vmf->vma;
1520         struct inode *inode = file_inode(vma->vm_file);
1521         struct ceph_inode_info *ci = ceph_inode(inode);
1522         struct ceph_file_info *fi = vma->vm_file->private_data;
1523         struct page *pinned_page = NULL;
1524         loff_t off = vmf->pgoff << PAGE_SHIFT;
1525         int want, got, err;
1526         sigset_t oldset;
1527         vm_fault_t ret = VM_FAULT_SIGBUS;
1528
1529         ceph_block_sigs(&oldset);
1530
1531         dout("filemap_fault %p %llx.%llx %llu~%zd trying to get caps\n",
1532              inode, ceph_vinop(inode), off, (size_t)PAGE_SIZE);
1533         if (fi->fmode & CEPH_FILE_MODE_LAZY)
1534                 want = CEPH_CAP_FILE_CACHE | CEPH_CAP_FILE_LAZYIO;
1535         else
1536                 want = CEPH_CAP_FILE_CACHE;
1537
1538         got = 0;
1539         err = ceph_get_caps(vma->vm_file, CEPH_CAP_FILE_RD, want, -1,
1540                             &got, &pinned_page);
1541         if (err < 0)
1542                 goto out_restore;
1543
1544         dout("filemap_fault %p %llu~%zd got cap refs on %s\n",
1545              inode, off, (size_t)PAGE_SIZE, ceph_cap_string(got));
1546
1547         if ((got & (CEPH_CAP_FILE_CACHE | CEPH_CAP_FILE_LAZYIO)) ||
1548             ci->i_inline_version == CEPH_INLINE_NONE) {
1549                 CEPH_DEFINE_RW_CONTEXT(rw_ctx, got);
1550                 ceph_add_rw_context(fi, &rw_ctx);
1551                 ret = filemap_fault(vmf);
1552                 ceph_del_rw_context(fi, &rw_ctx);
1553                 dout("filemap_fault %p %llu~%zd drop cap refs %s ret %x\n",
1554                         inode, off, (size_t)PAGE_SIZE,
1555                                 ceph_cap_string(got), ret);
1556         } else
1557                 err = -EAGAIN;
1558
1559         if (pinned_page)
1560                 put_page(pinned_page);
1561         ceph_put_cap_refs(ci, got);
1562
1563         if (err != -EAGAIN)
1564                 goto out_restore;
1565
1566         /* read inline data */
1567         if (off >= PAGE_SIZE) {
1568                 /* does not support inline data > PAGE_SIZE */
1569                 ret = VM_FAULT_SIGBUS;
1570         } else {
1571                 struct address_space *mapping = inode->i_mapping;
1572                 struct page *page = find_or_create_page(mapping, 0,
1573                                                 mapping_gfp_constraint(mapping,
1574                                                 ~__GFP_FS));
1575                 if (!page) {
1576                         ret = VM_FAULT_OOM;
1577                         goto out_inline;
1578                 }
1579                 err = __ceph_do_getattr(inode, page,
1580                                          CEPH_STAT_CAP_INLINE_DATA, true);
1581                 if (err < 0 || off >= i_size_read(inode)) {
1582                         unlock_page(page);
1583                         put_page(page);
1584                         ret = vmf_error(err);
1585                         goto out_inline;
1586                 }
1587                 if (err < PAGE_SIZE)
1588                         zero_user_segment(page, err, PAGE_SIZE);
1589                 else
1590                         flush_dcache_page(page);
1591                 SetPageUptodate(page);
1592                 vmf->page = page;
1593                 ret = VM_FAULT_MAJOR | VM_FAULT_LOCKED;
1594 out_inline:
1595                 dout("filemap_fault %p %llu~%zd read inline data ret %x\n",
1596                      inode, off, (size_t)PAGE_SIZE, ret);
1597         }
1598 out_restore:
1599         ceph_restore_sigs(&oldset);
1600         if (err < 0)
1601                 ret = vmf_error(err);
1602
1603         return ret;
1604 }
1605
1606 /*
1607  * Reuse write_begin here for simplicity.
1608  */
1609 static vm_fault_t ceph_page_mkwrite(struct vm_fault *vmf)
1610 {
1611         struct vm_area_struct *vma = vmf->vma;
1612         struct inode *inode = file_inode(vma->vm_file);
1613         struct ceph_inode_info *ci = ceph_inode(inode);
1614         struct ceph_file_info *fi = vma->vm_file->private_data;
1615         struct ceph_cap_flush *prealloc_cf;
1616         struct page *page = vmf->page;
1617         loff_t off = page_offset(page);
1618         loff_t size = i_size_read(inode);
1619         size_t len;
1620         int want, got, err;
1621         sigset_t oldset;
1622         vm_fault_t ret = VM_FAULT_SIGBUS;
1623
1624         prealloc_cf = ceph_alloc_cap_flush();
1625         if (!prealloc_cf)
1626                 return VM_FAULT_OOM;
1627
1628         sb_start_pagefault(inode->i_sb);
1629         ceph_block_sigs(&oldset);
1630
1631         if (ci->i_inline_version != CEPH_INLINE_NONE) {
1632                 struct page *locked_page = NULL;
1633                 if (off == 0) {
1634                         lock_page(page);
1635                         locked_page = page;
1636                 }
1637                 err = ceph_uninline_data(vma->vm_file, locked_page);
1638                 if (locked_page)
1639                         unlock_page(locked_page);
1640                 if (err < 0)
1641                         goto out_free;
1642         }
1643
1644         if (off + PAGE_SIZE <= size)
1645                 len = PAGE_SIZE;
1646         else
1647                 len = size & ~PAGE_MASK;
1648
1649         dout("page_mkwrite %p %llx.%llx %llu~%zd getting caps i_size %llu\n",
1650              inode, ceph_vinop(inode), off, len, size);
1651         if (fi->fmode & CEPH_FILE_MODE_LAZY)
1652                 want = CEPH_CAP_FILE_BUFFER | CEPH_CAP_FILE_LAZYIO;
1653         else
1654                 want = CEPH_CAP_FILE_BUFFER;
1655
1656         got = 0;
1657         err = ceph_get_caps(vma->vm_file, CEPH_CAP_FILE_WR, want, off + len,
1658                             &got, NULL);
1659         if (err < 0)
1660                 goto out_free;
1661
1662         dout("page_mkwrite %p %llu~%zd got cap refs on %s\n",
1663              inode, off, len, ceph_cap_string(got));
1664
1665         /* Update time before taking page lock */
1666         file_update_time(vma->vm_file);
1667         inode_inc_iversion_raw(inode);
1668
1669         do {
1670                 lock_page(page);
1671
1672                 if (page_mkwrite_check_truncate(page, inode) < 0) {
1673                         unlock_page(page);
1674                         ret = VM_FAULT_NOPAGE;
1675                         break;
1676                 }
1677
1678                 err = ceph_update_writeable_page(vma->vm_file, off, len, page);
1679                 if (err >= 0) {
1680                         /* success.  we'll keep the page locked. */
1681                         set_page_dirty(page);
1682                         ret = VM_FAULT_LOCKED;
1683                 }
1684         } while (err == -EAGAIN);
1685
1686         if (ret == VM_FAULT_LOCKED ||
1687             ci->i_inline_version != CEPH_INLINE_NONE) {
1688                 int dirty;
1689                 spin_lock(&ci->i_ceph_lock);
1690                 ci->i_inline_version = CEPH_INLINE_NONE;
1691                 dirty = __ceph_mark_dirty_caps(ci, CEPH_CAP_FILE_WR,
1692                                                &prealloc_cf);
1693                 spin_unlock(&ci->i_ceph_lock);
1694                 if (dirty)
1695                         __mark_inode_dirty(inode, dirty);
1696         }
1697
1698         dout("page_mkwrite %p %llu~%zd dropping cap refs on %s ret %x\n",
1699              inode, off, len, ceph_cap_string(got), ret);
1700         ceph_put_cap_refs(ci, got);
1701 out_free:
1702         ceph_restore_sigs(&oldset);
1703         sb_end_pagefault(inode->i_sb);
1704         ceph_free_cap_flush(prealloc_cf);
1705         if (err < 0)
1706                 ret = vmf_error(err);
1707         return ret;
1708 }
1709
1710 void ceph_fill_inline_data(struct inode *inode, struct page *locked_page,
1711                            char *data, size_t len)
1712 {
1713         struct address_space *mapping = inode->i_mapping;
1714         struct page *page;
1715
1716         if (locked_page) {
1717                 page = locked_page;
1718         } else {
1719                 if (i_size_read(inode) == 0)
1720                         return;
1721                 page = find_or_create_page(mapping, 0,
1722                                            mapping_gfp_constraint(mapping,
1723                                            ~__GFP_FS));
1724                 if (!page)
1725                         return;
1726                 if (PageUptodate(page)) {
1727                         unlock_page(page);
1728                         put_page(page);
1729                         return;
1730                 }
1731         }
1732
1733         dout("fill_inline_data %p %llx.%llx len %zu locked_page %p\n",
1734              inode, ceph_vinop(inode), len, locked_page);
1735
1736         if (len > 0) {
1737                 void *kaddr = kmap_atomic(page);
1738                 memcpy(kaddr, data, len);
1739                 kunmap_atomic(kaddr);
1740         }
1741
1742         if (page != locked_page) {
1743                 if (len < PAGE_SIZE)
1744                         zero_user_segment(page, len, PAGE_SIZE);
1745                 else
1746                         flush_dcache_page(page);
1747
1748                 SetPageUptodate(page);
1749                 unlock_page(page);
1750                 put_page(page);
1751         }
1752 }
1753
1754 int ceph_uninline_data(struct file *filp, struct page *locked_page)
1755 {
1756         struct inode *inode = file_inode(filp);
1757         struct ceph_inode_info *ci = ceph_inode(inode);
1758         struct ceph_fs_client *fsc = ceph_inode_to_client(inode);
1759         struct ceph_osd_request *req;
1760         struct page *page = NULL;
1761         u64 len, inline_version;
1762         int err = 0;
1763         bool from_pagecache = false;
1764
1765         spin_lock(&ci->i_ceph_lock);
1766         inline_version = ci->i_inline_version;
1767         spin_unlock(&ci->i_ceph_lock);
1768
1769         dout("uninline_data %p %llx.%llx inline_version %llu\n",
1770              inode, ceph_vinop(inode), inline_version);
1771
1772         if (inline_version == 1 || /* initial version, no data */
1773             inline_version == CEPH_INLINE_NONE)
1774                 goto out;
1775
1776         if (locked_page) {
1777                 page = locked_page;
1778                 WARN_ON(!PageUptodate(page));
1779         } else if (ceph_caps_issued(ci) &
1780                    (CEPH_CAP_FILE_CACHE|CEPH_CAP_FILE_LAZYIO)) {
1781                 page = find_get_page(inode->i_mapping, 0);
1782                 if (page) {
1783                         if (PageUptodate(page)) {
1784                                 from_pagecache = true;
1785                                 lock_page(page);
1786                         } else {
1787                                 put_page(page);
1788                                 page = NULL;
1789                         }
1790                 }
1791         }
1792
1793         if (page) {
1794                 len = i_size_read(inode);
1795                 if (len > PAGE_SIZE)
1796                         len = PAGE_SIZE;
1797         } else {
1798                 page = __page_cache_alloc(GFP_NOFS);
1799                 if (!page) {
1800                         err = -ENOMEM;
1801                         goto out;
1802                 }
1803                 err = __ceph_do_getattr(inode, page,
1804                                         CEPH_STAT_CAP_INLINE_DATA, true);
1805                 if (err < 0) {
1806                         /* no inline data */
1807                         if (err == -ENODATA)
1808                                 err = 0;
1809                         goto out;
1810                 }
1811                 len = err;
1812         }
1813
1814         req = ceph_osdc_new_request(&fsc->client->osdc, &ci->i_layout,
1815                                     ceph_vino(inode), 0, &len, 0, 1,
1816                                     CEPH_OSD_OP_CREATE, CEPH_OSD_FLAG_WRITE,
1817                                     NULL, 0, 0, false);
1818         if (IS_ERR(req)) {
1819                 err = PTR_ERR(req);
1820                 goto out;
1821         }
1822
1823         req->r_mtime = inode->i_mtime;
1824         err = ceph_osdc_start_request(&fsc->client->osdc, req, false);
1825         if (!err)
1826                 err = ceph_osdc_wait_request(&fsc->client->osdc, req);
1827         ceph_osdc_put_request(req);
1828         if (err < 0)
1829                 goto out;
1830
1831         req = ceph_osdc_new_request(&fsc->client->osdc, &ci->i_layout,
1832                                     ceph_vino(inode), 0, &len, 1, 3,
1833                                     CEPH_OSD_OP_WRITE, CEPH_OSD_FLAG_WRITE,
1834                                     NULL, ci->i_truncate_seq,
1835                                     ci->i_truncate_size, false);
1836         if (IS_ERR(req)) {
1837                 err = PTR_ERR(req);
1838                 goto out;
1839         }
1840
1841         osd_req_op_extent_osd_data_pages(req, 1, &page, len, 0, false, false);
1842
1843         {
1844                 __le64 xattr_buf = cpu_to_le64(inline_version);
1845                 err = osd_req_op_xattr_init(req, 0, CEPH_OSD_OP_CMPXATTR,
1846                                             "inline_version", &xattr_buf,
1847                                             sizeof(xattr_buf),
1848                                             CEPH_OSD_CMPXATTR_OP_GT,
1849                                             CEPH_OSD_CMPXATTR_MODE_U64);
1850                 if (err)
1851                         goto out_put;
1852         }
1853
1854         {
1855                 char xattr_buf[32];
1856                 int xattr_len = snprintf(xattr_buf, sizeof(xattr_buf),
1857                                          "%llu", inline_version);
1858                 err = osd_req_op_xattr_init(req, 2, CEPH_OSD_OP_SETXATTR,
1859                                             "inline_version",
1860                                             xattr_buf, xattr_len, 0, 0);
1861                 if (err)
1862                         goto out_put;
1863         }
1864
1865         req->r_mtime = inode->i_mtime;
1866         err = ceph_osdc_start_request(&fsc->client->osdc, req, false);
1867         if (!err)
1868                 err = ceph_osdc_wait_request(&fsc->client->osdc, req);
1869
1870         ceph_update_write_latency(&fsc->mdsc->metric, req->r_start_latency,
1871                                   req->r_end_latency, err);
1872
1873 out_put:
1874         ceph_osdc_put_request(req);
1875         if (err == -ECANCELED)
1876                 err = 0;
1877 out:
1878         if (page && page != locked_page) {
1879                 if (from_pagecache) {
1880                         unlock_page(page);
1881                         put_page(page);
1882                 } else
1883                         __free_pages(page, 0);
1884         }
1885
1886         dout("uninline_data %p %llx.%llx inline_version %llu = %d\n",
1887              inode, ceph_vinop(inode), inline_version, err);
1888         return err;
1889 }
1890
1891 static const struct vm_operations_struct ceph_vmops = {
1892         .fault          = ceph_filemap_fault,
1893         .page_mkwrite   = ceph_page_mkwrite,
1894 };
1895
1896 int ceph_mmap(struct file *file, struct vm_area_struct *vma)
1897 {
1898         struct address_space *mapping = file->f_mapping;
1899
1900         if (!mapping->a_ops->readpage)
1901                 return -ENOEXEC;
1902         file_accessed(file);
1903         vma->vm_ops = &ceph_vmops;
1904         return 0;
1905 }
1906
1907 enum {
1908         POOL_READ       = 1,
1909         POOL_WRITE      = 2,
1910 };
1911
1912 static int __ceph_pool_perm_get(struct ceph_inode_info *ci,
1913                                 s64 pool, struct ceph_string *pool_ns)
1914 {
1915         struct ceph_fs_client *fsc = ceph_inode_to_client(&ci->vfs_inode);
1916         struct ceph_mds_client *mdsc = fsc->mdsc;
1917         struct ceph_osd_request *rd_req = NULL, *wr_req = NULL;
1918         struct rb_node **p, *parent;
1919         struct ceph_pool_perm *perm;
1920         struct page **pages;
1921         size_t pool_ns_len;
1922         int err = 0, err2 = 0, have = 0;
1923
1924         down_read(&mdsc->pool_perm_rwsem);
1925         p = &mdsc->pool_perm_tree.rb_node;
1926         while (*p) {
1927                 perm = rb_entry(*p, struct ceph_pool_perm, node);
1928                 if (pool < perm->pool)
1929                         p = &(*p)->rb_left;
1930                 else if (pool > perm->pool)
1931                         p = &(*p)->rb_right;
1932                 else {
1933                         int ret = ceph_compare_string(pool_ns,
1934                                                 perm->pool_ns,
1935                                                 perm->pool_ns_len);
1936                         if (ret < 0)
1937                                 p = &(*p)->rb_left;
1938                         else if (ret > 0)
1939                                 p = &(*p)->rb_right;
1940                         else {
1941                                 have = perm->perm;
1942                                 break;
1943                         }
1944                 }
1945         }
1946         up_read(&mdsc->pool_perm_rwsem);
1947         if (*p)
1948                 goto out;
1949
1950         if (pool_ns)
1951                 dout("__ceph_pool_perm_get pool %lld ns %.*s no perm cached\n",
1952                      pool, (int)pool_ns->len, pool_ns->str);
1953         else
1954                 dout("__ceph_pool_perm_get pool %lld no perm cached\n", pool);
1955
1956         down_write(&mdsc->pool_perm_rwsem);
1957         p = &mdsc->pool_perm_tree.rb_node;
1958         parent = NULL;
1959         while (*p) {
1960                 parent = *p;
1961                 perm = rb_entry(parent, struct ceph_pool_perm, node);
1962                 if (pool < perm->pool)
1963                         p = &(*p)->rb_left;
1964                 else if (pool > perm->pool)
1965                         p = &(*p)->rb_right;
1966                 else {
1967                         int ret = ceph_compare_string(pool_ns,
1968                                                 perm->pool_ns,
1969                                                 perm->pool_ns_len);
1970                         if (ret < 0)
1971                                 p = &(*p)->rb_left;
1972                         else if (ret > 0)
1973                                 p = &(*p)->rb_right;
1974                         else {
1975                                 have = perm->perm;
1976                                 break;
1977                         }
1978                 }
1979         }
1980         if (*p) {
1981                 up_write(&mdsc->pool_perm_rwsem);
1982                 goto out;
1983         }
1984
1985         rd_req = ceph_osdc_alloc_request(&fsc->client->osdc, NULL,
1986                                          1, false, GFP_NOFS);
1987         if (!rd_req) {
1988                 err = -ENOMEM;
1989                 goto out_unlock;
1990         }
1991
1992         rd_req->r_flags = CEPH_OSD_FLAG_READ;
1993         osd_req_op_init(rd_req, 0, CEPH_OSD_OP_STAT, 0);
1994         rd_req->r_base_oloc.pool = pool;
1995         if (pool_ns)
1996                 rd_req->r_base_oloc.pool_ns = ceph_get_string(pool_ns);
1997         ceph_oid_printf(&rd_req->r_base_oid, "%llx.00000000", ci->i_vino.ino);
1998
1999         err = ceph_osdc_alloc_messages(rd_req, GFP_NOFS);
2000         if (err)
2001                 goto out_unlock;
2002
2003         wr_req = ceph_osdc_alloc_request(&fsc->client->osdc, NULL,
2004                                          1, false, GFP_NOFS);
2005         if (!wr_req) {
2006                 err = -ENOMEM;
2007                 goto out_unlock;
2008         }
2009
2010         wr_req->r_flags = CEPH_OSD_FLAG_WRITE;
2011         osd_req_op_init(wr_req, 0, CEPH_OSD_OP_CREATE, CEPH_OSD_OP_FLAG_EXCL);
2012         ceph_oloc_copy(&wr_req->r_base_oloc, &rd_req->r_base_oloc);
2013         ceph_oid_copy(&wr_req->r_base_oid, &rd_req->r_base_oid);
2014
2015         err = ceph_osdc_alloc_messages(wr_req, GFP_NOFS);
2016         if (err)
2017                 goto out_unlock;
2018
2019         /* one page should be large enough for STAT data */
2020         pages = ceph_alloc_page_vector(1, GFP_KERNEL);
2021         if (IS_ERR(pages)) {
2022                 err = PTR_ERR(pages);
2023                 goto out_unlock;
2024         }
2025
2026         osd_req_op_raw_data_in_pages(rd_req, 0, pages, PAGE_SIZE,
2027                                      0, false, true);
2028         err = ceph_osdc_start_request(&fsc->client->osdc, rd_req, false);
2029
2030         wr_req->r_mtime = ci->vfs_inode.i_mtime;
2031         err2 = ceph_osdc_start_request(&fsc->client->osdc, wr_req, false);
2032
2033         if (!err)
2034                 err = ceph_osdc_wait_request(&fsc->client->osdc, rd_req);
2035         if (!err2)
2036                 err2 = ceph_osdc_wait_request(&fsc->client->osdc, wr_req);
2037
2038         if (err >= 0 || err == -ENOENT)
2039                 have |= POOL_READ;
2040         else if (err != -EPERM) {
2041                 if (err == -EBLACKLISTED)
2042                         fsc->blacklisted = true;
2043                 goto out_unlock;
2044         }
2045
2046         if (err2 == 0 || err2 == -EEXIST)
2047                 have |= POOL_WRITE;
2048         else if (err2 != -EPERM) {
2049                 if (err2 == -EBLACKLISTED)
2050                         fsc->blacklisted = true;
2051                 err = err2;
2052                 goto out_unlock;
2053         }
2054
2055         pool_ns_len = pool_ns ? pool_ns->len : 0;
2056         perm = kmalloc(sizeof(*perm) + pool_ns_len + 1, GFP_NOFS);
2057         if (!perm) {
2058                 err = -ENOMEM;
2059                 goto out_unlock;
2060         }
2061
2062         perm->pool = pool;
2063         perm->perm = have;
2064         perm->pool_ns_len = pool_ns_len;
2065         if (pool_ns_len > 0)
2066                 memcpy(perm->pool_ns, pool_ns->str, pool_ns_len);
2067         perm->pool_ns[pool_ns_len] = 0;
2068
2069         rb_link_node(&perm->node, parent, p);
2070         rb_insert_color(&perm->node, &mdsc->pool_perm_tree);
2071         err = 0;
2072 out_unlock:
2073         up_write(&mdsc->pool_perm_rwsem);
2074
2075         ceph_osdc_put_request(rd_req);
2076         ceph_osdc_put_request(wr_req);
2077 out:
2078         if (!err)
2079                 err = have;
2080         if (pool_ns)
2081                 dout("__ceph_pool_perm_get pool %lld ns %.*s result = %d\n",
2082                      pool, (int)pool_ns->len, pool_ns->str, err);
2083         else
2084                 dout("__ceph_pool_perm_get pool %lld result = %d\n", pool, err);
2085         return err;
2086 }
2087
2088 int ceph_pool_perm_check(struct inode *inode, int need)
2089 {
2090         struct ceph_inode_info *ci = ceph_inode(inode);
2091         struct ceph_string *pool_ns;
2092         s64 pool;
2093         int ret, flags;
2094
2095         if (ci->i_vino.snap != CEPH_NOSNAP) {
2096                 /*
2097                  * Pool permission check needs to write to the first object.
2098                  * But for snapshot, head of the first object may have alread
2099                  * been deleted. Skip check to avoid creating orphan object.
2100                  */
2101                 return 0;
2102         }
2103
2104         if (ceph_test_mount_opt(ceph_inode_to_client(inode),
2105                                 NOPOOLPERM))
2106                 return 0;
2107
2108         spin_lock(&ci->i_ceph_lock);
2109         flags = ci->i_ceph_flags;
2110         pool = ci->i_layout.pool_id;
2111         spin_unlock(&ci->i_ceph_lock);
2112 check:
2113         if (flags & CEPH_I_POOL_PERM) {
2114                 if ((need & CEPH_CAP_FILE_RD) && !(flags & CEPH_I_POOL_RD)) {
2115                         dout("ceph_pool_perm_check pool %lld no read perm\n",
2116                              pool);
2117                         return -EPERM;
2118                 }
2119                 if ((need & CEPH_CAP_FILE_WR) && !(flags & CEPH_I_POOL_WR)) {
2120                         dout("ceph_pool_perm_check pool %lld no write perm\n",
2121                              pool);
2122                         return -EPERM;
2123                 }
2124                 return 0;
2125         }
2126
2127         pool_ns = ceph_try_get_string(ci->i_layout.pool_ns);
2128         ret = __ceph_pool_perm_get(ci, pool, pool_ns);
2129         ceph_put_string(pool_ns);
2130         if (ret < 0)
2131                 return ret;
2132
2133         flags = CEPH_I_POOL_PERM;
2134         if (ret & POOL_READ)
2135                 flags |= CEPH_I_POOL_RD;
2136         if (ret & POOL_WRITE)
2137                 flags |= CEPH_I_POOL_WR;
2138
2139         spin_lock(&ci->i_ceph_lock);
2140         if (pool == ci->i_layout.pool_id &&
2141             pool_ns == rcu_dereference_raw(ci->i_layout.pool_ns)) {
2142                 ci->i_ceph_flags |= flags;
2143         } else {
2144                 pool = ci->i_layout.pool_id;
2145                 flags = ci->i_ceph_flags;
2146         }
2147         spin_unlock(&ci->i_ceph_lock);
2148         goto check;
2149 }
2150
2151 void ceph_pool_perm_destroy(struct ceph_mds_client *mdsc)
2152 {
2153         struct ceph_pool_perm *perm;
2154         struct rb_node *n;
2155
2156         while (!RB_EMPTY_ROOT(&mdsc->pool_perm_tree)) {
2157                 n = rb_first(&mdsc->pool_perm_tree);
2158                 perm = rb_entry(n, struct ceph_pool_perm, node);
2159                 rb_erase(n, &mdsc->pool_perm_tree);
2160                 kfree(perm);
2161         }
2162 }