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