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