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