filemap.c 67 KB

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