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