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