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