filemap.c 72 KB

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