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