filemap.c 65 KB

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