xref: /linux/drivers/md/dm-zoned-metadata.c (revision f86fd32d)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Copyright (C) 2017 Western Digital Corporation or its affiliates.
4  *
5  * This file is released under the GPL.
6  */
7 
8 #include "dm-zoned.h"
9 
10 #include <linux/module.h>
11 #include <linux/crc32.h>
12 #include <linux/sched/mm.h>
13 
14 #define	DM_MSG_PREFIX		"zoned metadata"
15 
16 /*
17  * Metadata version.
18  */
19 #define DMZ_META_VER	1
20 
21 /*
22  * On-disk super block magic.
23  */
24 #define DMZ_MAGIC	((((unsigned int)('D')) << 24) | \
25 			 (((unsigned int)('Z')) << 16) | \
26 			 (((unsigned int)('B')) <<  8) | \
27 			 ((unsigned int)('D')))
28 
29 /*
30  * On disk super block.
31  * This uses only 512 B but uses on disk a full 4KB block. This block is
32  * followed on disk by the mapping table of chunks to zones and the bitmap
33  * blocks indicating zone block validity.
34  * The overall resulting metadata format is:
35  *    (1) Super block (1 block)
36  *    (2) Chunk mapping table (nr_map_blocks)
37  *    (3) Bitmap blocks (nr_bitmap_blocks)
38  * All metadata blocks are stored in conventional zones, starting from
39  * the first conventional zone found on disk.
40  */
41 struct dmz_super {
42 	/* Magic number */
43 	__le32		magic;			/*   4 */
44 
45 	/* Metadata version number */
46 	__le32		version;		/*   8 */
47 
48 	/* Generation number */
49 	__le64		gen;			/*  16 */
50 
51 	/* This block number */
52 	__le64		sb_block;		/*  24 */
53 
54 	/* The number of metadata blocks, including this super block */
55 	__le32		nr_meta_blocks;		/*  28 */
56 
57 	/* The number of sequential zones reserved for reclaim */
58 	__le32		nr_reserved_seq;	/*  32 */
59 
60 	/* The number of entries in the mapping table */
61 	__le32		nr_chunks;		/*  36 */
62 
63 	/* The number of blocks used for the chunk mapping table */
64 	__le32		nr_map_blocks;		/*  40 */
65 
66 	/* The number of blocks used for the block bitmaps */
67 	__le32		nr_bitmap_blocks;	/*  44 */
68 
69 	/* Checksum */
70 	__le32		crc;			/*  48 */
71 
72 	/* Padding to full 512B sector */
73 	u8		reserved[464];		/* 512 */
74 };
75 
76 /*
77  * Chunk mapping entry: entries are indexed by chunk number
78  * and give the zone ID (dzone_id) mapping the chunk on disk.
79  * This zone may be sequential or random. If it is a sequential
80  * zone, a second zone (bzone_id) used as a write buffer may
81  * also be specified. This second zone will always be a randomly
82  * writeable zone.
83  */
84 struct dmz_map {
85 	__le32			dzone_id;
86 	__le32			bzone_id;
87 };
88 
89 /*
90  * Chunk mapping table metadata: 512 8-bytes entries per 4KB block.
91  */
92 #define DMZ_MAP_ENTRIES		(DMZ_BLOCK_SIZE / sizeof(struct dmz_map))
93 #define DMZ_MAP_ENTRIES_SHIFT	(ilog2(DMZ_MAP_ENTRIES))
94 #define DMZ_MAP_ENTRIES_MASK	(DMZ_MAP_ENTRIES - 1)
95 #define DMZ_MAP_UNMAPPED	UINT_MAX
96 
97 /*
98  * Meta data block descriptor (for cached metadata blocks).
99  */
100 struct dmz_mblock {
101 	struct rb_node		node;
102 	struct list_head	link;
103 	sector_t		no;
104 	unsigned int		ref;
105 	unsigned long		state;
106 	struct page		*page;
107 	void			*data;
108 };
109 
110 /*
111  * Metadata block state flags.
112  */
113 enum {
114 	DMZ_META_DIRTY,
115 	DMZ_META_READING,
116 	DMZ_META_WRITING,
117 	DMZ_META_ERROR,
118 };
119 
120 /*
121  * Super block information (one per metadata set).
122  */
123 struct dmz_sb {
124 	sector_t		block;
125 	struct dmz_mblock	*mblk;
126 	struct dmz_super	*sb;
127 };
128 
129 /*
130  * In-memory metadata.
131  */
132 struct dmz_metadata {
133 	struct dmz_dev		*dev;
134 
135 	sector_t		zone_bitmap_size;
136 	unsigned int		zone_nr_bitmap_blocks;
137 	unsigned int		zone_bits_per_mblk;
138 
139 	unsigned int		nr_bitmap_blocks;
140 	unsigned int		nr_map_blocks;
141 
142 	unsigned int		nr_useable_zones;
143 	unsigned int		nr_meta_blocks;
144 	unsigned int		nr_meta_zones;
145 	unsigned int		nr_data_zones;
146 	unsigned int		nr_rnd_zones;
147 	unsigned int		nr_reserved_seq;
148 	unsigned int		nr_chunks;
149 
150 	/* Zone information array */
151 	struct dm_zone		*zones;
152 
153 	struct dm_zone		*sb_zone;
154 	struct dmz_sb		sb[2];
155 	unsigned int		mblk_primary;
156 	u64			sb_gen;
157 	unsigned int		min_nr_mblks;
158 	unsigned int		max_nr_mblks;
159 	atomic_t		nr_mblks;
160 	struct rw_semaphore	mblk_sem;
161 	struct mutex		mblk_flush_lock;
162 	spinlock_t		mblk_lock;
163 	struct rb_root		mblk_rbtree;
164 	struct list_head	mblk_lru_list;
165 	struct list_head	mblk_dirty_list;
166 	struct shrinker		mblk_shrinker;
167 
168 	/* Zone allocation management */
169 	struct mutex		map_lock;
170 	struct dmz_mblock	**map_mblk;
171 	unsigned int		nr_rnd;
172 	atomic_t		unmap_nr_rnd;
173 	struct list_head	unmap_rnd_list;
174 	struct list_head	map_rnd_list;
175 
176 	unsigned int		nr_seq;
177 	atomic_t		unmap_nr_seq;
178 	struct list_head	unmap_seq_list;
179 	struct list_head	map_seq_list;
180 
181 	atomic_t		nr_reserved_seq_zones;
182 	struct list_head	reserved_seq_zones_list;
183 
184 	wait_queue_head_t	free_wq;
185 };
186 
187 /*
188  * Various accessors
189  */
190 unsigned int dmz_id(struct dmz_metadata *zmd, struct dm_zone *zone)
191 {
192 	return ((unsigned int)(zone - zmd->zones));
193 }
194 
195 sector_t dmz_start_sect(struct dmz_metadata *zmd, struct dm_zone *zone)
196 {
197 	return (sector_t)dmz_id(zmd, zone) << zmd->dev->zone_nr_sectors_shift;
198 }
199 
200 sector_t dmz_start_block(struct dmz_metadata *zmd, struct dm_zone *zone)
201 {
202 	return (sector_t)dmz_id(zmd, zone) << zmd->dev->zone_nr_blocks_shift;
203 }
204 
205 unsigned int dmz_nr_chunks(struct dmz_metadata *zmd)
206 {
207 	return zmd->nr_chunks;
208 }
209 
210 unsigned int dmz_nr_rnd_zones(struct dmz_metadata *zmd)
211 {
212 	return zmd->nr_rnd;
213 }
214 
215 unsigned int dmz_nr_unmap_rnd_zones(struct dmz_metadata *zmd)
216 {
217 	return atomic_read(&zmd->unmap_nr_rnd);
218 }
219 
220 /*
221  * Lock/unlock mapping table.
222  * The map lock also protects all the zone lists.
223  */
224 void dmz_lock_map(struct dmz_metadata *zmd)
225 {
226 	mutex_lock(&zmd->map_lock);
227 }
228 
229 void dmz_unlock_map(struct dmz_metadata *zmd)
230 {
231 	mutex_unlock(&zmd->map_lock);
232 }
233 
234 /*
235  * Lock/unlock metadata access. This is a "read" lock on a semaphore
236  * that prevents metadata flush from running while metadata are being
237  * modified. The actual metadata write mutual exclusion is achieved with
238  * the map lock and zone state management (active and reclaim state are
239  * mutually exclusive).
240  */
241 void dmz_lock_metadata(struct dmz_metadata *zmd)
242 {
243 	down_read(&zmd->mblk_sem);
244 }
245 
246 void dmz_unlock_metadata(struct dmz_metadata *zmd)
247 {
248 	up_read(&zmd->mblk_sem);
249 }
250 
251 /*
252  * Lock/unlock flush: prevent concurrent executions
253  * of dmz_flush_metadata as well as metadata modification in reclaim
254  * while flush is being executed.
255  */
256 void dmz_lock_flush(struct dmz_metadata *zmd)
257 {
258 	mutex_lock(&zmd->mblk_flush_lock);
259 }
260 
261 void dmz_unlock_flush(struct dmz_metadata *zmd)
262 {
263 	mutex_unlock(&zmd->mblk_flush_lock);
264 }
265 
266 /*
267  * Allocate a metadata block.
268  */
269 static struct dmz_mblock *dmz_alloc_mblock(struct dmz_metadata *zmd,
270 					   sector_t mblk_no)
271 {
272 	struct dmz_mblock *mblk = NULL;
273 
274 	/* See if we can reuse cached blocks */
275 	if (zmd->max_nr_mblks && atomic_read(&zmd->nr_mblks) > zmd->max_nr_mblks) {
276 		spin_lock(&zmd->mblk_lock);
277 		mblk = list_first_entry_or_null(&zmd->mblk_lru_list,
278 						struct dmz_mblock, link);
279 		if (mblk) {
280 			list_del_init(&mblk->link);
281 			rb_erase(&mblk->node, &zmd->mblk_rbtree);
282 			mblk->no = mblk_no;
283 		}
284 		spin_unlock(&zmd->mblk_lock);
285 		if (mblk)
286 			return mblk;
287 	}
288 
289 	/* Allocate a new block */
290 	mblk = kmalloc(sizeof(struct dmz_mblock), GFP_NOIO);
291 	if (!mblk)
292 		return NULL;
293 
294 	mblk->page = alloc_page(GFP_NOIO);
295 	if (!mblk->page) {
296 		kfree(mblk);
297 		return NULL;
298 	}
299 
300 	RB_CLEAR_NODE(&mblk->node);
301 	INIT_LIST_HEAD(&mblk->link);
302 	mblk->ref = 0;
303 	mblk->state = 0;
304 	mblk->no = mblk_no;
305 	mblk->data = page_address(mblk->page);
306 
307 	atomic_inc(&zmd->nr_mblks);
308 
309 	return mblk;
310 }
311 
312 /*
313  * Free a metadata block.
314  */
315 static void dmz_free_mblock(struct dmz_metadata *zmd, struct dmz_mblock *mblk)
316 {
317 	__free_pages(mblk->page, 0);
318 	kfree(mblk);
319 
320 	atomic_dec(&zmd->nr_mblks);
321 }
322 
323 /*
324  * Insert a metadata block in the rbtree.
325  */
326 static void dmz_insert_mblock(struct dmz_metadata *zmd, struct dmz_mblock *mblk)
327 {
328 	struct rb_root *root = &zmd->mblk_rbtree;
329 	struct rb_node **new = &(root->rb_node), *parent = NULL;
330 	struct dmz_mblock *b;
331 
332 	/* Figure out where to put the new node */
333 	while (*new) {
334 		b = container_of(*new, struct dmz_mblock, node);
335 		parent = *new;
336 		new = (b->no < mblk->no) ? &((*new)->rb_left) : &((*new)->rb_right);
337 	}
338 
339 	/* Add new node and rebalance tree */
340 	rb_link_node(&mblk->node, parent, new);
341 	rb_insert_color(&mblk->node, root);
342 }
343 
344 /*
345  * Lookup a metadata block in the rbtree. If the block is found, increment
346  * its reference count.
347  */
348 static struct dmz_mblock *dmz_get_mblock_fast(struct dmz_metadata *zmd,
349 					      sector_t mblk_no)
350 {
351 	struct rb_root *root = &zmd->mblk_rbtree;
352 	struct rb_node *node = root->rb_node;
353 	struct dmz_mblock *mblk;
354 
355 	while (node) {
356 		mblk = container_of(node, struct dmz_mblock, node);
357 		if (mblk->no == mblk_no) {
358 			/*
359 			 * If this is the first reference to the block,
360 			 * remove it from the LRU list.
361 			 */
362 			mblk->ref++;
363 			if (mblk->ref == 1 &&
364 			    !test_bit(DMZ_META_DIRTY, &mblk->state))
365 				list_del_init(&mblk->link);
366 			return mblk;
367 		}
368 		node = (mblk->no < mblk_no) ? node->rb_left : node->rb_right;
369 	}
370 
371 	return NULL;
372 }
373 
374 /*
375  * Metadata block BIO end callback.
376  */
377 static void dmz_mblock_bio_end_io(struct bio *bio)
378 {
379 	struct dmz_mblock *mblk = bio->bi_private;
380 	int flag;
381 
382 	if (bio->bi_status)
383 		set_bit(DMZ_META_ERROR, &mblk->state);
384 
385 	if (bio_op(bio) == REQ_OP_WRITE)
386 		flag = DMZ_META_WRITING;
387 	else
388 		flag = DMZ_META_READING;
389 
390 	clear_bit_unlock(flag, &mblk->state);
391 	smp_mb__after_atomic();
392 	wake_up_bit(&mblk->state, flag);
393 
394 	bio_put(bio);
395 }
396 
397 /*
398  * Read an uncached metadata block from disk and add it to the cache.
399  */
400 static struct dmz_mblock *dmz_get_mblock_slow(struct dmz_metadata *zmd,
401 					      sector_t mblk_no)
402 {
403 	struct dmz_mblock *mblk, *m;
404 	sector_t block = zmd->sb[zmd->mblk_primary].block + mblk_no;
405 	struct bio *bio;
406 
407 	if (dmz_bdev_is_dying(zmd->dev))
408 		return ERR_PTR(-EIO);
409 
410 	/* Get a new block and a BIO to read it */
411 	mblk = dmz_alloc_mblock(zmd, mblk_no);
412 	if (!mblk)
413 		return ERR_PTR(-ENOMEM);
414 
415 	bio = bio_alloc(GFP_NOIO, 1);
416 	if (!bio) {
417 		dmz_free_mblock(zmd, mblk);
418 		return ERR_PTR(-ENOMEM);
419 	}
420 
421 	spin_lock(&zmd->mblk_lock);
422 
423 	/*
424 	 * Make sure that another context did not start reading
425 	 * the block already.
426 	 */
427 	m = dmz_get_mblock_fast(zmd, mblk_no);
428 	if (m) {
429 		spin_unlock(&zmd->mblk_lock);
430 		dmz_free_mblock(zmd, mblk);
431 		bio_put(bio);
432 		return m;
433 	}
434 
435 	mblk->ref++;
436 	set_bit(DMZ_META_READING, &mblk->state);
437 	dmz_insert_mblock(zmd, mblk);
438 
439 	spin_unlock(&zmd->mblk_lock);
440 
441 	/* Submit read BIO */
442 	bio->bi_iter.bi_sector = dmz_blk2sect(block);
443 	bio_set_dev(bio, zmd->dev->bdev);
444 	bio->bi_private = mblk;
445 	bio->bi_end_io = dmz_mblock_bio_end_io;
446 	bio_set_op_attrs(bio, REQ_OP_READ, REQ_META | REQ_PRIO);
447 	bio_add_page(bio, mblk->page, DMZ_BLOCK_SIZE, 0);
448 	submit_bio(bio);
449 
450 	return mblk;
451 }
452 
453 /*
454  * Free metadata blocks.
455  */
456 static unsigned long dmz_shrink_mblock_cache(struct dmz_metadata *zmd,
457 					     unsigned long limit)
458 {
459 	struct dmz_mblock *mblk;
460 	unsigned long count = 0;
461 
462 	if (!zmd->max_nr_mblks)
463 		return 0;
464 
465 	while (!list_empty(&zmd->mblk_lru_list) &&
466 	       atomic_read(&zmd->nr_mblks) > zmd->min_nr_mblks &&
467 	       count < limit) {
468 		mblk = list_first_entry(&zmd->mblk_lru_list,
469 					struct dmz_mblock, link);
470 		list_del_init(&mblk->link);
471 		rb_erase(&mblk->node, &zmd->mblk_rbtree);
472 		dmz_free_mblock(zmd, mblk);
473 		count++;
474 	}
475 
476 	return count;
477 }
478 
479 /*
480  * For mblock shrinker: get the number of unused metadata blocks in the cache.
481  */
482 static unsigned long dmz_mblock_shrinker_count(struct shrinker *shrink,
483 					       struct shrink_control *sc)
484 {
485 	struct dmz_metadata *zmd = container_of(shrink, struct dmz_metadata, mblk_shrinker);
486 
487 	return atomic_read(&zmd->nr_mblks);
488 }
489 
490 /*
491  * For mblock shrinker: scan unused metadata blocks and shrink the cache.
492  */
493 static unsigned long dmz_mblock_shrinker_scan(struct shrinker *shrink,
494 					      struct shrink_control *sc)
495 {
496 	struct dmz_metadata *zmd = container_of(shrink, struct dmz_metadata, mblk_shrinker);
497 	unsigned long count;
498 
499 	spin_lock(&zmd->mblk_lock);
500 	count = dmz_shrink_mblock_cache(zmd, sc->nr_to_scan);
501 	spin_unlock(&zmd->mblk_lock);
502 
503 	return count ? count : SHRINK_STOP;
504 }
505 
506 /*
507  * Release a metadata block.
508  */
509 static void dmz_release_mblock(struct dmz_metadata *zmd,
510 			       struct dmz_mblock *mblk)
511 {
512 
513 	if (!mblk)
514 		return;
515 
516 	spin_lock(&zmd->mblk_lock);
517 
518 	mblk->ref--;
519 	if (mblk->ref == 0) {
520 		if (test_bit(DMZ_META_ERROR, &mblk->state)) {
521 			rb_erase(&mblk->node, &zmd->mblk_rbtree);
522 			dmz_free_mblock(zmd, mblk);
523 		} else if (!test_bit(DMZ_META_DIRTY, &mblk->state)) {
524 			list_add_tail(&mblk->link, &zmd->mblk_lru_list);
525 			dmz_shrink_mblock_cache(zmd, 1);
526 		}
527 	}
528 
529 	spin_unlock(&zmd->mblk_lock);
530 }
531 
532 /*
533  * Get a metadata block from the rbtree. If the block
534  * is not present, read it from disk.
535  */
536 static struct dmz_mblock *dmz_get_mblock(struct dmz_metadata *zmd,
537 					 sector_t mblk_no)
538 {
539 	struct dmz_mblock *mblk;
540 
541 	/* Check rbtree */
542 	spin_lock(&zmd->mblk_lock);
543 	mblk = dmz_get_mblock_fast(zmd, mblk_no);
544 	spin_unlock(&zmd->mblk_lock);
545 
546 	if (!mblk) {
547 		/* Cache miss: read the block from disk */
548 		mblk = dmz_get_mblock_slow(zmd, mblk_no);
549 		if (IS_ERR(mblk))
550 			return mblk;
551 	}
552 
553 	/* Wait for on-going read I/O and check for error */
554 	wait_on_bit_io(&mblk->state, DMZ_META_READING,
555 		       TASK_UNINTERRUPTIBLE);
556 	if (test_bit(DMZ_META_ERROR, &mblk->state)) {
557 		dmz_release_mblock(zmd, mblk);
558 		dmz_check_bdev(zmd->dev);
559 		return ERR_PTR(-EIO);
560 	}
561 
562 	return mblk;
563 }
564 
565 /*
566  * Mark a metadata block dirty.
567  */
568 static void dmz_dirty_mblock(struct dmz_metadata *zmd, struct dmz_mblock *mblk)
569 {
570 	spin_lock(&zmd->mblk_lock);
571 	if (!test_and_set_bit(DMZ_META_DIRTY, &mblk->state))
572 		list_add_tail(&mblk->link, &zmd->mblk_dirty_list);
573 	spin_unlock(&zmd->mblk_lock);
574 }
575 
576 /*
577  * Issue a metadata block write BIO.
578  */
579 static int dmz_write_mblock(struct dmz_metadata *zmd, struct dmz_mblock *mblk,
580 			    unsigned int set)
581 {
582 	sector_t block = zmd->sb[set].block + mblk->no;
583 	struct bio *bio;
584 
585 	if (dmz_bdev_is_dying(zmd->dev))
586 		return -EIO;
587 
588 	bio = bio_alloc(GFP_NOIO, 1);
589 	if (!bio) {
590 		set_bit(DMZ_META_ERROR, &mblk->state);
591 		return -ENOMEM;
592 	}
593 
594 	set_bit(DMZ_META_WRITING, &mblk->state);
595 
596 	bio->bi_iter.bi_sector = dmz_blk2sect(block);
597 	bio_set_dev(bio, zmd->dev->bdev);
598 	bio->bi_private = mblk;
599 	bio->bi_end_io = dmz_mblock_bio_end_io;
600 	bio_set_op_attrs(bio, REQ_OP_WRITE, REQ_META | REQ_PRIO);
601 	bio_add_page(bio, mblk->page, DMZ_BLOCK_SIZE, 0);
602 	submit_bio(bio);
603 
604 	return 0;
605 }
606 
607 /*
608  * Read/write a metadata block.
609  */
610 static int dmz_rdwr_block(struct dmz_metadata *zmd, int op, sector_t block,
611 			  struct page *page)
612 {
613 	struct bio *bio;
614 	int ret;
615 
616 	if (dmz_bdev_is_dying(zmd->dev))
617 		return -EIO;
618 
619 	bio = bio_alloc(GFP_NOIO, 1);
620 	if (!bio)
621 		return -ENOMEM;
622 
623 	bio->bi_iter.bi_sector = dmz_blk2sect(block);
624 	bio_set_dev(bio, zmd->dev->bdev);
625 	bio_set_op_attrs(bio, op, REQ_SYNC | REQ_META | REQ_PRIO);
626 	bio_add_page(bio, page, DMZ_BLOCK_SIZE, 0);
627 	ret = submit_bio_wait(bio);
628 	bio_put(bio);
629 
630 	if (ret)
631 		dmz_check_bdev(zmd->dev);
632 	return ret;
633 }
634 
635 /*
636  * Write super block of the specified metadata set.
637  */
638 static int dmz_write_sb(struct dmz_metadata *zmd, unsigned int set)
639 {
640 	sector_t block = zmd->sb[set].block;
641 	struct dmz_mblock *mblk = zmd->sb[set].mblk;
642 	struct dmz_super *sb = zmd->sb[set].sb;
643 	u64 sb_gen = zmd->sb_gen + 1;
644 	int ret;
645 
646 	sb->magic = cpu_to_le32(DMZ_MAGIC);
647 	sb->version = cpu_to_le32(DMZ_META_VER);
648 
649 	sb->gen = cpu_to_le64(sb_gen);
650 
651 	sb->sb_block = cpu_to_le64(block);
652 	sb->nr_meta_blocks = cpu_to_le32(zmd->nr_meta_blocks);
653 	sb->nr_reserved_seq = cpu_to_le32(zmd->nr_reserved_seq);
654 	sb->nr_chunks = cpu_to_le32(zmd->nr_chunks);
655 
656 	sb->nr_map_blocks = cpu_to_le32(zmd->nr_map_blocks);
657 	sb->nr_bitmap_blocks = cpu_to_le32(zmd->nr_bitmap_blocks);
658 
659 	sb->crc = 0;
660 	sb->crc = cpu_to_le32(crc32_le(sb_gen, (unsigned char *)sb, DMZ_BLOCK_SIZE));
661 
662 	ret = dmz_rdwr_block(zmd, REQ_OP_WRITE, block, mblk->page);
663 	if (ret == 0)
664 		ret = blkdev_issue_flush(zmd->dev->bdev, GFP_NOIO, NULL);
665 
666 	return ret;
667 }
668 
669 /*
670  * Write dirty metadata blocks to the specified set.
671  */
672 static int dmz_write_dirty_mblocks(struct dmz_metadata *zmd,
673 				   struct list_head *write_list,
674 				   unsigned int set)
675 {
676 	struct dmz_mblock *mblk;
677 	struct blk_plug plug;
678 	int ret = 0, nr_mblks_submitted = 0;
679 
680 	/* Issue writes */
681 	blk_start_plug(&plug);
682 	list_for_each_entry(mblk, write_list, link) {
683 		ret = dmz_write_mblock(zmd, mblk, set);
684 		if (ret)
685 			break;
686 		nr_mblks_submitted++;
687 	}
688 	blk_finish_plug(&plug);
689 
690 	/* Wait for completion */
691 	list_for_each_entry(mblk, write_list, link) {
692 		if (!nr_mblks_submitted)
693 			break;
694 		wait_on_bit_io(&mblk->state, DMZ_META_WRITING,
695 			       TASK_UNINTERRUPTIBLE);
696 		if (test_bit(DMZ_META_ERROR, &mblk->state)) {
697 			clear_bit(DMZ_META_ERROR, &mblk->state);
698 			dmz_check_bdev(zmd->dev);
699 			ret = -EIO;
700 		}
701 		nr_mblks_submitted--;
702 	}
703 
704 	/* Flush drive cache (this will also sync data) */
705 	if (ret == 0)
706 		ret = blkdev_issue_flush(zmd->dev->bdev, GFP_NOIO, NULL);
707 
708 	return ret;
709 }
710 
711 /*
712  * Log dirty metadata blocks.
713  */
714 static int dmz_log_dirty_mblocks(struct dmz_metadata *zmd,
715 				 struct list_head *write_list)
716 {
717 	unsigned int log_set = zmd->mblk_primary ^ 0x1;
718 	int ret;
719 
720 	/* Write dirty blocks to the log */
721 	ret = dmz_write_dirty_mblocks(zmd, write_list, log_set);
722 	if (ret)
723 		return ret;
724 
725 	/*
726 	 * No error so far: now validate the log by updating the
727 	 * log index super block generation.
728 	 */
729 	ret = dmz_write_sb(zmd, log_set);
730 	if (ret)
731 		return ret;
732 
733 	return 0;
734 }
735 
736 /*
737  * Flush dirty metadata blocks.
738  */
739 int dmz_flush_metadata(struct dmz_metadata *zmd)
740 {
741 	struct dmz_mblock *mblk;
742 	struct list_head write_list;
743 	int ret;
744 
745 	if (WARN_ON(!zmd))
746 		return 0;
747 
748 	INIT_LIST_HEAD(&write_list);
749 
750 	/*
751 	 * Make sure that metadata blocks are stable before logging: take
752 	 * the write lock on the metadata semaphore to prevent target BIOs
753 	 * from modifying metadata.
754 	 */
755 	down_write(&zmd->mblk_sem);
756 
757 	/*
758 	 * This is called from the target flush work and reclaim work.
759 	 * Concurrent execution is not allowed.
760 	 */
761 	dmz_lock_flush(zmd);
762 
763 	if (dmz_bdev_is_dying(zmd->dev)) {
764 		ret = -EIO;
765 		goto out;
766 	}
767 
768 	/* Get dirty blocks */
769 	spin_lock(&zmd->mblk_lock);
770 	list_splice_init(&zmd->mblk_dirty_list, &write_list);
771 	spin_unlock(&zmd->mblk_lock);
772 
773 	/* If there are no dirty metadata blocks, just flush the device cache */
774 	if (list_empty(&write_list)) {
775 		ret = blkdev_issue_flush(zmd->dev->bdev, GFP_NOIO, NULL);
776 		goto err;
777 	}
778 
779 	/*
780 	 * The primary metadata set is still clean. Keep it this way until
781 	 * all updates are successful in the secondary set. That is, use
782 	 * the secondary set as a log.
783 	 */
784 	ret = dmz_log_dirty_mblocks(zmd, &write_list);
785 	if (ret)
786 		goto err;
787 
788 	/*
789 	 * The log is on disk. It is now safe to update in place
790 	 * in the primary metadata set.
791 	 */
792 	ret = dmz_write_dirty_mblocks(zmd, &write_list, zmd->mblk_primary);
793 	if (ret)
794 		goto err;
795 
796 	ret = dmz_write_sb(zmd, zmd->mblk_primary);
797 	if (ret)
798 		goto err;
799 
800 	while (!list_empty(&write_list)) {
801 		mblk = list_first_entry(&write_list, struct dmz_mblock, link);
802 		list_del_init(&mblk->link);
803 
804 		spin_lock(&zmd->mblk_lock);
805 		clear_bit(DMZ_META_DIRTY, &mblk->state);
806 		if (mblk->ref == 0)
807 			list_add_tail(&mblk->link, &zmd->mblk_lru_list);
808 		spin_unlock(&zmd->mblk_lock);
809 	}
810 
811 	zmd->sb_gen++;
812 out:
813 	dmz_unlock_flush(zmd);
814 	up_write(&zmd->mblk_sem);
815 
816 	return ret;
817 
818 err:
819 	if (!list_empty(&write_list)) {
820 		spin_lock(&zmd->mblk_lock);
821 		list_splice(&write_list, &zmd->mblk_dirty_list);
822 		spin_unlock(&zmd->mblk_lock);
823 	}
824 	if (!dmz_check_bdev(zmd->dev))
825 		ret = -EIO;
826 	goto out;
827 }
828 
829 /*
830  * Check super block.
831  */
832 static int dmz_check_sb(struct dmz_metadata *zmd, struct dmz_super *sb)
833 {
834 	unsigned int nr_meta_zones, nr_data_zones;
835 	struct dmz_dev *dev = zmd->dev;
836 	u32 crc, stored_crc;
837 	u64 gen;
838 
839 	gen = le64_to_cpu(sb->gen);
840 	stored_crc = le32_to_cpu(sb->crc);
841 	sb->crc = 0;
842 	crc = crc32_le(gen, (unsigned char *)sb, DMZ_BLOCK_SIZE);
843 	if (crc != stored_crc) {
844 		dmz_dev_err(dev, "Invalid checksum (needed 0x%08x, got 0x%08x)",
845 			    crc, stored_crc);
846 		return -ENXIO;
847 	}
848 
849 	if (le32_to_cpu(sb->magic) != DMZ_MAGIC) {
850 		dmz_dev_err(dev, "Invalid meta magic (needed 0x%08x, got 0x%08x)",
851 			    DMZ_MAGIC, le32_to_cpu(sb->magic));
852 		return -ENXIO;
853 	}
854 
855 	if (le32_to_cpu(sb->version) != DMZ_META_VER) {
856 		dmz_dev_err(dev, "Invalid meta version (needed %d, got %d)",
857 			    DMZ_META_VER, le32_to_cpu(sb->version));
858 		return -ENXIO;
859 	}
860 
861 	nr_meta_zones = (le32_to_cpu(sb->nr_meta_blocks) + dev->zone_nr_blocks - 1)
862 		>> dev->zone_nr_blocks_shift;
863 	if (!nr_meta_zones ||
864 	    nr_meta_zones >= zmd->nr_rnd_zones) {
865 		dmz_dev_err(dev, "Invalid number of metadata blocks");
866 		return -ENXIO;
867 	}
868 
869 	if (!le32_to_cpu(sb->nr_reserved_seq) ||
870 	    le32_to_cpu(sb->nr_reserved_seq) >= (zmd->nr_useable_zones - nr_meta_zones)) {
871 		dmz_dev_err(dev, "Invalid number of reserved sequential zones");
872 		return -ENXIO;
873 	}
874 
875 	nr_data_zones = zmd->nr_useable_zones -
876 		(nr_meta_zones * 2 + le32_to_cpu(sb->nr_reserved_seq));
877 	if (le32_to_cpu(sb->nr_chunks) > nr_data_zones) {
878 		dmz_dev_err(dev, "Invalid number of chunks %u / %u",
879 			    le32_to_cpu(sb->nr_chunks), nr_data_zones);
880 		return -ENXIO;
881 	}
882 
883 	/* OK */
884 	zmd->nr_meta_blocks = le32_to_cpu(sb->nr_meta_blocks);
885 	zmd->nr_reserved_seq = le32_to_cpu(sb->nr_reserved_seq);
886 	zmd->nr_chunks = le32_to_cpu(sb->nr_chunks);
887 	zmd->nr_map_blocks = le32_to_cpu(sb->nr_map_blocks);
888 	zmd->nr_bitmap_blocks = le32_to_cpu(sb->nr_bitmap_blocks);
889 	zmd->nr_meta_zones = nr_meta_zones;
890 	zmd->nr_data_zones = nr_data_zones;
891 
892 	return 0;
893 }
894 
895 /*
896  * Read the first or second super block from disk.
897  */
898 static int dmz_read_sb(struct dmz_metadata *zmd, unsigned int set)
899 {
900 	return dmz_rdwr_block(zmd, REQ_OP_READ, zmd->sb[set].block,
901 			      zmd->sb[set].mblk->page);
902 }
903 
904 /*
905  * Determine the position of the secondary super blocks on disk.
906  * This is used only if a corruption of the primary super block
907  * is detected.
908  */
909 static int dmz_lookup_secondary_sb(struct dmz_metadata *zmd)
910 {
911 	unsigned int zone_nr_blocks = zmd->dev->zone_nr_blocks;
912 	struct dmz_mblock *mblk;
913 	int i;
914 
915 	/* Allocate a block */
916 	mblk = dmz_alloc_mblock(zmd, 0);
917 	if (!mblk)
918 		return -ENOMEM;
919 
920 	zmd->sb[1].mblk = mblk;
921 	zmd->sb[1].sb = mblk->data;
922 
923 	/* Bad first super block: search for the second one */
924 	zmd->sb[1].block = zmd->sb[0].block + zone_nr_blocks;
925 	for (i = 0; i < zmd->nr_rnd_zones - 1; i++) {
926 		if (dmz_read_sb(zmd, 1) != 0)
927 			break;
928 		if (le32_to_cpu(zmd->sb[1].sb->magic) == DMZ_MAGIC)
929 			return 0;
930 		zmd->sb[1].block += zone_nr_blocks;
931 	}
932 
933 	dmz_free_mblock(zmd, mblk);
934 	zmd->sb[1].mblk = NULL;
935 
936 	return -EIO;
937 }
938 
939 /*
940  * Read the first or second super block from disk.
941  */
942 static int dmz_get_sb(struct dmz_metadata *zmd, unsigned int set)
943 {
944 	struct dmz_mblock *mblk;
945 	int ret;
946 
947 	/* Allocate a block */
948 	mblk = dmz_alloc_mblock(zmd, 0);
949 	if (!mblk)
950 		return -ENOMEM;
951 
952 	zmd->sb[set].mblk = mblk;
953 	zmd->sb[set].sb = mblk->data;
954 
955 	/* Read super block */
956 	ret = dmz_read_sb(zmd, set);
957 	if (ret) {
958 		dmz_free_mblock(zmd, mblk);
959 		zmd->sb[set].mblk = NULL;
960 		return ret;
961 	}
962 
963 	return 0;
964 }
965 
966 /*
967  * Recover a metadata set.
968  */
969 static int dmz_recover_mblocks(struct dmz_metadata *zmd, unsigned int dst_set)
970 {
971 	unsigned int src_set = dst_set ^ 0x1;
972 	struct page *page;
973 	int i, ret;
974 
975 	dmz_dev_warn(zmd->dev, "Metadata set %u invalid: recovering", dst_set);
976 
977 	if (dst_set == 0)
978 		zmd->sb[0].block = dmz_start_block(zmd, zmd->sb_zone);
979 	else {
980 		zmd->sb[1].block = zmd->sb[0].block +
981 			(zmd->nr_meta_zones << zmd->dev->zone_nr_blocks_shift);
982 	}
983 
984 	page = alloc_page(GFP_NOIO);
985 	if (!page)
986 		return -ENOMEM;
987 
988 	/* Copy metadata blocks */
989 	for (i = 1; i < zmd->nr_meta_blocks; i++) {
990 		ret = dmz_rdwr_block(zmd, REQ_OP_READ,
991 				     zmd->sb[src_set].block + i, page);
992 		if (ret)
993 			goto out;
994 		ret = dmz_rdwr_block(zmd, REQ_OP_WRITE,
995 				     zmd->sb[dst_set].block + i, page);
996 		if (ret)
997 			goto out;
998 	}
999 
1000 	/* Finalize with the super block */
1001 	if (!zmd->sb[dst_set].mblk) {
1002 		zmd->sb[dst_set].mblk = dmz_alloc_mblock(zmd, 0);
1003 		if (!zmd->sb[dst_set].mblk) {
1004 			ret = -ENOMEM;
1005 			goto out;
1006 		}
1007 		zmd->sb[dst_set].sb = zmd->sb[dst_set].mblk->data;
1008 	}
1009 
1010 	ret = dmz_write_sb(zmd, dst_set);
1011 out:
1012 	__free_pages(page, 0);
1013 
1014 	return ret;
1015 }
1016 
1017 /*
1018  * Get super block from disk.
1019  */
1020 static int dmz_load_sb(struct dmz_metadata *zmd)
1021 {
1022 	bool sb_good[2] = {false, false};
1023 	u64 sb_gen[2] = {0, 0};
1024 	int ret;
1025 
1026 	/* Read and check the primary super block */
1027 	zmd->sb[0].block = dmz_start_block(zmd, zmd->sb_zone);
1028 	ret = dmz_get_sb(zmd, 0);
1029 	if (ret) {
1030 		dmz_dev_err(zmd->dev, "Read primary super block failed");
1031 		return ret;
1032 	}
1033 
1034 	ret = dmz_check_sb(zmd, zmd->sb[0].sb);
1035 
1036 	/* Read and check secondary super block */
1037 	if (ret == 0) {
1038 		sb_good[0] = true;
1039 		zmd->sb[1].block = zmd->sb[0].block +
1040 			(zmd->nr_meta_zones << zmd->dev->zone_nr_blocks_shift);
1041 		ret = dmz_get_sb(zmd, 1);
1042 	} else
1043 		ret = dmz_lookup_secondary_sb(zmd);
1044 
1045 	if (ret) {
1046 		dmz_dev_err(zmd->dev, "Read secondary super block failed");
1047 		return ret;
1048 	}
1049 
1050 	ret = dmz_check_sb(zmd, zmd->sb[1].sb);
1051 	if (ret == 0)
1052 		sb_good[1] = true;
1053 
1054 	/* Use highest generation sb first */
1055 	if (!sb_good[0] && !sb_good[1]) {
1056 		dmz_dev_err(zmd->dev, "No valid super block found");
1057 		return -EIO;
1058 	}
1059 
1060 	if (sb_good[0])
1061 		sb_gen[0] = le64_to_cpu(zmd->sb[0].sb->gen);
1062 	else
1063 		ret = dmz_recover_mblocks(zmd, 0);
1064 
1065 	if (sb_good[1])
1066 		sb_gen[1] = le64_to_cpu(zmd->sb[1].sb->gen);
1067 	else
1068 		ret = dmz_recover_mblocks(zmd, 1);
1069 
1070 	if (ret) {
1071 		dmz_dev_err(zmd->dev, "Recovery failed");
1072 		return -EIO;
1073 	}
1074 
1075 	if (sb_gen[0] >= sb_gen[1]) {
1076 		zmd->sb_gen = sb_gen[0];
1077 		zmd->mblk_primary = 0;
1078 	} else {
1079 		zmd->sb_gen = sb_gen[1];
1080 		zmd->mblk_primary = 1;
1081 	}
1082 
1083 	dmz_dev_debug(zmd->dev, "Using super block %u (gen %llu)",
1084 		      zmd->mblk_primary, zmd->sb_gen);
1085 
1086 	return 0;
1087 }
1088 
1089 /*
1090  * Initialize a zone descriptor.
1091  */
1092 static int dmz_init_zone(struct blk_zone *blkz, unsigned int idx, void *data)
1093 {
1094 	struct dmz_metadata *zmd = data;
1095 	struct dm_zone *zone = &zmd->zones[idx];
1096 	struct dmz_dev *dev = zmd->dev;
1097 
1098 	/* Ignore the eventual last runt (smaller) zone */
1099 	if (blkz->len != dev->zone_nr_sectors) {
1100 		if (blkz->start + blkz->len == dev->capacity)
1101 			return 0;
1102 		return -ENXIO;
1103 	}
1104 
1105 	INIT_LIST_HEAD(&zone->link);
1106 	atomic_set(&zone->refcount, 0);
1107 	zone->chunk = DMZ_MAP_UNMAPPED;
1108 
1109 	switch (blkz->type) {
1110 	case BLK_ZONE_TYPE_CONVENTIONAL:
1111 		set_bit(DMZ_RND, &zone->flags);
1112 		zmd->nr_rnd_zones++;
1113 		break;
1114 	case BLK_ZONE_TYPE_SEQWRITE_REQ:
1115 	case BLK_ZONE_TYPE_SEQWRITE_PREF:
1116 		set_bit(DMZ_SEQ, &zone->flags);
1117 		break;
1118 	default:
1119 		return -ENXIO;
1120 	}
1121 
1122 	if (dmz_is_rnd(zone))
1123 		zone->wp_block = 0;
1124 	else
1125 		zone->wp_block = dmz_sect2blk(blkz->wp - blkz->start);
1126 
1127 	if (blkz->cond == BLK_ZONE_COND_OFFLINE)
1128 		set_bit(DMZ_OFFLINE, &zone->flags);
1129 	else if (blkz->cond == BLK_ZONE_COND_READONLY)
1130 		set_bit(DMZ_READ_ONLY, &zone->flags);
1131 	else {
1132 		zmd->nr_useable_zones++;
1133 		if (dmz_is_rnd(zone)) {
1134 			zmd->nr_rnd_zones++;
1135 			if (!zmd->sb_zone) {
1136 				/* Super block zone */
1137 				zmd->sb_zone = zone;
1138 			}
1139 		}
1140 	}
1141 
1142 	return 0;
1143 }
1144 
1145 /*
1146  * Free zones descriptors.
1147  */
1148 static void dmz_drop_zones(struct dmz_metadata *zmd)
1149 {
1150 	kfree(zmd->zones);
1151 	zmd->zones = NULL;
1152 }
1153 
1154 /*
1155  * Allocate and initialize zone descriptors using the zone
1156  * information from disk.
1157  */
1158 static int dmz_init_zones(struct dmz_metadata *zmd)
1159 {
1160 	struct dmz_dev *dev = zmd->dev;
1161 	int ret;
1162 
1163 	/* Init */
1164 	zmd->zone_bitmap_size = dev->zone_nr_blocks >> 3;
1165 	zmd->zone_nr_bitmap_blocks =
1166 		max_t(sector_t, 1, zmd->zone_bitmap_size >> DMZ_BLOCK_SHIFT);
1167 	zmd->zone_bits_per_mblk = min_t(sector_t, dev->zone_nr_blocks,
1168 					DMZ_BLOCK_SIZE_BITS);
1169 
1170 	/* Allocate zone array */
1171 	zmd->zones = kcalloc(dev->nr_zones, sizeof(struct dm_zone), GFP_KERNEL);
1172 	if (!zmd->zones)
1173 		return -ENOMEM;
1174 
1175 	dmz_dev_info(dev, "Using %zu B for zone information",
1176 		     sizeof(struct dm_zone) * dev->nr_zones);
1177 
1178 	/*
1179 	 * Get zone information and initialize zone descriptors.  At the same
1180 	 * time, determine where the super block should be: first block of the
1181 	 * first randomly writable zone.
1182 	 */
1183 	ret = blkdev_report_zones(dev->bdev, 0, BLK_ALL_ZONES, dmz_init_zone,
1184 				  zmd);
1185 	if (ret < 0) {
1186 		dmz_drop_zones(zmd);
1187 		return ret;
1188 	}
1189 
1190 	return 0;
1191 }
1192 
1193 static int dmz_update_zone_cb(struct blk_zone *blkz, unsigned int idx,
1194 			      void *data)
1195 {
1196 	struct dm_zone *zone = data;
1197 
1198 	clear_bit(DMZ_OFFLINE, &zone->flags);
1199 	clear_bit(DMZ_READ_ONLY, &zone->flags);
1200 	if (blkz->cond == BLK_ZONE_COND_OFFLINE)
1201 		set_bit(DMZ_OFFLINE, &zone->flags);
1202 	else if (blkz->cond == BLK_ZONE_COND_READONLY)
1203 		set_bit(DMZ_READ_ONLY, &zone->flags);
1204 
1205 	if (dmz_is_seq(zone))
1206 		zone->wp_block = dmz_sect2blk(blkz->wp - blkz->start);
1207 	else
1208 		zone->wp_block = 0;
1209 	return 0;
1210 }
1211 
1212 /*
1213  * Update a zone information.
1214  */
1215 static int dmz_update_zone(struct dmz_metadata *zmd, struct dm_zone *zone)
1216 {
1217 	unsigned int noio_flag;
1218 	int ret;
1219 
1220 	/*
1221 	 * Get zone information from disk. Since blkdev_report_zones() uses
1222 	 * GFP_KERNEL by default for memory allocations, set the per-task
1223 	 * PF_MEMALLOC_NOIO flag so that all allocations are done as if
1224 	 * GFP_NOIO was specified.
1225 	 */
1226 	noio_flag = memalloc_noio_save();
1227 	ret = blkdev_report_zones(zmd->dev->bdev, dmz_start_sect(zmd, zone), 1,
1228 				  dmz_update_zone_cb, zone);
1229 	memalloc_noio_restore(noio_flag);
1230 
1231 	if (ret == 0)
1232 		ret = -EIO;
1233 	if (ret < 0) {
1234 		dmz_dev_err(zmd->dev, "Get zone %u report failed",
1235 			    dmz_id(zmd, zone));
1236 		dmz_check_bdev(zmd->dev);
1237 		return ret;
1238 	}
1239 
1240 	return 0;
1241 }
1242 
1243 /*
1244  * Check a zone write pointer position when the zone is marked
1245  * with the sequential write error flag.
1246  */
1247 static int dmz_handle_seq_write_err(struct dmz_metadata *zmd,
1248 				    struct dm_zone *zone)
1249 {
1250 	unsigned int wp = 0;
1251 	int ret;
1252 
1253 	wp = zone->wp_block;
1254 	ret = dmz_update_zone(zmd, zone);
1255 	if (ret)
1256 		return ret;
1257 
1258 	dmz_dev_warn(zmd->dev, "Processing zone %u write error (zone wp %u/%u)",
1259 		     dmz_id(zmd, zone), zone->wp_block, wp);
1260 
1261 	if (zone->wp_block < wp) {
1262 		dmz_invalidate_blocks(zmd, zone, zone->wp_block,
1263 				      wp - zone->wp_block);
1264 	}
1265 
1266 	return 0;
1267 }
1268 
1269 static struct dm_zone *dmz_get(struct dmz_metadata *zmd, unsigned int zone_id)
1270 {
1271 	return &zmd->zones[zone_id];
1272 }
1273 
1274 /*
1275  * Reset a zone write pointer.
1276  */
1277 static int dmz_reset_zone(struct dmz_metadata *zmd, struct dm_zone *zone)
1278 {
1279 	int ret;
1280 
1281 	/*
1282 	 * Ignore offline zones, read only zones,
1283 	 * and conventional zones.
1284 	 */
1285 	if (dmz_is_offline(zone) ||
1286 	    dmz_is_readonly(zone) ||
1287 	    dmz_is_rnd(zone))
1288 		return 0;
1289 
1290 	if (!dmz_is_empty(zone) || dmz_seq_write_err(zone)) {
1291 		struct dmz_dev *dev = zmd->dev;
1292 
1293 		ret = blkdev_zone_mgmt(dev->bdev, REQ_OP_ZONE_RESET,
1294 				       dmz_start_sect(zmd, zone),
1295 				       dev->zone_nr_sectors, GFP_NOIO);
1296 		if (ret) {
1297 			dmz_dev_err(dev, "Reset zone %u failed %d",
1298 				    dmz_id(zmd, zone), ret);
1299 			return ret;
1300 		}
1301 	}
1302 
1303 	/* Clear write error bit and rewind write pointer position */
1304 	clear_bit(DMZ_SEQ_WRITE_ERR, &zone->flags);
1305 	zone->wp_block = 0;
1306 
1307 	return 0;
1308 }
1309 
1310 static void dmz_get_zone_weight(struct dmz_metadata *zmd, struct dm_zone *zone);
1311 
1312 /*
1313  * Initialize chunk mapping.
1314  */
1315 static int dmz_load_mapping(struct dmz_metadata *zmd)
1316 {
1317 	struct dmz_dev *dev = zmd->dev;
1318 	struct dm_zone *dzone, *bzone;
1319 	struct dmz_mblock *dmap_mblk = NULL;
1320 	struct dmz_map *dmap;
1321 	unsigned int i = 0, e = 0, chunk = 0;
1322 	unsigned int dzone_id;
1323 	unsigned int bzone_id;
1324 
1325 	/* Metadata block array for the chunk mapping table */
1326 	zmd->map_mblk = kcalloc(zmd->nr_map_blocks,
1327 				sizeof(struct dmz_mblk *), GFP_KERNEL);
1328 	if (!zmd->map_mblk)
1329 		return -ENOMEM;
1330 
1331 	/* Get chunk mapping table blocks and initialize zone mapping */
1332 	while (chunk < zmd->nr_chunks) {
1333 		if (!dmap_mblk) {
1334 			/* Get mapping block */
1335 			dmap_mblk = dmz_get_mblock(zmd, i + 1);
1336 			if (IS_ERR(dmap_mblk))
1337 				return PTR_ERR(dmap_mblk);
1338 			zmd->map_mblk[i] = dmap_mblk;
1339 			dmap = (struct dmz_map *) dmap_mblk->data;
1340 			i++;
1341 			e = 0;
1342 		}
1343 
1344 		/* Check data zone */
1345 		dzone_id = le32_to_cpu(dmap[e].dzone_id);
1346 		if (dzone_id == DMZ_MAP_UNMAPPED)
1347 			goto next;
1348 
1349 		if (dzone_id >= dev->nr_zones) {
1350 			dmz_dev_err(dev, "Chunk %u mapping: invalid data zone ID %u",
1351 				    chunk, dzone_id);
1352 			return -EIO;
1353 		}
1354 
1355 		dzone = dmz_get(zmd, dzone_id);
1356 		set_bit(DMZ_DATA, &dzone->flags);
1357 		dzone->chunk = chunk;
1358 		dmz_get_zone_weight(zmd, dzone);
1359 
1360 		if (dmz_is_rnd(dzone))
1361 			list_add_tail(&dzone->link, &zmd->map_rnd_list);
1362 		else
1363 			list_add_tail(&dzone->link, &zmd->map_seq_list);
1364 
1365 		/* Check buffer zone */
1366 		bzone_id = le32_to_cpu(dmap[e].bzone_id);
1367 		if (bzone_id == DMZ_MAP_UNMAPPED)
1368 			goto next;
1369 
1370 		if (bzone_id >= dev->nr_zones) {
1371 			dmz_dev_err(dev, "Chunk %u mapping: invalid buffer zone ID %u",
1372 				    chunk, bzone_id);
1373 			return -EIO;
1374 		}
1375 
1376 		bzone = dmz_get(zmd, bzone_id);
1377 		if (!dmz_is_rnd(bzone)) {
1378 			dmz_dev_err(dev, "Chunk %u mapping: invalid buffer zone %u",
1379 				    chunk, bzone_id);
1380 			return -EIO;
1381 		}
1382 
1383 		set_bit(DMZ_DATA, &bzone->flags);
1384 		set_bit(DMZ_BUF, &bzone->flags);
1385 		bzone->chunk = chunk;
1386 		bzone->bzone = dzone;
1387 		dzone->bzone = bzone;
1388 		dmz_get_zone_weight(zmd, bzone);
1389 		list_add_tail(&bzone->link, &zmd->map_rnd_list);
1390 next:
1391 		chunk++;
1392 		e++;
1393 		if (e >= DMZ_MAP_ENTRIES)
1394 			dmap_mblk = NULL;
1395 	}
1396 
1397 	/*
1398 	 * At this point, only meta zones and mapped data zones were
1399 	 * fully initialized. All remaining zones are unmapped data
1400 	 * zones. Finish initializing those here.
1401 	 */
1402 	for (i = 0; i < dev->nr_zones; i++) {
1403 		dzone = dmz_get(zmd, i);
1404 		if (dmz_is_meta(dzone))
1405 			continue;
1406 
1407 		if (dmz_is_rnd(dzone))
1408 			zmd->nr_rnd++;
1409 		else
1410 			zmd->nr_seq++;
1411 
1412 		if (dmz_is_data(dzone)) {
1413 			/* Already initialized */
1414 			continue;
1415 		}
1416 
1417 		/* Unmapped data zone */
1418 		set_bit(DMZ_DATA, &dzone->flags);
1419 		dzone->chunk = DMZ_MAP_UNMAPPED;
1420 		if (dmz_is_rnd(dzone)) {
1421 			list_add_tail(&dzone->link, &zmd->unmap_rnd_list);
1422 			atomic_inc(&zmd->unmap_nr_rnd);
1423 		} else if (atomic_read(&zmd->nr_reserved_seq_zones) < zmd->nr_reserved_seq) {
1424 			list_add_tail(&dzone->link, &zmd->reserved_seq_zones_list);
1425 			atomic_inc(&zmd->nr_reserved_seq_zones);
1426 			zmd->nr_seq--;
1427 		} else {
1428 			list_add_tail(&dzone->link, &zmd->unmap_seq_list);
1429 			atomic_inc(&zmd->unmap_nr_seq);
1430 		}
1431 	}
1432 
1433 	return 0;
1434 }
1435 
1436 /*
1437  * Set a data chunk mapping.
1438  */
1439 static void dmz_set_chunk_mapping(struct dmz_metadata *zmd, unsigned int chunk,
1440 				  unsigned int dzone_id, unsigned int bzone_id)
1441 {
1442 	struct dmz_mblock *dmap_mblk = zmd->map_mblk[chunk >> DMZ_MAP_ENTRIES_SHIFT];
1443 	struct dmz_map *dmap = (struct dmz_map *) dmap_mblk->data;
1444 	int map_idx = chunk & DMZ_MAP_ENTRIES_MASK;
1445 
1446 	dmap[map_idx].dzone_id = cpu_to_le32(dzone_id);
1447 	dmap[map_idx].bzone_id = cpu_to_le32(bzone_id);
1448 	dmz_dirty_mblock(zmd, dmap_mblk);
1449 }
1450 
1451 /*
1452  * The list of mapped zones is maintained in LRU order.
1453  * This rotates a zone at the end of its map list.
1454  */
1455 static void __dmz_lru_zone(struct dmz_metadata *zmd, struct dm_zone *zone)
1456 {
1457 	if (list_empty(&zone->link))
1458 		return;
1459 
1460 	list_del_init(&zone->link);
1461 	if (dmz_is_seq(zone)) {
1462 		/* LRU rotate sequential zone */
1463 		list_add_tail(&zone->link, &zmd->map_seq_list);
1464 	} else {
1465 		/* LRU rotate random zone */
1466 		list_add_tail(&zone->link, &zmd->map_rnd_list);
1467 	}
1468 }
1469 
1470 /*
1471  * The list of mapped random zones is maintained
1472  * in LRU order. This rotates a zone at the end of the list.
1473  */
1474 static void dmz_lru_zone(struct dmz_metadata *zmd, struct dm_zone *zone)
1475 {
1476 	__dmz_lru_zone(zmd, zone);
1477 	if (zone->bzone)
1478 		__dmz_lru_zone(zmd, zone->bzone);
1479 }
1480 
1481 /*
1482  * Wait for any zone to be freed.
1483  */
1484 static void dmz_wait_for_free_zones(struct dmz_metadata *zmd)
1485 {
1486 	DEFINE_WAIT(wait);
1487 
1488 	prepare_to_wait(&zmd->free_wq, &wait, TASK_UNINTERRUPTIBLE);
1489 	dmz_unlock_map(zmd);
1490 	dmz_unlock_metadata(zmd);
1491 
1492 	io_schedule_timeout(HZ);
1493 
1494 	dmz_lock_metadata(zmd);
1495 	dmz_lock_map(zmd);
1496 	finish_wait(&zmd->free_wq, &wait);
1497 }
1498 
1499 /*
1500  * Lock a zone for reclaim (set the zone RECLAIM bit).
1501  * Returns false if the zone cannot be locked or if it is already locked
1502  * and 1 otherwise.
1503  */
1504 int dmz_lock_zone_reclaim(struct dm_zone *zone)
1505 {
1506 	/* Active zones cannot be reclaimed */
1507 	if (dmz_is_active(zone))
1508 		return 0;
1509 
1510 	return !test_and_set_bit(DMZ_RECLAIM, &zone->flags);
1511 }
1512 
1513 /*
1514  * Clear a zone reclaim flag.
1515  */
1516 void dmz_unlock_zone_reclaim(struct dm_zone *zone)
1517 {
1518 	WARN_ON(dmz_is_active(zone));
1519 	WARN_ON(!dmz_in_reclaim(zone));
1520 
1521 	clear_bit_unlock(DMZ_RECLAIM, &zone->flags);
1522 	smp_mb__after_atomic();
1523 	wake_up_bit(&zone->flags, DMZ_RECLAIM);
1524 }
1525 
1526 /*
1527  * Wait for a zone reclaim to complete.
1528  */
1529 static void dmz_wait_for_reclaim(struct dmz_metadata *zmd, struct dm_zone *zone)
1530 {
1531 	dmz_unlock_map(zmd);
1532 	dmz_unlock_metadata(zmd);
1533 	wait_on_bit_timeout(&zone->flags, DMZ_RECLAIM, TASK_UNINTERRUPTIBLE, HZ);
1534 	dmz_lock_metadata(zmd);
1535 	dmz_lock_map(zmd);
1536 }
1537 
1538 /*
1539  * Select a random write zone for reclaim.
1540  */
1541 static struct dm_zone *dmz_get_rnd_zone_for_reclaim(struct dmz_metadata *zmd)
1542 {
1543 	struct dm_zone *dzone = NULL;
1544 	struct dm_zone *zone;
1545 
1546 	if (list_empty(&zmd->map_rnd_list))
1547 		return ERR_PTR(-EBUSY);
1548 
1549 	list_for_each_entry(zone, &zmd->map_rnd_list, link) {
1550 		if (dmz_is_buf(zone))
1551 			dzone = zone->bzone;
1552 		else
1553 			dzone = zone;
1554 		if (dmz_lock_zone_reclaim(dzone))
1555 			return dzone;
1556 	}
1557 
1558 	return ERR_PTR(-EBUSY);
1559 }
1560 
1561 /*
1562  * Select a buffered sequential zone for reclaim.
1563  */
1564 static struct dm_zone *dmz_get_seq_zone_for_reclaim(struct dmz_metadata *zmd)
1565 {
1566 	struct dm_zone *zone;
1567 
1568 	if (list_empty(&zmd->map_seq_list))
1569 		return ERR_PTR(-EBUSY);
1570 
1571 	list_for_each_entry(zone, &zmd->map_seq_list, link) {
1572 		if (!zone->bzone)
1573 			continue;
1574 		if (dmz_lock_zone_reclaim(zone))
1575 			return zone;
1576 	}
1577 
1578 	return ERR_PTR(-EBUSY);
1579 }
1580 
1581 /*
1582  * Select a zone for reclaim.
1583  */
1584 struct dm_zone *dmz_get_zone_for_reclaim(struct dmz_metadata *zmd)
1585 {
1586 	struct dm_zone *zone;
1587 
1588 	/*
1589 	 * Search for a zone candidate to reclaim: 2 cases are possible.
1590 	 * (1) There is no free sequential zones. Then a random data zone
1591 	 *     cannot be reclaimed. So choose a sequential zone to reclaim so
1592 	 *     that afterward a random zone can be reclaimed.
1593 	 * (2) At least one free sequential zone is available, then choose
1594 	 *     the oldest random zone (data or buffer) that can be locked.
1595 	 */
1596 	dmz_lock_map(zmd);
1597 	if (list_empty(&zmd->reserved_seq_zones_list))
1598 		zone = dmz_get_seq_zone_for_reclaim(zmd);
1599 	else
1600 		zone = dmz_get_rnd_zone_for_reclaim(zmd);
1601 	dmz_unlock_map(zmd);
1602 
1603 	return zone;
1604 }
1605 
1606 /*
1607  * Get the zone mapping a chunk, if the chunk is mapped already.
1608  * If no mapping exist and the operation is WRITE, a zone is
1609  * allocated and used to map the chunk.
1610  * The zone returned will be set to the active state.
1611  */
1612 struct dm_zone *dmz_get_chunk_mapping(struct dmz_metadata *zmd, unsigned int chunk, int op)
1613 {
1614 	struct dmz_mblock *dmap_mblk = zmd->map_mblk[chunk >> DMZ_MAP_ENTRIES_SHIFT];
1615 	struct dmz_map *dmap = (struct dmz_map *) dmap_mblk->data;
1616 	int dmap_idx = chunk & DMZ_MAP_ENTRIES_MASK;
1617 	unsigned int dzone_id;
1618 	struct dm_zone *dzone = NULL;
1619 	int ret = 0;
1620 
1621 	dmz_lock_map(zmd);
1622 again:
1623 	/* Get the chunk mapping */
1624 	dzone_id = le32_to_cpu(dmap[dmap_idx].dzone_id);
1625 	if (dzone_id == DMZ_MAP_UNMAPPED) {
1626 		/*
1627 		 * Read or discard in unmapped chunks are fine. But for
1628 		 * writes, we need a mapping, so get one.
1629 		 */
1630 		if (op != REQ_OP_WRITE)
1631 			goto out;
1632 
1633 		/* Allocate a random zone */
1634 		dzone = dmz_alloc_zone(zmd, DMZ_ALLOC_RND);
1635 		if (!dzone) {
1636 			if (dmz_bdev_is_dying(zmd->dev)) {
1637 				dzone = ERR_PTR(-EIO);
1638 				goto out;
1639 			}
1640 			dmz_wait_for_free_zones(zmd);
1641 			goto again;
1642 		}
1643 
1644 		dmz_map_zone(zmd, dzone, chunk);
1645 
1646 	} else {
1647 		/* The chunk is already mapped: get the mapping zone */
1648 		dzone = dmz_get(zmd, dzone_id);
1649 		if (dzone->chunk != chunk) {
1650 			dzone = ERR_PTR(-EIO);
1651 			goto out;
1652 		}
1653 
1654 		/* Repair write pointer if the sequential dzone has error */
1655 		if (dmz_seq_write_err(dzone)) {
1656 			ret = dmz_handle_seq_write_err(zmd, dzone);
1657 			if (ret) {
1658 				dzone = ERR_PTR(-EIO);
1659 				goto out;
1660 			}
1661 			clear_bit(DMZ_SEQ_WRITE_ERR, &dzone->flags);
1662 		}
1663 	}
1664 
1665 	/*
1666 	 * If the zone is being reclaimed, the chunk mapping may change
1667 	 * to a different zone. So wait for reclaim and retry. Otherwise,
1668 	 * activate the zone (this will prevent reclaim from touching it).
1669 	 */
1670 	if (dmz_in_reclaim(dzone)) {
1671 		dmz_wait_for_reclaim(zmd, dzone);
1672 		goto again;
1673 	}
1674 	dmz_activate_zone(dzone);
1675 	dmz_lru_zone(zmd, dzone);
1676 out:
1677 	dmz_unlock_map(zmd);
1678 
1679 	return dzone;
1680 }
1681 
1682 /*
1683  * Write and discard change the block validity of data zones and their buffer
1684  * zones. Check here that valid blocks are still present. If all blocks are
1685  * invalid, the zones can be unmapped on the fly without waiting for reclaim
1686  * to do it.
1687  */
1688 void dmz_put_chunk_mapping(struct dmz_metadata *zmd, struct dm_zone *dzone)
1689 {
1690 	struct dm_zone *bzone;
1691 
1692 	dmz_lock_map(zmd);
1693 
1694 	bzone = dzone->bzone;
1695 	if (bzone) {
1696 		if (dmz_weight(bzone))
1697 			dmz_lru_zone(zmd, bzone);
1698 		else {
1699 			/* Empty buffer zone: reclaim it */
1700 			dmz_unmap_zone(zmd, bzone);
1701 			dmz_free_zone(zmd, bzone);
1702 			bzone = NULL;
1703 		}
1704 	}
1705 
1706 	/* Deactivate the data zone */
1707 	dmz_deactivate_zone(dzone);
1708 	if (dmz_is_active(dzone) || bzone || dmz_weight(dzone))
1709 		dmz_lru_zone(zmd, dzone);
1710 	else {
1711 		/* Unbuffered inactive empty data zone: reclaim it */
1712 		dmz_unmap_zone(zmd, dzone);
1713 		dmz_free_zone(zmd, dzone);
1714 	}
1715 
1716 	dmz_unlock_map(zmd);
1717 }
1718 
1719 /*
1720  * Allocate and map a random zone to buffer a chunk
1721  * already mapped to a sequential zone.
1722  */
1723 struct dm_zone *dmz_get_chunk_buffer(struct dmz_metadata *zmd,
1724 				     struct dm_zone *dzone)
1725 {
1726 	struct dm_zone *bzone;
1727 
1728 	dmz_lock_map(zmd);
1729 again:
1730 	bzone = dzone->bzone;
1731 	if (bzone)
1732 		goto out;
1733 
1734 	/* Allocate a random zone */
1735 	bzone = dmz_alloc_zone(zmd, DMZ_ALLOC_RND);
1736 	if (!bzone) {
1737 		if (dmz_bdev_is_dying(zmd->dev)) {
1738 			bzone = ERR_PTR(-EIO);
1739 			goto out;
1740 		}
1741 		dmz_wait_for_free_zones(zmd);
1742 		goto again;
1743 	}
1744 
1745 	/* Update the chunk mapping */
1746 	dmz_set_chunk_mapping(zmd, dzone->chunk, dmz_id(zmd, dzone),
1747 			      dmz_id(zmd, bzone));
1748 
1749 	set_bit(DMZ_BUF, &bzone->flags);
1750 	bzone->chunk = dzone->chunk;
1751 	bzone->bzone = dzone;
1752 	dzone->bzone = bzone;
1753 	list_add_tail(&bzone->link, &zmd->map_rnd_list);
1754 out:
1755 	dmz_unlock_map(zmd);
1756 
1757 	return bzone;
1758 }
1759 
1760 /*
1761  * Get an unmapped (free) zone.
1762  * This must be called with the mapping lock held.
1763  */
1764 struct dm_zone *dmz_alloc_zone(struct dmz_metadata *zmd, unsigned long flags)
1765 {
1766 	struct list_head *list;
1767 	struct dm_zone *zone;
1768 
1769 	if (flags & DMZ_ALLOC_RND)
1770 		list = &zmd->unmap_rnd_list;
1771 	else
1772 		list = &zmd->unmap_seq_list;
1773 again:
1774 	if (list_empty(list)) {
1775 		/*
1776 		 * No free zone: if this is for reclaim, allow using the
1777 		 * reserved sequential zones.
1778 		 */
1779 		if (!(flags & DMZ_ALLOC_RECLAIM) ||
1780 		    list_empty(&zmd->reserved_seq_zones_list))
1781 			return NULL;
1782 
1783 		zone = list_first_entry(&zmd->reserved_seq_zones_list,
1784 					struct dm_zone, link);
1785 		list_del_init(&zone->link);
1786 		atomic_dec(&zmd->nr_reserved_seq_zones);
1787 		return zone;
1788 	}
1789 
1790 	zone = list_first_entry(list, struct dm_zone, link);
1791 	list_del_init(&zone->link);
1792 
1793 	if (dmz_is_rnd(zone))
1794 		atomic_dec(&zmd->unmap_nr_rnd);
1795 	else
1796 		atomic_dec(&zmd->unmap_nr_seq);
1797 
1798 	if (dmz_is_offline(zone)) {
1799 		dmz_dev_warn(zmd->dev, "Zone %u is offline", dmz_id(zmd, zone));
1800 		zone = NULL;
1801 		goto again;
1802 	}
1803 
1804 	return zone;
1805 }
1806 
1807 /*
1808  * Free a zone.
1809  * This must be called with the mapping lock held.
1810  */
1811 void dmz_free_zone(struct dmz_metadata *zmd, struct dm_zone *zone)
1812 {
1813 	/* If this is a sequential zone, reset it */
1814 	if (dmz_is_seq(zone))
1815 		dmz_reset_zone(zmd, zone);
1816 
1817 	/* Return the zone to its type unmap list */
1818 	if (dmz_is_rnd(zone)) {
1819 		list_add_tail(&zone->link, &zmd->unmap_rnd_list);
1820 		atomic_inc(&zmd->unmap_nr_rnd);
1821 	} else if (atomic_read(&zmd->nr_reserved_seq_zones) <
1822 		   zmd->nr_reserved_seq) {
1823 		list_add_tail(&zone->link, &zmd->reserved_seq_zones_list);
1824 		atomic_inc(&zmd->nr_reserved_seq_zones);
1825 	} else {
1826 		list_add_tail(&zone->link, &zmd->unmap_seq_list);
1827 		atomic_inc(&zmd->unmap_nr_seq);
1828 	}
1829 
1830 	wake_up_all(&zmd->free_wq);
1831 }
1832 
1833 /*
1834  * Map a chunk to a zone.
1835  * This must be called with the mapping lock held.
1836  */
1837 void dmz_map_zone(struct dmz_metadata *zmd, struct dm_zone *dzone,
1838 		  unsigned int chunk)
1839 {
1840 	/* Set the chunk mapping */
1841 	dmz_set_chunk_mapping(zmd, chunk, dmz_id(zmd, dzone),
1842 			      DMZ_MAP_UNMAPPED);
1843 	dzone->chunk = chunk;
1844 	if (dmz_is_rnd(dzone))
1845 		list_add_tail(&dzone->link, &zmd->map_rnd_list);
1846 	else
1847 		list_add_tail(&dzone->link, &zmd->map_seq_list);
1848 }
1849 
1850 /*
1851  * Unmap a zone.
1852  * This must be called with the mapping lock held.
1853  */
1854 void dmz_unmap_zone(struct dmz_metadata *zmd, struct dm_zone *zone)
1855 {
1856 	unsigned int chunk = zone->chunk;
1857 	unsigned int dzone_id;
1858 
1859 	if (chunk == DMZ_MAP_UNMAPPED) {
1860 		/* Already unmapped */
1861 		return;
1862 	}
1863 
1864 	if (test_and_clear_bit(DMZ_BUF, &zone->flags)) {
1865 		/*
1866 		 * Unmapping the chunk buffer zone: clear only
1867 		 * the chunk buffer mapping
1868 		 */
1869 		dzone_id = dmz_id(zmd, zone->bzone);
1870 		zone->bzone->bzone = NULL;
1871 		zone->bzone = NULL;
1872 
1873 	} else {
1874 		/*
1875 		 * Unmapping the chunk data zone: the zone must
1876 		 * not be buffered.
1877 		 */
1878 		if (WARN_ON(zone->bzone)) {
1879 			zone->bzone->bzone = NULL;
1880 			zone->bzone = NULL;
1881 		}
1882 		dzone_id = DMZ_MAP_UNMAPPED;
1883 	}
1884 
1885 	dmz_set_chunk_mapping(zmd, chunk, dzone_id, DMZ_MAP_UNMAPPED);
1886 
1887 	zone->chunk = DMZ_MAP_UNMAPPED;
1888 	list_del_init(&zone->link);
1889 }
1890 
1891 /*
1892  * Set @nr_bits bits in @bitmap starting from @bit.
1893  * Return the number of bits changed from 0 to 1.
1894  */
1895 static unsigned int dmz_set_bits(unsigned long *bitmap,
1896 				 unsigned int bit, unsigned int nr_bits)
1897 {
1898 	unsigned long *addr;
1899 	unsigned int end = bit + nr_bits;
1900 	unsigned int n = 0;
1901 
1902 	while (bit < end) {
1903 		if (((bit & (BITS_PER_LONG - 1)) == 0) &&
1904 		    ((end - bit) >= BITS_PER_LONG)) {
1905 			/* Try to set the whole word at once */
1906 			addr = bitmap + BIT_WORD(bit);
1907 			if (*addr == 0) {
1908 				*addr = ULONG_MAX;
1909 				n += BITS_PER_LONG;
1910 				bit += BITS_PER_LONG;
1911 				continue;
1912 			}
1913 		}
1914 
1915 		if (!test_and_set_bit(bit, bitmap))
1916 			n++;
1917 		bit++;
1918 	}
1919 
1920 	return n;
1921 }
1922 
1923 /*
1924  * Get the bitmap block storing the bit for chunk_block in zone.
1925  */
1926 static struct dmz_mblock *dmz_get_bitmap(struct dmz_metadata *zmd,
1927 					 struct dm_zone *zone,
1928 					 sector_t chunk_block)
1929 {
1930 	sector_t bitmap_block = 1 + zmd->nr_map_blocks +
1931 		(sector_t)(dmz_id(zmd, zone) * zmd->zone_nr_bitmap_blocks) +
1932 		(chunk_block >> DMZ_BLOCK_SHIFT_BITS);
1933 
1934 	return dmz_get_mblock(zmd, bitmap_block);
1935 }
1936 
1937 /*
1938  * Copy the valid blocks bitmap of from_zone to the bitmap of to_zone.
1939  */
1940 int dmz_copy_valid_blocks(struct dmz_metadata *zmd, struct dm_zone *from_zone,
1941 			  struct dm_zone *to_zone)
1942 {
1943 	struct dmz_mblock *from_mblk, *to_mblk;
1944 	sector_t chunk_block = 0;
1945 
1946 	/* Get the zones bitmap blocks */
1947 	while (chunk_block < zmd->dev->zone_nr_blocks) {
1948 		from_mblk = dmz_get_bitmap(zmd, from_zone, chunk_block);
1949 		if (IS_ERR(from_mblk))
1950 			return PTR_ERR(from_mblk);
1951 		to_mblk = dmz_get_bitmap(zmd, to_zone, chunk_block);
1952 		if (IS_ERR(to_mblk)) {
1953 			dmz_release_mblock(zmd, from_mblk);
1954 			return PTR_ERR(to_mblk);
1955 		}
1956 
1957 		memcpy(to_mblk->data, from_mblk->data, DMZ_BLOCK_SIZE);
1958 		dmz_dirty_mblock(zmd, to_mblk);
1959 
1960 		dmz_release_mblock(zmd, to_mblk);
1961 		dmz_release_mblock(zmd, from_mblk);
1962 
1963 		chunk_block += zmd->zone_bits_per_mblk;
1964 	}
1965 
1966 	to_zone->weight = from_zone->weight;
1967 
1968 	return 0;
1969 }
1970 
1971 /*
1972  * Merge the valid blocks bitmap of from_zone into the bitmap of to_zone,
1973  * starting from chunk_block.
1974  */
1975 int dmz_merge_valid_blocks(struct dmz_metadata *zmd, struct dm_zone *from_zone,
1976 			   struct dm_zone *to_zone, sector_t chunk_block)
1977 {
1978 	unsigned int nr_blocks;
1979 	int ret;
1980 
1981 	/* Get the zones bitmap blocks */
1982 	while (chunk_block < zmd->dev->zone_nr_blocks) {
1983 		/* Get a valid region from the source zone */
1984 		ret = dmz_first_valid_block(zmd, from_zone, &chunk_block);
1985 		if (ret <= 0)
1986 			return ret;
1987 
1988 		nr_blocks = ret;
1989 		ret = dmz_validate_blocks(zmd, to_zone, chunk_block, nr_blocks);
1990 		if (ret)
1991 			return ret;
1992 
1993 		chunk_block += nr_blocks;
1994 	}
1995 
1996 	return 0;
1997 }
1998 
1999 /*
2000  * Validate all the blocks in the range [block..block+nr_blocks-1].
2001  */
2002 int dmz_validate_blocks(struct dmz_metadata *zmd, struct dm_zone *zone,
2003 			sector_t chunk_block, unsigned int nr_blocks)
2004 {
2005 	unsigned int count, bit, nr_bits;
2006 	unsigned int zone_nr_blocks = zmd->dev->zone_nr_blocks;
2007 	struct dmz_mblock *mblk;
2008 	unsigned int n = 0;
2009 
2010 	dmz_dev_debug(zmd->dev, "=> VALIDATE zone %u, block %llu, %u blocks",
2011 		      dmz_id(zmd, zone), (unsigned long long)chunk_block,
2012 		      nr_blocks);
2013 
2014 	WARN_ON(chunk_block + nr_blocks > zone_nr_blocks);
2015 
2016 	while (nr_blocks) {
2017 		/* Get bitmap block */
2018 		mblk = dmz_get_bitmap(zmd, zone, chunk_block);
2019 		if (IS_ERR(mblk))
2020 			return PTR_ERR(mblk);
2021 
2022 		/* Set bits */
2023 		bit = chunk_block & DMZ_BLOCK_MASK_BITS;
2024 		nr_bits = min(nr_blocks, zmd->zone_bits_per_mblk - bit);
2025 
2026 		count = dmz_set_bits((unsigned long *)mblk->data, bit, nr_bits);
2027 		if (count) {
2028 			dmz_dirty_mblock(zmd, mblk);
2029 			n += count;
2030 		}
2031 		dmz_release_mblock(zmd, mblk);
2032 
2033 		nr_blocks -= nr_bits;
2034 		chunk_block += nr_bits;
2035 	}
2036 
2037 	if (likely(zone->weight + n <= zone_nr_blocks))
2038 		zone->weight += n;
2039 	else {
2040 		dmz_dev_warn(zmd->dev, "Zone %u: weight %u should be <= %u",
2041 			     dmz_id(zmd, zone), zone->weight,
2042 			     zone_nr_blocks - n);
2043 		zone->weight = zone_nr_blocks;
2044 	}
2045 
2046 	return 0;
2047 }
2048 
2049 /*
2050  * Clear nr_bits bits in bitmap starting from bit.
2051  * Return the number of bits cleared.
2052  */
2053 static int dmz_clear_bits(unsigned long *bitmap, int bit, int nr_bits)
2054 {
2055 	unsigned long *addr;
2056 	int end = bit + nr_bits;
2057 	int n = 0;
2058 
2059 	while (bit < end) {
2060 		if (((bit & (BITS_PER_LONG - 1)) == 0) &&
2061 		    ((end - bit) >= BITS_PER_LONG)) {
2062 			/* Try to clear whole word at once */
2063 			addr = bitmap + BIT_WORD(bit);
2064 			if (*addr == ULONG_MAX) {
2065 				*addr = 0;
2066 				n += BITS_PER_LONG;
2067 				bit += BITS_PER_LONG;
2068 				continue;
2069 			}
2070 		}
2071 
2072 		if (test_and_clear_bit(bit, bitmap))
2073 			n++;
2074 		bit++;
2075 	}
2076 
2077 	return n;
2078 }
2079 
2080 /*
2081  * Invalidate all the blocks in the range [block..block+nr_blocks-1].
2082  */
2083 int dmz_invalidate_blocks(struct dmz_metadata *zmd, struct dm_zone *zone,
2084 			  sector_t chunk_block, unsigned int nr_blocks)
2085 {
2086 	unsigned int count, bit, nr_bits;
2087 	struct dmz_mblock *mblk;
2088 	unsigned int n = 0;
2089 
2090 	dmz_dev_debug(zmd->dev, "=> INVALIDATE zone %u, block %llu, %u blocks",
2091 		      dmz_id(zmd, zone), (u64)chunk_block, nr_blocks);
2092 
2093 	WARN_ON(chunk_block + nr_blocks > zmd->dev->zone_nr_blocks);
2094 
2095 	while (nr_blocks) {
2096 		/* Get bitmap block */
2097 		mblk = dmz_get_bitmap(zmd, zone, chunk_block);
2098 		if (IS_ERR(mblk))
2099 			return PTR_ERR(mblk);
2100 
2101 		/* Clear bits */
2102 		bit = chunk_block & DMZ_BLOCK_MASK_BITS;
2103 		nr_bits = min(nr_blocks, zmd->zone_bits_per_mblk - bit);
2104 
2105 		count = dmz_clear_bits((unsigned long *)mblk->data,
2106 				       bit, nr_bits);
2107 		if (count) {
2108 			dmz_dirty_mblock(zmd, mblk);
2109 			n += count;
2110 		}
2111 		dmz_release_mblock(zmd, mblk);
2112 
2113 		nr_blocks -= nr_bits;
2114 		chunk_block += nr_bits;
2115 	}
2116 
2117 	if (zone->weight >= n)
2118 		zone->weight -= n;
2119 	else {
2120 		dmz_dev_warn(zmd->dev, "Zone %u: weight %u should be >= %u",
2121 			     dmz_id(zmd, zone), zone->weight, n);
2122 		zone->weight = 0;
2123 	}
2124 
2125 	return 0;
2126 }
2127 
2128 /*
2129  * Get a block bit value.
2130  */
2131 static int dmz_test_block(struct dmz_metadata *zmd, struct dm_zone *zone,
2132 			  sector_t chunk_block)
2133 {
2134 	struct dmz_mblock *mblk;
2135 	int ret;
2136 
2137 	WARN_ON(chunk_block >= zmd->dev->zone_nr_blocks);
2138 
2139 	/* Get bitmap block */
2140 	mblk = dmz_get_bitmap(zmd, zone, chunk_block);
2141 	if (IS_ERR(mblk))
2142 		return PTR_ERR(mblk);
2143 
2144 	/* Get offset */
2145 	ret = test_bit(chunk_block & DMZ_BLOCK_MASK_BITS,
2146 		       (unsigned long *) mblk->data) != 0;
2147 
2148 	dmz_release_mblock(zmd, mblk);
2149 
2150 	return ret;
2151 }
2152 
2153 /*
2154  * Return the number of blocks from chunk_block to the first block with a bit
2155  * value specified by set. Search at most nr_blocks blocks from chunk_block.
2156  */
2157 static int dmz_to_next_set_block(struct dmz_metadata *zmd, struct dm_zone *zone,
2158 				 sector_t chunk_block, unsigned int nr_blocks,
2159 				 int set)
2160 {
2161 	struct dmz_mblock *mblk;
2162 	unsigned int bit, set_bit, nr_bits;
2163 	unsigned int zone_bits = zmd->zone_bits_per_mblk;
2164 	unsigned long *bitmap;
2165 	int n = 0;
2166 
2167 	WARN_ON(chunk_block + nr_blocks > zmd->dev->zone_nr_blocks);
2168 
2169 	while (nr_blocks) {
2170 		/* Get bitmap block */
2171 		mblk = dmz_get_bitmap(zmd, zone, chunk_block);
2172 		if (IS_ERR(mblk))
2173 			return PTR_ERR(mblk);
2174 
2175 		/* Get offset */
2176 		bitmap = (unsigned long *) mblk->data;
2177 		bit = chunk_block & DMZ_BLOCK_MASK_BITS;
2178 		nr_bits = min(nr_blocks, zone_bits - bit);
2179 		if (set)
2180 			set_bit = find_next_bit(bitmap, zone_bits, bit);
2181 		else
2182 			set_bit = find_next_zero_bit(bitmap, zone_bits, bit);
2183 		dmz_release_mblock(zmd, mblk);
2184 
2185 		n += set_bit - bit;
2186 		if (set_bit < zone_bits)
2187 			break;
2188 
2189 		nr_blocks -= nr_bits;
2190 		chunk_block += nr_bits;
2191 	}
2192 
2193 	return n;
2194 }
2195 
2196 /*
2197  * Test if chunk_block is valid. If it is, the number of consecutive
2198  * valid blocks from chunk_block will be returned.
2199  */
2200 int dmz_block_valid(struct dmz_metadata *zmd, struct dm_zone *zone,
2201 		    sector_t chunk_block)
2202 {
2203 	int valid;
2204 
2205 	valid = dmz_test_block(zmd, zone, chunk_block);
2206 	if (valid <= 0)
2207 		return valid;
2208 
2209 	/* The block is valid: get the number of valid blocks from block */
2210 	return dmz_to_next_set_block(zmd, zone, chunk_block,
2211 				     zmd->dev->zone_nr_blocks - chunk_block, 0);
2212 }
2213 
2214 /*
2215  * Find the first valid block from @chunk_block in @zone.
2216  * If such a block is found, its number is returned using
2217  * @chunk_block and the total number of valid blocks from @chunk_block
2218  * is returned.
2219  */
2220 int dmz_first_valid_block(struct dmz_metadata *zmd, struct dm_zone *zone,
2221 			  sector_t *chunk_block)
2222 {
2223 	sector_t start_block = *chunk_block;
2224 	int ret;
2225 
2226 	ret = dmz_to_next_set_block(zmd, zone, start_block,
2227 				    zmd->dev->zone_nr_blocks - start_block, 1);
2228 	if (ret < 0)
2229 		return ret;
2230 
2231 	start_block += ret;
2232 	*chunk_block = start_block;
2233 
2234 	return dmz_to_next_set_block(zmd, zone, start_block,
2235 				     zmd->dev->zone_nr_blocks - start_block, 0);
2236 }
2237 
2238 /*
2239  * Count the number of bits set starting from bit up to bit + nr_bits - 1.
2240  */
2241 static int dmz_count_bits(void *bitmap, int bit, int nr_bits)
2242 {
2243 	unsigned long *addr;
2244 	int end = bit + nr_bits;
2245 	int n = 0;
2246 
2247 	while (bit < end) {
2248 		if (((bit & (BITS_PER_LONG - 1)) == 0) &&
2249 		    ((end - bit) >= BITS_PER_LONG)) {
2250 			addr = (unsigned long *)bitmap + BIT_WORD(bit);
2251 			if (*addr == ULONG_MAX) {
2252 				n += BITS_PER_LONG;
2253 				bit += BITS_PER_LONG;
2254 				continue;
2255 			}
2256 		}
2257 
2258 		if (test_bit(bit, bitmap))
2259 			n++;
2260 		bit++;
2261 	}
2262 
2263 	return n;
2264 }
2265 
2266 /*
2267  * Get a zone weight.
2268  */
2269 static void dmz_get_zone_weight(struct dmz_metadata *zmd, struct dm_zone *zone)
2270 {
2271 	struct dmz_mblock *mblk;
2272 	sector_t chunk_block = 0;
2273 	unsigned int bit, nr_bits;
2274 	unsigned int nr_blocks = zmd->dev->zone_nr_blocks;
2275 	void *bitmap;
2276 	int n = 0;
2277 
2278 	while (nr_blocks) {
2279 		/* Get bitmap block */
2280 		mblk = dmz_get_bitmap(zmd, zone, chunk_block);
2281 		if (IS_ERR(mblk)) {
2282 			n = 0;
2283 			break;
2284 		}
2285 
2286 		/* Count bits in this block */
2287 		bitmap = mblk->data;
2288 		bit = chunk_block & DMZ_BLOCK_MASK_BITS;
2289 		nr_bits = min(nr_blocks, zmd->zone_bits_per_mblk - bit);
2290 		n += dmz_count_bits(bitmap, bit, nr_bits);
2291 
2292 		dmz_release_mblock(zmd, mblk);
2293 
2294 		nr_blocks -= nr_bits;
2295 		chunk_block += nr_bits;
2296 	}
2297 
2298 	zone->weight = n;
2299 }
2300 
2301 /*
2302  * Cleanup the zoned metadata resources.
2303  */
2304 static void dmz_cleanup_metadata(struct dmz_metadata *zmd)
2305 {
2306 	struct rb_root *root;
2307 	struct dmz_mblock *mblk, *next;
2308 	int i;
2309 
2310 	/* Release zone mapping resources */
2311 	if (zmd->map_mblk) {
2312 		for (i = 0; i < zmd->nr_map_blocks; i++)
2313 			dmz_release_mblock(zmd, zmd->map_mblk[i]);
2314 		kfree(zmd->map_mblk);
2315 		zmd->map_mblk = NULL;
2316 	}
2317 
2318 	/* Release super blocks */
2319 	for (i = 0; i < 2; i++) {
2320 		if (zmd->sb[i].mblk) {
2321 			dmz_free_mblock(zmd, zmd->sb[i].mblk);
2322 			zmd->sb[i].mblk = NULL;
2323 		}
2324 	}
2325 
2326 	/* Free cached blocks */
2327 	while (!list_empty(&zmd->mblk_dirty_list)) {
2328 		mblk = list_first_entry(&zmd->mblk_dirty_list,
2329 					struct dmz_mblock, link);
2330 		dmz_dev_warn(zmd->dev, "mblock %llu still in dirty list (ref %u)",
2331 			     (u64)mblk->no, mblk->ref);
2332 		list_del_init(&mblk->link);
2333 		rb_erase(&mblk->node, &zmd->mblk_rbtree);
2334 		dmz_free_mblock(zmd, mblk);
2335 	}
2336 
2337 	while (!list_empty(&zmd->mblk_lru_list)) {
2338 		mblk = list_first_entry(&zmd->mblk_lru_list,
2339 					struct dmz_mblock, link);
2340 		list_del_init(&mblk->link);
2341 		rb_erase(&mblk->node, &zmd->mblk_rbtree);
2342 		dmz_free_mblock(zmd, mblk);
2343 	}
2344 
2345 	/* Sanity checks: the mblock rbtree should now be empty */
2346 	root = &zmd->mblk_rbtree;
2347 	rbtree_postorder_for_each_entry_safe(mblk, next, root, node) {
2348 		dmz_dev_warn(zmd->dev, "mblock %llu ref %u still in rbtree",
2349 			     (u64)mblk->no, mblk->ref);
2350 		mblk->ref = 0;
2351 		dmz_free_mblock(zmd, mblk);
2352 	}
2353 
2354 	/* Free the zone descriptors */
2355 	dmz_drop_zones(zmd);
2356 
2357 	mutex_destroy(&zmd->mblk_flush_lock);
2358 	mutex_destroy(&zmd->map_lock);
2359 }
2360 
2361 /*
2362  * Initialize the zoned metadata.
2363  */
2364 int dmz_ctr_metadata(struct dmz_dev *dev, struct dmz_metadata **metadata)
2365 {
2366 	struct dmz_metadata *zmd;
2367 	unsigned int i, zid;
2368 	struct dm_zone *zone;
2369 	int ret;
2370 
2371 	zmd = kzalloc(sizeof(struct dmz_metadata), GFP_KERNEL);
2372 	if (!zmd)
2373 		return -ENOMEM;
2374 
2375 	zmd->dev = dev;
2376 	zmd->mblk_rbtree = RB_ROOT;
2377 	init_rwsem(&zmd->mblk_sem);
2378 	mutex_init(&zmd->mblk_flush_lock);
2379 	spin_lock_init(&zmd->mblk_lock);
2380 	INIT_LIST_HEAD(&zmd->mblk_lru_list);
2381 	INIT_LIST_HEAD(&zmd->mblk_dirty_list);
2382 
2383 	mutex_init(&zmd->map_lock);
2384 	atomic_set(&zmd->unmap_nr_rnd, 0);
2385 	INIT_LIST_HEAD(&zmd->unmap_rnd_list);
2386 	INIT_LIST_HEAD(&zmd->map_rnd_list);
2387 
2388 	atomic_set(&zmd->unmap_nr_seq, 0);
2389 	INIT_LIST_HEAD(&zmd->unmap_seq_list);
2390 	INIT_LIST_HEAD(&zmd->map_seq_list);
2391 
2392 	atomic_set(&zmd->nr_reserved_seq_zones, 0);
2393 	INIT_LIST_HEAD(&zmd->reserved_seq_zones_list);
2394 
2395 	init_waitqueue_head(&zmd->free_wq);
2396 
2397 	/* Initialize zone descriptors */
2398 	ret = dmz_init_zones(zmd);
2399 	if (ret)
2400 		goto err;
2401 
2402 	/* Get super block */
2403 	ret = dmz_load_sb(zmd);
2404 	if (ret)
2405 		goto err;
2406 
2407 	/* Set metadata zones starting from sb_zone */
2408 	zid = dmz_id(zmd, zmd->sb_zone);
2409 	for (i = 0; i < zmd->nr_meta_zones << 1; i++) {
2410 		zone = dmz_get(zmd, zid + i);
2411 		if (!dmz_is_rnd(zone))
2412 			goto err;
2413 		set_bit(DMZ_META, &zone->flags);
2414 	}
2415 
2416 	/* Load mapping table */
2417 	ret = dmz_load_mapping(zmd);
2418 	if (ret)
2419 		goto err;
2420 
2421 	/*
2422 	 * Cache size boundaries: allow at least 2 super blocks, the chunk map
2423 	 * blocks and enough blocks to be able to cache the bitmap blocks of
2424 	 * up to 16 zones when idle (min_nr_mblks). Otherwise, if busy, allow
2425 	 * the cache to add 512 more metadata blocks.
2426 	 */
2427 	zmd->min_nr_mblks = 2 + zmd->nr_map_blocks + zmd->zone_nr_bitmap_blocks * 16;
2428 	zmd->max_nr_mblks = zmd->min_nr_mblks + 512;
2429 	zmd->mblk_shrinker.count_objects = dmz_mblock_shrinker_count;
2430 	zmd->mblk_shrinker.scan_objects = dmz_mblock_shrinker_scan;
2431 	zmd->mblk_shrinker.seeks = DEFAULT_SEEKS;
2432 
2433 	/* Metadata cache shrinker */
2434 	ret = register_shrinker(&zmd->mblk_shrinker);
2435 	if (ret) {
2436 		dmz_dev_err(dev, "Register metadata cache shrinker failed");
2437 		goto err;
2438 	}
2439 
2440 	dmz_dev_info(dev, "Host-%s zoned block device",
2441 		     bdev_zoned_model(dev->bdev) == BLK_ZONED_HA ?
2442 		     "aware" : "managed");
2443 	dmz_dev_info(dev, "  %llu 512-byte logical sectors",
2444 		     (u64)dev->capacity);
2445 	dmz_dev_info(dev, "  %u zones of %llu 512-byte logical sectors",
2446 		     dev->nr_zones, (u64)dev->zone_nr_sectors);
2447 	dmz_dev_info(dev, "  %u metadata zones",
2448 		     zmd->nr_meta_zones * 2);
2449 	dmz_dev_info(dev, "  %u data zones for %u chunks",
2450 		     zmd->nr_data_zones, zmd->nr_chunks);
2451 	dmz_dev_info(dev, "    %u random zones (%u unmapped)",
2452 		     zmd->nr_rnd, atomic_read(&zmd->unmap_nr_rnd));
2453 	dmz_dev_info(dev, "    %u sequential zones (%u unmapped)",
2454 		     zmd->nr_seq, atomic_read(&zmd->unmap_nr_seq));
2455 	dmz_dev_info(dev, "  %u reserved sequential data zones",
2456 		     zmd->nr_reserved_seq);
2457 
2458 	dmz_dev_debug(dev, "Format:");
2459 	dmz_dev_debug(dev, "%u metadata blocks per set (%u max cache)",
2460 		      zmd->nr_meta_blocks, zmd->max_nr_mblks);
2461 	dmz_dev_debug(dev, "  %u data zone mapping blocks",
2462 		      zmd->nr_map_blocks);
2463 	dmz_dev_debug(dev, "  %u bitmap blocks",
2464 		      zmd->nr_bitmap_blocks);
2465 
2466 	*metadata = zmd;
2467 
2468 	return 0;
2469 err:
2470 	dmz_cleanup_metadata(zmd);
2471 	kfree(zmd);
2472 	*metadata = NULL;
2473 
2474 	return ret;
2475 }
2476 
2477 /*
2478  * Cleanup the zoned metadata resources.
2479  */
2480 void dmz_dtr_metadata(struct dmz_metadata *zmd)
2481 {
2482 	unregister_shrinker(&zmd->mblk_shrinker);
2483 	dmz_cleanup_metadata(zmd);
2484 	kfree(zmd);
2485 }
2486 
2487 /*
2488  * Check zone information on resume.
2489  */
2490 int dmz_resume_metadata(struct dmz_metadata *zmd)
2491 {
2492 	struct dmz_dev *dev = zmd->dev;
2493 	struct dm_zone *zone;
2494 	sector_t wp_block;
2495 	unsigned int i;
2496 	int ret;
2497 
2498 	/* Check zones */
2499 	for (i = 0; i < dev->nr_zones; i++) {
2500 		zone = dmz_get(zmd, i);
2501 		if (!zone) {
2502 			dmz_dev_err(dev, "Unable to get zone %u", i);
2503 			return -EIO;
2504 		}
2505 
2506 		wp_block = zone->wp_block;
2507 
2508 		ret = dmz_update_zone(zmd, zone);
2509 		if (ret) {
2510 			dmz_dev_err(dev, "Broken zone %u", i);
2511 			return ret;
2512 		}
2513 
2514 		if (dmz_is_offline(zone)) {
2515 			dmz_dev_warn(dev, "Zone %u is offline", i);
2516 			continue;
2517 		}
2518 
2519 		/* Check write pointer */
2520 		if (!dmz_is_seq(zone))
2521 			zone->wp_block = 0;
2522 		else if (zone->wp_block != wp_block) {
2523 			dmz_dev_err(dev, "Zone %u: Invalid wp (%llu / %llu)",
2524 				    i, (u64)zone->wp_block, (u64)wp_block);
2525 			zone->wp_block = wp_block;
2526 			dmz_invalidate_blocks(zmd, zone, zone->wp_block,
2527 					      dev->zone_nr_blocks - zone->wp_block);
2528 		}
2529 	}
2530 
2531 	return 0;
2532 }
2533