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