filemap.c 70 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703
  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/export.h>
  12. #include <linux/compiler.h>
  13. #include <linux/fs.h>
  14. #include <linux/uaccess.h>
  15. #include <linux/aio.h>
  16. #include <linux/capability.h>
  17. #include <linux/kernel_stat.h>
  18. #include <linux/gfp.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/cpuset.h>
  32. #include <linux/hardirq.h> /* for BUG_ON(!in_atomic()) only */
  33. #include <linux/hugetlb.h>
  34. #include <linux/memcontrol.h>
  35. #include <linux/cleancache.h>
  36. #include <linux/rmap.h>
  37. #include "internal.h"
  38. #define CREATE_TRACE_POINTS
  39. #include <trace/events/filemap.h>
  40. /*
  41. * FIXME: remove all knowledge of the buffer layer from the core VM
  42. */
  43. #include <linux/buffer_head.h> /* for try_to_free_buffers */
  44. #include <asm/mman.h>
  45. /*
  46. * Shared mappings implemented 30.11.1994. It's not fully working yet,
  47. * though.
  48. *
  49. * Shared mappings now work. 15.8.1995 Bruno.
  50. *
  51. * finished 'unifying' the page and buffer cache and SMP-threaded the
  52. * page-cache, 21.05.1999, Ingo Molnar <mingo@redhat.com>
  53. *
  54. * SMP-threaded pagemap-LRU 1999, Andrea Arcangeli <andrea@suse.de>
  55. */
  56. /*
  57. * Lock ordering:
  58. *
  59. * ->i_mmap_rwsem (truncate_pagecache)
  60. * ->private_lock (__free_pte->__set_page_dirty_buffers)
  61. * ->swap_lock (exclusive_swap_page, others)
  62. * ->mapping->tree_lock
  63. *
  64. * ->i_mutex
  65. * ->i_mmap_rwsem (truncate->unmap_mapping_range)
  66. *
  67. * ->mmap_sem
  68. * ->i_mmap_rwsem
  69. * ->page_table_lock or pte_lock (various, mainly in memory.c)
  70. * ->mapping->tree_lock (arch-dependent flush_dcache_mmap_lock)
  71. *
  72. * ->mmap_sem
  73. * ->lock_page (access_process_vm)
  74. *
  75. * ->i_mutex (generic_perform_write)
  76. * ->mmap_sem (fault_in_pages_readable->do_page_fault)
  77. *
  78. * bdi->wb.list_lock
  79. * sb_lock (fs/fs-writeback.c)
  80. * ->mapping->tree_lock (__sync_single_inode)
  81. *
  82. * ->i_mmap_rwsem
  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. * bdi.wb->list_lock (page_remove_rmap->set_page_dirty)
  97. * ->inode->i_lock (page_remove_rmap->set_page_dirty)
  98. * bdi.wb->list_lock (zap_pte_range->set_page_dirty)
  99. * ->inode->i_lock (zap_pte_range->set_page_dirty)
  100. * ->private_lock (zap_pte_range->__set_page_dirty_buffers)
  101. *
  102. * ->i_mmap_rwsem
  103. * ->tasklist_lock (memory_failure, collect_procs_ao)
  104. */
  105. static void page_cache_tree_delete(struct address_space *mapping,
  106. struct page *page, void *shadow)
  107. {
  108. struct radix_tree_node *node;
  109. unsigned long index;
  110. unsigned int offset;
  111. unsigned int tag;
  112. void **slot;
  113. VM_BUG_ON(!PageLocked(page));
  114. __radix_tree_lookup(&mapping->page_tree, page->index, &node, &slot);
  115. if (shadow) {
  116. mapping->nrshadows++;
  117. /*
  118. * Make sure the nrshadows update is committed before
  119. * the nrpages update so that final truncate racing
  120. * with reclaim does not see both counters 0 at the
  121. * same time and miss a shadow entry.
  122. */
  123. smp_wmb();
  124. }
  125. mapping->nrpages--;
  126. if (!node) {
  127. /* Clear direct pointer tags in root node */
  128. mapping->page_tree.gfp_mask &= __GFP_BITS_MASK;
  129. radix_tree_replace_slot(slot, shadow);
  130. return;
  131. }
  132. /* Clear tree tags for the removed page */
  133. index = page->index;
  134. offset = index & RADIX_TREE_MAP_MASK;
  135. for (tag = 0; tag < RADIX_TREE_MAX_TAGS; tag++) {
  136. if (test_bit(offset, node->tags[tag]))
  137. radix_tree_tag_clear(&mapping->page_tree, index, tag);
  138. }
  139. /* Delete page, swap shadow entry */
  140. radix_tree_replace_slot(slot, shadow);
  141. workingset_node_pages_dec(node);
  142. if (shadow)
  143. workingset_node_shadows_inc(node);
  144. else
  145. if (__radix_tree_delete_node(&mapping->page_tree, node))
  146. return;
  147. /*
  148. * Track node that only contains shadow entries.
  149. *
  150. * Avoid acquiring the list_lru lock if already tracked. The
  151. * list_empty() test is safe as node->private_list is
  152. * protected by mapping->tree_lock.
  153. */
  154. if (!workingset_node_pages(node) &&
  155. list_empty(&node->private_list)) {
  156. node->private_data = mapping;
  157. list_lru_add(&workingset_shadow_nodes, &node->private_list);
  158. }
  159. }
  160. /*
  161. * Delete a page from the page cache and free it. Caller has to make
  162. * sure the page is locked and that nobody else uses it - or that usage
  163. * is safe. The caller must hold the mapping's tree_lock.
  164. */
  165. void __delete_from_page_cache(struct page *page, void *shadow)
  166. {
  167. struct address_space *mapping = page->mapping;
  168. trace_mm_filemap_delete_from_page_cache(page);
  169. /*
  170. * if we're uptodate, flush out into the cleancache, otherwise
  171. * invalidate any existing cleancache entries. We can't leave
  172. * stale data around in the cleancache once our page is gone
  173. */
  174. if (PageUptodate(page) && PageMappedToDisk(page))
  175. cleancache_put_page(page);
  176. else
  177. cleancache_invalidate_page(mapping, page);
  178. page_cache_tree_delete(mapping, page, shadow);
  179. page->mapping = NULL;
  180. /* Leave page->index set: truncation lookup relies upon it */
  181. __dec_zone_page_state(page, NR_FILE_PAGES);
  182. if (PageSwapBacked(page))
  183. __dec_zone_page_state(page, NR_SHMEM);
  184. BUG_ON(page_mapped(page));
  185. /*
  186. * Some filesystems seem to re-dirty the page even after
  187. * the VM has canceled the dirty bit (eg ext3 journaling).
  188. *
  189. * Fix it up by doing a final dirty accounting check after
  190. * having removed the page entirely.
  191. */
  192. if (PageDirty(page) && mapping_cap_account_dirty(mapping)) {
  193. dec_zone_page_state(page, NR_FILE_DIRTY);
  194. dec_bdi_stat(mapping->backing_dev_info, BDI_RECLAIMABLE);
  195. }
  196. }
  197. /**
  198. * delete_from_page_cache - delete page from page cache
  199. * @page: the page which the kernel is trying to remove from page cache
  200. *
  201. * This must be called only on pages that have been verified to be in the page
  202. * cache and locked. It will never put the page into the free list, the caller
  203. * has a reference on the page.
  204. */
  205. void delete_from_page_cache(struct page *page)
  206. {
  207. struct address_space *mapping = page->mapping;
  208. void (*freepage)(struct page *);
  209. BUG_ON(!PageLocked(page));
  210. freepage = mapping->a_ops->freepage;
  211. spin_lock_irq(&mapping->tree_lock);
  212. __delete_from_page_cache(page, NULL);
  213. spin_unlock_irq(&mapping->tree_lock);
  214. if (freepage)
  215. freepage(page);
  216. page_cache_release(page);
  217. }
  218. EXPORT_SYMBOL(delete_from_page_cache);
  219. static int filemap_check_errors(struct address_space *mapping)
  220. {
  221. int ret = 0;
  222. /* Check for outstanding write errors */
  223. if (test_bit(AS_ENOSPC, &mapping->flags) &&
  224. test_and_clear_bit(AS_ENOSPC, &mapping->flags))
  225. ret = -ENOSPC;
  226. if (test_bit(AS_EIO, &mapping->flags) &&
  227. test_and_clear_bit(AS_EIO, &mapping->flags))
  228. ret = -EIO;
  229. return ret;
  230. }
  231. /**
  232. * __filemap_fdatawrite_range - start writeback on mapping dirty pages in range
  233. * @mapping: address space structure to write
  234. * @start: offset in bytes where the range starts
  235. * @end: offset in bytes where the range ends (inclusive)
  236. * @sync_mode: enable synchronous operation
  237. *
  238. * Start writeback against all of a mapping's dirty pages that lie
  239. * within the byte offsets <start, end> inclusive.
  240. *
  241. * If sync_mode is WB_SYNC_ALL then this is a "data integrity" operation, as
  242. * opposed to a regular memory cleansing writeback. The difference between
  243. * these two operations is that if a dirty page/buffer is encountered, it must
  244. * be waited upon, and not just skipped over.
  245. */
  246. int __filemap_fdatawrite_range(struct address_space *mapping, loff_t start,
  247. loff_t end, int sync_mode)
  248. {
  249. int ret;
  250. struct writeback_control wbc = {
  251. .sync_mode = sync_mode,
  252. .nr_to_write = LONG_MAX,
  253. .range_start = start,
  254. .range_end = end,
  255. };
  256. if (!mapping_cap_writeback_dirty(mapping))
  257. return 0;
  258. ret = do_writepages(mapping, &wbc);
  259. return ret;
  260. }
  261. static inline int __filemap_fdatawrite(struct address_space *mapping,
  262. int sync_mode)
  263. {
  264. return __filemap_fdatawrite_range(mapping, 0, LLONG_MAX, sync_mode);
  265. }
  266. int filemap_fdatawrite(struct address_space *mapping)
  267. {
  268. return __filemap_fdatawrite(mapping, WB_SYNC_ALL);
  269. }
  270. EXPORT_SYMBOL(filemap_fdatawrite);
  271. int filemap_fdatawrite_range(struct address_space *mapping, loff_t start,
  272. loff_t end)
  273. {
  274. return __filemap_fdatawrite_range(mapping, start, end, WB_SYNC_ALL);
  275. }
  276. EXPORT_SYMBOL(filemap_fdatawrite_range);
  277. /**
  278. * filemap_flush - mostly a non-blocking flush
  279. * @mapping: target address_space
  280. *
  281. * This is a mostly non-blocking flush. Not suitable for data-integrity
  282. * purposes - I/O may not be started against all dirty pages.
  283. */
  284. int filemap_flush(struct address_space *mapping)
  285. {
  286. return __filemap_fdatawrite(mapping, WB_SYNC_NONE);
  287. }
  288. EXPORT_SYMBOL(filemap_flush);
  289. /**
  290. * filemap_fdatawait_range - wait for writeback to complete
  291. * @mapping: address space structure to wait for
  292. * @start_byte: offset in bytes where the range starts
  293. * @end_byte: offset in bytes where the range ends (inclusive)
  294. *
  295. * Walk the list of under-writeback pages of the given address space
  296. * in the given range and wait for all of them.
  297. */
  298. int filemap_fdatawait_range(struct address_space *mapping, loff_t start_byte,
  299. loff_t end_byte)
  300. {
  301. pgoff_t index = start_byte >> PAGE_CACHE_SHIFT;
  302. pgoff_t end = end_byte >> PAGE_CACHE_SHIFT;
  303. struct pagevec pvec;
  304. int nr_pages;
  305. int ret2, ret = 0;
  306. if (end_byte < start_byte)
  307. goto out;
  308. pagevec_init(&pvec, 0);
  309. while ((index <= end) &&
  310. (nr_pages = pagevec_lookup_tag(&pvec, mapping, &index,
  311. PAGECACHE_TAG_WRITEBACK,
  312. min(end - index, (pgoff_t)PAGEVEC_SIZE-1) + 1)) != 0) {
  313. unsigned i;
  314. for (i = 0; i < nr_pages; i++) {
  315. struct page *page = pvec.pages[i];
  316. /* until radix tree lookup accepts end_index */
  317. if (page->index > end)
  318. continue;
  319. wait_on_page_writeback(page);
  320. if (TestClearPageError(page))
  321. ret = -EIO;
  322. }
  323. pagevec_release(&pvec);
  324. cond_resched();
  325. }
  326. out:
  327. ret2 = filemap_check_errors(mapping);
  328. if (!ret)
  329. ret = ret2;
  330. return ret;
  331. }
  332. EXPORT_SYMBOL(filemap_fdatawait_range);
  333. /**
  334. * filemap_fdatawait - wait for all under-writeback pages to complete
  335. * @mapping: address space structure to wait for
  336. *
  337. * Walk the list of under-writeback pages of the given address space
  338. * and wait for all of them.
  339. */
  340. int filemap_fdatawait(struct address_space *mapping)
  341. {
  342. loff_t i_size = i_size_read(mapping->host);
  343. if (i_size == 0)
  344. return 0;
  345. return filemap_fdatawait_range(mapping, 0, i_size - 1);
  346. }
  347. EXPORT_SYMBOL(filemap_fdatawait);
  348. int filemap_write_and_wait(struct address_space *mapping)
  349. {
  350. int err = 0;
  351. if (mapping->nrpages) {
  352. err = filemap_fdatawrite(mapping);
  353. /*
  354. * Even if the above returned error, the pages may be
  355. * written partially (e.g. -ENOSPC), so we wait for it.
  356. * But the -EIO is special case, it may indicate the worst
  357. * thing (e.g. bug) happened, so we avoid waiting for it.
  358. */
  359. if (err != -EIO) {
  360. int err2 = filemap_fdatawait(mapping);
  361. if (!err)
  362. err = err2;
  363. }
  364. } else {
  365. err = filemap_check_errors(mapping);
  366. }
  367. return err;
  368. }
  369. EXPORT_SYMBOL(filemap_write_and_wait);
  370. /**
  371. * filemap_write_and_wait_range - write out & wait on a file range
  372. * @mapping: the address_space for the pages
  373. * @lstart: offset in bytes where the range starts
  374. * @lend: offset in bytes where the range ends (inclusive)
  375. *
  376. * Write out and wait upon file offsets lstart->lend, inclusive.
  377. *
  378. * Note that `lend' is inclusive (describes the last byte to be written) so
  379. * that this function can be used to write to the very end-of-file (end = -1).
  380. */
  381. int filemap_write_and_wait_range(struct address_space *mapping,
  382. loff_t lstart, loff_t lend)
  383. {
  384. int err = 0;
  385. if (mapping->nrpages) {
  386. err = __filemap_fdatawrite_range(mapping, lstart, lend,
  387. WB_SYNC_ALL);
  388. /* See comment of filemap_write_and_wait() */
  389. if (err != -EIO) {
  390. int err2 = filemap_fdatawait_range(mapping,
  391. lstart, lend);
  392. if (!err)
  393. err = err2;
  394. }
  395. } else {
  396. err = filemap_check_errors(mapping);
  397. }
  398. return err;
  399. }
  400. EXPORT_SYMBOL(filemap_write_and_wait_range);
  401. /**
  402. * replace_page_cache_page - replace a pagecache page with a new one
  403. * @old: page to be replaced
  404. * @new: page to replace with
  405. * @gfp_mask: allocation mode
  406. *
  407. * This function replaces a page in the pagecache with a new one. On
  408. * success it acquires the pagecache reference for the new page and
  409. * drops it for the old page. Both the old and new pages must be
  410. * locked. This function does not add the new page to the LRU, the
  411. * caller must do that.
  412. *
  413. * The remove + add is atomic. The only way this function can fail is
  414. * memory allocation failure.
  415. */
  416. int replace_page_cache_page(struct page *old, struct page *new, gfp_t gfp_mask)
  417. {
  418. int error;
  419. VM_BUG_ON_PAGE(!PageLocked(old), old);
  420. VM_BUG_ON_PAGE(!PageLocked(new), new);
  421. VM_BUG_ON_PAGE(new->mapping, new);
  422. error = radix_tree_preload(gfp_mask & ~__GFP_HIGHMEM);
  423. if (!error) {
  424. struct address_space *mapping = old->mapping;
  425. void (*freepage)(struct page *);
  426. pgoff_t offset = old->index;
  427. freepage = mapping->a_ops->freepage;
  428. page_cache_get(new);
  429. new->mapping = mapping;
  430. new->index = offset;
  431. spin_lock_irq(&mapping->tree_lock);
  432. __delete_from_page_cache(old, NULL);
  433. error = radix_tree_insert(&mapping->page_tree, offset, new);
  434. BUG_ON(error);
  435. mapping->nrpages++;
  436. __inc_zone_page_state(new, NR_FILE_PAGES);
  437. if (PageSwapBacked(new))
  438. __inc_zone_page_state(new, NR_SHMEM);
  439. spin_unlock_irq(&mapping->tree_lock);
  440. mem_cgroup_migrate(old, new, true);
  441. radix_tree_preload_end();
  442. if (freepage)
  443. freepage(old);
  444. page_cache_release(old);
  445. }
  446. return error;
  447. }
  448. EXPORT_SYMBOL_GPL(replace_page_cache_page);
  449. static int page_cache_tree_insert(struct address_space *mapping,
  450. struct page *page, void **shadowp)
  451. {
  452. struct radix_tree_node *node;
  453. void **slot;
  454. int error;
  455. error = __radix_tree_create(&mapping->page_tree, page->index,
  456. &node, &slot);
  457. if (error)
  458. return error;
  459. if (*slot) {
  460. void *p;
  461. p = radix_tree_deref_slot_protected(slot, &mapping->tree_lock);
  462. if (!radix_tree_exceptional_entry(p))
  463. return -EEXIST;
  464. if (shadowp)
  465. *shadowp = p;
  466. mapping->nrshadows--;
  467. if (node)
  468. workingset_node_shadows_dec(node);
  469. }
  470. radix_tree_replace_slot(slot, page);
  471. mapping->nrpages++;
  472. if (node) {
  473. workingset_node_pages_inc(node);
  474. /*
  475. * Don't track node that contains actual pages.
  476. *
  477. * Avoid acquiring the list_lru lock if already
  478. * untracked. The list_empty() test is safe as
  479. * node->private_list is protected by
  480. * mapping->tree_lock.
  481. */
  482. if (!list_empty(&node->private_list))
  483. list_lru_del(&workingset_shadow_nodes,
  484. &node->private_list);
  485. }
  486. return 0;
  487. }
  488. static int __add_to_page_cache_locked(struct page *page,
  489. struct address_space *mapping,
  490. pgoff_t offset, gfp_t gfp_mask,
  491. void **shadowp)
  492. {
  493. int huge = PageHuge(page);
  494. struct mem_cgroup *memcg;
  495. int error;
  496. VM_BUG_ON_PAGE(!PageLocked(page), page);
  497. VM_BUG_ON_PAGE(PageSwapBacked(page), page);
  498. if (!huge) {
  499. error = mem_cgroup_try_charge(page, current->mm,
  500. gfp_mask, &memcg);
  501. if (error)
  502. return error;
  503. }
  504. error = radix_tree_maybe_preload(gfp_mask & ~__GFP_HIGHMEM);
  505. if (error) {
  506. if (!huge)
  507. mem_cgroup_cancel_charge(page, memcg);
  508. return error;
  509. }
  510. page_cache_get(page);
  511. page->mapping = mapping;
  512. page->index = offset;
  513. spin_lock_irq(&mapping->tree_lock);
  514. error = page_cache_tree_insert(mapping, page, shadowp);
  515. radix_tree_preload_end();
  516. if (unlikely(error))
  517. goto err_insert;
  518. __inc_zone_page_state(page, NR_FILE_PAGES);
  519. spin_unlock_irq(&mapping->tree_lock);
  520. if (!huge)
  521. mem_cgroup_commit_charge(page, memcg, false);
  522. trace_mm_filemap_add_to_page_cache(page);
  523. return 0;
  524. err_insert:
  525. page->mapping = NULL;
  526. /* Leave page->index set: truncation relies upon it */
  527. spin_unlock_irq(&mapping->tree_lock);
  528. if (!huge)
  529. mem_cgroup_cancel_charge(page, memcg);
  530. page_cache_release(page);
  531. return error;
  532. }
  533. /**
  534. * add_to_page_cache_locked - add a locked page to the pagecache
  535. * @page: page to add
  536. * @mapping: the page's address_space
  537. * @offset: page index
  538. * @gfp_mask: page allocation mode
  539. *
  540. * This function is used to add a page to the pagecache. It must be locked.
  541. * This function does not add the page to the LRU. The caller must do that.
  542. */
  543. int add_to_page_cache_locked(struct page *page, struct address_space *mapping,
  544. pgoff_t offset, gfp_t gfp_mask)
  545. {
  546. return __add_to_page_cache_locked(page, mapping, offset,
  547. gfp_mask, NULL);
  548. }
  549. EXPORT_SYMBOL(add_to_page_cache_locked);
  550. int add_to_page_cache_lru(struct page *page, struct address_space *mapping,
  551. pgoff_t offset, gfp_t gfp_mask)
  552. {
  553. void *shadow = NULL;
  554. int ret;
  555. __set_page_locked(page);
  556. ret = __add_to_page_cache_locked(page, mapping, offset,
  557. gfp_mask, &shadow);
  558. if (unlikely(ret))
  559. __clear_page_locked(page);
  560. else {
  561. /*
  562. * The page might have been evicted from cache only
  563. * recently, in which case it should be activated like
  564. * any other repeatedly accessed page.
  565. */
  566. if (shadow && workingset_refault(shadow)) {
  567. SetPageActive(page);
  568. workingset_activation(page);
  569. } else
  570. ClearPageActive(page);
  571. lru_cache_add(page);
  572. }
  573. return ret;
  574. }
  575. EXPORT_SYMBOL_GPL(add_to_page_cache_lru);
  576. #ifdef CONFIG_NUMA
  577. struct page *__page_cache_alloc(gfp_t gfp)
  578. {
  579. int n;
  580. struct page *page;
  581. if (cpuset_do_page_mem_spread()) {
  582. unsigned int cpuset_mems_cookie;
  583. do {
  584. cpuset_mems_cookie = read_mems_allowed_begin();
  585. n = cpuset_mem_spread_node();
  586. page = alloc_pages_exact_node(n, gfp, 0);
  587. } while (!page && read_mems_allowed_retry(cpuset_mems_cookie));
  588. return page;
  589. }
  590. return alloc_pages(gfp, 0);
  591. }
  592. EXPORT_SYMBOL(__page_cache_alloc);
  593. #endif
  594. /*
  595. * In order to wait for pages to become available there must be
  596. * waitqueues associated with pages. By using a hash table of
  597. * waitqueues where the bucket discipline is to maintain all
  598. * waiters on the same queue and wake all when any of the pages
  599. * become available, and for the woken contexts to check to be
  600. * sure the appropriate page became available, this saves space
  601. * at a cost of "thundering herd" phenomena during rare hash
  602. * collisions.
  603. */
  604. wait_queue_head_t *page_waitqueue(struct page *page)
  605. {
  606. const struct zone *zone = page_zone(page);
  607. return &zone->wait_table[hash_ptr(page, zone->wait_table_bits)];
  608. }
  609. EXPORT_SYMBOL(page_waitqueue);
  610. void wait_on_page_bit(struct page *page, int bit_nr)
  611. {
  612. DEFINE_WAIT_BIT(wait, &page->flags, bit_nr);
  613. if (test_bit(bit_nr, &page->flags))
  614. __wait_on_bit(page_waitqueue(page), &wait, bit_wait_io,
  615. TASK_UNINTERRUPTIBLE);
  616. }
  617. EXPORT_SYMBOL(wait_on_page_bit);
  618. int wait_on_page_bit_killable(struct page *page, int bit_nr)
  619. {
  620. DEFINE_WAIT_BIT(wait, &page->flags, bit_nr);
  621. if (!test_bit(bit_nr, &page->flags))
  622. return 0;
  623. return __wait_on_bit(page_waitqueue(page), &wait,
  624. bit_wait_io, TASK_KILLABLE);
  625. }
  626. int wait_on_page_bit_killable_timeout(struct page *page,
  627. int bit_nr, unsigned long timeout)
  628. {
  629. DEFINE_WAIT_BIT(wait, &page->flags, bit_nr);
  630. wait.key.timeout = jiffies + timeout;
  631. if (!test_bit(bit_nr, &page->flags))
  632. return 0;
  633. return __wait_on_bit(page_waitqueue(page), &wait,
  634. bit_wait_io_timeout, TASK_KILLABLE);
  635. }
  636. EXPORT_SYMBOL_GPL(wait_on_page_bit_killable_timeout);
  637. /**
  638. * add_page_wait_queue - Add an arbitrary waiter to a page's wait queue
  639. * @page: Page defining the wait queue of interest
  640. * @waiter: Waiter to add to the queue
  641. *
  642. * Add an arbitrary @waiter to the wait queue for the nominated @page.
  643. */
  644. void add_page_wait_queue(struct page *page, wait_queue_t *waiter)
  645. {
  646. wait_queue_head_t *q = page_waitqueue(page);
  647. unsigned long flags;
  648. spin_lock_irqsave(&q->lock, flags);
  649. __add_wait_queue(q, waiter);
  650. spin_unlock_irqrestore(&q->lock, flags);
  651. }
  652. EXPORT_SYMBOL_GPL(add_page_wait_queue);
  653. /**
  654. * unlock_page - unlock a locked page
  655. * @page: the page
  656. *
  657. * Unlocks the page and wakes up sleepers in ___wait_on_page_locked().
  658. * Also wakes sleepers in wait_on_page_writeback() because the wakeup
  659. * mechanism between PageLocked pages and PageWriteback pages is shared.
  660. * But that's OK - sleepers in wait_on_page_writeback() just go back to sleep.
  661. *
  662. * The mb is necessary to enforce ordering between the clear_bit and the read
  663. * of the waitqueue (to avoid SMP races with a parallel wait_on_page_locked()).
  664. */
  665. void unlock_page(struct page *page)
  666. {
  667. VM_BUG_ON_PAGE(!PageLocked(page), page);
  668. clear_bit_unlock(PG_locked, &page->flags);
  669. smp_mb__after_atomic();
  670. wake_up_page(page, PG_locked);
  671. }
  672. EXPORT_SYMBOL(unlock_page);
  673. /**
  674. * end_page_writeback - end writeback against a page
  675. * @page: the page
  676. */
  677. void end_page_writeback(struct page *page)
  678. {
  679. /*
  680. * TestClearPageReclaim could be used here but it is an atomic
  681. * operation and overkill in this particular case. Failing to
  682. * shuffle a page marked for immediate reclaim is too mild to
  683. * justify taking an atomic operation penalty at the end of
  684. * ever page writeback.
  685. */
  686. if (PageReclaim(page)) {
  687. ClearPageReclaim(page);
  688. rotate_reclaimable_page(page);
  689. }
  690. if (!test_clear_page_writeback(page))
  691. BUG();
  692. smp_mb__after_atomic();
  693. wake_up_page(page, PG_writeback);
  694. }
  695. EXPORT_SYMBOL(end_page_writeback);
  696. /*
  697. * After completing I/O on a page, call this routine to update the page
  698. * flags appropriately
  699. */
  700. void page_endio(struct page *page, int rw, int err)
  701. {
  702. if (rw == READ) {
  703. if (!err) {
  704. SetPageUptodate(page);
  705. } else {
  706. ClearPageUptodate(page);
  707. SetPageError(page);
  708. }
  709. unlock_page(page);
  710. } else { /* rw == WRITE */
  711. if (err) {
  712. SetPageError(page);
  713. if (page->mapping)
  714. mapping_set_error(page->mapping, err);
  715. }
  716. end_page_writeback(page);
  717. }
  718. }
  719. EXPORT_SYMBOL_GPL(page_endio);
  720. /**
  721. * __lock_page - get a lock on the page, assuming we need to sleep to get it
  722. * @page: the page to lock
  723. */
  724. void __lock_page(struct page *page)
  725. {
  726. DEFINE_WAIT_BIT(wait, &page->flags, PG_locked);
  727. __wait_on_bit_lock(page_waitqueue(page), &wait, bit_wait_io,
  728. TASK_UNINTERRUPTIBLE);
  729. }
  730. EXPORT_SYMBOL(__lock_page);
  731. int __lock_page_killable(struct page *page)
  732. {
  733. DEFINE_WAIT_BIT(wait, &page->flags, PG_locked);
  734. return __wait_on_bit_lock(page_waitqueue(page), &wait,
  735. bit_wait_io, TASK_KILLABLE);
  736. }
  737. EXPORT_SYMBOL_GPL(__lock_page_killable);
  738. /*
  739. * Return values:
  740. * 1 - page is locked; mmap_sem is still held.
  741. * 0 - page is not locked.
  742. * mmap_sem has been released (up_read()), unless flags had both
  743. * FAULT_FLAG_ALLOW_RETRY and FAULT_FLAG_RETRY_NOWAIT set, in
  744. * which case mmap_sem is still held.
  745. *
  746. * If neither ALLOW_RETRY nor KILLABLE are set, will always return 1
  747. * with the page locked and the mmap_sem unperturbed.
  748. */
  749. int __lock_page_or_retry(struct page *page, struct mm_struct *mm,
  750. unsigned int flags)
  751. {
  752. if (flags & FAULT_FLAG_ALLOW_RETRY) {
  753. /*
  754. * CAUTION! In this case, mmap_sem is not released
  755. * even though return 0.
  756. */
  757. if (flags & FAULT_FLAG_RETRY_NOWAIT)
  758. return 0;
  759. up_read(&mm->mmap_sem);
  760. if (flags & FAULT_FLAG_KILLABLE)
  761. wait_on_page_locked_killable(page);
  762. else
  763. wait_on_page_locked(page);
  764. return 0;
  765. } else {
  766. if (flags & FAULT_FLAG_KILLABLE) {
  767. int ret;
  768. ret = __lock_page_killable(page);
  769. if (ret) {
  770. up_read(&mm->mmap_sem);
  771. return 0;
  772. }
  773. } else
  774. __lock_page(page);
  775. return 1;
  776. }
  777. }
  778. /**
  779. * page_cache_next_hole - find the next hole (not-present entry)
  780. * @mapping: mapping
  781. * @index: index
  782. * @max_scan: maximum range to search
  783. *
  784. * Search the set [index, min(index+max_scan-1, MAX_INDEX)] for the
  785. * lowest indexed hole.
  786. *
  787. * Returns: the index of the hole if found, otherwise returns an index
  788. * outside of the set specified (in which case 'return - index >=
  789. * max_scan' will be true). In rare cases of index wrap-around, 0 will
  790. * be returned.
  791. *
  792. * page_cache_next_hole may be called under rcu_read_lock. However,
  793. * like radix_tree_gang_lookup, this will not atomically search a
  794. * snapshot of the tree at a single point in time. For example, if a
  795. * hole is created at index 5, then subsequently a hole is created at
  796. * index 10, page_cache_next_hole covering both indexes may return 10
  797. * if called under rcu_read_lock.
  798. */
  799. pgoff_t page_cache_next_hole(struct address_space *mapping,
  800. pgoff_t index, unsigned long max_scan)
  801. {
  802. unsigned long i;
  803. for (i = 0; i < max_scan; i++) {
  804. struct page *page;
  805. page = radix_tree_lookup(&mapping->page_tree, index);
  806. if (!page || radix_tree_exceptional_entry(page))
  807. break;
  808. index++;
  809. if (index == 0)
  810. break;
  811. }
  812. return index;
  813. }
  814. EXPORT_SYMBOL(page_cache_next_hole);
  815. /**
  816. * page_cache_prev_hole - find the prev hole (not-present entry)
  817. * @mapping: mapping
  818. * @index: index
  819. * @max_scan: maximum range to search
  820. *
  821. * Search backwards in the range [max(index-max_scan+1, 0), index] for
  822. * the first hole.
  823. *
  824. * Returns: the index of the hole if found, otherwise returns an index
  825. * outside of the set specified (in which case 'index - return >=
  826. * max_scan' will be true). In rare cases of wrap-around, ULONG_MAX
  827. * will be returned.
  828. *
  829. * page_cache_prev_hole may be called under rcu_read_lock. However,
  830. * like radix_tree_gang_lookup, this will not atomically search a
  831. * snapshot of the tree at a single point in time. For example, if a
  832. * hole is created at index 10, then subsequently a hole is created at
  833. * index 5, page_cache_prev_hole covering both indexes may return 5 if
  834. * called under rcu_read_lock.
  835. */
  836. pgoff_t page_cache_prev_hole(struct address_space *mapping,
  837. pgoff_t index, unsigned long max_scan)
  838. {
  839. unsigned long i;
  840. for (i = 0; i < max_scan; i++) {
  841. struct page *page;
  842. page = radix_tree_lookup(&mapping->page_tree, index);
  843. if (!page || radix_tree_exceptional_entry(page))
  844. break;
  845. index--;
  846. if (index == ULONG_MAX)
  847. break;
  848. }
  849. return index;
  850. }
  851. EXPORT_SYMBOL(page_cache_prev_hole);
  852. /**
  853. * find_get_entry - find and get a page cache entry
  854. * @mapping: the address_space to search
  855. * @offset: the page cache index
  856. *
  857. * Looks up the page cache slot at @mapping & @offset. If there is a
  858. * page cache page, it is returned with an increased refcount.
  859. *
  860. * If the slot holds a shadow entry of a previously evicted page, or a
  861. * swap entry from shmem/tmpfs, it is returned.
  862. *
  863. * Otherwise, %NULL is returned.
  864. */
  865. struct page *find_get_entry(struct address_space *mapping, pgoff_t offset)
  866. {
  867. void **pagep;
  868. struct page *page;
  869. rcu_read_lock();
  870. repeat:
  871. page = NULL;
  872. pagep = radix_tree_lookup_slot(&mapping->page_tree, offset);
  873. if (pagep) {
  874. page = radix_tree_deref_slot(pagep);
  875. if (unlikely(!page))
  876. goto out;
  877. if (radix_tree_exception(page)) {
  878. if (radix_tree_deref_retry(page))
  879. goto repeat;
  880. /*
  881. * A shadow entry of a recently evicted page,
  882. * or a swap entry from shmem/tmpfs. Return
  883. * it without attempting to raise page count.
  884. */
  885. goto out;
  886. }
  887. if (!page_cache_get_speculative(page))
  888. goto repeat;
  889. /*
  890. * Has the page moved?
  891. * This is part of the lockless pagecache protocol. See
  892. * include/linux/pagemap.h for details.
  893. */
  894. if (unlikely(page != *pagep)) {
  895. page_cache_release(page);
  896. goto repeat;
  897. }
  898. }
  899. out:
  900. rcu_read_unlock();
  901. return page;
  902. }
  903. EXPORT_SYMBOL(find_get_entry);
  904. /**
  905. * find_lock_entry - locate, pin and lock a page cache entry
  906. * @mapping: the address_space to search
  907. * @offset: the page cache index
  908. *
  909. * Looks up the page cache slot at @mapping & @offset. If there is a
  910. * page cache page, it is returned locked and with an increased
  911. * refcount.
  912. *
  913. * If the slot holds a shadow entry of a previously evicted page, or a
  914. * swap entry from shmem/tmpfs, it is returned.
  915. *
  916. * Otherwise, %NULL is returned.
  917. *
  918. * find_lock_entry() may sleep.
  919. */
  920. struct page *find_lock_entry(struct address_space *mapping, pgoff_t offset)
  921. {
  922. struct page *page;
  923. repeat:
  924. page = find_get_entry(mapping, offset);
  925. if (page && !radix_tree_exception(page)) {
  926. lock_page(page);
  927. /* Has the page been truncated? */
  928. if (unlikely(page->mapping != mapping)) {
  929. unlock_page(page);
  930. page_cache_release(page);
  931. goto repeat;
  932. }
  933. VM_BUG_ON_PAGE(page->index != offset, page);
  934. }
  935. return page;
  936. }
  937. EXPORT_SYMBOL(find_lock_entry);
  938. /**
  939. * pagecache_get_page - find and get a page reference
  940. * @mapping: the address_space to search
  941. * @offset: the page index
  942. * @fgp_flags: PCG flags
  943. * @gfp_mask: gfp mask to use for the page cache data page allocation
  944. *
  945. * Looks up the page cache slot at @mapping & @offset.
  946. *
  947. * PCG flags modify how the page is returned.
  948. *
  949. * FGP_ACCESSED: the page will be marked accessed
  950. * FGP_LOCK: Page is return locked
  951. * FGP_CREAT: If page is not present then a new page is allocated using
  952. * @gfp_mask and added to the page cache and the VM's LRU
  953. * list. The page is returned locked and with an increased
  954. * refcount. Otherwise, %NULL is returned.
  955. *
  956. * If FGP_LOCK or FGP_CREAT are specified then the function may sleep even
  957. * if the GFP flags specified for FGP_CREAT are atomic.
  958. *
  959. * If there is a page cache page, it is returned with an increased refcount.
  960. */
  961. struct page *pagecache_get_page(struct address_space *mapping, pgoff_t offset,
  962. int fgp_flags, gfp_t gfp_mask)
  963. {
  964. struct page *page;
  965. repeat:
  966. page = find_get_entry(mapping, offset);
  967. if (radix_tree_exceptional_entry(page))
  968. page = NULL;
  969. if (!page)
  970. goto no_page;
  971. if (fgp_flags & FGP_LOCK) {
  972. if (fgp_flags & FGP_NOWAIT) {
  973. if (!trylock_page(page)) {
  974. page_cache_release(page);
  975. return NULL;
  976. }
  977. } else {
  978. lock_page(page);
  979. }
  980. /* Has the page been truncated? */
  981. if (unlikely(page->mapping != mapping)) {
  982. unlock_page(page);
  983. page_cache_release(page);
  984. goto repeat;
  985. }
  986. VM_BUG_ON_PAGE(page->index != offset, page);
  987. }
  988. if (page && (fgp_flags & FGP_ACCESSED))
  989. mark_page_accessed(page);
  990. no_page:
  991. if (!page && (fgp_flags & FGP_CREAT)) {
  992. int err;
  993. if ((fgp_flags & FGP_WRITE) && mapping_cap_account_dirty(mapping))
  994. gfp_mask |= __GFP_WRITE;
  995. if (fgp_flags & FGP_NOFS)
  996. gfp_mask &= ~__GFP_FS;
  997. page = __page_cache_alloc(gfp_mask);
  998. if (!page)
  999. return NULL;
  1000. if (WARN_ON_ONCE(!(fgp_flags & FGP_LOCK)))
  1001. fgp_flags |= FGP_LOCK;
  1002. /* Init accessed so avoid atomic mark_page_accessed later */
  1003. if (fgp_flags & FGP_ACCESSED)
  1004. __SetPageReferenced(page);
  1005. err = add_to_page_cache_lru(page, mapping, offset,
  1006. gfp_mask & GFP_RECLAIM_MASK);
  1007. if (unlikely(err)) {
  1008. page_cache_release(page);
  1009. page = NULL;
  1010. if (err == -EEXIST)
  1011. goto repeat;
  1012. }
  1013. }
  1014. return page;
  1015. }
  1016. EXPORT_SYMBOL(pagecache_get_page);
  1017. /**
  1018. * find_get_entries - gang pagecache lookup
  1019. * @mapping: The address_space to search
  1020. * @start: The starting page cache index
  1021. * @nr_entries: The maximum number of entries
  1022. * @entries: Where the resulting entries are placed
  1023. * @indices: The cache indices corresponding to the entries in @entries
  1024. *
  1025. * find_get_entries() will search for and return a group of up to
  1026. * @nr_entries entries in the mapping. The entries are placed at
  1027. * @entries. find_get_entries() takes a reference against any actual
  1028. * pages it returns.
  1029. *
  1030. * The search returns a group of mapping-contiguous page cache entries
  1031. * with ascending indexes. There may be holes in the indices due to
  1032. * not-present pages.
  1033. *
  1034. * Any shadow entries of evicted pages, or swap entries from
  1035. * shmem/tmpfs, are included in the returned array.
  1036. *
  1037. * find_get_entries() returns the number of pages and shadow entries
  1038. * which were found.
  1039. */
  1040. unsigned find_get_entries(struct address_space *mapping,
  1041. pgoff_t start, unsigned int nr_entries,
  1042. struct page **entries, pgoff_t *indices)
  1043. {
  1044. void **slot;
  1045. unsigned int ret = 0;
  1046. struct radix_tree_iter iter;
  1047. if (!nr_entries)
  1048. return 0;
  1049. rcu_read_lock();
  1050. restart:
  1051. radix_tree_for_each_slot(slot, &mapping->page_tree, &iter, start) {
  1052. struct page *page;
  1053. repeat:
  1054. page = radix_tree_deref_slot(slot);
  1055. if (unlikely(!page))
  1056. continue;
  1057. if (radix_tree_exception(page)) {
  1058. if (radix_tree_deref_retry(page))
  1059. goto restart;
  1060. /*
  1061. * A shadow entry of a recently evicted page,
  1062. * or a swap entry from shmem/tmpfs. Return
  1063. * it without attempting to raise page count.
  1064. */
  1065. goto export;
  1066. }
  1067. if (!page_cache_get_speculative(page))
  1068. goto repeat;
  1069. /* Has the page moved? */
  1070. if (unlikely(page != *slot)) {
  1071. page_cache_release(page);
  1072. goto repeat;
  1073. }
  1074. export:
  1075. indices[ret] = iter.index;
  1076. entries[ret] = page;
  1077. if (++ret == nr_entries)
  1078. break;
  1079. }
  1080. rcu_read_unlock();
  1081. return ret;
  1082. }
  1083. /**
  1084. * find_get_pages - gang pagecache lookup
  1085. * @mapping: The address_space to search
  1086. * @start: The starting page index
  1087. * @nr_pages: The maximum number of pages
  1088. * @pages: Where the resulting pages are placed
  1089. *
  1090. * find_get_pages() will search for and return a group of up to
  1091. * @nr_pages pages in the mapping. The pages are placed at @pages.
  1092. * find_get_pages() takes a reference against the returned pages.
  1093. *
  1094. * The search returns a group of mapping-contiguous pages with ascending
  1095. * indexes. There may be holes in the indices due to not-present pages.
  1096. *
  1097. * find_get_pages() returns the number of pages which were found.
  1098. */
  1099. unsigned find_get_pages(struct address_space *mapping, pgoff_t start,
  1100. unsigned int nr_pages, struct page **pages)
  1101. {
  1102. struct radix_tree_iter iter;
  1103. void **slot;
  1104. unsigned ret = 0;
  1105. if (unlikely(!nr_pages))
  1106. return 0;
  1107. rcu_read_lock();
  1108. restart:
  1109. radix_tree_for_each_slot(slot, &mapping->page_tree, &iter, start) {
  1110. struct page *page;
  1111. repeat:
  1112. page = radix_tree_deref_slot(slot);
  1113. if (unlikely(!page))
  1114. continue;
  1115. if (radix_tree_exception(page)) {
  1116. if (radix_tree_deref_retry(page)) {
  1117. /*
  1118. * Transient condition which can only trigger
  1119. * when entry at index 0 moves out of or back
  1120. * to root: none yet gotten, safe to restart.
  1121. */
  1122. WARN_ON(iter.index);
  1123. goto restart;
  1124. }
  1125. /*
  1126. * A shadow entry of a recently evicted page,
  1127. * or a swap entry from shmem/tmpfs. Skip
  1128. * over it.
  1129. */
  1130. continue;
  1131. }
  1132. if (!page_cache_get_speculative(page))
  1133. goto repeat;
  1134. /* Has the page moved? */
  1135. if (unlikely(page != *slot)) {
  1136. page_cache_release(page);
  1137. goto repeat;
  1138. }
  1139. pages[ret] = page;
  1140. if (++ret == nr_pages)
  1141. break;
  1142. }
  1143. rcu_read_unlock();
  1144. return ret;
  1145. }
  1146. /**
  1147. * find_get_pages_contig - gang contiguous pagecache lookup
  1148. * @mapping: The address_space to search
  1149. * @index: The starting page index
  1150. * @nr_pages: The maximum number of pages
  1151. * @pages: Where the resulting pages are placed
  1152. *
  1153. * find_get_pages_contig() works exactly like find_get_pages(), except
  1154. * that the returned number of pages are guaranteed to be contiguous.
  1155. *
  1156. * find_get_pages_contig() returns the number of pages which were found.
  1157. */
  1158. unsigned find_get_pages_contig(struct address_space *mapping, pgoff_t index,
  1159. unsigned int nr_pages, struct page **pages)
  1160. {
  1161. struct radix_tree_iter iter;
  1162. void **slot;
  1163. unsigned int ret = 0;
  1164. if (unlikely(!nr_pages))
  1165. return 0;
  1166. rcu_read_lock();
  1167. restart:
  1168. radix_tree_for_each_contig(slot, &mapping->page_tree, &iter, index) {
  1169. struct page *page;
  1170. repeat:
  1171. page = radix_tree_deref_slot(slot);
  1172. /* The hole, there no reason to continue */
  1173. if (unlikely(!page))
  1174. break;
  1175. if (radix_tree_exception(page)) {
  1176. if (radix_tree_deref_retry(page)) {
  1177. /*
  1178. * Transient condition which can only trigger
  1179. * when entry at index 0 moves out of or back
  1180. * to root: none yet gotten, safe to restart.
  1181. */
  1182. goto restart;
  1183. }
  1184. /*
  1185. * A shadow entry of a recently evicted page,
  1186. * or a swap entry from shmem/tmpfs. Stop
  1187. * looking for contiguous pages.
  1188. */
  1189. break;
  1190. }
  1191. if (!page_cache_get_speculative(page))
  1192. goto repeat;
  1193. /* Has the page moved? */
  1194. if (unlikely(page != *slot)) {
  1195. page_cache_release(page);
  1196. goto repeat;
  1197. }
  1198. /*
  1199. * must check mapping and index after taking the ref.
  1200. * otherwise we can get both false positives and false
  1201. * negatives, which is just confusing to the caller.
  1202. */
  1203. if (page->mapping == NULL || page->index != iter.index) {
  1204. page_cache_release(page);
  1205. break;
  1206. }
  1207. pages[ret] = page;
  1208. if (++ret == nr_pages)
  1209. break;
  1210. }
  1211. rcu_read_unlock();
  1212. return ret;
  1213. }
  1214. EXPORT_SYMBOL(find_get_pages_contig);
  1215. /**
  1216. * find_get_pages_tag - find and return pages that match @tag
  1217. * @mapping: the address_space to search
  1218. * @index: the starting page index
  1219. * @tag: the tag index
  1220. * @nr_pages: the maximum number of pages
  1221. * @pages: where the resulting pages are placed
  1222. *
  1223. * Like find_get_pages, except we only return pages which are tagged with
  1224. * @tag. We update @index to index the next page for the traversal.
  1225. */
  1226. unsigned find_get_pages_tag(struct address_space *mapping, pgoff_t *index,
  1227. int tag, unsigned int nr_pages, struct page **pages)
  1228. {
  1229. struct radix_tree_iter iter;
  1230. void **slot;
  1231. unsigned ret = 0;
  1232. if (unlikely(!nr_pages))
  1233. return 0;
  1234. rcu_read_lock();
  1235. restart:
  1236. radix_tree_for_each_tagged(slot, &mapping->page_tree,
  1237. &iter, *index, tag) {
  1238. struct page *page;
  1239. repeat:
  1240. page = radix_tree_deref_slot(slot);
  1241. if (unlikely(!page))
  1242. continue;
  1243. if (radix_tree_exception(page)) {
  1244. if (radix_tree_deref_retry(page)) {
  1245. /*
  1246. * Transient condition which can only trigger
  1247. * when entry at index 0 moves out of or back
  1248. * to root: none yet gotten, safe to restart.
  1249. */
  1250. goto restart;
  1251. }
  1252. /*
  1253. * A shadow entry of a recently evicted page.
  1254. *
  1255. * Those entries should never be tagged, but
  1256. * this tree walk is lockless and the tags are
  1257. * looked up in bulk, one radix tree node at a
  1258. * time, so there is a sizable window for page
  1259. * reclaim to evict a page we saw tagged.
  1260. *
  1261. * Skip over it.
  1262. */
  1263. continue;
  1264. }
  1265. if (!page_cache_get_speculative(page))
  1266. goto repeat;
  1267. /* Has the page moved? */
  1268. if (unlikely(page != *slot)) {
  1269. page_cache_release(page);
  1270. goto repeat;
  1271. }
  1272. pages[ret] = page;
  1273. if (++ret == nr_pages)
  1274. break;
  1275. }
  1276. rcu_read_unlock();
  1277. if (ret)
  1278. *index = pages[ret - 1]->index + 1;
  1279. return ret;
  1280. }
  1281. EXPORT_SYMBOL(find_get_pages_tag);
  1282. /*
  1283. * CD/DVDs are error prone. When a medium error occurs, the driver may fail
  1284. * a _large_ part of the i/o request. Imagine the worst scenario:
  1285. *
  1286. * ---R__________________________________________B__________
  1287. * ^ reading here ^ bad block(assume 4k)
  1288. *
  1289. * read(R) => miss => readahead(R...B) => media error => frustrating retries
  1290. * => failing the whole request => read(R) => read(R+1) =>
  1291. * readahead(R+1...B+1) => bang => read(R+2) => read(R+3) =>
  1292. * readahead(R+3...B+2) => bang => read(R+3) => read(R+4) =>
  1293. * readahead(R+4...B+3) => bang => read(R+4) => read(R+5) => ......
  1294. *
  1295. * It is going insane. Fix it by quickly scaling down the readahead size.
  1296. */
  1297. static void shrink_readahead_size_eio(struct file *filp,
  1298. struct file_ra_state *ra)
  1299. {
  1300. ra->ra_pages /= 4;
  1301. }
  1302. /**
  1303. * do_generic_file_read - generic file read routine
  1304. * @filp: the file to read
  1305. * @ppos: current file position
  1306. * @iter: data destination
  1307. * @written: already copied
  1308. *
  1309. * This is a generic file read routine, and uses the
  1310. * mapping->a_ops->readpage() function for the actual low-level stuff.
  1311. *
  1312. * This is really ugly. But the goto's actually try to clarify some
  1313. * of the logic when it comes to error handling etc.
  1314. */
  1315. static ssize_t do_generic_file_read(struct file *filp, loff_t *ppos,
  1316. struct iov_iter *iter, ssize_t written)
  1317. {
  1318. struct address_space *mapping = filp->f_mapping;
  1319. struct inode *inode = mapping->host;
  1320. struct file_ra_state *ra = &filp->f_ra;
  1321. pgoff_t index;
  1322. pgoff_t last_index;
  1323. pgoff_t prev_index;
  1324. unsigned long offset; /* offset into pagecache page */
  1325. unsigned int prev_offset;
  1326. int error = 0;
  1327. index = *ppos >> PAGE_CACHE_SHIFT;
  1328. prev_index = ra->prev_pos >> PAGE_CACHE_SHIFT;
  1329. prev_offset = ra->prev_pos & (PAGE_CACHE_SIZE-1);
  1330. last_index = (*ppos + iter->count + PAGE_CACHE_SIZE-1) >> PAGE_CACHE_SHIFT;
  1331. offset = *ppos & ~PAGE_CACHE_MASK;
  1332. for (;;) {
  1333. struct page *page;
  1334. pgoff_t end_index;
  1335. loff_t isize;
  1336. unsigned long nr, ret;
  1337. cond_resched();
  1338. find_page:
  1339. page = find_get_page(mapping, index);
  1340. if (!page) {
  1341. page_cache_sync_readahead(mapping,
  1342. ra, filp,
  1343. index, last_index - index);
  1344. page = find_get_page(mapping, index);
  1345. if (unlikely(page == NULL))
  1346. goto no_cached_page;
  1347. }
  1348. if (PageReadahead(page)) {
  1349. page_cache_async_readahead(mapping,
  1350. ra, filp, page,
  1351. index, last_index - index);
  1352. }
  1353. if (!PageUptodate(page)) {
  1354. if (inode->i_blkbits == PAGE_CACHE_SHIFT ||
  1355. !mapping->a_ops->is_partially_uptodate)
  1356. goto page_not_up_to_date;
  1357. if (!trylock_page(page))
  1358. goto page_not_up_to_date;
  1359. /* Did it get truncated before we got the lock? */
  1360. if (!page->mapping)
  1361. goto page_not_up_to_date_locked;
  1362. if (!mapping->a_ops->is_partially_uptodate(page,
  1363. offset, iter->count))
  1364. goto page_not_up_to_date_locked;
  1365. unlock_page(page);
  1366. }
  1367. page_ok:
  1368. /*
  1369. * i_size must be checked after we know the page is Uptodate.
  1370. *
  1371. * Checking i_size after the check allows us to calculate
  1372. * the correct value for "nr", which means the zero-filled
  1373. * part of the page is not copied back to userspace (unless
  1374. * another truncate extends the file - this is desired though).
  1375. */
  1376. isize = i_size_read(inode);
  1377. end_index = (isize - 1) >> PAGE_CACHE_SHIFT;
  1378. if (unlikely(!isize || index > end_index)) {
  1379. page_cache_release(page);
  1380. goto out;
  1381. }
  1382. /* nr is the maximum number of bytes to copy from this page */
  1383. nr = PAGE_CACHE_SIZE;
  1384. if (index == end_index) {
  1385. nr = ((isize - 1) & ~PAGE_CACHE_MASK) + 1;
  1386. if (nr <= offset) {
  1387. page_cache_release(page);
  1388. goto out;
  1389. }
  1390. }
  1391. nr = nr - offset;
  1392. /* If users can be writing to this page using arbitrary
  1393. * virtual addresses, take care about potential aliasing
  1394. * before reading the page on the kernel side.
  1395. */
  1396. if (mapping_writably_mapped(mapping))
  1397. flush_dcache_page(page);
  1398. /*
  1399. * When a sequential read accesses a page several times,
  1400. * only mark it as accessed the first time.
  1401. */
  1402. if (prev_index != index || offset != prev_offset)
  1403. mark_page_accessed(page);
  1404. prev_index = index;
  1405. /*
  1406. * Ok, we have the page, and it's up-to-date, so
  1407. * now we can copy it to user space...
  1408. */
  1409. ret = copy_page_to_iter(page, offset, nr, iter);
  1410. offset += ret;
  1411. index += offset >> PAGE_CACHE_SHIFT;
  1412. offset &= ~PAGE_CACHE_MASK;
  1413. prev_offset = offset;
  1414. page_cache_release(page);
  1415. written += ret;
  1416. if (!iov_iter_count(iter))
  1417. goto out;
  1418. if (ret < nr) {
  1419. error = -EFAULT;
  1420. goto out;
  1421. }
  1422. continue;
  1423. page_not_up_to_date:
  1424. /* Get exclusive access to the page ... */
  1425. error = lock_page_killable(page);
  1426. if (unlikely(error))
  1427. goto readpage_error;
  1428. page_not_up_to_date_locked:
  1429. /* Did it get truncated before we got the lock? */
  1430. if (!page->mapping) {
  1431. unlock_page(page);
  1432. page_cache_release(page);
  1433. continue;
  1434. }
  1435. /* Did somebody else fill it already? */
  1436. if (PageUptodate(page)) {
  1437. unlock_page(page);
  1438. goto page_ok;
  1439. }
  1440. readpage:
  1441. /*
  1442. * A previous I/O error may have been due to temporary
  1443. * failures, eg. multipath errors.
  1444. * PG_error will be set again if readpage fails.
  1445. */
  1446. ClearPageError(page);
  1447. /* Start the actual read. The read will unlock the page. */
  1448. error = mapping->a_ops->readpage(filp, page);
  1449. if (unlikely(error)) {
  1450. if (error == AOP_TRUNCATED_PAGE) {
  1451. page_cache_release(page);
  1452. error = 0;
  1453. goto find_page;
  1454. }
  1455. goto readpage_error;
  1456. }
  1457. if (!PageUptodate(page)) {
  1458. error = lock_page_killable(page);
  1459. if (unlikely(error))
  1460. goto readpage_error;
  1461. if (!PageUptodate(page)) {
  1462. if (page->mapping == NULL) {
  1463. /*
  1464. * invalidate_mapping_pages got it
  1465. */
  1466. unlock_page(page);
  1467. page_cache_release(page);
  1468. goto find_page;
  1469. }
  1470. unlock_page(page);
  1471. shrink_readahead_size_eio(filp, ra);
  1472. error = -EIO;
  1473. goto readpage_error;
  1474. }
  1475. unlock_page(page);
  1476. }
  1477. goto page_ok;
  1478. readpage_error:
  1479. /* UHHUH! A synchronous read error occurred. Report it */
  1480. page_cache_release(page);
  1481. goto out;
  1482. no_cached_page:
  1483. /*
  1484. * Ok, it wasn't cached, so we need to create a new
  1485. * page..
  1486. */
  1487. page = page_cache_alloc_cold(mapping);
  1488. if (!page) {
  1489. error = -ENOMEM;
  1490. goto out;
  1491. }
  1492. error = add_to_page_cache_lru(page, mapping,
  1493. index, GFP_KERNEL);
  1494. if (error) {
  1495. page_cache_release(page);
  1496. if (error == -EEXIST) {
  1497. error = 0;
  1498. goto find_page;
  1499. }
  1500. goto out;
  1501. }
  1502. goto readpage;
  1503. }
  1504. out:
  1505. ra->prev_pos = prev_index;
  1506. ra->prev_pos <<= PAGE_CACHE_SHIFT;
  1507. ra->prev_pos |= prev_offset;
  1508. *ppos = ((loff_t)index << PAGE_CACHE_SHIFT) + offset;
  1509. file_accessed(filp);
  1510. return written ? written : error;
  1511. }
  1512. /**
  1513. * generic_file_read_iter - generic filesystem read routine
  1514. * @iocb: kernel I/O control block
  1515. * @iter: destination for the data read
  1516. *
  1517. * This is the "read_iter()" routine for all filesystems
  1518. * that can use the page cache directly.
  1519. */
  1520. ssize_t
  1521. generic_file_read_iter(struct kiocb *iocb, struct iov_iter *iter)
  1522. {
  1523. struct file *file = iocb->ki_filp;
  1524. ssize_t retval = 0;
  1525. loff_t *ppos = &iocb->ki_pos;
  1526. loff_t pos = *ppos;
  1527. /* coalesce the iovecs and go direct-to-BIO for O_DIRECT */
  1528. if (file->f_flags & O_DIRECT) {
  1529. struct address_space *mapping = file->f_mapping;
  1530. struct inode *inode = mapping->host;
  1531. size_t count = iov_iter_count(iter);
  1532. loff_t size;
  1533. if (!count)
  1534. goto out; /* skip atime */
  1535. size = i_size_read(inode);
  1536. retval = filemap_write_and_wait_range(mapping, pos,
  1537. pos + count - 1);
  1538. if (!retval) {
  1539. struct iov_iter data = *iter;
  1540. retval = mapping->a_ops->direct_IO(READ, iocb, &data, pos);
  1541. }
  1542. if (retval > 0) {
  1543. *ppos = pos + retval;
  1544. iov_iter_advance(iter, retval);
  1545. }
  1546. /*
  1547. * Btrfs can have a short DIO read if we encounter
  1548. * compressed extents, so if there was an error, or if
  1549. * we've already read everything we wanted to, or if
  1550. * there was a short read because we hit EOF, go ahead
  1551. * and return. Otherwise fallthrough to buffered io for
  1552. * the rest of the read.
  1553. */
  1554. if (retval < 0 || !iov_iter_count(iter) || *ppos >= size) {
  1555. file_accessed(file);
  1556. goto out;
  1557. }
  1558. }
  1559. retval = do_generic_file_read(file, ppos, iter, retval);
  1560. out:
  1561. return retval;
  1562. }
  1563. EXPORT_SYMBOL(generic_file_read_iter);
  1564. #ifdef CONFIG_MMU
  1565. /**
  1566. * page_cache_read - adds requested page to the page cache if not already there
  1567. * @file: file to read
  1568. * @offset: page index
  1569. *
  1570. * This adds the requested page to the page cache if it isn't already there,
  1571. * and schedules an I/O to read in its contents from disk.
  1572. */
  1573. static int page_cache_read(struct file *file, pgoff_t offset)
  1574. {
  1575. struct address_space *mapping = file->f_mapping;
  1576. struct page *page;
  1577. int ret;
  1578. do {
  1579. page = page_cache_alloc_cold(mapping);
  1580. if (!page)
  1581. return -ENOMEM;
  1582. ret = add_to_page_cache_lru(page, mapping, offset, GFP_KERNEL);
  1583. if (ret == 0)
  1584. ret = mapping->a_ops->readpage(file, page);
  1585. else if (ret == -EEXIST)
  1586. ret = 0; /* losing race to add is OK */
  1587. page_cache_release(page);
  1588. } while (ret == AOP_TRUNCATED_PAGE);
  1589. return ret;
  1590. }
  1591. #define MMAP_LOTSAMISS (100)
  1592. /*
  1593. * Synchronous readahead happens when we don't even find
  1594. * a page in the page cache at all.
  1595. */
  1596. static void do_sync_mmap_readahead(struct vm_area_struct *vma,
  1597. struct file_ra_state *ra,
  1598. struct file *file,
  1599. pgoff_t offset)
  1600. {
  1601. unsigned long ra_pages;
  1602. struct address_space *mapping = file->f_mapping;
  1603. /* If we don't want any read-ahead, don't bother */
  1604. if (vma->vm_flags & VM_RAND_READ)
  1605. return;
  1606. if (!ra->ra_pages)
  1607. return;
  1608. if (vma->vm_flags & VM_SEQ_READ) {
  1609. page_cache_sync_readahead(mapping, ra, file, offset,
  1610. ra->ra_pages);
  1611. return;
  1612. }
  1613. /* Avoid banging the cache line if not needed */
  1614. if (ra->mmap_miss < MMAP_LOTSAMISS * 10)
  1615. ra->mmap_miss++;
  1616. /*
  1617. * Do we miss much more than hit in this file? If so,
  1618. * stop bothering with read-ahead. It will only hurt.
  1619. */
  1620. if (ra->mmap_miss > MMAP_LOTSAMISS)
  1621. return;
  1622. /*
  1623. * mmap read-around
  1624. */
  1625. ra_pages = max_sane_readahead(ra->ra_pages);
  1626. ra->start = max_t(long, 0, offset - ra_pages / 2);
  1627. ra->size = ra_pages;
  1628. ra->async_size = ra_pages / 4;
  1629. ra_submit(ra, mapping, file);
  1630. }
  1631. /*
  1632. * Asynchronous readahead happens when we find the page and PG_readahead,
  1633. * so we want to possibly extend the readahead further..
  1634. */
  1635. static void do_async_mmap_readahead(struct vm_area_struct *vma,
  1636. struct file_ra_state *ra,
  1637. struct file *file,
  1638. struct page *page,
  1639. pgoff_t offset)
  1640. {
  1641. struct address_space *mapping = file->f_mapping;
  1642. /* If we don't want any read-ahead, don't bother */
  1643. if (vma->vm_flags & VM_RAND_READ)
  1644. return;
  1645. if (ra->mmap_miss > 0)
  1646. ra->mmap_miss--;
  1647. if (PageReadahead(page))
  1648. page_cache_async_readahead(mapping, ra, file,
  1649. page, offset, ra->ra_pages);
  1650. }
  1651. /**
  1652. * filemap_fault - read in file data for page fault handling
  1653. * @vma: vma in which the fault was taken
  1654. * @vmf: struct vm_fault containing details of the fault
  1655. *
  1656. * filemap_fault() is invoked via the vma operations vector for a
  1657. * mapped memory region to read in file data during a page fault.
  1658. *
  1659. * The goto's are kind of ugly, but this streamlines the normal case of having
  1660. * it in the page cache, and handles the special cases reasonably without
  1661. * having a lot of duplicated code.
  1662. *
  1663. * vma->vm_mm->mmap_sem must be held on entry.
  1664. *
  1665. * If our return value has VM_FAULT_RETRY set, it's because
  1666. * lock_page_or_retry() returned 0.
  1667. * The mmap_sem has usually been released in this case.
  1668. * See __lock_page_or_retry() for the exception.
  1669. *
  1670. * If our return value does not have VM_FAULT_RETRY set, the mmap_sem
  1671. * has not been released.
  1672. *
  1673. * We never return with VM_FAULT_RETRY and a bit from VM_FAULT_ERROR set.
  1674. */
  1675. int filemap_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
  1676. {
  1677. int error;
  1678. struct file *file = vma->vm_file;
  1679. struct address_space *mapping = file->f_mapping;
  1680. struct file_ra_state *ra = &file->f_ra;
  1681. struct inode *inode = mapping->host;
  1682. pgoff_t offset = vmf->pgoff;
  1683. struct page *page;
  1684. loff_t size;
  1685. int ret = 0;
  1686. size = round_up(i_size_read(inode), PAGE_CACHE_SIZE);
  1687. if (offset >= size >> PAGE_CACHE_SHIFT)
  1688. return VM_FAULT_SIGBUS;
  1689. /*
  1690. * Do we have something in the page cache already?
  1691. */
  1692. page = find_get_page(mapping, offset);
  1693. if (likely(page) && !(vmf->flags & FAULT_FLAG_TRIED)) {
  1694. /*
  1695. * We found the page, so try async readahead before
  1696. * waiting for the lock.
  1697. */
  1698. do_async_mmap_readahead(vma, ra, file, page, offset);
  1699. } else if (!page) {
  1700. /* No page in the page cache at all */
  1701. do_sync_mmap_readahead(vma, ra, file, offset);
  1702. count_vm_event(PGMAJFAULT);
  1703. mem_cgroup_count_vm_event(vma->vm_mm, PGMAJFAULT);
  1704. ret = VM_FAULT_MAJOR;
  1705. retry_find:
  1706. page = find_get_page(mapping, offset);
  1707. if (!page)
  1708. goto no_cached_page;
  1709. }
  1710. if (!lock_page_or_retry(page, vma->vm_mm, vmf->flags)) {
  1711. page_cache_release(page);
  1712. return ret | VM_FAULT_RETRY;
  1713. }
  1714. /* Did it get truncated? */
  1715. if (unlikely(page->mapping != mapping)) {
  1716. unlock_page(page);
  1717. put_page(page);
  1718. goto retry_find;
  1719. }
  1720. VM_BUG_ON_PAGE(page->index != offset, page);
  1721. /*
  1722. * We have a locked page in the page cache, now we need to check
  1723. * that it's up-to-date. If not, it is going to be due to an error.
  1724. */
  1725. if (unlikely(!PageUptodate(page)))
  1726. goto page_not_uptodate;
  1727. /*
  1728. * Found the page and have a reference on it.
  1729. * We must recheck i_size under page lock.
  1730. */
  1731. size = round_up(i_size_read(inode), PAGE_CACHE_SIZE);
  1732. if (unlikely(offset >= size >> PAGE_CACHE_SHIFT)) {
  1733. unlock_page(page);
  1734. page_cache_release(page);
  1735. return VM_FAULT_SIGBUS;
  1736. }
  1737. vmf->page = page;
  1738. return ret | VM_FAULT_LOCKED;
  1739. no_cached_page:
  1740. /*
  1741. * We're only likely to ever get here if MADV_RANDOM is in
  1742. * effect.
  1743. */
  1744. error = page_cache_read(file, offset);
  1745. /*
  1746. * The page we want has now been added to the page cache.
  1747. * In the unlikely event that someone removed it in the
  1748. * meantime, we'll just come back here and read it again.
  1749. */
  1750. if (error >= 0)
  1751. goto retry_find;
  1752. /*
  1753. * An error return from page_cache_read can result if the
  1754. * system is low on memory, or a problem occurs while trying
  1755. * to schedule I/O.
  1756. */
  1757. if (error == -ENOMEM)
  1758. return VM_FAULT_OOM;
  1759. return VM_FAULT_SIGBUS;
  1760. page_not_uptodate:
  1761. /*
  1762. * Umm, take care of errors if the page isn't up-to-date.
  1763. * Try to re-read it _once_. We do this synchronously,
  1764. * because there really aren't any performance issues here
  1765. * and we need to check for errors.
  1766. */
  1767. ClearPageError(page);
  1768. error = mapping->a_ops->readpage(file, page);
  1769. if (!error) {
  1770. wait_on_page_locked(page);
  1771. if (!PageUptodate(page))
  1772. error = -EIO;
  1773. }
  1774. page_cache_release(page);
  1775. if (!error || error == AOP_TRUNCATED_PAGE)
  1776. goto retry_find;
  1777. /* Things didn't work out. Return zero to tell the mm layer so. */
  1778. shrink_readahead_size_eio(file, ra);
  1779. return VM_FAULT_SIGBUS;
  1780. }
  1781. EXPORT_SYMBOL(filemap_fault);
  1782. void filemap_map_pages(struct vm_area_struct *vma, struct vm_fault *vmf)
  1783. {
  1784. struct radix_tree_iter iter;
  1785. void **slot;
  1786. struct file *file = vma->vm_file;
  1787. struct address_space *mapping = file->f_mapping;
  1788. loff_t size;
  1789. struct page *page;
  1790. unsigned long address = (unsigned long) vmf->virtual_address;
  1791. unsigned long addr;
  1792. pte_t *pte;
  1793. rcu_read_lock();
  1794. radix_tree_for_each_slot(slot, &mapping->page_tree, &iter, vmf->pgoff) {
  1795. if (iter.index > vmf->max_pgoff)
  1796. break;
  1797. repeat:
  1798. page = radix_tree_deref_slot(slot);
  1799. if (unlikely(!page))
  1800. goto next;
  1801. if (radix_tree_exception(page)) {
  1802. if (radix_tree_deref_retry(page))
  1803. break;
  1804. else
  1805. goto next;
  1806. }
  1807. if (!page_cache_get_speculative(page))
  1808. goto repeat;
  1809. /* Has the page moved? */
  1810. if (unlikely(page != *slot)) {
  1811. page_cache_release(page);
  1812. goto repeat;
  1813. }
  1814. if (!PageUptodate(page) ||
  1815. PageReadahead(page) ||
  1816. PageHWPoison(page))
  1817. goto skip;
  1818. if (!trylock_page(page))
  1819. goto skip;
  1820. if (page->mapping != mapping || !PageUptodate(page))
  1821. goto unlock;
  1822. size = round_up(i_size_read(mapping->host), PAGE_CACHE_SIZE);
  1823. if (page->index >= size >> PAGE_CACHE_SHIFT)
  1824. goto unlock;
  1825. pte = vmf->pte + page->index - vmf->pgoff;
  1826. if (!pte_none(*pte))
  1827. goto unlock;
  1828. if (file->f_ra.mmap_miss > 0)
  1829. file->f_ra.mmap_miss--;
  1830. addr = address + (page->index - vmf->pgoff) * PAGE_SIZE;
  1831. do_set_pte(vma, addr, page, pte, false, false);
  1832. unlock_page(page);
  1833. goto next;
  1834. unlock:
  1835. unlock_page(page);
  1836. skip:
  1837. page_cache_release(page);
  1838. next:
  1839. if (iter.index == vmf->max_pgoff)
  1840. break;
  1841. }
  1842. rcu_read_unlock();
  1843. }
  1844. EXPORT_SYMBOL(filemap_map_pages);
  1845. int filemap_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf)
  1846. {
  1847. struct page *page = vmf->page;
  1848. struct inode *inode = file_inode(vma->vm_file);
  1849. int ret = VM_FAULT_LOCKED;
  1850. sb_start_pagefault(inode->i_sb);
  1851. file_update_time(vma->vm_file);
  1852. lock_page(page);
  1853. if (page->mapping != inode->i_mapping) {
  1854. unlock_page(page);
  1855. ret = VM_FAULT_NOPAGE;
  1856. goto out;
  1857. }
  1858. /*
  1859. * We mark the page dirty already here so that when freeze is in
  1860. * progress, we are guaranteed that writeback during freezing will
  1861. * see the dirty page and writeprotect it again.
  1862. */
  1863. set_page_dirty(page);
  1864. wait_for_stable_page(page);
  1865. out:
  1866. sb_end_pagefault(inode->i_sb);
  1867. return ret;
  1868. }
  1869. EXPORT_SYMBOL(filemap_page_mkwrite);
  1870. const struct vm_operations_struct generic_file_vm_ops = {
  1871. .fault = filemap_fault,
  1872. .map_pages = filemap_map_pages,
  1873. .page_mkwrite = filemap_page_mkwrite,
  1874. .remap_pages = generic_file_remap_pages,
  1875. };
  1876. /* This is used for a general mmap of a disk file */
  1877. int generic_file_mmap(struct file * file, struct vm_area_struct * vma)
  1878. {
  1879. struct address_space *mapping = file->f_mapping;
  1880. if (!mapping->a_ops->readpage)
  1881. return -ENOEXEC;
  1882. file_accessed(file);
  1883. vma->vm_ops = &generic_file_vm_ops;
  1884. return 0;
  1885. }
  1886. /*
  1887. * This is for filesystems which do not implement ->writepage.
  1888. */
  1889. int generic_file_readonly_mmap(struct file *file, struct vm_area_struct *vma)
  1890. {
  1891. if ((vma->vm_flags & VM_SHARED) && (vma->vm_flags & VM_MAYWRITE))
  1892. return -EINVAL;
  1893. return generic_file_mmap(file, vma);
  1894. }
  1895. #else
  1896. int generic_file_mmap(struct file * file, struct vm_area_struct * vma)
  1897. {
  1898. return -ENOSYS;
  1899. }
  1900. int generic_file_readonly_mmap(struct file * file, struct vm_area_struct * vma)
  1901. {
  1902. return -ENOSYS;
  1903. }
  1904. #endif /* CONFIG_MMU */
  1905. EXPORT_SYMBOL(generic_file_mmap);
  1906. EXPORT_SYMBOL(generic_file_readonly_mmap);
  1907. static struct page *wait_on_page_read(struct page *page)
  1908. {
  1909. if (!IS_ERR(page)) {
  1910. wait_on_page_locked(page);
  1911. if (!PageUptodate(page)) {
  1912. page_cache_release(page);
  1913. page = ERR_PTR(-EIO);
  1914. }
  1915. }
  1916. return page;
  1917. }
  1918. static struct page *__read_cache_page(struct address_space *mapping,
  1919. pgoff_t index,
  1920. int (*filler)(void *, struct page *),
  1921. void *data,
  1922. gfp_t gfp)
  1923. {
  1924. struct page *page;
  1925. int err;
  1926. repeat:
  1927. page = find_get_page(mapping, index);
  1928. if (!page) {
  1929. page = __page_cache_alloc(gfp | __GFP_COLD);
  1930. if (!page)
  1931. return ERR_PTR(-ENOMEM);
  1932. err = add_to_page_cache_lru(page, mapping, index, gfp);
  1933. if (unlikely(err)) {
  1934. page_cache_release(page);
  1935. if (err == -EEXIST)
  1936. goto repeat;
  1937. /* Presumably ENOMEM for radix tree node */
  1938. return ERR_PTR(err);
  1939. }
  1940. err = filler(data, page);
  1941. if (err < 0) {
  1942. page_cache_release(page);
  1943. page = ERR_PTR(err);
  1944. } else {
  1945. page = wait_on_page_read(page);
  1946. }
  1947. }
  1948. return page;
  1949. }
  1950. static struct page *do_read_cache_page(struct address_space *mapping,
  1951. pgoff_t index,
  1952. int (*filler)(void *, struct page *),
  1953. void *data,
  1954. gfp_t gfp)
  1955. {
  1956. struct page *page;
  1957. int err;
  1958. retry:
  1959. page = __read_cache_page(mapping, index, filler, data, gfp);
  1960. if (IS_ERR(page))
  1961. return page;
  1962. if (PageUptodate(page))
  1963. goto out;
  1964. lock_page(page);
  1965. if (!page->mapping) {
  1966. unlock_page(page);
  1967. page_cache_release(page);
  1968. goto retry;
  1969. }
  1970. if (PageUptodate(page)) {
  1971. unlock_page(page);
  1972. goto out;
  1973. }
  1974. err = filler(data, page);
  1975. if (err < 0) {
  1976. page_cache_release(page);
  1977. return ERR_PTR(err);
  1978. } else {
  1979. page = wait_on_page_read(page);
  1980. if (IS_ERR(page))
  1981. return page;
  1982. }
  1983. out:
  1984. mark_page_accessed(page);
  1985. return page;
  1986. }
  1987. /**
  1988. * read_cache_page - read into page cache, fill it if needed
  1989. * @mapping: the page's address_space
  1990. * @index: the page index
  1991. * @filler: function to perform the read
  1992. * @data: first arg to filler(data, page) function, often left as NULL
  1993. *
  1994. * Read into the page cache. If a page already exists, and PageUptodate() is
  1995. * not set, try to fill the page and wait for it to become unlocked.
  1996. *
  1997. * If the page does not get brought uptodate, return -EIO.
  1998. */
  1999. struct page *read_cache_page(struct address_space *mapping,
  2000. pgoff_t index,
  2001. int (*filler)(void *, struct page *),
  2002. void *data)
  2003. {
  2004. return do_read_cache_page(mapping, index, filler, data, mapping_gfp_mask(mapping));
  2005. }
  2006. EXPORT_SYMBOL(read_cache_page);
  2007. /**
  2008. * read_cache_page_gfp - read into page cache, using specified page allocation flags.
  2009. * @mapping: the page's address_space
  2010. * @index: the page index
  2011. * @gfp: the page allocator flags to use if allocating
  2012. *
  2013. * This is the same as "read_mapping_page(mapping, index, NULL)", but with
  2014. * any new page allocations done using the specified allocation flags.
  2015. *
  2016. * If the page does not get brought uptodate, return -EIO.
  2017. */
  2018. struct page *read_cache_page_gfp(struct address_space *mapping,
  2019. pgoff_t index,
  2020. gfp_t gfp)
  2021. {
  2022. filler_t *filler = (filler_t *)mapping->a_ops->readpage;
  2023. return do_read_cache_page(mapping, index, filler, NULL, gfp);
  2024. }
  2025. EXPORT_SYMBOL(read_cache_page_gfp);
  2026. /*
  2027. * Performs necessary checks before doing a write
  2028. *
  2029. * Can adjust writing position or amount of bytes to write.
  2030. * Returns appropriate error code that caller should return or
  2031. * zero in case that write should be allowed.
  2032. */
  2033. inline int generic_write_checks(struct file *file, loff_t *pos, size_t *count, int isblk)
  2034. {
  2035. struct inode *inode = file->f_mapping->host;
  2036. unsigned long limit = rlimit(RLIMIT_FSIZE);
  2037. if (unlikely(*pos < 0))
  2038. return -EINVAL;
  2039. if (!isblk) {
  2040. /* FIXME: this is for backwards compatibility with 2.4 */
  2041. if (file->f_flags & O_APPEND)
  2042. *pos = i_size_read(inode);
  2043. if (limit != RLIM_INFINITY) {
  2044. if (*pos >= limit) {
  2045. send_sig(SIGXFSZ, current, 0);
  2046. return -EFBIG;
  2047. }
  2048. if (*count > limit - (typeof(limit))*pos) {
  2049. *count = limit - (typeof(limit))*pos;
  2050. }
  2051. }
  2052. }
  2053. /*
  2054. * LFS rule
  2055. */
  2056. if (unlikely(*pos + *count > MAX_NON_LFS &&
  2057. !(file->f_flags & O_LARGEFILE))) {
  2058. if (*pos >= MAX_NON_LFS) {
  2059. return -EFBIG;
  2060. }
  2061. if (*count > MAX_NON_LFS - (unsigned long)*pos) {
  2062. *count = MAX_NON_LFS - (unsigned long)*pos;
  2063. }
  2064. }
  2065. /*
  2066. * Are we about to exceed the fs block limit ?
  2067. *
  2068. * If we have written data it becomes a short write. If we have
  2069. * exceeded without writing data we send a signal and return EFBIG.
  2070. * Linus frestrict idea will clean these up nicely..
  2071. */
  2072. if (likely(!isblk)) {
  2073. if (unlikely(*pos >= inode->i_sb->s_maxbytes)) {
  2074. if (*count || *pos > inode->i_sb->s_maxbytes) {
  2075. return -EFBIG;
  2076. }
  2077. /* zero-length writes at ->s_maxbytes are OK */
  2078. }
  2079. if (unlikely(*pos + *count > inode->i_sb->s_maxbytes))
  2080. *count = inode->i_sb->s_maxbytes - *pos;
  2081. } else {
  2082. #ifdef CONFIG_BLOCK
  2083. loff_t isize;
  2084. if (bdev_read_only(I_BDEV(inode)))
  2085. return -EPERM;
  2086. isize = i_size_read(inode);
  2087. if (*pos >= isize) {
  2088. if (*count || *pos > isize)
  2089. return -ENOSPC;
  2090. }
  2091. if (*pos + *count > isize)
  2092. *count = isize - *pos;
  2093. #else
  2094. return -EPERM;
  2095. #endif
  2096. }
  2097. return 0;
  2098. }
  2099. EXPORT_SYMBOL(generic_write_checks);
  2100. int pagecache_write_begin(struct file *file, struct address_space *mapping,
  2101. loff_t pos, unsigned len, unsigned flags,
  2102. struct page **pagep, void **fsdata)
  2103. {
  2104. const struct address_space_operations *aops = mapping->a_ops;
  2105. return aops->write_begin(file, mapping, pos, len, flags,
  2106. pagep, fsdata);
  2107. }
  2108. EXPORT_SYMBOL(pagecache_write_begin);
  2109. int pagecache_write_end(struct file *file, struct address_space *mapping,
  2110. loff_t pos, unsigned len, unsigned copied,
  2111. struct page *page, void *fsdata)
  2112. {
  2113. const struct address_space_operations *aops = mapping->a_ops;
  2114. return aops->write_end(file, mapping, pos, len, copied, page, fsdata);
  2115. }
  2116. EXPORT_SYMBOL(pagecache_write_end);
  2117. ssize_t
  2118. generic_file_direct_write(struct kiocb *iocb, struct iov_iter *from, loff_t pos)
  2119. {
  2120. struct file *file = iocb->ki_filp;
  2121. struct address_space *mapping = file->f_mapping;
  2122. struct inode *inode = mapping->host;
  2123. ssize_t written;
  2124. size_t write_len;
  2125. pgoff_t end;
  2126. struct iov_iter data;
  2127. write_len = iov_iter_count(from);
  2128. end = (pos + write_len - 1) >> PAGE_CACHE_SHIFT;
  2129. written = filemap_write_and_wait_range(mapping, pos, pos + write_len - 1);
  2130. if (written)
  2131. goto out;
  2132. /*
  2133. * After a write we want buffered reads to be sure to go to disk to get
  2134. * the new data. We invalidate clean cached page from the region we're
  2135. * about to write. We do this *before* the write so that we can return
  2136. * without clobbering -EIOCBQUEUED from ->direct_IO().
  2137. */
  2138. if (mapping->nrpages) {
  2139. written = invalidate_inode_pages2_range(mapping,
  2140. pos >> PAGE_CACHE_SHIFT, end);
  2141. /*
  2142. * If a page can not be invalidated, return 0 to fall back
  2143. * to buffered write.
  2144. */
  2145. if (written) {
  2146. if (written == -EBUSY)
  2147. return 0;
  2148. goto out;
  2149. }
  2150. }
  2151. data = *from;
  2152. written = mapping->a_ops->direct_IO(WRITE, iocb, &data, pos);
  2153. /*
  2154. * Finally, try again to invalidate clean pages which might have been
  2155. * cached by non-direct readahead, or faulted in by get_user_pages()
  2156. * if the source of the write was an mmap'ed region of the file
  2157. * we're writing. Either one is a pretty crazy thing to do,
  2158. * so we don't support it 100%. If this invalidation
  2159. * fails, tough, the write still worked...
  2160. */
  2161. if (mapping->nrpages) {
  2162. invalidate_inode_pages2_range(mapping,
  2163. pos >> PAGE_CACHE_SHIFT, end);
  2164. }
  2165. if (written > 0) {
  2166. pos += written;
  2167. iov_iter_advance(from, written);
  2168. if (pos > i_size_read(inode) && !S_ISBLK(inode->i_mode)) {
  2169. i_size_write(inode, pos);
  2170. mark_inode_dirty(inode);
  2171. }
  2172. iocb->ki_pos = pos;
  2173. }
  2174. out:
  2175. return written;
  2176. }
  2177. EXPORT_SYMBOL(generic_file_direct_write);
  2178. /*
  2179. * Find or create a page at the given pagecache position. Return the locked
  2180. * page. This function is specifically for buffered writes.
  2181. */
  2182. struct page *grab_cache_page_write_begin(struct address_space *mapping,
  2183. pgoff_t index, unsigned flags)
  2184. {
  2185. struct page *page;
  2186. int fgp_flags = FGP_LOCK|FGP_ACCESSED|FGP_WRITE|FGP_CREAT;
  2187. if (flags & AOP_FLAG_NOFS)
  2188. fgp_flags |= FGP_NOFS;
  2189. page = pagecache_get_page(mapping, index, fgp_flags,
  2190. mapping_gfp_mask(mapping));
  2191. if (page)
  2192. wait_for_stable_page(page);
  2193. return page;
  2194. }
  2195. EXPORT_SYMBOL(grab_cache_page_write_begin);
  2196. ssize_t generic_perform_write(struct file *file,
  2197. struct iov_iter *i, loff_t pos)
  2198. {
  2199. struct address_space *mapping = file->f_mapping;
  2200. const struct address_space_operations *a_ops = mapping->a_ops;
  2201. long status = 0;
  2202. ssize_t written = 0;
  2203. unsigned int flags = 0;
  2204. /*
  2205. * Copies from kernel address space cannot fail (NFSD is a big user).
  2206. */
  2207. if (!iter_is_iovec(i))
  2208. flags |= AOP_FLAG_UNINTERRUPTIBLE;
  2209. do {
  2210. struct page *page;
  2211. unsigned long offset; /* Offset into pagecache page */
  2212. unsigned long bytes; /* Bytes to write to page */
  2213. size_t copied; /* Bytes copied from user */
  2214. void *fsdata;
  2215. offset = (pos & (PAGE_CACHE_SIZE - 1));
  2216. bytes = min_t(unsigned long, PAGE_CACHE_SIZE - offset,
  2217. iov_iter_count(i));
  2218. again:
  2219. /*
  2220. * Bring in the user page that we will copy from _first_.
  2221. * Otherwise there's a nasty deadlock on copying from the
  2222. * same page as we're writing to, without it being marked
  2223. * up-to-date.
  2224. *
  2225. * Not only is this an optimisation, but it is also required
  2226. * to check that the address is actually valid, when atomic
  2227. * usercopies are used, below.
  2228. */
  2229. if (unlikely(iov_iter_fault_in_readable(i, bytes))) {
  2230. status = -EFAULT;
  2231. break;
  2232. }
  2233. status = a_ops->write_begin(file, mapping, pos, bytes, flags,
  2234. &page, &fsdata);
  2235. if (unlikely(status < 0))
  2236. break;
  2237. if (mapping_writably_mapped(mapping))
  2238. flush_dcache_page(page);
  2239. copied = iov_iter_copy_from_user_atomic(page, i, offset, bytes);
  2240. flush_dcache_page(page);
  2241. status = a_ops->write_end(file, mapping, pos, bytes, copied,
  2242. page, fsdata);
  2243. if (unlikely(status < 0))
  2244. break;
  2245. copied = status;
  2246. cond_resched();
  2247. iov_iter_advance(i, copied);
  2248. if (unlikely(copied == 0)) {
  2249. /*
  2250. * If we were unable to copy any data at all, we must
  2251. * fall back to a single segment length write.
  2252. *
  2253. * If we didn't fallback here, we could livelock
  2254. * because not all segments in the iov can be copied at
  2255. * once without a pagefault.
  2256. */
  2257. bytes = min_t(unsigned long, PAGE_CACHE_SIZE - offset,
  2258. iov_iter_single_seg_count(i));
  2259. goto again;
  2260. }
  2261. pos += copied;
  2262. written += copied;
  2263. balance_dirty_pages_ratelimited(mapping);
  2264. if (fatal_signal_pending(current)) {
  2265. status = -EINTR;
  2266. break;
  2267. }
  2268. } while (iov_iter_count(i));
  2269. return written ? written : status;
  2270. }
  2271. EXPORT_SYMBOL(generic_perform_write);
  2272. /**
  2273. * __generic_file_write_iter - write data to a file
  2274. * @iocb: IO state structure (file, offset, etc.)
  2275. * @from: iov_iter with data to write
  2276. *
  2277. * This function does all the work needed for actually writing data to a
  2278. * file. It does all basic checks, removes SUID from the file, updates
  2279. * modification times and calls proper subroutines depending on whether we
  2280. * do direct IO or a standard buffered write.
  2281. *
  2282. * It expects i_mutex to be grabbed unless we work on a block device or similar
  2283. * object which does not need locking at all.
  2284. *
  2285. * This function does *not* take care of syncing data in case of O_SYNC write.
  2286. * A caller has to handle it. This is mainly due to the fact that we want to
  2287. * avoid syncing under i_mutex.
  2288. */
  2289. ssize_t __generic_file_write_iter(struct kiocb *iocb, struct iov_iter *from)
  2290. {
  2291. struct file *file = iocb->ki_filp;
  2292. struct address_space * mapping = file->f_mapping;
  2293. struct inode *inode = mapping->host;
  2294. loff_t pos = iocb->ki_pos;
  2295. ssize_t written = 0;
  2296. ssize_t err;
  2297. ssize_t status;
  2298. size_t count = iov_iter_count(from);
  2299. /* We can write back this queue in page reclaim */
  2300. current->backing_dev_info = mapping->backing_dev_info;
  2301. err = generic_write_checks(file, &pos, &count, S_ISBLK(inode->i_mode));
  2302. if (err)
  2303. goto out;
  2304. if (count == 0)
  2305. goto out;
  2306. iov_iter_truncate(from, count);
  2307. err = file_remove_suid(file);
  2308. if (err)
  2309. goto out;
  2310. err = file_update_time(file);
  2311. if (err)
  2312. goto out;
  2313. /* coalesce the iovecs and go direct-to-BIO for O_DIRECT */
  2314. if (unlikely(file->f_flags & O_DIRECT)) {
  2315. loff_t endbyte;
  2316. written = generic_file_direct_write(iocb, from, pos);
  2317. if (written < 0 || written == count)
  2318. goto out;
  2319. /*
  2320. * direct-io write to a hole: fall through to buffered I/O
  2321. * for completing the rest of the request.
  2322. */
  2323. pos += written;
  2324. count -= written;
  2325. status = generic_perform_write(file, from, pos);
  2326. /*
  2327. * If generic_perform_write() returned a synchronous error
  2328. * then we want to return the number of bytes which were
  2329. * direct-written, or the error code if that was zero. Note
  2330. * that this differs from normal direct-io semantics, which
  2331. * will return -EFOO even if some bytes were written.
  2332. */
  2333. if (unlikely(status < 0)) {
  2334. err = status;
  2335. goto out;
  2336. }
  2337. iocb->ki_pos = pos + status;
  2338. /*
  2339. * We need to ensure that the page cache pages are written to
  2340. * disk and invalidated to preserve the expected O_DIRECT
  2341. * semantics.
  2342. */
  2343. endbyte = pos + status - 1;
  2344. err = filemap_write_and_wait_range(file->f_mapping, pos, endbyte);
  2345. if (err == 0) {
  2346. written += status;
  2347. invalidate_mapping_pages(mapping,
  2348. pos >> PAGE_CACHE_SHIFT,
  2349. endbyte >> PAGE_CACHE_SHIFT);
  2350. } else {
  2351. /*
  2352. * We don't know how much we wrote, so just return
  2353. * the number of bytes which were direct-written
  2354. */
  2355. }
  2356. } else {
  2357. written = generic_perform_write(file, from, pos);
  2358. if (likely(written >= 0))
  2359. iocb->ki_pos = pos + written;
  2360. }
  2361. out:
  2362. current->backing_dev_info = NULL;
  2363. return written ? written : err;
  2364. }
  2365. EXPORT_SYMBOL(__generic_file_write_iter);
  2366. /**
  2367. * generic_file_write_iter - write data to a file
  2368. * @iocb: IO state structure
  2369. * @from: iov_iter with data to write
  2370. *
  2371. * This is a wrapper around __generic_file_write_iter() to be used by most
  2372. * filesystems. It takes care of syncing the file in case of O_SYNC file
  2373. * and acquires i_mutex as needed.
  2374. */
  2375. ssize_t generic_file_write_iter(struct kiocb *iocb, struct iov_iter *from)
  2376. {
  2377. struct file *file = iocb->ki_filp;
  2378. struct inode *inode = file->f_mapping->host;
  2379. ssize_t ret;
  2380. mutex_lock(&inode->i_mutex);
  2381. ret = __generic_file_write_iter(iocb, from);
  2382. mutex_unlock(&inode->i_mutex);
  2383. if (ret > 0) {
  2384. ssize_t err;
  2385. err = generic_write_sync(file, iocb->ki_pos - ret, ret);
  2386. if (err < 0)
  2387. ret = err;
  2388. }
  2389. return ret;
  2390. }
  2391. EXPORT_SYMBOL(generic_file_write_iter);
  2392. /**
  2393. * try_to_release_page() - release old fs-specific metadata on a page
  2394. *
  2395. * @page: the page which the kernel is trying to free
  2396. * @gfp_mask: memory allocation flags (and I/O mode)
  2397. *
  2398. * The address_space is to try to release any data against the page
  2399. * (presumably at page->private). If the release was successful, return `1'.
  2400. * Otherwise return zero.
  2401. *
  2402. * This may also be called if PG_fscache is set on a page, indicating that the
  2403. * page is known to the local caching routines.
  2404. *
  2405. * The @gfp_mask argument specifies whether I/O may be performed to release
  2406. * this page (__GFP_IO), and whether the call may block (__GFP_WAIT & __GFP_FS).
  2407. *
  2408. */
  2409. int try_to_release_page(struct page *page, gfp_t gfp_mask)
  2410. {
  2411. struct address_space * const mapping = page->mapping;
  2412. BUG_ON(!PageLocked(page));
  2413. if (PageWriteback(page))
  2414. return 0;
  2415. if (mapping && mapping->a_ops->releasepage)
  2416. return mapping->a_ops->releasepage(page, gfp_mask);
  2417. return try_to_free_buffers(page);
  2418. }
  2419. EXPORT_SYMBOL(try_to_release_page);