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