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