Merge branch 'for-linus' of git://www.jni.nu/cris
[linux-2.6] / 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@suse.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
29 #include <asm/uaccess.h>
30 #include <asm/mmu_context.h>
31 #include <asm/pgtable.h>
32 #include <asm/tlbflush.h>
33 #include <asm/io.h>
34
35 #include "power.h"
36
37 static int swsusp_page_is_free(struct page *);
38 static void swsusp_set_page_forbidden(struct page *);
39 static void swsusp_unset_page_forbidden(struct page *);
40
41 /* List of PBEs needed for restoring the pages that were allocated before
42  * the suspend and included in the suspend image, but have also been
43  * allocated by the "resume" kernel, so their contents cannot be written
44  * directly to their "original" page frames.
45  */
46 struct pbe *restore_pblist;
47
48 /* Pointer to an auxiliary buffer (1 page) */
49 static void *buffer;
50
51 /**
52  *      @safe_needed - on resume, for storing the PBE list and the image,
53  *      we can only use memory pages that do not conflict with the pages
54  *      used before suspend.  The unsafe pages have PageNosaveFree set
55  *      and we count them using unsafe_pages.
56  *
57  *      Each allocated image page is marked as PageNosave and PageNosaveFree
58  *      so that swsusp_free() can release it.
59  */
60
61 #define PG_ANY          0
62 #define PG_SAFE         1
63 #define PG_UNSAFE_CLEAR 1
64 #define PG_UNSAFE_KEEP  0
65
66 static unsigned int allocated_unsafe_pages;
67
68 static void *get_image_page(gfp_t gfp_mask, int safe_needed)
69 {
70         void *res;
71
72         res = (void *)get_zeroed_page(gfp_mask);
73         if (safe_needed)
74                 while (res && swsusp_page_is_free(virt_to_page(res))) {
75                         /* The page is unsafe, mark it for swsusp_free() */
76                         swsusp_set_page_forbidden(virt_to_page(res));
77                         allocated_unsafe_pages++;
78                         res = (void *)get_zeroed_page(gfp_mask);
79                 }
80         if (res) {
81                 swsusp_set_page_forbidden(virt_to_page(res));
82                 swsusp_set_page_free(virt_to_page(res));
83         }
84         return res;
85 }
86
87 unsigned long get_safe_page(gfp_t gfp_mask)
88 {
89         return (unsigned long)get_image_page(gfp_mask, PG_SAFE);
90 }
91
92 static struct page *alloc_image_page(gfp_t gfp_mask)
93 {
94         struct page *page;
95
96         page = alloc_page(gfp_mask);
97         if (page) {
98                 swsusp_set_page_forbidden(page);
99                 swsusp_set_page_free(page);
100         }
101         return page;
102 }
103
104 /**
105  *      free_image_page - free page represented by @addr, allocated with
106  *      get_image_page (page flags set by it must be cleared)
107  */
108
109 static inline void free_image_page(void *addr, int clear_nosave_free)
110 {
111         struct page *page;
112
113         BUG_ON(!virt_addr_valid(addr));
114
115         page = virt_to_page(addr);
116
117         swsusp_unset_page_forbidden(page);
118         if (clear_nosave_free)
119                 swsusp_unset_page_free(page);
120
121         __free_page(page);
122 }
123
124 /* struct linked_page is used to build chains of pages */
125
126 #define LINKED_PAGE_DATA_SIZE   (PAGE_SIZE - sizeof(void *))
127
128 struct linked_page {
129         struct linked_page *next;
130         char data[LINKED_PAGE_DATA_SIZE];
131 } __attribute__((packed));
132
133 static inline void
134 free_list_of_pages(struct linked_page *list, int clear_page_nosave)
135 {
136         while (list) {
137                 struct linked_page *lp = list->next;
138
139                 free_image_page(list, clear_page_nosave);
140                 list = lp;
141         }
142 }
143
144 /**
145   *     struct chain_allocator is used for allocating small objects out of
146   *     a linked list of pages called 'the chain'.
147   *
148   *     The chain grows each time when there is no room for a new object in
149   *     the current page.  The allocated objects cannot be freed individually.
150   *     It is only possible to free them all at once, by freeing the entire
151   *     chain.
152   *
153   *     NOTE: The chain allocator may be inefficient if the allocated objects
154   *     are not much smaller than PAGE_SIZE.
155   */
156
157 struct chain_allocator {
158         struct linked_page *chain;      /* the chain */
159         unsigned int used_space;        /* total size of objects allocated out
160                                          * of the current page
161                                          */
162         gfp_t gfp_mask;         /* mask for allocating pages */
163         int safe_needed;        /* if set, only "safe" pages are allocated */
164 };
165
166 static void
167 chain_init(struct chain_allocator *ca, gfp_t gfp_mask, int safe_needed)
168 {
169         ca->chain = NULL;
170         ca->used_space = LINKED_PAGE_DATA_SIZE;
171         ca->gfp_mask = gfp_mask;
172         ca->safe_needed = safe_needed;
173 }
174
175 static void *chain_alloc(struct chain_allocator *ca, unsigned int size)
176 {
177         void *ret;
178
179         if (LINKED_PAGE_DATA_SIZE - ca->used_space < size) {
180                 struct linked_page *lp;
181
182                 lp = get_image_page(ca->gfp_mask, ca->safe_needed);
183                 if (!lp)
184                         return NULL;
185
186                 lp->next = ca->chain;
187                 ca->chain = lp;
188                 ca->used_space = 0;
189         }
190         ret = ca->chain->data + ca->used_space;
191         ca->used_space += size;
192         return ret;
193 }
194
195 static void chain_free(struct chain_allocator *ca, int clear_page_nosave)
196 {
197         free_list_of_pages(ca->chain, clear_page_nosave);
198         memset(ca, 0, sizeof(struct chain_allocator));
199 }
200
201 /**
202  *      Data types related to memory bitmaps.
203  *
204  *      Memory bitmap is a structure consiting of many linked lists of
205  *      objects.  The main list's elements are of type struct zone_bitmap
206  *      and each of them corresonds to one zone.  For each zone bitmap
207  *      object there is a list of objects of type struct bm_block that
208  *      represent each blocks of bit chunks in which information is
209  *      stored.
210  *
211  *      struct memory_bitmap contains a pointer to the main list of zone
212  *      bitmap objects, a struct bm_position used for browsing the bitmap,
213  *      and a pointer to the list of pages used for allocating all of the
214  *      zone bitmap objects and bitmap block objects.
215  *
216  *      NOTE: It has to be possible to lay out the bitmap in memory
217  *      using only allocations of order 0.  Additionally, the bitmap is
218  *      designed to work with arbitrary number of zones (this is over the
219  *      top for now, but let's avoid making unnecessary assumptions ;-).
220  *
221  *      struct zone_bitmap contains a pointer to a list of bitmap block
222  *      objects and a pointer to the bitmap block object that has been
223  *      most recently used for setting bits.  Additionally, it contains the
224  *      pfns that correspond to the start and end of the represented zone.
225  *
226  *      struct bm_block contains a pointer to the memory page in which
227  *      information is stored (in the form of a block of bit chunks
228  *      of type unsigned long each).  It also contains the pfns that
229  *      correspond to the start and end of the represented memory area and
230  *      the number of bit chunks in the block.
231  */
232
233 #define BM_END_OF_MAP   (~0UL)
234
235 #define BM_CHUNKS_PER_BLOCK     (PAGE_SIZE / sizeof(long))
236 #define BM_BITS_PER_CHUNK       (sizeof(long) << 3)
237 #define BM_BITS_PER_BLOCK       (PAGE_SIZE << 3)
238
239 struct bm_block {
240         struct bm_block *next;          /* next element of the list */
241         unsigned long start_pfn;        /* pfn represented by the first bit */
242         unsigned long end_pfn;  /* pfn represented by the last bit plus 1 */
243         unsigned int size;      /* number of bit chunks */
244         unsigned long *data;    /* chunks of bits representing pages */
245 };
246
247 struct zone_bitmap {
248         struct zone_bitmap *next;       /* next element of the list */
249         unsigned long start_pfn;        /* minimal pfn in this zone */
250         unsigned long end_pfn;          /* maximal pfn in this zone plus 1 */
251         struct bm_block *bm_blocks;     /* list of bitmap blocks */
252         struct bm_block *cur_block;     /* recently used bitmap block */
253 };
254
255 /* strcut bm_position is used for browsing memory bitmaps */
256
257 struct bm_position {
258         struct zone_bitmap *zone_bm;
259         struct bm_block *block;
260         int chunk;
261         int bit;
262 };
263
264 struct memory_bitmap {
265         struct zone_bitmap *zone_bm_list;       /* list of zone bitmaps */
266         struct linked_page *p_list;     /* list of pages used to store zone
267                                          * bitmap objects and bitmap block
268                                          * objects
269                                          */
270         struct bm_position cur; /* most recently used bit position */
271 };
272
273 /* Functions that operate on memory bitmaps */
274
275 static inline void memory_bm_reset_chunk(struct memory_bitmap *bm)
276 {
277         bm->cur.chunk = 0;
278         bm->cur.bit = -1;
279 }
280
281 static void memory_bm_position_reset(struct memory_bitmap *bm)
282 {
283         struct zone_bitmap *zone_bm;
284
285         zone_bm = bm->zone_bm_list;
286         bm->cur.zone_bm = zone_bm;
287         bm->cur.block = zone_bm->bm_blocks;
288         memory_bm_reset_chunk(bm);
289 }
290
291 static void memory_bm_free(struct memory_bitmap *bm, int clear_nosave_free);
292
293 /**
294  *      create_bm_block_list - create a list of block bitmap objects
295  */
296
297 static inline struct bm_block *
298 create_bm_block_list(unsigned int nr_blocks, struct chain_allocator *ca)
299 {
300         struct bm_block *bblist = NULL;
301
302         while (nr_blocks-- > 0) {
303                 struct bm_block *bb;
304
305                 bb = chain_alloc(ca, sizeof(struct bm_block));
306                 if (!bb)
307                         return NULL;
308
309                 bb->next = bblist;
310                 bblist = bb;
311         }
312         return bblist;
313 }
314
315 /**
316  *      create_zone_bm_list - create a list of zone bitmap objects
317  */
318
319 static inline struct zone_bitmap *
320 create_zone_bm_list(unsigned int nr_zones, struct chain_allocator *ca)
321 {
322         struct zone_bitmap *zbmlist = NULL;
323
324         while (nr_zones-- > 0) {
325                 struct zone_bitmap *zbm;
326
327                 zbm = chain_alloc(ca, sizeof(struct zone_bitmap));
328                 if (!zbm)
329                         return NULL;
330
331                 zbm->next = zbmlist;
332                 zbmlist = zbm;
333         }
334         return zbmlist;
335 }
336
337 /**
338   *     memory_bm_create - allocate memory for a memory bitmap
339   */
340
341 static int
342 memory_bm_create(struct memory_bitmap *bm, gfp_t gfp_mask, int safe_needed)
343 {
344         struct chain_allocator ca;
345         struct zone *zone;
346         struct zone_bitmap *zone_bm;
347         struct bm_block *bb;
348         unsigned int nr;
349
350         chain_init(&ca, gfp_mask, safe_needed);
351
352         /* Compute the number of zones */
353         nr = 0;
354         for_each_zone(zone)
355                 if (populated_zone(zone))
356                         nr++;
357
358         /* Allocate the list of zones bitmap objects */
359         zone_bm = create_zone_bm_list(nr, &ca);
360         bm->zone_bm_list = zone_bm;
361         if (!zone_bm) {
362                 chain_free(&ca, PG_UNSAFE_CLEAR);
363                 return -ENOMEM;
364         }
365
366         /* Initialize the zone bitmap objects */
367         for_each_zone(zone) {
368                 unsigned long pfn;
369
370                 if (!populated_zone(zone))
371                         continue;
372
373                 zone_bm->start_pfn = zone->zone_start_pfn;
374                 zone_bm->end_pfn = zone->zone_start_pfn + zone->spanned_pages;
375                 /* Allocate the list of bitmap block objects */
376                 nr = DIV_ROUND_UP(zone->spanned_pages, BM_BITS_PER_BLOCK);
377                 bb = create_bm_block_list(nr, &ca);
378                 zone_bm->bm_blocks = bb;
379                 zone_bm->cur_block = bb;
380                 if (!bb)
381                         goto Free;
382
383                 nr = zone->spanned_pages;
384                 pfn = zone->zone_start_pfn;
385                 /* Initialize the bitmap block objects */
386                 while (bb) {
387                         unsigned long *ptr;
388
389                         ptr = get_image_page(gfp_mask, safe_needed);
390                         bb->data = ptr;
391                         if (!ptr)
392                                 goto Free;
393
394                         bb->start_pfn = pfn;
395                         if (nr >= BM_BITS_PER_BLOCK) {
396                                 pfn += BM_BITS_PER_BLOCK;
397                                 bb->size = BM_CHUNKS_PER_BLOCK;
398                                 nr -= BM_BITS_PER_BLOCK;
399                         } else {
400                                 /* This is executed only once in the loop */
401                                 pfn += nr;
402                                 bb->size = DIV_ROUND_UP(nr, BM_BITS_PER_CHUNK);
403                         }
404                         bb->end_pfn = pfn;
405                         bb = bb->next;
406                 }
407                 zone_bm = zone_bm->next;
408         }
409         bm->p_list = ca.chain;
410         memory_bm_position_reset(bm);
411         return 0;
412
413  Free:
414         bm->p_list = ca.chain;
415         memory_bm_free(bm, PG_UNSAFE_CLEAR);
416         return -ENOMEM;
417 }
418
419 /**
420   *     memory_bm_free - free memory occupied by the memory bitmap @bm
421   */
422
423 static void memory_bm_free(struct memory_bitmap *bm, int clear_nosave_free)
424 {
425         struct zone_bitmap *zone_bm;
426
427         /* Free the list of bit blocks for each zone_bitmap object */
428         zone_bm = bm->zone_bm_list;
429         while (zone_bm) {
430                 struct bm_block *bb;
431
432                 bb = zone_bm->bm_blocks;
433                 while (bb) {
434                         if (bb->data)
435                                 free_image_page(bb->data, clear_nosave_free);
436                         bb = bb->next;
437                 }
438                 zone_bm = zone_bm->next;
439         }
440         free_list_of_pages(bm->p_list, clear_nosave_free);
441         bm->zone_bm_list = NULL;
442 }
443
444 /**
445  *      memory_bm_find_bit - find the bit in the bitmap @bm that corresponds
446  *      to given pfn.  The cur_zone_bm member of @bm and the cur_block member
447  *      of @bm->cur_zone_bm are updated.
448  */
449
450 static int memory_bm_find_bit(struct memory_bitmap *bm, unsigned long pfn,
451                                 void **addr, unsigned int *bit_nr)
452 {
453         struct zone_bitmap *zone_bm;
454         struct bm_block *bb;
455
456         /* Check if the pfn is from the current zone */
457         zone_bm = bm->cur.zone_bm;
458         if (pfn < zone_bm->start_pfn || pfn >= zone_bm->end_pfn) {
459                 zone_bm = bm->zone_bm_list;
460                 /* We don't assume that the zones are sorted by pfns */
461                 while (pfn < zone_bm->start_pfn || pfn >= zone_bm->end_pfn) {
462                         zone_bm = zone_bm->next;
463
464                         if (!zone_bm)
465                                 return -EFAULT;
466                 }
467                 bm->cur.zone_bm = zone_bm;
468         }
469         /* Check if the pfn corresponds to the current bitmap block */
470         bb = zone_bm->cur_block;
471         if (pfn < bb->start_pfn)
472                 bb = zone_bm->bm_blocks;
473
474         while (pfn >= bb->end_pfn) {
475                 bb = bb->next;
476
477                 BUG_ON(!bb);
478         }
479         zone_bm->cur_block = bb;
480         pfn -= bb->start_pfn;
481         *bit_nr = pfn % BM_BITS_PER_CHUNK;
482         *addr = bb->data + pfn / BM_BITS_PER_CHUNK;
483         return 0;
484 }
485
486 static void memory_bm_set_bit(struct memory_bitmap *bm, unsigned long pfn)
487 {
488         void *addr;
489         unsigned int bit;
490         int error;
491
492         error = memory_bm_find_bit(bm, pfn, &addr, &bit);
493         BUG_ON(error);
494         set_bit(bit, addr);
495 }
496
497 static int mem_bm_set_bit_check(struct memory_bitmap *bm, unsigned long pfn)
498 {
499         void *addr;
500         unsigned int bit;
501         int error;
502
503         error = memory_bm_find_bit(bm, pfn, &addr, &bit);
504         if (!error)
505                 set_bit(bit, addr);
506         return error;
507 }
508
509 static void memory_bm_clear_bit(struct memory_bitmap *bm, unsigned long pfn)
510 {
511         void *addr;
512         unsigned int bit;
513         int error;
514
515         error = memory_bm_find_bit(bm, pfn, &addr, &bit);
516         BUG_ON(error);
517         clear_bit(bit, addr);
518 }
519
520 static int memory_bm_test_bit(struct memory_bitmap *bm, unsigned long pfn)
521 {
522         void *addr;
523         unsigned int bit;
524         int error;
525
526         error = memory_bm_find_bit(bm, pfn, &addr, &bit);
527         BUG_ON(error);
528         return test_bit(bit, addr);
529 }
530
531 /* Two auxiliary functions for memory_bm_next_pfn */
532
533 /* Find the first set bit in the given chunk, if there is one */
534
535 static inline int next_bit_in_chunk(int bit, unsigned long *chunk_p)
536 {
537         bit++;
538         while (bit < BM_BITS_PER_CHUNK) {
539                 if (test_bit(bit, chunk_p))
540                         return bit;
541
542                 bit++;
543         }
544         return -1;
545 }
546
547 /* Find a chunk containing some bits set in given block of bits */
548
549 static inline int next_chunk_in_block(int n, struct bm_block *bb)
550 {
551         n++;
552         while (n < bb->size) {
553                 if (bb->data[n])
554                         return n;
555
556                 n++;
557         }
558         return -1;
559 }
560
561 /**
562  *      memory_bm_next_pfn - find the pfn that corresponds to the next set bit
563  *      in the bitmap @bm.  If the pfn cannot be found, BM_END_OF_MAP is
564  *      returned.
565  *
566  *      It is required to run memory_bm_position_reset() before the first call to
567  *      this function.
568  */
569
570 static unsigned long memory_bm_next_pfn(struct memory_bitmap *bm)
571 {
572         struct zone_bitmap *zone_bm;
573         struct bm_block *bb;
574         int chunk;
575         int bit;
576
577         do {
578                 bb = bm->cur.block;
579                 do {
580                         chunk = bm->cur.chunk;
581                         bit = bm->cur.bit;
582                         do {
583                                 bit = next_bit_in_chunk(bit, bb->data + chunk);
584                                 if (bit >= 0)
585                                         goto Return_pfn;
586
587                                 chunk = next_chunk_in_block(chunk, bb);
588                                 bit = -1;
589                         } while (chunk >= 0);
590                         bb = bb->next;
591                         bm->cur.block = bb;
592                         memory_bm_reset_chunk(bm);
593                 } while (bb);
594                 zone_bm = bm->cur.zone_bm->next;
595                 if (zone_bm) {
596                         bm->cur.zone_bm = zone_bm;
597                         bm->cur.block = zone_bm->bm_blocks;
598                         memory_bm_reset_chunk(bm);
599                 }
600         } while (zone_bm);
601         memory_bm_position_reset(bm);
602         return BM_END_OF_MAP;
603
604  Return_pfn:
605         bm->cur.chunk = chunk;
606         bm->cur.bit = bit;
607         return bb->start_pfn + chunk * BM_BITS_PER_CHUNK + bit;
608 }
609
610 /**
611  *      This structure represents a range of page frames the contents of which
612  *      should not be saved during the suspend.
613  */
614
615 struct nosave_region {
616         struct list_head list;
617         unsigned long start_pfn;
618         unsigned long end_pfn;
619 };
620
621 static LIST_HEAD(nosave_regions);
622
623 /**
624  *      register_nosave_region - register a range of page frames the contents
625  *      of which should not be saved during the suspend (to be used in the early
626  *      initialization code)
627  */
628
629 void __init
630 __register_nosave_region(unsigned long start_pfn, unsigned long end_pfn,
631                          int use_kmalloc)
632 {
633         struct nosave_region *region;
634
635         if (start_pfn >= end_pfn)
636                 return;
637
638         if (!list_empty(&nosave_regions)) {
639                 /* Try to extend the previous region (they should be sorted) */
640                 region = list_entry(nosave_regions.prev,
641                                         struct nosave_region, list);
642                 if (region->end_pfn == start_pfn) {
643                         region->end_pfn = end_pfn;
644                         goto Report;
645                 }
646         }
647         if (use_kmalloc) {
648                 /* during init, this shouldn't fail */
649                 region = kmalloc(sizeof(struct nosave_region), GFP_KERNEL);
650                 BUG_ON(!region);
651         } else
652                 /* This allocation cannot fail */
653                 region = alloc_bootmem_low(sizeof(struct nosave_region));
654         region->start_pfn = start_pfn;
655         region->end_pfn = end_pfn;
656         list_add_tail(&region->list, &nosave_regions);
657  Report:
658         printk(KERN_INFO "PM: Registered nosave memory: %016lx - %016lx\n",
659                 start_pfn << PAGE_SHIFT, end_pfn << PAGE_SHIFT);
660 }
661
662 /*
663  * Set bits in this map correspond to the page frames the contents of which
664  * should not be saved during the suspend.
665  */
666 static struct memory_bitmap *forbidden_pages_map;
667
668 /* Set bits in this map correspond to free page frames. */
669 static struct memory_bitmap *free_pages_map;
670
671 /*
672  * Each page frame allocated for creating the image is marked by setting the
673  * corresponding bits in forbidden_pages_map and free_pages_map simultaneously
674  */
675
676 void swsusp_set_page_free(struct page *page)
677 {
678         if (free_pages_map)
679                 memory_bm_set_bit(free_pages_map, page_to_pfn(page));
680 }
681
682 static int swsusp_page_is_free(struct page *page)
683 {
684         return free_pages_map ?
685                 memory_bm_test_bit(free_pages_map, page_to_pfn(page)) : 0;
686 }
687
688 void swsusp_unset_page_free(struct page *page)
689 {
690         if (free_pages_map)
691                 memory_bm_clear_bit(free_pages_map, page_to_pfn(page));
692 }
693
694 static void swsusp_set_page_forbidden(struct page *page)
695 {
696         if (forbidden_pages_map)
697                 memory_bm_set_bit(forbidden_pages_map, page_to_pfn(page));
698 }
699
700 int swsusp_page_is_forbidden(struct page *page)
701 {
702         return forbidden_pages_map ?
703                 memory_bm_test_bit(forbidden_pages_map, page_to_pfn(page)) : 0;
704 }
705
706 static void swsusp_unset_page_forbidden(struct page *page)
707 {
708         if (forbidden_pages_map)
709                 memory_bm_clear_bit(forbidden_pages_map, page_to_pfn(page));
710 }
711
712 /**
713  *      mark_nosave_pages - set bits corresponding to the page frames the
714  *      contents of which should not be saved in a given bitmap.
715  */
716
717 static void mark_nosave_pages(struct memory_bitmap *bm)
718 {
719         struct nosave_region *region;
720
721         if (list_empty(&nosave_regions))
722                 return;
723
724         list_for_each_entry(region, &nosave_regions, list) {
725                 unsigned long pfn;
726
727                 pr_debug("PM: Marking nosave pages: %016lx - %016lx\n",
728                                 region->start_pfn << PAGE_SHIFT,
729                                 region->end_pfn << PAGE_SHIFT);
730
731                 for (pfn = region->start_pfn; pfn < region->end_pfn; pfn++)
732                         if (pfn_valid(pfn)) {
733                                 /*
734                                  * It is safe to ignore the result of
735                                  * mem_bm_set_bit_check() here, since we won't
736                                  * touch the PFNs for which the error is
737                                  * returned anyway.
738                                  */
739                                 mem_bm_set_bit_check(bm, pfn);
740                         }
741         }
742 }
743
744 /**
745  *      create_basic_memory_bitmaps - create bitmaps needed for marking page
746  *      frames that should not be saved and free page frames.  The pointers
747  *      forbidden_pages_map and free_pages_map are only modified if everything
748  *      goes well, because we don't want the bits to be used before both bitmaps
749  *      are set up.
750  */
751
752 int create_basic_memory_bitmaps(void)
753 {
754         struct memory_bitmap *bm1, *bm2;
755         int error = 0;
756
757         BUG_ON(forbidden_pages_map || free_pages_map);
758
759         bm1 = kzalloc(sizeof(struct memory_bitmap), GFP_KERNEL);
760         if (!bm1)
761                 return -ENOMEM;
762
763         error = memory_bm_create(bm1, GFP_KERNEL, PG_ANY);
764         if (error)
765                 goto Free_first_object;
766
767         bm2 = kzalloc(sizeof(struct memory_bitmap), GFP_KERNEL);
768         if (!bm2)
769                 goto Free_first_bitmap;
770
771         error = memory_bm_create(bm2, GFP_KERNEL, PG_ANY);
772         if (error)
773                 goto Free_second_object;
774
775         forbidden_pages_map = bm1;
776         free_pages_map = bm2;
777         mark_nosave_pages(forbidden_pages_map);
778
779         pr_debug("PM: Basic memory bitmaps created\n");
780
781         return 0;
782
783  Free_second_object:
784         kfree(bm2);
785  Free_first_bitmap:
786         memory_bm_free(bm1, PG_UNSAFE_CLEAR);
787  Free_first_object:
788         kfree(bm1);
789         return -ENOMEM;
790 }
791
792 /**
793  *      free_basic_memory_bitmaps - free memory bitmaps allocated by
794  *      create_basic_memory_bitmaps().  The auxiliary pointers are necessary
795  *      so that the bitmaps themselves are not referred to while they are being
796  *      freed.
797  */
798
799 void free_basic_memory_bitmaps(void)
800 {
801         struct memory_bitmap *bm1, *bm2;
802
803         BUG_ON(!(forbidden_pages_map && free_pages_map));
804
805         bm1 = forbidden_pages_map;
806         bm2 = free_pages_map;
807         forbidden_pages_map = NULL;
808         free_pages_map = NULL;
809         memory_bm_free(bm1, PG_UNSAFE_CLEAR);
810         kfree(bm1);
811         memory_bm_free(bm2, PG_UNSAFE_CLEAR);
812         kfree(bm2);
813
814         pr_debug("PM: Basic memory bitmaps freed\n");
815 }
816
817 /**
818  *      snapshot_additional_pages - estimate the number of additional pages
819  *      be needed for setting up the suspend image data structures for given
820  *      zone (usually the returned value is greater than the exact number)
821  */
822
823 unsigned int snapshot_additional_pages(struct zone *zone)
824 {
825         unsigned int res;
826
827         res = DIV_ROUND_UP(zone->spanned_pages, BM_BITS_PER_BLOCK);
828         res += DIV_ROUND_UP(res * sizeof(struct bm_block), PAGE_SIZE);
829         return 2 * res;
830 }
831
832 #ifdef CONFIG_HIGHMEM
833 /**
834  *      count_free_highmem_pages - compute the total number of free highmem
835  *      pages, system-wide.
836  */
837
838 static unsigned int count_free_highmem_pages(void)
839 {
840         struct zone *zone;
841         unsigned int cnt = 0;
842
843         for_each_zone(zone)
844                 if (populated_zone(zone) && is_highmem(zone))
845                         cnt += zone_page_state(zone, NR_FREE_PAGES);
846
847         return cnt;
848 }
849
850 /**
851  *      saveable_highmem_page - Determine whether a highmem page should be
852  *      included in the suspend image.
853  *
854  *      We should save the page if it isn't Nosave or NosaveFree, or Reserved,
855  *      and it isn't a part of a free chunk of pages.
856  */
857
858 static struct page *saveable_highmem_page(unsigned long pfn)
859 {
860         struct page *page;
861
862         if (!pfn_valid(pfn))
863                 return NULL;
864
865         page = pfn_to_page(pfn);
866
867         BUG_ON(!PageHighMem(page));
868
869         if (swsusp_page_is_forbidden(page) ||  swsusp_page_is_free(page) ||
870             PageReserved(page))
871                 return NULL;
872
873         return page;
874 }
875
876 /**
877  *      count_highmem_pages - compute the total number of saveable highmem
878  *      pages.
879  */
880
881 unsigned int count_highmem_pages(void)
882 {
883         struct zone *zone;
884         unsigned int n = 0;
885
886         for_each_zone(zone) {
887                 unsigned long pfn, max_zone_pfn;
888
889                 if (!is_highmem(zone))
890                         continue;
891
892                 mark_free_pages(zone);
893                 max_zone_pfn = zone->zone_start_pfn + zone->spanned_pages;
894                 for (pfn = zone->zone_start_pfn; pfn < max_zone_pfn; pfn++)
895                         if (saveable_highmem_page(pfn))
896                                 n++;
897         }
898         return n;
899 }
900 #else
901 static inline void *saveable_highmem_page(unsigned long pfn) { return NULL; }
902 #endif /* CONFIG_HIGHMEM */
903
904 /**
905  *      saveable_page - Determine whether a non-highmem page should be included
906  *      in the suspend image.
907  *
908  *      We should save the page if it isn't Nosave, and is not in the range
909  *      of pages statically defined as 'unsaveable', and it isn't a part of
910  *      a free chunk of pages.
911  */
912
913 static struct page *saveable_page(unsigned long pfn)
914 {
915         struct page *page;
916
917         if (!pfn_valid(pfn))
918                 return NULL;
919
920         page = pfn_to_page(pfn);
921
922         BUG_ON(PageHighMem(page));
923
924         if (swsusp_page_is_forbidden(page) || swsusp_page_is_free(page))
925                 return NULL;
926
927         if (PageReserved(page)
928             && (!kernel_page_present(page) || pfn_is_nosave(pfn)))
929                 return NULL;
930
931         return page;
932 }
933
934 /**
935  *      count_data_pages - compute the total number of saveable non-highmem
936  *      pages.
937  */
938
939 unsigned int count_data_pages(void)
940 {
941         struct zone *zone;
942         unsigned long pfn, max_zone_pfn;
943         unsigned int n = 0;
944
945         for_each_zone(zone) {
946                 if (is_highmem(zone))
947                         continue;
948
949                 mark_free_pages(zone);
950                 max_zone_pfn = zone->zone_start_pfn + zone->spanned_pages;
951                 for (pfn = zone->zone_start_pfn; pfn < max_zone_pfn; pfn++)
952                         if(saveable_page(pfn))
953                                 n++;
954         }
955         return n;
956 }
957
958 /* This is needed, because copy_page and memcpy are not usable for copying
959  * task structs.
960  */
961 static inline void do_copy_page(long *dst, long *src)
962 {
963         int n;
964
965         for (n = PAGE_SIZE / sizeof(long); n; n--)
966                 *dst++ = *src++;
967 }
968
969
970 /**
971  *      safe_copy_page - check if the page we are going to copy is marked as
972  *              present in the kernel page tables (this always is the case if
973  *              CONFIG_DEBUG_PAGEALLOC is not set and in that case
974  *              kernel_page_present() always returns 'true').
975  */
976 static void safe_copy_page(void *dst, struct page *s_page)
977 {
978         if (kernel_page_present(s_page)) {
979                 do_copy_page(dst, page_address(s_page));
980         } else {
981                 kernel_map_pages(s_page, 1, 1);
982                 do_copy_page(dst, page_address(s_page));
983                 kernel_map_pages(s_page, 1, 0);
984         }
985 }
986
987
988 #ifdef CONFIG_HIGHMEM
989 static inline struct page *
990 page_is_saveable(struct zone *zone, unsigned long pfn)
991 {
992         return is_highmem(zone) ?
993                         saveable_highmem_page(pfn) : saveable_page(pfn);
994 }
995
996 static void copy_data_page(unsigned long dst_pfn, unsigned long src_pfn)
997 {
998         struct page *s_page, *d_page;
999         void *src, *dst;
1000
1001         s_page = pfn_to_page(src_pfn);
1002         d_page = pfn_to_page(dst_pfn);
1003         if (PageHighMem(s_page)) {
1004                 src = kmap_atomic(s_page, KM_USER0);
1005                 dst = kmap_atomic(d_page, KM_USER1);
1006                 do_copy_page(dst, src);
1007                 kunmap_atomic(src, KM_USER0);
1008                 kunmap_atomic(dst, KM_USER1);
1009         } else {
1010                 if (PageHighMem(d_page)) {
1011                         /* Page pointed to by src may contain some kernel
1012                          * data modified by kmap_atomic()
1013                          */
1014                         safe_copy_page(buffer, s_page);
1015                         dst = kmap_atomic(pfn_to_page(dst_pfn), KM_USER0);
1016                         memcpy(dst, buffer, PAGE_SIZE);
1017                         kunmap_atomic(dst, KM_USER0);
1018                 } else {
1019                         safe_copy_page(page_address(d_page), s_page);
1020                 }
1021         }
1022 }
1023 #else
1024 #define page_is_saveable(zone, pfn)     saveable_page(pfn)
1025
1026 static inline void copy_data_page(unsigned long dst_pfn, unsigned long src_pfn)
1027 {
1028         safe_copy_page(page_address(pfn_to_page(dst_pfn)),
1029                                 pfn_to_page(src_pfn));
1030 }
1031 #endif /* CONFIG_HIGHMEM */
1032
1033 static void
1034 copy_data_pages(struct memory_bitmap *copy_bm, struct memory_bitmap *orig_bm)
1035 {
1036         struct zone *zone;
1037         unsigned long pfn;
1038
1039         for_each_zone(zone) {
1040                 unsigned long max_zone_pfn;
1041
1042                 mark_free_pages(zone);
1043                 max_zone_pfn = zone->zone_start_pfn + zone->spanned_pages;
1044                 for (pfn = zone->zone_start_pfn; pfn < max_zone_pfn; pfn++)
1045                         if (page_is_saveable(zone, pfn))
1046                                 memory_bm_set_bit(orig_bm, pfn);
1047         }
1048         memory_bm_position_reset(orig_bm);
1049         memory_bm_position_reset(copy_bm);
1050         for(;;) {
1051                 pfn = memory_bm_next_pfn(orig_bm);
1052                 if (unlikely(pfn == BM_END_OF_MAP))
1053                         break;
1054                 copy_data_page(memory_bm_next_pfn(copy_bm), pfn);
1055         }
1056 }
1057
1058 /* Total number of image pages */
1059 static unsigned int nr_copy_pages;
1060 /* Number of pages needed for saving the original pfns of the image pages */
1061 static unsigned int nr_meta_pages;
1062
1063 /**
1064  *      swsusp_free - free pages allocated for the suspend.
1065  *
1066  *      Suspend pages are alocated before the atomic copy is made, so we
1067  *      need to release them after the resume.
1068  */
1069
1070 void swsusp_free(void)
1071 {
1072         struct zone *zone;
1073         unsigned long pfn, max_zone_pfn;
1074
1075         for_each_zone(zone) {
1076                 max_zone_pfn = zone->zone_start_pfn + zone->spanned_pages;
1077                 for (pfn = zone->zone_start_pfn; pfn < max_zone_pfn; pfn++)
1078                         if (pfn_valid(pfn)) {
1079                                 struct page *page = pfn_to_page(pfn);
1080
1081                                 if (swsusp_page_is_forbidden(page) &&
1082                                     swsusp_page_is_free(page)) {
1083                                         swsusp_unset_page_forbidden(page);
1084                                         swsusp_unset_page_free(page);
1085                                         __free_page(page);
1086                                 }
1087                         }
1088         }
1089         nr_copy_pages = 0;
1090         nr_meta_pages = 0;
1091         restore_pblist = NULL;
1092         buffer = NULL;
1093 }
1094
1095 #ifdef CONFIG_HIGHMEM
1096 /**
1097   *     count_pages_for_highmem - compute the number of non-highmem pages
1098   *     that will be necessary for creating copies of highmem pages.
1099   */
1100
1101 static unsigned int count_pages_for_highmem(unsigned int nr_highmem)
1102 {
1103         unsigned int free_highmem = count_free_highmem_pages();
1104
1105         if (free_highmem >= nr_highmem)
1106                 nr_highmem = 0;
1107         else
1108                 nr_highmem -= free_highmem;
1109
1110         return nr_highmem;
1111 }
1112 #else
1113 static unsigned int
1114 count_pages_for_highmem(unsigned int nr_highmem) { return 0; }
1115 #endif /* CONFIG_HIGHMEM */
1116
1117 /**
1118  *      enough_free_mem - Make sure we have enough free memory for the
1119  *      snapshot image.
1120  */
1121
1122 static int enough_free_mem(unsigned int nr_pages, unsigned int nr_highmem)
1123 {
1124         struct zone *zone;
1125         unsigned int free = 0, meta = 0;
1126
1127         for_each_zone(zone) {
1128                 meta += snapshot_additional_pages(zone);
1129                 if (!is_highmem(zone))
1130                         free += zone_page_state(zone, NR_FREE_PAGES);
1131         }
1132
1133         nr_pages += count_pages_for_highmem(nr_highmem);
1134         pr_debug("PM: Normal pages needed: %u + %u + %u, available pages: %u\n",
1135                 nr_pages, PAGES_FOR_IO, meta, free);
1136
1137         return free > nr_pages + PAGES_FOR_IO + meta;
1138 }
1139
1140 #ifdef CONFIG_HIGHMEM
1141 /**
1142  *      get_highmem_buffer - if there are some highmem pages in the suspend
1143  *      image, we may need the buffer to copy them and/or load their data.
1144  */
1145
1146 static inline int get_highmem_buffer(int safe_needed)
1147 {
1148         buffer = get_image_page(GFP_ATOMIC | __GFP_COLD, safe_needed);
1149         return buffer ? 0 : -ENOMEM;
1150 }
1151
1152 /**
1153  *      alloc_highmem_image_pages - allocate some highmem pages for the image.
1154  *      Try to allocate as many pages as needed, but if the number of free
1155  *      highmem pages is lesser than that, allocate them all.
1156  */
1157
1158 static inline unsigned int
1159 alloc_highmem_image_pages(struct memory_bitmap *bm, unsigned int nr_highmem)
1160 {
1161         unsigned int to_alloc = count_free_highmem_pages();
1162
1163         if (to_alloc > nr_highmem)
1164                 to_alloc = nr_highmem;
1165
1166         nr_highmem -= to_alloc;
1167         while (to_alloc-- > 0) {
1168                 struct page *page;
1169
1170                 page = alloc_image_page(__GFP_HIGHMEM);
1171                 memory_bm_set_bit(bm, page_to_pfn(page));
1172         }
1173         return nr_highmem;
1174 }
1175 #else
1176 static inline int get_highmem_buffer(int safe_needed) { return 0; }
1177
1178 static inline unsigned int
1179 alloc_highmem_image_pages(struct memory_bitmap *bm, unsigned int n) { return 0; }
1180 #endif /* CONFIG_HIGHMEM */
1181
1182 /**
1183  *      swsusp_alloc - allocate memory for the suspend image
1184  *
1185  *      We first try to allocate as many highmem pages as there are
1186  *      saveable highmem pages in the system.  If that fails, we allocate
1187  *      non-highmem pages for the copies of the remaining highmem ones.
1188  *
1189  *      In this approach it is likely that the copies of highmem pages will
1190  *      also be located in the high memory, because of the way in which
1191  *      copy_data_pages() works.
1192  */
1193
1194 static int
1195 swsusp_alloc(struct memory_bitmap *orig_bm, struct memory_bitmap *copy_bm,
1196                 unsigned int nr_pages, unsigned int nr_highmem)
1197 {
1198         int error;
1199
1200         error = memory_bm_create(orig_bm, GFP_ATOMIC | __GFP_COLD, PG_ANY);
1201         if (error)
1202                 goto Free;
1203
1204         error = memory_bm_create(copy_bm, GFP_ATOMIC | __GFP_COLD, PG_ANY);
1205         if (error)
1206                 goto Free;
1207
1208         if (nr_highmem > 0) {
1209                 error = get_highmem_buffer(PG_ANY);
1210                 if (error)
1211                         goto Free;
1212
1213                 nr_pages += alloc_highmem_image_pages(copy_bm, nr_highmem);
1214         }
1215         while (nr_pages-- > 0) {
1216                 struct page *page = alloc_image_page(GFP_ATOMIC | __GFP_COLD);
1217
1218                 if (!page)
1219                         goto Free;
1220
1221                 memory_bm_set_bit(copy_bm, page_to_pfn(page));
1222         }
1223         return 0;
1224
1225  Free:
1226         swsusp_free();
1227         return -ENOMEM;
1228 }
1229
1230 /* Memory bitmap used for marking saveable pages (during suspend) or the
1231  * suspend image pages (during resume)
1232  */
1233 static struct memory_bitmap orig_bm;
1234 /* Memory bitmap used on suspend for marking allocated pages that will contain
1235  * the copies of saveable pages.  During resume it is initially used for
1236  * marking the suspend image pages, but then its set bits are duplicated in
1237  * @orig_bm and it is released.  Next, on systems with high memory, it may be
1238  * used for marking "safe" highmem pages, but it has to be reinitialized for
1239  * this purpose.
1240  */
1241 static struct memory_bitmap copy_bm;
1242
1243 asmlinkage int swsusp_save(void)
1244 {
1245         unsigned int nr_pages, nr_highmem;
1246
1247         printk(KERN_INFO "PM: Creating hibernation image: \n");
1248
1249         drain_local_pages(NULL);
1250         nr_pages = count_data_pages();
1251         nr_highmem = count_highmem_pages();
1252         printk(KERN_INFO "PM: Need to copy %u pages\n", nr_pages + nr_highmem);
1253
1254         if (!enough_free_mem(nr_pages, nr_highmem)) {
1255                 printk(KERN_ERR "PM: Not enough free memory\n");
1256                 return -ENOMEM;
1257         }
1258
1259         if (swsusp_alloc(&orig_bm, &copy_bm, nr_pages, nr_highmem)) {
1260                 printk(KERN_ERR "PM: Memory allocation failed\n");
1261                 return -ENOMEM;
1262         }
1263
1264         /* During allocating of suspend pagedir, new cold pages may appear.
1265          * Kill them.
1266          */
1267         drain_local_pages(NULL);
1268         copy_data_pages(&copy_bm, &orig_bm);
1269
1270         /*
1271          * End of critical section. From now on, we can write to memory,
1272          * but we should not touch disk. This specially means we must _not_
1273          * touch swap space! Except we must write out our image of course.
1274          */
1275
1276         nr_pages += nr_highmem;
1277         nr_copy_pages = nr_pages;
1278         nr_meta_pages = DIV_ROUND_UP(nr_pages * sizeof(long), PAGE_SIZE);
1279
1280         printk(KERN_INFO "PM: Hibernation image created (%d pages copied)\n",
1281                 nr_pages);
1282
1283         return 0;
1284 }
1285
1286 #ifndef CONFIG_ARCH_HIBERNATION_HEADER
1287 static int init_header_complete(struct swsusp_info *info)
1288 {
1289         memcpy(&info->uts, init_utsname(), sizeof(struct new_utsname));
1290         info->version_code = LINUX_VERSION_CODE;
1291         return 0;
1292 }
1293
1294 static char *check_image_kernel(struct swsusp_info *info)
1295 {
1296         if (info->version_code != LINUX_VERSION_CODE)
1297                 return "kernel version";
1298         if (strcmp(info->uts.sysname,init_utsname()->sysname))
1299                 return "system type";
1300         if (strcmp(info->uts.release,init_utsname()->release))
1301                 return "kernel release";
1302         if (strcmp(info->uts.version,init_utsname()->version))
1303                 return "version";
1304         if (strcmp(info->uts.machine,init_utsname()->machine))
1305                 return "machine";
1306         return NULL;
1307 }
1308 #endif /* CONFIG_ARCH_HIBERNATION_HEADER */
1309
1310 unsigned long snapshot_get_image_size(void)
1311 {
1312         return nr_copy_pages + nr_meta_pages + 1;
1313 }
1314
1315 static int init_header(struct swsusp_info *info)
1316 {
1317         memset(info, 0, sizeof(struct swsusp_info));
1318         info->num_physpages = num_physpages;
1319         info->image_pages = nr_copy_pages;
1320         info->pages = snapshot_get_image_size();
1321         info->size = info->pages;
1322         info->size <<= PAGE_SHIFT;
1323         return init_header_complete(info);
1324 }
1325
1326 /**
1327  *      pack_pfns - pfns corresponding to the set bits found in the bitmap @bm
1328  *      are stored in the array @buf[] (1 page at a time)
1329  */
1330
1331 static inline void
1332 pack_pfns(unsigned long *buf, struct memory_bitmap *bm)
1333 {
1334         int j;
1335
1336         for (j = 0; j < PAGE_SIZE / sizeof(long); j++) {
1337                 buf[j] = memory_bm_next_pfn(bm);
1338                 if (unlikely(buf[j] == BM_END_OF_MAP))
1339                         break;
1340         }
1341 }
1342
1343 /**
1344  *      snapshot_read_next - used for reading the system memory snapshot.
1345  *
1346  *      On the first call to it @handle should point to a zeroed
1347  *      snapshot_handle structure.  The structure gets updated and a pointer
1348  *      to it should be passed to this function every next time.
1349  *
1350  *      The @count parameter should contain the number of bytes the caller
1351  *      wants to read from the snapshot.  It must not be zero.
1352  *
1353  *      On success the function returns a positive number.  Then, the caller
1354  *      is allowed to read up to the returned number of bytes from the memory
1355  *      location computed by the data_of() macro.  The number returned
1356  *      may be smaller than @count, but this only happens if the read would
1357  *      cross a page boundary otherwise.
1358  *
1359  *      The function returns 0 to indicate the end of data stream condition,
1360  *      and a negative number is returned on error.  In such cases the
1361  *      structure pointed to by @handle is not updated and should not be used
1362  *      any more.
1363  */
1364
1365 int snapshot_read_next(struct snapshot_handle *handle, size_t count)
1366 {
1367         if (handle->cur > nr_meta_pages + nr_copy_pages)
1368                 return 0;
1369
1370         if (!buffer) {
1371                 /* This makes the buffer be freed by swsusp_free() */
1372                 buffer = get_image_page(GFP_ATOMIC, PG_ANY);
1373                 if (!buffer)
1374                         return -ENOMEM;
1375         }
1376         if (!handle->offset) {
1377                 int error;
1378
1379                 error = init_header((struct swsusp_info *)buffer);
1380                 if (error)
1381                         return error;
1382                 handle->buffer = buffer;
1383                 memory_bm_position_reset(&orig_bm);
1384                 memory_bm_position_reset(&copy_bm);
1385         }
1386         if (handle->prev < handle->cur) {
1387                 if (handle->cur <= nr_meta_pages) {
1388                         memset(buffer, 0, PAGE_SIZE);
1389                         pack_pfns(buffer, &orig_bm);
1390                 } else {
1391                         struct page *page;
1392
1393                         page = pfn_to_page(memory_bm_next_pfn(&copy_bm));
1394                         if (PageHighMem(page)) {
1395                                 /* Highmem pages are copied to the buffer,
1396                                  * because we can't return with a kmapped
1397                                  * highmem page (we may not be called again).
1398                                  */
1399                                 void *kaddr;
1400
1401                                 kaddr = kmap_atomic(page, KM_USER0);
1402                                 memcpy(buffer, kaddr, PAGE_SIZE);
1403                                 kunmap_atomic(kaddr, KM_USER0);
1404                                 handle->buffer = buffer;
1405                         } else {
1406                                 handle->buffer = page_address(page);
1407                         }
1408                 }
1409                 handle->prev = handle->cur;
1410         }
1411         handle->buf_offset = handle->cur_offset;
1412         if (handle->cur_offset + count >= PAGE_SIZE) {
1413                 count = PAGE_SIZE - handle->cur_offset;
1414                 handle->cur_offset = 0;
1415                 handle->cur++;
1416         } else {
1417                 handle->cur_offset += count;
1418         }
1419         handle->offset += count;
1420         return count;
1421 }
1422
1423 /**
1424  *      mark_unsafe_pages - mark the pages that cannot be used for storing
1425  *      the image during resume, because they conflict with the pages that
1426  *      had been used before suspend
1427  */
1428
1429 static int mark_unsafe_pages(struct memory_bitmap *bm)
1430 {
1431         struct zone *zone;
1432         unsigned long pfn, max_zone_pfn;
1433
1434         /* Clear page flags */
1435         for_each_zone(zone) {
1436                 max_zone_pfn = zone->zone_start_pfn + zone->spanned_pages;
1437                 for (pfn = zone->zone_start_pfn; pfn < max_zone_pfn; pfn++)
1438                         if (pfn_valid(pfn))
1439                                 swsusp_unset_page_free(pfn_to_page(pfn));
1440         }
1441
1442         /* Mark pages that correspond to the "original" pfns as "unsafe" */
1443         memory_bm_position_reset(bm);
1444         do {
1445                 pfn = memory_bm_next_pfn(bm);
1446                 if (likely(pfn != BM_END_OF_MAP)) {
1447                         if (likely(pfn_valid(pfn)))
1448                                 swsusp_set_page_free(pfn_to_page(pfn));
1449                         else
1450                                 return -EFAULT;
1451                 }
1452         } while (pfn != BM_END_OF_MAP);
1453
1454         allocated_unsafe_pages = 0;
1455
1456         return 0;
1457 }
1458
1459 static void
1460 duplicate_memory_bitmap(struct memory_bitmap *dst, struct memory_bitmap *src)
1461 {
1462         unsigned long pfn;
1463
1464         memory_bm_position_reset(src);
1465         pfn = memory_bm_next_pfn(src);
1466         while (pfn != BM_END_OF_MAP) {
1467                 memory_bm_set_bit(dst, pfn);
1468                 pfn = memory_bm_next_pfn(src);
1469         }
1470 }
1471
1472 static int check_header(struct swsusp_info *info)
1473 {
1474         char *reason;
1475
1476         reason = check_image_kernel(info);
1477         if (!reason && info->num_physpages != num_physpages)
1478                 reason = "memory size";
1479         if (reason) {
1480                 printk(KERN_ERR "PM: Image mismatch: %s\n", reason);
1481                 return -EPERM;
1482         }
1483         return 0;
1484 }
1485
1486 /**
1487  *      load header - check the image header and copy data from it
1488  */
1489
1490 static int
1491 load_header(struct swsusp_info *info)
1492 {
1493         int error;
1494
1495         restore_pblist = NULL;
1496         error = check_header(info);
1497         if (!error) {
1498                 nr_copy_pages = info->image_pages;
1499                 nr_meta_pages = info->pages - info->image_pages - 1;
1500         }
1501         return error;
1502 }
1503
1504 /**
1505  *      unpack_orig_pfns - for each element of @buf[] (1 page at a time) set
1506  *      the corresponding bit in the memory bitmap @bm
1507  */
1508
1509 static inline void
1510 unpack_orig_pfns(unsigned long *buf, struct memory_bitmap *bm)
1511 {
1512         int j;
1513
1514         for (j = 0; j < PAGE_SIZE / sizeof(long); j++) {
1515                 if (unlikely(buf[j] == BM_END_OF_MAP))
1516                         break;
1517
1518                 memory_bm_set_bit(bm, buf[j]);
1519         }
1520 }
1521
1522 /* List of "safe" pages that may be used to store data loaded from the suspend
1523  * image
1524  */
1525 static struct linked_page *safe_pages_list;
1526
1527 #ifdef CONFIG_HIGHMEM
1528 /* struct highmem_pbe is used for creating the list of highmem pages that
1529  * should be restored atomically during the resume from disk, because the page
1530  * frames they have occupied before the suspend are in use.
1531  */
1532 struct highmem_pbe {
1533         struct page *copy_page; /* data is here now */
1534         struct page *orig_page; /* data was here before the suspend */
1535         struct highmem_pbe *next;
1536 };
1537
1538 /* List of highmem PBEs needed for restoring the highmem pages that were
1539  * allocated before the suspend and included in the suspend image, but have
1540  * also been allocated by the "resume" kernel, so their contents cannot be
1541  * written directly to their "original" page frames.
1542  */
1543 static struct highmem_pbe *highmem_pblist;
1544
1545 /**
1546  *      count_highmem_image_pages - compute the number of highmem pages in the
1547  *      suspend image.  The bits in the memory bitmap @bm that correspond to the
1548  *      image pages are assumed to be set.
1549  */
1550
1551 static unsigned int count_highmem_image_pages(struct memory_bitmap *bm)
1552 {
1553         unsigned long pfn;
1554         unsigned int cnt = 0;
1555
1556         memory_bm_position_reset(bm);
1557         pfn = memory_bm_next_pfn(bm);
1558         while (pfn != BM_END_OF_MAP) {
1559                 if (PageHighMem(pfn_to_page(pfn)))
1560                         cnt++;
1561
1562                 pfn = memory_bm_next_pfn(bm);
1563         }
1564         return cnt;
1565 }
1566
1567 /**
1568  *      prepare_highmem_image - try to allocate as many highmem pages as
1569  *      there are highmem image pages (@nr_highmem_p points to the variable
1570  *      containing the number of highmem image pages).  The pages that are
1571  *      "safe" (ie. will not be overwritten when the suspend image is
1572  *      restored) have the corresponding bits set in @bm (it must be
1573  *      unitialized).
1574  *
1575  *      NOTE: This function should not be called if there are no highmem
1576  *      image pages.
1577  */
1578
1579 static unsigned int safe_highmem_pages;
1580
1581 static struct memory_bitmap *safe_highmem_bm;
1582
1583 static int
1584 prepare_highmem_image(struct memory_bitmap *bm, unsigned int *nr_highmem_p)
1585 {
1586         unsigned int to_alloc;
1587
1588         if (memory_bm_create(bm, GFP_ATOMIC, PG_SAFE))
1589                 return -ENOMEM;
1590
1591         if (get_highmem_buffer(PG_SAFE))
1592                 return -ENOMEM;
1593
1594         to_alloc = count_free_highmem_pages();
1595         if (to_alloc > *nr_highmem_p)
1596                 to_alloc = *nr_highmem_p;
1597         else
1598                 *nr_highmem_p = to_alloc;
1599
1600         safe_highmem_pages = 0;
1601         while (to_alloc-- > 0) {
1602                 struct page *page;
1603
1604                 page = alloc_page(__GFP_HIGHMEM);
1605                 if (!swsusp_page_is_free(page)) {
1606                         /* The page is "safe", set its bit the bitmap */
1607                         memory_bm_set_bit(bm, page_to_pfn(page));
1608                         safe_highmem_pages++;
1609                 }
1610                 /* Mark the page as allocated */
1611                 swsusp_set_page_forbidden(page);
1612                 swsusp_set_page_free(page);
1613         }
1614         memory_bm_position_reset(bm);
1615         safe_highmem_bm = bm;
1616         return 0;
1617 }
1618
1619 /**
1620  *      get_highmem_page_buffer - for given highmem image page find the buffer
1621  *      that suspend_write_next() should set for its caller to write to.
1622  *
1623  *      If the page is to be saved to its "original" page frame or a copy of
1624  *      the page is to be made in the highmem, @buffer is returned.  Otherwise,
1625  *      the copy of the page is to be made in normal memory, so the address of
1626  *      the copy is returned.
1627  *
1628  *      If @buffer is returned, the caller of suspend_write_next() will write
1629  *      the page's contents to @buffer, so they will have to be copied to the
1630  *      right location on the next call to suspend_write_next() and it is done
1631  *      with the help of copy_last_highmem_page().  For this purpose, if
1632  *      @buffer is returned, @last_highmem page is set to the page to which
1633  *      the data will have to be copied from @buffer.
1634  */
1635
1636 static struct page *last_highmem_page;
1637
1638 static void *
1639 get_highmem_page_buffer(struct page *page, struct chain_allocator *ca)
1640 {
1641         struct highmem_pbe *pbe;
1642         void *kaddr;
1643
1644         if (swsusp_page_is_forbidden(page) && swsusp_page_is_free(page)) {
1645                 /* We have allocated the "original" page frame and we can
1646                  * use it directly to store the loaded page.
1647                  */
1648                 last_highmem_page = page;
1649                 return buffer;
1650         }
1651         /* The "original" page frame has not been allocated and we have to
1652          * use a "safe" page frame to store the loaded page.
1653          */
1654         pbe = chain_alloc(ca, sizeof(struct highmem_pbe));
1655         if (!pbe) {
1656                 swsusp_free();
1657                 return NULL;
1658         }
1659         pbe->orig_page = page;
1660         if (safe_highmem_pages > 0) {
1661                 struct page *tmp;
1662
1663                 /* Copy of the page will be stored in high memory */
1664                 kaddr = buffer;
1665                 tmp = pfn_to_page(memory_bm_next_pfn(safe_highmem_bm));
1666                 safe_highmem_pages--;
1667                 last_highmem_page = tmp;
1668                 pbe->copy_page = tmp;
1669         } else {
1670                 /* Copy of the page will be stored in normal memory */
1671                 kaddr = safe_pages_list;
1672                 safe_pages_list = safe_pages_list->next;
1673                 pbe->copy_page = virt_to_page(kaddr);
1674         }
1675         pbe->next = highmem_pblist;
1676         highmem_pblist = pbe;
1677         return kaddr;
1678 }
1679
1680 /**
1681  *      copy_last_highmem_page - copy the contents of a highmem image from
1682  *      @buffer, where the caller of snapshot_write_next() has place them,
1683  *      to the right location represented by @last_highmem_page .
1684  */
1685
1686 static void copy_last_highmem_page(void)
1687 {
1688         if (last_highmem_page) {
1689                 void *dst;
1690
1691                 dst = kmap_atomic(last_highmem_page, KM_USER0);
1692                 memcpy(dst, buffer, PAGE_SIZE);
1693                 kunmap_atomic(dst, KM_USER0);
1694                 last_highmem_page = NULL;
1695         }
1696 }
1697
1698 static inline int last_highmem_page_copied(void)
1699 {
1700         return !last_highmem_page;
1701 }
1702
1703 static inline void free_highmem_data(void)
1704 {
1705         if (safe_highmem_bm)
1706                 memory_bm_free(safe_highmem_bm, PG_UNSAFE_CLEAR);
1707
1708         if (buffer)
1709                 free_image_page(buffer, PG_UNSAFE_CLEAR);
1710 }
1711 #else
1712 static inline int get_safe_write_buffer(void) { return 0; }
1713
1714 static unsigned int
1715 count_highmem_image_pages(struct memory_bitmap *bm) { return 0; }
1716
1717 static inline int
1718 prepare_highmem_image(struct memory_bitmap *bm, unsigned int *nr_highmem_p)
1719 {
1720         return 0;
1721 }
1722
1723 static inline void *
1724 get_highmem_page_buffer(struct page *page, struct chain_allocator *ca)
1725 {
1726         return NULL;
1727 }
1728
1729 static inline void copy_last_highmem_page(void) {}
1730 static inline int last_highmem_page_copied(void) { return 1; }
1731 static inline void free_highmem_data(void) {}
1732 #endif /* CONFIG_HIGHMEM */
1733
1734 /**
1735  *      prepare_image - use the memory bitmap @bm to mark the pages that will
1736  *      be overwritten in the process of restoring the system memory state
1737  *      from the suspend image ("unsafe" pages) and allocate memory for the
1738  *      image.
1739  *
1740  *      The idea is to allocate a new memory bitmap first and then allocate
1741  *      as many pages as needed for the image data, but not to assign these
1742  *      pages to specific tasks initially.  Instead, we just mark them as
1743  *      allocated and create a lists of "safe" pages that will be used
1744  *      later.  On systems with high memory a list of "safe" highmem pages is
1745  *      also created.
1746  */
1747
1748 #define PBES_PER_LINKED_PAGE    (LINKED_PAGE_DATA_SIZE / sizeof(struct pbe))
1749
1750 static int
1751 prepare_image(struct memory_bitmap *new_bm, struct memory_bitmap *bm)
1752 {
1753         unsigned int nr_pages, nr_highmem;
1754         struct linked_page *sp_list, *lp;
1755         int error;
1756
1757         /* If there is no highmem, the buffer will not be necessary */
1758         free_image_page(buffer, PG_UNSAFE_CLEAR);
1759         buffer = NULL;
1760
1761         nr_highmem = count_highmem_image_pages(bm);
1762         error = mark_unsafe_pages(bm);
1763         if (error)
1764                 goto Free;
1765
1766         error = memory_bm_create(new_bm, GFP_ATOMIC, PG_SAFE);
1767         if (error)
1768                 goto Free;
1769
1770         duplicate_memory_bitmap(new_bm, bm);
1771         memory_bm_free(bm, PG_UNSAFE_KEEP);
1772         if (nr_highmem > 0) {
1773                 error = prepare_highmem_image(bm, &nr_highmem);
1774                 if (error)
1775                         goto Free;
1776         }
1777         /* Reserve some safe pages for potential later use.
1778          *
1779          * NOTE: This way we make sure there will be enough safe pages for the
1780          * chain_alloc() in get_buffer().  It is a bit wasteful, but
1781          * nr_copy_pages cannot be greater than 50% of the memory anyway.
1782          */
1783         sp_list = NULL;
1784         /* nr_copy_pages cannot be lesser than allocated_unsafe_pages */
1785         nr_pages = nr_copy_pages - nr_highmem - allocated_unsafe_pages;
1786         nr_pages = DIV_ROUND_UP(nr_pages, PBES_PER_LINKED_PAGE);
1787         while (nr_pages > 0) {
1788                 lp = get_image_page(GFP_ATOMIC, PG_SAFE);
1789                 if (!lp) {
1790                         error = -ENOMEM;
1791                         goto Free;
1792                 }
1793                 lp->next = sp_list;
1794                 sp_list = lp;
1795                 nr_pages--;
1796         }
1797         /* Preallocate memory for the image */
1798         safe_pages_list = NULL;
1799         nr_pages = nr_copy_pages - nr_highmem - allocated_unsafe_pages;
1800         while (nr_pages > 0) {
1801                 lp = (struct linked_page *)get_zeroed_page(GFP_ATOMIC);
1802                 if (!lp) {
1803                         error = -ENOMEM;
1804                         goto Free;
1805                 }
1806                 if (!swsusp_page_is_free(virt_to_page(lp))) {
1807                         /* The page is "safe", add it to the list */
1808                         lp->next = safe_pages_list;
1809                         safe_pages_list = lp;
1810                 }
1811                 /* Mark the page as allocated */
1812                 swsusp_set_page_forbidden(virt_to_page(lp));
1813                 swsusp_set_page_free(virt_to_page(lp));
1814                 nr_pages--;
1815         }
1816         /* Free the reserved safe pages so that chain_alloc() can use them */
1817         while (sp_list) {
1818                 lp = sp_list->next;
1819                 free_image_page(sp_list, PG_UNSAFE_CLEAR);
1820                 sp_list = lp;
1821         }
1822         return 0;
1823
1824  Free:
1825         swsusp_free();
1826         return error;
1827 }
1828
1829 /**
1830  *      get_buffer - compute the address that snapshot_write_next() should
1831  *      set for its caller to write to.
1832  */
1833
1834 static void *get_buffer(struct memory_bitmap *bm, struct chain_allocator *ca)
1835 {
1836         struct pbe *pbe;
1837         struct page *page = pfn_to_page(memory_bm_next_pfn(bm));
1838
1839         if (PageHighMem(page))
1840                 return get_highmem_page_buffer(page, ca);
1841
1842         if (swsusp_page_is_forbidden(page) && swsusp_page_is_free(page))
1843                 /* We have allocated the "original" page frame and we can
1844                  * use it directly to store the loaded page.
1845                  */
1846                 return page_address(page);
1847
1848         /* The "original" page frame has not been allocated and we have to
1849          * use a "safe" page frame to store the loaded page.
1850          */
1851         pbe = chain_alloc(ca, sizeof(struct pbe));
1852         if (!pbe) {
1853                 swsusp_free();
1854                 return NULL;
1855         }
1856         pbe->orig_address = page_address(page);
1857         pbe->address = safe_pages_list;
1858         safe_pages_list = safe_pages_list->next;
1859         pbe->next = restore_pblist;
1860         restore_pblist = pbe;
1861         return pbe->address;
1862 }
1863
1864 /**
1865  *      snapshot_write_next - used for writing the system memory snapshot.
1866  *
1867  *      On the first call to it @handle should point to a zeroed
1868  *      snapshot_handle structure.  The structure gets updated and a pointer
1869  *      to it should be passed to this function every next time.
1870  *
1871  *      The @count parameter should contain the number of bytes the caller
1872  *      wants to write to the image.  It must not be zero.
1873  *
1874  *      On success the function returns a positive number.  Then, the caller
1875  *      is allowed to write up to the returned number of bytes to the memory
1876  *      location computed by the data_of() macro.  The number returned
1877  *      may be smaller than @count, but this only happens if the write would
1878  *      cross a page boundary otherwise.
1879  *
1880  *      The function returns 0 to indicate the "end of file" condition,
1881  *      and a negative number is returned on error.  In such cases the
1882  *      structure pointed to by @handle is not updated and should not be used
1883  *      any more.
1884  */
1885
1886 int snapshot_write_next(struct snapshot_handle *handle, size_t count)
1887 {
1888         static struct chain_allocator ca;
1889         int error = 0;
1890
1891         /* Check if we have already loaded the entire image */
1892         if (handle->prev && handle->cur > nr_meta_pages + nr_copy_pages)
1893                 return 0;
1894
1895         if (handle->offset == 0) {
1896                 if (!buffer)
1897                         /* This makes the buffer be freed by swsusp_free() */
1898                         buffer = get_image_page(GFP_ATOMIC, PG_ANY);
1899
1900                 if (!buffer)
1901                         return -ENOMEM;
1902
1903                 handle->buffer = buffer;
1904         }
1905         handle->sync_read = 1;
1906         if (handle->prev < handle->cur) {
1907                 if (handle->prev == 0) {
1908                         error = load_header(buffer);
1909                         if (error)
1910                                 return error;
1911
1912                         error = memory_bm_create(&copy_bm, GFP_ATOMIC, PG_ANY);
1913                         if (error)
1914                                 return error;
1915
1916                 } else if (handle->prev <= nr_meta_pages) {
1917                         unpack_orig_pfns(buffer, &copy_bm);
1918                         if (handle->prev == nr_meta_pages) {
1919                                 error = prepare_image(&orig_bm, &copy_bm);
1920                                 if (error)
1921                                         return error;
1922
1923                                 chain_init(&ca, GFP_ATOMIC, PG_SAFE);
1924                                 memory_bm_position_reset(&orig_bm);
1925                                 restore_pblist = NULL;
1926                                 handle->buffer = get_buffer(&orig_bm, &ca);
1927                                 handle->sync_read = 0;
1928                                 if (!handle->buffer)
1929                                         return -ENOMEM;
1930                         }
1931                 } else {
1932                         copy_last_highmem_page();
1933                         handle->buffer = get_buffer(&orig_bm, &ca);
1934                         if (handle->buffer != buffer)
1935                                 handle->sync_read = 0;
1936                 }
1937                 handle->prev = handle->cur;
1938         }
1939         handle->buf_offset = handle->cur_offset;
1940         if (handle->cur_offset + count >= PAGE_SIZE) {
1941                 count = PAGE_SIZE - handle->cur_offset;
1942                 handle->cur_offset = 0;
1943                 handle->cur++;
1944         } else {
1945                 handle->cur_offset += count;
1946         }
1947         handle->offset += count;
1948         return count;
1949 }
1950
1951 /**
1952  *      snapshot_write_finalize - must be called after the last call to
1953  *      snapshot_write_next() in case the last page in the image happens
1954  *      to be a highmem page and its contents should be stored in the
1955  *      highmem.  Additionally, it releases the memory that will not be
1956  *      used any more.
1957  */
1958
1959 void snapshot_write_finalize(struct snapshot_handle *handle)
1960 {
1961         copy_last_highmem_page();
1962         /* Free only if we have loaded the image entirely */
1963         if (handle->prev && handle->cur > nr_meta_pages + nr_copy_pages) {
1964                 memory_bm_free(&orig_bm, PG_UNSAFE_CLEAR);
1965                 free_highmem_data();
1966         }
1967 }
1968
1969 int snapshot_image_loaded(struct snapshot_handle *handle)
1970 {
1971         return !(!nr_copy_pages || !last_highmem_page_copied() ||
1972                         handle->cur <= nr_meta_pages + nr_copy_pages);
1973 }
1974
1975 #ifdef CONFIG_HIGHMEM
1976 /* Assumes that @buf is ready and points to a "safe" page */
1977 static inline void
1978 swap_two_pages_data(struct page *p1, struct page *p2, void *buf)
1979 {
1980         void *kaddr1, *kaddr2;
1981
1982         kaddr1 = kmap_atomic(p1, KM_USER0);
1983         kaddr2 = kmap_atomic(p2, KM_USER1);
1984         memcpy(buf, kaddr1, PAGE_SIZE);
1985         memcpy(kaddr1, kaddr2, PAGE_SIZE);
1986         memcpy(kaddr2, buf, PAGE_SIZE);
1987         kunmap_atomic(kaddr1, KM_USER0);
1988         kunmap_atomic(kaddr2, KM_USER1);
1989 }
1990
1991 /**
1992  *      restore_highmem - for each highmem page that was allocated before
1993  *      the suspend and included in the suspend image, and also has been
1994  *      allocated by the "resume" kernel swap its current (ie. "before
1995  *      resume") contents with the previous (ie. "before suspend") one.
1996  *
1997  *      If the resume eventually fails, we can call this function once
1998  *      again and restore the "before resume" highmem state.
1999  */
2000
2001 int restore_highmem(void)
2002 {
2003         struct highmem_pbe *pbe = highmem_pblist;
2004         void *buf;
2005
2006         if (!pbe)
2007                 return 0;
2008
2009         buf = get_image_page(GFP_ATOMIC, PG_SAFE);
2010         if (!buf)
2011                 return -ENOMEM;
2012
2013         while (pbe) {
2014                 swap_two_pages_data(pbe->copy_page, pbe->orig_page, buf);
2015                 pbe = pbe->next;
2016         }
2017         free_image_page(buf, PG_UNSAFE_CLEAR);
2018         return 0;
2019 }
2020 #endif /* CONFIG_HIGHMEM */