xref: /linux/drivers/block/zloop.c (revision 8fbee85a90789d367c347b1cfd5a5ef37f3a934a)
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 	int ret;
1111 
1112 	mutex_init(&zone->lock);
1113 	INIT_LIST_HEAD(&zone->open_zone_entry);
1114 	spin_lock_init(&zone->wp_lock);
1115 	zone->start = (sector_t)zone_no << zlo->zone_shift;
1116 
1117 	if (!restore)
1118 		oflags |= O_CREAT;
1119 
1120 	if (!opts->buffered_io)
1121 		oflags |= O_DIRECT;
1122 
1123 	zone->file = zloop_filp_open_fmt(oflags, 0600, "%s/%u/%s-%06u",
1124 				zlo->base_dir, zlo->id,
1125 				zone_no < zlo->nr_conv_zones ? "cnv" : "seq",
1126 				zone_no);
1127 	if (IS_ERR(zone->file)) {
1128 		pr_err("Failed to open zone %u file %s/%u/%s-%06u (err=%ld)",
1129 		       zone_no, zlo->base_dir, zlo->id,
1130 		       zone_no < zlo->nr_conv_zones ? "cnv" : "seq",
1131 		       zone_no, PTR_ERR(zone->file));
1132 		return PTR_ERR(zone->file);
1133 	}
1134 
1135 	if (!zone->file->f_op->read_iter || !zone->file->f_op->write_iter) {
1136 		ret = -EINVAL;
1137 		goto out_fput;
1138 	}
1139 
1140 	if (!zlo->block_size) {
1141 		ret = zloop_get_block_size(zlo, zone);
1142 		if (ret)
1143 			goto out_fput;
1144 	}
1145 
1146 	if (zone_no < zlo->nr_conv_zones) {
1147 		sector_t file_sectors;
1148 		struct kstat stat;
1149 
1150 		/* Conventional zone file. */
1151 		set_bit(ZLOOP_ZONE_CONV, &zone->flags);
1152 		zone->cond = BLK_ZONE_COND_NOT_WP;
1153 		zone->wp = U64_MAX;
1154 
1155 		ret = vfs_getattr(&zone->file->f_path, &stat, STATX_SIZE, 0);
1156 		if (ret < 0) {
1157 			pr_err("Failed to get zone %u file stat\n", zone_no);
1158 			goto out_fput;
1159 		}
1160 		file_sectors = stat.size >> SECTOR_SHIFT;
1161 
1162 		if (restore && file_sectors != zlo->zone_size) {
1163 			pr_err("Invalid conventional zone %u file size (%llu sectors != %llu)\n",
1164 			       zone_no, file_sectors, zlo->zone_size);
1165 			ret = -EINVAL;
1166 			goto out_fput;
1167 		}
1168 
1169 		ret = vfs_truncate(&zone->file->f_path,
1170 				   zlo->zone_size << SECTOR_SHIFT);
1171 		if (ret < 0) {
1172 			pr_err("Failed to truncate zone %u file (err=%d)\n",
1173 			       zone_no, ret);
1174 			goto out_fput;
1175 		}
1176 	} else {
1177 		/* Sequential zone file. */
1178 		mutex_lock(&zone->lock);
1179 		ret = zloop_update_seq_zone(zlo, zone_no);
1180 		mutex_unlock(&zone->lock);
1181 		if (ret)
1182 			goto out_fput;
1183 	}
1184 
1185 	return 0;
1186 
1187 out_fput:
1188 	fput(zone->file);
1189 	return ret;
1190 }
1191 
1192 static bool zloop_dev_exists(struct zloop_device *zlo)
1193 {
1194 	struct file *cnv, *seq;
1195 	bool exists;
1196 
1197 	cnv = zloop_filp_open_fmt(O_RDONLY, 0600, "%s/%u/cnv-%06u",
1198 				  zlo->base_dir, zlo->id, 0);
1199 	seq = zloop_filp_open_fmt(O_RDONLY, 0600, "%s/%u/seq-%06u",
1200 				  zlo->base_dir, zlo->id, 0);
1201 	exists = !IS_ERR(cnv) || !IS_ERR(seq);
1202 
1203 	if (!IS_ERR(cnv))
1204 		fput(cnv);
1205 	if (!IS_ERR(seq))
1206 		fput(seq);
1207 
1208 	return exists;
1209 }
1210 
1211 static int zloop_ctl_add(struct zloop_options *opts)
1212 {
1213 	struct queue_limits lim = {
1214 		.max_hw_sectors		= SZ_1M >> SECTOR_SHIFT,
1215 		.chunk_sectors		= opts->zone_size,
1216 		.features		= BLK_FEAT_ZONED | BLK_FEAT_WRITE_CACHE,
1217 
1218 	};
1219 	unsigned int nr_zones, i, j;
1220 	struct zloop_device *zlo;
1221 	int ret = -EINVAL;
1222 	bool restore;
1223 
1224 	__module_get(THIS_MODULE);
1225 
1226 	nr_zones = opts->capacity >> ilog2(opts->zone_size);
1227 	if (opts->nr_conv_zones >= nr_zones) {
1228 		pr_err("Invalid number of conventional zones %u\n",
1229 		       opts->nr_conv_zones);
1230 		goto out;
1231 	}
1232 
1233 	if (opts->max_open_zones > nr_zones - opts->nr_conv_zones) {
1234 		pr_err("Invalid maximum number of open zones %u\n",
1235 		       opts->max_open_zones);
1236 		goto out;
1237 	}
1238 
1239 	zlo = kvzalloc_flex(*zlo, zones, nr_zones);
1240 	if (!zlo) {
1241 		ret = -ENOMEM;
1242 		goto out;
1243 	}
1244 	WRITE_ONCE(zlo->state, Zlo_creating);
1245 	spin_lock_init(&zlo->open_zones_lock);
1246 	INIT_LIST_HEAD(&zlo->open_zones_lru_list);
1247 
1248 	ret = mutex_lock_killable(&zloop_ctl_mutex);
1249 	if (ret)
1250 		goto out_free_dev;
1251 
1252 	/* Allocate id, if @opts->id >= 0, we're requesting that specific id */
1253 	if (opts->id >= 0) {
1254 		ret = idr_alloc(&zloop_index_idr, zlo,
1255 				  opts->id, opts->id + 1, GFP_KERNEL);
1256 		if (ret == -ENOSPC)
1257 			ret = -EEXIST;
1258 	} else {
1259 		ret = idr_alloc(&zloop_index_idr, zlo, 0, 0, GFP_KERNEL);
1260 	}
1261 	mutex_unlock(&zloop_ctl_mutex);
1262 	if (ret < 0)
1263 		goto out_free_dev;
1264 
1265 	zlo->id = ret;
1266 	zlo->zone_shift = ilog2(opts->zone_size);
1267 	zlo->zone_size = opts->zone_size;
1268 	if (opts->zone_capacity)
1269 		zlo->zone_capacity = opts->zone_capacity;
1270 	else
1271 		zlo->zone_capacity = zlo->zone_size;
1272 	zlo->nr_zones = nr_zones;
1273 	zlo->nr_conv_zones = opts->nr_conv_zones;
1274 	zlo->max_open_zones = opts->max_open_zones;
1275 	zlo->buffered_io = opts->buffered_io;
1276 	zlo->zone_append = opts->zone_append;
1277 	if (zlo->zone_append)
1278 		zlo->ordered_zone_append = opts->ordered_zone_append;
1279 	zlo->discard_write_cache = opts->discard_write_cache;
1280 
1281 	zlo->workqueue = alloc_workqueue("zloop%d", WQ_UNBOUND | WQ_FREEZABLE,
1282 				opts->nr_queues * opts->queue_depth, zlo->id);
1283 	if (!zlo->workqueue) {
1284 		ret = -ENOMEM;
1285 		goto out_free_idr;
1286 	}
1287 
1288 	if (opts->base_dir)
1289 		zlo->base_dir = kstrdup(opts->base_dir, GFP_KERNEL);
1290 	else
1291 		zlo->base_dir = kstrdup(ZLOOP_DEF_BASE_DIR, GFP_KERNEL);
1292 	if (!zlo->base_dir) {
1293 		ret = -ENOMEM;
1294 		goto out_destroy_workqueue;
1295 	}
1296 
1297 	zlo->data_dir = zloop_filp_open_fmt(O_RDONLY | O_DIRECTORY, 0, "%s/%u",
1298 					    zlo->base_dir, zlo->id);
1299 	if (IS_ERR(zlo->data_dir)) {
1300 		ret = PTR_ERR(zlo->data_dir);
1301 		pr_warn("Failed to open directory %s/%u (err=%d)\n",
1302 			zlo->base_dir, zlo->id, ret);
1303 		goto out_free_base_dir;
1304 	}
1305 
1306 	/*
1307 	 * If we already have zone files, we are restoring a device created by a
1308 	 * previous add operation. In this case, zloop_init_zone() will check
1309 	 * that the zone files are consistent with the zone configuration given.
1310 	 */
1311 	restore = zloop_dev_exists(zlo);
1312 	for (i = 0; i < nr_zones; i++) {
1313 		ret = zloop_init_zone(zlo, opts, i, restore);
1314 		if (ret)
1315 			goto out_close_files;
1316 	}
1317 
1318 	lim.physical_block_size = zlo->block_size;
1319 	lim.logical_block_size = zlo->block_size;
1320 	/* Direct I/O forwards the request pages to the backing files as-is. */
1321 	if (!opts->buffered_io)
1322 		lim.dma_alignment = max_t(unsigned int, zlo->dio_mem_align,
1323 					  SECTOR_SIZE - 1);
1324 	if (zlo->zone_append)
1325 		lim.max_hw_zone_append_sectors = lim.max_hw_sectors;
1326 	lim.max_open_zones = zlo->max_open_zones;
1327 
1328 	zlo->tag_set.ops = &zloop_mq_ops;
1329 	zlo->tag_set.nr_hw_queues = opts->nr_queues;
1330 	zlo->tag_set.queue_depth = opts->queue_depth;
1331 	zlo->tag_set.numa_node = NUMA_NO_NODE;
1332 	zlo->tag_set.cmd_size = sizeof(struct zloop_cmd);
1333 	zlo->tag_set.driver_data = zlo;
1334 
1335 	ret = blk_mq_alloc_tag_set(&zlo->tag_set);
1336 	if (ret) {
1337 		pr_err("blk_mq_alloc_tag_set failed (err=%d)\n", ret);
1338 		goto out_close_files;
1339 	}
1340 
1341 	zlo->disk = blk_mq_alloc_disk(&zlo->tag_set, &lim, zlo);
1342 	if (IS_ERR(zlo->disk)) {
1343 		ret = PTR_ERR(zlo->disk);
1344 		pr_err("blk_mq_alloc_disk failed (err=%d)\n", ret);
1345 		goto out_cleanup_tags;
1346 	}
1347 	zlo->disk->flags = GENHD_FL_NO_PART;
1348 	zlo->disk->fops = &zloop_fops;
1349 	zlo->disk->private_data = zlo;
1350 	sprintf(zlo->disk->disk_name, "zloop%d", zlo->id);
1351 	set_capacity(zlo->disk, (u64)lim.chunk_sectors * zlo->nr_zones);
1352 
1353 	ret = blk_revalidate_disk_zones(zlo->disk);
1354 	if (ret)
1355 		goto out_cleanup_disk;
1356 
1357 	ret = add_disk(zlo->disk);
1358 	if (ret) {
1359 		pr_err("add_disk failed (err=%d)\n", ret);
1360 		goto out_cleanup_disk;
1361 	}
1362 
1363 	mutex_lock(&zloop_ctl_mutex);
1364 	WRITE_ONCE(zlo->state, Zlo_live);
1365 	mutex_unlock(&zloop_ctl_mutex);
1366 
1367 	pr_info("zloop: device %d, %u zones of %llu MiB, %u B block size\n",
1368 		zlo->id, zlo->nr_zones,
1369 		((sector_t)zlo->zone_size << SECTOR_SHIFT) >> 20,
1370 		zlo->block_size);
1371 	pr_info("zloop%d: using %s%s zone append\n",
1372 		zlo->id,
1373 		zlo->ordered_zone_append ? "ordered " : "",
1374 		zlo->zone_append ? "native" : "emulated");
1375 
1376 	return 0;
1377 
1378 out_cleanup_disk:
1379 	put_disk(zlo->disk);
1380 out_cleanup_tags:
1381 	blk_mq_free_tag_set(&zlo->tag_set);
1382 out_close_files:
1383 	for (j = 0; j < i; j++) {
1384 		struct zloop_zone *zone = &zlo->zones[j];
1385 
1386 		if (!IS_ERR_OR_NULL(zone->file))
1387 			fput(zone->file);
1388 	}
1389 	fput(zlo->data_dir);
1390 out_free_base_dir:
1391 	kfree(zlo->base_dir);
1392 out_destroy_workqueue:
1393 	destroy_workqueue(zlo->workqueue);
1394 out_free_idr:
1395 	mutex_lock(&zloop_ctl_mutex);
1396 	idr_remove(&zloop_index_idr, zlo->id);
1397 	mutex_unlock(&zloop_ctl_mutex);
1398 out_free_dev:
1399 	kvfree(zlo);
1400 out:
1401 	module_put(THIS_MODULE);
1402 	if (ret == -ENOENT)
1403 		ret = -EINVAL;
1404 	return ret;
1405 }
1406 
1407 static void zloop_forget_cache(struct zloop_device *zlo)
1408 {
1409 	unsigned int i;
1410 	int ret;
1411 
1412 	pr_info("%pg: discarding volatile write cache\n", zlo->disk->part0);
1413 
1414 	for (i = 0; i < zlo->nr_zones; i++) {
1415 		struct zloop_zone *zone = &zlo->zones[i];
1416 		struct file *file = zone->file;
1417 		sector_t old_wp;
1418 
1419 		if (!zloop_zone_is_active(zone))
1420 			continue;
1421 
1422 		ret = vfs_getxattr(file_mnt_idmap(file), file_dentry(file),
1423 				"user.zloop.wp", &old_wp, sizeof(old_wp));
1424 		if (ret == -ENODATA) {
1425 			old_wp = 0;
1426 		} else if (ret != sizeof(old_wp)) {
1427 			pr_err("%pg: failed to retrieve write pointer (%d)\n",
1428 				zlo->disk->part0, ret);
1429 			continue;
1430 		}
1431 
1432 		if (old_wp > zone->wp)
1433 			continue;
1434 		/*
1435 		 * This should not happen, if we recored a full zone, it can't
1436 		 * be active.
1437 		 */
1438 		if (WARN_ON_ONCE(old_wp == ULLONG_MAX))
1439 			continue;
1440 
1441 		vfs_truncate(&file->f_path,
1442 			(old_wp - zone->start) << SECTOR_SHIFT);
1443 	}
1444 }
1445 
1446 static int zloop_ctl_remove(struct zloop_options *opts)
1447 {
1448 	struct zloop_device *zlo;
1449 	int ret;
1450 
1451 	if (!(opts->mask & ZLOOP_OPT_ID)) {
1452 		pr_err("No ID specified for remove\n");
1453 		return -EINVAL;
1454 	}
1455 
1456 	if (opts->mask & ~ZLOOP_OPT_ID) {
1457 		pr_err("Invalid option specified for remove\n");
1458 		return -EINVAL;
1459 	}
1460 
1461 	ret = mutex_lock_killable(&zloop_ctl_mutex);
1462 	if (ret)
1463 		return ret;
1464 
1465 	zlo = idr_find(&zloop_index_idr, opts->id);
1466 	if (!zlo || zlo->state == Zlo_creating) {
1467 		ret = -ENODEV;
1468 	} else if (zlo->state == Zlo_deleting) {
1469 		ret = -EINVAL;
1470 	} else {
1471 		idr_remove(&zloop_index_idr, zlo->id);
1472 		WRITE_ONCE(zlo->state, Zlo_deleting);
1473 	}
1474 
1475 	mutex_unlock(&zloop_ctl_mutex);
1476 	if (ret)
1477 		return ret;
1478 
1479 	del_gendisk(zlo->disk);
1480 
1481 	if (zlo->discard_write_cache)
1482 		zloop_forget_cache(zlo);
1483 
1484 	put_disk(zlo->disk);
1485 
1486 	pr_info("Removed device %d\n", opts->id);
1487 
1488 	module_put(THIS_MODULE);
1489 
1490 	return 0;
1491 }
1492 
1493 static int zloop_parse_options(struct zloop_options *opts, const char *buf)
1494 {
1495 	substring_t args[MAX_OPT_ARGS];
1496 	char *options, *o, *p;
1497 	unsigned int token;
1498 	int ret = 0;
1499 
1500 	/* Set defaults. */
1501 	opts->mask = 0;
1502 	opts->id = ZLOOP_DEF_ID;
1503 	opts->capacity = ZLOOP_DEF_ZONE_SIZE * ZLOOP_DEF_NR_ZONES;
1504 	opts->zone_size = ZLOOP_DEF_ZONE_SIZE;
1505 	opts->nr_conv_zones = ZLOOP_DEF_NR_CONV_ZONES;
1506 	opts->max_open_zones = ZLOOP_DEF_MAX_OPEN_ZONES;
1507 	opts->nr_queues = ZLOOP_DEF_NR_QUEUES;
1508 	opts->queue_depth = ZLOOP_DEF_QUEUE_DEPTH;
1509 	opts->buffered_io = ZLOOP_DEF_BUFFERED_IO;
1510 	opts->zone_append = ZLOOP_DEF_ZONE_APPEND;
1511 	opts->ordered_zone_append = ZLOOP_DEF_ORDERED_ZONE_APPEND;
1512 
1513 	if (!buf)
1514 		return 0;
1515 
1516 	/* Skip leading spaces before the options. */
1517 	while (isspace(*buf))
1518 		buf++;
1519 
1520 	options = o = kstrdup(buf, GFP_KERNEL);
1521 	if (!options)
1522 		return -ENOMEM;
1523 
1524 	/* Parse the options, doing only some light invalid value checks. */
1525 	while ((p = strsep(&o, ",\n")) != NULL) {
1526 		if (!*p)
1527 			continue;
1528 
1529 		token = match_token(p, zloop_opt_tokens, args);
1530 		opts->mask |= token;
1531 		switch (token) {
1532 		case ZLOOP_OPT_ID:
1533 			if (match_int(args, &opts->id)) {
1534 				ret = -EINVAL;
1535 				goto out;
1536 			}
1537 			break;
1538 		case ZLOOP_OPT_CAPACITY:
1539 			if (match_uint(args, &token)) {
1540 				ret = -EINVAL;
1541 				goto out;
1542 			}
1543 			if (!token) {
1544 				pr_err("Invalid capacity\n");
1545 				ret = -EINVAL;
1546 				goto out;
1547 			}
1548 			opts->capacity =
1549 				((sector_t)token * SZ_1M) >> SECTOR_SHIFT;
1550 			break;
1551 		case ZLOOP_OPT_ZONE_SIZE:
1552 			if (match_uint(args, &token)) {
1553 				ret = -EINVAL;
1554 				goto out;
1555 			}
1556 			if (!token || token > ZLOOP_MAX_ZONE_SIZE_MB ||
1557 			    !is_power_of_2(token)) {
1558 				pr_err("Invalid zone size %u\n", token);
1559 				ret = -EINVAL;
1560 				goto out;
1561 			}
1562 			opts->zone_size =
1563 				((sector_t)token * SZ_1M) >> SECTOR_SHIFT;
1564 			break;
1565 		case ZLOOP_OPT_ZONE_CAPACITY:
1566 			if (match_uint(args, &token)) {
1567 				ret = -EINVAL;
1568 				goto out;
1569 			}
1570 			if (!token) {
1571 				pr_err("Invalid zone capacity\n");
1572 				ret = -EINVAL;
1573 				goto out;
1574 			}
1575 			opts->zone_capacity =
1576 				((sector_t)token * SZ_1M) >> SECTOR_SHIFT;
1577 			break;
1578 		case ZLOOP_OPT_NR_CONV_ZONES:
1579 			if (match_uint(args, &token)) {
1580 				ret = -EINVAL;
1581 				goto out;
1582 			}
1583 			opts->nr_conv_zones = token;
1584 			break;
1585 		case ZLOOP_OPT_MAX_OPEN_ZONES:
1586 			if (match_uint(args, &token)) {
1587 				ret = -EINVAL;
1588 				goto out;
1589 			}
1590 			opts->max_open_zones = token;
1591 			break;
1592 		case ZLOOP_OPT_BASE_DIR:
1593 			p = match_strdup(args);
1594 			if (!p) {
1595 				ret = -ENOMEM;
1596 				goto out;
1597 			}
1598 			kfree(opts->base_dir);
1599 			opts->base_dir = p;
1600 			break;
1601 		case ZLOOP_OPT_NR_QUEUES:
1602 			if (match_uint(args, &token)) {
1603 				ret = -EINVAL;
1604 				goto out;
1605 			}
1606 			if (!token) {
1607 				pr_err("Invalid number of queues\n");
1608 				ret = -EINVAL;
1609 				goto out;
1610 			}
1611 			opts->nr_queues = min(token, num_online_cpus());
1612 			break;
1613 		case ZLOOP_OPT_QUEUE_DEPTH:
1614 			if (match_uint(args, &token)) {
1615 				ret = -EINVAL;
1616 				goto out;
1617 			}
1618 			if (!token) {
1619 				pr_err("Invalid queue depth\n");
1620 				ret = -EINVAL;
1621 				goto out;
1622 			}
1623 			opts->queue_depth = token;
1624 			break;
1625 		case ZLOOP_OPT_BUFFERED_IO:
1626 			opts->buffered_io = true;
1627 			break;
1628 		case ZLOOP_OPT_ZONE_APPEND:
1629 			if (match_uint(args, &token)) {
1630 				ret = -EINVAL;
1631 				goto out;
1632 			}
1633 			if (token != 0 && token != 1) {
1634 				pr_err("Invalid zone_append value\n");
1635 				ret = -EINVAL;
1636 				goto out;
1637 			}
1638 			opts->zone_append = token;
1639 			break;
1640 		case ZLOOP_OPT_ORDERED_ZONE_APPEND:
1641 			opts->ordered_zone_append = true;
1642 			break;
1643 		case ZLOOP_OPT_DISCARD_WRITE_CACHE:
1644 			opts->discard_write_cache = true;
1645 			break;
1646 		case ZLOOP_OPT_ERR:
1647 		default:
1648 			pr_warn("unknown parameter or missing value '%s'\n", p);
1649 			ret = -EINVAL;
1650 			goto out;
1651 		}
1652 	}
1653 
1654 	ret = -EINVAL;
1655 	if (opts->capacity <= opts->zone_size) {
1656 		pr_err("Invalid capacity\n");
1657 		goto out;
1658 	}
1659 
1660 	if (opts->zone_capacity > opts->zone_size) {
1661 		pr_err("Invalid zone capacity\n");
1662 		goto out;
1663 	}
1664 
1665 	ret = 0;
1666 out:
1667 	kfree(options);
1668 	return ret;
1669 }
1670 
1671 enum {
1672 	ZLOOP_CTL_ADD,
1673 	ZLOOP_CTL_REMOVE,
1674 };
1675 
1676 static struct zloop_ctl_op {
1677 	int		code;
1678 	const char	*name;
1679 } zloop_ctl_ops[] = {
1680 	{ ZLOOP_CTL_ADD,	"add" },
1681 	{ ZLOOP_CTL_REMOVE,	"remove" },
1682 	{ -1,	NULL },
1683 };
1684 
1685 static ssize_t zloop_ctl_write(struct file *file, const char __user *ubuf,
1686 			       size_t count, loff_t *pos)
1687 {
1688 	struct zloop_options opts = { };
1689 	struct zloop_ctl_op *op;
1690 	const char *buf, *opts_buf;
1691 	int i, ret;
1692 
1693 	if (count > PAGE_SIZE)
1694 		return -ENOMEM;
1695 
1696 	buf = memdup_user_nul(ubuf, count);
1697 	if (IS_ERR(buf))
1698 		return PTR_ERR(buf);
1699 
1700 	for (i = 0; i < ARRAY_SIZE(zloop_ctl_ops); i++) {
1701 		op = &zloop_ctl_ops[i];
1702 		if (!op->name) {
1703 			pr_err("Invalid operation\n");
1704 			ret = -EINVAL;
1705 			goto out;
1706 		}
1707 		if (!strncmp(buf, op->name, strlen(op->name)))
1708 			break;
1709 	}
1710 
1711 	if (count <= strlen(op->name))
1712 		opts_buf = NULL;
1713 	else
1714 		opts_buf = buf + strlen(op->name);
1715 
1716 	ret = zloop_parse_options(&opts, opts_buf);
1717 	if (ret) {
1718 		pr_err("Failed to parse options\n");
1719 		goto out;
1720 	}
1721 
1722 	switch (op->code) {
1723 	case ZLOOP_CTL_ADD:
1724 		ret = zloop_ctl_add(&opts);
1725 		break;
1726 	case ZLOOP_CTL_REMOVE:
1727 		ret = zloop_ctl_remove(&opts);
1728 		break;
1729 	default:
1730 		pr_err("Invalid operation\n");
1731 		ret = -EINVAL;
1732 		goto out;
1733 	}
1734 
1735 out:
1736 	kfree(opts.base_dir);
1737 	kfree(buf);
1738 	return ret ? ret : count;
1739 }
1740 
1741 static int zloop_ctl_show(struct seq_file *seq_file, void *private)
1742 {
1743 	const struct match_token *tok;
1744 	int i;
1745 
1746 	/* Add operation */
1747 	seq_printf(seq_file, "%s ", zloop_ctl_ops[0].name);
1748 	for (i = 0; i < ARRAY_SIZE(zloop_opt_tokens); i++) {
1749 		tok = &zloop_opt_tokens[i];
1750 		if (!tok->pattern)
1751 			break;
1752 		if (i)
1753 			seq_putc(seq_file, ',');
1754 		seq_puts(seq_file, tok->pattern);
1755 	}
1756 	seq_putc(seq_file, '\n');
1757 
1758 	/* Remove operation */
1759 	seq_puts(seq_file, zloop_ctl_ops[1].name);
1760 	seq_puts(seq_file, " id=%d\n");
1761 
1762 	return 0;
1763 }
1764 
1765 static int zloop_ctl_open(struct inode *inode, struct file *file)
1766 {
1767 	file->private_data = NULL;
1768 	return single_open(file, zloop_ctl_show, NULL);
1769 }
1770 
1771 static int zloop_ctl_release(struct inode *inode, struct file *file)
1772 {
1773 	return single_release(inode, file);
1774 }
1775 
1776 static const struct file_operations zloop_ctl_fops = {
1777 	.owner		= THIS_MODULE,
1778 	.open		= zloop_ctl_open,
1779 	.release	= zloop_ctl_release,
1780 	.write		= zloop_ctl_write,
1781 	.read		= seq_read,
1782 };
1783 
1784 static struct miscdevice zloop_misc = {
1785 	.minor		= MISC_DYNAMIC_MINOR,
1786 	.name		= "zloop-control",
1787 	.fops		= &zloop_ctl_fops,
1788 };
1789 
1790 static int __init zloop_init(void)
1791 {
1792 	int ret;
1793 
1794 	ret = misc_register(&zloop_misc);
1795 	if (ret) {
1796 		pr_err("Failed to register misc device: %d\n", ret);
1797 		return ret;
1798 	}
1799 	pr_info("Module loaded\n");
1800 
1801 	return 0;
1802 }
1803 
1804 static void __exit zloop_exit(void)
1805 {
1806 	misc_deregister(&zloop_misc);
1807 	idr_destroy(&zloop_index_idr);
1808 }
1809 
1810 module_init(zloop_init);
1811 module_exit(zloop_exit);
1812 
1813 MODULE_DESCRIPTION("Zoned loopback device");
1814 MODULE_LICENSE("GPL");
1815