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