direct-io.c 41 KB

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