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