filemap.c 87 KB

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