[PATCH] swsusp: make image size limit tunable
[pandora-kernel.git] / kernel / power / swsusp.c
1 /*
2  * linux/kernel/power/swsusp.c
3  *
4  * This file provides code to write suspend image to swap and read it back.
5  *
6  * Copyright (C) 1998-2001 Gabor Kuti <seasons@fornax.hu>
7  * Copyright (C) 1998,2001-2005 Pavel Machek <pavel@suse.cz>
8  *
9  * This file is released under the GPLv2.
10  *
11  * I'd like to thank the following people for their work:
12  *
13  * Pavel Machek <pavel@ucw.cz>:
14  * Modifications, defectiveness pointing, being with me at the very beginning,
15  * suspend to swap space, stop all tasks. Port to 2.4.18-ac and 2.5.17.
16  *
17  * Steve Doddi <dirk@loth.demon.co.uk>:
18  * Support the possibility of hardware state restoring.
19  *
20  * Raph <grey.havens@earthling.net>:
21  * Support for preserving states of network devices and virtual console
22  * (including X and svgatextmode)
23  *
24  * Kurt Garloff <garloff@suse.de>:
25  * Straightened the critical function in order to prevent compilers from
26  * playing tricks with local variables.
27  *
28  * Andreas Mohr <a.mohr@mailto.de>
29  *
30  * Alex Badea <vampire@go.ro>:
31  * Fixed runaway init
32  *
33  * Rafael J. Wysocki <rjw@sisk.pl>
34  * Added the swap map data structure and reworked the handling of swap
35  *
36  * More state savers are welcome. Especially for the scsi layer...
37  *
38  * For TODOs,FIXMEs also look in Documentation/power/swsusp.txt
39  */
40
41 #include <linux/module.h>
42 #include <linux/mm.h>
43 #include <linux/suspend.h>
44 #include <linux/smp_lock.h>
45 #include <linux/file.h>
46 #include <linux/utsname.h>
47 #include <linux/version.h>
48 #include <linux/delay.h>
49 #include <linux/bitops.h>
50 #include <linux/spinlock.h>
51 #include <linux/genhd.h>
52 #include <linux/kernel.h>
53 #include <linux/major.h>
54 #include <linux/swap.h>
55 #include <linux/pm.h>
56 #include <linux/device.h>
57 #include <linux/buffer_head.h>
58 #include <linux/swapops.h>
59 #include <linux/bootmem.h>
60 #include <linux/syscalls.h>
61 #include <linux/highmem.h>
62 #include <linux/bio.h>
63
64 #include <asm/uaccess.h>
65 #include <asm/mmu_context.h>
66 #include <asm/pgtable.h>
67 #include <asm/tlbflush.h>
68 #include <asm/io.h>
69
70 #include "power.h"
71
72 /*
73  * Preferred image size in MB (tunable via /sys/power/image_size).
74  * When it is set to N, swsusp will do its best to ensure the image
75  * size will not exceed N MB, but if that is impossible, it will
76  * try to create the smallest image possible.
77  */
78 unsigned int image_size = 500;
79
80 #ifdef CONFIG_HIGHMEM
81 unsigned int count_highmem_pages(void);
82 int save_highmem(void);
83 int restore_highmem(void);
84 #else
85 static int save_highmem(void) { return 0; }
86 static int restore_highmem(void) { return 0; }
87 static unsigned int count_highmem_pages(void) { return 0; }
88 #endif
89
90 extern char resume_file[];
91
92 #define SWSUSP_SIG      "S1SUSPEND"
93
94 static struct swsusp_header {
95         char reserved[PAGE_SIZE - 20 - sizeof(swp_entry_t)];
96         swp_entry_t swsusp_info;
97         char    orig_sig[10];
98         char    sig[10];
99 } __attribute__((packed, aligned(PAGE_SIZE))) swsusp_header;
100
101 static struct swsusp_info swsusp_info;
102
103 /*
104  * Saving part...
105  */
106
107 /* We memorize in swapfile_used what swap devices are used for suspension */
108 #define SWAPFILE_UNUSED    0
109 #define SWAPFILE_SUSPEND   1    /* This is the suspending device */
110 #define SWAPFILE_IGNORED   2    /* Those are other swap devices ignored for suspension */
111
112 static unsigned short swapfile_used[MAX_SWAPFILES];
113 static unsigned short root_swap;
114
115 static int mark_swapfiles(swp_entry_t prev)
116 {
117         int error;
118
119         rw_swap_page_sync(READ,
120                           swp_entry(root_swap, 0),
121                           virt_to_page((unsigned long)&swsusp_header));
122         if (!memcmp("SWAP-SPACE",swsusp_header.sig, 10) ||
123             !memcmp("SWAPSPACE2",swsusp_header.sig, 10)) {
124                 memcpy(swsusp_header.orig_sig,swsusp_header.sig, 10);
125                 memcpy(swsusp_header.sig,SWSUSP_SIG, 10);
126                 swsusp_header.swsusp_info = prev;
127                 error = rw_swap_page_sync(WRITE,
128                                           swp_entry(root_swap, 0),
129                                           virt_to_page((unsigned long)
130                                                        &swsusp_header));
131         } else {
132                 pr_debug("swsusp: Partition is not swap space.\n");
133                 error = -ENODEV;
134         }
135         return error;
136 }
137
138 /*
139  * Check whether the swap device is the specified resume
140  * device, irrespective of whether they are specified by
141  * identical names.
142  *
143  * (Thus, device inode aliasing is allowed.  You can say /dev/hda4
144  * instead of /dev/ide/host0/bus0/target0/lun0/part4 [if using devfs]
145  * and they'll be considered the same device.  This is *necessary* for
146  * devfs, since the resume code can only recognize the form /dev/hda4,
147  * but the suspend code would see the long name.)
148  */
149 static int is_resume_device(const struct swap_info_struct *swap_info)
150 {
151         struct file *file = swap_info->swap_file;
152         struct inode *inode = file->f_dentry->d_inode;
153
154         return S_ISBLK(inode->i_mode) &&
155                 swsusp_resume_device == MKDEV(imajor(inode), iminor(inode));
156 }
157
158 static int swsusp_swap_check(void) /* This is called before saving image */
159 {
160         int i, len;
161
162         len=strlen(resume_file);
163         root_swap = 0xFFFF;
164
165         spin_lock(&swap_lock);
166         for (i=0; i<MAX_SWAPFILES; i++) {
167                 if (!(swap_info[i].flags & SWP_WRITEOK)) {
168                         swapfile_used[i]=SWAPFILE_UNUSED;
169                 } else {
170                         if (!len) {
171                                 printk(KERN_WARNING "resume= option should be used to set suspend device" );
172                                 if (root_swap == 0xFFFF) {
173                                         swapfile_used[i] = SWAPFILE_SUSPEND;
174                                         root_swap = i;
175                                 } else
176                                         swapfile_used[i] = SWAPFILE_IGNORED;
177                         } else {
178                                 /* we ignore all swap devices that are not the resume_file */
179                                 if (is_resume_device(&swap_info[i])) {
180                                         swapfile_used[i] = SWAPFILE_SUSPEND;
181                                         root_swap = i;
182                                 } else {
183                                         swapfile_used[i] = SWAPFILE_IGNORED;
184                                 }
185                         }
186                 }
187         }
188         spin_unlock(&swap_lock);
189         return (root_swap != 0xffff) ? 0 : -ENODEV;
190 }
191
192 /**
193  * This is called after saving image so modification
194  * will be lost after resume... and that's what we want.
195  * we make the device unusable. A new call to
196  * lock_swapdevices can unlock the devices.
197  */
198 static void lock_swapdevices(void)
199 {
200         int i;
201
202         spin_lock(&swap_lock);
203         for (i = 0; i< MAX_SWAPFILES; i++)
204                 if (swapfile_used[i] == SWAPFILE_IGNORED) {
205                         swap_info[i].flags ^= SWP_WRITEOK;
206                 }
207         spin_unlock(&swap_lock);
208 }
209
210 /**
211  *      write_page - Write one page to a fresh swap location.
212  *      @addr:  Address we're writing.
213  *      @loc:   Place to store the entry we used.
214  *
215  *      Allocate a new swap entry and 'sync' it. Note we discard -EIO
216  *      errors. That is an artifact left over from swsusp. It did not
217  *      check the return of rw_swap_page_sync() at all, since most pages
218  *      written back to swap would return -EIO.
219  *      This is a partial improvement, since we will at least return other
220  *      errors, though we need to eventually fix the damn code.
221  */
222 static int write_page(unsigned long addr, swp_entry_t *loc)
223 {
224         swp_entry_t entry;
225         int error = 0;
226
227         entry = get_swap_page();
228         if (swp_offset(entry) &&
229             swapfile_used[swp_type(entry)] == SWAPFILE_SUSPEND) {
230                 error = rw_swap_page_sync(WRITE, entry,
231                                           virt_to_page(addr));
232                 if (error == -EIO)
233                         error = 0;
234                 if (!error)
235                         *loc = entry;
236         } else
237                 error = -ENOSPC;
238         return error;
239 }
240
241 /**
242  *      Swap map-handling functions
243  *
244  *      The swap map is a data structure used for keeping track of each page
245  *      written to the swap.  It consists of many swap_map_page structures
246  *      that contain each an array of MAP_PAGE_SIZE swap entries.
247  *      These structures are linked together with the help of either the
248  *      .next (in memory) or the .next_swap (in swap) member.
249  *
250  *      The swap map is created during suspend.  At that time we need to keep
251  *      it in memory, because we have to free all of the allocated swap
252  *      entries if an error occurs.  The memory needed is preallocated
253  *      so that we know in advance if there's enough of it.
254  *
255  *      The first swap_map_page structure is filled with the swap entries that
256  *      correspond to the first MAP_PAGE_SIZE data pages written to swap and
257  *      so on.  After the all of the data pages have been written, the order
258  *      of the swap_map_page structures in the map is reversed so that they
259  *      can be read from swap in the original order.  This causes the data
260  *      pages to be loaded in exactly the same order in which they have been
261  *      saved.
262  *
263  *      During resume we only need to use one swap_map_page structure
264  *      at a time, which means that we only need to use two memory pages for
265  *      reading the image - one for reading the swap_map_page structures
266  *      and the second for reading the data pages from swap.
267  */
268
269 #define MAP_PAGE_SIZE   ((PAGE_SIZE - sizeof(swp_entry_t) - sizeof(void *)) \
270                         / sizeof(swp_entry_t))
271
272 struct swap_map_page {
273         swp_entry_t             entries[MAP_PAGE_SIZE];
274         swp_entry_t             next_swap;
275         struct swap_map_page    *next;
276 };
277
278 static inline void free_swap_map(struct swap_map_page *swap_map)
279 {
280         struct swap_map_page *swp;
281
282         while (swap_map) {
283                 swp = swap_map->next;
284                 free_page((unsigned long)swap_map);
285                 swap_map = swp;
286         }
287 }
288
289 static struct swap_map_page *alloc_swap_map(unsigned int nr_pages)
290 {
291         struct swap_map_page *swap_map, *swp;
292         unsigned n = 0;
293
294         if (!nr_pages)
295                 return NULL;
296
297         pr_debug("alloc_swap_map(): nr_pages = %d\n", nr_pages);
298         swap_map = (struct swap_map_page *)get_zeroed_page(GFP_ATOMIC);
299         swp = swap_map;
300         for (n = MAP_PAGE_SIZE; n < nr_pages; n += MAP_PAGE_SIZE) {
301                 swp->next = (struct swap_map_page *)get_zeroed_page(GFP_ATOMIC);
302                 swp = swp->next;
303                 if (!swp) {
304                         free_swap_map(swap_map);
305                         return NULL;
306                 }
307         }
308         return swap_map;
309 }
310
311 /**
312  *      reverse_swap_map - reverse the order of pages in the swap map
313  *      @swap_map
314  */
315
316 static inline struct swap_map_page *reverse_swap_map(struct swap_map_page *swap_map)
317 {
318         struct swap_map_page *prev, *next;
319
320         prev = NULL;
321         while (swap_map) {
322                 next = swap_map->next;
323                 swap_map->next = prev;
324                 prev = swap_map;
325                 swap_map = next;
326         }
327         return prev;
328 }
329
330 /**
331  *      free_swap_map_entries - free the swap entries allocated to store
332  *      the swap map @swap_map (this is only called in case of an error)
333  */
334 static inline void free_swap_map_entries(struct swap_map_page *swap_map)
335 {
336         while (swap_map) {
337                 if (swap_map->next_swap.val)
338                         swap_free(swap_map->next_swap);
339                 swap_map = swap_map->next;
340         }
341 }
342
343 /**
344  *      save_swap_map - save the swap map used for tracing the data pages
345  *      stored in the swap
346  */
347
348 static int save_swap_map(struct swap_map_page *swap_map, swp_entry_t *start)
349 {
350         swp_entry_t entry = (swp_entry_t){0};
351         int error;
352
353         while (swap_map) {
354                 swap_map->next_swap = entry;
355                 if ((error = write_page((unsigned long)swap_map, &entry)))
356                         return error;
357                 swap_map = swap_map->next;
358         }
359         *start = entry;
360         return 0;
361 }
362
363 /**
364  *      free_image_entries - free the swap entries allocated to store
365  *      the image data pages (this is only called in case of an error)
366  */
367
368 static inline void free_image_entries(struct swap_map_page *swp)
369 {
370         unsigned k;
371
372         while (swp) {
373                 for (k = 0; k < MAP_PAGE_SIZE; k++)
374                         if (swp->entries[k].val)
375                                 swap_free(swp->entries[k]);
376                 swp = swp->next;
377         }
378 }
379
380 /**
381  *      The swap_map_handle structure is used for handling the swap map in
382  *      a file-alike way
383  */
384
385 struct swap_map_handle {
386         struct swap_map_page *cur;
387         unsigned int k;
388 };
389
390 static inline void init_swap_map_handle(struct swap_map_handle *handle,
391                                         struct swap_map_page *map)
392 {
393         handle->cur = map;
394         handle->k = 0;
395 }
396
397 static inline int swap_map_write_page(struct swap_map_handle *handle,
398                                       unsigned long addr)
399 {
400         int error;
401
402         error = write_page(addr, handle->cur->entries + handle->k);
403         if (error)
404                 return error;
405         if (++handle->k >= MAP_PAGE_SIZE) {
406                 handle->cur = handle->cur->next;
407                 handle->k = 0;
408         }
409         return 0;
410 }
411
412 /**
413  *      save_image_data - save the data pages pointed to by the PBEs
414  *      from the list @pblist using the swap map handle @handle
415  *      (assume there are @nr_pages data pages to save)
416  */
417
418 static int save_image_data(struct pbe *pblist,
419                            struct swap_map_handle *handle,
420                            unsigned int nr_pages)
421 {
422         unsigned int m;
423         struct pbe *p;
424         int error = 0;
425
426         printk("Saving image data pages (%u pages) ...     ", nr_pages);
427         m = nr_pages / 100;
428         if (!m)
429                 m = 1;
430         nr_pages = 0;
431         for_each_pbe (p, pblist) {
432                 error = swap_map_write_page(handle, p->address);
433                 if (error)
434                         break;
435                 if (!(nr_pages % m))
436                         printk("\b\b\b\b%3d%%", nr_pages / m);
437                 nr_pages++;
438         }
439         if (!error)
440                 printk("\b\b\b\bdone\n");
441         return error;
442 }
443
444 static void dump_info(void)
445 {
446         pr_debug(" swsusp: Version: %u\n",swsusp_info.version_code);
447         pr_debug(" swsusp: Num Pages: %ld\n",swsusp_info.num_physpages);
448         pr_debug(" swsusp: UTS Sys: %s\n",swsusp_info.uts.sysname);
449         pr_debug(" swsusp: UTS Node: %s\n",swsusp_info.uts.nodename);
450         pr_debug(" swsusp: UTS Release: %s\n",swsusp_info.uts.release);
451         pr_debug(" swsusp: UTS Version: %s\n",swsusp_info.uts.version);
452         pr_debug(" swsusp: UTS Machine: %s\n",swsusp_info.uts.machine);
453         pr_debug(" swsusp: UTS Domain: %s\n",swsusp_info.uts.domainname);
454         pr_debug(" swsusp: CPUs: %d\n",swsusp_info.cpus);
455         pr_debug(" swsusp: Image: %ld Pages\n",swsusp_info.image_pages);
456         pr_debug(" swsusp: Total: %ld Pages\n", swsusp_info.pages);
457 }
458
459 static void init_header(unsigned int nr_pages)
460 {
461         memset(&swsusp_info, 0, sizeof(swsusp_info));
462         swsusp_info.version_code = LINUX_VERSION_CODE;
463         swsusp_info.num_physpages = num_physpages;
464         memcpy(&swsusp_info.uts, &system_utsname, sizeof(system_utsname));
465
466         swsusp_info.cpus = num_online_cpus();
467         swsusp_info.image_pages = nr_pages;
468         swsusp_info.pages = nr_pages +
469                 ((nr_pages * sizeof(long) + PAGE_SIZE - 1) >> PAGE_SHIFT);
470 }
471
472 static int close_swap(void)
473 {
474         swp_entry_t entry;
475         int error;
476
477         dump_info();
478         error = write_page((unsigned long)&swsusp_info, &entry);
479         if (!error) {
480                 printk( "S" );
481                 error = mark_swapfiles(entry);
482                 printk( "|\n" );
483         }
484         return error;
485 }
486
487 /**
488  *      pack_orig_addresses - the .orig_address fields of the PBEs from the
489  *      list starting at @pbe are stored in the array @buf[] (1 page)
490  */
491
492 static inline struct pbe *pack_orig_addresses(unsigned long *buf,
493                                               struct pbe *pbe)
494 {
495         int j;
496
497         for (j = 0; j < PAGE_SIZE / sizeof(long) && pbe; j++) {
498                 buf[j] = pbe->orig_address;
499                 pbe = pbe->next;
500         }
501         if (!pbe)
502                 for (; j < PAGE_SIZE / sizeof(long); j++)
503                         buf[j] = 0;
504         return pbe;
505 }
506
507 /**
508  *      save_image_metadata - save the .orig_address fields of the PBEs
509  *      from the list @pblist using the swap map handle @handle
510  */
511
512 static int save_image_metadata(struct pbe *pblist,
513                                struct swap_map_handle *handle)
514 {
515         unsigned long *buf;
516         unsigned int n = 0;
517         struct pbe *p;
518         int error = 0;
519
520         printk("Saving image metadata ... ");
521         buf = (unsigned long *)get_zeroed_page(GFP_ATOMIC);
522         if (!buf)
523                 return -ENOMEM;
524         p = pblist;
525         while (p) {
526                 p = pack_orig_addresses(buf, p);
527                 error = swap_map_write_page(handle, (unsigned long)buf);
528                 if (error)
529                         break;
530                 n++;
531         }
532         free_page((unsigned long)buf);
533         if (!error)
534                 printk("done (%u pages saved)\n", n);
535         return error;
536 }
537
538 /**
539  *      enough_swap - Make sure we have enough swap to save the image.
540  *
541  *      Returns TRUE or FALSE after checking the total amount of swap
542  *      space avaiable.
543  *
544  *      FIXME: si_swapinfo(&i) returns all swap devices information.
545  *      We should only consider resume_device.
546  */
547
548 static int enough_swap(unsigned int nr_pages)
549 {
550         struct sysinfo i;
551
552         si_swapinfo(&i);
553         pr_debug("swsusp: available swap: %lu pages\n", i.freeswap);
554         return i.freeswap > (nr_pages + PAGES_FOR_IO +
555                 (nr_pages + PBES_PER_PAGE - 1) / PBES_PER_PAGE);
556 }
557
558 /**
559  *      write_suspend_image - Write entire image and metadata.
560  */
561 static int write_suspend_image(struct pbe *pblist, unsigned int nr_pages)
562 {
563         struct swap_map_page *swap_map;
564         struct swap_map_handle handle;
565         int error;
566
567         if (!enough_swap(nr_pages)) {
568                 printk(KERN_ERR "swsusp: Not enough free swap\n");
569                 return -ENOSPC;
570         }
571
572         init_header(nr_pages);
573         swap_map = alloc_swap_map(swsusp_info.pages);
574         if (!swap_map)
575                 return -ENOMEM;
576         init_swap_map_handle(&handle, swap_map);
577
578         error = save_image_metadata(pblist, &handle);
579         if (!error)
580                 error = save_image_data(pblist, &handle, nr_pages);
581         if (error)
582                 goto Free_image_entries;
583
584         swap_map = reverse_swap_map(swap_map);
585         error = save_swap_map(swap_map, &swsusp_info.start);
586         if (error)
587                 goto Free_map_entries;
588
589         error = close_swap();
590         if (error)
591                 goto Free_map_entries;
592
593 Free_swap_map:
594         free_swap_map(swap_map);
595         return error;
596
597 Free_map_entries:
598         free_swap_map_entries(swap_map);
599 Free_image_entries:
600         free_image_entries(swap_map);
601         goto Free_swap_map;
602 }
603
604 /* It is important _NOT_ to umount filesystems at this point. We want
605  * them synced (in case something goes wrong) but we DO not want to mark
606  * filesystem clean: it is not. (And it does not matter, if we resume
607  * correctly, we'll mark system clean, anyway.)
608  */
609 int swsusp_write(struct pbe *pblist, unsigned int nr_pages)
610 {
611         int error;
612
613         if ((error = swsusp_swap_check())) {
614                 printk(KERN_ERR "swsusp: cannot find swap device, try swapon -a.\n");
615                 return error;
616         }
617         lock_swapdevices();
618         error = write_suspend_image(pblist, nr_pages);
619         /* This will unlock ignored swap devices since writing is finished */
620         lock_swapdevices();
621         return error;
622 }
623
624 /**
625  *      swsusp_shrink_memory -  Try to free as much memory as needed
626  *
627  *      ... but do not OOM-kill anyone
628  *
629  *      Notice: all userland should be stopped before it is called, or
630  *      livelock is possible.
631  */
632
633 #define SHRINK_BITE     10000
634
635 int swsusp_shrink_memory(void)
636 {
637         long size, tmp;
638         struct zone *zone;
639         unsigned long pages = 0;
640         unsigned int i = 0;
641         char *p = "-\\|/";
642
643         printk("Shrinking memory...  ");
644         do {
645                 size = 2 * count_highmem_pages();
646                 size += size / 50 + count_data_pages();
647                 size += (size + PBES_PER_PAGE - 1) / PBES_PER_PAGE +
648                         PAGES_FOR_IO;
649                 tmp = size;
650                 for_each_zone (zone)
651                         if (!is_highmem(zone))
652                                 tmp -= zone->free_pages;
653                 if (tmp > 0) {
654                         tmp = shrink_all_memory(SHRINK_BITE);
655                         if (!tmp)
656                                 return -ENOMEM;
657                         pages += tmp;
658                 } else if (size > (image_size * 1024 * 1024) / PAGE_SIZE) {
659                         tmp = shrink_all_memory(SHRINK_BITE);
660                         pages += tmp;
661                 }
662                 printk("\b%c", p[i++%4]);
663         } while (tmp > 0);
664         printk("\bdone (%lu pages freed)\n", pages);
665
666         return 0;
667 }
668
669 int swsusp_suspend(void)
670 {
671         int error;
672
673         if ((error = arch_prepare_suspend()))
674                 return error;
675         local_irq_disable();
676         /* At this point, device_suspend() has been called, but *not*
677          * device_power_down(). We *must* device_power_down() now.
678          * Otherwise, drivers for some devices (e.g. interrupt controllers)
679          * become desynchronized with the actual state of the hardware
680          * at resume time, and evil weirdness ensues.
681          */
682         if ((error = device_power_down(PMSG_FREEZE))) {
683                 printk(KERN_ERR "Some devices failed to power down, aborting suspend\n");
684                 goto Enable_irqs;
685         }
686
687         if ((error = save_highmem())) {
688                 printk(KERN_ERR "swsusp: Not enough free pages for highmem\n");
689                 goto Restore_highmem;
690         }
691
692         save_processor_state();
693         if ((error = swsusp_arch_suspend()))
694                 printk(KERN_ERR "Error %d suspending\n", error);
695         /* Restore control flow magically appears here */
696         restore_processor_state();
697 Restore_highmem:
698         restore_highmem();
699         device_power_up();
700 Enable_irqs:
701         local_irq_enable();
702         return error;
703 }
704
705 int swsusp_resume(void)
706 {
707         int error;
708         local_irq_disable();
709         if (device_power_down(PMSG_FREEZE))
710                 printk(KERN_ERR "Some devices failed to power down, very bad\n");
711         /* We'll ignore saved state, but this gets preempt count (etc) right */
712         save_processor_state();
713         error = swsusp_arch_resume();
714         /* Code below is only ever reached in case of failure. Otherwise
715          * execution continues at place where swsusp_arch_suspend was called
716          */
717         BUG_ON(!error);
718         /* The only reason why swsusp_arch_resume() can fail is memory being
719          * very tight, so we have to free it as soon as we can to avoid
720          * subsequent failures
721          */
722         swsusp_free();
723         restore_processor_state();
724         restore_highmem();
725         touch_softlockup_watchdog();
726         device_power_up();
727         local_irq_enable();
728         return error;
729 }
730
731 /**
732  *      mark_unsafe_pages - mark the pages that cannot be used for storing
733  *      the image during resume, because they conflict with the pages that
734  *      had been used before suspend
735  */
736
737 static void mark_unsafe_pages(struct pbe *pblist)
738 {
739         struct zone *zone;
740         unsigned long zone_pfn;
741         struct pbe *p;
742
743         if (!pblist) /* a sanity check */
744                 return;
745
746         /* Clear page flags */
747         for_each_zone (zone) {
748                 for (zone_pfn = 0; zone_pfn < zone->spanned_pages; ++zone_pfn)
749                         if (pfn_valid(zone_pfn + zone->zone_start_pfn))
750                                 ClearPageNosaveFree(pfn_to_page(zone_pfn +
751                                         zone->zone_start_pfn));
752         }
753
754         /* Mark orig addresses */
755         for_each_pbe (p, pblist)
756                 SetPageNosaveFree(virt_to_page(p->orig_address));
757
758 }
759
760 static void copy_page_backup_list(struct pbe *dst, struct pbe *src)
761 {
762         /* We assume both lists contain the same number of elements */
763         while (src) {
764                 dst->orig_address = src->orig_address;
765                 dst = dst->next;
766                 src = src->next;
767         }
768 }
769
770 /*
771  *      Using bio to read from swap.
772  *      This code requires a bit more work than just using buffer heads
773  *      but, it is the recommended way for 2.5/2.6.
774  *      The following are to signal the beginning and end of I/O. Bios
775  *      finish asynchronously, while we want them to happen synchronously.
776  *      A simple atomic_t, and a wait loop take care of this problem.
777  */
778
779 static atomic_t io_done = ATOMIC_INIT(0);
780
781 static int end_io(struct bio *bio, unsigned int num, int err)
782 {
783         if (!test_bit(BIO_UPTODATE, &bio->bi_flags))
784                 panic("I/O error reading memory image");
785         atomic_set(&io_done, 0);
786         return 0;
787 }
788
789 static struct block_device *resume_bdev;
790
791 /**
792  *      submit - submit BIO request.
793  *      @rw:    READ or WRITE.
794  *      @off    physical offset of page.
795  *      @page:  page we're reading or writing.
796  *
797  *      Straight from the textbook - allocate and initialize the bio.
798  *      If we're writing, make sure the page is marked as dirty.
799  *      Then submit it and wait.
800  */
801
802 static int submit(int rw, pgoff_t page_off, void *page)
803 {
804         int error = 0;
805         struct bio *bio;
806
807         bio = bio_alloc(GFP_ATOMIC, 1);
808         if (!bio)
809                 return -ENOMEM;
810         bio->bi_sector = page_off * (PAGE_SIZE >> 9);
811         bio_get(bio);
812         bio->bi_bdev = resume_bdev;
813         bio->bi_end_io = end_io;
814
815         if (bio_add_page(bio, virt_to_page(page), PAGE_SIZE, 0) < PAGE_SIZE) {
816                 printk("swsusp: ERROR: adding page to bio at %ld\n",page_off);
817                 error = -EFAULT;
818                 goto Done;
819         }
820
821         if (rw == WRITE)
822                 bio_set_pages_dirty(bio);
823
824         atomic_set(&io_done, 1);
825         submit_bio(rw | (1 << BIO_RW_SYNC), bio);
826         while (atomic_read(&io_done))
827                 yield();
828
829  Done:
830         bio_put(bio);
831         return error;
832 }
833
834 static int bio_read_page(pgoff_t page_off, void *page)
835 {
836         return submit(READ, page_off, page);
837 }
838
839 static int bio_write_page(pgoff_t page_off, void *page)
840 {
841         return submit(WRITE, page_off, page);
842 }
843
844 /**
845  *      The following functions allow us to read data using a swap map
846  *      in a file-alike way
847  */
848
849 static inline void release_swap_map_reader(struct swap_map_handle *handle)
850 {
851         if (handle->cur)
852                 free_page((unsigned long)handle->cur);
853         handle->cur = NULL;
854 }
855
856 static inline int get_swap_map_reader(struct swap_map_handle *handle,
857                                       swp_entry_t start)
858 {
859         int error;
860
861         if (!swp_offset(start))
862                 return -EINVAL;
863         handle->cur = (struct swap_map_page *)get_zeroed_page(GFP_ATOMIC);
864         if (!handle->cur)
865                 return -ENOMEM;
866         error = bio_read_page(swp_offset(start), handle->cur);
867         if (error) {
868                 release_swap_map_reader(handle);
869                 return error;
870         }
871         handle->k = 0;
872         return 0;
873 }
874
875 static inline int swap_map_read_page(struct swap_map_handle *handle, void *buf)
876 {
877         unsigned long offset;
878         int error;
879
880         if (!handle->cur)
881                 return -EINVAL;
882         offset = swp_offset(handle->cur->entries[handle->k]);
883         if (!offset)
884                 return -EINVAL;
885         error = bio_read_page(offset, buf);
886         if (error)
887                 return error;
888         if (++handle->k >= MAP_PAGE_SIZE) {
889                 handle->k = 0;
890                 offset = swp_offset(handle->cur->next_swap);
891                 if (!offset)
892                         release_swap_map_reader(handle);
893                 else
894                         error = bio_read_page(offset, handle->cur);
895         }
896         return error;
897 }
898
899 /*
900  * Sanity check if this image makes sense with this kernel/swap context
901  * I really don't think that it's foolproof but more than nothing..
902  */
903
904 static const char *sanity_check(void)
905 {
906         dump_info();
907         if (swsusp_info.version_code != LINUX_VERSION_CODE)
908                 return "kernel version";
909         if (swsusp_info.num_physpages != num_physpages)
910                 return "memory size";
911         if (strcmp(swsusp_info.uts.sysname,system_utsname.sysname))
912                 return "system type";
913         if (strcmp(swsusp_info.uts.release,system_utsname.release))
914                 return "kernel release";
915         if (strcmp(swsusp_info.uts.version,system_utsname.version))
916                 return "version";
917         if (strcmp(swsusp_info.uts.machine,system_utsname.machine))
918                 return "machine";
919 #if 0
920         /* We can't use number of online CPUs when we use hotplug to remove them ;-))) */
921         if (swsusp_info.cpus != num_possible_cpus())
922                 return "number of cpus";
923 #endif
924         return NULL;
925 }
926
927 static int check_header(void)
928 {
929         const char *reason = NULL;
930         int error;
931
932         if ((error = bio_read_page(swp_offset(swsusp_header.swsusp_info), &swsusp_info)))
933                 return error;
934
935         /* Is this same machine? */
936         if ((reason = sanity_check())) {
937                 printk(KERN_ERR "swsusp: Resume mismatch: %s\n",reason);
938                 return -EPERM;
939         }
940         return error;
941 }
942
943 static int check_sig(void)
944 {
945         int error;
946
947         memset(&swsusp_header, 0, sizeof(swsusp_header));
948         if ((error = bio_read_page(0, &swsusp_header)))
949                 return error;
950         if (!memcmp(SWSUSP_SIG, swsusp_header.sig, 10)) {
951                 memcpy(swsusp_header.sig, swsusp_header.orig_sig, 10);
952
953                 /*
954                  * Reset swap signature now.
955                  */
956                 error = bio_write_page(0, &swsusp_header);
957         } else {
958                 return -EINVAL;
959         }
960         if (!error)
961                 pr_debug("swsusp: Signature found, resuming\n");
962         return error;
963 }
964
965 /**
966  *      load_image_data - load the image data using the swap map handle
967  *      @handle and store them using the page backup list @pblist
968  *      (assume there are @nr_pages pages to load)
969  */
970
971 static int load_image_data(struct pbe *pblist,
972                            struct swap_map_handle *handle,
973                            unsigned int nr_pages)
974 {
975         int error;
976         unsigned int m;
977         struct pbe *p;
978
979         if (!pblist)
980                 return -EINVAL;
981         printk("Loading image data pages (%u pages) ...     ", nr_pages);
982         m = nr_pages / 100;
983         if (!m)
984                 m = 1;
985         nr_pages = 0;
986         p = pblist;
987         while (p) {
988                 error = swap_map_read_page(handle, (void *)p->address);
989                 if (error)
990                         break;
991                 p = p->next;
992                 if (!(nr_pages % m))
993                         printk("\b\b\b\b%3d%%", nr_pages / m);
994                 nr_pages++;
995         }
996         if (!error)
997                 printk("\b\b\b\bdone\n");
998         return error;
999 }
1000
1001 /**
1002  *      unpack_orig_addresses - copy the elements of @buf[] (1 page) to
1003  *      the PBEs in the list starting at @pbe
1004  */
1005
1006 static inline struct pbe *unpack_orig_addresses(unsigned long *buf,
1007                                                 struct pbe *pbe)
1008 {
1009         int j;
1010
1011         for (j = 0; j < PAGE_SIZE / sizeof(long) && pbe; j++) {
1012                 pbe->orig_address = buf[j];
1013                 pbe = pbe->next;
1014         }
1015         return pbe;
1016 }
1017
1018 /**
1019  *      load_image_metadata - load the image metadata using the swap map
1020  *      handle @handle and put them into the PBEs in the list @pblist
1021  */
1022
1023 static int load_image_metadata(struct pbe *pblist, struct swap_map_handle *handle)
1024 {
1025         struct pbe *p;
1026         unsigned long *buf;
1027         unsigned int n = 0;
1028         int error = 0;
1029
1030         printk("Loading image metadata ... ");
1031         buf = (unsigned long *)get_zeroed_page(GFP_ATOMIC);
1032         if (!buf)
1033                 return -ENOMEM;
1034         p = pblist;
1035         while (p) {
1036                 error = swap_map_read_page(handle, buf);
1037                 if (error)
1038                         break;
1039                 p = unpack_orig_addresses(buf, p);
1040                 n++;
1041         }
1042         free_page((unsigned long)buf);
1043         if (!error)
1044                 printk("done (%u pages loaded)\n", n);
1045         return error;
1046 }
1047
1048 static int check_suspend_image(void)
1049 {
1050         int error = 0;
1051
1052         if ((error = check_sig()))
1053                 return error;
1054
1055         if ((error = check_header()))
1056                 return error;
1057
1058         return 0;
1059 }
1060
1061 static int read_suspend_image(struct pbe **pblist_ptr)
1062 {
1063         int error = 0;
1064         struct pbe *p, *pblist;
1065         struct swap_map_handle handle;
1066         unsigned int nr_pages = swsusp_info.image_pages;
1067
1068         p = alloc_pagedir(nr_pages, GFP_ATOMIC, 0);
1069         if (!p)
1070                 return -ENOMEM;
1071         error = get_swap_map_reader(&handle, swsusp_info.start);
1072         if (error)
1073                 /* The PBE list at p will be released by swsusp_free() */
1074                 return error;
1075         error = load_image_metadata(p, &handle);
1076         if (!error) {
1077                 mark_unsafe_pages(p);
1078                 pblist = alloc_pagedir(nr_pages, GFP_ATOMIC, 1);
1079                 if (pblist)
1080                         copy_page_backup_list(pblist, p);
1081                 free_pagedir(p);
1082                 if (!pblist)
1083                         error = -ENOMEM;
1084
1085                 /* Allocate memory for the image and read the data from swap */
1086                 if (!error)
1087                         error = alloc_data_pages(pblist, GFP_ATOMIC, 1);
1088                 if (!error) {
1089                         release_eaten_pages();
1090                         error = load_image_data(pblist, &handle, nr_pages);
1091                 }
1092                 if (!error)
1093                         *pblist_ptr = pblist;
1094         }
1095         release_swap_map_reader(&handle);
1096         return error;
1097 }
1098
1099 /**
1100  *      swsusp_check - Check for saved image in swap
1101  */
1102
1103 int swsusp_check(void)
1104 {
1105         int error;
1106
1107         resume_bdev = open_by_devnum(swsusp_resume_device, FMODE_READ);
1108         if (!IS_ERR(resume_bdev)) {
1109                 set_blocksize(resume_bdev, PAGE_SIZE);
1110                 error = check_suspend_image();
1111                 if (error)
1112                     blkdev_put(resume_bdev);
1113         } else
1114                 error = PTR_ERR(resume_bdev);
1115
1116         if (!error)
1117                 pr_debug("swsusp: resume file found\n");
1118         else
1119                 pr_debug("swsusp: Error %d check for resume file\n", error);
1120         return error;
1121 }
1122
1123 /**
1124  *      swsusp_read - Read saved image from swap.
1125  */
1126
1127 int swsusp_read(struct pbe **pblist_ptr)
1128 {
1129         int error;
1130
1131         if (IS_ERR(resume_bdev)) {
1132                 pr_debug("swsusp: block device not initialised\n");
1133                 return PTR_ERR(resume_bdev);
1134         }
1135
1136         error = read_suspend_image(pblist_ptr);
1137         blkdev_put(resume_bdev);
1138
1139         if (!error)
1140                 pr_debug("swsusp: Reading resume file was successful\n");
1141         else
1142                 pr_debug("swsusp: Error %d resuming\n", error);
1143         return error;
1144 }
1145
1146 /**
1147  *      swsusp_close - close swap device.
1148  */
1149
1150 void swsusp_close(void)
1151 {
1152         if (IS_ERR(resume_bdev)) {
1153                 pr_debug("swsusp: block device not initialised\n");
1154                 return;
1155         }
1156
1157         blkdev_put(resume_bdev);
1158 }