vmscan: stop kswapd waiting on congestion when the min watermark is not being met
[GitHub/LineageOS/android_kernel_motorola_exynos9610.git] / mm / swapfile.c
CommitLineData
1da177e4
LT
1/*
2 * linux/mm/swapfile.c
3 *
4 * Copyright (C) 1991, 1992, 1993, 1994 Linus Torvalds
5 * Swap reorganised 29.12.95, Stephen Tweedie
6 */
7
1da177e4
LT
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>
20137a49 19#include <linux/random.h>
1da177e4
LT
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>
fc0abb14 28#include <linux/mutex.h>
c59ede7b 29#include <linux/capability.h>
1da177e4 30#include <linux/syscalls.h>
8a9f3ccd 31#include <linux/memcontrol.h>
1da177e4
LT
32
33#include <asm/pgtable.h>
34#include <asm/tlbflush.h>
35#include <linux/swapops.h>
27a7faa0 36#include <linux/page_cgroup.h>
1da177e4 37
570a335b
HD
38static bool swap_count_continued(struct swap_info_struct *, pgoff_t,
39 unsigned char);
40static void free_swap_count_continuations(struct swap_info_struct *);
d4906e1a 41static sector_t map_swap_entry(swp_entry_t, struct block_device**);
570a335b 42
7c363b8c
AB
43static DEFINE_SPINLOCK(swap_lock);
44static unsigned int nr_swapfiles;
b962716b 45long nr_swap_pages;
1da177e4 46long total_swap_pages;
78ecba08 47static int least_priority;
1da177e4 48
1da177e4
LT
49static const char Bad_file[] = "Bad swap file entry ";
50static const char Unused_file[] = "Unused swap file entry ";
51static const char Bad_offset[] = "Bad swap offset entry ";
52static const char Unused_offset[] = "Unused swap offset entry ";
53
7c363b8c 54static struct swap_list_t swap_list = {-1, -1};
1da177e4 55
efa90a98 56static struct swap_info_struct *swap_info[MAX_SWAPFILES];
1da177e4 57
fc0abb14 58static DEFINE_MUTEX(swapon_mutex);
1da177e4 59
8d69aaee 60static inline unsigned char swap_count(unsigned char ent)
355cfa73 61{
570a335b 62 return ent & ~SWAP_HAS_CACHE; /* may include SWAP_HAS_CONT flag */
355cfa73
KH
63}
64
efa90a98 65/* returns 1 if swap entry is freed */
c9e44410
KH
66static int
67__try_to_reclaim_swap(struct swap_info_struct *si, unsigned long offset)
68{
efa90a98 69 swp_entry_t entry = swp_entry(si->type, offset);
c9e44410
KH
70 struct page *page;
71 int ret = 0;
72
73 page = find_get_page(&swapper_space, entry.val);
74 if (!page)
75 return 0;
76 /*
77 * This function is called from scan_swap_map() and it's called
78 * by vmscan.c at reclaiming pages. So, we hold a lock on a page, here.
79 * We have to use trylock for avoiding deadlock. This is a special
80 * case and you should use try_to_free_swap() with explicit lock_page()
81 * in usual operations.
82 */
83 if (trylock_page(page)) {
84 ret = try_to_free_swap(page);
85 unlock_page(page);
86 }
87 page_cache_release(page);
88 return ret;
89}
355cfa73 90
1da177e4
LT
91/*
92 * We need this because the bdev->unplug_fn can sleep and we cannot
5d337b91 93 * hold swap_lock while calling the unplug_fn. And swap_lock
fc0abb14 94 * cannot be turned into a mutex.
1da177e4
LT
95 */
96static DECLARE_RWSEM(swap_unplug_sem);
97
1da177e4
LT
98void swap_unplug_io_fn(struct backing_dev_info *unused_bdi, struct page *page)
99{
100 swp_entry_t entry;
101
102 down_read(&swap_unplug_sem);
4c21e2f2 103 entry.val = page_private(page);
1da177e4 104 if (PageSwapCache(page)) {
efa90a98 105 struct block_device *bdev = swap_info[swp_type(entry)]->bdev;
1da177e4
LT
106 struct backing_dev_info *bdi;
107
108 /*
109 * If the page is removed from swapcache from under us (with a
110 * racy try_to_unuse/swapoff) we need an additional reference
4c21e2f2
HD
111 * count to avoid reading garbage from page_private(page) above.
112 * If the WARN_ON triggers during a swapoff it maybe the race
1da177e4
LT
113 * condition and it's harmless. However if it triggers without
114 * swapoff it signals a problem.
115 */
116 WARN_ON(page_count(page) <= 1);
117
118 bdi = bdev->bd_inode->i_mapping->backing_dev_info;
ba32311e 119 blk_run_backing_dev(bdi, page);
1da177e4
LT
120 }
121 up_read(&swap_unplug_sem);
122}
123
6a6ba831
HD
124/*
125 * swapon tell device that all the old swap contents can be discarded,
126 * to allow the swap device to optimize its wear-levelling.
127 */
128static int discard_swap(struct swap_info_struct *si)
129{
130 struct swap_extent *se;
9625a5f2
HD
131 sector_t start_block;
132 sector_t nr_blocks;
6a6ba831
HD
133 int err = 0;
134
9625a5f2
HD
135 /* Do not discard the swap header page! */
136 se = &si->first_swap_extent;
137 start_block = (se->start_block + 1) << (PAGE_SHIFT - 9);
138 nr_blocks = ((sector_t)se->nr_pages - 1) << (PAGE_SHIFT - 9);
139 if (nr_blocks) {
140 err = blkdev_issue_discard(si->bdev, start_block,
141 nr_blocks, GFP_KERNEL, DISCARD_FL_BARRIER);
142 if (err)
143 return err;
144 cond_resched();
145 }
6a6ba831 146
9625a5f2
HD
147 list_for_each_entry(se, &si->first_swap_extent.list, list) {
148 start_block = se->start_block << (PAGE_SHIFT - 9);
149 nr_blocks = (sector_t)se->nr_pages << (PAGE_SHIFT - 9);
6a6ba831
HD
150
151 err = blkdev_issue_discard(si->bdev, start_block,
9625a5f2 152 nr_blocks, GFP_KERNEL, DISCARD_FL_BARRIER);
6a6ba831
HD
153 if (err)
154 break;
155
156 cond_resched();
157 }
158 return err; /* That will often be -EOPNOTSUPP */
159}
160
7992fde7
HD
161/*
162 * swap allocation tell device that a cluster of swap can now be discarded,
163 * to allow the swap device to optimize its wear-levelling.
164 */
165static void discard_swap_cluster(struct swap_info_struct *si,
166 pgoff_t start_page, pgoff_t nr_pages)
167{
168 struct swap_extent *se = si->curr_swap_extent;
169 int found_extent = 0;
170
171 while (nr_pages) {
172 struct list_head *lh;
173
174 if (se->start_page <= start_page &&
175 start_page < se->start_page + se->nr_pages) {
176 pgoff_t offset = start_page - se->start_page;
177 sector_t start_block = se->start_block + offset;
858a2990 178 sector_t nr_blocks = se->nr_pages - offset;
7992fde7
HD
179
180 if (nr_blocks > nr_pages)
181 nr_blocks = nr_pages;
182 start_page += nr_blocks;
183 nr_pages -= nr_blocks;
184
185 if (!found_extent++)
186 si->curr_swap_extent = se;
187
188 start_block <<= PAGE_SHIFT - 9;
189 nr_blocks <<= PAGE_SHIFT - 9;
190 if (blkdev_issue_discard(si->bdev, start_block,
9625a5f2 191 nr_blocks, GFP_NOIO, DISCARD_FL_BARRIER))
7992fde7
HD
192 break;
193 }
194
195 lh = se->list.next;
7992fde7
HD
196 se = list_entry(lh, struct swap_extent, list);
197 }
198}
199
200static int wait_for_discard(void *word)
201{
202 schedule();
203 return 0;
204}
205
048c27fd
HD
206#define SWAPFILE_CLUSTER 256
207#define LATENCY_LIMIT 256
208
355cfa73 209static inline unsigned long scan_swap_map(struct swap_info_struct *si,
8d69aaee 210 unsigned char usage)
1da177e4 211{
ebebbbe9 212 unsigned long offset;
c60aa176 213 unsigned long scan_base;
7992fde7 214 unsigned long last_in_cluster = 0;
048c27fd 215 int latency_ration = LATENCY_LIMIT;
7992fde7 216 int found_free_cluster = 0;
7dfad418 217
886bb7e9 218 /*
7dfad418
HD
219 * We try to cluster swap pages by allocating them sequentially
220 * in swap. Once we've allocated SWAPFILE_CLUSTER pages this
221 * way, however, we resort to first-free allocation, starting
222 * a new cluster. This prevents us from scattering swap pages
223 * all over the entire swap partition, so that we reduce
224 * overall disk seek times between swap pages. -- sct
225 * But we do now try to find an empty cluster. -Andrea
c60aa176 226 * And we let swap pages go all over an SSD partition. Hugh
7dfad418
HD
227 */
228
52b7efdb 229 si->flags += SWP_SCANNING;
c60aa176 230 scan_base = offset = si->cluster_next;
ebebbbe9
HD
231
232 if (unlikely(!si->cluster_nr--)) {
233 if (si->pages - si->inuse_pages < SWAPFILE_CLUSTER) {
234 si->cluster_nr = SWAPFILE_CLUSTER - 1;
235 goto checks;
236 }
7992fde7
HD
237 if (si->flags & SWP_DISCARDABLE) {
238 /*
239 * Start range check on racing allocations, in case
240 * they overlap the cluster we eventually decide on
241 * (we scan without swap_lock to allow preemption).
242 * It's hardly conceivable that cluster_nr could be
243 * wrapped during our scan, but don't depend on it.
244 */
245 if (si->lowest_alloc)
246 goto checks;
247 si->lowest_alloc = si->max;
248 si->highest_alloc = 0;
249 }
5d337b91 250 spin_unlock(&swap_lock);
7dfad418 251
c60aa176
HD
252 /*
253 * If seek is expensive, start searching for new cluster from
254 * start of partition, to minimize the span of allocated swap.
255 * But if seek is cheap, search from our current position, so
256 * that swap is allocated from all over the partition: if the
257 * Flash Translation Layer only remaps within limited zones,
258 * we don't want to wear out the first zone too quickly.
259 */
260 if (!(si->flags & SWP_SOLIDSTATE))
261 scan_base = offset = si->lowest_bit;
7dfad418
HD
262 last_in_cluster = offset + SWAPFILE_CLUSTER - 1;
263
264 /* Locate the first empty (unaligned) cluster */
265 for (; last_in_cluster <= si->highest_bit; offset++) {
1da177e4 266 if (si->swap_map[offset])
7dfad418
HD
267 last_in_cluster = offset + SWAPFILE_CLUSTER;
268 else if (offset == last_in_cluster) {
5d337b91 269 spin_lock(&swap_lock);
ebebbbe9
HD
270 offset -= SWAPFILE_CLUSTER - 1;
271 si->cluster_next = offset;
272 si->cluster_nr = SWAPFILE_CLUSTER - 1;
7992fde7 273 found_free_cluster = 1;
ebebbbe9 274 goto checks;
1da177e4 275 }
048c27fd
HD
276 if (unlikely(--latency_ration < 0)) {
277 cond_resched();
278 latency_ration = LATENCY_LIMIT;
279 }
7dfad418 280 }
ebebbbe9
HD
281
282 offset = si->lowest_bit;
c60aa176
HD
283 last_in_cluster = offset + SWAPFILE_CLUSTER - 1;
284
285 /* Locate the first empty (unaligned) cluster */
286 for (; last_in_cluster < scan_base; offset++) {
287 if (si->swap_map[offset])
288 last_in_cluster = offset + SWAPFILE_CLUSTER;
289 else if (offset == last_in_cluster) {
290 spin_lock(&swap_lock);
291 offset -= SWAPFILE_CLUSTER - 1;
292 si->cluster_next = offset;
293 si->cluster_nr = SWAPFILE_CLUSTER - 1;
294 found_free_cluster = 1;
295 goto checks;
296 }
297 if (unlikely(--latency_ration < 0)) {
298 cond_resched();
299 latency_ration = LATENCY_LIMIT;
300 }
301 }
302
303 offset = scan_base;
5d337b91 304 spin_lock(&swap_lock);
ebebbbe9 305 si->cluster_nr = SWAPFILE_CLUSTER - 1;
7992fde7 306 si->lowest_alloc = 0;
1da177e4 307 }
7dfad418 308
ebebbbe9
HD
309checks:
310 if (!(si->flags & SWP_WRITEOK))
52b7efdb 311 goto no_page;
7dfad418
HD
312 if (!si->highest_bit)
313 goto no_page;
ebebbbe9 314 if (offset > si->highest_bit)
c60aa176 315 scan_base = offset = si->lowest_bit;
c9e44410
KH
316
317 /* reuse swap entry of cache-only swap if not busy. */
318 if (vm_swap_full() && si->swap_map[offset] == SWAP_HAS_CACHE) {
319 int swap_was_freed;
320 spin_unlock(&swap_lock);
321 swap_was_freed = __try_to_reclaim_swap(si, offset);
322 spin_lock(&swap_lock);
323 /* entry was freed successfully, try to use this again */
324 if (swap_was_freed)
325 goto checks;
326 goto scan; /* check next one */
327 }
328
ebebbbe9
HD
329 if (si->swap_map[offset])
330 goto scan;
331
332 if (offset == si->lowest_bit)
333 si->lowest_bit++;
334 if (offset == si->highest_bit)
335 si->highest_bit--;
336 si->inuse_pages++;
337 if (si->inuse_pages == si->pages) {
338 si->lowest_bit = si->max;
339 si->highest_bit = 0;
1da177e4 340 }
253d553b 341 si->swap_map[offset] = usage;
ebebbbe9
HD
342 si->cluster_next = offset + 1;
343 si->flags -= SWP_SCANNING;
7992fde7
HD
344
345 if (si->lowest_alloc) {
346 /*
347 * Only set when SWP_DISCARDABLE, and there's a scan
348 * for a free cluster in progress or just completed.
349 */
350 if (found_free_cluster) {
351 /*
352 * To optimize wear-levelling, discard the
353 * old data of the cluster, taking care not to
354 * discard any of its pages that have already
355 * been allocated by racing tasks (offset has
356 * already stepped over any at the beginning).
357 */
358 if (offset < si->highest_alloc &&
359 si->lowest_alloc <= last_in_cluster)
360 last_in_cluster = si->lowest_alloc - 1;
361 si->flags |= SWP_DISCARDING;
362 spin_unlock(&swap_lock);
363
364 if (offset < last_in_cluster)
365 discard_swap_cluster(si, offset,
366 last_in_cluster - offset + 1);
367
368 spin_lock(&swap_lock);
369 si->lowest_alloc = 0;
370 si->flags &= ~SWP_DISCARDING;
371
372 smp_mb(); /* wake_up_bit advises this */
373 wake_up_bit(&si->flags, ilog2(SWP_DISCARDING));
374
375 } else if (si->flags & SWP_DISCARDING) {
376 /*
377 * Delay using pages allocated by racing tasks
378 * until the whole discard has been issued. We
379 * could defer that delay until swap_writepage,
380 * but it's easier to keep this self-contained.
381 */
382 spin_unlock(&swap_lock);
383 wait_on_bit(&si->flags, ilog2(SWP_DISCARDING),
384 wait_for_discard, TASK_UNINTERRUPTIBLE);
385 spin_lock(&swap_lock);
386 } else {
387 /*
388 * Note pages allocated by racing tasks while
389 * scan for a free cluster is in progress, so
390 * that its final discard can exclude them.
391 */
392 if (offset < si->lowest_alloc)
393 si->lowest_alloc = offset;
394 if (offset > si->highest_alloc)
395 si->highest_alloc = offset;
396 }
397 }
ebebbbe9 398 return offset;
7dfad418 399
ebebbbe9 400scan:
5d337b91 401 spin_unlock(&swap_lock);
7dfad418 402 while (++offset <= si->highest_bit) {
52b7efdb 403 if (!si->swap_map[offset]) {
5d337b91 404 spin_lock(&swap_lock);
52b7efdb
HD
405 goto checks;
406 }
c9e44410
KH
407 if (vm_swap_full() && si->swap_map[offset] == SWAP_HAS_CACHE) {
408 spin_lock(&swap_lock);
409 goto checks;
410 }
048c27fd
HD
411 if (unlikely(--latency_ration < 0)) {
412 cond_resched();
413 latency_ration = LATENCY_LIMIT;
414 }
7dfad418 415 }
c60aa176
HD
416 offset = si->lowest_bit;
417 while (++offset < scan_base) {
418 if (!si->swap_map[offset]) {
419 spin_lock(&swap_lock);
420 goto checks;
421 }
c9e44410
KH
422 if (vm_swap_full() && si->swap_map[offset] == SWAP_HAS_CACHE) {
423 spin_lock(&swap_lock);
424 goto checks;
425 }
c60aa176
HD
426 if (unlikely(--latency_ration < 0)) {
427 cond_resched();
428 latency_ration = LATENCY_LIMIT;
429 }
430 }
5d337b91 431 spin_lock(&swap_lock);
7dfad418
HD
432
433no_page:
52b7efdb 434 si->flags -= SWP_SCANNING;
1da177e4
LT
435 return 0;
436}
437
438swp_entry_t get_swap_page(void)
439{
fb4f88dc
HD
440 struct swap_info_struct *si;
441 pgoff_t offset;
442 int type, next;
443 int wrapped = 0;
1da177e4 444
5d337b91 445 spin_lock(&swap_lock);
1da177e4 446 if (nr_swap_pages <= 0)
fb4f88dc
HD
447 goto noswap;
448 nr_swap_pages--;
449
450 for (type = swap_list.next; type >= 0 && wrapped < 2; type = next) {
efa90a98 451 si = swap_info[type];
fb4f88dc
HD
452 next = si->next;
453 if (next < 0 ||
efa90a98 454 (!wrapped && si->prio != swap_info[next]->prio)) {
fb4f88dc
HD
455 next = swap_list.head;
456 wrapped++;
1da177e4 457 }
fb4f88dc
HD
458
459 if (!si->highest_bit)
460 continue;
461 if (!(si->flags & SWP_WRITEOK))
462 continue;
463
464 swap_list.next = next;
355cfa73 465 /* This is called for allocating swap entry for cache */
253d553b 466 offset = scan_swap_map(si, SWAP_HAS_CACHE);
5d337b91
HD
467 if (offset) {
468 spin_unlock(&swap_lock);
fb4f88dc 469 return swp_entry(type, offset);
5d337b91 470 }
fb4f88dc 471 next = swap_list.next;
1da177e4 472 }
fb4f88dc
HD
473
474 nr_swap_pages++;
475noswap:
5d337b91 476 spin_unlock(&swap_lock);
fb4f88dc 477 return (swp_entry_t) {0};
1da177e4
LT
478}
479
355cfa73 480/* The only caller of this function is now susupend routine */
3a291a20
RW
481swp_entry_t get_swap_page_of_type(int type)
482{
483 struct swap_info_struct *si;
484 pgoff_t offset;
485
486 spin_lock(&swap_lock);
efa90a98
HD
487 si = swap_info[type];
488 if (si && (si->flags & SWP_WRITEOK)) {
3a291a20 489 nr_swap_pages--;
355cfa73 490 /* This is called for allocating swap entry, not cache */
253d553b 491 offset = scan_swap_map(si, 1);
3a291a20
RW
492 if (offset) {
493 spin_unlock(&swap_lock);
494 return swp_entry(type, offset);
495 }
496 nr_swap_pages++;
497 }
498 spin_unlock(&swap_lock);
499 return (swp_entry_t) {0};
500}
501
73c34b6a 502static struct swap_info_struct *swap_info_get(swp_entry_t entry)
1da177e4 503{
73c34b6a 504 struct swap_info_struct *p;
1da177e4
LT
505 unsigned long offset, type;
506
507 if (!entry.val)
508 goto out;
509 type = swp_type(entry);
510 if (type >= nr_swapfiles)
511 goto bad_nofile;
efa90a98 512 p = swap_info[type];
1da177e4
LT
513 if (!(p->flags & SWP_USED))
514 goto bad_device;
515 offset = swp_offset(entry);
516 if (offset >= p->max)
517 goto bad_offset;
518 if (!p->swap_map[offset])
519 goto bad_free;
5d337b91 520 spin_lock(&swap_lock);
1da177e4
LT
521 return p;
522
523bad_free:
524 printk(KERN_ERR "swap_free: %s%08lx\n", Unused_offset, entry.val);
525 goto out;
526bad_offset:
527 printk(KERN_ERR "swap_free: %s%08lx\n", Bad_offset, entry.val);
528 goto out;
529bad_device:
530 printk(KERN_ERR "swap_free: %s%08lx\n", Unused_file, entry.val);
531 goto out;
532bad_nofile:
533 printk(KERN_ERR "swap_free: %s%08lx\n", Bad_file, entry.val);
534out:
535 return NULL;
886bb7e9 536}
1da177e4 537
8d69aaee
HD
538static unsigned char swap_entry_free(struct swap_info_struct *p,
539 swp_entry_t entry, unsigned char usage)
1da177e4 540{
253d553b 541 unsigned long offset = swp_offset(entry);
8d69aaee
HD
542 unsigned char count;
543 unsigned char has_cache;
355cfa73 544
253d553b
HD
545 count = p->swap_map[offset];
546 has_cache = count & SWAP_HAS_CACHE;
547 count &= ~SWAP_HAS_CACHE;
355cfa73 548
253d553b 549 if (usage == SWAP_HAS_CACHE) {
355cfa73 550 VM_BUG_ON(!has_cache);
253d553b 551 has_cache = 0;
aaa46865
HD
552 } else if (count == SWAP_MAP_SHMEM) {
553 /*
554 * Or we could insist on shmem.c using a special
555 * swap_shmem_free() and free_shmem_swap_and_cache()...
556 */
557 count = 0;
570a335b
HD
558 } else if ((count & ~COUNT_CONTINUED) <= SWAP_MAP_MAX) {
559 if (count == COUNT_CONTINUED) {
560 if (swap_count_continued(p, offset, count))
561 count = SWAP_MAP_MAX | COUNT_CONTINUED;
562 else
563 count = SWAP_MAP_MAX;
564 } else
565 count--;
566 }
253d553b
HD
567
568 if (!count)
569 mem_cgroup_uncharge_swap(entry);
570
571 usage = count | has_cache;
572 p->swap_map[offset] = usage;
355cfa73 573
355cfa73 574 /* free if no reference */
253d553b 575 if (!usage) {
355cfa73
KH
576 if (offset < p->lowest_bit)
577 p->lowest_bit = offset;
578 if (offset > p->highest_bit)
579 p->highest_bit = offset;
efa90a98
HD
580 if (swap_list.next >= 0 &&
581 p->prio > swap_info[swap_list.next]->prio)
582 swap_list.next = p->type;
355cfa73
KH
583 nr_swap_pages++;
584 p->inuse_pages--;
1da177e4 585 }
253d553b
HD
586
587 return usage;
1da177e4
LT
588}
589
590/*
591 * Caller has made sure that the swapdevice corresponding to entry
592 * is still around or has not been recycled.
593 */
594void swap_free(swp_entry_t entry)
595{
73c34b6a 596 struct swap_info_struct *p;
1da177e4
LT
597
598 p = swap_info_get(entry);
599 if (p) {
253d553b 600 swap_entry_free(p, entry, 1);
5d337b91 601 spin_unlock(&swap_lock);
1da177e4
LT
602 }
603}
604
cb4b86ba
KH
605/*
606 * Called after dropping swapcache to decrease refcnt to swap entries.
607 */
608void swapcache_free(swp_entry_t entry, struct page *page)
609{
355cfa73 610 struct swap_info_struct *p;
8d69aaee 611 unsigned char count;
355cfa73 612
355cfa73
KH
613 p = swap_info_get(entry);
614 if (p) {
253d553b
HD
615 count = swap_entry_free(p, entry, SWAP_HAS_CACHE);
616 if (page)
617 mem_cgroup_uncharge_swapcache(page, entry, count != 0);
355cfa73
KH
618 spin_unlock(&swap_lock);
619 }
cb4b86ba
KH
620}
621
1da177e4 622/*
c475a8ab 623 * How many references to page are currently swapped out?
570a335b
HD
624 * This does not give an exact answer when swap count is continued,
625 * but does include the high COUNT_CONTINUED flag to allow for that.
1da177e4 626 */
c475a8ab 627static inline int page_swapcount(struct page *page)
1da177e4 628{
c475a8ab
HD
629 int count = 0;
630 struct swap_info_struct *p;
1da177e4
LT
631 swp_entry_t entry;
632
4c21e2f2 633 entry.val = page_private(page);
1da177e4
LT
634 p = swap_info_get(entry);
635 if (p) {
355cfa73 636 count = swap_count(p->swap_map[swp_offset(entry)]);
5d337b91 637 spin_unlock(&swap_lock);
1da177e4 638 }
c475a8ab 639 return count;
1da177e4
LT
640}
641
642/*
7b1fe597
HD
643 * We can write to an anon page without COW if there are no other references
644 * to it. And as a side-effect, free up its swap: because the old content
645 * on disk will never be read, and seeking back there to write new content
646 * later would only waste time away from clustering.
1da177e4 647 */
7b1fe597 648int reuse_swap_page(struct page *page)
1da177e4 649{
c475a8ab
HD
650 int count;
651
51726b12 652 VM_BUG_ON(!PageLocked(page));
c475a8ab 653 count = page_mapcount(page);
7b1fe597 654 if (count <= 1 && PageSwapCache(page)) {
c475a8ab 655 count += page_swapcount(page);
7b1fe597
HD
656 if (count == 1 && !PageWriteback(page)) {
657 delete_from_swap_cache(page);
658 SetPageDirty(page);
659 }
660 }
c475a8ab 661 return count == 1;
1da177e4
LT
662}
663
664/*
a2c43eed
HD
665 * If swap is getting full, or if there are no more mappings of this page,
666 * then try_to_free_swap is called to free its swap space.
1da177e4 667 */
a2c43eed 668int try_to_free_swap(struct page *page)
1da177e4 669{
51726b12 670 VM_BUG_ON(!PageLocked(page));
1da177e4
LT
671
672 if (!PageSwapCache(page))
673 return 0;
674 if (PageWriteback(page))
675 return 0;
a2c43eed 676 if (page_swapcount(page))
1da177e4
LT
677 return 0;
678
a2c43eed
HD
679 delete_from_swap_cache(page);
680 SetPageDirty(page);
681 return 1;
68a22394
RR
682}
683
1da177e4
LT
684/*
685 * Free the swap entry like above, but also try to
686 * free the page cache entry if it is the last user.
687 */
2509ef26 688int free_swap_and_cache(swp_entry_t entry)
1da177e4 689{
2509ef26 690 struct swap_info_struct *p;
1da177e4
LT
691 struct page *page = NULL;
692
a7420aa5 693 if (non_swap_entry(entry))
2509ef26 694 return 1;
0697212a 695
1da177e4
LT
696 p = swap_info_get(entry);
697 if (p) {
253d553b 698 if (swap_entry_free(p, entry, 1) == SWAP_HAS_CACHE) {
93fac704 699 page = find_get_page(&swapper_space, entry.val);
8413ac9d 700 if (page && !trylock_page(page)) {
93fac704
NP
701 page_cache_release(page);
702 page = NULL;
703 }
704 }
5d337b91 705 spin_unlock(&swap_lock);
1da177e4
LT
706 }
707 if (page) {
a2c43eed
HD
708 /*
709 * Not mapped elsewhere, or swap space full? Free it!
710 * Also recheck PageSwapCache now page is locked (above).
711 */
93fac704 712 if (PageSwapCache(page) && !PageWriteback(page) &&
a2c43eed 713 (!page_mapped(page) || vm_swap_full())) {
1da177e4
LT
714 delete_from_swap_cache(page);
715 SetPageDirty(page);
716 }
717 unlock_page(page);
718 page_cache_release(page);
719 }
2509ef26 720 return p != NULL;
1da177e4
LT
721}
722
b0cb1a19 723#ifdef CONFIG_HIBERNATION
f577eb30 724/*
915bae9e 725 * Find the swap type that corresponds to given device (if any).
f577eb30 726 *
915bae9e
RW
727 * @offset - number of the PAGE_SIZE-sized block of the device, starting
728 * from 0, in which the swap header is expected to be located.
729 *
730 * This is needed for the suspend to disk (aka swsusp).
f577eb30 731 */
7bf23687 732int swap_type_of(dev_t device, sector_t offset, struct block_device **bdev_p)
f577eb30 733{
915bae9e 734 struct block_device *bdev = NULL;
efa90a98 735 int type;
f577eb30 736
915bae9e
RW
737 if (device)
738 bdev = bdget(device);
739
f577eb30 740 spin_lock(&swap_lock);
efa90a98
HD
741 for (type = 0; type < nr_swapfiles; type++) {
742 struct swap_info_struct *sis = swap_info[type];
f577eb30 743
915bae9e 744 if (!(sis->flags & SWP_WRITEOK))
f577eb30 745 continue;
b6b5bce3 746
915bae9e 747 if (!bdev) {
7bf23687 748 if (bdev_p)
dddac6a7 749 *bdev_p = bdgrab(sis->bdev);
7bf23687 750
6e1819d6 751 spin_unlock(&swap_lock);
efa90a98 752 return type;
6e1819d6 753 }
915bae9e 754 if (bdev == sis->bdev) {
9625a5f2 755 struct swap_extent *se = &sis->first_swap_extent;
915bae9e 756
915bae9e 757 if (se->start_block == offset) {
7bf23687 758 if (bdev_p)
dddac6a7 759 *bdev_p = bdgrab(sis->bdev);
7bf23687 760
915bae9e
RW
761 spin_unlock(&swap_lock);
762 bdput(bdev);
efa90a98 763 return type;
915bae9e 764 }
f577eb30
RW
765 }
766 }
767 spin_unlock(&swap_lock);
915bae9e
RW
768 if (bdev)
769 bdput(bdev);
770
f577eb30
RW
771 return -ENODEV;
772}
773
73c34b6a
HD
774/*
775 * Get the (PAGE_SIZE) block corresponding to given offset on the swapdev
776 * corresponding to given index in swap_info (swap type).
777 */
778sector_t swapdev_block(int type, pgoff_t offset)
779{
780 struct block_device *bdev;
781
782 if ((unsigned int)type >= nr_swapfiles)
783 return 0;
784 if (!(swap_info[type]->flags & SWP_WRITEOK))
785 return 0;
d4906e1a 786 return map_swap_entry(swp_entry(type, offset), &bdev);
73c34b6a
HD
787}
788
f577eb30
RW
789/*
790 * Return either the total number of swap pages of given type, or the number
791 * of free pages of that type (depending on @free)
792 *
793 * This is needed for software suspend
794 */
795unsigned int count_swap_pages(int type, int free)
796{
797 unsigned int n = 0;
798
efa90a98
HD
799 spin_lock(&swap_lock);
800 if ((unsigned int)type < nr_swapfiles) {
801 struct swap_info_struct *sis = swap_info[type];
802
803 if (sis->flags & SWP_WRITEOK) {
804 n = sis->pages;
f577eb30 805 if (free)
efa90a98 806 n -= sis->inuse_pages;
f577eb30 807 }
f577eb30 808 }
efa90a98 809 spin_unlock(&swap_lock);
f577eb30
RW
810 return n;
811}
73c34b6a 812#endif /* CONFIG_HIBERNATION */
f577eb30 813
1da177e4 814/*
72866f6f
HD
815 * No need to decide whether this PTE shares the swap entry with others,
816 * just let do_wp_page work it out if a write is requested later - to
817 * force COW, vm_page_prot omits write permission from any private vma.
1da177e4 818 */
044d66c1 819static int unuse_pte(struct vm_area_struct *vma, pmd_t *pmd,
1da177e4
LT
820 unsigned long addr, swp_entry_t entry, struct page *page)
821{
7a81b88c 822 struct mem_cgroup *ptr = NULL;
044d66c1
HD
823 spinlock_t *ptl;
824 pte_t *pte;
825 int ret = 1;
826
85d9fc89 827 if (mem_cgroup_try_charge_swapin(vma->vm_mm, page, GFP_KERNEL, &ptr)) {
044d66c1 828 ret = -ENOMEM;
85d9fc89
KH
829 goto out_nolock;
830 }
044d66c1
HD
831
832 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
833 if (unlikely(!pte_same(*pte, swp_entry_to_pte(entry)))) {
834 if (ret > 0)
7a81b88c 835 mem_cgroup_cancel_charge_swapin(ptr);
044d66c1
HD
836 ret = 0;
837 goto out;
838 }
8a9f3ccd 839
4294621f 840 inc_mm_counter(vma->vm_mm, anon_rss);
1da177e4
LT
841 get_page(page);
842 set_pte_at(vma->vm_mm, addr, pte,
843 pte_mkold(mk_pte(page, vma->vm_page_prot)));
844 page_add_anon_rmap(page, vma, addr);
7a81b88c 845 mem_cgroup_commit_charge_swapin(page, ptr);
1da177e4
LT
846 swap_free(entry);
847 /*
848 * Move the page to the active list so it is not
849 * immediately swapped out again after swapon.
850 */
851 activate_page(page);
044d66c1
HD
852out:
853 pte_unmap_unlock(pte, ptl);
85d9fc89 854out_nolock:
044d66c1 855 return ret;
1da177e4
LT
856}
857
858static int unuse_pte_range(struct vm_area_struct *vma, pmd_t *pmd,
859 unsigned long addr, unsigned long end,
860 swp_entry_t entry, struct page *page)
861{
1da177e4 862 pte_t swp_pte = swp_entry_to_pte(entry);
705e87c0 863 pte_t *pte;
8a9f3ccd 864 int ret = 0;
1da177e4 865
044d66c1
HD
866 /*
867 * We don't actually need pte lock while scanning for swp_pte: since
868 * we hold page lock and mmap_sem, swp_pte cannot be inserted into the
869 * page table while we're scanning; though it could get zapped, and on
870 * some architectures (e.g. x86_32 with PAE) we might catch a glimpse
871 * of unmatched parts which look like swp_pte, so unuse_pte must
872 * recheck under pte lock. Scanning without pte lock lets it be
873 * preemptible whenever CONFIG_PREEMPT but not CONFIG_HIGHPTE.
874 */
875 pte = pte_offset_map(pmd, addr);
1da177e4
LT
876 do {
877 /*
878 * swapoff spends a _lot_ of time in this loop!
879 * Test inline before going to call unuse_pte.
880 */
881 if (unlikely(pte_same(*pte, swp_pte))) {
044d66c1
HD
882 pte_unmap(pte);
883 ret = unuse_pte(vma, pmd, addr, entry, page);
884 if (ret)
885 goto out;
886 pte = pte_offset_map(pmd, addr);
1da177e4
LT
887 }
888 } while (pte++, addr += PAGE_SIZE, addr != end);
044d66c1
HD
889 pte_unmap(pte - 1);
890out:
8a9f3ccd 891 return ret;
1da177e4
LT
892}
893
894static inline int unuse_pmd_range(struct vm_area_struct *vma, pud_t *pud,
895 unsigned long addr, unsigned long end,
896 swp_entry_t entry, struct page *page)
897{
898 pmd_t *pmd;
899 unsigned long next;
8a9f3ccd 900 int ret;
1da177e4
LT
901
902 pmd = pmd_offset(pud, addr);
903 do {
904 next = pmd_addr_end(addr, end);
905 if (pmd_none_or_clear_bad(pmd))
906 continue;
8a9f3ccd
BS
907 ret = unuse_pte_range(vma, pmd, addr, next, entry, page);
908 if (ret)
909 return ret;
1da177e4
LT
910 } while (pmd++, addr = next, addr != end);
911 return 0;
912}
913
914static inline int unuse_pud_range(struct vm_area_struct *vma, pgd_t *pgd,
915 unsigned long addr, unsigned long end,
916 swp_entry_t entry, struct page *page)
917{
918 pud_t *pud;
919 unsigned long next;
8a9f3ccd 920 int ret;
1da177e4
LT
921
922 pud = pud_offset(pgd, addr);
923 do {
924 next = pud_addr_end(addr, end);
925 if (pud_none_or_clear_bad(pud))
926 continue;
8a9f3ccd
BS
927 ret = unuse_pmd_range(vma, pud, addr, next, entry, page);
928 if (ret)
929 return ret;
1da177e4
LT
930 } while (pud++, addr = next, addr != end);
931 return 0;
932}
933
934static int unuse_vma(struct vm_area_struct *vma,
935 swp_entry_t entry, struct page *page)
936{
937 pgd_t *pgd;
938 unsigned long addr, end, next;
8a9f3ccd 939 int ret;
1da177e4
LT
940
941 if (page->mapping) {
942 addr = page_address_in_vma(page, vma);
943 if (addr == -EFAULT)
944 return 0;
945 else
946 end = addr + PAGE_SIZE;
947 } else {
948 addr = vma->vm_start;
949 end = vma->vm_end;
950 }
951
952 pgd = pgd_offset(vma->vm_mm, addr);
953 do {
954 next = pgd_addr_end(addr, end);
955 if (pgd_none_or_clear_bad(pgd))
956 continue;
8a9f3ccd
BS
957 ret = unuse_pud_range(vma, pgd, addr, next, entry, page);
958 if (ret)
959 return ret;
1da177e4
LT
960 } while (pgd++, addr = next, addr != end);
961 return 0;
962}
963
964static int unuse_mm(struct mm_struct *mm,
965 swp_entry_t entry, struct page *page)
966{
967 struct vm_area_struct *vma;
8a9f3ccd 968 int ret = 0;
1da177e4
LT
969
970 if (!down_read_trylock(&mm->mmap_sem)) {
971 /*
7d03431c
FLVC
972 * Activate page so shrink_inactive_list is unlikely to unmap
973 * its ptes while lock is dropped, so swapoff can make progress.
1da177e4 974 */
c475a8ab 975 activate_page(page);
1da177e4
LT
976 unlock_page(page);
977 down_read(&mm->mmap_sem);
978 lock_page(page);
979 }
1da177e4 980 for (vma = mm->mmap; vma; vma = vma->vm_next) {
8a9f3ccd 981 if (vma->anon_vma && (ret = unuse_vma(vma, entry, page)))
1da177e4
LT
982 break;
983 }
1da177e4 984 up_read(&mm->mmap_sem);
8a9f3ccd 985 return (ret < 0)? ret: 0;
1da177e4
LT
986}
987
988/*
989 * Scan swap_map from current position to next entry still in use.
990 * Recycle to start on reaching the end, returning 0 when empty.
991 */
6eb396dc
HD
992static unsigned int find_next_to_unuse(struct swap_info_struct *si,
993 unsigned int prev)
1da177e4 994{
6eb396dc
HD
995 unsigned int max = si->max;
996 unsigned int i = prev;
8d69aaee 997 unsigned char count;
1da177e4
LT
998
999 /*
5d337b91 1000 * No need for swap_lock here: we're just looking
1da177e4
LT
1001 * for whether an entry is in use, not modifying it; false
1002 * hits are okay, and sys_swapoff() has already prevented new
5d337b91 1003 * allocations from this area (while holding swap_lock).
1da177e4
LT
1004 */
1005 for (;;) {
1006 if (++i >= max) {
1007 if (!prev) {
1008 i = 0;
1009 break;
1010 }
1011 /*
1012 * No entries in use at top of swap_map,
1013 * loop back to start and recheck there.
1014 */
1015 max = prev + 1;
1016 prev = 0;
1017 i = 1;
1018 }
1019 count = si->swap_map[i];
355cfa73 1020 if (count && swap_count(count) != SWAP_MAP_BAD)
1da177e4
LT
1021 break;
1022 }
1023 return i;
1024}
1025
1026/*
1027 * We completely avoid races by reading each swap page in advance,
1028 * and then search for the process using it. All the necessary
1029 * page table adjustments can then be made atomically.
1030 */
1031static int try_to_unuse(unsigned int type)
1032{
efa90a98 1033 struct swap_info_struct *si = swap_info[type];
1da177e4 1034 struct mm_struct *start_mm;
8d69aaee
HD
1035 unsigned char *swap_map;
1036 unsigned char swcount;
1da177e4
LT
1037 struct page *page;
1038 swp_entry_t entry;
6eb396dc 1039 unsigned int i = 0;
1da177e4 1040 int retval = 0;
1da177e4
LT
1041
1042 /*
1043 * When searching mms for an entry, a good strategy is to
1044 * start at the first mm we freed the previous entry from
1045 * (though actually we don't notice whether we or coincidence
1046 * freed the entry). Initialize this start_mm with a hold.
1047 *
1048 * A simpler strategy would be to start at the last mm we
1049 * freed the previous entry from; but that would take less
1050 * advantage of mmlist ordering, which clusters forked mms
1051 * together, child after parent. If we race with dup_mmap(), we
1052 * prefer to resolve parent before child, lest we miss entries
1053 * duplicated after we scanned child: using last mm would invert
570a335b 1054 * that.
1da177e4
LT
1055 */
1056 start_mm = &init_mm;
1057 atomic_inc(&init_mm.mm_users);
1058
1059 /*
1060 * Keep on scanning until all entries have gone. Usually,
1061 * one pass through swap_map is enough, but not necessarily:
1062 * there are races when an instance of an entry might be missed.
1063 */
1064 while ((i = find_next_to_unuse(si, i)) != 0) {
1065 if (signal_pending(current)) {
1066 retval = -EINTR;
1067 break;
1068 }
1069
886bb7e9 1070 /*
1da177e4
LT
1071 * Get a page for the entry, using the existing swap
1072 * cache page if there is one. Otherwise, get a clean
886bb7e9 1073 * page and read the swap into it.
1da177e4
LT
1074 */
1075 swap_map = &si->swap_map[i];
1076 entry = swp_entry(type, i);
02098fea
HD
1077 page = read_swap_cache_async(entry,
1078 GFP_HIGHUSER_MOVABLE, NULL, 0);
1da177e4
LT
1079 if (!page) {
1080 /*
1081 * Either swap_duplicate() failed because entry
1082 * has been freed independently, and will not be
1083 * reused since sys_swapoff() already disabled
1084 * allocation from here, or alloc_page() failed.
1085 */
1086 if (!*swap_map)
1087 continue;
1088 retval = -ENOMEM;
1089 break;
1090 }
1091
1092 /*
1093 * Don't hold on to start_mm if it looks like exiting.
1094 */
1095 if (atomic_read(&start_mm->mm_users) == 1) {
1096 mmput(start_mm);
1097 start_mm = &init_mm;
1098 atomic_inc(&init_mm.mm_users);
1099 }
1100
1101 /*
1102 * Wait for and lock page. When do_swap_page races with
1103 * try_to_unuse, do_swap_page can handle the fault much
1104 * faster than try_to_unuse can locate the entry. This
1105 * apparently redundant "wait_on_page_locked" lets try_to_unuse
1106 * defer to do_swap_page in such a case - in some tests,
1107 * do_swap_page and try_to_unuse repeatedly compete.
1108 */
1109 wait_on_page_locked(page);
1110 wait_on_page_writeback(page);
1111 lock_page(page);
1112 wait_on_page_writeback(page);
1113
1114 /*
1115 * Remove all references to entry.
1da177e4 1116 */
1da177e4 1117 swcount = *swap_map;
aaa46865
HD
1118 if (swap_count(swcount) == SWAP_MAP_SHMEM) {
1119 retval = shmem_unuse(entry, page);
1120 /* page has already been unlocked and released */
1121 if (retval < 0)
1122 break;
1123 continue;
1da177e4 1124 }
aaa46865
HD
1125 if (swap_count(swcount) && start_mm != &init_mm)
1126 retval = unuse_mm(start_mm, entry, page);
1127
355cfa73 1128 if (swap_count(*swap_map)) {
1da177e4
LT
1129 int set_start_mm = (*swap_map >= swcount);
1130 struct list_head *p = &start_mm->mmlist;
1131 struct mm_struct *new_start_mm = start_mm;
1132 struct mm_struct *prev_mm = start_mm;
1133 struct mm_struct *mm;
1134
1135 atomic_inc(&new_start_mm->mm_users);
1136 atomic_inc(&prev_mm->mm_users);
1137 spin_lock(&mmlist_lock);
aaa46865 1138 while (swap_count(*swap_map) && !retval &&
1da177e4
LT
1139 (p = p->next) != &start_mm->mmlist) {
1140 mm = list_entry(p, struct mm_struct, mmlist);
70af7c5c 1141 if (!atomic_inc_not_zero(&mm->mm_users))
1da177e4 1142 continue;
1da177e4
LT
1143 spin_unlock(&mmlist_lock);
1144 mmput(prev_mm);
1145 prev_mm = mm;
1146
1147 cond_resched();
1148
1149 swcount = *swap_map;
355cfa73 1150 if (!swap_count(swcount)) /* any usage ? */
1da177e4 1151 ;
aaa46865 1152 else if (mm == &init_mm)
1da177e4 1153 set_start_mm = 1;
aaa46865 1154 else
1da177e4 1155 retval = unuse_mm(mm, entry, page);
355cfa73 1156
32c5fc10 1157 if (set_start_mm && *swap_map < swcount) {
1da177e4
LT
1158 mmput(new_start_mm);
1159 atomic_inc(&mm->mm_users);
1160 new_start_mm = mm;
1161 set_start_mm = 0;
1162 }
1163 spin_lock(&mmlist_lock);
1164 }
1165 spin_unlock(&mmlist_lock);
1166 mmput(prev_mm);
1167 mmput(start_mm);
1168 start_mm = new_start_mm;
1169 }
1170 if (retval) {
1171 unlock_page(page);
1172 page_cache_release(page);
1173 break;
1174 }
1175
1da177e4
LT
1176 /*
1177 * If a reference remains (rare), we would like to leave
1178 * the page in the swap cache; but try_to_unmap could
1179 * then re-duplicate the entry once we drop page lock,
1180 * so we might loop indefinitely; also, that page could
1181 * not be swapped out to other storage meanwhile. So:
1182 * delete from cache even if there's another reference,
1183 * after ensuring that the data has been saved to disk -
1184 * since if the reference remains (rarer), it will be
1185 * read from disk into another page. Splitting into two
1186 * pages would be incorrect if swap supported "shared
1187 * private" pages, but they are handled by tmpfs files.
1da177e4 1188 */
355cfa73
KH
1189 if (swap_count(*swap_map) &&
1190 PageDirty(page) && PageSwapCache(page)) {
1da177e4
LT
1191 struct writeback_control wbc = {
1192 .sync_mode = WB_SYNC_NONE,
1193 };
1194
1195 swap_writepage(page, &wbc);
1196 lock_page(page);
1197 wait_on_page_writeback(page);
1198 }
68bdc8d6
HD
1199
1200 /*
1201 * It is conceivable that a racing task removed this page from
1202 * swap cache just before we acquired the page lock at the top,
1203 * or while we dropped it in unuse_mm(). The page might even
1204 * be back in swap cache on another swap area: that we must not
1205 * delete, since it may not have been written out to swap yet.
1206 */
1207 if (PageSwapCache(page) &&
1208 likely(page_private(page) == entry.val))
2e0e26c7 1209 delete_from_swap_cache(page);
1da177e4
LT
1210
1211 /*
1212 * So we could skip searching mms once swap count went
1213 * to 1, we did not mark any present ptes as dirty: must
2706a1b8 1214 * mark page dirty so shrink_page_list will preserve it.
1da177e4
LT
1215 */
1216 SetPageDirty(page);
1217 unlock_page(page);
1218 page_cache_release(page);
1219
1220 /*
1221 * Make sure that we aren't completely killing
1222 * interactive performance.
1223 */
1224 cond_resched();
1225 }
1226
1227 mmput(start_mm);
1da177e4
LT
1228 return retval;
1229}
1230
1231/*
5d337b91
HD
1232 * After a successful try_to_unuse, if no swap is now in use, we know
1233 * we can empty the mmlist. swap_lock must be held on entry and exit.
1234 * Note that mmlist_lock nests inside swap_lock, and an mm must be
1da177e4
LT
1235 * added to the mmlist just after page_duplicate - before would be racy.
1236 */
1237static void drain_mmlist(void)
1238{
1239 struct list_head *p, *next;
efa90a98 1240 unsigned int type;
1da177e4 1241
efa90a98
HD
1242 for (type = 0; type < nr_swapfiles; type++)
1243 if (swap_info[type]->inuse_pages)
1da177e4
LT
1244 return;
1245 spin_lock(&mmlist_lock);
1246 list_for_each_safe(p, next, &init_mm.mmlist)
1247 list_del_init(p);
1248 spin_unlock(&mmlist_lock);
1249}
1250
1251/*
1252 * Use this swapdev's extent info to locate the (PAGE_SIZE) block which
d4906e1a
LS
1253 * corresponds to page offset for the specified swap entry.
1254 * Note that the type of this function is sector_t, but it returns page offset
1255 * into the bdev, not sector offset.
1da177e4 1256 */
d4906e1a 1257static sector_t map_swap_entry(swp_entry_t entry, struct block_device **bdev)
1da177e4 1258{
f29ad6a9
HD
1259 struct swap_info_struct *sis;
1260 struct swap_extent *start_se;
1261 struct swap_extent *se;
1262 pgoff_t offset;
1263
efa90a98 1264 sis = swap_info[swp_type(entry)];
f29ad6a9
HD
1265 *bdev = sis->bdev;
1266
1267 offset = swp_offset(entry);
1268 start_se = sis->curr_swap_extent;
1269 se = start_se;
1da177e4
LT
1270
1271 for ( ; ; ) {
1272 struct list_head *lh;
1273
1274 if (se->start_page <= offset &&
1275 offset < (se->start_page + se->nr_pages)) {
1276 return se->start_block + (offset - se->start_page);
1277 }
11d31886 1278 lh = se->list.next;
1da177e4
LT
1279 se = list_entry(lh, struct swap_extent, list);
1280 sis->curr_swap_extent = se;
1281 BUG_ON(se == start_se); /* It *must* be present */
1282 }
1283}
1284
d4906e1a
LS
1285/*
1286 * Returns the page offset into bdev for the specified page's swap entry.
1287 */
1288sector_t map_swap_page(struct page *page, struct block_device **bdev)
1289{
1290 swp_entry_t entry;
1291 entry.val = page_private(page);
1292 return map_swap_entry(entry, bdev);
1293}
1294
1da177e4
LT
1295/*
1296 * Free all of a swapdev's extent information
1297 */
1298static void destroy_swap_extents(struct swap_info_struct *sis)
1299{
9625a5f2 1300 while (!list_empty(&sis->first_swap_extent.list)) {
1da177e4
LT
1301 struct swap_extent *se;
1302
9625a5f2 1303 se = list_entry(sis->first_swap_extent.list.next,
1da177e4
LT
1304 struct swap_extent, list);
1305 list_del(&se->list);
1306 kfree(se);
1307 }
1da177e4
LT
1308}
1309
1310/*
1311 * Add a block range (and the corresponding page range) into this swapdev's
11d31886 1312 * extent list. The extent list is kept sorted in page order.
1da177e4 1313 *
11d31886 1314 * This function rather assumes that it is called in ascending page order.
1da177e4
LT
1315 */
1316static int
1317add_swap_extent(struct swap_info_struct *sis, unsigned long start_page,
1318 unsigned long nr_pages, sector_t start_block)
1319{
1320 struct swap_extent *se;
1321 struct swap_extent *new_se;
1322 struct list_head *lh;
1323
9625a5f2
HD
1324 if (start_page == 0) {
1325 se = &sis->first_swap_extent;
1326 sis->curr_swap_extent = se;
1327 se->start_page = 0;
1328 se->nr_pages = nr_pages;
1329 se->start_block = start_block;
1330 return 1;
1331 } else {
1332 lh = sis->first_swap_extent.list.prev; /* Highest extent */
1da177e4 1333 se = list_entry(lh, struct swap_extent, list);
11d31886
HD
1334 BUG_ON(se->start_page + se->nr_pages != start_page);
1335 if (se->start_block + se->nr_pages == start_block) {
1da177e4
LT
1336 /* Merge it */
1337 se->nr_pages += nr_pages;
1338 return 0;
1339 }
1da177e4
LT
1340 }
1341
1342 /*
1343 * No merge. Insert a new extent, preserving ordering.
1344 */
1345 new_se = kmalloc(sizeof(*se), GFP_KERNEL);
1346 if (new_se == NULL)
1347 return -ENOMEM;
1348 new_se->start_page = start_page;
1349 new_se->nr_pages = nr_pages;
1350 new_se->start_block = start_block;
1351
9625a5f2 1352 list_add_tail(&new_se->list, &sis->first_swap_extent.list);
53092a74 1353 return 1;
1da177e4
LT
1354}
1355
1356/*
1357 * A `swap extent' is a simple thing which maps a contiguous range of pages
1358 * onto a contiguous range of disk blocks. An ordered list of swap extents
1359 * is built at swapon time and is then used at swap_writepage/swap_readpage
1360 * time for locating where on disk a page belongs.
1361 *
1362 * If the swapfile is an S_ISBLK block device, a single extent is installed.
1363 * This is done so that the main operating code can treat S_ISBLK and S_ISREG
1364 * swap files identically.
1365 *
1366 * Whether the swapdev is an S_ISREG file or an S_ISBLK blockdev, the swap
1367 * extent list operates in PAGE_SIZE disk blocks. Both S_ISREG and S_ISBLK
1368 * swapfiles are handled *identically* after swapon time.
1369 *
1370 * For S_ISREG swapfiles, setup_swap_extents() will walk all the file's blocks
1371 * and will parse them into an ordered extent list, in PAGE_SIZE chunks. If
1372 * some stray blocks are found which do not fall within the PAGE_SIZE alignment
1373 * requirements, they are simply tossed out - we will never use those blocks
1374 * for swapping.
1375 *
b0d9bcd4 1376 * For S_ISREG swapfiles we set S_SWAPFILE across the life of the swapon. This
1da177e4
LT
1377 * prevents root from shooting her foot off by ftruncating an in-use swapfile,
1378 * which will scribble on the fs.
1379 *
1380 * The amount of disk space which a single swap extent represents varies.
1381 * Typically it is in the 1-4 megabyte range. So we can have hundreds of
1382 * extents in the list. To avoid much list walking, we cache the previous
1383 * search location in `curr_swap_extent', and start new searches from there.
1384 * This is extremely effective. The average number of iterations in
1385 * map_swap_page() has been measured at about 0.3 per page. - akpm.
1386 */
53092a74 1387static int setup_swap_extents(struct swap_info_struct *sis, sector_t *span)
1da177e4
LT
1388{
1389 struct inode *inode;
1390 unsigned blocks_per_page;
1391 unsigned long page_no;
1392 unsigned blkbits;
1393 sector_t probe_block;
1394 sector_t last_block;
53092a74
HD
1395 sector_t lowest_block = -1;
1396 sector_t highest_block = 0;
1397 int nr_extents = 0;
1da177e4
LT
1398 int ret;
1399
1400 inode = sis->swap_file->f_mapping->host;
1401 if (S_ISBLK(inode->i_mode)) {
1402 ret = add_swap_extent(sis, 0, sis->max, 0);
53092a74 1403 *span = sis->pages;
9625a5f2 1404 goto out;
1da177e4
LT
1405 }
1406
1407 blkbits = inode->i_blkbits;
1408 blocks_per_page = PAGE_SIZE >> blkbits;
1409
1410 /*
1411 * Map all the blocks into the extent list. This code doesn't try
1412 * to be very smart.
1413 */
1414 probe_block = 0;
1415 page_no = 0;
1416 last_block = i_size_read(inode) >> blkbits;
1417 while ((probe_block + blocks_per_page) <= last_block &&
1418 page_no < sis->max) {
1419 unsigned block_in_page;
1420 sector_t first_block;
1421
1422 first_block = bmap(inode, probe_block);
1423 if (first_block == 0)
1424 goto bad_bmap;
1425
1426 /*
1427 * It must be PAGE_SIZE aligned on-disk
1428 */
1429 if (first_block & (blocks_per_page - 1)) {
1430 probe_block++;
1431 goto reprobe;
1432 }
1433
1434 for (block_in_page = 1; block_in_page < blocks_per_page;
1435 block_in_page++) {
1436 sector_t block;
1437
1438 block = bmap(inode, probe_block + block_in_page);
1439 if (block == 0)
1440 goto bad_bmap;
1441 if (block != first_block + block_in_page) {
1442 /* Discontiguity */
1443 probe_block++;
1444 goto reprobe;
1445 }
1446 }
1447
53092a74
HD
1448 first_block >>= (PAGE_SHIFT - blkbits);
1449 if (page_no) { /* exclude the header page */
1450 if (first_block < lowest_block)
1451 lowest_block = first_block;
1452 if (first_block > highest_block)
1453 highest_block = first_block;
1454 }
1455
1da177e4
LT
1456 /*
1457 * We found a PAGE_SIZE-length, PAGE_SIZE-aligned run of blocks
1458 */
53092a74
HD
1459 ret = add_swap_extent(sis, page_no, 1, first_block);
1460 if (ret < 0)
1da177e4 1461 goto out;
53092a74 1462 nr_extents += ret;
1da177e4
LT
1463 page_no++;
1464 probe_block += blocks_per_page;
1465reprobe:
1466 continue;
1467 }
53092a74
HD
1468 ret = nr_extents;
1469 *span = 1 + highest_block - lowest_block;
1da177e4 1470 if (page_no == 0)
e2244ec2 1471 page_no = 1; /* force Empty message */
1da177e4 1472 sis->max = page_no;
e2244ec2 1473 sis->pages = page_no - 1;
1da177e4 1474 sis->highest_bit = page_no - 1;
9625a5f2
HD
1475out:
1476 return ret;
1da177e4
LT
1477bad_bmap:
1478 printk(KERN_ERR "swapon: swapfile has holes\n");
1479 ret = -EINVAL;
9625a5f2 1480 goto out;
1da177e4
LT
1481}
1482
c4ea37c2 1483SYSCALL_DEFINE1(swapoff, const char __user *, specialfile)
1da177e4 1484{
73c34b6a 1485 struct swap_info_struct *p = NULL;
8d69aaee 1486 unsigned char *swap_map;
1da177e4
LT
1487 struct file *swap_file, *victim;
1488 struct address_space *mapping;
1489 struct inode *inode;
73c34b6a 1490 char *pathname;
1da177e4
LT
1491 int i, type, prev;
1492 int err;
886bb7e9 1493
1da177e4
LT
1494 if (!capable(CAP_SYS_ADMIN))
1495 return -EPERM;
1496
1497 pathname = getname(specialfile);
1498 err = PTR_ERR(pathname);
1499 if (IS_ERR(pathname))
1500 goto out;
1501
1502 victim = filp_open(pathname, O_RDWR|O_LARGEFILE, 0);
1503 putname(pathname);
1504 err = PTR_ERR(victim);
1505 if (IS_ERR(victim))
1506 goto out;
1507
1508 mapping = victim->f_mapping;
1509 prev = -1;
5d337b91 1510 spin_lock(&swap_lock);
efa90a98
HD
1511 for (type = swap_list.head; type >= 0; type = swap_info[type]->next) {
1512 p = swap_info[type];
22c6f8fd 1513 if (p->flags & SWP_WRITEOK) {
1da177e4
LT
1514 if (p->swap_file->f_mapping == mapping)
1515 break;
1516 }
1517 prev = type;
1518 }
1519 if (type < 0) {
1520 err = -EINVAL;
5d337b91 1521 spin_unlock(&swap_lock);
1da177e4
LT
1522 goto out_dput;
1523 }
1524 if (!security_vm_enough_memory(p->pages))
1525 vm_unacct_memory(p->pages);
1526 else {
1527 err = -ENOMEM;
5d337b91 1528 spin_unlock(&swap_lock);
1da177e4
LT
1529 goto out_dput;
1530 }
efa90a98 1531 if (prev < 0)
1da177e4 1532 swap_list.head = p->next;
efa90a98
HD
1533 else
1534 swap_info[prev]->next = p->next;
1da177e4
LT
1535 if (type == swap_list.next) {
1536 /* just pick something that's safe... */
1537 swap_list.next = swap_list.head;
1538 }
78ecba08 1539 if (p->prio < 0) {
efa90a98
HD
1540 for (i = p->next; i >= 0; i = swap_info[i]->next)
1541 swap_info[i]->prio = p->prio--;
78ecba08
HD
1542 least_priority++;
1543 }
1da177e4
LT
1544 nr_swap_pages -= p->pages;
1545 total_swap_pages -= p->pages;
1546 p->flags &= ~SWP_WRITEOK;
5d337b91 1547 spin_unlock(&swap_lock);
fb4f88dc 1548
35451bee 1549 current->flags |= PF_OOM_ORIGIN;
1da177e4 1550 err = try_to_unuse(type);
35451bee 1551 current->flags &= ~PF_OOM_ORIGIN;
1da177e4 1552
1da177e4
LT
1553 if (err) {
1554 /* re-insert swap space back into swap_list */
5d337b91 1555 spin_lock(&swap_lock);
78ecba08
HD
1556 if (p->prio < 0)
1557 p->prio = --least_priority;
1558 prev = -1;
efa90a98
HD
1559 for (i = swap_list.head; i >= 0; i = swap_info[i]->next) {
1560 if (p->prio >= swap_info[i]->prio)
1da177e4 1561 break;
78ecba08
HD
1562 prev = i;
1563 }
1da177e4
LT
1564 p->next = i;
1565 if (prev < 0)
efa90a98 1566 swap_list.head = swap_list.next = type;
1da177e4 1567 else
efa90a98 1568 swap_info[prev]->next = type;
1da177e4
LT
1569 nr_swap_pages += p->pages;
1570 total_swap_pages += p->pages;
1571 p->flags |= SWP_WRITEOK;
5d337b91 1572 spin_unlock(&swap_lock);
1da177e4
LT
1573 goto out_dput;
1574 }
52b7efdb
HD
1575
1576 /* wait for any unplug function to finish */
1577 down_write(&swap_unplug_sem);
1578 up_write(&swap_unplug_sem);
1579
5d337b91 1580 destroy_swap_extents(p);
570a335b
HD
1581 if (p->flags & SWP_CONTINUED)
1582 free_swap_count_continuations(p);
1583
fc0abb14 1584 mutex_lock(&swapon_mutex);
5d337b91
HD
1585 spin_lock(&swap_lock);
1586 drain_mmlist();
1587
52b7efdb 1588 /* wait for anyone still in scan_swap_map */
52b7efdb
HD
1589 p->highest_bit = 0; /* cuts scans short */
1590 while (p->flags >= SWP_SCANNING) {
5d337b91 1591 spin_unlock(&swap_lock);
13e4b57f 1592 schedule_timeout_uninterruptible(1);
5d337b91 1593 spin_lock(&swap_lock);
52b7efdb 1594 }
52b7efdb 1595
1da177e4
LT
1596 swap_file = p->swap_file;
1597 p->swap_file = NULL;
1598 p->max = 0;
1599 swap_map = p->swap_map;
1600 p->swap_map = NULL;
1601 p->flags = 0;
5d337b91 1602 spin_unlock(&swap_lock);
fc0abb14 1603 mutex_unlock(&swapon_mutex);
1da177e4 1604 vfree(swap_map);
27a7faa0
KH
1605 /* Destroy swap account informatin */
1606 swap_cgroup_swapoff(type);
1607
1da177e4
LT
1608 inode = mapping->host;
1609 if (S_ISBLK(inode->i_mode)) {
1610 struct block_device *bdev = I_BDEV(inode);
1611 set_blocksize(bdev, p->old_block_size);
1612 bd_release(bdev);
1613 } else {
1b1dcc1b 1614 mutex_lock(&inode->i_mutex);
1da177e4 1615 inode->i_flags &= ~S_SWAPFILE;
1b1dcc1b 1616 mutex_unlock(&inode->i_mutex);
1da177e4
LT
1617 }
1618 filp_close(swap_file, NULL);
1619 err = 0;
1620
1621out_dput:
1622 filp_close(victim, NULL);
1623out:
1624 return err;
1625}
1626
1627#ifdef CONFIG_PROC_FS
1628/* iterator */
1629static void *swap_start(struct seq_file *swap, loff_t *pos)
1630{
efa90a98
HD
1631 struct swap_info_struct *si;
1632 int type;
1da177e4
LT
1633 loff_t l = *pos;
1634
fc0abb14 1635 mutex_lock(&swapon_mutex);
1da177e4 1636
881e4aab
SS
1637 if (!l)
1638 return SEQ_START_TOKEN;
1639
efa90a98
HD
1640 for (type = 0; type < nr_swapfiles; type++) {
1641 smp_rmb(); /* read nr_swapfiles before swap_info[type] */
1642 si = swap_info[type];
1643 if (!(si->flags & SWP_USED) || !si->swap_map)
1da177e4 1644 continue;
881e4aab 1645 if (!--l)
efa90a98 1646 return si;
1da177e4
LT
1647 }
1648
1649 return NULL;
1650}
1651
1652static void *swap_next(struct seq_file *swap, void *v, loff_t *pos)
1653{
efa90a98
HD
1654 struct swap_info_struct *si = v;
1655 int type;
1da177e4 1656
881e4aab 1657 if (v == SEQ_START_TOKEN)
efa90a98
HD
1658 type = 0;
1659 else
1660 type = si->type + 1;
881e4aab 1661
efa90a98
HD
1662 for (; type < nr_swapfiles; type++) {
1663 smp_rmb(); /* read nr_swapfiles before swap_info[type] */
1664 si = swap_info[type];
1665 if (!(si->flags & SWP_USED) || !si->swap_map)
1da177e4
LT
1666 continue;
1667 ++*pos;
efa90a98 1668 return si;
1da177e4
LT
1669 }
1670
1671 return NULL;
1672}
1673
1674static void swap_stop(struct seq_file *swap, void *v)
1675{
fc0abb14 1676 mutex_unlock(&swapon_mutex);
1da177e4
LT
1677}
1678
1679static int swap_show(struct seq_file *swap, void *v)
1680{
efa90a98 1681 struct swap_info_struct *si = v;
1da177e4
LT
1682 struct file *file;
1683 int len;
1684
efa90a98 1685 if (si == SEQ_START_TOKEN) {
881e4aab
SS
1686 seq_puts(swap,"Filename\t\t\t\tType\t\tSize\tUsed\tPriority\n");
1687 return 0;
1688 }
1da177e4 1689
efa90a98 1690 file = si->swap_file;
c32c2f63 1691 len = seq_path(swap, &file->f_path, " \t\n\\");
6eb396dc 1692 seq_printf(swap, "%*s%s\t%u\t%u\t%d\n",
886bb7e9
HD
1693 len < 40 ? 40 - len : 1, " ",
1694 S_ISBLK(file->f_path.dentry->d_inode->i_mode) ?
1da177e4 1695 "partition" : "file\t",
efa90a98
HD
1696 si->pages << (PAGE_SHIFT - 10),
1697 si->inuse_pages << (PAGE_SHIFT - 10),
1698 si->prio);
1da177e4
LT
1699 return 0;
1700}
1701
15ad7cdc 1702static const struct seq_operations swaps_op = {
1da177e4
LT
1703 .start = swap_start,
1704 .next = swap_next,
1705 .stop = swap_stop,
1706 .show = swap_show
1707};
1708
1709static int swaps_open(struct inode *inode, struct file *file)
1710{
1711 return seq_open(file, &swaps_op);
1712}
1713
15ad7cdc 1714static const struct file_operations proc_swaps_operations = {
1da177e4
LT
1715 .open = swaps_open,
1716 .read = seq_read,
1717 .llseek = seq_lseek,
1718 .release = seq_release,
1719};
1720
1721static int __init procswaps_init(void)
1722{
3d71f86f 1723 proc_create("swaps", 0, NULL, &proc_swaps_operations);
1da177e4
LT
1724 return 0;
1725}
1726__initcall(procswaps_init);
1727#endif /* CONFIG_PROC_FS */
1728
1796316a
JB
1729#ifdef MAX_SWAPFILES_CHECK
1730static int __init max_swapfiles_check(void)
1731{
1732 MAX_SWAPFILES_CHECK();
1733 return 0;
1734}
1735late_initcall(max_swapfiles_check);
1736#endif
1737
1da177e4
LT
1738/*
1739 * Written 01/25/92 by Simmule Turner, heavily changed by Linus.
1740 *
1741 * The swapon system call
1742 */
c4ea37c2 1743SYSCALL_DEFINE2(swapon, const char __user *, specialfile, int, swap_flags)
1da177e4 1744{
73c34b6a 1745 struct swap_info_struct *p;
1da177e4
LT
1746 char *name = NULL;
1747 struct block_device *bdev = NULL;
1748 struct file *swap_file = NULL;
1749 struct address_space *mapping;
1750 unsigned int type;
1751 int i, prev;
1752 int error;
1da177e4 1753 union swap_header *swap_header = NULL;
6eb396dc
HD
1754 unsigned int nr_good_pages = 0;
1755 int nr_extents = 0;
53092a74 1756 sector_t span;
1da177e4 1757 unsigned long maxpages = 1;
73fd8748 1758 unsigned long swapfilepages;
8d69aaee 1759 unsigned char *swap_map = NULL;
1da177e4
LT
1760 struct page *page = NULL;
1761 struct inode *inode = NULL;
1762 int did_down = 0;
1763
1764 if (!capable(CAP_SYS_ADMIN))
1765 return -EPERM;
efa90a98
HD
1766
1767 p = kzalloc(sizeof(*p), GFP_KERNEL);
1768 if (!p)
1769 return -ENOMEM;
1770
5d337b91 1771 spin_lock(&swap_lock);
efa90a98
HD
1772 for (type = 0; type < nr_swapfiles; type++) {
1773 if (!(swap_info[type]->flags & SWP_USED))
1da177e4 1774 break;
efa90a98 1775 }
1da177e4 1776 error = -EPERM;
0697212a 1777 if (type >= MAX_SWAPFILES) {
5d337b91 1778 spin_unlock(&swap_lock);
efa90a98 1779 kfree(p);
1da177e4
LT
1780 goto out;
1781 }
efa90a98
HD
1782 if (type >= nr_swapfiles) {
1783 p->type = type;
1784 swap_info[type] = p;
1785 /*
1786 * Write swap_info[type] before nr_swapfiles, in case a
1787 * racing procfs swap_start() or swap_next() is reading them.
1788 * (We never shrink nr_swapfiles, we never free this entry.)
1789 */
1790 smp_wmb();
1791 nr_swapfiles++;
1792 } else {
1793 kfree(p);
1794 p = swap_info[type];
1795 /*
1796 * Do not memset this entry: a racing procfs swap_next()
1797 * would be relying on p->type to remain valid.
1798 */
1799 }
9625a5f2 1800 INIT_LIST_HEAD(&p->first_swap_extent.list);
1da177e4 1801 p->flags = SWP_USED;
1da177e4 1802 p->next = -1;
5d337b91 1803 spin_unlock(&swap_lock);
efa90a98 1804
1da177e4
LT
1805 name = getname(specialfile);
1806 error = PTR_ERR(name);
1807 if (IS_ERR(name)) {
1808 name = NULL;
1809 goto bad_swap_2;
1810 }
1811 swap_file = filp_open(name, O_RDWR|O_LARGEFILE, 0);
1812 error = PTR_ERR(swap_file);
1813 if (IS_ERR(swap_file)) {
1814 swap_file = NULL;
1815 goto bad_swap_2;
1816 }
1817
1818 p->swap_file = swap_file;
1819 mapping = swap_file->f_mapping;
1820 inode = mapping->host;
1821
1822 error = -EBUSY;
1823 for (i = 0; i < nr_swapfiles; i++) {
efa90a98 1824 struct swap_info_struct *q = swap_info[i];
1da177e4
LT
1825
1826 if (i == type || !q->swap_file)
1827 continue;
1828 if (mapping == q->swap_file->f_mapping)
1829 goto bad_swap;
1830 }
1831
1832 error = -EINVAL;
1833 if (S_ISBLK(inode->i_mode)) {
1834 bdev = I_BDEV(inode);
1835 error = bd_claim(bdev, sys_swapon);
1836 if (error < 0) {
1837 bdev = NULL;
f7b3a435 1838 error = -EINVAL;
1da177e4
LT
1839 goto bad_swap;
1840 }
1841 p->old_block_size = block_size(bdev);
1842 error = set_blocksize(bdev, PAGE_SIZE);
1843 if (error < 0)
1844 goto bad_swap;
1845 p->bdev = bdev;
1846 } else if (S_ISREG(inode->i_mode)) {
1847 p->bdev = inode->i_sb->s_bdev;
1b1dcc1b 1848 mutex_lock(&inode->i_mutex);
1da177e4
LT
1849 did_down = 1;
1850 if (IS_SWAPFILE(inode)) {
1851 error = -EBUSY;
1852 goto bad_swap;
1853 }
1854 } else {
1855 goto bad_swap;
1856 }
1857
73fd8748 1858 swapfilepages = i_size_read(inode) >> PAGE_SHIFT;
1da177e4
LT
1859
1860 /*
1861 * Read the swap header.
1862 */
1863 if (!mapping->a_ops->readpage) {
1864 error = -EINVAL;
1865 goto bad_swap;
1866 }
090d2b18 1867 page = read_mapping_page(mapping, 0, swap_file);
1da177e4
LT
1868 if (IS_ERR(page)) {
1869 error = PTR_ERR(page);
1870 goto bad_swap;
1871 }
81e33971 1872 swap_header = kmap(page);
1da177e4 1873
81e33971 1874 if (memcmp("SWAPSPACE2", swap_header->magic.magic, 10)) {
e97a3111 1875 printk(KERN_ERR "Unable to find swap-space signature\n");
1da177e4
LT
1876 error = -EINVAL;
1877 goto bad_swap;
1878 }
886bb7e9 1879
81e33971
HD
1880 /* swap partition endianess hack... */
1881 if (swab32(swap_header->info.version) == 1) {
1882 swab32s(&swap_header->info.version);
1883 swab32s(&swap_header->info.last_page);
1884 swab32s(&swap_header->info.nr_badpages);
1885 for (i = 0; i < swap_header->info.nr_badpages; i++)
1886 swab32s(&swap_header->info.badpages[i]);
1887 }
1888 /* Check the swap header's sub-version */
1889 if (swap_header->info.version != 1) {
1890 printk(KERN_WARNING
1891 "Unable to handle swap header version %d\n",
1892 swap_header->info.version);
1da177e4
LT
1893 error = -EINVAL;
1894 goto bad_swap;
81e33971 1895 }
1da177e4 1896
81e33971
HD
1897 p->lowest_bit = 1;
1898 p->cluster_next = 1;
efa90a98 1899 p->cluster_nr = 0;
52b7efdb 1900
81e33971
HD
1901 /*
1902 * Find out how many pages are allowed for a single swap
1903 * device. There are two limiting factors: 1) the number of
1904 * bits for the swap offset in the swp_entry_t type and
1905 * 2) the number of bits in the a swap pte as defined by
1906 * the different architectures. In order to find the
1907 * largest possible bit mask a swap entry with swap type 0
1908 * and swap offset ~0UL is created, encoded to a swap pte,
1909 * decoded to a swp_entry_t again and finally the swap
1910 * offset is extracted. This will mask all the bits from
1911 * the initial ~0UL mask that can't be encoded in either
1912 * the swp_entry_t or the architecture definition of a
1913 * swap pte.
1914 */
1915 maxpages = swp_offset(pte_to_swp_entry(
1916 swp_entry_to_pte(swp_entry(0, ~0UL)))) - 1;
1917 if (maxpages > swap_header->info.last_page)
1918 maxpages = swap_header->info.last_page;
1919 p->highest_bit = maxpages - 1;
1da177e4 1920
81e33971
HD
1921 error = -EINVAL;
1922 if (!maxpages)
1923 goto bad_swap;
1924 if (swapfilepages && maxpages > swapfilepages) {
1925 printk(KERN_WARNING
1926 "Swap area shorter than signature indicates\n");
1927 goto bad_swap;
1928 }
1929 if (swap_header->info.nr_badpages && S_ISREG(inode->i_mode))
1930 goto bad_swap;
1931 if (swap_header->info.nr_badpages > MAX_SWAP_BADPAGES)
1932 goto bad_swap;
cd105df4 1933
81e33971 1934 /* OK, set up the swap map and apply the bad block list */
8d69aaee 1935 swap_map = vmalloc(maxpages);
81e33971
HD
1936 if (!swap_map) {
1937 error = -ENOMEM;
1938 goto bad_swap;
1939 }
1da177e4 1940
8d69aaee 1941 memset(swap_map, 0, maxpages);
81e33971
HD
1942 for (i = 0; i < swap_header->info.nr_badpages; i++) {
1943 int page_nr = swap_header->info.badpages[i];
1944 if (page_nr <= 0 || page_nr >= swap_header->info.last_page) {
1945 error = -EINVAL;
1da177e4 1946 goto bad_swap;
81e33971
HD
1947 }
1948 swap_map[page_nr] = SWAP_MAP_BAD;
1da177e4 1949 }
27a7faa0
KH
1950
1951 error = swap_cgroup_swapon(type, maxpages);
1952 if (error)
1953 goto bad_swap;
1954
81e33971
HD
1955 nr_good_pages = swap_header->info.last_page -
1956 swap_header->info.nr_badpages -
1957 1 /* header page */;
e2244ec2 1958
e2244ec2 1959 if (nr_good_pages) {
78ecba08 1960 swap_map[0] = SWAP_MAP_BAD;
e2244ec2
HD
1961 p->max = maxpages;
1962 p->pages = nr_good_pages;
53092a74
HD
1963 nr_extents = setup_swap_extents(p, &span);
1964 if (nr_extents < 0) {
1965 error = nr_extents;
e2244ec2 1966 goto bad_swap;
53092a74 1967 }
e2244ec2
HD
1968 nr_good_pages = p->pages;
1969 }
1da177e4
LT
1970 if (!nr_good_pages) {
1971 printk(KERN_WARNING "Empty swap-file\n");
1972 error = -EINVAL;
1973 goto bad_swap;
1974 }
1da177e4 1975
3bd0f0c7
SJ
1976 if (p->bdev) {
1977 if (blk_queue_nonrot(bdev_get_queue(p->bdev))) {
1978 p->flags |= SWP_SOLIDSTATE;
1979 p->cluster_next = 1 + (random32() % p->highest_bit);
1980 }
1981 if (discard_swap(p) == 0)
1982 p->flags |= SWP_DISCARDABLE;
20137a49 1983 }
6a6ba831 1984
fc0abb14 1985 mutex_lock(&swapon_mutex);
5d337b91 1986 spin_lock(&swap_lock);
78ecba08
HD
1987 if (swap_flags & SWAP_FLAG_PREFER)
1988 p->prio =
1989 (swap_flags & SWAP_FLAG_PRIO_MASK) >> SWAP_FLAG_PRIO_SHIFT;
1990 else
1991 p->prio = --least_priority;
1992 p->swap_map = swap_map;
22c6f8fd 1993 p->flags |= SWP_WRITEOK;
1da177e4
LT
1994 nr_swap_pages += nr_good_pages;
1995 total_swap_pages += nr_good_pages;
53092a74 1996
6eb396dc 1997 printk(KERN_INFO "Adding %uk swap on %s. "
20137a49 1998 "Priority:%d extents:%d across:%lluk %s%s\n",
53092a74 1999 nr_good_pages<<(PAGE_SHIFT-10), name, p->prio,
6a6ba831 2000 nr_extents, (unsigned long long)span<<(PAGE_SHIFT-10),
20137a49
HD
2001 (p->flags & SWP_SOLIDSTATE) ? "SS" : "",
2002 (p->flags & SWP_DISCARDABLE) ? "D" : "");
1da177e4
LT
2003
2004 /* insert swap space into swap_list: */
2005 prev = -1;
efa90a98
HD
2006 for (i = swap_list.head; i >= 0; i = swap_info[i]->next) {
2007 if (p->prio >= swap_info[i]->prio)
1da177e4 2008 break;
1da177e4
LT
2009 prev = i;
2010 }
2011 p->next = i;
efa90a98
HD
2012 if (prev < 0)
2013 swap_list.head = swap_list.next = type;
2014 else
2015 swap_info[prev]->next = type;
5d337b91 2016 spin_unlock(&swap_lock);
fc0abb14 2017 mutex_unlock(&swapon_mutex);
1da177e4
LT
2018 error = 0;
2019 goto out;
2020bad_swap:
2021 if (bdev) {
2022 set_blocksize(bdev, p->old_block_size);
2023 bd_release(bdev);
2024 }
4cd3bb10 2025 destroy_swap_extents(p);
27a7faa0 2026 swap_cgroup_swapoff(type);
1da177e4 2027bad_swap_2:
5d337b91 2028 spin_lock(&swap_lock);
1da177e4 2029 p->swap_file = NULL;
1da177e4 2030 p->flags = 0;
5d337b91 2031 spin_unlock(&swap_lock);
1da177e4
LT
2032 vfree(swap_map);
2033 if (swap_file)
2034 filp_close(swap_file, NULL);
2035out:
2036 if (page && !IS_ERR(page)) {
2037 kunmap(page);
2038 page_cache_release(page);
2039 }
2040 if (name)
2041 putname(name);
2042 if (did_down) {
2043 if (!error)
2044 inode->i_flags |= S_SWAPFILE;
1b1dcc1b 2045 mutex_unlock(&inode->i_mutex);
1da177e4
LT
2046 }
2047 return error;
2048}
2049
2050void si_swapinfo(struct sysinfo *val)
2051{
efa90a98 2052 unsigned int type;
1da177e4
LT
2053 unsigned long nr_to_be_unused = 0;
2054
5d337b91 2055 spin_lock(&swap_lock);
efa90a98
HD
2056 for (type = 0; type < nr_swapfiles; type++) {
2057 struct swap_info_struct *si = swap_info[type];
2058
2059 if ((si->flags & SWP_USED) && !(si->flags & SWP_WRITEOK))
2060 nr_to_be_unused += si->inuse_pages;
1da177e4
LT
2061 }
2062 val->freeswap = nr_swap_pages + nr_to_be_unused;
2063 val->totalswap = total_swap_pages + nr_to_be_unused;
5d337b91 2064 spin_unlock(&swap_lock);
1da177e4
LT
2065}
2066
2067/*
2068 * Verify that a swap entry is valid and increment its swap map count.
2069 *
355cfa73
KH
2070 * Returns error code in following case.
2071 * - success -> 0
2072 * - swp_entry is invalid -> EINVAL
2073 * - swp_entry is migration entry -> EINVAL
2074 * - swap-cache reference is requested but there is already one. -> EEXIST
2075 * - swap-cache reference is requested but the entry is not used. -> ENOENT
570a335b 2076 * - swap-mapped reference requested but needs continued swap count. -> ENOMEM
1da177e4 2077 */
8d69aaee 2078static int __swap_duplicate(swp_entry_t entry, unsigned char usage)
1da177e4 2079{
73c34b6a 2080 struct swap_info_struct *p;
1da177e4 2081 unsigned long offset, type;
8d69aaee
HD
2082 unsigned char count;
2083 unsigned char has_cache;
253d553b 2084 int err = -EINVAL;
1da177e4 2085
a7420aa5 2086 if (non_swap_entry(entry))
253d553b 2087 goto out;
0697212a 2088
1da177e4
LT
2089 type = swp_type(entry);
2090 if (type >= nr_swapfiles)
2091 goto bad_file;
efa90a98 2092 p = swap_info[type];
1da177e4
LT
2093 offset = swp_offset(entry);
2094
5d337b91 2095 spin_lock(&swap_lock);
355cfa73
KH
2096 if (unlikely(offset >= p->max))
2097 goto unlock_out;
2098
253d553b
HD
2099 count = p->swap_map[offset];
2100 has_cache = count & SWAP_HAS_CACHE;
2101 count &= ~SWAP_HAS_CACHE;
2102 err = 0;
355cfa73 2103
253d553b 2104 if (usage == SWAP_HAS_CACHE) {
355cfa73
KH
2105
2106 /* set SWAP_HAS_CACHE if there is no cache and entry is used */
253d553b
HD
2107 if (!has_cache && count)
2108 has_cache = SWAP_HAS_CACHE;
2109 else if (has_cache) /* someone else added cache */
2110 err = -EEXIST;
2111 else /* no users remaining */
2112 err = -ENOENT;
355cfa73
KH
2113
2114 } else if (count || has_cache) {
253d553b 2115
570a335b
HD
2116 if ((count & ~COUNT_CONTINUED) < SWAP_MAP_MAX)
2117 count += usage;
2118 else if ((count & ~COUNT_CONTINUED) > SWAP_MAP_MAX)
253d553b 2119 err = -EINVAL;
570a335b
HD
2120 else if (swap_count_continued(p, offset, count))
2121 count = COUNT_CONTINUED;
2122 else
2123 err = -ENOMEM;
355cfa73 2124 } else
253d553b
HD
2125 err = -ENOENT; /* unused swap entry */
2126
2127 p->swap_map[offset] = count | has_cache;
2128
355cfa73 2129unlock_out:
5d337b91 2130 spin_unlock(&swap_lock);
1da177e4 2131out:
253d553b 2132 return err;
1da177e4
LT
2133
2134bad_file:
2135 printk(KERN_ERR "swap_dup: %s%08lx\n", Bad_file, entry.val);
2136 goto out;
2137}
253d553b 2138
aaa46865
HD
2139/*
2140 * Help swapoff by noting that swap entry belongs to shmem/tmpfs
2141 * (in which case its reference count is never incremented).
2142 */
2143void swap_shmem_alloc(swp_entry_t entry)
2144{
2145 __swap_duplicate(entry, SWAP_MAP_SHMEM);
2146}
2147
355cfa73
KH
2148/*
2149 * increase reference count of swap entry by 1.
2150 */
570a335b 2151int swap_duplicate(swp_entry_t entry)
355cfa73 2152{
570a335b
HD
2153 int err = 0;
2154
2155 while (!err && __swap_duplicate(entry, 1) == -ENOMEM)
2156 err = add_swap_count_continuation(entry, GFP_ATOMIC);
2157 return err;
355cfa73 2158}
1da177e4 2159
cb4b86ba 2160/*
355cfa73
KH
2161 * @entry: swap entry for which we allocate swap cache.
2162 *
73c34b6a 2163 * Called when allocating swap cache for existing swap entry,
355cfa73
KH
2164 * This can return error codes. Returns 0 at success.
2165 * -EBUSY means there is a swap cache.
2166 * Note: return code is different from swap_duplicate().
cb4b86ba
KH
2167 */
2168int swapcache_prepare(swp_entry_t entry)
2169{
253d553b 2170 return __swap_duplicate(entry, SWAP_HAS_CACHE);
cb4b86ba
KH
2171}
2172
1da177e4 2173/*
5d337b91 2174 * swap_lock prevents swap_map being freed. Don't grab an extra
1da177e4
LT
2175 * reference on the swaphandle, it doesn't matter if it becomes unused.
2176 */
2177int valid_swaphandles(swp_entry_t entry, unsigned long *offset)
2178{
8952898b 2179 struct swap_info_struct *si;
3f9e7949 2180 int our_page_cluster = page_cluster;
8952898b
HD
2181 pgoff_t target, toff;
2182 pgoff_t base, end;
2183 int nr_pages = 0;
1da177e4 2184
3f9e7949 2185 if (!our_page_cluster) /* no readahead */
1da177e4 2186 return 0;
8952898b 2187
efa90a98 2188 si = swap_info[swp_type(entry)];
8952898b
HD
2189 target = swp_offset(entry);
2190 base = (target >> our_page_cluster) << our_page_cluster;
2191 end = base + (1 << our_page_cluster);
2192 if (!base) /* first page is swap header */
2193 base++;
1da177e4 2194
5d337b91 2195 spin_lock(&swap_lock);
8952898b
HD
2196 if (end > si->max) /* don't go beyond end of map */
2197 end = si->max;
2198
2199 /* Count contiguous allocated slots above our target */
2200 for (toff = target; ++toff < end; nr_pages++) {
2201 /* Don't read in free or bad pages */
2202 if (!si->swap_map[toff])
2203 break;
355cfa73 2204 if (swap_count(si->swap_map[toff]) == SWAP_MAP_BAD)
1da177e4 2205 break;
8952898b
HD
2206 }
2207 /* Count contiguous allocated slots below our target */
2208 for (toff = target; --toff >= base; nr_pages++) {
1da177e4 2209 /* Don't read in free or bad pages */
8952898b 2210 if (!si->swap_map[toff])
1da177e4 2211 break;
355cfa73 2212 if (swap_count(si->swap_map[toff]) == SWAP_MAP_BAD)
1da177e4 2213 break;
8952898b 2214 }
5d337b91 2215 spin_unlock(&swap_lock);
8952898b
HD
2216
2217 /*
2218 * Indicate starting offset, and return number of pages to get:
2219 * if only 1, say 0, since there's then no readahead to be done.
2220 */
2221 *offset = ++toff;
2222 return nr_pages? ++nr_pages: 0;
1da177e4 2223}
570a335b
HD
2224
2225/*
2226 * add_swap_count_continuation - called when a swap count is duplicated
2227 * beyond SWAP_MAP_MAX, it allocates a new page and links that to the entry's
2228 * page of the original vmalloc'ed swap_map, to hold the continuation count
2229 * (for that entry and for its neighbouring PAGE_SIZE swap entries). Called
2230 * again when count is duplicated beyond SWAP_MAP_MAX * SWAP_CONT_MAX, etc.
2231 *
2232 * These continuation pages are seldom referenced: the common paths all work
2233 * on the original swap_map, only referring to a continuation page when the
2234 * low "digit" of a count is incremented or decremented through SWAP_MAP_MAX.
2235 *
2236 * add_swap_count_continuation(, GFP_ATOMIC) can be called while holding
2237 * page table locks; if it fails, add_swap_count_continuation(, GFP_KERNEL)
2238 * can be called after dropping locks.
2239 */
2240int add_swap_count_continuation(swp_entry_t entry, gfp_t gfp_mask)
2241{
2242 struct swap_info_struct *si;
2243 struct page *head;
2244 struct page *page;
2245 struct page *list_page;
2246 pgoff_t offset;
2247 unsigned char count;
2248
2249 /*
2250 * When debugging, it's easier to use __GFP_ZERO here; but it's better
2251 * for latency not to zero a page while GFP_ATOMIC and holding locks.
2252 */
2253 page = alloc_page(gfp_mask | __GFP_HIGHMEM);
2254
2255 si = swap_info_get(entry);
2256 if (!si) {
2257 /*
2258 * An acceptable race has occurred since the failing
2259 * __swap_duplicate(): the swap entry has been freed,
2260 * perhaps even the whole swap_map cleared for swapoff.
2261 */
2262 goto outer;
2263 }
2264
2265 offset = swp_offset(entry);
2266 count = si->swap_map[offset] & ~SWAP_HAS_CACHE;
2267
2268 if ((count & ~COUNT_CONTINUED) != SWAP_MAP_MAX) {
2269 /*
2270 * The higher the swap count, the more likely it is that tasks
2271 * will race to add swap count continuation: we need to avoid
2272 * over-provisioning.
2273 */
2274 goto out;
2275 }
2276
2277 if (!page) {
2278 spin_unlock(&swap_lock);
2279 return -ENOMEM;
2280 }
2281
2282 /*
2283 * We are fortunate that although vmalloc_to_page uses pte_offset_map,
2284 * no architecture is using highmem pages for kernel pagetables: so it
2285 * will not corrupt the GFP_ATOMIC caller's atomic pagetable kmaps.
2286 */
2287 head = vmalloc_to_page(si->swap_map + offset);
2288 offset &= ~PAGE_MASK;
2289
2290 /*
2291 * Page allocation does not initialize the page's lru field,
2292 * but it does always reset its private field.
2293 */
2294 if (!page_private(head)) {
2295 BUG_ON(count & COUNT_CONTINUED);
2296 INIT_LIST_HEAD(&head->lru);
2297 set_page_private(head, SWP_CONTINUED);
2298 si->flags |= SWP_CONTINUED;
2299 }
2300
2301 list_for_each_entry(list_page, &head->lru, lru) {
2302 unsigned char *map;
2303
2304 /*
2305 * If the previous map said no continuation, but we've found
2306 * a continuation page, free our allocation and use this one.
2307 */
2308 if (!(count & COUNT_CONTINUED))
2309 goto out;
2310
2311 map = kmap_atomic(list_page, KM_USER0) + offset;
2312 count = *map;
2313 kunmap_atomic(map, KM_USER0);
2314
2315 /*
2316 * If this continuation count now has some space in it,
2317 * free our allocation and use this one.
2318 */
2319 if ((count & ~COUNT_CONTINUED) != SWAP_CONT_MAX)
2320 goto out;
2321 }
2322
2323 list_add_tail(&page->lru, &head->lru);
2324 page = NULL; /* now it's attached, don't free it */
2325out:
2326 spin_unlock(&swap_lock);
2327outer:
2328 if (page)
2329 __free_page(page);
2330 return 0;
2331}
2332
2333/*
2334 * swap_count_continued - when the original swap_map count is incremented
2335 * from SWAP_MAP_MAX, check if there is already a continuation page to carry
2336 * into, carry if so, or else fail until a new continuation page is allocated;
2337 * when the original swap_map count is decremented from 0 with continuation,
2338 * borrow from the continuation and report whether it still holds more.
2339 * Called while __swap_duplicate() or swap_entry_free() holds swap_lock.
2340 */
2341static bool swap_count_continued(struct swap_info_struct *si,
2342 pgoff_t offset, unsigned char count)
2343{
2344 struct page *head;
2345 struct page *page;
2346 unsigned char *map;
2347
2348 head = vmalloc_to_page(si->swap_map + offset);
2349 if (page_private(head) != SWP_CONTINUED) {
2350 BUG_ON(count & COUNT_CONTINUED);
2351 return false; /* need to add count continuation */
2352 }
2353
2354 offset &= ~PAGE_MASK;
2355 page = list_entry(head->lru.next, struct page, lru);
2356 map = kmap_atomic(page, KM_USER0) + offset;
2357
2358 if (count == SWAP_MAP_MAX) /* initial increment from swap_map */
2359 goto init_map; /* jump over SWAP_CONT_MAX checks */
2360
2361 if (count == (SWAP_MAP_MAX | COUNT_CONTINUED)) { /* incrementing */
2362 /*
2363 * Think of how you add 1 to 999
2364 */
2365 while (*map == (SWAP_CONT_MAX | COUNT_CONTINUED)) {
2366 kunmap_atomic(map, KM_USER0);
2367 page = list_entry(page->lru.next, struct page, lru);
2368 BUG_ON(page == head);
2369 map = kmap_atomic(page, KM_USER0) + offset;
2370 }
2371 if (*map == SWAP_CONT_MAX) {
2372 kunmap_atomic(map, KM_USER0);
2373 page = list_entry(page->lru.next, struct page, lru);
2374 if (page == head)
2375 return false; /* add count continuation */
2376 map = kmap_atomic(page, KM_USER0) + offset;
2377init_map: *map = 0; /* we didn't zero the page */
2378 }
2379 *map += 1;
2380 kunmap_atomic(map, KM_USER0);
2381 page = list_entry(page->lru.prev, struct page, lru);
2382 while (page != head) {
2383 map = kmap_atomic(page, KM_USER0) + offset;
2384 *map = COUNT_CONTINUED;
2385 kunmap_atomic(map, KM_USER0);
2386 page = list_entry(page->lru.prev, struct page, lru);
2387 }
2388 return true; /* incremented */
2389
2390 } else { /* decrementing */
2391 /*
2392 * Think of how you subtract 1 from 1000
2393 */
2394 BUG_ON(count != COUNT_CONTINUED);
2395 while (*map == COUNT_CONTINUED) {
2396 kunmap_atomic(map, KM_USER0);
2397 page = list_entry(page->lru.next, struct page, lru);
2398 BUG_ON(page == head);
2399 map = kmap_atomic(page, KM_USER0) + offset;
2400 }
2401 BUG_ON(*map == 0);
2402 *map -= 1;
2403 if (*map == 0)
2404 count = 0;
2405 kunmap_atomic(map, KM_USER0);
2406 page = list_entry(page->lru.prev, struct page, lru);
2407 while (page != head) {
2408 map = kmap_atomic(page, KM_USER0) + offset;
2409 *map = SWAP_CONT_MAX | count;
2410 count = COUNT_CONTINUED;
2411 kunmap_atomic(map, KM_USER0);
2412 page = list_entry(page->lru.prev, struct page, lru);
2413 }
2414 return count == COUNT_CONTINUED;
2415 }
2416}
2417
2418/*
2419 * free_swap_count_continuations - swapoff free all the continuation pages
2420 * appended to the swap_map, after swap_map is quiesced, before vfree'ing it.
2421 */
2422static void free_swap_count_continuations(struct swap_info_struct *si)
2423{
2424 pgoff_t offset;
2425
2426 for (offset = 0; offset < si->max; offset += PAGE_SIZE) {
2427 struct page *head;
2428 head = vmalloc_to_page(si->swap_map + offset);
2429 if (page_private(head)) {
2430 struct list_head *this, *next;
2431 list_for_each_safe(this, next, &head->lru) {
2432 struct page *page;
2433 page = list_entry(this, struct page, lru);
2434 list_del(this);
2435 __free_page(page);
2436 }
2437 }
2438 }
2439}