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