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