filemap.c 76 KB

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