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