staging: comedi: fix oops for USB DAQ devices.
[linux-2.6/linux-acpi-2.6/ibm-acpi-2.6.git] / mm / swapfile.c
blob270e136349a0efc72359ad37e9956e65ba4a4eef
1 /*
2 * linux/mm/swapfile.c
4 * Copyright (C) 1991, 1992, 1993, 1994 Linus Torvalds
5 * Swap reorganised 29.12.95, Stephen Tweedie
6 */
8 #include <linux/mm.h>
9 #include <linux/hugetlb.h>
10 #include <linux/mman.h>
11 #include <linux/slab.h>
12 #include <linux/kernel_stat.h>
13 #include <linux/swap.h>
14 #include <linux/vmalloc.h>
15 #include <linux/pagemap.h>
16 #include <linux/namei.h>
17 #include <linux/shm.h>
18 #include <linux/blkdev.h>
19 #include <linux/random.h>
20 #include <linux/writeback.h>
21 #include <linux/proc_fs.h>
22 #include <linux/seq_file.h>
23 #include <linux/init.h>
24 #include <linux/module.h>
25 #include <linux/rmap.h>
26 #include <linux/security.h>
27 #include <linux/backing-dev.h>
28 #include <linux/mutex.h>
29 #include <linux/capability.h>
30 #include <linux/syscalls.h>
31 #include <linux/memcontrol.h>
33 #include <asm/pgtable.h>
34 #include <asm/tlbflush.h>
35 #include <linux/swapops.h>
36 #include <linux/page_cgroup.h>
38 static DEFINE_SPINLOCK(swap_lock);
39 static unsigned int nr_swapfiles;
40 long nr_swap_pages;
41 long total_swap_pages;
42 static int swap_overflow;
43 static int least_priority;
45 static const char Bad_file[] = "Bad swap file entry ";
46 static const char Unused_file[] = "Unused swap file entry ";
47 static const char Bad_offset[] = "Bad swap offset entry ";
48 static const char Unused_offset[] = "Unused swap offset entry ";
50 static struct swap_list_t swap_list = {-1, -1};
52 static struct swap_info_struct swap_info[MAX_SWAPFILES];
54 static DEFINE_MUTEX(swapon_mutex);
56 /* For reference count accounting in swap_map */
57 /* enum for swap_map[] handling. internal use only */
58 enum {
59 SWAP_MAP = 0, /* ops for reference from swap users */
60 SWAP_CACHE, /* ops for reference from swap cache */
63 static inline int swap_count(unsigned short ent)
65 return ent & SWAP_COUNT_MASK;
68 static inline bool swap_has_cache(unsigned short ent)
70 return !!(ent & SWAP_HAS_CACHE);
73 static inline unsigned short encode_swapmap(int count, bool has_cache)
75 unsigned short ret = count;
77 if (has_cache)
78 return SWAP_HAS_CACHE | ret;
79 return ret;
82 /* returnes 1 if swap entry is freed */
83 static int
84 __try_to_reclaim_swap(struct swap_info_struct *si, unsigned long offset)
86 int type = si - swap_info;
87 swp_entry_t entry = swp_entry(type, offset);
88 struct page *page;
89 int ret = 0;
91 page = find_get_page(&swapper_space, entry.val);
92 if (!page)
93 return 0;
95 * This function is called from scan_swap_map() and it's called
96 * by vmscan.c at reclaiming pages. So, we hold a lock on a page, here.
97 * We have to use trylock for avoiding deadlock. This is a special
98 * case and you should use try_to_free_swap() with explicit lock_page()
99 * in usual operations.
101 if (trylock_page(page)) {
102 ret = try_to_free_swap(page);
103 unlock_page(page);
105 page_cache_release(page);
106 return ret;
110 * We need this because the bdev->unplug_fn can sleep and we cannot
111 * hold swap_lock while calling the unplug_fn. And swap_lock
112 * cannot be turned into a mutex.
114 static DECLARE_RWSEM(swap_unplug_sem);
116 void swap_unplug_io_fn(struct backing_dev_info *unused_bdi, struct page *page)
118 swp_entry_t entry;
120 down_read(&swap_unplug_sem);
121 entry.val = page_private(page);
122 if (PageSwapCache(page)) {
123 struct block_device *bdev = swap_info[swp_type(entry)].bdev;
124 struct backing_dev_info *bdi;
127 * If the page is removed from swapcache from under us (with a
128 * racy try_to_unuse/swapoff) we need an additional reference
129 * count to avoid reading garbage from page_private(page) above.
130 * If the WARN_ON triggers during a swapoff it maybe the race
131 * condition and it's harmless. However if it triggers without
132 * swapoff it signals a problem.
134 WARN_ON(page_count(page) <= 1);
136 bdi = bdev->bd_inode->i_mapping->backing_dev_info;
137 blk_run_backing_dev(bdi, page);
139 up_read(&swap_unplug_sem);
143 * swapon tell device that all the old swap contents can be discarded,
144 * to allow the swap device to optimize its wear-levelling.
146 static int discard_swap(struct swap_info_struct *si)
148 struct swap_extent *se;
149 int err = 0;
151 list_for_each_entry(se, &si->extent_list, list) {
152 sector_t start_block = se->start_block << (PAGE_SHIFT - 9);
153 sector_t nr_blocks = (sector_t)se->nr_pages << (PAGE_SHIFT - 9);
155 if (se->start_page == 0) {
156 /* Do not discard the swap header page! */
157 start_block += 1 << (PAGE_SHIFT - 9);
158 nr_blocks -= 1 << (PAGE_SHIFT - 9);
159 if (!nr_blocks)
160 continue;
163 err = blkdev_issue_discard(si->bdev, start_block,
164 nr_blocks, GFP_KERNEL,
165 DISCARD_FL_BARRIER);
166 if (err)
167 break;
169 cond_resched();
171 return err; /* That will often be -EOPNOTSUPP */
175 * swap allocation tell device that a cluster of swap can now be discarded,
176 * to allow the swap device to optimize its wear-levelling.
178 static void discard_swap_cluster(struct swap_info_struct *si,
179 pgoff_t start_page, pgoff_t nr_pages)
181 struct swap_extent *se = si->curr_swap_extent;
182 int found_extent = 0;
184 while (nr_pages) {
185 struct list_head *lh;
187 if (se->start_page <= start_page &&
188 start_page < se->start_page + se->nr_pages) {
189 pgoff_t offset = start_page - se->start_page;
190 sector_t start_block = se->start_block + offset;
191 sector_t nr_blocks = se->nr_pages - offset;
193 if (nr_blocks > nr_pages)
194 nr_blocks = nr_pages;
195 start_page += nr_blocks;
196 nr_pages -= nr_blocks;
198 if (!found_extent++)
199 si->curr_swap_extent = se;
201 start_block <<= PAGE_SHIFT - 9;
202 nr_blocks <<= PAGE_SHIFT - 9;
203 if (blkdev_issue_discard(si->bdev, start_block,
204 nr_blocks, GFP_NOIO,
205 DISCARD_FL_BARRIER))
206 break;
209 lh = se->list.next;
210 if (lh == &si->extent_list)
211 lh = lh->next;
212 se = list_entry(lh, struct swap_extent, list);
216 static int wait_for_discard(void *word)
218 schedule();
219 return 0;
222 #define SWAPFILE_CLUSTER 256
223 #define LATENCY_LIMIT 256
225 static inline unsigned long scan_swap_map(struct swap_info_struct *si,
226 int cache)
228 unsigned long offset;
229 unsigned long scan_base;
230 unsigned long last_in_cluster = 0;
231 int latency_ration = LATENCY_LIMIT;
232 int found_free_cluster = 0;
235 * We try to cluster swap pages by allocating them sequentially
236 * in swap. Once we've allocated SWAPFILE_CLUSTER pages this
237 * way, however, we resort to first-free allocation, starting
238 * a new cluster. This prevents us from scattering swap pages
239 * all over the entire swap partition, so that we reduce
240 * overall disk seek times between swap pages. -- sct
241 * But we do now try to find an empty cluster. -Andrea
242 * And we let swap pages go all over an SSD partition. Hugh
245 si->flags += SWP_SCANNING;
246 scan_base = offset = si->cluster_next;
248 if (unlikely(!si->cluster_nr--)) {
249 if (si->pages - si->inuse_pages < SWAPFILE_CLUSTER) {
250 si->cluster_nr = SWAPFILE_CLUSTER - 1;
251 goto checks;
253 if (si->flags & SWP_DISCARDABLE) {
255 * Start range check on racing allocations, in case
256 * they overlap the cluster we eventually decide on
257 * (we scan without swap_lock to allow preemption).
258 * It's hardly conceivable that cluster_nr could be
259 * wrapped during our scan, but don't depend on it.
261 if (si->lowest_alloc)
262 goto checks;
263 si->lowest_alloc = si->max;
264 si->highest_alloc = 0;
266 spin_unlock(&swap_lock);
269 * If seek is expensive, start searching for new cluster from
270 * start of partition, to minimize the span of allocated swap.
271 * But if seek is cheap, search from our current position, so
272 * that swap is allocated from all over the partition: if the
273 * Flash Translation Layer only remaps within limited zones,
274 * we don't want to wear out the first zone too quickly.
276 if (!(si->flags & SWP_SOLIDSTATE))
277 scan_base = offset = si->lowest_bit;
278 last_in_cluster = offset + SWAPFILE_CLUSTER - 1;
280 /* Locate the first empty (unaligned) cluster */
281 for (; last_in_cluster <= si->highest_bit; offset++) {
282 if (si->swap_map[offset])
283 last_in_cluster = offset + SWAPFILE_CLUSTER;
284 else if (offset == last_in_cluster) {
285 spin_lock(&swap_lock);
286 offset -= SWAPFILE_CLUSTER - 1;
287 si->cluster_next = offset;
288 si->cluster_nr = SWAPFILE_CLUSTER - 1;
289 found_free_cluster = 1;
290 goto checks;
292 if (unlikely(--latency_ration < 0)) {
293 cond_resched();
294 latency_ration = LATENCY_LIMIT;
298 offset = si->lowest_bit;
299 last_in_cluster = offset + SWAPFILE_CLUSTER - 1;
301 /* Locate the first empty (unaligned) cluster */
302 for (; last_in_cluster < scan_base; offset++) {
303 if (si->swap_map[offset])
304 last_in_cluster = offset + SWAPFILE_CLUSTER;
305 else if (offset == last_in_cluster) {
306 spin_lock(&swap_lock);
307 offset -= SWAPFILE_CLUSTER - 1;
308 si->cluster_next = offset;
309 si->cluster_nr = SWAPFILE_CLUSTER - 1;
310 found_free_cluster = 1;
311 goto checks;
313 if (unlikely(--latency_ration < 0)) {
314 cond_resched();
315 latency_ration = LATENCY_LIMIT;
319 offset = scan_base;
320 spin_lock(&swap_lock);
321 si->cluster_nr = SWAPFILE_CLUSTER - 1;
322 si->lowest_alloc = 0;
325 checks:
326 if (!(si->flags & SWP_WRITEOK))
327 goto no_page;
328 if (!si->highest_bit)
329 goto no_page;
330 if (offset > si->highest_bit)
331 scan_base = offset = si->lowest_bit;
333 /* reuse swap entry of cache-only swap if not hibernation. */
334 if (vm_swap_full()
335 && cache == SWAP_CACHE
336 && si->swap_map[offset] == SWAP_HAS_CACHE) {
337 int swap_was_freed;
338 spin_unlock(&swap_lock);
339 swap_was_freed = __try_to_reclaim_swap(si, offset);
340 spin_lock(&swap_lock);
341 /* entry was freed successfully, try to use this again */
342 if (swap_was_freed)
343 goto checks;
344 goto scan; /* check next one */
347 if (si->swap_map[offset])
348 goto scan;
350 if (offset == si->lowest_bit)
351 si->lowest_bit++;
352 if (offset == si->highest_bit)
353 si->highest_bit--;
354 si->inuse_pages++;
355 if (si->inuse_pages == si->pages) {
356 si->lowest_bit = si->max;
357 si->highest_bit = 0;
359 if (cache == SWAP_CACHE) /* at usual swap-out via vmscan.c */
360 si->swap_map[offset] = encode_swapmap(0, true);
361 else /* at suspend */
362 si->swap_map[offset] = encode_swapmap(1, false);
363 si->cluster_next = offset + 1;
364 si->flags -= SWP_SCANNING;
366 if (si->lowest_alloc) {
368 * Only set when SWP_DISCARDABLE, and there's a scan
369 * for a free cluster in progress or just completed.
371 if (found_free_cluster) {
373 * To optimize wear-levelling, discard the
374 * old data of the cluster, taking care not to
375 * discard any of its pages that have already
376 * been allocated by racing tasks (offset has
377 * already stepped over any at the beginning).
379 if (offset < si->highest_alloc &&
380 si->lowest_alloc <= last_in_cluster)
381 last_in_cluster = si->lowest_alloc - 1;
382 si->flags |= SWP_DISCARDING;
383 spin_unlock(&swap_lock);
385 if (offset < last_in_cluster)
386 discard_swap_cluster(si, offset,
387 last_in_cluster - offset + 1);
389 spin_lock(&swap_lock);
390 si->lowest_alloc = 0;
391 si->flags &= ~SWP_DISCARDING;
393 smp_mb(); /* wake_up_bit advises this */
394 wake_up_bit(&si->flags, ilog2(SWP_DISCARDING));
396 } else if (si->flags & SWP_DISCARDING) {
398 * Delay using pages allocated by racing tasks
399 * until the whole discard has been issued. We
400 * could defer that delay until swap_writepage,
401 * but it's easier to keep this self-contained.
403 spin_unlock(&swap_lock);
404 wait_on_bit(&si->flags, ilog2(SWP_DISCARDING),
405 wait_for_discard, TASK_UNINTERRUPTIBLE);
406 spin_lock(&swap_lock);
407 } else {
409 * Note pages allocated by racing tasks while
410 * scan for a free cluster is in progress, so
411 * that its final discard can exclude them.
413 if (offset < si->lowest_alloc)
414 si->lowest_alloc = offset;
415 if (offset > si->highest_alloc)
416 si->highest_alloc = offset;
419 return offset;
421 scan:
422 spin_unlock(&swap_lock);
423 while (++offset <= si->highest_bit) {
424 if (!si->swap_map[offset]) {
425 spin_lock(&swap_lock);
426 goto checks;
428 if (vm_swap_full() && si->swap_map[offset] == SWAP_HAS_CACHE) {
429 spin_lock(&swap_lock);
430 goto checks;
432 if (unlikely(--latency_ration < 0)) {
433 cond_resched();
434 latency_ration = LATENCY_LIMIT;
437 offset = si->lowest_bit;
438 while (++offset < scan_base) {
439 if (!si->swap_map[offset]) {
440 spin_lock(&swap_lock);
441 goto checks;
443 if (vm_swap_full() && si->swap_map[offset] == SWAP_HAS_CACHE) {
444 spin_lock(&swap_lock);
445 goto checks;
447 if (unlikely(--latency_ration < 0)) {
448 cond_resched();
449 latency_ration = LATENCY_LIMIT;
452 spin_lock(&swap_lock);
454 no_page:
455 si->flags -= SWP_SCANNING;
456 return 0;
459 swp_entry_t get_swap_page(void)
461 struct swap_info_struct *si;
462 pgoff_t offset;
463 int type, next;
464 int wrapped = 0;
466 spin_lock(&swap_lock);
467 if (nr_swap_pages <= 0)
468 goto noswap;
469 nr_swap_pages--;
471 for (type = swap_list.next; type >= 0 && wrapped < 2; type = next) {
472 si = swap_info + type;
473 next = si->next;
474 if (next < 0 ||
475 (!wrapped && si->prio != swap_info[next].prio)) {
476 next = swap_list.head;
477 wrapped++;
480 if (!si->highest_bit)
481 continue;
482 if (!(si->flags & SWP_WRITEOK))
483 continue;
485 swap_list.next = next;
486 /* This is called for allocating swap entry for cache */
487 offset = scan_swap_map(si, SWAP_CACHE);
488 if (offset) {
489 spin_unlock(&swap_lock);
490 return swp_entry(type, offset);
492 next = swap_list.next;
495 nr_swap_pages++;
496 noswap:
497 spin_unlock(&swap_lock);
498 return (swp_entry_t) {0};
501 /* The only caller of this function is now susupend routine */
502 swp_entry_t get_swap_page_of_type(int type)
504 struct swap_info_struct *si;
505 pgoff_t offset;
507 spin_lock(&swap_lock);
508 si = swap_info + type;
509 if (si->flags & SWP_WRITEOK) {
510 nr_swap_pages--;
511 /* This is called for allocating swap entry, not cache */
512 offset = scan_swap_map(si, SWAP_MAP);
513 if (offset) {
514 spin_unlock(&swap_lock);
515 return swp_entry(type, offset);
517 nr_swap_pages++;
519 spin_unlock(&swap_lock);
520 return (swp_entry_t) {0};
523 static struct swap_info_struct * swap_info_get(swp_entry_t entry)
525 struct swap_info_struct * p;
526 unsigned long offset, type;
528 if (!entry.val)
529 goto out;
530 type = swp_type(entry);
531 if (type >= nr_swapfiles)
532 goto bad_nofile;
533 p = & swap_info[type];
534 if (!(p->flags & SWP_USED))
535 goto bad_device;
536 offset = swp_offset(entry);
537 if (offset >= p->max)
538 goto bad_offset;
539 if (!p->swap_map[offset])
540 goto bad_free;
541 spin_lock(&swap_lock);
542 return p;
544 bad_free:
545 printk(KERN_ERR "swap_free: %s%08lx\n", Unused_offset, entry.val);
546 goto out;
547 bad_offset:
548 printk(KERN_ERR "swap_free: %s%08lx\n", Bad_offset, entry.val);
549 goto out;
550 bad_device:
551 printk(KERN_ERR "swap_free: %s%08lx\n", Unused_file, entry.val);
552 goto out;
553 bad_nofile:
554 printk(KERN_ERR "swap_free: %s%08lx\n", Bad_file, entry.val);
555 out:
556 return NULL;
559 static int swap_entry_free(struct swap_info_struct *p,
560 swp_entry_t ent, int cache)
562 unsigned long offset = swp_offset(ent);
563 int count = swap_count(p->swap_map[offset]);
564 bool has_cache;
566 has_cache = swap_has_cache(p->swap_map[offset]);
568 if (cache == SWAP_MAP) { /* dropping usage count of swap */
569 if (count < SWAP_MAP_MAX) {
570 count--;
571 p->swap_map[offset] = encode_swapmap(count, has_cache);
573 } else { /* dropping swap cache flag */
574 VM_BUG_ON(!has_cache);
575 p->swap_map[offset] = encode_swapmap(count, false);
578 /* return code. */
579 count = p->swap_map[offset];
580 /* free if no reference */
581 if (!count) {
582 if (offset < p->lowest_bit)
583 p->lowest_bit = offset;
584 if (offset > p->highest_bit)
585 p->highest_bit = offset;
586 if (p->prio > swap_info[swap_list.next].prio)
587 swap_list.next = p - swap_info;
588 nr_swap_pages++;
589 p->inuse_pages--;
591 if (!swap_count(count))
592 mem_cgroup_uncharge_swap(ent);
593 return count;
597 * Caller has made sure that the swapdevice corresponding to entry
598 * is still around or has not been recycled.
600 void swap_free(swp_entry_t entry)
602 struct swap_info_struct * p;
604 p = swap_info_get(entry);
605 if (p) {
606 swap_entry_free(p, entry, SWAP_MAP);
607 spin_unlock(&swap_lock);
612 * Called after dropping swapcache to decrease refcnt to swap entries.
614 void swapcache_free(swp_entry_t entry, struct page *page)
616 struct swap_info_struct *p;
617 int ret;
619 p = swap_info_get(entry);
620 if (p) {
621 ret = swap_entry_free(p, entry, SWAP_CACHE);
622 if (page) {
623 bool swapout;
624 if (ret)
625 swapout = true; /* the end of swap out */
626 else
627 swapout = false; /* no more swap users! */
628 mem_cgroup_uncharge_swapcache(page, entry, swapout);
630 spin_unlock(&swap_lock);
632 return;
636 * How many references to page are currently swapped out?
638 static inline int page_swapcount(struct page *page)
640 int count = 0;
641 struct swap_info_struct *p;
642 swp_entry_t entry;
644 entry.val = page_private(page);
645 p = swap_info_get(entry);
646 if (p) {
647 count = swap_count(p->swap_map[swp_offset(entry)]);
648 spin_unlock(&swap_lock);
650 return count;
654 * We can write to an anon page without COW if there are no other references
655 * to it. And as a side-effect, free up its swap: because the old content
656 * on disk will never be read, and seeking back there to write new content
657 * later would only waste time away from clustering.
659 int reuse_swap_page(struct page *page)
661 int count;
663 VM_BUG_ON(!PageLocked(page));
664 count = page_mapcount(page);
665 if (count <= 1 && PageSwapCache(page)) {
666 count += page_swapcount(page);
667 if (count == 1 && !PageWriteback(page)) {
668 delete_from_swap_cache(page);
669 SetPageDirty(page);
672 return count == 1;
676 * If swap is getting full, or if there are no more mappings of this page,
677 * then try_to_free_swap is called to free its swap space.
679 int try_to_free_swap(struct page *page)
681 VM_BUG_ON(!PageLocked(page));
683 if (!PageSwapCache(page))
684 return 0;
685 if (PageWriteback(page))
686 return 0;
687 if (page_swapcount(page))
688 return 0;
690 delete_from_swap_cache(page);
691 SetPageDirty(page);
692 return 1;
696 * Free the swap entry like above, but also try to
697 * free the page cache entry if it is the last user.
699 int free_swap_and_cache(swp_entry_t entry)
701 struct swap_info_struct *p;
702 struct page *page = NULL;
704 if (non_swap_entry(entry))
705 return 1;
707 p = swap_info_get(entry);
708 if (p) {
709 if (swap_entry_free(p, entry, SWAP_MAP) == SWAP_HAS_CACHE) {
710 page = find_get_page(&swapper_space, entry.val);
711 if (page && !trylock_page(page)) {
712 page_cache_release(page);
713 page = NULL;
716 spin_unlock(&swap_lock);
718 if (page) {
720 * Not mapped elsewhere, or swap space full? Free it!
721 * Also recheck PageSwapCache now page is locked (above).
723 if (PageSwapCache(page) && !PageWriteback(page) &&
724 (!page_mapped(page) || vm_swap_full())) {
725 delete_from_swap_cache(page);
726 SetPageDirty(page);
728 unlock_page(page);
729 page_cache_release(page);
731 return p != NULL;
734 #ifdef CONFIG_HIBERNATION
736 * Find the swap type that corresponds to given device (if any).
738 * @offset - number of the PAGE_SIZE-sized block of the device, starting
739 * from 0, in which the swap header is expected to be located.
741 * This is needed for the suspend to disk (aka swsusp).
743 int swap_type_of(dev_t device, sector_t offset, struct block_device **bdev_p)
745 struct block_device *bdev = NULL;
746 int i;
748 if (device)
749 bdev = bdget(device);
751 spin_lock(&swap_lock);
752 for (i = 0; i < nr_swapfiles; i++) {
753 struct swap_info_struct *sis = swap_info + i;
755 if (!(sis->flags & SWP_WRITEOK))
756 continue;
758 if (!bdev) {
759 if (bdev_p)
760 *bdev_p = bdgrab(sis->bdev);
762 spin_unlock(&swap_lock);
763 return i;
765 if (bdev == sis->bdev) {
766 struct swap_extent *se;
768 se = list_entry(sis->extent_list.next,
769 struct swap_extent, list);
770 if (se->start_block == offset) {
771 if (bdev_p)
772 *bdev_p = bdgrab(sis->bdev);
774 spin_unlock(&swap_lock);
775 bdput(bdev);
776 return i;
780 spin_unlock(&swap_lock);
781 if (bdev)
782 bdput(bdev);
784 return -ENODEV;
788 * Return either the total number of swap pages of given type, or the number
789 * of free pages of that type (depending on @free)
791 * This is needed for software suspend
793 unsigned int count_swap_pages(int type, int free)
795 unsigned int n = 0;
797 if (type < nr_swapfiles) {
798 spin_lock(&swap_lock);
799 if (swap_info[type].flags & SWP_WRITEOK) {
800 n = swap_info[type].pages;
801 if (free)
802 n -= swap_info[type].inuse_pages;
804 spin_unlock(&swap_lock);
806 return n;
808 #endif
811 * No need to decide whether this PTE shares the swap entry with others,
812 * just let do_wp_page work it out if a write is requested later - to
813 * force COW, vm_page_prot omits write permission from any private vma.
815 static int unuse_pte(struct vm_area_struct *vma, pmd_t *pmd,
816 unsigned long addr, swp_entry_t entry, struct page *page)
818 struct mem_cgroup *ptr = NULL;
819 spinlock_t *ptl;
820 pte_t *pte;
821 int ret = 1;
823 if (mem_cgroup_try_charge_swapin(vma->vm_mm, page, GFP_KERNEL, &ptr)) {
824 ret = -ENOMEM;
825 goto out_nolock;
828 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
829 if (unlikely(!pte_same(*pte, swp_entry_to_pte(entry)))) {
830 if (ret > 0)
831 mem_cgroup_cancel_charge_swapin(ptr);
832 ret = 0;
833 goto out;
836 inc_mm_counter(vma->vm_mm, anon_rss);
837 get_page(page);
838 set_pte_at(vma->vm_mm, addr, pte,
839 pte_mkold(mk_pte(page, vma->vm_page_prot)));
840 page_add_anon_rmap(page, vma, addr);
841 mem_cgroup_commit_charge_swapin(page, ptr);
842 swap_free(entry);
844 * Move the page to the active list so it is not
845 * immediately swapped out again after swapon.
847 activate_page(page);
848 out:
849 pte_unmap_unlock(pte, ptl);
850 out_nolock:
851 return ret;
854 static int unuse_pte_range(struct vm_area_struct *vma, pmd_t *pmd,
855 unsigned long addr, unsigned long end,
856 swp_entry_t entry, struct page *page)
858 pte_t swp_pte = swp_entry_to_pte(entry);
859 pte_t *pte;
860 int ret = 0;
863 * We don't actually need pte lock while scanning for swp_pte: since
864 * we hold page lock and mmap_sem, swp_pte cannot be inserted into the
865 * page table while we're scanning; though it could get zapped, and on
866 * some architectures (e.g. x86_32 with PAE) we might catch a glimpse
867 * of unmatched parts which look like swp_pte, so unuse_pte must
868 * recheck under pte lock. Scanning without pte lock lets it be
869 * preemptible whenever CONFIG_PREEMPT but not CONFIG_HIGHPTE.
871 pte = pte_offset_map(pmd, addr);
872 do {
874 * swapoff spends a _lot_ of time in this loop!
875 * Test inline before going to call unuse_pte.
877 if (unlikely(pte_same(*pte, swp_pte))) {
878 pte_unmap(pte);
879 ret = unuse_pte(vma, pmd, addr, entry, page);
880 if (ret)
881 goto out;
882 pte = pte_offset_map(pmd, addr);
884 } while (pte++, addr += PAGE_SIZE, addr != end);
885 pte_unmap(pte - 1);
886 out:
887 return ret;
890 static inline int unuse_pmd_range(struct vm_area_struct *vma, pud_t *pud,
891 unsigned long addr, unsigned long end,
892 swp_entry_t entry, struct page *page)
894 pmd_t *pmd;
895 unsigned long next;
896 int ret;
898 pmd = pmd_offset(pud, addr);
899 do {
900 next = pmd_addr_end(addr, end);
901 if (pmd_none_or_clear_bad(pmd))
902 continue;
903 ret = unuse_pte_range(vma, pmd, addr, next, entry, page);
904 if (ret)
905 return ret;
906 } while (pmd++, addr = next, addr != end);
907 return 0;
910 static inline int unuse_pud_range(struct vm_area_struct *vma, pgd_t *pgd,
911 unsigned long addr, unsigned long end,
912 swp_entry_t entry, struct page *page)
914 pud_t *pud;
915 unsigned long next;
916 int ret;
918 pud = pud_offset(pgd, addr);
919 do {
920 next = pud_addr_end(addr, end);
921 if (pud_none_or_clear_bad(pud))
922 continue;
923 ret = unuse_pmd_range(vma, pud, addr, next, entry, page);
924 if (ret)
925 return ret;
926 } while (pud++, addr = next, addr != end);
927 return 0;
930 static int unuse_vma(struct vm_area_struct *vma,
931 swp_entry_t entry, struct page *page)
933 pgd_t *pgd;
934 unsigned long addr, end, next;
935 int ret;
937 if (page->mapping) {
938 addr = page_address_in_vma(page, vma);
939 if (addr == -EFAULT)
940 return 0;
941 else
942 end = addr + PAGE_SIZE;
943 } else {
944 addr = vma->vm_start;
945 end = vma->vm_end;
948 pgd = pgd_offset(vma->vm_mm, addr);
949 do {
950 next = pgd_addr_end(addr, end);
951 if (pgd_none_or_clear_bad(pgd))
952 continue;
953 ret = unuse_pud_range(vma, pgd, addr, next, entry, page);
954 if (ret)
955 return ret;
956 } while (pgd++, addr = next, addr != end);
957 return 0;
960 static int unuse_mm(struct mm_struct *mm,
961 swp_entry_t entry, struct page *page)
963 struct vm_area_struct *vma;
964 int ret = 0;
966 if (!down_read_trylock(&mm->mmap_sem)) {
968 * Activate page so shrink_inactive_list is unlikely to unmap
969 * its ptes while lock is dropped, so swapoff can make progress.
971 activate_page(page);
972 unlock_page(page);
973 down_read(&mm->mmap_sem);
974 lock_page(page);
976 for (vma = mm->mmap; vma; vma = vma->vm_next) {
977 if (vma->anon_vma && (ret = unuse_vma(vma, entry, page)))
978 break;
980 up_read(&mm->mmap_sem);
981 return (ret < 0)? ret: 0;
985 * Scan swap_map from current position to next entry still in use.
986 * Recycle to start on reaching the end, returning 0 when empty.
988 static unsigned int find_next_to_unuse(struct swap_info_struct *si,
989 unsigned int prev)
991 unsigned int max = si->max;
992 unsigned int i = prev;
993 int count;
996 * No need for swap_lock here: we're just looking
997 * for whether an entry is in use, not modifying it; false
998 * hits are okay, and sys_swapoff() has already prevented new
999 * allocations from this area (while holding swap_lock).
1001 for (;;) {
1002 if (++i >= max) {
1003 if (!prev) {
1004 i = 0;
1005 break;
1008 * No entries in use at top of swap_map,
1009 * loop back to start and recheck there.
1011 max = prev + 1;
1012 prev = 0;
1013 i = 1;
1015 count = si->swap_map[i];
1016 if (count && swap_count(count) != SWAP_MAP_BAD)
1017 break;
1019 return i;
1023 * We completely avoid races by reading each swap page in advance,
1024 * and then search for the process using it. All the necessary
1025 * page table adjustments can then be made atomically.
1027 static int try_to_unuse(unsigned int type)
1029 struct swap_info_struct * si = &swap_info[type];
1030 struct mm_struct *start_mm;
1031 unsigned short *swap_map;
1032 unsigned short swcount;
1033 struct page *page;
1034 swp_entry_t entry;
1035 unsigned int i = 0;
1036 int retval = 0;
1037 int reset_overflow = 0;
1038 int shmem;
1041 * When searching mms for an entry, a good strategy is to
1042 * start at the first mm we freed the previous entry from
1043 * (though actually we don't notice whether we or coincidence
1044 * freed the entry). Initialize this start_mm with a hold.
1046 * A simpler strategy would be to start at the last mm we
1047 * freed the previous entry from; but that would take less
1048 * advantage of mmlist ordering, which clusters forked mms
1049 * together, child after parent. If we race with dup_mmap(), we
1050 * prefer to resolve parent before child, lest we miss entries
1051 * duplicated after we scanned child: using last mm would invert
1052 * that. Though it's only a serious concern when an overflowed
1053 * swap count is reset from SWAP_MAP_MAX, preventing a rescan.
1055 start_mm = &init_mm;
1056 atomic_inc(&init_mm.mm_users);
1059 * Keep on scanning until all entries have gone. Usually,
1060 * one pass through swap_map is enough, but not necessarily:
1061 * there are races when an instance of an entry might be missed.
1063 while ((i = find_next_to_unuse(si, i)) != 0) {
1064 if (signal_pending(current)) {
1065 retval = -EINTR;
1066 break;
1070 * Get a page for the entry, using the existing swap
1071 * cache page if there is one. Otherwise, get a clean
1072 * page and read the swap into it.
1074 swap_map = &si->swap_map[i];
1075 entry = swp_entry(type, i);
1076 page = read_swap_cache_async(entry,
1077 GFP_HIGHUSER_MOVABLE, NULL, 0);
1078 if (!page) {
1080 * Either swap_duplicate() failed because entry
1081 * has been freed independently, and will not be
1082 * reused since sys_swapoff() already disabled
1083 * allocation from here, or alloc_page() failed.
1085 if (!*swap_map)
1086 continue;
1087 retval = -ENOMEM;
1088 break;
1092 * Don't hold on to start_mm if it looks like exiting.
1094 if (atomic_read(&start_mm->mm_users) == 1) {
1095 mmput(start_mm);
1096 start_mm = &init_mm;
1097 atomic_inc(&init_mm.mm_users);
1101 * Wait for and lock page. When do_swap_page races with
1102 * try_to_unuse, do_swap_page can handle the fault much
1103 * faster than try_to_unuse can locate the entry. This
1104 * apparently redundant "wait_on_page_locked" lets try_to_unuse
1105 * defer to do_swap_page in such a case - in some tests,
1106 * do_swap_page and try_to_unuse repeatedly compete.
1108 wait_on_page_locked(page);
1109 wait_on_page_writeback(page);
1110 lock_page(page);
1111 wait_on_page_writeback(page);
1114 * Remove all references to entry.
1115 * Whenever we reach init_mm, there's no address space
1116 * to search, but use it as a reminder to search shmem.
1118 shmem = 0;
1119 swcount = *swap_map;
1120 if (swap_count(swcount)) {
1121 if (start_mm == &init_mm)
1122 shmem = shmem_unuse(entry, page);
1123 else
1124 retval = unuse_mm(start_mm, entry, page);
1126 if (swap_count(*swap_map)) {
1127 int set_start_mm = (*swap_map >= swcount);
1128 struct list_head *p = &start_mm->mmlist;
1129 struct mm_struct *new_start_mm = start_mm;
1130 struct mm_struct *prev_mm = start_mm;
1131 struct mm_struct *mm;
1133 atomic_inc(&new_start_mm->mm_users);
1134 atomic_inc(&prev_mm->mm_users);
1135 spin_lock(&mmlist_lock);
1136 while (swap_count(*swap_map) && !retval && !shmem &&
1137 (p = p->next) != &start_mm->mmlist) {
1138 mm = list_entry(p, struct mm_struct, mmlist);
1139 if (!atomic_inc_not_zero(&mm->mm_users))
1140 continue;
1141 spin_unlock(&mmlist_lock);
1142 mmput(prev_mm);
1143 prev_mm = mm;
1145 cond_resched();
1147 swcount = *swap_map;
1148 if (!swap_count(swcount)) /* any usage ? */
1150 else if (mm == &init_mm) {
1151 set_start_mm = 1;
1152 shmem = shmem_unuse(entry, page);
1153 } else
1154 retval = unuse_mm(mm, entry, page);
1156 if (set_start_mm && *swap_map < swcount) {
1157 mmput(new_start_mm);
1158 atomic_inc(&mm->mm_users);
1159 new_start_mm = mm;
1160 set_start_mm = 0;
1162 spin_lock(&mmlist_lock);
1164 spin_unlock(&mmlist_lock);
1165 mmput(prev_mm);
1166 mmput(start_mm);
1167 start_mm = new_start_mm;
1169 if (shmem) {
1170 /* page has already been unlocked and released */
1171 if (shmem > 0)
1172 continue;
1173 retval = shmem;
1174 break;
1176 if (retval) {
1177 unlock_page(page);
1178 page_cache_release(page);
1179 break;
1183 * How could swap count reach 0x7ffe ?
1184 * There's no way to repeat a swap page within an mm
1185 * (except in shmem, where it's the shared object which takes
1186 * the reference count)?
1187 * We believe SWAP_MAP_MAX cannot occur.(if occur, unsigned
1188 * short is too small....)
1189 * If that's wrong, then we should worry more about
1190 * exit_mmap() and do_munmap() cases described above:
1191 * we might be resetting SWAP_MAP_MAX too early here.
1192 * We know "Undead"s can happen, they're okay, so don't
1193 * report them; but do report if we reset SWAP_MAP_MAX.
1195 /* We might release the lock_page() in unuse_mm(). */
1196 if (!PageSwapCache(page) || page_private(page) != entry.val)
1197 goto retry;
1199 if (swap_count(*swap_map) == SWAP_MAP_MAX) {
1200 spin_lock(&swap_lock);
1201 *swap_map = encode_swapmap(0, true);
1202 spin_unlock(&swap_lock);
1203 reset_overflow = 1;
1207 * If a reference remains (rare), we would like to leave
1208 * the page in the swap cache; but try_to_unmap could
1209 * then re-duplicate the entry once we drop page lock,
1210 * so we might loop indefinitely; also, that page could
1211 * not be swapped out to other storage meanwhile. So:
1212 * delete from cache even if there's another reference,
1213 * after ensuring that the data has been saved to disk -
1214 * since if the reference remains (rarer), it will be
1215 * read from disk into another page. Splitting into two
1216 * pages would be incorrect if swap supported "shared
1217 * private" pages, but they are handled by tmpfs files.
1219 if (swap_count(*swap_map) &&
1220 PageDirty(page) && PageSwapCache(page)) {
1221 struct writeback_control wbc = {
1222 .sync_mode = WB_SYNC_NONE,
1225 swap_writepage(page, &wbc);
1226 lock_page(page);
1227 wait_on_page_writeback(page);
1231 * It is conceivable that a racing task removed this page from
1232 * swap cache just before we acquired the page lock at the top,
1233 * or while we dropped it in unuse_mm(). The page might even
1234 * be back in swap cache on another swap area: that we must not
1235 * delete, since it may not have been written out to swap yet.
1237 if (PageSwapCache(page) &&
1238 likely(page_private(page) == entry.val))
1239 delete_from_swap_cache(page);
1242 * So we could skip searching mms once swap count went
1243 * to 1, we did not mark any present ptes as dirty: must
1244 * mark page dirty so shrink_page_list will preserve it.
1246 SetPageDirty(page);
1247 retry:
1248 unlock_page(page);
1249 page_cache_release(page);
1252 * Make sure that we aren't completely killing
1253 * interactive performance.
1255 cond_resched();
1258 mmput(start_mm);
1259 if (reset_overflow) {
1260 printk(KERN_WARNING "swapoff: cleared swap entry overflow\n");
1261 swap_overflow = 0;
1263 return retval;
1267 * After a successful try_to_unuse, if no swap is now in use, we know
1268 * we can empty the mmlist. swap_lock must be held on entry and exit.
1269 * Note that mmlist_lock nests inside swap_lock, and an mm must be
1270 * added to the mmlist just after page_duplicate - before would be racy.
1272 static void drain_mmlist(void)
1274 struct list_head *p, *next;
1275 unsigned int i;
1277 for (i = 0; i < nr_swapfiles; i++)
1278 if (swap_info[i].inuse_pages)
1279 return;
1280 spin_lock(&mmlist_lock);
1281 list_for_each_safe(p, next, &init_mm.mmlist)
1282 list_del_init(p);
1283 spin_unlock(&mmlist_lock);
1287 * Use this swapdev's extent info to locate the (PAGE_SIZE) block which
1288 * corresponds to page offset `offset'.
1290 sector_t map_swap_page(struct swap_info_struct *sis, pgoff_t offset)
1292 struct swap_extent *se = sis->curr_swap_extent;
1293 struct swap_extent *start_se = se;
1295 for ( ; ; ) {
1296 struct list_head *lh;
1298 if (se->start_page <= offset &&
1299 offset < (se->start_page + se->nr_pages)) {
1300 return se->start_block + (offset - se->start_page);
1302 lh = se->list.next;
1303 if (lh == &sis->extent_list)
1304 lh = lh->next;
1305 se = list_entry(lh, struct swap_extent, list);
1306 sis->curr_swap_extent = se;
1307 BUG_ON(se == start_se); /* It *must* be present */
1311 #ifdef CONFIG_HIBERNATION
1313 * Get the (PAGE_SIZE) block corresponding to given offset on the swapdev
1314 * corresponding to given index in swap_info (swap type).
1316 sector_t swapdev_block(int swap_type, pgoff_t offset)
1318 struct swap_info_struct *sis;
1320 if (swap_type >= nr_swapfiles)
1321 return 0;
1323 sis = swap_info + swap_type;
1324 return (sis->flags & SWP_WRITEOK) ? map_swap_page(sis, offset) : 0;
1326 #endif /* CONFIG_HIBERNATION */
1329 * Free all of a swapdev's extent information
1331 static void destroy_swap_extents(struct swap_info_struct *sis)
1333 while (!list_empty(&sis->extent_list)) {
1334 struct swap_extent *se;
1336 se = list_entry(sis->extent_list.next,
1337 struct swap_extent, list);
1338 list_del(&se->list);
1339 kfree(se);
1344 * Add a block range (and the corresponding page range) into this swapdev's
1345 * extent list. The extent list is kept sorted in page order.
1347 * This function rather assumes that it is called in ascending page order.
1349 static int
1350 add_swap_extent(struct swap_info_struct *sis, unsigned long start_page,
1351 unsigned long nr_pages, sector_t start_block)
1353 struct swap_extent *se;
1354 struct swap_extent *new_se;
1355 struct list_head *lh;
1357 lh = sis->extent_list.prev; /* The highest page extent */
1358 if (lh != &sis->extent_list) {
1359 se = list_entry(lh, struct swap_extent, list);
1360 BUG_ON(se->start_page + se->nr_pages != start_page);
1361 if (se->start_block + se->nr_pages == start_block) {
1362 /* Merge it */
1363 se->nr_pages += nr_pages;
1364 return 0;
1369 * No merge. Insert a new extent, preserving ordering.
1371 new_se = kmalloc(sizeof(*se), GFP_KERNEL);
1372 if (new_se == NULL)
1373 return -ENOMEM;
1374 new_se->start_page = start_page;
1375 new_se->nr_pages = nr_pages;
1376 new_se->start_block = start_block;
1378 list_add_tail(&new_se->list, &sis->extent_list);
1379 return 1;
1383 * A `swap extent' is a simple thing which maps a contiguous range of pages
1384 * onto a contiguous range of disk blocks. An ordered list of swap extents
1385 * is built at swapon time and is then used at swap_writepage/swap_readpage
1386 * time for locating where on disk a page belongs.
1388 * If the swapfile is an S_ISBLK block device, a single extent is installed.
1389 * This is done so that the main operating code can treat S_ISBLK and S_ISREG
1390 * swap files identically.
1392 * Whether the swapdev is an S_ISREG file or an S_ISBLK blockdev, the swap
1393 * extent list operates in PAGE_SIZE disk blocks. Both S_ISREG and S_ISBLK
1394 * swapfiles are handled *identically* after swapon time.
1396 * For S_ISREG swapfiles, setup_swap_extents() will walk all the file's blocks
1397 * and will parse them into an ordered extent list, in PAGE_SIZE chunks. If
1398 * some stray blocks are found which do not fall within the PAGE_SIZE alignment
1399 * requirements, they are simply tossed out - we will never use those blocks
1400 * for swapping.
1402 * For S_ISREG swapfiles we set S_SWAPFILE across the life of the swapon. This
1403 * prevents root from shooting her foot off by ftruncating an in-use swapfile,
1404 * which will scribble on the fs.
1406 * The amount of disk space which a single swap extent represents varies.
1407 * Typically it is in the 1-4 megabyte range. So we can have hundreds of
1408 * extents in the list. To avoid much list walking, we cache the previous
1409 * search location in `curr_swap_extent', and start new searches from there.
1410 * This is extremely effective. The average number of iterations in
1411 * map_swap_page() has been measured at about 0.3 per page. - akpm.
1413 static int setup_swap_extents(struct swap_info_struct *sis, sector_t *span)
1415 struct inode *inode;
1416 unsigned blocks_per_page;
1417 unsigned long page_no;
1418 unsigned blkbits;
1419 sector_t probe_block;
1420 sector_t last_block;
1421 sector_t lowest_block = -1;
1422 sector_t highest_block = 0;
1423 int nr_extents = 0;
1424 int ret;
1426 inode = sis->swap_file->f_mapping->host;
1427 if (S_ISBLK(inode->i_mode)) {
1428 ret = add_swap_extent(sis, 0, sis->max, 0);
1429 *span = sis->pages;
1430 goto done;
1433 blkbits = inode->i_blkbits;
1434 blocks_per_page = PAGE_SIZE >> blkbits;
1437 * Map all the blocks into the extent list. This code doesn't try
1438 * to be very smart.
1440 probe_block = 0;
1441 page_no = 0;
1442 last_block = i_size_read(inode) >> blkbits;
1443 while ((probe_block + blocks_per_page) <= last_block &&
1444 page_no < sis->max) {
1445 unsigned block_in_page;
1446 sector_t first_block;
1448 first_block = bmap(inode, probe_block);
1449 if (first_block == 0)
1450 goto bad_bmap;
1453 * It must be PAGE_SIZE aligned on-disk
1455 if (first_block & (blocks_per_page - 1)) {
1456 probe_block++;
1457 goto reprobe;
1460 for (block_in_page = 1; block_in_page < blocks_per_page;
1461 block_in_page++) {
1462 sector_t block;
1464 block = bmap(inode, probe_block + block_in_page);
1465 if (block == 0)
1466 goto bad_bmap;
1467 if (block != first_block + block_in_page) {
1468 /* Discontiguity */
1469 probe_block++;
1470 goto reprobe;
1474 first_block >>= (PAGE_SHIFT - blkbits);
1475 if (page_no) { /* exclude the header page */
1476 if (first_block < lowest_block)
1477 lowest_block = first_block;
1478 if (first_block > highest_block)
1479 highest_block = first_block;
1483 * We found a PAGE_SIZE-length, PAGE_SIZE-aligned run of blocks
1485 ret = add_swap_extent(sis, page_no, 1, first_block);
1486 if (ret < 0)
1487 goto out;
1488 nr_extents += ret;
1489 page_no++;
1490 probe_block += blocks_per_page;
1491 reprobe:
1492 continue;
1494 ret = nr_extents;
1495 *span = 1 + highest_block - lowest_block;
1496 if (page_no == 0)
1497 page_no = 1; /* force Empty message */
1498 sis->max = page_no;
1499 sis->pages = page_no - 1;
1500 sis->highest_bit = page_no - 1;
1501 done:
1502 sis->curr_swap_extent = list_entry(sis->extent_list.prev,
1503 struct swap_extent, list);
1504 goto out;
1505 bad_bmap:
1506 printk(KERN_ERR "swapon: swapfile has holes\n");
1507 ret = -EINVAL;
1508 out:
1509 return ret;
1512 SYSCALL_DEFINE1(swapoff, const char __user *, specialfile)
1514 struct swap_info_struct * p = NULL;
1515 unsigned short *swap_map;
1516 struct file *swap_file, *victim;
1517 struct address_space *mapping;
1518 struct inode *inode;
1519 char * pathname;
1520 int i, type, prev;
1521 int err;
1523 if (!capable(CAP_SYS_ADMIN))
1524 return -EPERM;
1526 pathname = getname(specialfile);
1527 err = PTR_ERR(pathname);
1528 if (IS_ERR(pathname))
1529 goto out;
1531 victim = filp_open(pathname, O_RDWR|O_LARGEFILE, 0);
1532 putname(pathname);
1533 err = PTR_ERR(victim);
1534 if (IS_ERR(victim))
1535 goto out;
1537 mapping = victim->f_mapping;
1538 prev = -1;
1539 spin_lock(&swap_lock);
1540 for (type = swap_list.head; type >= 0; type = swap_info[type].next) {
1541 p = swap_info + type;
1542 if (p->flags & SWP_WRITEOK) {
1543 if (p->swap_file->f_mapping == mapping)
1544 break;
1546 prev = type;
1548 if (type < 0) {
1549 err = -EINVAL;
1550 spin_unlock(&swap_lock);
1551 goto out_dput;
1553 if (!security_vm_enough_memory(p->pages))
1554 vm_unacct_memory(p->pages);
1555 else {
1556 err = -ENOMEM;
1557 spin_unlock(&swap_lock);
1558 goto out_dput;
1560 if (prev < 0) {
1561 swap_list.head = p->next;
1562 } else {
1563 swap_info[prev].next = p->next;
1565 if (type == swap_list.next) {
1566 /* just pick something that's safe... */
1567 swap_list.next = swap_list.head;
1569 if (p->prio < 0) {
1570 for (i = p->next; i >= 0; i = swap_info[i].next)
1571 swap_info[i].prio = p->prio--;
1572 least_priority++;
1574 nr_swap_pages -= p->pages;
1575 total_swap_pages -= p->pages;
1576 p->flags &= ~SWP_WRITEOK;
1577 spin_unlock(&swap_lock);
1579 current->flags |= PF_OOM_ORIGIN;
1580 err = try_to_unuse(type);
1581 current->flags &= ~PF_OOM_ORIGIN;
1583 if (err) {
1584 /* re-insert swap space back into swap_list */
1585 spin_lock(&swap_lock);
1586 if (p->prio < 0)
1587 p->prio = --least_priority;
1588 prev = -1;
1589 for (i = swap_list.head; i >= 0; i = swap_info[i].next) {
1590 if (p->prio >= swap_info[i].prio)
1591 break;
1592 prev = i;
1594 p->next = i;
1595 if (prev < 0)
1596 swap_list.head = swap_list.next = p - swap_info;
1597 else
1598 swap_info[prev].next = p - swap_info;
1599 nr_swap_pages += p->pages;
1600 total_swap_pages += p->pages;
1601 p->flags |= SWP_WRITEOK;
1602 spin_unlock(&swap_lock);
1603 goto out_dput;
1606 /* wait for any unplug function to finish */
1607 down_write(&swap_unplug_sem);
1608 up_write(&swap_unplug_sem);
1610 destroy_swap_extents(p);
1611 mutex_lock(&swapon_mutex);
1612 spin_lock(&swap_lock);
1613 drain_mmlist();
1615 /* wait for anyone still in scan_swap_map */
1616 p->highest_bit = 0; /* cuts scans short */
1617 while (p->flags >= SWP_SCANNING) {
1618 spin_unlock(&swap_lock);
1619 schedule_timeout_uninterruptible(1);
1620 spin_lock(&swap_lock);
1623 swap_file = p->swap_file;
1624 p->swap_file = NULL;
1625 p->max = 0;
1626 swap_map = p->swap_map;
1627 p->swap_map = NULL;
1628 p->flags = 0;
1629 spin_unlock(&swap_lock);
1630 mutex_unlock(&swapon_mutex);
1631 vfree(swap_map);
1632 /* Destroy swap account informatin */
1633 swap_cgroup_swapoff(type);
1635 inode = mapping->host;
1636 if (S_ISBLK(inode->i_mode)) {
1637 struct block_device *bdev = I_BDEV(inode);
1638 set_blocksize(bdev, p->old_block_size);
1639 bd_release(bdev);
1640 } else {
1641 mutex_lock(&inode->i_mutex);
1642 inode->i_flags &= ~S_SWAPFILE;
1643 mutex_unlock(&inode->i_mutex);
1645 filp_close(swap_file, NULL);
1646 err = 0;
1648 out_dput:
1649 filp_close(victim, NULL);
1650 out:
1651 return err;
1654 #ifdef CONFIG_PROC_FS
1655 /* iterator */
1656 static void *swap_start(struct seq_file *swap, loff_t *pos)
1658 struct swap_info_struct *ptr = swap_info;
1659 int i;
1660 loff_t l = *pos;
1662 mutex_lock(&swapon_mutex);
1664 if (!l)
1665 return SEQ_START_TOKEN;
1667 for (i = 0; i < nr_swapfiles; i++, ptr++) {
1668 if (!(ptr->flags & SWP_USED) || !ptr->swap_map)
1669 continue;
1670 if (!--l)
1671 return ptr;
1674 return NULL;
1677 static void *swap_next(struct seq_file *swap, void *v, loff_t *pos)
1679 struct swap_info_struct *ptr;
1680 struct swap_info_struct *endptr = swap_info + nr_swapfiles;
1682 if (v == SEQ_START_TOKEN)
1683 ptr = swap_info;
1684 else {
1685 ptr = v;
1686 ptr++;
1689 for (; ptr < endptr; ptr++) {
1690 if (!(ptr->flags & SWP_USED) || !ptr->swap_map)
1691 continue;
1692 ++*pos;
1693 return ptr;
1696 return NULL;
1699 static void swap_stop(struct seq_file *swap, void *v)
1701 mutex_unlock(&swapon_mutex);
1704 static int swap_show(struct seq_file *swap, void *v)
1706 struct swap_info_struct *ptr = v;
1707 struct file *file;
1708 int len;
1710 if (ptr == SEQ_START_TOKEN) {
1711 seq_puts(swap,"Filename\t\t\t\tType\t\tSize\tUsed\tPriority\n");
1712 return 0;
1715 file = ptr->swap_file;
1716 len = seq_path(swap, &file->f_path, " \t\n\\");
1717 seq_printf(swap, "%*s%s\t%u\t%u\t%d\n",
1718 len < 40 ? 40 - len : 1, " ",
1719 S_ISBLK(file->f_path.dentry->d_inode->i_mode) ?
1720 "partition" : "file\t",
1721 ptr->pages << (PAGE_SHIFT - 10),
1722 ptr->inuse_pages << (PAGE_SHIFT - 10),
1723 ptr->prio);
1724 return 0;
1727 static const struct seq_operations swaps_op = {
1728 .start = swap_start,
1729 .next = swap_next,
1730 .stop = swap_stop,
1731 .show = swap_show
1734 static int swaps_open(struct inode *inode, struct file *file)
1736 return seq_open(file, &swaps_op);
1739 static const struct file_operations proc_swaps_operations = {
1740 .open = swaps_open,
1741 .read = seq_read,
1742 .llseek = seq_lseek,
1743 .release = seq_release,
1746 static int __init procswaps_init(void)
1748 proc_create("swaps", 0, NULL, &proc_swaps_operations);
1749 return 0;
1751 __initcall(procswaps_init);
1752 #endif /* CONFIG_PROC_FS */
1754 #ifdef MAX_SWAPFILES_CHECK
1755 static int __init max_swapfiles_check(void)
1757 MAX_SWAPFILES_CHECK();
1758 return 0;
1760 late_initcall(max_swapfiles_check);
1761 #endif
1764 * Written 01/25/92 by Simmule Turner, heavily changed by Linus.
1766 * The swapon system call
1768 SYSCALL_DEFINE2(swapon, const char __user *, specialfile, int, swap_flags)
1770 struct swap_info_struct * p;
1771 char *name = NULL;
1772 struct block_device *bdev = NULL;
1773 struct file *swap_file = NULL;
1774 struct address_space *mapping;
1775 unsigned int type;
1776 int i, prev;
1777 int error;
1778 union swap_header *swap_header = NULL;
1779 unsigned int nr_good_pages = 0;
1780 int nr_extents = 0;
1781 sector_t span;
1782 unsigned long maxpages = 1;
1783 unsigned long swapfilepages;
1784 unsigned short *swap_map = NULL;
1785 struct page *page = NULL;
1786 struct inode *inode = NULL;
1787 int did_down = 0;
1789 if (!capable(CAP_SYS_ADMIN))
1790 return -EPERM;
1791 spin_lock(&swap_lock);
1792 p = swap_info;
1793 for (type = 0 ; type < nr_swapfiles ; type++,p++)
1794 if (!(p->flags & SWP_USED))
1795 break;
1796 error = -EPERM;
1797 if (type >= MAX_SWAPFILES) {
1798 spin_unlock(&swap_lock);
1799 goto out;
1801 if (type >= nr_swapfiles)
1802 nr_swapfiles = type+1;
1803 memset(p, 0, sizeof(*p));
1804 INIT_LIST_HEAD(&p->extent_list);
1805 p->flags = SWP_USED;
1806 p->next = -1;
1807 spin_unlock(&swap_lock);
1808 name = getname(specialfile);
1809 error = PTR_ERR(name);
1810 if (IS_ERR(name)) {
1811 name = NULL;
1812 goto bad_swap_2;
1814 swap_file = filp_open(name, O_RDWR|O_LARGEFILE, 0);
1815 error = PTR_ERR(swap_file);
1816 if (IS_ERR(swap_file)) {
1817 swap_file = NULL;
1818 goto bad_swap_2;
1821 p->swap_file = swap_file;
1822 mapping = swap_file->f_mapping;
1823 inode = mapping->host;
1825 error = -EBUSY;
1826 for (i = 0; i < nr_swapfiles; i++) {
1827 struct swap_info_struct *q = &swap_info[i];
1829 if (i == type || !q->swap_file)
1830 continue;
1831 if (mapping == q->swap_file->f_mapping)
1832 goto bad_swap;
1835 error = -EINVAL;
1836 if (S_ISBLK(inode->i_mode)) {
1837 bdev = I_BDEV(inode);
1838 error = bd_claim(bdev, sys_swapon);
1839 if (error < 0) {
1840 bdev = NULL;
1841 error = -EINVAL;
1842 goto bad_swap;
1844 p->old_block_size = block_size(bdev);
1845 error = set_blocksize(bdev, PAGE_SIZE);
1846 if (error < 0)
1847 goto bad_swap;
1848 p->bdev = bdev;
1849 } else if (S_ISREG(inode->i_mode)) {
1850 p->bdev = inode->i_sb->s_bdev;
1851 mutex_lock(&inode->i_mutex);
1852 did_down = 1;
1853 if (IS_SWAPFILE(inode)) {
1854 error = -EBUSY;
1855 goto bad_swap;
1857 } else {
1858 goto bad_swap;
1861 swapfilepages = i_size_read(inode) >> PAGE_SHIFT;
1864 * Read the swap header.
1866 if (!mapping->a_ops->readpage) {
1867 error = -EINVAL;
1868 goto bad_swap;
1870 page = read_mapping_page(mapping, 0, swap_file);
1871 if (IS_ERR(page)) {
1872 error = PTR_ERR(page);
1873 goto bad_swap;
1875 swap_header = kmap(page);
1877 if (memcmp("SWAPSPACE2", swap_header->magic.magic, 10)) {
1878 printk(KERN_ERR "Unable to find swap-space signature\n");
1879 error = -EINVAL;
1880 goto bad_swap;
1883 /* swap partition endianess hack... */
1884 if (swab32(swap_header->info.version) == 1) {
1885 swab32s(&swap_header->info.version);
1886 swab32s(&swap_header->info.last_page);
1887 swab32s(&swap_header->info.nr_badpages);
1888 for (i = 0; i < swap_header->info.nr_badpages; i++)
1889 swab32s(&swap_header->info.badpages[i]);
1891 /* Check the swap header's sub-version */
1892 if (swap_header->info.version != 1) {
1893 printk(KERN_WARNING
1894 "Unable to handle swap header version %d\n",
1895 swap_header->info.version);
1896 error = -EINVAL;
1897 goto bad_swap;
1900 p->lowest_bit = 1;
1901 p->cluster_next = 1;
1904 * Find out how many pages are allowed for a single swap
1905 * device. There are two limiting factors: 1) the number of
1906 * bits for the swap offset in the swp_entry_t type and
1907 * 2) the number of bits in the a swap pte as defined by
1908 * the different architectures. In order to find the
1909 * largest possible bit mask a swap entry with swap type 0
1910 * and swap offset ~0UL is created, encoded to a swap pte,
1911 * decoded to a swp_entry_t again and finally the swap
1912 * offset is extracted. This will mask all the bits from
1913 * the initial ~0UL mask that can't be encoded in either
1914 * the swp_entry_t or the architecture definition of a
1915 * swap pte.
1917 maxpages = swp_offset(pte_to_swp_entry(
1918 swp_entry_to_pte(swp_entry(0, ~0UL)))) - 1;
1919 if (maxpages > swap_header->info.last_page)
1920 maxpages = swap_header->info.last_page;
1921 p->highest_bit = maxpages - 1;
1923 error = -EINVAL;
1924 if (!maxpages)
1925 goto bad_swap;
1926 if (swapfilepages && maxpages > swapfilepages) {
1927 printk(KERN_WARNING
1928 "Swap area shorter than signature indicates\n");
1929 goto bad_swap;
1931 if (swap_header->info.nr_badpages && S_ISREG(inode->i_mode))
1932 goto bad_swap;
1933 if (swap_header->info.nr_badpages > MAX_SWAP_BADPAGES)
1934 goto bad_swap;
1936 /* OK, set up the swap map and apply the bad block list */
1937 swap_map = vmalloc(maxpages * sizeof(short));
1938 if (!swap_map) {
1939 error = -ENOMEM;
1940 goto bad_swap;
1943 memset(swap_map, 0, maxpages * sizeof(short));
1944 for (i = 0; i < swap_header->info.nr_badpages; i++) {
1945 int page_nr = swap_header->info.badpages[i];
1946 if (page_nr <= 0 || page_nr >= swap_header->info.last_page) {
1947 error = -EINVAL;
1948 goto bad_swap;
1950 swap_map[page_nr] = SWAP_MAP_BAD;
1953 error = swap_cgroup_swapon(type, maxpages);
1954 if (error)
1955 goto bad_swap;
1957 nr_good_pages = swap_header->info.last_page -
1958 swap_header->info.nr_badpages -
1959 1 /* header page */;
1961 if (nr_good_pages) {
1962 swap_map[0] = SWAP_MAP_BAD;
1963 p->max = maxpages;
1964 p->pages = nr_good_pages;
1965 nr_extents = setup_swap_extents(p, &span);
1966 if (nr_extents < 0) {
1967 error = nr_extents;
1968 goto bad_swap;
1970 nr_good_pages = p->pages;
1972 if (!nr_good_pages) {
1973 printk(KERN_WARNING "Empty swap-file\n");
1974 error = -EINVAL;
1975 goto bad_swap;
1978 if (p->bdev) {
1979 if (blk_queue_nonrot(bdev_get_queue(p->bdev))) {
1980 p->flags |= SWP_SOLIDSTATE;
1981 p->cluster_next = 1 + (random32() % p->highest_bit);
1983 if (discard_swap(p) == 0)
1984 p->flags |= SWP_DISCARDABLE;
1987 mutex_lock(&swapon_mutex);
1988 spin_lock(&swap_lock);
1989 if (swap_flags & SWAP_FLAG_PREFER)
1990 p->prio =
1991 (swap_flags & SWAP_FLAG_PRIO_MASK) >> SWAP_FLAG_PRIO_SHIFT;
1992 else
1993 p->prio = --least_priority;
1994 p->swap_map = swap_map;
1995 p->flags |= SWP_WRITEOK;
1996 nr_swap_pages += nr_good_pages;
1997 total_swap_pages += nr_good_pages;
1999 printk(KERN_INFO "Adding %uk swap on %s. "
2000 "Priority:%d extents:%d across:%lluk %s%s\n",
2001 nr_good_pages<<(PAGE_SHIFT-10), name, p->prio,
2002 nr_extents, (unsigned long long)span<<(PAGE_SHIFT-10),
2003 (p->flags & SWP_SOLIDSTATE) ? "SS" : "",
2004 (p->flags & SWP_DISCARDABLE) ? "D" : "");
2006 /* insert swap space into swap_list: */
2007 prev = -1;
2008 for (i = swap_list.head; i >= 0; i = swap_info[i].next) {
2009 if (p->prio >= swap_info[i].prio) {
2010 break;
2012 prev = i;
2014 p->next = i;
2015 if (prev < 0) {
2016 swap_list.head = swap_list.next = p - swap_info;
2017 } else {
2018 swap_info[prev].next = p - swap_info;
2020 spin_unlock(&swap_lock);
2021 mutex_unlock(&swapon_mutex);
2022 error = 0;
2023 goto out;
2024 bad_swap:
2025 if (bdev) {
2026 set_blocksize(bdev, p->old_block_size);
2027 bd_release(bdev);
2029 destroy_swap_extents(p);
2030 swap_cgroup_swapoff(type);
2031 bad_swap_2:
2032 spin_lock(&swap_lock);
2033 p->swap_file = NULL;
2034 p->flags = 0;
2035 spin_unlock(&swap_lock);
2036 vfree(swap_map);
2037 if (swap_file)
2038 filp_close(swap_file, NULL);
2039 out:
2040 if (page && !IS_ERR(page)) {
2041 kunmap(page);
2042 page_cache_release(page);
2044 if (name)
2045 putname(name);
2046 if (did_down) {
2047 if (!error)
2048 inode->i_flags |= S_SWAPFILE;
2049 mutex_unlock(&inode->i_mutex);
2051 return error;
2054 void si_swapinfo(struct sysinfo *val)
2056 unsigned int i;
2057 unsigned long nr_to_be_unused = 0;
2059 spin_lock(&swap_lock);
2060 for (i = 0; i < nr_swapfiles; i++) {
2061 if (!(swap_info[i].flags & SWP_USED) ||
2062 (swap_info[i].flags & SWP_WRITEOK))
2063 continue;
2064 nr_to_be_unused += swap_info[i].inuse_pages;
2066 val->freeswap = nr_swap_pages + nr_to_be_unused;
2067 val->totalswap = total_swap_pages + nr_to_be_unused;
2068 spin_unlock(&swap_lock);
2072 * Verify that a swap entry is valid and increment its swap map count.
2074 * Note: if swap_map[] reaches SWAP_MAP_MAX the entries are treated as
2075 * "permanent", but will be reclaimed by the next swapoff.
2076 * Returns error code in following case.
2077 * - success -> 0
2078 * - swp_entry is invalid -> EINVAL
2079 * - swp_entry is migration entry -> EINVAL
2080 * - swap-cache reference is requested but there is already one. -> EEXIST
2081 * - swap-cache reference is requested but the entry is not used. -> ENOENT
2083 static int __swap_duplicate(swp_entry_t entry, bool cache)
2085 struct swap_info_struct * p;
2086 unsigned long offset, type;
2087 int result = -EINVAL;
2088 int count;
2089 bool has_cache;
2091 if (non_swap_entry(entry))
2092 return -EINVAL;
2094 type = swp_type(entry);
2095 if (type >= nr_swapfiles)
2096 goto bad_file;
2097 p = type + swap_info;
2098 offset = swp_offset(entry);
2100 spin_lock(&swap_lock);
2102 if (unlikely(offset >= p->max))
2103 goto unlock_out;
2105 count = swap_count(p->swap_map[offset]);
2106 has_cache = swap_has_cache(p->swap_map[offset]);
2108 if (cache == SWAP_CACHE) { /* called for swapcache/swapin-readahead */
2110 /* set SWAP_HAS_CACHE if there is no cache and entry is used */
2111 if (!has_cache && count) {
2112 p->swap_map[offset] = encode_swapmap(count, true);
2113 result = 0;
2114 } else if (has_cache) /* someone added cache */
2115 result = -EEXIST;
2116 else if (!count) /* no users */
2117 result = -ENOENT;
2119 } else if (count || has_cache) {
2120 if (count < SWAP_MAP_MAX - 1) {
2121 p->swap_map[offset] = encode_swapmap(count + 1,
2122 has_cache);
2123 result = 0;
2124 } else if (count <= SWAP_MAP_MAX) {
2125 if (swap_overflow++ < 5)
2126 printk(KERN_WARNING
2127 "swap_dup: swap entry overflow\n");
2128 p->swap_map[offset] = encode_swapmap(SWAP_MAP_MAX,
2129 has_cache);
2130 result = 0;
2132 } else
2133 result = -ENOENT; /* unused swap entry */
2134 unlock_out:
2135 spin_unlock(&swap_lock);
2136 out:
2137 return result;
2139 bad_file:
2140 printk(KERN_ERR "swap_dup: %s%08lx\n", Bad_file, entry.val);
2141 goto out;
2144 * increase reference count of swap entry by 1.
2146 void swap_duplicate(swp_entry_t entry)
2148 __swap_duplicate(entry, SWAP_MAP);
2152 * @entry: swap entry for which we allocate swap cache.
2154 * Called when allocating swap cache for exising swap entry,
2155 * This can return error codes. Returns 0 at success.
2156 * -EBUSY means there is a swap cache.
2157 * Note: return code is different from swap_duplicate().
2159 int swapcache_prepare(swp_entry_t entry)
2161 return __swap_duplicate(entry, SWAP_CACHE);
2165 struct swap_info_struct *
2166 get_swap_info_struct(unsigned type)
2168 return &swap_info[type];
2172 * swap_lock prevents swap_map being freed. Don't grab an extra
2173 * reference on the swaphandle, it doesn't matter if it becomes unused.
2175 int valid_swaphandles(swp_entry_t entry, unsigned long *offset)
2177 struct swap_info_struct *si;
2178 int our_page_cluster = page_cluster;
2179 pgoff_t target, toff;
2180 pgoff_t base, end;
2181 int nr_pages = 0;
2183 if (!our_page_cluster) /* no readahead */
2184 return 0;
2186 si = &swap_info[swp_type(entry)];
2187 target = swp_offset(entry);
2188 base = (target >> our_page_cluster) << our_page_cluster;
2189 end = base + (1 << our_page_cluster);
2190 if (!base) /* first page is swap header */
2191 base++;
2193 spin_lock(&swap_lock);
2194 if (end > si->max) /* don't go beyond end of map */
2195 end = si->max;
2197 /* Count contiguous allocated slots above our target */
2198 for (toff = target; ++toff < end; nr_pages++) {
2199 /* Don't read in free or bad pages */
2200 if (!si->swap_map[toff])
2201 break;
2202 if (swap_count(si->swap_map[toff]) == SWAP_MAP_BAD)
2203 break;
2205 /* Count contiguous allocated slots below our target */
2206 for (toff = target; --toff >= base; nr_pages++) {
2207 /* Don't read in free or bad pages */
2208 if (!si->swap_map[toff])
2209 break;
2210 if (swap_count(si->swap_map[toff]) == SWAP_MAP_BAD)
2211 break;
2213 spin_unlock(&swap_lock);
2216 * Indicate starting offset, and return number of pages to get:
2217 * if only 1, say 0, since there's then no readahead to be done.
2219 *offset = ++toff;
2220 return nr_pages? ++nr_pages: 0;