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