xref: /linux/drivers/block/zloop.c (revision b23545529c21737dd7939e86b6f649f06480796d)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Copyright (c) 2025, Christoph Hellwig.
4  * Copyright (c) 2025, Western Digital Corporation or its affiliates.
5  *
6  * Zoned Loop Device driver - exports a zoned block device using one file per
7  * zone as backing storage.
8  */
9 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
10 
11 #include <linux/module.h>
12 #include <linux/blk-mq.h>
13 #include <linux/blkzoned.h>
14 #include <linux/pagemap.h>
15 #include <linux/miscdevice.h>
16 #include <linux/falloc.h>
17 #include <linux/mutex.h>
18 #include <linux/parser.h>
19 #include <linux/seq_file.h>
20 #include <linux/xattr.h>
21 
22 /*
23  * Options for adding (and removing) a device.
24  */
25 enum {
26 	ZLOOP_OPT_ERR			= 0,
27 	ZLOOP_OPT_ID			= (1 << 0),
28 	ZLOOP_OPT_CAPACITY		= (1 << 1),
29 	ZLOOP_OPT_ZONE_SIZE		= (1 << 2),
30 	ZLOOP_OPT_ZONE_CAPACITY		= (1 << 3),
31 	ZLOOP_OPT_NR_CONV_ZONES		= (1 << 4),
32 	ZLOOP_OPT_BASE_DIR		= (1 << 5),
33 	ZLOOP_OPT_NR_QUEUES		= (1 << 6),
34 	ZLOOP_OPT_QUEUE_DEPTH		= (1 << 7),
35 	ZLOOP_OPT_BUFFERED_IO		= (1 << 8),
36 	ZLOOP_OPT_ZONE_APPEND		= (1 << 9),
37 	ZLOOP_OPT_ORDERED_ZONE_APPEND	= (1 << 10),
38 	ZLOOP_OPT_DISCARD_WRITE_CACHE	= (1 << 11),
39 	ZLOOP_OPT_MAX_OPEN_ZONES	= (1 << 12),
40 };
41 
42 static const match_table_t zloop_opt_tokens = {
43 	{ ZLOOP_OPT_ID,			"id=%d"	},
44 	{ ZLOOP_OPT_CAPACITY,		"capacity_mb=%u"	},
45 	{ ZLOOP_OPT_ZONE_SIZE,		"zone_size_mb=%u"	},
46 	{ ZLOOP_OPT_ZONE_CAPACITY,	"zone_capacity_mb=%u"	},
47 	{ ZLOOP_OPT_NR_CONV_ZONES,	"conv_zones=%u"		},
48 	{ ZLOOP_OPT_BASE_DIR,		"base_dir=%s"		},
49 	{ ZLOOP_OPT_NR_QUEUES,		"nr_queues=%u"		},
50 	{ ZLOOP_OPT_QUEUE_DEPTH,	"queue_depth=%u"	},
51 	{ ZLOOP_OPT_BUFFERED_IO,	"buffered_io"		},
52 	{ ZLOOP_OPT_ZONE_APPEND,	"zone_append=%u"	},
53 	{ ZLOOP_OPT_ORDERED_ZONE_APPEND, "ordered_zone_append"	},
54 	{ ZLOOP_OPT_DISCARD_WRITE_CACHE, "discard_write_cache" },
55 	{ ZLOOP_OPT_MAX_OPEN_ZONES,	"max_open_zones=%u"	},
56 	{ ZLOOP_OPT_ERR,		NULL			}
57 };
58 
59 /* Default values for the "add" operation. */
60 #define ZLOOP_DEF_ID			-1
61 #define ZLOOP_DEF_ZONE_SIZE		((256ULL * SZ_1M) >> SECTOR_SHIFT)
62 #define ZLOOP_DEF_NR_ZONES		64
63 #define ZLOOP_DEF_NR_CONV_ZONES		8
64 #define ZLOOP_DEF_MAX_OPEN_ZONES	0
65 #define ZLOOP_DEF_BASE_DIR		"/var/local/zloop"
66 #define ZLOOP_DEF_NR_QUEUES		1
67 #define ZLOOP_DEF_QUEUE_DEPTH		128
68 #define ZLOOP_DEF_BUFFERED_IO		false
69 #define ZLOOP_DEF_ZONE_APPEND		true
70 #define ZLOOP_DEF_ORDERED_ZONE_APPEND	false
71 
72 /* Arbitrary limit on the zone size (16GB). */
73 #define ZLOOP_MAX_ZONE_SIZE_MB		16384
74 
75 struct zloop_options {
76 	unsigned int		mask;
77 	int			id;
78 	sector_t		capacity;
79 	sector_t		zone_size;
80 	sector_t		zone_capacity;
81 	unsigned int		nr_conv_zones;
82 	unsigned int		max_open_zones;
83 	char			*base_dir;
84 	unsigned int		nr_queues;
85 	unsigned int		queue_depth;
86 	bool			buffered_io;
87 	bool			zone_append;
88 	bool			ordered_zone_append;
89 	bool			discard_write_cache;
90 };
91 
92 /*
93  * Device states.
94  */
95 enum {
96 	Zlo_creating = 0,
97 	Zlo_live,
98 	Zlo_deleting,
99 };
100 
101 enum zloop_zone_flags {
102 	ZLOOP_ZONE_CONV = 0,
103 	ZLOOP_ZONE_SEQ_ERROR,
104 };
105 
106 /*
107  * Zone descriptor.
108  * Locking order: z.lock -> z.wp_lock -> zlo.open_zones_lock
109  */
110 struct zloop_zone {
111 	struct list_head	open_zone_entry;
112 	struct file		*file;
113 
114 	unsigned long		flags;
115 	struct mutex		lock;
116 	spinlock_t		wp_lock;
117 	enum blk_zone_cond	cond;
118 	sector_t		start;
119 	sector_t		wp;
120 
121 	gfp_t			old_gfp_mask;
122 };
123 
124 struct zloop_device {
125 	unsigned int		id;
126 	unsigned int		state;
127 
128 	struct blk_mq_tag_set	tag_set;
129 	struct gendisk		*disk;
130 
131 	struct workqueue_struct *workqueue;
132 	bool			buffered_io;
133 	bool			zone_append;
134 	bool			ordered_zone_append;
135 	bool			discard_write_cache;
136 
137 	const char		*base_dir;
138 	struct file		*data_dir;
139 
140 	unsigned int		zone_shift;
141 	sector_t		zone_size;
142 	sector_t		zone_capacity;
143 	unsigned int		nr_zones;
144 	unsigned int		nr_conv_zones;
145 	unsigned int		max_open_zones;
146 	unsigned int		block_size;
147 	unsigned int		dio_mem_align;
148 
149 	spinlock_t		open_zones_lock;
150 	struct list_head	open_zones_lru_list;
151 	unsigned int		nr_open_zones;
152 
153 	struct zloop_zone	zones[] __counted_by(nr_zones);
154 };
155 
156 struct zloop_cmd {
157 	struct work_struct	work;
158 	atomic_t		ref;
159 	sector_t		sector;
160 	sector_t		nr_sectors;
161 	long			ret;
162 	struct kiocb		iocb;
163 	struct bio_vec		*bvec;
164 };
165 
166 static DEFINE_IDR(zloop_index_idr);
167 static DEFINE_MUTEX(zloop_ctl_mutex);
168 
169 static unsigned int rq_zone_no(struct request *rq)
170 {
171 	struct zloop_device *zlo = rq->q->queuedata;
172 
173 	return blk_rq_pos(rq) >> zlo->zone_shift;
174 }
175 
176 /*
177  * Open an already open zone. This is mostly a no-op, except for the imp open ->
178  * exp open condition change that may happen. We also move a zone at the tail of
179  * the list of open zones so that if we need to
180  * implicitly close one open zone, we can do so in LRU order.
181  */
182 static inline void zloop_lru_rotate_open_zone(struct zloop_device *zlo,
183 					      struct zloop_zone *zone)
184 {
185 	if (zlo->max_open_zones) {
186 		spin_lock(&zlo->open_zones_lock);
187 		list_move_tail(&zone->open_zone_entry,
188 			       &zlo->open_zones_lru_list);
189 		spin_unlock(&zlo->open_zones_lock);
190 	}
191 }
192 
193 static inline void zloop_lru_remove_open_zone(struct zloop_device *zlo,
194 					      struct zloop_zone *zone)
195 {
196 	if (zone->cond == BLK_ZONE_COND_IMP_OPEN ||
197 	    zone->cond == BLK_ZONE_COND_EXP_OPEN) {
198 		spin_lock(&zlo->open_zones_lock);
199 		list_del_init(&zone->open_zone_entry);
200 		zlo->nr_open_zones--;
201 		spin_unlock(&zlo->open_zones_lock);
202 	}
203 }
204 
205 static inline bool zloop_can_open_zone(struct zloop_device *zlo)
206 {
207 	return !zlo->max_open_zones || zlo->nr_open_zones < zlo->max_open_zones;
208 }
209 
210 /*
211  * If we have reached the maximum open zones limit, attempt to close an
212  * implicitly open zone (if we have any) so that we can implicitly open another
213  * zone without exceeding the maximum number of open zones.
214  */
215 static bool zloop_close_imp_open_zone(struct zloop_device *zlo)
216 {
217 	struct zloop_zone *zone;
218 
219 	lockdep_assert_held(&zlo->open_zones_lock);
220 
221 	if (zloop_can_open_zone(zlo))
222 		return true;
223 
224 	list_for_each_entry(zone, &zlo->open_zones_lru_list, open_zone_entry) {
225 		if (zone->cond == BLK_ZONE_COND_IMP_OPEN) {
226 			zone->cond = BLK_ZONE_COND_CLOSED;
227 			list_del_init(&zone->open_zone_entry);
228 			zlo->nr_open_zones--;
229 			return true;
230 		}
231 	}
232 
233 	return false;
234 }
235 
236 static bool zloop_open_closed_or_empty_zone(struct zloop_device *zlo,
237 					    struct zloop_zone *zone,
238 					    bool explicit)
239 {
240 	spin_lock(&zlo->open_zones_lock);
241 
242 	if (explicit) {
243 		/*
244 		 * Explicit open: we cannot allow this if we have reached the
245 		 * maximum open zones limit.
246 		 */
247 		if (!zloop_can_open_zone(zlo))
248 			goto fail;
249 		zone->cond = BLK_ZONE_COND_EXP_OPEN;
250 	} else {
251 		/*
252 		 * Implicit open case: if we have reached the maximum open zones
253 		 * limit, try to close an implicitly open zone first.
254 		 */
255 		if (!zloop_close_imp_open_zone(zlo))
256 			goto fail;
257 		zone->cond = BLK_ZONE_COND_IMP_OPEN;
258 	}
259 
260 	zlo->nr_open_zones++;
261 	list_add_tail(&zone->open_zone_entry,
262 		      &zlo->open_zones_lru_list);
263 
264 	spin_unlock(&zlo->open_zones_lock);
265 
266 	return true;
267 
268 fail:
269 	spin_unlock(&zlo->open_zones_lock);
270 
271 	return false;
272 }
273 
274 static bool zloop_do_open_zone(struct zloop_device *zlo,
275 			       struct zloop_zone *zone, bool explicit)
276 {
277 	switch (zone->cond) {
278 	case BLK_ZONE_COND_IMP_OPEN:
279 	case BLK_ZONE_COND_EXP_OPEN:
280 		if (explicit)
281 			zone->cond = BLK_ZONE_COND_EXP_OPEN;
282 		zloop_lru_rotate_open_zone(zlo, zone);
283 		return true;
284 	case BLK_ZONE_COND_EMPTY:
285 	case BLK_ZONE_COND_CLOSED:
286 		return zloop_open_closed_or_empty_zone(zlo, zone, explicit);
287 	default:
288 		return false;
289 	}
290 }
291 
292 static void zloop_mark_full(struct zloop_device *zlo, struct zloop_zone *zone)
293 {
294 	lockdep_assert_held(&zone->wp_lock);
295 
296 	zloop_lru_remove_open_zone(zlo, zone);
297 	zone->cond = BLK_ZONE_COND_FULL;
298 	zone->wp = ULLONG_MAX;
299 }
300 
301 static void zloop_mark_empty(struct zloop_device *zlo, struct zloop_zone *zone)
302 {
303 	lockdep_assert_held(&zone->wp_lock);
304 
305 	zloop_lru_remove_open_zone(zlo, zone);
306 	zone->cond = BLK_ZONE_COND_EMPTY;
307 	zone->wp = zone->start;
308 }
309 
310 static int zloop_update_seq_zone(struct zloop_device *zlo, unsigned int zone_no)
311 {
312 	struct zloop_zone *zone = &zlo->zones[zone_no];
313 	struct kstat stat;
314 	sector_t file_sectors;
315 	int ret;
316 
317 	lockdep_assert_held(&zone->lock);
318 
319 	ret = vfs_getattr(&zone->file->f_path, &stat, STATX_SIZE, 0);
320 	if (ret < 0) {
321 		pr_err("%pg: Failed to get zone %u file stat (err=%d)\n",
322 		       zlo->disk->part0, zone_no, ret);
323 		set_bit(ZLOOP_ZONE_SEQ_ERROR, &zone->flags);
324 		return ret;
325 	}
326 
327 	file_sectors = stat.size >> SECTOR_SHIFT;
328 	if (file_sectors > zlo->zone_capacity) {
329 		pr_err("%pg: Zone %u file too large (%llu sectors > %llu)\n",
330 		       zlo->disk->part0, zone_no, file_sectors,
331 		       zlo->zone_capacity);
332 		return -EINVAL;
333 	}
334 
335 	if (!IS_ALIGNED(stat.size, zlo->block_size)) {
336 		pr_err("%pg: Zone %u file size (%llu) not aligned to block size %u\n",
337 		       zlo->disk->part0, zone_no, stat.size, zlo->block_size);
338 		return -EINVAL;
339 	}
340 
341 	spin_lock(&zone->wp_lock);
342 	if (!file_sectors) {
343 		zloop_mark_empty(zlo, zone);
344 	} else if (file_sectors == zlo->zone_capacity) {
345 		zloop_mark_full(zlo, zone);
346 	} else {
347 		if (zone->cond != BLK_ZONE_COND_IMP_OPEN &&
348 		    zone->cond != BLK_ZONE_COND_EXP_OPEN)
349 			zone->cond = BLK_ZONE_COND_CLOSED;
350 		zone->wp = zone->start + file_sectors;
351 	}
352 	spin_unlock(&zone->wp_lock);
353 
354 	return 0;
355 }
356 
357 static int zloop_open_zone(struct zloop_device *zlo, unsigned int zone_no)
358 {
359 	struct zloop_zone *zone = &zlo->zones[zone_no];
360 	int ret = 0;
361 
362 	if (test_bit(ZLOOP_ZONE_CONV, &zone->flags))
363 		return -EIO;
364 
365 	mutex_lock(&zone->lock);
366 
367 	if (test_and_clear_bit(ZLOOP_ZONE_SEQ_ERROR, &zone->flags)) {
368 		ret = zloop_update_seq_zone(zlo, zone_no);
369 		if (ret)
370 			goto unlock;
371 	}
372 
373 	if (!zloop_do_open_zone(zlo, zone, true))
374 		ret = -EIO;
375 
376 unlock:
377 	mutex_unlock(&zone->lock);
378 
379 	return ret;
380 }
381 
382 static int zloop_close_zone(struct zloop_device *zlo, unsigned int zone_no)
383 {
384 	struct zloop_zone *zone = &zlo->zones[zone_no];
385 	int ret = 0;
386 
387 	if (test_bit(ZLOOP_ZONE_CONV, &zone->flags))
388 		return -EIO;
389 
390 	mutex_lock(&zone->lock);
391 
392 	if (test_and_clear_bit(ZLOOP_ZONE_SEQ_ERROR, &zone->flags)) {
393 		ret = zloop_update_seq_zone(zlo, zone_no);
394 		if (ret)
395 			goto unlock;
396 	}
397 
398 	switch (zone->cond) {
399 	case BLK_ZONE_COND_CLOSED:
400 		break;
401 	case BLK_ZONE_COND_IMP_OPEN:
402 	case BLK_ZONE_COND_EXP_OPEN:
403 		spin_lock(&zone->wp_lock);
404 		zloop_lru_remove_open_zone(zlo, zone);
405 		if (zone->wp == zone->start)
406 			zone->cond = BLK_ZONE_COND_EMPTY;
407 		else
408 			zone->cond = BLK_ZONE_COND_CLOSED;
409 		spin_unlock(&zone->wp_lock);
410 		break;
411 	case BLK_ZONE_COND_EMPTY:
412 	case BLK_ZONE_COND_FULL:
413 	default:
414 		ret = -EIO;
415 		break;
416 	}
417 
418 unlock:
419 	mutex_unlock(&zone->lock);
420 
421 	return ret;
422 }
423 
424 static int zloop_reset_zone(struct zloop_device *zlo, unsigned int zone_no)
425 {
426 	struct zloop_zone *zone = &zlo->zones[zone_no];
427 	int ret = 0;
428 
429 	if (test_bit(ZLOOP_ZONE_CONV, &zone->flags))
430 		return -EIO;
431 
432 	mutex_lock(&zone->lock);
433 
434 	if (!test_bit(ZLOOP_ZONE_SEQ_ERROR, &zone->flags) &&
435 	    zone->cond == BLK_ZONE_COND_EMPTY)
436 		goto unlock;
437 
438 	if (vfs_truncate(&zone->file->f_path, 0)) {
439 		set_bit(ZLOOP_ZONE_SEQ_ERROR, &zone->flags);
440 		ret = -EIO;
441 		goto unlock;
442 	}
443 
444 	spin_lock(&zone->wp_lock);
445 	zloop_mark_empty(zlo, zone);
446 	clear_bit(ZLOOP_ZONE_SEQ_ERROR, &zone->flags);
447 	spin_unlock(&zone->wp_lock);
448 
449 unlock:
450 	mutex_unlock(&zone->lock);
451 
452 	return ret;
453 }
454 
455 static int zloop_reset_all_zones(struct zloop_device *zlo)
456 {
457 	unsigned int i;
458 	int ret;
459 
460 	for (i = zlo->nr_conv_zones; i < zlo->nr_zones; i++) {
461 		ret = zloop_reset_zone(zlo, i);
462 		if (ret)
463 			return ret;
464 	}
465 
466 	return 0;
467 }
468 
469 static int zloop_finish_zone(struct zloop_device *zlo, unsigned int zone_no)
470 {
471 	struct zloop_zone *zone = &zlo->zones[zone_no];
472 	int ret = 0;
473 
474 	if (test_bit(ZLOOP_ZONE_CONV, &zone->flags))
475 		return -EIO;
476 
477 	mutex_lock(&zone->lock);
478 
479 	if (!test_bit(ZLOOP_ZONE_SEQ_ERROR, &zone->flags) &&
480 	    zone->cond == BLK_ZONE_COND_FULL)
481 		goto unlock;
482 
483 	if (vfs_truncate(&zone->file->f_path,
484 			 zlo->zone_capacity << SECTOR_SHIFT)) {
485 		set_bit(ZLOOP_ZONE_SEQ_ERROR, &zone->flags);
486 		ret = -EIO;
487 		goto unlock;
488 	}
489 
490 	spin_lock(&zone->wp_lock);
491 	zloop_mark_full(zlo, zone);
492 	clear_bit(ZLOOP_ZONE_SEQ_ERROR, &zone->flags);
493 	spin_unlock(&zone->wp_lock);
494 
495  unlock:
496 	mutex_unlock(&zone->lock);
497 
498 	return ret;
499 }
500 
501 static void zloop_put_cmd(struct zloop_cmd *cmd)
502 {
503 	struct request *rq = blk_mq_rq_from_pdu(cmd);
504 
505 	if (!atomic_dec_and_test(&cmd->ref))
506 		return;
507 	kfree(cmd->bvec);
508 	cmd->bvec = NULL;
509 	if (likely(!blk_should_fake_timeout(rq->q)))
510 		blk_mq_complete_request(rq);
511 }
512 
513 static void zloop_rw_complete(struct kiocb *iocb, long ret)
514 {
515 	struct zloop_cmd *cmd = container_of(iocb, struct zloop_cmd, iocb);
516 
517 	cmd->ret = ret;
518 	zloop_put_cmd(cmd);
519 }
520 
521 static int zloop_do_rw(struct zloop_cmd *cmd)
522 {
523 	struct request *rq = blk_mq_rq_from_pdu(cmd);
524 	int rw = req_op(rq) == REQ_OP_READ ? ITER_DEST : ITER_SOURCE;
525 	unsigned int nr_bvec = blk_rq_nr_bvec(rq);
526 	struct zloop_device *zlo = rq->q->queuedata;
527 	struct zloop_zone *zone = &zlo->zones[rq_zone_no(rq)];
528 	struct req_iterator rq_iter;
529 	struct iov_iter iter;
530 
531 	if (rq->bio != rq->biotail) {
532 		struct bio_vec tmp, *bvec;
533 
534 		cmd->bvec = kmalloc_objs(*cmd->bvec, nr_bvec, GFP_NOIO);
535 		if (!cmd->bvec)
536 			return -EIO;
537 
538 		/*
539 		 * The bios of the request may be started from the middle of
540 		 * the 'bvec' because of bio splitting, so we can't directly
541 		 * copy bio->bi_iov_vec to new bvec. The rq_for_each_bvec
542 		 * API will take care of all details for us.
543 		 */
544 		bvec = cmd->bvec;
545 		rq_for_each_bvec(tmp, rq, rq_iter) {
546 			*bvec = tmp;
547 			bvec++;
548 		}
549 		iov_iter_bvec(&iter, rw, cmd->bvec, nr_bvec, blk_rq_bytes(rq));
550 	} else {
551 		/*
552 		 * Same here, this bio may be started from the middle of the
553 		 * 'bvec' because of bio splitting, so offset from the bvec
554 		 * must be passed to iov iterator
555 		 */
556 		iov_iter_bvec(&iter, rw,
557 			__bvec_iter_bvec(rq->bio->bi_io_vec, rq->bio->bi_iter),
558 					nr_bvec, blk_rq_bytes(rq));
559 		iter.iov_offset = rq->bio->bi_iter.bi_offset;
560 	}
561 
562 	cmd->iocb.ki_pos = (cmd->sector - zone->start) << SECTOR_SHIFT;
563 	cmd->iocb.ki_filp = zone->file;
564 	cmd->iocb.ki_complete = zloop_rw_complete;
565 	if (!zlo->buffered_io)
566 		cmd->iocb.ki_flags = IOCB_DIRECT;
567 	cmd->iocb.ki_ioprio = IOPRIO_PRIO_VALUE(IOPRIO_CLASS_NONE, 0);
568 
569 	if (rw == ITER_SOURCE)
570 		return zone->file->f_op->write_iter(&cmd->iocb, &iter);
571 	return zone->file->f_op->read_iter(&cmd->iocb, &iter);
572 }
573 
574 static int zloop_seq_write_prep(struct zloop_cmd *cmd)
575 {
576 	struct request *rq = blk_mq_rq_from_pdu(cmd);
577 	struct zloop_device *zlo = rq->q->queuedata;
578 	unsigned int zone_no = rq_zone_no(rq);
579 	sector_t nr_sectors = blk_rq_sectors(rq);
580 	bool is_append = req_op(rq) == REQ_OP_ZONE_APPEND;
581 	struct zloop_zone *zone = &zlo->zones[zone_no];
582 	sector_t zone_end = zone->start + zlo->zone_capacity;
583 	int ret = 0;
584 
585 	spin_lock(&zone->wp_lock);
586 
587 	/*
588 	 * Zone append operations always go at the current write pointer, but
589 	 * regular write operations must already be aligned to the write pointer
590 	 * when submitted.
591 	 */
592 	if (is_append) {
593 		/*
594 		 * If ordered zone append is in use, we already checked and set
595 		 * the target sector in zloop_queue_rq().
596 		 */
597 		if (!zlo->ordered_zone_append) {
598 			if (zone->cond == BLK_ZONE_COND_FULL ||
599 			    zone->wp + nr_sectors > zone_end) {
600 				ret = -EIO;
601 				goto out_unlock;
602 			}
603 			cmd->sector = zone->wp;
604 		}
605 	} else {
606 		if (cmd->sector != zone->wp) {
607 			if (zone->wp == ULLONG_MAX)
608 				pr_err("%pg: Zone %u: write to %s zone: sect %llu\n",
609 				       zlo->disk->part0, zone_no,
610 				       blk_zone_cond_str(zone->cond),
611 				       cmd->sector);
612 			else
613 				pr_err("%pg: Zone %u: unaligned write: sect %llu, wp %llu\n",
614 				       zlo->disk->part0, zone_no, cmd->sector,
615 				       zone->wp);
616 			ret = -EIO;
617 			goto out_unlock;
618 		}
619 	}
620 
621 	/* Implicitly open the target zone. */
622 	if (!zloop_do_open_zone(zlo, zone, false)) {
623 		ret = -EIO;
624 		goto out_unlock;
625 	}
626 
627 	/*
628 	 * Advance the write pointer, unless ordered zone append is in use. If
629 	 * the write fails, the write pointer position will be corrected when
630 	 * the next I/O starts execution.
631 	 */
632 	if (!is_append || !zlo->ordered_zone_append) {
633 		zone->wp += nr_sectors;
634 		if (zone->wp == zone_end)
635 			zloop_mark_full(zlo, zone);
636 	}
637 out_unlock:
638 	spin_unlock(&zone->wp_lock);
639 	return ret;
640 }
641 
642 static void zloop_rw(struct zloop_cmd *cmd)
643 {
644 	struct request *rq = blk_mq_rq_from_pdu(cmd);
645 	struct zloop_device *zlo = rq->q->queuedata;
646 	unsigned int zone_no = rq_zone_no(rq);
647 	sector_t nr_sectors = blk_rq_sectors(rq);
648 	bool is_append = req_op(rq) == REQ_OP_ZONE_APPEND;
649 	bool is_write = req_op(rq) == REQ_OP_WRITE || is_append;
650 	struct zloop_zone *zone;
651 	int ret = -EIO;
652 
653 	atomic_set(&cmd->ref, 2);
654 	cmd->sector = blk_rq_pos(rq);
655 	cmd->nr_sectors = nr_sectors;
656 	cmd->ret = 0;
657 
658 	if (WARN_ON_ONCE(is_append && !zlo->zone_append))
659 		goto out;
660 
661 	/* We should never get an I/O beyond the device capacity. */
662 	if (WARN_ON_ONCE(zone_no >= zlo->nr_zones))
663 		goto out;
664 
665 	zone = &zlo->zones[zone_no];
666 
667 	/*
668 	 * The block layer should never send requests that are not fully
669 	 * contained within the zone.
670 	 */
671 	if (WARN_ON_ONCE(cmd->sector + nr_sectors >
672 			 zone->start + zlo->zone_size))
673 		goto out;
674 
675 	if (test_and_clear_bit(ZLOOP_ZONE_SEQ_ERROR, &zone->flags)) {
676 		mutex_lock(&zone->lock);
677 		ret = zloop_update_seq_zone(zlo, zone_no);
678 		mutex_unlock(&zone->lock);
679 		if (ret)
680 			goto out;
681 	}
682 
683 	if (!test_bit(ZLOOP_ZONE_CONV, &zone->flags) && is_write) {
684 		mutex_lock(&zone->lock);
685 		ret = zloop_seq_write_prep(cmd);
686 		if (!ret)
687 			ret = zloop_do_rw(cmd);
688 		mutex_unlock(&zone->lock);
689 	} else {
690 		ret = zloop_do_rw(cmd);
691 	}
692 out:
693 	if (ret != -EIOCBQUEUED)
694 		zloop_rw_complete(&cmd->iocb, ret);
695 	zloop_put_cmd(cmd);
696 }
697 
698 static inline bool zloop_zone_is_active(struct zloop_zone *zone)
699 {
700 	switch (zone->cond) {
701 	case BLK_ZONE_COND_EXP_OPEN:
702 	case BLK_ZONE_COND_IMP_OPEN:
703 	case BLK_ZONE_COND_CLOSED:
704 		return true;
705 	default:
706 		return false;
707 	}
708 }
709 
710 static int zloop_record_safe_wps(struct zloop_device *zlo)
711 {
712 	unsigned int i;
713 	int ret;
714 
715 	for (i = 0; i < zlo->nr_zones; i++) {
716 		struct zloop_zone *zone = &zlo->zones[i];
717 		struct file *file = zone->file;
718 
719 		if (!zloop_zone_is_active(zone))
720 			continue;
721 		ret = vfs_setxattr(file_mnt_idmap(file), file_dentry(file),
722 				"user.zloop.wp", &zone->wp, sizeof(zone->wp), 0);
723 		if (ret) {
724 			pr_err("%pg: failed to record write pointer (%d)\n",
725 				zlo->disk->part0, ret);
726 			return ret;
727 		}
728 	}
729 
730 	return 0;
731 }
732 
733 /*
734  * Sync the entire FS containing the zone files instead of walking all files.
735  */
736 static int zloop_flush(struct zloop_device *zlo)
737 {
738 	struct super_block *sb = file_inode(zlo->data_dir)->i_sb;
739 	int ret;
740 
741 	if (zlo->discard_write_cache) {
742 		ret = zloop_record_safe_wps(zlo);
743 		if (ret)
744 			return ret;
745 	}
746 
747 	down_read(&sb->s_umount);
748 	ret = sync_filesystem(sb);
749 	up_read(&sb->s_umount);
750 
751 	return ret;
752 }
753 
754 static void zloop_handle_cmd(struct zloop_cmd *cmd)
755 {
756 	struct request *rq = blk_mq_rq_from_pdu(cmd);
757 	struct zloop_device *zlo = rq->q->queuedata;
758 
759 	/* We can block in this context, so ignore REQ_NOWAIT. */
760 	if (rq->cmd_flags & REQ_NOWAIT)
761 		rq->cmd_flags &= ~REQ_NOWAIT;
762 
763 	switch (req_op(rq)) {
764 	case REQ_OP_READ:
765 	case REQ_OP_WRITE:
766 	case REQ_OP_ZONE_APPEND:
767 		/*
768 		 * zloop_rw() always executes asynchronously or completes
769 		 * directly.
770 		 */
771 		zloop_rw(cmd);
772 		return;
773 	case REQ_OP_FLUSH:
774 		cmd->ret = zloop_flush(zlo);
775 		break;
776 	case REQ_OP_ZONE_RESET:
777 		cmd->ret = zloop_reset_zone(zlo, rq_zone_no(rq));
778 		break;
779 	case REQ_OP_ZONE_RESET_ALL:
780 		cmd->ret = zloop_reset_all_zones(zlo);
781 		break;
782 	case REQ_OP_ZONE_FINISH:
783 		cmd->ret = zloop_finish_zone(zlo, rq_zone_no(rq));
784 		break;
785 	case REQ_OP_ZONE_OPEN:
786 		cmd->ret = zloop_open_zone(zlo, rq_zone_no(rq));
787 		break;
788 	case REQ_OP_ZONE_CLOSE:
789 		cmd->ret = zloop_close_zone(zlo, rq_zone_no(rq));
790 		break;
791 	default:
792 		WARN_ON_ONCE(1);
793 		pr_err("Unsupported operation %d\n", req_op(rq));
794 		cmd->ret = -EOPNOTSUPP;
795 		break;
796 	}
797 
798 	blk_mq_complete_request(rq);
799 }
800 
801 static void zloop_cmd_workfn(struct work_struct *work)
802 {
803 	struct zloop_cmd *cmd = container_of(work, struct zloop_cmd, work);
804 	int orig_flags = current->flags;
805 
806 	current->flags |= PF_LOCAL_THROTTLE | PF_MEMALLOC_NOIO;
807 	zloop_handle_cmd(cmd);
808 	current->flags = orig_flags;
809 }
810 
811 static void zloop_fill_zero_rq(struct request *rq, unsigned int zero_from)
812 {
813 	struct req_iterator iter;
814 	struct bio_vec bv;
815 	unsigned int pos = 0;
816 	unsigned int end, off;
817 
818 	rq_for_each_segment(bv, rq, iter) {
819 		end = pos + bv.bv_len;
820 		if (end > zero_from) {
821 			if (pos < zero_from)
822 				off = zero_from - pos;
823 			else
824 				off = 0;
825 			memzero_page(bv.bv_page, bv.bv_offset + off,
826 				     bv.bv_len - off);
827 		}
828 		pos = end;
829 	}
830 }
831 
832 static void zloop_complete_rq(struct request *rq)
833 {
834 	struct zloop_cmd *cmd = blk_mq_rq_to_pdu(rq);
835 	struct zloop_device *zlo = rq->q->queuedata;
836 	unsigned int zone_no = cmd->sector >> zlo->zone_shift;
837 	struct zloop_zone *zone = &zlo->zones[zone_no];
838 	blk_status_t sts = BLK_STS_OK;
839 
840 	switch (req_op(rq)) {
841 	case REQ_OP_READ:
842 		if (cmd->ret < 0)
843 			pr_err("%pg: Zone %u: failed read sector %llu, %llu sectors\n",
844 			       zlo->disk->part0, zone_no, cmd->sector,
845 			       cmd->nr_sectors);
846 
847 		/* Short read. Zero out the unread tail beyond cmd->ret. */
848 		if (cmd->ret >= 0 && cmd->ret != blk_rq_bytes(rq))
849 			zloop_fill_zero_rq(rq, cmd->ret);
850 		break;
851 	case REQ_OP_WRITE:
852 	case REQ_OP_ZONE_APPEND:
853 		if (cmd->ret < 0)
854 			pr_err("%pg: Zone %u: failed %swrite sector %llu, %llu sectors\n",
855 			       zlo->disk->part0, zone_no,
856 			       req_op(rq) == REQ_OP_WRITE ? "" : "append ",
857 			       cmd->sector, cmd->nr_sectors);
858 
859 		if (cmd->ret >= 0 && cmd->ret != blk_rq_bytes(rq)) {
860 			pr_err("%pg: Zone %u: partial write %ld/%u B\n",
861 			       zlo->disk->part0, zone_no, cmd->ret,
862 			       blk_rq_bytes(rq));
863 			cmd->ret = -EIO;
864 		}
865 
866 		if (cmd->ret < 0 && !test_bit(ZLOOP_ZONE_CONV, &zone->flags)) {
867 			/*
868 			 * A write to a sequential zone file failed: mark the
869 			 * zone as having an error. This will be corrected and
870 			 * cleared when the next IO is submitted.
871 			 */
872 			set_bit(ZLOOP_ZONE_SEQ_ERROR, &zone->flags);
873 			break;
874 		}
875 		if (req_op(rq) == REQ_OP_ZONE_APPEND)
876 			rq->__sector = cmd->sector;
877 
878 		break;
879 	default:
880 		break;
881 	}
882 
883 	if (cmd->ret < 0)
884 		sts = errno_to_blk_status(cmd->ret);
885 	blk_mq_end_request(rq, sts);
886 }
887 
888 static bool zloop_set_zone_append_sector(struct request *rq)
889 {
890 	struct zloop_device *zlo = rq->q->queuedata;
891 	unsigned int zone_no = rq_zone_no(rq);
892 	struct zloop_zone *zone = &zlo->zones[zone_no];
893 	sector_t zone_end = zone->start + zlo->zone_capacity;
894 	sector_t nr_sectors = blk_rq_sectors(rq);
895 
896 	spin_lock(&zone->wp_lock);
897 
898 	if (zone->cond == BLK_ZONE_COND_FULL ||
899 	    zone->wp + nr_sectors > zone_end) {
900 		spin_unlock(&zone->wp_lock);
901 		return false;
902 	}
903 
904 	rq->__sector = zone->wp;
905 	zone->wp += blk_rq_sectors(rq);
906 	if (zone->wp >= zone_end)
907 		zloop_mark_full(zlo, zone);
908 
909 	spin_unlock(&zone->wp_lock);
910 
911 	return true;
912 }
913 
914 static blk_status_t zloop_queue_rq(struct blk_mq_hw_ctx *hctx,
915 				   const struct blk_mq_queue_data *bd)
916 {
917 	struct request *rq = bd->rq;
918 	struct zloop_cmd *cmd = blk_mq_rq_to_pdu(rq);
919 	struct zloop_device *zlo = rq->q->queuedata;
920 
921 	if (data_race(READ_ONCE(zlo->state)) == Zlo_deleting) {
922 		rq->rq_flags |= RQF_QUIET;
923 		return BLK_STS_IOERR;
924 	}
925 
926 	/*
927 	 * If we need to strongly order zone append operations, set the request
928 	 * sector to the zone write pointer location now instead of when the
929 	 * command work runs.
930 	 */
931 	if (zlo->ordered_zone_append && req_op(rq) == REQ_OP_ZONE_APPEND) {
932 		if (!zloop_set_zone_append_sector(rq))
933 			return BLK_STS_IOERR;
934 	}
935 
936 	blk_mq_start_request(rq);
937 
938 	INIT_WORK(&cmd->work, zloop_cmd_workfn);
939 	queue_work(zlo->workqueue, &cmd->work);
940 
941 	return BLK_STS_OK;
942 }
943 
944 static const struct blk_mq_ops zloop_mq_ops = {
945 	.queue_rq       = zloop_queue_rq,
946 	.complete	= zloop_complete_rq,
947 };
948 
949 static int zloop_open(struct gendisk *disk, blk_mode_t mode)
950 {
951 	struct zloop_device *zlo = disk->private_data;
952 	int ret;
953 
954 	ret = mutex_lock_killable(&zloop_ctl_mutex);
955 	if (ret)
956 		return ret;
957 
958 	if (zlo->state != Zlo_live)
959 		ret = -ENXIO;
960 	mutex_unlock(&zloop_ctl_mutex);
961 	return ret;
962 }
963 
964 static int zloop_report_zones(struct gendisk *disk, sector_t sector,
965 		unsigned int nr_zones, struct blk_report_zones_args *args)
966 {
967 	struct zloop_device *zlo = disk->private_data;
968 	struct blk_zone blkz = {};
969 	unsigned int first, i;
970 	int ret;
971 
972 	first = disk_zone_no(disk, sector);
973 	if (first >= zlo->nr_zones)
974 		return 0;
975 	nr_zones = min(nr_zones, zlo->nr_zones - first);
976 
977 	for (i = 0; i < nr_zones; i++) {
978 		unsigned int zone_no = first + i;
979 		struct zloop_zone *zone = &zlo->zones[zone_no];
980 
981 		mutex_lock(&zone->lock);
982 
983 		if (test_and_clear_bit(ZLOOP_ZONE_SEQ_ERROR, &zone->flags)) {
984 			ret = zloop_update_seq_zone(zlo, zone_no);
985 			if (ret) {
986 				mutex_unlock(&zone->lock);
987 				return ret;
988 			}
989 		}
990 
991 		blkz.start = zone->start;
992 		blkz.len = zlo->zone_size;
993 		spin_lock(&zone->wp_lock);
994 		blkz.wp = zone->wp;
995 		spin_unlock(&zone->wp_lock);
996 		blkz.cond = zone->cond;
997 		if (test_bit(ZLOOP_ZONE_CONV, &zone->flags)) {
998 			blkz.type = BLK_ZONE_TYPE_CONVENTIONAL;
999 			blkz.capacity = zlo->zone_size;
1000 		} else {
1001 			blkz.type = BLK_ZONE_TYPE_SEQWRITE_REQ;
1002 			blkz.capacity = zlo->zone_capacity;
1003 		}
1004 
1005 		mutex_unlock(&zone->lock);
1006 
1007 		ret = disk_report_zone(disk, &blkz, i, args);
1008 		if (ret)
1009 			return ret;
1010 	}
1011 
1012 	return nr_zones;
1013 }
1014 
1015 static void zloop_free_disk(struct gendisk *disk)
1016 {
1017 	struct zloop_device *zlo = disk->private_data;
1018 	unsigned int i;
1019 
1020 	blk_mq_free_tag_set(&zlo->tag_set);
1021 
1022 	for (i = 0; i < zlo->nr_zones; i++) {
1023 		struct zloop_zone *zone = &zlo->zones[i];
1024 
1025 		mapping_set_gfp_mask(zone->file->f_mapping,
1026 				zone->old_gfp_mask);
1027 		fput(zone->file);
1028 	}
1029 
1030 	fput(zlo->data_dir);
1031 	destroy_workqueue(zlo->workqueue);
1032 	kfree(zlo->base_dir);
1033 	kvfree(zlo);
1034 }
1035 
1036 static const struct block_device_operations zloop_fops = {
1037 	.owner			= THIS_MODULE,
1038 	.open			= zloop_open,
1039 	.report_zones		= zloop_report_zones,
1040 	.free_disk		= zloop_free_disk,
1041 };
1042 
1043 __printf(3, 4)
1044 static struct file *zloop_filp_open_fmt(int oflags, umode_t mode,
1045 		const char *fmt, ...)
1046 {
1047 	struct file *file;
1048 	va_list ap;
1049 	char *p;
1050 
1051 	va_start(ap, fmt);
1052 	p = kvasprintf(GFP_KERNEL, fmt, ap);
1053 	va_end(ap);
1054 
1055 	if (!p)
1056 		return ERR_PTR(-ENOMEM);
1057 	file = filp_open(p, oflags, mode);
1058 	kfree(p);
1059 	return file;
1060 }
1061 
1062 static int zloop_get_block_size(struct zloop_device *zlo,
1063 				struct zloop_zone *zone)
1064 {
1065 	struct block_device *sb_bdev = zone->file->f_mapping->host->i_sb->s_bdev;
1066 	struct kstat st;
1067 
1068 	/*
1069 	 * Use the dio alignment of the file system if provided.  The incoming
1070 	 * request's bio_vec is forwarded to the backing file unchanged, so its
1071 	 * required memory alignment becomes the device's dma_alignment when
1072 	 * used for direct-io.  The file system reports zeroed alignments if the
1073 	 * file can't be used for direct-io at all, so fall back to the block
1074 	 * device limits in that case.
1075 	 */
1076 	if (!vfs_getattr(&zone->file->f_path, &st, STATX_DIOALIGN, 0) &&
1077 	    (st.result_mask & STATX_DIOALIGN) && st.dio_mem_align) {
1078 		zlo->block_size = st.dio_offset_align;
1079 		zlo->dio_mem_align = min(st.dio_mem_align - 1, PAGE_SIZE - 1);
1080 	} else if (sb_bdev) {
1081 		zlo->block_size = bdev_physical_block_size(sb_bdev);
1082 		zlo->dio_mem_align = bdev_dma_alignment(sb_bdev);
1083 	} else {
1084 		zlo->block_size = SECTOR_SIZE;
1085 		zlo->dio_mem_align = SECTOR_SIZE - 1;
1086 	}
1087 
1088 	/*
1089 	 * Prefer the FS block size for the device block size when it is no
1090 	 * larger than 4K; otherwise keep the direct I/O / physical block size
1091 	 * selected above.
1092 	 */
1093 	if (file_inode(zone->file)->i_sb->s_blocksize <= SZ_4K)
1094 		zlo->block_size = file_inode(zone->file)->i_sb->s_blocksize;
1095 
1096 	if (zlo->zone_capacity & ((zlo->block_size >> SECTOR_SHIFT) - 1)) {
1097 		pr_err("Zone capacity is not aligned to block size %u\n",
1098 		       zlo->block_size);
1099 		return -EINVAL;
1100 	}
1101 
1102 	return 0;
1103 }
1104 
1105 static int zloop_init_zone(struct zloop_device *zlo, struct zloop_options *opts,
1106 			   unsigned int zone_no, bool restore)
1107 {
1108 	struct zloop_zone *zone = &zlo->zones[zone_no];
1109 	int oflags = O_RDWR;
1110 	struct kstat stat;
1111 	sector_t file_sectors;
1112 	int ret;
1113 
1114 	mutex_init(&zone->lock);
1115 	INIT_LIST_HEAD(&zone->open_zone_entry);
1116 	spin_lock_init(&zone->wp_lock);
1117 	zone->start = (sector_t)zone_no << zlo->zone_shift;
1118 
1119 	if (!restore)
1120 		oflags |= O_CREAT;
1121 
1122 	if (!opts->buffered_io)
1123 		oflags |= O_DIRECT;
1124 
1125 	if (zone_no < zlo->nr_conv_zones) {
1126 		/* Conventional zone file. */
1127 		set_bit(ZLOOP_ZONE_CONV, &zone->flags);
1128 		zone->cond = BLK_ZONE_COND_NOT_WP;
1129 		zone->wp = U64_MAX;
1130 
1131 		zone->file = zloop_filp_open_fmt(oflags, 0600, "%s/%u/cnv-%06u",
1132 					zlo->base_dir, zlo->id, zone_no);
1133 		if (IS_ERR(zone->file)) {
1134 			pr_err("Failed to open zone %u file %s/%u/cnv-%06u (err=%ld)",
1135 			       zone_no, zlo->base_dir, zlo->id, zone_no,
1136 			       PTR_ERR(zone->file));
1137 			return PTR_ERR(zone->file);
1138 		}
1139 
1140 		if (!zlo->block_size) {
1141 			ret = zloop_get_block_size(zlo, zone);
1142 			if (ret)
1143 				return ret;
1144 		}
1145 
1146 		ret = vfs_getattr(&zone->file->f_path, &stat, STATX_SIZE, 0);
1147 		if (ret < 0) {
1148 			pr_err("Failed to get zone %u file stat\n", zone_no);
1149 			return ret;
1150 		}
1151 		file_sectors = stat.size >> SECTOR_SHIFT;
1152 
1153 		if (restore && file_sectors != zlo->zone_size) {
1154 			pr_err("Invalid conventional zone %u file size (%llu sectors != %llu)\n",
1155 			       zone_no, file_sectors, zlo->zone_capacity);
1156 			return ret;
1157 		}
1158 
1159 		ret = vfs_truncate(&zone->file->f_path,
1160 				   zlo->zone_size << SECTOR_SHIFT);
1161 		if (ret < 0) {
1162 			pr_err("Failed to truncate zone %u file (err=%d)\n",
1163 			       zone_no, ret);
1164 			return ret;
1165 		}
1166 
1167 		return 0;
1168 	}
1169 
1170 	/* Sequential zone file. */
1171 	zone->file = zloop_filp_open_fmt(oflags, 0600, "%s/%u/seq-%06u",
1172 					 zlo->base_dir, zlo->id, zone_no);
1173 	if (IS_ERR(zone->file)) {
1174 		pr_err("Failed to open zone %u file %s/%u/seq-%06u (err=%ld)",
1175 		       zone_no, zlo->base_dir, zlo->id, zone_no,
1176 		       PTR_ERR(zone->file));
1177 		return PTR_ERR(zone->file);
1178 	}
1179 
1180 	if (!zlo->block_size) {
1181 		ret = zloop_get_block_size(zlo, zone);
1182 		if (ret)
1183 			return ret;
1184 	}
1185 
1186 	zloop_get_block_size(zlo, zone);
1187 
1188 	mutex_lock(&zone->lock);
1189 	ret = zloop_update_seq_zone(zlo, zone_no);
1190 	mutex_unlock(&zone->lock);
1191 
1192 	return ret;
1193 }
1194 
1195 static bool zloop_dev_exists(struct zloop_device *zlo)
1196 {
1197 	struct file *cnv, *seq;
1198 	bool exists;
1199 
1200 	cnv = zloop_filp_open_fmt(O_RDONLY, 0600, "%s/%u/cnv-%06u",
1201 				  zlo->base_dir, zlo->id, 0);
1202 	seq = zloop_filp_open_fmt(O_RDONLY, 0600, "%s/%u/seq-%06u",
1203 				  zlo->base_dir, zlo->id, 0);
1204 	exists = !IS_ERR(cnv) || !IS_ERR(seq);
1205 
1206 	if (!IS_ERR(cnv))
1207 		fput(cnv);
1208 	if (!IS_ERR(seq))
1209 		fput(seq);
1210 
1211 	return exists;
1212 }
1213 
1214 static int zloop_ctl_add(struct zloop_options *opts)
1215 {
1216 	struct queue_limits lim = {
1217 		.max_hw_sectors		= SZ_1M >> SECTOR_SHIFT,
1218 		.chunk_sectors		= opts->zone_size,
1219 		.features		= BLK_FEAT_ZONED | BLK_FEAT_WRITE_CACHE,
1220 
1221 	};
1222 	unsigned int nr_zones, i, j;
1223 	struct zloop_device *zlo;
1224 	int ret = -EINVAL;
1225 	bool restore;
1226 
1227 	__module_get(THIS_MODULE);
1228 
1229 	nr_zones = opts->capacity >> ilog2(opts->zone_size);
1230 	if (opts->nr_conv_zones >= nr_zones) {
1231 		pr_err("Invalid number of conventional zones %u\n",
1232 		       opts->nr_conv_zones);
1233 		goto out;
1234 	}
1235 
1236 	if (opts->max_open_zones > nr_zones - opts->nr_conv_zones) {
1237 		pr_err("Invalid maximum number of open zones %u\n",
1238 		       opts->max_open_zones);
1239 		goto out;
1240 	}
1241 
1242 	zlo = kvzalloc_flex(*zlo, zones, nr_zones);
1243 	if (!zlo) {
1244 		ret = -ENOMEM;
1245 		goto out;
1246 	}
1247 	WRITE_ONCE(zlo->state, Zlo_creating);
1248 	spin_lock_init(&zlo->open_zones_lock);
1249 	INIT_LIST_HEAD(&zlo->open_zones_lru_list);
1250 
1251 	ret = mutex_lock_killable(&zloop_ctl_mutex);
1252 	if (ret)
1253 		goto out_free_dev;
1254 
1255 	/* Allocate id, if @opts->id >= 0, we're requesting that specific id */
1256 	if (opts->id >= 0) {
1257 		ret = idr_alloc(&zloop_index_idr, zlo,
1258 				  opts->id, opts->id + 1, GFP_KERNEL);
1259 		if (ret == -ENOSPC)
1260 			ret = -EEXIST;
1261 	} else {
1262 		ret = idr_alloc(&zloop_index_idr, zlo, 0, 0, GFP_KERNEL);
1263 	}
1264 	mutex_unlock(&zloop_ctl_mutex);
1265 	if (ret < 0)
1266 		goto out_free_dev;
1267 
1268 	zlo->id = ret;
1269 	zlo->zone_shift = ilog2(opts->zone_size);
1270 	zlo->zone_size = opts->zone_size;
1271 	if (opts->zone_capacity)
1272 		zlo->zone_capacity = opts->zone_capacity;
1273 	else
1274 		zlo->zone_capacity = zlo->zone_size;
1275 	zlo->nr_zones = nr_zones;
1276 	zlo->nr_conv_zones = opts->nr_conv_zones;
1277 	zlo->max_open_zones = opts->max_open_zones;
1278 	zlo->buffered_io = opts->buffered_io;
1279 	zlo->zone_append = opts->zone_append;
1280 	if (zlo->zone_append)
1281 		zlo->ordered_zone_append = opts->ordered_zone_append;
1282 	zlo->discard_write_cache = opts->discard_write_cache;
1283 
1284 	zlo->workqueue = alloc_workqueue("zloop%d", WQ_UNBOUND | WQ_FREEZABLE,
1285 				opts->nr_queues * opts->queue_depth, zlo->id);
1286 	if (!zlo->workqueue) {
1287 		ret = -ENOMEM;
1288 		goto out_free_idr;
1289 	}
1290 
1291 	if (opts->base_dir)
1292 		zlo->base_dir = kstrdup(opts->base_dir, GFP_KERNEL);
1293 	else
1294 		zlo->base_dir = kstrdup(ZLOOP_DEF_BASE_DIR, GFP_KERNEL);
1295 	if (!zlo->base_dir) {
1296 		ret = -ENOMEM;
1297 		goto out_destroy_workqueue;
1298 	}
1299 
1300 	zlo->data_dir = zloop_filp_open_fmt(O_RDONLY | O_DIRECTORY, 0, "%s/%u",
1301 					    zlo->base_dir, zlo->id);
1302 	if (IS_ERR(zlo->data_dir)) {
1303 		ret = PTR_ERR(zlo->data_dir);
1304 		pr_warn("Failed to open directory %s/%u (err=%d)\n",
1305 			zlo->base_dir, zlo->id, ret);
1306 		goto out_free_base_dir;
1307 	}
1308 
1309 	/*
1310 	 * If we already have zone files, we are restoring a device created by a
1311 	 * previous add operation. In this case, zloop_init_zone() will check
1312 	 * that the zone files are consistent with the zone configuration given.
1313 	 */
1314 	restore = zloop_dev_exists(zlo);
1315 	for (i = 0; i < nr_zones; i++) {
1316 		ret = zloop_init_zone(zlo, opts, i, restore);
1317 		if (ret)
1318 			goto out_close_files;
1319 	}
1320 
1321 	lim.physical_block_size = zlo->block_size;
1322 	lim.logical_block_size = zlo->block_size;
1323 	/* Direct I/O forwards the request pages to the backing files as-is. */
1324 	if (!opts->buffered_io)
1325 		lim.dma_alignment = max_t(unsigned int, zlo->dio_mem_align,
1326 					  SECTOR_SIZE - 1);
1327 	if (zlo->zone_append)
1328 		lim.max_hw_zone_append_sectors = lim.max_hw_sectors;
1329 	lim.max_open_zones = zlo->max_open_zones;
1330 
1331 	zlo->tag_set.ops = &zloop_mq_ops;
1332 	zlo->tag_set.nr_hw_queues = opts->nr_queues;
1333 	zlo->tag_set.queue_depth = opts->queue_depth;
1334 	zlo->tag_set.numa_node = NUMA_NO_NODE;
1335 	zlo->tag_set.cmd_size = sizeof(struct zloop_cmd);
1336 	zlo->tag_set.driver_data = zlo;
1337 
1338 	ret = blk_mq_alloc_tag_set(&zlo->tag_set);
1339 	if (ret) {
1340 		pr_err("blk_mq_alloc_tag_set failed (err=%d)\n", ret);
1341 		goto out_close_files;
1342 	}
1343 
1344 	zlo->disk = blk_mq_alloc_disk(&zlo->tag_set, &lim, zlo);
1345 	if (IS_ERR(zlo->disk)) {
1346 		pr_err("blk_mq_alloc_disk failed (err=%d)\n", ret);
1347 		ret = PTR_ERR(zlo->disk);
1348 		goto out_cleanup_tags;
1349 	}
1350 	zlo->disk->flags = GENHD_FL_NO_PART;
1351 	zlo->disk->fops = &zloop_fops;
1352 	zlo->disk->private_data = zlo;
1353 	sprintf(zlo->disk->disk_name, "zloop%d", zlo->id);
1354 	set_capacity(zlo->disk, (u64)lim.chunk_sectors * zlo->nr_zones);
1355 
1356 	ret = blk_revalidate_disk_zones(zlo->disk);
1357 	if (ret)
1358 		goto out_cleanup_disk;
1359 
1360 	ret = add_disk(zlo->disk);
1361 	if (ret) {
1362 		pr_err("add_disk failed (err=%d)\n", ret);
1363 		goto out_cleanup_disk;
1364 	}
1365 
1366 	mutex_lock(&zloop_ctl_mutex);
1367 	WRITE_ONCE(zlo->state, Zlo_live);
1368 	mutex_unlock(&zloop_ctl_mutex);
1369 
1370 	pr_info("zloop: device %d, %u zones of %llu MiB, %u B block size\n",
1371 		zlo->id, zlo->nr_zones,
1372 		((sector_t)zlo->zone_size << SECTOR_SHIFT) >> 20,
1373 		zlo->block_size);
1374 	pr_info("zloop%d: using %s%s zone append\n",
1375 		zlo->id,
1376 		zlo->ordered_zone_append ? "ordered " : "",
1377 		zlo->zone_append ? "native" : "emulated");
1378 
1379 	return 0;
1380 
1381 out_cleanup_disk:
1382 	put_disk(zlo->disk);
1383 out_cleanup_tags:
1384 	blk_mq_free_tag_set(&zlo->tag_set);
1385 out_close_files:
1386 	for (j = 0; j < i; j++) {
1387 		struct zloop_zone *zone = &zlo->zones[j];
1388 
1389 		if (!IS_ERR_OR_NULL(zone->file))
1390 			fput(zone->file);
1391 	}
1392 	fput(zlo->data_dir);
1393 out_free_base_dir:
1394 	kfree(zlo->base_dir);
1395 out_destroy_workqueue:
1396 	destroy_workqueue(zlo->workqueue);
1397 out_free_idr:
1398 	mutex_lock(&zloop_ctl_mutex);
1399 	idr_remove(&zloop_index_idr, zlo->id);
1400 	mutex_unlock(&zloop_ctl_mutex);
1401 out_free_dev:
1402 	kvfree(zlo);
1403 out:
1404 	module_put(THIS_MODULE);
1405 	if (ret == -ENOENT)
1406 		ret = -EINVAL;
1407 	return ret;
1408 }
1409 
1410 static void zloop_forget_cache(struct zloop_device *zlo)
1411 {
1412 	unsigned int i;
1413 	int ret;
1414 
1415 	pr_info("%pg: discarding volatile write cache\n", zlo->disk->part0);
1416 
1417 	for (i = 0; i < zlo->nr_zones; i++) {
1418 		struct zloop_zone *zone = &zlo->zones[i];
1419 		struct file *file = zone->file;
1420 		sector_t old_wp;
1421 
1422 		if (!zloop_zone_is_active(zone))
1423 			continue;
1424 
1425 		ret = vfs_getxattr(file_mnt_idmap(file), file_dentry(file),
1426 				"user.zloop.wp", &old_wp, sizeof(old_wp));
1427 		if (ret == -ENODATA) {
1428 			old_wp = 0;
1429 		} else if (ret != sizeof(old_wp)) {
1430 			pr_err("%pg: failed to retrieve write pointer (%d)\n",
1431 				zlo->disk->part0, ret);
1432 			continue;
1433 		}
1434 
1435 		if (old_wp > zone->wp)
1436 			continue;
1437 		/*
1438 		 * This should not happen, if we recored a full zone, it can't
1439 		 * be active.
1440 		 */
1441 		if (WARN_ON_ONCE(old_wp == ULLONG_MAX))
1442 			continue;
1443 
1444 		vfs_truncate(&file->f_path,
1445 			(old_wp - zone->start) << SECTOR_SHIFT);
1446 	}
1447 }
1448 
1449 static int zloop_ctl_remove(struct zloop_options *opts)
1450 {
1451 	struct zloop_device *zlo;
1452 	int ret;
1453 
1454 	if (!(opts->mask & ZLOOP_OPT_ID)) {
1455 		pr_err("No ID specified for remove\n");
1456 		return -EINVAL;
1457 	}
1458 
1459 	if (opts->mask & ~ZLOOP_OPT_ID) {
1460 		pr_err("Invalid option specified for remove\n");
1461 		return -EINVAL;
1462 	}
1463 
1464 	ret = mutex_lock_killable(&zloop_ctl_mutex);
1465 	if (ret)
1466 		return ret;
1467 
1468 	zlo = idr_find(&zloop_index_idr, opts->id);
1469 	if (!zlo || zlo->state == Zlo_creating) {
1470 		ret = -ENODEV;
1471 	} else if (zlo->state == Zlo_deleting) {
1472 		ret = -EINVAL;
1473 	} else {
1474 		idr_remove(&zloop_index_idr, zlo->id);
1475 		WRITE_ONCE(zlo->state, Zlo_deleting);
1476 	}
1477 
1478 	mutex_unlock(&zloop_ctl_mutex);
1479 	if (ret)
1480 		return ret;
1481 
1482 	del_gendisk(zlo->disk);
1483 
1484 	if (zlo->discard_write_cache)
1485 		zloop_forget_cache(zlo);
1486 
1487 	put_disk(zlo->disk);
1488 
1489 	pr_info("Removed device %d\n", opts->id);
1490 
1491 	module_put(THIS_MODULE);
1492 
1493 	return 0;
1494 }
1495 
1496 static int zloop_parse_options(struct zloop_options *opts, const char *buf)
1497 {
1498 	substring_t args[MAX_OPT_ARGS];
1499 	char *options, *o, *p;
1500 	unsigned int token;
1501 	int ret = 0;
1502 
1503 	/* Set defaults. */
1504 	opts->mask = 0;
1505 	opts->id = ZLOOP_DEF_ID;
1506 	opts->capacity = ZLOOP_DEF_ZONE_SIZE * ZLOOP_DEF_NR_ZONES;
1507 	opts->zone_size = ZLOOP_DEF_ZONE_SIZE;
1508 	opts->nr_conv_zones = ZLOOP_DEF_NR_CONV_ZONES;
1509 	opts->max_open_zones = ZLOOP_DEF_MAX_OPEN_ZONES;
1510 	opts->nr_queues = ZLOOP_DEF_NR_QUEUES;
1511 	opts->queue_depth = ZLOOP_DEF_QUEUE_DEPTH;
1512 	opts->buffered_io = ZLOOP_DEF_BUFFERED_IO;
1513 	opts->zone_append = ZLOOP_DEF_ZONE_APPEND;
1514 	opts->ordered_zone_append = ZLOOP_DEF_ORDERED_ZONE_APPEND;
1515 
1516 	if (!buf)
1517 		return 0;
1518 
1519 	/* Skip leading spaces before the options. */
1520 	while (isspace(*buf))
1521 		buf++;
1522 
1523 	options = o = kstrdup(buf, GFP_KERNEL);
1524 	if (!options)
1525 		return -ENOMEM;
1526 
1527 	/* Parse the options, doing only some light invalid value checks. */
1528 	while ((p = strsep(&o, ",\n")) != NULL) {
1529 		if (!*p)
1530 			continue;
1531 
1532 		token = match_token(p, zloop_opt_tokens, args);
1533 		opts->mask |= token;
1534 		switch (token) {
1535 		case ZLOOP_OPT_ID:
1536 			if (match_int(args, &opts->id)) {
1537 				ret = -EINVAL;
1538 				goto out;
1539 			}
1540 			break;
1541 		case ZLOOP_OPT_CAPACITY:
1542 			if (match_uint(args, &token)) {
1543 				ret = -EINVAL;
1544 				goto out;
1545 			}
1546 			if (!token) {
1547 				pr_err("Invalid capacity\n");
1548 				ret = -EINVAL;
1549 				goto out;
1550 			}
1551 			opts->capacity =
1552 				((sector_t)token * SZ_1M) >> SECTOR_SHIFT;
1553 			break;
1554 		case ZLOOP_OPT_ZONE_SIZE:
1555 			if (match_uint(args, &token)) {
1556 				ret = -EINVAL;
1557 				goto out;
1558 			}
1559 			if (!token || token > ZLOOP_MAX_ZONE_SIZE_MB ||
1560 			    !is_power_of_2(token)) {
1561 				pr_err("Invalid zone size %u\n", token);
1562 				ret = -EINVAL;
1563 				goto out;
1564 			}
1565 			opts->zone_size =
1566 				((sector_t)token * SZ_1M) >> SECTOR_SHIFT;
1567 			break;
1568 		case ZLOOP_OPT_ZONE_CAPACITY:
1569 			if (match_uint(args, &token)) {
1570 				ret = -EINVAL;
1571 				goto out;
1572 			}
1573 			if (!token) {
1574 				pr_err("Invalid zone capacity\n");
1575 				ret = -EINVAL;
1576 				goto out;
1577 			}
1578 			opts->zone_capacity =
1579 				((sector_t)token * SZ_1M) >> SECTOR_SHIFT;
1580 			break;
1581 		case ZLOOP_OPT_NR_CONV_ZONES:
1582 			if (match_uint(args, &token)) {
1583 				ret = -EINVAL;
1584 				goto out;
1585 			}
1586 			opts->nr_conv_zones = token;
1587 			break;
1588 		case ZLOOP_OPT_MAX_OPEN_ZONES:
1589 			if (match_uint(args, &token)) {
1590 				ret = -EINVAL;
1591 				goto out;
1592 			}
1593 			opts->max_open_zones = token;
1594 			break;
1595 		case ZLOOP_OPT_BASE_DIR:
1596 			p = match_strdup(args);
1597 			if (!p) {
1598 				ret = -ENOMEM;
1599 				goto out;
1600 			}
1601 			kfree(opts->base_dir);
1602 			opts->base_dir = p;
1603 			break;
1604 		case ZLOOP_OPT_NR_QUEUES:
1605 			if (match_uint(args, &token)) {
1606 				ret = -EINVAL;
1607 				goto out;
1608 			}
1609 			if (!token) {
1610 				pr_err("Invalid number of queues\n");
1611 				ret = -EINVAL;
1612 				goto out;
1613 			}
1614 			opts->nr_queues = min(token, num_online_cpus());
1615 			break;
1616 		case ZLOOP_OPT_QUEUE_DEPTH:
1617 			if (match_uint(args, &token)) {
1618 				ret = -EINVAL;
1619 				goto out;
1620 			}
1621 			if (!token) {
1622 				pr_err("Invalid queue depth\n");
1623 				ret = -EINVAL;
1624 				goto out;
1625 			}
1626 			opts->queue_depth = token;
1627 			break;
1628 		case ZLOOP_OPT_BUFFERED_IO:
1629 			opts->buffered_io = true;
1630 			break;
1631 		case ZLOOP_OPT_ZONE_APPEND:
1632 			if (match_uint(args, &token)) {
1633 				ret = -EINVAL;
1634 				goto out;
1635 			}
1636 			if (token != 0 && token != 1) {
1637 				pr_err("Invalid zone_append value\n");
1638 				ret = -EINVAL;
1639 				goto out;
1640 			}
1641 			opts->zone_append = token;
1642 			break;
1643 		case ZLOOP_OPT_ORDERED_ZONE_APPEND:
1644 			opts->ordered_zone_append = true;
1645 			break;
1646 		case ZLOOP_OPT_DISCARD_WRITE_CACHE:
1647 			opts->discard_write_cache = true;
1648 			break;
1649 		case ZLOOP_OPT_ERR:
1650 		default:
1651 			pr_warn("unknown parameter or missing value '%s'\n", p);
1652 			ret = -EINVAL;
1653 			goto out;
1654 		}
1655 	}
1656 
1657 	ret = -EINVAL;
1658 	if (opts->capacity <= opts->zone_size) {
1659 		pr_err("Invalid capacity\n");
1660 		goto out;
1661 	}
1662 
1663 	if (opts->zone_capacity > opts->zone_size) {
1664 		pr_err("Invalid zone capacity\n");
1665 		goto out;
1666 	}
1667 
1668 	ret = 0;
1669 out:
1670 	kfree(options);
1671 	return ret;
1672 }
1673 
1674 enum {
1675 	ZLOOP_CTL_ADD,
1676 	ZLOOP_CTL_REMOVE,
1677 };
1678 
1679 static struct zloop_ctl_op {
1680 	int		code;
1681 	const char	*name;
1682 } zloop_ctl_ops[] = {
1683 	{ ZLOOP_CTL_ADD,	"add" },
1684 	{ ZLOOP_CTL_REMOVE,	"remove" },
1685 	{ -1,	NULL },
1686 };
1687 
1688 static ssize_t zloop_ctl_write(struct file *file, const char __user *ubuf,
1689 			       size_t count, loff_t *pos)
1690 {
1691 	struct zloop_options opts = { };
1692 	struct zloop_ctl_op *op;
1693 	const char *buf, *opts_buf;
1694 	int i, ret;
1695 
1696 	if (count > PAGE_SIZE)
1697 		return -ENOMEM;
1698 
1699 	buf = memdup_user_nul(ubuf, count);
1700 	if (IS_ERR(buf))
1701 		return PTR_ERR(buf);
1702 
1703 	for (i = 0; i < ARRAY_SIZE(zloop_ctl_ops); i++) {
1704 		op = &zloop_ctl_ops[i];
1705 		if (!op->name) {
1706 			pr_err("Invalid operation\n");
1707 			ret = -EINVAL;
1708 			goto out;
1709 		}
1710 		if (!strncmp(buf, op->name, strlen(op->name)))
1711 			break;
1712 	}
1713 
1714 	if (count <= strlen(op->name))
1715 		opts_buf = NULL;
1716 	else
1717 		opts_buf = buf + strlen(op->name);
1718 
1719 	ret = zloop_parse_options(&opts, opts_buf);
1720 	if (ret) {
1721 		pr_err("Failed to parse options\n");
1722 		goto out;
1723 	}
1724 
1725 	switch (op->code) {
1726 	case ZLOOP_CTL_ADD:
1727 		ret = zloop_ctl_add(&opts);
1728 		break;
1729 	case ZLOOP_CTL_REMOVE:
1730 		ret = zloop_ctl_remove(&opts);
1731 		break;
1732 	default:
1733 		pr_err("Invalid operation\n");
1734 		ret = -EINVAL;
1735 		goto out;
1736 	}
1737 
1738 out:
1739 	kfree(opts.base_dir);
1740 	kfree(buf);
1741 	return ret ? ret : count;
1742 }
1743 
1744 static int zloop_ctl_show(struct seq_file *seq_file, void *private)
1745 {
1746 	const struct match_token *tok;
1747 	int i;
1748 
1749 	/* Add operation */
1750 	seq_printf(seq_file, "%s ", zloop_ctl_ops[0].name);
1751 	for (i = 0; i < ARRAY_SIZE(zloop_opt_tokens); i++) {
1752 		tok = &zloop_opt_tokens[i];
1753 		if (!tok->pattern)
1754 			break;
1755 		if (i)
1756 			seq_putc(seq_file, ',');
1757 		seq_puts(seq_file, tok->pattern);
1758 	}
1759 	seq_putc(seq_file, '\n');
1760 
1761 	/* Remove operation */
1762 	seq_puts(seq_file, zloop_ctl_ops[1].name);
1763 	seq_puts(seq_file, " id=%d\n");
1764 
1765 	return 0;
1766 }
1767 
1768 static int zloop_ctl_open(struct inode *inode, struct file *file)
1769 {
1770 	file->private_data = NULL;
1771 	return single_open(file, zloop_ctl_show, NULL);
1772 }
1773 
1774 static int zloop_ctl_release(struct inode *inode, struct file *file)
1775 {
1776 	return single_release(inode, file);
1777 }
1778 
1779 static const struct file_operations zloop_ctl_fops = {
1780 	.owner		= THIS_MODULE,
1781 	.open		= zloop_ctl_open,
1782 	.release	= zloop_ctl_release,
1783 	.write		= zloop_ctl_write,
1784 	.read		= seq_read,
1785 };
1786 
1787 static struct miscdevice zloop_misc = {
1788 	.minor		= MISC_DYNAMIC_MINOR,
1789 	.name		= "zloop-control",
1790 	.fops		= &zloop_ctl_fops,
1791 };
1792 
1793 static int __init zloop_init(void)
1794 {
1795 	int ret;
1796 
1797 	ret = misc_register(&zloop_misc);
1798 	if (ret) {
1799 		pr_err("Failed to register misc device: %d\n", ret);
1800 		return ret;
1801 	}
1802 	pr_info("Module loaded\n");
1803 
1804 	return 0;
1805 }
1806 
1807 static void __exit zloop_exit(void)
1808 {
1809 	misc_deregister(&zloop_misc);
1810 	idr_destroy(&zloop_index_idr);
1811 }
1812 
1813 module_init(zloop_init);
1814 module_exit(zloop_exit);
1815 
1816 MODULE_DESCRIPTION("Zoned loopback device");
1817 MODULE_LICENSE("GPL");
1818