filemap.c 80 KB

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