filemap.c 74 KB

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