]> git.karo-electronics.de Git - mv-sheeva.git/blob - fs/ceph/caps.c
ceph: skip if no auth cap in flush_snaps
[mv-sheeva.git] / fs / ceph / caps.c
1 #include "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 "decode.h"
13 #include "messenger.h"
14
15 /*
16  * Capability management
17  *
18  * The Ceph metadata servers control client access to inode metadata
19  * and file data by issuing capabilities, granting clients permission
20  * to read and/or write both inode field and file data to OSDs
21  * (storage nodes).  Each capability consists of a set of bits
22  * indicating which operations are allowed.
23  *
24  * If the client holds a *_SHARED cap, the client has a coherent value
25  * that can be safely read from the cached inode.
26  *
27  * In the case of a *_EXCL (exclusive) or FILE_WR capabilities, the
28  * client is allowed to change inode attributes (e.g., file size,
29  * mtime), note its dirty state in the ceph_cap, and asynchronously
30  * flush that metadata change to the MDS.
31  *
32  * In the event of a conflicting operation (perhaps by another
33  * client), the MDS will revoke the conflicting client capabilities.
34  *
35  * In order for a client to cache an inode, it must hold a capability
36  * with at least one MDS server.  When inodes are released, release
37  * notifications are batched and periodically sent en masse to the MDS
38  * cluster to release server state.
39  */
40
41
42 /*
43  * Generate readable cap strings for debugging output.
44  */
45 #define MAX_CAP_STR 20
46 static char cap_str[MAX_CAP_STR][40];
47 static DEFINE_SPINLOCK(cap_str_lock);
48 static int last_cap_str;
49
50 static char *gcap_string(char *s, int c)
51 {
52         if (c & CEPH_CAP_GSHARED)
53                 *s++ = 's';
54         if (c & CEPH_CAP_GEXCL)
55                 *s++ = 'x';
56         if (c & CEPH_CAP_GCACHE)
57                 *s++ = 'c';
58         if (c & CEPH_CAP_GRD)
59                 *s++ = 'r';
60         if (c & CEPH_CAP_GWR)
61                 *s++ = 'w';
62         if (c & CEPH_CAP_GBUFFER)
63                 *s++ = 'b';
64         if (c & CEPH_CAP_GLAZYIO)
65                 *s++ = 'l';
66         return s;
67 }
68
69 const char *ceph_cap_string(int caps)
70 {
71         int i;
72         char *s;
73         int c;
74
75         spin_lock(&cap_str_lock);
76         i = last_cap_str++;
77         if (last_cap_str == MAX_CAP_STR)
78                 last_cap_str = 0;
79         spin_unlock(&cap_str_lock);
80
81         s = cap_str[i];
82
83         if (caps & CEPH_CAP_PIN)
84                 *s++ = 'p';
85
86         c = (caps >> CEPH_CAP_SAUTH) & 3;
87         if (c) {
88                 *s++ = 'A';
89                 s = gcap_string(s, c);
90         }
91
92         c = (caps >> CEPH_CAP_SLINK) & 3;
93         if (c) {
94                 *s++ = 'L';
95                 s = gcap_string(s, c);
96         }
97
98         c = (caps >> CEPH_CAP_SXATTR) & 3;
99         if (c) {
100                 *s++ = 'X';
101                 s = gcap_string(s, c);
102         }
103
104         c = caps >> CEPH_CAP_SFILE;
105         if (c) {
106                 *s++ = 'F';
107                 s = gcap_string(s, c);
108         }
109
110         if (s == cap_str[i])
111                 *s++ = '-';
112         *s = 0;
113         return cap_str[i];
114 }
115
116 /*
117  * Cap reservations
118  *
119  * Maintain a global pool of preallocated struct ceph_caps, referenced
120  * by struct ceph_caps_reservations.  This ensures that we preallocate
121  * memory needed to successfully process an MDS response.  (If an MDS
122  * sends us cap information and we fail to process it, we will have
123  * problems due to the client and MDS being out of sync.)
124  *
125  * Reservations are 'owned' by a ceph_cap_reservation context.
126  */
127 static spinlock_t caps_list_lock;
128 static struct list_head caps_list;  /* unused (reserved or unreserved) */
129 static int caps_total_count;        /* total caps allocated */
130 static int caps_use_count;          /* in use */
131 static int caps_reserve_count;      /* unused, reserved */
132 static int caps_avail_count;        /* unused, unreserved */
133 static int caps_min_count;          /* keep at least this many (unreserved) */
134
135 void __init ceph_caps_init(void)
136 {
137         INIT_LIST_HEAD(&caps_list);
138         spin_lock_init(&caps_list_lock);
139 }
140
141 void ceph_caps_finalize(void)
142 {
143         struct ceph_cap *cap;
144
145         spin_lock(&caps_list_lock);
146         while (!list_empty(&caps_list)) {
147                 cap = list_first_entry(&caps_list, struct ceph_cap, caps_item);
148                 list_del(&cap->caps_item);
149                 kmem_cache_free(ceph_cap_cachep, cap);
150         }
151         caps_total_count = 0;
152         caps_avail_count = 0;
153         caps_use_count = 0;
154         caps_reserve_count = 0;
155         caps_min_count = 0;
156         spin_unlock(&caps_list_lock);
157 }
158
159 void ceph_adjust_min_caps(int delta)
160 {
161         spin_lock(&caps_list_lock);
162         caps_min_count += delta;
163         BUG_ON(caps_min_count < 0);
164         spin_unlock(&caps_list_lock);
165 }
166
167 int ceph_reserve_caps(struct ceph_cap_reservation *ctx, int need)
168 {
169         int i;
170         struct ceph_cap *cap;
171         int have;
172         int alloc = 0;
173         LIST_HEAD(newcaps);
174         int ret = 0;
175
176         dout("reserve caps ctx=%p need=%d\n", ctx, need);
177
178         /* first reserve any caps that are already allocated */
179         spin_lock(&caps_list_lock);
180         if (caps_avail_count >= need)
181                 have = need;
182         else
183                 have = caps_avail_count;
184         caps_avail_count -= have;
185         caps_reserve_count += have;
186         BUG_ON(caps_total_count != caps_use_count + caps_reserve_count +
187                caps_avail_count);
188         spin_unlock(&caps_list_lock);
189
190         for (i = have; i < need; i++) {
191                 cap = kmem_cache_alloc(ceph_cap_cachep, GFP_NOFS);
192                 if (!cap) {
193                         ret = -ENOMEM;
194                         goto out_alloc_count;
195                 }
196                 list_add(&cap->caps_item, &newcaps);
197                 alloc++;
198         }
199         BUG_ON(have + alloc != need);
200
201         spin_lock(&caps_list_lock);
202         caps_total_count += alloc;
203         caps_reserve_count += alloc;
204         list_splice(&newcaps, &caps_list);
205
206         BUG_ON(caps_total_count != caps_use_count + caps_reserve_count +
207                caps_avail_count);
208         spin_unlock(&caps_list_lock);
209
210         ctx->count = need;
211         dout("reserve caps ctx=%p %d = %d used + %d resv + %d avail\n",
212              ctx, caps_total_count, caps_use_count, caps_reserve_count,
213              caps_avail_count);
214         return 0;
215
216 out_alloc_count:
217         /* we didn't manage to reserve as much as we needed */
218         pr_warning("reserve caps ctx=%p ENOMEM need=%d got=%d\n",
219                    ctx, need, have);
220         return ret;
221 }
222
223 int ceph_unreserve_caps(struct ceph_cap_reservation *ctx)
224 {
225         dout("unreserve caps ctx=%p count=%d\n", ctx, ctx->count);
226         if (ctx->count) {
227                 spin_lock(&caps_list_lock);
228                 BUG_ON(caps_reserve_count < ctx->count);
229                 caps_reserve_count -= ctx->count;
230                 caps_avail_count += ctx->count;
231                 ctx->count = 0;
232                 dout("unreserve caps %d = %d used + %d resv + %d avail\n",
233                      caps_total_count, caps_use_count, caps_reserve_count,
234                      caps_avail_count);
235                 BUG_ON(caps_total_count != caps_use_count + caps_reserve_count +
236                        caps_avail_count);
237                 spin_unlock(&caps_list_lock);
238         }
239         return 0;
240 }
241
242 static struct ceph_cap *get_cap(struct ceph_cap_reservation *ctx)
243 {
244         struct ceph_cap *cap = NULL;
245
246         /* temporary, until we do something about cap import/export */
247         if (!ctx) {
248                 cap = kmem_cache_alloc(ceph_cap_cachep, GFP_NOFS);
249                 if (cap) {
250                         caps_use_count++;
251                         caps_total_count++;
252                 }
253                 return cap;
254         }
255
256         spin_lock(&caps_list_lock);
257         dout("get_cap ctx=%p (%d) %d = %d used + %d resv + %d avail\n",
258              ctx, ctx->count, caps_total_count, caps_use_count,
259              caps_reserve_count, caps_avail_count);
260         BUG_ON(!ctx->count);
261         BUG_ON(ctx->count > caps_reserve_count);
262         BUG_ON(list_empty(&caps_list));
263
264         ctx->count--;
265         caps_reserve_count--;
266         caps_use_count++;
267
268         cap = list_first_entry(&caps_list, struct ceph_cap, caps_item);
269         list_del(&cap->caps_item);
270
271         BUG_ON(caps_total_count != caps_use_count + caps_reserve_count +
272                caps_avail_count);
273         spin_unlock(&caps_list_lock);
274         return cap;
275 }
276
277 void ceph_put_cap(struct ceph_cap *cap)
278 {
279         spin_lock(&caps_list_lock);
280         dout("put_cap %p %d = %d used + %d resv + %d avail\n",
281              cap, caps_total_count, caps_use_count,
282              caps_reserve_count, caps_avail_count);
283         caps_use_count--;
284         /*
285          * Keep some preallocated caps around (ceph_min_count), to
286          * avoid lots of free/alloc churn.
287          */
288         if (caps_avail_count >= caps_reserve_count + caps_min_count) {
289                 caps_total_count--;
290                 kmem_cache_free(ceph_cap_cachep, cap);
291         } else {
292                 caps_avail_count++;
293                 list_add(&cap->caps_item, &caps_list);
294         }
295
296         BUG_ON(caps_total_count != caps_use_count + caps_reserve_count +
297                caps_avail_count);
298         spin_unlock(&caps_list_lock);
299 }
300
301 void ceph_reservation_status(struct ceph_client *client,
302                              int *total, int *avail, int *used, int *reserved,
303                              int *min)
304 {
305         if (total)
306                 *total = caps_total_count;
307         if (avail)
308                 *avail = caps_avail_count;
309         if (used)
310                 *used = caps_use_count;
311         if (reserved)
312                 *reserved = caps_reserve_count;
313         if (min)
314                 *min = caps_min_count;
315 }
316
317 /*
318  * Find ceph_cap for given mds, if any.
319  *
320  * Called with i_lock held.
321  */
322 static struct ceph_cap *__get_cap_for_mds(struct ceph_inode_info *ci, int mds)
323 {
324         struct ceph_cap *cap;
325         struct rb_node *n = ci->i_caps.rb_node;
326
327         while (n) {
328                 cap = rb_entry(n, struct ceph_cap, ci_node);
329                 if (mds < cap->mds)
330                         n = n->rb_left;
331                 else if (mds > cap->mds)
332                         n = n->rb_right;
333                 else
334                         return cap;
335         }
336         return NULL;
337 }
338
339 /*
340  * Return id of any MDS with a cap, preferably FILE_WR|BUFFER|EXCL, else -1.
341  */
342 static int __ceph_get_cap_mds(struct ceph_inode_info *ci)
343 {
344         struct ceph_cap *cap;
345         int mds = -1;
346         struct rb_node *p;
347
348         /* prefer mds with WR|BUFFER|EXCL caps */
349         for (p = rb_first(&ci->i_caps); p; p = rb_next(p)) {
350                 cap = rb_entry(p, struct ceph_cap, ci_node);
351                 mds = cap->mds;
352                 if (cap->issued & (CEPH_CAP_FILE_WR |
353                                    CEPH_CAP_FILE_BUFFER |
354                                    CEPH_CAP_FILE_EXCL))
355                         break;
356         }
357         return mds;
358 }
359
360 int ceph_get_cap_mds(struct inode *inode)
361 {
362         int mds;
363         spin_lock(&inode->i_lock);
364         mds = __ceph_get_cap_mds(ceph_inode(inode));
365         spin_unlock(&inode->i_lock);
366         return mds;
367 }
368
369 /*
370  * Called under i_lock.
371  */
372 static void __insert_cap_node(struct ceph_inode_info *ci,
373                               struct ceph_cap *new)
374 {
375         struct rb_node **p = &ci->i_caps.rb_node;
376         struct rb_node *parent = NULL;
377         struct ceph_cap *cap = NULL;
378
379         while (*p) {
380                 parent = *p;
381                 cap = rb_entry(parent, struct ceph_cap, ci_node);
382                 if (new->mds < cap->mds)
383                         p = &(*p)->rb_left;
384                 else if (new->mds > cap->mds)
385                         p = &(*p)->rb_right;
386                 else
387                         BUG();
388         }
389
390         rb_link_node(&new->ci_node, parent, p);
391         rb_insert_color(&new->ci_node, &ci->i_caps);
392 }
393
394 /*
395  * (re)set cap hold timeouts, which control the delayed release
396  * of unused caps back to the MDS.  Should be called on cap use.
397  */
398 static void __cap_set_timeouts(struct ceph_mds_client *mdsc,
399                                struct ceph_inode_info *ci)
400 {
401         struct ceph_mount_args *ma = mdsc->client->mount_args;
402
403         ci->i_hold_caps_min = round_jiffies(jiffies +
404                                             ma->caps_wanted_delay_min * HZ);
405         ci->i_hold_caps_max = round_jiffies(jiffies +
406                                             ma->caps_wanted_delay_max * HZ);
407         dout("__cap_set_timeouts %p min %lu max %lu\n", &ci->vfs_inode,
408              ci->i_hold_caps_min - jiffies, ci->i_hold_caps_max - jiffies);
409 }
410
411 /*
412  * (Re)queue cap at the end of the delayed cap release list.
413  *
414  * If I_FLUSH is set, leave the inode at the front of the list.
415  *
416  * Caller holds i_lock
417  *    -> we take mdsc->cap_delay_lock
418  */
419 static void __cap_delay_requeue(struct ceph_mds_client *mdsc,
420                                 struct ceph_inode_info *ci)
421 {
422         __cap_set_timeouts(mdsc, ci);
423         dout("__cap_delay_requeue %p flags %d at %lu\n", &ci->vfs_inode,
424              ci->i_ceph_flags, ci->i_hold_caps_max);
425         if (!mdsc->stopping) {
426                 spin_lock(&mdsc->cap_delay_lock);
427                 if (!list_empty(&ci->i_cap_delay_list)) {
428                         if (ci->i_ceph_flags & CEPH_I_FLUSH)
429                                 goto no_change;
430                         list_del_init(&ci->i_cap_delay_list);
431                 }
432                 list_add_tail(&ci->i_cap_delay_list, &mdsc->cap_delay_list);
433 no_change:
434                 spin_unlock(&mdsc->cap_delay_lock);
435         }
436 }
437
438 /*
439  * Queue an inode for immediate writeback.  Mark inode with I_FLUSH,
440  * indicating we should send a cap message to flush dirty metadata
441  * asap, and move to the front of the delayed cap list.
442  */
443 static void __cap_delay_requeue_front(struct ceph_mds_client *mdsc,
444                                       struct ceph_inode_info *ci)
445 {
446         dout("__cap_delay_requeue_front %p\n", &ci->vfs_inode);
447         spin_lock(&mdsc->cap_delay_lock);
448         ci->i_ceph_flags |= CEPH_I_FLUSH;
449         if (!list_empty(&ci->i_cap_delay_list))
450                 list_del_init(&ci->i_cap_delay_list);
451         list_add(&ci->i_cap_delay_list, &mdsc->cap_delay_list);
452         spin_unlock(&mdsc->cap_delay_lock);
453 }
454
455 /*
456  * Cancel delayed work on cap.
457  *
458  * Caller must hold i_lock.
459  */
460 static void __cap_delay_cancel(struct ceph_mds_client *mdsc,
461                                struct ceph_inode_info *ci)
462 {
463         dout("__cap_delay_cancel %p\n", &ci->vfs_inode);
464         if (list_empty(&ci->i_cap_delay_list))
465                 return;
466         spin_lock(&mdsc->cap_delay_lock);
467         list_del_init(&ci->i_cap_delay_list);
468         spin_unlock(&mdsc->cap_delay_lock);
469 }
470
471 /*
472  * Common issue checks for add_cap, handle_cap_grant.
473  */
474 static void __check_cap_issue(struct ceph_inode_info *ci, struct ceph_cap *cap,
475                               unsigned issued)
476 {
477         unsigned had = __ceph_caps_issued(ci, NULL);
478
479         /*
480          * Each time we receive FILE_CACHE anew, we increment
481          * i_rdcache_gen.
482          */
483         if ((issued & (CEPH_CAP_FILE_CACHE|CEPH_CAP_FILE_LAZYIO)) &&
484             (had & (CEPH_CAP_FILE_CACHE|CEPH_CAP_FILE_LAZYIO)) == 0)
485                 ci->i_rdcache_gen++;
486
487         /*
488          * if we are newly issued FILE_SHARED, clear I_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                         ci->i_ceph_flags &= ~CEPH_I_COMPLETE;
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 int 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_reservation *caps_reservation)
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 *new_cap = NULL;
520         struct ceph_cap *cap;
521         int mds = session->s_mds;
522         int actual_wanted;
523
524         dout("add_cap %p mds%d cap %llx %s seq %d\n", inode,
525              session->s_mds, cap_id, ceph_cap_string(issued), seq);
526
527         /*
528          * If we are opening the file, include file mode wanted bits
529          * in wanted.
530          */
531         if (fmode >= 0)
532                 wanted |= ceph_caps_for_mode(fmode);
533
534 retry:
535         spin_lock(&inode->i_lock);
536         cap = __get_cap_for_mds(ci, mds);
537         if (!cap) {
538                 if (new_cap) {
539                         cap = new_cap;
540                         new_cap = NULL;
541                 } else {
542                         spin_unlock(&inode->i_lock);
543                         new_cap = get_cap(caps_reservation);
544                         if (new_cap == NULL)
545                                 return -ENOMEM;
546                         goto retry;
547                 }
548
549                 cap->issued = 0;
550                 cap->implemented = 0;
551                 cap->mds = mds;
552                 cap->mds_wanted = 0;
553
554                 cap->ci = ci;
555                 __insert_cap_node(ci, cap);
556
557                 /* clear out old exporting info?  (i.e. on cap import) */
558                 if (ci->i_cap_exporting_mds == mds) {
559                         ci->i_cap_exporting_issued = 0;
560                         ci->i_cap_exporting_mseq = 0;
561                         ci->i_cap_exporting_mds = -1;
562                 }
563
564                 /* add to session cap list */
565                 cap->session = session;
566                 spin_lock(&session->s_cap_lock);
567                 list_add_tail(&cap->session_caps, &session->s_caps);
568                 session->s_nr_caps++;
569                 spin_unlock(&session->s_cap_lock);
570         }
571
572         if (!ci->i_snap_realm) {
573                 /*
574                  * add this inode to the appropriate snap realm
575                  */
576                 struct ceph_snap_realm *realm = ceph_lookup_snap_realm(mdsc,
577                                                                realmino);
578                 if (realm) {
579                         ceph_get_snap_realm(mdsc, 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                 }
589         }
590
591         __check_cap_issue(ci, cap, issued);
592
593         /*
594          * If we are issued caps we don't want, or the mds' wanted
595          * value appears to be off, queue a check so we'll release
596          * later and/or update the mds wanted value.
597          */
598         actual_wanted = __ceph_caps_wanted(ci);
599         if ((wanted & ~actual_wanted) ||
600             (issued & ~actual_wanted & CEPH_CAP_ANY_WR)) {
601                 dout(" issued %s, mds wanted %s, actual %s, queueing\n",
602                      ceph_cap_string(issued), ceph_cap_string(wanted),
603                      ceph_cap_string(actual_wanted));
604                 __cap_delay_requeue(mdsc, ci);
605         }
606
607         if (flags & CEPH_CAP_FLAG_AUTH)
608                 ci->i_auth_cap = cap;
609         else if (ci->i_auth_cap == cap)
610                 ci->i_auth_cap = NULL;
611
612         dout("add_cap inode %p (%llx.%llx) cap %p %s now %s seq %d mds%d\n",
613              inode, ceph_vinop(inode), cap, ceph_cap_string(issued),
614              ceph_cap_string(issued|cap->issued), seq, mds);
615         cap->cap_id = cap_id;
616         cap->issued = issued;
617         cap->implemented |= issued;
618         cap->mds_wanted |= wanted;
619         cap->seq = seq;
620         cap->issue_seq = seq;
621         cap->mseq = mseq;
622         cap->cap_gen = session->s_cap_gen;
623
624         if (fmode >= 0)
625                 __ceph_get_fmode(ci, fmode);
626         spin_unlock(&inode->i_lock);
627         wake_up_all(&ci->i_cap_wq);
628         return 0;
629 }
630
631 /*
632  * Return true if cap has not timed out and belongs to the current
633  * generation of the MDS session (i.e. has not gone 'stale' due to
634  * us losing touch with the mds).
635  */
636 static int __cap_is_valid(struct ceph_cap *cap)
637 {
638         unsigned long ttl;
639         u32 gen;
640
641         spin_lock(&cap->session->s_cap_lock);
642         gen = cap->session->s_cap_gen;
643         ttl = cap->session->s_cap_ttl;
644         spin_unlock(&cap->session->s_cap_lock);
645
646         if (cap->cap_gen < gen || time_after_eq(jiffies, ttl)) {
647                 dout("__cap_is_valid %p cap %p issued %s "
648                      "but STALE (gen %u vs %u)\n", &cap->ci->vfs_inode,
649                      cap, ceph_cap_string(cap->issued), cap->cap_gen, gen);
650                 return 0;
651         }
652
653         return 1;
654 }
655
656 /*
657  * Return set of valid cap bits issued to us.  Note that caps time
658  * out, and may be invalidated in bulk if the client session times out
659  * and session->s_cap_gen is bumped.
660  */
661 int __ceph_caps_issued(struct ceph_inode_info *ci, int *implemented)
662 {
663         int have = ci->i_snap_caps | ci->i_cap_exporting_issued;
664         struct ceph_cap *cap;
665         struct rb_node *p;
666
667         if (implemented)
668                 *implemented = 0;
669         for (p = rb_first(&ci->i_caps); p; p = rb_next(p)) {
670                 cap = rb_entry(p, struct ceph_cap, ci_node);
671                 if (!__cap_is_valid(cap))
672                         continue;
673                 dout("__ceph_caps_issued %p cap %p issued %s\n",
674                      &ci->vfs_inode, cap, ceph_cap_string(cap->issued));
675                 have |= cap->issued;
676                 if (implemented)
677                         *implemented |= cap->implemented;
678         }
679         return have;
680 }
681
682 /*
683  * Get cap bits issued by caps other than @ocap
684  */
685 int __ceph_caps_issued_other(struct ceph_inode_info *ci, struct ceph_cap *ocap)
686 {
687         int have = ci->i_snap_caps;
688         struct ceph_cap *cap;
689         struct rb_node *p;
690
691         for (p = rb_first(&ci->i_caps); p; p = rb_next(p)) {
692                 cap = rb_entry(p, struct ceph_cap, ci_node);
693                 if (cap == ocap)
694                         continue;
695                 if (!__cap_is_valid(cap))
696                         continue;
697                 have |= cap->issued;
698         }
699         return have;
700 }
701
702 /*
703  * Move a cap to the end of the LRU (oldest caps at list head, newest
704  * at list tail).
705  */
706 static void __touch_cap(struct ceph_cap *cap)
707 {
708         struct ceph_mds_session *s = cap->session;
709
710         spin_lock(&s->s_cap_lock);
711         if (s->s_cap_iterator == NULL) {
712                 dout("__touch_cap %p cap %p mds%d\n", &cap->ci->vfs_inode, cap,
713                      s->s_mds);
714                 list_move_tail(&cap->session_caps, &s->s_caps);
715         } else {
716                 dout("__touch_cap %p cap %p mds%d NOP, iterating over caps\n",
717                      &cap->ci->vfs_inode, cap, s->s_mds);
718         }
719         spin_unlock(&s->s_cap_lock);
720 }
721
722 /*
723  * Check if we hold the given mask.  If so, move the cap(s) to the
724  * front of their respective LRUs.  (This is the preferred way for
725  * callers to check for caps they want.)
726  */
727 int __ceph_caps_issued_mask(struct ceph_inode_info *ci, int mask, int touch)
728 {
729         struct ceph_cap *cap;
730         struct rb_node *p;
731         int have = ci->i_snap_caps;
732
733         if ((have & mask) == mask) {
734                 dout("__ceph_caps_issued_mask %p snap issued %s"
735                      " (mask %s)\n", &ci->vfs_inode,
736                      ceph_cap_string(have),
737                      ceph_cap_string(mask));
738                 return 1;
739         }
740
741         for (p = rb_first(&ci->i_caps); p; p = rb_next(p)) {
742                 cap = rb_entry(p, struct ceph_cap, ci_node);
743                 if (!__cap_is_valid(cap))
744                         continue;
745                 if ((cap->issued & mask) == mask) {
746                         dout("__ceph_caps_issued_mask %p cap %p issued %s"
747                              " (mask %s)\n", &ci->vfs_inode, cap,
748                              ceph_cap_string(cap->issued),
749                              ceph_cap_string(mask));
750                         if (touch)
751                                 __touch_cap(cap);
752                         return 1;
753                 }
754
755                 /* does a combination of caps satisfy mask? */
756                 have |= cap->issued;
757                 if ((have & mask) == mask) {
758                         dout("__ceph_caps_issued_mask %p combo issued %s"
759                              " (mask %s)\n", &ci->vfs_inode,
760                              ceph_cap_string(cap->issued),
761                              ceph_cap_string(mask));
762                         if (touch) {
763                                 struct rb_node *q;
764
765                                 /* touch this + preceeding caps */
766                                 __touch_cap(cap);
767                                 for (q = rb_first(&ci->i_caps); q != p;
768                                      q = rb_next(q)) {
769                                         cap = rb_entry(q, struct ceph_cap,
770                                                        ci_node);
771                                         if (!__cap_is_valid(cap))
772                                                 continue;
773                                         __touch_cap(cap);
774                                 }
775                         }
776                         return 1;
777                 }
778         }
779
780         return 0;
781 }
782
783 /*
784  * Return true if mask caps are currently being revoked by an MDS.
785  */
786 int ceph_caps_revoking(struct ceph_inode_info *ci, int mask)
787 {
788         struct inode *inode = &ci->vfs_inode;
789         struct ceph_cap *cap;
790         struct rb_node *p;
791         int ret = 0;
792
793         spin_lock(&inode->i_lock);
794         for (p = rb_first(&ci->i_caps); p; p = rb_next(p)) {
795                 cap = rb_entry(p, struct ceph_cap, ci_node);
796                 if (__cap_is_valid(cap) &&
797                     (cap->implemented & ~cap->issued & mask)) {
798                         ret = 1;
799                         break;
800                 }
801         }
802         spin_unlock(&inode->i_lock);
803         dout("ceph_caps_revoking %p %s = %d\n", inode,
804              ceph_cap_string(mask), ret);
805         return ret;
806 }
807
808 int __ceph_caps_used(struct ceph_inode_info *ci)
809 {
810         int used = 0;
811         if (ci->i_pin_ref)
812                 used |= CEPH_CAP_PIN;
813         if (ci->i_rd_ref)
814                 used |= CEPH_CAP_FILE_RD;
815         if (ci->i_rdcache_ref || ci->i_rdcache_gen)
816                 used |= CEPH_CAP_FILE_CACHE;
817         if (ci->i_wr_ref)
818                 used |= CEPH_CAP_FILE_WR;
819         if (ci->i_wrbuffer_ref)
820                 used |= CEPH_CAP_FILE_BUFFER;
821         return used;
822 }
823
824 /*
825  * wanted, by virtue of open file modes
826  */
827 int __ceph_caps_file_wanted(struct ceph_inode_info *ci)
828 {
829         int want = 0;
830         int mode;
831         for (mode = 0; mode < CEPH_FILE_MODE_NUM; mode++)
832                 if (ci->i_nr_by_mode[mode])
833                         want |= ceph_caps_for_mode(mode);
834         return want;
835 }
836
837 /*
838  * Return caps we have registered with the MDS(s) as 'wanted'.
839  */
840 int __ceph_caps_mds_wanted(struct ceph_inode_info *ci)
841 {
842         struct ceph_cap *cap;
843         struct rb_node *p;
844         int mds_wanted = 0;
845
846         for (p = rb_first(&ci->i_caps); p; p = rb_next(p)) {
847                 cap = rb_entry(p, struct ceph_cap, ci_node);
848                 if (!__cap_is_valid(cap))
849                         continue;
850                 mds_wanted |= cap->mds_wanted;
851         }
852         return mds_wanted;
853 }
854
855 /*
856  * called under i_lock
857  */
858 static int __ceph_is_any_caps(struct ceph_inode_info *ci)
859 {
860         return !RB_EMPTY_ROOT(&ci->i_caps) || ci->i_cap_exporting_mds >= 0;
861 }
862
863 /*
864  * Remove a cap.  Take steps to deal with a racing iterate_session_caps.
865  *
866  * caller should hold i_lock.
867  * caller will not hold session s_mutex if called from destroy_inode.
868  */
869 void __ceph_remove_cap(struct ceph_cap *cap)
870 {
871         struct ceph_mds_session *session = cap->session;
872         struct ceph_inode_info *ci = cap->ci;
873         struct ceph_mds_client *mdsc =
874                 &ceph_sb_to_client(ci->vfs_inode.i_sb)->mdsc;
875         int removed = 0;
876
877         dout("__ceph_remove_cap %p from %p\n", cap, &ci->vfs_inode);
878
879         /* remove from session list */
880         spin_lock(&session->s_cap_lock);
881         if (session->s_cap_iterator == cap) {
882                 /* not yet, we are iterating over this very cap */
883                 dout("__ceph_remove_cap  delaying %p removal from session %p\n",
884                      cap, cap->session);
885         } else {
886                 list_del_init(&cap->session_caps);
887                 session->s_nr_caps--;
888                 cap->session = NULL;
889                 removed = 1;
890         }
891         /* protect backpointer with s_cap_lock: see iterate_session_caps */
892         cap->ci = NULL;
893         spin_unlock(&session->s_cap_lock);
894
895         /* remove from inode list */
896         rb_erase(&cap->ci_node, &ci->i_caps);
897         if (ci->i_auth_cap == cap)
898                 ci->i_auth_cap = NULL;
899
900         if (removed)
901                 ceph_put_cap(cap);
902
903         if (!__ceph_is_any_caps(ci) && ci->i_snap_realm) {
904                 struct ceph_snap_realm *realm = ci->i_snap_realm;
905                 spin_lock(&realm->inodes_with_caps_lock);
906                 list_del_init(&ci->i_snap_realm_item);
907                 ci->i_snap_realm_counter++;
908                 ci->i_snap_realm = NULL;
909                 spin_unlock(&realm->inodes_with_caps_lock);
910                 ceph_put_snap_realm(mdsc, realm);
911         }
912         if (!__ceph_is_any_real_caps(ci))
913                 __cap_delay_cancel(mdsc, ci);
914 }
915
916 /*
917  * Build and send a cap message to the given MDS.
918  *
919  * Caller should be holding s_mutex.
920  */
921 static int send_cap_msg(struct ceph_mds_session *session,
922                         u64 ino, u64 cid, int op,
923                         int caps, int wanted, int dirty,
924                         u32 seq, u64 flush_tid, u32 issue_seq, u32 mseq,
925                         u64 size, u64 max_size,
926                         struct timespec *mtime, struct timespec *atime,
927                         u64 time_warp_seq,
928                         uid_t uid, gid_t gid, mode_t mode,
929                         u64 xattr_version,
930                         struct ceph_buffer *xattrs_buf,
931                         u64 follows)
932 {
933         struct ceph_mds_caps *fc;
934         struct ceph_msg *msg;
935
936         dout("send_cap_msg %s %llx %llx caps %s wanted %s dirty %s"
937              " seq %u/%u mseq %u follows %lld size %llu/%llu"
938              " xattr_ver %llu xattr_len %d\n", ceph_cap_op_name(op),
939              cid, ino, ceph_cap_string(caps), ceph_cap_string(wanted),
940              ceph_cap_string(dirty),
941              seq, issue_seq, mseq, follows, size, max_size,
942              xattr_version, xattrs_buf ? (int)xattrs_buf->vec.iov_len : 0);
943
944         msg = ceph_msg_new(CEPH_MSG_CLIENT_CAPS, sizeof(*fc), GFP_NOFS);
945         if (!msg)
946                 return -ENOMEM;
947
948         msg->hdr.tid = cpu_to_le64(flush_tid);
949
950         fc = msg->front.iov_base;
951         memset(fc, 0, sizeof(*fc));
952
953         fc->cap_id = cpu_to_le64(cid);
954         fc->op = cpu_to_le32(op);
955         fc->seq = cpu_to_le32(seq);
956         fc->issue_seq = cpu_to_le32(issue_seq);
957         fc->migrate_seq = cpu_to_le32(mseq);
958         fc->caps = cpu_to_le32(caps);
959         fc->wanted = cpu_to_le32(wanted);
960         fc->dirty = cpu_to_le32(dirty);
961         fc->ino = cpu_to_le64(ino);
962         fc->snap_follows = cpu_to_le64(follows);
963
964         fc->size = cpu_to_le64(size);
965         fc->max_size = cpu_to_le64(max_size);
966         if (mtime)
967                 ceph_encode_timespec(&fc->mtime, mtime);
968         if (atime)
969                 ceph_encode_timespec(&fc->atime, atime);
970         fc->time_warp_seq = cpu_to_le32(time_warp_seq);
971
972         fc->uid = cpu_to_le32(uid);
973         fc->gid = cpu_to_le32(gid);
974         fc->mode = cpu_to_le32(mode);
975
976         fc->xattr_version = cpu_to_le64(xattr_version);
977         if (xattrs_buf) {
978                 msg->middle = ceph_buffer_get(xattrs_buf);
979                 fc->xattr_len = cpu_to_le32(xattrs_buf->vec.iov_len);
980                 msg->hdr.middle_len = cpu_to_le32(xattrs_buf->vec.iov_len);
981         }
982
983         ceph_con_send(&session->s_con, msg);
984         return 0;
985 }
986
987 static void __queue_cap_release(struct ceph_mds_session *session,
988                                 u64 ino, u64 cap_id, u32 migrate_seq,
989                                 u32 issue_seq)
990 {
991         struct ceph_msg *msg;
992         struct ceph_mds_cap_release *head;
993         struct ceph_mds_cap_item *item;
994
995         spin_lock(&session->s_cap_lock);
996         BUG_ON(!session->s_num_cap_releases);
997         msg = list_first_entry(&session->s_cap_releases,
998                                struct ceph_msg, list_head);
999
1000         dout(" adding %llx release to mds%d msg %p (%d left)\n",
1001              ino, session->s_mds, msg, session->s_num_cap_releases);
1002
1003         BUG_ON(msg->front.iov_len + sizeof(*item) > PAGE_CACHE_SIZE);
1004         head = msg->front.iov_base;
1005         head->num = cpu_to_le32(le32_to_cpu(head->num) + 1);
1006         item = msg->front.iov_base + msg->front.iov_len;
1007         item->ino = cpu_to_le64(ino);
1008         item->cap_id = cpu_to_le64(cap_id);
1009         item->migrate_seq = cpu_to_le32(migrate_seq);
1010         item->seq = cpu_to_le32(issue_seq);
1011
1012         session->s_num_cap_releases--;
1013
1014         msg->front.iov_len += sizeof(*item);
1015         if (le32_to_cpu(head->num) == CEPH_CAPS_PER_RELEASE) {
1016                 dout(" release msg %p full\n", msg);
1017                 list_move_tail(&msg->list_head, &session->s_cap_releases_done);
1018         } else {
1019                 dout(" release msg %p at %d/%d (%d)\n", msg,
1020                      (int)le32_to_cpu(head->num),
1021                      (int)CEPH_CAPS_PER_RELEASE,
1022                      (int)msg->front.iov_len);
1023         }
1024         spin_unlock(&session->s_cap_lock);
1025 }
1026
1027 /*
1028  * Queue cap releases when an inode is dropped from our cache.  Since
1029  * inode is about to be destroyed, there is no need for i_lock.
1030  */
1031 void ceph_queue_caps_release(struct inode *inode)
1032 {
1033         struct ceph_inode_info *ci = ceph_inode(inode);
1034         struct rb_node *p;
1035
1036         p = rb_first(&ci->i_caps);
1037         while (p) {
1038                 struct ceph_cap *cap = rb_entry(p, struct ceph_cap, ci_node);
1039                 struct ceph_mds_session *session = cap->session;
1040
1041                 __queue_cap_release(session, ceph_ino(inode), cap->cap_id,
1042                                     cap->mseq, cap->issue_seq);
1043                 p = rb_next(p);
1044                 __ceph_remove_cap(cap);
1045         }
1046 }
1047
1048 /*
1049  * Send a cap msg on the given inode.  Update our caps state, then
1050  * drop i_lock and send the message.
1051  *
1052  * Make note of max_size reported/requested from mds, revoked caps
1053  * that have now been implemented.
1054  *
1055  * Make half-hearted attempt ot to invalidate page cache if we are
1056  * dropping RDCACHE.  Note that this will leave behind locked pages
1057  * that we'll then need to deal with elsewhere.
1058  *
1059  * Return non-zero if delayed release, or we experienced an error
1060  * such that the caller should requeue + retry later.
1061  *
1062  * called with i_lock, then drops it.
1063  * caller should hold snap_rwsem (read), s_mutex.
1064  */
1065 static int __send_cap(struct ceph_mds_client *mdsc, struct ceph_cap *cap,
1066                       int op, int used, int want, int retain, int flushing,
1067                       unsigned *pflush_tid)
1068         __releases(cap->ci->vfs_inode->i_lock)
1069 {
1070         struct ceph_inode_info *ci = cap->ci;
1071         struct inode *inode = &ci->vfs_inode;
1072         u64 cap_id = cap->cap_id;
1073         int held, revoking, dropping, keep;
1074         u64 seq, issue_seq, mseq, time_warp_seq, follows;
1075         u64 size, max_size;
1076         struct timespec mtime, atime;
1077         int wake = 0;
1078         mode_t mode;
1079         uid_t uid;
1080         gid_t gid;
1081         struct ceph_mds_session *session;
1082         u64 xattr_version = 0;
1083         int delayed = 0;
1084         u64 flush_tid = 0;
1085         int i;
1086         int ret;
1087
1088         held = cap->issued | cap->implemented;
1089         revoking = cap->implemented & ~cap->issued;
1090         retain &= ~revoking;
1091         dropping = cap->issued & ~retain;
1092
1093         dout("__send_cap %p cap %p session %p %s -> %s (revoking %s)\n",
1094              inode, cap, cap->session,
1095              ceph_cap_string(held), ceph_cap_string(held & retain),
1096              ceph_cap_string(revoking));
1097         BUG_ON((retain & CEPH_CAP_PIN) == 0);
1098
1099         session = cap->session;
1100
1101         /* don't release wanted unless we've waited a bit. */
1102         if ((ci->i_ceph_flags & CEPH_I_NODELAY) == 0 &&
1103             time_before(jiffies, ci->i_hold_caps_min)) {
1104                 dout(" delaying issued %s -> %s, wanted %s -> %s on send\n",
1105                      ceph_cap_string(cap->issued),
1106                      ceph_cap_string(cap->issued & retain),
1107                      ceph_cap_string(cap->mds_wanted),
1108                      ceph_cap_string(want));
1109                 want |= cap->mds_wanted;
1110                 retain |= cap->issued;
1111                 delayed = 1;
1112         }
1113         ci->i_ceph_flags &= ~(CEPH_I_NODELAY | CEPH_I_FLUSH);
1114
1115         cap->issued &= retain;  /* drop bits we don't want */
1116         if (cap->implemented & ~cap->issued) {
1117                 /*
1118                  * Wake up any waiters on wanted -> needed transition.
1119                  * This is due to the weird transition from buffered
1120                  * to sync IO... we need to flush dirty pages _before_
1121                  * allowing sync writes to avoid reordering.
1122                  */
1123                 wake = 1;
1124         }
1125         cap->implemented &= cap->issued | used;
1126         cap->mds_wanted = want;
1127
1128         if (flushing) {
1129                 /*
1130                  * assign a tid for flush operations so we can avoid
1131                  * flush1 -> dirty1 -> flush2 -> flushack1 -> mark
1132                  * clean type races.  track latest tid for every bit
1133                  * so we can handle flush AxFw, flush Fw, and have the
1134                  * first ack clean Ax.
1135                  */
1136                 flush_tid = ++ci->i_cap_flush_last_tid;
1137                 if (pflush_tid)
1138                         *pflush_tid = flush_tid;
1139                 dout(" cap_flush_tid %d\n", (int)flush_tid);
1140                 for (i = 0; i < CEPH_CAP_BITS; i++)
1141                         if (flushing & (1 << i))
1142                                 ci->i_cap_flush_tid[i] = flush_tid;
1143         }
1144
1145         keep = cap->implemented;
1146         seq = cap->seq;
1147         issue_seq = cap->issue_seq;
1148         mseq = cap->mseq;
1149         size = inode->i_size;
1150         ci->i_reported_size = size;
1151         max_size = ci->i_wanted_max_size;
1152         ci->i_requested_max_size = max_size;
1153         mtime = inode->i_mtime;
1154         atime = inode->i_atime;
1155         time_warp_seq = ci->i_time_warp_seq;
1156         follows = ci->i_snap_realm->cached_context->seq;
1157         uid = inode->i_uid;
1158         gid = inode->i_gid;
1159         mode = inode->i_mode;
1160
1161         if (dropping & CEPH_CAP_XATTR_EXCL) {
1162                 __ceph_build_xattrs_blob(ci);
1163                 xattr_version = ci->i_xattrs.version + 1;
1164         }
1165
1166         spin_unlock(&inode->i_lock);
1167
1168         ret = send_cap_msg(session, ceph_vino(inode).ino, cap_id,
1169                 op, keep, want, flushing, seq, flush_tid, issue_seq, mseq,
1170                 size, max_size, &mtime, &atime, time_warp_seq,
1171                 uid, gid, mode,
1172                 xattr_version,
1173                 (flushing & CEPH_CAP_XATTR_EXCL) ? ci->i_xattrs.blob : NULL,
1174                 follows);
1175         if (ret < 0) {
1176                 dout("error sending cap msg, must requeue %p\n", inode);
1177                 delayed = 1;
1178         }
1179
1180         if (wake)
1181                 wake_up_all(&ci->i_cap_wq);
1182
1183         return delayed;
1184 }
1185
1186 /*
1187  * When a snapshot is taken, clients accumulate dirty metadata on
1188  * inodes with capabilities in ceph_cap_snaps to describe the file
1189  * state at the time the snapshot was taken.  This must be flushed
1190  * asynchronously back to the MDS once sync writes complete and dirty
1191  * data is written out.
1192  *
1193  * Called under i_lock.  Takes s_mutex as needed.
1194  */
1195 void __ceph_flush_snaps(struct ceph_inode_info *ci,
1196                         struct ceph_mds_session **psession)
1197 {
1198         struct inode *inode = &ci->vfs_inode;
1199         int mds;
1200         struct ceph_cap_snap *capsnap;
1201         u32 mseq;
1202         struct ceph_mds_client *mdsc = &ceph_inode_to_client(inode)->mdsc;
1203         struct ceph_mds_session *session = NULL; /* if session != NULL, we hold
1204                                                     session->s_mutex */
1205         u64 next_follows = 0;  /* keep track of how far we've gotten through the
1206                              i_cap_snaps list, and skip these entries next time
1207                              around to avoid an infinite loop */
1208
1209         if (psession)
1210                 session = *psession;
1211
1212         dout("__flush_snaps %p\n", inode);
1213 retry:
1214         list_for_each_entry(capsnap, &ci->i_cap_snaps, ci_item) {
1215                 /* avoid an infiniute loop after retry */
1216                 if (capsnap->follows < next_follows)
1217                         continue;
1218                 /*
1219                  * we need to wait for sync writes to complete and for dirty
1220                  * pages to be written out.
1221                  */
1222                 if (capsnap->dirty_pages || capsnap->writing)
1223                         continue;
1224
1225                 /*
1226                  * if cap writeback already occurred, we should have dropped
1227                  * the capsnap in ceph_put_wrbuffer_cap_refs.
1228                  */
1229                 BUG_ON(capsnap->dirty == 0);
1230
1231                 /* pick mds, take s_mutex */
1232                 if (ci->i_auth_cap == NULL) {
1233                         dout("no auth cap (migrating?), doing nothing\n");
1234                         goto out;
1235                 }
1236                 mds = ci->i_auth_cap->session->s_mds;
1237                 mseq = ci->i_auth_cap->mseq;
1238
1239                 if (session && session->s_mds != mds) {
1240                         dout("oops, wrong session %p mutex\n", session);
1241                         mutex_unlock(&session->s_mutex);
1242                         ceph_put_mds_session(session);
1243                         session = NULL;
1244                 }
1245                 if (!session) {
1246                         spin_unlock(&inode->i_lock);
1247                         mutex_lock(&mdsc->mutex);
1248                         session = __ceph_lookup_mds_session(mdsc, mds);
1249                         mutex_unlock(&mdsc->mutex);
1250                         if (session) {
1251                                 dout("inverting session/ino locks on %p\n",
1252                                      session);
1253                                 mutex_lock(&session->s_mutex);
1254                         }
1255                         /*
1256                          * if session == NULL, we raced against a cap
1257                          * deletion or migration.  retry, and we'll
1258                          * get a better @mds value next time.
1259                          */
1260                         spin_lock(&inode->i_lock);
1261                         goto retry;
1262                 }
1263
1264                 capsnap->flush_tid = ++ci->i_cap_flush_last_tid;
1265                 atomic_inc(&capsnap->nref);
1266                 if (!list_empty(&capsnap->flushing_item))
1267                         list_del_init(&capsnap->flushing_item);
1268                 list_add_tail(&capsnap->flushing_item,
1269                               &session->s_cap_snaps_flushing);
1270                 spin_unlock(&inode->i_lock);
1271
1272                 dout("flush_snaps %p cap_snap %p follows %lld size %llu\n",
1273                      inode, capsnap, next_follows, capsnap->size);
1274                 send_cap_msg(session, ceph_vino(inode).ino, 0,
1275                              CEPH_CAP_OP_FLUSHSNAP, capsnap->issued, 0,
1276                              capsnap->dirty, 0, capsnap->flush_tid, 0, mseq,
1277                              capsnap->size, 0,
1278                              &capsnap->mtime, &capsnap->atime,
1279                              capsnap->time_warp_seq,
1280                              capsnap->uid, capsnap->gid, capsnap->mode,
1281                              0, NULL,
1282                              capsnap->follows);
1283
1284                 next_follows = capsnap->follows + 1;
1285                 ceph_put_cap_snap(capsnap);
1286
1287                 spin_lock(&inode->i_lock);
1288                 goto retry;
1289         }
1290
1291         /* we flushed them all; remove this inode from the queue */
1292         spin_lock(&mdsc->snap_flush_lock);
1293         list_del_init(&ci->i_snap_flush_item);
1294         spin_unlock(&mdsc->snap_flush_lock);
1295
1296 out:
1297         if (psession)
1298                 *psession = session;
1299         else if (session) {
1300                 mutex_unlock(&session->s_mutex);
1301                 ceph_put_mds_session(session);
1302         }
1303 }
1304
1305 static void ceph_flush_snaps(struct ceph_inode_info *ci)
1306 {
1307         struct inode *inode = &ci->vfs_inode;
1308
1309         spin_lock(&inode->i_lock);
1310         __ceph_flush_snaps(ci, NULL);
1311         spin_unlock(&inode->i_lock);
1312 }
1313
1314 /*
1315  * Mark caps dirty.  If inode is newly dirty, add to the global dirty
1316  * list.
1317  */
1318 void __ceph_mark_dirty_caps(struct ceph_inode_info *ci, int mask)
1319 {
1320         struct ceph_mds_client *mdsc =
1321                 &ceph_sb_to_client(ci->vfs_inode.i_sb)->mdsc;
1322         struct inode *inode = &ci->vfs_inode;
1323         int was = ci->i_dirty_caps;
1324         int dirty = 0;
1325
1326         dout("__mark_dirty_caps %p %s dirty %s -> %s\n", &ci->vfs_inode,
1327              ceph_cap_string(mask), ceph_cap_string(was),
1328              ceph_cap_string(was | mask));
1329         ci->i_dirty_caps |= mask;
1330         if (was == 0) {
1331                 dout(" inode %p now dirty\n", &ci->vfs_inode);
1332                 BUG_ON(!list_empty(&ci->i_dirty_item));
1333                 spin_lock(&mdsc->cap_dirty_lock);
1334                 list_add(&ci->i_dirty_item, &mdsc->cap_dirty);
1335                 spin_unlock(&mdsc->cap_dirty_lock);
1336                 if (ci->i_flushing_caps == 0) {
1337                         igrab(inode);
1338                         dirty |= I_DIRTY_SYNC;
1339                 }
1340         }
1341         BUG_ON(list_empty(&ci->i_dirty_item));
1342         if (((was | ci->i_flushing_caps) & CEPH_CAP_FILE_BUFFER) &&
1343             (mask & CEPH_CAP_FILE_BUFFER))
1344                 dirty |= I_DIRTY_DATASYNC;
1345         if (dirty)
1346                 __mark_inode_dirty(inode, dirty);
1347         __cap_delay_requeue(mdsc, ci);
1348 }
1349
1350 /*
1351  * Add dirty inode to the flushing list.  Assigned a seq number so we
1352  * can wait for caps to flush without starving.
1353  *
1354  * Called under i_lock.
1355  */
1356 static int __mark_caps_flushing(struct inode *inode,
1357                                  struct ceph_mds_session *session)
1358 {
1359         struct ceph_mds_client *mdsc = &ceph_sb_to_client(inode->i_sb)->mdsc;
1360         struct ceph_inode_info *ci = ceph_inode(inode);
1361         int flushing;
1362
1363         BUG_ON(ci->i_dirty_caps == 0);
1364         BUG_ON(list_empty(&ci->i_dirty_item));
1365
1366         flushing = ci->i_dirty_caps;
1367         dout("__mark_caps_flushing flushing %s, flushing_caps %s -> %s\n",
1368              ceph_cap_string(flushing),
1369              ceph_cap_string(ci->i_flushing_caps),
1370              ceph_cap_string(ci->i_flushing_caps | flushing));
1371         ci->i_flushing_caps |= flushing;
1372         ci->i_dirty_caps = 0;
1373         dout(" inode %p now !dirty\n", inode);
1374
1375         spin_lock(&mdsc->cap_dirty_lock);
1376         list_del_init(&ci->i_dirty_item);
1377
1378         ci->i_cap_flush_seq = ++mdsc->cap_flush_seq;
1379         if (list_empty(&ci->i_flushing_item)) {
1380                 list_add_tail(&ci->i_flushing_item, &session->s_cap_flushing);
1381                 mdsc->num_cap_flushing++;
1382                 dout(" inode %p now flushing seq %lld\n", inode,
1383                      ci->i_cap_flush_seq);
1384         } else {
1385                 list_move_tail(&ci->i_flushing_item, &session->s_cap_flushing);
1386                 dout(" inode %p now flushing (more) seq %lld\n", inode,
1387                      ci->i_cap_flush_seq);
1388         }
1389         spin_unlock(&mdsc->cap_dirty_lock);
1390
1391         return flushing;
1392 }
1393
1394 /*
1395  * try to invalidate mapping pages without blocking.
1396  */
1397 static int mapping_is_empty(struct address_space *mapping)
1398 {
1399         struct page *page = find_get_page(mapping, 0);
1400
1401         if (!page)
1402                 return 1;
1403
1404         put_page(page);
1405         return 0;
1406 }
1407
1408 static int try_nonblocking_invalidate(struct inode *inode)
1409 {
1410         struct ceph_inode_info *ci = ceph_inode(inode);
1411         u32 invalidating_gen = ci->i_rdcache_gen;
1412
1413         spin_unlock(&inode->i_lock);
1414         invalidate_mapping_pages(&inode->i_data, 0, -1);
1415         spin_lock(&inode->i_lock);
1416
1417         if (mapping_is_empty(&inode->i_data) &&
1418             invalidating_gen == ci->i_rdcache_gen) {
1419                 /* success. */
1420                 dout("try_nonblocking_invalidate %p success\n", inode);
1421                 ci->i_rdcache_gen = 0;
1422                 ci->i_rdcache_revoking = 0;
1423                 return 0;
1424         }
1425         dout("try_nonblocking_invalidate %p failed\n", inode);
1426         return -1;
1427 }
1428
1429 /*
1430  * Swiss army knife function to examine currently used and wanted
1431  * versus held caps.  Release, flush, ack revoked caps to mds as
1432  * appropriate.
1433  *
1434  *  CHECK_CAPS_NODELAY - caller is delayed work and we should not delay
1435  *    cap release further.
1436  *  CHECK_CAPS_AUTHONLY - we should only check the auth cap
1437  *  CHECK_CAPS_FLUSH - we should flush any dirty caps immediately, without
1438  *    further delay.
1439  */
1440 void ceph_check_caps(struct ceph_inode_info *ci, int flags,
1441                      struct ceph_mds_session *session)
1442         __releases(session->s_mutex)
1443 {
1444         struct ceph_client *client = ceph_inode_to_client(&ci->vfs_inode);
1445         struct ceph_mds_client *mdsc = &client->mdsc;
1446         struct inode *inode = &ci->vfs_inode;
1447         struct ceph_cap *cap;
1448         int file_wanted, used;
1449         int took_snap_rwsem = 0;             /* true if mdsc->snap_rwsem held */
1450         int issued, implemented, want, retain, revoking, flushing = 0;
1451         int mds = -1;   /* keep track of how far we've gone through i_caps list
1452                            to avoid an infinite loop on retry */
1453         struct rb_node *p;
1454         int tried_invalidate = 0;
1455         int delayed = 0, sent = 0, force_requeue = 0, num;
1456         int queue_invalidate = 0;
1457         int is_delayed = flags & CHECK_CAPS_NODELAY;
1458
1459         /* if we are unmounting, flush any unused caps immediately. */
1460         if (mdsc->stopping)
1461                 is_delayed = 1;
1462
1463         spin_lock(&inode->i_lock);
1464
1465         if (ci->i_ceph_flags & CEPH_I_FLUSH)
1466                 flags |= CHECK_CAPS_FLUSH;
1467
1468         /* flush snaps first time around only */
1469         if (!list_empty(&ci->i_cap_snaps))
1470                 __ceph_flush_snaps(ci, &session);
1471         goto retry_locked;
1472 retry:
1473         spin_lock(&inode->i_lock);
1474 retry_locked:
1475         file_wanted = __ceph_caps_file_wanted(ci);
1476         used = __ceph_caps_used(ci);
1477         want = file_wanted | used;
1478         issued = __ceph_caps_issued(ci, &implemented);
1479         revoking = implemented & ~issued;
1480
1481         retain = want | CEPH_CAP_PIN;
1482         if (!mdsc->stopping && inode->i_nlink > 0) {
1483                 if (want) {
1484                         retain |= CEPH_CAP_ANY;       /* be greedy */
1485                 } else {
1486                         retain |= CEPH_CAP_ANY_SHARED;
1487                         /*
1488                          * keep RD only if we didn't have the file open RW,
1489                          * because then the mds would revoke it anyway to
1490                          * journal max_size=0.
1491                          */
1492                         if (ci->i_max_size == 0)
1493                                 retain |= CEPH_CAP_ANY_RD;
1494                 }
1495         }
1496
1497         dout("check_caps %p file_want %s used %s dirty %s flushing %s"
1498              " issued %s revoking %s retain %s %s%s%s\n", inode,
1499              ceph_cap_string(file_wanted),
1500              ceph_cap_string(used), ceph_cap_string(ci->i_dirty_caps),
1501              ceph_cap_string(ci->i_flushing_caps),
1502              ceph_cap_string(issued), ceph_cap_string(revoking),
1503              ceph_cap_string(retain),
1504              (flags & CHECK_CAPS_AUTHONLY) ? " AUTHONLY" : "",
1505              (flags & CHECK_CAPS_NODELAY) ? " NODELAY" : "",
1506              (flags & CHECK_CAPS_FLUSH) ? " FLUSH" : "");
1507
1508         /*
1509          * If we no longer need to hold onto old our caps, and we may
1510          * have cached pages, but don't want them, then try to invalidate.
1511          * If we fail, it's because pages are locked.... try again later.
1512          */
1513         if ((!is_delayed || mdsc->stopping) &&
1514             ci->i_wrbuffer_ref == 0 &&               /* no dirty pages... */
1515             ci->i_rdcache_gen &&                     /* may have cached pages */
1516             (file_wanted == 0 ||                     /* no open files */
1517              (revoking & (CEPH_CAP_FILE_CACHE|
1518                           CEPH_CAP_FILE_LAZYIO))) && /*  or revoking cache */
1519             !tried_invalidate) {
1520                 dout("check_caps trying to invalidate on %p\n", inode);
1521                 if (try_nonblocking_invalidate(inode) < 0) {
1522                         if (revoking & (CEPH_CAP_FILE_CACHE|
1523                                         CEPH_CAP_FILE_LAZYIO)) {
1524                                 dout("check_caps queuing invalidate\n");
1525                                 queue_invalidate = 1;
1526                                 ci->i_rdcache_revoking = ci->i_rdcache_gen;
1527                         } else {
1528                                 dout("check_caps failed to invalidate pages\n");
1529                                 /* we failed to invalidate pages.  check these
1530                                    caps again later. */
1531                                 force_requeue = 1;
1532                                 __cap_set_timeouts(mdsc, ci);
1533                         }
1534                 }
1535                 tried_invalidate = 1;
1536                 goto retry_locked;
1537         }
1538
1539         num = 0;
1540         for (p = rb_first(&ci->i_caps); p; p = rb_next(p)) {
1541                 cap = rb_entry(p, struct ceph_cap, ci_node);
1542                 num++;
1543
1544                 /* avoid looping forever */
1545                 if (mds >= cap->mds ||
1546                     ((flags & CHECK_CAPS_AUTHONLY) && cap != ci->i_auth_cap))
1547                         continue;
1548
1549                 /* NOTE: no side-effects allowed, until we take s_mutex */
1550
1551                 revoking = cap->implemented & ~cap->issued;
1552                 if (revoking)
1553                         dout(" mds%d revoking %s\n", cap->mds,
1554                              ceph_cap_string(revoking));
1555
1556                 if (cap == ci->i_auth_cap &&
1557                     (cap->issued & CEPH_CAP_FILE_WR)) {
1558                         /* request larger max_size from MDS? */
1559                         if (ci->i_wanted_max_size > ci->i_max_size &&
1560                             ci->i_wanted_max_size > ci->i_requested_max_size) {
1561                                 dout("requesting new max_size\n");
1562                                 goto ack;
1563                         }
1564
1565                         /* approaching file_max? */
1566                         if ((inode->i_size << 1) >= ci->i_max_size &&
1567                             (ci->i_reported_size << 1) < ci->i_max_size) {
1568                                 dout("i_size approaching max_size\n");
1569                                 goto ack;
1570                         }
1571                 }
1572                 /* flush anything dirty? */
1573                 if (cap == ci->i_auth_cap && (flags & CHECK_CAPS_FLUSH) &&
1574                     ci->i_dirty_caps) {
1575                         dout("flushing dirty caps\n");
1576                         goto ack;
1577                 }
1578
1579                 /* completed revocation? going down and there are no caps? */
1580                 if (revoking && (revoking & used) == 0) {
1581                         dout("completed revocation of %s\n",
1582                              ceph_cap_string(cap->implemented & ~cap->issued));
1583                         goto ack;
1584                 }
1585
1586                 /* want more caps from mds? */
1587                 if (want & ~(cap->mds_wanted | cap->issued))
1588                         goto ack;
1589
1590                 /* things we might delay */
1591                 if ((cap->issued & ~retain) == 0 &&
1592                     cap->mds_wanted == want)
1593                         continue;     /* nope, all good */
1594
1595                 if (is_delayed)
1596                         goto ack;
1597
1598                 /* delay? */
1599                 if ((ci->i_ceph_flags & CEPH_I_NODELAY) == 0 &&
1600                     time_before(jiffies, ci->i_hold_caps_max)) {
1601                         dout(" delaying issued %s -> %s, wanted %s -> %s\n",
1602                              ceph_cap_string(cap->issued),
1603                              ceph_cap_string(cap->issued & retain),
1604                              ceph_cap_string(cap->mds_wanted),
1605                              ceph_cap_string(want));
1606                         delayed++;
1607                         continue;
1608                 }
1609
1610 ack:
1611                 if (ci->i_ceph_flags & CEPH_I_NOFLUSH) {
1612                         dout(" skipping %p I_NOFLUSH set\n", inode);
1613                         continue;
1614                 }
1615
1616                 if (session && session != cap->session) {
1617                         dout("oops, wrong session %p mutex\n", session);
1618                         mutex_unlock(&session->s_mutex);
1619                         session = NULL;
1620                 }
1621                 if (!session) {
1622                         session = cap->session;
1623                         if (mutex_trylock(&session->s_mutex) == 0) {
1624                                 dout("inverting session/ino locks on %p\n",
1625                                      session);
1626                                 spin_unlock(&inode->i_lock);
1627                                 if (took_snap_rwsem) {
1628                                         up_read(&mdsc->snap_rwsem);
1629                                         took_snap_rwsem = 0;
1630                                 }
1631                                 mutex_lock(&session->s_mutex);
1632                                 goto retry;
1633                         }
1634                 }
1635                 /* take snap_rwsem after session mutex */
1636                 if (!took_snap_rwsem) {
1637                         if (down_read_trylock(&mdsc->snap_rwsem) == 0) {
1638                                 dout("inverting snap/in locks on %p\n",
1639                                      inode);
1640                                 spin_unlock(&inode->i_lock);
1641                                 down_read(&mdsc->snap_rwsem);
1642                                 took_snap_rwsem = 1;
1643                                 goto retry;
1644                         }
1645                         took_snap_rwsem = 1;
1646                 }
1647
1648                 if (cap == ci->i_auth_cap && ci->i_dirty_caps)
1649                         flushing = __mark_caps_flushing(inode, session);
1650
1651                 mds = cap->mds;  /* remember mds, so we don't repeat */
1652                 sent++;
1653
1654                 /* __send_cap drops i_lock */
1655                 delayed += __send_cap(mdsc, cap, CEPH_CAP_OP_UPDATE, used, want,
1656                                       retain, flushing, NULL);
1657                 goto retry; /* retake i_lock and restart our cap scan. */
1658         }
1659
1660         /*
1661          * Reschedule delayed caps release if we delayed anything,
1662          * otherwise cancel.
1663          */
1664         if (delayed && is_delayed)
1665                 force_requeue = 1;   /* __send_cap delayed release; requeue */
1666         if (!delayed && !is_delayed)
1667                 __cap_delay_cancel(mdsc, ci);
1668         else if (!is_delayed || force_requeue)
1669                 __cap_delay_requeue(mdsc, ci);
1670
1671         spin_unlock(&inode->i_lock);
1672
1673         if (queue_invalidate)
1674                 ceph_queue_invalidate(inode);
1675
1676         if (session)
1677                 mutex_unlock(&session->s_mutex);
1678         if (took_snap_rwsem)
1679                 up_read(&mdsc->snap_rwsem);
1680 }
1681
1682 /*
1683  * Try to flush dirty caps back to the auth mds.
1684  */
1685 static int try_flush_caps(struct inode *inode, struct ceph_mds_session *session,
1686                           unsigned *flush_tid)
1687 {
1688         struct ceph_mds_client *mdsc = &ceph_sb_to_client(inode->i_sb)->mdsc;
1689         struct ceph_inode_info *ci = ceph_inode(inode);
1690         int unlock_session = session ? 0 : 1;
1691         int flushing = 0;
1692
1693 retry:
1694         spin_lock(&inode->i_lock);
1695         if (ci->i_ceph_flags & CEPH_I_NOFLUSH) {
1696                 dout("try_flush_caps skipping %p I_NOFLUSH set\n", inode);
1697                 goto out;
1698         }
1699         if (ci->i_dirty_caps && ci->i_auth_cap) {
1700                 struct ceph_cap *cap = ci->i_auth_cap;
1701                 int used = __ceph_caps_used(ci);
1702                 int want = __ceph_caps_wanted(ci);
1703                 int delayed;
1704
1705                 if (!session) {
1706                         spin_unlock(&inode->i_lock);
1707                         session = cap->session;
1708                         mutex_lock(&session->s_mutex);
1709                         goto retry;
1710                 }
1711                 BUG_ON(session != cap->session);
1712                 if (cap->session->s_state < CEPH_MDS_SESSION_OPEN)
1713                         goto out;
1714
1715                 flushing = __mark_caps_flushing(inode, session);
1716
1717                 /* __send_cap drops i_lock */
1718                 delayed = __send_cap(mdsc, cap, CEPH_CAP_OP_FLUSH, used, want,
1719                                      cap->issued | cap->implemented, flushing,
1720                                      flush_tid);
1721                 if (!delayed)
1722                         goto out_unlocked;
1723
1724                 spin_lock(&inode->i_lock);
1725                 __cap_delay_requeue(mdsc, ci);
1726         }
1727 out:
1728         spin_unlock(&inode->i_lock);
1729 out_unlocked:
1730         if (session && unlock_session)
1731                 mutex_unlock(&session->s_mutex);
1732         return flushing;
1733 }
1734
1735 /*
1736  * Return true if we've flushed caps through the given flush_tid.
1737  */
1738 static int caps_are_flushed(struct inode *inode, unsigned tid)
1739 {
1740         struct ceph_inode_info *ci = ceph_inode(inode);
1741         int i, ret = 1;
1742
1743         spin_lock(&inode->i_lock);
1744         for (i = 0; i < CEPH_CAP_BITS; i++)
1745                 if ((ci->i_flushing_caps & (1 << i)) &&
1746                     ci->i_cap_flush_tid[i] <= tid) {
1747                         /* still flushing this bit */
1748                         ret = 0;
1749                         break;
1750                 }
1751         spin_unlock(&inode->i_lock);
1752         return ret;
1753 }
1754
1755 /*
1756  * Wait on any unsafe replies for the given inode.  First wait on the
1757  * newest request, and make that the upper bound.  Then, if there are
1758  * more requests, keep waiting on the oldest as long as it is still older
1759  * than the original request.
1760  */
1761 static void sync_write_wait(struct inode *inode)
1762 {
1763         struct ceph_inode_info *ci = ceph_inode(inode);
1764         struct list_head *head = &ci->i_unsafe_writes;
1765         struct ceph_osd_request *req;
1766         u64 last_tid;
1767
1768         spin_lock(&ci->i_unsafe_lock);
1769         if (list_empty(head))
1770                 goto out;
1771
1772         /* set upper bound as _last_ entry in chain */
1773         req = list_entry(head->prev, struct ceph_osd_request,
1774                          r_unsafe_item);
1775         last_tid = req->r_tid;
1776
1777         do {
1778                 ceph_osdc_get_request(req);
1779                 spin_unlock(&ci->i_unsafe_lock);
1780                 dout("sync_write_wait on tid %llu (until %llu)\n",
1781                      req->r_tid, last_tid);
1782                 wait_for_completion(&req->r_safe_completion);
1783                 spin_lock(&ci->i_unsafe_lock);
1784                 ceph_osdc_put_request(req);
1785
1786                 /*
1787                  * from here on look at first entry in chain, since we
1788                  * only want to wait for anything older than last_tid
1789                  */
1790                 if (list_empty(head))
1791                         break;
1792                 req = list_entry(head->next, struct ceph_osd_request,
1793                                  r_unsafe_item);
1794         } while (req->r_tid < last_tid);
1795 out:
1796         spin_unlock(&ci->i_unsafe_lock);
1797 }
1798
1799 int ceph_fsync(struct file *file, int datasync)
1800 {
1801         struct inode *inode = file->f_mapping->host;
1802         struct ceph_inode_info *ci = ceph_inode(inode);
1803         unsigned flush_tid;
1804         int ret;
1805         int dirty;
1806
1807         dout("fsync %p%s\n", inode, datasync ? " datasync" : "");
1808         sync_write_wait(inode);
1809
1810         ret = filemap_write_and_wait(inode->i_mapping);
1811         if (ret < 0)
1812                 return ret;
1813
1814         dirty = try_flush_caps(inode, NULL, &flush_tid);
1815         dout("fsync dirty caps are %s\n", ceph_cap_string(dirty));
1816
1817         /*
1818          * only wait on non-file metadata writeback (the mds
1819          * can recover size and mtime, so we don't need to
1820          * wait for that)
1821          */
1822         if (!datasync && (dirty & ~CEPH_CAP_ANY_FILE_WR)) {
1823                 dout("fsync waiting for flush_tid %u\n", flush_tid);
1824                 ret = wait_event_interruptible(ci->i_cap_wq,
1825                                        caps_are_flushed(inode, flush_tid));
1826         }
1827
1828         dout("fsync %p%s done\n", inode, datasync ? " datasync" : "");
1829         return ret;
1830 }
1831
1832 /*
1833  * Flush any dirty caps back to the mds.  If we aren't asked to wait,
1834  * queue inode for flush but don't do so immediately, because we can
1835  * get by with fewer MDS messages if we wait for data writeback to
1836  * complete first.
1837  */
1838 int ceph_write_inode(struct inode *inode, struct writeback_control *wbc)
1839 {
1840         struct ceph_inode_info *ci = ceph_inode(inode);
1841         unsigned flush_tid;
1842         int err = 0;
1843         int dirty;
1844         int wait = wbc->sync_mode == WB_SYNC_ALL;
1845
1846         dout("write_inode %p wait=%d\n", inode, wait);
1847         if (wait) {
1848                 dirty = try_flush_caps(inode, NULL, &flush_tid);
1849                 if (dirty)
1850                         err = wait_event_interruptible(ci->i_cap_wq,
1851                                        caps_are_flushed(inode, flush_tid));
1852         } else {
1853                 struct ceph_mds_client *mdsc =
1854                         &ceph_sb_to_client(inode->i_sb)->mdsc;
1855
1856                 spin_lock(&inode->i_lock);
1857                 if (__ceph_caps_dirty(ci))
1858                         __cap_delay_requeue_front(mdsc, ci);
1859                 spin_unlock(&inode->i_lock);
1860         }
1861         return err;
1862 }
1863
1864 /*
1865  * After a recovering MDS goes active, we need to resend any caps
1866  * we were flushing.
1867  *
1868  * Caller holds session->s_mutex.
1869  */
1870 static void kick_flushing_capsnaps(struct ceph_mds_client *mdsc,
1871                                    struct ceph_mds_session *session)
1872 {
1873         struct ceph_cap_snap *capsnap;
1874
1875         dout("kick_flushing_capsnaps mds%d\n", session->s_mds);
1876         list_for_each_entry(capsnap, &session->s_cap_snaps_flushing,
1877                             flushing_item) {
1878                 struct ceph_inode_info *ci = capsnap->ci;
1879                 struct inode *inode = &ci->vfs_inode;
1880                 struct ceph_cap *cap;
1881
1882                 spin_lock(&inode->i_lock);
1883                 cap = ci->i_auth_cap;
1884                 if (cap && cap->session == session) {
1885                         dout("kick_flushing_caps %p cap %p capsnap %p\n", inode,
1886                              cap, capsnap);
1887                         __ceph_flush_snaps(ci, &session);
1888                 } else {
1889                         pr_err("%p auth cap %p not mds%d ???\n", inode,
1890                                cap, session->s_mds);
1891                 }
1892                 spin_unlock(&inode->i_lock);
1893         }
1894 }
1895
1896 void ceph_kick_flushing_caps(struct ceph_mds_client *mdsc,
1897                              struct ceph_mds_session *session)
1898 {
1899         struct ceph_inode_info *ci;
1900
1901         kick_flushing_capsnaps(mdsc, session);
1902
1903         dout("kick_flushing_caps mds%d\n", session->s_mds);
1904         list_for_each_entry(ci, &session->s_cap_flushing, i_flushing_item) {
1905                 struct inode *inode = &ci->vfs_inode;
1906                 struct ceph_cap *cap;
1907                 int delayed = 0;
1908
1909                 spin_lock(&inode->i_lock);
1910                 cap = ci->i_auth_cap;
1911                 if (cap && cap->session == session) {
1912                         dout("kick_flushing_caps %p cap %p %s\n", inode,
1913                              cap, ceph_cap_string(ci->i_flushing_caps));
1914                         delayed = __send_cap(mdsc, cap, CEPH_CAP_OP_FLUSH,
1915                                              __ceph_caps_used(ci),
1916                                              __ceph_caps_wanted(ci),
1917                                              cap->issued | cap->implemented,
1918                                              ci->i_flushing_caps, NULL);
1919                         if (delayed) {
1920                                 spin_lock(&inode->i_lock);
1921                                 __cap_delay_requeue(mdsc, ci);
1922                                 spin_unlock(&inode->i_lock);
1923                         }
1924                 } else {
1925                         pr_err("%p auth cap %p not mds%d ???\n", inode,
1926                                cap, session->s_mds);
1927                         spin_unlock(&inode->i_lock);
1928                 }
1929         }
1930 }
1931
1932
1933 /*
1934  * Take references to capabilities we hold, so that we don't release
1935  * them to the MDS prematurely.
1936  *
1937  * Protected by i_lock.
1938  */
1939 static void __take_cap_refs(struct ceph_inode_info *ci, int got)
1940 {
1941         if (got & CEPH_CAP_PIN)
1942                 ci->i_pin_ref++;
1943         if (got & CEPH_CAP_FILE_RD)
1944                 ci->i_rd_ref++;
1945         if (got & CEPH_CAP_FILE_CACHE)
1946                 ci->i_rdcache_ref++;
1947         if (got & CEPH_CAP_FILE_WR)
1948                 ci->i_wr_ref++;
1949         if (got & CEPH_CAP_FILE_BUFFER) {
1950                 if (ci->i_wrbuffer_ref == 0)
1951                         igrab(&ci->vfs_inode);
1952                 ci->i_wrbuffer_ref++;
1953                 dout("__take_cap_refs %p wrbuffer %d -> %d (?)\n",
1954                      &ci->vfs_inode, ci->i_wrbuffer_ref-1, ci->i_wrbuffer_ref);
1955         }
1956 }
1957
1958 /*
1959  * Try to grab cap references.  Specify those refs we @want, and the
1960  * minimal set we @need.  Also include the larger offset we are writing
1961  * to (when applicable), and check against max_size here as well.
1962  * Note that caller is responsible for ensuring max_size increases are
1963  * requested from the MDS.
1964  */
1965 static int try_get_cap_refs(struct ceph_inode_info *ci, int need, int want,
1966                             int *got, loff_t endoff, int *check_max, int *err)
1967 {
1968         struct inode *inode = &ci->vfs_inode;
1969         int ret = 0;
1970         int have, implemented;
1971         int file_wanted;
1972
1973         dout("get_cap_refs %p need %s want %s\n", inode,
1974              ceph_cap_string(need), ceph_cap_string(want));
1975         spin_lock(&inode->i_lock);
1976
1977         /* make sure file is actually open */
1978         file_wanted = __ceph_caps_file_wanted(ci);
1979         if ((file_wanted & need) == 0) {
1980                 dout("try_get_cap_refs need %s file_wanted %s, EBADF\n",
1981                      ceph_cap_string(need), ceph_cap_string(file_wanted));
1982                 *err = -EBADF;
1983                 ret = 1;
1984                 goto out;
1985         }
1986
1987         if (need & CEPH_CAP_FILE_WR) {
1988                 if (endoff >= 0 && endoff > (loff_t)ci->i_max_size) {
1989                         dout("get_cap_refs %p endoff %llu > maxsize %llu\n",
1990                              inode, endoff, ci->i_max_size);
1991                         if (endoff > ci->i_wanted_max_size) {
1992                                 *check_max = 1;
1993                                 ret = 1;
1994                         }
1995                         goto out;
1996                 }
1997                 /*
1998                  * If a sync write is in progress, we must wait, so that we
1999                  * can get a final snapshot value for size+mtime.
2000                  */
2001                 if (__ceph_have_pending_cap_snap(ci)) {
2002                         dout("get_cap_refs %p cap_snap_pending\n", inode);
2003                         goto out;
2004                 }
2005         }
2006         have = __ceph_caps_issued(ci, &implemented);
2007
2008         /*
2009          * disallow writes while a truncate is pending
2010          */
2011         if (ci->i_truncate_pending)
2012                 have &= ~CEPH_CAP_FILE_WR;
2013
2014         if ((have & need) == need) {
2015                 /*
2016                  * Look at (implemented & ~have & not) so that we keep waiting
2017                  * on transition from wanted -> needed caps.  This is needed
2018                  * for WRBUFFER|WR -> WR to avoid a new WR sync write from
2019                  * going before a prior buffered writeback happens.
2020                  */
2021                 int not = want & ~(have & need);
2022                 int revoking = implemented & ~have;
2023                 dout("get_cap_refs %p have %s but not %s (revoking %s)\n",
2024                      inode, ceph_cap_string(have), ceph_cap_string(not),
2025                      ceph_cap_string(revoking));
2026                 if ((revoking & not) == 0) {
2027                         *got = need | (have & want);
2028                         __take_cap_refs(ci, *got);
2029                         ret = 1;
2030                 }
2031         } else {
2032                 dout("get_cap_refs %p have %s needed %s\n", inode,
2033                      ceph_cap_string(have), ceph_cap_string(need));
2034         }
2035 out:
2036         spin_unlock(&inode->i_lock);
2037         dout("get_cap_refs %p ret %d got %s\n", inode,
2038              ret, ceph_cap_string(*got));
2039         return ret;
2040 }
2041
2042 /*
2043  * Check the offset we are writing up to against our current
2044  * max_size.  If necessary, tell the MDS we want to write to
2045  * a larger offset.
2046  */
2047 static void check_max_size(struct inode *inode, loff_t endoff)
2048 {
2049         struct ceph_inode_info *ci = ceph_inode(inode);
2050         int check = 0;
2051
2052         /* do we need to explicitly request a larger max_size? */
2053         spin_lock(&inode->i_lock);
2054         if ((endoff >= ci->i_max_size ||
2055              endoff > (inode->i_size << 1)) &&
2056             endoff > ci->i_wanted_max_size) {
2057                 dout("write %p at large endoff %llu, req max_size\n",
2058                      inode, endoff);
2059                 ci->i_wanted_max_size = endoff;
2060                 check = 1;
2061         }
2062         spin_unlock(&inode->i_lock);
2063         if (check)
2064                 ceph_check_caps(ci, CHECK_CAPS_AUTHONLY, NULL);
2065 }
2066
2067 /*
2068  * Wait for caps, and take cap references.  If we can't get a WR cap
2069  * due to a small max_size, make sure we check_max_size (and possibly
2070  * ask the mds) so we don't get hung up indefinitely.
2071  */
2072 int ceph_get_caps(struct ceph_inode_info *ci, int need, int want, int *got,
2073                   loff_t endoff)
2074 {
2075         int check_max, ret, err;
2076
2077 retry:
2078         if (endoff > 0)
2079                 check_max_size(&ci->vfs_inode, endoff);
2080         check_max = 0;
2081         err = 0;
2082         ret = wait_event_interruptible(ci->i_cap_wq,
2083                                        try_get_cap_refs(ci, need, want,
2084                                                         got, endoff,
2085                                                         &check_max, &err));
2086         if (err)
2087                 ret = err;
2088         if (check_max)
2089                 goto retry;
2090         return ret;
2091 }
2092
2093 /*
2094  * Take cap refs.  Caller must already know we hold at least one ref
2095  * on the caps in question or we don't know this is safe.
2096  */
2097 void ceph_get_cap_refs(struct ceph_inode_info *ci, int caps)
2098 {
2099         spin_lock(&ci->vfs_inode.i_lock);
2100         __take_cap_refs(ci, caps);
2101         spin_unlock(&ci->vfs_inode.i_lock);
2102 }
2103
2104 /*
2105  * Release cap refs.
2106  *
2107  * If we released the last ref on any given cap, call ceph_check_caps
2108  * to release (or schedule a release).
2109  *
2110  * If we are releasing a WR cap (from a sync write), finalize any affected
2111  * cap_snap, and wake up any waiters.
2112  */
2113 void ceph_put_cap_refs(struct ceph_inode_info *ci, int had)
2114 {
2115         struct inode *inode = &ci->vfs_inode;
2116         int last = 0, put = 0, flushsnaps = 0, wake = 0;
2117         struct ceph_cap_snap *capsnap;
2118
2119         spin_lock(&inode->i_lock);
2120         if (had & CEPH_CAP_PIN)
2121                 --ci->i_pin_ref;
2122         if (had & CEPH_CAP_FILE_RD)
2123                 if (--ci->i_rd_ref == 0)
2124                         last++;
2125         if (had & CEPH_CAP_FILE_CACHE)
2126                 if (--ci->i_rdcache_ref == 0)
2127                         last++;
2128         if (had & CEPH_CAP_FILE_BUFFER) {
2129                 if (--ci->i_wrbuffer_ref == 0) {
2130                         last++;
2131                         put++;
2132                 }
2133                 dout("put_cap_refs %p wrbuffer %d -> %d (?)\n",
2134                      inode, ci->i_wrbuffer_ref+1, ci->i_wrbuffer_ref);
2135         }
2136         if (had & CEPH_CAP_FILE_WR)
2137                 if (--ci->i_wr_ref == 0) {
2138                         last++;
2139                         if (!list_empty(&ci->i_cap_snaps)) {
2140                                 capsnap = list_first_entry(&ci->i_cap_snaps,
2141                                                      struct ceph_cap_snap,
2142                                                      ci_item);
2143                                 if (capsnap->writing) {
2144                                         capsnap->writing = 0;
2145                                         flushsnaps =
2146                                                 __ceph_finish_cap_snap(ci,
2147                                                                        capsnap);
2148                                         wake = 1;
2149                                 }
2150                         }
2151                 }
2152         spin_unlock(&inode->i_lock);
2153
2154         dout("put_cap_refs %p had %s%s%s\n", inode, ceph_cap_string(had),
2155              last ? " last" : "", put ? " put" : "");
2156
2157         if (last && !flushsnaps)
2158                 ceph_check_caps(ci, 0, NULL);
2159         else if (flushsnaps)
2160                 ceph_flush_snaps(ci);
2161         if (wake)
2162                 wake_up_all(&ci->i_cap_wq);
2163         if (put)
2164                 iput(inode);
2165 }
2166
2167 /*
2168  * Release @nr WRBUFFER refs on dirty pages for the given @snapc snap
2169  * context.  Adjust per-snap dirty page accounting as appropriate.
2170  * Once all dirty data for a cap_snap is flushed, flush snapped file
2171  * metadata back to the MDS.  If we dropped the last ref, call
2172  * ceph_check_caps.
2173  */
2174 void ceph_put_wrbuffer_cap_refs(struct ceph_inode_info *ci, int nr,
2175                                 struct ceph_snap_context *snapc)
2176 {
2177         struct inode *inode = &ci->vfs_inode;
2178         int last = 0;
2179         int complete_capsnap = 0;
2180         int drop_capsnap = 0;
2181         int found = 0;
2182         struct ceph_cap_snap *capsnap = NULL;
2183
2184         spin_lock(&inode->i_lock);
2185         ci->i_wrbuffer_ref -= nr;
2186         last = !ci->i_wrbuffer_ref;
2187
2188         if (ci->i_head_snapc == snapc) {
2189                 ci->i_wrbuffer_ref_head -= nr;
2190                 if (!ci->i_wrbuffer_ref_head) {
2191                         ceph_put_snap_context(ci->i_head_snapc);
2192                         ci->i_head_snapc = NULL;
2193                 }
2194                 dout("put_wrbuffer_cap_refs on %p head %d/%d -> %d/%d %s\n",
2195                      inode,
2196                      ci->i_wrbuffer_ref+nr, ci->i_wrbuffer_ref_head+nr,
2197                      ci->i_wrbuffer_ref, ci->i_wrbuffer_ref_head,
2198                      last ? " LAST" : "");
2199         } else {
2200                 list_for_each_entry(capsnap, &ci->i_cap_snaps, ci_item) {
2201                         if (capsnap->context == snapc) {
2202                                 found = 1;
2203                                 break;
2204                         }
2205                 }
2206                 BUG_ON(!found);
2207                 capsnap->dirty_pages -= nr;
2208                 if (capsnap->dirty_pages == 0) {
2209                         complete_capsnap = 1;
2210                         if (capsnap->dirty == 0)
2211                                 /* cap writeback completed before we created
2212                                  * the cap_snap; no FLUSHSNAP is needed */
2213                                 drop_capsnap = 1;
2214                 }
2215                 dout("put_wrbuffer_cap_refs on %p cap_snap %p "
2216                      " snap %lld %d/%d -> %d/%d %s%s%s\n",
2217                      inode, capsnap, capsnap->context->seq,
2218                      ci->i_wrbuffer_ref+nr, capsnap->dirty_pages + nr,
2219                      ci->i_wrbuffer_ref, capsnap->dirty_pages,
2220                      last ? " (wrbuffer last)" : "",
2221                      complete_capsnap ? " (complete capsnap)" : "",
2222                      drop_capsnap ? " (drop capsnap)" : "");
2223                 if (drop_capsnap) {
2224                         ceph_put_snap_context(capsnap->context);
2225                         list_del(&capsnap->ci_item);
2226                         list_del(&capsnap->flushing_item);
2227                         ceph_put_cap_snap(capsnap);
2228                 }
2229         }
2230
2231         spin_unlock(&inode->i_lock);
2232
2233         if (last) {
2234                 ceph_check_caps(ci, CHECK_CAPS_AUTHONLY, NULL);
2235                 iput(inode);
2236         } else if (complete_capsnap) {
2237                 ceph_flush_snaps(ci);
2238                 wake_up_all(&ci->i_cap_wq);
2239         }
2240         if (drop_capsnap)
2241                 iput(inode);
2242 }
2243
2244 /*
2245  * Handle a cap GRANT message from the MDS.  (Note that a GRANT may
2246  * actually be a revocation if it specifies a smaller cap set.)
2247  *
2248  * caller holds s_mutex and i_lock, we drop both.
2249  *
2250  * return value:
2251  *  0 - ok
2252  *  1 - check_caps on auth cap only (writeback)
2253  *  2 - check_caps (ack revoke)
2254  */
2255 static void handle_cap_grant(struct inode *inode, struct ceph_mds_caps *grant,
2256                              struct ceph_mds_session *session,
2257                              struct ceph_cap *cap,
2258                              struct ceph_buffer *xattr_buf)
2259         __releases(inode->i_lock)
2260         __releases(session->s_mutex)
2261 {
2262         struct ceph_inode_info *ci = ceph_inode(inode);
2263         int mds = session->s_mds;
2264         int seq = le32_to_cpu(grant->seq);
2265         int newcaps = le32_to_cpu(grant->caps);
2266         int issued, implemented, used, wanted, dirty;
2267         u64 size = le64_to_cpu(grant->size);
2268         u64 max_size = le64_to_cpu(grant->max_size);
2269         struct timespec mtime, atime, ctime;
2270         int check_caps = 0;
2271         int wake = 0;
2272         int writeback = 0;
2273         int revoked_rdcache = 0;
2274         int queue_invalidate = 0;
2275
2276         dout("handle_cap_grant inode %p cap %p mds%d seq %d %s\n",
2277              inode, cap, mds, seq, ceph_cap_string(newcaps));
2278         dout(" size %llu max_size %llu, i_size %llu\n", size, max_size,
2279                 inode->i_size);
2280
2281         /*
2282          * If CACHE is being revoked, and we have no dirty buffers,
2283          * try to invalidate (once).  (If there are dirty buffers, we
2284          * will invalidate _after_ writeback.)
2285          */
2286         if (((cap->issued & ~newcaps) & CEPH_CAP_FILE_CACHE) &&
2287             (newcaps & CEPH_CAP_FILE_LAZYIO) == 0 &&
2288             !ci->i_wrbuffer_ref) {
2289                 if (try_nonblocking_invalidate(inode) == 0) {
2290                         revoked_rdcache = 1;
2291                 } else {
2292                         /* there were locked pages.. invalidate later
2293                            in a separate thread. */
2294                         if (ci->i_rdcache_revoking != ci->i_rdcache_gen) {
2295                                 queue_invalidate = 1;
2296                                 ci->i_rdcache_revoking = ci->i_rdcache_gen;
2297                         }
2298                 }
2299         }
2300
2301         /* side effects now are allowed */
2302
2303         issued = __ceph_caps_issued(ci, &implemented);
2304         issued |= implemented | __ceph_caps_dirty(ci);
2305
2306         cap->cap_gen = session->s_cap_gen;
2307
2308         __check_cap_issue(ci, cap, newcaps);
2309
2310         if ((issued & CEPH_CAP_AUTH_EXCL) == 0) {
2311                 inode->i_mode = le32_to_cpu(grant->mode);
2312                 inode->i_uid = le32_to_cpu(grant->uid);
2313                 inode->i_gid = le32_to_cpu(grant->gid);
2314                 dout("%p mode 0%o uid.gid %d.%d\n", inode, inode->i_mode,
2315                      inode->i_uid, inode->i_gid);
2316         }
2317
2318         if ((issued & CEPH_CAP_LINK_EXCL) == 0)
2319                 inode->i_nlink = le32_to_cpu(grant->nlink);
2320
2321         if ((issued & CEPH_CAP_XATTR_EXCL) == 0 && grant->xattr_len) {
2322                 int len = le32_to_cpu(grant->xattr_len);
2323                 u64 version = le64_to_cpu(grant->xattr_version);
2324
2325                 if (version > ci->i_xattrs.version) {
2326                         dout(" got new xattrs v%llu on %p len %d\n",
2327                              version, inode, len);
2328                         if (ci->i_xattrs.blob)
2329                                 ceph_buffer_put(ci->i_xattrs.blob);
2330                         ci->i_xattrs.blob = ceph_buffer_get(xattr_buf);
2331                         ci->i_xattrs.version = version;
2332                 }
2333         }
2334
2335         /* size/ctime/mtime/atime? */
2336         ceph_fill_file_size(inode, issued,
2337                             le32_to_cpu(grant->truncate_seq),
2338                             le64_to_cpu(grant->truncate_size), size);
2339         ceph_decode_timespec(&mtime, &grant->mtime);
2340         ceph_decode_timespec(&atime, &grant->atime);
2341         ceph_decode_timespec(&ctime, &grant->ctime);
2342         ceph_fill_file_time(inode, issued,
2343                             le32_to_cpu(grant->time_warp_seq), &ctime, &mtime,
2344                             &atime);
2345
2346         /* max size increase? */
2347         if (max_size != ci->i_max_size) {
2348                 dout("max_size %lld -> %llu\n", ci->i_max_size, max_size);
2349                 ci->i_max_size = max_size;
2350                 if (max_size >= ci->i_wanted_max_size) {
2351                         ci->i_wanted_max_size = 0;  /* reset */
2352                         ci->i_requested_max_size = 0;
2353                 }
2354                 wake = 1;
2355         }
2356
2357         /* check cap bits */
2358         wanted = __ceph_caps_wanted(ci);
2359         used = __ceph_caps_used(ci);
2360         dirty = __ceph_caps_dirty(ci);
2361         dout(" my wanted = %s, used = %s, dirty %s\n",
2362              ceph_cap_string(wanted),
2363              ceph_cap_string(used),
2364              ceph_cap_string(dirty));
2365         if (wanted != le32_to_cpu(grant->wanted)) {
2366                 dout("mds wanted %s -> %s\n",
2367                      ceph_cap_string(le32_to_cpu(grant->wanted)),
2368                      ceph_cap_string(wanted));
2369                 grant->wanted = cpu_to_le32(wanted);
2370         }
2371
2372         cap->seq = seq;
2373
2374         /* file layout may have changed */
2375         ci->i_layout = grant->layout;
2376
2377         /* revocation, grant, or no-op? */
2378         if (cap->issued & ~newcaps) {
2379                 int revoking = cap->issued & ~newcaps;
2380
2381                 dout("revocation: %s -> %s (revoking %s)\n",
2382                      ceph_cap_string(cap->issued),
2383                      ceph_cap_string(newcaps),
2384                      ceph_cap_string(revoking));
2385                 if (revoking & CEPH_CAP_FILE_BUFFER)
2386                         writeback = 1;  /* initiate writeback; will delay ack */
2387                 else if (revoking == CEPH_CAP_FILE_CACHE &&
2388                          (newcaps & CEPH_CAP_FILE_LAZYIO) == 0 &&
2389                          queue_invalidate)
2390                         ; /* do nothing yet, invalidation will be queued */
2391                 else if (cap == ci->i_auth_cap)
2392                         check_caps = 1; /* check auth cap only */
2393                 else
2394                         check_caps = 2; /* check all caps */
2395                 cap->issued = newcaps;
2396                 cap->implemented |= newcaps;
2397         } else if (cap->issued == newcaps) {
2398                 dout("caps unchanged: %s -> %s\n",
2399                      ceph_cap_string(cap->issued), ceph_cap_string(newcaps));
2400         } else {
2401                 dout("grant: %s -> %s\n", ceph_cap_string(cap->issued),
2402                      ceph_cap_string(newcaps));
2403                 cap->issued = newcaps;
2404                 cap->implemented |= newcaps; /* add bits only, to
2405                                               * avoid stepping on a
2406                                               * pending revocation */
2407                 wake = 1;
2408         }
2409         BUG_ON(cap->issued & ~cap->implemented);
2410
2411         spin_unlock(&inode->i_lock);
2412         if (writeback)
2413                 /*
2414                  * queue inode for writeback: we can't actually call
2415                  * filemap_write_and_wait, etc. from message handler
2416                  * context.
2417                  */
2418                 ceph_queue_writeback(inode);
2419         if (queue_invalidate)
2420                 ceph_queue_invalidate(inode);
2421         if (wake)
2422                 wake_up_all(&ci->i_cap_wq);
2423
2424         if (check_caps == 1)
2425                 ceph_check_caps(ci, CHECK_CAPS_NODELAY|CHECK_CAPS_AUTHONLY,
2426                                 session);
2427         else if (check_caps == 2)
2428                 ceph_check_caps(ci, CHECK_CAPS_NODELAY, session);
2429         else
2430                 mutex_unlock(&session->s_mutex);
2431 }
2432
2433 /*
2434  * Handle FLUSH_ACK from MDS, indicating that metadata we sent to the
2435  * MDS has been safely committed.
2436  */
2437 static void handle_cap_flush_ack(struct inode *inode, u64 flush_tid,
2438                                  struct ceph_mds_caps *m,
2439                                  struct ceph_mds_session *session,
2440                                  struct ceph_cap *cap)
2441         __releases(inode->i_lock)
2442 {
2443         struct ceph_inode_info *ci = ceph_inode(inode);
2444         struct ceph_mds_client *mdsc = &ceph_sb_to_client(inode->i_sb)->mdsc;
2445         unsigned seq = le32_to_cpu(m->seq);
2446         int dirty = le32_to_cpu(m->dirty);
2447         int cleaned = 0;
2448         int drop = 0;
2449         int i;
2450
2451         for (i = 0; i < CEPH_CAP_BITS; i++)
2452                 if ((dirty & (1 << i)) &&
2453                     flush_tid == ci->i_cap_flush_tid[i])
2454                         cleaned |= 1 << i;
2455
2456         dout("handle_cap_flush_ack inode %p mds%d seq %d on %s cleaned %s,"
2457              " flushing %s -> %s\n",
2458              inode, session->s_mds, seq, ceph_cap_string(dirty),
2459              ceph_cap_string(cleaned), ceph_cap_string(ci->i_flushing_caps),
2460              ceph_cap_string(ci->i_flushing_caps & ~cleaned));
2461
2462         if (ci->i_flushing_caps == (ci->i_flushing_caps & ~cleaned))
2463                 goto out;
2464
2465         ci->i_flushing_caps &= ~cleaned;
2466
2467         spin_lock(&mdsc->cap_dirty_lock);
2468         if (ci->i_flushing_caps == 0) {
2469                 list_del_init(&ci->i_flushing_item);
2470                 if (!list_empty(&session->s_cap_flushing))
2471                         dout(" mds%d still flushing cap on %p\n",
2472                              session->s_mds,
2473                              &list_entry(session->s_cap_flushing.next,
2474                                          struct ceph_inode_info,
2475                                          i_flushing_item)->vfs_inode);
2476                 mdsc->num_cap_flushing--;
2477                 wake_up_all(&mdsc->cap_flushing_wq);
2478                 dout(" inode %p now !flushing\n", inode);
2479
2480                 if (ci->i_dirty_caps == 0) {
2481                         dout(" inode %p now clean\n", inode);
2482                         BUG_ON(!list_empty(&ci->i_dirty_item));
2483                         drop = 1;
2484                 } else {
2485                         BUG_ON(list_empty(&ci->i_dirty_item));
2486                 }
2487         }
2488         spin_unlock(&mdsc->cap_dirty_lock);
2489         wake_up_all(&ci->i_cap_wq);
2490
2491 out:
2492         spin_unlock(&inode->i_lock);
2493         if (drop)
2494                 iput(inode);
2495 }
2496
2497 /*
2498  * Handle FLUSHSNAP_ACK.  MDS has flushed snap data to disk and we can
2499  * throw away our cap_snap.
2500  *
2501  * Caller hold s_mutex.
2502  */
2503 static void handle_cap_flushsnap_ack(struct inode *inode, u64 flush_tid,
2504                                      struct ceph_mds_caps *m,
2505                                      struct ceph_mds_session *session)
2506 {
2507         struct ceph_inode_info *ci = ceph_inode(inode);
2508         u64 follows = le64_to_cpu(m->snap_follows);
2509         struct ceph_cap_snap *capsnap;
2510         int drop = 0;
2511
2512         dout("handle_cap_flushsnap_ack inode %p ci %p mds%d follows %lld\n",
2513              inode, ci, session->s_mds, follows);
2514
2515         spin_lock(&inode->i_lock);
2516         list_for_each_entry(capsnap, &ci->i_cap_snaps, ci_item) {
2517                 if (capsnap->follows == follows) {
2518                         if (capsnap->flush_tid != flush_tid) {
2519                                 dout(" cap_snap %p follows %lld tid %lld !="
2520                                      " %lld\n", capsnap, follows,
2521                                      flush_tid, capsnap->flush_tid);
2522                                 break;
2523                         }
2524                         WARN_ON(capsnap->dirty_pages || capsnap->writing);
2525                         dout(" removing %p cap_snap %p follows %lld\n",
2526                              inode, capsnap, follows);
2527                         ceph_put_snap_context(capsnap->context);
2528                         list_del(&capsnap->ci_item);
2529                         list_del(&capsnap->flushing_item);
2530                         ceph_put_cap_snap(capsnap);
2531                         drop = 1;
2532                         break;
2533                 } else {
2534                         dout(" skipping cap_snap %p follows %lld\n",
2535                              capsnap, capsnap->follows);
2536                 }
2537         }
2538         spin_unlock(&inode->i_lock);
2539         if (drop)
2540                 iput(inode);
2541 }
2542
2543 /*
2544  * Handle TRUNC from MDS, indicating file truncation.
2545  *
2546  * caller hold s_mutex.
2547  */
2548 static void handle_cap_trunc(struct inode *inode,
2549                              struct ceph_mds_caps *trunc,
2550                              struct ceph_mds_session *session)
2551         __releases(inode->i_lock)
2552 {
2553         struct ceph_inode_info *ci = ceph_inode(inode);
2554         int mds = session->s_mds;
2555         int seq = le32_to_cpu(trunc->seq);
2556         u32 truncate_seq = le32_to_cpu(trunc->truncate_seq);
2557         u64 truncate_size = le64_to_cpu(trunc->truncate_size);
2558         u64 size = le64_to_cpu(trunc->size);
2559         int implemented = 0;
2560         int dirty = __ceph_caps_dirty(ci);
2561         int issued = __ceph_caps_issued(ceph_inode(inode), &implemented);
2562         int queue_trunc = 0;
2563
2564         issued |= implemented | dirty;
2565
2566         dout("handle_cap_trunc inode %p mds%d seq %d to %lld seq %d\n",
2567              inode, mds, seq, truncate_size, truncate_seq);
2568         queue_trunc = ceph_fill_file_size(inode, issued,
2569                                           truncate_seq, truncate_size, size);
2570         spin_unlock(&inode->i_lock);
2571
2572         if (queue_trunc)
2573                 ceph_queue_vmtruncate(inode);
2574 }
2575
2576 /*
2577  * Handle EXPORT from MDS.  Cap is being migrated _from_ this mds to a
2578  * different one.  If we are the most recent migration we've seen (as
2579  * indicated by mseq), make note of the migrating cap bits for the
2580  * duration (until we see the corresponding IMPORT).
2581  *
2582  * caller holds s_mutex
2583  */
2584 static void handle_cap_export(struct inode *inode, struct ceph_mds_caps *ex,
2585                               struct ceph_mds_session *session)
2586 {
2587         struct ceph_inode_info *ci = ceph_inode(inode);
2588         int mds = session->s_mds;
2589         unsigned mseq = le32_to_cpu(ex->migrate_seq);
2590         struct ceph_cap *cap = NULL, *t;
2591         struct rb_node *p;
2592         int remember = 1;
2593
2594         dout("handle_cap_export inode %p ci %p mds%d mseq %d\n",
2595              inode, ci, mds, mseq);
2596
2597         spin_lock(&inode->i_lock);
2598
2599         /* make sure we haven't seen a higher mseq */
2600         for (p = rb_first(&ci->i_caps); p; p = rb_next(p)) {
2601                 t = rb_entry(p, struct ceph_cap, ci_node);
2602                 if (ceph_seq_cmp(t->mseq, mseq) > 0) {
2603                         dout(" higher mseq on cap from mds%d\n",
2604                              t->session->s_mds);
2605                         remember = 0;
2606                 }
2607                 if (t->session->s_mds == mds)
2608                         cap = t;
2609         }
2610
2611         if (cap) {
2612                 if (remember) {
2613                         /* make note */
2614                         ci->i_cap_exporting_mds = mds;
2615                         ci->i_cap_exporting_mseq = mseq;
2616                         ci->i_cap_exporting_issued = cap->issued;
2617                 }
2618                 __ceph_remove_cap(cap);
2619         }
2620         /* else, we already released it */
2621
2622         spin_unlock(&inode->i_lock);
2623 }
2624
2625 /*
2626  * Handle cap IMPORT.  If there are temp bits from an older EXPORT,
2627  * clean them up.
2628  *
2629  * caller holds s_mutex.
2630  */
2631 static void handle_cap_import(struct ceph_mds_client *mdsc,
2632                               struct inode *inode, struct ceph_mds_caps *im,
2633                               struct ceph_mds_session *session,
2634                               void *snaptrace, int snaptrace_len)
2635 {
2636         struct ceph_inode_info *ci = ceph_inode(inode);
2637         int mds = session->s_mds;
2638         unsigned issued = le32_to_cpu(im->caps);
2639         unsigned wanted = le32_to_cpu(im->wanted);
2640         unsigned seq = le32_to_cpu(im->seq);
2641         unsigned mseq = le32_to_cpu(im->migrate_seq);
2642         u64 realmino = le64_to_cpu(im->realm);
2643         u64 cap_id = le64_to_cpu(im->cap_id);
2644
2645         if (ci->i_cap_exporting_mds >= 0 &&
2646             ceph_seq_cmp(ci->i_cap_exporting_mseq, mseq) < 0) {
2647                 dout("handle_cap_import inode %p ci %p mds%d mseq %d"
2648                      " - cleared exporting from mds%d\n",
2649                      inode, ci, mds, mseq,
2650                      ci->i_cap_exporting_mds);
2651                 ci->i_cap_exporting_issued = 0;
2652                 ci->i_cap_exporting_mseq = 0;
2653                 ci->i_cap_exporting_mds = -1;
2654         } else {
2655                 dout("handle_cap_import inode %p ci %p mds%d mseq %d\n",
2656                      inode, ci, mds, mseq);
2657         }
2658
2659         down_write(&mdsc->snap_rwsem);
2660         ceph_update_snap_trace(mdsc, snaptrace, snaptrace+snaptrace_len,
2661                                false);
2662         downgrade_write(&mdsc->snap_rwsem);
2663         ceph_add_cap(inode, session, cap_id, -1,
2664                      issued, wanted, seq, mseq, realmino, CEPH_CAP_FLAG_AUTH,
2665                      NULL /* no caps context */);
2666         try_flush_caps(inode, session, NULL);
2667         up_read(&mdsc->snap_rwsem);
2668 }
2669
2670 /*
2671  * Handle a caps message from the MDS.
2672  *
2673  * Identify the appropriate session, inode, and call the right handler
2674  * based on the cap op.
2675  */
2676 void ceph_handle_caps(struct ceph_mds_session *session,
2677                       struct ceph_msg *msg)
2678 {
2679         struct ceph_mds_client *mdsc = session->s_mdsc;
2680         struct super_block *sb = mdsc->client->sb;
2681         struct inode *inode;
2682         struct ceph_cap *cap;
2683         struct ceph_mds_caps *h;
2684         int mds = session->s_mds;
2685         int op;
2686         u32 seq, mseq;
2687         struct ceph_vino vino;
2688         u64 cap_id;
2689         u64 size, max_size;
2690         u64 tid;
2691         void *snaptrace;
2692
2693         dout("handle_caps from mds%d\n", mds);
2694
2695         /* decode */
2696         tid = le64_to_cpu(msg->hdr.tid);
2697         if (msg->front.iov_len < sizeof(*h))
2698                 goto bad;
2699         h = msg->front.iov_base;
2700         snaptrace = h + 1;
2701         op = le32_to_cpu(h->op);
2702         vino.ino = le64_to_cpu(h->ino);
2703         vino.snap = CEPH_NOSNAP;
2704         cap_id = le64_to_cpu(h->cap_id);
2705         seq = le32_to_cpu(h->seq);
2706         mseq = le32_to_cpu(h->migrate_seq);
2707         size = le64_to_cpu(h->size);
2708         max_size = le64_to_cpu(h->max_size);
2709
2710         mutex_lock(&session->s_mutex);
2711         session->s_seq++;
2712         dout(" mds%d seq %lld cap seq %u\n", session->s_mds, session->s_seq,
2713              (unsigned)seq);
2714
2715         /* lookup ino */
2716         inode = ceph_find_inode(sb, vino);
2717         dout(" op %s ino %llx.%llx inode %p\n", ceph_cap_op_name(op), vino.ino,
2718              vino.snap, inode);
2719         if (!inode) {
2720                 dout(" i don't have ino %llx\n", vino.ino);
2721
2722                 if (op == CEPH_CAP_OP_IMPORT)
2723                         __queue_cap_release(session, vino.ino, cap_id,
2724                                             mseq, seq);
2725
2726                 /*
2727                  * send any full release message to try to move things
2728                  * along for the mds (who clearly thinks we still have this
2729                  * cap).
2730                  */
2731                 ceph_add_cap_releases(mdsc, session);
2732                 ceph_send_cap_releases(mdsc, session);
2733                 goto done;
2734         }
2735
2736         /* these will work even if we don't have a cap yet */
2737         switch (op) {
2738         case CEPH_CAP_OP_FLUSHSNAP_ACK:
2739                 handle_cap_flushsnap_ack(inode, tid, h, session);
2740                 goto done;
2741
2742         case CEPH_CAP_OP_EXPORT:
2743                 handle_cap_export(inode, h, session);
2744                 goto done;
2745
2746         case CEPH_CAP_OP_IMPORT:
2747                 handle_cap_import(mdsc, inode, h, session,
2748                                   snaptrace, le32_to_cpu(h->snap_trace_len));
2749                 ceph_check_caps(ceph_inode(inode), CHECK_CAPS_NODELAY,
2750                                 session);
2751                 goto done_unlocked;
2752         }
2753
2754         /* the rest require a cap */
2755         spin_lock(&inode->i_lock);
2756         cap = __get_cap_for_mds(ceph_inode(inode), mds);
2757         if (!cap) {
2758                 dout(" no cap on %p ino %llx.%llx from mds%d\n",
2759                      inode, ceph_ino(inode), ceph_snap(inode), mds);
2760                 spin_unlock(&inode->i_lock);
2761                 goto done;
2762         }
2763
2764         /* note that each of these drops i_lock for us */
2765         switch (op) {
2766         case CEPH_CAP_OP_REVOKE:
2767         case CEPH_CAP_OP_GRANT:
2768                 handle_cap_grant(inode, h, session, cap, msg->middle);
2769                 goto done_unlocked;
2770
2771         case CEPH_CAP_OP_FLUSH_ACK:
2772                 handle_cap_flush_ack(inode, tid, h, session, cap);
2773                 break;
2774
2775         case CEPH_CAP_OP_TRUNC:
2776                 handle_cap_trunc(inode, h, session);
2777                 break;
2778
2779         default:
2780                 spin_unlock(&inode->i_lock);
2781                 pr_err("ceph_handle_caps: unknown cap op %d %s\n", op,
2782                        ceph_cap_op_name(op));
2783         }
2784
2785 done:
2786         mutex_unlock(&session->s_mutex);
2787 done_unlocked:
2788         if (inode)
2789                 iput(inode);
2790         return;
2791
2792 bad:
2793         pr_err("ceph_handle_caps: corrupt message\n");
2794         ceph_msg_dump(msg);
2795         return;
2796 }
2797
2798 /*
2799  * Delayed work handler to process end of delayed cap release LRU list.
2800  */
2801 void ceph_check_delayed_caps(struct ceph_mds_client *mdsc)
2802 {
2803         struct ceph_inode_info *ci;
2804         int flags = CHECK_CAPS_NODELAY;
2805
2806         dout("check_delayed_caps\n");
2807         while (1) {
2808                 spin_lock(&mdsc->cap_delay_lock);
2809                 if (list_empty(&mdsc->cap_delay_list))
2810                         break;
2811                 ci = list_first_entry(&mdsc->cap_delay_list,
2812                                       struct ceph_inode_info,
2813                                       i_cap_delay_list);
2814                 if ((ci->i_ceph_flags & CEPH_I_FLUSH) == 0 &&
2815                     time_before(jiffies, ci->i_hold_caps_max))
2816                         break;
2817                 list_del_init(&ci->i_cap_delay_list);
2818                 spin_unlock(&mdsc->cap_delay_lock);
2819                 dout("check_delayed_caps on %p\n", &ci->vfs_inode);
2820                 ceph_check_caps(ci, flags, NULL);
2821         }
2822         spin_unlock(&mdsc->cap_delay_lock);
2823 }
2824
2825 /*
2826  * Flush all dirty caps to the mds
2827  */
2828 void ceph_flush_dirty_caps(struct ceph_mds_client *mdsc)
2829 {
2830         struct ceph_inode_info *ci, *nci = NULL;
2831         struct inode *inode, *ninode = NULL;
2832         struct list_head *p, *n;
2833
2834         dout("flush_dirty_caps\n");
2835         spin_lock(&mdsc->cap_dirty_lock);
2836         list_for_each_safe(p, n, &mdsc->cap_dirty) {
2837                 if (nci) {
2838                         ci = nci;
2839                         inode = ninode;
2840                         ci->i_ceph_flags &= ~CEPH_I_NOFLUSH;
2841                         dout("flush_dirty_caps inode %p (was next inode)\n",
2842                              inode);
2843                 } else {
2844                         ci = list_entry(p, struct ceph_inode_info,
2845                                         i_dirty_item);
2846                         inode = igrab(&ci->vfs_inode);
2847                         BUG_ON(!inode);
2848                         dout("flush_dirty_caps inode %p\n", inode);
2849                 }
2850                 if (n != &mdsc->cap_dirty) {
2851                         nci = list_entry(n, struct ceph_inode_info,
2852                                          i_dirty_item);
2853                         ninode = igrab(&nci->vfs_inode);
2854                         BUG_ON(!ninode);
2855                         nci->i_ceph_flags |= CEPH_I_NOFLUSH;
2856                         dout("flush_dirty_caps next inode %p, noflush\n",
2857                              ninode);
2858                 } else {
2859                         nci = NULL;
2860                         ninode = NULL;
2861                 }
2862                 spin_unlock(&mdsc->cap_dirty_lock);
2863                 if (inode) {
2864                         ceph_check_caps(ci, CHECK_CAPS_NODELAY|CHECK_CAPS_FLUSH,
2865                                         NULL);
2866                         iput(inode);
2867                 }
2868                 spin_lock(&mdsc->cap_dirty_lock);
2869         }
2870         spin_unlock(&mdsc->cap_dirty_lock);
2871 }
2872
2873 /*
2874  * Drop open file reference.  If we were the last open file,
2875  * we may need to release capabilities to the MDS (or schedule
2876  * their delayed release).
2877  */
2878 void ceph_put_fmode(struct ceph_inode_info *ci, int fmode)
2879 {
2880         struct inode *inode = &ci->vfs_inode;
2881         int last = 0;
2882
2883         spin_lock(&inode->i_lock);
2884         dout("put_fmode %p fmode %d %d -> %d\n", inode, fmode,
2885              ci->i_nr_by_mode[fmode], ci->i_nr_by_mode[fmode]-1);
2886         BUG_ON(ci->i_nr_by_mode[fmode] == 0);
2887         if (--ci->i_nr_by_mode[fmode] == 0)
2888                 last++;
2889         spin_unlock(&inode->i_lock);
2890
2891         if (last && ci->i_vino.snap == CEPH_NOSNAP)
2892                 ceph_check_caps(ci, 0, NULL);
2893 }
2894
2895 /*
2896  * Helpers for embedding cap and dentry lease releases into mds
2897  * requests.
2898  *
2899  * @force is used by dentry_release (below) to force inclusion of a
2900  * record for the directory inode, even when there aren't any caps to
2901  * drop.
2902  */
2903 int ceph_encode_inode_release(void **p, struct inode *inode,
2904                               int mds, int drop, int unless, int force)
2905 {
2906         struct ceph_inode_info *ci = ceph_inode(inode);
2907         struct ceph_cap *cap;
2908         struct ceph_mds_request_release *rel = *p;
2909         int used, dirty;
2910         int ret = 0;
2911
2912         spin_lock(&inode->i_lock);
2913         used = __ceph_caps_used(ci);
2914         dirty = __ceph_caps_dirty(ci);
2915
2916         dout("encode_inode_release %p mds%d used|dirty %s drop %s unless %s\n",
2917              inode, mds, ceph_cap_string(used|dirty), ceph_cap_string(drop),
2918              ceph_cap_string(unless));
2919
2920         /* only drop unused, clean caps */
2921         drop &= ~(used | dirty);
2922
2923         cap = __get_cap_for_mds(ci, mds);
2924         if (cap && __cap_is_valid(cap)) {
2925                 if (force ||
2926                     ((cap->issued & drop) &&
2927                      (cap->issued & unless) == 0)) {
2928                         if ((cap->issued & drop) &&
2929                             (cap->issued & unless) == 0) {
2930                                 dout("encode_inode_release %p cap %p %s -> "
2931                                      "%s\n", inode, cap,
2932                                      ceph_cap_string(cap->issued),
2933                                      ceph_cap_string(cap->issued & ~drop));
2934                                 cap->issued &= ~drop;
2935                                 cap->implemented &= ~drop;
2936                                 if (ci->i_ceph_flags & CEPH_I_NODELAY) {
2937                                         int wanted = __ceph_caps_wanted(ci);
2938                                         dout("  wanted %s -> %s (act %s)\n",
2939                                              ceph_cap_string(cap->mds_wanted),
2940                                              ceph_cap_string(cap->mds_wanted &
2941                                                              ~wanted),
2942                                              ceph_cap_string(wanted));
2943                                         cap->mds_wanted &= wanted;
2944                                 }
2945                         } else {
2946                                 dout("encode_inode_release %p cap %p %s"
2947                                      " (force)\n", inode, cap,
2948                                      ceph_cap_string(cap->issued));
2949                         }
2950
2951                         rel->ino = cpu_to_le64(ceph_ino(inode));
2952                         rel->cap_id = cpu_to_le64(cap->cap_id);
2953                         rel->seq = cpu_to_le32(cap->seq);
2954                         rel->issue_seq = cpu_to_le32(cap->issue_seq),
2955                         rel->mseq = cpu_to_le32(cap->mseq);
2956                         rel->caps = cpu_to_le32(cap->issued);
2957                         rel->wanted = cpu_to_le32(cap->mds_wanted);
2958                         rel->dname_len = 0;
2959                         rel->dname_seq = 0;
2960                         *p += sizeof(*rel);
2961                         ret = 1;
2962                 } else {
2963                         dout("encode_inode_release %p cap %p %s\n",
2964                              inode, cap, ceph_cap_string(cap->issued));
2965                 }
2966         }
2967         spin_unlock(&inode->i_lock);
2968         return ret;
2969 }
2970
2971 int ceph_encode_dentry_release(void **p, struct dentry *dentry,
2972                                int mds, int drop, int unless)
2973 {
2974         struct inode *dir = dentry->d_parent->d_inode;
2975         struct ceph_mds_request_release *rel = *p;
2976         struct ceph_dentry_info *di = ceph_dentry(dentry);
2977         int force = 0;
2978         int ret;
2979
2980         /*
2981          * force an record for the directory caps if we have a dentry lease.
2982          * this is racy (can't take i_lock and d_lock together), but it
2983          * doesn't have to be perfect; the mds will revoke anything we don't
2984          * release.
2985          */
2986         spin_lock(&dentry->d_lock);
2987         if (di->lease_session && di->lease_session->s_mds == mds)
2988                 force = 1;
2989         spin_unlock(&dentry->d_lock);
2990
2991         ret = ceph_encode_inode_release(p, dir, mds, drop, unless, force);
2992
2993         spin_lock(&dentry->d_lock);
2994         if (ret && di->lease_session && di->lease_session->s_mds == mds) {
2995                 dout("encode_dentry_release %p mds%d seq %d\n",
2996                      dentry, mds, (int)di->lease_seq);
2997                 rel->dname_len = cpu_to_le32(dentry->d_name.len);
2998                 memcpy(*p, dentry->d_name.name, dentry->d_name.len);
2999                 *p += dentry->d_name.len;
3000                 rel->dname_seq = cpu_to_le32(di->lease_seq);
3001                 __ceph_mdsc_drop_dentry_lease(dentry);
3002         }
3003         spin_unlock(&dentry->d_lock);
3004         return ret;
3005 }