xref: /openbmc/linux/fs/ceph/caps.c (revision 5d37a119)
1 // SPDX-License-Identifier: GPL-2.0
2 #include <linux/ceph/ceph_debug.h>
3 
4 #include <linux/fs.h>
5 #include <linux/kernel.h>
6 #include <linux/sched/signal.h>
7 #include <linux/slab.h>
8 #include <linux/vmalloc.h>
9 #include <linux/wait.h>
10 #include <linux/writeback.h>
11 #include <linux/iversion.h>
12 #include <linux/filelock.h>
13 
14 #include "super.h"
15 #include "mds_client.h"
16 #include "cache.h"
17 #include <linux/ceph/decode.h>
18 #include <linux/ceph/messenger.h>
19 
20 /*
21  * Capability management
22  *
23  * The Ceph metadata servers control client access to inode metadata
24  * and file data by issuing capabilities, granting clients permission
25  * to read and/or write both inode field and file data to OSDs
26  * (storage nodes).  Each capability consists of a set of bits
27  * indicating which operations are allowed.
28  *
29  * If the client holds a *_SHARED cap, the client has a coherent value
30  * that can be safely read from the cached inode.
31  *
32  * In the case of a *_EXCL (exclusive) or FILE_WR capabilities, the
33  * client is allowed to change inode attributes (e.g., file size,
34  * mtime), note its dirty state in the ceph_cap, and asynchronously
35  * flush that metadata change to the MDS.
36  *
37  * In the event of a conflicting operation (perhaps by another
38  * client), the MDS will revoke the conflicting client capabilities.
39  *
40  * In order for a client to cache an inode, it must hold a capability
41  * with at least one MDS server.  When inodes are released, release
42  * notifications are batched and periodically sent en masse to the MDS
43  * cluster to release server state.
44  */
45 
46 static u64 __get_oldest_flush_tid(struct ceph_mds_client *mdsc);
47 static void __kick_flushing_caps(struct ceph_mds_client *mdsc,
48 				 struct ceph_mds_session *session,
49 				 struct ceph_inode_info *ci,
50 				 u64 oldest_flush_tid);
51 
52 /*
53  * Generate readable cap strings for debugging output.
54  */
55 #define MAX_CAP_STR 20
56 static char cap_str[MAX_CAP_STR][40];
57 static DEFINE_SPINLOCK(cap_str_lock);
58 static int last_cap_str;
59 
60 static char *gcap_string(char *s, int c)
61 {
62 	if (c & CEPH_CAP_GSHARED)
63 		*s++ = 's';
64 	if (c & CEPH_CAP_GEXCL)
65 		*s++ = 'x';
66 	if (c & CEPH_CAP_GCACHE)
67 		*s++ = 'c';
68 	if (c & CEPH_CAP_GRD)
69 		*s++ = 'r';
70 	if (c & CEPH_CAP_GWR)
71 		*s++ = 'w';
72 	if (c & CEPH_CAP_GBUFFER)
73 		*s++ = 'b';
74 	if (c & CEPH_CAP_GWREXTEND)
75 		*s++ = 'a';
76 	if (c & CEPH_CAP_GLAZYIO)
77 		*s++ = 'l';
78 	return s;
79 }
80 
81 const char *ceph_cap_string(int caps)
82 {
83 	int i;
84 	char *s;
85 	int c;
86 
87 	spin_lock(&cap_str_lock);
88 	i = last_cap_str++;
89 	if (last_cap_str == MAX_CAP_STR)
90 		last_cap_str = 0;
91 	spin_unlock(&cap_str_lock);
92 
93 	s = cap_str[i];
94 
95 	if (caps & CEPH_CAP_PIN)
96 		*s++ = 'p';
97 
98 	c = (caps >> CEPH_CAP_SAUTH) & 3;
99 	if (c) {
100 		*s++ = 'A';
101 		s = gcap_string(s, c);
102 	}
103 
104 	c = (caps >> CEPH_CAP_SLINK) & 3;
105 	if (c) {
106 		*s++ = 'L';
107 		s = gcap_string(s, c);
108 	}
109 
110 	c = (caps >> CEPH_CAP_SXATTR) & 3;
111 	if (c) {
112 		*s++ = 'X';
113 		s = gcap_string(s, c);
114 	}
115 
116 	c = caps >> CEPH_CAP_SFILE;
117 	if (c) {
118 		*s++ = 'F';
119 		s = gcap_string(s, c);
120 	}
121 
122 	if (s == cap_str[i])
123 		*s++ = '-';
124 	*s = 0;
125 	return cap_str[i];
126 }
127 
128 void ceph_caps_init(struct ceph_mds_client *mdsc)
129 {
130 	INIT_LIST_HEAD(&mdsc->caps_list);
131 	spin_lock_init(&mdsc->caps_list_lock);
132 }
133 
134 void ceph_caps_finalize(struct ceph_mds_client *mdsc)
135 {
136 	struct ceph_cap *cap;
137 
138 	spin_lock(&mdsc->caps_list_lock);
139 	while (!list_empty(&mdsc->caps_list)) {
140 		cap = list_first_entry(&mdsc->caps_list,
141 				       struct ceph_cap, caps_item);
142 		list_del(&cap->caps_item);
143 		kmem_cache_free(ceph_cap_cachep, cap);
144 	}
145 	mdsc->caps_total_count = 0;
146 	mdsc->caps_avail_count = 0;
147 	mdsc->caps_use_count = 0;
148 	mdsc->caps_reserve_count = 0;
149 	mdsc->caps_min_count = 0;
150 	spin_unlock(&mdsc->caps_list_lock);
151 }
152 
153 void ceph_adjust_caps_max_min(struct ceph_mds_client *mdsc,
154 			      struct ceph_mount_options *fsopt)
155 {
156 	spin_lock(&mdsc->caps_list_lock);
157 	mdsc->caps_min_count = fsopt->max_readdir;
158 	if (mdsc->caps_min_count < 1024)
159 		mdsc->caps_min_count = 1024;
160 	mdsc->caps_use_max = fsopt->caps_max;
161 	if (mdsc->caps_use_max > 0 &&
162 	    mdsc->caps_use_max < mdsc->caps_min_count)
163 		mdsc->caps_use_max = mdsc->caps_min_count;
164 	spin_unlock(&mdsc->caps_list_lock);
165 }
166 
167 static void __ceph_unreserve_caps(struct ceph_mds_client *mdsc, int nr_caps)
168 {
169 	struct ceph_cap *cap;
170 	int i;
171 
172 	if (nr_caps) {
173 		BUG_ON(mdsc->caps_reserve_count < nr_caps);
174 		mdsc->caps_reserve_count -= nr_caps;
175 		if (mdsc->caps_avail_count >=
176 		    mdsc->caps_reserve_count + mdsc->caps_min_count) {
177 			mdsc->caps_total_count -= nr_caps;
178 			for (i = 0; i < nr_caps; i++) {
179 				cap = list_first_entry(&mdsc->caps_list,
180 					struct ceph_cap, caps_item);
181 				list_del(&cap->caps_item);
182 				kmem_cache_free(ceph_cap_cachep, cap);
183 			}
184 		} else {
185 			mdsc->caps_avail_count += nr_caps;
186 		}
187 
188 		dout("%s: caps %d = %d used + %d resv + %d avail\n",
189 		     __func__,
190 		     mdsc->caps_total_count, mdsc->caps_use_count,
191 		     mdsc->caps_reserve_count, mdsc->caps_avail_count);
192 		BUG_ON(mdsc->caps_total_count != mdsc->caps_use_count +
193 						 mdsc->caps_reserve_count +
194 						 mdsc->caps_avail_count);
195 	}
196 }
197 
198 /*
199  * Called under mdsc->mutex.
200  */
201 int ceph_reserve_caps(struct ceph_mds_client *mdsc,
202 		      struct ceph_cap_reservation *ctx, int need)
203 {
204 	int i, j;
205 	struct ceph_cap *cap;
206 	int have;
207 	int alloc = 0;
208 	int max_caps;
209 	int err = 0;
210 	bool trimmed = false;
211 	struct ceph_mds_session *s;
212 	LIST_HEAD(newcaps);
213 
214 	dout("reserve caps ctx=%p need=%d\n", ctx, need);
215 
216 	/* first reserve any caps that are already allocated */
217 	spin_lock(&mdsc->caps_list_lock);
218 	if (mdsc->caps_avail_count >= need)
219 		have = need;
220 	else
221 		have = mdsc->caps_avail_count;
222 	mdsc->caps_avail_count -= have;
223 	mdsc->caps_reserve_count += have;
224 	BUG_ON(mdsc->caps_total_count != mdsc->caps_use_count +
225 					 mdsc->caps_reserve_count +
226 					 mdsc->caps_avail_count);
227 	spin_unlock(&mdsc->caps_list_lock);
228 
229 	for (i = have; i < need; ) {
230 		cap = kmem_cache_alloc(ceph_cap_cachep, GFP_NOFS);
231 		if (cap) {
232 			list_add(&cap->caps_item, &newcaps);
233 			alloc++;
234 			i++;
235 			continue;
236 		}
237 
238 		if (!trimmed) {
239 			for (j = 0; j < mdsc->max_sessions; j++) {
240 				s = __ceph_lookup_mds_session(mdsc, j);
241 				if (!s)
242 					continue;
243 				mutex_unlock(&mdsc->mutex);
244 
245 				mutex_lock(&s->s_mutex);
246 				max_caps = s->s_nr_caps - (need - i);
247 				ceph_trim_caps(mdsc, s, max_caps);
248 				mutex_unlock(&s->s_mutex);
249 
250 				ceph_put_mds_session(s);
251 				mutex_lock(&mdsc->mutex);
252 			}
253 			trimmed = true;
254 
255 			spin_lock(&mdsc->caps_list_lock);
256 			if (mdsc->caps_avail_count) {
257 				int more_have;
258 				if (mdsc->caps_avail_count >= need - i)
259 					more_have = need - i;
260 				else
261 					more_have = mdsc->caps_avail_count;
262 
263 				i += more_have;
264 				have += more_have;
265 				mdsc->caps_avail_count -= more_have;
266 				mdsc->caps_reserve_count += more_have;
267 
268 			}
269 			spin_unlock(&mdsc->caps_list_lock);
270 
271 			continue;
272 		}
273 
274 		pr_warn("reserve caps ctx=%p ENOMEM need=%d got=%d\n",
275 			ctx, need, have + alloc);
276 		err = -ENOMEM;
277 		break;
278 	}
279 
280 	if (!err) {
281 		BUG_ON(have + alloc != need);
282 		ctx->count = need;
283 		ctx->used = 0;
284 	}
285 
286 	spin_lock(&mdsc->caps_list_lock);
287 	mdsc->caps_total_count += alloc;
288 	mdsc->caps_reserve_count += alloc;
289 	list_splice(&newcaps, &mdsc->caps_list);
290 
291 	BUG_ON(mdsc->caps_total_count != mdsc->caps_use_count +
292 					 mdsc->caps_reserve_count +
293 					 mdsc->caps_avail_count);
294 
295 	if (err)
296 		__ceph_unreserve_caps(mdsc, have + alloc);
297 
298 	spin_unlock(&mdsc->caps_list_lock);
299 
300 	dout("reserve caps ctx=%p %d = %d used + %d resv + %d avail\n",
301 	     ctx, mdsc->caps_total_count, mdsc->caps_use_count,
302 	     mdsc->caps_reserve_count, mdsc->caps_avail_count);
303 	return err;
304 }
305 
306 void ceph_unreserve_caps(struct ceph_mds_client *mdsc,
307 			 struct ceph_cap_reservation *ctx)
308 {
309 	bool reclaim = false;
310 	if (!ctx->count)
311 		return;
312 
313 	dout("unreserve caps ctx=%p count=%d\n", ctx, ctx->count);
314 	spin_lock(&mdsc->caps_list_lock);
315 	__ceph_unreserve_caps(mdsc, ctx->count);
316 	ctx->count = 0;
317 
318 	if (mdsc->caps_use_max > 0 &&
319 	    mdsc->caps_use_count > mdsc->caps_use_max)
320 		reclaim = true;
321 	spin_unlock(&mdsc->caps_list_lock);
322 
323 	if (reclaim)
324 		ceph_reclaim_caps_nr(mdsc, ctx->used);
325 }
326 
327 struct ceph_cap *ceph_get_cap(struct ceph_mds_client *mdsc,
328 			      struct ceph_cap_reservation *ctx)
329 {
330 	struct ceph_cap *cap = NULL;
331 
332 	/* temporary, until we do something about cap import/export */
333 	if (!ctx) {
334 		cap = kmem_cache_alloc(ceph_cap_cachep, GFP_NOFS);
335 		if (cap) {
336 			spin_lock(&mdsc->caps_list_lock);
337 			mdsc->caps_use_count++;
338 			mdsc->caps_total_count++;
339 			spin_unlock(&mdsc->caps_list_lock);
340 		} else {
341 			spin_lock(&mdsc->caps_list_lock);
342 			if (mdsc->caps_avail_count) {
343 				BUG_ON(list_empty(&mdsc->caps_list));
344 
345 				mdsc->caps_avail_count--;
346 				mdsc->caps_use_count++;
347 				cap = list_first_entry(&mdsc->caps_list,
348 						struct ceph_cap, caps_item);
349 				list_del(&cap->caps_item);
350 
351 				BUG_ON(mdsc->caps_total_count != mdsc->caps_use_count +
352 				       mdsc->caps_reserve_count + mdsc->caps_avail_count);
353 			}
354 			spin_unlock(&mdsc->caps_list_lock);
355 		}
356 
357 		return cap;
358 	}
359 
360 	spin_lock(&mdsc->caps_list_lock);
361 	dout("get_cap ctx=%p (%d) %d = %d used + %d resv + %d avail\n",
362 	     ctx, ctx->count, mdsc->caps_total_count, mdsc->caps_use_count,
363 	     mdsc->caps_reserve_count, mdsc->caps_avail_count);
364 	BUG_ON(!ctx->count);
365 	BUG_ON(ctx->count > mdsc->caps_reserve_count);
366 	BUG_ON(list_empty(&mdsc->caps_list));
367 
368 	ctx->count--;
369 	ctx->used++;
370 	mdsc->caps_reserve_count--;
371 	mdsc->caps_use_count++;
372 
373 	cap = list_first_entry(&mdsc->caps_list, struct ceph_cap, caps_item);
374 	list_del(&cap->caps_item);
375 
376 	BUG_ON(mdsc->caps_total_count != mdsc->caps_use_count +
377 	       mdsc->caps_reserve_count + mdsc->caps_avail_count);
378 	spin_unlock(&mdsc->caps_list_lock);
379 	return cap;
380 }
381 
382 void ceph_put_cap(struct ceph_mds_client *mdsc, struct ceph_cap *cap)
383 {
384 	spin_lock(&mdsc->caps_list_lock);
385 	dout("put_cap %p %d = %d used + %d resv + %d avail\n",
386 	     cap, mdsc->caps_total_count, mdsc->caps_use_count,
387 	     mdsc->caps_reserve_count, mdsc->caps_avail_count);
388 	mdsc->caps_use_count--;
389 	/*
390 	 * Keep some preallocated caps around (ceph_min_count), to
391 	 * avoid lots of free/alloc churn.
392 	 */
393 	if (mdsc->caps_avail_count >= mdsc->caps_reserve_count +
394 				      mdsc->caps_min_count) {
395 		mdsc->caps_total_count--;
396 		kmem_cache_free(ceph_cap_cachep, cap);
397 	} else {
398 		mdsc->caps_avail_count++;
399 		list_add(&cap->caps_item, &mdsc->caps_list);
400 	}
401 
402 	BUG_ON(mdsc->caps_total_count != mdsc->caps_use_count +
403 	       mdsc->caps_reserve_count + mdsc->caps_avail_count);
404 	spin_unlock(&mdsc->caps_list_lock);
405 }
406 
407 void ceph_reservation_status(struct ceph_fs_client *fsc,
408 			     int *total, int *avail, int *used, int *reserved,
409 			     int *min)
410 {
411 	struct ceph_mds_client *mdsc = fsc->mdsc;
412 
413 	spin_lock(&mdsc->caps_list_lock);
414 
415 	if (total)
416 		*total = mdsc->caps_total_count;
417 	if (avail)
418 		*avail = mdsc->caps_avail_count;
419 	if (used)
420 		*used = mdsc->caps_use_count;
421 	if (reserved)
422 		*reserved = mdsc->caps_reserve_count;
423 	if (min)
424 		*min = mdsc->caps_min_count;
425 
426 	spin_unlock(&mdsc->caps_list_lock);
427 }
428 
429 /*
430  * Find ceph_cap for given mds, if any.
431  *
432  * Called with i_ceph_lock held.
433  */
434 struct ceph_cap *__get_cap_for_mds(struct ceph_inode_info *ci, int mds)
435 {
436 	struct ceph_cap *cap;
437 	struct rb_node *n = ci->i_caps.rb_node;
438 
439 	while (n) {
440 		cap = rb_entry(n, struct ceph_cap, ci_node);
441 		if (mds < cap->mds)
442 			n = n->rb_left;
443 		else if (mds > cap->mds)
444 			n = n->rb_right;
445 		else
446 			return cap;
447 	}
448 	return NULL;
449 }
450 
451 struct ceph_cap *ceph_get_cap_for_mds(struct ceph_inode_info *ci, int mds)
452 {
453 	struct ceph_cap *cap;
454 
455 	spin_lock(&ci->i_ceph_lock);
456 	cap = __get_cap_for_mds(ci, mds);
457 	spin_unlock(&ci->i_ceph_lock);
458 	return cap;
459 }
460 
461 /*
462  * Called under i_ceph_lock.
463  */
464 static void __insert_cap_node(struct ceph_inode_info *ci,
465 			      struct ceph_cap *new)
466 {
467 	struct rb_node **p = &ci->i_caps.rb_node;
468 	struct rb_node *parent = NULL;
469 	struct ceph_cap *cap = NULL;
470 
471 	while (*p) {
472 		parent = *p;
473 		cap = rb_entry(parent, struct ceph_cap, ci_node);
474 		if (new->mds < cap->mds)
475 			p = &(*p)->rb_left;
476 		else if (new->mds > cap->mds)
477 			p = &(*p)->rb_right;
478 		else
479 			BUG();
480 	}
481 
482 	rb_link_node(&new->ci_node, parent, p);
483 	rb_insert_color(&new->ci_node, &ci->i_caps);
484 }
485 
486 /*
487  * (re)set cap hold timeouts, which control the delayed release
488  * of unused caps back to the MDS.  Should be called on cap use.
489  */
490 static void __cap_set_timeouts(struct ceph_mds_client *mdsc,
491 			       struct ceph_inode_info *ci)
492 {
493 	struct ceph_mount_options *opt = mdsc->fsc->mount_options;
494 	ci->i_hold_caps_max = round_jiffies(jiffies +
495 					    opt->caps_wanted_delay_max * HZ);
496 	dout("__cap_set_timeouts %p %lu\n", &ci->netfs.inode,
497 	     ci->i_hold_caps_max - jiffies);
498 }
499 
500 /*
501  * (Re)queue cap at the end of the delayed cap release list.
502  *
503  * If I_FLUSH is set, leave the inode at the front of the list.
504  *
505  * Caller holds i_ceph_lock
506  *    -> we take mdsc->cap_delay_lock
507  */
508 static void __cap_delay_requeue(struct ceph_mds_client *mdsc,
509 				struct ceph_inode_info *ci)
510 {
511 	dout("__cap_delay_requeue %p flags 0x%lx at %lu\n", &ci->netfs.inode,
512 	     ci->i_ceph_flags, ci->i_hold_caps_max);
513 	if (!mdsc->stopping) {
514 		spin_lock(&mdsc->cap_delay_lock);
515 		if (!list_empty(&ci->i_cap_delay_list)) {
516 			if (ci->i_ceph_flags & CEPH_I_FLUSH)
517 				goto no_change;
518 			list_del_init(&ci->i_cap_delay_list);
519 		}
520 		__cap_set_timeouts(mdsc, ci);
521 		list_add_tail(&ci->i_cap_delay_list, &mdsc->cap_delay_list);
522 no_change:
523 		spin_unlock(&mdsc->cap_delay_lock);
524 	}
525 }
526 
527 /*
528  * Queue an inode for immediate writeback.  Mark inode with I_FLUSH,
529  * indicating we should send a cap message to flush dirty metadata
530  * asap, and move to the front of the delayed cap list.
531  */
532 static void __cap_delay_requeue_front(struct ceph_mds_client *mdsc,
533 				      struct ceph_inode_info *ci)
534 {
535 	dout("__cap_delay_requeue_front %p\n", &ci->netfs.inode);
536 	spin_lock(&mdsc->cap_delay_lock);
537 	ci->i_ceph_flags |= CEPH_I_FLUSH;
538 	if (!list_empty(&ci->i_cap_delay_list))
539 		list_del_init(&ci->i_cap_delay_list);
540 	list_add(&ci->i_cap_delay_list, &mdsc->cap_delay_list);
541 	spin_unlock(&mdsc->cap_delay_lock);
542 }
543 
544 /*
545  * Cancel delayed work on cap.
546  *
547  * Caller must hold i_ceph_lock.
548  */
549 static void __cap_delay_cancel(struct ceph_mds_client *mdsc,
550 			       struct ceph_inode_info *ci)
551 {
552 	dout("__cap_delay_cancel %p\n", &ci->netfs.inode);
553 	if (list_empty(&ci->i_cap_delay_list))
554 		return;
555 	spin_lock(&mdsc->cap_delay_lock);
556 	list_del_init(&ci->i_cap_delay_list);
557 	spin_unlock(&mdsc->cap_delay_lock);
558 }
559 
560 /* Common issue checks for add_cap, handle_cap_grant. */
561 static void __check_cap_issue(struct ceph_inode_info *ci, struct ceph_cap *cap,
562 			      unsigned issued)
563 {
564 	unsigned had = __ceph_caps_issued(ci, NULL);
565 
566 	lockdep_assert_held(&ci->i_ceph_lock);
567 
568 	/*
569 	 * Each time we receive FILE_CACHE anew, we increment
570 	 * i_rdcache_gen.
571 	 */
572 	if (S_ISREG(ci->netfs.inode.i_mode) &&
573 	    (issued & (CEPH_CAP_FILE_CACHE|CEPH_CAP_FILE_LAZYIO)) &&
574 	    (had & (CEPH_CAP_FILE_CACHE|CEPH_CAP_FILE_LAZYIO)) == 0) {
575 		ci->i_rdcache_gen++;
576 	}
577 
578 	/*
579 	 * If FILE_SHARED is newly issued, mark dir not complete. We don't
580 	 * know what happened to this directory while we didn't have the cap.
581 	 * If FILE_SHARED is being revoked, also mark dir not complete. It
582 	 * stops on-going cached readdir.
583 	 */
584 	if ((issued & CEPH_CAP_FILE_SHARED) != (had & CEPH_CAP_FILE_SHARED)) {
585 		if (issued & CEPH_CAP_FILE_SHARED)
586 			atomic_inc(&ci->i_shared_gen);
587 		if (S_ISDIR(ci->netfs.inode.i_mode)) {
588 			dout(" marking %p NOT complete\n", &ci->netfs.inode);
589 			__ceph_dir_clear_complete(ci);
590 		}
591 	}
592 
593 	/* Wipe saved layout if we're losing DIR_CREATE caps */
594 	if (S_ISDIR(ci->netfs.inode.i_mode) && (had & CEPH_CAP_DIR_CREATE) &&
595 		!(issued & CEPH_CAP_DIR_CREATE)) {
596 	     ceph_put_string(rcu_dereference_raw(ci->i_cached_layout.pool_ns));
597 	     memset(&ci->i_cached_layout, 0, sizeof(ci->i_cached_layout));
598 	}
599 }
600 
601 /**
602  * change_auth_cap_ses - move inode to appropriate lists when auth caps change
603  * @ci: inode to be moved
604  * @session: new auth caps session
605  */
606 void change_auth_cap_ses(struct ceph_inode_info *ci,
607 			 struct ceph_mds_session *session)
608 {
609 	lockdep_assert_held(&ci->i_ceph_lock);
610 
611 	if (list_empty(&ci->i_dirty_item) && list_empty(&ci->i_flushing_item))
612 		return;
613 
614 	spin_lock(&session->s_mdsc->cap_dirty_lock);
615 	if (!list_empty(&ci->i_dirty_item))
616 		list_move(&ci->i_dirty_item, &session->s_cap_dirty);
617 	if (!list_empty(&ci->i_flushing_item))
618 		list_move_tail(&ci->i_flushing_item, &session->s_cap_flushing);
619 	spin_unlock(&session->s_mdsc->cap_dirty_lock);
620 }
621 
622 /*
623  * Add a capability under the given MDS session.
624  *
625  * Caller should hold session snap_rwsem (read) and ci->i_ceph_lock
626  *
627  * @fmode is the open file mode, if we are opening a file, otherwise
628  * it is < 0.  (This is so we can atomically add the cap and add an
629  * open file reference to it.)
630  */
631 void ceph_add_cap(struct inode *inode,
632 		  struct ceph_mds_session *session, u64 cap_id,
633 		  unsigned issued, unsigned wanted,
634 		  unsigned seq, unsigned mseq, u64 realmino, int flags,
635 		  struct ceph_cap **new_cap)
636 {
637 	struct ceph_mds_client *mdsc = ceph_inode_to_client(inode)->mdsc;
638 	struct ceph_inode_info *ci = ceph_inode(inode);
639 	struct ceph_cap *cap;
640 	int mds = session->s_mds;
641 	int actual_wanted;
642 	u32 gen;
643 
644 	lockdep_assert_held(&ci->i_ceph_lock);
645 
646 	dout("add_cap %p mds%d cap %llx %s seq %d\n", inode,
647 	     session->s_mds, cap_id, ceph_cap_string(issued), seq);
648 
649 	gen = atomic_read(&session->s_cap_gen);
650 
651 	cap = __get_cap_for_mds(ci, mds);
652 	if (!cap) {
653 		cap = *new_cap;
654 		*new_cap = NULL;
655 
656 		cap->issued = 0;
657 		cap->implemented = 0;
658 		cap->mds = mds;
659 		cap->mds_wanted = 0;
660 		cap->mseq = 0;
661 
662 		cap->ci = ci;
663 		__insert_cap_node(ci, cap);
664 
665 		/* add to session cap list */
666 		cap->session = session;
667 		spin_lock(&session->s_cap_lock);
668 		list_add_tail(&cap->session_caps, &session->s_caps);
669 		session->s_nr_caps++;
670 		atomic64_inc(&mdsc->metric.total_caps);
671 		spin_unlock(&session->s_cap_lock);
672 	} else {
673 		spin_lock(&session->s_cap_lock);
674 		list_move_tail(&cap->session_caps, &session->s_caps);
675 		spin_unlock(&session->s_cap_lock);
676 
677 		if (cap->cap_gen < gen)
678 			cap->issued = cap->implemented = CEPH_CAP_PIN;
679 
680 		/*
681 		 * auth mds of the inode changed. we received the cap export
682 		 * message, but still haven't received the cap import message.
683 		 * handle_cap_export() updated the new auth MDS' cap.
684 		 *
685 		 * "ceph_seq_cmp(seq, cap->seq) <= 0" means we are processing
686 		 * a message that was send before the cap import message. So
687 		 * don't remove caps.
688 		 */
689 		if (ceph_seq_cmp(seq, cap->seq) <= 0) {
690 			WARN_ON(cap != ci->i_auth_cap);
691 			WARN_ON(cap->cap_id != cap_id);
692 			seq = cap->seq;
693 			mseq = cap->mseq;
694 			issued |= cap->issued;
695 			flags |= CEPH_CAP_FLAG_AUTH;
696 		}
697 	}
698 
699 	if (!ci->i_snap_realm ||
700 	    ((flags & CEPH_CAP_FLAG_AUTH) &&
701 	     realmino != (u64)-1 && ci->i_snap_realm->ino != realmino)) {
702 		/*
703 		 * add this inode to the appropriate snap realm
704 		 */
705 		struct ceph_snap_realm *realm = ceph_lookup_snap_realm(mdsc,
706 							       realmino);
707 		if (realm)
708 			ceph_change_snap_realm(inode, realm);
709 		else
710 			WARN(1, "%s: couldn't find snap realm 0x%llx (ino 0x%llx oldrealm 0x%llx)\n",
711 			     __func__, realmino, ci->i_vino.ino,
712 			     ci->i_snap_realm ? ci->i_snap_realm->ino : 0);
713 	}
714 
715 	__check_cap_issue(ci, cap, issued);
716 
717 	/*
718 	 * If we are issued caps we don't want, or the mds' wanted
719 	 * value appears to be off, queue a check so we'll release
720 	 * later and/or update the mds wanted value.
721 	 */
722 	actual_wanted = __ceph_caps_wanted(ci);
723 	if ((wanted & ~actual_wanted) ||
724 	    (issued & ~actual_wanted & CEPH_CAP_ANY_WR)) {
725 		dout(" issued %s, mds wanted %s, actual %s, queueing\n",
726 		     ceph_cap_string(issued), ceph_cap_string(wanted),
727 		     ceph_cap_string(actual_wanted));
728 		__cap_delay_requeue(mdsc, ci);
729 	}
730 
731 	if (flags & CEPH_CAP_FLAG_AUTH) {
732 		if (!ci->i_auth_cap ||
733 		    ceph_seq_cmp(ci->i_auth_cap->mseq, mseq) < 0) {
734 			if (ci->i_auth_cap &&
735 			    ci->i_auth_cap->session != cap->session)
736 				change_auth_cap_ses(ci, cap->session);
737 			ci->i_auth_cap = cap;
738 			cap->mds_wanted = wanted;
739 		}
740 	} else {
741 		WARN_ON(ci->i_auth_cap == cap);
742 	}
743 
744 	dout("add_cap inode %p (%llx.%llx) cap %p %s now %s seq %d mds%d\n",
745 	     inode, ceph_vinop(inode), cap, ceph_cap_string(issued),
746 	     ceph_cap_string(issued|cap->issued), seq, mds);
747 	cap->cap_id = cap_id;
748 	cap->issued = issued;
749 	cap->implemented |= issued;
750 	if (ceph_seq_cmp(mseq, cap->mseq) > 0)
751 		cap->mds_wanted = wanted;
752 	else
753 		cap->mds_wanted |= wanted;
754 	cap->seq = seq;
755 	cap->issue_seq = seq;
756 	cap->mseq = mseq;
757 	cap->cap_gen = gen;
758 	wake_up_all(&ci->i_cap_wq);
759 }
760 
761 /*
762  * Return true if cap has not timed out and belongs to the current
763  * generation of the MDS session (i.e. has not gone 'stale' due to
764  * us losing touch with the mds).
765  */
766 static int __cap_is_valid(struct ceph_cap *cap)
767 {
768 	unsigned long ttl;
769 	u32 gen;
770 
771 	gen = atomic_read(&cap->session->s_cap_gen);
772 	ttl = cap->session->s_cap_ttl;
773 
774 	if (cap->cap_gen < gen || time_after_eq(jiffies, ttl)) {
775 		dout("__cap_is_valid %p cap %p issued %s "
776 		     "but STALE (gen %u vs %u)\n", &cap->ci->netfs.inode,
777 		     cap, ceph_cap_string(cap->issued), cap->cap_gen, gen);
778 		return 0;
779 	}
780 
781 	return 1;
782 }
783 
784 /*
785  * Return set of valid cap bits issued to us.  Note that caps time
786  * out, and may be invalidated in bulk if the client session times out
787  * and session->s_cap_gen is bumped.
788  */
789 int __ceph_caps_issued(struct ceph_inode_info *ci, int *implemented)
790 {
791 	int have = ci->i_snap_caps;
792 	struct ceph_cap *cap;
793 	struct rb_node *p;
794 
795 	if (implemented)
796 		*implemented = 0;
797 	for (p = rb_first(&ci->i_caps); p; p = rb_next(p)) {
798 		cap = rb_entry(p, struct ceph_cap, ci_node);
799 		if (!__cap_is_valid(cap))
800 			continue;
801 		dout("__ceph_caps_issued %p cap %p issued %s\n",
802 		     &ci->netfs.inode, cap, ceph_cap_string(cap->issued));
803 		have |= cap->issued;
804 		if (implemented)
805 			*implemented |= cap->implemented;
806 	}
807 	/*
808 	 * exclude caps issued by non-auth MDS, but are been revoking
809 	 * by the auth MDS. The non-auth MDS should be revoking/exporting
810 	 * these caps, but the message is delayed.
811 	 */
812 	if (ci->i_auth_cap) {
813 		cap = ci->i_auth_cap;
814 		have &= ~cap->implemented | cap->issued;
815 	}
816 	return have;
817 }
818 
819 /*
820  * Get cap bits issued by caps other than @ocap
821  */
822 int __ceph_caps_issued_other(struct ceph_inode_info *ci, struct ceph_cap *ocap)
823 {
824 	int have = ci->i_snap_caps;
825 	struct ceph_cap *cap;
826 	struct rb_node *p;
827 
828 	for (p = rb_first(&ci->i_caps); p; p = rb_next(p)) {
829 		cap = rb_entry(p, struct ceph_cap, ci_node);
830 		if (cap == ocap)
831 			continue;
832 		if (!__cap_is_valid(cap))
833 			continue;
834 		have |= cap->issued;
835 	}
836 	return have;
837 }
838 
839 /*
840  * Move a cap to the end of the LRU (oldest caps at list head, newest
841  * at list tail).
842  */
843 static void __touch_cap(struct ceph_cap *cap)
844 {
845 	struct ceph_mds_session *s = cap->session;
846 
847 	spin_lock(&s->s_cap_lock);
848 	if (!s->s_cap_iterator) {
849 		dout("__touch_cap %p cap %p mds%d\n", &cap->ci->netfs.inode, cap,
850 		     s->s_mds);
851 		list_move_tail(&cap->session_caps, &s->s_caps);
852 	} else {
853 		dout("__touch_cap %p cap %p mds%d NOP, iterating over caps\n",
854 		     &cap->ci->netfs.inode, cap, s->s_mds);
855 	}
856 	spin_unlock(&s->s_cap_lock);
857 }
858 
859 /*
860  * Check if we hold the given mask.  If so, move the cap(s) to the
861  * front of their respective LRUs.  (This is the preferred way for
862  * callers to check for caps they want.)
863  */
864 int __ceph_caps_issued_mask(struct ceph_inode_info *ci, int mask, int touch)
865 {
866 	struct ceph_cap *cap;
867 	struct rb_node *p;
868 	int have = ci->i_snap_caps;
869 
870 	if ((have & mask) == mask) {
871 		dout("__ceph_caps_issued_mask ino 0x%llx snap issued %s"
872 		     " (mask %s)\n", ceph_ino(&ci->netfs.inode),
873 		     ceph_cap_string(have),
874 		     ceph_cap_string(mask));
875 		return 1;
876 	}
877 
878 	for (p = rb_first(&ci->i_caps); p; p = rb_next(p)) {
879 		cap = rb_entry(p, struct ceph_cap, ci_node);
880 		if (!__cap_is_valid(cap))
881 			continue;
882 		if ((cap->issued & mask) == mask) {
883 			dout("__ceph_caps_issued_mask ino 0x%llx cap %p issued %s"
884 			     " (mask %s)\n", ceph_ino(&ci->netfs.inode), cap,
885 			     ceph_cap_string(cap->issued),
886 			     ceph_cap_string(mask));
887 			if (touch)
888 				__touch_cap(cap);
889 			return 1;
890 		}
891 
892 		/* does a combination of caps satisfy mask? */
893 		have |= cap->issued;
894 		if ((have & mask) == mask) {
895 			dout("__ceph_caps_issued_mask ino 0x%llx combo issued %s"
896 			     " (mask %s)\n", ceph_ino(&ci->netfs.inode),
897 			     ceph_cap_string(cap->issued),
898 			     ceph_cap_string(mask));
899 			if (touch) {
900 				struct rb_node *q;
901 
902 				/* touch this + preceding caps */
903 				__touch_cap(cap);
904 				for (q = rb_first(&ci->i_caps); q != p;
905 				     q = rb_next(q)) {
906 					cap = rb_entry(q, struct ceph_cap,
907 						       ci_node);
908 					if (!__cap_is_valid(cap))
909 						continue;
910 					if (cap->issued & mask)
911 						__touch_cap(cap);
912 				}
913 			}
914 			return 1;
915 		}
916 	}
917 
918 	return 0;
919 }
920 
921 int __ceph_caps_issued_mask_metric(struct ceph_inode_info *ci, int mask,
922 				   int touch)
923 {
924 	struct ceph_fs_client *fsc = ceph_sb_to_client(ci->netfs.inode.i_sb);
925 	int r;
926 
927 	r = __ceph_caps_issued_mask(ci, mask, touch);
928 	if (r)
929 		ceph_update_cap_hit(&fsc->mdsc->metric);
930 	else
931 		ceph_update_cap_mis(&fsc->mdsc->metric);
932 	return r;
933 }
934 
935 /*
936  * Return true if mask caps are currently being revoked by an MDS.
937  */
938 int __ceph_caps_revoking_other(struct ceph_inode_info *ci,
939 			       struct ceph_cap *ocap, int mask)
940 {
941 	struct ceph_cap *cap;
942 	struct rb_node *p;
943 
944 	for (p = rb_first(&ci->i_caps); p; p = rb_next(p)) {
945 		cap = rb_entry(p, struct ceph_cap, ci_node);
946 		if (cap != ocap &&
947 		    (cap->implemented & ~cap->issued & mask))
948 			return 1;
949 	}
950 	return 0;
951 }
952 
953 int ceph_caps_revoking(struct ceph_inode_info *ci, int mask)
954 {
955 	struct inode *inode = &ci->netfs.inode;
956 	int ret;
957 
958 	spin_lock(&ci->i_ceph_lock);
959 	ret = __ceph_caps_revoking_other(ci, NULL, mask);
960 	spin_unlock(&ci->i_ceph_lock);
961 	dout("ceph_caps_revoking %p %s = %d\n", inode,
962 	     ceph_cap_string(mask), ret);
963 	return ret;
964 }
965 
966 int __ceph_caps_used(struct ceph_inode_info *ci)
967 {
968 	int used = 0;
969 	if (ci->i_pin_ref)
970 		used |= CEPH_CAP_PIN;
971 	if (ci->i_rd_ref)
972 		used |= CEPH_CAP_FILE_RD;
973 	if (ci->i_rdcache_ref ||
974 	    (S_ISREG(ci->netfs.inode.i_mode) &&
975 	     ci->netfs.inode.i_data.nrpages))
976 		used |= CEPH_CAP_FILE_CACHE;
977 	if (ci->i_wr_ref)
978 		used |= CEPH_CAP_FILE_WR;
979 	if (ci->i_wb_ref || ci->i_wrbuffer_ref)
980 		used |= CEPH_CAP_FILE_BUFFER;
981 	if (ci->i_fx_ref)
982 		used |= CEPH_CAP_FILE_EXCL;
983 	return used;
984 }
985 
986 #define FMODE_WAIT_BIAS 1000
987 
988 /*
989  * wanted, by virtue of open file modes
990  */
991 int __ceph_caps_file_wanted(struct ceph_inode_info *ci)
992 {
993 	const int PIN_SHIFT = ffs(CEPH_FILE_MODE_PIN);
994 	const int RD_SHIFT = ffs(CEPH_FILE_MODE_RD);
995 	const int WR_SHIFT = ffs(CEPH_FILE_MODE_WR);
996 	const int LAZY_SHIFT = ffs(CEPH_FILE_MODE_LAZY);
997 	struct ceph_mount_options *opt =
998 		ceph_inode_to_client(&ci->netfs.inode)->mount_options;
999 	unsigned long used_cutoff = jiffies - opt->caps_wanted_delay_max * HZ;
1000 	unsigned long idle_cutoff = jiffies - opt->caps_wanted_delay_min * HZ;
1001 
1002 	if (S_ISDIR(ci->netfs.inode.i_mode)) {
1003 		int want = 0;
1004 
1005 		/* use used_cutoff here, to keep dir's wanted caps longer */
1006 		if (ci->i_nr_by_mode[RD_SHIFT] > 0 ||
1007 		    time_after(ci->i_last_rd, used_cutoff))
1008 			want |= CEPH_CAP_ANY_SHARED;
1009 
1010 		if (ci->i_nr_by_mode[WR_SHIFT] > 0 ||
1011 		    time_after(ci->i_last_wr, used_cutoff)) {
1012 			want |= CEPH_CAP_ANY_SHARED | CEPH_CAP_FILE_EXCL;
1013 			if (opt->flags & CEPH_MOUNT_OPT_ASYNC_DIROPS)
1014 				want |= CEPH_CAP_ANY_DIR_OPS;
1015 		}
1016 
1017 		if (want || ci->i_nr_by_mode[PIN_SHIFT] > 0)
1018 			want |= CEPH_CAP_PIN;
1019 
1020 		return want;
1021 	} else {
1022 		int bits = 0;
1023 
1024 		if (ci->i_nr_by_mode[RD_SHIFT] > 0) {
1025 			if (ci->i_nr_by_mode[RD_SHIFT] >= FMODE_WAIT_BIAS ||
1026 			    time_after(ci->i_last_rd, used_cutoff))
1027 				bits |= 1 << RD_SHIFT;
1028 		} else if (time_after(ci->i_last_rd, idle_cutoff)) {
1029 			bits |= 1 << RD_SHIFT;
1030 		}
1031 
1032 		if (ci->i_nr_by_mode[WR_SHIFT] > 0) {
1033 			if (ci->i_nr_by_mode[WR_SHIFT] >= FMODE_WAIT_BIAS ||
1034 			    time_after(ci->i_last_wr, used_cutoff))
1035 				bits |= 1 << WR_SHIFT;
1036 		} else if (time_after(ci->i_last_wr, idle_cutoff)) {
1037 			bits |= 1 << WR_SHIFT;
1038 		}
1039 
1040 		/* check lazyio only when read/write is wanted */
1041 		if ((bits & (CEPH_FILE_MODE_RDWR << 1)) &&
1042 		    ci->i_nr_by_mode[LAZY_SHIFT] > 0)
1043 			bits |= 1 << LAZY_SHIFT;
1044 
1045 		return bits ? ceph_caps_for_mode(bits >> 1) : 0;
1046 	}
1047 }
1048 
1049 /*
1050  * wanted, by virtue of open file modes AND cap refs (buffered/cached data)
1051  */
1052 int __ceph_caps_wanted(struct ceph_inode_info *ci)
1053 {
1054 	int w = __ceph_caps_file_wanted(ci) | __ceph_caps_used(ci);
1055 	if (S_ISDIR(ci->netfs.inode.i_mode)) {
1056 		/* we want EXCL if holding caps of dir ops */
1057 		if (w & CEPH_CAP_ANY_DIR_OPS)
1058 			w |= CEPH_CAP_FILE_EXCL;
1059 	} else {
1060 		/* we want EXCL if dirty data */
1061 		if (w & CEPH_CAP_FILE_BUFFER)
1062 			w |= CEPH_CAP_FILE_EXCL;
1063 	}
1064 	return w;
1065 }
1066 
1067 /*
1068  * Return caps we have registered with the MDS(s) as 'wanted'.
1069  */
1070 int __ceph_caps_mds_wanted(struct ceph_inode_info *ci, bool check)
1071 {
1072 	struct ceph_cap *cap;
1073 	struct rb_node *p;
1074 	int mds_wanted = 0;
1075 
1076 	for (p = rb_first(&ci->i_caps); p; p = rb_next(p)) {
1077 		cap = rb_entry(p, struct ceph_cap, ci_node);
1078 		if (check && !__cap_is_valid(cap))
1079 			continue;
1080 		if (cap == ci->i_auth_cap)
1081 			mds_wanted |= cap->mds_wanted;
1082 		else
1083 			mds_wanted |= (cap->mds_wanted & ~CEPH_CAP_ANY_FILE_WR);
1084 	}
1085 	return mds_wanted;
1086 }
1087 
1088 int ceph_is_any_caps(struct inode *inode)
1089 {
1090 	struct ceph_inode_info *ci = ceph_inode(inode);
1091 	int ret;
1092 
1093 	spin_lock(&ci->i_ceph_lock);
1094 	ret = __ceph_is_any_real_caps(ci);
1095 	spin_unlock(&ci->i_ceph_lock);
1096 
1097 	return ret;
1098 }
1099 
1100 /*
1101  * Remove a cap.  Take steps to deal with a racing iterate_session_caps.
1102  *
1103  * caller should hold i_ceph_lock.
1104  * caller will not hold session s_mutex if called from destroy_inode.
1105  */
1106 void __ceph_remove_cap(struct ceph_cap *cap, bool queue_release)
1107 {
1108 	struct ceph_mds_session *session = cap->session;
1109 	struct ceph_inode_info *ci = cap->ci;
1110 	struct ceph_mds_client *mdsc;
1111 	int removed = 0;
1112 
1113 	/* 'ci' being NULL means the remove have already occurred */
1114 	if (!ci) {
1115 		dout("%s: cap inode is NULL\n", __func__);
1116 		return;
1117 	}
1118 
1119 	lockdep_assert_held(&ci->i_ceph_lock);
1120 
1121 	dout("__ceph_remove_cap %p from %p\n", cap, &ci->netfs.inode);
1122 
1123 	mdsc = ceph_inode_to_client(&ci->netfs.inode)->mdsc;
1124 
1125 	/* remove from inode's cap rbtree, and clear auth cap */
1126 	rb_erase(&cap->ci_node, &ci->i_caps);
1127 	if (ci->i_auth_cap == cap)
1128 		ci->i_auth_cap = NULL;
1129 
1130 	/* remove from session list */
1131 	spin_lock(&session->s_cap_lock);
1132 	if (session->s_cap_iterator == cap) {
1133 		/* not yet, we are iterating over this very cap */
1134 		dout("__ceph_remove_cap  delaying %p removal from session %p\n",
1135 		     cap, cap->session);
1136 	} else {
1137 		list_del_init(&cap->session_caps);
1138 		session->s_nr_caps--;
1139 		atomic64_dec(&mdsc->metric.total_caps);
1140 		cap->session = NULL;
1141 		removed = 1;
1142 	}
1143 	/* protect backpointer with s_cap_lock: see iterate_session_caps */
1144 	cap->ci = NULL;
1145 
1146 	/*
1147 	 * s_cap_reconnect is protected by s_cap_lock. no one changes
1148 	 * s_cap_gen while session is in the reconnect state.
1149 	 */
1150 	if (queue_release &&
1151 	    (!session->s_cap_reconnect ||
1152 	     cap->cap_gen == atomic_read(&session->s_cap_gen))) {
1153 		cap->queue_release = 1;
1154 		if (removed) {
1155 			__ceph_queue_cap_release(session, cap);
1156 			removed = 0;
1157 		}
1158 	} else {
1159 		cap->queue_release = 0;
1160 	}
1161 	cap->cap_ino = ci->i_vino.ino;
1162 
1163 	spin_unlock(&session->s_cap_lock);
1164 
1165 	if (removed)
1166 		ceph_put_cap(mdsc, cap);
1167 
1168 	if (!__ceph_is_any_real_caps(ci)) {
1169 		/* when reconnect denied, we remove session caps forcibly,
1170 		 * i_wr_ref can be non-zero. If there are ongoing write,
1171 		 * keep i_snap_realm.
1172 		 */
1173 		if (ci->i_wr_ref == 0 && ci->i_snap_realm)
1174 			ceph_change_snap_realm(&ci->netfs.inode, NULL);
1175 
1176 		__cap_delay_cancel(mdsc, ci);
1177 	}
1178 }
1179 
1180 void ceph_remove_cap(struct ceph_cap *cap, bool queue_release)
1181 {
1182 	struct ceph_inode_info *ci = cap->ci;
1183 	struct ceph_fs_client *fsc;
1184 
1185 	/* 'ci' being NULL means the remove have already occurred */
1186 	if (!ci) {
1187 		dout("%s: cap inode is NULL\n", __func__);
1188 		return;
1189 	}
1190 
1191 	lockdep_assert_held(&ci->i_ceph_lock);
1192 
1193 	fsc = ceph_inode_to_client(&ci->netfs.inode);
1194 	WARN_ON_ONCE(ci->i_auth_cap == cap &&
1195 		     !list_empty(&ci->i_dirty_item) &&
1196 		     !fsc->blocklisted &&
1197 		     !ceph_inode_is_shutdown(&ci->netfs.inode));
1198 
1199 	__ceph_remove_cap(cap, queue_release);
1200 }
1201 
1202 struct cap_msg_args {
1203 	struct ceph_mds_session	*session;
1204 	u64			ino, cid, follows;
1205 	u64			flush_tid, oldest_flush_tid, size, max_size;
1206 	u64			xattr_version;
1207 	u64			change_attr;
1208 	struct ceph_buffer	*xattr_buf;
1209 	struct ceph_buffer	*old_xattr_buf;
1210 	struct timespec64	atime, mtime, ctime, btime;
1211 	int			op, caps, wanted, dirty;
1212 	u32			seq, issue_seq, mseq, time_warp_seq;
1213 	u32			flags;
1214 	kuid_t			uid;
1215 	kgid_t			gid;
1216 	umode_t			mode;
1217 	bool			inline_data;
1218 	bool			wake;
1219 };
1220 
1221 /*
1222  * cap struct size + flock buffer size + inline version + inline data size +
1223  * osd_epoch_barrier + oldest_flush_tid
1224  */
1225 #define CAP_MSG_SIZE (sizeof(struct ceph_mds_caps) + \
1226 		      4 + 8 + 4 + 4 + 8 + 4 + 4 + 4 + 8 + 8 + 4)
1227 
1228 /* Marshal up the cap msg to the MDS */
1229 static void encode_cap_msg(struct ceph_msg *msg, struct cap_msg_args *arg)
1230 {
1231 	struct ceph_mds_caps *fc;
1232 	void *p;
1233 	struct ceph_osd_client *osdc = &arg->session->s_mdsc->fsc->client->osdc;
1234 
1235 	dout("%s %s %llx %llx caps %s wanted %s dirty %s seq %u/%u tid %llu/%llu mseq %u follows %lld size %llu/%llu xattr_ver %llu xattr_len %d\n",
1236 	     __func__, ceph_cap_op_name(arg->op), arg->cid, arg->ino,
1237 	     ceph_cap_string(arg->caps), ceph_cap_string(arg->wanted),
1238 	     ceph_cap_string(arg->dirty), arg->seq, arg->issue_seq,
1239 	     arg->flush_tid, arg->oldest_flush_tid, arg->mseq, arg->follows,
1240 	     arg->size, arg->max_size, arg->xattr_version,
1241 	     arg->xattr_buf ? (int)arg->xattr_buf->vec.iov_len : 0);
1242 
1243 	msg->hdr.version = cpu_to_le16(10);
1244 	msg->hdr.tid = cpu_to_le64(arg->flush_tid);
1245 
1246 	fc = msg->front.iov_base;
1247 	memset(fc, 0, sizeof(*fc));
1248 
1249 	fc->cap_id = cpu_to_le64(arg->cid);
1250 	fc->op = cpu_to_le32(arg->op);
1251 	fc->seq = cpu_to_le32(arg->seq);
1252 	fc->issue_seq = cpu_to_le32(arg->issue_seq);
1253 	fc->migrate_seq = cpu_to_le32(arg->mseq);
1254 	fc->caps = cpu_to_le32(arg->caps);
1255 	fc->wanted = cpu_to_le32(arg->wanted);
1256 	fc->dirty = cpu_to_le32(arg->dirty);
1257 	fc->ino = cpu_to_le64(arg->ino);
1258 	fc->snap_follows = cpu_to_le64(arg->follows);
1259 
1260 	fc->size = cpu_to_le64(arg->size);
1261 	fc->max_size = cpu_to_le64(arg->max_size);
1262 	ceph_encode_timespec64(&fc->mtime, &arg->mtime);
1263 	ceph_encode_timespec64(&fc->atime, &arg->atime);
1264 	ceph_encode_timespec64(&fc->ctime, &arg->ctime);
1265 	fc->time_warp_seq = cpu_to_le32(arg->time_warp_seq);
1266 
1267 	fc->uid = cpu_to_le32(from_kuid(&init_user_ns, arg->uid));
1268 	fc->gid = cpu_to_le32(from_kgid(&init_user_ns, arg->gid));
1269 	fc->mode = cpu_to_le32(arg->mode);
1270 
1271 	fc->xattr_version = cpu_to_le64(arg->xattr_version);
1272 	if (arg->xattr_buf) {
1273 		msg->middle = ceph_buffer_get(arg->xattr_buf);
1274 		fc->xattr_len = cpu_to_le32(arg->xattr_buf->vec.iov_len);
1275 		msg->hdr.middle_len = cpu_to_le32(arg->xattr_buf->vec.iov_len);
1276 	}
1277 
1278 	p = fc + 1;
1279 	/* flock buffer size (version 2) */
1280 	ceph_encode_32(&p, 0);
1281 	/* inline version (version 4) */
1282 	ceph_encode_64(&p, arg->inline_data ? 0 : CEPH_INLINE_NONE);
1283 	/* inline data size */
1284 	ceph_encode_32(&p, 0);
1285 	/*
1286 	 * osd_epoch_barrier (version 5)
1287 	 * The epoch_barrier is protected osdc->lock, so READ_ONCE here in
1288 	 * case it was recently changed
1289 	 */
1290 	ceph_encode_32(&p, READ_ONCE(osdc->epoch_barrier));
1291 	/* oldest_flush_tid (version 6) */
1292 	ceph_encode_64(&p, arg->oldest_flush_tid);
1293 
1294 	/*
1295 	 * caller_uid/caller_gid (version 7)
1296 	 *
1297 	 * Currently, we don't properly track which caller dirtied the caps
1298 	 * last, and force a flush of them when there is a conflict. For now,
1299 	 * just set this to 0:0, to emulate how the MDS has worked up to now.
1300 	 */
1301 	ceph_encode_32(&p, 0);
1302 	ceph_encode_32(&p, 0);
1303 
1304 	/* pool namespace (version 8) (mds always ignores this) */
1305 	ceph_encode_32(&p, 0);
1306 
1307 	/* btime and change_attr (version 9) */
1308 	ceph_encode_timespec64(p, &arg->btime);
1309 	p += sizeof(struct ceph_timespec);
1310 	ceph_encode_64(&p, arg->change_attr);
1311 
1312 	/* Advisory flags (version 10) */
1313 	ceph_encode_32(&p, arg->flags);
1314 }
1315 
1316 /*
1317  * Queue cap releases when an inode is dropped from our cache.
1318  */
1319 void __ceph_remove_caps(struct ceph_inode_info *ci)
1320 {
1321 	struct rb_node *p;
1322 
1323 	/* lock i_ceph_lock, because ceph_d_revalidate(..., LOOKUP_RCU)
1324 	 * may call __ceph_caps_issued_mask() on a freeing inode. */
1325 	spin_lock(&ci->i_ceph_lock);
1326 	p = rb_first(&ci->i_caps);
1327 	while (p) {
1328 		struct ceph_cap *cap = rb_entry(p, struct ceph_cap, ci_node);
1329 		p = rb_next(p);
1330 		ceph_remove_cap(cap, true);
1331 	}
1332 	spin_unlock(&ci->i_ceph_lock);
1333 }
1334 
1335 /*
1336  * Prepare to send a cap message to an MDS. Update the cap state, and populate
1337  * the arg struct with the parameters that will need to be sent. This should
1338  * be done under the i_ceph_lock to guard against changes to cap state.
1339  *
1340  * Make note of max_size reported/requested from mds, revoked caps
1341  * that have now been implemented.
1342  */
1343 static void __prep_cap(struct cap_msg_args *arg, struct ceph_cap *cap,
1344 		       int op, int flags, int used, int want, int retain,
1345 		       int flushing, u64 flush_tid, u64 oldest_flush_tid)
1346 {
1347 	struct ceph_inode_info *ci = cap->ci;
1348 	struct inode *inode = &ci->netfs.inode;
1349 	int held, revoking;
1350 
1351 	lockdep_assert_held(&ci->i_ceph_lock);
1352 
1353 	held = cap->issued | cap->implemented;
1354 	revoking = cap->implemented & ~cap->issued;
1355 	retain &= ~revoking;
1356 
1357 	dout("%s %p cap %p session %p %s -> %s (revoking %s)\n",
1358 	     __func__, inode, cap, cap->session,
1359 	     ceph_cap_string(held), ceph_cap_string(held & retain),
1360 	     ceph_cap_string(revoking));
1361 	BUG_ON((retain & CEPH_CAP_PIN) == 0);
1362 
1363 	ci->i_ceph_flags &= ~CEPH_I_FLUSH;
1364 
1365 	cap->issued &= retain;  /* drop bits we don't want */
1366 	/*
1367 	 * Wake up any waiters on wanted -> needed transition. This is due to
1368 	 * the weird transition from buffered to sync IO... we need to flush
1369 	 * dirty pages _before_ allowing sync writes to avoid reordering.
1370 	 */
1371 	arg->wake = cap->implemented & ~cap->issued;
1372 	cap->implemented &= cap->issued | used;
1373 	cap->mds_wanted = want;
1374 
1375 	arg->session = cap->session;
1376 	arg->ino = ceph_vino(inode).ino;
1377 	arg->cid = cap->cap_id;
1378 	arg->follows = flushing ? ci->i_head_snapc->seq : 0;
1379 	arg->flush_tid = flush_tid;
1380 	arg->oldest_flush_tid = oldest_flush_tid;
1381 
1382 	arg->size = i_size_read(inode);
1383 	ci->i_reported_size = arg->size;
1384 	arg->max_size = ci->i_wanted_max_size;
1385 	if (cap == ci->i_auth_cap) {
1386 		if (want & CEPH_CAP_ANY_FILE_WR)
1387 			ci->i_requested_max_size = arg->max_size;
1388 		else
1389 			ci->i_requested_max_size = 0;
1390 	}
1391 
1392 	if (flushing & CEPH_CAP_XATTR_EXCL) {
1393 		arg->old_xattr_buf = __ceph_build_xattrs_blob(ci);
1394 		arg->xattr_version = ci->i_xattrs.version;
1395 		arg->xattr_buf = ci->i_xattrs.blob;
1396 	} else {
1397 		arg->xattr_buf = NULL;
1398 		arg->old_xattr_buf = NULL;
1399 	}
1400 
1401 	arg->mtime = inode->i_mtime;
1402 	arg->atime = inode->i_atime;
1403 	arg->ctime = inode->i_ctime;
1404 	arg->btime = ci->i_btime;
1405 	arg->change_attr = inode_peek_iversion_raw(inode);
1406 
1407 	arg->op = op;
1408 	arg->caps = cap->implemented;
1409 	arg->wanted = want;
1410 	arg->dirty = flushing;
1411 
1412 	arg->seq = cap->seq;
1413 	arg->issue_seq = cap->issue_seq;
1414 	arg->mseq = cap->mseq;
1415 	arg->time_warp_seq = ci->i_time_warp_seq;
1416 
1417 	arg->uid = inode->i_uid;
1418 	arg->gid = inode->i_gid;
1419 	arg->mode = inode->i_mode;
1420 
1421 	arg->inline_data = ci->i_inline_version != CEPH_INLINE_NONE;
1422 	if (!(flags & CEPH_CLIENT_CAPS_PENDING_CAPSNAP) &&
1423 	    !list_empty(&ci->i_cap_snaps)) {
1424 		struct ceph_cap_snap *capsnap;
1425 		list_for_each_entry_reverse(capsnap, &ci->i_cap_snaps, ci_item) {
1426 			if (capsnap->cap_flush.tid)
1427 				break;
1428 			if (capsnap->need_flush) {
1429 				flags |= CEPH_CLIENT_CAPS_PENDING_CAPSNAP;
1430 				break;
1431 			}
1432 		}
1433 	}
1434 	arg->flags = flags;
1435 }
1436 
1437 /*
1438  * Send a cap msg on the given inode.
1439  *
1440  * Caller should hold snap_rwsem (read), s_mutex.
1441  */
1442 static void __send_cap(struct cap_msg_args *arg, struct ceph_inode_info *ci)
1443 {
1444 	struct ceph_msg *msg;
1445 	struct inode *inode = &ci->netfs.inode;
1446 
1447 	msg = ceph_msg_new(CEPH_MSG_CLIENT_CAPS, CAP_MSG_SIZE, GFP_NOFS, false);
1448 	if (!msg) {
1449 		pr_err("error allocating cap msg: ino (%llx.%llx) flushing %s tid %llu, requeuing cap.\n",
1450 		       ceph_vinop(inode), ceph_cap_string(arg->dirty),
1451 		       arg->flush_tid);
1452 		spin_lock(&ci->i_ceph_lock);
1453 		__cap_delay_requeue(arg->session->s_mdsc, ci);
1454 		spin_unlock(&ci->i_ceph_lock);
1455 		return;
1456 	}
1457 
1458 	encode_cap_msg(msg, arg);
1459 	ceph_con_send(&arg->session->s_con, msg);
1460 	ceph_buffer_put(arg->old_xattr_buf);
1461 	if (arg->wake)
1462 		wake_up_all(&ci->i_cap_wq);
1463 }
1464 
1465 static inline int __send_flush_snap(struct inode *inode,
1466 				    struct ceph_mds_session *session,
1467 				    struct ceph_cap_snap *capsnap,
1468 				    u32 mseq, u64 oldest_flush_tid)
1469 {
1470 	struct cap_msg_args	arg;
1471 	struct ceph_msg		*msg;
1472 
1473 	msg = ceph_msg_new(CEPH_MSG_CLIENT_CAPS, CAP_MSG_SIZE, GFP_NOFS, false);
1474 	if (!msg)
1475 		return -ENOMEM;
1476 
1477 	arg.session = session;
1478 	arg.ino = ceph_vino(inode).ino;
1479 	arg.cid = 0;
1480 	arg.follows = capsnap->follows;
1481 	arg.flush_tid = capsnap->cap_flush.tid;
1482 	arg.oldest_flush_tid = oldest_flush_tid;
1483 
1484 	arg.size = capsnap->size;
1485 	arg.max_size = 0;
1486 	arg.xattr_version = capsnap->xattr_version;
1487 	arg.xattr_buf = capsnap->xattr_blob;
1488 	arg.old_xattr_buf = NULL;
1489 
1490 	arg.atime = capsnap->atime;
1491 	arg.mtime = capsnap->mtime;
1492 	arg.ctime = capsnap->ctime;
1493 	arg.btime = capsnap->btime;
1494 	arg.change_attr = capsnap->change_attr;
1495 
1496 	arg.op = CEPH_CAP_OP_FLUSHSNAP;
1497 	arg.caps = capsnap->issued;
1498 	arg.wanted = 0;
1499 	arg.dirty = capsnap->dirty;
1500 
1501 	arg.seq = 0;
1502 	arg.issue_seq = 0;
1503 	arg.mseq = mseq;
1504 	arg.time_warp_seq = capsnap->time_warp_seq;
1505 
1506 	arg.uid = capsnap->uid;
1507 	arg.gid = capsnap->gid;
1508 	arg.mode = capsnap->mode;
1509 
1510 	arg.inline_data = capsnap->inline_data;
1511 	arg.flags = 0;
1512 	arg.wake = false;
1513 
1514 	encode_cap_msg(msg, &arg);
1515 	ceph_con_send(&arg.session->s_con, msg);
1516 	return 0;
1517 }
1518 
1519 /*
1520  * When a snapshot is taken, clients accumulate dirty metadata on
1521  * inodes with capabilities in ceph_cap_snaps to describe the file
1522  * state at the time the snapshot was taken.  This must be flushed
1523  * asynchronously back to the MDS once sync writes complete and dirty
1524  * data is written out.
1525  *
1526  * Called under i_ceph_lock.
1527  */
1528 static void __ceph_flush_snaps(struct ceph_inode_info *ci,
1529 			       struct ceph_mds_session *session)
1530 		__releases(ci->i_ceph_lock)
1531 		__acquires(ci->i_ceph_lock)
1532 {
1533 	struct inode *inode = &ci->netfs.inode;
1534 	struct ceph_mds_client *mdsc = session->s_mdsc;
1535 	struct ceph_cap_snap *capsnap;
1536 	u64 oldest_flush_tid = 0;
1537 	u64 first_tid = 1, last_tid = 0;
1538 
1539 	dout("__flush_snaps %p session %p\n", inode, session);
1540 
1541 	list_for_each_entry(capsnap, &ci->i_cap_snaps, ci_item) {
1542 		/*
1543 		 * we need to wait for sync writes to complete and for dirty
1544 		 * pages to be written out.
1545 		 */
1546 		if (capsnap->dirty_pages || capsnap->writing)
1547 			break;
1548 
1549 		/* should be removed by ceph_try_drop_cap_snap() */
1550 		BUG_ON(!capsnap->need_flush);
1551 
1552 		/* only flush each capsnap once */
1553 		if (capsnap->cap_flush.tid > 0) {
1554 			dout(" already flushed %p, skipping\n", capsnap);
1555 			continue;
1556 		}
1557 
1558 		spin_lock(&mdsc->cap_dirty_lock);
1559 		capsnap->cap_flush.tid = ++mdsc->last_cap_flush_tid;
1560 		list_add_tail(&capsnap->cap_flush.g_list,
1561 			      &mdsc->cap_flush_list);
1562 		if (oldest_flush_tid == 0)
1563 			oldest_flush_tid = __get_oldest_flush_tid(mdsc);
1564 		if (list_empty(&ci->i_flushing_item)) {
1565 			list_add_tail(&ci->i_flushing_item,
1566 				      &session->s_cap_flushing);
1567 		}
1568 		spin_unlock(&mdsc->cap_dirty_lock);
1569 
1570 		list_add_tail(&capsnap->cap_flush.i_list,
1571 			      &ci->i_cap_flush_list);
1572 
1573 		if (first_tid == 1)
1574 			first_tid = capsnap->cap_flush.tid;
1575 		last_tid = capsnap->cap_flush.tid;
1576 	}
1577 
1578 	ci->i_ceph_flags &= ~CEPH_I_FLUSH_SNAPS;
1579 
1580 	while (first_tid <= last_tid) {
1581 		struct ceph_cap *cap = ci->i_auth_cap;
1582 		struct ceph_cap_flush *cf = NULL, *iter;
1583 		int ret;
1584 
1585 		if (!(cap && cap->session == session)) {
1586 			dout("__flush_snaps %p auth cap %p not mds%d, "
1587 			     "stop\n", inode, cap, session->s_mds);
1588 			break;
1589 		}
1590 
1591 		ret = -ENOENT;
1592 		list_for_each_entry(iter, &ci->i_cap_flush_list, i_list) {
1593 			if (iter->tid >= first_tid) {
1594 				cf = iter;
1595 				ret = 0;
1596 				break;
1597 			}
1598 		}
1599 		if (ret < 0)
1600 			break;
1601 
1602 		first_tid = cf->tid + 1;
1603 
1604 		capsnap = container_of(cf, struct ceph_cap_snap, cap_flush);
1605 		refcount_inc(&capsnap->nref);
1606 		spin_unlock(&ci->i_ceph_lock);
1607 
1608 		dout("__flush_snaps %p capsnap %p tid %llu %s\n",
1609 		     inode, capsnap, cf->tid, ceph_cap_string(capsnap->dirty));
1610 
1611 		ret = __send_flush_snap(inode, session, capsnap, cap->mseq,
1612 					oldest_flush_tid);
1613 		if (ret < 0) {
1614 			pr_err("__flush_snaps: error sending cap flushsnap, "
1615 			       "ino (%llx.%llx) tid %llu follows %llu\n",
1616 				ceph_vinop(inode), cf->tid, capsnap->follows);
1617 		}
1618 
1619 		ceph_put_cap_snap(capsnap);
1620 		spin_lock(&ci->i_ceph_lock);
1621 	}
1622 }
1623 
1624 void ceph_flush_snaps(struct ceph_inode_info *ci,
1625 		      struct ceph_mds_session **psession)
1626 {
1627 	struct inode *inode = &ci->netfs.inode;
1628 	struct ceph_mds_client *mdsc = ceph_inode_to_client(inode)->mdsc;
1629 	struct ceph_mds_session *session = NULL;
1630 	bool need_put = false;
1631 	int mds;
1632 
1633 	dout("ceph_flush_snaps %p\n", inode);
1634 	if (psession)
1635 		session = *psession;
1636 retry:
1637 	spin_lock(&ci->i_ceph_lock);
1638 	if (!(ci->i_ceph_flags & CEPH_I_FLUSH_SNAPS)) {
1639 		dout(" no capsnap needs flush, doing nothing\n");
1640 		goto out;
1641 	}
1642 	if (!ci->i_auth_cap) {
1643 		dout(" no auth cap (migrating?), doing nothing\n");
1644 		goto out;
1645 	}
1646 
1647 	mds = ci->i_auth_cap->session->s_mds;
1648 	if (session && session->s_mds != mds) {
1649 		dout(" oops, wrong session %p mutex\n", session);
1650 		ceph_put_mds_session(session);
1651 		session = NULL;
1652 	}
1653 	if (!session) {
1654 		spin_unlock(&ci->i_ceph_lock);
1655 		mutex_lock(&mdsc->mutex);
1656 		session = __ceph_lookup_mds_session(mdsc, mds);
1657 		mutex_unlock(&mdsc->mutex);
1658 		goto retry;
1659 	}
1660 
1661 	// make sure flushsnap messages are sent in proper order.
1662 	if (ci->i_ceph_flags & CEPH_I_KICK_FLUSH)
1663 		__kick_flushing_caps(mdsc, session, ci, 0);
1664 
1665 	__ceph_flush_snaps(ci, session);
1666 out:
1667 	spin_unlock(&ci->i_ceph_lock);
1668 
1669 	if (psession)
1670 		*psession = session;
1671 	else
1672 		ceph_put_mds_session(session);
1673 	/* we flushed them all; remove this inode from the queue */
1674 	spin_lock(&mdsc->snap_flush_lock);
1675 	if (!list_empty(&ci->i_snap_flush_item))
1676 		need_put = true;
1677 	list_del_init(&ci->i_snap_flush_item);
1678 	spin_unlock(&mdsc->snap_flush_lock);
1679 
1680 	if (need_put)
1681 		iput(inode);
1682 }
1683 
1684 /*
1685  * Mark caps dirty.  If inode is newly dirty, return the dirty flags.
1686  * Caller is then responsible for calling __mark_inode_dirty with the
1687  * returned flags value.
1688  */
1689 int __ceph_mark_dirty_caps(struct ceph_inode_info *ci, int mask,
1690 			   struct ceph_cap_flush **pcf)
1691 {
1692 	struct ceph_mds_client *mdsc =
1693 		ceph_sb_to_client(ci->netfs.inode.i_sb)->mdsc;
1694 	struct inode *inode = &ci->netfs.inode;
1695 	int was = ci->i_dirty_caps;
1696 	int dirty = 0;
1697 
1698 	lockdep_assert_held(&ci->i_ceph_lock);
1699 
1700 	if (!ci->i_auth_cap) {
1701 		pr_warn("__mark_dirty_caps %p %llx mask %s, "
1702 			"but no auth cap (session was closed?)\n",
1703 			inode, ceph_ino(inode), ceph_cap_string(mask));
1704 		return 0;
1705 	}
1706 
1707 	dout("__mark_dirty_caps %p %s dirty %s -> %s\n", &ci->netfs.inode,
1708 	     ceph_cap_string(mask), ceph_cap_string(was),
1709 	     ceph_cap_string(was | mask));
1710 	ci->i_dirty_caps |= mask;
1711 	if (was == 0) {
1712 		struct ceph_mds_session *session = ci->i_auth_cap->session;
1713 
1714 		WARN_ON_ONCE(ci->i_prealloc_cap_flush);
1715 		swap(ci->i_prealloc_cap_flush, *pcf);
1716 
1717 		if (!ci->i_head_snapc) {
1718 			WARN_ON_ONCE(!rwsem_is_locked(&mdsc->snap_rwsem));
1719 			ci->i_head_snapc = ceph_get_snap_context(
1720 				ci->i_snap_realm->cached_context);
1721 		}
1722 		dout(" inode %p now dirty snapc %p auth cap %p\n",
1723 		     &ci->netfs.inode, ci->i_head_snapc, ci->i_auth_cap);
1724 		BUG_ON(!list_empty(&ci->i_dirty_item));
1725 		spin_lock(&mdsc->cap_dirty_lock);
1726 		list_add(&ci->i_dirty_item, &session->s_cap_dirty);
1727 		spin_unlock(&mdsc->cap_dirty_lock);
1728 		if (ci->i_flushing_caps == 0) {
1729 			ihold(inode);
1730 			dirty |= I_DIRTY_SYNC;
1731 		}
1732 	} else {
1733 		WARN_ON_ONCE(!ci->i_prealloc_cap_flush);
1734 	}
1735 	BUG_ON(list_empty(&ci->i_dirty_item));
1736 	if (((was | ci->i_flushing_caps) & CEPH_CAP_FILE_BUFFER) &&
1737 	    (mask & CEPH_CAP_FILE_BUFFER))
1738 		dirty |= I_DIRTY_DATASYNC;
1739 	__cap_delay_requeue(mdsc, ci);
1740 	return dirty;
1741 }
1742 
1743 struct ceph_cap_flush *ceph_alloc_cap_flush(void)
1744 {
1745 	struct ceph_cap_flush *cf;
1746 
1747 	cf = kmem_cache_alloc(ceph_cap_flush_cachep, GFP_KERNEL);
1748 	if (!cf)
1749 		return NULL;
1750 
1751 	cf->is_capsnap = false;
1752 	return cf;
1753 }
1754 
1755 void ceph_free_cap_flush(struct ceph_cap_flush *cf)
1756 {
1757 	if (cf)
1758 		kmem_cache_free(ceph_cap_flush_cachep, cf);
1759 }
1760 
1761 static u64 __get_oldest_flush_tid(struct ceph_mds_client *mdsc)
1762 {
1763 	if (!list_empty(&mdsc->cap_flush_list)) {
1764 		struct ceph_cap_flush *cf =
1765 			list_first_entry(&mdsc->cap_flush_list,
1766 					 struct ceph_cap_flush, g_list);
1767 		return cf->tid;
1768 	}
1769 	return 0;
1770 }
1771 
1772 /*
1773  * Remove cap_flush from the mdsc's or inode's flushing cap list.
1774  * Return true if caller needs to wake up flush waiters.
1775  */
1776 static bool __detach_cap_flush_from_mdsc(struct ceph_mds_client *mdsc,
1777 					 struct ceph_cap_flush *cf)
1778 {
1779 	struct ceph_cap_flush *prev;
1780 	bool wake = cf->wake;
1781 
1782 	if (wake && cf->g_list.prev != &mdsc->cap_flush_list) {
1783 		prev = list_prev_entry(cf, g_list);
1784 		prev->wake = true;
1785 		wake = false;
1786 	}
1787 	list_del_init(&cf->g_list);
1788 	return wake;
1789 }
1790 
1791 static bool __detach_cap_flush_from_ci(struct ceph_inode_info *ci,
1792 				       struct ceph_cap_flush *cf)
1793 {
1794 	struct ceph_cap_flush *prev;
1795 	bool wake = cf->wake;
1796 
1797 	if (wake && cf->i_list.prev != &ci->i_cap_flush_list) {
1798 		prev = list_prev_entry(cf, i_list);
1799 		prev->wake = true;
1800 		wake = false;
1801 	}
1802 	list_del_init(&cf->i_list);
1803 	return wake;
1804 }
1805 
1806 /*
1807  * Add dirty inode to the flushing list.  Assigned a seq number so we
1808  * can wait for caps to flush without starving.
1809  *
1810  * Called under i_ceph_lock. Returns the flush tid.
1811  */
1812 static u64 __mark_caps_flushing(struct inode *inode,
1813 				struct ceph_mds_session *session, bool wake,
1814 				u64 *oldest_flush_tid)
1815 {
1816 	struct ceph_mds_client *mdsc = ceph_sb_to_client(inode->i_sb)->mdsc;
1817 	struct ceph_inode_info *ci = ceph_inode(inode);
1818 	struct ceph_cap_flush *cf = NULL;
1819 	int flushing;
1820 
1821 	lockdep_assert_held(&ci->i_ceph_lock);
1822 	BUG_ON(ci->i_dirty_caps == 0);
1823 	BUG_ON(list_empty(&ci->i_dirty_item));
1824 	BUG_ON(!ci->i_prealloc_cap_flush);
1825 
1826 	flushing = ci->i_dirty_caps;
1827 	dout("__mark_caps_flushing flushing %s, flushing_caps %s -> %s\n",
1828 	     ceph_cap_string(flushing),
1829 	     ceph_cap_string(ci->i_flushing_caps),
1830 	     ceph_cap_string(ci->i_flushing_caps | flushing));
1831 	ci->i_flushing_caps |= flushing;
1832 	ci->i_dirty_caps = 0;
1833 	dout(" inode %p now !dirty\n", inode);
1834 
1835 	swap(cf, ci->i_prealloc_cap_flush);
1836 	cf->caps = flushing;
1837 	cf->wake = wake;
1838 
1839 	spin_lock(&mdsc->cap_dirty_lock);
1840 	list_del_init(&ci->i_dirty_item);
1841 
1842 	cf->tid = ++mdsc->last_cap_flush_tid;
1843 	list_add_tail(&cf->g_list, &mdsc->cap_flush_list);
1844 	*oldest_flush_tid = __get_oldest_flush_tid(mdsc);
1845 
1846 	if (list_empty(&ci->i_flushing_item)) {
1847 		list_add_tail(&ci->i_flushing_item, &session->s_cap_flushing);
1848 		mdsc->num_cap_flushing++;
1849 	}
1850 	spin_unlock(&mdsc->cap_dirty_lock);
1851 
1852 	list_add_tail(&cf->i_list, &ci->i_cap_flush_list);
1853 
1854 	return cf->tid;
1855 }
1856 
1857 /*
1858  * try to invalidate mapping pages without blocking.
1859  */
1860 static int try_nonblocking_invalidate(struct inode *inode)
1861 	__releases(ci->i_ceph_lock)
1862 	__acquires(ci->i_ceph_lock)
1863 {
1864 	struct ceph_inode_info *ci = ceph_inode(inode);
1865 	u32 invalidating_gen = ci->i_rdcache_gen;
1866 
1867 	spin_unlock(&ci->i_ceph_lock);
1868 	ceph_fscache_invalidate(inode, false);
1869 	invalidate_mapping_pages(&inode->i_data, 0, -1);
1870 	spin_lock(&ci->i_ceph_lock);
1871 
1872 	if (inode->i_data.nrpages == 0 &&
1873 	    invalidating_gen == ci->i_rdcache_gen) {
1874 		/* success. */
1875 		dout("try_nonblocking_invalidate %p success\n", inode);
1876 		/* save any racing async invalidate some trouble */
1877 		ci->i_rdcache_revoking = ci->i_rdcache_gen - 1;
1878 		return 0;
1879 	}
1880 	dout("try_nonblocking_invalidate %p failed\n", inode);
1881 	return -1;
1882 }
1883 
1884 bool __ceph_should_report_size(struct ceph_inode_info *ci)
1885 {
1886 	loff_t size = i_size_read(&ci->netfs.inode);
1887 	/* mds will adjust max size according to the reported size */
1888 	if (ci->i_flushing_caps & CEPH_CAP_FILE_WR)
1889 		return false;
1890 	if (size >= ci->i_max_size)
1891 		return true;
1892 	/* half of previous max_size increment has been used */
1893 	if (ci->i_max_size > ci->i_reported_size &&
1894 	    (size << 1) >= ci->i_max_size + ci->i_reported_size)
1895 		return true;
1896 	return false;
1897 }
1898 
1899 /*
1900  * Swiss army knife function to examine currently used and wanted
1901  * versus held caps.  Release, flush, ack revoked caps to mds as
1902  * appropriate.
1903  *
1904  *  CHECK_CAPS_AUTHONLY - we should only check the auth cap
1905  *  CHECK_CAPS_FLUSH - we should flush any dirty caps immediately, without
1906  *    further delay.
1907  */
1908 void ceph_check_caps(struct ceph_inode_info *ci, int flags)
1909 {
1910 	struct inode *inode = &ci->netfs.inode;
1911 	struct ceph_mds_client *mdsc = ceph_sb_to_mdsc(inode->i_sb);
1912 	struct ceph_cap *cap;
1913 	u64 flush_tid, oldest_flush_tid;
1914 	int file_wanted, used, cap_used;
1915 	int issued, implemented, want, retain, revoking, flushing = 0;
1916 	int mds = -1;   /* keep track of how far we've gone through i_caps list
1917 			   to avoid an infinite loop on retry */
1918 	struct rb_node *p;
1919 	bool queue_invalidate = false;
1920 	bool tried_invalidate = false;
1921 	bool queue_writeback = false;
1922 	struct ceph_mds_session *session = NULL;
1923 
1924 	spin_lock(&ci->i_ceph_lock);
1925 	if (ci->i_ceph_flags & CEPH_I_ASYNC_CREATE) {
1926 		ci->i_ceph_flags |= CEPH_I_ASYNC_CHECK_CAPS;
1927 
1928 		/* Don't send messages until we get async create reply */
1929 		spin_unlock(&ci->i_ceph_lock);
1930 		return;
1931 	}
1932 
1933 	if (ci->i_ceph_flags & CEPH_I_FLUSH)
1934 		flags |= CHECK_CAPS_FLUSH;
1935 retry:
1936 	/* Caps wanted by virtue of active open files. */
1937 	file_wanted = __ceph_caps_file_wanted(ci);
1938 
1939 	/* Caps which have active references against them */
1940 	used = __ceph_caps_used(ci);
1941 
1942 	/*
1943 	 * "issued" represents the current caps that the MDS wants us to have.
1944 	 * "implemented" is the set that we have been granted, and includes the
1945 	 * ones that have not yet been returned to the MDS (the "revoking" set,
1946 	 * usually because they have outstanding references).
1947 	 */
1948 	issued = __ceph_caps_issued(ci, &implemented);
1949 	revoking = implemented & ~issued;
1950 
1951 	want = file_wanted;
1952 
1953 	/* The ones we currently want to retain (may be adjusted below) */
1954 	retain = file_wanted | used | CEPH_CAP_PIN;
1955 	if (!mdsc->stopping && inode->i_nlink > 0) {
1956 		if (file_wanted) {
1957 			retain |= CEPH_CAP_ANY;       /* be greedy */
1958 		} else if (S_ISDIR(inode->i_mode) &&
1959 			   (issued & CEPH_CAP_FILE_SHARED) &&
1960 			   __ceph_dir_is_complete(ci)) {
1961 			/*
1962 			 * If a directory is complete, we want to keep
1963 			 * the exclusive cap. So that MDS does not end up
1964 			 * revoking the shared cap on every create/unlink
1965 			 * operation.
1966 			 */
1967 			if (IS_RDONLY(inode)) {
1968 				want = CEPH_CAP_ANY_SHARED;
1969 			} else {
1970 				want |= CEPH_CAP_ANY_SHARED | CEPH_CAP_FILE_EXCL;
1971 			}
1972 			retain |= want;
1973 		} else {
1974 
1975 			retain |= CEPH_CAP_ANY_SHARED;
1976 			/*
1977 			 * keep RD only if we didn't have the file open RW,
1978 			 * because then the mds would revoke it anyway to
1979 			 * journal max_size=0.
1980 			 */
1981 			if (ci->i_max_size == 0)
1982 				retain |= CEPH_CAP_ANY_RD;
1983 		}
1984 	}
1985 
1986 	dout("check_caps %llx.%llx file_want %s used %s dirty %s flushing %s"
1987 	     " issued %s revoking %s retain %s %s%s%s\n", ceph_vinop(inode),
1988 	     ceph_cap_string(file_wanted),
1989 	     ceph_cap_string(used), ceph_cap_string(ci->i_dirty_caps),
1990 	     ceph_cap_string(ci->i_flushing_caps),
1991 	     ceph_cap_string(issued), ceph_cap_string(revoking),
1992 	     ceph_cap_string(retain),
1993 	     (flags & CHECK_CAPS_AUTHONLY) ? " AUTHONLY" : "",
1994 	     (flags & CHECK_CAPS_FLUSH) ? " FLUSH" : "",
1995 	     (flags & CHECK_CAPS_NOINVAL) ? " NOINVAL" : "");
1996 
1997 	/*
1998 	 * If we no longer need to hold onto old our caps, and we may
1999 	 * have cached pages, but don't want them, then try to invalidate.
2000 	 * If we fail, it's because pages are locked.... try again later.
2001 	 */
2002 	if ((!(flags & CHECK_CAPS_NOINVAL) || mdsc->stopping) &&
2003 	    S_ISREG(inode->i_mode) &&
2004 	    !(ci->i_wb_ref || ci->i_wrbuffer_ref) &&   /* no dirty pages... */
2005 	    inode->i_data.nrpages &&		/* have cached pages */
2006 	    (revoking & (CEPH_CAP_FILE_CACHE|
2007 			 CEPH_CAP_FILE_LAZYIO)) && /*  or revoking cache */
2008 	    !tried_invalidate) {
2009 		dout("check_caps trying to invalidate on %llx.%llx\n",
2010 		     ceph_vinop(inode));
2011 		if (try_nonblocking_invalidate(inode) < 0) {
2012 			dout("check_caps queuing invalidate\n");
2013 			queue_invalidate = true;
2014 			ci->i_rdcache_revoking = ci->i_rdcache_gen;
2015 		}
2016 		tried_invalidate = true;
2017 		goto retry;
2018 	}
2019 
2020 	for (p = rb_first(&ci->i_caps); p; p = rb_next(p)) {
2021 		int mflags = 0;
2022 		struct cap_msg_args arg;
2023 
2024 		cap = rb_entry(p, struct ceph_cap, ci_node);
2025 
2026 		/* avoid looping forever */
2027 		if (mds >= cap->mds ||
2028 		    ((flags & CHECK_CAPS_AUTHONLY) && cap != ci->i_auth_cap))
2029 			continue;
2030 
2031 		/*
2032 		 * If we have an auth cap, we don't need to consider any
2033 		 * overlapping caps as used.
2034 		 */
2035 		cap_used = used;
2036 		if (ci->i_auth_cap && cap != ci->i_auth_cap)
2037 			cap_used &= ~ci->i_auth_cap->issued;
2038 
2039 		revoking = cap->implemented & ~cap->issued;
2040 		dout(" mds%d cap %p used %s issued %s implemented %s revoking %s\n",
2041 		     cap->mds, cap, ceph_cap_string(cap_used),
2042 		     ceph_cap_string(cap->issued),
2043 		     ceph_cap_string(cap->implemented),
2044 		     ceph_cap_string(revoking));
2045 
2046 		if (cap == ci->i_auth_cap &&
2047 		    (cap->issued & CEPH_CAP_FILE_WR)) {
2048 			/* request larger max_size from MDS? */
2049 			if (ci->i_wanted_max_size > ci->i_max_size &&
2050 			    ci->i_wanted_max_size > ci->i_requested_max_size) {
2051 				dout("requesting new max_size\n");
2052 				goto ack;
2053 			}
2054 
2055 			/* approaching file_max? */
2056 			if (__ceph_should_report_size(ci)) {
2057 				dout("i_size approaching max_size\n");
2058 				goto ack;
2059 			}
2060 		}
2061 		/* flush anything dirty? */
2062 		if (cap == ci->i_auth_cap) {
2063 			if ((flags & CHECK_CAPS_FLUSH) && ci->i_dirty_caps) {
2064 				dout("flushing dirty caps\n");
2065 				goto ack;
2066 			}
2067 			if (ci->i_ceph_flags & CEPH_I_FLUSH_SNAPS) {
2068 				dout("flushing snap caps\n");
2069 				goto ack;
2070 			}
2071 		}
2072 
2073 		/* completed revocation? going down and there are no caps? */
2074 		if (revoking) {
2075 			if ((revoking & cap_used) == 0) {
2076 				dout("completed revocation of %s\n",
2077 				      ceph_cap_string(cap->implemented & ~cap->issued));
2078 				goto ack;
2079 			}
2080 
2081 			/*
2082 			 * If the "i_wrbuffer_ref" was increased by mmap or generic
2083 			 * cache write just before the ceph_check_caps() is called,
2084 			 * the Fb capability revoking will fail this time. Then we
2085 			 * must wait for the BDI's delayed work to flush the dirty
2086 			 * pages and to release the "i_wrbuffer_ref", which will cost
2087 			 * at most 5 seconds. That means the MDS needs to wait at
2088 			 * most 5 seconds to finished the Fb capability's revocation.
2089 			 *
2090 			 * Let's queue a writeback for it.
2091 			 */
2092 			if (S_ISREG(inode->i_mode) && ci->i_wrbuffer_ref &&
2093 			    (revoking & CEPH_CAP_FILE_BUFFER))
2094 				queue_writeback = true;
2095 		}
2096 
2097 		/* want more caps from mds? */
2098 		if (want & ~cap->mds_wanted) {
2099 			if (want & ~(cap->mds_wanted | cap->issued))
2100 				goto ack;
2101 			if (!__cap_is_valid(cap))
2102 				goto ack;
2103 		}
2104 
2105 		/* things we might delay */
2106 		if ((cap->issued & ~retain) == 0)
2107 			continue;     /* nope, all good */
2108 
2109 ack:
2110 		ceph_put_mds_session(session);
2111 		session = ceph_get_mds_session(cap->session);
2112 
2113 		/* kick flushing and flush snaps before sending normal
2114 		 * cap message */
2115 		if (cap == ci->i_auth_cap &&
2116 		    (ci->i_ceph_flags &
2117 		     (CEPH_I_KICK_FLUSH | CEPH_I_FLUSH_SNAPS))) {
2118 			if (ci->i_ceph_flags & CEPH_I_KICK_FLUSH)
2119 				__kick_flushing_caps(mdsc, session, ci, 0);
2120 			if (ci->i_ceph_flags & CEPH_I_FLUSH_SNAPS)
2121 				__ceph_flush_snaps(ci, session);
2122 
2123 			goto retry;
2124 		}
2125 
2126 		if (cap == ci->i_auth_cap && ci->i_dirty_caps) {
2127 			flushing = ci->i_dirty_caps;
2128 			flush_tid = __mark_caps_flushing(inode, session, false,
2129 							 &oldest_flush_tid);
2130 			if (flags & CHECK_CAPS_FLUSH &&
2131 			    list_empty(&session->s_cap_dirty))
2132 				mflags |= CEPH_CLIENT_CAPS_SYNC;
2133 		} else {
2134 			flushing = 0;
2135 			flush_tid = 0;
2136 			spin_lock(&mdsc->cap_dirty_lock);
2137 			oldest_flush_tid = __get_oldest_flush_tid(mdsc);
2138 			spin_unlock(&mdsc->cap_dirty_lock);
2139 		}
2140 
2141 		mds = cap->mds;  /* remember mds, so we don't repeat */
2142 
2143 		__prep_cap(&arg, cap, CEPH_CAP_OP_UPDATE, mflags, cap_used,
2144 			   want, retain, flushing, flush_tid, oldest_flush_tid);
2145 
2146 		spin_unlock(&ci->i_ceph_lock);
2147 		__send_cap(&arg, ci);
2148 		spin_lock(&ci->i_ceph_lock);
2149 
2150 		goto retry; /* retake i_ceph_lock and restart our cap scan. */
2151 	}
2152 
2153 	/* periodically re-calculate caps wanted by open files */
2154 	if (__ceph_is_any_real_caps(ci) &&
2155 	    list_empty(&ci->i_cap_delay_list) &&
2156 	    (file_wanted & ~CEPH_CAP_PIN) &&
2157 	    !(used & (CEPH_CAP_FILE_RD | CEPH_CAP_ANY_FILE_WR))) {
2158 		__cap_delay_requeue(mdsc, ci);
2159 	}
2160 
2161 	spin_unlock(&ci->i_ceph_lock);
2162 
2163 	ceph_put_mds_session(session);
2164 	if (queue_writeback)
2165 		ceph_queue_writeback(inode);
2166 	if (queue_invalidate)
2167 		ceph_queue_invalidate(inode);
2168 }
2169 
2170 /*
2171  * Try to flush dirty caps back to the auth mds.
2172  */
2173 static int try_flush_caps(struct inode *inode, u64 *ptid)
2174 {
2175 	struct ceph_mds_client *mdsc = ceph_sb_to_client(inode->i_sb)->mdsc;
2176 	struct ceph_inode_info *ci = ceph_inode(inode);
2177 	int flushing = 0;
2178 	u64 flush_tid = 0, oldest_flush_tid = 0;
2179 
2180 	spin_lock(&ci->i_ceph_lock);
2181 retry_locked:
2182 	if (ci->i_dirty_caps && ci->i_auth_cap) {
2183 		struct ceph_cap *cap = ci->i_auth_cap;
2184 		struct cap_msg_args arg;
2185 		struct ceph_mds_session *session = cap->session;
2186 
2187 		if (session->s_state < CEPH_MDS_SESSION_OPEN) {
2188 			spin_unlock(&ci->i_ceph_lock);
2189 			goto out;
2190 		}
2191 
2192 		if (ci->i_ceph_flags &
2193 		    (CEPH_I_KICK_FLUSH | CEPH_I_FLUSH_SNAPS)) {
2194 			if (ci->i_ceph_flags & CEPH_I_KICK_FLUSH)
2195 				__kick_flushing_caps(mdsc, session, ci, 0);
2196 			if (ci->i_ceph_flags & CEPH_I_FLUSH_SNAPS)
2197 				__ceph_flush_snaps(ci, session);
2198 			goto retry_locked;
2199 		}
2200 
2201 		flushing = ci->i_dirty_caps;
2202 		flush_tid = __mark_caps_flushing(inode, session, true,
2203 						 &oldest_flush_tid);
2204 
2205 		__prep_cap(&arg, cap, CEPH_CAP_OP_FLUSH, CEPH_CLIENT_CAPS_SYNC,
2206 			   __ceph_caps_used(ci), __ceph_caps_wanted(ci),
2207 			   (cap->issued | cap->implemented),
2208 			   flushing, flush_tid, oldest_flush_tid);
2209 		spin_unlock(&ci->i_ceph_lock);
2210 
2211 		__send_cap(&arg, ci);
2212 	} else {
2213 		if (!list_empty(&ci->i_cap_flush_list)) {
2214 			struct ceph_cap_flush *cf =
2215 				list_last_entry(&ci->i_cap_flush_list,
2216 						struct ceph_cap_flush, i_list);
2217 			cf->wake = true;
2218 			flush_tid = cf->tid;
2219 		}
2220 		flushing = ci->i_flushing_caps;
2221 		spin_unlock(&ci->i_ceph_lock);
2222 	}
2223 out:
2224 	*ptid = flush_tid;
2225 	return flushing;
2226 }
2227 
2228 /*
2229  * Return true if we've flushed caps through the given flush_tid.
2230  */
2231 static int caps_are_flushed(struct inode *inode, u64 flush_tid)
2232 {
2233 	struct ceph_inode_info *ci = ceph_inode(inode);
2234 	int ret = 1;
2235 
2236 	spin_lock(&ci->i_ceph_lock);
2237 	if (!list_empty(&ci->i_cap_flush_list)) {
2238 		struct ceph_cap_flush * cf =
2239 			list_first_entry(&ci->i_cap_flush_list,
2240 					 struct ceph_cap_flush, i_list);
2241 		if (cf->tid <= flush_tid)
2242 			ret = 0;
2243 	}
2244 	spin_unlock(&ci->i_ceph_lock);
2245 	return ret;
2246 }
2247 
2248 /*
2249  * flush the mdlog and wait for any unsafe requests to complete.
2250  */
2251 static int flush_mdlog_and_wait_inode_unsafe_requests(struct inode *inode)
2252 {
2253 	struct ceph_mds_client *mdsc = ceph_sb_to_client(inode->i_sb)->mdsc;
2254 	struct ceph_inode_info *ci = ceph_inode(inode);
2255 	struct ceph_mds_request *req1 = NULL, *req2 = NULL;
2256 	int ret, err = 0;
2257 
2258 	spin_lock(&ci->i_unsafe_lock);
2259 	if (S_ISDIR(inode->i_mode) && !list_empty(&ci->i_unsafe_dirops)) {
2260 		req1 = list_last_entry(&ci->i_unsafe_dirops,
2261 					struct ceph_mds_request,
2262 					r_unsafe_dir_item);
2263 		ceph_mdsc_get_request(req1);
2264 	}
2265 	if (!list_empty(&ci->i_unsafe_iops)) {
2266 		req2 = list_last_entry(&ci->i_unsafe_iops,
2267 					struct ceph_mds_request,
2268 					r_unsafe_target_item);
2269 		ceph_mdsc_get_request(req2);
2270 	}
2271 	spin_unlock(&ci->i_unsafe_lock);
2272 
2273 	/*
2274 	 * Trigger to flush the journal logs in all the relevant MDSes
2275 	 * manually, or in the worst case we must wait at most 5 seconds
2276 	 * to wait the journal logs to be flushed by the MDSes periodically.
2277 	 */
2278 	if (req1 || req2) {
2279 		struct ceph_mds_request *req;
2280 		struct ceph_mds_session **sessions;
2281 		struct ceph_mds_session *s;
2282 		unsigned int max_sessions;
2283 		int i;
2284 
2285 		mutex_lock(&mdsc->mutex);
2286 		max_sessions = mdsc->max_sessions;
2287 
2288 		sessions = kcalloc(max_sessions, sizeof(s), GFP_KERNEL);
2289 		if (!sessions) {
2290 			mutex_unlock(&mdsc->mutex);
2291 			err = -ENOMEM;
2292 			goto out;
2293 		}
2294 
2295 		spin_lock(&ci->i_unsafe_lock);
2296 		if (req1) {
2297 			list_for_each_entry(req, &ci->i_unsafe_dirops,
2298 					    r_unsafe_dir_item) {
2299 				s = req->r_session;
2300 				if (!s)
2301 					continue;
2302 				if (!sessions[s->s_mds]) {
2303 					s = ceph_get_mds_session(s);
2304 					sessions[s->s_mds] = s;
2305 				}
2306 			}
2307 		}
2308 		if (req2) {
2309 			list_for_each_entry(req, &ci->i_unsafe_iops,
2310 					    r_unsafe_target_item) {
2311 				s = req->r_session;
2312 				if (!s)
2313 					continue;
2314 				if (!sessions[s->s_mds]) {
2315 					s = ceph_get_mds_session(s);
2316 					sessions[s->s_mds] = s;
2317 				}
2318 			}
2319 		}
2320 		spin_unlock(&ci->i_unsafe_lock);
2321 
2322 		/* the auth MDS */
2323 		spin_lock(&ci->i_ceph_lock);
2324 		if (ci->i_auth_cap) {
2325 			s = ci->i_auth_cap->session;
2326 			if (!sessions[s->s_mds])
2327 				sessions[s->s_mds] = ceph_get_mds_session(s);
2328 		}
2329 		spin_unlock(&ci->i_ceph_lock);
2330 		mutex_unlock(&mdsc->mutex);
2331 
2332 		/* send flush mdlog request to MDSes */
2333 		for (i = 0; i < max_sessions; i++) {
2334 			s = sessions[i];
2335 			if (s) {
2336 				send_flush_mdlog(s);
2337 				ceph_put_mds_session(s);
2338 			}
2339 		}
2340 		kfree(sessions);
2341 	}
2342 
2343 	dout("%s %p wait on tid %llu %llu\n", __func__,
2344 	     inode, req1 ? req1->r_tid : 0ULL, req2 ? req2->r_tid : 0ULL);
2345 	if (req1) {
2346 		ret = !wait_for_completion_timeout(&req1->r_safe_completion,
2347 					ceph_timeout_jiffies(req1->r_timeout));
2348 		if (ret)
2349 			err = -EIO;
2350 	}
2351 	if (req2) {
2352 		ret = !wait_for_completion_timeout(&req2->r_safe_completion,
2353 					ceph_timeout_jiffies(req2->r_timeout));
2354 		if (ret)
2355 			err = -EIO;
2356 	}
2357 
2358 out:
2359 	if (req1)
2360 		ceph_mdsc_put_request(req1);
2361 	if (req2)
2362 		ceph_mdsc_put_request(req2);
2363 	return err;
2364 }
2365 
2366 int ceph_fsync(struct file *file, loff_t start, loff_t end, int datasync)
2367 {
2368 	struct inode *inode = file->f_mapping->host;
2369 	struct ceph_inode_info *ci = ceph_inode(inode);
2370 	u64 flush_tid;
2371 	int ret, err;
2372 	int dirty;
2373 
2374 	dout("fsync %p%s\n", inode, datasync ? " datasync" : "");
2375 
2376 	ret = file_write_and_wait_range(file, start, end);
2377 	if (datasync)
2378 		goto out;
2379 
2380 	ret = ceph_wait_on_async_create(inode);
2381 	if (ret)
2382 		goto out;
2383 
2384 	dirty = try_flush_caps(inode, &flush_tid);
2385 	dout("fsync dirty caps are %s\n", ceph_cap_string(dirty));
2386 
2387 	err = flush_mdlog_and_wait_inode_unsafe_requests(inode);
2388 
2389 	/*
2390 	 * only wait on non-file metadata writeback (the mds
2391 	 * can recover size and mtime, so we don't need to
2392 	 * wait for that)
2393 	 */
2394 	if (!err && (dirty & ~CEPH_CAP_ANY_FILE_WR)) {
2395 		err = wait_event_interruptible(ci->i_cap_wq,
2396 					caps_are_flushed(inode, flush_tid));
2397 	}
2398 
2399 	if (err < 0)
2400 		ret = err;
2401 
2402 	err = file_check_and_advance_wb_err(file);
2403 	if (err < 0)
2404 		ret = err;
2405 out:
2406 	dout("fsync %p%s result=%d\n", inode, datasync ? " datasync" : "", ret);
2407 	return ret;
2408 }
2409 
2410 /*
2411  * Flush any dirty caps back to the mds.  If we aren't asked to wait,
2412  * queue inode for flush but don't do so immediately, because we can
2413  * get by with fewer MDS messages if we wait for data writeback to
2414  * complete first.
2415  */
2416 int ceph_write_inode(struct inode *inode, struct writeback_control *wbc)
2417 {
2418 	struct ceph_inode_info *ci = ceph_inode(inode);
2419 	u64 flush_tid;
2420 	int err = 0;
2421 	int dirty;
2422 	int wait = (wbc->sync_mode == WB_SYNC_ALL && !wbc->for_sync);
2423 
2424 	dout("write_inode %p wait=%d\n", inode, wait);
2425 	ceph_fscache_unpin_writeback(inode, wbc);
2426 	if (wait) {
2427 		err = ceph_wait_on_async_create(inode);
2428 		if (err)
2429 			return err;
2430 		dirty = try_flush_caps(inode, &flush_tid);
2431 		if (dirty)
2432 			err = wait_event_interruptible(ci->i_cap_wq,
2433 				       caps_are_flushed(inode, flush_tid));
2434 	} else {
2435 		struct ceph_mds_client *mdsc =
2436 			ceph_sb_to_client(inode->i_sb)->mdsc;
2437 
2438 		spin_lock(&ci->i_ceph_lock);
2439 		if (__ceph_caps_dirty(ci))
2440 			__cap_delay_requeue_front(mdsc, ci);
2441 		spin_unlock(&ci->i_ceph_lock);
2442 	}
2443 	return err;
2444 }
2445 
2446 static void __kick_flushing_caps(struct ceph_mds_client *mdsc,
2447 				 struct ceph_mds_session *session,
2448 				 struct ceph_inode_info *ci,
2449 				 u64 oldest_flush_tid)
2450 	__releases(ci->i_ceph_lock)
2451 	__acquires(ci->i_ceph_lock)
2452 {
2453 	struct inode *inode = &ci->netfs.inode;
2454 	struct ceph_cap *cap;
2455 	struct ceph_cap_flush *cf;
2456 	int ret;
2457 	u64 first_tid = 0;
2458 	u64 last_snap_flush = 0;
2459 
2460 	/* Don't do anything until create reply comes in */
2461 	if (ci->i_ceph_flags & CEPH_I_ASYNC_CREATE)
2462 		return;
2463 
2464 	ci->i_ceph_flags &= ~CEPH_I_KICK_FLUSH;
2465 
2466 	list_for_each_entry_reverse(cf, &ci->i_cap_flush_list, i_list) {
2467 		if (cf->is_capsnap) {
2468 			last_snap_flush = cf->tid;
2469 			break;
2470 		}
2471 	}
2472 
2473 	list_for_each_entry(cf, &ci->i_cap_flush_list, i_list) {
2474 		if (cf->tid < first_tid)
2475 			continue;
2476 
2477 		cap = ci->i_auth_cap;
2478 		if (!(cap && cap->session == session)) {
2479 			pr_err("%p auth cap %p not mds%d ???\n",
2480 			       inode, cap, session->s_mds);
2481 			break;
2482 		}
2483 
2484 		first_tid = cf->tid + 1;
2485 
2486 		if (!cf->is_capsnap) {
2487 			struct cap_msg_args arg;
2488 
2489 			dout("kick_flushing_caps %p cap %p tid %llu %s\n",
2490 			     inode, cap, cf->tid, ceph_cap_string(cf->caps));
2491 			__prep_cap(&arg, cap, CEPH_CAP_OP_FLUSH,
2492 					 (cf->tid < last_snap_flush ?
2493 					  CEPH_CLIENT_CAPS_PENDING_CAPSNAP : 0),
2494 					  __ceph_caps_used(ci),
2495 					  __ceph_caps_wanted(ci),
2496 					  (cap->issued | cap->implemented),
2497 					  cf->caps, cf->tid, oldest_flush_tid);
2498 			spin_unlock(&ci->i_ceph_lock);
2499 			__send_cap(&arg, ci);
2500 		} else {
2501 			struct ceph_cap_snap *capsnap =
2502 					container_of(cf, struct ceph_cap_snap,
2503 						    cap_flush);
2504 			dout("kick_flushing_caps %p capsnap %p tid %llu %s\n",
2505 			     inode, capsnap, cf->tid,
2506 			     ceph_cap_string(capsnap->dirty));
2507 
2508 			refcount_inc(&capsnap->nref);
2509 			spin_unlock(&ci->i_ceph_lock);
2510 
2511 			ret = __send_flush_snap(inode, session, capsnap, cap->mseq,
2512 						oldest_flush_tid);
2513 			if (ret < 0) {
2514 				pr_err("kick_flushing_caps: error sending "
2515 					"cap flushsnap, ino (%llx.%llx) "
2516 					"tid %llu follows %llu\n",
2517 					ceph_vinop(inode), cf->tid,
2518 					capsnap->follows);
2519 			}
2520 
2521 			ceph_put_cap_snap(capsnap);
2522 		}
2523 
2524 		spin_lock(&ci->i_ceph_lock);
2525 	}
2526 }
2527 
2528 void ceph_early_kick_flushing_caps(struct ceph_mds_client *mdsc,
2529 				   struct ceph_mds_session *session)
2530 {
2531 	struct ceph_inode_info *ci;
2532 	struct ceph_cap *cap;
2533 	u64 oldest_flush_tid;
2534 
2535 	dout("early_kick_flushing_caps mds%d\n", session->s_mds);
2536 
2537 	spin_lock(&mdsc->cap_dirty_lock);
2538 	oldest_flush_tid = __get_oldest_flush_tid(mdsc);
2539 	spin_unlock(&mdsc->cap_dirty_lock);
2540 
2541 	list_for_each_entry(ci, &session->s_cap_flushing, i_flushing_item) {
2542 		spin_lock(&ci->i_ceph_lock);
2543 		cap = ci->i_auth_cap;
2544 		if (!(cap && cap->session == session)) {
2545 			pr_err("%p auth cap %p not mds%d ???\n",
2546 				&ci->netfs.inode, cap, session->s_mds);
2547 			spin_unlock(&ci->i_ceph_lock);
2548 			continue;
2549 		}
2550 
2551 
2552 		/*
2553 		 * if flushing caps were revoked, we re-send the cap flush
2554 		 * in client reconnect stage. This guarantees MDS * processes
2555 		 * the cap flush message before issuing the flushing caps to
2556 		 * other client.
2557 		 */
2558 		if ((cap->issued & ci->i_flushing_caps) !=
2559 		    ci->i_flushing_caps) {
2560 			/* encode_caps_cb() also will reset these sequence
2561 			 * numbers. make sure sequence numbers in cap flush
2562 			 * message match later reconnect message */
2563 			cap->seq = 0;
2564 			cap->issue_seq = 0;
2565 			cap->mseq = 0;
2566 			__kick_flushing_caps(mdsc, session, ci,
2567 					     oldest_flush_tid);
2568 		} else {
2569 			ci->i_ceph_flags |= CEPH_I_KICK_FLUSH;
2570 		}
2571 
2572 		spin_unlock(&ci->i_ceph_lock);
2573 	}
2574 }
2575 
2576 void ceph_kick_flushing_caps(struct ceph_mds_client *mdsc,
2577 			     struct ceph_mds_session *session)
2578 {
2579 	struct ceph_inode_info *ci;
2580 	struct ceph_cap *cap;
2581 	u64 oldest_flush_tid;
2582 
2583 	lockdep_assert_held(&session->s_mutex);
2584 
2585 	dout("kick_flushing_caps mds%d\n", session->s_mds);
2586 
2587 	spin_lock(&mdsc->cap_dirty_lock);
2588 	oldest_flush_tid = __get_oldest_flush_tid(mdsc);
2589 	spin_unlock(&mdsc->cap_dirty_lock);
2590 
2591 	list_for_each_entry(ci, &session->s_cap_flushing, i_flushing_item) {
2592 		spin_lock(&ci->i_ceph_lock);
2593 		cap = ci->i_auth_cap;
2594 		if (!(cap && cap->session == session)) {
2595 			pr_err("%p auth cap %p not mds%d ???\n",
2596 				&ci->netfs.inode, cap, session->s_mds);
2597 			spin_unlock(&ci->i_ceph_lock);
2598 			continue;
2599 		}
2600 		if (ci->i_ceph_flags & CEPH_I_KICK_FLUSH) {
2601 			__kick_flushing_caps(mdsc, session, ci,
2602 					     oldest_flush_tid);
2603 		}
2604 		spin_unlock(&ci->i_ceph_lock);
2605 	}
2606 }
2607 
2608 void ceph_kick_flushing_inode_caps(struct ceph_mds_session *session,
2609 				   struct ceph_inode_info *ci)
2610 {
2611 	struct ceph_mds_client *mdsc = session->s_mdsc;
2612 	struct ceph_cap *cap = ci->i_auth_cap;
2613 
2614 	lockdep_assert_held(&ci->i_ceph_lock);
2615 
2616 	dout("%s %p flushing %s\n", __func__, &ci->netfs.inode,
2617 	     ceph_cap_string(ci->i_flushing_caps));
2618 
2619 	if (!list_empty(&ci->i_cap_flush_list)) {
2620 		u64 oldest_flush_tid;
2621 		spin_lock(&mdsc->cap_dirty_lock);
2622 		list_move_tail(&ci->i_flushing_item,
2623 			       &cap->session->s_cap_flushing);
2624 		oldest_flush_tid = __get_oldest_flush_tid(mdsc);
2625 		spin_unlock(&mdsc->cap_dirty_lock);
2626 
2627 		__kick_flushing_caps(mdsc, session, ci, oldest_flush_tid);
2628 	}
2629 }
2630 
2631 
2632 /*
2633  * Take references to capabilities we hold, so that we don't release
2634  * them to the MDS prematurely.
2635  */
2636 void ceph_take_cap_refs(struct ceph_inode_info *ci, int got,
2637 			    bool snap_rwsem_locked)
2638 {
2639 	lockdep_assert_held(&ci->i_ceph_lock);
2640 
2641 	if (got & CEPH_CAP_PIN)
2642 		ci->i_pin_ref++;
2643 	if (got & CEPH_CAP_FILE_RD)
2644 		ci->i_rd_ref++;
2645 	if (got & CEPH_CAP_FILE_CACHE)
2646 		ci->i_rdcache_ref++;
2647 	if (got & CEPH_CAP_FILE_EXCL)
2648 		ci->i_fx_ref++;
2649 	if (got & CEPH_CAP_FILE_WR) {
2650 		if (ci->i_wr_ref == 0 && !ci->i_head_snapc) {
2651 			BUG_ON(!snap_rwsem_locked);
2652 			ci->i_head_snapc = ceph_get_snap_context(
2653 					ci->i_snap_realm->cached_context);
2654 		}
2655 		ci->i_wr_ref++;
2656 	}
2657 	if (got & CEPH_CAP_FILE_BUFFER) {
2658 		if (ci->i_wb_ref == 0)
2659 			ihold(&ci->netfs.inode);
2660 		ci->i_wb_ref++;
2661 		dout("%s %p wb %d -> %d (?)\n", __func__,
2662 		     &ci->netfs.inode, ci->i_wb_ref-1, ci->i_wb_ref);
2663 	}
2664 }
2665 
2666 /*
2667  * Try to grab cap references.  Specify those refs we @want, and the
2668  * minimal set we @need.  Also include the larger offset we are writing
2669  * to (when applicable), and check against max_size here as well.
2670  * Note that caller is responsible for ensuring max_size increases are
2671  * requested from the MDS.
2672  *
2673  * Returns 0 if caps were not able to be acquired (yet), 1 if succeed,
2674  * or a negative error code. There are 3 speical error codes:
2675  *  -EAGAIN:  need to sleep but non-blocking is specified
2676  *  -EFBIG:   ask caller to call check_max_size() and try again.
2677  *  -EUCLEAN: ask caller to call ceph_renew_caps() and try again.
2678  */
2679 enum {
2680 	/* first 8 bits are reserved for CEPH_FILE_MODE_FOO */
2681 	NON_BLOCKING	= (1 << 8),
2682 	CHECK_FILELOCK	= (1 << 9),
2683 };
2684 
2685 static int try_get_cap_refs(struct inode *inode, int need, int want,
2686 			    loff_t endoff, int flags, int *got)
2687 {
2688 	struct ceph_inode_info *ci = ceph_inode(inode);
2689 	struct ceph_mds_client *mdsc = ceph_inode_to_client(inode)->mdsc;
2690 	int ret = 0;
2691 	int have, implemented;
2692 	bool snap_rwsem_locked = false;
2693 
2694 	dout("get_cap_refs %p need %s want %s\n", inode,
2695 	     ceph_cap_string(need), ceph_cap_string(want));
2696 
2697 again:
2698 	spin_lock(&ci->i_ceph_lock);
2699 
2700 	if ((flags & CHECK_FILELOCK) &&
2701 	    (ci->i_ceph_flags & CEPH_I_ERROR_FILELOCK)) {
2702 		dout("try_get_cap_refs %p error filelock\n", inode);
2703 		ret = -EIO;
2704 		goto out_unlock;
2705 	}
2706 
2707 	/* finish pending truncate */
2708 	while (ci->i_truncate_pending) {
2709 		spin_unlock(&ci->i_ceph_lock);
2710 		if (snap_rwsem_locked) {
2711 			up_read(&mdsc->snap_rwsem);
2712 			snap_rwsem_locked = false;
2713 		}
2714 		__ceph_do_pending_vmtruncate(inode);
2715 		spin_lock(&ci->i_ceph_lock);
2716 	}
2717 
2718 	have = __ceph_caps_issued(ci, &implemented);
2719 
2720 	if (have & need & CEPH_CAP_FILE_WR) {
2721 		if (endoff >= 0 && endoff > (loff_t)ci->i_max_size) {
2722 			dout("get_cap_refs %p endoff %llu > maxsize %llu\n",
2723 			     inode, endoff, ci->i_max_size);
2724 			if (endoff > ci->i_requested_max_size)
2725 				ret = ci->i_auth_cap ? -EFBIG : -EUCLEAN;
2726 			goto out_unlock;
2727 		}
2728 		/*
2729 		 * If a sync write is in progress, we must wait, so that we
2730 		 * can get a final snapshot value for size+mtime.
2731 		 */
2732 		if (__ceph_have_pending_cap_snap(ci)) {
2733 			dout("get_cap_refs %p cap_snap_pending\n", inode);
2734 			goto out_unlock;
2735 		}
2736 	}
2737 
2738 	if ((have & need) == need) {
2739 		/*
2740 		 * Look at (implemented & ~have & not) so that we keep waiting
2741 		 * on transition from wanted -> needed caps.  This is needed
2742 		 * for WRBUFFER|WR -> WR to avoid a new WR sync write from
2743 		 * going before a prior buffered writeback happens.
2744 		 *
2745 		 * For RDCACHE|RD -> RD, there is not need to wait and we can
2746 		 * just exclude the revoking caps and force to sync read.
2747 		 */
2748 		int not = want & ~(have & need);
2749 		int revoking = implemented & ~have;
2750 		int exclude = revoking & not;
2751 		dout("get_cap_refs %p have %s but not %s (revoking %s)\n",
2752 		     inode, ceph_cap_string(have), ceph_cap_string(not),
2753 		     ceph_cap_string(revoking));
2754 		if (!exclude || !(exclude & CEPH_CAP_FILE_BUFFER)) {
2755 			if (!snap_rwsem_locked &&
2756 			    !ci->i_head_snapc &&
2757 			    (need & CEPH_CAP_FILE_WR)) {
2758 				if (!down_read_trylock(&mdsc->snap_rwsem)) {
2759 					/*
2760 					 * we can not call down_read() when
2761 					 * task isn't in TASK_RUNNING state
2762 					 */
2763 					if (flags & NON_BLOCKING) {
2764 						ret = -EAGAIN;
2765 						goto out_unlock;
2766 					}
2767 
2768 					spin_unlock(&ci->i_ceph_lock);
2769 					down_read(&mdsc->snap_rwsem);
2770 					snap_rwsem_locked = true;
2771 					goto again;
2772 				}
2773 				snap_rwsem_locked = true;
2774 			}
2775 			if ((have & want) == want)
2776 				*got = need | (want & ~exclude);
2777 			else
2778 				*got = need;
2779 			ceph_take_cap_refs(ci, *got, true);
2780 			ret = 1;
2781 		}
2782 	} else {
2783 		int session_readonly = false;
2784 		int mds_wanted;
2785 		if (ci->i_auth_cap &&
2786 		    (need & (CEPH_CAP_FILE_WR | CEPH_CAP_FILE_EXCL))) {
2787 			struct ceph_mds_session *s = ci->i_auth_cap->session;
2788 			spin_lock(&s->s_cap_lock);
2789 			session_readonly = s->s_readonly;
2790 			spin_unlock(&s->s_cap_lock);
2791 		}
2792 		if (session_readonly) {
2793 			dout("get_cap_refs %p need %s but mds%d readonly\n",
2794 			     inode, ceph_cap_string(need), ci->i_auth_cap->mds);
2795 			ret = -EROFS;
2796 			goto out_unlock;
2797 		}
2798 
2799 		if (ceph_inode_is_shutdown(inode)) {
2800 			dout("get_cap_refs %p inode is shutdown\n", inode);
2801 			ret = -ESTALE;
2802 			goto out_unlock;
2803 		}
2804 		mds_wanted = __ceph_caps_mds_wanted(ci, false);
2805 		if (need & ~mds_wanted) {
2806 			dout("get_cap_refs %p need %s > mds_wanted %s\n",
2807 			     inode, ceph_cap_string(need),
2808 			     ceph_cap_string(mds_wanted));
2809 			ret = -EUCLEAN;
2810 			goto out_unlock;
2811 		}
2812 
2813 		dout("get_cap_refs %p have %s need %s\n", inode,
2814 		     ceph_cap_string(have), ceph_cap_string(need));
2815 	}
2816 out_unlock:
2817 
2818 	__ceph_touch_fmode(ci, mdsc, flags);
2819 
2820 	spin_unlock(&ci->i_ceph_lock);
2821 	if (snap_rwsem_locked)
2822 		up_read(&mdsc->snap_rwsem);
2823 
2824 	if (!ret)
2825 		ceph_update_cap_mis(&mdsc->metric);
2826 	else if (ret == 1)
2827 		ceph_update_cap_hit(&mdsc->metric);
2828 
2829 	dout("get_cap_refs %p ret %d got %s\n", inode,
2830 	     ret, ceph_cap_string(*got));
2831 	return ret;
2832 }
2833 
2834 /*
2835  * Check the offset we are writing up to against our current
2836  * max_size.  If necessary, tell the MDS we want to write to
2837  * a larger offset.
2838  */
2839 static void check_max_size(struct inode *inode, loff_t endoff)
2840 {
2841 	struct ceph_inode_info *ci = ceph_inode(inode);
2842 	int check = 0;
2843 
2844 	/* do we need to explicitly request a larger max_size? */
2845 	spin_lock(&ci->i_ceph_lock);
2846 	if (endoff >= ci->i_max_size && endoff > ci->i_wanted_max_size) {
2847 		dout("write %p at large endoff %llu, req max_size\n",
2848 		     inode, endoff);
2849 		ci->i_wanted_max_size = endoff;
2850 	}
2851 	/* duplicate ceph_check_caps()'s logic */
2852 	if (ci->i_auth_cap &&
2853 	    (ci->i_auth_cap->issued & CEPH_CAP_FILE_WR) &&
2854 	    ci->i_wanted_max_size > ci->i_max_size &&
2855 	    ci->i_wanted_max_size > ci->i_requested_max_size)
2856 		check = 1;
2857 	spin_unlock(&ci->i_ceph_lock);
2858 	if (check)
2859 		ceph_check_caps(ci, CHECK_CAPS_AUTHONLY);
2860 }
2861 
2862 static inline int get_used_fmode(int caps)
2863 {
2864 	int fmode = 0;
2865 	if (caps & CEPH_CAP_FILE_RD)
2866 		fmode |= CEPH_FILE_MODE_RD;
2867 	if (caps & CEPH_CAP_FILE_WR)
2868 		fmode |= CEPH_FILE_MODE_WR;
2869 	return fmode;
2870 }
2871 
2872 int ceph_try_get_caps(struct inode *inode, int need, int want,
2873 		      bool nonblock, int *got)
2874 {
2875 	int ret, flags;
2876 
2877 	BUG_ON(need & ~CEPH_CAP_FILE_RD);
2878 	BUG_ON(want & ~(CEPH_CAP_FILE_CACHE | CEPH_CAP_FILE_LAZYIO |
2879 			CEPH_CAP_FILE_SHARED | CEPH_CAP_FILE_EXCL |
2880 			CEPH_CAP_ANY_DIR_OPS));
2881 	if (need) {
2882 		ret = ceph_pool_perm_check(inode, need);
2883 		if (ret < 0)
2884 			return ret;
2885 	}
2886 
2887 	flags = get_used_fmode(need | want);
2888 	if (nonblock)
2889 		flags |= NON_BLOCKING;
2890 
2891 	ret = try_get_cap_refs(inode, need, want, 0, flags, got);
2892 	/* three special error codes */
2893 	if (ret == -EAGAIN || ret == -EFBIG || ret == -EUCLEAN)
2894 		ret = 0;
2895 	return ret;
2896 }
2897 
2898 /*
2899  * Wait for caps, and take cap references.  If we can't get a WR cap
2900  * due to a small max_size, make sure we check_max_size (and possibly
2901  * ask the mds) so we don't get hung up indefinitely.
2902  */
2903 int ceph_get_caps(struct file *filp, int need, int want, loff_t endoff, int *got)
2904 {
2905 	struct ceph_file_info *fi = filp->private_data;
2906 	struct inode *inode = file_inode(filp);
2907 	struct ceph_inode_info *ci = ceph_inode(inode);
2908 	struct ceph_fs_client *fsc = ceph_inode_to_client(inode);
2909 	int ret, _got, flags;
2910 
2911 	ret = ceph_pool_perm_check(inode, need);
2912 	if (ret < 0)
2913 		return ret;
2914 
2915 	if ((fi->fmode & CEPH_FILE_MODE_WR) &&
2916 	    fi->filp_gen != READ_ONCE(fsc->filp_gen))
2917 		return -EBADF;
2918 
2919 	flags = get_used_fmode(need | want);
2920 
2921 	while (true) {
2922 		flags &= CEPH_FILE_MODE_MASK;
2923 		if (vfs_inode_has_locks(inode))
2924 			flags |= CHECK_FILELOCK;
2925 		_got = 0;
2926 		ret = try_get_cap_refs(inode, need, want, endoff,
2927 				       flags, &_got);
2928 		WARN_ON_ONCE(ret == -EAGAIN);
2929 		if (!ret) {
2930 			struct ceph_mds_client *mdsc = fsc->mdsc;
2931 			struct cap_wait cw;
2932 			DEFINE_WAIT_FUNC(wait, woken_wake_function);
2933 
2934 			cw.ino = ceph_ino(inode);
2935 			cw.tgid = current->tgid;
2936 			cw.need = need;
2937 			cw.want = want;
2938 
2939 			spin_lock(&mdsc->caps_list_lock);
2940 			list_add(&cw.list, &mdsc->cap_wait_list);
2941 			spin_unlock(&mdsc->caps_list_lock);
2942 
2943 			/* make sure used fmode not timeout */
2944 			ceph_get_fmode(ci, flags, FMODE_WAIT_BIAS);
2945 			add_wait_queue(&ci->i_cap_wq, &wait);
2946 
2947 			flags |= NON_BLOCKING;
2948 			while (!(ret = try_get_cap_refs(inode, need, want,
2949 							endoff, flags, &_got))) {
2950 				if (signal_pending(current)) {
2951 					ret = -ERESTARTSYS;
2952 					break;
2953 				}
2954 				wait_woken(&wait, TASK_INTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT);
2955 			}
2956 
2957 			remove_wait_queue(&ci->i_cap_wq, &wait);
2958 			ceph_put_fmode(ci, flags, FMODE_WAIT_BIAS);
2959 
2960 			spin_lock(&mdsc->caps_list_lock);
2961 			list_del(&cw.list);
2962 			spin_unlock(&mdsc->caps_list_lock);
2963 
2964 			if (ret == -EAGAIN)
2965 				continue;
2966 		}
2967 
2968 		if ((fi->fmode & CEPH_FILE_MODE_WR) &&
2969 		    fi->filp_gen != READ_ONCE(fsc->filp_gen)) {
2970 			if (ret >= 0 && _got)
2971 				ceph_put_cap_refs(ci, _got);
2972 			return -EBADF;
2973 		}
2974 
2975 		if (ret < 0) {
2976 			if (ret == -EFBIG || ret == -EUCLEAN) {
2977 				int ret2 = ceph_wait_on_async_create(inode);
2978 				if (ret2 < 0)
2979 					return ret2;
2980 			}
2981 			if (ret == -EFBIG) {
2982 				check_max_size(inode, endoff);
2983 				continue;
2984 			}
2985 			if (ret == -EUCLEAN) {
2986 				/* session was killed, try renew caps */
2987 				ret = ceph_renew_caps(inode, flags);
2988 				if (ret == 0)
2989 					continue;
2990 			}
2991 			return ret;
2992 		}
2993 
2994 		if (S_ISREG(ci->netfs.inode.i_mode) &&
2995 		    ceph_has_inline_data(ci) &&
2996 		    (_got & (CEPH_CAP_FILE_CACHE|CEPH_CAP_FILE_LAZYIO)) &&
2997 		    i_size_read(inode) > 0) {
2998 			struct page *page =
2999 				find_get_page(inode->i_mapping, 0);
3000 			if (page) {
3001 				bool uptodate = PageUptodate(page);
3002 
3003 				put_page(page);
3004 				if (uptodate)
3005 					break;
3006 			}
3007 			/*
3008 			 * drop cap refs first because getattr while
3009 			 * holding * caps refs can cause deadlock.
3010 			 */
3011 			ceph_put_cap_refs(ci, _got);
3012 			_got = 0;
3013 
3014 			/*
3015 			 * getattr request will bring inline data into
3016 			 * page cache
3017 			 */
3018 			ret = __ceph_do_getattr(inode, NULL,
3019 						CEPH_STAT_CAP_INLINE_DATA,
3020 						true);
3021 			if (ret < 0)
3022 				return ret;
3023 			continue;
3024 		}
3025 		break;
3026 	}
3027 	*got = _got;
3028 	return 0;
3029 }
3030 
3031 /*
3032  * Take cap refs.  Caller must already know we hold at least one ref
3033  * on the caps in question or we don't know this is safe.
3034  */
3035 void ceph_get_cap_refs(struct ceph_inode_info *ci, int caps)
3036 {
3037 	spin_lock(&ci->i_ceph_lock);
3038 	ceph_take_cap_refs(ci, caps, false);
3039 	spin_unlock(&ci->i_ceph_lock);
3040 }
3041 
3042 
3043 /*
3044  * drop cap_snap that is not associated with any snapshot.
3045  * we don't need to send FLUSHSNAP message for it.
3046  */
3047 static int ceph_try_drop_cap_snap(struct ceph_inode_info *ci,
3048 				  struct ceph_cap_snap *capsnap)
3049 {
3050 	if (!capsnap->need_flush &&
3051 	    !capsnap->writing && !capsnap->dirty_pages) {
3052 		dout("dropping cap_snap %p follows %llu\n",
3053 		     capsnap, capsnap->follows);
3054 		BUG_ON(capsnap->cap_flush.tid > 0);
3055 		ceph_put_snap_context(capsnap->context);
3056 		if (!list_is_last(&capsnap->ci_item, &ci->i_cap_snaps))
3057 			ci->i_ceph_flags |= CEPH_I_FLUSH_SNAPS;
3058 
3059 		list_del(&capsnap->ci_item);
3060 		ceph_put_cap_snap(capsnap);
3061 		return 1;
3062 	}
3063 	return 0;
3064 }
3065 
3066 enum put_cap_refs_mode {
3067 	PUT_CAP_REFS_SYNC = 0,
3068 	PUT_CAP_REFS_NO_CHECK,
3069 	PUT_CAP_REFS_ASYNC,
3070 };
3071 
3072 /*
3073  * Release cap refs.
3074  *
3075  * If we released the last ref on any given cap, call ceph_check_caps
3076  * to release (or schedule a release).
3077  *
3078  * If we are releasing a WR cap (from a sync write), finalize any affected
3079  * cap_snap, and wake up any waiters.
3080  */
3081 static void __ceph_put_cap_refs(struct ceph_inode_info *ci, int had,
3082 				enum put_cap_refs_mode mode)
3083 {
3084 	struct inode *inode = &ci->netfs.inode;
3085 	int last = 0, put = 0, flushsnaps = 0, wake = 0;
3086 	bool check_flushsnaps = false;
3087 
3088 	spin_lock(&ci->i_ceph_lock);
3089 	if (had & CEPH_CAP_PIN)
3090 		--ci->i_pin_ref;
3091 	if (had & CEPH_CAP_FILE_RD)
3092 		if (--ci->i_rd_ref == 0)
3093 			last++;
3094 	if (had & CEPH_CAP_FILE_CACHE)
3095 		if (--ci->i_rdcache_ref == 0)
3096 			last++;
3097 	if (had & CEPH_CAP_FILE_EXCL)
3098 		if (--ci->i_fx_ref == 0)
3099 			last++;
3100 	if (had & CEPH_CAP_FILE_BUFFER) {
3101 		if (--ci->i_wb_ref == 0) {
3102 			last++;
3103 			/* put the ref held by ceph_take_cap_refs() */
3104 			put++;
3105 			check_flushsnaps = true;
3106 		}
3107 		dout("put_cap_refs %p wb %d -> %d (?)\n",
3108 		     inode, ci->i_wb_ref+1, ci->i_wb_ref);
3109 	}
3110 	if (had & CEPH_CAP_FILE_WR) {
3111 		if (--ci->i_wr_ref == 0) {
3112 			/*
3113 			 * The Fb caps will always be took and released
3114 			 * together with the Fw caps.
3115 			 */
3116 			WARN_ON_ONCE(ci->i_wb_ref);
3117 
3118 			last++;
3119 			check_flushsnaps = true;
3120 			if (ci->i_wrbuffer_ref_head == 0 &&
3121 			    ci->i_dirty_caps == 0 &&
3122 			    ci->i_flushing_caps == 0) {
3123 				BUG_ON(!ci->i_head_snapc);
3124 				ceph_put_snap_context(ci->i_head_snapc);
3125 				ci->i_head_snapc = NULL;
3126 			}
3127 			/* see comment in __ceph_remove_cap() */
3128 			if (!__ceph_is_any_real_caps(ci) && ci->i_snap_realm)
3129 				ceph_change_snap_realm(inode, NULL);
3130 		}
3131 	}
3132 	if (check_flushsnaps && __ceph_have_pending_cap_snap(ci)) {
3133 		struct ceph_cap_snap *capsnap =
3134 			list_last_entry(&ci->i_cap_snaps,
3135 					struct ceph_cap_snap,
3136 					ci_item);
3137 
3138 		capsnap->writing = 0;
3139 		if (ceph_try_drop_cap_snap(ci, capsnap))
3140 			/* put the ref held by ceph_queue_cap_snap() */
3141 			put++;
3142 		else if (__ceph_finish_cap_snap(ci, capsnap))
3143 			flushsnaps = 1;
3144 		wake = 1;
3145 	}
3146 	spin_unlock(&ci->i_ceph_lock);
3147 
3148 	dout("put_cap_refs %p had %s%s%s\n", inode, ceph_cap_string(had),
3149 	     last ? " last" : "", put ? " put" : "");
3150 
3151 	switch (mode) {
3152 	case PUT_CAP_REFS_SYNC:
3153 		if (last)
3154 			ceph_check_caps(ci, 0);
3155 		else if (flushsnaps)
3156 			ceph_flush_snaps(ci, NULL);
3157 		break;
3158 	case PUT_CAP_REFS_ASYNC:
3159 		if (last)
3160 			ceph_queue_check_caps(inode);
3161 		else if (flushsnaps)
3162 			ceph_queue_flush_snaps(inode);
3163 		break;
3164 	default:
3165 		break;
3166 	}
3167 	if (wake)
3168 		wake_up_all(&ci->i_cap_wq);
3169 	while (put-- > 0)
3170 		iput(inode);
3171 }
3172 
3173 void ceph_put_cap_refs(struct ceph_inode_info *ci, int had)
3174 {
3175 	__ceph_put_cap_refs(ci, had, PUT_CAP_REFS_SYNC);
3176 }
3177 
3178 void ceph_put_cap_refs_async(struct ceph_inode_info *ci, int had)
3179 {
3180 	__ceph_put_cap_refs(ci, had, PUT_CAP_REFS_ASYNC);
3181 }
3182 
3183 void ceph_put_cap_refs_no_check_caps(struct ceph_inode_info *ci, int had)
3184 {
3185 	__ceph_put_cap_refs(ci, had, PUT_CAP_REFS_NO_CHECK);
3186 }
3187 
3188 /*
3189  * Release @nr WRBUFFER refs on dirty pages for the given @snapc snap
3190  * context.  Adjust per-snap dirty page accounting as appropriate.
3191  * Once all dirty data for a cap_snap is flushed, flush snapped file
3192  * metadata back to the MDS.  If we dropped the last ref, call
3193  * ceph_check_caps.
3194  */
3195 void ceph_put_wrbuffer_cap_refs(struct ceph_inode_info *ci, int nr,
3196 				struct ceph_snap_context *snapc)
3197 {
3198 	struct inode *inode = &ci->netfs.inode;
3199 	struct ceph_cap_snap *capsnap = NULL, *iter;
3200 	int put = 0;
3201 	bool last = false;
3202 	bool flush_snaps = false;
3203 	bool complete_capsnap = false;
3204 
3205 	spin_lock(&ci->i_ceph_lock);
3206 	ci->i_wrbuffer_ref -= nr;
3207 	if (ci->i_wrbuffer_ref == 0) {
3208 		last = true;
3209 		put++;
3210 	}
3211 
3212 	if (ci->i_head_snapc == snapc) {
3213 		ci->i_wrbuffer_ref_head -= nr;
3214 		if (ci->i_wrbuffer_ref_head == 0 &&
3215 		    ci->i_wr_ref == 0 &&
3216 		    ci->i_dirty_caps == 0 &&
3217 		    ci->i_flushing_caps == 0) {
3218 			BUG_ON(!ci->i_head_snapc);
3219 			ceph_put_snap_context(ci->i_head_snapc);
3220 			ci->i_head_snapc = NULL;
3221 		}
3222 		dout("put_wrbuffer_cap_refs on %p head %d/%d -> %d/%d %s\n",
3223 		     inode,
3224 		     ci->i_wrbuffer_ref+nr, ci->i_wrbuffer_ref_head+nr,
3225 		     ci->i_wrbuffer_ref, ci->i_wrbuffer_ref_head,
3226 		     last ? " LAST" : "");
3227 	} else {
3228 		list_for_each_entry(iter, &ci->i_cap_snaps, ci_item) {
3229 			if (iter->context == snapc) {
3230 				capsnap = iter;
3231 				break;
3232 			}
3233 		}
3234 
3235 		if (!capsnap) {
3236 			/*
3237 			 * The capsnap should already be removed when removing
3238 			 * auth cap in the case of a forced unmount.
3239 			 */
3240 			WARN_ON_ONCE(ci->i_auth_cap);
3241 			goto unlock;
3242 		}
3243 
3244 		capsnap->dirty_pages -= nr;
3245 		if (capsnap->dirty_pages == 0) {
3246 			complete_capsnap = true;
3247 			if (!capsnap->writing) {
3248 				if (ceph_try_drop_cap_snap(ci, capsnap)) {
3249 					put++;
3250 				} else {
3251 					ci->i_ceph_flags |= CEPH_I_FLUSH_SNAPS;
3252 					flush_snaps = true;
3253 				}
3254 			}
3255 		}
3256 		dout("put_wrbuffer_cap_refs on %p cap_snap %p "
3257 		     " snap %lld %d/%d -> %d/%d %s%s\n",
3258 		     inode, capsnap, capsnap->context->seq,
3259 		     ci->i_wrbuffer_ref+nr, capsnap->dirty_pages + nr,
3260 		     ci->i_wrbuffer_ref, capsnap->dirty_pages,
3261 		     last ? " (wrbuffer last)" : "",
3262 		     complete_capsnap ? " (complete capsnap)" : "");
3263 	}
3264 
3265 unlock:
3266 	spin_unlock(&ci->i_ceph_lock);
3267 
3268 	if (last) {
3269 		ceph_check_caps(ci, 0);
3270 	} else if (flush_snaps) {
3271 		ceph_flush_snaps(ci, NULL);
3272 	}
3273 	if (complete_capsnap)
3274 		wake_up_all(&ci->i_cap_wq);
3275 	while (put-- > 0) {
3276 		iput(inode);
3277 	}
3278 }
3279 
3280 /*
3281  * Invalidate unlinked inode's aliases, so we can drop the inode ASAP.
3282  */
3283 static void invalidate_aliases(struct inode *inode)
3284 {
3285 	struct dentry *dn, *prev = NULL;
3286 
3287 	dout("invalidate_aliases inode %p\n", inode);
3288 	d_prune_aliases(inode);
3289 	/*
3290 	 * For non-directory inode, d_find_alias() only returns
3291 	 * hashed dentry. After calling d_invalidate(), the
3292 	 * dentry becomes unhashed.
3293 	 *
3294 	 * For directory inode, d_find_alias() can return
3295 	 * unhashed dentry. But directory inode should have
3296 	 * one alias at most.
3297 	 */
3298 	while ((dn = d_find_alias(inode))) {
3299 		if (dn == prev) {
3300 			dput(dn);
3301 			break;
3302 		}
3303 		d_invalidate(dn);
3304 		if (prev)
3305 			dput(prev);
3306 		prev = dn;
3307 	}
3308 	if (prev)
3309 		dput(prev);
3310 }
3311 
3312 struct cap_extra_info {
3313 	struct ceph_string *pool_ns;
3314 	/* inline data */
3315 	u64 inline_version;
3316 	void *inline_data;
3317 	u32 inline_len;
3318 	/* dirstat */
3319 	bool dirstat_valid;
3320 	u64 nfiles;
3321 	u64 nsubdirs;
3322 	u64 change_attr;
3323 	/* currently issued */
3324 	int issued;
3325 	struct timespec64 btime;
3326 };
3327 
3328 /*
3329  * Handle a cap GRANT message from the MDS.  (Note that a GRANT may
3330  * actually be a revocation if it specifies a smaller cap set.)
3331  *
3332  * caller holds s_mutex and i_ceph_lock, we drop both.
3333  */
3334 static void handle_cap_grant(struct inode *inode,
3335 			     struct ceph_mds_session *session,
3336 			     struct ceph_cap *cap,
3337 			     struct ceph_mds_caps *grant,
3338 			     struct ceph_buffer *xattr_buf,
3339 			     struct cap_extra_info *extra_info)
3340 	__releases(ci->i_ceph_lock)
3341 	__releases(session->s_mdsc->snap_rwsem)
3342 {
3343 	struct ceph_inode_info *ci = ceph_inode(inode);
3344 	int seq = le32_to_cpu(grant->seq);
3345 	int newcaps = le32_to_cpu(grant->caps);
3346 	int used, wanted, dirty;
3347 	u64 size = le64_to_cpu(grant->size);
3348 	u64 max_size = le64_to_cpu(grant->max_size);
3349 	unsigned char check_caps = 0;
3350 	bool was_stale = cap->cap_gen < atomic_read(&session->s_cap_gen);
3351 	bool wake = false;
3352 	bool writeback = false;
3353 	bool queue_trunc = false;
3354 	bool queue_invalidate = false;
3355 	bool deleted_inode = false;
3356 	bool fill_inline = false;
3357 
3358 	dout("handle_cap_grant inode %p cap %p mds%d seq %d %s\n",
3359 	     inode, cap, session->s_mds, seq, ceph_cap_string(newcaps));
3360 	dout(" size %llu max_size %llu, i_size %llu\n", size, max_size,
3361 		i_size_read(inode));
3362 
3363 
3364 	/*
3365 	 * If CACHE is being revoked, and we have no dirty buffers,
3366 	 * try to invalidate (once).  (If there are dirty buffers, we
3367 	 * will invalidate _after_ writeback.)
3368 	 */
3369 	if (S_ISREG(inode->i_mode) && /* don't invalidate readdir cache */
3370 	    ((cap->issued & ~newcaps) & CEPH_CAP_FILE_CACHE) &&
3371 	    (newcaps & CEPH_CAP_FILE_LAZYIO) == 0 &&
3372 	    !(ci->i_wrbuffer_ref || ci->i_wb_ref)) {
3373 		if (try_nonblocking_invalidate(inode)) {
3374 			/* there were locked pages.. invalidate later
3375 			   in a separate thread. */
3376 			if (ci->i_rdcache_revoking != ci->i_rdcache_gen) {
3377 				queue_invalidate = true;
3378 				ci->i_rdcache_revoking = ci->i_rdcache_gen;
3379 			}
3380 		}
3381 	}
3382 
3383 	if (was_stale)
3384 		cap->issued = cap->implemented = CEPH_CAP_PIN;
3385 
3386 	/*
3387 	 * auth mds of the inode changed. we received the cap export message,
3388 	 * but still haven't received the cap import message. handle_cap_export
3389 	 * updated the new auth MDS' cap.
3390 	 *
3391 	 * "ceph_seq_cmp(seq, cap->seq) <= 0" means we are processing a message
3392 	 * that was sent before the cap import message. So don't remove caps.
3393 	 */
3394 	if (ceph_seq_cmp(seq, cap->seq) <= 0) {
3395 		WARN_ON(cap != ci->i_auth_cap);
3396 		WARN_ON(cap->cap_id != le64_to_cpu(grant->cap_id));
3397 		seq = cap->seq;
3398 		newcaps |= cap->issued;
3399 	}
3400 
3401 	/* side effects now are allowed */
3402 	cap->cap_gen = atomic_read(&session->s_cap_gen);
3403 	cap->seq = seq;
3404 
3405 	__check_cap_issue(ci, cap, newcaps);
3406 
3407 	inode_set_max_iversion_raw(inode, extra_info->change_attr);
3408 
3409 	if ((newcaps & CEPH_CAP_AUTH_SHARED) &&
3410 	    (extra_info->issued & CEPH_CAP_AUTH_EXCL) == 0) {
3411 		umode_t mode = le32_to_cpu(grant->mode);
3412 
3413 		if (inode_wrong_type(inode, mode))
3414 			pr_warn_once("inode type changed! (ino %llx.%llx is 0%o, mds says 0%o)\n",
3415 				     ceph_vinop(inode), inode->i_mode, mode);
3416 		else
3417 			inode->i_mode = mode;
3418 		inode->i_uid = make_kuid(&init_user_ns, le32_to_cpu(grant->uid));
3419 		inode->i_gid = make_kgid(&init_user_ns, le32_to_cpu(grant->gid));
3420 		ci->i_btime = extra_info->btime;
3421 		dout("%p mode 0%o uid.gid %d.%d\n", inode, inode->i_mode,
3422 		     from_kuid(&init_user_ns, inode->i_uid),
3423 		     from_kgid(&init_user_ns, inode->i_gid));
3424 	}
3425 
3426 	if ((newcaps & CEPH_CAP_LINK_SHARED) &&
3427 	    (extra_info->issued & CEPH_CAP_LINK_EXCL) == 0) {
3428 		set_nlink(inode, le32_to_cpu(grant->nlink));
3429 		if (inode->i_nlink == 0)
3430 			deleted_inode = true;
3431 	}
3432 
3433 	if ((extra_info->issued & CEPH_CAP_XATTR_EXCL) == 0 &&
3434 	    grant->xattr_len) {
3435 		int len = le32_to_cpu(grant->xattr_len);
3436 		u64 version = le64_to_cpu(grant->xattr_version);
3437 
3438 		if (version > ci->i_xattrs.version) {
3439 			dout(" got new xattrs v%llu on %p len %d\n",
3440 			     version, inode, len);
3441 			if (ci->i_xattrs.blob)
3442 				ceph_buffer_put(ci->i_xattrs.blob);
3443 			ci->i_xattrs.blob = ceph_buffer_get(xattr_buf);
3444 			ci->i_xattrs.version = version;
3445 			ceph_forget_all_cached_acls(inode);
3446 			ceph_security_invalidate_secctx(inode);
3447 		}
3448 	}
3449 
3450 	if (newcaps & CEPH_CAP_ANY_RD) {
3451 		struct timespec64 mtime, atime, ctime;
3452 		/* ctime/mtime/atime? */
3453 		ceph_decode_timespec64(&mtime, &grant->mtime);
3454 		ceph_decode_timespec64(&atime, &grant->atime);
3455 		ceph_decode_timespec64(&ctime, &grant->ctime);
3456 		ceph_fill_file_time(inode, extra_info->issued,
3457 				    le32_to_cpu(grant->time_warp_seq),
3458 				    &ctime, &mtime, &atime);
3459 	}
3460 
3461 	if ((newcaps & CEPH_CAP_FILE_SHARED) && extra_info->dirstat_valid) {
3462 		ci->i_files = extra_info->nfiles;
3463 		ci->i_subdirs = extra_info->nsubdirs;
3464 	}
3465 
3466 	if (newcaps & (CEPH_CAP_ANY_FILE_RD | CEPH_CAP_ANY_FILE_WR)) {
3467 		/* file layout may have changed */
3468 		s64 old_pool = ci->i_layout.pool_id;
3469 		struct ceph_string *old_ns;
3470 
3471 		ceph_file_layout_from_legacy(&ci->i_layout, &grant->layout);
3472 		old_ns = rcu_dereference_protected(ci->i_layout.pool_ns,
3473 					lockdep_is_held(&ci->i_ceph_lock));
3474 		rcu_assign_pointer(ci->i_layout.pool_ns, extra_info->pool_ns);
3475 
3476 		if (ci->i_layout.pool_id != old_pool ||
3477 		    extra_info->pool_ns != old_ns)
3478 			ci->i_ceph_flags &= ~CEPH_I_POOL_PERM;
3479 
3480 		extra_info->pool_ns = old_ns;
3481 
3482 		/* size/truncate_seq? */
3483 		queue_trunc = ceph_fill_file_size(inode, extra_info->issued,
3484 					le32_to_cpu(grant->truncate_seq),
3485 					le64_to_cpu(grant->truncate_size),
3486 					size);
3487 	}
3488 
3489 	if (ci->i_auth_cap == cap && (newcaps & CEPH_CAP_ANY_FILE_WR)) {
3490 		if (max_size != ci->i_max_size) {
3491 			dout("max_size %lld -> %llu\n",
3492 			     ci->i_max_size, max_size);
3493 			ci->i_max_size = max_size;
3494 			if (max_size >= ci->i_wanted_max_size) {
3495 				ci->i_wanted_max_size = 0;  /* reset */
3496 				ci->i_requested_max_size = 0;
3497 			}
3498 			wake = true;
3499 		}
3500 	}
3501 
3502 	/* check cap bits */
3503 	wanted = __ceph_caps_wanted(ci);
3504 	used = __ceph_caps_used(ci);
3505 	dirty = __ceph_caps_dirty(ci);
3506 	dout(" my wanted = %s, used = %s, dirty %s\n",
3507 	     ceph_cap_string(wanted),
3508 	     ceph_cap_string(used),
3509 	     ceph_cap_string(dirty));
3510 
3511 	if ((was_stale || le32_to_cpu(grant->op) == CEPH_CAP_OP_IMPORT) &&
3512 	    (wanted & ~(cap->mds_wanted | newcaps))) {
3513 		/*
3514 		 * If mds is importing cap, prior cap messages that update
3515 		 * 'wanted' may get dropped by mds (migrate seq mismatch).
3516 		 *
3517 		 * We don't send cap message to update 'wanted' if what we
3518 		 * want are already issued. If mds revokes caps, cap message
3519 		 * that releases caps also tells mds what we want. But if
3520 		 * caps got revoked by mds forcedly (session stale). We may
3521 		 * haven't told mds what we want.
3522 		 */
3523 		check_caps = 1;
3524 	}
3525 
3526 	/* revocation, grant, or no-op? */
3527 	if (cap->issued & ~newcaps) {
3528 		int revoking = cap->issued & ~newcaps;
3529 
3530 		dout("revocation: %s -> %s (revoking %s)\n",
3531 		     ceph_cap_string(cap->issued),
3532 		     ceph_cap_string(newcaps),
3533 		     ceph_cap_string(revoking));
3534 		if (S_ISREG(inode->i_mode) &&
3535 		    (revoking & used & CEPH_CAP_FILE_BUFFER))
3536 			writeback = true;  /* initiate writeback; will delay ack */
3537 		else if (queue_invalidate &&
3538 			 revoking == CEPH_CAP_FILE_CACHE &&
3539 			 (newcaps & CEPH_CAP_FILE_LAZYIO) == 0)
3540 			; /* do nothing yet, invalidation will be queued */
3541 		else if (cap == ci->i_auth_cap)
3542 			check_caps = 1; /* check auth cap only */
3543 		else
3544 			check_caps = 2; /* check all caps */
3545 		/* If there is new caps, try to wake up the waiters */
3546 		if (~cap->issued & newcaps)
3547 			wake = true;
3548 		cap->issued = newcaps;
3549 		cap->implemented |= newcaps;
3550 	} else if (cap->issued == newcaps) {
3551 		dout("caps unchanged: %s -> %s\n",
3552 		     ceph_cap_string(cap->issued), ceph_cap_string(newcaps));
3553 	} else {
3554 		dout("grant: %s -> %s\n", ceph_cap_string(cap->issued),
3555 		     ceph_cap_string(newcaps));
3556 		/* non-auth MDS is revoking the newly grant caps ? */
3557 		if (cap == ci->i_auth_cap &&
3558 		    __ceph_caps_revoking_other(ci, cap, newcaps))
3559 		    check_caps = 2;
3560 
3561 		cap->issued = newcaps;
3562 		cap->implemented |= newcaps; /* add bits only, to
3563 					      * avoid stepping on a
3564 					      * pending revocation */
3565 		wake = true;
3566 	}
3567 	BUG_ON(cap->issued & ~cap->implemented);
3568 
3569 	/* don't let check_caps skip sending a response to MDS for revoke msgs */
3570 	if (le32_to_cpu(grant->op) == CEPH_CAP_OP_REVOKE) {
3571 		cap->mds_wanted = 0;
3572 		if (cap == ci->i_auth_cap)
3573 			check_caps = 1; /* check auth cap only */
3574 		else
3575 			check_caps = 2; /* check all caps */
3576 	}
3577 
3578 	if (extra_info->inline_version > 0 &&
3579 	    extra_info->inline_version >= ci->i_inline_version) {
3580 		ci->i_inline_version = extra_info->inline_version;
3581 		if (ci->i_inline_version != CEPH_INLINE_NONE &&
3582 		    (newcaps & (CEPH_CAP_FILE_CACHE|CEPH_CAP_FILE_LAZYIO)))
3583 			fill_inline = true;
3584 	}
3585 
3586 	if (le32_to_cpu(grant->op) == CEPH_CAP_OP_IMPORT) {
3587 		if (ci->i_auth_cap == cap) {
3588 			if (newcaps & ~extra_info->issued)
3589 				wake = true;
3590 
3591 			if (ci->i_requested_max_size > max_size ||
3592 			    !(le32_to_cpu(grant->wanted) & CEPH_CAP_ANY_FILE_WR)) {
3593 				/* re-request max_size if necessary */
3594 				ci->i_requested_max_size = 0;
3595 				wake = true;
3596 			}
3597 
3598 			ceph_kick_flushing_inode_caps(session, ci);
3599 		}
3600 		up_read(&session->s_mdsc->snap_rwsem);
3601 	}
3602 	spin_unlock(&ci->i_ceph_lock);
3603 
3604 	if (fill_inline)
3605 		ceph_fill_inline_data(inode, NULL, extra_info->inline_data,
3606 				      extra_info->inline_len);
3607 
3608 	if (queue_trunc)
3609 		ceph_queue_vmtruncate(inode);
3610 
3611 	if (writeback)
3612 		/*
3613 		 * queue inode for writeback: we can't actually call
3614 		 * filemap_write_and_wait, etc. from message handler
3615 		 * context.
3616 		 */
3617 		ceph_queue_writeback(inode);
3618 	if (queue_invalidate)
3619 		ceph_queue_invalidate(inode);
3620 	if (deleted_inode)
3621 		invalidate_aliases(inode);
3622 	if (wake)
3623 		wake_up_all(&ci->i_cap_wq);
3624 
3625 	mutex_unlock(&session->s_mutex);
3626 	if (check_caps == 1)
3627 		ceph_check_caps(ci, CHECK_CAPS_AUTHONLY | CHECK_CAPS_NOINVAL);
3628 	else if (check_caps == 2)
3629 		ceph_check_caps(ci, CHECK_CAPS_NOINVAL);
3630 }
3631 
3632 /*
3633  * Handle FLUSH_ACK from MDS, indicating that metadata we sent to the
3634  * MDS has been safely committed.
3635  */
3636 static void handle_cap_flush_ack(struct inode *inode, u64 flush_tid,
3637 				 struct ceph_mds_caps *m,
3638 				 struct ceph_mds_session *session,
3639 				 struct ceph_cap *cap)
3640 	__releases(ci->i_ceph_lock)
3641 {
3642 	struct ceph_inode_info *ci = ceph_inode(inode);
3643 	struct ceph_mds_client *mdsc = ceph_sb_to_client(inode->i_sb)->mdsc;
3644 	struct ceph_cap_flush *cf, *tmp_cf;
3645 	LIST_HEAD(to_remove);
3646 	unsigned seq = le32_to_cpu(m->seq);
3647 	int dirty = le32_to_cpu(m->dirty);
3648 	int cleaned = 0;
3649 	bool drop = false;
3650 	bool wake_ci = false;
3651 	bool wake_mdsc = false;
3652 
3653 	list_for_each_entry_safe(cf, tmp_cf, &ci->i_cap_flush_list, i_list) {
3654 		/* Is this the one that was flushed? */
3655 		if (cf->tid == flush_tid)
3656 			cleaned = cf->caps;
3657 
3658 		/* Is this a capsnap? */
3659 		if (cf->is_capsnap)
3660 			continue;
3661 
3662 		if (cf->tid <= flush_tid) {
3663 			/*
3664 			 * An earlier or current tid. The FLUSH_ACK should
3665 			 * represent a superset of this flush's caps.
3666 			 */
3667 			wake_ci |= __detach_cap_flush_from_ci(ci, cf);
3668 			list_add_tail(&cf->i_list, &to_remove);
3669 		} else {
3670 			/*
3671 			 * This is a later one. Any caps in it are still dirty
3672 			 * so don't count them as cleaned.
3673 			 */
3674 			cleaned &= ~cf->caps;
3675 			if (!cleaned)
3676 				break;
3677 		}
3678 	}
3679 
3680 	dout("handle_cap_flush_ack inode %p mds%d seq %d on %s cleaned %s,"
3681 	     " flushing %s -> %s\n",
3682 	     inode, session->s_mds, seq, ceph_cap_string(dirty),
3683 	     ceph_cap_string(cleaned), ceph_cap_string(ci->i_flushing_caps),
3684 	     ceph_cap_string(ci->i_flushing_caps & ~cleaned));
3685 
3686 	if (list_empty(&to_remove) && !cleaned)
3687 		goto out;
3688 
3689 	ci->i_flushing_caps &= ~cleaned;
3690 
3691 	spin_lock(&mdsc->cap_dirty_lock);
3692 
3693 	list_for_each_entry(cf, &to_remove, i_list)
3694 		wake_mdsc |= __detach_cap_flush_from_mdsc(mdsc, cf);
3695 
3696 	if (ci->i_flushing_caps == 0) {
3697 		if (list_empty(&ci->i_cap_flush_list)) {
3698 			list_del_init(&ci->i_flushing_item);
3699 			if (!list_empty(&session->s_cap_flushing)) {
3700 				dout(" mds%d still flushing cap on %p\n",
3701 				     session->s_mds,
3702 				     &list_first_entry(&session->s_cap_flushing,
3703 						struct ceph_inode_info,
3704 						i_flushing_item)->netfs.inode);
3705 			}
3706 		}
3707 		mdsc->num_cap_flushing--;
3708 		dout(" inode %p now !flushing\n", inode);
3709 
3710 		if (ci->i_dirty_caps == 0) {
3711 			dout(" inode %p now clean\n", inode);
3712 			BUG_ON(!list_empty(&ci->i_dirty_item));
3713 			drop = true;
3714 			if (ci->i_wr_ref == 0 &&
3715 			    ci->i_wrbuffer_ref_head == 0) {
3716 				BUG_ON(!ci->i_head_snapc);
3717 				ceph_put_snap_context(ci->i_head_snapc);
3718 				ci->i_head_snapc = NULL;
3719 			}
3720 		} else {
3721 			BUG_ON(list_empty(&ci->i_dirty_item));
3722 		}
3723 	}
3724 	spin_unlock(&mdsc->cap_dirty_lock);
3725 
3726 out:
3727 	spin_unlock(&ci->i_ceph_lock);
3728 
3729 	while (!list_empty(&to_remove)) {
3730 		cf = list_first_entry(&to_remove,
3731 				      struct ceph_cap_flush, i_list);
3732 		list_del_init(&cf->i_list);
3733 		if (!cf->is_capsnap)
3734 			ceph_free_cap_flush(cf);
3735 	}
3736 
3737 	if (wake_ci)
3738 		wake_up_all(&ci->i_cap_wq);
3739 	if (wake_mdsc)
3740 		wake_up_all(&mdsc->cap_flushing_wq);
3741 	if (drop)
3742 		iput(inode);
3743 }
3744 
3745 void __ceph_remove_capsnap(struct inode *inode, struct ceph_cap_snap *capsnap,
3746 			   bool *wake_ci, bool *wake_mdsc)
3747 {
3748 	struct ceph_inode_info *ci = ceph_inode(inode);
3749 	struct ceph_mds_client *mdsc = ceph_sb_to_client(inode->i_sb)->mdsc;
3750 	bool ret;
3751 
3752 	lockdep_assert_held(&ci->i_ceph_lock);
3753 
3754 	dout("removing capsnap %p, inode %p ci %p\n", capsnap, inode, ci);
3755 
3756 	list_del_init(&capsnap->ci_item);
3757 	ret = __detach_cap_flush_from_ci(ci, &capsnap->cap_flush);
3758 	if (wake_ci)
3759 		*wake_ci = ret;
3760 
3761 	spin_lock(&mdsc->cap_dirty_lock);
3762 	if (list_empty(&ci->i_cap_flush_list))
3763 		list_del_init(&ci->i_flushing_item);
3764 
3765 	ret = __detach_cap_flush_from_mdsc(mdsc, &capsnap->cap_flush);
3766 	if (wake_mdsc)
3767 		*wake_mdsc = ret;
3768 	spin_unlock(&mdsc->cap_dirty_lock);
3769 }
3770 
3771 void ceph_remove_capsnap(struct inode *inode, struct ceph_cap_snap *capsnap,
3772 			 bool *wake_ci, bool *wake_mdsc)
3773 {
3774 	struct ceph_inode_info *ci = ceph_inode(inode);
3775 
3776 	lockdep_assert_held(&ci->i_ceph_lock);
3777 
3778 	WARN_ON_ONCE(capsnap->dirty_pages || capsnap->writing);
3779 	__ceph_remove_capsnap(inode, capsnap, wake_ci, wake_mdsc);
3780 }
3781 
3782 /*
3783  * Handle FLUSHSNAP_ACK.  MDS has flushed snap data to disk and we can
3784  * throw away our cap_snap.
3785  *
3786  * Caller hold s_mutex.
3787  */
3788 static void handle_cap_flushsnap_ack(struct inode *inode, u64 flush_tid,
3789 				     struct ceph_mds_caps *m,
3790 				     struct ceph_mds_session *session)
3791 {
3792 	struct ceph_inode_info *ci = ceph_inode(inode);
3793 	struct ceph_mds_client *mdsc = ceph_sb_to_client(inode->i_sb)->mdsc;
3794 	u64 follows = le64_to_cpu(m->snap_follows);
3795 	struct ceph_cap_snap *capsnap = NULL, *iter;
3796 	bool wake_ci = false;
3797 	bool wake_mdsc = false;
3798 
3799 	dout("handle_cap_flushsnap_ack inode %p ci %p mds%d follows %lld\n",
3800 	     inode, ci, session->s_mds, follows);
3801 
3802 	spin_lock(&ci->i_ceph_lock);
3803 	list_for_each_entry(iter, &ci->i_cap_snaps, ci_item) {
3804 		if (iter->follows == follows) {
3805 			if (iter->cap_flush.tid != flush_tid) {
3806 				dout(" cap_snap %p follows %lld tid %lld !="
3807 				     " %lld\n", iter, follows,
3808 				     flush_tid, iter->cap_flush.tid);
3809 				break;
3810 			}
3811 			capsnap = iter;
3812 			break;
3813 		} else {
3814 			dout(" skipping cap_snap %p follows %lld\n",
3815 			     iter, iter->follows);
3816 		}
3817 	}
3818 	if (capsnap)
3819 		ceph_remove_capsnap(inode, capsnap, &wake_ci, &wake_mdsc);
3820 	spin_unlock(&ci->i_ceph_lock);
3821 
3822 	if (capsnap) {
3823 		ceph_put_snap_context(capsnap->context);
3824 		ceph_put_cap_snap(capsnap);
3825 		if (wake_ci)
3826 			wake_up_all(&ci->i_cap_wq);
3827 		if (wake_mdsc)
3828 			wake_up_all(&mdsc->cap_flushing_wq);
3829 		iput(inode);
3830 	}
3831 }
3832 
3833 /*
3834  * Handle TRUNC from MDS, indicating file truncation.
3835  *
3836  * caller hold s_mutex.
3837  */
3838 static bool handle_cap_trunc(struct inode *inode,
3839 			     struct ceph_mds_caps *trunc,
3840 			     struct ceph_mds_session *session)
3841 {
3842 	struct ceph_inode_info *ci = ceph_inode(inode);
3843 	int mds = session->s_mds;
3844 	int seq = le32_to_cpu(trunc->seq);
3845 	u32 truncate_seq = le32_to_cpu(trunc->truncate_seq);
3846 	u64 truncate_size = le64_to_cpu(trunc->truncate_size);
3847 	u64 size = le64_to_cpu(trunc->size);
3848 	int implemented = 0;
3849 	int dirty = __ceph_caps_dirty(ci);
3850 	int issued = __ceph_caps_issued(ceph_inode(inode), &implemented);
3851 	bool queue_trunc = false;
3852 
3853 	lockdep_assert_held(&ci->i_ceph_lock);
3854 
3855 	issued |= implemented | dirty;
3856 
3857 	dout("handle_cap_trunc inode %p mds%d seq %d to %lld seq %d\n",
3858 	     inode, mds, seq, truncate_size, truncate_seq);
3859 	queue_trunc = ceph_fill_file_size(inode, issued,
3860 					  truncate_seq, truncate_size, size);
3861 	return queue_trunc;
3862 }
3863 
3864 /*
3865  * Handle EXPORT from MDS.  Cap is being migrated _from_ this mds to a
3866  * different one.  If we are the most recent migration we've seen (as
3867  * indicated by mseq), make note of the migrating cap bits for the
3868  * duration (until we see the corresponding IMPORT).
3869  *
3870  * caller holds s_mutex
3871  */
3872 static void handle_cap_export(struct inode *inode, struct ceph_mds_caps *ex,
3873 			      struct ceph_mds_cap_peer *ph,
3874 			      struct ceph_mds_session *session)
3875 {
3876 	struct ceph_mds_client *mdsc = ceph_inode_to_client(inode)->mdsc;
3877 	struct ceph_mds_session *tsession = NULL;
3878 	struct ceph_cap *cap, *tcap, *new_cap = NULL;
3879 	struct ceph_inode_info *ci = ceph_inode(inode);
3880 	u64 t_cap_id;
3881 	unsigned mseq = le32_to_cpu(ex->migrate_seq);
3882 	unsigned t_seq, t_mseq;
3883 	int target, issued;
3884 	int mds = session->s_mds;
3885 
3886 	if (ph) {
3887 		t_cap_id = le64_to_cpu(ph->cap_id);
3888 		t_seq = le32_to_cpu(ph->seq);
3889 		t_mseq = le32_to_cpu(ph->mseq);
3890 		target = le32_to_cpu(ph->mds);
3891 	} else {
3892 		t_cap_id = t_seq = t_mseq = 0;
3893 		target = -1;
3894 	}
3895 
3896 	dout("handle_cap_export inode %p ci %p mds%d mseq %d target %d\n",
3897 	     inode, ci, mds, mseq, target);
3898 retry:
3899 	down_read(&mdsc->snap_rwsem);
3900 	spin_lock(&ci->i_ceph_lock);
3901 	cap = __get_cap_for_mds(ci, mds);
3902 	if (!cap || cap->cap_id != le64_to_cpu(ex->cap_id))
3903 		goto out_unlock;
3904 
3905 	if (target < 0) {
3906 		ceph_remove_cap(cap, false);
3907 		goto out_unlock;
3908 	}
3909 
3910 	/*
3911 	 * now we know we haven't received the cap import message yet
3912 	 * because the exported cap still exist.
3913 	 */
3914 
3915 	issued = cap->issued;
3916 	if (issued != cap->implemented)
3917 		pr_err_ratelimited("handle_cap_export: issued != implemented: "
3918 				"ino (%llx.%llx) mds%d seq %d mseq %d "
3919 				"issued %s implemented %s\n",
3920 				ceph_vinop(inode), mds, cap->seq, cap->mseq,
3921 				ceph_cap_string(issued),
3922 				ceph_cap_string(cap->implemented));
3923 
3924 
3925 	tcap = __get_cap_for_mds(ci, target);
3926 	if (tcap) {
3927 		/* already have caps from the target */
3928 		if (tcap->cap_id == t_cap_id &&
3929 		    ceph_seq_cmp(tcap->seq, t_seq) < 0) {
3930 			dout(" updating import cap %p mds%d\n", tcap, target);
3931 			tcap->cap_id = t_cap_id;
3932 			tcap->seq = t_seq - 1;
3933 			tcap->issue_seq = t_seq - 1;
3934 			tcap->issued |= issued;
3935 			tcap->implemented |= issued;
3936 			if (cap == ci->i_auth_cap) {
3937 				ci->i_auth_cap = tcap;
3938 				change_auth_cap_ses(ci, tcap->session);
3939 			}
3940 		}
3941 		ceph_remove_cap(cap, false);
3942 		goto out_unlock;
3943 	} else if (tsession) {
3944 		/* add placeholder for the export tagert */
3945 		int flag = (cap == ci->i_auth_cap) ? CEPH_CAP_FLAG_AUTH : 0;
3946 		tcap = new_cap;
3947 		ceph_add_cap(inode, tsession, t_cap_id, issued, 0,
3948 			     t_seq - 1, t_mseq, (u64)-1, flag, &new_cap);
3949 
3950 		if (!list_empty(&ci->i_cap_flush_list) &&
3951 		    ci->i_auth_cap == tcap) {
3952 			spin_lock(&mdsc->cap_dirty_lock);
3953 			list_move_tail(&ci->i_flushing_item,
3954 				       &tcap->session->s_cap_flushing);
3955 			spin_unlock(&mdsc->cap_dirty_lock);
3956 		}
3957 
3958 		ceph_remove_cap(cap, false);
3959 		goto out_unlock;
3960 	}
3961 
3962 	spin_unlock(&ci->i_ceph_lock);
3963 	up_read(&mdsc->snap_rwsem);
3964 	mutex_unlock(&session->s_mutex);
3965 
3966 	/* open target session */
3967 	tsession = ceph_mdsc_open_export_target_session(mdsc, target);
3968 	if (!IS_ERR(tsession)) {
3969 		if (mds > target) {
3970 			mutex_lock(&session->s_mutex);
3971 			mutex_lock_nested(&tsession->s_mutex,
3972 					  SINGLE_DEPTH_NESTING);
3973 		} else {
3974 			mutex_lock(&tsession->s_mutex);
3975 			mutex_lock_nested(&session->s_mutex,
3976 					  SINGLE_DEPTH_NESTING);
3977 		}
3978 		new_cap = ceph_get_cap(mdsc, NULL);
3979 	} else {
3980 		WARN_ON(1);
3981 		tsession = NULL;
3982 		target = -1;
3983 		mutex_lock(&session->s_mutex);
3984 	}
3985 	goto retry;
3986 
3987 out_unlock:
3988 	spin_unlock(&ci->i_ceph_lock);
3989 	up_read(&mdsc->snap_rwsem);
3990 	mutex_unlock(&session->s_mutex);
3991 	if (tsession) {
3992 		mutex_unlock(&tsession->s_mutex);
3993 		ceph_put_mds_session(tsession);
3994 	}
3995 	if (new_cap)
3996 		ceph_put_cap(mdsc, new_cap);
3997 }
3998 
3999 /*
4000  * Handle cap IMPORT.
4001  *
4002  * caller holds s_mutex. acquires i_ceph_lock
4003  */
4004 static void handle_cap_import(struct ceph_mds_client *mdsc,
4005 			      struct inode *inode, struct ceph_mds_caps *im,
4006 			      struct ceph_mds_cap_peer *ph,
4007 			      struct ceph_mds_session *session,
4008 			      struct ceph_cap **target_cap, int *old_issued)
4009 {
4010 	struct ceph_inode_info *ci = ceph_inode(inode);
4011 	struct ceph_cap *cap, *ocap, *new_cap = NULL;
4012 	int mds = session->s_mds;
4013 	int issued;
4014 	unsigned caps = le32_to_cpu(im->caps);
4015 	unsigned wanted = le32_to_cpu(im->wanted);
4016 	unsigned seq = le32_to_cpu(im->seq);
4017 	unsigned mseq = le32_to_cpu(im->migrate_seq);
4018 	u64 realmino = le64_to_cpu(im->realm);
4019 	u64 cap_id = le64_to_cpu(im->cap_id);
4020 	u64 p_cap_id;
4021 	int peer;
4022 
4023 	if (ph) {
4024 		p_cap_id = le64_to_cpu(ph->cap_id);
4025 		peer = le32_to_cpu(ph->mds);
4026 	} else {
4027 		p_cap_id = 0;
4028 		peer = -1;
4029 	}
4030 
4031 	dout("handle_cap_import inode %p ci %p mds%d mseq %d peer %d\n",
4032 	     inode, ci, mds, mseq, peer);
4033 retry:
4034 	cap = __get_cap_for_mds(ci, mds);
4035 	if (!cap) {
4036 		if (!new_cap) {
4037 			spin_unlock(&ci->i_ceph_lock);
4038 			new_cap = ceph_get_cap(mdsc, NULL);
4039 			spin_lock(&ci->i_ceph_lock);
4040 			goto retry;
4041 		}
4042 		cap = new_cap;
4043 	} else {
4044 		if (new_cap) {
4045 			ceph_put_cap(mdsc, new_cap);
4046 			new_cap = NULL;
4047 		}
4048 	}
4049 
4050 	__ceph_caps_issued(ci, &issued);
4051 	issued |= __ceph_caps_dirty(ci);
4052 
4053 	ceph_add_cap(inode, session, cap_id, caps, wanted, seq, mseq,
4054 		     realmino, CEPH_CAP_FLAG_AUTH, &new_cap);
4055 
4056 	ocap = peer >= 0 ? __get_cap_for_mds(ci, peer) : NULL;
4057 	if (ocap && ocap->cap_id == p_cap_id) {
4058 		dout(" remove export cap %p mds%d flags %d\n",
4059 		     ocap, peer, ph->flags);
4060 		if ((ph->flags & CEPH_CAP_FLAG_AUTH) &&
4061 		    (ocap->seq != le32_to_cpu(ph->seq) ||
4062 		     ocap->mseq != le32_to_cpu(ph->mseq))) {
4063 			pr_err_ratelimited("handle_cap_import: "
4064 					"mismatched seq/mseq: ino (%llx.%llx) "
4065 					"mds%d seq %d mseq %d importer mds%d "
4066 					"has peer seq %d mseq %d\n",
4067 					ceph_vinop(inode), peer, ocap->seq,
4068 					ocap->mseq, mds, le32_to_cpu(ph->seq),
4069 					le32_to_cpu(ph->mseq));
4070 		}
4071 		ceph_remove_cap(ocap, (ph->flags & CEPH_CAP_FLAG_RELEASE));
4072 	}
4073 
4074 	*old_issued = issued;
4075 	*target_cap = cap;
4076 }
4077 
4078 /*
4079  * Handle a caps message from the MDS.
4080  *
4081  * Identify the appropriate session, inode, and call the right handler
4082  * based on the cap op.
4083  */
4084 void ceph_handle_caps(struct ceph_mds_session *session,
4085 		      struct ceph_msg *msg)
4086 {
4087 	struct ceph_mds_client *mdsc = session->s_mdsc;
4088 	struct inode *inode;
4089 	struct ceph_inode_info *ci;
4090 	struct ceph_cap *cap;
4091 	struct ceph_mds_caps *h;
4092 	struct ceph_mds_cap_peer *peer = NULL;
4093 	struct ceph_snap_realm *realm = NULL;
4094 	int op;
4095 	int msg_version = le16_to_cpu(msg->hdr.version);
4096 	u32 seq, mseq;
4097 	struct ceph_vino vino;
4098 	void *snaptrace;
4099 	size_t snaptrace_len;
4100 	void *p, *end;
4101 	struct cap_extra_info extra_info = {};
4102 	bool queue_trunc;
4103 	bool close_sessions = false;
4104 	bool do_cap_release = false;
4105 
4106 	dout("handle_caps from mds%d\n", session->s_mds);
4107 
4108 	/* decode */
4109 	end = msg->front.iov_base + msg->front.iov_len;
4110 	if (msg->front.iov_len < sizeof(*h))
4111 		goto bad;
4112 	h = msg->front.iov_base;
4113 	op = le32_to_cpu(h->op);
4114 	vino.ino = le64_to_cpu(h->ino);
4115 	vino.snap = CEPH_NOSNAP;
4116 	seq = le32_to_cpu(h->seq);
4117 	mseq = le32_to_cpu(h->migrate_seq);
4118 
4119 	snaptrace = h + 1;
4120 	snaptrace_len = le32_to_cpu(h->snap_trace_len);
4121 	p = snaptrace + snaptrace_len;
4122 
4123 	if (msg_version >= 2) {
4124 		u32 flock_len;
4125 		ceph_decode_32_safe(&p, end, flock_len, bad);
4126 		if (p + flock_len > end)
4127 			goto bad;
4128 		p += flock_len;
4129 	}
4130 
4131 	if (msg_version >= 3) {
4132 		if (op == CEPH_CAP_OP_IMPORT) {
4133 			if (p + sizeof(*peer) > end)
4134 				goto bad;
4135 			peer = p;
4136 			p += sizeof(*peer);
4137 		} else if (op == CEPH_CAP_OP_EXPORT) {
4138 			/* recorded in unused fields */
4139 			peer = (void *)&h->size;
4140 		}
4141 	}
4142 
4143 	if (msg_version >= 4) {
4144 		ceph_decode_64_safe(&p, end, extra_info.inline_version, bad);
4145 		ceph_decode_32_safe(&p, end, extra_info.inline_len, bad);
4146 		if (p + extra_info.inline_len > end)
4147 			goto bad;
4148 		extra_info.inline_data = p;
4149 		p += extra_info.inline_len;
4150 	}
4151 
4152 	if (msg_version >= 5) {
4153 		struct ceph_osd_client	*osdc = &mdsc->fsc->client->osdc;
4154 		u32			epoch_barrier;
4155 
4156 		ceph_decode_32_safe(&p, end, epoch_barrier, bad);
4157 		ceph_osdc_update_epoch_barrier(osdc, epoch_barrier);
4158 	}
4159 
4160 	if (msg_version >= 8) {
4161 		u32 pool_ns_len;
4162 
4163 		/* version >= 6 */
4164 		ceph_decode_skip_64(&p, end, bad);	// flush_tid
4165 		/* version >= 7 */
4166 		ceph_decode_skip_32(&p, end, bad);	// caller_uid
4167 		ceph_decode_skip_32(&p, end, bad);	// caller_gid
4168 		/* version >= 8 */
4169 		ceph_decode_32_safe(&p, end, pool_ns_len, bad);
4170 		if (pool_ns_len > 0) {
4171 			ceph_decode_need(&p, end, pool_ns_len, bad);
4172 			extra_info.pool_ns =
4173 				ceph_find_or_create_string(p, pool_ns_len);
4174 			p += pool_ns_len;
4175 		}
4176 	}
4177 
4178 	if (msg_version >= 9) {
4179 		struct ceph_timespec *btime;
4180 
4181 		if (p + sizeof(*btime) > end)
4182 			goto bad;
4183 		btime = p;
4184 		ceph_decode_timespec64(&extra_info.btime, btime);
4185 		p += sizeof(*btime);
4186 		ceph_decode_64_safe(&p, end, extra_info.change_attr, bad);
4187 	}
4188 
4189 	if (msg_version >= 11) {
4190 		/* version >= 10 */
4191 		ceph_decode_skip_32(&p, end, bad); // flags
4192 		/* version >= 11 */
4193 		extra_info.dirstat_valid = true;
4194 		ceph_decode_64_safe(&p, end, extra_info.nfiles, bad);
4195 		ceph_decode_64_safe(&p, end, extra_info.nsubdirs, bad);
4196 	}
4197 
4198 	/* lookup ino */
4199 	inode = ceph_find_inode(mdsc->fsc->sb, vino);
4200 	dout(" op %s ino %llx.%llx inode %p\n", ceph_cap_op_name(op), vino.ino,
4201 	     vino.snap, inode);
4202 
4203 	mutex_lock(&session->s_mutex);
4204 	inc_session_sequence(session);
4205 	dout(" mds%d seq %lld cap seq %u\n", session->s_mds, session->s_seq,
4206 	     (unsigned)seq);
4207 
4208 	if (!inode) {
4209 		dout(" i don't have ino %llx\n", vino.ino);
4210 
4211 		switch (op) {
4212 		case CEPH_CAP_OP_IMPORT:
4213 		case CEPH_CAP_OP_REVOKE:
4214 		case CEPH_CAP_OP_GRANT:
4215 			do_cap_release = true;
4216 			break;
4217 		default:
4218 			break;
4219 		}
4220 		goto flush_cap_releases;
4221 	}
4222 	ci = ceph_inode(inode);
4223 
4224 	/* these will work even if we don't have a cap yet */
4225 	switch (op) {
4226 	case CEPH_CAP_OP_FLUSHSNAP_ACK:
4227 		handle_cap_flushsnap_ack(inode, le64_to_cpu(msg->hdr.tid),
4228 					 h, session);
4229 		goto done;
4230 
4231 	case CEPH_CAP_OP_EXPORT:
4232 		handle_cap_export(inode, h, peer, session);
4233 		goto done_unlocked;
4234 
4235 	case CEPH_CAP_OP_IMPORT:
4236 		realm = NULL;
4237 		if (snaptrace_len) {
4238 			down_write(&mdsc->snap_rwsem);
4239 			if (ceph_update_snap_trace(mdsc, snaptrace,
4240 						   snaptrace + snaptrace_len,
4241 						   false, &realm)) {
4242 				up_write(&mdsc->snap_rwsem);
4243 				close_sessions = true;
4244 				goto done;
4245 			}
4246 			downgrade_write(&mdsc->snap_rwsem);
4247 		} else {
4248 			down_read(&mdsc->snap_rwsem);
4249 		}
4250 		spin_lock(&ci->i_ceph_lock);
4251 		handle_cap_import(mdsc, inode, h, peer, session,
4252 				  &cap, &extra_info.issued);
4253 		handle_cap_grant(inode, session, cap,
4254 				 h, msg->middle, &extra_info);
4255 		if (realm)
4256 			ceph_put_snap_realm(mdsc, realm);
4257 		goto done_unlocked;
4258 	}
4259 
4260 	/* the rest require a cap */
4261 	spin_lock(&ci->i_ceph_lock);
4262 	cap = __get_cap_for_mds(ceph_inode(inode), session->s_mds);
4263 	if (!cap) {
4264 		dout(" no cap on %p ino %llx.%llx from mds%d\n",
4265 		     inode, ceph_ino(inode), ceph_snap(inode),
4266 		     session->s_mds);
4267 		spin_unlock(&ci->i_ceph_lock);
4268 		switch (op) {
4269 		case CEPH_CAP_OP_REVOKE:
4270 		case CEPH_CAP_OP_GRANT:
4271 			do_cap_release = true;
4272 			break;
4273 		default:
4274 			break;
4275 		}
4276 		goto flush_cap_releases;
4277 	}
4278 
4279 	/* note that each of these drops i_ceph_lock for us */
4280 	switch (op) {
4281 	case CEPH_CAP_OP_REVOKE:
4282 	case CEPH_CAP_OP_GRANT:
4283 		__ceph_caps_issued(ci, &extra_info.issued);
4284 		extra_info.issued |= __ceph_caps_dirty(ci);
4285 		handle_cap_grant(inode, session, cap,
4286 				 h, msg->middle, &extra_info);
4287 		goto done_unlocked;
4288 
4289 	case CEPH_CAP_OP_FLUSH_ACK:
4290 		handle_cap_flush_ack(inode, le64_to_cpu(msg->hdr.tid),
4291 				     h, session, cap);
4292 		break;
4293 
4294 	case CEPH_CAP_OP_TRUNC:
4295 		queue_trunc = handle_cap_trunc(inode, h, session);
4296 		spin_unlock(&ci->i_ceph_lock);
4297 		if (queue_trunc)
4298 			ceph_queue_vmtruncate(inode);
4299 		break;
4300 
4301 	default:
4302 		spin_unlock(&ci->i_ceph_lock);
4303 		pr_err("ceph_handle_caps: unknown cap op %d %s\n", op,
4304 		       ceph_cap_op_name(op));
4305 	}
4306 
4307 done:
4308 	mutex_unlock(&session->s_mutex);
4309 done_unlocked:
4310 	iput(inode);
4311 out:
4312 	ceph_put_string(extra_info.pool_ns);
4313 
4314 	/* Defer closing the sessions after s_mutex lock being released */
4315 	if (close_sessions)
4316 		ceph_mdsc_close_sessions(mdsc);
4317 
4318 	return;
4319 
4320 flush_cap_releases:
4321 	/*
4322 	 * send any cap release message to try to move things
4323 	 * along for the mds (who clearly thinks we still have this
4324 	 * cap).
4325 	 */
4326 	if (do_cap_release) {
4327 		cap = ceph_get_cap(mdsc, NULL);
4328 		cap->cap_ino = vino.ino;
4329 		cap->queue_release = 1;
4330 		cap->cap_id = le64_to_cpu(h->cap_id);
4331 		cap->mseq = mseq;
4332 		cap->seq = seq;
4333 		cap->issue_seq = seq;
4334 		spin_lock(&session->s_cap_lock);
4335 		__ceph_queue_cap_release(session, cap);
4336 		spin_unlock(&session->s_cap_lock);
4337 	}
4338 	ceph_flush_cap_releases(mdsc, session);
4339 	goto done;
4340 
4341 bad:
4342 	pr_err("ceph_handle_caps: corrupt message\n");
4343 	ceph_msg_dump(msg);
4344 	goto out;
4345 }
4346 
4347 /*
4348  * Delayed work handler to process end of delayed cap release LRU list.
4349  *
4350  * If new caps are added to the list while processing it, these won't get
4351  * processed in this run.  In this case, the ci->i_hold_caps_max will be
4352  * returned so that the work can be scheduled accordingly.
4353  */
4354 unsigned long ceph_check_delayed_caps(struct ceph_mds_client *mdsc)
4355 {
4356 	struct inode *inode;
4357 	struct ceph_inode_info *ci;
4358 	struct ceph_mount_options *opt = mdsc->fsc->mount_options;
4359 	unsigned long delay_max = opt->caps_wanted_delay_max * HZ;
4360 	unsigned long loop_start = jiffies;
4361 	unsigned long delay = 0;
4362 
4363 	dout("check_delayed_caps\n");
4364 	spin_lock(&mdsc->cap_delay_lock);
4365 	while (!list_empty(&mdsc->cap_delay_list)) {
4366 		ci = list_first_entry(&mdsc->cap_delay_list,
4367 				      struct ceph_inode_info,
4368 				      i_cap_delay_list);
4369 		if (time_before(loop_start, ci->i_hold_caps_max - delay_max)) {
4370 			dout("%s caps added recently.  Exiting loop", __func__);
4371 			delay = ci->i_hold_caps_max;
4372 			break;
4373 		}
4374 		if ((ci->i_ceph_flags & CEPH_I_FLUSH) == 0 &&
4375 		    time_before(jiffies, ci->i_hold_caps_max))
4376 			break;
4377 		list_del_init(&ci->i_cap_delay_list);
4378 
4379 		inode = igrab(&ci->netfs.inode);
4380 		if (inode) {
4381 			spin_unlock(&mdsc->cap_delay_lock);
4382 			dout("check_delayed_caps on %p\n", inode);
4383 			ceph_check_caps(ci, 0);
4384 			iput(inode);
4385 			spin_lock(&mdsc->cap_delay_lock);
4386 		}
4387 	}
4388 	spin_unlock(&mdsc->cap_delay_lock);
4389 
4390 	return delay;
4391 }
4392 
4393 /*
4394  * Flush all dirty caps to the mds
4395  */
4396 static void flush_dirty_session_caps(struct ceph_mds_session *s)
4397 {
4398 	struct ceph_mds_client *mdsc = s->s_mdsc;
4399 	struct ceph_inode_info *ci;
4400 	struct inode *inode;
4401 
4402 	dout("flush_dirty_caps\n");
4403 	spin_lock(&mdsc->cap_dirty_lock);
4404 	while (!list_empty(&s->s_cap_dirty)) {
4405 		ci = list_first_entry(&s->s_cap_dirty, struct ceph_inode_info,
4406 				      i_dirty_item);
4407 		inode = &ci->netfs.inode;
4408 		ihold(inode);
4409 		dout("flush_dirty_caps %llx.%llx\n", ceph_vinop(inode));
4410 		spin_unlock(&mdsc->cap_dirty_lock);
4411 		ceph_wait_on_async_create(inode);
4412 		ceph_check_caps(ci, CHECK_CAPS_FLUSH);
4413 		iput(inode);
4414 		spin_lock(&mdsc->cap_dirty_lock);
4415 	}
4416 	spin_unlock(&mdsc->cap_dirty_lock);
4417 	dout("flush_dirty_caps done\n");
4418 }
4419 
4420 void ceph_flush_dirty_caps(struct ceph_mds_client *mdsc)
4421 {
4422 	ceph_mdsc_iterate_sessions(mdsc, flush_dirty_session_caps, true);
4423 }
4424 
4425 void __ceph_touch_fmode(struct ceph_inode_info *ci,
4426 			struct ceph_mds_client *mdsc, int fmode)
4427 {
4428 	unsigned long now = jiffies;
4429 	if (fmode & CEPH_FILE_MODE_RD)
4430 		ci->i_last_rd = now;
4431 	if (fmode & CEPH_FILE_MODE_WR)
4432 		ci->i_last_wr = now;
4433 	/* queue periodic check */
4434 	if (fmode &&
4435 	    __ceph_is_any_real_caps(ci) &&
4436 	    list_empty(&ci->i_cap_delay_list))
4437 		__cap_delay_requeue(mdsc, ci);
4438 }
4439 
4440 void ceph_get_fmode(struct ceph_inode_info *ci, int fmode, int count)
4441 {
4442 	struct ceph_mds_client *mdsc = ceph_sb_to_mdsc(ci->netfs.inode.i_sb);
4443 	int bits = (fmode << 1) | 1;
4444 	bool already_opened = false;
4445 	int i;
4446 
4447 	if (count == 1)
4448 		atomic64_inc(&mdsc->metric.opened_files);
4449 
4450 	spin_lock(&ci->i_ceph_lock);
4451 	for (i = 0; i < CEPH_FILE_MODE_BITS; i++) {
4452 		/*
4453 		 * If any of the mode ref is larger than 0,
4454 		 * that means it has been already opened by
4455 		 * others. Just skip checking the PIN ref.
4456 		 */
4457 		if (i && ci->i_nr_by_mode[i])
4458 			already_opened = true;
4459 
4460 		if (bits & (1 << i))
4461 			ci->i_nr_by_mode[i] += count;
4462 	}
4463 
4464 	if (!already_opened)
4465 		percpu_counter_inc(&mdsc->metric.opened_inodes);
4466 	spin_unlock(&ci->i_ceph_lock);
4467 }
4468 
4469 /*
4470  * Drop open file reference.  If we were the last open file,
4471  * we may need to release capabilities to the MDS (or schedule
4472  * their delayed release).
4473  */
4474 void ceph_put_fmode(struct ceph_inode_info *ci, int fmode, int count)
4475 {
4476 	struct ceph_mds_client *mdsc = ceph_sb_to_mdsc(ci->netfs.inode.i_sb);
4477 	int bits = (fmode << 1) | 1;
4478 	bool is_closed = true;
4479 	int i;
4480 
4481 	if (count == 1)
4482 		atomic64_dec(&mdsc->metric.opened_files);
4483 
4484 	spin_lock(&ci->i_ceph_lock);
4485 	for (i = 0; i < CEPH_FILE_MODE_BITS; i++) {
4486 		if (bits & (1 << i)) {
4487 			BUG_ON(ci->i_nr_by_mode[i] < count);
4488 			ci->i_nr_by_mode[i] -= count;
4489 		}
4490 
4491 		/*
4492 		 * If any of the mode ref is not 0 after
4493 		 * decreased, that means it is still opened
4494 		 * by others. Just skip checking the PIN ref.
4495 		 */
4496 		if (i && ci->i_nr_by_mode[i])
4497 			is_closed = false;
4498 	}
4499 
4500 	if (is_closed)
4501 		percpu_counter_dec(&mdsc->metric.opened_inodes);
4502 	spin_unlock(&ci->i_ceph_lock);
4503 }
4504 
4505 /*
4506  * For a soon-to-be unlinked file, drop the LINK caps. If it
4507  * looks like the link count will hit 0, drop any other caps (other
4508  * than PIN) we don't specifically want (due to the file still being
4509  * open).
4510  */
4511 int ceph_drop_caps_for_unlink(struct inode *inode)
4512 {
4513 	struct ceph_inode_info *ci = ceph_inode(inode);
4514 	int drop = CEPH_CAP_LINK_SHARED | CEPH_CAP_LINK_EXCL;
4515 
4516 	spin_lock(&ci->i_ceph_lock);
4517 	if (inode->i_nlink == 1) {
4518 		drop |= ~(__ceph_caps_wanted(ci) | CEPH_CAP_PIN);
4519 
4520 		if (__ceph_caps_dirty(ci)) {
4521 			struct ceph_mds_client *mdsc =
4522 				ceph_inode_to_client(inode)->mdsc;
4523 			__cap_delay_requeue_front(mdsc, ci);
4524 		}
4525 	}
4526 	spin_unlock(&ci->i_ceph_lock);
4527 	return drop;
4528 }
4529 
4530 /*
4531  * Helpers for embedding cap and dentry lease releases into mds
4532  * requests.
4533  *
4534  * @force is used by dentry_release (below) to force inclusion of a
4535  * record for the directory inode, even when there aren't any caps to
4536  * drop.
4537  */
4538 int ceph_encode_inode_release(void **p, struct inode *inode,
4539 			      int mds, int drop, int unless, int force)
4540 {
4541 	struct ceph_inode_info *ci = ceph_inode(inode);
4542 	struct ceph_cap *cap;
4543 	struct ceph_mds_request_release *rel = *p;
4544 	int used, dirty;
4545 	int ret = 0;
4546 
4547 	spin_lock(&ci->i_ceph_lock);
4548 	used = __ceph_caps_used(ci);
4549 	dirty = __ceph_caps_dirty(ci);
4550 
4551 	dout("encode_inode_release %p mds%d used|dirty %s drop %s unless %s\n",
4552 	     inode, mds, ceph_cap_string(used|dirty), ceph_cap_string(drop),
4553 	     ceph_cap_string(unless));
4554 
4555 	/* only drop unused, clean caps */
4556 	drop &= ~(used | dirty);
4557 
4558 	cap = __get_cap_for_mds(ci, mds);
4559 	if (cap && __cap_is_valid(cap)) {
4560 		unless &= cap->issued;
4561 		if (unless) {
4562 			if (unless & CEPH_CAP_AUTH_EXCL)
4563 				drop &= ~CEPH_CAP_AUTH_SHARED;
4564 			if (unless & CEPH_CAP_LINK_EXCL)
4565 				drop &= ~CEPH_CAP_LINK_SHARED;
4566 			if (unless & CEPH_CAP_XATTR_EXCL)
4567 				drop &= ~CEPH_CAP_XATTR_SHARED;
4568 			if (unless & CEPH_CAP_FILE_EXCL)
4569 				drop &= ~CEPH_CAP_FILE_SHARED;
4570 		}
4571 
4572 		if (force || (cap->issued & drop)) {
4573 			if (cap->issued & drop) {
4574 				int wanted = __ceph_caps_wanted(ci);
4575 				dout("encode_inode_release %p cap %p "
4576 				     "%s -> %s, wanted %s -> %s\n", inode, cap,
4577 				     ceph_cap_string(cap->issued),
4578 				     ceph_cap_string(cap->issued & ~drop),
4579 				     ceph_cap_string(cap->mds_wanted),
4580 				     ceph_cap_string(wanted));
4581 
4582 				cap->issued &= ~drop;
4583 				cap->implemented &= ~drop;
4584 				cap->mds_wanted = wanted;
4585 				if (cap == ci->i_auth_cap &&
4586 				    !(wanted & CEPH_CAP_ANY_FILE_WR))
4587 					ci->i_requested_max_size = 0;
4588 			} else {
4589 				dout("encode_inode_release %p cap %p %s"
4590 				     " (force)\n", inode, cap,
4591 				     ceph_cap_string(cap->issued));
4592 			}
4593 
4594 			rel->ino = cpu_to_le64(ceph_ino(inode));
4595 			rel->cap_id = cpu_to_le64(cap->cap_id);
4596 			rel->seq = cpu_to_le32(cap->seq);
4597 			rel->issue_seq = cpu_to_le32(cap->issue_seq);
4598 			rel->mseq = cpu_to_le32(cap->mseq);
4599 			rel->caps = cpu_to_le32(cap->implemented);
4600 			rel->wanted = cpu_to_le32(cap->mds_wanted);
4601 			rel->dname_len = 0;
4602 			rel->dname_seq = 0;
4603 			*p += sizeof(*rel);
4604 			ret = 1;
4605 		} else {
4606 			dout("encode_inode_release %p cap %p %s (noop)\n",
4607 			     inode, cap, ceph_cap_string(cap->issued));
4608 		}
4609 	}
4610 	spin_unlock(&ci->i_ceph_lock);
4611 	return ret;
4612 }
4613 
4614 int ceph_encode_dentry_release(void **p, struct dentry *dentry,
4615 			       struct inode *dir,
4616 			       int mds, int drop, int unless)
4617 {
4618 	struct dentry *parent = NULL;
4619 	struct ceph_mds_request_release *rel = *p;
4620 	struct ceph_dentry_info *di = ceph_dentry(dentry);
4621 	int force = 0;
4622 	int ret;
4623 
4624 	/*
4625 	 * force an record for the directory caps if we have a dentry lease.
4626 	 * this is racy (can't take i_ceph_lock and d_lock together), but it
4627 	 * doesn't have to be perfect; the mds will revoke anything we don't
4628 	 * release.
4629 	 */
4630 	spin_lock(&dentry->d_lock);
4631 	if (di->lease_session && di->lease_session->s_mds == mds)
4632 		force = 1;
4633 	if (!dir) {
4634 		parent = dget(dentry->d_parent);
4635 		dir = d_inode(parent);
4636 	}
4637 	spin_unlock(&dentry->d_lock);
4638 
4639 	ret = ceph_encode_inode_release(p, dir, mds, drop, unless, force);
4640 	dput(parent);
4641 
4642 	spin_lock(&dentry->d_lock);
4643 	if (ret && di->lease_session && di->lease_session->s_mds == mds) {
4644 		dout("encode_dentry_release %p mds%d seq %d\n",
4645 		     dentry, mds, (int)di->lease_seq);
4646 		rel->dname_len = cpu_to_le32(dentry->d_name.len);
4647 		memcpy(*p, dentry->d_name.name, dentry->d_name.len);
4648 		*p += dentry->d_name.len;
4649 		rel->dname_seq = cpu_to_le32(di->lease_seq);
4650 		__ceph_mdsc_drop_dentry_lease(dentry);
4651 	}
4652 	spin_unlock(&dentry->d_lock);
4653 	return ret;
4654 }
4655 
4656 static int remove_capsnaps(struct ceph_mds_client *mdsc, struct inode *inode)
4657 {
4658 	struct ceph_inode_info *ci = ceph_inode(inode);
4659 	struct ceph_cap_snap *capsnap;
4660 	int capsnap_release = 0;
4661 
4662 	lockdep_assert_held(&ci->i_ceph_lock);
4663 
4664 	dout("removing capsnaps, ci is %p, inode is %p\n", ci, inode);
4665 
4666 	while (!list_empty(&ci->i_cap_snaps)) {
4667 		capsnap = list_first_entry(&ci->i_cap_snaps,
4668 					   struct ceph_cap_snap, ci_item);
4669 		__ceph_remove_capsnap(inode, capsnap, NULL, NULL);
4670 		ceph_put_snap_context(capsnap->context);
4671 		ceph_put_cap_snap(capsnap);
4672 		capsnap_release++;
4673 	}
4674 	wake_up_all(&ci->i_cap_wq);
4675 	wake_up_all(&mdsc->cap_flushing_wq);
4676 	return capsnap_release;
4677 }
4678 
4679 int ceph_purge_inode_cap(struct inode *inode, struct ceph_cap *cap, bool *invalidate)
4680 {
4681 	struct ceph_fs_client *fsc = ceph_inode_to_client(inode);
4682 	struct ceph_mds_client *mdsc = fsc->mdsc;
4683 	struct ceph_inode_info *ci = ceph_inode(inode);
4684 	bool is_auth;
4685 	bool dirty_dropped = false;
4686 	int iputs = 0;
4687 
4688 	lockdep_assert_held(&ci->i_ceph_lock);
4689 
4690 	dout("removing cap %p, ci is %p, inode is %p\n",
4691 	     cap, ci, &ci->netfs.inode);
4692 
4693 	is_auth = (cap == ci->i_auth_cap);
4694 	__ceph_remove_cap(cap, false);
4695 	if (is_auth) {
4696 		struct ceph_cap_flush *cf;
4697 
4698 		if (ceph_inode_is_shutdown(inode)) {
4699 			if (inode->i_data.nrpages > 0)
4700 				*invalidate = true;
4701 			if (ci->i_wrbuffer_ref > 0)
4702 				mapping_set_error(&inode->i_data, -EIO);
4703 		}
4704 
4705 		spin_lock(&mdsc->cap_dirty_lock);
4706 
4707 		/* trash all of the cap flushes for this inode */
4708 		while (!list_empty(&ci->i_cap_flush_list)) {
4709 			cf = list_first_entry(&ci->i_cap_flush_list,
4710 					      struct ceph_cap_flush, i_list);
4711 			list_del_init(&cf->g_list);
4712 			list_del_init(&cf->i_list);
4713 			if (!cf->is_capsnap)
4714 				ceph_free_cap_flush(cf);
4715 		}
4716 
4717 		if (!list_empty(&ci->i_dirty_item)) {
4718 			pr_warn_ratelimited(
4719 				" dropping dirty %s state for %p %lld\n",
4720 				ceph_cap_string(ci->i_dirty_caps),
4721 				inode, ceph_ino(inode));
4722 			ci->i_dirty_caps = 0;
4723 			list_del_init(&ci->i_dirty_item);
4724 			dirty_dropped = true;
4725 		}
4726 		if (!list_empty(&ci->i_flushing_item)) {
4727 			pr_warn_ratelimited(
4728 				" dropping dirty+flushing %s state for %p %lld\n",
4729 				ceph_cap_string(ci->i_flushing_caps),
4730 				inode, ceph_ino(inode));
4731 			ci->i_flushing_caps = 0;
4732 			list_del_init(&ci->i_flushing_item);
4733 			mdsc->num_cap_flushing--;
4734 			dirty_dropped = true;
4735 		}
4736 		spin_unlock(&mdsc->cap_dirty_lock);
4737 
4738 		if (dirty_dropped) {
4739 			mapping_set_error(inode->i_mapping, -EIO);
4740 
4741 			if (ci->i_wrbuffer_ref_head == 0 &&
4742 			    ci->i_wr_ref == 0 &&
4743 			    ci->i_dirty_caps == 0 &&
4744 			    ci->i_flushing_caps == 0) {
4745 				ceph_put_snap_context(ci->i_head_snapc);
4746 				ci->i_head_snapc = NULL;
4747 			}
4748 		}
4749 
4750 		if (atomic_read(&ci->i_filelock_ref) > 0) {
4751 			/* make further file lock syscall return -EIO */
4752 			ci->i_ceph_flags |= CEPH_I_ERROR_FILELOCK;
4753 			pr_warn_ratelimited(" dropping file locks for %p %lld\n",
4754 					    inode, ceph_ino(inode));
4755 		}
4756 
4757 		if (!ci->i_dirty_caps && ci->i_prealloc_cap_flush) {
4758 			cf = ci->i_prealloc_cap_flush;
4759 			ci->i_prealloc_cap_flush = NULL;
4760 			if (!cf->is_capsnap)
4761 				ceph_free_cap_flush(cf);
4762 		}
4763 
4764 		if (!list_empty(&ci->i_cap_snaps))
4765 			iputs = remove_capsnaps(mdsc, inode);
4766 	}
4767 	if (dirty_dropped)
4768 		++iputs;
4769 	return iputs;
4770 }
4771