filemap.c 65 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469
  1. /*
  2. * linux/mm/filemap.c
  3. *
  4. * Copyright (C) 1994-1999 Linus Torvalds
  5. */
  6. /*
  7. * This file handles the generic file mmap semantics used by
  8. * most "normal" filesystems (but you don't /have/ to use this:
  9. * the NFS filesystem used to do this differently, for example)
  10. */
  11. #include <linux/module.h>
  12. #include <linux/slab.h>
  13. #include <linux/compiler.h>
  14. #include <linux/fs.h>
  15. #include <linux/uaccess.h>
  16. #include <linux/aio.h>
  17. #include <linux/capability.h>
  18. #include <linux/kernel_stat.h>
  19. #include <linux/mm.h>
  20. #include <linux/swap.h>
  21. #include <linux/mman.h>
  22. #include <linux/pagemap.h>
  23. #include <linux/file.h>
  24. #include <linux/uio.h>
  25. #include <linux/hash.h>
  26. #include <linux/writeback.h>
  27. #include <linux/backing-dev.h>
  28. #include <linux/pagevec.h>
  29. #include <linux/blkdev.h>
  30. #include <linux/security.h>
  31. #include <linux/syscalls.h>
  32. #include <linux/cpuset.h>
  33. #include <linux/hardirq.h> /* for BUG_ON(!in_atomic()) only */
  34. #include <linux/memcontrol.h>
  35. #include <linux/mm_inline.h> /* for page_is_file_cache() */
  36. #include "internal.h"
  37. /*
  38. * FIXME: remove all knowledge of the buffer layer from the core VM
  39. */
  40. #include <linux/buffer_head.h> /* for try_to_free_buffers */
  41. #include <asm/mman.h>
  42. /*
  43. * Shared mappings implemented 30.11.1994. It's not fully working yet,
  44. * though.
  45. *
  46. * Shared mappings now work. 15.8.1995 Bruno.
  47. *
  48. * finished 'unifying' the page and buffer cache and SMP-threaded the
  49. * page-cache, 21.05.1999, Ingo Molnar <mingo@redhat.com>
  50. *
  51. * SMP-threaded pagemap-LRU 1999, Andrea Arcangeli <andrea@suse.de>
  52. */
  53. /*
  54. * Lock ordering:
  55. *
  56. * ->i_mmap_lock (vmtruncate)
  57. * ->private_lock (__free_pte->__set_page_dirty_buffers)
  58. * ->swap_lock (exclusive_swap_page, others)
  59. * ->mapping->tree_lock
  60. *
  61. * ->i_mutex
  62. * ->i_mmap_lock (truncate->unmap_mapping_range)
  63. *
  64. * ->mmap_sem
  65. * ->i_mmap_lock
  66. * ->page_table_lock or pte_lock (various, mainly in memory.c)
  67. * ->mapping->tree_lock (arch-dependent flush_dcache_mmap_lock)
  68. *
  69. * ->mmap_sem
  70. * ->lock_page (access_process_vm)
  71. *
  72. * ->i_mutex (generic_file_buffered_write)
  73. * ->mmap_sem (fault_in_pages_readable->do_page_fault)
  74. *
  75. * ->i_mutex
  76. * ->i_alloc_sem (various)
  77. *
  78. * ->inode_lock
  79. * ->sb_lock (fs/fs-writeback.c)
  80. * ->mapping->tree_lock (__sync_single_inode)
  81. *
  82. * ->i_mmap_lock
  83. * ->anon_vma.lock (vma_adjust)
  84. *
  85. * ->anon_vma.lock
  86. * ->page_table_lock or pte_lock (anon_vma_prepare and various)
  87. *
  88. * ->page_table_lock or pte_lock
  89. * ->swap_lock (try_to_unmap_one)
  90. * ->private_lock (try_to_unmap_one)
  91. * ->tree_lock (try_to_unmap_one)
  92. * ->zone.lru_lock (follow_page->mark_page_accessed)
  93. * ->zone.lru_lock (check_pte_range->isolate_lru_page)
  94. * ->private_lock (page_remove_rmap->set_page_dirty)
  95. * ->tree_lock (page_remove_rmap->set_page_dirty)
  96. * ->inode_lock (page_remove_rmap->set_page_dirty)
  97. * ->inode_lock (zap_pte_range->set_page_dirty)
  98. * ->private_lock (zap_pte_range->__set_page_dirty_buffers)
  99. *
  100. * ->task->proc_lock
  101. * ->dcache_lock (proc_pid_lookup)
  102. */
  103. /*
  104. * Remove a page from the page cache and free it. Caller has to make
  105. * sure the page is locked and that nobody else uses it - or that usage
  106. * is safe. The caller must hold the mapping's tree_lock.
  107. */
  108. void __remove_from_page_cache(struct page *page)
  109. {
  110. struct address_space *mapping = page->mapping;
  111. radix_tree_delete(&mapping->page_tree, page->index);
  112. page->mapping = NULL;
  113. mapping->nrpages--;
  114. __dec_zone_page_state(page, NR_FILE_PAGES);
  115. if (PageSwapBacked(page))
  116. __dec_zone_page_state(page, NR_SHMEM);
  117. BUG_ON(page_mapped(page));
  118. /*
  119. * Some filesystems seem to re-dirty the page even after
  120. * the VM has canceled the dirty bit (eg ext3 journaling).
  121. *
  122. * Fix it up by doing a final dirty accounting check after
  123. * having removed the page entirely.
  124. */
  125. if (PageDirty(page) && mapping_cap_account_dirty(mapping)) {
  126. dec_zone_page_state(page, NR_FILE_DIRTY);
  127. dec_bdi_stat(mapping->backing_dev_info, BDI_RECLAIMABLE);
  128. }
  129. }
  130. void remove_from_page_cache(struct page *page)
  131. {
  132. struct address_space *mapping = page->mapping;
  133. BUG_ON(!PageLocked(page));
  134. spin_lock_irq(&mapping->tree_lock);
  135. __remove_from_page_cache(page);
  136. spin_unlock_irq(&mapping->tree_lock);
  137. mem_cgroup_uncharge_cache_page(page);
  138. }
  139. static int sync_page(void *word)
  140. {
  141. struct address_space *mapping;
  142. struct page *page;
  143. page = container_of((unsigned long *)word, struct page, flags);
  144. /*
  145. * page_mapping() is being called without PG_locked held.
  146. * Some knowledge of the state and use of the page is used to
  147. * reduce the requirements down to a memory barrier.
  148. * The danger here is of a stale page_mapping() return value
  149. * indicating a struct address_space different from the one it's
  150. * associated with when it is associated with one.
  151. * After smp_mb(), it's either the correct page_mapping() for
  152. * the page, or an old page_mapping() and the page's own
  153. * page_mapping() has gone NULL.
  154. * The ->sync_page() address_space operation must tolerate
  155. * page_mapping() going NULL. By an amazing coincidence,
  156. * this comes about because none of the users of the page
  157. * in the ->sync_page() methods make essential use of the
  158. * page_mapping(), merely passing the page down to the backing
  159. * device's unplug functions when it's non-NULL, which in turn
  160. * ignore it for all cases but swap, where only page_private(page) is
  161. * of interest. When page_mapping() does go NULL, the entire
  162. * call stack gracefully ignores the page and returns.
  163. * -- wli
  164. */
  165. smp_mb();
  166. mapping = page_mapping(page);
  167. if (mapping && mapping->a_ops && mapping->a_ops->sync_page)
  168. mapping->a_ops->sync_page(page);
  169. io_schedule();
  170. return 0;
  171. }
  172. static int sync_page_killable(void *word)
  173. {
  174. sync_page(word);
  175. return fatal_signal_pending(current) ? -EINTR : 0;
  176. }
  177. /**
  178. * __filemap_fdatawrite_range - start writeback on mapping dirty pages in range
  179. * @mapping: address space structure to write
  180. * @start: offset in bytes where the range starts
  181. * @end: offset in bytes where the range ends (inclusive)
  182. * @sync_mode: enable synchronous operation
  183. *
  184. * Start writeback against all of a mapping's dirty pages that lie
  185. * within the byte offsets <start, end> inclusive.
  186. *
  187. * If sync_mode is WB_SYNC_ALL then this is a "data integrity" operation, as
  188. * opposed to a regular memory cleansing writeback. The difference between
  189. * these two operations is that if a dirty page/buffer is encountered, it must
  190. * be waited upon, and not just skipped over.
  191. */
  192. int __filemap_fdatawrite_range(struct address_space *mapping, loff_t start,
  193. loff_t end, int sync_mode)
  194. {
  195. int ret;
  196. struct writeback_control wbc = {
  197. .sync_mode = sync_mode,
  198. .nr_to_write = LONG_MAX,
  199. .range_start = start,
  200. .range_end = end,
  201. };
  202. if (!mapping_cap_writeback_dirty(mapping))
  203. return 0;
  204. ret = do_writepages(mapping, &wbc);
  205. return ret;
  206. }
  207. static inline int __filemap_fdatawrite(struct address_space *mapping,
  208. int sync_mode)
  209. {
  210. return __filemap_fdatawrite_range(mapping, 0, LLONG_MAX, sync_mode);
  211. }
  212. int filemap_fdatawrite(struct address_space *mapping)
  213. {
  214. return __filemap_fdatawrite(mapping, WB_SYNC_ALL);
  215. }
  216. EXPORT_SYMBOL(filemap_fdatawrite);
  217. int filemap_fdatawrite_range(struct address_space *mapping, loff_t start,
  218. loff_t end)
  219. {
  220. return __filemap_fdatawrite_range(mapping, start, end, WB_SYNC_ALL);
  221. }
  222. EXPORT_SYMBOL(filemap_fdatawrite_range);
  223. /**
  224. * filemap_flush - mostly a non-blocking flush
  225. * @mapping: target address_space
  226. *
  227. * This is a mostly non-blocking flush. Not suitable for data-integrity
  228. * purposes - I/O may not be started against all dirty pages.
  229. */
  230. int filemap_flush(struct address_space *mapping)
  231. {
  232. return __filemap_fdatawrite(mapping, WB_SYNC_NONE);
  233. }
  234. EXPORT_SYMBOL(filemap_flush);
  235. /**
  236. * wait_on_page_writeback_range - wait for writeback to complete
  237. * @mapping: target address_space
  238. * @start: beginning page index
  239. * @end: ending page index
  240. *
  241. * Wait for writeback to complete against pages indexed by start->end
  242. * inclusive
  243. */
  244. int wait_on_page_writeback_range(struct address_space *mapping,
  245. pgoff_t start, pgoff_t end)
  246. {
  247. struct pagevec pvec;
  248. int nr_pages;
  249. int ret = 0;
  250. pgoff_t index;
  251. if (end < start)
  252. return 0;
  253. pagevec_init(&pvec, 0);
  254. index = start;
  255. while ((index <= end) &&
  256. (nr_pages = pagevec_lookup_tag(&pvec, mapping, &index,
  257. PAGECACHE_TAG_WRITEBACK,
  258. min(end - index, (pgoff_t)PAGEVEC_SIZE-1) + 1)) != 0) {
  259. unsigned i;
  260. for (i = 0; i < nr_pages; i++) {
  261. struct page *page = pvec.pages[i];
  262. /* until radix tree lookup accepts end_index */
  263. if (page->index > end)
  264. continue;
  265. wait_on_page_writeback(page);
  266. if (PageError(page))
  267. ret = -EIO;
  268. }
  269. pagevec_release(&pvec);
  270. cond_resched();
  271. }
  272. /* Check for outstanding write errors */
  273. if (test_and_clear_bit(AS_ENOSPC, &mapping->flags))
  274. ret = -ENOSPC;
  275. if (test_and_clear_bit(AS_EIO, &mapping->flags))
  276. ret = -EIO;
  277. return ret;
  278. }
  279. /**
  280. * filemap_fdatawait_range - wait for all under-writeback pages to complete in a given range
  281. * @mapping: address space structure to wait for
  282. * @start: offset in bytes where the range starts
  283. * @end: offset in bytes where the range ends (inclusive)
  284. *
  285. * Walk the list of under-writeback pages of the given address space
  286. * in the given range and wait for all of them.
  287. *
  288. * This is just a simple wrapper so that callers don't have to convert offsets
  289. * to page indexes themselves
  290. */
  291. int filemap_fdatawait_range(struct address_space *mapping, loff_t start,
  292. loff_t end)
  293. {
  294. return wait_on_page_writeback_range(mapping, start >> PAGE_CACHE_SHIFT,
  295. end >> PAGE_CACHE_SHIFT);
  296. }
  297. EXPORT_SYMBOL(filemap_fdatawait_range);
  298. /**
  299. * filemap_fdatawait - wait for all under-writeback pages to complete
  300. * @mapping: address space structure to wait for
  301. *
  302. * Walk the list of under-writeback pages of the given address space
  303. * and wait for all of them.
  304. */
  305. int filemap_fdatawait(struct address_space *mapping)
  306. {
  307. loff_t i_size = i_size_read(mapping->host);
  308. if (i_size == 0)
  309. return 0;
  310. return wait_on_page_writeback_range(mapping, 0,
  311. (i_size - 1) >> PAGE_CACHE_SHIFT);
  312. }
  313. EXPORT_SYMBOL(filemap_fdatawait);
  314. int filemap_write_and_wait(struct address_space *mapping)
  315. {
  316. int err = 0;
  317. if (mapping->nrpages) {
  318. err = filemap_fdatawrite(mapping);
  319. /*
  320. * Even if the above returned error, the pages may be
  321. * written partially (e.g. -ENOSPC), so we wait for it.
  322. * But the -EIO is special case, it may indicate the worst
  323. * thing (e.g. bug) happened, so we avoid waiting for it.
  324. */
  325. if (err != -EIO) {
  326. int err2 = filemap_fdatawait(mapping);
  327. if (!err)
  328. err = err2;
  329. }
  330. }
  331. return err;
  332. }
  333. EXPORT_SYMBOL(filemap_write_and_wait);
  334. /**
  335. * filemap_write_and_wait_range - write out & wait on a file range
  336. * @mapping: the address_space for the pages
  337. * @lstart: offset in bytes where the range starts
  338. * @lend: offset in bytes where the range ends (inclusive)
  339. *
  340. * Write out and wait upon file offsets lstart->lend, inclusive.
  341. *
  342. * Note that `lend' is inclusive (describes the last byte to be written) so
  343. * that this function can be used to write to the very end-of-file (end = -1).
  344. */
  345. int filemap_write_and_wait_range(struct address_space *mapping,
  346. loff_t lstart, loff_t lend)
  347. {
  348. int err = 0;
  349. if (mapping->nrpages) {
  350. err = __filemap_fdatawrite_range(mapping, lstart, lend,
  351. WB_SYNC_ALL);
  352. /* See comment of filemap_write_and_wait() */
  353. if (err != -EIO) {
  354. int err2 = wait_on_page_writeback_range(mapping,
  355. lstart >> PAGE_CACHE_SHIFT,
  356. lend >> PAGE_CACHE_SHIFT);
  357. if (!err)
  358. err = err2;
  359. }
  360. }
  361. return err;
  362. }
  363. EXPORT_SYMBOL(filemap_write_and_wait_range);
  364. /**
  365. * add_to_page_cache_locked - add a locked page to the pagecache
  366. * @page: page to add
  367. * @mapping: the page's address_space
  368. * @offset: page index
  369. * @gfp_mask: page allocation mode
  370. *
  371. * This function is used to add a page to the pagecache. It must be locked.
  372. * This function does not add the page to the LRU. The caller must do that.
  373. */
  374. int add_to_page_cache_locked(struct page *page, struct address_space *mapping,
  375. pgoff_t offset, gfp_t gfp_mask)
  376. {
  377. int error;
  378. VM_BUG_ON(!PageLocked(page));
  379. error = mem_cgroup_cache_charge(page, current->mm,
  380. gfp_mask & GFP_RECLAIM_MASK);
  381. if (error)
  382. goto out;
  383. error = radix_tree_preload(gfp_mask & ~__GFP_HIGHMEM);
  384. if (error == 0) {
  385. page_cache_get(page);
  386. page->mapping = mapping;
  387. page->index = offset;
  388. spin_lock_irq(&mapping->tree_lock);
  389. error = radix_tree_insert(&mapping->page_tree, offset, page);
  390. if (likely(!error)) {
  391. mapping->nrpages++;
  392. __inc_zone_page_state(page, NR_FILE_PAGES);
  393. if (PageSwapBacked(page))
  394. __inc_zone_page_state(page, NR_SHMEM);
  395. spin_unlock_irq(&mapping->tree_lock);
  396. } else {
  397. page->mapping = NULL;
  398. spin_unlock_irq(&mapping->tree_lock);
  399. mem_cgroup_uncharge_cache_page(page);
  400. page_cache_release(page);
  401. }
  402. radix_tree_preload_end();
  403. } else
  404. mem_cgroup_uncharge_cache_page(page);
  405. out:
  406. return error;
  407. }
  408. EXPORT_SYMBOL(add_to_page_cache_locked);
  409. int add_to_page_cache_lru(struct page *page, struct address_space *mapping,
  410. pgoff_t offset, gfp_t gfp_mask)
  411. {
  412. int ret;
  413. /*
  414. * Splice_read and readahead add shmem/tmpfs pages into the page cache
  415. * before shmem_readpage has a chance to mark them as SwapBacked: they
  416. * need to go on the active_anon lru below, and mem_cgroup_cache_charge
  417. * (called in add_to_page_cache) needs to know where they're going too.
  418. */
  419. if (mapping_cap_swap_backed(mapping))
  420. SetPageSwapBacked(page);
  421. ret = add_to_page_cache(page, mapping, offset, gfp_mask);
  422. if (ret == 0) {
  423. if (page_is_file_cache(page))
  424. lru_cache_add_file(page);
  425. else
  426. lru_cache_add_active_anon(page);
  427. }
  428. return ret;
  429. }
  430. EXPORT_SYMBOL_GPL(add_to_page_cache_lru);
  431. #ifdef CONFIG_NUMA
  432. struct page *__page_cache_alloc(gfp_t gfp)
  433. {
  434. if (cpuset_do_page_mem_spread()) {
  435. int n = cpuset_mem_spread_node();
  436. return alloc_pages_exact_node(n, gfp, 0);
  437. }
  438. return alloc_pages(gfp, 0);
  439. }
  440. EXPORT_SYMBOL(__page_cache_alloc);
  441. #endif
  442. static int __sleep_on_page_lock(void *word)
  443. {
  444. io_schedule();
  445. return 0;
  446. }
  447. /*
  448. * In order to wait for pages to become available there must be
  449. * waitqueues associated with pages. By using a hash table of
  450. * waitqueues where the bucket discipline is to maintain all
  451. * waiters on the same queue and wake all when any of the pages
  452. * become available, and for the woken contexts to check to be
  453. * sure the appropriate page became available, this saves space
  454. * at a cost of "thundering herd" phenomena during rare hash
  455. * collisions.
  456. */
  457. static wait_queue_head_t *page_waitqueue(struct page *page)
  458. {
  459. const struct zone *zone = page_zone(page);
  460. return &zone->wait_table[hash_ptr(page, zone->wait_table_bits)];
  461. }
  462. static inline void wake_up_page(struct page *page, int bit)
  463. {
  464. __wake_up_bit(page_waitqueue(page), &page->flags, bit);
  465. }
  466. void wait_on_page_bit(struct page *page, int bit_nr)
  467. {
  468. DEFINE_WAIT_BIT(wait, &page->flags, bit_nr);
  469. if (test_bit(bit_nr, &page->flags))
  470. __wait_on_bit(page_waitqueue(page), &wait, sync_page,
  471. TASK_UNINTERRUPTIBLE);
  472. }
  473. EXPORT_SYMBOL(wait_on_page_bit);
  474. /**
  475. * add_page_wait_queue - Add an arbitrary waiter to a page's wait queue
  476. * @page: Page defining the wait queue of interest
  477. * @waiter: Waiter to add to the queue
  478. *
  479. * Add an arbitrary @waiter to the wait queue for the nominated @page.
  480. */
  481. void add_page_wait_queue(struct page *page, wait_queue_t *waiter)
  482. {
  483. wait_queue_head_t *q = page_waitqueue(page);
  484. unsigned long flags;
  485. spin_lock_irqsave(&q->lock, flags);
  486. __add_wait_queue(q, waiter);
  487. spin_unlock_irqrestore(&q->lock, flags);
  488. }
  489. EXPORT_SYMBOL_GPL(add_page_wait_queue);
  490. /**
  491. * unlock_page - unlock a locked page
  492. * @page: the page
  493. *
  494. * Unlocks the page and wakes up sleepers in ___wait_on_page_locked().
  495. * Also wakes sleepers in wait_on_page_writeback() because the wakeup
  496. * mechananism between PageLocked pages and PageWriteback pages is shared.
  497. * But that's OK - sleepers in wait_on_page_writeback() just go back to sleep.
  498. *
  499. * The mb is necessary to enforce ordering between the clear_bit and the read
  500. * of the waitqueue (to avoid SMP races with a parallel wait_on_page_locked()).
  501. */
  502. void unlock_page(struct page *page)
  503. {
  504. VM_BUG_ON(!PageLocked(page));
  505. clear_bit_unlock(PG_locked, &page->flags);
  506. smp_mb__after_clear_bit();
  507. wake_up_page(page, PG_locked);
  508. }
  509. EXPORT_SYMBOL(unlock_page);
  510. /**
  511. * end_page_writeback - end writeback against a page
  512. * @page: the page
  513. */
  514. void end_page_writeback(struct page *page)
  515. {
  516. if (TestClearPageReclaim(page))
  517. rotate_reclaimable_page(page);
  518. if (!test_clear_page_writeback(page))
  519. BUG();
  520. smp_mb__after_clear_bit();
  521. wake_up_page(page, PG_writeback);
  522. }
  523. EXPORT_SYMBOL(end_page_writeback);
  524. /**
  525. * __lock_page - get a lock on the page, assuming we need to sleep to get it
  526. * @page: the page to lock
  527. *
  528. * Ugly. Running sync_page() in state TASK_UNINTERRUPTIBLE is scary. If some
  529. * random driver's requestfn sets TASK_RUNNING, we could busywait. However
  530. * chances are that on the second loop, the block layer's plug list is empty,
  531. * so sync_page() will then return in state TASK_UNINTERRUPTIBLE.
  532. */
  533. void __lock_page(struct page *page)
  534. {
  535. DEFINE_WAIT_BIT(wait, &page->flags, PG_locked);
  536. __wait_on_bit_lock(page_waitqueue(page), &wait, sync_page,
  537. TASK_UNINTERRUPTIBLE);
  538. }
  539. EXPORT_SYMBOL(__lock_page);
  540. int __lock_page_killable(struct page *page)
  541. {
  542. DEFINE_WAIT_BIT(wait, &page->flags, PG_locked);
  543. return __wait_on_bit_lock(page_waitqueue(page), &wait,
  544. sync_page_killable, TASK_KILLABLE);
  545. }
  546. EXPORT_SYMBOL_GPL(__lock_page_killable);
  547. /**
  548. * __lock_page_nosync - get a lock on the page, without calling sync_page()
  549. * @page: the page to lock
  550. *
  551. * Variant of lock_page that does not require the caller to hold a reference
  552. * on the page's mapping.
  553. */
  554. void __lock_page_nosync(struct page *page)
  555. {
  556. DEFINE_WAIT_BIT(wait, &page->flags, PG_locked);
  557. __wait_on_bit_lock(page_waitqueue(page), &wait, __sleep_on_page_lock,
  558. TASK_UNINTERRUPTIBLE);
  559. }
  560. /**
  561. * find_get_page - find and get a page reference
  562. * @mapping: the address_space to search
  563. * @offset: the page index
  564. *
  565. * Is there a pagecache struct page at the given (mapping, offset) tuple?
  566. * If yes, increment its refcount and return it; if no, return NULL.
  567. */
  568. struct page *find_get_page(struct address_space *mapping, pgoff_t offset)
  569. {
  570. void **pagep;
  571. struct page *page;
  572. rcu_read_lock();
  573. repeat:
  574. page = NULL;
  575. pagep = radix_tree_lookup_slot(&mapping->page_tree, offset);
  576. if (pagep) {
  577. page = radix_tree_deref_slot(pagep);
  578. if (unlikely(!page || page == RADIX_TREE_RETRY))
  579. goto repeat;
  580. if (!page_cache_get_speculative(page))
  581. goto repeat;
  582. /*
  583. * Has the page moved?
  584. * This is part of the lockless pagecache protocol. See
  585. * include/linux/pagemap.h for details.
  586. */
  587. if (unlikely(page != *pagep)) {
  588. page_cache_release(page);
  589. goto repeat;
  590. }
  591. }
  592. rcu_read_unlock();
  593. return page;
  594. }
  595. EXPORT_SYMBOL(find_get_page);
  596. /**
  597. * find_lock_page - locate, pin and lock a pagecache page
  598. * @mapping: the address_space to search
  599. * @offset: the page index
  600. *
  601. * Locates the desired pagecache page, locks it, increments its reference
  602. * count and returns its address.
  603. *
  604. * Returns zero if the page was not present. find_lock_page() may sleep.
  605. */
  606. struct page *find_lock_page(struct address_space *mapping, pgoff_t offset)
  607. {
  608. struct page *page;
  609. repeat:
  610. page = find_get_page(mapping, offset);
  611. if (page) {
  612. lock_page(page);
  613. /* Has the page been truncated? */
  614. if (unlikely(page->mapping != mapping)) {
  615. unlock_page(page);
  616. page_cache_release(page);
  617. goto repeat;
  618. }
  619. VM_BUG_ON(page->index != offset);
  620. }
  621. return page;
  622. }
  623. EXPORT_SYMBOL(find_lock_page);
  624. /**
  625. * find_or_create_page - locate or add a pagecache page
  626. * @mapping: the page's address_space
  627. * @index: the page's index into the mapping
  628. * @gfp_mask: page allocation mode
  629. *
  630. * Locates a page in the pagecache. If the page is not present, a new page
  631. * is allocated using @gfp_mask and is added to the pagecache and to the VM's
  632. * LRU list. The returned page is locked and has its reference count
  633. * incremented.
  634. *
  635. * find_or_create_page() may sleep, even if @gfp_flags specifies an atomic
  636. * allocation!
  637. *
  638. * find_or_create_page() returns the desired page's address, or zero on
  639. * memory exhaustion.
  640. */
  641. struct page *find_or_create_page(struct address_space *mapping,
  642. pgoff_t index, gfp_t gfp_mask)
  643. {
  644. struct page *page;
  645. int err;
  646. repeat:
  647. page = find_lock_page(mapping, index);
  648. if (!page) {
  649. page = __page_cache_alloc(gfp_mask);
  650. if (!page)
  651. return NULL;
  652. /*
  653. * We want a regular kernel memory (not highmem or DMA etc)
  654. * allocation for the radix tree nodes, but we need to honour
  655. * the context-specific requirements the caller has asked for.
  656. * GFP_RECLAIM_MASK collects those requirements.
  657. */
  658. err = add_to_page_cache_lru(page, mapping, index,
  659. (gfp_mask & GFP_RECLAIM_MASK));
  660. if (unlikely(err)) {
  661. page_cache_release(page);
  662. page = NULL;
  663. if (err == -EEXIST)
  664. goto repeat;
  665. }
  666. }
  667. return page;
  668. }
  669. EXPORT_SYMBOL(find_or_create_page);
  670. /**
  671. * find_get_pages - gang pagecache lookup
  672. * @mapping: The address_space to search
  673. * @start: The starting page index
  674. * @nr_pages: The maximum number of pages
  675. * @pages: Where the resulting pages are placed
  676. *
  677. * find_get_pages() will search for and return a group of up to
  678. * @nr_pages pages in the mapping. The pages are placed at @pages.
  679. * find_get_pages() takes a reference against the returned pages.
  680. *
  681. * The search returns a group of mapping-contiguous pages with ascending
  682. * indexes. There may be holes in the indices due to not-present pages.
  683. *
  684. * find_get_pages() returns the number of pages which were found.
  685. */
  686. unsigned find_get_pages(struct address_space *mapping, pgoff_t start,
  687. unsigned int nr_pages, struct page **pages)
  688. {
  689. unsigned int i;
  690. unsigned int ret;
  691. unsigned int nr_found;
  692. rcu_read_lock();
  693. restart:
  694. nr_found = radix_tree_gang_lookup_slot(&mapping->page_tree,
  695. (void ***)pages, start, nr_pages);
  696. ret = 0;
  697. for (i = 0; i < nr_found; i++) {
  698. struct page *page;
  699. repeat:
  700. page = radix_tree_deref_slot((void **)pages[i]);
  701. if (unlikely(!page))
  702. continue;
  703. /*
  704. * this can only trigger if nr_found == 1, making livelock
  705. * a non issue.
  706. */
  707. if (unlikely(page == RADIX_TREE_RETRY))
  708. goto restart;
  709. if (!page_cache_get_speculative(page))
  710. goto repeat;
  711. /* Has the page moved? */
  712. if (unlikely(page != *((void **)pages[i]))) {
  713. page_cache_release(page);
  714. goto repeat;
  715. }
  716. pages[ret] = page;
  717. ret++;
  718. }
  719. rcu_read_unlock();
  720. return ret;
  721. }
  722. /**
  723. * find_get_pages_contig - gang contiguous pagecache lookup
  724. * @mapping: The address_space to search
  725. * @index: The starting page index
  726. * @nr_pages: The maximum number of pages
  727. * @pages: Where the resulting pages are placed
  728. *
  729. * find_get_pages_contig() works exactly like find_get_pages(), except
  730. * that the returned number of pages are guaranteed to be contiguous.
  731. *
  732. * find_get_pages_contig() returns the number of pages which were found.
  733. */
  734. unsigned find_get_pages_contig(struct address_space *mapping, pgoff_t index,
  735. unsigned int nr_pages, struct page **pages)
  736. {
  737. unsigned int i;
  738. unsigned int ret;
  739. unsigned int nr_found;
  740. rcu_read_lock();
  741. restart:
  742. nr_found = radix_tree_gang_lookup_slot(&mapping->page_tree,
  743. (void ***)pages, index, nr_pages);
  744. ret = 0;
  745. for (i = 0; i < nr_found; i++) {
  746. struct page *page;
  747. repeat:
  748. page = radix_tree_deref_slot((void **)pages[i]);
  749. if (unlikely(!page))
  750. continue;
  751. /*
  752. * this can only trigger if nr_found == 1, making livelock
  753. * a non issue.
  754. */
  755. if (unlikely(page == RADIX_TREE_RETRY))
  756. goto restart;
  757. if (page->mapping == NULL || page->index != index)
  758. break;
  759. if (!page_cache_get_speculative(page))
  760. goto repeat;
  761. /* Has the page moved? */
  762. if (unlikely(page != *((void **)pages[i]))) {
  763. page_cache_release(page);
  764. goto repeat;
  765. }
  766. pages[ret] = page;
  767. ret++;
  768. index++;
  769. }
  770. rcu_read_unlock();
  771. return ret;
  772. }
  773. EXPORT_SYMBOL(find_get_pages_contig);
  774. /**
  775. * find_get_pages_tag - find and return pages that match @tag
  776. * @mapping: the address_space to search
  777. * @index: the starting page index
  778. * @tag: the tag index
  779. * @nr_pages: the maximum number of pages
  780. * @pages: where the resulting pages are placed
  781. *
  782. * Like find_get_pages, except we only return pages which are tagged with
  783. * @tag. We update @index to index the next page for the traversal.
  784. */
  785. unsigned find_get_pages_tag(struct address_space *mapping, pgoff_t *index,
  786. int tag, unsigned int nr_pages, struct page **pages)
  787. {
  788. unsigned int i;
  789. unsigned int ret;
  790. unsigned int nr_found;
  791. rcu_read_lock();
  792. restart:
  793. nr_found = radix_tree_gang_lookup_tag_slot(&mapping->page_tree,
  794. (void ***)pages, *index, nr_pages, tag);
  795. ret = 0;
  796. for (i = 0; i < nr_found; i++) {
  797. struct page *page;
  798. repeat:
  799. page = radix_tree_deref_slot((void **)pages[i]);
  800. if (unlikely(!page))
  801. continue;
  802. /*
  803. * this can only trigger if nr_found == 1, making livelock
  804. * a non issue.
  805. */
  806. if (unlikely(page == RADIX_TREE_RETRY))
  807. goto restart;
  808. if (!page_cache_get_speculative(page))
  809. goto repeat;
  810. /* Has the page moved? */
  811. if (unlikely(page != *((void **)pages[i]))) {
  812. page_cache_release(page);
  813. goto repeat;
  814. }
  815. pages[ret] = page;
  816. ret++;
  817. }
  818. rcu_read_unlock();
  819. if (ret)
  820. *index = pages[ret - 1]->index + 1;
  821. return ret;
  822. }
  823. EXPORT_SYMBOL(find_get_pages_tag);
  824. /**
  825. * grab_cache_page_nowait - returns locked page at given index in given cache
  826. * @mapping: target address_space
  827. * @index: the page index
  828. *
  829. * Same as grab_cache_page(), but do not wait if the page is unavailable.
  830. * This is intended for speculative data generators, where the data can
  831. * be regenerated if the page couldn't be grabbed. This routine should
  832. * be safe to call while holding the lock for another page.
  833. *
  834. * Clear __GFP_FS when allocating the page to avoid recursion into the fs
  835. * and deadlock against the caller's locked page.
  836. */
  837. struct page *
  838. grab_cache_page_nowait(struct address_space *mapping, pgoff_t index)
  839. {
  840. struct page *page = find_get_page(mapping, index);
  841. if (page) {
  842. if (trylock_page(page))
  843. return page;
  844. page_cache_release(page);
  845. return NULL;
  846. }
  847. page = __page_cache_alloc(mapping_gfp_mask(mapping) & ~__GFP_FS);
  848. if (page && add_to_page_cache_lru(page, mapping, index, GFP_NOFS)) {
  849. page_cache_release(page);
  850. page = NULL;
  851. }
  852. return page;
  853. }
  854. EXPORT_SYMBOL(grab_cache_page_nowait);
  855. /*
  856. * CD/DVDs are error prone. When a medium error occurs, the driver may fail
  857. * a _large_ part of the i/o request. Imagine the worst scenario:
  858. *
  859. * ---R__________________________________________B__________
  860. * ^ reading here ^ bad block(assume 4k)
  861. *
  862. * read(R) => miss => readahead(R...B) => media error => frustrating retries
  863. * => failing the whole request => read(R) => read(R+1) =>
  864. * readahead(R+1...B+1) => bang => read(R+2) => read(R+3) =>
  865. * readahead(R+3...B+2) => bang => read(R+3) => read(R+4) =>
  866. * readahead(R+4...B+3) => bang => read(R+4) => read(R+5) => ......
  867. *
  868. * It is going insane. Fix it by quickly scaling down the readahead size.
  869. */
  870. static void shrink_readahead_size_eio(struct file *filp,
  871. struct file_ra_state *ra)
  872. {
  873. ra->ra_pages /= 4;
  874. }
  875. /**
  876. * do_generic_file_read - generic file read routine
  877. * @filp: the file to read
  878. * @ppos: current file position
  879. * @desc: read_descriptor
  880. * @actor: read method
  881. *
  882. * This is a generic file read routine, and uses the
  883. * mapping->a_ops->readpage() function for the actual low-level stuff.
  884. *
  885. * This is really ugly. But the goto's actually try to clarify some
  886. * of the logic when it comes to error handling etc.
  887. */
  888. static void do_generic_file_read(struct file *filp, loff_t *ppos,
  889. read_descriptor_t *desc, read_actor_t actor)
  890. {
  891. struct address_space *mapping = filp->f_mapping;
  892. struct inode *inode = mapping->host;
  893. struct file_ra_state *ra = &filp->f_ra;
  894. pgoff_t index;
  895. pgoff_t last_index;
  896. pgoff_t prev_index;
  897. unsigned long offset; /* offset into pagecache page */
  898. unsigned int prev_offset;
  899. int error;
  900. index = *ppos >> PAGE_CACHE_SHIFT;
  901. prev_index = ra->prev_pos >> PAGE_CACHE_SHIFT;
  902. prev_offset = ra->prev_pos & (PAGE_CACHE_SIZE-1);
  903. last_index = (*ppos + desc->count + PAGE_CACHE_SIZE-1) >> PAGE_CACHE_SHIFT;
  904. offset = *ppos & ~PAGE_CACHE_MASK;
  905. for (;;) {
  906. struct page *page;
  907. pgoff_t end_index;
  908. loff_t isize;
  909. unsigned long nr, ret;
  910. cond_resched();
  911. find_page:
  912. page = find_get_page(mapping, index);
  913. if (!page) {
  914. page_cache_sync_readahead(mapping,
  915. ra, filp,
  916. index, last_index - index);
  917. page = find_get_page(mapping, index);
  918. if (unlikely(page == NULL))
  919. goto no_cached_page;
  920. }
  921. if (PageReadahead(page)) {
  922. page_cache_async_readahead(mapping,
  923. ra, filp, page,
  924. index, last_index - index);
  925. }
  926. if (!PageUptodate(page)) {
  927. if (inode->i_blkbits == PAGE_CACHE_SHIFT ||
  928. !mapping->a_ops->is_partially_uptodate)
  929. goto page_not_up_to_date;
  930. if (!trylock_page(page))
  931. goto page_not_up_to_date;
  932. if (!mapping->a_ops->is_partially_uptodate(page,
  933. desc, offset))
  934. goto page_not_up_to_date_locked;
  935. unlock_page(page);
  936. }
  937. page_ok:
  938. /*
  939. * i_size must be checked after we know the page is Uptodate.
  940. *
  941. * Checking i_size after the check allows us to calculate
  942. * the correct value for "nr", which means the zero-filled
  943. * part of the page is not copied back to userspace (unless
  944. * another truncate extends the file - this is desired though).
  945. */
  946. isize = i_size_read(inode);
  947. end_index = (isize - 1) >> PAGE_CACHE_SHIFT;
  948. if (unlikely(!isize || index > end_index)) {
  949. page_cache_release(page);
  950. goto out;
  951. }
  952. /* nr is the maximum number of bytes to copy from this page */
  953. nr = PAGE_CACHE_SIZE;
  954. if (index == end_index) {
  955. nr = ((isize - 1) & ~PAGE_CACHE_MASK) + 1;
  956. if (nr <= offset) {
  957. page_cache_release(page);
  958. goto out;
  959. }
  960. }
  961. nr = nr - offset;
  962. /* If users can be writing to this page using arbitrary
  963. * virtual addresses, take care about potential aliasing
  964. * before reading the page on the kernel side.
  965. */
  966. if (mapping_writably_mapped(mapping))
  967. flush_dcache_page(page);
  968. /*
  969. * When a sequential read accesses a page several times,
  970. * only mark it as accessed the first time.
  971. */
  972. if (prev_index != index || offset != prev_offset)
  973. mark_page_accessed(page);
  974. prev_index = index;
  975. /*
  976. * Ok, we have the page, and it's up-to-date, so
  977. * now we can copy it to user space...
  978. *
  979. * The actor routine returns how many bytes were actually used..
  980. * NOTE! This may not be the same as how much of a user buffer
  981. * we filled up (we may be padding etc), so we can only update
  982. * "pos" here (the actor routine has to update the user buffer
  983. * pointers and the remaining count).
  984. */
  985. ret = actor(desc, page, offset, nr);
  986. offset += ret;
  987. index += offset >> PAGE_CACHE_SHIFT;
  988. offset &= ~PAGE_CACHE_MASK;
  989. prev_offset = offset;
  990. page_cache_release(page);
  991. if (ret == nr && desc->count)
  992. continue;
  993. goto out;
  994. page_not_up_to_date:
  995. /* Get exclusive access to the page ... */
  996. error = lock_page_killable(page);
  997. if (unlikely(error))
  998. goto readpage_error;
  999. page_not_up_to_date_locked:
  1000. /* Did it get truncated before we got the lock? */
  1001. if (!page->mapping) {
  1002. unlock_page(page);
  1003. page_cache_release(page);
  1004. continue;
  1005. }
  1006. /* Did somebody else fill it already? */
  1007. if (PageUptodate(page)) {
  1008. unlock_page(page);
  1009. goto page_ok;
  1010. }
  1011. readpage:
  1012. /* Start the actual read. The read will unlock the page. */
  1013. error = mapping->a_ops->readpage(filp, page);
  1014. if (unlikely(error)) {
  1015. if (error == AOP_TRUNCATED_PAGE) {
  1016. page_cache_release(page);
  1017. goto find_page;
  1018. }
  1019. goto readpage_error;
  1020. }
  1021. if (!PageUptodate(page)) {
  1022. error = lock_page_killable(page);
  1023. if (unlikely(error))
  1024. goto readpage_error;
  1025. if (!PageUptodate(page)) {
  1026. if (page->mapping == NULL) {
  1027. /*
  1028. * invalidate_inode_pages got it
  1029. */
  1030. unlock_page(page);
  1031. page_cache_release(page);
  1032. goto find_page;
  1033. }
  1034. unlock_page(page);
  1035. shrink_readahead_size_eio(filp, ra);
  1036. error = -EIO;
  1037. goto readpage_error;
  1038. }
  1039. unlock_page(page);
  1040. }
  1041. goto page_ok;
  1042. readpage_error:
  1043. /* UHHUH! A synchronous read error occurred. Report it */
  1044. desc->error = error;
  1045. page_cache_release(page);
  1046. goto out;
  1047. no_cached_page:
  1048. /*
  1049. * Ok, it wasn't cached, so we need to create a new
  1050. * page..
  1051. */
  1052. page = page_cache_alloc_cold(mapping);
  1053. if (!page) {
  1054. desc->error = -ENOMEM;
  1055. goto out;
  1056. }
  1057. error = add_to_page_cache_lru(page, mapping,
  1058. index, GFP_KERNEL);
  1059. if (error) {
  1060. page_cache_release(page);
  1061. if (error == -EEXIST)
  1062. goto find_page;
  1063. desc->error = error;
  1064. goto out;
  1065. }
  1066. goto readpage;
  1067. }
  1068. out:
  1069. ra->prev_pos = prev_index;
  1070. ra->prev_pos <<= PAGE_CACHE_SHIFT;
  1071. ra->prev_pos |= prev_offset;
  1072. *ppos = ((loff_t)index << PAGE_CACHE_SHIFT) + offset;
  1073. file_accessed(filp);
  1074. }
  1075. int file_read_actor(read_descriptor_t *desc, struct page *page,
  1076. unsigned long offset, unsigned long size)
  1077. {
  1078. char *kaddr;
  1079. unsigned long left, count = desc->count;
  1080. if (size > count)
  1081. size = count;
  1082. /*
  1083. * Faults on the destination of a read are common, so do it before
  1084. * taking the kmap.
  1085. */
  1086. if (!fault_in_pages_writeable(desc->arg.buf, size)) {
  1087. kaddr = kmap_atomic(page, KM_USER0);
  1088. left = __copy_to_user_inatomic(desc->arg.buf,
  1089. kaddr + offset, size);
  1090. kunmap_atomic(kaddr, KM_USER0);
  1091. if (left == 0)
  1092. goto success;
  1093. }
  1094. /* Do it the slow way */
  1095. kaddr = kmap(page);
  1096. left = __copy_to_user(desc->arg.buf, kaddr + offset, size);
  1097. kunmap(page);
  1098. if (left) {
  1099. size -= left;
  1100. desc->error = -EFAULT;
  1101. }
  1102. success:
  1103. desc->count = count - size;
  1104. desc->written += size;
  1105. desc->arg.buf += size;
  1106. return size;
  1107. }
  1108. /*
  1109. * Performs necessary checks before doing a write
  1110. * @iov: io vector request
  1111. * @nr_segs: number of segments in the iovec
  1112. * @count: number of bytes to write
  1113. * @access_flags: type of access: %VERIFY_READ or %VERIFY_WRITE
  1114. *
  1115. * Adjust number of segments and amount of bytes to write (nr_segs should be
  1116. * properly initialized first). Returns appropriate error code that caller
  1117. * should return or zero in case that write should be allowed.
  1118. */
  1119. int generic_segment_checks(const struct iovec *iov,
  1120. unsigned long *nr_segs, size_t *count, int access_flags)
  1121. {
  1122. unsigned long seg;
  1123. size_t cnt = 0;
  1124. for (seg = 0; seg < *nr_segs; seg++) {
  1125. const struct iovec *iv = &iov[seg];
  1126. /*
  1127. * If any segment has a negative length, or the cumulative
  1128. * length ever wraps negative then return -EINVAL.
  1129. */
  1130. cnt += iv->iov_len;
  1131. if (unlikely((ssize_t)(cnt|iv->iov_len) < 0))
  1132. return -EINVAL;
  1133. if (access_ok(access_flags, iv->iov_base, iv->iov_len))
  1134. continue;
  1135. if (seg == 0)
  1136. return -EFAULT;
  1137. *nr_segs = seg;
  1138. cnt -= iv->iov_len; /* This segment is no good */
  1139. break;
  1140. }
  1141. *count = cnt;
  1142. return 0;
  1143. }
  1144. EXPORT_SYMBOL(generic_segment_checks);
  1145. /**
  1146. * generic_file_aio_read - generic filesystem read routine
  1147. * @iocb: kernel I/O control block
  1148. * @iov: io vector request
  1149. * @nr_segs: number of segments in the iovec
  1150. * @pos: current file position
  1151. *
  1152. * This is the "read()" routine for all filesystems
  1153. * that can use the page cache directly.
  1154. */
  1155. ssize_t
  1156. generic_file_aio_read(struct kiocb *iocb, const struct iovec *iov,
  1157. unsigned long nr_segs, loff_t pos)
  1158. {
  1159. struct file *filp = iocb->ki_filp;
  1160. ssize_t retval;
  1161. unsigned long seg;
  1162. size_t count;
  1163. loff_t *ppos = &iocb->ki_pos;
  1164. count = 0;
  1165. retval = generic_segment_checks(iov, &nr_segs, &count, VERIFY_WRITE);
  1166. if (retval)
  1167. return retval;
  1168. /* coalesce the iovecs and go direct-to-BIO for O_DIRECT */
  1169. if (filp->f_flags & O_DIRECT) {
  1170. loff_t size;
  1171. struct address_space *mapping;
  1172. struct inode *inode;
  1173. mapping = filp->f_mapping;
  1174. inode = mapping->host;
  1175. if (!count)
  1176. goto out; /* skip atime */
  1177. size = i_size_read(inode);
  1178. if (pos < size) {
  1179. retval = filemap_write_and_wait_range(mapping, pos,
  1180. pos + iov_length(iov, nr_segs) - 1);
  1181. if (!retval) {
  1182. retval = mapping->a_ops->direct_IO(READ, iocb,
  1183. iov, pos, nr_segs);
  1184. }
  1185. if (retval > 0)
  1186. *ppos = pos + retval;
  1187. if (retval) {
  1188. file_accessed(filp);
  1189. goto out;
  1190. }
  1191. }
  1192. }
  1193. for (seg = 0; seg < nr_segs; seg++) {
  1194. read_descriptor_t desc;
  1195. desc.written = 0;
  1196. desc.arg.buf = iov[seg].iov_base;
  1197. desc.count = iov[seg].iov_len;
  1198. if (desc.count == 0)
  1199. continue;
  1200. desc.error = 0;
  1201. do_generic_file_read(filp, ppos, &desc, file_read_actor);
  1202. retval += desc.written;
  1203. if (desc.error) {
  1204. retval = retval ?: desc.error;
  1205. break;
  1206. }
  1207. if (desc.count > 0)
  1208. break;
  1209. }
  1210. out:
  1211. return retval;
  1212. }
  1213. EXPORT_SYMBOL(generic_file_aio_read);
  1214. static ssize_t
  1215. do_readahead(struct address_space *mapping, struct file *filp,
  1216. pgoff_t index, unsigned long nr)
  1217. {
  1218. if (!mapping || !mapping->a_ops || !mapping->a_ops->readpage)
  1219. return -EINVAL;
  1220. force_page_cache_readahead(mapping, filp, index, nr);
  1221. return 0;
  1222. }
  1223. SYSCALL_DEFINE(readahead)(int fd, loff_t offset, size_t count)
  1224. {
  1225. ssize_t ret;
  1226. struct file *file;
  1227. ret = -EBADF;
  1228. file = fget(fd);
  1229. if (file) {
  1230. if (file->f_mode & FMODE_READ) {
  1231. struct address_space *mapping = file->f_mapping;
  1232. pgoff_t start = offset >> PAGE_CACHE_SHIFT;
  1233. pgoff_t end = (offset + count - 1) >> PAGE_CACHE_SHIFT;
  1234. unsigned long len = end - start + 1;
  1235. ret = do_readahead(mapping, file, start, len);
  1236. }
  1237. fput(file);
  1238. }
  1239. return ret;
  1240. }
  1241. #ifdef CONFIG_HAVE_SYSCALL_WRAPPERS
  1242. asmlinkage long SyS_readahead(long fd, loff_t offset, long count)
  1243. {
  1244. return SYSC_readahead((int) fd, offset, (size_t) count);
  1245. }
  1246. SYSCALL_ALIAS(sys_readahead, SyS_readahead);
  1247. #endif
  1248. #ifdef CONFIG_MMU
  1249. /**
  1250. * page_cache_read - adds requested page to the page cache if not already there
  1251. * @file: file to read
  1252. * @offset: page index
  1253. *
  1254. * This adds the requested page to the page cache if it isn't already there,
  1255. * and schedules an I/O to read in its contents from disk.
  1256. */
  1257. static int page_cache_read(struct file *file, pgoff_t offset)
  1258. {
  1259. struct address_space *mapping = file->f_mapping;
  1260. struct page *page;
  1261. int ret;
  1262. do {
  1263. page = page_cache_alloc_cold(mapping);
  1264. if (!page)
  1265. return -ENOMEM;
  1266. ret = add_to_page_cache_lru(page, mapping, offset, GFP_KERNEL);
  1267. if (ret == 0)
  1268. ret = mapping->a_ops->readpage(file, page);
  1269. else if (ret == -EEXIST)
  1270. ret = 0; /* losing race to add is OK */
  1271. page_cache_release(page);
  1272. } while (ret == AOP_TRUNCATED_PAGE);
  1273. return ret;
  1274. }
  1275. #define MMAP_LOTSAMISS (100)
  1276. /*
  1277. * Synchronous readahead happens when we don't even find
  1278. * a page in the page cache at all.
  1279. */
  1280. static void do_sync_mmap_readahead(struct vm_area_struct *vma,
  1281. struct file_ra_state *ra,
  1282. struct file *file,
  1283. pgoff_t offset)
  1284. {
  1285. unsigned long ra_pages;
  1286. struct address_space *mapping = file->f_mapping;
  1287. /* If we don't want any read-ahead, don't bother */
  1288. if (VM_RandomReadHint(vma))
  1289. return;
  1290. if (VM_SequentialReadHint(vma) ||
  1291. offset - 1 == (ra->prev_pos >> PAGE_CACHE_SHIFT)) {
  1292. page_cache_sync_readahead(mapping, ra, file, offset,
  1293. ra->ra_pages);
  1294. return;
  1295. }
  1296. if (ra->mmap_miss < INT_MAX)
  1297. ra->mmap_miss++;
  1298. /*
  1299. * Do we miss much more than hit in this file? If so,
  1300. * stop bothering with read-ahead. It will only hurt.
  1301. */
  1302. if (ra->mmap_miss > MMAP_LOTSAMISS)
  1303. return;
  1304. /*
  1305. * mmap read-around
  1306. */
  1307. ra_pages = max_sane_readahead(ra->ra_pages);
  1308. if (ra_pages) {
  1309. ra->start = max_t(long, 0, offset - ra_pages/2);
  1310. ra->size = ra_pages;
  1311. ra->async_size = 0;
  1312. ra_submit(ra, mapping, file);
  1313. }
  1314. }
  1315. /*
  1316. * Asynchronous readahead happens when we find the page and PG_readahead,
  1317. * so we want to possibly extend the readahead further..
  1318. */
  1319. static void do_async_mmap_readahead(struct vm_area_struct *vma,
  1320. struct file_ra_state *ra,
  1321. struct file *file,
  1322. struct page *page,
  1323. pgoff_t offset)
  1324. {
  1325. struct address_space *mapping = file->f_mapping;
  1326. /* If we don't want any read-ahead, don't bother */
  1327. if (VM_RandomReadHint(vma))
  1328. return;
  1329. if (ra->mmap_miss > 0)
  1330. ra->mmap_miss--;
  1331. if (PageReadahead(page))
  1332. page_cache_async_readahead(mapping, ra, file,
  1333. page, offset, ra->ra_pages);
  1334. }
  1335. /**
  1336. * filemap_fault - read in file data for page fault handling
  1337. * @vma: vma in which the fault was taken
  1338. * @vmf: struct vm_fault containing details of the fault
  1339. *
  1340. * filemap_fault() is invoked via the vma operations vector for a
  1341. * mapped memory region to read in file data during a page fault.
  1342. *
  1343. * The goto's are kind of ugly, but this streamlines the normal case of having
  1344. * it in the page cache, and handles the special cases reasonably without
  1345. * having a lot of duplicated code.
  1346. */
  1347. int filemap_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
  1348. {
  1349. int error;
  1350. struct file *file = vma->vm_file;
  1351. struct address_space *mapping = file->f_mapping;
  1352. struct file_ra_state *ra = &file->f_ra;
  1353. struct inode *inode = mapping->host;
  1354. pgoff_t offset = vmf->pgoff;
  1355. struct page *page;
  1356. pgoff_t size;
  1357. int ret = 0;
  1358. size = (i_size_read(inode) + PAGE_CACHE_SIZE - 1) >> PAGE_CACHE_SHIFT;
  1359. if (offset >= size)
  1360. return VM_FAULT_SIGBUS;
  1361. /*
  1362. * Do we have something in the page cache already?
  1363. */
  1364. page = find_get_page(mapping, offset);
  1365. if (likely(page)) {
  1366. /*
  1367. * We found the page, so try async readahead before
  1368. * waiting for the lock.
  1369. */
  1370. do_async_mmap_readahead(vma, ra, file, page, offset);
  1371. lock_page(page);
  1372. /* Did it get truncated? */
  1373. if (unlikely(page->mapping != mapping)) {
  1374. unlock_page(page);
  1375. put_page(page);
  1376. goto no_cached_page;
  1377. }
  1378. } else {
  1379. /* No page in the page cache at all */
  1380. do_sync_mmap_readahead(vma, ra, file, offset);
  1381. count_vm_event(PGMAJFAULT);
  1382. ret = VM_FAULT_MAJOR;
  1383. retry_find:
  1384. page = find_lock_page(mapping, offset);
  1385. if (!page)
  1386. goto no_cached_page;
  1387. }
  1388. /*
  1389. * We have a locked page in the page cache, now we need to check
  1390. * that it's up-to-date. If not, it is going to be due to an error.
  1391. */
  1392. if (unlikely(!PageUptodate(page)))
  1393. goto page_not_uptodate;
  1394. /*
  1395. * Found the page and have a reference on it.
  1396. * We must recheck i_size under page lock.
  1397. */
  1398. size = (i_size_read(inode) + PAGE_CACHE_SIZE - 1) >> PAGE_CACHE_SHIFT;
  1399. if (unlikely(offset >= size)) {
  1400. unlock_page(page);
  1401. page_cache_release(page);
  1402. return VM_FAULT_SIGBUS;
  1403. }
  1404. ra->prev_pos = (loff_t)offset << PAGE_CACHE_SHIFT;
  1405. vmf->page = page;
  1406. return ret | VM_FAULT_LOCKED;
  1407. no_cached_page:
  1408. /*
  1409. * We're only likely to ever get here if MADV_RANDOM is in
  1410. * effect.
  1411. */
  1412. error = page_cache_read(file, offset);
  1413. /*
  1414. * The page we want has now been added to the page cache.
  1415. * In the unlikely event that someone removed it in the
  1416. * meantime, we'll just come back here and read it again.
  1417. */
  1418. if (error >= 0)
  1419. goto retry_find;
  1420. /*
  1421. * An error return from page_cache_read can result if the
  1422. * system is low on memory, or a problem occurs while trying
  1423. * to schedule I/O.
  1424. */
  1425. if (error == -ENOMEM)
  1426. return VM_FAULT_OOM;
  1427. return VM_FAULT_SIGBUS;
  1428. page_not_uptodate:
  1429. /*
  1430. * Umm, take care of errors if the page isn't up-to-date.
  1431. * Try to re-read it _once_. We do this synchronously,
  1432. * because there really aren't any performance issues here
  1433. * and we need to check for errors.
  1434. */
  1435. ClearPageError(page);
  1436. error = mapping->a_ops->readpage(file, page);
  1437. if (!error) {
  1438. wait_on_page_locked(page);
  1439. if (!PageUptodate(page))
  1440. error = -EIO;
  1441. }
  1442. page_cache_release(page);
  1443. if (!error || error == AOP_TRUNCATED_PAGE)
  1444. goto retry_find;
  1445. /* Things didn't work out. Return zero to tell the mm layer so. */
  1446. shrink_readahead_size_eio(file, ra);
  1447. return VM_FAULT_SIGBUS;
  1448. }
  1449. EXPORT_SYMBOL(filemap_fault);
  1450. struct vm_operations_struct generic_file_vm_ops = {
  1451. .fault = filemap_fault,
  1452. };
  1453. /* This is used for a general mmap of a disk file */
  1454. int generic_file_mmap(struct file * file, struct vm_area_struct * vma)
  1455. {
  1456. struct address_space *mapping = file->f_mapping;
  1457. if (!mapping->a_ops->readpage)
  1458. return -ENOEXEC;
  1459. file_accessed(file);
  1460. vma->vm_ops = &generic_file_vm_ops;
  1461. vma->vm_flags |= VM_CAN_NONLINEAR;
  1462. return 0;
  1463. }
  1464. /*
  1465. * This is for filesystems which do not implement ->writepage.
  1466. */
  1467. int generic_file_readonly_mmap(struct file *file, struct vm_area_struct *vma)
  1468. {
  1469. if ((vma->vm_flags & VM_SHARED) && (vma->vm_flags & VM_MAYWRITE))
  1470. return -EINVAL;
  1471. return generic_file_mmap(file, vma);
  1472. }
  1473. #else
  1474. int generic_file_mmap(struct file * file, struct vm_area_struct * vma)
  1475. {
  1476. return -ENOSYS;
  1477. }
  1478. int generic_file_readonly_mmap(struct file * file, struct vm_area_struct * vma)
  1479. {
  1480. return -ENOSYS;
  1481. }
  1482. #endif /* CONFIG_MMU */
  1483. EXPORT_SYMBOL(generic_file_mmap);
  1484. EXPORT_SYMBOL(generic_file_readonly_mmap);
  1485. static struct page *__read_cache_page(struct address_space *mapping,
  1486. pgoff_t index,
  1487. int (*filler)(void *,struct page*),
  1488. void *data)
  1489. {
  1490. struct page *page;
  1491. int err;
  1492. repeat:
  1493. page = find_get_page(mapping, index);
  1494. if (!page) {
  1495. page = page_cache_alloc_cold(mapping);
  1496. if (!page)
  1497. return ERR_PTR(-ENOMEM);
  1498. err = add_to_page_cache_lru(page, mapping, index, GFP_KERNEL);
  1499. if (unlikely(err)) {
  1500. page_cache_release(page);
  1501. if (err == -EEXIST)
  1502. goto repeat;
  1503. /* Presumably ENOMEM for radix tree node */
  1504. return ERR_PTR(err);
  1505. }
  1506. err = filler(data, page);
  1507. if (err < 0) {
  1508. page_cache_release(page);
  1509. page = ERR_PTR(err);
  1510. }
  1511. }
  1512. return page;
  1513. }
  1514. /**
  1515. * read_cache_page_async - read into page cache, fill it if needed
  1516. * @mapping: the page's address_space
  1517. * @index: the page index
  1518. * @filler: function to perform the read
  1519. * @data: destination for read data
  1520. *
  1521. * Same as read_cache_page, but don't wait for page to become unlocked
  1522. * after submitting it to the filler.
  1523. *
  1524. * Read into the page cache. If a page already exists, and PageUptodate() is
  1525. * not set, try to fill the page but don't wait for it to become unlocked.
  1526. *
  1527. * If the page does not get brought uptodate, return -EIO.
  1528. */
  1529. struct page *read_cache_page_async(struct address_space *mapping,
  1530. pgoff_t index,
  1531. int (*filler)(void *,struct page*),
  1532. void *data)
  1533. {
  1534. struct page *page;
  1535. int err;
  1536. retry:
  1537. page = __read_cache_page(mapping, index, filler, data);
  1538. if (IS_ERR(page))
  1539. return page;
  1540. if (PageUptodate(page))
  1541. goto out;
  1542. lock_page(page);
  1543. if (!page->mapping) {
  1544. unlock_page(page);
  1545. page_cache_release(page);
  1546. goto retry;
  1547. }
  1548. if (PageUptodate(page)) {
  1549. unlock_page(page);
  1550. goto out;
  1551. }
  1552. err = filler(data, page);
  1553. if (err < 0) {
  1554. page_cache_release(page);
  1555. return ERR_PTR(err);
  1556. }
  1557. out:
  1558. mark_page_accessed(page);
  1559. return page;
  1560. }
  1561. EXPORT_SYMBOL(read_cache_page_async);
  1562. /**
  1563. * read_cache_page - read into page cache, fill it if needed
  1564. * @mapping: the page's address_space
  1565. * @index: the page index
  1566. * @filler: function to perform the read
  1567. * @data: destination for read data
  1568. *
  1569. * Read into the page cache. If a page already exists, and PageUptodate() is
  1570. * not set, try to fill the page then wait for it to become unlocked.
  1571. *
  1572. * If the page does not get brought uptodate, return -EIO.
  1573. */
  1574. struct page *read_cache_page(struct address_space *mapping,
  1575. pgoff_t index,
  1576. int (*filler)(void *,struct page*),
  1577. void *data)
  1578. {
  1579. struct page *page;
  1580. page = read_cache_page_async(mapping, index, filler, data);
  1581. if (IS_ERR(page))
  1582. goto out;
  1583. wait_on_page_locked(page);
  1584. if (!PageUptodate(page)) {
  1585. page_cache_release(page);
  1586. page = ERR_PTR(-EIO);
  1587. }
  1588. out:
  1589. return page;
  1590. }
  1591. EXPORT_SYMBOL(read_cache_page);
  1592. /*
  1593. * The logic we want is
  1594. *
  1595. * if suid or (sgid and xgrp)
  1596. * remove privs
  1597. */
  1598. int should_remove_suid(struct dentry *dentry)
  1599. {
  1600. mode_t mode = dentry->d_inode->i_mode;
  1601. int kill = 0;
  1602. /* suid always must be killed */
  1603. if (unlikely(mode & S_ISUID))
  1604. kill = ATTR_KILL_SUID;
  1605. /*
  1606. * sgid without any exec bits is just a mandatory locking mark; leave
  1607. * it alone. If some exec bits are set, it's a real sgid; kill it.
  1608. */
  1609. if (unlikely((mode & S_ISGID) && (mode & S_IXGRP)))
  1610. kill |= ATTR_KILL_SGID;
  1611. if (unlikely(kill && !capable(CAP_FSETID) && S_ISREG(mode)))
  1612. return kill;
  1613. return 0;
  1614. }
  1615. EXPORT_SYMBOL(should_remove_suid);
  1616. static int __remove_suid(struct dentry *dentry, int kill)
  1617. {
  1618. struct iattr newattrs;
  1619. newattrs.ia_valid = ATTR_FORCE | kill;
  1620. return notify_change(dentry, &newattrs);
  1621. }
  1622. int file_remove_suid(struct file *file)
  1623. {
  1624. struct dentry *dentry = file->f_path.dentry;
  1625. int killsuid = should_remove_suid(dentry);
  1626. int killpriv = security_inode_need_killpriv(dentry);
  1627. int error = 0;
  1628. if (killpriv < 0)
  1629. return killpriv;
  1630. if (killpriv)
  1631. error = security_inode_killpriv(dentry);
  1632. if (!error && killsuid)
  1633. error = __remove_suid(dentry, killsuid);
  1634. return error;
  1635. }
  1636. EXPORT_SYMBOL(file_remove_suid);
  1637. static size_t __iovec_copy_from_user_inatomic(char *vaddr,
  1638. const struct iovec *iov, size_t base, size_t bytes)
  1639. {
  1640. size_t copied = 0, left = 0;
  1641. while (bytes) {
  1642. char __user *buf = iov->iov_base + base;
  1643. int copy = min(bytes, iov->iov_len - base);
  1644. base = 0;
  1645. left = __copy_from_user_inatomic(vaddr, buf, copy);
  1646. copied += copy;
  1647. bytes -= copy;
  1648. vaddr += copy;
  1649. iov++;
  1650. if (unlikely(left))
  1651. break;
  1652. }
  1653. return copied - left;
  1654. }
  1655. /*
  1656. * Copy as much as we can into the page and return the number of bytes which
  1657. * were sucessfully copied. If a fault is encountered then return the number of
  1658. * bytes which were copied.
  1659. */
  1660. size_t iov_iter_copy_from_user_atomic(struct page *page,
  1661. struct iov_iter *i, unsigned long offset, size_t bytes)
  1662. {
  1663. char *kaddr;
  1664. size_t copied;
  1665. BUG_ON(!in_atomic());
  1666. kaddr = kmap_atomic(page, KM_USER0);
  1667. if (likely(i->nr_segs == 1)) {
  1668. int left;
  1669. char __user *buf = i->iov->iov_base + i->iov_offset;
  1670. left = __copy_from_user_inatomic(kaddr + offset, buf, bytes);
  1671. copied = bytes - left;
  1672. } else {
  1673. copied = __iovec_copy_from_user_inatomic(kaddr + offset,
  1674. i->iov, i->iov_offset, bytes);
  1675. }
  1676. kunmap_atomic(kaddr, KM_USER0);
  1677. return copied;
  1678. }
  1679. EXPORT_SYMBOL(iov_iter_copy_from_user_atomic);
  1680. /*
  1681. * This has the same sideeffects and return value as
  1682. * iov_iter_copy_from_user_atomic().
  1683. * The difference is that it attempts to resolve faults.
  1684. * Page must not be locked.
  1685. */
  1686. size_t iov_iter_copy_from_user(struct page *page,
  1687. struct iov_iter *i, unsigned long offset, size_t bytes)
  1688. {
  1689. char *kaddr;
  1690. size_t copied;
  1691. kaddr = kmap(page);
  1692. if (likely(i->nr_segs == 1)) {
  1693. int left;
  1694. char __user *buf = i->iov->iov_base + i->iov_offset;
  1695. left = __copy_from_user(kaddr + offset, buf, bytes);
  1696. copied = bytes - left;
  1697. } else {
  1698. copied = __iovec_copy_from_user_inatomic(kaddr + offset,
  1699. i->iov, i->iov_offset, bytes);
  1700. }
  1701. kunmap(page);
  1702. return copied;
  1703. }
  1704. EXPORT_SYMBOL(iov_iter_copy_from_user);
  1705. void iov_iter_advance(struct iov_iter *i, size_t bytes)
  1706. {
  1707. BUG_ON(i->count < bytes);
  1708. if (likely(i->nr_segs == 1)) {
  1709. i->iov_offset += bytes;
  1710. i->count -= bytes;
  1711. } else {
  1712. const struct iovec *iov = i->iov;
  1713. size_t base = i->iov_offset;
  1714. /*
  1715. * The !iov->iov_len check ensures we skip over unlikely
  1716. * zero-length segments (without overruning the iovec).
  1717. */
  1718. while (bytes || unlikely(i->count && !iov->iov_len)) {
  1719. int copy;
  1720. copy = min(bytes, iov->iov_len - base);
  1721. BUG_ON(!i->count || i->count < copy);
  1722. i->count -= copy;
  1723. bytes -= copy;
  1724. base += copy;
  1725. if (iov->iov_len == base) {
  1726. iov++;
  1727. base = 0;
  1728. }
  1729. }
  1730. i->iov = iov;
  1731. i->iov_offset = base;
  1732. }
  1733. }
  1734. EXPORT_SYMBOL(iov_iter_advance);
  1735. /*
  1736. * Fault in the first iovec of the given iov_iter, to a maximum length
  1737. * of bytes. Returns 0 on success, or non-zero if the memory could not be
  1738. * accessed (ie. because it is an invalid address).
  1739. *
  1740. * writev-intensive code may want this to prefault several iovecs -- that
  1741. * would be possible (callers must not rely on the fact that _only_ the
  1742. * first iovec will be faulted with the current implementation).
  1743. */
  1744. int iov_iter_fault_in_readable(struct iov_iter *i, size_t bytes)
  1745. {
  1746. char __user *buf = i->iov->iov_base + i->iov_offset;
  1747. bytes = min(bytes, i->iov->iov_len - i->iov_offset);
  1748. return fault_in_pages_readable(buf, bytes);
  1749. }
  1750. EXPORT_SYMBOL(iov_iter_fault_in_readable);
  1751. /*
  1752. * Return the count of just the current iov_iter segment.
  1753. */
  1754. size_t iov_iter_single_seg_count(struct iov_iter *i)
  1755. {
  1756. const struct iovec *iov = i->iov;
  1757. if (i->nr_segs == 1)
  1758. return i->count;
  1759. else
  1760. return min(i->count, iov->iov_len - i->iov_offset);
  1761. }
  1762. EXPORT_SYMBOL(iov_iter_single_seg_count);
  1763. /*
  1764. * Performs necessary checks before doing a write
  1765. *
  1766. * Can adjust writing position or amount of bytes to write.
  1767. * Returns appropriate error code that caller should return or
  1768. * zero in case that write should be allowed.
  1769. */
  1770. inline int generic_write_checks(struct file *file, loff_t *pos, size_t *count, int isblk)
  1771. {
  1772. struct inode *inode = file->f_mapping->host;
  1773. unsigned long limit = current->signal->rlim[RLIMIT_FSIZE].rlim_cur;
  1774. if (unlikely(*pos < 0))
  1775. return -EINVAL;
  1776. if (!isblk) {
  1777. /* FIXME: this is for backwards compatibility with 2.4 */
  1778. if (file->f_flags & O_APPEND)
  1779. *pos = i_size_read(inode);
  1780. if (limit != RLIM_INFINITY) {
  1781. if (*pos >= limit) {
  1782. send_sig(SIGXFSZ, current, 0);
  1783. return -EFBIG;
  1784. }
  1785. if (*count > limit - (typeof(limit))*pos) {
  1786. *count = limit - (typeof(limit))*pos;
  1787. }
  1788. }
  1789. }
  1790. /*
  1791. * LFS rule
  1792. */
  1793. if (unlikely(*pos + *count > MAX_NON_LFS &&
  1794. !(file->f_flags & O_LARGEFILE))) {
  1795. if (*pos >= MAX_NON_LFS) {
  1796. return -EFBIG;
  1797. }
  1798. if (*count > MAX_NON_LFS - (unsigned long)*pos) {
  1799. *count = MAX_NON_LFS - (unsigned long)*pos;
  1800. }
  1801. }
  1802. /*
  1803. * Are we about to exceed the fs block limit ?
  1804. *
  1805. * If we have written data it becomes a short write. If we have
  1806. * exceeded without writing data we send a signal and return EFBIG.
  1807. * Linus frestrict idea will clean these up nicely..
  1808. */
  1809. if (likely(!isblk)) {
  1810. if (unlikely(*pos >= inode->i_sb->s_maxbytes)) {
  1811. if (*count || *pos > inode->i_sb->s_maxbytes) {
  1812. return -EFBIG;
  1813. }
  1814. /* zero-length writes at ->s_maxbytes are OK */
  1815. }
  1816. if (unlikely(*pos + *count > inode->i_sb->s_maxbytes))
  1817. *count = inode->i_sb->s_maxbytes - *pos;
  1818. } else {
  1819. #ifdef CONFIG_BLOCK
  1820. loff_t isize;
  1821. if (bdev_read_only(I_BDEV(inode)))
  1822. return -EPERM;
  1823. isize = i_size_read(inode);
  1824. if (*pos >= isize) {
  1825. if (*count || *pos > isize)
  1826. return -ENOSPC;
  1827. }
  1828. if (*pos + *count > isize)
  1829. *count = isize - *pos;
  1830. #else
  1831. return -EPERM;
  1832. #endif
  1833. }
  1834. return 0;
  1835. }
  1836. EXPORT_SYMBOL(generic_write_checks);
  1837. int pagecache_write_begin(struct file *file, struct address_space *mapping,
  1838. loff_t pos, unsigned len, unsigned flags,
  1839. struct page **pagep, void **fsdata)
  1840. {
  1841. const struct address_space_operations *aops = mapping->a_ops;
  1842. return aops->write_begin(file, mapping, pos, len, flags,
  1843. pagep, fsdata);
  1844. }
  1845. EXPORT_SYMBOL(pagecache_write_begin);
  1846. int pagecache_write_end(struct file *file, struct address_space *mapping,
  1847. loff_t pos, unsigned len, unsigned copied,
  1848. struct page *page, void *fsdata)
  1849. {
  1850. const struct address_space_operations *aops = mapping->a_ops;
  1851. mark_page_accessed(page);
  1852. return aops->write_end(file, mapping, pos, len, copied, page, fsdata);
  1853. }
  1854. EXPORT_SYMBOL(pagecache_write_end);
  1855. ssize_t
  1856. generic_file_direct_write(struct kiocb *iocb, const struct iovec *iov,
  1857. unsigned long *nr_segs, loff_t pos, loff_t *ppos,
  1858. size_t count, size_t ocount)
  1859. {
  1860. struct file *file = iocb->ki_filp;
  1861. struct address_space *mapping = file->f_mapping;
  1862. struct inode *inode = mapping->host;
  1863. ssize_t written;
  1864. size_t write_len;
  1865. pgoff_t end;
  1866. if (count != ocount)
  1867. *nr_segs = iov_shorten((struct iovec *)iov, *nr_segs, count);
  1868. write_len = iov_length(iov, *nr_segs);
  1869. end = (pos + write_len - 1) >> PAGE_CACHE_SHIFT;
  1870. written = filemap_write_and_wait_range(mapping, pos, pos + write_len - 1);
  1871. if (written)
  1872. goto out;
  1873. /*
  1874. * After a write we want buffered reads to be sure to go to disk to get
  1875. * the new data. We invalidate clean cached page from the region we're
  1876. * about to write. We do this *before* the write so that we can return
  1877. * without clobbering -EIOCBQUEUED from ->direct_IO().
  1878. */
  1879. if (mapping->nrpages) {
  1880. written = invalidate_inode_pages2_range(mapping,
  1881. pos >> PAGE_CACHE_SHIFT, end);
  1882. /*
  1883. * If a page can not be invalidated, return 0 to fall back
  1884. * to buffered write.
  1885. */
  1886. if (written) {
  1887. if (written == -EBUSY)
  1888. return 0;
  1889. goto out;
  1890. }
  1891. }
  1892. written = mapping->a_ops->direct_IO(WRITE, iocb, iov, pos, *nr_segs);
  1893. /*
  1894. * Finally, try again to invalidate clean pages which might have been
  1895. * cached by non-direct readahead, or faulted in by get_user_pages()
  1896. * if the source of the write was an mmap'ed region of the file
  1897. * we're writing. Either one is a pretty crazy thing to do,
  1898. * so we don't support it 100%. If this invalidation
  1899. * fails, tough, the write still worked...
  1900. */
  1901. if (mapping->nrpages) {
  1902. invalidate_inode_pages2_range(mapping,
  1903. pos >> PAGE_CACHE_SHIFT, end);
  1904. }
  1905. if (written > 0) {
  1906. loff_t end = pos + written;
  1907. if (end > i_size_read(inode) && !S_ISBLK(inode->i_mode)) {
  1908. i_size_write(inode, end);
  1909. mark_inode_dirty(inode);
  1910. }
  1911. *ppos = end;
  1912. }
  1913. out:
  1914. return written;
  1915. }
  1916. EXPORT_SYMBOL(generic_file_direct_write);
  1917. /*
  1918. * Find or create a page at the given pagecache position. Return the locked
  1919. * page. This function is specifically for buffered writes.
  1920. */
  1921. struct page *grab_cache_page_write_begin(struct address_space *mapping,
  1922. pgoff_t index, unsigned flags)
  1923. {
  1924. int status;
  1925. struct page *page;
  1926. gfp_t gfp_notmask = 0;
  1927. if (flags & AOP_FLAG_NOFS)
  1928. gfp_notmask = __GFP_FS;
  1929. repeat:
  1930. page = find_lock_page(mapping, index);
  1931. if (likely(page))
  1932. return page;
  1933. page = __page_cache_alloc(mapping_gfp_mask(mapping) & ~gfp_notmask);
  1934. if (!page)
  1935. return NULL;
  1936. status = add_to_page_cache_lru(page, mapping, index,
  1937. GFP_KERNEL & ~gfp_notmask);
  1938. if (unlikely(status)) {
  1939. page_cache_release(page);
  1940. if (status == -EEXIST)
  1941. goto repeat;
  1942. return NULL;
  1943. }
  1944. return page;
  1945. }
  1946. EXPORT_SYMBOL(grab_cache_page_write_begin);
  1947. static ssize_t generic_perform_write(struct file *file,
  1948. struct iov_iter *i, loff_t pos)
  1949. {
  1950. struct address_space *mapping = file->f_mapping;
  1951. const struct address_space_operations *a_ops = mapping->a_ops;
  1952. long status = 0;
  1953. ssize_t written = 0;
  1954. unsigned int flags = 0;
  1955. /*
  1956. * Copies from kernel address space cannot fail (NFSD is a big user).
  1957. */
  1958. if (segment_eq(get_fs(), KERNEL_DS))
  1959. flags |= AOP_FLAG_UNINTERRUPTIBLE;
  1960. do {
  1961. struct page *page;
  1962. pgoff_t index; /* Pagecache index for current page */
  1963. unsigned long offset; /* Offset into pagecache page */
  1964. unsigned long bytes; /* Bytes to write to page */
  1965. size_t copied; /* Bytes copied from user */
  1966. void *fsdata;
  1967. offset = (pos & (PAGE_CACHE_SIZE - 1));
  1968. index = pos >> PAGE_CACHE_SHIFT;
  1969. bytes = min_t(unsigned long, PAGE_CACHE_SIZE - offset,
  1970. iov_iter_count(i));
  1971. again:
  1972. /*
  1973. * Bring in the user page that we will copy from _first_.
  1974. * Otherwise there's a nasty deadlock on copying from the
  1975. * same page as we're writing to, without it being marked
  1976. * up-to-date.
  1977. *
  1978. * Not only is this an optimisation, but it is also required
  1979. * to check that the address is actually valid, when atomic
  1980. * usercopies are used, below.
  1981. */
  1982. if (unlikely(iov_iter_fault_in_readable(i, bytes))) {
  1983. status = -EFAULT;
  1984. break;
  1985. }
  1986. status = a_ops->write_begin(file, mapping, pos, bytes, flags,
  1987. &page, &fsdata);
  1988. if (unlikely(status))
  1989. break;
  1990. pagefault_disable();
  1991. copied = iov_iter_copy_from_user_atomic(page, i, offset, bytes);
  1992. pagefault_enable();
  1993. flush_dcache_page(page);
  1994. mark_page_accessed(page);
  1995. status = a_ops->write_end(file, mapping, pos, bytes, copied,
  1996. page, fsdata);
  1997. if (unlikely(status < 0))
  1998. break;
  1999. copied = status;
  2000. cond_resched();
  2001. iov_iter_advance(i, copied);
  2002. if (unlikely(copied == 0)) {
  2003. /*
  2004. * If we were unable to copy any data at all, we must
  2005. * fall back to a single segment length write.
  2006. *
  2007. * If we didn't fallback here, we could livelock
  2008. * because not all segments in the iov can be copied at
  2009. * once without a pagefault.
  2010. */
  2011. bytes = min_t(unsigned long, PAGE_CACHE_SIZE - offset,
  2012. iov_iter_single_seg_count(i));
  2013. goto again;
  2014. }
  2015. pos += copied;
  2016. written += copied;
  2017. balance_dirty_pages_ratelimited(mapping);
  2018. } while (iov_iter_count(i));
  2019. return written ? written : status;
  2020. }
  2021. ssize_t
  2022. generic_file_buffered_write(struct kiocb *iocb, const struct iovec *iov,
  2023. unsigned long nr_segs, loff_t pos, loff_t *ppos,
  2024. size_t count, ssize_t written)
  2025. {
  2026. struct file *file = iocb->ki_filp;
  2027. struct address_space *mapping = file->f_mapping;
  2028. ssize_t status;
  2029. struct iov_iter i;
  2030. iov_iter_init(&i, iov, nr_segs, count, written);
  2031. status = generic_perform_write(file, &i, pos);
  2032. if (likely(status >= 0)) {
  2033. written += status;
  2034. *ppos = pos + status;
  2035. }
  2036. /*
  2037. * If we get here for O_DIRECT writes then we must have fallen through
  2038. * to buffered writes (block instantiation inside i_size). So we sync
  2039. * the file data here, to try to honour O_DIRECT expectations.
  2040. */
  2041. if (unlikely(file->f_flags & O_DIRECT) && written)
  2042. status = filemap_write_and_wait_range(mapping,
  2043. pos, pos + written - 1);
  2044. return written ? written : status;
  2045. }
  2046. EXPORT_SYMBOL(generic_file_buffered_write);
  2047. /**
  2048. * __generic_file_aio_write - write data to a file
  2049. * @iocb: IO state structure (file, offset, etc.)
  2050. * @iov: vector with data to write
  2051. * @nr_segs: number of segments in the vector
  2052. * @ppos: position where to write
  2053. *
  2054. * This function does all the work needed for actually writing data to a
  2055. * file. It does all basic checks, removes SUID from the file, updates
  2056. * modification times and calls proper subroutines depending on whether we
  2057. * do direct IO or a standard buffered write.
  2058. *
  2059. * It expects i_mutex to be grabbed unless we work on a block device or similar
  2060. * object which does not need locking at all.
  2061. *
  2062. * This function does *not* take care of syncing data in case of O_SYNC write.
  2063. * A caller has to handle it. This is mainly due to the fact that we want to
  2064. * avoid syncing under i_mutex.
  2065. */
  2066. ssize_t __generic_file_aio_write(struct kiocb *iocb, const struct iovec *iov,
  2067. unsigned long nr_segs, loff_t *ppos)
  2068. {
  2069. struct file *file = iocb->ki_filp;
  2070. struct address_space * mapping = file->f_mapping;
  2071. size_t ocount; /* original count */
  2072. size_t count; /* after file limit checks */
  2073. struct inode *inode = mapping->host;
  2074. loff_t pos;
  2075. ssize_t written;
  2076. ssize_t err;
  2077. ocount = 0;
  2078. err = generic_segment_checks(iov, &nr_segs, &ocount, VERIFY_READ);
  2079. if (err)
  2080. return err;
  2081. count = ocount;
  2082. pos = *ppos;
  2083. vfs_check_frozen(inode->i_sb, SB_FREEZE_WRITE);
  2084. /* We can write back this queue in page reclaim */
  2085. current->backing_dev_info = mapping->backing_dev_info;
  2086. written = 0;
  2087. err = generic_write_checks(file, &pos, &count, S_ISBLK(inode->i_mode));
  2088. if (err)
  2089. goto out;
  2090. if (count == 0)
  2091. goto out;
  2092. err = file_remove_suid(file);
  2093. if (err)
  2094. goto out;
  2095. file_update_time(file);
  2096. /* coalesce the iovecs and go direct-to-BIO for O_DIRECT */
  2097. if (unlikely(file->f_flags & O_DIRECT)) {
  2098. loff_t endbyte;
  2099. ssize_t written_buffered;
  2100. written = generic_file_direct_write(iocb, iov, &nr_segs, pos,
  2101. ppos, count, ocount);
  2102. if (written < 0 || written == count)
  2103. goto out;
  2104. /*
  2105. * direct-io write to a hole: fall through to buffered I/O
  2106. * for completing the rest of the request.
  2107. */
  2108. pos += written;
  2109. count -= written;
  2110. written_buffered = generic_file_buffered_write(iocb, iov,
  2111. nr_segs, pos, ppos, count,
  2112. written);
  2113. /*
  2114. * If generic_file_buffered_write() retuned a synchronous error
  2115. * then we want to return the number of bytes which were
  2116. * direct-written, or the error code if that was zero. Note
  2117. * that this differs from normal direct-io semantics, which
  2118. * will return -EFOO even if some bytes were written.
  2119. */
  2120. if (written_buffered < 0) {
  2121. err = written_buffered;
  2122. goto out;
  2123. }
  2124. /*
  2125. * We need to ensure that the page cache pages are written to
  2126. * disk and invalidated to preserve the expected O_DIRECT
  2127. * semantics.
  2128. */
  2129. endbyte = pos + written_buffered - written - 1;
  2130. err = do_sync_mapping_range(file->f_mapping, pos, endbyte,
  2131. SYNC_FILE_RANGE_WAIT_BEFORE|
  2132. SYNC_FILE_RANGE_WRITE|
  2133. SYNC_FILE_RANGE_WAIT_AFTER);
  2134. if (err == 0) {
  2135. written = written_buffered;
  2136. invalidate_mapping_pages(mapping,
  2137. pos >> PAGE_CACHE_SHIFT,
  2138. endbyte >> PAGE_CACHE_SHIFT);
  2139. } else {
  2140. /*
  2141. * We don't know how much we wrote, so just return
  2142. * the number of bytes which were direct-written
  2143. */
  2144. }
  2145. } else {
  2146. written = generic_file_buffered_write(iocb, iov, nr_segs,
  2147. pos, ppos, count, written);
  2148. }
  2149. out:
  2150. current->backing_dev_info = NULL;
  2151. return written ? written : err;
  2152. }
  2153. EXPORT_SYMBOL(__generic_file_aio_write);
  2154. /**
  2155. * generic_file_aio_write - write data to a file
  2156. * @iocb: IO state structure
  2157. * @iov: vector with data to write
  2158. * @nr_segs: number of segments in the vector
  2159. * @pos: position in file where to write
  2160. *
  2161. * This is a wrapper around __generic_file_aio_write() to be used by most
  2162. * filesystems. It takes care of syncing the file in case of O_SYNC file
  2163. * and acquires i_mutex as needed.
  2164. */
  2165. ssize_t generic_file_aio_write(struct kiocb *iocb, const struct iovec *iov,
  2166. unsigned long nr_segs, loff_t pos)
  2167. {
  2168. struct file *file = iocb->ki_filp;
  2169. struct inode *inode = file->f_mapping->host;
  2170. ssize_t ret;
  2171. BUG_ON(iocb->ki_pos != pos);
  2172. mutex_lock(&inode->i_mutex);
  2173. ret = __generic_file_aio_write(iocb, iov, nr_segs, &iocb->ki_pos);
  2174. mutex_unlock(&inode->i_mutex);
  2175. if (ret > 0 || ret == -EIOCBQUEUED) {
  2176. ssize_t err;
  2177. err = generic_write_sync(file, pos, ret);
  2178. if (err < 0 && ret > 0)
  2179. ret = err;
  2180. }
  2181. return ret;
  2182. }
  2183. EXPORT_SYMBOL(generic_file_aio_write);
  2184. /**
  2185. * try_to_release_page() - release old fs-specific metadata on a page
  2186. *
  2187. * @page: the page which the kernel is trying to free
  2188. * @gfp_mask: memory allocation flags (and I/O mode)
  2189. *
  2190. * The address_space is to try to release any data against the page
  2191. * (presumably at page->private). If the release was successful, return `1'.
  2192. * Otherwise return zero.
  2193. *
  2194. * This may also be called if PG_fscache is set on a page, indicating that the
  2195. * page is known to the local caching routines.
  2196. *
  2197. * The @gfp_mask argument specifies whether I/O may be performed to release
  2198. * this page (__GFP_IO), and whether the call may block (__GFP_WAIT & __GFP_FS).
  2199. *
  2200. */
  2201. int try_to_release_page(struct page *page, gfp_t gfp_mask)
  2202. {
  2203. struct address_space * const mapping = page->mapping;
  2204. BUG_ON(!PageLocked(page));
  2205. if (PageWriteback(page))
  2206. return 0;
  2207. if (mapping && mapping->a_ops->releasepage)
  2208. return mapping->a_ops->releasepage(page, gfp_mask);
  2209. return try_to_free_buffers(page);
  2210. }
  2211. EXPORT_SYMBOL(try_to_release_page);