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