xref: /openbmc/linux/drivers/block/null_blk/main.c (revision f4ce3b5d)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Add configfs and memory store: Kyungchan Koh <kkc6196@fb.com> and
4  * Shaohua Li <shli@fb.com>
5  */
6 #include <linux/module.h>
7 
8 #include <linux/moduleparam.h>
9 #include <linux/sched.h>
10 #include <linux/fs.h>
11 #include <linux/init.h>
12 #include "null_blk.h"
13 
14 #undef pr_fmt
15 #define pr_fmt(fmt)	"null_blk: " fmt
16 
17 #define FREE_BATCH		16
18 
19 #define TICKS_PER_SEC		50ULL
20 #define TIMER_INTERVAL		(NSEC_PER_SEC / TICKS_PER_SEC)
21 
22 #ifdef CONFIG_BLK_DEV_NULL_BLK_FAULT_INJECTION
23 static DECLARE_FAULT_ATTR(null_timeout_attr);
24 static DECLARE_FAULT_ATTR(null_requeue_attr);
25 static DECLARE_FAULT_ATTR(null_init_hctx_attr);
26 #endif
27 
28 static inline u64 mb_per_tick(int mbps)
29 {
30 	return (1 << 20) / TICKS_PER_SEC * ((u64) mbps);
31 }
32 
33 /*
34  * Status flags for nullb_device.
35  *
36  * CONFIGURED:	Device has been configured and turned on. Cannot reconfigure.
37  * UP:		Device is currently on and visible in userspace.
38  * THROTTLED:	Device is being throttled.
39  * CACHE:	Device is using a write-back cache.
40  */
41 enum nullb_device_flags {
42 	NULLB_DEV_FL_CONFIGURED	= 0,
43 	NULLB_DEV_FL_UP		= 1,
44 	NULLB_DEV_FL_THROTTLED	= 2,
45 	NULLB_DEV_FL_CACHE	= 3,
46 };
47 
48 #define MAP_SZ		((PAGE_SIZE >> SECTOR_SHIFT) + 2)
49 /*
50  * nullb_page is a page in memory for nullb devices.
51  *
52  * @page:	The page holding the data.
53  * @bitmap:	The bitmap represents which sector in the page has data.
54  *		Each bit represents one block size. For example, sector 8
55  *		will use the 7th bit
56  * The highest 2 bits of bitmap are for special purpose. LOCK means the cache
57  * page is being flushing to storage. FREE means the cache page is freed and
58  * should be skipped from flushing to storage. Please see
59  * null_make_cache_space
60  */
61 struct nullb_page {
62 	struct page *page;
63 	DECLARE_BITMAP(bitmap, MAP_SZ);
64 };
65 #define NULLB_PAGE_LOCK (MAP_SZ - 1)
66 #define NULLB_PAGE_FREE (MAP_SZ - 2)
67 
68 static LIST_HEAD(nullb_list);
69 static struct mutex lock;
70 static int null_major;
71 static DEFINE_IDA(nullb_indexes);
72 static struct blk_mq_tag_set tag_set;
73 
74 enum {
75 	NULL_IRQ_NONE		= 0,
76 	NULL_IRQ_SOFTIRQ	= 1,
77 	NULL_IRQ_TIMER		= 2,
78 };
79 
80 static bool g_virt_boundary = false;
81 module_param_named(virt_boundary, g_virt_boundary, bool, 0444);
82 MODULE_PARM_DESC(virt_boundary, "Require a virtual boundary for the device. Default: False");
83 
84 static int g_no_sched;
85 module_param_named(no_sched, g_no_sched, int, 0444);
86 MODULE_PARM_DESC(no_sched, "No io scheduler");
87 
88 static int g_submit_queues = 1;
89 module_param_named(submit_queues, g_submit_queues, int, 0444);
90 MODULE_PARM_DESC(submit_queues, "Number of submission queues");
91 
92 static int g_poll_queues = 1;
93 module_param_named(poll_queues, g_poll_queues, int, 0444);
94 MODULE_PARM_DESC(poll_queues, "Number of IOPOLL submission queues");
95 
96 static int g_home_node = NUMA_NO_NODE;
97 module_param_named(home_node, g_home_node, int, 0444);
98 MODULE_PARM_DESC(home_node, "Home node for the device");
99 
100 #ifdef CONFIG_BLK_DEV_NULL_BLK_FAULT_INJECTION
101 /*
102  * For more details about fault injection, please refer to
103  * Documentation/fault-injection/fault-injection.rst.
104  */
105 static char g_timeout_str[80];
106 module_param_string(timeout, g_timeout_str, sizeof(g_timeout_str), 0444);
107 MODULE_PARM_DESC(timeout, "Fault injection. timeout=<interval>,<probability>,<space>,<times>");
108 
109 static char g_requeue_str[80];
110 module_param_string(requeue, g_requeue_str, sizeof(g_requeue_str), 0444);
111 MODULE_PARM_DESC(requeue, "Fault injection. requeue=<interval>,<probability>,<space>,<times>");
112 
113 static char g_init_hctx_str[80];
114 module_param_string(init_hctx, g_init_hctx_str, sizeof(g_init_hctx_str), 0444);
115 MODULE_PARM_DESC(init_hctx, "Fault injection to fail hctx init. init_hctx=<interval>,<probability>,<space>,<times>");
116 #endif
117 
118 static int g_queue_mode = NULL_Q_MQ;
119 
120 static int null_param_store_val(const char *str, int *val, int min, int max)
121 {
122 	int ret, new_val;
123 
124 	ret = kstrtoint(str, 10, &new_val);
125 	if (ret)
126 		return -EINVAL;
127 
128 	if (new_val < min || new_val > max)
129 		return -EINVAL;
130 
131 	*val = new_val;
132 	return 0;
133 }
134 
135 static int null_set_queue_mode(const char *str, const struct kernel_param *kp)
136 {
137 	return null_param_store_val(str, &g_queue_mode, NULL_Q_BIO, NULL_Q_MQ);
138 }
139 
140 static const struct kernel_param_ops null_queue_mode_param_ops = {
141 	.set	= null_set_queue_mode,
142 	.get	= param_get_int,
143 };
144 
145 device_param_cb(queue_mode, &null_queue_mode_param_ops, &g_queue_mode, 0444);
146 MODULE_PARM_DESC(queue_mode, "Block interface to use (0=bio,1=rq,2=multiqueue)");
147 
148 static int g_gb = 250;
149 module_param_named(gb, g_gb, int, 0444);
150 MODULE_PARM_DESC(gb, "Size in GB");
151 
152 static int g_bs = 512;
153 module_param_named(bs, g_bs, int, 0444);
154 MODULE_PARM_DESC(bs, "Block size (in bytes)");
155 
156 static int g_max_sectors;
157 module_param_named(max_sectors, g_max_sectors, int, 0444);
158 MODULE_PARM_DESC(max_sectors, "Maximum size of a command (in 512B sectors)");
159 
160 static unsigned int nr_devices = 1;
161 module_param(nr_devices, uint, 0444);
162 MODULE_PARM_DESC(nr_devices, "Number of devices to register");
163 
164 static bool g_blocking;
165 module_param_named(blocking, g_blocking, bool, 0444);
166 MODULE_PARM_DESC(blocking, "Register as a blocking blk-mq driver device");
167 
168 static bool shared_tags;
169 module_param(shared_tags, bool, 0444);
170 MODULE_PARM_DESC(shared_tags, "Share tag set between devices for blk-mq");
171 
172 static bool g_shared_tag_bitmap;
173 module_param_named(shared_tag_bitmap, g_shared_tag_bitmap, bool, 0444);
174 MODULE_PARM_DESC(shared_tag_bitmap, "Use shared tag bitmap for all submission queues for blk-mq");
175 
176 static int g_irqmode = NULL_IRQ_SOFTIRQ;
177 
178 static int null_set_irqmode(const char *str, const struct kernel_param *kp)
179 {
180 	return null_param_store_val(str, &g_irqmode, NULL_IRQ_NONE,
181 					NULL_IRQ_TIMER);
182 }
183 
184 static const struct kernel_param_ops null_irqmode_param_ops = {
185 	.set	= null_set_irqmode,
186 	.get	= param_get_int,
187 };
188 
189 device_param_cb(irqmode, &null_irqmode_param_ops, &g_irqmode, 0444);
190 MODULE_PARM_DESC(irqmode, "IRQ completion handler. 0-none, 1-softirq, 2-timer");
191 
192 static unsigned long g_completion_nsec = 10000;
193 module_param_named(completion_nsec, g_completion_nsec, ulong, 0444);
194 MODULE_PARM_DESC(completion_nsec, "Time in ns to complete a request in hardware. Default: 10,000ns");
195 
196 static int g_hw_queue_depth = 64;
197 module_param_named(hw_queue_depth, g_hw_queue_depth, int, 0444);
198 MODULE_PARM_DESC(hw_queue_depth, "Queue depth for each hardware queue. Default: 64");
199 
200 static bool g_use_per_node_hctx;
201 module_param_named(use_per_node_hctx, g_use_per_node_hctx, bool, 0444);
202 MODULE_PARM_DESC(use_per_node_hctx, "Use per-node allocation for hardware context queues. Default: false");
203 
204 static bool g_memory_backed;
205 module_param_named(memory_backed, g_memory_backed, bool, 0444);
206 MODULE_PARM_DESC(memory_backed, "Create a memory-backed block device. Default: false");
207 
208 static bool g_discard;
209 module_param_named(discard, g_discard, bool, 0444);
210 MODULE_PARM_DESC(discard, "Support discard operations (requires memory-backed null_blk device). Default: false");
211 
212 static unsigned long g_cache_size;
213 module_param_named(cache_size, g_cache_size, ulong, 0444);
214 MODULE_PARM_DESC(mbps, "Cache size in MiB for memory-backed device. Default: 0 (none)");
215 
216 static unsigned int g_mbps;
217 module_param_named(mbps, g_mbps, uint, 0444);
218 MODULE_PARM_DESC(mbps, "Limit maximum bandwidth (in MiB/s). Default: 0 (no limit)");
219 
220 static bool g_zoned;
221 module_param_named(zoned, g_zoned, bool, S_IRUGO);
222 MODULE_PARM_DESC(zoned, "Make device as a host-managed zoned block device. Default: false");
223 
224 static unsigned long g_zone_size = 256;
225 module_param_named(zone_size, g_zone_size, ulong, S_IRUGO);
226 MODULE_PARM_DESC(zone_size, "Zone size in MB when block device is zoned. Must be power-of-two: Default: 256");
227 
228 static unsigned long g_zone_capacity;
229 module_param_named(zone_capacity, g_zone_capacity, ulong, 0444);
230 MODULE_PARM_DESC(zone_capacity, "Zone capacity in MB when block device is zoned. Can be less than or equal to zone size. Default: Zone size");
231 
232 static unsigned int g_zone_nr_conv;
233 module_param_named(zone_nr_conv, g_zone_nr_conv, uint, 0444);
234 MODULE_PARM_DESC(zone_nr_conv, "Number of conventional zones when block device is zoned. Default: 0");
235 
236 static unsigned int g_zone_max_open;
237 module_param_named(zone_max_open, g_zone_max_open, uint, 0444);
238 MODULE_PARM_DESC(zone_max_open, "Maximum number of open zones when block device is zoned. Default: 0 (no limit)");
239 
240 static unsigned int g_zone_max_active;
241 module_param_named(zone_max_active, g_zone_max_active, uint, 0444);
242 MODULE_PARM_DESC(zone_max_active, "Maximum number of active zones when block device is zoned. Default: 0 (no limit)");
243 
244 static struct nullb_device *null_alloc_dev(void);
245 static void null_free_dev(struct nullb_device *dev);
246 static void null_del_dev(struct nullb *nullb);
247 static int null_add_dev(struct nullb_device *dev);
248 static struct nullb *null_find_dev_by_name(const char *name);
249 static void null_free_device_storage(struct nullb_device *dev, bool is_cache);
250 
251 static inline struct nullb_device *to_nullb_device(struct config_item *item)
252 {
253 	return item ? container_of(to_config_group(item), struct nullb_device, group) : NULL;
254 }
255 
256 static inline ssize_t nullb_device_uint_attr_show(unsigned int val, char *page)
257 {
258 	return snprintf(page, PAGE_SIZE, "%u\n", val);
259 }
260 
261 static inline ssize_t nullb_device_ulong_attr_show(unsigned long val,
262 	char *page)
263 {
264 	return snprintf(page, PAGE_SIZE, "%lu\n", val);
265 }
266 
267 static inline ssize_t nullb_device_bool_attr_show(bool val, char *page)
268 {
269 	return snprintf(page, PAGE_SIZE, "%u\n", val);
270 }
271 
272 static ssize_t nullb_device_uint_attr_store(unsigned int *val,
273 	const char *page, size_t count)
274 {
275 	unsigned int tmp;
276 	int result;
277 
278 	result = kstrtouint(page, 0, &tmp);
279 	if (result < 0)
280 		return result;
281 
282 	*val = tmp;
283 	return count;
284 }
285 
286 static ssize_t nullb_device_ulong_attr_store(unsigned long *val,
287 	const char *page, size_t count)
288 {
289 	int result;
290 	unsigned long tmp;
291 
292 	result = kstrtoul(page, 0, &tmp);
293 	if (result < 0)
294 		return result;
295 
296 	*val = tmp;
297 	return count;
298 }
299 
300 static ssize_t nullb_device_bool_attr_store(bool *val, const char *page,
301 	size_t count)
302 {
303 	bool tmp;
304 	int result;
305 
306 	result = kstrtobool(page,  &tmp);
307 	if (result < 0)
308 		return result;
309 
310 	*val = tmp;
311 	return count;
312 }
313 
314 /* The following macro should only be used with TYPE = {uint, ulong, bool}. */
315 #define NULLB_DEVICE_ATTR(NAME, TYPE, APPLY)				\
316 static ssize_t								\
317 nullb_device_##NAME##_show(struct config_item *item, char *page)	\
318 {									\
319 	return nullb_device_##TYPE##_attr_show(				\
320 				to_nullb_device(item)->NAME, page);	\
321 }									\
322 static ssize_t								\
323 nullb_device_##NAME##_store(struct config_item *item, const char *page,	\
324 			    size_t count)				\
325 {									\
326 	int (*apply_fn)(struct nullb_device *dev, TYPE new_value) = APPLY;\
327 	struct nullb_device *dev = to_nullb_device(item);		\
328 	TYPE new_value = 0;						\
329 	int ret;							\
330 									\
331 	ret = nullb_device_##TYPE##_attr_store(&new_value, page, count);\
332 	if (ret < 0)							\
333 		return ret;						\
334 	if (apply_fn)							\
335 		ret = apply_fn(dev, new_value);				\
336 	else if (test_bit(NULLB_DEV_FL_CONFIGURED, &dev->flags)) 	\
337 		ret = -EBUSY;						\
338 	if (ret < 0)							\
339 		return ret;						\
340 	dev->NAME = new_value;						\
341 	return count;							\
342 }									\
343 CONFIGFS_ATTR(nullb_device_, NAME);
344 
345 static int nullb_update_nr_hw_queues(struct nullb_device *dev,
346 				     unsigned int submit_queues,
347 				     unsigned int poll_queues)
348 
349 {
350 	struct blk_mq_tag_set *set;
351 	int ret, nr_hw_queues;
352 
353 	if (!dev->nullb)
354 		return 0;
355 
356 	/*
357 	 * Make sure at least one submit queue exists.
358 	 */
359 	if (!submit_queues)
360 		return -EINVAL;
361 
362 	/*
363 	 * Make sure that null_init_hctx() does not access nullb->queues[] past
364 	 * the end of that array.
365 	 */
366 	if (submit_queues > nr_cpu_ids || poll_queues > g_poll_queues)
367 		return -EINVAL;
368 
369 	/*
370 	 * Keep previous and new queue numbers in nullb_device for reference in
371 	 * the call back function null_map_queues().
372 	 */
373 	dev->prev_submit_queues = dev->submit_queues;
374 	dev->prev_poll_queues = dev->poll_queues;
375 	dev->submit_queues = submit_queues;
376 	dev->poll_queues = poll_queues;
377 
378 	set = dev->nullb->tag_set;
379 	nr_hw_queues = submit_queues + poll_queues;
380 	blk_mq_update_nr_hw_queues(set, nr_hw_queues);
381 	ret = set->nr_hw_queues == nr_hw_queues ? 0 : -ENOMEM;
382 
383 	if (ret) {
384 		/* on error, revert the queue numbers */
385 		dev->submit_queues = dev->prev_submit_queues;
386 		dev->poll_queues = dev->prev_poll_queues;
387 	}
388 
389 	return ret;
390 }
391 
392 static int nullb_apply_submit_queues(struct nullb_device *dev,
393 				     unsigned int submit_queues)
394 {
395 	int ret;
396 
397 	mutex_lock(&lock);
398 	ret = nullb_update_nr_hw_queues(dev, submit_queues, dev->poll_queues);
399 	mutex_unlock(&lock);
400 
401 	return ret;
402 }
403 
404 static int nullb_apply_poll_queues(struct nullb_device *dev,
405 				   unsigned int poll_queues)
406 {
407 	int ret;
408 
409 	mutex_lock(&lock);
410 	ret = nullb_update_nr_hw_queues(dev, dev->submit_queues, poll_queues);
411 	mutex_unlock(&lock);
412 
413 	return ret;
414 }
415 
416 NULLB_DEVICE_ATTR(size, ulong, NULL);
417 NULLB_DEVICE_ATTR(completion_nsec, ulong, NULL);
418 NULLB_DEVICE_ATTR(submit_queues, uint, nullb_apply_submit_queues);
419 NULLB_DEVICE_ATTR(poll_queues, uint, nullb_apply_poll_queues);
420 NULLB_DEVICE_ATTR(home_node, uint, NULL);
421 NULLB_DEVICE_ATTR(queue_mode, uint, NULL);
422 NULLB_DEVICE_ATTR(blocksize, uint, NULL);
423 NULLB_DEVICE_ATTR(max_sectors, uint, NULL);
424 NULLB_DEVICE_ATTR(irqmode, uint, NULL);
425 NULLB_DEVICE_ATTR(hw_queue_depth, uint, NULL);
426 NULLB_DEVICE_ATTR(index, uint, NULL);
427 NULLB_DEVICE_ATTR(blocking, bool, NULL);
428 NULLB_DEVICE_ATTR(use_per_node_hctx, bool, NULL);
429 NULLB_DEVICE_ATTR(memory_backed, bool, NULL);
430 NULLB_DEVICE_ATTR(discard, bool, NULL);
431 NULLB_DEVICE_ATTR(mbps, uint, NULL);
432 NULLB_DEVICE_ATTR(cache_size, ulong, NULL);
433 NULLB_DEVICE_ATTR(zoned, bool, NULL);
434 NULLB_DEVICE_ATTR(zone_size, ulong, NULL);
435 NULLB_DEVICE_ATTR(zone_capacity, ulong, NULL);
436 NULLB_DEVICE_ATTR(zone_nr_conv, uint, NULL);
437 NULLB_DEVICE_ATTR(zone_max_open, uint, NULL);
438 NULLB_DEVICE_ATTR(zone_max_active, uint, NULL);
439 NULLB_DEVICE_ATTR(virt_boundary, bool, NULL);
440 NULLB_DEVICE_ATTR(no_sched, bool, NULL);
441 NULLB_DEVICE_ATTR(shared_tag_bitmap, bool, NULL);
442 
443 static ssize_t nullb_device_power_show(struct config_item *item, char *page)
444 {
445 	return nullb_device_bool_attr_show(to_nullb_device(item)->power, page);
446 }
447 
448 static ssize_t nullb_device_power_store(struct config_item *item,
449 				     const char *page, size_t count)
450 {
451 	struct nullb_device *dev = to_nullb_device(item);
452 	bool newp = false;
453 	ssize_t ret;
454 
455 	ret = nullb_device_bool_attr_store(&newp, page, count);
456 	if (ret < 0)
457 		return ret;
458 
459 	ret = count;
460 	mutex_lock(&lock);
461 	if (!dev->power && newp) {
462 		if (test_and_set_bit(NULLB_DEV_FL_UP, &dev->flags))
463 			goto out;
464 
465 		ret = null_add_dev(dev);
466 		if (ret) {
467 			clear_bit(NULLB_DEV_FL_UP, &dev->flags);
468 			goto out;
469 		}
470 
471 		set_bit(NULLB_DEV_FL_CONFIGURED, &dev->flags);
472 		dev->power = newp;
473 		ret = count;
474 	} else if (dev->power && !newp) {
475 		if (test_and_clear_bit(NULLB_DEV_FL_UP, &dev->flags)) {
476 			dev->power = newp;
477 			null_del_dev(dev->nullb);
478 		}
479 		clear_bit(NULLB_DEV_FL_CONFIGURED, &dev->flags);
480 	}
481 
482 out:
483 	mutex_unlock(&lock);
484 	return ret;
485 }
486 
487 CONFIGFS_ATTR(nullb_device_, power);
488 
489 static ssize_t nullb_device_badblocks_show(struct config_item *item, char *page)
490 {
491 	struct nullb_device *t_dev = to_nullb_device(item);
492 
493 	return badblocks_show(&t_dev->badblocks, page, 0);
494 }
495 
496 static ssize_t nullb_device_badblocks_store(struct config_item *item,
497 				     const char *page, size_t count)
498 {
499 	struct nullb_device *t_dev = to_nullb_device(item);
500 	char *orig, *buf, *tmp;
501 	u64 start, end;
502 	int ret;
503 
504 	orig = kstrndup(page, count, GFP_KERNEL);
505 	if (!orig)
506 		return -ENOMEM;
507 
508 	buf = strstrip(orig);
509 
510 	ret = -EINVAL;
511 	if (buf[0] != '+' && buf[0] != '-')
512 		goto out;
513 	tmp = strchr(&buf[1], '-');
514 	if (!tmp)
515 		goto out;
516 	*tmp = '\0';
517 	ret = kstrtoull(buf + 1, 0, &start);
518 	if (ret)
519 		goto out;
520 	ret = kstrtoull(tmp + 1, 0, &end);
521 	if (ret)
522 		goto out;
523 	ret = -EINVAL;
524 	if (start > end)
525 		goto out;
526 	/* enable badblocks */
527 	cmpxchg(&t_dev->badblocks.shift, -1, 0);
528 	if (buf[0] == '+')
529 		ret = badblocks_set(&t_dev->badblocks, start,
530 			end - start + 1, 1);
531 	else
532 		ret = badblocks_clear(&t_dev->badblocks, start,
533 			end - start + 1);
534 	if (ret == 0)
535 		ret = count;
536 out:
537 	kfree(orig);
538 	return ret;
539 }
540 CONFIGFS_ATTR(nullb_device_, badblocks);
541 
542 static ssize_t nullb_device_zone_readonly_store(struct config_item *item,
543 						const char *page, size_t count)
544 {
545 	struct nullb_device *dev = to_nullb_device(item);
546 
547 	return zone_cond_store(dev, page, count, BLK_ZONE_COND_READONLY);
548 }
549 CONFIGFS_ATTR_WO(nullb_device_, zone_readonly);
550 
551 static ssize_t nullb_device_zone_offline_store(struct config_item *item,
552 					       const char *page, size_t count)
553 {
554 	struct nullb_device *dev = to_nullb_device(item);
555 
556 	return zone_cond_store(dev, page, count, BLK_ZONE_COND_OFFLINE);
557 }
558 CONFIGFS_ATTR_WO(nullb_device_, zone_offline);
559 
560 static struct configfs_attribute *nullb_device_attrs[] = {
561 	&nullb_device_attr_size,
562 	&nullb_device_attr_completion_nsec,
563 	&nullb_device_attr_submit_queues,
564 	&nullb_device_attr_poll_queues,
565 	&nullb_device_attr_home_node,
566 	&nullb_device_attr_queue_mode,
567 	&nullb_device_attr_blocksize,
568 	&nullb_device_attr_max_sectors,
569 	&nullb_device_attr_irqmode,
570 	&nullb_device_attr_hw_queue_depth,
571 	&nullb_device_attr_index,
572 	&nullb_device_attr_blocking,
573 	&nullb_device_attr_use_per_node_hctx,
574 	&nullb_device_attr_power,
575 	&nullb_device_attr_memory_backed,
576 	&nullb_device_attr_discard,
577 	&nullb_device_attr_mbps,
578 	&nullb_device_attr_cache_size,
579 	&nullb_device_attr_badblocks,
580 	&nullb_device_attr_zoned,
581 	&nullb_device_attr_zone_size,
582 	&nullb_device_attr_zone_capacity,
583 	&nullb_device_attr_zone_nr_conv,
584 	&nullb_device_attr_zone_max_open,
585 	&nullb_device_attr_zone_max_active,
586 	&nullb_device_attr_zone_readonly,
587 	&nullb_device_attr_zone_offline,
588 	&nullb_device_attr_virt_boundary,
589 	&nullb_device_attr_no_sched,
590 	&nullb_device_attr_shared_tag_bitmap,
591 	NULL,
592 };
593 
594 static void nullb_device_release(struct config_item *item)
595 {
596 	struct nullb_device *dev = to_nullb_device(item);
597 
598 	null_free_device_storage(dev, false);
599 	null_free_dev(dev);
600 }
601 
602 static struct configfs_item_operations nullb_device_ops = {
603 	.release	= nullb_device_release,
604 };
605 
606 static const struct config_item_type nullb_device_type = {
607 	.ct_item_ops	= &nullb_device_ops,
608 	.ct_attrs	= nullb_device_attrs,
609 	.ct_owner	= THIS_MODULE,
610 };
611 
612 #ifdef CONFIG_BLK_DEV_NULL_BLK_FAULT_INJECTION
613 
614 static void nullb_add_fault_config(struct nullb_device *dev)
615 {
616 	fault_config_init(&dev->timeout_config, "timeout_inject");
617 	fault_config_init(&dev->requeue_config, "requeue_inject");
618 	fault_config_init(&dev->init_hctx_fault_config, "init_hctx_fault_inject");
619 
620 	configfs_add_default_group(&dev->timeout_config.group, &dev->group);
621 	configfs_add_default_group(&dev->requeue_config.group, &dev->group);
622 	configfs_add_default_group(&dev->init_hctx_fault_config.group, &dev->group);
623 }
624 
625 #else
626 
627 static void nullb_add_fault_config(struct nullb_device *dev)
628 {
629 }
630 
631 #endif
632 
633 static struct
634 config_group *nullb_group_make_group(struct config_group *group, const char *name)
635 {
636 	struct nullb_device *dev;
637 
638 	if (null_find_dev_by_name(name))
639 		return ERR_PTR(-EEXIST);
640 
641 	dev = null_alloc_dev();
642 	if (!dev)
643 		return ERR_PTR(-ENOMEM);
644 
645 	config_group_init_type_name(&dev->group, name, &nullb_device_type);
646 	nullb_add_fault_config(dev);
647 
648 	return &dev->group;
649 }
650 
651 static void
652 nullb_group_drop_item(struct config_group *group, struct config_item *item)
653 {
654 	struct nullb_device *dev = to_nullb_device(item);
655 
656 	if (test_and_clear_bit(NULLB_DEV_FL_UP, &dev->flags)) {
657 		mutex_lock(&lock);
658 		dev->power = false;
659 		null_del_dev(dev->nullb);
660 		mutex_unlock(&lock);
661 	}
662 
663 	config_item_put(item);
664 }
665 
666 static ssize_t memb_group_features_show(struct config_item *item, char *page)
667 {
668 	return snprintf(page, PAGE_SIZE,
669 			"badblocks,blocking,blocksize,cache_size,"
670 			"completion_nsec,discard,home_node,hw_queue_depth,"
671 			"irqmode,max_sectors,mbps,memory_backed,no_sched,"
672 			"poll_queues,power,queue_mode,shared_tag_bitmap,size,"
673 			"submit_queues,use_per_node_hctx,virt_boundary,zoned,"
674 			"zone_capacity,zone_max_active,zone_max_open,"
675 			"zone_nr_conv,zone_offline,zone_readonly,zone_size\n");
676 }
677 
678 CONFIGFS_ATTR_RO(memb_group_, features);
679 
680 static struct configfs_attribute *nullb_group_attrs[] = {
681 	&memb_group_attr_features,
682 	NULL,
683 };
684 
685 static struct configfs_group_operations nullb_group_ops = {
686 	.make_group	= nullb_group_make_group,
687 	.drop_item	= nullb_group_drop_item,
688 };
689 
690 static const struct config_item_type nullb_group_type = {
691 	.ct_group_ops	= &nullb_group_ops,
692 	.ct_attrs	= nullb_group_attrs,
693 	.ct_owner	= THIS_MODULE,
694 };
695 
696 static struct configfs_subsystem nullb_subsys = {
697 	.su_group = {
698 		.cg_item = {
699 			.ci_namebuf = "nullb",
700 			.ci_type = &nullb_group_type,
701 		},
702 	},
703 };
704 
705 static inline int null_cache_active(struct nullb *nullb)
706 {
707 	return test_bit(NULLB_DEV_FL_CACHE, &nullb->dev->flags);
708 }
709 
710 static struct nullb_device *null_alloc_dev(void)
711 {
712 	struct nullb_device *dev;
713 
714 	dev = kzalloc(sizeof(*dev), GFP_KERNEL);
715 	if (!dev)
716 		return NULL;
717 
718 #ifdef CONFIG_BLK_DEV_NULL_BLK_FAULT_INJECTION
719 	dev->timeout_config.attr = null_timeout_attr;
720 	dev->requeue_config.attr = null_requeue_attr;
721 	dev->init_hctx_fault_config.attr = null_init_hctx_attr;
722 #endif
723 
724 	INIT_RADIX_TREE(&dev->data, GFP_ATOMIC);
725 	INIT_RADIX_TREE(&dev->cache, GFP_ATOMIC);
726 	if (badblocks_init(&dev->badblocks, 0)) {
727 		kfree(dev);
728 		return NULL;
729 	}
730 
731 	dev->size = g_gb * 1024;
732 	dev->completion_nsec = g_completion_nsec;
733 	dev->submit_queues = g_submit_queues;
734 	dev->prev_submit_queues = g_submit_queues;
735 	dev->poll_queues = g_poll_queues;
736 	dev->prev_poll_queues = g_poll_queues;
737 	dev->home_node = g_home_node;
738 	dev->queue_mode = g_queue_mode;
739 	dev->blocksize = g_bs;
740 	dev->max_sectors = g_max_sectors;
741 	dev->irqmode = g_irqmode;
742 	dev->hw_queue_depth = g_hw_queue_depth;
743 	dev->blocking = g_blocking;
744 	dev->memory_backed = g_memory_backed;
745 	dev->discard = g_discard;
746 	dev->cache_size = g_cache_size;
747 	dev->mbps = g_mbps;
748 	dev->use_per_node_hctx = g_use_per_node_hctx;
749 	dev->zoned = g_zoned;
750 	dev->zone_size = g_zone_size;
751 	dev->zone_capacity = g_zone_capacity;
752 	dev->zone_nr_conv = g_zone_nr_conv;
753 	dev->zone_max_open = g_zone_max_open;
754 	dev->zone_max_active = g_zone_max_active;
755 	dev->virt_boundary = g_virt_boundary;
756 	dev->no_sched = g_no_sched;
757 	dev->shared_tag_bitmap = g_shared_tag_bitmap;
758 	return dev;
759 }
760 
761 static void null_free_dev(struct nullb_device *dev)
762 {
763 	if (!dev)
764 		return;
765 
766 	null_free_zoned_dev(dev);
767 	badblocks_exit(&dev->badblocks);
768 	kfree(dev);
769 }
770 
771 static void put_tag(struct nullb_queue *nq, unsigned int tag)
772 {
773 	clear_bit_unlock(tag, nq->tag_map);
774 
775 	if (waitqueue_active(&nq->wait))
776 		wake_up(&nq->wait);
777 }
778 
779 static unsigned int get_tag(struct nullb_queue *nq)
780 {
781 	unsigned int tag;
782 
783 	do {
784 		tag = find_first_zero_bit(nq->tag_map, nq->queue_depth);
785 		if (tag >= nq->queue_depth)
786 			return -1U;
787 	} while (test_and_set_bit_lock(tag, nq->tag_map));
788 
789 	return tag;
790 }
791 
792 static void free_cmd(struct nullb_cmd *cmd)
793 {
794 	put_tag(cmd->nq, cmd->tag);
795 }
796 
797 static enum hrtimer_restart null_cmd_timer_expired(struct hrtimer *timer);
798 
799 static struct nullb_cmd *__alloc_cmd(struct nullb_queue *nq)
800 {
801 	struct nullb_cmd *cmd;
802 	unsigned int tag;
803 
804 	tag = get_tag(nq);
805 	if (tag != -1U) {
806 		cmd = &nq->cmds[tag];
807 		cmd->tag = tag;
808 		cmd->error = BLK_STS_OK;
809 		cmd->nq = nq;
810 		if (nq->dev->irqmode == NULL_IRQ_TIMER) {
811 			hrtimer_init(&cmd->timer, CLOCK_MONOTONIC,
812 				     HRTIMER_MODE_REL);
813 			cmd->timer.function = null_cmd_timer_expired;
814 		}
815 		return cmd;
816 	}
817 
818 	return NULL;
819 }
820 
821 static struct nullb_cmd *alloc_cmd(struct nullb_queue *nq, struct bio *bio)
822 {
823 	struct nullb_cmd *cmd;
824 	DEFINE_WAIT(wait);
825 
826 	do {
827 		/*
828 		 * This avoids multiple return statements, multiple calls to
829 		 * __alloc_cmd() and a fast path call to prepare_to_wait().
830 		 */
831 		cmd = __alloc_cmd(nq);
832 		if (cmd) {
833 			cmd->bio = bio;
834 			return cmd;
835 		}
836 		prepare_to_wait(&nq->wait, &wait, TASK_UNINTERRUPTIBLE);
837 		io_schedule();
838 		finish_wait(&nq->wait, &wait);
839 	} while (1);
840 }
841 
842 static void end_cmd(struct nullb_cmd *cmd)
843 {
844 	int queue_mode = cmd->nq->dev->queue_mode;
845 
846 	switch (queue_mode)  {
847 	case NULL_Q_MQ:
848 		blk_mq_end_request(cmd->rq, cmd->error);
849 		return;
850 	case NULL_Q_BIO:
851 		cmd->bio->bi_status = cmd->error;
852 		bio_endio(cmd->bio);
853 		break;
854 	}
855 
856 	free_cmd(cmd);
857 }
858 
859 static enum hrtimer_restart null_cmd_timer_expired(struct hrtimer *timer)
860 {
861 	end_cmd(container_of(timer, struct nullb_cmd, timer));
862 
863 	return HRTIMER_NORESTART;
864 }
865 
866 static void null_cmd_end_timer(struct nullb_cmd *cmd)
867 {
868 	ktime_t kt = cmd->nq->dev->completion_nsec;
869 
870 	hrtimer_start(&cmd->timer, kt, HRTIMER_MODE_REL);
871 }
872 
873 static void null_complete_rq(struct request *rq)
874 {
875 	end_cmd(blk_mq_rq_to_pdu(rq));
876 }
877 
878 static struct nullb_page *null_alloc_page(void)
879 {
880 	struct nullb_page *t_page;
881 
882 	t_page = kmalloc(sizeof(struct nullb_page), GFP_NOIO);
883 	if (!t_page)
884 		return NULL;
885 
886 	t_page->page = alloc_pages(GFP_NOIO, 0);
887 	if (!t_page->page) {
888 		kfree(t_page);
889 		return NULL;
890 	}
891 
892 	memset(t_page->bitmap, 0, sizeof(t_page->bitmap));
893 	return t_page;
894 }
895 
896 static void null_free_page(struct nullb_page *t_page)
897 {
898 	__set_bit(NULLB_PAGE_FREE, t_page->bitmap);
899 	if (test_bit(NULLB_PAGE_LOCK, t_page->bitmap))
900 		return;
901 	__free_page(t_page->page);
902 	kfree(t_page);
903 }
904 
905 static bool null_page_empty(struct nullb_page *page)
906 {
907 	int size = MAP_SZ - 2;
908 
909 	return find_first_bit(page->bitmap, size) == size;
910 }
911 
912 static void null_free_sector(struct nullb *nullb, sector_t sector,
913 	bool is_cache)
914 {
915 	unsigned int sector_bit;
916 	u64 idx;
917 	struct nullb_page *t_page, *ret;
918 	struct radix_tree_root *root;
919 
920 	root = is_cache ? &nullb->dev->cache : &nullb->dev->data;
921 	idx = sector >> PAGE_SECTORS_SHIFT;
922 	sector_bit = (sector & SECTOR_MASK);
923 
924 	t_page = radix_tree_lookup(root, idx);
925 	if (t_page) {
926 		__clear_bit(sector_bit, t_page->bitmap);
927 
928 		if (null_page_empty(t_page)) {
929 			ret = radix_tree_delete_item(root, idx, t_page);
930 			WARN_ON(ret != t_page);
931 			null_free_page(ret);
932 			if (is_cache)
933 				nullb->dev->curr_cache -= PAGE_SIZE;
934 		}
935 	}
936 }
937 
938 static struct nullb_page *null_radix_tree_insert(struct nullb *nullb, u64 idx,
939 	struct nullb_page *t_page, bool is_cache)
940 {
941 	struct radix_tree_root *root;
942 
943 	root = is_cache ? &nullb->dev->cache : &nullb->dev->data;
944 
945 	if (radix_tree_insert(root, idx, t_page)) {
946 		null_free_page(t_page);
947 		t_page = radix_tree_lookup(root, idx);
948 		WARN_ON(!t_page || t_page->page->index != idx);
949 	} else if (is_cache)
950 		nullb->dev->curr_cache += PAGE_SIZE;
951 
952 	return t_page;
953 }
954 
955 static void null_free_device_storage(struct nullb_device *dev, bool is_cache)
956 {
957 	unsigned long pos = 0;
958 	int nr_pages;
959 	struct nullb_page *ret, *t_pages[FREE_BATCH];
960 	struct radix_tree_root *root;
961 
962 	root = is_cache ? &dev->cache : &dev->data;
963 
964 	do {
965 		int i;
966 
967 		nr_pages = radix_tree_gang_lookup(root,
968 				(void **)t_pages, pos, FREE_BATCH);
969 
970 		for (i = 0; i < nr_pages; i++) {
971 			pos = t_pages[i]->page->index;
972 			ret = radix_tree_delete_item(root, pos, t_pages[i]);
973 			WARN_ON(ret != t_pages[i]);
974 			null_free_page(ret);
975 		}
976 
977 		pos++;
978 	} while (nr_pages == FREE_BATCH);
979 
980 	if (is_cache)
981 		dev->curr_cache = 0;
982 }
983 
984 static struct nullb_page *__null_lookup_page(struct nullb *nullb,
985 	sector_t sector, bool for_write, bool is_cache)
986 {
987 	unsigned int sector_bit;
988 	u64 idx;
989 	struct nullb_page *t_page;
990 	struct radix_tree_root *root;
991 
992 	idx = sector >> PAGE_SECTORS_SHIFT;
993 	sector_bit = (sector & SECTOR_MASK);
994 
995 	root = is_cache ? &nullb->dev->cache : &nullb->dev->data;
996 	t_page = radix_tree_lookup(root, idx);
997 	WARN_ON(t_page && t_page->page->index != idx);
998 
999 	if (t_page && (for_write || test_bit(sector_bit, t_page->bitmap)))
1000 		return t_page;
1001 
1002 	return NULL;
1003 }
1004 
1005 static struct nullb_page *null_lookup_page(struct nullb *nullb,
1006 	sector_t sector, bool for_write, bool ignore_cache)
1007 {
1008 	struct nullb_page *page = NULL;
1009 
1010 	if (!ignore_cache)
1011 		page = __null_lookup_page(nullb, sector, for_write, true);
1012 	if (page)
1013 		return page;
1014 	return __null_lookup_page(nullb, sector, for_write, false);
1015 }
1016 
1017 static struct nullb_page *null_insert_page(struct nullb *nullb,
1018 					   sector_t sector, bool ignore_cache)
1019 	__releases(&nullb->lock)
1020 	__acquires(&nullb->lock)
1021 {
1022 	u64 idx;
1023 	struct nullb_page *t_page;
1024 
1025 	t_page = null_lookup_page(nullb, sector, true, ignore_cache);
1026 	if (t_page)
1027 		return t_page;
1028 
1029 	spin_unlock_irq(&nullb->lock);
1030 
1031 	t_page = null_alloc_page();
1032 	if (!t_page)
1033 		goto out_lock;
1034 
1035 	if (radix_tree_preload(GFP_NOIO))
1036 		goto out_freepage;
1037 
1038 	spin_lock_irq(&nullb->lock);
1039 	idx = sector >> PAGE_SECTORS_SHIFT;
1040 	t_page->page->index = idx;
1041 	t_page = null_radix_tree_insert(nullb, idx, t_page, !ignore_cache);
1042 	radix_tree_preload_end();
1043 
1044 	return t_page;
1045 out_freepage:
1046 	null_free_page(t_page);
1047 out_lock:
1048 	spin_lock_irq(&nullb->lock);
1049 	return null_lookup_page(nullb, sector, true, ignore_cache);
1050 }
1051 
1052 static int null_flush_cache_page(struct nullb *nullb, struct nullb_page *c_page)
1053 {
1054 	int i;
1055 	unsigned int offset;
1056 	u64 idx;
1057 	struct nullb_page *t_page, *ret;
1058 	void *dst, *src;
1059 
1060 	idx = c_page->page->index;
1061 
1062 	t_page = null_insert_page(nullb, idx << PAGE_SECTORS_SHIFT, true);
1063 
1064 	__clear_bit(NULLB_PAGE_LOCK, c_page->bitmap);
1065 	if (test_bit(NULLB_PAGE_FREE, c_page->bitmap)) {
1066 		null_free_page(c_page);
1067 		if (t_page && null_page_empty(t_page)) {
1068 			ret = radix_tree_delete_item(&nullb->dev->data,
1069 				idx, t_page);
1070 			null_free_page(t_page);
1071 		}
1072 		return 0;
1073 	}
1074 
1075 	if (!t_page)
1076 		return -ENOMEM;
1077 
1078 	src = kmap_local_page(c_page->page);
1079 	dst = kmap_local_page(t_page->page);
1080 
1081 	for (i = 0; i < PAGE_SECTORS;
1082 			i += (nullb->dev->blocksize >> SECTOR_SHIFT)) {
1083 		if (test_bit(i, c_page->bitmap)) {
1084 			offset = (i << SECTOR_SHIFT);
1085 			memcpy(dst + offset, src + offset,
1086 				nullb->dev->blocksize);
1087 			__set_bit(i, t_page->bitmap);
1088 		}
1089 	}
1090 
1091 	kunmap_local(dst);
1092 	kunmap_local(src);
1093 
1094 	ret = radix_tree_delete_item(&nullb->dev->cache, idx, c_page);
1095 	null_free_page(ret);
1096 	nullb->dev->curr_cache -= PAGE_SIZE;
1097 
1098 	return 0;
1099 }
1100 
1101 static int null_make_cache_space(struct nullb *nullb, unsigned long n)
1102 {
1103 	int i, err, nr_pages;
1104 	struct nullb_page *c_pages[FREE_BATCH];
1105 	unsigned long flushed = 0, one_round;
1106 
1107 again:
1108 	if ((nullb->dev->cache_size * 1024 * 1024) >
1109 	     nullb->dev->curr_cache + n || nullb->dev->curr_cache == 0)
1110 		return 0;
1111 
1112 	nr_pages = radix_tree_gang_lookup(&nullb->dev->cache,
1113 			(void **)c_pages, nullb->cache_flush_pos, FREE_BATCH);
1114 	/*
1115 	 * nullb_flush_cache_page could unlock before using the c_pages. To
1116 	 * avoid race, we don't allow page free
1117 	 */
1118 	for (i = 0; i < nr_pages; i++) {
1119 		nullb->cache_flush_pos = c_pages[i]->page->index;
1120 		/*
1121 		 * We found the page which is being flushed to disk by other
1122 		 * threads
1123 		 */
1124 		if (test_bit(NULLB_PAGE_LOCK, c_pages[i]->bitmap))
1125 			c_pages[i] = NULL;
1126 		else
1127 			__set_bit(NULLB_PAGE_LOCK, c_pages[i]->bitmap);
1128 	}
1129 
1130 	one_round = 0;
1131 	for (i = 0; i < nr_pages; i++) {
1132 		if (c_pages[i] == NULL)
1133 			continue;
1134 		err = null_flush_cache_page(nullb, c_pages[i]);
1135 		if (err)
1136 			return err;
1137 		one_round++;
1138 	}
1139 	flushed += one_round << PAGE_SHIFT;
1140 
1141 	if (n > flushed) {
1142 		if (nr_pages == 0)
1143 			nullb->cache_flush_pos = 0;
1144 		if (one_round == 0) {
1145 			/* give other threads a chance */
1146 			spin_unlock_irq(&nullb->lock);
1147 			spin_lock_irq(&nullb->lock);
1148 		}
1149 		goto again;
1150 	}
1151 	return 0;
1152 }
1153 
1154 static int copy_to_nullb(struct nullb *nullb, struct page *source,
1155 	unsigned int off, sector_t sector, size_t n, bool is_fua)
1156 {
1157 	size_t temp, count = 0;
1158 	unsigned int offset;
1159 	struct nullb_page *t_page;
1160 
1161 	while (count < n) {
1162 		temp = min_t(size_t, nullb->dev->blocksize, n - count);
1163 
1164 		if (null_cache_active(nullb) && !is_fua)
1165 			null_make_cache_space(nullb, PAGE_SIZE);
1166 
1167 		offset = (sector & SECTOR_MASK) << SECTOR_SHIFT;
1168 		t_page = null_insert_page(nullb, sector,
1169 			!null_cache_active(nullb) || is_fua);
1170 		if (!t_page)
1171 			return -ENOSPC;
1172 
1173 		memcpy_page(t_page->page, offset, source, off + count, temp);
1174 
1175 		__set_bit(sector & SECTOR_MASK, t_page->bitmap);
1176 
1177 		if (is_fua)
1178 			null_free_sector(nullb, sector, true);
1179 
1180 		count += temp;
1181 		sector += temp >> SECTOR_SHIFT;
1182 	}
1183 	return 0;
1184 }
1185 
1186 static int copy_from_nullb(struct nullb *nullb, struct page *dest,
1187 	unsigned int off, sector_t sector, size_t n)
1188 {
1189 	size_t temp, count = 0;
1190 	unsigned int offset;
1191 	struct nullb_page *t_page;
1192 
1193 	while (count < n) {
1194 		temp = min_t(size_t, nullb->dev->blocksize, n - count);
1195 
1196 		offset = (sector & SECTOR_MASK) << SECTOR_SHIFT;
1197 		t_page = null_lookup_page(nullb, sector, false,
1198 			!null_cache_active(nullb));
1199 
1200 		if (t_page)
1201 			memcpy_page(dest, off + count, t_page->page, offset,
1202 				    temp);
1203 		else
1204 			zero_user(dest, off + count, temp);
1205 
1206 		count += temp;
1207 		sector += temp >> SECTOR_SHIFT;
1208 	}
1209 	return 0;
1210 }
1211 
1212 static void nullb_fill_pattern(struct nullb *nullb, struct page *page,
1213 			       unsigned int len, unsigned int off)
1214 {
1215 	memset_page(page, off, 0xff, len);
1216 }
1217 
1218 blk_status_t null_handle_discard(struct nullb_device *dev,
1219 				 sector_t sector, sector_t nr_sectors)
1220 {
1221 	struct nullb *nullb = dev->nullb;
1222 	size_t n = nr_sectors << SECTOR_SHIFT;
1223 	size_t temp;
1224 
1225 	spin_lock_irq(&nullb->lock);
1226 	while (n > 0) {
1227 		temp = min_t(size_t, n, dev->blocksize);
1228 		null_free_sector(nullb, sector, false);
1229 		if (null_cache_active(nullb))
1230 			null_free_sector(nullb, sector, true);
1231 		sector += temp >> SECTOR_SHIFT;
1232 		n -= temp;
1233 	}
1234 	spin_unlock_irq(&nullb->lock);
1235 
1236 	return BLK_STS_OK;
1237 }
1238 
1239 static int null_handle_flush(struct nullb *nullb)
1240 {
1241 	int err;
1242 
1243 	if (!null_cache_active(nullb))
1244 		return 0;
1245 
1246 	spin_lock_irq(&nullb->lock);
1247 	while (true) {
1248 		err = null_make_cache_space(nullb,
1249 			nullb->dev->cache_size * 1024 * 1024);
1250 		if (err || nullb->dev->curr_cache == 0)
1251 			break;
1252 	}
1253 
1254 	WARN_ON(!radix_tree_empty(&nullb->dev->cache));
1255 	spin_unlock_irq(&nullb->lock);
1256 	return err;
1257 }
1258 
1259 static int null_transfer(struct nullb *nullb, struct page *page,
1260 	unsigned int len, unsigned int off, bool is_write, sector_t sector,
1261 	bool is_fua)
1262 {
1263 	struct nullb_device *dev = nullb->dev;
1264 	unsigned int valid_len = len;
1265 	int err = 0;
1266 
1267 	if (!is_write) {
1268 		if (dev->zoned)
1269 			valid_len = null_zone_valid_read_len(nullb,
1270 				sector, len);
1271 
1272 		if (valid_len) {
1273 			err = copy_from_nullb(nullb, page, off,
1274 				sector, valid_len);
1275 			off += valid_len;
1276 			len -= valid_len;
1277 		}
1278 
1279 		if (len)
1280 			nullb_fill_pattern(nullb, page, len, off);
1281 		flush_dcache_page(page);
1282 	} else {
1283 		flush_dcache_page(page);
1284 		err = copy_to_nullb(nullb, page, off, sector, len, is_fua);
1285 	}
1286 
1287 	return err;
1288 }
1289 
1290 static int null_handle_rq(struct nullb_cmd *cmd)
1291 {
1292 	struct request *rq = cmd->rq;
1293 	struct nullb *nullb = cmd->nq->dev->nullb;
1294 	int err;
1295 	unsigned int len;
1296 	sector_t sector = blk_rq_pos(rq);
1297 	struct req_iterator iter;
1298 	struct bio_vec bvec;
1299 
1300 	spin_lock_irq(&nullb->lock);
1301 	rq_for_each_segment(bvec, rq, iter) {
1302 		len = bvec.bv_len;
1303 		err = null_transfer(nullb, bvec.bv_page, len, bvec.bv_offset,
1304 				     op_is_write(req_op(rq)), sector,
1305 				     rq->cmd_flags & REQ_FUA);
1306 		if (err) {
1307 			spin_unlock_irq(&nullb->lock);
1308 			return err;
1309 		}
1310 		sector += len >> SECTOR_SHIFT;
1311 	}
1312 	spin_unlock_irq(&nullb->lock);
1313 
1314 	return 0;
1315 }
1316 
1317 static int null_handle_bio(struct nullb_cmd *cmd)
1318 {
1319 	struct bio *bio = cmd->bio;
1320 	struct nullb *nullb = cmd->nq->dev->nullb;
1321 	int err;
1322 	unsigned int len;
1323 	sector_t sector = bio->bi_iter.bi_sector;
1324 	struct bio_vec bvec;
1325 	struct bvec_iter iter;
1326 
1327 	spin_lock_irq(&nullb->lock);
1328 	bio_for_each_segment(bvec, bio, iter) {
1329 		len = bvec.bv_len;
1330 		err = null_transfer(nullb, bvec.bv_page, len, bvec.bv_offset,
1331 				     op_is_write(bio_op(bio)), sector,
1332 				     bio->bi_opf & REQ_FUA);
1333 		if (err) {
1334 			spin_unlock_irq(&nullb->lock);
1335 			return err;
1336 		}
1337 		sector += len >> SECTOR_SHIFT;
1338 	}
1339 	spin_unlock_irq(&nullb->lock);
1340 	return 0;
1341 }
1342 
1343 static void null_stop_queue(struct nullb *nullb)
1344 {
1345 	struct request_queue *q = nullb->q;
1346 
1347 	if (nullb->dev->queue_mode == NULL_Q_MQ)
1348 		blk_mq_stop_hw_queues(q);
1349 }
1350 
1351 static void null_restart_queue_async(struct nullb *nullb)
1352 {
1353 	struct request_queue *q = nullb->q;
1354 
1355 	if (nullb->dev->queue_mode == NULL_Q_MQ)
1356 		blk_mq_start_stopped_hw_queues(q, true);
1357 }
1358 
1359 static inline blk_status_t null_handle_throttled(struct nullb_cmd *cmd)
1360 {
1361 	struct nullb_device *dev = cmd->nq->dev;
1362 	struct nullb *nullb = dev->nullb;
1363 	blk_status_t sts = BLK_STS_OK;
1364 	struct request *rq = cmd->rq;
1365 
1366 	if (!hrtimer_active(&nullb->bw_timer))
1367 		hrtimer_restart(&nullb->bw_timer);
1368 
1369 	if (atomic_long_sub_return(blk_rq_bytes(rq), &nullb->cur_bytes) < 0) {
1370 		null_stop_queue(nullb);
1371 		/* race with timer */
1372 		if (atomic_long_read(&nullb->cur_bytes) > 0)
1373 			null_restart_queue_async(nullb);
1374 		/* requeue request */
1375 		sts = BLK_STS_DEV_RESOURCE;
1376 	}
1377 	return sts;
1378 }
1379 
1380 static inline blk_status_t null_handle_badblocks(struct nullb_cmd *cmd,
1381 						 sector_t sector,
1382 						 sector_t nr_sectors)
1383 {
1384 	struct badblocks *bb = &cmd->nq->dev->badblocks;
1385 	sector_t first_bad;
1386 	int bad_sectors;
1387 
1388 	if (badblocks_check(bb, sector, nr_sectors, &first_bad, &bad_sectors))
1389 		return BLK_STS_IOERR;
1390 
1391 	return BLK_STS_OK;
1392 }
1393 
1394 static inline blk_status_t null_handle_memory_backed(struct nullb_cmd *cmd,
1395 						     enum req_op op,
1396 						     sector_t sector,
1397 						     sector_t nr_sectors)
1398 {
1399 	struct nullb_device *dev = cmd->nq->dev;
1400 	int err;
1401 
1402 	if (op == REQ_OP_DISCARD)
1403 		return null_handle_discard(dev, sector, nr_sectors);
1404 
1405 	if (dev->queue_mode == NULL_Q_BIO)
1406 		err = null_handle_bio(cmd);
1407 	else
1408 		err = null_handle_rq(cmd);
1409 
1410 	return errno_to_blk_status(err);
1411 }
1412 
1413 static void nullb_zero_read_cmd_buffer(struct nullb_cmd *cmd)
1414 {
1415 	struct nullb_device *dev = cmd->nq->dev;
1416 	struct bio *bio;
1417 
1418 	if (dev->memory_backed)
1419 		return;
1420 
1421 	if (dev->queue_mode == NULL_Q_BIO && bio_op(cmd->bio) == REQ_OP_READ) {
1422 		zero_fill_bio(cmd->bio);
1423 	} else if (req_op(cmd->rq) == REQ_OP_READ) {
1424 		__rq_for_each_bio(bio, cmd->rq)
1425 			zero_fill_bio(bio);
1426 	}
1427 }
1428 
1429 static inline void nullb_complete_cmd(struct nullb_cmd *cmd)
1430 {
1431 	/*
1432 	 * Since root privileges are required to configure the null_blk
1433 	 * driver, it is fine that this driver does not initialize the
1434 	 * data buffers of read commands. Zero-initialize these buffers
1435 	 * anyway if KMSAN is enabled to prevent that KMSAN complains
1436 	 * about null_blk not initializing read data buffers.
1437 	 */
1438 	if (IS_ENABLED(CONFIG_KMSAN))
1439 		nullb_zero_read_cmd_buffer(cmd);
1440 
1441 	/* Complete IO by inline, softirq or timer */
1442 	switch (cmd->nq->dev->irqmode) {
1443 	case NULL_IRQ_SOFTIRQ:
1444 		switch (cmd->nq->dev->queue_mode) {
1445 		case NULL_Q_MQ:
1446 			blk_mq_complete_request(cmd->rq);
1447 			break;
1448 		case NULL_Q_BIO:
1449 			/*
1450 			 * XXX: no proper submitting cpu information available.
1451 			 */
1452 			end_cmd(cmd);
1453 			break;
1454 		}
1455 		break;
1456 	case NULL_IRQ_NONE:
1457 		end_cmd(cmd);
1458 		break;
1459 	case NULL_IRQ_TIMER:
1460 		null_cmd_end_timer(cmd);
1461 		break;
1462 	}
1463 }
1464 
1465 blk_status_t null_process_cmd(struct nullb_cmd *cmd, enum req_op op,
1466 			      sector_t sector, unsigned int nr_sectors)
1467 {
1468 	struct nullb_device *dev = cmd->nq->dev;
1469 	blk_status_t ret;
1470 
1471 	if (dev->badblocks.shift != -1) {
1472 		ret = null_handle_badblocks(cmd, sector, nr_sectors);
1473 		if (ret != BLK_STS_OK)
1474 			return ret;
1475 	}
1476 
1477 	if (dev->memory_backed)
1478 		return null_handle_memory_backed(cmd, op, sector, nr_sectors);
1479 
1480 	return BLK_STS_OK;
1481 }
1482 
1483 static blk_status_t null_handle_cmd(struct nullb_cmd *cmd, sector_t sector,
1484 				    sector_t nr_sectors, enum req_op op)
1485 {
1486 	struct nullb_device *dev = cmd->nq->dev;
1487 	struct nullb *nullb = dev->nullb;
1488 	blk_status_t sts;
1489 
1490 	if (test_bit(NULLB_DEV_FL_THROTTLED, &dev->flags)) {
1491 		sts = null_handle_throttled(cmd);
1492 		if (sts != BLK_STS_OK)
1493 			return sts;
1494 	}
1495 
1496 	if (op == REQ_OP_FLUSH) {
1497 		cmd->error = errno_to_blk_status(null_handle_flush(nullb));
1498 		goto out;
1499 	}
1500 
1501 	if (dev->zoned)
1502 		sts = null_process_zoned_cmd(cmd, op, sector, nr_sectors);
1503 	else
1504 		sts = null_process_cmd(cmd, op, sector, nr_sectors);
1505 
1506 	/* Do not overwrite errors (e.g. timeout errors) */
1507 	if (cmd->error == BLK_STS_OK)
1508 		cmd->error = sts;
1509 
1510 out:
1511 	nullb_complete_cmd(cmd);
1512 	return BLK_STS_OK;
1513 }
1514 
1515 static enum hrtimer_restart nullb_bwtimer_fn(struct hrtimer *timer)
1516 {
1517 	struct nullb *nullb = container_of(timer, struct nullb, bw_timer);
1518 	ktime_t timer_interval = ktime_set(0, TIMER_INTERVAL);
1519 	unsigned int mbps = nullb->dev->mbps;
1520 
1521 	if (atomic_long_read(&nullb->cur_bytes) == mb_per_tick(mbps))
1522 		return HRTIMER_NORESTART;
1523 
1524 	atomic_long_set(&nullb->cur_bytes, mb_per_tick(mbps));
1525 	null_restart_queue_async(nullb);
1526 
1527 	hrtimer_forward_now(&nullb->bw_timer, timer_interval);
1528 
1529 	return HRTIMER_RESTART;
1530 }
1531 
1532 static void nullb_setup_bwtimer(struct nullb *nullb)
1533 {
1534 	ktime_t timer_interval = ktime_set(0, TIMER_INTERVAL);
1535 
1536 	hrtimer_init(&nullb->bw_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
1537 	nullb->bw_timer.function = nullb_bwtimer_fn;
1538 	atomic_long_set(&nullb->cur_bytes, mb_per_tick(nullb->dev->mbps));
1539 	hrtimer_start(&nullb->bw_timer, timer_interval, HRTIMER_MODE_REL);
1540 }
1541 
1542 static struct nullb_queue *nullb_to_queue(struct nullb *nullb)
1543 {
1544 	int index = 0;
1545 
1546 	if (nullb->nr_queues != 1)
1547 		index = raw_smp_processor_id() / ((nr_cpu_ids + nullb->nr_queues - 1) / nullb->nr_queues);
1548 
1549 	return &nullb->queues[index];
1550 }
1551 
1552 static void null_submit_bio(struct bio *bio)
1553 {
1554 	sector_t sector = bio->bi_iter.bi_sector;
1555 	sector_t nr_sectors = bio_sectors(bio);
1556 	struct nullb *nullb = bio->bi_bdev->bd_disk->private_data;
1557 	struct nullb_queue *nq = nullb_to_queue(nullb);
1558 
1559 	null_handle_cmd(alloc_cmd(nq, bio), sector, nr_sectors, bio_op(bio));
1560 }
1561 
1562 #ifdef CONFIG_BLK_DEV_NULL_BLK_FAULT_INJECTION
1563 
1564 static bool should_timeout_request(struct request *rq)
1565 {
1566 	struct nullb_cmd *cmd = blk_mq_rq_to_pdu(rq);
1567 	struct nullb_device *dev = cmd->nq->dev;
1568 
1569 	return should_fail(&dev->timeout_config.attr, 1);
1570 }
1571 
1572 static bool should_requeue_request(struct request *rq)
1573 {
1574 	struct nullb_cmd *cmd = blk_mq_rq_to_pdu(rq);
1575 	struct nullb_device *dev = cmd->nq->dev;
1576 
1577 	return should_fail(&dev->requeue_config.attr, 1);
1578 }
1579 
1580 static bool should_init_hctx_fail(struct nullb_device *dev)
1581 {
1582 	return should_fail(&dev->init_hctx_fault_config.attr, 1);
1583 }
1584 
1585 #else
1586 
1587 static bool should_timeout_request(struct request *rq)
1588 {
1589 	return false;
1590 }
1591 
1592 static bool should_requeue_request(struct request *rq)
1593 {
1594 	return false;
1595 }
1596 
1597 static bool should_init_hctx_fail(struct nullb_device *dev)
1598 {
1599 	return false;
1600 }
1601 
1602 #endif
1603 
1604 static void null_map_queues(struct blk_mq_tag_set *set)
1605 {
1606 	struct nullb *nullb = set->driver_data;
1607 	int i, qoff;
1608 	unsigned int submit_queues = g_submit_queues;
1609 	unsigned int poll_queues = g_poll_queues;
1610 
1611 	if (nullb) {
1612 		struct nullb_device *dev = nullb->dev;
1613 
1614 		/*
1615 		 * Refer nr_hw_queues of the tag set to check if the expected
1616 		 * number of hardware queues are prepared. If block layer failed
1617 		 * to prepare them, use previous numbers of submit queues and
1618 		 * poll queues to map queues.
1619 		 */
1620 		if (set->nr_hw_queues ==
1621 		    dev->submit_queues + dev->poll_queues) {
1622 			submit_queues = dev->submit_queues;
1623 			poll_queues = dev->poll_queues;
1624 		} else if (set->nr_hw_queues ==
1625 			   dev->prev_submit_queues + dev->prev_poll_queues) {
1626 			submit_queues = dev->prev_submit_queues;
1627 			poll_queues = dev->prev_poll_queues;
1628 		} else {
1629 			pr_warn("tag set has unexpected nr_hw_queues: %d\n",
1630 				set->nr_hw_queues);
1631 			WARN_ON_ONCE(true);
1632 			submit_queues = 1;
1633 			poll_queues = 0;
1634 		}
1635 	}
1636 
1637 	for (i = 0, qoff = 0; i < set->nr_maps; i++) {
1638 		struct blk_mq_queue_map *map = &set->map[i];
1639 
1640 		switch (i) {
1641 		case HCTX_TYPE_DEFAULT:
1642 			map->nr_queues = submit_queues;
1643 			break;
1644 		case HCTX_TYPE_READ:
1645 			map->nr_queues = 0;
1646 			continue;
1647 		case HCTX_TYPE_POLL:
1648 			map->nr_queues = poll_queues;
1649 			break;
1650 		}
1651 		map->queue_offset = qoff;
1652 		qoff += map->nr_queues;
1653 		blk_mq_map_queues(map);
1654 	}
1655 }
1656 
1657 static int null_poll(struct blk_mq_hw_ctx *hctx, struct io_comp_batch *iob)
1658 {
1659 	struct nullb_queue *nq = hctx->driver_data;
1660 	LIST_HEAD(list);
1661 	int nr = 0;
1662 	struct request *rq;
1663 
1664 	spin_lock(&nq->poll_lock);
1665 	list_splice_init(&nq->poll_list, &list);
1666 	list_for_each_entry(rq, &list, queuelist)
1667 		blk_mq_set_request_complete(rq);
1668 	spin_unlock(&nq->poll_lock);
1669 
1670 	while (!list_empty(&list)) {
1671 		struct nullb_cmd *cmd;
1672 		struct request *req;
1673 
1674 		req = list_first_entry(&list, struct request, queuelist);
1675 		list_del_init(&req->queuelist);
1676 		cmd = blk_mq_rq_to_pdu(req);
1677 		cmd->error = null_process_cmd(cmd, req_op(req), blk_rq_pos(req),
1678 						blk_rq_sectors(req));
1679 		if (!blk_mq_add_to_batch(req, iob, (__force int) cmd->error,
1680 					blk_mq_end_request_batch))
1681 			end_cmd(cmd);
1682 		nr++;
1683 	}
1684 
1685 	return nr;
1686 }
1687 
1688 static enum blk_eh_timer_return null_timeout_rq(struct request *rq)
1689 {
1690 	struct blk_mq_hw_ctx *hctx = rq->mq_hctx;
1691 	struct nullb_cmd *cmd = blk_mq_rq_to_pdu(rq);
1692 
1693 	if (hctx->type == HCTX_TYPE_POLL) {
1694 		struct nullb_queue *nq = hctx->driver_data;
1695 
1696 		spin_lock(&nq->poll_lock);
1697 		/* The request may have completed meanwhile. */
1698 		if (blk_mq_request_completed(rq)) {
1699 			spin_unlock(&nq->poll_lock);
1700 			return BLK_EH_DONE;
1701 		}
1702 		list_del_init(&rq->queuelist);
1703 		spin_unlock(&nq->poll_lock);
1704 	}
1705 
1706 	pr_info("rq %p timed out\n", rq);
1707 
1708 	/*
1709 	 * If the device is marked as blocking (i.e. memory backed or zoned
1710 	 * device), the submission path may be blocked waiting for resources
1711 	 * and cause real timeouts. For these real timeouts, the submission
1712 	 * path will complete the request using blk_mq_complete_request().
1713 	 * Only fake timeouts need to execute blk_mq_complete_request() here.
1714 	 */
1715 	cmd->error = BLK_STS_TIMEOUT;
1716 	if (cmd->fake_timeout || hctx->type == HCTX_TYPE_POLL)
1717 		blk_mq_complete_request(rq);
1718 	return BLK_EH_DONE;
1719 }
1720 
1721 static blk_status_t null_queue_rq(struct blk_mq_hw_ctx *hctx,
1722 				  const struct blk_mq_queue_data *bd)
1723 {
1724 	struct request *rq = bd->rq;
1725 	struct nullb_cmd *cmd = blk_mq_rq_to_pdu(rq);
1726 	struct nullb_queue *nq = hctx->driver_data;
1727 	sector_t nr_sectors = blk_rq_sectors(rq);
1728 	sector_t sector = blk_rq_pos(rq);
1729 	const bool is_poll = hctx->type == HCTX_TYPE_POLL;
1730 
1731 	might_sleep_if(hctx->flags & BLK_MQ_F_BLOCKING);
1732 
1733 	if (!is_poll && nq->dev->irqmode == NULL_IRQ_TIMER) {
1734 		hrtimer_init(&cmd->timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
1735 		cmd->timer.function = null_cmd_timer_expired;
1736 	}
1737 	cmd->rq = rq;
1738 	cmd->error = BLK_STS_OK;
1739 	cmd->nq = nq;
1740 	cmd->fake_timeout = should_timeout_request(rq) ||
1741 		blk_should_fake_timeout(rq->q);
1742 
1743 	blk_mq_start_request(rq);
1744 
1745 	if (should_requeue_request(rq)) {
1746 		/*
1747 		 * Alternate between hitting the core BUSY path, and the
1748 		 * driver driven requeue path
1749 		 */
1750 		nq->requeue_selection++;
1751 		if (nq->requeue_selection & 1)
1752 			return BLK_STS_RESOURCE;
1753 		blk_mq_requeue_request(rq, true);
1754 		return BLK_STS_OK;
1755 	}
1756 
1757 	if (is_poll) {
1758 		spin_lock(&nq->poll_lock);
1759 		list_add_tail(&rq->queuelist, &nq->poll_list);
1760 		spin_unlock(&nq->poll_lock);
1761 		return BLK_STS_OK;
1762 	}
1763 	if (cmd->fake_timeout)
1764 		return BLK_STS_OK;
1765 
1766 	return null_handle_cmd(cmd, sector, nr_sectors, req_op(rq));
1767 }
1768 
1769 static void cleanup_queue(struct nullb_queue *nq)
1770 {
1771 	bitmap_free(nq->tag_map);
1772 	kfree(nq->cmds);
1773 }
1774 
1775 static void cleanup_queues(struct nullb *nullb)
1776 {
1777 	int i;
1778 
1779 	for (i = 0; i < nullb->nr_queues; i++)
1780 		cleanup_queue(&nullb->queues[i]);
1781 
1782 	kfree(nullb->queues);
1783 }
1784 
1785 static void null_exit_hctx(struct blk_mq_hw_ctx *hctx, unsigned int hctx_idx)
1786 {
1787 	struct nullb_queue *nq = hctx->driver_data;
1788 	struct nullb *nullb = nq->dev->nullb;
1789 
1790 	nullb->nr_queues--;
1791 }
1792 
1793 static void null_init_queue(struct nullb *nullb, struct nullb_queue *nq)
1794 {
1795 	init_waitqueue_head(&nq->wait);
1796 	nq->queue_depth = nullb->queue_depth;
1797 	nq->dev = nullb->dev;
1798 	INIT_LIST_HEAD(&nq->poll_list);
1799 	spin_lock_init(&nq->poll_lock);
1800 }
1801 
1802 static int null_init_hctx(struct blk_mq_hw_ctx *hctx, void *driver_data,
1803 			  unsigned int hctx_idx)
1804 {
1805 	struct nullb *nullb = hctx->queue->queuedata;
1806 	struct nullb_queue *nq;
1807 
1808 	if (should_init_hctx_fail(nullb->dev))
1809 		return -EFAULT;
1810 
1811 	nq = &nullb->queues[hctx_idx];
1812 	hctx->driver_data = nq;
1813 	null_init_queue(nullb, nq);
1814 	nullb->nr_queues++;
1815 
1816 	return 0;
1817 }
1818 
1819 static const struct blk_mq_ops null_mq_ops = {
1820 	.queue_rq       = null_queue_rq,
1821 	.complete	= null_complete_rq,
1822 	.timeout	= null_timeout_rq,
1823 	.poll		= null_poll,
1824 	.map_queues	= null_map_queues,
1825 	.init_hctx	= null_init_hctx,
1826 	.exit_hctx	= null_exit_hctx,
1827 };
1828 
1829 static void null_del_dev(struct nullb *nullb)
1830 {
1831 	struct nullb_device *dev;
1832 
1833 	if (!nullb)
1834 		return;
1835 
1836 	dev = nullb->dev;
1837 
1838 	ida_free(&nullb_indexes, nullb->index);
1839 
1840 	list_del_init(&nullb->list);
1841 
1842 	del_gendisk(nullb->disk);
1843 
1844 	if (test_bit(NULLB_DEV_FL_THROTTLED, &nullb->dev->flags)) {
1845 		hrtimer_cancel(&nullb->bw_timer);
1846 		atomic_long_set(&nullb->cur_bytes, LONG_MAX);
1847 		null_restart_queue_async(nullb);
1848 	}
1849 
1850 	put_disk(nullb->disk);
1851 	if (dev->queue_mode == NULL_Q_MQ &&
1852 	    nullb->tag_set == &nullb->__tag_set)
1853 		blk_mq_free_tag_set(nullb->tag_set);
1854 	cleanup_queues(nullb);
1855 	if (null_cache_active(nullb))
1856 		null_free_device_storage(nullb->dev, true);
1857 	kfree(nullb);
1858 	dev->nullb = NULL;
1859 }
1860 
1861 static void null_config_discard(struct nullb *nullb)
1862 {
1863 	if (nullb->dev->discard == false)
1864 		return;
1865 
1866 	if (!nullb->dev->memory_backed) {
1867 		nullb->dev->discard = false;
1868 		pr_info("discard option is ignored without memory backing\n");
1869 		return;
1870 	}
1871 
1872 	if (nullb->dev->zoned) {
1873 		nullb->dev->discard = false;
1874 		pr_info("discard option is ignored in zoned mode\n");
1875 		return;
1876 	}
1877 
1878 	nullb->q->limits.discard_granularity = nullb->dev->blocksize;
1879 	blk_queue_max_discard_sectors(nullb->q, UINT_MAX >> 9);
1880 }
1881 
1882 static const struct block_device_operations null_bio_ops = {
1883 	.owner		= THIS_MODULE,
1884 	.submit_bio	= null_submit_bio,
1885 	.report_zones	= null_report_zones,
1886 };
1887 
1888 static const struct block_device_operations null_rq_ops = {
1889 	.owner		= THIS_MODULE,
1890 	.report_zones	= null_report_zones,
1891 };
1892 
1893 static int setup_commands(struct nullb_queue *nq)
1894 {
1895 	struct nullb_cmd *cmd;
1896 	int i;
1897 
1898 	nq->cmds = kcalloc(nq->queue_depth, sizeof(*cmd), GFP_KERNEL);
1899 	if (!nq->cmds)
1900 		return -ENOMEM;
1901 
1902 	nq->tag_map = bitmap_zalloc(nq->queue_depth, GFP_KERNEL);
1903 	if (!nq->tag_map) {
1904 		kfree(nq->cmds);
1905 		return -ENOMEM;
1906 	}
1907 
1908 	for (i = 0; i < nq->queue_depth; i++) {
1909 		cmd = &nq->cmds[i];
1910 		cmd->tag = -1U;
1911 	}
1912 
1913 	return 0;
1914 }
1915 
1916 static int setup_queues(struct nullb *nullb)
1917 {
1918 	int nqueues = nr_cpu_ids;
1919 
1920 	if (g_poll_queues)
1921 		nqueues += g_poll_queues;
1922 
1923 	nullb->queues = kcalloc(nqueues, sizeof(struct nullb_queue),
1924 				GFP_KERNEL);
1925 	if (!nullb->queues)
1926 		return -ENOMEM;
1927 
1928 	nullb->queue_depth = nullb->dev->hw_queue_depth;
1929 	return 0;
1930 }
1931 
1932 static int init_driver_queues(struct nullb *nullb)
1933 {
1934 	struct nullb_queue *nq;
1935 	int i, ret = 0;
1936 
1937 	for (i = 0; i < nullb->dev->submit_queues; i++) {
1938 		nq = &nullb->queues[i];
1939 
1940 		null_init_queue(nullb, nq);
1941 
1942 		ret = setup_commands(nq);
1943 		if (ret)
1944 			return ret;
1945 		nullb->nr_queues++;
1946 	}
1947 	return 0;
1948 }
1949 
1950 static int null_gendisk_register(struct nullb *nullb)
1951 {
1952 	sector_t size = ((sector_t)nullb->dev->size * SZ_1M) >> SECTOR_SHIFT;
1953 	struct gendisk *disk = nullb->disk;
1954 
1955 	set_capacity(disk, size);
1956 
1957 	disk->major		= null_major;
1958 	disk->first_minor	= nullb->index;
1959 	disk->minors		= 1;
1960 	if (queue_is_mq(nullb->q))
1961 		disk->fops		= &null_rq_ops;
1962 	else
1963 		disk->fops		= &null_bio_ops;
1964 	disk->private_data	= nullb;
1965 	strncpy(disk->disk_name, nullb->disk_name, DISK_NAME_LEN);
1966 
1967 	if (nullb->dev->zoned) {
1968 		int ret = null_register_zoned_dev(nullb);
1969 
1970 		if (ret)
1971 			return ret;
1972 	}
1973 
1974 	return add_disk(disk);
1975 }
1976 
1977 static int null_init_tag_set(struct nullb *nullb, struct blk_mq_tag_set *set)
1978 {
1979 	unsigned int flags = BLK_MQ_F_SHOULD_MERGE;
1980 	int hw_queues, numa_node;
1981 	unsigned int queue_depth;
1982 	int poll_queues;
1983 
1984 	if (nullb) {
1985 		hw_queues = nullb->dev->submit_queues;
1986 		poll_queues = nullb->dev->poll_queues;
1987 		queue_depth = nullb->dev->hw_queue_depth;
1988 		numa_node = nullb->dev->home_node;
1989 		if (nullb->dev->no_sched)
1990 			flags |= BLK_MQ_F_NO_SCHED;
1991 		if (nullb->dev->shared_tag_bitmap)
1992 			flags |= BLK_MQ_F_TAG_HCTX_SHARED;
1993 		if (nullb->dev->blocking)
1994 			flags |= BLK_MQ_F_BLOCKING;
1995 	} else {
1996 		hw_queues = g_submit_queues;
1997 		poll_queues = g_poll_queues;
1998 		queue_depth = g_hw_queue_depth;
1999 		numa_node = g_home_node;
2000 		if (g_no_sched)
2001 			flags |= BLK_MQ_F_NO_SCHED;
2002 		if (g_shared_tag_bitmap)
2003 			flags |= BLK_MQ_F_TAG_HCTX_SHARED;
2004 		if (g_blocking)
2005 			flags |= BLK_MQ_F_BLOCKING;
2006 	}
2007 
2008 	set->ops = &null_mq_ops;
2009 	set->cmd_size	= sizeof(struct nullb_cmd);
2010 	set->flags = flags;
2011 	set->driver_data = nullb;
2012 	set->nr_hw_queues = hw_queues;
2013 	set->queue_depth = queue_depth;
2014 	set->numa_node = numa_node;
2015 	if (poll_queues) {
2016 		set->nr_hw_queues += poll_queues;
2017 		set->nr_maps = 3;
2018 	} else {
2019 		set->nr_maps = 1;
2020 	}
2021 
2022 	return blk_mq_alloc_tag_set(set);
2023 }
2024 
2025 static int null_validate_conf(struct nullb_device *dev)
2026 {
2027 	if (dev->queue_mode == NULL_Q_RQ) {
2028 		pr_err("legacy IO path is no longer available\n");
2029 		return -EINVAL;
2030 	}
2031 
2032 	if (blk_validate_block_size(dev->blocksize))
2033 		return -EINVAL;
2034 
2035 	if (dev->queue_mode == NULL_Q_MQ && dev->use_per_node_hctx) {
2036 		if (dev->submit_queues != nr_online_nodes)
2037 			dev->submit_queues = nr_online_nodes;
2038 	} else if (dev->submit_queues > nr_cpu_ids)
2039 		dev->submit_queues = nr_cpu_ids;
2040 	else if (dev->submit_queues == 0)
2041 		dev->submit_queues = 1;
2042 	dev->prev_submit_queues = dev->submit_queues;
2043 
2044 	if (dev->poll_queues > g_poll_queues)
2045 		dev->poll_queues = g_poll_queues;
2046 	dev->prev_poll_queues = dev->poll_queues;
2047 
2048 	dev->queue_mode = min_t(unsigned int, dev->queue_mode, NULL_Q_MQ);
2049 	dev->irqmode = min_t(unsigned int, dev->irqmode, NULL_IRQ_TIMER);
2050 
2051 	/* Do memory allocation, so set blocking */
2052 	if (dev->memory_backed)
2053 		dev->blocking = true;
2054 	else /* cache is meaningless */
2055 		dev->cache_size = 0;
2056 	dev->cache_size = min_t(unsigned long, ULONG_MAX / 1024 / 1024,
2057 						dev->cache_size);
2058 	dev->mbps = min_t(unsigned int, 1024 * 40, dev->mbps);
2059 	/* can not stop a queue */
2060 	if (dev->queue_mode == NULL_Q_BIO)
2061 		dev->mbps = 0;
2062 
2063 	if (dev->zoned &&
2064 	    (!dev->zone_size || !is_power_of_2(dev->zone_size))) {
2065 		pr_err("zone_size must be power-of-two\n");
2066 		return -EINVAL;
2067 	}
2068 
2069 	return 0;
2070 }
2071 
2072 #ifdef CONFIG_BLK_DEV_NULL_BLK_FAULT_INJECTION
2073 static bool __null_setup_fault(struct fault_attr *attr, char *str)
2074 {
2075 	if (!str[0])
2076 		return true;
2077 
2078 	if (!setup_fault_attr(attr, str))
2079 		return false;
2080 
2081 	attr->verbose = 0;
2082 	return true;
2083 }
2084 #endif
2085 
2086 static bool null_setup_fault(void)
2087 {
2088 #ifdef CONFIG_BLK_DEV_NULL_BLK_FAULT_INJECTION
2089 	if (!__null_setup_fault(&null_timeout_attr, g_timeout_str))
2090 		return false;
2091 	if (!__null_setup_fault(&null_requeue_attr, g_requeue_str))
2092 		return false;
2093 	if (!__null_setup_fault(&null_init_hctx_attr, g_init_hctx_str))
2094 		return false;
2095 #endif
2096 	return true;
2097 }
2098 
2099 static int null_add_dev(struct nullb_device *dev)
2100 {
2101 	struct nullb *nullb;
2102 	int rv;
2103 
2104 	rv = null_validate_conf(dev);
2105 	if (rv)
2106 		return rv;
2107 
2108 	nullb = kzalloc_node(sizeof(*nullb), GFP_KERNEL, dev->home_node);
2109 	if (!nullb) {
2110 		rv = -ENOMEM;
2111 		goto out;
2112 	}
2113 	nullb->dev = dev;
2114 	dev->nullb = nullb;
2115 
2116 	spin_lock_init(&nullb->lock);
2117 
2118 	rv = setup_queues(nullb);
2119 	if (rv)
2120 		goto out_free_nullb;
2121 
2122 	if (dev->queue_mode == NULL_Q_MQ) {
2123 		if (shared_tags) {
2124 			nullb->tag_set = &tag_set;
2125 			rv = 0;
2126 		} else {
2127 			nullb->tag_set = &nullb->__tag_set;
2128 			rv = null_init_tag_set(nullb, nullb->tag_set);
2129 		}
2130 
2131 		if (rv)
2132 			goto out_cleanup_queues;
2133 
2134 		nullb->tag_set->timeout = 5 * HZ;
2135 		nullb->disk = blk_mq_alloc_disk(nullb->tag_set, nullb);
2136 		if (IS_ERR(nullb->disk)) {
2137 			rv = PTR_ERR(nullb->disk);
2138 			goto out_cleanup_tags;
2139 		}
2140 		nullb->q = nullb->disk->queue;
2141 	} else if (dev->queue_mode == NULL_Q_BIO) {
2142 		rv = -ENOMEM;
2143 		nullb->disk = blk_alloc_disk(nullb->dev->home_node);
2144 		if (!nullb->disk)
2145 			goto out_cleanup_queues;
2146 
2147 		nullb->q = nullb->disk->queue;
2148 		rv = init_driver_queues(nullb);
2149 		if (rv)
2150 			goto out_cleanup_disk;
2151 	}
2152 
2153 	if (dev->mbps) {
2154 		set_bit(NULLB_DEV_FL_THROTTLED, &dev->flags);
2155 		nullb_setup_bwtimer(nullb);
2156 	}
2157 
2158 	if (dev->cache_size > 0) {
2159 		set_bit(NULLB_DEV_FL_CACHE, &nullb->dev->flags);
2160 		blk_queue_write_cache(nullb->q, true, true);
2161 	}
2162 
2163 	if (dev->zoned) {
2164 		rv = null_init_zoned_dev(dev, nullb->q);
2165 		if (rv)
2166 			goto out_cleanup_disk;
2167 	}
2168 
2169 	nullb->q->queuedata = nullb;
2170 	blk_queue_flag_set(QUEUE_FLAG_NONROT, nullb->q);
2171 
2172 	rv = ida_alloc(&nullb_indexes, GFP_KERNEL);
2173 	if (rv < 0)
2174 		goto out_cleanup_zone;
2175 
2176 	nullb->index = rv;
2177 	dev->index = rv;
2178 
2179 	blk_queue_logical_block_size(nullb->q, dev->blocksize);
2180 	blk_queue_physical_block_size(nullb->q, dev->blocksize);
2181 	if (dev->max_sectors)
2182 		blk_queue_max_hw_sectors(nullb->q, dev->max_sectors);
2183 
2184 	if (dev->virt_boundary)
2185 		blk_queue_virt_boundary(nullb->q, PAGE_SIZE - 1);
2186 
2187 	null_config_discard(nullb);
2188 
2189 	if (config_item_name(&dev->group.cg_item)) {
2190 		/* Use configfs dir name as the device name */
2191 		snprintf(nullb->disk_name, sizeof(nullb->disk_name),
2192 			 "%s", config_item_name(&dev->group.cg_item));
2193 	} else {
2194 		sprintf(nullb->disk_name, "nullb%d", nullb->index);
2195 	}
2196 
2197 	rv = null_gendisk_register(nullb);
2198 	if (rv)
2199 		goto out_ida_free;
2200 
2201 	list_add_tail(&nullb->list, &nullb_list);
2202 
2203 	pr_info("disk %s created\n", nullb->disk_name);
2204 
2205 	return 0;
2206 
2207 out_ida_free:
2208 	ida_free(&nullb_indexes, nullb->index);
2209 out_cleanup_zone:
2210 	null_free_zoned_dev(dev);
2211 out_cleanup_disk:
2212 	put_disk(nullb->disk);
2213 out_cleanup_tags:
2214 	if (dev->queue_mode == NULL_Q_MQ && nullb->tag_set == &nullb->__tag_set)
2215 		blk_mq_free_tag_set(nullb->tag_set);
2216 out_cleanup_queues:
2217 	cleanup_queues(nullb);
2218 out_free_nullb:
2219 	kfree(nullb);
2220 	dev->nullb = NULL;
2221 out:
2222 	return rv;
2223 }
2224 
2225 static struct nullb *null_find_dev_by_name(const char *name)
2226 {
2227 	struct nullb *nullb = NULL, *nb;
2228 
2229 	mutex_lock(&lock);
2230 	list_for_each_entry(nb, &nullb_list, list) {
2231 		if (strcmp(nb->disk_name, name) == 0) {
2232 			nullb = nb;
2233 			break;
2234 		}
2235 	}
2236 	mutex_unlock(&lock);
2237 
2238 	return nullb;
2239 }
2240 
2241 static int null_create_dev(void)
2242 {
2243 	struct nullb_device *dev;
2244 	int ret;
2245 
2246 	dev = null_alloc_dev();
2247 	if (!dev)
2248 		return -ENOMEM;
2249 
2250 	mutex_lock(&lock);
2251 	ret = null_add_dev(dev);
2252 	mutex_unlock(&lock);
2253 	if (ret) {
2254 		null_free_dev(dev);
2255 		return ret;
2256 	}
2257 
2258 	return 0;
2259 }
2260 
2261 static void null_destroy_dev(struct nullb *nullb)
2262 {
2263 	struct nullb_device *dev = nullb->dev;
2264 
2265 	null_del_dev(nullb);
2266 	null_free_device_storage(dev, false);
2267 	null_free_dev(dev);
2268 }
2269 
2270 static int __init null_init(void)
2271 {
2272 	int ret = 0;
2273 	unsigned int i;
2274 	struct nullb *nullb;
2275 
2276 	if (g_bs > PAGE_SIZE) {
2277 		pr_warn("invalid block size\n");
2278 		pr_warn("defaults block size to %lu\n", PAGE_SIZE);
2279 		g_bs = PAGE_SIZE;
2280 	}
2281 
2282 	if (g_home_node != NUMA_NO_NODE && g_home_node >= nr_online_nodes) {
2283 		pr_err("invalid home_node value\n");
2284 		g_home_node = NUMA_NO_NODE;
2285 	}
2286 
2287 	if (!null_setup_fault())
2288 		return -EINVAL;
2289 
2290 	if (g_queue_mode == NULL_Q_RQ) {
2291 		pr_err("legacy IO path is no longer available\n");
2292 		return -EINVAL;
2293 	}
2294 
2295 	if (g_queue_mode == NULL_Q_MQ && g_use_per_node_hctx) {
2296 		if (g_submit_queues != nr_online_nodes) {
2297 			pr_warn("submit_queues param is set to %u.\n",
2298 				nr_online_nodes);
2299 			g_submit_queues = nr_online_nodes;
2300 		}
2301 	} else if (g_submit_queues > nr_cpu_ids) {
2302 		g_submit_queues = nr_cpu_ids;
2303 	} else if (g_submit_queues <= 0) {
2304 		g_submit_queues = 1;
2305 	}
2306 
2307 	if (g_queue_mode == NULL_Q_MQ && shared_tags) {
2308 		ret = null_init_tag_set(NULL, &tag_set);
2309 		if (ret)
2310 			return ret;
2311 	}
2312 
2313 	config_group_init(&nullb_subsys.su_group);
2314 	mutex_init(&nullb_subsys.su_mutex);
2315 
2316 	ret = configfs_register_subsystem(&nullb_subsys);
2317 	if (ret)
2318 		goto err_tagset;
2319 
2320 	mutex_init(&lock);
2321 
2322 	null_major = register_blkdev(0, "nullb");
2323 	if (null_major < 0) {
2324 		ret = null_major;
2325 		goto err_conf;
2326 	}
2327 
2328 	for (i = 0; i < nr_devices; i++) {
2329 		ret = null_create_dev();
2330 		if (ret)
2331 			goto err_dev;
2332 	}
2333 
2334 	pr_info("module loaded\n");
2335 	return 0;
2336 
2337 err_dev:
2338 	while (!list_empty(&nullb_list)) {
2339 		nullb = list_entry(nullb_list.next, struct nullb, list);
2340 		null_destroy_dev(nullb);
2341 	}
2342 	unregister_blkdev(null_major, "nullb");
2343 err_conf:
2344 	configfs_unregister_subsystem(&nullb_subsys);
2345 err_tagset:
2346 	if (g_queue_mode == NULL_Q_MQ && shared_tags)
2347 		blk_mq_free_tag_set(&tag_set);
2348 	return ret;
2349 }
2350 
2351 static void __exit null_exit(void)
2352 {
2353 	struct nullb *nullb;
2354 
2355 	configfs_unregister_subsystem(&nullb_subsys);
2356 
2357 	unregister_blkdev(null_major, "nullb");
2358 
2359 	mutex_lock(&lock);
2360 	while (!list_empty(&nullb_list)) {
2361 		nullb = list_entry(nullb_list.next, struct nullb, list);
2362 		null_destroy_dev(nullb);
2363 	}
2364 	mutex_unlock(&lock);
2365 
2366 	if (g_queue_mode == NULL_Q_MQ && shared_tags)
2367 		blk_mq_free_tag_set(&tag_set);
2368 
2369 	mutex_destroy(&lock);
2370 }
2371 
2372 module_init(null_init);
2373 module_exit(null_exit);
2374 
2375 MODULE_AUTHOR("Jens Axboe <axboe@kernel.dk>");
2376 MODULE_DESCRIPTION("multi queue aware block test driver");
2377 MODULE_LICENSE("GPL");
2378