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