direct-io.c 35 KB

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