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