filemap.c 77 KB

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