filemap.c 63 KB

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