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