filemap.c 66 KB

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