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