filemap.c 65 KB

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