filemap.c 89 KB

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