]> git.karo-electronics.de Git - karo-tx-linux.git/blob - fs/ocfs2/dlm/dlmmaster.c
ocfs2/dlm: do not get resource spinlock if lockres is new
[karo-tx-linux.git] / fs / ocfs2 / dlm / dlmmaster.c
1 /* -*- mode: c; c-basic-offset: 8; -*-
2  * vim: noexpandtab sw=8 ts=8 sts=0:
3  *
4  * dlmmod.c
5  *
6  * standalone DLM module
7  *
8  * Copyright (C) 2004 Oracle.  All rights reserved.
9  *
10  * This program is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU General Public
12  * License as published by the Free Software Foundation; either
13  * version 2 of the License, or (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18  * General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public
21  * License along with this program; if not, write to the
22  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
23  * Boston, MA 021110-1307, USA.
24  *
25  */
26
27
28 #include <linux/module.h>
29 #include <linux/fs.h>
30 #include <linux/types.h>
31 #include <linux/slab.h>
32 #include <linux/highmem.h>
33 #include <linux/init.h>
34 #include <linux/sysctl.h>
35 #include <linux/random.h>
36 #include <linux/blkdev.h>
37 #include <linux/socket.h>
38 #include <linux/inet.h>
39 #include <linux/spinlock.h>
40 #include <linux/delay.h>
41
42
43 #include "cluster/heartbeat.h"
44 #include "cluster/nodemanager.h"
45 #include "cluster/tcp.h"
46
47 #include "dlmapi.h"
48 #include "dlmcommon.h"
49 #include "dlmdomain.h"
50 #include "dlmdebug.h"
51
52 #define MLOG_MASK_PREFIX (ML_DLM|ML_DLM_MASTER)
53 #include "cluster/masklog.h"
54
55 static void dlm_mle_node_down(struct dlm_ctxt *dlm,
56                               struct dlm_master_list_entry *mle,
57                               struct o2nm_node *node,
58                               int idx);
59 static void dlm_mle_node_up(struct dlm_ctxt *dlm,
60                             struct dlm_master_list_entry *mle,
61                             struct o2nm_node *node,
62                             int idx);
63
64 static void dlm_assert_master_worker(struct dlm_work_item *item, void *data);
65 static int dlm_do_assert_master(struct dlm_ctxt *dlm,
66                                 struct dlm_lock_resource *res,
67                                 void *nodemap, u32 flags);
68 static void dlm_deref_lockres_worker(struct dlm_work_item *item, void *data);
69
70 static inline int dlm_mle_equal(struct dlm_ctxt *dlm,
71                                 struct dlm_master_list_entry *mle,
72                                 const char *name,
73                                 unsigned int namelen)
74 {
75         if (dlm != mle->dlm)
76                 return 0;
77
78         if (namelen != mle->mnamelen ||
79             memcmp(name, mle->mname, namelen) != 0)
80                 return 0;
81
82         return 1;
83 }
84
85 static struct kmem_cache *dlm_lockres_cache;
86 static struct kmem_cache *dlm_lockname_cache;
87 static struct kmem_cache *dlm_mle_cache;
88
89 static void dlm_mle_release(struct kref *kref);
90 static void dlm_init_mle(struct dlm_master_list_entry *mle,
91                         enum dlm_mle_type type,
92                         struct dlm_ctxt *dlm,
93                         struct dlm_lock_resource *res,
94                         const char *name,
95                         unsigned int namelen);
96 static void dlm_put_mle(struct dlm_master_list_entry *mle);
97 static void __dlm_put_mle(struct dlm_master_list_entry *mle);
98 static int dlm_find_mle(struct dlm_ctxt *dlm,
99                         struct dlm_master_list_entry **mle,
100                         char *name, unsigned int namelen);
101
102 static int dlm_do_master_request(struct dlm_lock_resource *res,
103                                  struct dlm_master_list_entry *mle, int to);
104
105
106 static int dlm_wait_for_lock_mastery(struct dlm_ctxt *dlm,
107                                      struct dlm_lock_resource *res,
108                                      struct dlm_master_list_entry *mle,
109                                      int *blocked);
110 static int dlm_restart_lock_mastery(struct dlm_ctxt *dlm,
111                                     struct dlm_lock_resource *res,
112                                     struct dlm_master_list_entry *mle,
113                                     int blocked);
114 static int dlm_add_migration_mle(struct dlm_ctxt *dlm,
115                                  struct dlm_lock_resource *res,
116                                  struct dlm_master_list_entry *mle,
117                                  struct dlm_master_list_entry **oldmle,
118                                  const char *name, unsigned int namelen,
119                                  u8 new_master, u8 master);
120
121 static u8 dlm_pick_migration_target(struct dlm_ctxt *dlm,
122                                     struct dlm_lock_resource *res);
123 static void dlm_remove_nonlocal_locks(struct dlm_ctxt *dlm,
124                                       struct dlm_lock_resource *res);
125 static int dlm_mark_lockres_migrating(struct dlm_ctxt *dlm,
126                                        struct dlm_lock_resource *res,
127                                        u8 target);
128 static int dlm_pre_master_reco_lockres(struct dlm_ctxt *dlm,
129                                        struct dlm_lock_resource *res);
130
131
132 int dlm_is_host_down(int errno)
133 {
134         switch (errno) {
135                 case -EBADF:
136                 case -ECONNREFUSED:
137                 case -ENOTCONN:
138                 case -ECONNRESET:
139                 case -EPIPE:
140                 case -EHOSTDOWN:
141                 case -EHOSTUNREACH:
142                 case -ETIMEDOUT:
143                 case -ECONNABORTED:
144                 case -ENETDOWN:
145                 case -ENETUNREACH:
146                 case -ENETRESET:
147                 case -ESHUTDOWN:
148                 case -ENOPROTOOPT:
149                 case -EINVAL:   /* if returned from our tcp code,
150                                    this means there is no socket */
151                         return 1;
152         }
153         return 0;
154 }
155
156
157 /*
158  * MASTER LIST FUNCTIONS
159  */
160
161
162 /*
163  * regarding master list entries and heartbeat callbacks:
164  *
165  * in order to avoid sleeping and allocation that occurs in
166  * heartbeat, master list entries are simply attached to the
167  * dlm's established heartbeat callbacks.  the mle is attached
168  * when it is created, and since the dlm->spinlock is held at
169  * that time, any heartbeat event will be properly discovered
170  * by the mle.  the mle needs to be detached from the
171  * dlm->mle_hb_events list as soon as heartbeat events are no
172  * longer useful to the mle, and before the mle is freed.
173  *
174  * as a general rule, heartbeat events are no longer needed by
175  * the mle once an "answer" regarding the lock master has been
176  * received.
177  */
178 static inline void __dlm_mle_attach_hb_events(struct dlm_ctxt *dlm,
179                                               struct dlm_master_list_entry *mle)
180 {
181         assert_spin_locked(&dlm->spinlock);
182
183         list_add_tail(&mle->hb_events, &dlm->mle_hb_events);
184 }
185
186
187 static inline void __dlm_mle_detach_hb_events(struct dlm_ctxt *dlm,
188                                               struct dlm_master_list_entry *mle)
189 {
190         if (!list_empty(&mle->hb_events))
191                 list_del_init(&mle->hb_events);
192 }
193
194
195 static inline void dlm_mle_detach_hb_events(struct dlm_ctxt *dlm,
196                                             struct dlm_master_list_entry *mle)
197 {
198         spin_lock(&dlm->spinlock);
199         __dlm_mle_detach_hb_events(dlm, mle);
200         spin_unlock(&dlm->spinlock);
201 }
202
203 static void dlm_get_mle_inuse(struct dlm_master_list_entry *mle)
204 {
205         struct dlm_ctxt *dlm;
206         dlm = mle->dlm;
207
208         assert_spin_locked(&dlm->spinlock);
209         assert_spin_locked(&dlm->master_lock);
210         mle->inuse++;
211         kref_get(&mle->mle_refs);
212 }
213
214 static void dlm_put_mle_inuse(struct dlm_master_list_entry *mle)
215 {
216         struct dlm_ctxt *dlm;
217         dlm = mle->dlm;
218
219         spin_lock(&dlm->spinlock);
220         spin_lock(&dlm->master_lock);
221         mle->inuse--;
222         __dlm_put_mle(mle);
223         spin_unlock(&dlm->master_lock);
224         spin_unlock(&dlm->spinlock);
225
226 }
227
228 /* remove from list and free */
229 static void __dlm_put_mle(struct dlm_master_list_entry *mle)
230 {
231         struct dlm_ctxt *dlm;
232         dlm = mle->dlm;
233
234         assert_spin_locked(&dlm->spinlock);
235         assert_spin_locked(&dlm->master_lock);
236         if (!atomic_read(&mle->mle_refs.refcount)) {
237                 /* this may or may not crash, but who cares.
238                  * it's a BUG. */
239                 mlog(ML_ERROR, "bad mle: %p\n", mle);
240                 dlm_print_one_mle(mle);
241                 BUG();
242         } else
243                 kref_put(&mle->mle_refs, dlm_mle_release);
244 }
245
246
247 /* must not have any spinlocks coming in */
248 static void dlm_put_mle(struct dlm_master_list_entry *mle)
249 {
250         struct dlm_ctxt *dlm;
251         dlm = mle->dlm;
252
253         spin_lock(&dlm->spinlock);
254         spin_lock(&dlm->master_lock);
255         __dlm_put_mle(mle);
256         spin_unlock(&dlm->master_lock);
257         spin_unlock(&dlm->spinlock);
258 }
259
260 static inline void dlm_get_mle(struct dlm_master_list_entry *mle)
261 {
262         kref_get(&mle->mle_refs);
263 }
264
265 static void dlm_init_mle(struct dlm_master_list_entry *mle,
266                         enum dlm_mle_type type,
267                         struct dlm_ctxt *dlm,
268                         struct dlm_lock_resource *res,
269                         const char *name,
270                         unsigned int namelen)
271 {
272         assert_spin_locked(&dlm->spinlock);
273
274         mle->dlm = dlm;
275         mle->type = type;
276         INIT_HLIST_NODE(&mle->master_hash_node);
277         INIT_LIST_HEAD(&mle->hb_events);
278         memset(mle->maybe_map, 0, sizeof(mle->maybe_map));
279         spin_lock_init(&mle->spinlock);
280         init_waitqueue_head(&mle->wq);
281         atomic_set(&mle->woken, 0);
282         kref_init(&mle->mle_refs);
283         memset(mle->response_map, 0, sizeof(mle->response_map));
284         mle->master = O2NM_MAX_NODES;
285         mle->new_master = O2NM_MAX_NODES;
286         mle->inuse = 0;
287
288         BUG_ON(mle->type != DLM_MLE_BLOCK &&
289                mle->type != DLM_MLE_MASTER &&
290                mle->type != DLM_MLE_MIGRATION);
291
292         if (mle->type == DLM_MLE_MASTER) {
293                 BUG_ON(!res);
294                 mle->mleres = res;
295                 memcpy(mle->mname, res->lockname.name, res->lockname.len);
296                 mle->mnamelen = res->lockname.len;
297                 mle->mnamehash = res->lockname.hash;
298         } else {
299                 BUG_ON(!name);
300                 mle->mleres = NULL;
301                 memcpy(mle->mname, name, namelen);
302                 mle->mnamelen = namelen;
303                 mle->mnamehash = dlm_lockid_hash(name, namelen);
304         }
305
306         atomic_inc(&dlm->mle_tot_count[mle->type]);
307         atomic_inc(&dlm->mle_cur_count[mle->type]);
308
309         /* copy off the node_map and register hb callbacks on our copy */
310         memcpy(mle->node_map, dlm->domain_map, sizeof(mle->node_map));
311         memcpy(mle->vote_map, dlm->domain_map, sizeof(mle->vote_map));
312         clear_bit(dlm->node_num, mle->vote_map);
313         clear_bit(dlm->node_num, mle->node_map);
314
315         /* attach the mle to the domain node up/down events */
316         __dlm_mle_attach_hb_events(dlm, mle);
317 }
318
319 void __dlm_unlink_mle(struct dlm_ctxt *dlm, struct dlm_master_list_entry *mle)
320 {
321         assert_spin_locked(&dlm->spinlock);
322         assert_spin_locked(&dlm->master_lock);
323
324         if (!hlist_unhashed(&mle->master_hash_node))
325                 hlist_del_init(&mle->master_hash_node);
326 }
327
328 void __dlm_insert_mle(struct dlm_ctxt *dlm, struct dlm_master_list_entry *mle)
329 {
330         struct hlist_head *bucket;
331
332         assert_spin_locked(&dlm->master_lock);
333
334         bucket = dlm_master_hash(dlm, mle->mnamehash);
335         hlist_add_head(&mle->master_hash_node, bucket);
336 }
337
338 /* returns 1 if found, 0 if not */
339 static int dlm_find_mle(struct dlm_ctxt *dlm,
340                         struct dlm_master_list_entry **mle,
341                         char *name, unsigned int namelen)
342 {
343         struct dlm_master_list_entry *tmpmle;
344         struct hlist_head *bucket;
345         unsigned int hash;
346
347         assert_spin_locked(&dlm->master_lock);
348
349         hash = dlm_lockid_hash(name, namelen);
350         bucket = dlm_master_hash(dlm, hash);
351         hlist_for_each_entry(tmpmle, bucket, master_hash_node) {
352                 if (!dlm_mle_equal(dlm, tmpmle, name, namelen))
353                         continue;
354                 dlm_get_mle(tmpmle);
355                 *mle = tmpmle;
356                 return 1;
357         }
358         return 0;
359 }
360
361 void dlm_hb_event_notify_attached(struct dlm_ctxt *dlm, int idx, int node_up)
362 {
363         struct dlm_master_list_entry *mle;
364
365         assert_spin_locked(&dlm->spinlock);
366
367         list_for_each_entry(mle, &dlm->mle_hb_events, hb_events) {
368                 if (node_up)
369                         dlm_mle_node_up(dlm, mle, NULL, idx);
370                 else
371                         dlm_mle_node_down(dlm, mle, NULL, idx);
372         }
373 }
374
375 static void dlm_mle_node_down(struct dlm_ctxt *dlm,
376                               struct dlm_master_list_entry *mle,
377                               struct o2nm_node *node, int idx)
378 {
379         spin_lock(&mle->spinlock);
380
381         if (!test_bit(idx, mle->node_map))
382                 mlog(0, "node %u already removed from nodemap!\n", idx);
383         else
384                 clear_bit(idx, mle->node_map);
385
386         spin_unlock(&mle->spinlock);
387 }
388
389 static void dlm_mle_node_up(struct dlm_ctxt *dlm,
390                             struct dlm_master_list_entry *mle,
391                             struct o2nm_node *node, int idx)
392 {
393         spin_lock(&mle->spinlock);
394
395         if (test_bit(idx, mle->node_map))
396                 mlog(0, "node %u already in node map!\n", idx);
397         else
398                 set_bit(idx, mle->node_map);
399
400         spin_unlock(&mle->spinlock);
401 }
402
403
404 int dlm_init_mle_cache(void)
405 {
406         dlm_mle_cache = kmem_cache_create("o2dlm_mle",
407                                           sizeof(struct dlm_master_list_entry),
408                                           0, SLAB_HWCACHE_ALIGN,
409                                           NULL);
410         if (dlm_mle_cache == NULL)
411                 return -ENOMEM;
412         return 0;
413 }
414
415 void dlm_destroy_mle_cache(void)
416 {
417         if (dlm_mle_cache)
418                 kmem_cache_destroy(dlm_mle_cache);
419 }
420
421 static void dlm_mle_release(struct kref *kref)
422 {
423         struct dlm_master_list_entry *mle;
424         struct dlm_ctxt *dlm;
425
426         mle = container_of(kref, struct dlm_master_list_entry, mle_refs);
427         dlm = mle->dlm;
428
429         assert_spin_locked(&dlm->spinlock);
430         assert_spin_locked(&dlm->master_lock);
431
432         mlog(0, "Releasing mle for %.*s, type %d\n", mle->mnamelen, mle->mname,
433              mle->type);
434
435         /* remove from list if not already */
436         __dlm_unlink_mle(dlm, mle);
437
438         /* detach the mle from the domain node up/down events */
439         __dlm_mle_detach_hb_events(dlm, mle);
440
441         atomic_dec(&dlm->mle_cur_count[mle->type]);
442
443         /* NOTE: kfree under spinlock here.
444          * if this is bad, we can move this to a freelist. */
445         kmem_cache_free(dlm_mle_cache, mle);
446 }
447
448
449 /*
450  * LOCK RESOURCE FUNCTIONS
451  */
452
453 int dlm_init_master_caches(void)
454 {
455         dlm_lockres_cache = kmem_cache_create("o2dlm_lockres",
456                                               sizeof(struct dlm_lock_resource),
457                                               0, SLAB_HWCACHE_ALIGN, NULL);
458         if (!dlm_lockres_cache)
459                 goto bail;
460
461         dlm_lockname_cache = kmem_cache_create("o2dlm_lockname",
462                                                DLM_LOCKID_NAME_MAX, 0,
463                                                SLAB_HWCACHE_ALIGN, NULL);
464         if (!dlm_lockname_cache)
465                 goto bail;
466
467         return 0;
468 bail:
469         dlm_destroy_master_caches();
470         return -ENOMEM;
471 }
472
473 void dlm_destroy_master_caches(void)
474 {
475         if (dlm_lockname_cache) {
476                 kmem_cache_destroy(dlm_lockname_cache);
477                 dlm_lockname_cache = NULL;
478         }
479
480         if (dlm_lockres_cache) {
481                 kmem_cache_destroy(dlm_lockres_cache);
482                 dlm_lockres_cache = NULL;
483         }
484 }
485
486 static void dlm_lockres_release(struct kref *kref)
487 {
488         struct dlm_lock_resource *res;
489         struct dlm_ctxt *dlm;
490
491         res = container_of(kref, struct dlm_lock_resource, refs);
492         dlm = res->dlm;
493
494         /* This should not happen -- all lockres' have a name
495          * associated with them at init time. */
496         BUG_ON(!res->lockname.name);
497
498         mlog(0, "destroying lockres %.*s\n", res->lockname.len,
499              res->lockname.name);
500
501         spin_lock(&dlm->track_lock);
502         if (!list_empty(&res->tracking))
503                 list_del_init(&res->tracking);
504         else {
505                 mlog(ML_ERROR, "Resource %.*s not on the Tracking list\n",
506                      res->lockname.len, res->lockname.name);
507                 dlm_print_one_lock_resource(res);
508         }
509         spin_unlock(&dlm->track_lock);
510
511         atomic_dec(&dlm->res_cur_count);
512
513         if (!hlist_unhashed(&res->hash_node) ||
514             !list_empty(&res->granted) ||
515             !list_empty(&res->converting) ||
516             !list_empty(&res->blocked) ||
517             !list_empty(&res->dirty) ||
518             !list_empty(&res->recovering) ||
519             !list_empty(&res->purge)) {
520                 mlog(ML_ERROR,
521                      "Going to BUG for resource %.*s."
522                      "  We're on a list! [%c%c%c%c%c%c%c]\n",
523                      res->lockname.len, res->lockname.name,
524                      !hlist_unhashed(&res->hash_node) ? 'H' : ' ',
525                      !list_empty(&res->granted) ? 'G' : ' ',
526                      !list_empty(&res->converting) ? 'C' : ' ',
527                      !list_empty(&res->blocked) ? 'B' : ' ',
528                      !list_empty(&res->dirty) ? 'D' : ' ',
529                      !list_empty(&res->recovering) ? 'R' : ' ',
530                      !list_empty(&res->purge) ? 'P' : ' ');
531
532                 dlm_print_one_lock_resource(res);
533         }
534
535         /* By the time we're ready to blow this guy away, we shouldn't
536          * be on any lists. */
537         BUG_ON(!hlist_unhashed(&res->hash_node));
538         BUG_ON(!list_empty(&res->granted));
539         BUG_ON(!list_empty(&res->converting));
540         BUG_ON(!list_empty(&res->blocked));
541         BUG_ON(!list_empty(&res->dirty));
542         BUG_ON(!list_empty(&res->recovering));
543         BUG_ON(!list_empty(&res->purge));
544
545         kmem_cache_free(dlm_lockname_cache, (void *)res->lockname.name);
546
547         kmem_cache_free(dlm_lockres_cache, res);
548 }
549
550 void dlm_lockres_put(struct dlm_lock_resource *res)
551 {
552         kref_put(&res->refs, dlm_lockres_release);
553 }
554
555 static void dlm_init_lockres(struct dlm_ctxt *dlm,
556                              struct dlm_lock_resource *res,
557                              const char *name, unsigned int namelen)
558 {
559         char *qname;
560
561         /* If we memset here, we lose our reference to the kmalloc'd
562          * res->lockname.name, so be sure to init every field
563          * correctly! */
564
565         qname = (char *) res->lockname.name;
566         memcpy(qname, name, namelen);
567
568         res->lockname.len = namelen;
569         res->lockname.hash = dlm_lockid_hash(name, namelen);
570
571         init_waitqueue_head(&res->wq);
572         spin_lock_init(&res->spinlock);
573         INIT_HLIST_NODE(&res->hash_node);
574         INIT_LIST_HEAD(&res->granted);
575         INIT_LIST_HEAD(&res->converting);
576         INIT_LIST_HEAD(&res->blocked);
577         INIT_LIST_HEAD(&res->dirty);
578         INIT_LIST_HEAD(&res->recovering);
579         INIT_LIST_HEAD(&res->purge);
580         INIT_LIST_HEAD(&res->tracking);
581         atomic_set(&res->asts_reserved, 0);
582         res->migration_pending = 0;
583         res->inflight_locks = 0;
584         res->inflight_assert_workers = 0;
585
586         res->dlm = dlm;
587
588         kref_init(&res->refs);
589
590         atomic_inc(&dlm->res_tot_count);
591         atomic_inc(&dlm->res_cur_count);
592
593         /* just for consistency */
594         spin_lock(&res->spinlock);
595         dlm_set_lockres_owner(dlm, res, DLM_LOCK_RES_OWNER_UNKNOWN);
596         spin_unlock(&res->spinlock);
597
598         res->state = DLM_LOCK_RES_IN_PROGRESS;
599
600         res->last_used = 0;
601
602         spin_lock(&dlm->spinlock);
603         list_add_tail(&res->tracking, &dlm->tracking_list);
604         spin_unlock(&dlm->spinlock);
605
606         memset(res->lvb, 0, DLM_LVB_LEN);
607         memset(res->refmap, 0, sizeof(res->refmap));
608 }
609
610 struct dlm_lock_resource *dlm_new_lockres(struct dlm_ctxt *dlm,
611                                    const char *name,
612                                    unsigned int namelen)
613 {
614         struct dlm_lock_resource *res = NULL;
615
616         res = kmem_cache_zalloc(dlm_lockres_cache, GFP_NOFS);
617         if (!res)
618                 goto error;
619
620         res->lockname.name = kmem_cache_zalloc(dlm_lockname_cache, GFP_NOFS);
621         if (!res->lockname.name)
622                 goto error;
623
624         dlm_init_lockres(dlm, res, name, namelen);
625         return res;
626
627 error:
628         if (res && res->lockname.name)
629                 kmem_cache_free(dlm_lockname_cache, (void *)res->lockname.name);
630
631         if (res)
632                 kmem_cache_free(dlm_lockres_cache, res);
633         return NULL;
634 }
635
636 void dlm_lockres_set_refmap_bit(struct dlm_ctxt *dlm,
637                                 struct dlm_lock_resource *res, int bit)
638 {
639         assert_spin_locked(&res->spinlock);
640
641         mlog(0, "res %.*s, set node %u, %ps()\n", res->lockname.len,
642              res->lockname.name, bit, __builtin_return_address(0));
643
644         set_bit(bit, res->refmap);
645 }
646
647 void dlm_lockres_clear_refmap_bit(struct dlm_ctxt *dlm,
648                                   struct dlm_lock_resource *res, int bit)
649 {
650         assert_spin_locked(&res->spinlock);
651
652         mlog(0, "res %.*s, clr node %u, %ps()\n", res->lockname.len,
653              res->lockname.name, bit, __builtin_return_address(0));
654
655         clear_bit(bit, res->refmap);
656 }
657
658 static void __dlm_lockres_grab_inflight_ref(struct dlm_ctxt *dlm,
659                                    struct dlm_lock_resource *res)
660 {
661         res->inflight_locks++;
662
663         mlog(0, "%s: res %.*s, inflight++: now %u, %ps()\n", dlm->name,
664              res->lockname.len, res->lockname.name, res->inflight_locks,
665              __builtin_return_address(0));
666 }
667
668 void dlm_lockres_grab_inflight_ref(struct dlm_ctxt *dlm,
669                                    struct dlm_lock_resource *res)
670 {
671         assert_spin_locked(&res->spinlock);
672         __dlm_lockres_grab_inflight_ref(dlm, res);
673 }
674
675 void dlm_lockres_drop_inflight_ref(struct dlm_ctxt *dlm,
676                                    struct dlm_lock_resource *res)
677 {
678         assert_spin_locked(&res->spinlock);
679
680         BUG_ON(res->inflight_locks == 0);
681
682         res->inflight_locks--;
683
684         mlog(0, "%s: res %.*s, inflight--: now %u, %ps()\n", dlm->name,
685              res->lockname.len, res->lockname.name, res->inflight_locks,
686              __builtin_return_address(0));
687
688         wake_up(&res->wq);
689 }
690
691 void __dlm_lockres_grab_inflight_worker(struct dlm_ctxt *dlm,
692                 struct dlm_lock_resource *res)
693 {
694         assert_spin_locked(&res->spinlock);
695         res->inflight_assert_workers++;
696         mlog(0, "%s:%.*s: inflight assert worker++: now %u\n",
697                         dlm->name, res->lockname.len, res->lockname.name,
698                         res->inflight_assert_workers);
699 }
700
701 static void dlm_lockres_grab_inflight_worker(struct dlm_ctxt *dlm,
702                 struct dlm_lock_resource *res)
703 {
704         spin_lock(&res->spinlock);
705         __dlm_lockres_grab_inflight_worker(dlm, res);
706         spin_unlock(&res->spinlock);
707 }
708
709 static void __dlm_lockres_drop_inflight_worker(struct dlm_ctxt *dlm,
710                 struct dlm_lock_resource *res)
711 {
712         assert_spin_locked(&res->spinlock);
713         BUG_ON(res->inflight_assert_workers == 0);
714         res->inflight_assert_workers--;
715         mlog(0, "%s:%.*s: inflight assert worker--: now %u\n",
716                         dlm->name, res->lockname.len, res->lockname.name,
717                         res->inflight_assert_workers);
718 }
719
720 static void dlm_lockres_drop_inflight_worker(struct dlm_ctxt *dlm,
721                 struct dlm_lock_resource *res)
722 {
723         spin_lock(&res->spinlock);
724         __dlm_lockres_drop_inflight_worker(dlm, res);
725         spin_unlock(&res->spinlock);
726 }
727
728 /*
729  * lookup a lock resource by name.
730  * may already exist in the hashtable.
731  * lockid is null terminated
732  *
733  * if not, allocate enough for the lockres and for
734  * the temporary structure used in doing the mastering.
735  *
736  * also, do a lookup in the dlm->master_list to see
737  * if another node has begun mastering the same lock.
738  * if so, there should be a block entry in there
739  * for this name, and we should *not* attempt to master
740  * the lock here.   need to wait around for that node
741  * to assert_master (or die).
742  *
743  */
744 struct dlm_lock_resource * dlm_get_lock_resource(struct dlm_ctxt *dlm,
745                                           const char *lockid,
746                                           int namelen,
747                                           int flags)
748 {
749         struct dlm_lock_resource *tmpres=NULL, *res=NULL;
750         struct dlm_master_list_entry *mle = NULL;
751         struct dlm_master_list_entry *alloc_mle = NULL;
752         int blocked = 0;
753         int ret, nodenum;
754         struct dlm_node_iter iter;
755         unsigned int hash;
756         int tries = 0;
757         int bit, wait_on_recovery = 0;
758
759         BUG_ON(!lockid);
760
761         hash = dlm_lockid_hash(lockid, namelen);
762
763         mlog(0, "get lockres %s (len %d)\n", lockid, namelen);
764
765 lookup:
766         spin_lock(&dlm->spinlock);
767         tmpres = __dlm_lookup_lockres_full(dlm, lockid, namelen, hash);
768         if (tmpres) {
769                 spin_unlock(&dlm->spinlock);
770                 spin_lock(&tmpres->spinlock);
771                 /* Wait on the thread that is mastering the resource */
772                 if (tmpres->owner == DLM_LOCK_RES_OWNER_UNKNOWN) {
773                         __dlm_wait_on_lockres(tmpres);
774                         BUG_ON(tmpres->owner == DLM_LOCK_RES_OWNER_UNKNOWN);
775                         spin_unlock(&tmpres->spinlock);
776                         dlm_lockres_put(tmpres);
777                         tmpres = NULL;
778                         goto lookup;
779                 }
780
781                 /* Wait on the resource purge to complete before continuing */
782                 if (tmpres->state & DLM_LOCK_RES_DROPPING_REF) {
783                         BUG_ON(tmpres->owner == dlm->node_num);
784                         __dlm_wait_on_lockres_flags(tmpres,
785                                                     DLM_LOCK_RES_DROPPING_REF);
786                         spin_unlock(&tmpres->spinlock);
787                         dlm_lockres_put(tmpres);
788                         tmpres = NULL;
789                         goto lookup;
790                 }
791
792                 /* Grab inflight ref to pin the resource */
793                 dlm_lockres_grab_inflight_ref(dlm, tmpres);
794
795                 spin_unlock(&tmpres->spinlock);
796                 if (res)
797                         dlm_lockres_put(res);
798                 res = tmpres;
799                 goto leave;
800         }
801
802         if (!res) {
803                 spin_unlock(&dlm->spinlock);
804                 mlog(0, "allocating a new resource\n");
805                 /* nothing found and we need to allocate one. */
806                 alloc_mle = kmem_cache_alloc(dlm_mle_cache, GFP_NOFS);
807                 if (!alloc_mle)
808                         goto leave;
809                 res = dlm_new_lockres(dlm, lockid, namelen);
810                 if (!res)
811                         goto leave;
812                 goto lookup;
813         }
814
815         mlog(0, "no lockres found, allocated our own: %p\n", res);
816
817         if (flags & LKM_LOCAL) {
818                 /* caller knows it's safe to assume it's not mastered elsewhere
819                  * DONE!  return right away */
820                 spin_lock(&res->spinlock);
821                 dlm_change_lockres_owner(dlm, res, dlm->node_num);
822                 __dlm_insert_lockres(dlm, res);
823                 dlm_lockres_grab_inflight_ref(dlm, res);
824                 spin_unlock(&res->spinlock);
825                 spin_unlock(&dlm->spinlock);
826                 /* lockres still marked IN_PROGRESS */
827                 goto wake_waiters;
828         }
829
830         /* check master list to see if another node has started mastering it */
831         spin_lock(&dlm->master_lock);
832
833         /* if we found a block, wait for lock to be mastered by another node */
834         blocked = dlm_find_mle(dlm, &mle, (char *)lockid, namelen);
835         if (blocked) {
836                 int mig;
837                 if (mle->type == DLM_MLE_MASTER) {
838                         mlog(ML_ERROR, "master entry for nonexistent lock!\n");
839                         BUG();
840                 }
841                 mig = (mle->type == DLM_MLE_MIGRATION);
842                 /* if there is a migration in progress, let the migration
843                  * finish before continuing.  we can wait for the absence
844                  * of the MIGRATION mle: either the migrate finished or
845                  * one of the nodes died and the mle was cleaned up.
846                  * if there is a BLOCK here, but it already has a master
847                  * set, we are too late.  the master does not have a ref
848                  * for us in the refmap.  detach the mle and drop it.
849                  * either way, go back to the top and start over. */
850                 if (mig || mle->master != O2NM_MAX_NODES) {
851                         BUG_ON(mig && mle->master == dlm->node_num);
852                         /* we arrived too late.  the master does not
853                          * have a ref for us. retry. */
854                         mlog(0, "%s:%.*s: late on %s\n",
855                              dlm->name, namelen, lockid,
856                              mig ?  "MIGRATION" : "BLOCK");
857                         spin_unlock(&dlm->master_lock);
858                         spin_unlock(&dlm->spinlock);
859
860                         /* master is known, detach */
861                         if (!mig)
862                                 dlm_mle_detach_hb_events(dlm, mle);
863                         dlm_put_mle(mle);
864                         mle = NULL;
865                         /* this is lame, but we can't wait on either
866                          * the mle or lockres waitqueue here */
867                         if (mig)
868                                 msleep(100);
869                         goto lookup;
870                 }
871         } else {
872                 /* go ahead and try to master lock on this node */
873                 mle = alloc_mle;
874                 /* make sure this does not get freed below */
875                 alloc_mle = NULL;
876                 dlm_init_mle(mle, DLM_MLE_MASTER, dlm, res, NULL, 0);
877                 set_bit(dlm->node_num, mle->maybe_map);
878                 __dlm_insert_mle(dlm, mle);
879
880                 /* still holding the dlm spinlock, check the recovery map
881                  * to see if there are any nodes that still need to be
882                  * considered.  these will not appear in the mle nodemap
883                  * but they might own this lockres.  wait on them. */
884                 bit = find_next_bit(dlm->recovery_map, O2NM_MAX_NODES, 0);
885                 if (bit < O2NM_MAX_NODES) {
886                         mlog(0, "%s: res %.*s, At least one node (%d) "
887                              "to recover before lock mastery can begin\n",
888                              dlm->name, namelen, (char *)lockid, bit);
889                         wait_on_recovery = 1;
890                 }
891         }
892
893         /* at this point there is either a DLM_MLE_BLOCK or a
894          * DLM_MLE_MASTER on the master list, so it's safe to add the
895          * lockres to the hashtable.  anyone who finds the lock will
896          * still have to wait on the IN_PROGRESS. */
897
898         /* finally add the lockres to its hash bucket */
899         __dlm_insert_lockres(dlm, res);
900
901         /* since this lockres is new it doesn't not require the spinlock */
902         __dlm_lockres_grab_inflight_ref(dlm, res);
903
904         /* get an extra ref on the mle in case this is a BLOCK
905          * if so, the creator of the BLOCK may try to put the last
906          * ref at this time in the assert master handler, so we
907          * need an extra one to keep from a bad ptr deref. */
908         dlm_get_mle_inuse(mle);
909         spin_unlock(&dlm->master_lock);
910         spin_unlock(&dlm->spinlock);
911
912 redo_request:
913         while (wait_on_recovery) {
914                 /* any cluster changes that occurred after dropping the
915                  * dlm spinlock would be detectable be a change on the mle,
916                  * so we only need to clear out the recovery map once. */
917                 if (dlm_is_recovery_lock(lockid, namelen)) {
918                         mlog(0, "%s: Recovery map is not empty, but must "
919                              "master $RECOVERY lock now\n", dlm->name);
920                         if (!dlm_pre_master_reco_lockres(dlm, res))
921                                 wait_on_recovery = 0;
922                         else {
923                                 mlog(0, "%s: waiting 500ms for heartbeat state "
924                                     "change\n", dlm->name);
925                                 msleep(500);
926                         }
927                         continue;
928                 }
929
930                 dlm_kick_recovery_thread(dlm);
931                 msleep(1000);
932                 dlm_wait_for_recovery(dlm);
933
934                 spin_lock(&dlm->spinlock);
935                 bit = find_next_bit(dlm->recovery_map, O2NM_MAX_NODES, 0);
936                 if (bit < O2NM_MAX_NODES) {
937                         mlog(0, "%s: res %.*s, At least one node (%d) "
938                              "to recover before lock mastery can begin\n",
939                              dlm->name, namelen, (char *)lockid, bit);
940                         wait_on_recovery = 1;
941                 } else
942                         wait_on_recovery = 0;
943                 spin_unlock(&dlm->spinlock);
944
945                 if (wait_on_recovery)
946                         dlm_wait_for_node_recovery(dlm, bit, 10000);
947         }
948
949         /* must wait for lock to be mastered elsewhere */
950         if (blocked)
951                 goto wait;
952
953         ret = -EINVAL;
954         dlm_node_iter_init(mle->vote_map, &iter);
955         while ((nodenum = dlm_node_iter_next(&iter)) >= 0) {
956                 ret = dlm_do_master_request(res, mle, nodenum);
957                 if (ret < 0)
958                         mlog_errno(ret);
959                 if (mle->master != O2NM_MAX_NODES) {
960                         /* found a master ! */
961                         if (mle->master <= nodenum)
962                                 break;
963                         /* if our master request has not reached the master
964                          * yet, keep going until it does.  this is how the
965                          * master will know that asserts are needed back to
966                          * the lower nodes. */
967                         mlog(0, "%s: res %.*s, Requests only up to %u but "
968                              "master is %u, keep going\n", dlm->name, namelen,
969                              lockid, nodenum, mle->master);
970                 }
971         }
972
973 wait:
974         /* keep going until the response map includes all nodes */
975         ret = dlm_wait_for_lock_mastery(dlm, res, mle, &blocked);
976         if (ret < 0) {
977                 wait_on_recovery = 1;
978                 mlog(0, "%s: res %.*s, Node map changed, redo the master "
979                      "request now, blocked=%d\n", dlm->name, res->lockname.len,
980                      res->lockname.name, blocked);
981                 if (++tries > 20) {
982                         mlog(ML_ERROR, "%s: res %.*s, Spinning on "
983                              "dlm_wait_for_lock_mastery, blocked = %d\n",
984                              dlm->name, res->lockname.len,
985                              res->lockname.name, blocked);
986                         dlm_print_one_lock_resource(res);
987                         dlm_print_one_mle(mle);
988                         tries = 0;
989                 }
990                 goto redo_request;
991         }
992
993         mlog(0, "%s: res %.*s, Mastered by %u\n", dlm->name, res->lockname.len,
994              res->lockname.name, res->owner);
995         /* make sure we never continue without this */
996         BUG_ON(res->owner == O2NM_MAX_NODES);
997
998         /* master is known, detach if not already detached */
999         dlm_mle_detach_hb_events(dlm, mle);
1000         dlm_put_mle(mle);
1001         /* put the extra ref */
1002         dlm_put_mle_inuse(mle);
1003
1004 wake_waiters:
1005         spin_lock(&res->spinlock);
1006         res->state &= ~DLM_LOCK_RES_IN_PROGRESS;
1007         spin_unlock(&res->spinlock);
1008         wake_up(&res->wq);
1009
1010 leave:
1011         /* need to free the unused mle */
1012         if (alloc_mle)
1013                 kmem_cache_free(dlm_mle_cache, alloc_mle);
1014
1015         return res;
1016 }
1017
1018
1019 #define DLM_MASTERY_TIMEOUT_MS   5000
1020
1021 static int dlm_wait_for_lock_mastery(struct dlm_ctxt *dlm,
1022                                      struct dlm_lock_resource *res,
1023                                      struct dlm_master_list_entry *mle,
1024                                      int *blocked)
1025 {
1026         u8 m;
1027         int ret, bit;
1028         int map_changed, voting_done;
1029         int assert, sleep;
1030
1031 recheck:
1032         ret = 0;
1033         assert = 0;
1034
1035         /* check if another node has already become the owner */
1036         spin_lock(&res->spinlock);
1037         if (res->owner != DLM_LOCK_RES_OWNER_UNKNOWN) {
1038                 mlog(0, "%s:%.*s: owner is suddenly %u\n", dlm->name,
1039                      res->lockname.len, res->lockname.name, res->owner);
1040                 spin_unlock(&res->spinlock);
1041                 /* this will cause the master to re-assert across
1042                  * the whole cluster, freeing up mles */
1043                 if (res->owner != dlm->node_num) {
1044                         ret = dlm_do_master_request(res, mle, res->owner);
1045                         if (ret < 0) {
1046                                 /* give recovery a chance to run */
1047                                 mlog(ML_ERROR, "link to %u went down?: %d\n", res->owner, ret);
1048                                 msleep(500);
1049                                 goto recheck;
1050                         }
1051                 }
1052                 ret = 0;
1053                 goto leave;
1054         }
1055         spin_unlock(&res->spinlock);
1056
1057         spin_lock(&mle->spinlock);
1058         m = mle->master;
1059         map_changed = (memcmp(mle->vote_map, mle->node_map,
1060                               sizeof(mle->vote_map)) != 0);
1061         voting_done = (memcmp(mle->vote_map, mle->response_map,
1062                              sizeof(mle->vote_map)) == 0);
1063
1064         /* restart if we hit any errors */
1065         if (map_changed) {
1066                 int b;
1067                 mlog(0, "%s: %.*s: node map changed, restarting\n",
1068                      dlm->name, res->lockname.len, res->lockname.name);
1069                 ret = dlm_restart_lock_mastery(dlm, res, mle, *blocked);
1070                 b = (mle->type == DLM_MLE_BLOCK);
1071                 if ((*blocked && !b) || (!*blocked && b)) {
1072                         mlog(0, "%s:%.*s: status change: old=%d new=%d\n",
1073                              dlm->name, res->lockname.len, res->lockname.name,
1074                              *blocked, b);
1075                         *blocked = b;
1076                 }
1077                 spin_unlock(&mle->spinlock);
1078                 if (ret < 0) {
1079                         mlog_errno(ret);
1080                         goto leave;
1081                 }
1082                 mlog(0, "%s:%.*s: restart lock mastery succeeded, "
1083                      "rechecking now\n", dlm->name, res->lockname.len,
1084                      res->lockname.name);
1085                 goto recheck;
1086         } else {
1087                 if (!voting_done) {
1088                         mlog(0, "map not changed and voting not done "
1089                              "for %s:%.*s\n", dlm->name, res->lockname.len,
1090                              res->lockname.name);
1091                 }
1092         }
1093
1094         if (m != O2NM_MAX_NODES) {
1095                 /* another node has done an assert!
1096                  * all done! */
1097                 sleep = 0;
1098         } else {
1099                 sleep = 1;
1100                 /* have all nodes responded? */
1101                 if (voting_done && !*blocked) {
1102                         bit = find_next_bit(mle->maybe_map, O2NM_MAX_NODES, 0);
1103                         if (dlm->node_num <= bit) {
1104                                 /* my node number is lowest.
1105                                  * now tell other nodes that I am
1106                                  * mastering this. */
1107                                 mle->master = dlm->node_num;
1108                                 /* ref was grabbed in get_lock_resource
1109                                  * will be dropped in dlmlock_master */
1110                                 assert = 1;
1111                                 sleep = 0;
1112                         }
1113                         /* if voting is done, but we have not received
1114                          * an assert master yet, we must sleep */
1115                 }
1116         }
1117
1118         spin_unlock(&mle->spinlock);
1119
1120         /* sleep if we haven't finished voting yet */
1121         if (sleep) {
1122                 unsigned long timeo = msecs_to_jiffies(DLM_MASTERY_TIMEOUT_MS);
1123
1124                 /*
1125                 if (atomic_read(&mle->mle_refs.refcount) < 2)
1126                         mlog(ML_ERROR, "mle (%p) refs=%d, name=%.*s\n", mle,
1127                         atomic_read(&mle->mle_refs.refcount),
1128                         res->lockname.len, res->lockname.name);
1129                 */
1130                 atomic_set(&mle->woken, 0);
1131                 (void)wait_event_timeout(mle->wq,
1132                                          (atomic_read(&mle->woken) == 1),
1133                                          timeo);
1134                 if (res->owner == O2NM_MAX_NODES) {
1135                         mlog(0, "%s:%.*s: waiting again\n", dlm->name,
1136                              res->lockname.len, res->lockname.name);
1137                         goto recheck;
1138                 }
1139                 mlog(0, "done waiting, master is %u\n", res->owner);
1140                 ret = 0;
1141                 goto leave;
1142         }
1143
1144         ret = 0;   /* done */
1145         if (assert) {
1146                 m = dlm->node_num;
1147                 mlog(0, "about to master %.*s here, this=%u\n",
1148                      res->lockname.len, res->lockname.name, m);
1149                 ret = dlm_do_assert_master(dlm, res, mle->vote_map, 0);
1150                 if (ret) {
1151                         /* This is a failure in the network path,
1152                          * not in the response to the assert_master
1153                          * (any nonzero response is a BUG on this node).
1154                          * Most likely a socket just got disconnected
1155                          * due to node death. */
1156                         mlog_errno(ret);
1157                 }
1158                 /* no longer need to restart lock mastery.
1159                  * all living nodes have been contacted. */
1160                 ret = 0;
1161         }
1162
1163         /* set the lockres owner */
1164         spin_lock(&res->spinlock);
1165         /* mastery reference obtained either during
1166          * assert_master_handler or in get_lock_resource */
1167         dlm_change_lockres_owner(dlm, res, m);
1168         spin_unlock(&res->spinlock);
1169
1170 leave:
1171         return ret;
1172 }
1173
1174 struct dlm_bitmap_diff_iter
1175 {
1176         int curnode;
1177         unsigned long *orig_bm;
1178         unsigned long *cur_bm;
1179         unsigned long diff_bm[BITS_TO_LONGS(O2NM_MAX_NODES)];
1180 };
1181
1182 enum dlm_node_state_change
1183 {
1184         NODE_DOWN = -1,
1185         NODE_NO_CHANGE = 0,
1186         NODE_UP
1187 };
1188
1189 static void dlm_bitmap_diff_iter_init(struct dlm_bitmap_diff_iter *iter,
1190                                       unsigned long *orig_bm,
1191                                       unsigned long *cur_bm)
1192 {
1193         unsigned long p1, p2;
1194         int i;
1195
1196         iter->curnode = -1;
1197         iter->orig_bm = orig_bm;
1198         iter->cur_bm = cur_bm;
1199
1200         for (i = 0; i < BITS_TO_LONGS(O2NM_MAX_NODES); i++) {
1201                 p1 = *(iter->orig_bm + i);
1202                 p2 = *(iter->cur_bm + i);
1203                 iter->diff_bm[i] = (p1 & ~p2) | (p2 & ~p1);
1204         }
1205 }
1206
1207 static int dlm_bitmap_diff_iter_next(struct dlm_bitmap_diff_iter *iter,
1208                                      enum dlm_node_state_change *state)
1209 {
1210         int bit;
1211
1212         if (iter->curnode >= O2NM_MAX_NODES)
1213                 return -ENOENT;
1214
1215         bit = find_next_bit(iter->diff_bm, O2NM_MAX_NODES,
1216                             iter->curnode+1);
1217         if (bit >= O2NM_MAX_NODES) {
1218                 iter->curnode = O2NM_MAX_NODES;
1219                 return -ENOENT;
1220         }
1221
1222         /* if it was there in the original then this node died */
1223         if (test_bit(bit, iter->orig_bm))
1224                 *state = NODE_DOWN;
1225         else
1226                 *state = NODE_UP;
1227
1228         iter->curnode = bit;
1229         return bit;
1230 }
1231
1232
1233 static int dlm_restart_lock_mastery(struct dlm_ctxt *dlm,
1234                                     struct dlm_lock_resource *res,
1235                                     struct dlm_master_list_entry *mle,
1236                                     int blocked)
1237 {
1238         struct dlm_bitmap_diff_iter bdi;
1239         enum dlm_node_state_change sc;
1240         int node;
1241         int ret = 0;
1242
1243         mlog(0, "something happened such that the "
1244              "master process may need to be restarted!\n");
1245
1246         assert_spin_locked(&mle->spinlock);
1247
1248         dlm_bitmap_diff_iter_init(&bdi, mle->vote_map, mle->node_map);
1249         node = dlm_bitmap_diff_iter_next(&bdi, &sc);
1250         while (node >= 0) {
1251                 if (sc == NODE_UP) {
1252                         /* a node came up.  clear any old vote from
1253                          * the response map and set it in the vote map
1254                          * then restart the mastery. */
1255                         mlog(ML_NOTICE, "node %d up while restarting\n", node);
1256
1257                         /* redo the master request, but only for the new node */
1258                         mlog(0, "sending request to new node\n");
1259                         clear_bit(node, mle->response_map);
1260                         set_bit(node, mle->vote_map);
1261                 } else {
1262                         mlog(ML_ERROR, "node down! %d\n", node);
1263                         if (blocked) {
1264                                 int lowest = find_next_bit(mle->maybe_map,
1265                                                        O2NM_MAX_NODES, 0);
1266
1267                                 /* act like it was never there */
1268                                 clear_bit(node, mle->maybe_map);
1269
1270                                 if (node == lowest) {
1271                                         mlog(0, "expected master %u died"
1272                                             " while this node was blocked "
1273                                             "waiting on it!\n", node);
1274                                         lowest = find_next_bit(mle->maybe_map,
1275                                                         O2NM_MAX_NODES,
1276                                                         lowest+1);
1277                                         if (lowest < O2NM_MAX_NODES) {
1278                                                 mlog(0, "%s:%.*s:still "
1279                                                      "blocked. waiting on %u "
1280                                                      "now\n", dlm->name,
1281                                                      res->lockname.len,
1282                                                      res->lockname.name,
1283                                                      lowest);
1284                                         } else {
1285                                                 /* mle is an MLE_BLOCK, but
1286                                                  * there is now nothing left to
1287                                                  * block on.  we need to return
1288                                                  * all the way back out and try
1289                                                  * again with an MLE_MASTER.
1290                                                  * dlm_do_local_recovery_cleanup
1291                                                  * has already run, so the mle
1292                                                  * refcount is ok */
1293                                                 mlog(0, "%s:%.*s: no "
1294                                                      "longer blocking. try to "
1295                                                      "master this here\n",
1296                                                      dlm->name,
1297                                                      res->lockname.len,
1298                                                      res->lockname.name);
1299                                                 mle->type = DLM_MLE_MASTER;
1300                                                 mle->mleres = res;
1301                                         }
1302                                 }
1303                         }
1304
1305                         /* now blank out everything, as if we had never
1306                          * contacted anyone */
1307                         memset(mle->maybe_map, 0, sizeof(mle->maybe_map));
1308                         memset(mle->response_map, 0, sizeof(mle->response_map));
1309                         /* reset the vote_map to the current node_map */
1310                         memcpy(mle->vote_map, mle->node_map,
1311                                sizeof(mle->node_map));
1312                         /* put myself into the maybe map */
1313                         if (mle->type != DLM_MLE_BLOCK)
1314                                 set_bit(dlm->node_num, mle->maybe_map);
1315                 }
1316                 ret = -EAGAIN;
1317                 node = dlm_bitmap_diff_iter_next(&bdi, &sc);
1318         }
1319         return ret;
1320 }
1321
1322
1323 /*
1324  * DLM_MASTER_REQUEST_MSG
1325  *
1326  * returns: 0 on success,
1327  *          -errno on a network error
1328  *
1329  * on error, the caller should assume the target node is "dead"
1330  *
1331  */
1332
1333 static int dlm_do_master_request(struct dlm_lock_resource *res,
1334                                  struct dlm_master_list_entry *mle, int to)
1335 {
1336         struct dlm_ctxt *dlm = mle->dlm;
1337         struct dlm_master_request request;
1338         int ret, response=0, resend;
1339
1340         memset(&request, 0, sizeof(request));
1341         request.node_idx = dlm->node_num;
1342
1343         BUG_ON(mle->type == DLM_MLE_MIGRATION);
1344
1345         request.namelen = (u8)mle->mnamelen;
1346         memcpy(request.name, mle->mname, request.namelen);
1347
1348 again:
1349         ret = o2net_send_message(DLM_MASTER_REQUEST_MSG, dlm->key, &request,
1350                                  sizeof(request), to, &response);
1351         if (ret < 0)  {
1352                 if (ret == -ESRCH) {
1353                         /* should never happen */
1354                         mlog(ML_ERROR, "TCP stack not ready!\n");
1355                         BUG();
1356                 } else if (ret == -EINVAL) {
1357                         mlog(ML_ERROR, "bad args passed to o2net!\n");
1358                         BUG();
1359                 } else if (ret == -ENOMEM) {
1360                         mlog(ML_ERROR, "out of memory while trying to send "
1361                              "network message!  retrying\n");
1362                         /* this is totally crude */
1363                         msleep(50);
1364                         goto again;
1365                 } else if (!dlm_is_host_down(ret)) {
1366                         /* not a network error. bad. */
1367                         mlog_errno(ret);
1368                         mlog(ML_ERROR, "unhandled error!");
1369                         BUG();
1370                 }
1371                 /* all other errors should be network errors,
1372                  * and likely indicate node death */
1373                 mlog(ML_ERROR, "link to %d went down!\n", to);
1374                 goto out;
1375         }
1376
1377         ret = 0;
1378         resend = 0;
1379         spin_lock(&mle->spinlock);
1380         switch (response) {
1381                 case DLM_MASTER_RESP_YES:
1382                         set_bit(to, mle->response_map);
1383                         mlog(0, "node %u is the master, response=YES\n", to);
1384                         mlog(0, "%s:%.*s: master node %u now knows I have a "
1385                              "reference\n", dlm->name, res->lockname.len,
1386                              res->lockname.name, to);
1387                         mle->master = to;
1388                         break;
1389                 case DLM_MASTER_RESP_NO:
1390                         mlog(0, "node %u not master, response=NO\n", to);
1391                         set_bit(to, mle->response_map);
1392                         break;
1393                 case DLM_MASTER_RESP_MAYBE:
1394                         mlog(0, "node %u not master, response=MAYBE\n", to);
1395                         set_bit(to, mle->response_map);
1396                         set_bit(to, mle->maybe_map);
1397                         break;
1398                 case DLM_MASTER_RESP_ERROR:
1399                         mlog(0, "node %u hit an error, resending\n", to);
1400                         resend = 1;
1401                         response = 0;
1402                         break;
1403                 default:
1404                         mlog(ML_ERROR, "bad response! %u\n", response);
1405                         BUG();
1406         }
1407         spin_unlock(&mle->spinlock);
1408         if (resend) {
1409                 /* this is also totally crude */
1410                 msleep(50);
1411                 goto again;
1412         }
1413
1414 out:
1415         return ret;
1416 }
1417
1418 /*
1419  * locks that can be taken here:
1420  * dlm->spinlock
1421  * res->spinlock
1422  * mle->spinlock
1423  * dlm->master_list
1424  *
1425  * if possible, TRIM THIS DOWN!!!
1426  */
1427 int dlm_master_request_handler(struct o2net_msg *msg, u32 len, void *data,
1428                                void **ret_data)
1429 {
1430         u8 response = DLM_MASTER_RESP_MAYBE;
1431         struct dlm_ctxt *dlm = data;
1432         struct dlm_lock_resource *res = NULL;
1433         struct dlm_master_request *request = (struct dlm_master_request *) msg->buf;
1434         struct dlm_master_list_entry *mle = NULL, *tmpmle = NULL;
1435         char *name;
1436         unsigned int namelen, hash;
1437         int found, ret;
1438         int set_maybe;
1439         int dispatch_assert = 0;
1440
1441         if (!dlm_grab(dlm))
1442                 return DLM_MASTER_RESP_NO;
1443
1444         if (!dlm_domain_fully_joined(dlm)) {
1445                 response = DLM_MASTER_RESP_NO;
1446                 goto send_response;
1447         }
1448
1449         name = request->name;
1450         namelen = request->namelen;
1451         hash = dlm_lockid_hash(name, namelen);
1452
1453         if (namelen > DLM_LOCKID_NAME_MAX) {
1454                 response = DLM_IVBUFLEN;
1455                 goto send_response;
1456         }
1457
1458 way_up_top:
1459         spin_lock(&dlm->spinlock);
1460         res = __dlm_lookup_lockres(dlm, name, namelen, hash);
1461         if (res) {
1462                 spin_unlock(&dlm->spinlock);
1463
1464                 /* take care of the easy cases up front */
1465                 spin_lock(&res->spinlock);
1466                 if (res->state & (DLM_LOCK_RES_RECOVERING|
1467                                   DLM_LOCK_RES_MIGRATING)) {
1468                         spin_unlock(&res->spinlock);
1469                         mlog(0, "returning DLM_MASTER_RESP_ERROR since res is "
1470                              "being recovered/migrated\n");
1471                         response = DLM_MASTER_RESP_ERROR;
1472                         if (mle)
1473                                 kmem_cache_free(dlm_mle_cache, mle);
1474                         goto send_response;
1475                 }
1476
1477                 if (res->owner == dlm->node_num) {
1478                         dlm_lockres_set_refmap_bit(dlm, res, request->node_idx);
1479                         spin_unlock(&res->spinlock);
1480                         response = DLM_MASTER_RESP_YES;
1481                         if (mle)
1482                                 kmem_cache_free(dlm_mle_cache, mle);
1483
1484                         /* this node is the owner.
1485                          * there is some extra work that needs to
1486                          * happen now.  the requesting node has
1487                          * caused all nodes up to this one to
1488                          * create mles.  this node now needs to
1489                          * go back and clean those up. */
1490                         dispatch_assert = 1;
1491                         goto send_response;
1492                 } else if (res->owner != DLM_LOCK_RES_OWNER_UNKNOWN) {
1493                         spin_unlock(&res->spinlock);
1494                         // mlog(0, "node %u is the master\n", res->owner);
1495                         response = DLM_MASTER_RESP_NO;
1496                         if (mle)
1497                                 kmem_cache_free(dlm_mle_cache, mle);
1498                         goto send_response;
1499                 }
1500
1501                 /* ok, there is no owner.  either this node is
1502                  * being blocked, or it is actively trying to
1503                  * master this lock. */
1504                 if (!(res->state & DLM_LOCK_RES_IN_PROGRESS)) {
1505                         mlog(ML_ERROR, "lock with no owner should be "
1506                              "in-progress!\n");
1507                         BUG();
1508                 }
1509
1510                 // mlog(0, "lockres is in progress...\n");
1511                 spin_lock(&dlm->master_lock);
1512                 found = dlm_find_mle(dlm, &tmpmle, name, namelen);
1513                 if (!found) {
1514                         mlog(ML_ERROR, "no mle found for this lock!\n");
1515                         BUG();
1516                 }
1517                 set_maybe = 1;
1518                 spin_lock(&tmpmle->spinlock);
1519                 if (tmpmle->type == DLM_MLE_BLOCK) {
1520                         // mlog(0, "this node is waiting for "
1521                         // "lockres to be mastered\n");
1522                         response = DLM_MASTER_RESP_NO;
1523                 } else if (tmpmle->type == DLM_MLE_MIGRATION) {
1524                         mlog(0, "node %u is master, but trying to migrate to "
1525                              "node %u.\n", tmpmle->master, tmpmle->new_master);
1526                         if (tmpmle->master == dlm->node_num) {
1527                                 mlog(ML_ERROR, "no owner on lockres, but this "
1528                                      "node is trying to migrate it to %u?!\n",
1529                                      tmpmle->new_master);
1530                                 BUG();
1531                         } else {
1532                                 /* the real master can respond on its own */
1533                                 response = DLM_MASTER_RESP_NO;
1534                         }
1535                 } else if (tmpmle->master != DLM_LOCK_RES_OWNER_UNKNOWN) {
1536                         set_maybe = 0;
1537                         if (tmpmle->master == dlm->node_num) {
1538                                 response = DLM_MASTER_RESP_YES;
1539                                 /* this node will be the owner.
1540                                  * go back and clean the mles on any
1541                                  * other nodes */
1542                                 dispatch_assert = 1;
1543                                 dlm_lockres_set_refmap_bit(dlm, res,
1544                                                            request->node_idx);
1545                         } else
1546                                 response = DLM_MASTER_RESP_NO;
1547                 } else {
1548                         // mlog(0, "this node is attempting to "
1549                         // "master lockres\n");
1550                         response = DLM_MASTER_RESP_MAYBE;
1551                 }
1552                 if (set_maybe)
1553                         set_bit(request->node_idx, tmpmle->maybe_map);
1554                 spin_unlock(&tmpmle->spinlock);
1555
1556                 spin_unlock(&dlm->master_lock);
1557                 spin_unlock(&res->spinlock);
1558
1559                 /* keep the mle attached to heartbeat events */
1560                 dlm_put_mle(tmpmle);
1561                 if (mle)
1562                         kmem_cache_free(dlm_mle_cache, mle);
1563                 goto send_response;
1564         }
1565
1566         /*
1567          * lockres doesn't exist on this node
1568          * if there is an MLE_BLOCK, return NO
1569          * if there is an MLE_MASTER, return MAYBE
1570          * otherwise, add an MLE_BLOCK, return NO
1571          */
1572         spin_lock(&dlm->master_lock);
1573         found = dlm_find_mle(dlm, &tmpmle, name, namelen);
1574         if (!found) {
1575                 /* this lockid has never been seen on this node yet */
1576                 // mlog(0, "no mle found\n");
1577                 if (!mle) {
1578                         spin_unlock(&dlm->master_lock);
1579                         spin_unlock(&dlm->spinlock);
1580
1581                         mle = kmem_cache_alloc(dlm_mle_cache, GFP_NOFS);
1582                         if (!mle) {
1583                                 response = DLM_MASTER_RESP_ERROR;
1584                                 mlog_errno(-ENOMEM);
1585                                 goto send_response;
1586                         }
1587                         goto way_up_top;
1588                 }
1589
1590                 // mlog(0, "this is second time thru, already allocated, "
1591                 // "add the block.\n");
1592                 dlm_init_mle(mle, DLM_MLE_BLOCK, dlm, NULL, name, namelen);
1593                 set_bit(request->node_idx, mle->maybe_map);
1594                 __dlm_insert_mle(dlm, mle);
1595                 response = DLM_MASTER_RESP_NO;
1596         } else {
1597                 // mlog(0, "mle was found\n");
1598                 set_maybe = 1;
1599                 spin_lock(&tmpmle->spinlock);
1600                 if (tmpmle->master == dlm->node_num) {
1601                         mlog(ML_ERROR, "no lockres, but an mle with this node as master!\n");
1602                         BUG();
1603                 }
1604                 if (tmpmle->type == DLM_MLE_BLOCK)
1605                         response = DLM_MASTER_RESP_NO;
1606                 else if (tmpmle->type == DLM_MLE_MIGRATION) {
1607                         mlog(0, "migration mle was found (%u->%u)\n",
1608                              tmpmle->master, tmpmle->new_master);
1609                         /* real master can respond on its own */
1610                         response = DLM_MASTER_RESP_NO;
1611                 } else
1612                         response = DLM_MASTER_RESP_MAYBE;
1613                 if (set_maybe)
1614                         set_bit(request->node_idx, tmpmle->maybe_map);
1615                 spin_unlock(&tmpmle->spinlock);
1616         }
1617         spin_unlock(&dlm->master_lock);
1618         spin_unlock(&dlm->spinlock);
1619
1620         if (found) {
1621                 /* keep the mle attached to heartbeat events */
1622                 dlm_put_mle(tmpmle);
1623         }
1624 send_response:
1625         /*
1626          * __dlm_lookup_lockres() grabbed a reference to this lockres.
1627          * The reference is released by dlm_assert_master_worker() under
1628          * the call to dlm_dispatch_assert_master().  If
1629          * dlm_assert_master_worker() isn't called, we drop it here.
1630          */
1631         if (dispatch_assert) {
1632                 if (response != DLM_MASTER_RESP_YES)
1633                         mlog(ML_ERROR, "invalid response %d\n", response);
1634                 if (!res) {
1635                         mlog(ML_ERROR, "bad lockres while trying to assert!\n");
1636                         BUG();
1637                 }
1638                 mlog(0, "%u is the owner of %.*s, cleaning everyone else\n",
1639                              dlm->node_num, res->lockname.len, res->lockname.name);
1640                 ret = dlm_dispatch_assert_master(dlm, res, 0, request->node_idx,
1641                                                  DLM_ASSERT_MASTER_MLE_CLEANUP);
1642                 if (ret < 0) {
1643                         mlog(ML_ERROR, "failed to dispatch assert master work\n");
1644                         response = DLM_MASTER_RESP_ERROR;
1645                         dlm_lockres_put(res);
1646                 } else
1647                         dlm_lockres_grab_inflight_worker(dlm, res);
1648         } else {
1649                 if (res)
1650                         dlm_lockres_put(res);
1651         }
1652
1653         dlm_put(dlm);
1654         return response;
1655 }
1656
1657 /*
1658  * DLM_ASSERT_MASTER_MSG
1659  */
1660
1661
1662 /*
1663  * NOTE: this can be used for debugging
1664  * can periodically run all locks owned by this node
1665  * and re-assert across the cluster...
1666  */
1667 static int dlm_do_assert_master(struct dlm_ctxt *dlm,
1668                                 struct dlm_lock_resource *res,
1669                                 void *nodemap, u32 flags)
1670 {
1671         struct dlm_assert_master assert;
1672         int to, tmpret;
1673         struct dlm_node_iter iter;
1674         int ret = 0;
1675         int reassert;
1676         const char *lockname = res->lockname.name;
1677         unsigned int namelen = res->lockname.len;
1678
1679         BUG_ON(namelen > O2NM_MAX_NAME_LEN);
1680
1681         spin_lock(&res->spinlock);
1682         res->state |= DLM_LOCK_RES_SETREF_INPROG;
1683         spin_unlock(&res->spinlock);
1684
1685 again:
1686         reassert = 0;
1687
1688         /* note that if this nodemap is empty, it returns 0 */
1689         dlm_node_iter_init(nodemap, &iter);
1690         while ((to = dlm_node_iter_next(&iter)) >= 0) {
1691                 int r = 0;
1692                 struct dlm_master_list_entry *mle = NULL;
1693
1694                 mlog(0, "sending assert master to %d (%.*s)\n", to,
1695                      namelen, lockname);
1696                 memset(&assert, 0, sizeof(assert));
1697                 assert.node_idx = dlm->node_num;
1698                 assert.namelen = namelen;
1699                 memcpy(assert.name, lockname, namelen);
1700                 assert.flags = cpu_to_be32(flags);
1701
1702                 tmpret = o2net_send_message(DLM_ASSERT_MASTER_MSG, dlm->key,
1703                                             &assert, sizeof(assert), to, &r);
1704                 if (tmpret < 0) {
1705                         mlog(ML_ERROR, "Error %d when sending message %u (key "
1706                              "0x%x) to node %u\n", tmpret,
1707                              DLM_ASSERT_MASTER_MSG, dlm->key, to);
1708                         if (!dlm_is_host_down(tmpret)) {
1709                                 mlog(ML_ERROR, "unhandled error=%d!\n", tmpret);
1710                                 BUG();
1711                         }
1712                         /* a node died.  finish out the rest of the nodes. */
1713                         mlog(0, "link to %d went down!\n", to);
1714                         /* any nonzero status return will do */
1715                         ret = tmpret;
1716                         r = 0;
1717                 } else if (r < 0) {
1718                         /* ok, something horribly messed.  kill thyself. */
1719                         mlog(ML_ERROR,"during assert master of %.*s to %u, "
1720                              "got %d.\n", namelen, lockname, to, r);
1721                         spin_lock(&dlm->spinlock);
1722                         spin_lock(&dlm->master_lock);
1723                         if (dlm_find_mle(dlm, &mle, (char *)lockname,
1724                                          namelen)) {
1725                                 dlm_print_one_mle(mle);
1726                                 __dlm_put_mle(mle);
1727                         }
1728                         spin_unlock(&dlm->master_lock);
1729                         spin_unlock(&dlm->spinlock);
1730                         BUG();
1731                 }
1732
1733                 if (r & DLM_ASSERT_RESPONSE_REASSERT &&
1734                     !(r & DLM_ASSERT_RESPONSE_MASTERY_REF)) {
1735                                 mlog(ML_ERROR, "%.*s: very strange, "
1736                                      "master MLE but no lockres on %u\n",
1737                                      namelen, lockname, to);
1738                 }
1739
1740                 if (r & DLM_ASSERT_RESPONSE_REASSERT) {
1741                         mlog(0, "%.*s: node %u create mles on other "
1742                              "nodes and requests a re-assert\n",
1743                              namelen, lockname, to);
1744                         reassert = 1;
1745                 }
1746                 if (r & DLM_ASSERT_RESPONSE_MASTERY_REF) {
1747                         mlog(0, "%.*s: node %u has a reference to this "
1748                              "lockres, set the bit in the refmap\n",
1749                              namelen, lockname, to);
1750                         spin_lock(&res->spinlock);
1751                         dlm_lockres_set_refmap_bit(dlm, res, to);
1752                         spin_unlock(&res->spinlock);
1753                 }
1754         }
1755
1756         if (reassert)
1757                 goto again;
1758
1759         spin_lock(&res->spinlock);
1760         res->state &= ~DLM_LOCK_RES_SETREF_INPROG;
1761         spin_unlock(&res->spinlock);
1762         wake_up(&res->wq);
1763
1764         return ret;
1765 }
1766
1767 /*
1768  * locks that can be taken here:
1769  * dlm->spinlock
1770  * res->spinlock
1771  * mle->spinlock
1772  * dlm->master_list
1773  *
1774  * if possible, TRIM THIS DOWN!!!
1775  */
1776 int dlm_assert_master_handler(struct o2net_msg *msg, u32 len, void *data,
1777                               void **ret_data)
1778 {
1779         struct dlm_ctxt *dlm = data;
1780         struct dlm_master_list_entry *mle = NULL;
1781         struct dlm_assert_master *assert = (struct dlm_assert_master *)msg->buf;
1782         struct dlm_lock_resource *res = NULL;
1783         char *name;
1784         unsigned int namelen, hash;
1785         u32 flags;
1786         int master_request = 0, have_lockres_ref = 0;
1787         int ret = 0;
1788
1789         if (!dlm_grab(dlm))
1790                 return 0;
1791
1792         name = assert->name;
1793         namelen = assert->namelen;
1794         hash = dlm_lockid_hash(name, namelen);
1795         flags = be32_to_cpu(assert->flags);
1796
1797         if (namelen > DLM_LOCKID_NAME_MAX) {
1798                 mlog(ML_ERROR, "Invalid name length!");
1799                 goto done;
1800         }
1801
1802         spin_lock(&dlm->spinlock);
1803
1804         if (flags)
1805                 mlog(0, "assert_master with flags: %u\n", flags);
1806
1807         /* find the MLE */
1808         spin_lock(&dlm->master_lock);
1809         if (!dlm_find_mle(dlm, &mle, name, namelen)) {
1810                 /* not an error, could be master just re-asserting */
1811                 mlog(0, "just got an assert_master from %u, but no "
1812                      "MLE for it! (%.*s)\n", assert->node_idx,
1813                      namelen, name);
1814         } else {
1815                 int bit = find_next_bit (mle->maybe_map, O2NM_MAX_NODES, 0);
1816                 if (bit >= O2NM_MAX_NODES) {
1817                         /* not necessarily an error, though less likely.
1818                          * could be master just re-asserting. */
1819                         mlog(0, "no bits set in the maybe_map, but %u "
1820                              "is asserting! (%.*s)\n", assert->node_idx,
1821                              namelen, name);
1822                 } else if (bit != assert->node_idx) {
1823                         if (flags & DLM_ASSERT_MASTER_MLE_CLEANUP) {
1824                                 mlog(0, "master %u was found, %u should "
1825                                      "back off\n", assert->node_idx, bit);
1826                         } else {
1827                                 /* with the fix for bug 569, a higher node
1828                                  * number winning the mastery will respond
1829                                  * YES to mastery requests, but this node
1830                                  * had no way of knowing.  let it pass. */
1831                                 mlog(0, "%u is the lowest node, "
1832                                      "%u is asserting. (%.*s)  %u must "
1833                                      "have begun after %u won.\n", bit,
1834                                      assert->node_idx, namelen, name, bit,
1835                                      assert->node_idx);
1836                         }
1837                 }
1838                 if (mle->type == DLM_MLE_MIGRATION) {
1839                         if (flags & DLM_ASSERT_MASTER_MLE_CLEANUP) {
1840                                 mlog(0, "%s:%.*s: got cleanup assert"
1841                                      " from %u for migration\n",
1842                                      dlm->name, namelen, name,
1843                                      assert->node_idx);
1844                         } else if (!(flags & DLM_ASSERT_MASTER_FINISH_MIGRATION)) {
1845                                 mlog(0, "%s:%.*s: got unrelated assert"
1846                                      " from %u for migration, ignoring\n",
1847                                      dlm->name, namelen, name,
1848                                      assert->node_idx);
1849                                 __dlm_put_mle(mle);
1850                                 spin_unlock(&dlm->master_lock);
1851                                 spin_unlock(&dlm->spinlock);
1852                                 goto done;
1853                         }
1854                 }
1855         }
1856         spin_unlock(&dlm->master_lock);
1857
1858         /* ok everything checks out with the MLE
1859          * now check to see if there is a lockres */
1860         res = __dlm_lookup_lockres(dlm, name, namelen, hash);
1861         if (res) {
1862                 spin_lock(&res->spinlock);
1863                 if (res->state & DLM_LOCK_RES_RECOVERING)  {
1864                         mlog(ML_ERROR, "%u asserting but %.*s is "
1865                              "RECOVERING!\n", assert->node_idx, namelen, name);
1866                         goto kill;
1867                 }
1868                 if (!mle) {
1869                         if (res->owner != DLM_LOCK_RES_OWNER_UNKNOWN &&
1870                             res->owner != assert->node_idx) {
1871                                 mlog(ML_ERROR, "DIE! Mastery assert from %u, "
1872                                      "but current owner is %u! (%.*s)\n",
1873                                      assert->node_idx, res->owner, namelen,
1874                                      name);
1875                                 __dlm_print_one_lock_resource(res);
1876                                 BUG();
1877                         }
1878                 } else if (mle->type != DLM_MLE_MIGRATION) {
1879                         if (res->owner != DLM_LOCK_RES_OWNER_UNKNOWN) {
1880                                 /* owner is just re-asserting */
1881                                 if (res->owner == assert->node_idx) {
1882                                         mlog(0, "owner %u re-asserting on "
1883                                              "lock %.*s\n", assert->node_idx,
1884                                              namelen, name);
1885                                         goto ok;
1886                                 }
1887                                 mlog(ML_ERROR, "got assert_master from "
1888                                      "node %u, but %u is the owner! "
1889                                      "(%.*s)\n", assert->node_idx,
1890                                      res->owner, namelen, name);
1891                                 goto kill;
1892                         }
1893                         if (!(res->state & DLM_LOCK_RES_IN_PROGRESS)) {
1894                                 mlog(ML_ERROR, "got assert from %u, but lock "
1895                                      "with no owner should be "
1896                                      "in-progress! (%.*s)\n",
1897                                      assert->node_idx,
1898                                      namelen, name);
1899                                 goto kill;
1900                         }
1901                 } else /* mle->type == DLM_MLE_MIGRATION */ {
1902                         /* should only be getting an assert from new master */
1903                         if (assert->node_idx != mle->new_master) {
1904                                 mlog(ML_ERROR, "got assert from %u, but "
1905                                      "new master is %u, and old master "
1906                                      "was %u (%.*s)\n",
1907                                      assert->node_idx, mle->new_master,
1908                                      mle->master, namelen, name);
1909                                 goto kill;
1910                         }
1911
1912                 }
1913 ok:
1914                 spin_unlock(&res->spinlock);
1915         }
1916
1917         // mlog(0, "woo!  got an assert_master from node %u!\n",
1918         //           assert->node_idx);
1919         if (mle) {
1920                 int extra_ref = 0;
1921                 int nn = -1;
1922                 int rr, err = 0;
1923
1924                 spin_lock(&mle->spinlock);
1925                 if (mle->type == DLM_MLE_BLOCK || mle->type == DLM_MLE_MIGRATION)
1926                         extra_ref = 1;
1927                 else {
1928                         /* MASTER mle: if any bits set in the response map
1929                          * then the calling node needs to re-assert to clear
1930                          * up nodes that this node contacted */
1931                         while ((nn = find_next_bit (mle->response_map, O2NM_MAX_NODES,
1932                                                     nn+1)) < O2NM_MAX_NODES) {
1933                                 if (nn != dlm->node_num && nn != assert->node_idx) {
1934                                         master_request = 1;
1935                                         break;
1936                                 }
1937                         }
1938                 }
1939                 mle->master = assert->node_idx;
1940                 atomic_set(&mle->woken, 1);
1941                 wake_up(&mle->wq);
1942                 spin_unlock(&mle->spinlock);
1943
1944                 if (res) {
1945                         int wake = 0;
1946                         spin_lock(&res->spinlock);
1947                         if (mle->type == DLM_MLE_MIGRATION) {
1948                                 mlog(0, "finishing off migration of lockres %.*s, "
1949                                         "from %u to %u\n",
1950                                         res->lockname.len, res->lockname.name,
1951                                         dlm->node_num, mle->new_master);
1952                                 res->state &= ~DLM_LOCK_RES_MIGRATING;
1953                                 wake = 1;
1954                                 dlm_change_lockres_owner(dlm, res, mle->new_master);
1955                                 BUG_ON(res->state & DLM_LOCK_RES_DIRTY);
1956                         } else {
1957                                 dlm_change_lockres_owner(dlm, res, mle->master);
1958                         }
1959                         spin_unlock(&res->spinlock);
1960                         have_lockres_ref = 1;
1961                         if (wake)
1962                                 wake_up(&res->wq);
1963                 }
1964
1965                 /* master is known, detach if not already detached.
1966                  * ensures that only one assert_master call will happen
1967                  * on this mle. */
1968                 spin_lock(&dlm->master_lock);
1969
1970                 rr = atomic_read(&mle->mle_refs.refcount);
1971                 if (mle->inuse > 0) {
1972                         if (extra_ref && rr < 3)
1973                                 err = 1;
1974                         else if (!extra_ref && rr < 2)
1975                                 err = 1;
1976                 } else {
1977                         if (extra_ref && rr < 2)
1978                                 err = 1;
1979                         else if (!extra_ref && rr < 1)
1980                                 err = 1;
1981                 }
1982                 if (err) {
1983                         mlog(ML_ERROR, "%s:%.*s: got assert master from %u "
1984                              "that will mess up this node, refs=%d, extra=%d, "
1985                              "inuse=%d\n", dlm->name, namelen, name,
1986                              assert->node_idx, rr, extra_ref, mle->inuse);
1987                         dlm_print_one_mle(mle);
1988                 }
1989                 __dlm_unlink_mle(dlm, mle);
1990                 __dlm_mle_detach_hb_events(dlm, mle);
1991                 __dlm_put_mle(mle);
1992                 if (extra_ref) {
1993                         /* the assert master message now balances the extra
1994                          * ref given by the master / migration request message.
1995                          * if this is the last put, it will be removed
1996                          * from the list. */
1997                         __dlm_put_mle(mle);
1998                 }
1999                 spin_unlock(&dlm->master_lock);
2000         } else if (res) {
2001                 if (res->owner != assert->node_idx) {
2002                         mlog(0, "assert_master from %u, but current "
2003                              "owner is %u (%.*s), no mle\n", assert->node_idx,
2004                              res->owner, namelen, name);
2005                 }
2006         }
2007         spin_unlock(&dlm->spinlock);
2008
2009 done:
2010         ret = 0;
2011         if (res) {
2012                 spin_lock(&res->spinlock);
2013                 res->state |= DLM_LOCK_RES_SETREF_INPROG;
2014                 spin_unlock(&res->spinlock);
2015                 *ret_data = (void *)res;
2016         }
2017         dlm_put(dlm);
2018         if (master_request) {
2019                 mlog(0, "need to tell master to reassert\n");
2020                 /* positive. negative would shoot down the node. */
2021                 ret |= DLM_ASSERT_RESPONSE_REASSERT;
2022                 if (!have_lockres_ref) {
2023                         mlog(ML_ERROR, "strange, got assert from %u, MASTER "
2024                              "mle present here for %s:%.*s, but no lockres!\n",
2025                              assert->node_idx, dlm->name, namelen, name);
2026                 }
2027         }
2028         if (have_lockres_ref) {
2029                 /* let the master know we have a reference to the lockres */
2030                 ret |= DLM_ASSERT_RESPONSE_MASTERY_REF;
2031                 mlog(0, "%s:%.*s: got assert from %u, need a ref\n",
2032                      dlm->name, namelen, name, assert->node_idx);
2033         }
2034         return ret;
2035
2036 kill:
2037         /* kill the caller! */
2038         mlog(ML_ERROR, "Bad message received from another node.  Dumping state "
2039              "and killing the other node now!  This node is OK and can continue.\n");
2040         __dlm_print_one_lock_resource(res);
2041         spin_unlock(&res->spinlock);
2042         spin_unlock(&dlm->spinlock);
2043         *ret_data = (void *)res;
2044         dlm_put(dlm);
2045         return -EINVAL;
2046 }
2047
2048 void dlm_assert_master_post_handler(int status, void *data, void *ret_data)
2049 {
2050         struct dlm_lock_resource *res = (struct dlm_lock_resource *)ret_data;
2051
2052         if (ret_data) {
2053                 spin_lock(&res->spinlock);
2054                 res->state &= ~DLM_LOCK_RES_SETREF_INPROG;
2055                 spin_unlock(&res->spinlock);
2056                 wake_up(&res->wq);
2057                 dlm_lockres_put(res);
2058         }
2059         return;
2060 }
2061
2062 int dlm_dispatch_assert_master(struct dlm_ctxt *dlm,
2063                                struct dlm_lock_resource *res,
2064                                int ignore_higher, u8 request_from, u32 flags)
2065 {
2066         struct dlm_work_item *item;
2067         item = kzalloc(sizeof(*item), GFP_ATOMIC);
2068         if (!item)
2069                 return -ENOMEM;
2070
2071
2072         /* queue up work for dlm_assert_master_worker */
2073         dlm_grab(dlm);  /* get an extra ref for the work item */
2074         dlm_init_work_item(dlm, item, dlm_assert_master_worker, NULL);
2075         item->u.am.lockres = res; /* already have a ref */
2076         /* can optionally ignore node numbers higher than this node */
2077         item->u.am.ignore_higher = ignore_higher;
2078         item->u.am.request_from = request_from;
2079         item->u.am.flags = flags;
2080
2081         if (ignore_higher)
2082                 mlog(0, "IGNORE HIGHER: %.*s\n", res->lockname.len,
2083                      res->lockname.name);
2084
2085         spin_lock(&dlm->work_lock);
2086         list_add_tail(&item->list, &dlm->work_list);
2087         spin_unlock(&dlm->work_lock);
2088
2089         queue_work(dlm->dlm_worker, &dlm->dispatched_work);
2090         return 0;
2091 }
2092
2093 static void dlm_assert_master_worker(struct dlm_work_item *item, void *data)
2094 {
2095         struct dlm_ctxt *dlm = data;
2096         int ret = 0;
2097         struct dlm_lock_resource *res;
2098         unsigned long nodemap[BITS_TO_LONGS(O2NM_MAX_NODES)];
2099         int ignore_higher;
2100         int bit;
2101         u8 request_from;
2102         u32 flags;
2103
2104         dlm = item->dlm;
2105         res = item->u.am.lockres;
2106         ignore_higher = item->u.am.ignore_higher;
2107         request_from = item->u.am.request_from;
2108         flags = item->u.am.flags;
2109
2110         spin_lock(&dlm->spinlock);
2111         memcpy(nodemap, dlm->domain_map, sizeof(nodemap));
2112         spin_unlock(&dlm->spinlock);
2113
2114         clear_bit(dlm->node_num, nodemap);
2115         if (ignore_higher) {
2116                 /* if is this just to clear up mles for nodes below
2117                  * this node, do not send the message to the original
2118                  * caller or any node number higher than this */
2119                 clear_bit(request_from, nodemap);
2120                 bit = dlm->node_num;
2121                 while (1) {
2122                         bit = find_next_bit(nodemap, O2NM_MAX_NODES,
2123                                             bit+1);
2124                         if (bit >= O2NM_MAX_NODES)
2125                                 break;
2126                         clear_bit(bit, nodemap);
2127                 }
2128         }
2129
2130         /*
2131          * If we're migrating this lock to someone else, we are no
2132          * longer allowed to assert out own mastery.  OTOH, we need to
2133          * prevent migration from starting while we're still asserting
2134          * our dominance.  The reserved ast delays migration.
2135          */
2136         spin_lock(&res->spinlock);
2137         if (res->state & DLM_LOCK_RES_MIGRATING) {
2138                 mlog(0, "Someone asked us to assert mastery, but we're "
2139                      "in the middle of migration.  Skipping assert, "
2140                      "the new master will handle that.\n");
2141                 spin_unlock(&res->spinlock);
2142                 goto put;
2143         } else
2144                 __dlm_lockres_reserve_ast(res);
2145         spin_unlock(&res->spinlock);
2146
2147         /* this call now finishes out the nodemap
2148          * even if one or more nodes die */
2149         mlog(0, "worker about to master %.*s here, this=%u\n",
2150                      res->lockname.len, res->lockname.name, dlm->node_num);
2151         ret = dlm_do_assert_master(dlm, res, nodemap, flags);
2152         if (ret < 0) {
2153                 /* no need to restart, we are done */
2154                 if (!dlm_is_host_down(ret))
2155                         mlog_errno(ret);
2156         }
2157
2158         /* Ok, we've asserted ourselves.  Let's let migration start. */
2159         dlm_lockres_release_ast(dlm, res);
2160
2161 put:
2162         dlm_lockres_drop_inflight_worker(dlm, res);
2163
2164         dlm_lockres_put(res);
2165
2166         mlog(0, "finished with dlm_assert_master_worker\n");
2167 }
2168
2169 /* SPECIAL CASE for the $RECOVERY lock used by the recovery thread.
2170  * We cannot wait for node recovery to complete to begin mastering this
2171  * lockres because this lockres is used to kick off recovery! ;-)
2172  * So, do a pre-check on all living nodes to see if any of those nodes
2173  * think that $RECOVERY is currently mastered by a dead node.  If so,
2174  * we wait a short time to allow that node to get notified by its own
2175  * heartbeat stack, then check again.  All $RECOVERY lock resources
2176  * mastered by dead nodes are purged when the hearbeat callback is
2177  * fired, so we can know for sure that it is safe to continue once
2178  * the node returns a live node or no node.  */
2179 static int dlm_pre_master_reco_lockres(struct dlm_ctxt *dlm,
2180                                        struct dlm_lock_resource *res)
2181 {
2182         struct dlm_node_iter iter;
2183         int nodenum;
2184         int ret = 0;
2185         u8 master = DLM_LOCK_RES_OWNER_UNKNOWN;
2186
2187         spin_lock(&dlm->spinlock);
2188         dlm_node_iter_init(dlm->domain_map, &iter);
2189         spin_unlock(&dlm->spinlock);
2190
2191         while ((nodenum = dlm_node_iter_next(&iter)) >= 0) {
2192                 /* do not send to self */
2193                 if (nodenum == dlm->node_num)
2194                         continue;
2195                 ret = dlm_do_master_requery(dlm, res, nodenum, &master);
2196                 if (ret < 0) {
2197                         mlog_errno(ret);
2198                         if (!dlm_is_host_down(ret))
2199                                 BUG();
2200                         /* host is down, so answer for that node would be
2201                          * DLM_LOCK_RES_OWNER_UNKNOWN.  continue. */
2202                         ret = 0;
2203                 }
2204
2205                 if (master != DLM_LOCK_RES_OWNER_UNKNOWN) {
2206                         /* check to see if this master is in the recovery map */
2207                         spin_lock(&dlm->spinlock);
2208                         if (test_bit(master, dlm->recovery_map)) {
2209                                 mlog(ML_NOTICE, "%s: node %u has not seen "
2210                                      "node %u go down yet, and thinks the "
2211                                      "dead node is mastering the recovery "
2212                                      "lock.  must wait.\n", dlm->name,
2213                                      nodenum, master);
2214                                 ret = -EAGAIN;
2215                         }
2216                         spin_unlock(&dlm->spinlock);
2217                         mlog(0, "%s: reco lock master is %u\n", dlm->name,
2218                              master);
2219                         break;
2220                 }
2221         }
2222         return ret;
2223 }
2224
2225 /*
2226  * DLM_DEREF_LOCKRES_MSG
2227  */
2228
2229 int dlm_drop_lockres_ref(struct dlm_ctxt *dlm, struct dlm_lock_resource *res)
2230 {
2231         struct dlm_deref_lockres deref;
2232         int ret = 0, r;
2233         const char *lockname;
2234         unsigned int namelen;
2235
2236         lockname = res->lockname.name;
2237         namelen = res->lockname.len;
2238         BUG_ON(namelen > O2NM_MAX_NAME_LEN);
2239
2240         memset(&deref, 0, sizeof(deref));
2241         deref.node_idx = dlm->node_num;
2242         deref.namelen = namelen;
2243         memcpy(deref.name, lockname, namelen);
2244
2245         ret = o2net_send_message(DLM_DEREF_LOCKRES_MSG, dlm->key,
2246                                  &deref, sizeof(deref), res->owner, &r);
2247         if (ret < 0)
2248                 mlog(ML_ERROR, "%s: res %.*s, error %d send DEREF to node %u\n",
2249                      dlm->name, namelen, lockname, ret, res->owner);
2250         else if (r < 0) {
2251                 /* BAD.  other node says I did not have a ref. */
2252                 mlog(ML_ERROR, "%s: res %.*s, DEREF to node %u got %d\n",
2253                      dlm->name, namelen, lockname, res->owner, r);
2254                 dlm_print_one_lock_resource(res);
2255                 BUG();
2256         }
2257         return ret;
2258 }
2259
2260 int dlm_deref_lockres_handler(struct o2net_msg *msg, u32 len, void *data,
2261                               void **ret_data)
2262 {
2263         struct dlm_ctxt *dlm = data;
2264         struct dlm_deref_lockres *deref = (struct dlm_deref_lockres *)msg->buf;
2265         struct dlm_lock_resource *res = NULL;
2266         char *name;
2267         unsigned int namelen;
2268         int ret = -EINVAL;
2269         u8 node;
2270         unsigned int hash;
2271         struct dlm_work_item *item;
2272         int cleared = 0;
2273         int dispatch = 0;
2274
2275         if (!dlm_grab(dlm))
2276                 return 0;
2277
2278         name = deref->name;
2279         namelen = deref->namelen;
2280         node = deref->node_idx;
2281
2282         if (namelen > DLM_LOCKID_NAME_MAX) {
2283                 mlog(ML_ERROR, "Invalid name length!");
2284                 goto done;
2285         }
2286         if (deref->node_idx >= O2NM_MAX_NODES) {
2287                 mlog(ML_ERROR, "Invalid node number: %u\n", node);
2288                 goto done;
2289         }
2290
2291         hash = dlm_lockid_hash(name, namelen);
2292
2293         spin_lock(&dlm->spinlock);
2294         res = __dlm_lookup_lockres_full(dlm, name, namelen, hash);
2295         if (!res) {
2296                 spin_unlock(&dlm->spinlock);
2297                 mlog(ML_ERROR, "%s:%.*s: bad lockres name\n",
2298                      dlm->name, namelen, name);
2299                 goto done;
2300         }
2301         spin_unlock(&dlm->spinlock);
2302
2303         spin_lock(&res->spinlock);
2304         if (res->state & DLM_LOCK_RES_SETREF_INPROG)
2305                 dispatch = 1;
2306         else {
2307                 BUG_ON(res->state & DLM_LOCK_RES_DROPPING_REF);
2308                 if (test_bit(node, res->refmap)) {
2309                         dlm_lockres_clear_refmap_bit(dlm, res, node);
2310                         cleared = 1;
2311                 }
2312         }
2313         spin_unlock(&res->spinlock);
2314
2315         if (!dispatch) {
2316                 if (cleared)
2317                         dlm_lockres_calc_usage(dlm, res);
2318                 else {
2319                         mlog(ML_ERROR, "%s:%.*s: node %u trying to drop ref "
2320                         "but it is already dropped!\n", dlm->name,
2321                         res->lockname.len, res->lockname.name, node);
2322                         dlm_print_one_lock_resource(res);
2323                 }
2324                 ret = 0;
2325                 goto done;
2326         }
2327
2328         item = kzalloc(sizeof(*item), GFP_NOFS);
2329         if (!item) {
2330                 ret = -ENOMEM;
2331                 mlog_errno(ret);
2332                 goto done;
2333         }
2334
2335         dlm_init_work_item(dlm, item, dlm_deref_lockres_worker, NULL);
2336         item->u.dl.deref_res = res;
2337         item->u.dl.deref_node = node;
2338
2339         spin_lock(&dlm->work_lock);
2340         list_add_tail(&item->list, &dlm->work_list);
2341         spin_unlock(&dlm->work_lock);
2342
2343         queue_work(dlm->dlm_worker, &dlm->dispatched_work);
2344         return 0;
2345
2346 done:
2347         if (res)
2348                 dlm_lockres_put(res);
2349         dlm_put(dlm);
2350
2351         return ret;
2352 }
2353
2354 static void dlm_deref_lockres_worker(struct dlm_work_item *item, void *data)
2355 {
2356         struct dlm_ctxt *dlm;
2357         struct dlm_lock_resource *res;
2358         u8 node;
2359         u8 cleared = 0;
2360
2361         dlm = item->dlm;
2362         res = item->u.dl.deref_res;
2363         node = item->u.dl.deref_node;
2364
2365         spin_lock(&res->spinlock);
2366         BUG_ON(res->state & DLM_LOCK_RES_DROPPING_REF);
2367         if (test_bit(node, res->refmap)) {
2368                 __dlm_wait_on_lockres_flags(res, DLM_LOCK_RES_SETREF_INPROG);
2369                 dlm_lockres_clear_refmap_bit(dlm, res, node);
2370                 cleared = 1;
2371         }
2372         spin_unlock(&res->spinlock);
2373
2374         if (cleared) {
2375                 mlog(0, "%s:%.*s node %u ref dropped in dispatch\n",
2376                      dlm->name, res->lockname.len, res->lockname.name, node);
2377                 dlm_lockres_calc_usage(dlm, res);
2378         } else {
2379                 mlog(ML_ERROR, "%s:%.*s: node %u trying to drop ref "
2380                      "but it is already dropped!\n", dlm->name,
2381                      res->lockname.len, res->lockname.name, node);
2382                 dlm_print_one_lock_resource(res);
2383         }
2384
2385         dlm_lockres_put(res);
2386 }
2387
2388 /*
2389  * A migrateable resource is one that is :
2390  * 1. locally mastered, and,
2391  * 2. zero local locks, and,
2392  * 3. one or more non-local locks, or, one or more references
2393  * Returns 1 if yes, 0 if not.
2394  */
2395 static int dlm_is_lockres_migrateable(struct dlm_ctxt *dlm,
2396                                       struct dlm_lock_resource *res)
2397 {
2398         enum dlm_lockres_list idx;
2399         int nonlocal = 0, node_ref;
2400         struct list_head *queue;
2401         struct dlm_lock *lock;
2402         u64 cookie;
2403
2404         assert_spin_locked(&res->spinlock);
2405
2406         /* delay migration when the lockres is in MIGRATING state */
2407         if (res->state & DLM_LOCK_RES_MIGRATING)
2408                 return 0;
2409
2410         /* delay migration when the lockres is in RECOCERING state */
2411         if (res->state & DLM_LOCK_RES_RECOVERING)
2412                 return 0;
2413
2414         if (res->owner != dlm->node_num)
2415                 return 0;
2416
2417         for (idx = DLM_GRANTED_LIST; idx <= DLM_BLOCKED_LIST; idx++) {
2418                 queue = dlm_list_idx_to_ptr(res, idx);
2419                 list_for_each_entry(lock, queue, list) {
2420                         if (lock->ml.node != dlm->node_num) {
2421                                 nonlocal++;
2422                                 continue;
2423                         }
2424                         cookie = be64_to_cpu(lock->ml.cookie);
2425                         mlog(0, "%s: Not migrateable res %.*s, lock %u:%llu on "
2426                              "%s list\n", dlm->name, res->lockname.len,
2427                              res->lockname.name,
2428                              dlm_get_lock_cookie_node(cookie),
2429                              dlm_get_lock_cookie_seq(cookie),
2430                              dlm_list_in_text(idx));
2431                         return 0;
2432                 }
2433         }
2434
2435         if (!nonlocal) {
2436                 node_ref = find_next_bit(res->refmap, O2NM_MAX_NODES, 0);
2437                 if (node_ref >= O2NM_MAX_NODES)
2438                         return 0;
2439         }
2440
2441         mlog(0, "%s: res %.*s, Migrateable\n", dlm->name, res->lockname.len,
2442              res->lockname.name);
2443
2444         return 1;
2445 }
2446
2447 /*
2448  * DLM_MIGRATE_LOCKRES
2449  */
2450
2451
2452 static int dlm_migrate_lockres(struct dlm_ctxt *dlm,
2453                                struct dlm_lock_resource *res, u8 target)
2454 {
2455         struct dlm_master_list_entry *mle = NULL;
2456         struct dlm_master_list_entry *oldmle = NULL;
2457         struct dlm_migratable_lockres *mres = NULL;
2458         int ret = 0;
2459         const char *name;
2460         unsigned int namelen;
2461         int mle_added = 0;
2462         int wake = 0;
2463
2464         if (!dlm_grab(dlm))
2465                 return -EINVAL;
2466
2467         BUG_ON(target == O2NM_MAX_NODES);
2468
2469         name = res->lockname.name;
2470         namelen = res->lockname.len;
2471
2472         mlog(0, "%s: Migrating %.*s to node %u\n", dlm->name, namelen, name,
2473              target);
2474
2475         /* preallocate up front. if this fails, abort */
2476         ret = -ENOMEM;
2477         mres = (struct dlm_migratable_lockres *) __get_free_page(GFP_NOFS);
2478         if (!mres) {
2479                 mlog_errno(ret);
2480                 goto leave;
2481         }
2482
2483         mle = kmem_cache_alloc(dlm_mle_cache, GFP_NOFS);
2484         if (!mle) {
2485                 mlog_errno(ret);
2486                 goto leave;
2487         }
2488         ret = 0;
2489
2490         /*
2491          * clear any existing master requests and
2492          * add the migration mle to the list
2493          */
2494         spin_lock(&dlm->spinlock);
2495         spin_lock(&dlm->master_lock);
2496         ret = dlm_add_migration_mle(dlm, res, mle, &oldmle, name,
2497                                     namelen, target, dlm->node_num);
2498         spin_unlock(&dlm->master_lock);
2499         spin_unlock(&dlm->spinlock);
2500
2501         if (ret == -EEXIST) {
2502                 mlog(0, "another process is already migrating it\n");
2503                 goto fail;
2504         }
2505         mle_added = 1;
2506
2507         /*
2508          * set the MIGRATING flag and flush asts
2509          * if we fail after this we need to re-dirty the lockres
2510          */
2511         if (dlm_mark_lockres_migrating(dlm, res, target) < 0) {
2512                 mlog(ML_ERROR, "tried to migrate %.*s to %u, but "
2513                      "the target went down.\n", res->lockname.len,
2514                      res->lockname.name, target);
2515                 spin_lock(&res->spinlock);
2516                 res->state &= ~DLM_LOCK_RES_MIGRATING;
2517                 wake = 1;
2518                 spin_unlock(&res->spinlock);
2519                 ret = -EINVAL;
2520         }
2521
2522 fail:
2523         if (oldmle) {
2524                 /* master is known, detach if not already detached */
2525                 dlm_mle_detach_hb_events(dlm, oldmle);
2526                 dlm_put_mle(oldmle);
2527         }
2528
2529         if (ret < 0) {
2530                 if (mle_added) {
2531                         dlm_mle_detach_hb_events(dlm, mle);
2532                         dlm_put_mle(mle);
2533                 } else if (mle) {
2534                         kmem_cache_free(dlm_mle_cache, mle);
2535                         mle = NULL;
2536                 }
2537                 goto leave;
2538         }
2539
2540         /*
2541          * at this point, we have a migration target, an mle
2542          * in the master list, and the MIGRATING flag set on
2543          * the lockres
2544          */
2545
2546         /* now that remote nodes are spinning on the MIGRATING flag,
2547          * ensure that all assert_master work is flushed. */
2548         flush_workqueue(dlm->dlm_worker);
2549
2550         /* get an extra reference on the mle.
2551          * otherwise the assert_master from the new
2552          * master will destroy this.
2553          * also, make sure that all callers of dlm_get_mle
2554          * take both dlm->spinlock and dlm->master_lock */
2555         spin_lock(&dlm->spinlock);
2556         spin_lock(&dlm->master_lock);
2557         dlm_get_mle_inuse(mle);
2558         spin_unlock(&dlm->master_lock);
2559         spin_unlock(&dlm->spinlock);
2560
2561         /* notify new node and send all lock state */
2562         /* call send_one_lockres with migration flag.
2563          * this serves as notice to the target node that a
2564          * migration is starting. */
2565         ret = dlm_send_one_lockres(dlm, res, mres, target,
2566                                    DLM_MRES_MIGRATION);
2567
2568         if (ret < 0) {
2569                 mlog(0, "migration to node %u failed with %d\n",
2570                      target, ret);
2571                 /* migration failed, detach and clean up mle */
2572                 dlm_mle_detach_hb_events(dlm, mle);
2573                 dlm_put_mle(mle);
2574                 dlm_put_mle_inuse(mle);
2575                 spin_lock(&res->spinlock);
2576                 res->state &= ~DLM_LOCK_RES_MIGRATING;
2577                 wake = 1;
2578                 spin_unlock(&res->spinlock);
2579                 if (dlm_is_host_down(ret))
2580                         dlm_wait_for_node_death(dlm, target,
2581                                                 DLM_NODE_DEATH_WAIT_MAX);
2582                 goto leave;
2583         }
2584
2585         /* at this point, the target sends a message to all nodes,
2586          * (using dlm_do_migrate_request).  this node is skipped since
2587          * we had to put an mle in the list to begin the process.  this
2588          * node now waits for target to do an assert master.  this node
2589          * will be the last one notified, ensuring that the migration
2590          * is complete everywhere.  if the target dies while this is
2591          * going on, some nodes could potentially see the target as the
2592          * master, so it is important that my recovery finds the migration
2593          * mle and sets the master to UNKNOWN. */
2594
2595
2596         /* wait for new node to assert master */
2597         while (1) {
2598                 ret = wait_event_interruptible_timeout(mle->wq,
2599                                         (atomic_read(&mle->woken) == 1),
2600                                         msecs_to_jiffies(5000));
2601
2602                 if (ret >= 0) {
2603                         if (atomic_read(&mle->woken) == 1 ||
2604                             res->owner == target)
2605                                 break;
2606
2607                         mlog(0, "%s:%.*s: timed out during migration\n",
2608                              dlm->name, res->lockname.len, res->lockname.name);
2609                         /* avoid hang during shutdown when migrating lockres
2610                          * to a node which also goes down */
2611                         if (dlm_is_node_dead(dlm, target)) {
2612                                 mlog(0, "%s:%.*s: expected migration "
2613                                      "target %u is no longer up, restarting\n",
2614                                      dlm->name, res->lockname.len,
2615                                      res->lockname.name, target);
2616                                 ret = -EINVAL;
2617                                 /* migration failed, detach and clean up mle */
2618                                 dlm_mle_detach_hb_events(dlm, mle);
2619                                 dlm_put_mle(mle);
2620                                 dlm_put_mle_inuse(mle);
2621                                 spin_lock(&res->spinlock);
2622                                 res->state &= ~DLM_LOCK_RES_MIGRATING;
2623                                 wake = 1;
2624                                 spin_unlock(&res->spinlock);
2625                                 goto leave;
2626                         }
2627                 } else
2628                         mlog(0, "%s:%.*s: caught signal during migration\n",
2629                              dlm->name, res->lockname.len, res->lockname.name);
2630         }
2631
2632         /* all done, set the owner, clear the flag */
2633         spin_lock(&res->spinlock);
2634         dlm_set_lockres_owner(dlm, res, target);
2635         res->state &= ~DLM_LOCK_RES_MIGRATING;
2636         dlm_remove_nonlocal_locks(dlm, res);
2637         spin_unlock(&res->spinlock);
2638         wake_up(&res->wq);
2639
2640         /* master is known, detach if not already detached */
2641         dlm_mle_detach_hb_events(dlm, mle);
2642         dlm_put_mle_inuse(mle);
2643         ret = 0;
2644
2645         dlm_lockres_calc_usage(dlm, res);
2646
2647 leave:
2648         /* re-dirty the lockres if we failed */
2649         if (ret < 0)
2650                 dlm_kick_thread(dlm, res);
2651
2652         /* wake up waiters if the MIGRATING flag got set
2653          * but migration failed */
2654         if (wake)
2655                 wake_up(&res->wq);
2656
2657         if (mres)
2658                 free_page((unsigned long)mres);
2659
2660         dlm_put(dlm);
2661
2662         mlog(0, "%s: Migrating %.*s to %u, returns %d\n", dlm->name, namelen,
2663              name, target, ret);
2664         return ret;
2665 }
2666
2667 #define DLM_MIGRATION_RETRY_MS  100
2668
2669 /*
2670  * Should be called only after beginning the domain leave process.
2671  * There should not be any remaining locks on nonlocal lock resources,
2672  * and there should be no local locks left on locally mastered resources.
2673  *
2674  * Called with the dlm spinlock held, may drop it to do migration, but
2675  * will re-acquire before exit.
2676  *
2677  * Returns: 1 if dlm->spinlock was dropped/retaken, 0 if never dropped
2678  */
2679 int dlm_empty_lockres(struct dlm_ctxt *dlm, struct dlm_lock_resource *res)
2680 {
2681         int ret;
2682         int lock_dropped = 0;
2683         u8 target = O2NM_MAX_NODES;
2684
2685         assert_spin_locked(&dlm->spinlock);
2686
2687         spin_lock(&res->spinlock);
2688         if (dlm_is_lockres_migrateable(dlm, res))
2689                 target = dlm_pick_migration_target(dlm, res);
2690         spin_unlock(&res->spinlock);
2691
2692         if (target == O2NM_MAX_NODES)
2693                 goto leave;
2694
2695         /* Wheee! Migrate lockres here! Will sleep so drop spinlock. */
2696         spin_unlock(&dlm->spinlock);
2697         lock_dropped = 1;
2698         ret = dlm_migrate_lockres(dlm, res, target);
2699         if (ret)
2700                 mlog(0, "%s: res %.*s, Migrate to node %u failed with %d\n",
2701                      dlm->name, res->lockname.len, res->lockname.name,
2702                      target, ret);
2703         spin_lock(&dlm->spinlock);
2704 leave:
2705         return lock_dropped;
2706 }
2707
2708 int dlm_lock_basts_flushed(struct dlm_ctxt *dlm, struct dlm_lock *lock)
2709 {
2710         int ret;
2711         spin_lock(&dlm->ast_lock);
2712         spin_lock(&lock->spinlock);
2713         ret = (list_empty(&lock->bast_list) && !lock->bast_pending);
2714         spin_unlock(&lock->spinlock);
2715         spin_unlock(&dlm->ast_lock);
2716         return ret;
2717 }
2718
2719 static int dlm_migration_can_proceed(struct dlm_ctxt *dlm,
2720                                      struct dlm_lock_resource *res,
2721                                      u8 mig_target)
2722 {
2723         int can_proceed;
2724         spin_lock(&res->spinlock);
2725         can_proceed = !!(res->state & DLM_LOCK_RES_MIGRATING);
2726         spin_unlock(&res->spinlock);
2727
2728         /* target has died, so make the caller break out of the
2729          * wait_event, but caller must recheck the domain_map */
2730         spin_lock(&dlm->spinlock);
2731         if (!test_bit(mig_target, dlm->domain_map))
2732                 can_proceed = 1;
2733         spin_unlock(&dlm->spinlock);
2734         return can_proceed;
2735 }
2736
2737 static int dlm_lockres_is_dirty(struct dlm_ctxt *dlm,
2738                                 struct dlm_lock_resource *res)
2739 {
2740         int ret;
2741         spin_lock(&res->spinlock);
2742         ret = !!(res->state & DLM_LOCK_RES_DIRTY);
2743         spin_unlock(&res->spinlock);
2744         return ret;
2745 }
2746
2747
2748 static int dlm_mark_lockres_migrating(struct dlm_ctxt *dlm,
2749                                        struct dlm_lock_resource *res,
2750                                        u8 target)
2751 {
2752         int ret = 0;
2753
2754         mlog(0, "dlm_mark_lockres_migrating: %.*s, from %u to %u\n",
2755                res->lockname.len, res->lockname.name, dlm->node_num,
2756                target);
2757         /* need to set MIGRATING flag on lockres.  this is done by
2758          * ensuring that all asts have been flushed for this lockres. */
2759         spin_lock(&res->spinlock);
2760         BUG_ON(res->migration_pending);
2761         res->migration_pending = 1;
2762         /* strategy is to reserve an extra ast then release
2763          * it below, letting the release do all of the work */
2764         __dlm_lockres_reserve_ast(res);
2765         spin_unlock(&res->spinlock);
2766
2767         /* now flush all the pending asts */
2768         dlm_kick_thread(dlm, res);
2769         /* before waiting on DIRTY, block processes which may
2770          * try to dirty the lockres before MIGRATING is set */
2771         spin_lock(&res->spinlock);
2772         BUG_ON(res->state & DLM_LOCK_RES_BLOCK_DIRTY);
2773         res->state |= DLM_LOCK_RES_BLOCK_DIRTY;
2774         spin_unlock(&res->spinlock);
2775         /* now wait on any pending asts and the DIRTY state */
2776         wait_event(dlm->ast_wq, !dlm_lockres_is_dirty(dlm, res));
2777         dlm_lockres_release_ast(dlm, res);
2778
2779         mlog(0, "about to wait on migration_wq, dirty=%s\n",
2780                res->state & DLM_LOCK_RES_DIRTY ? "yes" : "no");
2781         /* if the extra ref we just put was the final one, this
2782          * will pass thru immediately.  otherwise, we need to wait
2783          * for the last ast to finish. */
2784 again:
2785         ret = wait_event_interruptible_timeout(dlm->migration_wq,
2786                    dlm_migration_can_proceed(dlm, res, target),
2787                    msecs_to_jiffies(1000));
2788         if (ret < 0) {
2789                 mlog(0, "woken again: migrating? %s, dead? %s\n",
2790                        res->state & DLM_LOCK_RES_MIGRATING ? "yes":"no",
2791                        test_bit(target, dlm->domain_map) ? "no":"yes");
2792         } else {
2793                 mlog(0, "all is well: migrating? %s, dead? %s\n",
2794                        res->state & DLM_LOCK_RES_MIGRATING ? "yes":"no",
2795                        test_bit(target, dlm->domain_map) ? "no":"yes");
2796         }
2797         if (!dlm_migration_can_proceed(dlm, res, target)) {
2798                 mlog(0, "trying again...\n");
2799                 goto again;
2800         }
2801
2802         ret = 0;
2803         /* did the target go down or die? */
2804         spin_lock(&dlm->spinlock);
2805         if (!test_bit(target, dlm->domain_map)) {
2806                 mlog(ML_ERROR, "aha. migration target %u just went down\n",
2807                      target);
2808                 ret = -EHOSTDOWN;
2809         }
2810         spin_unlock(&dlm->spinlock);
2811
2812         /*
2813          * if target is down, we need to clear DLM_LOCK_RES_BLOCK_DIRTY for
2814          * another try; otherwise, we are sure the MIGRATING state is there,
2815          * drop the unneded state which blocked threads trying to DIRTY
2816          */
2817         spin_lock(&res->spinlock);
2818         BUG_ON(!(res->state & DLM_LOCK_RES_BLOCK_DIRTY));
2819         res->state &= ~DLM_LOCK_RES_BLOCK_DIRTY;
2820         if (!ret)
2821                 BUG_ON(!(res->state & DLM_LOCK_RES_MIGRATING));
2822         spin_unlock(&res->spinlock);
2823
2824         /*
2825          * at this point:
2826          *
2827          *   o the DLM_LOCK_RES_MIGRATING flag is set if target not down
2828          *   o there are no pending asts on this lockres
2829          *   o all processes trying to reserve an ast on this
2830          *     lockres must wait for the MIGRATING flag to clear
2831          */
2832         return ret;
2833 }
2834
2835 /* last step in the migration process.
2836  * original master calls this to free all of the dlm_lock
2837  * structures that used to be for other nodes. */
2838 static void dlm_remove_nonlocal_locks(struct dlm_ctxt *dlm,
2839                                       struct dlm_lock_resource *res)
2840 {
2841         struct list_head *queue = &res->granted;
2842         int i, bit;
2843         struct dlm_lock *lock, *next;
2844
2845         assert_spin_locked(&res->spinlock);
2846
2847         BUG_ON(res->owner == dlm->node_num);
2848
2849         for (i=0; i<3; i++) {
2850                 list_for_each_entry_safe(lock, next, queue, list) {
2851                         if (lock->ml.node != dlm->node_num) {
2852                                 mlog(0, "putting lock for node %u\n",
2853                                      lock->ml.node);
2854                                 /* be extra careful */
2855                                 BUG_ON(!list_empty(&lock->ast_list));
2856                                 BUG_ON(!list_empty(&lock->bast_list));
2857                                 BUG_ON(lock->ast_pending);
2858                                 BUG_ON(lock->bast_pending);
2859                                 dlm_lockres_clear_refmap_bit(dlm, res,
2860                                                              lock->ml.node);
2861                                 list_del_init(&lock->list);
2862                                 dlm_lock_put(lock);
2863                                 /* In a normal unlock, we would have added a
2864                                  * DLM_UNLOCK_FREE_LOCK action. Force it. */
2865                                 dlm_lock_put(lock);
2866                         }
2867                 }
2868                 queue++;
2869         }
2870         bit = 0;
2871         while (1) {
2872                 bit = find_next_bit(res->refmap, O2NM_MAX_NODES, bit);
2873                 if (bit >= O2NM_MAX_NODES)
2874                         break;
2875                 /* do not clear the local node reference, if there is a
2876                  * process holding this, let it drop the ref itself */
2877                 if (bit != dlm->node_num) {
2878                         mlog(0, "%s:%.*s: node %u had a ref to this "
2879                              "migrating lockres, clearing\n", dlm->name,
2880                              res->lockname.len, res->lockname.name, bit);
2881                         dlm_lockres_clear_refmap_bit(dlm, res, bit);
2882                 }
2883                 bit++;
2884         }
2885 }
2886
2887 /*
2888  * Pick a node to migrate the lock resource to. This function selects a
2889  * potential target based first on the locks and then on refmap. It skips
2890  * nodes that are in the process of exiting the domain.
2891  */
2892 static u8 dlm_pick_migration_target(struct dlm_ctxt *dlm,
2893                                     struct dlm_lock_resource *res)
2894 {
2895         enum dlm_lockres_list idx;
2896         struct list_head *queue = &res->granted;
2897         struct dlm_lock *lock;
2898         int noderef;
2899         u8 nodenum = O2NM_MAX_NODES;
2900
2901         assert_spin_locked(&dlm->spinlock);
2902         assert_spin_locked(&res->spinlock);
2903
2904         /* Go through all the locks */
2905         for (idx = DLM_GRANTED_LIST; idx <= DLM_BLOCKED_LIST; idx++) {
2906                 queue = dlm_list_idx_to_ptr(res, idx);
2907                 list_for_each_entry(lock, queue, list) {
2908                         if (lock->ml.node == dlm->node_num)
2909                                 continue;
2910                         if (test_bit(lock->ml.node, dlm->exit_domain_map))
2911                                 continue;
2912                         nodenum = lock->ml.node;
2913                         goto bail;
2914                 }
2915         }
2916
2917         /* Go thru the refmap */
2918         noderef = -1;
2919         while (1) {
2920                 noderef = find_next_bit(res->refmap, O2NM_MAX_NODES,
2921                                         noderef + 1);
2922                 if (noderef >= O2NM_MAX_NODES)
2923                         break;
2924                 if (noderef == dlm->node_num)
2925                         continue;
2926                 if (test_bit(noderef, dlm->exit_domain_map))
2927                         continue;
2928                 nodenum = noderef;
2929                 goto bail;
2930         }
2931
2932 bail:
2933         return nodenum;
2934 }
2935
2936 /* this is called by the new master once all lockres
2937  * data has been received */
2938 static int dlm_do_migrate_request(struct dlm_ctxt *dlm,
2939                                   struct dlm_lock_resource *res,
2940                                   u8 master, u8 new_master,
2941                                   struct dlm_node_iter *iter)
2942 {
2943         struct dlm_migrate_request migrate;
2944         int ret, skip, status = 0;
2945         int nodenum;
2946
2947         memset(&migrate, 0, sizeof(migrate));
2948         migrate.namelen = res->lockname.len;
2949         memcpy(migrate.name, res->lockname.name, migrate.namelen);
2950         migrate.new_master = new_master;
2951         migrate.master = master;
2952
2953         ret = 0;
2954
2955         /* send message to all nodes, except the master and myself */
2956         while ((nodenum = dlm_node_iter_next(iter)) >= 0) {
2957                 if (nodenum == master ||
2958                     nodenum == new_master)
2959                         continue;
2960
2961                 /* We could race exit domain. If exited, skip. */
2962                 spin_lock(&dlm->spinlock);
2963                 skip = (!test_bit(nodenum, dlm->domain_map));
2964                 spin_unlock(&dlm->spinlock);
2965                 if (skip) {
2966                         clear_bit(nodenum, iter->node_map);
2967                         continue;
2968                 }
2969
2970                 ret = o2net_send_message(DLM_MIGRATE_REQUEST_MSG, dlm->key,
2971                                          &migrate, sizeof(migrate), nodenum,
2972                                          &status);
2973                 if (ret < 0) {
2974                         mlog(ML_ERROR, "%s: res %.*s, Error %d send "
2975                              "MIGRATE_REQUEST to node %u\n", dlm->name,
2976                              migrate.namelen, migrate.name, ret, nodenum);
2977                         if (!dlm_is_host_down(ret)) {
2978                                 mlog(ML_ERROR, "unhandled error=%d!\n", ret);
2979                                 BUG();
2980                         }
2981                         clear_bit(nodenum, iter->node_map);
2982                         ret = 0;
2983                 } else if (status < 0) {
2984                         mlog(0, "migrate request (node %u) returned %d!\n",
2985                              nodenum, status);
2986                         ret = status;
2987                 } else if (status == DLM_MIGRATE_RESPONSE_MASTERY_REF) {
2988                         /* during the migration request we short-circuited
2989                          * the mastery of the lockres.  make sure we have
2990                          * a mastery ref for nodenum */
2991                         mlog(0, "%s:%.*s: need ref for node %u\n",
2992                              dlm->name, res->lockname.len, res->lockname.name,
2993                              nodenum);
2994                         spin_lock(&res->spinlock);
2995                         dlm_lockres_set_refmap_bit(dlm, res, nodenum);
2996                         spin_unlock(&res->spinlock);
2997                 }
2998         }
2999
3000         if (ret < 0)
3001                 mlog_errno(ret);
3002
3003         mlog(0, "returning ret=%d\n", ret);
3004         return ret;
3005 }
3006
3007
3008 /* if there is an existing mle for this lockres, we now know who the master is.
3009  * (the one who sent us *this* message) we can clear it up right away.
3010  * since the process that put the mle on the list still has a reference to it,
3011  * we can unhash it now, set the master and wake the process.  as a result,
3012  * we will have no mle in the list to start with.  now we can add an mle for
3013  * the migration and this should be the only one found for those scanning the
3014  * list.  */
3015 int dlm_migrate_request_handler(struct o2net_msg *msg, u32 len, void *data,
3016                                 void **ret_data)
3017 {
3018         struct dlm_ctxt *dlm = data;
3019         struct dlm_lock_resource *res = NULL;
3020         struct dlm_migrate_request *migrate = (struct dlm_migrate_request *) msg->buf;
3021         struct dlm_master_list_entry *mle = NULL, *oldmle = NULL;
3022         const char *name;
3023         unsigned int namelen, hash;
3024         int ret = 0;
3025
3026         if (!dlm_grab(dlm))
3027                 return -EINVAL;
3028
3029         name = migrate->name;
3030         namelen = migrate->namelen;
3031         hash = dlm_lockid_hash(name, namelen);
3032
3033         /* preallocate.. if this fails, abort */
3034         mle = kmem_cache_alloc(dlm_mle_cache, GFP_NOFS);
3035
3036         if (!mle) {
3037                 ret = -ENOMEM;
3038                 goto leave;
3039         }
3040
3041         /* check for pre-existing lock */
3042         spin_lock(&dlm->spinlock);
3043         res = __dlm_lookup_lockres(dlm, name, namelen, hash);
3044         if (res) {
3045                 spin_lock(&res->spinlock);
3046                 if (res->state & DLM_LOCK_RES_RECOVERING) {
3047                         /* if all is working ok, this can only mean that we got
3048                         * a migrate request from a node that we now see as
3049                         * dead.  what can we do here?  drop it to the floor? */
3050                         spin_unlock(&res->spinlock);
3051                         mlog(ML_ERROR, "Got a migrate request, but the "
3052                              "lockres is marked as recovering!");
3053                         kmem_cache_free(dlm_mle_cache, mle);
3054                         ret = -EINVAL; /* need a better solution */
3055                         goto unlock;
3056                 }
3057                 res->state |= DLM_LOCK_RES_MIGRATING;
3058                 spin_unlock(&res->spinlock);
3059         }
3060
3061         spin_lock(&dlm->master_lock);
3062         /* ignore status.  only nonzero status would BUG. */
3063         ret = dlm_add_migration_mle(dlm, res, mle, &oldmle,
3064                                     name, namelen,
3065                                     migrate->new_master,
3066                                     migrate->master);
3067
3068         spin_unlock(&dlm->master_lock);
3069 unlock:
3070         spin_unlock(&dlm->spinlock);
3071
3072         if (oldmle) {
3073                 /* master is known, detach if not already detached */
3074                 dlm_mle_detach_hb_events(dlm, oldmle);
3075                 dlm_put_mle(oldmle);
3076         }
3077
3078         if (res)
3079                 dlm_lockres_put(res);
3080 leave:
3081         dlm_put(dlm);
3082         return ret;
3083 }
3084
3085 /* must be holding dlm->spinlock and dlm->master_lock
3086  * when adding a migration mle, we can clear any other mles
3087  * in the master list because we know with certainty that
3088  * the master is "master".  so we remove any old mle from
3089  * the list after setting it's master field, and then add
3090  * the new migration mle.  this way we can hold with the rule
3091  * of having only one mle for a given lock name at all times. */
3092 static int dlm_add_migration_mle(struct dlm_ctxt *dlm,
3093                                  struct dlm_lock_resource *res,
3094                                  struct dlm_master_list_entry *mle,
3095                                  struct dlm_master_list_entry **oldmle,
3096                                  const char *name, unsigned int namelen,
3097                                  u8 new_master, u8 master)
3098 {
3099         int found;
3100         int ret = 0;
3101
3102         *oldmle = NULL;
3103
3104         assert_spin_locked(&dlm->spinlock);
3105         assert_spin_locked(&dlm->master_lock);
3106
3107         /* caller is responsible for any ref taken here on oldmle */
3108         found = dlm_find_mle(dlm, oldmle, (char *)name, namelen);
3109         if (found) {
3110                 struct dlm_master_list_entry *tmp = *oldmle;
3111                 spin_lock(&tmp->spinlock);
3112                 if (tmp->type == DLM_MLE_MIGRATION) {
3113                         if (master == dlm->node_num) {
3114                                 /* ah another process raced me to it */
3115                                 mlog(0, "tried to migrate %.*s, but some "
3116                                      "process beat me to it\n",
3117                                      namelen, name);
3118                                 ret = -EEXIST;
3119                         } else {
3120                                 /* bad.  2 NODES are trying to migrate! */
3121                                 mlog(ML_ERROR, "migration error  mle: "
3122                                      "master=%u new_master=%u // request: "
3123                                      "master=%u new_master=%u // "
3124                                      "lockres=%.*s\n",
3125                                      tmp->master, tmp->new_master,
3126                                      master, new_master,
3127                                      namelen, name);
3128                                 BUG();
3129                         }
3130                 } else {
3131                         /* this is essentially what assert_master does */
3132                         tmp->master = master;
3133                         atomic_set(&tmp->woken, 1);
3134                         wake_up(&tmp->wq);
3135                         /* remove it so that only one mle will be found */
3136                         __dlm_unlink_mle(dlm, tmp);
3137                         __dlm_mle_detach_hb_events(dlm, tmp);
3138                         if (tmp->type == DLM_MLE_MASTER) {
3139                                 ret = DLM_MIGRATE_RESPONSE_MASTERY_REF;
3140                                 mlog(0, "%s:%.*s: master=%u, newmaster=%u, "
3141                                                 "telling master to get ref "
3142                                                 "for cleared out mle during "
3143                                                 "migration\n", dlm->name,
3144                                                 namelen, name, master,
3145                                                 new_master);
3146                         }
3147                 }
3148                 spin_unlock(&tmp->spinlock);
3149         }
3150
3151         /* now add a migration mle to the tail of the list */
3152         dlm_init_mle(mle, DLM_MLE_MIGRATION, dlm, res, name, namelen);
3153         mle->new_master = new_master;
3154         /* the new master will be sending an assert master for this.
3155          * at that point we will get the refmap reference */
3156         mle->master = master;
3157         /* do this for consistency with other mle types */
3158         set_bit(new_master, mle->maybe_map);
3159         __dlm_insert_mle(dlm, mle);
3160
3161         return ret;
3162 }
3163
3164 /*
3165  * Sets the owner of the lockres, associated to the mle, to UNKNOWN
3166  */
3167 static struct dlm_lock_resource *dlm_reset_mleres_owner(struct dlm_ctxt *dlm,
3168                                         struct dlm_master_list_entry *mle)
3169 {
3170         struct dlm_lock_resource *res;
3171
3172         /* Find the lockres associated to the mle and set its owner to UNK */
3173         res = __dlm_lookup_lockres(dlm, mle->mname, mle->mnamelen,
3174                                    mle->mnamehash);
3175         if (res) {
3176                 spin_unlock(&dlm->master_lock);
3177
3178                 /* move lockres onto recovery list */
3179                 spin_lock(&res->spinlock);
3180                 dlm_set_lockres_owner(dlm, res, DLM_LOCK_RES_OWNER_UNKNOWN);
3181                 dlm_move_lockres_to_recovery_list(dlm, res);
3182                 spin_unlock(&res->spinlock);
3183                 dlm_lockres_put(res);
3184
3185                 /* about to get rid of mle, detach from heartbeat */
3186                 __dlm_mle_detach_hb_events(dlm, mle);
3187
3188                 /* dump the mle */
3189                 spin_lock(&dlm->master_lock);
3190                 __dlm_put_mle(mle);
3191                 spin_unlock(&dlm->master_lock);
3192         }
3193
3194         return res;
3195 }
3196
3197 static void dlm_clean_migration_mle(struct dlm_ctxt *dlm,
3198                                     struct dlm_master_list_entry *mle)
3199 {
3200         __dlm_mle_detach_hb_events(dlm, mle);
3201
3202         spin_lock(&mle->spinlock);
3203         __dlm_unlink_mle(dlm, mle);
3204         atomic_set(&mle->woken, 1);
3205         spin_unlock(&mle->spinlock);
3206
3207         wake_up(&mle->wq);
3208 }
3209
3210 static void dlm_clean_block_mle(struct dlm_ctxt *dlm,
3211                                 struct dlm_master_list_entry *mle, u8 dead_node)
3212 {
3213         int bit;
3214
3215         BUG_ON(mle->type != DLM_MLE_BLOCK);
3216
3217         spin_lock(&mle->spinlock);
3218         bit = find_next_bit(mle->maybe_map, O2NM_MAX_NODES, 0);
3219         if (bit != dead_node) {
3220                 mlog(0, "mle found, but dead node %u would not have been "
3221                      "master\n", dead_node);
3222                 spin_unlock(&mle->spinlock);
3223         } else {
3224                 /* Must drop the refcount by one since the assert_master will
3225                  * never arrive. This may result in the mle being unlinked and
3226                  * freed, but there may still be a process waiting in the
3227                  * dlmlock path which is fine. */
3228                 mlog(0, "node %u was expected master\n", dead_node);
3229                 atomic_set(&mle->woken, 1);
3230                 spin_unlock(&mle->spinlock);
3231                 wake_up(&mle->wq);
3232
3233                 /* Do not need events any longer, so detach from heartbeat */
3234                 __dlm_mle_detach_hb_events(dlm, mle);
3235                 __dlm_put_mle(mle);
3236         }
3237 }
3238
3239 void dlm_clean_master_list(struct dlm_ctxt *dlm, u8 dead_node)
3240 {
3241         struct dlm_master_list_entry *mle;
3242         struct dlm_lock_resource *res;
3243         struct hlist_head *bucket;
3244         struct hlist_node *tmp;
3245         unsigned int i;
3246
3247         mlog(0, "dlm=%s, dead node=%u\n", dlm->name, dead_node);
3248 top:
3249         assert_spin_locked(&dlm->spinlock);
3250
3251         /* clean the master list */
3252         spin_lock(&dlm->master_lock);
3253         for (i = 0; i < DLM_HASH_BUCKETS; i++) {
3254                 bucket = dlm_master_hash(dlm, i);
3255                 hlist_for_each_entry_safe(mle, tmp, bucket, master_hash_node) {
3256                         BUG_ON(mle->type != DLM_MLE_BLOCK &&
3257                                mle->type != DLM_MLE_MASTER &&
3258                                mle->type != DLM_MLE_MIGRATION);
3259
3260                         /* MASTER mles are initiated locally. The waiting
3261                          * process will notice the node map change shortly.
3262                          * Let that happen as normal. */
3263                         if (mle->type == DLM_MLE_MASTER)
3264                                 continue;
3265
3266                         /* BLOCK mles are initiated by other nodes. Need to
3267                          * clean up if the dead node would have been the
3268                          * master. */
3269                         if (mle->type == DLM_MLE_BLOCK) {
3270                                 dlm_clean_block_mle(dlm, mle, dead_node);
3271                                 continue;
3272                         }
3273
3274                         /* Everything else is a MIGRATION mle */
3275
3276                         /* The rule for MIGRATION mles is that the master
3277                          * becomes UNKNOWN if *either* the original or the new
3278                          * master dies. All UNKNOWN lockres' are sent to
3279                          * whichever node becomes the recovery master. The new
3280                          * master is responsible for determining if there is
3281                          * still a master for this lockres, or if he needs to
3282                          * take over mastery. Either way, this node should
3283                          * expect another message to resolve this. */
3284
3285                         if (mle->master != dead_node &&
3286                             mle->new_master != dead_node)
3287                                 continue;
3288
3289                         /* If we have reached this point, this mle needs to be
3290                          * removed from the list and freed. */
3291                         dlm_clean_migration_mle(dlm, mle);
3292
3293                         mlog(0, "%s: node %u died during migration from "
3294                              "%u to %u!\n", dlm->name, dead_node, mle->master,
3295                              mle->new_master);
3296
3297                         /* If we find a lockres associated with the mle, we've
3298                          * hit this rare case that messes up our lock ordering.
3299                          * If so, we need to drop the master lock so that we can
3300                          * take the lockres lock, meaning that we will have to
3301                          * restart from the head of list. */
3302                         res = dlm_reset_mleres_owner(dlm, mle);
3303                         if (res)
3304                                 /* restart */
3305                                 goto top;
3306
3307                         /* This may be the last reference */
3308                         __dlm_put_mle(mle);
3309                 }
3310         }
3311         spin_unlock(&dlm->master_lock);
3312 }
3313
3314 int dlm_finish_migration(struct dlm_ctxt *dlm, struct dlm_lock_resource *res,
3315                          u8 old_master)
3316 {
3317         struct dlm_node_iter iter;
3318         int ret = 0;
3319
3320         spin_lock(&dlm->spinlock);
3321         dlm_node_iter_init(dlm->domain_map, &iter);
3322         clear_bit(old_master, iter.node_map);
3323         clear_bit(dlm->node_num, iter.node_map);
3324         spin_unlock(&dlm->spinlock);
3325
3326         /* ownership of the lockres is changing.  account for the
3327          * mastery reference here since old_master will briefly have
3328          * a reference after the migration completes */
3329         spin_lock(&res->spinlock);
3330         dlm_lockres_set_refmap_bit(dlm, res, old_master);
3331         spin_unlock(&res->spinlock);
3332
3333         mlog(0, "now time to do a migrate request to other nodes\n");
3334         ret = dlm_do_migrate_request(dlm, res, old_master,
3335                                      dlm->node_num, &iter);
3336         if (ret < 0) {
3337                 mlog_errno(ret);
3338                 goto leave;
3339         }
3340
3341         mlog(0, "doing assert master of %.*s to all except the original node\n",
3342              res->lockname.len, res->lockname.name);
3343         /* this call now finishes out the nodemap
3344          * even if one or more nodes die */
3345         ret = dlm_do_assert_master(dlm, res, iter.node_map,
3346                                    DLM_ASSERT_MASTER_FINISH_MIGRATION);
3347         if (ret < 0) {
3348                 /* no longer need to retry.  all living nodes contacted. */
3349                 mlog_errno(ret);
3350                 ret = 0;
3351         }
3352
3353         memset(iter.node_map, 0, sizeof(iter.node_map));
3354         set_bit(old_master, iter.node_map);
3355         mlog(0, "doing assert master of %.*s back to %u\n",
3356              res->lockname.len, res->lockname.name, old_master);
3357         ret = dlm_do_assert_master(dlm, res, iter.node_map,
3358                                    DLM_ASSERT_MASTER_FINISH_MIGRATION);
3359         if (ret < 0) {
3360                 mlog(0, "assert master to original master failed "
3361                      "with %d.\n", ret);
3362                 /* the only nonzero status here would be because of
3363                  * a dead original node.  we're done. */
3364                 ret = 0;
3365         }
3366
3367         /* all done, set the owner, clear the flag */
3368         spin_lock(&res->spinlock);
3369         dlm_set_lockres_owner(dlm, res, dlm->node_num);
3370         res->state &= ~DLM_LOCK_RES_MIGRATING;
3371         spin_unlock(&res->spinlock);
3372         /* re-dirty it on the new master */
3373         dlm_kick_thread(dlm, res);
3374         wake_up(&res->wq);
3375 leave:
3376         return ret;
3377 }
3378
3379 /*
3380  * LOCKRES AST REFCOUNT
3381  * this is integral to migration
3382  */
3383
3384 /* for future intent to call an ast, reserve one ahead of time.
3385  * this should be called only after waiting on the lockres
3386  * with dlm_wait_on_lockres, and while still holding the
3387  * spinlock after the call. */
3388 void __dlm_lockres_reserve_ast(struct dlm_lock_resource *res)
3389 {
3390         assert_spin_locked(&res->spinlock);
3391         if (res->state & DLM_LOCK_RES_MIGRATING) {
3392                 __dlm_print_one_lock_resource(res);
3393         }
3394         BUG_ON(res->state & DLM_LOCK_RES_MIGRATING);
3395
3396         atomic_inc(&res->asts_reserved);
3397 }
3398
3399 /*
3400  * used to drop the reserved ast, either because it went unused,
3401  * or because the ast/bast was actually called.
3402  *
3403  * also, if there is a pending migration on this lockres,
3404  * and this was the last pending ast on the lockres,
3405  * atomically set the MIGRATING flag before we drop the lock.
3406  * this is how we ensure that migration can proceed with no
3407  * asts in progress.  note that it is ok if the state of the
3408  * queues is such that a lock should be granted in the future
3409  * or that a bast should be fired, because the new master will
3410  * shuffle the lists on this lockres as soon as it is migrated.
3411  */
3412 void dlm_lockres_release_ast(struct dlm_ctxt *dlm,
3413                              struct dlm_lock_resource *res)
3414 {
3415         if (!atomic_dec_and_lock(&res->asts_reserved, &res->spinlock))
3416                 return;
3417
3418         if (!res->migration_pending) {
3419                 spin_unlock(&res->spinlock);
3420                 return;
3421         }
3422
3423         BUG_ON(res->state & DLM_LOCK_RES_MIGRATING);
3424         res->migration_pending = 0;
3425         res->state |= DLM_LOCK_RES_MIGRATING;
3426         spin_unlock(&res->spinlock);
3427         wake_up(&res->wq);
3428         wake_up(&dlm->migration_wq);
3429 }
3430
3431 void dlm_force_free_mles(struct dlm_ctxt *dlm)
3432 {
3433         int i;
3434         struct hlist_head *bucket;
3435         struct dlm_master_list_entry *mle;
3436         struct hlist_node *tmp;
3437
3438         /*
3439          * We notified all other nodes that we are exiting the domain and
3440          * marked the dlm state to DLM_CTXT_LEAVING. If any mles are still
3441          * around we force free them and wake any processes that are waiting
3442          * on the mles
3443          */
3444         spin_lock(&dlm->spinlock);
3445         spin_lock(&dlm->master_lock);
3446
3447         BUG_ON(dlm->dlm_state != DLM_CTXT_LEAVING);
3448         BUG_ON((find_next_bit(dlm->domain_map, O2NM_MAX_NODES, 0) < O2NM_MAX_NODES));
3449
3450         for (i = 0; i < DLM_HASH_BUCKETS; i++) {
3451                 bucket = dlm_master_hash(dlm, i);
3452                 hlist_for_each_entry_safe(mle, tmp, bucket, master_hash_node) {
3453                         if (mle->type != DLM_MLE_BLOCK) {
3454                                 mlog(ML_ERROR, "bad mle: %p\n", mle);
3455                                 dlm_print_one_mle(mle);
3456                         }
3457                         atomic_set(&mle->woken, 1);
3458                         wake_up(&mle->wq);
3459
3460                         __dlm_unlink_mle(dlm, mle);
3461                         __dlm_mle_detach_hb_events(dlm, mle);
3462                         __dlm_put_mle(mle);
3463                 }
3464         }
3465         spin_unlock(&dlm->master_lock);
3466         spin_unlock(&dlm->spinlock);
3467 }