OSDN Git Service

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