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