swap: make swap discard async
[linux-2.6-block.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>
072441e2 17#include <linux/shmem_fs.h>
1da177e4 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>
5ad64688 24#include <linux/ksm.h>
1da177e4
LT
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>
66d7dd51 32#include <linux/poll.h>
72788c38 33#include <linux/oom.h>
38b5faf4
DM
34#include <linux/frontswap.h>
35#include <linux/swapfile.h>
f981c595 36#include <linux/export.h>
1da177e4
LT
37
38#include <asm/pgtable.h>
39#include <asm/tlbflush.h>
40#include <linux/swapops.h>
27a7faa0 41#include <linux/page_cgroup.h>
1da177e4 42
570a335b
HD
43static bool swap_count_continued(struct swap_info_struct *, pgoff_t,
44 unsigned char);
45static void free_swap_count_continuations(struct swap_info_struct *);
d4906e1a 46static sector_t map_swap_entry(swp_entry_t, struct block_device**);
570a335b 47
38b5faf4 48DEFINE_SPINLOCK(swap_lock);
7c363b8c 49static unsigned int nr_swapfiles;
ec8acf20
SL
50atomic_long_t nr_swap_pages;
51/* protected with swap_lock. reading in vm_swap_full() doesn't need lock */
1da177e4 52long total_swap_pages;
78ecba08 53static int least_priority;
ec8acf20 54static atomic_t highest_priority_index = ATOMIC_INIT(-1);
1da177e4 55
1da177e4
LT
56static const char Bad_file[] = "Bad swap file entry ";
57static const char Unused_file[] = "Unused swap file entry ";
58static const char Bad_offset[] = "Bad swap offset entry ";
59static const char Unused_offset[] = "Unused swap offset entry ";
60
38b5faf4 61struct swap_list_t swap_list = {-1, -1};
1da177e4 62
38b5faf4 63struct swap_info_struct *swap_info[MAX_SWAPFILES];
1da177e4 64
fc0abb14 65static DEFINE_MUTEX(swapon_mutex);
1da177e4 66
66d7dd51
KS
67static DECLARE_WAIT_QUEUE_HEAD(proc_poll_wait);
68/* Activity counter to indicate that a swapon or swapoff has occurred */
69static atomic_t proc_poll_event = ATOMIC_INIT(0);
70
8d69aaee 71static inline unsigned char swap_count(unsigned char ent)
355cfa73 72{
570a335b 73 return ent & ~SWAP_HAS_CACHE; /* may include SWAP_HAS_CONT flag */
355cfa73
KH
74}
75
efa90a98 76/* returns 1 if swap entry is freed */
c9e44410
KH
77static int
78__try_to_reclaim_swap(struct swap_info_struct *si, unsigned long offset)
79{
efa90a98 80 swp_entry_t entry = swp_entry(si->type, offset);
c9e44410
KH
81 struct page *page;
82 int ret = 0;
83
33806f06 84 page = find_get_page(swap_address_space(entry), entry.val);
c9e44410
KH
85 if (!page)
86 return 0;
87 /*
88 * This function is called from scan_swap_map() and it's called
89 * by vmscan.c at reclaiming pages. So, we hold a lock on a page, here.
90 * We have to use trylock for avoiding deadlock. This is a special
91 * case and you should use try_to_free_swap() with explicit lock_page()
92 * in usual operations.
93 */
94 if (trylock_page(page)) {
95 ret = try_to_free_swap(page);
96 unlock_page(page);
97 }
98 page_cache_release(page);
99 return ret;
100}
355cfa73 101
6a6ba831
HD
102/*
103 * swapon tell device that all the old swap contents can be discarded,
104 * to allow the swap device to optimize its wear-levelling.
105 */
106static int discard_swap(struct swap_info_struct *si)
107{
108 struct swap_extent *se;
9625a5f2
HD
109 sector_t start_block;
110 sector_t nr_blocks;
6a6ba831
HD
111 int err = 0;
112
9625a5f2
HD
113 /* Do not discard the swap header page! */
114 se = &si->first_swap_extent;
115 start_block = (se->start_block + 1) << (PAGE_SHIFT - 9);
116 nr_blocks = ((sector_t)se->nr_pages - 1) << (PAGE_SHIFT - 9);
117 if (nr_blocks) {
118 err = blkdev_issue_discard(si->bdev, start_block,
dd3932ed 119 nr_blocks, GFP_KERNEL, 0);
9625a5f2
HD
120 if (err)
121 return err;
122 cond_resched();
123 }
6a6ba831 124
9625a5f2
HD
125 list_for_each_entry(se, &si->first_swap_extent.list, list) {
126 start_block = se->start_block << (PAGE_SHIFT - 9);
127 nr_blocks = (sector_t)se->nr_pages << (PAGE_SHIFT - 9);
6a6ba831
HD
128
129 err = blkdev_issue_discard(si->bdev, start_block,
dd3932ed 130 nr_blocks, GFP_KERNEL, 0);
6a6ba831
HD
131 if (err)
132 break;
133
134 cond_resched();
135 }
136 return err; /* That will often be -EOPNOTSUPP */
137}
138
7992fde7
HD
139/*
140 * swap allocation tell device that a cluster of swap can now be discarded,
141 * to allow the swap device to optimize its wear-levelling.
142 */
143static void discard_swap_cluster(struct swap_info_struct *si,
144 pgoff_t start_page, pgoff_t nr_pages)
145{
146 struct swap_extent *se = si->curr_swap_extent;
147 int found_extent = 0;
148
149 while (nr_pages) {
150 struct list_head *lh;
151
152 if (se->start_page <= start_page &&
153 start_page < se->start_page + se->nr_pages) {
154 pgoff_t offset = start_page - se->start_page;
155 sector_t start_block = se->start_block + offset;
858a2990 156 sector_t nr_blocks = se->nr_pages - offset;
7992fde7
HD
157
158 if (nr_blocks > nr_pages)
159 nr_blocks = nr_pages;
160 start_page += nr_blocks;
161 nr_pages -= nr_blocks;
162
163 if (!found_extent++)
164 si->curr_swap_extent = se;
165
166 start_block <<= PAGE_SHIFT - 9;
167 nr_blocks <<= PAGE_SHIFT - 9;
168 if (blkdev_issue_discard(si->bdev, start_block,
dd3932ed 169 nr_blocks, GFP_NOIO, 0))
7992fde7
HD
170 break;
171 }
172
173 lh = se->list.next;
7992fde7
HD
174 se = list_entry(lh, struct swap_extent, list);
175 }
176}
177
048c27fd
HD
178#define SWAPFILE_CLUSTER 256
179#define LATENCY_LIMIT 256
180
2a8f9449
SL
181static inline void cluster_set_flag(struct swap_cluster_info *info,
182 unsigned int flag)
183{
184 info->flags = flag;
185}
186
187static inline unsigned int cluster_count(struct swap_cluster_info *info)
188{
189 return info->data;
190}
191
192static inline void cluster_set_count(struct swap_cluster_info *info,
193 unsigned int c)
194{
195 info->data = c;
196}
197
198static inline void cluster_set_count_flag(struct swap_cluster_info *info,
199 unsigned int c, unsigned int f)
200{
201 info->flags = f;
202 info->data = c;
203}
204
205static inline unsigned int cluster_next(struct swap_cluster_info *info)
206{
207 return info->data;
208}
209
210static inline void cluster_set_next(struct swap_cluster_info *info,
211 unsigned int n)
212{
213 info->data = n;
214}
215
216static inline void cluster_set_next_flag(struct swap_cluster_info *info,
217 unsigned int n, unsigned int f)
218{
219 info->flags = f;
220 info->data = n;
221}
222
223static inline bool cluster_is_free(struct swap_cluster_info *info)
224{
225 return info->flags & CLUSTER_FLAG_FREE;
226}
227
228static inline bool cluster_is_null(struct swap_cluster_info *info)
229{
230 return info->flags & CLUSTER_FLAG_NEXT_NULL;
231}
232
233static inline void cluster_set_null(struct swap_cluster_info *info)
234{
235 info->flags = CLUSTER_FLAG_NEXT_NULL;
236 info->data = 0;
237}
238
815c2c54
SL
239/* Add a cluster to discard list and schedule it to do discard */
240static void swap_cluster_schedule_discard(struct swap_info_struct *si,
241 unsigned int idx)
242{
243 /*
244 * If scan_swap_map() can't find a free cluster, it will check
245 * si->swap_map directly. To make sure the discarding cluster isn't
246 * taken by scan_swap_map(), mark the swap entries bad (occupied). It
247 * will be cleared after discard
248 */
249 memset(si->swap_map + idx * SWAPFILE_CLUSTER,
250 SWAP_MAP_BAD, SWAPFILE_CLUSTER);
251
252 if (cluster_is_null(&si->discard_cluster_head)) {
253 cluster_set_next_flag(&si->discard_cluster_head,
254 idx, 0);
255 cluster_set_next_flag(&si->discard_cluster_tail,
256 idx, 0);
257 } else {
258 unsigned int tail = cluster_next(&si->discard_cluster_tail);
259 cluster_set_next(&si->cluster_info[tail], idx);
260 cluster_set_next_flag(&si->discard_cluster_tail,
261 idx, 0);
262 }
263
264 schedule_work(&si->discard_work);
265}
266
267/*
268 * Doing discard actually. After a cluster discard is finished, the cluster
269 * will be added to free cluster list. caller should hold si->lock.
270*/
271static void swap_do_scheduled_discard(struct swap_info_struct *si)
272{
273 struct swap_cluster_info *info;
274 unsigned int idx;
275
276 info = si->cluster_info;
277
278 while (!cluster_is_null(&si->discard_cluster_head)) {
279 idx = cluster_next(&si->discard_cluster_head);
280
281 cluster_set_next_flag(&si->discard_cluster_head,
282 cluster_next(&info[idx]), 0);
283 if (cluster_next(&si->discard_cluster_tail) == idx) {
284 cluster_set_null(&si->discard_cluster_head);
285 cluster_set_null(&si->discard_cluster_tail);
286 }
287 spin_unlock(&si->lock);
288
289 discard_swap_cluster(si, idx * SWAPFILE_CLUSTER,
290 SWAPFILE_CLUSTER);
291
292 spin_lock(&si->lock);
293 cluster_set_flag(&info[idx], CLUSTER_FLAG_FREE);
294 if (cluster_is_null(&si->free_cluster_head)) {
295 cluster_set_next_flag(&si->free_cluster_head,
296 idx, 0);
297 cluster_set_next_flag(&si->free_cluster_tail,
298 idx, 0);
299 } else {
300 unsigned int tail;
301
302 tail = cluster_next(&si->free_cluster_tail);
303 cluster_set_next(&info[tail], idx);
304 cluster_set_next_flag(&si->free_cluster_tail,
305 idx, 0);
306 }
307 memset(si->swap_map + idx * SWAPFILE_CLUSTER,
308 0, SWAPFILE_CLUSTER);
309 }
310}
311
312static void swap_discard_work(struct work_struct *work)
313{
314 struct swap_info_struct *si;
315
316 si = container_of(work, struct swap_info_struct, discard_work);
317
318 spin_lock(&si->lock);
319 swap_do_scheduled_discard(si);
320 spin_unlock(&si->lock);
321}
322
2a8f9449
SL
323/*
324 * The cluster corresponding to page_nr will be used. The cluster will be
325 * removed from free cluster list and its usage counter will be increased.
326 */
327static void inc_cluster_info_page(struct swap_info_struct *p,
328 struct swap_cluster_info *cluster_info, unsigned long page_nr)
329{
330 unsigned long idx = page_nr / SWAPFILE_CLUSTER;
331
332 if (!cluster_info)
333 return;
334 if (cluster_is_free(&cluster_info[idx])) {
335 VM_BUG_ON(cluster_next(&p->free_cluster_head) != idx);
336 cluster_set_next_flag(&p->free_cluster_head,
337 cluster_next(&cluster_info[idx]), 0);
338 if (cluster_next(&p->free_cluster_tail) == idx) {
339 cluster_set_null(&p->free_cluster_tail);
340 cluster_set_null(&p->free_cluster_head);
341 }
342 cluster_set_count_flag(&cluster_info[idx], 0, 0);
343 }
344
345 VM_BUG_ON(cluster_count(&cluster_info[idx]) >= SWAPFILE_CLUSTER);
346 cluster_set_count(&cluster_info[idx],
347 cluster_count(&cluster_info[idx]) + 1);
348}
349
350/*
351 * The cluster corresponding to page_nr decreases one usage. If the usage
352 * counter becomes 0, which means no page in the cluster is in using, we can
353 * optionally discard the cluster and add it to free cluster list.
354 */
355static void dec_cluster_info_page(struct swap_info_struct *p,
356 struct swap_cluster_info *cluster_info, unsigned long page_nr)
357{
358 unsigned long idx = page_nr / SWAPFILE_CLUSTER;
359
360 if (!cluster_info)
361 return;
362
363 VM_BUG_ON(cluster_count(&cluster_info[idx]) == 0);
364 cluster_set_count(&cluster_info[idx],
365 cluster_count(&cluster_info[idx]) - 1);
366
367 if (cluster_count(&cluster_info[idx]) == 0) {
815c2c54
SL
368 /*
369 * If the swap is discardable, prepare discard the cluster
370 * instead of free it immediately. The cluster will be freed
371 * after discard.
372 */
373 if (p->flags & SWP_PAGE_DISCARD) {
374 swap_cluster_schedule_discard(p, idx);
375 return;
376 }
377
2a8f9449
SL
378 cluster_set_flag(&cluster_info[idx], CLUSTER_FLAG_FREE);
379 if (cluster_is_null(&p->free_cluster_head)) {
380 cluster_set_next_flag(&p->free_cluster_head, idx, 0);
381 cluster_set_next_flag(&p->free_cluster_tail, idx, 0);
382 } else {
383 unsigned int tail = cluster_next(&p->free_cluster_tail);
384 cluster_set_next(&cluster_info[tail], idx);
385 cluster_set_next_flag(&p->free_cluster_tail, idx, 0);
386 }
387 }
388}
389
390/*
391 * It's possible scan_swap_map() uses a free cluster in the middle of free
392 * cluster list. Avoiding such abuse to avoid list corruption.
393 */
394static inline bool scan_swap_map_recheck_cluster(struct swap_info_struct *si,
395 unsigned long offset)
396{
397 offset /= SWAPFILE_CLUSTER;
398 return !cluster_is_null(&si->free_cluster_head) &&
399 offset != cluster_next(&si->free_cluster_head) &&
400 cluster_is_free(&si->cluster_info[offset]);
401}
402
24b8ff7c
CEB
403static unsigned long scan_swap_map(struct swap_info_struct *si,
404 unsigned char usage)
1da177e4 405{
ebebbbe9 406 unsigned long offset;
c60aa176 407 unsigned long scan_base;
7992fde7 408 unsigned long last_in_cluster = 0;
048c27fd 409 int latency_ration = LATENCY_LIMIT;
7dfad418 410
886bb7e9 411 /*
7dfad418
HD
412 * We try to cluster swap pages by allocating them sequentially
413 * in swap. Once we've allocated SWAPFILE_CLUSTER pages this
414 * way, however, we resort to first-free allocation, starting
415 * a new cluster. This prevents us from scattering swap pages
416 * all over the entire swap partition, so that we reduce
417 * overall disk seek times between swap pages. -- sct
418 * But we do now try to find an empty cluster. -Andrea
c60aa176 419 * And we let swap pages go all over an SSD partition. Hugh
7dfad418
HD
420 */
421
52b7efdb 422 si->flags += SWP_SCANNING;
c60aa176 423 scan_base = offset = si->cluster_next;
ebebbbe9
HD
424
425 if (unlikely(!si->cluster_nr--)) {
426 if (si->pages - si->inuse_pages < SWAPFILE_CLUSTER) {
427 si->cluster_nr = SWAPFILE_CLUSTER - 1;
428 goto checks;
429 }
2a8f9449
SL
430check_cluster:
431 if (!cluster_is_null(&si->free_cluster_head)) {
432 offset = cluster_next(&si->free_cluster_head) *
433 SWAPFILE_CLUSTER;
434 last_in_cluster = offset + SWAPFILE_CLUSTER - 1;
435 si->cluster_next = offset;
436 si->cluster_nr = SWAPFILE_CLUSTER - 1;
2a8f9449
SL
437 goto checks;
438 } else if (si->cluster_info) {
815c2c54
SL
439 /*
440 * we don't have free cluster but have some clusters in
441 * discarding, do discard now and reclaim them
442 */
443 if (!cluster_is_null(&si->discard_cluster_head)) {
444 si->cluster_nr = 0;
445 swap_do_scheduled_discard(si);
446 scan_base = offset = si->cluster_next;
447 if (!si->cluster_nr)
448 goto check_cluster;
449 si->cluster_nr--;
450 goto checks;
451 }
452
2a8f9449
SL
453 /*
454 * Checking free cluster is fast enough, we can do the
455 * check every time
456 */
457 si->cluster_nr = 0;
2a8f9449
SL
458 goto checks;
459 }
460
ec8acf20 461 spin_unlock(&si->lock);
7dfad418 462
c60aa176
HD
463 /*
464 * If seek is expensive, start searching for new cluster from
465 * start of partition, to minimize the span of allocated swap.
466 * But if seek is cheap, search from our current position, so
467 * that swap is allocated from all over the partition: if the
468 * Flash Translation Layer only remaps within limited zones,
469 * we don't want to wear out the first zone too quickly.
470 */
471 if (!(si->flags & SWP_SOLIDSTATE))
472 scan_base = offset = si->lowest_bit;
7dfad418
HD
473 last_in_cluster = offset + SWAPFILE_CLUSTER - 1;
474
475 /* Locate the first empty (unaligned) cluster */
476 for (; last_in_cluster <= si->highest_bit; offset++) {
1da177e4 477 if (si->swap_map[offset])
7dfad418
HD
478 last_in_cluster = offset + SWAPFILE_CLUSTER;
479 else if (offset == last_in_cluster) {
ec8acf20 480 spin_lock(&si->lock);
ebebbbe9
HD
481 offset -= SWAPFILE_CLUSTER - 1;
482 si->cluster_next = offset;
483 si->cluster_nr = SWAPFILE_CLUSTER - 1;
484 goto checks;
1da177e4 485 }
048c27fd
HD
486 if (unlikely(--latency_ration < 0)) {
487 cond_resched();
488 latency_ration = LATENCY_LIMIT;
489 }
7dfad418 490 }
ebebbbe9
HD
491
492 offset = si->lowest_bit;
c60aa176
HD
493 last_in_cluster = offset + SWAPFILE_CLUSTER - 1;
494
495 /* Locate the first empty (unaligned) cluster */
496 for (; last_in_cluster < scan_base; offset++) {
497 if (si->swap_map[offset])
498 last_in_cluster = offset + SWAPFILE_CLUSTER;
499 else if (offset == last_in_cluster) {
ec8acf20 500 spin_lock(&si->lock);
c60aa176
HD
501 offset -= SWAPFILE_CLUSTER - 1;
502 si->cluster_next = offset;
503 si->cluster_nr = SWAPFILE_CLUSTER - 1;
c60aa176
HD
504 goto checks;
505 }
506 if (unlikely(--latency_ration < 0)) {
507 cond_resched();
508 latency_ration = LATENCY_LIMIT;
509 }
510 }
511
512 offset = scan_base;
ec8acf20 513 spin_lock(&si->lock);
ebebbbe9 514 si->cluster_nr = SWAPFILE_CLUSTER - 1;
1da177e4 515 }
7dfad418 516
ebebbbe9 517checks:
2a8f9449
SL
518 if (scan_swap_map_recheck_cluster(si, offset))
519 goto check_cluster;
ebebbbe9 520 if (!(si->flags & SWP_WRITEOK))
52b7efdb 521 goto no_page;
7dfad418
HD
522 if (!si->highest_bit)
523 goto no_page;
ebebbbe9 524 if (offset > si->highest_bit)
c60aa176 525 scan_base = offset = si->lowest_bit;
c9e44410 526
b73d7fce
HD
527 /* reuse swap entry of cache-only swap if not busy. */
528 if (vm_swap_full() && si->swap_map[offset] == SWAP_HAS_CACHE) {
c9e44410 529 int swap_was_freed;
ec8acf20 530 spin_unlock(&si->lock);
c9e44410 531 swap_was_freed = __try_to_reclaim_swap(si, offset);
ec8acf20 532 spin_lock(&si->lock);
c9e44410
KH
533 /* entry was freed successfully, try to use this again */
534 if (swap_was_freed)
535 goto checks;
536 goto scan; /* check next one */
537 }
538
ebebbbe9
HD
539 if (si->swap_map[offset])
540 goto scan;
541
542 if (offset == si->lowest_bit)
543 si->lowest_bit++;
544 if (offset == si->highest_bit)
545 si->highest_bit--;
546 si->inuse_pages++;
547 if (si->inuse_pages == si->pages) {
548 si->lowest_bit = si->max;
549 si->highest_bit = 0;
1da177e4 550 }
253d553b 551 si->swap_map[offset] = usage;
2a8f9449 552 inc_cluster_info_page(si, si->cluster_info, offset);
ebebbbe9
HD
553 si->cluster_next = offset + 1;
554 si->flags -= SWP_SCANNING;
7992fde7 555
ebebbbe9 556 return offset;
7dfad418 557
ebebbbe9 558scan:
ec8acf20 559 spin_unlock(&si->lock);
7dfad418 560 while (++offset <= si->highest_bit) {
52b7efdb 561 if (!si->swap_map[offset]) {
ec8acf20 562 spin_lock(&si->lock);
52b7efdb
HD
563 goto checks;
564 }
c9e44410 565 if (vm_swap_full() && si->swap_map[offset] == SWAP_HAS_CACHE) {
ec8acf20 566 spin_lock(&si->lock);
c9e44410
KH
567 goto checks;
568 }
048c27fd
HD
569 if (unlikely(--latency_ration < 0)) {
570 cond_resched();
571 latency_ration = LATENCY_LIMIT;
572 }
7dfad418 573 }
c60aa176
HD
574 offset = si->lowest_bit;
575 while (++offset < scan_base) {
576 if (!si->swap_map[offset]) {
ec8acf20 577 spin_lock(&si->lock);
c60aa176
HD
578 goto checks;
579 }
c9e44410 580 if (vm_swap_full() && si->swap_map[offset] == SWAP_HAS_CACHE) {
ec8acf20 581 spin_lock(&si->lock);
c9e44410
KH
582 goto checks;
583 }
c60aa176
HD
584 if (unlikely(--latency_ration < 0)) {
585 cond_resched();
586 latency_ration = LATENCY_LIMIT;
587 }
588 }
ec8acf20 589 spin_lock(&si->lock);
7dfad418
HD
590
591no_page:
52b7efdb 592 si->flags -= SWP_SCANNING;
1da177e4
LT
593 return 0;
594}
595
596swp_entry_t get_swap_page(void)
597{
fb4f88dc
HD
598 struct swap_info_struct *si;
599 pgoff_t offset;
600 int type, next;
601 int wrapped = 0;
ec8acf20 602 int hp_index;
1da177e4 603
5d337b91 604 spin_lock(&swap_lock);
ec8acf20 605 if (atomic_long_read(&nr_swap_pages) <= 0)
fb4f88dc 606 goto noswap;
ec8acf20 607 atomic_long_dec(&nr_swap_pages);
fb4f88dc
HD
608
609 for (type = swap_list.next; type >= 0 && wrapped < 2; type = next) {
ec8acf20
SL
610 hp_index = atomic_xchg(&highest_priority_index, -1);
611 /*
612 * highest_priority_index records current highest priority swap
613 * type which just frees swap entries. If its priority is
614 * higher than that of swap_list.next swap type, we use it. It
615 * isn't protected by swap_lock, so it can be an invalid value
616 * if the corresponding swap type is swapoff. We double check
617 * the flags here. It's even possible the swap type is swapoff
618 * and swapon again and its priority is changed. In such rare
619 * case, low prority swap type might be used, but eventually
620 * high priority swap will be used after several rounds of
621 * swap.
622 */
623 if (hp_index != -1 && hp_index != type &&
624 swap_info[type]->prio < swap_info[hp_index]->prio &&
625 (swap_info[hp_index]->flags & SWP_WRITEOK)) {
626 type = hp_index;
627 swap_list.next = type;
628 }
629
efa90a98 630 si = swap_info[type];
fb4f88dc
HD
631 next = si->next;
632 if (next < 0 ||
efa90a98 633 (!wrapped && si->prio != swap_info[next]->prio)) {
fb4f88dc
HD
634 next = swap_list.head;
635 wrapped++;
1da177e4 636 }
fb4f88dc 637
ec8acf20
SL
638 spin_lock(&si->lock);
639 if (!si->highest_bit) {
640 spin_unlock(&si->lock);
fb4f88dc 641 continue;
ec8acf20
SL
642 }
643 if (!(si->flags & SWP_WRITEOK)) {
644 spin_unlock(&si->lock);
fb4f88dc 645 continue;
ec8acf20 646 }
fb4f88dc
HD
647
648 swap_list.next = next;
ec8acf20
SL
649
650 spin_unlock(&swap_lock);
355cfa73 651 /* This is called for allocating swap entry for cache */
253d553b 652 offset = scan_swap_map(si, SWAP_HAS_CACHE);
ec8acf20
SL
653 spin_unlock(&si->lock);
654 if (offset)
fb4f88dc 655 return swp_entry(type, offset);
ec8acf20 656 spin_lock(&swap_lock);
fb4f88dc 657 next = swap_list.next;
1da177e4 658 }
fb4f88dc 659
ec8acf20 660 atomic_long_inc(&nr_swap_pages);
fb4f88dc 661noswap:
5d337b91 662 spin_unlock(&swap_lock);
fb4f88dc 663 return (swp_entry_t) {0};
1da177e4
LT
664}
665
910321ea
HD
666/* The only caller of this function is now susupend routine */
667swp_entry_t get_swap_page_of_type(int type)
668{
669 struct swap_info_struct *si;
670 pgoff_t offset;
671
910321ea 672 si = swap_info[type];
ec8acf20 673 spin_lock(&si->lock);
910321ea 674 if (si && (si->flags & SWP_WRITEOK)) {
ec8acf20 675 atomic_long_dec(&nr_swap_pages);
910321ea
HD
676 /* This is called for allocating swap entry, not cache */
677 offset = scan_swap_map(si, 1);
678 if (offset) {
ec8acf20 679 spin_unlock(&si->lock);
910321ea
HD
680 return swp_entry(type, offset);
681 }
ec8acf20 682 atomic_long_inc(&nr_swap_pages);
910321ea 683 }
ec8acf20 684 spin_unlock(&si->lock);
910321ea
HD
685 return (swp_entry_t) {0};
686}
687
73c34b6a 688static struct swap_info_struct *swap_info_get(swp_entry_t entry)
1da177e4 689{
73c34b6a 690 struct swap_info_struct *p;
1da177e4
LT
691 unsigned long offset, type;
692
693 if (!entry.val)
694 goto out;
695 type = swp_type(entry);
696 if (type >= nr_swapfiles)
697 goto bad_nofile;
efa90a98 698 p = swap_info[type];
1da177e4
LT
699 if (!(p->flags & SWP_USED))
700 goto bad_device;
701 offset = swp_offset(entry);
702 if (offset >= p->max)
703 goto bad_offset;
704 if (!p->swap_map[offset])
705 goto bad_free;
ec8acf20 706 spin_lock(&p->lock);
1da177e4
LT
707 return p;
708
709bad_free:
465c47fd 710 pr_err("swap_free: %s%08lx\n", Unused_offset, entry.val);
1da177e4
LT
711 goto out;
712bad_offset:
465c47fd 713 pr_err("swap_free: %s%08lx\n", Bad_offset, entry.val);
1da177e4
LT
714 goto out;
715bad_device:
465c47fd 716 pr_err("swap_free: %s%08lx\n", Unused_file, entry.val);
1da177e4
LT
717 goto out;
718bad_nofile:
465c47fd 719 pr_err("swap_free: %s%08lx\n", Bad_file, entry.val);
1da177e4
LT
720out:
721 return NULL;
886bb7e9 722}
1da177e4 723
ec8acf20
SL
724/*
725 * This swap type frees swap entry, check if it is the highest priority swap
726 * type which just frees swap entry. get_swap_page() uses
727 * highest_priority_index to search highest priority swap type. The
728 * swap_info_struct.lock can't protect us if there are multiple swap types
729 * active, so we use atomic_cmpxchg.
730 */
731static void set_highest_priority_index(int type)
732{
733 int old_hp_index, new_hp_index;
734
735 do {
736 old_hp_index = atomic_read(&highest_priority_index);
737 if (old_hp_index != -1 &&
738 swap_info[old_hp_index]->prio >= swap_info[type]->prio)
739 break;
740 new_hp_index = type;
741 } while (atomic_cmpxchg(&highest_priority_index,
742 old_hp_index, new_hp_index) != old_hp_index);
743}
744
8d69aaee
HD
745static unsigned char swap_entry_free(struct swap_info_struct *p,
746 swp_entry_t entry, unsigned char usage)
1da177e4 747{
253d553b 748 unsigned long offset = swp_offset(entry);
8d69aaee
HD
749 unsigned char count;
750 unsigned char has_cache;
355cfa73 751
253d553b
HD
752 count = p->swap_map[offset];
753 has_cache = count & SWAP_HAS_CACHE;
754 count &= ~SWAP_HAS_CACHE;
355cfa73 755
253d553b 756 if (usage == SWAP_HAS_CACHE) {
355cfa73 757 VM_BUG_ON(!has_cache);
253d553b 758 has_cache = 0;
aaa46865
HD
759 } else if (count == SWAP_MAP_SHMEM) {
760 /*
761 * Or we could insist on shmem.c using a special
762 * swap_shmem_free() and free_shmem_swap_and_cache()...
763 */
764 count = 0;
570a335b
HD
765 } else if ((count & ~COUNT_CONTINUED) <= SWAP_MAP_MAX) {
766 if (count == COUNT_CONTINUED) {
767 if (swap_count_continued(p, offset, count))
768 count = SWAP_MAP_MAX | COUNT_CONTINUED;
769 else
770 count = SWAP_MAP_MAX;
771 } else
772 count--;
773 }
253d553b
HD
774
775 if (!count)
776 mem_cgroup_uncharge_swap(entry);
777
778 usage = count | has_cache;
779 p->swap_map[offset] = usage;
355cfa73 780
355cfa73 781 /* free if no reference */
253d553b 782 if (!usage) {
2a8f9449 783 dec_cluster_info_page(p, p->cluster_info, offset);
355cfa73
KH
784 if (offset < p->lowest_bit)
785 p->lowest_bit = offset;
786 if (offset > p->highest_bit)
787 p->highest_bit = offset;
ec8acf20
SL
788 set_highest_priority_index(p->type);
789 atomic_long_inc(&nr_swap_pages);
355cfa73 790 p->inuse_pages--;
38b5faf4 791 frontswap_invalidate_page(p->type, offset);
73744923
MG
792 if (p->flags & SWP_BLKDEV) {
793 struct gendisk *disk = p->bdev->bd_disk;
794 if (disk->fops->swap_slot_free_notify)
795 disk->fops->swap_slot_free_notify(p->bdev,
796 offset);
797 }
1da177e4 798 }
253d553b
HD
799
800 return usage;
1da177e4
LT
801}
802
803/*
804 * Caller has made sure that the swapdevice corresponding to entry
805 * is still around or has not been recycled.
806 */
807void swap_free(swp_entry_t entry)
808{
73c34b6a 809 struct swap_info_struct *p;
1da177e4
LT
810
811 p = swap_info_get(entry);
812 if (p) {
253d553b 813 swap_entry_free(p, entry, 1);
ec8acf20 814 spin_unlock(&p->lock);
1da177e4
LT
815 }
816}
817
cb4b86ba
KH
818/*
819 * Called after dropping swapcache to decrease refcnt to swap entries.
820 */
821void swapcache_free(swp_entry_t entry, struct page *page)
822{
355cfa73 823 struct swap_info_struct *p;
8d69aaee 824 unsigned char count;
355cfa73 825
355cfa73
KH
826 p = swap_info_get(entry);
827 if (p) {
253d553b
HD
828 count = swap_entry_free(p, entry, SWAP_HAS_CACHE);
829 if (page)
830 mem_cgroup_uncharge_swapcache(page, entry, count != 0);
ec8acf20 831 spin_unlock(&p->lock);
355cfa73 832 }
cb4b86ba
KH
833}
834
1da177e4 835/*
c475a8ab 836 * How many references to page are currently swapped out?
570a335b
HD
837 * This does not give an exact answer when swap count is continued,
838 * but does include the high COUNT_CONTINUED flag to allow for that.
1da177e4 839 */
bde05d1c 840int page_swapcount(struct page *page)
1da177e4 841{
c475a8ab
HD
842 int count = 0;
843 struct swap_info_struct *p;
1da177e4
LT
844 swp_entry_t entry;
845
4c21e2f2 846 entry.val = page_private(page);
1da177e4
LT
847 p = swap_info_get(entry);
848 if (p) {
355cfa73 849 count = swap_count(p->swap_map[swp_offset(entry)]);
ec8acf20 850 spin_unlock(&p->lock);
1da177e4 851 }
c475a8ab 852 return count;
1da177e4
LT
853}
854
855/*
7b1fe597
HD
856 * We can write to an anon page without COW if there are no other references
857 * to it. And as a side-effect, free up its swap: because the old content
858 * on disk will never be read, and seeking back there to write new content
859 * later would only waste time away from clustering.
1da177e4 860 */
7b1fe597 861int reuse_swap_page(struct page *page)
1da177e4 862{
c475a8ab
HD
863 int count;
864
51726b12 865 VM_BUG_ON(!PageLocked(page));
5ad64688
HD
866 if (unlikely(PageKsm(page)))
867 return 0;
c475a8ab 868 count = page_mapcount(page);
7b1fe597 869 if (count <= 1 && PageSwapCache(page)) {
c475a8ab 870 count += page_swapcount(page);
7b1fe597
HD
871 if (count == 1 && !PageWriteback(page)) {
872 delete_from_swap_cache(page);
873 SetPageDirty(page);
874 }
875 }
5ad64688 876 return count <= 1;
1da177e4
LT
877}
878
879/*
a2c43eed
HD
880 * If swap is getting full, or if there are no more mappings of this page,
881 * then try_to_free_swap is called to free its swap space.
1da177e4 882 */
a2c43eed 883int try_to_free_swap(struct page *page)
1da177e4 884{
51726b12 885 VM_BUG_ON(!PageLocked(page));
1da177e4
LT
886
887 if (!PageSwapCache(page))
888 return 0;
889 if (PageWriteback(page))
890 return 0;
a2c43eed 891 if (page_swapcount(page))
1da177e4
LT
892 return 0;
893
b73d7fce
HD
894 /*
895 * Once hibernation has begun to create its image of memory,
896 * there's a danger that one of the calls to try_to_free_swap()
897 * - most probably a call from __try_to_reclaim_swap() while
898 * hibernation is allocating its own swap pages for the image,
899 * but conceivably even a call from memory reclaim - will free
900 * the swap from a page which has already been recorded in the
901 * image as a clean swapcache page, and then reuse its swap for
902 * another page of the image. On waking from hibernation, the
903 * original page might be freed under memory pressure, then
904 * later read back in from swap, now with the wrong data.
905 *
f90ac398
MG
906 * Hibration suspends storage while it is writing the image
907 * to disk so check that here.
b73d7fce 908 */
f90ac398 909 if (pm_suspended_storage())
b73d7fce
HD
910 return 0;
911
a2c43eed
HD
912 delete_from_swap_cache(page);
913 SetPageDirty(page);
914 return 1;
68a22394
RR
915}
916
1da177e4
LT
917/*
918 * Free the swap entry like above, but also try to
919 * free the page cache entry if it is the last user.
920 */
2509ef26 921int free_swap_and_cache(swp_entry_t entry)
1da177e4 922{
2509ef26 923 struct swap_info_struct *p;
1da177e4
LT
924 struct page *page = NULL;
925
a7420aa5 926 if (non_swap_entry(entry))
2509ef26 927 return 1;
0697212a 928
1da177e4
LT
929 p = swap_info_get(entry);
930 if (p) {
253d553b 931 if (swap_entry_free(p, entry, 1) == SWAP_HAS_CACHE) {
33806f06
SL
932 page = find_get_page(swap_address_space(entry),
933 entry.val);
8413ac9d 934 if (page && !trylock_page(page)) {
93fac704
NP
935 page_cache_release(page);
936 page = NULL;
937 }
938 }
ec8acf20 939 spin_unlock(&p->lock);
1da177e4
LT
940 }
941 if (page) {
a2c43eed
HD
942 /*
943 * Not mapped elsewhere, or swap space full? Free it!
944 * Also recheck PageSwapCache now page is locked (above).
945 */
93fac704 946 if (PageSwapCache(page) && !PageWriteback(page) &&
a2c43eed 947 (!page_mapped(page) || vm_swap_full())) {
1da177e4
LT
948 delete_from_swap_cache(page);
949 SetPageDirty(page);
950 }
951 unlock_page(page);
952 page_cache_release(page);
953 }
2509ef26 954 return p != NULL;
1da177e4
LT
955}
956
b0cb1a19 957#ifdef CONFIG_HIBERNATION
f577eb30 958/*
915bae9e 959 * Find the swap type that corresponds to given device (if any).
f577eb30 960 *
915bae9e
RW
961 * @offset - number of the PAGE_SIZE-sized block of the device, starting
962 * from 0, in which the swap header is expected to be located.
963 *
964 * This is needed for the suspend to disk (aka swsusp).
f577eb30 965 */
7bf23687 966int swap_type_of(dev_t device, sector_t offset, struct block_device **bdev_p)
f577eb30 967{
915bae9e 968 struct block_device *bdev = NULL;
efa90a98 969 int type;
f577eb30 970
915bae9e
RW
971 if (device)
972 bdev = bdget(device);
973
f577eb30 974 spin_lock(&swap_lock);
efa90a98
HD
975 for (type = 0; type < nr_swapfiles; type++) {
976 struct swap_info_struct *sis = swap_info[type];
f577eb30 977
915bae9e 978 if (!(sis->flags & SWP_WRITEOK))
f577eb30 979 continue;
b6b5bce3 980
915bae9e 981 if (!bdev) {
7bf23687 982 if (bdev_p)
dddac6a7 983 *bdev_p = bdgrab(sis->bdev);
7bf23687 984
6e1819d6 985 spin_unlock(&swap_lock);
efa90a98 986 return type;
6e1819d6 987 }
915bae9e 988 if (bdev == sis->bdev) {
9625a5f2 989 struct swap_extent *se = &sis->first_swap_extent;
915bae9e 990
915bae9e 991 if (se->start_block == offset) {
7bf23687 992 if (bdev_p)
dddac6a7 993 *bdev_p = bdgrab(sis->bdev);
7bf23687 994
915bae9e
RW
995 spin_unlock(&swap_lock);
996 bdput(bdev);
efa90a98 997 return type;
915bae9e 998 }
f577eb30
RW
999 }
1000 }
1001 spin_unlock(&swap_lock);
915bae9e
RW
1002 if (bdev)
1003 bdput(bdev);
1004
f577eb30
RW
1005 return -ENODEV;
1006}
1007
73c34b6a
HD
1008/*
1009 * Get the (PAGE_SIZE) block corresponding to given offset on the swapdev
1010 * corresponding to given index in swap_info (swap type).
1011 */
1012sector_t swapdev_block(int type, pgoff_t offset)
1013{
1014 struct block_device *bdev;
1015
1016 if ((unsigned int)type >= nr_swapfiles)
1017 return 0;
1018 if (!(swap_info[type]->flags & SWP_WRITEOK))
1019 return 0;
d4906e1a 1020 return map_swap_entry(swp_entry(type, offset), &bdev);
73c34b6a
HD
1021}
1022
f577eb30
RW
1023/*
1024 * Return either the total number of swap pages of given type, or the number
1025 * of free pages of that type (depending on @free)
1026 *
1027 * This is needed for software suspend
1028 */
1029unsigned int count_swap_pages(int type, int free)
1030{
1031 unsigned int n = 0;
1032
efa90a98
HD
1033 spin_lock(&swap_lock);
1034 if ((unsigned int)type < nr_swapfiles) {
1035 struct swap_info_struct *sis = swap_info[type];
1036
ec8acf20 1037 spin_lock(&sis->lock);
efa90a98
HD
1038 if (sis->flags & SWP_WRITEOK) {
1039 n = sis->pages;
f577eb30 1040 if (free)
efa90a98 1041 n -= sis->inuse_pages;
f577eb30 1042 }
ec8acf20 1043 spin_unlock(&sis->lock);
f577eb30 1044 }
efa90a98 1045 spin_unlock(&swap_lock);
f577eb30
RW
1046 return n;
1047}
73c34b6a 1048#endif /* CONFIG_HIBERNATION */
f577eb30 1049
179ef71c
CG
1050static inline int maybe_same_pte(pte_t pte, pte_t swp_pte)
1051{
1052#ifdef CONFIG_MEM_SOFT_DIRTY
1053 /*
1054 * When pte keeps soft dirty bit the pte generated
1055 * from swap entry does not has it, still it's same
1056 * pte from logical point of view.
1057 */
1058 pte_t swp_pte_dirty = pte_swp_mksoft_dirty(swp_pte);
1059 return pte_same(pte, swp_pte) || pte_same(pte, swp_pte_dirty);
1060#else
1061 return pte_same(pte, swp_pte);
1062#endif
1063}
1064
1da177e4 1065/*
72866f6f
HD
1066 * No need to decide whether this PTE shares the swap entry with others,
1067 * just let do_wp_page work it out if a write is requested later - to
1068 * force COW, vm_page_prot omits write permission from any private vma.
1da177e4 1069 */
044d66c1 1070static int unuse_pte(struct vm_area_struct *vma, pmd_t *pmd,
1da177e4
LT
1071 unsigned long addr, swp_entry_t entry, struct page *page)
1072{
9e16b7fb 1073 struct page *swapcache;
72835c86 1074 struct mem_cgroup *memcg;
044d66c1
HD
1075 spinlock_t *ptl;
1076 pte_t *pte;
1077 int ret = 1;
1078
9e16b7fb
HD
1079 swapcache = page;
1080 page = ksm_might_need_to_copy(page, vma, addr);
1081 if (unlikely(!page))
1082 return -ENOMEM;
1083
72835c86
JW
1084 if (mem_cgroup_try_charge_swapin(vma->vm_mm, page,
1085 GFP_KERNEL, &memcg)) {
044d66c1 1086 ret = -ENOMEM;
85d9fc89
KH
1087 goto out_nolock;
1088 }
044d66c1
HD
1089
1090 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
179ef71c 1091 if (unlikely(!maybe_same_pte(*pte, swp_entry_to_pte(entry)))) {
5d84c776 1092 mem_cgroup_cancel_charge_swapin(memcg);
044d66c1
HD
1093 ret = 0;
1094 goto out;
1095 }
8a9f3ccd 1096
b084d435 1097 dec_mm_counter(vma->vm_mm, MM_SWAPENTS);
d559db08 1098 inc_mm_counter(vma->vm_mm, MM_ANONPAGES);
1da177e4
LT
1099 get_page(page);
1100 set_pte_at(vma->vm_mm, addr, pte,
1101 pte_mkold(mk_pte(page, vma->vm_page_prot)));
9e16b7fb
HD
1102 if (page == swapcache)
1103 page_add_anon_rmap(page, vma, addr);
1104 else /* ksm created a completely new copy */
1105 page_add_new_anon_rmap(page, vma, addr);
72835c86 1106 mem_cgroup_commit_charge_swapin(page, memcg);
1da177e4
LT
1107 swap_free(entry);
1108 /*
1109 * Move the page to the active list so it is not
1110 * immediately swapped out again after swapon.
1111 */
1112 activate_page(page);
044d66c1
HD
1113out:
1114 pte_unmap_unlock(pte, ptl);
85d9fc89 1115out_nolock:
9e16b7fb
HD
1116 if (page != swapcache) {
1117 unlock_page(page);
1118 put_page(page);
1119 }
044d66c1 1120 return ret;
1da177e4
LT
1121}
1122
1123static int unuse_pte_range(struct vm_area_struct *vma, pmd_t *pmd,
1124 unsigned long addr, unsigned long end,
1125 swp_entry_t entry, struct page *page)
1126{
1da177e4 1127 pte_t swp_pte = swp_entry_to_pte(entry);
705e87c0 1128 pte_t *pte;
8a9f3ccd 1129 int ret = 0;
1da177e4 1130
044d66c1
HD
1131 /*
1132 * We don't actually need pte lock while scanning for swp_pte: since
1133 * we hold page lock and mmap_sem, swp_pte cannot be inserted into the
1134 * page table while we're scanning; though it could get zapped, and on
1135 * some architectures (e.g. x86_32 with PAE) we might catch a glimpse
1136 * of unmatched parts which look like swp_pte, so unuse_pte must
1137 * recheck under pte lock. Scanning without pte lock lets it be
1138 * preemptible whenever CONFIG_PREEMPT but not CONFIG_HIGHPTE.
1139 */
1140 pte = pte_offset_map(pmd, addr);
1da177e4
LT
1141 do {
1142 /*
1143 * swapoff spends a _lot_ of time in this loop!
1144 * Test inline before going to call unuse_pte.
1145 */
179ef71c 1146 if (unlikely(maybe_same_pte(*pte, swp_pte))) {
044d66c1
HD
1147 pte_unmap(pte);
1148 ret = unuse_pte(vma, pmd, addr, entry, page);
1149 if (ret)
1150 goto out;
1151 pte = pte_offset_map(pmd, addr);
1da177e4
LT
1152 }
1153 } while (pte++, addr += PAGE_SIZE, addr != end);
044d66c1
HD
1154 pte_unmap(pte - 1);
1155out:
8a9f3ccd 1156 return ret;
1da177e4
LT
1157}
1158
1159static inline int unuse_pmd_range(struct vm_area_struct *vma, pud_t *pud,
1160 unsigned long addr, unsigned long end,
1161 swp_entry_t entry, struct page *page)
1162{
1163 pmd_t *pmd;
1164 unsigned long next;
8a9f3ccd 1165 int ret;
1da177e4
LT
1166
1167 pmd = pmd_offset(pud, addr);
1168 do {
1169 next = pmd_addr_end(addr, end);
1a5a9906 1170 if (pmd_none_or_trans_huge_or_clear_bad(pmd))
1da177e4 1171 continue;
8a9f3ccd
BS
1172 ret = unuse_pte_range(vma, pmd, addr, next, entry, page);
1173 if (ret)
1174 return ret;
1da177e4
LT
1175 } while (pmd++, addr = next, addr != end);
1176 return 0;
1177}
1178
1179static inline int unuse_pud_range(struct vm_area_struct *vma, pgd_t *pgd,
1180 unsigned long addr, unsigned long end,
1181 swp_entry_t entry, struct page *page)
1182{
1183 pud_t *pud;
1184 unsigned long next;
8a9f3ccd 1185 int ret;
1da177e4
LT
1186
1187 pud = pud_offset(pgd, addr);
1188 do {
1189 next = pud_addr_end(addr, end);
1190 if (pud_none_or_clear_bad(pud))
1191 continue;
8a9f3ccd
BS
1192 ret = unuse_pmd_range(vma, pud, addr, next, entry, page);
1193 if (ret)
1194 return ret;
1da177e4
LT
1195 } while (pud++, addr = next, addr != end);
1196 return 0;
1197}
1198
1199static int unuse_vma(struct vm_area_struct *vma,
1200 swp_entry_t entry, struct page *page)
1201{
1202 pgd_t *pgd;
1203 unsigned long addr, end, next;
8a9f3ccd 1204 int ret;
1da177e4 1205
3ca7b3c5 1206 if (page_anon_vma(page)) {
1da177e4
LT
1207 addr = page_address_in_vma(page, vma);
1208 if (addr == -EFAULT)
1209 return 0;
1210 else
1211 end = addr + PAGE_SIZE;
1212 } else {
1213 addr = vma->vm_start;
1214 end = vma->vm_end;
1215 }
1216
1217 pgd = pgd_offset(vma->vm_mm, addr);
1218 do {
1219 next = pgd_addr_end(addr, end);
1220 if (pgd_none_or_clear_bad(pgd))
1221 continue;
8a9f3ccd
BS
1222 ret = unuse_pud_range(vma, pgd, addr, next, entry, page);
1223 if (ret)
1224 return ret;
1da177e4
LT
1225 } while (pgd++, addr = next, addr != end);
1226 return 0;
1227}
1228
1229static int unuse_mm(struct mm_struct *mm,
1230 swp_entry_t entry, struct page *page)
1231{
1232 struct vm_area_struct *vma;
8a9f3ccd 1233 int ret = 0;
1da177e4
LT
1234
1235 if (!down_read_trylock(&mm->mmap_sem)) {
1236 /*
7d03431c
FLVC
1237 * Activate page so shrink_inactive_list is unlikely to unmap
1238 * its ptes while lock is dropped, so swapoff can make progress.
1da177e4 1239 */
c475a8ab 1240 activate_page(page);
1da177e4
LT
1241 unlock_page(page);
1242 down_read(&mm->mmap_sem);
1243 lock_page(page);
1244 }
1da177e4 1245 for (vma = mm->mmap; vma; vma = vma->vm_next) {
8a9f3ccd 1246 if (vma->anon_vma && (ret = unuse_vma(vma, entry, page)))
1da177e4
LT
1247 break;
1248 }
1da177e4 1249 up_read(&mm->mmap_sem);
8a9f3ccd 1250 return (ret < 0)? ret: 0;
1da177e4
LT
1251}
1252
1253/*
38b5faf4
DM
1254 * Scan swap_map (or frontswap_map if frontswap parameter is true)
1255 * from current position to next entry still in use.
1da177e4
LT
1256 * Recycle to start on reaching the end, returning 0 when empty.
1257 */
6eb396dc 1258static unsigned int find_next_to_unuse(struct swap_info_struct *si,
38b5faf4 1259 unsigned int prev, bool frontswap)
1da177e4 1260{
6eb396dc
HD
1261 unsigned int max = si->max;
1262 unsigned int i = prev;
8d69aaee 1263 unsigned char count;
1da177e4
LT
1264
1265 /*
5d337b91 1266 * No need for swap_lock here: we're just looking
1da177e4
LT
1267 * for whether an entry is in use, not modifying it; false
1268 * hits are okay, and sys_swapoff() has already prevented new
5d337b91 1269 * allocations from this area (while holding swap_lock).
1da177e4
LT
1270 */
1271 for (;;) {
1272 if (++i >= max) {
1273 if (!prev) {
1274 i = 0;
1275 break;
1276 }
1277 /*
1278 * No entries in use at top of swap_map,
1279 * loop back to start and recheck there.
1280 */
1281 max = prev + 1;
1282 prev = 0;
1283 i = 1;
1284 }
38b5faf4
DM
1285 if (frontswap) {
1286 if (frontswap_test(si, i))
1287 break;
1288 else
1289 continue;
1290 }
1da177e4 1291 count = si->swap_map[i];
355cfa73 1292 if (count && swap_count(count) != SWAP_MAP_BAD)
1da177e4
LT
1293 break;
1294 }
1295 return i;
1296}
1297
1298/*
1299 * We completely avoid races by reading each swap page in advance,
1300 * and then search for the process using it. All the necessary
1301 * page table adjustments can then be made atomically.
38b5faf4
DM
1302 *
1303 * if the boolean frontswap is true, only unuse pages_to_unuse pages;
1304 * pages_to_unuse==0 means all pages; ignored if frontswap is false
1da177e4 1305 */
38b5faf4
DM
1306int try_to_unuse(unsigned int type, bool frontswap,
1307 unsigned long pages_to_unuse)
1da177e4 1308{
efa90a98 1309 struct swap_info_struct *si = swap_info[type];
1da177e4 1310 struct mm_struct *start_mm;
8d69aaee
HD
1311 unsigned char *swap_map;
1312 unsigned char swcount;
1da177e4
LT
1313 struct page *page;
1314 swp_entry_t entry;
6eb396dc 1315 unsigned int i = 0;
1da177e4 1316 int retval = 0;
1da177e4
LT
1317
1318 /*
1319 * When searching mms for an entry, a good strategy is to
1320 * start at the first mm we freed the previous entry from
1321 * (though actually we don't notice whether we or coincidence
1322 * freed the entry). Initialize this start_mm with a hold.
1323 *
1324 * A simpler strategy would be to start at the last mm we
1325 * freed the previous entry from; but that would take less
1326 * advantage of mmlist ordering, which clusters forked mms
1327 * together, child after parent. If we race with dup_mmap(), we
1328 * prefer to resolve parent before child, lest we miss entries
1329 * duplicated after we scanned child: using last mm would invert
570a335b 1330 * that.
1da177e4
LT
1331 */
1332 start_mm = &init_mm;
1333 atomic_inc(&init_mm.mm_users);
1334
1335 /*
1336 * Keep on scanning until all entries have gone. Usually,
1337 * one pass through swap_map is enough, but not necessarily:
1338 * there are races when an instance of an entry might be missed.
1339 */
38b5faf4 1340 while ((i = find_next_to_unuse(si, i, frontswap)) != 0) {
1da177e4
LT
1341 if (signal_pending(current)) {
1342 retval = -EINTR;
1343 break;
1344 }
1345
886bb7e9 1346 /*
1da177e4
LT
1347 * Get a page for the entry, using the existing swap
1348 * cache page if there is one. Otherwise, get a clean
886bb7e9 1349 * page and read the swap into it.
1da177e4
LT
1350 */
1351 swap_map = &si->swap_map[i];
1352 entry = swp_entry(type, i);
02098fea
HD
1353 page = read_swap_cache_async(entry,
1354 GFP_HIGHUSER_MOVABLE, NULL, 0);
1da177e4
LT
1355 if (!page) {
1356 /*
1357 * Either swap_duplicate() failed because entry
1358 * has been freed independently, and will not be
1359 * reused since sys_swapoff() already disabled
1360 * allocation from here, or alloc_page() failed.
1361 */
1362 if (!*swap_map)
1363 continue;
1364 retval = -ENOMEM;
1365 break;
1366 }
1367
1368 /*
1369 * Don't hold on to start_mm if it looks like exiting.
1370 */
1371 if (atomic_read(&start_mm->mm_users) == 1) {
1372 mmput(start_mm);
1373 start_mm = &init_mm;
1374 atomic_inc(&init_mm.mm_users);
1375 }
1376
1377 /*
1378 * Wait for and lock page. When do_swap_page races with
1379 * try_to_unuse, do_swap_page can handle the fault much
1380 * faster than try_to_unuse can locate the entry. This
1381 * apparently redundant "wait_on_page_locked" lets try_to_unuse
1382 * defer to do_swap_page in such a case - in some tests,
1383 * do_swap_page and try_to_unuse repeatedly compete.
1384 */
1385 wait_on_page_locked(page);
1386 wait_on_page_writeback(page);
1387 lock_page(page);
1388 wait_on_page_writeback(page);
1389
1390 /*
1391 * Remove all references to entry.
1da177e4 1392 */
1da177e4 1393 swcount = *swap_map;
aaa46865
HD
1394 if (swap_count(swcount) == SWAP_MAP_SHMEM) {
1395 retval = shmem_unuse(entry, page);
1396 /* page has already been unlocked and released */
1397 if (retval < 0)
1398 break;
1399 continue;
1da177e4 1400 }
aaa46865
HD
1401 if (swap_count(swcount) && start_mm != &init_mm)
1402 retval = unuse_mm(start_mm, entry, page);
1403
355cfa73 1404 if (swap_count(*swap_map)) {
1da177e4
LT
1405 int set_start_mm = (*swap_map >= swcount);
1406 struct list_head *p = &start_mm->mmlist;
1407 struct mm_struct *new_start_mm = start_mm;
1408 struct mm_struct *prev_mm = start_mm;
1409 struct mm_struct *mm;
1410
1411 atomic_inc(&new_start_mm->mm_users);
1412 atomic_inc(&prev_mm->mm_users);
1413 spin_lock(&mmlist_lock);
aaa46865 1414 while (swap_count(*swap_map) && !retval &&
1da177e4
LT
1415 (p = p->next) != &start_mm->mmlist) {
1416 mm = list_entry(p, struct mm_struct, mmlist);
70af7c5c 1417 if (!atomic_inc_not_zero(&mm->mm_users))
1da177e4 1418 continue;
1da177e4
LT
1419 spin_unlock(&mmlist_lock);
1420 mmput(prev_mm);
1421 prev_mm = mm;
1422
1423 cond_resched();
1424
1425 swcount = *swap_map;
355cfa73 1426 if (!swap_count(swcount)) /* any usage ? */
1da177e4 1427 ;
aaa46865 1428 else if (mm == &init_mm)
1da177e4 1429 set_start_mm = 1;
aaa46865 1430 else
1da177e4 1431 retval = unuse_mm(mm, entry, page);
355cfa73 1432
32c5fc10 1433 if (set_start_mm && *swap_map < swcount) {
1da177e4
LT
1434 mmput(new_start_mm);
1435 atomic_inc(&mm->mm_users);
1436 new_start_mm = mm;
1437 set_start_mm = 0;
1438 }
1439 spin_lock(&mmlist_lock);
1440 }
1441 spin_unlock(&mmlist_lock);
1442 mmput(prev_mm);
1443 mmput(start_mm);
1444 start_mm = new_start_mm;
1445 }
1446 if (retval) {
1447 unlock_page(page);
1448 page_cache_release(page);
1449 break;
1450 }
1451
1da177e4
LT
1452 /*
1453 * If a reference remains (rare), we would like to leave
1454 * the page in the swap cache; but try_to_unmap could
1455 * then re-duplicate the entry once we drop page lock,
1456 * so we might loop indefinitely; also, that page could
1457 * not be swapped out to other storage meanwhile. So:
1458 * delete from cache even if there's another reference,
1459 * after ensuring that the data has been saved to disk -
1460 * since if the reference remains (rarer), it will be
1461 * read from disk into another page. Splitting into two
1462 * pages would be incorrect if swap supported "shared
1463 * private" pages, but they are handled by tmpfs files.
5ad64688
HD
1464 *
1465 * Given how unuse_vma() targets one particular offset
1466 * in an anon_vma, once the anon_vma has been determined,
1467 * this splitting happens to be just what is needed to
1468 * handle where KSM pages have been swapped out: re-reading
1469 * is unnecessarily slow, but we can fix that later on.
1da177e4 1470 */
355cfa73
KH
1471 if (swap_count(*swap_map) &&
1472 PageDirty(page) && PageSwapCache(page)) {
1da177e4
LT
1473 struct writeback_control wbc = {
1474 .sync_mode = WB_SYNC_NONE,
1475 };
1476
1477 swap_writepage(page, &wbc);
1478 lock_page(page);
1479 wait_on_page_writeback(page);
1480 }
68bdc8d6
HD
1481
1482 /*
1483 * It is conceivable that a racing task removed this page from
1484 * swap cache just before we acquired the page lock at the top,
1485 * or while we dropped it in unuse_mm(). The page might even
1486 * be back in swap cache on another swap area: that we must not
1487 * delete, since it may not have been written out to swap yet.
1488 */
1489 if (PageSwapCache(page) &&
1490 likely(page_private(page) == entry.val))
2e0e26c7 1491 delete_from_swap_cache(page);
1da177e4
LT
1492
1493 /*
1494 * So we could skip searching mms once swap count went
1495 * to 1, we did not mark any present ptes as dirty: must
2706a1b8 1496 * mark page dirty so shrink_page_list will preserve it.
1da177e4
LT
1497 */
1498 SetPageDirty(page);
1499 unlock_page(page);
1500 page_cache_release(page);
1501
1502 /*
1503 * Make sure that we aren't completely killing
1504 * interactive performance.
1505 */
1506 cond_resched();
38b5faf4
DM
1507 if (frontswap && pages_to_unuse > 0) {
1508 if (!--pages_to_unuse)
1509 break;
1510 }
1da177e4
LT
1511 }
1512
1513 mmput(start_mm);
1da177e4
LT
1514 return retval;
1515}
1516
1517/*
5d337b91
HD
1518 * After a successful try_to_unuse, if no swap is now in use, we know
1519 * we can empty the mmlist. swap_lock must be held on entry and exit.
1520 * Note that mmlist_lock nests inside swap_lock, and an mm must be
1da177e4
LT
1521 * added to the mmlist just after page_duplicate - before would be racy.
1522 */
1523static void drain_mmlist(void)
1524{
1525 struct list_head *p, *next;
efa90a98 1526 unsigned int type;
1da177e4 1527
efa90a98
HD
1528 for (type = 0; type < nr_swapfiles; type++)
1529 if (swap_info[type]->inuse_pages)
1da177e4
LT
1530 return;
1531 spin_lock(&mmlist_lock);
1532 list_for_each_safe(p, next, &init_mm.mmlist)
1533 list_del_init(p);
1534 spin_unlock(&mmlist_lock);
1535}
1536
1537/*
1538 * Use this swapdev's extent info to locate the (PAGE_SIZE) block which
d4906e1a
LS
1539 * corresponds to page offset for the specified swap entry.
1540 * Note that the type of this function is sector_t, but it returns page offset
1541 * into the bdev, not sector offset.
1da177e4 1542 */
d4906e1a 1543static sector_t map_swap_entry(swp_entry_t entry, struct block_device **bdev)
1da177e4 1544{
f29ad6a9
HD
1545 struct swap_info_struct *sis;
1546 struct swap_extent *start_se;
1547 struct swap_extent *se;
1548 pgoff_t offset;
1549
efa90a98 1550 sis = swap_info[swp_type(entry)];
f29ad6a9
HD
1551 *bdev = sis->bdev;
1552
1553 offset = swp_offset(entry);
1554 start_se = sis->curr_swap_extent;
1555 se = start_se;
1da177e4
LT
1556
1557 for ( ; ; ) {
1558 struct list_head *lh;
1559
1560 if (se->start_page <= offset &&
1561 offset < (se->start_page + se->nr_pages)) {
1562 return se->start_block + (offset - se->start_page);
1563 }
11d31886 1564 lh = se->list.next;
1da177e4
LT
1565 se = list_entry(lh, struct swap_extent, list);
1566 sis->curr_swap_extent = se;
1567 BUG_ON(se == start_se); /* It *must* be present */
1568 }
1569}
1570
d4906e1a
LS
1571/*
1572 * Returns the page offset into bdev for the specified page's swap entry.
1573 */
1574sector_t map_swap_page(struct page *page, struct block_device **bdev)
1575{
1576 swp_entry_t entry;
1577 entry.val = page_private(page);
1578 return map_swap_entry(entry, bdev);
1579}
1580
1da177e4
LT
1581/*
1582 * Free all of a swapdev's extent information
1583 */
1584static void destroy_swap_extents(struct swap_info_struct *sis)
1585{
9625a5f2 1586 while (!list_empty(&sis->first_swap_extent.list)) {
1da177e4
LT
1587 struct swap_extent *se;
1588
9625a5f2 1589 se = list_entry(sis->first_swap_extent.list.next,
1da177e4
LT
1590 struct swap_extent, list);
1591 list_del(&se->list);
1592 kfree(se);
1593 }
62c230bc
MG
1594
1595 if (sis->flags & SWP_FILE) {
1596 struct file *swap_file = sis->swap_file;
1597 struct address_space *mapping = swap_file->f_mapping;
1598
1599 sis->flags &= ~SWP_FILE;
1600 mapping->a_ops->swap_deactivate(swap_file);
1601 }
1da177e4
LT
1602}
1603
1604/*
1605 * Add a block range (and the corresponding page range) into this swapdev's
11d31886 1606 * extent list. The extent list is kept sorted in page order.
1da177e4 1607 *
11d31886 1608 * This function rather assumes that it is called in ascending page order.
1da177e4 1609 */
a509bc1a 1610int
1da177e4
LT
1611add_swap_extent(struct swap_info_struct *sis, unsigned long start_page,
1612 unsigned long nr_pages, sector_t start_block)
1613{
1614 struct swap_extent *se;
1615 struct swap_extent *new_se;
1616 struct list_head *lh;
1617
9625a5f2
HD
1618 if (start_page == 0) {
1619 se = &sis->first_swap_extent;
1620 sis->curr_swap_extent = se;
1621 se->start_page = 0;
1622 se->nr_pages = nr_pages;
1623 se->start_block = start_block;
1624 return 1;
1625 } else {
1626 lh = sis->first_swap_extent.list.prev; /* Highest extent */
1da177e4 1627 se = list_entry(lh, struct swap_extent, list);
11d31886
HD
1628 BUG_ON(se->start_page + se->nr_pages != start_page);
1629 if (se->start_block + se->nr_pages == start_block) {
1da177e4
LT
1630 /* Merge it */
1631 se->nr_pages += nr_pages;
1632 return 0;
1633 }
1da177e4
LT
1634 }
1635
1636 /*
1637 * No merge. Insert a new extent, preserving ordering.
1638 */
1639 new_se = kmalloc(sizeof(*se), GFP_KERNEL);
1640 if (new_se == NULL)
1641 return -ENOMEM;
1642 new_se->start_page = start_page;
1643 new_se->nr_pages = nr_pages;
1644 new_se->start_block = start_block;
1645
9625a5f2 1646 list_add_tail(&new_se->list, &sis->first_swap_extent.list);
53092a74 1647 return 1;
1da177e4
LT
1648}
1649
1650/*
1651 * A `swap extent' is a simple thing which maps a contiguous range of pages
1652 * onto a contiguous range of disk blocks. An ordered list of swap extents
1653 * is built at swapon time and is then used at swap_writepage/swap_readpage
1654 * time for locating where on disk a page belongs.
1655 *
1656 * If the swapfile is an S_ISBLK block device, a single extent is installed.
1657 * This is done so that the main operating code can treat S_ISBLK and S_ISREG
1658 * swap files identically.
1659 *
1660 * Whether the swapdev is an S_ISREG file or an S_ISBLK blockdev, the swap
1661 * extent list operates in PAGE_SIZE disk blocks. Both S_ISREG and S_ISBLK
1662 * swapfiles are handled *identically* after swapon time.
1663 *
1664 * For S_ISREG swapfiles, setup_swap_extents() will walk all the file's blocks
1665 * and will parse them into an ordered extent list, in PAGE_SIZE chunks. If
1666 * some stray blocks are found which do not fall within the PAGE_SIZE alignment
1667 * requirements, they are simply tossed out - we will never use those blocks
1668 * for swapping.
1669 *
b0d9bcd4 1670 * For S_ISREG swapfiles we set S_SWAPFILE across the life of the swapon. This
1da177e4
LT
1671 * prevents root from shooting her foot off by ftruncating an in-use swapfile,
1672 * which will scribble on the fs.
1673 *
1674 * The amount of disk space which a single swap extent represents varies.
1675 * Typically it is in the 1-4 megabyte range. So we can have hundreds of
1676 * extents in the list. To avoid much list walking, we cache the previous
1677 * search location in `curr_swap_extent', and start new searches from there.
1678 * This is extremely effective. The average number of iterations in
1679 * map_swap_page() has been measured at about 0.3 per page. - akpm.
1680 */
53092a74 1681static int setup_swap_extents(struct swap_info_struct *sis, sector_t *span)
1da177e4 1682{
62c230bc
MG
1683 struct file *swap_file = sis->swap_file;
1684 struct address_space *mapping = swap_file->f_mapping;
1685 struct inode *inode = mapping->host;
1da177e4
LT
1686 int ret;
1687
1da177e4
LT
1688 if (S_ISBLK(inode->i_mode)) {
1689 ret = add_swap_extent(sis, 0, sis->max, 0);
53092a74 1690 *span = sis->pages;
a509bc1a 1691 return ret;
1da177e4
LT
1692 }
1693
62c230bc 1694 if (mapping->a_ops->swap_activate) {
a509bc1a 1695 ret = mapping->a_ops->swap_activate(sis, swap_file, span);
62c230bc
MG
1696 if (!ret) {
1697 sis->flags |= SWP_FILE;
1698 ret = add_swap_extent(sis, 0, sis->max, 0);
1699 *span = sis->pages;
1700 }
a509bc1a 1701 return ret;
62c230bc
MG
1702 }
1703
a509bc1a 1704 return generic_swapfile_activate(sis, swap_file, span);
1da177e4
LT
1705}
1706
cf0cac0a 1707static void _enable_swap_info(struct swap_info_struct *p, int prio,
2a8f9449
SL
1708 unsigned char *swap_map,
1709 struct swap_cluster_info *cluster_info)
40531542
CEB
1710{
1711 int i, prev;
1712
40531542
CEB
1713 if (prio >= 0)
1714 p->prio = prio;
1715 else
1716 p->prio = --least_priority;
1717 p->swap_map = swap_map;
2a8f9449 1718 p->cluster_info = cluster_info;
40531542 1719 p->flags |= SWP_WRITEOK;
ec8acf20 1720 atomic_long_add(p->pages, &nr_swap_pages);
40531542
CEB
1721 total_swap_pages += p->pages;
1722
1723 /* insert swap space into swap_list: */
1724 prev = -1;
1725 for (i = swap_list.head; i >= 0; i = swap_info[i]->next) {
1726 if (p->prio >= swap_info[i]->prio)
1727 break;
1728 prev = i;
1729 }
1730 p->next = i;
1731 if (prev < 0)
1732 swap_list.head = swap_list.next = p->type;
1733 else
1734 swap_info[prev]->next = p->type;
cf0cac0a
CEB
1735}
1736
1737static void enable_swap_info(struct swap_info_struct *p, int prio,
1738 unsigned char *swap_map,
2a8f9449 1739 struct swap_cluster_info *cluster_info,
cf0cac0a
CEB
1740 unsigned long *frontswap_map)
1741{
4f89849d 1742 frontswap_init(p->type, frontswap_map);
cf0cac0a 1743 spin_lock(&swap_lock);
ec8acf20 1744 spin_lock(&p->lock);
2a8f9449 1745 _enable_swap_info(p, prio, swap_map, cluster_info);
ec8acf20 1746 spin_unlock(&p->lock);
cf0cac0a
CEB
1747 spin_unlock(&swap_lock);
1748}
1749
1750static void reinsert_swap_info(struct swap_info_struct *p)
1751{
1752 spin_lock(&swap_lock);
ec8acf20 1753 spin_lock(&p->lock);
2a8f9449 1754 _enable_swap_info(p, p->prio, p->swap_map, p->cluster_info);
ec8acf20 1755 spin_unlock(&p->lock);
40531542
CEB
1756 spin_unlock(&swap_lock);
1757}
1758
c4ea37c2 1759SYSCALL_DEFINE1(swapoff, const char __user *, specialfile)
1da177e4 1760{
73c34b6a 1761 struct swap_info_struct *p = NULL;
8d69aaee 1762 unsigned char *swap_map;
2a8f9449 1763 struct swap_cluster_info *cluster_info;
4f89849d 1764 unsigned long *frontswap_map;
1da177e4
LT
1765 struct file *swap_file, *victim;
1766 struct address_space *mapping;
1767 struct inode *inode;
91a27b2a 1768 struct filename *pathname;
1da177e4
LT
1769 int i, type, prev;
1770 int err;
886bb7e9 1771
1da177e4
LT
1772 if (!capable(CAP_SYS_ADMIN))
1773 return -EPERM;
1774
191c5424
AV
1775 BUG_ON(!current->mm);
1776
1da177e4 1777 pathname = getname(specialfile);
1da177e4 1778 if (IS_ERR(pathname))
f58b59c1 1779 return PTR_ERR(pathname);
1da177e4 1780
669abf4e 1781 victim = file_open_name(pathname, O_RDWR|O_LARGEFILE, 0);
1da177e4
LT
1782 err = PTR_ERR(victim);
1783 if (IS_ERR(victim))
1784 goto out;
1785
1786 mapping = victim->f_mapping;
1787 prev = -1;
5d337b91 1788 spin_lock(&swap_lock);
efa90a98
HD
1789 for (type = swap_list.head; type >= 0; type = swap_info[type]->next) {
1790 p = swap_info[type];
22c6f8fd 1791 if (p->flags & SWP_WRITEOK) {
1da177e4
LT
1792 if (p->swap_file->f_mapping == mapping)
1793 break;
1794 }
1795 prev = type;
1796 }
1797 if (type < 0) {
1798 err = -EINVAL;
5d337b91 1799 spin_unlock(&swap_lock);
1da177e4
LT
1800 goto out_dput;
1801 }
191c5424 1802 if (!security_vm_enough_memory_mm(current->mm, p->pages))
1da177e4
LT
1803 vm_unacct_memory(p->pages);
1804 else {
1805 err = -ENOMEM;
5d337b91 1806 spin_unlock(&swap_lock);
1da177e4
LT
1807 goto out_dput;
1808 }
efa90a98 1809 if (prev < 0)
1da177e4 1810 swap_list.head = p->next;
efa90a98
HD
1811 else
1812 swap_info[prev]->next = p->next;
1da177e4
LT
1813 if (type == swap_list.next) {
1814 /* just pick something that's safe... */
1815 swap_list.next = swap_list.head;
1816 }
ec8acf20 1817 spin_lock(&p->lock);
78ecba08 1818 if (p->prio < 0) {
efa90a98
HD
1819 for (i = p->next; i >= 0; i = swap_info[i]->next)
1820 swap_info[i]->prio = p->prio--;
78ecba08
HD
1821 least_priority++;
1822 }
ec8acf20 1823 atomic_long_sub(p->pages, &nr_swap_pages);
1da177e4
LT
1824 total_swap_pages -= p->pages;
1825 p->flags &= ~SWP_WRITEOK;
ec8acf20 1826 spin_unlock(&p->lock);
5d337b91 1827 spin_unlock(&swap_lock);
fb4f88dc 1828
e1e12d2f 1829 set_current_oom_origin();
38b5faf4 1830 err = try_to_unuse(type, false, 0); /* force all pages to be unused */
e1e12d2f 1831 clear_current_oom_origin();
1da177e4 1832
1da177e4
LT
1833 if (err) {
1834 /* re-insert swap space back into swap_list */
cf0cac0a 1835 reinsert_swap_info(p);
1da177e4
LT
1836 goto out_dput;
1837 }
52b7efdb 1838
815c2c54
SL
1839 flush_work(&p->discard_work);
1840
5d337b91 1841 destroy_swap_extents(p);
570a335b
HD
1842 if (p->flags & SWP_CONTINUED)
1843 free_swap_count_continuations(p);
1844
fc0abb14 1845 mutex_lock(&swapon_mutex);
5d337b91 1846 spin_lock(&swap_lock);
ec8acf20 1847 spin_lock(&p->lock);
5d337b91
HD
1848 drain_mmlist();
1849
52b7efdb 1850 /* wait for anyone still in scan_swap_map */
52b7efdb
HD
1851 p->highest_bit = 0; /* cuts scans short */
1852 while (p->flags >= SWP_SCANNING) {
ec8acf20 1853 spin_unlock(&p->lock);
5d337b91 1854 spin_unlock(&swap_lock);
13e4b57f 1855 schedule_timeout_uninterruptible(1);
5d337b91 1856 spin_lock(&swap_lock);
ec8acf20 1857 spin_lock(&p->lock);
52b7efdb 1858 }
52b7efdb 1859
1da177e4
LT
1860 swap_file = p->swap_file;
1861 p->swap_file = NULL;
1862 p->max = 0;
1863 swap_map = p->swap_map;
1864 p->swap_map = NULL;
2a8f9449
SL
1865 cluster_info = p->cluster_info;
1866 p->cluster_info = NULL;
1da177e4 1867 p->flags = 0;
4f89849d
MK
1868 frontswap_map = frontswap_map_get(p);
1869 frontswap_map_set(p, NULL);
ec8acf20 1870 spin_unlock(&p->lock);
5d337b91 1871 spin_unlock(&swap_lock);
4f89849d 1872 frontswap_invalidate_area(type);
fc0abb14 1873 mutex_unlock(&swapon_mutex);
1da177e4 1874 vfree(swap_map);
2a8f9449 1875 vfree(cluster_info);
4f89849d 1876 vfree(frontswap_map);
27a7faa0
KH
1877 /* Destroy swap account informatin */
1878 swap_cgroup_swapoff(type);
1879
1da177e4
LT
1880 inode = mapping->host;
1881 if (S_ISBLK(inode->i_mode)) {
1882 struct block_device *bdev = I_BDEV(inode);
1883 set_blocksize(bdev, p->old_block_size);
e525fd89 1884 blkdev_put(bdev, FMODE_READ | FMODE_WRITE | FMODE_EXCL);
1da177e4 1885 } else {
1b1dcc1b 1886 mutex_lock(&inode->i_mutex);
1da177e4 1887 inode->i_flags &= ~S_SWAPFILE;
1b1dcc1b 1888 mutex_unlock(&inode->i_mutex);
1da177e4
LT
1889 }
1890 filp_close(swap_file, NULL);
1891 err = 0;
66d7dd51
KS
1892 atomic_inc(&proc_poll_event);
1893 wake_up_interruptible(&proc_poll_wait);
1da177e4
LT
1894
1895out_dput:
1896 filp_close(victim, NULL);
1897out:
f58b59c1 1898 putname(pathname);
1da177e4
LT
1899 return err;
1900}
1901
1902#ifdef CONFIG_PROC_FS
66d7dd51
KS
1903static unsigned swaps_poll(struct file *file, poll_table *wait)
1904{
f1514638 1905 struct seq_file *seq = file->private_data;
66d7dd51
KS
1906
1907 poll_wait(file, &proc_poll_wait, wait);
1908
f1514638
KS
1909 if (seq->poll_event != atomic_read(&proc_poll_event)) {
1910 seq->poll_event = atomic_read(&proc_poll_event);
66d7dd51
KS
1911 return POLLIN | POLLRDNORM | POLLERR | POLLPRI;
1912 }
1913
1914 return POLLIN | POLLRDNORM;
1915}
1916
1da177e4
LT
1917/* iterator */
1918static void *swap_start(struct seq_file *swap, loff_t *pos)
1919{
efa90a98
HD
1920 struct swap_info_struct *si;
1921 int type;
1da177e4
LT
1922 loff_t l = *pos;
1923
fc0abb14 1924 mutex_lock(&swapon_mutex);
1da177e4 1925
881e4aab
SS
1926 if (!l)
1927 return SEQ_START_TOKEN;
1928
efa90a98
HD
1929 for (type = 0; type < nr_swapfiles; type++) {
1930 smp_rmb(); /* read nr_swapfiles before swap_info[type] */
1931 si = swap_info[type];
1932 if (!(si->flags & SWP_USED) || !si->swap_map)
1da177e4 1933 continue;
881e4aab 1934 if (!--l)
efa90a98 1935 return si;
1da177e4
LT
1936 }
1937
1938 return NULL;
1939}
1940
1941static void *swap_next(struct seq_file *swap, void *v, loff_t *pos)
1942{
efa90a98
HD
1943 struct swap_info_struct *si = v;
1944 int type;
1da177e4 1945
881e4aab 1946 if (v == SEQ_START_TOKEN)
efa90a98
HD
1947 type = 0;
1948 else
1949 type = si->type + 1;
881e4aab 1950
efa90a98
HD
1951 for (; type < nr_swapfiles; type++) {
1952 smp_rmb(); /* read nr_swapfiles before swap_info[type] */
1953 si = swap_info[type];
1954 if (!(si->flags & SWP_USED) || !si->swap_map)
1da177e4
LT
1955 continue;
1956 ++*pos;
efa90a98 1957 return si;
1da177e4
LT
1958 }
1959
1960 return NULL;
1961}
1962
1963static void swap_stop(struct seq_file *swap, void *v)
1964{
fc0abb14 1965 mutex_unlock(&swapon_mutex);
1da177e4
LT
1966}
1967
1968static int swap_show(struct seq_file *swap, void *v)
1969{
efa90a98 1970 struct swap_info_struct *si = v;
1da177e4
LT
1971 struct file *file;
1972 int len;
1973
efa90a98 1974 if (si == SEQ_START_TOKEN) {
881e4aab
SS
1975 seq_puts(swap,"Filename\t\t\t\tType\t\tSize\tUsed\tPriority\n");
1976 return 0;
1977 }
1da177e4 1978
efa90a98 1979 file = si->swap_file;
c32c2f63 1980 len = seq_path(swap, &file->f_path, " \t\n\\");
6eb396dc 1981 seq_printf(swap, "%*s%s\t%u\t%u\t%d\n",
886bb7e9 1982 len < 40 ? 40 - len : 1, " ",
496ad9aa 1983 S_ISBLK(file_inode(file)->i_mode) ?
1da177e4 1984 "partition" : "file\t",
efa90a98
HD
1985 si->pages << (PAGE_SHIFT - 10),
1986 si->inuse_pages << (PAGE_SHIFT - 10),
1987 si->prio);
1da177e4
LT
1988 return 0;
1989}
1990
15ad7cdc 1991static const struct seq_operations swaps_op = {
1da177e4
LT
1992 .start = swap_start,
1993 .next = swap_next,
1994 .stop = swap_stop,
1995 .show = swap_show
1996};
1997
1998static int swaps_open(struct inode *inode, struct file *file)
1999{
f1514638 2000 struct seq_file *seq;
66d7dd51
KS
2001 int ret;
2002
66d7dd51 2003 ret = seq_open(file, &swaps_op);
f1514638 2004 if (ret)
66d7dd51 2005 return ret;
66d7dd51 2006
f1514638
KS
2007 seq = file->private_data;
2008 seq->poll_event = atomic_read(&proc_poll_event);
2009 return 0;
1da177e4
LT
2010}
2011
15ad7cdc 2012static const struct file_operations proc_swaps_operations = {
1da177e4
LT
2013 .open = swaps_open,
2014 .read = seq_read,
2015 .llseek = seq_lseek,
2016 .release = seq_release,
66d7dd51 2017 .poll = swaps_poll,
1da177e4
LT
2018};
2019
2020static int __init procswaps_init(void)
2021{
3d71f86f 2022 proc_create("swaps", 0, NULL, &proc_swaps_operations);
1da177e4
LT
2023 return 0;
2024}
2025__initcall(procswaps_init);
2026#endif /* CONFIG_PROC_FS */
2027
1796316a
JB
2028#ifdef MAX_SWAPFILES_CHECK
2029static int __init max_swapfiles_check(void)
2030{
2031 MAX_SWAPFILES_CHECK();
2032 return 0;
2033}
2034late_initcall(max_swapfiles_check);
2035#endif
2036
53cbb243 2037static struct swap_info_struct *alloc_swap_info(void)
1da177e4 2038{
73c34b6a 2039 struct swap_info_struct *p;
1da177e4 2040 unsigned int type;
efa90a98
HD
2041
2042 p = kzalloc(sizeof(*p), GFP_KERNEL);
2043 if (!p)
53cbb243 2044 return ERR_PTR(-ENOMEM);
efa90a98 2045
5d337b91 2046 spin_lock(&swap_lock);
efa90a98
HD
2047 for (type = 0; type < nr_swapfiles; type++) {
2048 if (!(swap_info[type]->flags & SWP_USED))
1da177e4 2049 break;
efa90a98 2050 }
0697212a 2051 if (type >= MAX_SWAPFILES) {
5d337b91 2052 spin_unlock(&swap_lock);
efa90a98 2053 kfree(p);
730c0581 2054 return ERR_PTR(-EPERM);
1da177e4 2055 }
efa90a98
HD
2056 if (type >= nr_swapfiles) {
2057 p->type = type;
2058 swap_info[type] = p;
2059 /*
2060 * Write swap_info[type] before nr_swapfiles, in case a
2061 * racing procfs swap_start() or swap_next() is reading them.
2062 * (We never shrink nr_swapfiles, we never free this entry.)
2063 */
2064 smp_wmb();
2065 nr_swapfiles++;
2066 } else {
2067 kfree(p);
2068 p = swap_info[type];
2069 /*
2070 * Do not memset this entry: a racing procfs swap_next()
2071 * would be relying on p->type to remain valid.
2072 */
2073 }
9625a5f2 2074 INIT_LIST_HEAD(&p->first_swap_extent.list);
1da177e4 2075 p->flags = SWP_USED;
1da177e4 2076 p->next = -1;
5d337b91 2077 spin_unlock(&swap_lock);
ec8acf20 2078 spin_lock_init(&p->lock);
efa90a98 2079
53cbb243 2080 return p;
53cbb243
CEB
2081}
2082
4d0e1e10
CEB
2083static int claim_swapfile(struct swap_info_struct *p, struct inode *inode)
2084{
2085 int error;
2086
2087 if (S_ISBLK(inode->i_mode)) {
2088 p->bdev = bdgrab(I_BDEV(inode));
2089 error = blkdev_get(p->bdev,
2090 FMODE_READ | FMODE_WRITE | FMODE_EXCL,
2091 sys_swapon);
2092 if (error < 0) {
2093 p->bdev = NULL;
87ade72a 2094 return -EINVAL;
4d0e1e10
CEB
2095 }
2096 p->old_block_size = block_size(p->bdev);
2097 error = set_blocksize(p->bdev, PAGE_SIZE);
2098 if (error < 0)
87ade72a 2099 return error;
4d0e1e10
CEB
2100 p->flags |= SWP_BLKDEV;
2101 } else if (S_ISREG(inode->i_mode)) {
2102 p->bdev = inode->i_sb->s_bdev;
2103 mutex_lock(&inode->i_mutex);
87ade72a
CEB
2104 if (IS_SWAPFILE(inode))
2105 return -EBUSY;
2106 } else
2107 return -EINVAL;
4d0e1e10
CEB
2108
2109 return 0;
4d0e1e10
CEB
2110}
2111
ca8bd38b
CEB
2112static unsigned long read_swap_header(struct swap_info_struct *p,
2113 union swap_header *swap_header,
2114 struct inode *inode)
2115{
2116 int i;
2117 unsigned long maxpages;
2118 unsigned long swapfilepages;
d6bbbd29 2119 unsigned long last_page;
ca8bd38b
CEB
2120
2121 if (memcmp("SWAPSPACE2", swap_header->magic.magic, 10)) {
465c47fd 2122 pr_err("Unable to find swap-space signature\n");
38719025 2123 return 0;
ca8bd38b
CEB
2124 }
2125
2126 /* swap partition endianess hack... */
2127 if (swab32(swap_header->info.version) == 1) {
2128 swab32s(&swap_header->info.version);
2129 swab32s(&swap_header->info.last_page);
2130 swab32s(&swap_header->info.nr_badpages);
2131 for (i = 0; i < swap_header->info.nr_badpages; i++)
2132 swab32s(&swap_header->info.badpages[i]);
2133 }
2134 /* Check the swap header's sub-version */
2135 if (swap_header->info.version != 1) {
465c47fd
AM
2136 pr_warn("Unable to handle swap header version %d\n",
2137 swap_header->info.version);
38719025 2138 return 0;
ca8bd38b
CEB
2139 }
2140
2141 p->lowest_bit = 1;
2142 p->cluster_next = 1;
2143 p->cluster_nr = 0;
2144
2145 /*
2146 * Find out how many pages are allowed for a single swap
9b15b817 2147 * device. There are two limiting factors: 1) the number
a2c16d6c
HD
2148 * of bits for the swap offset in the swp_entry_t type, and
2149 * 2) the number of bits in the swap pte as defined by the
9b15b817 2150 * different architectures. In order to find the
a2c16d6c 2151 * largest possible bit mask, a swap entry with swap type 0
ca8bd38b 2152 * and swap offset ~0UL is created, encoded to a swap pte,
a2c16d6c 2153 * decoded to a swp_entry_t again, and finally the swap
ca8bd38b
CEB
2154 * offset is extracted. This will mask all the bits from
2155 * the initial ~0UL mask that can't be encoded in either
2156 * the swp_entry_t or the architecture definition of a
9b15b817 2157 * swap pte.
ca8bd38b
CEB
2158 */
2159 maxpages = swp_offset(pte_to_swp_entry(
9b15b817 2160 swp_entry_to_pte(swp_entry(0, ~0UL)))) + 1;
d6bbbd29
RJ
2161 last_page = swap_header->info.last_page;
2162 if (last_page > maxpages) {
465c47fd 2163 pr_warn("Truncating oversized swap area, only using %luk out of %luk\n",
d6bbbd29
RJ
2164 maxpages << (PAGE_SHIFT - 10),
2165 last_page << (PAGE_SHIFT - 10));
2166 }
2167 if (maxpages > last_page) {
2168 maxpages = last_page + 1;
ca8bd38b
CEB
2169 /* p->max is an unsigned int: don't overflow it */
2170 if ((unsigned int)maxpages == 0)
2171 maxpages = UINT_MAX;
2172 }
2173 p->highest_bit = maxpages - 1;
2174
2175 if (!maxpages)
38719025 2176 return 0;
ca8bd38b
CEB
2177 swapfilepages = i_size_read(inode) >> PAGE_SHIFT;
2178 if (swapfilepages && maxpages > swapfilepages) {
465c47fd 2179 pr_warn("Swap area shorter than signature indicates\n");
38719025 2180 return 0;
ca8bd38b
CEB
2181 }
2182 if (swap_header->info.nr_badpages && S_ISREG(inode->i_mode))
38719025 2183 return 0;
ca8bd38b 2184 if (swap_header->info.nr_badpages > MAX_SWAP_BADPAGES)
38719025 2185 return 0;
ca8bd38b
CEB
2186
2187 return maxpages;
ca8bd38b
CEB
2188}
2189
915d4d7b
CEB
2190static int setup_swap_map_and_extents(struct swap_info_struct *p,
2191 union swap_header *swap_header,
2192 unsigned char *swap_map,
2a8f9449 2193 struct swap_cluster_info *cluster_info,
915d4d7b
CEB
2194 unsigned long maxpages,
2195 sector_t *span)
2196{
2197 int i;
915d4d7b
CEB
2198 unsigned int nr_good_pages;
2199 int nr_extents;
2a8f9449
SL
2200 unsigned long nr_clusters = DIV_ROUND_UP(maxpages, SWAPFILE_CLUSTER);
2201 unsigned long idx = p->cluster_next / SWAPFILE_CLUSTER;
915d4d7b
CEB
2202
2203 nr_good_pages = maxpages - 1; /* omit header page */
2204
2a8f9449
SL
2205 cluster_set_null(&p->free_cluster_head);
2206 cluster_set_null(&p->free_cluster_tail);
815c2c54
SL
2207 cluster_set_null(&p->discard_cluster_head);
2208 cluster_set_null(&p->discard_cluster_tail);
2a8f9449 2209
915d4d7b
CEB
2210 for (i = 0; i < swap_header->info.nr_badpages; i++) {
2211 unsigned int page_nr = swap_header->info.badpages[i];
bdb8e3f6
CEB
2212 if (page_nr == 0 || page_nr > swap_header->info.last_page)
2213 return -EINVAL;
915d4d7b
CEB
2214 if (page_nr < maxpages) {
2215 swap_map[page_nr] = SWAP_MAP_BAD;
2216 nr_good_pages--;
2a8f9449
SL
2217 /*
2218 * Haven't marked the cluster free yet, no list
2219 * operation involved
2220 */
2221 inc_cluster_info_page(p, cluster_info, page_nr);
915d4d7b
CEB
2222 }
2223 }
2224
2a8f9449
SL
2225 /* Haven't marked the cluster free yet, no list operation involved */
2226 for (i = maxpages; i < round_up(maxpages, SWAPFILE_CLUSTER); i++)
2227 inc_cluster_info_page(p, cluster_info, i);
2228
915d4d7b
CEB
2229 if (nr_good_pages) {
2230 swap_map[0] = SWAP_MAP_BAD;
2a8f9449
SL
2231 /*
2232 * Not mark the cluster free yet, no list
2233 * operation involved
2234 */
2235 inc_cluster_info_page(p, cluster_info, 0);
915d4d7b
CEB
2236 p->max = maxpages;
2237 p->pages = nr_good_pages;
2238 nr_extents = setup_swap_extents(p, span);
bdb8e3f6
CEB
2239 if (nr_extents < 0)
2240 return nr_extents;
915d4d7b
CEB
2241 nr_good_pages = p->pages;
2242 }
2243 if (!nr_good_pages) {
465c47fd 2244 pr_warn("Empty swap-file\n");
bdb8e3f6 2245 return -EINVAL;
915d4d7b
CEB
2246 }
2247
2a8f9449
SL
2248 if (!cluster_info)
2249 return nr_extents;
2250
2251 for (i = 0; i < nr_clusters; i++) {
2252 if (!cluster_count(&cluster_info[idx])) {
2253 cluster_set_flag(&cluster_info[idx], CLUSTER_FLAG_FREE);
2254 if (cluster_is_null(&p->free_cluster_head)) {
2255 cluster_set_next_flag(&p->free_cluster_head,
2256 idx, 0);
2257 cluster_set_next_flag(&p->free_cluster_tail,
2258 idx, 0);
2259 } else {
2260 unsigned int tail;
2261
2262 tail = cluster_next(&p->free_cluster_tail);
2263 cluster_set_next(&cluster_info[tail], idx);
2264 cluster_set_next_flag(&p->free_cluster_tail,
2265 idx, 0);
2266 }
2267 }
2268 idx++;
2269 if (idx == nr_clusters)
2270 idx = 0;
2271 }
915d4d7b 2272 return nr_extents;
915d4d7b
CEB
2273}
2274
dcf6b7dd
RA
2275/*
2276 * Helper to sys_swapon determining if a given swap
2277 * backing device queue supports DISCARD operations.
2278 */
2279static bool swap_discardable(struct swap_info_struct *si)
2280{
2281 struct request_queue *q = bdev_get_queue(si->bdev);
2282
2283 if (!q || !blk_queue_discard(q))
2284 return false;
2285
2286 return true;
2287}
2288
53cbb243
CEB
2289SYSCALL_DEFINE2(swapon, const char __user *, specialfile, int, swap_flags)
2290{
2291 struct swap_info_struct *p;
91a27b2a 2292 struct filename *name;
53cbb243
CEB
2293 struct file *swap_file = NULL;
2294 struct address_space *mapping;
40531542
CEB
2295 int i;
2296 int prio;
53cbb243
CEB
2297 int error;
2298 union swap_header *swap_header;
915d4d7b 2299 int nr_extents;
53cbb243
CEB
2300 sector_t span;
2301 unsigned long maxpages;
53cbb243 2302 unsigned char *swap_map = NULL;
2a8f9449 2303 struct swap_cluster_info *cluster_info = NULL;
38b5faf4 2304 unsigned long *frontswap_map = NULL;
53cbb243
CEB
2305 struct page *page = NULL;
2306 struct inode *inode = NULL;
53cbb243 2307
d15cab97
HD
2308 if (swap_flags & ~SWAP_FLAGS_VALID)
2309 return -EINVAL;
2310
53cbb243
CEB
2311 if (!capable(CAP_SYS_ADMIN))
2312 return -EPERM;
2313
2314 p = alloc_swap_info();
2542e513
CEB
2315 if (IS_ERR(p))
2316 return PTR_ERR(p);
53cbb243 2317
815c2c54
SL
2318 INIT_WORK(&p->discard_work, swap_discard_work);
2319
1da177e4 2320 name = getname(specialfile);
1da177e4 2321 if (IS_ERR(name)) {
7de7fb6b 2322 error = PTR_ERR(name);
1da177e4 2323 name = NULL;
bd69010b 2324 goto bad_swap;
1da177e4 2325 }
669abf4e 2326 swap_file = file_open_name(name, O_RDWR|O_LARGEFILE, 0);
1da177e4 2327 if (IS_ERR(swap_file)) {
7de7fb6b 2328 error = PTR_ERR(swap_file);
1da177e4 2329 swap_file = NULL;
bd69010b 2330 goto bad_swap;
1da177e4
LT
2331 }
2332
2333 p->swap_file = swap_file;
2334 mapping = swap_file->f_mapping;
1da177e4 2335
1da177e4 2336 for (i = 0; i < nr_swapfiles; i++) {
efa90a98 2337 struct swap_info_struct *q = swap_info[i];
1da177e4 2338
e8e6c2ec 2339 if (q == p || !q->swap_file)
1da177e4 2340 continue;
7de7fb6b
CEB
2341 if (mapping == q->swap_file->f_mapping) {
2342 error = -EBUSY;
1da177e4 2343 goto bad_swap;
7de7fb6b 2344 }
1da177e4
LT
2345 }
2346
2130781e
CEB
2347 inode = mapping->host;
2348 /* If S_ISREG(inode->i_mode) will do mutex_lock(&inode->i_mutex); */
4d0e1e10
CEB
2349 error = claim_swapfile(p, inode);
2350 if (unlikely(error))
1da177e4 2351 goto bad_swap;
1da177e4 2352
1da177e4
LT
2353 /*
2354 * Read the swap header.
2355 */
2356 if (!mapping->a_ops->readpage) {
2357 error = -EINVAL;
2358 goto bad_swap;
2359 }
090d2b18 2360 page = read_mapping_page(mapping, 0, swap_file);
1da177e4
LT
2361 if (IS_ERR(page)) {
2362 error = PTR_ERR(page);
2363 goto bad_swap;
2364 }
81e33971 2365 swap_header = kmap(page);
1da177e4 2366
ca8bd38b
CEB
2367 maxpages = read_swap_header(p, swap_header, inode);
2368 if (unlikely(!maxpages)) {
1da177e4
LT
2369 error = -EINVAL;
2370 goto bad_swap;
2371 }
886bb7e9 2372
81e33971 2373 /* OK, set up the swap map and apply the bad block list */
803d0c83 2374 swap_map = vzalloc(maxpages);
81e33971
HD
2375 if (!swap_map) {
2376 error = -ENOMEM;
2377 goto bad_swap;
2378 }
2a8f9449
SL
2379 if (p->bdev && blk_queue_nonrot(bdev_get_queue(p->bdev))) {
2380 p->flags |= SWP_SOLIDSTATE;
2381 /*
2382 * select a random position to start with to help wear leveling
2383 * SSD
2384 */
2385 p->cluster_next = 1 + (prandom_u32() % p->highest_bit);
2386
2387 cluster_info = vzalloc(DIV_ROUND_UP(maxpages,
2388 SWAPFILE_CLUSTER) * sizeof(*cluster_info));
2389 if (!cluster_info) {
2390 error = -ENOMEM;
2391 goto bad_swap;
2392 }
2393 }
1da177e4 2394
1421ef3c
CEB
2395 error = swap_cgroup_swapon(p->type, maxpages);
2396 if (error)
2397 goto bad_swap;
2398
915d4d7b 2399 nr_extents = setup_swap_map_and_extents(p, swap_header, swap_map,
2a8f9449 2400 cluster_info, maxpages, &span);
915d4d7b
CEB
2401 if (unlikely(nr_extents < 0)) {
2402 error = nr_extents;
1da177e4
LT
2403 goto bad_swap;
2404 }
38b5faf4
DM
2405 /* frontswap enabled? set up bit-per-page map for frontswap */
2406 if (frontswap_enabled)
7b57976d 2407 frontswap_map = vzalloc(BITS_TO_LONGS(maxpages) * sizeof(long));
1da177e4 2408
2a8f9449
SL
2409 if (p->bdev &&(swap_flags & SWAP_FLAG_DISCARD) && swap_discardable(p)) {
2410 /*
2411 * When discard is enabled for swap with no particular
2412 * policy flagged, we set all swap discard flags here in
2413 * order to sustain backward compatibility with older
2414 * swapon(8) releases.
2415 */
2416 p->flags |= (SWP_DISCARDABLE | SWP_AREA_DISCARD |
2417 SWP_PAGE_DISCARD);
dcf6b7dd 2418
2a8f9449
SL
2419 /*
2420 * By flagging sys_swapon, a sysadmin can tell us to
2421 * either do single-time area discards only, or to just
2422 * perform discards for released swap page-clusters.
2423 * Now it's time to adjust the p->flags accordingly.
2424 */
2425 if (swap_flags & SWAP_FLAG_DISCARD_ONCE)
2426 p->flags &= ~SWP_PAGE_DISCARD;
2427 else if (swap_flags & SWAP_FLAG_DISCARD_PAGES)
2428 p->flags &= ~SWP_AREA_DISCARD;
2429
2430 /* issue a swapon-time discard if it's still required */
2431 if (p->flags & SWP_AREA_DISCARD) {
2432 int err = discard_swap(p);
2433 if (unlikely(err))
2434 pr_err("swapon: discard_swap(%p): %d\n",
2435 p, err);
dcf6b7dd 2436 }
20137a49 2437 }
6a6ba831 2438
fc0abb14 2439 mutex_lock(&swapon_mutex);
40531542 2440 prio = -1;
78ecba08 2441 if (swap_flags & SWAP_FLAG_PREFER)
40531542 2442 prio =
78ecba08 2443 (swap_flags & SWAP_FLAG_PRIO_MASK) >> SWAP_FLAG_PRIO_SHIFT;
2a8f9449 2444 enable_swap_info(p, prio, swap_map, cluster_info, frontswap_map);
c69dbfb8 2445
465c47fd 2446 pr_info("Adding %uk swap on %s. "
dcf6b7dd 2447 "Priority:%d extents:%d across:%lluk %s%s%s%s%s\n",
91a27b2a 2448 p->pages<<(PAGE_SHIFT-10), name->name, p->prio,
c69dbfb8
CEB
2449 nr_extents, (unsigned long long)span<<(PAGE_SHIFT-10),
2450 (p->flags & SWP_SOLIDSTATE) ? "SS" : "",
38b5faf4 2451 (p->flags & SWP_DISCARDABLE) ? "D" : "",
dcf6b7dd
RA
2452 (p->flags & SWP_AREA_DISCARD) ? "s" : "",
2453 (p->flags & SWP_PAGE_DISCARD) ? "c" : "",
38b5faf4 2454 (frontswap_map) ? "FS" : "");
c69dbfb8 2455
fc0abb14 2456 mutex_unlock(&swapon_mutex);
66d7dd51
KS
2457 atomic_inc(&proc_poll_event);
2458 wake_up_interruptible(&proc_poll_wait);
2459
9b01c350
CEB
2460 if (S_ISREG(inode->i_mode))
2461 inode->i_flags |= S_SWAPFILE;
1da177e4
LT
2462 error = 0;
2463 goto out;
2464bad_swap:
bd69010b 2465 if (inode && S_ISBLK(inode->i_mode) && p->bdev) {
f2090d2d
CEB
2466 set_blocksize(p->bdev, p->old_block_size);
2467 blkdev_put(p->bdev, FMODE_READ | FMODE_WRITE | FMODE_EXCL);
1da177e4 2468 }
4cd3bb10 2469 destroy_swap_extents(p);
e8e6c2ec 2470 swap_cgroup_swapoff(p->type);
5d337b91 2471 spin_lock(&swap_lock);
1da177e4 2472 p->swap_file = NULL;
1da177e4 2473 p->flags = 0;
5d337b91 2474 spin_unlock(&swap_lock);
1da177e4 2475 vfree(swap_map);
2a8f9449 2476 vfree(cluster_info);
52c50567 2477 if (swap_file) {
2130781e 2478 if (inode && S_ISREG(inode->i_mode)) {
52c50567 2479 mutex_unlock(&inode->i_mutex);
2130781e
CEB
2480 inode = NULL;
2481 }
1da177e4 2482 filp_close(swap_file, NULL);
52c50567 2483 }
1da177e4
LT
2484out:
2485 if (page && !IS_ERR(page)) {
2486 kunmap(page);
2487 page_cache_release(page);
2488 }
2489 if (name)
2490 putname(name);
9b01c350 2491 if (inode && S_ISREG(inode->i_mode))
1b1dcc1b 2492 mutex_unlock(&inode->i_mutex);
1da177e4
LT
2493 return error;
2494}
2495
2496void si_swapinfo(struct sysinfo *val)
2497{
efa90a98 2498 unsigned int type;
1da177e4
LT
2499 unsigned long nr_to_be_unused = 0;
2500
5d337b91 2501 spin_lock(&swap_lock);
efa90a98
HD
2502 for (type = 0; type < nr_swapfiles; type++) {
2503 struct swap_info_struct *si = swap_info[type];
2504
2505 if ((si->flags & SWP_USED) && !(si->flags & SWP_WRITEOK))
2506 nr_to_be_unused += si->inuse_pages;
1da177e4 2507 }
ec8acf20 2508 val->freeswap = atomic_long_read(&nr_swap_pages) + nr_to_be_unused;
1da177e4 2509 val->totalswap = total_swap_pages + nr_to_be_unused;
5d337b91 2510 spin_unlock(&swap_lock);
1da177e4
LT
2511}
2512
2513/*
2514 * Verify that a swap entry is valid and increment its swap map count.
2515 *
355cfa73
KH
2516 * Returns error code in following case.
2517 * - success -> 0
2518 * - swp_entry is invalid -> EINVAL
2519 * - swp_entry is migration entry -> EINVAL
2520 * - swap-cache reference is requested but there is already one. -> EEXIST
2521 * - swap-cache reference is requested but the entry is not used. -> ENOENT
570a335b 2522 * - swap-mapped reference requested but needs continued swap count. -> ENOMEM
1da177e4 2523 */
8d69aaee 2524static int __swap_duplicate(swp_entry_t entry, unsigned char usage)
1da177e4 2525{
73c34b6a 2526 struct swap_info_struct *p;
1da177e4 2527 unsigned long offset, type;
8d69aaee
HD
2528 unsigned char count;
2529 unsigned char has_cache;
253d553b 2530 int err = -EINVAL;
1da177e4 2531
a7420aa5 2532 if (non_swap_entry(entry))
253d553b 2533 goto out;
0697212a 2534
1da177e4
LT
2535 type = swp_type(entry);
2536 if (type >= nr_swapfiles)
2537 goto bad_file;
efa90a98 2538 p = swap_info[type];
1da177e4
LT
2539 offset = swp_offset(entry);
2540
ec8acf20 2541 spin_lock(&p->lock);
355cfa73
KH
2542 if (unlikely(offset >= p->max))
2543 goto unlock_out;
2544
253d553b
HD
2545 count = p->swap_map[offset];
2546 has_cache = count & SWAP_HAS_CACHE;
2547 count &= ~SWAP_HAS_CACHE;
2548 err = 0;
355cfa73 2549
253d553b 2550 if (usage == SWAP_HAS_CACHE) {
355cfa73
KH
2551
2552 /* set SWAP_HAS_CACHE if there is no cache and entry is used */
253d553b
HD
2553 if (!has_cache && count)
2554 has_cache = SWAP_HAS_CACHE;
2555 else if (has_cache) /* someone else added cache */
2556 err = -EEXIST;
2557 else /* no users remaining */
2558 err = -ENOENT;
355cfa73
KH
2559
2560 } else if (count || has_cache) {
253d553b 2561
570a335b
HD
2562 if ((count & ~COUNT_CONTINUED) < SWAP_MAP_MAX)
2563 count += usage;
2564 else if ((count & ~COUNT_CONTINUED) > SWAP_MAP_MAX)
253d553b 2565 err = -EINVAL;
570a335b
HD
2566 else if (swap_count_continued(p, offset, count))
2567 count = COUNT_CONTINUED;
2568 else
2569 err = -ENOMEM;
355cfa73 2570 } else
253d553b
HD
2571 err = -ENOENT; /* unused swap entry */
2572
2573 p->swap_map[offset] = count | has_cache;
2574
355cfa73 2575unlock_out:
ec8acf20 2576 spin_unlock(&p->lock);
1da177e4 2577out:
253d553b 2578 return err;
1da177e4
LT
2579
2580bad_file:
465c47fd 2581 pr_err("swap_dup: %s%08lx\n", Bad_file, entry.val);
1da177e4
LT
2582 goto out;
2583}
253d553b 2584
aaa46865
HD
2585/*
2586 * Help swapoff by noting that swap entry belongs to shmem/tmpfs
2587 * (in which case its reference count is never incremented).
2588 */
2589void swap_shmem_alloc(swp_entry_t entry)
2590{
2591 __swap_duplicate(entry, SWAP_MAP_SHMEM);
2592}
2593
355cfa73 2594/*
08259d58
HD
2595 * Increase reference count of swap entry by 1.
2596 * Returns 0 for success, or -ENOMEM if a swap_count_continuation is required
2597 * but could not be atomically allocated. Returns 0, just as if it succeeded,
2598 * if __swap_duplicate() fails for another reason (-EINVAL or -ENOENT), which
2599 * might occur if a page table entry has got corrupted.
355cfa73 2600 */
570a335b 2601int swap_duplicate(swp_entry_t entry)
355cfa73 2602{
570a335b
HD
2603 int err = 0;
2604
2605 while (!err && __swap_duplicate(entry, 1) == -ENOMEM)
2606 err = add_swap_count_continuation(entry, GFP_ATOMIC);
2607 return err;
355cfa73 2608}
1da177e4 2609
cb4b86ba 2610/*
355cfa73
KH
2611 * @entry: swap entry for which we allocate swap cache.
2612 *
73c34b6a 2613 * Called when allocating swap cache for existing swap entry,
355cfa73
KH
2614 * This can return error codes. Returns 0 at success.
2615 * -EBUSY means there is a swap cache.
2616 * Note: return code is different from swap_duplicate().
cb4b86ba
KH
2617 */
2618int swapcache_prepare(swp_entry_t entry)
2619{
253d553b 2620 return __swap_duplicate(entry, SWAP_HAS_CACHE);
cb4b86ba
KH
2621}
2622
f981c595
MG
2623struct swap_info_struct *page_swap_info(struct page *page)
2624{
2625 swp_entry_t swap = { .val = page_private(page) };
2626 BUG_ON(!PageSwapCache(page));
2627 return swap_info[swp_type(swap)];
2628}
2629
2630/*
2631 * out-of-line __page_file_ methods to avoid include hell.
2632 */
2633struct address_space *__page_file_mapping(struct page *page)
2634{
2635 VM_BUG_ON(!PageSwapCache(page));
2636 return page_swap_info(page)->swap_file->f_mapping;
2637}
2638EXPORT_SYMBOL_GPL(__page_file_mapping);
2639
2640pgoff_t __page_file_index(struct page *page)
2641{
2642 swp_entry_t swap = { .val = page_private(page) };
2643 VM_BUG_ON(!PageSwapCache(page));
2644 return swp_offset(swap);
2645}
2646EXPORT_SYMBOL_GPL(__page_file_index);
2647
570a335b
HD
2648/*
2649 * add_swap_count_continuation - called when a swap count is duplicated
2650 * beyond SWAP_MAP_MAX, it allocates a new page and links that to the entry's
2651 * page of the original vmalloc'ed swap_map, to hold the continuation count
2652 * (for that entry and for its neighbouring PAGE_SIZE swap entries). Called
2653 * again when count is duplicated beyond SWAP_MAP_MAX * SWAP_CONT_MAX, etc.
2654 *
2655 * These continuation pages are seldom referenced: the common paths all work
2656 * on the original swap_map, only referring to a continuation page when the
2657 * low "digit" of a count is incremented or decremented through SWAP_MAP_MAX.
2658 *
2659 * add_swap_count_continuation(, GFP_ATOMIC) can be called while holding
2660 * page table locks; if it fails, add_swap_count_continuation(, GFP_KERNEL)
2661 * can be called after dropping locks.
2662 */
2663int add_swap_count_continuation(swp_entry_t entry, gfp_t gfp_mask)
2664{
2665 struct swap_info_struct *si;
2666 struct page *head;
2667 struct page *page;
2668 struct page *list_page;
2669 pgoff_t offset;
2670 unsigned char count;
2671
2672 /*
2673 * When debugging, it's easier to use __GFP_ZERO here; but it's better
2674 * for latency not to zero a page while GFP_ATOMIC and holding locks.
2675 */
2676 page = alloc_page(gfp_mask | __GFP_HIGHMEM);
2677
2678 si = swap_info_get(entry);
2679 if (!si) {
2680 /*
2681 * An acceptable race has occurred since the failing
2682 * __swap_duplicate(): the swap entry has been freed,
2683 * perhaps even the whole swap_map cleared for swapoff.
2684 */
2685 goto outer;
2686 }
2687
2688 offset = swp_offset(entry);
2689 count = si->swap_map[offset] & ~SWAP_HAS_CACHE;
2690
2691 if ((count & ~COUNT_CONTINUED) != SWAP_MAP_MAX) {
2692 /*
2693 * The higher the swap count, the more likely it is that tasks
2694 * will race to add swap count continuation: we need to avoid
2695 * over-provisioning.
2696 */
2697 goto out;
2698 }
2699
2700 if (!page) {
ec8acf20 2701 spin_unlock(&si->lock);
570a335b
HD
2702 return -ENOMEM;
2703 }
2704
2705 /*
2706 * We are fortunate that although vmalloc_to_page uses pte_offset_map,
2707 * no architecture is using highmem pages for kernel pagetables: so it
2708 * will not corrupt the GFP_ATOMIC caller's atomic pagetable kmaps.
2709 */
2710 head = vmalloc_to_page(si->swap_map + offset);
2711 offset &= ~PAGE_MASK;
2712
2713 /*
2714 * Page allocation does not initialize the page's lru field,
2715 * but it does always reset its private field.
2716 */
2717 if (!page_private(head)) {
2718 BUG_ON(count & COUNT_CONTINUED);
2719 INIT_LIST_HEAD(&head->lru);
2720 set_page_private(head, SWP_CONTINUED);
2721 si->flags |= SWP_CONTINUED;
2722 }
2723
2724 list_for_each_entry(list_page, &head->lru, lru) {
2725 unsigned char *map;
2726
2727 /*
2728 * If the previous map said no continuation, but we've found
2729 * a continuation page, free our allocation and use this one.
2730 */
2731 if (!(count & COUNT_CONTINUED))
2732 goto out;
2733
9b04c5fe 2734 map = kmap_atomic(list_page) + offset;
570a335b 2735 count = *map;
9b04c5fe 2736 kunmap_atomic(map);
570a335b
HD
2737
2738 /*
2739 * If this continuation count now has some space in it,
2740 * free our allocation and use this one.
2741 */
2742 if ((count & ~COUNT_CONTINUED) != SWAP_CONT_MAX)
2743 goto out;
2744 }
2745
2746 list_add_tail(&page->lru, &head->lru);
2747 page = NULL; /* now it's attached, don't free it */
2748out:
ec8acf20 2749 spin_unlock(&si->lock);
570a335b
HD
2750outer:
2751 if (page)
2752 __free_page(page);
2753 return 0;
2754}
2755
2756/*
2757 * swap_count_continued - when the original swap_map count is incremented
2758 * from SWAP_MAP_MAX, check if there is already a continuation page to carry
2759 * into, carry if so, or else fail until a new continuation page is allocated;
2760 * when the original swap_map count is decremented from 0 with continuation,
2761 * borrow from the continuation and report whether it still holds more.
2762 * Called while __swap_duplicate() or swap_entry_free() holds swap_lock.
2763 */
2764static bool swap_count_continued(struct swap_info_struct *si,
2765 pgoff_t offset, unsigned char count)
2766{
2767 struct page *head;
2768 struct page *page;
2769 unsigned char *map;
2770
2771 head = vmalloc_to_page(si->swap_map + offset);
2772 if (page_private(head) != SWP_CONTINUED) {
2773 BUG_ON(count & COUNT_CONTINUED);
2774 return false; /* need to add count continuation */
2775 }
2776
2777 offset &= ~PAGE_MASK;
2778 page = list_entry(head->lru.next, struct page, lru);
9b04c5fe 2779 map = kmap_atomic(page) + offset;
570a335b
HD
2780
2781 if (count == SWAP_MAP_MAX) /* initial increment from swap_map */
2782 goto init_map; /* jump over SWAP_CONT_MAX checks */
2783
2784 if (count == (SWAP_MAP_MAX | COUNT_CONTINUED)) { /* incrementing */
2785 /*
2786 * Think of how you add 1 to 999
2787 */
2788 while (*map == (SWAP_CONT_MAX | COUNT_CONTINUED)) {
9b04c5fe 2789 kunmap_atomic(map);
570a335b
HD
2790 page = list_entry(page->lru.next, struct page, lru);
2791 BUG_ON(page == head);
9b04c5fe 2792 map = kmap_atomic(page) + offset;
570a335b
HD
2793 }
2794 if (*map == SWAP_CONT_MAX) {
9b04c5fe 2795 kunmap_atomic(map);
570a335b
HD
2796 page = list_entry(page->lru.next, struct page, lru);
2797 if (page == head)
2798 return false; /* add count continuation */
9b04c5fe 2799 map = kmap_atomic(page) + offset;
570a335b
HD
2800init_map: *map = 0; /* we didn't zero the page */
2801 }
2802 *map += 1;
9b04c5fe 2803 kunmap_atomic(map);
570a335b
HD
2804 page = list_entry(page->lru.prev, struct page, lru);
2805 while (page != head) {
9b04c5fe 2806 map = kmap_atomic(page) + offset;
570a335b 2807 *map = COUNT_CONTINUED;
9b04c5fe 2808 kunmap_atomic(map);
570a335b
HD
2809 page = list_entry(page->lru.prev, struct page, lru);
2810 }
2811 return true; /* incremented */
2812
2813 } else { /* decrementing */
2814 /*
2815 * Think of how you subtract 1 from 1000
2816 */
2817 BUG_ON(count != COUNT_CONTINUED);
2818 while (*map == COUNT_CONTINUED) {
9b04c5fe 2819 kunmap_atomic(map);
570a335b
HD
2820 page = list_entry(page->lru.next, struct page, lru);
2821 BUG_ON(page == head);
9b04c5fe 2822 map = kmap_atomic(page) + offset;
570a335b
HD
2823 }
2824 BUG_ON(*map == 0);
2825 *map -= 1;
2826 if (*map == 0)
2827 count = 0;
9b04c5fe 2828 kunmap_atomic(map);
570a335b
HD
2829 page = list_entry(page->lru.prev, struct page, lru);
2830 while (page != head) {
9b04c5fe 2831 map = kmap_atomic(page) + offset;
570a335b
HD
2832 *map = SWAP_CONT_MAX | count;
2833 count = COUNT_CONTINUED;
9b04c5fe 2834 kunmap_atomic(map);
570a335b
HD
2835 page = list_entry(page->lru.prev, struct page, lru);
2836 }
2837 return count == COUNT_CONTINUED;
2838 }
2839}
2840
2841/*
2842 * free_swap_count_continuations - swapoff free all the continuation pages
2843 * appended to the swap_map, after swap_map is quiesced, before vfree'ing it.
2844 */
2845static void free_swap_count_continuations(struct swap_info_struct *si)
2846{
2847 pgoff_t offset;
2848
2849 for (offset = 0; offset < si->max; offset += PAGE_SIZE) {
2850 struct page *head;
2851 head = vmalloc_to_page(si->swap_map + offset);
2852 if (page_private(head)) {
2853 struct list_head *this, *next;
2854 list_for_each_safe(this, next, &head->lru) {
2855 struct page *page;
2856 page = list_entry(this, struct page, lru);
2857 list_del(this);
2858 __free_page(page);
2859 }
2860 }
2861 }
2862}