filemap.c 90 KB

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