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