filemap.c 90 KB

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