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