fs: remove ksys_dup
[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                 int mflags = 0;
2001                 struct cap_msg_args arg;
2002
2003                 cap = rb_entry(p, struct ceph_cap, ci_node);
2004
2005                 /* avoid looping forever */
2006                 if (mds >= cap->mds ||
2007                     ((flags & CHECK_CAPS_AUTHONLY) && cap != ci->i_auth_cap))
2008                         continue;
2009
2010                 /* NOTE: no side-effects allowed, until we take s_mutex */
2011
2012                 cap_used = used;
2013                 if (ci->i_auth_cap && cap != ci->i_auth_cap)
2014                         cap_used &= ~ci->i_auth_cap->issued;
2015
2016                 revoking = cap->implemented & ~cap->issued;
2017                 dout(" mds%d cap %p used %s issued %s implemented %s revoking %s\n",
2018                      cap->mds, cap, ceph_cap_string(cap_used),
2019                      ceph_cap_string(cap->issued),
2020                      ceph_cap_string(cap->implemented),
2021                      ceph_cap_string(revoking));
2022
2023                 if (cap == ci->i_auth_cap &&
2024                     (cap->issued & CEPH_CAP_FILE_WR)) {
2025                         /* request larger max_size from MDS? */
2026                         if (ci->i_wanted_max_size > ci->i_max_size &&
2027                             ci->i_wanted_max_size > ci->i_requested_max_size) {
2028                                 dout("requesting new max_size\n");
2029                                 goto ack;
2030                         }
2031
2032                         /* approaching file_max? */
2033                         if (__ceph_should_report_size(ci)) {
2034                                 dout("i_size approaching max_size\n");
2035                                 goto ack;
2036                         }
2037                 }
2038                 /* flush anything dirty? */
2039                 if (cap == ci->i_auth_cap) {
2040                         if ((flags & CHECK_CAPS_FLUSH) && ci->i_dirty_caps) {
2041                                 dout("flushing dirty caps\n");
2042                                 goto ack;
2043                         }
2044                         if (ci->i_ceph_flags & CEPH_I_FLUSH_SNAPS) {
2045                                 dout("flushing snap caps\n");
2046                                 goto ack;
2047                         }
2048                 }
2049
2050                 /* completed revocation? going down and there are no caps? */
2051                 if (revoking && (revoking & cap_used) == 0) {
2052                         dout("completed revocation of %s\n",
2053                              ceph_cap_string(cap->implemented & ~cap->issued));
2054                         goto ack;
2055                 }
2056
2057                 /* want more caps from mds? */
2058                 if (want & ~cap->mds_wanted) {
2059                         if (want & ~(cap->mds_wanted | cap->issued))
2060                                 goto ack;
2061                         if (!__cap_is_valid(cap))
2062                                 goto ack;
2063                 }
2064
2065                 /* things we might delay */
2066                 if ((cap->issued & ~retain) == 0)
2067                         continue;     /* nope, all good */
2068
2069 ack:
2070                 if (session && session != cap->session) {
2071                         dout("oops, wrong session %p mutex\n", session);
2072                         mutex_unlock(&session->s_mutex);
2073                         session = NULL;
2074                 }
2075                 if (!session) {
2076                         session = cap->session;
2077                         if (mutex_trylock(&session->s_mutex) == 0) {
2078                                 dout("inverting session/ino locks on %p\n",
2079                                      session);
2080                                 session = ceph_get_mds_session(session);
2081                                 spin_unlock(&ci->i_ceph_lock);
2082                                 if (took_snap_rwsem) {
2083                                         up_read(&mdsc->snap_rwsem);
2084                                         took_snap_rwsem = 0;
2085                                 }
2086                                 if (session) {
2087                                         mutex_lock(&session->s_mutex);
2088                                         ceph_put_mds_session(session);
2089                                 } else {
2090                                         /*
2091                                          * Because we take the reference while
2092                                          * holding the i_ceph_lock, it should
2093                                          * never be NULL. Throw a warning if it
2094                                          * ever is.
2095                                          */
2096                                         WARN_ON_ONCE(true);
2097                                 }
2098                                 goto retry;
2099                         }
2100                 }
2101
2102                 /* kick flushing and flush snaps before sending normal
2103                  * cap message */
2104                 if (cap == ci->i_auth_cap &&
2105                     (ci->i_ceph_flags &
2106                      (CEPH_I_KICK_FLUSH | CEPH_I_FLUSH_SNAPS))) {
2107                         if (ci->i_ceph_flags & CEPH_I_KICK_FLUSH)
2108                                 __kick_flushing_caps(mdsc, session, ci, 0);
2109                         if (ci->i_ceph_flags & CEPH_I_FLUSH_SNAPS)
2110                                 __ceph_flush_snaps(ci, session);
2111
2112                         goto retry_locked;
2113                 }
2114
2115                 /* take snap_rwsem after session mutex */
2116                 if (!took_snap_rwsem) {
2117                         if (down_read_trylock(&mdsc->snap_rwsem) == 0) {
2118                                 dout("inverting snap/in locks on %p\n",
2119                                      inode);
2120                                 spin_unlock(&ci->i_ceph_lock);
2121                                 down_read(&mdsc->snap_rwsem);
2122                                 took_snap_rwsem = 1;
2123                                 goto retry;
2124                         }
2125                         took_snap_rwsem = 1;
2126                 }
2127
2128                 if (cap == ci->i_auth_cap && ci->i_dirty_caps) {
2129                         flushing = ci->i_dirty_caps;
2130                         flush_tid = __mark_caps_flushing(inode, session, false,
2131                                                          &oldest_flush_tid);
2132                         if (flags & CHECK_CAPS_FLUSH &&
2133                             list_empty(&session->s_cap_dirty))
2134                                 mflags |= CEPH_CLIENT_CAPS_SYNC;
2135                 } else {
2136                         flushing = 0;
2137                         flush_tid = 0;
2138                         spin_lock(&mdsc->cap_dirty_lock);
2139                         oldest_flush_tid = __get_oldest_flush_tid(mdsc);
2140                         spin_unlock(&mdsc->cap_dirty_lock);
2141                 }
2142
2143                 mds = cap->mds;  /* remember mds, so we don't repeat */
2144
2145                 __prep_cap(&arg, cap, CEPH_CAP_OP_UPDATE, mflags, cap_used,
2146                            want, retain, flushing, flush_tid, oldest_flush_tid);
2147                 spin_unlock(&ci->i_ceph_lock);
2148
2149                 __send_cap(mdsc, &arg, ci);
2150
2151                 goto retry; /* retake i_ceph_lock and restart our cap scan. */
2152         }
2153
2154         /* periodically re-calculate caps wanted by open files */
2155         if (__ceph_is_any_real_caps(ci) &&
2156             list_empty(&ci->i_cap_delay_list) &&
2157             (file_wanted & ~CEPH_CAP_PIN) &&
2158             !(used & (CEPH_CAP_FILE_RD | CEPH_CAP_ANY_FILE_WR))) {
2159                 __cap_delay_requeue(mdsc, ci);
2160         }
2161
2162         spin_unlock(&ci->i_ceph_lock);
2163
2164         if (queue_invalidate)
2165                 ceph_queue_invalidate(inode);
2166
2167         if (session)
2168                 mutex_unlock(&session->s_mutex);
2169         if (took_snap_rwsem)
2170                 up_read(&mdsc->snap_rwsem);
2171 }
2172
2173 /*
2174  * Try to flush dirty caps back to the auth mds.
2175  */
2176 static int try_flush_caps(struct inode *inode, u64 *ptid)
2177 {
2178         struct ceph_mds_client *mdsc = ceph_sb_to_client(inode->i_sb)->mdsc;
2179         struct ceph_inode_info *ci = ceph_inode(inode);
2180         struct ceph_mds_session *session = NULL;
2181         int flushing = 0;
2182         u64 flush_tid = 0, oldest_flush_tid = 0;
2183
2184 retry:
2185         spin_lock(&ci->i_ceph_lock);
2186 retry_locked:
2187         if (ci->i_dirty_caps && ci->i_auth_cap) {
2188                 struct ceph_cap *cap = ci->i_auth_cap;
2189                 struct cap_msg_args arg;
2190
2191                 if (session != cap->session) {
2192                         spin_unlock(&ci->i_ceph_lock);
2193                         if (session)
2194                                 mutex_unlock(&session->s_mutex);
2195                         session = cap->session;
2196                         mutex_lock(&session->s_mutex);
2197                         goto retry;
2198                 }
2199                 if (cap->session->s_state < CEPH_MDS_SESSION_OPEN) {
2200                         spin_unlock(&ci->i_ceph_lock);
2201                         goto out;
2202                 }
2203
2204                 if (ci->i_ceph_flags &
2205                     (CEPH_I_KICK_FLUSH | CEPH_I_FLUSH_SNAPS)) {
2206                         if (ci->i_ceph_flags & CEPH_I_KICK_FLUSH)
2207                                 __kick_flushing_caps(mdsc, session, ci, 0);
2208                         if (ci->i_ceph_flags & CEPH_I_FLUSH_SNAPS)
2209                                 __ceph_flush_snaps(ci, session);
2210                         goto retry_locked;
2211                 }
2212
2213                 flushing = ci->i_dirty_caps;
2214                 flush_tid = __mark_caps_flushing(inode, session, true,
2215                                                  &oldest_flush_tid);
2216
2217                 __prep_cap(&arg, cap, CEPH_CAP_OP_FLUSH, CEPH_CLIENT_CAPS_SYNC,
2218                            __ceph_caps_used(ci), __ceph_caps_wanted(ci),
2219                            (cap->issued | cap->implemented),
2220                            flushing, flush_tid, oldest_flush_tid);
2221                 spin_unlock(&ci->i_ceph_lock);
2222
2223                 __send_cap(mdsc, &arg, ci);
2224         } else {
2225                 if (!list_empty(&ci->i_cap_flush_list)) {
2226                         struct ceph_cap_flush *cf =
2227                                 list_last_entry(&ci->i_cap_flush_list,
2228                                                 struct ceph_cap_flush, i_list);
2229                         cf->wake = true;
2230                         flush_tid = cf->tid;
2231                 }
2232                 flushing = ci->i_flushing_caps;
2233                 spin_unlock(&ci->i_ceph_lock);
2234         }
2235 out:
2236         if (session)
2237                 mutex_unlock(&session->s_mutex);
2238
2239         *ptid = flush_tid;
2240         return flushing;
2241 }
2242
2243 /*
2244  * Return true if we've flushed caps through the given flush_tid.
2245  */
2246 static int caps_are_flushed(struct inode *inode, u64 flush_tid)
2247 {
2248         struct ceph_inode_info *ci = ceph_inode(inode);
2249         int ret = 1;
2250
2251         spin_lock(&ci->i_ceph_lock);
2252         if (!list_empty(&ci->i_cap_flush_list)) {
2253                 struct ceph_cap_flush * cf =
2254                         list_first_entry(&ci->i_cap_flush_list,
2255                                          struct ceph_cap_flush, i_list);
2256                 if (cf->tid <= flush_tid)
2257                         ret = 0;
2258         }
2259         spin_unlock(&ci->i_ceph_lock);
2260         return ret;
2261 }
2262
2263 /*
2264  * wait for any unsafe requests to complete.
2265  */
2266 static int unsafe_request_wait(struct inode *inode)
2267 {
2268         struct ceph_inode_info *ci = ceph_inode(inode);
2269         struct ceph_mds_request *req1 = NULL, *req2 = NULL;
2270         int ret, err = 0;
2271
2272         spin_lock(&ci->i_unsafe_lock);
2273         if (S_ISDIR(inode->i_mode) && !list_empty(&ci->i_unsafe_dirops)) {
2274                 req1 = list_last_entry(&ci->i_unsafe_dirops,
2275                                         struct ceph_mds_request,
2276                                         r_unsafe_dir_item);
2277                 ceph_mdsc_get_request(req1);
2278         }
2279         if (!list_empty(&ci->i_unsafe_iops)) {
2280                 req2 = list_last_entry(&ci->i_unsafe_iops,
2281                                         struct ceph_mds_request,
2282                                         r_unsafe_target_item);
2283                 ceph_mdsc_get_request(req2);
2284         }
2285         spin_unlock(&ci->i_unsafe_lock);
2286
2287         dout("unsafe_request_wait %p wait on tid %llu %llu\n",
2288              inode, req1 ? req1->r_tid : 0ULL, req2 ? req2->r_tid : 0ULL);
2289         if (req1) {
2290                 ret = !wait_for_completion_timeout(&req1->r_safe_completion,
2291                                         ceph_timeout_jiffies(req1->r_timeout));
2292                 if (ret)
2293                         err = -EIO;
2294                 ceph_mdsc_put_request(req1);
2295         }
2296         if (req2) {
2297                 ret = !wait_for_completion_timeout(&req2->r_safe_completion,
2298                                         ceph_timeout_jiffies(req2->r_timeout));
2299                 if (ret)
2300                         err = -EIO;
2301                 ceph_mdsc_put_request(req2);
2302         }
2303         return err;
2304 }
2305
2306 int ceph_fsync(struct file *file, loff_t start, loff_t end, int datasync)
2307 {
2308         struct ceph_file_info *fi = file->private_data;
2309         struct inode *inode = file->f_mapping->host;
2310         struct ceph_inode_info *ci = ceph_inode(inode);
2311         u64 flush_tid;
2312         int ret, err;
2313         int dirty;
2314
2315         dout("fsync %p%s\n", inode, datasync ? " datasync" : "");
2316
2317         ret = file_write_and_wait_range(file, start, end);
2318         if (datasync)
2319                 goto out;
2320
2321         ret = ceph_wait_on_async_create(inode);
2322         if (ret)
2323                 goto out;
2324
2325         dirty = try_flush_caps(inode, &flush_tid);
2326         dout("fsync dirty caps are %s\n", ceph_cap_string(dirty));
2327
2328         err = unsafe_request_wait(inode);
2329
2330         /*
2331          * only wait on non-file metadata writeback (the mds
2332          * can recover size and mtime, so we don't need to
2333          * wait for that)
2334          */
2335         if (!err && (dirty & ~CEPH_CAP_ANY_FILE_WR)) {
2336                 err = wait_event_interruptible(ci->i_cap_wq,
2337                                         caps_are_flushed(inode, flush_tid));
2338         }
2339
2340         if (err < 0)
2341                 ret = err;
2342
2343         if (errseq_check(&ci->i_meta_err, READ_ONCE(fi->meta_err))) {
2344                 spin_lock(&file->f_lock);
2345                 err = errseq_check_and_advance(&ci->i_meta_err,
2346                                                &fi->meta_err);
2347                 spin_unlock(&file->f_lock);
2348                 if (err < 0)
2349                         ret = err;
2350         }
2351 out:
2352         dout("fsync %p%s result=%d\n", inode, datasync ? " datasync" : "", ret);
2353         return ret;
2354 }
2355
2356 /*
2357  * Flush any dirty caps back to the mds.  If we aren't asked to wait,
2358  * queue inode for flush but don't do so immediately, because we can
2359  * get by with fewer MDS messages if we wait for data writeback to
2360  * complete first.
2361  */
2362 int ceph_write_inode(struct inode *inode, struct writeback_control *wbc)
2363 {
2364         struct ceph_inode_info *ci = ceph_inode(inode);
2365         u64 flush_tid;
2366         int err = 0;
2367         int dirty;
2368         int wait = (wbc->sync_mode == WB_SYNC_ALL && !wbc->for_sync);
2369
2370         dout("write_inode %p wait=%d\n", inode, wait);
2371         if (wait) {
2372                 dirty = try_flush_caps(inode, &flush_tid);
2373                 if (dirty)
2374                         err = wait_event_interruptible(ci->i_cap_wq,
2375                                        caps_are_flushed(inode, flush_tid));
2376         } else {
2377                 struct ceph_mds_client *mdsc =
2378                         ceph_sb_to_client(inode->i_sb)->mdsc;
2379
2380                 spin_lock(&ci->i_ceph_lock);
2381                 if (__ceph_caps_dirty(ci))
2382                         __cap_delay_requeue_front(mdsc, ci);
2383                 spin_unlock(&ci->i_ceph_lock);
2384         }
2385         return err;
2386 }
2387
2388 static void __kick_flushing_caps(struct ceph_mds_client *mdsc,
2389                                  struct ceph_mds_session *session,
2390                                  struct ceph_inode_info *ci,
2391                                  u64 oldest_flush_tid)
2392         __releases(ci->i_ceph_lock)
2393         __acquires(ci->i_ceph_lock)
2394 {
2395         struct inode *inode = &ci->vfs_inode;
2396         struct ceph_cap *cap;
2397         struct ceph_cap_flush *cf;
2398         int ret;
2399         u64 first_tid = 0;
2400         u64 last_snap_flush = 0;
2401
2402         ci->i_ceph_flags &= ~CEPH_I_KICK_FLUSH;
2403
2404         list_for_each_entry_reverse(cf, &ci->i_cap_flush_list, i_list) {
2405                 if (!cf->caps) {
2406                         last_snap_flush = cf->tid;
2407                         break;
2408                 }
2409         }
2410
2411         list_for_each_entry(cf, &ci->i_cap_flush_list, i_list) {
2412                 if (cf->tid < first_tid)
2413                         continue;
2414
2415                 cap = ci->i_auth_cap;
2416                 if (!(cap && cap->session == session)) {
2417                         pr_err("%p auth cap %p not mds%d ???\n",
2418                                inode, cap, session->s_mds);
2419                         break;
2420                 }
2421
2422                 first_tid = cf->tid + 1;
2423
2424                 if (cf->caps) {
2425                         struct cap_msg_args arg;
2426
2427                         dout("kick_flushing_caps %p cap %p tid %llu %s\n",
2428                              inode, cap, cf->tid, ceph_cap_string(cf->caps));
2429                         __prep_cap(&arg, cap, CEPH_CAP_OP_FLUSH,
2430                                          (cf->tid < last_snap_flush ?
2431                                           CEPH_CLIENT_CAPS_PENDING_CAPSNAP : 0),
2432                                           __ceph_caps_used(ci),
2433                                           __ceph_caps_wanted(ci),
2434                                           (cap->issued | cap->implemented),
2435                                           cf->caps, cf->tid, oldest_flush_tid);
2436                         spin_unlock(&ci->i_ceph_lock);
2437                         __send_cap(mdsc, &arg, ci);
2438                 } else {
2439                         struct ceph_cap_snap *capsnap =
2440                                         container_of(cf, struct ceph_cap_snap,
2441                                                     cap_flush);
2442                         dout("kick_flushing_caps %p capsnap %p tid %llu %s\n",
2443                              inode, capsnap, cf->tid,
2444                              ceph_cap_string(capsnap->dirty));
2445
2446                         refcount_inc(&capsnap->nref);
2447                         spin_unlock(&ci->i_ceph_lock);
2448
2449                         ret = __send_flush_snap(inode, session, capsnap, cap->mseq,
2450                                                 oldest_flush_tid);
2451                         if (ret < 0) {
2452                                 pr_err("kick_flushing_caps: error sending "
2453                                         "cap flushsnap, ino (%llx.%llx) "
2454                                         "tid %llu follows %llu\n",
2455                                         ceph_vinop(inode), cf->tid,
2456                                         capsnap->follows);
2457                         }
2458
2459                         ceph_put_cap_snap(capsnap);
2460                 }
2461
2462                 spin_lock(&ci->i_ceph_lock);
2463         }
2464 }
2465
2466 void ceph_early_kick_flushing_caps(struct ceph_mds_client *mdsc,
2467                                    struct ceph_mds_session *session)
2468 {
2469         struct ceph_inode_info *ci;
2470         struct ceph_cap *cap;
2471         u64 oldest_flush_tid;
2472
2473         dout("early_kick_flushing_caps mds%d\n", session->s_mds);
2474
2475         spin_lock(&mdsc->cap_dirty_lock);
2476         oldest_flush_tid = __get_oldest_flush_tid(mdsc);
2477         spin_unlock(&mdsc->cap_dirty_lock);
2478
2479         list_for_each_entry(ci, &session->s_cap_flushing, i_flushing_item) {
2480                 spin_lock(&ci->i_ceph_lock);
2481                 cap = ci->i_auth_cap;
2482                 if (!(cap && cap->session == session)) {
2483                         pr_err("%p auth cap %p not mds%d ???\n",
2484                                 &ci->vfs_inode, cap, session->s_mds);
2485                         spin_unlock(&ci->i_ceph_lock);
2486                         continue;
2487                 }
2488
2489
2490                 /*
2491                  * if flushing caps were revoked, we re-send the cap flush
2492                  * in client reconnect stage. This guarantees MDS * processes
2493                  * the cap flush message before issuing the flushing caps to
2494                  * other client.
2495                  */
2496                 if ((cap->issued & ci->i_flushing_caps) !=
2497                     ci->i_flushing_caps) {
2498                         /* encode_caps_cb() also will reset these sequence
2499                          * numbers. make sure sequence numbers in cap flush
2500                          * message match later reconnect message */
2501                         cap->seq = 0;
2502                         cap->issue_seq = 0;
2503                         cap->mseq = 0;
2504                         __kick_flushing_caps(mdsc, session, ci,
2505                                              oldest_flush_tid);
2506                 } else {
2507                         ci->i_ceph_flags |= CEPH_I_KICK_FLUSH;
2508                 }
2509
2510                 spin_unlock(&ci->i_ceph_lock);
2511         }
2512 }
2513
2514 void ceph_kick_flushing_caps(struct ceph_mds_client *mdsc,
2515                              struct ceph_mds_session *session)
2516 {
2517         struct ceph_inode_info *ci;
2518         struct ceph_cap *cap;
2519         u64 oldest_flush_tid;
2520
2521         lockdep_assert_held(&session->s_mutex);
2522
2523         dout("kick_flushing_caps mds%d\n", session->s_mds);
2524
2525         spin_lock(&mdsc->cap_dirty_lock);
2526         oldest_flush_tid = __get_oldest_flush_tid(mdsc);
2527         spin_unlock(&mdsc->cap_dirty_lock);
2528
2529         list_for_each_entry(ci, &session->s_cap_flushing, i_flushing_item) {
2530                 spin_lock(&ci->i_ceph_lock);
2531                 cap = ci->i_auth_cap;
2532                 if (!(cap && cap->session == session)) {
2533                         pr_err("%p auth cap %p not mds%d ???\n",
2534                                 &ci->vfs_inode, cap, session->s_mds);
2535                         spin_unlock(&ci->i_ceph_lock);
2536                         continue;
2537                 }
2538                 if (ci->i_ceph_flags & CEPH_I_KICK_FLUSH) {
2539                         __kick_flushing_caps(mdsc, session, ci,
2540                                              oldest_flush_tid);
2541                 }
2542                 spin_unlock(&ci->i_ceph_lock);
2543         }
2544 }
2545
2546 void ceph_kick_flushing_inode_caps(struct ceph_mds_session *session,
2547                                    struct ceph_inode_info *ci)
2548 {
2549         struct ceph_mds_client *mdsc = session->s_mdsc;
2550         struct ceph_cap *cap = ci->i_auth_cap;
2551
2552         lockdep_assert_held(&ci->i_ceph_lock);
2553
2554         dout("%s %p flushing %s\n", __func__, &ci->vfs_inode,
2555              ceph_cap_string(ci->i_flushing_caps));
2556
2557         if (!list_empty(&ci->i_cap_flush_list)) {
2558                 u64 oldest_flush_tid;
2559                 spin_lock(&mdsc->cap_dirty_lock);
2560                 list_move_tail(&ci->i_flushing_item,
2561                                &cap->session->s_cap_flushing);
2562                 oldest_flush_tid = __get_oldest_flush_tid(mdsc);
2563                 spin_unlock(&mdsc->cap_dirty_lock);
2564
2565                 __kick_flushing_caps(mdsc, session, ci, oldest_flush_tid);
2566         }
2567 }
2568
2569
2570 /*
2571  * Take references to capabilities we hold, so that we don't release
2572  * them to the MDS prematurely.
2573  */
2574 void ceph_take_cap_refs(struct ceph_inode_info *ci, int got,
2575                             bool snap_rwsem_locked)
2576 {
2577         lockdep_assert_held(&ci->i_ceph_lock);
2578
2579         if (got & CEPH_CAP_PIN)
2580                 ci->i_pin_ref++;
2581         if (got & CEPH_CAP_FILE_RD)
2582                 ci->i_rd_ref++;
2583         if (got & CEPH_CAP_FILE_CACHE)
2584                 ci->i_rdcache_ref++;
2585         if (got & CEPH_CAP_FILE_EXCL)
2586                 ci->i_fx_ref++;
2587         if (got & CEPH_CAP_FILE_WR) {
2588                 if (ci->i_wr_ref == 0 && !ci->i_head_snapc) {
2589                         BUG_ON(!snap_rwsem_locked);
2590                         ci->i_head_snapc = ceph_get_snap_context(
2591                                         ci->i_snap_realm->cached_context);
2592                 }
2593                 ci->i_wr_ref++;
2594         }
2595         if (got & CEPH_CAP_FILE_BUFFER) {
2596                 if (ci->i_wb_ref == 0)
2597                         ihold(&ci->vfs_inode);
2598                 ci->i_wb_ref++;
2599                 dout("%s %p wb %d -> %d (?)\n", __func__,
2600                      &ci->vfs_inode, ci->i_wb_ref-1, ci->i_wb_ref);
2601         }
2602 }
2603
2604 /*
2605  * Try to grab cap references.  Specify those refs we @want, and the
2606  * minimal set we @need.  Also include the larger offset we are writing
2607  * to (when applicable), and check against max_size here as well.
2608  * Note that caller is responsible for ensuring max_size increases are
2609  * requested from the MDS.
2610  *
2611  * Returns 0 if caps were not able to be acquired (yet), 1 if succeed,
2612  * or a negative error code. There are 3 speical error codes:
2613  *  -EAGAIN: need to sleep but non-blocking is specified
2614  *  -EFBIG:  ask caller to call check_max_size() and try again.
2615  *  -ESTALE: ask caller to call ceph_renew_caps() and try again.
2616  */
2617 enum {
2618         /* first 8 bits are reserved for CEPH_FILE_MODE_FOO */
2619         NON_BLOCKING    = (1 << 8),
2620         CHECK_FILELOCK  = (1 << 9),
2621 };
2622
2623 static int try_get_cap_refs(struct inode *inode, int need, int want,
2624                             loff_t endoff, int flags, int *got)
2625 {
2626         struct ceph_inode_info *ci = ceph_inode(inode);
2627         struct ceph_mds_client *mdsc = ceph_inode_to_client(inode)->mdsc;
2628         int ret = 0;
2629         int have, implemented;
2630         bool snap_rwsem_locked = false;
2631
2632         dout("get_cap_refs %p need %s want %s\n", inode,
2633              ceph_cap_string(need), ceph_cap_string(want));
2634
2635 again:
2636         spin_lock(&ci->i_ceph_lock);
2637
2638         if ((flags & CHECK_FILELOCK) &&
2639             (ci->i_ceph_flags & CEPH_I_ERROR_FILELOCK)) {
2640                 dout("try_get_cap_refs %p error filelock\n", inode);
2641                 ret = -EIO;
2642                 goto out_unlock;
2643         }
2644
2645         /* finish pending truncate */
2646         while (ci->i_truncate_pending) {
2647                 spin_unlock(&ci->i_ceph_lock);
2648                 if (snap_rwsem_locked) {
2649                         up_read(&mdsc->snap_rwsem);
2650                         snap_rwsem_locked = false;
2651                 }
2652                 __ceph_do_pending_vmtruncate(inode);
2653                 spin_lock(&ci->i_ceph_lock);
2654         }
2655
2656         have = __ceph_caps_issued(ci, &implemented);
2657
2658         if (have & need & CEPH_CAP_FILE_WR) {
2659                 if (endoff >= 0 && endoff > (loff_t)ci->i_max_size) {
2660                         dout("get_cap_refs %p endoff %llu > maxsize %llu\n",
2661                              inode, endoff, ci->i_max_size);
2662                         if (endoff > ci->i_requested_max_size)
2663                                 ret = ci->i_auth_cap ? -EFBIG : -ESTALE;
2664                         goto out_unlock;
2665                 }
2666                 /*
2667                  * If a sync write is in progress, we must wait, so that we
2668                  * can get a final snapshot value for size+mtime.
2669                  */
2670                 if (__ceph_have_pending_cap_snap(ci)) {
2671                         dout("get_cap_refs %p cap_snap_pending\n", inode);
2672                         goto out_unlock;
2673                 }
2674         }
2675
2676         if ((have & need) == need) {
2677                 /*
2678                  * Look at (implemented & ~have & not) so that we keep waiting
2679                  * on transition from wanted -> needed caps.  This is needed
2680                  * for WRBUFFER|WR -> WR to avoid a new WR sync write from
2681                  * going before a prior buffered writeback happens.
2682                  */
2683                 int not = want & ~(have & need);
2684                 int revoking = implemented & ~have;
2685                 dout("get_cap_refs %p have %s but not %s (revoking %s)\n",
2686                      inode, ceph_cap_string(have), ceph_cap_string(not),
2687                      ceph_cap_string(revoking));
2688                 if ((revoking & not) == 0) {
2689                         if (!snap_rwsem_locked &&
2690                             !ci->i_head_snapc &&
2691                             (need & CEPH_CAP_FILE_WR)) {
2692                                 if (!down_read_trylock(&mdsc->snap_rwsem)) {
2693                                         /*
2694                                          * we can not call down_read() when
2695                                          * task isn't in TASK_RUNNING state
2696                                          */
2697                                         if (flags & NON_BLOCKING) {
2698                                                 ret = -EAGAIN;
2699                                                 goto out_unlock;
2700                                         }
2701
2702                                         spin_unlock(&ci->i_ceph_lock);
2703                                         down_read(&mdsc->snap_rwsem);
2704                                         snap_rwsem_locked = true;
2705                                         goto again;
2706                                 }
2707                                 snap_rwsem_locked = true;
2708                         }
2709                         if ((have & want) == want)
2710                                 *got = need | want;
2711                         else
2712                                 *got = need;
2713                         if (S_ISREG(inode->i_mode) &&
2714                             (need & CEPH_CAP_FILE_RD) &&
2715                             !(*got & CEPH_CAP_FILE_CACHE))
2716                                 ceph_disable_fscache_readpage(ci);
2717                         ceph_take_cap_refs(ci, *got, true);
2718                         ret = 1;
2719                 }
2720         } else {
2721                 int session_readonly = false;
2722                 int mds_wanted;
2723                 if (ci->i_auth_cap &&
2724                     (need & (CEPH_CAP_FILE_WR | CEPH_CAP_FILE_EXCL))) {
2725                         struct ceph_mds_session *s = ci->i_auth_cap->session;
2726                         spin_lock(&s->s_cap_lock);
2727                         session_readonly = s->s_readonly;
2728                         spin_unlock(&s->s_cap_lock);
2729                 }
2730                 if (session_readonly) {
2731                         dout("get_cap_refs %p need %s but mds%d readonly\n",
2732                              inode, ceph_cap_string(need), ci->i_auth_cap->mds);
2733                         ret = -EROFS;
2734                         goto out_unlock;
2735                 }
2736
2737                 if (READ_ONCE(mdsc->fsc->mount_state) == CEPH_MOUNT_SHUTDOWN) {
2738                         dout("get_cap_refs %p forced umount\n", inode);
2739                         ret = -EIO;
2740                         goto out_unlock;
2741                 }
2742                 mds_wanted = __ceph_caps_mds_wanted(ci, false);
2743                 if (need & ~mds_wanted) {
2744                         dout("get_cap_refs %p need %s > mds_wanted %s\n",
2745                              inode, ceph_cap_string(need),
2746                              ceph_cap_string(mds_wanted));
2747                         ret = -ESTALE;
2748                         goto out_unlock;
2749                 }
2750
2751                 dout("get_cap_refs %p have %s need %s\n", inode,
2752                      ceph_cap_string(have), ceph_cap_string(need));
2753         }
2754 out_unlock:
2755
2756         __ceph_touch_fmode(ci, mdsc, flags);
2757
2758         spin_unlock(&ci->i_ceph_lock);
2759         if (snap_rwsem_locked)
2760                 up_read(&mdsc->snap_rwsem);
2761
2762         if (!ret)
2763                 ceph_update_cap_mis(&mdsc->metric);
2764         else if (ret == 1)
2765                 ceph_update_cap_hit(&mdsc->metric);
2766
2767         dout("get_cap_refs %p ret %d got %s\n", inode,
2768              ret, ceph_cap_string(*got));
2769         return ret;
2770 }
2771
2772 /*
2773  * Check the offset we are writing up to against our current
2774  * max_size.  If necessary, tell the MDS we want to write to
2775  * a larger offset.
2776  */
2777 static void check_max_size(struct inode *inode, loff_t endoff)
2778 {
2779         struct ceph_inode_info *ci = ceph_inode(inode);
2780         int check = 0;
2781
2782         /* do we need to explicitly request a larger max_size? */
2783         spin_lock(&ci->i_ceph_lock);
2784         if (endoff >= ci->i_max_size && endoff > ci->i_wanted_max_size) {
2785                 dout("write %p at large endoff %llu, req max_size\n",
2786                      inode, endoff);
2787                 ci->i_wanted_max_size = endoff;
2788         }
2789         /* duplicate ceph_check_caps()'s logic */
2790         if (ci->i_auth_cap &&
2791             (ci->i_auth_cap->issued & CEPH_CAP_FILE_WR) &&
2792             ci->i_wanted_max_size > ci->i_max_size &&
2793             ci->i_wanted_max_size > ci->i_requested_max_size)
2794                 check = 1;
2795         spin_unlock(&ci->i_ceph_lock);
2796         if (check)
2797                 ceph_check_caps(ci, CHECK_CAPS_AUTHONLY, NULL);
2798 }
2799
2800 static inline int get_used_fmode(int caps)
2801 {
2802         int fmode = 0;
2803         if (caps & CEPH_CAP_FILE_RD)
2804                 fmode |= CEPH_FILE_MODE_RD;
2805         if (caps & CEPH_CAP_FILE_WR)
2806                 fmode |= CEPH_FILE_MODE_WR;
2807         return fmode;
2808 }
2809
2810 int ceph_try_get_caps(struct inode *inode, int need, int want,
2811                       bool nonblock, int *got)
2812 {
2813         int ret, flags;
2814
2815         BUG_ON(need & ~CEPH_CAP_FILE_RD);
2816         BUG_ON(want & ~(CEPH_CAP_FILE_CACHE | CEPH_CAP_FILE_LAZYIO |
2817                         CEPH_CAP_FILE_SHARED | CEPH_CAP_FILE_EXCL |
2818                         CEPH_CAP_ANY_DIR_OPS));
2819         if (need) {
2820                 ret = ceph_pool_perm_check(inode, need);
2821                 if (ret < 0)
2822                         return ret;
2823         }
2824
2825         flags = get_used_fmode(need | want);
2826         if (nonblock)
2827                 flags |= NON_BLOCKING;
2828
2829         ret = try_get_cap_refs(inode, need, want, 0, flags, got);
2830         /* three special error codes */
2831         if (ret == -EAGAIN || ret == -EFBIG || ret == -ESTALE)
2832                 ret = 0;
2833         return ret;
2834 }
2835
2836 /*
2837  * Wait for caps, and take cap references.  If we can't get a WR cap
2838  * due to a small max_size, make sure we check_max_size (and possibly
2839  * ask the mds) so we don't get hung up indefinitely.
2840  */
2841 int ceph_get_caps(struct file *filp, int need, int want,
2842                   loff_t endoff, int *got, struct page **pinned_page)
2843 {
2844         struct ceph_file_info *fi = filp->private_data;
2845         struct inode *inode = file_inode(filp);
2846         struct ceph_inode_info *ci = ceph_inode(inode);
2847         struct ceph_fs_client *fsc = ceph_inode_to_client(inode);
2848         int ret, _got, flags;
2849
2850         ret = ceph_pool_perm_check(inode, need);
2851         if (ret < 0)
2852                 return ret;
2853
2854         if ((fi->fmode & CEPH_FILE_MODE_WR) &&
2855             fi->filp_gen != READ_ONCE(fsc->filp_gen))
2856                 return -EBADF;
2857
2858         flags = get_used_fmode(need | want);
2859
2860         while (true) {
2861                 flags &= CEPH_FILE_MODE_MASK;
2862                 if (atomic_read(&fi->num_locks))
2863                         flags |= CHECK_FILELOCK;
2864                 _got = 0;
2865                 ret = try_get_cap_refs(inode, need, want, endoff,
2866                                        flags, &_got);
2867                 WARN_ON_ONCE(ret == -EAGAIN);
2868                 if (!ret) {
2869                         struct ceph_mds_client *mdsc = fsc->mdsc;
2870                         struct cap_wait cw;
2871                         DEFINE_WAIT_FUNC(wait, woken_wake_function);
2872
2873                         cw.ino = inode->i_ino;
2874                         cw.tgid = current->tgid;
2875                         cw.need = need;
2876                         cw.want = want;
2877
2878                         spin_lock(&mdsc->caps_list_lock);
2879                         list_add(&cw.list, &mdsc->cap_wait_list);
2880                         spin_unlock(&mdsc->caps_list_lock);
2881
2882                         /* make sure used fmode not timeout */
2883                         ceph_get_fmode(ci, flags, FMODE_WAIT_BIAS);
2884                         add_wait_queue(&ci->i_cap_wq, &wait);
2885
2886                         flags |= NON_BLOCKING;
2887                         while (!(ret = try_get_cap_refs(inode, need, want,
2888                                                         endoff, flags, &_got))) {
2889                                 if (signal_pending(current)) {
2890                                         ret = -ERESTARTSYS;
2891                                         break;
2892                                 }
2893                                 wait_woken(&wait, TASK_INTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT);
2894                         }
2895
2896                         remove_wait_queue(&ci->i_cap_wq, &wait);
2897                         ceph_put_fmode(ci, flags, FMODE_WAIT_BIAS);
2898
2899                         spin_lock(&mdsc->caps_list_lock);
2900                         list_del(&cw.list);
2901                         spin_unlock(&mdsc->caps_list_lock);
2902
2903                         if (ret == -EAGAIN)
2904                                 continue;
2905                 }
2906
2907                 if ((fi->fmode & CEPH_FILE_MODE_WR) &&
2908                     fi->filp_gen != READ_ONCE(fsc->filp_gen)) {
2909                         if (ret >= 0 && _got)
2910                                 ceph_put_cap_refs(ci, _got);
2911                         return -EBADF;
2912                 }
2913
2914                 if (ret < 0) {
2915                         if (ret == -EFBIG || ret == -ESTALE) {
2916                                 int ret2 = ceph_wait_on_async_create(inode);
2917                                 if (ret2 < 0)
2918                                         return ret2;
2919                         }
2920                         if (ret == -EFBIG) {
2921                                 check_max_size(inode, endoff);
2922                                 continue;
2923                         }
2924                         if (ret == -ESTALE) {
2925                                 /* session was killed, try renew caps */
2926                                 ret = ceph_renew_caps(inode, flags);
2927                                 if (ret == 0)
2928                                         continue;
2929                         }
2930                         return ret;
2931                 }
2932
2933                 if (S_ISREG(ci->vfs_inode.i_mode) &&
2934                     ci->i_inline_version != CEPH_INLINE_NONE &&
2935                     (_got & (CEPH_CAP_FILE_CACHE|CEPH_CAP_FILE_LAZYIO)) &&
2936                     i_size_read(inode) > 0) {
2937                         struct page *page =
2938                                 find_get_page(inode->i_mapping, 0);
2939                         if (page) {
2940                                 if (PageUptodate(page)) {
2941                                         *pinned_page = page;
2942                                         break;
2943                                 }
2944                                 put_page(page);
2945                         }
2946                         /*
2947                          * drop cap refs first because getattr while
2948                          * holding * caps refs can cause deadlock.
2949                          */
2950                         ceph_put_cap_refs(ci, _got);
2951                         _got = 0;
2952
2953                         /*
2954                          * getattr request will bring inline data into
2955                          * page cache
2956                          */
2957                         ret = __ceph_do_getattr(inode, NULL,
2958                                                 CEPH_STAT_CAP_INLINE_DATA,
2959                                                 true);
2960                         if (ret < 0)
2961                                 return ret;
2962                         continue;
2963                 }
2964                 break;
2965         }
2966
2967         if (S_ISREG(ci->vfs_inode.i_mode) &&
2968             (_got & CEPH_CAP_FILE_RD) && (_got & CEPH_CAP_FILE_CACHE))
2969                 ceph_fscache_revalidate_cookie(ci);
2970
2971         *got = _got;
2972         return 0;
2973 }
2974
2975 /*
2976  * Take cap refs.  Caller must already know we hold at least one ref
2977  * on the caps in question or we don't know this is safe.
2978  */
2979 void ceph_get_cap_refs(struct ceph_inode_info *ci, int caps)
2980 {
2981         spin_lock(&ci->i_ceph_lock);
2982         ceph_take_cap_refs(ci, caps, false);
2983         spin_unlock(&ci->i_ceph_lock);
2984 }
2985
2986
2987 /*
2988  * drop cap_snap that is not associated with any snapshot.
2989  * we don't need to send FLUSHSNAP message for it.
2990  */
2991 static int ceph_try_drop_cap_snap(struct ceph_inode_info *ci,
2992                                   struct ceph_cap_snap *capsnap)
2993 {
2994         if (!capsnap->need_flush &&
2995             !capsnap->writing && !capsnap->dirty_pages) {
2996                 dout("dropping cap_snap %p follows %llu\n",
2997                      capsnap, capsnap->follows);
2998                 BUG_ON(capsnap->cap_flush.tid > 0);
2999                 ceph_put_snap_context(capsnap->context);
3000                 if (!list_is_last(&capsnap->ci_item, &ci->i_cap_snaps))
3001                         ci->i_ceph_flags |= CEPH_I_FLUSH_SNAPS;
3002
3003                 list_del(&capsnap->ci_item);
3004                 ceph_put_cap_snap(capsnap);
3005                 return 1;
3006         }
3007         return 0;
3008 }
3009
3010 /*
3011  * Release cap refs.
3012  *
3013  * If we released the last ref on any given cap, call ceph_check_caps
3014  * to release (or schedule a release).
3015  *
3016  * If we are releasing a WR cap (from a sync write), finalize any affected
3017  * cap_snap, and wake up any waiters.
3018  */
3019 static void __ceph_put_cap_refs(struct ceph_inode_info *ci, int had,
3020                                 bool skip_checking_caps)
3021 {
3022         struct inode *inode = &ci->vfs_inode;
3023         int last = 0, put = 0, flushsnaps = 0, wake = 0;
3024
3025         spin_lock(&ci->i_ceph_lock);
3026         if (had & CEPH_CAP_PIN)
3027                 --ci->i_pin_ref;
3028         if (had & CEPH_CAP_FILE_RD)
3029                 if (--ci->i_rd_ref == 0)
3030                         last++;
3031         if (had & CEPH_CAP_FILE_CACHE)
3032                 if (--ci->i_rdcache_ref == 0)
3033                         last++;
3034         if (had & CEPH_CAP_FILE_EXCL)
3035                 if (--ci->i_fx_ref == 0)
3036                         last++;
3037         if (had & CEPH_CAP_FILE_BUFFER) {
3038                 if (--ci->i_wb_ref == 0) {
3039                         last++;
3040                         put++;
3041                 }
3042                 dout("put_cap_refs %p wb %d -> %d (?)\n",
3043                      inode, ci->i_wb_ref+1, ci->i_wb_ref);
3044         }
3045         if (had & CEPH_CAP_FILE_WR)
3046                 if (--ci->i_wr_ref == 0) {
3047                         last++;
3048                         if (__ceph_have_pending_cap_snap(ci)) {
3049                                 struct ceph_cap_snap *capsnap =
3050                                         list_last_entry(&ci->i_cap_snaps,
3051                                                         struct ceph_cap_snap,
3052                                                         ci_item);
3053                                 capsnap->writing = 0;
3054                                 if (ceph_try_drop_cap_snap(ci, capsnap))
3055                                         put++;
3056                                 else if (__ceph_finish_cap_snap(ci, capsnap))
3057                                         flushsnaps = 1;
3058                                 wake = 1;
3059                         }
3060                         if (ci->i_wrbuffer_ref_head == 0 &&
3061                             ci->i_dirty_caps == 0 &&
3062                             ci->i_flushing_caps == 0) {
3063                                 BUG_ON(!ci->i_head_snapc);
3064                                 ceph_put_snap_context(ci->i_head_snapc);
3065                                 ci->i_head_snapc = NULL;
3066                         }
3067                         /* see comment in __ceph_remove_cap() */
3068                         if (!__ceph_is_any_real_caps(ci) && ci->i_snap_realm)
3069                                 drop_inode_snap_realm(ci);
3070                 }
3071         spin_unlock(&ci->i_ceph_lock);
3072
3073         dout("put_cap_refs %p had %s%s%s\n", inode, ceph_cap_string(had),
3074              last ? " last" : "", put ? " put" : "");
3075
3076         if (last && !skip_checking_caps)
3077                 ceph_check_caps(ci, 0, NULL);
3078         else if (flushsnaps)
3079                 ceph_flush_snaps(ci, NULL);
3080         if (wake)
3081                 wake_up_all(&ci->i_cap_wq);
3082         while (put-- > 0)
3083                 iput(inode);
3084 }
3085
3086 void ceph_put_cap_refs(struct ceph_inode_info *ci, int had)
3087 {
3088         __ceph_put_cap_refs(ci, had, false);
3089 }
3090
3091 void ceph_put_cap_refs_no_check_caps(struct ceph_inode_info *ci, int had)
3092 {
3093         __ceph_put_cap_refs(ci, had, true);
3094 }
3095
3096 /*
3097  * Release @nr WRBUFFER refs on dirty pages for the given @snapc snap
3098  * context.  Adjust per-snap dirty page accounting as appropriate.
3099  * Once all dirty data for a cap_snap is flushed, flush snapped file
3100  * metadata back to the MDS.  If we dropped the last ref, call
3101  * ceph_check_caps.
3102  */
3103 void ceph_put_wrbuffer_cap_refs(struct ceph_inode_info *ci, int nr,
3104                                 struct ceph_snap_context *snapc)
3105 {
3106         struct inode *inode = &ci->vfs_inode;
3107         struct ceph_cap_snap *capsnap = NULL;
3108         int put = 0;
3109         bool last = false;
3110         bool found = false;
3111         bool flush_snaps = false;
3112         bool complete_capsnap = false;
3113
3114         spin_lock(&ci->i_ceph_lock);
3115         ci->i_wrbuffer_ref -= nr;
3116         if (ci->i_wrbuffer_ref == 0) {
3117                 last = true;
3118                 put++;
3119         }
3120
3121         if (ci->i_head_snapc == snapc) {
3122                 ci->i_wrbuffer_ref_head -= nr;
3123                 if (ci->i_wrbuffer_ref_head == 0 &&
3124                     ci->i_wr_ref == 0 &&
3125                     ci->i_dirty_caps == 0 &&
3126                     ci->i_flushing_caps == 0) {
3127                         BUG_ON(!ci->i_head_snapc);
3128                         ceph_put_snap_context(ci->i_head_snapc);
3129                         ci->i_head_snapc = NULL;
3130                 }
3131                 dout("put_wrbuffer_cap_refs on %p head %d/%d -> %d/%d %s\n",
3132                      inode,
3133                      ci->i_wrbuffer_ref+nr, ci->i_wrbuffer_ref_head+nr,
3134                      ci->i_wrbuffer_ref, ci->i_wrbuffer_ref_head,
3135                      last ? " LAST" : "");
3136         } else {
3137                 list_for_each_entry(capsnap, &ci->i_cap_snaps, ci_item) {
3138                         if (capsnap->context == snapc) {
3139                                 found = true;
3140                                 break;
3141                         }
3142                 }
3143                 BUG_ON(!found);
3144                 capsnap->dirty_pages -= nr;
3145                 if (capsnap->dirty_pages == 0) {
3146                         complete_capsnap = true;
3147                         if (!capsnap->writing) {
3148                                 if (ceph_try_drop_cap_snap(ci, capsnap)) {
3149                                         put++;
3150                                 } else {
3151                                         ci->i_ceph_flags |= CEPH_I_FLUSH_SNAPS;
3152                                         flush_snaps = true;
3153                                 }
3154                         }
3155                 }
3156                 dout("put_wrbuffer_cap_refs on %p cap_snap %p "
3157                      " snap %lld %d/%d -> %d/%d %s%s\n",
3158                      inode, capsnap, capsnap->context->seq,
3159                      ci->i_wrbuffer_ref+nr, capsnap->dirty_pages + nr,
3160                      ci->i_wrbuffer_ref, capsnap->dirty_pages,
3161                      last ? " (wrbuffer last)" : "",
3162                      complete_capsnap ? " (complete capsnap)" : "");
3163         }
3164
3165         spin_unlock(&ci->i_ceph_lock);
3166
3167         if (last) {
3168                 ceph_check_caps(ci, 0, NULL);
3169         } else if (flush_snaps) {
3170                 ceph_flush_snaps(ci, NULL);
3171         }
3172         if (complete_capsnap)
3173                 wake_up_all(&ci->i_cap_wq);
3174         while (put-- > 0) {
3175                 /* avoid calling iput_final() in osd dispatch threads */
3176                 ceph_async_iput(inode);
3177         }
3178 }
3179
3180 /*
3181  * Invalidate unlinked inode's aliases, so we can drop the inode ASAP.
3182  */
3183 static void invalidate_aliases(struct inode *inode)
3184 {
3185         struct dentry *dn, *prev = NULL;
3186
3187         dout("invalidate_aliases inode %p\n", inode);
3188         d_prune_aliases(inode);
3189         /*
3190          * For non-directory inode, d_find_alias() only returns
3191          * hashed dentry. After calling d_invalidate(), the
3192          * dentry becomes unhashed.
3193          *
3194          * For directory inode, d_find_alias() can return
3195          * unhashed dentry. But directory inode should have
3196          * one alias at most.
3197          */
3198         while ((dn = d_find_alias(inode))) {
3199                 if (dn == prev) {
3200                         dput(dn);
3201                         break;
3202                 }
3203                 d_invalidate(dn);
3204                 if (prev)
3205                         dput(prev);
3206                 prev = dn;
3207         }
3208         if (prev)
3209                 dput(prev);
3210 }
3211
3212 struct cap_extra_info {
3213         struct ceph_string *pool_ns;
3214         /* inline data */
3215         u64 inline_version;
3216         void *inline_data;
3217         u32 inline_len;
3218         /* dirstat */
3219         bool dirstat_valid;
3220         u64 nfiles;
3221         u64 nsubdirs;
3222         u64 change_attr;
3223         /* currently issued */
3224         int issued;
3225         struct timespec64 btime;
3226 };
3227
3228 /*
3229  * Handle a cap GRANT message from the MDS.  (Note that a GRANT may
3230  * actually be a revocation if it specifies a smaller cap set.)
3231  *
3232  * caller holds s_mutex and i_ceph_lock, we drop both.
3233  */
3234 static void handle_cap_grant(struct inode *inode,
3235                              struct ceph_mds_session *session,
3236                              struct ceph_cap *cap,
3237                              struct ceph_mds_caps *grant,
3238                              struct ceph_buffer *xattr_buf,
3239                              struct cap_extra_info *extra_info)
3240         __releases(ci->i_ceph_lock)
3241         __releases(session->s_mdsc->snap_rwsem)
3242 {
3243         struct ceph_inode_info *ci = ceph_inode(inode);
3244         int seq = le32_to_cpu(grant->seq);
3245         int newcaps = le32_to_cpu(grant->caps);
3246         int used, wanted, dirty;
3247         u64 size = le64_to_cpu(grant->size);
3248         u64 max_size = le64_to_cpu(grant->max_size);
3249         unsigned char check_caps = 0;
3250         bool was_stale = cap->cap_gen < session->s_cap_gen;
3251         bool wake = false;
3252         bool writeback = false;
3253         bool queue_trunc = false;
3254         bool queue_invalidate = false;
3255         bool deleted_inode = false;
3256         bool fill_inline = false;
3257
3258         dout("handle_cap_grant inode %p cap %p mds%d seq %d %s\n",
3259              inode, cap, session->s_mds, seq, ceph_cap_string(newcaps));
3260         dout(" size %llu max_size %llu, i_size %llu\n", size, max_size,
3261                 inode->i_size);
3262
3263
3264         /*
3265          * If CACHE is being revoked, and we have no dirty buffers,
3266          * try to invalidate (once).  (If there are dirty buffers, we
3267          * will invalidate _after_ writeback.)
3268          */
3269         if (S_ISREG(inode->i_mode) && /* don't invalidate readdir cache */
3270             ((cap->issued & ~newcaps) & CEPH_CAP_FILE_CACHE) &&
3271             (newcaps & CEPH_CAP_FILE_LAZYIO) == 0 &&
3272             !(ci->i_wrbuffer_ref || ci->i_wb_ref)) {
3273                 if (try_nonblocking_invalidate(inode)) {
3274                         /* there were locked pages.. invalidate later
3275                            in a separate thread. */
3276                         if (ci->i_rdcache_revoking != ci->i_rdcache_gen) {
3277                                 queue_invalidate = true;
3278                                 ci->i_rdcache_revoking = ci->i_rdcache_gen;
3279                         }
3280                 }
3281         }
3282
3283         if (was_stale)
3284                 cap->issued = cap->implemented = CEPH_CAP_PIN;
3285
3286         /*
3287          * auth mds of the inode changed. we received the cap export message,
3288          * but still haven't received the cap import message. handle_cap_export
3289          * updated the new auth MDS' cap.
3290          *
3291          * "ceph_seq_cmp(seq, cap->seq) <= 0" means we are processing a message
3292          * that was sent before the cap import message. So don't remove caps.
3293          */
3294         if (ceph_seq_cmp(seq, cap->seq) <= 0) {
3295                 WARN_ON(cap != ci->i_auth_cap);
3296                 WARN_ON(cap->cap_id != le64_to_cpu(grant->cap_id));
3297                 seq = cap->seq;
3298                 newcaps |= cap->issued;
3299         }
3300
3301         /* side effects now are allowed */
3302         cap->cap_gen = session->s_cap_gen;
3303         cap->seq = seq;
3304
3305         __check_cap_issue(ci, cap, newcaps);
3306
3307         inode_set_max_iversion_raw(inode, extra_info->change_attr);
3308
3309         if ((newcaps & CEPH_CAP_AUTH_SHARED) &&
3310             (extra_info->issued & CEPH_CAP_AUTH_EXCL) == 0) {
3311                 inode->i_mode = le32_to_cpu(grant->mode);
3312                 inode->i_uid = make_kuid(&init_user_ns, le32_to_cpu(grant->uid));
3313                 inode->i_gid = make_kgid(&init_user_ns, le32_to_cpu(grant->gid));
3314                 ci->i_btime = extra_info->btime;
3315                 dout("%p mode 0%o uid.gid %d.%d\n", inode, inode->i_mode,
3316                      from_kuid(&init_user_ns, inode->i_uid),
3317                      from_kgid(&init_user_ns, inode->i_gid));
3318         }
3319
3320         if ((newcaps & CEPH_CAP_LINK_SHARED) &&
3321             (extra_info->issued & CEPH_CAP_LINK_EXCL) == 0) {
3322                 set_nlink(inode, le32_to_cpu(grant->nlink));
3323                 if (inode->i_nlink == 0 &&
3324                     (newcaps & (CEPH_CAP_LINK_SHARED | CEPH_CAP_LINK_EXCL)))
3325                         deleted_inode = true;
3326         }
3327
3328         if ((extra_info->issued & CEPH_CAP_XATTR_EXCL) == 0 &&
3329             grant->xattr_len) {
3330                 int len = le32_to_cpu(grant->xattr_len);
3331                 u64 version = le64_to_cpu(grant->xattr_version);
3332
3333                 if (version > ci->i_xattrs.version) {
3334                         dout(" got new xattrs v%llu on %p len %d\n",
3335                              version, inode, len);
3336                         if (ci->i_xattrs.blob)
3337                                 ceph_buffer_put(ci->i_xattrs.blob);
3338                         ci->i_xattrs.blob = ceph_buffer_get(xattr_buf);
3339                         ci->i_xattrs.version = version;
3340                         ceph_forget_all_cached_acls(inode);
3341                         ceph_security_invalidate_secctx(inode);
3342                 }
3343         }
3344
3345         if (newcaps & CEPH_CAP_ANY_RD) {
3346                 struct timespec64 mtime, atime, ctime;
3347                 /* ctime/mtime/atime? */
3348                 ceph_decode_timespec64(&mtime, &grant->mtime);
3349                 ceph_decode_timespec64(&atime, &grant->atime);
3350                 ceph_decode_timespec64(&ctime, &grant->ctime);
3351                 ceph_fill_file_time(inode, extra_info->issued,
3352                                     le32_to_cpu(grant->time_warp_seq),
3353                                     &ctime, &mtime, &atime);
3354         }
3355
3356         if ((newcaps & CEPH_CAP_FILE_SHARED) && extra_info->dirstat_valid) {
3357                 ci->i_files = extra_info->nfiles;
3358                 ci->i_subdirs = extra_info->nsubdirs;
3359         }
3360
3361         if (newcaps & (CEPH_CAP_ANY_FILE_RD | CEPH_CAP_ANY_FILE_WR)) {
3362                 /* file layout may have changed */
3363                 s64 old_pool = ci->i_layout.pool_id;
3364                 struct ceph_string *old_ns;
3365
3366                 ceph_file_layout_from_legacy(&ci->i_layout, &grant->layout);
3367                 old_ns = rcu_dereference_protected(ci->i_layout.pool_ns,
3368                                         lockdep_is_held(&ci->i_ceph_lock));
3369                 rcu_assign_pointer(ci->i_layout.pool_ns, extra_info->pool_ns);
3370
3371                 if (ci->i_layout.pool_id != old_pool ||
3372                     extra_info->pool_ns != old_ns)
3373                         ci->i_ceph_flags &= ~CEPH_I_POOL_PERM;
3374
3375                 extra_info->pool_ns = old_ns;
3376
3377                 /* size/truncate_seq? */
3378                 queue_trunc = ceph_fill_file_size(inode, extra_info->issued,
3379                                         le32_to_cpu(grant->truncate_seq),
3380                                         le64_to_cpu(grant->truncate_size),
3381                                         size);
3382         }
3383
3384         if (ci->i_auth_cap == cap && (newcaps & CEPH_CAP_ANY_FILE_WR)) {
3385                 if (max_size != ci->i_max_size) {
3386                         dout("max_size %lld -> %llu\n",
3387                              ci->i_max_size, max_size);
3388                         ci->i_max_size = max_size;
3389                         if (max_size >= ci->i_wanted_max_size) {
3390                                 ci->i_wanted_max_size = 0;  /* reset */
3391                                 ci->i_requested_max_size = 0;
3392                         }
3393                         wake = true;
3394                 }
3395         }
3396
3397         /* check cap bits */
3398         wanted = __ceph_caps_wanted(ci);
3399         used = __ceph_caps_used(ci);
3400         dirty = __ceph_caps_dirty(ci);
3401         dout(" my wanted = %s, used = %s, dirty %s\n",
3402              ceph_cap_string(wanted),
3403              ceph_cap_string(used),
3404              ceph_cap_string(dirty));
3405
3406         if ((was_stale || le32_to_cpu(grant->op) == CEPH_CAP_OP_IMPORT) &&
3407             (wanted & ~(cap->mds_wanted | newcaps))) {
3408                 /*
3409                  * If mds is importing cap, prior cap messages that update
3410                  * 'wanted' may get dropped by mds (migrate seq mismatch).
3411                  *
3412                  * We don't send cap message to update 'wanted' if what we
3413                  * want are already issued. If mds revokes caps, cap message
3414                  * that releases caps also tells mds what we want. But if
3415                  * caps got revoked by mds forcedly (session stale). We may
3416                  * haven't told mds what we want.
3417                  */
3418                 check_caps = 1;
3419         }
3420
3421         /* revocation, grant, or no-op? */
3422         if (cap->issued & ~newcaps) {
3423                 int revoking = cap->issued & ~newcaps;
3424
3425                 dout("revocation: %s -> %s (revoking %s)\n",
3426                      ceph_cap_string(cap->issued),
3427                      ceph_cap_string(newcaps),
3428                      ceph_cap_string(revoking));
3429                 if (S_ISREG(inode->i_mode) &&
3430                     (revoking & used & CEPH_CAP_FILE_BUFFER))
3431                         writeback = true;  /* initiate writeback; will delay ack */
3432                 else if (queue_invalidate &&
3433                          revoking == CEPH_CAP_FILE_CACHE &&
3434                          (newcaps & CEPH_CAP_FILE_LAZYIO) == 0)
3435                         ; /* do nothing yet, invalidation will be queued */
3436                 else if (cap == ci->i_auth_cap)
3437                         check_caps = 1; /* check auth cap only */
3438                 else
3439                         check_caps = 2; /* check all caps */
3440                 cap->issued = newcaps;
3441                 cap->implemented |= newcaps;
3442         } else if (cap->issued == newcaps) {
3443                 dout("caps unchanged: %s -> %s\n",
3444                      ceph_cap_string(cap->issued), ceph_cap_string(newcaps));
3445         } else {
3446                 dout("grant: %s -> %s\n", ceph_cap_string(cap->issued),
3447                      ceph_cap_string(newcaps));
3448                 /* non-auth MDS is revoking the newly grant caps ? */
3449                 if (cap == ci->i_auth_cap &&
3450                     __ceph_caps_revoking_other(ci, cap, newcaps))
3451                     check_caps = 2;
3452
3453                 cap->issued = newcaps;
3454                 cap->implemented |= newcaps; /* add bits only, to
3455                                               * avoid stepping on a
3456                                               * pending revocation */
3457                 wake = true;
3458         }
3459         BUG_ON(cap->issued & ~cap->implemented);
3460
3461         if (extra_info->inline_version > 0 &&
3462             extra_info->inline_version >= ci->i_inline_version) {
3463                 ci->i_inline_version = extra_info->inline_version;
3464                 if (ci->i_inline_version != CEPH_INLINE_NONE &&
3465                     (newcaps & (CEPH_CAP_FILE_CACHE|CEPH_CAP_FILE_LAZYIO)))
3466                         fill_inline = true;
3467         }
3468
3469         if (ci->i_auth_cap == cap &&
3470             le32_to_cpu(grant->op) == CEPH_CAP_OP_IMPORT) {
3471                 if (newcaps & ~extra_info->issued)
3472                         wake = true;
3473
3474                 if (ci->i_requested_max_size > max_size ||
3475                     !(le32_to_cpu(grant->wanted) & CEPH_CAP_ANY_FILE_WR)) {
3476                         /* re-request max_size if necessary */
3477                         ci->i_requested_max_size = 0;
3478                         wake = true;
3479                 }
3480
3481                 ceph_kick_flushing_inode_caps(session, ci);
3482                 spin_unlock(&ci->i_ceph_lock);
3483                 up_read(&session->s_mdsc->snap_rwsem);
3484         } else {
3485                 spin_unlock(&ci->i_ceph_lock);
3486         }
3487
3488         if (fill_inline)
3489                 ceph_fill_inline_data(inode, NULL, extra_info->inline_data,
3490                                       extra_info->inline_len);
3491
3492         if (queue_trunc)
3493                 ceph_queue_vmtruncate(inode);
3494
3495         if (writeback)
3496                 /*
3497                  * queue inode for writeback: we can't actually call
3498                  * filemap_write_and_wait, etc. from message handler
3499                  * context.
3500                  */
3501                 ceph_queue_writeback(inode);
3502         if (queue_invalidate)
3503                 ceph_queue_invalidate(inode);
3504         if (deleted_inode)
3505                 invalidate_aliases(inode);
3506         if (wake)
3507                 wake_up_all(&ci->i_cap_wq);
3508
3509         if (check_caps == 1)
3510                 ceph_check_caps(ci, CHECK_CAPS_AUTHONLY | CHECK_CAPS_NOINVAL,
3511                                 session);
3512         else if (check_caps == 2)
3513                 ceph_check_caps(ci, CHECK_CAPS_NOINVAL, session);
3514         else
3515                 mutex_unlock(&session->s_mutex);
3516 }
3517
3518 /*
3519  * Handle FLUSH_ACK from MDS, indicating that metadata we sent to the
3520  * MDS has been safely committed.
3521  */
3522 static void handle_cap_flush_ack(struct inode *inode, u64 flush_tid,
3523                                  struct ceph_mds_caps *m,
3524                                  struct ceph_mds_session *session,
3525                                  struct ceph_cap *cap)
3526         __releases(ci->i_ceph_lock)
3527 {
3528         struct ceph_inode_info *ci = ceph_inode(inode);
3529         struct ceph_mds_client *mdsc = ceph_sb_to_client(inode->i_sb)->mdsc;
3530         struct ceph_cap_flush *cf, *tmp_cf;
3531         LIST_HEAD(to_remove);
3532         unsigned seq = le32_to_cpu(m->seq);
3533         int dirty = le32_to_cpu(m->dirty);
3534         int cleaned = 0;
3535         bool drop = false;
3536         bool wake_ci = false;
3537         bool wake_mdsc = false;
3538
3539         list_for_each_entry_safe(cf, tmp_cf, &ci->i_cap_flush_list, i_list) {
3540                 /* Is this the one that was flushed? */
3541                 if (cf->tid == flush_tid)
3542                         cleaned = cf->caps;
3543
3544                 /* Is this a capsnap? */
3545                 if (cf->caps == 0)
3546                         continue;
3547
3548                 if (cf->tid <= flush_tid) {
3549                         /*
3550                          * An earlier or current tid. The FLUSH_ACK should
3551                          * represent a superset of this flush's caps.
3552                          */
3553                         wake_ci |= __detach_cap_flush_from_ci(ci, cf);
3554                         list_add_tail(&cf->i_list, &to_remove);
3555                 } else {
3556                         /*
3557                          * This is a later one. Any caps in it are still dirty
3558                          * so don't count them as cleaned.
3559                          */
3560                         cleaned &= ~cf->caps;
3561                         if (!cleaned)
3562                                 break;
3563                 }
3564         }
3565
3566         dout("handle_cap_flush_ack inode %p mds%d seq %d on %s cleaned %s,"
3567              " flushing %s -> %s\n",
3568              inode, session->s_mds, seq, ceph_cap_string(dirty),
3569              ceph_cap_string(cleaned), ceph_cap_string(ci->i_flushing_caps),
3570              ceph_cap_string(ci->i_flushing_caps & ~cleaned));
3571
3572         if (list_empty(&to_remove) && !cleaned)
3573                 goto out;
3574
3575         ci->i_flushing_caps &= ~cleaned;
3576
3577         spin_lock(&mdsc->cap_dirty_lock);
3578
3579         list_for_each_entry(cf, &to_remove, i_list)
3580                 wake_mdsc |= __detach_cap_flush_from_mdsc(mdsc, cf);
3581
3582         if (ci->i_flushing_caps == 0) {
3583                 if (list_empty(&ci->i_cap_flush_list)) {
3584                         list_del_init(&ci->i_flushing_item);
3585                         if (!list_empty(&session->s_cap_flushing)) {
3586                                 dout(" mds%d still flushing cap on %p\n",
3587                                      session->s_mds,
3588                                      &list_first_entry(&session->s_cap_flushing,
3589                                                 struct ceph_inode_info,
3590                                                 i_flushing_item)->vfs_inode);
3591                         }
3592                 }
3593                 mdsc->num_cap_flushing--;
3594                 dout(" inode %p now !flushing\n", inode);
3595
3596                 if (ci->i_dirty_caps == 0) {
3597                         dout(" inode %p now clean\n", inode);
3598                         BUG_ON(!list_empty(&ci->i_dirty_item));
3599                         drop = true;
3600                         if (ci->i_wr_ref == 0 &&
3601                             ci->i_wrbuffer_ref_head == 0) {
3602                                 BUG_ON(!ci->i_head_snapc);
3603                                 ceph_put_snap_context(ci->i_head_snapc);
3604                                 ci->i_head_snapc = NULL;
3605                         }
3606                 } else {
3607                         BUG_ON(list_empty(&ci->i_dirty_item));
3608                 }
3609         }
3610         spin_unlock(&mdsc->cap_dirty_lock);
3611
3612 out:
3613         spin_unlock(&ci->i_ceph_lock);
3614
3615         while (!list_empty(&to_remove)) {
3616                 cf = list_first_entry(&to_remove,
3617                                       struct ceph_cap_flush, i_list);
3618                 list_del(&cf->i_list);
3619                 ceph_free_cap_flush(cf);
3620         }
3621
3622         if (wake_ci)
3623                 wake_up_all(&ci->i_cap_wq);
3624         if (wake_mdsc)
3625                 wake_up_all(&mdsc->cap_flushing_wq);
3626         if (drop)
3627                 iput(inode);
3628 }
3629
3630 /*
3631  * Handle FLUSHSNAP_ACK.  MDS has flushed snap data to disk and we can
3632  * throw away our cap_snap.
3633  *
3634  * Caller hold s_mutex.
3635  */
3636 static void handle_cap_flushsnap_ack(struct inode *inode, u64 flush_tid,
3637                                      struct ceph_mds_caps *m,
3638                                      struct ceph_mds_session *session)
3639 {
3640         struct ceph_inode_info *ci = ceph_inode(inode);
3641         struct ceph_mds_client *mdsc = ceph_sb_to_client(inode->i_sb)->mdsc;
3642         u64 follows = le64_to_cpu(m->snap_follows);
3643         struct ceph_cap_snap *capsnap;
3644         bool flushed = false;
3645         bool wake_ci = false;
3646         bool wake_mdsc = false;
3647
3648         dout("handle_cap_flushsnap_ack inode %p ci %p mds%d follows %lld\n",
3649              inode, ci, session->s_mds, follows);
3650
3651         spin_lock(&ci->i_ceph_lock);
3652         list_for_each_entry(capsnap, &ci->i_cap_snaps, ci_item) {
3653                 if (capsnap->follows == follows) {
3654                         if (capsnap->cap_flush.tid != flush_tid) {
3655                                 dout(" cap_snap %p follows %lld tid %lld !="
3656                                      " %lld\n", capsnap, follows,
3657                                      flush_tid, capsnap->cap_flush.tid);
3658                                 break;
3659                         }
3660                         flushed = true;
3661                         break;
3662                 } else {
3663                         dout(" skipping cap_snap %p follows %lld\n",
3664                              capsnap, capsnap->follows);
3665                 }
3666         }
3667         if (flushed) {
3668                 WARN_ON(capsnap->dirty_pages || capsnap->writing);
3669                 dout(" removing %p cap_snap %p follows %lld\n",
3670                      inode, capsnap, follows);
3671                 list_del(&capsnap->ci_item);
3672                 wake_ci |= __detach_cap_flush_from_ci(ci, &capsnap->cap_flush);
3673
3674                 spin_lock(&mdsc->cap_dirty_lock);
3675
3676                 if (list_empty(&ci->i_cap_flush_list))
3677                         list_del_init(&ci->i_flushing_item);
3678
3679                 wake_mdsc |= __detach_cap_flush_from_mdsc(mdsc,
3680                                                           &capsnap->cap_flush);
3681                 spin_unlock(&mdsc->cap_dirty_lock);
3682         }
3683         spin_unlock(&ci->i_ceph_lock);
3684         if (flushed) {
3685                 ceph_put_snap_context(capsnap->context);
3686                 ceph_put_cap_snap(capsnap);
3687                 if (wake_ci)
3688                         wake_up_all(&ci->i_cap_wq);
3689                 if (wake_mdsc)
3690                         wake_up_all(&mdsc->cap_flushing_wq);
3691                 iput(inode);
3692         }
3693 }
3694
3695 /*
3696  * Handle TRUNC from MDS, indicating file truncation.
3697  *
3698  * caller hold s_mutex.
3699  */
3700 static bool handle_cap_trunc(struct inode *inode,
3701                              struct ceph_mds_caps *trunc,
3702                              struct ceph_mds_session *session)
3703 {
3704         struct ceph_inode_info *ci = ceph_inode(inode);
3705         int mds = session->s_mds;
3706         int seq = le32_to_cpu(trunc->seq);
3707         u32 truncate_seq = le32_to_cpu(trunc->truncate_seq);
3708         u64 truncate_size = le64_to_cpu(trunc->truncate_size);
3709         u64 size = le64_to_cpu(trunc->size);
3710         int implemented = 0;
3711         int dirty = __ceph_caps_dirty(ci);
3712         int issued = __ceph_caps_issued(ceph_inode(inode), &implemented);
3713         bool queue_trunc = false;
3714
3715         lockdep_assert_held(&ci->i_ceph_lock);
3716
3717         issued |= implemented | dirty;
3718
3719         dout("handle_cap_trunc inode %p mds%d seq %d to %lld seq %d\n",
3720              inode, mds, seq, truncate_size, truncate_seq);
3721         queue_trunc = ceph_fill_file_size(inode, issued,
3722                                           truncate_seq, truncate_size, size);
3723         return queue_trunc;
3724 }
3725
3726 /*
3727  * Handle EXPORT from MDS.  Cap is being migrated _from_ this mds to a
3728  * different one.  If we are the most recent migration we've seen (as
3729  * indicated by mseq), make note of the migrating cap bits for the
3730  * duration (until we see the corresponding IMPORT).
3731  *
3732  * caller holds s_mutex
3733  */
3734 static void handle_cap_export(struct inode *inode, struct ceph_mds_caps *ex,
3735                               struct ceph_mds_cap_peer *ph,
3736                               struct ceph_mds_session *session)
3737 {
3738         struct ceph_mds_client *mdsc = ceph_inode_to_client(inode)->mdsc;
3739         struct ceph_mds_session *tsession = NULL;
3740         struct ceph_cap *cap, *tcap, *new_cap = NULL;
3741         struct ceph_inode_info *ci = ceph_inode(inode);
3742         u64 t_cap_id;
3743         unsigned mseq = le32_to_cpu(ex->migrate_seq);
3744         unsigned t_seq, t_mseq;
3745         int target, issued;
3746         int mds = session->s_mds;
3747
3748         if (ph) {
3749                 t_cap_id = le64_to_cpu(ph->cap_id);
3750                 t_seq = le32_to_cpu(ph->seq);
3751                 t_mseq = le32_to_cpu(ph->mseq);
3752                 target = le32_to_cpu(ph->mds);
3753         } else {
3754                 t_cap_id = t_seq = t_mseq = 0;
3755                 target = -1;
3756         }
3757
3758         dout("handle_cap_export inode %p ci %p mds%d mseq %d target %d\n",
3759              inode, ci, mds, mseq, target);
3760 retry:
3761         spin_lock(&ci->i_ceph_lock);
3762         cap = __get_cap_for_mds(ci, mds);
3763         if (!cap || cap->cap_id != le64_to_cpu(ex->cap_id))
3764                 goto out_unlock;
3765
3766         if (target < 0) {
3767                 __ceph_remove_cap(cap, false);
3768                 goto out_unlock;
3769         }
3770
3771         /*
3772          * now we know we haven't received the cap import message yet
3773          * because the exported cap still exist.
3774          */
3775
3776         issued = cap->issued;
3777         if (issued != cap->implemented)
3778                 pr_err_ratelimited("handle_cap_export: issued != implemented: "
3779                                 "ino (%llx.%llx) mds%d seq %d mseq %d "
3780                                 "issued %s implemented %s\n",
3781                                 ceph_vinop(inode), mds, cap->seq, cap->mseq,
3782                                 ceph_cap_string(issued),
3783                                 ceph_cap_string(cap->implemented));
3784
3785
3786         tcap = __get_cap_for_mds(ci, target);
3787         if (tcap) {
3788                 /* already have caps from the target */
3789                 if (tcap->cap_id == t_cap_id &&
3790                     ceph_seq_cmp(tcap->seq, t_seq) < 0) {
3791                         dout(" updating import cap %p mds%d\n", tcap, target);
3792                         tcap->cap_id = t_cap_id;
3793                         tcap->seq = t_seq - 1;
3794                         tcap->issue_seq = t_seq - 1;
3795                         tcap->issued |= issued;
3796                         tcap->implemented |= issued;
3797                         if (cap == ci->i_auth_cap) {
3798                                 ci->i_auth_cap = tcap;
3799                                 change_auth_cap_ses(ci, tcap->session);
3800                         }
3801                 }
3802                 __ceph_remove_cap(cap, false);
3803                 goto out_unlock;
3804         } else if (tsession) {
3805                 /* add placeholder for the export tagert */
3806                 int flag = (cap == ci->i_auth_cap) ? CEPH_CAP_FLAG_AUTH : 0;
3807                 tcap = new_cap;
3808                 ceph_add_cap(inode, tsession, t_cap_id, issued, 0,
3809                              t_seq - 1, t_mseq, (u64)-1, flag, &new_cap);
3810
3811                 if (!list_empty(&ci->i_cap_flush_list) &&
3812                     ci->i_auth_cap == tcap) {
3813                         spin_lock(&mdsc->cap_dirty_lock);
3814                         list_move_tail(&ci->i_flushing_item,
3815                                        &tcap->session->s_cap_flushing);
3816                         spin_unlock(&mdsc->cap_dirty_lock);
3817                 }
3818
3819                 __ceph_remove_cap(cap, false);
3820                 goto out_unlock;
3821         }
3822
3823         spin_unlock(&ci->i_ceph_lock);
3824         mutex_unlock(&session->s_mutex);
3825
3826         /* open target session */
3827         tsession = ceph_mdsc_open_export_target_session(mdsc, target);
3828         if (!IS_ERR(tsession)) {
3829                 if (mds > target) {
3830                         mutex_lock(&session->s_mutex);
3831                         mutex_lock_nested(&tsession->s_mutex,
3832                                           SINGLE_DEPTH_NESTING);
3833                 } else {
3834                         mutex_lock(&tsession->s_mutex);
3835                         mutex_lock_nested(&session->s_mutex,
3836                                           SINGLE_DEPTH_NESTING);
3837                 }
3838                 new_cap = ceph_get_cap(mdsc, NULL);
3839         } else {
3840                 WARN_ON(1);
3841                 tsession = NULL;
3842                 target = -1;
3843                 mutex_lock(&session->s_mutex);
3844         }
3845         goto retry;
3846
3847 out_unlock:
3848         spin_unlock(&ci->i_ceph_lock);
3849         mutex_unlock(&session->s_mutex);
3850         if (tsession) {
3851                 mutex_unlock(&tsession->s_mutex);
3852                 ceph_put_mds_session(tsession);
3853         }
3854         if (new_cap)
3855                 ceph_put_cap(mdsc, new_cap);
3856 }
3857
3858 /*
3859  * Handle cap IMPORT.
3860  *
3861  * caller holds s_mutex. acquires i_ceph_lock
3862  */
3863 static void handle_cap_import(struct ceph_mds_client *mdsc,
3864                               struct inode *inode, struct ceph_mds_caps *im,
3865                               struct ceph_mds_cap_peer *ph,
3866                               struct ceph_mds_session *session,
3867                               struct ceph_cap **target_cap, int *old_issued)
3868 {
3869         struct ceph_inode_info *ci = ceph_inode(inode);
3870         struct ceph_cap *cap, *ocap, *new_cap = NULL;
3871         int mds = session->s_mds;
3872         int issued;
3873         unsigned caps = le32_to_cpu(im->caps);
3874         unsigned wanted = le32_to_cpu(im->wanted);
3875         unsigned seq = le32_to_cpu(im->seq);
3876         unsigned mseq = le32_to_cpu(im->migrate_seq);
3877         u64 realmino = le64_to_cpu(im->realm);
3878         u64 cap_id = le64_to_cpu(im->cap_id);
3879         u64 p_cap_id;
3880         int peer;
3881
3882         if (ph) {
3883                 p_cap_id = le64_to_cpu(ph->cap_id);
3884                 peer = le32_to_cpu(ph->mds);
3885         } else {
3886                 p_cap_id = 0;
3887                 peer = -1;
3888         }
3889
3890         dout("handle_cap_import inode %p ci %p mds%d mseq %d peer %d\n",
3891              inode, ci, mds, mseq, peer);
3892 retry:
3893         cap = __get_cap_for_mds(ci, mds);
3894         if (!cap) {
3895                 if (!new_cap) {
3896                         spin_unlock(&ci->i_ceph_lock);
3897                         new_cap = ceph_get_cap(mdsc, NULL);
3898                         spin_lock(&ci->i_ceph_lock);
3899                         goto retry;
3900                 }
3901                 cap = new_cap;
3902         } else {
3903                 if (new_cap) {
3904                         ceph_put_cap(mdsc, new_cap);
3905                         new_cap = NULL;
3906                 }
3907         }
3908
3909         __ceph_caps_issued(ci, &issued);
3910         issued |= __ceph_caps_dirty(ci);
3911
3912         ceph_add_cap(inode, session, cap_id, caps, wanted, seq, mseq,
3913                      realmino, CEPH_CAP_FLAG_AUTH, &new_cap);
3914
3915         ocap = peer >= 0 ? __get_cap_for_mds(ci, peer) : NULL;
3916         if (ocap && ocap->cap_id == p_cap_id) {
3917                 dout(" remove export cap %p mds%d flags %d\n",
3918                      ocap, peer, ph->flags);
3919                 if ((ph->flags & CEPH_CAP_FLAG_AUTH) &&
3920                     (ocap->seq != le32_to_cpu(ph->seq) ||
3921                      ocap->mseq != le32_to_cpu(ph->mseq))) {
3922                         pr_err_ratelimited("handle_cap_import: "
3923                                         "mismatched seq/mseq: ino (%llx.%llx) "
3924                                         "mds%d seq %d mseq %d importer mds%d "
3925                                         "has peer seq %d mseq %d\n",
3926                                         ceph_vinop(inode), peer, ocap->seq,
3927                                         ocap->mseq, mds, le32_to_cpu(ph->seq),
3928                                         le32_to_cpu(ph->mseq));
3929                 }
3930                 __ceph_remove_cap(ocap, (ph->flags & CEPH_CAP_FLAG_RELEASE));
3931         }
3932
3933         *old_issued = issued;
3934         *target_cap = cap;
3935 }
3936
3937 /*
3938  * Handle a caps message from the MDS.
3939  *
3940  * Identify the appropriate session, inode, and call the right handler
3941  * based on the cap op.
3942  */
3943 void ceph_handle_caps(struct ceph_mds_session *session,
3944                       struct ceph_msg *msg)
3945 {
3946         struct ceph_mds_client *mdsc = session->s_mdsc;
3947         struct inode *inode;
3948         struct ceph_inode_info *ci;
3949         struct ceph_cap *cap;
3950         struct ceph_mds_caps *h;
3951         struct ceph_mds_cap_peer *peer = NULL;
3952         struct ceph_snap_realm *realm = NULL;
3953         int op;
3954         int msg_version = le16_to_cpu(msg->hdr.version);
3955         u32 seq, mseq;
3956         struct ceph_vino vino;
3957         void *snaptrace;
3958         size_t snaptrace_len;
3959         void *p, *end;
3960         struct cap_extra_info extra_info = {};
3961         bool queue_trunc;
3962
3963         dout("handle_caps from mds%d\n", session->s_mds);
3964
3965         /* decode */
3966         end = msg->front.iov_base + msg->front.iov_len;
3967         if (msg->front.iov_len < sizeof(*h))
3968                 goto bad;
3969         h = msg->front.iov_base;
3970         op = le32_to_cpu(h->op);
3971         vino.ino = le64_to_cpu(h->ino);
3972         vino.snap = CEPH_NOSNAP;
3973         seq = le32_to_cpu(h->seq);
3974         mseq = le32_to_cpu(h->migrate_seq);
3975
3976         snaptrace = h + 1;
3977         snaptrace_len = le32_to_cpu(h->snap_trace_len);
3978         p = snaptrace + snaptrace_len;
3979
3980         if (msg_version >= 2) {
3981                 u32 flock_len;
3982                 ceph_decode_32_safe(&p, end, flock_len, bad);
3983                 if (p + flock_len > end)
3984                         goto bad;
3985                 p += flock_len;
3986         }
3987
3988         if (msg_version >= 3) {
3989                 if (op == CEPH_CAP_OP_IMPORT) {
3990                         if (p + sizeof(*peer) > end)
3991                                 goto bad;
3992                         peer = p;
3993                         p += sizeof(*peer);
3994                 } else if (op == CEPH_CAP_OP_EXPORT) {
3995                         /* recorded in unused fields */
3996                         peer = (void *)&h->size;
3997                 }
3998         }
3999
4000         if (msg_version >= 4) {
4001                 ceph_decode_64_safe(&p, end, extra_info.inline_version, bad);
4002                 ceph_decode_32_safe(&p, end, extra_info.inline_len, bad);
4003                 if (p + extra_info.inline_len > end)
4004                         goto bad;
4005                 extra_info.inline_data = p;
4006                 p += extra_info.inline_len;
4007         }
4008
4009         if (msg_version >= 5) {
4010                 struct ceph_osd_client  *osdc = &mdsc->fsc->client->osdc;
4011                 u32                     epoch_barrier;
4012
4013                 ceph_decode_32_safe(&p, end, epoch_barrier, bad);
4014                 ceph_osdc_update_epoch_barrier(osdc, epoch_barrier);
4015         }
4016
4017         if (msg_version >= 8) {
4018                 u64 flush_tid;
4019                 u32 caller_uid, caller_gid;
4020                 u32 pool_ns_len;
4021
4022                 /* version >= 6 */
4023                 ceph_decode_64_safe(&p, end, flush_tid, bad);
4024                 /* version >= 7 */
4025                 ceph_decode_32_safe(&p, end, caller_uid, bad);
4026                 ceph_decode_32_safe(&p, end, caller_gid, bad);
4027                 /* version >= 8 */
4028                 ceph_decode_32_safe(&p, end, pool_ns_len, bad);
4029                 if (pool_ns_len > 0) {
4030                         ceph_decode_need(&p, end, pool_ns_len, bad);
4031                         extra_info.pool_ns =
4032                                 ceph_find_or_create_string(p, pool_ns_len);
4033                         p += pool_ns_len;
4034                 }
4035         }
4036
4037         if (msg_version >= 9) {
4038                 struct ceph_timespec *btime;
4039
4040                 if (p + sizeof(*btime) > end)
4041                         goto bad;
4042                 btime = p;
4043                 ceph_decode_timespec64(&extra_info.btime, btime);
4044                 p += sizeof(*btime);
4045                 ceph_decode_64_safe(&p, end, extra_info.change_attr, bad);
4046         }
4047
4048         if (msg_version >= 11) {
4049                 u32 flags;
4050                 /* version >= 10 */
4051                 ceph_decode_32_safe(&p, end, flags, bad);
4052                 /* version >= 11 */
4053                 extra_info.dirstat_valid = true;
4054                 ceph_decode_64_safe(&p, end, extra_info.nfiles, bad);
4055                 ceph_decode_64_safe(&p, end, extra_info.nsubdirs, bad);
4056         }
4057
4058         /* lookup ino */
4059         inode = ceph_find_inode(mdsc->fsc->sb, vino);
4060         ci = ceph_inode(inode);
4061         dout(" op %s ino %llx.%llx inode %p\n", ceph_cap_op_name(op), vino.ino,
4062              vino.snap, inode);
4063
4064         mutex_lock(&session->s_mutex);
4065         session->s_seq++;
4066         dout(" mds%d seq %lld cap seq %u\n", session->s_mds, session->s_seq,
4067              (unsigned)seq);
4068
4069         if (!inode) {
4070                 dout(" i don't have ino %llx\n", vino.ino);
4071
4072                 if (op == CEPH_CAP_OP_IMPORT) {
4073                         cap = ceph_get_cap(mdsc, NULL);
4074                         cap->cap_ino = vino.ino;
4075                         cap->queue_release = 1;
4076                         cap->cap_id = le64_to_cpu(h->cap_id);
4077                         cap->mseq = mseq;
4078                         cap->seq = seq;
4079                         cap->issue_seq = seq;
4080                         spin_lock(&session->s_cap_lock);
4081                         __ceph_queue_cap_release(session, cap);
4082                         spin_unlock(&session->s_cap_lock);
4083                 }
4084                 goto flush_cap_releases;
4085         }
4086
4087         /* these will work even if we don't have a cap yet */
4088         switch (op) {
4089         case CEPH_CAP_OP_FLUSHSNAP_ACK:
4090                 handle_cap_flushsnap_ack(inode, le64_to_cpu(msg->hdr.tid),
4091                                          h, session);
4092                 goto done;
4093
4094         case CEPH_CAP_OP_EXPORT:
4095                 handle_cap_export(inode, h, peer, session);
4096                 goto done_unlocked;
4097
4098         case CEPH_CAP_OP_IMPORT:
4099                 realm = NULL;
4100                 if (snaptrace_len) {
4101                         down_write(&mdsc->snap_rwsem);
4102                         ceph_update_snap_trace(mdsc, snaptrace,
4103                                                snaptrace + snaptrace_len,
4104                                                false, &realm);
4105                         downgrade_write(&mdsc->snap_rwsem);
4106                 } else {
4107                         down_read(&mdsc->snap_rwsem);
4108                 }
4109                 spin_lock(&ci->i_ceph_lock);
4110                 handle_cap_import(mdsc, inode, h, peer, session,
4111                                   &cap, &extra_info.issued);
4112                 handle_cap_grant(inode, session, cap,
4113                                  h, msg->middle, &extra_info);
4114                 if (realm)
4115                         ceph_put_snap_realm(mdsc, realm);
4116                 goto done_unlocked;
4117         }
4118
4119         /* the rest require a cap */
4120         spin_lock(&ci->i_ceph_lock);
4121         cap = __get_cap_for_mds(ceph_inode(inode), session->s_mds);
4122         if (!cap) {
4123                 dout(" no cap on %p ino %llx.%llx from mds%d\n",
4124                      inode, ceph_ino(inode), ceph_snap(inode),
4125                      session->s_mds);
4126                 spin_unlock(&ci->i_ceph_lock);
4127                 goto flush_cap_releases;
4128         }
4129
4130         /* note that each of these drops i_ceph_lock for us */
4131         switch (op) {
4132         case CEPH_CAP_OP_REVOKE:
4133         case CEPH_CAP_OP_GRANT:
4134                 __ceph_caps_issued(ci, &extra_info.issued);
4135                 extra_info.issued |= __ceph_caps_dirty(ci);
4136                 handle_cap_grant(inode, session, cap,
4137                                  h, msg->middle, &extra_info);
4138                 goto done_unlocked;
4139
4140         case CEPH_CAP_OP_FLUSH_ACK:
4141                 handle_cap_flush_ack(inode, le64_to_cpu(msg->hdr.tid),
4142                                      h, session, cap);
4143                 break;
4144
4145         case CEPH_CAP_OP_TRUNC:
4146                 queue_trunc = handle_cap_trunc(inode, h, session);
4147                 spin_unlock(&ci->i_ceph_lock);
4148                 if (queue_trunc)
4149                         ceph_queue_vmtruncate(inode);
4150                 break;
4151
4152         default:
4153                 spin_unlock(&ci->i_ceph_lock);
4154                 pr_err("ceph_handle_caps: unknown cap op %d %s\n", op,
4155                        ceph_cap_op_name(op));
4156         }
4157
4158 done:
4159         mutex_unlock(&session->s_mutex);
4160 done_unlocked:
4161         ceph_put_string(extra_info.pool_ns);
4162         /* avoid calling iput_final() in mds dispatch threads */
4163         ceph_async_iput(inode);
4164         return;
4165
4166 flush_cap_releases:
4167         /*
4168          * send any cap release message to try to move things
4169          * along for the mds (who clearly thinks we still have this
4170          * cap).
4171          */
4172         ceph_flush_cap_releases(mdsc, session);
4173         goto done;
4174
4175 bad:
4176         pr_err("ceph_handle_caps: corrupt message\n");
4177         ceph_msg_dump(msg);
4178         return;
4179 }
4180
4181 /*
4182  * Delayed work handler to process end of delayed cap release LRU list.
4183  */
4184 void ceph_check_delayed_caps(struct ceph_mds_client *mdsc)
4185 {
4186         struct inode *inode;
4187         struct ceph_inode_info *ci;
4188
4189         dout("check_delayed_caps\n");
4190         while (1) {
4191                 spin_lock(&mdsc->cap_delay_lock);
4192                 if (list_empty(&mdsc->cap_delay_list))
4193                         break;
4194                 ci = list_first_entry(&mdsc->cap_delay_list,
4195                                       struct ceph_inode_info,
4196                                       i_cap_delay_list);
4197                 if ((ci->i_ceph_flags & CEPH_I_FLUSH) == 0 &&
4198                     time_before(jiffies, ci->i_hold_caps_max))
4199                         break;
4200                 list_del_init(&ci->i_cap_delay_list);
4201
4202                 inode = igrab(&ci->vfs_inode);
4203                 spin_unlock(&mdsc->cap_delay_lock);
4204
4205                 if (inode) {
4206                         dout("check_delayed_caps on %p\n", inode);
4207                         ceph_check_caps(ci, 0, NULL);
4208                         /* avoid calling iput_final() in tick thread */
4209                         ceph_async_iput(inode);
4210                 }
4211         }
4212         spin_unlock(&mdsc->cap_delay_lock);
4213 }
4214
4215 /*
4216  * Flush all dirty caps to the mds
4217  */
4218 static void flush_dirty_session_caps(struct ceph_mds_session *s)
4219 {
4220         struct ceph_mds_client *mdsc = s->s_mdsc;
4221         struct ceph_inode_info *ci;
4222         struct inode *inode;
4223
4224         dout("flush_dirty_caps\n");
4225         spin_lock(&mdsc->cap_dirty_lock);
4226         while (!list_empty(&s->s_cap_dirty)) {
4227                 ci = list_first_entry(&s->s_cap_dirty, struct ceph_inode_info,
4228                                       i_dirty_item);
4229                 inode = &ci->vfs_inode;
4230                 ihold(inode);
4231                 dout("flush_dirty_caps %p\n", inode);
4232                 spin_unlock(&mdsc->cap_dirty_lock);
4233                 ceph_check_caps(ci, CHECK_CAPS_FLUSH, NULL);
4234                 iput(inode);
4235                 spin_lock(&mdsc->cap_dirty_lock);
4236         }
4237         spin_unlock(&mdsc->cap_dirty_lock);
4238         dout("flush_dirty_caps done\n");
4239 }
4240
4241 static void iterate_sessions(struct ceph_mds_client *mdsc,
4242                              void (*cb)(struct ceph_mds_session *))
4243 {
4244         int mds;
4245
4246         mutex_lock(&mdsc->mutex);
4247         for (mds = 0; mds < mdsc->max_sessions; ++mds) {
4248                 struct ceph_mds_session *s;
4249
4250                 if (!mdsc->sessions[mds])
4251                         continue;
4252
4253                 s = ceph_get_mds_session(mdsc->sessions[mds]);
4254                 if (!s)
4255                         continue;
4256
4257                 mutex_unlock(&mdsc->mutex);
4258                 cb(s);
4259                 ceph_put_mds_session(s);
4260                 mutex_lock(&mdsc->mutex);
4261         }
4262         mutex_unlock(&mdsc->mutex);
4263 }
4264
4265 void ceph_flush_dirty_caps(struct ceph_mds_client *mdsc)
4266 {
4267         iterate_sessions(mdsc, flush_dirty_session_caps);
4268 }
4269
4270 void __ceph_touch_fmode(struct ceph_inode_info *ci,
4271                         struct ceph_mds_client *mdsc, int fmode)
4272 {
4273         unsigned long now = jiffies;
4274         if (fmode & CEPH_FILE_MODE_RD)
4275                 ci->i_last_rd = now;
4276         if (fmode & CEPH_FILE_MODE_WR)
4277                 ci->i_last_wr = now;
4278         /* queue periodic check */
4279         if (fmode &&
4280             __ceph_is_any_real_caps(ci) &&
4281             list_empty(&ci->i_cap_delay_list))
4282                 __cap_delay_requeue(mdsc, ci);
4283 }
4284
4285 void ceph_get_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                         ci->i_nr_by_mode[i] += count;
4293         }
4294         spin_unlock(&ci->i_ceph_lock);
4295 }
4296
4297 /*
4298  * Drop open file reference.  If we were the last open file,
4299  * we may need to release capabilities to the MDS (or schedule
4300  * their delayed release).
4301  */
4302 void ceph_put_fmode(struct ceph_inode_info *ci, int fmode, int count)
4303 {
4304         int i;
4305         int bits = (fmode << 1) | 1;
4306         spin_lock(&ci->i_ceph_lock);
4307         for (i = 0; i < CEPH_FILE_MODE_BITS; i++) {
4308                 if (bits & (1 << i)) {
4309                         BUG_ON(ci->i_nr_by_mode[i] < count);
4310                         ci->i_nr_by_mode[i] -= count;
4311                 }
4312         }
4313         spin_unlock(&ci->i_ceph_lock);
4314 }
4315
4316 /*
4317  * For a soon-to-be unlinked file, drop the LINK caps. If it
4318  * looks like the link count will hit 0, drop any other caps (other
4319  * than PIN) we don't specifically want (due to the file still being
4320  * open).
4321  */
4322 int ceph_drop_caps_for_unlink(struct inode *inode)
4323 {
4324         struct ceph_inode_info *ci = ceph_inode(inode);
4325         int drop = CEPH_CAP_LINK_SHARED | CEPH_CAP_LINK_EXCL;
4326
4327         spin_lock(&ci->i_ceph_lock);
4328         if (inode->i_nlink == 1) {
4329                 drop |= ~(__ceph_caps_wanted(ci) | CEPH_CAP_PIN);
4330
4331                 if (__ceph_caps_dirty(ci)) {
4332                         struct ceph_mds_client *mdsc =
4333                                 ceph_inode_to_client(inode)->mdsc;
4334                         __cap_delay_requeue_front(mdsc, ci);
4335                 }
4336         }
4337         spin_unlock(&ci->i_ceph_lock);
4338         return drop;
4339 }
4340
4341 /*
4342  * Helpers for embedding cap and dentry lease releases into mds
4343  * requests.
4344  *
4345  * @force is used by dentry_release (below) to force inclusion of a
4346  * record for the directory inode, even when there aren't any caps to
4347  * drop.
4348  */
4349 int ceph_encode_inode_release(void **p, struct inode *inode,
4350                               int mds, int drop, int unless, int force)
4351 {
4352         struct ceph_inode_info *ci = ceph_inode(inode);
4353         struct ceph_cap *cap;
4354         struct ceph_mds_request_release *rel = *p;
4355         int used, dirty;
4356         int ret = 0;
4357
4358         spin_lock(&ci->i_ceph_lock);
4359         used = __ceph_caps_used(ci);
4360         dirty = __ceph_caps_dirty(ci);
4361
4362         dout("encode_inode_release %p mds%d used|dirty %s drop %s unless %s\n",
4363              inode, mds, ceph_cap_string(used|dirty), ceph_cap_string(drop),
4364              ceph_cap_string(unless));
4365
4366         /* only drop unused, clean caps */
4367         drop &= ~(used | dirty);
4368
4369         cap = __get_cap_for_mds(ci, mds);
4370         if (cap && __cap_is_valid(cap)) {
4371                 unless &= cap->issued;
4372                 if (unless) {
4373                         if (unless & CEPH_CAP_AUTH_EXCL)
4374                                 drop &= ~CEPH_CAP_AUTH_SHARED;
4375                         if (unless & CEPH_CAP_LINK_EXCL)
4376                                 drop &= ~CEPH_CAP_LINK_SHARED;
4377                         if (unless & CEPH_CAP_XATTR_EXCL)
4378                                 drop &= ~CEPH_CAP_XATTR_SHARED;
4379                         if (unless & CEPH_CAP_FILE_EXCL)
4380                                 drop &= ~CEPH_CAP_FILE_SHARED;
4381                 }
4382
4383                 if (force || (cap->issued & drop)) {
4384                         if (cap->issued & drop) {
4385                                 int wanted = __ceph_caps_wanted(ci);
4386                                 dout("encode_inode_release %p cap %p "
4387                                      "%s -> %s, wanted %s -> %s\n", inode, cap,
4388                                      ceph_cap_string(cap->issued),
4389                                      ceph_cap_string(cap->issued & ~drop),
4390                                      ceph_cap_string(cap->mds_wanted),
4391                                      ceph_cap_string(wanted));
4392
4393                                 cap->issued &= ~drop;
4394                                 cap->implemented &= ~drop;
4395                                 cap->mds_wanted = wanted;
4396                                 if (cap == ci->i_auth_cap &&
4397                                     !(wanted & CEPH_CAP_ANY_FILE_WR))
4398                                         ci->i_requested_max_size = 0;
4399                         } else {
4400                                 dout("encode_inode_release %p cap %p %s"
4401                                      " (force)\n", inode, cap,
4402                                      ceph_cap_string(cap->issued));
4403                         }
4404
4405                         rel->ino = cpu_to_le64(ceph_ino(inode));
4406                         rel->cap_id = cpu_to_le64(cap->cap_id);
4407                         rel->seq = cpu_to_le32(cap->seq);
4408                         rel->issue_seq = cpu_to_le32(cap->issue_seq);
4409                         rel->mseq = cpu_to_le32(cap->mseq);
4410                         rel->caps = cpu_to_le32(cap->implemented);
4411                         rel->wanted = cpu_to_le32(cap->mds_wanted);
4412                         rel->dname_len = 0;
4413                         rel->dname_seq = 0;
4414                         *p += sizeof(*rel);
4415                         ret = 1;
4416                 } else {
4417                         dout("encode_inode_release %p cap %p %s (noop)\n",
4418                              inode, cap, ceph_cap_string(cap->issued));
4419                 }
4420         }
4421         spin_unlock(&ci->i_ceph_lock);
4422         return ret;
4423 }
4424
4425 int ceph_encode_dentry_release(void **p, struct dentry *dentry,
4426                                struct inode *dir,
4427                                int mds, int drop, int unless)
4428 {
4429         struct dentry *parent = NULL;
4430         struct ceph_mds_request_release *rel = *p;
4431         struct ceph_dentry_info *di = ceph_dentry(dentry);
4432         int force = 0;
4433         int ret;
4434
4435         /*
4436          * force an record for the directory caps if we have a dentry lease.
4437          * this is racy (can't take i_ceph_lock and d_lock together), but it
4438          * doesn't have to be perfect; the mds will revoke anything we don't
4439          * release.
4440          */
4441         spin_lock(&dentry->d_lock);
4442         if (di->lease_session && di->lease_session->s_mds == mds)
4443                 force = 1;
4444         if (!dir) {
4445                 parent = dget(dentry->d_parent);
4446                 dir = d_inode(parent);
4447         }
4448         spin_unlock(&dentry->d_lock);
4449
4450         ret = ceph_encode_inode_release(p, dir, mds, drop, unless, force);
4451         dput(parent);
4452
4453         spin_lock(&dentry->d_lock);
4454         if (ret && di->lease_session && di->lease_session->s_mds == mds) {
4455                 dout("encode_dentry_release %p mds%d seq %d\n",
4456                      dentry, mds, (int)di->lease_seq);
4457                 rel->dname_len = cpu_to_le32(dentry->d_name.len);
4458                 memcpy(*p, dentry->d_name.name, dentry->d_name.len);
4459                 *p += dentry->d_name.len;
4460                 rel->dname_seq = cpu_to_le32(di->lease_seq);
4461                 __ceph_mdsc_drop_dentry_lease(dentry);
4462         }
4463         spin_unlock(&dentry->d_lock);
4464         return ret;
4465 }