direct-io.c 38 KB

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