Merge "kfence: Use pt_regs to generate stack trace on faults" into tizen
[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 #ifdef CONFIG_FINEGRAINED_THP
1677         for (i = 0; i < thp_nr_pages(page); i++)
1678 #else
1679         for (i = 0; i < HPAGE_PMD_NR; i++)
1680 #endif
1681         {
1682                 mapcount = atomic_read(&page[i]._mapcount) + 1;
1683                 _total_mapcount += mapcount;
1684                 if (map) {
1685                         swapcount = swap_count(map[offset + i]);
1686                         _total_swapcount += swapcount;
1687                 }
1688                 map_swapcount = max(map_swapcount, mapcount + swapcount);
1689         }
1690         unlock_cluster(ci);
1691         if (PageDoubleMap(page)) {
1692                 map_swapcount -= 1;
1693 #ifdef CONFIG_FINEGRAINED_THP
1694                 _total_mapcount -= thp_nr_pages(page);
1695 #else
1696                 _total_mapcount -= HPAGE_PMD_NR;
1697 #endif
1698         }
1699         mapcount = compound_mapcount(page);
1700         map_swapcount += mapcount;
1701         _total_mapcount += mapcount;
1702         if (total_mapcount)
1703                 *total_mapcount = _total_mapcount;
1704         if (total_swapcount)
1705                 *total_swapcount = _total_swapcount;
1706
1707         return map_swapcount;
1708 }
1709
1710 /*
1711  * We can write to an anon page without COW if there are no other references
1712  * to it.  And as a side-effect, free up its swap: because the old content
1713  * on disk will never be read, and seeking back there to write new content
1714  * later would only waste time away from clustering.
1715  *
1716  * NOTE: total_map_swapcount should not be relied upon by the caller if
1717  * reuse_swap_page() returns false, but it may be always overwritten
1718  * (see the other implementation for CONFIG_SWAP=n).
1719  */
1720 bool reuse_swap_page(struct page *page, int *total_map_swapcount)
1721 {
1722         int count, total_mapcount, total_swapcount;
1723
1724         VM_BUG_ON_PAGE(!PageLocked(page), page);
1725         if (unlikely(PageKsm(page)))
1726                 return false;
1727         count = page_trans_huge_map_swapcount(page, &total_mapcount,
1728                                               &total_swapcount);
1729         if (total_map_swapcount)
1730                 *total_map_swapcount = total_mapcount + total_swapcount;
1731         if (count == 1 && PageSwapCache(page) &&
1732             (likely(!PageTransCompound(page)) ||
1733              /* The remaining swap count will be freed soon */
1734              total_swapcount == page_swapcount(page))) {
1735                 if (!PageWriteback(page)) {
1736                         page = compound_head(page);
1737                         delete_from_swap_cache(page);
1738                         SetPageDirty(page);
1739                 } else {
1740                         swp_entry_t entry;
1741                         struct swap_info_struct *p;
1742
1743                         entry.val = page_private(page);
1744                         p = swap_info_get(entry);
1745                         if (p->flags & SWP_STABLE_WRITES) {
1746                                 spin_unlock(&p->lock);
1747                                 return false;
1748                         }
1749                         spin_unlock(&p->lock);
1750                 }
1751         }
1752
1753         return count <= 1;
1754 }
1755
1756 /*
1757  * If swap is getting full, or if there are no more mappings of this page,
1758  * then try_to_free_swap is called to free its swap space.
1759  */
1760 int try_to_free_swap(struct page *page)
1761 {
1762         VM_BUG_ON_PAGE(!PageLocked(page), page);
1763
1764         if (!PageSwapCache(page))
1765                 return 0;
1766         if (PageWriteback(page))
1767                 return 0;
1768         if (page_swapped(page))
1769                 return 0;
1770
1771         /*
1772          * Once hibernation has begun to create its image of memory,
1773          * there's a danger that one of the calls to try_to_free_swap()
1774          * - most probably a call from __try_to_reclaim_swap() while
1775          * hibernation is allocating its own swap pages for the image,
1776          * but conceivably even a call from memory reclaim - will free
1777          * the swap from a page which has already been recorded in the
1778          * image as a clean swapcache page, and then reuse its swap for
1779          * another page of the image.  On waking from hibernation, the
1780          * original page might be freed under memory pressure, then
1781          * later read back in from swap, now with the wrong data.
1782          *
1783          * Hibernation suspends storage while it is writing the image
1784          * to disk so check that here.
1785          */
1786         if (pm_suspended_storage())
1787                 return 0;
1788
1789         page = compound_head(page);
1790         delete_from_swap_cache(page);
1791         SetPageDirty(page);
1792         return 1;
1793 }
1794
1795 /*
1796  * Free the swap entry like above, but also try to
1797  * free the page cache entry if it is the last user.
1798  */
1799 int free_swap_and_cache(swp_entry_t entry)
1800 {
1801         struct swap_info_struct *p;
1802         unsigned char count;
1803
1804         if (non_swap_entry(entry))
1805                 return 1;
1806
1807         p = _swap_info_get(entry);
1808         if (p) {
1809                 count = __swap_entry_free(p, entry);
1810                 if (count == SWAP_HAS_CACHE &&
1811                     !swap_page_trans_huge_swapped(p, entry))
1812                         __try_to_reclaim_swap(p, swp_offset(entry),
1813                                               TTRS_UNMAPPED | TTRS_FULL);
1814         }
1815         return p != NULL;
1816 }
1817
1818 #ifdef CONFIG_HIBERNATION
1819 /*
1820  * Find the swap type that corresponds to given device (if any).
1821  *
1822  * @offset - number of the PAGE_SIZE-sized block of the device, starting
1823  * from 0, in which the swap header is expected to be located.
1824  *
1825  * This is needed for the suspend to disk (aka swsusp).
1826  */
1827 int swap_type_of(dev_t device, sector_t offset)
1828 {
1829         int type;
1830
1831         if (!device)
1832                 return -1;
1833
1834         spin_lock(&swap_lock);
1835         for (type = 0; type < nr_swapfiles; type++) {
1836                 struct swap_info_struct *sis = swap_info[type];
1837
1838                 if (!(sis->flags & SWP_WRITEOK))
1839                         continue;
1840
1841                 if (device == sis->bdev->bd_dev) {
1842                         struct swap_extent *se = first_se(sis);
1843
1844                         if (se->start_block == offset) {
1845                                 spin_unlock(&swap_lock);
1846                                 return type;
1847                         }
1848                 }
1849         }
1850         spin_unlock(&swap_lock);
1851         return -ENODEV;
1852 }
1853
1854 int find_first_swap(dev_t *device)
1855 {
1856         int type;
1857
1858         spin_lock(&swap_lock);
1859         for (type = 0; type < nr_swapfiles; type++) {
1860                 struct swap_info_struct *sis = swap_info[type];
1861
1862                 if (!(sis->flags & SWP_WRITEOK))
1863                         continue;
1864                 *device = sis->bdev->bd_dev;
1865                 spin_unlock(&swap_lock);
1866                 return type;
1867         }
1868         spin_unlock(&swap_lock);
1869         return -ENODEV;
1870 }
1871
1872 /*
1873  * Get the (PAGE_SIZE) block corresponding to given offset on the swapdev
1874  * corresponding to given index in swap_info (swap type).
1875  */
1876 sector_t swapdev_block(int type, pgoff_t offset)
1877 {
1878         struct block_device *bdev;
1879         struct swap_info_struct *si = swap_type_to_swap_info(type);
1880
1881         if (!si || !(si->flags & SWP_WRITEOK))
1882                 return 0;
1883         return map_swap_entry(swp_entry(type, offset), &bdev);
1884 }
1885
1886 /*
1887  * Return either the total number of swap pages of given type, or the number
1888  * of free pages of that type (depending on @free)
1889  *
1890  * This is needed for software suspend
1891  */
1892 unsigned int count_swap_pages(int type, int free)
1893 {
1894         unsigned int n = 0;
1895
1896         spin_lock(&swap_lock);
1897         if ((unsigned int)type < nr_swapfiles) {
1898                 struct swap_info_struct *sis = swap_info[type];
1899
1900                 spin_lock(&sis->lock);
1901                 if (sis->flags & SWP_WRITEOK) {
1902                         n = sis->pages;
1903                         if (free)
1904                                 n -= sis->inuse_pages;
1905                 }
1906                 spin_unlock(&sis->lock);
1907         }
1908         spin_unlock(&swap_lock);
1909         return n;
1910 }
1911 #endif /* CONFIG_HIBERNATION */
1912
1913 static inline int pte_same_as_swp(pte_t pte, pte_t swp_pte)
1914 {
1915         return pte_same(pte_swp_clear_flags(pte), swp_pte);
1916 }
1917
1918 /*
1919  * No need to decide whether this PTE shares the swap entry with others,
1920  * just let do_wp_page work it out if a write is requested later - to
1921  * force COW, vm_page_prot omits write permission from any private vma.
1922  */
1923 static int unuse_pte(struct vm_area_struct *vma, pmd_t *pmd,
1924                 unsigned long addr, swp_entry_t entry, struct page *page)
1925 {
1926         struct page *swapcache;
1927         spinlock_t *ptl;
1928         pte_t *pte;
1929         int ret = 1;
1930
1931         swapcache = page;
1932         page = ksm_might_need_to_copy(page, vma, addr);
1933         if (unlikely(!page))
1934                 return -ENOMEM;
1935
1936         pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
1937         if (unlikely(!pte_same_as_swp(*pte, swp_entry_to_pte(entry)))) {
1938                 ret = 0;
1939                 goto out;
1940         }
1941
1942         dec_mm_counter(vma->vm_mm, MM_SWAPENTS);
1943         inc_mm_counter(vma->vm_mm, MM_ANONPAGES);
1944         get_page(page);
1945         set_pte_at(vma->vm_mm, addr, pte,
1946                    pte_mkold(mk_pte(page, vma->vm_page_prot)));
1947         if (page == swapcache) {
1948                 page_add_anon_rmap(page, vma, addr, false);
1949         } else { /* ksm created a completely new copy */
1950                 page_add_new_anon_rmap(page, vma, addr, false);
1951                 lru_cache_add_inactive_or_unevictable(page, vma);
1952         }
1953         swap_free(entry);
1954 out:
1955         pte_unmap_unlock(pte, ptl);
1956         if (page != swapcache) {
1957                 unlock_page(page);
1958                 put_page(page);
1959         }
1960         return ret;
1961 }
1962
1963 static int unuse_pte_range(struct vm_area_struct *vma, pmd_t *pmd,
1964                         unsigned long addr, unsigned long end,
1965                         unsigned int type, bool frontswap,
1966                         unsigned long *fs_pages_to_unuse)
1967 {
1968         struct page *page;
1969         swp_entry_t entry;
1970         pte_t *pte;
1971         struct swap_info_struct *si;
1972         unsigned long offset;
1973         int ret = 0;
1974         volatile unsigned char *swap_map;
1975
1976         si = swap_info[type];
1977         pte = pte_offset_map(pmd, addr);
1978         do {
1979                 struct vm_fault vmf;
1980
1981                 if (!is_swap_pte(*pte))
1982                         continue;
1983
1984                 entry = pte_to_swp_entry(*pte);
1985                 if (swp_type(entry) != type)
1986                         continue;
1987
1988                 offset = swp_offset(entry);
1989                 if (frontswap && !frontswap_test(si, offset))
1990                         continue;
1991
1992                 pte_unmap(pte);
1993                 swap_map = &si->swap_map[offset];
1994                 page = lookup_swap_cache(entry, vma, addr);
1995                 if (!page) {
1996                         vmf.vma = vma;
1997                         vmf.address = addr;
1998                         vmf.pmd = pmd;
1999                         page = swapin_readahead(entry, GFP_HIGHUSER_MOVABLE,
2000                                                 &vmf);
2001                 }
2002                 if (!page) {
2003                         if (*swap_map == 0 || *swap_map == SWAP_MAP_BAD)
2004                                 goto try_next;
2005                         return -ENOMEM;
2006                 }
2007
2008                 lock_page(page);
2009                 wait_on_page_writeback(page);
2010                 ret = unuse_pte(vma, pmd, addr, entry, page);
2011                 if (ret < 0) {
2012                         unlock_page(page);
2013                         put_page(page);
2014                         goto out;
2015                 }
2016
2017                 try_to_free_swap(page);
2018                 unlock_page(page);
2019                 put_page(page);
2020
2021                 if (*fs_pages_to_unuse && !--(*fs_pages_to_unuse)) {
2022                         ret = FRONTSWAP_PAGES_UNUSED;
2023                         goto out;
2024                 }
2025 try_next:
2026                 pte = pte_offset_map(pmd, addr);
2027         } while (pte++, addr += PAGE_SIZE, addr != end);
2028         pte_unmap(pte - 1);
2029
2030         ret = 0;
2031 out:
2032         return ret;
2033 }
2034
2035 static inline int unuse_pmd_range(struct vm_area_struct *vma, pud_t *pud,
2036                                 unsigned long addr, unsigned long end,
2037                                 unsigned int type, bool frontswap,
2038                                 unsigned long *fs_pages_to_unuse)
2039 {
2040         pmd_t *pmd;
2041         unsigned long next;
2042         int ret;
2043
2044         pmd = pmd_offset(pud, addr);
2045         do {
2046                 cond_resched();
2047                 next = pmd_addr_end(addr, end);
2048                 if (pmd_none_or_trans_huge_or_clear_bad(pmd))
2049                         continue;
2050                 ret = unuse_pte_range(vma, pmd, addr, next, type,
2051                                       frontswap, fs_pages_to_unuse);
2052                 if (ret)
2053                         return ret;
2054         } while (pmd++, addr = next, addr != end);
2055         return 0;
2056 }
2057
2058 static inline int unuse_pud_range(struct vm_area_struct *vma, p4d_t *p4d,
2059                                 unsigned long addr, unsigned long end,
2060                                 unsigned int type, bool frontswap,
2061                                 unsigned long *fs_pages_to_unuse)
2062 {
2063         pud_t *pud;
2064         unsigned long next;
2065         int ret;
2066
2067         pud = pud_offset(p4d, addr);
2068         do {
2069                 next = pud_addr_end(addr, end);
2070                 if (pud_none_or_clear_bad(pud))
2071                         continue;
2072                 ret = unuse_pmd_range(vma, pud, addr, next, type,
2073                                       frontswap, fs_pages_to_unuse);
2074                 if (ret)
2075                         return ret;
2076         } while (pud++, addr = next, addr != end);
2077         return 0;
2078 }
2079
2080 static inline int unuse_p4d_range(struct vm_area_struct *vma, pgd_t *pgd,
2081                                 unsigned long addr, unsigned long end,
2082                                 unsigned int type, bool frontswap,
2083                                 unsigned long *fs_pages_to_unuse)
2084 {
2085         p4d_t *p4d;
2086         unsigned long next;
2087         int ret;
2088
2089         p4d = p4d_offset(pgd, addr);
2090         do {
2091                 next = p4d_addr_end(addr, end);
2092                 if (p4d_none_or_clear_bad(p4d))
2093                         continue;
2094                 ret = unuse_pud_range(vma, p4d, addr, next, type,
2095                                       frontswap, fs_pages_to_unuse);
2096                 if (ret)
2097                         return ret;
2098         } while (p4d++, addr = next, addr != end);
2099         return 0;
2100 }
2101
2102 static int unuse_vma(struct vm_area_struct *vma, unsigned int type,
2103                      bool frontswap, unsigned long *fs_pages_to_unuse)
2104 {
2105         pgd_t *pgd;
2106         unsigned long addr, end, next;
2107         int ret;
2108
2109         addr = vma->vm_start;
2110         end = vma->vm_end;
2111
2112         pgd = pgd_offset(vma->vm_mm, addr);
2113         do {
2114                 next = pgd_addr_end(addr, end);
2115                 if (pgd_none_or_clear_bad(pgd))
2116                         continue;
2117                 ret = unuse_p4d_range(vma, pgd, addr, next, type,
2118                                       frontswap, fs_pages_to_unuse);
2119                 if (ret)
2120                         return ret;
2121         } while (pgd++, addr = next, addr != end);
2122         return 0;
2123 }
2124
2125 static int unuse_mm(struct mm_struct *mm, unsigned int type,
2126                     bool frontswap, unsigned long *fs_pages_to_unuse)
2127 {
2128         struct vm_area_struct *vma;
2129         int ret = 0;
2130
2131         mmap_read_lock(mm);
2132         for (vma = mm->mmap; vma; vma = vma->vm_next) {
2133                 if (vma->anon_vma) {
2134                         ret = unuse_vma(vma, type, frontswap,
2135                                         fs_pages_to_unuse);
2136                         if (ret)
2137                                 break;
2138                 }
2139                 cond_resched();
2140         }
2141         mmap_read_unlock(mm);
2142         return ret;
2143 }
2144
2145 /*
2146  * Scan swap_map (or frontswap_map if frontswap parameter is true)
2147  * from current position to next entry still in use. Return 0
2148  * if there are no inuse entries after prev till end of the map.
2149  */
2150 static unsigned int find_next_to_unuse(struct swap_info_struct *si,
2151                                         unsigned int prev, bool frontswap)
2152 {
2153         unsigned int i;
2154         unsigned char count;
2155
2156         /*
2157          * No need for swap_lock here: we're just looking
2158          * for whether an entry is in use, not modifying it; false
2159          * hits are okay, and sys_swapoff() has already prevented new
2160          * allocations from this area (while holding swap_lock).
2161          */
2162         for (i = prev + 1; i < si->max; i++) {
2163                 count = READ_ONCE(si->swap_map[i]);
2164                 if (count && swap_count(count) != SWAP_MAP_BAD)
2165                         if (!frontswap || frontswap_test(si, i))
2166                                 break;
2167                 if ((i % LATENCY_LIMIT) == 0)
2168                         cond_resched();
2169         }
2170
2171         if (i == si->max)
2172                 i = 0;
2173
2174         return i;
2175 }
2176
2177 /*
2178  * If the boolean frontswap is true, only unuse pages_to_unuse pages;
2179  * pages_to_unuse==0 means all pages; ignored if frontswap is false
2180  */
2181 int try_to_unuse(unsigned int type, bool frontswap,
2182                  unsigned long pages_to_unuse)
2183 {
2184         struct mm_struct *prev_mm;
2185         struct mm_struct *mm;
2186         struct list_head *p;
2187         int retval = 0;
2188         struct swap_info_struct *si = swap_info[type];
2189         struct page *page;
2190         swp_entry_t entry;
2191         unsigned int i;
2192
2193         if (!READ_ONCE(si->inuse_pages))
2194                 return 0;
2195
2196         if (!frontswap)
2197                 pages_to_unuse = 0;
2198
2199 retry:
2200         retval = shmem_unuse(type, frontswap, &pages_to_unuse);
2201         if (retval)
2202                 goto out;
2203
2204         prev_mm = &init_mm;
2205         mmget(prev_mm);
2206
2207         spin_lock(&mmlist_lock);
2208         p = &init_mm.mmlist;
2209         while (READ_ONCE(si->inuse_pages) &&
2210                !signal_pending(current) &&
2211                (p = p->next) != &init_mm.mmlist) {
2212
2213                 mm = list_entry(p, struct mm_struct, mmlist);
2214                 if (!mmget_not_zero(mm))
2215                         continue;
2216                 spin_unlock(&mmlist_lock);
2217                 mmput(prev_mm);
2218                 prev_mm = mm;
2219                 retval = unuse_mm(mm, type, frontswap, &pages_to_unuse);
2220
2221                 if (retval) {
2222                         mmput(prev_mm);
2223                         goto out;
2224                 }
2225
2226                 /*
2227                  * Make sure that we aren't completely killing
2228                  * interactive performance.
2229                  */
2230                 cond_resched();
2231                 spin_lock(&mmlist_lock);
2232         }
2233         spin_unlock(&mmlist_lock);
2234
2235         mmput(prev_mm);
2236
2237         i = 0;
2238         while (READ_ONCE(si->inuse_pages) &&
2239                !signal_pending(current) &&
2240                (i = find_next_to_unuse(si, i, frontswap)) != 0) {
2241
2242                 entry = swp_entry(type, i);
2243                 page = find_get_page(swap_address_space(entry), i);
2244                 if (!page)
2245                         continue;
2246
2247                 /*
2248                  * It is conceivable that a racing task removed this page from
2249                  * swap cache just before we acquired the page lock. The page
2250                  * might even be back in swap cache on another swap area. But
2251                  * that is okay, try_to_free_swap() only removes stale pages.
2252                  */
2253                 lock_page(page);
2254                 wait_on_page_writeback(page);
2255                 try_to_free_swap(page);
2256                 unlock_page(page);
2257                 put_page(page);
2258
2259                 /*
2260                  * For frontswap, we just need to unuse pages_to_unuse, if
2261                  * it was specified. Need not check frontswap again here as
2262                  * we already zeroed out pages_to_unuse if not frontswap.
2263                  */
2264                 if (pages_to_unuse && --pages_to_unuse == 0)
2265                         goto out;
2266         }
2267
2268         /*
2269          * Lets check again to see if there are still swap entries in the map.
2270          * If yes, we would need to do retry the unuse logic again.
2271          * Under global memory pressure, swap entries can be reinserted back
2272          * into process space after the mmlist loop above passes over them.
2273          *
2274          * Limit the number of retries? No: when mmget_not_zero() above fails,
2275          * that mm is likely to be freeing swap from exit_mmap(), which proceeds
2276          * at its own independent pace; and even shmem_writepage() could have
2277          * been preempted after get_swap_page(), temporarily hiding that swap.
2278          * It's easy and robust (though cpu-intensive) just to keep retrying.
2279          */
2280         if (READ_ONCE(si->inuse_pages)) {
2281                 if (!signal_pending(current))
2282                         goto retry;
2283                 retval = -EINTR;
2284         }
2285 out:
2286         return (retval == FRONTSWAP_PAGES_UNUSED) ? 0 : retval;
2287 }
2288
2289 /*
2290  * After a successful try_to_unuse, if no swap is now in use, we know
2291  * we can empty the mmlist.  swap_lock must be held on entry and exit.
2292  * Note that mmlist_lock nests inside swap_lock, and an mm must be
2293  * added to the mmlist just after page_duplicate - before would be racy.
2294  */
2295 static void drain_mmlist(void)
2296 {
2297         struct list_head *p, *next;
2298         unsigned int type;
2299
2300         for (type = 0; type < nr_swapfiles; type++)
2301                 if (swap_info[type]->inuse_pages)
2302                         return;
2303         spin_lock(&mmlist_lock);
2304         list_for_each_safe(p, next, &init_mm.mmlist)
2305                 list_del_init(p);
2306         spin_unlock(&mmlist_lock);
2307 }
2308
2309 /*
2310  * Use this swapdev's extent info to locate the (PAGE_SIZE) block which
2311  * corresponds to page offset for the specified swap entry.
2312  * Note that the type of this function is sector_t, but it returns page offset
2313  * into the bdev, not sector offset.
2314  */
2315 static sector_t map_swap_entry(swp_entry_t entry, struct block_device **bdev)
2316 {
2317         struct swap_info_struct *sis;
2318         struct swap_extent *se;
2319         pgoff_t offset;
2320
2321         sis = swp_swap_info(entry);
2322         *bdev = sis->bdev;
2323
2324         offset = swp_offset(entry);
2325         se = offset_to_swap_extent(sis, offset);
2326         return se->start_block + (offset - se->start_page);
2327 }
2328
2329 /*
2330  * Returns the page offset into bdev for the specified page's swap entry.
2331  */
2332 sector_t map_swap_page(struct page *page, struct block_device **bdev)
2333 {
2334         swp_entry_t entry;
2335         entry.val = page_private(page);
2336         return map_swap_entry(entry, bdev);
2337 }
2338
2339 /*
2340  * Free all of a swapdev's extent information
2341  */
2342 static void destroy_swap_extents(struct swap_info_struct *sis)
2343 {
2344         while (!RB_EMPTY_ROOT(&sis->swap_extent_root)) {
2345                 struct rb_node *rb = sis->swap_extent_root.rb_node;
2346                 struct swap_extent *se = rb_entry(rb, struct swap_extent, rb_node);
2347
2348                 rb_erase(rb, &sis->swap_extent_root);
2349                 kfree(se);
2350         }
2351
2352         if (sis->flags & SWP_ACTIVATED) {
2353                 struct file *swap_file = sis->swap_file;
2354                 struct address_space *mapping = swap_file->f_mapping;
2355
2356                 sis->flags &= ~SWP_ACTIVATED;
2357                 if (mapping->a_ops->swap_deactivate)
2358                         mapping->a_ops->swap_deactivate(swap_file);
2359         }
2360 }
2361
2362 /*
2363  * Add a block range (and the corresponding page range) into this swapdev's
2364  * extent tree.
2365  *
2366  * This function rather assumes that it is called in ascending page order.
2367  */
2368 int
2369 add_swap_extent(struct swap_info_struct *sis, unsigned long start_page,
2370                 unsigned long nr_pages, sector_t start_block)
2371 {
2372         struct rb_node **link = &sis->swap_extent_root.rb_node, *parent = NULL;
2373         struct swap_extent *se;
2374         struct swap_extent *new_se;
2375
2376         /*
2377          * place the new node at the right most since the
2378          * function is called in ascending page order.
2379          */
2380         while (*link) {
2381                 parent = *link;
2382                 link = &parent->rb_right;
2383         }
2384
2385         if (parent) {
2386                 se = rb_entry(parent, struct swap_extent, rb_node);
2387                 BUG_ON(se->start_page + se->nr_pages != start_page);
2388                 if (se->start_block + se->nr_pages == start_block) {
2389                         /* Merge it */
2390                         se->nr_pages += nr_pages;
2391                         return 0;
2392                 }
2393         }
2394
2395         /* No merge, insert a new extent. */
2396         new_se = kmalloc(sizeof(*se), GFP_KERNEL);
2397         if (new_se == NULL)
2398                 return -ENOMEM;
2399         new_se->start_page = start_page;
2400         new_se->nr_pages = nr_pages;
2401         new_se->start_block = start_block;
2402
2403         rb_link_node(&new_se->rb_node, parent, link);
2404         rb_insert_color(&new_se->rb_node, &sis->swap_extent_root);
2405         return 1;
2406 }
2407 EXPORT_SYMBOL_GPL(add_swap_extent);
2408
2409 /*
2410  * A `swap extent' is a simple thing which maps a contiguous range of pages
2411  * onto a contiguous range of disk blocks.  An ordered list of swap extents
2412  * is built at swapon time and is then used at swap_writepage/swap_readpage
2413  * time for locating where on disk a page belongs.
2414  *
2415  * If the swapfile is an S_ISBLK block device, a single extent is installed.
2416  * This is done so that the main operating code can treat S_ISBLK and S_ISREG
2417  * swap files identically.
2418  *
2419  * Whether the swapdev is an S_ISREG file or an S_ISBLK blockdev, the swap
2420  * extent list operates in PAGE_SIZE disk blocks.  Both S_ISREG and S_ISBLK
2421  * swapfiles are handled *identically* after swapon time.
2422  *
2423  * For S_ISREG swapfiles, setup_swap_extents() will walk all the file's blocks
2424  * and will parse them into an ordered extent list, in PAGE_SIZE chunks.  If
2425  * some stray blocks are found which do not fall within the PAGE_SIZE alignment
2426  * requirements, they are simply tossed out - we will never use those blocks
2427  * for swapping.
2428  *
2429  * For all swap devices we set S_SWAPFILE across the life of the swapon.  This
2430  * prevents users from writing to the swap device, which will corrupt memory.
2431  *
2432  * The amount of disk space which a single swap extent represents varies.
2433  * Typically it is in the 1-4 megabyte range.  So we can have hundreds of
2434  * extents in the list.  To avoid much list walking, we cache the previous
2435  * search location in `curr_swap_extent', and start new searches from there.
2436  * This is extremely effective.  The average number of iterations in
2437  * map_swap_page() has been measured at about 0.3 per page.  - akpm.
2438  */
2439 static int setup_swap_extents(struct swap_info_struct *sis, sector_t *span)
2440 {
2441         struct file *swap_file = sis->swap_file;
2442         struct address_space *mapping = swap_file->f_mapping;
2443         struct inode *inode = mapping->host;
2444         int ret;
2445
2446         if (S_ISBLK(inode->i_mode)) {
2447                 ret = add_swap_extent(sis, 0, sis->max, 0);
2448                 *span = sis->pages;
2449                 return ret;
2450         }
2451
2452         if (mapping->a_ops->swap_activate) {
2453                 ret = mapping->a_ops->swap_activate(sis, swap_file, span);
2454                 if (ret >= 0)
2455                         sis->flags |= SWP_ACTIVATED;
2456                 if (!ret) {
2457                         sis->flags |= SWP_FS_OPS;
2458                         ret = add_swap_extent(sis, 0, sis->max, 0);
2459                         *span = sis->pages;
2460                 }
2461                 return ret;
2462         }
2463
2464         return generic_swapfile_activate(sis, swap_file, span);
2465 }
2466
2467 static int swap_node(struct swap_info_struct *p)
2468 {
2469         struct block_device *bdev;
2470
2471         if (p->bdev)
2472                 bdev = p->bdev;
2473         else
2474                 bdev = p->swap_file->f_inode->i_sb->s_bdev;
2475
2476         return bdev ? bdev->bd_disk->node_id : NUMA_NO_NODE;
2477 }
2478
2479 static void setup_swap_info(struct swap_info_struct *p, int prio,
2480                             unsigned char *swap_map,
2481                             struct swap_cluster_info *cluster_info)
2482 {
2483         int i;
2484
2485         if (prio >= 0)
2486                 p->prio = prio;
2487         else
2488                 p->prio = --least_priority;
2489         /*
2490          * the plist prio is negated because plist ordering is
2491          * low-to-high, while swap ordering is high-to-low
2492          */
2493         p->list.prio = -p->prio;
2494         for_each_node(i) {
2495                 if (p->prio >= 0)
2496                         p->avail_lists[i].prio = -p->prio;
2497                 else {
2498                         if (swap_node(p) == i)
2499                                 p->avail_lists[i].prio = 1;
2500                         else
2501                                 p->avail_lists[i].prio = -p->prio;
2502                 }
2503         }
2504         p->swap_map = swap_map;
2505         p->cluster_info = cluster_info;
2506 }
2507
2508 static void _enable_swap_info(struct swap_info_struct *p)
2509 {
2510         p->flags |= SWP_WRITEOK | SWP_VALID;
2511         atomic_long_add(p->pages, &nr_swap_pages);
2512         total_swap_pages += p->pages;
2513
2514         assert_spin_locked(&swap_lock);
2515         /*
2516          * both lists are plists, and thus priority ordered.
2517          * swap_active_head needs to be priority ordered for swapoff(),
2518          * which on removal of any swap_info_struct with an auto-assigned
2519          * (i.e. negative) priority increments the auto-assigned priority
2520          * of any lower-priority swap_info_structs.
2521          * swap_avail_head needs to be priority ordered for get_swap_page(),
2522          * which allocates swap pages from the highest available priority
2523          * swap_info_struct.
2524          */
2525         plist_add(&p->list, &swap_active_head);
2526         add_to_avail_list(p);
2527 }
2528
2529 static void enable_swap_info(struct swap_info_struct *p, int prio,
2530                                 unsigned char *swap_map,
2531                                 struct swap_cluster_info *cluster_info,
2532                                 unsigned long *frontswap_map)
2533 {
2534         frontswap_init(p->type, frontswap_map);
2535         spin_lock(&swap_lock);
2536         spin_lock(&p->lock);
2537         setup_swap_info(p, prio, swap_map, cluster_info);
2538         spin_unlock(&p->lock);
2539         spin_unlock(&swap_lock);
2540         /*
2541          * Guarantee swap_map, cluster_info, etc. fields are valid
2542          * between get/put_swap_device() if SWP_VALID bit is set
2543          */
2544         synchronize_rcu();
2545         spin_lock(&swap_lock);
2546         spin_lock(&p->lock);
2547         _enable_swap_info(p);
2548         spin_unlock(&p->lock);
2549         spin_unlock(&swap_lock);
2550 }
2551
2552 static void reinsert_swap_info(struct swap_info_struct *p)
2553 {
2554         spin_lock(&swap_lock);
2555         spin_lock(&p->lock);
2556         setup_swap_info(p, p->prio, p->swap_map, p->cluster_info);
2557         _enable_swap_info(p);
2558         spin_unlock(&p->lock);
2559         spin_unlock(&swap_lock);
2560 }
2561
2562 bool has_usable_swap(void)
2563 {
2564         bool ret = true;
2565
2566         spin_lock(&swap_lock);
2567         if (plist_head_empty(&swap_active_head))
2568                 ret = false;
2569         spin_unlock(&swap_lock);
2570         return ret;
2571 }
2572
2573 SYSCALL_DEFINE1(swapoff, const char __user *, specialfile)
2574 {
2575         struct swap_info_struct *p = NULL;
2576         unsigned char *swap_map;
2577         struct swap_cluster_info *cluster_info;
2578         unsigned long *frontswap_map;
2579         struct file *swap_file, *victim;
2580         struct address_space *mapping;
2581         struct inode *inode;
2582         struct filename *pathname;
2583         int err, found = 0;
2584         unsigned int old_block_size;
2585
2586         if (!capable(CAP_SYS_ADMIN))
2587                 return -EPERM;
2588
2589         BUG_ON(!current->mm);
2590
2591         pathname = getname(specialfile);
2592         if (IS_ERR(pathname))
2593                 return PTR_ERR(pathname);
2594
2595         victim = file_open_name(pathname, O_RDWR|O_LARGEFILE, 0);
2596         err = PTR_ERR(victim);
2597         if (IS_ERR(victim))
2598                 goto out;
2599
2600         mapping = victim->f_mapping;
2601         spin_lock(&swap_lock);
2602         plist_for_each_entry(p, &swap_active_head, list) {
2603                 if (p->flags & SWP_WRITEOK) {
2604                         if (p->swap_file->f_mapping == mapping) {
2605                                 found = 1;
2606                                 break;
2607                         }
2608                 }
2609         }
2610         if (!found) {
2611                 err = -EINVAL;
2612                 spin_unlock(&swap_lock);
2613                 goto out_dput;
2614         }
2615         if (!security_vm_enough_memory_mm(current->mm, p->pages))
2616                 vm_unacct_memory(p->pages);
2617         else {
2618                 err = -ENOMEM;
2619                 spin_unlock(&swap_lock);
2620                 goto out_dput;
2621         }
2622         del_from_avail_list(p);
2623         spin_lock(&p->lock);
2624         if (p->prio < 0) {
2625                 struct swap_info_struct *si = p;
2626                 int nid;
2627
2628                 plist_for_each_entry_continue(si, &swap_active_head, list) {
2629                         si->prio++;
2630                         si->list.prio--;
2631                         for_each_node(nid) {
2632                                 if (si->avail_lists[nid].prio != 1)
2633                                         si->avail_lists[nid].prio--;
2634                         }
2635                 }
2636                 least_priority++;
2637         }
2638         plist_del(&p->list, &swap_active_head);
2639         atomic_long_sub(p->pages, &nr_swap_pages);
2640         total_swap_pages -= p->pages;
2641         p->flags &= ~SWP_WRITEOK;
2642         spin_unlock(&p->lock);
2643         spin_unlock(&swap_lock);
2644
2645         disable_swap_slots_cache_lock();
2646
2647         set_current_oom_origin();
2648         err = try_to_unuse(p->type, false, 0); /* force unuse all pages */
2649         clear_current_oom_origin();
2650
2651         if (err) {
2652                 /* re-insert swap space back into swap_list */
2653                 reinsert_swap_info(p);
2654                 reenable_swap_slots_cache_unlock();
2655                 goto out_dput;
2656         }
2657
2658         reenable_swap_slots_cache_unlock();
2659
2660         spin_lock(&swap_lock);
2661         spin_lock(&p->lock);
2662         p->flags &= ~SWP_VALID;         /* mark swap device as invalid */
2663         spin_unlock(&p->lock);
2664         spin_unlock(&swap_lock);
2665         /*
2666          * wait for swap operations protected by get/put_swap_device()
2667          * to complete
2668          */
2669         synchronize_rcu();
2670
2671         flush_work(&p->discard_work);
2672
2673         destroy_swap_extents(p);
2674         if (p->flags & SWP_CONTINUED)
2675                 free_swap_count_continuations(p);
2676
2677         if (!p->bdev || !blk_queue_nonrot(bdev_get_queue(p->bdev)))
2678                 atomic_dec(&nr_rotate_swap);
2679
2680         mutex_lock(&swapon_mutex);
2681         spin_lock(&swap_lock);
2682         spin_lock(&p->lock);
2683         drain_mmlist();
2684
2685         /* wait for anyone still in scan_swap_map */
2686         p->highest_bit = 0;             /* cuts scans short */
2687         while (p->flags >= SWP_SCANNING) {
2688                 spin_unlock(&p->lock);
2689                 spin_unlock(&swap_lock);
2690                 schedule_timeout_uninterruptible(1);
2691                 spin_lock(&swap_lock);
2692                 spin_lock(&p->lock);
2693         }
2694
2695         swap_file = p->swap_file;
2696         old_block_size = p->old_block_size;
2697         p->swap_file = NULL;
2698         p->max = 0;
2699         swap_map = p->swap_map;
2700         p->swap_map = NULL;
2701         cluster_info = p->cluster_info;
2702         p->cluster_info = NULL;
2703         frontswap_map = frontswap_map_get(p);
2704         spin_unlock(&p->lock);
2705         spin_unlock(&swap_lock);
2706         arch_swap_invalidate_area(p->type);
2707         frontswap_invalidate_area(p->type);
2708         frontswap_map_set(p, NULL);
2709         mutex_unlock(&swapon_mutex);
2710         free_percpu(p->percpu_cluster);
2711         p->percpu_cluster = NULL;
2712         free_percpu(p->cluster_next_cpu);
2713         p->cluster_next_cpu = NULL;
2714         vfree(swap_map);
2715         kvfree(cluster_info);
2716         kvfree(frontswap_map);
2717         /* Destroy swap account information */
2718         swap_cgroup_swapoff(p->type);
2719         exit_swap_address_space(p->type);
2720
2721         inode = mapping->host;
2722         if (S_ISBLK(inode->i_mode)) {
2723                 struct block_device *bdev = I_BDEV(inode);
2724
2725                 set_blocksize(bdev, old_block_size);
2726                 blkdev_put(bdev, FMODE_READ | FMODE_WRITE | FMODE_EXCL);
2727         }
2728
2729         inode_lock(inode);
2730         inode->i_flags &= ~S_SWAPFILE;
2731         inode_unlock(inode);
2732         filp_close(swap_file, NULL);
2733
2734         /*
2735          * Clear the SWP_USED flag after all resources are freed so that swapon
2736          * can reuse this swap_info in alloc_swap_info() safely.  It is ok to
2737          * not hold p->lock after we cleared its SWP_WRITEOK.
2738          */
2739         spin_lock(&swap_lock);
2740         p->flags = 0;
2741         spin_unlock(&swap_lock);
2742
2743         err = 0;
2744         atomic_inc(&proc_poll_event);
2745         wake_up_interruptible(&proc_poll_wait);
2746
2747 out_dput:
2748         filp_close(victim, NULL);
2749 out:
2750         putname(pathname);
2751         return err;
2752 }
2753
2754 #ifdef CONFIG_PROC_FS
2755 static __poll_t swaps_poll(struct file *file, poll_table *wait)
2756 {
2757         struct seq_file *seq = file->private_data;
2758
2759         poll_wait(file, &proc_poll_wait, wait);
2760
2761         if (seq->poll_event != atomic_read(&proc_poll_event)) {
2762                 seq->poll_event = atomic_read(&proc_poll_event);
2763                 return EPOLLIN | EPOLLRDNORM | EPOLLERR | EPOLLPRI;
2764         }
2765
2766         return EPOLLIN | EPOLLRDNORM;
2767 }
2768
2769 /* iterator */
2770 static void *swap_start(struct seq_file *swap, loff_t *pos)
2771 {
2772         struct swap_info_struct *si;
2773         int type;
2774         loff_t l = *pos;
2775
2776         mutex_lock(&swapon_mutex);
2777
2778         if (!l)
2779                 return SEQ_START_TOKEN;
2780
2781         for (type = 0; (si = swap_type_to_swap_info(type)); type++) {
2782                 if (!(si->flags & SWP_USED) || !si->swap_map)
2783                         continue;
2784                 if (!--l)
2785                         return si;
2786         }
2787
2788         return NULL;
2789 }
2790
2791 static void *swap_next(struct seq_file *swap, void *v, loff_t *pos)
2792 {
2793         struct swap_info_struct *si = v;
2794         int type;
2795
2796         if (v == SEQ_START_TOKEN)
2797                 type = 0;
2798         else
2799                 type = si->type + 1;
2800
2801         ++(*pos);
2802         for (; (si = swap_type_to_swap_info(type)); type++) {
2803                 if (!(si->flags & SWP_USED) || !si->swap_map)
2804                         continue;
2805                 return si;
2806         }
2807
2808         return NULL;
2809 }
2810
2811 static void swap_stop(struct seq_file *swap, void *v)
2812 {
2813         mutex_unlock(&swapon_mutex);
2814 }
2815
2816 static int swap_show(struct seq_file *swap, void *v)
2817 {
2818         struct swap_info_struct *si = v;
2819         struct file *file;
2820         int len;
2821         unsigned int bytes, inuse;
2822
2823         if (si == SEQ_START_TOKEN) {
2824                 seq_puts(swap,"Filename\t\t\t\tType\t\tSize\t\tUsed\t\tPriority\n");
2825                 return 0;
2826         }
2827
2828         bytes = si->pages << (PAGE_SHIFT - 10);
2829         inuse = si->inuse_pages << (PAGE_SHIFT - 10);
2830
2831         file = si->swap_file;
2832         len = seq_file_path(swap, file, " \t\n\\");
2833         seq_printf(swap, "%*s%s\t%u\t%s%u\t%s%d\n",
2834                         len < 40 ? 40 - len : 1, " ",
2835                         S_ISBLK(file_inode(file)->i_mode) ?
2836                                 "partition" : "file\t",
2837                         bytes, bytes < 10000000 ? "\t" : "",
2838                         inuse, inuse < 10000000 ? "\t" : "",
2839                         si->prio);
2840         return 0;
2841 }
2842
2843 static const struct seq_operations swaps_op = {
2844         .start =        swap_start,
2845         .next =         swap_next,
2846         .stop =         swap_stop,
2847         .show =         swap_show
2848 };
2849
2850 static int swaps_open(struct inode *inode, struct file *file)
2851 {
2852         struct seq_file *seq;
2853         int ret;
2854
2855         ret = seq_open(file, &swaps_op);
2856         if (ret)
2857                 return ret;
2858
2859         seq = file->private_data;
2860         seq->poll_event = atomic_read(&proc_poll_event);
2861         return 0;
2862 }
2863
2864 static const struct proc_ops swaps_proc_ops = {
2865         .proc_flags     = PROC_ENTRY_PERMANENT,
2866         .proc_open      = swaps_open,
2867         .proc_read      = seq_read,
2868         .proc_lseek     = seq_lseek,
2869         .proc_release   = seq_release,
2870         .proc_poll      = swaps_poll,
2871 };
2872
2873 static int __init procswaps_init(void)
2874 {
2875         proc_create("swaps", 0, NULL, &swaps_proc_ops);
2876         return 0;
2877 }
2878 __initcall(procswaps_init);
2879 #endif /* CONFIG_PROC_FS */
2880
2881 #ifdef MAX_SWAPFILES_CHECK
2882 static int __init max_swapfiles_check(void)
2883 {
2884         MAX_SWAPFILES_CHECK();
2885         return 0;
2886 }
2887 late_initcall(max_swapfiles_check);
2888 #endif
2889
2890 static struct swap_info_struct *alloc_swap_info(void)
2891 {
2892         struct swap_info_struct *p;
2893         struct swap_info_struct *defer = NULL;
2894         unsigned int type;
2895         int i;
2896
2897         p = kvzalloc(struct_size(p, avail_lists, nr_node_ids), GFP_KERNEL);
2898         if (!p)
2899                 return ERR_PTR(-ENOMEM);
2900
2901         spin_lock(&swap_lock);
2902         for (type = 0; type < nr_swapfiles; type++) {
2903                 if (!(swap_info[type]->flags & SWP_USED))
2904                         break;
2905         }
2906         if (type >= MAX_SWAPFILES) {
2907                 spin_unlock(&swap_lock);
2908                 kvfree(p);
2909                 return ERR_PTR(-EPERM);
2910         }
2911         if (type >= nr_swapfiles) {
2912                 p->type = type;
2913                 WRITE_ONCE(swap_info[type], p);
2914                 /*
2915                  * Write swap_info[type] before nr_swapfiles, in case a
2916                  * racing procfs swap_start() or swap_next() is reading them.
2917                  * (We never shrink nr_swapfiles, we never free this entry.)
2918                  */
2919                 smp_wmb();
2920                 WRITE_ONCE(nr_swapfiles, nr_swapfiles + 1);
2921         } else {
2922                 defer = p;
2923                 p = swap_info[type];
2924                 /*
2925                  * Do not memset this entry: a racing procfs swap_next()
2926                  * would be relying on p->type to remain valid.
2927                  */
2928         }
2929         p->swap_extent_root = RB_ROOT;
2930         plist_node_init(&p->list, 0);
2931         for_each_node(i)
2932                 plist_node_init(&p->avail_lists[i], 0);
2933         p->flags = SWP_USED;
2934         spin_unlock(&swap_lock);
2935         kvfree(defer);
2936         spin_lock_init(&p->lock);
2937         spin_lock_init(&p->cont_lock);
2938
2939         return p;
2940 }
2941
2942 static int claim_swapfile(struct swap_info_struct *p, struct inode *inode)
2943 {
2944         int error;
2945
2946         if (S_ISBLK(inode->i_mode)) {
2947                 p->bdev = blkdev_get_by_dev(inode->i_rdev,
2948                                    FMODE_READ | FMODE_WRITE | FMODE_EXCL, p);
2949                 if (IS_ERR(p->bdev)) {
2950                         error = PTR_ERR(p->bdev);
2951                         p->bdev = NULL;
2952                         return error;
2953                 }
2954                 p->old_block_size = block_size(p->bdev);
2955                 error = set_blocksize(p->bdev, PAGE_SIZE);
2956                 if (error < 0)
2957                         return error;
2958                 /*
2959                  * Zoned block devices contain zones that have a sequential
2960                  * write only restriction.  Hence zoned block devices are not
2961                  * suitable for swapping.  Disallow them here.
2962                  */
2963                 if (blk_queue_is_zoned(p->bdev->bd_disk->queue))
2964                         return -EINVAL;
2965                 p->flags |= SWP_BLKDEV;
2966         } else if (S_ISREG(inode->i_mode)) {
2967                 p->bdev = inode->i_sb->s_bdev;
2968         }
2969
2970         return 0;
2971 }
2972
2973
2974 /*
2975  * Find out how many pages are allowed for a single swap device. There
2976  * are two limiting factors:
2977  * 1) the number of bits for the swap offset in the swp_entry_t type, and
2978  * 2) the number of bits in the swap pte, as defined by the different
2979  * architectures.
2980  *
2981  * In order to find the largest possible bit mask, a swap entry with
2982  * swap type 0 and swap offset ~0UL is created, encoded to a swap pte,
2983  * decoded to a swp_entry_t again, and finally the swap offset is
2984  * extracted.
2985  *
2986  * This will mask all the bits from the initial ~0UL mask that can't
2987  * be encoded in either the swp_entry_t or the architecture definition
2988  * of a swap pte.
2989  */
2990 unsigned long generic_max_swapfile_size(void)
2991 {
2992         return swp_offset(pte_to_swp_entry(
2993                         swp_entry_to_pte(swp_entry(0, ~0UL)))) + 1;
2994 }
2995
2996 /* Can be overridden by an architecture for additional checks. */
2997 __weak unsigned long max_swapfile_size(void)
2998 {
2999         return generic_max_swapfile_size();
3000 }
3001
3002 static unsigned long read_swap_header(struct swap_info_struct *p,
3003                                         union swap_header *swap_header,
3004                                         struct inode *inode)
3005 {
3006         int i;
3007         unsigned long maxpages;
3008         unsigned long swapfilepages;
3009         unsigned long last_page;
3010
3011         if (memcmp("SWAPSPACE2", swap_header->magic.magic, 10)) {
3012                 pr_err("Unable to find swap-space signature\n");
3013                 return 0;
3014         }
3015
3016         /* swap partition endianess hack... */
3017         if (swab32(swap_header->info.version) == 1) {
3018                 swab32s(&swap_header->info.version);
3019                 swab32s(&swap_header->info.last_page);
3020                 swab32s(&swap_header->info.nr_badpages);
3021                 if (swap_header->info.nr_badpages > MAX_SWAP_BADPAGES)
3022                         return 0;
3023                 for (i = 0; i < swap_header->info.nr_badpages; i++)
3024                         swab32s(&swap_header->info.badpages[i]);
3025         }
3026         /* Check the swap header's sub-version */
3027         if (swap_header->info.version != 1) {
3028                 pr_warn("Unable to handle swap header version %d\n",
3029                         swap_header->info.version);
3030                 return 0;
3031         }
3032
3033         p->lowest_bit  = 1;
3034         p->cluster_next = 1;
3035         p->cluster_nr = 0;
3036
3037         maxpages = max_swapfile_size();
3038         last_page = swap_header->info.last_page;
3039         if (!last_page) {
3040                 pr_warn("Empty swap-file\n");
3041                 return 0;
3042         }
3043         if (last_page > maxpages) {
3044                 pr_warn("Truncating oversized swap area, only using %luk out of %luk\n",
3045                         maxpages << (PAGE_SHIFT - 10),
3046                         last_page << (PAGE_SHIFT - 10));
3047         }
3048         if (maxpages > last_page) {
3049                 maxpages = last_page + 1;
3050                 /* p->max is an unsigned int: don't overflow it */
3051                 if ((unsigned int)maxpages == 0)
3052                         maxpages = UINT_MAX;
3053         }
3054         p->highest_bit = maxpages - 1;
3055
3056         if (!maxpages)
3057                 return 0;
3058         swapfilepages = i_size_read(inode) >> PAGE_SHIFT;
3059         if (swapfilepages && maxpages > swapfilepages) {
3060                 pr_warn("Swap area shorter than signature indicates\n");
3061                 return 0;
3062         }
3063         if (swap_header->info.nr_badpages && S_ISREG(inode->i_mode))
3064                 return 0;
3065         if (swap_header->info.nr_badpages > MAX_SWAP_BADPAGES)
3066                 return 0;
3067
3068         return maxpages;
3069 }
3070
3071 #define SWAP_CLUSTER_INFO_COLS                                          \
3072         DIV_ROUND_UP(L1_CACHE_BYTES, sizeof(struct swap_cluster_info))
3073 #define SWAP_CLUSTER_SPACE_COLS                                         \
3074         DIV_ROUND_UP(SWAP_ADDRESS_SPACE_PAGES, SWAPFILE_CLUSTER)
3075 #define SWAP_CLUSTER_COLS                                               \
3076         max_t(unsigned int, SWAP_CLUSTER_INFO_COLS, SWAP_CLUSTER_SPACE_COLS)
3077
3078 static int setup_swap_map_and_extents(struct swap_info_struct *p,
3079                                         union swap_header *swap_header,
3080                                         unsigned char *swap_map,
3081                                         struct swap_cluster_info *cluster_info,
3082                                         unsigned long maxpages,
3083                                         sector_t *span)
3084 {
3085         unsigned int j, k;
3086         unsigned int nr_good_pages;
3087         int nr_extents;
3088         unsigned long nr_clusters = DIV_ROUND_UP(maxpages, SWAPFILE_CLUSTER);
3089         unsigned long col = p->cluster_next / SWAPFILE_CLUSTER % SWAP_CLUSTER_COLS;
3090         unsigned long i, idx;
3091
3092         nr_good_pages = maxpages - 1;   /* omit header page */
3093
3094         cluster_list_init(&p->free_clusters);
3095         cluster_list_init(&p->discard_clusters);
3096
3097         for (i = 0; i < swap_header->info.nr_badpages; i++) {
3098                 unsigned int page_nr = swap_header->info.badpages[i];
3099                 if (page_nr == 0 || page_nr > swap_header->info.last_page)
3100                         return -EINVAL;
3101                 if (page_nr < maxpages) {
3102                         swap_map[page_nr] = SWAP_MAP_BAD;
3103                         nr_good_pages--;
3104                         /*
3105                          * Haven't marked the cluster free yet, no list
3106                          * operation involved
3107                          */
3108                         inc_cluster_info_page(p, cluster_info, page_nr);
3109                 }
3110         }
3111
3112         /* Haven't marked the cluster free yet, no list operation involved */
3113         for (i = maxpages; i < round_up(maxpages, SWAPFILE_CLUSTER); i++)
3114                 inc_cluster_info_page(p, cluster_info, i);
3115
3116         if (nr_good_pages) {
3117                 swap_map[0] = SWAP_MAP_BAD;
3118                 /*
3119                  * Not mark the cluster free yet, no list
3120                  * operation involved
3121                  */
3122                 inc_cluster_info_page(p, cluster_info, 0);
3123                 p->max = maxpages;
3124                 p->pages = nr_good_pages;
3125                 nr_extents = setup_swap_extents(p, span);
3126                 if (nr_extents < 0)
3127                         return nr_extents;
3128                 nr_good_pages = p->pages;
3129         }
3130         if (!nr_good_pages) {
3131                 pr_warn("Empty swap-file\n");
3132                 return -EINVAL;
3133         }
3134
3135         if (!cluster_info)
3136                 return nr_extents;
3137
3138
3139         /*
3140          * Reduce false cache line sharing between cluster_info and
3141          * sharing same address space.
3142          */
3143         for (k = 0; k < SWAP_CLUSTER_COLS; k++) {
3144                 j = (k + col) % SWAP_CLUSTER_COLS;
3145                 for (i = 0; i < DIV_ROUND_UP(nr_clusters, SWAP_CLUSTER_COLS); i++) {
3146                         idx = i * SWAP_CLUSTER_COLS + j;
3147                         if (idx >= nr_clusters)
3148                                 continue;
3149                         if (cluster_count(&cluster_info[idx]))
3150                                 continue;
3151                         cluster_set_flag(&cluster_info[idx], CLUSTER_FLAG_FREE);
3152                         cluster_list_add_tail(&p->free_clusters, cluster_info,
3153                                               idx);
3154                 }
3155         }
3156         return nr_extents;
3157 }
3158
3159 /*
3160  * Helper to sys_swapon determining if a given swap
3161  * backing device queue supports DISCARD operations.
3162  */
3163 static bool swap_discardable(struct swap_info_struct *si)
3164 {
3165         struct request_queue *q = bdev_get_queue(si->bdev);
3166
3167         if (!q || !blk_queue_discard(q))
3168                 return false;
3169
3170         return true;
3171 }
3172
3173 SYSCALL_DEFINE2(swapon, const char __user *, specialfile, int, swap_flags)
3174 {
3175         struct swap_info_struct *p;
3176         struct filename *name;
3177         struct file *swap_file = NULL;
3178         struct address_space *mapping;
3179         int prio;
3180         int error;
3181         union swap_header *swap_header;
3182         int nr_extents;
3183         sector_t span;
3184         unsigned long maxpages;
3185         unsigned char *swap_map = NULL;
3186         struct swap_cluster_info *cluster_info = NULL;
3187         unsigned long *frontswap_map = NULL;
3188         struct page *page = NULL;
3189         struct inode *inode = NULL;
3190         bool inced_nr_rotate_swap = false;
3191
3192         if (swap_flags & ~SWAP_FLAGS_VALID)
3193                 return -EINVAL;
3194
3195         if (!capable(CAP_SYS_ADMIN))
3196                 return -EPERM;
3197
3198         if (!swap_avail_heads)
3199                 return -ENOMEM;
3200
3201         p = alloc_swap_info();
3202         if (IS_ERR(p))
3203                 return PTR_ERR(p);
3204
3205         INIT_WORK(&p->discard_work, swap_discard_work);
3206
3207         name = getname(specialfile);
3208         if (IS_ERR(name)) {
3209                 error = PTR_ERR(name);
3210                 name = NULL;
3211                 goto bad_swap;
3212         }
3213         swap_file = file_open_name(name, O_RDWR|O_LARGEFILE, 0);
3214         if (IS_ERR(swap_file)) {
3215                 error = PTR_ERR(swap_file);
3216                 swap_file = NULL;
3217                 goto bad_swap;
3218         }
3219
3220         p->swap_file = swap_file;
3221         mapping = swap_file->f_mapping;
3222         inode = mapping->host;
3223
3224         error = claim_swapfile(p, inode);
3225         if (unlikely(error))
3226                 goto bad_swap;
3227
3228         inode_lock(inode);
3229         if (IS_SWAPFILE(inode)) {
3230                 error = -EBUSY;
3231                 goto bad_swap_unlock_inode;
3232         }
3233
3234         /*
3235          * Read the swap header.
3236          */
3237         if (!mapping->a_ops->readpage) {
3238                 error = -EINVAL;
3239                 goto bad_swap_unlock_inode;
3240         }
3241         page = read_mapping_page(mapping, 0, swap_file);
3242         if (IS_ERR(page)) {
3243                 error = PTR_ERR(page);
3244                 goto bad_swap_unlock_inode;
3245         }
3246         swap_header = kmap(page);
3247
3248         maxpages = read_swap_header(p, swap_header, inode);
3249         if (unlikely(!maxpages)) {
3250                 error = -EINVAL;
3251                 goto bad_swap_unlock_inode;
3252         }
3253
3254         /* OK, set up the swap map and apply the bad block list */
3255         swap_map = vzalloc(maxpages);
3256         if (!swap_map) {
3257                 error = -ENOMEM;
3258                 goto bad_swap_unlock_inode;
3259         }
3260
3261         if (p->bdev && blk_queue_stable_writes(p->bdev->bd_disk->queue))
3262                 p->flags |= SWP_STABLE_WRITES;
3263
3264         if (p->bdev && p->bdev->bd_disk->fops->rw_page)
3265                 p->flags |= SWP_SYNCHRONOUS_IO;
3266
3267         if (p->bdev && blk_queue_nonrot(bdev_get_queue(p->bdev))) {
3268                 int cpu;
3269                 unsigned long ci, nr_cluster;
3270
3271                 p->flags |= SWP_SOLIDSTATE;
3272                 p->cluster_next_cpu = alloc_percpu(unsigned int);
3273                 if (!p->cluster_next_cpu) {
3274                         error = -ENOMEM;
3275                         goto bad_swap_unlock_inode;
3276                 }
3277                 /*
3278                  * select a random position to start with to help wear leveling
3279                  * SSD
3280                  */
3281                 for_each_possible_cpu(cpu) {
3282                         per_cpu(*p->cluster_next_cpu, cpu) =
3283                                 1 + prandom_u32_max(p->highest_bit);
3284                 }
3285                 nr_cluster = DIV_ROUND_UP(maxpages, SWAPFILE_CLUSTER);
3286
3287                 cluster_info = kvcalloc(nr_cluster, sizeof(*cluster_info),
3288                                         GFP_KERNEL);
3289                 if (!cluster_info) {
3290                         error = -ENOMEM;
3291                         goto bad_swap_unlock_inode;
3292                 }
3293
3294                 for (ci = 0; ci < nr_cluster; ci++)
3295                         spin_lock_init(&((cluster_info + ci)->lock));
3296
3297                 p->percpu_cluster = alloc_percpu(struct percpu_cluster);
3298                 if (!p->percpu_cluster) {
3299                         error = -ENOMEM;
3300                         goto bad_swap_unlock_inode;
3301                 }
3302                 for_each_possible_cpu(cpu) {
3303                         struct percpu_cluster *cluster;
3304                         cluster = per_cpu_ptr(p->percpu_cluster, cpu);
3305                         cluster_set_null(&cluster->index);
3306                 }
3307         } else {
3308                 atomic_inc(&nr_rotate_swap);
3309                 inced_nr_rotate_swap = true;
3310         }
3311
3312         error = swap_cgroup_swapon(p->type, maxpages);
3313         if (error)
3314                 goto bad_swap_unlock_inode;
3315
3316         nr_extents = setup_swap_map_and_extents(p, swap_header, swap_map,
3317                 cluster_info, maxpages, &span);
3318         if (unlikely(nr_extents < 0)) {
3319                 error = nr_extents;
3320                 goto bad_swap_unlock_inode;
3321         }
3322         /* frontswap enabled? set up bit-per-page map for frontswap */
3323         if (IS_ENABLED(CONFIG_FRONTSWAP))
3324                 frontswap_map = kvcalloc(BITS_TO_LONGS(maxpages),
3325                                          sizeof(long),
3326                                          GFP_KERNEL);
3327
3328         if (p->bdev &&(swap_flags & SWAP_FLAG_DISCARD) && swap_discardable(p)) {
3329                 /*
3330                  * When discard is enabled for swap with no particular
3331                  * policy flagged, we set all swap discard flags here in
3332                  * order to sustain backward compatibility with older
3333                  * swapon(8) releases.
3334                  */
3335                 p->flags |= (SWP_DISCARDABLE | SWP_AREA_DISCARD |
3336                              SWP_PAGE_DISCARD);
3337
3338                 /*
3339                  * By flagging sys_swapon, a sysadmin can tell us to
3340                  * either do single-time area discards only, or to just
3341                  * perform discards for released swap page-clusters.
3342                  * Now it's time to adjust the p->flags accordingly.
3343                  */
3344                 if (swap_flags & SWAP_FLAG_DISCARD_ONCE)
3345                         p->flags &= ~SWP_PAGE_DISCARD;
3346                 else if (swap_flags & SWAP_FLAG_DISCARD_PAGES)
3347                         p->flags &= ~SWP_AREA_DISCARD;
3348
3349                 /* issue a swapon-time discard if it's still required */
3350                 if (p->flags & SWP_AREA_DISCARD) {
3351                         int err = discard_swap(p);
3352                         if (unlikely(err))
3353                                 pr_err("swapon: discard_swap(%p): %d\n",
3354                                         p, err);
3355                 }
3356         }
3357
3358         error = init_swap_address_space(p->type, maxpages);
3359         if (error)
3360                 goto bad_swap_unlock_inode;
3361
3362         /*
3363          * Flush any pending IO and dirty mappings before we start using this
3364          * swap device.
3365          */
3366         inode->i_flags |= S_SWAPFILE;
3367         error = inode_drain_writes(inode);
3368         if (error) {
3369                 inode->i_flags &= ~S_SWAPFILE;
3370                 goto free_swap_address_space;
3371         }
3372
3373         mutex_lock(&swapon_mutex);
3374         prio = -1;
3375         if (swap_flags & SWAP_FLAG_PREFER)
3376                 prio =
3377                   (swap_flags & SWAP_FLAG_PRIO_MASK) >> SWAP_FLAG_PRIO_SHIFT;
3378         enable_swap_info(p, prio, swap_map, cluster_info, frontswap_map);
3379
3380         pr_info("Adding %uk swap on %s.  Priority:%d extents:%d across:%lluk %s%s%s%s%s\n",
3381                 p->pages<<(PAGE_SHIFT-10), name->name, p->prio,
3382                 nr_extents, (unsigned long long)span<<(PAGE_SHIFT-10),
3383                 (p->flags & SWP_SOLIDSTATE) ? "SS" : "",
3384                 (p->flags & SWP_DISCARDABLE) ? "D" : "",
3385                 (p->flags & SWP_AREA_DISCARD) ? "s" : "",
3386                 (p->flags & SWP_PAGE_DISCARD) ? "c" : "",
3387                 (frontswap_map) ? "FS" : "");
3388
3389         mutex_unlock(&swapon_mutex);
3390         atomic_inc(&proc_poll_event);
3391         wake_up_interruptible(&proc_poll_wait);
3392
3393         error = 0;
3394         goto out;
3395 free_swap_address_space:
3396         exit_swap_address_space(p->type);
3397 bad_swap_unlock_inode:
3398         inode_unlock(inode);
3399 bad_swap:
3400         free_percpu(p->percpu_cluster);
3401         p->percpu_cluster = NULL;
3402         free_percpu(p->cluster_next_cpu);
3403         p->cluster_next_cpu = NULL;
3404         if (inode && S_ISBLK(inode->i_mode) && p->bdev) {
3405                 set_blocksize(p->bdev, p->old_block_size);
3406                 blkdev_put(p->bdev, FMODE_READ | FMODE_WRITE | FMODE_EXCL);
3407         }
3408         inode = NULL;
3409         destroy_swap_extents(p);
3410         swap_cgroup_swapoff(p->type);
3411         spin_lock(&swap_lock);
3412         p->swap_file = NULL;
3413         p->flags = 0;
3414         spin_unlock(&swap_lock);
3415         vfree(swap_map);
3416         kvfree(cluster_info);
3417         kvfree(frontswap_map);
3418         if (inced_nr_rotate_swap)
3419                 atomic_dec(&nr_rotate_swap);
3420         if (swap_file)
3421                 filp_close(swap_file, NULL);
3422 out:
3423         if (page && !IS_ERR(page)) {
3424                 kunmap(page);
3425                 put_page(page);
3426         }
3427         if (name)
3428                 putname(name);
3429         if (inode)
3430                 inode_unlock(inode);
3431         if (!error)
3432                 enable_swap_slots_cache();
3433         return error;
3434 }
3435
3436 void si_swapinfo(struct sysinfo *val)
3437 {
3438         unsigned int type;
3439         unsigned long nr_to_be_unused = 0;
3440
3441         spin_lock(&swap_lock);
3442         for (type = 0; type < nr_swapfiles; type++) {
3443                 struct swap_info_struct *si = swap_info[type];
3444
3445                 if ((si->flags & SWP_USED) && !(si->flags & SWP_WRITEOK))
3446                         nr_to_be_unused += si->inuse_pages;
3447         }
3448         val->freeswap = atomic_long_read(&nr_swap_pages) + nr_to_be_unused;
3449         val->totalswap = total_swap_pages + nr_to_be_unused;
3450         spin_unlock(&swap_lock);
3451 }
3452
3453 /*
3454  * Verify that a swap entry is valid and increment its swap map count.
3455  *
3456  * Returns error code in following case.
3457  * - success -> 0
3458  * - swp_entry is invalid -> EINVAL
3459  * - swp_entry is migration entry -> EINVAL
3460  * - swap-cache reference is requested but there is already one. -> EEXIST
3461  * - swap-cache reference is requested but the entry is not used. -> ENOENT
3462  * - swap-mapped reference requested but needs continued swap count. -> ENOMEM
3463  */
3464 static int __swap_duplicate(swp_entry_t entry, unsigned char usage)
3465 {
3466         struct swap_info_struct *p;
3467         struct swap_cluster_info *ci;
3468         unsigned long offset;
3469         unsigned char count;
3470         unsigned char has_cache;
3471         int err = -EINVAL;
3472
3473         p = get_swap_device(entry);
3474         if (!p)
3475                 goto out;
3476
3477         offset = swp_offset(entry);
3478         ci = lock_cluster_or_swap_info(p, offset);
3479
3480         count = p->swap_map[offset];
3481
3482         /*
3483          * swapin_readahead() doesn't check if a swap entry is valid, so the
3484          * swap entry could be SWAP_MAP_BAD. Check here with lock held.
3485          */
3486         if (unlikely(swap_count(count) == SWAP_MAP_BAD)) {
3487                 err = -ENOENT;
3488                 goto unlock_out;
3489         }
3490
3491         has_cache = count & SWAP_HAS_CACHE;
3492         count &= ~SWAP_HAS_CACHE;
3493         err = 0;
3494
3495         if (usage == SWAP_HAS_CACHE) {
3496
3497                 /* set SWAP_HAS_CACHE if there is no cache and entry is used */
3498                 if (!has_cache && count)
3499                         has_cache = SWAP_HAS_CACHE;
3500                 else if (has_cache)             /* someone else added cache */
3501                         err = -EEXIST;
3502                 else                            /* no users remaining */
3503                         err = -ENOENT;
3504
3505         } else if (count || has_cache) {
3506
3507                 if ((count & ~COUNT_CONTINUED) < SWAP_MAP_MAX)
3508                         count += usage;
3509                 else if ((count & ~COUNT_CONTINUED) > SWAP_MAP_MAX)
3510                         err = -EINVAL;
3511                 else if (swap_count_continued(p, offset, count))
3512                         count = COUNT_CONTINUED;
3513                 else
3514                         err = -ENOMEM;
3515         } else
3516                 err = -ENOENT;                  /* unused swap entry */
3517
3518         WRITE_ONCE(p->swap_map[offset], count | has_cache);
3519
3520 unlock_out:
3521         unlock_cluster_or_swap_info(p, ci);
3522 out:
3523         if (p)
3524                 put_swap_device(p);
3525         return err;
3526 }
3527
3528 /*
3529  * Help swapoff by noting that swap entry belongs to shmem/tmpfs
3530  * (in which case its reference count is never incremented).
3531  */
3532 void swap_shmem_alloc(swp_entry_t entry)
3533 {
3534         __swap_duplicate(entry, SWAP_MAP_SHMEM);
3535 }
3536
3537 /*
3538  * Increase reference count of swap entry by 1.
3539  * Returns 0 for success, or -ENOMEM if a swap_count_continuation is required
3540  * but could not be atomically allocated.  Returns 0, just as if it succeeded,
3541  * if __swap_duplicate() fails for another reason (-EINVAL or -ENOENT), which
3542  * might occur if a page table entry has got corrupted.
3543  */
3544 int swap_duplicate(swp_entry_t entry)
3545 {
3546         int err = 0;
3547
3548         while (!err && __swap_duplicate(entry, 1) == -ENOMEM)
3549                 err = add_swap_count_continuation(entry, GFP_ATOMIC);
3550         return err;
3551 }
3552
3553 /*
3554  * @entry: swap entry for which we allocate swap cache.
3555  *
3556  * Called when allocating swap cache for existing swap entry,
3557  * This can return error codes. Returns 0 at success.
3558  * -EEXIST means there is a swap cache.
3559  * Note: return code is different from swap_duplicate().
3560  */
3561 int swapcache_prepare(swp_entry_t entry)
3562 {
3563         return __swap_duplicate(entry, SWAP_HAS_CACHE);
3564 }
3565
3566 struct swap_info_struct *swp_swap_info(swp_entry_t entry)
3567 {
3568         return swap_type_to_swap_info(swp_type(entry));
3569 }
3570
3571 struct swap_info_struct *page_swap_info(struct page *page)
3572 {
3573         swp_entry_t entry = { .val = page_private(page) };
3574         return swp_swap_info(entry);
3575 }
3576
3577 /*
3578  * out-of-line __page_file_ methods to avoid include hell.
3579  */
3580 struct address_space *__page_file_mapping(struct page *page)
3581 {
3582         return page_swap_info(page)->swap_file->f_mapping;
3583 }
3584 EXPORT_SYMBOL_GPL(__page_file_mapping);
3585
3586 pgoff_t __page_file_index(struct page *page)
3587 {
3588         swp_entry_t swap = { .val = page_private(page) };
3589         return swp_offset(swap);
3590 }
3591 EXPORT_SYMBOL_GPL(__page_file_index);
3592
3593 /*
3594  * add_swap_count_continuation - called when a swap count is duplicated
3595  * beyond SWAP_MAP_MAX, it allocates a new page and links that to the entry's
3596  * page of the original vmalloc'ed swap_map, to hold the continuation count
3597  * (for that entry and for its neighbouring PAGE_SIZE swap entries).  Called
3598  * again when count is duplicated beyond SWAP_MAP_MAX * SWAP_CONT_MAX, etc.
3599  *
3600  * These continuation pages are seldom referenced: the common paths all work
3601  * on the original swap_map, only referring to a continuation page when the
3602  * low "digit" of a count is incremented or decremented through SWAP_MAP_MAX.
3603  *
3604  * add_swap_count_continuation(, GFP_ATOMIC) can be called while holding
3605  * page table locks; if it fails, add_swap_count_continuation(, GFP_KERNEL)
3606  * can be called after dropping locks.
3607  */
3608 int add_swap_count_continuation(swp_entry_t entry, gfp_t gfp_mask)
3609 {
3610         struct swap_info_struct *si;
3611         struct swap_cluster_info *ci;
3612         struct page *head;
3613         struct page *page;
3614         struct page *list_page;
3615         pgoff_t offset;
3616         unsigned char count;
3617         int ret = 0;
3618
3619         /*
3620          * When debugging, it's easier to use __GFP_ZERO here; but it's better
3621          * for latency not to zero a page while GFP_ATOMIC and holding locks.
3622          */
3623         page = alloc_page(gfp_mask | __GFP_HIGHMEM);
3624
3625         si = get_swap_device(entry);
3626         if (!si) {
3627                 /*
3628                  * An acceptable race has occurred since the failing
3629                  * __swap_duplicate(): the swap device may be swapoff
3630                  */
3631                 goto outer;
3632         }
3633         spin_lock(&si->lock);
3634
3635         offset = swp_offset(entry);
3636
3637         ci = lock_cluster(si, offset);
3638
3639         count = si->swap_map[offset] & ~SWAP_HAS_CACHE;
3640
3641         if ((count & ~COUNT_CONTINUED) != SWAP_MAP_MAX) {
3642                 /*
3643                  * The higher the swap count, the more likely it is that tasks
3644                  * will race to add swap count continuation: we need to avoid
3645                  * over-provisioning.
3646                  */
3647                 goto out;
3648         }
3649
3650         if (!page) {
3651                 ret = -ENOMEM;
3652                 goto out;
3653         }
3654
3655         /*
3656          * We are fortunate that although vmalloc_to_page uses pte_offset_map,
3657          * no architecture is using highmem pages for kernel page tables: so it
3658          * will not corrupt the GFP_ATOMIC caller's atomic page table kmaps.
3659          */
3660         head = vmalloc_to_page(si->swap_map + offset);
3661         offset &= ~PAGE_MASK;
3662
3663         spin_lock(&si->cont_lock);
3664         /*
3665          * Page allocation does not initialize the page's lru field,
3666          * but it does always reset its private field.
3667          */
3668         if (!page_private(head)) {
3669                 BUG_ON(count & COUNT_CONTINUED);
3670                 INIT_LIST_HEAD(&head->lru);
3671                 set_page_private(head, SWP_CONTINUED);
3672                 si->flags |= SWP_CONTINUED;
3673         }
3674
3675         list_for_each_entry(list_page, &head->lru, lru) {
3676                 unsigned char *map;
3677
3678                 /*
3679                  * If the previous map said no continuation, but we've found
3680                  * a continuation page, free our allocation and use this one.
3681                  */
3682                 if (!(count & COUNT_CONTINUED))
3683                         goto out_unlock_cont;
3684
3685                 map = kmap_atomic(list_page) + offset;
3686                 count = *map;
3687                 kunmap_atomic(map);
3688
3689                 /*
3690                  * If this continuation count now has some space in it,
3691                  * free our allocation and use this one.
3692                  */
3693                 if ((count & ~COUNT_CONTINUED) != SWAP_CONT_MAX)
3694                         goto out_unlock_cont;
3695         }
3696
3697         list_add_tail(&page->lru, &head->lru);
3698         page = NULL;                    /* now it's attached, don't free it */
3699 out_unlock_cont:
3700         spin_unlock(&si->cont_lock);
3701 out:
3702         unlock_cluster(ci);
3703         spin_unlock(&si->lock);
3704         put_swap_device(si);
3705 outer:
3706         if (page)
3707                 __free_page(page);
3708         return ret;
3709 }
3710
3711 /*
3712  * swap_count_continued - when the original swap_map count is incremented
3713  * from SWAP_MAP_MAX, check if there is already a continuation page to carry
3714  * into, carry if so, or else fail until a new continuation page is allocated;
3715  * when the original swap_map count is decremented from 0 with continuation,
3716  * borrow from the continuation and report whether it still holds more.
3717  * Called while __swap_duplicate() or swap_entry_free() holds swap or cluster
3718  * lock.
3719  */
3720 static bool swap_count_continued(struct swap_info_struct *si,
3721                                  pgoff_t offset, unsigned char count)
3722 {
3723         struct page *head;
3724         struct page *page;
3725         unsigned char *map;
3726         bool ret;
3727
3728         head = vmalloc_to_page(si->swap_map + offset);
3729         if (page_private(head) != SWP_CONTINUED) {
3730                 BUG_ON(count & COUNT_CONTINUED);
3731                 return false;           /* need to add count continuation */
3732         }
3733
3734         spin_lock(&si->cont_lock);
3735         offset &= ~PAGE_MASK;
3736         page = list_next_entry(head, lru);
3737         map = kmap_atomic(page) + offset;
3738
3739         if (count == SWAP_MAP_MAX)      /* initial increment from swap_map */
3740                 goto init_map;          /* jump over SWAP_CONT_MAX checks */
3741
3742         if (count == (SWAP_MAP_MAX | COUNT_CONTINUED)) { /* incrementing */
3743                 /*
3744                  * Think of how you add 1 to 999
3745                  */
3746                 while (*map == (SWAP_CONT_MAX | COUNT_CONTINUED)) {
3747                         kunmap_atomic(map);
3748                         page = list_next_entry(page, lru);
3749                         BUG_ON(page == head);
3750                         map = kmap_atomic(page) + offset;
3751                 }
3752                 if (*map == SWAP_CONT_MAX) {
3753                         kunmap_atomic(map);
3754                         page = list_next_entry(page, lru);
3755                         if (page == head) {
3756                                 ret = false;    /* add count continuation */
3757                                 goto out;
3758                         }
3759                         map = kmap_atomic(page) + offset;
3760 init_map:               *map = 0;               /* we didn't zero the page */
3761                 }
3762                 *map += 1;
3763                 kunmap_atomic(map);
3764                 while ((page = list_prev_entry(page, lru)) != head) {
3765                         map = kmap_atomic(page) + offset;
3766                         *map = COUNT_CONTINUED;
3767                         kunmap_atomic(map);
3768                 }
3769                 ret = true;                     /* incremented */
3770
3771         } else {                                /* decrementing */
3772                 /*
3773                  * Think of how you subtract 1 from 1000
3774                  */
3775                 BUG_ON(count != COUNT_CONTINUED);
3776                 while (*map == COUNT_CONTINUED) {
3777                         kunmap_atomic(map);
3778                         page = list_next_entry(page, lru);
3779                         BUG_ON(page == head);
3780                         map = kmap_atomic(page) + offset;
3781                 }
3782                 BUG_ON(*map == 0);
3783                 *map -= 1;
3784                 if (*map == 0)
3785                         count = 0;
3786                 kunmap_atomic(map);
3787                 while ((page = list_prev_entry(page, lru)) != head) {
3788                         map = kmap_atomic(page) + offset;
3789                         *map = SWAP_CONT_MAX | count;
3790                         count = COUNT_CONTINUED;
3791                         kunmap_atomic(map);
3792                 }
3793                 ret = count == COUNT_CONTINUED;
3794         }
3795 out:
3796         spin_unlock(&si->cont_lock);
3797         return ret;
3798 }
3799
3800 /*
3801  * free_swap_count_continuations - swapoff free all the continuation pages
3802  * appended to the swap_map, after swap_map is quiesced, before vfree'ing it.
3803  */
3804 static void free_swap_count_continuations(struct swap_info_struct *si)
3805 {
3806         pgoff_t offset;
3807
3808         for (offset = 0; offset < si->max; offset += PAGE_SIZE) {
3809                 struct page *head;
3810                 head = vmalloc_to_page(si->swap_map + offset);
3811                 if (page_private(head)) {
3812                         struct page *page, *next;
3813
3814                         list_for_each_entry_safe(page, next, &head->lru, lru) {
3815                                 list_del(&page->lru);
3816                                 __free_page(page);
3817                         }
3818                 }
3819         }
3820 }
3821
3822 #if defined(CONFIG_MEMCG) && defined(CONFIG_BLK_CGROUP)
3823 void cgroup_throttle_swaprate(struct page *page, gfp_t gfp_mask)
3824 {
3825         struct swap_info_struct *si, *next;
3826         int nid = page_to_nid(page);
3827
3828         if (!(gfp_mask & __GFP_IO))
3829                 return;
3830
3831         if (!blk_cgroup_congested())
3832                 return;
3833
3834         /*
3835          * We've already scheduled a throttle, avoid taking the global swap
3836          * lock.
3837          */
3838         if (current->throttle_queue)
3839                 return;
3840
3841         spin_lock(&swap_avail_lock);
3842         plist_for_each_entry_safe(si, next, &swap_avail_heads[nid],
3843                                   avail_lists[nid]) {
3844                 if (si->bdev) {
3845                         blkcg_schedule_throttle(bdev_get_queue(si->bdev), true);
3846                         break;
3847                 }
3848         }
3849         spin_unlock(&swap_avail_lock);
3850 }
3851 #endif
3852
3853 static int __init swapfile_init(void)
3854 {
3855         int nid;
3856
3857         swap_avail_heads = kmalloc_array(nr_node_ids, sizeof(struct plist_head),
3858                                          GFP_KERNEL);
3859         if (!swap_avail_heads) {
3860                 pr_emerg("Not enough memory for swap heads, swap is disabled\n");
3861                 return -ENOMEM;
3862         }
3863
3864         for_each_node(nid)
3865                 plist_head_init(&swap_avail_heads[nid]);
3866
3867         return 0;
3868 }
3869 subsys_initcall(swapfile_init);