filemap.c 85 KB

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