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