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