]> Git Repo - linux.git/blob - fs/ceph/mds_client.c
ceph: use kref for struct ceph_mds_request
[linux.git] / fs / ceph / mds_client.c
1 #include "ceph_debug.h"
2
3 #include <linux/wait.h>
4 #include <linux/sched.h>
5
6 #include "mds_client.h"
7 #include "mon_client.h"
8 #include "super.h"
9 #include "messenger.h"
10 #include "decode.h"
11 #include "auth.h"
12
13 /*
14  * A cluster of MDS (metadata server) daemons is responsible for
15  * managing the file system namespace (the directory hierarchy and
16  * inodes) and for coordinating shared access to storage.  Metadata is
17  * partitioning hierarchically across a number of servers, and that
18  * partition varies over time as the cluster adjusts the distribution
19  * in order to balance load.
20  *
21  * The MDS client is primarily responsible to managing synchronous
22  * metadata requests for operations like open, unlink, and so forth.
23  * If there is a MDS failure, we find out about it when we (possibly
24  * request and) receive a new MDS map, and can resubmit affected
25  * requests.
26  *
27  * For the most part, though, we take advantage of a lossless
28  * communications channel to the MDS, and do not need to worry about
29  * timing out or resubmitting requests.
30  *
31  * We maintain a stateful "session" with each MDS we interact with.
32  * Within each session, we sent periodic heartbeat messages to ensure
33  * any capabilities or leases we have been issues remain valid.  If
34  * the session times out and goes stale, our leases and capabilities
35  * are no longer valid.
36  */
37
38 static void __wake_requests(struct ceph_mds_client *mdsc,
39                             struct list_head *head);
40
41 const static struct ceph_connection_operations mds_con_ops;
42
43
44 /*
45  * mds reply parsing
46  */
47
48 /*
49  * parse individual inode info
50  */
51 static int parse_reply_info_in(void **p, void *end,
52                                struct ceph_mds_reply_info_in *info)
53 {
54         int err = -EIO;
55
56         info->in = *p;
57         *p += sizeof(struct ceph_mds_reply_inode) +
58                 sizeof(*info->in->fragtree.splits) *
59                 le32_to_cpu(info->in->fragtree.nsplits);
60
61         ceph_decode_32_safe(p, end, info->symlink_len, bad);
62         ceph_decode_need(p, end, info->symlink_len, bad);
63         info->symlink = *p;
64         *p += info->symlink_len;
65
66         ceph_decode_32_safe(p, end, info->xattr_len, bad);
67         ceph_decode_need(p, end, info->xattr_len, bad);
68         info->xattr_data = *p;
69         *p += info->xattr_len;
70         return 0;
71 bad:
72         return err;
73 }
74
75 /*
76  * parse a normal reply, which may contain a (dir+)dentry and/or a
77  * target inode.
78  */
79 static int parse_reply_info_trace(void **p, void *end,
80                                   struct ceph_mds_reply_info_parsed *info)
81 {
82         int err;
83
84         if (info->head->is_dentry) {
85                 err = parse_reply_info_in(p, end, &info->diri);
86                 if (err < 0)
87                         goto out_bad;
88
89                 if (unlikely(*p + sizeof(*info->dirfrag) > end))
90                         goto bad;
91                 info->dirfrag = *p;
92                 *p += sizeof(*info->dirfrag) +
93                         sizeof(u32)*le32_to_cpu(info->dirfrag->ndist);
94                 if (unlikely(*p > end))
95                         goto bad;
96
97                 ceph_decode_32_safe(p, end, info->dname_len, bad);
98                 ceph_decode_need(p, end, info->dname_len, bad);
99                 info->dname = *p;
100                 *p += info->dname_len;
101                 info->dlease = *p;
102                 *p += sizeof(*info->dlease);
103         }
104
105         if (info->head->is_target) {
106                 err = parse_reply_info_in(p, end, &info->targeti);
107                 if (err < 0)
108                         goto out_bad;
109         }
110
111         if (unlikely(*p != end))
112                 goto bad;
113         return 0;
114
115 bad:
116         err = -EIO;
117 out_bad:
118         pr_err("problem parsing mds trace %d\n", err);
119         return err;
120 }
121
122 /*
123  * parse readdir results
124  */
125 static int parse_reply_info_dir(void **p, void *end,
126                                 struct ceph_mds_reply_info_parsed *info)
127 {
128         u32 num, i = 0;
129         int err;
130
131         info->dir_dir = *p;
132         if (*p + sizeof(*info->dir_dir) > end)
133                 goto bad;
134         *p += sizeof(*info->dir_dir) +
135                 sizeof(u32)*le32_to_cpu(info->dir_dir->ndist);
136         if (*p > end)
137                 goto bad;
138
139         ceph_decode_need(p, end, sizeof(num) + 2, bad);
140         num = ceph_decode_32(p);
141         info->dir_end = ceph_decode_8(p);
142         info->dir_complete = ceph_decode_8(p);
143         if (num == 0)
144                 goto done;
145
146         /* alloc large array */
147         info->dir_nr = num;
148         info->dir_in = kcalloc(num, sizeof(*info->dir_in) +
149                                sizeof(*info->dir_dname) +
150                                sizeof(*info->dir_dname_len) +
151                                sizeof(*info->dir_dlease),
152                                GFP_NOFS);
153         if (info->dir_in == NULL) {
154                 err = -ENOMEM;
155                 goto out_bad;
156         }
157         info->dir_dname = (void *)(info->dir_in + num);
158         info->dir_dname_len = (void *)(info->dir_dname + num);
159         info->dir_dlease = (void *)(info->dir_dname_len + num);
160
161         while (num) {
162                 /* dentry */
163                 ceph_decode_need(p, end, sizeof(u32)*2, bad);
164                 info->dir_dname_len[i] = ceph_decode_32(p);
165                 ceph_decode_need(p, end, info->dir_dname_len[i], bad);
166                 info->dir_dname[i] = *p;
167                 *p += info->dir_dname_len[i];
168                 dout("parsed dir dname '%.*s'\n", info->dir_dname_len[i],
169                      info->dir_dname[i]);
170                 info->dir_dlease[i] = *p;
171                 *p += sizeof(struct ceph_mds_reply_lease);
172
173                 /* inode */
174                 err = parse_reply_info_in(p, end, &info->dir_in[i]);
175                 if (err < 0)
176                         goto out_bad;
177                 i++;
178                 num--;
179         }
180
181 done:
182         if (*p != end)
183                 goto bad;
184         return 0;
185
186 bad:
187         err = -EIO;
188 out_bad:
189         pr_err("problem parsing dir contents %d\n", err);
190         return err;
191 }
192
193 /*
194  * parse entire mds reply
195  */
196 static int parse_reply_info(struct ceph_msg *msg,
197                             struct ceph_mds_reply_info_parsed *info)
198 {
199         void *p, *end;
200         u32 len;
201         int err;
202
203         info->head = msg->front.iov_base;
204         p = msg->front.iov_base + sizeof(struct ceph_mds_reply_head);
205         end = p + msg->front.iov_len - sizeof(struct ceph_mds_reply_head);
206
207         /* trace */
208         ceph_decode_32_safe(&p, end, len, bad);
209         if (len > 0) {
210                 err = parse_reply_info_trace(&p, p+len, info);
211                 if (err < 0)
212                         goto out_bad;
213         }
214
215         /* dir content */
216         ceph_decode_32_safe(&p, end, len, bad);
217         if (len > 0) {
218                 err = parse_reply_info_dir(&p, p+len, info);
219                 if (err < 0)
220                         goto out_bad;
221         }
222
223         /* snap blob */
224         ceph_decode_32_safe(&p, end, len, bad);
225         info->snapblob_len = len;
226         info->snapblob = p;
227         p += len;
228
229         if (p != end)
230                 goto bad;
231         return 0;
232
233 bad:
234         err = -EIO;
235 out_bad:
236         pr_err("mds parse_reply err %d\n", err);
237         return err;
238 }
239
240 static void destroy_reply_info(struct ceph_mds_reply_info_parsed *info)
241 {
242         kfree(info->dir_in);
243 }
244
245
246 /*
247  * sessions
248  */
249 static const char *session_state_name(int s)
250 {
251         switch (s) {
252         case CEPH_MDS_SESSION_NEW: return "new";
253         case CEPH_MDS_SESSION_OPENING: return "opening";
254         case CEPH_MDS_SESSION_OPEN: return "open";
255         case CEPH_MDS_SESSION_HUNG: return "hung";
256         case CEPH_MDS_SESSION_CLOSING: return "closing";
257         case CEPH_MDS_SESSION_RECONNECTING: return "reconnecting";
258         default: return "???";
259         }
260 }
261
262 static struct ceph_mds_session *get_session(struct ceph_mds_session *s)
263 {
264         if (atomic_inc_not_zero(&s->s_ref)) {
265                 dout("mdsc get_session %p %d -> %d\n", s,
266                      atomic_read(&s->s_ref)-1, atomic_read(&s->s_ref));
267                 return s;
268         } else {
269                 dout("mdsc get_session %p 0 -- FAIL", s);
270                 return NULL;
271         }
272 }
273
274 void ceph_put_mds_session(struct ceph_mds_session *s)
275 {
276         dout("mdsc put_session %p %d -> %d\n", s,
277              atomic_read(&s->s_ref), atomic_read(&s->s_ref)-1);
278         if (atomic_dec_and_test(&s->s_ref)) {
279                 if (s->s_authorizer)
280                         s->s_mdsc->client->monc.auth->ops->destroy_authorizer(
281                                 s->s_mdsc->client->monc.auth, s->s_authorizer);
282                 kfree(s);
283         }
284 }
285
286 /*
287  * called under mdsc->mutex
288  */
289 struct ceph_mds_session *__ceph_lookup_mds_session(struct ceph_mds_client *mdsc,
290                                                    int mds)
291 {
292         struct ceph_mds_session *session;
293
294         if (mds >= mdsc->max_sessions || mdsc->sessions[mds] == NULL)
295                 return NULL;
296         session = mdsc->sessions[mds];
297         dout("lookup_mds_session %p %d\n", session,
298              atomic_read(&session->s_ref));
299         get_session(session);
300         return session;
301 }
302
303 static bool __have_session(struct ceph_mds_client *mdsc, int mds)
304 {
305         if (mds >= mdsc->max_sessions)
306                 return false;
307         return mdsc->sessions[mds];
308 }
309
310 /*
311  * create+register a new session for given mds.
312  * called under mdsc->mutex.
313  */
314 static struct ceph_mds_session *register_session(struct ceph_mds_client *mdsc,
315                                                  int mds)
316 {
317         struct ceph_mds_session *s;
318
319         s = kzalloc(sizeof(*s), GFP_NOFS);
320         s->s_mdsc = mdsc;
321         s->s_mds = mds;
322         s->s_state = CEPH_MDS_SESSION_NEW;
323         s->s_ttl = 0;
324         s->s_seq = 0;
325         mutex_init(&s->s_mutex);
326
327         ceph_con_init(mdsc->client->msgr, &s->s_con);
328         s->s_con.private = s;
329         s->s_con.ops = &mds_con_ops;
330         s->s_con.peer_name.type = CEPH_ENTITY_TYPE_MDS;
331         s->s_con.peer_name.num = cpu_to_le64(mds);
332
333         spin_lock_init(&s->s_cap_lock);
334         s->s_cap_gen = 0;
335         s->s_cap_ttl = 0;
336         s->s_renew_requested = 0;
337         s->s_renew_seq = 0;
338         INIT_LIST_HEAD(&s->s_caps);
339         s->s_nr_caps = 0;
340         atomic_set(&s->s_ref, 1);
341         INIT_LIST_HEAD(&s->s_waiting);
342         INIT_LIST_HEAD(&s->s_unsafe);
343         s->s_num_cap_releases = 0;
344         INIT_LIST_HEAD(&s->s_cap_releases);
345         INIT_LIST_HEAD(&s->s_cap_releases_done);
346         INIT_LIST_HEAD(&s->s_cap_flushing);
347         INIT_LIST_HEAD(&s->s_cap_snaps_flushing);
348
349         dout("register_session mds%d\n", mds);
350         if (mds >= mdsc->max_sessions) {
351                 int newmax = 1 << get_count_order(mds+1);
352                 struct ceph_mds_session **sa;
353
354                 dout("register_session realloc to %d\n", newmax);
355                 sa = kcalloc(newmax, sizeof(void *), GFP_NOFS);
356                 if (sa == NULL)
357                         goto fail_realloc;
358                 if (mdsc->sessions) {
359                         memcpy(sa, mdsc->sessions,
360                                mdsc->max_sessions * sizeof(void *));
361                         kfree(mdsc->sessions);
362                 }
363                 mdsc->sessions = sa;
364                 mdsc->max_sessions = newmax;
365         }
366         mdsc->sessions[mds] = s;
367         atomic_inc(&s->s_ref);  /* one ref to sessions[], one to caller */
368
369         ceph_con_open(&s->s_con, ceph_mdsmap_get_addr(mdsc->mdsmap, mds));
370
371         return s;
372
373 fail_realloc:
374         kfree(s);
375         return ERR_PTR(-ENOMEM);
376 }
377
378 /*
379  * called under mdsc->mutex
380  */
381 static void unregister_session(struct ceph_mds_client *mdsc,
382                                struct ceph_mds_session *s)
383 {
384         dout("unregister_session mds%d %p\n", s->s_mds, s);
385         mdsc->sessions[s->s_mds] = NULL;
386         ceph_con_close(&s->s_con);
387         ceph_put_mds_session(s);
388 }
389
390 /*
391  * drop session refs in request.
392  *
393  * should be last request ref, or hold mdsc->mutex
394  */
395 static void put_request_session(struct ceph_mds_request *req)
396 {
397         if (req->r_session) {
398                 ceph_put_mds_session(req->r_session);
399                 req->r_session = NULL;
400         }
401 }
402
403 void ceph_mdsc_release_request(struct kref *kref)
404 {
405         struct ceph_mds_request *req = container_of(kref,
406                                                     struct ceph_mds_request,
407                                                     r_kref);
408         if (req->r_request)
409                 ceph_msg_put(req->r_request);
410         if (req->r_reply) {
411                 ceph_msg_put(req->r_reply);
412                 destroy_reply_info(&req->r_reply_info);
413         }
414         if (req->r_inode) {
415                 ceph_put_cap_refs(ceph_inode(req->r_inode),
416                                   CEPH_CAP_PIN);
417                 iput(req->r_inode);
418         }
419         if (req->r_locked_dir)
420                 ceph_put_cap_refs(ceph_inode(req->r_locked_dir),
421                                   CEPH_CAP_PIN);
422         if (req->r_target_inode)
423                 iput(req->r_target_inode);
424         if (req->r_dentry)
425                 dput(req->r_dentry);
426         if (req->r_old_dentry) {
427                 ceph_put_cap_refs(
428                         ceph_inode(req->r_old_dentry->d_parent->d_inode),
429                         CEPH_CAP_PIN);
430                 dput(req->r_old_dentry);
431         }
432         kfree(req->r_path1);
433         kfree(req->r_path2);
434         put_request_session(req);
435         ceph_unreserve_caps(&req->r_caps_reservation);
436         kfree(req);
437 }
438
439 /*
440  * lookup session, bump ref if found.
441  *
442  * called under mdsc->mutex.
443  */
444 static struct ceph_mds_request *__lookup_request(struct ceph_mds_client *mdsc,
445                                              u64 tid)
446 {
447         struct ceph_mds_request *req;
448         req = radix_tree_lookup(&mdsc->request_tree, tid);
449         if (req)
450                 ceph_mdsc_get_request(req);
451         return req;
452 }
453
454 /*
455  * Register an in-flight request, and assign a tid.  Link to directory
456  * are modifying (if any).
457  *
458  * Called under mdsc->mutex.
459  */
460 static void __register_request(struct ceph_mds_client *mdsc,
461                                struct ceph_mds_request *req,
462                                struct inode *dir)
463 {
464         req->r_tid = ++mdsc->last_tid;
465         if (req->r_num_caps)
466                 ceph_reserve_caps(&req->r_caps_reservation, req->r_num_caps);
467         dout("__register_request %p tid %lld\n", req, req->r_tid);
468         ceph_mdsc_get_request(req);
469         radix_tree_insert(&mdsc->request_tree, req->r_tid, (void *)req);
470
471         if (dir) {
472                 struct ceph_inode_info *ci = ceph_inode(dir);
473
474                 spin_lock(&ci->i_unsafe_lock);
475                 req->r_unsafe_dir = dir;
476                 list_add_tail(&req->r_unsafe_dir_item, &ci->i_unsafe_dirops);
477                 spin_unlock(&ci->i_unsafe_lock);
478         }
479 }
480
481 static void __unregister_request(struct ceph_mds_client *mdsc,
482                                  struct ceph_mds_request *req)
483 {
484         dout("__unregister_request %p tid %lld\n", req, req->r_tid);
485         radix_tree_delete(&mdsc->request_tree, req->r_tid);
486         ceph_mdsc_put_request(req);
487
488         if (req->r_unsafe_dir) {
489                 struct ceph_inode_info *ci = ceph_inode(req->r_unsafe_dir);
490
491                 spin_lock(&ci->i_unsafe_lock);
492                 list_del_init(&req->r_unsafe_dir_item);
493                 spin_unlock(&ci->i_unsafe_lock);
494         }
495 }
496
497 /*
498  * Choose mds to send request to next.  If there is a hint set in the
499  * request (e.g., due to a prior forward hint from the mds), use that.
500  * Otherwise, consult frag tree and/or caps to identify the
501  * appropriate mds.  If all else fails, choose randomly.
502  *
503  * Called under mdsc->mutex.
504  */
505 static int __choose_mds(struct ceph_mds_client *mdsc,
506                         struct ceph_mds_request *req)
507 {
508         struct inode *inode;
509         struct ceph_inode_info *ci;
510         struct ceph_cap *cap;
511         int mode = req->r_direct_mode;
512         int mds = -1;
513         u32 hash = req->r_direct_hash;
514         bool is_hash = req->r_direct_is_hash;
515
516         /*
517          * is there a specific mds we should try?  ignore hint if we have
518          * no session and the mds is not up (active or recovering).
519          */
520         if (req->r_resend_mds >= 0 &&
521             (__have_session(mdsc, req->r_resend_mds) ||
522              ceph_mdsmap_get_state(mdsc->mdsmap, req->r_resend_mds) > 0)) {
523                 dout("choose_mds using resend_mds mds%d\n",
524                      req->r_resend_mds);
525                 return req->r_resend_mds;
526         }
527
528         if (mode == USE_RANDOM_MDS)
529                 goto random;
530
531         inode = NULL;
532         if (req->r_inode) {
533                 inode = req->r_inode;
534         } else if (req->r_dentry) {
535                 if (req->r_dentry->d_inode) {
536                         inode = req->r_dentry->d_inode;
537                 } else {
538                         inode = req->r_dentry->d_parent->d_inode;
539                         hash = req->r_dentry->d_name.hash;
540                         is_hash = true;
541                 }
542         }
543         dout("__choose_mds %p is_hash=%d (%d) mode %d\n", inode, (int)is_hash,
544              (int)hash, mode);
545         if (!inode)
546                 goto random;
547         ci = ceph_inode(inode);
548
549         if (is_hash && S_ISDIR(inode->i_mode)) {
550                 struct ceph_inode_frag frag;
551                 int found;
552
553                 ceph_choose_frag(ci, hash, &frag, &found);
554                 if (found) {
555                         if (mode == USE_ANY_MDS && frag.ndist > 0) {
556                                 u8 r;
557
558                                 /* choose a random replica */
559                                 get_random_bytes(&r, 1);
560                                 r %= frag.ndist;
561                                 mds = frag.dist[r];
562                                 dout("choose_mds %p %llx.%llx "
563                                      "frag %u mds%d (%d/%d)\n",
564                                      inode, ceph_vinop(inode),
565                                      frag.frag, frag.mds,
566                                      (int)r, frag.ndist);
567                                 return mds;
568                         }
569
570                         /* since this file/dir wasn't known to be
571                          * replicated, then we want to look for the
572                          * authoritative mds. */
573                         mode = USE_AUTH_MDS;
574                         if (frag.mds >= 0) {
575                                 /* choose auth mds */
576                                 mds = frag.mds;
577                                 dout("choose_mds %p %llx.%llx "
578                                      "frag %u mds%d (auth)\n",
579                                      inode, ceph_vinop(inode), frag.frag, mds);
580                                 return mds;
581                         }
582                 }
583         }
584
585         spin_lock(&inode->i_lock);
586         cap = NULL;
587         if (mode == USE_AUTH_MDS)
588                 cap = ci->i_auth_cap;
589         if (!cap && !RB_EMPTY_ROOT(&ci->i_caps))
590                 cap = rb_entry(rb_first(&ci->i_caps), struct ceph_cap, ci_node);
591         if (!cap) {
592                 spin_unlock(&inode->i_lock);
593                 goto random;
594         }
595         mds = cap->session->s_mds;
596         dout("choose_mds %p %llx.%llx mds%d (%scap %p)\n",
597              inode, ceph_vinop(inode), mds,
598              cap == ci->i_auth_cap ? "auth " : "", cap);
599         spin_unlock(&inode->i_lock);
600         return mds;
601
602 random:
603         mds = ceph_mdsmap_get_random_mds(mdsc->mdsmap);
604         dout("choose_mds chose random mds%d\n", mds);
605         return mds;
606 }
607
608
609 /*
610  * session messages
611  */
612 static struct ceph_msg *create_session_msg(u32 op, u64 seq)
613 {
614         struct ceph_msg *msg;
615         struct ceph_mds_session_head *h;
616
617         msg = ceph_msg_new(CEPH_MSG_CLIENT_SESSION, sizeof(*h), 0, 0, NULL);
618         if (IS_ERR(msg)) {
619                 pr_err("create_session_msg ENOMEM creating msg\n");
620                 return ERR_PTR(PTR_ERR(msg));
621         }
622         h = msg->front.iov_base;
623         h->op = cpu_to_le32(op);
624         h->seq = cpu_to_le64(seq);
625         return msg;
626 }
627
628 /*
629  * send session open request.
630  *
631  * called under mdsc->mutex
632  */
633 static int __open_session(struct ceph_mds_client *mdsc,
634                           struct ceph_mds_session *session)
635 {
636         struct ceph_msg *msg;
637         int mstate;
638         int mds = session->s_mds;
639         int err = 0;
640
641         /* wait for mds to go active? */
642         mstate = ceph_mdsmap_get_state(mdsc->mdsmap, mds);
643         dout("open_session to mds%d (%s)\n", mds,
644              ceph_mds_state_name(mstate));
645         session->s_state = CEPH_MDS_SESSION_OPENING;
646         session->s_renew_requested = jiffies;
647
648         /* send connect message */
649         msg = create_session_msg(CEPH_SESSION_REQUEST_OPEN, session->s_seq);
650         if (IS_ERR(msg)) {
651                 err = PTR_ERR(msg);
652                 goto out;
653         }
654         ceph_con_send(&session->s_con, msg);
655
656 out:
657         return 0;
658 }
659
660 /*
661  * session caps
662  */
663
664 /*
665  * Free preallocated cap messages assigned to this session
666  */
667 static void cleanup_cap_releases(struct ceph_mds_session *session)
668 {
669         struct ceph_msg *msg;
670
671         spin_lock(&session->s_cap_lock);
672         while (!list_empty(&session->s_cap_releases)) {
673                 msg = list_first_entry(&session->s_cap_releases,
674                                        struct ceph_msg, list_head);
675                 list_del_init(&msg->list_head);
676                 ceph_msg_put(msg);
677         }
678         while (!list_empty(&session->s_cap_releases_done)) {
679                 msg = list_first_entry(&session->s_cap_releases_done,
680                                        struct ceph_msg, list_head);
681                 list_del_init(&msg->list_head);
682                 ceph_msg_put(msg);
683         }
684         spin_unlock(&session->s_cap_lock);
685 }
686
687 /*
688  * Helper to safely iterate over all caps associated with a session.
689  *
690  * caller must hold session s_mutex
691  */
692 static int iterate_session_caps(struct ceph_mds_session *session,
693                                  int (*cb)(struct inode *, struct ceph_cap *,
694                                             void *), void *arg)
695 {
696         struct ceph_cap *cap, *ncap;
697         struct inode *inode;
698         int ret;
699
700         dout("iterate_session_caps %p mds%d\n", session, session->s_mds);
701         spin_lock(&session->s_cap_lock);
702         list_for_each_entry_safe(cap, ncap, &session->s_caps, session_caps) {
703                 inode = igrab(&cap->ci->vfs_inode);
704                 if (!inode)
705                         continue;
706                 spin_unlock(&session->s_cap_lock);
707                 ret = cb(inode, cap, arg);
708                 iput(inode);
709                 if (ret < 0)
710                         return ret;
711                 spin_lock(&session->s_cap_lock);
712         }
713         spin_unlock(&session->s_cap_lock);
714
715         return 0;
716 }
717
718 static int remove_session_caps_cb(struct inode *inode, struct ceph_cap *cap,
719                                    void *arg)
720 {
721         struct ceph_inode_info *ci = ceph_inode(inode);
722         dout("removing cap %p, ci is %p, inode is %p\n",
723              cap, ci, &ci->vfs_inode);
724         ceph_remove_cap(cap);
725         return 0;
726 }
727
728 /*
729  * caller must hold session s_mutex
730  */
731 static void remove_session_caps(struct ceph_mds_session *session)
732 {
733         dout("remove_session_caps on %p\n", session);
734         iterate_session_caps(session, remove_session_caps_cb, NULL);
735         BUG_ON(session->s_nr_caps > 0);
736         cleanup_cap_releases(session);
737 }
738
739 /*
740  * wake up any threads waiting on this session's caps.  if the cap is
741  * old (didn't get renewed on the client reconnect), remove it now.
742  *
743  * caller must hold s_mutex.
744  */
745 static int wake_up_session_cb(struct inode *inode, struct ceph_cap *cap,
746                               void *arg)
747 {
748         struct ceph_inode_info *ci = ceph_inode(inode);
749
750         wake_up(&ci->i_cap_wq);
751         if (arg) {
752                 spin_lock(&inode->i_lock);
753                 ci->i_wanted_max_size = 0;
754                 ci->i_requested_max_size = 0;
755                 spin_unlock(&inode->i_lock);
756         }
757         return 0;
758 }
759
760 static void wake_up_session_caps(struct ceph_mds_session *session,
761                                  int reconnect)
762 {
763         dout("wake_up_session_caps %p mds%d\n", session, session->s_mds);
764         iterate_session_caps(session, wake_up_session_cb,
765                              (void *)(unsigned long)reconnect);
766 }
767
768 /*
769  * Send periodic message to MDS renewing all currently held caps.  The
770  * ack will reset the expiration for all caps from this session.
771  *
772  * caller holds s_mutex
773  */
774 static int send_renew_caps(struct ceph_mds_client *mdsc,
775                            struct ceph_mds_session *session)
776 {
777         struct ceph_msg *msg;
778         int state;
779
780         if (time_after_eq(jiffies, session->s_cap_ttl) &&
781             time_after_eq(session->s_cap_ttl, session->s_renew_requested))
782                 pr_info("mds%d caps stale\n", session->s_mds);
783
784         /* do not try to renew caps until a recovering mds has reconnected
785          * with its clients. */
786         state = ceph_mdsmap_get_state(mdsc->mdsmap, session->s_mds);
787         if (state < CEPH_MDS_STATE_RECONNECT) {
788                 dout("send_renew_caps ignoring mds%d (%s)\n",
789                      session->s_mds, ceph_mds_state_name(state));
790                 return 0;
791         }
792
793         dout("send_renew_caps to mds%d (%s)\n", session->s_mds,
794                 ceph_mds_state_name(state));
795         session->s_renew_requested = jiffies;
796         msg = create_session_msg(CEPH_SESSION_REQUEST_RENEWCAPS,
797                                  ++session->s_renew_seq);
798         if (IS_ERR(msg))
799                 return PTR_ERR(msg);
800         ceph_con_send(&session->s_con, msg);
801         return 0;
802 }
803
804 /*
805  * Note new cap ttl, and any transition from stale -> not stale (fresh?).
806  *
807  * Called under session->s_mutex
808  */
809 static void renewed_caps(struct ceph_mds_client *mdsc,
810                          struct ceph_mds_session *session, int is_renew)
811 {
812         int was_stale;
813         int wake = 0;
814
815         spin_lock(&session->s_cap_lock);
816         was_stale = is_renew && (session->s_cap_ttl == 0 ||
817                                  time_after_eq(jiffies, session->s_cap_ttl));
818
819         session->s_cap_ttl = session->s_renew_requested +
820                 mdsc->mdsmap->m_session_timeout*HZ;
821
822         if (was_stale) {
823                 if (time_before(jiffies, session->s_cap_ttl)) {
824                         pr_info("mds%d caps renewed\n", session->s_mds);
825                         wake = 1;
826                 } else {
827                         pr_info("mds%d caps still stale\n", session->s_mds);
828                 }
829         }
830         dout("renewed_caps mds%d ttl now %lu, was %s, now %s\n",
831              session->s_mds, session->s_cap_ttl, was_stale ? "stale" : "fresh",
832              time_before(jiffies, session->s_cap_ttl) ? "stale" : "fresh");
833         spin_unlock(&session->s_cap_lock);
834
835         if (wake)
836                 wake_up_session_caps(session, 0);
837 }
838
839 /*
840  * send a session close request
841  */
842 static int request_close_session(struct ceph_mds_client *mdsc,
843                                  struct ceph_mds_session *session)
844 {
845         struct ceph_msg *msg;
846         int err = 0;
847
848         dout("request_close_session mds%d state %s seq %lld\n",
849              session->s_mds, session_state_name(session->s_state),
850              session->s_seq);
851         msg = create_session_msg(CEPH_SESSION_REQUEST_CLOSE, session->s_seq);
852         if (IS_ERR(msg))
853                 err = PTR_ERR(msg);
854         else
855                 ceph_con_send(&session->s_con, msg);
856         return err;
857 }
858
859 /*
860  * Called with s_mutex held.
861  */
862 static int __close_session(struct ceph_mds_client *mdsc,
863                          struct ceph_mds_session *session)
864 {
865         if (session->s_state >= CEPH_MDS_SESSION_CLOSING)
866                 return 0;
867         session->s_state = CEPH_MDS_SESSION_CLOSING;
868         return request_close_session(mdsc, session);
869 }
870
871 /*
872  * Trim old(er) caps.
873  *
874  * Because we can't cache an inode without one or more caps, we do
875  * this indirectly: if a cap is unused, we prune its aliases, at which
876  * point the inode will hopefully get dropped to.
877  *
878  * Yes, this is a bit sloppy.  Our only real goal here is to respond to
879  * memory pressure from the MDS, though, so it needn't be perfect.
880  */
881 static int trim_caps_cb(struct inode *inode, struct ceph_cap *cap, void *arg)
882 {
883         struct ceph_mds_session *session = arg;
884         struct ceph_inode_info *ci = ceph_inode(inode);
885         int used, oissued, mine;
886
887         if (session->s_trim_caps <= 0)
888                 return -1;
889
890         spin_lock(&inode->i_lock);
891         mine = cap->issued | cap->implemented;
892         used = __ceph_caps_used(ci);
893         oissued = __ceph_caps_issued_other(ci, cap);
894
895         dout("trim_caps_cb %p cap %p mine %s oissued %s used %s\n",
896              inode, cap, ceph_cap_string(mine), ceph_cap_string(oissued),
897              ceph_cap_string(used));
898         if (ci->i_dirty_caps)
899                 goto out;   /* dirty caps */
900         if ((used & ~oissued) & mine)
901                 goto out;   /* we need these caps */
902
903         session->s_trim_caps--;
904         if (oissued) {
905                 /* we aren't the only cap.. just remove us */
906                 __ceph_remove_cap(cap, NULL);
907         } else {
908                 /* try to drop referring dentries */
909                 spin_unlock(&inode->i_lock);
910                 d_prune_aliases(inode);
911                 dout("trim_caps_cb %p cap %p  pruned, count now %d\n",
912                      inode, cap, atomic_read(&inode->i_count));
913                 return 0;
914         }
915
916 out:
917         spin_unlock(&inode->i_lock);
918         return 0;
919 }
920
921 /*
922  * Trim session cap count down to some max number.
923  */
924 static int trim_caps(struct ceph_mds_client *mdsc,
925                      struct ceph_mds_session *session,
926                      int max_caps)
927 {
928         int trim_caps = session->s_nr_caps - max_caps;
929
930         dout("trim_caps mds%d start: %d / %d, trim %d\n",
931              session->s_mds, session->s_nr_caps, max_caps, trim_caps);
932         if (trim_caps > 0) {
933                 session->s_trim_caps = trim_caps;
934                 iterate_session_caps(session, trim_caps_cb, session);
935                 dout("trim_caps mds%d done: %d / %d, trimmed %d\n",
936                      session->s_mds, session->s_nr_caps, max_caps,
937                         trim_caps - session->s_trim_caps);
938         }
939         return 0;
940 }
941
942 /*
943  * Allocate cap_release messages.  If there is a partially full message
944  * in the queue, try to allocate enough to cover it's remainder, so that
945  * we can send it immediately.
946  *
947  * Called under s_mutex.
948  */
949 static int add_cap_releases(struct ceph_mds_client *mdsc,
950                             struct ceph_mds_session *session,
951                             int extra)
952 {
953         struct ceph_msg *msg;
954         struct ceph_mds_cap_release *head;
955         int err = -ENOMEM;
956
957         if (extra < 0)
958                 extra = mdsc->client->mount_args->cap_release_safety;
959
960         spin_lock(&session->s_cap_lock);
961
962         if (!list_empty(&session->s_cap_releases)) {
963                 msg = list_first_entry(&session->s_cap_releases,
964                                        struct ceph_msg,
965                                  list_head);
966                 head = msg->front.iov_base;
967                 extra += CEPH_CAPS_PER_RELEASE - le32_to_cpu(head->num);
968         }
969
970         while (session->s_num_cap_releases < session->s_nr_caps + extra) {
971                 spin_unlock(&session->s_cap_lock);
972                 msg = ceph_msg_new(CEPH_MSG_CLIENT_CAPRELEASE, PAGE_CACHE_SIZE,
973                                    0, 0, NULL);
974                 if (!msg)
975                         goto out_unlocked;
976                 dout("add_cap_releases %p msg %p now %d\n", session, msg,
977                      (int)msg->front.iov_len);
978                 head = msg->front.iov_base;
979                 head->num = cpu_to_le32(0);
980                 msg->front.iov_len = sizeof(*head);
981                 spin_lock(&session->s_cap_lock);
982                 list_add(&msg->list_head, &session->s_cap_releases);
983                 session->s_num_cap_releases += CEPH_CAPS_PER_RELEASE;
984         }
985
986         if (!list_empty(&session->s_cap_releases)) {
987                 msg = list_first_entry(&session->s_cap_releases,
988                                        struct ceph_msg,
989                                        list_head);
990                 head = msg->front.iov_base;
991                 if (head->num) {
992                         dout(" queueing non-full %p (%d)\n", msg,
993                              le32_to_cpu(head->num));
994                         list_move_tail(&msg->list_head,
995                                       &session->s_cap_releases_done);
996                         session->s_num_cap_releases -=
997                                 CEPH_CAPS_PER_RELEASE - le32_to_cpu(head->num);
998                 }
999         }
1000         err = 0;
1001         spin_unlock(&session->s_cap_lock);
1002 out_unlocked:
1003         return err;
1004 }
1005
1006 /*
1007  * flush all dirty inode data to disk.
1008  *
1009  * returns true if we've flushed through want_flush_seq
1010  */
1011 static int check_cap_flush(struct ceph_mds_client *mdsc, u64 want_flush_seq)
1012 {
1013         int mds, ret = 1;
1014
1015         dout("check_cap_flush want %lld\n", want_flush_seq);
1016         mutex_lock(&mdsc->mutex);
1017         for (mds = 0; ret && mds < mdsc->max_sessions; mds++) {
1018                 struct ceph_mds_session *session = mdsc->sessions[mds];
1019
1020                 if (!session)
1021                         continue;
1022                 get_session(session);
1023                 mutex_unlock(&mdsc->mutex);
1024
1025                 mutex_lock(&session->s_mutex);
1026                 if (!list_empty(&session->s_cap_flushing)) {
1027                         struct ceph_inode_info *ci =
1028                                 list_entry(session->s_cap_flushing.next,
1029                                            struct ceph_inode_info,
1030                                            i_flushing_item);
1031                         struct inode *inode = &ci->vfs_inode;
1032
1033                         spin_lock(&inode->i_lock);
1034                         if (ci->i_cap_flush_seq <= want_flush_seq) {
1035                                 dout("check_cap_flush still flushing %p "
1036                                      "seq %lld <= %lld to mds%d\n", inode,
1037                                      ci->i_cap_flush_seq, want_flush_seq,
1038                                      session->s_mds);
1039                                 ret = 0;
1040                         }
1041                         spin_unlock(&inode->i_lock);
1042                 }
1043                 mutex_unlock(&session->s_mutex);
1044                 ceph_put_mds_session(session);
1045
1046                 if (!ret)
1047                         return ret;
1048                 mutex_lock(&mdsc->mutex);
1049         }
1050
1051         mutex_unlock(&mdsc->mutex);
1052         dout("check_cap_flush ok, flushed thru %lld\n", want_flush_seq);
1053         return ret;
1054 }
1055
1056 /*
1057  * called under s_mutex
1058  */
1059 static void send_cap_releases(struct ceph_mds_client *mdsc,
1060                        struct ceph_mds_session *session)
1061 {
1062         struct ceph_msg *msg;
1063
1064         dout("send_cap_releases mds%d\n", session->s_mds);
1065         while (1) {
1066                 spin_lock(&session->s_cap_lock);
1067                 if (list_empty(&session->s_cap_releases_done))
1068                         break;
1069                 msg = list_first_entry(&session->s_cap_releases_done,
1070                                  struct ceph_msg, list_head);
1071                 list_del_init(&msg->list_head);
1072                 spin_unlock(&session->s_cap_lock);
1073                 msg->hdr.front_len = cpu_to_le32(msg->front.iov_len);
1074                 dout("send_cap_releases mds%d %p\n", session->s_mds, msg);
1075                 ceph_con_send(&session->s_con, msg);
1076         }
1077         spin_unlock(&session->s_cap_lock);
1078 }
1079
1080 /*
1081  * requests
1082  */
1083
1084 /*
1085  * Create an mds request.
1086  */
1087 struct ceph_mds_request *
1088 ceph_mdsc_create_request(struct ceph_mds_client *mdsc, int op, int mode)
1089 {
1090         struct ceph_mds_request *req = kzalloc(sizeof(*req), GFP_NOFS);
1091
1092         if (!req)
1093                 return ERR_PTR(-ENOMEM);
1094
1095         req->r_started = jiffies;
1096         req->r_resend_mds = -1;
1097         INIT_LIST_HEAD(&req->r_unsafe_dir_item);
1098         req->r_fmode = -1;
1099         kref_init(&req->r_kref);
1100         INIT_LIST_HEAD(&req->r_wait);
1101         init_completion(&req->r_completion);
1102         init_completion(&req->r_safe_completion);
1103         INIT_LIST_HEAD(&req->r_unsafe_item);
1104
1105         req->r_op = op;
1106         req->r_direct_mode = mode;
1107         return req;
1108 }
1109
1110 /*
1111  * return oldest (lowest) tid in request tree, 0 if none.
1112  *
1113  * called under mdsc->mutex.
1114  */
1115 static u64 __get_oldest_tid(struct ceph_mds_client *mdsc)
1116 {
1117         struct ceph_mds_request *first;
1118         if (radix_tree_gang_lookup(&mdsc->request_tree,
1119                                    (void **)&first, 0, 1) <= 0)
1120                 return 0;
1121         return first->r_tid;
1122 }
1123
1124 /*
1125  * Build a dentry's path.  Allocate on heap; caller must kfree.  Based
1126  * on build_path_from_dentry in fs/cifs/dir.c.
1127  *
1128  * If @stop_on_nosnap, generate path relative to the first non-snapped
1129  * inode.
1130  *
1131  * Encode hidden .snap dirs as a double /, i.e.
1132  *   foo/.snap/bar -> foo//bar
1133  */
1134 char *ceph_mdsc_build_path(struct dentry *dentry, int *plen, u64 *base,
1135                            int stop_on_nosnap)
1136 {
1137         struct dentry *temp;
1138         char *path;
1139         int len, pos;
1140
1141         if (dentry == NULL)
1142                 return ERR_PTR(-EINVAL);
1143
1144 retry:
1145         len = 0;
1146         for (temp = dentry; !IS_ROOT(temp);) {
1147                 struct inode *inode = temp->d_inode;
1148                 if (inode && ceph_snap(inode) == CEPH_SNAPDIR)
1149                         len++;  /* slash only */
1150                 else if (stop_on_nosnap && inode &&
1151                          ceph_snap(inode) == CEPH_NOSNAP)
1152                         break;
1153                 else
1154                         len += 1 + temp->d_name.len;
1155                 temp = temp->d_parent;
1156                 if (temp == NULL) {
1157                         pr_err("build_path_dentry corrupt dentry %p\n", dentry);
1158                         return ERR_PTR(-EINVAL);
1159                 }
1160         }
1161         if (len)
1162                 len--;  /* no leading '/' */
1163
1164         path = kmalloc(len+1, GFP_NOFS);
1165         if (path == NULL)
1166                 return ERR_PTR(-ENOMEM);
1167         pos = len;
1168         path[pos] = 0;  /* trailing null */
1169         for (temp = dentry; !IS_ROOT(temp) && pos != 0; ) {
1170                 struct inode *inode = temp->d_inode;
1171
1172                 if (inode && ceph_snap(inode) == CEPH_SNAPDIR) {
1173                         dout("build_path_dentry path+%d: %p SNAPDIR\n",
1174                              pos, temp);
1175                 } else if (stop_on_nosnap && inode &&
1176                            ceph_snap(inode) == CEPH_NOSNAP) {
1177                         break;
1178                 } else {
1179                         pos -= temp->d_name.len;
1180                         if (pos < 0)
1181                                 break;
1182                         strncpy(path + pos, temp->d_name.name,
1183                                 temp->d_name.len);
1184                         dout("build_path_dentry path+%d: %p '%.*s'\n",
1185                              pos, temp, temp->d_name.len, path + pos);
1186                 }
1187                 if (pos)
1188                         path[--pos] = '/';
1189                 temp = temp->d_parent;
1190                 if (temp == NULL) {
1191                         pr_err("build_path_dentry corrupt dentry\n");
1192                         kfree(path);
1193                         return ERR_PTR(-EINVAL);
1194                 }
1195         }
1196         if (pos != 0) {
1197                 pr_err("build_path_dentry did not end path lookup where "
1198                        "expected, namelen is %d, pos is %d\n", len, pos);
1199                 /* presumably this is only possible if racing with a
1200                    rename of one of the parent directories (we can not
1201                    lock the dentries above us to prevent this, but
1202                    retrying should be harmless) */
1203                 kfree(path);
1204                 goto retry;
1205         }
1206
1207         *base = ceph_ino(temp->d_inode);
1208         *plen = len;
1209         dout("build_path_dentry on %p %d built %llx '%.*s'\n",
1210              dentry, atomic_read(&dentry->d_count), *base, len, path);
1211         return path;
1212 }
1213
1214 static int build_dentry_path(struct dentry *dentry,
1215                              const char **ppath, int *ppathlen, u64 *pino,
1216                              int *pfreepath)
1217 {
1218         char *path;
1219
1220         if (ceph_snap(dentry->d_parent->d_inode) == CEPH_NOSNAP) {
1221                 *pino = ceph_ino(dentry->d_parent->d_inode);
1222                 *ppath = dentry->d_name.name;
1223                 *ppathlen = dentry->d_name.len;
1224                 return 0;
1225         }
1226         path = ceph_mdsc_build_path(dentry, ppathlen, pino, 1);
1227         if (IS_ERR(path))
1228                 return PTR_ERR(path);
1229         *ppath = path;
1230         *pfreepath = 1;
1231         return 0;
1232 }
1233
1234 static int build_inode_path(struct inode *inode,
1235                             const char **ppath, int *ppathlen, u64 *pino,
1236                             int *pfreepath)
1237 {
1238         struct dentry *dentry;
1239         char *path;
1240
1241         if (ceph_snap(inode) == CEPH_NOSNAP) {
1242                 *pino = ceph_ino(inode);
1243                 *ppathlen = 0;
1244                 return 0;
1245         }
1246         dentry = d_find_alias(inode);
1247         path = ceph_mdsc_build_path(dentry, ppathlen, pino, 1);
1248         dput(dentry);
1249         if (IS_ERR(path))
1250                 return PTR_ERR(path);
1251         *ppath = path;
1252         *pfreepath = 1;
1253         return 0;
1254 }
1255
1256 /*
1257  * request arguments may be specified via an inode *, a dentry *, or
1258  * an explicit ino+path.
1259  */
1260 static int set_request_path_attr(struct inode *rinode, struct dentry *rdentry,
1261                                   const char *rpath, u64 rino,
1262                                   const char **ppath, int *pathlen,
1263                                   u64 *ino, int *freepath)
1264 {
1265         int r = 0;
1266
1267         if (rinode) {
1268                 r = build_inode_path(rinode, ppath, pathlen, ino, freepath);
1269                 dout(" inode %p %llx.%llx\n", rinode, ceph_ino(rinode),
1270                      ceph_snap(rinode));
1271         } else if (rdentry) {
1272                 r = build_dentry_path(rdentry, ppath, pathlen, ino, freepath);
1273                 dout(" dentry %p %llx/%.*s\n", rdentry, *ino, *pathlen,
1274                      *ppath);
1275         } else if (rpath) {
1276                 *ino = rino;
1277                 *ppath = rpath;
1278                 *pathlen = strlen(rpath);
1279                 dout(" path %.*s\n", *pathlen, rpath);
1280         }
1281
1282         return r;
1283 }
1284
1285 /*
1286  * called under mdsc->mutex
1287  */
1288 static struct ceph_msg *create_request_message(struct ceph_mds_client *mdsc,
1289                                                struct ceph_mds_request *req,
1290                                                int mds)
1291 {
1292         struct ceph_msg *msg;
1293         struct ceph_mds_request_head *head;
1294         const char *path1 = NULL;
1295         const char *path2 = NULL;
1296         u64 ino1 = 0, ino2 = 0;
1297         int pathlen1 = 0, pathlen2 = 0;
1298         int freepath1 = 0, freepath2 = 0;
1299         int len;
1300         u16 releases;
1301         void *p, *end;
1302         int ret;
1303
1304         ret = set_request_path_attr(req->r_inode, req->r_dentry,
1305                               req->r_path1, req->r_ino1.ino,
1306                               &path1, &pathlen1, &ino1, &freepath1);
1307         if (ret < 0) {
1308                 msg = ERR_PTR(ret);
1309                 goto out;
1310         }
1311
1312         ret = set_request_path_attr(NULL, req->r_old_dentry,
1313                               req->r_path2, req->r_ino2.ino,
1314                               &path2, &pathlen2, &ino2, &freepath2);
1315         if (ret < 0) {
1316                 msg = ERR_PTR(ret);
1317                 goto out_free1;
1318         }
1319
1320         len = sizeof(*head) +
1321                 pathlen1 + pathlen2 + 2*(sizeof(u32) + sizeof(u64));
1322
1323         /* calculate (max) length for cap releases */
1324         len += sizeof(struct ceph_mds_request_release) *
1325                 (!!req->r_inode_drop + !!req->r_dentry_drop +
1326                  !!req->r_old_inode_drop + !!req->r_old_dentry_drop);
1327         if (req->r_dentry_drop)
1328                 len += req->r_dentry->d_name.len;
1329         if (req->r_old_dentry_drop)
1330                 len += req->r_old_dentry->d_name.len;
1331
1332         msg = ceph_msg_new(CEPH_MSG_CLIENT_REQUEST, len, 0, 0, NULL);
1333         if (IS_ERR(msg))
1334                 goto out_free2;
1335
1336         head = msg->front.iov_base;
1337         p = msg->front.iov_base + sizeof(*head);
1338         end = msg->front.iov_base + msg->front.iov_len;
1339
1340         head->mdsmap_epoch = cpu_to_le32(mdsc->mdsmap->m_epoch);
1341         head->op = cpu_to_le32(req->r_op);
1342         head->caller_uid = cpu_to_le32(current_fsuid());
1343         head->caller_gid = cpu_to_le32(current_fsgid());
1344         head->args = req->r_args;
1345
1346         ceph_encode_filepath(&p, end, ino1, path1);
1347         ceph_encode_filepath(&p, end, ino2, path2);
1348
1349         /* cap releases */
1350         releases = 0;
1351         if (req->r_inode_drop)
1352                 releases += ceph_encode_inode_release(&p,
1353                       req->r_inode ? req->r_inode : req->r_dentry->d_inode,
1354                       mds, req->r_inode_drop, req->r_inode_unless, 0);
1355         if (req->r_dentry_drop)
1356                 releases += ceph_encode_dentry_release(&p, req->r_dentry,
1357                        mds, req->r_dentry_drop, req->r_dentry_unless);
1358         if (req->r_old_dentry_drop)
1359                 releases += ceph_encode_dentry_release(&p, req->r_old_dentry,
1360                        mds, req->r_old_dentry_drop, req->r_old_dentry_unless);
1361         if (req->r_old_inode_drop)
1362                 releases += ceph_encode_inode_release(&p,
1363                       req->r_old_dentry->d_inode,
1364                       mds, req->r_old_inode_drop, req->r_old_inode_unless, 0);
1365         head->num_releases = cpu_to_le16(releases);
1366
1367         BUG_ON(p > end);
1368         msg->front.iov_len = p - msg->front.iov_base;
1369         msg->hdr.front_len = cpu_to_le32(msg->front.iov_len);
1370
1371         msg->pages = req->r_pages;
1372         msg->nr_pages = req->r_num_pages;
1373         msg->hdr.data_len = cpu_to_le32(req->r_data_len);
1374         msg->hdr.data_off = cpu_to_le16(0);
1375
1376 out_free2:
1377         if (freepath2)
1378                 kfree((char *)path2);
1379 out_free1:
1380         if (freepath1)
1381                 kfree((char *)path1);
1382 out:
1383         return msg;
1384 }
1385
1386 /*
1387  * called under mdsc->mutex if error, under no mutex if
1388  * success.
1389  */
1390 static void complete_request(struct ceph_mds_client *mdsc,
1391                              struct ceph_mds_request *req)
1392 {
1393         if (req->r_callback)
1394                 req->r_callback(mdsc, req);
1395         else
1396                 complete(&req->r_completion);
1397 }
1398
1399 /*
1400  * called under mdsc->mutex
1401  */
1402 static int __prepare_send_request(struct ceph_mds_client *mdsc,
1403                                   struct ceph_mds_request *req,
1404                                   int mds)
1405 {
1406         struct ceph_mds_request_head *rhead;
1407         struct ceph_msg *msg;
1408         int flags = 0;
1409
1410         req->r_mds = mds;
1411         req->r_attempts++;
1412         dout("prepare_send_request %p tid %lld %s (attempt %d)\n", req,
1413              req->r_tid, ceph_mds_op_name(req->r_op), req->r_attempts);
1414
1415         if (req->r_request) {
1416                 ceph_msg_put(req->r_request);
1417                 req->r_request = NULL;
1418         }
1419         msg = create_request_message(mdsc, req, mds);
1420         if (IS_ERR(msg)) {
1421                 req->r_reply = ERR_PTR(PTR_ERR(msg));
1422                 complete_request(mdsc, req);
1423                 return -PTR_ERR(msg);
1424         }
1425         req->r_request = msg;
1426
1427         rhead = msg->front.iov_base;
1428         rhead->tid = cpu_to_le64(req->r_tid);
1429         rhead->oldest_client_tid = cpu_to_le64(__get_oldest_tid(mdsc));
1430         if (req->r_got_unsafe)
1431                 flags |= CEPH_MDS_FLAG_REPLAY;
1432         if (req->r_locked_dir)
1433                 flags |= CEPH_MDS_FLAG_WANT_DENTRY;
1434         rhead->flags = cpu_to_le32(flags);
1435         rhead->num_fwd = req->r_num_fwd;
1436         rhead->num_retry = req->r_attempts - 1;
1437
1438         dout(" r_locked_dir = %p\n", req->r_locked_dir);
1439
1440         if (req->r_target_inode && req->r_got_unsafe)
1441                 rhead->ino = cpu_to_le64(ceph_ino(req->r_target_inode));
1442         else
1443                 rhead->ino = 0;
1444         return 0;
1445 }
1446
1447 /*
1448  * send request, or put it on the appropriate wait list.
1449  */
1450 static int __do_request(struct ceph_mds_client *mdsc,
1451                         struct ceph_mds_request *req)
1452 {
1453         struct ceph_mds_session *session = NULL;
1454         int mds = -1;
1455         int err = -EAGAIN;
1456
1457         if (req->r_reply)
1458                 goto out;
1459
1460         if (req->r_timeout &&
1461             time_after_eq(jiffies, req->r_started + req->r_timeout)) {
1462                 dout("do_request timed out\n");
1463                 err = -EIO;
1464                 goto finish;
1465         }
1466
1467         mds = __choose_mds(mdsc, req);
1468         if (mds < 0 ||
1469             ceph_mdsmap_get_state(mdsc->mdsmap, mds) < CEPH_MDS_STATE_ACTIVE) {
1470                 dout("do_request no mds or not active, waiting for map\n");
1471                 list_add(&req->r_wait, &mdsc->waiting_for_map);
1472                 goto out;
1473         }
1474
1475         /* get, open session */
1476         session = __ceph_lookup_mds_session(mdsc, mds);
1477         if (!session)
1478                 session = register_session(mdsc, mds);
1479         dout("do_request mds%d session %p state %s\n", mds, session,
1480              session_state_name(session->s_state));
1481         if (session->s_state != CEPH_MDS_SESSION_OPEN &&
1482             session->s_state != CEPH_MDS_SESSION_HUNG) {
1483                 if (session->s_state == CEPH_MDS_SESSION_NEW ||
1484                     session->s_state == CEPH_MDS_SESSION_CLOSING)
1485                         __open_session(mdsc, session);
1486                 list_add(&req->r_wait, &session->s_waiting);
1487                 goto out_session;
1488         }
1489
1490         /* send request */
1491         req->r_session = get_session(session);
1492         req->r_resend_mds = -1;   /* forget any previous mds hint */
1493
1494         if (req->r_request_started == 0)   /* note request start time */
1495                 req->r_request_started = jiffies;
1496
1497         err = __prepare_send_request(mdsc, req, mds);
1498         if (!err) {
1499                 ceph_msg_get(req->r_request);
1500                 ceph_con_send(&session->s_con, req->r_request);
1501         }
1502
1503 out_session:
1504         ceph_put_mds_session(session);
1505 out:
1506         return err;
1507
1508 finish:
1509         req->r_reply = ERR_PTR(err);
1510         complete_request(mdsc, req);
1511         goto out;
1512 }
1513
1514 /*
1515  * called under mdsc->mutex
1516  */
1517 static void __wake_requests(struct ceph_mds_client *mdsc,
1518                             struct list_head *head)
1519 {
1520         struct ceph_mds_request *req, *nreq;
1521
1522         list_for_each_entry_safe(req, nreq, head, r_wait) {
1523                 list_del_init(&req->r_wait);
1524                 __do_request(mdsc, req);
1525         }
1526 }
1527
1528 /*
1529  * Wake up threads with requests pending for @mds, so that they can
1530  * resubmit their requests to a possibly different mds.  If @all is set,
1531  * wake up if their requests has been forwarded to @mds, too.
1532  */
1533 static void kick_requests(struct ceph_mds_client *mdsc, int mds, int all)
1534 {
1535         struct ceph_mds_request *reqs[10];
1536         u64 nexttid = 0;
1537         int i, got;
1538
1539         dout("kick_requests mds%d\n", mds);
1540         while (nexttid <= mdsc->last_tid) {
1541                 got = radix_tree_gang_lookup(&mdsc->request_tree,
1542                                              (void **)&reqs, nexttid, 10);
1543                 if (got == 0)
1544                         break;
1545                 nexttid = reqs[got-1]->r_tid + 1;
1546                 for (i = 0; i < got; i++) {
1547                         if (reqs[i]->r_got_unsafe)
1548                                 continue;
1549                         if (reqs[i]->r_session &&
1550                             reqs[i]->r_session->s_mds == mds) {
1551                                 dout(" kicking tid %llu\n", reqs[i]->r_tid);
1552                                 put_request_session(reqs[i]);
1553                                 __do_request(mdsc, reqs[i]);
1554                         }
1555                 }
1556         }
1557 }
1558
1559 void ceph_mdsc_submit_request(struct ceph_mds_client *mdsc,
1560                               struct ceph_mds_request *req)
1561 {
1562         dout("submit_request on %p\n", req);
1563         mutex_lock(&mdsc->mutex);
1564         __register_request(mdsc, req, NULL);
1565         __do_request(mdsc, req);
1566         mutex_unlock(&mdsc->mutex);
1567 }
1568
1569 /*
1570  * Synchrously perform an mds request.  Take care of all of the
1571  * session setup, forwarding, retry details.
1572  */
1573 int ceph_mdsc_do_request(struct ceph_mds_client *mdsc,
1574                          struct inode *dir,
1575                          struct ceph_mds_request *req)
1576 {
1577         int err;
1578
1579         dout("do_request on %p\n", req);
1580
1581         /* take CAP_PIN refs for r_inode, r_locked_dir, r_old_dentry */
1582         if (req->r_inode)
1583                 ceph_get_cap_refs(ceph_inode(req->r_inode), CEPH_CAP_PIN);
1584         if (req->r_locked_dir)
1585                 ceph_get_cap_refs(ceph_inode(req->r_locked_dir), CEPH_CAP_PIN);
1586         if (req->r_old_dentry)
1587                 ceph_get_cap_refs(
1588                         ceph_inode(req->r_old_dentry->d_parent->d_inode),
1589                         CEPH_CAP_PIN);
1590
1591         /* issue */
1592         mutex_lock(&mdsc->mutex);
1593         __register_request(mdsc, req, dir);
1594         __do_request(mdsc, req);
1595
1596         /* wait */
1597         if (!req->r_reply) {
1598                 mutex_unlock(&mdsc->mutex);
1599                 if (req->r_timeout) {
1600                         err = wait_for_completion_timeout(&req->r_completion,
1601                                                           req->r_timeout);
1602                         if (err > 0)
1603                                 err = 0;
1604                         else if (err == 0)
1605                                 req->r_reply = ERR_PTR(-EIO);
1606                 } else {
1607                         wait_for_completion(&req->r_completion);
1608                 }
1609                 mutex_lock(&mdsc->mutex);
1610         }
1611
1612         if (IS_ERR(req->r_reply)) {
1613                 err = PTR_ERR(req->r_reply);
1614                 req->r_reply = NULL;
1615
1616                 /* clean up */
1617                 __unregister_request(mdsc, req);
1618                 if (!list_empty(&req->r_unsafe_item))
1619                         list_del_init(&req->r_unsafe_item);
1620                 complete(&req->r_safe_completion);
1621         } else if (req->r_err) {
1622                 err = req->r_err;
1623         } else {
1624                 err = le32_to_cpu(req->r_reply_info.head->result);
1625         }
1626         mutex_unlock(&mdsc->mutex);
1627
1628         dout("do_request %p done, result %d\n", req, err);
1629         return err;
1630 }
1631
1632 /*
1633  * Handle mds reply.
1634  *
1635  * We take the session mutex and parse and process the reply immediately.
1636  * This preserves the logical ordering of replies, capabilities, etc., sent
1637  * by the MDS as they are applied to our local cache.
1638  */
1639 static void handle_reply(struct ceph_mds_session *session, struct ceph_msg *msg)
1640 {
1641         struct ceph_mds_client *mdsc = session->s_mdsc;
1642         struct ceph_mds_request *req;
1643         struct ceph_mds_reply_head *head = msg->front.iov_base;
1644         struct ceph_mds_reply_info_parsed *rinfo;  /* parsed reply info */
1645         u64 tid;
1646         int err, result;
1647         int mds;
1648
1649         if (msg->hdr.src.name.type != CEPH_ENTITY_TYPE_MDS)
1650                 return;
1651         if (msg->front.iov_len < sizeof(*head)) {
1652                 pr_err("mdsc_handle_reply got corrupt (short) reply\n");
1653                 return;
1654         }
1655
1656         /* get request, session */
1657         tid = le64_to_cpu(head->tid);
1658         mutex_lock(&mdsc->mutex);
1659         req = __lookup_request(mdsc, tid);
1660         if (!req) {
1661                 dout("handle_reply on unknown tid %llu\n", tid);
1662                 mutex_unlock(&mdsc->mutex);
1663                 return;
1664         }
1665         dout("handle_reply %p\n", req);
1666         mds = le64_to_cpu(msg->hdr.src.name.num);
1667
1668         /* correct session? */
1669         if (!req->r_session && req->r_session != session) {
1670                 pr_err("mdsc_handle_reply got %llu on session mds%d"
1671                        " not mds%d\n", tid, session->s_mds,
1672                        req->r_session ? req->r_session->s_mds : -1);
1673                 mutex_unlock(&mdsc->mutex);
1674                 goto out;
1675         }
1676
1677         /* dup? */
1678         if ((req->r_got_unsafe && !head->safe) ||
1679             (req->r_got_safe && head->safe)) {
1680                 pr_warning("got a dup %s reply on %llu from mds%d\n",
1681                            head->safe ? "safe" : "unsafe", tid, mds);
1682                 mutex_unlock(&mdsc->mutex);
1683                 goto out;
1684         }
1685
1686         result = le32_to_cpu(head->result);
1687
1688         /*
1689          * Tolerate 2 consecutive ESTALEs from the same mds.
1690          * FIXME: we should be looking at the cap migrate_seq.
1691          */
1692         if (result == -ESTALE) {
1693                 req->r_direct_mode = USE_AUTH_MDS;
1694                 req->r_num_stale++;
1695                 if (req->r_num_stale <= 2) {
1696                         __do_request(mdsc, req);
1697                         mutex_unlock(&mdsc->mutex);
1698                         goto out;
1699                 }
1700         } else {
1701                 req->r_num_stale = 0;
1702         }
1703
1704         if (head->safe) {
1705                 req->r_got_safe = true;
1706                 __unregister_request(mdsc, req);
1707                 complete(&req->r_safe_completion);
1708
1709                 if (req->r_got_unsafe) {
1710                         /*
1711                          * We already handled the unsafe response, now do the
1712                          * cleanup.  No need to examine the response; the MDS
1713                          * doesn't include any result info in the safe
1714                          * response.  And even if it did, there is nothing
1715                          * useful we could do with a revised return value.
1716                          */
1717                         dout("got safe reply %llu, mds%d\n", tid, mds);
1718                         list_del_init(&req->r_unsafe_item);
1719
1720                         /* last unsafe request during umount? */
1721                         if (mdsc->stopping && !__get_oldest_tid(mdsc))
1722                                 complete(&mdsc->safe_umount_waiters);
1723                         mutex_unlock(&mdsc->mutex);
1724                         goto out;
1725                 }
1726         }
1727
1728         BUG_ON(req->r_reply);
1729
1730         if (!head->safe) {
1731                 req->r_got_unsafe = true;
1732                 list_add_tail(&req->r_unsafe_item, &req->r_session->s_unsafe);
1733         }
1734
1735         dout("handle_reply tid %lld result %d\n", tid, result);
1736         rinfo = &req->r_reply_info;
1737         err = parse_reply_info(msg, rinfo);
1738         mutex_unlock(&mdsc->mutex);
1739
1740         mutex_lock(&session->s_mutex);
1741         if (err < 0) {
1742                 pr_err("mdsc_handle_reply got corrupt reply mds%d\n", mds);
1743                 goto out_err;
1744         }
1745
1746         /* snap trace */
1747         if (rinfo->snapblob_len) {
1748                 down_write(&mdsc->snap_rwsem);
1749                 ceph_update_snap_trace(mdsc, rinfo->snapblob,
1750                                rinfo->snapblob + rinfo->snapblob_len,
1751                                le32_to_cpu(head->op) == CEPH_MDS_OP_RMSNAP);
1752                 downgrade_write(&mdsc->snap_rwsem);
1753         } else {
1754                 down_read(&mdsc->snap_rwsem);
1755         }
1756
1757         /* insert trace into our cache */
1758         err = ceph_fill_trace(mdsc->client->sb, req, req->r_session);
1759         if (err == 0) {
1760                 if (result == 0 && rinfo->dir_nr)
1761                         ceph_readdir_prepopulate(req, req->r_session);
1762                 ceph_unreserve_caps(&req->r_caps_reservation);
1763         }
1764
1765         up_read(&mdsc->snap_rwsem);
1766 out_err:
1767         if (err) {
1768                 req->r_err = err;
1769         } else {
1770                 req->r_reply = msg;
1771                 ceph_msg_get(msg);
1772         }
1773
1774         add_cap_releases(mdsc, req->r_session, -1);
1775         mutex_unlock(&session->s_mutex);
1776
1777         /* kick calling process */
1778         complete_request(mdsc, req);
1779 out:
1780         ceph_mdsc_put_request(req);
1781         return;
1782 }
1783
1784
1785
1786 /*
1787  * handle mds notification that our request has been forwarded.
1788  */
1789 static void handle_forward(struct ceph_mds_client *mdsc, struct ceph_msg *msg)
1790 {
1791         struct ceph_mds_request *req;
1792         u64 tid;
1793         u32 next_mds;
1794         u32 fwd_seq;
1795         u8 must_resend;
1796         int err = -EINVAL;
1797         void *p = msg->front.iov_base;
1798         void *end = p + msg->front.iov_len;
1799         int from_mds, state;
1800
1801         if (msg->hdr.src.name.type != CEPH_ENTITY_TYPE_MDS)
1802                 goto bad;
1803         from_mds = le64_to_cpu(msg->hdr.src.name.num);
1804
1805         ceph_decode_need(&p, end, sizeof(u64)+2*sizeof(u32), bad);
1806         tid = ceph_decode_64(&p);
1807         next_mds = ceph_decode_32(&p);
1808         fwd_seq = ceph_decode_32(&p);
1809         must_resend = ceph_decode_8(&p);
1810
1811         WARN_ON(must_resend);  /* shouldn't happen. */
1812
1813         mutex_lock(&mdsc->mutex);
1814         req = __lookup_request(mdsc, tid);
1815         if (!req) {
1816                 dout("forward %llu dne\n", tid);
1817                 goto out;  /* dup reply? */
1818         }
1819
1820         state = mdsc->sessions[next_mds]->s_state;
1821         if (fwd_seq <= req->r_num_fwd) {
1822                 dout("forward %llu to mds%d - old seq %d <= %d\n",
1823                      tid, next_mds, req->r_num_fwd, fwd_seq);
1824         } else {
1825                 /* resend. forward race not possible; mds would drop */
1826                 dout("forward %llu to mds%d (we resend)\n", tid, next_mds);
1827                 req->r_num_fwd = fwd_seq;
1828                 req->r_resend_mds = next_mds;
1829                 put_request_session(req);
1830                 __do_request(mdsc, req);
1831         }
1832         ceph_mdsc_put_request(req);
1833 out:
1834         mutex_unlock(&mdsc->mutex);
1835         return;
1836
1837 bad:
1838         pr_err("mdsc_handle_forward decode error err=%d\n", err);
1839 }
1840
1841 /*
1842  * handle a mds session control message
1843  */
1844 static void handle_session(struct ceph_mds_session *session,
1845                            struct ceph_msg *msg)
1846 {
1847         struct ceph_mds_client *mdsc = session->s_mdsc;
1848         u32 op;
1849         u64 seq;
1850         int mds;
1851         struct ceph_mds_session_head *h = msg->front.iov_base;
1852         int wake = 0;
1853
1854         if (msg->hdr.src.name.type != CEPH_ENTITY_TYPE_MDS)
1855                 return;
1856         mds = le64_to_cpu(msg->hdr.src.name.num);
1857
1858         /* decode */
1859         if (msg->front.iov_len != sizeof(*h))
1860                 goto bad;
1861         op = le32_to_cpu(h->op);
1862         seq = le64_to_cpu(h->seq);
1863
1864         mutex_lock(&mdsc->mutex);
1865         /* FIXME: this ttl calculation is generous */
1866         session->s_ttl = jiffies + HZ*mdsc->mdsmap->m_session_autoclose;
1867         mutex_unlock(&mdsc->mutex);
1868
1869         mutex_lock(&session->s_mutex);
1870
1871         dout("handle_session mds%d %s %p state %s seq %llu\n",
1872              mds, ceph_session_op_name(op), session,
1873              session_state_name(session->s_state), seq);
1874
1875         if (session->s_state == CEPH_MDS_SESSION_HUNG) {
1876                 session->s_state = CEPH_MDS_SESSION_OPEN;
1877                 pr_info("mds%d came back\n", session->s_mds);
1878         }
1879
1880         switch (op) {
1881         case CEPH_SESSION_OPEN:
1882                 session->s_state = CEPH_MDS_SESSION_OPEN;
1883                 renewed_caps(mdsc, session, 0);
1884                 wake = 1;
1885                 if (mdsc->stopping)
1886                         __close_session(mdsc, session);
1887                 break;
1888
1889         case CEPH_SESSION_RENEWCAPS:
1890                 if (session->s_renew_seq == seq)
1891                         renewed_caps(mdsc, session, 1);
1892                 break;
1893
1894         case CEPH_SESSION_CLOSE:
1895                 unregister_session(mdsc, session);
1896                 remove_session_caps(session);
1897                 wake = 1; /* for good measure */
1898                 complete(&mdsc->session_close_waiters);
1899                 kick_requests(mdsc, mds, 0);      /* cur only */
1900                 break;
1901
1902         case CEPH_SESSION_STALE:
1903                 pr_info("mds%d caps went stale, renewing\n",
1904                         session->s_mds);
1905                 spin_lock(&session->s_cap_lock);
1906                 session->s_cap_gen++;
1907                 session->s_cap_ttl = 0;
1908                 spin_unlock(&session->s_cap_lock);
1909                 send_renew_caps(mdsc, session);
1910                 break;
1911
1912         case CEPH_SESSION_RECALL_STATE:
1913                 trim_caps(mdsc, session, le32_to_cpu(h->max_caps));
1914                 break;
1915
1916         default:
1917                 pr_err("mdsc_handle_session bad op %d mds%d\n", op, mds);
1918                 WARN_ON(1);
1919         }
1920
1921         mutex_unlock(&session->s_mutex);
1922         if (wake) {
1923                 mutex_lock(&mdsc->mutex);
1924                 __wake_requests(mdsc, &session->s_waiting);
1925                 mutex_unlock(&mdsc->mutex);
1926         }
1927         return;
1928
1929 bad:
1930         pr_err("mdsc_handle_session corrupt message mds%d len %d\n", mds,
1931                (int)msg->front.iov_len);
1932         return;
1933 }
1934
1935
1936 /*
1937  * called under session->mutex.
1938  */
1939 static void replay_unsafe_requests(struct ceph_mds_client *mdsc,
1940                                    struct ceph_mds_session *session)
1941 {
1942         struct ceph_mds_request *req, *nreq;
1943         int err;
1944
1945         dout("replay_unsafe_requests mds%d\n", session->s_mds);
1946
1947         mutex_lock(&mdsc->mutex);
1948         list_for_each_entry_safe(req, nreq, &session->s_unsafe, r_unsafe_item) {
1949                 err = __prepare_send_request(mdsc, req, session->s_mds);
1950                 if (!err) {
1951                         ceph_msg_get(req->r_request);
1952                         ceph_con_send(&session->s_con, req->r_request);
1953                 }
1954         }
1955         mutex_unlock(&mdsc->mutex);
1956 }
1957
1958 /*
1959  * Encode information about a cap for a reconnect with the MDS.
1960  */
1961 struct encode_caps_data {
1962         void **pp;
1963         void *end;
1964         int *num_caps;
1965 };
1966
1967 static int encode_caps_cb(struct inode *inode, struct ceph_cap *cap,
1968                           void *arg)
1969 {
1970         struct ceph_mds_cap_reconnect *rec;
1971         struct ceph_inode_info *ci;
1972         struct encode_caps_data *data = (struct encode_caps_data *)arg;
1973         void *p = *(data->pp);
1974         void *end = data->end;
1975         char *path;
1976         int pathlen, err;
1977         u64 pathbase;
1978         struct dentry *dentry;
1979
1980         ci = cap->ci;
1981
1982         dout(" adding %p ino %llx.%llx cap %p %lld %s\n",
1983              inode, ceph_vinop(inode), cap, cap->cap_id,
1984              ceph_cap_string(cap->issued));
1985         ceph_decode_need(&p, end, sizeof(u64), needmore);
1986         ceph_encode_64(&p, ceph_ino(inode));
1987
1988         dentry = d_find_alias(inode);
1989         if (dentry) {
1990                 path = ceph_mdsc_build_path(dentry, &pathlen, &pathbase, 0);
1991                 if (IS_ERR(path)) {
1992                         err = PTR_ERR(path);
1993                         BUG_ON(err);
1994                 }
1995         } else {
1996                 path = NULL;
1997                 pathlen = 0;
1998         }
1999         ceph_decode_need(&p, end, pathlen+4, needmore);
2000         ceph_encode_string(&p, end, path, pathlen);
2001
2002         ceph_decode_need(&p, end, sizeof(*rec), needmore);
2003         rec = p;
2004         p += sizeof(*rec);
2005         BUG_ON(p > end);
2006         spin_lock(&inode->i_lock);
2007         cap->seq = 0;        /* reset cap seq */
2008         cap->issue_seq = 0;  /* and issue_seq */
2009         rec->cap_id = cpu_to_le64(cap->cap_id);
2010         rec->pathbase = cpu_to_le64(pathbase);
2011         rec->wanted = cpu_to_le32(__ceph_caps_wanted(ci));
2012         rec->issued = cpu_to_le32(cap->issued);
2013         rec->size = cpu_to_le64(inode->i_size);
2014         ceph_encode_timespec(&rec->mtime, &inode->i_mtime);
2015         ceph_encode_timespec(&rec->atime, &inode->i_atime);
2016         rec->snaprealm = cpu_to_le64(ci->i_snap_realm->ino);
2017         spin_unlock(&inode->i_lock);
2018
2019         kfree(path);
2020         dput(dentry);
2021         (*data->num_caps)++;
2022         *(data->pp) = p;
2023         return 0;
2024 needmore:
2025         return -ENOSPC;
2026 }
2027
2028
2029 /*
2030  * If an MDS fails and recovers, clients need to reconnect in order to
2031  * reestablish shared state.  This includes all caps issued through
2032  * this session _and_ the snap_realm hierarchy.  Because it's not
2033  * clear which snap realms the mds cares about, we send everything we
2034  * know about.. that ensures we'll then get any new info the
2035  * recovering MDS might have.
2036  *
2037  * This is a relatively heavyweight operation, but it's rare.
2038  *
2039  * called with mdsc->mutex held.
2040  */
2041 static void send_mds_reconnect(struct ceph_mds_client *mdsc, int mds)
2042 {
2043         struct ceph_mds_session *session;
2044         struct ceph_msg *reply;
2045         int newlen, len = 4 + 1;
2046         void *p, *end;
2047         int err;
2048         int num_caps, num_realms = 0;
2049         int got;
2050         u64 next_snap_ino = 0;
2051         __le32 *pnum_caps, *pnum_realms;
2052         struct encode_caps_data iter_args;
2053
2054         pr_info("reconnect to recovering mds%d\n", mds);
2055
2056         /* find session */
2057         session = __ceph_lookup_mds_session(mdsc, mds);
2058         mutex_unlock(&mdsc->mutex);    /* drop lock for duration */
2059
2060         if (session) {
2061                 mutex_lock(&session->s_mutex);
2062
2063                 session->s_state = CEPH_MDS_SESSION_RECONNECTING;
2064                 session->s_seq = 0;
2065
2066                 ceph_con_open(&session->s_con,
2067                               ceph_mdsmap_get_addr(mdsc->mdsmap, mds));
2068
2069                 /* replay unsafe requests */
2070                 replay_unsafe_requests(mdsc, session);
2071
2072                 /* estimate needed space */
2073                 len += session->s_nr_caps *
2074                         (100+sizeof(struct ceph_mds_cap_reconnect));
2075                 pr_info("estimating i need %d bytes for %d caps\n",
2076                      len, session->s_nr_caps);
2077         } else {
2078                 dout("no session for mds%d, will send short reconnect\n",
2079                      mds);
2080         }
2081
2082         down_read(&mdsc->snap_rwsem);
2083
2084 retry:
2085         /* build reply */
2086         reply = ceph_msg_new(CEPH_MSG_CLIENT_RECONNECT, len, 0, 0, NULL);
2087         if (IS_ERR(reply)) {
2088                 err = PTR_ERR(reply);
2089                 pr_err("send_mds_reconnect ENOMEM on %d for mds%d\n",
2090                        len, mds);
2091                 goto out;
2092         }
2093         p = reply->front.iov_base;
2094         end = p + len;
2095
2096         if (!session) {
2097                 ceph_encode_8(&p, 1); /* session was closed */
2098                 ceph_encode_32(&p, 0);
2099                 goto send;
2100         }
2101         dout("session %p state %s\n", session,
2102              session_state_name(session->s_state));
2103
2104         /* traverse this session's caps */
2105         ceph_encode_8(&p, 0);
2106         pnum_caps = p;
2107         ceph_encode_32(&p, session->s_nr_caps);
2108         num_caps = 0;
2109
2110         iter_args.pp = &p;
2111         iter_args.end = end;
2112         iter_args.num_caps = &num_caps;
2113         err = iterate_session_caps(session, encode_caps_cb, &iter_args);
2114         if (err == -ENOSPC)
2115                 goto needmore;
2116         if (err < 0)
2117                 goto out;
2118         *pnum_caps = cpu_to_le32(num_caps);
2119
2120         /*
2121          * snaprealms.  we provide mds with the ino, seq (version), and
2122          * parent for all of our realms.  If the mds has any newer info,
2123          * it will tell us.
2124          */
2125         next_snap_ino = 0;
2126         /* save some space for the snaprealm count */
2127         pnum_realms = p;
2128         ceph_decode_need(&p, end, sizeof(*pnum_realms), needmore);
2129         p += sizeof(*pnum_realms);
2130         num_realms = 0;
2131         while (1) {
2132                 struct ceph_snap_realm *realm;
2133                 struct ceph_mds_snaprealm_reconnect *sr_rec;
2134                 got = radix_tree_gang_lookup(&mdsc->snap_realms,
2135                                              (void **)&realm, next_snap_ino, 1);
2136                 if (!got)
2137                         break;
2138
2139                 dout(" adding snap realm %llx seq %lld parent %llx\n",
2140                      realm->ino, realm->seq, realm->parent_ino);
2141                 ceph_decode_need(&p, end, sizeof(*sr_rec), needmore);
2142                 sr_rec = p;
2143                 sr_rec->ino = cpu_to_le64(realm->ino);
2144                 sr_rec->seq = cpu_to_le64(realm->seq);
2145                 sr_rec->parent = cpu_to_le64(realm->parent_ino);
2146                 p += sizeof(*sr_rec);
2147                 num_realms++;
2148                 next_snap_ino = realm->ino + 1;
2149         }
2150         *pnum_realms = cpu_to_le32(num_realms);
2151
2152 send:
2153         reply->front.iov_len = p - reply->front.iov_base;
2154         reply->hdr.front_len = cpu_to_le32(reply->front.iov_len);
2155         dout("final len was %u (guessed %d)\n",
2156              (unsigned)reply->front.iov_len, len);
2157         ceph_con_send(&session->s_con, reply);
2158
2159         if (session) {
2160                 session->s_state = CEPH_MDS_SESSION_OPEN;
2161                 __wake_requests(mdsc, &session->s_waiting);
2162         }
2163
2164 out:
2165         up_read(&mdsc->snap_rwsem);
2166         if (session) {
2167                 mutex_unlock(&session->s_mutex);
2168                 ceph_put_mds_session(session);
2169         }
2170         mutex_lock(&mdsc->mutex);
2171         return;
2172
2173 needmore:
2174         /*
2175          * we need a larger buffer.  this doesn't very accurately
2176          * factor in snap realms, but it's safe.
2177          */
2178         num_caps += num_realms;
2179         newlen = len * ((100 * (session->s_nr_caps+3)) / (num_caps + 1)) / 100;
2180         pr_info("i guessed %d, and did %d of %d caps, retrying with %d\n",
2181              len, num_caps, session->s_nr_caps, newlen);
2182         len = newlen;
2183         ceph_msg_put(reply);
2184         goto retry;
2185 }
2186
2187
2188 /*
2189  * compare old and new mdsmaps, kicking requests
2190  * and closing out old connections as necessary
2191  *
2192  * called under mdsc->mutex.
2193  */
2194 static void check_new_map(struct ceph_mds_client *mdsc,
2195                           struct ceph_mdsmap *newmap,
2196                           struct ceph_mdsmap *oldmap)
2197 {
2198         int i;
2199         int oldstate, newstate;
2200         struct ceph_mds_session *s;
2201
2202         dout("check_new_map new %u old %u\n",
2203              newmap->m_epoch, oldmap->m_epoch);
2204
2205         for (i = 0; i < oldmap->m_max_mds && i < mdsc->max_sessions; i++) {
2206                 if (mdsc->sessions[i] == NULL)
2207                         continue;
2208                 s = mdsc->sessions[i];
2209                 oldstate = ceph_mdsmap_get_state(oldmap, i);
2210                 newstate = ceph_mdsmap_get_state(newmap, i);
2211
2212                 dout("check_new_map mds%d state %s -> %s (session %s)\n",
2213                      i, ceph_mds_state_name(oldstate),
2214                      ceph_mds_state_name(newstate),
2215                      session_state_name(s->s_state));
2216
2217                 if (memcmp(ceph_mdsmap_get_addr(oldmap, i),
2218                            ceph_mdsmap_get_addr(newmap, i),
2219                            sizeof(struct ceph_entity_addr))) {
2220                         if (s->s_state == CEPH_MDS_SESSION_OPENING) {
2221                                 /* the session never opened, just close it
2222                                  * out now */
2223                                 __wake_requests(mdsc, &s->s_waiting);
2224                                 unregister_session(mdsc, s);
2225                         } else {
2226                                 /* just close it */
2227                                 mutex_unlock(&mdsc->mutex);
2228                                 mutex_lock(&s->s_mutex);
2229                                 mutex_lock(&mdsc->mutex);
2230                                 ceph_con_close(&s->s_con);
2231                                 mutex_unlock(&s->s_mutex);
2232                                 s->s_state = CEPH_MDS_SESSION_RESTARTING;
2233                         }
2234
2235                         /* kick any requests waiting on the recovering mds */
2236                         kick_requests(mdsc, i, 1);
2237                 } else if (oldstate == newstate) {
2238                         continue;  /* nothing new with this mds */
2239                 }
2240
2241                 /*
2242                  * send reconnect?
2243                  */
2244                 if (s->s_state == CEPH_MDS_SESSION_RESTARTING &&
2245                     newstate >= CEPH_MDS_STATE_RECONNECT)
2246                         send_mds_reconnect(mdsc, i);
2247
2248                 /*
2249                  * kick requests on any mds that has gone active.
2250                  *
2251                  * kick requests on cur or forwarder: we may have sent
2252                  * the request to mds1, mds1 told us it forwarded it
2253                  * to mds2, but then we learn mds1 failed and can't be
2254                  * sure it successfully forwarded our request before
2255                  * it died.
2256                  */
2257                 if (oldstate < CEPH_MDS_STATE_ACTIVE &&
2258                     newstate >= CEPH_MDS_STATE_ACTIVE) {
2259                         pr_info("mds%d reconnect completed\n", s->s_mds);
2260                         kick_requests(mdsc, i, 1);
2261                         ceph_kick_flushing_caps(mdsc, s);
2262                         wake_up_session_caps(s, 1);
2263                 }
2264         }
2265 }
2266
2267
2268
2269 /*
2270  * leases
2271  */
2272
2273 /*
2274  * caller must hold session s_mutex, dentry->d_lock
2275  */
2276 void __ceph_mdsc_drop_dentry_lease(struct dentry *dentry)
2277 {
2278         struct ceph_dentry_info *di = ceph_dentry(dentry);
2279
2280         ceph_put_mds_session(di->lease_session);
2281         di->lease_session = NULL;
2282 }
2283
2284 static void handle_lease(struct ceph_mds_client *mdsc, struct ceph_msg *msg)
2285 {
2286         struct super_block *sb = mdsc->client->sb;
2287         struct inode *inode;
2288         struct ceph_mds_session *session;
2289         struct ceph_inode_info *ci;
2290         struct dentry *parent, *dentry;
2291         struct ceph_dentry_info *di;
2292         int mds;
2293         struct ceph_mds_lease *h = msg->front.iov_base;
2294         struct ceph_vino vino;
2295         int mask;
2296         struct qstr dname;
2297         int release = 0;
2298
2299         if (msg->hdr.src.name.type != CEPH_ENTITY_TYPE_MDS)
2300                 return;
2301         mds = le64_to_cpu(msg->hdr.src.name.num);
2302         dout("handle_lease from mds%d\n", mds);
2303
2304         /* decode */
2305         if (msg->front.iov_len < sizeof(*h) + sizeof(u32))
2306                 goto bad;
2307         vino.ino = le64_to_cpu(h->ino);
2308         vino.snap = CEPH_NOSNAP;
2309         mask = le16_to_cpu(h->mask);
2310         dname.name = (void *)h + sizeof(*h) + sizeof(u32);
2311         dname.len = msg->front.iov_len - sizeof(*h) - sizeof(u32);
2312         if (dname.len != get_unaligned_le32(h+1))
2313                 goto bad;
2314
2315         /* find session */
2316         mutex_lock(&mdsc->mutex);
2317         session = __ceph_lookup_mds_session(mdsc, mds);
2318         mutex_unlock(&mdsc->mutex);
2319         if (!session) {
2320                 pr_err("handle_lease got lease but no session mds%d\n", mds);
2321                 return;
2322         }
2323
2324         mutex_lock(&session->s_mutex);
2325         session->s_seq++;
2326
2327         /* lookup inode */
2328         inode = ceph_find_inode(sb, vino);
2329         dout("handle_lease '%s', mask %d, ino %llx %p\n",
2330              ceph_lease_op_name(h->action), mask, vino.ino, inode);
2331         if (inode == NULL) {
2332                 dout("handle_lease no inode %llx\n", vino.ino);
2333                 goto release;
2334         }
2335         ci = ceph_inode(inode);
2336
2337         /* dentry */
2338         parent = d_find_alias(inode);
2339         if (!parent) {
2340                 dout("no parent dentry on inode %p\n", inode);
2341                 WARN_ON(1);
2342                 goto release;  /* hrm... */
2343         }
2344         dname.hash = full_name_hash(dname.name, dname.len);
2345         dentry = d_lookup(parent, &dname);
2346         dput(parent);
2347         if (!dentry)
2348                 goto release;
2349
2350         spin_lock(&dentry->d_lock);
2351         di = ceph_dentry(dentry);
2352         switch (h->action) {
2353         case CEPH_MDS_LEASE_REVOKE:
2354                 if (di && di->lease_session == session) {
2355                         h->seq = cpu_to_le32(di->lease_seq);
2356                         __ceph_mdsc_drop_dentry_lease(dentry);
2357                 }
2358                 release = 1;
2359                 break;
2360
2361         case CEPH_MDS_LEASE_RENEW:
2362                 if (di && di->lease_session == session &&
2363                     di->lease_gen == session->s_cap_gen &&
2364                     di->lease_renew_from &&
2365                     di->lease_renew_after == 0) {
2366                         unsigned long duration =
2367                                 le32_to_cpu(h->duration_ms) * HZ / 1000;
2368
2369                         di->lease_seq = le32_to_cpu(h->seq);
2370                         dentry->d_time = di->lease_renew_from + duration;
2371                         di->lease_renew_after = di->lease_renew_from +
2372                                 (duration >> 1);
2373                         di->lease_renew_from = 0;
2374                 }
2375                 break;
2376         }
2377         spin_unlock(&dentry->d_lock);
2378         dput(dentry);
2379
2380         if (!release)
2381                 goto out;
2382
2383 release:
2384         /* let's just reuse the same message */
2385         h->action = CEPH_MDS_LEASE_REVOKE_ACK;
2386         ceph_msg_get(msg);
2387         ceph_con_send(&session->s_con, msg);
2388
2389 out:
2390         iput(inode);
2391         mutex_unlock(&session->s_mutex);
2392         ceph_put_mds_session(session);
2393         return;
2394
2395 bad:
2396         pr_err("corrupt lease message\n");
2397 }
2398
2399 void ceph_mdsc_lease_send_msg(struct ceph_mds_session *session,
2400                               struct inode *inode,
2401                               struct dentry *dentry, char action,
2402                               u32 seq)
2403 {
2404         struct ceph_msg *msg;
2405         struct ceph_mds_lease *lease;
2406         int len = sizeof(*lease) + sizeof(u32);
2407         int dnamelen = 0;
2408
2409         dout("lease_send_msg inode %p dentry %p %s to mds%d\n",
2410              inode, dentry, ceph_lease_op_name(action), session->s_mds);
2411         dnamelen = dentry->d_name.len;
2412         len += dnamelen;
2413
2414         msg = ceph_msg_new(CEPH_MSG_CLIENT_LEASE, len, 0, 0, NULL);
2415         if (IS_ERR(msg))
2416                 return;
2417         lease = msg->front.iov_base;
2418         lease->action = action;
2419         lease->mask = cpu_to_le16(CEPH_LOCK_DN);
2420         lease->ino = cpu_to_le64(ceph_vino(inode).ino);
2421         lease->first = lease->last = cpu_to_le64(ceph_vino(inode).snap);
2422         lease->seq = cpu_to_le32(seq);
2423         put_unaligned_le32(dnamelen, lease + 1);
2424         memcpy((void *)(lease + 1) + 4, dentry->d_name.name, dnamelen);
2425
2426         /*
2427          * if this is a preemptive lease RELEASE, no need to
2428          * flush request stream, since the actual request will
2429          * soon follow.
2430          */
2431         msg->more_to_follow = (action == CEPH_MDS_LEASE_RELEASE);
2432
2433         ceph_con_send(&session->s_con, msg);
2434 }
2435
2436 /*
2437  * Preemptively release a lease we expect to invalidate anyway.
2438  * Pass @inode always, @dentry is optional.
2439  */
2440 void ceph_mdsc_lease_release(struct ceph_mds_client *mdsc, struct inode *inode,
2441                              struct dentry *dentry, int mask)
2442 {
2443         struct ceph_dentry_info *di;
2444         struct ceph_mds_session *session;
2445         u32 seq;
2446
2447         BUG_ON(inode == NULL);
2448         BUG_ON(dentry == NULL);
2449         BUG_ON(mask != CEPH_LOCK_DN);
2450
2451         /* is dentry lease valid? */
2452         spin_lock(&dentry->d_lock);
2453         di = ceph_dentry(dentry);
2454         if (!di || !di->lease_session ||
2455             di->lease_session->s_mds < 0 ||
2456             di->lease_gen != di->lease_session->s_cap_gen ||
2457             !time_before(jiffies, dentry->d_time)) {
2458                 dout("lease_release inode %p dentry %p -- "
2459                      "no lease on %d\n",
2460                      inode, dentry, mask);
2461                 spin_unlock(&dentry->d_lock);
2462                 return;
2463         }
2464
2465         /* we do have a lease on this dentry; note mds and seq */
2466         session = ceph_get_mds_session(di->lease_session);
2467         seq = di->lease_seq;
2468         __ceph_mdsc_drop_dentry_lease(dentry);
2469         spin_unlock(&dentry->d_lock);
2470
2471         dout("lease_release inode %p dentry %p mask %d to mds%d\n",
2472              inode, dentry, mask, session->s_mds);
2473         ceph_mdsc_lease_send_msg(session, inode, dentry,
2474                                  CEPH_MDS_LEASE_RELEASE, seq);
2475         ceph_put_mds_session(session);
2476 }
2477
2478 /*
2479  * drop all leases (and dentry refs) in preparation for umount
2480  */
2481 static void drop_leases(struct ceph_mds_client *mdsc)
2482 {
2483         int i;
2484
2485         dout("drop_leases\n");
2486         mutex_lock(&mdsc->mutex);
2487         for (i = 0; i < mdsc->max_sessions; i++) {
2488                 struct ceph_mds_session *s = __ceph_lookup_mds_session(mdsc, i);
2489                 if (!s)
2490                         continue;
2491                 mutex_unlock(&mdsc->mutex);
2492                 mutex_lock(&s->s_mutex);
2493                 mutex_unlock(&s->s_mutex);
2494                 ceph_put_mds_session(s);
2495                 mutex_lock(&mdsc->mutex);
2496         }
2497         mutex_unlock(&mdsc->mutex);
2498 }
2499
2500
2501
2502 /*
2503  * delayed work -- periodically trim expired leases, renew caps with mds
2504  */
2505 static void schedule_delayed(struct ceph_mds_client *mdsc)
2506 {
2507         int delay = 5;
2508         unsigned hz = round_jiffies_relative(HZ * delay);
2509         schedule_delayed_work(&mdsc->delayed_work, hz);
2510 }
2511
2512 static void delayed_work(struct work_struct *work)
2513 {
2514         int i;
2515         struct ceph_mds_client *mdsc =
2516                 container_of(work, struct ceph_mds_client, delayed_work.work);
2517         int renew_interval;
2518         int renew_caps;
2519
2520         dout("mdsc delayed_work\n");
2521         ceph_check_delayed_caps(mdsc);
2522
2523         mutex_lock(&mdsc->mutex);
2524         renew_interval = mdsc->mdsmap->m_session_timeout >> 2;
2525         renew_caps = time_after_eq(jiffies, HZ*renew_interval +
2526                                    mdsc->last_renew_caps);
2527         if (renew_caps)
2528                 mdsc->last_renew_caps = jiffies;
2529
2530         for (i = 0; i < mdsc->max_sessions; i++) {
2531                 struct ceph_mds_session *s = __ceph_lookup_mds_session(mdsc, i);
2532                 if (s == NULL)
2533                         continue;
2534                 if (s->s_state == CEPH_MDS_SESSION_CLOSING) {
2535                         dout("resending session close request for mds%d\n",
2536                              s->s_mds);
2537                         request_close_session(mdsc, s);
2538                         ceph_put_mds_session(s);
2539                         continue;
2540                 }
2541                 if (s->s_ttl && time_after(jiffies, s->s_ttl)) {
2542                         if (s->s_state == CEPH_MDS_SESSION_OPEN) {
2543                                 s->s_state = CEPH_MDS_SESSION_HUNG;
2544                                 pr_info("mds%d hung\n", s->s_mds);
2545                         }
2546                 }
2547                 if (s->s_state < CEPH_MDS_SESSION_OPEN) {
2548                         /* this mds is failed or recovering, just wait */
2549                         ceph_put_mds_session(s);
2550                         continue;
2551                 }
2552                 mutex_unlock(&mdsc->mutex);
2553
2554                 mutex_lock(&s->s_mutex);
2555                 if (renew_caps)
2556                         send_renew_caps(mdsc, s);
2557                 else
2558                         ceph_con_keepalive(&s->s_con);
2559                 add_cap_releases(mdsc, s, -1);
2560                 send_cap_releases(mdsc, s);
2561                 mutex_unlock(&s->s_mutex);
2562                 ceph_put_mds_session(s);
2563
2564                 mutex_lock(&mdsc->mutex);
2565         }
2566         mutex_unlock(&mdsc->mutex);
2567
2568         schedule_delayed(mdsc);
2569 }
2570
2571
2572 int ceph_mdsc_init(struct ceph_mds_client *mdsc, struct ceph_client *client)
2573 {
2574         mdsc->client = client;
2575         mutex_init(&mdsc->mutex);
2576         mdsc->mdsmap = kzalloc(sizeof(*mdsc->mdsmap), GFP_NOFS);
2577         init_completion(&mdsc->safe_umount_waiters);
2578         init_completion(&mdsc->session_close_waiters);
2579         INIT_LIST_HEAD(&mdsc->waiting_for_map);
2580         mdsc->sessions = NULL;
2581         mdsc->max_sessions = 0;
2582         mdsc->stopping = 0;
2583         init_rwsem(&mdsc->snap_rwsem);
2584         INIT_RADIX_TREE(&mdsc->snap_realms, GFP_NOFS);
2585         INIT_LIST_HEAD(&mdsc->snap_empty);
2586         spin_lock_init(&mdsc->snap_empty_lock);
2587         mdsc->last_tid = 0;
2588         INIT_RADIX_TREE(&mdsc->request_tree, GFP_NOFS);
2589         INIT_DELAYED_WORK(&mdsc->delayed_work, delayed_work);
2590         mdsc->last_renew_caps = jiffies;
2591         INIT_LIST_HEAD(&mdsc->cap_delay_list);
2592         spin_lock_init(&mdsc->cap_delay_lock);
2593         INIT_LIST_HEAD(&mdsc->snap_flush_list);
2594         spin_lock_init(&mdsc->snap_flush_lock);
2595         mdsc->cap_flush_seq = 0;
2596         INIT_LIST_HEAD(&mdsc->cap_dirty);
2597         mdsc->num_cap_flushing = 0;
2598         spin_lock_init(&mdsc->cap_dirty_lock);
2599         init_waitqueue_head(&mdsc->cap_flushing_wq);
2600         spin_lock_init(&mdsc->dentry_lru_lock);
2601         INIT_LIST_HEAD(&mdsc->dentry_lru);
2602         return 0;
2603 }
2604
2605 /*
2606  * Wait for safe replies on open mds requests.  If we time out, drop
2607  * all requests from the tree to avoid dangling dentry refs.
2608  */
2609 static void wait_requests(struct ceph_mds_client *mdsc)
2610 {
2611         struct ceph_mds_request *req;
2612         struct ceph_client *client = mdsc->client;
2613
2614         mutex_lock(&mdsc->mutex);
2615         if (__get_oldest_tid(mdsc)) {
2616                 mutex_unlock(&mdsc->mutex);
2617                 dout("wait_requests waiting for requests\n");
2618                 wait_for_completion_timeout(&mdsc->safe_umount_waiters,
2619                                     client->mount_args->mount_timeout * HZ);
2620                 mutex_lock(&mdsc->mutex);
2621
2622                 /* tear down remaining requests */
2623                 while (radix_tree_gang_lookup(&mdsc->request_tree,
2624                                               (void **)&req, 0, 1)) {
2625                         dout("wait_requests timed out on tid %llu\n",
2626                              req->r_tid);
2627                         radix_tree_delete(&mdsc->request_tree, req->r_tid);
2628                         ceph_mdsc_put_request(req);
2629                 }
2630         }
2631         mutex_unlock(&mdsc->mutex);
2632         dout("wait_requests done\n");
2633 }
2634
2635 /*
2636  * called before mount is ro, and before dentries are torn down.
2637  * (hmm, does this still race with new lookups?)
2638  */
2639 void ceph_mdsc_pre_umount(struct ceph_mds_client *mdsc)
2640 {
2641         dout("pre_umount\n");
2642         mdsc->stopping = 1;
2643
2644         drop_leases(mdsc);
2645         ceph_flush_dirty_caps(mdsc);
2646         wait_requests(mdsc);
2647 }
2648
2649 /*
2650  * wait for all write mds requests to flush.
2651  */
2652 static void wait_unsafe_requests(struct ceph_mds_client *mdsc, u64 want_tid)
2653 {
2654         struct ceph_mds_request *req;
2655         u64 next_tid = 0;
2656         int got;
2657
2658         mutex_lock(&mdsc->mutex);
2659         dout("wait_unsafe_requests want %lld\n", want_tid);
2660         while (1) {
2661                 got = radix_tree_gang_lookup(&mdsc->request_tree, (void **)&req,
2662                                              next_tid, 1);
2663                 if (!got)
2664                         break;
2665                 if (req->r_tid > want_tid)
2666                         break;
2667
2668                 next_tid = req->r_tid + 1;
2669                 if ((req->r_op & CEPH_MDS_OP_WRITE) == 0)
2670                         continue;  /* not a write op */
2671
2672                 ceph_mdsc_get_request(req);
2673                 mutex_unlock(&mdsc->mutex);
2674                 dout("wait_unsafe_requests  wait on %llu (want %llu)\n",
2675                      req->r_tid, want_tid);
2676                 wait_for_completion(&req->r_safe_completion);
2677                 mutex_lock(&mdsc->mutex);
2678                 ceph_mdsc_put_request(req);
2679         }
2680         mutex_unlock(&mdsc->mutex);
2681         dout("wait_unsafe_requests done\n");
2682 }
2683
2684 void ceph_mdsc_sync(struct ceph_mds_client *mdsc)
2685 {
2686         u64 want_tid, want_flush;
2687
2688         dout("sync\n");
2689         mutex_lock(&mdsc->mutex);
2690         want_tid = mdsc->last_tid;
2691         want_flush = mdsc->cap_flush_seq;
2692         mutex_unlock(&mdsc->mutex);
2693         dout("sync want tid %lld flush_seq %lld\n", want_tid, want_flush);
2694
2695         ceph_flush_dirty_caps(mdsc);
2696
2697         wait_unsafe_requests(mdsc, want_tid);
2698         wait_event(mdsc->cap_flushing_wq, check_cap_flush(mdsc, want_flush));
2699 }
2700
2701
2702 /*
2703  * called after sb is ro.
2704  */
2705 void ceph_mdsc_close_sessions(struct ceph_mds_client *mdsc)
2706 {
2707         struct ceph_mds_session *session;
2708         int i;
2709         int n;
2710         struct ceph_client *client = mdsc->client;
2711         unsigned long started, timeout = client->mount_args->mount_timeout * HZ;
2712
2713         dout("close_sessions\n");
2714
2715         mutex_lock(&mdsc->mutex);
2716
2717         /* close sessions */
2718         started = jiffies;
2719         while (time_before(jiffies, started + timeout)) {
2720                 dout("closing sessions\n");
2721                 n = 0;
2722                 for (i = 0; i < mdsc->max_sessions; i++) {
2723                         session = __ceph_lookup_mds_session(mdsc, i);
2724                         if (!session)
2725                                 continue;
2726                         mutex_unlock(&mdsc->mutex);
2727                         mutex_lock(&session->s_mutex);
2728                         __close_session(mdsc, session);
2729                         mutex_unlock(&session->s_mutex);
2730                         ceph_put_mds_session(session);
2731                         mutex_lock(&mdsc->mutex);
2732                         n++;
2733                 }
2734                 if (n == 0)
2735                         break;
2736
2737                 if (client->mount_state == CEPH_MOUNT_SHUTDOWN)
2738                         break;
2739
2740                 dout("waiting for sessions to close\n");
2741                 mutex_unlock(&mdsc->mutex);
2742                 wait_for_completion_timeout(&mdsc->session_close_waiters,
2743                                             timeout);
2744                 mutex_lock(&mdsc->mutex);
2745         }
2746
2747         /* tear down remaining sessions */
2748         for (i = 0; i < mdsc->max_sessions; i++) {
2749                 if (mdsc->sessions[i]) {
2750                         session = get_session(mdsc->sessions[i]);
2751                         unregister_session(mdsc, session);
2752                         mutex_unlock(&mdsc->mutex);
2753                         mutex_lock(&session->s_mutex);
2754                         remove_session_caps(session);
2755                         mutex_unlock(&session->s_mutex);
2756                         ceph_put_mds_session(session);
2757                         mutex_lock(&mdsc->mutex);
2758                 }
2759         }
2760
2761         WARN_ON(!list_empty(&mdsc->cap_delay_list));
2762
2763         mutex_unlock(&mdsc->mutex);
2764
2765         ceph_cleanup_empty_realms(mdsc);
2766
2767         cancel_delayed_work_sync(&mdsc->delayed_work); /* cancel timer */
2768
2769         dout("stopped\n");
2770 }
2771
2772 void ceph_mdsc_stop(struct ceph_mds_client *mdsc)
2773 {
2774         dout("stop\n");
2775         cancel_delayed_work_sync(&mdsc->delayed_work); /* cancel timer */
2776         if (mdsc->mdsmap)
2777                 ceph_mdsmap_destroy(mdsc->mdsmap);
2778         kfree(mdsc->sessions);
2779 }
2780
2781
2782 /*
2783  * handle mds map update.
2784  */
2785 void ceph_mdsc_handle_map(struct ceph_mds_client *mdsc, struct ceph_msg *msg)
2786 {
2787         u32 epoch;
2788         u32 maplen;
2789         void *p = msg->front.iov_base;
2790         void *end = p + msg->front.iov_len;
2791         struct ceph_mdsmap *newmap, *oldmap;
2792         struct ceph_fsid fsid;
2793         int err = -EINVAL;
2794
2795         ceph_decode_need(&p, end, sizeof(fsid)+2*sizeof(u32), bad);
2796         ceph_decode_copy(&p, &fsid, sizeof(fsid));
2797         if (ceph_check_fsid(mdsc->client, &fsid) < 0)
2798                 return;
2799         epoch = ceph_decode_32(&p);
2800         maplen = ceph_decode_32(&p);
2801         dout("handle_map epoch %u len %d\n", epoch, (int)maplen);
2802
2803         /* do we need it? */
2804         ceph_monc_got_mdsmap(&mdsc->client->monc, epoch);
2805         mutex_lock(&mdsc->mutex);
2806         if (mdsc->mdsmap && epoch <= mdsc->mdsmap->m_epoch) {
2807                 dout("handle_map epoch %u <= our %u\n",
2808                      epoch, mdsc->mdsmap->m_epoch);
2809                 mutex_unlock(&mdsc->mutex);
2810                 return;
2811         }
2812
2813         newmap = ceph_mdsmap_decode(&p, end);
2814         if (IS_ERR(newmap)) {
2815                 err = PTR_ERR(newmap);
2816                 goto bad_unlock;
2817         }
2818
2819         /* swap into place */
2820         if (mdsc->mdsmap) {
2821                 oldmap = mdsc->mdsmap;
2822                 mdsc->mdsmap = newmap;
2823                 check_new_map(mdsc, newmap, oldmap);
2824                 ceph_mdsmap_destroy(oldmap);
2825         } else {
2826                 mdsc->mdsmap = newmap;  /* first mds map */
2827         }
2828         mdsc->client->sb->s_maxbytes = mdsc->mdsmap->m_max_file_size;
2829
2830         __wake_requests(mdsc, &mdsc->waiting_for_map);
2831
2832         mutex_unlock(&mdsc->mutex);
2833         schedule_delayed(mdsc);
2834         return;
2835
2836 bad_unlock:
2837         mutex_unlock(&mdsc->mutex);
2838 bad:
2839         pr_err("error decoding mdsmap %d\n", err);
2840         return;
2841 }
2842
2843 static struct ceph_connection *con_get(struct ceph_connection *con)
2844 {
2845         struct ceph_mds_session *s = con->private;
2846
2847         if (get_session(s)) {
2848                 dout("mdsc con_get %p %d -> %d\n", s,
2849                      atomic_read(&s->s_ref) - 1, atomic_read(&s->s_ref));
2850                 return con;
2851         }
2852         dout("mdsc con_get %p FAIL\n", s);
2853         return NULL;
2854 }
2855
2856 static void con_put(struct ceph_connection *con)
2857 {
2858         struct ceph_mds_session *s = con->private;
2859
2860         dout("mdsc con_put %p %d -> %d\n", s, atomic_read(&s->s_ref),
2861              atomic_read(&s->s_ref) - 1);
2862         ceph_put_mds_session(s);
2863 }
2864
2865 /*
2866  * if the client is unresponsive for long enough, the mds will kill
2867  * the session entirely.
2868  */
2869 static void peer_reset(struct ceph_connection *con)
2870 {
2871         struct ceph_mds_session *s = con->private;
2872
2873         pr_err("mds%d gave us the boot.  IMPLEMENT RECONNECT.\n",
2874                s->s_mds);
2875 }
2876
2877 static void dispatch(struct ceph_connection *con, struct ceph_msg *msg)
2878 {
2879         struct ceph_mds_session *s = con->private;
2880         struct ceph_mds_client *mdsc = s->s_mdsc;
2881         int type = le16_to_cpu(msg->hdr.type);
2882
2883         switch (type) {
2884         case CEPH_MSG_MDS_MAP:
2885                 ceph_mdsc_handle_map(mdsc, msg);
2886                 break;
2887         case CEPH_MSG_CLIENT_SESSION:
2888                 handle_session(s, msg);
2889                 break;
2890         case CEPH_MSG_CLIENT_REPLY:
2891                 handle_reply(s, msg);
2892                 break;
2893         case CEPH_MSG_CLIENT_REQUEST_FORWARD:
2894                 handle_forward(mdsc, msg);
2895                 break;
2896         case CEPH_MSG_CLIENT_CAPS:
2897                 ceph_handle_caps(s, msg);
2898                 break;
2899         case CEPH_MSG_CLIENT_SNAP:
2900                 ceph_handle_snap(mdsc, msg);
2901                 break;
2902         case CEPH_MSG_CLIENT_LEASE:
2903                 handle_lease(mdsc, msg);
2904                 break;
2905
2906         default:
2907                 pr_err("received unknown message type %d %s\n", type,
2908                        ceph_msg_type_name(type));
2909         }
2910         ceph_msg_put(msg);
2911 }
2912
2913 /*
2914  * authentication
2915  */
2916 static int get_authorizer(struct ceph_connection *con,
2917                           void **buf, int *len, int *proto,
2918                           void **reply_buf, int *reply_len, int force_new)
2919 {
2920         struct ceph_mds_session *s = con->private;
2921         struct ceph_mds_client *mdsc = s->s_mdsc;
2922         struct ceph_auth_client *ac = mdsc->client->monc.auth;
2923         int ret = 0;
2924
2925         if (force_new && s->s_authorizer) {
2926                 ac->ops->destroy_authorizer(ac, s->s_authorizer);
2927                 s->s_authorizer = NULL;
2928         }
2929         if (s->s_authorizer == NULL) {
2930                 if (ac->ops->create_authorizer) {
2931                         ret = ac->ops->create_authorizer(
2932                                 ac, CEPH_ENTITY_TYPE_MDS,
2933                                 &s->s_authorizer,
2934                                 &s->s_authorizer_buf,
2935                                 &s->s_authorizer_buf_len,
2936                                 &s->s_authorizer_reply_buf,
2937                                 &s->s_authorizer_reply_buf_len);
2938                         if (ret)
2939                                 return ret;
2940                 }
2941         }
2942
2943         *proto = ac->protocol;
2944         *buf = s->s_authorizer_buf;
2945         *len = s->s_authorizer_buf_len;
2946         *reply_buf = s->s_authorizer_reply_buf;
2947         *reply_len = s->s_authorizer_reply_buf_len;
2948         return 0;
2949 }
2950
2951
2952 static int verify_authorizer_reply(struct ceph_connection *con, int len)
2953 {
2954         struct ceph_mds_session *s = con->private;
2955         struct ceph_mds_client *mdsc = s->s_mdsc;
2956         struct ceph_auth_client *ac = mdsc->client->monc.auth;
2957
2958         return ac->ops->verify_authorizer_reply(ac, s->s_authorizer, len);
2959 }
2960
2961 const static struct ceph_connection_operations mds_con_ops = {
2962         .get = con_get,
2963         .put = con_put,
2964         .dispatch = dispatch,
2965         .get_authorizer = get_authorizer,
2966         .verify_authorizer_reply = verify_authorizer_reply,
2967         .peer_reset = peer_reset,
2968         .alloc_msg = ceph_alloc_msg,
2969         .alloc_middle = ceph_alloc_middle,
2970 };
2971
2972
2973
2974
2975 /* eof */
This page took 0.200173 seconds and 4 git commands to generate.