direct-io.c 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346
  1. // SPDX-License-Identifier: GPL-2.0-only
  2. /*
  3. * fs/direct-io.c
  4. *
  5. * Copyright (C) 2002, Linus Torvalds.
  6. *
  7. * O_DIRECT
  8. *
  9. * 04Jul2002 Andrew Morton
  10. * Initial version
  11. * 11Sep2002 [email protected]
  12. * added readv/writev support.
  13. * 29Oct2002 Andrew Morton
  14. * rewrote bio_add_page() support.
  15. * 30Oct2002 [email protected]
  16. * added support for non-aligned IO.
  17. * 06Nov2002 [email protected]
  18. * added asynchronous IO support.
  19. * 21Jul2003 [email protected]
  20. * added IO completion notifier.
  21. */
  22. #include <linux/kernel.h>
  23. #include <linux/module.h>
  24. #include <linux/types.h>
  25. #include <linux/fs.h>
  26. #include <linux/mm.h>
  27. #include <linux/slab.h>
  28. #include <linux/highmem.h>
  29. #include <linux/pagemap.h>
  30. #include <linux/task_io_accounting_ops.h>
  31. #include <linux/bio.h>
  32. #include <linux/wait.h>
  33. #include <linux/err.h>
  34. #include <linux/blkdev.h>
  35. #include <linux/buffer_head.h>
  36. #include <linux/rwsem.h>
  37. #include <linux/uio.h>
  38. #include <linux/atomic.h>
  39. #include <linux/prefetch.h>
  40. #include "internal.h"
  41. /*
  42. * How many user pages to map in one call to get_user_pages(). This determines
  43. * the size of a structure in the slab cache
  44. */
  45. #define DIO_PAGES 64
  46. /*
  47. * Flags for dio_complete()
  48. */
  49. #define DIO_COMPLETE_ASYNC 0x01 /* This is async IO */
  50. #define DIO_COMPLETE_INVALIDATE 0x02 /* Can invalidate pages */
  51. /*
  52. * This code generally works in units of "dio_blocks". A dio_block is
  53. * somewhere between the hard sector size and the filesystem block size. it
  54. * is determined on a per-invocation basis. When talking to the filesystem
  55. * we need to convert dio_blocks to fs_blocks by scaling the dio_block quantity
  56. * down by dio->blkfactor. Similarly, fs-blocksize quantities are converted
  57. * to bio_block quantities by shifting left by blkfactor.
  58. *
  59. * If blkfactor is zero then the user's request was aligned to the filesystem's
  60. * blocksize.
  61. */
  62. /* dio_state only used in the submission path */
  63. struct dio_submit {
  64. struct bio *bio; /* bio under assembly */
  65. unsigned blkbits; /* doesn't change */
  66. unsigned blkfactor; /* When we're using an alignment which
  67. is finer than the filesystem's soft
  68. blocksize, this specifies how much
  69. finer. blkfactor=2 means 1/4-block
  70. alignment. Does not change */
  71. unsigned start_zero_done; /* flag: sub-blocksize zeroing has
  72. been performed at the start of a
  73. write */
  74. int pages_in_io; /* approximate total IO pages */
  75. sector_t block_in_file; /* Current offset into the underlying
  76. file in dio_block units. */
  77. unsigned blocks_available; /* At block_in_file. changes */
  78. int reap_counter; /* rate limit reaping */
  79. sector_t final_block_in_request;/* doesn't change */
  80. int boundary; /* prev block is at a boundary */
  81. get_block_t *get_block; /* block mapping function */
  82. dio_submit_t *submit_io; /* IO submition function */
  83. loff_t logical_offset_in_bio; /* current first logical block in bio */
  84. sector_t final_block_in_bio; /* current final block in bio + 1 */
  85. sector_t next_block_for_io; /* next block to be put under IO,
  86. in dio_blocks units */
  87. /*
  88. * Deferred addition of a page to the dio. These variables are
  89. * private to dio_send_cur_page(), submit_page_section() and
  90. * dio_bio_add_page().
  91. */
  92. struct page *cur_page; /* The page */
  93. unsigned cur_page_offset; /* Offset into it, in bytes */
  94. unsigned cur_page_len; /* Nr of bytes at cur_page_offset */
  95. sector_t cur_page_block; /* Where it starts */
  96. loff_t cur_page_fs_offset; /* Offset in file */
  97. struct iov_iter *iter;
  98. /*
  99. * Page queue. These variables belong to dio_refill_pages() and
  100. * dio_get_page().
  101. */
  102. unsigned head; /* next page to process */
  103. unsigned tail; /* last valid page + 1 */
  104. size_t from, to;
  105. };
  106. /* dio_state communicated between submission path and end_io */
  107. struct dio {
  108. int flags; /* doesn't change */
  109. blk_opf_t opf; /* request operation type and flags */
  110. struct gendisk *bio_disk;
  111. struct inode *inode;
  112. loff_t i_size; /* i_size when submitted */
  113. dio_iodone_t *end_io; /* IO completion function */
  114. void *private; /* copy from map_bh.b_private */
  115. /* BIO completion state */
  116. spinlock_t bio_lock; /* protects BIO fields below */
  117. int page_errors; /* errno from get_user_pages() */
  118. int is_async; /* is IO async ? */
  119. bool defer_completion; /* defer AIO completion to workqueue? */
  120. bool should_dirty; /* if pages should be dirtied */
  121. int io_error; /* IO error in completion path */
  122. unsigned long refcount; /* direct_io_worker() and bios */
  123. struct bio *bio_list; /* singly linked via bi_private */
  124. struct task_struct *waiter; /* waiting task (NULL if none) */
  125. /* AIO related stuff */
  126. struct kiocb *iocb; /* kiocb */
  127. ssize_t result; /* IO result */
  128. /*
  129. * pages[] (and any fields placed after it) are not zeroed out at
  130. * allocation time. Don't add new fields after pages[] unless you
  131. * wish that they not be zeroed.
  132. */
  133. union {
  134. struct page *pages[DIO_PAGES]; /* page buffer */
  135. struct work_struct complete_work;/* deferred AIO completion */
  136. };
  137. } ____cacheline_aligned_in_smp;
  138. static struct kmem_cache *dio_cache __read_mostly;
  139. /*
  140. * How many pages are in the queue?
  141. */
  142. static inline unsigned dio_pages_present(struct dio_submit *sdio)
  143. {
  144. return sdio->tail - sdio->head;
  145. }
  146. /*
  147. * Go grab and pin some userspace pages. Typically we'll get 64 at a time.
  148. */
  149. static inline int dio_refill_pages(struct dio *dio, struct dio_submit *sdio)
  150. {
  151. const enum req_op dio_op = dio->opf & REQ_OP_MASK;
  152. ssize_t ret;
  153. ret = iov_iter_get_pages2(sdio->iter, dio->pages, LONG_MAX, DIO_PAGES,
  154. &sdio->from);
  155. if (ret < 0 && sdio->blocks_available && dio_op == REQ_OP_WRITE) {
  156. struct page *page = ZERO_PAGE(0);
  157. /*
  158. * A memory fault, but the filesystem has some outstanding
  159. * mapped blocks. We need to use those blocks up to avoid
  160. * leaking stale data in the file.
  161. */
  162. if (dio->page_errors == 0)
  163. dio->page_errors = ret;
  164. get_page(page);
  165. dio->pages[0] = page;
  166. sdio->head = 0;
  167. sdio->tail = 1;
  168. sdio->from = 0;
  169. sdio->to = PAGE_SIZE;
  170. return 0;
  171. }
  172. if (ret >= 0) {
  173. ret += sdio->from;
  174. sdio->head = 0;
  175. sdio->tail = (ret + PAGE_SIZE - 1) / PAGE_SIZE;
  176. sdio->to = ((ret - 1) & (PAGE_SIZE - 1)) + 1;
  177. return 0;
  178. }
  179. return ret;
  180. }
  181. /*
  182. * Get another userspace page. Returns an ERR_PTR on error. Pages are
  183. * buffered inside the dio so that we can call get_user_pages() against a
  184. * decent number of pages, less frequently. To provide nicer use of the
  185. * L1 cache.
  186. */
  187. static inline struct page *dio_get_page(struct dio *dio,
  188. struct dio_submit *sdio)
  189. {
  190. if (dio_pages_present(sdio) == 0) {
  191. int ret;
  192. ret = dio_refill_pages(dio, sdio);
  193. if (ret)
  194. return ERR_PTR(ret);
  195. BUG_ON(dio_pages_present(sdio) == 0);
  196. }
  197. return dio->pages[sdio->head];
  198. }
  199. /*
  200. * dio_complete() - called when all DIO BIO I/O has been completed
  201. *
  202. * This drops i_dio_count, lets interested parties know that a DIO operation
  203. * has completed, and calculates the resulting return code for the operation.
  204. *
  205. * It lets the filesystem know if it registered an interest earlier via
  206. * get_block. Pass the private field of the map buffer_head so that
  207. * filesystems can use it to hold additional state between get_block calls and
  208. * dio_complete.
  209. */
  210. static ssize_t dio_complete(struct dio *dio, ssize_t ret, unsigned int flags)
  211. {
  212. const enum req_op dio_op = dio->opf & REQ_OP_MASK;
  213. loff_t offset = dio->iocb->ki_pos;
  214. ssize_t transferred = 0;
  215. int err;
  216. /*
  217. * AIO submission can race with bio completion to get here while
  218. * expecting to have the last io completed by bio completion.
  219. * In that case -EIOCBQUEUED is in fact not an error we want
  220. * to preserve through this call.
  221. */
  222. if (ret == -EIOCBQUEUED)
  223. ret = 0;
  224. if (dio->result) {
  225. transferred = dio->result;
  226. /* Check for short read case */
  227. if (dio_op == REQ_OP_READ &&
  228. ((offset + transferred) > dio->i_size))
  229. transferred = dio->i_size - offset;
  230. /* ignore EFAULT if some IO has been done */
  231. if (unlikely(ret == -EFAULT) && transferred)
  232. ret = 0;
  233. }
  234. if (ret == 0)
  235. ret = dio->page_errors;
  236. if (ret == 0)
  237. ret = dio->io_error;
  238. if (ret == 0)
  239. ret = transferred;
  240. if (dio->end_io) {
  241. // XXX: ki_pos??
  242. err = dio->end_io(dio->iocb, offset, ret, dio->private);
  243. if (err)
  244. ret = err;
  245. }
  246. /*
  247. * Try again to invalidate clean pages which might have been cached by
  248. * non-direct readahead, or faulted in by get_user_pages() if the source
  249. * of the write was an mmap'ed region of the file we're writing. Either
  250. * one is a pretty crazy thing to do, so we don't support it 100%. If
  251. * this invalidation fails, tough, the write still worked...
  252. *
  253. * And this page cache invalidation has to be after dio->end_io(), as
  254. * some filesystems convert unwritten extents to real allocations in
  255. * end_io() when necessary, otherwise a racing buffer read would cache
  256. * zeros from unwritten extents.
  257. */
  258. if (flags & DIO_COMPLETE_INVALIDATE &&
  259. ret > 0 && dio_op == REQ_OP_WRITE &&
  260. dio->inode->i_mapping->nrpages) {
  261. err = invalidate_inode_pages2_range(dio->inode->i_mapping,
  262. offset >> PAGE_SHIFT,
  263. (offset + ret - 1) >> PAGE_SHIFT);
  264. if (err)
  265. dio_warn_stale_pagecache(dio->iocb->ki_filp);
  266. }
  267. inode_dio_end(dio->inode);
  268. if (flags & DIO_COMPLETE_ASYNC) {
  269. /*
  270. * generic_write_sync expects ki_pos to have been updated
  271. * already, but the submission path only does this for
  272. * synchronous I/O.
  273. */
  274. dio->iocb->ki_pos += transferred;
  275. if (ret > 0 && dio_op == REQ_OP_WRITE)
  276. ret = generic_write_sync(dio->iocb, ret);
  277. dio->iocb->ki_complete(dio->iocb, ret);
  278. }
  279. kmem_cache_free(dio_cache, dio);
  280. return ret;
  281. }
  282. static void dio_aio_complete_work(struct work_struct *work)
  283. {
  284. struct dio *dio = container_of(work, struct dio, complete_work);
  285. dio_complete(dio, 0, DIO_COMPLETE_ASYNC | DIO_COMPLETE_INVALIDATE);
  286. }
  287. static blk_status_t dio_bio_complete(struct dio *dio, struct bio *bio);
  288. /*
  289. * Asynchronous IO callback.
  290. */
  291. static void dio_bio_end_aio(struct bio *bio)
  292. {
  293. struct dio *dio = bio->bi_private;
  294. const enum req_op dio_op = dio->opf & REQ_OP_MASK;
  295. unsigned long remaining;
  296. unsigned long flags;
  297. bool defer_completion = false;
  298. /* cleanup the bio */
  299. dio_bio_complete(dio, bio);
  300. spin_lock_irqsave(&dio->bio_lock, flags);
  301. remaining = --dio->refcount;
  302. if (remaining == 1 && dio->waiter)
  303. wake_up_process(dio->waiter);
  304. spin_unlock_irqrestore(&dio->bio_lock, flags);
  305. if (remaining == 0) {
  306. /*
  307. * Defer completion when defer_completion is set or
  308. * when the inode has pages mapped and this is AIO write.
  309. * We need to invalidate those pages because there is a
  310. * chance they contain stale data in the case buffered IO
  311. * went in between AIO submission and completion into the
  312. * same region.
  313. */
  314. if (dio->result)
  315. defer_completion = dio->defer_completion ||
  316. (dio_op == REQ_OP_WRITE &&
  317. dio->inode->i_mapping->nrpages);
  318. if (defer_completion) {
  319. INIT_WORK(&dio->complete_work, dio_aio_complete_work);
  320. queue_work(dio->inode->i_sb->s_dio_done_wq,
  321. &dio->complete_work);
  322. } else {
  323. dio_complete(dio, 0, DIO_COMPLETE_ASYNC);
  324. }
  325. }
  326. }
  327. /*
  328. * The BIO completion handler simply queues the BIO up for the process-context
  329. * handler.
  330. *
  331. * During I/O bi_private points at the dio. After I/O, bi_private is used to
  332. * implement a singly-linked list of completed BIOs, at dio->bio_list.
  333. */
  334. static void dio_bio_end_io(struct bio *bio)
  335. {
  336. struct dio *dio = bio->bi_private;
  337. unsigned long flags;
  338. spin_lock_irqsave(&dio->bio_lock, flags);
  339. bio->bi_private = dio->bio_list;
  340. dio->bio_list = bio;
  341. if (--dio->refcount == 1 && dio->waiter)
  342. wake_up_process(dio->waiter);
  343. spin_unlock_irqrestore(&dio->bio_lock, flags);
  344. }
  345. static inline void
  346. dio_bio_alloc(struct dio *dio, struct dio_submit *sdio,
  347. struct block_device *bdev,
  348. sector_t first_sector, int nr_vecs)
  349. {
  350. struct bio *bio;
  351. /*
  352. * bio_alloc() is guaranteed to return a bio when allowed to sleep and
  353. * we request a valid number of vectors.
  354. */
  355. bio = bio_alloc(bdev, nr_vecs, dio->opf, GFP_KERNEL);
  356. bio->bi_iter.bi_sector = first_sector;
  357. if (dio->is_async)
  358. bio->bi_end_io = dio_bio_end_aio;
  359. else
  360. bio->bi_end_io = dio_bio_end_io;
  361. sdio->bio = bio;
  362. sdio->logical_offset_in_bio = sdio->cur_page_fs_offset;
  363. }
  364. /*
  365. * In the AIO read case we speculatively dirty the pages before starting IO.
  366. * During IO completion, any of these pages which happen to have been written
  367. * back will be redirtied by bio_check_pages_dirty().
  368. *
  369. * bios hold a dio reference between submit_bio and ->end_io.
  370. */
  371. static inline void dio_bio_submit(struct dio *dio, struct dio_submit *sdio)
  372. {
  373. const enum req_op dio_op = dio->opf & REQ_OP_MASK;
  374. struct bio *bio = sdio->bio;
  375. unsigned long flags;
  376. bio->bi_private = dio;
  377. spin_lock_irqsave(&dio->bio_lock, flags);
  378. dio->refcount++;
  379. spin_unlock_irqrestore(&dio->bio_lock, flags);
  380. if (dio->is_async && dio_op == REQ_OP_READ && dio->should_dirty)
  381. bio_set_pages_dirty(bio);
  382. dio->bio_disk = bio->bi_bdev->bd_disk;
  383. if (sdio->submit_io)
  384. sdio->submit_io(bio, dio->inode, sdio->logical_offset_in_bio);
  385. else
  386. submit_bio(bio);
  387. sdio->bio = NULL;
  388. sdio->boundary = 0;
  389. sdio->logical_offset_in_bio = 0;
  390. }
  391. /*
  392. * Release any resources in case of a failure
  393. */
  394. static inline void dio_cleanup(struct dio *dio, struct dio_submit *sdio)
  395. {
  396. while (sdio->head < sdio->tail)
  397. put_page(dio->pages[sdio->head++]);
  398. }
  399. /*
  400. * Wait for the next BIO to complete. Remove it and return it. NULL is
  401. * returned once all BIOs have been completed. This must only be called once
  402. * all bios have been issued so that dio->refcount can only decrease. This
  403. * requires that the caller hold a reference on the dio.
  404. */
  405. static struct bio *dio_await_one(struct dio *dio)
  406. {
  407. unsigned long flags;
  408. struct bio *bio = NULL;
  409. spin_lock_irqsave(&dio->bio_lock, flags);
  410. /*
  411. * Wait as long as the list is empty and there are bios in flight. bio
  412. * completion drops the count, maybe adds to the list, and wakes while
  413. * holding the bio_lock so we don't need set_current_state()'s barrier
  414. * and can call it after testing our condition.
  415. */
  416. while (dio->refcount > 1 && dio->bio_list == NULL) {
  417. __set_current_state(TASK_UNINTERRUPTIBLE);
  418. dio->waiter = current;
  419. spin_unlock_irqrestore(&dio->bio_lock, flags);
  420. blk_io_schedule();
  421. /* wake up sets us TASK_RUNNING */
  422. spin_lock_irqsave(&dio->bio_lock, flags);
  423. dio->waiter = NULL;
  424. }
  425. if (dio->bio_list) {
  426. bio = dio->bio_list;
  427. dio->bio_list = bio->bi_private;
  428. }
  429. spin_unlock_irqrestore(&dio->bio_lock, flags);
  430. return bio;
  431. }
  432. /*
  433. * Process one completed BIO. No locks are held.
  434. */
  435. static blk_status_t dio_bio_complete(struct dio *dio, struct bio *bio)
  436. {
  437. blk_status_t err = bio->bi_status;
  438. const enum req_op dio_op = dio->opf & REQ_OP_MASK;
  439. bool should_dirty = dio_op == REQ_OP_READ && dio->should_dirty;
  440. if (err) {
  441. if (err == BLK_STS_AGAIN && (bio->bi_opf & REQ_NOWAIT))
  442. dio->io_error = -EAGAIN;
  443. else
  444. dio->io_error = -EIO;
  445. }
  446. if (dio->is_async && should_dirty) {
  447. bio_check_pages_dirty(bio); /* transfers ownership */
  448. } else {
  449. bio_release_pages(bio, should_dirty);
  450. bio_put(bio);
  451. }
  452. return err;
  453. }
  454. /*
  455. * Wait on and process all in-flight BIOs. This must only be called once
  456. * all bios have been issued so that the refcount can only decrease.
  457. * This just waits for all bios to make it through dio_bio_complete. IO
  458. * errors are propagated through dio->io_error and should be propagated via
  459. * dio_complete().
  460. */
  461. static void dio_await_completion(struct dio *dio)
  462. {
  463. struct bio *bio;
  464. do {
  465. bio = dio_await_one(dio);
  466. if (bio)
  467. dio_bio_complete(dio, bio);
  468. } while (bio);
  469. }
  470. /*
  471. * A really large O_DIRECT read or write can generate a lot of BIOs. So
  472. * to keep the memory consumption sane we periodically reap any completed BIOs
  473. * during the BIO generation phase.
  474. *
  475. * This also helps to limit the peak amount of pinned userspace memory.
  476. */
  477. static inline int dio_bio_reap(struct dio *dio, struct dio_submit *sdio)
  478. {
  479. int ret = 0;
  480. if (sdio->reap_counter++ >= 64) {
  481. while (dio->bio_list) {
  482. unsigned long flags;
  483. struct bio *bio;
  484. int ret2;
  485. spin_lock_irqsave(&dio->bio_lock, flags);
  486. bio = dio->bio_list;
  487. dio->bio_list = bio->bi_private;
  488. spin_unlock_irqrestore(&dio->bio_lock, flags);
  489. ret2 = blk_status_to_errno(dio_bio_complete(dio, bio));
  490. if (ret == 0)
  491. ret = ret2;
  492. }
  493. sdio->reap_counter = 0;
  494. }
  495. return ret;
  496. }
  497. /*
  498. * Create workqueue for deferred direct IO completions. We allocate the
  499. * workqueue when it's first needed. This avoids creating workqueue for
  500. * filesystems that don't need it and also allows us to create the workqueue
  501. * late enough so the we can include s_id in the name of the workqueue.
  502. */
  503. int sb_init_dio_done_wq(struct super_block *sb)
  504. {
  505. struct workqueue_struct *old;
  506. struct workqueue_struct *wq = alloc_workqueue("dio/%s",
  507. WQ_MEM_RECLAIM, 0,
  508. sb->s_id);
  509. if (!wq)
  510. return -ENOMEM;
  511. /*
  512. * This has to be atomic as more DIOs can race to create the workqueue
  513. */
  514. old = cmpxchg(&sb->s_dio_done_wq, NULL, wq);
  515. /* Someone created workqueue before us? Free ours... */
  516. if (old)
  517. destroy_workqueue(wq);
  518. return 0;
  519. }
  520. static int dio_set_defer_completion(struct dio *dio)
  521. {
  522. struct super_block *sb = dio->inode->i_sb;
  523. if (dio->defer_completion)
  524. return 0;
  525. dio->defer_completion = true;
  526. if (!sb->s_dio_done_wq)
  527. return sb_init_dio_done_wq(sb);
  528. return 0;
  529. }
  530. /*
  531. * Call into the fs to map some more disk blocks. We record the current number
  532. * of available blocks at sdio->blocks_available. These are in units of the
  533. * fs blocksize, i_blocksize(inode).
  534. *
  535. * The fs is allowed to map lots of blocks at once. If it wants to do that,
  536. * it uses the passed inode-relative block number as the file offset, as usual.
  537. *
  538. * get_block() is passed the number of i_blkbits-sized blocks which direct_io
  539. * has remaining to do. The fs should not map more than this number of blocks.
  540. *
  541. * If the fs has mapped a lot of blocks, it should populate bh->b_size to
  542. * indicate how much contiguous disk space has been made available at
  543. * bh->b_blocknr.
  544. *
  545. * If *any* of the mapped blocks are new, then the fs must set buffer_new().
  546. * This isn't very efficient...
  547. *
  548. * In the case of filesystem holes: the fs may return an arbitrarily-large
  549. * hole by returning an appropriate value in b_size and by clearing
  550. * buffer_mapped(). However the direct-io code will only process holes one
  551. * block at a time - it will repeatedly call get_block() as it walks the hole.
  552. */
  553. static int get_more_blocks(struct dio *dio, struct dio_submit *sdio,
  554. struct buffer_head *map_bh)
  555. {
  556. const enum req_op dio_op = dio->opf & REQ_OP_MASK;
  557. int ret;
  558. sector_t fs_startblk; /* Into file, in filesystem-sized blocks */
  559. sector_t fs_endblk; /* Into file, in filesystem-sized blocks */
  560. unsigned long fs_count; /* Number of filesystem-sized blocks */
  561. int create;
  562. unsigned int i_blkbits = sdio->blkbits + sdio->blkfactor;
  563. loff_t i_size;
  564. /*
  565. * If there was a memory error and we've overwritten all the
  566. * mapped blocks then we can now return that memory error
  567. */
  568. ret = dio->page_errors;
  569. if (ret == 0) {
  570. BUG_ON(sdio->block_in_file >= sdio->final_block_in_request);
  571. fs_startblk = sdio->block_in_file >> sdio->blkfactor;
  572. fs_endblk = (sdio->final_block_in_request - 1) >>
  573. sdio->blkfactor;
  574. fs_count = fs_endblk - fs_startblk + 1;
  575. map_bh->b_state = 0;
  576. map_bh->b_size = fs_count << i_blkbits;
  577. /*
  578. * For writes that could fill holes inside i_size on a
  579. * DIO_SKIP_HOLES filesystem we forbid block creations: only
  580. * overwrites are permitted. We will return early to the caller
  581. * once we see an unmapped buffer head returned, and the caller
  582. * will fall back to buffered I/O.
  583. *
  584. * Otherwise the decision is left to the get_blocks method,
  585. * which may decide to handle it or also return an unmapped
  586. * buffer head.
  587. */
  588. create = dio_op == REQ_OP_WRITE;
  589. if (dio->flags & DIO_SKIP_HOLES) {
  590. i_size = i_size_read(dio->inode);
  591. if (i_size && fs_startblk <= (i_size - 1) >> i_blkbits)
  592. create = 0;
  593. }
  594. ret = (*sdio->get_block)(dio->inode, fs_startblk,
  595. map_bh, create);
  596. /* Store for completion */
  597. dio->private = map_bh->b_private;
  598. if (ret == 0 && buffer_defer_completion(map_bh))
  599. ret = dio_set_defer_completion(dio);
  600. }
  601. return ret;
  602. }
  603. /*
  604. * There is no bio. Make one now.
  605. */
  606. static inline int dio_new_bio(struct dio *dio, struct dio_submit *sdio,
  607. sector_t start_sector, struct buffer_head *map_bh)
  608. {
  609. sector_t sector;
  610. int ret, nr_pages;
  611. ret = dio_bio_reap(dio, sdio);
  612. if (ret)
  613. goto out;
  614. sector = start_sector << (sdio->blkbits - 9);
  615. nr_pages = bio_max_segs(sdio->pages_in_io);
  616. BUG_ON(nr_pages <= 0);
  617. dio_bio_alloc(dio, sdio, map_bh->b_bdev, sector, nr_pages);
  618. sdio->boundary = 0;
  619. out:
  620. return ret;
  621. }
  622. /*
  623. * Attempt to put the current chunk of 'cur_page' into the current BIO. If
  624. * that was successful then update final_block_in_bio and take a ref against
  625. * the just-added page.
  626. *
  627. * Return zero on success. Non-zero means the caller needs to start a new BIO.
  628. */
  629. static inline int dio_bio_add_page(struct dio_submit *sdio)
  630. {
  631. int ret;
  632. ret = bio_add_page(sdio->bio, sdio->cur_page,
  633. sdio->cur_page_len, sdio->cur_page_offset);
  634. if (ret == sdio->cur_page_len) {
  635. /*
  636. * Decrement count only, if we are done with this page
  637. */
  638. if ((sdio->cur_page_len + sdio->cur_page_offset) == PAGE_SIZE)
  639. sdio->pages_in_io--;
  640. get_page(sdio->cur_page);
  641. sdio->final_block_in_bio = sdio->cur_page_block +
  642. (sdio->cur_page_len >> sdio->blkbits);
  643. ret = 0;
  644. } else {
  645. ret = 1;
  646. }
  647. return ret;
  648. }
  649. /*
  650. * Put cur_page under IO. The section of cur_page which is described by
  651. * cur_page_offset,cur_page_len is put into a BIO. The section of cur_page
  652. * starts on-disk at cur_page_block.
  653. *
  654. * We take a ref against the page here (on behalf of its presence in the bio).
  655. *
  656. * The caller of this function is responsible for removing cur_page from the
  657. * dio, and for dropping the refcount which came from that presence.
  658. */
  659. static inline int dio_send_cur_page(struct dio *dio, struct dio_submit *sdio,
  660. struct buffer_head *map_bh)
  661. {
  662. int ret = 0;
  663. if (sdio->bio) {
  664. loff_t cur_offset = sdio->cur_page_fs_offset;
  665. loff_t bio_next_offset = sdio->logical_offset_in_bio +
  666. sdio->bio->bi_iter.bi_size;
  667. /*
  668. * See whether this new request is contiguous with the old.
  669. *
  670. * Btrfs cannot handle having logically non-contiguous requests
  671. * submitted. For example if you have
  672. *
  673. * Logical: [0-4095][HOLE][8192-12287]
  674. * Physical: [0-4095] [4096-8191]
  675. *
  676. * We cannot submit those pages together as one BIO. So if our
  677. * current logical offset in the file does not equal what would
  678. * be the next logical offset in the bio, submit the bio we
  679. * have.
  680. */
  681. if (sdio->final_block_in_bio != sdio->cur_page_block ||
  682. cur_offset != bio_next_offset)
  683. dio_bio_submit(dio, sdio);
  684. }
  685. if (sdio->bio == NULL) {
  686. ret = dio_new_bio(dio, sdio, sdio->cur_page_block, map_bh);
  687. if (ret)
  688. goto out;
  689. }
  690. if (dio_bio_add_page(sdio) != 0) {
  691. dio_bio_submit(dio, sdio);
  692. ret = dio_new_bio(dio, sdio, sdio->cur_page_block, map_bh);
  693. if (ret == 0) {
  694. ret = dio_bio_add_page(sdio);
  695. BUG_ON(ret != 0);
  696. }
  697. }
  698. out:
  699. return ret;
  700. }
  701. /*
  702. * An autonomous function to put a chunk of a page under deferred IO.
  703. *
  704. * The caller doesn't actually know (or care) whether this piece of page is in
  705. * a BIO, or is under IO or whatever. We just take care of all possible
  706. * situations here. The separation between the logic of do_direct_IO() and
  707. * that of submit_page_section() is important for clarity. Please don't break.
  708. *
  709. * The chunk of page starts on-disk at blocknr.
  710. *
  711. * We perform deferred IO, by recording the last-submitted page inside our
  712. * private part of the dio structure. If possible, we just expand the IO
  713. * across that page here.
  714. *
  715. * If that doesn't work out then we put the old page into the bio and add this
  716. * page to the dio instead.
  717. */
  718. static inline int
  719. submit_page_section(struct dio *dio, struct dio_submit *sdio, struct page *page,
  720. unsigned offset, unsigned len, sector_t blocknr,
  721. struct buffer_head *map_bh)
  722. {
  723. const enum req_op dio_op = dio->opf & REQ_OP_MASK;
  724. int ret = 0;
  725. int boundary = sdio->boundary; /* dio_send_cur_page may clear it */
  726. if (dio_op == REQ_OP_WRITE) {
  727. /*
  728. * Read accounting is performed in submit_bio()
  729. */
  730. task_io_account_write(len);
  731. }
  732. /*
  733. * Can we just grow the current page's presence in the dio?
  734. */
  735. if (sdio->cur_page == page &&
  736. sdio->cur_page_offset + sdio->cur_page_len == offset &&
  737. sdio->cur_page_block +
  738. (sdio->cur_page_len >> sdio->blkbits) == blocknr) {
  739. sdio->cur_page_len += len;
  740. goto out;
  741. }
  742. /*
  743. * If there's a deferred page already there then send it.
  744. */
  745. if (sdio->cur_page) {
  746. ret = dio_send_cur_page(dio, sdio, map_bh);
  747. put_page(sdio->cur_page);
  748. sdio->cur_page = NULL;
  749. if (ret)
  750. return ret;
  751. }
  752. get_page(page); /* It is in dio */
  753. sdio->cur_page = page;
  754. sdio->cur_page_offset = offset;
  755. sdio->cur_page_len = len;
  756. sdio->cur_page_block = blocknr;
  757. sdio->cur_page_fs_offset = sdio->block_in_file << sdio->blkbits;
  758. out:
  759. /*
  760. * If boundary then we want to schedule the IO now to
  761. * avoid metadata seeks.
  762. */
  763. if (boundary) {
  764. ret = dio_send_cur_page(dio, sdio, map_bh);
  765. if (sdio->bio)
  766. dio_bio_submit(dio, sdio);
  767. put_page(sdio->cur_page);
  768. sdio->cur_page = NULL;
  769. }
  770. return ret;
  771. }
  772. /*
  773. * If we are not writing the entire block and get_block() allocated
  774. * the block for us, we need to fill-in the unused portion of the
  775. * block with zeros. This happens only if user-buffer, fileoffset or
  776. * io length is not filesystem block-size multiple.
  777. *
  778. * `end' is zero if we're doing the start of the IO, 1 at the end of the
  779. * IO.
  780. */
  781. static inline void dio_zero_block(struct dio *dio, struct dio_submit *sdio,
  782. int end, struct buffer_head *map_bh)
  783. {
  784. unsigned dio_blocks_per_fs_block;
  785. unsigned this_chunk_blocks; /* In dio_blocks */
  786. unsigned this_chunk_bytes;
  787. struct page *page;
  788. sdio->start_zero_done = 1;
  789. if (!sdio->blkfactor || !buffer_new(map_bh))
  790. return;
  791. dio_blocks_per_fs_block = 1 << sdio->blkfactor;
  792. this_chunk_blocks = sdio->block_in_file & (dio_blocks_per_fs_block - 1);
  793. if (!this_chunk_blocks)
  794. return;
  795. /*
  796. * We need to zero out part of an fs block. It is either at the
  797. * beginning or the end of the fs block.
  798. */
  799. if (end)
  800. this_chunk_blocks = dio_blocks_per_fs_block - this_chunk_blocks;
  801. this_chunk_bytes = this_chunk_blocks << sdio->blkbits;
  802. page = ZERO_PAGE(0);
  803. if (submit_page_section(dio, sdio, page, 0, this_chunk_bytes,
  804. sdio->next_block_for_io, map_bh))
  805. return;
  806. sdio->next_block_for_io += this_chunk_blocks;
  807. }
  808. /*
  809. * Walk the user pages, and the file, mapping blocks to disk and generating
  810. * a sequence of (page,offset,len,block) mappings. These mappings are injected
  811. * into submit_page_section(), which takes care of the next stage of submission
  812. *
  813. * Direct IO against a blockdev is different from a file. Because we can
  814. * happily perform page-sized but 512-byte aligned IOs. It is important that
  815. * blockdev IO be able to have fine alignment and large sizes.
  816. *
  817. * So what we do is to permit the ->get_block function to populate bh.b_size
  818. * with the size of IO which is permitted at this offset and this i_blkbits.
  819. *
  820. * For best results, the blockdev should be set up with 512-byte i_blkbits and
  821. * it should set b_size to PAGE_SIZE or more inside get_block(). This gives
  822. * fine alignment but still allows this function to work in PAGE_SIZE units.
  823. */
  824. static int do_direct_IO(struct dio *dio, struct dio_submit *sdio,
  825. struct buffer_head *map_bh)
  826. {
  827. const enum req_op dio_op = dio->opf & REQ_OP_MASK;
  828. const unsigned blkbits = sdio->blkbits;
  829. const unsigned i_blkbits = blkbits + sdio->blkfactor;
  830. int ret = 0;
  831. while (sdio->block_in_file < sdio->final_block_in_request) {
  832. struct page *page;
  833. size_t from, to;
  834. page = dio_get_page(dio, sdio);
  835. if (IS_ERR(page)) {
  836. ret = PTR_ERR(page);
  837. goto out;
  838. }
  839. from = sdio->head ? 0 : sdio->from;
  840. to = (sdio->head == sdio->tail - 1) ? sdio->to : PAGE_SIZE;
  841. sdio->head++;
  842. while (from < to) {
  843. unsigned this_chunk_bytes; /* # of bytes mapped */
  844. unsigned this_chunk_blocks; /* # of blocks */
  845. unsigned u;
  846. if (sdio->blocks_available == 0) {
  847. /*
  848. * Need to go and map some more disk
  849. */
  850. unsigned long blkmask;
  851. unsigned long dio_remainder;
  852. ret = get_more_blocks(dio, sdio, map_bh);
  853. if (ret) {
  854. put_page(page);
  855. goto out;
  856. }
  857. if (!buffer_mapped(map_bh))
  858. goto do_holes;
  859. sdio->blocks_available =
  860. map_bh->b_size >> blkbits;
  861. sdio->next_block_for_io =
  862. map_bh->b_blocknr << sdio->blkfactor;
  863. if (buffer_new(map_bh)) {
  864. clean_bdev_aliases(
  865. map_bh->b_bdev,
  866. map_bh->b_blocknr,
  867. map_bh->b_size >> i_blkbits);
  868. }
  869. if (!sdio->blkfactor)
  870. goto do_holes;
  871. blkmask = (1 << sdio->blkfactor) - 1;
  872. dio_remainder = (sdio->block_in_file & blkmask);
  873. /*
  874. * If we are at the start of IO and that IO
  875. * starts partway into a fs-block,
  876. * dio_remainder will be non-zero. If the IO
  877. * is a read then we can simply advance the IO
  878. * cursor to the first block which is to be
  879. * read. But if the IO is a write and the
  880. * block was newly allocated we cannot do that;
  881. * the start of the fs block must be zeroed out
  882. * on-disk
  883. */
  884. if (!buffer_new(map_bh))
  885. sdio->next_block_for_io += dio_remainder;
  886. sdio->blocks_available -= dio_remainder;
  887. }
  888. do_holes:
  889. /* Handle holes */
  890. if (!buffer_mapped(map_bh)) {
  891. loff_t i_size_aligned;
  892. /* AKPM: eargh, -ENOTBLK is a hack */
  893. if (dio_op == REQ_OP_WRITE) {
  894. put_page(page);
  895. return -ENOTBLK;
  896. }
  897. /*
  898. * Be sure to account for a partial block as the
  899. * last block in the file
  900. */
  901. i_size_aligned = ALIGN(i_size_read(dio->inode),
  902. 1 << blkbits);
  903. if (sdio->block_in_file >=
  904. i_size_aligned >> blkbits) {
  905. /* We hit eof */
  906. put_page(page);
  907. goto out;
  908. }
  909. zero_user(page, from, 1 << blkbits);
  910. sdio->block_in_file++;
  911. from += 1 << blkbits;
  912. dio->result += 1 << blkbits;
  913. goto next_block;
  914. }
  915. /*
  916. * If we're performing IO which has an alignment which
  917. * is finer than the underlying fs, go check to see if
  918. * we must zero out the start of this block.
  919. */
  920. if (unlikely(sdio->blkfactor && !sdio->start_zero_done))
  921. dio_zero_block(dio, sdio, 0, map_bh);
  922. /*
  923. * Work out, in this_chunk_blocks, how much disk we
  924. * can add to this page
  925. */
  926. this_chunk_blocks = sdio->blocks_available;
  927. u = (to - from) >> blkbits;
  928. if (this_chunk_blocks > u)
  929. this_chunk_blocks = u;
  930. u = sdio->final_block_in_request - sdio->block_in_file;
  931. if (this_chunk_blocks > u)
  932. this_chunk_blocks = u;
  933. this_chunk_bytes = this_chunk_blocks << blkbits;
  934. BUG_ON(this_chunk_bytes == 0);
  935. if (this_chunk_blocks == sdio->blocks_available)
  936. sdio->boundary = buffer_boundary(map_bh);
  937. ret = submit_page_section(dio, sdio, page,
  938. from,
  939. this_chunk_bytes,
  940. sdio->next_block_for_io,
  941. map_bh);
  942. if (ret) {
  943. put_page(page);
  944. goto out;
  945. }
  946. sdio->next_block_for_io += this_chunk_blocks;
  947. sdio->block_in_file += this_chunk_blocks;
  948. from += this_chunk_bytes;
  949. dio->result += this_chunk_bytes;
  950. sdio->blocks_available -= this_chunk_blocks;
  951. next_block:
  952. BUG_ON(sdio->block_in_file > sdio->final_block_in_request);
  953. if (sdio->block_in_file == sdio->final_block_in_request)
  954. break;
  955. }
  956. /* Drop the ref which was taken in get_user_pages() */
  957. put_page(page);
  958. }
  959. out:
  960. return ret;
  961. }
  962. static inline int drop_refcount(struct dio *dio)
  963. {
  964. int ret2;
  965. unsigned long flags;
  966. /*
  967. * Sync will always be dropping the final ref and completing the
  968. * operation. AIO can if it was a broken operation described above or
  969. * in fact if all the bios race to complete before we get here. In
  970. * that case dio_complete() translates the EIOCBQUEUED into the proper
  971. * return code that the caller will hand to ->complete().
  972. *
  973. * This is managed by the bio_lock instead of being an atomic_t so that
  974. * completion paths can drop their ref and use the remaining count to
  975. * decide to wake the submission path atomically.
  976. */
  977. spin_lock_irqsave(&dio->bio_lock, flags);
  978. ret2 = --dio->refcount;
  979. spin_unlock_irqrestore(&dio->bio_lock, flags);
  980. return ret2;
  981. }
  982. /*
  983. * This is a library function for use by filesystem drivers.
  984. *
  985. * The locking rules are governed by the flags parameter:
  986. * - if the flags value contains DIO_LOCKING we use a fancy locking
  987. * scheme for dumb filesystems.
  988. * For writes this function is called under i_mutex and returns with
  989. * i_mutex held, for reads, i_mutex is not held on entry, but it is
  990. * taken and dropped again before returning.
  991. * - if the flags value does NOT contain DIO_LOCKING we don't use any
  992. * internal locking but rather rely on the filesystem to synchronize
  993. * direct I/O reads/writes versus each other and truncate.
  994. *
  995. * To help with locking against truncate we incremented the i_dio_count
  996. * counter before starting direct I/O, and decrement it once we are done.
  997. * Truncate can wait for it to reach zero to provide exclusion. It is
  998. * expected that filesystem provide exclusion between new direct I/O
  999. * and truncates. For DIO_LOCKING filesystems this is done by i_mutex,
  1000. * but other filesystems need to take care of this on their own.
  1001. *
  1002. * NOTE: if you pass "sdio" to anything by pointer make sure that function
  1003. * is always inlined. Otherwise gcc is unable to split the structure into
  1004. * individual fields and will generate much worse code. This is important
  1005. * for the whole file.
  1006. */
  1007. ssize_t __blockdev_direct_IO(struct kiocb *iocb, struct inode *inode,
  1008. struct block_device *bdev, struct iov_iter *iter,
  1009. get_block_t get_block, dio_iodone_t end_io,
  1010. dio_submit_t submit_io, int flags)
  1011. {
  1012. unsigned i_blkbits = READ_ONCE(inode->i_blkbits);
  1013. unsigned blkbits = i_blkbits;
  1014. unsigned blocksize_mask = (1 << blkbits) - 1;
  1015. ssize_t retval = -EINVAL;
  1016. const size_t count = iov_iter_count(iter);
  1017. loff_t offset = iocb->ki_pos;
  1018. const loff_t end = offset + count;
  1019. struct dio *dio;
  1020. struct dio_submit sdio = { 0, };
  1021. struct buffer_head map_bh = { 0, };
  1022. struct blk_plug plug;
  1023. unsigned long align = offset | iov_iter_alignment(iter);
  1024. /*
  1025. * Avoid references to bdev if not absolutely needed to give
  1026. * the early prefetch in the caller enough time.
  1027. */
  1028. /* watch out for a 0 len io from a tricksy fs */
  1029. if (iov_iter_rw(iter) == READ && !count)
  1030. return 0;
  1031. dio = kmem_cache_alloc(dio_cache, GFP_KERNEL);
  1032. if (!dio)
  1033. return -ENOMEM;
  1034. /*
  1035. * Believe it or not, zeroing out the page array caused a .5%
  1036. * performance regression in a database benchmark. So, we take
  1037. * care to only zero out what's needed.
  1038. */
  1039. memset(dio, 0, offsetof(struct dio, pages));
  1040. dio->flags = flags;
  1041. if (dio->flags & DIO_LOCKING && iov_iter_rw(iter) == READ) {
  1042. /* will be released by direct_io_worker */
  1043. inode_lock(inode);
  1044. }
  1045. /* Once we sampled i_size check for reads beyond EOF */
  1046. dio->i_size = i_size_read(inode);
  1047. if (iov_iter_rw(iter) == READ && offset >= dio->i_size) {
  1048. retval = 0;
  1049. goto fail_dio;
  1050. }
  1051. if (align & blocksize_mask) {
  1052. if (bdev)
  1053. blkbits = blksize_bits(bdev_logical_block_size(bdev));
  1054. blocksize_mask = (1 << blkbits) - 1;
  1055. if (align & blocksize_mask)
  1056. goto fail_dio;
  1057. }
  1058. if (dio->flags & DIO_LOCKING && iov_iter_rw(iter) == READ) {
  1059. struct address_space *mapping = iocb->ki_filp->f_mapping;
  1060. retval = filemap_write_and_wait_range(mapping, offset, end - 1);
  1061. if (retval)
  1062. goto fail_dio;
  1063. }
  1064. /*
  1065. * For file extending writes updating i_size before data writeouts
  1066. * complete can expose uninitialized blocks in dumb filesystems.
  1067. * In that case we need to wait for I/O completion even if asked
  1068. * for an asynchronous write.
  1069. */
  1070. if (is_sync_kiocb(iocb))
  1071. dio->is_async = false;
  1072. else if (iov_iter_rw(iter) == WRITE && end > i_size_read(inode))
  1073. dio->is_async = false;
  1074. else
  1075. dio->is_async = true;
  1076. dio->inode = inode;
  1077. if (iov_iter_rw(iter) == WRITE) {
  1078. dio->opf = REQ_OP_WRITE | REQ_SYNC | REQ_IDLE;
  1079. if (iocb->ki_flags & IOCB_NOWAIT)
  1080. dio->opf |= REQ_NOWAIT;
  1081. } else {
  1082. dio->opf = REQ_OP_READ;
  1083. }
  1084. /*
  1085. * For AIO O_(D)SYNC writes we need to defer completions to a workqueue
  1086. * so that we can call ->fsync.
  1087. */
  1088. if (dio->is_async && iov_iter_rw(iter) == WRITE) {
  1089. retval = 0;
  1090. if (iocb_is_dsync(iocb))
  1091. retval = dio_set_defer_completion(dio);
  1092. else if (!dio->inode->i_sb->s_dio_done_wq) {
  1093. /*
  1094. * In case of AIO write racing with buffered read we
  1095. * need to defer completion. We can't decide this now,
  1096. * however the workqueue needs to be initialized here.
  1097. */
  1098. retval = sb_init_dio_done_wq(dio->inode->i_sb);
  1099. }
  1100. if (retval)
  1101. goto fail_dio;
  1102. }
  1103. /*
  1104. * Will be decremented at I/O completion time.
  1105. */
  1106. inode_dio_begin(inode);
  1107. retval = 0;
  1108. sdio.blkbits = blkbits;
  1109. sdio.blkfactor = i_blkbits - blkbits;
  1110. sdio.block_in_file = offset >> blkbits;
  1111. sdio.get_block = get_block;
  1112. dio->end_io = end_io;
  1113. sdio.submit_io = submit_io;
  1114. sdio.final_block_in_bio = -1;
  1115. sdio.next_block_for_io = -1;
  1116. dio->iocb = iocb;
  1117. spin_lock_init(&dio->bio_lock);
  1118. dio->refcount = 1;
  1119. dio->should_dirty = user_backed_iter(iter) && iov_iter_rw(iter) == READ;
  1120. sdio.iter = iter;
  1121. sdio.final_block_in_request = end >> blkbits;
  1122. /*
  1123. * In case of non-aligned buffers, we may need 2 more
  1124. * pages since we need to zero out first and last block.
  1125. */
  1126. if (unlikely(sdio.blkfactor))
  1127. sdio.pages_in_io = 2;
  1128. sdio.pages_in_io += iov_iter_npages(iter, INT_MAX);
  1129. blk_start_plug(&plug);
  1130. retval = do_direct_IO(dio, &sdio, &map_bh);
  1131. if (retval)
  1132. dio_cleanup(dio, &sdio);
  1133. if (retval == -ENOTBLK) {
  1134. /*
  1135. * The remaining part of the request will be
  1136. * handled by buffered I/O when we return
  1137. */
  1138. retval = 0;
  1139. }
  1140. /*
  1141. * There may be some unwritten disk at the end of a part-written
  1142. * fs-block-sized block. Go zero that now.
  1143. */
  1144. dio_zero_block(dio, &sdio, 1, &map_bh);
  1145. if (sdio.cur_page) {
  1146. ssize_t ret2;
  1147. ret2 = dio_send_cur_page(dio, &sdio, &map_bh);
  1148. if (retval == 0)
  1149. retval = ret2;
  1150. put_page(sdio.cur_page);
  1151. sdio.cur_page = NULL;
  1152. }
  1153. if (sdio.bio)
  1154. dio_bio_submit(dio, &sdio);
  1155. blk_finish_plug(&plug);
  1156. /*
  1157. * It is possible that, we return short IO due to end of file.
  1158. * In that case, we need to release all the pages we got hold on.
  1159. */
  1160. dio_cleanup(dio, &sdio);
  1161. /*
  1162. * All block lookups have been performed. For READ requests
  1163. * we can let i_mutex go now that its achieved its purpose
  1164. * of protecting us from looking up uninitialized blocks.
  1165. */
  1166. if (iov_iter_rw(iter) == READ && (dio->flags & DIO_LOCKING))
  1167. inode_unlock(dio->inode);
  1168. /*
  1169. * The only time we want to leave bios in flight is when a successful
  1170. * partial aio read or full aio write have been setup. In that case
  1171. * bio completion will call aio_complete. The only time it's safe to
  1172. * call aio_complete is when we return -EIOCBQUEUED, so we key on that.
  1173. * This had *better* be the only place that raises -EIOCBQUEUED.
  1174. */
  1175. BUG_ON(retval == -EIOCBQUEUED);
  1176. if (dio->is_async && retval == 0 && dio->result &&
  1177. (iov_iter_rw(iter) == READ || dio->result == count))
  1178. retval = -EIOCBQUEUED;
  1179. else
  1180. dio_await_completion(dio);
  1181. if (drop_refcount(dio) == 0) {
  1182. retval = dio_complete(dio, retval, DIO_COMPLETE_INVALIDATE);
  1183. } else
  1184. BUG_ON(retval != -EIOCBQUEUED);
  1185. return retval;
  1186. fail_dio:
  1187. if (dio->flags & DIO_LOCKING && iov_iter_rw(iter) == READ)
  1188. inode_unlock(inode);
  1189. kmem_cache_free(dio_cache, dio);
  1190. return retval;
  1191. }
  1192. EXPORT_SYMBOL(__blockdev_direct_IO);
  1193. static __init int dio_init(void)
  1194. {
  1195. dio_cache = KMEM_CACHE(dio, SLAB_PANIC);
  1196. return 0;
  1197. }
  1198. module_init(dio_init)