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