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