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