bio.c 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754
  1. // SPDX-License-Identifier: GPL-2.0
  2. /*
  3. * Copyright (C) 2001 Jens Axboe <[email protected]>
  4. */
  5. #include <linux/mm.h>
  6. #include <linux/swap.h>
  7. #include <linux/bio.h>
  8. #include <linux/blkdev.h>
  9. #include <linux/uio.h>
  10. #include <linux/iocontext.h>
  11. #include <linux/slab.h>
  12. #include <linux/init.h>
  13. #include <linux/kernel.h>
  14. #include <linux/export.h>
  15. #include <linux/mempool.h>
  16. #include <linux/workqueue.h>
  17. #include <linux/cgroup.h>
  18. #include <linux/highmem.h>
  19. #include <linux/sched/sysctl.h>
  20. #include <linux/blk-crypto.h>
  21. #include <linux/xarray.h>
  22. #include <trace/events/block.h>
  23. #include "blk.h"
  24. #include "blk-rq-qos.h"
  25. #include "blk-cgroup.h"
  26. struct bio_alloc_cache {
  27. struct bio *free_list;
  28. unsigned int nr;
  29. };
  30. static struct biovec_slab {
  31. int nr_vecs;
  32. char *name;
  33. struct kmem_cache *slab;
  34. } bvec_slabs[] __read_mostly = {
  35. { .nr_vecs = 16, .name = "biovec-16" },
  36. { .nr_vecs = 64, .name = "biovec-64" },
  37. { .nr_vecs = 128, .name = "biovec-128" },
  38. { .nr_vecs = BIO_MAX_VECS, .name = "biovec-max" },
  39. };
  40. static struct biovec_slab *biovec_slab(unsigned short nr_vecs)
  41. {
  42. switch (nr_vecs) {
  43. /* smaller bios use inline vecs */
  44. case 5 ... 16:
  45. return &bvec_slabs[0];
  46. case 17 ... 64:
  47. return &bvec_slabs[1];
  48. case 65 ... 128:
  49. return &bvec_slabs[2];
  50. case 129 ... BIO_MAX_VECS:
  51. return &bvec_slabs[3];
  52. default:
  53. BUG();
  54. return NULL;
  55. }
  56. }
  57. /*
  58. * fs_bio_set is the bio_set containing bio and iovec memory pools used by
  59. * IO code that does not need private memory pools.
  60. */
  61. struct bio_set fs_bio_set;
  62. EXPORT_SYMBOL(fs_bio_set);
  63. /*
  64. * Our slab pool management
  65. */
  66. struct bio_slab {
  67. struct kmem_cache *slab;
  68. unsigned int slab_ref;
  69. unsigned int slab_size;
  70. char name[8];
  71. };
  72. static DEFINE_MUTEX(bio_slab_lock);
  73. static DEFINE_XARRAY(bio_slabs);
  74. static struct bio_slab *create_bio_slab(unsigned int size)
  75. {
  76. struct bio_slab *bslab = kzalloc(sizeof(*bslab), GFP_KERNEL);
  77. if (!bslab)
  78. return NULL;
  79. snprintf(bslab->name, sizeof(bslab->name), "bio-%d", size);
  80. bslab->slab = kmem_cache_create(bslab->name, size,
  81. ARCH_KMALLOC_MINALIGN,
  82. SLAB_HWCACHE_ALIGN | SLAB_TYPESAFE_BY_RCU, NULL);
  83. if (!bslab->slab)
  84. goto fail_alloc_slab;
  85. bslab->slab_ref = 1;
  86. bslab->slab_size = size;
  87. if (!xa_err(xa_store(&bio_slabs, size, bslab, GFP_KERNEL)))
  88. return bslab;
  89. kmem_cache_destroy(bslab->slab);
  90. fail_alloc_slab:
  91. kfree(bslab);
  92. return NULL;
  93. }
  94. static inline unsigned int bs_bio_slab_size(struct bio_set *bs)
  95. {
  96. return bs->front_pad + sizeof(struct bio) + bs->back_pad;
  97. }
  98. static struct kmem_cache *bio_find_or_create_slab(struct bio_set *bs)
  99. {
  100. unsigned int size = bs_bio_slab_size(bs);
  101. struct bio_slab *bslab;
  102. mutex_lock(&bio_slab_lock);
  103. bslab = xa_load(&bio_slabs, size);
  104. if (bslab)
  105. bslab->slab_ref++;
  106. else
  107. bslab = create_bio_slab(size);
  108. mutex_unlock(&bio_slab_lock);
  109. if (bslab)
  110. return bslab->slab;
  111. return NULL;
  112. }
  113. static void bio_put_slab(struct bio_set *bs)
  114. {
  115. struct bio_slab *bslab = NULL;
  116. unsigned int slab_size = bs_bio_slab_size(bs);
  117. mutex_lock(&bio_slab_lock);
  118. bslab = xa_load(&bio_slabs, slab_size);
  119. if (WARN(!bslab, KERN_ERR "bio: unable to find slab!\n"))
  120. goto out;
  121. WARN_ON_ONCE(bslab->slab != bs->bio_slab);
  122. WARN_ON(!bslab->slab_ref);
  123. if (--bslab->slab_ref)
  124. goto out;
  125. xa_erase(&bio_slabs, slab_size);
  126. kmem_cache_destroy(bslab->slab);
  127. kfree(bslab);
  128. out:
  129. mutex_unlock(&bio_slab_lock);
  130. }
  131. void bvec_free(mempool_t *pool, struct bio_vec *bv, unsigned short nr_vecs)
  132. {
  133. BUG_ON(nr_vecs > BIO_MAX_VECS);
  134. if (nr_vecs == BIO_MAX_VECS)
  135. mempool_free(bv, pool);
  136. else if (nr_vecs > BIO_INLINE_VECS)
  137. kmem_cache_free(biovec_slab(nr_vecs)->slab, bv);
  138. }
  139. /*
  140. * Make the first allocation restricted and don't dump info on allocation
  141. * failures, since we'll fall back to the mempool in case of failure.
  142. */
  143. static inline gfp_t bvec_alloc_gfp(gfp_t gfp)
  144. {
  145. return (gfp & ~(__GFP_DIRECT_RECLAIM | __GFP_IO)) |
  146. __GFP_NOMEMALLOC | __GFP_NORETRY | __GFP_NOWARN;
  147. }
  148. struct bio_vec *bvec_alloc(mempool_t *pool, unsigned short *nr_vecs,
  149. gfp_t gfp_mask)
  150. {
  151. struct biovec_slab *bvs = biovec_slab(*nr_vecs);
  152. if (WARN_ON_ONCE(!bvs))
  153. return NULL;
  154. /*
  155. * Upgrade the nr_vecs request to take full advantage of the allocation.
  156. * We also rely on this in the bvec_free path.
  157. */
  158. *nr_vecs = bvs->nr_vecs;
  159. /*
  160. * Try a slab allocation first for all smaller allocations. If that
  161. * fails and __GFP_DIRECT_RECLAIM is set retry with the mempool.
  162. * The mempool is sized to handle up to BIO_MAX_VECS entries.
  163. */
  164. if (*nr_vecs < BIO_MAX_VECS) {
  165. struct bio_vec *bvl;
  166. bvl = kmem_cache_alloc(bvs->slab, bvec_alloc_gfp(gfp_mask));
  167. if (likely(bvl) || !(gfp_mask & __GFP_DIRECT_RECLAIM))
  168. return bvl;
  169. *nr_vecs = BIO_MAX_VECS;
  170. }
  171. return mempool_alloc(pool, gfp_mask);
  172. }
  173. void bio_uninit(struct bio *bio)
  174. {
  175. #ifdef CONFIG_BLK_CGROUP
  176. if (bio->bi_blkg) {
  177. blkg_put(bio->bi_blkg);
  178. bio->bi_blkg = NULL;
  179. }
  180. #endif
  181. if (bio_integrity(bio))
  182. bio_integrity_free(bio);
  183. bio_crypt_free_ctx(bio);
  184. }
  185. EXPORT_SYMBOL(bio_uninit);
  186. static void bio_free(struct bio *bio)
  187. {
  188. struct bio_set *bs = bio->bi_pool;
  189. void *p = bio;
  190. WARN_ON_ONCE(!bs);
  191. bio_uninit(bio);
  192. bvec_free(&bs->bvec_pool, bio->bi_io_vec, bio->bi_max_vecs);
  193. mempool_free(p - bs->front_pad, &bs->bio_pool);
  194. }
  195. /*
  196. * Users of this function have their own bio allocation. Subsequently,
  197. * they must remember to pair any call to bio_init() with bio_uninit()
  198. * when IO has completed, or when the bio is released.
  199. */
  200. void bio_init(struct bio *bio, struct block_device *bdev, struct bio_vec *table,
  201. unsigned short max_vecs, blk_opf_t opf)
  202. {
  203. bio->bi_next = NULL;
  204. bio->bi_bdev = bdev;
  205. bio->bi_opf = opf;
  206. bio->bi_flags = 0;
  207. bio->bi_ioprio = 0;
  208. bio->bi_status = 0;
  209. bio->bi_iter.bi_sector = 0;
  210. bio->bi_iter.bi_size = 0;
  211. bio->bi_iter.bi_idx = 0;
  212. bio->bi_iter.bi_bvec_done = 0;
  213. bio->bi_end_io = NULL;
  214. bio->bi_private = NULL;
  215. #ifdef CONFIG_BLK_CGROUP
  216. bio->bi_blkg = NULL;
  217. bio->bi_issue.value = 0;
  218. if (bdev)
  219. bio_associate_blkg(bio);
  220. #ifdef CONFIG_BLK_CGROUP_IOCOST
  221. bio->bi_iocost_cost = 0;
  222. #endif
  223. #endif
  224. #ifdef CONFIG_BLK_INLINE_ENCRYPTION
  225. bio->bi_crypt_context = NULL;
  226. #if IS_ENABLED(CONFIG_DM_DEFAULT_KEY)
  227. bio->bi_skip_dm_default_key = false;
  228. #endif
  229. #endif
  230. #ifdef CONFIG_BLK_DEV_INTEGRITY
  231. bio->bi_integrity = NULL;
  232. #endif
  233. bio->bi_vcnt = 0;
  234. atomic_set(&bio->__bi_remaining, 1);
  235. atomic_set(&bio->__bi_cnt, 1);
  236. bio->bi_cookie = BLK_QC_T_NONE;
  237. bio->bi_max_vecs = max_vecs;
  238. bio->bi_io_vec = table;
  239. bio->bi_pool = NULL;
  240. }
  241. EXPORT_SYMBOL(bio_init);
  242. /**
  243. * bio_reset - reinitialize a bio
  244. * @bio: bio to reset
  245. * @bdev: block device to use the bio for
  246. * @opf: operation and flags for bio
  247. *
  248. * Description:
  249. * After calling bio_reset(), @bio will be in the same state as a freshly
  250. * allocated bio returned bio bio_alloc_bioset() - the only fields that are
  251. * preserved are the ones that are initialized by bio_alloc_bioset(). See
  252. * comment in struct bio.
  253. */
  254. void bio_reset(struct bio *bio, struct block_device *bdev, blk_opf_t opf)
  255. {
  256. bio_uninit(bio);
  257. memset(bio, 0, BIO_RESET_BYTES);
  258. atomic_set(&bio->__bi_remaining, 1);
  259. bio->bi_bdev = bdev;
  260. if (bio->bi_bdev)
  261. bio_associate_blkg(bio);
  262. bio->bi_opf = opf;
  263. }
  264. EXPORT_SYMBOL(bio_reset);
  265. static struct bio *__bio_chain_endio(struct bio *bio)
  266. {
  267. struct bio *parent = bio->bi_private;
  268. if (bio->bi_status && !parent->bi_status)
  269. parent->bi_status = bio->bi_status;
  270. bio_put(bio);
  271. return parent;
  272. }
  273. static void bio_chain_endio(struct bio *bio)
  274. {
  275. bio_endio(__bio_chain_endio(bio));
  276. }
  277. /**
  278. * bio_chain - chain bio completions
  279. * @bio: the target bio
  280. * @parent: the parent bio of @bio
  281. *
  282. * The caller won't have a bi_end_io called when @bio completes - instead,
  283. * @parent's bi_end_io won't be called until both @parent and @bio have
  284. * completed; the chained bio will also be freed when it completes.
  285. *
  286. * The caller must not set bi_private or bi_end_io in @bio.
  287. */
  288. void bio_chain(struct bio *bio, struct bio *parent)
  289. {
  290. BUG_ON(bio->bi_private || bio->bi_end_io);
  291. bio->bi_private = parent;
  292. bio->bi_end_io = bio_chain_endio;
  293. bio_inc_remaining(parent);
  294. }
  295. EXPORT_SYMBOL(bio_chain);
  296. struct bio *blk_next_bio(struct bio *bio, struct block_device *bdev,
  297. unsigned int nr_pages, blk_opf_t opf, gfp_t gfp)
  298. {
  299. struct bio *new = bio_alloc(bdev, nr_pages, opf, gfp);
  300. if (bio) {
  301. bio_chain(bio, new);
  302. submit_bio(bio);
  303. }
  304. return new;
  305. }
  306. EXPORT_SYMBOL_GPL(blk_next_bio);
  307. static void bio_alloc_rescue(struct work_struct *work)
  308. {
  309. struct bio_set *bs = container_of(work, struct bio_set, rescue_work);
  310. struct bio *bio;
  311. while (1) {
  312. spin_lock(&bs->rescue_lock);
  313. bio = bio_list_pop(&bs->rescue_list);
  314. spin_unlock(&bs->rescue_lock);
  315. if (!bio)
  316. break;
  317. submit_bio_noacct(bio);
  318. }
  319. }
  320. static void punt_bios_to_rescuer(struct bio_set *bs)
  321. {
  322. struct bio_list punt, nopunt;
  323. struct bio *bio;
  324. if (WARN_ON_ONCE(!bs->rescue_workqueue))
  325. return;
  326. /*
  327. * In order to guarantee forward progress we must punt only bios that
  328. * were allocated from this bio_set; otherwise, if there was a bio on
  329. * there for a stacking driver higher up in the stack, processing it
  330. * could require allocating bios from this bio_set, and doing that from
  331. * our own rescuer would be bad.
  332. *
  333. * Since bio lists are singly linked, pop them all instead of trying to
  334. * remove from the middle of the list:
  335. */
  336. bio_list_init(&punt);
  337. bio_list_init(&nopunt);
  338. while ((bio = bio_list_pop(&current->bio_list[0])))
  339. bio_list_add(bio->bi_pool == bs ? &punt : &nopunt, bio);
  340. current->bio_list[0] = nopunt;
  341. bio_list_init(&nopunt);
  342. while ((bio = bio_list_pop(&current->bio_list[1])))
  343. bio_list_add(bio->bi_pool == bs ? &punt : &nopunt, bio);
  344. current->bio_list[1] = nopunt;
  345. spin_lock(&bs->rescue_lock);
  346. bio_list_merge(&bs->rescue_list, &punt);
  347. spin_unlock(&bs->rescue_lock);
  348. queue_work(bs->rescue_workqueue, &bs->rescue_work);
  349. }
  350. static struct bio *bio_alloc_percpu_cache(struct block_device *bdev,
  351. unsigned short nr_vecs, blk_opf_t opf, gfp_t gfp,
  352. struct bio_set *bs)
  353. {
  354. struct bio_alloc_cache *cache;
  355. struct bio *bio;
  356. cache = per_cpu_ptr(bs->cache, get_cpu());
  357. if (!cache->free_list) {
  358. put_cpu();
  359. return NULL;
  360. }
  361. bio = cache->free_list;
  362. cache->free_list = bio->bi_next;
  363. cache->nr--;
  364. put_cpu();
  365. bio_init(bio, bdev, nr_vecs ? bio->bi_inline_vecs : NULL, nr_vecs, opf);
  366. bio->bi_pool = bs;
  367. return bio;
  368. }
  369. /**
  370. * bio_alloc_bioset - allocate a bio for I/O
  371. * @bdev: block device to allocate the bio for (can be %NULL)
  372. * @nr_vecs: number of bvecs to pre-allocate
  373. * @opf: operation and flags for bio
  374. * @gfp_mask: the GFP_* mask given to the slab allocator
  375. * @bs: the bio_set to allocate from.
  376. *
  377. * Allocate a bio from the mempools in @bs.
  378. *
  379. * If %__GFP_DIRECT_RECLAIM is set then bio_alloc will always be able to
  380. * allocate a bio. This is due to the mempool guarantees. To make this work,
  381. * callers must never allocate more than 1 bio at a time from the general pool.
  382. * Callers that need to allocate more than 1 bio must always submit the
  383. * previously allocated bio for IO before attempting to allocate a new one.
  384. * Failure to do so can cause deadlocks under memory pressure.
  385. *
  386. * Note that when running under submit_bio_noacct() (i.e. any block driver),
  387. * bios are not submitted until after you return - see the code in
  388. * submit_bio_noacct() that converts recursion into iteration, to prevent
  389. * stack overflows.
  390. *
  391. * This would normally mean allocating multiple bios under submit_bio_noacct()
  392. * would be susceptible to deadlocks, but we have
  393. * deadlock avoidance code that resubmits any blocked bios from a rescuer
  394. * thread.
  395. *
  396. * However, we do not guarantee forward progress for allocations from other
  397. * mempools. Doing multiple allocations from the same mempool under
  398. * submit_bio_noacct() should be avoided - instead, use bio_set's front_pad
  399. * for per bio allocations.
  400. *
  401. * If REQ_ALLOC_CACHE is set, the final put of the bio MUST be done from process
  402. * context, not hard/soft IRQ.
  403. *
  404. * Returns: Pointer to new bio on success, NULL on failure.
  405. */
  406. struct bio *bio_alloc_bioset(struct block_device *bdev, unsigned short nr_vecs,
  407. blk_opf_t opf, gfp_t gfp_mask,
  408. struct bio_set *bs)
  409. {
  410. gfp_t saved_gfp = gfp_mask;
  411. struct bio *bio;
  412. void *p;
  413. /* should not use nobvec bioset for nr_vecs > 0 */
  414. if (WARN_ON_ONCE(!mempool_initialized(&bs->bvec_pool) && nr_vecs > 0))
  415. return NULL;
  416. if (opf & REQ_ALLOC_CACHE) {
  417. if (bs->cache && nr_vecs <= BIO_INLINE_VECS) {
  418. bio = bio_alloc_percpu_cache(bdev, nr_vecs, opf,
  419. gfp_mask, bs);
  420. if (bio)
  421. return bio;
  422. /*
  423. * No cached bio available, bio returned below marked with
  424. * REQ_ALLOC_CACHE to particpate in per-cpu alloc cache.
  425. */
  426. } else {
  427. opf &= ~REQ_ALLOC_CACHE;
  428. }
  429. }
  430. /*
  431. * submit_bio_noacct() converts recursion to iteration; this means if
  432. * we're running beneath it, any bios we allocate and submit will not be
  433. * submitted (and thus freed) until after we return.
  434. *
  435. * This exposes us to a potential deadlock if we allocate multiple bios
  436. * from the same bio_set() while running underneath submit_bio_noacct().
  437. * If we were to allocate multiple bios (say a stacking block driver
  438. * that was splitting bios), we would deadlock if we exhausted the
  439. * mempool's reserve.
  440. *
  441. * We solve this, and guarantee forward progress, with a rescuer
  442. * workqueue per bio_set. If we go to allocate and there are bios on
  443. * current->bio_list, we first try the allocation without
  444. * __GFP_DIRECT_RECLAIM; if that fails, we punt those bios we would be
  445. * blocking to the rescuer workqueue before we retry with the original
  446. * gfp_flags.
  447. */
  448. if (current->bio_list &&
  449. (!bio_list_empty(&current->bio_list[0]) ||
  450. !bio_list_empty(&current->bio_list[1])) &&
  451. bs->rescue_workqueue)
  452. gfp_mask &= ~__GFP_DIRECT_RECLAIM;
  453. p = mempool_alloc(&bs->bio_pool, gfp_mask);
  454. if (!p && gfp_mask != saved_gfp) {
  455. punt_bios_to_rescuer(bs);
  456. gfp_mask = saved_gfp;
  457. p = mempool_alloc(&bs->bio_pool, gfp_mask);
  458. }
  459. if (unlikely(!p))
  460. return NULL;
  461. bio = p + bs->front_pad;
  462. if (nr_vecs > BIO_INLINE_VECS) {
  463. struct bio_vec *bvl = NULL;
  464. bvl = bvec_alloc(&bs->bvec_pool, &nr_vecs, gfp_mask);
  465. if (!bvl && gfp_mask != saved_gfp) {
  466. punt_bios_to_rescuer(bs);
  467. gfp_mask = saved_gfp;
  468. bvl = bvec_alloc(&bs->bvec_pool, &nr_vecs, gfp_mask);
  469. }
  470. if (unlikely(!bvl))
  471. goto err_free;
  472. bio_init(bio, bdev, bvl, nr_vecs, opf);
  473. } else if (nr_vecs) {
  474. bio_init(bio, bdev, bio->bi_inline_vecs, BIO_INLINE_VECS, opf);
  475. } else {
  476. bio_init(bio, bdev, NULL, 0, opf);
  477. }
  478. bio->bi_pool = bs;
  479. return bio;
  480. err_free:
  481. mempool_free(p, &bs->bio_pool);
  482. return NULL;
  483. }
  484. EXPORT_SYMBOL(bio_alloc_bioset);
  485. /**
  486. * bio_kmalloc - kmalloc a bio
  487. * @nr_vecs: number of bio_vecs to allocate
  488. * @gfp_mask: the GFP_* mask given to the slab allocator
  489. *
  490. * Use kmalloc to allocate a bio (including bvecs). The bio must be initialized
  491. * using bio_init() before use. To free a bio returned from this function use
  492. * kfree() after calling bio_uninit(). A bio returned from this function can
  493. * be reused by calling bio_uninit() before calling bio_init() again.
  494. *
  495. * Note that unlike bio_alloc() or bio_alloc_bioset() allocations from this
  496. * function are not backed by a mempool can fail. Do not use this function
  497. * for allocations in the file system I/O path.
  498. *
  499. * Returns: Pointer to new bio on success, NULL on failure.
  500. */
  501. struct bio *bio_kmalloc(unsigned short nr_vecs, gfp_t gfp_mask)
  502. {
  503. struct bio *bio;
  504. if (nr_vecs > UIO_MAXIOV)
  505. return NULL;
  506. return kmalloc(struct_size(bio, bi_inline_vecs, nr_vecs), gfp_mask);
  507. }
  508. EXPORT_SYMBOL(bio_kmalloc);
  509. void zero_fill_bio(struct bio *bio)
  510. {
  511. struct bio_vec bv;
  512. struct bvec_iter iter;
  513. bio_for_each_segment(bv, bio, iter)
  514. memzero_bvec(&bv);
  515. }
  516. EXPORT_SYMBOL(zero_fill_bio);
  517. /**
  518. * bio_truncate - truncate the bio to small size of @new_size
  519. * @bio: the bio to be truncated
  520. * @new_size: new size for truncating the bio
  521. *
  522. * Description:
  523. * Truncate the bio to new size of @new_size. If bio_op(bio) is
  524. * REQ_OP_READ, zero the truncated part. This function should only
  525. * be used for handling corner cases, such as bio eod.
  526. */
  527. static void bio_truncate(struct bio *bio, unsigned new_size)
  528. {
  529. struct bio_vec bv;
  530. struct bvec_iter iter;
  531. unsigned int done = 0;
  532. bool truncated = false;
  533. if (new_size >= bio->bi_iter.bi_size)
  534. return;
  535. if (bio_op(bio) != REQ_OP_READ)
  536. goto exit;
  537. bio_for_each_segment(bv, bio, iter) {
  538. if (done + bv.bv_len > new_size) {
  539. unsigned offset;
  540. if (!truncated)
  541. offset = new_size - done;
  542. else
  543. offset = 0;
  544. zero_user(bv.bv_page, bv.bv_offset + offset,
  545. bv.bv_len - offset);
  546. truncated = true;
  547. }
  548. done += bv.bv_len;
  549. }
  550. exit:
  551. /*
  552. * Don't touch bvec table here and make it really immutable, since
  553. * fs bio user has to retrieve all pages via bio_for_each_segment_all
  554. * in its .end_bio() callback.
  555. *
  556. * It is enough to truncate bio by updating .bi_size since we can make
  557. * correct bvec with the updated .bi_size for drivers.
  558. */
  559. bio->bi_iter.bi_size = new_size;
  560. }
  561. /**
  562. * guard_bio_eod - truncate a BIO to fit the block device
  563. * @bio: bio to truncate
  564. *
  565. * This allows us to do IO even on the odd last sectors of a device, even if the
  566. * block size is some multiple of the physical sector size.
  567. *
  568. * We'll just truncate the bio to the size of the device, and clear the end of
  569. * the buffer head manually. Truly out-of-range accesses will turn into actual
  570. * I/O errors, this only handles the "we need to be able to do I/O at the final
  571. * sector" case.
  572. */
  573. void guard_bio_eod(struct bio *bio)
  574. {
  575. sector_t maxsector = bdev_nr_sectors(bio->bi_bdev);
  576. if (!maxsector)
  577. return;
  578. /*
  579. * If the *whole* IO is past the end of the device,
  580. * let it through, and the IO layer will turn it into
  581. * an EIO.
  582. */
  583. if (unlikely(bio->bi_iter.bi_sector >= maxsector))
  584. return;
  585. maxsector -= bio->bi_iter.bi_sector;
  586. if (likely((bio->bi_iter.bi_size >> 9) <= maxsector))
  587. return;
  588. bio_truncate(bio, maxsector << 9);
  589. }
  590. #define ALLOC_CACHE_MAX 512
  591. #define ALLOC_CACHE_SLACK 64
  592. static void bio_alloc_cache_prune(struct bio_alloc_cache *cache,
  593. unsigned int nr)
  594. {
  595. unsigned int i = 0;
  596. struct bio *bio;
  597. while ((bio = cache->free_list) != NULL) {
  598. cache->free_list = bio->bi_next;
  599. cache->nr--;
  600. bio_free(bio);
  601. if (++i == nr)
  602. break;
  603. }
  604. }
  605. static int bio_cpu_dead(unsigned int cpu, struct hlist_node *node)
  606. {
  607. struct bio_set *bs;
  608. bs = hlist_entry_safe(node, struct bio_set, cpuhp_dead);
  609. if (bs->cache) {
  610. struct bio_alloc_cache *cache = per_cpu_ptr(bs->cache, cpu);
  611. bio_alloc_cache_prune(cache, -1U);
  612. }
  613. return 0;
  614. }
  615. static void bio_alloc_cache_destroy(struct bio_set *bs)
  616. {
  617. int cpu;
  618. if (!bs->cache)
  619. return;
  620. cpuhp_state_remove_instance_nocalls(CPUHP_BIO_DEAD, &bs->cpuhp_dead);
  621. for_each_possible_cpu(cpu) {
  622. struct bio_alloc_cache *cache;
  623. cache = per_cpu_ptr(bs->cache, cpu);
  624. bio_alloc_cache_prune(cache, -1U);
  625. }
  626. free_percpu(bs->cache);
  627. bs->cache = NULL;
  628. }
  629. /**
  630. * bio_put - release a reference to a bio
  631. * @bio: bio to release reference to
  632. *
  633. * Description:
  634. * Put a reference to a &struct bio, either one you have gotten with
  635. * bio_alloc, bio_get or bio_clone_*. The last put of a bio will free it.
  636. **/
  637. void bio_put(struct bio *bio)
  638. {
  639. if (unlikely(bio_flagged(bio, BIO_REFFED))) {
  640. BUG_ON(!atomic_read(&bio->__bi_cnt));
  641. if (!atomic_dec_and_test(&bio->__bi_cnt))
  642. return;
  643. }
  644. if ((bio->bi_opf & REQ_ALLOC_CACHE) && !WARN_ON_ONCE(in_interrupt())) {
  645. struct bio_alloc_cache *cache;
  646. bio_uninit(bio);
  647. cache = per_cpu_ptr(bio->bi_pool->cache, get_cpu());
  648. bio->bi_next = cache->free_list;
  649. bio->bi_bdev = NULL;
  650. cache->free_list = bio;
  651. if (++cache->nr > ALLOC_CACHE_MAX + ALLOC_CACHE_SLACK)
  652. bio_alloc_cache_prune(cache, ALLOC_CACHE_SLACK);
  653. put_cpu();
  654. } else {
  655. bio_free(bio);
  656. }
  657. }
  658. EXPORT_SYMBOL(bio_put);
  659. static int __bio_clone(struct bio *bio, struct bio *bio_src, gfp_t gfp)
  660. {
  661. bio_set_flag(bio, BIO_CLONED);
  662. bio->bi_ioprio = bio_src->bi_ioprio;
  663. bio->bi_iter = bio_src->bi_iter;
  664. if (bio->bi_bdev) {
  665. if (bio->bi_bdev == bio_src->bi_bdev &&
  666. bio_flagged(bio_src, BIO_REMAPPED))
  667. bio_set_flag(bio, BIO_REMAPPED);
  668. bio_clone_blkg_association(bio, bio_src);
  669. }
  670. if (bio_crypt_clone(bio, bio_src, gfp) < 0)
  671. return -ENOMEM;
  672. if (bio_integrity(bio_src) &&
  673. bio_integrity_clone(bio, bio_src, gfp) < 0)
  674. return -ENOMEM;
  675. return 0;
  676. }
  677. /**
  678. * bio_alloc_clone - clone a bio that shares the original bio's biovec
  679. * @bdev: block_device to clone onto
  680. * @bio_src: bio to clone from
  681. * @gfp: allocation priority
  682. * @bs: bio_set to allocate from
  683. *
  684. * Allocate a new bio that is a clone of @bio_src. The caller owns the returned
  685. * bio, but not the actual data it points to.
  686. *
  687. * The caller must ensure that the return bio is not freed before @bio_src.
  688. */
  689. struct bio *bio_alloc_clone(struct block_device *bdev, struct bio *bio_src,
  690. gfp_t gfp, struct bio_set *bs)
  691. {
  692. struct bio *bio;
  693. bio = bio_alloc_bioset(bdev, 0, bio_src->bi_opf, gfp, bs);
  694. if (!bio)
  695. return NULL;
  696. if (__bio_clone(bio, bio_src, gfp) < 0) {
  697. bio_put(bio);
  698. return NULL;
  699. }
  700. bio->bi_io_vec = bio_src->bi_io_vec;
  701. return bio;
  702. }
  703. EXPORT_SYMBOL(bio_alloc_clone);
  704. /**
  705. * bio_init_clone - clone a bio that shares the original bio's biovec
  706. * @bdev: block_device to clone onto
  707. * @bio: bio to clone into
  708. * @bio_src: bio to clone from
  709. * @gfp: allocation priority
  710. *
  711. * Initialize a new bio in caller provided memory that is a clone of @bio_src.
  712. * The caller owns the returned bio, but not the actual data it points to.
  713. *
  714. * The caller must ensure that @bio_src is not freed before @bio.
  715. */
  716. int bio_init_clone(struct block_device *bdev, struct bio *bio,
  717. struct bio *bio_src, gfp_t gfp)
  718. {
  719. int ret;
  720. bio_init(bio, bdev, bio_src->bi_io_vec, 0, bio_src->bi_opf);
  721. ret = __bio_clone(bio, bio_src, gfp);
  722. if (ret)
  723. bio_uninit(bio);
  724. return ret;
  725. }
  726. EXPORT_SYMBOL(bio_init_clone);
  727. /**
  728. * bio_full - check if the bio is full
  729. * @bio: bio to check
  730. * @len: length of one segment to be added
  731. *
  732. * Return true if @bio is full and one segment with @len bytes can't be
  733. * added to the bio, otherwise return false
  734. */
  735. static inline bool bio_full(struct bio *bio, unsigned len)
  736. {
  737. if (bio->bi_vcnt >= bio->bi_max_vecs)
  738. return true;
  739. if (bio->bi_iter.bi_size > UINT_MAX - len)
  740. return true;
  741. return false;
  742. }
  743. static inline bool page_is_mergeable(const struct bio_vec *bv,
  744. struct page *page, unsigned int len, unsigned int off,
  745. bool *same_page)
  746. {
  747. size_t bv_end = bv->bv_offset + bv->bv_len;
  748. phys_addr_t vec_end_addr = page_to_phys(bv->bv_page) + bv_end - 1;
  749. phys_addr_t page_addr = page_to_phys(page);
  750. if (vec_end_addr + 1 != page_addr + off)
  751. return false;
  752. if (xen_domain() && !xen_biovec_phys_mergeable(bv, page))
  753. return false;
  754. *same_page = ((vec_end_addr & PAGE_MASK) == page_addr);
  755. if (*same_page)
  756. return true;
  757. else if (IS_ENABLED(CONFIG_KMSAN))
  758. return false;
  759. return (bv->bv_page + bv_end / PAGE_SIZE) == (page + off / PAGE_SIZE);
  760. }
  761. /**
  762. * __bio_try_merge_page - try appending data to an existing bvec.
  763. * @bio: destination bio
  764. * @page: start page to add
  765. * @len: length of the data to add
  766. * @off: offset of the data relative to @page
  767. * @same_page: return if the segment has been merged inside the same page
  768. *
  769. * Try to add the data at @page + @off to the last bvec of @bio. This is a
  770. * useful optimisation for file systems with a block size smaller than the
  771. * page size.
  772. *
  773. * Warn if (@len, @off) crosses pages in case that @same_page is true.
  774. *
  775. * Return %true on success or %false on failure.
  776. */
  777. static bool __bio_try_merge_page(struct bio *bio, struct page *page,
  778. unsigned int len, unsigned int off, bool *same_page)
  779. {
  780. if (WARN_ON_ONCE(bio_flagged(bio, BIO_CLONED)))
  781. return false;
  782. if (bio->bi_vcnt > 0) {
  783. struct bio_vec *bv = &bio->bi_io_vec[bio->bi_vcnt - 1];
  784. if (page_is_mergeable(bv, page, len, off, same_page)) {
  785. if (bio->bi_iter.bi_size > UINT_MAX - len) {
  786. *same_page = false;
  787. return false;
  788. }
  789. bv->bv_len += len;
  790. bio->bi_iter.bi_size += len;
  791. return true;
  792. }
  793. }
  794. return false;
  795. }
  796. /*
  797. * Try to merge a page into a segment, while obeying the hardware segment
  798. * size limit. This is not for normal read/write bios, but for passthrough
  799. * or Zone Append operations that we can't split.
  800. */
  801. static bool bio_try_merge_hw_seg(struct request_queue *q, struct bio *bio,
  802. struct page *page, unsigned len,
  803. unsigned offset, bool *same_page)
  804. {
  805. struct bio_vec *bv = &bio->bi_io_vec[bio->bi_vcnt - 1];
  806. unsigned long mask = queue_segment_boundary(q);
  807. phys_addr_t addr1 = page_to_phys(bv->bv_page) + bv->bv_offset;
  808. phys_addr_t addr2 = page_to_phys(page) + offset + len - 1;
  809. if ((addr1 | mask) != (addr2 | mask))
  810. return false;
  811. if (bv->bv_len + len > queue_max_segment_size(q))
  812. return false;
  813. return __bio_try_merge_page(bio, page, len, offset, same_page);
  814. }
  815. /**
  816. * bio_add_hw_page - attempt to add a page to a bio with hw constraints
  817. * @q: the target queue
  818. * @bio: destination bio
  819. * @page: page to add
  820. * @len: vec entry length
  821. * @offset: vec entry offset
  822. * @max_sectors: maximum number of sectors that can be added
  823. * @same_page: return if the segment has been merged inside the same page
  824. *
  825. * Add a page to a bio while respecting the hardware max_sectors, max_segment
  826. * and gap limitations.
  827. */
  828. int bio_add_hw_page(struct request_queue *q, struct bio *bio,
  829. struct page *page, unsigned int len, unsigned int offset,
  830. unsigned int max_sectors, bool *same_page)
  831. {
  832. struct bio_vec *bvec;
  833. if (WARN_ON_ONCE(bio_flagged(bio, BIO_CLONED)))
  834. return 0;
  835. if (((bio->bi_iter.bi_size + len) >> 9) > max_sectors)
  836. return 0;
  837. if (bio->bi_vcnt > 0) {
  838. if (bio_try_merge_hw_seg(q, bio, page, len, offset, same_page))
  839. return len;
  840. /*
  841. * If the queue doesn't support SG gaps and adding this segment
  842. * would create a gap, disallow it.
  843. */
  844. bvec = &bio->bi_io_vec[bio->bi_vcnt - 1];
  845. if (bvec_gap_to_prev(&q->limits, bvec, offset))
  846. return 0;
  847. }
  848. if (bio_full(bio, len))
  849. return 0;
  850. if (bio->bi_vcnt >= queue_max_segments(q))
  851. return 0;
  852. bvec_set_page(&bio->bi_io_vec[bio->bi_vcnt], page, len, offset);
  853. bio->bi_vcnt++;
  854. bio->bi_iter.bi_size += len;
  855. return len;
  856. }
  857. /**
  858. * bio_add_pc_page - attempt to add page to passthrough bio
  859. * @q: the target queue
  860. * @bio: destination bio
  861. * @page: page to add
  862. * @len: vec entry length
  863. * @offset: vec entry offset
  864. *
  865. * Attempt to add a page to the bio_vec maplist. This can fail for a
  866. * number of reasons, such as the bio being full or target block device
  867. * limitations. The target block device must allow bio's up to PAGE_SIZE,
  868. * so it is always possible to add a single page to an empty bio.
  869. *
  870. * This should only be used by passthrough bios.
  871. */
  872. int bio_add_pc_page(struct request_queue *q, struct bio *bio,
  873. struct page *page, unsigned int len, unsigned int offset)
  874. {
  875. bool same_page = false;
  876. return bio_add_hw_page(q, bio, page, len, offset,
  877. queue_max_hw_sectors(q), &same_page);
  878. }
  879. EXPORT_SYMBOL(bio_add_pc_page);
  880. /**
  881. * bio_add_zone_append_page - attempt to add page to zone-append bio
  882. * @bio: destination bio
  883. * @page: page to add
  884. * @len: vec entry length
  885. * @offset: vec entry offset
  886. *
  887. * Attempt to add a page to the bio_vec maplist of a bio that will be submitted
  888. * for a zone-append request. This can fail for a number of reasons, such as the
  889. * bio being full or the target block device is not a zoned block device or
  890. * other limitations of the target block device. The target block device must
  891. * allow bio's up to PAGE_SIZE, so it is always possible to add a single page
  892. * to an empty bio.
  893. *
  894. * Returns: number of bytes added to the bio, or 0 in case of a failure.
  895. */
  896. int bio_add_zone_append_page(struct bio *bio, struct page *page,
  897. unsigned int len, unsigned int offset)
  898. {
  899. struct request_queue *q = bdev_get_queue(bio->bi_bdev);
  900. bool same_page = false;
  901. if (WARN_ON_ONCE(bio_op(bio) != REQ_OP_ZONE_APPEND))
  902. return 0;
  903. if (WARN_ON_ONCE(!bdev_is_zoned(bio->bi_bdev)))
  904. return 0;
  905. return bio_add_hw_page(q, bio, page, len, offset,
  906. queue_max_zone_append_sectors(q), &same_page);
  907. }
  908. EXPORT_SYMBOL_GPL(bio_add_zone_append_page);
  909. /**
  910. * __bio_add_page - add page(s) to a bio in a new segment
  911. * @bio: destination bio
  912. * @page: start page to add
  913. * @len: length of the data to add, may cross pages
  914. * @off: offset of the data relative to @page, may cross pages
  915. *
  916. * Add the data at @page + @off to @bio as a new bvec. The caller must ensure
  917. * that @bio has space for another bvec.
  918. */
  919. void __bio_add_page(struct bio *bio, struct page *page,
  920. unsigned int len, unsigned int off)
  921. {
  922. WARN_ON_ONCE(bio_flagged(bio, BIO_CLONED));
  923. WARN_ON_ONCE(bio_full(bio, len));
  924. bvec_set_page(&bio->bi_io_vec[bio->bi_vcnt], page, len, off);
  925. bio->bi_iter.bi_size += len;
  926. bio->bi_vcnt++;
  927. }
  928. EXPORT_SYMBOL_GPL(__bio_add_page);
  929. /**
  930. * bio_add_page - attempt to add page(s) to bio
  931. * @bio: destination bio
  932. * @page: start page to add
  933. * @len: vec entry length, may cross pages
  934. * @offset: vec entry offset relative to @page, may cross pages
  935. *
  936. * Attempt to add page(s) to the bio_vec maplist. This will only fail
  937. * if either bio->bi_vcnt == bio->bi_max_vecs or it's a cloned bio.
  938. */
  939. int bio_add_page(struct bio *bio, struct page *page,
  940. unsigned int len, unsigned int offset)
  941. {
  942. bool same_page = false;
  943. if (!__bio_try_merge_page(bio, page, len, offset, &same_page)) {
  944. if (bio_full(bio, len))
  945. return 0;
  946. __bio_add_page(bio, page, len, offset);
  947. }
  948. return len;
  949. }
  950. EXPORT_SYMBOL(bio_add_page);
  951. /**
  952. * bio_add_folio - Attempt to add part of a folio to a bio.
  953. * @bio: BIO to add to.
  954. * @folio: Folio to add.
  955. * @len: How many bytes from the folio to add.
  956. * @off: First byte in this folio to add.
  957. *
  958. * Filesystems that use folios can call this function instead of calling
  959. * bio_add_page() for each page in the folio. If @off is bigger than
  960. * PAGE_SIZE, this function can create a bio_vec that starts in a page
  961. * after the bv_page. BIOs do not support folios that are 4GiB or larger.
  962. *
  963. * Return: Whether the addition was successful.
  964. */
  965. bool bio_add_folio(struct bio *bio, struct folio *folio, size_t len,
  966. size_t off)
  967. {
  968. if (len > UINT_MAX || off > UINT_MAX)
  969. return false;
  970. return bio_add_page(bio, &folio->page, len, off) > 0;
  971. }
  972. void __bio_release_pages(struct bio *bio, bool mark_dirty)
  973. {
  974. struct bvec_iter_all iter_all;
  975. struct bio_vec *bvec;
  976. bio_for_each_segment_all(bvec, bio, iter_all) {
  977. if (mark_dirty && !PageCompound(bvec->bv_page))
  978. set_page_dirty_lock(bvec->bv_page);
  979. put_page(bvec->bv_page);
  980. }
  981. }
  982. EXPORT_SYMBOL_GPL(__bio_release_pages);
  983. void bio_iov_bvec_set(struct bio *bio, struct iov_iter *iter)
  984. {
  985. size_t size = iov_iter_count(iter);
  986. WARN_ON_ONCE(bio->bi_max_vecs);
  987. if (bio_op(bio) == REQ_OP_ZONE_APPEND) {
  988. struct request_queue *q = bdev_get_queue(bio->bi_bdev);
  989. size_t max_sectors = queue_max_zone_append_sectors(q);
  990. size = min(size, max_sectors << SECTOR_SHIFT);
  991. }
  992. bio->bi_vcnt = iter->nr_segs;
  993. bio->bi_io_vec = (struct bio_vec *)iter->bvec;
  994. bio->bi_iter.bi_bvec_done = iter->iov_offset;
  995. bio->bi_iter.bi_size = size;
  996. bio_set_flag(bio, BIO_NO_PAGE_REF);
  997. bio_set_flag(bio, BIO_CLONED);
  998. }
  999. static int bio_iov_add_page(struct bio *bio, struct page *page,
  1000. unsigned int len, unsigned int offset)
  1001. {
  1002. bool same_page = false;
  1003. if (!__bio_try_merge_page(bio, page, len, offset, &same_page)) {
  1004. __bio_add_page(bio, page, len, offset);
  1005. return 0;
  1006. }
  1007. if (same_page)
  1008. put_page(page);
  1009. return 0;
  1010. }
  1011. static int bio_iov_add_zone_append_page(struct bio *bio, struct page *page,
  1012. unsigned int len, unsigned int offset)
  1013. {
  1014. struct request_queue *q = bdev_get_queue(bio->bi_bdev);
  1015. bool same_page = false;
  1016. if (bio_add_hw_page(q, bio, page, len, offset,
  1017. queue_max_zone_append_sectors(q), &same_page) != len)
  1018. return -EINVAL;
  1019. if (same_page)
  1020. put_page(page);
  1021. return 0;
  1022. }
  1023. #define PAGE_PTRS_PER_BVEC (sizeof(struct bio_vec) / sizeof(struct page *))
  1024. /**
  1025. * __bio_iov_iter_get_pages - pin user or kernel pages and add them to a bio
  1026. * @bio: bio to add pages to
  1027. * @iter: iov iterator describing the region to be mapped
  1028. *
  1029. * Pins pages from *iter and appends them to @bio's bvec array. The
  1030. * pages will have to be released using put_page() when done.
  1031. * For multi-segment *iter, this function only adds pages from the
  1032. * next non-empty segment of the iov iterator.
  1033. */
  1034. static int __bio_iov_iter_get_pages(struct bio *bio, struct iov_iter *iter)
  1035. {
  1036. unsigned short nr_pages = bio->bi_max_vecs - bio->bi_vcnt;
  1037. unsigned short entries_left = bio->bi_max_vecs - bio->bi_vcnt;
  1038. struct bio_vec *bv = bio->bi_io_vec + bio->bi_vcnt;
  1039. struct page **pages = (struct page **)bv;
  1040. ssize_t size, left;
  1041. unsigned len, i = 0;
  1042. size_t offset, trim;
  1043. int ret = 0;
  1044. /*
  1045. * Move page array up in the allocated memory for the bio vecs as far as
  1046. * possible so that we can start filling biovecs from the beginning
  1047. * without overwriting the temporary page array.
  1048. */
  1049. BUILD_BUG_ON(PAGE_PTRS_PER_BVEC < 2);
  1050. pages += entries_left * (PAGE_PTRS_PER_BVEC - 1);
  1051. /*
  1052. * Each segment in the iov is required to be a block size multiple.
  1053. * However, we may not be able to get the entire segment if it spans
  1054. * more pages than bi_max_vecs allows, so we have to ALIGN_DOWN the
  1055. * result to ensure the bio's total size is correct. The remainder of
  1056. * the iov data will be picked up in the next bio iteration.
  1057. */
  1058. size = iov_iter_get_pages2(iter, pages, UINT_MAX - bio->bi_iter.bi_size,
  1059. nr_pages, &offset);
  1060. if (unlikely(size <= 0))
  1061. return size ? size : -EFAULT;
  1062. nr_pages = DIV_ROUND_UP(offset + size, PAGE_SIZE);
  1063. trim = size & (bdev_logical_block_size(bio->bi_bdev) - 1);
  1064. iov_iter_revert(iter, trim);
  1065. size -= trim;
  1066. if (unlikely(!size)) {
  1067. ret = -EFAULT;
  1068. goto out;
  1069. }
  1070. for (left = size, i = 0; left > 0; left -= len, i++) {
  1071. struct page *page = pages[i];
  1072. len = min_t(size_t, PAGE_SIZE - offset, left);
  1073. if (bio_op(bio) == REQ_OP_ZONE_APPEND) {
  1074. ret = bio_iov_add_zone_append_page(bio, page, len,
  1075. offset);
  1076. if (ret)
  1077. break;
  1078. } else
  1079. bio_iov_add_page(bio, page, len, offset);
  1080. offset = 0;
  1081. }
  1082. iov_iter_revert(iter, left);
  1083. out:
  1084. while (i < nr_pages)
  1085. put_page(pages[i++]);
  1086. return ret;
  1087. }
  1088. /**
  1089. * bio_iov_iter_get_pages - add user or kernel pages to a bio
  1090. * @bio: bio to add pages to
  1091. * @iter: iov iterator describing the region to be added
  1092. *
  1093. * This takes either an iterator pointing to user memory, or one pointing to
  1094. * kernel pages (BVEC iterator). If we're adding user pages, we pin them and
  1095. * map them into the kernel. On IO completion, the caller should put those
  1096. * pages. For bvec based iterators bio_iov_iter_get_pages() uses the provided
  1097. * bvecs rather than copying them. Hence anyone issuing kiocb based IO needs
  1098. * to ensure the bvecs and pages stay referenced until the submitted I/O is
  1099. * completed by a call to ->ki_complete() or returns with an error other than
  1100. * -EIOCBQUEUED. The caller needs to check if the bio is flagged BIO_NO_PAGE_REF
  1101. * on IO completion. If it isn't, then pages should be released.
  1102. *
  1103. * The function tries, but does not guarantee, to pin as many pages as
  1104. * fit into the bio, or are requested in @iter, whatever is smaller. If
  1105. * MM encounters an error pinning the requested pages, it stops. Error
  1106. * is returned only if 0 pages could be pinned.
  1107. */
  1108. int bio_iov_iter_get_pages(struct bio *bio, struct iov_iter *iter)
  1109. {
  1110. int ret = 0;
  1111. if (iov_iter_is_bvec(iter)) {
  1112. bio_iov_bvec_set(bio, iter);
  1113. iov_iter_advance(iter, bio->bi_iter.bi_size);
  1114. return 0;
  1115. }
  1116. do {
  1117. ret = __bio_iov_iter_get_pages(bio, iter);
  1118. } while (!ret && iov_iter_count(iter) && !bio_full(bio, 0));
  1119. return bio->bi_vcnt ? 0 : ret;
  1120. }
  1121. EXPORT_SYMBOL_GPL(bio_iov_iter_get_pages);
  1122. static void submit_bio_wait_endio(struct bio *bio)
  1123. {
  1124. complete(bio->bi_private);
  1125. }
  1126. /**
  1127. * submit_bio_wait - submit a bio, and wait until it completes
  1128. * @bio: The &struct bio which describes the I/O
  1129. *
  1130. * Simple wrapper around submit_bio(). Returns 0 on success, or the error from
  1131. * bio_endio() on failure.
  1132. *
  1133. * WARNING: Unlike to how submit_bio() is usually used, this function does not
  1134. * result in bio reference to be consumed. The caller must drop the reference
  1135. * on his own.
  1136. */
  1137. int submit_bio_wait(struct bio *bio)
  1138. {
  1139. DECLARE_COMPLETION_ONSTACK_MAP(done,
  1140. bio->bi_bdev->bd_disk->lockdep_map);
  1141. unsigned long hang_check;
  1142. bio->bi_private = &done;
  1143. bio->bi_end_io = submit_bio_wait_endio;
  1144. bio->bi_opf |= REQ_SYNC;
  1145. submit_bio(bio);
  1146. /* Prevent hang_check timer from firing at us during very long I/O */
  1147. hang_check = sysctl_hung_task_timeout_secs;
  1148. if (hang_check)
  1149. while (!wait_for_completion_io_timeout(&done,
  1150. hang_check * (HZ/2)))
  1151. ;
  1152. else
  1153. wait_for_completion_io(&done);
  1154. return blk_status_to_errno(bio->bi_status);
  1155. }
  1156. EXPORT_SYMBOL(submit_bio_wait);
  1157. void __bio_advance(struct bio *bio, unsigned bytes)
  1158. {
  1159. if (bio_integrity(bio))
  1160. bio_integrity_advance(bio, bytes);
  1161. bio_crypt_advance(bio, bytes);
  1162. bio_advance_iter(bio, &bio->bi_iter, bytes);
  1163. }
  1164. EXPORT_SYMBOL(__bio_advance);
  1165. void bio_copy_data_iter(struct bio *dst, struct bvec_iter *dst_iter,
  1166. struct bio *src, struct bvec_iter *src_iter)
  1167. {
  1168. while (src_iter->bi_size && dst_iter->bi_size) {
  1169. struct bio_vec src_bv = bio_iter_iovec(src, *src_iter);
  1170. struct bio_vec dst_bv = bio_iter_iovec(dst, *dst_iter);
  1171. unsigned int bytes = min(src_bv.bv_len, dst_bv.bv_len);
  1172. void *src_buf = bvec_kmap_local(&src_bv);
  1173. void *dst_buf = bvec_kmap_local(&dst_bv);
  1174. memcpy(dst_buf, src_buf, bytes);
  1175. kunmap_local(dst_buf);
  1176. kunmap_local(src_buf);
  1177. bio_advance_iter_single(src, src_iter, bytes);
  1178. bio_advance_iter_single(dst, dst_iter, bytes);
  1179. }
  1180. }
  1181. EXPORT_SYMBOL(bio_copy_data_iter);
  1182. /**
  1183. * bio_copy_data - copy contents of data buffers from one bio to another
  1184. * @src: source bio
  1185. * @dst: destination bio
  1186. *
  1187. * Stops when it reaches the end of either @src or @dst - that is, copies
  1188. * min(src->bi_size, dst->bi_size) bytes (or the equivalent for lists of bios).
  1189. */
  1190. void bio_copy_data(struct bio *dst, struct bio *src)
  1191. {
  1192. struct bvec_iter src_iter = src->bi_iter;
  1193. struct bvec_iter dst_iter = dst->bi_iter;
  1194. bio_copy_data_iter(dst, &dst_iter, src, &src_iter);
  1195. }
  1196. EXPORT_SYMBOL(bio_copy_data);
  1197. void bio_free_pages(struct bio *bio)
  1198. {
  1199. struct bio_vec *bvec;
  1200. struct bvec_iter_all iter_all;
  1201. bio_for_each_segment_all(bvec, bio, iter_all)
  1202. __free_page(bvec->bv_page);
  1203. }
  1204. EXPORT_SYMBOL(bio_free_pages);
  1205. /*
  1206. * bio_set_pages_dirty() and bio_check_pages_dirty() are support functions
  1207. * for performing direct-IO in BIOs.
  1208. *
  1209. * The problem is that we cannot run set_page_dirty() from interrupt context
  1210. * because the required locks are not interrupt-safe. So what we can do is to
  1211. * mark the pages dirty _before_ performing IO. And in interrupt context,
  1212. * check that the pages are still dirty. If so, fine. If not, redirty them
  1213. * in process context.
  1214. *
  1215. * We special-case compound pages here: normally this means reads into hugetlb
  1216. * pages. The logic in here doesn't really work right for compound pages
  1217. * because the VM does not uniformly chase down the head page in all cases.
  1218. * But dirtiness of compound pages is pretty meaningless anyway: the VM doesn't
  1219. * handle them at all. So we skip compound pages here at an early stage.
  1220. *
  1221. * Note that this code is very hard to test under normal circumstances because
  1222. * direct-io pins the pages with get_user_pages(). This makes
  1223. * is_page_cache_freeable return false, and the VM will not clean the pages.
  1224. * But other code (eg, flusher threads) could clean the pages if they are mapped
  1225. * pagecache.
  1226. *
  1227. * Simply disabling the call to bio_set_pages_dirty() is a good way to test the
  1228. * deferred bio dirtying paths.
  1229. */
  1230. /*
  1231. * bio_set_pages_dirty() will mark all the bio's pages as dirty.
  1232. */
  1233. void bio_set_pages_dirty(struct bio *bio)
  1234. {
  1235. struct bio_vec *bvec;
  1236. struct bvec_iter_all iter_all;
  1237. bio_for_each_segment_all(bvec, bio, iter_all) {
  1238. if (!PageCompound(bvec->bv_page))
  1239. set_page_dirty_lock(bvec->bv_page);
  1240. }
  1241. }
  1242. /*
  1243. * bio_check_pages_dirty() will check that all the BIO's pages are still dirty.
  1244. * If they are, then fine. If, however, some pages are clean then they must
  1245. * have been written out during the direct-IO read. So we take another ref on
  1246. * the BIO and re-dirty the pages in process context.
  1247. *
  1248. * It is expected that bio_check_pages_dirty() will wholly own the BIO from
  1249. * here on. It will run one put_page() against each page and will run one
  1250. * bio_put() against the BIO.
  1251. */
  1252. static void bio_dirty_fn(struct work_struct *work);
  1253. static DECLARE_WORK(bio_dirty_work, bio_dirty_fn);
  1254. static DEFINE_SPINLOCK(bio_dirty_lock);
  1255. static struct bio *bio_dirty_list;
  1256. /*
  1257. * This runs in process context
  1258. */
  1259. static void bio_dirty_fn(struct work_struct *work)
  1260. {
  1261. struct bio *bio, *next;
  1262. spin_lock_irq(&bio_dirty_lock);
  1263. next = bio_dirty_list;
  1264. bio_dirty_list = NULL;
  1265. spin_unlock_irq(&bio_dirty_lock);
  1266. while ((bio = next) != NULL) {
  1267. next = bio->bi_private;
  1268. bio_release_pages(bio, true);
  1269. bio_put(bio);
  1270. }
  1271. }
  1272. void bio_check_pages_dirty(struct bio *bio)
  1273. {
  1274. struct bio_vec *bvec;
  1275. unsigned long flags;
  1276. struct bvec_iter_all iter_all;
  1277. bio_for_each_segment_all(bvec, bio, iter_all) {
  1278. if (!PageDirty(bvec->bv_page) && !PageCompound(bvec->bv_page))
  1279. goto defer;
  1280. }
  1281. bio_release_pages(bio, false);
  1282. bio_put(bio);
  1283. return;
  1284. defer:
  1285. spin_lock_irqsave(&bio_dirty_lock, flags);
  1286. bio->bi_private = bio_dirty_list;
  1287. bio_dirty_list = bio;
  1288. spin_unlock_irqrestore(&bio_dirty_lock, flags);
  1289. schedule_work(&bio_dirty_work);
  1290. }
  1291. static inline bool bio_remaining_done(struct bio *bio)
  1292. {
  1293. /*
  1294. * If we're not chaining, then ->__bi_remaining is always 1 and
  1295. * we always end io on the first invocation.
  1296. */
  1297. if (!bio_flagged(bio, BIO_CHAIN))
  1298. return true;
  1299. BUG_ON(atomic_read(&bio->__bi_remaining) <= 0);
  1300. if (atomic_dec_and_test(&bio->__bi_remaining)) {
  1301. bio_clear_flag(bio, BIO_CHAIN);
  1302. return true;
  1303. }
  1304. return false;
  1305. }
  1306. /**
  1307. * bio_endio - end I/O on a bio
  1308. * @bio: bio
  1309. *
  1310. * Description:
  1311. * bio_endio() will end I/O on the whole bio. bio_endio() is the preferred
  1312. * way to end I/O on a bio. No one should call bi_end_io() directly on a
  1313. * bio unless they own it and thus know that it has an end_io function.
  1314. *
  1315. * bio_endio() can be called several times on a bio that has been chained
  1316. * using bio_chain(). The ->bi_end_io() function will only be called the
  1317. * last time.
  1318. **/
  1319. void bio_endio(struct bio *bio)
  1320. {
  1321. again:
  1322. if (!bio_remaining_done(bio))
  1323. return;
  1324. if (!bio_integrity_endio(bio))
  1325. return;
  1326. rq_qos_done_bio(bio);
  1327. if (bio->bi_bdev && bio_flagged(bio, BIO_TRACE_COMPLETION)) {
  1328. trace_block_bio_complete(bdev_get_queue(bio->bi_bdev), bio);
  1329. bio_clear_flag(bio, BIO_TRACE_COMPLETION);
  1330. }
  1331. /*
  1332. * Need to have a real endio function for chained bios, otherwise
  1333. * various corner cases will break (like stacking block devices that
  1334. * save/restore bi_end_io) - however, we want to avoid unbounded
  1335. * recursion and blowing the stack. Tail call optimization would
  1336. * handle this, but compiling with frame pointers also disables
  1337. * gcc's sibling call optimization.
  1338. */
  1339. if (bio->bi_end_io == bio_chain_endio) {
  1340. bio = __bio_chain_endio(bio);
  1341. goto again;
  1342. }
  1343. blk_throtl_bio_endio(bio);
  1344. /* release cgroup info */
  1345. bio_uninit(bio);
  1346. if (bio->bi_end_io)
  1347. bio->bi_end_io(bio);
  1348. }
  1349. EXPORT_SYMBOL(bio_endio);
  1350. /**
  1351. * bio_split - split a bio
  1352. * @bio: bio to split
  1353. * @sectors: number of sectors to split from the front of @bio
  1354. * @gfp: gfp mask
  1355. * @bs: bio set to allocate from
  1356. *
  1357. * Allocates and returns a new bio which represents @sectors from the start of
  1358. * @bio, and updates @bio to represent the remaining sectors.
  1359. *
  1360. * Unless this is a discard request the newly allocated bio will point
  1361. * to @bio's bi_io_vec. It is the caller's responsibility to ensure that
  1362. * neither @bio nor @bs are freed before the split bio.
  1363. */
  1364. struct bio *bio_split(struct bio *bio, int sectors,
  1365. gfp_t gfp, struct bio_set *bs)
  1366. {
  1367. struct bio *split;
  1368. BUG_ON(sectors <= 0);
  1369. BUG_ON(sectors >= bio_sectors(bio));
  1370. /* Zone append commands cannot be split */
  1371. if (WARN_ON_ONCE(bio_op(bio) == REQ_OP_ZONE_APPEND))
  1372. return NULL;
  1373. split = bio_alloc_clone(bio->bi_bdev, bio, gfp, bs);
  1374. if (!split)
  1375. return NULL;
  1376. split->bi_iter.bi_size = sectors << 9;
  1377. if (bio_integrity(split))
  1378. bio_integrity_trim(split);
  1379. bio_advance(bio, split->bi_iter.bi_size);
  1380. if (bio_flagged(bio, BIO_TRACE_COMPLETION))
  1381. bio_set_flag(split, BIO_TRACE_COMPLETION);
  1382. return split;
  1383. }
  1384. EXPORT_SYMBOL(bio_split);
  1385. /**
  1386. * bio_trim - trim a bio
  1387. * @bio: bio to trim
  1388. * @offset: number of sectors to trim from the front of @bio
  1389. * @size: size we want to trim @bio to, in sectors
  1390. *
  1391. * This function is typically used for bios that are cloned and submitted
  1392. * to the underlying device in parts.
  1393. */
  1394. void bio_trim(struct bio *bio, sector_t offset, sector_t size)
  1395. {
  1396. if (WARN_ON_ONCE(offset > BIO_MAX_SECTORS || size > BIO_MAX_SECTORS ||
  1397. offset + size > bio_sectors(bio)))
  1398. return;
  1399. size <<= 9;
  1400. if (offset == 0 && size == bio->bi_iter.bi_size)
  1401. return;
  1402. bio_advance(bio, offset << 9);
  1403. bio->bi_iter.bi_size = size;
  1404. if (bio_integrity(bio))
  1405. bio_integrity_trim(bio);
  1406. }
  1407. EXPORT_SYMBOL_GPL(bio_trim);
  1408. /*
  1409. * create memory pools for biovec's in a bio_set.
  1410. * use the global biovec slabs created for general use.
  1411. */
  1412. int biovec_init_pool(mempool_t *pool, int pool_entries)
  1413. {
  1414. struct biovec_slab *bp = bvec_slabs + ARRAY_SIZE(bvec_slabs) - 1;
  1415. return mempool_init_slab_pool(pool, pool_entries, bp->slab);
  1416. }
  1417. /*
  1418. * bioset_exit - exit a bioset initialized with bioset_init()
  1419. *
  1420. * May be called on a zeroed but uninitialized bioset (i.e. allocated with
  1421. * kzalloc()).
  1422. */
  1423. void bioset_exit(struct bio_set *bs)
  1424. {
  1425. bio_alloc_cache_destroy(bs);
  1426. if (bs->rescue_workqueue)
  1427. destroy_workqueue(bs->rescue_workqueue);
  1428. bs->rescue_workqueue = NULL;
  1429. mempool_exit(&bs->bio_pool);
  1430. mempool_exit(&bs->bvec_pool);
  1431. bioset_integrity_free(bs);
  1432. if (bs->bio_slab)
  1433. bio_put_slab(bs);
  1434. bs->bio_slab = NULL;
  1435. }
  1436. EXPORT_SYMBOL(bioset_exit);
  1437. /**
  1438. * bioset_init - Initialize a bio_set
  1439. * @bs: pool to initialize
  1440. * @pool_size: Number of bio and bio_vecs to cache in the mempool
  1441. * @front_pad: Number of bytes to allocate in front of the returned bio
  1442. * @flags: Flags to modify behavior, currently %BIOSET_NEED_BVECS
  1443. * and %BIOSET_NEED_RESCUER
  1444. *
  1445. * Description:
  1446. * Set up a bio_set to be used with @bio_alloc_bioset. Allows the caller
  1447. * to ask for a number of bytes to be allocated in front of the bio.
  1448. * Front pad allocation is useful for embedding the bio inside
  1449. * another structure, to avoid allocating extra data to go with the bio.
  1450. * Note that the bio must be embedded at the END of that structure always,
  1451. * or things will break badly.
  1452. * If %BIOSET_NEED_BVECS is set in @flags, a separate pool will be allocated
  1453. * for allocating iovecs. This pool is not needed e.g. for bio_init_clone().
  1454. * If %BIOSET_NEED_RESCUER is set, a workqueue is created which can be used
  1455. * to dispatch queued requests when the mempool runs out of space.
  1456. *
  1457. */
  1458. int bioset_init(struct bio_set *bs,
  1459. unsigned int pool_size,
  1460. unsigned int front_pad,
  1461. int flags)
  1462. {
  1463. bs->front_pad = front_pad;
  1464. if (flags & BIOSET_NEED_BVECS)
  1465. bs->back_pad = BIO_INLINE_VECS * sizeof(struct bio_vec);
  1466. else
  1467. bs->back_pad = 0;
  1468. spin_lock_init(&bs->rescue_lock);
  1469. bio_list_init(&bs->rescue_list);
  1470. INIT_WORK(&bs->rescue_work, bio_alloc_rescue);
  1471. bs->bio_slab = bio_find_or_create_slab(bs);
  1472. if (!bs->bio_slab)
  1473. return -ENOMEM;
  1474. if (mempool_init_slab_pool(&bs->bio_pool, pool_size, bs->bio_slab))
  1475. goto bad;
  1476. if ((flags & BIOSET_NEED_BVECS) &&
  1477. biovec_init_pool(&bs->bvec_pool, pool_size))
  1478. goto bad;
  1479. if (flags & BIOSET_NEED_RESCUER) {
  1480. bs->rescue_workqueue = alloc_workqueue("bioset",
  1481. WQ_MEM_RECLAIM, 0);
  1482. if (!bs->rescue_workqueue)
  1483. goto bad;
  1484. }
  1485. if (flags & BIOSET_PERCPU_CACHE) {
  1486. bs->cache = alloc_percpu(struct bio_alloc_cache);
  1487. if (!bs->cache)
  1488. goto bad;
  1489. cpuhp_state_add_instance_nocalls(CPUHP_BIO_DEAD, &bs->cpuhp_dead);
  1490. }
  1491. return 0;
  1492. bad:
  1493. bioset_exit(bs);
  1494. return -ENOMEM;
  1495. }
  1496. EXPORT_SYMBOL(bioset_init);
  1497. static int __init init_bio(void)
  1498. {
  1499. int i;
  1500. bio_integrity_init();
  1501. for (i = 0; i < ARRAY_SIZE(bvec_slabs); i++) {
  1502. struct biovec_slab *bvs = bvec_slabs + i;
  1503. bvs->slab = kmem_cache_create(bvs->name,
  1504. bvs->nr_vecs * sizeof(struct bio_vec), 0,
  1505. SLAB_HWCACHE_ALIGN | SLAB_PANIC, NULL);
  1506. }
  1507. cpuhp_setup_state_multi(CPUHP_BIO_DEAD, "block/bio:dead", NULL,
  1508. bio_cpu_dead);
  1509. if (bioset_init(&fs_bio_set, BIO_POOL_SIZE, 0,
  1510. BIOSET_NEED_BVECS | BIOSET_PERCPU_CACHE))
  1511. panic("bio: can't allocate bios\n");
  1512. if (bioset_integrity_create(&fs_bio_set, BIO_POOL_SIZE))
  1513. panic("bio: can't create integrity pool\n");
  1514. return 0;
  1515. }
  1516. subsys_initcall(init_bio);