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