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