filemap.c 75 KB

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