e100/e1000*/igb*/ixgb*: Add missing read memory barrier
[linux-2.6/linux-acpi-2.6/ibm-acpi-2.6.git] / mm / swapfile.c
blobf08d165871b38cd658ffc366cdf3b39290b829da
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/ksm.h>
26 #include <linux/rmap.h>
27 #include <linux/security.h>
28 #include <linux/backing-dev.h>
29 #include <linux/mutex.h>
30 #include <linux/capability.h>
31 #include <linux/syscalls.h>
32 #include <linux/memcontrol.h>
34 #include <asm/pgtable.h>
35 #include <asm/tlbflush.h>
36 #include <linux/swapops.h>
37 #include <linux/page_cgroup.h>
39 static bool swap_count_continued(struct swap_info_struct *, pgoff_t,
40 unsigned char);
41 static void free_swap_count_continuations(struct swap_info_struct *);
42 static sector_t map_swap_entry(swp_entry_t, struct block_device**);
44 static DEFINE_SPINLOCK(swap_lock);
45 static unsigned int nr_swapfiles;
46 long nr_swap_pages;
47 long total_swap_pages;
48 static int least_priority;
50 static const char Bad_file[] = "Bad swap file entry ";
51 static const char Unused_file[] = "Unused swap file entry ";
52 static const char Bad_offset[] = "Bad swap offset entry ";
53 static const char Unused_offset[] = "Unused swap offset entry ";
55 static struct swap_list_t swap_list = {-1, -1};
57 static struct swap_info_struct *swap_info[MAX_SWAPFILES];
59 static DEFINE_MUTEX(swapon_mutex);
61 static inline unsigned char swap_count(unsigned char ent)
63 return ent & ~SWAP_HAS_CACHE; /* may include SWAP_HAS_CONT flag */
66 /* returns 1 if swap entry is freed */
67 static int
68 __try_to_reclaim_swap(struct swap_info_struct *si, unsigned long offset)
70 swp_entry_t entry = swp_entry(si->type, offset);
71 struct page *page;
72 int ret = 0;
74 page = find_get_page(&swapper_space, entry.val);
75 if (!page)
76 return 0;
78 * This function is called from scan_swap_map() and it's called
79 * by vmscan.c at reclaiming pages. So, we hold a lock on a page, here.
80 * We have to use trylock for avoiding deadlock. This is a special
81 * case and you should use try_to_free_swap() with explicit lock_page()
82 * in usual operations.
84 if (trylock_page(page)) {
85 ret = try_to_free_swap(page);
86 unlock_page(page);
88 page_cache_release(page);
89 return ret;
93 * We need this because the bdev->unplug_fn can sleep and we cannot
94 * hold swap_lock while calling the unplug_fn. And swap_lock
95 * cannot be turned into a mutex.
97 static DECLARE_RWSEM(swap_unplug_sem);
99 void swap_unplug_io_fn(struct backing_dev_info *unused_bdi, struct page *page)
101 swp_entry_t entry;
103 down_read(&swap_unplug_sem);
104 entry.val = page_private(page);
105 if (PageSwapCache(page)) {
106 struct block_device *bdev = swap_info[swp_type(entry)]->bdev;
107 struct backing_dev_info *bdi;
110 * If the page is removed from swapcache from under us (with a
111 * racy try_to_unuse/swapoff) we need an additional reference
112 * count to avoid reading garbage from page_private(page) above.
113 * If the WARN_ON triggers during a swapoff it maybe the race
114 * condition and it's harmless. However if it triggers without
115 * swapoff it signals a problem.
117 WARN_ON(page_count(page) <= 1);
119 bdi = bdev->bd_inode->i_mapping->backing_dev_info;
120 blk_run_backing_dev(bdi, page);
122 up_read(&swap_unplug_sem);
126 * swapon tell device that all the old swap contents can be discarded,
127 * to allow the swap device to optimize its wear-levelling.
129 static int discard_swap(struct swap_info_struct *si)
131 struct swap_extent *se;
132 sector_t start_block;
133 sector_t nr_blocks;
134 int err = 0;
136 /* Do not discard the swap header page! */
137 se = &si->first_swap_extent;
138 start_block = (se->start_block + 1) << (PAGE_SHIFT - 9);
139 nr_blocks = ((sector_t)se->nr_pages - 1) << (PAGE_SHIFT - 9);
140 if (nr_blocks) {
141 err = blkdev_issue_discard(si->bdev, start_block,
142 nr_blocks, GFP_KERNEL,
143 BLKDEV_IFL_WAIT | BLKDEV_IFL_BARRIER);
144 if (err)
145 return err;
146 cond_resched();
149 list_for_each_entry(se, &si->first_swap_extent.list, list) {
150 start_block = se->start_block << (PAGE_SHIFT - 9);
151 nr_blocks = (sector_t)se->nr_pages << (PAGE_SHIFT - 9);
153 err = blkdev_issue_discard(si->bdev, start_block,
154 nr_blocks, GFP_KERNEL,
155 BLKDEV_IFL_WAIT | BLKDEV_IFL_BARRIER);
156 if (err)
157 break;
159 cond_resched();
161 return err; /* That will often be -EOPNOTSUPP */
165 * swap allocation tell device that a cluster of swap can now be discarded,
166 * to allow the swap device to optimize its wear-levelling.
168 static void discard_swap_cluster(struct swap_info_struct *si,
169 pgoff_t start_page, pgoff_t nr_pages)
171 struct swap_extent *se = si->curr_swap_extent;
172 int found_extent = 0;
174 while (nr_pages) {
175 struct list_head *lh;
177 if (se->start_page <= start_page &&
178 start_page < se->start_page + se->nr_pages) {
179 pgoff_t offset = start_page - se->start_page;
180 sector_t start_block = se->start_block + offset;
181 sector_t nr_blocks = se->nr_pages - offset;
183 if (nr_blocks > nr_pages)
184 nr_blocks = nr_pages;
185 start_page += nr_blocks;
186 nr_pages -= nr_blocks;
188 if (!found_extent++)
189 si->curr_swap_extent = se;
191 start_block <<= PAGE_SHIFT - 9;
192 nr_blocks <<= PAGE_SHIFT - 9;
193 if (blkdev_issue_discard(si->bdev, start_block,
194 nr_blocks, GFP_NOIO, BLKDEV_IFL_WAIT |
195 BLKDEV_IFL_BARRIER))
196 break;
199 lh = se->list.next;
200 se = list_entry(lh, struct swap_extent, list);
204 static int wait_for_discard(void *word)
206 schedule();
207 return 0;
210 #define SWAPFILE_CLUSTER 256
211 #define LATENCY_LIMIT 256
213 static inline unsigned long scan_swap_map(struct swap_info_struct *si,
214 unsigned char usage)
216 unsigned long offset;
217 unsigned long scan_base;
218 unsigned long last_in_cluster = 0;
219 int latency_ration = LATENCY_LIMIT;
220 int found_free_cluster = 0;
223 * We try to cluster swap pages by allocating them sequentially
224 * in swap. Once we've allocated SWAPFILE_CLUSTER pages this
225 * way, however, we resort to first-free allocation, starting
226 * a new cluster. This prevents us from scattering swap pages
227 * all over the entire swap partition, so that we reduce
228 * overall disk seek times between swap pages. -- sct
229 * But we do now try to find an empty cluster. -Andrea
230 * And we let swap pages go all over an SSD partition. Hugh
233 si->flags += SWP_SCANNING;
234 scan_base = offset = si->cluster_next;
236 if (unlikely(!si->cluster_nr--)) {
237 if (si->pages - si->inuse_pages < SWAPFILE_CLUSTER) {
238 si->cluster_nr = SWAPFILE_CLUSTER - 1;
239 goto checks;
241 if (si->flags & SWP_DISCARDABLE) {
243 * Start range check on racing allocations, in case
244 * they overlap the cluster we eventually decide on
245 * (we scan without swap_lock to allow preemption).
246 * It's hardly conceivable that cluster_nr could be
247 * wrapped during our scan, but don't depend on it.
249 if (si->lowest_alloc)
250 goto checks;
251 si->lowest_alloc = si->max;
252 si->highest_alloc = 0;
254 spin_unlock(&swap_lock);
257 * If seek is expensive, start searching for new cluster from
258 * start of partition, to minimize the span of allocated swap.
259 * But if seek is cheap, search from our current position, so
260 * that swap is allocated from all over the partition: if the
261 * Flash Translation Layer only remaps within limited zones,
262 * we don't want to wear out the first zone too quickly.
264 if (!(si->flags & SWP_SOLIDSTATE))
265 scan_base = offset = si->lowest_bit;
266 last_in_cluster = offset + SWAPFILE_CLUSTER - 1;
268 /* Locate the first empty (unaligned) cluster */
269 for (; last_in_cluster <= si->highest_bit; offset++) {
270 if (si->swap_map[offset])
271 last_in_cluster = offset + SWAPFILE_CLUSTER;
272 else if (offset == last_in_cluster) {
273 spin_lock(&swap_lock);
274 offset -= SWAPFILE_CLUSTER - 1;
275 si->cluster_next = offset;
276 si->cluster_nr = SWAPFILE_CLUSTER - 1;
277 found_free_cluster = 1;
278 goto checks;
280 if (unlikely(--latency_ration < 0)) {
281 cond_resched();
282 latency_ration = LATENCY_LIMIT;
286 offset = si->lowest_bit;
287 last_in_cluster = offset + SWAPFILE_CLUSTER - 1;
289 /* Locate the first empty (unaligned) cluster */
290 for (; last_in_cluster < scan_base; offset++) {
291 if (si->swap_map[offset])
292 last_in_cluster = offset + SWAPFILE_CLUSTER;
293 else if (offset == last_in_cluster) {
294 spin_lock(&swap_lock);
295 offset -= SWAPFILE_CLUSTER - 1;
296 si->cluster_next = offset;
297 si->cluster_nr = SWAPFILE_CLUSTER - 1;
298 found_free_cluster = 1;
299 goto checks;
301 if (unlikely(--latency_ration < 0)) {
302 cond_resched();
303 latency_ration = LATENCY_LIMIT;
307 offset = scan_base;
308 spin_lock(&swap_lock);
309 si->cluster_nr = SWAPFILE_CLUSTER - 1;
310 si->lowest_alloc = 0;
313 checks:
314 if (!(si->flags & SWP_WRITEOK))
315 goto no_page;
316 if (!si->highest_bit)
317 goto no_page;
318 if (offset > si->highest_bit)
319 scan_base = offset = si->lowest_bit;
321 /* reuse swap entry of cache-only swap if not hibernation. */
322 if (vm_swap_full()
323 && usage == SWAP_HAS_CACHE
324 && si->swap_map[offset] == SWAP_HAS_CACHE) {
325 int swap_was_freed;
326 spin_unlock(&swap_lock);
327 swap_was_freed = __try_to_reclaim_swap(si, offset);
328 spin_lock(&swap_lock);
329 /* entry was freed successfully, try to use this again */
330 if (swap_was_freed)
331 goto checks;
332 goto scan; /* check next one */
335 if (si->swap_map[offset])
336 goto scan;
338 if (offset == si->lowest_bit)
339 si->lowest_bit++;
340 if (offset == si->highest_bit)
341 si->highest_bit--;
342 si->inuse_pages++;
343 if (si->inuse_pages == si->pages) {
344 si->lowest_bit = si->max;
345 si->highest_bit = 0;
347 si->swap_map[offset] = usage;
348 si->cluster_next = offset + 1;
349 si->flags -= SWP_SCANNING;
351 if (si->lowest_alloc) {
353 * Only set when SWP_DISCARDABLE, and there's a scan
354 * for a free cluster in progress or just completed.
356 if (found_free_cluster) {
358 * To optimize wear-levelling, discard the
359 * old data of the cluster, taking care not to
360 * discard any of its pages that have already
361 * been allocated by racing tasks (offset has
362 * already stepped over any at the beginning).
364 if (offset < si->highest_alloc &&
365 si->lowest_alloc <= last_in_cluster)
366 last_in_cluster = si->lowest_alloc - 1;
367 si->flags |= SWP_DISCARDING;
368 spin_unlock(&swap_lock);
370 if (offset < last_in_cluster)
371 discard_swap_cluster(si, offset,
372 last_in_cluster - offset + 1);
374 spin_lock(&swap_lock);
375 si->lowest_alloc = 0;
376 si->flags &= ~SWP_DISCARDING;
378 smp_mb(); /* wake_up_bit advises this */
379 wake_up_bit(&si->flags, ilog2(SWP_DISCARDING));
381 } else if (si->flags & SWP_DISCARDING) {
383 * Delay using pages allocated by racing tasks
384 * until the whole discard has been issued. We
385 * could defer that delay until swap_writepage,
386 * but it's easier to keep this self-contained.
388 spin_unlock(&swap_lock);
389 wait_on_bit(&si->flags, ilog2(SWP_DISCARDING),
390 wait_for_discard, TASK_UNINTERRUPTIBLE);
391 spin_lock(&swap_lock);
392 } else {
394 * Note pages allocated by racing tasks while
395 * scan for a free cluster is in progress, so
396 * that its final discard can exclude them.
398 if (offset < si->lowest_alloc)
399 si->lowest_alloc = offset;
400 if (offset > si->highest_alloc)
401 si->highest_alloc = offset;
404 return offset;
406 scan:
407 spin_unlock(&swap_lock);
408 while (++offset <= si->highest_bit) {
409 if (!si->swap_map[offset]) {
410 spin_lock(&swap_lock);
411 goto checks;
413 if (vm_swap_full() && si->swap_map[offset] == SWAP_HAS_CACHE) {
414 spin_lock(&swap_lock);
415 goto checks;
417 if (unlikely(--latency_ration < 0)) {
418 cond_resched();
419 latency_ration = LATENCY_LIMIT;
422 offset = si->lowest_bit;
423 while (++offset < scan_base) {
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 spin_lock(&swap_lock);
439 no_page:
440 si->flags -= SWP_SCANNING;
441 return 0;
444 swp_entry_t get_swap_page(void)
446 struct swap_info_struct *si;
447 pgoff_t offset;
448 int type, next;
449 int wrapped = 0;
451 spin_lock(&swap_lock);
452 if (nr_swap_pages <= 0)
453 goto noswap;
454 nr_swap_pages--;
456 for (type = swap_list.next; type >= 0 && wrapped < 2; type = next) {
457 si = swap_info[type];
458 next = si->next;
459 if (next < 0 ||
460 (!wrapped && si->prio != swap_info[next]->prio)) {
461 next = swap_list.head;
462 wrapped++;
465 if (!si->highest_bit)
466 continue;
467 if (!(si->flags & SWP_WRITEOK))
468 continue;
470 swap_list.next = next;
471 /* This is called for allocating swap entry for cache */
472 offset = scan_swap_map(si, SWAP_HAS_CACHE);
473 if (offset) {
474 spin_unlock(&swap_lock);
475 return swp_entry(type, offset);
477 next = swap_list.next;
480 nr_swap_pages++;
481 noswap:
482 spin_unlock(&swap_lock);
483 return (swp_entry_t) {0};
486 /* The only caller of this function is now susupend routine */
487 swp_entry_t get_swap_page_of_type(int type)
489 struct swap_info_struct *si;
490 pgoff_t offset;
492 spin_lock(&swap_lock);
493 si = swap_info[type];
494 if (si && (si->flags & SWP_WRITEOK)) {
495 nr_swap_pages--;
496 /* This is called for allocating swap entry, not cache */
497 offset = scan_swap_map(si, 1);
498 if (offset) {
499 spin_unlock(&swap_lock);
500 return swp_entry(type, offset);
502 nr_swap_pages++;
504 spin_unlock(&swap_lock);
505 return (swp_entry_t) {0};
508 static struct swap_info_struct *swap_info_get(swp_entry_t entry)
510 struct swap_info_struct *p;
511 unsigned long offset, type;
513 if (!entry.val)
514 goto out;
515 type = swp_type(entry);
516 if (type >= nr_swapfiles)
517 goto bad_nofile;
518 p = swap_info[type];
519 if (!(p->flags & SWP_USED))
520 goto bad_device;
521 offset = swp_offset(entry);
522 if (offset >= p->max)
523 goto bad_offset;
524 if (!p->swap_map[offset])
525 goto bad_free;
526 spin_lock(&swap_lock);
527 return p;
529 bad_free:
530 printk(KERN_ERR "swap_free: %s%08lx\n", Unused_offset, entry.val);
531 goto out;
532 bad_offset:
533 printk(KERN_ERR "swap_free: %s%08lx\n", Bad_offset, entry.val);
534 goto out;
535 bad_device:
536 printk(KERN_ERR "swap_free: %s%08lx\n", Unused_file, entry.val);
537 goto out;
538 bad_nofile:
539 printk(KERN_ERR "swap_free: %s%08lx\n", Bad_file, entry.val);
540 out:
541 return NULL;
544 static unsigned char swap_entry_free(struct swap_info_struct *p,
545 swp_entry_t entry, unsigned char usage)
547 unsigned long offset = swp_offset(entry);
548 unsigned char count;
549 unsigned char has_cache;
551 count = p->swap_map[offset];
552 has_cache = count & SWAP_HAS_CACHE;
553 count &= ~SWAP_HAS_CACHE;
555 if (usage == SWAP_HAS_CACHE) {
556 VM_BUG_ON(!has_cache);
557 has_cache = 0;
558 } else if (count == SWAP_MAP_SHMEM) {
560 * Or we could insist on shmem.c using a special
561 * swap_shmem_free() and free_shmem_swap_and_cache()...
563 count = 0;
564 } else if ((count & ~COUNT_CONTINUED) <= SWAP_MAP_MAX) {
565 if (count == COUNT_CONTINUED) {
566 if (swap_count_continued(p, offset, count))
567 count = SWAP_MAP_MAX | COUNT_CONTINUED;
568 else
569 count = SWAP_MAP_MAX;
570 } else
571 count--;
574 if (!count)
575 mem_cgroup_uncharge_swap(entry);
577 usage = count | has_cache;
578 p->swap_map[offset] = usage;
580 /* free if no reference */
581 if (!usage) {
582 struct gendisk *disk = p->bdev->bd_disk;
583 if (offset < p->lowest_bit)
584 p->lowest_bit = offset;
585 if (offset > p->highest_bit)
586 p->highest_bit = offset;
587 if (swap_list.next >= 0 &&
588 p->prio > swap_info[swap_list.next]->prio)
589 swap_list.next = p->type;
590 nr_swap_pages++;
591 p->inuse_pages--;
592 if ((p->flags & SWP_BLKDEV) &&
593 disk->fops->swap_slot_free_notify)
594 disk->fops->swap_slot_free_notify(p->bdev, offset);
597 return usage;
601 * Caller has made sure that the swapdevice corresponding to entry
602 * is still around or has not been recycled.
604 void swap_free(swp_entry_t entry)
606 struct swap_info_struct *p;
608 p = swap_info_get(entry);
609 if (p) {
610 swap_entry_free(p, entry, 1);
611 spin_unlock(&swap_lock);
616 * Called after dropping swapcache to decrease refcnt to swap entries.
618 void swapcache_free(swp_entry_t entry, struct page *page)
620 struct swap_info_struct *p;
621 unsigned char count;
623 p = swap_info_get(entry);
624 if (p) {
625 count = swap_entry_free(p, entry, SWAP_HAS_CACHE);
626 if (page)
627 mem_cgroup_uncharge_swapcache(page, entry, count != 0);
628 spin_unlock(&swap_lock);
633 * How many references to page are currently swapped out?
634 * This does not give an exact answer when swap count is continued,
635 * but does include the high COUNT_CONTINUED flag to allow for that.
637 static inline int page_swapcount(struct page *page)
639 int count = 0;
640 struct swap_info_struct *p;
641 swp_entry_t entry;
643 entry.val = page_private(page);
644 p = swap_info_get(entry);
645 if (p) {
646 count = swap_count(p->swap_map[swp_offset(entry)]);
647 spin_unlock(&swap_lock);
649 return count;
653 * We can write to an anon page without COW if there are no other references
654 * to it. And as a side-effect, free up its swap: because the old content
655 * on disk will never be read, and seeking back there to write new content
656 * later would only waste time away from clustering.
658 int reuse_swap_page(struct page *page)
660 int count;
662 VM_BUG_ON(!PageLocked(page));
663 if (unlikely(PageKsm(page)))
664 return 0;
665 count = page_mapcount(page);
666 if (count <= 1 && PageSwapCache(page)) {
667 count += page_swapcount(page);
668 if (count == 1 && !PageWriteback(page)) {
669 delete_from_swap_cache(page);
670 SetPageDirty(page);
673 return count <= 1;
677 * If swap is getting full, or if there are no more mappings of this page,
678 * then try_to_free_swap is called to free its swap space.
680 int try_to_free_swap(struct page *page)
682 VM_BUG_ON(!PageLocked(page));
684 if (!PageSwapCache(page))
685 return 0;
686 if (PageWriteback(page))
687 return 0;
688 if (page_swapcount(page))
689 return 0;
691 delete_from_swap_cache(page);
692 SetPageDirty(page);
693 return 1;
697 * Free the swap entry like above, but also try to
698 * free the page cache entry if it is the last user.
700 int free_swap_and_cache(swp_entry_t entry)
702 struct swap_info_struct *p;
703 struct page *page = NULL;
705 if (non_swap_entry(entry))
706 return 1;
708 p = swap_info_get(entry);
709 if (p) {
710 if (swap_entry_free(p, entry, 1) == SWAP_HAS_CACHE) {
711 page = find_get_page(&swapper_space, entry.val);
712 if (page && !trylock_page(page)) {
713 page_cache_release(page);
714 page = NULL;
717 spin_unlock(&swap_lock);
719 if (page) {
721 * Not mapped elsewhere, or swap space full? Free it!
722 * Also recheck PageSwapCache now page is locked (above).
724 if (PageSwapCache(page) && !PageWriteback(page) &&
725 (!page_mapped(page) || vm_swap_full())) {
726 delete_from_swap_cache(page);
727 SetPageDirty(page);
729 unlock_page(page);
730 page_cache_release(page);
732 return p != NULL;
735 #ifdef CONFIG_CGROUP_MEM_RES_CTLR
737 * mem_cgroup_count_swap_user - count the user of a swap entry
738 * @ent: the swap entry to be checked
739 * @pagep: the pointer for the swap cache page of the entry to be stored
741 * Returns the number of the user of the swap entry. The number is valid only
742 * for swaps of anonymous pages.
743 * If the entry is found on swap cache, the page is stored to pagep with
744 * refcount of it being incremented.
746 int mem_cgroup_count_swap_user(swp_entry_t ent, struct page **pagep)
748 struct page *page;
749 struct swap_info_struct *p;
750 int count = 0;
752 page = find_get_page(&swapper_space, ent.val);
753 if (page)
754 count += page_mapcount(page);
755 p = swap_info_get(ent);
756 if (p) {
757 count += swap_count(p->swap_map[swp_offset(ent)]);
758 spin_unlock(&swap_lock);
761 *pagep = page;
762 return count;
764 #endif
766 #ifdef CONFIG_HIBERNATION
768 * Find the swap type that corresponds to given device (if any).
770 * @offset - number of the PAGE_SIZE-sized block of the device, starting
771 * from 0, in which the swap header is expected to be located.
773 * This is needed for the suspend to disk (aka swsusp).
775 int swap_type_of(dev_t device, sector_t offset, struct block_device **bdev_p)
777 struct block_device *bdev = NULL;
778 int type;
780 if (device)
781 bdev = bdget(device);
783 spin_lock(&swap_lock);
784 for (type = 0; type < nr_swapfiles; type++) {
785 struct swap_info_struct *sis = swap_info[type];
787 if (!(sis->flags & SWP_WRITEOK))
788 continue;
790 if (!bdev) {
791 if (bdev_p)
792 *bdev_p = bdgrab(sis->bdev);
794 spin_unlock(&swap_lock);
795 return type;
797 if (bdev == sis->bdev) {
798 struct swap_extent *se = &sis->first_swap_extent;
800 if (se->start_block == offset) {
801 if (bdev_p)
802 *bdev_p = bdgrab(sis->bdev);
804 spin_unlock(&swap_lock);
805 bdput(bdev);
806 return type;
810 spin_unlock(&swap_lock);
811 if (bdev)
812 bdput(bdev);
814 return -ENODEV;
818 * Get the (PAGE_SIZE) block corresponding to given offset on the swapdev
819 * corresponding to given index in swap_info (swap type).
821 sector_t swapdev_block(int type, pgoff_t offset)
823 struct block_device *bdev;
825 if ((unsigned int)type >= nr_swapfiles)
826 return 0;
827 if (!(swap_info[type]->flags & SWP_WRITEOK))
828 return 0;
829 return map_swap_entry(swp_entry(type, offset), &bdev);
833 * Return either the total number of swap pages of given type, or the number
834 * of free pages of that type (depending on @free)
836 * This is needed for software suspend
838 unsigned int count_swap_pages(int type, int free)
840 unsigned int n = 0;
842 spin_lock(&swap_lock);
843 if ((unsigned int)type < nr_swapfiles) {
844 struct swap_info_struct *sis = swap_info[type];
846 if (sis->flags & SWP_WRITEOK) {
847 n = sis->pages;
848 if (free)
849 n -= sis->inuse_pages;
852 spin_unlock(&swap_lock);
853 return n;
855 #endif /* CONFIG_HIBERNATION */
858 * No need to decide whether this PTE shares the swap entry with others,
859 * just let do_wp_page work it out if a write is requested later - to
860 * force COW, vm_page_prot omits write permission from any private vma.
862 static int unuse_pte(struct vm_area_struct *vma, pmd_t *pmd,
863 unsigned long addr, swp_entry_t entry, struct page *page)
865 struct mem_cgroup *ptr = NULL;
866 spinlock_t *ptl;
867 pte_t *pte;
868 int ret = 1;
870 if (mem_cgroup_try_charge_swapin(vma->vm_mm, page, GFP_KERNEL, &ptr)) {
871 ret = -ENOMEM;
872 goto out_nolock;
875 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
876 if (unlikely(!pte_same(*pte, swp_entry_to_pte(entry)))) {
877 if (ret > 0)
878 mem_cgroup_cancel_charge_swapin(ptr);
879 ret = 0;
880 goto out;
883 dec_mm_counter(vma->vm_mm, MM_SWAPENTS);
884 inc_mm_counter(vma->vm_mm, MM_ANONPAGES);
885 get_page(page);
886 set_pte_at(vma->vm_mm, addr, pte,
887 pte_mkold(mk_pte(page, vma->vm_page_prot)));
888 page_add_anon_rmap(page, vma, addr);
889 mem_cgroup_commit_charge_swapin(page, ptr);
890 swap_free(entry);
892 * Move the page to the active list so it is not
893 * immediately swapped out again after swapon.
895 activate_page(page);
896 out:
897 pte_unmap_unlock(pte, ptl);
898 out_nolock:
899 return ret;
902 static int unuse_pte_range(struct vm_area_struct *vma, pmd_t *pmd,
903 unsigned long addr, unsigned long end,
904 swp_entry_t entry, struct page *page)
906 pte_t swp_pte = swp_entry_to_pte(entry);
907 pte_t *pte;
908 int ret = 0;
911 * We don't actually need pte lock while scanning for swp_pte: since
912 * we hold page lock and mmap_sem, swp_pte cannot be inserted into the
913 * page table while we're scanning; though it could get zapped, and on
914 * some architectures (e.g. x86_32 with PAE) we might catch a glimpse
915 * of unmatched parts which look like swp_pte, so unuse_pte must
916 * recheck under pte lock. Scanning without pte lock lets it be
917 * preemptible whenever CONFIG_PREEMPT but not CONFIG_HIGHPTE.
919 pte = pte_offset_map(pmd, addr);
920 do {
922 * swapoff spends a _lot_ of time in this loop!
923 * Test inline before going to call unuse_pte.
925 if (unlikely(pte_same(*pte, swp_pte))) {
926 pte_unmap(pte);
927 ret = unuse_pte(vma, pmd, addr, entry, page);
928 if (ret)
929 goto out;
930 pte = pte_offset_map(pmd, addr);
932 } while (pte++, addr += PAGE_SIZE, addr != end);
933 pte_unmap(pte - 1);
934 out:
935 return ret;
938 static inline int unuse_pmd_range(struct vm_area_struct *vma, pud_t *pud,
939 unsigned long addr, unsigned long end,
940 swp_entry_t entry, struct page *page)
942 pmd_t *pmd;
943 unsigned long next;
944 int ret;
946 pmd = pmd_offset(pud, addr);
947 do {
948 next = pmd_addr_end(addr, end);
949 if (pmd_none_or_clear_bad(pmd))
950 continue;
951 ret = unuse_pte_range(vma, pmd, addr, next, entry, page);
952 if (ret)
953 return ret;
954 } while (pmd++, addr = next, addr != end);
955 return 0;
958 static inline int unuse_pud_range(struct vm_area_struct *vma, pgd_t *pgd,
959 unsigned long addr, unsigned long end,
960 swp_entry_t entry, struct page *page)
962 pud_t *pud;
963 unsigned long next;
964 int ret;
966 pud = pud_offset(pgd, addr);
967 do {
968 next = pud_addr_end(addr, end);
969 if (pud_none_or_clear_bad(pud))
970 continue;
971 ret = unuse_pmd_range(vma, pud, addr, next, entry, page);
972 if (ret)
973 return ret;
974 } while (pud++, addr = next, addr != end);
975 return 0;
978 static int unuse_vma(struct vm_area_struct *vma,
979 swp_entry_t entry, struct page *page)
981 pgd_t *pgd;
982 unsigned long addr, end, next;
983 int ret;
985 if (page_anon_vma(page)) {
986 addr = page_address_in_vma(page, vma);
987 if (addr == -EFAULT)
988 return 0;
989 else
990 end = addr + PAGE_SIZE;
991 } else {
992 addr = vma->vm_start;
993 end = vma->vm_end;
996 pgd = pgd_offset(vma->vm_mm, addr);
997 do {
998 next = pgd_addr_end(addr, end);
999 if (pgd_none_or_clear_bad(pgd))
1000 continue;
1001 ret = unuse_pud_range(vma, pgd, addr, next, entry, page);
1002 if (ret)
1003 return ret;
1004 } while (pgd++, addr = next, addr != end);
1005 return 0;
1008 static int unuse_mm(struct mm_struct *mm,
1009 swp_entry_t entry, struct page *page)
1011 struct vm_area_struct *vma;
1012 int ret = 0;
1014 if (!down_read_trylock(&mm->mmap_sem)) {
1016 * Activate page so shrink_inactive_list is unlikely to unmap
1017 * its ptes while lock is dropped, so swapoff can make progress.
1019 activate_page(page);
1020 unlock_page(page);
1021 down_read(&mm->mmap_sem);
1022 lock_page(page);
1024 for (vma = mm->mmap; vma; vma = vma->vm_next) {
1025 if (vma->anon_vma && (ret = unuse_vma(vma, entry, page)))
1026 break;
1028 up_read(&mm->mmap_sem);
1029 return (ret < 0)? ret: 0;
1033 * Scan swap_map from current position to next entry still in use.
1034 * Recycle to start on reaching the end, returning 0 when empty.
1036 static unsigned int find_next_to_unuse(struct swap_info_struct *si,
1037 unsigned int prev)
1039 unsigned int max = si->max;
1040 unsigned int i = prev;
1041 unsigned char count;
1044 * No need for swap_lock here: we're just looking
1045 * for whether an entry is in use, not modifying it; false
1046 * hits are okay, and sys_swapoff() has already prevented new
1047 * allocations from this area (while holding swap_lock).
1049 for (;;) {
1050 if (++i >= max) {
1051 if (!prev) {
1052 i = 0;
1053 break;
1056 * No entries in use at top of swap_map,
1057 * loop back to start and recheck there.
1059 max = prev + 1;
1060 prev = 0;
1061 i = 1;
1063 count = si->swap_map[i];
1064 if (count && swap_count(count) != SWAP_MAP_BAD)
1065 break;
1067 return i;
1071 * We completely avoid races by reading each swap page in advance,
1072 * and then search for the process using it. All the necessary
1073 * page table adjustments can then be made atomically.
1075 static int try_to_unuse(unsigned int type)
1077 struct swap_info_struct *si = swap_info[type];
1078 struct mm_struct *start_mm;
1079 unsigned char *swap_map;
1080 unsigned char swcount;
1081 struct page *page;
1082 swp_entry_t entry;
1083 unsigned int i = 0;
1084 int retval = 0;
1087 * When searching mms for an entry, a good strategy is to
1088 * start at the first mm we freed the previous entry from
1089 * (though actually we don't notice whether we or coincidence
1090 * freed the entry). Initialize this start_mm with a hold.
1092 * A simpler strategy would be to start at the last mm we
1093 * freed the previous entry from; but that would take less
1094 * advantage of mmlist ordering, which clusters forked mms
1095 * together, child after parent. If we race with dup_mmap(), we
1096 * prefer to resolve parent before child, lest we miss entries
1097 * duplicated after we scanned child: using last mm would invert
1098 * that.
1100 start_mm = &init_mm;
1101 atomic_inc(&init_mm.mm_users);
1104 * Keep on scanning until all entries have gone. Usually,
1105 * one pass through swap_map is enough, but not necessarily:
1106 * there are races when an instance of an entry might be missed.
1108 while ((i = find_next_to_unuse(si, i)) != 0) {
1109 if (signal_pending(current)) {
1110 retval = -EINTR;
1111 break;
1115 * Get a page for the entry, using the existing swap
1116 * cache page if there is one. Otherwise, get a clean
1117 * page and read the swap into it.
1119 swap_map = &si->swap_map[i];
1120 entry = swp_entry(type, i);
1121 page = read_swap_cache_async(entry,
1122 GFP_HIGHUSER_MOVABLE, NULL, 0);
1123 if (!page) {
1125 * Either swap_duplicate() failed because entry
1126 * has been freed independently, and will not be
1127 * reused since sys_swapoff() already disabled
1128 * allocation from here, or alloc_page() failed.
1130 if (!*swap_map)
1131 continue;
1132 retval = -ENOMEM;
1133 break;
1137 * Don't hold on to start_mm if it looks like exiting.
1139 if (atomic_read(&start_mm->mm_users) == 1) {
1140 mmput(start_mm);
1141 start_mm = &init_mm;
1142 atomic_inc(&init_mm.mm_users);
1146 * Wait for and lock page. When do_swap_page races with
1147 * try_to_unuse, do_swap_page can handle the fault much
1148 * faster than try_to_unuse can locate the entry. This
1149 * apparently redundant "wait_on_page_locked" lets try_to_unuse
1150 * defer to do_swap_page in such a case - in some tests,
1151 * do_swap_page and try_to_unuse repeatedly compete.
1153 wait_on_page_locked(page);
1154 wait_on_page_writeback(page);
1155 lock_page(page);
1156 wait_on_page_writeback(page);
1159 * Remove all references to entry.
1161 swcount = *swap_map;
1162 if (swap_count(swcount) == SWAP_MAP_SHMEM) {
1163 retval = shmem_unuse(entry, page);
1164 /* page has already been unlocked and released */
1165 if (retval < 0)
1166 break;
1167 continue;
1169 if (swap_count(swcount) && start_mm != &init_mm)
1170 retval = unuse_mm(start_mm, entry, page);
1172 if (swap_count(*swap_map)) {
1173 int set_start_mm = (*swap_map >= swcount);
1174 struct list_head *p = &start_mm->mmlist;
1175 struct mm_struct *new_start_mm = start_mm;
1176 struct mm_struct *prev_mm = start_mm;
1177 struct mm_struct *mm;
1179 atomic_inc(&new_start_mm->mm_users);
1180 atomic_inc(&prev_mm->mm_users);
1181 spin_lock(&mmlist_lock);
1182 while (swap_count(*swap_map) && !retval &&
1183 (p = p->next) != &start_mm->mmlist) {
1184 mm = list_entry(p, struct mm_struct, mmlist);
1185 if (!atomic_inc_not_zero(&mm->mm_users))
1186 continue;
1187 spin_unlock(&mmlist_lock);
1188 mmput(prev_mm);
1189 prev_mm = mm;
1191 cond_resched();
1193 swcount = *swap_map;
1194 if (!swap_count(swcount)) /* any usage ? */
1196 else if (mm == &init_mm)
1197 set_start_mm = 1;
1198 else
1199 retval = unuse_mm(mm, entry, page);
1201 if (set_start_mm && *swap_map < swcount) {
1202 mmput(new_start_mm);
1203 atomic_inc(&mm->mm_users);
1204 new_start_mm = mm;
1205 set_start_mm = 0;
1207 spin_lock(&mmlist_lock);
1209 spin_unlock(&mmlist_lock);
1210 mmput(prev_mm);
1211 mmput(start_mm);
1212 start_mm = new_start_mm;
1214 if (retval) {
1215 unlock_page(page);
1216 page_cache_release(page);
1217 break;
1221 * If a reference remains (rare), we would like to leave
1222 * the page in the swap cache; but try_to_unmap could
1223 * then re-duplicate the entry once we drop page lock,
1224 * so we might loop indefinitely; also, that page could
1225 * not be swapped out to other storage meanwhile. So:
1226 * delete from cache even if there's another reference,
1227 * after ensuring that the data has been saved to disk -
1228 * since if the reference remains (rarer), it will be
1229 * read from disk into another page. Splitting into two
1230 * pages would be incorrect if swap supported "shared
1231 * private" pages, but they are handled by tmpfs files.
1233 * Given how unuse_vma() targets one particular offset
1234 * in an anon_vma, once the anon_vma has been determined,
1235 * this splitting happens to be just what is needed to
1236 * handle where KSM pages have been swapped out: re-reading
1237 * is unnecessarily slow, but we can fix that later on.
1239 if (swap_count(*swap_map) &&
1240 PageDirty(page) && PageSwapCache(page)) {
1241 struct writeback_control wbc = {
1242 .sync_mode = WB_SYNC_NONE,
1245 swap_writepage(page, &wbc);
1246 lock_page(page);
1247 wait_on_page_writeback(page);
1251 * It is conceivable that a racing task removed this page from
1252 * swap cache just before we acquired the page lock at the top,
1253 * or while we dropped it in unuse_mm(). The page might even
1254 * be back in swap cache on another swap area: that we must not
1255 * delete, since it may not have been written out to swap yet.
1257 if (PageSwapCache(page) &&
1258 likely(page_private(page) == entry.val))
1259 delete_from_swap_cache(page);
1262 * So we could skip searching mms once swap count went
1263 * to 1, we did not mark any present ptes as dirty: must
1264 * mark page dirty so shrink_page_list will preserve it.
1266 SetPageDirty(page);
1267 unlock_page(page);
1268 page_cache_release(page);
1271 * Make sure that we aren't completely killing
1272 * interactive performance.
1274 cond_resched();
1277 mmput(start_mm);
1278 return retval;
1282 * After a successful try_to_unuse, if no swap is now in use, we know
1283 * we can empty the mmlist. swap_lock must be held on entry and exit.
1284 * Note that mmlist_lock nests inside swap_lock, and an mm must be
1285 * added to the mmlist just after page_duplicate - before would be racy.
1287 static void drain_mmlist(void)
1289 struct list_head *p, *next;
1290 unsigned int type;
1292 for (type = 0; type < nr_swapfiles; type++)
1293 if (swap_info[type]->inuse_pages)
1294 return;
1295 spin_lock(&mmlist_lock);
1296 list_for_each_safe(p, next, &init_mm.mmlist)
1297 list_del_init(p);
1298 spin_unlock(&mmlist_lock);
1302 * Use this swapdev's extent info to locate the (PAGE_SIZE) block which
1303 * corresponds to page offset for the specified swap entry.
1304 * Note that the type of this function is sector_t, but it returns page offset
1305 * into the bdev, not sector offset.
1307 static sector_t map_swap_entry(swp_entry_t entry, struct block_device **bdev)
1309 struct swap_info_struct *sis;
1310 struct swap_extent *start_se;
1311 struct swap_extent *se;
1312 pgoff_t offset;
1314 sis = swap_info[swp_type(entry)];
1315 *bdev = sis->bdev;
1317 offset = swp_offset(entry);
1318 start_se = sis->curr_swap_extent;
1319 se = start_se;
1321 for ( ; ; ) {
1322 struct list_head *lh;
1324 if (se->start_page <= offset &&
1325 offset < (se->start_page + se->nr_pages)) {
1326 return se->start_block + (offset - se->start_page);
1328 lh = se->list.next;
1329 se = list_entry(lh, struct swap_extent, list);
1330 sis->curr_swap_extent = se;
1331 BUG_ON(se == start_se); /* It *must* be present */
1336 * Returns the page offset into bdev for the specified page's swap entry.
1338 sector_t map_swap_page(struct page *page, struct block_device **bdev)
1340 swp_entry_t entry;
1341 entry.val = page_private(page);
1342 return map_swap_entry(entry, bdev);
1346 * Free all of a swapdev's extent information
1348 static void destroy_swap_extents(struct swap_info_struct *sis)
1350 while (!list_empty(&sis->first_swap_extent.list)) {
1351 struct swap_extent *se;
1353 se = list_entry(sis->first_swap_extent.list.next,
1354 struct swap_extent, list);
1355 list_del(&se->list);
1356 kfree(se);
1361 * Add a block range (and the corresponding page range) into this swapdev's
1362 * extent list. The extent list is kept sorted in page order.
1364 * This function rather assumes that it is called in ascending page order.
1366 static int
1367 add_swap_extent(struct swap_info_struct *sis, unsigned long start_page,
1368 unsigned long nr_pages, sector_t start_block)
1370 struct swap_extent *se;
1371 struct swap_extent *new_se;
1372 struct list_head *lh;
1374 if (start_page == 0) {
1375 se = &sis->first_swap_extent;
1376 sis->curr_swap_extent = se;
1377 se->start_page = 0;
1378 se->nr_pages = nr_pages;
1379 se->start_block = start_block;
1380 return 1;
1381 } else {
1382 lh = sis->first_swap_extent.list.prev; /* Highest extent */
1383 se = list_entry(lh, struct swap_extent, list);
1384 BUG_ON(se->start_page + se->nr_pages != start_page);
1385 if (se->start_block + se->nr_pages == start_block) {
1386 /* Merge it */
1387 se->nr_pages += nr_pages;
1388 return 0;
1393 * No merge. Insert a new extent, preserving ordering.
1395 new_se = kmalloc(sizeof(*se), GFP_KERNEL);
1396 if (new_se == NULL)
1397 return -ENOMEM;
1398 new_se->start_page = start_page;
1399 new_se->nr_pages = nr_pages;
1400 new_se->start_block = start_block;
1402 list_add_tail(&new_se->list, &sis->first_swap_extent.list);
1403 return 1;
1407 * A `swap extent' is a simple thing which maps a contiguous range of pages
1408 * onto a contiguous range of disk blocks. An ordered list of swap extents
1409 * is built at swapon time and is then used at swap_writepage/swap_readpage
1410 * time for locating where on disk a page belongs.
1412 * If the swapfile is an S_ISBLK block device, a single extent is installed.
1413 * This is done so that the main operating code can treat S_ISBLK and S_ISREG
1414 * swap files identically.
1416 * Whether the swapdev is an S_ISREG file or an S_ISBLK blockdev, the swap
1417 * extent list operates in PAGE_SIZE disk blocks. Both S_ISREG and S_ISBLK
1418 * swapfiles are handled *identically* after swapon time.
1420 * For S_ISREG swapfiles, setup_swap_extents() will walk all the file's blocks
1421 * and will parse them into an ordered extent list, in PAGE_SIZE chunks. If
1422 * some stray blocks are found which do not fall within the PAGE_SIZE alignment
1423 * requirements, they are simply tossed out - we will never use those blocks
1424 * for swapping.
1426 * For S_ISREG swapfiles we set S_SWAPFILE across the life of the swapon. This
1427 * prevents root from shooting her foot off by ftruncating an in-use swapfile,
1428 * which will scribble on the fs.
1430 * The amount of disk space which a single swap extent represents varies.
1431 * Typically it is in the 1-4 megabyte range. So we can have hundreds of
1432 * extents in the list. To avoid much list walking, we cache the previous
1433 * search location in `curr_swap_extent', and start new searches from there.
1434 * This is extremely effective. The average number of iterations in
1435 * map_swap_page() has been measured at about 0.3 per page. - akpm.
1437 static int setup_swap_extents(struct swap_info_struct *sis, sector_t *span)
1439 struct inode *inode;
1440 unsigned blocks_per_page;
1441 unsigned long page_no;
1442 unsigned blkbits;
1443 sector_t probe_block;
1444 sector_t last_block;
1445 sector_t lowest_block = -1;
1446 sector_t highest_block = 0;
1447 int nr_extents = 0;
1448 int ret;
1450 inode = sis->swap_file->f_mapping->host;
1451 if (S_ISBLK(inode->i_mode)) {
1452 ret = add_swap_extent(sis, 0, sis->max, 0);
1453 *span = sis->pages;
1454 goto out;
1457 blkbits = inode->i_blkbits;
1458 blocks_per_page = PAGE_SIZE >> blkbits;
1461 * Map all the blocks into the extent list. This code doesn't try
1462 * to be very smart.
1464 probe_block = 0;
1465 page_no = 0;
1466 last_block = i_size_read(inode) >> blkbits;
1467 while ((probe_block + blocks_per_page) <= last_block &&
1468 page_no < sis->max) {
1469 unsigned block_in_page;
1470 sector_t first_block;
1472 first_block = bmap(inode, probe_block);
1473 if (first_block == 0)
1474 goto bad_bmap;
1477 * It must be PAGE_SIZE aligned on-disk
1479 if (first_block & (blocks_per_page - 1)) {
1480 probe_block++;
1481 goto reprobe;
1484 for (block_in_page = 1; block_in_page < blocks_per_page;
1485 block_in_page++) {
1486 sector_t block;
1488 block = bmap(inode, probe_block + block_in_page);
1489 if (block == 0)
1490 goto bad_bmap;
1491 if (block != first_block + block_in_page) {
1492 /* Discontiguity */
1493 probe_block++;
1494 goto reprobe;
1498 first_block >>= (PAGE_SHIFT - blkbits);
1499 if (page_no) { /* exclude the header page */
1500 if (first_block < lowest_block)
1501 lowest_block = first_block;
1502 if (first_block > highest_block)
1503 highest_block = first_block;
1507 * We found a PAGE_SIZE-length, PAGE_SIZE-aligned run of blocks
1509 ret = add_swap_extent(sis, page_no, 1, first_block);
1510 if (ret < 0)
1511 goto out;
1512 nr_extents += ret;
1513 page_no++;
1514 probe_block += blocks_per_page;
1515 reprobe:
1516 continue;
1518 ret = nr_extents;
1519 *span = 1 + highest_block - lowest_block;
1520 if (page_no == 0)
1521 page_no = 1; /* force Empty message */
1522 sis->max = page_no;
1523 sis->pages = page_no - 1;
1524 sis->highest_bit = page_no - 1;
1525 out:
1526 return ret;
1527 bad_bmap:
1528 printk(KERN_ERR "swapon: swapfile has holes\n");
1529 ret = -EINVAL;
1530 goto out;
1533 SYSCALL_DEFINE1(swapoff, const char __user *, specialfile)
1535 struct swap_info_struct *p = NULL;
1536 unsigned char *swap_map;
1537 struct file *swap_file, *victim;
1538 struct address_space *mapping;
1539 struct inode *inode;
1540 char *pathname;
1541 int i, type, prev;
1542 int err;
1544 if (!capable(CAP_SYS_ADMIN))
1545 return -EPERM;
1547 pathname = getname(specialfile);
1548 err = PTR_ERR(pathname);
1549 if (IS_ERR(pathname))
1550 goto out;
1552 victim = filp_open(pathname, O_RDWR|O_LARGEFILE, 0);
1553 putname(pathname);
1554 err = PTR_ERR(victim);
1555 if (IS_ERR(victim))
1556 goto out;
1558 mapping = victim->f_mapping;
1559 prev = -1;
1560 spin_lock(&swap_lock);
1561 for (type = swap_list.head; type >= 0; type = swap_info[type]->next) {
1562 p = swap_info[type];
1563 if (p->flags & SWP_WRITEOK) {
1564 if (p->swap_file->f_mapping == mapping)
1565 break;
1567 prev = type;
1569 if (type < 0) {
1570 err = -EINVAL;
1571 spin_unlock(&swap_lock);
1572 goto out_dput;
1574 if (!security_vm_enough_memory(p->pages))
1575 vm_unacct_memory(p->pages);
1576 else {
1577 err = -ENOMEM;
1578 spin_unlock(&swap_lock);
1579 goto out_dput;
1581 if (prev < 0)
1582 swap_list.head = p->next;
1583 else
1584 swap_info[prev]->next = p->next;
1585 if (type == swap_list.next) {
1586 /* just pick something that's safe... */
1587 swap_list.next = swap_list.head;
1589 if (p->prio < 0) {
1590 for (i = p->next; i >= 0; i = swap_info[i]->next)
1591 swap_info[i]->prio = p->prio--;
1592 least_priority++;
1594 nr_swap_pages -= p->pages;
1595 total_swap_pages -= p->pages;
1596 p->flags &= ~SWP_WRITEOK;
1597 spin_unlock(&swap_lock);
1599 current->flags |= PF_OOM_ORIGIN;
1600 err = try_to_unuse(type);
1601 current->flags &= ~PF_OOM_ORIGIN;
1603 if (err) {
1604 /* re-insert swap space back into swap_list */
1605 spin_lock(&swap_lock);
1606 if (p->prio < 0)
1607 p->prio = --least_priority;
1608 prev = -1;
1609 for (i = swap_list.head; i >= 0; i = swap_info[i]->next) {
1610 if (p->prio >= swap_info[i]->prio)
1611 break;
1612 prev = i;
1614 p->next = i;
1615 if (prev < 0)
1616 swap_list.head = swap_list.next = type;
1617 else
1618 swap_info[prev]->next = type;
1619 nr_swap_pages += p->pages;
1620 total_swap_pages += p->pages;
1621 p->flags |= SWP_WRITEOK;
1622 spin_unlock(&swap_lock);
1623 goto out_dput;
1626 /* wait for any unplug function to finish */
1627 down_write(&swap_unplug_sem);
1628 up_write(&swap_unplug_sem);
1630 destroy_swap_extents(p);
1631 if (p->flags & SWP_CONTINUED)
1632 free_swap_count_continuations(p);
1634 mutex_lock(&swapon_mutex);
1635 spin_lock(&swap_lock);
1636 drain_mmlist();
1638 /* wait for anyone still in scan_swap_map */
1639 p->highest_bit = 0; /* cuts scans short */
1640 while (p->flags >= SWP_SCANNING) {
1641 spin_unlock(&swap_lock);
1642 schedule_timeout_uninterruptible(1);
1643 spin_lock(&swap_lock);
1646 swap_file = p->swap_file;
1647 p->swap_file = NULL;
1648 p->max = 0;
1649 swap_map = p->swap_map;
1650 p->swap_map = NULL;
1651 p->flags = 0;
1652 spin_unlock(&swap_lock);
1653 mutex_unlock(&swapon_mutex);
1654 vfree(swap_map);
1655 /* Destroy swap account informatin */
1656 swap_cgroup_swapoff(type);
1658 inode = mapping->host;
1659 if (S_ISBLK(inode->i_mode)) {
1660 struct block_device *bdev = I_BDEV(inode);
1661 set_blocksize(bdev, p->old_block_size);
1662 bd_release(bdev);
1663 } else {
1664 mutex_lock(&inode->i_mutex);
1665 inode->i_flags &= ~S_SWAPFILE;
1666 mutex_unlock(&inode->i_mutex);
1668 filp_close(swap_file, NULL);
1669 err = 0;
1671 out_dput:
1672 filp_close(victim, NULL);
1673 out:
1674 return err;
1677 #ifdef CONFIG_PROC_FS
1678 /* iterator */
1679 static void *swap_start(struct seq_file *swap, loff_t *pos)
1681 struct swap_info_struct *si;
1682 int type;
1683 loff_t l = *pos;
1685 mutex_lock(&swapon_mutex);
1687 if (!l)
1688 return SEQ_START_TOKEN;
1690 for (type = 0; type < nr_swapfiles; type++) {
1691 smp_rmb(); /* read nr_swapfiles before swap_info[type] */
1692 si = swap_info[type];
1693 if (!(si->flags & SWP_USED) || !si->swap_map)
1694 continue;
1695 if (!--l)
1696 return si;
1699 return NULL;
1702 static void *swap_next(struct seq_file *swap, void *v, loff_t *pos)
1704 struct swap_info_struct *si = v;
1705 int type;
1707 if (v == SEQ_START_TOKEN)
1708 type = 0;
1709 else
1710 type = si->type + 1;
1712 for (; type < nr_swapfiles; type++) {
1713 smp_rmb(); /* read nr_swapfiles before swap_info[type] */
1714 si = swap_info[type];
1715 if (!(si->flags & SWP_USED) || !si->swap_map)
1716 continue;
1717 ++*pos;
1718 return si;
1721 return NULL;
1724 static void swap_stop(struct seq_file *swap, void *v)
1726 mutex_unlock(&swapon_mutex);
1729 static int swap_show(struct seq_file *swap, void *v)
1731 struct swap_info_struct *si = v;
1732 struct file *file;
1733 int len;
1735 if (si == SEQ_START_TOKEN) {
1736 seq_puts(swap,"Filename\t\t\t\tType\t\tSize\tUsed\tPriority\n");
1737 return 0;
1740 file = si->swap_file;
1741 len = seq_path(swap, &file->f_path, " \t\n\\");
1742 seq_printf(swap, "%*s%s\t%u\t%u\t%d\n",
1743 len < 40 ? 40 - len : 1, " ",
1744 S_ISBLK(file->f_path.dentry->d_inode->i_mode) ?
1745 "partition" : "file\t",
1746 si->pages << (PAGE_SHIFT - 10),
1747 si->inuse_pages << (PAGE_SHIFT - 10),
1748 si->prio);
1749 return 0;
1752 static const struct seq_operations swaps_op = {
1753 .start = swap_start,
1754 .next = swap_next,
1755 .stop = swap_stop,
1756 .show = swap_show
1759 static int swaps_open(struct inode *inode, struct file *file)
1761 return seq_open(file, &swaps_op);
1764 static const struct file_operations proc_swaps_operations = {
1765 .open = swaps_open,
1766 .read = seq_read,
1767 .llseek = seq_lseek,
1768 .release = seq_release,
1771 static int __init procswaps_init(void)
1773 proc_create("swaps", 0, NULL, &proc_swaps_operations);
1774 return 0;
1776 __initcall(procswaps_init);
1777 #endif /* CONFIG_PROC_FS */
1779 #ifdef MAX_SWAPFILES_CHECK
1780 static int __init max_swapfiles_check(void)
1782 MAX_SWAPFILES_CHECK();
1783 return 0;
1785 late_initcall(max_swapfiles_check);
1786 #endif
1789 * Written 01/25/92 by Simmule Turner, heavily changed by Linus.
1791 * The swapon system call
1793 SYSCALL_DEFINE2(swapon, const char __user *, specialfile, int, swap_flags)
1795 struct swap_info_struct *p;
1796 char *name = NULL;
1797 struct block_device *bdev = NULL;
1798 struct file *swap_file = NULL;
1799 struct address_space *mapping;
1800 unsigned int type;
1801 int i, prev;
1802 int error;
1803 union swap_header *swap_header;
1804 unsigned int nr_good_pages;
1805 int nr_extents = 0;
1806 sector_t span;
1807 unsigned long maxpages;
1808 unsigned long swapfilepages;
1809 unsigned char *swap_map = NULL;
1810 struct page *page = NULL;
1811 struct inode *inode = NULL;
1812 int did_down = 0;
1814 if (!capable(CAP_SYS_ADMIN))
1815 return -EPERM;
1817 p = kzalloc(sizeof(*p), GFP_KERNEL);
1818 if (!p)
1819 return -ENOMEM;
1821 spin_lock(&swap_lock);
1822 for (type = 0; type < nr_swapfiles; type++) {
1823 if (!(swap_info[type]->flags & SWP_USED))
1824 break;
1826 error = -EPERM;
1827 if (type >= MAX_SWAPFILES) {
1828 spin_unlock(&swap_lock);
1829 kfree(p);
1830 goto out;
1832 if (type >= nr_swapfiles) {
1833 p->type = type;
1834 swap_info[type] = p;
1836 * Write swap_info[type] before nr_swapfiles, in case a
1837 * racing procfs swap_start() or swap_next() is reading them.
1838 * (We never shrink nr_swapfiles, we never free this entry.)
1840 smp_wmb();
1841 nr_swapfiles++;
1842 } else {
1843 kfree(p);
1844 p = swap_info[type];
1846 * Do not memset this entry: a racing procfs swap_next()
1847 * would be relying on p->type to remain valid.
1850 INIT_LIST_HEAD(&p->first_swap_extent.list);
1851 p->flags = SWP_USED;
1852 p->next = -1;
1853 spin_unlock(&swap_lock);
1855 name = getname(specialfile);
1856 error = PTR_ERR(name);
1857 if (IS_ERR(name)) {
1858 name = NULL;
1859 goto bad_swap_2;
1861 swap_file = filp_open(name, O_RDWR|O_LARGEFILE, 0);
1862 error = PTR_ERR(swap_file);
1863 if (IS_ERR(swap_file)) {
1864 swap_file = NULL;
1865 goto bad_swap_2;
1868 p->swap_file = swap_file;
1869 mapping = swap_file->f_mapping;
1870 inode = mapping->host;
1872 error = -EBUSY;
1873 for (i = 0; i < nr_swapfiles; i++) {
1874 struct swap_info_struct *q = swap_info[i];
1876 if (i == type || !q->swap_file)
1877 continue;
1878 if (mapping == q->swap_file->f_mapping)
1879 goto bad_swap;
1882 error = -EINVAL;
1883 if (S_ISBLK(inode->i_mode)) {
1884 bdev = I_BDEV(inode);
1885 error = bd_claim(bdev, sys_swapon);
1886 if (error < 0) {
1887 bdev = NULL;
1888 error = -EINVAL;
1889 goto bad_swap;
1891 p->old_block_size = block_size(bdev);
1892 error = set_blocksize(bdev, PAGE_SIZE);
1893 if (error < 0)
1894 goto bad_swap;
1895 p->bdev = bdev;
1896 p->flags |= SWP_BLKDEV;
1897 } else if (S_ISREG(inode->i_mode)) {
1898 p->bdev = inode->i_sb->s_bdev;
1899 mutex_lock(&inode->i_mutex);
1900 did_down = 1;
1901 if (IS_SWAPFILE(inode)) {
1902 error = -EBUSY;
1903 goto bad_swap;
1905 } else {
1906 goto bad_swap;
1909 swapfilepages = i_size_read(inode) >> PAGE_SHIFT;
1912 * Read the swap header.
1914 if (!mapping->a_ops->readpage) {
1915 error = -EINVAL;
1916 goto bad_swap;
1918 page = read_mapping_page(mapping, 0, swap_file);
1919 if (IS_ERR(page)) {
1920 error = PTR_ERR(page);
1921 goto bad_swap;
1923 swap_header = kmap(page);
1925 if (memcmp("SWAPSPACE2", swap_header->magic.magic, 10)) {
1926 printk(KERN_ERR "Unable to find swap-space signature\n");
1927 error = -EINVAL;
1928 goto bad_swap;
1931 /* swap partition endianess hack... */
1932 if (swab32(swap_header->info.version) == 1) {
1933 swab32s(&swap_header->info.version);
1934 swab32s(&swap_header->info.last_page);
1935 swab32s(&swap_header->info.nr_badpages);
1936 for (i = 0; i < swap_header->info.nr_badpages; i++)
1937 swab32s(&swap_header->info.badpages[i]);
1939 /* Check the swap header's sub-version */
1940 if (swap_header->info.version != 1) {
1941 printk(KERN_WARNING
1942 "Unable to handle swap header version %d\n",
1943 swap_header->info.version);
1944 error = -EINVAL;
1945 goto bad_swap;
1948 p->lowest_bit = 1;
1949 p->cluster_next = 1;
1950 p->cluster_nr = 0;
1953 * Find out how many pages are allowed for a single swap
1954 * device. There are two limiting factors: 1) the number of
1955 * bits for the swap offset in the swp_entry_t type and
1956 * 2) the number of bits in the a swap pte as defined by
1957 * the different architectures. In order to find the
1958 * largest possible bit mask a swap entry with swap type 0
1959 * and swap offset ~0UL is created, encoded to a swap pte,
1960 * decoded to a swp_entry_t again and finally the swap
1961 * offset is extracted. This will mask all the bits from
1962 * the initial ~0UL mask that can't be encoded in either
1963 * the swp_entry_t or the architecture definition of a
1964 * swap pte.
1966 maxpages = swp_offset(pte_to_swp_entry(
1967 swp_entry_to_pte(swp_entry(0, ~0UL)))) + 1;
1968 if (maxpages > swap_header->info.last_page) {
1969 maxpages = swap_header->info.last_page + 1;
1970 /* p->max is an unsigned int: don't overflow it */
1971 if ((unsigned int)maxpages == 0)
1972 maxpages = UINT_MAX;
1974 p->highest_bit = maxpages - 1;
1976 error = -EINVAL;
1977 if (!maxpages)
1978 goto bad_swap;
1979 if (swapfilepages && maxpages > swapfilepages) {
1980 printk(KERN_WARNING
1981 "Swap area shorter than signature indicates\n");
1982 goto bad_swap;
1984 if (swap_header->info.nr_badpages && S_ISREG(inode->i_mode))
1985 goto bad_swap;
1986 if (swap_header->info.nr_badpages > MAX_SWAP_BADPAGES)
1987 goto bad_swap;
1989 /* OK, set up the swap map and apply the bad block list */
1990 swap_map = vmalloc(maxpages);
1991 if (!swap_map) {
1992 error = -ENOMEM;
1993 goto bad_swap;
1996 memset(swap_map, 0, maxpages);
1997 nr_good_pages = maxpages - 1; /* omit header page */
1999 for (i = 0; i < swap_header->info.nr_badpages; i++) {
2000 unsigned int page_nr = swap_header->info.badpages[i];
2001 if (page_nr == 0 || page_nr > swap_header->info.last_page) {
2002 error = -EINVAL;
2003 goto bad_swap;
2005 if (page_nr < maxpages) {
2006 swap_map[page_nr] = SWAP_MAP_BAD;
2007 nr_good_pages--;
2011 error = swap_cgroup_swapon(type, maxpages);
2012 if (error)
2013 goto bad_swap;
2015 if (nr_good_pages) {
2016 swap_map[0] = SWAP_MAP_BAD;
2017 p->max = maxpages;
2018 p->pages = nr_good_pages;
2019 nr_extents = setup_swap_extents(p, &span);
2020 if (nr_extents < 0) {
2021 error = nr_extents;
2022 goto bad_swap;
2024 nr_good_pages = p->pages;
2026 if (!nr_good_pages) {
2027 printk(KERN_WARNING "Empty swap-file\n");
2028 error = -EINVAL;
2029 goto bad_swap;
2032 if (p->bdev) {
2033 if (blk_queue_nonrot(bdev_get_queue(p->bdev))) {
2034 p->flags |= SWP_SOLIDSTATE;
2035 p->cluster_next = 1 + (random32() % p->highest_bit);
2037 if (discard_swap(p) == 0)
2038 p->flags |= SWP_DISCARDABLE;
2041 mutex_lock(&swapon_mutex);
2042 spin_lock(&swap_lock);
2043 if (swap_flags & SWAP_FLAG_PREFER)
2044 p->prio =
2045 (swap_flags & SWAP_FLAG_PRIO_MASK) >> SWAP_FLAG_PRIO_SHIFT;
2046 else
2047 p->prio = --least_priority;
2048 p->swap_map = swap_map;
2049 p->flags |= SWP_WRITEOK;
2050 nr_swap_pages += nr_good_pages;
2051 total_swap_pages += nr_good_pages;
2053 printk(KERN_INFO "Adding %uk swap on %s. "
2054 "Priority:%d extents:%d across:%lluk %s%s\n",
2055 nr_good_pages<<(PAGE_SHIFT-10), name, p->prio,
2056 nr_extents, (unsigned long long)span<<(PAGE_SHIFT-10),
2057 (p->flags & SWP_SOLIDSTATE) ? "SS" : "",
2058 (p->flags & SWP_DISCARDABLE) ? "D" : "");
2060 /* insert swap space into swap_list: */
2061 prev = -1;
2062 for (i = swap_list.head; i >= 0; i = swap_info[i]->next) {
2063 if (p->prio >= swap_info[i]->prio)
2064 break;
2065 prev = i;
2067 p->next = i;
2068 if (prev < 0)
2069 swap_list.head = swap_list.next = type;
2070 else
2071 swap_info[prev]->next = type;
2072 spin_unlock(&swap_lock);
2073 mutex_unlock(&swapon_mutex);
2074 error = 0;
2075 goto out;
2076 bad_swap:
2077 if (bdev) {
2078 set_blocksize(bdev, p->old_block_size);
2079 bd_release(bdev);
2081 destroy_swap_extents(p);
2082 swap_cgroup_swapoff(type);
2083 bad_swap_2:
2084 spin_lock(&swap_lock);
2085 p->swap_file = NULL;
2086 p->flags = 0;
2087 spin_unlock(&swap_lock);
2088 vfree(swap_map);
2089 if (swap_file)
2090 filp_close(swap_file, NULL);
2091 out:
2092 if (page && !IS_ERR(page)) {
2093 kunmap(page);
2094 page_cache_release(page);
2096 if (name)
2097 putname(name);
2098 if (did_down) {
2099 if (!error)
2100 inode->i_flags |= S_SWAPFILE;
2101 mutex_unlock(&inode->i_mutex);
2103 return error;
2106 void si_swapinfo(struct sysinfo *val)
2108 unsigned int type;
2109 unsigned long nr_to_be_unused = 0;
2111 spin_lock(&swap_lock);
2112 for (type = 0; type < nr_swapfiles; type++) {
2113 struct swap_info_struct *si = swap_info[type];
2115 if ((si->flags & SWP_USED) && !(si->flags & SWP_WRITEOK))
2116 nr_to_be_unused += si->inuse_pages;
2118 val->freeswap = nr_swap_pages + nr_to_be_unused;
2119 val->totalswap = total_swap_pages + nr_to_be_unused;
2120 spin_unlock(&swap_lock);
2124 * Verify that a swap entry is valid and increment its swap map count.
2126 * Returns error code in following case.
2127 * - success -> 0
2128 * - swp_entry is invalid -> EINVAL
2129 * - swp_entry is migration entry -> EINVAL
2130 * - swap-cache reference is requested but there is already one. -> EEXIST
2131 * - swap-cache reference is requested but the entry is not used. -> ENOENT
2132 * - swap-mapped reference requested but needs continued swap count. -> ENOMEM
2134 static int __swap_duplicate(swp_entry_t entry, unsigned char usage)
2136 struct swap_info_struct *p;
2137 unsigned long offset, type;
2138 unsigned char count;
2139 unsigned char has_cache;
2140 int err = -EINVAL;
2142 if (non_swap_entry(entry))
2143 goto out;
2145 type = swp_type(entry);
2146 if (type >= nr_swapfiles)
2147 goto bad_file;
2148 p = swap_info[type];
2149 offset = swp_offset(entry);
2151 spin_lock(&swap_lock);
2152 if (unlikely(offset >= p->max))
2153 goto unlock_out;
2155 count = p->swap_map[offset];
2156 has_cache = count & SWAP_HAS_CACHE;
2157 count &= ~SWAP_HAS_CACHE;
2158 err = 0;
2160 if (usage == SWAP_HAS_CACHE) {
2162 /* set SWAP_HAS_CACHE if there is no cache and entry is used */
2163 if (!has_cache && count)
2164 has_cache = SWAP_HAS_CACHE;
2165 else if (has_cache) /* someone else added cache */
2166 err = -EEXIST;
2167 else /* no users remaining */
2168 err = -ENOENT;
2170 } else if (count || has_cache) {
2172 if ((count & ~COUNT_CONTINUED) < SWAP_MAP_MAX)
2173 count += usage;
2174 else if ((count & ~COUNT_CONTINUED) > SWAP_MAP_MAX)
2175 err = -EINVAL;
2176 else if (swap_count_continued(p, offset, count))
2177 count = COUNT_CONTINUED;
2178 else
2179 err = -ENOMEM;
2180 } else
2181 err = -ENOENT; /* unused swap entry */
2183 p->swap_map[offset] = count | has_cache;
2185 unlock_out:
2186 spin_unlock(&swap_lock);
2187 out:
2188 return err;
2190 bad_file:
2191 printk(KERN_ERR "swap_dup: %s%08lx\n", Bad_file, entry.val);
2192 goto out;
2196 * Help swapoff by noting that swap entry belongs to shmem/tmpfs
2197 * (in which case its reference count is never incremented).
2199 void swap_shmem_alloc(swp_entry_t entry)
2201 __swap_duplicate(entry, SWAP_MAP_SHMEM);
2205 * Increase reference count of swap entry by 1.
2206 * Returns 0 for success, or -ENOMEM if a swap_count_continuation is required
2207 * but could not be atomically allocated. Returns 0, just as if it succeeded,
2208 * if __swap_duplicate() fails for another reason (-EINVAL or -ENOENT), which
2209 * might occur if a page table entry has got corrupted.
2211 int swap_duplicate(swp_entry_t entry)
2213 int err = 0;
2215 while (!err && __swap_duplicate(entry, 1) == -ENOMEM)
2216 err = add_swap_count_continuation(entry, GFP_ATOMIC);
2217 return err;
2221 * @entry: swap entry for which we allocate swap cache.
2223 * Called when allocating swap cache for existing swap entry,
2224 * This can return error codes. Returns 0 at success.
2225 * -EBUSY means there is a swap cache.
2226 * Note: return code is different from swap_duplicate().
2228 int swapcache_prepare(swp_entry_t entry)
2230 return __swap_duplicate(entry, SWAP_HAS_CACHE);
2234 * swap_lock prevents swap_map being freed. Don't grab an extra
2235 * reference on the swaphandle, it doesn't matter if it becomes unused.
2237 int valid_swaphandles(swp_entry_t entry, unsigned long *offset)
2239 struct swap_info_struct *si;
2240 int our_page_cluster = page_cluster;
2241 pgoff_t target, toff;
2242 pgoff_t base, end;
2243 int nr_pages = 0;
2245 if (!our_page_cluster) /* no readahead */
2246 return 0;
2248 si = swap_info[swp_type(entry)];
2249 target = swp_offset(entry);
2250 base = (target >> our_page_cluster) << our_page_cluster;
2251 end = base + (1 << our_page_cluster);
2252 if (!base) /* first page is swap header */
2253 base++;
2255 spin_lock(&swap_lock);
2256 if (end > si->max) /* don't go beyond end of map */
2257 end = si->max;
2259 /* Count contiguous allocated slots above our target */
2260 for (toff = target; ++toff < end; nr_pages++) {
2261 /* Don't read in free or bad pages */
2262 if (!si->swap_map[toff])
2263 break;
2264 if (swap_count(si->swap_map[toff]) == SWAP_MAP_BAD)
2265 break;
2267 /* Count contiguous allocated slots below our target */
2268 for (toff = target; --toff >= base; nr_pages++) {
2269 /* Don't read in free or bad pages */
2270 if (!si->swap_map[toff])
2271 break;
2272 if (swap_count(si->swap_map[toff]) == SWAP_MAP_BAD)
2273 break;
2275 spin_unlock(&swap_lock);
2278 * Indicate starting offset, and return number of pages to get:
2279 * if only 1, say 0, since there's then no readahead to be done.
2281 *offset = ++toff;
2282 return nr_pages? ++nr_pages: 0;
2286 * add_swap_count_continuation - called when a swap count is duplicated
2287 * beyond SWAP_MAP_MAX, it allocates a new page and links that to the entry's
2288 * page of the original vmalloc'ed swap_map, to hold the continuation count
2289 * (for that entry and for its neighbouring PAGE_SIZE swap entries). Called
2290 * again when count is duplicated beyond SWAP_MAP_MAX * SWAP_CONT_MAX, etc.
2292 * These continuation pages are seldom referenced: the common paths all work
2293 * on the original swap_map, only referring to a continuation page when the
2294 * low "digit" of a count is incremented or decremented through SWAP_MAP_MAX.
2296 * add_swap_count_continuation(, GFP_ATOMIC) can be called while holding
2297 * page table locks; if it fails, add_swap_count_continuation(, GFP_KERNEL)
2298 * can be called after dropping locks.
2300 int add_swap_count_continuation(swp_entry_t entry, gfp_t gfp_mask)
2302 struct swap_info_struct *si;
2303 struct page *head;
2304 struct page *page;
2305 struct page *list_page;
2306 pgoff_t offset;
2307 unsigned char count;
2310 * When debugging, it's easier to use __GFP_ZERO here; but it's better
2311 * for latency not to zero a page while GFP_ATOMIC and holding locks.
2313 page = alloc_page(gfp_mask | __GFP_HIGHMEM);
2315 si = swap_info_get(entry);
2316 if (!si) {
2318 * An acceptable race has occurred since the failing
2319 * __swap_duplicate(): the swap entry has been freed,
2320 * perhaps even the whole swap_map cleared for swapoff.
2322 goto outer;
2325 offset = swp_offset(entry);
2326 count = si->swap_map[offset] & ~SWAP_HAS_CACHE;
2328 if ((count & ~COUNT_CONTINUED) != SWAP_MAP_MAX) {
2330 * The higher the swap count, the more likely it is that tasks
2331 * will race to add swap count continuation: we need to avoid
2332 * over-provisioning.
2334 goto out;
2337 if (!page) {
2338 spin_unlock(&swap_lock);
2339 return -ENOMEM;
2343 * We are fortunate that although vmalloc_to_page uses pte_offset_map,
2344 * no architecture is using highmem pages for kernel pagetables: so it
2345 * will not corrupt the GFP_ATOMIC caller's atomic pagetable kmaps.
2347 head = vmalloc_to_page(si->swap_map + offset);
2348 offset &= ~PAGE_MASK;
2351 * Page allocation does not initialize the page's lru field,
2352 * but it does always reset its private field.
2354 if (!page_private(head)) {
2355 BUG_ON(count & COUNT_CONTINUED);
2356 INIT_LIST_HEAD(&head->lru);
2357 set_page_private(head, SWP_CONTINUED);
2358 si->flags |= SWP_CONTINUED;
2361 list_for_each_entry(list_page, &head->lru, lru) {
2362 unsigned char *map;
2365 * If the previous map said no continuation, but we've found
2366 * a continuation page, free our allocation and use this one.
2368 if (!(count & COUNT_CONTINUED))
2369 goto out;
2371 map = kmap_atomic(list_page, KM_USER0) + offset;
2372 count = *map;
2373 kunmap_atomic(map, KM_USER0);
2376 * If this continuation count now has some space in it,
2377 * free our allocation and use this one.
2379 if ((count & ~COUNT_CONTINUED) != SWAP_CONT_MAX)
2380 goto out;
2383 list_add_tail(&page->lru, &head->lru);
2384 page = NULL; /* now it's attached, don't free it */
2385 out:
2386 spin_unlock(&swap_lock);
2387 outer:
2388 if (page)
2389 __free_page(page);
2390 return 0;
2394 * swap_count_continued - when the original swap_map count is incremented
2395 * from SWAP_MAP_MAX, check if there is already a continuation page to carry
2396 * into, carry if so, or else fail until a new continuation page is allocated;
2397 * when the original swap_map count is decremented from 0 with continuation,
2398 * borrow from the continuation and report whether it still holds more.
2399 * Called while __swap_duplicate() or swap_entry_free() holds swap_lock.
2401 static bool swap_count_continued(struct swap_info_struct *si,
2402 pgoff_t offset, unsigned char count)
2404 struct page *head;
2405 struct page *page;
2406 unsigned char *map;
2408 head = vmalloc_to_page(si->swap_map + offset);
2409 if (page_private(head) != SWP_CONTINUED) {
2410 BUG_ON(count & COUNT_CONTINUED);
2411 return false; /* need to add count continuation */
2414 offset &= ~PAGE_MASK;
2415 page = list_entry(head->lru.next, struct page, lru);
2416 map = kmap_atomic(page, KM_USER0) + offset;
2418 if (count == SWAP_MAP_MAX) /* initial increment from swap_map */
2419 goto init_map; /* jump over SWAP_CONT_MAX checks */
2421 if (count == (SWAP_MAP_MAX | COUNT_CONTINUED)) { /* incrementing */
2423 * Think of how you add 1 to 999
2425 while (*map == (SWAP_CONT_MAX | COUNT_CONTINUED)) {
2426 kunmap_atomic(map, KM_USER0);
2427 page = list_entry(page->lru.next, struct page, lru);
2428 BUG_ON(page == head);
2429 map = kmap_atomic(page, KM_USER0) + offset;
2431 if (*map == SWAP_CONT_MAX) {
2432 kunmap_atomic(map, KM_USER0);
2433 page = list_entry(page->lru.next, struct page, lru);
2434 if (page == head)
2435 return false; /* add count continuation */
2436 map = kmap_atomic(page, KM_USER0) + offset;
2437 init_map: *map = 0; /* we didn't zero the page */
2439 *map += 1;
2440 kunmap_atomic(map, KM_USER0);
2441 page = list_entry(page->lru.prev, struct page, lru);
2442 while (page != head) {
2443 map = kmap_atomic(page, KM_USER0) + offset;
2444 *map = COUNT_CONTINUED;
2445 kunmap_atomic(map, KM_USER0);
2446 page = list_entry(page->lru.prev, struct page, lru);
2448 return true; /* incremented */
2450 } else { /* decrementing */
2452 * Think of how you subtract 1 from 1000
2454 BUG_ON(count != COUNT_CONTINUED);
2455 while (*map == COUNT_CONTINUED) {
2456 kunmap_atomic(map, KM_USER0);
2457 page = list_entry(page->lru.next, struct page, lru);
2458 BUG_ON(page == head);
2459 map = kmap_atomic(page, KM_USER0) + offset;
2461 BUG_ON(*map == 0);
2462 *map -= 1;
2463 if (*map == 0)
2464 count = 0;
2465 kunmap_atomic(map, KM_USER0);
2466 page = list_entry(page->lru.prev, struct page, lru);
2467 while (page != head) {
2468 map = kmap_atomic(page, KM_USER0) + offset;
2469 *map = SWAP_CONT_MAX | count;
2470 count = COUNT_CONTINUED;
2471 kunmap_atomic(map, KM_USER0);
2472 page = list_entry(page->lru.prev, struct page, lru);
2474 return count == COUNT_CONTINUED;
2479 * free_swap_count_continuations - swapoff free all the continuation pages
2480 * appended to the swap_map, after swap_map is quiesced, before vfree'ing it.
2482 static void free_swap_count_continuations(struct swap_info_struct *si)
2484 pgoff_t offset;
2486 for (offset = 0; offset < si->max; offset += PAGE_SIZE) {
2487 struct page *head;
2488 head = vmalloc_to_page(si->swap_map + offset);
2489 if (page_private(head)) {
2490 struct list_head *this, *next;
2491 list_for_each_safe(this, next, &head->lru) {
2492 struct page *page;
2493 page = list_entry(this, struct page, lru);
2494 list_del(this);
2495 __free_page(page);