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