blk-core.c 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294
  1. // SPDX-License-Identifier: GPL-2.0
  2. /*
  3. * Copyright (C) 1991, 1992 Linus Torvalds
  4. * Copyright (C) 1994, Karl Keyte: Added support for disk statistics
  5. * Elevator latency, (C) 2000 Andrea Arcangeli <andrea@suse.de> SuSE
  6. * Queue request tables / lock, selectable elevator, Jens Axboe <axboe@suse.de>
  7. * kernel-doc documentation started by NeilBrown <neilb@cse.unsw.edu.au>
  8. * - July2000
  9. * bio rewrite, highmem i/o, etc, Jens Axboe <axboe@suse.de> - may 2001
  10. */
  11. /*
  12. * This handles all read/write requests to block devices
  13. */
  14. #include <linux/kernel.h>
  15. #include <linux/module.h>
  16. #include <linux/bio.h>
  17. #include <linux/blkdev.h>
  18. #include <linux/blk-pm.h>
  19. #include <linux/blk-integrity.h>
  20. #include <linux/highmem.h>
  21. #include <linux/mm.h>
  22. #include <linux/pagemap.h>
  23. #include <linux/kernel_stat.h>
  24. #include <linux/string.h>
  25. #include <linux/init.h>
  26. #include <linux/completion.h>
  27. #include <linux/slab.h>
  28. #include <linux/swap.h>
  29. #include <linux/writeback.h>
  30. #include <linux/task_io_accounting_ops.h>
  31. #include <linux/fault-inject.h>
  32. #include <linux/list_sort.h>
  33. #include <linux/delay.h>
  34. #include <linux/ratelimit.h>
  35. #include <linux/pm_runtime.h>
  36. #include <linux/t10-pi.h>
  37. #include <linux/debugfs.h>
  38. #include <linux/bpf.h>
  39. #include <linux/part_stat.h>
  40. #include <linux/sched/sysctl.h>
  41. #include <linux/blk-crypto.h>
  42. #define CREATE_TRACE_POINTS
  43. #include <trace/events/block.h>
  44. #include "blk.h"
  45. #include "blk-mq-sched.h"
  46. #include "blk-pm.h"
  47. #include "blk-cgroup.h"
  48. #include "blk-throttle.h"
  49. #include "blk-ioprio.h"
  50. struct dentry *blk_debugfs_root;
  51. EXPORT_TRACEPOINT_SYMBOL_GPL(block_bio_remap);
  52. EXPORT_TRACEPOINT_SYMBOL_GPL(block_rq_remap);
  53. EXPORT_TRACEPOINT_SYMBOL_GPL(block_bio_complete);
  54. EXPORT_TRACEPOINT_SYMBOL_GPL(block_split);
  55. EXPORT_TRACEPOINT_SYMBOL_GPL(block_unplug);
  56. EXPORT_TRACEPOINT_SYMBOL_GPL(block_rq_insert);
  57. static DEFINE_IDA(blk_queue_ida);
  58. /*
  59. * For queue allocation
  60. */
  61. static struct kmem_cache *blk_requestq_cachep;
  62. /*
  63. * Controlling structure to kblockd
  64. */
  65. static struct workqueue_struct *kblockd_workqueue;
  66. /**
  67. * blk_queue_flag_set - atomically set a queue flag
  68. * @flag: flag to be set
  69. * @q: request queue
  70. */
  71. void blk_queue_flag_set(unsigned int flag, struct request_queue *q)
  72. {
  73. set_bit(flag, &q->queue_flags);
  74. }
  75. EXPORT_SYMBOL(blk_queue_flag_set);
  76. /**
  77. * blk_queue_flag_clear - atomically clear a queue flag
  78. * @flag: flag to be cleared
  79. * @q: request queue
  80. */
  81. void blk_queue_flag_clear(unsigned int flag, struct request_queue *q)
  82. {
  83. clear_bit(flag, &q->queue_flags);
  84. }
  85. EXPORT_SYMBOL(blk_queue_flag_clear);
  86. #define REQ_OP_NAME(name) [REQ_OP_##name] = #name
  87. static const char *const blk_op_name[] = {
  88. REQ_OP_NAME(READ),
  89. REQ_OP_NAME(WRITE),
  90. REQ_OP_NAME(FLUSH),
  91. REQ_OP_NAME(DISCARD),
  92. REQ_OP_NAME(SECURE_ERASE),
  93. REQ_OP_NAME(ZONE_RESET),
  94. REQ_OP_NAME(ZONE_RESET_ALL),
  95. REQ_OP_NAME(ZONE_OPEN),
  96. REQ_OP_NAME(ZONE_CLOSE),
  97. REQ_OP_NAME(ZONE_FINISH),
  98. REQ_OP_NAME(ZONE_APPEND),
  99. REQ_OP_NAME(WRITE_ZEROES),
  100. REQ_OP_NAME(DRV_IN),
  101. REQ_OP_NAME(DRV_OUT),
  102. };
  103. #undef REQ_OP_NAME
  104. /**
  105. * blk_op_str - Return the string "name" for an operation REQ_OP_name.
  106. * @op: a request operation.
  107. *
  108. * Convert a request operation REQ_OP_name into the string "name". Useful for
  109. * debugging and tracing BIOs and requests. For an invalid request operation
  110. * code, the string "UNKNOWN" is returned.
  111. */
  112. inline const char *blk_op_str(enum req_op op)
  113. {
  114. const char *op_str = "UNKNOWN";
  115. if (op < ARRAY_SIZE(blk_op_name) && blk_op_name[op])
  116. op_str = blk_op_name[op];
  117. return op_str;
  118. }
  119. EXPORT_SYMBOL_GPL(blk_op_str);
  120. static const struct {
  121. int errno;
  122. const char *name;
  123. } blk_errors[] = {
  124. [BLK_STS_OK] = { 0, "" },
  125. [BLK_STS_NOTSUPP] = { -EOPNOTSUPP, "operation not supported" },
  126. [BLK_STS_TIMEOUT] = { -ETIMEDOUT, "timeout" },
  127. [BLK_STS_NOSPC] = { -ENOSPC, "critical space allocation" },
  128. [BLK_STS_TRANSPORT] = { -ENOLINK, "recoverable transport" },
  129. [BLK_STS_TARGET] = { -EREMOTEIO, "critical target" },
  130. [BLK_STS_RESV_CONFLICT] = { -EBADE, "reservation conflict" },
  131. [BLK_STS_MEDIUM] = { -ENODATA, "critical medium" },
  132. [BLK_STS_PROTECTION] = { -EILSEQ, "protection" },
  133. [BLK_STS_RESOURCE] = { -ENOMEM, "kernel resource" },
  134. [BLK_STS_DEV_RESOURCE] = { -EBUSY, "device resource" },
  135. [BLK_STS_AGAIN] = { -EAGAIN, "nonblocking retry" },
  136. [BLK_STS_OFFLINE] = { -ENODEV, "device offline" },
  137. /* device mapper special case, should not leak out: */
  138. [BLK_STS_DM_REQUEUE] = { -EREMCHG, "dm internal retry" },
  139. /* zone device specific errors */
  140. [BLK_STS_ZONE_OPEN_RESOURCE] = { -ETOOMANYREFS, "open zones exceeded" },
  141. [BLK_STS_ZONE_ACTIVE_RESOURCE] = { -EOVERFLOW, "active zones exceeded" },
  142. /* Command duration limit device-side timeout */
  143. [BLK_STS_DURATION_LIMIT] = { -ETIME, "duration limit exceeded" },
  144. [BLK_STS_INVAL] = { -EINVAL, "invalid" },
  145. /* everything else not covered above: */
  146. [BLK_STS_IOERR] = { -EIO, "I/O" },
  147. };
  148. blk_status_t errno_to_blk_status(int errno)
  149. {
  150. int i;
  151. for (i = 0; i < ARRAY_SIZE(blk_errors); i++) {
  152. if (blk_errors[i].errno == errno)
  153. return (__force blk_status_t)i;
  154. }
  155. return BLK_STS_IOERR;
  156. }
  157. EXPORT_SYMBOL_GPL(errno_to_blk_status);
  158. int blk_status_to_errno(blk_status_t status)
  159. {
  160. int idx = (__force int)status;
  161. if (WARN_ON_ONCE(idx >= ARRAY_SIZE(blk_errors)))
  162. return -EIO;
  163. return blk_errors[idx].errno;
  164. }
  165. EXPORT_SYMBOL_GPL(blk_status_to_errno);
  166. const char *blk_status_to_str(blk_status_t status)
  167. {
  168. int idx = (__force int)status;
  169. if (WARN_ON_ONCE(idx >= ARRAY_SIZE(blk_errors)))
  170. return "<null>";
  171. return blk_errors[idx].name;
  172. }
  173. EXPORT_SYMBOL_GPL(blk_status_to_str);
  174. /**
  175. * blk_sync_queue - cancel any pending callbacks on a queue
  176. * @q: the queue
  177. *
  178. * Description:
  179. * The block layer may perform asynchronous callback activity
  180. * on a queue, such as calling the unplug function after a timeout.
  181. * A block device may call blk_sync_queue to ensure that any
  182. * such activity is cancelled, thus allowing it to release resources
  183. * that the callbacks might use. The caller must already have made sure
  184. * that its ->submit_bio will not re-add plugging prior to calling
  185. * this function.
  186. *
  187. * This function does not cancel any asynchronous activity arising
  188. * out of elevator or throttling code. That would require elevator_exit()
  189. * and blkcg_exit_queue() to be called with queue lock initialized.
  190. *
  191. */
  192. void blk_sync_queue(struct request_queue *q)
  193. {
  194. timer_delete_sync(&q->timeout);
  195. cancel_work_sync(&q->timeout_work);
  196. }
  197. EXPORT_SYMBOL(blk_sync_queue);
  198. /**
  199. * blk_set_pm_only - increment pm_only counter
  200. * @q: request queue pointer
  201. */
  202. void blk_set_pm_only(struct request_queue *q)
  203. {
  204. atomic_inc(&q->pm_only);
  205. }
  206. EXPORT_SYMBOL_GPL(blk_set_pm_only);
  207. void blk_clear_pm_only(struct request_queue *q)
  208. {
  209. int pm_only;
  210. pm_only = atomic_dec_return(&q->pm_only);
  211. WARN_ON_ONCE(pm_only < 0);
  212. if (pm_only == 0)
  213. wake_up_all(&q->mq_freeze_wq);
  214. }
  215. EXPORT_SYMBOL_GPL(blk_clear_pm_only);
  216. static void blk_free_queue_rcu(struct rcu_head *rcu_head)
  217. {
  218. struct request_queue *q = container_of(rcu_head,
  219. struct request_queue, rcu_head);
  220. percpu_ref_exit(&q->q_usage_counter);
  221. kmem_cache_free(blk_requestq_cachep, q);
  222. }
  223. static void blk_free_queue(struct request_queue *q)
  224. {
  225. blk_free_queue_stats(q->stats);
  226. if (queue_is_mq(q))
  227. blk_mq_release(q);
  228. ida_free(&blk_queue_ida, q->id);
  229. lockdep_unregister_key(&q->io_lock_cls_key);
  230. lockdep_unregister_key(&q->q_lock_cls_key);
  231. call_rcu(&q->rcu_head, blk_free_queue_rcu);
  232. }
  233. /**
  234. * blk_put_queue - decrement the request_queue refcount
  235. * @q: the request_queue structure to decrement the refcount for
  236. *
  237. * Decrements the refcount of the request_queue and free it when the refcount
  238. * reaches 0.
  239. */
  240. void blk_put_queue(struct request_queue *q)
  241. {
  242. if (refcount_dec_and_test(&q->refs))
  243. blk_free_queue(q);
  244. }
  245. EXPORT_SYMBOL(blk_put_queue);
  246. bool blk_queue_start_drain(struct request_queue *q)
  247. {
  248. /*
  249. * When queue DYING flag is set, we need to block new req
  250. * entering queue, so we call blk_freeze_queue_start() to
  251. * prevent I/O from crossing blk_queue_enter().
  252. */
  253. bool freeze = __blk_freeze_queue_start(q, current);
  254. if (queue_is_mq(q))
  255. blk_mq_wake_waiters(q);
  256. /* Make blk_queue_enter() reexamine the DYING flag. */
  257. wake_up_all(&q->mq_freeze_wq);
  258. return freeze;
  259. }
  260. /**
  261. * blk_queue_enter() - try to increase q->q_usage_counter
  262. * @q: request queue pointer
  263. * @flags: BLK_MQ_REQ_NOWAIT and/or BLK_MQ_REQ_PM
  264. */
  265. int blk_queue_enter(struct request_queue *q, blk_mq_req_flags_t flags)
  266. {
  267. const bool pm = flags & BLK_MQ_REQ_PM;
  268. while (!blk_try_enter_queue(q, pm)) {
  269. if (flags & BLK_MQ_REQ_NOWAIT)
  270. return -EAGAIN;
  271. /*
  272. * read pair of barrier in blk_freeze_queue_start(), we need to
  273. * order reading __PERCPU_REF_DEAD flag of .q_usage_counter and
  274. * reading .mq_freeze_depth or queue dying flag, otherwise the
  275. * following wait may never return if the two reads are
  276. * reordered.
  277. */
  278. smp_rmb();
  279. wait_event(q->mq_freeze_wq,
  280. (!q->mq_freeze_depth &&
  281. blk_pm_resume_queue(pm, q)) ||
  282. blk_queue_dying(q));
  283. if (blk_queue_dying(q))
  284. return -ENODEV;
  285. }
  286. rwsem_acquire_read(&q->q_lockdep_map, 0, 0, _RET_IP_);
  287. rwsem_release(&q->q_lockdep_map, _RET_IP_);
  288. return 0;
  289. }
  290. int __bio_queue_enter(struct request_queue *q, struct bio *bio)
  291. {
  292. while (!blk_try_enter_queue(q, false)) {
  293. struct gendisk *disk = bio->bi_bdev->bd_disk;
  294. if (bio->bi_opf & REQ_NOWAIT) {
  295. if (test_bit(GD_DEAD, &disk->state))
  296. goto dead;
  297. bio_wouldblock_error(bio);
  298. return -EAGAIN;
  299. }
  300. /*
  301. * read pair of barrier in blk_freeze_queue_start(), we need to
  302. * order reading __PERCPU_REF_DEAD flag of .q_usage_counter and
  303. * reading .mq_freeze_depth or queue dying flag, otherwise the
  304. * following wait may never return if the two reads are
  305. * reordered.
  306. */
  307. smp_rmb();
  308. wait_event(q->mq_freeze_wq,
  309. (!q->mq_freeze_depth &&
  310. blk_pm_resume_queue(false, q)) ||
  311. test_bit(GD_DEAD, &disk->state));
  312. if (test_bit(GD_DEAD, &disk->state))
  313. goto dead;
  314. }
  315. rwsem_acquire_read(&q->io_lockdep_map, 0, 0, _RET_IP_);
  316. rwsem_release(&q->io_lockdep_map, _RET_IP_);
  317. return 0;
  318. dead:
  319. bio_io_error(bio);
  320. return -ENODEV;
  321. }
  322. void blk_queue_exit(struct request_queue *q)
  323. {
  324. percpu_ref_put(&q->q_usage_counter);
  325. }
  326. static void blk_queue_usage_counter_release(struct percpu_ref *ref)
  327. {
  328. struct request_queue *q =
  329. container_of(ref, struct request_queue, q_usage_counter);
  330. wake_up_all(&q->mq_freeze_wq);
  331. }
  332. static void blk_rq_timed_out_timer(struct timer_list *t)
  333. {
  334. struct request_queue *q = timer_container_of(q, t, timeout);
  335. kblockd_schedule_work(&q->timeout_work);
  336. }
  337. static void blk_timeout_work(struct work_struct *work)
  338. {
  339. }
  340. struct request_queue *blk_alloc_queue(struct queue_limits *lim, int node_id)
  341. {
  342. struct request_queue *q;
  343. int error;
  344. q = kmem_cache_alloc_node(blk_requestq_cachep, GFP_KERNEL | __GFP_ZERO,
  345. node_id);
  346. if (!q)
  347. return ERR_PTR(-ENOMEM);
  348. q->last_merge = NULL;
  349. q->id = ida_alloc(&blk_queue_ida, GFP_KERNEL);
  350. if (q->id < 0) {
  351. error = q->id;
  352. goto fail_q;
  353. }
  354. q->stats = blk_alloc_queue_stats();
  355. if (!q->stats) {
  356. error = -ENOMEM;
  357. goto fail_id;
  358. }
  359. error = blk_set_default_limits(lim);
  360. if (error)
  361. goto fail_stats;
  362. q->limits = *lim;
  363. q->node = node_id;
  364. atomic_set(&q->nr_active_requests_shared_tags, 0);
  365. timer_setup(&q->timeout, blk_rq_timed_out_timer, 0);
  366. INIT_WORK(&q->timeout_work, blk_timeout_work);
  367. INIT_LIST_HEAD(&q->icq_list);
  368. refcount_set(&q->refs, 1);
  369. mutex_init(&q->debugfs_mutex);
  370. mutex_init(&q->elevator_lock);
  371. mutex_init(&q->sysfs_lock);
  372. mutex_init(&q->limits_lock);
  373. mutex_init(&q->rq_qos_mutex);
  374. spin_lock_init(&q->queue_lock);
  375. init_waitqueue_head(&q->mq_freeze_wq);
  376. mutex_init(&q->mq_freeze_lock);
  377. blkg_init_queue(q);
  378. /*
  379. * Init percpu_ref in atomic mode so that it's faster to shutdown.
  380. * See blk_register_queue() for details.
  381. */
  382. error = percpu_ref_init(&q->q_usage_counter,
  383. blk_queue_usage_counter_release,
  384. PERCPU_REF_INIT_ATOMIC, GFP_KERNEL);
  385. if (error)
  386. goto fail_stats;
  387. lockdep_register_key(&q->io_lock_cls_key);
  388. lockdep_register_key(&q->q_lock_cls_key);
  389. lockdep_init_map(&q->io_lockdep_map, "&q->q_usage_counter(io)",
  390. &q->io_lock_cls_key, 0);
  391. lockdep_init_map(&q->q_lockdep_map, "&q->q_usage_counter(queue)",
  392. &q->q_lock_cls_key, 0);
  393. /* Teach lockdep about lock ordering (reclaim WRT queue freeze lock). */
  394. fs_reclaim_acquire(GFP_KERNEL);
  395. rwsem_acquire_read(&q->io_lockdep_map, 0, 0, _RET_IP_);
  396. rwsem_release(&q->io_lockdep_map, _RET_IP_);
  397. fs_reclaim_release(GFP_KERNEL);
  398. q->nr_requests = BLKDEV_DEFAULT_RQ;
  399. q->async_depth = BLKDEV_DEFAULT_RQ;
  400. return q;
  401. fail_stats:
  402. blk_free_queue_stats(q->stats);
  403. fail_id:
  404. ida_free(&blk_queue_ida, q->id);
  405. fail_q:
  406. kmem_cache_free(blk_requestq_cachep, q);
  407. return ERR_PTR(error);
  408. }
  409. /**
  410. * blk_get_queue - increment the request_queue refcount
  411. * @q: the request_queue structure to increment the refcount for
  412. *
  413. * Increment the refcount of the request_queue kobject.
  414. *
  415. * Context: Any context.
  416. */
  417. bool blk_get_queue(struct request_queue *q)
  418. {
  419. if (unlikely(blk_queue_dying(q)))
  420. return false;
  421. refcount_inc(&q->refs);
  422. return true;
  423. }
  424. EXPORT_SYMBOL(blk_get_queue);
  425. #ifdef CONFIG_FAIL_MAKE_REQUEST
  426. static DECLARE_FAULT_ATTR(fail_make_request);
  427. static int __init setup_fail_make_request(char *str)
  428. {
  429. return setup_fault_attr(&fail_make_request, str);
  430. }
  431. __setup("fail_make_request=", setup_fail_make_request);
  432. bool should_fail_request(struct block_device *part, unsigned int bytes)
  433. {
  434. return bdev_test_flag(part, BD_MAKE_IT_FAIL) &&
  435. should_fail(&fail_make_request, bytes);
  436. }
  437. static int __init fail_make_request_debugfs(void)
  438. {
  439. struct dentry *dir = fault_create_debugfs_attr("fail_make_request",
  440. NULL, &fail_make_request);
  441. return PTR_ERR_OR_ZERO(dir);
  442. }
  443. late_initcall(fail_make_request_debugfs);
  444. #endif /* CONFIG_FAIL_MAKE_REQUEST */
  445. static inline void bio_check_ro(struct bio *bio)
  446. {
  447. if (op_is_write(bio_op(bio)) && bdev_read_only(bio->bi_bdev)) {
  448. if (op_is_flush(bio->bi_opf) && !bio_sectors(bio))
  449. return;
  450. if (bdev_test_flag(bio->bi_bdev, BD_RO_WARNED))
  451. return;
  452. bdev_set_flag(bio->bi_bdev, BD_RO_WARNED);
  453. /*
  454. * Use ioctl to set underlying disk of raid/dm to read-only
  455. * will trigger this.
  456. */
  457. pr_warn("Trying to write to read-only block-device %pg\n",
  458. bio->bi_bdev);
  459. }
  460. }
  461. int should_fail_bio(struct bio *bio)
  462. {
  463. if (should_fail_request(bdev_whole(bio->bi_bdev), bio->bi_iter.bi_size))
  464. return -EIO;
  465. return 0;
  466. }
  467. ALLOW_ERROR_INJECTION(should_fail_bio, ERRNO);
  468. /*
  469. * Check whether this bio extends beyond the end of the device or partition.
  470. * This may well happen - the kernel calls bread() without checking the size of
  471. * the device, e.g., when mounting a file system.
  472. */
  473. static inline int bio_check_eod(struct bio *bio)
  474. {
  475. sector_t maxsector = bdev_nr_sectors(bio->bi_bdev);
  476. unsigned int nr_sectors = bio_sectors(bio);
  477. if (nr_sectors &&
  478. (nr_sectors > maxsector ||
  479. bio->bi_iter.bi_sector > maxsector - nr_sectors)) {
  480. if (!maxsector)
  481. return -EIO;
  482. pr_info_ratelimited("%s: attempt to access beyond end of device\n"
  483. "%pg: rw=%d, sector=%llu, nr_sectors = %u limit=%llu\n",
  484. current->comm, bio->bi_bdev, bio->bi_opf,
  485. bio->bi_iter.bi_sector, nr_sectors, maxsector);
  486. return -EIO;
  487. }
  488. return 0;
  489. }
  490. /*
  491. * Remap block n of partition p to block n+start(p) of the disk.
  492. */
  493. static int blk_partition_remap(struct bio *bio)
  494. {
  495. struct block_device *p = bio->bi_bdev;
  496. if (unlikely(should_fail_request(p, bio->bi_iter.bi_size)))
  497. return -EIO;
  498. if (bio_sectors(bio)) {
  499. bio->bi_iter.bi_sector += p->bd_start_sect;
  500. trace_block_bio_remap(bio, p->bd_dev,
  501. bio->bi_iter.bi_sector -
  502. p->bd_start_sect);
  503. }
  504. bio_set_flag(bio, BIO_REMAPPED);
  505. return 0;
  506. }
  507. /*
  508. * Check write append to a zoned block device.
  509. */
  510. static inline blk_status_t blk_check_zone_append(struct request_queue *q,
  511. struct bio *bio)
  512. {
  513. int nr_sectors = bio_sectors(bio);
  514. /* Only applicable to zoned block devices */
  515. if (!bdev_is_zoned(bio->bi_bdev))
  516. return BLK_STS_NOTSUPP;
  517. /* The bio sector must point to the start of a sequential zone */
  518. if (!bdev_is_zone_start(bio->bi_bdev, bio->bi_iter.bi_sector))
  519. return BLK_STS_IOERR;
  520. /*
  521. * Not allowed to cross zone boundaries. Otherwise, the BIO will be
  522. * split and could result in non-contiguous sectors being written in
  523. * different zones.
  524. */
  525. if (nr_sectors > q->limits.chunk_sectors)
  526. return BLK_STS_IOERR;
  527. /* Make sure the BIO is small enough and will not get split */
  528. if (nr_sectors > q->limits.max_zone_append_sectors)
  529. return BLK_STS_IOERR;
  530. bio->bi_opf |= REQ_NOMERGE;
  531. return BLK_STS_OK;
  532. }
  533. static void __submit_bio(struct bio *bio)
  534. {
  535. /* If plug is not used, add new plug here to cache nsecs time. */
  536. struct blk_plug plug;
  537. blk_start_plug(&plug);
  538. if (!bdev_test_flag(bio->bi_bdev, BD_HAS_SUBMIT_BIO)) {
  539. blk_mq_submit_bio(bio);
  540. } else if (likely(bio_queue_enter(bio) == 0)) {
  541. struct gendisk *disk = bio->bi_bdev->bd_disk;
  542. if ((bio->bi_opf & REQ_POLLED) &&
  543. !(disk->queue->limits.features & BLK_FEAT_POLL)) {
  544. bio->bi_status = BLK_STS_NOTSUPP;
  545. bio_endio(bio);
  546. } else {
  547. disk->fops->submit_bio(bio);
  548. }
  549. blk_queue_exit(disk->queue);
  550. }
  551. blk_finish_plug(&plug);
  552. }
  553. /*
  554. * The loop in this function may be a bit non-obvious, and so deserves some
  555. * explanation:
  556. *
  557. * - Before entering the loop, bio->bi_next is NULL (as all callers ensure
  558. * that), so we have a list with a single bio.
  559. * - We pretend that we have just taken it off a longer list, so we assign
  560. * bio_list to a pointer to the bio_list_on_stack, thus initialising the
  561. * bio_list of new bios to be added. ->submit_bio() may indeed add some more
  562. * bios through a recursive call to submit_bio_noacct. If it did, we find a
  563. * non-NULL value in bio_list and re-enter the loop from the top.
  564. * - In this case we really did just take the bio off the top of the list (no
  565. * pretending) and so remove it from bio_list, and call into ->submit_bio()
  566. * again.
  567. *
  568. * bio_list_on_stack[0] contains bios submitted by the current ->submit_bio.
  569. * bio_list_on_stack[1] contains bios that were submitted before the current
  570. * ->submit_bio(), but that haven't been processed yet.
  571. */
  572. static void __submit_bio_noacct(struct bio *bio)
  573. {
  574. struct bio_list bio_list_on_stack[2];
  575. BUG_ON(bio->bi_next);
  576. bio_list_init(&bio_list_on_stack[0]);
  577. current->bio_list = bio_list_on_stack;
  578. do {
  579. struct request_queue *q = bdev_get_queue(bio->bi_bdev);
  580. struct bio_list lower, same;
  581. /*
  582. * Create a fresh bio_list for all subordinate requests.
  583. */
  584. bio_list_on_stack[1] = bio_list_on_stack[0];
  585. bio_list_init(&bio_list_on_stack[0]);
  586. __submit_bio(bio);
  587. /*
  588. * Sort new bios into those for a lower level and those for the
  589. * same level.
  590. */
  591. bio_list_init(&lower);
  592. bio_list_init(&same);
  593. while ((bio = bio_list_pop(&bio_list_on_stack[0])) != NULL)
  594. if (q == bdev_get_queue(bio->bi_bdev))
  595. bio_list_add(&same, bio);
  596. else
  597. bio_list_add(&lower, bio);
  598. /*
  599. * Now assemble so we handle the lowest level first.
  600. */
  601. bio_list_merge(&bio_list_on_stack[0], &lower);
  602. bio_list_merge(&bio_list_on_stack[0], &same);
  603. bio_list_merge(&bio_list_on_stack[0], &bio_list_on_stack[1]);
  604. } while ((bio = bio_list_pop(&bio_list_on_stack[0])));
  605. current->bio_list = NULL;
  606. }
  607. static void __submit_bio_noacct_mq(struct bio *bio)
  608. {
  609. struct bio_list bio_list[2] = { };
  610. current->bio_list = bio_list;
  611. do {
  612. __submit_bio(bio);
  613. } while ((bio = bio_list_pop(&bio_list[0])));
  614. current->bio_list = NULL;
  615. }
  616. void submit_bio_noacct_nocheck(struct bio *bio, bool split)
  617. {
  618. blk_cgroup_bio_start(bio);
  619. if (!bio_flagged(bio, BIO_TRACE_COMPLETION)) {
  620. trace_block_bio_queue(bio);
  621. /*
  622. * Now that enqueuing has been traced, we need to trace
  623. * completion as well.
  624. */
  625. bio_set_flag(bio, BIO_TRACE_COMPLETION);
  626. }
  627. /*
  628. * We only want one ->submit_bio to be active at a time, else stack
  629. * usage with stacked devices could be a problem. Use current->bio_list
  630. * to collect a list of requests submitted by a ->submit_bio method
  631. * while it is active, and then process them after it returned.
  632. */
  633. if (current->bio_list) {
  634. if (split)
  635. bio_list_add_head(&current->bio_list[0], bio);
  636. else
  637. bio_list_add(&current->bio_list[0], bio);
  638. } else if (!bdev_test_flag(bio->bi_bdev, BD_HAS_SUBMIT_BIO)) {
  639. __submit_bio_noacct_mq(bio);
  640. } else {
  641. __submit_bio_noacct(bio);
  642. }
  643. }
  644. static blk_status_t blk_validate_atomic_write_op_size(struct request_queue *q,
  645. struct bio *bio)
  646. {
  647. if (bio->bi_iter.bi_size > queue_atomic_write_unit_max_bytes(q))
  648. return BLK_STS_INVAL;
  649. if (bio->bi_iter.bi_size % queue_atomic_write_unit_min_bytes(q))
  650. return BLK_STS_INVAL;
  651. return BLK_STS_OK;
  652. }
  653. /**
  654. * submit_bio_noacct - re-submit a bio to the block device layer for I/O
  655. * @bio: The bio describing the location in memory and on the device.
  656. *
  657. * This is a version of submit_bio() that shall only be used for I/O that is
  658. * resubmitted to lower level drivers by stacking block drivers. All file
  659. * systems and other upper level users of the block layer should use
  660. * submit_bio() instead.
  661. */
  662. void submit_bio_noacct(struct bio *bio)
  663. {
  664. struct block_device *bdev = bio->bi_bdev;
  665. struct request_queue *q = bdev_get_queue(bdev);
  666. blk_status_t status = BLK_STS_IOERR;
  667. might_sleep();
  668. /*
  669. * For a REQ_NOWAIT based request, return -EOPNOTSUPP
  670. * if queue does not support NOWAIT.
  671. */
  672. if ((bio->bi_opf & REQ_NOWAIT) && !bdev_nowait(bdev))
  673. goto not_supported;
  674. if (bio_has_crypt_ctx(bio)) {
  675. if (WARN_ON_ONCE(!bio_has_data(bio)))
  676. goto end_io;
  677. if (!blk_crypto_supported(bio))
  678. goto not_supported;
  679. }
  680. if (should_fail_bio(bio))
  681. goto end_io;
  682. bio_check_ro(bio);
  683. if (!bio_flagged(bio, BIO_REMAPPED)) {
  684. if (unlikely(bio_check_eod(bio)))
  685. goto end_io;
  686. if (bdev_is_partition(bdev) &&
  687. unlikely(blk_partition_remap(bio)))
  688. goto end_io;
  689. }
  690. /*
  691. * Filter flush bio's early so that bio based drivers without flush
  692. * support don't have to worry about them.
  693. */
  694. if (op_is_flush(bio->bi_opf)) {
  695. if (WARN_ON_ONCE(bio_op(bio) != REQ_OP_WRITE &&
  696. bio_op(bio) != REQ_OP_ZONE_APPEND))
  697. goto end_io;
  698. if (!bdev_write_cache(bdev)) {
  699. bio->bi_opf &= ~(REQ_PREFLUSH | REQ_FUA);
  700. if (!bio_sectors(bio)) {
  701. status = BLK_STS_OK;
  702. goto end_io;
  703. }
  704. }
  705. }
  706. switch (bio_op(bio)) {
  707. case REQ_OP_READ:
  708. break;
  709. case REQ_OP_WRITE:
  710. if (bio->bi_opf & REQ_ATOMIC) {
  711. status = blk_validate_atomic_write_op_size(q, bio);
  712. if (status != BLK_STS_OK)
  713. goto end_io;
  714. }
  715. break;
  716. case REQ_OP_FLUSH:
  717. /*
  718. * REQ_OP_FLUSH can't be submitted through bios, it is only
  719. * synthetized in struct request by the flush state machine.
  720. */
  721. goto not_supported;
  722. case REQ_OP_DISCARD:
  723. if (!bdev_max_discard_sectors(bdev))
  724. goto not_supported;
  725. break;
  726. case REQ_OP_SECURE_ERASE:
  727. if (!bdev_max_secure_erase_sectors(bdev))
  728. goto not_supported;
  729. break;
  730. case REQ_OP_ZONE_APPEND:
  731. status = blk_check_zone_append(q, bio);
  732. if (status != BLK_STS_OK)
  733. goto end_io;
  734. break;
  735. case REQ_OP_WRITE_ZEROES:
  736. if (!q->limits.max_write_zeroes_sectors)
  737. goto not_supported;
  738. break;
  739. case REQ_OP_ZONE_RESET:
  740. case REQ_OP_ZONE_OPEN:
  741. case REQ_OP_ZONE_CLOSE:
  742. case REQ_OP_ZONE_FINISH:
  743. case REQ_OP_ZONE_RESET_ALL:
  744. if (!bdev_is_zoned(bio->bi_bdev))
  745. goto not_supported;
  746. break;
  747. case REQ_OP_DRV_IN:
  748. case REQ_OP_DRV_OUT:
  749. /*
  750. * Driver private operations are only used with passthrough
  751. * requests.
  752. */
  753. fallthrough;
  754. default:
  755. goto not_supported;
  756. }
  757. if (blk_throtl_bio(bio))
  758. return;
  759. submit_bio_noacct_nocheck(bio, false);
  760. return;
  761. not_supported:
  762. status = BLK_STS_NOTSUPP;
  763. end_io:
  764. bio->bi_status = status;
  765. bio_endio(bio);
  766. }
  767. EXPORT_SYMBOL(submit_bio_noacct);
  768. static void bio_set_ioprio(struct bio *bio)
  769. {
  770. /* Nobody set ioprio so far? Initialize it based on task's nice value */
  771. if (IOPRIO_PRIO_CLASS(bio->bi_ioprio) == IOPRIO_CLASS_NONE)
  772. bio->bi_ioprio = get_current_ioprio();
  773. blkcg_set_ioprio(bio);
  774. }
  775. /**
  776. * submit_bio - submit a bio to the block device layer for I/O
  777. * @bio: The &struct bio which describes the I/O
  778. *
  779. * submit_bio() is used to submit I/O requests to block devices. It is passed a
  780. * fully set up &struct bio that describes the I/O that needs to be done. The
  781. * bio will be sent to the device described by the bi_bdev field.
  782. *
  783. * The success/failure status of the request, along with notification of
  784. * completion, is delivered asynchronously through the ->bi_end_io() callback
  785. * in @bio. The bio must NOT be touched by the caller until ->bi_end_io() has
  786. * been called.
  787. */
  788. void submit_bio(struct bio *bio)
  789. {
  790. if (bio_op(bio) == REQ_OP_READ) {
  791. task_io_account_read(bio->bi_iter.bi_size);
  792. count_vm_events(PGPGIN, bio_sectors(bio));
  793. } else if (bio_op(bio) == REQ_OP_WRITE) {
  794. count_vm_events(PGPGOUT, bio_sectors(bio));
  795. }
  796. bio_set_ioprio(bio);
  797. submit_bio_noacct(bio);
  798. }
  799. EXPORT_SYMBOL(submit_bio);
  800. /**
  801. * bio_poll - poll for BIO completions
  802. * @bio: bio to poll for
  803. * @iob: batches of IO
  804. * @flags: BLK_POLL_* flags that control the behavior
  805. *
  806. * Poll for completions on queue associated with the bio. Returns number of
  807. * completed entries found.
  808. *
  809. * Note: the caller must either be the context that submitted @bio, or
  810. * be in a RCU critical section to prevent freeing of @bio.
  811. */
  812. int bio_poll(struct bio *bio, struct io_comp_batch *iob, unsigned int flags)
  813. {
  814. blk_qc_t cookie = READ_ONCE(bio->bi_cookie);
  815. struct block_device *bdev;
  816. struct request_queue *q;
  817. int ret = 0;
  818. bdev = READ_ONCE(bio->bi_bdev);
  819. if (!bdev)
  820. return 0;
  821. q = bdev_get_queue(bdev);
  822. if (cookie == BLK_QC_T_NONE)
  823. return 0;
  824. blk_flush_plug(current->plug, false);
  825. /*
  826. * We need to be able to enter a frozen queue, similar to how
  827. * timeouts also need to do that. If that is blocked, then we can
  828. * have pending IO when a queue freeze is started, and then the
  829. * wait for the freeze to finish will wait for polled requests to
  830. * timeout as the poller is preventer from entering the queue and
  831. * completing them. As long as we prevent new IO from being queued,
  832. * that should be all that matters.
  833. */
  834. if (!percpu_ref_tryget(&q->q_usage_counter))
  835. return 0;
  836. if (queue_is_mq(q)) {
  837. ret = blk_mq_poll(q, cookie, iob, flags);
  838. } else {
  839. struct gendisk *disk = q->disk;
  840. if ((q->limits.features & BLK_FEAT_POLL) && disk &&
  841. disk->fops->poll_bio)
  842. ret = disk->fops->poll_bio(bio, iob, flags);
  843. }
  844. blk_queue_exit(q);
  845. return ret;
  846. }
  847. EXPORT_SYMBOL_GPL(bio_poll);
  848. /*
  849. * Helper to implement file_operations.iopoll. Requires the bio to be stored
  850. * in iocb->private, and cleared before freeing the bio.
  851. */
  852. int iocb_bio_iopoll(struct kiocb *kiocb, struct io_comp_batch *iob,
  853. unsigned int flags)
  854. {
  855. struct bio *bio;
  856. int ret = 0;
  857. /*
  858. * Note: the bio cache only uses SLAB_TYPESAFE_BY_RCU, so bio can
  859. * point to a freshly allocated bio at this point. If that happens
  860. * we have a few cases to consider:
  861. *
  862. * 1) the bio is being initialized and bi_bdev is NULL. We can just
  863. * simply nothing in this case
  864. * 2) the bio points to a not poll enabled device. bio_poll will catch
  865. * this and return 0
  866. * 3) the bio points to a poll capable device, including but not
  867. * limited to the one that the original bio pointed to. In this
  868. * case we will call into the actual poll method and poll for I/O,
  869. * even if we don't need to, but it won't cause harm either.
  870. *
  871. * For cases 2) and 3) above the RCU grace period ensures that bi_bdev
  872. * is still allocated. Because partitions hold a reference to the whole
  873. * device bdev and thus disk, the disk is also still valid. Grabbing
  874. * a reference to the queue in bio_poll() ensures the hctxs and requests
  875. * are still valid as well.
  876. */
  877. rcu_read_lock();
  878. bio = READ_ONCE(kiocb->private);
  879. if (bio)
  880. ret = bio_poll(bio, iob, flags);
  881. rcu_read_unlock();
  882. return ret;
  883. }
  884. EXPORT_SYMBOL_GPL(iocb_bio_iopoll);
  885. void update_io_ticks(struct block_device *part, unsigned long now, bool end)
  886. {
  887. unsigned long stamp;
  888. again:
  889. stamp = READ_ONCE(part->bd_stamp);
  890. if (unlikely(time_after(now, stamp)) &&
  891. likely(try_cmpxchg(&part->bd_stamp, &stamp, now)) &&
  892. (end || bdev_count_inflight(part)))
  893. __part_stat_add(part, io_ticks, now - stamp);
  894. if (bdev_is_partition(part)) {
  895. part = bdev_whole(part);
  896. goto again;
  897. }
  898. }
  899. unsigned long bdev_start_io_acct(struct block_device *bdev, enum req_op op,
  900. unsigned long start_time)
  901. {
  902. part_stat_lock();
  903. update_io_ticks(bdev, start_time, false);
  904. part_stat_local_inc(bdev, in_flight[op_is_write(op)]);
  905. part_stat_unlock();
  906. return start_time;
  907. }
  908. EXPORT_SYMBOL(bdev_start_io_acct);
  909. /**
  910. * bio_start_io_acct - start I/O accounting for bio based drivers
  911. * @bio: bio to start account for
  912. *
  913. * Returns the start time that should be passed back to bio_end_io_acct().
  914. */
  915. unsigned long bio_start_io_acct(struct bio *bio)
  916. {
  917. return bdev_start_io_acct(bio->bi_bdev, bio_op(bio), jiffies);
  918. }
  919. EXPORT_SYMBOL_GPL(bio_start_io_acct);
  920. void bdev_end_io_acct(struct block_device *bdev, enum req_op op,
  921. unsigned int sectors, unsigned long start_time)
  922. {
  923. const int sgrp = op_stat_group(op);
  924. unsigned long now = READ_ONCE(jiffies);
  925. unsigned long duration = now - start_time;
  926. part_stat_lock();
  927. update_io_ticks(bdev, now, true);
  928. part_stat_inc(bdev, ios[sgrp]);
  929. part_stat_add(bdev, sectors[sgrp], sectors);
  930. part_stat_add(bdev, nsecs[sgrp], jiffies_to_nsecs(duration));
  931. part_stat_local_dec(bdev, in_flight[op_is_write(op)]);
  932. part_stat_unlock();
  933. }
  934. EXPORT_SYMBOL(bdev_end_io_acct);
  935. void bio_end_io_acct_remapped(struct bio *bio, unsigned long start_time,
  936. struct block_device *orig_bdev)
  937. {
  938. bdev_end_io_acct(orig_bdev, bio_op(bio), bio_sectors(bio), start_time);
  939. }
  940. EXPORT_SYMBOL_GPL(bio_end_io_acct_remapped);
  941. /**
  942. * blk_lld_busy - Check if underlying low-level drivers of a device are busy
  943. * @q : the queue of the device being checked
  944. *
  945. * Description:
  946. * Check if underlying low-level drivers of a device are busy.
  947. * If the drivers want to export their busy state, they must set own
  948. * exporting function using blk_queue_lld_busy() first.
  949. *
  950. * Basically, this function is used only by request stacking drivers
  951. * to stop dispatching requests to underlying devices when underlying
  952. * devices are busy. This behavior helps more I/O merging on the queue
  953. * of the request stacking driver and prevents I/O throughput regression
  954. * on burst I/O load.
  955. *
  956. * Return:
  957. * 0 - Not busy (The request stacking driver should dispatch request)
  958. * 1 - Busy (The request stacking driver should stop dispatching request)
  959. */
  960. int blk_lld_busy(struct request_queue *q)
  961. {
  962. if (queue_is_mq(q) && q->mq_ops->busy)
  963. return q->mq_ops->busy(q);
  964. return 0;
  965. }
  966. EXPORT_SYMBOL_GPL(blk_lld_busy);
  967. int kblockd_schedule_work(struct work_struct *work)
  968. {
  969. return queue_work(kblockd_workqueue, work);
  970. }
  971. EXPORT_SYMBOL(kblockd_schedule_work);
  972. int kblockd_mod_delayed_work_on(int cpu, struct delayed_work *dwork,
  973. unsigned long delay)
  974. {
  975. return mod_delayed_work_on(cpu, kblockd_workqueue, dwork, delay);
  976. }
  977. EXPORT_SYMBOL(kblockd_mod_delayed_work_on);
  978. void blk_start_plug_nr_ios(struct blk_plug *plug, unsigned short nr_ios)
  979. {
  980. struct task_struct *tsk = current;
  981. /*
  982. * If this is a nested plug, don't actually assign it.
  983. */
  984. if (tsk->plug)
  985. return;
  986. plug->cur_ktime = 0;
  987. rq_list_init(&plug->mq_list);
  988. rq_list_init(&plug->cached_rqs);
  989. plug->nr_ios = min_t(unsigned short, nr_ios, BLK_MAX_REQUEST_COUNT);
  990. plug->rq_count = 0;
  991. plug->multiple_queues = false;
  992. plug->has_elevator = false;
  993. INIT_LIST_HEAD(&plug->cb_list);
  994. /*
  995. * Store ordering should not be needed here, since a potential
  996. * preempt will imply a full memory barrier
  997. */
  998. tsk->plug = plug;
  999. }
  1000. /**
  1001. * blk_start_plug - initialize blk_plug and track it inside the task_struct
  1002. * @plug: The &struct blk_plug that needs to be initialized
  1003. *
  1004. * Description:
  1005. * blk_start_plug() indicates to the block layer an intent by the caller
  1006. * to submit multiple I/O requests in a batch. The block layer may use
  1007. * this hint to defer submitting I/Os from the caller until blk_finish_plug()
  1008. * is called. However, the block layer may choose to submit requests
  1009. * before a call to blk_finish_plug() if the number of queued I/Os
  1010. * exceeds %BLK_MAX_REQUEST_COUNT, or if the size of the I/O is larger than
  1011. * %BLK_PLUG_FLUSH_SIZE. The queued I/Os may also be submitted early if
  1012. * the task schedules (see below).
  1013. *
  1014. * Tracking blk_plug inside the task_struct will help with auto-flushing the
  1015. * pending I/O should the task end up blocking between blk_start_plug() and
  1016. * blk_finish_plug(). This is important from a performance perspective, but
  1017. * also ensures that we don't deadlock. For instance, if the task is blocking
  1018. * for a memory allocation, memory reclaim could end up wanting to free a
  1019. * page belonging to that request that is currently residing in our private
  1020. * plug. By flushing the pending I/O when the process goes to sleep, we avoid
  1021. * this kind of deadlock.
  1022. */
  1023. void blk_start_plug(struct blk_plug *plug)
  1024. {
  1025. blk_start_plug_nr_ios(plug, 1);
  1026. }
  1027. EXPORT_SYMBOL(blk_start_plug);
  1028. static void flush_plug_callbacks(struct blk_plug *plug, bool from_schedule)
  1029. {
  1030. LIST_HEAD(callbacks);
  1031. while (!list_empty(&plug->cb_list)) {
  1032. list_splice_init(&plug->cb_list, &callbacks);
  1033. while (!list_empty(&callbacks)) {
  1034. struct blk_plug_cb *cb = list_first_entry(&callbacks,
  1035. struct blk_plug_cb,
  1036. list);
  1037. list_del(&cb->list);
  1038. cb->callback(cb, from_schedule);
  1039. }
  1040. }
  1041. }
  1042. struct blk_plug_cb *blk_check_plugged(blk_plug_cb_fn unplug, void *data,
  1043. int size)
  1044. {
  1045. struct blk_plug *plug = current->plug;
  1046. struct blk_plug_cb *cb;
  1047. if (!plug)
  1048. return NULL;
  1049. list_for_each_entry(cb, &plug->cb_list, list)
  1050. if (cb->callback == unplug && cb->data == data)
  1051. return cb;
  1052. /* Not currently on the callback list */
  1053. BUG_ON(size < sizeof(*cb));
  1054. cb = kzalloc(size, GFP_ATOMIC);
  1055. if (cb) {
  1056. cb->data = data;
  1057. cb->callback = unplug;
  1058. list_add(&cb->list, &plug->cb_list);
  1059. }
  1060. return cb;
  1061. }
  1062. EXPORT_SYMBOL(blk_check_plugged);
  1063. void __blk_flush_plug(struct blk_plug *plug, bool from_schedule)
  1064. {
  1065. if (!list_empty(&plug->cb_list))
  1066. flush_plug_callbacks(plug, from_schedule);
  1067. blk_mq_flush_plug_list(plug, from_schedule);
  1068. /*
  1069. * Unconditionally flush out cached requests, even if the unplug
  1070. * event came from schedule. Since we know hold references to the
  1071. * queue for cached requests, we don't want a blocked task holding
  1072. * up a queue freeze/quiesce event.
  1073. */
  1074. if (unlikely(!rq_list_empty(&plug->cached_rqs)))
  1075. blk_mq_free_plug_rqs(plug);
  1076. plug->cur_ktime = 0;
  1077. current->flags &= ~PF_BLOCK_TS;
  1078. }
  1079. /**
  1080. * blk_finish_plug - mark the end of a batch of submitted I/O
  1081. * @plug: The &struct blk_plug passed to blk_start_plug()
  1082. *
  1083. * Description:
  1084. * Indicate that a batch of I/O submissions is complete. This function
  1085. * must be paired with an initial call to blk_start_plug(). The intent
  1086. * is to allow the block layer to optimize I/O submission. See the
  1087. * documentation for blk_start_plug() for more information.
  1088. */
  1089. void blk_finish_plug(struct blk_plug *plug)
  1090. {
  1091. if (plug == current->plug) {
  1092. __blk_flush_plug(plug, false);
  1093. current->plug = NULL;
  1094. }
  1095. }
  1096. EXPORT_SYMBOL(blk_finish_plug);
  1097. void blk_io_schedule(void)
  1098. {
  1099. /* Prevent hang_check timer from firing at us during very long I/O */
  1100. unsigned long timeout = sysctl_hung_task_timeout_secs * HZ / 2;
  1101. if (timeout)
  1102. io_schedule_timeout(timeout);
  1103. else
  1104. io_schedule();
  1105. }
  1106. EXPORT_SYMBOL_GPL(blk_io_schedule);
  1107. int __init blk_dev_init(void)
  1108. {
  1109. BUILD_BUG_ON((__force u32)REQ_OP_LAST >= (1 << REQ_OP_BITS));
  1110. BUILD_BUG_ON(REQ_OP_BITS + REQ_FLAG_BITS > 8 *
  1111. sizeof_field(struct request, cmd_flags));
  1112. BUILD_BUG_ON(REQ_OP_BITS + REQ_FLAG_BITS > 8 *
  1113. sizeof_field(struct bio, bi_opf));
  1114. /* used for unplugging and affects IO latency/throughput - HIGHPRI */
  1115. kblockd_workqueue = alloc_workqueue("kblockd",
  1116. WQ_MEM_RECLAIM | WQ_HIGHPRI, 0);
  1117. if (!kblockd_workqueue)
  1118. panic("Failed to create kblockd\n");
  1119. blk_requestq_cachep = KMEM_CACHE(request_queue, SLAB_PANIC);
  1120. blk_debugfs_root = debugfs_create_dir("block", NULL);
  1121. return 0;
  1122. }