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