filemap.c 77 KB

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