1/* -*- mode: c; c-basic-offset: 8; -*-
2 * vim: noexpandtab sw=8 ts=8 sts=0:
3 *
4 * dlmrecovery.c
5 *
6 * recovery stuff
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/timer.h>
40#include <linux/kthread.h>
41#include <linux/delay.h>
42
43
44#include "cluster/heartbeat.h"
45#include "cluster/nodemanager.h"
46#include "cluster/tcp.h"
47
48#include "dlmapi.h"
49#include "dlmcommon.h"
50#include "dlmdomain.h"
51
52#define MLOG_MASK_PREFIX (ML_DLM|ML_DLM_RECOVERY)
53#include "cluster/masklog.h"
54
55static void dlm_do_local_recovery_cleanup(struct dlm_ctxt *dlm, u8 dead_node);
56
57static int dlm_recovery_thread(void *data);
58static int dlm_do_recovery(struct dlm_ctxt *dlm);
59
60static int dlm_pick_recovery_master(struct dlm_ctxt *dlm);
61static int dlm_remaster_locks(struct dlm_ctxt *dlm, u8 dead_node);
62static int dlm_init_recovery_area(struct dlm_ctxt *dlm, u8 dead_node);
63static int dlm_request_all_locks(struct dlm_ctxt *dlm,
64				 u8 request_from, u8 dead_node);
65static void dlm_destroy_recovery_area(struct dlm_ctxt *dlm, u8 dead_node);
66
67static inline int dlm_num_locks_in_lockres(struct dlm_lock_resource *res);
68static void dlm_init_migratable_lockres(struct dlm_migratable_lockres *mres,
69					const char *lockname, int namelen,
70					int total_locks, u64 cookie,
71					u8 flags, u8 master);
72static int dlm_send_mig_lockres_msg(struct dlm_ctxt *dlm,
73				    struct dlm_migratable_lockres *mres,
74				    u8 send_to,
75				    struct dlm_lock_resource *res,
76				    int total_locks);
77static int dlm_process_recovery_data(struct dlm_ctxt *dlm,
78				     struct dlm_lock_resource *res,
79				     struct dlm_migratable_lockres *mres);
80static int dlm_send_finalize_reco_message(struct dlm_ctxt *dlm);
81static int dlm_send_all_done_msg(struct dlm_ctxt *dlm,
82				 u8 dead_node, u8 send_to);
83static int dlm_send_begin_reco_message(struct dlm_ctxt *dlm, u8 dead_node);
84static void dlm_move_reco_locks_to_list(struct dlm_ctxt *dlm,
85					struct list_head *list, u8 dead_node);
86static void dlm_finish_local_lockres_recovery(struct dlm_ctxt *dlm,
87					      u8 dead_node, u8 new_master);
88static void dlm_reco_ast(void *astdata);
89static void dlm_reco_bast(void *astdata, int blocked_type);
90static void dlm_reco_unlock_ast(void *astdata, enum dlm_status st);
91static void dlm_request_all_locks_worker(struct dlm_work_item *item,
92					 void *data);
93static void dlm_mig_lockres_worker(struct dlm_work_item *item, void *data);
94static int dlm_lockres_master_requery(struct dlm_ctxt *dlm,
95				      struct dlm_lock_resource *res,
96				      u8 *real_master);
97
98static u64 dlm_get_next_mig_cookie(void);
99
100static DEFINE_SPINLOCK(dlm_reco_state_lock);
101static DEFINE_SPINLOCK(dlm_mig_cookie_lock);
102static u64 dlm_mig_cookie = 1;
103
104static u64 dlm_get_next_mig_cookie(void)
105{
106	u64 c;
107	spin_lock(&dlm_mig_cookie_lock);
108	c = dlm_mig_cookie;
109	if (dlm_mig_cookie == (~0ULL))
110		dlm_mig_cookie = 1;
111	else
112		dlm_mig_cookie++;
113	spin_unlock(&dlm_mig_cookie_lock);
114	return c;
115}
116
117static inline void dlm_set_reco_dead_node(struct dlm_ctxt *dlm,
118					  u8 dead_node)
119{
120	assert_spin_locked(&dlm->spinlock);
121	if (dlm->reco.dead_node != dead_node)
122		mlog(0, "%s: changing dead_node from %u to %u\n",
123		     dlm->name, dlm->reco.dead_node, dead_node);
124	dlm->reco.dead_node = dead_node;
125}
126
127static inline void dlm_set_reco_master(struct dlm_ctxt *dlm,
128				       u8 master)
129{
130	assert_spin_locked(&dlm->spinlock);
131	mlog(0, "%s: changing new_master from %u to %u\n",
132	     dlm->name, dlm->reco.new_master, master);
133	dlm->reco.new_master = master;
134}
135
136static inline void __dlm_reset_recovery(struct dlm_ctxt *dlm)
137{
138	assert_spin_locked(&dlm->spinlock);
139	clear_bit(dlm->reco.dead_node, dlm->recovery_map);
140	dlm_set_reco_dead_node(dlm, O2NM_INVALID_NODE_NUM);
141	dlm_set_reco_master(dlm, O2NM_INVALID_NODE_NUM);
142}
143
144static inline void dlm_reset_recovery(struct dlm_ctxt *dlm)
145{
146	spin_lock(&dlm->spinlock);
147	__dlm_reset_recovery(dlm);
148	spin_unlock(&dlm->spinlock);
149}
150
151/* Worker function used during recovery. */
152void dlm_dispatch_work(struct work_struct *work)
153{
154	struct dlm_ctxt *dlm =
155		container_of(work, struct dlm_ctxt, dispatched_work);
156	LIST_HEAD(tmp_list);
157	struct dlm_work_item *item, *next;
158	dlm_workfunc_t *workfunc;
159	int tot=0;
160
161	spin_lock(&dlm->work_lock);
162	list_splice_init(&dlm->work_list, &tmp_list);
163	spin_unlock(&dlm->work_lock);
164
165	list_for_each_entry(item, &tmp_list, list) {
166		tot++;
167	}
168	mlog(0, "%s: work thread has %d work items\n", dlm->name, tot);
169
170	list_for_each_entry_safe(item, next, &tmp_list, list) {
171		workfunc = item->func;
172		list_del_init(&item->list);
173
174		/* already have ref on dlm to avoid having
175		 * it disappear.  just double-check. */
176		BUG_ON(item->dlm != dlm);
177
178		/* this is allowed to sleep and
179		 * call network stuff */
180		workfunc(item, item->data);
181
182		dlm_put(dlm);
183		kfree(item);
184	}
185}
186
187/*
188 * RECOVERY THREAD
189 */
190
191void dlm_kick_recovery_thread(struct dlm_ctxt *dlm)
192{
193	/* wake the recovery thread
194	 * this will wake the reco thread in one of three places
195	 * 1) sleeping with no recovery happening
196	 * 2) sleeping with recovery mastered elsewhere
197	 * 3) recovery mastered here, waiting on reco data */
198
199	wake_up(&dlm->dlm_reco_thread_wq);
200}
201
202/* Launch the recovery thread */
203int dlm_launch_recovery_thread(struct dlm_ctxt *dlm)
204{
205	mlog(0, "starting dlm recovery thread...\n");
206
207	dlm->dlm_reco_thread_task = kthread_run(dlm_recovery_thread, dlm,
208						"dlm_reco_thread");
209	if (IS_ERR(dlm->dlm_reco_thread_task)) {
210		mlog_errno(PTR_ERR(dlm->dlm_reco_thread_task));
211		dlm->dlm_reco_thread_task = NULL;
212		return -EINVAL;
213	}
214
215	return 0;
216}
217
218void dlm_complete_recovery_thread(struct dlm_ctxt *dlm)
219{
220	if (dlm->dlm_reco_thread_task) {
221		mlog(0, "waiting for dlm recovery thread to exit\n");
222		kthread_stop(dlm->dlm_reco_thread_task);
223		dlm->dlm_reco_thread_task = NULL;
224	}
225}
226
227
228
229/*
230 * this is lame, but here's how recovery works...
231 * 1) all recovery threads cluster wide will work on recovering
232 *    ONE node at a time
233 * 2) negotiate who will take over all the locks for the dead node.
234 *    thats right... ALL the locks.
235 * 3) once a new master is chosen, everyone scans all locks
236 *    and moves aside those mastered by the dead guy
237 * 4) each of these locks should be locked until recovery is done
238 * 5) the new master collects up all of secondary lock queue info
239 *    one lock at a time, forcing each node to communicate back
240 *    before continuing
241 * 6) each secondary lock queue responds with the full known lock info
242 * 7) once the new master has run all its locks, it sends a ALLDONE!
243 *    message to everyone
244 * 8) upon receiving this message, the secondary queue node unlocks
245 *    and responds to the ALLDONE
246 * 9) once the new master gets responses from everyone, he unlocks
247 *    everything and recovery for this dead node is done
248 *10) go back to 2) while there are still dead nodes
249 *
250 */
251
252static void dlm_print_reco_node_status(struct dlm_ctxt *dlm)
253{
254	struct dlm_reco_node_data *ndata;
255	struct dlm_lock_resource *res;
256
257	mlog(ML_NOTICE, "%s(%d): recovery info, state=%s, dead=%u, master=%u\n",
258	     dlm->name, task_pid_nr(dlm->dlm_reco_thread_task),
259	     dlm->reco.state & DLM_RECO_STATE_ACTIVE ? "ACTIVE" : "inactive",
260	     dlm->reco.dead_node, dlm->reco.new_master);
261
262	list_for_each_entry(ndata, &dlm->reco.node_data, list) {
263		char *st = "unknown";
264		switch (ndata->state) {
265			case DLM_RECO_NODE_DATA_INIT:
266				st = "init";
267				break;
268			case DLM_RECO_NODE_DATA_REQUESTING:
269				st = "requesting";
270				break;
271			case DLM_RECO_NODE_DATA_DEAD:
272				st = "dead";
273				break;
274			case DLM_RECO_NODE_DATA_RECEIVING:
275				st = "receiving";
276				break;
277			case DLM_RECO_NODE_DATA_REQUESTED:
278				st = "requested";
279				break;
280			case DLM_RECO_NODE_DATA_DONE:
281				st = "done";
282				break;
283			case DLM_RECO_NODE_DATA_FINALIZE_SENT:
284				st = "finalize-sent";
285				break;
286			default:
287				st = "bad";
288				break;
289		}
290		mlog(ML_NOTICE, "%s: reco state, node %u, state=%s\n",
291		     dlm->name, ndata->node_num, st);
292	}
293	list_for_each_entry(res, &dlm->reco.resources, recovering) {
294		mlog(ML_NOTICE, "%s: lockres %.*s on recovering list\n",
295		     dlm->name, res->lockname.len, res->lockname.name);
296	}
297}
298
299#define DLM_RECO_THREAD_TIMEOUT_MS (5 * 1000)
300
301static int dlm_recovery_thread(void *data)
302{
303	int status;
304	struct dlm_ctxt *dlm = data;
305	unsigned long timeout = msecs_to_jiffies(DLM_RECO_THREAD_TIMEOUT_MS);
306
307	mlog(0, "dlm thread running for %s...\n", dlm->name);
308
309	while (!kthread_should_stop()) {
310		if (dlm_domain_fully_joined(dlm)) {
311			status = dlm_do_recovery(dlm);
312			if (status == -EAGAIN) {
313				/* do not sleep, recheck immediately. */
314				continue;
315			}
316			if (status < 0)
317				mlog_errno(status);
318		}
319
320		wait_event_interruptible_timeout(dlm->dlm_reco_thread_wq,
321						 kthread_should_stop(),
322						 timeout);
323	}
324
325	mlog(0, "quitting DLM recovery thread\n");
326	return 0;
327}
328
329/* returns true when the recovery master has contacted us */
330static int dlm_reco_master_ready(struct dlm_ctxt *dlm)
331{
332	int ready;
333	spin_lock(&dlm->spinlock);
334	ready = (dlm->reco.new_master != O2NM_INVALID_NODE_NUM);
335	spin_unlock(&dlm->spinlock);
336	return ready;
337}
338
339/* returns true if node is no longer in the domain
340 * could be dead or just not joined */
341int dlm_is_node_dead(struct dlm_ctxt *dlm, u8 node)
342{
343	int dead;
344	spin_lock(&dlm->spinlock);
345	dead = !test_bit(node, dlm->domain_map);
346	spin_unlock(&dlm->spinlock);
347	return dead;
348}
349
350/* returns true if node is no longer in the domain
351 * could be dead or just not joined */
352static int dlm_is_node_recovered(struct dlm_ctxt *dlm, u8 node)
353{
354	int recovered;
355	spin_lock(&dlm->spinlock);
356	recovered = !test_bit(node, dlm->recovery_map);
357	spin_unlock(&dlm->spinlock);
358	return recovered;
359}
360
361
362void dlm_wait_for_node_death(struct dlm_ctxt *dlm, u8 node, int timeout)
363{
364	if (dlm_is_node_dead(dlm, node))
365		return;
366
367	printk(KERN_NOTICE "o2dlm: Waiting on the death of node %u in "
368	       "domain %s\n", node, dlm->name);
369
370	if (timeout)
371		wait_event_timeout(dlm->dlm_reco_thread_wq,
372				   dlm_is_node_dead(dlm, node),
373				   msecs_to_jiffies(timeout));
374	else
375		wait_event(dlm->dlm_reco_thread_wq,
376			   dlm_is_node_dead(dlm, node));
377}
378
379void dlm_wait_for_node_recovery(struct dlm_ctxt *dlm, u8 node, int timeout)
380{
381	if (dlm_is_node_recovered(dlm, node))
382		return;
383
384	printk(KERN_NOTICE "o2dlm: Waiting on the recovery of node %u in "
385	       "domain %s\n", node, dlm->name);
386
387	if (timeout)
388		wait_event_timeout(dlm->dlm_reco_thread_wq,
389				   dlm_is_node_recovered(dlm, node),
390				   msecs_to_jiffies(timeout));
391	else
392		wait_event(dlm->dlm_reco_thread_wq,
393			   dlm_is_node_recovered(dlm, node));
394}
395
396/* callers of the top-level api calls (dlmlock/dlmunlock) should
397 * block on the dlm->reco.event when recovery is in progress.
398 * the dlm recovery thread will set this state when it begins
399 * recovering a dead node (as the new master or not) and clear
400 * the state and wake as soon as all affected lock resources have
401 * been marked with the RECOVERY flag */
402static int dlm_in_recovery(struct dlm_ctxt *dlm)
403{
404	int in_recovery;
405	spin_lock(&dlm->spinlock);
406	in_recovery = !!(dlm->reco.state & DLM_RECO_STATE_ACTIVE);
407	spin_unlock(&dlm->spinlock);
408	return in_recovery;
409}
410
411
412void dlm_wait_for_recovery(struct dlm_ctxt *dlm)
413{
414	if (dlm_in_recovery(dlm)) {
415		mlog(0, "%s: reco thread %d in recovery: "
416		     "state=%d, master=%u, dead=%u\n",
417		     dlm->name, task_pid_nr(dlm->dlm_reco_thread_task),
418		     dlm->reco.state, dlm->reco.new_master,
419		     dlm->reco.dead_node);
420	}
421	wait_event(dlm->reco.event, !dlm_in_recovery(dlm));
422}
423
424static void dlm_begin_recovery(struct dlm_ctxt *dlm)
425{
426	spin_lock(&dlm->spinlock);
427	BUG_ON(dlm->reco.state & DLM_RECO_STATE_ACTIVE);
428	printk(KERN_NOTICE "o2dlm: Begin recovery on domain %s for node %u\n",
429	       dlm->name, dlm->reco.dead_node);
430	dlm->reco.state |= DLM_RECO_STATE_ACTIVE;
431	spin_unlock(&dlm->spinlock);
432}
433
434static void dlm_end_recovery(struct dlm_ctxt *dlm)
435{
436	spin_lock(&dlm->spinlock);
437	BUG_ON(!(dlm->reco.state & DLM_RECO_STATE_ACTIVE));
438	dlm->reco.state &= ~DLM_RECO_STATE_ACTIVE;
439	spin_unlock(&dlm->spinlock);
440	printk(KERN_NOTICE "o2dlm: End recovery on domain %s\n", dlm->name);
441	wake_up(&dlm->reco.event);
442}
443
444static void dlm_print_recovery_master(struct dlm_ctxt *dlm)
445{
446	printk(KERN_NOTICE "o2dlm: Node %u (%s) is the Recovery Master for the "
447	       "dead node %u in domain %s\n", dlm->reco.new_master,
448	       (dlm->node_num == dlm->reco.new_master ? "me" : "he"),
449	       dlm->reco.dead_node, dlm->name);
450}
451
452static int dlm_do_recovery(struct dlm_ctxt *dlm)
453{
454	int status = 0;
455	int ret;
456
457	spin_lock(&dlm->spinlock);
458
459	/* check to see if the new master has died */
460	if (dlm->reco.new_master != O2NM_INVALID_NODE_NUM &&
461	    test_bit(dlm->reco.new_master, dlm->recovery_map)) {
462		mlog(0, "new master %u died while recovering %u!\n",
463		     dlm->reco.new_master, dlm->reco.dead_node);
464		/* unset the new_master, leave dead_node */
465		dlm_set_reco_master(dlm, O2NM_INVALID_NODE_NUM);
466	}
467
468	/* select a target to recover */
469	if (dlm->reco.dead_node == O2NM_INVALID_NODE_NUM) {
470		int bit;
471
472		bit = find_next_bit (dlm->recovery_map, O2NM_MAX_NODES, 0);
473		if (bit >= O2NM_MAX_NODES || bit < 0)
474			dlm_set_reco_dead_node(dlm, O2NM_INVALID_NODE_NUM);
475		else
476			dlm_set_reco_dead_node(dlm, bit);
477	} else if (!test_bit(dlm->reco.dead_node, dlm->recovery_map)) {
478		/* BUG? */
479		mlog(ML_ERROR, "dead_node %u no longer in recovery map!\n",
480		     dlm->reco.dead_node);
481		dlm_set_reco_dead_node(dlm, O2NM_INVALID_NODE_NUM);
482	}
483
484	if (dlm->reco.dead_node == O2NM_INVALID_NODE_NUM) {
485		// mlog(0, "nothing to recover!  sleeping now!\n");
486		spin_unlock(&dlm->spinlock);
487		/* return to main thread loop and sleep. */
488		return 0;
489	}
490	mlog(0, "%s(%d):recovery thread found node %u in the recovery map!\n",
491	     dlm->name, task_pid_nr(dlm->dlm_reco_thread_task),
492	     dlm->reco.dead_node);
493	spin_unlock(&dlm->spinlock);
494
495	/* take write barrier */
496	/* (stops the list reshuffling thread, proxy ast handling) */
497	dlm_begin_recovery(dlm);
498
499	if (dlm->reco.new_master == dlm->node_num)
500		goto master_here;
501
502	if (dlm->reco.new_master == O2NM_INVALID_NODE_NUM) {
503		/* choose a new master, returns 0 if this node
504		 * is the master, -EEXIST if it's another node.
505		 * this does not return until a new master is chosen
506		 * or recovery completes entirely. */
507		ret = dlm_pick_recovery_master(dlm);
508		if (!ret) {
509			/* already notified everyone.  go. */
510			goto master_here;
511		}
512		mlog(0, "another node will master this recovery session.\n");
513	}
514
515	dlm_print_recovery_master(dlm);
516
517	/* it is safe to start everything back up here
518	 * because all of the dead node's lock resources
519	 * have been marked as in-recovery */
520	dlm_end_recovery(dlm);
521
522	/* sleep out in main dlm_recovery_thread loop. */
523	return 0;
524
525master_here:
526	dlm_print_recovery_master(dlm);
527
528	status = dlm_remaster_locks(dlm, dlm->reco.dead_node);
529	if (status < 0) {
530		/* we should never hit this anymore */
531		mlog(ML_ERROR, "%s: Error %d remastering locks for node %u, "
532		     "retrying.\n", dlm->name, status, dlm->reco.dead_node);
533		/* yield a bit to allow any final network messages
534		 * to get handled on remaining nodes */
535		msleep(100);
536	} else {
537		/* success!  see if any other nodes need recovery */
538		mlog(0, "DONE mastering recovery of %s:%u here(this=%u)!\n",
539		     dlm->name, dlm->reco.dead_node, dlm->node_num);
540		spin_lock(&dlm->spinlock);
541		__dlm_reset_recovery(dlm);
542		dlm->reco.state &= ~DLM_RECO_STATE_FINALIZE;
543		spin_unlock(&dlm->spinlock);
544	}
545	dlm_end_recovery(dlm);
546
547	/* continue and look for another dead node */
548	return -EAGAIN;
549}
550
551static int dlm_remaster_locks(struct dlm_ctxt *dlm, u8 dead_node)
552{
553	int status = 0;
554	struct dlm_reco_node_data *ndata;
555	int all_nodes_done;
556	int destroy = 0;
557	int pass = 0;
558
559	do {
560		/* we have become recovery master.  there is no escaping
561		 * this, so just keep trying until we get it. */
562		status = dlm_init_recovery_area(dlm, dead_node);
563		if (status < 0) {
564			mlog(ML_ERROR, "%s: failed to alloc recovery area, "
565			     "retrying\n", dlm->name);
566			msleep(1000);
567		}
568	} while (status != 0);
569
570	/* safe to access the node data list without a lock, since this
571	 * process is the only one to change the list */
572	list_for_each_entry(ndata, &dlm->reco.node_data, list) {
573		BUG_ON(ndata->state != DLM_RECO_NODE_DATA_INIT);
574		ndata->state = DLM_RECO_NODE_DATA_REQUESTING;
575
576		mlog(0, "%s: Requesting lock info from node %u\n", dlm->name,
577		     ndata->node_num);
578
579		if (ndata->node_num == dlm->node_num) {
580			ndata->state = DLM_RECO_NODE_DATA_DONE;
581			continue;
582		}
583
584		do {
585			status = dlm_request_all_locks(dlm, ndata->node_num,
586						       dead_node);
587			if (status < 0) {
588				mlog_errno(status);
589				if (dlm_is_host_down(status)) {
590					/* node died, ignore it for recovery */
591					status = 0;
592					ndata->state = DLM_RECO_NODE_DATA_DEAD;
593					/* wait for the domain map to catch up
594					 * with the network state. */
595					wait_event_timeout(dlm->dlm_reco_thread_wq,
596							   dlm_is_node_dead(dlm,
597								ndata->node_num),
598							   msecs_to_jiffies(1000));
599					mlog(0, "waited 1 sec for %u, "
600					     "dead? %s\n", ndata->node_num,
601					     dlm_is_node_dead(dlm, ndata->node_num) ?
602					     "yes" : "no");
603				} else {
604					/* -ENOMEM on the other node */
605					mlog(0, "%s: node %u returned "
606					     "%d during recovery, retrying "
607					     "after a short wait\n",
608					     dlm->name, ndata->node_num,
609					     status);
610					msleep(100);
611				}
612			}
613		} while (status != 0);
614
615		spin_lock(&dlm_reco_state_lock);
616		switch (ndata->state) {
617			case DLM_RECO_NODE_DATA_INIT:
618			case DLM_RECO_NODE_DATA_FINALIZE_SENT:
619			case DLM_RECO_NODE_DATA_REQUESTED:
620				BUG();
621				break;
622			case DLM_RECO_NODE_DATA_DEAD:
623				mlog(0, "node %u died after requesting "
624				     "recovery info for node %u\n",
625				     ndata->node_num, dead_node);
626				/* fine.  don't need this node's info.
627				 * continue without it. */
628				break;
629			case DLM_RECO_NODE_DATA_REQUESTING:
630				ndata->state = DLM_RECO_NODE_DATA_REQUESTED;
631				mlog(0, "now receiving recovery data from "
632				     "node %u for dead node %u\n",
633				     ndata->node_num, dead_node);
634				break;
635			case DLM_RECO_NODE_DATA_RECEIVING:
636				mlog(0, "already receiving recovery data from "
637				     "node %u for dead node %u\n",
638				     ndata->node_num, dead_node);
639				break;
640			case DLM_RECO_NODE_DATA_DONE:
641				mlog(0, "already DONE receiving recovery data "
642				     "from node %u for dead node %u\n",
643				     ndata->node_num, dead_node);
644				break;
645		}
646		spin_unlock(&dlm_reco_state_lock);
647	}
648
649	mlog(0, "%s: Done requesting all lock info\n", dlm->name);
650
651	/* nodes should be sending reco data now
652	 * just need to wait */
653
654	while (1) {
655		/* check all the nodes now to see if we are
656		 * done, or if anyone died */
657		all_nodes_done = 1;
658		spin_lock(&dlm_reco_state_lock);
659		list_for_each_entry(ndata, &dlm->reco.node_data, list) {
660			mlog(0, "checking recovery state of node %u\n",
661			     ndata->node_num);
662			switch (ndata->state) {
663				case DLM_RECO_NODE_DATA_INIT:
664				case DLM_RECO_NODE_DATA_REQUESTING:
665					mlog(ML_ERROR, "bad ndata state for "
666					     "node %u: state=%d\n",
667					     ndata->node_num, ndata->state);
668					BUG();
669					break;
670				case DLM_RECO_NODE_DATA_DEAD:
671					mlog(0, "node %u died after "
672					     "requesting recovery info for "
673					     "node %u\n", ndata->node_num,
674					     dead_node);
675					break;
676				case DLM_RECO_NODE_DATA_RECEIVING:
677				case DLM_RECO_NODE_DATA_REQUESTED:
678					mlog(0, "%s: node %u still in state %s\n",
679					     dlm->name, ndata->node_num,
680					     ndata->state==DLM_RECO_NODE_DATA_RECEIVING ?
681					     "receiving" : "requested");
682					all_nodes_done = 0;
683					break;
684				case DLM_RECO_NODE_DATA_DONE:
685					mlog(0, "%s: node %u state is done\n",
686					     dlm->name, ndata->node_num);
687					break;
688				case DLM_RECO_NODE_DATA_FINALIZE_SENT:
689					mlog(0, "%s: node %u state is finalize\n",
690					     dlm->name, ndata->node_num);
691					break;
692			}
693		}
694		spin_unlock(&dlm_reco_state_lock);
695
696		mlog(0, "pass #%d, all_nodes_done?: %s\n", ++pass,
697		     all_nodes_done?"yes":"no");
698		if (all_nodes_done) {
699			int ret;
700
701			/* Set this flag on recovery master to avoid
702			 * a new recovery for another dead node start
703			 * before the recovery is not done. That may
704			 * cause recovery hung.*/
705			spin_lock(&dlm->spinlock);
706			dlm->reco.state |= DLM_RECO_STATE_FINALIZE;
707			spin_unlock(&dlm->spinlock);
708
709			/* all nodes are now in DLM_RECO_NODE_DATA_DONE state
710	 		 * just send a finalize message to everyone and
711	 		 * clean up */
712			mlog(0, "all nodes are done! send finalize\n");
713			ret = dlm_send_finalize_reco_message(dlm);
714			if (ret < 0)
715				mlog_errno(ret);
716
717			spin_lock(&dlm->spinlock);
718			dlm_finish_local_lockres_recovery(dlm, dead_node,
719							  dlm->node_num);
720			spin_unlock(&dlm->spinlock);
721			mlog(0, "should be done with recovery!\n");
722
723			mlog(0, "finishing recovery of %s at %lu, "
724			     "dead=%u, this=%u, new=%u\n", dlm->name,
725			     jiffies, dlm->reco.dead_node,
726			     dlm->node_num, dlm->reco.new_master);
727			destroy = 1;
728			status = 0;
729			/* rescan everything marked dirty along the way */
730			dlm_kick_thread(dlm, NULL);
731			break;
732		}
733		/* wait to be signalled, with periodic timeout
734		 * to check for node death */
735		wait_event_interruptible_timeout(dlm->dlm_reco_thread_wq,
736					 kthread_should_stop(),
737					 msecs_to_jiffies(DLM_RECO_THREAD_TIMEOUT_MS));
738
739	}
740
741	if (destroy)
742		dlm_destroy_recovery_area(dlm, dead_node);
743
744	return status;
745}
746
747static int dlm_init_recovery_area(struct dlm_ctxt *dlm, u8 dead_node)
748{
749	int num=0;
750	struct dlm_reco_node_data *ndata;
751
752	spin_lock(&dlm->spinlock);
753	memcpy(dlm->reco.node_map, dlm->domain_map, sizeof(dlm->domain_map));
754	/* nodes can only be removed (by dying) after dropping
755	 * this lock, and death will be trapped later, so this should do */
756	spin_unlock(&dlm->spinlock);
757
758	while (1) {
759		num = find_next_bit (dlm->reco.node_map, O2NM_MAX_NODES, num);
760		if (num >= O2NM_MAX_NODES) {
761			break;
762		}
763		BUG_ON(num == dead_node);
764
765		ndata = kzalloc(sizeof(*ndata), GFP_NOFS);
766		if (!ndata) {
767			dlm_destroy_recovery_area(dlm, dead_node);
768			return -ENOMEM;
769		}
770		ndata->node_num = num;
771		ndata->state = DLM_RECO_NODE_DATA_INIT;
772		spin_lock(&dlm_reco_state_lock);
773		list_add_tail(&ndata->list, &dlm->reco.node_data);
774		spin_unlock(&dlm_reco_state_lock);
775		num++;
776	}
777
778	return 0;
779}
780
781static void dlm_destroy_recovery_area(struct dlm_ctxt *dlm, u8 dead_node)
782{
783	struct dlm_reco_node_data *ndata, *next;
784	LIST_HEAD(tmplist);
785
786	spin_lock(&dlm_reco_state_lock);
787	list_splice_init(&dlm->reco.node_data, &tmplist);
788	spin_unlock(&dlm_reco_state_lock);
789
790	list_for_each_entry_safe(ndata, next, &tmplist, list) {
791		list_del_init(&ndata->list);
792		kfree(ndata);
793	}
794}
795
796static int dlm_request_all_locks(struct dlm_ctxt *dlm, u8 request_from,
797				 u8 dead_node)
798{
799	struct dlm_lock_request lr;
800	int ret;
801	int status;
802
803	mlog(0, "\n");
804
805
806	mlog(0, "dlm_request_all_locks: dead node is %u, sending request "
807		  "to %u\n", dead_node, request_from);
808
809	memset(&lr, 0, sizeof(lr));
810	lr.node_idx = dlm->node_num;
811	lr.dead_node = dead_node;
812
813	// send message
814	ret = o2net_send_message(DLM_LOCK_REQUEST_MSG, dlm->key,
815				 &lr, sizeof(lr), request_from, &status);
816
817	/* negative status is handled by caller */
818	if (ret < 0)
819		mlog(ML_ERROR, "%s: Error %d send LOCK_REQUEST to node %u "
820		     "to recover dead node %u\n", dlm->name, ret,
821		     request_from, dead_node);
822	else
823		ret = status;
824	// return from here, then
825	// sleep until all received or error
826	return ret;
827
828}
829
830int dlm_request_all_locks_handler(struct o2net_msg *msg, u32 len, void *data,
831				  void **ret_data)
832{
833	struct dlm_ctxt *dlm = data;
834	struct dlm_lock_request *lr = (struct dlm_lock_request *)msg->buf;
835	char *buf = NULL;
836	struct dlm_work_item *item = NULL;
837
838	if (!dlm_grab(dlm))
839		return -EINVAL;
840
841	if (lr->dead_node != dlm->reco.dead_node) {
842		mlog(ML_ERROR, "%s: node %u sent dead_node=%u, but local "
843		     "dead_node is %u\n", dlm->name, lr->node_idx,
844		     lr->dead_node, dlm->reco.dead_node);
845		dlm_print_reco_node_status(dlm);
846		/* this is a hack */
847		dlm_put(dlm);
848		return -ENOMEM;
849	}
850	BUG_ON(lr->dead_node != dlm->reco.dead_node);
851
852	item = kzalloc(sizeof(*item), GFP_NOFS);
853	if (!item) {
854		dlm_put(dlm);
855		return -ENOMEM;
856	}
857
858	/* this will get freed by dlm_request_all_locks_worker */
859	buf = (char *) __get_free_page(GFP_NOFS);
860	if (!buf) {
861		kfree(item);
862		dlm_put(dlm);
863		return -ENOMEM;
864	}
865
866	/* queue up work for dlm_request_all_locks_worker */
867	dlm_grab(dlm);  /* get an extra ref for the work item */
868	dlm_init_work_item(dlm, item, dlm_request_all_locks_worker, buf);
869	item->u.ral.reco_master = lr->node_idx;
870	item->u.ral.dead_node = lr->dead_node;
871	spin_lock(&dlm->work_lock);
872	list_add_tail(&item->list, &dlm->work_list);
873	spin_unlock(&dlm->work_lock);
874	queue_work(dlm->dlm_worker, &dlm->dispatched_work);
875
876	dlm_put(dlm);
877	return 0;
878}
879
880static void dlm_request_all_locks_worker(struct dlm_work_item *item, void *data)
881{
882	struct dlm_migratable_lockres *mres;
883	struct dlm_lock_resource *res;
884	struct dlm_ctxt *dlm;
885	LIST_HEAD(resources);
886	int ret;
887	u8 dead_node, reco_master;
888	int skip_all_done = 0;
889
890	dlm = item->dlm;
891	dead_node = item->u.ral.dead_node;
892	reco_master = item->u.ral.reco_master;
893	mres = (struct dlm_migratable_lockres *)data;
894
895	mlog(0, "%s: recovery worker started, dead=%u, master=%u\n",
896	     dlm->name, dead_node, reco_master);
897
898	if (dead_node != dlm->reco.dead_node ||
899	    reco_master != dlm->reco.new_master) {
900		/* worker could have been created before the recovery master
901		 * died.  if so, do not continue, but do not error. */
902		if (dlm->reco.new_master == O2NM_INVALID_NODE_NUM) {
903			mlog(ML_NOTICE, "%s: will not send recovery state, "
904			     "recovery master %u died, thread=(dead=%u,mas=%u)"
905			     " current=(dead=%u,mas=%u)\n", dlm->name,
906			     reco_master, dead_node, reco_master,
907			     dlm->reco.dead_node, dlm->reco.new_master);
908		} else {
909			mlog(ML_NOTICE, "%s: reco state invalid: reco(dead=%u, "
910			     "master=%u), request(dead=%u, master=%u)\n",
911			     dlm->name, dlm->reco.dead_node,
912			     dlm->reco.new_master, dead_node, reco_master);
913		}
914		goto leave;
915	}
916
917	/* lock resources should have already been moved to the
918 	 * dlm->reco.resources list.  now move items from that list
919 	 * to a temp list if the dead owner matches.  note that the
920	 * whole cluster recovers only one node at a time, so we
921	 * can safely move UNKNOWN lock resources for each recovery
922	 * session. */
923	dlm_move_reco_locks_to_list(dlm, &resources, dead_node);
924
925	/* now we can begin blasting lockreses without the dlm lock */
926
927	/* any errors returned will be due to the new_master dying,
928	 * the dlm_reco_thread should detect this */
929	list_for_each_entry(res, &resources, recovering) {
930		ret = dlm_send_one_lockres(dlm, res, mres, reco_master,
931				   	DLM_MRES_RECOVERY);
932		if (ret < 0) {
933			mlog(ML_ERROR, "%s: node %u went down while sending "
934			     "recovery state for dead node %u, ret=%d\n", dlm->name,
935			     reco_master, dead_node, ret);
936			skip_all_done = 1;
937			break;
938		}
939	}
940
941	/* move the resources back to the list */
942	spin_lock(&dlm->spinlock);
943	list_splice_init(&resources, &dlm->reco.resources);
944	spin_unlock(&dlm->spinlock);
945
946	if (!skip_all_done) {
947		ret = dlm_send_all_done_msg(dlm, dead_node, reco_master);
948		if (ret < 0) {
949			mlog(ML_ERROR, "%s: node %u went down while sending "
950			     "recovery all-done for dead node %u, ret=%d\n",
951			     dlm->name, reco_master, dead_node, ret);
952		}
953	}
954leave:
955	free_page((unsigned long)data);
956}
957
958
959static int dlm_send_all_done_msg(struct dlm_ctxt *dlm, u8 dead_node, u8 send_to)
960{
961	int ret, tmpret;
962	struct dlm_reco_data_done done_msg;
963
964	memset(&done_msg, 0, sizeof(done_msg));
965	done_msg.node_idx = dlm->node_num;
966	done_msg.dead_node = dead_node;
967	mlog(0, "sending DATA DONE message to %u, "
968	     "my node=%u, dead node=%u\n", send_to, done_msg.node_idx,
969	     done_msg.dead_node);
970
971	ret = o2net_send_message(DLM_RECO_DATA_DONE_MSG, dlm->key, &done_msg,
972				 sizeof(done_msg), send_to, &tmpret);
973	if (ret < 0) {
974		mlog(ML_ERROR, "%s: Error %d send RECO_DATA_DONE to node %u "
975		     "to recover dead node %u\n", dlm->name, ret, send_to,
976		     dead_node);
977		if (!dlm_is_host_down(ret)) {
978			BUG();
979		}
980	} else
981		ret = tmpret;
982	return ret;
983}
984
985
986int dlm_reco_data_done_handler(struct o2net_msg *msg, u32 len, void *data,
987			       void **ret_data)
988{
989	struct dlm_ctxt *dlm = data;
990	struct dlm_reco_data_done *done = (struct dlm_reco_data_done *)msg->buf;
991	struct dlm_reco_node_data *ndata = NULL;
992	int ret = -EINVAL;
993
994	if (!dlm_grab(dlm))
995		return -EINVAL;
996
997	mlog(0, "got DATA DONE: dead_node=%u, reco.dead_node=%u, "
998	     "node_idx=%u, this node=%u\n", done->dead_node,
999	     dlm->reco.dead_node, done->node_idx, dlm->node_num);
1000
1001	mlog_bug_on_msg((done->dead_node != dlm->reco.dead_node),
1002			"Got DATA DONE: dead_node=%u, reco.dead_node=%u, "
1003			"node_idx=%u, this node=%u\n", done->dead_node,
1004			dlm->reco.dead_node, done->node_idx, dlm->node_num);
1005
1006	spin_lock(&dlm_reco_state_lock);
1007	list_for_each_entry(ndata, &dlm->reco.node_data, list) {
1008		if (ndata->node_num != done->node_idx)
1009			continue;
1010
1011		switch (ndata->state) {
1012			/* should have moved beyond INIT but not to FINALIZE yet */
1013			case DLM_RECO_NODE_DATA_INIT:
1014			case DLM_RECO_NODE_DATA_DEAD:
1015			case DLM_RECO_NODE_DATA_FINALIZE_SENT:
1016				mlog(ML_ERROR, "bad ndata state for node %u:"
1017				     " state=%d\n", ndata->node_num,
1018				     ndata->state);
1019				BUG();
1020				break;
1021			/* these states are possible at this point, anywhere along
1022			 * the line of recovery */
1023			case DLM_RECO_NODE_DATA_DONE:
1024			case DLM_RECO_NODE_DATA_RECEIVING:
1025			case DLM_RECO_NODE_DATA_REQUESTED:
1026			case DLM_RECO_NODE_DATA_REQUESTING:
1027				mlog(0, "node %u is DONE sending "
1028					  "recovery data!\n",
1029					  ndata->node_num);
1030
1031				ndata->state = DLM_RECO_NODE_DATA_DONE;
1032				ret = 0;
1033				break;
1034		}
1035	}
1036	spin_unlock(&dlm_reco_state_lock);
1037
1038	/* wake the recovery thread, some node is done */
1039	if (!ret)
1040		dlm_kick_recovery_thread(dlm);
1041
1042	if (ret < 0)
1043		mlog(ML_ERROR, "failed to find recovery node data for node "
1044		     "%u\n", done->node_idx);
1045	dlm_put(dlm);
1046
1047	mlog(0, "leaving reco data done handler, ret=%d\n", ret);
1048	return ret;
1049}
1050
1051static void dlm_move_reco_locks_to_list(struct dlm_ctxt *dlm,
1052					struct list_head *list,
1053				       	u8 dead_node)
1054{
1055	struct dlm_lock_resource *res, *next;
1056	struct dlm_lock *lock;
1057
1058	spin_lock(&dlm->spinlock);
1059	list_for_each_entry_safe(res, next, &dlm->reco.resources, recovering) {
1060		/* always prune any $RECOVERY entries for dead nodes,
1061		 * otherwise hangs can occur during later recovery */
1062		if (dlm_is_recovery_lock(res->lockname.name,
1063					 res->lockname.len)) {
1064			spin_lock(&res->spinlock);
1065			list_for_each_entry(lock, &res->granted, list) {
1066				if (lock->ml.node == dead_node) {
1067					mlog(0, "AHA! there was "
1068					     "a $RECOVERY lock for dead "
1069					     "node %u (%s)!\n",
1070					     dead_node, dlm->name);
1071					list_del_init(&lock->list);
1072					dlm_lock_put(lock);
1073					/* Can't schedule DLM_UNLOCK_FREE_LOCK
1074					 * - do manually */
1075					dlm_lock_put(lock);
1076					break;
1077				}
1078			}
1079			spin_unlock(&res->spinlock);
1080			continue;
1081		}
1082
1083		if (res->owner == dead_node) {
1084			mlog(0, "found lockres owned by dead node while "
1085				  "doing recovery for node %u. sending it.\n",
1086				  dead_node);
1087			list_move_tail(&res->recovering, list);
1088		} else if (res->owner == DLM_LOCK_RES_OWNER_UNKNOWN) {
1089			mlog(0, "found UNKNOWN owner while doing recovery "
1090				  "for node %u. sending it.\n", dead_node);
1091			list_move_tail(&res->recovering, list);
1092		}
1093	}
1094	spin_unlock(&dlm->spinlock);
1095}
1096
1097static inline int dlm_num_locks_in_lockres(struct dlm_lock_resource *res)
1098{
1099	int total_locks = 0;
1100	struct list_head *iter, *queue = &res->granted;
1101	int i;
1102
1103	for (i=0; i<3; i++) {
1104		list_for_each(iter, queue)
1105			total_locks++;
1106		queue++;
1107	}
1108	return total_locks;
1109}
1110
1111
1112static int dlm_send_mig_lockres_msg(struct dlm_ctxt *dlm,
1113				      struct dlm_migratable_lockres *mres,
1114				      u8 send_to,
1115				      struct dlm_lock_resource *res,
1116				      int total_locks)
1117{
1118	u64 mig_cookie = be64_to_cpu(mres->mig_cookie);
1119	int mres_total_locks = be32_to_cpu(mres->total_locks);
1120	int sz, ret = 0, status = 0;
1121	u8 orig_flags = mres->flags,
1122	   orig_master = mres->master;
1123
1124	BUG_ON(mres->num_locks > DLM_MAX_MIGRATABLE_LOCKS);
1125	if (!mres->num_locks)
1126		return 0;
1127
1128	sz = sizeof(struct dlm_migratable_lockres) +
1129		(mres->num_locks * sizeof(struct dlm_migratable_lock));
1130
1131	/* add an all-done flag if we reached the last lock */
1132	orig_flags = mres->flags;
1133	BUG_ON(total_locks > mres_total_locks);
1134	if (total_locks == mres_total_locks)
1135		mres->flags |= DLM_MRES_ALL_DONE;
1136
1137	mlog(0, "%s:%.*s: sending mig lockres (%s) to %u\n",
1138	     dlm->name, res->lockname.len, res->lockname.name,
1139	     orig_flags & DLM_MRES_MIGRATION ? "migration" : "recovery",
1140	     send_to);
1141
1142	/* send it */
1143	ret = o2net_send_message(DLM_MIG_LOCKRES_MSG, dlm->key, mres,
1144				 sz, send_to, &status);
1145	if (ret < 0) {
1146		/* XXX: negative status is not handled.
1147		 * this will end up killing this node. */
1148		mlog(ML_ERROR, "%s: res %.*s, Error %d send MIG_LOCKRES to "
1149		     "node %u (%s)\n", dlm->name, mres->lockname_len,
1150		     mres->lockname, ret, send_to,
1151		     (orig_flags & DLM_MRES_MIGRATION ?
1152		      "migration" : "recovery"));
1153	} else {
1154		/* might get an -ENOMEM back here */
1155		ret = status;
1156		if (ret < 0) {
1157			mlog_errno(ret);
1158
1159			if (ret == -EFAULT) {
1160				mlog(ML_ERROR, "node %u told me to kill "
1161				     "myself!\n", send_to);
1162				BUG();
1163			}
1164		}
1165	}
1166
1167	/* zero and reinit the message buffer */
1168	dlm_init_migratable_lockres(mres, res->lockname.name,
1169				    res->lockname.len, mres_total_locks,
1170				    mig_cookie, orig_flags, orig_master);
1171	return ret;
1172}
1173
1174static void dlm_init_migratable_lockres(struct dlm_migratable_lockres *mres,
1175					const char *lockname, int namelen,
1176					int total_locks, u64 cookie,
1177					u8 flags, u8 master)
1178{
1179	/* mres here is one full page */
1180	clear_page(mres);
1181	mres->lockname_len = namelen;
1182	memcpy(mres->lockname, lockname, namelen);
1183	mres->num_locks = 0;
1184	mres->total_locks = cpu_to_be32(total_locks);
1185	mres->mig_cookie = cpu_to_be64(cookie);
1186	mres->flags = flags;
1187	mres->master = master;
1188}
1189
1190static void dlm_prepare_lvb_for_migration(struct dlm_lock *lock,
1191					  struct dlm_migratable_lockres *mres,
1192					  int queue)
1193{
1194	if (!lock->lksb)
1195	       return;
1196
1197	/* Ignore lvb in all locks in the blocked list */
1198	if (queue == DLM_BLOCKED_LIST)
1199		return;
1200
1201	/* Only consider lvbs in locks with granted EX or PR lock levels */
1202	if (lock->ml.type != LKM_EXMODE && lock->ml.type != LKM_PRMODE)
1203		return;
1204
1205	if (dlm_lvb_is_empty(mres->lvb)) {
1206		memcpy(mres->lvb, lock->lksb->lvb, DLM_LVB_LEN);
1207		return;
1208	}
1209
1210	/* Ensure the lvb copied for migration matches in other valid locks */
1211	if (!memcmp(mres->lvb, lock->lksb->lvb, DLM_LVB_LEN))
1212		return;
1213
1214	mlog(ML_ERROR, "Mismatched lvb in lock cookie=%u:%llu, name=%.*s, "
1215	     "node=%u\n",
1216	     dlm_get_lock_cookie_node(be64_to_cpu(lock->ml.cookie)),
1217	     dlm_get_lock_cookie_seq(be64_to_cpu(lock->ml.cookie)),
1218	     lock->lockres->lockname.len, lock->lockres->lockname.name,
1219	     lock->ml.node);
1220	dlm_print_one_lock_resource(lock->lockres);
1221	BUG();
1222}
1223
1224/* returns 1 if this lock fills the network structure,
1225 * 0 otherwise */
1226static int dlm_add_lock_to_array(struct dlm_lock *lock,
1227				 struct dlm_migratable_lockres *mres, int queue)
1228{
1229	struct dlm_migratable_lock *ml;
1230	int lock_num = mres->num_locks;
1231
1232	ml = &(mres->ml[lock_num]);
1233	ml->cookie = lock->ml.cookie;
1234	ml->type = lock->ml.type;
1235	ml->convert_type = lock->ml.convert_type;
1236	ml->highest_blocked = lock->ml.highest_blocked;
1237	ml->list = queue;
1238	if (lock->lksb) {
1239		ml->flags = lock->lksb->flags;
1240		dlm_prepare_lvb_for_migration(lock, mres, queue);
1241	}
1242	ml->node = lock->ml.node;
1243	mres->num_locks++;
1244	/* we reached the max, send this network message */
1245	if (mres->num_locks == DLM_MAX_MIGRATABLE_LOCKS)
1246		return 1;
1247	return 0;
1248}
1249
1250static void dlm_add_dummy_lock(struct dlm_ctxt *dlm,
1251			       struct dlm_migratable_lockres *mres)
1252{
1253	struct dlm_lock dummy;
1254	memset(&dummy, 0, sizeof(dummy));
1255	dummy.ml.cookie = 0;
1256	dummy.ml.type = LKM_IVMODE;
1257	dummy.ml.convert_type = LKM_IVMODE;
1258	dummy.ml.highest_blocked = LKM_IVMODE;
1259	dummy.lksb = NULL;
1260	dummy.ml.node = dlm->node_num;
1261	dlm_add_lock_to_array(&dummy, mres, DLM_BLOCKED_LIST);
1262}
1263
1264static inline int dlm_is_dummy_lock(struct dlm_ctxt *dlm,
1265				    struct dlm_migratable_lock *ml,
1266				    u8 *nodenum)
1267{
1268	if (unlikely(ml->cookie == 0 &&
1269	    ml->type == LKM_IVMODE &&
1270	    ml->convert_type == LKM_IVMODE &&
1271	    ml->highest_blocked == LKM_IVMODE &&
1272	    ml->list == DLM_BLOCKED_LIST)) {
1273		*nodenum = ml->node;
1274		return 1;
1275	}
1276	return 0;
1277}
1278
1279int dlm_send_one_lockres(struct dlm_ctxt *dlm, struct dlm_lock_resource *res,
1280			 struct dlm_migratable_lockres *mres,
1281			 u8 send_to, u8 flags)
1282{
1283	struct list_head *queue;
1284	int total_locks, i;
1285	u64 mig_cookie = 0;
1286	struct dlm_lock *lock;
1287	int ret = 0;
1288
1289	BUG_ON(!(flags & (DLM_MRES_RECOVERY|DLM_MRES_MIGRATION)));
1290
1291	mlog(0, "sending to %u\n", send_to);
1292
1293	total_locks = dlm_num_locks_in_lockres(res);
1294	if (total_locks > DLM_MAX_MIGRATABLE_LOCKS) {
1295		/* rare, but possible */
1296		mlog(0, "argh.  lockres has %d locks.  this will "
1297			  "require more than one network packet to "
1298			  "migrate\n", total_locks);
1299		mig_cookie = dlm_get_next_mig_cookie();
1300	}
1301
1302	dlm_init_migratable_lockres(mres, res->lockname.name,
1303				    res->lockname.len, total_locks,
1304				    mig_cookie, flags, res->owner);
1305
1306	total_locks = 0;
1307	for (i=DLM_GRANTED_LIST; i<=DLM_BLOCKED_LIST; i++) {
1308		queue = dlm_list_idx_to_ptr(res, i);
1309		list_for_each_entry(lock, queue, list) {
1310			/* add another lock. */
1311			total_locks++;
1312			if (!dlm_add_lock_to_array(lock, mres, i))
1313				continue;
1314
1315			/* this filled the lock message,
1316			 * we must send it immediately. */
1317			ret = dlm_send_mig_lockres_msg(dlm, mres, send_to,
1318						       res, total_locks);
1319			if (ret < 0)
1320				goto error;
1321		}
1322	}
1323	if (total_locks == 0) {
1324		/* send a dummy lock to indicate a mastery reference only */
1325		mlog(0, "%s:%.*s: sending dummy lock to %u, %s\n",
1326		     dlm->name, res->lockname.len, res->lockname.name,
1327		     send_to, flags & DLM_MRES_RECOVERY ? "recovery" :
1328		     "migration");
1329		dlm_add_dummy_lock(dlm, mres);
1330	}
1331	/* flush any remaining locks */
1332	ret = dlm_send_mig_lockres_msg(dlm, mres, send_to, res, total_locks);
1333	if (ret < 0)
1334		goto error;
1335	return ret;
1336
1337error:
1338	mlog(ML_ERROR, "%s: dlm_send_mig_lockres_msg returned %d\n",
1339	     dlm->name, ret);
1340	if (!dlm_is_host_down(ret))
1341		BUG();
1342	mlog(0, "%s: node %u went down while sending %s "
1343	     "lockres %.*s\n", dlm->name, send_to,
1344	     flags & DLM_MRES_RECOVERY ?  "recovery" : "migration",
1345	     res->lockname.len, res->lockname.name);
1346	return ret;
1347}
1348
1349
1350
1351/*
1352 * this message will contain no more than one page worth of
1353 * recovery data, and it will work on only one lockres.
1354 * there may be many locks in this page, and we may need to wait
1355 * for additional packets to complete all the locks (rare, but
1356 * possible).
1357 */
1358/*
1359 * NOTE: the allocation error cases here are scary
1360 * we really cannot afford to fail an alloc in recovery
1361 * do we spin?  returning an error only delays the problem really
1362 */
1363
1364int dlm_mig_lockres_handler(struct o2net_msg *msg, u32 len, void *data,
1365			    void **ret_data)
1366{
1367	struct dlm_ctxt *dlm = data;
1368	struct dlm_migratable_lockres *mres =
1369		(struct dlm_migratable_lockres *)msg->buf;
1370	int ret = 0;
1371	u8 real_master;
1372	u8 extra_refs = 0;
1373	char *buf = NULL;
1374	struct dlm_work_item *item = NULL;
1375	struct dlm_lock_resource *res = NULL;
1376
1377	if (!dlm_grab(dlm))
1378		return -EINVAL;
1379
1380	BUG_ON(!(mres->flags & (DLM_MRES_RECOVERY|DLM_MRES_MIGRATION)));
1381
1382	real_master = mres->master;
1383	if (real_master == DLM_LOCK_RES_OWNER_UNKNOWN) {
1384		/* cannot migrate a lockres with no master */
1385		BUG_ON(!(mres->flags & DLM_MRES_RECOVERY));
1386	}
1387
1388	mlog(0, "%s message received from node %u\n",
1389		  (mres->flags & DLM_MRES_RECOVERY) ?
1390		  "recovery" : "migration", mres->master);
1391	if (mres->flags & DLM_MRES_ALL_DONE)
1392		mlog(0, "all done flag.  all lockres data received!\n");
1393
1394	ret = -ENOMEM;
1395	buf = kmalloc(be16_to_cpu(msg->data_len), GFP_NOFS);
1396	item = kzalloc(sizeof(*item), GFP_NOFS);
1397	if (!buf || !item)
1398		goto leave;
1399
1400	/* lookup the lock to see if we have a secondary queue for this
1401	 * already...  just add the locks in and this will have its owner
1402	 * and RECOVERY flag changed when it completes. */
1403	res = dlm_lookup_lockres(dlm, mres->lockname, mres->lockname_len);
1404	if (res) {
1405	 	/* this will get a ref on res */
1406		/* mark it as recovering/migrating and hash it */
1407		spin_lock(&res->spinlock);
1408		if (mres->flags & DLM_MRES_RECOVERY) {
1409			res->state |= DLM_LOCK_RES_RECOVERING;
1410		} else {
1411			if (res->state & DLM_LOCK_RES_MIGRATING) {
1412				/* this is at least the second
1413				 * lockres message */
1414				mlog(0, "lock %.*s is already migrating\n",
1415					  mres->lockname_len,
1416					  mres->lockname);
1417			} else if (res->state & DLM_LOCK_RES_RECOVERING) {
1418				/* caller should BUG */
1419				mlog(ML_ERROR, "node is attempting to migrate "
1420				     "lock %.*s, but marked as recovering!\n",
1421				     mres->lockname_len, mres->lockname);
1422				ret = -EFAULT;
1423				spin_unlock(&res->spinlock);
1424				dlm_lockres_put(res);
1425				goto leave;
1426			}
1427			res->state |= DLM_LOCK_RES_MIGRATING;
1428		}
1429		spin_unlock(&res->spinlock);
1430	} else {
1431		/* need to allocate, just like if it was
1432		 * mastered here normally  */
1433		res = dlm_new_lockres(dlm, mres->lockname, mres->lockname_len);
1434		if (!res)
1435			goto leave;
1436
1437		/* to match the ref that we would have gotten if
1438		 * dlm_lookup_lockres had succeeded */
1439		dlm_lockres_get(res);
1440
1441		/* mark it as recovering/migrating and hash it */
1442		if (mres->flags & DLM_MRES_RECOVERY)
1443			res->state |= DLM_LOCK_RES_RECOVERING;
1444		else
1445			res->state |= DLM_LOCK_RES_MIGRATING;
1446
1447		spin_lock(&dlm->spinlock);
1448		__dlm_insert_lockres(dlm, res);
1449		spin_unlock(&dlm->spinlock);
1450
1451		/* Add an extra ref for this lock-less lockres lest the
1452		 * dlm_thread purges it before we get the chance to add
1453		 * locks to it */
1454		dlm_lockres_get(res);
1455
1456		/* There are three refs that need to be put.
1457		 * 1. Taken above.
1458		 * 2. kref_init in dlm_new_lockres()->dlm_init_lockres().
1459		 * 3. dlm_lookup_lockres()
1460		 * The first one is handled at the end of this function. The
1461		 * other two are handled in the worker thread after locks have
1462		 * been attached. Yes, we don't wait for purge time to match
1463		 * kref_init. The lockres will still have atleast one ref
1464		 * added because it is in the hash __dlm_insert_lockres() */
1465		extra_refs++;
1466
1467		/* now that the new lockres is inserted,
1468		 * make it usable by other processes */
1469		spin_lock(&res->spinlock);
1470		res->state &= ~DLM_LOCK_RES_IN_PROGRESS;
1471		spin_unlock(&res->spinlock);
1472		wake_up(&res->wq);
1473	}
1474
1475	/* at this point we have allocated everything we need,
1476	 * and we have a hashed lockres with an extra ref and
1477	 * the proper res->state flags. */
1478	ret = 0;
1479	spin_lock(&res->spinlock);
1480	/* drop this either when master requery finds a different master
1481	 * or when a lock is added by the recovery worker */
1482	dlm_lockres_grab_inflight_ref(dlm, res);
1483	if (mres->master == DLM_LOCK_RES_OWNER_UNKNOWN) {
1484		/* migration cannot have an unknown master */
1485		BUG_ON(!(mres->flags & DLM_MRES_RECOVERY));
1486		mlog(0, "recovery has passed me a lockres with an "
1487			  "unknown owner.. will need to requery: "
1488			  "%.*s\n", mres->lockname_len, mres->lockname);
1489	} else {
1490		/* take a reference now to pin the lockres, drop it
1491		 * when locks are added in the worker */
1492		dlm_change_lockres_owner(dlm, res, dlm->node_num);
1493	}
1494	spin_unlock(&res->spinlock);
1495
1496	/* queue up work for dlm_mig_lockres_worker */
1497	dlm_grab(dlm);  /* get an extra ref for the work item */
1498	memcpy(buf, msg->buf, be16_to_cpu(msg->data_len));  /* copy the whole message */
1499	dlm_init_work_item(dlm, item, dlm_mig_lockres_worker, buf);
1500	item->u.ml.lockres = res; /* already have a ref */
1501	item->u.ml.real_master = real_master;
1502	item->u.ml.extra_ref = extra_refs;
1503	spin_lock(&dlm->work_lock);
1504	list_add_tail(&item->list, &dlm->work_list);
1505	spin_unlock(&dlm->work_lock);
1506	queue_work(dlm->dlm_worker, &dlm->dispatched_work);
1507
1508leave:
1509	/* One extra ref taken needs to be put here */
1510	if (extra_refs)
1511		dlm_lockres_put(res);
1512
1513	dlm_put(dlm);
1514	if (ret < 0) {
1515		kfree(buf);
1516		kfree(item);
1517		mlog_errno(ret);
1518	}
1519
1520	return ret;
1521}
1522
1523
1524static void dlm_mig_lockres_worker(struct dlm_work_item *item, void *data)
1525{
1526	struct dlm_ctxt *dlm;
1527	struct dlm_migratable_lockres *mres;
1528	int ret = 0;
1529	struct dlm_lock_resource *res;
1530	u8 real_master;
1531	u8 extra_ref;
1532
1533	dlm = item->dlm;
1534	mres = (struct dlm_migratable_lockres *)data;
1535
1536	res = item->u.ml.lockres;
1537	real_master = item->u.ml.real_master;
1538	extra_ref = item->u.ml.extra_ref;
1539
1540	if (real_master == DLM_LOCK_RES_OWNER_UNKNOWN) {
1541		/* this case is super-rare. only occurs if
1542		 * node death happens during migration. */
1543again:
1544		ret = dlm_lockres_master_requery(dlm, res, &real_master);
1545		if (ret < 0) {
1546			mlog(0, "dlm_lockres_master_requery ret=%d\n",
1547				  ret);
1548			goto again;
1549		}
1550		if (real_master == DLM_LOCK_RES_OWNER_UNKNOWN) {
1551			mlog(0, "lockres %.*s not claimed.  "
1552				   "this node will take it.\n",
1553				   res->lockname.len, res->lockname.name);
1554		} else {
1555			spin_lock(&res->spinlock);
1556			dlm_lockres_drop_inflight_ref(dlm, res);
1557			spin_unlock(&res->spinlock);
1558			mlog(0, "master needs to respond to sender "
1559				  "that node %u still owns %.*s\n",
1560				  real_master, res->lockname.len,
1561				  res->lockname.name);
1562			/* cannot touch this lockres */
1563			goto leave;
1564		}
1565	}
1566
1567	ret = dlm_process_recovery_data(dlm, res, mres);
1568	if (ret < 0)
1569		mlog(0, "dlm_process_recovery_data returned  %d\n", ret);
1570	else
1571		mlog(0, "dlm_process_recovery_data succeeded\n");
1572
1573	if ((mres->flags & (DLM_MRES_MIGRATION|DLM_MRES_ALL_DONE)) ==
1574	                   (DLM_MRES_MIGRATION|DLM_MRES_ALL_DONE)) {
1575		ret = dlm_finish_migration(dlm, res, mres->master);
1576		if (ret < 0)
1577			mlog_errno(ret);
1578	}
1579
1580leave:
1581	/* See comment in dlm_mig_lockres_handler() */
1582	if (res) {
1583		if (extra_ref)
1584			dlm_lockres_put(res);
1585		dlm_lockres_put(res);
1586	}
1587	kfree(data);
1588}
1589
1590
1591
1592static int dlm_lockres_master_requery(struct dlm_ctxt *dlm,
1593				      struct dlm_lock_resource *res,
1594				      u8 *real_master)
1595{
1596	struct dlm_node_iter iter;
1597	int nodenum;
1598	int ret = 0;
1599
1600	*real_master = DLM_LOCK_RES_OWNER_UNKNOWN;
1601
1602	/* we only reach here if one of the two nodes in a
1603	 * migration died while the migration was in progress.
1604	 * at this point we need to requery the master.  we
1605	 * know that the new_master got as far as creating
1606	 * an mle on at least one node, but we do not know
1607	 * if any nodes had actually cleared the mle and set
1608	 * the master to the new_master.  the old master
1609	 * is supposed to set the owner to UNKNOWN in the
1610	 * event of a new_master death, so the only possible
1611	 * responses that we can get from nodes here are
1612	 * that the master is new_master, or that the master
1613	 * is UNKNOWN.
1614	 * if all nodes come back with UNKNOWN then we know
1615	 * the lock needs remastering here.
1616	 * if any node comes back with a valid master, check
1617	 * to see if that master is the one that we are
1618	 * recovering.  if so, then the new_master died and
1619	 * we need to remaster this lock.  if not, then the
1620	 * new_master survived and that node will respond to
1621	 * other nodes about the owner.
1622	 * if there is an owner, this node needs to dump this
1623	 * lockres and alert the sender that this lockres
1624	 * was rejected. */
1625	spin_lock(&dlm->spinlock);
1626	dlm_node_iter_init(dlm->domain_map, &iter);
1627	spin_unlock(&dlm->spinlock);
1628
1629	while ((nodenum = dlm_node_iter_next(&iter)) >= 0) {
1630		/* do not send to self */
1631		if (nodenum == dlm->node_num)
1632			continue;
1633		ret = dlm_do_master_requery(dlm, res, nodenum, real_master);
1634		if (ret < 0) {
1635			mlog_errno(ret);
1636			if (!dlm_is_host_down(ret))
1637				BUG();
1638			/* host is down, so answer for that node would be
1639			 * DLM_LOCK_RES_OWNER_UNKNOWN.  continue. */
1640		}
1641		if (*real_master != DLM_LOCK_RES_OWNER_UNKNOWN) {
1642			mlog(0, "lock master is %u\n", *real_master);
1643			break;
1644		}
1645	}
1646	return ret;
1647}
1648
1649
1650int dlm_do_master_requery(struct dlm_ctxt *dlm, struct dlm_lock_resource *res,
1651			  u8 nodenum, u8 *real_master)
1652{
1653	int ret = -EINVAL;
1654	struct dlm_master_requery req;
1655	int status = DLM_LOCK_RES_OWNER_UNKNOWN;
1656
1657	memset(&req, 0, sizeof(req));
1658	req.node_idx = dlm->node_num;
1659	req.namelen = res->lockname.len;
1660	memcpy(req.name, res->lockname.name, res->lockname.len);
1661
1662resend:
1663	ret = o2net_send_message(DLM_MASTER_REQUERY_MSG, dlm->key,
1664				 &req, sizeof(req), nodenum, &status);
1665	if (ret < 0)
1666		mlog(ML_ERROR, "Error %d when sending message %u (key "
1667		     "0x%x) to node %u\n", ret, DLM_MASTER_REQUERY_MSG,
1668		     dlm->key, nodenum);
1669	else if (status == -ENOMEM) {
1670		mlog_errno(status);
1671		msleep(50);
1672		goto resend;
1673	} else {
1674		BUG_ON(status < 0);
1675		BUG_ON(status > DLM_LOCK_RES_OWNER_UNKNOWN);
1676		*real_master = (u8) (status & 0xff);
1677		mlog(0, "node %u responded to master requery with %u\n",
1678			  nodenum, *real_master);
1679		ret = 0;
1680	}
1681	return ret;
1682}
1683
1684
1685/* this function cannot error, so unless the sending
1686 * or receiving of the message failed, the owner can
1687 * be trusted */
1688int dlm_master_requery_handler(struct o2net_msg *msg, u32 len, void *data,
1689			       void **ret_data)
1690{
1691	struct dlm_ctxt *dlm = data;
1692	struct dlm_master_requery *req = (struct dlm_master_requery *)msg->buf;
1693	struct dlm_lock_resource *res = NULL;
1694	unsigned int hash;
1695	int master = DLM_LOCK_RES_OWNER_UNKNOWN;
1696	u32 flags = DLM_ASSERT_MASTER_REQUERY;
1697	int dispatched = 0;
1698
1699	if (!dlm_grab(dlm)) {
1700		/* since the domain has gone away on this
1701		 * node, the proper response is UNKNOWN */
1702		return master;
1703	}
1704
1705	hash = dlm_lockid_hash(req->name, req->namelen);
1706
1707	spin_lock(&dlm->spinlock);
1708	res = __dlm_lookup_lockres(dlm, req->name, req->namelen, hash);
1709	if (res) {
1710		spin_lock(&res->spinlock);
1711		master = res->owner;
1712		if (master == dlm->node_num) {
1713			int ret = dlm_dispatch_assert_master(dlm, res,
1714							     0, 0, flags);
1715			if (ret < 0) {
1716				mlog_errno(ret);
1717				spin_unlock(&res->spinlock);
1718				dlm_lockres_put(res);
1719				spin_unlock(&dlm->spinlock);
1720				dlm_put(dlm);
1721				/* sender will take care of this and retry */
1722				return ret;
1723			} else {
1724				dispatched = 1;
1725				__dlm_lockres_grab_inflight_worker(dlm, res);
1726			}
1727			spin_unlock(&res->spinlock);
1728		} else {
1729			/* put.. incase we are not the master */
1730			spin_unlock(&res->spinlock);
1731			dlm_lockres_put(res);
1732		}
1733	}
1734	spin_unlock(&dlm->spinlock);
1735
1736	if (!dispatched)
1737		dlm_put(dlm);
1738	return master;
1739}
1740
1741static inline struct list_head *
1742dlm_list_num_to_pointer(struct dlm_lock_resource *res, int list_num)
1743{
1744	struct list_head *ret;
1745	BUG_ON(list_num < 0);
1746	BUG_ON(list_num > 2);
1747	ret = &(res->granted);
1748	ret += list_num;
1749	return ret;
1750}
1751/* TODO: do ast flush business
1752 * TODO: do MIGRATING and RECOVERING spinning
1753 */
1754
1755/*
1756* NOTE about in-flight requests during migration:
1757*
1758* Before attempting the migrate, the master has marked the lockres as
1759* MIGRATING and then flushed all of its pending ASTS.  So any in-flight
1760* requests either got queued before the MIGRATING flag got set, in which
1761* case the lock data will reflect the change and a return message is on
1762* the way, or the request failed to get in before MIGRATING got set.  In
1763* this case, the caller will be told to spin and wait for the MIGRATING
1764* flag to be dropped, then recheck the master.
1765* This holds true for the convert, cancel and unlock cases, and since lvb
1766* updates are tied to these same messages, it applies to lvb updates as
1767* well.  For the lock case, there is no way a lock can be on the master
1768* queue and not be on the secondary queue since the lock is always added
1769* locally first.  This means that the new target node will never be sent
1770* a lock that he doesn't already have on the list.
1771* In total, this means that the local lock is correct and should not be
1772* updated to match the one sent by the master.  Any messages sent back
1773* from the master before the MIGRATING flag will bring the lock properly
1774* up-to-date, and the change will be ordered properly for the waiter.
1775* We will *not* attempt to modify the lock underneath the waiter.
1776*/
1777
1778static int dlm_process_recovery_data(struct dlm_ctxt *dlm,
1779				     struct dlm_lock_resource *res,
1780				     struct dlm_migratable_lockres *mres)
1781{
1782	struct dlm_migratable_lock *ml;
1783	struct list_head *queue, *iter;
1784	struct list_head *tmpq = NULL;
1785	struct dlm_lock *newlock = NULL;
1786	struct dlm_lockstatus *lksb = NULL;
1787	int ret = 0;
1788	int i, j, bad;
1789	struct dlm_lock *lock;
1790	u8 from = O2NM_MAX_NODES;
1791	unsigned int added = 0;
1792	__be64 c;
1793
1794	mlog(0, "running %d locks for this lockres\n", mres->num_locks);
1795	for (i=0; i<mres->num_locks; i++) {
1796		ml = &(mres->ml[i]);
1797
1798		if (dlm_is_dummy_lock(dlm, ml, &from)) {
1799			/* placeholder, just need to set the refmap bit */
1800			BUG_ON(mres->num_locks != 1);
1801			mlog(0, "%s:%.*s: dummy lock for %u\n",
1802			     dlm->name, mres->lockname_len, mres->lockname,
1803			     from);
1804			spin_lock(&res->spinlock);
1805			dlm_lockres_set_refmap_bit(dlm, res, from);
1806			spin_unlock(&res->spinlock);
1807			added++;
1808			break;
1809		}
1810		BUG_ON(ml->highest_blocked != LKM_IVMODE);
1811		newlock = NULL;
1812		lksb = NULL;
1813
1814		queue = dlm_list_num_to_pointer(res, ml->list);
1815		tmpq = NULL;
1816
1817		/* if the lock is for the local node it needs to
1818		 * be moved to the proper location within the queue.
1819		 * do not allocate a new lock structure. */
1820		if (ml->node == dlm->node_num) {
1821			/* MIGRATION ONLY! */
1822			BUG_ON(!(mres->flags & DLM_MRES_MIGRATION));
1823
1824			lock = NULL;
1825			spin_lock(&res->spinlock);
1826			for (j = DLM_GRANTED_LIST; j <= DLM_BLOCKED_LIST; j++) {
1827				tmpq = dlm_list_idx_to_ptr(res, j);
1828				list_for_each(iter, tmpq) {
1829					lock = list_entry(iter,
1830						  struct dlm_lock, list);
1831					if (lock->ml.cookie == ml->cookie)
1832						break;
1833					lock = NULL;
1834				}
1835				if (lock)
1836					break;
1837			}
1838
1839			/* lock is always created locally first, and
1840			 * destroyed locally last.  it must be on the list */
1841			if (!lock) {
1842				c = ml->cookie;
1843				mlog(ML_ERROR, "Could not find local lock "
1844					       "with cookie %u:%llu, node %u, "
1845					       "list %u, flags 0x%x, type %d, "
1846					       "conv %d, highest blocked %d\n",
1847				     dlm_get_lock_cookie_node(be64_to_cpu(c)),
1848				     dlm_get_lock_cookie_seq(be64_to_cpu(c)),
1849				     ml->node, ml->list, ml->flags, ml->type,
1850				     ml->convert_type, ml->highest_blocked);
1851				__dlm_print_one_lock_resource(res);
1852				BUG();
1853			}
1854
1855			if (lock->ml.node != ml->node) {
1856				c = lock->ml.cookie;
1857				mlog(ML_ERROR, "Mismatched node# in lock "
1858				     "cookie %u:%llu, name %.*s, node %u\n",
1859				     dlm_get_lock_cookie_node(be64_to_cpu(c)),
1860				     dlm_get_lock_cookie_seq(be64_to_cpu(c)),
1861				     res->lockname.len, res->lockname.name,
1862				     lock->ml.node);
1863				c = ml->cookie;
1864				mlog(ML_ERROR, "Migrate lock cookie %u:%llu, "
1865				     "node %u, list %u, flags 0x%x, type %d, "
1866				     "conv %d, highest blocked %d\n",
1867				     dlm_get_lock_cookie_node(be64_to_cpu(c)),
1868				     dlm_get_lock_cookie_seq(be64_to_cpu(c)),
1869				     ml->node, ml->list, ml->flags, ml->type,
1870				     ml->convert_type, ml->highest_blocked);
1871				__dlm_print_one_lock_resource(res);
1872				BUG();
1873			}
1874
1875			if (tmpq != queue) {
1876				c = ml->cookie;
1877				mlog(0, "Lock cookie %u:%llu was on list %u "
1878				     "instead of list %u for %.*s\n",
1879				     dlm_get_lock_cookie_node(be64_to_cpu(c)),
1880				     dlm_get_lock_cookie_seq(be64_to_cpu(c)),
1881				     j, ml->list, res->lockname.len,
1882				     res->lockname.name);
1883				__dlm_print_one_lock_resource(res);
1884				spin_unlock(&res->spinlock);
1885				continue;
1886			}
1887
1888			/* see NOTE above about why we do not update
1889			 * to match the master here */
1890
1891			/* move the lock to its proper place */
1892			/* do not alter lock refcount.  switching lists. */
1893			list_move_tail(&lock->list, queue);
1894			spin_unlock(&res->spinlock);
1895			added++;
1896
1897			mlog(0, "just reordered a local lock!\n");
1898			continue;
1899		}
1900
1901		/* lock is for another node. */
1902		newlock = dlm_new_lock(ml->type, ml->node,
1903				       be64_to_cpu(ml->cookie), NULL);
1904		if (!newlock) {
1905			ret = -ENOMEM;
1906			goto leave;
1907		}
1908		lksb = newlock->lksb;
1909		dlm_lock_attach_lockres(newlock, res);
1910
1911		if (ml->convert_type != LKM_IVMODE) {
1912			BUG_ON(queue != &res->converting);
1913			newlock->ml.convert_type = ml->convert_type;
1914		}
1915		lksb->flags |= (ml->flags &
1916				(DLM_LKSB_PUT_LVB|DLM_LKSB_GET_LVB));
1917
1918		if (ml->type == LKM_NLMODE)
1919			goto skip_lvb;
1920
1921		/*
1922		 * If the lock is in the blocked list it can't have a valid lvb,
1923		 * so skip it
1924		 */
1925		if (ml->list == DLM_BLOCKED_LIST)
1926			goto skip_lvb;
1927
1928		if (!dlm_lvb_is_empty(mres->lvb)) {
1929			if (lksb->flags & DLM_LKSB_PUT_LVB) {
1930				/* other node was trying to update
1931				 * lvb when node died.  recreate the
1932				 * lksb with the updated lvb. */
1933				memcpy(lksb->lvb, mres->lvb, DLM_LVB_LEN);
1934				/* the lock resource lvb update must happen
1935				 * NOW, before the spinlock is dropped.
1936				 * we no longer wait for the AST to update
1937				 * the lvb. */
1938				memcpy(res->lvb, mres->lvb, DLM_LVB_LEN);
1939			} else {
1940				/* otherwise, the node is sending its
1941				 * most recent valid lvb info */
1942				BUG_ON(ml->type != LKM_EXMODE &&
1943				       ml->type != LKM_PRMODE);
1944				if (!dlm_lvb_is_empty(res->lvb) &&
1945 				    (ml->type == LKM_EXMODE ||
1946 				     memcmp(res->lvb, mres->lvb, DLM_LVB_LEN))) {
1947 					int i;
1948 					mlog(ML_ERROR, "%s:%.*s: received bad "
1949 					     "lvb! type=%d\n", dlm->name,
1950 					     res->lockname.len,
1951 					     res->lockname.name, ml->type);
1952 					printk("lockres lvb=[");
1953 					for (i=0; i<DLM_LVB_LEN; i++)
1954 						printk("%02x", res->lvb[i]);
1955 					printk("]\nmigrated lvb=[");
1956 					for (i=0; i<DLM_LVB_LEN; i++)
1957 						printk("%02x", mres->lvb[i]);
1958 					printk("]\n");
1959 					dlm_print_one_lock_resource(res);
1960 					BUG();
1961				}
1962				memcpy(res->lvb, mres->lvb, DLM_LVB_LEN);
1963			}
1964		}
1965skip_lvb:
1966
1967		/* NOTE:
1968		 * wrt lock queue ordering and recovery:
1969		 *    1. order of locks on granted queue is
1970		 *       meaningless.
1971		 *    2. order of locks on converting queue is
1972		 *       LOST with the node death.  sorry charlie.
1973		 *    3. order of locks on the blocked queue is
1974		 *       also LOST.
1975		 * order of locks does not affect integrity, it
1976		 * just means that a lock request may get pushed
1977		 * back in line as a result of the node death.
1978		 * also note that for a given node the lock order
1979		 * for its secondary queue locks is preserved
1980		 * relative to each other, but clearly *not*
1981		 * preserved relative to locks from other nodes.
1982		 */
1983		bad = 0;
1984		spin_lock(&res->spinlock);
1985		list_for_each_entry(lock, queue, list) {
1986			if (lock->ml.cookie == ml->cookie) {
1987				c = lock->ml.cookie;
1988				mlog(ML_ERROR, "%s:%.*s: %u:%llu: lock already "
1989				     "exists on this lockres!\n", dlm->name,
1990				     res->lockname.len, res->lockname.name,
1991				     dlm_get_lock_cookie_node(be64_to_cpu(c)),
1992				     dlm_get_lock_cookie_seq(be64_to_cpu(c)));
1993
1994				mlog(ML_NOTICE, "sent lock: type=%d, conv=%d, "
1995				     "node=%u, cookie=%u:%llu, queue=%d\n",
1996	      			     ml->type, ml->convert_type, ml->node,
1997				     dlm_get_lock_cookie_node(be64_to_cpu(ml->cookie)),
1998				     dlm_get_lock_cookie_seq(be64_to_cpu(ml->cookie)),
1999				     ml->list);
2000
2001				__dlm_print_one_lock_resource(res);
2002				bad = 1;
2003				break;
2004			}
2005		}
2006		if (!bad) {
2007			dlm_lock_get(newlock);
2008			if (mres->flags & DLM_MRES_RECOVERY &&
2009					ml->list == DLM_CONVERTING_LIST &&
2010					newlock->ml.type >
2011					newlock->ml.convert_type) {
2012				/* newlock is doing downconvert, add it to the
2013				 * head of converting list */
2014				list_add(&newlock->list, queue);
2015			} else
2016				list_add_tail(&newlock->list, queue);
2017			mlog(0, "%s:%.*s: added lock for node %u, "
2018			     "setting refmap bit\n", dlm->name,
2019			     res->lockname.len, res->lockname.name, ml->node);
2020			dlm_lockres_set_refmap_bit(dlm, res, ml->node);
2021			added++;
2022		}
2023		spin_unlock(&res->spinlock);
2024	}
2025	mlog(0, "done running all the locks\n");
2026
2027leave:
2028	/* balance the ref taken when the work was queued */
2029	spin_lock(&res->spinlock);
2030	dlm_lockres_drop_inflight_ref(dlm, res);
2031	spin_unlock(&res->spinlock);
2032
2033	if (ret < 0)
2034		mlog_errno(ret);
2035
2036	return ret;
2037}
2038
2039void dlm_move_lockres_to_recovery_list(struct dlm_ctxt *dlm,
2040				       struct dlm_lock_resource *res)
2041{
2042	int i;
2043	struct list_head *queue;
2044	struct dlm_lock *lock, *next;
2045
2046	assert_spin_locked(&dlm->spinlock);
2047	assert_spin_locked(&res->spinlock);
2048	res->state |= DLM_LOCK_RES_RECOVERING;
2049	if (!list_empty(&res->recovering)) {
2050		mlog(0,
2051		     "Recovering res %s:%.*s, is already on recovery list!\n",
2052		     dlm->name, res->lockname.len, res->lockname.name);
2053		list_del_init(&res->recovering);
2054		dlm_lockres_put(res);
2055	}
2056	/* We need to hold a reference while on the recovery list */
2057	dlm_lockres_get(res);
2058	list_add_tail(&res->recovering, &dlm->reco.resources);
2059
2060	/* find any pending locks and put them back on proper list */
2061	for (i=DLM_BLOCKED_LIST; i>=DLM_GRANTED_LIST; i--) {
2062		queue = dlm_list_idx_to_ptr(res, i);
2063		list_for_each_entry_safe(lock, next, queue, list) {
2064			dlm_lock_get(lock);
2065			if (lock->convert_pending) {
2066				/* move converting lock back to granted */
2067				mlog(0, "node died with convert pending "
2068				     "on %.*s. move back to granted list.\n",
2069				     res->lockname.len, res->lockname.name);
2070				dlm_revert_pending_convert(res, lock);
2071				lock->convert_pending = 0;
2072			} else if (lock->lock_pending) {
2073				/* remove pending lock requests completely */
2074				BUG_ON(i != DLM_BLOCKED_LIST);
2075				mlog(0, "node died with lock pending "
2076				     "on %.*s. remove from blocked list and skip.\n",
2077				     res->lockname.len, res->lockname.name);
2078				/* lock will be floating until ref in
2079				 * dlmlock_remote is freed after the network
2080				 * call returns.  ok for it to not be on any
2081				 * list since no ast can be called
2082				 * (the master is dead). */
2083				dlm_revert_pending_lock(res, lock);
2084				lock->lock_pending = 0;
2085			} else if (lock->unlock_pending) {
2086				/* if an unlock was in progress, treat as
2087				 * if this had completed successfully
2088				 * before sending this lock state to the
2089				 * new master.  note that the dlm_unlock
2090				 * call is still responsible for calling
2091				 * the unlockast.  that will happen after
2092				 * the network call times out.  for now,
2093				 * just move lists to prepare the new
2094				 * recovery master.  */
2095				BUG_ON(i != DLM_GRANTED_LIST);
2096				mlog(0, "node died with unlock pending "
2097				     "on %.*s. remove from blocked list and skip.\n",
2098				     res->lockname.len, res->lockname.name);
2099				dlm_commit_pending_unlock(res, lock);
2100				lock->unlock_pending = 0;
2101			} else if (lock->cancel_pending) {
2102				/* if a cancel was in progress, treat as
2103				 * if this had completed successfully
2104				 * before sending this lock state to the
2105				 * new master */
2106				BUG_ON(i != DLM_CONVERTING_LIST);
2107				mlog(0, "node died with cancel pending "
2108				     "on %.*s. move back to granted list.\n",
2109				     res->lockname.len, res->lockname.name);
2110				dlm_commit_pending_cancel(res, lock);
2111				lock->cancel_pending = 0;
2112			}
2113			dlm_lock_put(lock);
2114		}
2115	}
2116}
2117
2118
2119
2120/* removes all recovered locks from the recovery list.
2121 * sets the res->owner to the new master.
2122 * unsets the RECOVERY flag and wakes waiters. */
2123static void dlm_finish_local_lockres_recovery(struct dlm_ctxt *dlm,
2124					      u8 dead_node, u8 new_master)
2125{
2126	int i;
2127	struct hlist_head *bucket;
2128	struct dlm_lock_resource *res, *next;
2129
2130	assert_spin_locked(&dlm->spinlock);
2131
2132	list_for_each_entry_safe(res, next, &dlm->reco.resources, recovering) {
2133		if (res->owner == dead_node) {
2134			mlog(0, "%s: res %.*s, Changing owner from %u to %u\n",
2135			     dlm->name, res->lockname.len, res->lockname.name,
2136			     res->owner, new_master);
2137			list_del_init(&res->recovering);
2138			spin_lock(&res->spinlock);
2139			/* new_master has our reference from
2140			 * the lock state sent during recovery */
2141			dlm_change_lockres_owner(dlm, res, new_master);
2142			res->state &= ~DLM_LOCK_RES_RECOVERING;
2143			if (__dlm_lockres_has_locks(res))
2144				__dlm_dirty_lockres(dlm, res);
2145			spin_unlock(&res->spinlock);
2146			wake_up(&res->wq);
2147			dlm_lockres_put(res);
2148		}
2149	}
2150
2151	/* this will become unnecessary eventually, but
2152	 * for now we need to run the whole hash, clear
2153	 * the RECOVERING state and set the owner
2154	 * if necessary */
2155	for (i = 0; i < DLM_HASH_BUCKETS; i++) {
2156		bucket = dlm_lockres_hash(dlm, i);
2157		hlist_for_each_entry(res, bucket, hash_node) {
2158			if (!(res->state & DLM_LOCK_RES_RECOVERING))
2159				continue;
2160
2161			if (res->owner != dead_node &&
2162			    res->owner != dlm->node_num)
2163				continue;
2164
2165			if (!list_empty(&res->recovering)) {
2166				list_del_init(&res->recovering);
2167				dlm_lockres_put(res);
2168			}
2169
2170			/* new_master has our reference from
2171			 * the lock state sent during recovery */
2172			mlog(0, "%s: res %.*s, Changing owner from %u to %u\n",
2173			     dlm->name, res->lockname.len, res->lockname.name,
2174			     res->owner, new_master);
2175			spin_lock(&res->spinlock);
2176			dlm_change_lockres_owner(dlm, res, new_master);
2177			res->state &= ~DLM_LOCK_RES_RECOVERING;
2178			if (__dlm_lockres_has_locks(res))
2179				__dlm_dirty_lockres(dlm, res);
2180			spin_unlock(&res->spinlock);
2181			wake_up(&res->wq);
2182		}
2183	}
2184}
2185
2186static inline int dlm_lvb_needs_invalidation(struct dlm_lock *lock, int local)
2187{
2188	if (local) {
2189		if (lock->ml.type != LKM_EXMODE &&
2190		    lock->ml.type != LKM_PRMODE)
2191			return 1;
2192	} else if (lock->ml.type == LKM_EXMODE)
2193		return 1;
2194	return 0;
2195}
2196
2197static void dlm_revalidate_lvb(struct dlm_ctxt *dlm,
2198			       struct dlm_lock_resource *res, u8 dead_node)
2199{
2200	struct list_head *queue;
2201	struct dlm_lock *lock;
2202	int blank_lvb = 0, local = 0;
2203	int i;
2204	u8 search_node;
2205
2206	assert_spin_locked(&dlm->spinlock);
2207	assert_spin_locked(&res->spinlock);
2208
2209	if (res->owner == dlm->node_num)
2210		/* if this node owned the lockres, and if the dead node
2211		 * had an EX when he died, blank out the lvb */
2212		search_node = dead_node;
2213	else {
2214		/* if this is a secondary lockres, and we had no EX or PR
2215		 * locks granted, we can no longer trust the lvb */
2216		search_node = dlm->node_num;
2217		local = 1;  /* check local state for valid lvb */
2218	}
2219
2220	for (i=DLM_GRANTED_LIST; i<=DLM_CONVERTING_LIST; i++) {
2221		queue = dlm_list_idx_to_ptr(res, i);
2222		list_for_each_entry(lock, queue, list) {
2223			if (lock->ml.node == search_node) {
2224				if (dlm_lvb_needs_invalidation(lock, local)) {
2225					/* zero the lksb lvb and lockres lvb */
2226					blank_lvb = 1;
2227					memset(lock->lksb->lvb, 0, DLM_LVB_LEN);
2228				}
2229			}
2230		}
2231	}
2232
2233	if (blank_lvb) {
2234		mlog(0, "clearing %.*s lvb, dead node %u had EX\n",
2235		     res->lockname.len, res->lockname.name, dead_node);
2236		memset(res->lvb, 0, DLM_LVB_LEN);
2237	}
2238}
2239
2240static void dlm_free_dead_locks(struct dlm_ctxt *dlm,
2241				struct dlm_lock_resource *res, u8 dead_node)
2242{
2243	struct dlm_lock *lock, *next;
2244	unsigned int freed = 0;
2245
2246	/* this node is the lockres master:
2247	 * 1) remove any stale locks for the dead node
2248	 * 2) if the dead node had an EX when he died, blank out the lvb
2249	 */
2250	assert_spin_locked(&dlm->spinlock);
2251	assert_spin_locked(&res->spinlock);
2252
2253	/* We do two dlm_lock_put(). One for removing from list and the other is
2254	 * to force the DLM_UNLOCK_FREE_LOCK action so as to free the locks */
2255
2256	/* TODO: check pending_asts, pending_basts here */
2257	list_for_each_entry_safe(lock, next, &res->granted, list) {
2258		if (lock->ml.node == dead_node) {
2259			list_del_init(&lock->list);
2260			dlm_lock_put(lock);
2261			/* Can't schedule DLM_UNLOCK_FREE_LOCK - do manually */
2262			dlm_lock_put(lock);
2263			freed++;
2264		}
2265	}
2266	list_for_each_entry_safe(lock, next, &res->converting, list) {
2267		if (lock->ml.node == dead_node) {
2268			list_del_init(&lock->list);
2269			dlm_lock_put(lock);
2270			/* Can't schedule DLM_UNLOCK_FREE_LOCK - do manually */
2271			dlm_lock_put(lock);
2272			freed++;
2273		}
2274	}
2275	list_for_each_entry_safe(lock, next, &res->blocked, list) {
2276		if (lock->ml.node == dead_node) {
2277			list_del_init(&lock->list);
2278			dlm_lock_put(lock);
2279			/* Can't schedule DLM_UNLOCK_FREE_LOCK - do manually */
2280			dlm_lock_put(lock);
2281			freed++;
2282		}
2283	}
2284
2285	if (freed) {
2286		mlog(0, "%s:%.*s: freed %u locks for dead node %u, "
2287		     "dropping ref from lockres\n", dlm->name,
2288		     res->lockname.len, res->lockname.name, freed, dead_node);
2289		if(!test_bit(dead_node, res->refmap)) {
2290			mlog(ML_ERROR, "%s:%.*s: freed %u locks for dead node %u, "
2291			     "but ref was not set\n", dlm->name,
2292			     res->lockname.len, res->lockname.name, freed, dead_node);
2293			__dlm_print_one_lock_resource(res);
2294		}
2295		dlm_lockres_clear_refmap_bit(dlm, res, dead_node);
2296	} else if (test_bit(dead_node, res->refmap)) {
2297		mlog(0, "%s:%.*s: dead node %u had a ref, but had "
2298		     "no locks and had not purged before dying\n", dlm->name,
2299		     res->lockname.len, res->lockname.name, dead_node);
2300		dlm_lockres_clear_refmap_bit(dlm, res, dead_node);
2301	}
2302
2303	/* do not kick thread yet */
2304	__dlm_dirty_lockres(dlm, res);
2305}
2306
2307/* if this node is the recovery master, and there are no
2308 * locks for a given lockres owned by this node that are in
2309 * either PR or EX mode, zero out the lvb before requesting.
2310 *
2311 */
2312
2313
2314static void dlm_do_local_recovery_cleanup(struct dlm_ctxt *dlm, u8 dead_node)
2315{
2316	struct dlm_lock_resource *res;
2317	int i;
2318	struct hlist_head *bucket;
2319	struct dlm_lock *lock;
2320
2321
2322	/* purge any stale mles */
2323	dlm_clean_master_list(dlm, dead_node);
2324
2325	/*
2326	 * now clean up all lock resources.  there are two rules:
2327	 *
2328	 * 1) if the dead node was the master, move the lockres
2329	 *    to the recovering list.  set the RECOVERING flag.
2330	 *    this lockres needs to be cleaned up before it can
2331	 *    be used further.
2332	 *
2333	 * 2) if this node was the master, remove all locks from
2334	 *    each of the lockres queues that were owned by the
2335	 *    dead node.  once recovery finishes, the dlm thread
2336	 *    can be kicked again to see if any ASTs or BASTs
2337	 *    need to be fired as a result.
2338	 */
2339	for (i = 0; i < DLM_HASH_BUCKETS; i++) {
2340		bucket = dlm_lockres_hash(dlm, i);
2341		hlist_for_each_entry(res, bucket, hash_node) {
2342 			/* always prune any $RECOVERY entries for dead nodes,
2343 			 * otherwise hangs can occur during later recovery */
2344			if (dlm_is_recovery_lock(res->lockname.name,
2345						 res->lockname.len)) {
2346				spin_lock(&res->spinlock);
2347				list_for_each_entry(lock, &res->granted, list) {
2348					if (lock->ml.node == dead_node) {
2349						mlog(0, "AHA! there was "
2350						     "a $RECOVERY lock for dead "
2351						     "node %u (%s)!\n",
2352						     dead_node, dlm->name);
2353						list_del_init(&lock->list);
2354						dlm_lock_put(lock);
2355						/* Can't schedule
2356						 * DLM_UNLOCK_FREE_LOCK
2357						 * - do manually */
2358						dlm_lock_put(lock);
2359						break;
2360					}
2361				}
2362				dlm_lockres_clear_refmap_bit(dlm, res,
2363						dead_node);
2364				spin_unlock(&res->spinlock);
2365				continue;
2366			}
2367			spin_lock(&res->spinlock);
2368			/* zero the lvb if necessary */
2369			dlm_revalidate_lvb(dlm, res, dead_node);
2370			if (res->owner == dead_node) {
2371				if (res->state & DLM_LOCK_RES_DROPPING_REF) {
2372					mlog(ML_NOTICE, "%s: res %.*s, Skip "
2373					     "recovery as it is being freed\n",
2374					     dlm->name, res->lockname.len,
2375					     res->lockname.name);
2376				} else
2377					dlm_move_lockres_to_recovery_list(dlm,
2378									  res);
2379
2380			} else if (res->owner == dlm->node_num) {
2381				dlm_free_dead_locks(dlm, res, dead_node);
2382				__dlm_lockres_calc_usage(dlm, res);
2383			} else if (res->owner == DLM_LOCK_RES_OWNER_UNKNOWN) {
2384				if (test_bit(dead_node, res->refmap)) {
2385					mlog(0, "%s:%.*s: dead node %u had a ref, but had "
2386						"no locks and had not purged before dying\n",
2387						dlm->name, res->lockname.len,
2388						res->lockname.name, dead_node);
2389					dlm_lockres_clear_refmap_bit(dlm, res, dead_node);
2390				}
2391			}
2392			spin_unlock(&res->spinlock);
2393		}
2394	}
2395
2396}
2397
2398static void __dlm_hb_node_down(struct dlm_ctxt *dlm, int idx)
2399{
2400	assert_spin_locked(&dlm->spinlock);
2401
2402	if (dlm->reco.new_master == idx) {
2403		mlog(0, "%s: recovery master %d just died\n",
2404		     dlm->name, idx);
2405		if (dlm->reco.state & DLM_RECO_STATE_FINALIZE) {
2406			/* finalize1 was reached, so it is safe to clear
2407			 * the new_master and dead_node.  that recovery
2408			 * is complete. */
2409			mlog(0, "%s: dead master %d had reached "
2410			     "finalize1 state, clearing\n", dlm->name, idx);
2411			dlm->reco.state &= ~DLM_RECO_STATE_FINALIZE;
2412			__dlm_reset_recovery(dlm);
2413		}
2414	}
2415
2416	/* Clean up join state on node death. */
2417	if (dlm->joining_node == idx) {
2418		mlog(0, "Clearing join state for node %u\n", idx);
2419		__dlm_set_joining_node(dlm, DLM_LOCK_RES_OWNER_UNKNOWN);
2420	}
2421
2422	/* check to see if the node is already considered dead */
2423	if (!test_bit(idx, dlm->live_nodes_map)) {
2424		mlog(0, "for domain %s, node %d is already dead. "
2425		     "another node likely did recovery already.\n",
2426		     dlm->name, idx);
2427		return;
2428	}
2429
2430	/* check to see if we do not care about this node */
2431	if (!test_bit(idx, dlm->domain_map)) {
2432		/* This also catches the case that we get a node down
2433		 * but haven't joined the domain yet. */
2434		mlog(0, "node %u already removed from domain!\n", idx);
2435		return;
2436	}
2437
2438	clear_bit(idx, dlm->live_nodes_map);
2439
2440	/* make sure local cleanup occurs before the heartbeat events */
2441	if (!test_bit(idx, dlm->recovery_map))
2442		dlm_do_local_recovery_cleanup(dlm, idx);
2443
2444	/* notify anything attached to the heartbeat events */
2445	dlm_hb_event_notify_attached(dlm, idx, 0);
2446
2447	mlog(0, "node %u being removed from domain map!\n", idx);
2448	clear_bit(idx, dlm->domain_map);
2449	clear_bit(idx, dlm->exit_domain_map);
2450	/* wake up migration waiters if a node goes down.
2451	 * perhaps later we can genericize this for other waiters. */
2452	wake_up(&dlm->migration_wq);
2453
2454	if (test_bit(idx, dlm->recovery_map))
2455		mlog(0, "domain %s, node %u already added "
2456		     "to recovery map!\n", dlm->name, idx);
2457	else
2458		set_bit(idx, dlm->recovery_map);
2459}
2460
2461void dlm_hb_node_down_cb(struct o2nm_node *node, int idx, void *data)
2462{
2463	struct dlm_ctxt *dlm = data;
2464
2465	if (!dlm_grab(dlm))
2466		return;
2467
2468	/*
2469	 * This will notify any dlm users that a node in our domain
2470	 * went away without notifying us first.
2471	 */
2472	if (test_bit(idx, dlm->domain_map))
2473		dlm_fire_domain_eviction_callbacks(dlm, idx);
2474
2475	spin_lock(&dlm->spinlock);
2476	__dlm_hb_node_down(dlm, idx);
2477	spin_unlock(&dlm->spinlock);
2478
2479	dlm_put(dlm);
2480}
2481
2482void dlm_hb_node_up_cb(struct o2nm_node *node, int idx, void *data)
2483{
2484	struct dlm_ctxt *dlm = data;
2485
2486	if (!dlm_grab(dlm))
2487		return;
2488
2489	spin_lock(&dlm->spinlock);
2490	set_bit(idx, dlm->live_nodes_map);
2491	/* do NOT notify mle attached to the heartbeat events.
2492	 * new nodes are not interesting in mastery until joined. */
2493	spin_unlock(&dlm->spinlock);
2494
2495	dlm_put(dlm);
2496}
2497
2498static void dlm_reco_ast(void *astdata)
2499{
2500	struct dlm_ctxt *dlm = astdata;
2501	mlog(0, "ast for recovery lock fired!, this=%u, dlm=%s\n",
2502	     dlm->node_num, dlm->name);
2503}
2504static void dlm_reco_bast(void *astdata, int blocked_type)
2505{
2506	struct dlm_ctxt *dlm = astdata;
2507	mlog(0, "bast for recovery lock fired!, this=%u, dlm=%s\n",
2508	     dlm->node_num, dlm->name);
2509}
2510static void dlm_reco_unlock_ast(void *astdata, enum dlm_status st)
2511{
2512	mlog(0, "unlockast for recovery lock fired!\n");
2513}
2514
2515/*
2516 * dlm_pick_recovery_master will continually attempt to use
2517 * dlmlock() on the special "$RECOVERY" lockres with the
2518 * LKM_NOQUEUE flag to get an EX.  every thread that enters
2519 * this function on each node racing to become the recovery
2520 * master will not stop attempting this until either:
2521 * a) this node gets the EX (and becomes the recovery master),
2522 * or b) dlm->reco.new_master gets set to some nodenum
2523 * != O2NM_INVALID_NODE_NUM (another node will do the reco).
2524 * so each time a recovery master is needed, the entire cluster
2525 * will sync at this point.  if the new master dies, that will
2526 * be detected in dlm_do_recovery */
2527static int dlm_pick_recovery_master(struct dlm_ctxt *dlm)
2528{
2529	enum dlm_status ret;
2530	struct dlm_lockstatus lksb;
2531	int status = -EINVAL;
2532
2533	mlog(0, "starting recovery of %s at %lu, dead=%u, this=%u\n",
2534	     dlm->name, jiffies, dlm->reco.dead_node, dlm->node_num);
2535again:
2536	memset(&lksb, 0, sizeof(lksb));
2537
2538	ret = dlmlock(dlm, LKM_EXMODE, &lksb, LKM_NOQUEUE|LKM_RECOVERY,
2539		      DLM_RECOVERY_LOCK_NAME, DLM_RECOVERY_LOCK_NAME_LEN,
2540		      dlm_reco_ast, dlm, dlm_reco_bast);
2541
2542	mlog(0, "%s: dlmlock($RECOVERY) returned %d, lksb=%d\n",
2543	     dlm->name, ret, lksb.status);
2544
2545	if (ret == DLM_NORMAL) {
2546		mlog(0, "dlm=%s dlmlock says I got it (this=%u)\n",
2547		     dlm->name, dlm->node_num);
2548
2549		/* got the EX lock.  check to see if another node
2550		 * just became the reco master */
2551		if (dlm_reco_master_ready(dlm)) {
2552			mlog(0, "%s: got reco EX lock, but %u will "
2553			     "do the recovery\n", dlm->name,
2554			     dlm->reco.new_master);
2555			status = -EEXIST;
2556		} else {
2557			status = 0;
2558
2559			/* see if recovery was already finished elsewhere */
2560			spin_lock(&dlm->spinlock);
2561			if (dlm->reco.dead_node == O2NM_INVALID_NODE_NUM) {
2562				status = -EINVAL;
2563				mlog(0, "%s: got reco EX lock, but "
2564				     "node got recovered already\n", dlm->name);
2565				if (dlm->reco.new_master != O2NM_INVALID_NODE_NUM) {
2566					mlog(ML_ERROR, "%s: new master is %u "
2567					     "but no dead node!\n",
2568					     dlm->name, dlm->reco.new_master);
2569					BUG();
2570				}
2571			}
2572			spin_unlock(&dlm->spinlock);
2573		}
2574
2575		/* if this node has actually become the recovery master,
2576		 * set the master and send the messages to begin recovery */
2577		if (!status) {
2578			mlog(0, "%s: dead=%u, this=%u, sending "
2579			     "begin_reco now\n", dlm->name,
2580			     dlm->reco.dead_node, dlm->node_num);
2581			status = dlm_send_begin_reco_message(dlm,
2582				      dlm->reco.dead_node);
2583			/* this always succeeds */
2584			BUG_ON(status);
2585
2586			/* set the new_master to this node */
2587			spin_lock(&dlm->spinlock);
2588			dlm_set_reco_master(dlm, dlm->node_num);
2589			spin_unlock(&dlm->spinlock);
2590		}
2591
2592		/* recovery lock is a special case.  ast will not get fired,
2593		 * so just go ahead and unlock it. */
2594		ret = dlmunlock(dlm, &lksb, 0, dlm_reco_unlock_ast, dlm);
2595		if (ret == DLM_DENIED) {
2596			mlog(0, "got DLM_DENIED, trying LKM_CANCEL\n");
2597			ret = dlmunlock(dlm, &lksb, LKM_CANCEL, dlm_reco_unlock_ast, dlm);
2598		}
2599		if (ret != DLM_NORMAL) {
2600			/* this would really suck. this could only happen
2601			 * if there was a network error during the unlock
2602			 * because of node death.  this means the unlock
2603			 * is actually "done" and the lock structure is
2604			 * even freed.  we can continue, but only
2605			 * because this specific lock name is special. */
2606			mlog(ML_ERROR, "dlmunlock returned %d\n", ret);
2607		}
2608	} else if (ret == DLM_NOTQUEUED) {
2609		mlog(0, "dlm=%s dlmlock says another node got it (this=%u)\n",
2610		     dlm->name, dlm->node_num);
2611		/* another node is master. wait on
2612		 * reco.new_master != O2NM_INVALID_NODE_NUM
2613		 * for at most one second */
2614		wait_event_timeout(dlm->dlm_reco_thread_wq,
2615					 dlm_reco_master_ready(dlm),
2616					 msecs_to_jiffies(1000));
2617		if (!dlm_reco_master_ready(dlm)) {
2618			mlog(0, "%s: reco master taking awhile\n",
2619			     dlm->name);
2620			goto again;
2621		}
2622		/* another node has informed this one that it is reco master */
2623		mlog(0, "%s: reco master %u is ready to recover %u\n",
2624		     dlm->name, dlm->reco.new_master, dlm->reco.dead_node);
2625		status = -EEXIST;
2626	} else if (ret == DLM_RECOVERING) {
2627		mlog(0, "dlm=%s dlmlock says master node died (this=%u)\n",
2628		     dlm->name, dlm->node_num);
2629		goto again;
2630	} else {
2631		struct dlm_lock_resource *res;
2632
2633		/* dlmlock returned something other than NOTQUEUED or NORMAL */
2634		mlog(ML_ERROR, "%s: got %s from dlmlock($RECOVERY), "
2635		     "lksb.status=%s\n", dlm->name, dlm_errname(ret),
2636		     dlm_errname(lksb.status));
2637		res = dlm_lookup_lockres(dlm, DLM_RECOVERY_LOCK_NAME,
2638					 DLM_RECOVERY_LOCK_NAME_LEN);
2639		if (res) {
2640			dlm_print_one_lock_resource(res);
2641			dlm_lockres_put(res);
2642		} else {
2643			mlog(ML_ERROR, "recovery lock not found\n");
2644		}
2645		BUG();
2646	}
2647
2648	return status;
2649}
2650
2651static int dlm_send_begin_reco_message(struct dlm_ctxt *dlm, u8 dead_node)
2652{
2653	struct dlm_begin_reco br;
2654	int ret = 0;
2655	struct dlm_node_iter iter;
2656	int nodenum;
2657	int status;
2658
2659	mlog(0, "%s: dead node is %u\n", dlm->name, dead_node);
2660
2661	spin_lock(&dlm->spinlock);
2662	dlm_node_iter_init(dlm->domain_map, &iter);
2663	spin_unlock(&dlm->spinlock);
2664
2665	clear_bit(dead_node, iter.node_map);
2666
2667	memset(&br, 0, sizeof(br));
2668	br.node_idx = dlm->node_num;
2669	br.dead_node = dead_node;
2670
2671	while ((nodenum = dlm_node_iter_next(&iter)) >= 0) {
2672		ret = 0;
2673		if (nodenum == dead_node) {
2674			mlog(0, "not sending begin reco to dead node "
2675				  "%u\n", dead_node);
2676			continue;
2677		}
2678		if (nodenum == dlm->node_num) {
2679			mlog(0, "not sending begin reco to self\n");
2680			continue;
2681		}
2682retry:
2683		ret = -EINVAL;
2684		mlog(0, "attempting to send begin reco msg to %d\n",
2685			  nodenum);
2686		ret = o2net_send_message(DLM_BEGIN_RECO_MSG, dlm->key,
2687					 &br, sizeof(br), nodenum, &status);
2688		/* negative status is handled ok by caller here */
2689		if (ret >= 0)
2690			ret = status;
2691		if (dlm_is_host_down(ret)) {
2692			/* node is down.  not involved in recovery
2693			 * so just keep going */
2694			mlog(ML_NOTICE, "%s: node %u was down when sending "
2695			     "begin reco msg (%d)\n", dlm->name, nodenum, ret);
2696			ret = 0;
2697		}
2698
2699		/*
2700		 * Prior to commit aad1b15310b9bcd59fa81ab8f2b1513b59553ea8,
2701		 * dlm_begin_reco_handler() returned EAGAIN and not -EAGAIN.
2702		 * We are handling both for compatibility reasons.
2703		 */
2704		if (ret == -EAGAIN || ret == EAGAIN) {
2705			mlog(0, "%s: trying to start recovery of node "
2706			     "%u, but node %u is waiting for last recovery "
2707			     "to complete, backoff for a bit\n", dlm->name,
2708			     dead_node, nodenum);
2709			msleep(100);
2710			goto retry;
2711		}
2712		if (ret < 0) {
2713			struct dlm_lock_resource *res;
2714
2715			/* this is now a serious problem, possibly ENOMEM
2716			 * in the network stack.  must retry */
2717			mlog_errno(ret);
2718			mlog(ML_ERROR, "begin reco of dlm %s to node %u "
2719			     "returned %d\n", dlm->name, nodenum, ret);
2720			res = dlm_lookup_lockres(dlm, DLM_RECOVERY_LOCK_NAME,
2721						 DLM_RECOVERY_LOCK_NAME_LEN);
2722			if (res) {
2723				dlm_print_one_lock_resource(res);
2724				dlm_lockres_put(res);
2725			} else {
2726				mlog(ML_ERROR, "recovery lock not found\n");
2727			}
2728			/* sleep for a bit in hopes that we can avoid
2729			 * another ENOMEM */
2730			msleep(100);
2731			goto retry;
2732		}
2733	}
2734
2735	return ret;
2736}
2737
2738int dlm_begin_reco_handler(struct o2net_msg *msg, u32 len, void *data,
2739			   void **ret_data)
2740{
2741	struct dlm_ctxt *dlm = data;
2742	struct dlm_begin_reco *br = (struct dlm_begin_reco *)msg->buf;
2743
2744	/* ok to return 0, domain has gone away */
2745	if (!dlm_grab(dlm))
2746		return 0;
2747
2748	spin_lock(&dlm->spinlock);
2749	if (dlm->reco.state & DLM_RECO_STATE_FINALIZE) {
2750		mlog(0, "%s: node %u wants to recover node %u (%u:%u) "
2751		     "but this node is in finalize state, waiting on finalize2\n",
2752		     dlm->name, br->node_idx, br->dead_node,
2753		     dlm->reco.dead_node, dlm->reco.new_master);
2754		spin_unlock(&dlm->spinlock);
2755		dlm_put(dlm);
2756		return -EAGAIN;
2757	}
2758	spin_unlock(&dlm->spinlock);
2759
2760	mlog(0, "%s: node %u wants to recover node %u (%u:%u)\n",
2761	     dlm->name, br->node_idx, br->dead_node,
2762	     dlm->reco.dead_node, dlm->reco.new_master);
2763
2764	dlm_fire_domain_eviction_callbacks(dlm, br->dead_node);
2765
2766	spin_lock(&dlm->spinlock);
2767	if (dlm->reco.new_master != O2NM_INVALID_NODE_NUM) {
2768		if (test_bit(dlm->reco.new_master, dlm->recovery_map)) {
2769			mlog(0, "%s: new_master %u died, changing "
2770			     "to %u\n", dlm->name, dlm->reco.new_master,
2771			     br->node_idx);
2772		} else {
2773			mlog(0, "%s: new_master %u NOT DEAD, changing "
2774			     "to %u\n", dlm->name, dlm->reco.new_master,
2775			     br->node_idx);
2776			/* may not have seen the new master as dead yet */
2777		}
2778	}
2779	if (dlm->reco.dead_node != O2NM_INVALID_NODE_NUM) {
2780		mlog(ML_NOTICE, "%s: dead_node previously set to %u, "
2781		     "node %u changing it to %u\n", dlm->name,
2782		     dlm->reco.dead_node, br->node_idx, br->dead_node);
2783	}
2784	dlm_set_reco_master(dlm, br->node_idx);
2785	dlm_set_reco_dead_node(dlm, br->dead_node);
2786	if (!test_bit(br->dead_node, dlm->recovery_map)) {
2787		mlog(0, "recovery master %u sees %u as dead, but this "
2788		     "node has not yet.  marking %u as dead\n",
2789		     br->node_idx, br->dead_node, br->dead_node);
2790		if (!test_bit(br->dead_node, dlm->domain_map) ||
2791		    !test_bit(br->dead_node, dlm->live_nodes_map))
2792			mlog(0, "%u not in domain/live_nodes map "
2793			     "so setting it in reco map manually\n",
2794			     br->dead_node);
2795		/* force the recovery cleanup in __dlm_hb_node_down
2796		 * both of these will be cleared in a moment */
2797		set_bit(br->dead_node, dlm->domain_map);
2798		set_bit(br->dead_node, dlm->live_nodes_map);
2799		__dlm_hb_node_down(dlm, br->dead_node);
2800	}
2801	spin_unlock(&dlm->spinlock);
2802
2803	dlm_kick_recovery_thread(dlm);
2804
2805	mlog(0, "%s: recovery started by node %u, for %u (%u:%u)\n",
2806	     dlm->name, br->node_idx, br->dead_node,
2807	     dlm->reco.dead_node, dlm->reco.new_master);
2808
2809	dlm_put(dlm);
2810	return 0;
2811}
2812
2813#define DLM_FINALIZE_STAGE2  0x01
2814static int dlm_send_finalize_reco_message(struct dlm_ctxt *dlm)
2815{
2816	int ret = 0;
2817	struct dlm_finalize_reco fr;
2818	struct dlm_node_iter iter;
2819	int nodenum;
2820	int status;
2821	int stage = 1;
2822
2823	mlog(0, "finishing recovery for node %s:%u, "
2824	     "stage %d\n", dlm->name, dlm->reco.dead_node, stage);
2825
2826	spin_lock(&dlm->spinlock);
2827	dlm_node_iter_init(dlm->domain_map, &iter);
2828	spin_unlock(&dlm->spinlock);
2829
2830stage2:
2831	memset(&fr, 0, sizeof(fr));
2832	fr.node_idx = dlm->node_num;
2833	fr.dead_node = dlm->reco.dead_node;
2834	if (stage == 2)
2835		fr.flags |= DLM_FINALIZE_STAGE2;
2836
2837	while ((nodenum = dlm_node_iter_next(&iter)) >= 0) {
2838		if (nodenum == dlm->node_num)
2839			continue;
2840		ret = o2net_send_message(DLM_FINALIZE_RECO_MSG, dlm->key,
2841					 &fr, sizeof(fr), nodenum, &status);
2842		if (ret >= 0)
2843			ret = status;
2844		if (ret < 0) {
2845			mlog(ML_ERROR, "Error %d when sending message %u (key "
2846			     "0x%x) to node %u\n", ret, DLM_FINALIZE_RECO_MSG,
2847			     dlm->key, nodenum);
2848			if (dlm_is_host_down(ret)) {
2849				/* this has no effect on this recovery
2850				 * session, so set the status to zero to
2851				 * finish out the last recovery */
2852				mlog(ML_ERROR, "node %u went down after this "
2853				     "node finished recovery.\n", nodenum);
2854				ret = 0;
2855				continue;
2856			}
2857			break;
2858		}
2859	}
2860	if (stage == 1) {
2861		/* reset the node_iter back to the top and send finalize2 */
2862		iter.curnode = -1;
2863		stage = 2;
2864		goto stage2;
2865	}
2866
2867	return ret;
2868}
2869
2870int dlm_finalize_reco_handler(struct o2net_msg *msg, u32 len, void *data,
2871			      void **ret_data)
2872{
2873	struct dlm_ctxt *dlm = data;
2874	struct dlm_finalize_reco *fr = (struct dlm_finalize_reco *)msg->buf;
2875	int stage = 1;
2876
2877	/* ok to return 0, domain has gone away */
2878	if (!dlm_grab(dlm))
2879		return 0;
2880
2881	if (fr->flags & DLM_FINALIZE_STAGE2)
2882		stage = 2;
2883
2884	mlog(0, "%s: node %u finalizing recovery stage%d of "
2885	     "node %u (%u:%u)\n", dlm->name, fr->node_idx, stage,
2886	     fr->dead_node, dlm->reco.dead_node, dlm->reco.new_master);
2887
2888	spin_lock(&dlm->spinlock);
2889
2890	if (dlm->reco.new_master != fr->node_idx) {
2891		mlog(ML_ERROR, "node %u sent recovery finalize msg, but node "
2892		     "%u is supposed to be the new master, dead=%u\n",
2893		     fr->node_idx, dlm->reco.new_master, fr->dead_node);
2894		BUG();
2895	}
2896	if (dlm->reco.dead_node != fr->dead_node) {
2897		mlog(ML_ERROR, "node %u sent recovery finalize msg for dead "
2898		     "node %u, but node %u is supposed to be dead\n",
2899		     fr->node_idx, fr->dead_node, dlm->reco.dead_node);
2900		BUG();
2901	}
2902
2903	switch (stage) {
2904		case 1:
2905			dlm_finish_local_lockres_recovery(dlm, fr->dead_node, fr->node_idx);
2906			if (dlm->reco.state & DLM_RECO_STATE_FINALIZE) {
2907				mlog(ML_ERROR, "%s: received finalize1 from "
2908				     "new master %u for dead node %u, but "
2909				     "this node has already received it!\n",
2910				     dlm->name, fr->node_idx, fr->dead_node);
2911				dlm_print_reco_node_status(dlm);
2912				BUG();
2913			}
2914			dlm->reco.state |= DLM_RECO_STATE_FINALIZE;
2915			spin_unlock(&dlm->spinlock);
2916			break;
2917		case 2:
2918			if (!(dlm->reco.state & DLM_RECO_STATE_FINALIZE)) {
2919				mlog(ML_ERROR, "%s: received finalize2 from "
2920				     "new master %u for dead node %u, but "
2921				     "this node did not have finalize1!\n",
2922				     dlm->name, fr->node_idx, fr->dead_node);
2923				dlm_print_reco_node_status(dlm);
2924				BUG();
2925			}
2926			dlm->reco.state &= ~DLM_RECO_STATE_FINALIZE;
2927			__dlm_reset_recovery(dlm);
2928			spin_unlock(&dlm->spinlock);
2929			dlm_kick_recovery_thread(dlm);
2930			break;
2931		default:
2932			BUG();
2933	}
2934
2935	mlog(0, "%s: recovery done, reco master was %u, dead now %u, master now %u\n",
2936	     dlm->name, fr->node_idx, dlm->reco.dead_node, dlm->reco.new_master);
2937
2938	dlm_put(dlm);
2939	return 0;
2940}
2941