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