filemap.c 65 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473
  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/module.h>
  12. #include <linux/slab.h>
  13. #include <linux/compiler.h>
  14. #include <linux/fs.h>
  15. #include <linux/uaccess.h>
  16. #include <linux/aio.h>
  17. #include <linux/capability.h>
  18. #include <linux/kernel_stat.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/syscalls.h>
  32. #include <linux/cpuset.h>
  33. #include <linux/hardirq.h> /* for BUG_ON(!in_atomic()) only */
  34. #include <linux/memcontrol.h>
  35. #include <linux/mm_inline.h> /* for page_is_file_cache() */
  36. #include "internal.h"
  37. /*
  38. * FIXME: remove all knowledge of the buffer layer from the core VM
  39. */
  40. #include <linux/buffer_head.h> /* for try_to_free_buffers */
  41. #include <asm/mman.h>
  42. /*
  43. * Shared mappings implemented 30.11.1994. It's not fully working yet,
  44. * though.
  45. *
  46. * Shared mappings now work. 15.8.1995 Bruno.
  47. *
  48. * finished 'unifying' the page and buffer cache and SMP-threaded the
  49. * page-cache, 21.05.1999, Ingo Molnar <mingo@redhat.com>
  50. *
  51. * SMP-threaded pagemap-LRU 1999, Andrea Arcangeli <andrea@suse.de>
  52. */
  53. /*
  54. * Lock ordering:
  55. *
  56. * ->i_mmap_lock (truncate_pagecache)
  57. * ->private_lock (__free_pte->__set_page_dirty_buffers)
  58. * ->swap_lock (exclusive_swap_page, others)
  59. * ->mapping->tree_lock
  60. *
  61. * ->i_mutex
  62. * ->i_mmap_lock (truncate->unmap_mapping_range)
  63. *
  64. * ->mmap_sem
  65. * ->i_mmap_lock
  66. * ->page_table_lock or pte_lock (various, mainly in memory.c)
  67. * ->mapping->tree_lock (arch-dependent flush_dcache_mmap_lock)
  68. *
  69. * ->mmap_sem
  70. * ->lock_page (access_process_vm)
  71. *
  72. * ->i_mutex (generic_file_buffered_write)
  73. * ->mmap_sem (fault_in_pages_readable->do_page_fault)
  74. *
  75. * ->i_mutex
  76. * ->i_alloc_sem (various)
  77. *
  78. * ->inode_lock
  79. * ->sb_lock (fs/fs-writeback.c)
  80. * ->mapping->tree_lock (__sync_single_inode)
  81. *
  82. * ->i_mmap_lock
  83. * ->anon_vma.lock (vma_adjust)
  84. *
  85. * ->anon_vma.lock
  86. * ->page_table_lock or pte_lock (anon_vma_prepare and various)
  87. *
  88. * ->page_table_lock or pte_lock
  89. * ->swap_lock (try_to_unmap_one)
  90. * ->private_lock (try_to_unmap_one)
  91. * ->tree_lock (try_to_unmap_one)
  92. * ->zone.lru_lock (follow_page->mark_page_accessed)
  93. * ->zone.lru_lock (check_pte_range->isolate_lru_page)
  94. * ->private_lock (page_remove_rmap->set_page_dirty)
  95. * ->tree_lock (page_remove_rmap->set_page_dirty)
  96. * ->inode_lock (page_remove_rmap->set_page_dirty)
  97. * ->inode_lock (zap_pte_range->set_page_dirty)
  98. * ->private_lock (zap_pte_range->__set_page_dirty_buffers)
  99. *
  100. * ->task->proc_lock
  101. * ->dcache_lock (proc_pid_lookup)
  102. *
  103. * (code doesn't rely on that order, so you could switch it around)
  104. * ->tasklist_lock (memory_failure, collect_procs_ao)
  105. * ->i_mmap_lock
  106. */
  107. /*
  108. * Remove a page from the page cache and free it. Caller has to make
  109. * sure the page is locked and that nobody else uses it - or that usage
  110. * is safe. The caller must hold the mapping's tree_lock.
  111. */
  112. void __remove_from_page_cache(struct page *page)
  113. {
  114. struct address_space *mapping = page->mapping;
  115. radix_tree_delete(&mapping->page_tree, page->index);
  116. page->mapping = NULL;
  117. mapping->nrpages--;
  118. __dec_zone_page_state(page, NR_FILE_PAGES);
  119. if (PageSwapBacked(page))
  120. __dec_zone_page_state(page, NR_SHMEM);
  121. BUG_ON(page_mapped(page));
  122. /*
  123. * Some filesystems seem to re-dirty the page even after
  124. * the VM has canceled the dirty bit (eg ext3 journaling).
  125. *
  126. * Fix it up by doing a final dirty accounting check after
  127. * having removed the page entirely.
  128. */
  129. if (PageDirty(page) && mapping_cap_account_dirty(mapping)) {
  130. dec_zone_page_state(page, NR_FILE_DIRTY);
  131. dec_bdi_stat(mapping->backing_dev_info, BDI_RECLAIMABLE);
  132. }
  133. }
  134. void remove_from_page_cache(struct page *page)
  135. {
  136. struct address_space *mapping = page->mapping;
  137. BUG_ON(!PageLocked(page));
  138. spin_lock_irq(&mapping->tree_lock);
  139. __remove_from_page_cache(page);
  140. spin_unlock_irq(&mapping->tree_lock);
  141. mem_cgroup_uncharge_cache_page(page);
  142. }
  143. static int sync_page(void *word)
  144. {
  145. struct address_space *mapping;
  146. struct page *page;
  147. page = container_of((unsigned long *)word, struct page, flags);
  148. /*
  149. * page_mapping() is being called without PG_locked held.
  150. * Some knowledge of the state and use of the page is used to
  151. * reduce the requirements down to a memory barrier.
  152. * The danger here is of a stale page_mapping() return value
  153. * indicating a struct address_space different from the one it's
  154. * associated with when it is associated with one.
  155. * After smp_mb(), it's either the correct page_mapping() for
  156. * the page, or an old page_mapping() and the page's own
  157. * page_mapping() has gone NULL.
  158. * The ->sync_page() address_space operation must tolerate
  159. * page_mapping() going NULL. By an amazing coincidence,
  160. * this comes about because none of the users of the page
  161. * in the ->sync_page() methods make essential use of the
  162. * page_mapping(), merely passing the page down to the backing
  163. * device's unplug functions when it's non-NULL, which in turn
  164. * ignore it for all cases but swap, where only page_private(page) is
  165. * of interest. When page_mapping() does go NULL, the entire
  166. * call stack gracefully ignores the page and returns.
  167. * -- wli
  168. */
  169. smp_mb();
  170. mapping = page_mapping(page);
  171. if (mapping && mapping->a_ops && mapping->a_ops->sync_page)
  172. mapping->a_ops->sync_page(page);
  173. io_schedule();
  174. return 0;
  175. }
  176. static int sync_page_killable(void *word)
  177. {
  178. sync_page(word);
  179. return fatal_signal_pending(current) ? -EINTR : 0;
  180. }
  181. /**
  182. * __filemap_fdatawrite_range - start writeback on mapping dirty pages in range
  183. * @mapping: address space structure to write
  184. * @start: offset in bytes where the range starts
  185. * @end: offset in bytes where the range ends (inclusive)
  186. * @sync_mode: enable synchronous operation
  187. *
  188. * Start writeback against all of a mapping's dirty pages that lie
  189. * within the byte offsets <start, end> inclusive.
  190. *
  191. * If sync_mode is WB_SYNC_ALL then this is a "data integrity" operation, as
  192. * opposed to a regular memory cleansing writeback. The difference between
  193. * these two operations is that if a dirty page/buffer is encountered, it must
  194. * be waited upon, and not just skipped over.
  195. */
  196. int __filemap_fdatawrite_range(struct address_space *mapping, loff_t start,
  197. loff_t end, int sync_mode)
  198. {
  199. int ret;
  200. struct writeback_control wbc = {
  201. .sync_mode = sync_mode,
  202. .nr_to_write = LONG_MAX,
  203. .range_start = start,
  204. .range_end = end,
  205. };
  206. if (!mapping_cap_writeback_dirty(mapping))
  207. return 0;
  208. ret = do_writepages(mapping, &wbc);
  209. return ret;
  210. }
  211. static inline int __filemap_fdatawrite(struct address_space *mapping,
  212. int sync_mode)
  213. {
  214. return __filemap_fdatawrite_range(mapping, 0, LLONG_MAX, sync_mode);
  215. }
  216. int filemap_fdatawrite(struct address_space *mapping)
  217. {
  218. return __filemap_fdatawrite(mapping, WB_SYNC_ALL);
  219. }
  220. EXPORT_SYMBOL(filemap_fdatawrite);
  221. int filemap_fdatawrite_range(struct address_space *mapping, loff_t start,
  222. loff_t end)
  223. {
  224. return __filemap_fdatawrite_range(mapping, start, end, WB_SYNC_ALL);
  225. }
  226. EXPORT_SYMBOL(filemap_fdatawrite_range);
  227. /**
  228. * filemap_flush - mostly a non-blocking flush
  229. * @mapping: target address_space
  230. *
  231. * This is a mostly non-blocking flush. Not suitable for data-integrity
  232. * purposes - I/O may not be started against all dirty pages.
  233. */
  234. int filemap_flush(struct address_space *mapping)
  235. {
  236. return __filemap_fdatawrite(mapping, WB_SYNC_NONE);
  237. }
  238. EXPORT_SYMBOL(filemap_flush);
  239. /**
  240. * wait_on_page_writeback_range - wait for writeback to complete
  241. * @mapping: target address_space
  242. * @start: beginning page index
  243. * @end: ending page index
  244. *
  245. * Wait for writeback to complete against pages indexed by start->end
  246. * inclusive
  247. */
  248. int wait_on_page_writeback_range(struct address_space *mapping,
  249. pgoff_t start, pgoff_t end)
  250. {
  251. struct pagevec pvec;
  252. int nr_pages;
  253. int ret = 0;
  254. pgoff_t index;
  255. if (end < start)
  256. return 0;
  257. pagevec_init(&pvec, 0);
  258. index = start;
  259. while ((index <= end) &&
  260. (nr_pages = pagevec_lookup_tag(&pvec, mapping, &index,
  261. PAGECACHE_TAG_WRITEBACK,
  262. min(end - index, (pgoff_t)PAGEVEC_SIZE-1) + 1)) != 0) {
  263. unsigned i;
  264. for (i = 0; i < nr_pages; i++) {
  265. struct page *page = pvec.pages[i];
  266. /* until radix tree lookup accepts end_index */
  267. if (page->index > end)
  268. continue;
  269. wait_on_page_writeback(page);
  270. if (PageError(page))
  271. ret = -EIO;
  272. }
  273. pagevec_release(&pvec);
  274. cond_resched();
  275. }
  276. /* Check for outstanding write errors */
  277. if (test_and_clear_bit(AS_ENOSPC, &mapping->flags))
  278. ret = -ENOSPC;
  279. if (test_and_clear_bit(AS_EIO, &mapping->flags))
  280. ret = -EIO;
  281. return ret;
  282. }
  283. /**
  284. * filemap_fdatawait_range - wait for all under-writeback pages to complete in a given range
  285. * @mapping: address space structure to wait for
  286. * @start: offset in bytes where the range starts
  287. * @end: offset in bytes where the range ends (inclusive)
  288. *
  289. * Walk the list of under-writeback pages of the given address space
  290. * in the given range and wait for all of them.
  291. *
  292. * This is just a simple wrapper so that callers don't have to convert offsets
  293. * to page indexes themselves
  294. */
  295. int filemap_fdatawait_range(struct address_space *mapping, loff_t start,
  296. loff_t end)
  297. {
  298. return wait_on_page_writeback_range(mapping, start >> PAGE_CACHE_SHIFT,
  299. end >> PAGE_CACHE_SHIFT);
  300. }
  301. EXPORT_SYMBOL(filemap_fdatawait_range);
  302. /**
  303. * filemap_fdatawait - wait for all under-writeback pages to complete
  304. * @mapping: address space structure to wait for
  305. *
  306. * Walk the list of under-writeback pages of the given address space
  307. * and wait for all of them.
  308. */
  309. int filemap_fdatawait(struct address_space *mapping)
  310. {
  311. loff_t i_size = i_size_read(mapping->host);
  312. if (i_size == 0)
  313. return 0;
  314. return wait_on_page_writeback_range(mapping, 0,
  315. (i_size - 1) >> PAGE_CACHE_SHIFT);
  316. }
  317. EXPORT_SYMBOL(filemap_fdatawait);
  318. int filemap_write_and_wait(struct address_space *mapping)
  319. {
  320. int err = 0;
  321. if (mapping->nrpages) {
  322. err = filemap_fdatawrite(mapping);
  323. /*
  324. * Even if the above returned error, the pages may be
  325. * written partially (e.g. -ENOSPC), so we wait for it.
  326. * But the -EIO is special case, it may indicate the worst
  327. * thing (e.g. bug) happened, so we avoid waiting for it.
  328. */
  329. if (err != -EIO) {
  330. int err2 = filemap_fdatawait(mapping);
  331. if (!err)
  332. err = err2;
  333. }
  334. }
  335. return err;
  336. }
  337. EXPORT_SYMBOL(filemap_write_and_wait);
  338. /**
  339. * filemap_write_and_wait_range - write out & wait on a file range
  340. * @mapping: the address_space for the pages
  341. * @lstart: offset in bytes where the range starts
  342. * @lend: offset in bytes where the range ends (inclusive)
  343. *
  344. * Write out and wait upon file offsets lstart->lend, inclusive.
  345. *
  346. * Note that `lend' is inclusive (describes the last byte to be written) so
  347. * that this function can be used to write to the very end-of-file (end = -1).
  348. */
  349. int filemap_write_and_wait_range(struct address_space *mapping,
  350. loff_t lstart, loff_t lend)
  351. {
  352. int err = 0;
  353. if (mapping->nrpages) {
  354. err = __filemap_fdatawrite_range(mapping, lstart, lend,
  355. WB_SYNC_ALL);
  356. /* See comment of filemap_write_and_wait() */
  357. if (err != -EIO) {
  358. int err2 = wait_on_page_writeback_range(mapping,
  359. lstart >> PAGE_CACHE_SHIFT,
  360. lend >> PAGE_CACHE_SHIFT);
  361. if (!err)
  362. err = err2;
  363. }
  364. }
  365. return err;
  366. }
  367. EXPORT_SYMBOL(filemap_write_and_wait_range);
  368. /**
  369. * add_to_page_cache_locked - add a locked page to the pagecache
  370. * @page: page to add
  371. * @mapping: the page's address_space
  372. * @offset: page index
  373. * @gfp_mask: page allocation mode
  374. *
  375. * This function is used to add a page to the pagecache. It must be locked.
  376. * This function does not add the page to the LRU. The caller must do that.
  377. */
  378. int add_to_page_cache_locked(struct page *page, struct address_space *mapping,
  379. pgoff_t offset, gfp_t gfp_mask)
  380. {
  381. int error;
  382. VM_BUG_ON(!PageLocked(page));
  383. error = mem_cgroup_cache_charge(page, current->mm,
  384. gfp_mask & GFP_RECLAIM_MASK);
  385. if (error)
  386. goto out;
  387. error = radix_tree_preload(gfp_mask & ~__GFP_HIGHMEM);
  388. if (error == 0) {
  389. page_cache_get(page);
  390. page->mapping = mapping;
  391. page->index = offset;
  392. spin_lock_irq(&mapping->tree_lock);
  393. error = radix_tree_insert(&mapping->page_tree, offset, page);
  394. if (likely(!error)) {
  395. mapping->nrpages++;
  396. __inc_zone_page_state(page, NR_FILE_PAGES);
  397. if (PageSwapBacked(page))
  398. __inc_zone_page_state(page, NR_SHMEM);
  399. spin_unlock_irq(&mapping->tree_lock);
  400. } else {
  401. page->mapping = NULL;
  402. spin_unlock_irq(&mapping->tree_lock);
  403. mem_cgroup_uncharge_cache_page(page);
  404. page_cache_release(page);
  405. }
  406. radix_tree_preload_end();
  407. } else
  408. mem_cgroup_uncharge_cache_page(page);
  409. out:
  410. return error;
  411. }
  412. EXPORT_SYMBOL(add_to_page_cache_locked);
  413. int add_to_page_cache_lru(struct page *page, struct address_space *mapping,
  414. pgoff_t offset, gfp_t gfp_mask)
  415. {
  416. int ret;
  417. /*
  418. * Splice_read and readahead add shmem/tmpfs pages into the page cache
  419. * before shmem_readpage has a chance to mark them as SwapBacked: they
  420. * need to go on the active_anon lru below, and mem_cgroup_cache_charge
  421. * (called in add_to_page_cache) needs to know where they're going too.
  422. */
  423. if (mapping_cap_swap_backed(mapping))
  424. SetPageSwapBacked(page);
  425. ret = add_to_page_cache(page, mapping, offset, gfp_mask);
  426. if (ret == 0) {
  427. if (page_is_file_cache(page))
  428. lru_cache_add_file(page);
  429. else
  430. lru_cache_add_active_anon(page);
  431. }
  432. return ret;
  433. }
  434. EXPORT_SYMBOL_GPL(add_to_page_cache_lru);
  435. #ifdef CONFIG_NUMA
  436. struct page *__page_cache_alloc(gfp_t gfp)
  437. {
  438. if (cpuset_do_page_mem_spread()) {
  439. int n = cpuset_mem_spread_node();
  440. return alloc_pages_exact_node(n, gfp, 0);
  441. }
  442. return alloc_pages(gfp, 0);
  443. }
  444. EXPORT_SYMBOL(__page_cache_alloc);
  445. #endif
  446. static int __sleep_on_page_lock(void *word)
  447. {
  448. io_schedule();
  449. return 0;
  450. }
  451. /*
  452. * In order to wait for pages to become available there must be
  453. * waitqueues associated with pages. By using a hash table of
  454. * waitqueues where the bucket discipline is to maintain all
  455. * waiters on the same queue and wake all when any of the pages
  456. * become available, and for the woken contexts to check to be
  457. * sure the appropriate page became available, this saves space
  458. * at a cost of "thundering herd" phenomena during rare hash
  459. * collisions.
  460. */
  461. static wait_queue_head_t *page_waitqueue(struct page *page)
  462. {
  463. const struct zone *zone = page_zone(page);
  464. return &zone->wait_table[hash_ptr(page, zone->wait_table_bits)];
  465. }
  466. static inline void wake_up_page(struct page *page, int bit)
  467. {
  468. __wake_up_bit(page_waitqueue(page), &page->flags, bit);
  469. }
  470. void wait_on_page_bit(struct page *page, int bit_nr)
  471. {
  472. DEFINE_WAIT_BIT(wait, &page->flags, bit_nr);
  473. if (test_bit(bit_nr, &page->flags))
  474. __wait_on_bit(page_waitqueue(page), &wait, sync_page,
  475. TASK_UNINTERRUPTIBLE);
  476. }
  477. EXPORT_SYMBOL(wait_on_page_bit);
  478. /**
  479. * add_page_wait_queue - Add an arbitrary waiter to a page's wait queue
  480. * @page: Page defining the wait queue of interest
  481. * @waiter: Waiter to add to the queue
  482. *
  483. * Add an arbitrary @waiter to the wait queue for the nominated @page.
  484. */
  485. void add_page_wait_queue(struct page *page, wait_queue_t *waiter)
  486. {
  487. wait_queue_head_t *q = page_waitqueue(page);
  488. unsigned long flags;
  489. spin_lock_irqsave(&q->lock, flags);
  490. __add_wait_queue(q, waiter);
  491. spin_unlock_irqrestore(&q->lock, flags);
  492. }
  493. EXPORT_SYMBOL_GPL(add_page_wait_queue);
  494. /**
  495. * unlock_page - unlock a locked page
  496. * @page: the page
  497. *
  498. * Unlocks the page and wakes up sleepers in ___wait_on_page_locked().
  499. * Also wakes sleepers in wait_on_page_writeback() because the wakeup
  500. * mechananism between PageLocked pages and PageWriteback pages is shared.
  501. * But that's OK - sleepers in wait_on_page_writeback() just go back to sleep.
  502. *
  503. * The mb is necessary to enforce ordering between the clear_bit and the read
  504. * of the waitqueue (to avoid SMP races with a parallel wait_on_page_locked()).
  505. */
  506. void unlock_page(struct page *page)
  507. {
  508. VM_BUG_ON(!PageLocked(page));
  509. clear_bit_unlock(PG_locked, &page->flags);
  510. smp_mb__after_clear_bit();
  511. wake_up_page(page, PG_locked);
  512. }
  513. EXPORT_SYMBOL(unlock_page);
  514. /**
  515. * end_page_writeback - end writeback against a page
  516. * @page: the page
  517. */
  518. void end_page_writeback(struct page *page)
  519. {
  520. if (TestClearPageReclaim(page))
  521. rotate_reclaimable_page(page);
  522. if (!test_clear_page_writeback(page))
  523. BUG();
  524. smp_mb__after_clear_bit();
  525. wake_up_page(page, PG_writeback);
  526. }
  527. EXPORT_SYMBOL(end_page_writeback);
  528. /**
  529. * __lock_page - get a lock on the page, assuming we need to sleep to get it
  530. * @page: the page to lock
  531. *
  532. * Ugly. Running sync_page() in state TASK_UNINTERRUPTIBLE is scary. If some
  533. * random driver's requestfn sets TASK_RUNNING, we could busywait. However
  534. * chances are that on the second loop, the block layer's plug list is empty,
  535. * so sync_page() will then return in state TASK_UNINTERRUPTIBLE.
  536. */
  537. void __lock_page(struct page *page)
  538. {
  539. DEFINE_WAIT_BIT(wait, &page->flags, PG_locked);
  540. __wait_on_bit_lock(page_waitqueue(page), &wait, sync_page,
  541. TASK_UNINTERRUPTIBLE);
  542. }
  543. EXPORT_SYMBOL(__lock_page);
  544. int __lock_page_killable(struct page *page)
  545. {
  546. DEFINE_WAIT_BIT(wait, &page->flags, PG_locked);
  547. return __wait_on_bit_lock(page_waitqueue(page), &wait,
  548. sync_page_killable, TASK_KILLABLE);
  549. }
  550. EXPORT_SYMBOL_GPL(__lock_page_killable);
  551. /**
  552. * __lock_page_nosync - get a lock on the page, without calling sync_page()
  553. * @page: the page to lock
  554. *
  555. * Variant of lock_page that does not require the caller to hold a reference
  556. * on the page's mapping.
  557. */
  558. void __lock_page_nosync(struct page *page)
  559. {
  560. DEFINE_WAIT_BIT(wait, &page->flags, PG_locked);
  561. __wait_on_bit_lock(page_waitqueue(page), &wait, __sleep_on_page_lock,
  562. TASK_UNINTERRUPTIBLE);
  563. }
  564. /**
  565. * find_get_page - find and get a page reference
  566. * @mapping: the address_space to search
  567. * @offset: the page index
  568. *
  569. * Is there a pagecache struct page at the given (mapping, offset) tuple?
  570. * If yes, increment its refcount and return it; if no, return NULL.
  571. */
  572. struct page *find_get_page(struct address_space *mapping, pgoff_t offset)
  573. {
  574. void **pagep;
  575. struct page *page;
  576. rcu_read_lock();
  577. repeat:
  578. page = NULL;
  579. pagep = radix_tree_lookup_slot(&mapping->page_tree, offset);
  580. if (pagep) {
  581. page = radix_tree_deref_slot(pagep);
  582. if (unlikely(!page || page == RADIX_TREE_RETRY))
  583. goto repeat;
  584. if (!page_cache_get_speculative(page))
  585. goto repeat;
  586. /*
  587. * Has the page moved?
  588. * This is part of the lockless pagecache protocol. See
  589. * include/linux/pagemap.h for details.
  590. */
  591. if (unlikely(page != *pagep)) {
  592. page_cache_release(page);
  593. goto repeat;
  594. }
  595. }
  596. rcu_read_unlock();
  597. return page;
  598. }
  599. EXPORT_SYMBOL(find_get_page);
  600. /**
  601. * find_lock_page - locate, pin and lock a pagecache page
  602. * @mapping: the address_space to search
  603. * @offset: the page index
  604. *
  605. * Locates the desired pagecache page, locks it, increments its reference
  606. * count and returns its address.
  607. *
  608. * Returns zero if the page was not present. find_lock_page() may sleep.
  609. */
  610. struct page *find_lock_page(struct address_space *mapping, pgoff_t offset)
  611. {
  612. struct page *page;
  613. repeat:
  614. page = find_get_page(mapping, offset);
  615. if (page) {
  616. lock_page(page);
  617. /* Has the page been truncated? */
  618. if (unlikely(page->mapping != mapping)) {
  619. unlock_page(page);
  620. page_cache_release(page);
  621. goto repeat;
  622. }
  623. VM_BUG_ON(page->index != offset);
  624. }
  625. return page;
  626. }
  627. EXPORT_SYMBOL(find_lock_page);
  628. /**
  629. * find_or_create_page - locate or add a pagecache page
  630. * @mapping: the page's address_space
  631. * @index: the page's index into the mapping
  632. * @gfp_mask: page allocation mode
  633. *
  634. * Locates a page in the pagecache. If the page is not present, a new page
  635. * is allocated using @gfp_mask and is added to the pagecache and to the VM's
  636. * LRU list. The returned page is locked and has its reference count
  637. * incremented.
  638. *
  639. * find_or_create_page() may sleep, even if @gfp_flags specifies an atomic
  640. * allocation!
  641. *
  642. * find_or_create_page() returns the desired page's address, or zero on
  643. * memory exhaustion.
  644. */
  645. struct page *find_or_create_page(struct address_space *mapping,
  646. pgoff_t index, gfp_t gfp_mask)
  647. {
  648. struct page *page;
  649. int err;
  650. repeat:
  651. page = find_lock_page(mapping, index);
  652. if (!page) {
  653. page = __page_cache_alloc(gfp_mask);
  654. if (!page)
  655. return NULL;
  656. /*
  657. * We want a regular kernel memory (not highmem or DMA etc)
  658. * allocation for the radix tree nodes, but we need to honour
  659. * the context-specific requirements the caller has asked for.
  660. * GFP_RECLAIM_MASK collects those requirements.
  661. */
  662. err = add_to_page_cache_lru(page, mapping, index,
  663. (gfp_mask & GFP_RECLAIM_MASK));
  664. if (unlikely(err)) {
  665. page_cache_release(page);
  666. page = NULL;
  667. if (err == -EEXIST)
  668. goto repeat;
  669. }
  670. }
  671. return page;
  672. }
  673. EXPORT_SYMBOL(find_or_create_page);
  674. /**
  675. * find_get_pages - gang pagecache lookup
  676. * @mapping: The address_space to search
  677. * @start: The starting page index
  678. * @nr_pages: The maximum number of pages
  679. * @pages: Where the resulting pages are placed
  680. *
  681. * find_get_pages() will search for and return a group of up to
  682. * @nr_pages pages in the mapping. The pages are placed at @pages.
  683. * find_get_pages() takes a reference against the returned pages.
  684. *
  685. * The search returns a group of mapping-contiguous pages with ascending
  686. * indexes. There may be holes in the indices due to not-present pages.
  687. *
  688. * find_get_pages() returns the number of pages which were found.
  689. */
  690. unsigned find_get_pages(struct address_space *mapping, pgoff_t start,
  691. unsigned int nr_pages, struct page **pages)
  692. {
  693. unsigned int i;
  694. unsigned int ret;
  695. unsigned int nr_found;
  696. rcu_read_lock();
  697. restart:
  698. nr_found = radix_tree_gang_lookup_slot(&mapping->page_tree,
  699. (void ***)pages, start, nr_pages);
  700. ret = 0;
  701. for (i = 0; i < nr_found; i++) {
  702. struct page *page;
  703. repeat:
  704. page = radix_tree_deref_slot((void **)pages[i]);
  705. if (unlikely(!page))
  706. continue;
  707. /*
  708. * this can only trigger if nr_found == 1, making livelock
  709. * a non issue.
  710. */
  711. if (unlikely(page == RADIX_TREE_RETRY))
  712. goto restart;
  713. if (!page_cache_get_speculative(page))
  714. goto repeat;
  715. /* Has the page moved? */
  716. if (unlikely(page != *((void **)pages[i]))) {
  717. page_cache_release(page);
  718. goto repeat;
  719. }
  720. pages[ret] = page;
  721. ret++;
  722. }
  723. rcu_read_unlock();
  724. return ret;
  725. }
  726. /**
  727. * find_get_pages_contig - gang contiguous pagecache lookup
  728. * @mapping: The address_space to search
  729. * @index: The starting page index
  730. * @nr_pages: The maximum number of pages
  731. * @pages: Where the resulting pages are placed
  732. *
  733. * find_get_pages_contig() works exactly like find_get_pages(), except
  734. * that the returned number of pages are guaranteed to be contiguous.
  735. *
  736. * find_get_pages_contig() returns the number of pages which were found.
  737. */
  738. unsigned find_get_pages_contig(struct address_space *mapping, pgoff_t index,
  739. unsigned int nr_pages, struct page **pages)
  740. {
  741. unsigned int i;
  742. unsigned int ret;
  743. unsigned int nr_found;
  744. rcu_read_lock();
  745. restart:
  746. nr_found = radix_tree_gang_lookup_slot(&mapping->page_tree,
  747. (void ***)pages, index, nr_pages);
  748. ret = 0;
  749. for (i = 0; i < nr_found; i++) {
  750. struct page *page;
  751. repeat:
  752. page = radix_tree_deref_slot((void **)pages[i]);
  753. if (unlikely(!page))
  754. continue;
  755. /*
  756. * this can only trigger if nr_found == 1, making livelock
  757. * a non issue.
  758. */
  759. if (unlikely(page == RADIX_TREE_RETRY))
  760. goto restart;
  761. if (page->mapping == NULL || page->index != index)
  762. break;
  763. if (!page_cache_get_speculative(page))
  764. goto repeat;
  765. /* Has the page moved? */
  766. if (unlikely(page != *((void **)pages[i]))) {
  767. page_cache_release(page);
  768. goto repeat;
  769. }
  770. pages[ret] = page;
  771. ret++;
  772. index++;
  773. }
  774. rcu_read_unlock();
  775. return ret;
  776. }
  777. EXPORT_SYMBOL(find_get_pages_contig);
  778. /**
  779. * find_get_pages_tag - find and return pages that match @tag
  780. * @mapping: the address_space to search
  781. * @index: the starting page index
  782. * @tag: the tag index
  783. * @nr_pages: the maximum number of pages
  784. * @pages: where the resulting pages are placed
  785. *
  786. * Like find_get_pages, except we only return pages which are tagged with
  787. * @tag. We update @index to index the next page for the traversal.
  788. */
  789. unsigned find_get_pages_tag(struct address_space *mapping, pgoff_t *index,
  790. int tag, unsigned int nr_pages, struct page **pages)
  791. {
  792. unsigned int i;
  793. unsigned int ret;
  794. unsigned int nr_found;
  795. rcu_read_lock();
  796. restart:
  797. nr_found = radix_tree_gang_lookup_tag_slot(&mapping->page_tree,
  798. (void ***)pages, *index, nr_pages, tag);
  799. ret = 0;
  800. for (i = 0; i < nr_found; i++) {
  801. struct page *page;
  802. repeat:
  803. page = radix_tree_deref_slot((void **)pages[i]);
  804. if (unlikely(!page))
  805. continue;
  806. /*
  807. * this can only trigger if nr_found == 1, making livelock
  808. * a non issue.
  809. */
  810. if (unlikely(page == RADIX_TREE_RETRY))
  811. goto restart;
  812. if (!page_cache_get_speculative(page))
  813. goto repeat;
  814. /* Has the page moved? */
  815. if (unlikely(page != *((void **)pages[i]))) {
  816. page_cache_release(page);
  817. goto repeat;
  818. }
  819. pages[ret] = page;
  820. ret++;
  821. }
  822. rcu_read_unlock();
  823. if (ret)
  824. *index = pages[ret - 1]->index + 1;
  825. return ret;
  826. }
  827. EXPORT_SYMBOL(find_get_pages_tag);
  828. /**
  829. * grab_cache_page_nowait - returns locked page at given index in given cache
  830. * @mapping: target address_space
  831. * @index: the page index
  832. *
  833. * Same as grab_cache_page(), but do not wait if the page is unavailable.
  834. * This is intended for speculative data generators, where the data can
  835. * be regenerated if the page couldn't be grabbed. This routine should
  836. * be safe to call while holding the lock for another page.
  837. *
  838. * Clear __GFP_FS when allocating the page to avoid recursion into the fs
  839. * and deadlock against the caller's locked page.
  840. */
  841. struct page *
  842. grab_cache_page_nowait(struct address_space *mapping, pgoff_t index)
  843. {
  844. struct page *page = find_get_page(mapping, index);
  845. if (page) {
  846. if (trylock_page(page))
  847. return page;
  848. page_cache_release(page);
  849. return NULL;
  850. }
  851. page = __page_cache_alloc(mapping_gfp_mask(mapping) & ~__GFP_FS);
  852. if (page && add_to_page_cache_lru(page, mapping, index, GFP_NOFS)) {
  853. page_cache_release(page);
  854. page = NULL;
  855. }
  856. return page;
  857. }
  858. EXPORT_SYMBOL(grab_cache_page_nowait);
  859. /*
  860. * CD/DVDs are error prone. When a medium error occurs, the driver may fail
  861. * a _large_ part of the i/o request. Imagine the worst scenario:
  862. *
  863. * ---R__________________________________________B__________
  864. * ^ reading here ^ bad block(assume 4k)
  865. *
  866. * read(R) => miss => readahead(R...B) => media error => frustrating retries
  867. * => failing the whole request => read(R) => read(R+1) =>
  868. * readahead(R+1...B+1) => bang => read(R+2) => read(R+3) =>
  869. * readahead(R+3...B+2) => bang => read(R+3) => read(R+4) =>
  870. * readahead(R+4...B+3) => bang => read(R+4) => read(R+5) => ......
  871. *
  872. * It is going insane. Fix it by quickly scaling down the readahead size.
  873. */
  874. static void shrink_readahead_size_eio(struct file *filp,
  875. struct file_ra_state *ra)
  876. {
  877. ra->ra_pages /= 4;
  878. }
  879. /**
  880. * do_generic_file_read - generic file read routine
  881. * @filp: the file to read
  882. * @ppos: current file position
  883. * @desc: read_descriptor
  884. * @actor: read method
  885. *
  886. * This is a generic file read routine, and uses the
  887. * mapping->a_ops->readpage() function for the actual low-level stuff.
  888. *
  889. * This is really ugly. But the goto's actually try to clarify some
  890. * of the logic when it comes to error handling etc.
  891. */
  892. static void do_generic_file_read(struct file *filp, loff_t *ppos,
  893. read_descriptor_t *desc, read_actor_t actor)
  894. {
  895. struct address_space *mapping = filp->f_mapping;
  896. struct inode *inode = mapping->host;
  897. struct file_ra_state *ra = &filp->f_ra;
  898. pgoff_t index;
  899. pgoff_t last_index;
  900. pgoff_t prev_index;
  901. unsigned long offset; /* offset into pagecache page */
  902. unsigned int prev_offset;
  903. int error;
  904. index = *ppos >> PAGE_CACHE_SHIFT;
  905. prev_index = ra->prev_pos >> PAGE_CACHE_SHIFT;
  906. prev_offset = ra->prev_pos & (PAGE_CACHE_SIZE-1);
  907. last_index = (*ppos + desc->count + PAGE_CACHE_SIZE-1) >> PAGE_CACHE_SHIFT;
  908. offset = *ppos & ~PAGE_CACHE_MASK;
  909. for (;;) {
  910. struct page *page;
  911. pgoff_t end_index;
  912. loff_t isize;
  913. unsigned long nr, ret;
  914. cond_resched();
  915. find_page:
  916. page = find_get_page(mapping, index);
  917. if (!page) {
  918. page_cache_sync_readahead(mapping,
  919. ra, filp,
  920. index, last_index - index);
  921. page = find_get_page(mapping, index);
  922. if (unlikely(page == NULL))
  923. goto no_cached_page;
  924. }
  925. if (PageReadahead(page)) {
  926. page_cache_async_readahead(mapping,
  927. ra, filp, page,
  928. index, last_index - index);
  929. }
  930. if (!PageUptodate(page)) {
  931. if (inode->i_blkbits == PAGE_CACHE_SHIFT ||
  932. !mapping->a_ops->is_partially_uptodate)
  933. goto page_not_up_to_date;
  934. if (!trylock_page(page))
  935. goto page_not_up_to_date;
  936. if (!mapping->a_ops->is_partially_uptodate(page,
  937. desc, offset))
  938. goto page_not_up_to_date_locked;
  939. unlock_page(page);
  940. }
  941. page_ok:
  942. /*
  943. * i_size must be checked after we know the page is Uptodate.
  944. *
  945. * Checking i_size after the check allows us to calculate
  946. * the correct value for "nr", which means the zero-filled
  947. * part of the page is not copied back to userspace (unless
  948. * another truncate extends the file - this is desired though).
  949. */
  950. isize = i_size_read(inode);
  951. end_index = (isize - 1) >> PAGE_CACHE_SHIFT;
  952. if (unlikely(!isize || index > end_index)) {
  953. page_cache_release(page);
  954. goto out;
  955. }
  956. /* nr is the maximum number of bytes to copy from this page */
  957. nr = PAGE_CACHE_SIZE;
  958. if (index == end_index) {
  959. nr = ((isize - 1) & ~PAGE_CACHE_MASK) + 1;
  960. if (nr <= offset) {
  961. page_cache_release(page);
  962. goto out;
  963. }
  964. }
  965. nr = nr - offset;
  966. /* If users can be writing to this page using arbitrary
  967. * virtual addresses, take care about potential aliasing
  968. * before reading the page on the kernel side.
  969. */
  970. if (mapping_writably_mapped(mapping))
  971. flush_dcache_page(page);
  972. /*
  973. * When a sequential read accesses a page several times,
  974. * only mark it as accessed the first time.
  975. */
  976. if (prev_index != index || offset != prev_offset)
  977. mark_page_accessed(page);
  978. prev_index = index;
  979. /*
  980. * Ok, we have the page, and it's up-to-date, so
  981. * now we can copy it to user space...
  982. *
  983. * The actor routine returns how many bytes were actually used..
  984. * NOTE! This may not be the same as how much of a user buffer
  985. * we filled up (we may be padding etc), so we can only update
  986. * "pos" here (the actor routine has to update the user buffer
  987. * pointers and the remaining count).
  988. */
  989. ret = actor(desc, page, offset, nr);
  990. offset += ret;
  991. index += offset >> PAGE_CACHE_SHIFT;
  992. offset &= ~PAGE_CACHE_MASK;
  993. prev_offset = offset;
  994. page_cache_release(page);
  995. if (ret == nr && desc->count)
  996. continue;
  997. goto out;
  998. page_not_up_to_date:
  999. /* Get exclusive access to the page ... */
  1000. error = lock_page_killable(page);
  1001. if (unlikely(error))
  1002. goto readpage_error;
  1003. page_not_up_to_date_locked:
  1004. /* Did it get truncated before we got the lock? */
  1005. if (!page->mapping) {
  1006. unlock_page(page);
  1007. page_cache_release(page);
  1008. continue;
  1009. }
  1010. /* Did somebody else fill it already? */
  1011. if (PageUptodate(page)) {
  1012. unlock_page(page);
  1013. goto page_ok;
  1014. }
  1015. readpage:
  1016. /* Start the actual read. The read will unlock the page. */
  1017. error = mapping->a_ops->readpage(filp, page);
  1018. if (unlikely(error)) {
  1019. if (error == AOP_TRUNCATED_PAGE) {
  1020. page_cache_release(page);
  1021. goto find_page;
  1022. }
  1023. goto readpage_error;
  1024. }
  1025. if (!PageUptodate(page)) {
  1026. error = lock_page_killable(page);
  1027. if (unlikely(error))
  1028. goto readpage_error;
  1029. if (!PageUptodate(page)) {
  1030. if (page->mapping == NULL) {
  1031. /*
  1032. * invalidate_inode_pages got it
  1033. */
  1034. unlock_page(page);
  1035. page_cache_release(page);
  1036. goto find_page;
  1037. }
  1038. unlock_page(page);
  1039. shrink_readahead_size_eio(filp, ra);
  1040. error = -EIO;
  1041. goto readpage_error;
  1042. }
  1043. unlock_page(page);
  1044. }
  1045. goto page_ok;
  1046. readpage_error:
  1047. /* UHHUH! A synchronous read error occurred. Report it */
  1048. desc->error = error;
  1049. page_cache_release(page);
  1050. goto out;
  1051. no_cached_page:
  1052. /*
  1053. * Ok, it wasn't cached, so we need to create a new
  1054. * page..
  1055. */
  1056. page = page_cache_alloc_cold(mapping);
  1057. if (!page) {
  1058. desc->error = -ENOMEM;
  1059. goto out;
  1060. }
  1061. error = add_to_page_cache_lru(page, mapping,
  1062. index, GFP_KERNEL);
  1063. if (error) {
  1064. page_cache_release(page);
  1065. if (error == -EEXIST)
  1066. goto find_page;
  1067. desc->error = error;
  1068. goto out;
  1069. }
  1070. goto readpage;
  1071. }
  1072. out:
  1073. ra->prev_pos = prev_index;
  1074. ra->prev_pos <<= PAGE_CACHE_SHIFT;
  1075. ra->prev_pos |= prev_offset;
  1076. *ppos = ((loff_t)index << PAGE_CACHE_SHIFT) + offset;
  1077. file_accessed(filp);
  1078. }
  1079. int file_read_actor(read_descriptor_t *desc, struct page *page,
  1080. unsigned long offset, unsigned long size)
  1081. {
  1082. char *kaddr;
  1083. unsigned long left, count = desc->count;
  1084. if (size > count)
  1085. size = count;
  1086. /*
  1087. * Faults on the destination of a read are common, so do it before
  1088. * taking the kmap.
  1089. */
  1090. if (!fault_in_pages_writeable(desc->arg.buf, size)) {
  1091. kaddr = kmap_atomic(page, KM_USER0);
  1092. left = __copy_to_user_inatomic(desc->arg.buf,
  1093. kaddr + offset, size);
  1094. kunmap_atomic(kaddr, KM_USER0);
  1095. if (left == 0)
  1096. goto success;
  1097. }
  1098. /* Do it the slow way */
  1099. kaddr = kmap(page);
  1100. left = __copy_to_user(desc->arg.buf, kaddr + offset, size);
  1101. kunmap(page);
  1102. if (left) {
  1103. size -= left;
  1104. desc->error = -EFAULT;
  1105. }
  1106. success:
  1107. desc->count = count - size;
  1108. desc->written += size;
  1109. desc->arg.buf += size;
  1110. return size;
  1111. }
  1112. /*
  1113. * Performs necessary checks before doing a write
  1114. * @iov: io vector request
  1115. * @nr_segs: number of segments in the iovec
  1116. * @count: number of bytes to write
  1117. * @access_flags: type of access: %VERIFY_READ or %VERIFY_WRITE
  1118. *
  1119. * Adjust number of segments and amount of bytes to write (nr_segs should be
  1120. * properly initialized first). Returns appropriate error code that caller
  1121. * should return or zero in case that write should be allowed.
  1122. */
  1123. int generic_segment_checks(const struct iovec *iov,
  1124. unsigned long *nr_segs, size_t *count, int access_flags)
  1125. {
  1126. unsigned long seg;
  1127. size_t cnt = 0;
  1128. for (seg = 0; seg < *nr_segs; seg++) {
  1129. const struct iovec *iv = &iov[seg];
  1130. /*
  1131. * If any segment has a negative length, or the cumulative
  1132. * length ever wraps negative then return -EINVAL.
  1133. */
  1134. cnt += iv->iov_len;
  1135. if (unlikely((ssize_t)(cnt|iv->iov_len) < 0))
  1136. return -EINVAL;
  1137. if (access_ok(access_flags, iv->iov_base, iv->iov_len))
  1138. continue;
  1139. if (seg == 0)
  1140. return -EFAULT;
  1141. *nr_segs = seg;
  1142. cnt -= iv->iov_len; /* This segment is no good */
  1143. break;
  1144. }
  1145. *count = cnt;
  1146. return 0;
  1147. }
  1148. EXPORT_SYMBOL(generic_segment_checks);
  1149. /**
  1150. * generic_file_aio_read - generic filesystem read routine
  1151. * @iocb: kernel I/O control block
  1152. * @iov: io vector request
  1153. * @nr_segs: number of segments in the iovec
  1154. * @pos: current file position
  1155. *
  1156. * This is the "read()" routine for all filesystems
  1157. * that can use the page cache directly.
  1158. */
  1159. ssize_t
  1160. generic_file_aio_read(struct kiocb *iocb, const struct iovec *iov,
  1161. unsigned long nr_segs, loff_t pos)
  1162. {
  1163. struct file *filp = iocb->ki_filp;
  1164. ssize_t retval;
  1165. unsigned long seg;
  1166. size_t count;
  1167. loff_t *ppos = &iocb->ki_pos;
  1168. count = 0;
  1169. retval = generic_segment_checks(iov, &nr_segs, &count, VERIFY_WRITE);
  1170. if (retval)
  1171. return retval;
  1172. /* coalesce the iovecs and go direct-to-BIO for O_DIRECT */
  1173. if (filp->f_flags & O_DIRECT) {
  1174. loff_t size;
  1175. struct address_space *mapping;
  1176. struct inode *inode;
  1177. mapping = filp->f_mapping;
  1178. inode = mapping->host;
  1179. if (!count)
  1180. goto out; /* skip atime */
  1181. size = i_size_read(inode);
  1182. if (pos < size) {
  1183. retval = filemap_write_and_wait_range(mapping, pos,
  1184. pos + iov_length(iov, nr_segs) - 1);
  1185. if (!retval) {
  1186. retval = mapping->a_ops->direct_IO(READ, iocb,
  1187. iov, pos, nr_segs);
  1188. }
  1189. if (retval > 0)
  1190. *ppos = pos + retval;
  1191. if (retval) {
  1192. file_accessed(filp);
  1193. goto out;
  1194. }
  1195. }
  1196. }
  1197. for (seg = 0; seg < nr_segs; seg++) {
  1198. read_descriptor_t desc;
  1199. desc.written = 0;
  1200. desc.arg.buf = iov[seg].iov_base;
  1201. desc.count = iov[seg].iov_len;
  1202. if (desc.count == 0)
  1203. continue;
  1204. desc.error = 0;
  1205. do_generic_file_read(filp, ppos, &desc, file_read_actor);
  1206. retval += desc.written;
  1207. if (desc.error) {
  1208. retval = retval ?: desc.error;
  1209. break;
  1210. }
  1211. if (desc.count > 0)
  1212. break;
  1213. }
  1214. out:
  1215. return retval;
  1216. }
  1217. EXPORT_SYMBOL(generic_file_aio_read);
  1218. static ssize_t
  1219. do_readahead(struct address_space *mapping, struct file *filp,
  1220. pgoff_t index, unsigned long nr)
  1221. {
  1222. if (!mapping || !mapping->a_ops || !mapping->a_ops->readpage)
  1223. return -EINVAL;
  1224. force_page_cache_readahead(mapping, filp, index, nr);
  1225. return 0;
  1226. }
  1227. SYSCALL_DEFINE(readahead)(int fd, loff_t offset, size_t count)
  1228. {
  1229. ssize_t ret;
  1230. struct file *file;
  1231. ret = -EBADF;
  1232. file = fget(fd);
  1233. if (file) {
  1234. if (file->f_mode & FMODE_READ) {
  1235. struct address_space *mapping = file->f_mapping;
  1236. pgoff_t start = offset >> PAGE_CACHE_SHIFT;
  1237. pgoff_t end = (offset + count - 1) >> PAGE_CACHE_SHIFT;
  1238. unsigned long len = end - start + 1;
  1239. ret = do_readahead(mapping, file, start, len);
  1240. }
  1241. fput(file);
  1242. }
  1243. return ret;
  1244. }
  1245. #ifdef CONFIG_HAVE_SYSCALL_WRAPPERS
  1246. asmlinkage long SyS_readahead(long fd, loff_t offset, long count)
  1247. {
  1248. return SYSC_readahead((int) fd, offset, (size_t) count);
  1249. }
  1250. SYSCALL_ALIAS(sys_readahead, SyS_readahead);
  1251. #endif
  1252. #ifdef CONFIG_MMU
  1253. /**
  1254. * page_cache_read - adds requested page to the page cache if not already there
  1255. * @file: file to read
  1256. * @offset: page index
  1257. *
  1258. * This adds the requested page to the page cache if it isn't already there,
  1259. * and schedules an I/O to read in its contents from disk.
  1260. */
  1261. static int page_cache_read(struct file *file, pgoff_t offset)
  1262. {
  1263. struct address_space *mapping = file->f_mapping;
  1264. struct page *page;
  1265. int ret;
  1266. do {
  1267. page = page_cache_alloc_cold(mapping);
  1268. if (!page)
  1269. return -ENOMEM;
  1270. ret = add_to_page_cache_lru(page, mapping, offset, GFP_KERNEL);
  1271. if (ret == 0)
  1272. ret = mapping->a_ops->readpage(file, page);
  1273. else if (ret == -EEXIST)
  1274. ret = 0; /* losing race to add is OK */
  1275. page_cache_release(page);
  1276. } while (ret == AOP_TRUNCATED_PAGE);
  1277. return ret;
  1278. }
  1279. #define MMAP_LOTSAMISS (100)
  1280. /*
  1281. * Synchronous readahead happens when we don't even find
  1282. * a page in the page cache at all.
  1283. */
  1284. static void do_sync_mmap_readahead(struct vm_area_struct *vma,
  1285. struct file_ra_state *ra,
  1286. struct file *file,
  1287. pgoff_t offset)
  1288. {
  1289. unsigned long ra_pages;
  1290. struct address_space *mapping = file->f_mapping;
  1291. /* If we don't want any read-ahead, don't bother */
  1292. if (VM_RandomReadHint(vma))
  1293. return;
  1294. if (VM_SequentialReadHint(vma) ||
  1295. offset - 1 == (ra->prev_pos >> PAGE_CACHE_SHIFT)) {
  1296. page_cache_sync_readahead(mapping, ra, file, offset,
  1297. ra->ra_pages);
  1298. return;
  1299. }
  1300. if (ra->mmap_miss < INT_MAX)
  1301. ra->mmap_miss++;
  1302. /*
  1303. * Do we miss much more than hit in this file? If so,
  1304. * stop bothering with read-ahead. It will only hurt.
  1305. */
  1306. if (ra->mmap_miss > MMAP_LOTSAMISS)
  1307. return;
  1308. /*
  1309. * mmap read-around
  1310. */
  1311. ra_pages = max_sane_readahead(ra->ra_pages);
  1312. if (ra_pages) {
  1313. ra->start = max_t(long, 0, offset - ra_pages/2);
  1314. ra->size = ra_pages;
  1315. ra->async_size = 0;
  1316. ra_submit(ra, mapping, file);
  1317. }
  1318. }
  1319. /*
  1320. * Asynchronous readahead happens when we find the page and PG_readahead,
  1321. * so we want to possibly extend the readahead further..
  1322. */
  1323. static void do_async_mmap_readahead(struct vm_area_struct *vma,
  1324. struct file_ra_state *ra,
  1325. struct file *file,
  1326. struct page *page,
  1327. pgoff_t offset)
  1328. {
  1329. struct address_space *mapping = file->f_mapping;
  1330. /* If we don't want any read-ahead, don't bother */
  1331. if (VM_RandomReadHint(vma))
  1332. return;
  1333. if (ra->mmap_miss > 0)
  1334. ra->mmap_miss--;
  1335. if (PageReadahead(page))
  1336. page_cache_async_readahead(mapping, ra, file,
  1337. page, offset, ra->ra_pages);
  1338. }
  1339. /**
  1340. * filemap_fault - read in file data for page fault handling
  1341. * @vma: vma in which the fault was taken
  1342. * @vmf: struct vm_fault containing details of the fault
  1343. *
  1344. * filemap_fault() is invoked via the vma operations vector for a
  1345. * mapped memory region to read in file data during a page fault.
  1346. *
  1347. * The goto's are kind of ugly, but this streamlines the normal case of having
  1348. * it in the page cache, and handles the special cases reasonably without
  1349. * having a lot of duplicated code.
  1350. */
  1351. int filemap_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
  1352. {
  1353. int error;
  1354. struct file *file = vma->vm_file;
  1355. struct address_space *mapping = file->f_mapping;
  1356. struct file_ra_state *ra = &file->f_ra;
  1357. struct inode *inode = mapping->host;
  1358. pgoff_t offset = vmf->pgoff;
  1359. struct page *page;
  1360. pgoff_t size;
  1361. int ret = 0;
  1362. size = (i_size_read(inode) + PAGE_CACHE_SIZE - 1) >> PAGE_CACHE_SHIFT;
  1363. if (offset >= size)
  1364. return VM_FAULT_SIGBUS;
  1365. /*
  1366. * Do we have something in the page cache already?
  1367. */
  1368. page = find_get_page(mapping, offset);
  1369. if (likely(page)) {
  1370. /*
  1371. * We found the page, so try async readahead before
  1372. * waiting for the lock.
  1373. */
  1374. do_async_mmap_readahead(vma, ra, file, page, offset);
  1375. lock_page(page);
  1376. /* Did it get truncated? */
  1377. if (unlikely(page->mapping != mapping)) {
  1378. unlock_page(page);
  1379. put_page(page);
  1380. goto no_cached_page;
  1381. }
  1382. } else {
  1383. /* No page in the page cache at all */
  1384. do_sync_mmap_readahead(vma, ra, file, offset);
  1385. count_vm_event(PGMAJFAULT);
  1386. ret = VM_FAULT_MAJOR;
  1387. retry_find:
  1388. page = find_lock_page(mapping, offset);
  1389. if (!page)
  1390. goto no_cached_page;
  1391. }
  1392. /*
  1393. * We have a locked page in the page cache, now we need to check
  1394. * that it's up-to-date. If not, it is going to be due to an error.
  1395. */
  1396. if (unlikely(!PageUptodate(page)))
  1397. goto page_not_uptodate;
  1398. /*
  1399. * Found the page and have a reference on it.
  1400. * We must recheck i_size under page lock.
  1401. */
  1402. size = (i_size_read(inode) + PAGE_CACHE_SIZE - 1) >> PAGE_CACHE_SHIFT;
  1403. if (unlikely(offset >= size)) {
  1404. unlock_page(page);
  1405. page_cache_release(page);
  1406. return VM_FAULT_SIGBUS;
  1407. }
  1408. ra->prev_pos = (loff_t)offset << PAGE_CACHE_SHIFT;
  1409. vmf->page = page;
  1410. return ret | VM_FAULT_LOCKED;
  1411. no_cached_page:
  1412. /*
  1413. * We're only likely to ever get here if MADV_RANDOM is in
  1414. * effect.
  1415. */
  1416. error = page_cache_read(file, offset);
  1417. /*
  1418. * The page we want has now been added to the page cache.
  1419. * In the unlikely event that someone removed it in the
  1420. * meantime, we'll just come back here and read it again.
  1421. */
  1422. if (error >= 0)
  1423. goto retry_find;
  1424. /*
  1425. * An error return from page_cache_read can result if the
  1426. * system is low on memory, or a problem occurs while trying
  1427. * to schedule I/O.
  1428. */
  1429. if (error == -ENOMEM)
  1430. return VM_FAULT_OOM;
  1431. return VM_FAULT_SIGBUS;
  1432. page_not_uptodate:
  1433. /*
  1434. * Umm, take care of errors if the page isn't up-to-date.
  1435. * Try to re-read it _once_. We do this synchronously,
  1436. * because there really aren't any performance issues here
  1437. * and we need to check for errors.
  1438. */
  1439. ClearPageError(page);
  1440. error = mapping->a_ops->readpage(file, page);
  1441. if (!error) {
  1442. wait_on_page_locked(page);
  1443. if (!PageUptodate(page))
  1444. error = -EIO;
  1445. }
  1446. page_cache_release(page);
  1447. if (!error || error == AOP_TRUNCATED_PAGE)
  1448. goto retry_find;
  1449. /* Things didn't work out. Return zero to tell the mm layer so. */
  1450. shrink_readahead_size_eio(file, ra);
  1451. return VM_FAULT_SIGBUS;
  1452. }
  1453. EXPORT_SYMBOL(filemap_fault);
  1454. const struct vm_operations_struct generic_file_vm_ops = {
  1455. .fault = filemap_fault,
  1456. };
  1457. /* This is used for a general mmap of a disk file */
  1458. int generic_file_mmap(struct file * file, struct vm_area_struct * vma)
  1459. {
  1460. struct address_space *mapping = file->f_mapping;
  1461. if (!mapping->a_ops->readpage)
  1462. return -ENOEXEC;
  1463. file_accessed(file);
  1464. vma->vm_ops = &generic_file_vm_ops;
  1465. vma->vm_flags |= VM_CAN_NONLINEAR;
  1466. return 0;
  1467. }
  1468. /*
  1469. * This is for filesystems which do not implement ->writepage.
  1470. */
  1471. int generic_file_readonly_mmap(struct file *file, struct vm_area_struct *vma)
  1472. {
  1473. if ((vma->vm_flags & VM_SHARED) && (vma->vm_flags & VM_MAYWRITE))
  1474. return -EINVAL;
  1475. return generic_file_mmap(file, vma);
  1476. }
  1477. #else
  1478. int generic_file_mmap(struct file * file, struct vm_area_struct * vma)
  1479. {
  1480. return -ENOSYS;
  1481. }
  1482. int generic_file_readonly_mmap(struct file * file, struct vm_area_struct * vma)
  1483. {
  1484. return -ENOSYS;
  1485. }
  1486. #endif /* CONFIG_MMU */
  1487. EXPORT_SYMBOL(generic_file_mmap);
  1488. EXPORT_SYMBOL(generic_file_readonly_mmap);
  1489. static struct page *__read_cache_page(struct address_space *mapping,
  1490. pgoff_t index,
  1491. int (*filler)(void *,struct page*),
  1492. void *data)
  1493. {
  1494. struct page *page;
  1495. int err;
  1496. repeat:
  1497. page = find_get_page(mapping, index);
  1498. if (!page) {
  1499. page = page_cache_alloc_cold(mapping);
  1500. if (!page)
  1501. return ERR_PTR(-ENOMEM);
  1502. err = add_to_page_cache_lru(page, mapping, index, GFP_KERNEL);
  1503. if (unlikely(err)) {
  1504. page_cache_release(page);
  1505. if (err == -EEXIST)
  1506. goto repeat;
  1507. /* Presumably ENOMEM for radix tree node */
  1508. return ERR_PTR(err);
  1509. }
  1510. err = filler(data, page);
  1511. if (err < 0) {
  1512. page_cache_release(page);
  1513. page = ERR_PTR(err);
  1514. }
  1515. }
  1516. return page;
  1517. }
  1518. /**
  1519. * read_cache_page_async - read into page cache, fill it if needed
  1520. * @mapping: the page's address_space
  1521. * @index: the page index
  1522. * @filler: function to perform the read
  1523. * @data: destination for read data
  1524. *
  1525. * Same as read_cache_page, but don't wait for page to become unlocked
  1526. * after submitting it to the filler.
  1527. *
  1528. * Read into the page cache. If a page already exists, and PageUptodate() is
  1529. * not set, try to fill the page but don't wait for it to become unlocked.
  1530. *
  1531. * If the page does not get brought uptodate, return -EIO.
  1532. */
  1533. struct page *read_cache_page_async(struct address_space *mapping,
  1534. pgoff_t index,
  1535. int (*filler)(void *,struct page*),
  1536. void *data)
  1537. {
  1538. struct page *page;
  1539. int err;
  1540. retry:
  1541. page = __read_cache_page(mapping, index, filler, data);
  1542. if (IS_ERR(page))
  1543. return page;
  1544. if (PageUptodate(page))
  1545. goto out;
  1546. lock_page(page);
  1547. if (!page->mapping) {
  1548. unlock_page(page);
  1549. page_cache_release(page);
  1550. goto retry;
  1551. }
  1552. if (PageUptodate(page)) {
  1553. unlock_page(page);
  1554. goto out;
  1555. }
  1556. err = filler(data, page);
  1557. if (err < 0) {
  1558. page_cache_release(page);
  1559. return ERR_PTR(err);
  1560. }
  1561. out:
  1562. mark_page_accessed(page);
  1563. return page;
  1564. }
  1565. EXPORT_SYMBOL(read_cache_page_async);
  1566. /**
  1567. * read_cache_page - read into page cache, fill it if needed
  1568. * @mapping: the page's address_space
  1569. * @index: the page index
  1570. * @filler: function to perform the read
  1571. * @data: destination for read data
  1572. *
  1573. * Read into the page cache. If a page already exists, and PageUptodate() is
  1574. * not set, try to fill the page then wait for it to become unlocked.
  1575. *
  1576. * If the page does not get brought uptodate, return -EIO.
  1577. */
  1578. struct page *read_cache_page(struct address_space *mapping,
  1579. pgoff_t index,
  1580. int (*filler)(void *,struct page*),
  1581. void *data)
  1582. {
  1583. struct page *page;
  1584. page = read_cache_page_async(mapping, index, filler, data);
  1585. if (IS_ERR(page))
  1586. goto out;
  1587. wait_on_page_locked(page);
  1588. if (!PageUptodate(page)) {
  1589. page_cache_release(page);
  1590. page = ERR_PTR(-EIO);
  1591. }
  1592. out:
  1593. return page;
  1594. }
  1595. EXPORT_SYMBOL(read_cache_page);
  1596. /*
  1597. * The logic we want is
  1598. *
  1599. * if suid or (sgid and xgrp)
  1600. * remove privs
  1601. */
  1602. int should_remove_suid(struct dentry *dentry)
  1603. {
  1604. mode_t mode = dentry->d_inode->i_mode;
  1605. int kill = 0;
  1606. /* suid always must be killed */
  1607. if (unlikely(mode & S_ISUID))
  1608. kill = ATTR_KILL_SUID;
  1609. /*
  1610. * sgid without any exec bits is just a mandatory locking mark; leave
  1611. * it alone. If some exec bits are set, it's a real sgid; kill it.
  1612. */
  1613. if (unlikely((mode & S_ISGID) && (mode & S_IXGRP)))
  1614. kill |= ATTR_KILL_SGID;
  1615. if (unlikely(kill && !capable(CAP_FSETID) && S_ISREG(mode)))
  1616. return kill;
  1617. return 0;
  1618. }
  1619. EXPORT_SYMBOL(should_remove_suid);
  1620. static int __remove_suid(struct dentry *dentry, int kill)
  1621. {
  1622. struct iattr newattrs;
  1623. newattrs.ia_valid = ATTR_FORCE | kill;
  1624. return notify_change(dentry, &newattrs);
  1625. }
  1626. int file_remove_suid(struct file *file)
  1627. {
  1628. struct dentry *dentry = file->f_path.dentry;
  1629. int killsuid = should_remove_suid(dentry);
  1630. int killpriv = security_inode_need_killpriv(dentry);
  1631. int error = 0;
  1632. if (killpriv < 0)
  1633. return killpriv;
  1634. if (killpriv)
  1635. error = security_inode_killpriv(dentry);
  1636. if (!error && killsuid)
  1637. error = __remove_suid(dentry, killsuid);
  1638. return error;
  1639. }
  1640. EXPORT_SYMBOL(file_remove_suid);
  1641. static size_t __iovec_copy_from_user_inatomic(char *vaddr,
  1642. const struct iovec *iov, size_t base, size_t bytes)
  1643. {
  1644. size_t copied = 0, left = 0;
  1645. while (bytes) {
  1646. char __user *buf = iov->iov_base + base;
  1647. int copy = min(bytes, iov->iov_len - base);
  1648. base = 0;
  1649. left = __copy_from_user_inatomic(vaddr, buf, copy);
  1650. copied += copy;
  1651. bytes -= copy;
  1652. vaddr += copy;
  1653. iov++;
  1654. if (unlikely(left))
  1655. break;
  1656. }
  1657. return copied - left;
  1658. }
  1659. /*
  1660. * Copy as much as we can into the page and return the number of bytes which
  1661. * were sucessfully copied. If a fault is encountered then return the number of
  1662. * bytes which were copied.
  1663. */
  1664. size_t iov_iter_copy_from_user_atomic(struct page *page,
  1665. struct iov_iter *i, unsigned long offset, size_t bytes)
  1666. {
  1667. char *kaddr;
  1668. size_t copied;
  1669. BUG_ON(!in_atomic());
  1670. kaddr = kmap_atomic(page, KM_USER0);
  1671. if (likely(i->nr_segs == 1)) {
  1672. int left;
  1673. char __user *buf = i->iov->iov_base + i->iov_offset;
  1674. left = __copy_from_user_inatomic(kaddr + offset, buf, bytes);
  1675. copied = bytes - left;
  1676. } else {
  1677. copied = __iovec_copy_from_user_inatomic(kaddr + offset,
  1678. i->iov, i->iov_offset, bytes);
  1679. }
  1680. kunmap_atomic(kaddr, KM_USER0);
  1681. return copied;
  1682. }
  1683. EXPORT_SYMBOL(iov_iter_copy_from_user_atomic);
  1684. /*
  1685. * This has the same sideeffects and return value as
  1686. * iov_iter_copy_from_user_atomic().
  1687. * The difference is that it attempts to resolve faults.
  1688. * Page must not be locked.
  1689. */
  1690. size_t iov_iter_copy_from_user(struct page *page,
  1691. struct iov_iter *i, unsigned long offset, size_t bytes)
  1692. {
  1693. char *kaddr;
  1694. size_t copied;
  1695. kaddr = kmap(page);
  1696. if (likely(i->nr_segs == 1)) {
  1697. int left;
  1698. char __user *buf = i->iov->iov_base + i->iov_offset;
  1699. left = __copy_from_user(kaddr + offset, buf, bytes);
  1700. copied = bytes - left;
  1701. } else {
  1702. copied = __iovec_copy_from_user_inatomic(kaddr + offset,
  1703. i->iov, i->iov_offset, bytes);
  1704. }
  1705. kunmap(page);
  1706. return copied;
  1707. }
  1708. EXPORT_SYMBOL(iov_iter_copy_from_user);
  1709. void iov_iter_advance(struct iov_iter *i, size_t bytes)
  1710. {
  1711. BUG_ON(i->count < bytes);
  1712. if (likely(i->nr_segs == 1)) {
  1713. i->iov_offset += bytes;
  1714. i->count -= bytes;
  1715. } else {
  1716. const struct iovec *iov = i->iov;
  1717. size_t base = i->iov_offset;
  1718. /*
  1719. * The !iov->iov_len check ensures we skip over unlikely
  1720. * zero-length segments (without overruning the iovec).
  1721. */
  1722. while (bytes || unlikely(i->count && !iov->iov_len)) {
  1723. int copy;
  1724. copy = min(bytes, iov->iov_len - base);
  1725. BUG_ON(!i->count || i->count < copy);
  1726. i->count -= copy;
  1727. bytes -= copy;
  1728. base += copy;
  1729. if (iov->iov_len == base) {
  1730. iov++;
  1731. base = 0;
  1732. }
  1733. }
  1734. i->iov = iov;
  1735. i->iov_offset = base;
  1736. }
  1737. }
  1738. EXPORT_SYMBOL(iov_iter_advance);
  1739. /*
  1740. * Fault in the first iovec of the given iov_iter, to a maximum length
  1741. * of bytes. Returns 0 on success, or non-zero if the memory could not be
  1742. * accessed (ie. because it is an invalid address).
  1743. *
  1744. * writev-intensive code may want this to prefault several iovecs -- that
  1745. * would be possible (callers must not rely on the fact that _only_ the
  1746. * first iovec will be faulted with the current implementation).
  1747. */
  1748. int iov_iter_fault_in_readable(struct iov_iter *i, size_t bytes)
  1749. {
  1750. char __user *buf = i->iov->iov_base + i->iov_offset;
  1751. bytes = min(bytes, i->iov->iov_len - i->iov_offset);
  1752. return fault_in_pages_readable(buf, bytes);
  1753. }
  1754. EXPORT_SYMBOL(iov_iter_fault_in_readable);
  1755. /*
  1756. * Return the count of just the current iov_iter segment.
  1757. */
  1758. size_t iov_iter_single_seg_count(struct iov_iter *i)
  1759. {
  1760. const struct iovec *iov = i->iov;
  1761. if (i->nr_segs == 1)
  1762. return i->count;
  1763. else
  1764. return min(i->count, iov->iov_len - i->iov_offset);
  1765. }
  1766. EXPORT_SYMBOL(iov_iter_single_seg_count);
  1767. /*
  1768. * Performs necessary checks before doing a write
  1769. *
  1770. * Can adjust writing position or amount of bytes to write.
  1771. * Returns appropriate error code that caller should return or
  1772. * zero in case that write should be allowed.
  1773. */
  1774. inline int generic_write_checks(struct file *file, loff_t *pos, size_t *count, int isblk)
  1775. {
  1776. struct inode *inode = file->f_mapping->host;
  1777. unsigned long limit = current->signal->rlim[RLIMIT_FSIZE].rlim_cur;
  1778. if (unlikely(*pos < 0))
  1779. return -EINVAL;
  1780. if (!isblk) {
  1781. /* FIXME: this is for backwards compatibility with 2.4 */
  1782. if (file->f_flags & O_APPEND)
  1783. *pos = i_size_read(inode);
  1784. if (limit != RLIM_INFINITY) {
  1785. if (*pos >= limit) {
  1786. send_sig(SIGXFSZ, current, 0);
  1787. return -EFBIG;
  1788. }
  1789. if (*count > limit - (typeof(limit))*pos) {
  1790. *count = limit - (typeof(limit))*pos;
  1791. }
  1792. }
  1793. }
  1794. /*
  1795. * LFS rule
  1796. */
  1797. if (unlikely(*pos + *count > MAX_NON_LFS &&
  1798. !(file->f_flags & O_LARGEFILE))) {
  1799. if (*pos >= MAX_NON_LFS) {
  1800. return -EFBIG;
  1801. }
  1802. if (*count > MAX_NON_LFS - (unsigned long)*pos) {
  1803. *count = MAX_NON_LFS - (unsigned long)*pos;
  1804. }
  1805. }
  1806. /*
  1807. * Are we about to exceed the fs block limit ?
  1808. *
  1809. * If we have written data it becomes a short write. If we have
  1810. * exceeded without writing data we send a signal and return EFBIG.
  1811. * Linus frestrict idea will clean these up nicely..
  1812. */
  1813. if (likely(!isblk)) {
  1814. if (unlikely(*pos >= inode->i_sb->s_maxbytes)) {
  1815. if (*count || *pos > inode->i_sb->s_maxbytes) {
  1816. return -EFBIG;
  1817. }
  1818. /* zero-length writes at ->s_maxbytes are OK */
  1819. }
  1820. if (unlikely(*pos + *count > inode->i_sb->s_maxbytes))
  1821. *count = inode->i_sb->s_maxbytes - *pos;
  1822. } else {
  1823. #ifdef CONFIG_BLOCK
  1824. loff_t isize;
  1825. if (bdev_read_only(I_BDEV(inode)))
  1826. return -EPERM;
  1827. isize = i_size_read(inode);
  1828. if (*pos >= isize) {
  1829. if (*count || *pos > isize)
  1830. return -ENOSPC;
  1831. }
  1832. if (*pos + *count > isize)
  1833. *count = isize - *pos;
  1834. #else
  1835. return -EPERM;
  1836. #endif
  1837. }
  1838. return 0;
  1839. }
  1840. EXPORT_SYMBOL(generic_write_checks);
  1841. int pagecache_write_begin(struct file *file, struct address_space *mapping,
  1842. loff_t pos, unsigned len, unsigned flags,
  1843. struct page **pagep, void **fsdata)
  1844. {
  1845. const struct address_space_operations *aops = mapping->a_ops;
  1846. return aops->write_begin(file, mapping, pos, len, flags,
  1847. pagep, fsdata);
  1848. }
  1849. EXPORT_SYMBOL(pagecache_write_begin);
  1850. int pagecache_write_end(struct file *file, struct address_space *mapping,
  1851. loff_t pos, unsigned len, unsigned copied,
  1852. struct page *page, void *fsdata)
  1853. {
  1854. const struct address_space_operations *aops = mapping->a_ops;
  1855. mark_page_accessed(page);
  1856. return aops->write_end(file, mapping, pos, len, copied, page, fsdata);
  1857. }
  1858. EXPORT_SYMBOL(pagecache_write_end);
  1859. ssize_t
  1860. generic_file_direct_write(struct kiocb *iocb, const struct iovec *iov,
  1861. unsigned long *nr_segs, loff_t pos, loff_t *ppos,
  1862. size_t count, size_t ocount)
  1863. {
  1864. struct file *file = iocb->ki_filp;
  1865. struct address_space *mapping = file->f_mapping;
  1866. struct inode *inode = mapping->host;
  1867. ssize_t written;
  1868. size_t write_len;
  1869. pgoff_t end;
  1870. if (count != ocount)
  1871. *nr_segs = iov_shorten((struct iovec *)iov, *nr_segs, count);
  1872. write_len = iov_length(iov, *nr_segs);
  1873. end = (pos + write_len - 1) >> PAGE_CACHE_SHIFT;
  1874. written = filemap_write_and_wait_range(mapping, pos, pos + write_len - 1);
  1875. if (written)
  1876. goto out;
  1877. /*
  1878. * After a write we want buffered reads to be sure to go to disk to get
  1879. * the new data. We invalidate clean cached page from the region we're
  1880. * about to write. We do this *before* the write so that we can return
  1881. * without clobbering -EIOCBQUEUED from ->direct_IO().
  1882. */
  1883. if (mapping->nrpages) {
  1884. written = invalidate_inode_pages2_range(mapping,
  1885. pos >> PAGE_CACHE_SHIFT, end);
  1886. /*
  1887. * If a page can not be invalidated, return 0 to fall back
  1888. * to buffered write.
  1889. */
  1890. if (written) {
  1891. if (written == -EBUSY)
  1892. return 0;
  1893. goto out;
  1894. }
  1895. }
  1896. written = mapping->a_ops->direct_IO(WRITE, iocb, iov, pos, *nr_segs);
  1897. /*
  1898. * Finally, try again to invalidate clean pages which might have been
  1899. * cached by non-direct readahead, or faulted in by get_user_pages()
  1900. * if the source of the write was an mmap'ed region of the file
  1901. * we're writing. Either one is a pretty crazy thing to do,
  1902. * so we don't support it 100%. If this invalidation
  1903. * fails, tough, the write still worked...
  1904. */
  1905. if (mapping->nrpages) {
  1906. invalidate_inode_pages2_range(mapping,
  1907. pos >> PAGE_CACHE_SHIFT, end);
  1908. }
  1909. if (written > 0) {
  1910. loff_t end = pos + written;
  1911. if (end > i_size_read(inode) && !S_ISBLK(inode->i_mode)) {
  1912. i_size_write(inode, end);
  1913. mark_inode_dirty(inode);
  1914. }
  1915. *ppos = end;
  1916. }
  1917. out:
  1918. return written;
  1919. }
  1920. EXPORT_SYMBOL(generic_file_direct_write);
  1921. /*
  1922. * Find or create a page at the given pagecache position. Return the locked
  1923. * page. This function is specifically for buffered writes.
  1924. */
  1925. struct page *grab_cache_page_write_begin(struct address_space *mapping,
  1926. pgoff_t index, unsigned flags)
  1927. {
  1928. int status;
  1929. struct page *page;
  1930. gfp_t gfp_notmask = 0;
  1931. if (flags & AOP_FLAG_NOFS)
  1932. gfp_notmask = __GFP_FS;
  1933. repeat:
  1934. page = find_lock_page(mapping, index);
  1935. if (likely(page))
  1936. return page;
  1937. page = __page_cache_alloc(mapping_gfp_mask(mapping) & ~gfp_notmask);
  1938. if (!page)
  1939. return NULL;
  1940. status = add_to_page_cache_lru(page, mapping, index,
  1941. GFP_KERNEL & ~gfp_notmask);
  1942. if (unlikely(status)) {
  1943. page_cache_release(page);
  1944. if (status == -EEXIST)
  1945. goto repeat;
  1946. return NULL;
  1947. }
  1948. return page;
  1949. }
  1950. EXPORT_SYMBOL(grab_cache_page_write_begin);
  1951. static ssize_t generic_perform_write(struct file *file,
  1952. struct iov_iter *i, loff_t pos)
  1953. {
  1954. struct address_space *mapping = file->f_mapping;
  1955. const struct address_space_operations *a_ops = mapping->a_ops;
  1956. long status = 0;
  1957. ssize_t written = 0;
  1958. unsigned int flags = 0;
  1959. /*
  1960. * Copies from kernel address space cannot fail (NFSD is a big user).
  1961. */
  1962. if (segment_eq(get_fs(), KERNEL_DS))
  1963. flags |= AOP_FLAG_UNINTERRUPTIBLE;
  1964. do {
  1965. struct page *page;
  1966. pgoff_t index; /* Pagecache index for current page */
  1967. unsigned long offset; /* Offset into pagecache page */
  1968. unsigned long bytes; /* Bytes to write to page */
  1969. size_t copied; /* Bytes copied from user */
  1970. void *fsdata;
  1971. offset = (pos & (PAGE_CACHE_SIZE - 1));
  1972. index = pos >> PAGE_CACHE_SHIFT;
  1973. bytes = min_t(unsigned long, PAGE_CACHE_SIZE - offset,
  1974. iov_iter_count(i));
  1975. again:
  1976. /*
  1977. * Bring in the user page that we will copy from _first_.
  1978. * Otherwise there's a nasty deadlock on copying from the
  1979. * same page as we're writing to, without it being marked
  1980. * up-to-date.
  1981. *
  1982. * Not only is this an optimisation, but it is also required
  1983. * to check that the address is actually valid, when atomic
  1984. * usercopies are used, below.
  1985. */
  1986. if (unlikely(iov_iter_fault_in_readable(i, bytes))) {
  1987. status = -EFAULT;
  1988. break;
  1989. }
  1990. status = a_ops->write_begin(file, mapping, pos, bytes, flags,
  1991. &page, &fsdata);
  1992. if (unlikely(status))
  1993. break;
  1994. pagefault_disable();
  1995. copied = iov_iter_copy_from_user_atomic(page, i, offset, bytes);
  1996. pagefault_enable();
  1997. flush_dcache_page(page);
  1998. mark_page_accessed(page);
  1999. status = a_ops->write_end(file, mapping, pos, bytes, copied,
  2000. page, fsdata);
  2001. if (unlikely(status < 0))
  2002. break;
  2003. copied = status;
  2004. cond_resched();
  2005. iov_iter_advance(i, copied);
  2006. if (unlikely(copied == 0)) {
  2007. /*
  2008. * If we were unable to copy any data at all, we must
  2009. * fall back to a single segment length write.
  2010. *
  2011. * If we didn't fallback here, we could livelock
  2012. * because not all segments in the iov can be copied at
  2013. * once without a pagefault.
  2014. */
  2015. bytes = min_t(unsigned long, PAGE_CACHE_SIZE - offset,
  2016. iov_iter_single_seg_count(i));
  2017. goto again;
  2018. }
  2019. pos += copied;
  2020. written += copied;
  2021. balance_dirty_pages_ratelimited(mapping);
  2022. } while (iov_iter_count(i));
  2023. return written ? written : status;
  2024. }
  2025. ssize_t
  2026. generic_file_buffered_write(struct kiocb *iocb, const struct iovec *iov,
  2027. unsigned long nr_segs, loff_t pos, loff_t *ppos,
  2028. size_t count, ssize_t written)
  2029. {
  2030. struct file *file = iocb->ki_filp;
  2031. struct address_space *mapping = file->f_mapping;
  2032. ssize_t status;
  2033. struct iov_iter i;
  2034. iov_iter_init(&i, iov, nr_segs, count, written);
  2035. status = generic_perform_write(file, &i, pos);
  2036. if (likely(status >= 0)) {
  2037. written += status;
  2038. *ppos = pos + status;
  2039. }
  2040. /*
  2041. * If we get here for O_DIRECT writes then we must have fallen through
  2042. * to buffered writes (block instantiation inside i_size). So we sync
  2043. * the file data here, to try to honour O_DIRECT expectations.
  2044. */
  2045. if (unlikely(file->f_flags & O_DIRECT) && written)
  2046. status = filemap_write_and_wait_range(mapping,
  2047. pos, pos + written - 1);
  2048. return written ? written : status;
  2049. }
  2050. EXPORT_SYMBOL(generic_file_buffered_write);
  2051. /**
  2052. * __generic_file_aio_write - write data to a file
  2053. * @iocb: IO state structure (file, offset, etc.)
  2054. * @iov: vector with data to write
  2055. * @nr_segs: number of segments in the vector
  2056. * @ppos: position where to write
  2057. *
  2058. * This function does all the work needed for actually writing data to a
  2059. * file. It does all basic checks, removes SUID from the file, updates
  2060. * modification times and calls proper subroutines depending on whether we
  2061. * do direct IO or a standard buffered write.
  2062. *
  2063. * It expects i_mutex to be grabbed unless we work on a block device or similar
  2064. * object which does not need locking at all.
  2065. *
  2066. * This function does *not* take care of syncing data in case of O_SYNC write.
  2067. * A caller has to handle it. This is mainly due to the fact that we want to
  2068. * avoid syncing under i_mutex.
  2069. */
  2070. ssize_t __generic_file_aio_write(struct kiocb *iocb, const struct iovec *iov,
  2071. unsigned long nr_segs, loff_t *ppos)
  2072. {
  2073. struct file *file = iocb->ki_filp;
  2074. struct address_space * mapping = file->f_mapping;
  2075. size_t ocount; /* original count */
  2076. size_t count; /* after file limit checks */
  2077. struct inode *inode = mapping->host;
  2078. loff_t pos;
  2079. ssize_t written;
  2080. ssize_t err;
  2081. ocount = 0;
  2082. err = generic_segment_checks(iov, &nr_segs, &ocount, VERIFY_READ);
  2083. if (err)
  2084. return err;
  2085. count = ocount;
  2086. pos = *ppos;
  2087. vfs_check_frozen(inode->i_sb, SB_FREEZE_WRITE);
  2088. /* We can write back this queue in page reclaim */
  2089. current->backing_dev_info = mapping->backing_dev_info;
  2090. written = 0;
  2091. err = generic_write_checks(file, &pos, &count, S_ISBLK(inode->i_mode));
  2092. if (err)
  2093. goto out;
  2094. if (count == 0)
  2095. goto out;
  2096. err = file_remove_suid(file);
  2097. if (err)
  2098. goto out;
  2099. file_update_time(file);
  2100. /* coalesce the iovecs and go direct-to-BIO for O_DIRECT */
  2101. if (unlikely(file->f_flags & O_DIRECT)) {
  2102. loff_t endbyte;
  2103. ssize_t written_buffered;
  2104. written = generic_file_direct_write(iocb, iov, &nr_segs, pos,
  2105. ppos, count, ocount);
  2106. if (written < 0 || written == count)
  2107. goto out;
  2108. /*
  2109. * direct-io write to a hole: fall through to buffered I/O
  2110. * for completing the rest of the request.
  2111. */
  2112. pos += written;
  2113. count -= written;
  2114. written_buffered = generic_file_buffered_write(iocb, iov,
  2115. nr_segs, pos, ppos, count,
  2116. written);
  2117. /*
  2118. * If generic_file_buffered_write() retuned a synchronous error
  2119. * then we want to return the number of bytes which were
  2120. * direct-written, or the error code if that was zero. Note
  2121. * that this differs from normal direct-io semantics, which
  2122. * will return -EFOO even if some bytes were written.
  2123. */
  2124. if (written_buffered < 0) {
  2125. err = written_buffered;
  2126. goto out;
  2127. }
  2128. /*
  2129. * We need to ensure that the page cache pages are written to
  2130. * disk and invalidated to preserve the expected O_DIRECT
  2131. * semantics.
  2132. */
  2133. endbyte = pos + written_buffered - written - 1;
  2134. err = do_sync_mapping_range(file->f_mapping, pos, endbyte,
  2135. SYNC_FILE_RANGE_WAIT_BEFORE|
  2136. SYNC_FILE_RANGE_WRITE|
  2137. SYNC_FILE_RANGE_WAIT_AFTER);
  2138. if (err == 0) {
  2139. written = written_buffered;
  2140. invalidate_mapping_pages(mapping,
  2141. pos >> PAGE_CACHE_SHIFT,
  2142. endbyte >> PAGE_CACHE_SHIFT);
  2143. } else {
  2144. /*
  2145. * We don't know how much we wrote, so just return
  2146. * the number of bytes which were direct-written
  2147. */
  2148. }
  2149. } else {
  2150. written = generic_file_buffered_write(iocb, iov, nr_segs,
  2151. pos, ppos, count, written);
  2152. }
  2153. out:
  2154. current->backing_dev_info = NULL;
  2155. return written ? written : err;
  2156. }
  2157. EXPORT_SYMBOL(__generic_file_aio_write);
  2158. /**
  2159. * generic_file_aio_write - write data to a file
  2160. * @iocb: IO state structure
  2161. * @iov: vector with data to write
  2162. * @nr_segs: number of segments in the vector
  2163. * @pos: position in file where to write
  2164. *
  2165. * This is a wrapper around __generic_file_aio_write() to be used by most
  2166. * filesystems. It takes care of syncing the file in case of O_SYNC file
  2167. * and acquires i_mutex as needed.
  2168. */
  2169. ssize_t generic_file_aio_write(struct kiocb *iocb, const struct iovec *iov,
  2170. unsigned long nr_segs, loff_t pos)
  2171. {
  2172. struct file *file = iocb->ki_filp;
  2173. struct inode *inode = file->f_mapping->host;
  2174. ssize_t ret;
  2175. BUG_ON(iocb->ki_pos != pos);
  2176. mutex_lock(&inode->i_mutex);
  2177. ret = __generic_file_aio_write(iocb, iov, nr_segs, &iocb->ki_pos);
  2178. mutex_unlock(&inode->i_mutex);
  2179. if (ret > 0 || ret == -EIOCBQUEUED) {
  2180. ssize_t err;
  2181. err = generic_write_sync(file, pos, ret);
  2182. if (err < 0 && ret > 0)
  2183. ret = err;
  2184. }
  2185. return ret;
  2186. }
  2187. EXPORT_SYMBOL(generic_file_aio_write);
  2188. /**
  2189. * try_to_release_page() - release old fs-specific metadata on a page
  2190. *
  2191. * @page: the page which the kernel is trying to free
  2192. * @gfp_mask: memory allocation flags (and I/O mode)
  2193. *
  2194. * The address_space is to try to release any data against the page
  2195. * (presumably at page->private). If the release was successful, return `1'.
  2196. * Otherwise return zero.
  2197. *
  2198. * This may also be called if PG_fscache is set on a page, indicating that the
  2199. * page is known to the local caching routines.
  2200. *
  2201. * The @gfp_mask argument specifies whether I/O may be performed to release
  2202. * this page (__GFP_IO), and whether the call may block (__GFP_WAIT & __GFP_FS).
  2203. *
  2204. */
  2205. int try_to_release_page(struct page *page, gfp_t gfp_mask)
  2206. {
  2207. struct address_space * const mapping = page->mapping;
  2208. BUG_ON(!PageLocked(page));
  2209. if (PageWriteback(page))
  2210. return 0;
  2211. if (mapping && mapping->a_ops->releasepage)
  2212. return mapping->a_ops->releasepage(page, gfp_mask);
  2213. return try_to_free_buffers(page);
  2214. }
  2215. EXPORT_SYMBOL(try_to_release_page);