PM / hibernate: Add missing braces in __register_nosave_region()
[cascardo/linux.git] / kernel / power / snapshot.c
1 /*
2  * linux/kernel/power/snapshot.c
3  *
4  * This file provides system snapshot/restore functionality for swsusp.
5  *
6  * Copyright (C) 1998-2005 Pavel Machek <pavel@ucw.cz>
7  * Copyright (C) 2006 Rafael J. Wysocki <rjw@sisk.pl>
8  *
9  * This file is released under the GPLv2.
10  *
11  */
12
13 #include <linux/version.h>
14 #include <linux/module.h>
15 #include <linux/mm.h>
16 #include <linux/suspend.h>
17 #include <linux/delay.h>
18 #include <linux/bitops.h>
19 #include <linux/spinlock.h>
20 #include <linux/kernel.h>
21 #include <linux/pm.h>
22 #include <linux/device.h>
23 #include <linux/init.h>
24 #include <linux/bootmem.h>
25 #include <linux/syscalls.h>
26 #include <linux/console.h>
27 #include <linux/highmem.h>
28 #include <linux/list.h>
29 #include <linux/slab.h>
30 #include <linux/compiler.h>
31 #include <linux/ktime.h>
32
33 #include <asm/uaccess.h>
34 #include <asm/mmu_context.h>
35 #include <asm/pgtable.h>
36 #include <asm/tlbflush.h>
37 #include <asm/io.h>
38
39 #include "power.h"
40
41 static int swsusp_page_is_free(struct page *);
42 static void swsusp_set_page_forbidden(struct page *);
43 static void swsusp_unset_page_forbidden(struct page *);
44
45 /*
46  * Number of bytes to reserve for memory allocations made by device drivers
47  * from their ->freeze() and ->freeze_noirq() callbacks so that they don't
48  * cause image creation to fail (tunable via /sys/power/reserved_size).
49  */
50 unsigned long reserved_size;
51
52 void __init hibernate_reserved_size_init(void)
53 {
54         reserved_size = SPARE_PAGES * PAGE_SIZE;
55 }
56
57 /*
58  * Preferred image size in bytes (tunable via /sys/power/image_size).
59  * When it is set to N, swsusp will do its best to ensure the image
60  * size will not exceed N bytes, but if that is impossible, it will
61  * try to create the smallest image possible.
62  */
63 unsigned long image_size;
64
65 void __init hibernate_image_size_init(void)
66 {
67         image_size = ((totalram_pages * 2) / 5) * PAGE_SIZE;
68 }
69
70 /*
71  * List of PBEs needed for restoring the pages that were allocated before
72  * the suspend and included in the suspend image, but have also been
73  * allocated by the "resume" kernel, so their contents cannot be written
74  * directly to their "original" page frames.
75  */
76 struct pbe *restore_pblist;
77
78 /* struct linked_page is used to build chains of pages */
79
80 #define LINKED_PAGE_DATA_SIZE   (PAGE_SIZE - sizeof(void *))
81
82 struct linked_page {
83         struct linked_page *next;
84         char data[LINKED_PAGE_DATA_SIZE];
85 } __packed;
86
87 /*
88  * List of "safe" pages (ie. pages that were not used by the image kernel
89  * before hibernation) that may be used as temporary storage for image kernel
90  * memory contents.
91  */
92 static struct linked_page *safe_pages_list;
93
94 /* Pointer to an auxiliary buffer (1 page) */
95 static void *buffer;
96
97 #define PG_ANY          0
98 #define PG_SAFE         1
99 #define PG_UNSAFE_CLEAR 1
100 #define PG_UNSAFE_KEEP  0
101
102 static unsigned int allocated_unsafe_pages;
103
104 /**
105  * get_image_page - Allocate a page for a hibernation image.
106  * @gfp_mask: GFP mask for the allocation.
107  * @safe_needed: Get pages that were not used before hibernation (restore only)
108  *
109  * During image restoration, for storing the PBE list and the image data, we can
110  * only use memory pages that do not conflict with the pages used before
111  * hibernation.  The "unsafe" pages have PageNosaveFree set and we count them
112  * using allocated_unsafe_pages.
113  *
114  * Each allocated image page is marked as PageNosave and PageNosaveFree so that
115  * swsusp_free() can release it.
116  */
117 static void *get_image_page(gfp_t gfp_mask, int safe_needed)
118 {
119         void *res;
120
121         res = (void *)get_zeroed_page(gfp_mask);
122         if (safe_needed)
123                 while (res && swsusp_page_is_free(virt_to_page(res))) {
124                         /* The page is unsafe, mark it for swsusp_free() */
125                         swsusp_set_page_forbidden(virt_to_page(res));
126                         allocated_unsafe_pages++;
127                         res = (void *)get_zeroed_page(gfp_mask);
128                 }
129         if (res) {
130                 swsusp_set_page_forbidden(virt_to_page(res));
131                 swsusp_set_page_free(virt_to_page(res));
132         }
133         return res;
134 }
135
136 static void *__get_safe_page(gfp_t gfp_mask)
137 {
138         if (safe_pages_list) {
139                 void *ret = safe_pages_list;
140
141                 safe_pages_list = safe_pages_list->next;
142                 memset(ret, 0, PAGE_SIZE);
143                 return ret;
144         }
145         return get_image_page(gfp_mask, PG_SAFE);
146 }
147
148 unsigned long get_safe_page(gfp_t gfp_mask)
149 {
150         return (unsigned long)__get_safe_page(gfp_mask);
151 }
152
153 static struct page *alloc_image_page(gfp_t gfp_mask)
154 {
155         struct page *page;
156
157         page = alloc_page(gfp_mask);
158         if (page) {
159                 swsusp_set_page_forbidden(page);
160                 swsusp_set_page_free(page);
161         }
162         return page;
163 }
164
165 static void recycle_safe_page(void *page_address)
166 {
167         struct linked_page *lp = page_address;
168
169         lp->next = safe_pages_list;
170         safe_pages_list = lp;
171 }
172
173 /**
174  * free_image_page - Free a page allocated for hibernation image.
175  * @addr: Address of the page to free.
176  * @clear_nosave_free: If set, clear the PageNosaveFree bit for the page.
177  *
178  * The page to free should have been allocated by get_image_page() (page flags
179  * set by it are affected).
180  */
181 static inline void free_image_page(void *addr, int clear_nosave_free)
182 {
183         struct page *page;
184
185         BUG_ON(!virt_addr_valid(addr));
186
187         page = virt_to_page(addr);
188
189         swsusp_unset_page_forbidden(page);
190         if (clear_nosave_free)
191                 swsusp_unset_page_free(page);
192
193         __free_page(page);
194 }
195
196 static inline void free_list_of_pages(struct linked_page *list,
197                                       int clear_page_nosave)
198 {
199         while (list) {
200                 struct linked_page *lp = list->next;
201
202                 free_image_page(list, clear_page_nosave);
203                 list = lp;
204         }
205 }
206
207 /*
208  * struct chain_allocator is used for allocating small objects out of
209  * a linked list of pages called 'the chain'.
210  *
211  * The chain grows each time when there is no room for a new object in
212  * the current page.  The allocated objects cannot be freed individually.
213  * It is only possible to free them all at once, by freeing the entire
214  * chain.
215  *
216  * NOTE: The chain allocator may be inefficient if the allocated objects
217  * are not much smaller than PAGE_SIZE.
218  */
219 struct chain_allocator {
220         struct linked_page *chain;      /* the chain */
221         unsigned int used_space;        /* total size of objects allocated out
222                                            of the current page */
223         gfp_t gfp_mask;         /* mask for allocating pages */
224         int safe_needed;        /* if set, only "safe" pages are allocated */
225 };
226
227 static void chain_init(struct chain_allocator *ca, gfp_t gfp_mask,
228                        int safe_needed)
229 {
230         ca->chain = NULL;
231         ca->used_space = LINKED_PAGE_DATA_SIZE;
232         ca->gfp_mask = gfp_mask;
233         ca->safe_needed = safe_needed;
234 }
235
236 static void *chain_alloc(struct chain_allocator *ca, unsigned int size)
237 {
238         void *ret;
239
240         if (LINKED_PAGE_DATA_SIZE - ca->used_space < size) {
241                 struct linked_page *lp;
242
243                 lp = ca->safe_needed ? __get_safe_page(ca->gfp_mask) :
244                                         get_image_page(ca->gfp_mask, PG_ANY);
245                 if (!lp)
246                         return NULL;
247
248                 lp->next = ca->chain;
249                 ca->chain = lp;
250                 ca->used_space = 0;
251         }
252         ret = ca->chain->data + ca->used_space;
253         ca->used_space += size;
254         return ret;
255 }
256
257 /**
258  * Data types related to memory bitmaps.
259  *
260  * Memory bitmap is a structure consiting of many linked lists of
261  * objects.  The main list's elements are of type struct zone_bitmap
262  * and each of them corresonds to one zone.  For each zone bitmap
263  * object there is a list of objects of type struct bm_block that
264  * represent each blocks of bitmap in which information is stored.
265  *
266  * struct memory_bitmap contains a pointer to the main list of zone
267  * bitmap objects, a struct bm_position used for browsing the bitmap,
268  * and a pointer to the list of pages used for allocating all of the
269  * zone bitmap objects and bitmap block objects.
270  *
271  * NOTE: It has to be possible to lay out the bitmap in memory
272  * using only allocations of order 0.  Additionally, the bitmap is
273  * designed to work with arbitrary number of zones (this is over the
274  * top for now, but let's avoid making unnecessary assumptions ;-).
275  *
276  * struct zone_bitmap contains a pointer to a list of bitmap block
277  * objects and a pointer to the bitmap block object that has been
278  * most recently used for setting bits.  Additionally, it contains the
279  * PFNs that correspond to the start and end of the represented zone.
280  *
281  * struct bm_block contains a pointer to the memory page in which
282  * information is stored (in the form of a block of bitmap)
283  * It also contains the pfns that correspond to the start and end of
284  * the represented memory area.
285  *
286  * The memory bitmap is organized as a radix tree to guarantee fast random
287  * access to the bits. There is one radix tree for each zone (as returned
288  * from create_mem_extents).
289  *
290  * One radix tree is represented by one struct mem_zone_bm_rtree. There are
291  * two linked lists for the nodes of the tree, one for the inner nodes and
292  * one for the leave nodes. The linked leave nodes are used for fast linear
293  * access of the memory bitmap.
294  *
295  * The struct rtree_node represents one node of the radix tree.
296  */
297
298 #define BM_END_OF_MAP   (~0UL)
299
300 #define BM_BITS_PER_BLOCK       (PAGE_SIZE * BITS_PER_BYTE)
301 #define BM_BLOCK_SHIFT          (PAGE_SHIFT + 3)
302 #define BM_BLOCK_MASK           ((1UL << BM_BLOCK_SHIFT) - 1)
303
304 /*
305  * struct rtree_node is a wrapper struct to link the nodes
306  * of the rtree together for easy linear iteration over
307  * bits and easy freeing
308  */
309 struct rtree_node {
310         struct list_head list;
311         unsigned long *data;
312 };
313
314 /*
315  * struct mem_zone_bm_rtree represents a bitmap used for one
316  * populated memory zone.
317  */
318 struct mem_zone_bm_rtree {
319         struct list_head list;          /* Link Zones together         */
320         struct list_head nodes;         /* Radix Tree inner nodes      */
321         struct list_head leaves;        /* Radix Tree leaves           */
322         unsigned long start_pfn;        /* Zone start page frame       */
323         unsigned long end_pfn;          /* Zone end page frame + 1     */
324         struct rtree_node *rtree;       /* Radix Tree Root             */
325         int levels;                     /* Number of Radix Tree Levels */
326         unsigned int blocks;            /* Number of Bitmap Blocks     */
327 };
328
329 /* strcut bm_position is used for browsing memory bitmaps */
330
331 struct bm_position {
332         struct mem_zone_bm_rtree *zone;
333         struct rtree_node *node;
334         unsigned long node_pfn;
335         int node_bit;
336 };
337
338 struct memory_bitmap {
339         struct list_head zones;
340         struct linked_page *p_list;     /* list of pages used to store zone
341                                            bitmap objects and bitmap block
342                                            objects */
343         struct bm_position cur; /* most recently used bit position */
344 };
345
346 /* Functions that operate on memory bitmaps */
347
348 #define BM_ENTRIES_PER_LEVEL    (PAGE_SIZE / sizeof(unsigned long))
349 #if BITS_PER_LONG == 32
350 #define BM_RTREE_LEVEL_SHIFT    (PAGE_SHIFT - 2)
351 #else
352 #define BM_RTREE_LEVEL_SHIFT    (PAGE_SHIFT - 3)
353 #endif
354 #define BM_RTREE_LEVEL_MASK     ((1UL << BM_RTREE_LEVEL_SHIFT) - 1)
355
356 /**
357  * alloc_rtree_node - Allocate a new node and add it to the radix tree.
358  *
359  * This function is used to allocate inner nodes as well as the
360  * leave nodes of the radix tree. It also adds the node to the
361  * corresponding linked list passed in by the *list parameter.
362  */
363 static struct rtree_node *alloc_rtree_node(gfp_t gfp_mask, int safe_needed,
364                                            struct chain_allocator *ca,
365                                            struct list_head *list)
366 {
367         struct rtree_node *node;
368
369         node = chain_alloc(ca, sizeof(struct rtree_node));
370         if (!node)
371                 return NULL;
372
373         node->data = get_image_page(gfp_mask, safe_needed);
374         if (!node->data)
375                 return NULL;
376
377         list_add_tail(&node->list, list);
378
379         return node;
380 }
381
382 /**
383  * add_rtree_block - Add a new leave node to the radix tree.
384  *
385  * The leave nodes need to be allocated in order to keep the leaves
386  * linked list in order. This is guaranteed by the zone->blocks
387  * counter.
388  */
389 static int add_rtree_block(struct mem_zone_bm_rtree *zone, gfp_t gfp_mask,
390                            int safe_needed, struct chain_allocator *ca)
391 {
392         struct rtree_node *node, *block, **dst;
393         unsigned int levels_needed, block_nr;
394         int i;
395
396         block_nr = zone->blocks;
397         levels_needed = 0;
398
399         /* How many levels do we need for this block nr? */
400         while (block_nr) {
401                 levels_needed += 1;
402                 block_nr >>= BM_RTREE_LEVEL_SHIFT;
403         }
404
405         /* Make sure the rtree has enough levels */
406         for (i = zone->levels; i < levels_needed; i++) {
407                 node = alloc_rtree_node(gfp_mask, safe_needed, ca,
408                                         &zone->nodes);
409                 if (!node)
410                         return -ENOMEM;
411
412                 node->data[0] = (unsigned long)zone->rtree;
413                 zone->rtree = node;
414                 zone->levels += 1;
415         }
416
417         /* Allocate new block */
418         block = alloc_rtree_node(gfp_mask, safe_needed, ca, &zone->leaves);
419         if (!block)
420                 return -ENOMEM;
421
422         /* Now walk the rtree to insert the block */
423         node = zone->rtree;
424         dst = &zone->rtree;
425         block_nr = zone->blocks;
426         for (i = zone->levels; i > 0; i--) {
427                 int index;
428
429                 if (!node) {
430                         node = alloc_rtree_node(gfp_mask, safe_needed, ca,
431                                                 &zone->nodes);
432                         if (!node)
433                                 return -ENOMEM;
434                         *dst = node;
435                 }
436
437                 index = block_nr >> ((i - 1) * BM_RTREE_LEVEL_SHIFT);
438                 index &= BM_RTREE_LEVEL_MASK;
439                 dst = (struct rtree_node **)&((*dst)->data[index]);
440                 node = *dst;
441         }
442
443         zone->blocks += 1;
444         *dst = block;
445
446         return 0;
447 }
448
449 static void free_zone_bm_rtree(struct mem_zone_bm_rtree *zone,
450                                int clear_nosave_free);
451
452 /**
453  * create_zone_bm_rtree - Create a radix tree for one zone.
454  *
455  * Allocated the mem_zone_bm_rtree structure and initializes it.
456  * This function also allocated and builds the radix tree for the
457  * zone.
458  */
459 static struct mem_zone_bm_rtree *create_zone_bm_rtree(gfp_t gfp_mask,
460                                                       int safe_needed,
461                                                       struct chain_allocator *ca,
462                                                       unsigned long start,
463                                                       unsigned long end)
464 {
465         struct mem_zone_bm_rtree *zone;
466         unsigned int i, nr_blocks;
467         unsigned long pages;
468
469         pages = end - start;
470         zone  = chain_alloc(ca, sizeof(struct mem_zone_bm_rtree));
471         if (!zone)
472                 return NULL;
473
474         INIT_LIST_HEAD(&zone->nodes);
475         INIT_LIST_HEAD(&zone->leaves);
476         zone->start_pfn = start;
477         zone->end_pfn = end;
478         nr_blocks = DIV_ROUND_UP(pages, BM_BITS_PER_BLOCK);
479
480         for (i = 0; i < nr_blocks; i++) {
481                 if (add_rtree_block(zone, gfp_mask, safe_needed, ca)) {
482                         free_zone_bm_rtree(zone, PG_UNSAFE_CLEAR);
483                         return NULL;
484                 }
485         }
486
487         return zone;
488 }
489
490 /**
491  * free_zone_bm_rtree - Free the memory of the radix tree.
492  *
493  * Free all node pages of the radix tree. The mem_zone_bm_rtree
494  * structure itself is not freed here nor are the rtree_node
495  * structs.
496  */
497 static void free_zone_bm_rtree(struct mem_zone_bm_rtree *zone,
498                                int clear_nosave_free)
499 {
500         struct rtree_node *node;
501
502         list_for_each_entry(node, &zone->nodes, list)
503                 free_image_page(node->data, clear_nosave_free);
504
505         list_for_each_entry(node, &zone->leaves, list)
506                 free_image_page(node->data, clear_nosave_free);
507 }
508
509 static void memory_bm_position_reset(struct memory_bitmap *bm)
510 {
511         bm->cur.zone = list_entry(bm->zones.next, struct mem_zone_bm_rtree,
512                                   list);
513         bm->cur.node = list_entry(bm->cur.zone->leaves.next,
514                                   struct rtree_node, list);
515         bm->cur.node_pfn = 0;
516         bm->cur.node_bit = 0;
517 }
518
519 static void memory_bm_free(struct memory_bitmap *bm, int clear_nosave_free);
520
521 struct mem_extent {
522         struct list_head hook;
523         unsigned long start;
524         unsigned long end;
525 };
526
527 /**
528  * free_mem_extents - Free a list of memory extents.
529  * @list: List of extents to free.
530  */
531 static void free_mem_extents(struct list_head *list)
532 {
533         struct mem_extent *ext, *aux;
534
535         list_for_each_entry_safe(ext, aux, list, hook) {
536                 list_del(&ext->hook);
537                 kfree(ext);
538         }
539 }
540
541 /**
542  * create_mem_extents - Create a list of memory extents.
543  * @list: List to put the extents into.
544  * @gfp_mask: Mask to use for memory allocations.
545  *
546  * The extents represent contiguous ranges of PFNs.
547  */
548 static int create_mem_extents(struct list_head *list, gfp_t gfp_mask)
549 {
550         struct zone *zone;
551
552         INIT_LIST_HEAD(list);
553
554         for_each_populated_zone(zone) {
555                 unsigned long zone_start, zone_end;
556                 struct mem_extent *ext, *cur, *aux;
557
558                 zone_start = zone->zone_start_pfn;
559                 zone_end = zone_end_pfn(zone);
560
561                 list_for_each_entry(ext, list, hook)
562                         if (zone_start <= ext->end)
563                                 break;
564
565                 if (&ext->hook == list || zone_end < ext->start) {
566                         /* New extent is necessary */
567                         struct mem_extent *new_ext;
568
569                         new_ext = kzalloc(sizeof(struct mem_extent), gfp_mask);
570                         if (!new_ext) {
571                                 free_mem_extents(list);
572                                 return -ENOMEM;
573                         }
574                         new_ext->start = zone_start;
575                         new_ext->end = zone_end;
576                         list_add_tail(&new_ext->hook, &ext->hook);
577                         continue;
578                 }
579
580                 /* Merge this zone's range of PFNs with the existing one */
581                 if (zone_start < ext->start)
582                         ext->start = zone_start;
583                 if (zone_end > ext->end)
584                         ext->end = zone_end;
585
586                 /* More merging may be possible */
587                 cur = ext;
588                 list_for_each_entry_safe_continue(cur, aux, list, hook) {
589                         if (zone_end < cur->start)
590                                 break;
591                         if (zone_end < cur->end)
592                                 ext->end = cur->end;
593                         list_del(&cur->hook);
594                         kfree(cur);
595                 }
596         }
597
598         return 0;
599 }
600
601 /**
602  * memory_bm_create - Allocate memory for a memory bitmap.
603  */
604 static int memory_bm_create(struct memory_bitmap *bm, gfp_t gfp_mask,
605                             int safe_needed)
606 {
607         struct chain_allocator ca;
608         struct list_head mem_extents;
609         struct mem_extent *ext;
610         int error;
611
612         chain_init(&ca, gfp_mask, safe_needed);
613         INIT_LIST_HEAD(&bm->zones);
614
615         error = create_mem_extents(&mem_extents, gfp_mask);
616         if (error)
617                 return error;
618
619         list_for_each_entry(ext, &mem_extents, hook) {
620                 struct mem_zone_bm_rtree *zone;
621
622                 zone = create_zone_bm_rtree(gfp_mask, safe_needed, &ca,
623                                             ext->start, ext->end);
624                 if (!zone) {
625                         error = -ENOMEM;
626                         goto Error;
627                 }
628                 list_add_tail(&zone->list, &bm->zones);
629         }
630
631         bm->p_list = ca.chain;
632         memory_bm_position_reset(bm);
633  Exit:
634         free_mem_extents(&mem_extents);
635         return error;
636
637  Error:
638         bm->p_list = ca.chain;
639         memory_bm_free(bm, PG_UNSAFE_CLEAR);
640         goto Exit;
641 }
642
643 /**
644  * memory_bm_free - Free memory occupied by the memory bitmap.
645  * @bm: Memory bitmap.
646  */
647 static void memory_bm_free(struct memory_bitmap *bm, int clear_nosave_free)
648 {
649         struct mem_zone_bm_rtree *zone;
650
651         list_for_each_entry(zone, &bm->zones, list)
652                 free_zone_bm_rtree(zone, clear_nosave_free);
653
654         free_list_of_pages(bm->p_list, clear_nosave_free);
655
656         INIT_LIST_HEAD(&bm->zones);
657 }
658
659 /**
660  * memory_bm_find_bit - Find the bit for a given PFN in a memory bitmap.
661  *
662  * Find the bit in memory bitmap @bm that corresponds to the given PFN.
663  * The cur.zone, cur.block and cur.node_pfn members of @bm are updated.
664  *
665  * Walk the radix tree to find the page containing the bit that represents @pfn
666  * and return the position of the bit in @addr and @bit_nr.
667  */
668 static int memory_bm_find_bit(struct memory_bitmap *bm, unsigned long pfn,
669                               void **addr, unsigned int *bit_nr)
670 {
671         struct mem_zone_bm_rtree *curr, *zone;
672         struct rtree_node *node;
673         int i, block_nr;
674
675         zone = bm->cur.zone;
676
677         if (pfn >= zone->start_pfn && pfn < zone->end_pfn)
678                 goto zone_found;
679
680         zone = NULL;
681
682         /* Find the right zone */
683         list_for_each_entry(curr, &bm->zones, list) {
684                 if (pfn >= curr->start_pfn && pfn < curr->end_pfn) {
685                         zone = curr;
686                         break;
687                 }
688         }
689
690         if (!zone)
691                 return -EFAULT;
692
693 zone_found:
694         /*
695          * We have found the zone. Now walk the radix tree to find the leaf node
696          * for our PFN.
697          */
698         node = bm->cur.node;
699         if (((pfn - zone->start_pfn) & ~BM_BLOCK_MASK) == bm->cur.node_pfn)
700                 goto node_found;
701
702         node      = zone->rtree;
703         block_nr  = (pfn - zone->start_pfn) >> BM_BLOCK_SHIFT;
704
705         for (i = zone->levels; i > 0; i--) {
706                 int index;
707
708                 index = block_nr >> ((i - 1) * BM_RTREE_LEVEL_SHIFT);
709                 index &= BM_RTREE_LEVEL_MASK;
710                 BUG_ON(node->data[index] == 0);
711                 node = (struct rtree_node *)node->data[index];
712         }
713
714 node_found:
715         /* Update last position */
716         bm->cur.zone = zone;
717         bm->cur.node = node;
718         bm->cur.node_pfn = (pfn - zone->start_pfn) & ~BM_BLOCK_MASK;
719
720         /* Set return values */
721         *addr = node->data;
722         *bit_nr = (pfn - zone->start_pfn) & BM_BLOCK_MASK;
723
724         return 0;
725 }
726
727 static void memory_bm_set_bit(struct memory_bitmap *bm, unsigned long pfn)
728 {
729         void *addr;
730         unsigned int bit;
731         int error;
732
733         error = memory_bm_find_bit(bm, pfn, &addr, &bit);
734         BUG_ON(error);
735         set_bit(bit, addr);
736 }
737
738 static int mem_bm_set_bit_check(struct memory_bitmap *bm, unsigned long pfn)
739 {
740         void *addr;
741         unsigned int bit;
742         int error;
743
744         error = memory_bm_find_bit(bm, pfn, &addr, &bit);
745         if (!error)
746                 set_bit(bit, addr);
747
748         return error;
749 }
750
751 static void memory_bm_clear_bit(struct memory_bitmap *bm, unsigned long pfn)
752 {
753         void *addr;
754         unsigned int bit;
755         int error;
756
757         error = memory_bm_find_bit(bm, pfn, &addr, &bit);
758         BUG_ON(error);
759         clear_bit(bit, addr);
760 }
761
762 static void memory_bm_clear_current(struct memory_bitmap *bm)
763 {
764         int bit;
765
766         bit = max(bm->cur.node_bit - 1, 0);
767         clear_bit(bit, bm->cur.node->data);
768 }
769
770 static int memory_bm_test_bit(struct memory_bitmap *bm, unsigned long pfn)
771 {
772         void *addr;
773         unsigned int bit;
774         int error;
775
776         error = memory_bm_find_bit(bm, pfn, &addr, &bit);
777         BUG_ON(error);
778         return test_bit(bit, addr);
779 }
780
781 static bool memory_bm_pfn_present(struct memory_bitmap *bm, unsigned long pfn)
782 {
783         void *addr;
784         unsigned int bit;
785
786         return !memory_bm_find_bit(bm, pfn, &addr, &bit);
787 }
788
789 /*
790  * rtree_next_node - Jump to the next leaf node.
791  *
792  * Set the position to the beginning of the next node in the
793  * memory bitmap. This is either the next node in the current
794  * zone's radix tree or the first node in the radix tree of the
795  * next zone.
796  *
797  * Return true if there is a next node, false otherwise.
798  */
799 static bool rtree_next_node(struct memory_bitmap *bm)
800 {
801         bm->cur.node = list_entry(bm->cur.node->list.next,
802                                   struct rtree_node, list);
803         if (&bm->cur.node->list != &bm->cur.zone->leaves) {
804                 bm->cur.node_pfn += BM_BITS_PER_BLOCK;
805                 bm->cur.node_bit  = 0;
806                 touch_softlockup_watchdog();
807                 return true;
808         }
809
810         /* No more nodes, goto next zone */
811         bm->cur.zone = list_entry(bm->cur.zone->list.next,
812                                   struct mem_zone_bm_rtree, list);
813         if (&bm->cur.zone->list != &bm->zones) {
814                 bm->cur.node = list_entry(bm->cur.zone->leaves.next,
815                                           struct rtree_node, list);
816                 bm->cur.node_pfn = 0;
817                 bm->cur.node_bit = 0;
818                 return true;
819         }
820
821         /* No more zones */
822         return false;
823 }
824
825 /**
826  * memory_bm_rtree_next_pfn - Find the next set bit in a memory bitmap.
827  * @bm: Memory bitmap.
828  *
829  * Starting from the last returned position this function searches for the next
830  * set bit in @bm and returns the PFN represented by it.  If no more bits are
831  * set, BM_END_OF_MAP is returned.
832  *
833  * It is required to run memory_bm_position_reset() before the first call to
834  * this function for the given memory bitmap.
835  */
836 static unsigned long memory_bm_next_pfn(struct memory_bitmap *bm)
837 {
838         unsigned long bits, pfn, pages;
839         int bit;
840
841         do {
842                 pages     = bm->cur.zone->end_pfn - bm->cur.zone->start_pfn;
843                 bits      = min(pages - bm->cur.node_pfn, BM_BITS_PER_BLOCK);
844                 bit       = find_next_bit(bm->cur.node->data, bits,
845                                           bm->cur.node_bit);
846                 if (bit < bits) {
847                         pfn = bm->cur.zone->start_pfn + bm->cur.node_pfn + bit;
848                         bm->cur.node_bit = bit + 1;
849                         return pfn;
850                 }
851         } while (rtree_next_node(bm));
852
853         return BM_END_OF_MAP;
854 }
855
856 /*
857  * This structure represents a range of page frames the contents of which
858  * should not be saved during hibernation.
859  */
860 struct nosave_region {
861         struct list_head list;
862         unsigned long start_pfn;
863         unsigned long end_pfn;
864 };
865
866 static LIST_HEAD(nosave_regions);
867
868 static void recycle_zone_bm_rtree(struct mem_zone_bm_rtree *zone)
869 {
870         struct rtree_node *node;
871
872         list_for_each_entry(node, &zone->nodes, list)
873                 recycle_safe_page(node->data);
874
875         list_for_each_entry(node, &zone->leaves, list)
876                 recycle_safe_page(node->data);
877 }
878
879 static void memory_bm_recycle(struct memory_bitmap *bm)
880 {
881         struct mem_zone_bm_rtree *zone;
882         struct linked_page *p_list;
883
884         list_for_each_entry(zone, &bm->zones, list)
885                 recycle_zone_bm_rtree(zone);
886
887         p_list = bm->p_list;
888         while (p_list) {
889                 struct linked_page *lp = p_list;
890
891                 p_list = lp->next;
892                 recycle_safe_page(lp);
893         }
894 }
895
896 /**
897  * register_nosave_region - Register a region of unsaveable memory.
898  *
899  * Register a range of page frames the contents of which should not be saved
900  * during hibernation (to be used in the early initialization code).
901  */
902 void __init __register_nosave_region(unsigned long start_pfn,
903                                      unsigned long end_pfn, int use_kmalloc)
904 {
905         struct nosave_region *region;
906
907         if (start_pfn >= end_pfn)
908                 return;
909
910         if (!list_empty(&nosave_regions)) {
911                 /* Try to extend the previous region (they should be sorted) */
912                 region = list_entry(nosave_regions.prev,
913                                         struct nosave_region, list);
914                 if (region->end_pfn == start_pfn) {
915                         region->end_pfn = end_pfn;
916                         goto Report;
917                 }
918         }
919         if (use_kmalloc) {
920                 /* During init, this shouldn't fail */
921                 region = kmalloc(sizeof(struct nosave_region), GFP_KERNEL);
922                 BUG_ON(!region);
923         } else {
924                 /* This allocation cannot fail */
925                 region = memblock_virt_alloc(sizeof(struct nosave_region), 0);
926         }
927         region->start_pfn = start_pfn;
928         region->end_pfn = end_pfn;
929         list_add_tail(&region->list, &nosave_regions);
930  Report:
931         printk(KERN_INFO "PM: Registered nosave memory: [mem %#010llx-%#010llx]\n",
932                 (unsigned long long) start_pfn << PAGE_SHIFT,
933                 ((unsigned long long) end_pfn << PAGE_SHIFT) - 1);
934 }
935
936 /*
937  * Set bits in this map correspond to the page frames the contents of which
938  * should not be saved during the suspend.
939  */
940 static struct memory_bitmap *forbidden_pages_map;
941
942 /* Set bits in this map correspond to free page frames. */
943 static struct memory_bitmap *free_pages_map;
944
945 /*
946  * Each page frame allocated for creating the image is marked by setting the
947  * corresponding bits in forbidden_pages_map and free_pages_map simultaneously
948  */
949
950 void swsusp_set_page_free(struct page *page)
951 {
952         if (free_pages_map)
953                 memory_bm_set_bit(free_pages_map, page_to_pfn(page));
954 }
955
956 static int swsusp_page_is_free(struct page *page)
957 {
958         return free_pages_map ?
959                 memory_bm_test_bit(free_pages_map, page_to_pfn(page)) : 0;
960 }
961
962 void swsusp_unset_page_free(struct page *page)
963 {
964         if (free_pages_map)
965                 memory_bm_clear_bit(free_pages_map, page_to_pfn(page));
966 }
967
968 static void swsusp_set_page_forbidden(struct page *page)
969 {
970         if (forbidden_pages_map)
971                 memory_bm_set_bit(forbidden_pages_map, page_to_pfn(page));
972 }
973
974 int swsusp_page_is_forbidden(struct page *page)
975 {
976         return forbidden_pages_map ?
977                 memory_bm_test_bit(forbidden_pages_map, page_to_pfn(page)) : 0;
978 }
979
980 static void swsusp_unset_page_forbidden(struct page *page)
981 {
982         if (forbidden_pages_map)
983                 memory_bm_clear_bit(forbidden_pages_map, page_to_pfn(page));
984 }
985
986 /**
987  * mark_nosave_pages - Mark pages that should not be saved.
988  * @bm: Memory bitmap.
989  *
990  * Set the bits in @bm that correspond to the page frames the contents of which
991  * should not be saved.
992  */
993 static void mark_nosave_pages(struct memory_bitmap *bm)
994 {
995         struct nosave_region *region;
996
997         if (list_empty(&nosave_regions))
998                 return;
999
1000         list_for_each_entry(region, &nosave_regions, list) {
1001                 unsigned long pfn;
1002
1003                 pr_debug("PM: Marking nosave pages: [mem %#010llx-%#010llx]\n",
1004                          (unsigned long long) region->start_pfn << PAGE_SHIFT,
1005                          ((unsigned long long) region->end_pfn << PAGE_SHIFT)
1006                                 - 1);
1007
1008                 for (pfn = region->start_pfn; pfn < region->end_pfn; pfn++)
1009                         if (pfn_valid(pfn)) {
1010                                 /*
1011                                  * It is safe to ignore the result of
1012                                  * mem_bm_set_bit_check() here, since we won't
1013                                  * touch the PFNs for which the error is
1014                                  * returned anyway.
1015                                  */
1016                                 mem_bm_set_bit_check(bm, pfn);
1017                         }
1018         }
1019 }
1020
1021 /**
1022  * create_basic_memory_bitmaps - Create bitmaps to hold basic page information.
1023  *
1024  * Create bitmaps needed for marking page frames that should not be saved and
1025  * free page frames.  The forbidden_pages_map and free_pages_map pointers are
1026  * only modified if everything goes well, because we don't want the bits to be
1027  * touched before both bitmaps are set up.
1028  */
1029 int create_basic_memory_bitmaps(void)
1030 {
1031         struct memory_bitmap *bm1, *bm2;
1032         int error = 0;
1033
1034         if (forbidden_pages_map && free_pages_map)
1035                 return 0;
1036         else
1037                 BUG_ON(forbidden_pages_map || free_pages_map);
1038
1039         bm1 = kzalloc(sizeof(struct memory_bitmap), GFP_KERNEL);
1040         if (!bm1)
1041                 return -ENOMEM;
1042
1043         error = memory_bm_create(bm1, GFP_KERNEL, PG_ANY);
1044         if (error)
1045                 goto Free_first_object;
1046
1047         bm2 = kzalloc(sizeof(struct memory_bitmap), GFP_KERNEL);
1048         if (!bm2)
1049                 goto Free_first_bitmap;
1050
1051         error = memory_bm_create(bm2, GFP_KERNEL, PG_ANY);
1052         if (error)
1053                 goto Free_second_object;
1054
1055         forbidden_pages_map = bm1;
1056         free_pages_map = bm2;
1057         mark_nosave_pages(forbidden_pages_map);
1058
1059         pr_debug("PM: Basic memory bitmaps created\n");
1060
1061         return 0;
1062
1063  Free_second_object:
1064         kfree(bm2);
1065  Free_first_bitmap:
1066         memory_bm_free(bm1, PG_UNSAFE_CLEAR);
1067  Free_first_object:
1068         kfree(bm1);
1069         return -ENOMEM;
1070 }
1071
1072 /**
1073  * free_basic_memory_bitmaps - Free memory bitmaps holding basic information.
1074  *
1075  * Free memory bitmaps allocated by create_basic_memory_bitmaps().  The
1076  * auxiliary pointers are necessary so that the bitmaps themselves are not
1077  * referred to while they are being freed.
1078  */
1079 void free_basic_memory_bitmaps(void)
1080 {
1081         struct memory_bitmap *bm1, *bm2;
1082
1083         if (WARN_ON(!(forbidden_pages_map && free_pages_map)))
1084                 return;
1085
1086         bm1 = forbidden_pages_map;
1087         bm2 = free_pages_map;
1088         forbidden_pages_map = NULL;
1089         free_pages_map = NULL;
1090         memory_bm_free(bm1, PG_UNSAFE_CLEAR);
1091         kfree(bm1);
1092         memory_bm_free(bm2, PG_UNSAFE_CLEAR);
1093         kfree(bm2);
1094
1095         pr_debug("PM: Basic memory bitmaps freed\n");
1096 }
1097
1098 /**
1099  * snapshot_additional_pages - Estimate the number of extra pages needed.
1100  * @zone: Memory zone to carry out the computation for.
1101  *
1102  * Estimate the number of additional pages needed for setting up a hibernation
1103  * image data structures for @zone (usually, the returned value is greater than
1104  * the exact number).
1105  */
1106 unsigned int snapshot_additional_pages(struct zone *zone)
1107 {
1108         unsigned int rtree, nodes;
1109
1110         rtree = nodes = DIV_ROUND_UP(zone->spanned_pages, BM_BITS_PER_BLOCK);
1111         rtree += DIV_ROUND_UP(rtree * sizeof(struct rtree_node),
1112                               LINKED_PAGE_DATA_SIZE);
1113         while (nodes > 1) {
1114                 nodes = DIV_ROUND_UP(nodes, BM_ENTRIES_PER_LEVEL);
1115                 rtree += nodes;
1116         }
1117
1118         return 2 * rtree;
1119 }
1120
1121 #ifdef CONFIG_HIGHMEM
1122 /**
1123  * count_free_highmem_pages - Compute the total number of free highmem pages.
1124  *
1125  * The returned number is system-wide.
1126  */
1127 static unsigned int count_free_highmem_pages(void)
1128 {
1129         struct zone *zone;
1130         unsigned int cnt = 0;
1131
1132         for_each_populated_zone(zone)
1133                 if (is_highmem(zone))
1134                         cnt += zone_page_state(zone, NR_FREE_PAGES);
1135
1136         return cnt;
1137 }
1138
1139 /**
1140  * saveable_highmem_page - Check if a highmem page is saveable.
1141  *
1142  * Determine whether a highmem page should be included in a hibernation image.
1143  *
1144  * We should save the page if it isn't Nosave or NosaveFree, or Reserved,
1145  * and it isn't part of a free chunk of pages.
1146  */
1147 static struct page *saveable_highmem_page(struct zone *zone, unsigned long pfn)
1148 {
1149         struct page *page;
1150
1151         if (!pfn_valid(pfn))
1152                 return NULL;
1153
1154         page = pfn_to_page(pfn);
1155         if (page_zone(page) != zone)
1156                 return NULL;
1157
1158         BUG_ON(!PageHighMem(page));
1159
1160         if (swsusp_page_is_forbidden(page) ||  swsusp_page_is_free(page) ||
1161             PageReserved(page))
1162                 return NULL;
1163
1164         if (page_is_guard(page))
1165                 return NULL;
1166
1167         return page;
1168 }
1169
1170 /**
1171  * count_highmem_pages - Compute the total number of saveable highmem pages.
1172  */
1173 static unsigned int count_highmem_pages(void)
1174 {
1175         struct zone *zone;
1176         unsigned int n = 0;
1177
1178         for_each_populated_zone(zone) {
1179                 unsigned long pfn, max_zone_pfn;
1180
1181                 if (!is_highmem(zone))
1182                         continue;
1183
1184                 mark_free_pages(zone);
1185                 max_zone_pfn = zone_end_pfn(zone);
1186                 for (pfn = zone->zone_start_pfn; pfn < max_zone_pfn; pfn++)
1187                         if (saveable_highmem_page(zone, pfn))
1188                                 n++;
1189         }
1190         return n;
1191 }
1192 #else
1193 static inline void *saveable_highmem_page(struct zone *z, unsigned long p)
1194 {
1195         return NULL;
1196 }
1197 #endif /* CONFIG_HIGHMEM */
1198
1199 /**
1200  * saveable_page - Check if the given page is saveable.
1201  *
1202  * Determine whether a non-highmem page should be included in a hibernation
1203  * image.
1204  *
1205  * We should save the page if it isn't Nosave, and is not in the range
1206  * of pages statically defined as 'unsaveable', and it isn't part of
1207  * a free chunk of pages.
1208  */
1209 static struct page *saveable_page(struct zone *zone, unsigned long pfn)
1210 {
1211         struct page *page;
1212
1213         if (!pfn_valid(pfn))
1214                 return NULL;
1215
1216         page = pfn_to_page(pfn);
1217         if (page_zone(page) != zone)
1218                 return NULL;
1219
1220         BUG_ON(PageHighMem(page));
1221
1222         if (swsusp_page_is_forbidden(page) || swsusp_page_is_free(page))
1223                 return NULL;
1224
1225         if (PageReserved(page)
1226             && (!kernel_page_present(page) || pfn_is_nosave(pfn)))
1227                 return NULL;
1228
1229         if (page_is_guard(page))
1230                 return NULL;
1231
1232         return page;
1233 }
1234
1235 /**
1236  * count_data_pages - Compute the total number of saveable non-highmem pages.
1237  */
1238 static unsigned int count_data_pages(void)
1239 {
1240         struct zone *zone;
1241         unsigned long pfn, max_zone_pfn;
1242         unsigned int n = 0;
1243
1244         for_each_populated_zone(zone) {
1245                 if (is_highmem(zone))
1246                         continue;
1247
1248                 mark_free_pages(zone);
1249                 max_zone_pfn = zone_end_pfn(zone);
1250                 for (pfn = zone->zone_start_pfn; pfn < max_zone_pfn; pfn++)
1251                         if (saveable_page(zone, pfn))
1252                                 n++;
1253         }
1254         return n;
1255 }
1256
1257 /*
1258  * This is needed, because copy_page and memcpy are not usable for copying
1259  * task structs.
1260  */
1261 static inline void do_copy_page(long *dst, long *src)
1262 {
1263         int n;
1264
1265         for (n = PAGE_SIZE / sizeof(long); n; n--)
1266                 *dst++ = *src++;
1267 }
1268
1269 /**
1270  * safe_copy_page - Copy a page in a safe way.
1271  *
1272  * Check if the page we are going to copy is marked as present in the kernel
1273  * page tables (this always is the case if CONFIG_DEBUG_PAGEALLOC is not set
1274  * and in that case kernel_page_present() always returns 'true').
1275  */
1276 static void safe_copy_page(void *dst, struct page *s_page)
1277 {
1278         if (kernel_page_present(s_page)) {
1279                 do_copy_page(dst, page_address(s_page));
1280         } else {
1281                 kernel_map_pages(s_page, 1, 1);
1282                 do_copy_page(dst, page_address(s_page));
1283                 kernel_map_pages(s_page, 1, 0);
1284         }
1285 }
1286
1287 #ifdef CONFIG_HIGHMEM
1288 static inline struct page *page_is_saveable(struct zone *zone, unsigned long pfn)
1289 {
1290         return is_highmem(zone) ?
1291                 saveable_highmem_page(zone, pfn) : saveable_page(zone, pfn);
1292 }
1293
1294 static void copy_data_page(unsigned long dst_pfn, unsigned long src_pfn)
1295 {
1296         struct page *s_page, *d_page;
1297         void *src, *dst;
1298
1299         s_page = pfn_to_page(src_pfn);
1300         d_page = pfn_to_page(dst_pfn);
1301         if (PageHighMem(s_page)) {
1302                 src = kmap_atomic(s_page);
1303                 dst = kmap_atomic(d_page);
1304                 do_copy_page(dst, src);
1305                 kunmap_atomic(dst);
1306                 kunmap_atomic(src);
1307         } else {
1308                 if (PageHighMem(d_page)) {
1309                         /*
1310                          * The page pointed to by src may contain some kernel
1311                          * data modified by kmap_atomic()
1312                          */
1313                         safe_copy_page(buffer, s_page);
1314                         dst = kmap_atomic(d_page);
1315                         copy_page(dst, buffer);
1316                         kunmap_atomic(dst);
1317                 } else {
1318                         safe_copy_page(page_address(d_page), s_page);
1319                 }
1320         }
1321 }
1322 #else
1323 #define page_is_saveable(zone, pfn)     saveable_page(zone, pfn)
1324
1325 static inline void copy_data_page(unsigned long dst_pfn, unsigned long src_pfn)
1326 {
1327         safe_copy_page(page_address(pfn_to_page(dst_pfn)),
1328                                 pfn_to_page(src_pfn));
1329 }
1330 #endif /* CONFIG_HIGHMEM */
1331
1332 static void copy_data_pages(struct memory_bitmap *copy_bm,
1333                             struct memory_bitmap *orig_bm)
1334 {
1335         struct zone *zone;
1336         unsigned long pfn;
1337
1338         for_each_populated_zone(zone) {
1339                 unsigned long max_zone_pfn;
1340
1341                 mark_free_pages(zone);
1342                 max_zone_pfn = zone_end_pfn(zone);
1343                 for (pfn = zone->zone_start_pfn; pfn < max_zone_pfn; pfn++)
1344                         if (page_is_saveable(zone, pfn))
1345                                 memory_bm_set_bit(orig_bm, pfn);
1346         }
1347         memory_bm_position_reset(orig_bm);
1348         memory_bm_position_reset(copy_bm);
1349         for(;;) {
1350                 pfn = memory_bm_next_pfn(orig_bm);
1351                 if (unlikely(pfn == BM_END_OF_MAP))
1352                         break;
1353                 copy_data_page(memory_bm_next_pfn(copy_bm), pfn);
1354         }
1355 }
1356
1357 /* Total number of image pages */
1358 static unsigned int nr_copy_pages;
1359 /* Number of pages needed for saving the original pfns of the image pages */
1360 static unsigned int nr_meta_pages;
1361 /*
1362  * Numbers of normal and highmem page frames allocated for hibernation image
1363  * before suspending devices.
1364  */
1365 unsigned int alloc_normal, alloc_highmem;
1366 /*
1367  * Memory bitmap used for marking saveable pages (during hibernation) or
1368  * hibernation image pages (during restore)
1369  */
1370 static struct memory_bitmap orig_bm;
1371 /*
1372  * Memory bitmap used during hibernation for marking allocated page frames that
1373  * will contain copies of saveable pages.  During restore it is initially used
1374  * for marking hibernation image pages, but then the set bits from it are
1375  * duplicated in @orig_bm and it is released.  On highmem systems it is next
1376  * used for marking "safe" highmem pages, but it has to be reinitialized for
1377  * this purpose.
1378  */
1379 static struct memory_bitmap copy_bm;
1380
1381 /**
1382  * swsusp_free - Free pages allocated for hibernation image.
1383  *
1384  * Image pages are alocated before snapshot creation, so they need to be
1385  * released after resume.
1386  */
1387 void swsusp_free(void)
1388 {
1389         unsigned long fb_pfn, fr_pfn;
1390
1391         if (!forbidden_pages_map || !free_pages_map)
1392                 goto out;
1393
1394         memory_bm_position_reset(forbidden_pages_map);
1395         memory_bm_position_reset(free_pages_map);
1396
1397 loop:
1398         fr_pfn = memory_bm_next_pfn(free_pages_map);
1399         fb_pfn = memory_bm_next_pfn(forbidden_pages_map);
1400
1401         /*
1402          * Find the next bit set in both bitmaps. This is guaranteed to
1403          * terminate when fb_pfn == fr_pfn == BM_END_OF_MAP.
1404          */
1405         do {
1406                 if (fb_pfn < fr_pfn)
1407                         fb_pfn = memory_bm_next_pfn(forbidden_pages_map);
1408                 if (fr_pfn < fb_pfn)
1409                         fr_pfn = memory_bm_next_pfn(free_pages_map);
1410         } while (fb_pfn != fr_pfn);
1411
1412         if (fr_pfn != BM_END_OF_MAP && pfn_valid(fr_pfn)) {
1413                 struct page *page = pfn_to_page(fr_pfn);
1414
1415                 memory_bm_clear_current(forbidden_pages_map);
1416                 memory_bm_clear_current(free_pages_map);
1417                 __free_page(page);
1418                 goto loop;
1419         }
1420
1421 out:
1422         nr_copy_pages = 0;
1423         nr_meta_pages = 0;
1424         restore_pblist = NULL;
1425         buffer = NULL;
1426         alloc_normal = 0;
1427         alloc_highmem = 0;
1428 }
1429
1430 /* Helper functions used for the shrinking of memory. */
1431
1432 #define GFP_IMAGE       (GFP_KERNEL | __GFP_NOWARN)
1433
1434 /**
1435  * preallocate_image_pages - Allocate a number of pages for hibernation image.
1436  * @nr_pages: Number of page frames to allocate.
1437  * @mask: GFP flags to use for the allocation.
1438  *
1439  * Return value: Number of page frames actually allocated
1440  */
1441 static unsigned long preallocate_image_pages(unsigned long nr_pages, gfp_t mask)
1442 {
1443         unsigned long nr_alloc = 0;
1444
1445         while (nr_pages > 0) {
1446                 struct page *page;
1447
1448                 page = alloc_image_page(mask);
1449                 if (!page)
1450                         break;
1451                 memory_bm_set_bit(&copy_bm, page_to_pfn(page));
1452                 if (PageHighMem(page))
1453                         alloc_highmem++;
1454                 else
1455                         alloc_normal++;
1456                 nr_pages--;
1457                 nr_alloc++;
1458         }
1459
1460         return nr_alloc;
1461 }
1462
1463 static unsigned long preallocate_image_memory(unsigned long nr_pages,
1464                                               unsigned long avail_normal)
1465 {
1466         unsigned long alloc;
1467
1468         if (avail_normal <= alloc_normal)
1469                 return 0;
1470
1471         alloc = avail_normal - alloc_normal;
1472         if (nr_pages < alloc)
1473                 alloc = nr_pages;
1474
1475         return preallocate_image_pages(alloc, GFP_IMAGE);
1476 }
1477
1478 #ifdef CONFIG_HIGHMEM
1479 static unsigned long preallocate_image_highmem(unsigned long nr_pages)
1480 {
1481         return preallocate_image_pages(nr_pages, GFP_IMAGE | __GFP_HIGHMEM);
1482 }
1483
1484 /**
1485  *  __fraction - Compute (an approximation of) x * (multiplier / base).
1486  */
1487 static unsigned long __fraction(u64 x, u64 multiplier, u64 base)
1488 {
1489         x *= multiplier;
1490         do_div(x, base);
1491         return (unsigned long)x;
1492 }
1493
1494 static unsigned long preallocate_highmem_fraction(unsigned long nr_pages,
1495                                                   unsigned long highmem,
1496                                                   unsigned long total)
1497 {
1498         unsigned long alloc = __fraction(nr_pages, highmem, total);
1499
1500         return preallocate_image_pages(alloc, GFP_IMAGE | __GFP_HIGHMEM);
1501 }
1502 #else /* CONFIG_HIGHMEM */
1503 static inline unsigned long preallocate_image_highmem(unsigned long nr_pages)
1504 {
1505         return 0;
1506 }
1507
1508 static inline unsigned long preallocate_highmem_fraction(unsigned long nr_pages,
1509                                                          unsigned long highmem,
1510                                                          unsigned long total)
1511 {
1512         return 0;
1513 }
1514 #endif /* CONFIG_HIGHMEM */
1515
1516 /**
1517  * free_unnecessary_pages - Release preallocated pages not needed for the image.
1518  */
1519 static unsigned long free_unnecessary_pages(void)
1520 {
1521         unsigned long save, to_free_normal, to_free_highmem, free;
1522
1523         save = count_data_pages();
1524         if (alloc_normal >= save) {
1525                 to_free_normal = alloc_normal - save;
1526                 save = 0;
1527         } else {
1528                 to_free_normal = 0;
1529                 save -= alloc_normal;
1530         }
1531         save += count_highmem_pages();
1532         if (alloc_highmem >= save) {
1533                 to_free_highmem = alloc_highmem - save;
1534         } else {
1535                 to_free_highmem = 0;
1536                 save -= alloc_highmem;
1537                 if (to_free_normal > save)
1538                         to_free_normal -= save;
1539                 else
1540                         to_free_normal = 0;
1541         }
1542         free = to_free_normal + to_free_highmem;
1543
1544         memory_bm_position_reset(&copy_bm);
1545
1546         while (to_free_normal > 0 || to_free_highmem > 0) {
1547                 unsigned long pfn = memory_bm_next_pfn(&copy_bm);
1548                 struct page *page = pfn_to_page(pfn);
1549
1550                 if (PageHighMem(page)) {
1551                         if (!to_free_highmem)
1552                                 continue;
1553                         to_free_highmem--;
1554                         alloc_highmem--;
1555                 } else {
1556                         if (!to_free_normal)
1557                                 continue;
1558                         to_free_normal--;
1559                         alloc_normal--;
1560                 }
1561                 memory_bm_clear_bit(&copy_bm, pfn);
1562                 swsusp_unset_page_forbidden(page);
1563                 swsusp_unset_page_free(page);
1564                 __free_page(page);
1565         }
1566
1567         return free;
1568 }
1569
1570 /**
1571  * minimum_image_size - Estimate the minimum acceptable size of an image.
1572  * @saveable: Number of saveable pages in the system.
1573  *
1574  * We want to avoid attempting to free too much memory too hard, so estimate the
1575  * minimum acceptable size of a hibernation image to use as the lower limit for
1576  * preallocating memory.
1577  *
1578  * We assume that the minimum image size should be proportional to
1579  *
1580  * [number of saveable pages] - [number of pages that can be freed in theory]
1581  *
1582  * where the second term is the sum of (1) reclaimable slab pages, (2) active
1583  * and (3) inactive anonymous pages, (4) active and (5) inactive file pages,
1584  * minus mapped file pages.
1585  */
1586 static unsigned long minimum_image_size(unsigned long saveable)
1587 {
1588         unsigned long size;
1589
1590         size = global_page_state(NR_SLAB_RECLAIMABLE)
1591                 + global_page_state(NR_ACTIVE_ANON)
1592                 + global_page_state(NR_INACTIVE_ANON)
1593                 + global_page_state(NR_ACTIVE_FILE)
1594                 + global_page_state(NR_INACTIVE_FILE)
1595                 - global_page_state(NR_FILE_MAPPED);
1596
1597         return saveable <= size ? 0 : saveable - size;
1598 }
1599
1600 /**
1601  * hibernate_preallocate_memory - Preallocate memory for hibernation image.
1602  *
1603  * To create a hibernation image it is necessary to make a copy of every page
1604  * frame in use.  We also need a number of page frames to be free during
1605  * hibernation for allocations made while saving the image and for device
1606  * drivers, in case they need to allocate memory from their hibernation
1607  * callbacks (these two numbers are given by PAGES_FOR_IO (which is a rough
1608  * estimate) and reserverd_size divided by PAGE_SIZE (which is tunable through
1609  * /sys/power/reserved_size, respectively).  To make this happen, we compute the
1610  * total number of available page frames and allocate at least
1611  *
1612  * ([page frames total] + PAGES_FOR_IO + [metadata pages]) / 2
1613  *  + 2 * DIV_ROUND_UP(reserved_size, PAGE_SIZE)
1614  *
1615  * of them, which corresponds to the maximum size of a hibernation image.
1616  *
1617  * If image_size is set below the number following from the above formula,
1618  * the preallocation of memory is continued until the total number of saveable
1619  * pages in the system is below the requested image size or the minimum
1620  * acceptable image size returned by minimum_image_size(), whichever is greater.
1621  */
1622 int hibernate_preallocate_memory(void)
1623 {
1624         struct zone *zone;
1625         unsigned long saveable, size, max_size, count, highmem, pages = 0;
1626         unsigned long alloc, save_highmem, pages_highmem, avail_normal;
1627         ktime_t start, stop;
1628         int error;
1629
1630         printk(KERN_INFO "PM: Preallocating image memory... ");
1631         start = ktime_get();
1632
1633         error = memory_bm_create(&orig_bm, GFP_IMAGE, PG_ANY);
1634         if (error)
1635                 goto err_out;
1636
1637         error = memory_bm_create(&copy_bm, GFP_IMAGE, PG_ANY);
1638         if (error)
1639                 goto err_out;
1640
1641         alloc_normal = 0;
1642         alloc_highmem = 0;
1643
1644         /* Count the number of saveable data pages. */
1645         save_highmem = count_highmem_pages();
1646         saveable = count_data_pages();
1647
1648         /*
1649          * Compute the total number of page frames we can use (count) and the
1650          * number of pages needed for image metadata (size).
1651          */
1652         count = saveable;
1653         saveable += save_highmem;
1654         highmem = save_highmem;
1655         size = 0;
1656         for_each_populated_zone(zone) {
1657                 size += snapshot_additional_pages(zone);
1658                 if (is_highmem(zone))
1659                         highmem += zone_page_state(zone, NR_FREE_PAGES);
1660                 else
1661                         count += zone_page_state(zone, NR_FREE_PAGES);
1662         }
1663         avail_normal = count;
1664         count += highmem;
1665         count -= totalreserve_pages;
1666
1667         /* Add number of pages required for page keys (s390 only). */
1668         size += page_key_additional_pages(saveable);
1669
1670         /* Compute the maximum number of saveable pages to leave in memory. */
1671         max_size = (count - (size + PAGES_FOR_IO)) / 2
1672                         - 2 * DIV_ROUND_UP(reserved_size, PAGE_SIZE);
1673         /* Compute the desired number of image pages specified by image_size. */
1674         size = DIV_ROUND_UP(image_size, PAGE_SIZE);
1675         if (size > max_size)
1676                 size = max_size;
1677         /*
1678          * If the desired number of image pages is at least as large as the
1679          * current number of saveable pages in memory, allocate page frames for
1680          * the image and we're done.
1681          */
1682         if (size >= saveable) {
1683                 pages = preallocate_image_highmem(save_highmem);
1684                 pages += preallocate_image_memory(saveable - pages, avail_normal);
1685                 goto out;
1686         }
1687
1688         /* Estimate the minimum size of the image. */
1689         pages = minimum_image_size(saveable);
1690         /*
1691          * To avoid excessive pressure on the normal zone, leave room in it to
1692          * accommodate an image of the minimum size (unless it's already too
1693          * small, in which case don't preallocate pages from it at all).
1694          */
1695         if (avail_normal > pages)
1696                 avail_normal -= pages;
1697         else
1698                 avail_normal = 0;
1699         if (size < pages)
1700                 size = min_t(unsigned long, pages, max_size);
1701
1702         /*
1703          * Let the memory management subsystem know that we're going to need a
1704          * large number of page frames to allocate and make it free some memory.
1705          * NOTE: If this is not done, performance will be hurt badly in some
1706          * test cases.
1707          */
1708         shrink_all_memory(saveable - size);
1709
1710         /*
1711          * The number of saveable pages in memory was too high, so apply some
1712          * pressure to decrease it.  First, make room for the largest possible
1713          * image and fail if that doesn't work.  Next, try to decrease the size
1714          * of the image as much as indicated by 'size' using allocations from
1715          * highmem and non-highmem zones separately.
1716          */
1717         pages_highmem = preallocate_image_highmem(highmem / 2);
1718         alloc = count - max_size;
1719         if (alloc > pages_highmem)
1720                 alloc -= pages_highmem;
1721         else
1722                 alloc = 0;
1723         pages = preallocate_image_memory(alloc, avail_normal);
1724         if (pages < alloc) {
1725                 /* We have exhausted non-highmem pages, try highmem. */
1726                 alloc -= pages;
1727                 pages += pages_highmem;
1728                 pages_highmem = preallocate_image_highmem(alloc);
1729                 if (pages_highmem < alloc)
1730                         goto err_out;
1731                 pages += pages_highmem;
1732                 /*
1733                  * size is the desired number of saveable pages to leave in
1734                  * memory, so try to preallocate (all memory - size) pages.
1735                  */
1736                 alloc = (count - pages) - size;
1737                 pages += preallocate_image_highmem(alloc);
1738         } else {
1739                 /*
1740                  * There are approximately max_size saveable pages at this point
1741                  * and we want to reduce this number down to size.
1742                  */
1743                 alloc = max_size - size;
1744                 size = preallocate_highmem_fraction(alloc, highmem, count);
1745                 pages_highmem += size;
1746                 alloc -= size;
1747                 size = preallocate_image_memory(alloc, avail_normal);
1748                 pages_highmem += preallocate_image_highmem(alloc - size);
1749                 pages += pages_highmem + size;
1750         }
1751
1752         /*
1753          * We only need as many page frames for the image as there are saveable
1754          * pages in memory, but we have allocated more.  Release the excessive
1755          * ones now.
1756          */
1757         pages -= free_unnecessary_pages();
1758
1759  out:
1760         stop = ktime_get();
1761         printk(KERN_CONT "done (allocated %lu pages)\n", pages);
1762         swsusp_show_speed(start, stop, pages, "Allocated");
1763
1764         return 0;
1765
1766  err_out:
1767         printk(KERN_CONT "\n");
1768         swsusp_free();
1769         return -ENOMEM;
1770 }
1771
1772 #ifdef CONFIG_HIGHMEM
1773 /**
1774  * count_pages_for_highmem - Count non-highmem pages needed for copying highmem.
1775  *
1776  * Compute the number of non-highmem pages that will be necessary for creating
1777  * copies of highmem pages.
1778  */
1779 static unsigned int count_pages_for_highmem(unsigned int nr_highmem)
1780 {
1781         unsigned int free_highmem = count_free_highmem_pages() + alloc_highmem;
1782
1783         if (free_highmem >= nr_highmem)
1784                 nr_highmem = 0;
1785         else
1786                 nr_highmem -= free_highmem;
1787
1788         return nr_highmem;
1789 }
1790 #else
1791 static unsigned int count_pages_for_highmem(unsigned int nr_highmem) { return 0; }
1792 #endif /* CONFIG_HIGHMEM */
1793
1794 /**
1795  * enough_free_mem - Check if there is enough free memory for the image.
1796  */
1797 static int enough_free_mem(unsigned int nr_pages, unsigned int nr_highmem)
1798 {
1799         struct zone *zone;
1800         unsigned int free = alloc_normal;
1801
1802         for_each_populated_zone(zone)
1803                 if (!is_highmem(zone))
1804                         free += zone_page_state(zone, NR_FREE_PAGES);
1805
1806         nr_pages += count_pages_for_highmem(nr_highmem);
1807         pr_debug("PM: Normal pages needed: %u + %u, available pages: %u\n",
1808                 nr_pages, PAGES_FOR_IO, free);
1809
1810         return free > nr_pages + PAGES_FOR_IO;
1811 }
1812
1813 #ifdef CONFIG_HIGHMEM
1814 /**
1815  * get_highmem_buffer - Allocate a buffer for highmem pages.
1816  *
1817  * If there are some highmem pages in the hibernation image, we may need a
1818  * buffer to copy them and/or load their data.
1819  */
1820 static inline int get_highmem_buffer(int safe_needed)
1821 {
1822         buffer = get_image_page(GFP_ATOMIC | __GFP_COLD, safe_needed);
1823         return buffer ? 0 : -ENOMEM;
1824 }
1825
1826 /**
1827  * alloc_highmem_image_pages - Allocate some highmem pages for the image.
1828  *
1829  * Try to allocate as many pages as needed, but if the number of free highmem
1830  * pages is less than that, allocate them all.
1831  */
1832 static inline unsigned int alloc_highmem_pages(struct memory_bitmap *bm,
1833                                                unsigned int nr_highmem)
1834 {
1835         unsigned int to_alloc = count_free_highmem_pages();
1836
1837         if (to_alloc > nr_highmem)
1838                 to_alloc = nr_highmem;
1839
1840         nr_highmem -= to_alloc;
1841         while (to_alloc-- > 0) {
1842                 struct page *page;
1843
1844                 page = alloc_image_page(__GFP_HIGHMEM|__GFP_KSWAPD_RECLAIM);
1845                 memory_bm_set_bit(bm, page_to_pfn(page));
1846         }
1847         return nr_highmem;
1848 }
1849 #else
1850 static inline int get_highmem_buffer(int safe_needed) { return 0; }
1851
1852 static inline unsigned int alloc_highmem_pages(struct memory_bitmap *bm,
1853                                                unsigned int n) { return 0; }
1854 #endif /* CONFIG_HIGHMEM */
1855
1856 /**
1857  * swsusp_alloc - Allocate memory for hibernation image.
1858  *
1859  * We first try to allocate as many highmem pages as there are
1860  * saveable highmem pages in the system.  If that fails, we allocate
1861  * non-highmem pages for the copies of the remaining highmem ones.
1862  *
1863  * In this approach it is likely that the copies of highmem pages will
1864  * also be located in the high memory, because of the way in which
1865  * copy_data_pages() works.
1866  */
1867 static int swsusp_alloc(struct memory_bitmap *orig_bm,
1868                         struct memory_bitmap *copy_bm,
1869                         unsigned int nr_pages, unsigned int nr_highmem)
1870 {
1871         if (nr_highmem > 0) {
1872                 if (get_highmem_buffer(PG_ANY))
1873                         goto err_out;
1874                 if (nr_highmem > alloc_highmem) {
1875                         nr_highmem -= alloc_highmem;
1876                         nr_pages += alloc_highmem_pages(copy_bm, nr_highmem);
1877                 }
1878         }
1879         if (nr_pages > alloc_normal) {
1880                 nr_pages -= alloc_normal;
1881                 while (nr_pages-- > 0) {
1882                         struct page *page;
1883
1884                         page = alloc_image_page(GFP_ATOMIC | __GFP_COLD);
1885                         if (!page)
1886                                 goto err_out;
1887                         memory_bm_set_bit(copy_bm, page_to_pfn(page));
1888                 }
1889         }
1890
1891         return 0;
1892
1893  err_out:
1894         swsusp_free();
1895         return -ENOMEM;
1896 }
1897
1898 asmlinkage __visible int swsusp_save(void)
1899 {
1900         unsigned int nr_pages, nr_highmem;
1901
1902         printk(KERN_INFO "PM: Creating hibernation image:\n");
1903
1904         drain_local_pages(NULL);
1905         nr_pages = count_data_pages();
1906         nr_highmem = count_highmem_pages();
1907         printk(KERN_INFO "PM: Need to copy %u pages\n", nr_pages + nr_highmem);
1908
1909         if (!enough_free_mem(nr_pages, nr_highmem)) {
1910                 printk(KERN_ERR "PM: Not enough free memory\n");
1911                 return -ENOMEM;
1912         }
1913
1914         if (swsusp_alloc(&orig_bm, &copy_bm, nr_pages, nr_highmem)) {
1915                 printk(KERN_ERR "PM: Memory allocation failed\n");
1916                 return -ENOMEM;
1917         }
1918
1919         /*
1920          * During allocating of suspend pagedir, new cold pages may appear.
1921          * Kill them.
1922          */
1923         drain_local_pages(NULL);
1924         copy_data_pages(&copy_bm, &orig_bm);
1925
1926         /*
1927          * End of critical section. From now on, we can write to memory,
1928          * but we should not touch disk. This specially means we must _not_
1929          * touch swap space! Except we must write out our image of course.
1930          */
1931
1932         nr_pages += nr_highmem;
1933         nr_copy_pages = nr_pages;
1934         nr_meta_pages = DIV_ROUND_UP(nr_pages * sizeof(long), PAGE_SIZE);
1935
1936         printk(KERN_INFO "PM: Hibernation image created (%d pages copied)\n",
1937                 nr_pages);
1938
1939         return 0;
1940 }
1941
1942 #ifndef CONFIG_ARCH_HIBERNATION_HEADER
1943 static int init_header_complete(struct swsusp_info *info)
1944 {
1945         memcpy(&info->uts, init_utsname(), sizeof(struct new_utsname));
1946         info->version_code = LINUX_VERSION_CODE;
1947         return 0;
1948 }
1949
1950 static char *check_image_kernel(struct swsusp_info *info)
1951 {
1952         if (info->version_code != LINUX_VERSION_CODE)
1953                 return "kernel version";
1954         if (strcmp(info->uts.sysname,init_utsname()->sysname))
1955                 return "system type";
1956         if (strcmp(info->uts.release,init_utsname()->release))
1957                 return "kernel release";
1958         if (strcmp(info->uts.version,init_utsname()->version))
1959                 return "version";
1960         if (strcmp(info->uts.machine,init_utsname()->machine))
1961                 return "machine";
1962         return NULL;
1963 }
1964 #endif /* CONFIG_ARCH_HIBERNATION_HEADER */
1965
1966 unsigned long snapshot_get_image_size(void)
1967 {
1968         return nr_copy_pages + nr_meta_pages + 1;
1969 }
1970
1971 static int init_header(struct swsusp_info *info)
1972 {
1973         memset(info, 0, sizeof(struct swsusp_info));
1974         info->num_physpages = get_num_physpages();
1975         info->image_pages = nr_copy_pages;
1976         info->pages = snapshot_get_image_size();
1977         info->size = info->pages;
1978         info->size <<= PAGE_SHIFT;
1979         return init_header_complete(info);
1980 }
1981
1982 /**
1983  * pack_pfns - Prepare PFNs for saving.
1984  * @bm: Memory bitmap.
1985  * @buf: Memory buffer to store the PFNs in.
1986  *
1987  * PFNs corresponding to set bits in @bm are stored in the area of memory
1988  * pointed to by @buf (1 page at a time).
1989  */
1990 static inline void pack_pfns(unsigned long *buf, struct memory_bitmap *bm)
1991 {
1992         int j;
1993
1994         for (j = 0; j < PAGE_SIZE / sizeof(long); j++) {
1995                 buf[j] = memory_bm_next_pfn(bm);
1996                 if (unlikely(buf[j] == BM_END_OF_MAP))
1997                         break;
1998                 /* Save page key for data page (s390 only). */
1999                 page_key_read(buf + j);
2000         }
2001 }
2002
2003 /**
2004  * snapshot_read_next - Get the address to read the next image page from.
2005  * @handle: Snapshot handle to be used for the reading.
2006  *
2007  * On the first call, @handle should point to a zeroed snapshot_handle
2008  * structure.  The structure gets populated then and a pointer to it should be
2009  * passed to this function every next time.
2010  *
2011  * On success, the function returns a positive number.  Then, the caller
2012  * is allowed to read up to the returned number of bytes from the memory
2013  * location computed by the data_of() macro.
2014  *
2015  * The function returns 0 to indicate the end of the data stream condition,
2016  * and negative numbers are returned on errors.  If that happens, the structure
2017  * pointed to by @handle is not updated and should not be used any more.
2018  */
2019 int snapshot_read_next(struct snapshot_handle *handle)
2020 {
2021         if (handle->cur > nr_meta_pages + nr_copy_pages)
2022                 return 0;
2023
2024         if (!buffer) {
2025                 /* This makes the buffer be freed by swsusp_free() */
2026                 buffer = get_image_page(GFP_ATOMIC, PG_ANY);
2027                 if (!buffer)
2028                         return -ENOMEM;
2029         }
2030         if (!handle->cur) {
2031                 int error;
2032
2033                 error = init_header((struct swsusp_info *)buffer);
2034                 if (error)
2035                         return error;
2036                 handle->buffer = buffer;
2037                 memory_bm_position_reset(&orig_bm);
2038                 memory_bm_position_reset(&copy_bm);
2039         } else if (handle->cur <= nr_meta_pages) {
2040                 clear_page(buffer);
2041                 pack_pfns(buffer, &orig_bm);
2042         } else {
2043                 struct page *page;
2044
2045                 page = pfn_to_page(memory_bm_next_pfn(&copy_bm));
2046                 if (PageHighMem(page)) {
2047                         /*
2048                          * Highmem pages are copied to the buffer,
2049                          * because we can't return with a kmapped
2050                          * highmem page (we may not be called again).
2051                          */
2052                         void *kaddr;
2053
2054                         kaddr = kmap_atomic(page);
2055                         copy_page(buffer, kaddr);
2056                         kunmap_atomic(kaddr);
2057                         handle->buffer = buffer;
2058                 } else {
2059                         handle->buffer = page_address(page);
2060                 }
2061         }
2062         handle->cur++;
2063         return PAGE_SIZE;
2064 }
2065
2066 static void duplicate_memory_bitmap(struct memory_bitmap *dst,
2067                                     struct memory_bitmap *src)
2068 {
2069         unsigned long pfn;
2070
2071         memory_bm_position_reset(src);
2072         pfn = memory_bm_next_pfn(src);
2073         while (pfn != BM_END_OF_MAP) {
2074                 memory_bm_set_bit(dst, pfn);
2075                 pfn = memory_bm_next_pfn(src);
2076         }
2077 }
2078
2079 /**
2080  * mark_unsafe_pages - Mark pages that were used before hibernation.
2081  *
2082  * Mark the pages that cannot be used for storing the image during restoration,
2083  * because they conflict with the pages that had been used before hibernation.
2084  */
2085 static void mark_unsafe_pages(struct memory_bitmap *bm)
2086 {
2087         unsigned long pfn;
2088
2089         /* Clear the "free"/"unsafe" bit for all PFNs */
2090         memory_bm_position_reset(free_pages_map);
2091         pfn = memory_bm_next_pfn(free_pages_map);
2092         while (pfn != BM_END_OF_MAP) {
2093                 memory_bm_clear_current(free_pages_map);
2094                 pfn = memory_bm_next_pfn(free_pages_map);
2095         }
2096
2097         /* Mark pages that correspond to the "original" PFNs as "unsafe" */
2098         duplicate_memory_bitmap(free_pages_map, bm);
2099
2100         allocated_unsafe_pages = 0;
2101 }
2102
2103 static int check_header(struct swsusp_info *info)
2104 {
2105         char *reason;
2106
2107         reason = check_image_kernel(info);
2108         if (!reason && info->num_physpages != get_num_physpages())
2109                 reason = "memory size";
2110         if (reason) {
2111                 printk(KERN_ERR "PM: Image mismatch: %s\n", reason);
2112                 return -EPERM;
2113         }
2114         return 0;
2115 }
2116
2117 /**
2118  * load header - Check the image header and copy the data from it.
2119  */
2120 static int load_header(struct swsusp_info *info)
2121 {
2122         int error;
2123
2124         restore_pblist = NULL;
2125         error = check_header(info);
2126         if (!error) {
2127                 nr_copy_pages = info->image_pages;
2128                 nr_meta_pages = info->pages - info->image_pages - 1;
2129         }
2130         return error;
2131 }
2132
2133 /**
2134  * unpack_orig_pfns - Set bits corresponding to given PFNs in a memory bitmap.
2135  * @bm: Memory bitmap.
2136  * @buf: Area of memory containing the PFNs.
2137  *
2138  * For each element of the array pointed to by @buf (1 page at a time), set the
2139  * corresponding bit in @bm.
2140  */
2141 static int unpack_orig_pfns(unsigned long *buf, struct memory_bitmap *bm)
2142 {
2143         int j;
2144
2145         for (j = 0; j < PAGE_SIZE / sizeof(long); j++) {
2146                 if (unlikely(buf[j] == BM_END_OF_MAP))
2147                         break;
2148
2149                 /* Extract and buffer page key for data page (s390 only). */
2150                 page_key_memorize(buf + j);
2151
2152                 if (pfn_valid(buf[j]) && memory_bm_pfn_present(bm, buf[j]))
2153                         memory_bm_set_bit(bm, buf[j]);
2154                 else
2155                         return -EFAULT;
2156         }
2157
2158         return 0;
2159 }
2160
2161 #ifdef CONFIG_HIGHMEM
2162 /*
2163  * struct highmem_pbe is used for creating the list of highmem pages that
2164  * should be restored atomically during the resume from disk, because the page
2165  * frames they have occupied before the suspend are in use.
2166  */
2167 struct highmem_pbe {
2168         struct page *copy_page; /* data is here now */
2169         struct page *orig_page; /* data was here before the suspend */
2170         struct highmem_pbe *next;
2171 };
2172
2173 /*
2174  * List of highmem PBEs needed for restoring the highmem pages that were
2175  * allocated before the suspend and included in the suspend image, but have
2176  * also been allocated by the "resume" kernel, so their contents cannot be
2177  * written directly to their "original" page frames.
2178  */
2179 static struct highmem_pbe *highmem_pblist;
2180
2181 /**
2182  * count_highmem_image_pages - Compute the number of highmem pages in the image.
2183  * @bm: Memory bitmap.
2184  *
2185  * The bits in @bm that correspond to image pages are assumed to be set.
2186  */
2187 static unsigned int count_highmem_image_pages(struct memory_bitmap *bm)
2188 {
2189         unsigned long pfn;
2190         unsigned int cnt = 0;
2191
2192         memory_bm_position_reset(bm);
2193         pfn = memory_bm_next_pfn(bm);
2194         while (pfn != BM_END_OF_MAP) {
2195                 if (PageHighMem(pfn_to_page(pfn)))
2196                         cnt++;
2197
2198                 pfn = memory_bm_next_pfn(bm);
2199         }
2200         return cnt;
2201 }
2202
2203 static unsigned int safe_highmem_pages;
2204
2205 static struct memory_bitmap *safe_highmem_bm;
2206
2207 /**
2208  * prepare_highmem_image - Allocate memory for loading highmem data from image.
2209  * @bm: Pointer to an uninitialized memory bitmap structure.
2210  * @nr_highmem_p: Pointer to the number of highmem image pages.
2211  *
2212  * Try to allocate as many highmem pages as there are highmem image pages
2213  * (@nr_highmem_p points to the variable containing the number of highmem image
2214  * pages).  The pages that are "safe" (ie. will not be overwritten when the
2215  * hibernation image is restored entirely) have the corresponding bits set in
2216  * @bm (it must be unitialized).
2217  *
2218  * NOTE: This function should not be called if there are no highmem image pages.
2219  */
2220 static int prepare_highmem_image(struct memory_bitmap *bm,
2221                                  unsigned int *nr_highmem_p)
2222 {
2223         unsigned int to_alloc;
2224
2225         if (memory_bm_create(bm, GFP_ATOMIC, PG_SAFE))
2226                 return -ENOMEM;
2227
2228         if (get_highmem_buffer(PG_SAFE))
2229                 return -ENOMEM;
2230
2231         to_alloc = count_free_highmem_pages();
2232         if (to_alloc > *nr_highmem_p)
2233                 to_alloc = *nr_highmem_p;
2234         else
2235                 *nr_highmem_p = to_alloc;
2236
2237         safe_highmem_pages = 0;
2238         while (to_alloc-- > 0) {
2239                 struct page *page;
2240
2241                 page = alloc_page(__GFP_HIGHMEM);
2242                 if (!swsusp_page_is_free(page)) {
2243                         /* The page is "safe", set its bit the bitmap */
2244                         memory_bm_set_bit(bm, page_to_pfn(page));
2245                         safe_highmem_pages++;
2246                 }
2247                 /* Mark the page as allocated */
2248                 swsusp_set_page_forbidden(page);
2249                 swsusp_set_page_free(page);
2250         }
2251         memory_bm_position_reset(bm);
2252         safe_highmem_bm = bm;
2253         return 0;
2254 }
2255
2256 static struct page *last_highmem_page;
2257
2258 /**
2259  * get_highmem_page_buffer - Prepare a buffer to store a highmem image page.
2260  *
2261  * For a given highmem image page get a buffer that suspend_write_next() should
2262  * return to its caller to write to.
2263  *
2264  * If the page is to be saved to its "original" page frame or a copy of
2265  * the page is to be made in the highmem, @buffer is returned.  Otherwise,
2266  * the copy of the page is to be made in normal memory, so the address of
2267  * the copy is returned.
2268  *
2269  * If @buffer is returned, the caller of suspend_write_next() will write
2270  * the page's contents to @buffer, so they will have to be copied to the
2271  * right location on the next call to suspend_write_next() and it is done
2272  * with the help of copy_last_highmem_page().  For this purpose, if
2273  * @buffer is returned, @last_highmem_page is set to the page to which
2274  * the data will have to be copied from @buffer.
2275  */
2276 static void *get_highmem_page_buffer(struct page *page,
2277                                      struct chain_allocator *ca)
2278 {
2279         struct highmem_pbe *pbe;
2280         void *kaddr;
2281
2282         if (swsusp_page_is_forbidden(page) && swsusp_page_is_free(page)) {
2283                 /*
2284                  * We have allocated the "original" page frame and we can
2285                  * use it directly to store the loaded page.
2286                  */
2287                 last_highmem_page = page;
2288                 return buffer;
2289         }
2290         /*
2291          * The "original" page frame has not been allocated and we have to
2292          * use a "safe" page frame to store the loaded page.
2293          */
2294         pbe = chain_alloc(ca, sizeof(struct highmem_pbe));
2295         if (!pbe) {
2296                 swsusp_free();
2297                 return ERR_PTR(-ENOMEM);
2298         }
2299         pbe->orig_page = page;
2300         if (safe_highmem_pages > 0) {
2301                 struct page *tmp;
2302
2303                 /* Copy of the page will be stored in high memory */
2304                 kaddr = buffer;
2305                 tmp = pfn_to_page(memory_bm_next_pfn(safe_highmem_bm));
2306                 safe_highmem_pages--;
2307                 last_highmem_page = tmp;
2308                 pbe->copy_page = tmp;
2309         } else {
2310                 /* Copy of the page will be stored in normal memory */
2311                 kaddr = safe_pages_list;
2312                 safe_pages_list = safe_pages_list->next;
2313                 pbe->copy_page = virt_to_page(kaddr);
2314         }
2315         pbe->next = highmem_pblist;
2316         highmem_pblist = pbe;
2317         return kaddr;
2318 }
2319
2320 /**
2321  * copy_last_highmem_page - Copy most the most recent highmem image page.
2322  *
2323  * Copy the contents of a highmem image from @buffer, where the caller of
2324  * snapshot_write_next() has stored them, to the right location represented by
2325  * @last_highmem_page .
2326  */
2327 static void copy_last_highmem_page(void)
2328 {
2329         if (last_highmem_page) {
2330                 void *dst;
2331
2332                 dst = kmap_atomic(last_highmem_page);
2333                 copy_page(dst, buffer);
2334                 kunmap_atomic(dst);
2335                 last_highmem_page = NULL;
2336         }
2337 }
2338
2339 static inline int last_highmem_page_copied(void)
2340 {
2341         return !last_highmem_page;
2342 }
2343
2344 static inline void free_highmem_data(void)
2345 {
2346         if (safe_highmem_bm)
2347                 memory_bm_free(safe_highmem_bm, PG_UNSAFE_CLEAR);
2348
2349         if (buffer)
2350                 free_image_page(buffer, PG_UNSAFE_CLEAR);
2351 }
2352 #else
2353 static unsigned int count_highmem_image_pages(struct memory_bitmap *bm) { return 0; }
2354
2355 static inline int prepare_highmem_image(struct memory_bitmap *bm,
2356                                         unsigned int *nr_highmem_p) { return 0; }
2357
2358 static inline void *get_highmem_page_buffer(struct page *page,
2359                                             struct chain_allocator *ca)
2360 {
2361         return ERR_PTR(-EINVAL);
2362 }
2363
2364 static inline void copy_last_highmem_page(void) {}
2365 static inline int last_highmem_page_copied(void) { return 1; }
2366 static inline void free_highmem_data(void) {}
2367 #endif /* CONFIG_HIGHMEM */
2368
2369 #define PBES_PER_LINKED_PAGE    (LINKED_PAGE_DATA_SIZE / sizeof(struct pbe))
2370
2371 /**
2372  * prepare_image - Make room for loading hibernation image.
2373  * @new_bm: Unitialized memory bitmap structure.
2374  * @bm: Memory bitmap with unsafe pages marked.
2375  *
2376  * Use @bm to mark the pages that will be overwritten in the process of
2377  * restoring the system memory state from the suspend image ("unsafe" pages)
2378  * and allocate memory for the image.
2379  *
2380  * The idea is to allocate a new memory bitmap first and then allocate
2381  * as many pages as needed for image data, but without specifying what those
2382  * pages will be used for just yet.  Instead, we mark them all as allocated and
2383  * create a lists of "safe" pages to be used later.  On systems with high
2384  * memory a list of "safe" highmem pages is created too.
2385  */
2386 static int prepare_image(struct memory_bitmap *new_bm, struct memory_bitmap *bm)
2387 {
2388         unsigned int nr_pages, nr_highmem;
2389         struct linked_page *lp;
2390         int error;
2391
2392         /* If there is no highmem, the buffer will not be necessary */
2393         free_image_page(buffer, PG_UNSAFE_CLEAR);
2394         buffer = NULL;
2395
2396         nr_highmem = count_highmem_image_pages(bm);
2397         mark_unsafe_pages(bm);
2398
2399         error = memory_bm_create(new_bm, GFP_ATOMIC, PG_SAFE);
2400         if (error)
2401                 goto Free;
2402
2403         duplicate_memory_bitmap(new_bm, bm);
2404         memory_bm_free(bm, PG_UNSAFE_KEEP);
2405         if (nr_highmem > 0) {
2406                 error = prepare_highmem_image(bm, &nr_highmem);
2407                 if (error)
2408                         goto Free;
2409         }
2410         /*
2411          * Reserve some safe pages for potential later use.
2412          *
2413          * NOTE: This way we make sure there will be enough safe pages for the
2414          * chain_alloc() in get_buffer().  It is a bit wasteful, but
2415          * nr_copy_pages cannot be greater than 50% of the memory anyway.
2416          *
2417          * nr_copy_pages cannot be less than allocated_unsafe_pages too.
2418          */
2419         nr_pages = nr_copy_pages - nr_highmem - allocated_unsafe_pages;
2420         nr_pages = DIV_ROUND_UP(nr_pages, PBES_PER_LINKED_PAGE);
2421         while (nr_pages > 0) {
2422                 lp = get_image_page(GFP_ATOMIC, PG_SAFE);
2423                 if (!lp) {
2424                         error = -ENOMEM;
2425                         goto Free;
2426                 }
2427                 lp->next = safe_pages_list;
2428                 safe_pages_list = lp;
2429                 nr_pages--;
2430         }
2431         /* Preallocate memory for the image */
2432         nr_pages = nr_copy_pages - nr_highmem - allocated_unsafe_pages;
2433         while (nr_pages > 0) {
2434                 lp = (struct linked_page *)get_zeroed_page(GFP_ATOMIC);
2435                 if (!lp) {
2436                         error = -ENOMEM;
2437                         goto Free;
2438                 }
2439                 if (!swsusp_page_is_free(virt_to_page(lp))) {
2440                         /* The page is "safe", add it to the list */
2441                         lp->next = safe_pages_list;
2442                         safe_pages_list = lp;
2443                 }
2444                 /* Mark the page as allocated */
2445                 swsusp_set_page_forbidden(virt_to_page(lp));
2446                 swsusp_set_page_free(virt_to_page(lp));
2447                 nr_pages--;
2448         }
2449         return 0;
2450
2451  Free:
2452         swsusp_free();
2453         return error;
2454 }
2455
2456 /**
2457  * get_buffer - Get the address to store the next image data page.
2458  *
2459  * Get the address that snapshot_write_next() should return to its caller to
2460  * write to.
2461  */
2462 static void *get_buffer(struct memory_bitmap *bm, struct chain_allocator *ca)
2463 {
2464         struct pbe *pbe;
2465         struct page *page;
2466         unsigned long pfn = memory_bm_next_pfn(bm);
2467
2468         if (pfn == BM_END_OF_MAP)
2469                 return ERR_PTR(-EFAULT);
2470
2471         page = pfn_to_page(pfn);
2472         if (PageHighMem(page))
2473                 return get_highmem_page_buffer(page, ca);
2474
2475         if (swsusp_page_is_forbidden(page) && swsusp_page_is_free(page))
2476                 /*
2477                  * We have allocated the "original" page frame and we can
2478                  * use it directly to store the loaded page.
2479                  */
2480                 return page_address(page);
2481
2482         /*
2483          * The "original" page frame has not been allocated and we have to
2484          * use a "safe" page frame to store the loaded page.
2485          */
2486         pbe = chain_alloc(ca, sizeof(struct pbe));
2487         if (!pbe) {
2488                 swsusp_free();
2489                 return ERR_PTR(-ENOMEM);
2490         }
2491         pbe->orig_address = page_address(page);
2492         pbe->address = safe_pages_list;
2493         safe_pages_list = safe_pages_list->next;
2494         pbe->next = restore_pblist;
2495         restore_pblist = pbe;
2496         return pbe->address;
2497 }
2498
2499 /**
2500  * snapshot_write_next - Get the address to store the next image page.
2501  * @handle: Snapshot handle structure to guide the writing.
2502  *
2503  * On the first call, @handle should point to a zeroed snapshot_handle
2504  * structure.  The structure gets populated then and a pointer to it should be
2505  * passed to this function every next time.
2506  *
2507  * On success, the function returns a positive number.  Then, the caller
2508  * is allowed to write up to the returned number of bytes to the memory
2509  * location computed by the data_of() macro.
2510  *
2511  * The function returns 0 to indicate the "end of file" condition.  Negative
2512  * numbers are returned on errors, in which cases the structure pointed to by
2513  * @handle is not updated and should not be used any more.
2514  */
2515 int snapshot_write_next(struct snapshot_handle *handle)
2516 {
2517         static struct chain_allocator ca;
2518         int error = 0;
2519
2520         /* Check if we have already loaded the entire image */
2521         if (handle->cur > 1 && handle->cur > nr_meta_pages + nr_copy_pages)
2522                 return 0;
2523
2524         handle->sync_read = 1;
2525
2526         if (!handle->cur) {
2527                 if (!buffer)
2528                         /* This makes the buffer be freed by swsusp_free() */
2529                         buffer = get_image_page(GFP_ATOMIC, PG_ANY);
2530
2531                 if (!buffer)
2532                         return -ENOMEM;
2533
2534                 handle->buffer = buffer;
2535         } else if (handle->cur == 1) {
2536                 error = load_header(buffer);
2537                 if (error)
2538                         return error;
2539
2540                 safe_pages_list = NULL;
2541
2542                 error = memory_bm_create(&copy_bm, GFP_ATOMIC, PG_ANY);
2543                 if (error)
2544                         return error;
2545
2546                 /* Allocate buffer for page keys. */
2547                 error = page_key_alloc(nr_copy_pages);
2548                 if (error)
2549                         return error;
2550
2551         } else if (handle->cur <= nr_meta_pages + 1) {
2552                 error = unpack_orig_pfns(buffer, &copy_bm);
2553                 if (error)
2554                         return error;
2555
2556                 if (handle->cur == nr_meta_pages + 1) {
2557                         error = prepare_image(&orig_bm, &copy_bm);
2558                         if (error)
2559                                 return error;
2560
2561                         chain_init(&ca, GFP_ATOMIC, PG_SAFE);
2562                         memory_bm_position_reset(&orig_bm);
2563                         restore_pblist = NULL;
2564                         handle->buffer = get_buffer(&orig_bm, &ca);
2565                         handle->sync_read = 0;
2566                         if (IS_ERR(handle->buffer))
2567                                 return PTR_ERR(handle->buffer);
2568                 }
2569         } else {
2570                 copy_last_highmem_page();
2571                 /* Restore page key for data page (s390 only). */
2572                 page_key_write(handle->buffer);
2573                 handle->buffer = get_buffer(&orig_bm, &ca);
2574                 if (IS_ERR(handle->buffer))
2575                         return PTR_ERR(handle->buffer);
2576                 if (handle->buffer != buffer)
2577                         handle->sync_read = 0;
2578         }
2579         handle->cur++;
2580         return PAGE_SIZE;
2581 }
2582
2583 /**
2584  * snapshot_write_finalize - Complete the loading of a hibernation image.
2585  *
2586  * Must be called after the last call to snapshot_write_next() in case the last
2587  * page in the image happens to be a highmem page and its contents should be
2588  * stored in highmem.  Additionally, it recycles bitmap memory that's not
2589  * necessary any more.
2590  */
2591 void snapshot_write_finalize(struct snapshot_handle *handle)
2592 {
2593         copy_last_highmem_page();
2594         /* Restore page key for data page (s390 only). */
2595         page_key_write(handle->buffer);
2596         page_key_free();
2597         /* Do that only if we have loaded the image entirely */
2598         if (handle->cur > 1 && handle->cur > nr_meta_pages + nr_copy_pages) {
2599                 memory_bm_recycle(&orig_bm);
2600                 free_highmem_data();
2601         }
2602 }
2603
2604 int snapshot_image_loaded(struct snapshot_handle *handle)
2605 {
2606         return !(!nr_copy_pages || !last_highmem_page_copied() ||
2607                         handle->cur <= nr_meta_pages + nr_copy_pages);
2608 }
2609
2610 #ifdef CONFIG_HIGHMEM
2611 /* Assumes that @buf is ready and points to a "safe" page */
2612 static inline void swap_two_pages_data(struct page *p1, struct page *p2,
2613                                        void *buf)
2614 {
2615         void *kaddr1, *kaddr2;
2616
2617         kaddr1 = kmap_atomic(p1);
2618         kaddr2 = kmap_atomic(p2);
2619         copy_page(buf, kaddr1);
2620         copy_page(kaddr1, kaddr2);
2621         copy_page(kaddr2, buf);
2622         kunmap_atomic(kaddr2);
2623         kunmap_atomic(kaddr1);
2624 }
2625
2626 /**
2627  * restore_highmem - Put highmem image pages into their original locations.
2628  *
2629  * For each highmem page that was in use before hibernation and is included in
2630  * the image, and also has been allocated by the "restore" kernel, swap its
2631  * current contents with the previous (ie. "before hibernation") ones.
2632  *
2633  * If the restore eventually fails, we can call this function once again and
2634  * restore the highmem state as seen by the restore kernel.
2635  */
2636 int restore_highmem(void)
2637 {
2638         struct highmem_pbe *pbe = highmem_pblist;
2639         void *buf;
2640
2641         if (!pbe)
2642                 return 0;
2643
2644         buf = get_image_page(GFP_ATOMIC, PG_SAFE);
2645         if (!buf)
2646                 return -ENOMEM;
2647
2648         while (pbe) {
2649                 swap_two_pages_data(pbe->copy_page, pbe->orig_page, buf);
2650                 pbe = pbe->next;
2651         }
2652         free_image_page(buf, PG_UNSAFE_CLEAR);
2653         return 0;
2654 }
2655 #endif /* CONFIG_HIGHMEM */