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