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