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