blk-core.c 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819
  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/backing-dev.h>
  17. #include <linux/bio.h>
  18. #include <linux/blkdev.h>
  19. #include <linux/blk-mq.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/blk-cgroup.h>
  37. #include <linux/t10-pi.h>
  38. #include <linux/debugfs.h>
  39. #include <linux/bpf.h>
  40. #include <linux/psi.h>
  41. #include <linux/sched/sysctl.h>
  42. #include <linux/blk-crypto.h>
  43. #define CREATE_TRACE_POINTS
  44. #include <trace/events/block.h>
  45. #include "blk.h"
  46. #include "blk-mq.h"
  47. #include "blk-mq-sched.h"
  48. #include "blk-pm.h"
  49. #include "blk-rq-qos.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_bio_queue);
  57. EXPORT_TRACEPOINT_SYMBOL_GPL(block_getrq);
  58. EXPORT_TRACEPOINT_SYMBOL_GPL(block_rq_insert);
  59. EXPORT_TRACEPOINT_SYMBOL_GPL(block_rq_issue);
  60. EXPORT_TRACEPOINT_SYMBOL_GPL(block_rq_merge);
  61. EXPORT_TRACEPOINT_SYMBOL_GPL(block_rq_requeue);
  62. EXPORT_TRACEPOINT_SYMBOL_GPL(block_rq_complete);
  63. DEFINE_IDA(blk_queue_ida);
  64. /*
  65. * For queue allocation
  66. */
  67. struct kmem_cache *blk_requestq_cachep;
  68. /*
  69. * Controlling structure to kblockd
  70. */
  71. static struct workqueue_struct *kblockd_workqueue;
  72. /**
  73. * blk_queue_flag_set - atomically set a queue flag
  74. * @flag: flag to be set
  75. * @q: request queue
  76. */
  77. void blk_queue_flag_set(unsigned int flag, struct request_queue *q)
  78. {
  79. set_bit(flag, &q->queue_flags);
  80. }
  81. EXPORT_SYMBOL(blk_queue_flag_set);
  82. /**
  83. * blk_queue_flag_clear - atomically clear a queue flag
  84. * @flag: flag to be cleared
  85. * @q: request queue
  86. */
  87. void blk_queue_flag_clear(unsigned int flag, struct request_queue *q)
  88. {
  89. clear_bit(flag, &q->queue_flags);
  90. }
  91. EXPORT_SYMBOL(blk_queue_flag_clear);
  92. /**
  93. * blk_queue_flag_test_and_set - atomically test and set a queue flag
  94. * @flag: flag to be set
  95. * @q: request queue
  96. *
  97. * Returns the previous value of @flag - 0 if the flag was not set and 1 if
  98. * the flag was already set.
  99. */
  100. bool blk_queue_flag_test_and_set(unsigned int flag, struct request_queue *q)
  101. {
  102. return test_and_set_bit(flag, &q->queue_flags);
  103. }
  104. EXPORT_SYMBOL_GPL(blk_queue_flag_test_and_set);
  105. void blk_rq_init(struct request_queue *q, struct request *rq)
  106. {
  107. memset(rq, 0, sizeof(*rq));
  108. INIT_LIST_HEAD(&rq->queuelist);
  109. rq->q = q;
  110. rq->__sector = (sector_t) -1;
  111. INIT_HLIST_NODE(&rq->hash);
  112. RB_CLEAR_NODE(&rq->rb_node);
  113. rq->tag = BLK_MQ_NO_TAG;
  114. rq->internal_tag = BLK_MQ_NO_TAG;
  115. rq->start_time_ns = ktime_get_ns();
  116. rq->part = NULL;
  117. blk_crypto_rq_set_defaults(rq);
  118. }
  119. EXPORT_SYMBOL(blk_rq_init);
  120. #define REQ_OP_NAME(name) [REQ_OP_##name] = #name
  121. static const char *const blk_op_name[] = {
  122. REQ_OP_NAME(READ),
  123. REQ_OP_NAME(WRITE),
  124. REQ_OP_NAME(FLUSH),
  125. REQ_OP_NAME(DISCARD),
  126. REQ_OP_NAME(SECURE_ERASE),
  127. REQ_OP_NAME(ZONE_RESET),
  128. REQ_OP_NAME(ZONE_RESET_ALL),
  129. REQ_OP_NAME(ZONE_OPEN),
  130. REQ_OP_NAME(ZONE_CLOSE),
  131. REQ_OP_NAME(ZONE_FINISH),
  132. REQ_OP_NAME(ZONE_APPEND),
  133. REQ_OP_NAME(WRITE_SAME),
  134. REQ_OP_NAME(WRITE_ZEROES),
  135. REQ_OP_NAME(SCSI_IN),
  136. REQ_OP_NAME(SCSI_OUT),
  137. REQ_OP_NAME(DRV_IN),
  138. REQ_OP_NAME(DRV_OUT),
  139. };
  140. #undef REQ_OP_NAME
  141. /**
  142. * blk_op_str - Return string XXX in the REQ_OP_XXX.
  143. * @op: REQ_OP_XXX.
  144. *
  145. * Description: Centralize block layer function to convert REQ_OP_XXX into
  146. * string format. Useful in the debugging and tracing bio or request. For
  147. * invalid REQ_OP_XXX it returns string "UNKNOWN".
  148. */
  149. inline const char *blk_op_str(unsigned int op)
  150. {
  151. const char *op_str = "UNKNOWN";
  152. if (op < ARRAY_SIZE(blk_op_name) && blk_op_name[op])
  153. op_str = blk_op_name[op];
  154. return op_str;
  155. }
  156. EXPORT_SYMBOL_GPL(blk_op_str);
  157. static const struct {
  158. int errno;
  159. const char *name;
  160. } blk_errors[] = {
  161. [BLK_STS_OK] = { 0, "" },
  162. [BLK_STS_NOTSUPP] = { -EOPNOTSUPP, "operation not supported" },
  163. [BLK_STS_TIMEOUT] = { -ETIMEDOUT, "timeout" },
  164. [BLK_STS_NOSPC] = { -ENOSPC, "critical space allocation" },
  165. [BLK_STS_TRANSPORT] = { -ENOLINK, "recoverable transport" },
  166. [BLK_STS_TARGET] = { -EREMOTEIO, "critical target" },
  167. [BLK_STS_NEXUS] = { -EBADE, "critical nexus" },
  168. [BLK_STS_MEDIUM] = { -ENODATA, "critical medium" },
  169. [BLK_STS_PROTECTION] = { -EILSEQ, "protection" },
  170. [BLK_STS_RESOURCE] = { -ENOMEM, "kernel resource" },
  171. [BLK_STS_DEV_RESOURCE] = { -EBUSY, "device resource" },
  172. [BLK_STS_AGAIN] = { -EAGAIN, "nonblocking retry" },
  173. /* device mapper special case, should not leak out: */
  174. [BLK_STS_DM_REQUEUE] = { -EREMCHG, "dm internal retry" },
  175. /* zone device specific errors */
  176. [BLK_STS_ZONE_OPEN_RESOURCE] = { -ETOOMANYREFS, "open zones exceeded" },
  177. [BLK_STS_ZONE_ACTIVE_RESOURCE] = { -EOVERFLOW, "active zones exceeded" },
  178. /* everything else not covered above: */
  179. [BLK_STS_IOERR] = { -EIO, "I/O" },
  180. };
  181. blk_status_t errno_to_blk_status(int errno)
  182. {
  183. int i;
  184. for (i = 0; i < ARRAY_SIZE(blk_errors); i++) {
  185. if (blk_errors[i].errno == errno)
  186. return (__force blk_status_t)i;
  187. }
  188. return BLK_STS_IOERR;
  189. }
  190. EXPORT_SYMBOL_GPL(errno_to_blk_status);
  191. int blk_status_to_errno(blk_status_t status)
  192. {
  193. int idx = (__force int)status;
  194. if (WARN_ON_ONCE(idx >= ARRAY_SIZE(blk_errors)))
  195. return -EIO;
  196. return blk_errors[idx].errno;
  197. }
  198. EXPORT_SYMBOL_GPL(blk_status_to_errno);
  199. static void print_req_error(struct request *req, blk_status_t status,
  200. const char *caller)
  201. {
  202. int idx = (__force int)status;
  203. if (WARN_ON_ONCE(idx >= ARRAY_SIZE(blk_errors)))
  204. return;
  205. printk_ratelimited(KERN_ERR
  206. "%s: %s error, dev %s, sector %llu op 0x%x:(%s) flags 0x%x "
  207. "phys_seg %u prio class %u\n",
  208. caller, blk_errors[idx].name,
  209. req->rq_disk ? req->rq_disk->disk_name : "?",
  210. blk_rq_pos(req), req_op(req), blk_op_str(req_op(req)),
  211. req->cmd_flags & ~REQ_OP_MASK,
  212. req->nr_phys_segments,
  213. IOPRIO_PRIO_CLASS(req->ioprio));
  214. }
  215. static void req_bio_endio(struct request *rq, struct bio *bio,
  216. unsigned int nbytes, blk_status_t error)
  217. {
  218. if (error)
  219. bio->bi_status = error;
  220. if (unlikely(rq->rq_flags & RQF_QUIET))
  221. bio_set_flag(bio, BIO_QUIET);
  222. bio_advance(bio, nbytes);
  223. if (req_op(rq) == REQ_OP_ZONE_APPEND && error == BLK_STS_OK) {
  224. /*
  225. * Partial zone append completions cannot be supported as the
  226. * BIO fragments may end up not being written sequentially.
  227. */
  228. if (bio->bi_iter.bi_size)
  229. bio->bi_status = BLK_STS_IOERR;
  230. else
  231. bio->bi_iter.bi_sector = rq->__sector;
  232. }
  233. /* don't actually finish bio if it's part of flush sequence */
  234. if (bio->bi_iter.bi_size == 0 && !(rq->rq_flags & RQF_FLUSH_SEQ))
  235. bio_endio(bio);
  236. }
  237. void blk_dump_rq_flags(struct request *rq, char *msg)
  238. {
  239. printk(KERN_INFO "%s: dev %s: flags=%llx\n", msg,
  240. rq->rq_disk ? rq->rq_disk->disk_name : "?",
  241. (unsigned long long) rq->cmd_flags);
  242. printk(KERN_INFO " sector %llu, nr/cnr %u/%u\n",
  243. (unsigned long long)blk_rq_pos(rq),
  244. blk_rq_sectors(rq), blk_rq_cur_sectors(rq));
  245. printk(KERN_INFO " bio %p, biotail %p, len %u\n",
  246. rq->bio, rq->biotail, blk_rq_bytes(rq));
  247. }
  248. EXPORT_SYMBOL(blk_dump_rq_flags);
  249. /**
  250. * blk_sync_queue - cancel any pending callbacks on a queue
  251. * @q: the queue
  252. *
  253. * Description:
  254. * The block layer may perform asynchronous callback activity
  255. * on a queue, such as calling the unplug function after a timeout.
  256. * A block device may call blk_sync_queue to ensure that any
  257. * such activity is cancelled, thus allowing it to release resources
  258. * that the callbacks might use. The caller must already have made sure
  259. * that its ->submit_bio will not re-add plugging prior to calling
  260. * this function.
  261. *
  262. * This function does not cancel any asynchronous activity arising
  263. * out of elevator or throttling code. That would require elevator_exit()
  264. * and blkcg_exit_queue() to be called with queue lock initialized.
  265. *
  266. */
  267. void blk_sync_queue(struct request_queue *q)
  268. {
  269. del_timer_sync(&q->timeout);
  270. cancel_work_sync(&q->timeout_work);
  271. }
  272. EXPORT_SYMBOL(blk_sync_queue);
  273. /**
  274. * blk_set_pm_only - increment pm_only counter
  275. * @q: request queue pointer
  276. */
  277. void blk_set_pm_only(struct request_queue *q)
  278. {
  279. atomic_inc(&q->pm_only);
  280. }
  281. EXPORT_SYMBOL_GPL(blk_set_pm_only);
  282. void blk_clear_pm_only(struct request_queue *q)
  283. {
  284. int pm_only;
  285. pm_only = atomic_dec_return(&q->pm_only);
  286. WARN_ON_ONCE(pm_only < 0);
  287. if (pm_only == 0)
  288. wake_up_all(&q->mq_freeze_wq);
  289. }
  290. EXPORT_SYMBOL_GPL(blk_clear_pm_only);
  291. /**
  292. * blk_put_queue - decrement the request_queue refcount
  293. * @q: the request_queue structure to decrement the refcount for
  294. *
  295. * Decrements the refcount of the request_queue kobject. When this reaches 0
  296. * we'll have blk_release_queue() called.
  297. *
  298. * Context: Any context, but the last reference must not be dropped from
  299. * atomic context.
  300. */
  301. void blk_put_queue(struct request_queue *q)
  302. {
  303. kobject_put(&q->kobj);
  304. }
  305. EXPORT_SYMBOL(blk_put_queue);
  306. void blk_set_queue_dying(struct request_queue *q)
  307. {
  308. blk_queue_flag_set(QUEUE_FLAG_DYING, q);
  309. /*
  310. * When queue DYING flag is set, we need to block new req
  311. * entering queue, so we call blk_freeze_queue_start() to
  312. * prevent I/O from crossing blk_queue_enter().
  313. */
  314. blk_freeze_queue_start(q);
  315. if (queue_is_mq(q))
  316. blk_mq_wake_waiters(q);
  317. /* Make blk_queue_enter() reexamine the DYING flag. */
  318. wake_up_all(&q->mq_freeze_wq);
  319. }
  320. EXPORT_SYMBOL_GPL(blk_set_queue_dying);
  321. /**
  322. * blk_cleanup_queue - shutdown a request queue
  323. * @q: request queue to shutdown
  324. *
  325. * Mark @q DYING, drain all pending requests, mark @q DEAD, destroy and
  326. * put it. All future requests will be failed immediately with -ENODEV.
  327. *
  328. * Context: can sleep
  329. */
  330. void blk_cleanup_queue(struct request_queue *q)
  331. {
  332. /* cannot be called from atomic context */
  333. might_sleep();
  334. WARN_ON_ONCE(blk_queue_registered(q));
  335. /* mark @q DYING, no new request or merges will be allowed afterwards */
  336. blk_set_queue_dying(q);
  337. blk_queue_flag_set(QUEUE_FLAG_NOMERGES, q);
  338. blk_queue_flag_set(QUEUE_FLAG_NOXMERGES, q);
  339. /*
  340. * Drain all requests queued before DYING marking. Set DEAD flag to
  341. * prevent that blk_mq_run_hw_queues() accesses the hardware queues
  342. * after draining finished.
  343. */
  344. blk_freeze_queue(q);
  345. rq_qos_exit(q);
  346. blk_queue_flag_set(QUEUE_FLAG_DEAD, q);
  347. /* for synchronous bio-based driver finish in-flight integrity i/o */
  348. blk_flush_integrity();
  349. /* @q won't process any more request, flush async actions */
  350. del_timer_sync(&q->backing_dev_info->laptop_mode_wb_timer);
  351. blk_sync_queue(q);
  352. if (queue_is_mq(q))
  353. blk_mq_exit_queue(q);
  354. /*
  355. * In theory, request pool of sched_tags belongs to request queue.
  356. * However, the current implementation requires tag_set for freeing
  357. * requests, so free the pool now.
  358. *
  359. * Queue has become frozen, there can't be any in-queue requests, so
  360. * it is safe to free requests now.
  361. */
  362. mutex_lock(&q->sysfs_lock);
  363. if (q->elevator)
  364. blk_mq_sched_free_requests(q);
  365. mutex_unlock(&q->sysfs_lock);
  366. percpu_ref_exit(&q->q_usage_counter);
  367. /* @q is and will stay empty, shutdown and put */
  368. blk_put_queue(q);
  369. }
  370. EXPORT_SYMBOL(blk_cleanup_queue);
  371. /**
  372. * blk_queue_enter() - try to increase q->q_usage_counter
  373. * @q: request queue pointer
  374. * @flags: BLK_MQ_REQ_NOWAIT and/or BLK_MQ_REQ_PM
  375. */
  376. int blk_queue_enter(struct request_queue *q, blk_mq_req_flags_t flags)
  377. {
  378. const bool pm = flags & BLK_MQ_REQ_PM;
  379. while (true) {
  380. bool success = false;
  381. rcu_read_lock();
  382. if (percpu_ref_tryget_live(&q->q_usage_counter)) {
  383. /*
  384. * The code that increments the pm_only counter is
  385. * responsible for ensuring that that counter is
  386. * globally visible before the queue is unfrozen.
  387. */
  388. if (pm || !blk_queue_pm_only(q)) {
  389. success = true;
  390. } else {
  391. percpu_ref_put(&q->q_usage_counter);
  392. }
  393. }
  394. rcu_read_unlock();
  395. if (success)
  396. return 0;
  397. if (flags & BLK_MQ_REQ_NOWAIT)
  398. return -EBUSY;
  399. /*
  400. * read pair of barrier in blk_freeze_queue_start(),
  401. * we need to order reading __PERCPU_REF_DEAD flag of
  402. * .q_usage_counter and reading .mq_freeze_depth or
  403. * queue dying flag, otherwise the following wait may
  404. * never return if the two reads are reordered.
  405. */
  406. smp_rmb();
  407. wait_event(q->mq_freeze_wq,
  408. (!q->mq_freeze_depth &&
  409. (pm || (blk_pm_request_resume(q),
  410. !blk_queue_pm_only(q)))) ||
  411. blk_queue_dying(q));
  412. if (blk_queue_dying(q))
  413. return -ENODEV;
  414. }
  415. }
  416. static inline int bio_queue_enter(struct bio *bio)
  417. {
  418. struct request_queue *q = bio->bi_disk->queue;
  419. bool nowait = bio->bi_opf & REQ_NOWAIT;
  420. int ret;
  421. ret = blk_queue_enter(q, nowait ? BLK_MQ_REQ_NOWAIT : 0);
  422. if (unlikely(ret)) {
  423. if (nowait && !blk_queue_dying(q))
  424. bio_wouldblock_error(bio);
  425. else
  426. bio_io_error(bio);
  427. }
  428. return ret;
  429. }
  430. void blk_queue_exit(struct request_queue *q)
  431. {
  432. percpu_ref_put(&q->q_usage_counter);
  433. }
  434. static void blk_queue_usage_counter_release(struct percpu_ref *ref)
  435. {
  436. struct request_queue *q =
  437. container_of(ref, struct request_queue, q_usage_counter);
  438. wake_up_all(&q->mq_freeze_wq);
  439. }
  440. static void blk_rq_timed_out_timer(struct timer_list *t)
  441. {
  442. struct request_queue *q = from_timer(q, t, timeout);
  443. kblockd_schedule_work(&q->timeout_work);
  444. }
  445. static void blk_timeout_work(struct work_struct *work)
  446. {
  447. }
  448. struct request_queue *blk_alloc_queue(int node_id)
  449. {
  450. struct request_queue *q;
  451. int ret;
  452. q = kmem_cache_alloc_node(blk_requestq_cachep,
  453. GFP_KERNEL | __GFP_ZERO, node_id);
  454. if (!q)
  455. return NULL;
  456. q->last_merge = NULL;
  457. q->id = ida_simple_get(&blk_queue_ida, 0, 0, GFP_KERNEL);
  458. if (q->id < 0)
  459. goto fail_q;
  460. ret = bioset_init(&q->bio_split, BIO_POOL_SIZE, 0, BIOSET_NEED_BVECS);
  461. if (ret)
  462. goto fail_id;
  463. q->backing_dev_info = bdi_alloc(node_id);
  464. if (!q->backing_dev_info)
  465. goto fail_split;
  466. q->stats = blk_alloc_queue_stats();
  467. if (!q->stats)
  468. goto fail_stats;
  469. q->node = node_id;
  470. atomic_set(&q->nr_active_requests_shared_sbitmap, 0);
  471. timer_setup(&q->backing_dev_info->laptop_mode_wb_timer,
  472. laptop_mode_timer_fn, 0);
  473. timer_setup(&q->timeout, blk_rq_timed_out_timer, 0);
  474. INIT_WORK(&q->timeout_work, blk_timeout_work);
  475. INIT_LIST_HEAD(&q->icq_list);
  476. #ifdef CONFIG_BLK_CGROUP
  477. INIT_LIST_HEAD(&q->blkg_list);
  478. #endif
  479. kobject_init(&q->kobj, &blk_queue_ktype);
  480. mutex_init(&q->debugfs_mutex);
  481. mutex_init(&q->sysfs_lock);
  482. mutex_init(&q->sysfs_dir_lock);
  483. spin_lock_init(&q->queue_lock);
  484. init_waitqueue_head(&q->mq_freeze_wq);
  485. mutex_init(&q->mq_freeze_lock);
  486. /*
  487. * Init percpu_ref in atomic mode so that it's faster to shutdown.
  488. * See blk_register_queue() for details.
  489. */
  490. if (percpu_ref_init(&q->q_usage_counter,
  491. blk_queue_usage_counter_release,
  492. PERCPU_REF_INIT_ATOMIC, GFP_KERNEL))
  493. goto fail_bdi;
  494. if (blkcg_init_queue(q))
  495. goto fail_ref;
  496. blk_queue_dma_alignment(q, 511);
  497. blk_set_default_limits(&q->limits);
  498. q->nr_requests = BLKDEV_MAX_RQ;
  499. return q;
  500. fail_ref:
  501. percpu_ref_exit(&q->q_usage_counter);
  502. fail_bdi:
  503. blk_free_queue_stats(q->stats);
  504. fail_stats:
  505. bdi_put(q->backing_dev_info);
  506. fail_split:
  507. bioset_exit(&q->bio_split);
  508. fail_id:
  509. ida_simple_remove(&blk_queue_ida, q->id);
  510. fail_q:
  511. kmem_cache_free(blk_requestq_cachep, q);
  512. return NULL;
  513. }
  514. EXPORT_SYMBOL(blk_alloc_queue);
  515. /**
  516. * blk_get_queue - increment the request_queue refcount
  517. * @q: the request_queue structure to increment the refcount for
  518. *
  519. * Increment the refcount of the request_queue kobject.
  520. *
  521. * Context: Any context.
  522. */
  523. bool blk_get_queue(struct request_queue *q)
  524. {
  525. if (likely(!blk_queue_dying(q))) {
  526. __blk_get_queue(q);
  527. return true;
  528. }
  529. return false;
  530. }
  531. EXPORT_SYMBOL(blk_get_queue);
  532. /**
  533. * blk_get_request - allocate a request
  534. * @q: request queue to allocate a request for
  535. * @op: operation (REQ_OP_*) and REQ_* flags, e.g. REQ_SYNC.
  536. * @flags: BLK_MQ_REQ_* flags, e.g. BLK_MQ_REQ_NOWAIT.
  537. */
  538. struct request *blk_get_request(struct request_queue *q, unsigned int op,
  539. blk_mq_req_flags_t flags)
  540. {
  541. struct request *req;
  542. WARN_ON_ONCE(op & REQ_NOWAIT);
  543. WARN_ON_ONCE(flags & ~(BLK_MQ_REQ_NOWAIT | BLK_MQ_REQ_PM));
  544. req = blk_mq_alloc_request(q, op, flags);
  545. if (!IS_ERR(req) && q->mq_ops->initialize_rq_fn)
  546. q->mq_ops->initialize_rq_fn(req);
  547. return req;
  548. }
  549. EXPORT_SYMBOL(blk_get_request);
  550. void blk_put_request(struct request *req)
  551. {
  552. blk_mq_free_request(req);
  553. }
  554. EXPORT_SYMBOL(blk_put_request);
  555. static void handle_bad_sector(struct bio *bio, sector_t maxsector)
  556. {
  557. char b[BDEVNAME_SIZE];
  558. pr_info_ratelimited("attempt to access beyond end of device\n"
  559. "%s: rw=%d, want=%llu, limit=%llu\n",
  560. bio_devname(bio, b), bio->bi_opf,
  561. bio_end_sector(bio), maxsector);
  562. }
  563. #ifdef CONFIG_FAIL_MAKE_REQUEST
  564. static DECLARE_FAULT_ATTR(fail_make_request);
  565. static int __init setup_fail_make_request(char *str)
  566. {
  567. return setup_fault_attr(&fail_make_request, str);
  568. }
  569. __setup("fail_make_request=", setup_fail_make_request);
  570. static bool should_fail_request(struct hd_struct *part, unsigned int bytes)
  571. {
  572. return part->make_it_fail && should_fail(&fail_make_request, bytes);
  573. }
  574. static int __init fail_make_request_debugfs(void)
  575. {
  576. struct dentry *dir = fault_create_debugfs_attr("fail_make_request",
  577. NULL, &fail_make_request);
  578. return PTR_ERR_OR_ZERO(dir);
  579. }
  580. late_initcall(fail_make_request_debugfs);
  581. #else /* CONFIG_FAIL_MAKE_REQUEST */
  582. static inline bool should_fail_request(struct hd_struct *part,
  583. unsigned int bytes)
  584. {
  585. return false;
  586. }
  587. #endif /* CONFIG_FAIL_MAKE_REQUEST */
  588. static inline bool bio_check_ro(struct bio *bio, struct hd_struct *part)
  589. {
  590. const int op = bio_op(bio);
  591. if (part->policy && op_is_write(op)) {
  592. char b[BDEVNAME_SIZE];
  593. if (op_is_flush(bio->bi_opf) && !bio_sectors(bio))
  594. return false;
  595. WARN_ONCE(1,
  596. "Trying to write to read-only block-device %s (partno %d)\n",
  597. bio_devname(bio, b), part->partno);
  598. /* Older lvm-tools actually trigger this */
  599. return false;
  600. }
  601. return false;
  602. }
  603. static noinline int should_fail_bio(struct bio *bio)
  604. {
  605. if (should_fail_request(&bio->bi_disk->part0, bio->bi_iter.bi_size))
  606. return -EIO;
  607. return 0;
  608. }
  609. ALLOW_ERROR_INJECTION(should_fail_bio, ERRNO);
  610. /*
  611. * Check whether this bio extends beyond the end of the device or partition.
  612. * This may well happen - the kernel calls bread() without checking the size of
  613. * the device, e.g., when mounting a file system.
  614. */
  615. static inline int bio_check_eod(struct bio *bio, sector_t maxsector)
  616. {
  617. unsigned int nr_sectors = bio_sectors(bio);
  618. if (nr_sectors && maxsector &&
  619. (nr_sectors > maxsector ||
  620. bio->bi_iter.bi_sector > maxsector - nr_sectors)) {
  621. handle_bad_sector(bio, maxsector);
  622. return -EIO;
  623. }
  624. return 0;
  625. }
  626. /*
  627. * Remap block n of partition p to block n+start(p) of the disk.
  628. */
  629. static inline int blk_partition_remap(struct bio *bio)
  630. {
  631. struct hd_struct *p;
  632. int ret = -EIO;
  633. rcu_read_lock();
  634. p = __disk_get_part(bio->bi_disk, bio->bi_partno);
  635. if (unlikely(!p))
  636. goto out;
  637. if (unlikely(should_fail_request(p, bio->bi_iter.bi_size)))
  638. goto out;
  639. if (unlikely(bio_check_ro(bio, p)))
  640. goto out;
  641. if (bio_sectors(bio)) {
  642. if (bio_check_eod(bio, part_nr_sects_read(p)))
  643. goto out;
  644. bio->bi_iter.bi_sector += p->start_sect;
  645. trace_block_bio_remap(bio->bi_disk->queue, bio, part_devt(p),
  646. bio->bi_iter.bi_sector - p->start_sect);
  647. }
  648. bio->bi_partno = 0;
  649. ret = 0;
  650. out:
  651. rcu_read_unlock();
  652. return ret;
  653. }
  654. /*
  655. * Check write append to a zoned block device.
  656. */
  657. static inline blk_status_t blk_check_zone_append(struct request_queue *q,
  658. struct bio *bio)
  659. {
  660. sector_t pos = bio->bi_iter.bi_sector;
  661. int nr_sectors = bio_sectors(bio);
  662. /* Only applicable to zoned block devices */
  663. if (!blk_queue_is_zoned(q))
  664. return BLK_STS_NOTSUPP;
  665. /* The bio sector must point to the start of a sequential zone */
  666. if (pos & (blk_queue_zone_sectors(q) - 1) ||
  667. !blk_queue_zone_is_seq(q, pos))
  668. return BLK_STS_IOERR;
  669. /*
  670. * Not allowed to cross zone boundaries. Otherwise, the BIO will be
  671. * split and could result in non-contiguous sectors being written in
  672. * different zones.
  673. */
  674. if (nr_sectors > q->limits.chunk_sectors)
  675. return BLK_STS_IOERR;
  676. /* Make sure the BIO is small enough and will not get split */
  677. if (nr_sectors > q->limits.max_zone_append_sectors)
  678. return BLK_STS_IOERR;
  679. bio->bi_opf |= REQ_NOMERGE;
  680. return BLK_STS_OK;
  681. }
  682. static noinline_for_stack bool submit_bio_checks(struct bio *bio)
  683. {
  684. struct request_queue *q = bio->bi_disk->queue;
  685. blk_status_t status = BLK_STS_IOERR;
  686. struct blk_plug *plug;
  687. might_sleep();
  688. plug = blk_mq_plug(q, bio);
  689. if (plug && plug->nowait)
  690. bio->bi_opf |= REQ_NOWAIT;
  691. /*
  692. * For a REQ_NOWAIT based request, return -EOPNOTSUPP
  693. * if queue does not support NOWAIT.
  694. */
  695. if ((bio->bi_opf & REQ_NOWAIT) && !blk_queue_nowait(q))
  696. goto not_supported;
  697. if (should_fail_bio(bio))
  698. goto end_io;
  699. if (bio->bi_partno) {
  700. if (unlikely(blk_partition_remap(bio)))
  701. goto end_io;
  702. } else {
  703. if (unlikely(bio_check_ro(bio, &bio->bi_disk->part0)))
  704. goto end_io;
  705. if (unlikely(bio_check_eod(bio, get_capacity(bio->bi_disk))))
  706. goto end_io;
  707. }
  708. /*
  709. * Filter flush bio's early so that bio based drivers without flush
  710. * support don't have to worry about them.
  711. */
  712. if (op_is_flush(bio->bi_opf) &&
  713. !test_bit(QUEUE_FLAG_WC, &q->queue_flags)) {
  714. bio->bi_opf &= ~(REQ_PREFLUSH | REQ_FUA);
  715. if (!bio_sectors(bio)) {
  716. status = BLK_STS_OK;
  717. goto end_io;
  718. }
  719. }
  720. if (!test_bit(QUEUE_FLAG_POLL, &q->queue_flags))
  721. bio->bi_opf &= ~REQ_HIPRI;
  722. switch (bio_op(bio)) {
  723. case REQ_OP_DISCARD:
  724. if (!blk_queue_discard(q))
  725. goto not_supported;
  726. break;
  727. case REQ_OP_SECURE_ERASE:
  728. if (!blk_queue_secure_erase(q))
  729. goto not_supported;
  730. break;
  731. case REQ_OP_WRITE_SAME:
  732. if (!q->limits.max_write_same_sectors)
  733. goto not_supported;
  734. break;
  735. case REQ_OP_ZONE_APPEND:
  736. status = blk_check_zone_append(q, bio);
  737. if (status != BLK_STS_OK)
  738. goto end_io;
  739. break;
  740. case REQ_OP_ZONE_RESET:
  741. case REQ_OP_ZONE_OPEN:
  742. case REQ_OP_ZONE_CLOSE:
  743. case REQ_OP_ZONE_FINISH:
  744. if (!blk_queue_is_zoned(q))
  745. goto not_supported;
  746. break;
  747. case REQ_OP_ZONE_RESET_ALL:
  748. if (!blk_queue_is_zoned(q) || !blk_queue_zone_resetall(q))
  749. goto not_supported;
  750. break;
  751. case REQ_OP_WRITE_ZEROES:
  752. if (!q->limits.max_write_zeroes_sectors)
  753. goto not_supported;
  754. break;
  755. default:
  756. break;
  757. }
  758. /*
  759. * Various block parts want %current->io_context, so allocate it up
  760. * front rather than dealing with lots of pain to allocate it only
  761. * where needed. This may fail and the block layer knows how to live
  762. * with it.
  763. */
  764. if (unlikely(!current->io_context))
  765. create_task_io_context(current, GFP_ATOMIC, q->node);
  766. if (blk_throtl_bio(bio))
  767. return false;
  768. blk_cgroup_bio_start(bio);
  769. blkcg_bio_issue_init(bio);
  770. if (!bio_flagged(bio, BIO_TRACE_COMPLETION)) {
  771. trace_block_bio_queue(q, bio);
  772. /* Now that enqueuing has been traced, we need to trace
  773. * completion as well.
  774. */
  775. bio_set_flag(bio, BIO_TRACE_COMPLETION);
  776. }
  777. return true;
  778. not_supported:
  779. status = BLK_STS_NOTSUPP;
  780. end_io:
  781. bio->bi_status = status;
  782. bio_endio(bio);
  783. return false;
  784. }
  785. static blk_qc_t __submit_bio(struct bio *bio)
  786. {
  787. struct gendisk *disk = bio->bi_disk;
  788. blk_qc_t ret = BLK_QC_T_NONE;
  789. if (blk_crypto_bio_prep(&bio)) {
  790. if (!disk->fops->submit_bio)
  791. return blk_mq_submit_bio(bio);
  792. ret = disk->fops->submit_bio(bio);
  793. }
  794. blk_queue_exit(disk->queue);
  795. return ret;
  796. }
  797. /*
  798. * The loop in this function may be a bit non-obvious, and so deserves some
  799. * explanation:
  800. *
  801. * - Before entering the loop, bio->bi_next is NULL (as all callers ensure
  802. * that), so we have a list with a single bio.
  803. * - We pretend that we have just taken it off a longer list, so we assign
  804. * bio_list to a pointer to the bio_list_on_stack, thus initialising the
  805. * bio_list of new bios to be added. ->submit_bio() may indeed add some more
  806. * bios through a recursive call to submit_bio_noacct. If it did, we find a
  807. * non-NULL value in bio_list and re-enter the loop from the top.
  808. * - In this case we really did just take the bio of the top of the list (no
  809. * pretending) and so remove it from bio_list, and call into ->submit_bio()
  810. * again.
  811. *
  812. * bio_list_on_stack[0] contains bios submitted by the current ->submit_bio.
  813. * bio_list_on_stack[1] contains bios that were submitted before the current
  814. * ->submit_bio_bio, but that haven't been processed yet.
  815. */
  816. static blk_qc_t __submit_bio_noacct(struct bio *bio)
  817. {
  818. struct bio_list bio_list_on_stack[2];
  819. blk_qc_t ret = BLK_QC_T_NONE;
  820. BUG_ON(bio->bi_next);
  821. bio_list_init(&bio_list_on_stack[0]);
  822. current->bio_list = bio_list_on_stack;
  823. do {
  824. struct request_queue *q = bio->bi_disk->queue;
  825. struct bio_list lower, same;
  826. if (unlikely(bio_queue_enter(bio) != 0))
  827. continue;
  828. /*
  829. * Create a fresh bio_list for all subordinate requests.
  830. */
  831. bio_list_on_stack[1] = bio_list_on_stack[0];
  832. bio_list_init(&bio_list_on_stack[0]);
  833. ret = __submit_bio(bio);
  834. /*
  835. * Sort new bios into those for a lower level and those for the
  836. * same level.
  837. */
  838. bio_list_init(&lower);
  839. bio_list_init(&same);
  840. while ((bio = bio_list_pop(&bio_list_on_stack[0])) != NULL)
  841. if (q == bio->bi_disk->queue)
  842. bio_list_add(&same, bio);
  843. else
  844. bio_list_add(&lower, bio);
  845. /*
  846. * Now assemble so we handle the lowest level first.
  847. */
  848. bio_list_merge(&bio_list_on_stack[0], &lower);
  849. bio_list_merge(&bio_list_on_stack[0], &same);
  850. bio_list_merge(&bio_list_on_stack[0], &bio_list_on_stack[1]);
  851. } while ((bio = bio_list_pop(&bio_list_on_stack[0])));
  852. current->bio_list = NULL;
  853. return ret;
  854. }
  855. static blk_qc_t __submit_bio_noacct_mq(struct bio *bio)
  856. {
  857. struct bio_list bio_list[2] = { };
  858. blk_qc_t ret = BLK_QC_T_NONE;
  859. current->bio_list = bio_list;
  860. do {
  861. struct gendisk *disk = bio->bi_disk;
  862. if (unlikely(bio_queue_enter(bio) != 0))
  863. continue;
  864. if (!blk_crypto_bio_prep(&bio)) {
  865. blk_queue_exit(disk->queue);
  866. ret = BLK_QC_T_NONE;
  867. continue;
  868. }
  869. ret = blk_mq_submit_bio(bio);
  870. } while ((bio = bio_list_pop(&bio_list[0])));
  871. current->bio_list = NULL;
  872. return ret;
  873. }
  874. /**
  875. * submit_bio_noacct - re-submit a bio to the block device layer for I/O
  876. * @bio: The bio describing the location in memory and on the device.
  877. *
  878. * This is a version of submit_bio() that shall only be used for I/O that is
  879. * resubmitted to lower level drivers by stacking block drivers. All file
  880. * systems and other upper level users of the block layer should use
  881. * submit_bio() instead.
  882. */
  883. blk_qc_t submit_bio_noacct(struct bio *bio)
  884. {
  885. if (!submit_bio_checks(bio))
  886. return BLK_QC_T_NONE;
  887. /*
  888. * We only want one ->submit_bio to be active at a time, else stack
  889. * usage with stacked devices could be a problem. Use current->bio_list
  890. * to collect a list of requests submited by a ->submit_bio method while
  891. * it is active, and then process them after it returned.
  892. */
  893. if (current->bio_list) {
  894. bio_list_add(&current->bio_list[0], bio);
  895. return BLK_QC_T_NONE;
  896. }
  897. if (!bio->bi_disk->fops->submit_bio)
  898. return __submit_bio_noacct_mq(bio);
  899. return __submit_bio_noacct(bio);
  900. }
  901. EXPORT_SYMBOL(submit_bio_noacct);
  902. /**
  903. * submit_bio - submit a bio to the block device layer for I/O
  904. * @bio: The &struct bio which describes the I/O
  905. *
  906. * submit_bio() is used to submit I/O requests to block devices. It is passed a
  907. * fully set up &struct bio that describes the I/O that needs to be done. The
  908. * bio will be send to the device described by the bi_disk and bi_partno fields.
  909. *
  910. * The success/failure status of the request, along with notification of
  911. * completion, is delivered asynchronously through the ->bi_end_io() callback
  912. * in @bio. The bio must NOT be touched by thecaller until ->bi_end_io() has
  913. * been called.
  914. */
  915. blk_qc_t submit_bio(struct bio *bio)
  916. {
  917. if (blkcg_punt_bio_submit(bio))
  918. return BLK_QC_T_NONE;
  919. /*
  920. * If it's a regular read/write or a barrier with data attached,
  921. * go through the normal accounting stuff before submission.
  922. */
  923. if (bio_has_data(bio)) {
  924. unsigned int count;
  925. if (unlikely(bio_op(bio) == REQ_OP_WRITE_SAME))
  926. count = queue_logical_block_size(bio->bi_disk->queue) >> 9;
  927. else
  928. count = bio_sectors(bio);
  929. if (op_is_write(bio_op(bio))) {
  930. count_vm_events(PGPGOUT, count);
  931. } else {
  932. task_io_account_read(bio->bi_iter.bi_size);
  933. count_vm_events(PGPGIN, count);
  934. }
  935. if (unlikely(block_dump)) {
  936. char b[BDEVNAME_SIZE];
  937. printk(KERN_DEBUG "%s(%d): %s block %Lu on %s (%u sectors)\n",
  938. current->comm, task_pid_nr(current),
  939. op_is_write(bio_op(bio)) ? "WRITE" : "READ",
  940. (unsigned long long)bio->bi_iter.bi_sector,
  941. bio_devname(bio, b), count);
  942. }
  943. }
  944. /*
  945. * If we're reading data that is part of the userspace workingset, count
  946. * submission time as memory stall. When the device is congested, or
  947. * the submitting cgroup IO-throttled, submission can be a significant
  948. * part of overall IO time.
  949. */
  950. if (unlikely(bio_op(bio) == REQ_OP_READ &&
  951. bio_flagged(bio, BIO_WORKINGSET))) {
  952. unsigned long pflags;
  953. blk_qc_t ret;
  954. psi_memstall_enter(&pflags);
  955. ret = submit_bio_noacct(bio);
  956. psi_memstall_leave(&pflags);
  957. return ret;
  958. }
  959. return submit_bio_noacct(bio);
  960. }
  961. EXPORT_SYMBOL(submit_bio);
  962. /**
  963. * blk_cloned_rq_check_limits - Helper function to check a cloned request
  964. * for the new queue limits
  965. * @q: the queue
  966. * @rq: the request being checked
  967. *
  968. * Description:
  969. * @rq may have been made based on weaker limitations of upper-level queues
  970. * in request stacking drivers, and it may violate the limitation of @q.
  971. * Since the block layer and the underlying device driver trust @rq
  972. * after it is inserted to @q, it should be checked against @q before
  973. * the insertion using this generic function.
  974. *
  975. * Request stacking drivers like request-based dm may change the queue
  976. * limits when retrying requests on other queues. Those requests need
  977. * to be checked against the new queue limits again during dispatch.
  978. */
  979. static blk_status_t blk_cloned_rq_check_limits(struct request_queue *q,
  980. struct request *rq)
  981. {
  982. unsigned int max_sectors = blk_queue_get_max_sectors(q, req_op(rq));
  983. if (blk_rq_sectors(rq) > max_sectors) {
  984. /*
  985. * SCSI device does not have a good way to return if
  986. * Write Same/Zero is actually supported. If a device rejects
  987. * a non-read/write command (discard, write same,etc.) the
  988. * low-level device driver will set the relevant queue limit to
  989. * 0 to prevent blk-lib from issuing more of the offending
  990. * operations. Commands queued prior to the queue limit being
  991. * reset need to be completed with BLK_STS_NOTSUPP to avoid I/O
  992. * errors being propagated to upper layers.
  993. */
  994. if (max_sectors == 0)
  995. return BLK_STS_NOTSUPP;
  996. printk(KERN_ERR "%s: over max size limit. (%u > %u)\n",
  997. __func__, blk_rq_sectors(rq), max_sectors);
  998. return BLK_STS_IOERR;
  999. }
  1000. /*
  1001. * queue's settings related to segment counting like q->bounce_pfn
  1002. * may differ from that of other stacking queues.
  1003. * Recalculate it to check the request correctly on this queue's
  1004. * limitation.
  1005. */
  1006. rq->nr_phys_segments = blk_recalc_rq_segments(rq);
  1007. if (rq->nr_phys_segments > queue_max_segments(q)) {
  1008. printk(KERN_ERR "%s: over max segments limit. (%hu > %hu)\n",
  1009. __func__, rq->nr_phys_segments, queue_max_segments(q));
  1010. return BLK_STS_IOERR;
  1011. }
  1012. return BLK_STS_OK;
  1013. }
  1014. /**
  1015. * blk_insert_cloned_request - Helper for stacking drivers to submit a request
  1016. * @q: the queue to submit the request
  1017. * @rq: the request being queued
  1018. */
  1019. blk_status_t blk_insert_cloned_request(struct request_queue *q, struct request *rq)
  1020. {
  1021. blk_status_t ret;
  1022. ret = blk_cloned_rq_check_limits(q, rq);
  1023. if (ret != BLK_STS_OK)
  1024. return ret;
  1025. if (rq->rq_disk &&
  1026. should_fail_request(&rq->rq_disk->part0, blk_rq_bytes(rq)))
  1027. return BLK_STS_IOERR;
  1028. if (blk_crypto_insert_cloned_request(rq))
  1029. return BLK_STS_IOERR;
  1030. if (blk_queue_io_stat(q))
  1031. blk_account_io_start(rq);
  1032. /*
  1033. * Since we have a scheduler attached on the top device,
  1034. * bypass a potential scheduler on the bottom device for
  1035. * insert.
  1036. */
  1037. return blk_mq_request_issue_directly(rq, true);
  1038. }
  1039. EXPORT_SYMBOL_GPL(blk_insert_cloned_request);
  1040. /**
  1041. * blk_rq_err_bytes - determine number of bytes till the next failure boundary
  1042. * @rq: request to examine
  1043. *
  1044. * Description:
  1045. * A request could be merge of IOs which require different failure
  1046. * handling. This function determines the number of bytes which
  1047. * can be failed from the beginning of the request without
  1048. * crossing into area which need to be retried further.
  1049. *
  1050. * Return:
  1051. * The number of bytes to fail.
  1052. */
  1053. unsigned int blk_rq_err_bytes(const struct request *rq)
  1054. {
  1055. unsigned int ff = rq->cmd_flags & REQ_FAILFAST_MASK;
  1056. unsigned int bytes = 0;
  1057. struct bio *bio;
  1058. if (!(rq->rq_flags & RQF_MIXED_MERGE))
  1059. return blk_rq_bytes(rq);
  1060. /*
  1061. * Currently the only 'mixing' which can happen is between
  1062. * different fastfail types. We can safely fail portions
  1063. * which have all the failfast bits that the first one has -
  1064. * the ones which are at least as eager to fail as the first
  1065. * one.
  1066. */
  1067. for (bio = rq->bio; bio; bio = bio->bi_next) {
  1068. if ((bio->bi_opf & ff) != ff)
  1069. break;
  1070. bytes += bio->bi_iter.bi_size;
  1071. }
  1072. /* this could lead to infinite loop */
  1073. BUG_ON(blk_rq_bytes(rq) && !bytes);
  1074. return bytes;
  1075. }
  1076. EXPORT_SYMBOL_GPL(blk_rq_err_bytes);
  1077. static void update_io_ticks(struct hd_struct *part, unsigned long now, bool end)
  1078. {
  1079. unsigned long stamp;
  1080. again:
  1081. stamp = READ_ONCE(part->stamp);
  1082. if (unlikely(stamp != now)) {
  1083. if (likely(cmpxchg(&part->stamp, stamp, now) == stamp))
  1084. __part_stat_add(part, io_ticks, end ? now - stamp : 1);
  1085. }
  1086. if (part->partno) {
  1087. part = &part_to_disk(part)->part0;
  1088. goto again;
  1089. }
  1090. }
  1091. static void blk_account_io_completion(struct request *req, unsigned int bytes)
  1092. {
  1093. if (req->part && blk_do_io_stat(req)) {
  1094. const int sgrp = op_stat_group(req_op(req));
  1095. struct hd_struct *part;
  1096. part_stat_lock();
  1097. part = req->part;
  1098. part_stat_add(part, sectors[sgrp], bytes >> 9);
  1099. part_stat_unlock();
  1100. }
  1101. }
  1102. void blk_account_io_done(struct request *req, u64 now)
  1103. {
  1104. /*
  1105. * Account IO completion. flush_rq isn't accounted as a
  1106. * normal IO on queueing nor completion. Accounting the
  1107. * containing request is enough.
  1108. */
  1109. if (req->part && blk_do_io_stat(req) &&
  1110. !(req->rq_flags & RQF_FLUSH_SEQ)) {
  1111. const int sgrp = op_stat_group(req_op(req));
  1112. struct hd_struct *part;
  1113. part_stat_lock();
  1114. part = req->part;
  1115. update_io_ticks(part, jiffies, true);
  1116. part_stat_inc(part, ios[sgrp]);
  1117. part_stat_add(part, nsecs[sgrp], now - req->start_time_ns);
  1118. part_stat_unlock();
  1119. hd_struct_put(part);
  1120. }
  1121. }
  1122. void blk_account_io_start(struct request *rq)
  1123. {
  1124. if (!blk_do_io_stat(rq))
  1125. return;
  1126. rq->part = disk_map_sector_rcu(rq->rq_disk, blk_rq_pos(rq));
  1127. part_stat_lock();
  1128. update_io_ticks(rq->part, jiffies, false);
  1129. part_stat_unlock();
  1130. }
  1131. static unsigned long __part_start_io_acct(struct hd_struct *part,
  1132. unsigned int sectors, unsigned int op)
  1133. {
  1134. const int sgrp = op_stat_group(op);
  1135. unsigned long now = READ_ONCE(jiffies);
  1136. part_stat_lock();
  1137. update_io_ticks(part, now, false);
  1138. part_stat_inc(part, ios[sgrp]);
  1139. part_stat_add(part, sectors[sgrp], sectors);
  1140. part_stat_local_inc(part, in_flight[op_is_write(op)]);
  1141. part_stat_unlock();
  1142. return now;
  1143. }
  1144. unsigned long part_start_io_acct(struct gendisk *disk, struct hd_struct **part,
  1145. struct bio *bio)
  1146. {
  1147. *part = disk_map_sector_rcu(disk, bio->bi_iter.bi_sector);
  1148. return __part_start_io_acct(*part, bio_sectors(bio), bio_op(bio));
  1149. }
  1150. EXPORT_SYMBOL_GPL(part_start_io_acct);
  1151. unsigned long disk_start_io_acct(struct gendisk *disk, unsigned int sectors,
  1152. unsigned int op)
  1153. {
  1154. return __part_start_io_acct(&disk->part0, sectors, op);
  1155. }
  1156. EXPORT_SYMBOL(disk_start_io_acct);
  1157. static void __part_end_io_acct(struct hd_struct *part, unsigned int op,
  1158. unsigned long start_time)
  1159. {
  1160. const int sgrp = op_stat_group(op);
  1161. unsigned long now = READ_ONCE(jiffies);
  1162. unsigned long duration = now - start_time;
  1163. part_stat_lock();
  1164. update_io_ticks(part, now, true);
  1165. part_stat_add(part, nsecs[sgrp], jiffies_to_nsecs(duration));
  1166. part_stat_local_dec(part, in_flight[op_is_write(op)]);
  1167. part_stat_unlock();
  1168. }
  1169. void part_end_io_acct(struct hd_struct *part, struct bio *bio,
  1170. unsigned long start_time)
  1171. {
  1172. __part_end_io_acct(part, bio_op(bio), start_time);
  1173. hd_struct_put(part);
  1174. }
  1175. EXPORT_SYMBOL_GPL(part_end_io_acct);
  1176. void disk_end_io_acct(struct gendisk *disk, unsigned int op,
  1177. unsigned long start_time)
  1178. {
  1179. __part_end_io_acct(&disk->part0, op, start_time);
  1180. }
  1181. EXPORT_SYMBOL(disk_end_io_acct);
  1182. /*
  1183. * Steal bios from a request and add them to a bio list.
  1184. * The request must not have been partially completed before.
  1185. */
  1186. void blk_steal_bios(struct bio_list *list, struct request *rq)
  1187. {
  1188. if (rq->bio) {
  1189. if (list->tail)
  1190. list->tail->bi_next = rq->bio;
  1191. else
  1192. list->head = rq->bio;
  1193. list->tail = rq->biotail;
  1194. rq->bio = NULL;
  1195. rq->biotail = NULL;
  1196. }
  1197. rq->__data_len = 0;
  1198. }
  1199. EXPORT_SYMBOL_GPL(blk_steal_bios);
  1200. /**
  1201. * blk_update_request - Special helper function for request stacking drivers
  1202. * @req: the request being processed
  1203. * @error: block status code
  1204. * @nr_bytes: number of bytes to complete @req
  1205. *
  1206. * Description:
  1207. * Ends I/O on a number of bytes attached to @req, but doesn't complete
  1208. * the request structure even if @req doesn't have leftover.
  1209. * If @req has leftover, sets it up for the next range of segments.
  1210. *
  1211. * This special helper function is only for request stacking drivers
  1212. * (e.g. request-based dm) so that they can handle partial completion.
  1213. * Actual device drivers should use blk_mq_end_request instead.
  1214. *
  1215. * Passing the result of blk_rq_bytes() as @nr_bytes guarantees
  1216. * %false return from this function.
  1217. *
  1218. * Note:
  1219. * The RQF_SPECIAL_PAYLOAD flag is ignored on purpose in both
  1220. * blk_rq_bytes() and in blk_update_request().
  1221. *
  1222. * Return:
  1223. * %false - this request doesn't have any more data
  1224. * %true - this request has more data
  1225. **/
  1226. bool blk_update_request(struct request *req, blk_status_t error,
  1227. unsigned int nr_bytes)
  1228. {
  1229. int total_bytes;
  1230. trace_block_rq_complete(req, blk_status_to_errno(error), nr_bytes);
  1231. if (!req->bio)
  1232. return false;
  1233. #ifdef CONFIG_BLK_DEV_INTEGRITY
  1234. if (blk_integrity_rq(req) && req_op(req) == REQ_OP_READ &&
  1235. error == BLK_STS_OK)
  1236. req->q->integrity.profile->complete_fn(req, nr_bytes);
  1237. #endif
  1238. if (unlikely(error && !blk_rq_is_passthrough(req) &&
  1239. !(req->rq_flags & RQF_QUIET)))
  1240. print_req_error(req, error, __func__);
  1241. blk_account_io_completion(req, nr_bytes);
  1242. total_bytes = 0;
  1243. while (req->bio) {
  1244. struct bio *bio = req->bio;
  1245. unsigned bio_bytes = min(bio->bi_iter.bi_size, nr_bytes);
  1246. if (bio_bytes == bio->bi_iter.bi_size)
  1247. req->bio = bio->bi_next;
  1248. /* Completion has already been traced */
  1249. bio_clear_flag(bio, BIO_TRACE_COMPLETION);
  1250. req_bio_endio(req, bio, bio_bytes, error);
  1251. total_bytes += bio_bytes;
  1252. nr_bytes -= bio_bytes;
  1253. if (!nr_bytes)
  1254. break;
  1255. }
  1256. /*
  1257. * completely done
  1258. */
  1259. if (!req->bio) {
  1260. /*
  1261. * Reset counters so that the request stacking driver
  1262. * can find how many bytes remain in the request
  1263. * later.
  1264. */
  1265. req->__data_len = 0;
  1266. return false;
  1267. }
  1268. req->__data_len -= total_bytes;
  1269. /* update sector only for requests with clear definition of sector */
  1270. if (!blk_rq_is_passthrough(req))
  1271. req->__sector += total_bytes >> 9;
  1272. /* mixed attributes always follow the first bio */
  1273. if (req->rq_flags & RQF_MIXED_MERGE) {
  1274. req->cmd_flags &= ~REQ_FAILFAST_MASK;
  1275. req->cmd_flags |= req->bio->bi_opf & REQ_FAILFAST_MASK;
  1276. }
  1277. if (!(req->rq_flags & RQF_SPECIAL_PAYLOAD)) {
  1278. /*
  1279. * If total number of sectors is less than the first segment
  1280. * size, something has gone terribly wrong.
  1281. */
  1282. if (blk_rq_bytes(req) < blk_rq_cur_bytes(req)) {
  1283. blk_dump_rq_flags(req, "request botched");
  1284. req->__data_len = blk_rq_cur_bytes(req);
  1285. }
  1286. /* recalculate the number of segments */
  1287. req->nr_phys_segments = blk_recalc_rq_segments(req);
  1288. }
  1289. return true;
  1290. }
  1291. EXPORT_SYMBOL_GPL(blk_update_request);
  1292. #if ARCH_IMPLEMENTS_FLUSH_DCACHE_PAGE
  1293. /**
  1294. * rq_flush_dcache_pages - Helper function to flush all pages in a request
  1295. * @rq: the request to be flushed
  1296. *
  1297. * Description:
  1298. * Flush all pages in @rq.
  1299. */
  1300. void rq_flush_dcache_pages(struct request *rq)
  1301. {
  1302. struct req_iterator iter;
  1303. struct bio_vec bvec;
  1304. rq_for_each_segment(bvec, rq, iter)
  1305. flush_dcache_page(bvec.bv_page);
  1306. }
  1307. EXPORT_SYMBOL_GPL(rq_flush_dcache_pages);
  1308. #endif
  1309. /**
  1310. * blk_lld_busy - Check if underlying low-level drivers of a device are busy
  1311. * @q : the queue of the device being checked
  1312. *
  1313. * Description:
  1314. * Check if underlying low-level drivers of a device are busy.
  1315. * If the drivers want to export their busy state, they must set own
  1316. * exporting function using blk_queue_lld_busy() first.
  1317. *
  1318. * Basically, this function is used only by request stacking drivers
  1319. * to stop dispatching requests to underlying devices when underlying
  1320. * devices are busy. This behavior helps more I/O merging on the queue
  1321. * of the request stacking driver and prevents I/O throughput regression
  1322. * on burst I/O load.
  1323. *
  1324. * Return:
  1325. * 0 - Not busy (The request stacking driver should dispatch request)
  1326. * 1 - Busy (The request stacking driver should stop dispatching request)
  1327. */
  1328. int blk_lld_busy(struct request_queue *q)
  1329. {
  1330. if (queue_is_mq(q) && q->mq_ops->busy)
  1331. return q->mq_ops->busy(q);
  1332. return 0;
  1333. }
  1334. EXPORT_SYMBOL_GPL(blk_lld_busy);
  1335. /**
  1336. * blk_rq_unprep_clone - Helper function to free all bios in a cloned request
  1337. * @rq: the clone request to be cleaned up
  1338. *
  1339. * Description:
  1340. * Free all bios in @rq for a cloned request.
  1341. */
  1342. void blk_rq_unprep_clone(struct request *rq)
  1343. {
  1344. struct bio *bio;
  1345. while ((bio = rq->bio) != NULL) {
  1346. rq->bio = bio->bi_next;
  1347. bio_put(bio);
  1348. }
  1349. }
  1350. EXPORT_SYMBOL_GPL(blk_rq_unprep_clone);
  1351. /**
  1352. * blk_rq_prep_clone - Helper function to setup clone request
  1353. * @rq: the request to be setup
  1354. * @rq_src: original request to be cloned
  1355. * @bs: bio_set that bios for clone are allocated from
  1356. * @gfp_mask: memory allocation mask for bio
  1357. * @bio_ctr: setup function to be called for each clone bio.
  1358. * Returns %0 for success, non %0 for failure.
  1359. * @data: private data to be passed to @bio_ctr
  1360. *
  1361. * Description:
  1362. * Clones bios in @rq_src to @rq, and copies attributes of @rq_src to @rq.
  1363. * Also, pages which the original bios are pointing to are not copied
  1364. * and the cloned bios just point same pages.
  1365. * So cloned bios must be completed before original bios, which means
  1366. * the caller must complete @rq before @rq_src.
  1367. */
  1368. int blk_rq_prep_clone(struct request *rq, struct request *rq_src,
  1369. struct bio_set *bs, gfp_t gfp_mask,
  1370. int (*bio_ctr)(struct bio *, struct bio *, void *),
  1371. void *data)
  1372. {
  1373. struct bio *bio, *bio_src;
  1374. if (!bs)
  1375. bs = &fs_bio_set;
  1376. __rq_for_each_bio(bio_src, rq_src) {
  1377. bio = bio_clone_fast(bio_src, gfp_mask, bs);
  1378. if (!bio)
  1379. goto free_and_out;
  1380. if (bio_ctr && bio_ctr(bio, bio_src, data))
  1381. goto free_and_out;
  1382. if (rq->bio) {
  1383. rq->biotail->bi_next = bio;
  1384. rq->biotail = bio;
  1385. } else {
  1386. rq->bio = rq->biotail = bio;
  1387. }
  1388. bio = NULL;
  1389. }
  1390. /* Copy attributes of the original request to the clone request. */
  1391. rq->__sector = blk_rq_pos(rq_src);
  1392. rq->__data_len = blk_rq_bytes(rq_src);
  1393. if (rq_src->rq_flags & RQF_SPECIAL_PAYLOAD) {
  1394. rq->rq_flags |= RQF_SPECIAL_PAYLOAD;
  1395. rq->special_vec = rq_src->special_vec;
  1396. }
  1397. rq->nr_phys_segments = rq_src->nr_phys_segments;
  1398. rq->ioprio = rq_src->ioprio;
  1399. if (rq->bio && blk_crypto_rq_bio_prep(rq, rq->bio, gfp_mask) < 0)
  1400. goto free_and_out;
  1401. return 0;
  1402. free_and_out:
  1403. if (bio)
  1404. bio_put(bio);
  1405. blk_rq_unprep_clone(rq);
  1406. return -ENOMEM;
  1407. }
  1408. EXPORT_SYMBOL_GPL(blk_rq_prep_clone);
  1409. int kblockd_schedule_work(struct work_struct *work)
  1410. {
  1411. return queue_work(kblockd_workqueue, work);
  1412. }
  1413. EXPORT_SYMBOL(kblockd_schedule_work);
  1414. int kblockd_mod_delayed_work_on(int cpu, struct delayed_work *dwork,
  1415. unsigned long delay)
  1416. {
  1417. return mod_delayed_work_on(cpu, kblockd_workqueue, dwork, delay);
  1418. }
  1419. EXPORT_SYMBOL(kblockd_mod_delayed_work_on);
  1420. /**
  1421. * blk_start_plug - initialize blk_plug and track it inside the task_struct
  1422. * @plug: The &struct blk_plug that needs to be initialized
  1423. *
  1424. * Description:
  1425. * blk_start_plug() indicates to the block layer an intent by the caller
  1426. * to submit multiple I/O requests in a batch. The block layer may use
  1427. * this hint to defer submitting I/Os from the caller until blk_finish_plug()
  1428. * is called. However, the block layer may choose to submit requests
  1429. * before a call to blk_finish_plug() if the number of queued I/Os
  1430. * exceeds %BLK_MAX_REQUEST_COUNT, or if the size of the I/O is larger than
  1431. * %BLK_PLUG_FLUSH_SIZE. The queued I/Os may also be submitted early if
  1432. * the task schedules (see below).
  1433. *
  1434. * Tracking blk_plug inside the task_struct will help with auto-flushing the
  1435. * pending I/O should the task end up blocking between blk_start_plug() and
  1436. * blk_finish_plug(). This is important from a performance perspective, but
  1437. * also ensures that we don't deadlock. For instance, if the task is blocking
  1438. * for a memory allocation, memory reclaim could end up wanting to free a
  1439. * page belonging to that request that is currently residing in our private
  1440. * plug. By flushing the pending I/O when the process goes to sleep, we avoid
  1441. * this kind of deadlock.
  1442. */
  1443. void blk_start_plug(struct blk_plug *plug)
  1444. {
  1445. struct task_struct *tsk = current;
  1446. /*
  1447. * If this is a nested plug, don't actually assign it.
  1448. */
  1449. if (tsk->plug)
  1450. return;
  1451. INIT_LIST_HEAD(&plug->mq_list);
  1452. INIT_LIST_HEAD(&plug->cb_list);
  1453. plug->rq_count = 0;
  1454. plug->multiple_queues = false;
  1455. plug->nowait = false;
  1456. /*
  1457. * Store ordering should not be needed here, since a potential
  1458. * preempt will imply a full memory barrier
  1459. */
  1460. tsk->plug = plug;
  1461. }
  1462. EXPORT_SYMBOL(blk_start_plug);
  1463. static void flush_plug_callbacks(struct blk_plug *plug, bool from_schedule)
  1464. {
  1465. LIST_HEAD(callbacks);
  1466. while (!list_empty(&plug->cb_list)) {
  1467. list_splice_init(&plug->cb_list, &callbacks);
  1468. while (!list_empty(&callbacks)) {
  1469. struct blk_plug_cb *cb = list_first_entry(&callbacks,
  1470. struct blk_plug_cb,
  1471. list);
  1472. list_del(&cb->list);
  1473. cb->callback(cb, from_schedule);
  1474. }
  1475. }
  1476. }
  1477. struct blk_plug_cb *blk_check_plugged(blk_plug_cb_fn unplug, void *data,
  1478. int size)
  1479. {
  1480. struct blk_plug *plug = current->plug;
  1481. struct blk_plug_cb *cb;
  1482. if (!plug)
  1483. return NULL;
  1484. list_for_each_entry(cb, &plug->cb_list, list)
  1485. if (cb->callback == unplug && cb->data == data)
  1486. return cb;
  1487. /* Not currently on the callback list */
  1488. BUG_ON(size < sizeof(*cb));
  1489. cb = kzalloc(size, GFP_ATOMIC);
  1490. if (cb) {
  1491. cb->data = data;
  1492. cb->callback = unplug;
  1493. list_add(&cb->list, &plug->cb_list);
  1494. }
  1495. return cb;
  1496. }
  1497. EXPORT_SYMBOL(blk_check_plugged);
  1498. void blk_flush_plug_list(struct blk_plug *plug, bool from_schedule)
  1499. {
  1500. flush_plug_callbacks(plug, from_schedule);
  1501. if (!list_empty(&plug->mq_list))
  1502. blk_mq_flush_plug_list(plug, from_schedule);
  1503. }
  1504. /**
  1505. * blk_finish_plug - mark the end of a batch of submitted I/O
  1506. * @plug: The &struct blk_plug passed to blk_start_plug()
  1507. *
  1508. * Description:
  1509. * Indicate that a batch of I/O submissions is complete. This function
  1510. * must be paired with an initial call to blk_start_plug(). The intent
  1511. * is to allow the block layer to optimize I/O submission. See the
  1512. * documentation for blk_start_plug() for more information.
  1513. */
  1514. void blk_finish_plug(struct blk_plug *plug)
  1515. {
  1516. if (plug != current->plug)
  1517. return;
  1518. blk_flush_plug_list(plug, false);
  1519. current->plug = NULL;
  1520. }
  1521. EXPORT_SYMBOL(blk_finish_plug);
  1522. void blk_io_schedule(void)
  1523. {
  1524. /* Prevent hang_check timer from firing at us during very long I/O */
  1525. unsigned long timeout = sysctl_hung_task_timeout_secs * HZ / 2;
  1526. if (timeout)
  1527. io_schedule_timeout(timeout);
  1528. else
  1529. io_schedule();
  1530. }
  1531. EXPORT_SYMBOL_GPL(blk_io_schedule);
  1532. int __init blk_dev_init(void)
  1533. {
  1534. BUILD_BUG_ON(REQ_OP_LAST >= (1 << REQ_OP_BITS));
  1535. BUILD_BUG_ON(REQ_OP_BITS + REQ_FLAG_BITS > 8 *
  1536. sizeof_field(struct request, cmd_flags));
  1537. BUILD_BUG_ON(REQ_OP_BITS + REQ_FLAG_BITS > 8 *
  1538. sizeof_field(struct bio, bi_opf));
  1539. /* used for unplugging and affects IO latency/throughput - HIGHPRI */
  1540. kblockd_workqueue = alloc_workqueue("kblockd",
  1541. WQ_MEM_RECLAIM | WQ_HIGHPRI, 0);
  1542. if (!kblockd_workqueue)
  1543. panic("Failed to create kblockd\n");
  1544. blk_requestq_cachep = kmem_cache_create("request_queue",
  1545. sizeof(struct request_queue), 0, SLAB_PANIC, NULL);
  1546. blk_debugfs_root = debugfs_create_dir("block", NULL);
  1547. return 0;
  1548. }