filemap.c 72 KB

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