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