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