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