]> git.proxmox.com Git - mirror_ubuntu-bionic-kernel.git/blame - mm/swapfile.c
memcg: killed threads should not invoke memcg OOM killer
[mirror_ubuntu-bionic-kernel.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 8#include <linux/mm.h>
6e84f315 9#include <linux/sched/mm.h>
29930025 10#include <linux/sched/task.h>
1da177e4
LT
11#include <linux/hugetlb.h>
12#include <linux/mman.h>
13#include <linux/slab.h>
14#include <linux/kernel_stat.h>
15#include <linux/swap.h>
16#include <linux/vmalloc.h>
17#include <linux/pagemap.h>
18#include <linux/namei.h>
072441e2 19#include <linux/shmem_fs.h>
1da177e4 20#include <linux/blkdev.h>
20137a49 21#include <linux/random.h>
1da177e4
LT
22#include <linux/writeback.h>
23#include <linux/proc_fs.h>
24#include <linux/seq_file.h>
25#include <linux/init.h>
5ad64688 26#include <linux/ksm.h>
1da177e4
LT
27#include <linux/rmap.h>
28#include <linux/security.h>
29#include <linux/backing-dev.h>
fc0abb14 30#include <linux/mutex.h>
c59ede7b 31#include <linux/capability.h>
1da177e4 32#include <linux/syscalls.h>
8a9f3ccd 33#include <linux/memcontrol.h>
66d7dd51 34#include <linux/poll.h>
72788c38 35#include <linux/oom.h>
38b5faf4
DM
36#include <linux/frontswap.h>
37#include <linux/swapfile.h>
f981c595 38#include <linux/export.h>
67afa38e 39#include <linux/swap_slots.h>
155b5f88 40#include <linux/sort.h>
1da177e4
LT
41
42#include <asm/pgtable.h>
43#include <asm/tlbflush.h>
44#include <linux/swapops.h>
5d1ea48b 45#include <linux/swap_cgroup.h>
1da177e4 46
570a335b
HD
47static bool swap_count_continued(struct swap_info_struct *, pgoff_t,
48 unsigned char);
49static void free_swap_count_continuations(struct swap_info_struct *);
d4906e1a 50static sector_t map_swap_entry(swp_entry_t, struct block_device**);
570a335b 51
38b5faf4 52DEFINE_SPINLOCK(swap_lock);
7c363b8c 53static unsigned int nr_swapfiles;
ec8acf20 54atomic_long_t nr_swap_pages;
fb0fec50
CW
55/*
56 * Some modules use swappable objects and may try to swap them out under
57 * memory pressure (via the shrinker). Before doing so, they may wish to
58 * check to see if any swap space is available.
59 */
60EXPORT_SYMBOL_GPL(nr_swap_pages);
ec8acf20 61/* protected with swap_lock. reading in vm_swap_full() doesn't need lock */
1da177e4 62long total_swap_pages;
a2468cc9 63static int least_priority = -1;
1da177e4 64
1da177e4
LT
65static const char Bad_file[] = "Bad swap file entry ";
66static const char Unused_file[] = "Unused swap file entry ";
67static const char Bad_offset[] = "Bad swap offset entry ";
68static const char Unused_offset[] = "Unused swap offset entry ";
69
adfab836
DS
70/*
71 * all active swap_info_structs
72 * protected with swap_lock, and ordered by priority.
73 */
18ab4d4c
DS
74PLIST_HEAD(swap_active_head);
75
76/*
77 * all available (active, not full) swap_info_structs
78 * protected with swap_avail_lock, ordered by priority.
79 * This is used by get_swap_page() instead of swap_active_head
80 * because swap_active_head includes all swap_info_structs,
81 * but get_swap_page() doesn't need to look at full ones.
82 * This uses its own lock instead of swap_lock because when a
83 * swap_info_struct changes between not-full/full, it needs to
84 * add/remove itself to/from this list, but the swap_info_struct->lock
85 * is held and the locking order requires swap_lock to be taken
86 * before any swap_info_struct->lock.
87 */
a2468cc9 88struct plist_head *swap_avail_heads;
18ab4d4c 89static DEFINE_SPINLOCK(swap_avail_lock);
1da177e4 90
38b5faf4 91struct swap_info_struct *swap_info[MAX_SWAPFILES];
1da177e4 92
fc0abb14 93static DEFINE_MUTEX(swapon_mutex);
1da177e4 94
66d7dd51
KS
95static DECLARE_WAIT_QUEUE_HEAD(proc_poll_wait);
96/* Activity counter to indicate that a swapon or swapoff has occurred */
97static atomic_t proc_poll_event = ATOMIC_INIT(0);
98
81a0298b
HY
99atomic_t nr_rotate_swap = ATOMIC_INIT(0);
100
27a34b2d
DJ
101static struct swap_info_struct *swap_type_to_swap_info(int type)
102{
103 if (type >= READ_ONCE(nr_swapfiles))
104 return NULL;
105
106 smp_rmb(); /* Pairs with smp_wmb in alloc_swap_info. */
107 return READ_ONCE(swap_info[type]);
108}
109
8d69aaee 110static inline unsigned char swap_count(unsigned char ent)
355cfa73 111{
570a335b 112 return ent & ~SWAP_HAS_CACHE; /* may include SWAP_HAS_CONT flag */
355cfa73
KH
113}
114
efa90a98 115/* returns 1 if swap entry is freed */
c9e44410
KH
116static int
117__try_to_reclaim_swap(struct swap_info_struct *si, unsigned long offset)
118{
efa90a98 119 swp_entry_t entry = swp_entry(si->type, offset);
c9e44410
KH
120 struct page *page;
121 int ret = 0;
122
f6ab1f7f 123 page = find_get_page(swap_address_space(entry), swp_offset(entry));
c9e44410
KH
124 if (!page)
125 return 0;
126 /*
127 * This function is called from scan_swap_map() and it's called
128 * by vmscan.c at reclaiming pages. So, we hold a lock on a page, here.
129 * We have to use trylock for avoiding deadlock. This is a special
130 * case and you should use try_to_free_swap() with explicit lock_page()
131 * in usual operations.
132 */
133 if (trylock_page(page)) {
134 ret = try_to_free_swap(page);
135 unlock_page(page);
136 }
09cbfeaf 137 put_page(page);
c9e44410
KH
138 return ret;
139}
355cfa73 140
6a6ba831
HD
141/*
142 * swapon tell device that all the old swap contents can be discarded,
143 * to allow the swap device to optimize its wear-levelling.
144 */
145static int discard_swap(struct swap_info_struct *si)
146{
147 struct swap_extent *se;
9625a5f2
HD
148 sector_t start_block;
149 sector_t nr_blocks;
6a6ba831
HD
150 int err = 0;
151
9625a5f2
HD
152 /* Do not discard the swap header page! */
153 se = &si->first_swap_extent;
154 start_block = (se->start_block + 1) << (PAGE_SHIFT - 9);
155 nr_blocks = ((sector_t)se->nr_pages - 1) << (PAGE_SHIFT - 9);
156 if (nr_blocks) {
157 err = blkdev_issue_discard(si->bdev, start_block,
dd3932ed 158 nr_blocks, GFP_KERNEL, 0);
9625a5f2
HD
159 if (err)
160 return err;
161 cond_resched();
162 }
6a6ba831 163
9625a5f2
HD
164 list_for_each_entry(se, &si->first_swap_extent.list, list) {
165 start_block = se->start_block << (PAGE_SHIFT - 9);
166 nr_blocks = (sector_t)se->nr_pages << (PAGE_SHIFT - 9);
6a6ba831
HD
167
168 err = blkdev_issue_discard(si->bdev, start_block,
dd3932ed 169 nr_blocks, GFP_KERNEL, 0);
6a6ba831
HD
170 if (err)
171 break;
172
173 cond_resched();
174 }
175 return err; /* That will often be -EOPNOTSUPP */
176}
177
7992fde7
HD
178/*
179 * swap allocation tell device that a cluster of swap can now be discarded,
180 * to allow the swap device to optimize its wear-levelling.
181 */
182static void discard_swap_cluster(struct swap_info_struct *si,
183 pgoff_t start_page, pgoff_t nr_pages)
184{
185 struct swap_extent *se = si->curr_swap_extent;
186 int found_extent = 0;
187
188 while (nr_pages) {
7992fde7
HD
189 if (se->start_page <= start_page &&
190 start_page < se->start_page + se->nr_pages) {
191 pgoff_t offset = start_page - se->start_page;
192 sector_t start_block = se->start_block + offset;
858a2990 193 sector_t nr_blocks = se->nr_pages - offset;
7992fde7
HD
194
195 if (nr_blocks > nr_pages)
196 nr_blocks = nr_pages;
197 start_page += nr_blocks;
198 nr_pages -= nr_blocks;
199
200 if (!found_extent++)
201 si->curr_swap_extent = se;
202
203 start_block <<= PAGE_SHIFT - 9;
204 nr_blocks <<= PAGE_SHIFT - 9;
205 if (blkdev_issue_discard(si->bdev, start_block,
dd3932ed 206 nr_blocks, GFP_NOIO, 0))
7992fde7
HD
207 break;
208 }
209
a8ae4991 210 se = list_next_entry(se, list);
7992fde7
HD
211 }
212}
213
38d8b4e6
HY
214#ifdef CONFIG_THP_SWAP
215#define SWAPFILE_CLUSTER HPAGE_PMD_NR
216#else
048c27fd 217#define SWAPFILE_CLUSTER 256
38d8b4e6 218#endif
048c27fd
HD
219#define LATENCY_LIMIT 256
220
2a8f9449
SL
221static inline void cluster_set_flag(struct swap_cluster_info *info,
222 unsigned int flag)
223{
224 info->flags = flag;
225}
226
227static inline unsigned int cluster_count(struct swap_cluster_info *info)
228{
229 return info->data;
230}
231
232static inline void cluster_set_count(struct swap_cluster_info *info,
233 unsigned int c)
234{
235 info->data = c;
236}
237
238static inline void cluster_set_count_flag(struct swap_cluster_info *info,
239 unsigned int c, unsigned int f)
240{
241 info->flags = f;
242 info->data = c;
243}
244
245static inline unsigned int cluster_next(struct swap_cluster_info *info)
246{
247 return info->data;
248}
249
250static inline void cluster_set_next(struct swap_cluster_info *info,
251 unsigned int n)
252{
253 info->data = n;
254}
255
256static inline void cluster_set_next_flag(struct swap_cluster_info *info,
257 unsigned int n, unsigned int f)
258{
259 info->flags = f;
260 info->data = n;
261}
262
263static inline bool cluster_is_free(struct swap_cluster_info *info)
264{
265 return info->flags & CLUSTER_FLAG_FREE;
266}
267
268static inline bool cluster_is_null(struct swap_cluster_info *info)
269{
270 return info->flags & CLUSTER_FLAG_NEXT_NULL;
271}
272
273static inline void cluster_set_null(struct swap_cluster_info *info)
274{
275 info->flags = CLUSTER_FLAG_NEXT_NULL;
276 info->data = 0;
277}
278
e0709829
HY
279static inline bool cluster_is_huge(struct swap_cluster_info *info)
280{
281 return info->flags & CLUSTER_FLAG_HUGE;
282}
283
284static inline void cluster_clear_huge(struct swap_cluster_info *info)
285{
286 info->flags &= ~CLUSTER_FLAG_HUGE;
287}
288
235b6217
HY
289static inline struct swap_cluster_info *lock_cluster(struct swap_info_struct *si,
290 unsigned long offset)
291{
292 struct swap_cluster_info *ci;
293
294 ci = si->cluster_info;
295 if (ci) {
296 ci += offset / SWAPFILE_CLUSTER;
297 spin_lock(&ci->lock);
298 }
299 return ci;
300}
301
302static inline void unlock_cluster(struct swap_cluster_info *ci)
303{
304 if (ci)
305 spin_unlock(&ci->lock);
306}
307
308static inline struct swap_cluster_info *lock_cluster_or_swap_info(
309 struct swap_info_struct *si,
310 unsigned long offset)
311{
312 struct swap_cluster_info *ci;
313
314 ci = lock_cluster(si, offset);
315 if (!ci)
316 spin_lock(&si->lock);
317
318 return ci;
319}
320
321static inline void unlock_cluster_or_swap_info(struct swap_info_struct *si,
322 struct swap_cluster_info *ci)
323{
324 if (ci)
325 unlock_cluster(ci);
326 else
327 spin_unlock(&si->lock);
328}
329
6b534915
HY
330static inline bool cluster_list_empty(struct swap_cluster_list *list)
331{
332 return cluster_is_null(&list->head);
333}
334
335static inline unsigned int cluster_list_first(struct swap_cluster_list *list)
336{
337 return cluster_next(&list->head);
338}
339
340static void cluster_list_init(struct swap_cluster_list *list)
341{
342 cluster_set_null(&list->head);
343 cluster_set_null(&list->tail);
344}
345
346static void cluster_list_add_tail(struct swap_cluster_list *list,
347 struct swap_cluster_info *ci,
348 unsigned int idx)
349{
350 if (cluster_list_empty(list)) {
351 cluster_set_next_flag(&list->head, idx, 0);
352 cluster_set_next_flag(&list->tail, idx, 0);
353 } else {
235b6217 354 struct swap_cluster_info *ci_tail;
6b534915
HY
355 unsigned int tail = cluster_next(&list->tail);
356
235b6217
HY
357 /*
358 * Nested cluster lock, but both cluster locks are
359 * only acquired when we held swap_info_struct->lock
360 */
361 ci_tail = ci + tail;
362 spin_lock_nested(&ci_tail->lock, SINGLE_DEPTH_NESTING);
363 cluster_set_next(ci_tail, idx);
0ef017d1 364 spin_unlock(&ci_tail->lock);
6b534915
HY
365 cluster_set_next_flag(&list->tail, idx, 0);
366 }
367}
368
369static unsigned int cluster_list_del_first(struct swap_cluster_list *list,
370 struct swap_cluster_info *ci)
371{
372 unsigned int idx;
373
374 idx = cluster_next(&list->head);
375 if (cluster_next(&list->tail) == idx) {
376 cluster_set_null(&list->head);
377 cluster_set_null(&list->tail);
378 } else
379 cluster_set_next_flag(&list->head,
380 cluster_next(&ci[idx]), 0);
381
382 return idx;
383}
384
815c2c54
SL
385/* Add a cluster to discard list and schedule it to do discard */
386static void swap_cluster_schedule_discard(struct swap_info_struct *si,
387 unsigned int idx)
388{
389 /*
390 * If scan_swap_map() can't find a free cluster, it will check
391 * si->swap_map directly. To make sure the discarding cluster isn't
392 * taken by scan_swap_map(), mark the swap entries bad (occupied). It
393 * will be cleared after discard
394 */
395 memset(si->swap_map + idx * SWAPFILE_CLUSTER,
396 SWAP_MAP_BAD, SWAPFILE_CLUSTER);
397
6b534915 398 cluster_list_add_tail(&si->discard_clusters, si->cluster_info, idx);
815c2c54
SL
399
400 schedule_work(&si->discard_work);
401}
402
38d8b4e6
HY
403static void __free_cluster(struct swap_info_struct *si, unsigned long idx)
404{
405 struct swap_cluster_info *ci = si->cluster_info;
406
407 cluster_set_flag(ci + idx, CLUSTER_FLAG_FREE);
408 cluster_list_add_tail(&si->free_clusters, ci, idx);
409}
410
815c2c54
SL
411/*
412 * Doing discard actually. After a cluster discard is finished, the cluster
413 * will be added to free cluster list. caller should hold si->lock.
414*/
415static void swap_do_scheduled_discard(struct swap_info_struct *si)
416{
235b6217 417 struct swap_cluster_info *info, *ci;
815c2c54
SL
418 unsigned int idx;
419
420 info = si->cluster_info;
421
6b534915
HY
422 while (!cluster_list_empty(&si->discard_clusters)) {
423 idx = cluster_list_del_first(&si->discard_clusters, info);
815c2c54
SL
424 spin_unlock(&si->lock);
425
426 discard_swap_cluster(si, idx * SWAPFILE_CLUSTER,
427 SWAPFILE_CLUSTER);
428
429 spin_lock(&si->lock);
235b6217 430 ci = lock_cluster(si, idx * SWAPFILE_CLUSTER);
38d8b4e6 431 __free_cluster(si, idx);
815c2c54
SL
432 memset(si->swap_map + idx * SWAPFILE_CLUSTER,
433 0, SWAPFILE_CLUSTER);
235b6217 434 unlock_cluster(ci);
815c2c54
SL
435 }
436}
437
438static void swap_discard_work(struct work_struct *work)
439{
440 struct swap_info_struct *si;
441
442 si = container_of(work, struct swap_info_struct, discard_work);
443
444 spin_lock(&si->lock);
445 swap_do_scheduled_discard(si);
446 spin_unlock(&si->lock);
447}
448
38d8b4e6
HY
449static void alloc_cluster(struct swap_info_struct *si, unsigned long idx)
450{
451 struct swap_cluster_info *ci = si->cluster_info;
452
453 VM_BUG_ON(cluster_list_first(&si->free_clusters) != idx);
454 cluster_list_del_first(&si->free_clusters, ci);
455 cluster_set_count_flag(ci + idx, 0, 0);
456}
457
458static void free_cluster(struct swap_info_struct *si, unsigned long idx)
459{
460 struct swap_cluster_info *ci = si->cluster_info + idx;
461
462 VM_BUG_ON(cluster_count(ci) != 0);
463 /*
464 * If the swap is discardable, prepare discard the cluster
465 * instead of free it immediately. The cluster will be freed
466 * after discard.
467 */
468 if ((si->flags & (SWP_WRITEOK | SWP_PAGE_DISCARD)) ==
469 (SWP_WRITEOK | SWP_PAGE_DISCARD)) {
470 swap_cluster_schedule_discard(si, idx);
471 return;
472 }
473
474 __free_cluster(si, idx);
475}
476
2a8f9449
SL
477/*
478 * The cluster corresponding to page_nr will be used. The cluster will be
479 * removed from free cluster list and its usage counter will be increased.
480 */
481static void inc_cluster_info_page(struct swap_info_struct *p,
482 struct swap_cluster_info *cluster_info, unsigned long page_nr)
483{
484 unsigned long idx = page_nr / SWAPFILE_CLUSTER;
485
486 if (!cluster_info)
487 return;
38d8b4e6
HY
488 if (cluster_is_free(&cluster_info[idx]))
489 alloc_cluster(p, idx);
2a8f9449
SL
490
491 VM_BUG_ON(cluster_count(&cluster_info[idx]) >= SWAPFILE_CLUSTER);
492 cluster_set_count(&cluster_info[idx],
493 cluster_count(&cluster_info[idx]) + 1);
494}
495
496/*
497 * The cluster corresponding to page_nr decreases one usage. If the usage
498 * counter becomes 0, which means no page in the cluster is in using, we can
499 * optionally discard the cluster and add it to free cluster list.
500 */
501static void dec_cluster_info_page(struct swap_info_struct *p,
502 struct swap_cluster_info *cluster_info, unsigned long page_nr)
503{
504 unsigned long idx = page_nr / SWAPFILE_CLUSTER;
505
506 if (!cluster_info)
507 return;
508
509 VM_BUG_ON(cluster_count(&cluster_info[idx]) == 0);
510 cluster_set_count(&cluster_info[idx],
511 cluster_count(&cluster_info[idx]) - 1);
512
38d8b4e6
HY
513 if (cluster_count(&cluster_info[idx]) == 0)
514 free_cluster(p, idx);
2a8f9449
SL
515}
516
517/*
518 * It's possible scan_swap_map() uses a free cluster in the middle of free
519 * cluster list. Avoiding such abuse to avoid list corruption.
520 */
ebc2a1a6
SL
521static bool
522scan_swap_map_ssd_cluster_conflict(struct swap_info_struct *si,
2a8f9449
SL
523 unsigned long offset)
524{
ebc2a1a6
SL
525 struct percpu_cluster *percpu_cluster;
526 bool conflict;
527
2a8f9449 528 offset /= SWAPFILE_CLUSTER;
6b534915
HY
529 conflict = !cluster_list_empty(&si->free_clusters) &&
530 offset != cluster_list_first(&si->free_clusters) &&
2a8f9449 531 cluster_is_free(&si->cluster_info[offset]);
ebc2a1a6
SL
532
533 if (!conflict)
534 return false;
535
536 percpu_cluster = this_cpu_ptr(si->percpu_cluster);
537 cluster_set_null(&percpu_cluster->index);
538 return true;
539}
540
541/*
542 * Try to get a swap entry from current cpu's swap entry pool (a cluster). This
543 * might involve allocating a new cluster for current CPU too.
544 */
36005bae 545static bool scan_swap_map_try_ssd_cluster(struct swap_info_struct *si,
ebc2a1a6
SL
546 unsigned long *offset, unsigned long *scan_base)
547{
548 struct percpu_cluster *cluster;
235b6217 549 struct swap_cluster_info *ci;
ebc2a1a6 550 bool found_free;
235b6217 551 unsigned long tmp, max;
ebc2a1a6
SL
552
553new_cluster:
554 cluster = this_cpu_ptr(si->percpu_cluster);
555 if (cluster_is_null(&cluster->index)) {
6b534915
HY
556 if (!cluster_list_empty(&si->free_clusters)) {
557 cluster->index = si->free_clusters.head;
ebc2a1a6
SL
558 cluster->next = cluster_next(&cluster->index) *
559 SWAPFILE_CLUSTER;
6b534915 560 } else if (!cluster_list_empty(&si->discard_clusters)) {
ebc2a1a6
SL
561 /*
562 * we don't have free cluster but have some clusters in
563 * discarding, do discard now and reclaim them
564 */
565 swap_do_scheduled_discard(si);
566 *scan_base = *offset = si->cluster_next;
567 goto new_cluster;
568 } else
36005bae 569 return false;
ebc2a1a6
SL
570 }
571
572 found_free = false;
573
574 /*
575 * Other CPUs can use our cluster if they can't find a free cluster,
576 * check if there is still free entry in the cluster
577 */
578 tmp = cluster->next;
235b6217
HY
579 max = min_t(unsigned long, si->max,
580 (cluster_next(&cluster->index) + 1) * SWAPFILE_CLUSTER);
581 if (tmp >= max) {
582 cluster_set_null(&cluster->index);
583 goto new_cluster;
584 }
585 ci = lock_cluster(si, tmp);
586 while (tmp < max) {
ebc2a1a6
SL
587 if (!si->swap_map[tmp]) {
588 found_free = true;
589 break;
590 }
591 tmp++;
592 }
235b6217 593 unlock_cluster(ci);
ebc2a1a6
SL
594 if (!found_free) {
595 cluster_set_null(&cluster->index);
596 goto new_cluster;
597 }
598 cluster->next = tmp + 1;
599 *offset = tmp;
600 *scan_base = tmp;
36005bae 601 return found_free;
2a8f9449
SL
602}
603
a2468cc9
AL
604static void __del_from_avail_list(struct swap_info_struct *p)
605{
606 int nid;
607
608 for_each_node(nid)
609 plist_del(&p->avail_lists[nid], &swap_avail_heads[nid]);
610}
611
612static void del_from_avail_list(struct swap_info_struct *p)
613{
614 spin_lock(&swap_avail_lock);
615 __del_from_avail_list(p);
616 spin_unlock(&swap_avail_lock);
617}
618
38d8b4e6
HY
619static void swap_range_alloc(struct swap_info_struct *si, unsigned long offset,
620 unsigned int nr_entries)
621{
622 unsigned int end = offset + nr_entries - 1;
623
624 if (offset == si->lowest_bit)
625 si->lowest_bit += nr_entries;
626 if (end == si->highest_bit)
627 si->highest_bit -= nr_entries;
628 si->inuse_pages += nr_entries;
629 if (si->inuse_pages == si->pages) {
630 si->lowest_bit = si->max;
631 si->highest_bit = 0;
a2468cc9 632 del_from_avail_list(si);
38d8b4e6
HY
633 }
634}
635
a2468cc9
AL
636static void add_to_avail_list(struct swap_info_struct *p)
637{
638 int nid;
639
640 spin_lock(&swap_avail_lock);
641 for_each_node(nid) {
642 WARN_ON(!plist_node_empty(&p->avail_lists[nid]));
643 plist_add(&p->avail_lists[nid], &swap_avail_heads[nid]);
644 }
645 spin_unlock(&swap_avail_lock);
646}
647
38d8b4e6
HY
648static void swap_range_free(struct swap_info_struct *si, unsigned long offset,
649 unsigned int nr_entries)
650{
651 unsigned long end = offset + nr_entries - 1;
652 void (*swap_slot_free_notify)(struct block_device *, unsigned long);
653
654 if (offset < si->lowest_bit)
655 si->lowest_bit = offset;
656 if (end > si->highest_bit) {
657 bool was_full = !si->highest_bit;
658
659 si->highest_bit = end;
a2468cc9
AL
660 if (was_full && (si->flags & SWP_WRITEOK))
661 add_to_avail_list(si);
38d8b4e6
HY
662 }
663 atomic_long_add(nr_entries, &nr_swap_pages);
664 si->inuse_pages -= nr_entries;
665 if (si->flags & SWP_BLKDEV)
666 swap_slot_free_notify =
667 si->bdev->bd_disk->fops->swap_slot_free_notify;
668 else
669 swap_slot_free_notify = NULL;
670 while (offset <= end) {
671 frontswap_invalidate_page(si->type, offset);
672 if (swap_slot_free_notify)
673 swap_slot_free_notify(si->bdev, offset);
674 offset++;
675 }
676}
677
36005bae
TC
678static int scan_swap_map_slots(struct swap_info_struct *si,
679 unsigned char usage, int nr,
680 swp_entry_t slots[])
1da177e4 681{
235b6217 682 struct swap_cluster_info *ci;
ebebbbe9 683 unsigned long offset;
c60aa176 684 unsigned long scan_base;
7992fde7 685 unsigned long last_in_cluster = 0;
048c27fd 686 int latency_ration = LATENCY_LIMIT;
36005bae
TC
687 int n_ret = 0;
688
689 if (nr > SWAP_BATCH)
690 nr = SWAP_BATCH;
7dfad418 691
886bb7e9 692 /*
7dfad418
HD
693 * We try to cluster swap pages by allocating them sequentially
694 * in swap. Once we've allocated SWAPFILE_CLUSTER pages this
695 * way, however, we resort to first-free allocation, starting
696 * a new cluster. This prevents us from scattering swap pages
697 * all over the entire swap partition, so that we reduce
698 * overall disk seek times between swap pages. -- sct
699 * But we do now try to find an empty cluster. -Andrea
c60aa176 700 * And we let swap pages go all over an SSD partition. Hugh
7dfad418
HD
701 */
702
52b7efdb 703 si->flags += SWP_SCANNING;
c60aa176 704 scan_base = offset = si->cluster_next;
ebebbbe9 705
ebc2a1a6
SL
706 /* SSD algorithm */
707 if (si->cluster_info) {
36005bae
TC
708 if (scan_swap_map_try_ssd_cluster(si, &offset, &scan_base))
709 goto checks;
710 else
711 goto scan;
ebc2a1a6
SL
712 }
713
ebebbbe9
HD
714 if (unlikely(!si->cluster_nr--)) {
715 if (si->pages - si->inuse_pages < SWAPFILE_CLUSTER) {
716 si->cluster_nr = SWAPFILE_CLUSTER - 1;
717 goto checks;
718 }
2a8f9449 719
ec8acf20 720 spin_unlock(&si->lock);
7dfad418 721
c60aa176
HD
722 /*
723 * If seek is expensive, start searching for new cluster from
724 * start of partition, to minimize the span of allocated swap.
50088c44
CY
725 * If seek is cheap, that is the SWP_SOLIDSTATE si->cluster_info
726 * case, just handled by scan_swap_map_try_ssd_cluster() above.
c60aa176 727 */
50088c44 728 scan_base = offset = si->lowest_bit;
7dfad418
HD
729 last_in_cluster = offset + SWAPFILE_CLUSTER - 1;
730
731 /* Locate the first empty (unaligned) cluster */
732 for (; last_in_cluster <= si->highest_bit; offset++) {
1da177e4 733 if (si->swap_map[offset])
7dfad418
HD
734 last_in_cluster = offset + SWAPFILE_CLUSTER;
735 else if (offset == last_in_cluster) {
ec8acf20 736 spin_lock(&si->lock);
ebebbbe9
HD
737 offset -= SWAPFILE_CLUSTER - 1;
738 si->cluster_next = offset;
739 si->cluster_nr = SWAPFILE_CLUSTER - 1;
c60aa176
HD
740 goto checks;
741 }
742 if (unlikely(--latency_ration < 0)) {
743 cond_resched();
744 latency_ration = LATENCY_LIMIT;
745 }
746 }
747
748 offset = scan_base;
ec8acf20 749 spin_lock(&si->lock);
ebebbbe9 750 si->cluster_nr = SWAPFILE_CLUSTER - 1;
1da177e4 751 }
7dfad418 752
ebebbbe9 753checks:
ebc2a1a6 754 if (si->cluster_info) {
36005bae
TC
755 while (scan_swap_map_ssd_cluster_conflict(si, offset)) {
756 /* take a break if we already got some slots */
757 if (n_ret)
758 goto done;
759 if (!scan_swap_map_try_ssd_cluster(si, &offset,
760 &scan_base))
761 goto scan;
762 }
ebc2a1a6 763 }
ebebbbe9 764 if (!(si->flags & SWP_WRITEOK))
52b7efdb 765 goto no_page;
7dfad418
HD
766 if (!si->highest_bit)
767 goto no_page;
ebebbbe9 768 if (offset > si->highest_bit)
c60aa176 769 scan_base = offset = si->lowest_bit;
c9e44410 770
235b6217 771 ci = lock_cluster(si, offset);
b73d7fce
HD
772 /* reuse swap entry of cache-only swap if not busy. */
773 if (vm_swap_full() && si->swap_map[offset] == SWAP_HAS_CACHE) {
c9e44410 774 int swap_was_freed;
235b6217 775 unlock_cluster(ci);
ec8acf20 776 spin_unlock(&si->lock);
c9e44410 777 swap_was_freed = __try_to_reclaim_swap(si, offset);
ec8acf20 778 spin_lock(&si->lock);
c9e44410
KH
779 /* entry was freed successfully, try to use this again */
780 if (swap_was_freed)
781 goto checks;
782 goto scan; /* check next one */
783 }
784
235b6217
HY
785 if (si->swap_map[offset]) {
786 unlock_cluster(ci);
36005bae
TC
787 if (!n_ret)
788 goto scan;
789 else
790 goto done;
235b6217 791 }
2872bb2d
HY
792 si->swap_map[offset] = usage;
793 inc_cluster_info_page(si, si->cluster_info, offset);
794 unlock_cluster(ci);
ebebbbe9 795
38d8b4e6 796 swap_range_alloc(si, offset, 1);
ebebbbe9 797 si->cluster_next = offset + 1;
36005bae
TC
798 slots[n_ret++] = swp_entry(si->type, offset);
799
800 /* got enough slots or reach max slots? */
801 if ((n_ret == nr) || (offset >= si->highest_bit))
802 goto done;
803
804 /* search for next available slot */
805
806 /* time to take a break? */
807 if (unlikely(--latency_ration < 0)) {
808 if (n_ret)
809 goto done;
810 spin_unlock(&si->lock);
811 cond_resched();
812 spin_lock(&si->lock);
813 latency_ration = LATENCY_LIMIT;
814 }
815
816 /* try to get more slots in cluster */
817 if (si->cluster_info) {
818 if (scan_swap_map_try_ssd_cluster(si, &offset, &scan_base))
819 goto checks;
820 else
821 goto done;
822 }
823 /* non-ssd case */
824 ++offset;
825
826 /* non-ssd case, still more slots in cluster? */
827 if (si->cluster_nr && !si->swap_map[offset]) {
828 --si->cluster_nr;
829 goto checks;
830 }
7992fde7 831
36005bae
TC
832done:
833 si->flags -= SWP_SCANNING;
834 return n_ret;
7dfad418 835
ebebbbe9 836scan:
ec8acf20 837 spin_unlock(&si->lock);
7dfad418 838 while (++offset <= si->highest_bit) {
52b7efdb 839 if (!si->swap_map[offset]) {
ec8acf20 840 spin_lock(&si->lock);
52b7efdb
HD
841 goto checks;
842 }
c9e44410 843 if (vm_swap_full() && si->swap_map[offset] == SWAP_HAS_CACHE) {
ec8acf20 844 spin_lock(&si->lock);
c9e44410
KH
845 goto checks;
846 }
048c27fd
HD
847 if (unlikely(--latency_ration < 0)) {
848 cond_resched();
849 latency_ration = LATENCY_LIMIT;
850 }
7dfad418 851 }
c60aa176 852 offset = si->lowest_bit;
a5998061 853 while (offset < scan_base) {
c60aa176 854 if (!si->swap_map[offset]) {
ec8acf20 855 spin_lock(&si->lock);
c60aa176
HD
856 goto checks;
857 }
c9e44410 858 if (vm_swap_full() && si->swap_map[offset] == SWAP_HAS_CACHE) {
ec8acf20 859 spin_lock(&si->lock);
c9e44410
KH
860 goto checks;
861 }
c60aa176
HD
862 if (unlikely(--latency_ration < 0)) {
863 cond_resched();
864 latency_ration = LATENCY_LIMIT;
865 }
a5998061 866 offset++;
c60aa176 867 }
ec8acf20 868 spin_lock(&si->lock);
7dfad418
HD
869
870no_page:
52b7efdb 871 si->flags -= SWP_SCANNING;
36005bae 872 return n_ret;
1da177e4
LT
873}
874
38d8b4e6
HY
875#ifdef CONFIG_THP_SWAP
876static int swap_alloc_cluster(struct swap_info_struct *si, swp_entry_t *slot)
877{
878 unsigned long idx;
879 struct swap_cluster_info *ci;
880 unsigned long offset, i;
881 unsigned char *map;
882
883 if (cluster_list_empty(&si->free_clusters))
884 return 0;
885
886 idx = cluster_list_first(&si->free_clusters);
887 offset = idx * SWAPFILE_CLUSTER;
888 ci = lock_cluster(si, offset);
889 alloc_cluster(si, idx);
e0709829 890 cluster_set_count_flag(ci, SWAPFILE_CLUSTER, CLUSTER_FLAG_HUGE);
38d8b4e6
HY
891
892 map = si->swap_map + offset;
893 for (i = 0; i < SWAPFILE_CLUSTER; i++)
894 map[i] = SWAP_HAS_CACHE;
895 unlock_cluster(ci);
896 swap_range_alloc(si, offset, SWAPFILE_CLUSTER);
897 *slot = swp_entry(si->type, offset);
898
899 return 1;
900}
901
902static void swap_free_cluster(struct swap_info_struct *si, unsigned long idx)
903{
904 unsigned long offset = idx * SWAPFILE_CLUSTER;
905 struct swap_cluster_info *ci;
906
907 ci = lock_cluster(si, offset);
908 cluster_set_count_flag(ci, 0, 0);
909 free_cluster(si, idx);
910 unlock_cluster(ci);
911 swap_range_free(si, offset, SWAPFILE_CLUSTER);
912}
913#else
914static int swap_alloc_cluster(struct swap_info_struct *si, swp_entry_t *slot)
915{
916 VM_WARN_ON_ONCE(1);
917 return 0;
918}
919#endif /* CONFIG_THP_SWAP */
920
36005bae
TC
921static unsigned long scan_swap_map(struct swap_info_struct *si,
922 unsigned char usage)
923{
924 swp_entry_t entry;
925 int n_ret;
926
927 n_ret = scan_swap_map_slots(si, usage, 1, &entry);
928
929 if (n_ret)
930 return swp_offset(entry);
931 else
932 return 0;
933
934}
935
38d8b4e6 936int get_swap_pages(int n_goal, bool cluster, swp_entry_t swp_entries[])
1da177e4 937{
38d8b4e6 938 unsigned long nr_pages = cluster ? SWAPFILE_CLUSTER : 1;
adfab836 939 struct swap_info_struct *si, *next;
36005bae
TC
940 long avail_pgs;
941 int n_ret = 0;
a2468cc9 942 int node;
1da177e4 943
38d8b4e6
HY
944 /* Only single cluster request supported */
945 WARN_ON_ONCE(n_goal > 1 && cluster);
946
947 avail_pgs = atomic_long_read(&nr_swap_pages) / nr_pages;
36005bae 948 if (avail_pgs <= 0)
fb4f88dc 949 goto noswap;
36005bae
TC
950
951 if (n_goal > SWAP_BATCH)
952 n_goal = SWAP_BATCH;
953
954 if (n_goal > avail_pgs)
955 n_goal = avail_pgs;
956
38d8b4e6 957 atomic_long_sub(n_goal * nr_pages, &nr_swap_pages);
fb4f88dc 958
18ab4d4c
DS
959 spin_lock(&swap_avail_lock);
960
961start_over:
a2468cc9
AL
962 node = numa_node_id();
963 plist_for_each_entry_safe(si, next, &swap_avail_heads[node], avail_lists[node]) {
18ab4d4c 964 /* requeue si to after same-priority siblings */
a2468cc9 965 plist_requeue(&si->avail_lists[node], &swap_avail_heads[node]);
18ab4d4c 966 spin_unlock(&swap_avail_lock);
ec8acf20 967 spin_lock(&si->lock);
adfab836 968 if (!si->highest_bit || !(si->flags & SWP_WRITEOK)) {
18ab4d4c 969 spin_lock(&swap_avail_lock);
a2468cc9 970 if (plist_node_empty(&si->avail_lists[node])) {
18ab4d4c
DS
971 spin_unlock(&si->lock);
972 goto nextsi;
973 }
974 WARN(!si->highest_bit,
975 "swap_info %d in list but !highest_bit\n",
976 si->type);
977 WARN(!(si->flags & SWP_WRITEOK),
978 "swap_info %d in list but !SWP_WRITEOK\n",
979 si->type);
a2468cc9 980 __del_from_avail_list(si);
ec8acf20 981 spin_unlock(&si->lock);
18ab4d4c 982 goto nextsi;
ec8acf20 983 }
f0eea189
HY
984 if (cluster) {
985 if (!(si->flags & SWP_FILE))
986 n_ret = swap_alloc_cluster(si, swp_entries);
987 } else
38d8b4e6
HY
988 n_ret = scan_swap_map_slots(si, SWAP_HAS_CACHE,
989 n_goal, swp_entries);
ec8acf20 990 spin_unlock(&si->lock);
38d8b4e6 991 if (n_ret || cluster)
36005bae 992 goto check_out;
18ab4d4c 993 pr_debug("scan_swap_map of si %d failed to find offset\n",
36005bae
TC
994 si->type);
995
18ab4d4c
DS
996 spin_lock(&swap_avail_lock);
997nextsi:
adfab836
DS
998 /*
999 * if we got here, it's likely that si was almost full before,
1000 * and since scan_swap_map() can drop the si->lock, multiple
1001 * callers probably all tried to get a page from the same si
18ab4d4c
DS
1002 * and it filled up before we could get one; or, the si filled
1003 * up between us dropping swap_avail_lock and taking si->lock.
1004 * Since we dropped the swap_avail_lock, the swap_avail_head
1005 * list may have been modified; so if next is still in the
36005bae
TC
1006 * swap_avail_head list then try it, otherwise start over
1007 * if we have not gotten any slots.
adfab836 1008 */
a2468cc9 1009 if (plist_node_empty(&next->avail_lists[node]))
18ab4d4c 1010 goto start_over;
1da177e4 1011 }
fb4f88dc 1012
18ab4d4c
DS
1013 spin_unlock(&swap_avail_lock);
1014
36005bae
TC
1015check_out:
1016 if (n_ret < n_goal)
38d8b4e6
HY
1017 atomic_long_add((long)(n_goal - n_ret) * nr_pages,
1018 &nr_swap_pages);
fb4f88dc 1019noswap:
36005bae
TC
1020 return n_ret;
1021}
1022
2de1a7e4 1023/* The only caller of this function is now suspend routine */
910321ea
HD
1024swp_entry_t get_swap_page_of_type(int type)
1025{
27a34b2d 1026 struct swap_info_struct *si = swap_type_to_swap_info(type);
910321ea
HD
1027 pgoff_t offset;
1028
27a34b2d
DJ
1029 if (!si)
1030 goto fail;
1031
ec8acf20 1032 spin_lock(&si->lock);
27a34b2d 1033 if (si->flags & SWP_WRITEOK) {
ec8acf20 1034 atomic_long_dec(&nr_swap_pages);
910321ea
HD
1035 /* This is called for allocating swap entry, not cache */
1036 offset = scan_swap_map(si, 1);
1037 if (offset) {
ec8acf20 1038 spin_unlock(&si->lock);
910321ea
HD
1039 return swp_entry(type, offset);
1040 }
ec8acf20 1041 atomic_long_inc(&nr_swap_pages);
910321ea 1042 }
ec8acf20 1043 spin_unlock(&si->lock);
27a34b2d 1044fail:
910321ea
HD
1045 return (swp_entry_t) {0};
1046}
1047
e8c26ab6 1048static struct swap_info_struct *__swap_info_get(swp_entry_t entry)
1da177e4 1049{
73c34b6a 1050 struct swap_info_struct *p;
1da177e4
LT
1051 unsigned long offset, type;
1052
1053 if (!entry.val)
1054 goto out;
1055 type = swp_type(entry);
27a34b2d
DJ
1056 p = swap_type_to_swap_info(type);
1057 if (!p)
1da177e4 1058 goto bad_nofile;
1da177e4
LT
1059 if (!(p->flags & SWP_USED))
1060 goto bad_device;
1061 offset = swp_offset(entry);
1062 if (offset >= p->max)
1063 goto bad_offset;
1da177e4
LT
1064 return p;
1065
1da177e4 1066bad_offset:
6a991fc7 1067 pr_err("swap_info_get: %s%08lx\n", Bad_offset, entry.val);
1da177e4
LT
1068 goto out;
1069bad_device:
6a991fc7 1070 pr_err("swap_info_get: %s%08lx\n", Unused_file, entry.val);
1da177e4
LT
1071 goto out;
1072bad_nofile:
6a991fc7 1073 pr_err("swap_info_get: %s%08lx\n", Bad_file, entry.val);
1da177e4
LT
1074out:
1075 return NULL;
886bb7e9 1076}
1da177e4 1077
e8c26ab6
TC
1078static struct swap_info_struct *_swap_info_get(swp_entry_t entry)
1079{
1080 struct swap_info_struct *p;
1081
1082 p = __swap_info_get(entry);
1083 if (!p)
1084 goto out;
1085 if (!p->swap_map[swp_offset(entry)])
1086 goto bad_free;
1087 return p;
1088
1089bad_free:
1090 pr_err("swap_info_get: %s%08lx\n", Unused_offset, entry.val);
1091 goto out;
1092out:
1093 return NULL;
1094}
1095
235b6217
HY
1096static struct swap_info_struct *swap_info_get(swp_entry_t entry)
1097{
1098 struct swap_info_struct *p;
1099
1100 p = _swap_info_get(entry);
1101 if (p)
1102 spin_lock(&p->lock);
1103 return p;
1104}
1105
7c00bafe
TC
1106static struct swap_info_struct *swap_info_get_cont(swp_entry_t entry,
1107 struct swap_info_struct *q)
1108{
1109 struct swap_info_struct *p;
1110
1111 p = _swap_info_get(entry);
1112
1113 if (p != q) {
1114 if (q != NULL)
1115 spin_unlock(&q->lock);
1116 if (p != NULL)
1117 spin_lock(&p->lock);
1118 }
1119 return p;
1120}
1121
1122static unsigned char __swap_entry_free(struct swap_info_struct *p,
1123 swp_entry_t entry, unsigned char usage)
1da177e4 1124{
235b6217 1125 struct swap_cluster_info *ci;
253d553b 1126 unsigned long offset = swp_offset(entry);
8d69aaee
HD
1127 unsigned char count;
1128 unsigned char has_cache;
235b6217 1129
7c00bafe 1130 ci = lock_cluster_or_swap_info(p, offset);
355cfa73 1131
253d553b 1132 count = p->swap_map[offset];
235b6217 1133
253d553b
HD
1134 has_cache = count & SWAP_HAS_CACHE;
1135 count &= ~SWAP_HAS_CACHE;
355cfa73 1136
253d553b 1137 if (usage == SWAP_HAS_CACHE) {
355cfa73 1138 VM_BUG_ON(!has_cache);
253d553b 1139 has_cache = 0;
aaa46865
HD
1140 } else if (count == SWAP_MAP_SHMEM) {
1141 /*
1142 * Or we could insist on shmem.c using a special
1143 * swap_shmem_free() and free_shmem_swap_and_cache()...
1144 */
1145 count = 0;
570a335b
HD
1146 } else if ((count & ~COUNT_CONTINUED) <= SWAP_MAP_MAX) {
1147 if (count == COUNT_CONTINUED) {
1148 if (swap_count_continued(p, offset, count))
1149 count = SWAP_MAP_MAX | COUNT_CONTINUED;
1150 else
1151 count = SWAP_MAP_MAX;
1152 } else
1153 count--;
1154 }
253d553b 1155
253d553b 1156 usage = count | has_cache;
7c00bafe
TC
1157 p->swap_map[offset] = usage ? : SWAP_HAS_CACHE;
1158
1159 unlock_cluster_or_swap_info(p, ci);
1160
1161 return usage;
1162}
355cfa73 1163
7c00bafe
TC
1164static void swap_entry_free(struct swap_info_struct *p, swp_entry_t entry)
1165{
1166 struct swap_cluster_info *ci;
1167 unsigned long offset = swp_offset(entry);
1168 unsigned char count;
1169
1170 ci = lock_cluster(p, offset);
1171 count = p->swap_map[offset];
1172 VM_BUG_ON(count != SWAP_HAS_CACHE);
1173 p->swap_map[offset] = 0;
1174 dec_cluster_info_page(p, p->cluster_info, offset);
235b6217
HY
1175 unlock_cluster(ci);
1176
38d8b4e6
HY
1177 mem_cgroup_uncharge_swap(entry, 1);
1178 swap_range_free(p, offset, 1);
1da177e4
LT
1179}
1180
1181/*
2de1a7e4 1182 * Caller has made sure that the swap device corresponding to entry
1da177e4
LT
1183 * is still around or has not been recycled.
1184 */
1185void swap_free(swp_entry_t entry)
1186{
73c34b6a 1187 struct swap_info_struct *p;
1da177e4 1188
235b6217 1189 p = _swap_info_get(entry);
7c00bafe
TC
1190 if (p) {
1191 if (!__swap_entry_free(p, entry, 1))
67afa38e 1192 free_swap_slot(entry);
7c00bafe 1193 }
1da177e4
LT
1194}
1195
cb4b86ba
KH
1196/*
1197 * Called after dropping swapcache to decrease refcnt to swap entries.
1198 */
75f6d6d2 1199static void swapcache_free(swp_entry_t entry)
cb4b86ba 1200{
355cfa73
KH
1201 struct swap_info_struct *p;
1202
235b6217 1203 p = _swap_info_get(entry);
7c00bafe
TC
1204 if (p) {
1205 if (!__swap_entry_free(p, entry, SWAP_HAS_CACHE))
67afa38e 1206 free_swap_slot(entry);
7c00bafe
TC
1207 }
1208}
1209
38d8b4e6 1210#ifdef CONFIG_THP_SWAP
75f6d6d2 1211static void swapcache_free_cluster(swp_entry_t entry)
38d8b4e6
HY
1212{
1213 unsigned long offset = swp_offset(entry);
1214 unsigned long idx = offset / SWAPFILE_CLUSTER;
1215 struct swap_cluster_info *ci;
1216 struct swap_info_struct *si;
1217 unsigned char *map;
a3aea839
HY
1218 unsigned int i, free_entries = 0;
1219 unsigned char val;
38d8b4e6 1220
a3aea839 1221 si = _swap_info_get(entry);
38d8b4e6
HY
1222 if (!si)
1223 return;
1224
1225 ci = lock_cluster(si, offset);
e0709829 1226 VM_BUG_ON(!cluster_is_huge(ci));
38d8b4e6
HY
1227 map = si->swap_map + offset;
1228 for (i = 0; i < SWAPFILE_CLUSTER; i++) {
a3aea839
HY
1229 val = map[i];
1230 VM_BUG_ON(!(val & SWAP_HAS_CACHE));
1231 if (val == SWAP_HAS_CACHE)
1232 free_entries++;
1233 }
1234 if (!free_entries) {
1235 for (i = 0; i < SWAPFILE_CLUSTER; i++)
1236 map[i] &= ~SWAP_HAS_CACHE;
38d8b4e6 1237 }
e0709829 1238 cluster_clear_huge(ci);
38d8b4e6 1239 unlock_cluster(ci);
a3aea839
HY
1240 if (free_entries == SWAPFILE_CLUSTER) {
1241 spin_lock(&si->lock);
1242 ci = lock_cluster(si, offset);
1243 memset(map, 0, SWAPFILE_CLUSTER);
1244 unlock_cluster(ci);
1245 mem_cgroup_uncharge_swap(entry, SWAPFILE_CLUSTER);
1246 swap_free_cluster(si, idx);
1247 spin_unlock(&si->lock);
1248 } else if (free_entries) {
1249 for (i = 0; i < SWAPFILE_CLUSTER; i++, entry.val++) {
1250 if (!__swap_entry_free(si, entry, SWAP_HAS_CACHE))
1251 free_swap_slot(entry);
1252 }
1253 }
38d8b4e6 1254}
59807685
HY
1255
1256int split_swap_cluster(swp_entry_t entry)
1257{
1258 struct swap_info_struct *si;
1259 struct swap_cluster_info *ci;
1260 unsigned long offset = swp_offset(entry);
1261
1262 si = _swap_info_get(entry);
1263 if (!si)
1264 return -EBUSY;
1265 ci = lock_cluster(si, offset);
1266 cluster_clear_huge(ci);
1267 unlock_cluster(ci);
1268 return 0;
1269}
75f6d6d2
MK
1270#else
1271static inline void swapcache_free_cluster(swp_entry_t entry)
1272{
1273}
38d8b4e6
HY
1274#endif /* CONFIG_THP_SWAP */
1275
75f6d6d2
MK
1276void put_swap_page(struct page *page, swp_entry_t entry)
1277{
1278 if (!PageTransHuge(page))
1279 swapcache_free(entry);
1280 else
1281 swapcache_free_cluster(entry);
1282}
1283
155b5f88
HY
1284static int swp_entry_cmp(const void *ent1, const void *ent2)
1285{
1286 const swp_entry_t *e1 = ent1, *e2 = ent2;
1287
1288 return (int)swp_type(*e1) - (int)swp_type(*e2);
1289}
1290
7c00bafe
TC
1291void swapcache_free_entries(swp_entry_t *entries, int n)
1292{
1293 struct swap_info_struct *p, *prev;
1294 int i;
1295
1296 if (n <= 0)
1297 return;
1298
1299 prev = NULL;
1300 p = NULL;
155b5f88
HY
1301
1302 /*
1303 * Sort swap entries by swap device, so each lock is only taken once.
1304 * nr_swapfiles isn't absolutely correct, but the overhead of sort() is
1305 * so low that it isn't necessary to optimize further.
1306 */
1307 if (nr_swapfiles > 1)
1308 sort(entries, n, sizeof(entries[0]), swp_entry_cmp, NULL);
7c00bafe
TC
1309 for (i = 0; i < n; ++i) {
1310 p = swap_info_get_cont(entries[i], prev);
1311 if (p)
1312 swap_entry_free(p, entries[i]);
7c00bafe
TC
1313 prev = p;
1314 }
235b6217 1315 if (p)
7c00bafe 1316 spin_unlock(&p->lock);
cb4b86ba
KH
1317}
1318
1da177e4 1319/*
c475a8ab 1320 * How many references to page are currently swapped out?
570a335b
HD
1321 * This does not give an exact answer when swap count is continued,
1322 * but does include the high COUNT_CONTINUED flag to allow for that.
1da177e4 1323 */
bde05d1c 1324int page_swapcount(struct page *page)
1da177e4 1325{
c475a8ab
HD
1326 int count = 0;
1327 struct swap_info_struct *p;
235b6217 1328 struct swap_cluster_info *ci;
1da177e4 1329 swp_entry_t entry;
235b6217 1330 unsigned long offset;
1da177e4 1331
4c21e2f2 1332 entry.val = page_private(page);
235b6217 1333 p = _swap_info_get(entry);
1da177e4 1334 if (p) {
235b6217
HY
1335 offset = swp_offset(entry);
1336 ci = lock_cluster_or_swap_info(p, offset);
1337 count = swap_count(p->swap_map[offset]);
1338 unlock_cluster_or_swap_info(p, ci);
1da177e4 1339 }
c475a8ab 1340 return count;
1da177e4
LT
1341}
1342
aa8d22a1
MK
1343int __swap_count(struct swap_info_struct *si, swp_entry_t entry)
1344{
1345 pgoff_t offset = swp_offset(entry);
1346
1347 return swap_count(si->swap_map[offset]);
1348}
1349
322b8afe
HY
1350static int swap_swapcount(struct swap_info_struct *si, swp_entry_t entry)
1351{
1352 int count = 0;
1353 pgoff_t offset = swp_offset(entry);
1354 struct swap_cluster_info *ci;
1355
1356 ci = lock_cluster_or_swap_info(si, offset);
1357 count = swap_count(si->swap_map[offset]);
1358 unlock_cluster_or_swap_info(si, ci);
1359 return count;
1360}
1361
e8c26ab6
TC
1362/*
1363 * How many references to @entry are currently swapped out?
1364 * This does not give an exact answer when swap count is continued,
1365 * but does include the high COUNT_CONTINUED flag to allow for that.
1366 */
1367int __swp_swapcount(swp_entry_t entry)
1368{
1369 int count = 0;
e8c26ab6 1370 struct swap_info_struct *si;
e8c26ab6
TC
1371
1372 si = __swap_info_get(entry);
322b8afe
HY
1373 if (si)
1374 count = swap_swapcount(si, entry);
e8c26ab6
TC
1375 return count;
1376}
1377
8334b962
MK
1378/*
1379 * How many references to @entry are currently swapped out?
1380 * This considers COUNT_CONTINUED so it returns exact answer.
1381 */
1382int swp_swapcount(swp_entry_t entry)
1383{
1384 int count, tmp_count, n;
1385 struct swap_info_struct *p;
235b6217 1386 struct swap_cluster_info *ci;
8334b962
MK
1387 struct page *page;
1388 pgoff_t offset;
1389 unsigned char *map;
1390
235b6217 1391 p = _swap_info_get(entry);
8334b962
MK
1392 if (!p)
1393 return 0;
1394
235b6217
HY
1395 offset = swp_offset(entry);
1396
1397 ci = lock_cluster_or_swap_info(p, offset);
1398
1399 count = swap_count(p->swap_map[offset]);
8334b962
MK
1400 if (!(count & COUNT_CONTINUED))
1401 goto out;
1402
1403 count &= ~COUNT_CONTINUED;
1404 n = SWAP_MAP_MAX + 1;
1405
8334b962
MK
1406 page = vmalloc_to_page(p->swap_map + offset);
1407 offset &= ~PAGE_MASK;
1408 VM_BUG_ON(page_private(page) != SWP_CONTINUED);
1409
1410 do {
a8ae4991 1411 page = list_next_entry(page, lru);
8334b962
MK
1412 map = kmap_atomic(page);
1413 tmp_count = map[offset];
1414 kunmap_atomic(map);
1415
1416 count += (tmp_count & ~COUNT_CONTINUED) * n;
1417 n *= (SWAP_CONT_MAX + 1);
1418 } while (tmp_count & COUNT_CONTINUED);
1419out:
235b6217 1420 unlock_cluster_or_swap_info(p, ci);
8334b962
MK
1421 return count;
1422}
1423
e0709829
HY
1424#ifdef CONFIG_THP_SWAP
1425static bool swap_page_trans_huge_swapped(struct swap_info_struct *si,
1426 swp_entry_t entry)
1427{
1428 struct swap_cluster_info *ci;
1429 unsigned char *map = si->swap_map;
1430 unsigned long roffset = swp_offset(entry);
1431 unsigned long offset = round_down(roffset, SWAPFILE_CLUSTER);
1432 int i;
1433 bool ret = false;
1434
1435 ci = lock_cluster_or_swap_info(si, offset);
1436 if (!ci || !cluster_is_huge(ci)) {
1437 if (map[roffset] != SWAP_HAS_CACHE)
1438 ret = true;
1439 goto unlock_out;
1440 }
1441 for (i = 0; i < SWAPFILE_CLUSTER; i++) {
1442 if (map[offset + i] != SWAP_HAS_CACHE) {
1443 ret = true;
1444 break;
1445 }
1446 }
1447unlock_out:
1448 unlock_cluster_or_swap_info(si, ci);
1449 return ret;
1450}
1451
1452static bool page_swapped(struct page *page)
1453{
1454 swp_entry_t entry;
1455 struct swap_info_struct *si;
1456
1457 if (likely(!PageTransCompound(page)))
1458 return page_swapcount(page) != 0;
1459
1460 page = compound_head(page);
1461 entry.val = page_private(page);
1462 si = _swap_info_get(entry);
1463 if (si)
1464 return swap_page_trans_huge_swapped(si, entry);
1465 return false;
1466}
ba3c4ce6
HY
1467
1468static int page_trans_huge_map_swapcount(struct page *page, int *total_mapcount,
1469 int *total_swapcount)
1470{
1471 int i, map_swapcount, _total_mapcount, _total_swapcount;
1472 unsigned long offset = 0;
1473 struct swap_info_struct *si;
1474 struct swap_cluster_info *ci = NULL;
1475 unsigned char *map = NULL;
1476 int mapcount, swapcount = 0;
1477
1478 /* hugetlbfs shouldn't call it */
1479 VM_BUG_ON_PAGE(PageHuge(page), page);
1480
1481 if (likely(!PageTransCompound(page))) {
1482 mapcount = atomic_read(&page->_mapcount) + 1;
1483 if (total_mapcount)
1484 *total_mapcount = mapcount;
1485 if (PageSwapCache(page))
1486 swapcount = page_swapcount(page);
1487 if (total_swapcount)
1488 *total_swapcount = swapcount;
1489 return mapcount + swapcount;
1490 }
1491
1492 page = compound_head(page);
1493
1494 _total_mapcount = _total_swapcount = map_swapcount = 0;
1495 if (PageSwapCache(page)) {
1496 swp_entry_t entry;
1497
1498 entry.val = page_private(page);
1499 si = _swap_info_get(entry);
1500 if (si) {
1501 map = si->swap_map;
1502 offset = swp_offset(entry);
1503 }
1504 }
1505 if (map)
1506 ci = lock_cluster(si, offset);
1507 for (i = 0; i < HPAGE_PMD_NR; i++) {
1508 mapcount = atomic_read(&page[i]._mapcount) + 1;
1509 _total_mapcount += mapcount;
1510 if (map) {
1511 swapcount = swap_count(map[offset + i]);
1512 _total_swapcount += swapcount;
1513 }
1514 map_swapcount = max(map_swapcount, mapcount + swapcount);
1515 }
1516 unlock_cluster(ci);
1517 if (PageDoubleMap(page)) {
1518 map_swapcount -= 1;
1519 _total_mapcount -= HPAGE_PMD_NR;
1520 }
1521 mapcount = compound_mapcount(page);
1522 map_swapcount += mapcount;
1523 _total_mapcount += mapcount;
1524 if (total_mapcount)
1525 *total_mapcount = _total_mapcount;
1526 if (total_swapcount)
1527 *total_swapcount = _total_swapcount;
1528
1529 return map_swapcount;
1530}
e0709829
HY
1531#else
1532#define swap_page_trans_huge_swapped(si, entry) swap_swapcount(si, entry)
1533#define page_swapped(page) (page_swapcount(page) != 0)
ba3c4ce6
HY
1534
1535static int page_trans_huge_map_swapcount(struct page *page, int *total_mapcount,
1536 int *total_swapcount)
1537{
1538 int mapcount, swapcount = 0;
1539
1540 /* hugetlbfs shouldn't call it */
1541 VM_BUG_ON_PAGE(PageHuge(page), page);
1542
1543 mapcount = page_trans_huge_mapcount(page, total_mapcount);
1544 if (PageSwapCache(page))
1545 swapcount = page_swapcount(page);
1546 if (total_swapcount)
1547 *total_swapcount = swapcount;
1548 return mapcount + swapcount;
1549}
e0709829
HY
1550#endif
1551
1da177e4 1552/*
7b1fe597
HD
1553 * We can write to an anon page without COW if there are no other references
1554 * to it. And as a side-effect, free up its swap: because the old content
1555 * on disk will never be read, and seeking back there to write new content
1556 * later would only waste time away from clustering.
6d0a07ed 1557 *
ba3c4ce6 1558 * NOTE: total_map_swapcount should not be relied upon by the caller if
6d0a07ed
AA
1559 * reuse_swap_page() returns false, but it may be always overwritten
1560 * (see the other implementation for CONFIG_SWAP=n).
1da177e4 1561 */
ba3c4ce6 1562bool reuse_swap_page(struct page *page, int *total_map_swapcount)
1da177e4 1563{
ba3c4ce6 1564 int count, total_mapcount, total_swapcount;
c475a8ab 1565
309381fe 1566 VM_BUG_ON_PAGE(!PageLocked(page), page);
5ad64688 1567 if (unlikely(PageKsm(page)))
6d0a07ed 1568 return false;
ba3c4ce6
HY
1569 count = page_trans_huge_map_swapcount(page, &total_mapcount,
1570 &total_swapcount);
1571 if (total_map_swapcount)
1572 *total_map_swapcount = total_mapcount + total_swapcount;
1573 if (count == 1 && PageSwapCache(page) &&
1574 (likely(!PageTransCompound(page)) ||
1575 /* The remaining swap count will be freed soon */
1576 total_swapcount == page_swapcount(page))) {
f0571429 1577 if (!PageWriteback(page)) {
ba3c4ce6 1578 page = compound_head(page);
7b1fe597
HD
1579 delete_from_swap_cache(page);
1580 SetPageDirty(page);
f0571429
MK
1581 } else {
1582 swp_entry_t entry;
1583 struct swap_info_struct *p;
1584
1585 entry.val = page_private(page);
1586 p = swap_info_get(entry);
1587 if (p->flags & SWP_STABLE_WRITES) {
1588 spin_unlock(&p->lock);
1589 return false;
1590 }
1591 spin_unlock(&p->lock);
7b1fe597
HD
1592 }
1593 }
ba3c4ce6 1594
5ad64688 1595 return count <= 1;
1da177e4
LT
1596}
1597
1598/*
a2c43eed
HD
1599 * If swap is getting full, or if there are no more mappings of this page,
1600 * then try_to_free_swap is called to free its swap space.
1da177e4 1601 */
a2c43eed 1602int try_to_free_swap(struct page *page)
1da177e4 1603{
309381fe 1604 VM_BUG_ON_PAGE(!PageLocked(page), page);
1da177e4
LT
1605
1606 if (!PageSwapCache(page))
1607 return 0;
1608 if (PageWriteback(page))
1609 return 0;
e0709829 1610 if (page_swapped(page))
1da177e4
LT
1611 return 0;
1612
b73d7fce
HD
1613 /*
1614 * Once hibernation has begun to create its image of memory,
1615 * there's a danger that one of the calls to try_to_free_swap()
1616 * - most probably a call from __try_to_reclaim_swap() while
1617 * hibernation is allocating its own swap pages for the image,
1618 * but conceivably even a call from memory reclaim - will free
1619 * the swap from a page which has already been recorded in the
1620 * image as a clean swapcache page, and then reuse its swap for
1621 * another page of the image. On waking from hibernation, the
1622 * original page might be freed under memory pressure, then
1623 * later read back in from swap, now with the wrong data.
1624 *
2de1a7e4 1625 * Hibernation suspends storage while it is writing the image
f90ac398 1626 * to disk so check that here.
b73d7fce 1627 */
f90ac398 1628 if (pm_suspended_storage())
b73d7fce
HD
1629 return 0;
1630
e0709829 1631 page = compound_head(page);
a2c43eed
HD
1632 delete_from_swap_cache(page);
1633 SetPageDirty(page);
1634 return 1;
68a22394
RR
1635}
1636
1da177e4
LT
1637/*
1638 * Free the swap entry like above, but also try to
1639 * free the page cache entry if it is the last user.
1640 */
2509ef26 1641int free_swap_and_cache(swp_entry_t entry)
1da177e4 1642{
2509ef26 1643 struct swap_info_struct *p;
1da177e4 1644 struct page *page = NULL;
7c00bafe 1645 unsigned char count;
1da177e4 1646
a7420aa5 1647 if (non_swap_entry(entry))
2509ef26 1648 return 1;
0697212a 1649
7c00bafe 1650 p = _swap_info_get(entry);
1da177e4 1651 if (p) {
7c00bafe 1652 count = __swap_entry_free(p, entry, 1);
e0709829
HY
1653 if (count == SWAP_HAS_CACHE &&
1654 !swap_page_trans_huge_swapped(p, entry)) {
33806f06 1655 page = find_get_page(swap_address_space(entry),
f6ab1f7f 1656 swp_offset(entry));
8413ac9d 1657 if (page && !trylock_page(page)) {
09cbfeaf 1658 put_page(page);
93fac704
NP
1659 page = NULL;
1660 }
7c00bafe 1661 } else if (!count)
67afa38e 1662 free_swap_slot(entry);
1da177e4
LT
1663 }
1664 if (page) {
a2c43eed
HD
1665 /*
1666 * Not mapped elsewhere, or swap space full? Free it!
1667 * Also recheck PageSwapCache now page is locked (above).
1668 */
93fac704 1669 if (PageSwapCache(page) && !PageWriteback(page) &&
322b8afe 1670 (!page_mapped(page) || mem_cgroup_swap_full(page)) &&
e0709829
HY
1671 !swap_page_trans_huge_swapped(p, entry)) {
1672 page = compound_head(page);
1da177e4
LT
1673 delete_from_swap_cache(page);
1674 SetPageDirty(page);
1675 }
1676 unlock_page(page);
09cbfeaf 1677 put_page(page);
1da177e4 1678 }
2509ef26 1679 return p != NULL;
1da177e4
LT
1680}
1681
b0cb1a19 1682#ifdef CONFIG_HIBERNATION
f577eb30 1683/*
915bae9e 1684 * Find the swap type that corresponds to given device (if any).
f577eb30 1685 *
915bae9e
RW
1686 * @offset - number of the PAGE_SIZE-sized block of the device, starting
1687 * from 0, in which the swap header is expected to be located.
1688 *
1689 * This is needed for the suspend to disk (aka swsusp).
f577eb30 1690 */
7bf23687 1691int swap_type_of(dev_t device, sector_t offset, struct block_device **bdev_p)
f577eb30 1692{
915bae9e 1693 struct block_device *bdev = NULL;
efa90a98 1694 int type;
f577eb30 1695
915bae9e
RW
1696 if (device)
1697 bdev = bdget(device);
1698
f577eb30 1699 spin_lock(&swap_lock);
efa90a98
HD
1700 for (type = 0; type < nr_swapfiles; type++) {
1701 struct swap_info_struct *sis = swap_info[type];
f577eb30 1702
915bae9e 1703 if (!(sis->flags & SWP_WRITEOK))
f577eb30 1704 continue;
b6b5bce3 1705
915bae9e 1706 if (!bdev) {
7bf23687 1707 if (bdev_p)
dddac6a7 1708 *bdev_p = bdgrab(sis->bdev);
7bf23687 1709
6e1819d6 1710 spin_unlock(&swap_lock);
efa90a98 1711 return type;
6e1819d6 1712 }
915bae9e 1713 if (bdev == sis->bdev) {
9625a5f2 1714 struct swap_extent *se = &sis->first_swap_extent;
915bae9e 1715
915bae9e 1716 if (se->start_block == offset) {
7bf23687 1717 if (bdev_p)
dddac6a7 1718 *bdev_p = bdgrab(sis->bdev);
7bf23687 1719
915bae9e
RW
1720 spin_unlock(&swap_lock);
1721 bdput(bdev);
efa90a98 1722 return type;
915bae9e 1723 }
f577eb30
RW
1724 }
1725 }
1726 spin_unlock(&swap_lock);
915bae9e
RW
1727 if (bdev)
1728 bdput(bdev);
1729
f577eb30
RW
1730 return -ENODEV;
1731}
1732
73c34b6a
HD
1733/*
1734 * Get the (PAGE_SIZE) block corresponding to given offset on the swapdev
1735 * corresponding to given index in swap_info (swap type).
1736 */
1737sector_t swapdev_block(int type, pgoff_t offset)
1738{
1739 struct block_device *bdev;
27a34b2d 1740 struct swap_info_struct *si = swap_type_to_swap_info(type);
73c34b6a 1741
27a34b2d 1742 if (!si || !(si->flags & SWP_WRITEOK))
73c34b6a 1743 return 0;
d4906e1a 1744 return map_swap_entry(swp_entry(type, offset), &bdev);
73c34b6a
HD
1745}
1746
f577eb30
RW
1747/*
1748 * Return either the total number of swap pages of given type, or the number
1749 * of free pages of that type (depending on @free)
1750 *
1751 * This is needed for software suspend
1752 */
1753unsigned int count_swap_pages(int type, int free)
1754{
1755 unsigned int n = 0;
1756
efa90a98
HD
1757 spin_lock(&swap_lock);
1758 if ((unsigned int)type < nr_swapfiles) {
1759 struct swap_info_struct *sis = swap_info[type];
1760
ec8acf20 1761 spin_lock(&sis->lock);
efa90a98
HD
1762 if (sis->flags & SWP_WRITEOK) {
1763 n = sis->pages;
f577eb30 1764 if (free)
efa90a98 1765 n -= sis->inuse_pages;
f577eb30 1766 }
ec8acf20 1767 spin_unlock(&sis->lock);
f577eb30 1768 }
efa90a98 1769 spin_unlock(&swap_lock);
f577eb30
RW
1770 return n;
1771}
73c34b6a 1772#endif /* CONFIG_HIBERNATION */
f577eb30 1773
9f8bdb3f 1774static inline int pte_same_as_swp(pte_t pte, pte_t swp_pte)
179ef71c 1775{
9f8bdb3f 1776 return pte_same(pte_swp_clear_soft_dirty(pte), swp_pte);
179ef71c
CG
1777}
1778
1da177e4 1779/*
72866f6f
HD
1780 * No need to decide whether this PTE shares the swap entry with others,
1781 * just let do_wp_page work it out if a write is requested later - to
1782 * force COW, vm_page_prot omits write permission from any private vma.
1da177e4 1783 */
044d66c1 1784static int unuse_pte(struct vm_area_struct *vma, pmd_t *pmd,
1da177e4
LT
1785 unsigned long addr, swp_entry_t entry, struct page *page)
1786{
9e16b7fb 1787 struct page *swapcache;
72835c86 1788 struct mem_cgroup *memcg;
044d66c1
HD
1789 spinlock_t *ptl;
1790 pte_t *pte;
1791 int ret = 1;
1792
9e16b7fb
HD
1793 swapcache = page;
1794 page = ksm_might_need_to_copy(page, vma, addr);
1795 if (unlikely(!page))
1796 return -ENOMEM;
1797
f627c2f5
KS
1798 if (mem_cgroup_try_charge(page, vma->vm_mm, GFP_KERNEL,
1799 &memcg, false)) {
044d66c1 1800 ret = -ENOMEM;
85d9fc89
KH
1801 goto out_nolock;
1802 }
044d66c1
HD
1803
1804 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
9f8bdb3f 1805 if (unlikely(!pte_same_as_swp(*pte, swp_entry_to_pte(entry)))) {
f627c2f5 1806 mem_cgroup_cancel_charge(page, memcg, false);
044d66c1
HD
1807 ret = 0;
1808 goto out;
1809 }
8a9f3ccd 1810
b084d435 1811 dec_mm_counter(vma->vm_mm, MM_SWAPENTS);
d559db08 1812 inc_mm_counter(vma->vm_mm, MM_ANONPAGES);
1da177e4
LT
1813 get_page(page);
1814 set_pte_at(vma->vm_mm, addr, pte,
1815 pte_mkold(mk_pte(page, vma->vm_page_prot)));
00501b53 1816 if (page == swapcache) {
d281ee61 1817 page_add_anon_rmap(page, vma, addr, false);
f627c2f5 1818 mem_cgroup_commit_charge(page, memcg, true, false);
00501b53 1819 } else { /* ksm created a completely new copy */
d281ee61 1820 page_add_new_anon_rmap(page, vma, addr, false);
f627c2f5 1821 mem_cgroup_commit_charge(page, memcg, false, false);
00501b53
JW
1822 lru_cache_add_active_or_unevictable(page, vma);
1823 }
1da177e4
LT
1824 swap_free(entry);
1825 /*
1826 * Move the page to the active list so it is not
1827 * immediately swapped out again after swapon.
1828 */
1829 activate_page(page);
044d66c1
HD
1830out:
1831 pte_unmap_unlock(pte, ptl);
85d9fc89 1832out_nolock:
9e16b7fb
HD
1833 if (page != swapcache) {
1834 unlock_page(page);
1835 put_page(page);
1836 }
044d66c1 1837 return ret;
1da177e4
LT
1838}
1839
1840static int unuse_pte_range(struct vm_area_struct *vma, pmd_t *pmd,
1841 unsigned long addr, unsigned long end,
1842 swp_entry_t entry, struct page *page)
1843{
1da177e4 1844 pte_t swp_pte = swp_entry_to_pte(entry);
705e87c0 1845 pte_t *pte;
8a9f3ccd 1846 int ret = 0;
1da177e4 1847
044d66c1
HD
1848 /*
1849 * We don't actually need pte lock while scanning for swp_pte: since
1850 * we hold page lock and mmap_sem, swp_pte cannot be inserted into the
1851 * page table while we're scanning; though it could get zapped, and on
1852 * some architectures (e.g. x86_32 with PAE) we might catch a glimpse
1853 * of unmatched parts which look like swp_pte, so unuse_pte must
1854 * recheck under pte lock. Scanning without pte lock lets it be
2de1a7e4 1855 * preemptable whenever CONFIG_PREEMPT but not CONFIG_HIGHPTE.
044d66c1
HD
1856 */
1857 pte = pte_offset_map(pmd, addr);
1da177e4
LT
1858 do {
1859 /*
1860 * swapoff spends a _lot_ of time in this loop!
1861 * Test inline before going to call unuse_pte.
1862 */
9f8bdb3f 1863 if (unlikely(pte_same_as_swp(*pte, swp_pte))) {
044d66c1
HD
1864 pte_unmap(pte);
1865 ret = unuse_pte(vma, pmd, addr, entry, page);
1866 if (ret)
1867 goto out;
1868 pte = pte_offset_map(pmd, addr);
1da177e4
LT
1869 }
1870 } while (pte++, addr += PAGE_SIZE, addr != end);
044d66c1
HD
1871 pte_unmap(pte - 1);
1872out:
8a9f3ccd 1873 return ret;
1da177e4
LT
1874}
1875
1876static inline int unuse_pmd_range(struct vm_area_struct *vma, pud_t *pud,
1877 unsigned long addr, unsigned long end,
1878 swp_entry_t entry, struct page *page)
1879{
1880 pmd_t *pmd;
1881 unsigned long next;
8a9f3ccd 1882 int ret;
1da177e4
LT
1883
1884 pmd = pmd_offset(pud, addr);
1885 do {
dc644a07 1886 cond_resched();
1da177e4 1887 next = pmd_addr_end(addr, end);
1a5a9906 1888 if (pmd_none_or_trans_huge_or_clear_bad(pmd))
1da177e4 1889 continue;
8a9f3ccd
BS
1890 ret = unuse_pte_range(vma, pmd, addr, next, entry, page);
1891 if (ret)
1892 return ret;
1da177e4
LT
1893 } while (pmd++, addr = next, addr != end);
1894 return 0;
1895}
1896
c2febafc 1897static inline int unuse_pud_range(struct vm_area_struct *vma, p4d_t *p4d,
1da177e4
LT
1898 unsigned long addr, unsigned long end,
1899 swp_entry_t entry, struct page *page)
1900{
1901 pud_t *pud;
1902 unsigned long next;
8a9f3ccd 1903 int ret;
1da177e4 1904
c2febafc 1905 pud = pud_offset(p4d, addr);
1da177e4
LT
1906 do {
1907 next = pud_addr_end(addr, end);
1908 if (pud_none_or_clear_bad(pud))
1909 continue;
8a9f3ccd
BS
1910 ret = unuse_pmd_range(vma, pud, addr, next, entry, page);
1911 if (ret)
1912 return ret;
1da177e4
LT
1913 } while (pud++, addr = next, addr != end);
1914 return 0;
1915}
1916
c2febafc
KS
1917static inline int unuse_p4d_range(struct vm_area_struct *vma, pgd_t *pgd,
1918 unsigned long addr, unsigned long end,
1919 swp_entry_t entry, struct page *page)
1920{
1921 p4d_t *p4d;
1922 unsigned long next;
1923 int ret;
1924
1925 p4d = p4d_offset(pgd, addr);
1926 do {
1927 next = p4d_addr_end(addr, end);
1928 if (p4d_none_or_clear_bad(p4d))
1929 continue;
1930 ret = unuse_pud_range(vma, p4d, addr, next, entry, page);
1931 if (ret)
1932 return ret;
1933 } while (p4d++, addr = next, addr != end);
1934 return 0;
1935}
1936
1da177e4
LT
1937static int unuse_vma(struct vm_area_struct *vma,
1938 swp_entry_t entry, struct page *page)
1939{
1940 pgd_t *pgd;
1941 unsigned long addr, end, next;
8a9f3ccd 1942 int ret;
1da177e4 1943
3ca7b3c5 1944 if (page_anon_vma(page)) {
1da177e4
LT
1945 addr = page_address_in_vma(page, vma);
1946 if (addr == -EFAULT)
1947 return 0;
1948 else
1949 end = addr + PAGE_SIZE;
1950 } else {
1951 addr = vma->vm_start;
1952 end = vma->vm_end;
1953 }
1954
1955 pgd = pgd_offset(vma->vm_mm, addr);
1956 do {
1957 next = pgd_addr_end(addr, end);
1958 if (pgd_none_or_clear_bad(pgd))
1959 continue;
c2febafc 1960 ret = unuse_p4d_range(vma, pgd, addr, next, entry, page);
8a9f3ccd
BS
1961 if (ret)
1962 return ret;
1da177e4
LT
1963 } while (pgd++, addr = next, addr != end);
1964 return 0;
1965}
1966
1967static int unuse_mm(struct mm_struct *mm,
1968 swp_entry_t entry, struct page *page)
1969{
1970 struct vm_area_struct *vma;
8a9f3ccd 1971 int ret = 0;
1da177e4
LT
1972
1973 if (!down_read_trylock(&mm->mmap_sem)) {
1974 /*
7d03431c
FLVC
1975 * Activate page so shrink_inactive_list is unlikely to unmap
1976 * its ptes while lock is dropped, so swapoff can make progress.
1da177e4 1977 */
c475a8ab 1978 activate_page(page);
1da177e4
LT
1979 unlock_page(page);
1980 down_read(&mm->mmap_sem);
1981 lock_page(page);
1982 }
1da177e4 1983 for (vma = mm->mmap; vma; vma = vma->vm_next) {
8a9f3ccd 1984 if (vma->anon_vma && (ret = unuse_vma(vma, entry, page)))
1da177e4 1985 break;
dc644a07 1986 cond_resched();
1da177e4 1987 }
1da177e4 1988 up_read(&mm->mmap_sem);
8a9f3ccd 1989 return (ret < 0)? ret: 0;
1da177e4
LT
1990}
1991
1992/*
38b5faf4
DM
1993 * Scan swap_map (or frontswap_map if frontswap parameter is true)
1994 * from current position to next entry still in use.
1da177e4
LT
1995 * Recycle to start on reaching the end, returning 0 when empty.
1996 */
6eb396dc 1997static unsigned int find_next_to_unuse(struct swap_info_struct *si,
38b5faf4 1998 unsigned int prev, bool frontswap)
1da177e4 1999{
6eb396dc
HD
2000 unsigned int max = si->max;
2001 unsigned int i = prev;
8d69aaee 2002 unsigned char count;
1da177e4
LT
2003
2004 /*
5d337b91 2005 * No need for swap_lock here: we're just looking
1da177e4
LT
2006 * for whether an entry is in use, not modifying it; false
2007 * hits are okay, and sys_swapoff() has already prevented new
5d337b91 2008 * allocations from this area (while holding swap_lock).
1da177e4
LT
2009 */
2010 for (;;) {
2011 if (++i >= max) {
2012 if (!prev) {
2013 i = 0;
2014 break;
2015 }
2016 /*
2017 * No entries in use at top of swap_map,
2018 * loop back to start and recheck there.
2019 */
2020 max = prev + 1;
2021 prev = 0;
2022 i = 1;
2023 }
4db0c3c2 2024 count = READ_ONCE(si->swap_map[i]);
355cfa73 2025 if (count && swap_count(count) != SWAP_MAP_BAD)
dc644a07
HD
2026 if (!frontswap || frontswap_test(si, i))
2027 break;
2028 if ((i % LATENCY_LIMIT) == 0)
2029 cond_resched();
1da177e4
LT
2030 }
2031 return i;
2032}
2033
2034/*
2035 * We completely avoid races by reading each swap page in advance,
2036 * and then search for the process using it. All the necessary
2037 * page table adjustments can then be made atomically.
38b5faf4
DM
2038 *
2039 * if the boolean frontswap is true, only unuse pages_to_unuse pages;
2040 * pages_to_unuse==0 means all pages; ignored if frontswap is false
1da177e4 2041 */
38b5faf4
DM
2042int try_to_unuse(unsigned int type, bool frontswap,
2043 unsigned long pages_to_unuse)
1da177e4 2044{
efa90a98 2045 struct swap_info_struct *si = swap_info[type];
1da177e4 2046 struct mm_struct *start_mm;
edfe23da
SL
2047 volatile unsigned char *swap_map; /* swap_map is accessed without
2048 * locking. Mark it as volatile
2049 * to prevent compiler doing
2050 * something odd.
2051 */
8d69aaee 2052 unsigned char swcount;
1da177e4
LT
2053 struct page *page;
2054 swp_entry_t entry;
6eb396dc 2055 unsigned int i = 0;
1da177e4 2056 int retval = 0;
1da177e4
LT
2057
2058 /*
2059 * When searching mms for an entry, a good strategy is to
2060 * start at the first mm we freed the previous entry from
2061 * (though actually we don't notice whether we or coincidence
2062 * freed the entry). Initialize this start_mm with a hold.
2063 *
2064 * A simpler strategy would be to start at the last mm we
2065 * freed the previous entry from; but that would take less
2066 * advantage of mmlist ordering, which clusters forked mms
2067 * together, child after parent. If we race with dup_mmap(), we
2068 * prefer to resolve parent before child, lest we miss entries
2069 * duplicated after we scanned child: using last mm would invert
570a335b 2070 * that.
1da177e4
LT
2071 */
2072 start_mm = &init_mm;
3fce371b 2073 mmget(&init_mm);
1da177e4
LT
2074
2075 /*
2076 * Keep on scanning until all entries have gone. Usually,
2077 * one pass through swap_map is enough, but not necessarily:
2078 * there are races when an instance of an entry might be missed.
2079 */
38b5faf4 2080 while ((i = find_next_to_unuse(si, i, frontswap)) != 0) {
1da177e4
LT
2081 if (signal_pending(current)) {
2082 retval = -EINTR;
2083 break;
2084 }
2085
886bb7e9 2086 /*
1da177e4
LT
2087 * Get a page for the entry, using the existing swap
2088 * cache page if there is one. Otherwise, get a clean
886bb7e9 2089 * page and read the swap into it.
1da177e4
LT
2090 */
2091 swap_map = &si->swap_map[i];
2092 entry = swp_entry(type, i);
02098fea 2093 page = read_swap_cache_async(entry,
23955622 2094 GFP_HIGHUSER_MOVABLE, NULL, 0, false);
1da177e4
LT
2095 if (!page) {
2096 /*
2097 * Either swap_duplicate() failed because entry
2098 * has been freed independently, and will not be
2099 * reused since sys_swapoff() already disabled
2100 * allocation from here, or alloc_page() failed.
2101 */
edfe23da
SL
2102 swcount = *swap_map;
2103 /*
2104 * We don't hold lock here, so the swap entry could be
2105 * SWAP_MAP_BAD (when the cluster is discarding).
2106 * Instead of fail out, We can just skip the swap
2107 * entry because swapoff will wait for discarding
2108 * finish anyway.
2109 */
2110 if (!swcount || swcount == SWAP_MAP_BAD)
1da177e4
LT
2111 continue;
2112 retval = -ENOMEM;
2113 break;
2114 }
2115
2116 /*
2117 * Don't hold on to start_mm if it looks like exiting.
2118 */
2119 if (atomic_read(&start_mm->mm_users) == 1) {
2120 mmput(start_mm);
2121 start_mm = &init_mm;
3fce371b 2122 mmget(&init_mm);
1da177e4
LT
2123 }
2124
2125 /*
2126 * Wait for and lock page. When do_swap_page races with
2127 * try_to_unuse, do_swap_page can handle the fault much
2128 * faster than try_to_unuse can locate the entry. This
2129 * apparently redundant "wait_on_page_locked" lets try_to_unuse
2130 * defer to do_swap_page in such a case - in some tests,
2131 * do_swap_page and try_to_unuse repeatedly compete.
2132 */
2133 wait_on_page_locked(page);
2134 wait_on_page_writeback(page);
2135 lock_page(page);
2136 wait_on_page_writeback(page);
2137
2138 /*
2139 * Remove all references to entry.
1da177e4 2140 */
1da177e4 2141 swcount = *swap_map;
aaa46865
HD
2142 if (swap_count(swcount) == SWAP_MAP_SHMEM) {
2143 retval = shmem_unuse(entry, page);
2144 /* page has already been unlocked and released */
2145 if (retval < 0)
2146 break;
2147 continue;
1da177e4 2148 }
aaa46865
HD
2149 if (swap_count(swcount) && start_mm != &init_mm)
2150 retval = unuse_mm(start_mm, entry, page);
2151
355cfa73 2152 if (swap_count(*swap_map)) {
1da177e4
LT
2153 int set_start_mm = (*swap_map >= swcount);
2154 struct list_head *p = &start_mm->mmlist;
2155 struct mm_struct *new_start_mm = start_mm;
2156 struct mm_struct *prev_mm = start_mm;
2157 struct mm_struct *mm;
2158
3fce371b
VN
2159 mmget(new_start_mm);
2160 mmget(prev_mm);
1da177e4 2161 spin_lock(&mmlist_lock);
aaa46865 2162 while (swap_count(*swap_map) && !retval &&
1da177e4
LT
2163 (p = p->next) != &start_mm->mmlist) {
2164 mm = list_entry(p, struct mm_struct, mmlist);
388f7934 2165 if (!mmget_not_zero(mm))
1da177e4 2166 continue;
1da177e4
LT
2167 spin_unlock(&mmlist_lock);
2168 mmput(prev_mm);
2169 prev_mm = mm;
2170
2171 cond_resched();
2172
2173 swcount = *swap_map;
355cfa73 2174 if (!swap_count(swcount)) /* any usage ? */
1da177e4 2175 ;
aaa46865 2176 else if (mm == &init_mm)
1da177e4 2177 set_start_mm = 1;
aaa46865 2178 else
1da177e4 2179 retval = unuse_mm(mm, entry, page);
355cfa73 2180
32c5fc10 2181 if (set_start_mm && *swap_map < swcount) {
1da177e4 2182 mmput(new_start_mm);
3fce371b 2183 mmget(mm);
1da177e4
LT
2184 new_start_mm = mm;
2185 set_start_mm = 0;
2186 }
2187 spin_lock(&mmlist_lock);
2188 }
2189 spin_unlock(&mmlist_lock);
2190 mmput(prev_mm);
2191 mmput(start_mm);
2192 start_mm = new_start_mm;
2193 }
2194 if (retval) {
2195 unlock_page(page);
09cbfeaf 2196 put_page(page);
1da177e4
LT
2197 break;
2198 }
2199
1da177e4
LT
2200 /*
2201 * If a reference remains (rare), we would like to leave
2202 * the page in the swap cache; but try_to_unmap could
2203 * then re-duplicate the entry once we drop page lock,
2204 * so we might loop indefinitely; also, that page could
2205 * not be swapped out to other storage meanwhile. So:
2206 * delete from cache even if there's another reference,
2207 * after ensuring that the data has been saved to disk -
2208 * since if the reference remains (rarer), it will be
2209 * read from disk into another page. Splitting into two
2210 * pages would be incorrect if swap supported "shared
2211 * private" pages, but they are handled by tmpfs files.
5ad64688
HD
2212 *
2213 * Given how unuse_vma() targets one particular offset
2214 * in an anon_vma, once the anon_vma has been determined,
2215 * this splitting happens to be just what is needed to
2216 * handle where KSM pages have been swapped out: re-reading
2217 * is unnecessarily slow, but we can fix that later on.
1da177e4 2218 */
355cfa73
KH
2219 if (swap_count(*swap_map) &&
2220 PageDirty(page) && PageSwapCache(page)) {
1da177e4
LT
2221 struct writeback_control wbc = {
2222 .sync_mode = WB_SYNC_NONE,
2223 };
2224
e0709829 2225 swap_writepage(compound_head(page), &wbc);
1da177e4
LT
2226 lock_page(page);
2227 wait_on_page_writeback(page);
2228 }
68bdc8d6
HD
2229
2230 /*
2231 * It is conceivable that a racing task removed this page from
2232 * swap cache just before we acquired the page lock at the top,
2233 * or while we dropped it in unuse_mm(). The page might even
2234 * be back in swap cache on another swap area: that we must not
2235 * delete, since it may not have been written out to swap yet.
2236 */
2237 if (PageSwapCache(page) &&
e0709829 2238 likely(page_private(page) == entry.val) &&
e25b4242
HY
2239 (!PageTransCompound(page) ||
2240 !swap_page_trans_huge_swapped(si, entry)))
e0709829 2241 delete_from_swap_cache(compound_head(page));
1da177e4
LT
2242
2243 /*
2244 * So we could skip searching mms once swap count went
2245 * to 1, we did not mark any present ptes as dirty: must
2706a1b8 2246 * mark page dirty so shrink_page_list will preserve it.
1da177e4
LT
2247 */
2248 SetPageDirty(page);
2249 unlock_page(page);
09cbfeaf 2250 put_page(page);
1da177e4
LT
2251
2252 /*
2253 * Make sure that we aren't completely killing
2254 * interactive performance.
2255 */
2256 cond_resched();
38b5faf4
DM
2257 if (frontswap && pages_to_unuse > 0) {
2258 if (!--pages_to_unuse)
2259 break;
2260 }
1da177e4
LT
2261 }
2262
2263 mmput(start_mm);
1da177e4
LT
2264 return retval;
2265}
2266
2267/*
5d337b91
HD
2268 * After a successful try_to_unuse, if no swap is now in use, we know
2269 * we can empty the mmlist. swap_lock must be held on entry and exit.
2270 * Note that mmlist_lock nests inside swap_lock, and an mm must be
1da177e4
LT
2271 * added to the mmlist just after page_duplicate - before would be racy.
2272 */
2273static void drain_mmlist(void)
2274{
2275 struct list_head *p, *next;
efa90a98 2276 unsigned int type;
1da177e4 2277
efa90a98
HD
2278 for (type = 0; type < nr_swapfiles; type++)
2279 if (swap_info[type]->inuse_pages)
1da177e4
LT
2280 return;
2281 spin_lock(&mmlist_lock);
2282 list_for_each_safe(p, next, &init_mm.mmlist)
2283 list_del_init(p);
2284 spin_unlock(&mmlist_lock);
2285}
2286
2287/*
2288 * Use this swapdev's extent info to locate the (PAGE_SIZE) block which
d4906e1a
LS
2289 * corresponds to page offset for the specified swap entry.
2290 * Note that the type of this function is sector_t, but it returns page offset
2291 * into the bdev, not sector offset.
1da177e4 2292 */
d4906e1a 2293static sector_t map_swap_entry(swp_entry_t entry, struct block_device **bdev)
1da177e4 2294{
f29ad6a9
HD
2295 struct swap_info_struct *sis;
2296 struct swap_extent *start_se;
2297 struct swap_extent *se;
2298 pgoff_t offset;
2299
27a34b2d 2300 sis = swp_swap_info(entry);
f29ad6a9
HD
2301 *bdev = sis->bdev;
2302
2303 offset = swp_offset(entry);
2304 start_se = sis->curr_swap_extent;
2305 se = start_se;
1da177e4
LT
2306
2307 for ( ; ; ) {
1da177e4
LT
2308 if (se->start_page <= offset &&
2309 offset < (se->start_page + se->nr_pages)) {
2310 return se->start_block + (offset - se->start_page);
2311 }
a8ae4991 2312 se = list_next_entry(se, list);
1da177e4
LT
2313 sis->curr_swap_extent = se;
2314 BUG_ON(se == start_se); /* It *must* be present */
2315 }
2316}
2317
d4906e1a
LS
2318/*
2319 * Returns the page offset into bdev for the specified page's swap entry.
2320 */
2321sector_t map_swap_page(struct page *page, struct block_device **bdev)
2322{
2323 swp_entry_t entry;
2324 entry.val = page_private(page);
2325 return map_swap_entry(entry, bdev);
2326}
2327
1da177e4
LT
2328/*
2329 * Free all of a swapdev's extent information
2330 */
2331static void destroy_swap_extents(struct swap_info_struct *sis)
2332{
9625a5f2 2333 while (!list_empty(&sis->first_swap_extent.list)) {
1da177e4
LT
2334 struct swap_extent *se;
2335
a8ae4991 2336 se = list_first_entry(&sis->first_swap_extent.list,
1da177e4
LT
2337 struct swap_extent, list);
2338 list_del(&se->list);
2339 kfree(se);
2340 }
62c230bc
MG
2341
2342 if (sis->flags & SWP_FILE) {
2343 struct file *swap_file = sis->swap_file;
2344 struct address_space *mapping = swap_file->f_mapping;
2345
2346 sis->flags &= ~SWP_FILE;
2347 mapping->a_ops->swap_deactivate(swap_file);
2348 }
1da177e4
LT
2349}
2350
2351/*
2352 * Add a block range (and the corresponding page range) into this swapdev's
11d31886 2353 * extent list. The extent list is kept sorted in page order.
1da177e4 2354 *
11d31886 2355 * This function rather assumes that it is called in ascending page order.
1da177e4 2356 */
a509bc1a 2357int
1da177e4
LT
2358add_swap_extent(struct swap_info_struct *sis, unsigned long start_page,
2359 unsigned long nr_pages, sector_t start_block)
2360{
2361 struct swap_extent *se;
2362 struct swap_extent *new_se;
2363 struct list_head *lh;
2364
9625a5f2
HD
2365 if (start_page == 0) {
2366 se = &sis->first_swap_extent;
2367 sis->curr_swap_extent = se;
2368 se->start_page = 0;
2369 se->nr_pages = nr_pages;
2370 se->start_block = start_block;
2371 return 1;
2372 } else {
2373 lh = sis->first_swap_extent.list.prev; /* Highest extent */
1da177e4 2374 se = list_entry(lh, struct swap_extent, list);
11d31886
HD
2375 BUG_ON(se->start_page + se->nr_pages != start_page);
2376 if (se->start_block + se->nr_pages == start_block) {
1da177e4
LT
2377 /* Merge it */
2378 se->nr_pages += nr_pages;
2379 return 0;
2380 }
1da177e4
LT
2381 }
2382
2383 /*
2384 * No merge. Insert a new extent, preserving ordering.
2385 */
2386 new_se = kmalloc(sizeof(*se), GFP_KERNEL);
2387 if (new_se == NULL)
2388 return -ENOMEM;
2389 new_se->start_page = start_page;
2390 new_se->nr_pages = nr_pages;
2391 new_se->start_block = start_block;
2392
9625a5f2 2393 list_add_tail(&new_se->list, &sis->first_swap_extent.list);
53092a74 2394 return 1;
1da177e4
LT
2395}
2396
2397/*
2398 * A `swap extent' is a simple thing which maps a contiguous range of pages
2399 * onto a contiguous range of disk blocks. An ordered list of swap extents
2400 * is built at swapon time and is then used at swap_writepage/swap_readpage
2401 * time for locating where on disk a page belongs.
2402 *
2403 * If the swapfile is an S_ISBLK block device, a single extent is installed.
2404 * This is done so that the main operating code can treat S_ISBLK and S_ISREG
2405 * swap files identically.
2406 *
2407 * Whether the swapdev is an S_ISREG file or an S_ISBLK blockdev, the swap
2408 * extent list operates in PAGE_SIZE disk blocks. Both S_ISREG and S_ISBLK
2409 * swapfiles are handled *identically* after swapon time.
2410 *
2411 * For S_ISREG swapfiles, setup_swap_extents() will walk all the file's blocks
2412 * and will parse them into an ordered extent list, in PAGE_SIZE chunks. If
2413 * some stray blocks are found which do not fall within the PAGE_SIZE alignment
2414 * requirements, they are simply tossed out - we will never use those blocks
2415 * for swapping.
2416 *
b0d9bcd4 2417 * For S_ISREG swapfiles we set S_SWAPFILE across the life of the swapon. This
1da177e4
LT
2418 * prevents root from shooting her foot off by ftruncating an in-use swapfile,
2419 * which will scribble on the fs.
2420 *
2421 * The amount of disk space which a single swap extent represents varies.
2422 * Typically it is in the 1-4 megabyte range. So we can have hundreds of
2423 * extents in the list. To avoid much list walking, we cache the previous
2424 * search location in `curr_swap_extent', and start new searches from there.
2425 * This is extremely effective. The average number of iterations in
2426 * map_swap_page() has been measured at about 0.3 per page. - akpm.
2427 */
53092a74 2428static int setup_swap_extents(struct swap_info_struct *sis, sector_t *span)
1da177e4 2429{
62c230bc
MG
2430 struct file *swap_file = sis->swap_file;
2431 struct address_space *mapping = swap_file->f_mapping;
2432 struct inode *inode = mapping->host;
1da177e4
LT
2433 int ret;
2434
1da177e4
LT
2435 if (S_ISBLK(inode->i_mode)) {
2436 ret = add_swap_extent(sis, 0, sis->max, 0);
53092a74 2437 *span = sis->pages;
a509bc1a 2438 return ret;
1da177e4
LT
2439 }
2440
62c230bc 2441 if (mapping->a_ops->swap_activate) {
a509bc1a 2442 ret = mapping->a_ops->swap_activate(sis, swap_file, span);
62c230bc
MG
2443 if (!ret) {
2444 sis->flags |= SWP_FILE;
2445 ret = add_swap_extent(sis, 0, sis->max, 0);
2446 *span = sis->pages;
2447 }
a509bc1a 2448 return ret;
62c230bc
MG
2449 }
2450
a509bc1a 2451 return generic_swapfile_activate(sis, swap_file, span);
1da177e4
LT
2452}
2453
a2468cc9
AL
2454static int swap_node(struct swap_info_struct *p)
2455{
2456 struct block_device *bdev;
2457
2458 if (p->bdev)
2459 bdev = p->bdev;
2460 else
2461 bdev = p->swap_file->f_inode->i_sb->s_bdev;
2462
2463 return bdev ? bdev->bd_disk->node_id : NUMA_NO_NODE;
2464}
2465
cf0cac0a 2466static void _enable_swap_info(struct swap_info_struct *p, int prio,
2a8f9449
SL
2467 unsigned char *swap_map,
2468 struct swap_cluster_info *cluster_info)
40531542 2469{
a2468cc9
AL
2470 int i;
2471
40531542
CEB
2472 if (prio >= 0)
2473 p->prio = prio;
2474 else
2475 p->prio = --least_priority;
18ab4d4c
DS
2476 /*
2477 * the plist prio is negated because plist ordering is
2478 * low-to-high, while swap ordering is high-to-low
2479 */
2480 p->list.prio = -p->prio;
a2468cc9
AL
2481 for_each_node(i) {
2482 if (p->prio >= 0)
2483 p->avail_lists[i].prio = -p->prio;
2484 else {
2485 if (swap_node(p) == i)
2486 p->avail_lists[i].prio = 1;
2487 else
2488 p->avail_lists[i].prio = -p->prio;
2489 }
2490 }
40531542 2491 p->swap_map = swap_map;
2a8f9449 2492 p->cluster_info = cluster_info;
40531542 2493 p->flags |= SWP_WRITEOK;
ec8acf20 2494 atomic_long_add(p->pages, &nr_swap_pages);
40531542
CEB
2495 total_swap_pages += p->pages;
2496
adfab836 2497 assert_spin_locked(&swap_lock);
adfab836 2498 /*
18ab4d4c
DS
2499 * both lists are plists, and thus priority ordered.
2500 * swap_active_head needs to be priority ordered for swapoff(),
2501 * which on removal of any swap_info_struct with an auto-assigned
2502 * (i.e. negative) priority increments the auto-assigned priority
2503 * of any lower-priority swap_info_structs.
2504 * swap_avail_head needs to be priority ordered for get_swap_page(),
2505 * which allocates swap pages from the highest available priority
2506 * swap_info_struct.
adfab836 2507 */
18ab4d4c 2508 plist_add(&p->list, &swap_active_head);
a2468cc9 2509 add_to_avail_list(p);
cf0cac0a
CEB
2510}
2511
2512static void enable_swap_info(struct swap_info_struct *p, int prio,
2513 unsigned char *swap_map,
2a8f9449 2514 struct swap_cluster_info *cluster_info,
cf0cac0a
CEB
2515 unsigned long *frontswap_map)
2516{
4f89849d 2517 frontswap_init(p->type, frontswap_map);
cf0cac0a 2518 spin_lock(&swap_lock);
ec8acf20 2519 spin_lock(&p->lock);
2a8f9449 2520 _enable_swap_info(p, prio, swap_map, cluster_info);
ec8acf20 2521 spin_unlock(&p->lock);
cf0cac0a
CEB
2522 spin_unlock(&swap_lock);
2523}
2524
2525static void reinsert_swap_info(struct swap_info_struct *p)
2526{
2527 spin_lock(&swap_lock);
ec8acf20 2528 spin_lock(&p->lock);
2a8f9449 2529 _enable_swap_info(p, p->prio, p->swap_map, p->cluster_info);
ec8acf20 2530 spin_unlock(&p->lock);
40531542
CEB
2531 spin_unlock(&swap_lock);
2532}
2533
67afa38e
TC
2534bool has_usable_swap(void)
2535{
2536 bool ret = true;
2537
2538 spin_lock(&swap_lock);
2539 if (plist_head_empty(&swap_active_head))
2540 ret = false;
2541 spin_unlock(&swap_lock);
2542 return ret;
2543}
2544
c4ea37c2 2545SYSCALL_DEFINE1(swapoff, const char __user *, specialfile)
1da177e4 2546{
73c34b6a 2547 struct swap_info_struct *p = NULL;
8d69aaee 2548 unsigned char *swap_map;
2a8f9449 2549 struct swap_cluster_info *cluster_info;
4f89849d 2550 unsigned long *frontswap_map;
1da177e4
LT
2551 struct file *swap_file, *victim;
2552 struct address_space *mapping;
2553 struct inode *inode;
91a27b2a 2554 struct filename *pathname;
adfab836 2555 int err, found = 0;
5b808a23 2556 unsigned int old_block_size;
886bb7e9 2557
1da177e4
LT
2558 if (!capable(CAP_SYS_ADMIN))
2559 return -EPERM;
2560
191c5424
AV
2561 BUG_ON(!current->mm);
2562
1da177e4 2563 pathname = getname(specialfile);
1da177e4 2564 if (IS_ERR(pathname))
f58b59c1 2565 return PTR_ERR(pathname);
1da177e4 2566
669abf4e 2567 victim = file_open_name(pathname, O_RDWR|O_LARGEFILE, 0);
1da177e4
LT
2568 err = PTR_ERR(victim);
2569 if (IS_ERR(victim))
2570 goto out;
2571
2572 mapping = victim->f_mapping;
5d337b91 2573 spin_lock(&swap_lock);
18ab4d4c 2574 plist_for_each_entry(p, &swap_active_head, list) {
22c6f8fd 2575 if (p->flags & SWP_WRITEOK) {
adfab836
DS
2576 if (p->swap_file->f_mapping == mapping) {
2577 found = 1;
1da177e4 2578 break;
adfab836 2579 }
1da177e4 2580 }
1da177e4 2581 }
adfab836 2582 if (!found) {
1da177e4 2583 err = -EINVAL;
5d337b91 2584 spin_unlock(&swap_lock);
1da177e4
LT
2585 goto out_dput;
2586 }
191c5424 2587 if (!security_vm_enough_memory_mm(current->mm, p->pages))
1da177e4
LT
2588 vm_unacct_memory(p->pages);
2589 else {
2590 err = -ENOMEM;
5d337b91 2591 spin_unlock(&swap_lock);
1da177e4
LT
2592 goto out_dput;
2593 }
a2468cc9 2594 del_from_avail_list(p);
ec8acf20 2595 spin_lock(&p->lock);
78ecba08 2596 if (p->prio < 0) {
adfab836 2597 struct swap_info_struct *si = p;
a2468cc9 2598 int nid;
adfab836 2599
18ab4d4c 2600 plist_for_each_entry_continue(si, &swap_active_head, list) {
adfab836 2601 si->prio++;
18ab4d4c 2602 si->list.prio--;
a2468cc9
AL
2603 for_each_node(nid) {
2604 if (si->avail_lists[nid].prio != 1)
2605 si->avail_lists[nid].prio--;
2606 }
adfab836 2607 }
78ecba08
HD
2608 least_priority++;
2609 }
18ab4d4c 2610 plist_del(&p->list, &swap_active_head);
ec8acf20 2611 atomic_long_sub(p->pages, &nr_swap_pages);
1da177e4
LT
2612 total_swap_pages -= p->pages;
2613 p->flags &= ~SWP_WRITEOK;
ec8acf20 2614 spin_unlock(&p->lock);
5d337b91 2615 spin_unlock(&swap_lock);
fb4f88dc 2616
039939a6
TC
2617 disable_swap_slots_cache_lock();
2618
e1e12d2f 2619 set_current_oom_origin();
adfab836 2620 err = try_to_unuse(p->type, false, 0); /* force unuse all pages */
e1e12d2f 2621 clear_current_oom_origin();
1da177e4 2622
1da177e4
LT
2623 if (err) {
2624 /* re-insert swap space back into swap_list */
cf0cac0a 2625 reinsert_swap_info(p);
039939a6 2626 reenable_swap_slots_cache_unlock();
1da177e4
LT
2627 goto out_dput;
2628 }
52b7efdb 2629
039939a6
TC
2630 reenable_swap_slots_cache_unlock();
2631
815c2c54
SL
2632 flush_work(&p->discard_work);
2633
5d337b91 2634 destroy_swap_extents(p);
570a335b
HD
2635 if (p->flags & SWP_CONTINUED)
2636 free_swap_count_continuations(p);
2637
81a0298b
HY
2638 if (!p->bdev || !blk_queue_nonrot(bdev_get_queue(p->bdev)))
2639 atomic_dec(&nr_rotate_swap);
2640
fc0abb14 2641 mutex_lock(&swapon_mutex);
5d337b91 2642 spin_lock(&swap_lock);
ec8acf20 2643 spin_lock(&p->lock);
5d337b91
HD
2644 drain_mmlist();
2645
52b7efdb 2646 /* wait for anyone still in scan_swap_map */
52b7efdb
HD
2647 p->highest_bit = 0; /* cuts scans short */
2648 while (p->flags >= SWP_SCANNING) {
ec8acf20 2649 spin_unlock(&p->lock);
5d337b91 2650 spin_unlock(&swap_lock);
13e4b57f 2651 schedule_timeout_uninterruptible(1);
5d337b91 2652 spin_lock(&swap_lock);
ec8acf20 2653 spin_lock(&p->lock);
52b7efdb 2654 }
52b7efdb 2655
1da177e4 2656 swap_file = p->swap_file;
5b808a23 2657 old_block_size = p->old_block_size;
1da177e4
LT
2658 p->swap_file = NULL;
2659 p->max = 0;
2660 swap_map = p->swap_map;
2661 p->swap_map = NULL;
2a8f9449
SL
2662 cluster_info = p->cluster_info;
2663 p->cluster_info = NULL;
4f89849d 2664 frontswap_map = frontswap_map_get(p);
ec8acf20 2665 spin_unlock(&p->lock);
5d337b91 2666 spin_unlock(&swap_lock);
adfab836 2667 frontswap_invalidate_area(p->type);
58e97ba6 2668 frontswap_map_set(p, NULL);
fc0abb14 2669 mutex_unlock(&swapon_mutex);
ebc2a1a6
SL
2670 free_percpu(p->percpu_cluster);
2671 p->percpu_cluster = NULL;
1da177e4 2672 vfree(swap_map);
54f180d3
HY
2673 kvfree(cluster_info);
2674 kvfree(frontswap_map);
2de1a7e4 2675 /* Destroy swap account information */
adfab836 2676 swap_cgroup_swapoff(p->type);
4b3ef9da 2677 exit_swap_address_space(p->type);
27a7faa0 2678
1da177e4
LT
2679 inode = mapping->host;
2680 if (S_ISBLK(inode->i_mode)) {
2681 struct block_device *bdev = I_BDEV(inode);
5b808a23 2682 set_blocksize(bdev, old_block_size);
e525fd89 2683 blkdev_put(bdev, FMODE_READ | FMODE_WRITE | FMODE_EXCL);
1da177e4 2684 } else {
5955102c 2685 inode_lock(inode);
1da177e4 2686 inode->i_flags &= ~S_SWAPFILE;
5955102c 2687 inode_unlock(inode);
1da177e4
LT
2688 }
2689 filp_close(swap_file, NULL);
f893ab41
WY
2690
2691 /*
2692 * Clear the SWP_USED flag after all resources are freed so that swapon
2693 * can reuse this swap_info in alloc_swap_info() safely. It is ok to
2694 * not hold p->lock after we cleared its SWP_WRITEOK.
2695 */
2696 spin_lock(&swap_lock);
2697 p->flags = 0;
2698 spin_unlock(&swap_lock);
2699
1da177e4 2700 err = 0;
66d7dd51
KS
2701 atomic_inc(&proc_poll_event);
2702 wake_up_interruptible(&proc_poll_wait);
1da177e4
LT
2703
2704out_dput:
2705 filp_close(victim, NULL);
2706out:
f58b59c1 2707 putname(pathname);
1da177e4
LT
2708 return err;
2709}
2710
2711#ifdef CONFIG_PROC_FS
66d7dd51
KS
2712static unsigned swaps_poll(struct file *file, poll_table *wait)
2713{
f1514638 2714 struct seq_file *seq = file->private_data;
66d7dd51
KS
2715
2716 poll_wait(file, &proc_poll_wait, wait);
2717
f1514638
KS
2718 if (seq->poll_event != atomic_read(&proc_poll_event)) {
2719 seq->poll_event = atomic_read(&proc_poll_event);
66d7dd51
KS
2720 return POLLIN | POLLRDNORM | POLLERR | POLLPRI;
2721 }
2722
2723 return POLLIN | POLLRDNORM;
2724}
2725
1da177e4
LT
2726/* iterator */
2727static void *swap_start(struct seq_file *swap, loff_t *pos)
2728{
efa90a98
HD
2729 struct swap_info_struct *si;
2730 int type;
1da177e4
LT
2731 loff_t l = *pos;
2732
fc0abb14 2733 mutex_lock(&swapon_mutex);
1da177e4 2734
881e4aab
SS
2735 if (!l)
2736 return SEQ_START_TOKEN;
2737
27a34b2d 2738 for (type = 0; (si = swap_type_to_swap_info(type)); type++) {
efa90a98 2739 if (!(si->flags & SWP_USED) || !si->swap_map)
1da177e4 2740 continue;
881e4aab 2741 if (!--l)
efa90a98 2742 return si;
1da177e4
LT
2743 }
2744
2745 return NULL;
2746}
2747
2748static void *swap_next(struct seq_file *swap, void *v, loff_t *pos)
2749{
efa90a98
HD
2750 struct swap_info_struct *si = v;
2751 int type;
1da177e4 2752
881e4aab 2753 if (v == SEQ_START_TOKEN)
efa90a98
HD
2754 type = 0;
2755 else
2756 type = si->type + 1;
881e4aab 2757
27a34b2d 2758 for (; (si = swap_type_to_swap_info(type)); type++) {
efa90a98 2759 if (!(si->flags & SWP_USED) || !si->swap_map)
1da177e4
LT
2760 continue;
2761 ++*pos;
efa90a98 2762 return si;
1da177e4
LT
2763 }
2764
2765 return NULL;
2766}
2767
2768static void swap_stop(struct seq_file *swap, void *v)
2769{
fc0abb14 2770 mutex_unlock(&swapon_mutex);
1da177e4
LT
2771}
2772
2773static int swap_show(struct seq_file *swap, void *v)
2774{
efa90a98 2775 struct swap_info_struct *si = v;
1da177e4
LT
2776 struct file *file;
2777 int len;
2778
efa90a98 2779 if (si == SEQ_START_TOKEN) {
881e4aab
SS
2780 seq_puts(swap,"Filename\t\t\t\tType\t\tSize\tUsed\tPriority\n");
2781 return 0;
2782 }
1da177e4 2783
efa90a98 2784 file = si->swap_file;
2726d566 2785 len = seq_file_path(swap, file, " \t\n\\");
6eb396dc 2786 seq_printf(swap, "%*s%s\t%u\t%u\t%d\n",
886bb7e9 2787 len < 40 ? 40 - len : 1, " ",
496ad9aa 2788 S_ISBLK(file_inode(file)->i_mode) ?
1da177e4 2789 "partition" : "file\t",
efa90a98
HD
2790 si->pages << (PAGE_SHIFT - 10),
2791 si->inuse_pages << (PAGE_SHIFT - 10),
2792 si->prio);
1da177e4
LT
2793 return 0;
2794}
2795
15ad7cdc 2796static const struct seq_operations swaps_op = {
1da177e4
LT
2797 .start = swap_start,
2798 .next = swap_next,
2799 .stop = swap_stop,
2800 .show = swap_show
2801};
2802
2803static int swaps_open(struct inode *inode, struct file *file)
2804{
f1514638 2805 struct seq_file *seq;
66d7dd51
KS
2806 int ret;
2807
66d7dd51 2808 ret = seq_open(file, &swaps_op);
f1514638 2809 if (ret)
66d7dd51 2810 return ret;
66d7dd51 2811
f1514638
KS
2812 seq = file->private_data;
2813 seq->poll_event = atomic_read(&proc_poll_event);
2814 return 0;
1da177e4
LT
2815}
2816
15ad7cdc 2817static const struct file_operations proc_swaps_operations = {
1da177e4
LT
2818 .open = swaps_open,
2819 .read = seq_read,
2820 .llseek = seq_lseek,
2821 .release = seq_release,
66d7dd51 2822 .poll = swaps_poll,
1da177e4
LT
2823};
2824
2825static int __init procswaps_init(void)
2826{
3d71f86f 2827 proc_create("swaps", 0, NULL, &proc_swaps_operations);
1da177e4
LT
2828 return 0;
2829}
2830__initcall(procswaps_init);
2831#endif /* CONFIG_PROC_FS */
2832
1796316a
JB
2833#ifdef MAX_SWAPFILES_CHECK
2834static int __init max_swapfiles_check(void)
2835{
2836 MAX_SWAPFILES_CHECK();
2837 return 0;
2838}
2839late_initcall(max_swapfiles_check);
2840#endif
2841
53cbb243 2842static struct swap_info_struct *alloc_swap_info(void)
1da177e4 2843{
73c34b6a 2844 struct swap_info_struct *p;
1da177e4 2845 unsigned int type;
a2468cc9 2846 int i;
92ee8bd3 2847 int size = sizeof(*p) + nr_node_ids * sizeof(struct plist_node);
efa90a98 2848
92ee8bd3 2849 p = kvzalloc(size, GFP_KERNEL);
efa90a98 2850 if (!p)
53cbb243 2851 return ERR_PTR(-ENOMEM);
efa90a98 2852
5d337b91 2853 spin_lock(&swap_lock);
efa90a98
HD
2854 for (type = 0; type < nr_swapfiles; type++) {
2855 if (!(swap_info[type]->flags & SWP_USED))
1da177e4 2856 break;
efa90a98 2857 }
0697212a 2858 if (type >= MAX_SWAPFILES) {
5d337b91 2859 spin_unlock(&swap_lock);
040e1b9f 2860 kvfree(p);
730c0581 2861 return ERR_PTR(-EPERM);
1da177e4 2862 }
efa90a98
HD
2863 if (type >= nr_swapfiles) {
2864 p->type = type;
27a34b2d 2865 WRITE_ONCE(swap_info[type], p);
efa90a98
HD
2866 /*
2867 * Write swap_info[type] before nr_swapfiles, in case a
2868 * racing procfs swap_start() or swap_next() is reading them.
2869 * (We never shrink nr_swapfiles, we never free this entry.)
2870 */
2871 smp_wmb();
27a34b2d 2872 WRITE_ONCE(nr_swapfiles, nr_swapfiles + 1);
efa90a98 2873 } else {
040e1b9f 2874 kvfree(p);
efa90a98
HD
2875 p = swap_info[type];
2876 /*
2877 * Do not memset this entry: a racing procfs swap_next()
2878 * would be relying on p->type to remain valid.
2879 */
2880 }
9625a5f2 2881 INIT_LIST_HEAD(&p->first_swap_extent.list);
18ab4d4c 2882 plist_node_init(&p->list, 0);
a2468cc9
AL
2883 for_each_node(i)
2884 plist_node_init(&p->avail_lists[i], 0);
1da177e4 2885 p->flags = SWP_USED;
5d337b91 2886 spin_unlock(&swap_lock);
ec8acf20 2887 spin_lock_init(&p->lock);
2628bd6f 2888 spin_lock_init(&p->cont_lock);
efa90a98 2889
53cbb243 2890 return p;
53cbb243
CEB
2891}
2892
4d0e1e10
CEB
2893static int claim_swapfile(struct swap_info_struct *p, struct inode *inode)
2894{
2895 int error;
2896
2897 if (S_ISBLK(inode->i_mode)) {
2898 p->bdev = bdgrab(I_BDEV(inode));
2899 error = blkdev_get(p->bdev,
6f179af8 2900 FMODE_READ | FMODE_WRITE | FMODE_EXCL, p);
4d0e1e10
CEB
2901 if (error < 0) {
2902 p->bdev = NULL;
6f179af8 2903 return error;
4d0e1e10
CEB
2904 }
2905 p->old_block_size = block_size(p->bdev);
2906 error = set_blocksize(p->bdev, PAGE_SIZE);
2907 if (error < 0)
87ade72a 2908 return error;
4d0e1e10
CEB
2909 p->flags |= SWP_BLKDEV;
2910 } else if (S_ISREG(inode->i_mode)) {
2911 p->bdev = inode->i_sb->s_bdev;
5955102c 2912 inode_lock(inode);
87ade72a
CEB
2913 if (IS_SWAPFILE(inode))
2914 return -EBUSY;
2915 } else
2916 return -EINVAL;
4d0e1e10
CEB
2917
2918 return 0;
4d0e1e10
CEB
2919}
2920
a98c27e1
AK
2921
2922/*
2923 * Find out how many pages are allowed for a single swap device. There
2924 * are two limiting factors:
2925 * 1) the number of bits for the swap offset in the swp_entry_t type, and
2926 * 2) the number of bits in the swap pte, as defined by the different
2927 * architectures.
2928 *
2929 * In order to find the largest possible bit mask, a swap entry with
2930 * swap type 0 and swap offset ~0UL is created, encoded to a swap pte,
2931 * decoded to a swp_entry_t again, and finally the swap offset is
2932 * extracted.
2933 *
2934 * This will mask all the bits from the initial ~0UL mask that can't
2935 * be encoded in either the swp_entry_t or the architecture definition
2936 * of a swap pte.
2937 */
2938unsigned long generic_max_swapfile_size(void)
2939{
2940 return swp_offset(pte_to_swp_entry(
2941 swp_entry_to_pte(swp_entry(0, ~0UL)))) + 1;
2942}
2943
2944/* Can be overridden by an architecture for additional checks. */
2945__weak unsigned long max_swapfile_size(void)
2946{
2947 return generic_max_swapfile_size();
2948}
2949
ca8bd38b
CEB
2950static unsigned long read_swap_header(struct swap_info_struct *p,
2951 union swap_header *swap_header,
2952 struct inode *inode)
2953{
2954 int i;
2955 unsigned long maxpages;
2956 unsigned long swapfilepages;
d6bbbd29 2957 unsigned long last_page;
ca8bd38b
CEB
2958
2959 if (memcmp("SWAPSPACE2", swap_header->magic.magic, 10)) {
465c47fd 2960 pr_err("Unable to find swap-space signature\n");
38719025 2961 return 0;
ca8bd38b
CEB
2962 }
2963
2964 /* swap partition endianess hack... */
2965 if (swab32(swap_header->info.version) == 1) {
2966 swab32s(&swap_header->info.version);
2967 swab32s(&swap_header->info.last_page);
2968 swab32s(&swap_header->info.nr_badpages);
dd111be6
JH
2969 if (swap_header->info.nr_badpages > MAX_SWAP_BADPAGES)
2970 return 0;
ca8bd38b
CEB
2971 for (i = 0; i < swap_header->info.nr_badpages; i++)
2972 swab32s(&swap_header->info.badpages[i]);
2973 }
2974 /* Check the swap header's sub-version */
2975 if (swap_header->info.version != 1) {
465c47fd
AM
2976 pr_warn("Unable to handle swap header version %d\n",
2977 swap_header->info.version);
38719025 2978 return 0;
ca8bd38b
CEB
2979 }
2980
2981 p->lowest_bit = 1;
2982 p->cluster_next = 1;
2983 p->cluster_nr = 0;
2984
a98c27e1 2985 maxpages = max_swapfile_size();
d6bbbd29 2986 last_page = swap_header->info.last_page;
e4efe5ef
TA
2987 if (!last_page) {
2988 pr_warn("Empty swap-file\n");
2989 return 0;
2990 }
d6bbbd29 2991 if (last_page > maxpages) {
465c47fd 2992 pr_warn("Truncating oversized swap area, only using %luk out of %luk\n",
d6bbbd29
RJ
2993 maxpages << (PAGE_SHIFT - 10),
2994 last_page << (PAGE_SHIFT - 10));
2995 }
2996 if (maxpages > last_page) {
2997 maxpages = last_page + 1;
ca8bd38b
CEB
2998 /* p->max is an unsigned int: don't overflow it */
2999 if ((unsigned int)maxpages == 0)
3000 maxpages = UINT_MAX;
3001 }
3002 p->highest_bit = maxpages - 1;
3003
3004 if (!maxpages)
38719025 3005 return 0;
ca8bd38b
CEB
3006 swapfilepages = i_size_read(inode) >> PAGE_SHIFT;
3007 if (swapfilepages && maxpages > swapfilepages) {
465c47fd 3008 pr_warn("Swap area shorter than signature indicates\n");
38719025 3009 return 0;
ca8bd38b
CEB
3010 }
3011 if (swap_header->info.nr_badpages && S_ISREG(inode->i_mode))
38719025 3012 return 0;
ca8bd38b 3013 if (swap_header->info.nr_badpages > MAX_SWAP_BADPAGES)
38719025 3014 return 0;
ca8bd38b
CEB
3015
3016 return maxpages;
ca8bd38b
CEB
3017}
3018
4b3ef9da 3019#define SWAP_CLUSTER_INFO_COLS \
235b6217 3020 DIV_ROUND_UP(L1_CACHE_BYTES, sizeof(struct swap_cluster_info))
4b3ef9da
HY
3021#define SWAP_CLUSTER_SPACE_COLS \
3022 DIV_ROUND_UP(SWAP_ADDRESS_SPACE_PAGES, SWAPFILE_CLUSTER)
3023#define SWAP_CLUSTER_COLS \
3024 max_t(unsigned int, SWAP_CLUSTER_INFO_COLS, SWAP_CLUSTER_SPACE_COLS)
235b6217 3025
915d4d7b
CEB
3026static int setup_swap_map_and_extents(struct swap_info_struct *p,
3027 union swap_header *swap_header,
3028 unsigned char *swap_map,
2a8f9449 3029 struct swap_cluster_info *cluster_info,
915d4d7b
CEB
3030 unsigned long maxpages,
3031 sector_t *span)
3032{
235b6217 3033 unsigned int j, k;
915d4d7b
CEB
3034 unsigned int nr_good_pages;
3035 int nr_extents;
2a8f9449 3036 unsigned long nr_clusters = DIV_ROUND_UP(maxpages, SWAPFILE_CLUSTER);
235b6217
HY
3037 unsigned long col = p->cluster_next / SWAPFILE_CLUSTER % SWAP_CLUSTER_COLS;
3038 unsigned long i, idx;
915d4d7b
CEB
3039
3040 nr_good_pages = maxpages - 1; /* omit header page */
3041
6b534915
HY
3042 cluster_list_init(&p->free_clusters);
3043 cluster_list_init(&p->discard_clusters);
2a8f9449 3044
915d4d7b
CEB
3045 for (i = 0; i < swap_header->info.nr_badpages; i++) {
3046 unsigned int page_nr = swap_header->info.badpages[i];
bdb8e3f6
CEB
3047 if (page_nr == 0 || page_nr > swap_header->info.last_page)
3048 return -EINVAL;
915d4d7b
CEB
3049 if (page_nr < maxpages) {
3050 swap_map[page_nr] = SWAP_MAP_BAD;
3051 nr_good_pages--;
2a8f9449
SL
3052 /*
3053 * Haven't marked the cluster free yet, no list
3054 * operation involved
3055 */
3056 inc_cluster_info_page(p, cluster_info, page_nr);
915d4d7b
CEB
3057 }
3058 }
3059
2a8f9449
SL
3060 /* Haven't marked the cluster free yet, no list operation involved */
3061 for (i = maxpages; i < round_up(maxpages, SWAPFILE_CLUSTER); i++)
3062 inc_cluster_info_page(p, cluster_info, i);
3063
915d4d7b
CEB
3064 if (nr_good_pages) {
3065 swap_map[0] = SWAP_MAP_BAD;
2a8f9449
SL
3066 /*
3067 * Not mark the cluster free yet, no list
3068 * operation involved
3069 */
3070 inc_cluster_info_page(p, cluster_info, 0);
915d4d7b
CEB
3071 p->max = maxpages;
3072 p->pages = nr_good_pages;
3073 nr_extents = setup_swap_extents(p, span);
bdb8e3f6
CEB
3074 if (nr_extents < 0)
3075 return nr_extents;
915d4d7b
CEB
3076 nr_good_pages = p->pages;
3077 }
3078 if (!nr_good_pages) {
465c47fd 3079 pr_warn("Empty swap-file\n");
bdb8e3f6 3080 return -EINVAL;
915d4d7b
CEB
3081 }
3082
2a8f9449
SL
3083 if (!cluster_info)
3084 return nr_extents;
3085
235b6217 3086
4b3ef9da
HY
3087 /*
3088 * Reduce false cache line sharing between cluster_info and
3089 * sharing same address space.
3090 */
235b6217
HY
3091 for (k = 0; k < SWAP_CLUSTER_COLS; k++) {
3092 j = (k + col) % SWAP_CLUSTER_COLS;
3093 for (i = 0; i < DIV_ROUND_UP(nr_clusters, SWAP_CLUSTER_COLS); i++) {
3094 idx = i * SWAP_CLUSTER_COLS + j;
3095 if (idx >= nr_clusters)
3096 continue;
3097 if (cluster_count(&cluster_info[idx]))
3098 continue;
2a8f9449 3099 cluster_set_flag(&cluster_info[idx], CLUSTER_FLAG_FREE);
6b534915
HY
3100 cluster_list_add_tail(&p->free_clusters, cluster_info,
3101 idx);
2a8f9449 3102 }
2a8f9449 3103 }
915d4d7b 3104 return nr_extents;
915d4d7b
CEB
3105}
3106
dcf6b7dd
RA
3107/*
3108 * Helper to sys_swapon determining if a given swap
3109 * backing device queue supports DISCARD operations.
3110 */
3111static bool swap_discardable(struct swap_info_struct *si)
3112{
3113 struct request_queue *q = bdev_get_queue(si->bdev);
3114
3115 if (!q || !blk_queue_discard(q))
3116 return false;
3117
3118 return true;
3119}
3120
53cbb243
CEB
3121SYSCALL_DEFINE2(swapon, const char __user *, specialfile, int, swap_flags)
3122{
3123 struct swap_info_struct *p;
91a27b2a 3124 struct filename *name;
53cbb243
CEB
3125 struct file *swap_file = NULL;
3126 struct address_space *mapping;
40531542 3127 int prio;
53cbb243
CEB
3128 int error;
3129 union swap_header *swap_header;
915d4d7b 3130 int nr_extents;
53cbb243
CEB
3131 sector_t span;
3132 unsigned long maxpages;
53cbb243 3133 unsigned char *swap_map = NULL;
2a8f9449 3134 struct swap_cluster_info *cluster_info = NULL;
38b5faf4 3135 unsigned long *frontswap_map = NULL;
53cbb243
CEB
3136 struct page *page = NULL;
3137 struct inode *inode = NULL;
53cbb243 3138
d15cab97
HD
3139 if (swap_flags & ~SWAP_FLAGS_VALID)
3140 return -EINVAL;
3141
53cbb243
CEB
3142 if (!capable(CAP_SYS_ADMIN))
3143 return -EPERM;
3144
a2468cc9
AL
3145 if (!swap_avail_heads)
3146 return -ENOMEM;
3147
53cbb243 3148 p = alloc_swap_info();
2542e513
CEB
3149 if (IS_ERR(p))
3150 return PTR_ERR(p);
53cbb243 3151
815c2c54
SL
3152 INIT_WORK(&p->discard_work, swap_discard_work);
3153
1da177e4 3154 name = getname(specialfile);
1da177e4 3155 if (IS_ERR(name)) {
7de7fb6b 3156 error = PTR_ERR(name);
1da177e4 3157 name = NULL;
bd69010b 3158 goto bad_swap;
1da177e4 3159 }
669abf4e 3160 swap_file = file_open_name(name, O_RDWR|O_LARGEFILE, 0);
1da177e4 3161 if (IS_ERR(swap_file)) {
7de7fb6b 3162 error = PTR_ERR(swap_file);
1da177e4 3163 swap_file = NULL;
bd69010b 3164 goto bad_swap;
1da177e4
LT
3165 }
3166
3167 p->swap_file = swap_file;
3168 mapping = swap_file->f_mapping;
2130781e 3169 inode = mapping->host;
6f179af8 3170
5955102c 3171 /* If S_ISREG(inode->i_mode) will do inode_lock(inode); */
4d0e1e10
CEB
3172 error = claim_swapfile(p, inode);
3173 if (unlikely(error))
1da177e4 3174 goto bad_swap;
1da177e4 3175
1da177e4
LT
3176 /*
3177 * Read the swap header.
3178 */
3179 if (!mapping->a_ops->readpage) {
3180 error = -EINVAL;
3181 goto bad_swap;
3182 }
090d2b18 3183 page = read_mapping_page(mapping, 0, swap_file);
1da177e4
LT
3184 if (IS_ERR(page)) {
3185 error = PTR_ERR(page);
3186 goto bad_swap;
3187 }
81e33971 3188 swap_header = kmap(page);
1da177e4 3189
ca8bd38b
CEB
3190 maxpages = read_swap_header(p, swap_header, inode);
3191 if (unlikely(!maxpages)) {
1da177e4
LT
3192 error = -EINVAL;
3193 goto bad_swap;
3194 }
886bb7e9 3195
81e33971 3196 /* OK, set up the swap map and apply the bad block list */
803d0c83 3197 swap_map = vzalloc(maxpages);
81e33971
HD
3198 if (!swap_map) {
3199 error = -ENOMEM;
3200 goto bad_swap;
3201 }
f0571429
MK
3202
3203 if (bdi_cap_stable_pages_required(inode_to_bdi(inode)))
3204 p->flags |= SWP_STABLE_WRITES;
3205
539a6fea
MK
3206 if (bdi_cap_synchronous_io(inode_to_bdi(inode)))
3207 p->flags |= SWP_SYNCHRONOUS_IO;
3208
2a8f9449 3209 if (p->bdev && blk_queue_nonrot(bdev_get_queue(p->bdev))) {
6f179af8 3210 int cpu;
235b6217 3211 unsigned long ci, nr_cluster;
6f179af8 3212
2a8f9449
SL
3213 p->flags |= SWP_SOLIDSTATE;
3214 /*
3215 * select a random position to start with to help wear leveling
3216 * SSD
3217 */
3218 p->cluster_next = 1 + (prandom_u32() % p->highest_bit);
235b6217 3219 nr_cluster = DIV_ROUND_UP(maxpages, SWAPFILE_CLUSTER);
2a8f9449 3220
54f180d3
HY
3221 cluster_info = kvzalloc(nr_cluster * sizeof(*cluster_info),
3222 GFP_KERNEL);
2a8f9449
SL
3223 if (!cluster_info) {
3224 error = -ENOMEM;
3225 goto bad_swap;
3226 }
235b6217
HY
3227
3228 for (ci = 0; ci < nr_cluster; ci++)
3229 spin_lock_init(&((cluster_info + ci)->lock));
3230
ebc2a1a6
SL
3231 p->percpu_cluster = alloc_percpu(struct percpu_cluster);
3232 if (!p->percpu_cluster) {
3233 error = -ENOMEM;
3234 goto bad_swap;
3235 }
6f179af8 3236 for_each_possible_cpu(cpu) {
ebc2a1a6 3237 struct percpu_cluster *cluster;
6f179af8 3238 cluster = per_cpu_ptr(p->percpu_cluster, cpu);
ebc2a1a6
SL
3239 cluster_set_null(&cluster->index);
3240 }
81a0298b
HY
3241 } else
3242 atomic_inc(&nr_rotate_swap);
1da177e4 3243
1421ef3c
CEB
3244 error = swap_cgroup_swapon(p->type, maxpages);
3245 if (error)
3246 goto bad_swap;
3247
915d4d7b 3248 nr_extents = setup_swap_map_and_extents(p, swap_header, swap_map,
2a8f9449 3249 cluster_info, maxpages, &span);
915d4d7b
CEB
3250 if (unlikely(nr_extents < 0)) {
3251 error = nr_extents;
1da177e4
LT
3252 goto bad_swap;
3253 }
38b5faf4 3254 /* frontswap enabled? set up bit-per-page map for frontswap */
8ea1d2a1 3255 if (IS_ENABLED(CONFIG_FRONTSWAP))
54f180d3
HY
3256 frontswap_map = kvzalloc(BITS_TO_LONGS(maxpages) * sizeof(long),
3257 GFP_KERNEL);
1da177e4 3258
2a8f9449
SL
3259 if (p->bdev &&(swap_flags & SWAP_FLAG_DISCARD) && swap_discardable(p)) {
3260 /*
3261 * When discard is enabled for swap with no particular
3262 * policy flagged, we set all swap discard flags here in
3263 * order to sustain backward compatibility with older
3264 * swapon(8) releases.
3265 */
3266 p->flags |= (SWP_DISCARDABLE | SWP_AREA_DISCARD |
3267 SWP_PAGE_DISCARD);
dcf6b7dd 3268
2a8f9449
SL
3269 /*
3270 * By flagging sys_swapon, a sysadmin can tell us to
3271 * either do single-time area discards only, or to just
3272 * perform discards for released swap page-clusters.
3273 * Now it's time to adjust the p->flags accordingly.
3274 */
3275 if (swap_flags & SWAP_FLAG_DISCARD_ONCE)
3276 p->flags &= ~SWP_PAGE_DISCARD;
3277 else if (swap_flags & SWAP_FLAG_DISCARD_PAGES)
3278 p->flags &= ~SWP_AREA_DISCARD;
3279
3280 /* issue a swapon-time discard if it's still required */
3281 if (p->flags & SWP_AREA_DISCARD) {
3282 int err = discard_swap(p);
3283 if (unlikely(err))
3284 pr_err("swapon: discard_swap(%p): %d\n",
3285 p, err);
dcf6b7dd 3286 }
20137a49 3287 }
6a6ba831 3288
4b3ef9da
HY
3289 error = init_swap_address_space(p->type, maxpages);
3290 if (error)
3291 goto bad_swap;
3292
fc0abb14 3293 mutex_lock(&swapon_mutex);
40531542 3294 prio = -1;
78ecba08 3295 if (swap_flags & SWAP_FLAG_PREFER)
40531542 3296 prio =
78ecba08 3297 (swap_flags & SWAP_FLAG_PRIO_MASK) >> SWAP_FLAG_PRIO_SHIFT;
2a8f9449 3298 enable_swap_info(p, prio, swap_map, cluster_info, frontswap_map);
c69dbfb8 3299
756a025f 3300 pr_info("Adding %uk swap on %s. Priority:%d extents:%d across:%lluk %s%s%s%s%s\n",
91a27b2a 3301 p->pages<<(PAGE_SHIFT-10), name->name, p->prio,
c69dbfb8
CEB
3302 nr_extents, (unsigned long long)span<<(PAGE_SHIFT-10),
3303 (p->flags & SWP_SOLIDSTATE) ? "SS" : "",
38b5faf4 3304 (p->flags & SWP_DISCARDABLE) ? "D" : "",
dcf6b7dd
RA
3305 (p->flags & SWP_AREA_DISCARD) ? "s" : "",
3306 (p->flags & SWP_PAGE_DISCARD) ? "c" : "",
38b5faf4 3307 (frontswap_map) ? "FS" : "");
c69dbfb8 3308
fc0abb14 3309 mutex_unlock(&swapon_mutex);
66d7dd51
KS
3310 atomic_inc(&proc_poll_event);
3311 wake_up_interruptible(&proc_poll_wait);
3312
9b01c350
CEB
3313 if (S_ISREG(inode->i_mode))
3314 inode->i_flags |= S_SWAPFILE;
1da177e4
LT
3315 error = 0;
3316 goto out;
3317bad_swap:
ebc2a1a6
SL
3318 free_percpu(p->percpu_cluster);
3319 p->percpu_cluster = NULL;
bd69010b 3320 if (inode && S_ISBLK(inode->i_mode) && p->bdev) {
f2090d2d
CEB
3321 set_blocksize(p->bdev, p->old_block_size);
3322 blkdev_put(p->bdev, FMODE_READ | FMODE_WRITE | FMODE_EXCL);
1da177e4 3323 }
4cd3bb10 3324 destroy_swap_extents(p);
e8e6c2ec 3325 swap_cgroup_swapoff(p->type);
5d337b91 3326 spin_lock(&swap_lock);
1da177e4 3327 p->swap_file = NULL;
1da177e4 3328 p->flags = 0;
5d337b91 3329 spin_unlock(&swap_lock);
1da177e4 3330 vfree(swap_map);
8606a1a9 3331 kvfree(cluster_info);
b6b1fd2a 3332 kvfree(frontswap_map);
52c50567 3333 if (swap_file) {
2130781e 3334 if (inode && S_ISREG(inode->i_mode)) {
5955102c 3335 inode_unlock(inode);
2130781e
CEB
3336 inode = NULL;
3337 }
1da177e4 3338 filp_close(swap_file, NULL);
52c50567 3339 }
1da177e4
LT
3340out:
3341 if (page && !IS_ERR(page)) {
3342 kunmap(page);
09cbfeaf 3343 put_page(page);
1da177e4
LT
3344 }
3345 if (name)
3346 putname(name);
9b01c350 3347 if (inode && S_ISREG(inode->i_mode))
5955102c 3348 inode_unlock(inode);
039939a6
TC
3349 if (!error)
3350 enable_swap_slots_cache();
1da177e4
LT
3351 return error;
3352}
3353
3354void si_swapinfo(struct sysinfo *val)
3355{
efa90a98 3356 unsigned int type;
1da177e4
LT
3357 unsigned long nr_to_be_unused = 0;
3358
5d337b91 3359 spin_lock(&swap_lock);
efa90a98
HD
3360 for (type = 0; type < nr_swapfiles; type++) {
3361 struct swap_info_struct *si = swap_info[type];
3362
3363 if ((si->flags & SWP_USED) && !(si->flags & SWP_WRITEOK))
3364 nr_to_be_unused += si->inuse_pages;
1da177e4 3365 }
ec8acf20 3366 val->freeswap = atomic_long_read(&nr_swap_pages) + nr_to_be_unused;
1da177e4 3367 val->totalswap = total_swap_pages + nr_to_be_unused;
5d337b91 3368 spin_unlock(&swap_lock);
1da177e4
LT
3369}
3370
3371/*
3372 * Verify that a swap entry is valid and increment its swap map count.
3373 *
355cfa73
KH
3374 * Returns error code in following case.
3375 * - success -> 0
3376 * - swp_entry is invalid -> EINVAL
3377 * - swp_entry is migration entry -> EINVAL
3378 * - swap-cache reference is requested but there is already one. -> EEXIST
3379 * - swap-cache reference is requested but the entry is not used. -> ENOENT
570a335b 3380 * - swap-mapped reference requested but needs continued swap count. -> ENOMEM
1da177e4 3381 */
8d69aaee 3382static int __swap_duplicate(swp_entry_t entry, unsigned char usage)
1da177e4 3383{
73c34b6a 3384 struct swap_info_struct *p;
235b6217 3385 struct swap_cluster_info *ci;
27a34b2d 3386 unsigned long offset;
8d69aaee
HD
3387 unsigned char count;
3388 unsigned char has_cache;
253d553b 3389 int err = -EINVAL;
1da177e4 3390
a7420aa5 3391 if (non_swap_entry(entry))
253d553b 3392 goto out;
0697212a 3393
27a34b2d
DJ
3394 p = swp_swap_info(entry);
3395 if (!p)
1da177e4 3396 goto bad_file;
27a34b2d 3397
1da177e4 3398 offset = swp_offset(entry);
355cfa73 3399 if (unlikely(offset >= p->max))
235b6217
HY
3400 goto out;
3401
3402 ci = lock_cluster_or_swap_info(p, offset);
355cfa73 3403
253d553b 3404 count = p->swap_map[offset];
edfe23da
SL
3405
3406 /*
3407 * swapin_readahead() doesn't check if a swap entry is valid, so the
3408 * swap entry could be SWAP_MAP_BAD. Check here with lock held.
3409 */
3410 if (unlikely(swap_count(count) == SWAP_MAP_BAD)) {
3411 err = -ENOENT;
3412 goto unlock_out;
3413 }
3414
253d553b
HD
3415 has_cache = count & SWAP_HAS_CACHE;
3416 count &= ~SWAP_HAS_CACHE;
3417 err = 0;
355cfa73 3418
253d553b 3419 if (usage == SWAP_HAS_CACHE) {
355cfa73
KH
3420
3421 /* set SWAP_HAS_CACHE if there is no cache and entry is used */
253d553b
HD
3422 if (!has_cache && count)
3423 has_cache = SWAP_HAS_CACHE;
3424 else if (has_cache) /* someone else added cache */
3425 err = -EEXIST;
3426 else /* no users remaining */
3427 err = -ENOENT;
355cfa73
KH
3428
3429 } else if (count || has_cache) {
253d553b 3430
570a335b
HD
3431 if ((count & ~COUNT_CONTINUED) < SWAP_MAP_MAX)
3432 count += usage;
3433 else if ((count & ~COUNT_CONTINUED) > SWAP_MAP_MAX)
253d553b 3434 err = -EINVAL;
570a335b
HD
3435 else if (swap_count_continued(p, offset, count))
3436 count = COUNT_CONTINUED;
3437 else
3438 err = -ENOMEM;
355cfa73 3439 } else
253d553b
HD
3440 err = -ENOENT; /* unused swap entry */
3441
3442 p->swap_map[offset] = count | has_cache;
3443
355cfa73 3444unlock_out:
235b6217 3445 unlock_cluster_or_swap_info(p, ci);
1da177e4 3446out:
253d553b 3447 return err;
1da177e4
LT
3448
3449bad_file:
465c47fd 3450 pr_err("swap_dup: %s%08lx\n", Bad_file, entry.val);
1da177e4
LT
3451 goto out;
3452}
253d553b 3453
aaa46865
HD
3454/*
3455 * Help swapoff by noting that swap entry belongs to shmem/tmpfs
3456 * (in which case its reference count is never incremented).
3457 */
3458void swap_shmem_alloc(swp_entry_t entry)
3459{
3460 __swap_duplicate(entry, SWAP_MAP_SHMEM);
3461}
3462
355cfa73 3463/*
08259d58
HD
3464 * Increase reference count of swap entry by 1.
3465 * Returns 0 for success, or -ENOMEM if a swap_count_continuation is required
3466 * but could not be atomically allocated. Returns 0, just as if it succeeded,
3467 * if __swap_duplicate() fails for another reason (-EINVAL or -ENOENT), which
3468 * might occur if a page table entry has got corrupted.
355cfa73 3469 */
570a335b 3470int swap_duplicate(swp_entry_t entry)
355cfa73 3471{
570a335b
HD
3472 int err = 0;
3473
3474 while (!err && __swap_duplicate(entry, 1) == -ENOMEM)
3475 err = add_swap_count_continuation(entry, GFP_ATOMIC);
3476 return err;
355cfa73 3477}
1da177e4 3478
cb4b86ba 3479/*
355cfa73
KH
3480 * @entry: swap entry for which we allocate swap cache.
3481 *
73c34b6a 3482 * Called when allocating swap cache for existing swap entry,
355cfa73
KH
3483 * This can return error codes. Returns 0 at success.
3484 * -EBUSY means there is a swap cache.
3485 * Note: return code is different from swap_duplicate().
cb4b86ba
KH
3486 */
3487int swapcache_prepare(swp_entry_t entry)
3488{
253d553b 3489 return __swap_duplicate(entry, SWAP_HAS_CACHE);
cb4b86ba
KH
3490}
3491
0bcac06f
MK
3492struct swap_info_struct *swp_swap_info(swp_entry_t entry)
3493{
27a34b2d 3494 return swap_type_to_swap_info(swp_type(entry));
0bcac06f
MK
3495}
3496
f981c595
MG
3497struct swap_info_struct *page_swap_info(struct page *page)
3498{
0bcac06f
MK
3499 swp_entry_t entry = { .val = page_private(page) };
3500 return swp_swap_info(entry);
f981c595
MG
3501}
3502
3503/*
3504 * out-of-line __page_file_ methods to avoid include hell.
3505 */
3506struct address_space *__page_file_mapping(struct page *page)
3507{
f981c595
MG
3508 return page_swap_info(page)->swap_file->f_mapping;
3509}
3510EXPORT_SYMBOL_GPL(__page_file_mapping);
3511
3512pgoff_t __page_file_index(struct page *page)
3513{
3514 swp_entry_t swap = { .val = page_private(page) };
f981c595
MG
3515 return swp_offset(swap);
3516}
3517EXPORT_SYMBOL_GPL(__page_file_index);
3518
570a335b
HD
3519/*
3520 * add_swap_count_continuation - called when a swap count is duplicated
3521 * beyond SWAP_MAP_MAX, it allocates a new page and links that to the entry's
3522 * page of the original vmalloc'ed swap_map, to hold the continuation count
3523 * (for that entry and for its neighbouring PAGE_SIZE swap entries). Called
3524 * again when count is duplicated beyond SWAP_MAP_MAX * SWAP_CONT_MAX, etc.
3525 *
3526 * These continuation pages are seldom referenced: the common paths all work
3527 * on the original swap_map, only referring to a continuation page when the
3528 * low "digit" of a count is incremented or decremented through SWAP_MAP_MAX.
3529 *
3530 * add_swap_count_continuation(, GFP_ATOMIC) can be called while holding
3531 * page table locks; if it fails, add_swap_count_continuation(, GFP_KERNEL)
3532 * can be called after dropping locks.
3533 */
3534int add_swap_count_continuation(swp_entry_t entry, gfp_t gfp_mask)
3535{
3536 struct swap_info_struct *si;
235b6217 3537 struct swap_cluster_info *ci;
570a335b
HD
3538 struct page *head;
3539 struct page *page;
3540 struct page *list_page;
3541 pgoff_t offset;
3542 unsigned char count;
3543
3544 /*
3545 * When debugging, it's easier to use __GFP_ZERO here; but it's better
3546 * for latency not to zero a page while GFP_ATOMIC and holding locks.
3547 */
3548 page = alloc_page(gfp_mask | __GFP_HIGHMEM);
3549
3550 si = swap_info_get(entry);
3551 if (!si) {
3552 /*
3553 * An acceptable race has occurred since the failing
3554 * __swap_duplicate(): the swap entry has been freed,
3555 * perhaps even the whole swap_map cleared for swapoff.
3556 */
3557 goto outer;
3558 }
3559
3560 offset = swp_offset(entry);
235b6217
HY
3561
3562 ci = lock_cluster(si, offset);
3563
570a335b
HD
3564 count = si->swap_map[offset] & ~SWAP_HAS_CACHE;
3565
3566 if ((count & ~COUNT_CONTINUED) != SWAP_MAP_MAX) {
3567 /*
3568 * The higher the swap count, the more likely it is that tasks
3569 * will race to add swap count continuation: we need to avoid
3570 * over-provisioning.
3571 */
3572 goto out;
3573 }
3574
3575 if (!page) {
235b6217 3576 unlock_cluster(ci);
ec8acf20 3577 spin_unlock(&si->lock);
570a335b
HD
3578 return -ENOMEM;
3579 }
3580
3581 /*
3582 * We are fortunate that although vmalloc_to_page uses pte_offset_map,
2de1a7e4
SJ
3583 * no architecture is using highmem pages for kernel page tables: so it
3584 * will not corrupt the GFP_ATOMIC caller's atomic page table kmaps.
570a335b
HD
3585 */
3586 head = vmalloc_to_page(si->swap_map + offset);
3587 offset &= ~PAGE_MASK;
3588
2628bd6f 3589 spin_lock(&si->cont_lock);
570a335b
HD
3590 /*
3591 * Page allocation does not initialize the page's lru field,
3592 * but it does always reset its private field.
3593 */
3594 if (!page_private(head)) {
3595 BUG_ON(count & COUNT_CONTINUED);
3596 INIT_LIST_HEAD(&head->lru);
3597 set_page_private(head, SWP_CONTINUED);
3598 si->flags |= SWP_CONTINUED;
3599 }
3600
3601 list_for_each_entry(list_page, &head->lru, lru) {
3602 unsigned char *map;
3603
3604 /*
3605 * If the previous map said no continuation, but we've found
3606 * a continuation page, free our allocation and use this one.
3607 */
3608 if (!(count & COUNT_CONTINUED))
2628bd6f 3609 goto out_unlock_cont;
570a335b 3610
9b04c5fe 3611 map = kmap_atomic(list_page) + offset;
570a335b 3612 count = *map;
9b04c5fe 3613 kunmap_atomic(map);
570a335b
HD
3614
3615 /*
3616 * If this continuation count now has some space in it,
3617 * free our allocation and use this one.
3618 */
3619 if ((count & ~COUNT_CONTINUED) != SWAP_CONT_MAX)
2628bd6f 3620 goto out_unlock_cont;
570a335b
HD
3621 }
3622
3623 list_add_tail(&page->lru, &head->lru);
3624 page = NULL; /* now it's attached, don't free it */
2628bd6f
HY
3625out_unlock_cont:
3626 spin_unlock(&si->cont_lock);
570a335b 3627out:
235b6217 3628 unlock_cluster(ci);
ec8acf20 3629 spin_unlock(&si->lock);
570a335b
HD
3630outer:
3631 if (page)
3632 __free_page(page);
3633 return 0;
3634}
3635
3636/*
3637 * swap_count_continued - when the original swap_map count is incremented
3638 * from SWAP_MAP_MAX, check if there is already a continuation page to carry
3639 * into, carry if so, or else fail until a new continuation page is allocated;
3640 * when the original swap_map count is decremented from 0 with continuation,
3641 * borrow from the continuation and report whether it still holds more.
235b6217
HY
3642 * Called while __swap_duplicate() or swap_entry_free() holds swap or cluster
3643 * lock.
570a335b
HD
3644 */
3645static bool swap_count_continued(struct swap_info_struct *si,
3646 pgoff_t offset, unsigned char count)
3647{
3648 struct page *head;
3649 struct page *page;
3650 unsigned char *map;
2628bd6f 3651 bool ret;
570a335b
HD
3652
3653 head = vmalloc_to_page(si->swap_map + offset);
3654 if (page_private(head) != SWP_CONTINUED) {
3655 BUG_ON(count & COUNT_CONTINUED);
3656 return false; /* need to add count continuation */
3657 }
3658
2628bd6f 3659 spin_lock(&si->cont_lock);
570a335b
HD
3660 offset &= ~PAGE_MASK;
3661 page = list_entry(head->lru.next, struct page, lru);
9b04c5fe 3662 map = kmap_atomic(page) + offset;
570a335b
HD
3663
3664 if (count == SWAP_MAP_MAX) /* initial increment from swap_map */
3665 goto init_map; /* jump over SWAP_CONT_MAX checks */
3666
3667 if (count == (SWAP_MAP_MAX | COUNT_CONTINUED)) { /* incrementing */
3668 /*
3669 * Think of how you add 1 to 999
3670 */
3671 while (*map == (SWAP_CONT_MAX | COUNT_CONTINUED)) {
9b04c5fe 3672 kunmap_atomic(map);
570a335b
HD
3673 page = list_entry(page->lru.next, struct page, lru);
3674 BUG_ON(page == head);
9b04c5fe 3675 map = kmap_atomic(page) + offset;
570a335b
HD
3676 }
3677 if (*map == SWAP_CONT_MAX) {
9b04c5fe 3678 kunmap_atomic(map);
570a335b 3679 page = list_entry(page->lru.next, struct page, lru);
2628bd6f
HY
3680 if (page == head) {
3681 ret = false; /* add count continuation */
3682 goto out;
3683 }
9b04c5fe 3684 map = kmap_atomic(page) + offset;
570a335b
HD
3685init_map: *map = 0; /* we didn't zero the page */
3686 }
3687 *map += 1;
9b04c5fe 3688 kunmap_atomic(map);
570a335b
HD
3689 page = list_entry(page->lru.prev, struct page, lru);
3690 while (page != head) {
9b04c5fe 3691 map = kmap_atomic(page) + offset;
570a335b 3692 *map = COUNT_CONTINUED;
9b04c5fe 3693 kunmap_atomic(map);
570a335b
HD
3694 page = list_entry(page->lru.prev, struct page, lru);
3695 }
2628bd6f 3696 ret = true; /* incremented */
570a335b
HD
3697
3698 } else { /* decrementing */
3699 /*
3700 * Think of how you subtract 1 from 1000
3701 */
3702 BUG_ON(count != COUNT_CONTINUED);
3703 while (*map == COUNT_CONTINUED) {
9b04c5fe 3704 kunmap_atomic(map);
570a335b
HD
3705 page = list_entry(page->lru.next, struct page, lru);
3706 BUG_ON(page == head);
9b04c5fe 3707 map = kmap_atomic(page) + offset;
570a335b
HD
3708 }
3709 BUG_ON(*map == 0);
3710 *map -= 1;
3711 if (*map == 0)
3712 count = 0;
9b04c5fe 3713 kunmap_atomic(map);
570a335b
HD
3714 page = list_entry(page->lru.prev, struct page, lru);
3715 while (page != head) {
9b04c5fe 3716 map = kmap_atomic(page) + offset;
570a335b
HD
3717 *map = SWAP_CONT_MAX | count;
3718 count = COUNT_CONTINUED;
9b04c5fe 3719 kunmap_atomic(map);
570a335b
HD
3720 page = list_entry(page->lru.prev, struct page, lru);
3721 }
2628bd6f 3722 ret = count == COUNT_CONTINUED;
570a335b 3723 }
2628bd6f
HY
3724out:
3725 spin_unlock(&si->cont_lock);
3726 return ret;
570a335b
HD
3727}
3728
3729/*
3730 * free_swap_count_continuations - swapoff free all the continuation pages
3731 * appended to the swap_map, after swap_map is quiesced, before vfree'ing it.
3732 */
3733static void free_swap_count_continuations(struct swap_info_struct *si)
3734{
3735 pgoff_t offset;
3736
3737 for (offset = 0; offset < si->max; offset += PAGE_SIZE) {
3738 struct page *head;
3739 head = vmalloc_to_page(si->swap_map + offset);
3740 if (page_private(head)) {
0d576d20
GT
3741 struct page *page, *next;
3742
3743 list_for_each_entry_safe(page, next, &head->lru, lru) {
3744 list_del(&page->lru);
570a335b
HD
3745 __free_page(page);
3746 }
3747 }
3748 }
3749}
a2468cc9
AL
3750
3751static int __init swapfile_init(void)
3752{
3753 int nid;
3754
3755 swap_avail_heads = kmalloc_array(nr_node_ids, sizeof(struct plist_head),
3756 GFP_KERNEL);
3757 if (!swap_avail_heads) {
3758 pr_emerg("Not enough memory for swap heads, swap is disabled\n");
3759 return -ENOMEM;
3760 }
3761
3762 for_each_node(nid)
3763 plist_head_init(&swap_avail_heads[nid]);
3764
3765 return 0;
3766}
3767subsys_initcall(swapfile_init);