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