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