direct-io.c 35 KB

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