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