direct-io.c 34 KB

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