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