mm: define PAGE_MAPPING_FLAGS
[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/mm.h>
9 #include <linux/hugetlb.h>
10 #include <linux/mman.h>
11 #include <linux/slab.h>
12 #include <linux/kernel_stat.h>
13 #include <linux/swap.h>
14 #include <linux/vmalloc.h>
15 #include <linux/pagemap.h>
16 #include <linux/namei.h>
17 #include <linux/shm.h>
18 #include <linux/blkdev.h>
19 #include <linux/random.h>
20 #include <linux/writeback.h>
21 #include <linux/proc_fs.h>
22 #include <linux/seq_file.h>
23 #include <linux/init.h>
24 #include <linux/module.h>
25 #include <linux/rmap.h>
26 #include <linux/security.h>
27 #include <linux/backing-dev.h>
28 #include <linux/mutex.h>
29 #include <linux/capability.h>
30 #include <linux/syscalls.h>
31 #include <linux/memcontrol.h>
32
33 #include <asm/pgtable.h>
34 #include <asm/tlbflush.h>
35 #include <linux/swapops.h>
36 #include <linux/page_cgroup.h>
37
38 static bool swap_count_continued(struct swap_info_struct *, pgoff_t,
39                                  unsigned char);
40 static void free_swap_count_continuations(struct swap_info_struct *);
41 static sector_t map_swap_entry(swp_entry_t, struct block_device**);
42
43 static DEFINE_SPINLOCK(swap_lock);
44 static unsigned int nr_swapfiles;
45 long nr_swap_pages;
46 long total_swap_pages;
47 static int least_priority;
48
49 static const char Bad_file[] = "Bad swap file entry ";
50 static const char Unused_file[] = "Unused swap file entry ";
51 static const char Bad_offset[] = "Bad swap offset entry ";
52 static const char Unused_offset[] = "Unused swap offset entry ";
53
54 static struct swap_list_t swap_list = {-1, -1};
55
56 static struct swap_info_struct *swap_info[MAX_SWAPFILES];
57
58 static DEFINE_MUTEX(swapon_mutex);
59
60 static inline unsigned char swap_count(unsigned char ent)
61 {
62         return ent & ~SWAP_HAS_CACHE;   /* may include SWAP_HAS_CONT flag */
63 }
64
65 /* returns 1 if swap entry is freed */
66 static int
67 __try_to_reclaim_swap(struct swap_info_struct *si, unsigned long offset)
68 {
69         swp_entry_t entry = swp_entry(si->type, offset);
70         struct page *page;
71         int ret = 0;
72
73         page = find_get_page(&swapper_space, entry.val);
74         if (!page)
75                 return 0;
76         /*
77          * This function is called from scan_swap_map() and it's called
78          * by vmscan.c at reclaiming pages. So, we hold a lock on a page, here.
79          * We have to use trylock for avoiding deadlock. This is a special
80          * case and you should use try_to_free_swap() with explicit lock_page()
81          * in usual operations.
82          */
83         if (trylock_page(page)) {
84                 ret = try_to_free_swap(page);
85                 unlock_page(page);
86         }
87         page_cache_release(page);
88         return ret;
89 }
90
91 /*
92  * We need this because the bdev->unplug_fn can sleep and we cannot
93  * hold swap_lock while calling the unplug_fn. And swap_lock
94  * cannot be turned into a mutex.
95  */
96 static DECLARE_RWSEM(swap_unplug_sem);
97
98 void swap_unplug_io_fn(struct backing_dev_info *unused_bdi, struct page *page)
99 {
100         swp_entry_t entry;
101
102         down_read(&swap_unplug_sem);
103         entry.val = page_private(page);
104         if (PageSwapCache(page)) {
105                 struct block_device *bdev = swap_info[swp_type(entry)]->bdev;
106                 struct backing_dev_info *bdi;
107
108                 /*
109                  * If the page is removed from swapcache from under us (with a
110                  * racy try_to_unuse/swapoff) we need an additional reference
111                  * count to avoid reading garbage from page_private(page) above.
112                  * If the WARN_ON triggers during a swapoff it maybe the race
113                  * condition and it's harmless. However if it triggers without
114                  * swapoff it signals a problem.
115                  */
116                 WARN_ON(page_count(page) <= 1);
117
118                 bdi = bdev->bd_inode->i_mapping->backing_dev_info;
119                 blk_run_backing_dev(bdi, page);
120         }
121         up_read(&swap_unplug_sem);
122 }
123
124 /*
125  * swapon tell device that all the old swap contents can be discarded,
126  * to allow the swap device to optimize its wear-levelling.
127  */
128 static int discard_swap(struct swap_info_struct *si)
129 {
130         struct swap_extent *se;
131         sector_t start_block;
132         sector_t nr_blocks;
133         int err = 0;
134
135         /* Do not discard the swap header page! */
136         se = &si->first_swap_extent;
137         start_block = (se->start_block + 1) << (PAGE_SHIFT - 9);
138         nr_blocks = ((sector_t)se->nr_pages - 1) << (PAGE_SHIFT - 9);
139         if (nr_blocks) {
140                 err = blkdev_issue_discard(si->bdev, start_block,
141                                 nr_blocks, GFP_KERNEL, DISCARD_FL_BARRIER);
142                 if (err)
143                         return err;
144                 cond_resched();
145         }
146
147         list_for_each_entry(se, &si->first_swap_extent.list, list) {
148                 start_block = se->start_block << (PAGE_SHIFT - 9);
149                 nr_blocks = (sector_t)se->nr_pages << (PAGE_SHIFT - 9);
150
151                 err = blkdev_issue_discard(si->bdev, start_block,
152                                 nr_blocks, GFP_KERNEL, DISCARD_FL_BARRIER);
153                 if (err)
154                         break;
155
156                 cond_resched();
157         }
158         return err;             /* That will often be -EOPNOTSUPP */
159 }
160
161 /*
162  * swap allocation tell device that a cluster of swap can now be discarded,
163  * to allow the swap device to optimize its wear-levelling.
164  */
165 static void discard_swap_cluster(struct swap_info_struct *si,
166                                  pgoff_t start_page, pgoff_t nr_pages)
167 {
168         struct swap_extent *se = si->curr_swap_extent;
169         int found_extent = 0;
170
171         while (nr_pages) {
172                 struct list_head *lh;
173
174                 if (se->start_page <= start_page &&
175                     start_page < se->start_page + se->nr_pages) {
176                         pgoff_t offset = start_page - se->start_page;
177                         sector_t start_block = se->start_block + offset;
178                         sector_t nr_blocks = se->nr_pages - offset;
179
180                         if (nr_blocks > nr_pages)
181                                 nr_blocks = nr_pages;
182                         start_page += nr_blocks;
183                         nr_pages -= nr_blocks;
184
185                         if (!found_extent++)
186                                 si->curr_swap_extent = se;
187
188                         start_block <<= PAGE_SHIFT - 9;
189                         nr_blocks <<= PAGE_SHIFT - 9;
190                         if (blkdev_issue_discard(si->bdev, start_block,
191                                     nr_blocks, GFP_NOIO, DISCARD_FL_BARRIER))
192                                 break;
193                 }
194
195                 lh = se->list.next;
196                 se = list_entry(lh, struct swap_extent, list);
197         }
198 }
199
200 static int wait_for_discard(void *word)
201 {
202         schedule();
203         return 0;
204 }
205
206 #define SWAPFILE_CLUSTER        256
207 #define LATENCY_LIMIT           256
208
209 static inline unsigned long scan_swap_map(struct swap_info_struct *si,
210                                           unsigned char usage)
211 {
212         unsigned long offset;
213         unsigned long scan_base;
214         unsigned long last_in_cluster = 0;
215         int latency_ration = LATENCY_LIMIT;
216         int found_free_cluster = 0;
217
218         /*
219          * We try to cluster swap pages by allocating them sequentially
220          * in swap.  Once we've allocated SWAPFILE_CLUSTER pages this
221          * way, however, we resort to first-free allocation, starting
222          * a new cluster.  This prevents us from scattering swap pages
223          * all over the entire swap partition, so that we reduce
224          * overall disk seek times between swap pages.  -- sct
225          * But we do now try to find an empty cluster.  -Andrea
226          * And we let swap pages go all over an SSD partition.  Hugh
227          */
228
229         si->flags += SWP_SCANNING;
230         scan_base = offset = si->cluster_next;
231
232         if (unlikely(!si->cluster_nr--)) {
233                 if (si->pages - si->inuse_pages < SWAPFILE_CLUSTER) {
234                         si->cluster_nr = SWAPFILE_CLUSTER - 1;
235                         goto checks;
236                 }
237                 if (si->flags & SWP_DISCARDABLE) {
238                         /*
239                          * Start range check on racing allocations, in case
240                          * they overlap the cluster we eventually decide on
241                          * (we scan without swap_lock to allow preemption).
242                          * It's hardly conceivable that cluster_nr could be
243                          * wrapped during our scan, but don't depend on it.
244                          */
245                         if (si->lowest_alloc)
246                                 goto checks;
247                         si->lowest_alloc = si->max;
248                         si->highest_alloc = 0;
249                 }
250                 spin_unlock(&swap_lock);
251
252                 /*
253                  * If seek is expensive, start searching for new cluster from
254                  * start of partition, to minimize the span of allocated swap.
255                  * But if seek is cheap, search from our current position, so
256                  * that swap is allocated from all over the partition: if the
257                  * Flash Translation Layer only remaps within limited zones,
258                  * we don't want to wear out the first zone too quickly.
259                  */
260                 if (!(si->flags & SWP_SOLIDSTATE))
261                         scan_base = offset = si->lowest_bit;
262                 last_in_cluster = offset + SWAPFILE_CLUSTER - 1;
263
264                 /* Locate the first empty (unaligned) cluster */
265                 for (; last_in_cluster <= si->highest_bit; offset++) {
266                         if (si->swap_map[offset])
267                                 last_in_cluster = offset + SWAPFILE_CLUSTER;
268                         else if (offset == last_in_cluster) {
269                                 spin_lock(&swap_lock);
270                                 offset -= SWAPFILE_CLUSTER - 1;
271                                 si->cluster_next = offset;
272                                 si->cluster_nr = SWAPFILE_CLUSTER - 1;
273                                 found_free_cluster = 1;
274                                 goto checks;
275                         }
276                         if (unlikely(--latency_ration < 0)) {
277                                 cond_resched();
278                                 latency_ration = LATENCY_LIMIT;
279                         }
280                 }
281
282                 offset = si->lowest_bit;
283                 last_in_cluster = offset + SWAPFILE_CLUSTER - 1;
284
285                 /* Locate the first empty (unaligned) cluster */
286                 for (; last_in_cluster < scan_base; offset++) {
287                         if (si->swap_map[offset])
288                                 last_in_cluster = offset + SWAPFILE_CLUSTER;
289                         else if (offset == last_in_cluster) {
290                                 spin_lock(&swap_lock);
291                                 offset -= SWAPFILE_CLUSTER - 1;
292                                 si->cluster_next = offset;
293                                 si->cluster_nr = SWAPFILE_CLUSTER - 1;
294                                 found_free_cluster = 1;
295                                 goto checks;
296                         }
297                         if (unlikely(--latency_ration < 0)) {
298                                 cond_resched();
299                                 latency_ration = LATENCY_LIMIT;
300                         }
301                 }
302
303                 offset = scan_base;
304                 spin_lock(&swap_lock);
305                 si->cluster_nr = SWAPFILE_CLUSTER - 1;
306                 si->lowest_alloc = 0;
307         }
308
309 checks:
310         if (!(si->flags & SWP_WRITEOK))
311                 goto no_page;
312         if (!si->highest_bit)
313                 goto no_page;
314         if (offset > si->highest_bit)
315                 scan_base = offset = si->lowest_bit;
316
317         /* reuse swap entry of cache-only swap if not busy. */
318         if (vm_swap_full() && si->swap_map[offset] == SWAP_HAS_CACHE) {
319                 int swap_was_freed;
320                 spin_unlock(&swap_lock);
321                 swap_was_freed = __try_to_reclaim_swap(si, offset);
322                 spin_lock(&swap_lock);
323                 /* entry was freed successfully, try to use this again */
324                 if (swap_was_freed)
325                         goto checks;
326                 goto scan; /* check next one */
327         }
328
329         if (si->swap_map[offset])
330                 goto scan;
331
332         if (offset == si->lowest_bit)
333                 si->lowest_bit++;
334         if (offset == si->highest_bit)
335                 si->highest_bit--;
336         si->inuse_pages++;
337         if (si->inuse_pages == si->pages) {
338                 si->lowest_bit = si->max;
339                 si->highest_bit = 0;
340         }
341         si->swap_map[offset] = usage;
342         si->cluster_next = offset + 1;
343         si->flags -= SWP_SCANNING;
344
345         if (si->lowest_alloc) {
346                 /*
347                  * Only set when SWP_DISCARDABLE, and there's a scan
348                  * for a free cluster in progress or just completed.
349                  */
350                 if (found_free_cluster) {
351                         /*
352                          * To optimize wear-levelling, discard the
353                          * old data of the cluster, taking care not to
354                          * discard any of its pages that have already
355                          * been allocated by racing tasks (offset has
356                          * already stepped over any at the beginning).
357                          */
358                         if (offset < si->highest_alloc &&
359                             si->lowest_alloc <= last_in_cluster)
360                                 last_in_cluster = si->lowest_alloc - 1;
361                         si->flags |= SWP_DISCARDING;
362                         spin_unlock(&swap_lock);
363
364                         if (offset < last_in_cluster)
365                                 discard_swap_cluster(si, offset,
366                                         last_in_cluster - offset + 1);
367
368                         spin_lock(&swap_lock);
369                         si->lowest_alloc = 0;
370                         si->flags &= ~SWP_DISCARDING;
371
372                         smp_mb();       /* wake_up_bit advises this */
373                         wake_up_bit(&si->flags, ilog2(SWP_DISCARDING));
374
375                 } else if (si->flags & SWP_DISCARDING) {
376                         /*
377                          * Delay using pages allocated by racing tasks
378                          * until the whole discard has been issued. We
379                          * could defer that delay until swap_writepage,
380                          * but it's easier to keep this self-contained.
381                          */
382                         spin_unlock(&swap_lock);
383                         wait_on_bit(&si->flags, ilog2(SWP_DISCARDING),
384                                 wait_for_discard, TASK_UNINTERRUPTIBLE);
385                         spin_lock(&swap_lock);
386                 } else {
387                         /*
388                          * Note pages allocated by racing tasks while
389                          * scan for a free cluster is in progress, so
390                          * that its final discard can exclude them.
391                          */
392                         if (offset < si->lowest_alloc)
393                                 si->lowest_alloc = offset;
394                         if (offset > si->highest_alloc)
395                                 si->highest_alloc = offset;
396                 }
397         }
398         return offset;
399
400 scan:
401         spin_unlock(&swap_lock);
402         while (++offset <= si->highest_bit) {
403                 if (!si->swap_map[offset]) {
404                         spin_lock(&swap_lock);
405                         goto checks;
406                 }
407                 if (vm_swap_full() && si->swap_map[offset] == SWAP_HAS_CACHE) {
408                         spin_lock(&swap_lock);
409                         goto checks;
410                 }
411                 if (unlikely(--latency_ration < 0)) {
412                         cond_resched();
413                         latency_ration = LATENCY_LIMIT;
414                 }
415         }
416         offset = si->lowest_bit;
417         while (++offset < scan_base) {
418                 if (!si->swap_map[offset]) {
419                         spin_lock(&swap_lock);
420                         goto checks;
421                 }
422                 if (vm_swap_full() && si->swap_map[offset] == SWAP_HAS_CACHE) {
423                         spin_lock(&swap_lock);
424                         goto checks;
425                 }
426                 if (unlikely(--latency_ration < 0)) {
427                         cond_resched();
428                         latency_ration = LATENCY_LIMIT;
429                 }
430         }
431         spin_lock(&swap_lock);
432
433 no_page:
434         si->flags -= SWP_SCANNING;
435         return 0;
436 }
437
438 swp_entry_t get_swap_page(void)
439 {
440         struct swap_info_struct *si;
441         pgoff_t offset;
442         int type, next;
443         int wrapped = 0;
444
445         spin_lock(&swap_lock);
446         if (nr_swap_pages <= 0)
447                 goto noswap;
448         nr_swap_pages--;
449
450         for (type = swap_list.next; type >= 0 && wrapped < 2; type = next) {
451                 si = swap_info[type];
452                 next = si->next;
453                 if (next < 0 ||
454                     (!wrapped && si->prio != swap_info[next]->prio)) {
455                         next = swap_list.head;
456                         wrapped++;
457                 }
458
459                 if (!si->highest_bit)
460                         continue;
461                 if (!(si->flags & SWP_WRITEOK))
462                         continue;
463
464                 swap_list.next = next;
465                 /* This is called for allocating swap entry for cache */
466                 offset = scan_swap_map(si, SWAP_HAS_CACHE);
467                 if (offset) {
468                         spin_unlock(&swap_lock);
469                         return swp_entry(type, offset);
470                 }
471                 next = swap_list.next;
472         }
473
474         nr_swap_pages++;
475 noswap:
476         spin_unlock(&swap_lock);
477         return (swp_entry_t) {0};
478 }
479
480 /* The only caller of this function is now susupend routine */
481 swp_entry_t get_swap_page_of_type(int type)
482 {
483         struct swap_info_struct *si;
484         pgoff_t offset;
485
486         spin_lock(&swap_lock);
487         si = swap_info[type];
488         if (si && (si->flags & SWP_WRITEOK)) {
489                 nr_swap_pages--;
490                 /* This is called for allocating swap entry, not cache */
491                 offset = scan_swap_map(si, 1);
492                 if (offset) {
493                         spin_unlock(&swap_lock);
494                         return swp_entry(type, offset);
495                 }
496                 nr_swap_pages++;
497         }
498         spin_unlock(&swap_lock);
499         return (swp_entry_t) {0};
500 }
501
502 static struct swap_info_struct *swap_info_get(swp_entry_t entry)
503 {
504         struct swap_info_struct *p;
505         unsigned long offset, type;
506
507         if (!entry.val)
508                 goto out;
509         type = swp_type(entry);
510         if (type >= nr_swapfiles)
511                 goto bad_nofile;
512         p = swap_info[type];
513         if (!(p->flags & SWP_USED))
514                 goto bad_device;
515         offset = swp_offset(entry);
516         if (offset >= p->max)
517                 goto bad_offset;
518         if (!p->swap_map[offset])
519                 goto bad_free;
520         spin_lock(&swap_lock);
521         return p;
522
523 bad_free:
524         printk(KERN_ERR "swap_free: %s%08lx\n", Unused_offset, entry.val);
525         goto out;
526 bad_offset:
527         printk(KERN_ERR "swap_free: %s%08lx\n", Bad_offset, entry.val);
528         goto out;
529 bad_device:
530         printk(KERN_ERR "swap_free: %s%08lx\n", Unused_file, entry.val);
531         goto out;
532 bad_nofile:
533         printk(KERN_ERR "swap_free: %s%08lx\n", Bad_file, entry.val);
534 out:
535         return NULL;
536 }
537
538 static unsigned char swap_entry_free(struct swap_info_struct *p,
539                                      swp_entry_t entry, unsigned char usage)
540 {
541         unsigned long offset = swp_offset(entry);
542         unsigned char count;
543         unsigned char has_cache;
544
545         count = p->swap_map[offset];
546         has_cache = count & SWAP_HAS_CACHE;
547         count &= ~SWAP_HAS_CACHE;
548
549         if (usage == SWAP_HAS_CACHE) {
550                 VM_BUG_ON(!has_cache);
551                 has_cache = 0;
552         } else if (count == SWAP_MAP_SHMEM) {
553                 /*
554                  * Or we could insist on shmem.c using a special
555                  * swap_shmem_free() and free_shmem_swap_and_cache()...
556                  */
557                 count = 0;
558         } else if ((count & ~COUNT_CONTINUED) <= SWAP_MAP_MAX) {
559                 if (count == COUNT_CONTINUED) {
560                         if (swap_count_continued(p, offset, count))
561                                 count = SWAP_MAP_MAX | COUNT_CONTINUED;
562                         else
563                                 count = SWAP_MAP_MAX;
564                 } else
565                         count--;
566         }
567
568         if (!count)
569                 mem_cgroup_uncharge_swap(entry);
570
571         usage = count | has_cache;
572         p->swap_map[offset] = usage;
573
574         /* free if no reference */
575         if (!usage) {
576                 if (offset < p->lowest_bit)
577                         p->lowest_bit = offset;
578                 if (offset > p->highest_bit)
579                         p->highest_bit = offset;
580                 if (swap_list.next >= 0 &&
581                     p->prio > swap_info[swap_list.next]->prio)
582                         swap_list.next = p->type;
583                 nr_swap_pages++;
584                 p->inuse_pages--;
585         }
586
587         return usage;
588 }
589
590 /*
591  * Caller has made sure that the swapdevice corresponding to entry
592  * is still around or has not been recycled.
593  */
594 void swap_free(swp_entry_t entry)
595 {
596         struct swap_info_struct *p;
597
598         p = swap_info_get(entry);
599         if (p) {
600                 swap_entry_free(p, entry, 1);
601                 spin_unlock(&swap_lock);
602         }
603 }
604
605 /*
606  * Called after dropping swapcache to decrease refcnt to swap entries.
607  */
608 void swapcache_free(swp_entry_t entry, struct page *page)
609 {
610         struct swap_info_struct *p;
611         unsigned char count;
612
613         p = swap_info_get(entry);
614         if (p) {
615                 count = swap_entry_free(p, entry, SWAP_HAS_CACHE);
616                 if (page)
617                         mem_cgroup_uncharge_swapcache(page, entry, count != 0);
618                 spin_unlock(&swap_lock);
619         }
620 }
621
622 /*
623  * How many references to page are currently swapped out?
624  * This does not give an exact answer when swap count is continued,
625  * but does include the high COUNT_CONTINUED flag to allow for that.
626  */
627 static inline int page_swapcount(struct page *page)
628 {
629         int count = 0;
630         struct swap_info_struct *p;
631         swp_entry_t entry;
632
633         entry.val = page_private(page);
634         p = swap_info_get(entry);
635         if (p) {
636                 count = swap_count(p->swap_map[swp_offset(entry)]);
637                 spin_unlock(&swap_lock);
638         }
639         return count;
640 }
641
642 /*
643  * We can write to an anon page without COW if there are no other references
644  * to it.  And as a side-effect, free up its swap: because the old content
645  * on disk will never be read, and seeking back there to write new content
646  * later would only waste time away from clustering.
647  */
648 int reuse_swap_page(struct page *page)
649 {
650         int count;
651
652         VM_BUG_ON(!PageLocked(page));
653         count = page_mapcount(page);
654         if (count <= 1 && PageSwapCache(page)) {
655                 count += page_swapcount(page);
656                 if (count == 1 && !PageWriteback(page)) {
657                         delete_from_swap_cache(page);
658                         SetPageDirty(page);
659                 }
660         }
661         return count == 1;
662 }
663
664 /*
665  * If swap is getting full, or if there are no more mappings of this page,
666  * then try_to_free_swap is called to free its swap space.
667  */
668 int try_to_free_swap(struct page *page)
669 {
670         VM_BUG_ON(!PageLocked(page));
671
672         if (!PageSwapCache(page))
673                 return 0;
674         if (PageWriteback(page))
675                 return 0;
676         if (page_swapcount(page))
677                 return 0;
678
679         delete_from_swap_cache(page);
680         SetPageDirty(page);
681         return 1;
682 }
683
684 /*
685  * Free the swap entry like above, but also try to
686  * free the page cache entry if it is the last user.
687  */
688 int free_swap_and_cache(swp_entry_t entry)
689 {
690         struct swap_info_struct *p;
691         struct page *page = NULL;
692
693         if (non_swap_entry(entry))
694                 return 1;
695
696         p = swap_info_get(entry);
697         if (p) {
698                 if (swap_entry_free(p, entry, 1) == SWAP_HAS_CACHE) {
699                         page = find_get_page(&swapper_space, entry.val);
700                         if (page && !trylock_page(page)) {
701                                 page_cache_release(page);
702                                 page = NULL;
703                         }
704                 }
705                 spin_unlock(&swap_lock);
706         }
707         if (page) {
708                 /*
709                  * Not mapped elsewhere, or swap space full? Free it!
710                  * Also recheck PageSwapCache now page is locked (above).
711                  */
712                 if (PageSwapCache(page) && !PageWriteback(page) &&
713                                 (!page_mapped(page) || vm_swap_full())) {
714                         delete_from_swap_cache(page);
715                         SetPageDirty(page);
716                 }
717                 unlock_page(page);
718                 page_cache_release(page);
719         }
720         return p != NULL;
721 }
722
723 #ifdef CONFIG_HIBERNATION
724 /*
725  * Find the swap type that corresponds to given device (if any).
726  *
727  * @offset - number of the PAGE_SIZE-sized block of the device, starting
728  * from 0, in which the swap header is expected to be located.
729  *
730  * This is needed for the suspend to disk (aka swsusp).
731  */
732 int swap_type_of(dev_t device, sector_t offset, struct block_device **bdev_p)
733 {
734         struct block_device *bdev = NULL;
735         int type;
736
737         if (device)
738                 bdev = bdget(device);
739
740         spin_lock(&swap_lock);
741         for (type = 0; type < nr_swapfiles; type++) {
742                 struct swap_info_struct *sis = swap_info[type];
743
744                 if (!(sis->flags & SWP_WRITEOK))
745                         continue;
746
747                 if (!bdev) {
748                         if (bdev_p)
749                                 *bdev_p = bdgrab(sis->bdev);
750
751                         spin_unlock(&swap_lock);
752                         return type;
753                 }
754                 if (bdev == sis->bdev) {
755                         struct swap_extent *se = &sis->first_swap_extent;
756
757                         if (se->start_block == offset) {
758                                 if (bdev_p)
759                                         *bdev_p = bdgrab(sis->bdev);
760
761                                 spin_unlock(&swap_lock);
762                                 bdput(bdev);
763                                 return type;
764                         }
765                 }
766         }
767         spin_unlock(&swap_lock);
768         if (bdev)
769                 bdput(bdev);
770
771         return -ENODEV;
772 }
773
774 /*
775  * Get the (PAGE_SIZE) block corresponding to given offset on the swapdev
776  * corresponding to given index in swap_info (swap type).
777  */
778 sector_t swapdev_block(int type, pgoff_t offset)
779 {
780         struct block_device *bdev;
781
782         if ((unsigned int)type >= nr_swapfiles)
783                 return 0;
784         if (!(swap_info[type]->flags & SWP_WRITEOK))
785                 return 0;
786         return map_swap_entry(swp_entry(type, offset), &bdev);
787 }
788
789 /*
790  * Return either the total number of swap pages of given type, or the number
791  * of free pages of that type (depending on @free)
792  *
793  * This is needed for software suspend
794  */
795 unsigned int count_swap_pages(int type, int free)
796 {
797         unsigned int n = 0;
798
799         spin_lock(&swap_lock);
800         if ((unsigned int)type < nr_swapfiles) {
801                 struct swap_info_struct *sis = swap_info[type];
802
803                 if (sis->flags & SWP_WRITEOK) {
804                         n = sis->pages;
805                         if (free)
806                                 n -= sis->inuse_pages;
807                 }
808         }
809         spin_unlock(&swap_lock);
810         return n;
811 }
812 #endif /* CONFIG_HIBERNATION */
813
814 /*
815  * No need to decide whether this PTE shares the swap entry with others,
816  * just let do_wp_page work it out if a write is requested later - to
817  * force COW, vm_page_prot omits write permission from any private vma.
818  */
819 static int unuse_pte(struct vm_area_struct *vma, pmd_t *pmd,
820                 unsigned long addr, swp_entry_t entry, struct page *page)
821 {
822         struct mem_cgroup *ptr = NULL;
823         spinlock_t *ptl;
824         pte_t *pte;
825         int ret = 1;
826
827         if (mem_cgroup_try_charge_swapin(vma->vm_mm, page, GFP_KERNEL, &ptr)) {
828                 ret = -ENOMEM;
829                 goto out_nolock;
830         }
831
832         pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
833         if (unlikely(!pte_same(*pte, swp_entry_to_pte(entry)))) {
834                 if (ret > 0)
835                         mem_cgroup_cancel_charge_swapin(ptr);
836                 ret = 0;
837                 goto out;
838         }
839
840         inc_mm_counter(vma->vm_mm, anon_rss);
841         get_page(page);
842         set_pte_at(vma->vm_mm, addr, pte,
843                    pte_mkold(mk_pte(page, vma->vm_page_prot)));
844         page_add_anon_rmap(page, vma, addr);
845         mem_cgroup_commit_charge_swapin(page, ptr);
846         swap_free(entry);
847         /*
848          * Move the page to the active list so it is not
849          * immediately swapped out again after swapon.
850          */
851         activate_page(page);
852 out:
853         pte_unmap_unlock(pte, ptl);
854 out_nolock:
855         return ret;
856 }
857
858 static int unuse_pte_range(struct vm_area_struct *vma, pmd_t *pmd,
859                                 unsigned long addr, unsigned long end,
860                                 swp_entry_t entry, struct page *page)
861 {
862         pte_t swp_pte = swp_entry_to_pte(entry);
863         pte_t *pte;
864         int ret = 0;
865
866         /*
867          * We don't actually need pte lock while scanning for swp_pte: since
868          * we hold page lock and mmap_sem, swp_pte cannot be inserted into the
869          * page table while we're scanning; though it could get zapped, and on
870          * some architectures (e.g. x86_32 with PAE) we might catch a glimpse
871          * of unmatched parts which look like swp_pte, so unuse_pte must
872          * recheck under pte lock.  Scanning without pte lock lets it be
873          * preemptible whenever CONFIG_PREEMPT but not CONFIG_HIGHPTE.
874          */
875         pte = pte_offset_map(pmd, addr);
876         do {
877                 /*
878                  * swapoff spends a _lot_ of time in this loop!
879                  * Test inline before going to call unuse_pte.
880                  */
881                 if (unlikely(pte_same(*pte, swp_pte))) {
882                         pte_unmap(pte);
883                         ret = unuse_pte(vma, pmd, addr, entry, page);
884                         if (ret)
885                                 goto out;
886                         pte = pte_offset_map(pmd, addr);
887                 }
888         } while (pte++, addr += PAGE_SIZE, addr != end);
889         pte_unmap(pte - 1);
890 out:
891         return ret;
892 }
893
894 static inline int unuse_pmd_range(struct vm_area_struct *vma, pud_t *pud,
895                                 unsigned long addr, unsigned long end,
896                                 swp_entry_t entry, struct page *page)
897 {
898         pmd_t *pmd;
899         unsigned long next;
900         int ret;
901
902         pmd = pmd_offset(pud, addr);
903         do {
904                 next = pmd_addr_end(addr, end);
905                 if (pmd_none_or_clear_bad(pmd))
906                         continue;
907                 ret = unuse_pte_range(vma, pmd, addr, next, entry, page);
908                 if (ret)
909                         return ret;
910         } while (pmd++, addr = next, addr != end);
911         return 0;
912 }
913
914 static inline int unuse_pud_range(struct vm_area_struct *vma, pgd_t *pgd,
915                                 unsigned long addr, unsigned long end,
916                                 swp_entry_t entry, struct page *page)
917 {
918         pud_t *pud;
919         unsigned long next;
920         int ret;
921
922         pud = pud_offset(pgd, addr);
923         do {
924                 next = pud_addr_end(addr, end);
925                 if (pud_none_or_clear_bad(pud))
926                         continue;
927                 ret = unuse_pmd_range(vma, pud, addr, next, entry, page);
928                 if (ret)
929                         return ret;
930         } while (pud++, addr = next, addr != end);
931         return 0;
932 }
933
934 static int unuse_vma(struct vm_area_struct *vma,
935                                 swp_entry_t entry, struct page *page)
936 {
937         pgd_t *pgd;
938         unsigned long addr, end, next;
939         int ret;
940
941         if (page_anon_vma(page)) {
942                 addr = page_address_in_vma(page, vma);
943                 if (addr == -EFAULT)
944                         return 0;
945                 else
946                         end = addr + PAGE_SIZE;
947         } else {
948                 addr = vma->vm_start;
949                 end = vma->vm_end;
950         }
951
952         pgd = pgd_offset(vma->vm_mm, addr);
953         do {
954                 next = pgd_addr_end(addr, end);
955                 if (pgd_none_or_clear_bad(pgd))
956                         continue;
957                 ret = unuse_pud_range(vma, pgd, addr, next, entry, page);
958                 if (ret)
959                         return ret;
960         } while (pgd++, addr = next, addr != end);
961         return 0;
962 }
963
964 static int unuse_mm(struct mm_struct *mm,
965                                 swp_entry_t entry, struct page *page)
966 {
967         struct vm_area_struct *vma;
968         int ret = 0;
969
970         if (!down_read_trylock(&mm->mmap_sem)) {
971                 /*
972                  * Activate page so shrink_inactive_list is unlikely to unmap
973                  * its ptes while lock is dropped, so swapoff can make progress.
974                  */
975                 activate_page(page);
976                 unlock_page(page);
977                 down_read(&mm->mmap_sem);
978                 lock_page(page);
979         }
980         for (vma = mm->mmap; vma; vma = vma->vm_next) {
981                 if (vma->anon_vma && (ret = unuse_vma(vma, entry, page)))
982                         break;
983         }
984         up_read(&mm->mmap_sem);
985         return (ret < 0)? ret: 0;
986 }
987
988 /*
989  * Scan swap_map from current position to next entry still in use.
990  * Recycle to start on reaching the end, returning 0 when empty.
991  */
992 static unsigned int find_next_to_unuse(struct swap_info_struct *si,
993                                         unsigned int prev)
994 {
995         unsigned int max = si->max;
996         unsigned int i = prev;
997         unsigned char count;
998
999         /*
1000          * No need for swap_lock here: we're just looking
1001          * for whether an entry is in use, not modifying it; false
1002          * hits are okay, and sys_swapoff() has already prevented new
1003          * allocations from this area (while holding swap_lock).
1004          */
1005         for (;;) {
1006                 if (++i >= max) {
1007                         if (!prev) {
1008                                 i = 0;
1009                                 break;
1010                         }
1011                         /*
1012                          * No entries in use at top of swap_map,
1013                          * loop back to start and recheck there.
1014                          */
1015                         max = prev + 1;
1016                         prev = 0;
1017                         i = 1;
1018                 }
1019                 count = si->swap_map[i];
1020                 if (count && swap_count(count) != SWAP_MAP_BAD)
1021                         break;
1022         }
1023         return i;
1024 }
1025
1026 /*
1027  * We completely avoid races by reading each swap page in advance,
1028  * and then search for the process using it.  All the necessary
1029  * page table adjustments can then be made atomically.
1030  */
1031 static int try_to_unuse(unsigned int type)
1032 {
1033         struct swap_info_struct *si = swap_info[type];
1034         struct mm_struct *start_mm;
1035         unsigned char *swap_map;
1036         unsigned char swcount;
1037         struct page *page;
1038         swp_entry_t entry;
1039         unsigned int i = 0;
1040         int retval = 0;
1041
1042         /*
1043          * When searching mms for an entry, a good strategy is to
1044          * start at the first mm we freed the previous entry from
1045          * (though actually we don't notice whether we or coincidence
1046          * freed the entry).  Initialize this start_mm with a hold.
1047          *
1048          * A simpler strategy would be to start at the last mm we
1049          * freed the previous entry from; but that would take less
1050          * advantage of mmlist ordering, which clusters forked mms
1051          * together, child after parent.  If we race with dup_mmap(), we
1052          * prefer to resolve parent before child, lest we miss entries
1053          * duplicated after we scanned child: using last mm would invert
1054          * that.
1055          */
1056         start_mm = &init_mm;
1057         atomic_inc(&init_mm.mm_users);
1058
1059         /*
1060          * Keep on scanning until all entries have gone.  Usually,
1061          * one pass through swap_map is enough, but not necessarily:
1062          * there are races when an instance of an entry might be missed.
1063          */
1064         while ((i = find_next_to_unuse(si, i)) != 0) {
1065                 if (signal_pending(current)) {
1066                         retval = -EINTR;
1067                         break;
1068                 }
1069
1070                 /*
1071                  * Get a page for the entry, using the existing swap
1072                  * cache page if there is one.  Otherwise, get a clean
1073                  * page and read the swap into it.
1074                  */
1075                 swap_map = &si->swap_map[i];
1076                 entry = swp_entry(type, i);
1077                 page = read_swap_cache_async(entry,
1078                                         GFP_HIGHUSER_MOVABLE, NULL, 0);
1079                 if (!page) {
1080                         /*
1081                          * Either swap_duplicate() failed because entry
1082                          * has been freed independently, and will not be
1083                          * reused since sys_swapoff() already disabled
1084                          * allocation from here, or alloc_page() failed.
1085                          */
1086                         if (!*swap_map)
1087                                 continue;
1088                         retval = -ENOMEM;
1089                         break;
1090                 }
1091
1092                 /*
1093                  * Don't hold on to start_mm if it looks like exiting.
1094                  */
1095                 if (atomic_read(&start_mm->mm_users) == 1) {
1096                         mmput(start_mm);
1097                         start_mm = &init_mm;
1098                         atomic_inc(&init_mm.mm_users);
1099                 }
1100
1101                 /*
1102                  * Wait for and lock page.  When do_swap_page races with
1103                  * try_to_unuse, do_swap_page can handle the fault much
1104                  * faster than try_to_unuse can locate the entry.  This
1105                  * apparently redundant "wait_on_page_locked" lets try_to_unuse
1106                  * defer to do_swap_page in such a case - in some tests,
1107                  * do_swap_page and try_to_unuse repeatedly compete.
1108                  */
1109                 wait_on_page_locked(page);
1110                 wait_on_page_writeback(page);
1111                 lock_page(page);
1112                 wait_on_page_writeback(page);
1113
1114                 /*
1115                  * Remove all references to entry.
1116                  */
1117                 swcount = *swap_map;
1118                 if (swap_count(swcount) == SWAP_MAP_SHMEM) {
1119                         retval = shmem_unuse(entry, page);
1120                         /* page has already been unlocked and released */
1121                         if (retval < 0)
1122                                 break;
1123                         continue;
1124                 }
1125                 if (swap_count(swcount) && start_mm != &init_mm)
1126                         retval = unuse_mm(start_mm, entry, page);
1127
1128                 if (swap_count(*swap_map)) {
1129                         int set_start_mm = (*swap_map >= swcount);
1130                         struct list_head *p = &start_mm->mmlist;
1131                         struct mm_struct *new_start_mm = start_mm;
1132                         struct mm_struct *prev_mm = start_mm;
1133                         struct mm_struct *mm;
1134
1135                         atomic_inc(&new_start_mm->mm_users);
1136                         atomic_inc(&prev_mm->mm_users);
1137                         spin_lock(&mmlist_lock);
1138                         while (swap_count(*swap_map) && !retval &&
1139                                         (p = p->next) != &start_mm->mmlist) {
1140                                 mm = list_entry(p, struct mm_struct, mmlist);
1141                                 if (!atomic_inc_not_zero(&mm->mm_users))
1142                                         continue;
1143                                 spin_unlock(&mmlist_lock);
1144                                 mmput(prev_mm);
1145                                 prev_mm = mm;
1146
1147                                 cond_resched();
1148
1149                                 swcount = *swap_map;
1150                                 if (!swap_count(swcount)) /* any usage ? */
1151                                         ;
1152                                 else if (mm == &init_mm)
1153                                         set_start_mm = 1;
1154                                 else
1155                                         retval = unuse_mm(mm, entry, page);
1156
1157                                 if (set_start_mm && *swap_map < swcount) {
1158                                         mmput(new_start_mm);
1159                                         atomic_inc(&mm->mm_users);
1160                                         new_start_mm = mm;
1161                                         set_start_mm = 0;
1162                                 }
1163                                 spin_lock(&mmlist_lock);
1164                         }
1165                         spin_unlock(&mmlist_lock);
1166                         mmput(prev_mm);
1167                         mmput(start_mm);
1168                         start_mm = new_start_mm;
1169                 }
1170                 if (retval) {
1171                         unlock_page(page);
1172                         page_cache_release(page);
1173                         break;
1174                 }
1175
1176                 /*
1177                  * If a reference remains (rare), we would like to leave
1178                  * the page in the swap cache; but try_to_unmap could
1179                  * then re-duplicate the entry once we drop page lock,
1180                  * so we might loop indefinitely; also, that page could
1181                  * not be swapped out to other storage meanwhile.  So:
1182                  * delete from cache even if there's another reference,
1183                  * after ensuring that the data has been saved to disk -
1184                  * since if the reference remains (rarer), it will be
1185                  * read from disk into another page.  Splitting into two
1186                  * pages would be incorrect if swap supported "shared
1187                  * private" pages, but they are handled by tmpfs files.
1188                  */
1189                 if (swap_count(*swap_map) &&
1190                      PageDirty(page) && PageSwapCache(page)) {
1191                         struct writeback_control wbc = {
1192                                 .sync_mode = WB_SYNC_NONE,
1193                         };
1194
1195                         swap_writepage(page, &wbc);
1196                         lock_page(page);
1197                         wait_on_page_writeback(page);
1198                 }
1199
1200                 /*
1201                  * It is conceivable that a racing task removed this page from
1202                  * swap cache just before we acquired the page lock at the top,
1203                  * or while we dropped it in unuse_mm().  The page might even
1204                  * be back in swap cache on another swap area: that we must not
1205                  * delete, since it may not have been written out to swap yet.
1206                  */
1207                 if (PageSwapCache(page) &&
1208                     likely(page_private(page) == entry.val))
1209                         delete_from_swap_cache(page);
1210
1211                 /*
1212                  * So we could skip searching mms once swap count went
1213                  * to 1, we did not mark any present ptes as dirty: must
1214                  * mark page dirty so shrink_page_list will preserve it.
1215                  */
1216                 SetPageDirty(page);
1217                 unlock_page(page);
1218                 page_cache_release(page);
1219
1220                 /*
1221                  * Make sure that we aren't completely killing
1222                  * interactive performance.
1223                  */
1224                 cond_resched();
1225         }
1226
1227         mmput(start_mm);
1228         return retval;
1229 }
1230
1231 /*
1232  * After a successful try_to_unuse, if no swap is now in use, we know
1233  * we can empty the mmlist.  swap_lock must be held on entry and exit.
1234  * Note that mmlist_lock nests inside swap_lock, and an mm must be
1235  * added to the mmlist just after page_duplicate - before would be racy.
1236  */
1237 static void drain_mmlist(void)
1238 {
1239         struct list_head *p, *next;
1240         unsigned int type;
1241
1242         for (type = 0; type < nr_swapfiles; type++)
1243                 if (swap_info[type]->inuse_pages)
1244                         return;
1245         spin_lock(&mmlist_lock);
1246         list_for_each_safe(p, next, &init_mm.mmlist)
1247                 list_del_init(p);
1248         spin_unlock(&mmlist_lock);
1249 }
1250
1251 /*
1252  * Use this swapdev's extent info to locate the (PAGE_SIZE) block which
1253  * corresponds to page offset for the specified swap entry.
1254  * Note that the type of this function is sector_t, but it returns page offset
1255  * into the bdev, not sector offset.
1256  */
1257 static sector_t map_swap_entry(swp_entry_t entry, struct block_device **bdev)
1258 {
1259         struct swap_info_struct *sis;
1260         struct swap_extent *start_se;
1261         struct swap_extent *se;
1262         pgoff_t offset;
1263
1264         sis = swap_info[swp_type(entry)];
1265         *bdev = sis->bdev;
1266
1267         offset = swp_offset(entry);
1268         start_se = sis->curr_swap_extent;
1269         se = start_se;
1270
1271         for ( ; ; ) {
1272                 struct list_head *lh;
1273
1274                 if (se->start_page <= offset &&
1275                                 offset < (se->start_page + se->nr_pages)) {
1276                         return se->start_block + (offset - se->start_page);
1277                 }
1278                 lh = se->list.next;
1279                 se = list_entry(lh, struct swap_extent, list);
1280                 sis->curr_swap_extent = se;
1281                 BUG_ON(se == start_se);         /* It *must* be present */
1282         }
1283 }
1284
1285 /*
1286  * Returns the page offset into bdev for the specified page's swap entry.
1287  */
1288 sector_t map_swap_page(struct page *page, struct block_device **bdev)
1289 {
1290         swp_entry_t entry;
1291         entry.val = page_private(page);
1292         return map_swap_entry(entry, bdev);
1293 }
1294
1295 /*
1296  * Free all of a swapdev's extent information
1297  */
1298 static void destroy_swap_extents(struct swap_info_struct *sis)
1299 {
1300         while (!list_empty(&sis->first_swap_extent.list)) {
1301                 struct swap_extent *se;
1302
1303                 se = list_entry(sis->first_swap_extent.list.next,
1304                                 struct swap_extent, list);
1305                 list_del(&se->list);
1306                 kfree(se);
1307         }
1308 }
1309
1310 /*
1311  * Add a block range (and the corresponding page range) into this swapdev's
1312  * extent list.  The extent list is kept sorted in page order.
1313  *
1314  * This function rather assumes that it is called in ascending page order.
1315  */
1316 static int
1317 add_swap_extent(struct swap_info_struct *sis, unsigned long start_page,
1318                 unsigned long nr_pages, sector_t start_block)
1319 {
1320         struct swap_extent *se;
1321         struct swap_extent *new_se;
1322         struct list_head *lh;
1323
1324         if (start_page == 0) {
1325                 se = &sis->first_swap_extent;
1326                 sis->curr_swap_extent = se;
1327                 se->start_page = 0;
1328                 se->nr_pages = nr_pages;
1329                 se->start_block = start_block;
1330                 return 1;
1331         } else {
1332                 lh = sis->first_swap_extent.list.prev;  /* Highest extent */
1333                 se = list_entry(lh, struct swap_extent, list);
1334                 BUG_ON(se->start_page + se->nr_pages != start_page);
1335                 if (se->start_block + se->nr_pages == start_block) {
1336                         /* Merge it */
1337                         se->nr_pages += nr_pages;
1338                         return 0;
1339                 }
1340         }
1341
1342         /*
1343          * No merge.  Insert a new extent, preserving ordering.
1344          */
1345         new_se = kmalloc(sizeof(*se), GFP_KERNEL);
1346         if (new_se == NULL)
1347                 return -ENOMEM;
1348         new_se->start_page = start_page;
1349         new_se->nr_pages = nr_pages;
1350         new_se->start_block = start_block;
1351
1352         list_add_tail(&new_se->list, &sis->first_swap_extent.list);
1353         return 1;
1354 }
1355
1356 /*
1357  * A `swap extent' is a simple thing which maps a contiguous range of pages
1358  * onto a contiguous range of disk blocks.  An ordered list of swap extents
1359  * is built at swapon time and is then used at swap_writepage/swap_readpage
1360  * time for locating where on disk a page belongs.
1361  *
1362  * If the swapfile is an S_ISBLK block device, a single extent is installed.
1363  * This is done so that the main operating code can treat S_ISBLK and S_ISREG
1364  * swap files identically.
1365  *
1366  * Whether the swapdev is an S_ISREG file or an S_ISBLK blockdev, the swap
1367  * extent list operates in PAGE_SIZE disk blocks.  Both S_ISREG and S_ISBLK
1368  * swapfiles are handled *identically* after swapon time.
1369  *
1370  * For S_ISREG swapfiles, setup_swap_extents() will walk all the file's blocks
1371  * and will parse them into an ordered extent list, in PAGE_SIZE chunks.  If
1372  * some stray blocks are found which do not fall within the PAGE_SIZE alignment
1373  * requirements, they are simply tossed out - we will never use those blocks
1374  * for swapping.
1375  *
1376  * For S_ISREG swapfiles we set S_SWAPFILE across the life of the swapon.  This
1377  * prevents root from shooting her foot off by ftruncating an in-use swapfile,
1378  * which will scribble on the fs.
1379  *
1380  * The amount of disk space which a single swap extent represents varies.
1381  * Typically it is in the 1-4 megabyte range.  So we can have hundreds of
1382  * extents in the list.  To avoid much list walking, we cache the previous
1383  * search location in `curr_swap_extent', and start new searches from there.
1384  * This is extremely effective.  The average number of iterations in
1385  * map_swap_page() has been measured at about 0.3 per page.  - akpm.
1386  */
1387 static int setup_swap_extents(struct swap_info_struct *sis, sector_t *span)
1388 {
1389         struct inode *inode;
1390         unsigned blocks_per_page;
1391         unsigned long page_no;
1392         unsigned blkbits;
1393         sector_t probe_block;
1394         sector_t last_block;
1395         sector_t lowest_block = -1;
1396         sector_t highest_block = 0;
1397         int nr_extents = 0;
1398         int ret;
1399
1400         inode = sis->swap_file->f_mapping->host;
1401         if (S_ISBLK(inode->i_mode)) {
1402                 ret = add_swap_extent(sis, 0, sis->max, 0);
1403                 *span = sis->pages;
1404                 goto out;
1405         }
1406
1407         blkbits = inode->i_blkbits;
1408         blocks_per_page = PAGE_SIZE >> blkbits;
1409
1410         /*
1411          * Map all the blocks into the extent list.  This code doesn't try
1412          * to be very smart.
1413          */
1414         probe_block = 0;
1415         page_no = 0;
1416         last_block = i_size_read(inode) >> blkbits;
1417         while ((probe_block + blocks_per_page) <= last_block &&
1418                         page_no < sis->max) {
1419                 unsigned block_in_page;
1420                 sector_t first_block;
1421
1422                 first_block = bmap(inode, probe_block);
1423                 if (first_block == 0)
1424                         goto bad_bmap;
1425
1426                 /*
1427                  * It must be PAGE_SIZE aligned on-disk
1428                  */
1429                 if (first_block & (blocks_per_page - 1)) {
1430                         probe_block++;
1431                         goto reprobe;
1432                 }
1433
1434                 for (block_in_page = 1; block_in_page < blocks_per_page;
1435                                         block_in_page++) {
1436                         sector_t block;
1437
1438                         block = bmap(inode, probe_block + block_in_page);
1439                         if (block == 0)
1440                                 goto bad_bmap;
1441                         if (block != first_block + block_in_page) {
1442                                 /* Discontiguity */
1443                                 probe_block++;
1444                                 goto reprobe;
1445                         }
1446                 }
1447
1448                 first_block >>= (PAGE_SHIFT - blkbits);
1449                 if (page_no) {  /* exclude the header page */
1450                         if (first_block < lowest_block)
1451                                 lowest_block = first_block;
1452                         if (first_block > highest_block)
1453                                 highest_block = first_block;
1454                 }
1455
1456                 /*
1457                  * We found a PAGE_SIZE-length, PAGE_SIZE-aligned run of blocks
1458                  */
1459                 ret = add_swap_extent(sis, page_no, 1, first_block);
1460                 if (ret < 0)
1461                         goto out;
1462                 nr_extents += ret;
1463                 page_no++;
1464                 probe_block += blocks_per_page;
1465 reprobe:
1466                 continue;
1467         }
1468         ret = nr_extents;
1469         *span = 1 + highest_block - lowest_block;
1470         if (page_no == 0)
1471                 page_no = 1;    /* force Empty message */
1472         sis->max = page_no;
1473         sis->pages = page_no - 1;
1474         sis->highest_bit = page_no - 1;
1475 out:
1476         return ret;
1477 bad_bmap:
1478         printk(KERN_ERR "swapon: swapfile has holes\n");
1479         ret = -EINVAL;
1480         goto out;
1481 }
1482
1483 SYSCALL_DEFINE1(swapoff, const char __user *, specialfile)
1484 {
1485         struct swap_info_struct *p = NULL;
1486         unsigned char *swap_map;
1487         struct file *swap_file, *victim;
1488         struct address_space *mapping;
1489         struct inode *inode;
1490         char *pathname;
1491         int i, type, prev;
1492         int err;
1493
1494         if (!capable(CAP_SYS_ADMIN))
1495                 return -EPERM;
1496
1497         pathname = getname(specialfile);
1498         err = PTR_ERR(pathname);
1499         if (IS_ERR(pathname))
1500                 goto out;
1501
1502         victim = filp_open(pathname, O_RDWR|O_LARGEFILE, 0);
1503         putname(pathname);
1504         err = PTR_ERR(victim);
1505         if (IS_ERR(victim))
1506                 goto out;
1507
1508         mapping = victim->f_mapping;
1509         prev = -1;
1510         spin_lock(&swap_lock);
1511         for (type = swap_list.head; type >= 0; type = swap_info[type]->next) {
1512                 p = swap_info[type];
1513                 if (p->flags & SWP_WRITEOK) {
1514                         if (p->swap_file->f_mapping == mapping)
1515                                 break;
1516                 }
1517                 prev = type;
1518         }
1519         if (type < 0) {
1520                 err = -EINVAL;
1521                 spin_unlock(&swap_lock);
1522                 goto out_dput;
1523         }
1524         if (!security_vm_enough_memory(p->pages))
1525                 vm_unacct_memory(p->pages);
1526         else {
1527                 err = -ENOMEM;
1528                 spin_unlock(&swap_lock);
1529                 goto out_dput;
1530         }
1531         if (prev < 0)
1532                 swap_list.head = p->next;
1533         else
1534                 swap_info[prev]->next = p->next;
1535         if (type == swap_list.next) {
1536                 /* just pick something that's safe... */
1537                 swap_list.next = swap_list.head;
1538         }
1539         if (p->prio < 0) {
1540                 for (i = p->next; i >= 0; i = swap_info[i]->next)
1541                         swap_info[i]->prio = p->prio--;
1542                 least_priority++;
1543         }
1544         nr_swap_pages -= p->pages;
1545         total_swap_pages -= p->pages;
1546         p->flags &= ~SWP_WRITEOK;
1547         spin_unlock(&swap_lock);
1548
1549         current->flags |= PF_OOM_ORIGIN;
1550         err = try_to_unuse(type);
1551         current->flags &= ~PF_OOM_ORIGIN;
1552
1553         if (err) {
1554                 /* re-insert swap space back into swap_list */
1555                 spin_lock(&swap_lock);
1556                 if (p->prio < 0)
1557                         p->prio = --least_priority;
1558                 prev = -1;
1559                 for (i = swap_list.head; i >= 0; i = swap_info[i]->next) {
1560                         if (p->prio >= swap_info[i]->prio)
1561                                 break;
1562                         prev = i;
1563                 }
1564                 p->next = i;
1565                 if (prev < 0)
1566                         swap_list.head = swap_list.next = type;
1567                 else
1568                         swap_info[prev]->next = type;
1569                 nr_swap_pages += p->pages;
1570                 total_swap_pages += p->pages;
1571                 p->flags |= SWP_WRITEOK;
1572                 spin_unlock(&swap_lock);
1573                 goto out_dput;
1574         }
1575
1576         /* wait for any unplug function to finish */
1577         down_write(&swap_unplug_sem);
1578         up_write(&swap_unplug_sem);
1579
1580         destroy_swap_extents(p);
1581         if (p->flags & SWP_CONTINUED)
1582                 free_swap_count_continuations(p);
1583
1584         mutex_lock(&swapon_mutex);
1585         spin_lock(&swap_lock);
1586         drain_mmlist();
1587
1588         /* wait for anyone still in scan_swap_map */
1589         p->highest_bit = 0;             /* cuts scans short */
1590         while (p->flags >= SWP_SCANNING) {
1591                 spin_unlock(&swap_lock);
1592                 schedule_timeout_uninterruptible(1);
1593                 spin_lock(&swap_lock);
1594         }
1595
1596         swap_file = p->swap_file;
1597         p->swap_file = NULL;
1598         p->max = 0;
1599         swap_map = p->swap_map;
1600         p->swap_map = NULL;
1601         p->flags = 0;
1602         spin_unlock(&swap_lock);
1603         mutex_unlock(&swapon_mutex);
1604         vfree(swap_map);
1605         /* Destroy swap account informatin */
1606         swap_cgroup_swapoff(type);
1607
1608         inode = mapping->host;
1609         if (S_ISBLK(inode->i_mode)) {
1610                 struct block_device *bdev = I_BDEV(inode);
1611                 set_blocksize(bdev, p->old_block_size);
1612                 bd_release(bdev);
1613         } else {
1614                 mutex_lock(&inode->i_mutex);
1615                 inode->i_flags &= ~S_SWAPFILE;
1616                 mutex_unlock(&inode->i_mutex);
1617         }
1618         filp_close(swap_file, NULL);
1619         err = 0;
1620
1621 out_dput:
1622         filp_close(victim, NULL);
1623 out:
1624         return err;
1625 }
1626
1627 #ifdef CONFIG_PROC_FS
1628 /* iterator */
1629 static void *swap_start(struct seq_file *swap, loff_t *pos)
1630 {
1631         struct swap_info_struct *si;
1632         int type;
1633         loff_t l = *pos;
1634
1635         mutex_lock(&swapon_mutex);
1636
1637         if (!l)
1638                 return SEQ_START_TOKEN;
1639
1640         for (type = 0; type < nr_swapfiles; type++) {
1641                 smp_rmb();      /* read nr_swapfiles before swap_info[type] */
1642                 si = swap_info[type];
1643                 if (!(si->flags & SWP_USED) || !si->swap_map)
1644                         continue;
1645                 if (!--l)
1646                         return si;
1647         }
1648
1649         return NULL;
1650 }
1651
1652 static void *swap_next(struct seq_file *swap, void *v, loff_t *pos)
1653 {
1654         struct swap_info_struct *si = v;
1655         int type;
1656
1657         if (v == SEQ_START_TOKEN)
1658                 type = 0;
1659         else
1660                 type = si->type + 1;
1661
1662         for (; type < nr_swapfiles; type++) {
1663                 smp_rmb();      /* read nr_swapfiles before swap_info[type] */
1664                 si = swap_info[type];
1665                 if (!(si->flags & SWP_USED) || !si->swap_map)
1666                         continue;
1667                 ++*pos;
1668                 return si;
1669         }
1670
1671         return NULL;
1672 }
1673
1674 static void swap_stop(struct seq_file *swap, void *v)
1675 {
1676         mutex_unlock(&swapon_mutex);
1677 }
1678
1679 static int swap_show(struct seq_file *swap, void *v)
1680 {
1681         struct swap_info_struct *si = v;
1682         struct file *file;
1683         int len;
1684
1685         if (si == SEQ_START_TOKEN) {
1686                 seq_puts(swap,"Filename\t\t\t\tType\t\tSize\tUsed\tPriority\n");
1687                 return 0;
1688         }
1689
1690         file = si->swap_file;
1691         len = seq_path(swap, &file->f_path, " \t\n\\");
1692         seq_printf(swap, "%*s%s\t%u\t%u\t%d\n",
1693                         len < 40 ? 40 - len : 1, " ",
1694                         S_ISBLK(file->f_path.dentry->d_inode->i_mode) ?
1695                                 "partition" : "file\t",
1696                         si->pages << (PAGE_SHIFT - 10),
1697                         si->inuse_pages << (PAGE_SHIFT - 10),
1698                         si->prio);
1699         return 0;
1700 }
1701
1702 static const struct seq_operations swaps_op = {
1703         .start =        swap_start,
1704         .next =         swap_next,
1705         .stop =         swap_stop,
1706         .show =         swap_show
1707 };
1708
1709 static int swaps_open(struct inode *inode, struct file *file)
1710 {
1711         return seq_open(file, &swaps_op);
1712 }
1713
1714 static const struct file_operations proc_swaps_operations = {
1715         .open           = swaps_open,
1716         .read           = seq_read,
1717         .llseek         = seq_lseek,
1718         .release        = seq_release,
1719 };
1720
1721 static int __init procswaps_init(void)
1722 {
1723         proc_create("swaps", 0, NULL, &proc_swaps_operations);
1724         return 0;
1725 }
1726 __initcall(procswaps_init);
1727 #endif /* CONFIG_PROC_FS */
1728
1729 #ifdef MAX_SWAPFILES_CHECK
1730 static int __init max_swapfiles_check(void)
1731 {
1732         MAX_SWAPFILES_CHECK();
1733         return 0;
1734 }
1735 late_initcall(max_swapfiles_check);
1736 #endif
1737
1738 /*
1739  * Written 01/25/92 by Simmule Turner, heavily changed by Linus.
1740  *
1741  * The swapon system call
1742  */
1743 SYSCALL_DEFINE2(swapon, const char __user *, specialfile, int, swap_flags)
1744 {
1745         struct swap_info_struct *p;
1746         char *name = NULL;
1747         struct block_device *bdev = NULL;
1748         struct file *swap_file = NULL;
1749         struct address_space *mapping;
1750         unsigned int type;
1751         int i, prev;
1752         int error;
1753         union swap_header *swap_header = NULL;
1754         unsigned int nr_good_pages = 0;
1755         int nr_extents = 0;
1756         sector_t span;
1757         unsigned long maxpages = 1;
1758         unsigned long swapfilepages;
1759         unsigned char *swap_map = NULL;
1760         struct page *page = NULL;
1761         struct inode *inode = NULL;
1762         int did_down = 0;
1763
1764         if (!capable(CAP_SYS_ADMIN))
1765                 return -EPERM;
1766
1767         p = kzalloc(sizeof(*p), GFP_KERNEL);
1768         if (!p)
1769                 return -ENOMEM;
1770
1771         spin_lock(&swap_lock);
1772         for (type = 0; type < nr_swapfiles; type++) {
1773                 if (!(swap_info[type]->flags & SWP_USED))
1774                         break;
1775         }
1776         error = -EPERM;
1777         if (type >= MAX_SWAPFILES) {
1778                 spin_unlock(&swap_lock);
1779                 kfree(p);
1780                 goto out;
1781         }
1782         if (type >= nr_swapfiles) {
1783                 p->type = type;
1784                 swap_info[type] = p;
1785                 /*
1786                  * Write swap_info[type] before nr_swapfiles, in case a
1787                  * racing procfs swap_start() or swap_next() is reading them.
1788                  * (We never shrink nr_swapfiles, we never free this entry.)
1789                  */
1790                 smp_wmb();
1791                 nr_swapfiles++;
1792         } else {
1793                 kfree(p);
1794                 p = swap_info[type];
1795                 /*
1796                  * Do not memset this entry: a racing procfs swap_next()
1797                  * would be relying on p->type to remain valid.
1798                  */
1799         }
1800         INIT_LIST_HEAD(&p->first_swap_extent.list);
1801         p->flags = SWP_USED;
1802         p->next = -1;
1803         spin_unlock(&swap_lock);
1804
1805         name = getname(specialfile);
1806         error = PTR_ERR(name);
1807         if (IS_ERR(name)) {
1808                 name = NULL;
1809                 goto bad_swap_2;
1810         }
1811         swap_file = filp_open(name, O_RDWR|O_LARGEFILE, 0);
1812         error = PTR_ERR(swap_file);
1813         if (IS_ERR(swap_file)) {
1814                 swap_file = NULL;
1815                 goto bad_swap_2;
1816         }
1817
1818         p->swap_file = swap_file;
1819         mapping = swap_file->f_mapping;
1820         inode = mapping->host;
1821
1822         error = -EBUSY;
1823         for (i = 0; i < nr_swapfiles; i++) {
1824                 struct swap_info_struct *q = swap_info[i];
1825
1826                 if (i == type || !q->swap_file)
1827                         continue;
1828                 if (mapping == q->swap_file->f_mapping)
1829                         goto bad_swap;
1830         }
1831
1832         error = -EINVAL;
1833         if (S_ISBLK(inode->i_mode)) {
1834                 bdev = I_BDEV(inode);
1835                 error = bd_claim(bdev, sys_swapon);
1836                 if (error < 0) {
1837                         bdev = NULL;
1838                         error = -EINVAL;
1839                         goto bad_swap;
1840                 }
1841                 p->old_block_size = block_size(bdev);
1842                 error = set_blocksize(bdev, PAGE_SIZE);
1843                 if (error < 0)
1844                         goto bad_swap;
1845                 p->bdev = bdev;
1846         } else if (S_ISREG(inode->i_mode)) {
1847                 p->bdev = inode->i_sb->s_bdev;
1848                 mutex_lock(&inode->i_mutex);
1849                 did_down = 1;
1850                 if (IS_SWAPFILE(inode)) {
1851                         error = -EBUSY;
1852                         goto bad_swap;
1853                 }
1854         } else {
1855                 goto bad_swap;
1856         }
1857
1858         swapfilepages = i_size_read(inode) >> PAGE_SHIFT;
1859
1860         /*
1861          * Read the swap header.
1862          */
1863         if (!mapping->a_ops->readpage) {
1864                 error = -EINVAL;
1865                 goto bad_swap;
1866         }
1867         page = read_mapping_page(mapping, 0, swap_file);
1868         if (IS_ERR(page)) {
1869                 error = PTR_ERR(page);
1870                 goto bad_swap;
1871         }
1872         swap_header = kmap(page);
1873
1874         if (memcmp("SWAPSPACE2", swap_header->magic.magic, 10)) {
1875                 printk(KERN_ERR "Unable to find swap-space signature\n");
1876                 error = -EINVAL;
1877                 goto bad_swap;
1878         }
1879
1880         /* swap partition endianess hack... */
1881         if (swab32(swap_header->info.version) == 1) {
1882                 swab32s(&swap_header->info.version);
1883                 swab32s(&swap_header->info.last_page);
1884                 swab32s(&swap_header->info.nr_badpages);
1885                 for (i = 0; i < swap_header->info.nr_badpages; i++)
1886                         swab32s(&swap_header->info.badpages[i]);
1887         }
1888         /* Check the swap header's sub-version */
1889         if (swap_header->info.version != 1) {
1890                 printk(KERN_WARNING
1891                        "Unable to handle swap header version %d\n",
1892                        swap_header->info.version);
1893                 error = -EINVAL;
1894                 goto bad_swap;
1895         }
1896
1897         p->lowest_bit  = 1;
1898         p->cluster_next = 1;
1899         p->cluster_nr = 0;
1900
1901         /*
1902          * Find out how many pages are allowed for a single swap
1903          * device. There are two limiting factors: 1) the number of
1904          * bits for the swap offset in the swp_entry_t type and
1905          * 2) the number of bits in the a swap pte as defined by
1906          * the different architectures. In order to find the
1907          * largest possible bit mask a swap entry with swap type 0
1908          * and swap offset ~0UL is created, encoded to a swap pte,
1909          * decoded to a swp_entry_t again and finally the swap
1910          * offset is extracted. This will mask all the bits from
1911          * the initial ~0UL mask that can't be encoded in either
1912          * the swp_entry_t or the architecture definition of a
1913          * swap pte.
1914          */
1915         maxpages = swp_offset(pte_to_swp_entry(
1916                         swp_entry_to_pte(swp_entry(0, ~0UL)))) - 1;
1917         if (maxpages > swap_header->info.last_page)
1918                 maxpages = swap_header->info.last_page;
1919         p->highest_bit = maxpages - 1;
1920
1921         error = -EINVAL;
1922         if (!maxpages)
1923                 goto bad_swap;
1924         if (swapfilepages && maxpages > swapfilepages) {
1925                 printk(KERN_WARNING
1926                        "Swap area shorter than signature indicates\n");
1927                 goto bad_swap;
1928         }
1929         if (swap_header->info.nr_badpages && S_ISREG(inode->i_mode))
1930                 goto bad_swap;
1931         if (swap_header->info.nr_badpages > MAX_SWAP_BADPAGES)
1932                 goto bad_swap;
1933
1934         /* OK, set up the swap map and apply the bad block list */
1935         swap_map = vmalloc(maxpages);
1936         if (!swap_map) {
1937                 error = -ENOMEM;
1938                 goto bad_swap;
1939         }
1940
1941         memset(swap_map, 0, maxpages);
1942         for (i = 0; i < swap_header->info.nr_badpages; i++) {
1943                 int page_nr = swap_header->info.badpages[i];
1944                 if (page_nr <= 0 || page_nr >= swap_header->info.last_page) {
1945                         error = -EINVAL;
1946                         goto bad_swap;
1947                 }
1948                 swap_map[page_nr] = SWAP_MAP_BAD;
1949         }
1950
1951         error = swap_cgroup_swapon(type, maxpages);
1952         if (error)
1953                 goto bad_swap;
1954
1955         nr_good_pages = swap_header->info.last_page -
1956                         swap_header->info.nr_badpages -
1957                         1 /* header page */;
1958
1959         if (nr_good_pages) {
1960                 swap_map[0] = SWAP_MAP_BAD;
1961                 p->max = maxpages;
1962                 p->pages = nr_good_pages;
1963                 nr_extents = setup_swap_extents(p, &span);
1964                 if (nr_extents < 0) {
1965                         error = nr_extents;
1966                         goto bad_swap;
1967                 }
1968                 nr_good_pages = p->pages;
1969         }
1970         if (!nr_good_pages) {
1971                 printk(KERN_WARNING "Empty swap-file\n");
1972                 error = -EINVAL;
1973                 goto bad_swap;
1974         }
1975
1976         if (p->bdev) {
1977                 if (blk_queue_nonrot(bdev_get_queue(p->bdev))) {
1978                         p->flags |= SWP_SOLIDSTATE;
1979                         p->cluster_next = 1 + (random32() % p->highest_bit);
1980                 }
1981                 if (discard_swap(p) == 0)
1982                         p->flags |= SWP_DISCARDABLE;
1983         }
1984
1985         mutex_lock(&swapon_mutex);
1986         spin_lock(&swap_lock);
1987         if (swap_flags & SWAP_FLAG_PREFER)
1988                 p->prio =
1989                   (swap_flags & SWAP_FLAG_PRIO_MASK) >> SWAP_FLAG_PRIO_SHIFT;
1990         else
1991                 p->prio = --least_priority;
1992         p->swap_map = swap_map;
1993         p->flags |= SWP_WRITEOK;
1994         nr_swap_pages += nr_good_pages;
1995         total_swap_pages += nr_good_pages;
1996
1997         printk(KERN_INFO "Adding %uk swap on %s.  "
1998                         "Priority:%d extents:%d across:%lluk %s%s\n",
1999                 nr_good_pages<<(PAGE_SHIFT-10), name, p->prio,
2000                 nr_extents, (unsigned long long)span<<(PAGE_SHIFT-10),
2001                 (p->flags & SWP_SOLIDSTATE) ? "SS" : "",
2002                 (p->flags & SWP_DISCARDABLE) ? "D" : "");
2003
2004         /* insert swap space into swap_list: */
2005         prev = -1;
2006         for (i = swap_list.head; i >= 0; i = swap_info[i]->next) {
2007                 if (p->prio >= swap_info[i]->prio)
2008                         break;
2009                 prev = i;
2010         }
2011         p->next = i;
2012         if (prev < 0)
2013                 swap_list.head = swap_list.next = type;
2014         else
2015                 swap_info[prev]->next = type;
2016         spin_unlock(&swap_lock);
2017         mutex_unlock(&swapon_mutex);
2018         error = 0;
2019         goto out;
2020 bad_swap:
2021         if (bdev) {
2022                 set_blocksize(bdev, p->old_block_size);
2023                 bd_release(bdev);
2024         }
2025         destroy_swap_extents(p);
2026         swap_cgroup_swapoff(type);
2027 bad_swap_2:
2028         spin_lock(&swap_lock);
2029         p->swap_file = NULL;
2030         p->flags = 0;
2031         spin_unlock(&swap_lock);
2032         vfree(swap_map);
2033         if (swap_file)
2034                 filp_close(swap_file, NULL);
2035 out:
2036         if (page && !IS_ERR(page)) {
2037                 kunmap(page);
2038                 page_cache_release(page);
2039         }
2040         if (name)
2041                 putname(name);
2042         if (did_down) {
2043                 if (!error)
2044                         inode->i_flags |= S_SWAPFILE;
2045                 mutex_unlock(&inode->i_mutex);
2046         }
2047         return error;
2048 }
2049
2050 void si_swapinfo(struct sysinfo *val)
2051 {
2052         unsigned int type;
2053         unsigned long nr_to_be_unused = 0;
2054
2055         spin_lock(&swap_lock);
2056         for (type = 0; type < nr_swapfiles; type++) {
2057                 struct swap_info_struct *si = swap_info[type];
2058
2059                 if ((si->flags & SWP_USED) && !(si->flags & SWP_WRITEOK))
2060                         nr_to_be_unused += si->inuse_pages;
2061         }
2062         val->freeswap = nr_swap_pages + nr_to_be_unused;
2063         val->totalswap = total_swap_pages + nr_to_be_unused;
2064         spin_unlock(&swap_lock);
2065 }
2066
2067 /*
2068  * Verify that a swap entry is valid and increment its swap map count.
2069  *
2070  * Returns error code in following case.
2071  * - success -> 0
2072  * - swp_entry is invalid -> EINVAL
2073  * - swp_entry is migration entry -> EINVAL
2074  * - swap-cache reference is requested but there is already one. -> EEXIST
2075  * - swap-cache reference is requested but the entry is not used. -> ENOENT
2076  * - swap-mapped reference requested but needs continued swap count. -> ENOMEM
2077  */
2078 static int __swap_duplicate(swp_entry_t entry, unsigned char usage)
2079 {
2080         struct swap_info_struct *p;
2081         unsigned long offset, type;
2082         unsigned char count;
2083         unsigned char has_cache;
2084         int err = -EINVAL;
2085
2086         if (non_swap_entry(entry))
2087                 goto out;
2088
2089         type = swp_type(entry);
2090         if (type >= nr_swapfiles)
2091                 goto bad_file;
2092         p = swap_info[type];
2093         offset = swp_offset(entry);
2094
2095         spin_lock(&swap_lock);
2096         if (unlikely(offset >= p->max))
2097                 goto unlock_out;
2098
2099         count = p->swap_map[offset];
2100         has_cache = count & SWAP_HAS_CACHE;
2101         count &= ~SWAP_HAS_CACHE;
2102         err = 0;
2103
2104         if (usage == SWAP_HAS_CACHE) {
2105
2106                 /* set SWAP_HAS_CACHE if there is no cache and entry is used */
2107                 if (!has_cache && count)
2108                         has_cache = SWAP_HAS_CACHE;
2109                 else if (has_cache)             /* someone else added cache */
2110                         err = -EEXIST;
2111                 else                            /* no users remaining */
2112                         err = -ENOENT;
2113
2114         } else if (count || has_cache) {
2115
2116                 if ((count & ~COUNT_CONTINUED) < SWAP_MAP_MAX)
2117                         count += usage;
2118                 else if ((count & ~COUNT_CONTINUED) > SWAP_MAP_MAX)
2119                         err = -EINVAL;
2120                 else if (swap_count_continued(p, offset, count))
2121                         count = COUNT_CONTINUED;
2122                 else
2123                         err = -ENOMEM;
2124         } else
2125                 err = -ENOENT;                  /* unused swap entry */
2126
2127         p->swap_map[offset] = count | has_cache;
2128
2129 unlock_out:
2130         spin_unlock(&swap_lock);
2131 out:
2132         return err;
2133
2134 bad_file:
2135         printk(KERN_ERR "swap_dup: %s%08lx\n", Bad_file, entry.val);
2136         goto out;
2137 }
2138
2139 /*
2140  * Help swapoff by noting that swap entry belongs to shmem/tmpfs
2141  * (in which case its reference count is never incremented).
2142  */
2143 void swap_shmem_alloc(swp_entry_t entry)
2144 {
2145         __swap_duplicate(entry, SWAP_MAP_SHMEM);
2146 }
2147
2148 /*
2149  * increase reference count of swap entry by 1.
2150  */
2151 int swap_duplicate(swp_entry_t entry)
2152 {
2153         int err = 0;
2154
2155         while (!err && __swap_duplicate(entry, 1) == -ENOMEM)
2156                 err = add_swap_count_continuation(entry, GFP_ATOMIC);
2157         return err;
2158 }
2159
2160 /*
2161  * @entry: swap entry for which we allocate swap cache.
2162  *
2163  * Called when allocating swap cache for existing swap entry,
2164  * This can return error codes. Returns 0 at success.
2165  * -EBUSY means there is a swap cache.
2166  * Note: return code is different from swap_duplicate().
2167  */
2168 int swapcache_prepare(swp_entry_t entry)
2169 {
2170         return __swap_duplicate(entry, SWAP_HAS_CACHE);
2171 }
2172
2173 /*
2174  * swap_lock prevents swap_map being freed. Don't grab an extra
2175  * reference on the swaphandle, it doesn't matter if it becomes unused.
2176  */
2177 int valid_swaphandles(swp_entry_t entry, unsigned long *offset)
2178 {
2179         struct swap_info_struct *si;
2180         int our_page_cluster = page_cluster;
2181         pgoff_t target, toff;
2182         pgoff_t base, end;
2183         int nr_pages = 0;
2184
2185         if (!our_page_cluster)  /* no readahead */
2186                 return 0;
2187
2188         si = swap_info[swp_type(entry)];
2189         target = swp_offset(entry);
2190         base = (target >> our_page_cluster) << our_page_cluster;
2191         end = base + (1 << our_page_cluster);
2192         if (!base)              /* first page is swap header */
2193                 base++;
2194
2195         spin_lock(&swap_lock);
2196         if (end > si->max)      /* don't go beyond end of map */
2197                 end = si->max;
2198
2199         /* Count contiguous allocated slots above our target */
2200         for (toff = target; ++toff < end; nr_pages++) {
2201                 /* Don't read in free or bad pages */
2202                 if (!si->swap_map[toff])
2203                         break;
2204                 if (swap_count(si->swap_map[toff]) == SWAP_MAP_BAD)
2205                         break;
2206         }
2207         /* Count contiguous allocated slots below our target */
2208         for (toff = target; --toff >= base; nr_pages++) {
2209                 /* Don't read in free or bad pages */
2210                 if (!si->swap_map[toff])
2211                         break;
2212                 if (swap_count(si->swap_map[toff]) == SWAP_MAP_BAD)
2213                         break;
2214         }
2215         spin_unlock(&swap_lock);
2216
2217         /*
2218          * Indicate starting offset, and return number of pages to get:
2219          * if only 1, say 0, since there's then no readahead to be done.
2220          */
2221         *offset = ++toff;
2222         return nr_pages? ++nr_pages: 0;
2223 }
2224
2225 /*
2226  * add_swap_count_continuation - called when a swap count is duplicated
2227  * beyond SWAP_MAP_MAX, it allocates a new page and links that to the entry's
2228  * page of the original vmalloc'ed swap_map, to hold the continuation count
2229  * (for that entry and for its neighbouring PAGE_SIZE swap entries).  Called
2230  * again when count is duplicated beyond SWAP_MAP_MAX * SWAP_CONT_MAX, etc.
2231  *
2232  * These continuation pages are seldom referenced: the common paths all work
2233  * on the original swap_map, only referring to a continuation page when the
2234  * low "digit" of a count is incremented or decremented through SWAP_MAP_MAX.
2235  *
2236  * add_swap_count_continuation(, GFP_ATOMIC) can be called while holding
2237  * page table locks; if it fails, add_swap_count_continuation(, GFP_KERNEL)
2238  * can be called after dropping locks.
2239  */
2240 int add_swap_count_continuation(swp_entry_t entry, gfp_t gfp_mask)
2241 {
2242         struct swap_info_struct *si;
2243         struct page *head;
2244         struct page *page;
2245         struct page *list_page;
2246         pgoff_t offset;
2247         unsigned char count;
2248
2249         /*
2250          * When debugging, it's easier to use __GFP_ZERO here; but it's better
2251          * for latency not to zero a page while GFP_ATOMIC and holding locks.
2252          */
2253         page = alloc_page(gfp_mask | __GFP_HIGHMEM);
2254
2255         si = swap_info_get(entry);
2256         if (!si) {
2257                 /*
2258                  * An acceptable race has occurred since the failing
2259                  * __swap_duplicate(): the swap entry has been freed,
2260                  * perhaps even the whole swap_map cleared for swapoff.
2261                  */
2262                 goto outer;
2263         }
2264
2265         offset = swp_offset(entry);
2266         count = si->swap_map[offset] & ~SWAP_HAS_CACHE;
2267
2268         if ((count & ~COUNT_CONTINUED) != SWAP_MAP_MAX) {
2269                 /*
2270                  * The higher the swap count, the more likely it is that tasks
2271                  * will race to add swap count continuation: we need to avoid
2272                  * over-provisioning.
2273                  */
2274                 goto out;
2275         }
2276
2277         if (!page) {
2278                 spin_unlock(&swap_lock);
2279                 return -ENOMEM;
2280         }
2281
2282         /*
2283          * We are fortunate that although vmalloc_to_page uses pte_offset_map,
2284          * no architecture is using highmem pages for kernel pagetables: so it
2285          * will not corrupt the GFP_ATOMIC caller's atomic pagetable kmaps.
2286          */
2287         head = vmalloc_to_page(si->swap_map + offset);
2288         offset &= ~PAGE_MASK;
2289
2290         /*
2291          * Page allocation does not initialize the page's lru field,
2292          * but it does always reset its private field.
2293          */
2294         if (!page_private(head)) {
2295                 BUG_ON(count & COUNT_CONTINUED);
2296                 INIT_LIST_HEAD(&head->lru);
2297                 set_page_private(head, SWP_CONTINUED);
2298                 si->flags |= SWP_CONTINUED;
2299         }
2300
2301         list_for_each_entry(list_page, &head->lru, lru) {
2302                 unsigned char *map;
2303
2304                 /*
2305                  * If the previous map said no continuation, but we've found
2306                  * a continuation page, free our allocation and use this one.
2307                  */
2308                 if (!(count & COUNT_CONTINUED))
2309                         goto out;
2310
2311                 map = kmap_atomic(list_page, KM_USER0) + offset;
2312                 count = *map;
2313                 kunmap_atomic(map, KM_USER0);
2314
2315                 /*
2316                  * If this continuation count now has some space in it,
2317                  * free our allocation and use this one.
2318                  */
2319                 if ((count & ~COUNT_CONTINUED) != SWAP_CONT_MAX)
2320                         goto out;
2321         }
2322
2323         list_add_tail(&page->lru, &head->lru);
2324         page = NULL;                    /* now it's attached, don't free it */
2325 out:
2326         spin_unlock(&swap_lock);
2327 outer:
2328         if (page)
2329                 __free_page(page);
2330         return 0;
2331 }
2332
2333 /*
2334  * swap_count_continued - when the original swap_map count is incremented
2335  * from SWAP_MAP_MAX, check if there is already a continuation page to carry
2336  * into, carry if so, or else fail until a new continuation page is allocated;
2337  * when the original swap_map count is decremented from 0 with continuation,
2338  * borrow from the continuation and report whether it still holds more.
2339  * Called while __swap_duplicate() or swap_entry_free() holds swap_lock.
2340  */
2341 static bool swap_count_continued(struct swap_info_struct *si,
2342                                  pgoff_t offset, unsigned char count)
2343 {
2344         struct page *head;
2345         struct page *page;
2346         unsigned char *map;
2347
2348         head = vmalloc_to_page(si->swap_map + offset);
2349         if (page_private(head) != SWP_CONTINUED) {
2350                 BUG_ON(count & COUNT_CONTINUED);
2351                 return false;           /* need to add count continuation */
2352         }
2353
2354         offset &= ~PAGE_MASK;
2355         page = list_entry(head->lru.next, struct page, lru);
2356         map = kmap_atomic(page, KM_USER0) + offset;
2357
2358         if (count == SWAP_MAP_MAX)      /* initial increment from swap_map */
2359                 goto init_map;          /* jump over SWAP_CONT_MAX checks */
2360
2361         if (count == (SWAP_MAP_MAX | COUNT_CONTINUED)) { /* incrementing */
2362                 /*
2363                  * Think of how you add 1 to 999
2364                  */
2365                 while (*map == (SWAP_CONT_MAX | COUNT_CONTINUED)) {
2366                         kunmap_atomic(map, KM_USER0);
2367                         page = list_entry(page->lru.next, struct page, lru);
2368                         BUG_ON(page == head);
2369                         map = kmap_atomic(page, KM_USER0) + offset;
2370                 }
2371                 if (*map == SWAP_CONT_MAX) {
2372                         kunmap_atomic(map, KM_USER0);
2373                         page = list_entry(page->lru.next, struct page, lru);
2374                         if (page == head)
2375                                 return false;   /* add count continuation */
2376                         map = kmap_atomic(page, KM_USER0) + offset;
2377 init_map:               *map = 0;               /* we didn't zero the page */
2378                 }
2379                 *map += 1;
2380                 kunmap_atomic(map, KM_USER0);
2381                 page = list_entry(page->lru.prev, struct page, lru);
2382                 while (page != head) {
2383                         map = kmap_atomic(page, KM_USER0) + offset;
2384                         *map = COUNT_CONTINUED;
2385                         kunmap_atomic(map, KM_USER0);
2386                         page = list_entry(page->lru.prev, struct page, lru);
2387                 }
2388                 return true;                    /* incremented */
2389
2390         } else {                                /* decrementing */
2391                 /*
2392                  * Think of how you subtract 1 from 1000
2393                  */
2394                 BUG_ON(count != COUNT_CONTINUED);
2395                 while (*map == COUNT_CONTINUED) {
2396                         kunmap_atomic(map, KM_USER0);
2397                         page = list_entry(page->lru.next, struct page, lru);
2398                         BUG_ON(page == head);
2399                         map = kmap_atomic(page, KM_USER0) + offset;
2400                 }
2401                 BUG_ON(*map == 0);
2402                 *map -= 1;
2403                 if (*map == 0)
2404                         count = 0;
2405                 kunmap_atomic(map, KM_USER0);
2406                 page = list_entry(page->lru.prev, struct page, lru);
2407                 while (page != head) {
2408                         map = kmap_atomic(page, KM_USER0) + offset;
2409                         *map = SWAP_CONT_MAX | count;
2410                         count = COUNT_CONTINUED;
2411                         kunmap_atomic(map, KM_USER0);
2412                         page = list_entry(page->lru.prev, struct page, lru);
2413                 }
2414                 return count == COUNT_CONTINUED;
2415         }
2416 }
2417
2418 /*
2419  * free_swap_count_continuations - swapoff free all the continuation pages
2420  * appended to the swap_map, after swap_map is quiesced, before vfree'ing it.
2421  */
2422 static void free_swap_count_continuations(struct swap_info_struct *si)
2423 {
2424         pgoff_t offset;
2425
2426         for (offset = 0; offset < si->max; offset += PAGE_SIZE) {
2427                 struct page *head;
2428                 head = vmalloc_to_page(si->swap_map + offset);
2429                 if (page_private(head)) {
2430                         struct list_head *this, *next;
2431                         list_for_each_safe(this, next, &head->lru) {
2432                                 struct page *page;
2433                                 page = list_entry(this, struct page, lru);
2434                                 list_del(this);
2435                                 __free_page(page);
2436                         }
2437                 }
2438         }
2439 }