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