direct-io.c 34 KB

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