root/drivers/block/null_blk_main.c

/* [<][>][^][v][top][bottom][index][help] */

DEFINITIONS

This source file includes following definitions.
  1. mb_per_tick
  2. null_param_store_val
  3. null_set_queue_mode
  4. null_set_irqmode
  5. to_nullb_device
  6. nullb_device_uint_attr_show
  7. nullb_device_ulong_attr_show
  8. nullb_device_bool_attr_show
  9. nullb_device_uint_attr_store
  10. nullb_device_ulong_attr_store
  11. nullb_device_bool_attr_store
  12. nullb_device_power_show
  13. nullb_device_power_store
  14. nullb_device_badblocks_show
  15. nullb_device_badblocks_store
  16. nullb_device_release
  17. nullb_group_make_item
  18. nullb_group_drop_item
  19. memb_group_features_show
  20. null_cache_active
  21. null_alloc_dev
  22. null_free_dev
  23. put_tag
  24. get_tag
  25. free_cmd
  26. __alloc_cmd
  27. alloc_cmd
  28. end_cmd
  29. null_cmd_timer_expired
  30. null_cmd_end_timer
  31. null_complete_rq
  32. null_alloc_page
  33. null_free_page
  34. null_page_empty
  35. null_free_sector
  36. null_radix_tree_insert
  37. null_free_device_storage
  38. __null_lookup_page
  39. null_lookup_page
  40. null_insert_page
  41. null_flush_cache_page
  42. null_make_cache_space
  43. copy_to_nullb
  44. copy_from_nullb
  45. null_handle_discard
  46. null_handle_flush
  47. null_transfer
  48. null_handle_rq
  49. null_handle_bio
  50. null_stop_queue
  51. null_restart_queue_async
  52. null_handle_throttled
  53. null_handle_badblocks
  54. null_handle_memory_backed
  55. nullb_complete_cmd
  56. null_handle_cmd
  57. nullb_bwtimer_fn
  58. nullb_setup_bwtimer
  59. nullb_to_queue
  60. null_queue_bio
  61. should_timeout_request
  62. should_requeue_request
  63. null_timeout_rq
  64. null_queue_rq
  65. cleanup_queue
  66. cleanup_queues
  67. null_del_dev
  68. null_config_discard
  69. null_open
  70. null_release
  71. null_init_queue
  72. null_init_queues
  73. setup_commands
  74. setup_queues
  75. init_driver_queues
  76. null_gendisk_register
  77. null_init_tag_set
  78. null_validate_conf
  79. __null_setup_fault
  80. null_setup_fault
  81. null_add_dev
  82. null_init
  83. null_exit

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

/* [<][>][^][v][top][bottom][index][help] */