• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Zoned block device handling
4  *
5  * Copyright (c) 2015, Hannes Reinecke
6  * Copyright (c) 2015, SUSE Linux GmbH
7  *
8  * Copyright (c) 2016, Damien Le Moal
9  * Copyright (c) 2016, Western Digital
10  * Copyright (c) 2024, Western Digital Corporation or its affiliates.
11  */
12 
13 #include <linux/kernel.h>
14 #include <linux/module.h>
15 #include <linux/blkdev.h>
16 #include <linux/blk-mq.h>
17 #include <linux/mm.h>
18 #include <linux/vmalloc.h>
19 #include <linux/sched/mm.h>
20 #include <linux/spinlock.h>
21 #include <linux/refcount.h>
22 #include <linux/mempool.h>
23 
24 #include <trace/events/block.h>
25 
26 #include "blk.h"
27 #include "blk-mq-sched.h"
28 #include "blk-mq-debugfs.h"
29 
30 ANDROID_KABI_DECLONLY(poll_table_struct);
31 ANDROID_KABI_DECLONLY(pollfd);
32 ANDROID_KABI_DECLONLY(readahead_control);
33 ANDROID_KABI_DECLONLY(trace_eval_map);
34 ANDROID_KABI_DECLONLY(wait_page_queue);
35 
36 #define ZONE_COND_NAME(name) [BLK_ZONE_COND_##name] = #name
37 static const char *const zone_cond_name[] = {
38 	ZONE_COND_NAME(NOT_WP),
39 	ZONE_COND_NAME(EMPTY),
40 	ZONE_COND_NAME(IMP_OPEN),
41 	ZONE_COND_NAME(EXP_OPEN),
42 	ZONE_COND_NAME(CLOSED),
43 	ZONE_COND_NAME(READONLY),
44 	ZONE_COND_NAME(FULL),
45 	ZONE_COND_NAME(OFFLINE),
46 };
47 #undef ZONE_COND_NAME
48 
49 /*
50  * Per-zone write plug.
51  * @node: hlist_node structure for managing the plug using a hash table.
52  * @ref: Zone write plug reference counter. A zone write plug reference is
53  *       always at least 1 when the plug is hashed in the disk plug hash table.
54  *       The reference is incremented whenever a new BIO needing plugging is
55  *       submitted and when a function needs to manipulate a plug. The
56  *       reference count is decremented whenever a plugged BIO completes and
57  *       when a function that referenced the plug returns. The initial
58  *       reference is dropped whenever the zone of the zone write plug is reset,
59  *       finished and when the zone becomes full (last write BIO to the zone
60  *       completes).
61  * @lock: Spinlock to atomically manipulate the plug.
62  * @flags: Flags indicating the plug state.
63  * @zone_no: The number of the zone the plug is managing.
64  * @wp_offset: The zone write pointer location relative to the start of the zone
65  *             as a number of 512B sectors.
66  * @bio_list: The list of BIOs that are currently plugged.
67  * @bio_work: Work struct to handle issuing of plugged BIOs
68  * @rcu_head: RCU head to free zone write plugs with an RCU grace period.
69  * @disk: The gendisk the plug belongs to.
70  */
71 struct blk_zone_wplug {
72 	struct hlist_node	node;
73 	refcount_t		ref;
74 	spinlock_t		lock;
75 	unsigned int		flags;
76 	unsigned int		zone_no;
77 	unsigned int		wp_offset;
78 	struct bio_list		bio_list;
79 	struct work_struct	bio_work;
80 	struct rcu_head		rcu_head;
81 	struct gendisk		*disk;
82 };
83 
84 /*
85  * Zone write plug flags bits:
86  *  - BLK_ZONE_WPLUG_PLUGGED: Indicates that the zone write plug is plugged,
87  *    that is, that write BIOs are being throttled due to a write BIO already
88  *    being executed or the zone write plug bio list is not empty.
89  *  - BLK_ZONE_WPLUG_NEED_WP_UPDATE: Indicates that we lost track of a zone
90  *    write pointer offset and need to update it.
91  *  - BLK_ZONE_WPLUG_UNHASHED: Indicates that the zone write plug was removed
92  *    from the disk hash table and that the initial reference to the zone
93  *    write plug set when the plug was first added to the hash table has been
94  *    dropped. This flag is set when a zone is reset, finished or become full,
95  *    to prevent new references to the zone write plug to be taken for
96  *    newly incoming BIOs. A zone write plug flagged with this flag will be
97  *    freed once all remaining references from BIOs or functions are dropped.
98  */
99 #define BLK_ZONE_WPLUG_PLUGGED		(1U << 0)
100 #define BLK_ZONE_WPLUG_NEED_WP_UPDATE	(1U << 1)
101 #define BLK_ZONE_WPLUG_UNHASHED		(1U << 2)
102 
103 /**
104  * blk_zone_cond_str - Return string XXX in BLK_ZONE_COND_XXX.
105  * @zone_cond: BLK_ZONE_COND_XXX.
106  *
107  * Description: Centralize block layer function to convert BLK_ZONE_COND_XXX
108  * into string format. Useful in the debugging and tracing zone conditions. For
109  * invalid BLK_ZONE_COND_XXX it returns string "UNKNOWN".
110  */
blk_zone_cond_str(enum blk_zone_cond zone_cond)111 const char *blk_zone_cond_str(enum blk_zone_cond zone_cond)
112 {
113 	static const char *zone_cond_str = "UNKNOWN";
114 
115 	if (zone_cond < ARRAY_SIZE(zone_cond_name) && zone_cond_name[zone_cond])
116 		zone_cond_str = zone_cond_name[zone_cond];
117 
118 	return zone_cond_str;
119 }
120 EXPORT_SYMBOL_GPL(blk_zone_cond_str);
121 
122 struct disk_report_zones_cb_args {
123 	struct gendisk	*disk;
124 	report_zones_cb	user_cb;
125 	void		*user_data;
126 };
127 
128 static void disk_zone_wplug_sync_wp_offset(struct gendisk *disk,
129 					   struct blk_zone *zone);
130 
disk_report_zones_cb(struct blk_zone * zone,unsigned int idx,void * data)131 static int disk_report_zones_cb(struct blk_zone *zone, unsigned int idx,
132 				void *data)
133 {
134 	struct disk_report_zones_cb_args *args = data;
135 	struct gendisk *disk = args->disk;
136 
137 	if (disk->zone_wplugs_hash)
138 		disk_zone_wplug_sync_wp_offset(disk, zone);
139 
140 	if (!args->user_cb)
141 		return 0;
142 
143 	return args->user_cb(zone, idx, args->user_data);
144 }
145 
146 /**
147  * blkdev_report_zones - Get zones information
148  * @bdev:	Target block device
149  * @sector:	Sector from which to report zones
150  * @nr_zones:	Maximum number of zones to report
151  * @cb:		Callback function called for each reported zone
152  * @data:	Private data for the callback
153  *
154  * Description:
155  *    Get zone information starting from the zone containing @sector for at most
156  *    @nr_zones, and call @cb for each zone reported by the device.
157  *    To report all zones in a device starting from @sector, the BLK_ALL_ZONES
158  *    constant can be passed to @nr_zones.
159  *    Returns the number of zones reported by the device, or a negative errno
160  *    value in case of failure.
161  *
162  *    Note: The caller must use memalloc_noXX_save/restore() calls to control
163  *    memory allocations done within this function.
164  */
blkdev_report_zones(struct block_device * bdev,sector_t sector,unsigned int nr_zones,report_zones_cb cb,void * data)165 int blkdev_report_zones(struct block_device *bdev, sector_t sector,
166 			unsigned int nr_zones, report_zones_cb cb, void *data)
167 {
168 	struct gendisk *disk = bdev->bd_disk;
169 	sector_t capacity = get_capacity(disk);
170 	struct disk_report_zones_cb_args args = {
171 		.disk = disk,
172 		.user_cb = cb,
173 		.user_data = data,
174 	};
175 
176 	if (!bdev_is_zoned(bdev) || WARN_ON_ONCE(!disk->fops->report_zones))
177 		return -EOPNOTSUPP;
178 
179 	if (!nr_zones || sector >= capacity)
180 		return 0;
181 
182 	return disk->fops->report_zones(disk, sector, nr_zones,
183 					disk_report_zones_cb, &args);
184 }
185 EXPORT_SYMBOL_GPL(blkdev_report_zones);
186 
blkdev_zone_reset_all(struct block_device * bdev)187 static int blkdev_zone_reset_all(struct block_device *bdev)
188 {
189 	struct bio bio;
190 
191 	bio_init(&bio, bdev, NULL, 0, REQ_OP_ZONE_RESET_ALL | REQ_SYNC);
192 	trace_blkdev_zone_mgmt(&bio, 0);
193 	return submit_bio_wait(&bio);
194 }
195 
196 /**
197  * blkdev_zone_mgmt - Execute a zone management operation on a range of zones
198  * @bdev:	Target block device
199  * @op:		Operation to be performed on the zones
200  * @sector:	Start sector of the first zone to operate on
201  * @nr_sectors:	Number of sectors, should be at least the length of one zone and
202  *		must be zone size aligned.
203  *
204  * Description:
205  *    Perform the specified operation on the range of zones specified by
206  *    @sector..@sector+@nr_sectors. Specifying the entire disk sector range
207  *    is valid, but the specified range should not contain conventional zones.
208  *    The operation to execute on each zone can be a zone reset, open, close
209  *    or finish request.
210  */
blkdev_zone_mgmt(struct block_device * bdev,enum req_op op,sector_t sector,sector_t nr_sectors)211 int blkdev_zone_mgmt(struct block_device *bdev, enum req_op op,
212 		     sector_t sector, sector_t nr_sectors)
213 {
214 	sector_t zone_sectors = bdev_zone_sectors(bdev);
215 	sector_t capacity = bdev_nr_sectors(bdev);
216 	sector_t end_sector = sector + nr_sectors;
217 	struct bio *bio = NULL;
218 	int ret = 0;
219 
220 	if (!bdev_is_zoned(bdev))
221 		return -EOPNOTSUPP;
222 
223 	if (bdev_read_only(bdev))
224 		return -EPERM;
225 
226 	if (!op_is_zone_mgmt(op))
227 		return -EOPNOTSUPP;
228 
229 	if (end_sector <= sector || end_sector > capacity)
230 		/* Out of range */
231 		return -EINVAL;
232 
233 	/* Check alignment (handle eventual smaller last zone) */
234 	if (!bdev_is_zone_start(bdev, sector))
235 		return -EINVAL;
236 
237 	if (!bdev_is_zone_start(bdev, nr_sectors) && end_sector != capacity)
238 		return -EINVAL;
239 
240 	/*
241 	 * In the case of a zone reset operation over all zones, use
242 	 * REQ_OP_ZONE_RESET_ALL.
243 	 */
244 	if (op == REQ_OP_ZONE_RESET && sector == 0 && nr_sectors == capacity)
245 		return blkdev_zone_reset_all(bdev);
246 
247 	while (sector < end_sector) {
248 		bio = blk_next_bio(bio, bdev, 0, op | REQ_SYNC, GFP_KERNEL);
249 		bio->bi_iter.bi_sector = sector;
250 		sector += zone_sectors;
251 
252 		/* This may take a while, so be nice to others */
253 		cond_resched();
254 	}
255 
256 	trace_blkdev_zone_mgmt(bio, nr_sectors);
257 	ret = submit_bio_wait(bio);
258 	bio_put(bio);
259 
260 	return ret;
261 }
262 EXPORT_SYMBOL_GPL(blkdev_zone_mgmt);
263 
264 struct zone_report_args {
265 	struct blk_zone __user *zones;
266 };
267 
blkdev_copy_zone_to_user(struct blk_zone * zone,unsigned int idx,void * data)268 static int blkdev_copy_zone_to_user(struct blk_zone *zone, unsigned int idx,
269 				    void *data)
270 {
271 	struct zone_report_args *args = data;
272 
273 	if (copy_to_user(&args->zones[idx], zone, sizeof(struct blk_zone)))
274 		return -EFAULT;
275 	return 0;
276 }
277 
278 /*
279  * BLKREPORTZONE ioctl processing.
280  * Called from blkdev_ioctl.
281  */
blkdev_report_zones_ioctl(struct block_device * bdev,unsigned int cmd,unsigned long arg)282 int blkdev_report_zones_ioctl(struct block_device *bdev, unsigned int cmd,
283 		unsigned long arg)
284 {
285 	void __user *argp = (void __user *)arg;
286 	struct zone_report_args args;
287 	struct blk_zone_report rep;
288 	int ret;
289 
290 	if (!argp)
291 		return -EINVAL;
292 
293 	if (!bdev_is_zoned(bdev))
294 		return -ENOTTY;
295 
296 	if (copy_from_user(&rep, argp, sizeof(struct blk_zone_report)))
297 		return -EFAULT;
298 
299 	if (!rep.nr_zones)
300 		return -EINVAL;
301 
302 	args.zones = argp + sizeof(struct blk_zone_report);
303 	ret = blkdev_report_zones(bdev, rep.sector, rep.nr_zones,
304 				  blkdev_copy_zone_to_user, &args);
305 	if (ret < 0)
306 		return ret;
307 
308 	rep.nr_zones = ret;
309 	rep.flags = BLK_ZONE_REP_CAPACITY;
310 	if (copy_to_user(argp, &rep, sizeof(struct blk_zone_report)))
311 		return -EFAULT;
312 	return 0;
313 }
314 
blkdev_truncate_zone_range(struct block_device * bdev,blk_mode_t mode,const struct blk_zone_range * zrange)315 static int blkdev_truncate_zone_range(struct block_device *bdev,
316 		blk_mode_t mode, const struct blk_zone_range *zrange)
317 {
318 	loff_t start, end;
319 
320 	if (zrange->sector + zrange->nr_sectors <= zrange->sector ||
321 	    zrange->sector + zrange->nr_sectors > get_capacity(bdev->bd_disk))
322 		/* Out of range */
323 		return -EINVAL;
324 
325 	start = zrange->sector << SECTOR_SHIFT;
326 	end = ((zrange->sector + zrange->nr_sectors) << SECTOR_SHIFT) - 1;
327 
328 	return truncate_bdev_range(bdev, mode, start, end);
329 }
330 
331 /*
332  * BLKRESETZONE, BLKOPENZONE, BLKCLOSEZONE and BLKFINISHZONE ioctl processing.
333  * Called from blkdev_ioctl.
334  */
blkdev_zone_mgmt_ioctl(struct block_device * bdev,blk_mode_t mode,unsigned int cmd,unsigned long arg)335 int blkdev_zone_mgmt_ioctl(struct block_device *bdev, blk_mode_t mode,
336 			   unsigned int cmd, unsigned long arg)
337 {
338 	void __user *argp = (void __user *)arg;
339 	struct blk_zone_range zrange;
340 	enum req_op op;
341 	int ret;
342 
343 	if (!argp)
344 		return -EINVAL;
345 
346 	if (!bdev_is_zoned(bdev))
347 		return -ENOTTY;
348 
349 	if (!(mode & BLK_OPEN_WRITE))
350 		return -EBADF;
351 
352 	if (copy_from_user(&zrange, argp, sizeof(struct blk_zone_range)))
353 		return -EFAULT;
354 
355 	switch (cmd) {
356 	case BLKRESETZONE:
357 		op = REQ_OP_ZONE_RESET;
358 
359 		/* Invalidate the page cache, including dirty pages. */
360 		inode_lock(bdev->bd_mapping->host);
361 		filemap_invalidate_lock(bdev->bd_mapping);
362 		ret = blkdev_truncate_zone_range(bdev, mode, &zrange);
363 		if (ret)
364 			goto fail;
365 		break;
366 	case BLKOPENZONE:
367 		op = REQ_OP_ZONE_OPEN;
368 		break;
369 	case BLKCLOSEZONE:
370 		op = REQ_OP_ZONE_CLOSE;
371 		break;
372 	case BLKFINISHZONE:
373 		op = REQ_OP_ZONE_FINISH;
374 		break;
375 	default:
376 		return -ENOTTY;
377 	}
378 
379 	ret = blkdev_zone_mgmt(bdev, op, zrange.sector, zrange.nr_sectors);
380 
381 fail:
382 	if (cmd == BLKRESETZONE) {
383 		filemap_invalidate_unlock(bdev->bd_mapping);
384 		inode_unlock(bdev->bd_mapping->host);
385 	}
386 
387 	return ret;
388 }
389 
disk_zone_is_last(struct gendisk * disk,struct blk_zone * zone)390 static bool disk_zone_is_last(struct gendisk *disk, struct blk_zone *zone)
391 {
392 	return zone->start + zone->len >= get_capacity(disk);
393 }
394 
disk_zone_is_full(struct gendisk * disk,unsigned int zno,unsigned int offset_in_zone)395 static bool disk_zone_is_full(struct gendisk *disk,
396 			      unsigned int zno, unsigned int offset_in_zone)
397 {
398 	if (zno < disk->nr_zones - 1)
399 		return offset_in_zone >= disk->zone_capacity;
400 	return offset_in_zone >= disk->last_zone_capacity;
401 }
402 
disk_zone_wplug_is_full(struct gendisk * disk,struct blk_zone_wplug * zwplug)403 static bool disk_zone_wplug_is_full(struct gendisk *disk,
404 				    struct blk_zone_wplug *zwplug)
405 {
406 	return disk_zone_is_full(disk, zwplug->zone_no, zwplug->wp_offset);
407 }
408 
disk_insert_zone_wplug(struct gendisk * disk,struct blk_zone_wplug * zwplug)409 static bool disk_insert_zone_wplug(struct gendisk *disk,
410 				   struct blk_zone_wplug *zwplug)
411 {
412 	struct blk_zone_wplug *zwplg;
413 	unsigned long flags;
414 	unsigned int idx =
415 		hash_32(zwplug->zone_no, disk->zone_wplugs_hash_bits);
416 
417 	/*
418 	 * Add the new zone write plug to the hash table, but carefully as we
419 	 * are racing with other submission context, so we may already have a
420 	 * zone write plug for the same zone.
421 	 */
422 	spin_lock_irqsave(&disk->zone_wplugs_lock, flags);
423 	hlist_for_each_entry_rcu(zwplg, &disk->zone_wplugs_hash[idx], node) {
424 		if (zwplg->zone_no == zwplug->zone_no) {
425 			spin_unlock_irqrestore(&disk->zone_wplugs_lock, flags);
426 			return false;
427 		}
428 	}
429 	hlist_add_head_rcu(&zwplug->node, &disk->zone_wplugs_hash[idx]);
430 	atomic_inc(&disk->nr_zone_wplugs);
431 	spin_unlock_irqrestore(&disk->zone_wplugs_lock, flags);
432 
433 	return true;
434 }
435 
disk_get_hashed_zone_wplug(struct gendisk * disk,sector_t sector)436 static struct blk_zone_wplug *disk_get_hashed_zone_wplug(struct gendisk *disk,
437 							 sector_t sector)
438 {
439 	unsigned int zno = disk_zone_no(disk, sector);
440 	unsigned int idx = hash_32(zno, disk->zone_wplugs_hash_bits);
441 	struct blk_zone_wplug *zwplug;
442 
443 	rcu_read_lock();
444 
445 	hlist_for_each_entry_rcu(zwplug, &disk->zone_wplugs_hash[idx], node) {
446 		if (zwplug->zone_no == zno &&
447 		    refcount_inc_not_zero(&zwplug->ref)) {
448 			rcu_read_unlock();
449 			return zwplug;
450 		}
451 	}
452 
453 	rcu_read_unlock();
454 
455 	return NULL;
456 }
457 
disk_get_zone_wplug(struct gendisk * disk,sector_t sector)458 static inline struct blk_zone_wplug *disk_get_zone_wplug(struct gendisk *disk,
459 							 sector_t sector)
460 {
461 	if (!atomic_read(&disk->nr_zone_wplugs))
462 		return NULL;
463 
464 	return disk_get_hashed_zone_wplug(disk, sector);
465 }
466 
disk_free_zone_wplug_rcu(struct rcu_head * rcu_head)467 static void disk_free_zone_wplug_rcu(struct rcu_head *rcu_head)
468 {
469 	struct blk_zone_wplug *zwplug =
470 		container_of(rcu_head, struct blk_zone_wplug, rcu_head);
471 
472 	mempool_free(zwplug, zwplug->disk->zone_wplugs_pool);
473 }
474 
disk_put_zone_wplug(struct blk_zone_wplug * zwplug)475 static inline void disk_put_zone_wplug(struct blk_zone_wplug *zwplug)
476 {
477 	if (refcount_dec_and_test(&zwplug->ref)) {
478 		WARN_ON_ONCE(!bio_list_empty(&zwplug->bio_list));
479 		WARN_ON_ONCE(zwplug->flags & BLK_ZONE_WPLUG_PLUGGED);
480 		WARN_ON_ONCE(!(zwplug->flags & BLK_ZONE_WPLUG_UNHASHED));
481 
482 		call_rcu(&zwplug->rcu_head, disk_free_zone_wplug_rcu);
483 	}
484 }
485 
disk_should_remove_zone_wplug(struct gendisk * disk,struct blk_zone_wplug * zwplug)486 static inline bool disk_should_remove_zone_wplug(struct gendisk *disk,
487 						 struct blk_zone_wplug *zwplug)
488 {
489 	/* If the zone write plug was already removed, we are done. */
490 	if (zwplug->flags & BLK_ZONE_WPLUG_UNHASHED)
491 		return false;
492 
493 	/* If the zone write plug is still plugged, it cannot be removed. */
494 	if (zwplug->flags & BLK_ZONE_WPLUG_PLUGGED)
495 		return false;
496 
497 	/*
498 	 * Completions of BIOs with blk_zone_write_plug_bio_endio() may
499 	 * happen after handling a request completion with
500 	 * blk_zone_write_plug_finish_request() (e.g. with split BIOs
501 	 * that are chained). In such case, disk_zone_wplug_unplug_bio()
502 	 * should not attempt to remove the zone write plug until all BIO
503 	 * completions are seen. Check by looking at the zone write plug
504 	 * reference count, which is 2 when the plug is unused (one reference
505 	 * taken when the plug was allocated and another reference taken by the
506 	 * caller context).
507 	 */
508 	if (refcount_read(&zwplug->ref) > 2)
509 		return false;
510 
511 	/* We can remove zone write plugs for zones that are empty or full. */
512 	return !zwplug->wp_offset || disk_zone_wplug_is_full(disk, zwplug);
513 }
514 
disk_remove_zone_wplug(struct gendisk * disk,struct blk_zone_wplug * zwplug)515 static void disk_remove_zone_wplug(struct gendisk *disk,
516 				   struct blk_zone_wplug *zwplug)
517 {
518 	unsigned long flags;
519 
520 	/* If the zone write plug was already removed, we have nothing to do. */
521 	if (zwplug->flags & BLK_ZONE_WPLUG_UNHASHED)
522 		return;
523 
524 	/*
525 	 * Mark the zone write plug as unhashed and drop the extra reference we
526 	 * took when the plug was inserted in the hash table.
527 	 */
528 	zwplug->flags |= BLK_ZONE_WPLUG_UNHASHED;
529 	spin_lock_irqsave(&disk->zone_wplugs_lock, flags);
530 	hlist_del_init_rcu(&zwplug->node);
531 	atomic_dec(&disk->nr_zone_wplugs);
532 	spin_unlock_irqrestore(&disk->zone_wplugs_lock, flags);
533 	disk_put_zone_wplug(zwplug);
534 }
535 
536 static void blk_zone_wplug_bio_work(struct work_struct *work);
537 
538 /*
539  * Get a reference on the write plug for the zone containing @sector.
540  * If the plug does not exist, it is allocated and hashed.
541  * Return a pointer to the zone write plug with the plug spinlock held.
542  */
disk_get_and_lock_zone_wplug(struct gendisk * disk,sector_t sector,gfp_t gfp_mask,unsigned long * flags)543 static struct blk_zone_wplug *disk_get_and_lock_zone_wplug(struct gendisk *disk,
544 					sector_t sector, gfp_t gfp_mask,
545 					unsigned long *flags)
546 {
547 	unsigned int zno = disk_zone_no(disk, sector);
548 	struct blk_zone_wplug *zwplug;
549 
550 again:
551 	zwplug = disk_get_zone_wplug(disk, sector);
552 	if (zwplug) {
553 		/*
554 		 * Check that a BIO completion or a zone reset or finish
555 		 * operation has not already removed the zone write plug from
556 		 * the hash table and dropped its reference count. In such case,
557 		 * we need to get a new plug so start over from the beginning.
558 		 */
559 		spin_lock_irqsave(&zwplug->lock, *flags);
560 		if (zwplug->flags & BLK_ZONE_WPLUG_UNHASHED) {
561 			spin_unlock_irqrestore(&zwplug->lock, *flags);
562 			disk_put_zone_wplug(zwplug);
563 			goto again;
564 		}
565 		return zwplug;
566 	}
567 
568 	/*
569 	 * Allocate and initialize a zone write plug with an extra reference
570 	 * so that it is not freed when the zone write plug becomes idle without
571 	 * the zone being full.
572 	 */
573 	zwplug = mempool_alloc(disk->zone_wplugs_pool, gfp_mask);
574 	if (!zwplug)
575 		return NULL;
576 
577 	INIT_HLIST_NODE(&zwplug->node);
578 	refcount_set(&zwplug->ref, 2);
579 	spin_lock_init(&zwplug->lock);
580 	zwplug->flags = 0;
581 	zwplug->zone_no = zno;
582 	zwplug->wp_offset = bdev_offset_from_zone_start(disk->part0, sector);
583 	bio_list_init(&zwplug->bio_list);
584 	INIT_WORK(&zwplug->bio_work, blk_zone_wplug_bio_work);
585 	zwplug->disk = disk;
586 
587 	spin_lock_irqsave(&zwplug->lock, *flags);
588 
589 	/*
590 	 * Insert the new zone write plug in the hash table. This can fail only
591 	 * if another context already inserted a plug. Retry from the beginning
592 	 * in such case.
593 	 */
594 	if (!disk_insert_zone_wplug(disk, zwplug)) {
595 		spin_unlock_irqrestore(&zwplug->lock, *flags);
596 		mempool_free(zwplug, disk->zone_wplugs_pool);
597 		goto again;
598 	}
599 
600 	return zwplug;
601 }
602 
blk_zone_wplug_bio_io_error(struct blk_zone_wplug * zwplug,struct bio * bio)603 static inline void blk_zone_wplug_bio_io_error(struct blk_zone_wplug *zwplug,
604 					       struct bio *bio)
605 {
606 	struct request_queue *q = zwplug->disk->queue;
607 
608 	bio_clear_flag(bio, BIO_ZONE_WRITE_PLUGGING);
609 	bio_io_error(bio);
610 	disk_put_zone_wplug(zwplug);
611 	blk_queue_exit(q);
612 }
613 
614 /*
615  * Abort (fail) all plugged BIOs of a zone write plug.
616  */
disk_zone_wplug_abort(struct blk_zone_wplug * zwplug)617 static void disk_zone_wplug_abort(struct blk_zone_wplug *zwplug)
618 {
619 	struct bio *bio;
620 
621 	if (bio_list_empty(&zwplug->bio_list))
622 		return;
623 
624 	pr_warn_ratelimited("%s: zone %u: Aborting plugged BIOs\n",
625 			    zwplug->disk->disk_name, zwplug->zone_no);
626 	while ((bio = bio_list_pop(&zwplug->bio_list)))
627 		blk_zone_wplug_bio_io_error(zwplug, bio);
628 }
629 
630 /*
631  * Set a zone write plug write pointer offset to the specified value.
632  * This aborts all plugged BIOs, which is fine as this function is called for
633  * a zone reset operation, a zone finish operation or if the zone needs a wp
634  * update from a report zone after a write error.
635  */
disk_zone_wplug_set_wp_offset(struct gendisk * disk,struct blk_zone_wplug * zwplug,unsigned int wp_offset)636 static void disk_zone_wplug_set_wp_offset(struct gendisk *disk,
637 					  struct blk_zone_wplug *zwplug,
638 					  unsigned int wp_offset)
639 {
640 	lockdep_assert_held(&zwplug->lock);
641 
642 	/* Update the zone write pointer and abort all plugged BIOs. */
643 	zwplug->flags &= ~BLK_ZONE_WPLUG_NEED_WP_UPDATE;
644 	zwplug->wp_offset = wp_offset;
645 	disk_zone_wplug_abort(zwplug);
646 
647 	/*
648 	 * The zone write plug now has no BIO plugged: remove it from the
649 	 * hash table so that it cannot be seen. The plug will be freed
650 	 * when the last reference is dropped.
651 	 */
652 	if (disk_should_remove_zone_wplug(disk, zwplug))
653 		disk_remove_zone_wplug(disk, zwplug);
654 }
655 
blk_zone_wp_offset(struct blk_zone * zone)656 static unsigned int blk_zone_wp_offset(struct blk_zone *zone)
657 {
658 	switch (zone->cond) {
659 	case BLK_ZONE_COND_IMP_OPEN:
660 	case BLK_ZONE_COND_EXP_OPEN:
661 	case BLK_ZONE_COND_CLOSED:
662 		return zone->wp - zone->start;
663 	case BLK_ZONE_COND_FULL:
664 		return zone->len;
665 	case BLK_ZONE_COND_EMPTY:
666 		return 0;
667 	case BLK_ZONE_COND_NOT_WP:
668 	case BLK_ZONE_COND_OFFLINE:
669 	case BLK_ZONE_COND_READONLY:
670 	default:
671 		/*
672 		 * Conventional, offline and read-only zones do not have a valid
673 		 * write pointer.
674 		 */
675 		return UINT_MAX;
676 	}
677 }
678 
disk_zone_wplug_sync_wp_offset(struct gendisk * disk,struct blk_zone * zone)679 static void disk_zone_wplug_sync_wp_offset(struct gendisk *disk,
680 					   struct blk_zone *zone)
681 {
682 	struct blk_zone_wplug *zwplug;
683 	unsigned long flags;
684 
685 	zwplug = disk_get_zone_wplug(disk, zone->start);
686 	if (!zwplug)
687 		return;
688 
689 	spin_lock_irqsave(&zwplug->lock, flags);
690 	if (zwplug->flags & BLK_ZONE_WPLUG_NEED_WP_UPDATE)
691 		disk_zone_wplug_set_wp_offset(disk, zwplug,
692 					      blk_zone_wp_offset(zone));
693 	spin_unlock_irqrestore(&zwplug->lock, flags);
694 
695 	disk_put_zone_wplug(zwplug);
696 }
697 
disk_zone_sync_wp_offset(struct gendisk * disk,sector_t sector)698 static int disk_zone_sync_wp_offset(struct gendisk *disk, sector_t sector)
699 {
700 	struct disk_report_zones_cb_args args = {
701 		.disk = disk,
702 	};
703 
704 	return disk->fops->report_zones(disk, sector, 1,
705 					disk_report_zones_cb, &args);
706 }
707 
blk_zone_wplug_handle_reset_or_finish(struct bio * bio,unsigned int wp_offset)708 static bool blk_zone_wplug_handle_reset_or_finish(struct bio *bio,
709 						  unsigned int wp_offset)
710 {
711 	struct gendisk *disk = bio->bi_bdev->bd_disk;
712 	sector_t sector = bio->bi_iter.bi_sector;
713 	struct blk_zone_wplug *zwplug;
714 	unsigned long flags;
715 
716 	/* Conventional zones cannot be reset nor finished. */
717 	if (!bdev_zone_is_seq(bio->bi_bdev, sector)) {
718 		bio_io_error(bio);
719 		return true;
720 	}
721 
722 	/*
723 	 * No-wait reset or finish BIOs do not make much sense as the callers
724 	 * issue these as blocking operations in most cases. To avoid issues
725 	 * the BIO execution potentially failing with BLK_STS_AGAIN, warn about
726 	 * REQ_NOWAIT being set and ignore that flag.
727 	 */
728 	if (WARN_ON_ONCE(bio->bi_opf & REQ_NOWAIT))
729 		bio->bi_opf &= ~REQ_NOWAIT;
730 
731 	/*
732 	 * If we have a zone write plug, set its write pointer offset to 0
733 	 * (reset case) or to the zone size (finish case). This will abort all
734 	 * BIOs plugged for the target zone. It is fine as resetting or
735 	 * finishing zones while writes are still in-flight will result in the
736 	 * writes failing anyway.
737 	 */
738 	zwplug = disk_get_zone_wplug(disk, sector);
739 	if (zwplug) {
740 		spin_lock_irqsave(&zwplug->lock, flags);
741 		disk_zone_wplug_set_wp_offset(disk, zwplug, wp_offset);
742 		spin_unlock_irqrestore(&zwplug->lock, flags);
743 		disk_put_zone_wplug(zwplug);
744 	}
745 
746 	return false;
747 }
748 
blk_zone_wplug_handle_reset_all(struct bio * bio)749 static bool blk_zone_wplug_handle_reset_all(struct bio *bio)
750 {
751 	struct gendisk *disk = bio->bi_bdev->bd_disk;
752 	struct blk_zone_wplug *zwplug;
753 	unsigned long flags;
754 	sector_t sector;
755 
756 	/*
757 	 * Set the write pointer offset of all zone write plugs to 0. This will
758 	 * abort all plugged BIOs. It is fine as resetting zones while writes
759 	 * are still in-flight will result in the writes failing anyway.
760 	 */
761 	for (sector = 0; sector < get_capacity(disk);
762 	     sector += disk->queue->limits.chunk_sectors) {
763 		zwplug = disk_get_zone_wplug(disk, sector);
764 		if (zwplug) {
765 			spin_lock_irqsave(&zwplug->lock, flags);
766 			disk_zone_wplug_set_wp_offset(disk, zwplug, 0);
767 			spin_unlock_irqrestore(&zwplug->lock, flags);
768 			disk_put_zone_wplug(zwplug);
769 		}
770 	}
771 
772 	return false;
773 }
774 
disk_zone_wplug_schedule_bio_work(struct gendisk * disk,struct blk_zone_wplug * zwplug)775 static void disk_zone_wplug_schedule_bio_work(struct gendisk *disk,
776 					      struct blk_zone_wplug *zwplug)
777 {
778 	/*
779 	 * Take a reference on the zone write plug and schedule the submission
780 	 * of the next plugged BIO. blk_zone_wplug_bio_work() will release the
781 	 * reference we take here.
782 	 */
783 	WARN_ON_ONCE(!(zwplug->flags & BLK_ZONE_WPLUG_PLUGGED));
784 	refcount_inc(&zwplug->ref);
785 	queue_work(disk->zone_wplugs_wq, &zwplug->bio_work);
786 }
787 
disk_zone_wplug_add_bio(struct gendisk * disk,struct blk_zone_wplug * zwplug,struct bio * bio,unsigned int nr_segs)788 static inline void disk_zone_wplug_add_bio(struct gendisk *disk,
789 				struct blk_zone_wplug *zwplug,
790 				struct bio *bio, unsigned int nr_segs)
791 {
792 	bool schedule_bio_work = false;
793 
794 	/*
795 	 * Grab an extra reference on the BIO request queue usage counter.
796 	 * This reference will be reused to submit a request for the BIO for
797 	 * blk-mq devices and dropped when the BIO is failed and after
798 	 * it is issued in the case of BIO-based devices.
799 	 */
800 	percpu_ref_get(&bio->bi_bdev->bd_disk->queue->q_usage_counter);
801 
802 	/*
803 	 * The BIO is being plugged and thus will have to wait for the on-going
804 	 * write and for all other writes already plugged. So polling makes
805 	 * no sense.
806 	 */
807 	bio_clear_polled(bio);
808 
809 	/*
810 	 * REQ_NOWAIT BIOs are always handled using the zone write plug BIO
811 	 * work, which can block. So clear the REQ_NOWAIT flag and schedule the
812 	 * work if this is the first BIO we are plugging.
813 	 */
814 	if (bio->bi_opf & REQ_NOWAIT) {
815 		schedule_bio_work = !(zwplug->flags & BLK_ZONE_WPLUG_PLUGGED);
816 		bio->bi_opf &= ~REQ_NOWAIT;
817 	}
818 
819 	/*
820 	 * Reuse the poll cookie field to store the number of segments when
821 	 * split to the hardware limits.
822 	 */
823 	bio->__bi_nr_segments = nr_segs;
824 
825 	/*
826 	 * We always receive BIOs after they are split and ready to be issued.
827 	 * The block layer passes the parts of a split BIO in order, and the
828 	 * user must also issue write sequentially. So simply add the new BIO
829 	 * at the tail of the list to preserve the sequential write order.
830 	 */
831 	bio_list_add(&zwplug->bio_list, bio);
832 	trace_disk_zone_wplug_add_bio(zwplug->disk->queue, zwplug->zone_no,
833 				      bio->bi_iter.bi_sector, bio_sectors(bio));
834 
835 	zwplug->flags |= BLK_ZONE_WPLUG_PLUGGED;
836 
837 	if (schedule_bio_work)
838 		disk_zone_wplug_schedule_bio_work(disk, zwplug);
839 }
840 
841 /*
842  * Called from bio_attempt_back_merge() when a BIO was merged with a request.
843  */
blk_zone_write_plug_bio_merged(struct bio * bio)844 void blk_zone_write_plug_bio_merged(struct bio *bio)
845 {
846 	struct blk_zone_wplug *zwplug;
847 	unsigned long flags;
848 
849 	/*
850 	 * If the BIO was already plugged, then we were called through
851 	 * blk_zone_write_plug_init_request() -> blk_attempt_bio_merge().
852 	 * For this case, we already hold a reference on the zone write plug for
853 	 * the BIO and blk_zone_write_plug_init_request() will handle the
854 	 * zone write pointer offset update.
855 	 */
856 	if (bio_flagged(bio, BIO_ZONE_WRITE_PLUGGING))
857 		return;
858 
859 	bio_set_flag(bio, BIO_ZONE_WRITE_PLUGGING);
860 
861 	/*
862 	 * Get a reference on the zone write plug of the target zone and advance
863 	 * the zone write pointer offset. Given that this is a merge, we already
864 	 * have at least one request and one BIO referencing the zone write
865 	 * plug. So this should not fail.
866 	 */
867 	zwplug = disk_get_zone_wplug(bio->bi_bdev->bd_disk,
868 				     bio->bi_iter.bi_sector);
869 	if (WARN_ON_ONCE(!zwplug))
870 		return;
871 
872 	spin_lock_irqsave(&zwplug->lock, flags);
873 	zwplug->wp_offset += bio_sectors(bio);
874 	spin_unlock_irqrestore(&zwplug->lock, flags);
875 }
876 
877 /*
878  * Attempt to merge plugged BIOs with a newly prepared request for a BIO that
879  * already went through zone write plugging (either a new BIO or one that was
880  * unplugged).
881  */
blk_zone_write_plug_init_request(struct request * req)882 void blk_zone_write_plug_init_request(struct request *req)
883 {
884 	sector_t req_back_sector = blk_rq_pos(req) + blk_rq_sectors(req);
885 	struct request_queue *q = req->q;
886 	struct gendisk *disk = q->disk;
887 	struct blk_zone_wplug *zwplug =
888 		disk_get_zone_wplug(disk, blk_rq_pos(req));
889 	unsigned long flags;
890 	struct bio *bio;
891 
892 	if (WARN_ON_ONCE(!zwplug))
893 		return;
894 
895 	/*
896 	 * Indicate that completion of this request needs to be handled with
897 	 * blk_zone_write_plug_finish_request(), which will drop the reference
898 	 * on the zone write plug we took above on entry to this function.
899 	 */
900 	req->rq_flags |= RQF_ZONE_WRITE_PLUGGING;
901 
902 	if (blk_queue_nomerges(q))
903 		return;
904 
905 	/*
906 	 * Walk through the list of plugged BIOs to check if they can be merged
907 	 * into the back of the request.
908 	 */
909 	spin_lock_irqsave(&zwplug->lock, flags);
910 	while (!disk_zone_wplug_is_full(disk, zwplug)) {
911 		bio = bio_list_peek(&zwplug->bio_list);
912 		if (!bio)
913 			break;
914 
915 		if (bio->bi_iter.bi_sector != req_back_sector ||
916 		    !blk_rq_merge_ok(req, bio))
917 			break;
918 
919 		WARN_ON_ONCE(bio_op(bio) != REQ_OP_WRITE_ZEROES &&
920 			     !bio->__bi_nr_segments);
921 
922 		bio_list_pop(&zwplug->bio_list);
923 		if (bio_attempt_back_merge(req, bio, bio->__bi_nr_segments) !=
924 		    BIO_MERGE_OK) {
925 			bio_list_add_head(&zwplug->bio_list, bio);
926 			break;
927 		}
928 
929 		/*
930 		 * Drop the extra reference on the queue usage we got when
931 		 * plugging the BIO and advance the write pointer offset.
932 		 */
933 		blk_queue_exit(q);
934 		zwplug->wp_offset += bio_sectors(bio);
935 
936 		req_back_sector += bio_sectors(bio);
937 	}
938 	spin_unlock_irqrestore(&zwplug->lock, flags);
939 }
940 
941 /*
942  * Check and prepare a BIO for submission by incrementing the write pointer
943  * offset of its zone write plug and changing zone append operations into
944  * regular write when zone append emulation is needed.
945  */
blk_zone_wplug_prepare_bio(struct blk_zone_wplug * zwplug,struct bio * bio)946 static bool blk_zone_wplug_prepare_bio(struct blk_zone_wplug *zwplug,
947 				       struct bio *bio)
948 {
949 	struct gendisk *disk = bio->bi_bdev->bd_disk;
950 
951 	/*
952 	 * If we lost track of the zone write pointer due to a write error,
953 	 * the user must either execute a report zones, reset the zone or finish
954 	 * the to recover a reliable write pointer position. Fail BIOs if the
955 	 * user did not do that as we cannot handle emulated zone append
956 	 * otherwise.
957 	 */
958 	if (zwplug->flags & BLK_ZONE_WPLUG_NEED_WP_UPDATE)
959 		return false;
960 
961 	/*
962 	 * Check that the user is not attempting to write to a full zone.
963 	 * We know such BIO will fail, and that would potentially overflow our
964 	 * write pointer offset beyond the end of the zone.
965 	 */
966 	if (disk_zone_wplug_is_full(disk, zwplug))
967 		return false;
968 
969 	if (bio_op(bio) == REQ_OP_ZONE_APPEND) {
970 		/*
971 		 * Use a regular write starting at the current write pointer.
972 		 * Similarly to native zone append operations, do not allow
973 		 * merging.
974 		 */
975 		bio->bi_opf &= ~REQ_OP_MASK;
976 		bio->bi_opf |= REQ_OP_WRITE | REQ_NOMERGE;
977 		bio->bi_iter.bi_sector += zwplug->wp_offset;
978 
979 		/*
980 		 * Remember that this BIO is in fact a zone append operation
981 		 * so that we can restore its operation code on completion.
982 		 */
983 		bio_set_flag(bio, BIO_EMULATES_ZONE_APPEND);
984 	} else {
985 		/*
986 		 * Check for non-sequential writes early as we know that BIOs
987 		 * with a start sector not unaligned to the zone write pointer
988 		 * will fail.
989 		 */
990 		if (bio_offset_from_zone_start(bio) != zwplug->wp_offset)
991 			return false;
992 	}
993 
994 	/* Advance the zone write pointer offset. */
995 	zwplug->wp_offset += bio_sectors(bio);
996 
997 	return true;
998 }
999 
blk_zone_wplug_handle_write(struct bio * bio,unsigned int nr_segs)1000 static bool blk_zone_wplug_handle_write(struct bio *bio, unsigned int nr_segs)
1001 {
1002 	struct gendisk *disk = bio->bi_bdev->bd_disk;
1003 	sector_t sector = bio->bi_iter.bi_sector;
1004 	struct blk_zone_wplug *zwplug;
1005 	gfp_t gfp_mask = GFP_NOIO;
1006 	unsigned long flags;
1007 
1008 	/*
1009 	 * BIOs must be fully contained within a zone so that we use the correct
1010 	 * zone write plug for the entire BIO. For blk-mq devices, the block
1011 	 * layer should already have done any splitting required to ensure this
1012 	 * and this BIO should thus not be straddling zone boundaries. For
1013 	 * BIO-based devices, it is the responsibility of the driver to split
1014 	 * the bio before submitting it.
1015 	 */
1016 	if (WARN_ON_ONCE(bio_straddles_zones(bio))) {
1017 		bio_io_error(bio);
1018 		return true;
1019 	}
1020 
1021 	/* Conventional zones do not need write plugging. */
1022 	if (!bdev_zone_is_seq(bio->bi_bdev, sector)) {
1023 		/* Zone append to conventional zones is not allowed. */
1024 		if (bio_op(bio) == REQ_OP_ZONE_APPEND) {
1025 			bio_io_error(bio);
1026 			return true;
1027 		}
1028 		return false;
1029 	}
1030 
1031 	if (bio->bi_opf & REQ_NOWAIT)
1032 		gfp_mask = GFP_NOWAIT;
1033 
1034 	zwplug = disk_get_and_lock_zone_wplug(disk, sector, gfp_mask, &flags);
1035 	if (!zwplug) {
1036 		if (bio->bi_opf & REQ_NOWAIT)
1037 			bio_wouldblock_error(bio);
1038 		else
1039 			bio_io_error(bio);
1040 		return true;
1041 	}
1042 
1043 	/* Indicate that this BIO is being handled using zone write plugging. */
1044 	bio_set_flag(bio, BIO_ZONE_WRITE_PLUGGING);
1045 
1046 	/*
1047 	 * If the zone is already plugged, add the BIO to the plug BIO list.
1048 	 * Do the same for REQ_NOWAIT BIOs to ensure that we will not see a
1049 	 * BLK_STS_AGAIN failure if we let the BIO execute.
1050 	 * Otherwise, plug and let the BIO execute.
1051 	 */
1052 	if ((zwplug->flags & BLK_ZONE_WPLUG_PLUGGED) ||
1053 	    (bio->bi_opf & REQ_NOWAIT))
1054 		goto plug;
1055 
1056 	if (!blk_zone_wplug_prepare_bio(zwplug, bio)) {
1057 		spin_unlock_irqrestore(&zwplug->lock, flags);
1058 		bio_io_error(bio);
1059 		return true;
1060 	}
1061 
1062 	zwplug->flags |= BLK_ZONE_WPLUG_PLUGGED;
1063 
1064 	spin_unlock_irqrestore(&zwplug->lock, flags);
1065 
1066 	return false;
1067 
1068 plug:
1069 	disk_zone_wplug_add_bio(disk, zwplug, bio, nr_segs);
1070 
1071 	spin_unlock_irqrestore(&zwplug->lock, flags);
1072 
1073 	return true;
1074 }
1075 
blk_zone_wplug_handle_native_zone_append(struct bio * bio)1076 static void blk_zone_wplug_handle_native_zone_append(struct bio *bio)
1077 {
1078 	struct gendisk *disk = bio->bi_bdev->bd_disk;
1079 	struct blk_zone_wplug *zwplug;
1080 	unsigned long flags;
1081 
1082 	/*
1083 	 * We have native support for zone append operations, so we are not
1084 	 * going to handle @bio through plugging. However, we may already have a
1085 	 * zone write plug for the target zone if that zone was previously
1086 	 * partially written using regular writes. In such case, we risk leaving
1087 	 * the plug in the disk hash table if the zone is fully written using
1088 	 * zone append operations. Avoid this by removing the zone write plug.
1089 	 */
1090 	zwplug = disk_get_zone_wplug(disk, bio->bi_iter.bi_sector);
1091 	if (likely(!zwplug))
1092 		return;
1093 
1094 	spin_lock_irqsave(&zwplug->lock, flags);
1095 
1096 	/*
1097 	 * We are about to remove the zone write plug. But if the user
1098 	 * (mistakenly) has issued regular writes together with native zone
1099 	 * append, we must aborts the writes as otherwise the plugged BIOs would
1100 	 * not be executed by the plug BIO work as disk_get_zone_wplug() will
1101 	 * return NULL after the plug is removed. Aborting the plugged write
1102 	 * BIOs is consistent with the fact that these writes will most likely
1103 	 * fail anyway as there is no ordering guarantees between zone append
1104 	 * operations and regular write operations.
1105 	 */
1106 	if (!bio_list_empty(&zwplug->bio_list)) {
1107 		pr_warn_ratelimited("%s: zone %u: Invalid mix of zone append and regular writes\n",
1108 				    disk->disk_name, zwplug->zone_no);
1109 		disk_zone_wplug_abort(zwplug);
1110 	}
1111 	disk_remove_zone_wplug(disk, zwplug);
1112 	spin_unlock_irqrestore(&zwplug->lock, flags);
1113 
1114 	disk_put_zone_wplug(zwplug);
1115 }
1116 
1117 /**
1118  * blk_zone_plug_bio - Handle a zone write BIO with zone write plugging
1119  * @bio: The BIO being submitted
1120  * @nr_segs: The number of physical segments of @bio
1121  *
1122  * Handle write, write zeroes and zone append operations requiring emulation
1123  * using zone write plugging.
1124  *
1125  * Return true whenever @bio execution needs to be delayed through the zone
1126  * write plug. Otherwise, return false to let the submission path process
1127  * @bio normally.
1128  */
blk_zone_plug_bio(struct bio * bio,unsigned int nr_segs)1129 bool blk_zone_plug_bio(struct bio *bio, unsigned int nr_segs)
1130 {
1131 	struct block_device *bdev = bio->bi_bdev;
1132 
1133 	if (WARN_ON_ONCE(!bdev->bd_disk->zone_wplugs_hash))
1134 		return false;
1135 
1136 	/*
1137 	 * Regular writes and write zeroes need to be handled through the target
1138 	 * zone write plug. This includes writes with REQ_FUA | REQ_PREFLUSH
1139 	 * which may need to go through the flush machinery depending on the
1140 	 * target device capabilities. Plugging such writes is fine as the flush
1141 	 * machinery operates at the request level, below the plug, and
1142 	 * completion of the flush sequence will go through the regular BIO
1143 	 * completion, which will handle zone write plugging.
1144 	 * Zone append operations for devices that requested emulation must
1145 	 * also be plugged so that these BIOs can be changed into regular
1146 	 * write BIOs.
1147 	 * Zone reset, reset all and finish commands need special treatment
1148 	 * to correctly track the write pointer offset of zones. These commands
1149 	 * are not plugged as we do not need serialization with write
1150 	 * operations. It is the responsibility of the user to not issue reset
1151 	 * and finish commands when write operations are in flight.
1152 	 */
1153 	switch (bio_op(bio)) {
1154 	case REQ_OP_ZONE_APPEND:
1155 		if (!bdev_emulates_zone_append(bdev)) {
1156 			blk_zone_wplug_handle_native_zone_append(bio);
1157 			return false;
1158 		}
1159 		fallthrough;
1160 	case REQ_OP_WRITE:
1161 	case REQ_OP_WRITE_ZEROES:
1162 		return blk_zone_wplug_handle_write(bio, nr_segs);
1163 	case REQ_OP_ZONE_RESET:
1164 		return blk_zone_wplug_handle_reset_or_finish(bio, 0);
1165 	case REQ_OP_ZONE_FINISH:
1166 		return blk_zone_wplug_handle_reset_or_finish(bio,
1167 						bdev_zone_sectors(bdev));
1168 	case REQ_OP_ZONE_RESET_ALL:
1169 		return blk_zone_wplug_handle_reset_all(bio);
1170 	default:
1171 		return false;
1172 	}
1173 
1174 	return false;
1175 }
1176 EXPORT_SYMBOL_GPL(blk_zone_plug_bio);
1177 
disk_zone_wplug_unplug_bio(struct gendisk * disk,struct blk_zone_wplug * zwplug)1178 static void disk_zone_wplug_unplug_bio(struct gendisk *disk,
1179 				       struct blk_zone_wplug *zwplug)
1180 {
1181 	unsigned long flags;
1182 
1183 	spin_lock_irqsave(&zwplug->lock, flags);
1184 
1185 	/* Schedule submission of the next plugged BIO if we have one. */
1186 	if (!bio_list_empty(&zwplug->bio_list)) {
1187 		disk_zone_wplug_schedule_bio_work(disk, zwplug);
1188 		spin_unlock_irqrestore(&zwplug->lock, flags);
1189 		return;
1190 	}
1191 
1192 	zwplug->flags &= ~BLK_ZONE_WPLUG_PLUGGED;
1193 
1194 	/*
1195 	 * If the zone is full (it was fully written or finished, or empty
1196 	 * (it was reset), remove its zone write plug from the hash table.
1197 	 */
1198 	if (disk_should_remove_zone_wplug(disk, zwplug))
1199 		disk_remove_zone_wplug(disk, zwplug);
1200 
1201 	spin_unlock_irqrestore(&zwplug->lock, flags);
1202 }
1203 
blk_zone_append_update_request_bio(struct request * rq,struct bio * bio)1204 void blk_zone_append_update_request_bio(struct request *rq, struct bio *bio)
1205 {
1206 	/*
1207 	 * For zone append requests, the request sector indicates the location
1208 	 * at which the BIO data was written. Return this value to the BIO
1209 	 * issuer through the BIO iter sector.
1210 	 * For plugged zone writes, which include emulated zone append, we need
1211 	 * the original BIO sector so that blk_zone_write_plug_bio_endio() can
1212 	 * lookup the zone write plug.
1213 	 */
1214 	bio->bi_iter.bi_sector = rq->__sector;
1215 	trace_blk_zone_append_update_request_bio(rq);
1216 }
1217 
blk_zone_write_plug_bio_endio(struct bio * bio)1218 void blk_zone_write_plug_bio_endio(struct bio *bio)
1219 {
1220 	struct gendisk *disk = bio->bi_bdev->bd_disk;
1221 	struct blk_zone_wplug *zwplug =
1222 		disk_get_zone_wplug(disk, bio->bi_iter.bi_sector);
1223 	unsigned long flags;
1224 
1225 	if (WARN_ON_ONCE(!zwplug))
1226 		return;
1227 
1228 	/* Make sure we do not see this BIO again by clearing the plug flag. */
1229 	bio_clear_flag(bio, BIO_ZONE_WRITE_PLUGGING);
1230 
1231 	/*
1232 	 * If this is a regular write emulating a zone append operation,
1233 	 * restore the original operation code.
1234 	 */
1235 	if (bio_flagged(bio, BIO_EMULATES_ZONE_APPEND)) {
1236 		bio->bi_opf &= ~REQ_OP_MASK;
1237 		bio->bi_opf |= REQ_OP_ZONE_APPEND;
1238 		bio_clear_flag(bio, BIO_EMULATES_ZONE_APPEND);
1239 	}
1240 
1241 	/*
1242 	 * If the BIO failed, abort all plugged BIOs and mark the plug as
1243 	 * needing a write pointer update.
1244 	 */
1245 	if (bio->bi_status != BLK_STS_OK) {
1246 		spin_lock_irqsave(&zwplug->lock, flags);
1247 		disk_zone_wplug_abort(zwplug);
1248 		zwplug->flags |= BLK_ZONE_WPLUG_NEED_WP_UPDATE;
1249 		spin_unlock_irqrestore(&zwplug->lock, flags);
1250 	}
1251 
1252 	/* Drop the reference we took when the BIO was issued. */
1253 	disk_put_zone_wplug(zwplug);
1254 
1255 	/*
1256 	 * For BIO-based devices, blk_zone_write_plug_finish_request()
1257 	 * is not called. So we need to schedule execution of the next
1258 	 * plugged BIO here.
1259 	 */
1260 	if (bdev_test_flag(bio->bi_bdev, BD_HAS_SUBMIT_BIO))
1261 		disk_zone_wplug_unplug_bio(disk, zwplug);
1262 
1263 	/* Drop the reference we took when entering this function. */
1264 	disk_put_zone_wplug(zwplug);
1265 }
1266 
blk_zone_write_plug_finish_request(struct request * req)1267 void blk_zone_write_plug_finish_request(struct request *req)
1268 {
1269 	struct gendisk *disk = req->q->disk;
1270 	struct blk_zone_wplug *zwplug;
1271 
1272 	zwplug = disk_get_zone_wplug(disk, req->__sector);
1273 	if (WARN_ON_ONCE(!zwplug))
1274 		return;
1275 
1276 	req->rq_flags &= ~RQF_ZONE_WRITE_PLUGGING;
1277 
1278 	/*
1279 	 * Drop the reference we took when the request was initialized in
1280 	 * blk_zone_write_plug_init_request().
1281 	 */
1282 	disk_put_zone_wplug(zwplug);
1283 
1284 	disk_zone_wplug_unplug_bio(disk, zwplug);
1285 
1286 	/* Drop the reference we took when entering this function. */
1287 	disk_put_zone_wplug(zwplug);
1288 }
1289 
blk_zone_wplug_bio_work(struct work_struct * work)1290 static void blk_zone_wplug_bio_work(struct work_struct *work)
1291 {
1292 	struct blk_zone_wplug *zwplug =
1293 		container_of(work, struct blk_zone_wplug, bio_work);
1294 	struct block_device *bdev;
1295 	unsigned long flags;
1296 	struct bio *bio;
1297 	bool prepared;
1298 
1299 	/*
1300 	 * Submit the next plugged BIO. If we do not have any, clear
1301 	 * the plugged flag.
1302 	 */
1303 again:
1304 	spin_lock_irqsave(&zwplug->lock, flags);
1305 	bio = bio_list_pop(&zwplug->bio_list);
1306 	if (!bio) {
1307 		zwplug->flags &= ~BLK_ZONE_WPLUG_PLUGGED;
1308 		spin_unlock_irqrestore(&zwplug->lock, flags);
1309 		goto put_zwplug;
1310 	}
1311 
1312 	trace_blk_zone_wplug_bio(zwplug->disk->queue, zwplug->zone_no,
1313 				 bio->bi_iter.bi_sector, bio_sectors(bio));
1314 
1315 	prepared = blk_zone_wplug_prepare_bio(zwplug, bio);
1316 	spin_unlock_irqrestore(&zwplug->lock, flags);
1317 
1318 	if (!prepared) {
1319 		blk_zone_wplug_bio_io_error(zwplug, bio);
1320 		goto again;
1321 	}
1322 
1323 	bdev = bio->bi_bdev;
1324 
1325 	/*
1326 	 * blk-mq devices will reuse the extra reference on the request queue
1327 	 * usage counter we took when the BIO was plugged, but the submission
1328 	 * path for BIO-based devices will not do that. So drop this extra
1329 	 * reference here.
1330 	 */
1331 	if (bdev_test_flag(bdev, BD_HAS_SUBMIT_BIO)) {
1332 		bdev->bd_disk->fops->submit_bio(bio);
1333 		blk_queue_exit(bdev->bd_disk->queue);
1334 	} else {
1335 		blk_mq_submit_bio(bio);
1336 	}
1337 
1338 put_zwplug:
1339 	/* Drop the reference we took in disk_zone_wplug_schedule_bio_work(). */
1340 	disk_put_zone_wplug(zwplug);
1341 }
1342 
disk_zone_wplugs_hash_size(struct gendisk * disk)1343 static inline unsigned int disk_zone_wplugs_hash_size(struct gendisk *disk)
1344 {
1345 	return 1U << disk->zone_wplugs_hash_bits;
1346 }
1347 
disk_init_zone_resources(struct gendisk * disk)1348 void disk_init_zone_resources(struct gendisk *disk)
1349 {
1350 	spin_lock_init(&disk->zone_wplugs_lock);
1351 }
1352 
1353 /*
1354  * For the size of a disk zone write plug hash table, use the size of the
1355  * zone write plug mempool, which is the maximum of the disk open zones and
1356  * active zones limits. But do not exceed 4KB (512 hlist head entries), that is,
1357  * 9 bits. For a disk that has no limits, mempool size defaults to 128.
1358  */
1359 #define BLK_ZONE_WPLUG_MAX_HASH_BITS		9
1360 #define BLK_ZONE_WPLUG_DEFAULT_POOL_SIZE	128
1361 
disk_alloc_zone_resources(struct gendisk * disk,unsigned int pool_size)1362 static int disk_alloc_zone_resources(struct gendisk *disk,
1363 				     unsigned int pool_size)
1364 {
1365 	unsigned int i;
1366 
1367 	atomic_set(&disk->nr_zone_wplugs, 0);
1368 	disk->zone_wplugs_hash_bits =
1369 		min(ilog2(pool_size) + 1, BLK_ZONE_WPLUG_MAX_HASH_BITS);
1370 
1371 	disk->zone_wplugs_hash =
1372 		kcalloc(disk_zone_wplugs_hash_size(disk),
1373 			sizeof(struct hlist_head), GFP_KERNEL);
1374 	if (!disk->zone_wplugs_hash)
1375 		return -ENOMEM;
1376 
1377 	for (i = 0; i < disk_zone_wplugs_hash_size(disk); i++)
1378 		INIT_HLIST_HEAD(&disk->zone_wplugs_hash[i]);
1379 
1380 	disk->zone_wplugs_pool = mempool_create_kmalloc_pool(pool_size,
1381 						sizeof(struct blk_zone_wplug));
1382 	if (!disk->zone_wplugs_pool)
1383 		goto free_hash;
1384 
1385 	disk->zone_wplugs_wq =
1386 		alloc_workqueue("%s_zwplugs", WQ_MEM_RECLAIM | WQ_HIGHPRI,
1387 				pool_size, disk->disk_name);
1388 	if (!disk->zone_wplugs_wq)
1389 		goto destroy_pool;
1390 
1391 	return 0;
1392 
1393 destroy_pool:
1394 	mempool_destroy(disk->zone_wplugs_pool);
1395 	disk->zone_wplugs_pool = NULL;
1396 free_hash:
1397 	kfree(disk->zone_wplugs_hash);
1398 	disk->zone_wplugs_hash = NULL;
1399 	disk->zone_wplugs_hash_bits = 0;
1400 	return -ENOMEM;
1401 }
1402 
disk_destroy_zone_wplugs_hash_table(struct gendisk * disk)1403 static void disk_destroy_zone_wplugs_hash_table(struct gendisk *disk)
1404 {
1405 	struct blk_zone_wplug *zwplug;
1406 	unsigned int i;
1407 
1408 	if (!disk->zone_wplugs_hash)
1409 		return;
1410 
1411 	/* Free all the zone write plugs we have. */
1412 	for (i = 0; i < disk_zone_wplugs_hash_size(disk); i++) {
1413 		while (!hlist_empty(&disk->zone_wplugs_hash[i])) {
1414 			zwplug = hlist_entry(disk->zone_wplugs_hash[i].first,
1415 					     struct blk_zone_wplug, node);
1416 			refcount_inc(&zwplug->ref);
1417 			disk_remove_zone_wplug(disk, zwplug);
1418 			disk_put_zone_wplug(zwplug);
1419 		}
1420 	}
1421 
1422 	WARN_ON_ONCE(atomic_read(&disk->nr_zone_wplugs));
1423 	kfree(disk->zone_wplugs_hash);
1424 	disk->zone_wplugs_hash = NULL;
1425 	disk->zone_wplugs_hash_bits = 0;
1426 }
1427 
disk_set_conv_zones_bitmap(struct gendisk * disk,unsigned long * bitmap)1428 static unsigned int disk_set_conv_zones_bitmap(struct gendisk *disk,
1429 					       unsigned long *bitmap)
1430 {
1431 	unsigned int nr_conv_zones = 0;
1432 	unsigned long flags;
1433 
1434 	spin_lock_irqsave(&disk->zone_wplugs_lock, flags);
1435 	if (bitmap)
1436 		nr_conv_zones = bitmap_weight(bitmap, disk->nr_zones);
1437 	bitmap = rcu_replace_pointer(disk->conv_zones_bitmap, bitmap,
1438 				     lockdep_is_held(&disk->zone_wplugs_lock));
1439 	spin_unlock_irqrestore(&disk->zone_wplugs_lock, flags);
1440 
1441 	kfree_rcu_mightsleep(bitmap);
1442 
1443 	return nr_conv_zones;
1444 }
1445 
disk_free_zone_resources(struct gendisk * disk)1446 void disk_free_zone_resources(struct gendisk *disk)
1447 {
1448 	if (!disk->zone_wplugs_pool)
1449 		return;
1450 
1451 	if (disk->zone_wplugs_wq) {
1452 		destroy_workqueue(disk->zone_wplugs_wq);
1453 		disk->zone_wplugs_wq = NULL;
1454 	}
1455 
1456 	disk_destroy_zone_wplugs_hash_table(disk);
1457 
1458 	/*
1459 	 * Wait for the zone write plugs to be RCU-freed before
1460 	 * destorying the mempool.
1461 	 */
1462 	rcu_barrier();
1463 
1464 	mempool_destroy(disk->zone_wplugs_pool);
1465 	disk->zone_wplugs_pool = NULL;
1466 
1467 	disk_set_conv_zones_bitmap(disk, NULL);
1468 	disk->zone_capacity = 0;
1469 	disk->last_zone_capacity = 0;
1470 	disk->nr_zones = 0;
1471 }
1472 
disk_need_zone_resources(struct gendisk * disk)1473 static inline bool disk_need_zone_resources(struct gendisk *disk)
1474 {
1475 	/*
1476 	 * All mq zoned devices need zone resources so that the block layer
1477 	 * can automatically handle write BIO plugging. BIO-based device drivers
1478 	 * (e.g. DM devices) are normally responsible for handling zone write
1479 	 * ordering and do not need zone resources, unless the driver requires
1480 	 * zone append emulation.
1481 	 */
1482 	return queue_is_mq(disk->queue) ||
1483 		queue_emulates_zone_append(disk->queue);
1484 }
1485 
disk_revalidate_zone_resources(struct gendisk * disk,unsigned int nr_zones)1486 static int disk_revalidate_zone_resources(struct gendisk *disk,
1487 					  unsigned int nr_zones)
1488 {
1489 	struct queue_limits *lim = &disk->queue->limits;
1490 	unsigned int pool_size;
1491 
1492 	if (!disk_need_zone_resources(disk))
1493 		return 0;
1494 
1495 	/*
1496 	 * If the device has no limit on the maximum number of open and active
1497 	 * zones, use BLK_ZONE_WPLUG_DEFAULT_POOL_SIZE.
1498 	 */
1499 	pool_size = max(lim->max_open_zones, lim->max_active_zones);
1500 	if (!pool_size)
1501 		pool_size = min(BLK_ZONE_WPLUG_DEFAULT_POOL_SIZE, nr_zones);
1502 
1503 	if (!disk->zone_wplugs_hash)
1504 		return disk_alloc_zone_resources(disk, pool_size);
1505 
1506 	return 0;
1507 }
1508 
1509 struct blk_revalidate_zone_args {
1510 	struct gendisk	*disk;
1511 	unsigned long	*conv_zones_bitmap;
1512 	unsigned int	nr_zones;
1513 	unsigned int	zone_capacity;
1514 	unsigned int	last_zone_capacity;
1515 	sector_t	sector;
1516 };
1517 
1518 /*
1519  * Update the disk zone resources information and device queue limits.
1520  * The disk queue is frozen when this is executed.
1521  */
disk_update_zone_resources(struct gendisk * disk,struct blk_revalidate_zone_args * args)1522 static int disk_update_zone_resources(struct gendisk *disk,
1523 				      struct blk_revalidate_zone_args *args)
1524 {
1525 	struct request_queue *q = disk->queue;
1526 	unsigned int nr_seq_zones, nr_conv_zones;
1527 	unsigned int pool_size;
1528 	struct queue_limits lim;
1529 
1530 	disk->nr_zones = args->nr_zones;
1531 	disk->zone_capacity = args->zone_capacity;
1532 	disk->last_zone_capacity = args->last_zone_capacity;
1533 	nr_conv_zones =
1534 		disk_set_conv_zones_bitmap(disk, args->conv_zones_bitmap);
1535 	if (nr_conv_zones >= disk->nr_zones) {
1536 		pr_warn("%s: Invalid number of conventional zones %u / %u\n",
1537 			disk->disk_name, nr_conv_zones, disk->nr_zones);
1538 		return -ENODEV;
1539 	}
1540 
1541 	lim = queue_limits_start_update(q);
1542 
1543 	/*
1544 	 * Some devices can advertize zone resource limits that are larger than
1545 	 * the number of sequential zones of the zoned block device, e.g. a
1546 	 * small ZNS namespace. For such case, assume that the zoned device has
1547 	 * no zone resource limits.
1548 	 */
1549 	nr_seq_zones = disk->nr_zones - nr_conv_zones;
1550 	if (lim.max_open_zones >= nr_seq_zones)
1551 		lim.max_open_zones = 0;
1552 	if (lim.max_active_zones >= nr_seq_zones)
1553 		lim.max_active_zones = 0;
1554 
1555 	if (!disk->zone_wplugs_pool)
1556 		goto commit;
1557 
1558 	/*
1559 	 * If the device has no limit on the maximum number of open and active
1560 	 * zones, set its max open zone limit to the mempool size to indicate
1561 	 * to the user that there is a potential performance impact due to
1562 	 * dynamic zone write plug allocation when simultaneously writing to
1563 	 * more zones than the size of the mempool.
1564 	 */
1565 	pool_size = max(lim.max_open_zones, lim.max_active_zones);
1566 	if (!pool_size)
1567 		pool_size = min(BLK_ZONE_WPLUG_DEFAULT_POOL_SIZE, nr_seq_zones);
1568 
1569 	mempool_resize(disk->zone_wplugs_pool, pool_size);
1570 
1571 	if (!lim.max_open_zones && !lim.max_active_zones) {
1572 		if (pool_size < nr_seq_zones)
1573 			lim.max_open_zones = pool_size;
1574 		else
1575 			lim.max_open_zones = 0;
1576 	}
1577 
1578 commit:
1579 	return queue_limits_commit_update_frozen(q, &lim);
1580 }
1581 
blk_revalidate_conv_zone(struct blk_zone * zone,unsigned int idx,struct blk_revalidate_zone_args * args)1582 static int blk_revalidate_conv_zone(struct blk_zone *zone, unsigned int idx,
1583 				    struct blk_revalidate_zone_args *args)
1584 {
1585 	struct gendisk *disk = args->disk;
1586 
1587 	if (zone->capacity != zone->len) {
1588 		pr_warn("%s: Invalid conventional zone capacity\n",
1589 			disk->disk_name);
1590 		return -ENODEV;
1591 	}
1592 
1593 	if (disk_zone_is_last(disk, zone))
1594 		args->last_zone_capacity = zone->capacity;
1595 
1596 	if (!disk_need_zone_resources(disk))
1597 		return 0;
1598 
1599 	if (!args->conv_zones_bitmap) {
1600 		args->conv_zones_bitmap =
1601 			bitmap_zalloc(args->nr_zones, GFP_NOIO);
1602 		if (!args->conv_zones_bitmap)
1603 			return -ENOMEM;
1604 	}
1605 
1606 	set_bit(idx, args->conv_zones_bitmap);
1607 
1608 	return 0;
1609 }
1610 
blk_revalidate_seq_zone(struct blk_zone * zone,unsigned int idx,struct blk_revalidate_zone_args * args)1611 static int blk_revalidate_seq_zone(struct blk_zone *zone, unsigned int idx,
1612 				   struct blk_revalidate_zone_args *args)
1613 {
1614 	struct gendisk *disk = args->disk;
1615 	struct blk_zone_wplug *zwplug;
1616 	unsigned int wp_offset;
1617 	unsigned long flags;
1618 
1619 	/*
1620 	 * Remember the capacity of the first sequential zone and check
1621 	 * if it is constant for all zones, ignoring the last zone as it can be
1622 	 * smaller.
1623 	 */
1624 	if (!args->zone_capacity)
1625 		args->zone_capacity = zone->capacity;
1626 	if (disk_zone_is_last(disk, zone)) {
1627 		args->last_zone_capacity = zone->capacity;
1628 	} else if (zone->capacity != args->zone_capacity) {
1629 		pr_warn("%s: Invalid variable zone capacity\n",
1630 			disk->disk_name);
1631 		return -ENODEV;
1632 	}
1633 
1634 	/*
1635 	 * If the device needs zone append emulation, we need to track the
1636 	 * write pointer of all zones that are not empty nor full. So make sure
1637 	 * we have a zone write plug for such zone if the device has a zone
1638 	 * write plug hash table.
1639 	 */
1640 	if (!queue_emulates_zone_append(disk->queue) || !disk->zone_wplugs_hash)
1641 		return 0;
1642 
1643 	disk_zone_wplug_sync_wp_offset(disk, zone);
1644 
1645 	wp_offset = blk_zone_wp_offset(zone);
1646 	if (!wp_offset || wp_offset >= zone->capacity)
1647 		return 0;
1648 
1649 	zwplug = disk_get_and_lock_zone_wplug(disk, zone->wp, GFP_NOIO, &flags);
1650 	if (!zwplug)
1651 		return -ENOMEM;
1652 	spin_unlock_irqrestore(&zwplug->lock, flags);
1653 	disk_put_zone_wplug(zwplug);
1654 
1655 	return 0;
1656 }
1657 
1658 /*
1659  * Helper function to check the validity of zones of a zoned block device.
1660  */
blk_revalidate_zone_cb(struct blk_zone * zone,unsigned int idx,void * data)1661 static int blk_revalidate_zone_cb(struct blk_zone *zone, unsigned int idx,
1662 				  void *data)
1663 {
1664 	struct blk_revalidate_zone_args *args = data;
1665 	struct gendisk *disk = args->disk;
1666 	sector_t zone_sectors = disk->queue->limits.chunk_sectors;
1667 	int ret;
1668 
1669 	/* Check for bad zones and holes in the zone report */
1670 	if (zone->start != args->sector) {
1671 		pr_warn("%s: Zone gap at sectors %llu..%llu\n",
1672 			disk->disk_name, args->sector, zone->start);
1673 		return -ENODEV;
1674 	}
1675 
1676 	if (zone->start >= get_capacity(disk) || !zone->len) {
1677 		pr_warn("%s: Invalid zone start %llu, length %llu\n",
1678 			disk->disk_name, zone->start, zone->len);
1679 		return -ENODEV;
1680 	}
1681 
1682 	if (zone->start == 0) {
1683 		if (zone->len == 0) {
1684 			pr_warn("%s: Invalid zero zone size", disk->disk_name);
1685 			return -ENODEV;
1686 		}
1687 
1688 		/*
1689 		 * Non power-of-2 zone size support was added to remove the gap
1690 		 * between zone capacity and zone size. Though it is technically
1691 		 * possible to have gaps in a non power-of-2 device, Linux
1692 		 * requires the zone size to be equal to zone capacity for non
1693 		 * power-of-2 zoned devices.
1694 		 */
1695 		if (!is_power_of_2(zone->len) && zone->capacity < zone->len) {
1696 			pr_err("%s: Invalid zone capacity %lld with non power-of-2 zone size %lld",
1697 			       disk->disk_name, zone->capacity, zone->len);
1698 			return -ENODEV;
1699 		}
1700 	}
1701 	/*
1702 	 * All zones must have the same size, with the exception on an eventual
1703 	 * smaller last zone.
1704 	 */
1705 	if (!disk_zone_is_last(disk, zone)) {
1706 		if (zone->len != zone_sectors) {
1707 			pr_warn("%s: Invalid zoned device with non constant zone size\n",
1708 				disk->disk_name);
1709 			return -ENODEV;
1710 		}
1711 	} else if (zone->len > zone_sectors) {
1712 		pr_warn("%s: Invalid zoned device with larger last zone size\n",
1713 			disk->disk_name);
1714 		return -ENODEV;
1715 	}
1716 
1717 	if (!zone->capacity || zone->capacity > zone->len) {
1718 		pr_warn("%s: Invalid zone capacity\n",
1719 			disk->disk_name);
1720 		return -ENODEV;
1721 	}
1722 
1723 	/* Check zone type */
1724 	switch (zone->type) {
1725 	case BLK_ZONE_TYPE_CONVENTIONAL:
1726 		ret = blk_revalidate_conv_zone(zone, idx, args);
1727 		break;
1728 	case BLK_ZONE_TYPE_SEQWRITE_REQ:
1729 		ret = blk_revalidate_seq_zone(zone, idx, args);
1730 		break;
1731 	case BLK_ZONE_TYPE_SEQWRITE_PREF:
1732 	default:
1733 		pr_warn("%s: Invalid zone type 0x%x at sectors %llu\n",
1734 			disk->disk_name, (int)zone->type, zone->start);
1735 		ret = -ENODEV;
1736 	}
1737 
1738 	if (!ret)
1739 		args->sector += zone->len;
1740 
1741 	return ret;
1742 }
1743 
1744 /**
1745  * blk_revalidate_disk_zones - (re)allocate and initialize zone write plugs
1746  * @disk:	Target disk
1747  *
1748  * Helper function for low-level device drivers to check, (re) allocate and
1749  * initialize resources used for managing zoned disks. This function should
1750  * normally be called by blk-mq based drivers when a zoned gendisk is probed
1751  * and when the zone configuration of the gendisk changes (e.g. after a format).
1752  * Before calling this function, the device driver must already have set the
1753  * device zone size (chunk_sector limit) and the max zone append limit.
1754  * BIO based drivers can also use this function as long as the device queue
1755  * can be safely frozen.
1756  */
blk_revalidate_disk_zones(struct gendisk * disk)1757 int blk_revalidate_disk_zones(struct gendisk *disk)
1758 {
1759 	struct request_queue *q = disk->queue;
1760 	sector_t zone_sectors = q->limits.chunk_sectors;
1761 	sector_t capacity = get_capacity(disk);
1762 	struct blk_revalidate_zone_args args = { };
1763 	unsigned int noio_flag;
1764 	int ret = -ENOMEM;
1765 
1766 	if (WARN_ON_ONCE(!blk_queue_is_zoned(q)))
1767 		return -EIO;
1768 
1769 	if (!capacity)
1770 		return -ENODEV;
1771 
1772 	/*
1773 	 * Checks that the device driver indicated a valid zone size and that
1774 	 * the max zone append limit is set.
1775 	 */
1776 	if (!zone_sectors) {
1777 		pr_warn("%s: Invalid zone size\n", disk->disk_name);
1778 		return -ENODEV;
1779 	}
1780 
1781 	if (!queue_max_zone_append_sectors(q)) {
1782 		pr_warn("%s: Invalid 0 maximum zone append limit\n",
1783 			disk->disk_name);
1784 		return -ENODEV;
1785 	}
1786 
1787 	/*
1788 	 * Ensure that all memory allocations in this context are done as if
1789 	 * GFP_NOIO was specified.
1790 	 */
1791 	args.disk = disk;
1792 	args.nr_zones = div64_u64(capacity + zone_sectors - 1, zone_sectors);
1793 	noio_flag = memalloc_noio_save();
1794 	ret = disk_revalidate_zone_resources(disk, args.nr_zones);
1795 	if (ret) {
1796 		memalloc_noio_restore(noio_flag);
1797 		return ret;
1798 	}
1799 
1800 	ret = disk->fops->report_zones(disk, 0, UINT_MAX,
1801 				       blk_revalidate_zone_cb, &args);
1802 	if (!ret) {
1803 		pr_warn("%s: No zones reported\n", disk->disk_name);
1804 		ret = -ENODEV;
1805 	}
1806 	memalloc_noio_restore(noio_flag);
1807 
1808 	/*
1809 	 * If zones where reported, make sure that the entire disk capacity
1810 	 * has been checked.
1811 	 */
1812 	if (ret > 0 && args.sector != capacity) {
1813 		pr_warn("%s: Missing zones from sector %llu\n",
1814 			disk->disk_name, args.sector);
1815 		ret = -ENODEV;
1816 	}
1817 
1818 	/*
1819 	 * Set the new disk zone parameters only once the queue is frozen and
1820 	 * all I/Os are completed.
1821 	 */
1822 	if (ret > 0)
1823 		ret = disk_update_zone_resources(disk, &args);
1824 	else
1825 		pr_warn("%s: failed to revalidate zones\n", disk->disk_name);
1826 	if (ret) {
1827 		blk_mq_freeze_queue(q);
1828 		disk_free_zone_resources(disk);
1829 		blk_mq_unfreeze_queue(q);
1830 	}
1831 
1832 	return ret;
1833 }
1834 EXPORT_SYMBOL_GPL(blk_revalidate_disk_zones);
1835 
1836 /**
1837  * blk_zone_issue_zeroout - zero-fill a block range in a zone
1838  * @bdev:	blockdev to write
1839  * @sector:	start sector
1840  * @nr_sects:	number of sectors to write
1841  * @gfp_mask:	memory allocation flags (for bio_alloc)
1842  *
1843  * Description:
1844  *  Zero-fill a block range in a zone (@sector must be equal to the zone write
1845  *  pointer), handling potential errors due to the (initially unknown) lack of
1846  *  hardware offload (See blkdev_issue_zeroout()).
1847  */
blk_zone_issue_zeroout(struct block_device * bdev,sector_t sector,sector_t nr_sects,gfp_t gfp_mask)1848 int blk_zone_issue_zeroout(struct block_device *bdev, sector_t sector,
1849 			   sector_t nr_sects, gfp_t gfp_mask)
1850 {
1851 	int ret;
1852 
1853 	if (WARN_ON_ONCE(!bdev_is_zoned(bdev)))
1854 		return -EIO;
1855 
1856 	ret = blkdev_issue_zeroout(bdev, sector, nr_sects, gfp_mask,
1857 				   BLKDEV_ZERO_NOFALLBACK);
1858 	if (ret != -EOPNOTSUPP)
1859 		return ret;
1860 
1861 	/*
1862 	 * The failed call to blkdev_issue_zeroout() advanced the zone write
1863 	 * pointer. Undo this using a report zone to update the zone write
1864 	 * pointer to the correct current value.
1865 	 */
1866 	ret = disk_zone_sync_wp_offset(bdev->bd_disk, sector);
1867 	if (ret != 1)
1868 		return ret < 0 ? ret : -EIO;
1869 
1870 	/*
1871 	 * Retry without BLKDEV_ZERO_NOFALLBACK to force the fallback to a
1872 	 * regular write with zero-pages.
1873 	 */
1874 	return blkdev_issue_zeroout(bdev, sector, nr_sects, gfp_mask, 0);
1875 }
1876 EXPORT_SYMBOL_GPL(blk_zone_issue_zeroout);
1877 
1878 #ifdef CONFIG_BLK_DEBUG_FS
queue_zone_wplug_show(struct blk_zone_wplug * zwplug,struct seq_file * m)1879 static void queue_zone_wplug_show(struct blk_zone_wplug *zwplug,
1880 				  struct seq_file *m)
1881 {
1882 	unsigned int zwp_wp_offset, zwp_flags;
1883 	unsigned int zwp_zone_no, zwp_ref;
1884 	unsigned int zwp_bio_list_size;
1885 	unsigned long flags;
1886 
1887 	spin_lock_irqsave(&zwplug->lock, flags);
1888 	zwp_zone_no = zwplug->zone_no;
1889 	zwp_flags = zwplug->flags;
1890 	zwp_ref = refcount_read(&zwplug->ref);
1891 	zwp_wp_offset = zwplug->wp_offset;
1892 	zwp_bio_list_size = bio_list_size(&zwplug->bio_list);
1893 	spin_unlock_irqrestore(&zwplug->lock, flags);
1894 
1895 	seq_printf(m, "%u 0x%x %u %u %u\n", zwp_zone_no, zwp_flags, zwp_ref,
1896 		   zwp_wp_offset, zwp_bio_list_size);
1897 }
1898 
queue_zone_wplugs_show(void * data,struct seq_file * m)1899 int queue_zone_wplugs_show(void *data, struct seq_file *m)
1900 {
1901 	struct request_queue *q = data;
1902 	struct gendisk *disk = q->disk;
1903 	struct blk_zone_wplug *zwplug;
1904 	unsigned int i;
1905 
1906 	if (!disk->zone_wplugs_hash)
1907 		return 0;
1908 
1909 	rcu_read_lock();
1910 	for (i = 0; i < disk_zone_wplugs_hash_size(disk); i++)
1911 		hlist_for_each_entry_rcu(zwplug, &disk->zone_wplugs_hash[i],
1912 					 node)
1913 			queue_zone_wplug_show(zwplug, m);
1914 	rcu_read_unlock();
1915 
1916 	return 0;
1917 }
1918 
1919 #endif
1920