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