filemap.c 77 KB

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