filemap.c 74 KB

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