filemap.c 77 KB

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