/*1* linux/mm/filemap.c2*3* Copyright (C) 1994-1999 Linus Torvalds4*/56/*7* This file handles the generic file mmap semantics used by8* most "normal" filesystems (but you don't /have/ to use this:9* the NFS filesystem used to do this differently, for example)10*/11#include <linux/module.h>12#include <linux/compiler.h>13#include <linux/fs.h>14#include <linux/uaccess.h>15#include <linux/aio.h>16#include <linux/capability.h>17#include <linux/kernel_stat.h>18#include <linux/gfp.h>19#include <linux/mm.h>20#include <linux/swap.h>21#include <linux/mman.h>22#include <linux/pagemap.h>23#include <linux/file.h>24#include <linux/uio.h>25#include <linux/hash.h>26#include <linux/writeback.h>27#include <linux/backing-dev.h>28#include <linux/pagevec.h>29#include <linux/blkdev.h>30#include <linux/security.h>31#include <linux/syscalls.h>32#include <linux/cpuset.h>33#include <linux/hardirq.h> /* for BUG_ON(!in_atomic()) only */34#include <linux/memcontrol.h>35#include <linux/mm_inline.h> /* for page_is_file_cache() */36#include <linux/cleancache.h>37#include "internal.h"3839/*40* FIXME: remove all knowledge of the buffer layer from the core VM41*/42#include <linux/buffer_head.h> /* for try_to_free_buffers */4344#include <asm/mman.h>4546/*47* Shared mappings implemented 30.11.1994. It's not fully working yet,48* though.49*50* Shared mappings now work. 15.8.1995 Bruno.51*52* finished 'unifying' the page and buffer cache and SMP-threaded the53* page-cache, 21.05.1999, Ingo Molnar <[email protected]>54*55* SMP-threaded pagemap-LRU 1999, Andrea Arcangeli <[email protected]>56*/5758/*59* Lock ordering:60*61* ->i_mmap_mutex (truncate_pagecache)62* ->private_lock (__free_pte->__set_page_dirty_buffers)63* ->swap_lock (exclusive_swap_page, others)64* ->mapping->tree_lock65*66* ->i_mutex67* ->i_mmap_mutex (truncate->unmap_mapping_range)68*69* ->mmap_sem70* ->i_mmap_mutex71* ->page_table_lock or pte_lock (various, mainly in memory.c)72* ->mapping->tree_lock (arch-dependent flush_dcache_mmap_lock)73*74* ->mmap_sem75* ->lock_page (access_process_vm)76*77* ->i_mutex (generic_file_buffered_write)78* ->mmap_sem (fault_in_pages_readable->do_page_fault)79*80* ->i_mutex81* ->i_alloc_sem (various)82*83* inode_wb_list_lock84* sb_lock (fs/fs-writeback.c)85* ->mapping->tree_lock (__sync_single_inode)86*87* ->i_mmap_mutex88* ->anon_vma.lock (vma_adjust)89*90* ->anon_vma.lock91* ->page_table_lock or pte_lock (anon_vma_prepare and various)92*93* ->page_table_lock or pte_lock94* ->swap_lock (try_to_unmap_one)95* ->private_lock (try_to_unmap_one)96* ->tree_lock (try_to_unmap_one)97* ->zone.lru_lock (follow_page->mark_page_accessed)98* ->zone.lru_lock (check_pte_range->isolate_lru_page)99* ->private_lock (page_remove_rmap->set_page_dirty)100* ->tree_lock (page_remove_rmap->set_page_dirty)101* inode_wb_list_lock (page_remove_rmap->set_page_dirty)102* ->inode->i_lock (page_remove_rmap->set_page_dirty)103* inode_wb_list_lock (zap_pte_range->set_page_dirty)104* ->inode->i_lock (zap_pte_range->set_page_dirty)105* ->private_lock (zap_pte_range->__set_page_dirty_buffers)106*107* (code doesn't rely on that order, so you could switch it around)108* ->tasklist_lock (memory_failure, collect_procs_ao)109* ->i_mmap_mutex110*/111112/*113* Delete a page from the page cache and free it. Caller has to make114* sure the page is locked and that nobody else uses it - or that usage115* is safe. The caller must hold the mapping's tree_lock.116*/117void __delete_from_page_cache(struct page *page)118{119struct address_space *mapping = page->mapping;120121/*122* if we're uptodate, flush out into the cleancache, otherwise123* invalidate any existing cleancache entries. We can't leave124* stale data around in the cleancache once our page is gone125*/126if (PageUptodate(page) && PageMappedToDisk(page))127cleancache_put_page(page);128else129cleancache_flush_page(mapping, page);130131radix_tree_delete(&mapping->page_tree, page->index);132page->mapping = NULL;133mapping->nrpages--;134__dec_zone_page_state(page, NR_FILE_PAGES);135if (PageSwapBacked(page))136__dec_zone_page_state(page, NR_SHMEM);137BUG_ON(page_mapped(page));138139/*140* Some filesystems seem to re-dirty the page even after141* the VM has canceled the dirty bit (eg ext3 journaling).142*143* Fix it up by doing a final dirty accounting check after144* having removed the page entirely.145*/146if (PageDirty(page) && mapping_cap_account_dirty(mapping)) {147dec_zone_page_state(page, NR_FILE_DIRTY);148dec_bdi_stat(mapping->backing_dev_info, BDI_RECLAIMABLE);149}150}151152/**153* delete_from_page_cache - delete page from page cache154* @page: the page which the kernel is trying to remove from page cache155*156* This must be called only on pages that have been verified to be in the page157* cache and locked. It will never put the page into the free list, the caller158* has a reference on the page.159*/160void delete_from_page_cache(struct page *page)161{162struct address_space *mapping = page->mapping;163void (*freepage)(struct page *);164165BUG_ON(!PageLocked(page));166167freepage = mapping->a_ops->freepage;168spin_lock_irq(&mapping->tree_lock);169__delete_from_page_cache(page);170spin_unlock_irq(&mapping->tree_lock);171mem_cgroup_uncharge_cache_page(page);172173if (freepage)174freepage(page);175page_cache_release(page);176}177EXPORT_SYMBOL(delete_from_page_cache);178179static int sleep_on_page(void *word)180{181io_schedule();182return 0;183}184185static int sleep_on_page_killable(void *word)186{187sleep_on_page(word);188return fatal_signal_pending(current) ? -EINTR : 0;189}190191/**192* __filemap_fdatawrite_range - start writeback on mapping dirty pages in range193* @mapping: address space structure to write194* @start: offset in bytes where the range starts195* @end: offset in bytes where the range ends (inclusive)196* @sync_mode: enable synchronous operation197*198* Start writeback against all of a mapping's dirty pages that lie199* within the byte offsets <start, end> inclusive.200*201* If sync_mode is WB_SYNC_ALL then this is a "data integrity" operation, as202* opposed to a regular memory cleansing writeback. The difference between203* these two operations is that if a dirty page/buffer is encountered, it must204* be waited upon, and not just skipped over.205*/206int __filemap_fdatawrite_range(struct address_space *mapping, loff_t start,207loff_t end, int sync_mode)208{209int ret;210struct writeback_control wbc = {211.sync_mode = sync_mode,212.nr_to_write = LONG_MAX,213.range_start = start,214.range_end = end,215};216217if (!mapping_cap_writeback_dirty(mapping))218return 0;219220ret = do_writepages(mapping, &wbc);221return ret;222}223224static inline int __filemap_fdatawrite(struct address_space *mapping,225int sync_mode)226{227return __filemap_fdatawrite_range(mapping, 0, LLONG_MAX, sync_mode);228}229230int filemap_fdatawrite(struct address_space *mapping)231{232return __filemap_fdatawrite(mapping, WB_SYNC_ALL);233}234EXPORT_SYMBOL(filemap_fdatawrite);235236int filemap_fdatawrite_range(struct address_space *mapping, loff_t start,237loff_t end)238{239return __filemap_fdatawrite_range(mapping, start, end, WB_SYNC_ALL);240}241EXPORT_SYMBOL(filemap_fdatawrite_range);242243/**244* filemap_flush - mostly a non-blocking flush245* @mapping: target address_space246*247* This is a mostly non-blocking flush. Not suitable for data-integrity248* purposes - I/O may not be started against all dirty pages.249*/250int filemap_flush(struct address_space *mapping)251{252return __filemap_fdatawrite(mapping, WB_SYNC_NONE);253}254EXPORT_SYMBOL(filemap_flush);255256/**257* filemap_fdatawait_range - wait for writeback to complete258* @mapping: address space structure to wait for259* @start_byte: offset in bytes where the range starts260* @end_byte: offset in bytes where the range ends (inclusive)261*262* Walk the list of under-writeback pages of the given address space263* in the given range and wait for all of them.264*/265int filemap_fdatawait_range(struct address_space *mapping, loff_t start_byte,266loff_t end_byte)267{268pgoff_t index = start_byte >> PAGE_CACHE_SHIFT;269pgoff_t end = end_byte >> PAGE_CACHE_SHIFT;270struct pagevec pvec;271int nr_pages;272int ret = 0;273274if (end_byte < start_byte)275return 0;276277pagevec_init(&pvec, 0);278while ((index <= end) &&279(nr_pages = pagevec_lookup_tag(&pvec, mapping, &index,280PAGECACHE_TAG_WRITEBACK,281min(end - index, (pgoff_t)PAGEVEC_SIZE-1) + 1)) != 0) {282unsigned i;283284for (i = 0; i < nr_pages; i++) {285struct page *page = pvec.pages[i];286287/* until radix tree lookup accepts end_index */288if (page->index > end)289continue;290291wait_on_page_writeback(page);292if (TestClearPageError(page))293ret = -EIO;294}295pagevec_release(&pvec);296cond_resched();297}298299/* Check for outstanding write errors */300if (test_and_clear_bit(AS_ENOSPC, &mapping->flags))301ret = -ENOSPC;302if (test_and_clear_bit(AS_EIO, &mapping->flags))303ret = -EIO;304305return ret;306}307EXPORT_SYMBOL(filemap_fdatawait_range);308309/**310* filemap_fdatawait - wait for all under-writeback pages to complete311* @mapping: address space structure to wait for312*313* Walk the list of under-writeback pages of the given address space314* and wait for all of them.315*/316int filemap_fdatawait(struct address_space *mapping)317{318loff_t i_size = i_size_read(mapping->host);319320if (i_size == 0)321return 0;322323return filemap_fdatawait_range(mapping, 0, i_size - 1);324}325EXPORT_SYMBOL(filemap_fdatawait);326327int filemap_write_and_wait(struct address_space *mapping)328{329int err = 0;330331if (mapping->nrpages) {332err = filemap_fdatawrite(mapping);333/*334* Even if the above returned error, the pages may be335* written partially (e.g. -ENOSPC), so we wait for it.336* But the -EIO is special case, it may indicate the worst337* thing (e.g. bug) happened, so we avoid waiting for it.338*/339if (err != -EIO) {340int err2 = filemap_fdatawait(mapping);341if (!err)342err = err2;343}344}345return err;346}347EXPORT_SYMBOL(filemap_write_and_wait);348349/**350* filemap_write_and_wait_range - write out & wait on a file range351* @mapping: the address_space for the pages352* @lstart: offset in bytes where the range starts353* @lend: offset in bytes where the range ends (inclusive)354*355* Write out and wait upon file offsets lstart->lend, inclusive.356*357* Note that `lend' is inclusive (describes the last byte to be written) so358* that this function can be used to write to the very end-of-file (end = -1).359*/360int filemap_write_and_wait_range(struct address_space *mapping,361loff_t lstart, loff_t lend)362{363int err = 0;364365if (mapping->nrpages) {366err = __filemap_fdatawrite_range(mapping, lstart, lend,367WB_SYNC_ALL);368/* See comment of filemap_write_and_wait() */369if (err != -EIO) {370int err2 = filemap_fdatawait_range(mapping,371lstart, lend);372if (!err)373err = err2;374}375}376return err;377}378EXPORT_SYMBOL(filemap_write_and_wait_range);379380/**381* replace_page_cache_page - replace a pagecache page with a new one382* @old: page to be replaced383* @new: page to replace with384* @gfp_mask: allocation mode385*386* This function replaces a page in the pagecache with a new one. On387* success it acquires the pagecache reference for the new page and388* drops it for the old page. Both the old and new pages must be389* locked. This function does not add the new page to the LRU, the390* caller must do that.391*392* The remove + add is atomic. The only way this function can fail is393* memory allocation failure.394*/395int replace_page_cache_page(struct page *old, struct page *new, gfp_t gfp_mask)396{397int error;398struct mem_cgroup *memcg = NULL;399400VM_BUG_ON(!PageLocked(old));401VM_BUG_ON(!PageLocked(new));402VM_BUG_ON(new->mapping);403404/*405* This is not page migration, but prepare_migration and406* end_migration does enough work for charge replacement.407*408* In the longer term we probably want a specialized function409* for moving the charge from old to new in a more efficient410* manner.411*/412error = mem_cgroup_prepare_migration(old, new, &memcg, gfp_mask);413if (error)414return error;415416error = radix_tree_preload(gfp_mask & ~__GFP_HIGHMEM);417if (!error) {418struct address_space *mapping = old->mapping;419void (*freepage)(struct page *);420421pgoff_t offset = old->index;422freepage = mapping->a_ops->freepage;423424page_cache_get(new);425new->mapping = mapping;426new->index = offset;427428spin_lock_irq(&mapping->tree_lock);429__delete_from_page_cache(old);430error = radix_tree_insert(&mapping->page_tree, offset, new);431BUG_ON(error);432mapping->nrpages++;433__inc_zone_page_state(new, NR_FILE_PAGES);434if (PageSwapBacked(new))435__inc_zone_page_state(new, NR_SHMEM);436spin_unlock_irq(&mapping->tree_lock);437radix_tree_preload_end();438if (freepage)439freepage(old);440page_cache_release(old);441mem_cgroup_end_migration(memcg, old, new, true);442} else {443mem_cgroup_end_migration(memcg, old, new, false);444}445446return error;447}448EXPORT_SYMBOL_GPL(replace_page_cache_page);449450/**451* add_to_page_cache_locked - add a locked page to the pagecache452* @page: page to add453* @mapping: the page's address_space454* @offset: page index455* @gfp_mask: page allocation mode456*457* This function is used to add a page to the pagecache. It must be locked.458* This function does not add the page to the LRU. The caller must do that.459*/460int add_to_page_cache_locked(struct page *page, struct address_space *mapping,461pgoff_t offset, gfp_t gfp_mask)462{463int error;464465VM_BUG_ON(!PageLocked(page));466467error = mem_cgroup_cache_charge(page, current->mm,468gfp_mask & GFP_RECLAIM_MASK);469if (error)470goto out;471472error = radix_tree_preload(gfp_mask & ~__GFP_HIGHMEM);473if (error == 0) {474page_cache_get(page);475page->mapping = mapping;476page->index = offset;477478spin_lock_irq(&mapping->tree_lock);479error = radix_tree_insert(&mapping->page_tree, offset, page);480if (likely(!error)) {481mapping->nrpages++;482__inc_zone_page_state(page, NR_FILE_PAGES);483if (PageSwapBacked(page))484__inc_zone_page_state(page, NR_SHMEM);485spin_unlock_irq(&mapping->tree_lock);486} else {487page->mapping = NULL;488spin_unlock_irq(&mapping->tree_lock);489mem_cgroup_uncharge_cache_page(page);490page_cache_release(page);491}492radix_tree_preload_end();493} else494mem_cgroup_uncharge_cache_page(page);495out:496return error;497}498EXPORT_SYMBOL(add_to_page_cache_locked);499500int add_to_page_cache_lru(struct page *page, struct address_space *mapping,501pgoff_t offset, gfp_t gfp_mask)502{503int ret;504505/*506* Splice_read and readahead add shmem/tmpfs pages into the page cache507* before shmem_readpage has a chance to mark them as SwapBacked: they508* need to go on the anon lru below, and mem_cgroup_cache_charge509* (called in add_to_page_cache) needs to know where they're going too.510*/511if (mapping_cap_swap_backed(mapping))512SetPageSwapBacked(page);513514ret = add_to_page_cache(page, mapping, offset, gfp_mask);515if (ret == 0) {516if (page_is_file_cache(page))517lru_cache_add_file(page);518else519lru_cache_add_anon(page);520}521return ret;522}523EXPORT_SYMBOL_GPL(add_to_page_cache_lru);524525#ifdef CONFIG_NUMA526struct page *__page_cache_alloc(gfp_t gfp)527{528int n;529struct page *page;530531if (cpuset_do_page_mem_spread()) {532get_mems_allowed();533n = cpuset_mem_spread_node();534page = alloc_pages_exact_node(n, gfp, 0);535put_mems_allowed();536return page;537}538return alloc_pages(gfp, 0);539}540EXPORT_SYMBOL(__page_cache_alloc);541#endif542543/*544* In order to wait for pages to become available there must be545* waitqueues associated with pages. By using a hash table of546* waitqueues where the bucket discipline is to maintain all547* waiters on the same queue and wake all when any of the pages548* become available, and for the woken contexts to check to be549* sure the appropriate page became available, this saves space550* at a cost of "thundering herd" phenomena during rare hash551* collisions.552*/553static wait_queue_head_t *page_waitqueue(struct page *page)554{555const struct zone *zone = page_zone(page);556557return &zone->wait_table[hash_ptr(page, zone->wait_table_bits)];558}559560static inline void wake_up_page(struct page *page, int bit)561{562__wake_up_bit(page_waitqueue(page), &page->flags, bit);563}564565void wait_on_page_bit(struct page *page, int bit_nr)566{567DEFINE_WAIT_BIT(wait, &page->flags, bit_nr);568569if (test_bit(bit_nr, &page->flags))570__wait_on_bit(page_waitqueue(page), &wait, sleep_on_page,571TASK_UNINTERRUPTIBLE);572}573EXPORT_SYMBOL(wait_on_page_bit);574575int wait_on_page_bit_killable(struct page *page, int bit_nr)576{577DEFINE_WAIT_BIT(wait, &page->flags, bit_nr);578579if (!test_bit(bit_nr, &page->flags))580return 0;581582return __wait_on_bit(page_waitqueue(page), &wait,583sleep_on_page_killable, TASK_KILLABLE);584}585586/**587* add_page_wait_queue - Add an arbitrary waiter to a page's wait queue588* @page: Page defining the wait queue of interest589* @waiter: Waiter to add to the queue590*591* Add an arbitrary @waiter to the wait queue for the nominated @page.592*/593void add_page_wait_queue(struct page *page, wait_queue_t *waiter)594{595wait_queue_head_t *q = page_waitqueue(page);596unsigned long flags;597598spin_lock_irqsave(&q->lock, flags);599__add_wait_queue(q, waiter);600spin_unlock_irqrestore(&q->lock, flags);601}602EXPORT_SYMBOL_GPL(add_page_wait_queue);603604/**605* unlock_page - unlock a locked page606* @page: the page607*608* Unlocks the page and wakes up sleepers in ___wait_on_page_locked().609* Also wakes sleepers in wait_on_page_writeback() because the wakeup610* mechananism between PageLocked pages and PageWriteback pages is shared.611* But that's OK - sleepers in wait_on_page_writeback() just go back to sleep.612*613* The mb is necessary to enforce ordering between the clear_bit and the read614* of the waitqueue (to avoid SMP races with a parallel wait_on_page_locked()).615*/616void unlock_page(struct page *page)617{618VM_BUG_ON(!PageLocked(page));619clear_bit_unlock(PG_locked, &page->flags);620smp_mb__after_clear_bit();621wake_up_page(page, PG_locked);622}623EXPORT_SYMBOL(unlock_page);624625/**626* end_page_writeback - end writeback against a page627* @page: the page628*/629void end_page_writeback(struct page *page)630{631if (TestClearPageReclaim(page))632rotate_reclaimable_page(page);633634if (!test_clear_page_writeback(page))635BUG();636637smp_mb__after_clear_bit();638wake_up_page(page, PG_writeback);639}640EXPORT_SYMBOL(end_page_writeback);641642/**643* __lock_page - get a lock on the page, assuming we need to sleep to get it644* @page: the page to lock645*/646void __lock_page(struct page *page)647{648DEFINE_WAIT_BIT(wait, &page->flags, PG_locked);649650__wait_on_bit_lock(page_waitqueue(page), &wait, sleep_on_page,651TASK_UNINTERRUPTIBLE);652}653EXPORT_SYMBOL(__lock_page);654655int __lock_page_killable(struct page *page)656{657DEFINE_WAIT_BIT(wait, &page->flags, PG_locked);658659return __wait_on_bit_lock(page_waitqueue(page), &wait,660sleep_on_page_killable, TASK_KILLABLE);661}662EXPORT_SYMBOL_GPL(__lock_page_killable);663664int __lock_page_or_retry(struct page *page, struct mm_struct *mm,665unsigned int flags)666{667if (flags & FAULT_FLAG_ALLOW_RETRY) {668/*669* CAUTION! In this case, mmap_sem is not released670* even though return 0.671*/672if (flags & FAULT_FLAG_RETRY_NOWAIT)673return 0;674675up_read(&mm->mmap_sem);676if (flags & FAULT_FLAG_KILLABLE)677wait_on_page_locked_killable(page);678else679wait_on_page_locked(page);680return 0;681} else {682if (flags & FAULT_FLAG_KILLABLE) {683int ret;684685ret = __lock_page_killable(page);686if (ret) {687up_read(&mm->mmap_sem);688return 0;689}690} else691__lock_page(page);692return 1;693}694}695696/**697* find_get_page - find and get a page reference698* @mapping: the address_space to search699* @offset: the page index700*701* Is there a pagecache struct page at the given (mapping, offset) tuple?702* If yes, increment its refcount and return it; if no, return NULL.703*/704struct page *find_get_page(struct address_space *mapping, pgoff_t offset)705{706void **pagep;707struct page *page;708709rcu_read_lock();710repeat:711page = NULL;712pagep = radix_tree_lookup_slot(&mapping->page_tree, offset);713if (pagep) {714page = radix_tree_deref_slot(pagep);715if (unlikely(!page))716goto out;717if (radix_tree_deref_retry(page))718goto repeat;719720if (!page_cache_get_speculative(page))721goto repeat;722723/*724* Has the page moved?725* This is part of the lockless pagecache protocol. See726* include/linux/pagemap.h for details.727*/728if (unlikely(page != *pagep)) {729page_cache_release(page);730goto repeat;731}732}733out:734rcu_read_unlock();735736return page;737}738EXPORT_SYMBOL(find_get_page);739740/**741* find_lock_page - locate, pin and lock a pagecache page742* @mapping: the address_space to search743* @offset: the page index744*745* Locates the desired pagecache page, locks it, increments its reference746* count and returns its address.747*748* Returns zero if the page was not present. find_lock_page() may sleep.749*/750struct page *find_lock_page(struct address_space *mapping, pgoff_t offset)751{752struct page *page;753754repeat:755page = find_get_page(mapping, offset);756if (page) {757lock_page(page);758/* Has the page been truncated? */759if (unlikely(page->mapping != mapping)) {760unlock_page(page);761page_cache_release(page);762goto repeat;763}764VM_BUG_ON(page->index != offset);765}766return page;767}768EXPORT_SYMBOL(find_lock_page);769770/**771* find_or_create_page - locate or add a pagecache page772* @mapping: the page's address_space773* @index: the page's index into the mapping774* @gfp_mask: page allocation mode775*776* Locates a page in the pagecache. If the page is not present, a new page777* is allocated using @gfp_mask and is added to the pagecache and to the VM's778* LRU list. The returned page is locked and has its reference count779* incremented.780*781* find_or_create_page() may sleep, even if @gfp_flags specifies an atomic782* allocation!783*784* find_or_create_page() returns the desired page's address, or zero on785* memory exhaustion.786*/787struct page *find_or_create_page(struct address_space *mapping,788pgoff_t index, gfp_t gfp_mask)789{790struct page *page;791int err;792repeat:793page = find_lock_page(mapping, index);794if (!page) {795page = __page_cache_alloc(gfp_mask);796if (!page)797return NULL;798/*799* We want a regular kernel memory (not highmem or DMA etc)800* allocation for the radix tree nodes, but we need to honour801* the context-specific requirements the caller has asked for.802* GFP_RECLAIM_MASK collects those requirements.803*/804err = add_to_page_cache_lru(page, mapping, index,805(gfp_mask & GFP_RECLAIM_MASK));806if (unlikely(err)) {807page_cache_release(page);808page = NULL;809if (err == -EEXIST)810goto repeat;811}812}813return page;814}815EXPORT_SYMBOL(find_or_create_page);816817/**818* find_get_pages - gang pagecache lookup819* @mapping: The address_space to search820* @start: The starting page index821* @nr_pages: The maximum number of pages822* @pages: Where the resulting pages are placed823*824* find_get_pages() will search for and return a group of up to825* @nr_pages pages in the mapping. The pages are placed at @pages.826* find_get_pages() takes a reference against the returned pages.827*828* The search returns a group of mapping-contiguous pages with ascending829* indexes. There may be holes in the indices due to not-present pages.830*831* find_get_pages() returns the number of pages which were found.832*/833unsigned find_get_pages(struct address_space *mapping, pgoff_t start,834unsigned int nr_pages, struct page **pages)835{836unsigned int i;837unsigned int ret;838unsigned int nr_found;839840rcu_read_lock();841restart:842nr_found = radix_tree_gang_lookup_slot(&mapping->page_tree,843(void ***)pages, start, nr_pages);844ret = 0;845for (i = 0; i < nr_found; i++) {846struct page *page;847repeat:848page = radix_tree_deref_slot((void **)pages[i]);849if (unlikely(!page))850continue;851852/*853* This can only trigger when the entry at index 0 moves out854* of or back to the root: none yet gotten, safe to restart.855*/856if (radix_tree_deref_retry(page)) {857WARN_ON(start | i);858goto restart;859}860861if (!page_cache_get_speculative(page))862goto repeat;863864/* Has the page moved? */865if (unlikely(page != *((void **)pages[i]))) {866page_cache_release(page);867goto repeat;868}869870pages[ret] = page;871ret++;872}873874/*875* If all entries were removed before we could secure them,876* try again, because callers stop trying once 0 is returned.877*/878if (unlikely(!ret && nr_found))879goto restart;880rcu_read_unlock();881return ret;882}883884/**885* find_get_pages_contig - gang contiguous pagecache lookup886* @mapping: The address_space to search887* @index: The starting page index888* @nr_pages: The maximum number of pages889* @pages: Where the resulting pages are placed890*891* find_get_pages_contig() works exactly like find_get_pages(), except892* that the returned number of pages are guaranteed to be contiguous.893*894* find_get_pages_contig() returns the number of pages which were found.895*/896unsigned find_get_pages_contig(struct address_space *mapping, pgoff_t index,897unsigned int nr_pages, struct page **pages)898{899unsigned int i;900unsigned int ret;901unsigned int nr_found;902903rcu_read_lock();904restart:905nr_found = radix_tree_gang_lookup_slot(&mapping->page_tree,906(void ***)pages, index, nr_pages);907ret = 0;908for (i = 0; i < nr_found; i++) {909struct page *page;910repeat:911page = radix_tree_deref_slot((void **)pages[i]);912if (unlikely(!page))913continue;914915/*916* This can only trigger when the entry at index 0 moves out917* of or back to the root: none yet gotten, safe to restart.918*/919if (radix_tree_deref_retry(page))920goto restart;921922if (!page_cache_get_speculative(page))923goto repeat;924925/* Has the page moved? */926if (unlikely(page != *((void **)pages[i]))) {927page_cache_release(page);928goto repeat;929}930931/*932* must check mapping and index after taking the ref.933* otherwise we can get both false positives and false934* negatives, which is just confusing to the caller.935*/936if (page->mapping == NULL || page->index != index) {937page_cache_release(page);938break;939}940941pages[ret] = page;942ret++;943index++;944}945rcu_read_unlock();946return ret;947}948EXPORT_SYMBOL(find_get_pages_contig);949950/**951* find_get_pages_tag - find and return pages that match @tag952* @mapping: the address_space to search953* @index: the starting page index954* @tag: the tag index955* @nr_pages: the maximum number of pages956* @pages: where the resulting pages are placed957*958* Like find_get_pages, except we only return pages which are tagged with959* @tag. We update @index to index the next page for the traversal.960*/961unsigned find_get_pages_tag(struct address_space *mapping, pgoff_t *index,962int tag, unsigned int nr_pages, struct page **pages)963{964unsigned int i;965unsigned int ret;966unsigned int nr_found;967968rcu_read_lock();969restart:970nr_found = radix_tree_gang_lookup_tag_slot(&mapping->page_tree,971(void ***)pages, *index, nr_pages, tag);972ret = 0;973for (i = 0; i < nr_found; i++) {974struct page *page;975repeat:976page = radix_tree_deref_slot((void **)pages[i]);977if (unlikely(!page))978continue;979980/*981* This can only trigger when the entry at index 0 moves out982* of or back to the root: none yet gotten, safe to restart.983*/984if (radix_tree_deref_retry(page))985goto restart;986987if (!page_cache_get_speculative(page))988goto repeat;989990/* Has the page moved? */991if (unlikely(page != *((void **)pages[i]))) {992page_cache_release(page);993goto repeat;994}995996pages[ret] = page;997ret++;998}9991000/*1001* If all entries were removed before we could secure them,1002* try again, because callers stop trying once 0 is returned.1003*/1004if (unlikely(!ret && nr_found))1005goto restart;1006rcu_read_unlock();10071008if (ret)1009*index = pages[ret - 1]->index + 1;10101011return ret;1012}1013EXPORT_SYMBOL(find_get_pages_tag);10141015/**1016* grab_cache_page_nowait - returns locked page at given index in given cache1017* @mapping: target address_space1018* @index: the page index1019*1020* Same as grab_cache_page(), but do not wait if the page is unavailable.1021* This is intended for speculative data generators, where the data can1022* be regenerated if the page couldn't be grabbed. This routine should1023* be safe to call while holding the lock for another page.1024*1025* Clear __GFP_FS when allocating the page to avoid recursion into the fs1026* and deadlock against the caller's locked page.1027*/1028struct page *1029grab_cache_page_nowait(struct address_space *mapping, pgoff_t index)1030{1031struct page *page = find_get_page(mapping, index);10321033if (page) {1034if (trylock_page(page))1035return page;1036page_cache_release(page);1037return NULL;1038}1039page = __page_cache_alloc(mapping_gfp_mask(mapping) & ~__GFP_FS);1040if (page && add_to_page_cache_lru(page, mapping, index, GFP_NOFS)) {1041page_cache_release(page);1042page = NULL;1043}1044return page;1045}1046EXPORT_SYMBOL(grab_cache_page_nowait);10471048/*1049* CD/DVDs are error prone. When a medium error occurs, the driver may fail1050* a _large_ part of the i/o request. Imagine the worst scenario:1051*1052* ---R__________________________________________B__________1053* ^ reading here ^ bad block(assume 4k)1054*1055* read(R) => miss => readahead(R...B) => media error => frustrating retries1056* => failing the whole request => read(R) => read(R+1) =>1057* readahead(R+1...B+1) => bang => read(R+2) => read(R+3) =>1058* readahead(R+3...B+2) => bang => read(R+3) => read(R+4) =>1059* readahead(R+4...B+3) => bang => read(R+4) => read(R+5) => ......1060*1061* It is going insane. Fix it by quickly scaling down the readahead size.1062*/1063static void shrink_readahead_size_eio(struct file *filp,1064struct file_ra_state *ra)1065{1066ra->ra_pages /= 4;1067}10681069/**1070* do_generic_file_read - generic file read routine1071* @filp: the file to read1072* @ppos: current file position1073* @desc: read_descriptor1074* @actor: read method1075*1076* This is a generic file read routine, and uses the1077* mapping->a_ops->readpage() function for the actual low-level stuff.1078*1079* This is really ugly. But the goto's actually try to clarify some1080* of the logic when it comes to error handling etc.1081*/1082static void do_generic_file_read(struct file *filp, loff_t *ppos,1083read_descriptor_t *desc, read_actor_t actor)1084{1085struct address_space *mapping = filp->f_mapping;1086struct inode *inode = mapping->host;1087struct file_ra_state *ra = &filp->f_ra;1088pgoff_t index;1089pgoff_t last_index;1090pgoff_t prev_index;1091unsigned long offset; /* offset into pagecache page */1092unsigned int prev_offset;1093int error;10941095index = *ppos >> PAGE_CACHE_SHIFT;1096prev_index = ra->prev_pos >> PAGE_CACHE_SHIFT;1097prev_offset = ra->prev_pos & (PAGE_CACHE_SIZE-1);1098last_index = (*ppos + desc->count + PAGE_CACHE_SIZE-1) >> PAGE_CACHE_SHIFT;1099offset = *ppos & ~PAGE_CACHE_MASK;11001101for (;;) {1102struct page *page;1103pgoff_t end_index;1104loff_t isize;1105unsigned long nr, ret;11061107cond_resched();1108find_page:1109page = find_get_page(mapping, index);1110if (!page) {1111page_cache_sync_readahead(mapping,1112ra, filp,1113index, last_index - index);1114page = find_get_page(mapping, index);1115if (unlikely(page == NULL))1116goto no_cached_page;1117}1118if (PageReadahead(page)) {1119page_cache_async_readahead(mapping,1120ra, filp, page,1121index, last_index - index);1122}1123if (!PageUptodate(page)) {1124if (inode->i_blkbits == PAGE_CACHE_SHIFT ||1125!mapping->a_ops->is_partially_uptodate)1126goto page_not_up_to_date;1127if (!trylock_page(page))1128goto page_not_up_to_date;1129/* Did it get truncated before we got the lock? */1130if (!page->mapping)1131goto page_not_up_to_date_locked;1132if (!mapping->a_ops->is_partially_uptodate(page,1133desc, offset))1134goto page_not_up_to_date_locked;1135unlock_page(page);1136}1137page_ok:1138/*1139* i_size must be checked after we know the page is Uptodate.1140*1141* Checking i_size after the check allows us to calculate1142* the correct value for "nr", which means the zero-filled1143* part of the page is not copied back to userspace (unless1144* another truncate extends the file - this is desired though).1145*/11461147isize = i_size_read(inode);1148end_index = (isize - 1) >> PAGE_CACHE_SHIFT;1149if (unlikely(!isize || index > end_index)) {1150page_cache_release(page);1151goto out;1152}11531154/* nr is the maximum number of bytes to copy from this page */1155nr = PAGE_CACHE_SIZE;1156if (index == end_index) {1157nr = ((isize - 1) & ~PAGE_CACHE_MASK) + 1;1158if (nr <= offset) {1159page_cache_release(page);1160goto out;1161}1162}1163nr = nr - offset;11641165/* If users can be writing to this page using arbitrary1166* virtual addresses, take care about potential aliasing1167* before reading the page on the kernel side.1168*/1169if (mapping_writably_mapped(mapping))1170flush_dcache_page(page);11711172/*1173* When a sequential read accesses a page several times,1174* only mark it as accessed the first time.1175*/1176if (prev_index != index || offset != prev_offset)1177mark_page_accessed(page);1178prev_index = index;11791180/*1181* Ok, we have the page, and it's up-to-date, so1182* now we can copy it to user space...1183*1184* The actor routine returns how many bytes were actually used..1185* NOTE! This may not be the same as how much of a user buffer1186* we filled up (we may be padding etc), so we can only update1187* "pos" here (the actor routine has to update the user buffer1188* pointers and the remaining count).1189*/1190ret = actor(desc, page, offset, nr);1191offset += ret;1192index += offset >> PAGE_CACHE_SHIFT;1193offset &= ~PAGE_CACHE_MASK;1194prev_offset = offset;11951196page_cache_release(page);1197if (ret == nr && desc->count)1198continue;1199goto out;12001201page_not_up_to_date:1202/* Get exclusive access to the page ... */1203error = lock_page_killable(page);1204if (unlikely(error))1205goto readpage_error;12061207page_not_up_to_date_locked:1208/* Did it get truncated before we got the lock? */1209if (!page->mapping) {1210unlock_page(page);1211page_cache_release(page);1212continue;1213}12141215/* Did somebody else fill it already? */1216if (PageUptodate(page)) {1217unlock_page(page);1218goto page_ok;1219}12201221readpage:1222/*1223* A previous I/O error may have been due to temporary1224* failures, eg. multipath errors.1225* PG_error will be set again if readpage fails.1226*/1227ClearPageError(page);1228/* Start the actual read. The read will unlock the page. */1229error = mapping->a_ops->readpage(filp, page);12301231if (unlikely(error)) {1232if (error == AOP_TRUNCATED_PAGE) {1233page_cache_release(page);1234goto find_page;1235}1236goto readpage_error;1237}12381239if (!PageUptodate(page)) {1240error = lock_page_killable(page);1241if (unlikely(error))1242goto readpage_error;1243if (!PageUptodate(page)) {1244if (page->mapping == NULL) {1245/*1246* invalidate_mapping_pages got it1247*/1248unlock_page(page);1249page_cache_release(page);1250goto find_page;1251}1252unlock_page(page);1253shrink_readahead_size_eio(filp, ra);1254error = -EIO;1255goto readpage_error;1256}1257unlock_page(page);1258}12591260goto page_ok;12611262readpage_error:1263/* UHHUH! A synchronous read error occurred. Report it */1264desc->error = error;1265page_cache_release(page);1266goto out;12671268no_cached_page:1269/*1270* Ok, it wasn't cached, so we need to create a new1271* page..1272*/1273page = page_cache_alloc_cold(mapping);1274if (!page) {1275desc->error = -ENOMEM;1276goto out;1277}1278error = add_to_page_cache_lru(page, mapping,1279index, GFP_KERNEL);1280if (error) {1281page_cache_release(page);1282if (error == -EEXIST)1283goto find_page;1284desc->error = error;1285goto out;1286}1287goto readpage;1288}12891290out:1291ra->prev_pos = prev_index;1292ra->prev_pos <<= PAGE_CACHE_SHIFT;1293ra->prev_pos |= prev_offset;12941295*ppos = ((loff_t)index << PAGE_CACHE_SHIFT) + offset;1296file_accessed(filp);1297}12981299int file_read_actor(read_descriptor_t *desc, struct page *page,1300unsigned long offset, unsigned long size)1301{1302char *kaddr;1303unsigned long left, count = desc->count;13041305if (size > count)1306size = count;13071308/*1309* Faults on the destination of a read are common, so do it before1310* taking the kmap.1311*/1312if (!fault_in_pages_writeable(desc->arg.buf, size)) {1313kaddr = kmap_atomic(page, KM_USER0);1314left = __copy_to_user_inatomic(desc->arg.buf,1315kaddr + offset, size);1316kunmap_atomic(kaddr, KM_USER0);1317if (left == 0)1318goto success;1319}13201321/* Do it the slow way */1322kaddr = kmap(page);1323left = __copy_to_user(desc->arg.buf, kaddr + offset, size);1324kunmap(page);13251326if (left) {1327size -= left;1328desc->error = -EFAULT;1329}1330success:1331desc->count = count - size;1332desc->written += size;1333desc->arg.buf += size;1334return size;1335}13361337/*1338* Performs necessary checks before doing a write1339* @iov: io vector request1340* @nr_segs: number of segments in the iovec1341* @count: number of bytes to write1342* @access_flags: type of access: %VERIFY_READ or %VERIFY_WRITE1343*1344* Adjust number of segments and amount of bytes to write (nr_segs should be1345* properly initialized first). Returns appropriate error code that caller1346* should return or zero in case that write should be allowed.1347*/1348int generic_segment_checks(const struct iovec *iov,1349unsigned long *nr_segs, size_t *count, int access_flags)1350{1351unsigned long seg;1352size_t cnt = 0;1353for (seg = 0; seg < *nr_segs; seg++) {1354const struct iovec *iv = &iov[seg];13551356/*1357* If any segment has a negative length, or the cumulative1358* length ever wraps negative then return -EINVAL.1359*/1360cnt += iv->iov_len;1361if (unlikely((ssize_t)(cnt|iv->iov_len) < 0))1362return -EINVAL;1363if (access_ok(access_flags, iv->iov_base, iv->iov_len))1364continue;1365if (seg == 0)1366return -EFAULT;1367*nr_segs = seg;1368cnt -= iv->iov_len; /* This segment is no good */1369break;1370}1371*count = cnt;1372return 0;1373}1374EXPORT_SYMBOL(generic_segment_checks);13751376/**1377* generic_file_aio_read - generic filesystem read routine1378* @iocb: kernel I/O control block1379* @iov: io vector request1380* @nr_segs: number of segments in the iovec1381* @pos: current file position1382*1383* This is the "read()" routine for all filesystems1384* that can use the page cache directly.1385*/1386ssize_t1387generic_file_aio_read(struct kiocb *iocb, const struct iovec *iov,1388unsigned long nr_segs, loff_t pos)1389{1390struct file *filp = iocb->ki_filp;1391ssize_t retval;1392unsigned long seg = 0;1393size_t count;1394loff_t *ppos = &iocb->ki_pos;1395struct blk_plug plug;13961397count = 0;1398retval = generic_segment_checks(iov, &nr_segs, &count, VERIFY_WRITE);1399if (retval)1400return retval;14011402blk_start_plug(&plug);14031404/* coalesce the iovecs and go direct-to-BIO for O_DIRECT */1405if (filp->f_flags & O_DIRECT) {1406loff_t size;1407struct address_space *mapping;1408struct inode *inode;14091410mapping = filp->f_mapping;1411inode = mapping->host;1412if (!count)1413goto out; /* skip atime */1414size = i_size_read(inode);1415if (pos < size) {1416retval = filemap_write_and_wait_range(mapping, pos,1417pos + iov_length(iov, nr_segs) - 1);1418if (!retval) {1419retval = mapping->a_ops->direct_IO(READ, iocb,1420iov, pos, nr_segs);1421}1422if (retval > 0) {1423*ppos = pos + retval;1424count -= retval;1425}14261427/*1428* Btrfs can have a short DIO read if we encounter1429* compressed extents, so if there was an error, or if1430* we've already read everything we wanted to, or if1431* there was a short read because we hit EOF, go ahead1432* and return. Otherwise fallthrough to buffered io for1433* the rest of the read.1434*/1435if (retval < 0 || !count || *ppos >= size) {1436file_accessed(filp);1437goto out;1438}1439}1440}14411442count = retval;1443for (seg = 0; seg < nr_segs; seg++) {1444read_descriptor_t desc;1445loff_t offset = 0;14461447/*1448* If we did a short DIO read we need to skip the section of the1449* iov that we've already read data into.1450*/1451if (count) {1452if (count > iov[seg].iov_len) {1453count -= iov[seg].iov_len;1454continue;1455}1456offset = count;1457count = 0;1458}14591460desc.written = 0;1461desc.arg.buf = iov[seg].iov_base + offset;1462desc.count = iov[seg].iov_len - offset;1463if (desc.count == 0)1464continue;1465desc.error = 0;1466do_generic_file_read(filp, ppos, &desc, file_read_actor);1467retval += desc.written;1468if (desc.error) {1469retval = retval ?: desc.error;1470break;1471}1472if (desc.count > 0)1473break;1474}1475out:1476blk_finish_plug(&plug);1477return retval;1478}1479EXPORT_SYMBOL(generic_file_aio_read);14801481static ssize_t1482do_readahead(struct address_space *mapping, struct file *filp,1483pgoff_t index, unsigned long nr)1484{1485if (!mapping || !mapping->a_ops || !mapping->a_ops->readpage)1486return -EINVAL;14871488force_page_cache_readahead(mapping, filp, index, nr);1489return 0;1490}14911492SYSCALL_DEFINE(readahead)(int fd, loff_t offset, size_t count)1493{1494ssize_t ret;1495struct file *file;14961497ret = -EBADF;1498file = fget(fd);1499if (file) {1500if (file->f_mode & FMODE_READ) {1501struct address_space *mapping = file->f_mapping;1502pgoff_t start = offset >> PAGE_CACHE_SHIFT;1503pgoff_t end = (offset + count - 1) >> PAGE_CACHE_SHIFT;1504unsigned long len = end - start + 1;1505ret = do_readahead(mapping, file, start, len);1506}1507fput(file);1508}1509return ret;1510}1511#ifdef CONFIG_HAVE_SYSCALL_WRAPPERS1512asmlinkage long SyS_readahead(long fd, loff_t offset, long count)1513{1514return SYSC_readahead((int) fd, offset, (size_t) count);1515}1516SYSCALL_ALIAS(sys_readahead, SyS_readahead);1517#endif15181519#ifdef CONFIG_MMU1520/**1521* page_cache_read - adds requested page to the page cache if not already there1522* @file: file to read1523* @offset: page index1524*1525* This adds the requested page to the page cache if it isn't already there,1526* and schedules an I/O to read in its contents from disk.1527*/1528static int page_cache_read(struct file *file, pgoff_t offset)1529{1530struct address_space *mapping = file->f_mapping;1531struct page *page;1532int ret;15331534do {1535page = page_cache_alloc_cold(mapping);1536if (!page)1537return -ENOMEM;15381539ret = add_to_page_cache_lru(page, mapping, offset, GFP_KERNEL);1540if (ret == 0)1541ret = mapping->a_ops->readpage(file, page);1542else if (ret == -EEXIST)1543ret = 0; /* losing race to add is OK */15441545page_cache_release(page);15461547} while (ret == AOP_TRUNCATED_PAGE);15481549return ret;1550}15511552#define MMAP_LOTSAMISS (100)15531554/*1555* Synchronous readahead happens when we don't even find1556* a page in the page cache at all.1557*/1558static void do_sync_mmap_readahead(struct vm_area_struct *vma,1559struct file_ra_state *ra,1560struct file *file,1561pgoff_t offset)1562{1563unsigned long ra_pages;1564struct address_space *mapping = file->f_mapping;15651566/* If we don't want any read-ahead, don't bother */1567if (VM_RandomReadHint(vma))1568return;1569if (!ra->ra_pages)1570return;15711572if (VM_SequentialReadHint(vma)) {1573page_cache_sync_readahead(mapping, ra, file, offset,1574ra->ra_pages);1575return;1576}15771578/* Avoid banging the cache line if not needed */1579if (ra->mmap_miss < MMAP_LOTSAMISS * 10)1580ra->mmap_miss++;15811582/*1583* Do we miss much more than hit in this file? If so,1584* stop bothering with read-ahead. It will only hurt.1585*/1586if (ra->mmap_miss > MMAP_LOTSAMISS)1587return;15881589/*1590* mmap read-around1591*/1592ra_pages = max_sane_readahead(ra->ra_pages);1593ra->start = max_t(long, 0, offset - ra_pages / 2);1594ra->size = ra_pages;1595ra->async_size = ra_pages / 4;1596ra_submit(ra, mapping, file);1597}15981599/*1600* Asynchronous readahead happens when we find the page and PG_readahead,1601* so we want to possibly extend the readahead further..1602*/1603static void do_async_mmap_readahead(struct vm_area_struct *vma,1604struct file_ra_state *ra,1605struct file *file,1606struct page *page,1607pgoff_t offset)1608{1609struct address_space *mapping = file->f_mapping;16101611/* If we don't want any read-ahead, don't bother */1612if (VM_RandomReadHint(vma))1613return;1614if (ra->mmap_miss > 0)1615ra->mmap_miss--;1616if (PageReadahead(page))1617page_cache_async_readahead(mapping, ra, file,1618page, offset, ra->ra_pages);1619}16201621/**1622* filemap_fault - read in file data for page fault handling1623* @vma: vma in which the fault was taken1624* @vmf: struct vm_fault containing details of the fault1625*1626* filemap_fault() is invoked via the vma operations vector for a1627* mapped memory region to read in file data during a page fault.1628*1629* The goto's are kind of ugly, but this streamlines the normal case of having1630* it in the page cache, and handles the special cases reasonably without1631* having a lot of duplicated code.1632*/1633int filemap_fault(struct vm_area_struct *vma, struct vm_fault *vmf)1634{1635int error;1636struct file *file = vma->vm_file;1637struct address_space *mapping = file->f_mapping;1638struct file_ra_state *ra = &file->f_ra;1639struct inode *inode = mapping->host;1640pgoff_t offset = vmf->pgoff;1641struct page *page;1642pgoff_t size;1643int ret = 0;16441645size = (i_size_read(inode) + PAGE_CACHE_SIZE - 1) >> PAGE_CACHE_SHIFT;1646if (offset >= size)1647return VM_FAULT_SIGBUS;16481649/*1650* Do we have something in the page cache already?1651*/1652page = find_get_page(mapping, offset);1653if (likely(page)) {1654/*1655* We found the page, so try async readahead before1656* waiting for the lock.1657*/1658do_async_mmap_readahead(vma, ra, file, page, offset);1659} else {1660/* No page in the page cache at all */1661do_sync_mmap_readahead(vma, ra, file, offset);1662count_vm_event(PGMAJFAULT);1663mem_cgroup_count_vm_event(vma->vm_mm, PGMAJFAULT);1664ret = VM_FAULT_MAJOR;1665retry_find:1666page = find_get_page(mapping, offset);1667if (!page)1668goto no_cached_page;1669}16701671if (!lock_page_or_retry(page, vma->vm_mm, vmf->flags)) {1672page_cache_release(page);1673return ret | VM_FAULT_RETRY;1674}16751676/* Did it get truncated? */1677if (unlikely(page->mapping != mapping)) {1678unlock_page(page);1679put_page(page);1680goto retry_find;1681}1682VM_BUG_ON(page->index != offset);16831684/*1685* We have a locked page in the page cache, now we need to check1686* that it's up-to-date. If not, it is going to be due to an error.1687*/1688if (unlikely(!PageUptodate(page)))1689goto page_not_uptodate;16901691/*1692* Found the page and have a reference on it.1693* We must recheck i_size under page lock.1694*/1695size = (i_size_read(inode) + PAGE_CACHE_SIZE - 1) >> PAGE_CACHE_SHIFT;1696if (unlikely(offset >= size)) {1697unlock_page(page);1698page_cache_release(page);1699return VM_FAULT_SIGBUS;1700}17011702vmf->page = page;1703return ret | VM_FAULT_LOCKED;17041705no_cached_page:1706/*1707* We're only likely to ever get here if MADV_RANDOM is in1708* effect.1709*/1710error = page_cache_read(file, offset);17111712/*1713* The page we want has now been added to the page cache.1714* In the unlikely event that someone removed it in the1715* meantime, we'll just come back here and read it again.1716*/1717if (error >= 0)1718goto retry_find;17191720/*1721* An error return from page_cache_read can result if the1722* system is low on memory, or a problem occurs while trying1723* to schedule I/O.1724*/1725if (error == -ENOMEM)1726return VM_FAULT_OOM;1727return VM_FAULT_SIGBUS;17281729page_not_uptodate:1730/*1731* Umm, take care of errors if the page isn't up-to-date.1732* Try to re-read it _once_. We do this synchronously,1733* because there really aren't any performance issues here1734* and we need to check for errors.1735*/1736ClearPageError(page);1737error = mapping->a_ops->readpage(file, page);1738if (!error) {1739wait_on_page_locked(page);1740if (!PageUptodate(page))1741error = -EIO;1742}1743page_cache_release(page);17441745if (!error || error == AOP_TRUNCATED_PAGE)1746goto retry_find;17471748/* Things didn't work out. Return zero to tell the mm layer so. */1749shrink_readahead_size_eio(file, ra);1750return VM_FAULT_SIGBUS;1751}1752EXPORT_SYMBOL(filemap_fault);17531754const struct vm_operations_struct generic_file_vm_ops = {1755.fault = filemap_fault,1756};17571758/* This is used for a general mmap of a disk file */17591760int generic_file_mmap(struct file * file, struct vm_area_struct * vma)1761{1762struct address_space *mapping = file->f_mapping;17631764if (!mapping->a_ops->readpage)1765return -ENOEXEC;1766file_accessed(file);1767vma->vm_ops = &generic_file_vm_ops;1768vma->vm_flags |= VM_CAN_NONLINEAR;1769return 0;1770}17711772/*1773* This is for filesystems which do not implement ->writepage.1774*/1775int generic_file_readonly_mmap(struct file *file, struct vm_area_struct *vma)1776{1777if ((vma->vm_flags & VM_SHARED) && (vma->vm_flags & VM_MAYWRITE))1778return -EINVAL;1779return generic_file_mmap(file, vma);1780}1781#else1782int generic_file_mmap(struct file * file, struct vm_area_struct * vma)1783{1784return -ENOSYS;1785}1786int generic_file_readonly_mmap(struct file * file, struct vm_area_struct * vma)1787{1788return -ENOSYS;1789}1790#endif /* CONFIG_MMU */17911792EXPORT_SYMBOL(generic_file_mmap);1793EXPORT_SYMBOL(generic_file_readonly_mmap);17941795static struct page *__read_cache_page(struct address_space *mapping,1796pgoff_t index,1797int (*filler)(void *,struct page*),1798void *data,1799gfp_t gfp)1800{1801struct page *page;1802int err;1803repeat:1804page = find_get_page(mapping, index);1805if (!page) {1806page = __page_cache_alloc(gfp | __GFP_COLD);1807if (!page)1808return ERR_PTR(-ENOMEM);1809err = add_to_page_cache_lru(page, mapping, index, GFP_KERNEL);1810if (unlikely(err)) {1811page_cache_release(page);1812if (err == -EEXIST)1813goto repeat;1814/* Presumably ENOMEM for radix tree node */1815return ERR_PTR(err);1816}1817err = filler(data, page);1818if (err < 0) {1819page_cache_release(page);1820page = ERR_PTR(err);1821}1822}1823return page;1824}18251826static struct page *do_read_cache_page(struct address_space *mapping,1827pgoff_t index,1828int (*filler)(void *,struct page*),1829void *data,1830gfp_t gfp)18311832{1833struct page *page;1834int err;18351836retry:1837page = __read_cache_page(mapping, index, filler, data, gfp);1838if (IS_ERR(page))1839return page;1840if (PageUptodate(page))1841goto out;18421843lock_page(page);1844if (!page->mapping) {1845unlock_page(page);1846page_cache_release(page);1847goto retry;1848}1849if (PageUptodate(page)) {1850unlock_page(page);1851goto out;1852}1853err = filler(data, page);1854if (err < 0) {1855page_cache_release(page);1856return ERR_PTR(err);1857}1858out:1859mark_page_accessed(page);1860return page;1861}18621863/**1864* read_cache_page_async - read into page cache, fill it if needed1865* @mapping: the page's address_space1866* @index: the page index1867* @filler: function to perform the read1868* @data: destination for read data1869*1870* Same as read_cache_page, but don't wait for page to become unlocked1871* after submitting it to the filler.1872*1873* Read into the page cache. If a page already exists, and PageUptodate() is1874* not set, try to fill the page but don't wait for it to become unlocked.1875*1876* If the page does not get brought uptodate, return -EIO.1877*/1878struct page *read_cache_page_async(struct address_space *mapping,1879pgoff_t index,1880int (*filler)(void *,struct page*),1881void *data)1882{1883return do_read_cache_page(mapping, index, filler, data, mapping_gfp_mask(mapping));1884}1885EXPORT_SYMBOL(read_cache_page_async);18861887static struct page *wait_on_page_read(struct page *page)1888{1889if (!IS_ERR(page)) {1890wait_on_page_locked(page);1891if (!PageUptodate(page)) {1892page_cache_release(page);1893page = ERR_PTR(-EIO);1894}1895}1896return page;1897}18981899/**1900* read_cache_page_gfp - read into page cache, using specified page allocation flags.1901* @mapping: the page's address_space1902* @index: the page index1903* @gfp: the page allocator flags to use if allocating1904*1905* This is the same as "read_mapping_page(mapping, index, NULL)", but with1906* any new page allocations done using the specified allocation flags. Note1907* that the Radix tree operations will still use GFP_KERNEL, so you can't1908* expect to do this atomically or anything like that - but you can pass in1909* other page requirements.1910*1911* If the page does not get brought uptodate, return -EIO.1912*/1913struct page *read_cache_page_gfp(struct address_space *mapping,1914pgoff_t index,1915gfp_t gfp)1916{1917filler_t *filler = (filler_t *)mapping->a_ops->readpage;19181919return wait_on_page_read(do_read_cache_page(mapping, index, filler, NULL, gfp));1920}1921EXPORT_SYMBOL(read_cache_page_gfp);19221923/**1924* read_cache_page - read into page cache, fill it if needed1925* @mapping: the page's address_space1926* @index: the page index1927* @filler: function to perform the read1928* @data: destination for read data1929*1930* Read into the page cache. If a page already exists, and PageUptodate() is1931* not set, try to fill the page then wait for it to become unlocked.1932*1933* If the page does not get brought uptodate, return -EIO.1934*/1935struct page *read_cache_page(struct address_space *mapping,1936pgoff_t index,1937int (*filler)(void *,struct page*),1938void *data)1939{1940return wait_on_page_read(read_cache_page_async(mapping, index, filler, data));1941}1942EXPORT_SYMBOL(read_cache_page);19431944/*1945* The logic we want is1946*1947* if suid or (sgid and xgrp)1948* remove privs1949*/1950int should_remove_suid(struct dentry *dentry)1951{1952mode_t mode = dentry->d_inode->i_mode;1953int kill = 0;19541955/* suid always must be killed */1956if (unlikely(mode & S_ISUID))1957kill = ATTR_KILL_SUID;19581959/*1960* sgid without any exec bits is just a mandatory locking mark; leave1961* it alone. If some exec bits are set, it's a real sgid; kill it.1962*/1963if (unlikely((mode & S_ISGID) && (mode & S_IXGRP)))1964kill |= ATTR_KILL_SGID;19651966if (unlikely(kill && !capable(CAP_FSETID) && S_ISREG(mode)))1967return kill;19681969return 0;1970}1971EXPORT_SYMBOL(should_remove_suid);19721973static int __remove_suid(struct dentry *dentry, int kill)1974{1975struct iattr newattrs;19761977newattrs.ia_valid = ATTR_FORCE | kill;1978return notify_change(dentry, &newattrs);1979}19801981int file_remove_suid(struct file *file)1982{1983struct dentry *dentry = file->f_path.dentry;1984struct inode *inode = dentry->d_inode;1985int killsuid;1986int killpriv;1987int error = 0;19881989/* Fast path for nothing security related */1990if (IS_NOSEC(inode))1991return 0;19921993killsuid = should_remove_suid(dentry);1994killpriv = security_inode_need_killpriv(dentry);19951996if (killpriv < 0)1997return killpriv;1998if (killpriv)1999error = security_inode_killpriv(dentry);2000if (!error && killsuid)2001error = __remove_suid(dentry, killsuid);2002if (!error && (inode->i_sb->s_flags & MS_NOSEC))2003inode->i_flags |= S_NOSEC;20042005return error;2006}2007EXPORT_SYMBOL(file_remove_suid);20082009static size_t __iovec_copy_from_user_inatomic(char *vaddr,2010const struct iovec *iov, size_t base, size_t bytes)2011{2012size_t copied = 0, left = 0;20132014while (bytes) {2015char __user *buf = iov->iov_base + base;2016int copy = min(bytes, iov->iov_len - base);20172018base = 0;2019left = __copy_from_user_inatomic(vaddr, buf, copy);2020copied += copy;2021bytes -= copy;2022vaddr += copy;2023iov++;20242025if (unlikely(left))2026break;2027}2028return copied - left;2029}20302031/*2032* Copy as much as we can into the page and return the number of bytes which2033* were successfully copied. If a fault is encountered then return the number of2034* bytes which were copied.2035*/2036size_t iov_iter_copy_from_user_atomic(struct page *page,2037struct iov_iter *i, unsigned long offset, size_t bytes)2038{2039char *kaddr;2040size_t copied;20412042BUG_ON(!in_atomic());2043kaddr = kmap_atomic(page, KM_USER0);2044if (likely(i->nr_segs == 1)) {2045int left;2046char __user *buf = i->iov->iov_base + i->iov_offset;2047left = __copy_from_user_inatomic(kaddr + offset, buf, bytes);2048copied = bytes - left;2049} else {2050copied = __iovec_copy_from_user_inatomic(kaddr + offset,2051i->iov, i->iov_offset, bytes);2052}2053kunmap_atomic(kaddr, KM_USER0);20542055return copied;2056}2057EXPORT_SYMBOL(iov_iter_copy_from_user_atomic);20582059/*2060* This has the same sideeffects and return value as2061* iov_iter_copy_from_user_atomic().2062* The difference is that it attempts to resolve faults.2063* Page must not be locked.2064*/2065size_t iov_iter_copy_from_user(struct page *page,2066struct iov_iter *i, unsigned long offset, size_t bytes)2067{2068char *kaddr;2069size_t copied;20702071kaddr = kmap(page);2072if (likely(i->nr_segs == 1)) {2073int left;2074char __user *buf = i->iov->iov_base + i->iov_offset;2075left = __copy_from_user(kaddr + offset, buf, bytes);2076copied = bytes - left;2077} else {2078copied = __iovec_copy_from_user_inatomic(kaddr + offset,2079i->iov, i->iov_offset, bytes);2080}2081kunmap(page);2082return copied;2083}2084EXPORT_SYMBOL(iov_iter_copy_from_user);20852086void iov_iter_advance(struct iov_iter *i, size_t bytes)2087{2088BUG_ON(i->count < bytes);20892090if (likely(i->nr_segs == 1)) {2091i->iov_offset += bytes;2092i->count -= bytes;2093} else {2094const struct iovec *iov = i->iov;2095size_t base = i->iov_offset;20962097/*2098* The !iov->iov_len check ensures we skip over unlikely2099* zero-length segments (without overruning the iovec).2100*/2101while (bytes || unlikely(i->count && !iov->iov_len)) {2102int copy;21032104copy = min(bytes, iov->iov_len - base);2105BUG_ON(!i->count || i->count < copy);2106i->count -= copy;2107bytes -= copy;2108base += copy;2109if (iov->iov_len == base) {2110iov++;2111base = 0;2112}2113}2114i->iov = iov;2115i->iov_offset = base;2116}2117}2118EXPORT_SYMBOL(iov_iter_advance);21192120/*2121* Fault in the first iovec of the given iov_iter, to a maximum length2122* of bytes. Returns 0 on success, or non-zero if the memory could not be2123* accessed (ie. because it is an invalid address).2124*2125* writev-intensive code may want this to prefault several iovecs -- that2126* would be possible (callers must not rely on the fact that _only_ the2127* first iovec will be faulted with the current implementation).2128*/2129int iov_iter_fault_in_readable(struct iov_iter *i, size_t bytes)2130{2131char __user *buf = i->iov->iov_base + i->iov_offset;2132bytes = min(bytes, i->iov->iov_len - i->iov_offset);2133return fault_in_pages_readable(buf, bytes);2134}2135EXPORT_SYMBOL(iov_iter_fault_in_readable);21362137/*2138* Return the count of just the current iov_iter segment.2139*/2140size_t iov_iter_single_seg_count(struct iov_iter *i)2141{2142const struct iovec *iov = i->iov;2143if (i->nr_segs == 1)2144return i->count;2145else2146return min(i->count, iov->iov_len - i->iov_offset);2147}2148EXPORT_SYMBOL(iov_iter_single_seg_count);21492150/*2151* Performs necessary checks before doing a write2152*2153* Can adjust writing position or amount of bytes to write.2154* Returns appropriate error code that caller should return or2155* zero in case that write should be allowed.2156*/2157inline int generic_write_checks(struct file *file, loff_t *pos, size_t *count, int isblk)2158{2159struct inode *inode = file->f_mapping->host;2160unsigned long limit = rlimit(RLIMIT_FSIZE);21612162if (unlikely(*pos < 0))2163return -EINVAL;21642165if (!isblk) {2166/* FIXME: this is for backwards compatibility with 2.4 */2167if (file->f_flags & O_APPEND)2168*pos = i_size_read(inode);21692170if (limit != RLIM_INFINITY) {2171if (*pos >= limit) {2172send_sig(SIGXFSZ, current, 0);2173return -EFBIG;2174}2175if (*count > limit - (typeof(limit))*pos) {2176*count = limit - (typeof(limit))*pos;2177}2178}2179}21802181/*2182* LFS rule2183*/2184if (unlikely(*pos + *count > MAX_NON_LFS &&2185!(file->f_flags & O_LARGEFILE))) {2186if (*pos >= MAX_NON_LFS) {2187return -EFBIG;2188}2189if (*count > MAX_NON_LFS - (unsigned long)*pos) {2190*count = MAX_NON_LFS - (unsigned long)*pos;2191}2192}21932194/*2195* Are we about to exceed the fs block limit ?2196*2197* If we have written data it becomes a short write. If we have2198* exceeded without writing data we send a signal and return EFBIG.2199* Linus frestrict idea will clean these up nicely..2200*/2201if (likely(!isblk)) {2202if (unlikely(*pos >= inode->i_sb->s_maxbytes)) {2203if (*count || *pos > inode->i_sb->s_maxbytes) {2204return -EFBIG;2205}2206/* zero-length writes at ->s_maxbytes are OK */2207}22082209if (unlikely(*pos + *count > inode->i_sb->s_maxbytes))2210*count = inode->i_sb->s_maxbytes - *pos;2211} else {2212#ifdef CONFIG_BLOCK2213loff_t isize;2214if (bdev_read_only(I_BDEV(inode)))2215return -EPERM;2216isize = i_size_read(inode);2217if (*pos >= isize) {2218if (*count || *pos > isize)2219return -ENOSPC;2220}22212222if (*pos + *count > isize)2223*count = isize - *pos;2224#else2225return -EPERM;2226#endif2227}2228return 0;2229}2230EXPORT_SYMBOL(generic_write_checks);22312232int pagecache_write_begin(struct file *file, struct address_space *mapping,2233loff_t pos, unsigned len, unsigned flags,2234struct page **pagep, void **fsdata)2235{2236const struct address_space_operations *aops = mapping->a_ops;22372238return aops->write_begin(file, mapping, pos, len, flags,2239pagep, fsdata);2240}2241EXPORT_SYMBOL(pagecache_write_begin);22422243int pagecache_write_end(struct file *file, struct address_space *mapping,2244loff_t pos, unsigned len, unsigned copied,2245struct page *page, void *fsdata)2246{2247const struct address_space_operations *aops = mapping->a_ops;22482249mark_page_accessed(page);2250return aops->write_end(file, mapping, pos, len, copied, page, fsdata);2251}2252EXPORT_SYMBOL(pagecache_write_end);22532254ssize_t2255generic_file_direct_write(struct kiocb *iocb, const struct iovec *iov,2256unsigned long *nr_segs, loff_t pos, loff_t *ppos,2257size_t count, size_t ocount)2258{2259struct file *file = iocb->ki_filp;2260struct address_space *mapping = file->f_mapping;2261struct inode *inode = mapping->host;2262ssize_t written;2263size_t write_len;2264pgoff_t end;22652266if (count != ocount)2267*nr_segs = iov_shorten((struct iovec *)iov, *nr_segs, count);22682269write_len = iov_length(iov, *nr_segs);2270end = (pos + write_len - 1) >> PAGE_CACHE_SHIFT;22712272written = filemap_write_and_wait_range(mapping, pos, pos + write_len - 1);2273if (written)2274goto out;22752276/*2277* After a write we want buffered reads to be sure to go to disk to get2278* the new data. We invalidate clean cached page from the region we're2279* about to write. We do this *before* the write so that we can return2280* without clobbering -EIOCBQUEUED from ->direct_IO().2281*/2282if (mapping->nrpages) {2283written = invalidate_inode_pages2_range(mapping,2284pos >> PAGE_CACHE_SHIFT, end);2285/*2286* If a page can not be invalidated, return 0 to fall back2287* to buffered write.2288*/2289if (written) {2290if (written == -EBUSY)2291return 0;2292goto out;2293}2294}22952296written = mapping->a_ops->direct_IO(WRITE, iocb, iov, pos, *nr_segs);22972298/*2299* Finally, try again to invalidate clean pages which might have been2300* cached by non-direct readahead, or faulted in by get_user_pages()2301* if the source of the write was an mmap'ed region of the file2302* we're writing. Either one is a pretty crazy thing to do,2303* so we don't support it 100%. If this invalidation2304* fails, tough, the write still worked...2305*/2306if (mapping->nrpages) {2307invalidate_inode_pages2_range(mapping,2308pos >> PAGE_CACHE_SHIFT, end);2309}23102311if (written > 0) {2312pos += written;2313if (pos > i_size_read(inode) && !S_ISBLK(inode->i_mode)) {2314i_size_write(inode, pos);2315mark_inode_dirty(inode);2316}2317*ppos = pos;2318}2319out:2320return written;2321}2322EXPORT_SYMBOL(generic_file_direct_write);23232324/*2325* Find or create a page at the given pagecache position. Return the locked2326* page. This function is specifically for buffered writes.2327*/2328struct page *grab_cache_page_write_begin(struct address_space *mapping,2329pgoff_t index, unsigned flags)2330{2331int status;2332struct page *page;2333gfp_t gfp_notmask = 0;2334if (flags & AOP_FLAG_NOFS)2335gfp_notmask = __GFP_FS;2336repeat:2337page = find_lock_page(mapping, index);2338if (page)2339goto found;23402341page = __page_cache_alloc(mapping_gfp_mask(mapping) & ~gfp_notmask);2342if (!page)2343return NULL;2344status = add_to_page_cache_lru(page, mapping, index,2345GFP_KERNEL & ~gfp_notmask);2346if (unlikely(status)) {2347page_cache_release(page);2348if (status == -EEXIST)2349goto repeat;2350return NULL;2351}2352found:2353wait_on_page_writeback(page);2354return page;2355}2356EXPORT_SYMBOL(grab_cache_page_write_begin);23572358static ssize_t generic_perform_write(struct file *file,2359struct iov_iter *i, loff_t pos)2360{2361struct address_space *mapping = file->f_mapping;2362const struct address_space_operations *a_ops = mapping->a_ops;2363long status = 0;2364ssize_t written = 0;2365unsigned int flags = 0;23662367/*2368* Copies from kernel address space cannot fail (NFSD is a big user).2369*/2370if (segment_eq(get_fs(), KERNEL_DS))2371flags |= AOP_FLAG_UNINTERRUPTIBLE;23722373do {2374struct page *page;2375unsigned long offset; /* Offset into pagecache page */2376unsigned long bytes; /* Bytes to write to page */2377size_t copied; /* Bytes copied from user */2378void *fsdata;23792380offset = (pos & (PAGE_CACHE_SIZE - 1));2381bytes = min_t(unsigned long, PAGE_CACHE_SIZE - offset,2382iov_iter_count(i));23832384again:23852386/*2387* Bring in the user page that we will copy from _first_.2388* Otherwise there's a nasty deadlock on copying from the2389* same page as we're writing to, without it being marked2390* up-to-date.2391*2392* Not only is this an optimisation, but it is also required2393* to check that the address is actually valid, when atomic2394* usercopies are used, below.2395*/2396if (unlikely(iov_iter_fault_in_readable(i, bytes))) {2397status = -EFAULT;2398break;2399}24002401status = a_ops->write_begin(file, mapping, pos, bytes, flags,2402&page, &fsdata);2403if (unlikely(status))2404break;24052406if (mapping_writably_mapped(mapping))2407flush_dcache_page(page);24082409pagefault_disable();2410copied = iov_iter_copy_from_user_atomic(page, i, offset, bytes);2411pagefault_enable();2412flush_dcache_page(page);24132414mark_page_accessed(page);2415status = a_ops->write_end(file, mapping, pos, bytes, copied,2416page, fsdata);2417if (unlikely(status < 0))2418break;2419copied = status;24202421cond_resched();24222423iov_iter_advance(i, copied);2424if (unlikely(copied == 0)) {2425/*2426* If we were unable to copy any data at all, we must2427* fall back to a single segment length write.2428*2429* If we didn't fallback here, we could livelock2430* because not all segments in the iov can be copied at2431* once without a pagefault.2432*/2433bytes = min_t(unsigned long, PAGE_CACHE_SIZE - offset,2434iov_iter_single_seg_count(i));2435goto again;2436}2437pos += copied;2438written += copied;24392440balance_dirty_pages_ratelimited(mapping);24412442} while (iov_iter_count(i));24432444return written ? written : status;2445}24462447ssize_t2448generic_file_buffered_write(struct kiocb *iocb, const struct iovec *iov,2449unsigned long nr_segs, loff_t pos, loff_t *ppos,2450size_t count, ssize_t written)2451{2452struct file *file = iocb->ki_filp;2453ssize_t status;2454struct iov_iter i;24552456iov_iter_init(&i, iov, nr_segs, count, written);2457status = generic_perform_write(file, &i, pos);24582459if (likely(status >= 0)) {2460written += status;2461*ppos = pos + status;2462}24632464return written ? written : status;2465}2466EXPORT_SYMBOL(generic_file_buffered_write);24672468/**2469* __generic_file_aio_write - write data to a file2470* @iocb: IO state structure (file, offset, etc.)2471* @iov: vector with data to write2472* @nr_segs: number of segments in the vector2473* @ppos: position where to write2474*2475* This function does all the work needed for actually writing data to a2476* file. It does all basic checks, removes SUID from the file, updates2477* modification times and calls proper subroutines depending on whether we2478* do direct IO or a standard buffered write.2479*2480* It expects i_mutex to be grabbed unless we work on a block device or similar2481* object which does not need locking at all.2482*2483* This function does *not* take care of syncing data in case of O_SYNC write.2484* A caller has to handle it. This is mainly due to the fact that we want to2485* avoid syncing under i_mutex.2486*/2487ssize_t __generic_file_aio_write(struct kiocb *iocb, const struct iovec *iov,2488unsigned long nr_segs, loff_t *ppos)2489{2490struct file *file = iocb->ki_filp;2491struct address_space * mapping = file->f_mapping;2492size_t ocount; /* original count */2493size_t count; /* after file limit checks */2494struct inode *inode = mapping->host;2495loff_t pos;2496ssize_t written;2497ssize_t err;24982499ocount = 0;2500err = generic_segment_checks(iov, &nr_segs, &ocount, VERIFY_READ);2501if (err)2502return err;25032504count = ocount;2505pos = *ppos;25062507vfs_check_frozen(inode->i_sb, SB_FREEZE_WRITE);25082509/* We can write back this queue in page reclaim */2510current->backing_dev_info = mapping->backing_dev_info;2511written = 0;25122513err = generic_write_checks(file, &pos, &count, S_ISBLK(inode->i_mode));2514if (err)2515goto out;25162517if (count == 0)2518goto out;25192520err = file_remove_suid(file);2521if (err)2522goto out;25232524file_update_time(file);25252526/* coalesce the iovecs and go direct-to-BIO for O_DIRECT */2527if (unlikely(file->f_flags & O_DIRECT)) {2528loff_t endbyte;2529ssize_t written_buffered;25302531written = generic_file_direct_write(iocb, iov, &nr_segs, pos,2532ppos, count, ocount);2533if (written < 0 || written == count)2534goto out;2535/*2536* direct-io write to a hole: fall through to buffered I/O2537* for completing the rest of the request.2538*/2539pos += written;2540count -= written;2541written_buffered = generic_file_buffered_write(iocb, iov,2542nr_segs, pos, ppos, count,2543written);2544/*2545* If generic_file_buffered_write() retuned a synchronous error2546* then we want to return the number of bytes which were2547* direct-written, or the error code if that was zero. Note2548* that this differs from normal direct-io semantics, which2549* will return -EFOO even if some bytes were written.2550*/2551if (written_buffered < 0) {2552err = written_buffered;2553goto out;2554}25552556/*2557* We need to ensure that the page cache pages are written to2558* disk and invalidated to preserve the expected O_DIRECT2559* semantics.2560*/2561endbyte = pos + written_buffered - written - 1;2562err = filemap_write_and_wait_range(file->f_mapping, pos, endbyte);2563if (err == 0) {2564written = written_buffered;2565invalidate_mapping_pages(mapping,2566pos >> PAGE_CACHE_SHIFT,2567endbyte >> PAGE_CACHE_SHIFT);2568} else {2569/*2570* We don't know how much we wrote, so just return2571* the number of bytes which were direct-written2572*/2573}2574} else {2575written = generic_file_buffered_write(iocb, iov, nr_segs,2576pos, ppos, count, written);2577}2578out:2579current->backing_dev_info = NULL;2580return written ? written : err;2581}2582EXPORT_SYMBOL(__generic_file_aio_write);25832584/**2585* generic_file_aio_write - write data to a file2586* @iocb: IO state structure2587* @iov: vector with data to write2588* @nr_segs: number of segments in the vector2589* @pos: position in file where to write2590*2591* This is a wrapper around __generic_file_aio_write() to be used by most2592* filesystems. It takes care of syncing the file in case of O_SYNC file2593* and acquires i_mutex as needed.2594*/2595ssize_t generic_file_aio_write(struct kiocb *iocb, const struct iovec *iov,2596unsigned long nr_segs, loff_t pos)2597{2598struct file *file = iocb->ki_filp;2599struct inode *inode = file->f_mapping->host;2600struct blk_plug plug;2601ssize_t ret;26022603BUG_ON(iocb->ki_pos != pos);26042605mutex_lock(&inode->i_mutex);2606blk_start_plug(&plug);2607ret = __generic_file_aio_write(iocb, iov, nr_segs, &iocb->ki_pos);2608mutex_unlock(&inode->i_mutex);26092610if (ret > 0 || ret == -EIOCBQUEUED) {2611ssize_t err;26122613err = generic_write_sync(file, pos, ret);2614if (err < 0 && ret > 0)2615ret = err;2616}2617blk_finish_plug(&plug);2618return ret;2619}2620EXPORT_SYMBOL(generic_file_aio_write);26212622/**2623* try_to_release_page() - release old fs-specific metadata on a page2624*2625* @page: the page which the kernel is trying to free2626* @gfp_mask: memory allocation flags (and I/O mode)2627*2628* The address_space is to try to release any data against the page2629* (presumably at page->private). If the release was successful, return `1'.2630* Otherwise return zero.2631*2632* This may also be called if PG_fscache is set on a page, indicating that the2633* page is known to the local caching routines.2634*2635* The @gfp_mask argument specifies whether I/O may be performed to release2636* this page (__GFP_IO), and whether the call may block (__GFP_WAIT & __GFP_FS).2637*2638*/2639int try_to_release_page(struct page *page, gfp_t gfp_mask)2640{2641struct address_space * const mapping = page->mapping;26422643BUG_ON(!PageLocked(page));2644if (PageWriteback(page))2645return 0;26462647if (mapping && mapping->a_ops->releasepage)2648return mapping->a_ops->releasepage(page, gfp_mask);2649return try_to_free_buffers(page);2650}26512652EXPORT_SYMBOL(try_to_release_page);265326542655