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