filemap.c 65 KB

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