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