block: make blkdev_get/put() handle exclusive access
[linux-2.6.git] / fs / ocfs2 / cluster / heartbeat.c
1 /* -*- mode: c; c-basic-offset: 8; -*-
2  * vim: noexpandtab sw=8 ts=8 sts=0:
3  *
4  * Copyright (C) 2004, 2005 Oracle.  All rights reserved.
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public
8  * License as published by the Free Software Foundation; either
9  * version 2 of the License, or (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public
17  * License along with this program; if not, write to the
18  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19  * Boston, MA 021110-1307, USA.
20  */
21
22 #include <linux/kernel.h>
23 #include <linux/sched.h>
24 #include <linux/jiffies.h>
25 #include <linux/module.h>
26 #include <linux/fs.h>
27 #include <linux/bio.h>
28 #include <linux/blkdev.h>
29 #include <linux/delay.h>
30 #include <linux/file.h>
31 #include <linux/kthread.h>
32 #include <linux/configfs.h>
33 #include <linux/random.h>
34 #include <linux/crc32.h>
35 #include <linux/time.h>
36 #include <linux/debugfs.h>
37 #include <linux/slab.h>
38
39 #include "heartbeat.h"
40 #include "tcp.h"
41 #include "nodemanager.h"
42 #include "quorum.h"
43
44 #include "masklog.h"
45
46
47 /*
48  * The first heartbeat pass had one global thread that would serialize all hb
49  * callback calls.  This global serializing sem should only be removed once
50  * we've made sure that all callees can deal with being called concurrently
51  * from multiple hb region threads.
52  */
53 static DECLARE_RWSEM(o2hb_callback_sem);
54
55 /*
56  * multiple hb threads are watching multiple regions.  A node is live
57  * whenever any of the threads sees activity from the node in its region.
58  */
59 static DEFINE_SPINLOCK(o2hb_live_lock);
60 static struct list_head o2hb_live_slots[O2NM_MAX_NODES];
61 static unsigned long o2hb_live_node_bitmap[BITS_TO_LONGS(O2NM_MAX_NODES)];
62 static LIST_HEAD(o2hb_node_events);
63 static DECLARE_WAIT_QUEUE_HEAD(o2hb_steady_queue);
64
65 /*
66  * In global heartbeat, we maintain a series of region bitmaps.
67  *      - o2hb_region_bitmap allows us to limit the region number to max region.
68  *      - o2hb_live_region_bitmap tracks live regions (seen steady iterations).
69  *      - o2hb_quorum_region_bitmap tracks live regions that have seen all nodes
70  *              heartbeat on it.
71  *      - o2hb_failed_region_bitmap tracks the regions that have seen io timeouts.
72  */
73 static unsigned long o2hb_region_bitmap[BITS_TO_LONGS(O2NM_MAX_REGIONS)];
74 static unsigned long o2hb_live_region_bitmap[BITS_TO_LONGS(O2NM_MAX_REGIONS)];
75 static unsigned long o2hb_quorum_region_bitmap[BITS_TO_LONGS(O2NM_MAX_REGIONS)];
76 static unsigned long o2hb_failed_region_bitmap[BITS_TO_LONGS(O2NM_MAX_REGIONS)];
77
78 #define O2HB_DB_TYPE_LIVENODES          0
79 #define O2HB_DB_TYPE_LIVEREGIONS        1
80 #define O2HB_DB_TYPE_QUORUMREGIONS      2
81 #define O2HB_DB_TYPE_FAILEDREGIONS      3
82 #define O2HB_DB_TYPE_REGION_LIVENODES   4
83 #define O2HB_DB_TYPE_REGION_NUMBER      5
84 #define O2HB_DB_TYPE_REGION_ELAPSED_TIME        6
85 struct o2hb_debug_buf {
86         int db_type;
87         int db_size;
88         int db_len;
89         void *db_data;
90 };
91
92 static struct o2hb_debug_buf *o2hb_db_livenodes;
93 static struct o2hb_debug_buf *o2hb_db_liveregions;
94 static struct o2hb_debug_buf *o2hb_db_quorumregions;
95 static struct o2hb_debug_buf *o2hb_db_failedregions;
96
97 #define O2HB_DEBUG_DIR                  "o2hb"
98 #define O2HB_DEBUG_LIVENODES            "livenodes"
99 #define O2HB_DEBUG_LIVEREGIONS          "live_regions"
100 #define O2HB_DEBUG_QUORUMREGIONS        "quorum_regions"
101 #define O2HB_DEBUG_FAILEDREGIONS        "failed_regions"
102 #define O2HB_DEBUG_REGION_NUMBER        "num"
103 #define O2HB_DEBUG_REGION_ELAPSED_TIME  "elapsed_time_in_ms"
104
105 static struct dentry *o2hb_debug_dir;
106 static struct dentry *o2hb_debug_livenodes;
107 static struct dentry *o2hb_debug_liveregions;
108 static struct dentry *o2hb_debug_quorumregions;
109 static struct dentry *o2hb_debug_failedregions;
110
111 static LIST_HEAD(o2hb_all_regions);
112
113 static struct o2hb_callback {
114         struct list_head list;
115 } o2hb_callbacks[O2HB_NUM_CB];
116
117 static struct o2hb_callback *hbcall_from_type(enum o2hb_callback_type type);
118
119 #define O2HB_DEFAULT_BLOCK_BITS       9
120
121 enum o2hb_heartbeat_modes {
122         O2HB_HEARTBEAT_LOCAL            = 0,
123         O2HB_HEARTBEAT_GLOBAL,
124         O2HB_HEARTBEAT_NUM_MODES,
125 };
126
127 char *o2hb_heartbeat_mode_desc[O2HB_HEARTBEAT_NUM_MODES] = {
128                 "local",        /* O2HB_HEARTBEAT_LOCAL */
129                 "global",       /* O2HB_HEARTBEAT_GLOBAL */
130 };
131
132 unsigned int o2hb_dead_threshold = O2HB_DEFAULT_DEAD_THRESHOLD;
133 unsigned int o2hb_heartbeat_mode = O2HB_HEARTBEAT_LOCAL;
134
135 /* Only sets a new threshold if there are no active regions.
136  *
137  * No locking or otherwise interesting code is required for reading
138  * o2hb_dead_threshold as it can't change once regions are active and
139  * it's not interesting to anyone until then anyway. */
140 static void o2hb_dead_threshold_set(unsigned int threshold)
141 {
142         if (threshold > O2HB_MIN_DEAD_THRESHOLD) {
143                 spin_lock(&o2hb_live_lock);
144                 if (list_empty(&o2hb_all_regions))
145                         o2hb_dead_threshold = threshold;
146                 spin_unlock(&o2hb_live_lock);
147         }
148 }
149
150 static int o2hb_global_hearbeat_mode_set(unsigned int hb_mode)
151 {
152         int ret = -1;
153
154         if (hb_mode < O2HB_HEARTBEAT_NUM_MODES) {
155                 spin_lock(&o2hb_live_lock);
156                 if (list_empty(&o2hb_all_regions)) {
157                         o2hb_heartbeat_mode = hb_mode;
158                         ret = 0;
159                 }
160                 spin_unlock(&o2hb_live_lock);
161         }
162
163         return ret;
164 }
165
166 struct o2hb_node_event {
167         struct list_head        hn_item;
168         enum o2hb_callback_type hn_event_type;
169         struct o2nm_node        *hn_node;
170         int                     hn_node_num;
171 };
172
173 struct o2hb_disk_slot {
174         struct o2hb_disk_heartbeat_block *ds_raw_block;
175         u8                      ds_node_num;
176         u64                     ds_last_time;
177         u64                     ds_last_generation;
178         u16                     ds_equal_samples;
179         u16                     ds_changed_samples;
180         struct list_head        ds_live_item;
181 };
182
183 /* each thread owns a region.. when we're asked to tear down the region
184  * we ask the thread to stop, who cleans up the region */
185 struct o2hb_region {
186         struct config_item      hr_item;
187
188         struct list_head        hr_all_item;
189         unsigned                hr_unclean_stop:1;
190
191         /* protected by the hr_callback_sem */
192         struct task_struct      *hr_task;
193
194         unsigned int            hr_blocks;
195         unsigned long long      hr_start_block;
196
197         unsigned int            hr_block_bits;
198         unsigned int            hr_block_bytes;
199
200         unsigned int            hr_slots_per_page;
201         unsigned int            hr_num_pages;
202
203         struct page             **hr_slot_data;
204         struct block_device     *hr_bdev;
205         struct o2hb_disk_slot   *hr_slots;
206
207         /* live node map of this region */
208         unsigned long           hr_live_node_bitmap[BITS_TO_LONGS(O2NM_MAX_NODES)];
209         unsigned int            hr_region_num;
210
211         struct dentry           *hr_debug_dir;
212         struct dentry           *hr_debug_livenodes;
213         struct dentry           *hr_debug_regnum;
214         struct dentry           *hr_debug_elapsed_time;
215         struct o2hb_debug_buf   *hr_db_livenodes;
216         struct o2hb_debug_buf   *hr_db_regnum;
217         struct o2hb_debug_buf   *hr_db_elapsed_time;
218
219         /* let the person setting up hb wait for it to return until it
220          * has reached a 'steady' state.  This will be fixed when we have
221          * a more complete api that doesn't lead to this sort of fragility. */
222         atomic_t                hr_steady_iterations;
223
224         char                    hr_dev_name[BDEVNAME_SIZE];
225
226         unsigned int            hr_timeout_ms;
227
228         /* randomized as the region goes up and down so that a node
229          * recognizes a node going up and down in one iteration */
230         u64                     hr_generation;
231
232         struct delayed_work     hr_write_timeout_work;
233         unsigned long           hr_last_timeout_start;
234
235         /* Used during o2hb_check_slot to hold a copy of the block
236          * being checked because we temporarily have to zero out the
237          * crc field. */
238         struct o2hb_disk_heartbeat_block *hr_tmp_block;
239 };
240
241 struct o2hb_bio_wait_ctxt {
242         atomic_t          wc_num_reqs;
243         struct completion wc_io_complete;
244         int               wc_error;
245 };
246
247 static int o2hb_pop_count(void *map, int count)
248 {
249         int i = -1, pop = 0;
250
251         while ((i = find_next_bit(map, count, i + 1)) < count)
252                 pop++;
253         return pop;
254 }
255
256 static void o2hb_write_timeout(struct work_struct *work)
257 {
258         int failed, quorum;
259         unsigned long flags;
260         struct o2hb_region *reg =
261                 container_of(work, struct o2hb_region,
262                              hr_write_timeout_work.work);
263
264         mlog(ML_ERROR, "Heartbeat write timeout to device %s after %u "
265              "milliseconds\n", reg->hr_dev_name,
266              jiffies_to_msecs(jiffies - reg->hr_last_timeout_start));
267
268         if (o2hb_global_heartbeat_active()) {
269                 spin_lock_irqsave(&o2hb_live_lock, flags);
270                 if (test_bit(reg->hr_region_num, o2hb_quorum_region_bitmap))
271                         set_bit(reg->hr_region_num, o2hb_failed_region_bitmap);
272                 failed = o2hb_pop_count(&o2hb_failed_region_bitmap,
273                                         O2NM_MAX_REGIONS);
274                 quorum = o2hb_pop_count(&o2hb_quorum_region_bitmap,
275                                         O2NM_MAX_REGIONS);
276                 spin_unlock_irqrestore(&o2hb_live_lock, flags);
277
278                 mlog(ML_HEARTBEAT, "Number of regions %d, failed regions %d\n",
279                      quorum, failed);
280
281                 /*
282                  * Fence if the number of failed regions >= half the number
283                  * of  quorum regions
284                  */
285                 if ((failed << 1) < quorum)
286                         return;
287         }
288
289         o2quo_disk_timeout();
290 }
291
292 static void o2hb_arm_write_timeout(struct o2hb_region *reg)
293 {
294         mlog(ML_HEARTBEAT, "Queue write timeout for %u ms\n",
295              O2HB_MAX_WRITE_TIMEOUT_MS);
296
297         if (o2hb_global_heartbeat_active()) {
298                 spin_lock(&o2hb_live_lock);
299                 clear_bit(reg->hr_region_num, o2hb_failed_region_bitmap);
300                 spin_unlock(&o2hb_live_lock);
301         }
302         cancel_delayed_work(&reg->hr_write_timeout_work);
303         reg->hr_last_timeout_start = jiffies;
304         schedule_delayed_work(&reg->hr_write_timeout_work,
305                               msecs_to_jiffies(O2HB_MAX_WRITE_TIMEOUT_MS));
306 }
307
308 static void o2hb_disarm_write_timeout(struct o2hb_region *reg)
309 {
310         cancel_delayed_work(&reg->hr_write_timeout_work);
311         flush_scheduled_work();
312 }
313
314 static inline void o2hb_bio_wait_init(struct o2hb_bio_wait_ctxt *wc)
315 {
316         atomic_set(&wc->wc_num_reqs, 1);
317         init_completion(&wc->wc_io_complete);
318         wc->wc_error = 0;
319 }
320
321 /* Used in error paths too */
322 static inline void o2hb_bio_wait_dec(struct o2hb_bio_wait_ctxt *wc,
323                                      unsigned int num)
324 {
325         /* sadly atomic_sub_and_test() isn't available on all platforms.  The
326          * good news is that the fast path only completes one at a time */
327         while(num--) {
328                 if (atomic_dec_and_test(&wc->wc_num_reqs)) {
329                         BUG_ON(num > 0);
330                         complete(&wc->wc_io_complete);
331                 }
332         }
333 }
334
335 static void o2hb_wait_on_io(struct o2hb_region *reg,
336                             struct o2hb_bio_wait_ctxt *wc)
337 {
338         struct address_space *mapping = reg->hr_bdev->bd_inode->i_mapping;
339
340         blk_run_address_space(mapping);
341         o2hb_bio_wait_dec(wc, 1);
342
343         wait_for_completion(&wc->wc_io_complete);
344 }
345
346 static void o2hb_bio_end_io(struct bio *bio,
347                            int error)
348 {
349         struct o2hb_bio_wait_ctxt *wc = bio->bi_private;
350
351         if (error) {
352                 mlog(ML_ERROR, "IO Error %d\n", error);
353                 wc->wc_error = error;
354         }
355
356         o2hb_bio_wait_dec(wc, 1);
357         bio_put(bio);
358 }
359
360 /* Setup a Bio to cover I/O against num_slots slots starting at
361  * start_slot. */
362 static struct bio *o2hb_setup_one_bio(struct o2hb_region *reg,
363                                       struct o2hb_bio_wait_ctxt *wc,
364                                       unsigned int *current_slot,
365                                       unsigned int max_slots)
366 {
367         int len, current_page;
368         unsigned int vec_len, vec_start;
369         unsigned int bits = reg->hr_block_bits;
370         unsigned int spp = reg->hr_slots_per_page;
371         unsigned int cs = *current_slot;
372         struct bio *bio;
373         struct page *page;
374
375         /* Testing has shown this allocation to take long enough under
376          * GFP_KERNEL that the local node can get fenced. It would be
377          * nicest if we could pre-allocate these bios and avoid this
378          * all together. */
379         bio = bio_alloc(GFP_ATOMIC, 16);
380         if (!bio) {
381                 mlog(ML_ERROR, "Could not alloc slots BIO!\n");
382                 bio = ERR_PTR(-ENOMEM);
383                 goto bail;
384         }
385
386         /* Must put everything in 512 byte sectors for the bio... */
387         bio->bi_sector = (reg->hr_start_block + cs) << (bits - 9);
388         bio->bi_bdev = reg->hr_bdev;
389         bio->bi_private = wc;
390         bio->bi_end_io = o2hb_bio_end_io;
391
392         vec_start = (cs << bits) % PAGE_CACHE_SIZE;
393         while(cs < max_slots) {
394                 current_page = cs / spp;
395                 page = reg->hr_slot_data[current_page];
396
397                 vec_len = min(PAGE_CACHE_SIZE - vec_start,
398                               (max_slots-cs) * (PAGE_CACHE_SIZE/spp) );
399
400                 mlog(ML_HB_BIO, "page %d, vec_len = %u, vec_start = %u\n",
401                      current_page, vec_len, vec_start);
402
403                 len = bio_add_page(bio, page, vec_len, vec_start);
404                 if (len != vec_len) break;
405
406                 cs += vec_len / (PAGE_CACHE_SIZE/spp);
407                 vec_start = 0;
408         }
409
410 bail:
411         *current_slot = cs;
412         return bio;
413 }
414
415 static int o2hb_read_slots(struct o2hb_region *reg,
416                            unsigned int max_slots)
417 {
418         unsigned int current_slot=0;
419         int status;
420         struct o2hb_bio_wait_ctxt wc;
421         struct bio *bio;
422
423         o2hb_bio_wait_init(&wc);
424
425         while(current_slot < max_slots) {
426                 bio = o2hb_setup_one_bio(reg, &wc, &current_slot, max_slots);
427                 if (IS_ERR(bio)) {
428                         status = PTR_ERR(bio);
429                         mlog_errno(status);
430                         goto bail_and_wait;
431                 }
432
433                 atomic_inc(&wc.wc_num_reqs);
434                 submit_bio(READ, bio);
435         }
436
437         status = 0;
438
439 bail_and_wait:
440         o2hb_wait_on_io(reg, &wc);
441         if (wc.wc_error && !status)
442                 status = wc.wc_error;
443
444         return status;
445 }
446
447 static int o2hb_issue_node_write(struct o2hb_region *reg,
448                                  struct o2hb_bio_wait_ctxt *write_wc)
449 {
450         int status;
451         unsigned int slot;
452         struct bio *bio;
453
454         o2hb_bio_wait_init(write_wc);
455
456         slot = o2nm_this_node();
457
458         bio = o2hb_setup_one_bio(reg, write_wc, &slot, slot+1);
459         if (IS_ERR(bio)) {
460                 status = PTR_ERR(bio);
461                 mlog_errno(status);
462                 goto bail;
463         }
464
465         atomic_inc(&write_wc->wc_num_reqs);
466         submit_bio(WRITE, bio);
467
468         status = 0;
469 bail:
470         return status;
471 }
472
473 static u32 o2hb_compute_block_crc_le(struct o2hb_region *reg,
474                                      struct o2hb_disk_heartbeat_block *hb_block)
475 {
476         __le32 old_cksum;
477         u32 ret;
478
479         /* We want to compute the block crc with a 0 value in the
480          * hb_cksum field. Save it off here and replace after the
481          * crc. */
482         old_cksum = hb_block->hb_cksum;
483         hb_block->hb_cksum = 0;
484
485         ret = crc32_le(0, (unsigned char *) hb_block, reg->hr_block_bytes);
486
487         hb_block->hb_cksum = old_cksum;
488
489         return ret;
490 }
491
492 static void o2hb_dump_slot(struct o2hb_disk_heartbeat_block *hb_block)
493 {
494         mlog(ML_ERROR, "Dump slot information: seq = 0x%llx, node = %u, "
495              "cksum = 0x%x, generation 0x%llx\n",
496              (long long)le64_to_cpu(hb_block->hb_seq),
497              hb_block->hb_node, le32_to_cpu(hb_block->hb_cksum),
498              (long long)le64_to_cpu(hb_block->hb_generation));
499 }
500
501 static int o2hb_verify_crc(struct o2hb_region *reg,
502                            struct o2hb_disk_heartbeat_block *hb_block)
503 {
504         u32 read, computed;
505
506         read = le32_to_cpu(hb_block->hb_cksum);
507         computed = o2hb_compute_block_crc_le(reg, hb_block);
508
509         return read == computed;
510 }
511
512 /* We want to make sure that nobody is heartbeating on top of us --
513  * this will help detect an invalid configuration. */
514 static int o2hb_check_last_timestamp(struct o2hb_region *reg)
515 {
516         int node_num, ret;
517         struct o2hb_disk_slot *slot;
518         struct o2hb_disk_heartbeat_block *hb_block;
519
520         node_num = o2nm_this_node();
521
522         ret = 1;
523         slot = &reg->hr_slots[node_num];
524         /* Don't check on our 1st timestamp */
525         if (slot->ds_last_time) {
526                 hb_block = slot->ds_raw_block;
527
528                 if (le64_to_cpu(hb_block->hb_seq) != slot->ds_last_time)
529                         ret = 0;
530         }
531
532         return ret;
533 }
534
535 static inline void o2hb_prepare_block(struct o2hb_region *reg,
536                                       u64 generation)
537 {
538         int node_num;
539         u64 cputime;
540         struct o2hb_disk_slot *slot;
541         struct o2hb_disk_heartbeat_block *hb_block;
542
543         node_num = o2nm_this_node();
544         slot = &reg->hr_slots[node_num];
545
546         hb_block = (struct o2hb_disk_heartbeat_block *)slot->ds_raw_block;
547         memset(hb_block, 0, reg->hr_block_bytes);
548         /* TODO: time stuff */
549         cputime = CURRENT_TIME.tv_sec;
550         if (!cputime)
551                 cputime = 1;
552
553         hb_block->hb_seq = cpu_to_le64(cputime);
554         hb_block->hb_node = node_num;
555         hb_block->hb_generation = cpu_to_le64(generation);
556         hb_block->hb_dead_ms = cpu_to_le32(o2hb_dead_threshold * O2HB_REGION_TIMEOUT_MS);
557
558         /* This step must always happen last! */
559         hb_block->hb_cksum = cpu_to_le32(o2hb_compute_block_crc_le(reg,
560                                                                    hb_block));
561
562         mlog(ML_HB_BIO, "our node generation = 0x%llx, cksum = 0x%x\n",
563              (long long)generation,
564              le32_to_cpu(hb_block->hb_cksum));
565 }
566
567 static void o2hb_fire_callbacks(struct o2hb_callback *hbcall,
568                                 struct o2nm_node *node,
569                                 int idx)
570 {
571         struct list_head *iter;
572         struct o2hb_callback_func *f;
573
574         list_for_each(iter, &hbcall->list) {
575                 f = list_entry(iter, struct o2hb_callback_func, hc_item);
576                 mlog(ML_HEARTBEAT, "calling funcs %p\n", f);
577                 (f->hc_func)(node, idx, f->hc_data);
578         }
579 }
580
581 /* Will run the list in order until we process the passed event */
582 static void o2hb_run_event_list(struct o2hb_node_event *queued_event)
583 {
584         int empty;
585         struct o2hb_callback *hbcall;
586         struct o2hb_node_event *event;
587
588         spin_lock(&o2hb_live_lock);
589         empty = list_empty(&queued_event->hn_item);
590         spin_unlock(&o2hb_live_lock);
591         if (empty)
592                 return;
593
594         /* Holding callback sem assures we don't alter the callback
595          * lists when doing this, and serializes ourselves with other
596          * processes wanting callbacks. */
597         down_write(&o2hb_callback_sem);
598
599         spin_lock(&o2hb_live_lock);
600         while (!list_empty(&o2hb_node_events)
601                && !list_empty(&queued_event->hn_item)) {
602                 event = list_entry(o2hb_node_events.next,
603                                    struct o2hb_node_event,
604                                    hn_item);
605                 list_del_init(&event->hn_item);
606                 spin_unlock(&o2hb_live_lock);
607
608                 mlog(ML_HEARTBEAT, "Node %s event for %d\n",
609                      event->hn_event_type == O2HB_NODE_UP_CB ? "UP" : "DOWN",
610                      event->hn_node_num);
611
612                 hbcall = hbcall_from_type(event->hn_event_type);
613
614                 /* We should *never* have gotten on to the list with a
615                  * bad type... This isn't something that we should try
616                  * to recover from. */
617                 BUG_ON(IS_ERR(hbcall));
618
619                 o2hb_fire_callbacks(hbcall, event->hn_node, event->hn_node_num);
620
621                 spin_lock(&o2hb_live_lock);
622         }
623         spin_unlock(&o2hb_live_lock);
624
625         up_write(&o2hb_callback_sem);
626 }
627
628 static void o2hb_queue_node_event(struct o2hb_node_event *event,
629                                   enum o2hb_callback_type type,
630                                   struct o2nm_node *node,
631                                   int node_num)
632 {
633         assert_spin_locked(&o2hb_live_lock);
634
635         BUG_ON((!node) && (type != O2HB_NODE_DOWN_CB));
636
637         event->hn_event_type = type;
638         event->hn_node = node;
639         event->hn_node_num = node_num;
640
641         mlog(ML_HEARTBEAT, "Queue node %s event for node %d\n",
642              type == O2HB_NODE_UP_CB ? "UP" : "DOWN", node_num);
643
644         list_add_tail(&event->hn_item, &o2hb_node_events);
645 }
646
647 static void o2hb_shutdown_slot(struct o2hb_disk_slot *slot)
648 {
649         struct o2hb_node_event event =
650                 { .hn_item = LIST_HEAD_INIT(event.hn_item), };
651         struct o2nm_node *node;
652
653         node = o2nm_get_node_by_num(slot->ds_node_num);
654         if (!node)
655                 return;
656
657         spin_lock(&o2hb_live_lock);
658         if (!list_empty(&slot->ds_live_item)) {
659                 mlog(ML_HEARTBEAT, "Shutdown, node %d leaves region\n",
660                      slot->ds_node_num);
661
662                 list_del_init(&slot->ds_live_item);
663
664                 if (list_empty(&o2hb_live_slots[slot->ds_node_num])) {
665                         clear_bit(slot->ds_node_num, o2hb_live_node_bitmap);
666
667                         o2hb_queue_node_event(&event, O2HB_NODE_DOWN_CB, node,
668                                               slot->ds_node_num);
669                 }
670         }
671         spin_unlock(&o2hb_live_lock);
672
673         o2hb_run_event_list(&event);
674
675         o2nm_node_put(node);
676 }
677
678 static void o2hb_set_quorum_device(struct o2hb_region *reg,
679                                    struct o2hb_disk_slot *slot)
680 {
681         assert_spin_locked(&o2hb_live_lock);
682
683         if (!o2hb_global_heartbeat_active())
684                 return;
685
686         if (test_bit(reg->hr_region_num, o2hb_quorum_region_bitmap))
687                 return;
688
689         /*
690          * A region can be added to the quorum only when it sees all
691          * live nodes heartbeat on it. In other words, the region has been
692          * added to all nodes.
693          */
694         if (memcmp(reg->hr_live_node_bitmap, o2hb_live_node_bitmap,
695                    sizeof(o2hb_live_node_bitmap)))
696                 return;
697
698         if (slot->ds_changed_samples < O2HB_LIVE_THRESHOLD)
699                 return;
700
701         printk(KERN_NOTICE "o2hb: Region %s is now a quorum device\n",
702                config_item_name(&reg->hr_item));
703
704         set_bit(reg->hr_region_num, o2hb_quorum_region_bitmap);
705 }
706
707 static int o2hb_check_slot(struct o2hb_region *reg,
708                            struct o2hb_disk_slot *slot)
709 {
710         int changed = 0, gen_changed = 0;
711         struct o2hb_node_event event =
712                 { .hn_item = LIST_HEAD_INIT(event.hn_item), };
713         struct o2nm_node *node;
714         struct o2hb_disk_heartbeat_block *hb_block = reg->hr_tmp_block;
715         u64 cputime;
716         unsigned int dead_ms = o2hb_dead_threshold * O2HB_REGION_TIMEOUT_MS;
717         unsigned int slot_dead_ms;
718         int tmp;
719
720         memcpy(hb_block, slot->ds_raw_block, reg->hr_block_bytes);
721
722         /*
723          * If a node is no longer configured but is still in the livemap, we
724          * may need to clear that bit from the livemap.
725          */
726         node = o2nm_get_node_by_num(slot->ds_node_num);
727         if (!node) {
728                 spin_lock(&o2hb_live_lock);
729                 tmp = test_bit(slot->ds_node_num, o2hb_live_node_bitmap);
730                 spin_unlock(&o2hb_live_lock);
731                 if (!tmp)
732                         return 0;
733         }
734
735         if (!o2hb_verify_crc(reg, hb_block)) {
736                 /* all paths from here will drop o2hb_live_lock for
737                  * us. */
738                 spin_lock(&o2hb_live_lock);
739
740                 /* Don't print an error on the console in this case -
741                  * a freshly formatted heartbeat area will not have a
742                  * crc set on it. */
743                 if (list_empty(&slot->ds_live_item))
744                         goto out;
745
746                 /* The node is live but pushed out a bad crc. We
747                  * consider it a transient miss but don't populate any
748                  * other values as they may be junk. */
749                 mlog(ML_ERROR, "Node %d has written a bad crc to %s\n",
750                      slot->ds_node_num, reg->hr_dev_name);
751                 o2hb_dump_slot(hb_block);
752
753                 slot->ds_equal_samples++;
754                 goto fire_callbacks;
755         }
756
757         /* we don't care if these wrap.. the state transitions below
758          * clear at the right places */
759         cputime = le64_to_cpu(hb_block->hb_seq);
760         if (slot->ds_last_time != cputime)
761                 slot->ds_changed_samples++;
762         else
763                 slot->ds_equal_samples++;
764         slot->ds_last_time = cputime;
765
766         /* The node changed heartbeat generations. We assume this to
767          * mean it dropped off but came back before we timed out. We
768          * want to consider it down for the time being but don't want
769          * to lose any changed_samples state we might build up to
770          * considering it live again. */
771         if (slot->ds_last_generation != le64_to_cpu(hb_block->hb_generation)) {
772                 gen_changed = 1;
773                 slot->ds_equal_samples = 0;
774                 mlog(ML_HEARTBEAT, "Node %d changed generation (0x%llx "
775                      "to 0x%llx)\n", slot->ds_node_num,
776                      (long long)slot->ds_last_generation,
777                      (long long)le64_to_cpu(hb_block->hb_generation));
778         }
779
780         slot->ds_last_generation = le64_to_cpu(hb_block->hb_generation);
781
782         mlog(ML_HEARTBEAT, "Slot %d gen 0x%llx cksum 0x%x "
783              "seq %llu last %llu changed %u equal %u\n",
784              slot->ds_node_num, (long long)slot->ds_last_generation,
785              le32_to_cpu(hb_block->hb_cksum),
786              (unsigned long long)le64_to_cpu(hb_block->hb_seq),
787              (unsigned long long)slot->ds_last_time, slot->ds_changed_samples,
788              slot->ds_equal_samples);
789
790         spin_lock(&o2hb_live_lock);
791
792 fire_callbacks:
793         /* dead nodes only come to life after some number of
794          * changes at any time during their dead time */
795         if (list_empty(&slot->ds_live_item) &&
796             slot->ds_changed_samples >= O2HB_LIVE_THRESHOLD) {
797                 mlog(ML_HEARTBEAT, "Node %d (id 0x%llx) joined my region\n",
798                      slot->ds_node_num, (long long)slot->ds_last_generation);
799
800                 set_bit(slot->ds_node_num, reg->hr_live_node_bitmap);
801
802                 /* first on the list generates a callback */
803                 if (list_empty(&o2hb_live_slots[slot->ds_node_num])) {
804                         mlog(ML_HEARTBEAT, "o2hb: Add node %d to live nodes "
805                              "bitmap\n", slot->ds_node_num);
806                         set_bit(slot->ds_node_num, o2hb_live_node_bitmap);
807
808                         o2hb_queue_node_event(&event, O2HB_NODE_UP_CB, node,
809                                               slot->ds_node_num);
810
811                         changed = 1;
812                 }
813
814                 list_add_tail(&slot->ds_live_item,
815                               &o2hb_live_slots[slot->ds_node_num]);
816
817                 slot->ds_equal_samples = 0;
818
819                 /* We want to be sure that all nodes agree on the
820                  * number of milliseconds before a node will be
821                  * considered dead. The self-fencing timeout is
822                  * computed from this value, and a discrepancy might
823                  * result in heartbeat calling a node dead when it
824                  * hasn't self-fenced yet. */
825                 slot_dead_ms = le32_to_cpu(hb_block->hb_dead_ms);
826                 if (slot_dead_ms && slot_dead_ms != dead_ms) {
827                         /* TODO: Perhaps we can fail the region here. */
828                         mlog(ML_ERROR, "Node %d on device %s has a dead count "
829                              "of %u ms, but our count is %u ms.\n"
830                              "Please double check your configuration values "
831                              "for 'O2CB_HEARTBEAT_THRESHOLD'\n",
832                              slot->ds_node_num, reg->hr_dev_name, slot_dead_ms,
833                              dead_ms);
834                 }
835                 goto out;
836         }
837
838         /* if the list is dead, we're done.. */
839         if (list_empty(&slot->ds_live_item))
840                 goto out;
841
842         /* live nodes only go dead after enough consequtive missed
843          * samples..  reset the missed counter whenever we see
844          * activity */
845         if (slot->ds_equal_samples >= o2hb_dead_threshold || gen_changed) {
846                 mlog(ML_HEARTBEAT, "Node %d left my region\n",
847                      slot->ds_node_num);
848
849                 clear_bit(slot->ds_node_num, reg->hr_live_node_bitmap);
850
851                 /* last off the live_slot generates a callback */
852                 list_del_init(&slot->ds_live_item);
853                 if (list_empty(&o2hb_live_slots[slot->ds_node_num])) {
854                         mlog(ML_HEARTBEAT, "o2hb: Remove node %d from live "
855                              "nodes bitmap\n", slot->ds_node_num);
856                         clear_bit(slot->ds_node_num, o2hb_live_node_bitmap);
857
858                         /* node can be null */
859                         o2hb_queue_node_event(&event, O2HB_NODE_DOWN_CB,
860                                               node, slot->ds_node_num);
861
862                         changed = 1;
863                 }
864
865                 /* We don't clear this because the node is still
866                  * actually writing new blocks. */
867                 if (!gen_changed)
868                         slot->ds_changed_samples = 0;
869                 goto out;
870         }
871         if (slot->ds_changed_samples) {
872                 slot->ds_changed_samples = 0;
873                 slot->ds_equal_samples = 0;
874         }
875 out:
876         o2hb_set_quorum_device(reg, slot);
877
878         spin_unlock(&o2hb_live_lock);
879
880         o2hb_run_event_list(&event);
881
882         if (node)
883                 o2nm_node_put(node);
884         return changed;
885 }
886
887 /* This could be faster if we just implmented a find_last_bit, but I
888  * don't think the circumstances warrant it. */
889 static int o2hb_highest_node(unsigned long *nodes,
890                              int numbits)
891 {
892         int highest, node;
893
894         highest = numbits;
895         node = -1;
896         while ((node = find_next_bit(nodes, numbits, node + 1)) != -1) {
897                 if (node >= numbits)
898                         break;
899
900                 highest = node;
901         }
902
903         return highest;
904 }
905
906 static int o2hb_do_disk_heartbeat(struct o2hb_region *reg)
907 {
908         int i, ret, highest_node, change = 0;
909         unsigned long configured_nodes[BITS_TO_LONGS(O2NM_MAX_NODES)];
910         unsigned long live_node_bitmap[BITS_TO_LONGS(O2NM_MAX_NODES)];
911         struct o2hb_bio_wait_ctxt write_wc;
912
913         ret = o2nm_configured_node_map(configured_nodes,
914                                        sizeof(configured_nodes));
915         if (ret) {
916                 mlog_errno(ret);
917                 return ret;
918         }
919
920         /*
921          * If a node is not configured but is in the livemap, we still need
922          * to read the slot so as to be able to remove it from the livemap.
923          */
924         o2hb_fill_node_map(live_node_bitmap, sizeof(live_node_bitmap));
925         i = -1;
926         while ((i = find_next_bit(live_node_bitmap,
927                                   O2NM_MAX_NODES, i + 1)) < O2NM_MAX_NODES) {
928                 set_bit(i, configured_nodes);
929         }
930
931         highest_node = o2hb_highest_node(configured_nodes, O2NM_MAX_NODES);
932         if (highest_node >= O2NM_MAX_NODES) {
933                 mlog(ML_NOTICE, "ocfs2_heartbeat: no configured nodes found!\n");
934                 return -EINVAL;
935         }
936
937         /* No sense in reading the slots of nodes that don't exist
938          * yet. Of course, if the node definitions have holes in them
939          * then we're reading an empty slot anyway... Consider this
940          * best-effort. */
941         ret = o2hb_read_slots(reg, highest_node + 1);
942         if (ret < 0) {
943                 mlog_errno(ret);
944                 return ret;
945         }
946
947         /* With an up to date view of the slots, we can check that no
948          * other node has been improperly configured to heartbeat in
949          * our slot. */
950         if (!o2hb_check_last_timestamp(reg))
951                 mlog(ML_ERROR, "Device \"%s\": another node is heartbeating "
952                      "in our slot!\n", reg->hr_dev_name);
953
954         /* fill in the proper info for our next heartbeat */
955         o2hb_prepare_block(reg, reg->hr_generation);
956
957         /* And fire off the write. Note that we don't wait on this I/O
958          * until later. */
959         ret = o2hb_issue_node_write(reg, &write_wc);
960         if (ret < 0) {
961                 mlog_errno(ret);
962                 return ret;
963         }
964
965         i = -1;
966         while((i = find_next_bit(configured_nodes, O2NM_MAX_NODES, i + 1)) < O2NM_MAX_NODES) {
967
968                 change |= o2hb_check_slot(reg, &reg->hr_slots[i]);
969         }
970
971         /*
972          * We have to be sure we've advertised ourselves on disk
973          * before we can go to steady state.  This ensures that
974          * people we find in our steady state have seen us.
975          */
976         o2hb_wait_on_io(reg, &write_wc);
977         if (write_wc.wc_error) {
978                 /* Do not re-arm the write timeout on I/O error - we
979                  * can't be sure that the new block ever made it to
980                  * disk */
981                 mlog(ML_ERROR, "Write error %d on device \"%s\"\n",
982                      write_wc.wc_error, reg->hr_dev_name);
983                 return write_wc.wc_error;
984         }
985
986         o2hb_arm_write_timeout(reg);
987
988         /* let the person who launched us know when things are steady */
989         if (!change && (atomic_read(&reg->hr_steady_iterations) != 0)) {
990                 if (atomic_dec_and_test(&reg->hr_steady_iterations))
991                         wake_up(&o2hb_steady_queue);
992         }
993
994         return 0;
995 }
996
997 /* Subtract b from a, storing the result in a. a *must* have a larger
998  * value than b. */
999 static void o2hb_tv_subtract(struct timeval *a,
1000                              struct timeval *b)
1001 {
1002         /* just return 0 when a is after b */
1003         if (a->tv_sec < b->tv_sec ||
1004             (a->tv_sec == b->tv_sec && a->tv_usec < b->tv_usec)) {
1005                 a->tv_sec = 0;
1006                 a->tv_usec = 0;
1007                 return;
1008         }
1009
1010         a->tv_sec -= b->tv_sec;
1011         a->tv_usec -= b->tv_usec;
1012         while ( a->tv_usec < 0 ) {
1013                 a->tv_sec--;
1014                 a->tv_usec += 1000000;
1015         }
1016 }
1017
1018 static unsigned int o2hb_elapsed_msecs(struct timeval *start,
1019                                        struct timeval *end)
1020 {
1021         struct timeval res = *end;
1022
1023         o2hb_tv_subtract(&res, start);
1024
1025         return res.tv_sec * 1000 + res.tv_usec / 1000;
1026 }
1027
1028 /*
1029  * we ride the region ref that the region dir holds.  before the region
1030  * dir is removed and drops it ref it will wait to tear down this
1031  * thread.
1032  */
1033 static int o2hb_thread(void *data)
1034 {
1035         int i, ret;
1036         struct o2hb_region *reg = data;
1037         struct o2hb_bio_wait_ctxt write_wc;
1038         struct timeval before_hb, after_hb;
1039         unsigned int elapsed_msec;
1040
1041         mlog(ML_HEARTBEAT|ML_KTHREAD, "hb thread running\n");
1042
1043         set_user_nice(current, -20);
1044
1045         while (!kthread_should_stop() && !reg->hr_unclean_stop) {
1046                 /* We track the time spent inside
1047                  * o2hb_do_disk_heartbeat so that we avoid more than
1048                  * hr_timeout_ms between disk writes. On busy systems
1049                  * this should result in a heartbeat which is less
1050                  * likely to time itself out. */
1051                 do_gettimeofday(&before_hb);
1052
1053                 i = 0;
1054                 do {
1055                         ret = o2hb_do_disk_heartbeat(reg);
1056                 } while (ret && ++i < 2);
1057
1058                 do_gettimeofday(&after_hb);
1059                 elapsed_msec = o2hb_elapsed_msecs(&before_hb, &after_hb);
1060
1061                 mlog(ML_HEARTBEAT,
1062                      "start = %lu.%lu, end = %lu.%lu, msec = %u\n",
1063                      before_hb.tv_sec, (unsigned long) before_hb.tv_usec,
1064                      after_hb.tv_sec, (unsigned long) after_hb.tv_usec,
1065                      elapsed_msec);
1066
1067                 if (elapsed_msec < reg->hr_timeout_ms) {
1068                         /* the kthread api has blocked signals for us so no
1069                          * need to record the return value. */
1070                         msleep_interruptible(reg->hr_timeout_ms - elapsed_msec);
1071                 }
1072         }
1073
1074         o2hb_disarm_write_timeout(reg);
1075
1076         /* unclean stop is only used in very bad situation */
1077         for(i = 0; !reg->hr_unclean_stop && i < reg->hr_blocks; i++)
1078                 o2hb_shutdown_slot(&reg->hr_slots[i]);
1079
1080         /* Explicit down notification - avoid forcing the other nodes
1081          * to timeout on this region when we could just as easily
1082          * write a clear generation - thus indicating to them that
1083          * this node has left this region.
1084          *
1085          * XXX: Should we skip this on unclean_stop? */
1086         o2hb_prepare_block(reg, 0);
1087         ret = o2hb_issue_node_write(reg, &write_wc);
1088         if (ret == 0) {
1089                 o2hb_wait_on_io(reg, &write_wc);
1090         } else {
1091                 mlog_errno(ret);
1092         }
1093
1094         mlog(ML_HEARTBEAT|ML_KTHREAD, "hb thread exiting\n");
1095
1096         return 0;
1097 }
1098
1099 #ifdef CONFIG_DEBUG_FS
1100 static int o2hb_debug_open(struct inode *inode, struct file *file)
1101 {
1102         struct o2hb_debug_buf *db = inode->i_private;
1103         struct o2hb_region *reg;
1104         unsigned long map[BITS_TO_LONGS(O2NM_MAX_NODES)];
1105         char *buf = NULL;
1106         int i = -1;
1107         int out = 0;
1108
1109         /* max_nodes should be the largest bitmap we pass here */
1110         BUG_ON(sizeof(map) < db->db_size);
1111
1112         buf = kmalloc(PAGE_SIZE, GFP_KERNEL);
1113         if (!buf)
1114                 goto bail;
1115
1116         switch (db->db_type) {
1117         case O2HB_DB_TYPE_LIVENODES:
1118         case O2HB_DB_TYPE_LIVEREGIONS:
1119         case O2HB_DB_TYPE_QUORUMREGIONS:
1120         case O2HB_DB_TYPE_FAILEDREGIONS:
1121                 spin_lock(&o2hb_live_lock);
1122                 memcpy(map, db->db_data, db->db_size);
1123                 spin_unlock(&o2hb_live_lock);
1124                 break;
1125
1126         case O2HB_DB_TYPE_REGION_LIVENODES:
1127                 spin_lock(&o2hb_live_lock);
1128                 reg = (struct o2hb_region *)db->db_data;
1129                 memcpy(map, reg->hr_live_node_bitmap, db->db_size);
1130                 spin_unlock(&o2hb_live_lock);
1131                 break;
1132
1133         case O2HB_DB_TYPE_REGION_NUMBER:
1134                 reg = (struct o2hb_region *)db->db_data;
1135                 out += snprintf(buf + out, PAGE_SIZE - out, "%d\n",
1136                                 reg->hr_region_num);
1137                 goto done;
1138
1139         case O2HB_DB_TYPE_REGION_ELAPSED_TIME:
1140                 reg = (struct o2hb_region *)db->db_data;
1141                 out += snprintf(buf + out, PAGE_SIZE - out, "%u\n",
1142                                 jiffies_to_msecs(jiffies -
1143                                                  reg->hr_last_timeout_start));
1144                 goto done;
1145
1146         default:
1147                 goto done;
1148         }
1149
1150         while ((i = find_next_bit(map, db->db_len, i + 1)) < db->db_len)
1151                 out += snprintf(buf + out, PAGE_SIZE - out, "%d ", i);
1152         out += snprintf(buf + out, PAGE_SIZE - out, "\n");
1153
1154 done:
1155         i_size_write(inode, out);
1156
1157         file->private_data = buf;
1158
1159         return 0;
1160 bail:
1161         return -ENOMEM;
1162 }
1163
1164 static int o2hb_debug_release(struct inode *inode, struct file *file)
1165 {
1166         kfree(file->private_data);
1167         return 0;
1168 }
1169
1170 static ssize_t o2hb_debug_read(struct file *file, char __user *buf,
1171                                  size_t nbytes, loff_t *ppos)
1172 {
1173         return simple_read_from_buffer(buf, nbytes, ppos, file->private_data,
1174                                        i_size_read(file->f_mapping->host));
1175 }
1176 #else
1177 static int o2hb_debug_open(struct inode *inode, struct file *file)
1178 {
1179         return 0;
1180 }
1181 static int o2hb_debug_release(struct inode *inode, struct file *file)
1182 {
1183         return 0;
1184 }
1185 static ssize_t o2hb_debug_read(struct file *file, char __user *buf,
1186                                size_t nbytes, loff_t *ppos)
1187 {
1188         return 0;
1189 }
1190 #endif  /* CONFIG_DEBUG_FS */
1191
1192 static const struct file_operations o2hb_debug_fops = {
1193         .open =         o2hb_debug_open,
1194         .release =      o2hb_debug_release,
1195         .read =         o2hb_debug_read,
1196         .llseek =       generic_file_llseek,
1197 };
1198
1199 void o2hb_exit(void)
1200 {
1201         kfree(o2hb_db_livenodes);
1202         kfree(o2hb_db_liveregions);
1203         kfree(o2hb_db_quorumregions);
1204         kfree(o2hb_db_failedregions);
1205         debugfs_remove(o2hb_debug_failedregions);
1206         debugfs_remove(o2hb_debug_quorumregions);
1207         debugfs_remove(o2hb_debug_liveregions);
1208         debugfs_remove(o2hb_debug_livenodes);
1209         debugfs_remove(o2hb_debug_dir);
1210 }
1211
1212 static struct dentry *o2hb_debug_create(const char *name, struct dentry *dir,
1213                                         struct o2hb_debug_buf **db, int db_len,
1214                                         int type, int size, int len, void *data)
1215 {
1216         *db = kmalloc(db_len, GFP_KERNEL);
1217         if (!*db)
1218                 return NULL;
1219
1220         (*db)->db_type = type;
1221         (*db)->db_size = size;
1222         (*db)->db_len = len;
1223         (*db)->db_data = data;
1224
1225         return debugfs_create_file(name, S_IFREG|S_IRUSR, dir, *db,
1226                                    &o2hb_debug_fops);
1227 }
1228
1229 static int o2hb_debug_init(void)
1230 {
1231         int ret = -ENOMEM;
1232
1233         o2hb_debug_dir = debugfs_create_dir(O2HB_DEBUG_DIR, NULL);
1234         if (!o2hb_debug_dir) {
1235                 mlog_errno(ret);
1236                 goto bail;
1237         }
1238
1239         o2hb_debug_livenodes = o2hb_debug_create(O2HB_DEBUG_LIVENODES,
1240                                                  o2hb_debug_dir,
1241                                                  &o2hb_db_livenodes,
1242                                                  sizeof(*o2hb_db_livenodes),
1243                                                  O2HB_DB_TYPE_LIVENODES,
1244                                                  sizeof(o2hb_live_node_bitmap),
1245                                                  O2NM_MAX_NODES,
1246                                                  o2hb_live_node_bitmap);
1247         if (!o2hb_debug_livenodes) {
1248                 mlog_errno(ret);
1249                 goto bail;
1250         }
1251
1252         o2hb_debug_liveregions = o2hb_debug_create(O2HB_DEBUG_LIVEREGIONS,
1253                                                    o2hb_debug_dir,
1254                                                    &o2hb_db_liveregions,
1255                                                    sizeof(*o2hb_db_liveregions),
1256                                                    O2HB_DB_TYPE_LIVEREGIONS,
1257                                                    sizeof(o2hb_live_region_bitmap),
1258                                                    O2NM_MAX_REGIONS,
1259                                                    o2hb_live_region_bitmap);
1260         if (!o2hb_debug_liveregions) {
1261                 mlog_errno(ret);
1262                 goto bail;
1263         }
1264
1265         o2hb_debug_quorumregions =
1266                         o2hb_debug_create(O2HB_DEBUG_QUORUMREGIONS,
1267                                           o2hb_debug_dir,
1268                                           &o2hb_db_quorumregions,
1269                                           sizeof(*o2hb_db_quorumregions),
1270                                           O2HB_DB_TYPE_QUORUMREGIONS,
1271                                           sizeof(o2hb_quorum_region_bitmap),
1272                                           O2NM_MAX_REGIONS,
1273                                           o2hb_quorum_region_bitmap);
1274         if (!o2hb_debug_quorumregions) {
1275                 mlog_errno(ret);
1276                 goto bail;
1277         }
1278
1279         o2hb_debug_failedregions =
1280                         o2hb_debug_create(O2HB_DEBUG_FAILEDREGIONS,
1281                                           o2hb_debug_dir,
1282                                           &o2hb_db_failedregions,
1283                                           sizeof(*o2hb_db_failedregions),
1284                                           O2HB_DB_TYPE_FAILEDREGIONS,
1285                                           sizeof(o2hb_failed_region_bitmap),
1286                                           O2NM_MAX_REGIONS,
1287                                           o2hb_failed_region_bitmap);
1288         if (!o2hb_debug_failedregions) {
1289                 mlog_errno(ret);
1290                 goto bail;
1291         }
1292
1293         ret = 0;
1294 bail:
1295         if (ret)
1296                 o2hb_exit();
1297
1298         return ret;
1299 }
1300
1301 int o2hb_init(void)
1302 {
1303         int i;
1304
1305         for (i = 0; i < ARRAY_SIZE(o2hb_callbacks); i++)
1306                 INIT_LIST_HEAD(&o2hb_callbacks[i].list);
1307
1308         for (i = 0; i < ARRAY_SIZE(o2hb_live_slots); i++)
1309                 INIT_LIST_HEAD(&o2hb_live_slots[i]);
1310
1311         INIT_LIST_HEAD(&o2hb_node_events);
1312
1313         memset(o2hb_live_node_bitmap, 0, sizeof(o2hb_live_node_bitmap));
1314         memset(o2hb_region_bitmap, 0, sizeof(o2hb_region_bitmap));
1315         memset(o2hb_live_region_bitmap, 0, sizeof(o2hb_live_region_bitmap));
1316         memset(o2hb_quorum_region_bitmap, 0, sizeof(o2hb_quorum_region_bitmap));
1317         memset(o2hb_failed_region_bitmap, 0, sizeof(o2hb_failed_region_bitmap));
1318
1319         return o2hb_debug_init();
1320 }
1321
1322 /* if we're already in a callback then we're already serialized by the sem */
1323 static void o2hb_fill_node_map_from_callback(unsigned long *map,
1324                                              unsigned bytes)
1325 {
1326         BUG_ON(bytes < (BITS_TO_LONGS(O2NM_MAX_NODES) * sizeof(unsigned long)));
1327
1328         memcpy(map, &o2hb_live_node_bitmap, bytes);
1329 }
1330
1331 /*
1332  * get a map of all nodes that are heartbeating in any regions
1333  */
1334 void o2hb_fill_node_map(unsigned long *map, unsigned bytes)
1335 {
1336         /* callers want to serialize this map and callbacks so that they
1337          * can trust that they don't miss nodes coming to the party */
1338         down_read(&o2hb_callback_sem);
1339         spin_lock(&o2hb_live_lock);
1340         o2hb_fill_node_map_from_callback(map, bytes);
1341         spin_unlock(&o2hb_live_lock);
1342         up_read(&o2hb_callback_sem);
1343 }
1344 EXPORT_SYMBOL_GPL(o2hb_fill_node_map);
1345
1346 /*
1347  * heartbeat configfs bits.  The heartbeat set is a default set under
1348  * the cluster set in nodemanager.c.
1349  */
1350
1351 static struct o2hb_region *to_o2hb_region(struct config_item *item)
1352 {
1353         return item ? container_of(item, struct o2hb_region, hr_item) : NULL;
1354 }
1355
1356 /* drop_item only drops its ref after killing the thread, nothing should
1357  * be using the region anymore.  this has to clean up any state that
1358  * attributes might have built up. */
1359 static void o2hb_region_release(struct config_item *item)
1360 {
1361         int i;
1362         struct page *page;
1363         struct o2hb_region *reg = to_o2hb_region(item);
1364
1365         if (reg->hr_tmp_block)
1366                 kfree(reg->hr_tmp_block);
1367
1368         if (reg->hr_slot_data) {
1369                 for (i = 0; i < reg->hr_num_pages; i++) {
1370                         page = reg->hr_slot_data[i];
1371                         if (page)
1372                                 __free_page(page);
1373                 }
1374                 kfree(reg->hr_slot_data);
1375         }
1376
1377         if (reg->hr_bdev)
1378                 blkdev_put(reg->hr_bdev, FMODE_READ|FMODE_WRITE);
1379
1380         if (reg->hr_slots)
1381                 kfree(reg->hr_slots);
1382
1383         kfree(reg->hr_db_regnum);
1384         kfree(reg->hr_db_livenodes);
1385         debugfs_remove(reg->hr_debug_livenodes);
1386         debugfs_remove(reg->hr_debug_regnum);
1387         debugfs_remove(reg->hr_debug_elapsed_time);
1388         debugfs_remove(reg->hr_debug_dir);
1389
1390         spin_lock(&o2hb_live_lock);
1391         list_del(&reg->hr_all_item);
1392         spin_unlock(&o2hb_live_lock);
1393
1394         kfree(reg);
1395 }
1396
1397 static int o2hb_read_block_input(struct o2hb_region *reg,
1398                                  const char *page,
1399                                  size_t count,
1400                                  unsigned long *ret_bytes,
1401                                  unsigned int *ret_bits)
1402 {
1403         unsigned long bytes;
1404         char *p = (char *)page;
1405
1406         bytes = simple_strtoul(p, &p, 0);
1407         if (!p || (*p && (*p != '\n')))
1408                 return -EINVAL;
1409
1410         /* Heartbeat and fs min / max block sizes are the same. */
1411         if (bytes > 4096 || bytes < 512)
1412                 return -ERANGE;
1413         if (hweight16(bytes) != 1)
1414                 return -EINVAL;
1415
1416         if (ret_bytes)
1417                 *ret_bytes = bytes;
1418         if (ret_bits)
1419                 *ret_bits = ffs(bytes) - 1;
1420
1421         return 0;
1422 }
1423
1424 static ssize_t o2hb_region_block_bytes_read(struct o2hb_region *reg,
1425                                             char *page)
1426 {
1427         return sprintf(page, "%u\n", reg->hr_block_bytes);
1428 }
1429
1430 static ssize_t o2hb_region_block_bytes_write(struct o2hb_region *reg,
1431                                              const char *page,
1432                                              size_t count)
1433 {
1434         int status;
1435         unsigned long block_bytes;
1436         unsigned int block_bits;
1437
1438         if (reg->hr_bdev)
1439                 return -EINVAL;
1440
1441         status = o2hb_read_block_input(reg, page, count,
1442                                        &block_bytes, &block_bits);
1443         if (status)
1444                 return status;
1445
1446         reg->hr_block_bytes = (unsigned int)block_bytes;
1447         reg->hr_block_bits = block_bits;
1448
1449         return count;
1450 }
1451
1452 static ssize_t o2hb_region_start_block_read(struct o2hb_region *reg,
1453                                             char *page)
1454 {
1455         return sprintf(page, "%llu\n", reg->hr_start_block);
1456 }
1457
1458 static ssize_t o2hb_region_start_block_write(struct o2hb_region *reg,
1459                                              const char *page,
1460                                              size_t count)
1461 {
1462         unsigned long long tmp;
1463         char *p = (char *)page;
1464
1465         if (reg->hr_bdev)
1466                 return -EINVAL;
1467
1468         tmp = simple_strtoull(p, &p, 0);
1469         if (!p || (*p && (*p != '\n')))
1470                 return -EINVAL;
1471
1472         reg->hr_start_block = tmp;
1473
1474         return count;
1475 }
1476
1477 static ssize_t o2hb_region_blocks_read(struct o2hb_region *reg,
1478                                        char *page)
1479 {
1480         return sprintf(page, "%d\n", reg->hr_blocks);
1481 }
1482
1483 static ssize_t o2hb_region_blocks_write(struct o2hb_region *reg,
1484                                         const char *page,
1485                                         size_t count)
1486 {
1487         unsigned long tmp;
1488         char *p = (char *)page;
1489
1490         if (reg->hr_bdev)
1491                 return -EINVAL;
1492
1493         tmp = simple_strtoul(p, &p, 0);
1494         if (!p || (*p && (*p != '\n')))
1495                 return -EINVAL;
1496
1497         if (tmp > O2NM_MAX_NODES || tmp == 0)
1498                 return -ERANGE;
1499
1500         reg->hr_blocks = (unsigned int)tmp;
1501
1502         return count;
1503 }
1504
1505 static ssize_t o2hb_region_dev_read(struct o2hb_region *reg,
1506                                     char *page)
1507 {
1508         unsigned int ret = 0;
1509
1510         if (reg->hr_bdev)
1511                 ret = sprintf(page, "%s\n", reg->hr_dev_name);
1512
1513         return ret;
1514 }
1515
1516 static void o2hb_init_region_params(struct o2hb_region *reg)
1517 {
1518         reg->hr_slots_per_page = PAGE_CACHE_SIZE >> reg->hr_block_bits;
1519         reg->hr_timeout_ms = O2HB_REGION_TIMEOUT_MS;
1520
1521         mlog(ML_HEARTBEAT, "hr_start_block = %llu, hr_blocks = %u\n",
1522              reg->hr_start_block, reg->hr_blocks);
1523         mlog(ML_HEARTBEAT, "hr_block_bytes = %u, hr_block_bits = %u\n",
1524              reg->hr_block_bytes, reg->hr_block_bits);
1525         mlog(ML_HEARTBEAT, "hr_timeout_ms = %u\n", reg->hr_timeout_ms);
1526         mlog(ML_HEARTBEAT, "dead threshold = %u\n", o2hb_dead_threshold);
1527 }
1528
1529 static int o2hb_map_slot_data(struct o2hb_region *reg)
1530 {
1531         int i, j;
1532         unsigned int last_slot;
1533         unsigned int spp = reg->hr_slots_per_page;
1534         struct page *page;
1535         char *raw;
1536         struct o2hb_disk_slot *slot;
1537
1538         reg->hr_tmp_block = kmalloc(reg->hr_block_bytes, GFP_KERNEL);
1539         if (reg->hr_tmp_block == NULL) {
1540                 mlog_errno(-ENOMEM);
1541                 return -ENOMEM;
1542         }
1543
1544         reg->hr_slots = kcalloc(reg->hr_blocks,
1545                                 sizeof(struct o2hb_disk_slot), GFP_KERNEL);
1546         if (reg->hr_slots == NULL) {
1547                 mlog_errno(-ENOMEM);
1548                 return -ENOMEM;
1549         }
1550
1551         for(i = 0; i < reg->hr_blocks; i++) {
1552                 slot = &reg->hr_slots[i];
1553                 slot->ds_node_num = i;
1554                 INIT_LIST_HEAD(&slot->ds_live_item);
1555                 slot->ds_raw_block = NULL;
1556         }
1557
1558         reg->hr_num_pages = (reg->hr_blocks + spp - 1) / spp;
1559         mlog(ML_HEARTBEAT, "Going to require %u pages to cover %u blocks "
1560                            "at %u blocks per page\n",
1561              reg->hr_num_pages, reg->hr_blocks, spp);
1562
1563         reg->hr_slot_data = kcalloc(reg->hr_num_pages, sizeof(struct page *),
1564                                     GFP_KERNEL);
1565         if (!reg->hr_slot_data) {
1566                 mlog_errno(-ENOMEM);
1567                 return -ENOMEM;
1568         }
1569
1570         for(i = 0; i < reg->hr_num_pages; i++) {
1571                 page = alloc_page(GFP_KERNEL);
1572                 if (!page) {
1573                         mlog_errno(-ENOMEM);
1574                         return -ENOMEM;
1575                 }
1576
1577                 reg->hr_slot_data[i] = page;
1578
1579                 last_slot = i * spp;
1580                 raw = page_address(page);
1581                 for (j = 0;
1582                      (j < spp) && ((j + last_slot) < reg->hr_blocks);
1583                      j++) {
1584                         BUG_ON((j + last_slot) >= reg->hr_blocks);
1585
1586                         slot = &reg->hr_slots[j + last_slot];
1587                         slot->ds_raw_block =
1588                                 (struct o2hb_disk_heartbeat_block *) raw;
1589
1590                         raw += reg->hr_block_bytes;
1591                 }
1592         }
1593
1594         return 0;
1595 }
1596
1597 /* Read in all the slots available and populate the tracking
1598  * structures so that we can start with a baseline idea of what's
1599  * there. */
1600 static int o2hb_populate_slot_data(struct o2hb_region *reg)
1601 {
1602         int ret, i;
1603         struct o2hb_disk_slot *slot;
1604         struct o2hb_disk_heartbeat_block *hb_block;
1605
1606         mlog_entry_void();
1607
1608         ret = o2hb_read_slots(reg, reg->hr_blocks);
1609         if (ret) {
1610                 mlog_errno(ret);
1611                 goto out;
1612         }
1613
1614         /* We only want to get an idea of the values initially in each
1615          * slot, so we do no verification - o2hb_check_slot will
1616          * actually determine if each configured slot is valid and
1617          * whether any values have changed. */
1618         for(i = 0; i < reg->hr_blocks; i++) {
1619                 slot = &reg->hr_slots[i];
1620                 hb_block = (struct o2hb_disk_heartbeat_block *) slot->ds_raw_block;
1621
1622                 /* Only fill the values that o2hb_check_slot uses to
1623                  * determine changing slots */
1624                 slot->ds_last_time = le64_to_cpu(hb_block->hb_seq);
1625                 slot->ds_last_generation = le64_to_cpu(hb_block->hb_generation);
1626         }
1627
1628 out:
1629         mlog_exit(ret);
1630         return ret;
1631 }
1632
1633 /* this is acting as commit; we set up all of hr_bdev and hr_task or nothing */
1634 static ssize_t o2hb_region_dev_write(struct o2hb_region *reg,
1635                                      const char *page,
1636                                      size_t count)
1637 {
1638         struct task_struct *hb_task;
1639         long fd;
1640         int sectsize;
1641         char *p = (char *)page;
1642         struct file *filp = NULL;
1643         struct inode *inode = NULL;
1644         ssize_t ret = -EINVAL;
1645
1646         if (reg->hr_bdev)
1647                 goto out;
1648
1649         /* We can't heartbeat without having had our node number
1650          * configured yet. */
1651         if (o2nm_this_node() == O2NM_MAX_NODES)
1652                 goto out;
1653
1654         fd = simple_strtol(p, &p, 0);
1655         if (!p || (*p && (*p != '\n')))
1656                 goto out;
1657
1658         if (fd < 0 || fd >= INT_MAX)
1659                 goto out;
1660
1661         filp = fget(fd);
1662         if (filp == NULL)
1663                 goto out;
1664
1665         if (reg->hr_blocks == 0 || reg->hr_start_block == 0 ||
1666             reg->hr_block_bytes == 0)
1667                 goto out;
1668
1669         inode = igrab(filp->f_mapping->host);
1670         if (inode == NULL)
1671                 goto out;
1672
1673         if (!S_ISBLK(inode->i_mode))
1674                 goto out;
1675
1676         reg->hr_bdev = I_BDEV(filp->f_mapping->host);
1677         ret = blkdev_get(reg->hr_bdev, FMODE_WRITE | FMODE_READ, NULL);
1678         if (ret) {
1679                 reg->hr_bdev = NULL;
1680                 goto out;
1681         }
1682         inode = NULL;
1683
1684         bdevname(reg->hr_bdev, reg->hr_dev_name);
1685
1686         sectsize = bdev_logical_block_size(reg->hr_bdev);
1687         if (sectsize != reg->hr_block_bytes) {
1688                 mlog(ML_ERROR,
1689                      "blocksize %u incorrect for device, expected %d",
1690                      reg->hr_block_bytes, sectsize);
1691                 ret = -EINVAL;
1692                 goto out;
1693         }
1694
1695         o2hb_init_region_params(reg);
1696
1697         /* Generation of zero is invalid */
1698         do {
1699                 get_random_bytes(&reg->hr_generation,
1700                                  sizeof(reg->hr_generation));
1701         } while (reg->hr_generation == 0);
1702
1703         ret = o2hb_map_slot_data(reg);
1704         if (ret) {
1705                 mlog_errno(ret);
1706                 goto out;
1707         }
1708
1709         ret = o2hb_populate_slot_data(reg);
1710         if (ret) {
1711                 mlog_errno(ret);
1712                 goto out;
1713         }
1714
1715         INIT_DELAYED_WORK(&reg->hr_write_timeout_work, o2hb_write_timeout);
1716
1717         /*
1718          * A node is considered live after it has beat LIVE_THRESHOLD
1719          * times.  We're not steady until we've given them a chance
1720          * _after_ our first read.
1721          */
1722         atomic_set(&reg->hr_steady_iterations, O2HB_LIVE_THRESHOLD + 1);
1723
1724         hb_task = kthread_run(o2hb_thread, reg, "o2hb-%s",
1725                               reg->hr_item.ci_name);
1726         if (IS_ERR(hb_task)) {
1727                 ret = PTR_ERR(hb_task);
1728                 mlog_errno(ret);
1729                 goto out;
1730         }
1731
1732         spin_lock(&o2hb_live_lock);
1733         reg->hr_task = hb_task;
1734         spin_unlock(&o2hb_live_lock);
1735
1736         ret = wait_event_interruptible(o2hb_steady_queue,
1737                                 atomic_read(&reg->hr_steady_iterations) == 0);
1738         if (ret) {
1739                 /* We got interrupted (hello ptrace!).  Clean up */
1740                 spin_lock(&o2hb_live_lock);
1741                 hb_task = reg->hr_task;
1742                 reg->hr_task = NULL;
1743                 spin_unlock(&o2hb_live_lock);
1744
1745                 if (hb_task)
1746                         kthread_stop(hb_task);
1747                 goto out;
1748         }
1749
1750         /* Ok, we were woken.  Make sure it wasn't by drop_item() */
1751         spin_lock(&o2hb_live_lock);
1752         hb_task = reg->hr_task;
1753         if (o2hb_global_heartbeat_active())
1754                 set_bit(reg->hr_region_num, o2hb_live_region_bitmap);
1755         spin_unlock(&o2hb_live_lock);
1756
1757         if (hb_task)
1758                 ret = count;
1759         else
1760                 ret = -EIO;
1761
1762         if (hb_task && o2hb_global_heartbeat_active())
1763                 printk(KERN_NOTICE "o2hb: Heartbeat started on region %s\n",
1764                        config_item_name(&reg->hr_item));
1765
1766 out:
1767         if (filp)
1768                 fput(filp);
1769         if (inode)
1770                 iput(inode);
1771         if (ret < 0) {
1772                 if (reg->hr_bdev) {
1773                         blkdev_put(reg->hr_bdev, FMODE_READ|FMODE_WRITE);
1774                         reg->hr_bdev = NULL;
1775                 }
1776         }
1777         return ret;
1778 }
1779
1780 static ssize_t o2hb_region_pid_read(struct o2hb_region *reg,
1781                                       char *page)
1782 {
1783         pid_t pid = 0;
1784
1785         spin_lock(&o2hb_live_lock);
1786         if (reg->hr_task)
1787                 pid = task_pid_nr(reg->hr_task);
1788         spin_unlock(&o2hb_live_lock);
1789
1790         if (!pid)
1791                 return 0;
1792
1793         return sprintf(page, "%u\n", pid);
1794 }
1795
1796 struct o2hb_region_attribute {
1797         struct configfs_attribute attr;
1798         ssize_t (*show)(struct o2hb_region *, char *);
1799         ssize_t (*store)(struct o2hb_region *, const char *, size_t);
1800 };
1801
1802 static struct o2hb_region_attribute o2hb_region_attr_block_bytes = {
1803         .attr   = { .ca_owner = THIS_MODULE,
1804                     .ca_name = "block_bytes",
1805                     .ca_mode = S_IRUGO | S_IWUSR },
1806         .show   = o2hb_region_block_bytes_read,
1807         .store  = o2hb_region_block_bytes_write,
1808 };
1809
1810 static struct o2hb_region_attribute o2hb_region_attr_start_block = {
1811         .attr   = { .ca_owner = THIS_MODULE,
1812                     .ca_name = "start_block",
1813                     .ca_mode = S_IRUGO | S_IWUSR },
1814         .show   = o2hb_region_start_block_read,
1815         .store  = o2hb_region_start_block_write,
1816 };
1817
1818 static struct o2hb_region_attribute o2hb_region_attr_blocks = {
1819         .attr   = { .ca_owner = THIS_MODULE,
1820                     .ca_name = "blocks",
1821                     .ca_mode = S_IRUGO | S_IWUSR },
1822         .show   = o2hb_region_blocks_read,
1823         .store  = o2hb_region_blocks_write,
1824 };
1825
1826 static struct o2hb_region_attribute o2hb_region_attr_dev = {
1827         .attr   = { .ca_owner = THIS_MODULE,
1828                     .ca_name = "dev",
1829                     .ca_mode = S_IRUGO | S_IWUSR },
1830         .show   = o2hb_region_dev_read,
1831         .store  = o2hb_region_dev_write,
1832 };
1833
1834 static struct o2hb_region_attribute o2hb_region_attr_pid = {
1835        .attr   = { .ca_owner = THIS_MODULE,
1836                    .ca_name = "pid",
1837                    .ca_mode = S_IRUGO | S_IRUSR },
1838        .show   = o2hb_region_pid_read,
1839 };
1840
1841 static struct configfs_attribute *o2hb_region_attrs[] = {
1842         &o2hb_region_attr_block_bytes.attr,
1843         &o2hb_region_attr_start_block.attr,
1844         &o2hb_region_attr_blocks.attr,
1845         &o2hb_region_attr_dev.attr,
1846         &o2hb_region_attr_pid.attr,
1847         NULL,
1848 };
1849
1850 static ssize_t o2hb_region_show(struct config_item *item,
1851                                 struct configfs_attribute *attr,
1852                                 char *page)
1853 {
1854         struct o2hb_region *reg = to_o2hb_region(item);
1855         struct o2hb_region_attribute *o2hb_region_attr =
1856                 container_of(attr, struct o2hb_region_attribute, attr);
1857         ssize_t ret = 0;
1858
1859         if (o2hb_region_attr->show)
1860                 ret = o2hb_region_attr->show(reg, page);
1861         return ret;
1862 }
1863
1864 static ssize_t o2hb_region_store(struct config_item *item,
1865                                  struct configfs_attribute *attr,
1866                                  const char *page, size_t count)
1867 {
1868         struct o2hb_region *reg = to_o2hb_region(item);
1869         struct o2hb_region_attribute *o2hb_region_attr =
1870                 container_of(attr, struct o2hb_region_attribute, attr);
1871         ssize_t ret = -EINVAL;
1872
1873         if (o2hb_region_attr->store)
1874                 ret = o2hb_region_attr->store(reg, page, count);
1875         return ret;
1876 }
1877
1878 static struct configfs_item_operations o2hb_region_item_ops = {
1879         .release                = o2hb_region_release,
1880         .show_attribute         = o2hb_region_show,
1881         .store_attribute        = o2hb_region_store,
1882 };
1883
1884 static struct config_item_type o2hb_region_type = {
1885         .ct_item_ops    = &o2hb_region_item_ops,
1886         .ct_attrs       = o2hb_region_attrs,
1887         .ct_owner       = THIS_MODULE,
1888 };
1889
1890 /* heartbeat set */
1891
1892 struct o2hb_heartbeat_group {
1893         struct config_group hs_group;
1894         /* some stuff? */
1895 };
1896
1897 static struct o2hb_heartbeat_group *to_o2hb_heartbeat_group(struct config_group *group)
1898 {
1899         return group ?
1900                 container_of(group, struct o2hb_heartbeat_group, hs_group)
1901                 : NULL;
1902 }
1903
1904 static int o2hb_debug_region_init(struct o2hb_region *reg, struct dentry *dir)
1905 {
1906         int ret = -ENOMEM;
1907
1908         reg->hr_debug_dir =
1909                 debugfs_create_dir(config_item_name(&reg->hr_item), dir);
1910         if (!reg->hr_debug_dir) {
1911                 mlog_errno(ret);
1912                 goto bail;
1913         }
1914
1915         reg->hr_debug_livenodes =
1916                         o2hb_debug_create(O2HB_DEBUG_LIVENODES,
1917                                           reg->hr_debug_dir,
1918                                           &(reg->hr_db_livenodes),
1919                                           sizeof(*(reg->hr_db_livenodes)),
1920                                           O2HB_DB_TYPE_REGION_LIVENODES,
1921                                           sizeof(reg->hr_live_node_bitmap),
1922                                           O2NM_MAX_NODES, reg);
1923         if (!reg->hr_debug_livenodes) {
1924                 mlog_errno(ret);
1925                 goto bail;
1926         }
1927
1928         reg->hr_debug_regnum =
1929                         o2hb_debug_create(O2HB_DEBUG_REGION_NUMBER,
1930                                           reg->hr_debug_dir,
1931                                           &(reg->hr_db_regnum),
1932                                           sizeof(*(reg->hr_db_regnum)),
1933                                           O2HB_DB_TYPE_REGION_NUMBER,
1934                                           0, O2NM_MAX_NODES, reg);
1935         if (!reg->hr_debug_regnum) {
1936                 mlog_errno(ret);
1937                 goto bail;
1938         }
1939
1940         reg->hr_debug_elapsed_time =
1941                         o2hb_debug_create(O2HB_DEBUG_REGION_ELAPSED_TIME,
1942                                           reg->hr_debug_dir,
1943                                           &(reg->hr_db_elapsed_time),
1944                                           sizeof(*(reg->hr_db_elapsed_time)),
1945                                           O2HB_DB_TYPE_REGION_ELAPSED_TIME,
1946                                           0, 0, reg);
1947         if (!reg->hr_debug_elapsed_time) {
1948                 mlog_errno(ret);
1949                 goto bail;
1950         }
1951
1952         ret = 0;
1953 bail:
1954         return ret;
1955 }
1956
1957 static struct config_item *o2hb_heartbeat_group_make_item(struct config_group *group,
1958                                                           const char *name)
1959 {
1960         struct o2hb_region *reg = NULL;
1961         int ret;
1962
1963         reg = kzalloc(sizeof(struct o2hb_region), GFP_KERNEL);
1964         if (reg == NULL)
1965                 return ERR_PTR(-ENOMEM);
1966
1967         if (strlen(name) > O2HB_MAX_REGION_NAME_LEN)
1968                 return ERR_PTR(-ENAMETOOLONG);
1969
1970         spin_lock(&o2hb_live_lock);
1971         reg->hr_region_num = 0;
1972         if (o2hb_global_heartbeat_active()) {
1973                 reg->hr_region_num = find_first_zero_bit(o2hb_region_bitmap,
1974                                                          O2NM_MAX_REGIONS);
1975                 if (reg->hr_region_num >= O2NM_MAX_REGIONS) {
1976                         spin_unlock(&o2hb_live_lock);
1977                         return ERR_PTR(-EFBIG);
1978                 }
1979                 set_bit(reg->hr_region_num, o2hb_region_bitmap);
1980         }
1981         list_add_tail(&reg->hr_all_item, &o2hb_all_regions);
1982         spin_unlock(&o2hb_live_lock);
1983
1984         config_item_init_type_name(&reg->hr_item, name, &o2hb_region_type);
1985
1986         ret = o2hb_debug_region_init(reg, o2hb_debug_dir);
1987         if (ret) {
1988                 config_item_put(&reg->hr_item);
1989                 return ERR_PTR(ret);
1990         }
1991
1992         return &reg->hr_item;
1993 }
1994
1995 static void o2hb_heartbeat_group_drop_item(struct config_group *group,
1996                                            struct config_item *item)
1997 {
1998         struct task_struct *hb_task;
1999         struct o2hb_region *reg = to_o2hb_region(item);
2000
2001         /* stop the thread when the user removes the region dir */
2002         spin_lock(&o2hb_live_lock);
2003         if (o2hb_global_heartbeat_active()) {
2004                 clear_bit(reg->hr_region_num, o2hb_region_bitmap);
2005                 clear_bit(reg->hr_region_num, o2hb_live_region_bitmap);
2006         }
2007         hb_task = reg->hr_task;
2008         reg->hr_task = NULL;
2009         spin_unlock(&o2hb_live_lock);
2010
2011         if (hb_task)
2012                 kthread_stop(hb_task);
2013
2014         /*
2015          * If we're racing a dev_write(), we need to wake them.  They will
2016          * check reg->hr_task
2017          */
2018         if (atomic_read(&reg->hr_steady_iterations) != 0) {
2019                 atomic_set(&reg->hr_steady_iterations, 0);
2020                 wake_up(&o2hb_steady_queue);
2021         }
2022
2023         if (o2hb_global_heartbeat_active())
2024                 printk(KERN_NOTICE "o2hb: Heartbeat stopped on region %s\n",
2025                        config_item_name(&reg->hr_item));
2026         config_item_put(item);
2027 }
2028
2029 struct o2hb_heartbeat_group_attribute {
2030         struct configfs_attribute attr;
2031         ssize_t (*show)(struct o2hb_heartbeat_group *, char *);
2032         ssize_t (*store)(struct o2hb_heartbeat_group *, const char *, size_t);
2033 };
2034
2035 static ssize_t o2hb_heartbeat_group_show(struct config_item *item,
2036                                          struct configfs_attribute *attr,
2037                                          char *page)
2038 {
2039         struct o2hb_heartbeat_group *reg = to_o2hb_heartbeat_group(to_config_group(item));
2040         struct o2hb_heartbeat_group_attribute *o2hb_heartbeat_group_attr =
2041                 container_of(attr, struct o2hb_heartbeat_group_attribute, attr);
2042         ssize_t ret = 0;
2043
2044         if (o2hb_heartbeat_group_attr->show)
2045                 ret = o2hb_heartbeat_group_attr->show(reg, page);
2046         return ret;
2047 }
2048
2049 static ssize_t o2hb_heartbeat_group_store(struct config_item *item,
2050                                           struct configfs_attribute *attr,
2051                                           const char *page, size_t count)
2052 {
2053         struct o2hb_heartbeat_group *reg = to_o2hb_heartbeat_group(to_config_group(item));
2054         struct o2hb_heartbeat_group_attribute *o2hb_heartbeat_group_attr =
2055                 container_of(attr, struct o2hb_heartbeat_group_attribute, attr);
2056         ssize_t ret = -EINVAL;
2057
2058         if (o2hb_heartbeat_group_attr->store)
2059                 ret = o2hb_heartbeat_group_attr->store(reg, page, count);
2060         return ret;
2061 }
2062
2063 static ssize_t o2hb_heartbeat_group_threshold_show(struct o2hb_heartbeat_group *group,
2064                                                      char *page)
2065 {
2066         return sprintf(page, "%u\n", o2hb_dead_threshold);
2067 }
2068
2069 static ssize_t o2hb_heartbeat_group_threshold_store(struct o2hb_heartbeat_group *group,
2070                                                     const char *page,
2071                                                     size_t count)
2072 {
2073         unsigned long tmp;
2074         char *p = (char *)page;
2075
2076         tmp = simple_strtoul(p, &p, 10);
2077         if (!p || (*p && (*p != '\n')))
2078                 return -EINVAL;
2079
2080         /* this will validate ranges for us. */
2081         o2hb_dead_threshold_set((unsigned int) tmp);
2082
2083         return count;
2084 }
2085
2086 static
2087 ssize_t o2hb_heartbeat_group_mode_show(struct o2hb_heartbeat_group *group,
2088                                        char *page)
2089 {
2090         return sprintf(page, "%s\n",
2091                        o2hb_heartbeat_mode_desc[o2hb_heartbeat_mode]);
2092 }
2093
2094 static
2095 ssize_t o2hb_heartbeat_group_mode_store(struct o2hb_heartbeat_group *group,
2096                                         const char *page, size_t count)
2097 {
2098         unsigned int i;
2099         int ret;
2100         size_t len;
2101
2102         len = (page[count - 1] == '\n') ? count - 1 : count;
2103         if (!len)
2104                 return -EINVAL;
2105
2106         for (i = 0; i < O2HB_HEARTBEAT_NUM_MODES; ++i) {
2107                 if (strnicmp(page, o2hb_heartbeat_mode_desc[i], len))
2108                         continue;
2109
2110                 ret = o2hb_global_hearbeat_mode_set(i);
2111                 if (!ret)
2112                         printk(KERN_NOTICE "o2hb: Heartbeat mode set to %s\n",
2113                                o2hb_heartbeat_mode_desc[i]);
2114                 return count;
2115         }
2116
2117         return -EINVAL;
2118
2119 }
2120
2121 static struct o2hb_heartbeat_group_attribute o2hb_heartbeat_group_attr_threshold = {
2122         .attr   = { .ca_owner = THIS_MODULE,
2123                     .ca_name = "dead_threshold",
2124                     .ca_mode = S_IRUGO | S_IWUSR },
2125         .show   = o2hb_heartbeat_group_threshold_show,
2126         .store  = o2hb_heartbeat_group_threshold_store,
2127 };
2128
2129 static struct o2hb_heartbeat_group_attribute o2hb_heartbeat_group_attr_mode = {
2130         .attr   = { .ca_owner = THIS_MODULE,
2131                 .ca_name = "mode",
2132                 .ca_mode = S_IRUGO | S_IWUSR },
2133         .show   = o2hb_heartbeat_group_mode_show,
2134         .store  = o2hb_heartbeat_group_mode_store,
2135 };
2136
2137 static struct configfs_attribute *o2hb_heartbeat_group_attrs[] = {
2138         &o2hb_heartbeat_group_attr_threshold.attr,
2139         &o2hb_heartbeat_group_attr_mode.attr,
2140         NULL,
2141 };
2142
2143 static struct configfs_item_operations o2hb_hearbeat_group_item_ops = {
2144         .show_attribute         = o2hb_heartbeat_group_show,
2145         .store_attribute        = o2hb_heartbeat_group_store,
2146 };
2147
2148 static struct configfs_group_operations o2hb_heartbeat_group_group_ops = {
2149         .make_item      = o2hb_heartbeat_group_make_item,
2150         .drop_item      = o2hb_heartbeat_group_drop_item,
2151 };
2152
2153 static struct config_item_type o2hb_heartbeat_group_type = {
2154         .ct_group_ops   = &o2hb_heartbeat_group_group_ops,
2155         .ct_item_ops    = &o2hb_hearbeat_group_item_ops,
2156         .ct_attrs       = o2hb_heartbeat_group_attrs,
2157         .ct_owner       = THIS_MODULE,
2158 };
2159
2160 /* this is just here to avoid touching group in heartbeat.h which the
2161  * entire damn world #includes */
2162 struct config_group *o2hb_alloc_hb_set(void)
2163 {
2164         struct o2hb_heartbeat_group *hs = NULL;
2165         struct config_group *ret = NULL;
2166
2167         hs = kzalloc(sizeof(struct o2hb_heartbeat_group), GFP_KERNEL);
2168         if (hs == NULL)
2169                 goto out;
2170
2171         config_group_init_type_name(&hs->hs_group, "heartbeat",
2172                                     &o2hb_heartbeat_group_type);
2173
2174         ret = &hs->hs_group;
2175 out:
2176         if (ret == NULL)
2177                 kfree(hs);
2178         return ret;
2179 }
2180
2181 void o2hb_free_hb_set(struct config_group *group)
2182 {
2183         struct o2hb_heartbeat_group *hs = to_o2hb_heartbeat_group(group);
2184         kfree(hs);
2185 }
2186
2187 /* hb callback registration and issueing */
2188
2189 static struct o2hb_callback *hbcall_from_type(enum o2hb_callback_type type)
2190 {
2191         if (type == O2HB_NUM_CB)
2192                 return ERR_PTR(-EINVAL);
2193
2194         return &o2hb_callbacks[type];
2195 }
2196
2197 void o2hb_setup_callback(struct o2hb_callback_func *hc,
2198                          enum o2hb_callback_type type,
2199                          o2hb_cb_func *func,
2200                          void *data,
2201                          int priority)
2202 {
2203         INIT_LIST_HEAD(&hc->hc_item);
2204         hc->hc_func = func;
2205         hc->hc_data = data;
2206         hc->hc_priority = priority;
2207         hc->hc_type = type;
2208         hc->hc_magic = O2HB_CB_MAGIC;
2209 }
2210 EXPORT_SYMBOL_GPL(o2hb_setup_callback);
2211
2212 static struct o2hb_region *o2hb_find_region(const char *region_uuid)
2213 {
2214         struct o2hb_region *p, *reg = NULL;
2215
2216         assert_spin_locked(&o2hb_live_lock);
2217
2218         list_for_each_entry(p, &o2hb_all_regions, hr_all_item) {
2219                 if (!strcmp(region_uuid, config_item_name(&p->hr_item))) {
2220                         reg = p;
2221                         break;
2222                 }
2223         }
2224
2225         return reg;
2226 }
2227
2228 static int o2hb_region_get(const char *region_uuid)
2229 {
2230         int ret = 0;
2231         struct o2hb_region *reg;
2232
2233         spin_lock(&o2hb_live_lock);
2234
2235         reg = o2hb_find_region(region_uuid);
2236         if (!reg)
2237                 ret = -ENOENT;
2238         spin_unlock(&o2hb_live_lock);
2239
2240         if (ret)
2241                 goto out;
2242
2243         ret = o2nm_depend_this_node();
2244         if (ret)
2245                 goto out;
2246
2247         ret = o2nm_depend_item(&reg->hr_item);
2248         if (ret)
2249                 o2nm_undepend_this_node();
2250
2251 out:
2252         return ret;
2253 }
2254
2255 static void o2hb_region_put(const char *region_uuid)
2256 {
2257         struct o2hb_region *reg;
2258
2259         spin_lock(&o2hb_live_lock);
2260
2261         reg = o2hb_find_region(region_uuid);
2262
2263         spin_unlock(&o2hb_live_lock);
2264
2265         if (reg) {
2266                 o2nm_undepend_item(&reg->hr_item);
2267                 o2nm_undepend_this_node();
2268         }
2269 }
2270
2271 int o2hb_register_callback(const char *region_uuid,
2272                            struct o2hb_callback_func *hc)
2273 {
2274         struct o2hb_callback_func *tmp;
2275         struct list_head *iter;
2276         struct o2hb_callback *hbcall;
2277         int ret;
2278
2279         BUG_ON(hc->hc_magic != O2HB_CB_MAGIC);
2280         BUG_ON(!list_empty(&hc->hc_item));
2281
2282         hbcall = hbcall_from_type(hc->hc_type);
2283         if (IS_ERR(hbcall)) {
2284                 ret = PTR_ERR(hbcall);
2285                 goto out;
2286         }
2287
2288         if (region_uuid) {
2289                 ret = o2hb_region_get(region_uuid);
2290                 if (ret)
2291                         goto out;
2292         }
2293
2294         down_write(&o2hb_callback_sem);
2295
2296         list_for_each(iter, &hbcall->list) {
2297                 tmp = list_entry(iter, struct o2hb_callback_func, hc_item);
2298                 if (hc->hc_priority < tmp->hc_priority) {
2299                         list_add_tail(&hc->hc_item, iter);
2300                         break;
2301                 }
2302         }
2303         if (list_empty(&hc->hc_item))
2304                 list_add_tail(&hc->hc_item, &hbcall->list);
2305
2306         up_write(&o2hb_callback_sem);
2307         ret = 0;
2308 out:
2309         mlog(ML_HEARTBEAT, "returning %d on behalf of %p for funcs %p\n",
2310              ret, __builtin_return_address(0), hc);
2311         return ret;
2312 }
2313 EXPORT_SYMBOL_GPL(o2hb_register_callback);
2314
2315 void o2hb_unregister_callback(const char *region_uuid,
2316                               struct o2hb_callback_func *hc)
2317 {
2318         BUG_ON(hc->hc_magic != O2HB_CB_MAGIC);
2319
2320         mlog(ML_HEARTBEAT, "on behalf of %p for funcs %p\n",
2321              __builtin_return_address(0), hc);
2322
2323         /* XXX Can this happen _with_ a region reference? */
2324         if (list_empty(&hc->hc_item))
2325                 return;
2326
2327         if (region_uuid)
2328                 o2hb_region_put(region_uuid);
2329
2330         down_write(&o2hb_callback_sem);
2331
2332         list_del_init(&hc->hc_item);
2333
2334         up_write(&o2hb_callback_sem);
2335 }
2336 EXPORT_SYMBOL_GPL(o2hb_unregister_callback);
2337
2338 int o2hb_check_node_heartbeating(u8 node_num)
2339 {
2340         unsigned long testing_map[BITS_TO_LONGS(O2NM_MAX_NODES)];
2341
2342         o2hb_fill_node_map(testing_map, sizeof(testing_map));
2343         if (!test_bit(node_num, testing_map)) {
2344                 mlog(ML_HEARTBEAT,
2345                      "node (%u) does not have heartbeating enabled.\n",
2346                      node_num);
2347                 return 0;
2348         }
2349
2350         return 1;
2351 }
2352 EXPORT_SYMBOL_GPL(o2hb_check_node_heartbeating);
2353
2354 int o2hb_check_node_heartbeating_from_callback(u8 node_num)
2355 {
2356         unsigned long testing_map[BITS_TO_LONGS(O2NM_MAX_NODES)];
2357
2358         o2hb_fill_node_map_from_callback(testing_map, sizeof(testing_map));
2359         if (!test_bit(node_num, testing_map)) {
2360                 mlog(ML_HEARTBEAT,
2361                      "node (%u) does not have heartbeating enabled.\n",
2362                      node_num);
2363                 return 0;
2364         }
2365
2366         return 1;
2367 }
2368 EXPORT_SYMBOL_GPL(o2hb_check_node_heartbeating_from_callback);
2369
2370 /* Makes sure our local node is configured with a node number, and is
2371  * heartbeating. */
2372 int o2hb_check_local_node_heartbeating(void)
2373 {
2374         u8 node_num;
2375
2376         /* if this node was set then we have networking */
2377         node_num = o2nm_this_node();
2378         if (node_num == O2NM_MAX_NODES) {
2379                 mlog(ML_HEARTBEAT, "this node has not been configured.\n");
2380                 return 0;
2381         }
2382
2383         return o2hb_check_node_heartbeating(node_num);
2384 }
2385 EXPORT_SYMBOL_GPL(o2hb_check_local_node_heartbeating);
2386
2387 /*
2388  * this is just a hack until we get the plumbing which flips file systems
2389  * read only and drops the hb ref instead of killing the node dead.
2390  */
2391 void o2hb_stop_all_regions(void)
2392 {
2393         struct o2hb_region *reg;
2394
2395         mlog(ML_ERROR, "stopping heartbeat on all active regions.\n");
2396
2397         spin_lock(&o2hb_live_lock);
2398
2399         list_for_each_entry(reg, &o2hb_all_regions, hr_all_item)
2400                 reg->hr_unclean_stop = 1;
2401
2402         spin_unlock(&o2hb_live_lock);
2403 }
2404 EXPORT_SYMBOL_GPL(o2hb_stop_all_regions);
2405
2406 int o2hb_get_all_regions(char *region_uuids, u8 max_regions)
2407 {
2408         struct o2hb_region *reg;
2409         int numregs = 0;
2410         char *p;
2411
2412         spin_lock(&o2hb_live_lock);
2413
2414         p = region_uuids;
2415         list_for_each_entry(reg, &o2hb_all_regions, hr_all_item) {
2416                 mlog(0, "Region: %s\n", config_item_name(&reg->hr_item));
2417                 if (numregs < max_regions) {
2418                         memcpy(p, config_item_name(&reg->hr_item),
2419                                O2HB_MAX_REGION_NAME_LEN);
2420                         p += O2HB_MAX_REGION_NAME_LEN;
2421                 }
2422                 numregs++;
2423         }
2424
2425         spin_unlock(&o2hb_live_lock);
2426
2427         return numregs;
2428 }
2429 EXPORT_SYMBOL_GPL(o2hb_get_all_regions);
2430
2431 int o2hb_global_heartbeat_active(void)
2432 {
2433         return (o2hb_heartbeat_mode == O2HB_HEARTBEAT_GLOBAL);
2434 }
2435 EXPORT_SYMBOL(o2hb_global_heartbeat_active);