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