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