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