PM / hibernate: Clean up comments in snapshot.c
[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         region->start_pfn = start_pfn;
927         region->end_pfn = end_pfn;
928         list_add_tail(&region->list, &nosave_regions);
929  Report:
930         printk(KERN_INFO "PM: Registered nosave memory: [mem %#010llx-%#010llx]\n",
931                 (unsigned long long) start_pfn << PAGE_SHIFT,
932                 ((unsigned long long) end_pfn << PAGE_SHIFT) - 1);
933 }
934
935 /*
936  * Set bits in this map correspond to the page frames the contents of which
937  * should not be saved during the suspend.
938  */
939 static struct memory_bitmap *forbidden_pages_map;
940
941 /* Set bits in this map correspond to free page frames. */
942 static struct memory_bitmap *free_pages_map;
943
944 /*
945  * Each page frame allocated for creating the image is marked by setting the
946  * corresponding bits in forbidden_pages_map and free_pages_map simultaneously
947  */
948
949 void swsusp_set_page_free(struct page *page)
950 {
951         if (free_pages_map)
952                 memory_bm_set_bit(free_pages_map, page_to_pfn(page));
953 }
954
955 static int swsusp_page_is_free(struct page *page)
956 {
957         return free_pages_map ?
958                 memory_bm_test_bit(free_pages_map, page_to_pfn(page)) : 0;
959 }
960
961 void swsusp_unset_page_free(struct page *page)
962 {
963         if (free_pages_map)
964                 memory_bm_clear_bit(free_pages_map, page_to_pfn(page));
965 }
966
967 static void swsusp_set_page_forbidden(struct page *page)
968 {
969         if (forbidden_pages_map)
970                 memory_bm_set_bit(forbidden_pages_map, page_to_pfn(page));
971 }
972
973 int swsusp_page_is_forbidden(struct page *page)
974 {
975         return forbidden_pages_map ?
976                 memory_bm_test_bit(forbidden_pages_map, page_to_pfn(page)) : 0;
977 }
978
979 static void swsusp_unset_page_forbidden(struct page *page)
980 {
981         if (forbidden_pages_map)
982                 memory_bm_clear_bit(forbidden_pages_map, page_to_pfn(page));
983 }
984
985 /**
986  * mark_nosave_pages - Mark pages that should not be saved.
987  * @bm: Memory bitmap.
988  *
989  * Set the bits in @bm that correspond to the page frames the contents of which
990  * should not be saved.
991  */
992 static void mark_nosave_pages(struct memory_bitmap *bm)
993 {
994         struct nosave_region *region;
995
996         if (list_empty(&nosave_regions))
997                 return;
998
999         list_for_each_entry(region, &nosave_regions, list) {
1000                 unsigned long pfn;
1001
1002                 pr_debug("PM: Marking nosave pages: [mem %#010llx-%#010llx]\n",
1003                          (unsigned long long) region->start_pfn << PAGE_SHIFT,
1004                          ((unsigned long long) region->end_pfn << PAGE_SHIFT)
1005                                 - 1);
1006
1007                 for (pfn = region->start_pfn; pfn < region->end_pfn; pfn++)
1008                         if (pfn_valid(pfn)) {
1009                                 /*
1010                                  * It is safe to ignore the result of
1011                                  * mem_bm_set_bit_check() here, since we won't
1012                                  * touch the PFNs for which the error is
1013                                  * returned anyway.
1014                                  */
1015                                 mem_bm_set_bit_check(bm, pfn);
1016                         }
1017         }
1018 }
1019
1020 /**
1021  * create_basic_memory_bitmaps - Create bitmaps to hold basic page information.
1022  *
1023  * Create bitmaps needed for marking page frames that should not be saved and
1024  * free page frames.  The forbidden_pages_map and free_pages_map pointers are
1025  * only modified if everything goes well, because we don't want the bits to be
1026  * touched before both bitmaps are set up.
1027  */
1028 int create_basic_memory_bitmaps(void)
1029 {
1030         struct memory_bitmap *bm1, *bm2;
1031         int error = 0;
1032
1033         if (forbidden_pages_map && free_pages_map)
1034                 return 0;
1035         else
1036                 BUG_ON(forbidden_pages_map || free_pages_map);
1037
1038         bm1 = kzalloc(sizeof(struct memory_bitmap), GFP_KERNEL);
1039         if (!bm1)
1040                 return -ENOMEM;
1041
1042         error = memory_bm_create(bm1, GFP_KERNEL, PG_ANY);
1043         if (error)
1044                 goto Free_first_object;
1045
1046         bm2 = kzalloc(sizeof(struct memory_bitmap), GFP_KERNEL);
1047         if (!bm2)
1048                 goto Free_first_bitmap;
1049
1050         error = memory_bm_create(bm2, GFP_KERNEL, PG_ANY);
1051         if (error)
1052                 goto Free_second_object;
1053
1054         forbidden_pages_map = bm1;
1055         free_pages_map = bm2;
1056         mark_nosave_pages(forbidden_pages_map);
1057
1058         pr_debug("PM: Basic memory bitmaps created\n");
1059
1060         return 0;
1061
1062  Free_second_object:
1063         kfree(bm2);
1064  Free_first_bitmap:
1065         memory_bm_free(bm1, PG_UNSAFE_CLEAR);
1066  Free_first_object:
1067         kfree(bm1);
1068         return -ENOMEM;
1069 }
1070
1071 /**
1072  * free_basic_memory_bitmaps - Free memory bitmaps holding basic information.
1073  *
1074  * Free memory bitmaps allocated by create_basic_memory_bitmaps().  The
1075  * auxiliary pointers are necessary so that the bitmaps themselves are not
1076  * referred to while they are being freed.
1077  */
1078 void free_basic_memory_bitmaps(void)
1079 {
1080         struct memory_bitmap *bm1, *bm2;
1081
1082         if (WARN_ON(!(forbidden_pages_map && free_pages_map)))
1083                 return;
1084
1085         bm1 = forbidden_pages_map;
1086         bm2 = free_pages_map;
1087         forbidden_pages_map = NULL;
1088         free_pages_map = NULL;
1089         memory_bm_free(bm1, PG_UNSAFE_CLEAR);
1090         kfree(bm1);
1091         memory_bm_free(bm2, PG_UNSAFE_CLEAR);
1092         kfree(bm2);
1093
1094         pr_debug("PM: Basic memory bitmaps freed\n");
1095 }
1096
1097 /**
1098  * snapshot_additional_pages - Estimate the number of extra pages needed.
1099  * @zone: Memory zone to carry out the computation for.
1100  *
1101  * Estimate the number of additional pages needed for setting up a hibernation
1102  * image data structures for @zone (usually, the returned value is greater than
1103  * the exact number).
1104  */
1105 unsigned int snapshot_additional_pages(struct zone *zone)
1106 {
1107         unsigned int rtree, nodes;
1108
1109         rtree = nodes = DIV_ROUND_UP(zone->spanned_pages, BM_BITS_PER_BLOCK);
1110         rtree += DIV_ROUND_UP(rtree * sizeof(struct rtree_node),
1111                               LINKED_PAGE_DATA_SIZE);
1112         while (nodes > 1) {
1113                 nodes = DIV_ROUND_UP(nodes, BM_ENTRIES_PER_LEVEL);
1114                 rtree += nodes;
1115         }
1116
1117         return 2 * rtree;
1118 }
1119
1120 #ifdef CONFIG_HIGHMEM
1121 /**
1122  * count_free_highmem_pages - Compute the total number of free highmem pages.
1123  *
1124  * The returned number is system-wide.
1125  */
1126 static unsigned int count_free_highmem_pages(void)
1127 {
1128         struct zone *zone;
1129         unsigned int cnt = 0;
1130
1131         for_each_populated_zone(zone)
1132                 if (is_highmem(zone))
1133                         cnt += zone_page_state(zone, NR_FREE_PAGES);
1134
1135         return cnt;
1136 }
1137
1138 /**
1139  * saveable_highmem_page - Check if a highmem page is saveable.
1140  *
1141  * Determine whether a highmem page should be included in a hibernation image.
1142  *
1143  * We should save the page if it isn't Nosave or NosaveFree, or Reserved,
1144  * and it isn't part of a free chunk of pages.
1145  */
1146 static struct page *saveable_highmem_page(struct zone *zone, unsigned long pfn)
1147 {
1148         struct page *page;
1149
1150         if (!pfn_valid(pfn))
1151                 return NULL;
1152
1153         page = pfn_to_page(pfn);
1154         if (page_zone(page) != zone)
1155                 return NULL;
1156
1157         BUG_ON(!PageHighMem(page));
1158
1159         if (swsusp_page_is_forbidden(page) ||  swsusp_page_is_free(page) ||
1160             PageReserved(page))
1161                 return NULL;
1162
1163         if (page_is_guard(page))
1164                 return NULL;
1165
1166         return page;
1167 }
1168
1169 /**
1170  * count_highmem_pages - Compute the total number of saveable highmem pages.
1171  */
1172 static unsigned int count_highmem_pages(void)
1173 {
1174         struct zone *zone;
1175         unsigned int n = 0;
1176
1177         for_each_populated_zone(zone) {
1178                 unsigned long pfn, max_zone_pfn;
1179
1180                 if (!is_highmem(zone))
1181                         continue;
1182
1183                 mark_free_pages(zone);
1184                 max_zone_pfn = zone_end_pfn(zone);
1185                 for (pfn = zone->zone_start_pfn; pfn < max_zone_pfn; pfn++)
1186                         if (saveable_highmem_page(zone, pfn))
1187                                 n++;
1188         }
1189         return n;
1190 }
1191 #else
1192 static inline void *saveable_highmem_page(struct zone *z, unsigned long p)
1193 {
1194         return NULL;
1195 }
1196 #endif /* CONFIG_HIGHMEM */
1197
1198 /**
1199  * saveable_page - Check if the given page is saveable.
1200  *
1201  * Determine whether a non-highmem page should be included in a hibernation
1202  * image.
1203  *
1204  * We should save the page if it isn't Nosave, and is not in the range
1205  * of pages statically defined as 'unsaveable', and it isn't part of
1206  * a free chunk of pages.
1207  */
1208 static struct page *saveable_page(struct zone *zone, unsigned long pfn)
1209 {
1210         struct page *page;
1211
1212         if (!pfn_valid(pfn))
1213                 return NULL;
1214
1215         page = pfn_to_page(pfn);
1216         if (page_zone(page) != zone)
1217                 return NULL;
1218
1219         BUG_ON(PageHighMem(page));
1220
1221         if (swsusp_page_is_forbidden(page) || swsusp_page_is_free(page))
1222                 return NULL;
1223
1224         if (PageReserved(page)
1225             && (!kernel_page_present(page) || pfn_is_nosave(pfn)))
1226                 return NULL;
1227
1228         if (page_is_guard(page))
1229                 return NULL;
1230
1231         return page;
1232 }
1233
1234 /**
1235  * count_data_pages - Compute the total number of saveable non-highmem pages.
1236  */
1237 static unsigned int count_data_pages(void)
1238 {
1239         struct zone *zone;
1240         unsigned long pfn, max_zone_pfn;
1241         unsigned int n = 0;
1242
1243         for_each_populated_zone(zone) {
1244                 if (is_highmem(zone))
1245                         continue;
1246
1247                 mark_free_pages(zone);
1248                 max_zone_pfn = zone_end_pfn(zone);
1249                 for (pfn = zone->zone_start_pfn; pfn < max_zone_pfn; pfn++)
1250                         if (saveable_page(zone, pfn))
1251                                 n++;
1252         }
1253         return n;
1254 }
1255
1256 /*
1257  * This is needed, because copy_page and memcpy are not usable for copying
1258  * task structs.
1259  */
1260 static inline void do_copy_page(long *dst, long *src)
1261 {
1262         int n;
1263
1264         for (n = PAGE_SIZE / sizeof(long); n; n--)
1265                 *dst++ = *src++;
1266 }
1267
1268 /**
1269  * safe_copy_page - Copy a page in a safe way.
1270  *
1271  * Check if the page we are going to copy is marked as present in the kernel
1272  * page tables (this always is the case if CONFIG_DEBUG_PAGEALLOC is not set
1273  * and in that case kernel_page_present() always returns 'true').
1274  */
1275 static void safe_copy_page(void *dst, struct page *s_page)
1276 {
1277         if (kernel_page_present(s_page)) {
1278                 do_copy_page(dst, page_address(s_page));
1279         } else {
1280                 kernel_map_pages(s_page, 1, 1);
1281                 do_copy_page(dst, page_address(s_page));
1282                 kernel_map_pages(s_page, 1, 0);
1283         }
1284 }
1285
1286 #ifdef CONFIG_HIGHMEM
1287 static inline struct page *page_is_saveable(struct zone *zone, unsigned long pfn)
1288 {
1289         return is_highmem(zone) ?
1290                 saveable_highmem_page(zone, pfn) : saveable_page(zone, pfn);
1291 }
1292
1293 static void copy_data_page(unsigned long dst_pfn, unsigned long src_pfn)
1294 {
1295         struct page *s_page, *d_page;
1296         void *src, *dst;
1297
1298         s_page = pfn_to_page(src_pfn);
1299         d_page = pfn_to_page(dst_pfn);
1300         if (PageHighMem(s_page)) {
1301                 src = kmap_atomic(s_page);
1302                 dst = kmap_atomic(d_page);
1303                 do_copy_page(dst, src);
1304                 kunmap_atomic(dst);
1305                 kunmap_atomic(src);
1306         } else {
1307                 if (PageHighMem(d_page)) {
1308                         /*
1309                          * The page pointed to by src may contain some kernel
1310                          * data modified by kmap_atomic()
1311                          */
1312                         safe_copy_page(buffer, s_page);
1313                         dst = kmap_atomic(d_page);
1314                         copy_page(dst, buffer);
1315                         kunmap_atomic(dst);
1316                 } else {
1317                         safe_copy_page(page_address(d_page), s_page);
1318                 }
1319         }
1320 }
1321 #else
1322 #define page_is_saveable(zone, pfn)     saveable_page(zone, pfn)
1323
1324 static inline void copy_data_page(unsigned long dst_pfn, unsigned long src_pfn)
1325 {
1326         safe_copy_page(page_address(pfn_to_page(dst_pfn)),
1327                                 pfn_to_page(src_pfn));
1328 }
1329 #endif /* CONFIG_HIGHMEM */
1330
1331 static void copy_data_pages(struct memory_bitmap *copy_bm,
1332                             struct memory_bitmap *orig_bm)
1333 {
1334         struct zone *zone;
1335         unsigned long pfn;
1336
1337         for_each_populated_zone(zone) {
1338                 unsigned long max_zone_pfn;
1339
1340                 mark_free_pages(zone);
1341                 max_zone_pfn = zone_end_pfn(zone);
1342                 for (pfn = zone->zone_start_pfn; pfn < max_zone_pfn; pfn++)
1343                         if (page_is_saveable(zone, pfn))
1344                                 memory_bm_set_bit(orig_bm, pfn);
1345         }
1346         memory_bm_position_reset(orig_bm);
1347         memory_bm_position_reset(copy_bm);
1348         for(;;) {
1349                 pfn = memory_bm_next_pfn(orig_bm);
1350                 if (unlikely(pfn == BM_END_OF_MAP))
1351                         break;
1352                 copy_data_page(memory_bm_next_pfn(copy_bm), pfn);
1353         }
1354 }
1355
1356 /* Total number of image pages */
1357 static unsigned int nr_copy_pages;
1358 /* Number of pages needed for saving the original pfns of the image pages */
1359 static unsigned int nr_meta_pages;
1360 /*
1361  * Numbers of normal and highmem page frames allocated for hibernation image
1362  * before suspending devices.
1363  */
1364 unsigned int alloc_normal, alloc_highmem;
1365 /*
1366  * Memory bitmap used for marking saveable pages (during hibernation) or
1367  * hibernation image pages (during restore)
1368  */
1369 static struct memory_bitmap orig_bm;
1370 /*
1371  * Memory bitmap used during hibernation for marking allocated page frames that
1372  * will contain copies of saveable pages.  During restore it is initially used
1373  * for marking hibernation image pages, but then the set bits from it are
1374  * duplicated in @orig_bm and it is released.  On highmem systems it is next
1375  * used for marking "safe" highmem pages, but it has to be reinitialized for
1376  * this purpose.
1377  */
1378 static struct memory_bitmap copy_bm;
1379
1380 /**
1381  * swsusp_free - Free pages allocated for hibernation image.
1382  *
1383  * Image pages are alocated before snapshot creation, so they need to be
1384  * released after resume.
1385  */
1386 void swsusp_free(void)
1387 {
1388         unsigned long fb_pfn, fr_pfn;
1389
1390         if (!forbidden_pages_map || !free_pages_map)
1391                 goto out;
1392
1393         memory_bm_position_reset(forbidden_pages_map);
1394         memory_bm_position_reset(free_pages_map);
1395
1396 loop:
1397         fr_pfn = memory_bm_next_pfn(free_pages_map);
1398         fb_pfn = memory_bm_next_pfn(forbidden_pages_map);
1399
1400         /*
1401          * Find the next bit set in both bitmaps. This is guaranteed to
1402          * terminate when fb_pfn == fr_pfn == BM_END_OF_MAP.
1403          */
1404         do {
1405                 if (fb_pfn < fr_pfn)
1406                         fb_pfn = memory_bm_next_pfn(forbidden_pages_map);
1407                 if (fr_pfn < fb_pfn)
1408                         fr_pfn = memory_bm_next_pfn(free_pages_map);
1409         } while (fb_pfn != fr_pfn);
1410
1411         if (fr_pfn != BM_END_OF_MAP && pfn_valid(fr_pfn)) {
1412                 struct page *page = pfn_to_page(fr_pfn);
1413
1414                 memory_bm_clear_current(forbidden_pages_map);
1415                 memory_bm_clear_current(free_pages_map);
1416                 __free_page(page);
1417                 goto loop;
1418         }
1419
1420 out:
1421         nr_copy_pages = 0;
1422         nr_meta_pages = 0;
1423         restore_pblist = NULL;
1424         buffer = NULL;
1425         alloc_normal = 0;
1426         alloc_highmem = 0;
1427 }
1428
1429 /* Helper functions used for the shrinking of memory. */
1430
1431 #define GFP_IMAGE       (GFP_KERNEL | __GFP_NOWARN)
1432
1433 /**
1434  * preallocate_image_pages - Allocate a number of pages for hibernation image.
1435  * @nr_pages: Number of page frames to allocate.
1436  * @mask: GFP flags to use for the allocation.
1437  *
1438  * Return value: Number of page frames actually allocated
1439  */
1440 static unsigned long preallocate_image_pages(unsigned long nr_pages, gfp_t mask)
1441 {
1442         unsigned long nr_alloc = 0;
1443
1444         while (nr_pages > 0) {
1445                 struct page *page;
1446
1447                 page = alloc_image_page(mask);
1448                 if (!page)
1449                         break;
1450                 memory_bm_set_bit(&copy_bm, page_to_pfn(page));
1451                 if (PageHighMem(page))
1452                         alloc_highmem++;
1453                 else
1454                         alloc_normal++;
1455                 nr_pages--;
1456                 nr_alloc++;
1457         }
1458
1459         return nr_alloc;
1460 }
1461
1462 static unsigned long preallocate_image_memory(unsigned long nr_pages,
1463                                               unsigned long avail_normal)
1464 {
1465         unsigned long alloc;
1466
1467         if (avail_normal <= alloc_normal)
1468                 return 0;
1469
1470         alloc = avail_normal - alloc_normal;
1471         if (nr_pages < alloc)
1472                 alloc = nr_pages;
1473
1474         return preallocate_image_pages(alloc, GFP_IMAGE);
1475 }
1476
1477 #ifdef CONFIG_HIGHMEM
1478 static unsigned long preallocate_image_highmem(unsigned long nr_pages)
1479 {
1480         return preallocate_image_pages(nr_pages, GFP_IMAGE | __GFP_HIGHMEM);
1481 }
1482
1483 /**
1484  *  __fraction - Compute (an approximation of) x * (multiplier / base).
1485  */
1486 static unsigned long __fraction(u64 x, u64 multiplier, u64 base)
1487 {
1488         x *= multiplier;
1489         do_div(x, base);
1490         return (unsigned long)x;
1491 }
1492
1493 static unsigned long preallocate_highmem_fraction(unsigned long nr_pages,
1494                                                   unsigned long highmem,
1495                                                   unsigned long total)
1496 {
1497         unsigned long alloc = __fraction(nr_pages, highmem, total);
1498
1499         return preallocate_image_pages(alloc, GFP_IMAGE | __GFP_HIGHMEM);
1500 }
1501 #else /* CONFIG_HIGHMEM */
1502 static inline unsigned long preallocate_image_highmem(unsigned long nr_pages)
1503 {
1504         return 0;
1505 }
1506
1507 static inline unsigned long preallocate_highmem_fraction(unsigned long nr_pages,
1508                                                          unsigned long highmem,
1509                                                          unsigned long total)
1510 {
1511         return 0;
1512 }
1513 #endif /* CONFIG_HIGHMEM */
1514
1515 /**
1516  * free_unnecessary_pages - Release preallocated pages not needed for the image.
1517  */
1518 static unsigned long free_unnecessary_pages(void)
1519 {
1520         unsigned long save, to_free_normal, to_free_highmem, free;
1521
1522         save = count_data_pages();
1523         if (alloc_normal >= save) {
1524                 to_free_normal = alloc_normal - save;
1525                 save = 0;
1526         } else {
1527                 to_free_normal = 0;
1528                 save -= alloc_normal;
1529         }
1530         save += count_highmem_pages();
1531         if (alloc_highmem >= save) {
1532                 to_free_highmem = alloc_highmem - save;
1533         } else {
1534                 to_free_highmem = 0;
1535                 save -= alloc_highmem;
1536                 if (to_free_normal > save)
1537                         to_free_normal -= save;
1538                 else
1539                         to_free_normal = 0;
1540         }
1541         free = to_free_normal + to_free_highmem;
1542
1543         memory_bm_position_reset(&copy_bm);
1544
1545         while (to_free_normal > 0 || to_free_highmem > 0) {
1546                 unsigned long pfn = memory_bm_next_pfn(&copy_bm);
1547                 struct page *page = pfn_to_page(pfn);
1548
1549                 if (PageHighMem(page)) {
1550                         if (!to_free_highmem)
1551                                 continue;
1552                         to_free_highmem--;
1553                         alloc_highmem--;
1554                 } else {
1555                         if (!to_free_normal)
1556                                 continue;
1557                         to_free_normal--;
1558                         alloc_normal--;
1559                 }
1560                 memory_bm_clear_bit(&copy_bm, pfn);
1561                 swsusp_unset_page_forbidden(page);
1562                 swsusp_unset_page_free(page);
1563                 __free_page(page);
1564         }
1565
1566         return free;
1567 }
1568
1569 /**
1570  * minimum_image_size - Estimate the minimum acceptable size of an image.
1571  * @saveable: Number of saveable pages in the system.
1572  *
1573  * We want to avoid attempting to free too much memory too hard, so estimate the
1574  * minimum acceptable size of a hibernation image to use as the lower limit for
1575  * preallocating memory.
1576  *
1577  * We assume that the minimum image size should be proportional to
1578  *
1579  * [number of saveable pages] - [number of pages that can be freed in theory]
1580  *
1581  * where the second term is the sum of (1) reclaimable slab pages, (2) active
1582  * and (3) inactive anonymous pages, (4) active and (5) inactive file pages,
1583  * minus mapped file pages.
1584  */
1585 static unsigned long minimum_image_size(unsigned long saveable)
1586 {
1587         unsigned long size;
1588
1589         size = global_page_state(NR_SLAB_RECLAIMABLE)
1590                 + global_page_state(NR_ACTIVE_ANON)
1591                 + global_page_state(NR_INACTIVE_ANON)
1592                 + global_page_state(NR_ACTIVE_FILE)
1593                 + global_page_state(NR_INACTIVE_FILE)
1594                 - global_page_state(NR_FILE_MAPPED);
1595
1596         return saveable <= size ? 0 : saveable - size;
1597 }
1598
1599 /**
1600  * hibernate_preallocate_memory - Preallocate memory for hibernation image.
1601  *
1602  * To create a hibernation image it is necessary to make a copy of every page
1603  * frame in use.  We also need a number of page frames to be free during
1604  * hibernation for allocations made while saving the image and for device
1605  * drivers, in case they need to allocate memory from their hibernation
1606  * callbacks (these two numbers are given by PAGES_FOR_IO (which is a rough
1607  * estimate) and reserverd_size divided by PAGE_SIZE (which is tunable through
1608  * /sys/power/reserved_size, respectively).  To make this happen, we compute the
1609  * total number of available page frames and allocate at least
1610  *
1611  * ([page frames total] + PAGES_FOR_IO + [metadata pages]) / 2
1612  *  + 2 * DIV_ROUND_UP(reserved_size, PAGE_SIZE)
1613  *
1614  * of them, which corresponds to the maximum size of a hibernation image.
1615  *
1616  * If image_size is set below the number following from the above formula,
1617  * the preallocation of memory is continued until the total number of saveable
1618  * pages in the system is below the requested image size or the minimum
1619  * acceptable image size returned by minimum_image_size(), whichever is greater.
1620  */
1621 int hibernate_preallocate_memory(void)
1622 {
1623         struct zone *zone;
1624         unsigned long saveable, size, max_size, count, highmem, pages = 0;
1625         unsigned long alloc, save_highmem, pages_highmem, avail_normal;
1626         ktime_t start, stop;
1627         int error;
1628
1629         printk(KERN_INFO "PM: Preallocating image memory... ");
1630         start = ktime_get();
1631
1632         error = memory_bm_create(&orig_bm, GFP_IMAGE, PG_ANY);
1633         if (error)
1634                 goto err_out;
1635
1636         error = memory_bm_create(&copy_bm, GFP_IMAGE, PG_ANY);
1637         if (error)
1638                 goto err_out;
1639
1640         alloc_normal = 0;
1641         alloc_highmem = 0;
1642
1643         /* Count the number of saveable data pages. */
1644         save_highmem = count_highmem_pages();
1645         saveable = count_data_pages();
1646
1647         /*
1648          * Compute the total number of page frames we can use (count) and the
1649          * number of pages needed for image metadata (size).
1650          */
1651         count = saveable;
1652         saveable += save_highmem;
1653         highmem = save_highmem;
1654         size = 0;
1655         for_each_populated_zone(zone) {
1656                 size += snapshot_additional_pages(zone);
1657                 if (is_highmem(zone))
1658                         highmem += zone_page_state(zone, NR_FREE_PAGES);
1659                 else
1660                         count += zone_page_state(zone, NR_FREE_PAGES);
1661         }
1662         avail_normal = count;
1663         count += highmem;
1664         count -= totalreserve_pages;
1665
1666         /* Add number of pages required for page keys (s390 only). */
1667         size += page_key_additional_pages(saveable);
1668
1669         /* Compute the maximum number of saveable pages to leave in memory. */
1670         max_size = (count - (size + PAGES_FOR_IO)) / 2
1671                         - 2 * DIV_ROUND_UP(reserved_size, PAGE_SIZE);
1672         /* Compute the desired number of image pages specified by image_size. */
1673         size = DIV_ROUND_UP(image_size, PAGE_SIZE);
1674         if (size > max_size)
1675                 size = max_size;
1676         /*
1677          * If the desired number of image pages is at least as large as the
1678          * current number of saveable pages in memory, allocate page frames for
1679          * the image and we're done.
1680          */
1681         if (size >= saveable) {
1682                 pages = preallocate_image_highmem(save_highmem);
1683                 pages += preallocate_image_memory(saveable - pages, avail_normal);
1684                 goto out;
1685         }
1686
1687         /* Estimate the minimum size of the image. */
1688         pages = minimum_image_size(saveable);
1689         /*
1690          * To avoid excessive pressure on the normal zone, leave room in it to
1691          * accommodate an image of the minimum size (unless it's already too
1692          * small, in which case don't preallocate pages from it at all).
1693          */
1694         if (avail_normal > pages)
1695                 avail_normal -= pages;
1696         else
1697                 avail_normal = 0;
1698         if (size < pages)
1699                 size = min_t(unsigned long, pages, max_size);
1700
1701         /*
1702          * Let the memory management subsystem know that we're going to need a
1703          * large number of page frames to allocate and make it free some memory.
1704          * NOTE: If this is not done, performance will be hurt badly in some
1705          * test cases.
1706          */
1707         shrink_all_memory(saveable - size);
1708
1709         /*
1710          * The number of saveable pages in memory was too high, so apply some
1711          * pressure to decrease it.  First, make room for the largest possible
1712          * image and fail if that doesn't work.  Next, try to decrease the size
1713          * of the image as much as indicated by 'size' using allocations from
1714          * highmem and non-highmem zones separately.
1715          */
1716         pages_highmem = preallocate_image_highmem(highmem / 2);
1717         alloc = count - max_size;
1718         if (alloc > pages_highmem)
1719                 alloc -= pages_highmem;
1720         else
1721                 alloc = 0;
1722         pages = preallocate_image_memory(alloc, avail_normal);
1723         if (pages < alloc) {
1724                 /* We have exhausted non-highmem pages, try highmem. */
1725                 alloc -= pages;
1726                 pages += pages_highmem;
1727                 pages_highmem = preallocate_image_highmem(alloc);
1728                 if (pages_highmem < alloc)
1729                         goto err_out;
1730                 pages += pages_highmem;
1731                 /*
1732                  * size is the desired number of saveable pages to leave in
1733                  * memory, so try to preallocate (all memory - size) pages.
1734                  */
1735                 alloc = (count - pages) - size;
1736                 pages += preallocate_image_highmem(alloc);
1737         } else {
1738                 /*
1739                  * There are approximately max_size saveable pages at this point
1740                  * and we want to reduce this number down to size.
1741                  */
1742                 alloc = max_size - size;
1743                 size = preallocate_highmem_fraction(alloc, highmem, count);
1744                 pages_highmem += size;
1745                 alloc -= size;
1746                 size = preallocate_image_memory(alloc, avail_normal);
1747                 pages_highmem += preallocate_image_highmem(alloc - size);
1748                 pages += pages_highmem + size;
1749         }
1750
1751         /*
1752          * We only need as many page frames for the image as there are saveable
1753          * pages in memory, but we have allocated more.  Release the excessive
1754          * ones now.
1755          */
1756         pages -= free_unnecessary_pages();
1757
1758  out:
1759         stop = ktime_get();
1760         printk(KERN_CONT "done (allocated %lu pages)\n", pages);
1761         swsusp_show_speed(start, stop, pages, "Allocated");
1762
1763         return 0;
1764
1765  err_out:
1766         printk(KERN_CONT "\n");
1767         swsusp_free();
1768         return -ENOMEM;
1769 }
1770
1771 #ifdef CONFIG_HIGHMEM
1772 /**
1773  * count_pages_for_highmem - Count non-highmem pages needed for copying highmem.
1774  *
1775  * Compute the number of non-highmem pages that will be necessary for creating
1776  * copies of highmem pages.
1777  */
1778 static unsigned int count_pages_for_highmem(unsigned int nr_highmem)
1779 {
1780         unsigned int free_highmem = count_free_highmem_pages() + alloc_highmem;
1781
1782         if (free_highmem >= nr_highmem)
1783                 nr_highmem = 0;
1784         else
1785                 nr_highmem -= free_highmem;
1786
1787         return nr_highmem;
1788 }
1789 #else
1790 static unsigned int count_pages_for_highmem(unsigned int nr_highmem) { return 0; }
1791 #endif /* CONFIG_HIGHMEM */
1792
1793 /**
1794  * enough_free_mem - Check if there is enough free memory for the image.
1795  */
1796 static int enough_free_mem(unsigned int nr_pages, unsigned int nr_highmem)
1797 {
1798         struct zone *zone;
1799         unsigned int free = alloc_normal;
1800
1801         for_each_populated_zone(zone)
1802                 if (!is_highmem(zone))
1803                         free += zone_page_state(zone, NR_FREE_PAGES);
1804
1805         nr_pages += count_pages_for_highmem(nr_highmem);
1806         pr_debug("PM: Normal pages needed: %u + %u, available pages: %u\n",
1807                 nr_pages, PAGES_FOR_IO, free);
1808
1809         return free > nr_pages + PAGES_FOR_IO;
1810 }
1811
1812 #ifdef CONFIG_HIGHMEM
1813 /**
1814  * get_highmem_buffer - Allocate a buffer for highmem pages.
1815  *
1816  * If there are some highmem pages in the hibernation image, we may need a
1817  * buffer to copy them and/or load their data.
1818  */
1819 static inline int get_highmem_buffer(int safe_needed)
1820 {
1821         buffer = get_image_page(GFP_ATOMIC | __GFP_COLD, safe_needed);
1822         return buffer ? 0 : -ENOMEM;
1823 }
1824
1825 /**
1826  * alloc_highmem_image_pages - Allocate some highmem pages for the image.
1827  *
1828  * Try to allocate as many pages as needed, but if the number of free highmem
1829  * pages is less than that, allocate them all.
1830  */
1831 static inline unsigned int alloc_highmem_pages(struct memory_bitmap *bm,
1832                                                unsigned int nr_highmem)
1833 {
1834         unsigned int to_alloc = count_free_highmem_pages();
1835
1836         if (to_alloc > nr_highmem)
1837                 to_alloc = nr_highmem;
1838
1839         nr_highmem -= to_alloc;
1840         while (to_alloc-- > 0) {
1841                 struct page *page;
1842
1843                 page = alloc_image_page(__GFP_HIGHMEM|__GFP_KSWAPD_RECLAIM);
1844                 memory_bm_set_bit(bm, page_to_pfn(page));
1845         }
1846         return nr_highmem;
1847 }
1848 #else
1849 static inline int get_highmem_buffer(int safe_needed) { return 0; }
1850
1851 static inline unsigned int alloc_highmem_pages(struct memory_bitmap *bm,
1852                                                unsigned int n) { return 0; }
1853 #endif /* CONFIG_HIGHMEM */
1854
1855 /**
1856  * swsusp_alloc - Allocate memory for hibernation image.
1857  *
1858  * We first try to allocate as many highmem pages as there are
1859  * saveable highmem pages in the system.  If that fails, we allocate
1860  * non-highmem pages for the copies of the remaining highmem ones.
1861  *
1862  * In this approach it is likely that the copies of highmem pages will
1863  * also be located in the high memory, because of the way in which
1864  * copy_data_pages() works.
1865  */
1866 static int swsusp_alloc(struct memory_bitmap *orig_bm,
1867                         struct memory_bitmap *copy_bm,
1868                         unsigned int nr_pages, unsigned int nr_highmem)
1869 {
1870         if (nr_highmem > 0) {
1871                 if (get_highmem_buffer(PG_ANY))
1872                         goto err_out;
1873                 if (nr_highmem > alloc_highmem) {
1874                         nr_highmem -= alloc_highmem;
1875                         nr_pages += alloc_highmem_pages(copy_bm, nr_highmem);
1876                 }
1877         }
1878         if (nr_pages > alloc_normal) {
1879                 nr_pages -= alloc_normal;
1880                 while (nr_pages-- > 0) {
1881                         struct page *page;
1882
1883                         page = alloc_image_page(GFP_ATOMIC | __GFP_COLD);
1884                         if (!page)
1885                                 goto err_out;
1886                         memory_bm_set_bit(copy_bm, page_to_pfn(page));
1887                 }
1888         }
1889
1890         return 0;
1891
1892  err_out:
1893         swsusp_free();
1894         return -ENOMEM;
1895 }
1896
1897 asmlinkage __visible int swsusp_save(void)
1898 {
1899         unsigned int nr_pages, nr_highmem;
1900
1901         printk(KERN_INFO "PM: Creating hibernation image:\n");
1902
1903         drain_local_pages(NULL);
1904         nr_pages = count_data_pages();
1905         nr_highmem = count_highmem_pages();
1906         printk(KERN_INFO "PM: Need to copy %u pages\n", nr_pages + nr_highmem);
1907
1908         if (!enough_free_mem(nr_pages, nr_highmem)) {
1909                 printk(KERN_ERR "PM: Not enough free memory\n");
1910                 return -ENOMEM;
1911         }
1912
1913         if (swsusp_alloc(&orig_bm, &copy_bm, nr_pages, nr_highmem)) {
1914                 printk(KERN_ERR "PM: Memory allocation failed\n");
1915                 return -ENOMEM;
1916         }
1917
1918         /*
1919          * During allocating of suspend pagedir, new cold pages may appear.
1920          * Kill them.
1921          */
1922         drain_local_pages(NULL);
1923         copy_data_pages(&copy_bm, &orig_bm);
1924
1925         /*
1926          * End of critical section. From now on, we can write to memory,
1927          * but we should not touch disk. This specially means we must _not_
1928          * touch swap space! Except we must write out our image of course.
1929          */
1930
1931         nr_pages += nr_highmem;
1932         nr_copy_pages = nr_pages;
1933         nr_meta_pages = DIV_ROUND_UP(nr_pages * sizeof(long), PAGE_SIZE);
1934
1935         printk(KERN_INFO "PM: Hibernation image created (%d pages copied)\n",
1936                 nr_pages);
1937
1938         return 0;
1939 }
1940
1941 #ifndef CONFIG_ARCH_HIBERNATION_HEADER
1942 static int init_header_complete(struct swsusp_info *info)
1943 {
1944         memcpy(&info->uts, init_utsname(), sizeof(struct new_utsname));
1945         info->version_code = LINUX_VERSION_CODE;
1946         return 0;
1947 }
1948
1949 static char *check_image_kernel(struct swsusp_info *info)
1950 {
1951         if (info->version_code != LINUX_VERSION_CODE)
1952                 return "kernel version";
1953         if (strcmp(info->uts.sysname,init_utsname()->sysname))
1954                 return "system type";
1955         if (strcmp(info->uts.release,init_utsname()->release))
1956                 return "kernel release";
1957         if (strcmp(info->uts.version,init_utsname()->version))
1958                 return "version";
1959         if (strcmp(info->uts.machine,init_utsname()->machine))
1960                 return "machine";
1961         return NULL;
1962 }
1963 #endif /* CONFIG_ARCH_HIBERNATION_HEADER */
1964
1965 unsigned long snapshot_get_image_size(void)
1966 {
1967         return nr_copy_pages + nr_meta_pages + 1;
1968 }
1969
1970 static int init_header(struct swsusp_info *info)
1971 {
1972         memset(info, 0, sizeof(struct swsusp_info));
1973         info->num_physpages = get_num_physpages();
1974         info->image_pages = nr_copy_pages;
1975         info->pages = snapshot_get_image_size();
1976         info->size = info->pages;
1977         info->size <<= PAGE_SHIFT;
1978         return init_header_complete(info);
1979 }
1980
1981 /**
1982  * pack_pfns - Prepare PFNs for saving.
1983  * @bm: Memory bitmap.
1984  * @buf: Memory buffer to store the PFNs in.
1985  *
1986  * PFNs corresponding to set bits in @bm are stored in the area of memory
1987  * pointed to by @buf (1 page at a time).
1988  */
1989 static inline void pack_pfns(unsigned long *buf, struct memory_bitmap *bm)
1990 {
1991         int j;
1992
1993         for (j = 0; j < PAGE_SIZE / sizeof(long); j++) {
1994                 buf[j] = memory_bm_next_pfn(bm);
1995                 if (unlikely(buf[j] == BM_END_OF_MAP))
1996                         break;
1997                 /* Save page key for data page (s390 only). */
1998                 page_key_read(buf + j);
1999         }
2000 }
2001
2002 /**
2003  * snapshot_read_next - Get the address to read the next image page from.
2004  * @handle: Snapshot handle to be used for the reading.
2005  *
2006  * On the first call, @handle should point to a zeroed snapshot_handle
2007  * structure.  The structure gets populated then and a pointer to it should be
2008  * passed to this function every next time.
2009  *
2010  * On success, the function returns a positive number.  Then, the caller
2011  * is allowed to read up to the returned number of bytes from the memory
2012  * location computed by the data_of() macro.
2013  *
2014  * The function returns 0 to indicate the end of the data stream condition,
2015  * and negative numbers are returned on errors.  If that happens, the structure
2016  * pointed to by @handle is not updated and should not be used any more.
2017  */
2018 int snapshot_read_next(struct snapshot_handle *handle)
2019 {
2020         if (handle->cur > nr_meta_pages + nr_copy_pages)
2021                 return 0;
2022
2023         if (!buffer) {
2024                 /* This makes the buffer be freed by swsusp_free() */
2025                 buffer = get_image_page(GFP_ATOMIC, PG_ANY);
2026                 if (!buffer)
2027                         return -ENOMEM;
2028         }
2029         if (!handle->cur) {
2030                 int error;
2031
2032                 error = init_header((struct swsusp_info *)buffer);
2033                 if (error)
2034                         return error;
2035                 handle->buffer = buffer;
2036                 memory_bm_position_reset(&orig_bm);
2037                 memory_bm_position_reset(&copy_bm);
2038         } else if (handle->cur <= nr_meta_pages) {
2039                 clear_page(buffer);
2040                 pack_pfns(buffer, &orig_bm);
2041         } else {
2042                 struct page *page;
2043
2044                 page = pfn_to_page(memory_bm_next_pfn(&copy_bm));
2045                 if (PageHighMem(page)) {
2046                         /*
2047                          * Highmem pages are copied to the buffer,
2048                          * because we can't return with a kmapped
2049                          * highmem page (we may not be called again).
2050                          */
2051                         void *kaddr;
2052
2053                         kaddr = kmap_atomic(page);
2054                         copy_page(buffer, kaddr);
2055                         kunmap_atomic(kaddr);
2056                         handle->buffer = buffer;
2057                 } else {
2058                         handle->buffer = page_address(page);
2059                 }
2060         }
2061         handle->cur++;
2062         return PAGE_SIZE;
2063 }
2064
2065 static void duplicate_memory_bitmap(struct memory_bitmap *dst,
2066                                     struct memory_bitmap *src)
2067 {
2068         unsigned long pfn;
2069
2070         memory_bm_position_reset(src);
2071         pfn = memory_bm_next_pfn(src);
2072         while (pfn != BM_END_OF_MAP) {
2073                 memory_bm_set_bit(dst, pfn);
2074                 pfn = memory_bm_next_pfn(src);
2075         }
2076 }
2077
2078 /**
2079  * mark_unsafe_pages - Mark pages that were used before hibernation.
2080  *
2081  * Mark the pages that cannot be used for storing the image during restoration,
2082  * because they conflict with the pages that had been used before hibernation.
2083  */
2084 static void mark_unsafe_pages(struct memory_bitmap *bm)
2085 {
2086         unsigned long pfn;
2087
2088         /* Clear the "free"/"unsafe" bit for all PFNs */
2089         memory_bm_position_reset(free_pages_map);
2090         pfn = memory_bm_next_pfn(free_pages_map);
2091         while (pfn != BM_END_OF_MAP) {
2092                 memory_bm_clear_current(free_pages_map);
2093                 pfn = memory_bm_next_pfn(free_pages_map);
2094         }
2095
2096         /* Mark pages that correspond to the "original" PFNs as "unsafe" */
2097         duplicate_memory_bitmap(free_pages_map, bm);
2098
2099         allocated_unsafe_pages = 0;
2100 }
2101
2102 static int check_header(struct swsusp_info *info)
2103 {
2104         char *reason;
2105
2106         reason = check_image_kernel(info);
2107         if (!reason && info->num_physpages != get_num_physpages())
2108                 reason = "memory size";
2109         if (reason) {
2110                 printk(KERN_ERR "PM: Image mismatch: %s\n", reason);
2111                 return -EPERM;
2112         }
2113         return 0;
2114 }
2115
2116 /**
2117  * load header - Check the image header and copy the data from it.
2118  */
2119 static int load_header(struct swsusp_info *info)
2120 {
2121         int error;
2122
2123         restore_pblist = NULL;
2124         error = check_header(info);
2125         if (!error) {
2126                 nr_copy_pages = info->image_pages;
2127                 nr_meta_pages = info->pages - info->image_pages - 1;
2128         }
2129         return error;
2130 }
2131
2132 /**
2133  * unpack_orig_pfns - Set bits corresponding to given PFNs in a memory bitmap.
2134  * @bm: Memory bitmap.
2135  * @buf: Area of memory containing the PFNs.
2136  *
2137  * For each element of the array pointed to by @buf (1 page at a time), set the
2138  * corresponding bit in @bm.
2139  */
2140 static int unpack_orig_pfns(unsigned long *buf, struct memory_bitmap *bm)
2141 {
2142         int j;
2143
2144         for (j = 0; j < PAGE_SIZE / sizeof(long); j++) {
2145                 if (unlikely(buf[j] == BM_END_OF_MAP))
2146                         break;
2147
2148                 /* Extract and buffer page key for data page (s390 only). */
2149                 page_key_memorize(buf + j);
2150
2151                 if (pfn_valid(buf[j]) && memory_bm_pfn_present(bm, buf[j]))
2152                         memory_bm_set_bit(bm, buf[j]);
2153                 else
2154                         return -EFAULT;
2155         }
2156
2157         return 0;
2158 }
2159
2160 #ifdef CONFIG_HIGHMEM
2161 /*
2162  * struct highmem_pbe is used for creating the list of highmem pages that
2163  * should be restored atomically during the resume from disk, because the page
2164  * frames they have occupied before the suspend are in use.
2165  */
2166 struct highmem_pbe {
2167         struct page *copy_page; /* data is here now */
2168         struct page *orig_page; /* data was here before the suspend */
2169         struct highmem_pbe *next;
2170 };
2171
2172 /*
2173  * List of highmem PBEs needed for restoring the highmem pages that were
2174  * allocated before the suspend and included in the suspend image, but have
2175  * also been allocated by the "resume" kernel, so their contents cannot be
2176  * written directly to their "original" page frames.
2177  */
2178 static struct highmem_pbe *highmem_pblist;
2179
2180 /**
2181  * count_highmem_image_pages - Compute the number of highmem pages in the image.
2182  * @bm: Memory bitmap.
2183  *
2184  * The bits in @bm that correspond to image pages are assumed to be set.
2185  */
2186 static unsigned int count_highmem_image_pages(struct memory_bitmap *bm)
2187 {
2188         unsigned long pfn;
2189         unsigned int cnt = 0;
2190
2191         memory_bm_position_reset(bm);
2192         pfn = memory_bm_next_pfn(bm);
2193         while (pfn != BM_END_OF_MAP) {
2194                 if (PageHighMem(pfn_to_page(pfn)))
2195                         cnt++;
2196
2197                 pfn = memory_bm_next_pfn(bm);
2198         }
2199         return cnt;
2200 }
2201
2202 static unsigned int safe_highmem_pages;
2203
2204 static struct memory_bitmap *safe_highmem_bm;
2205
2206 /**
2207  * prepare_highmem_image - Allocate memory for loading highmem data from image.
2208  * @bm: Pointer to an uninitialized memory bitmap structure.
2209  * @nr_highmem_p: Pointer to the number of highmem image pages.
2210  *
2211  * Try to allocate as many highmem pages as there are highmem image pages
2212  * (@nr_highmem_p points to the variable containing the number of highmem image
2213  * pages).  The pages that are "safe" (ie. will not be overwritten when the
2214  * hibernation image is restored entirely) have the corresponding bits set in
2215  * @bm (it must be unitialized).
2216  *
2217  * NOTE: This function should not be called if there are no highmem image pages.
2218  */
2219 static int prepare_highmem_image(struct memory_bitmap *bm,
2220                                  unsigned int *nr_highmem_p)
2221 {
2222         unsigned int to_alloc;
2223
2224         if (memory_bm_create(bm, GFP_ATOMIC, PG_SAFE))
2225                 return -ENOMEM;
2226
2227         if (get_highmem_buffer(PG_SAFE))
2228                 return -ENOMEM;
2229
2230         to_alloc = count_free_highmem_pages();
2231         if (to_alloc > *nr_highmem_p)
2232                 to_alloc = *nr_highmem_p;
2233         else
2234                 *nr_highmem_p = to_alloc;
2235
2236         safe_highmem_pages = 0;
2237         while (to_alloc-- > 0) {
2238                 struct page *page;
2239
2240                 page = alloc_page(__GFP_HIGHMEM);
2241                 if (!swsusp_page_is_free(page)) {
2242                         /* The page is "safe", set its bit the bitmap */
2243                         memory_bm_set_bit(bm, page_to_pfn(page));
2244                         safe_highmem_pages++;
2245                 }
2246                 /* Mark the page as allocated */
2247                 swsusp_set_page_forbidden(page);
2248                 swsusp_set_page_free(page);
2249         }
2250         memory_bm_position_reset(bm);
2251         safe_highmem_bm = bm;
2252         return 0;
2253 }
2254
2255 static struct page *last_highmem_page;
2256
2257 /**
2258  * get_highmem_page_buffer - Prepare a buffer to store a highmem image page.
2259  *
2260  * For a given highmem image page get a buffer that suspend_write_next() should
2261  * return to its caller to write to.
2262  *
2263  * If the page is to be saved to its "original" page frame or a copy of
2264  * the page is to be made in the highmem, @buffer is returned.  Otherwise,
2265  * the copy of the page is to be made in normal memory, so the address of
2266  * the copy is returned.
2267  *
2268  * If @buffer is returned, the caller of suspend_write_next() will write
2269  * the page's contents to @buffer, so they will have to be copied to the
2270  * right location on the next call to suspend_write_next() and it is done
2271  * with the help of copy_last_highmem_page().  For this purpose, if
2272  * @buffer is returned, @last_highmem_page is set to the page to which
2273  * the data will have to be copied from @buffer.
2274  */
2275 static void *get_highmem_page_buffer(struct page *page,
2276                                      struct chain_allocator *ca)
2277 {
2278         struct highmem_pbe *pbe;
2279         void *kaddr;
2280
2281         if (swsusp_page_is_forbidden(page) && swsusp_page_is_free(page)) {
2282                 /*
2283                  * We have allocated the "original" page frame and we can
2284                  * use it directly to store the loaded page.
2285                  */
2286                 last_highmem_page = page;
2287                 return buffer;
2288         }
2289         /*
2290          * The "original" page frame has not been allocated and we have to
2291          * use a "safe" page frame to store the loaded page.
2292          */
2293         pbe = chain_alloc(ca, sizeof(struct highmem_pbe));
2294         if (!pbe) {
2295                 swsusp_free();
2296                 return ERR_PTR(-ENOMEM);
2297         }
2298         pbe->orig_page = page;
2299         if (safe_highmem_pages > 0) {
2300                 struct page *tmp;
2301
2302                 /* Copy of the page will be stored in high memory */
2303                 kaddr = buffer;
2304                 tmp = pfn_to_page(memory_bm_next_pfn(safe_highmem_bm));
2305                 safe_highmem_pages--;
2306                 last_highmem_page = tmp;
2307                 pbe->copy_page = tmp;
2308         } else {
2309                 /* Copy of the page will be stored in normal memory */
2310                 kaddr = safe_pages_list;
2311                 safe_pages_list = safe_pages_list->next;
2312                 pbe->copy_page = virt_to_page(kaddr);
2313         }
2314         pbe->next = highmem_pblist;
2315         highmem_pblist = pbe;
2316         return kaddr;
2317 }
2318
2319 /**
2320  * copy_last_highmem_page - Copy most the most recent highmem image page.
2321  *
2322  * Copy the contents of a highmem image from @buffer, where the caller of
2323  * snapshot_write_next() has stored them, to the right location represented by
2324  * @last_highmem_page .
2325  */
2326 static void copy_last_highmem_page(void)
2327 {
2328         if (last_highmem_page) {
2329                 void *dst;
2330
2331                 dst = kmap_atomic(last_highmem_page);
2332                 copy_page(dst, buffer);
2333                 kunmap_atomic(dst);
2334                 last_highmem_page = NULL;
2335         }
2336 }
2337
2338 static inline int last_highmem_page_copied(void)
2339 {
2340         return !last_highmem_page;
2341 }
2342
2343 static inline void free_highmem_data(void)
2344 {
2345         if (safe_highmem_bm)
2346                 memory_bm_free(safe_highmem_bm, PG_UNSAFE_CLEAR);
2347
2348         if (buffer)
2349                 free_image_page(buffer, PG_UNSAFE_CLEAR);
2350 }
2351 #else
2352 static unsigned int count_highmem_image_pages(struct memory_bitmap *bm) { return 0; }
2353
2354 static inline int prepare_highmem_image(struct memory_bitmap *bm,
2355                                         unsigned int *nr_highmem_p) { return 0; }
2356
2357 static inline void *get_highmem_page_buffer(struct page *page,
2358                                             struct chain_allocator *ca)
2359 {
2360         return ERR_PTR(-EINVAL);
2361 }
2362
2363 static inline void copy_last_highmem_page(void) {}
2364 static inline int last_highmem_page_copied(void) { return 1; }
2365 static inline void free_highmem_data(void) {}
2366 #endif /* CONFIG_HIGHMEM */
2367
2368 #define PBES_PER_LINKED_PAGE    (LINKED_PAGE_DATA_SIZE / sizeof(struct pbe))
2369
2370 /**
2371  * prepare_image - Make room for loading hibernation image.
2372  * @new_bm: Unitialized memory bitmap structure.
2373  * @bm: Memory bitmap with unsafe pages marked.
2374  *
2375  * Use @bm to mark the pages that will be overwritten in the process of
2376  * restoring the system memory state from the suspend image ("unsafe" pages)
2377  * and allocate memory for the image.
2378  *
2379  * The idea is to allocate a new memory bitmap first and then allocate
2380  * as many pages as needed for image data, but without specifying what those
2381  * pages will be used for just yet.  Instead, we mark them all as allocated and
2382  * create a lists of "safe" pages to be used later.  On systems with high
2383  * memory a list of "safe" highmem pages is created too.
2384  */
2385 static int prepare_image(struct memory_bitmap *new_bm, struct memory_bitmap *bm)
2386 {
2387         unsigned int nr_pages, nr_highmem;
2388         struct linked_page *lp;
2389         int error;
2390
2391         /* If there is no highmem, the buffer will not be necessary */
2392         free_image_page(buffer, PG_UNSAFE_CLEAR);
2393         buffer = NULL;
2394
2395         nr_highmem = count_highmem_image_pages(bm);
2396         mark_unsafe_pages(bm);
2397
2398         error = memory_bm_create(new_bm, GFP_ATOMIC, PG_SAFE);
2399         if (error)
2400                 goto Free;
2401
2402         duplicate_memory_bitmap(new_bm, bm);
2403         memory_bm_free(bm, PG_UNSAFE_KEEP);
2404         if (nr_highmem > 0) {
2405                 error = prepare_highmem_image(bm, &nr_highmem);
2406                 if (error)
2407                         goto Free;
2408         }
2409         /*
2410          * Reserve some safe pages for potential later use.
2411          *
2412          * NOTE: This way we make sure there will be enough safe pages for the
2413          * chain_alloc() in get_buffer().  It is a bit wasteful, but
2414          * nr_copy_pages cannot be greater than 50% of the memory anyway.
2415          *
2416          * nr_copy_pages cannot be less than allocated_unsafe_pages too.
2417          */
2418         nr_pages = nr_copy_pages - nr_highmem - allocated_unsafe_pages;
2419         nr_pages = DIV_ROUND_UP(nr_pages, PBES_PER_LINKED_PAGE);
2420         while (nr_pages > 0) {
2421                 lp = get_image_page(GFP_ATOMIC, PG_SAFE);
2422                 if (!lp) {
2423                         error = -ENOMEM;
2424                         goto Free;
2425                 }
2426                 lp->next = safe_pages_list;
2427                 safe_pages_list = lp;
2428                 nr_pages--;
2429         }
2430         /* Preallocate memory for the image */
2431         nr_pages = nr_copy_pages - nr_highmem - allocated_unsafe_pages;
2432         while (nr_pages > 0) {
2433                 lp = (struct linked_page *)get_zeroed_page(GFP_ATOMIC);
2434                 if (!lp) {
2435                         error = -ENOMEM;
2436                         goto Free;
2437                 }
2438                 if (!swsusp_page_is_free(virt_to_page(lp))) {
2439                         /* The page is "safe", add it to the list */
2440                         lp->next = safe_pages_list;
2441                         safe_pages_list = lp;
2442                 }
2443                 /* Mark the page as allocated */
2444                 swsusp_set_page_forbidden(virt_to_page(lp));
2445                 swsusp_set_page_free(virt_to_page(lp));
2446                 nr_pages--;
2447         }
2448         return 0;
2449
2450  Free:
2451         swsusp_free();
2452         return error;
2453 }
2454
2455 /**
2456  * get_buffer - Get the address to store the next image data page.
2457  *
2458  * Get the address that snapshot_write_next() should return to its caller to
2459  * write to.
2460  */
2461 static void *get_buffer(struct memory_bitmap *bm, struct chain_allocator *ca)
2462 {
2463         struct pbe *pbe;
2464         struct page *page;
2465         unsigned long pfn = memory_bm_next_pfn(bm);
2466
2467         if (pfn == BM_END_OF_MAP)
2468                 return ERR_PTR(-EFAULT);
2469
2470         page = pfn_to_page(pfn);
2471         if (PageHighMem(page))
2472                 return get_highmem_page_buffer(page, ca);
2473
2474         if (swsusp_page_is_forbidden(page) && swsusp_page_is_free(page))
2475                 /*
2476                  * We have allocated the "original" page frame and we can
2477                  * use it directly to store the loaded page.
2478                  */
2479                 return page_address(page);
2480
2481         /*
2482          * The "original" page frame has not been allocated and we have to
2483          * use a "safe" page frame to store the loaded page.
2484          */
2485         pbe = chain_alloc(ca, sizeof(struct pbe));
2486         if (!pbe) {
2487                 swsusp_free();
2488                 return ERR_PTR(-ENOMEM);
2489         }
2490         pbe->orig_address = page_address(page);
2491         pbe->address = safe_pages_list;
2492         safe_pages_list = safe_pages_list->next;
2493         pbe->next = restore_pblist;
2494         restore_pblist = pbe;
2495         return pbe->address;
2496 }
2497
2498 /**
2499  * snapshot_write_next - Get the address to store the next image page.
2500  * @handle: Snapshot handle structure to guide the writing.
2501  *
2502  * On the first call, @handle should point to a zeroed snapshot_handle
2503  * structure.  The structure gets populated then and a pointer to it should be
2504  * passed to this function every next time.
2505  *
2506  * On success, the function returns a positive number.  Then, the caller
2507  * is allowed to write up to the returned number of bytes to the memory
2508  * location computed by the data_of() macro.
2509  *
2510  * The function returns 0 to indicate the "end of file" condition.  Negative
2511  * numbers are returned on errors, in which cases the structure pointed to by
2512  * @handle is not updated and should not be used any more.
2513  */
2514 int snapshot_write_next(struct snapshot_handle *handle)
2515 {
2516         static struct chain_allocator ca;
2517         int error = 0;
2518
2519         /* Check if we have already loaded the entire image */
2520         if (handle->cur > 1 && handle->cur > nr_meta_pages + nr_copy_pages)
2521                 return 0;
2522
2523         handle->sync_read = 1;
2524
2525         if (!handle->cur) {
2526                 if (!buffer)
2527                         /* This makes the buffer be freed by swsusp_free() */
2528                         buffer = get_image_page(GFP_ATOMIC, PG_ANY);
2529
2530                 if (!buffer)
2531                         return -ENOMEM;
2532
2533                 handle->buffer = buffer;
2534         } else if (handle->cur == 1) {
2535                 error = load_header(buffer);
2536                 if (error)
2537                         return error;
2538
2539                 safe_pages_list = NULL;
2540
2541                 error = memory_bm_create(&copy_bm, GFP_ATOMIC, PG_ANY);
2542                 if (error)
2543                         return error;
2544
2545                 /* Allocate buffer for page keys. */
2546                 error = page_key_alloc(nr_copy_pages);
2547                 if (error)
2548                         return error;
2549
2550         } else if (handle->cur <= nr_meta_pages + 1) {
2551                 error = unpack_orig_pfns(buffer, &copy_bm);
2552                 if (error)
2553                         return error;
2554
2555                 if (handle->cur == nr_meta_pages + 1) {
2556                         error = prepare_image(&orig_bm, &copy_bm);
2557                         if (error)
2558                                 return error;
2559
2560                         chain_init(&ca, GFP_ATOMIC, PG_SAFE);
2561                         memory_bm_position_reset(&orig_bm);
2562                         restore_pblist = NULL;
2563                         handle->buffer = get_buffer(&orig_bm, &ca);
2564                         handle->sync_read = 0;
2565                         if (IS_ERR(handle->buffer))
2566                                 return PTR_ERR(handle->buffer);
2567                 }
2568         } else {
2569                 copy_last_highmem_page();
2570                 /* Restore page key for data page (s390 only). */
2571                 page_key_write(handle->buffer);
2572                 handle->buffer = get_buffer(&orig_bm, &ca);
2573                 if (IS_ERR(handle->buffer))
2574                         return PTR_ERR(handle->buffer);
2575                 if (handle->buffer != buffer)
2576                         handle->sync_read = 0;
2577         }
2578         handle->cur++;
2579         return PAGE_SIZE;
2580 }
2581
2582 /**
2583  * snapshot_write_finalize - Complete the loading of a hibernation image.
2584  *
2585  * Must be called after the last call to snapshot_write_next() in case the last
2586  * page in the image happens to be a highmem page and its contents should be
2587  * stored in highmem.  Additionally, it recycles bitmap memory that's not
2588  * necessary any more.
2589  */
2590 void snapshot_write_finalize(struct snapshot_handle *handle)
2591 {
2592         copy_last_highmem_page();
2593         /* Restore page key for data page (s390 only). */
2594         page_key_write(handle->buffer);
2595         page_key_free();
2596         /* Do that only if we have loaded the image entirely */
2597         if (handle->cur > 1 && handle->cur > nr_meta_pages + nr_copy_pages) {
2598                 memory_bm_recycle(&orig_bm);
2599                 free_highmem_data();
2600         }
2601 }
2602
2603 int snapshot_image_loaded(struct snapshot_handle *handle)
2604 {
2605         return !(!nr_copy_pages || !last_highmem_page_copied() ||
2606                         handle->cur <= nr_meta_pages + nr_copy_pages);
2607 }
2608
2609 #ifdef CONFIG_HIGHMEM
2610 /* Assumes that @buf is ready and points to a "safe" page */
2611 static inline void swap_two_pages_data(struct page *p1, struct page *p2,
2612                                        void *buf)
2613 {
2614         void *kaddr1, *kaddr2;
2615
2616         kaddr1 = kmap_atomic(p1);
2617         kaddr2 = kmap_atomic(p2);
2618         copy_page(buf, kaddr1);
2619         copy_page(kaddr1, kaddr2);
2620         copy_page(kaddr2, buf);
2621         kunmap_atomic(kaddr2);
2622         kunmap_atomic(kaddr1);
2623 }
2624
2625 /**
2626  * restore_highmem - Put highmem image pages into their original locations.
2627  *
2628  * For each highmem page that was in use before hibernation and is included in
2629  * the image, and also has been allocated by the "restore" kernel, swap its
2630  * current contents with the previous (ie. "before hibernation") ones.
2631  *
2632  * If the restore eventually fails, we can call this function once again and
2633  * restore the highmem state as seen by the restore kernel.
2634  */
2635 int restore_highmem(void)
2636 {
2637         struct highmem_pbe *pbe = highmem_pblist;
2638         void *buf;
2639
2640         if (!pbe)
2641                 return 0;
2642
2643         buf = get_image_page(GFP_ATOMIC, PG_SAFE);
2644         if (!buf)
2645                 return -ENOMEM;
2646
2647         while (pbe) {
2648                 swap_two_pages_data(pbe->copy_page, pbe->orig_page, buf);
2649                 pbe = pbe->next;
2650         }
2651         free_image_page(buf, PG_UNSAFE_CLEAR);
2652         return 0;
2653 }
2654 #endif /* CONFIG_HIGHMEM */