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