filemap.c 80 KB

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