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