direct-io.c 38 KB

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