ceph: define struct for dir entry in readdir reply
[linux-2.6-block.git] / fs / ceph / mds_client.c
1 #include <linux/ceph/ceph_debug.h>
2
3 #include <linux/fs.h>
4 #include <linux/wait.h>
5 #include <linux/slab.h>
6 #include <linux/gfp.h>
7 #include <linux/sched.h>
8 #include <linux/debugfs.h>
9 #include <linux/seq_file.h>
10 #include <linux/utsname.h>
11 #include <linux/ratelimit.h>
12
13 #include "super.h"
14 #include "mds_client.h"
15
16 #include <linux/ceph/ceph_features.h>
17 #include <linux/ceph/messenger.h>
18 #include <linux/ceph/decode.h>
19 #include <linux/ceph/pagelist.h>
20 #include <linux/ceph/auth.h>
21 #include <linux/ceph/debugfs.h>
22
23 /*
24  * A cluster of MDS (metadata server) daemons is responsible for
25  * managing the file system namespace (the directory hierarchy and
26  * inodes) and for coordinating shared access to storage.  Metadata is
27  * partitioning hierarchically across a number of servers, and that
28  * partition varies over time as the cluster adjusts the distribution
29  * in order to balance load.
30  *
31  * The MDS client is primarily responsible to managing synchronous
32  * metadata requests for operations like open, unlink, and so forth.
33  * If there is a MDS failure, we find out about it when we (possibly
34  * request and) receive a new MDS map, and can resubmit affected
35  * requests.
36  *
37  * For the most part, though, we take advantage of a lossless
38  * communications channel to the MDS, and do not need to worry about
39  * timing out or resubmitting requests.
40  *
41  * We maintain a stateful "session" with each MDS we interact with.
42  * Within each session, we sent periodic heartbeat messages to ensure
43  * any capabilities or leases we have been issues remain valid.  If
44  * the session times out and goes stale, our leases and capabilities
45  * are no longer valid.
46  */
47
48 struct ceph_reconnect_state {
49         int nr_caps;
50         struct ceph_pagelist *pagelist;
51         bool flock;
52 };
53
54 static void __wake_requests(struct ceph_mds_client *mdsc,
55                             struct list_head *head);
56
57 static const struct ceph_connection_operations mds_con_ops;
58
59
60 /*
61  * mds reply parsing
62  */
63
64 /*
65  * parse individual inode info
66  */
67 static int parse_reply_info_in(void **p, void *end,
68                                struct ceph_mds_reply_info_in *info,
69                                u64 features)
70 {
71         int err = -EIO;
72
73         info->in = *p;
74         *p += sizeof(struct ceph_mds_reply_inode) +
75                 sizeof(*info->in->fragtree.splits) *
76                 le32_to_cpu(info->in->fragtree.nsplits);
77
78         ceph_decode_32_safe(p, end, info->symlink_len, bad);
79         ceph_decode_need(p, end, info->symlink_len, bad);
80         info->symlink = *p;
81         *p += info->symlink_len;
82
83         if (features & CEPH_FEATURE_DIRLAYOUTHASH)
84                 ceph_decode_copy_safe(p, end, &info->dir_layout,
85                                       sizeof(info->dir_layout), bad);
86         else
87                 memset(&info->dir_layout, 0, sizeof(info->dir_layout));
88
89         ceph_decode_32_safe(p, end, info->xattr_len, bad);
90         ceph_decode_need(p, end, info->xattr_len, bad);
91         info->xattr_data = *p;
92         *p += info->xattr_len;
93
94         if (features & CEPH_FEATURE_MDS_INLINE_DATA) {
95                 ceph_decode_64_safe(p, end, info->inline_version, bad);
96                 ceph_decode_32_safe(p, end, info->inline_len, bad);
97                 ceph_decode_need(p, end, info->inline_len, bad);
98                 info->inline_data = *p;
99                 *p += info->inline_len;
100         } else
101                 info->inline_version = CEPH_INLINE_NONE;
102
103         if (features & CEPH_FEATURE_FS_FILE_LAYOUT_V2) {
104                 ceph_decode_32_safe(p, end, info->pool_ns_len, bad);
105                 ceph_decode_need(p, end, info->pool_ns_len, bad);
106                 *p += info->pool_ns_len;
107         } else {
108                 info->pool_ns_len = 0;
109         }
110
111         return 0;
112 bad:
113         return err;
114 }
115
116 /*
117  * parse a normal reply, which may contain a (dir+)dentry and/or a
118  * target inode.
119  */
120 static int parse_reply_info_trace(void **p, void *end,
121                                   struct ceph_mds_reply_info_parsed *info,
122                                   u64 features)
123 {
124         int err;
125
126         if (info->head->is_dentry) {
127                 err = parse_reply_info_in(p, end, &info->diri, features);
128                 if (err < 0)
129                         goto out_bad;
130
131                 if (unlikely(*p + sizeof(*info->dirfrag) > end))
132                         goto bad;
133                 info->dirfrag = *p;
134                 *p += sizeof(*info->dirfrag) +
135                         sizeof(u32)*le32_to_cpu(info->dirfrag->ndist);
136                 if (unlikely(*p > end))
137                         goto bad;
138
139                 ceph_decode_32_safe(p, end, info->dname_len, bad);
140                 ceph_decode_need(p, end, info->dname_len, bad);
141                 info->dname = *p;
142                 *p += info->dname_len;
143                 info->dlease = *p;
144                 *p += sizeof(*info->dlease);
145         }
146
147         if (info->head->is_target) {
148                 err = parse_reply_info_in(p, end, &info->targeti, features);
149                 if (err < 0)
150                         goto out_bad;
151         }
152
153         if (unlikely(*p != end))
154                 goto bad;
155         return 0;
156
157 bad:
158         err = -EIO;
159 out_bad:
160         pr_err("problem parsing mds trace %d\n", err);
161         return err;
162 }
163
164 /*
165  * parse readdir results
166  */
167 static int parse_reply_info_dir(void **p, void *end,
168                                 struct ceph_mds_reply_info_parsed *info,
169                                 u64 features)
170 {
171         u32 num, i = 0;
172         int err;
173
174         info->dir_dir = *p;
175         if (*p + sizeof(*info->dir_dir) > end)
176                 goto bad;
177         *p += sizeof(*info->dir_dir) +
178                 sizeof(u32)*le32_to_cpu(info->dir_dir->ndist);
179         if (*p > end)
180                 goto bad;
181
182         ceph_decode_need(p, end, sizeof(num) + 2, bad);
183         num = ceph_decode_32(p);
184         info->dir_end = ceph_decode_8(p);
185         info->dir_complete = ceph_decode_8(p);
186         if (num == 0)
187                 goto done;
188
189         BUG_ON(!info->dir_entries);
190         if ((unsigned long)(info->dir_entries + num) >
191             (unsigned long)info->dir_entries + info->dir_buf_size) {
192                 pr_err("dir contents are larger than expected\n");
193                 WARN_ON(1);
194                 goto bad;
195         }
196
197         info->dir_nr = num;
198         while (num) {
199                 struct ceph_mds_reply_dir_entry *rde = info->dir_entries + i;
200                 /* dentry */
201                 ceph_decode_need(p, end, sizeof(u32)*2, bad);
202                 rde->name_len = ceph_decode_32(p);
203                 ceph_decode_need(p, end, rde->name_len, bad);
204                 rde->name = *p;
205                 *p += rde->name_len;
206                 dout("parsed dir dname '%.*s'\n", rde->name_len, rde->name);
207                 rde->lease = *p;
208                 *p += sizeof(struct ceph_mds_reply_lease);
209
210                 /* inode */
211                 err = parse_reply_info_in(p, end, &rde->inode, features);
212                 if (err < 0)
213                         goto out_bad;
214                 i++;
215                 num--;
216         }
217
218 done:
219         if (*p != end)
220                 goto bad;
221         return 0;
222
223 bad:
224         err = -EIO;
225 out_bad:
226         pr_err("problem parsing dir contents %d\n", err);
227         return err;
228 }
229
230 /*
231  * parse fcntl F_GETLK results
232  */
233 static int parse_reply_info_filelock(void **p, void *end,
234                                      struct ceph_mds_reply_info_parsed *info,
235                                      u64 features)
236 {
237         if (*p + sizeof(*info->filelock_reply) > end)
238                 goto bad;
239
240         info->filelock_reply = *p;
241         *p += sizeof(*info->filelock_reply);
242
243         if (unlikely(*p != end))
244                 goto bad;
245         return 0;
246
247 bad:
248         return -EIO;
249 }
250
251 /*
252  * parse create results
253  */
254 static int parse_reply_info_create(void **p, void *end,
255                                   struct ceph_mds_reply_info_parsed *info,
256                                   u64 features)
257 {
258         if (features & CEPH_FEATURE_REPLY_CREATE_INODE) {
259                 if (*p == end) {
260                         info->has_create_ino = false;
261                 } else {
262                         info->has_create_ino = true;
263                         info->ino = ceph_decode_64(p);
264                 }
265         }
266
267         if (unlikely(*p != end))
268                 goto bad;
269         return 0;
270
271 bad:
272         return -EIO;
273 }
274
275 /*
276  * parse extra results
277  */
278 static int parse_reply_info_extra(void **p, void *end,
279                                   struct ceph_mds_reply_info_parsed *info,
280                                   u64 features)
281 {
282         if (info->head->op == CEPH_MDS_OP_GETFILELOCK)
283                 return parse_reply_info_filelock(p, end, info, features);
284         else if (info->head->op == CEPH_MDS_OP_READDIR ||
285                  info->head->op == CEPH_MDS_OP_LSSNAP)
286                 return parse_reply_info_dir(p, end, info, features);
287         else if (info->head->op == CEPH_MDS_OP_CREATE)
288                 return parse_reply_info_create(p, end, info, features);
289         else
290                 return -EIO;
291 }
292
293 /*
294  * parse entire mds reply
295  */
296 static int parse_reply_info(struct ceph_msg *msg,
297                             struct ceph_mds_reply_info_parsed *info,
298                             u64 features)
299 {
300         void *p, *end;
301         u32 len;
302         int err;
303
304         info->head = msg->front.iov_base;
305         p = msg->front.iov_base + sizeof(struct ceph_mds_reply_head);
306         end = p + msg->front.iov_len - sizeof(struct ceph_mds_reply_head);
307
308         /* trace */
309         ceph_decode_32_safe(&p, end, len, bad);
310         if (len > 0) {
311                 ceph_decode_need(&p, end, len, bad);
312                 err = parse_reply_info_trace(&p, p+len, info, features);
313                 if (err < 0)
314                         goto out_bad;
315         }
316
317         /* extra */
318         ceph_decode_32_safe(&p, end, len, bad);
319         if (len > 0) {
320                 ceph_decode_need(&p, end, len, bad);
321                 err = parse_reply_info_extra(&p, p+len, info, features);
322                 if (err < 0)
323                         goto out_bad;
324         }
325
326         /* snap blob */
327         ceph_decode_32_safe(&p, end, len, bad);
328         info->snapblob_len = len;
329         info->snapblob = p;
330         p += len;
331
332         if (p != end)
333                 goto bad;
334         return 0;
335
336 bad:
337         err = -EIO;
338 out_bad:
339         pr_err("mds parse_reply err %d\n", err);
340         return err;
341 }
342
343 static void destroy_reply_info(struct ceph_mds_reply_info_parsed *info)
344 {
345         if (!info->dir_entries)
346                 return;
347         free_pages((unsigned long)info->dir_entries, get_order(info->dir_buf_size));
348 }
349
350
351 /*
352  * sessions
353  */
354 const char *ceph_session_state_name(int s)
355 {
356         switch (s) {
357         case CEPH_MDS_SESSION_NEW: return "new";
358         case CEPH_MDS_SESSION_OPENING: return "opening";
359         case CEPH_MDS_SESSION_OPEN: return "open";
360         case CEPH_MDS_SESSION_HUNG: return "hung";
361         case CEPH_MDS_SESSION_CLOSING: return "closing";
362         case CEPH_MDS_SESSION_RESTARTING: return "restarting";
363         case CEPH_MDS_SESSION_RECONNECTING: return "reconnecting";
364         default: return "???";
365         }
366 }
367
368 static struct ceph_mds_session *get_session(struct ceph_mds_session *s)
369 {
370         if (atomic_inc_not_zero(&s->s_ref)) {
371                 dout("mdsc get_session %p %d -> %d\n", s,
372                      atomic_read(&s->s_ref)-1, atomic_read(&s->s_ref));
373                 return s;
374         } else {
375                 dout("mdsc get_session %p 0 -- FAIL", s);
376                 return NULL;
377         }
378 }
379
380 void ceph_put_mds_session(struct ceph_mds_session *s)
381 {
382         dout("mdsc put_session %p %d -> %d\n", s,
383              atomic_read(&s->s_ref), atomic_read(&s->s_ref)-1);
384         if (atomic_dec_and_test(&s->s_ref)) {
385                 if (s->s_auth.authorizer)
386                         ceph_auth_destroy_authorizer(s->s_auth.authorizer);
387                 kfree(s);
388         }
389 }
390
391 /*
392  * called under mdsc->mutex
393  */
394 struct ceph_mds_session *__ceph_lookup_mds_session(struct ceph_mds_client *mdsc,
395                                                    int mds)
396 {
397         struct ceph_mds_session *session;
398
399         if (mds >= mdsc->max_sessions || mdsc->sessions[mds] == NULL)
400                 return NULL;
401         session = mdsc->sessions[mds];
402         dout("lookup_mds_session %p %d\n", session,
403              atomic_read(&session->s_ref));
404         get_session(session);
405         return session;
406 }
407
408 static bool __have_session(struct ceph_mds_client *mdsc, int mds)
409 {
410         if (mds >= mdsc->max_sessions)
411                 return false;
412         return mdsc->sessions[mds];
413 }
414
415 static int __verify_registered_session(struct ceph_mds_client *mdsc,
416                                        struct ceph_mds_session *s)
417 {
418         if (s->s_mds >= mdsc->max_sessions ||
419             mdsc->sessions[s->s_mds] != s)
420                 return -ENOENT;
421         return 0;
422 }
423
424 /*
425  * create+register a new session for given mds.
426  * called under mdsc->mutex.
427  */
428 static struct ceph_mds_session *register_session(struct ceph_mds_client *mdsc,
429                                                  int mds)
430 {
431         struct ceph_mds_session *s;
432
433         if (mds >= mdsc->mdsmap->m_max_mds)
434                 return ERR_PTR(-EINVAL);
435
436         s = kzalloc(sizeof(*s), GFP_NOFS);
437         if (!s)
438                 return ERR_PTR(-ENOMEM);
439         s->s_mdsc = mdsc;
440         s->s_mds = mds;
441         s->s_state = CEPH_MDS_SESSION_NEW;
442         s->s_ttl = 0;
443         s->s_seq = 0;
444         mutex_init(&s->s_mutex);
445
446         ceph_con_init(&s->s_con, s, &mds_con_ops, &mdsc->fsc->client->msgr);
447
448         spin_lock_init(&s->s_gen_ttl_lock);
449         s->s_cap_gen = 0;
450         s->s_cap_ttl = jiffies - 1;
451
452         spin_lock_init(&s->s_cap_lock);
453         s->s_renew_requested = 0;
454         s->s_renew_seq = 0;
455         INIT_LIST_HEAD(&s->s_caps);
456         s->s_nr_caps = 0;
457         s->s_trim_caps = 0;
458         atomic_set(&s->s_ref, 1);
459         INIT_LIST_HEAD(&s->s_waiting);
460         INIT_LIST_HEAD(&s->s_unsafe);
461         s->s_num_cap_releases = 0;
462         s->s_cap_reconnect = 0;
463         s->s_cap_iterator = NULL;
464         INIT_LIST_HEAD(&s->s_cap_releases);
465         INIT_LIST_HEAD(&s->s_cap_flushing);
466         INIT_LIST_HEAD(&s->s_cap_snaps_flushing);
467
468         dout("register_session mds%d\n", mds);
469         if (mds >= mdsc->max_sessions) {
470                 int newmax = 1 << get_count_order(mds+1);
471                 struct ceph_mds_session **sa;
472
473                 dout("register_session realloc to %d\n", newmax);
474                 sa = kcalloc(newmax, sizeof(void *), GFP_NOFS);
475                 if (sa == NULL)
476                         goto fail_realloc;
477                 if (mdsc->sessions) {
478                         memcpy(sa, mdsc->sessions,
479                                mdsc->max_sessions * sizeof(void *));
480                         kfree(mdsc->sessions);
481                 }
482                 mdsc->sessions = sa;
483                 mdsc->max_sessions = newmax;
484         }
485         mdsc->sessions[mds] = s;
486         atomic_inc(&mdsc->num_sessions);
487         atomic_inc(&s->s_ref);  /* one ref to sessions[], one to caller */
488
489         ceph_con_open(&s->s_con, CEPH_ENTITY_TYPE_MDS, mds,
490                       ceph_mdsmap_get_addr(mdsc->mdsmap, mds));
491
492         return s;
493
494 fail_realloc:
495         kfree(s);
496         return ERR_PTR(-ENOMEM);
497 }
498
499 /*
500  * called under mdsc->mutex
501  */
502 static void __unregister_session(struct ceph_mds_client *mdsc,
503                                struct ceph_mds_session *s)
504 {
505         dout("__unregister_session mds%d %p\n", s->s_mds, s);
506         BUG_ON(mdsc->sessions[s->s_mds] != s);
507         mdsc->sessions[s->s_mds] = NULL;
508         ceph_con_close(&s->s_con);
509         ceph_put_mds_session(s);
510         atomic_dec(&mdsc->num_sessions);
511 }
512
513 /*
514  * drop session refs in request.
515  *
516  * should be last request ref, or hold mdsc->mutex
517  */
518 static void put_request_session(struct ceph_mds_request *req)
519 {
520         if (req->r_session) {
521                 ceph_put_mds_session(req->r_session);
522                 req->r_session = NULL;
523         }
524 }
525
526 void ceph_mdsc_release_request(struct kref *kref)
527 {
528         struct ceph_mds_request *req = container_of(kref,
529                                                     struct ceph_mds_request,
530                                                     r_kref);
531         destroy_reply_info(&req->r_reply_info);
532         if (req->r_request)
533                 ceph_msg_put(req->r_request);
534         if (req->r_reply)
535                 ceph_msg_put(req->r_reply);
536         if (req->r_inode) {
537                 ceph_put_cap_refs(ceph_inode(req->r_inode), CEPH_CAP_PIN);
538                 iput(req->r_inode);
539         }
540         if (req->r_locked_dir)
541                 ceph_put_cap_refs(ceph_inode(req->r_locked_dir), CEPH_CAP_PIN);
542         iput(req->r_target_inode);
543         if (req->r_dentry)
544                 dput(req->r_dentry);
545         if (req->r_old_dentry)
546                 dput(req->r_old_dentry);
547         if (req->r_old_dentry_dir) {
548                 /*
549                  * track (and drop pins for) r_old_dentry_dir
550                  * separately, since r_old_dentry's d_parent may have
551                  * changed between the dir mutex being dropped and
552                  * this request being freed.
553                  */
554                 ceph_put_cap_refs(ceph_inode(req->r_old_dentry_dir),
555                                   CEPH_CAP_PIN);
556                 iput(req->r_old_dentry_dir);
557         }
558         kfree(req->r_path1);
559         kfree(req->r_path2);
560         if (req->r_pagelist)
561                 ceph_pagelist_release(req->r_pagelist);
562         put_request_session(req);
563         ceph_unreserve_caps(req->r_mdsc, &req->r_caps_reservation);
564         kfree(req);
565 }
566
567 DEFINE_RB_FUNCS(request, struct ceph_mds_request, r_tid, r_node)
568
569 /*
570  * lookup session, bump ref if found.
571  *
572  * called under mdsc->mutex.
573  */
574 static struct ceph_mds_request *
575 lookup_get_request(struct ceph_mds_client *mdsc, u64 tid)
576 {
577         struct ceph_mds_request *req;
578
579         req = lookup_request(&mdsc->request_tree, tid);
580         if (req)
581                 ceph_mdsc_get_request(req);
582
583         return req;
584 }
585
586 /*
587  * Register an in-flight request, and assign a tid.  Link to directory
588  * are modifying (if any).
589  *
590  * Called under mdsc->mutex.
591  */
592 static void __register_request(struct ceph_mds_client *mdsc,
593                                struct ceph_mds_request *req,
594                                struct inode *dir)
595 {
596         req->r_tid = ++mdsc->last_tid;
597         if (req->r_num_caps)
598                 ceph_reserve_caps(mdsc, &req->r_caps_reservation,
599                                   req->r_num_caps);
600         dout("__register_request %p tid %lld\n", req, req->r_tid);
601         ceph_mdsc_get_request(req);
602         insert_request(&mdsc->request_tree, req);
603
604         req->r_uid = current_fsuid();
605         req->r_gid = current_fsgid();
606
607         if (mdsc->oldest_tid == 0 && req->r_op != CEPH_MDS_OP_SETFILELOCK)
608                 mdsc->oldest_tid = req->r_tid;
609
610         if (dir) {
611                 ihold(dir);
612                 req->r_unsafe_dir = dir;
613         }
614 }
615
616 static void __unregister_request(struct ceph_mds_client *mdsc,
617                                  struct ceph_mds_request *req)
618 {
619         dout("__unregister_request %p tid %lld\n", req, req->r_tid);
620
621         if (req->r_tid == mdsc->oldest_tid) {
622                 struct rb_node *p = rb_next(&req->r_node);
623                 mdsc->oldest_tid = 0;
624                 while (p) {
625                         struct ceph_mds_request *next_req =
626                                 rb_entry(p, struct ceph_mds_request, r_node);
627                         if (next_req->r_op != CEPH_MDS_OP_SETFILELOCK) {
628                                 mdsc->oldest_tid = next_req->r_tid;
629                                 break;
630                         }
631                         p = rb_next(p);
632                 }
633         }
634
635         erase_request(&mdsc->request_tree, req);
636
637         if (req->r_unsafe_dir && req->r_got_unsafe) {
638                 struct ceph_inode_info *ci = ceph_inode(req->r_unsafe_dir);
639                 spin_lock(&ci->i_unsafe_lock);
640                 list_del_init(&req->r_unsafe_dir_item);
641                 spin_unlock(&ci->i_unsafe_lock);
642         }
643         if (req->r_target_inode && req->r_got_unsafe) {
644                 struct ceph_inode_info *ci = ceph_inode(req->r_target_inode);
645                 spin_lock(&ci->i_unsafe_lock);
646                 list_del_init(&req->r_unsafe_target_item);
647                 spin_unlock(&ci->i_unsafe_lock);
648         }
649
650         if (req->r_unsafe_dir) {
651                 iput(req->r_unsafe_dir);
652                 req->r_unsafe_dir = NULL;
653         }
654
655         complete_all(&req->r_safe_completion);
656
657         ceph_mdsc_put_request(req);
658 }
659
660 /*
661  * Choose mds to send request to next.  If there is a hint set in the
662  * request (e.g., due to a prior forward hint from the mds), use that.
663  * Otherwise, consult frag tree and/or caps to identify the
664  * appropriate mds.  If all else fails, choose randomly.
665  *
666  * Called under mdsc->mutex.
667  */
668 static struct dentry *get_nonsnap_parent(struct dentry *dentry)
669 {
670         /*
671          * we don't need to worry about protecting the d_parent access
672          * here because we never renaming inside the snapped namespace
673          * except to resplice to another snapdir, and either the old or new
674          * result is a valid result.
675          */
676         while (!IS_ROOT(dentry) && ceph_snap(d_inode(dentry)) != CEPH_NOSNAP)
677                 dentry = dentry->d_parent;
678         return dentry;
679 }
680
681 static int __choose_mds(struct ceph_mds_client *mdsc,
682                         struct ceph_mds_request *req)
683 {
684         struct inode *inode;
685         struct ceph_inode_info *ci;
686         struct ceph_cap *cap;
687         int mode = req->r_direct_mode;
688         int mds = -1;
689         u32 hash = req->r_direct_hash;
690         bool is_hash = req->r_direct_is_hash;
691
692         /*
693          * is there a specific mds we should try?  ignore hint if we have
694          * no session and the mds is not up (active or recovering).
695          */
696         if (req->r_resend_mds >= 0 &&
697             (__have_session(mdsc, req->r_resend_mds) ||
698              ceph_mdsmap_get_state(mdsc->mdsmap, req->r_resend_mds) > 0)) {
699                 dout("choose_mds using resend_mds mds%d\n",
700                      req->r_resend_mds);
701                 return req->r_resend_mds;
702         }
703
704         if (mode == USE_RANDOM_MDS)
705                 goto random;
706
707         inode = NULL;
708         if (req->r_inode) {
709                 inode = req->r_inode;
710         } else if (req->r_dentry) {
711                 /* ignore race with rename; old or new d_parent is okay */
712                 struct dentry *parent = req->r_dentry->d_parent;
713                 struct inode *dir = d_inode(parent);
714
715                 if (dir->i_sb != mdsc->fsc->sb) {
716                         /* not this fs! */
717                         inode = d_inode(req->r_dentry);
718                 } else if (ceph_snap(dir) != CEPH_NOSNAP) {
719                         /* direct snapped/virtual snapdir requests
720                          * based on parent dir inode */
721                         struct dentry *dn = get_nonsnap_parent(parent);
722                         inode = d_inode(dn);
723                         dout("__choose_mds using nonsnap parent %p\n", inode);
724                 } else {
725                         /* dentry target */
726                         inode = d_inode(req->r_dentry);
727                         if (!inode || mode == USE_AUTH_MDS) {
728                                 /* dir + name */
729                                 inode = dir;
730                                 hash = ceph_dentry_hash(dir, req->r_dentry);
731                                 is_hash = true;
732                         }
733                 }
734         }
735
736         dout("__choose_mds %p is_hash=%d (%d) mode %d\n", inode, (int)is_hash,
737              (int)hash, mode);
738         if (!inode)
739                 goto random;
740         ci = ceph_inode(inode);
741
742         if (is_hash && S_ISDIR(inode->i_mode)) {
743                 struct ceph_inode_frag frag;
744                 int found;
745
746                 ceph_choose_frag(ci, hash, &frag, &found);
747                 if (found) {
748                         if (mode == USE_ANY_MDS && frag.ndist > 0) {
749                                 u8 r;
750
751                                 /* choose a random replica */
752                                 get_random_bytes(&r, 1);
753                                 r %= frag.ndist;
754                                 mds = frag.dist[r];
755                                 dout("choose_mds %p %llx.%llx "
756                                      "frag %u mds%d (%d/%d)\n",
757                                      inode, ceph_vinop(inode),
758                                      frag.frag, mds,
759                                      (int)r, frag.ndist);
760                                 if (ceph_mdsmap_get_state(mdsc->mdsmap, mds) >=
761                                     CEPH_MDS_STATE_ACTIVE)
762                                         return mds;
763                         }
764
765                         /* since this file/dir wasn't known to be
766                          * replicated, then we want to look for the
767                          * authoritative mds. */
768                         mode = USE_AUTH_MDS;
769                         if (frag.mds >= 0) {
770                                 /* choose auth mds */
771                                 mds = frag.mds;
772                                 dout("choose_mds %p %llx.%llx "
773                                      "frag %u mds%d (auth)\n",
774                                      inode, ceph_vinop(inode), frag.frag, mds);
775                                 if (ceph_mdsmap_get_state(mdsc->mdsmap, mds) >=
776                                     CEPH_MDS_STATE_ACTIVE)
777                                         return mds;
778                         }
779                 }
780         }
781
782         spin_lock(&ci->i_ceph_lock);
783         cap = NULL;
784         if (mode == USE_AUTH_MDS)
785                 cap = ci->i_auth_cap;
786         if (!cap && !RB_EMPTY_ROOT(&ci->i_caps))
787                 cap = rb_entry(rb_first(&ci->i_caps), struct ceph_cap, ci_node);
788         if (!cap) {
789                 spin_unlock(&ci->i_ceph_lock);
790                 goto random;
791         }
792         mds = cap->session->s_mds;
793         dout("choose_mds %p %llx.%llx mds%d (%scap %p)\n",
794              inode, ceph_vinop(inode), mds,
795              cap == ci->i_auth_cap ? "auth " : "", cap);
796         spin_unlock(&ci->i_ceph_lock);
797         return mds;
798
799 random:
800         mds = ceph_mdsmap_get_random_mds(mdsc->mdsmap);
801         dout("choose_mds chose random mds%d\n", mds);
802         return mds;
803 }
804
805
806 /*
807  * session messages
808  */
809 static struct ceph_msg *create_session_msg(u32 op, u64 seq)
810 {
811         struct ceph_msg *msg;
812         struct ceph_mds_session_head *h;
813
814         msg = ceph_msg_new(CEPH_MSG_CLIENT_SESSION, sizeof(*h), GFP_NOFS,
815                            false);
816         if (!msg) {
817                 pr_err("create_session_msg ENOMEM creating msg\n");
818                 return NULL;
819         }
820         h = msg->front.iov_base;
821         h->op = cpu_to_le32(op);
822         h->seq = cpu_to_le64(seq);
823
824         return msg;
825 }
826
827 /*
828  * session message, specialization for CEPH_SESSION_REQUEST_OPEN
829  * to include additional client metadata fields.
830  */
831 static struct ceph_msg *create_session_open_msg(struct ceph_mds_client *mdsc, u64 seq)
832 {
833         struct ceph_msg *msg;
834         struct ceph_mds_session_head *h;
835         int i = -1;
836         int metadata_bytes = 0;
837         int metadata_key_count = 0;
838         struct ceph_options *opt = mdsc->fsc->client->options;
839         struct ceph_mount_options *fsopt = mdsc->fsc->mount_options;
840         void *p;
841
842         const char* metadata[][2] = {
843                 {"hostname", utsname()->nodename},
844                 {"kernel_version", utsname()->release},
845                 {"entity_id", opt->name ? : ""},
846                 {"root", fsopt->server_path ? : "/"},
847                 {NULL, NULL}
848         };
849
850         /* Calculate serialized length of metadata */
851         metadata_bytes = 4;  /* map length */
852         for (i = 0; metadata[i][0] != NULL; ++i) {
853                 metadata_bytes += 8 + strlen(metadata[i][0]) +
854                         strlen(metadata[i][1]);
855                 metadata_key_count++;
856         }
857
858         /* Allocate the message */
859         msg = ceph_msg_new(CEPH_MSG_CLIENT_SESSION, sizeof(*h) + metadata_bytes,
860                            GFP_NOFS, false);
861         if (!msg) {
862                 pr_err("create_session_msg ENOMEM creating msg\n");
863                 return NULL;
864         }
865         h = msg->front.iov_base;
866         h->op = cpu_to_le32(CEPH_SESSION_REQUEST_OPEN);
867         h->seq = cpu_to_le64(seq);
868
869         /*
870          * Serialize client metadata into waiting buffer space, using
871          * the format that userspace expects for map<string, string>
872          *
873          * ClientSession messages with metadata are v2
874          */
875         msg->hdr.version = cpu_to_le16(2);
876         msg->hdr.compat_version = cpu_to_le16(1);
877
878         /* The write pointer, following the session_head structure */
879         p = msg->front.iov_base + sizeof(*h);
880
881         /* Number of entries in the map */
882         ceph_encode_32(&p, metadata_key_count);
883
884         /* Two length-prefixed strings for each entry in the map */
885         for (i = 0; metadata[i][0] != NULL; ++i) {
886                 size_t const key_len = strlen(metadata[i][0]);
887                 size_t const val_len = strlen(metadata[i][1]);
888
889                 ceph_encode_32(&p, key_len);
890                 memcpy(p, metadata[i][0], key_len);
891                 p += key_len;
892                 ceph_encode_32(&p, val_len);
893                 memcpy(p, metadata[i][1], val_len);
894                 p += val_len;
895         }
896
897         return msg;
898 }
899
900 /*
901  * send session open request.
902  *
903  * called under mdsc->mutex
904  */
905 static int __open_session(struct ceph_mds_client *mdsc,
906                           struct ceph_mds_session *session)
907 {
908         struct ceph_msg *msg;
909         int mstate;
910         int mds = session->s_mds;
911
912         /* wait for mds to go active? */
913         mstate = ceph_mdsmap_get_state(mdsc->mdsmap, mds);
914         dout("open_session to mds%d (%s)\n", mds,
915              ceph_mds_state_name(mstate));
916         session->s_state = CEPH_MDS_SESSION_OPENING;
917         session->s_renew_requested = jiffies;
918
919         /* send connect message */
920         msg = create_session_open_msg(mdsc, session->s_seq);
921         if (!msg)
922                 return -ENOMEM;
923         ceph_con_send(&session->s_con, msg);
924         return 0;
925 }
926
927 /*
928  * open sessions for any export targets for the given mds
929  *
930  * called under mdsc->mutex
931  */
932 static struct ceph_mds_session *
933 __open_export_target_session(struct ceph_mds_client *mdsc, int target)
934 {
935         struct ceph_mds_session *session;
936
937         session = __ceph_lookup_mds_session(mdsc, target);
938         if (!session) {
939                 session = register_session(mdsc, target);
940                 if (IS_ERR(session))
941                         return session;
942         }
943         if (session->s_state == CEPH_MDS_SESSION_NEW ||
944             session->s_state == CEPH_MDS_SESSION_CLOSING)
945                 __open_session(mdsc, session);
946
947         return session;
948 }
949
950 struct ceph_mds_session *
951 ceph_mdsc_open_export_target_session(struct ceph_mds_client *mdsc, int target)
952 {
953         struct ceph_mds_session *session;
954
955         dout("open_export_target_session to mds%d\n", target);
956
957         mutex_lock(&mdsc->mutex);
958         session = __open_export_target_session(mdsc, target);
959         mutex_unlock(&mdsc->mutex);
960
961         return session;
962 }
963
964 static void __open_export_target_sessions(struct ceph_mds_client *mdsc,
965                                           struct ceph_mds_session *session)
966 {
967         struct ceph_mds_info *mi;
968         struct ceph_mds_session *ts;
969         int i, mds = session->s_mds;
970
971         if (mds >= mdsc->mdsmap->m_max_mds)
972                 return;
973
974         mi = &mdsc->mdsmap->m_info[mds];
975         dout("open_export_target_sessions for mds%d (%d targets)\n",
976              session->s_mds, mi->num_export_targets);
977
978         for (i = 0; i < mi->num_export_targets; i++) {
979                 ts = __open_export_target_session(mdsc, mi->export_targets[i]);
980                 if (!IS_ERR(ts))
981                         ceph_put_mds_session(ts);
982         }
983 }
984
985 void ceph_mdsc_open_export_target_sessions(struct ceph_mds_client *mdsc,
986                                            struct ceph_mds_session *session)
987 {
988         mutex_lock(&mdsc->mutex);
989         __open_export_target_sessions(mdsc, session);
990         mutex_unlock(&mdsc->mutex);
991 }
992
993 /*
994  * session caps
995  */
996
997 /* caller holds s_cap_lock, we drop it */
998 static void cleanup_cap_releases(struct ceph_mds_client *mdsc,
999                                  struct ceph_mds_session *session)
1000         __releases(session->s_cap_lock)
1001 {
1002         LIST_HEAD(tmp_list);
1003         list_splice_init(&session->s_cap_releases, &tmp_list);
1004         session->s_num_cap_releases = 0;
1005         spin_unlock(&session->s_cap_lock);
1006
1007         dout("cleanup_cap_releases mds%d\n", session->s_mds);
1008         while (!list_empty(&tmp_list)) {
1009                 struct ceph_cap *cap;
1010                 /* zero out the in-progress message */
1011                 cap = list_first_entry(&tmp_list,
1012                                         struct ceph_cap, session_caps);
1013                 list_del(&cap->session_caps);
1014                 ceph_put_cap(mdsc, cap);
1015         }
1016 }
1017
1018 static void cleanup_session_requests(struct ceph_mds_client *mdsc,
1019                                      struct ceph_mds_session *session)
1020 {
1021         struct ceph_mds_request *req;
1022         struct rb_node *p;
1023
1024         dout("cleanup_session_requests mds%d\n", session->s_mds);
1025         mutex_lock(&mdsc->mutex);
1026         while (!list_empty(&session->s_unsafe)) {
1027                 req = list_first_entry(&session->s_unsafe,
1028                                        struct ceph_mds_request, r_unsafe_item);
1029                 list_del_init(&req->r_unsafe_item);
1030                 pr_warn_ratelimited(" dropping unsafe request %llu\n",
1031                                     req->r_tid);
1032                 __unregister_request(mdsc, req);
1033         }
1034         /* zero r_attempts, so kick_requests() will re-send requests */
1035         p = rb_first(&mdsc->request_tree);
1036         while (p) {
1037                 req = rb_entry(p, struct ceph_mds_request, r_node);
1038                 p = rb_next(p);
1039                 if (req->r_session &&
1040                     req->r_session->s_mds == session->s_mds)
1041                         req->r_attempts = 0;
1042         }
1043         mutex_unlock(&mdsc->mutex);
1044 }
1045
1046 /*
1047  * Helper to safely iterate over all caps associated with a session, with
1048  * special care taken to handle a racing __ceph_remove_cap().
1049  *
1050  * Caller must hold session s_mutex.
1051  */
1052 static int iterate_session_caps(struct ceph_mds_session *session,
1053                                  int (*cb)(struct inode *, struct ceph_cap *,
1054                                             void *), void *arg)
1055 {
1056         struct list_head *p;
1057         struct ceph_cap *cap;
1058         struct inode *inode, *last_inode = NULL;
1059         struct ceph_cap *old_cap = NULL;
1060         int ret;
1061
1062         dout("iterate_session_caps %p mds%d\n", session, session->s_mds);
1063         spin_lock(&session->s_cap_lock);
1064         p = session->s_caps.next;
1065         while (p != &session->s_caps) {
1066                 cap = list_entry(p, struct ceph_cap, session_caps);
1067                 inode = igrab(&cap->ci->vfs_inode);
1068                 if (!inode) {
1069                         p = p->next;
1070                         continue;
1071                 }
1072                 session->s_cap_iterator = cap;
1073                 spin_unlock(&session->s_cap_lock);
1074
1075                 if (last_inode) {
1076                         iput(last_inode);
1077                         last_inode = NULL;
1078                 }
1079                 if (old_cap) {
1080                         ceph_put_cap(session->s_mdsc, old_cap);
1081                         old_cap = NULL;
1082                 }
1083
1084                 ret = cb(inode, cap, arg);
1085                 last_inode = inode;
1086
1087                 spin_lock(&session->s_cap_lock);
1088                 p = p->next;
1089                 if (cap->ci == NULL) {
1090                         dout("iterate_session_caps  finishing cap %p removal\n",
1091                              cap);
1092                         BUG_ON(cap->session != session);
1093                         cap->session = NULL;
1094                         list_del_init(&cap->session_caps);
1095                         session->s_nr_caps--;
1096                         if (cap->queue_release) {
1097                                 list_add_tail(&cap->session_caps,
1098                                               &session->s_cap_releases);
1099                                 session->s_num_cap_releases++;
1100                         } else {
1101                                 old_cap = cap;  /* put_cap it w/o locks held */
1102                         }
1103                 }
1104                 if (ret < 0)
1105                         goto out;
1106         }
1107         ret = 0;
1108 out:
1109         session->s_cap_iterator = NULL;
1110         spin_unlock(&session->s_cap_lock);
1111
1112         iput(last_inode);
1113         if (old_cap)
1114                 ceph_put_cap(session->s_mdsc, old_cap);
1115
1116         return ret;
1117 }
1118
1119 static int remove_session_caps_cb(struct inode *inode, struct ceph_cap *cap,
1120                                   void *arg)
1121 {
1122         struct ceph_fs_client *fsc = (struct ceph_fs_client *)arg;
1123         struct ceph_inode_info *ci = ceph_inode(inode);
1124         LIST_HEAD(to_remove);
1125         bool drop = false;
1126         bool invalidate = false;
1127
1128         dout("removing cap %p, ci is %p, inode is %p\n",
1129              cap, ci, &ci->vfs_inode);
1130         spin_lock(&ci->i_ceph_lock);
1131         __ceph_remove_cap(cap, false);
1132         if (!ci->i_auth_cap) {
1133                 struct ceph_cap_flush *cf;
1134                 struct ceph_mds_client *mdsc = fsc->mdsc;
1135
1136                 ci->i_ceph_flags |= CEPH_I_CAP_DROPPED;
1137
1138                 if (ci->i_wrbuffer_ref > 0 &&
1139                     ACCESS_ONCE(fsc->mount_state) == CEPH_MOUNT_SHUTDOWN)
1140                         invalidate = true;
1141
1142                 while (true) {
1143                         struct rb_node *n = rb_first(&ci->i_cap_flush_tree);
1144                         if (!n)
1145                                 break;
1146                         cf = rb_entry(n, struct ceph_cap_flush, i_node);
1147                         rb_erase(&cf->i_node, &ci->i_cap_flush_tree);
1148                         list_add(&cf->list, &to_remove);
1149                 }
1150
1151                 spin_lock(&mdsc->cap_dirty_lock);
1152
1153                 list_for_each_entry(cf, &to_remove, list)
1154                         rb_erase(&cf->g_node, &mdsc->cap_flush_tree);
1155
1156                 if (!list_empty(&ci->i_dirty_item)) {
1157                         pr_warn_ratelimited(
1158                                 " dropping dirty %s state for %p %lld\n",
1159                                 ceph_cap_string(ci->i_dirty_caps),
1160                                 inode, ceph_ino(inode));
1161                         ci->i_dirty_caps = 0;
1162                         list_del_init(&ci->i_dirty_item);
1163                         drop = true;
1164                 }
1165                 if (!list_empty(&ci->i_flushing_item)) {
1166                         pr_warn_ratelimited(
1167                                 " dropping dirty+flushing %s state for %p %lld\n",
1168                                 ceph_cap_string(ci->i_flushing_caps),
1169                                 inode, ceph_ino(inode));
1170                         ci->i_flushing_caps = 0;
1171                         list_del_init(&ci->i_flushing_item);
1172                         mdsc->num_cap_flushing--;
1173                         drop = true;
1174                 }
1175                 spin_unlock(&mdsc->cap_dirty_lock);
1176
1177                 if (!ci->i_dirty_caps && ci->i_prealloc_cap_flush) {
1178                         list_add(&ci->i_prealloc_cap_flush->list, &to_remove);
1179                         ci->i_prealloc_cap_flush = NULL;
1180                 }
1181         }
1182         spin_unlock(&ci->i_ceph_lock);
1183         while (!list_empty(&to_remove)) {
1184                 struct ceph_cap_flush *cf;
1185                 cf = list_first_entry(&to_remove,
1186                                       struct ceph_cap_flush, list);
1187                 list_del(&cf->list);
1188                 ceph_free_cap_flush(cf);
1189         }
1190
1191         wake_up_all(&ci->i_cap_wq);
1192         if (invalidate)
1193                 ceph_queue_invalidate(inode);
1194         if (drop)
1195                 iput(inode);
1196         return 0;
1197 }
1198
1199 /*
1200  * caller must hold session s_mutex
1201  */
1202 static void remove_session_caps(struct ceph_mds_session *session)
1203 {
1204         struct ceph_fs_client *fsc = session->s_mdsc->fsc;
1205         struct super_block *sb = fsc->sb;
1206         dout("remove_session_caps on %p\n", session);
1207         iterate_session_caps(session, remove_session_caps_cb, fsc);
1208
1209         spin_lock(&session->s_cap_lock);
1210         if (session->s_nr_caps > 0) {
1211                 struct inode *inode;
1212                 struct ceph_cap *cap, *prev = NULL;
1213                 struct ceph_vino vino;
1214                 /*
1215                  * iterate_session_caps() skips inodes that are being
1216                  * deleted, we need to wait until deletions are complete.
1217                  * __wait_on_freeing_inode() is designed for the job,
1218                  * but it is not exported, so use lookup inode function
1219                  * to access it.
1220                  */
1221                 while (!list_empty(&session->s_caps)) {
1222                         cap = list_entry(session->s_caps.next,
1223                                          struct ceph_cap, session_caps);
1224                         if (cap == prev)
1225                                 break;
1226                         prev = cap;
1227                         vino = cap->ci->i_vino;
1228                         spin_unlock(&session->s_cap_lock);
1229
1230                         inode = ceph_find_inode(sb, vino);
1231                         iput(inode);
1232
1233                         spin_lock(&session->s_cap_lock);
1234                 }
1235         }
1236
1237         // drop cap expires and unlock s_cap_lock
1238         cleanup_cap_releases(session->s_mdsc, session);
1239
1240         BUG_ON(session->s_nr_caps > 0);
1241         BUG_ON(!list_empty(&session->s_cap_flushing));
1242 }
1243
1244 /*
1245  * wake up any threads waiting on this session's caps.  if the cap is
1246  * old (didn't get renewed on the client reconnect), remove it now.
1247  *
1248  * caller must hold s_mutex.
1249  */
1250 static int wake_up_session_cb(struct inode *inode, struct ceph_cap *cap,
1251                               void *arg)
1252 {
1253         struct ceph_inode_info *ci = ceph_inode(inode);
1254
1255         wake_up_all(&ci->i_cap_wq);
1256         if (arg) {
1257                 spin_lock(&ci->i_ceph_lock);
1258                 ci->i_wanted_max_size = 0;
1259                 ci->i_requested_max_size = 0;
1260                 spin_unlock(&ci->i_ceph_lock);
1261         }
1262         return 0;
1263 }
1264
1265 static void wake_up_session_caps(struct ceph_mds_session *session,
1266                                  int reconnect)
1267 {
1268         dout("wake_up_session_caps %p mds%d\n", session, session->s_mds);
1269         iterate_session_caps(session, wake_up_session_cb,
1270                              (void *)(unsigned long)reconnect);
1271 }
1272
1273 /*
1274  * Send periodic message to MDS renewing all currently held caps.  The
1275  * ack will reset the expiration for all caps from this session.
1276  *
1277  * caller holds s_mutex
1278  */
1279 static int send_renew_caps(struct ceph_mds_client *mdsc,
1280                            struct ceph_mds_session *session)
1281 {
1282         struct ceph_msg *msg;
1283         int state;
1284
1285         if (time_after_eq(jiffies, session->s_cap_ttl) &&
1286             time_after_eq(session->s_cap_ttl, session->s_renew_requested))
1287                 pr_info("mds%d caps stale\n", session->s_mds);
1288         session->s_renew_requested = jiffies;
1289
1290         /* do not try to renew caps until a recovering mds has reconnected
1291          * with its clients. */
1292         state = ceph_mdsmap_get_state(mdsc->mdsmap, session->s_mds);
1293         if (state < CEPH_MDS_STATE_RECONNECT) {
1294                 dout("send_renew_caps ignoring mds%d (%s)\n",
1295                      session->s_mds, ceph_mds_state_name(state));
1296                 return 0;
1297         }
1298
1299         dout("send_renew_caps to mds%d (%s)\n", session->s_mds,
1300                 ceph_mds_state_name(state));
1301         msg = create_session_msg(CEPH_SESSION_REQUEST_RENEWCAPS,
1302                                  ++session->s_renew_seq);
1303         if (!msg)
1304                 return -ENOMEM;
1305         ceph_con_send(&session->s_con, msg);
1306         return 0;
1307 }
1308
1309 static int send_flushmsg_ack(struct ceph_mds_client *mdsc,
1310                              struct ceph_mds_session *session, u64 seq)
1311 {
1312         struct ceph_msg *msg;
1313
1314         dout("send_flushmsg_ack to mds%d (%s)s seq %lld\n",
1315              session->s_mds, ceph_session_state_name(session->s_state), seq);
1316         msg = create_session_msg(CEPH_SESSION_FLUSHMSG_ACK, seq);
1317         if (!msg)
1318                 return -ENOMEM;
1319         ceph_con_send(&session->s_con, msg);
1320         return 0;
1321 }
1322
1323
1324 /*
1325  * Note new cap ttl, and any transition from stale -> not stale (fresh?).
1326  *
1327  * Called under session->s_mutex
1328  */
1329 static void renewed_caps(struct ceph_mds_client *mdsc,
1330                          struct ceph_mds_session *session, int is_renew)
1331 {
1332         int was_stale;
1333         int wake = 0;
1334
1335         spin_lock(&session->s_cap_lock);
1336         was_stale = is_renew && time_after_eq(jiffies, session->s_cap_ttl);
1337
1338         session->s_cap_ttl = session->s_renew_requested +
1339                 mdsc->mdsmap->m_session_timeout*HZ;
1340
1341         if (was_stale) {
1342                 if (time_before(jiffies, session->s_cap_ttl)) {
1343                         pr_info("mds%d caps renewed\n", session->s_mds);
1344                         wake = 1;
1345                 } else {
1346                         pr_info("mds%d caps still stale\n", session->s_mds);
1347                 }
1348         }
1349         dout("renewed_caps mds%d ttl now %lu, was %s, now %s\n",
1350              session->s_mds, session->s_cap_ttl, was_stale ? "stale" : "fresh",
1351              time_before(jiffies, session->s_cap_ttl) ? "stale" : "fresh");
1352         spin_unlock(&session->s_cap_lock);
1353
1354         if (wake)
1355                 wake_up_session_caps(session, 0);
1356 }
1357
1358 /*
1359  * send a session close request
1360  */
1361 static int request_close_session(struct ceph_mds_client *mdsc,
1362                                  struct ceph_mds_session *session)
1363 {
1364         struct ceph_msg *msg;
1365
1366         dout("request_close_session mds%d state %s seq %lld\n",
1367              session->s_mds, ceph_session_state_name(session->s_state),
1368              session->s_seq);
1369         msg = create_session_msg(CEPH_SESSION_REQUEST_CLOSE, session->s_seq);
1370         if (!msg)
1371                 return -ENOMEM;
1372         ceph_con_send(&session->s_con, msg);
1373         return 0;
1374 }
1375
1376 /*
1377  * Called with s_mutex held.
1378  */
1379 static int __close_session(struct ceph_mds_client *mdsc,
1380                          struct ceph_mds_session *session)
1381 {
1382         if (session->s_state >= CEPH_MDS_SESSION_CLOSING)
1383                 return 0;
1384         session->s_state = CEPH_MDS_SESSION_CLOSING;
1385         return request_close_session(mdsc, session);
1386 }
1387
1388 /*
1389  * Trim old(er) caps.
1390  *
1391  * Because we can't cache an inode without one or more caps, we do
1392  * this indirectly: if a cap is unused, we prune its aliases, at which
1393  * point the inode will hopefully get dropped to.
1394  *
1395  * Yes, this is a bit sloppy.  Our only real goal here is to respond to
1396  * memory pressure from the MDS, though, so it needn't be perfect.
1397  */
1398 static int trim_caps_cb(struct inode *inode, struct ceph_cap *cap, void *arg)
1399 {
1400         struct ceph_mds_session *session = arg;
1401         struct ceph_inode_info *ci = ceph_inode(inode);
1402         int used, wanted, oissued, mine;
1403
1404         if (session->s_trim_caps <= 0)
1405                 return -1;
1406
1407         spin_lock(&ci->i_ceph_lock);
1408         mine = cap->issued | cap->implemented;
1409         used = __ceph_caps_used(ci);
1410         wanted = __ceph_caps_file_wanted(ci);
1411         oissued = __ceph_caps_issued_other(ci, cap);
1412
1413         dout("trim_caps_cb %p cap %p mine %s oissued %s used %s wanted %s\n",
1414              inode, cap, ceph_cap_string(mine), ceph_cap_string(oissued),
1415              ceph_cap_string(used), ceph_cap_string(wanted));
1416         if (cap == ci->i_auth_cap) {
1417                 if (ci->i_dirty_caps || ci->i_flushing_caps ||
1418                     !list_empty(&ci->i_cap_snaps))
1419                         goto out;
1420                 if ((used | wanted) & CEPH_CAP_ANY_WR)
1421                         goto out;
1422         }
1423         /* The inode has cached pages, but it's no longer used.
1424          * we can safely drop it */
1425         if (wanted == 0 && used == CEPH_CAP_FILE_CACHE &&
1426             !(oissued & CEPH_CAP_FILE_CACHE)) {
1427           used = 0;
1428           oissued = 0;
1429         }
1430         if ((used | wanted) & ~oissued & mine)
1431                 goto out;   /* we need these caps */
1432
1433         session->s_trim_caps--;
1434         if (oissued) {
1435                 /* we aren't the only cap.. just remove us */
1436                 __ceph_remove_cap(cap, true);
1437         } else {
1438                 /* try dropping referring dentries */
1439                 spin_unlock(&ci->i_ceph_lock);
1440                 d_prune_aliases(inode);
1441                 dout("trim_caps_cb %p cap %p  pruned, count now %d\n",
1442                      inode, cap, atomic_read(&inode->i_count));
1443                 return 0;
1444         }
1445
1446 out:
1447         spin_unlock(&ci->i_ceph_lock);
1448         return 0;
1449 }
1450
1451 /*
1452  * Trim session cap count down to some max number.
1453  */
1454 static int trim_caps(struct ceph_mds_client *mdsc,
1455                      struct ceph_mds_session *session,
1456                      int max_caps)
1457 {
1458         int trim_caps = session->s_nr_caps - max_caps;
1459
1460         dout("trim_caps mds%d start: %d / %d, trim %d\n",
1461              session->s_mds, session->s_nr_caps, max_caps, trim_caps);
1462         if (trim_caps > 0) {
1463                 session->s_trim_caps = trim_caps;
1464                 iterate_session_caps(session, trim_caps_cb, session);
1465                 dout("trim_caps mds%d done: %d / %d, trimmed %d\n",
1466                      session->s_mds, session->s_nr_caps, max_caps,
1467                         trim_caps - session->s_trim_caps);
1468                 session->s_trim_caps = 0;
1469         }
1470
1471         ceph_send_cap_releases(mdsc, session);
1472         return 0;
1473 }
1474
1475 static int check_capsnap_flush(struct ceph_inode_info *ci,
1476                                u64 want_snap_seq)
1477 {
1478         int ret = 1;
1479         spin_lock(&ci->i_ceph_lock);
1480         if (want_snap_seq > 0 && !list_empty(&ci->i_cap_snaps)) {
1481                 struct ceph_cap_snap *capsnap =
1482                         list_first_entry(&ci->i_cap_snaps,
1483                                          struct ceph_cap_snap, ci_item);
1484                 ret = capsnap->follows >= want_snap_seq;
1485         }
1486         spin_unlock(&ci->i_ceph_lock);
1487         return ret;
1488 }
1489
1490 static int check_caps_flush(struct ceph_mds_client *mdsc,
1491                             u64 want_flush_tid)
1492 {
1493         struct rb_node *n;
1494         struct ceph_cap_flush *cf;
1495         int ret = 1;
1496
1497         spin_lock(&mdsc->cap_dirty_lock);
1498         n = rb_first(&mdsc->cap_flush_tree);
1499         cf = n ? rb_entry(n, struct ceph_cap_flush, g_node) : NULL;
1500         if (cf && cf->tid <= want_flush_tid) {
1501                 dout("check_caps_flush still flushing tid %llu <= %llu\n",
1502                      cf->tid, want_flush_tid);
1503                 ret = 0;
1504         }
1505         spin_unlock(&mdsc->cap_dirty_lock);
1506         return ret;
1507 }
1508
1509 /*
1510  * flush all dirty inode data to disk.
1511  *
1512  * returns true if we've flushed through want_flush_tid
1513  */
1514 static void wait_caps_flush(struct ceph_mds_client *mdsc,
1515                             u64 want_flush_tid, u64 want_snap_seq)
1516 {
1517         int mds;
1518
1519         dout("check_caps_flush want %llu snap want %llu\n",
1520              want_flush_tid, want_snap_seq);
1521         mutex_lock(&mdsc->mutex);
1522         for (mds = 0; mds < mdsc->max_sessions; ) {
1523                 struct ceph_mds_session *session = mdsc->sessions[mds];
1524                 struct inode *inode = NULL;
1525
1526                 if (!session) {
1527                         mds++;
1528                         continue;
1529                 }
1530                 get_session(session);
1531                 mutex_unlock(&mdsc->mutex);
1532
1533                 mutex_lock(&session->s_mutex);
1534                 if (!list_empty(&session->s_cap_snaps_flushing)) {
1535                         struct ceph_cap_snap *capsnap =
1536                                 list_first_entry(&session->s_cap_snaps_flushing,
1537                                                  struct ceph_cap_snap,
1538                                                  flushing_item);
1539                         struct ceph_inode_info *ci = capsnap->ci;
1540                         if (!check_capsnap_flush(ci, want_snap_seq)) {
1541                                 dout("check_cap_flush still flushing snap %p "
1542                                      "follows %lld <= %lld to mds%d\n",
1543                                      &ci->vfs_inode, capsnap->follows,
1544                                      want_snap_seq, mds);
1545                                 inode = igrab(&ci->vfs_inode);
1546                         }
1547                 }
1548                 mutex_unlock(&session->s_mutex);
1549                 ceph_put_mds_session(session);
1550
1551                 if (inode) {
1552                         wait_event(mdsc->cap_flushing_wq,
1553                                    check_capsnap_flush(ceph_inode(inode),
1554                                                        want_snap_seq));
1555                         iput(inode);
1556                 } else {
1557                         mds++;
1558                 }
1559
1560                 mutex_lock(&mdsc->mutex);
1561         }
1562         mutex_unlock(&mdsc->mutex);
1563
1564         wait_event(mdsc->cap_flushing_wq,
1565                    check_caps_flush(mdsc, want_flush_tid));
1566
1567         dout("check_caps_flush ok, flushed thru %llu\n", want_flush_tid);
1568 }
1569
1570 /*
1571  * called under s_mutex
1572  */
1573 void ceph_send_cap_releases(struct ceph_mds_client *mdsc,
1574                             struct ceph_mds_session *session)
1575 {
1576         struct ceph_msg *msg = NULL;
1577         struct ceph_mds_cap_release *head;
1578         struct ceph_mds_cap_item *item;
1579         struct ceph_cap *cap;
1580         LIST_HEAD(tmp_list);
1581         int num_cap_releases;
1582
1583         spin_lock(&session->s_cap_lock);
1584 again:
1585         list_splice_init(&session->s_cap_releases, &tmp_list);
1586         num_cap_releases = session->s_num_cap_releases;
1587         session->s_num_cap_releases = 0;
1588         spin_unlock(&session->s_cap_lock);
1589
1590         while (!list_empty(&tmp_list)) {
1591                 if (!msg) {
1592                         msg = ceph_msg_new(CEPH_MSG_CLIENT_CAPRELEASE,
1593                                         PAGE_SIZE, GFP_NOFS, false);
1594                         if (!msg)
1595                                 goto out_err;
1596                         head = msg->front.iov_base;
1597                         head->num = cpu_to_le32(0);
1598                         msg->front.iov_len = sizeof(*head);
1599                 }
1600                 cap = list_first_entry(&tmp_list, struct ceph_cap,
1601                                         session_caps);
1602                 list_del(&cap->session_caps);
1603                 num_cap_releases--;
1604
1605                 head = msg->front.iov_base;
1606                 le32_add_cpu(&head->num, 1);
1607                 item = msg->front.iov_base + msg->front.iov_len;
1608                 item->ino = cpu_to_le64(cap->cap_ino);
1609                 item->cap_id = cpu_to_le64(cap->cap_id);
1610                 item->migrate_seq = cpu_to_le32(cap->mseq);
1611                 item->seq = cpu_to_le32(cap->issue_seq);
1612                 msg->front.iov_len += sizeof(*item);
1613
1614                 ceph_put_cap(mdsc, cap);
1615
1616                 if (le32_to_cpu(head->num) == CEPH_CAPS_PER_RELEASE) {
1617                         msg->hdr.front_len = cpu_to_le32(msg->front.iov_len);
1618                         dout("send_cap_releases mds%d %p\n", session->s_mds, msg);
1619                         ceph_con_send(&session->s_con, msg);
1620                         msg = NULL;
1621                 }
1622         }
1623
1624         BUG_ON(num_cap_releases != 0);
1625
1626         spin_lock(&session->s_cap_lock);
1627         if (!list_empty(&session->s_cap_releases))
1628                 goto again;
1629         spin_unlock(&session->s_cap_lock);
1630
1631         if (msg) {
1632                 msg->hdr.front_len = cpu_to_le32(msg->front.iov_len);
1633                 dout("send_cap_releases mds%d %p\n", session->s_mds, msg);
1634                 ceph_con_send(&session->s_con, msg);
1635         }
1636         return;
1637 out_err:
1638         pr_err("send_cap_releases mds%d, failed to allocate message\n",
1639                 session->s_mds);
1640         spin_lock(&session->s_cap_lock);
1641         list_splice(&tmp_list, &session->s_cap_releases);
1642         session->s_num_cap_releases += num_cap_releases;
1643         spin_unlock(&session->s_cap_lock);
1644 }
1645
1646 /*
1647  * requests
1648  */
1649
1650 int ceph_alloc_readdir_reply_buffer(struct ceph_mds_request *req,
1651                                     struct inode *dir)
1652 {
1653         struct ceph_inode_info *ci = ceph_inode(dir);
1654         struct ceph_mds_reply_info_parsed *rinfo = &req->r_reply_info;
1655         struct ceph_mount_options *opt = req->r_mdsc->fsc->mount_options;
1656         size_t size = sizeof(struct ceph_mds_reply_dir_entry);
1657         int order, num_entries;
1658
1659         spin_lock(&ci->i_ceph_lock);
1660         num_entries = ci->i_files + ci->i_subdirs;
1661         spin_unlock(&ci->i_ceph_lock);
1662         num_entries = max(num_entries, 1);
1663         num_entries = min(num_entries, opt->max_readdir);
1664
1665         order = get_order(size * num_entries);
1666         while (order >= 0) {
1667                 rinfo->dir_entries = (void*)__get_free_pages(GFP_KERNEL |
1668                                                              __GFP_NOWARN,
1669                                                              order);
1670                 if (rinfo->dir_entries)
1671                         break;
1672                 order--;
1673         }
1674         if (!rinfo->dir_entries)
1675                 return -ENOMEM;
1676
1677         num_entries = (PAGE_SIZE << order) / size;
1678         num_entries = min(num_entries, opt->max_readdir);
1679
1680         rinfo->dir_buf_size = PAGE_SIZE << order;
1681         req->r_num_caps = num_entries + 1;
1682         req->r_args.readdir.max_entries = cpu_to_le32(num_entries);
1683         req->r_args.readdir.max_bytes = cpu_to_le32(opt->max_readdir_bytes);
1684         return 0;
1685 }
1686
1687 /*
1688  * Create an mds request.
1689  */
1690 struct ceph_mds_request *
1691 ceph_mdsc_create_request(struct ceph_mds_client *mdsc, int op, int mode)
1692 {
1693         struct ceph_mds_request *req = kzalloc(sizeof(*req), GFP_NOFS);
1694
1695         if (!req)
1696                 return ERR_PTR(-ENOMEM);
1697
1698         mutex_init(&req->r_fill_mutex);
1699         req->r_mdsc = mdsc;
1700         req->r_started = jiffies;
1701         req->r_resend_mds = -1;
1702         INIT_LIST_HEAD(&req->r_unsafe_dir_item);
1703         INIT_LIST_HEAD(&req->r_unsafe_target_item);
1704         req->r_fmode = -1;
1705         kref_init(&req->r_kref);
1706         RB_CLEAR_NODE(&req->r_node);
1707         INIT_LIST_HEAD(&req->r_wait);
1708         init_completion(&req->r_completion);
1709         init_completion(&req->r_safe_completion);
1710         INIT_LIST_HEAD(&req->r_unsafe_item);
1711
1712         req->r_stamp = current_fs_time(mdsc->fsc->sb);
1713
1714         req->r_op = op;
1715         req->r_direct_mode = mode;
1716         return req;
1717 }
1718
1719 /*
1720  * return oldest (lowest) request, tid in request tree, 0 if none.
1721  *
1722  * called under mdsc->mutex.
1723  */
1724 static struct ceph_mds_request *__get_oldest_req(struct ceph_mds_client *mdsc)
1725 {
1726         if (RB_EMPTY_ROOT(&mdsc->request_tree))
1727                 return NULL;
1728         return rb_entry(rb_first(&mdsc->request_tree),
1729                         struct ceph_mds_request, r_node);
1730 }
1731
1732 static inline  u64 __get_oldest_tid(struct ceph_mds_client *mdsc)
1733 {
1734         return mdsc->oldest_tid;
1735 }
1736
1737 /*
1738  * Build a dentry's path.  Allocate on heap; caller must kfree.  Based
1739  * on build_path_from_dentry in fs/cifs/dir.c.
1740  *
1741  * If @stop_on_nosnap, generate path relative to the first non-snapped
1742  * inode.
1743  *
1744  * Encode hidden .snap dirs as a double /, i.e.
1745  *   foo/.snap/bar -> foo//bar
1746  */
1747 char *ceph_mdsc_build_path(struct dentry *dentry, int *plen, u64 *base,
1748                            int stop_on_nosnap)
1749 {
1750         struct dentry *temp;
1751         char *path;
1752         int len, pos;
1753         unsigned seq;
1754
1755         if (dentry == NULL)
1756                 return ERR_PTR(-EINVAL);
1757
1758 retry:
1759         len = 0;
1760         seq = read_seqbegin(&rename_lock);
1761         rcu_read_lock();
1762         for (temp = dentry; !IS_ROOT(temp);) {
1763                 struct inode *inode = d_inode(temp);
1764                 if (inode && ceph_snap(inode) == CEPH_SNAPDIR)
1765                         len++;  /* slash only */
1766                 else if (stop_on_nosnap && inode &&
1767                          ceph_snap(inode) == CEPH_NOSNAP)
1768                         break;
1769                 else
1770                         len += 1 + temp->d_name.len;
1771                 temp = temp->d_parent;
1772         }
1773         rcu_read_unlock();
1774         if (len)
1775                 len--;  /* no leading '/' */
1776
1777         path = kmalloc(len+1, GFP_NOFS);
1778         if (path == NULL)
1779                 return ERR_PTR(-ENOMEM);
1780         pos = len;
1781         path[pos] = 0;  /* trailing null */
1782         rcu_read_lock();
1783         for (temp = dentry; !IS_ROOT(temp) && pos != 0; ) {
1784                 struct inode *inode;
1785
1786                 spin_lock(&temp->d_lock);
1787                 inode = d_inode(temp);
1788                 if (inode && ceph_snap(inode) == CEPH_SNAPDIR) {
1789                         dout("build_path path+%d: %p SNAPDIR\n",
1790                              pos, temp);
1791                 } else if (stop_on_nosnap && inode &&
1792                            ceph_snap(inode) == CEPH_NOSNAP) {
1793                         spin_unlock(&temp->d_lock);
1794                         break;
1795                 } else {
1796                         pos -= temp->d_name.len;
1797                         if (pos < 0) {
1798                                 spin_unlock(&temp->d_lock);
1799                                 break;
1800                         }
1801                         strncpy(path + pos, temp->d_name.name,
1802                                 temp->d_name.len);
1803                 }
1804                 spin_unlock(&temp->d_lock);
1805                 if (pos)
1806                         path[--pos] = '/';
1807                 temp = temp->d_parent;
1808         }
1809         rcu_read_unlock();
1810         if (pos != 0 || read_seqretry(&rename_lock, seq)) {
1811                 pr_err("build_path did not end path lookup where "
1812                        "expected, namelen is %d, pos is %d\n", len, pos);
1813                 /* presumably this is only possible if racing with a
1814                    rename of one of the parent directories (we can not
1815                    lock the dentries above us to prevent this, but
1816                    retrying should be harmless) */
1817                 kfree(path);
1818                 goto retry;
1819         }
1820
1821         *base = ceph_ino(d_inode(temp));
1822         *plen = len;
1823         dout("build_path on %p %d built %llx '%.*s'\n",
1824              dentry, d_count(dentry), *base, len, path);
1825         return path;
1826 }
1827
1828 static int build_dentry_path(struct dentry *dentry,
1829                              const char **ppath, int *ppathlen, u64 *pino,
1830                              int *pfreepath)
1831 {
1832         char *path;
1833
1834         if (ceph_snap(d_inode(dentry->d_parent)) == CEPH_NOSNAP) {
1835                 *pino = ceph_ino(d_inode(dentry->d_parent));
1836                 *ppath = dentry->d_name.name;
1837                 *ppathlen = dentry->d_name.len;
1838                 return 0;
1839         }
1840         path = ceph_mdsc_build_path(dentry, ppathlen, pino, 1);
1841         if (IS_ERR(path))
1842                 return PTR_ERR(path);
1843         *ppath = path;
1844         *pfreepath = 1;
1845         return 0;
1846 }
1847
1848 static int build_inode_path(struct inode *inode,
1849                             const char **ppath, int *ppathlen, u64 *pino,
1850                             int *pfreepath)
1851 {
1852         struct dentry *dentry;
1853         char *path;
1854
1855         if (ceph_snap(inode) == CEPH_NOSNAP) {
1856                 *pino = ceph_ino(inode);
1857                 *ppathlen = 0;
1858                 return 0;
1859         }
1860         dentry = d_find_alias(inode);
1861         path = ceph_mdsc_build_path(dentry, ppathlen, pino, 1);
1862         dput(dentry);
1863         if (IS_ERR(path))
1864                 return PTR_ERR(path);
1865         *ppath = path;
1866         *pfreepath = 1;
1867         return 0;
1868 }
1869
1870 /*
1871  * request arguments may be specified via an inode *, a dentry *, or
1872  * an explicit ino+path.
1873  */
1874 static int set_request_path_attr(struct inode *rinode, struct dentry *rdentry,
1875                                   const char *rpath, u64 rino,
1876                                   const char **ppath, int *pathlen,
1877                                   u64 *ino, int *freepath)
1878 {
1879         int r = 0;
1880
1881         if (rinode) {
1882                 r = build_inode_path(rinode, ppath, pathlen, ino, freepath);
1883                 dout(" inode %p %llx.%llx\n", rinode, ceph_ino(rinode),
1884                      ceph_snap(rinode));
1885         } else if (rdentry) {
1886                 r = build_dentry_path(rdentry, ppath, pathlen, ino, freepath);
1887                 dout(" dentry %p %llx/%.*s\n", rdentry, *ino, *pathlen,
1888                      *ppath);
1889         } else if (rpath || rino) {
1890                 *ino = rino;
1891                 *ppath = rpath;
1892                 *pathlen = rpath ? strlen(rpath) : 0;
1893                 dout(" path %.*s\n", *pathlen, rpath);
1894         }
1895
1896         return r;
1897 }
1898
1899 /*
1900  * called under mdsc->mutex
1901  */
1902 static struct ceph_msg *create_request_message(struct ceph_mds_client *mdsc,
1903                                                struct ceph_mds_request *req,
1904                                                int mds, bool drop_cap_releases)
1905 {
1906         struct ceph_msg *msg;
1907         struct ceph_mds_request_head *head;
1908         const char *path1 = NULL;
1909         const char *path2 = NULL;
1910         u64 ino1 = 0, ino2 = 0;
1911         int pathlen1 = 0, pathlen2 = 0;
1912         int freepath1 = 0, freepath2 = 0;
1913         int len;
1914         u16 releases;
1915         void *p, *end;
1916         int ret;
1917
1918         ret = set_request_path_attr(req->r_inode, req->r_dentry,
1919                               req->r_path1, req->r_ino1.ino,
1920                               &path1, &pathlen1, &ino1, &freepath1);
1921         if (ret < 0) {
1922                 msg = ERR_PTR(ret);
1923                 goto out;
1924         }
1925
1926         ret = set_request_path_attr(NULL, req->r_old_dentry,
1927                               req->r_path2, req->r_ino2.ino,
1928                               &path2, &pathlen2, &ino2, &freepath2);
1929         if (ret < 0) {
1930                 msg = ERR_PTR(ret);
1931                 goto out_free1;
1932         }
1933
1934         len = sizeof(*head) +
1935                 pathlen1 + pathlen2 + 2*(1 + sizeof(u32) + sizeof(u64)) +
1936                 sizeof(struct ceph_timespec);
1937
1938         /* calculate (max) length for cap releases */
1939         len += sizeof(struct ceph_mds_request_release) *
1940                 (!!req->r_inode_drop + !!req->r_dentry_drop +
1941                  !!req->r_old_inode_drop + !!req->r_old_dentry_drop);
1942         if (req->r_dentry_drop)
1943                 len += req->r_dentry->d_name.len;
1944         if (req->r_old_dentry_drop)
1945                 len += req->r_old_dentry->d_name.len;
1946
1947         msg = ceph_msg_new(CEPH_MSG_CLIENT_REQUEST, len, GFP_NOFS, false);
1948         if (!msg) {
1949                 msg = ERR_PTR(-ENOMEM);
1950                 goto out_free2;
1951         }
1952
1953         msg->hdr.version = cpu_to_le16(2);
1954         msg->hdr.tid = cpu_to_le64(req->r_tid);
1955
1956         head = msg->front.iov_base;
1957         p = msg->front.iov_base + sizeof(*head);
1958         end = msg->front.iov_base + msg->front.iov_len;
1959
1960         head->mdsmap_epoch = cpu_to_le32(mdsc->mdsmap->m_epoch);
1961         head->op = cpu_to_le32(req->r_op);
1962         head->caller_uid = cpu_to_le32(from_kuid(&init_user_ns, req->r_uid));
1963         head->caller_gid = cpu_to_le32(from_kgid(&init_user_ns, req->r_gid));
1964         head->args = req->r_args;
1965
1966         ceph_encode_filepath(&p, end, ino1, path1);
1967         ceph_encode_filepath(&p, end, ino2, path2);
1968
1969         /* make note of release offset, in case we need to replay */
1970         req->r_request_release_offset = p - msg->front.iov_base;
1971
1972         /* cap releases */
1973         releases = 0;
1974         if (req->r_inode_drop)
1975                 releases += ceph_encode_inode_release(&p,
1976                       req->r_inode ? req->r_inode : d_inode(req->r_dentry),
1977                       mds, req->r_inode_drop, req->r_inode_unless, 0);
1978         if (req->r_dentry_drop)
1979                 releases += ceph_encode_dentry_release(&p, req->r_dentry,
1980                        mds, req->r_dentry_drop, req->r_dentry_unless);
1981         if (req->r_old_dentry_drop)
1982                 releases += ceph_encode_dentry_release(&p, req->r_old_dentry,
1983                        mds, req->r_old_dentry_drop, req->r_old_dentry_unless);
1984         if (req->r_old_inode_drop)
1985                 releases += ceph_encode_inode_release(&p,
1986                       d_inode(req->r_old_dentry),
1987                       mds, req->r_old_inode_drop, req->r_old_inode_unless, 0);
1988
1989         if (drop_cap_releases) {
1990                 releases = 0;
1991                 p = msg->front.iov_base + req->r_request_release_offset;
1992         }
1993
1994         head->num_releases = cpu_to_le16(releases);
1995
1996         /* time stamp */
1997         {
1998                 struct ceph_timespec ts;
1999                 ceph_encode_timespec(&ts, &req->r_stamp);
2000                 ceph_encode_copy(&p, &ts, sizeof(ts));
2001         }
2002
2003         BUG_ON(p > end);
2004         msg->front.iov_len = p - msg->front.iov_base;
2005         msg->hdr.front_len = cpu_to_le32(msg->front.iov_len);
2006
2007         if (req->r_pagelist) {
2008                 struct ceph_pagelist *pagelist = req->r_pagelist;
2009                 atomic_inc(&pagelist->refcnt);
2010                 ceph_msg_data_add_pagelist(msg, pagelist);
2011                 msg->hdr.data_len = cpu_to_le32(pagelist->length);
2012         } else {
2013                 msg->hdr.data_len = 0;
2014         }
2015
2016         msg->hdr.data_off = cpu_to_le16(0);
2017
2018 out_free2:
2019         if (freepath2)
2020                 kfree((char *)path2);
2021 out_free1:
2022         if (freepath1)
2023                 kfree((char *)path1);
2024 out:
2025         return msg;
2026 }
2027
2028 /*
2029  * called under mdsc->mutex if error, under no mutex if
2030  * success.
2031  */
2032 static void complete_request(struct ceph_mds_client *mdsc,
2033                              struct ceph_mds_request *req)
2034 {
2035         if (req->r_callback)
2036                 req->r_callback(mdsc, req);
2037         else
2038                 complete_all(&req->r_completion);
2039 }
2040
2041 /*
2042  * called under mdsc->mutex
2043  */
2044 static int __prepare_send_request(struct ceph_mds_client *mdsc,
2045                                   struct ceph_mds_request *req,
2046                                   int mds, bool drop_cap_releases)
2047 {
2048         struct ceph_mds_request_head *rhead;
2049         struct ceph_msg *msg;
2050         int flags = 0;
2051
2052         req->r_attempts++;
2053         if (req->r_inode) {
2054                 struct ceph_cap *cap =
2055                         ceph_get_cap_for_mds(ceph_inode(req->r_inode), mds);
2056
2057                 if (cap)
2058                         req->r_sent_on_mseq = cap->mseq;
2059                 else
2060                         req->r_sent_on_mseq = -1;
2061         }
2062         dout("prepare_send_request %p tid %lld %s (attempt %d)\n", req,
2063              req->r_tid, ceph_mds_op_name(req->r_op), req->r_attempts);
2064
2065         if (req->r_got_unsafe) {
2066                 void *p;
2067                 /*
2068                  * Replay.  Do not regenerate message (and rebuild
2069                  * paths, etc.); just use the original message.
2070                  * Rebuilding paths will break for renames because
2071                  * d_move mangles the src name.
2072                  */
2073                 msg = req->r_request;
2074                 rhead = msg->front.iov_base;
2075
2076                 flags = le32_to_cpu(rhead->flags);
2077                 flags |= CEPH_MDS_FLAG_REPLAY;
2078                 rhead->flags = cpu_to_le32(flags);
2079
2080                 if (req->r_target_inode)
2081                         rhead->ino = cpu_to_le64(ceph_ino(req->r_target_inode));
2082
2083                 rhead->num_retry = req->r_attempts - 1;
2084
2085                 /* remove cap/dentry releases from message */
2086                 rhead->num_releases = 0;
2087
2088                 /* time stamp */
2089                 p = msg->front.iov_base + req->r_request_release_offset;
2090                 {
2091                         struct ceph_timespec ts;
2092                         ceph_encode_timespec(&ts, &req->r_stamp);
2093                         ceph_encode_copy(&p, &ts, sizeof(ts));
2094                 }
2095
2096                 msg->front.iov_len = p - msg->front.iov_base;
2097                 msg->hdr.front_len = cpu_to_le32(msg->front.iov_len);
2098                 return 0;
2099         }
2100
2101         if (req->r_request) {
2102                 ceph_msg_put(req->r_request);
2103                 req->r_request = NULL;
2104         }
2105         msg = create_request_message(mdsc, req, mds, drop_cap_releases);
2106         if (IS_ERR(msg)) {
2107                 req->r_err = PTR_ERR(msg);
2108                 return PTR_ERR(msg);
2109         }
2110         req->r_request = msg;
2111
2112         rhead = msg->front.iov_base;
2113         rhead->oldest_client_tid = cpu_to_le64(__get_oldest_tid(mdsc));
2114         if (req->r_got_unsafe)
2115                 flags |= CEPH_MDS_FLAG_REPLAY;
2116         if (req->r_locked_dir)
2117                 flags |= CEPH_MDS_FLAG_WANT_DENTRY;
2118         rhead->flags = cpu_to_le32(flags);
2119         rhead->num_fwd = req->r_num_fwd;
2120         rhead->num_retry = req->r_attempts - 1;
2121         rhead->ino = 0;
2122
2123         dout(" r_locked_dir = %p\n", req->r_locked_dir);
2124         return 0;
2125 }
2126
2127 /*
2128  * send request, or put it on the appropriate wait list.
2129  */
2130 static int __do_request(struct ceph_mds_client *mdsc,
2131                         struct ceph_mds_request *req)
2132 {
2133         struct ceph_mds_session *session = NULL;
2134         int mds = -1;
2135         int err = 0;
2136
2137         if (req->r_err || req->r_got_result) {
2138                 if (req->r_aborted)
2139                         __unregister_request(mdsc, req);
2140                 goto out;
2141         }
2142
2143         if (req->r_timeout &&
2144             time_after_eq(jiffies, req->r_started + req->r_timeout)) {
2145                 dout("do_request timed out\n");
2146                 err = -EIO;
2147                 goto finish;
2148         }
2149         if (ACCESS_ONCE(mdsc->fsc->mount_state) == CEPH_MOUNT_SHUTDOWN) {
2150                 dout("do_request forced umount\n");
2151                 err = -EIO;
2152                 goto finish;
2153         }
2154
2155         put_request_session(req);
2156
2157         mds = __choose_mds(mdsc, req);
2158         if (mds < 0 ||
2159             ceph_mdsmap_get_state(mdsc->mdsmap, mds) < CEPH_MDS_STATE_ACTIVE) {
2160                 dout("do_request no mds or not active, waiting for map\n");
2161                 list_add(&req->r_wait, &mdsc->waiting_for_map);
2162                 goto out;
2163         }
2164
2165         /* get, open session */
2166         session = __ceph_lookup_mds_session(mdsc, mds);
2167         if (!session) {
2168                 session = register_session(mdsc, mds);
2169                 if (IS_ERR(session)) {
2170                         err = PTR_ERR(session);
2171                         goto finish;
2172                 }
2173         }
2174         req->r_session = get_session(session);
2175
2176         dout("do_request mds%d session %p state %s\n", mds, session,
2177              ceph_session_state_name(session->s_state));
2178         if (session->s_state != CEPH_MDS_SESSION_OPEN &&
2179             session->s_state != CEPH_MDS_SESSION_HUNG) {
2180                 if (session->s_state == CEPH_MDS_SESSION_NEW ||
2181                     session->s_state == CEPH_MDS_SESSION_CLOSING)
2182                         __open_session(mdsc, session);
2183                 list_add(&req->r_wait, &session->s_waiting);
2184                 goto out_session;
2185         }
2186
2187         /* send request */
2188         req->r_resend_mds = -1;   /* forget any previous mds hint */
2189
2190         if (req->r_request_started == 0)   /* note request start time */
2191                 req->r_request_started = jiffies;
2192
2193         err = __prepare_send_request(mdsc, req, mds, false);
2194         if (!err) {
2195                 ceph_msg_get(req->r_request);
2196                 ceph_con_send(&session->s_con, req->r_request);
2197         }
2198
2199 out_session:
2200         ceph_put_mds_session(session);
2201 finish:
2202         if (err) {
2203                 dout("__do_request early error %d\n", err);
2204                 req->r_err = err;
2205                 complete_request(mdsc, req);
2206                 __unregister_request(mdsc, req);
2207         }
2208 out:
2209         return err;
2210 }
2211
2212 /*
2213  * called under mdsc->mutex
2214  */
2215 static void __wake_requests(struct ceph_mds_client *mdsc,
2216                             struct list_head *head)
2217 {
2218         struct ceph_mds_request *req;
2219         LIST_HEAD(tmp_list);
2220
2221         list_splice_init(head, &tmp_list);
2222
2223         while (!list_empty(&tmp_list)) {
2224                 req = list_entry(tmp_list.next,
2225                                  struct ceph_mds_request, r_wait);
2226                 list_del_init(&req->r_wait);
2227                 dout(" wake request %p tid %llu\n", req, req->r_tid);
2228                 __do_request(mdsc, req);
2229         }
2230 }
2231
2232 /*
2233  * Wake up threads with requests pending for @mds, so that they can
2234  * resubmit their requests to a possibly different mds.
2235  */
2236 static void kick_requests(struct ceph_mds_client *mdsc, int mds)
2237 {
2238         struct ceph_mds_request *req;
2239         struct rb_node *p = rb_first(&mdsc->request_tree);
2240
2241         dout("kick_requests mds%d\n", mds);
2242         while (p) {
2243                 req = rb_entry(p, struct ceph_mds_request, r_node);
2244                 p = rb_next(p);
2245                 if (req->r_got_unsafe)
2246                         continue;
2247                 if (req->r_attempts > 0)
2248                         continue; /* only new requests */
2249                 if (req->r_session &&
2250                     req->r_session->s_mds == mds) {
2251                         dout(" kicking tid %llu\n", req->r_tid);
2252                         list_del_init(&req->r_wait);
2253                         __do_request(mdsc, req);
2254                 }
2255         }
2256 }
2257
2258 void ceph_mdsc_submit_request(struct ceph_mds_client *mdsc,
2259                               struct ceph_mds_request *req)
2260 {
2261         dout("submit_request on %p\n", req);
2262         mutex_lock(&mdsc->mutex);
2263         __register_request(mdsc, req, NULL);
2264         __do_request(mdsc, req);
2265         mutex_unlock(&mdsc->mutex);
2266 }
2267
2268 /*
2269  * Synchrously perform an mds request.  Take care of all of the
2270  * session setup, forwarding, retry details.
2271  */
2272 int ceph_mdsc_do_request(struct ceph_mds_client *mdsc,
2273                          struct inode *dir,
2274                          struct ceph_mds_request *req)
2275 {
2276         int err;
2277
2278         dout("do_request on %p\n", req);
2279
2280         /* take CAP_PIN refs for r_inode, r_locked_dir, r_old_dentry */
2281         if (req->r_inode)
2282                 ceph_get_cap_refs(ceph_inode(req->r_inode), CEPH_CAP_PIN);
2283         if (req->r_locked_dir)
2284                 ceph_get_cap_refs(ceph_inode(req->r_locked_dir), CEPH_CAP_PIN);
2285         if (req->r_old_dentry_dir)
2286                 ceph_get_cap_refs(ceph_inode(req->r_old_dentry_dir),
2287                                   CEPH_CAP_PIN);
2288
2289         /* deny access to directories with pool_ns layouts */
2290         if (req->r_inode && S_ISDIR(req->r_inode->i_mode) &&
2291             ceph_inode(req->r_inode)->i_pool_ns_len)
2292                 return -EIO;
2293         if (req->r_locked_dir &&
2294             ceph_inode(req->r_locked_dir)->i_pool_ns_len)
2295                 return -EIO;
2296
2297         /* issue */
2298         mutex_lock(&mdsc->mutex);
2299         __register_request(mdsc, req, dir);
2300         __do_request(mdsc, req);
2301
2302         if (req->r_err) {
2303                 err = req->r_err;
2304                 goto out;
2305         }
2306
2307         /* wait */
2308         mutex_unlock(&mdsc->mutex);
2309         dout("do_request waiting\n");
2310         if (!req->r_timeout && req->r_wait_for_completion) {
2311                 err = req->r_wait_for_completion(mdsc, req);
2312         } else {
2313                 long timeleft = wait_for_completion_killable_timeout(
2314                                         &req->r_completion,
2315                                         ceph_timeout_jiffies(req->r_timeout));
2316                 if (timeleft > 0)
2317                         err = 0;
2318                 else if (!timeleft)
2319                         err = -EIO;  /* timed out */
2320                 else
2321                         err = timeleft;  /* killed */
2322         }
2323         dout("do_request waited, got %d\n", err);
2324         mutex_lock(&mdsc->mutex);
2325
2326         /* only abort if we didn't race with a real reply */
2327         if (req->r_got_result) {
2328                 err = le32_to_cpu(req->r_reply_info.head->result);
2329         } else if (err < 0) {
2330                 dout("aborted request %lld with %d\n", req->r_tid, err);
2331
2332                 /*
2333                  * ensure we aren't running concurrently with
2334                  * ceph_fill_trace or ceph_readdir_prepopulate, which
2335                  * rely on locks (dir mutex) held by our caller.
2336                  */
2337                 mutex_lock(&req->r_fill_mutex);
2338                 req->r_err = err;
2339                 req->r_aborted = true;
2340                 mutex_unlock(&req->r_fill_mutex);
2341
2342                 if (req->r_locked_dir &&
2343                     (req->r_op & CEPH_MDS_OP_WRITE))
2344                         ceph_invalidate_dir_request(req);
2345         } else {
2346                 err = req->r_err;
2347         }
2348
2349 out:
2350         mutex_unlock(&mdsc->mutex);
2351         dout("do_request %p done, result %d\n", req, err);
2352         return err;
2353 }
2354
2355 /*
2356  * Invalidate dir's completeness, dentry lease state on an aborted MDS
2357  * namespace request.
2358  */
2359 void ceph_invalidate_dir_request(struct ceph_mds_request *req)
2360 {
2361         struct inode *inode = req->r_locked_dir;
2362
2363         dout("invalidate_dir_request %p (complete, lease(s))\n", inode);
2364
2365         ceph_dir_clear_complete(inode);
2366         if (req->r_dentry)
2367                 ceph_invalidate_dentry_lease(req->r_dentry);
2368         if (req->r_old_dentry)
2369                 ceph_invalidate_dentry_lease(req->r_old_dentry);
2370 }
2371
2372 /*
2373  * Handle mds reply.
2374  *
2375  * We take the session mutex and parse and process the reply immediately.
2376  * This preserves the logical ordering of replies, capabilities, etc., sent
2377  * by the MDS as they are applied to our local cache.
2378  */
2379 static void handle_reply(struct ceph_mds_session *session, struct ceph_msg *msg)
2380 {
2381         struct ceph_mds_client *mdsc = session->s_mdsc;
2382         struct ceph_mds_request *req;
2383         struct ceph_mds_reply_head *head = msg->front.iov_base;
2384         struct ceph_mds_reply_info_parsed *rinfo;  /* parsed reply info */
2385         struct ceph_snap_realm *realm;
2386         u64 tid;
2387         int err, result;
2388         int mds = session->s_mds;
2389
2390         if (msg->front.iov_len < sizeof(*head)) {
2391                 pr_err("mdsc_handle_reply got corrupt (short) reply\n");
2392                 ceph_msg_dump(msg);
2393                 return;
2394         }
2395
2396         /* get request, session */
2397         tid = le64_to_cpu(msg->hdr.tid);
2398         mutex_lock(&mdsc->mutex);
2399         req = lookup_get_request(mdsc, tid);
2400         if (!req) {
2401                 dout("handle_reply on unknown tid %llu\n", tid);
2402                 mutex_unlock(&mdsc->mutex);
2403                 return;
2404         }
2405         dout("handle_reply %p\n", req);
2406
2407         /* correct session? */
2408         if (req->r_session != session) {
2409                 pr_err("mdsc_handle_reply got %llu on session mds%d"
2410                        " not mds%d\n", tid, session->s_mds,
2411                        req->r_session ? req->r_session->s_mds : -1);
2412                 mutex_unlock(&mdsc->mutex);
2413                 goto out;
2414         }
2415
2416         /* dup? */
2417         if ((req->r_got_unsafe && !head->safe) ||
2418             (req->r_got_safe && head->safe)) {
2419                 pr_warn("got a dup %s reply on %llu from mds%d\n",
2420                            head->safe ? "safe" : "unsafe", tid, mds);
2421                 mutex_unlock(&mdsc->mutex);
2422                 goto out;
2423         }
2424         if (req->r_got_safe) {
2425                 pr_warn("got unsafe after safe on %llu from mds%d\n",
2426                            tid, mds);
2427                 mutex_unlock(&mdsc->mutex);
2428                 goto out;
2429         }
2430
2431         result = le32_to_cpu(head->result);
2432
2433         /*
2434          * Handle an ESTALE
2435          * if we're not talking to the authority, send to them
2436          * if the authority has changed while we weren't looking,
2437          * send to new authority
2438          * Otherwise we just have to return an ESTALE
2439          */
2440         if (result == -ESTALE) {
2441                 dout("got ESTALE on request %llu", req->r_tid);
2442                 req->r_resend_mds = -1;
2443                 if (req->r_direct_mode != USE_AUTH_MDS) {
2444                         dout("not using auth, setting for that now");
2445                         req->r_direct_mode = USE_AUTH_MDS;
2446                         __do_request(mdsc, req);
2447                         mutex_unlock(&mdsc->mutex);
2448                         goto out;
2449                 } else  {
2450                         int mds = __choose_mds(mdsc, req);
2451                         if (mds >= 0 && mds != req->r_session->s_mds) {
2452                                 dout("but auth changed, so resending");
2453                                 __do_request(mdsc, req);
2454                                 mutex_unlock(&mdsc->mutex);
2455                                 goto out;
2456                         }
2457                 }
2458                 dout("have to return ESTALE on request %llu", req->r_tid);
2459         }
2460
2461
2462         if (head->safe) {
2463                 req->r_got_safe = true;
2464                 __unregister_request(mdsc, req);
2465
2466                 if (req->r_got_unsafe) {
2467                         /*
2468                          * We already handled the unsafe response, now do the
2469                          * cleanup.  No need to examine the response; the MDS
2470                          * doesn't include any result info in the safe
2471                          * response.  And even if it did, there is nothing
2472                          * useful we could do with a revised return value.
2473                          */
2474                         dout("got safe reply %llu, mds%d\n", tid, mds);
2475                         list_del_init(&req->r_unsafe_item);
2476
2477                         /* last unsafe request during umount? */
2478                         if (mdsc->stopping && !__get_oldest_req(mdsc))
2479                                 complete_all(&mdsc->safe_umount_waiters);
2480                         mutex_unlock(&mdsc->mutex);
2481                         goto out;
2482                 }
2483         } else {
2484                 req->r_got_unsafe = true;
2485                 list_add_tail(&req->r_unsafe_item, &req->r_session->s_unsafe);
2486                 if (req->r_unsafe_dir) {
2487                         struct ceph_inode_info *ci =
2488                                         ceph_inode(req->r_unsafe_dir);
2489                         spin_lock(&ci->i_unsafe_lock);
2490                         list_add_tail(&req->r_unsafe_dir_item,
2491                                       &ci->i_unsafe_dirops);
2492                         spin_unlock(&ci->i_unsafe_lock);
2493                 }
2494         }
2495
2496         dout("handle_reply tid %lld result %d\n", tid, result);
2497         rinfo = &req->r_reply_info;
2498         err = parse_reply_info(msg, rinfo, session->s_con.peer_features);
2499         mutex_unlock(&mdsc->mutex);
2500
2501         mutex_lock(&session->s_mutex);
2502         if (err < 0) {
2503                 pr_err("mdsc_handle_reply got corrupt reply mds%d(tid:%lld)\n", mds, tid);
2504                 ceph_msg_dump(msg);
2505                 goto out_err;
2506         }
2507
2508         /* snap trace */
2509         realm = NULL;
2510         if (rinfo->snapblob_len) {
2511                 down_write(&mdsc->snap_rwsem);
2512                 ceph_update_snap_trace(mdsc, rinfo->snapblob,
2513                                 rinfo->snapblob + rinfo->snapblob_len,
2514                                 le32_to_cpu(head->op) == CEPH_MDS_OP_RMSNAP,
2515                                 &realm);
2516                 downgrade_write(&mdsc->snap_rwsem);
2517         } else {
2518                 down_read(&mdsc->snap_rwsem);
2519         }
2520
2521         /* insert trace into our cache */
2522         mutex_lock(&req->r_fill_mutex);
2523         current->journal_info = req;
2524         err = ceph_fill_trace(mdsc->fsc->sb, req, req->r_session);
2525         if (err == 0) {
2526                 if (result == 0 && (req->r_op == CEPH_MDS_OP_READDIR ||
2527                                     req->r_op == CEPH_MDS_OP_LSSNAP))
2528                         ceph_readdir_prepopulate(req, req->r_session);
2529                 ceph_unreserve_caps(mdsc, &req->r_caps_reservation);
2530         }
2531         current->journal_info = NULL;
2532         mutex_unlock(&req->r_fill_mutex);
2533
2534         up_read(&mdsc->snap_rwsem);
2535         if (realm)
2536                 ceph_put_snap_realm(mdsc, realm);
2537
2538         if (err == 0 && req->r_got_unsafe && req->r_target_inode) {
2539                 struct ceph_inode_info *ci = ceph_inode(req->r_target_inode);
2540                 spin_lock(&ci->i_unsafe_lock);
2541                 list_add_tail(&req->r_unsafe_target_item, &ci->i_unsafe_iops);
2542                 spin_unlock(&ci->i_unsafe_lock);
2543         }
2544 out_err:
2545         mutex_lock(&mdsc->mutex);
2546         if (!req->r_aborted) {
2547                 if (err) {
2548                         req->r_err = err;
2549                 } else {
2550                         req->r_reply =  ceph_msg_get(msg);
2551                         req->r_got_result = true;
2552                 }
2553         } else {
2554                 dout("reply arrived after request %lld was aborted\n", tid);
2555         }
2556         mutex_unlock(&mdsc->mutex);
2557
2558         mutex_unlock(&session->s_mutex);
2559
2560         /* kick calling process */
2561         complete_request(mdsc, req);
2562 out:
2563         ceph_mdsc_put_request(req);
2564         return;
2565 }
2566
2567
2568
2569 /*
2570  * handle mds notification that our request has been forwarded.
2571  */
2572 static void handle_forward(struct ceph_mds_client *mdsc,
2573                            struct ceph_mds_session *session,
2574                            struct ceph_msg *msg)
2575 {
2576         struct ceph_mds_request *req;
2577         u64 tid = le64_to_cpu(msg->hdr.tid);
2578         u32 next_mds;
2579         u32 fwd_seq;
2580         int err = -EINVAL;
2581         void *p = msg->front.iov_base;
2582         void *end = p + msg->front.iov_len;
2583
2584         ceph_decode_need(&p, end, 2*sizeof(u32), bad);
2585         next_mds = ceph_decode_32(&p);
2586         fwd_seq = ceph_decode_32(&p);
2587
2588         mutex_lock(&mdsc->mutex);
2589         req = lookup_get_request(mdsc, tid);
2590         if (!req) {
2591                 dout("forward tid %llu to mds%d - req dne\n", tid, next_mds);
2592                 goto out;  /* dup reply? */
2593         }
2594
2595         if (req->r_aborted) {
2596                 dout("forward tid %llu aborted, unregistering\n", tid);
2597                 __unregister_request(mdsc, req);
2598         } else if (fwd_seq <= req->r_num_fwd) {
2599                 dout("forward tid %llu to mds%d - old seq %d <= %d\n",
2600                      tid, next_mds, req->r_num_fwd, fwd_seq);
2601         } else {
2602                 /* resend. forward race not possible; mds would drop */
2603                 dout("forward tid %llu to mds%d (we resend)\n", tid, next_mds);
2604                 BUG_ON(req->r_err);
2605                 BUG_ON(req->r_got_result);
2606                 req->r_attempts = 0;
2607                 req->r_num_fwd = fwd_seq;
2608                 req->r_resend_mds = next_mds;
2609                 put_request_session(req);
2610                 __do_request(mdsc, req);
2611         }
2612         ceph_mdsc_put_request(req);
2613 out:
2614         mutex_unlock(&mdsc->mutex);
2615         return;
2616
2617 bad:
2618         pr_err("mdsc_handle_forward decode error err=%d\n", err);
2619 }
2620
2621 /*
2622  * handle a mds session control message
2623  */
2624 static void handle_session(struct ceph_mds_session *session,
2625                            struct ceph_msg *msg)
2626 {
2627         struct ceph_mds_client *mdsc = session->s_mdsc;
2628         u32 op;
2629         u64 seq;
2630         int mds = session->s_mds;
2631         struct ceph_mds_session_head *h = msg->front.iov_base;
2632         int wake = 0;
2633
2634         /* decode */
2635         if (msg->front.iov_len != sizeof(*h))
2636                 goto bad;
2637         op = le32_to_cpu(h->op);
2638         seq = le64_to_cpu(h->seq);
2639
2640         mutex_lock(&mdsc->mutex);
2641         if (op == CEPH_SESSION_CLOSE)
2642                 __unregister_session(mdsc, session);
2643         /* FIXME: this ttl calculation is generous */
2644         session->s_ttl = jiffies + HZ*mdsc->mdsmap->m_session_autoclose;
2645         mutex_unlock(&mdsc->mutex);
2646
2647         mutex_lock(&session->s_mutex);
2648
2649         dout("handle_session mds%d %s %p state %s seq %llu\n",
2650              mds, ceph_session_op_name(op), session,
2651              ceph_session_state_name(session->s_state), seq);
2652
2653         if (session->s_state == CEPH_MDS_SESSION_HUNG) {
2654                 session->s_state = CEPH_MDS_SESSION_OPEN;
2655                 pr_info("mds%d came back\n", session->s_mds);
2656         }
2657
2658         switch (op) {
2659         case CEPH_SESSION_OPEN:
2660                 if (session->s_state == CEPH_MDS_SESSION_RECONNECTING)
2661                         pr_info("mds%d reconnect success\n", session->s_mds);
2662                 session->s_state = CEPH_MDS_SESSION_OPEN;
2663                 renewed_caps(mdsc, session, 0);
2664                 wake = 1;
2665                 if (mdsc->stopping)
2666                         __close_session(mdsc, session);
2667                 break;
2668
2669         case CEPH_SESSION_RENEWCAPS:
2670                 if (session->s_renew_seq == seq)
2671                         renewed_caps(mdsc, session, 1);
2672                 break;
2673
2674         case CEPH_SESSION_CLOSE:
2675                 if (session->s_state == CEPH_MDS_SESSION_RECONNECTING)
2676                         pr_info("mds%d reconnect denied\n", session->s_mds);
2677                 cleanup_session_requests(mdsc, session);
2678                 remove_session_caps(session);
2679                 wake = 2; /* for good measure */
2680                 wake_up_all(&mdsc->session_close_wq);
2681                 break;
2682
2683         case CEPH_SESSION_STALE:
2684                 pr_info("mds%d caps went stale, renewing\n",
2685                         session->s_mds);
2686                 spin_lock(&session->s_gen_ttl_lock);
2687                 session->s_cap_gen++;
2688                 session->s_cap_ttl = jiffies - 1;
2689                 spin_unlock(&session->s_gen_ttl_lock);
2690                 send_renew_caps(mdsc, session);
2691                 break;
2692
2693         case CEPH_SESSION_RECALL_STATE:
2694                 trim_caps(mdsc, session, le32_to_cpu(h->max_caps));
2695                 break;
2696
2697         case CEPH_SESSION_FLUSHMSG:
2698                 send_flushmsg_ack(mdsc, session, seq);
2699                 break;
2700
2701         case CEPH_SESSION_FORCE_RO:
2702                 dout("force_session_readonly %p\n", session);
2703                 spin_lock(&session->s_cap_lock);
2704                 session->s_readonly = true;
2705                 spin_unlock(&session->s_cap_lock);
2706                 wake_up_session_caps(session, 0);
2707                 break;
2708
2709         default:
2710                 pr_err("mdsc_handle_session bad op %d mds%d\n", op, mds);
2711                 WARN_ON(1);
2712         }
2713
2714         mutex_unlock(&session->s_mutex);
2715         if (wake) {
2716                 mutex_lock(&mdsc->mutex);
2717                 __wake_requests(mdsc, &session->s_waiting);
2718                 if (wake == 2)
2719                         kick_requests(mdsc, mds);
2720                 mutex_unlock(&mdsc->mutex);
2721         }
2722         return;
2723
2724 bad:
2725         pr_err("mdsc_handle_session corrupt message mds%d len %d\n", mds,
2726                (int)msg->front.iov_len);
2727         ceph_msg_dump(msg);
2728         return;
2729 }
2730
2731
2732 /*
2733  * called under session->mutex.
2734  */
2735 static void replay_unsafe_requests(struct ceph_mds_client *mdsc,
2736                                    struct ceph_mds_session *session)
2737 {
2738         struct ceph_mds_request *req, *nreq;
2739         struct rb_node *p;
2740         int err;
2741
2742         dout("replay_unsafe_requests mds%d\n", session->s_mds);
2743
2744         mutex_lock(&mdsc->mutex);
2745         list_for_each_entry_safe(req, nreq, &session->s_unsafe, r_unsafe_item) {
2746                 err = __prepare_send_request(mdsc, req, session->s_mds, true);
2747                 if (!err) {
2748                         ceph_msg_get(req->r_request);
2749                         ceph_con_send(&session->s_con, req->r_request);
2750                 }
2751         }
2752
2753         /*
2754          * also re-send old requests when MDS enters reconnect stage. So that MDS
2755          * can process completed request in clientreplay stage.
2756          */
2757         p = rb_first(&mdsc->request_tree);
2758         while (p) {
2759                 req = rb_entry(p, struct ceph_mds_request, r_node);
2760                 p = rb_next(p);
2761                 if (req->r_got_unsafe)
2762                         continue;
2763                 if (req->r_attempts == 0)
2764                         continue; /* only old requests */
2765                 if (req->r_session &&
2766                     req->r_session->s_mds == session->s_mds) {
2767                         err = __prepare_send_request(mdsc, req,
2768                                                      session->s_mds, true);
2769                         if (!err) {
2770                                 ceph_msg_get(req->r_request);
2771                                 ceph_con_send(&session->s_con, req->r_request);
2772                         }
2773                 }
2774         }
2775         mutex_unlock(&mdsc->mutex);
2776 }
2777
2778 /*
2779  * Encode information about a cap for a reconnect with the MDS.
2780  */
2781 static int encode_caps_cb(struct inode *inode, struct ceph_cap *cap,
2782                           void *arg)
2783 {
2784         union {
2785                 struct ceph_mds_cap_reconnect v2;
2786                 struct ceph_mds_cap_reconnect_v1 v1;
2787         } rec;
2788         size_t reclen;
2789         struct ceph_inode_info *ci;
2790         struct ceph_reconnect_state *recon_state = arg;
2791         struct ceph_pagelist *pagelist = recon_state->pagelist;
2792         char *path;
2793         int pathlen, err;
2794         u64 pathbase;
2795         struct dentry *dentry;
2796
2797         ci = cap->ci;
2798
2799         dout(" adding %p ino %llx.%llx cap %p %lld %s\n",
2800              inode, ceph_vinop(inode), cap, cap->cap_id,
2801              ceph_cap_string(cap->issued));
2802         err = ceph_pagelist_encode_64(pagelist, ceph_ino(inode));
2803         if (err)
2804                 return err;
2805
2806         dentry = d_find_alias(inode);
2807         if (dentry) {
2808                 path = ceph_mdsc_build_path(dentry, &pathlen, &pathbase, 0);
2809                 if (IS_ERR(path)) {
2810                         err = PTR_ERR(path);
2811                         goto out_dput;
2812                 }
2813         } else {
2814                 path = NULL;
2815                 pathlen = 0;
2816         }
2817         err = ceph_pagelist_encode_string(pagelist, path, pathlen);
2818         if (err)
2819                 goto out_free;
2820
2821         spin_lock(&ci->i_ceph_lock);
2822         cap->seq = 0;        /* reset cap seq */
2823         cap->issue_seq = 0;  /* and issue_seq */
2824         cap->mseq = 0;       /* and migrate_seq */
2825         cap->cap_gen = cap->session->s_cap_gen;
2826
2827         if (recon_state->flock) {
2828                 rec.v2.cap_id = cpu_to_le64(cap->cap_id);
2829                 rec.v2.wanted = cpu_to_le32(__ceph_caps_wanted(ci));
2830                 rec.v2.issued = cpu_to_le32(cap->issued);
2831                 rec.v2.snaprealm = cpu_to_le64(ci->i_snap_realm->ino);
2832                 rec.v2.pathbase = cpu_to_le64(pathbase);
2833                 rec.v2.flock_len = 0;
2834                 reclen = sizeof(rec.v2);
2835         } else {
2836                 rec.v1.cap_id = cpu_to_le64(cap->cap_id);
2837                 rec.v1.wanted = cpu_to_le32(__ceph_caps_wanted(ci));
2838                 rec.v1.issued = cpu_to_le32(cap->issued);
2839                 rec.v1.size = cpu_to_le64(inode->i_size);
2840                 ceph_encode_timespec(&rec.v1.mtime, &inode->i_mtime);
2841                 ceph_encode_timespec(&rec.v1.atime, &inode->i_atime);
2842                 rec.v1.snaprealm = cpu_to_le64(ci->i_snap_realm->ino);
2843                 rec.v1.pathbase = cpu_to_le64(pathbase);
2844                 reclen = sizeof(rec.v1);
2845         }
2846         spin_unlock(&ci->i_ceph_lock);
2847
2848         if (recon_state->flock) {
2849                 int num_fcntl_locks, num_flock_locks;
2850                 struct ceph_filelock *flocks;
2851
2852 encode_again:
2853                 ceph_count_locks(inode, &num_fcntl_locks, &num_flock_locks);
2854                 flocks = kmalloc((num_fcntl_locks+num_flock_locks) *
2855                                  sizeof(struct ceph_filelock), GFP_NOFS);
2856                 if (!flocks) {
2857                         err = -ENOMEM;
2858                         goto out_free;
2859                 }
2860                 err = ceph_encode_locks_to_buffer(inode, flocks,
2861                                                   num_fcntl_locks,
2862                                                   num_flock_locks);
2863                 if (err) {
2864                         kfree(flocks);
2865                         if (err == -ENOSPC)
2866                                 goto encode_again;
2867                         goto out_free;
2868                 }
2869                 /*
2870                  * number of encoded locks is stable, so copy to pagelist
2871                  */
2872                 rec.v2.flock_len = cpu_to_le32(2*sizeof(u32) +
2873                                     (num_fcntl_locks+num_flock_locks) *
2874                                     sizeof(struct ceph_filelock));
2875                 err = ceph_pagelist_append(pagelist, &rec, reclen);
2876                 if (!err)
2877                         err = ceph_locks_to_pagelist(flocks, pagelist,
2878                                                      num_fcntl_locks,
2879                                                      num_flock_locks);
2880                 kfree(flocks);
2881         } else {
2882                 err = ceph_pagelist_append(pagelist, &rec, reclen);
2883         }
2884
2885         recon_state->nr_caps++;
2886 out_free:
2887         kfree(path);
2888 out_dput:
2889         dput(dentry);
2890         return err;
2891 }
2892
2893
2894 /*
2895  * If an MDS fails and recovers, clients need to reconnect in order to
2896  * reestablish shared state.  This includes all caps issued through
2897  * this session _and_ the snap_realm hierarchy.  Because it's not
2898  * clear which snap realms the mds cares about, we send everything we
2899  * know about.. that ensures we'll then get any new info the
2900  * recovering MDS might have.
2901  *
2902  * This is a relatively heavyweight operation, but it's rare.
2903  *
2904  * called with mdsc->mutex held.
2905  */
2906 static void send_mds_reconnect(struct ceph_mds_client *mdsc,
2907                                struct ceph_mds_session *session)
2908 {
2909         struct ceph_msg *reply;
2910         struct rb_node *p;
2911         int mds = session->s_mds;
2912         int err = -ENOMEM;
2913         int s_nr_caps;
2914         struct ceph_pagelist *pagelist;
2915         struct ceph_reconnect_state recon_state;
2916
2917         pr_info("mds%d reconnect start\n", mds);
2918
2919         pagelist = kmalloc(sizeof(*pagelist), GFP_NOFS);
2920         if (!pagelist)
2921                 goto fail_nopagelist;
2922         ceph_pagelist_init(pagelist);
2923
2924         reply = ceph_msg_new(CEPH_MSG_CLIENT_RECONNECT, 0, GFP_NOFS, false);
2925         if (!reply)
2926                 goto fail_nomsg;
2927
2928         mutex_lock(&session->s_mutex);
2929         session->s_state = CEPH_MDS_SESSION_RECONNECTING;
2930         session->s_seq = 0;
2931
2932         dout("session %p state %s\n", session,
2933              ceph_session_state_name(session->s_state));
2934
2935         spin_lock(&session->s_gen_ttl_lock);
2936         session->s_cap_gen++;
2937         spin_unlock(&session->s_gen_ttl_lock);
2938
2939         spin_lock(&session->s_cap_lock);
2940         /* don't know if session is readonly */
2941         session->s_readonly = 0;
2942         /*
2943          * notify __ceph_remove_cap() that we are composing cap reconnect.
2944          * If a cap get released before being added to the cap reconnect,
2945          * __ceph_remove_cap() should skip queuing cap release.
2946          */
2947         session->s_cap_reconnect = 1;
2948         /* drop old cap expires; we're about to reestablish that state */
2949         cleanup_cap_releases(mdsc, session);
2950
2951         /* trim unused caps to reduce MDS's cache rejoin time */
2952         if (mdsc->fsc->sb->s_root)
2953                 shrink_dcache_parent(mdsc->fsc->sb->s_root);
2954
2955         ceph_con_close(&session->s_con);
2956         ceph_con_open(&session->s_con,
2957                       CEPH_ENTITY_TYPE_MDS, mds,
2958                       ceph_mdsmap_get_addr(mdsc->mdsmap, mds));
2959
2960         /* replay unsafe requests */
2961         replay_unsafe_requests(mdsc, session);
2962
2963         down_read(&mdsc->snap_rwsem);
2964
2965         /* traverse this session's caps */
2966         s_nr_caps = session->s_nr_caps;
2967         err = ceph_pagelist_encode_32(pagelist, s_nr_caps);
2968         if (err)
2969                 goto fail;
2970
2971         recon_state.nr_caps = 0;
2972         recon_state.pagelist = pagelist;
2973         recon_state.flock = session->s_con.peer_features & CEPH_FEATURE_FLOCK;
2974         err = iterate_session_caps(session, encode_caps_cb, &recon_state);
2975         if (err < 0)
2976                 goto fail;
2977
2978         spin_lock(&session->s_cap_lock);
2979         session->s_cap_reconnect = 0;
2980         spin_unlock(&session->s_cap_lock);
2981
2982         /*
2983          * snaprealms.  we provide mds with the ino, seq (version), and
2984          * parent for all of our realms.  If the mds has any newer info,
2985          * it will tell us.
2986          */
2987         for (p = rb_first(&mdsc->snap_realms); p; p = rb_next(p)) {
2988                 struct ceph_snap_realm *realm =
2989                         rb_entry(p, struct ceph_snap_realm, node);
2990                 struct ceph_mds_snaprealm_reconnect sr_rec;
2991
2992                 dout(" adding snap realm %llx seq %lld parent %llx\n",
2993                      realm->ino, realm->seq, realm->parent_ino);
2994                 sr_rec.ino = cpu_to_le64(realm->ino);
2995                 sr_rec.seq = cpu_to_le64(realm->seq);
2996                 sr_rec.parent = cpu_to_le64(realm->parent_ino);
2997                 err = ceph_pagelist_append(pagelist, &sr_rec, sizeof(sr_rec));
2998                 if (err)
2999                         goto fail;
3000         }
3001
3002         if (recon_state.flock)
3003                 reply->hdr.version = cpu_to_le16(2);
3004
3005         /* raced with cap release? */
3006         if (s_nr_caps != recon_state.nr_caps) {
3007                 struct page *page = list_first_entry(&pagelist->head,
3008                                                      struct page, lru);
3009                 __le32 *addr = kmap_atomic(page);
3010                 *addr = cpu_to_le32(recon_state.nr_caps);
3011                 kunmap_atomic(addr);
3012         }
3013
3014         reply->hdr.data_len = cpu_to_le32(pagelist->length);
3015         ceph_msg_data_add_pagelist(reply, pagelist);
3016
3017         ceph_early_kick_flushing_caps(mdsc, session);
3018
3019         ceph_con_send(&session->s_con, reply);
3020
3021         mutex_unlock(&session->s_mutex);
3022
3023         mutex_lock(&mdsc->mutex);
3024         __wake_requests(mdsc, &session->s_waiting);
3025         mutex_unlock(&mdsc->mutex);
3026
3027         up_read(&mdsc->snap_rwsem);
3028         return;
3029
3030 fail:
3031         ceph_msg_put(reply);
3032         up_read(&mdsc->snap_rwsem);
3033         mutex_unlock(&session->s_mutex);
3034 fail_nomsg:
3035         ceph_pagelist_release(pagelist);
3036 fail_nopagelist:
3037         pr_err("error %d preparing reconnect for mds%d\n", err, mds);
3038         return;
3039 }
3040
3041
3042 /*
3043  * compare old and new mdsmaps, kicking requests
3044  * and closing out old connections as necessary
3045  *
3046  * called under mdsc->mutex.
3047  */
3048 static void check_new_map(struct ceph_mds_client *mdsc,
3049                           struct ceph_mdsmap *newmap,
3050                           struct ceph_mdsmap *oldmap)
3051 {
3052         int i;
3053         int oldstate, newstate;
3054         struct ceph_mds_session *s;
3055
3056         dout("check_new_map new %u old %u\n",
3057              newmap->m_epoch, oldmap->m_epoch);
3058
3059         for (i = 0; i < oldmap->m_max_mds && i < mdsc->max_sessions; i++) {
3060                 if (mdsc->sessions[i] == NULL)
3061                         continue;
3062                 s = mdsc->sessions[i];
3063                 oldstate = ceph_mdsmap_get_state(oldmap, i);
3064                 newstate = ceph_mdsmap_get_state(newmap, i);
3065
3066                 dout("check_new_map mds%d state %s%s -> %s%s (session %s)\n",
3067                      i, ceph_mds_state_name(oldstate),
3068                      ceph_mdsmap_is_laggy(oldmap, i) ? " (laggy)" : "",
3069                      ceph_mds_state_name(newstate),
3070                      ceph_mdsmap_is_laggy(newmap, i) ? " (laggy)" : "",
3071                      ceph_session_state_name(s->s_state));
3072
3073                 if (i >= newmap->m_max_mds ||
3074                     memcmp(ceph_mdsmap_get_addr(oldmap, i),
3075                            ceph_mdsmap_get_addr(newmap, i),
3076                            sizeof(struct ceph_entity_addr))) {
3077                         if (s->s_state == CEPH_MDS_SESSION_OPENING) {
3078                                 /* the session never opened, just close it
3079                                  * out now */
3080                                 __wake_requests(mdsc, &s->s_waiting);
3081                                 __unregister_session(mdsc, s);
3082                         } else {
3083                                 /* just close it */
3084                                 mutex_unlock(&mdsc->mutex);
3085                                 mutex_lock(&s->s_mutex);
3086                                 mutex_lock(&mdsc->mutex);
3087                                 ceph_con_close(&s->s_con);
3088                                 mutex_unlock(&s->s_mutex);
3089                                 s->s_state = CEPH_MDS_SESSION_RESTARTING;
3090                         }
3091                 } else if (oldstate == newstate) {
3092                         continue;  /* nothing new with this mds */
3093                 }
3094
3095                 /*
3096                  * send reconnect?
3097                  */
3098                 if (s->s_state == CEPH_MDS_SESSION_RESTARTING &&
3099                     newstate >= CEPH_MDS_STATE_RECONNECT) {
3100                         mutex_unlock(&mdsc->mutex);
3101                         send_mds_reconnect(mdsc, s);
3102                         mutex_lock(&mdsc->mutex);
3103                 }
3104
3105                 /*
3106                  * kick request on any mds that has gone active.
3107                  */
3108                 if (oldstate < CEPH_MDS_STATE_ACTIVE &&
3109                     newstate >= CEPH_MDS_STATE_ACTIVE) {
3110                         if (oldstate != CEPH_MDS_STATE_CREATING &&
3111                             oldstate != CEPH_MDS_STATE_STARTING)
3112                                 pr_info("mds%d recovery completed\n", s->s_mds);
3113                         kick_requests(mdsc, i);
3114                         ceph_kick_flushing_caps(mdsc, s);
3115                         wake_up_session_caps(s, 1);
3116                 }
3117         }
3118
3119         for (i = 0; i < newmap->m_max_mds && i < mdsc->max_sessions; i++) {
3120                 s = mdsc->sessions[i];
3121                 if (!s)
3122                         continue;
3123                 if (!ceph_mdsmap_is_laggy(newmap, i))
3124                         continue;
3125                 if (s->s_state == CEPH_MDS_SESSION_OPEN ||
3126                     s->s_state == CEPH_MDS_SESSION_HUNG ||
3127                     s->s_state == CEPH_MDS_SESSION_CLOSING) {
3128                         dout(" connecting to export targets of laggy mds%d\n",
3129                              i);
3130                         __open_export_target_sessions(mdsc, s);
3131                 }
3132         }
3133 }
3134
3135
3136
3137 /*
3138  * leases
3139  */
3140
3141 /*
3142  * caller must hold session s_mutex, dentry->d_lock
3143  */
3144 void __ceph_mdsc_drop_dentry_lease(struct dentry *dentry)
3145 {
3146         struct ceph_dentry_info *di = ceph_dentry(dentry);
3147
3148         ceph_put_mds_session(di->lease_session);
3149         di->lease_session = NULL;
3150 }
3151
3152 static void handle_lease(struct ceph_mds_client *mdsc,
3153                          struct ceph_mds_session *session,
3154                          struct ceph_msg *msg)
3155 {
3156         struct super_block *sb = mdsc->fsc->sb;
3157         struct inode *inode;
3158         struct dentry *parent, *dentry;
3159         struct ceph_dentry_info *di;
3160         int mds = session->s_mds;
3161         struct ceph_mds_lease *h = msg->front.iov_base;
3162         u32 seq;
3163         struct ceph_vino vino;
3164         struct qstr dname;
3165         int release = 0;
3166
3167         dout("handle_lease from mds%d\n", mds);
3168
3169         /* decode */
3170         if (msg->front.iov_len < sizeof(*h) + sizeof(u32))
3171                 goto bad;
3172         vino.ino = le64_to_cpu(h->ino);
3173         vino.snap = CEPH_NOSNAP;
3174         seq = le32_to_cpu(h->seq);
3175         dname.name = (void *)h + sizeof(*h) + sizeof(u32);
3176         dname.len = msg->front.iov_len - sizeof(*h) - sizeof(u32);
3177         if (dname.len != get_unaligned_le32(h+1))
3178                 goto bad;
3179
3180         /* lookup inode */
3181         inode = ceph_find_inode(sb, vino);
3182         dout("handle_lease %s, ino %llx %p %.*s\n",
3183              ceph_lease_op_name(h->action), vino.ino, inode,
3184              dname.len, dname.name);
3185
3186         mutex_lock(&session->s_mutex);
3187         session->s_seq++;
3188
3189         if (inode == NULL) {
3190                 dout("handle_lease no inode %llx\n", vino.ino);
3191                 goto release;
3192         }
3193
3194         /* dentry */
3195         parent = d_find_alias(inode);
3196         if (!parent) {
3197                 dout("no parent dentry on inode %p\n", inode);
3198                 WARN_ON(1);
3199                 goto release;  /* hrm... */
3200         }
3201         dname.hash = full_name_hash(dname.name, dname.len);
3202         dentry = d_lookup(parent, &dname);
3203         dput(parent);
3204         if (!dentry)
3205                 goto release;
3206
3207         spin_lock(&dentry->d_lock);
3208         di = ceph_dentry(dentry);
3209         switch (h->action) {
3210         case CEPH_MDS_LEASE_REVOKE:
3211                 if (di->lease_session == session) {
3212                         if (ceph_seq_cmp(di->lease_seq, seq) > 0)
3213                                 h->seq = cpu_to_le32(di->lease_seq);
3214                         __ceph_mdsc_drop_dentry_lease(dentry);
3215                 }
3216                 release = 1;
3217                 break;
3218
3219         case CEPH_MDS_LEASE_RENEW:
3220                 if (di->lease_session == session &&
3221                     di->lease_gen == session->s_cap_gen &&
3222                     di->lease_renew_from &&
3223                     di->lease_renew_after == 0) {
3224                         unsigned long duration =
3225                                 msecs_to_jiffies(le32_to_cpu(h->duration_ms));
3226
3227                         di->lease_seq = seq;
3228                         dentry->d_time = di->lease_renew_from + duration;
3229                         di->lease_renew_after = di->lease_renew_from +
3230                                 (duration >> 1);
3231                         di->lease_renew_from = 0;
3232                 }
3233                 break;
3234         }
3235         spin_unlock(&dentry->d_lock);
3236         dput(dentry);
3237
3238         if (!release)
3239                 goto out;
3240
3241 release:
3242         /* let's just reuse the same message */
3243         h->action = CEPH_MDS_LEASE_REVOKE_ACK;
3244         ceph_msg_get(msg);
3245         ceph_con_send(&session->s_con, msg);
3246
3247 out:
3248         iput(inode);
3249         mutex_unlock(&session->s_mutex);
3250         return;
3251
3252 bad:
3253         pr_err("corrupt lease message\n");
3254         ceph_msg_dump(msg);
3255 }
3256
3257 void ceph_mdsc_lease_send_msg(struct ceph_mds_session *session,
3258                               struct inode *inode,
3259                               struct dentry *dentry, char action,
3260                               u32 seq)
3261 {
3262         struct ceph_msg *msg;
3263         struct ceph_mds_lease *lease;
3264         int len = sizeof(*lease) + sizeof(u32);
3265         int dnamelen = 0;
3266
3267         dout("lease_send_msg inode %p dentry %p %s to mds%d\n",
3268              inode, dentry, ceph_lease_op_name(action), session->s_mds);
3269         dnamelen = dentry->d_name.len;
3270         len += dnamelen;
3271
3272         msg = ceph_msg_new(CEPH_MSG_CLIENT_LEASE, len, GFP_NOFS, false);
3273         if (!msg)
3274                 return;
3275         lease = msg->front.iov_base;
3276         lease->action = action;
3277         lease->ino = cpu_to_le64(ceph_vino(inode).ino);
3278         lease->first = lease->last = cpu_to_le64(ceph_vino(inode).snap);
3279         lease->seq = cpu_to_le32(seq);
3280         put_unaligned_le32(dnamelen, lease + 1);
3281         memcpy((void *)(lease + 1) + 4, dentry->d_name.name, dnamelen);
3282
3283         /*
3284          * if this is a preemptive lease RELEASE, no need to
3285          * flush request stream, since the actual request will
3286          * soon follow.
3287          */
3288         msg->more_to_follow = (action == CEPH_MDS_LEASE_RELEASE);
3289
3290         ceph_con_send(&session->s_con, msg);
3291 }
3292
3293 /*
3294  * Preemptively release a lease we expect to invalidate anyway.
3295  * Pass @inode always, @dentry is optional.
3296  */
3297 void ceph_mdsc_lease_release(struct ceph_mds_client *mdsc, struct inode *inode,
3298                              struct dentry *dentry)
3299 {
3300         struct ceph_dentry_info *di;
3301         struct ceph_mds_session *session;
3302         u32 seq;
3303
3304         BUG_ON(inode == NULL);
3305         BUG_ON(dentry == NULL);
3306
3307         /* is dentry lease valid? */
3308         spin_lock(&dentry->d_lock);
3309         di = ceph_dentry(dentry);
3310         if (!di || !di->lease_session ||
3311             di->lease_session->s_mds < 0 ||
3312             di->lease_gen != di->lease_session->s_cap_gen ||
3313             !time_before(jiffies, dentry->d_time)) {
3314                 dout("lease_release inode %p dentry %p -- "
3315                      "no lease\n",
3316                      inode, dentry);
3317                 spin_unlock(&dentry->d_lock);
3318                 return;
3319         }
3320
3321         /* we do have a lease on this dentry; note mds and seq */
3322         session = ceph_get_mds_session(di->lease_session);
3323         seq = di->lease_seq;
3324         __ceph_mdsc_drop_dentry_lease(dentry);
3325         spin_unlock(&dentry->d_lock);
3326
3327         dout("lease_release inode %p dentry %p to mds%d\n",
3328              inode, dentry, session->s_mds);
3329         ceph_mdsc_lease_send_msg(session, inode, dentry,
3330                                  CEPH_MDS_LEASE_RELEASE, seq);
3331         ceph_put_mds_session(session);
3332 }
3333
3334 /*
3335  * drop all leases (and dentry refs) in preparation for umount
3336  */
3337 static void drop_leases(struct ceph_mds_client *mdsc)
3338 {
3339         int i;
3340
3341         dout("drop_leases\n");
3342         mutex_lock(&mdsc->mutex);
3343         for (i = 0; i < mdsc->max_sessions; i++) {
3344                 struct ceph_mds_session *s = __ceph_lookup_mds_session(mdsc, i);
3345                 if (!s)
3346                         continue;
3347                 mutex_unlock(&mdsc->mutex);
3348                 mutex_lock(&s->s_mutex);
3349                 mutex_unlock(&s->s_mutex);
3350                 ceph_put_mds_session(s);
3351                 mutex_lock(&mdsc->mutex);
3352         }
3353         mutex_unlock(&mdsc->mutex);
3354 }
3355
3356
3357
3358 /*
3359  * delayed work -- periodically trim expired leases, renew caps with mds
3360  */
3361 static void schedule_delayed(struct ceph_mds_client *mdsc)
3362 {
3363         int delay = 5;
3364         unsigned hz = round_jiffies_relative(HZ * delay);
3365         schedule_delayed_work(&mdsc->delayed_work, hz);
3366 }
3367
3368 static void delayed_work(struct work_struct *work)
3369 {
3370         int i;
3371         struct ceph_mds_client *mdsc =
3372                 container_of(work, struct ceph_mds_client, delayed_work.work);
3373         int renew_interval;
3374         int renew_caps;
3375
3376         dout("mdsc delayed_work\n");
3377         ceph_check_delayed_caps(mdsc);
3378
3379         mutex_lock(&mdsc->mutex);
3380         renew_interval = mdsc->mdsmap->m_session_timeout >> 2;
3381         renew_caps = time_after_eq(jiffies, HZ*renew_interval +
3382                                    mdsc->last_renew_caps);
3383         if (renew_caps)
3384                 mdsc->last_renew_caps = jiffies;
3385
3386         for (i = 0; i < mdsc->max_sessions; i++) {
3387                 struct ceph_mds_session *s = __ceph_lookup_mds_session(mdsc, i);
3388                 if (s == NULL)
3389                         continue;
3390                 if (s->s_state == CEPH_MDS_SESSION_CLOSING) {
3391                         dout("resending session close request for mds%d\n",
3392                              s->s_mds);
3393                         request_close_session(mdsc, s);
3394                         ceph_put_mds_session(s);
3395                         continue;
3396                 }
3397                 if (s->s_ttl && time_after(jiffies, s->s_ttl)) {
3398                         if (s->s_state == CEPH_MDS_SESSION_OPEN) {
3399                                 s->s_state = CEPH_MDS_SESSION_HUNG;
3400                                 pr_info("mds%d hung\n", s->s_mds);
3401                         }
3402                 }
3403                 if (s->s_state < CEPH_MDS_SESSION_OPEN) {
3404                         /* this mds is failed or recovering, just wait */
3405                         ceph_put_mds_session(s);
3406                         continue;
3407                 }
3408                 mutex_unlock(&mdsc->mutex);
3409
3410                 mutex_lock(&s->s_mutex);
3411                 if (renew_caps)
3412                         send_renew_caps(mdsc, s);
3413                 else
3414                         ceph_con_keepalive(&s->s_con);
3415                 if (s->s_state == CEPH_MDS_SESSION_OPEN ||
3416                     s->s_state == CEPH_MDS_SESSION_HUNG)
3417                         ceph_send_cap_releases(mdsc, s);
3418                 mutex_unlock(&s->s_mutex);
3419                 ceph_put_mds_session(s);
3420
3421                 mutex_lock(&mdsc->mutex);
3422         }
3423         mutex_unlock(&mdsc->mutex);
3424
3425         schedule_delayed(mdsc);
3426 }
3427
3428 int ceph_mdsc_init(struct ceph_fs_client *fsc)
3429
3430 {
3431         struct ceph_mds_client *mdsc;
3432
3433         mdsc = kzalloc(sizeof(struct ceph_mds_client), GFP_NOFS);
3434         if (!mdsc)
3435                 return -ENOMEM;
3436         mdsc->fsc = fsc;
3437         fsc->mdsc = mdsc;
3438         mutex_init(&mdsc->mutex);
3439         mdsc->mdsmap = kzalloc(sizeof(*mdsc->mdsmap), GFP_NOFS);
3440         if (mdsc->mdsmap == NULL) {
3441                 kfree(mdsc);
3442                 return -ENOMEM;
3443         }
3444
3445         init_completion(&mdsc->safe_umount_waiters);
3446         init_waitqueue_head(&mdsc->session_close_wq);
3447         INIT_LIST_HEAD(&mdsc->waiting_for_map);
3448         mdsc->sessions = NULL;
3449         atomic_set(&mdsc->num_sessions, 0);
3450         mdsc->max_sessions = 0;
3451         mdsc->stopping = 0;
3452         mdsc->last_snap_seq = 0;
3453         init_rwsem(&mdsc->snap_rwsem);
3454         mdsc->snap_realms = RB_ROOT;
3455         INIT_LIST_HEAD(&mdsc->snap_empty);
3456         spin_lock_init(&mdsc->snap_empty_lock);
3457         mdsc->last_tid = 0;
3458         mdsc->oldest_tid = 0;
3459         mdsc->request_tree = RB_ROOT;
3460         INIT_DELAYED_WORK(&mdsc->delayed_work, delayed_work);
3461         mdsc->last_renew_caps = jiffies;
3462         INIT_LIST_HEAD(&mdsc->cap_delay_list);
3463         spin_lock_init(&mdsc->cap_delay_lock);
3464         INIT_LIST_HEAD(&mdsc->snap_flush_list);
3465         spin_lock_init(&mdsc->snap_flush_lock);
3466         mdsc->last_cap_flush_tid = 1;
3467         mdsc->cap_flush_tree = RB_ROOT;
3468         INIT_LIST_HEAD(&mdsc->cap_dirty);
3469         INIT_LIST_HEAD(&mdsc->cap_dirty_migrating);
3470         mdsc->num_cap_flushing = 0;
3471         spin_lock_init(&mdsc->cap_dirty_lock);
3472         init_waitqueue_head(&mdsc->cap_flushing_wq);
3473         spin_lock_init(&mdsc->dentry_lru_lock);
3474         INIT_LIST_HEAD(&mdsc->dentry_lru);
3475
3476         ceph_caps_init(mdsc);
3477         ceph_adjust_min_caps(mdsc, fsc->min_caps);
3478
3479         init_rwsem(&mdsc->pool_perm_rwsem);
3480         mdsc->pool_perm_tree = RB_ROOT;
3481
3482         return 0;
3483 }
3484
3485 /*
3486  * Wait for safe replies on open mds requests.  If we time out, drop
3487  * all requests from the tree to avoid dangling dentry refs.
3488  */
3489 static void wait_requests(struct ceph_mds_client *mdsc)
3490 {
3491         struct ceph_options *opts = mdsc->fsc->client->options;
3492         struct ceph_mds_request *req;
3493
3494         mutex_lock(&mdsc->mutex);
3495         if (__get_oldest_req(mdsc)) {
3496                 mutex_unlock(&mdsc->mutex);
3497
3498                 dout("wait_requests waiting for requests\n");
3499                 wait_for_completion_timeout(&mdsc->safe_umount_waiters,
3500                                     ceph_timeout_jiffies(opts->mount_timeout));
3501
3502                 /* tear down remaining requests */
3503                 mutex_lock(&mdsc->mutex);
3504                 while ((req = __get_oldest_req(mdsc))) {
3505                         dout("wait_requests timed out on tid %llu\n",
3506                              req->r_tid);
3507                         __unregister_request(mdsc, req);
3508                 }
3509         }
3510         mutex_unlock(&mdsc->mutex);
3511         dout("wait_requests done\n");
3512 }
3513
3514 /*
3515  * called before mount is ro, and before dentries are torn down.
3516  * (hmm, does this still race with new lookups?)
3517  */
3518 void ceph_mdsc_pre_umount(struct ceph_mds_client *mdsc)
3519 {
3520         dout("pre_umount\n");
3521         mdsc->stopping = 1;
3522
3523         drop_leases(mdsc);
3524         ceph_flush_dirty_caps(mdsc);
3525         wait_requests(mdsc);
3526
3527         /*
3528          * wait for reply handlers to drop their request refs and
3529          * their inode/dcache refs
3530          */
3531         ceph_msgr_flush();
3532 }
3533
3534 /*
3535  * wait for all write mds requests to flush.
3536  */
3537 static void wait_unsafe_requests(struct ceph_mds_client *mdsc, u64 want_tid)
3538 {
3539         struct ceph_mds_request *req = NULL, *nextreq;
3540         struct rb_node *n;
3541
3542         mutex_lock(&mdsc->mutex);
3543         dout("wait_unsafe_requests want %lld\n", want_tid);
3544 restart:
3545         req = __get_oldest_req(mdsc);
3546         while (req && req->r_tid <= want_tid) {
3547                 /* find next request */
3548                 n = rb_next(&req->r_node);
3549                 if (n)
3550                         nextreq = rb_entry(n, struct ceph_mds_request, r_node);
3551                 else
3552                         nextreq = NULL;
3553                 if (req->r_op != CEPH_MDS_OP_SETFILELOCK &&
3554                     (req->r_op & CEPH_MDS_OP_WRITE)) {
3555                         /* write op */
3556                         ceph_mdsc_get_request(req);
3557                         if (nextreq)
3558                                 ceph_mdsc_get_request(nextreq);
3559                         mutex_unlock(&mdsc->mutex);
3560                         dout("wait_unsafe_requests  wait on %llu (want %llu)\n",
3561                              req->r_tid, want_tid);
3562                         wait_for_completion(&req->r_safe_completion);
3563                         mutex_lock(&mdsc->mutex);
3564                         ceph_mdsc_put_request(req);
3565                         if (!nextreq)
3566                                 break;  /* next dne before, so we're done! */
3567                         if (RB_EMPTY_NODE(&nextreq->r_node)) {
3568                                 /* next request was removed from tree */
3569                                 ceph_mdsc_put_request(nextreq);
3570                                 goto restart;
3571                         }
3572                         ceph_mdsc_put_request(nextreq);  /* won't go away */
3573                 }
3574                 req = nextreq;
3575         }
3576         mutex_unlock(&mdsc->mutex);
3577         dout("wait_unsafe_requests done\n");
3578 }
3579
3580 void ceph_mdsc_sync(struct ceph_mds_client *mdsc)
3581 {
3582         u64 want_tid, want_flush, want_snap;
3583
3584         if (ACCESS_ONCE(mdsc->fsc->mount_state) == CEPH_MOUNT_SHUTDOWN)
3585                 return;
3586
3587         dout("sync\n");
3588         mutex_lock(&mdsc->mutex);
3589         want_tid = mdsc->last_tid;
3590         mutex_unlock(&mdsc->mutex);
3591
3592         ceph_flush_dirty_caps(mdsc);
3593         spin_lock(&mdsc->cap_dirty_lock);
3594         want_flush = mdsc->last_cap_flush_tid;
3595         spin_unlock(&mdsc->cap_dirty_lock);
3596
3597         down_read(&mdsc->snap_rwsem);
3598         want_snap = mdsc->last_snap_seq;
3599         up_read(&mdsc->snap_rwsem);
3600
3601         dout("sync want tid %lld flush_seq %lld snap_seq %lld\n",
3602              want_tid, want_flush, want_snap);
3603
3604         wait_unsafe_requests(mdsc, want_tid);
3605         wait_caps_flush(mdsc, want_flush, want_snap);
3606 }
3607
3608 /*
3609  * true if all sessions are closed, or we force unmount
3610  */
3611 static bool done_closing_sessions(struct ceph_mds_client *mdsc)
3612 {
3613         if (ACCESS_ONCE(mdsc->fsc->mount_state) == CEPH_MOUNT_SHUTDOWN)
3614                 return true;
3615         return atomic_read(&mdsc->num_sessions) == 0;
3616 }
3617
3618 /*
3619  * called after sb is ro.
3620  */
3621 void ceph_mdsc_close_sessions(struct ceph_mds_client *mdsc)
3622 {
3623         struct ceph_options *opts = mdsc->fsc->client->options;
3624         struct ceph_mds_session *session;
3625         int i;
3626
3627         dout("close_sessions\n");
3628
3629         /* close sessions */
3630         mutex_lock(&mdsc->mutex);
3631         for (i = 0; i < mdsc->max_sessions; i++) {
3632                 session = __ceph_lookup_mds_session(mdsc, i);
3633                 if (!session)
3634                         continue;
3635                 mutex_unlock(&mdsc->mutex);
3636                 mutex_lock(&session->s_mutex);
3637                 __close_session(mdsc, session);
3638                 mutex_unlock(&session->s_mutex);
3639                 ceph_put_mds_session(session);
3640                 mutex_lock(&mdsc->mutex);
3641         }
3642         mutex_unlock(&mdsc->mutex);
3643
3644         dout("waiting for sessions to close\n");
3645         wait_event_timeout(mdsc->session_close_wq, done_closing_sessions(mdsc),
3646                            ceph_timeout_jiffies(opts->mount_timeout));
3647
3648         /* tear down remaining sessions */
3649         mutex_lock(&mdsc->mutex);
3650         for (i = 0; i < mdsc->max_sessions; i++) {
3651                 if (mdsc->sessions[i]) {
3652                         session = get_session(mdsc->sessions[i]);
3653                         __unregister_session(mdsc, session);
3654                         mutex_unlock(&mdsc->mutex);
3655                         mutex_lock(&session->s_mutex);
3656                         remove_session_caps(session);
3657                         mutex_unlock(&session->s_mutex);
3658                         ceph_put_mds_session(session);
3659                         mutex_lock(&mdsc->mutex);
3660                 }
3661         }
3662         WARN_ON(!list_empty(&mdsc->cap_delay_list));
3663         mutex_unlock(&mdsc->mutex);
3664
3665         ceph_cleanup_empty_realms(mdsc);
3666
3667         cancel_delayed_work_sync(&mdsc->delayed_work); /* cancel timer */
3668
3669         dout("stopped\n");
3670 }
3671
3672 void ceph_mdsc_force_umount(struct ceph_mds_client *mdsc)
3673 {
3674         struct ceph_mds_session *session;
3675         int mds;
3676
3677         dout("force umount\n");
3678
3679         mutex_lock(&mdsc->mutex);
3680         for (mds = 0; mds < mdsc->max_sessions; mds++) {
3681                 session = __ceph_lookup_mds_session(mdsc, mds);
3682                 if (!session)
3683                         continue;
3684                 mutex_unlock(&mdsc->mutex);
3685                 mutex_lock(&session->s_mutex);
3686                 __close_session(mdsc, session);
3687                 if (session->s_state == CEPH_MDS_SESSION_CLOSING) {
3688                         cleanup_session_requests(mdsc, session);
3689                         remove_session_caps(session);
3690                 }
3691                 mutex_unlock(&session->s_mutex);
3692                 ceph_put_mds_session(session);
3693                 mutex_lock(&mdsc->mutex);
3694                 kick_requests(mdsc, mds);
3695         }
3696         __wake_requests(mdsc, &mdsc->waiting_for_map);
3697         mutex_unlock(&mdsc->mutex);
3698 }
3699
3700 static void ceph_mdsc_stop(struct ceph_mds_client *mdsc)
3701 {
3702         dout("stop\n");
3703         cancel_delayed_work_sync(&mdsc->delayed_work); /* cancel timer */
3704         if (mdsc->mdsmap)
3705                 ceph_mdsmap_destroy(mdsc->mdsmap);
3706         kfree(mdsc->sessions);
3707         ceph_caps_finalize(mdsc);
3708         ceph_pool_perm_destroy(mdsc);
3709 }
3710
3711 void ceph_mdsc_destroy(struct ceph_fs_client *fsc)
3712 {
3713         struct ceph_mds_client *mdsc = fsc->mdsc;
3714
3715         dout("mdsc_destroy %p\n", mdsc);
3716         ceph_mdsc_stop(mdsc);
3717
3718         /* flush out any connection work with references to us */
3719         ceph_msgr_flush();
3720
3721         fsc->mdsc = NULL;
3722         kfree(mdsc);
3723         dout("mdsc_destroy %p done\n", mdsc);
3724 }
3725
3726
3727 /*
3728  * handle mds map update.
3729  */
3730 void ceph_mdsc_handle_map(struct ceph_mds_client *mdsc, struct ceph_msg *msg)
3731 {
3732         u32 epoch;
3733         u32 maplen;
3734         void *p = msg->front.iov_base;
3735         void *end = p + msg->front.iov_len;
3736         struct ceph_mdsmap *newmap, *oldmap;
3737         struct ceph_fsid fsid;
3738         int err = -EINVAL;
3739
3740         ceph_decode_need(&p, end, sizeof(fsid)+2*sizeof(u32), bad);
3741         ceph_decode_copy(&p, &fsid, sizeof(fsid));
3742         if (ceph_check_fsid(mdsc->fsc->client, &fsid) < 0)
3743                 return;
3744         epoch = ceph_decode_32(&p);
3745         maplen = ceph_decode_32(&p);
3746         dout("handle_map epoch %u len %d\n", epoch, (int)maplen);
3747
3748         /* do we need it? */
3749         mutex_lock(&mdsc->mutex);
3750         if (mdsc->mdsmap && epoch <= mdsc->mdsmap->m_epoch) {
3751                 dout("handle_map epoch %u <= our %u\n",
3752                      epoch, mdsc->mdsmap->m_epoch);
3753                 mutex_unlock(&mdsc->mutex);
3754                 return;
3755         }
3756
3757         newmap = ceph_mdsmap_decode(&p, end);
3758         if (IS_ERR(newmap)) {
3759                 err = PTR_ERR(newmap);
3760                 goto bad_unlock;
3761         }
3762
3763         /* swap into place */
3764         if (mdsc->mdsmap) {
3765                 oldmap = mdsc->mdsmap;
3766                 mdsc->mdsmap = newmap;
3767                 check_new_map(mdsc, newmap, oldmap);
3768                 ceph_mdsmap_destroy(oldmap);
3769         } else {
3770                 mdsc->mdsmap = newmap;  /* first mds map */
3771         }
3772         mdsc->fsc->sb->s_maxbytes = mdsc->mdsmap->m_max_file_size;
3773
3774         __wake_requests(mdsc, &mdsc->waiting_for_map);
3775         ceph_monc_got_map(&mdsc->fsc->client->monc, CEPH_SUB_MDSMAP,
3776                           mdsc->mdsmap->m_epoch);
3777
3778         mutex_unlock(&mdsc->mutex);
3779         schedule_delayed(mdsc);
3780         return;
3781
3782 bad_unlock:
3783         mutex_unlock(&mdsc->mutex);
3784 bad:
3785         pr_err("error decoding mdsmap %d\n", err);
3786         return;
3787 }
3788
3789 static struct ceph_connection *con_get(struct ceph_connection *con)
3790 {
3791         struct ceph_mds_session *s = con->private;
3792
3793         if (get_session(s)) {
3794                 dout("mdsc con_get %p ok (%d)\n", s, atomic_read(&s->s_ref));
3795                 return con;
3796         }
3797         dout("mdsc con_get %p FAIL\n", s);
3798         return NULL;
3799 }
3800
3801 static void con_put(struct ceph_connection *con)
3802 {
3803         struct ceph_mds_session *s = con->private;
3804
3805         dout("mdsc con_put %p (%d)\n", s, atomic_read(&s->s_ref) - 1);
3806         ceph_put_mds_session(s);
3807 }
3808
3809 /*
3810  * if the client is unresponsive for long enough, the mds will kill
3811  * the session entirely.
3812  */
3813 static void peer_reset(struct ceph_connection *con)
3814 {
3815         struct ceph_mds_session *s = con->private;
3816         struct ceph_mds_client *mdsc = s->s_mdsc;
3817
3818         pr_warn("mds%d closed our session\n", s->s_mds);
3819         send_mds_reconnect(mdsc, s);
3820 }
3821
3822 static void dispatch(struct ceph_connection *con, struct ceph_msg *msg)
3823 {
3824         struct ceph_mds_session *s = con->private;
3825         struct ceph_mds_client *mdsc = s->s_mdsc;
3826         int type = le16_to_cpu(msg->hdr.type);
3827
3828         mutex_lock(&mdsc->mutex);
3829         if (__verify_registered_session(mdsc, s) < 0) {
3830                 mutex_unlock(&mdsc->mutex);
3831                 goto out;
3832         }
3833         mutex_unlock(&mdsc->mutex);
3834
3835         switch (type) {
3836         case CEPH_MSG_MDS_MAP:
3837                 ceph_mdsc_handle_map(mdsc, msg);
3838                 break;
3839         case CEPH_MSG_CLIENT_SESSION:
3840                 handle_session(s, msg);
3841                 break;
3842         case CEPH_MSG_CLIENT_REPLY:
3843                 handle_reply(s, msg);
3844                 break;
3845         case CEPH_MSG_CLIENT_REQUEST_FORWARD:
3846                 handle_forward(mdsc, s, msg);
3847                 break;
3848         case CEPH_MSG_CLIENT_CAPS:
3849                 ceph_handle_caps(s, msg);
3850                 break;
3851         case CEPH_MSG_CLIENT_SNAP:
3852                 ceph_handle_snap(mdsc, s, msg);
3853                 break;
3854         case CEPH_MSG_CLIENT_LEASE:
3855                 handle_lease(mdsc, s, msg);
3856                 break;
3857
3858         default:
3859                 pr_err("received unknown message type %d %s\n", type,
3860                        ceph_msg_type_name(type));
3861         }
3862 out:
3863         ceph_msg_put(msg);
3864 }
3865
3866 /*
3867  * authentication
3868  */
3869
3870 /*
3871  * Note: returned pointer is the address of a structure that's
3872  * managed separately.  Caller must *not* attempt to free it.
3873  */
3874 static struct ceph_auth_handshake *get_authorizer(struct ceph_connection *con,
3875                                         int *proto, int force_new)
3876 {
3877         struct ceph_mds_session *s = con->private;
3878         struct ceph_mds_client *mdsc = s->s_mdsc;
3879         struct ceph_auth_client *ac = mdsc->fsc->client->monc.auth;
3880         struct ceph_auth_handshake *auth = &s->s_auth;
3881
3882         if (force_new && auth->authorizer) {
3883                 ceph_auth_destroy_authorizer(auth->authorizer);
3884                 auth->authorizer = NULL;
3885         }
3886         if (!auth->authorizer) {
3887                 int ret = ceph_auth_create_authorizer(ac, CEPH_ENTITY_TYPE_MDS,
3888                                                       auth);
3889                 if (ret)
3890                         return ERR_PTR(ret);
3891         } else {
3892                 int ret = ceph_auth_update_authorizer(ac, CEPH_ENTITY_TYPE_MDS,
3893                                                       auth);
3894                 if (ret)
3895                         return ERR_PTR(ret);
3896         }
3897         *proto = ac->protocol;
3898
3899         return auth;
3900 }
3901
3902
3903 static int verify_authorizer_reply(struct ceph_connection *con, int len)
3904 {
3905         struct ceph_mds_session *s = con->private;
3906         struct ceph_mds_client *mdsc = s->s_mdsc;
3907         struct ceph_auth_client *ac = mdsc->fsc->client->monc.auth;
3908
3909         return ceph_auth_verify_authorizer_reply(ac, s->s_auth.authorizer, len);
3910 }
3911
3912 static int invalidate_authorizer(struct ceph_connection *con)
3913 {
3914         struct ceph_mds_session *s = con->private;
3915         struct ceph_mds_client *mdsc = s->s_mdsc;
3916         struct ceph_auth_client *ac = mdsc->fsc->client->monc.auth;
3917
3918         ceph_auth_invalidate_authorizer(ac, CEPH_ENTITY_TYPE_MDS);
3919
3920         return ceph_monc_validate_auth(&mdsc->fsc->client->monc);
3921 }
3922
3923 static struct ceph_msg *mds_alloc_msg(struct ceph_connection *con,
3924                                 struct ceph_msg_header *hdr, int *skip)
3925 {
3926         struct ceph_msg *msg;
3927         int type = (int) le16_to_cpu(hdr->type);
3928         int front_len = (int) le32_to_cpu(hdr->front_len);
3929
3930         if (con->in_msg)
3931                 return con->in_msg;
3932
3933         *skip = 0;
3934         msg = ceph_msg_new(type, front_len, GFP_NOFS, false);
3935         if (!msg) {
3936                 pr_err("unable to allocate msg type %d len %d\n",
3937                        type, front_len);
3938                 return NULL;
3939         }
3940
3941         return msg;
3942 }
3943
3944 static int mds_sign_message(struct ceph_msg *msg)
3945 {
3946        struct ceph_mds_session *s = msg->con->private;
3947        struct ceph_auth_handshake *auth = &s->s_auth;
3948
3949        return ceph_auth_sign_message(auth, msg);
3950 }
3951
3952 static int mds_check_message_signature(struct ceph_msg *msg)
3953 {
3954        struct ceph_mds_session *s = msg->con->private;
3955        struct ceph_auth_handshake *auth = &s->s_auth;
3956
3957        return ceph_auth_check_message_signature(auth, msg);
3958 }
3959
3960 static const struct ceph_connection_operations mds_con_ops = {
3961         .get = con_get,
3962         .put = con_put,
3963         .dispatch = dispatch,
3964         .get_authorizer = get_authorizer,
3965         .verify_authorizer_reply = verify_authorizer_reply,
3966         .invalidate_authorizer = invalidate_authorizer,
3967         .peer_reset = peer_reset,
3968         .alloc_msg = mds_alloc_msg,
3969         .sign_message = mds_sign_message,
3970         .check_message_signature = mds_check_message_signature,
3971 };
3972
3973 /* eof */