filemap.c 78 KB

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