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