vserver 1.9.3
[linux-2.6.git] / kernel / power / swsusp.c
1 /*
2  * linux/kernel/power/swsusp.c
3  *
4  * This file is to realize architecture-independent
5  * machine suspend feature using pretty near only high-level routines
6  *
7  * Copyright (C) 1998-2001 Gabor Kuti <seasons@fornax.hu>
8  * Copyright (C) 1998,2001-2004 Pavel Machek <pavel@suse.cz>
9  *
10  * This file is released under the GPLv2.
11  *
12  * I'd like to thank the following people for their work:
13  * 
14  * Pavel Machek <pavel@ucw.cz>:
15  * Modifications, defectiveness pointing, being with me at the very beginning,
16  * suspend to swap space, stop all tasks. Port to 2.4.18-ac and 2.5.17.
17  *
18  * Steve Doddi <dirk@loth.demon.co.uk>: 
19  * Support the possibility of hardware state restoring.
20  *
21  * Raph <grey.havens@earthling.net>:
22  * Support for preserving states of network devices and virtual console
23  * (including X and svgatextmode)
24  *
25  * Kurt Garloff <garloff@suse.de>:
26  * Straightened the critical function in order to prevent compilers from
27  * playing tricks with local variables.
28  *
29  * Andreas Mohr <a.mohr@mailto.de>
30  *
31  * Alex Badea <vampire@go.ro>:
32  * Fixed runaway init
33  *
34  * More state savers are welcome. Especially for the scsi layer...
35  *
36  * For TODOs,FIXMEs also look in Documentation/power/swsusp.txt
37  */
38
39 #include <linux/module.h>
40 #include <linux/mm.h>
41 #include <linux/suspend.h>
42 #include <linux/smp_lock.h>
43 #include <linux/file.h>
44 #include <linux/utsname.h>
45 #include <linux/version.h>
46 #include <linux/delay.h>
47 #include <linux/reboot.h>
48 #include <linux/bitops.h>
49 #include <linux/vt_kern.h>
50 #include <linux/kbd_kern.h>
51 #include <linux/keyboard.h>
52 #include <linux/spinlock.h>
53 #include <linux/genhd.h>
54 #include <linux/kernel.h>
55 #include <linux/major.h>
56 #include <linux/swap.h>
57 #include <linux/pm.h>
58 #include <linux/device.h>
59 #include <linux/buffer_head.h>
60 #include <linux/swapops.h>
61 #include <linux/bootmem.h>
62 #include <linux/syscalls.h>
63 #include <linux/console.h>
64 #include <linux/highmem.h>
65 #include <linux/bio.h>
66
67 #include <asm/uaccess.h>
68 #include <asm/mmu_context.h>
69 #include <asm/pgtable.h>
70 #include <asm/io.h>
71
72 #include "power.h"
73
74 /* References to section boundaries */
75 extern char __nosave_begin, __nosave_end;
76
77 extern int is_head_of_free_region(struct page *);
78
79 /* Variables to be preserved over suspend */
80 int pagedir_order_check;
81 int nr_copy_pages_check;
82
83 extern char resume_file[];
84 static dev_t resume_device;
85 /* Local variables that should not be affected by save */
86 unsigned int nr_copy_pages __nosavedata = 0;
87
88 /* Suspend pagedir is allocated before final copy, therefore it
89    must be freed after resume 
90
91    Warning: this is evil. There are actually two pagedirs at time of
92    resume. One is "pagedir_save", which is empty frame allocated at
93    time of suspend, that must be freed. Second is "pagedir_nosave", 
94    allocated at time of resume, that travels through memory not to
95    collide with anything.
96
97    Warning: this is even more evil than it seems. Pagedirs this file
98    talks about are completely different from page directories used by
99    MMU hardware.
100  */
101 suspend_pagedir_t *pagedir_nosave __nosavedata = NULL;
102 static suspend_pagedir_t *pagedir_save;
103 static int pagedir_order __nosavedata = 0;
104
105 #define SWSUSP_SIG      "S1SUSPEND"
106
107 struct swsusp_header {
108         char reserved[PAGE_SIZE - 20 - sizeof(swp_entry_t)];
109         swp_entry_t swsusp_info;
110         char    orig_sig[10];
111         char    sig[10];
112 } __attribute__((packed, aligned(PAGE_SIZE))) swsusp_header;
113
114 struct swsusp_info swsusp_info;
115
116 /*
117  * XXX: We try to keep some more pages free so that I/O operations succeed
118  * without paging. Might this be more?
119  */
120 #define PAGES_FOR_IO    512
121
122 /*
123  * Saving part...
124  */
125
126 /* We memorize in swapfile_used what swap devices are used for suspension */
127 #define SWAPFILE_UNUSED    0
128 #define SWAPFILE_SUSPEND   1    /* This is the suspending device */
129 #define SWAPFILE_IGNORED   2    /* Those are other swap devices ignored for suspension */
130
131 static unsigned short swapfile_used[MAX_SWAPFILES];
132 static unsigned short root_swap;
133
134 static int mark_swapfiles(swp_entry_t prev)
135 {
136         int error;
137
138         rw_swap_page_sync(READ, 
139                           swp_entry(root_swap, 0),
140                           virt_to_page((unsigned long)&swsusp_header));
141         if (!memcmp("SWAP-SPACE",swsusp_header.sig, 10) ||
142             !memcmp("SWAPSPACE2",swsusp_header.sig, 10)) {
143                 memcpy(swsusp_header.orig_sig,swsusp_header.sig, 10);
144                 memcpy(swsusp_header.sig,SWSUSP_SIG, 10);
145                 swsusp_header.swsusp_info = prev;
146                 error = rw_swap_page_sync(WRITE, 
147                                           swp_entry(root_swap, 0),
148                                           virt_to_page((unsigned long)
149                                                        &swsusp_header));
150         } else {
151                 pr_debug("swsusp: Partition is not swap space.\n");
152                 error = -ENODEV;
153         }
154         return error;
155 }
156
157 /*
158  * Check whether the swap device is the specified resume
159  * device, irrespective of whether they are specified by
160  * identical names.
161  *
162  * (Thus, device inode aliasing is allowed.  You can say /dev/hda4
163  * instead of /dev/ide/host0/bus0/target0/lun0/part4 [if using devfs]
164  * and they'll be considered the same device.  This is *necessary* for
165  * devfs, since the resume code can only recognize the form /dev/hda4,
166  * but the suspend code would see the long name.)
167  */
168 static int is_resume_device(const struct swap_info_struct *swap_info)
169 {
170         struct file *file = swap_info->swap_file;
171         struct inode *inode = file->f_dentry->d_inode;
172
173         return S_ISBLK(inode->i_mode) &&
174                 resume_device == MKDEV(imajor(inode), iminor(inode));
175 }
176
177 int swsusp_swap_check(void) /* This is called before saving image */
178 {
179         int i, len;
180         
181         len=strlen(resume_file);
182         root_swap = 0xFFFF;
183         
184         swap_list_lock();
185         for(i=0; i<MAX_SWAPFILES; i++) {
186                 if (swap_info[i].flags == 0) {
187                         swapfile_used[i]=SWAPFILE_UNUSED;
188                 } else {
189                         if(!len) {
190                                 printk(KERN_WARNING "resume= option should be used to set suspend device" );
191                                 if(root_swap == 0xFFFF) {
192                                         swapfile_used[i] = SWAPFILE_SUSPEND;
193                                         root_swap = i;
194                                 } else
195                                         swapfile_used[i] = SWAPFILE_IGNORED;                              
196                         } else {
197                                 /* we ignore all swap devices that are not the resume_file */
198                                 if (is_resume_device(&swap_info[i])) {
199                                         swapfile_used[i] = SWAPFILE_SUSPEND;
200                                         root_swap = i;
201                                 } else {
202                                         swapfile_used[i] = SWAPFILE_IGNORED;
203                                 }
204                         }
205                 }
206         }
207         swap_list_unlock();
208         return (root_swap != 0xffff) ? 0 : -ENODEV;
209 }
210
211 /**
212  * This is called after saving image so modification
213  * will be lost after resume... and that's what we want.
214  * we make the device unusable. A new call to
215  * lock_swapdevices can unlock the devices. 
216  */
217 static void lock_swapdevices(void)
218 {
219         int i;
220
221         swap_list_lock();
222         for(i = 0; i< MAX_SWAPFILES; i++)
223                 if(swapfile_used[i] == SWAPFILE_IGNORED) {
224                         swap_info[i].flags ^= 0xFF;
225                 }
226         swap_list_unlock();
227 }
228
229
230
231 /**
232  *      write_swap_page - Write one page to a fresh swap location.
233  *      @addr:  Address we're writing.
234  *      @loc:   Place to store the entry we used.
235  *
236  *      Allocate a new swap entry and 'sync' it. Note we discard -EIO
237  *      errors. That is an artifact left over from swsusp. It did not 
238  *      check the return of rw_swap_page_sync() at all, since most pages
239  *      written back to swap would return -EIO.
240  *      This is a partial improvement, since we will at least return other
241  *      errors, though we need to eventually fix the damn code.
242  */
243
244 static int write_page(unsigned long addr, swp_entry_t * loc)
245 {
246         swp_entry_t entry;
247         int error = 0;
248
249         entry = get_swap_page();
250         if (swp_offset(entry) && 
251             swapfile_used[swp_type(entry)] == SWAPFILE_SUSPEND) {
252                 error = rw_swap_page_sync(WRITE, entry,
253                                           virt_to_page(addr));
254                 if (error == -EIO)
255                         error = 0;
256                 if (!error)
257                         *loc = entry;
258         } else
259                 error = -ENOSPC;
260         return error;
261 }
262
263
264 /**
265  *      data_free - Free the swap entries used by the saved image.
266  *
267  *      Walk the list of used swap entries and free each one. 
268  *      This is only used for cleanup when suspend fails.
269  */
270
271 static void data_free(void)
272 {
273         swp_entry_t entry;
274         int i;
275
276         for (i = 0; i < nr_copy_pages; i++) {
277                 entry = (pagedir_nosave + i)->swap_address;
278                 if (entry.val)
279                         swap_free(entry);
280                 else
281                         break;
282                 (pagedir_nosave + i)->swap_address = (swp_entry_t){0};
283         }
284 }
285
286
287 /**
288  *      data_write - Write saved image to swap.
289  *
290  *      Walk the list of pages in the image and sync each one to swap.
291  */
292
293 static int data_write(void)
294 {
295         int error = 0;
296         int i;
297
298         printk( "Writing data to swap (%d pages): ", nr_copy_pages );
299         for (i = 0; i < nr_copy_pages && !error; i++) {
300                 if (!(i%100))
301                         printk( "." );
302                 error = write_page((pagedir_nosave+i)->address,
303                                           &((pagedir_nosave+i)->swap_address));
304         }
305         printk(" %d Pages done.\n",i);
306         return error;
307 }
308
309 static void dump_info(void)
310 {
311         pr_debug(" swsusp: Version: %u\n",swsusp_info.version_code);
312         pr_debug(" swsusp: Num Pages: %ld\n",swsusp_info.num_physpages);
313         pr_debug(" swsusp: UTS Sys: %s\n",swsusp_info.uts.sysname);
314         pr_debug(" swsusp: UTS Node: %s\n",swsusp_info.uts.nodename);
315         pr_debug(" swsusp: UTS Release: %s\n",swsusp_info.uts.release);
316         pr_debug(" swsusp: UTS Version: %s\n",swsusp_info.uts.version);
317         pr_debug(" swsusp: UTS Machine: %s\n",swsusp_info.uts.machine);
318         pr_debug(" swsusp: UTS Domain: %s\n",swsusp_info.uts.domainname);
319         pr_debug(" swsusp: CPUs: %d\n",swsusp_info.cpus);
320         pr_debug(" swsusp: Image: %ld Pages\n",swsusp_info.image_pages);
321         pr_debug(" swsusp: Pagedir: %ld Pages\n",swsusp_info.pagedir_pages);
322 }
323
324 static void init_header(void)
325 {
326         memset(&swsusp_info,0,sizeof(swsusp_info));
327         swsusp_info.version_code = LINUX_VERSION_CODE;
328         swsusp_info.num_physpages = num_physpages;
329         memcpy(&swsusp_info.uts,&system_utsname,sizeof(system_utsname));
330
331         swsusp_info.suspend_pagedir = pagedir_nosave;
332         swsusp_info.cpus = num_online_cpus();
333         swsusp_info.image_pages = nr_copy_pages;
334         dump_info();
335 }
336
337 static int close_swap(void)
338 {
339         swp_entry_t entry;
340         int error;
341
342         error = write_page((unsigned long)&swsusp_info,&entry);
343         if (!error) { 
344                 printk( "S" );
345                 error = mark_swapfiles(entry);
346                 printk( "|\n" );
347         }
348         return error;
349 }
350
351 /**
352  *      free_pagedir_entries - Free pages used by the page directory.
353  *
354  *      This is used during suspend for error recovery.
355  */
356
357 static void free_pagedir_entries(void)
358 {
359         int i;
360
361         for (i = 0; i < swsusp_info.pagedir_pages; i++)
362                 swap_free(swsusp_info.pagedir[i]);
363 }
364
365
366 /**
367  *      write_pagedir - Write the array of pages holding the page directory.
368  *      @last:  Last swap entry we write (needed for header).
369  */
370
371 static int write_pagedir(void)
372 {
373         unsigned long addr = (unsigned long)pagedir_nosave;
374         int error = 0;
375         int n = SUSPEND_PD_PAGES(nr_copy_pages);
376         int i;
377
378         swsusp_info.pagedir_pages = n;
379         printk( "Writing pagedir (%d pages)\n", n);
380         for (i = 0; i < n && !error; i++, addr += PAGE_SIZE)
381                 error = write_page(addr, &swsusp_info.pagedir[i]);
382         return error;
383 }
384
385 /**
386  *      write_suspend_image - Write entire image and metadata.
387  *
388  */
389
390 static int write_suspend_image(void)
391 {
392         int error;
393
394         init_header();
395         if ((error = data_write()))
396                 goto FreeData;
397
398         if ((error = write_pagedir()))
399                 goto FreePagedir;
400
401         if ((error = close_swap()))
402                 goto FreePagedir;
403  Done:
404         return error;
405  FreePagedir:
406         free_pagedir_entries();
407  FreeData:
408         data_free();
409         goto Done;
410 }
411
412
413 #ifdef CONFIG_HIGHMEM
414 struct highmem_page {
415         char *data;
416         struct page *page;
417         struct highmem_page *next;
418 };
419
420 struct highmem_page *highmem_copy = NULL;
421
422 static int save_highmem_zone(struct zone *zone)
423 {
424         unsigned long zone_pfn;
425         for (zone_pfn = 0; zone_pfn < zone->spanned_pages; ++zone_pfn) {
426                 struct page *page;
427                 struct highmem_page *save;
428                 void *kaddr;
429                 unsigned long pfn = zone_pfn + zone->zone_start_pfn;
430                 int chunk_size;
431
432                 if (!(pfn%1000))
433                         printk(".");
434                 if (!pfn_valid(pfn))
435                         continue;
436                 page = pfn_to_page(pfn);
437                 /*
438                  * This condition results from rvmalloc() sans vmalloc_32()
439                  * and architectural memory reservations. This should be
440                  * corrected eventually when the cases giving rise to this
441                  * are better understood.
442                  */
443                 if (PageReserved(page)) {
444                         printk("highmem reserved page?!\n");
445                         continue;
446                 }
447                 if ((chunk_size = is_head_of_free_region(page))) {
448                         pfn += chunk_size - 1;
449                         zone_pfn += chunk_size - 1;
450                         continue;
451                 }
452                 save = kmalloc(sizeof(struct highmem_page), GFP_ATOMIC);
453                 if (!save)
454                         return -ENOMEM;
455                 save->next = highmem_copy;
456                 save->page = page;
457                 save->data = (void *) get_zeroed_page(GFP_ATOMIC);
458                 if (!save->data) {
459                         kfree(save);
460                         return -ENOMEM;
461                 }
462                 kaddr = kmap_atomic(page, KM_USER0);
463                 memcpy(save->data, kaddr, PAGE_SIZE);
464                 kunmap_atomic(kaddr, KM_USER0);
465                 highmem_copy = save;
466         }
467         return 0;
468 }
469 #endif /* CONFIG_HIGHMEM */
470
471
472 static int save_highmem(void)
473 {
474 #ifdef CONFIG_HIGHMEM
475         struct zone *zone;
476         int res = 0;
477
478         pr_debug("swsusp: Saving Highmem\n");
479         for_each_zone(zone) {
480                 if (is_highmem(zone))
481                         res = save_highmem_zone(zone);
482                 if (res)
483                         return res;
484         }
485 #endif
486         return 0;
487 }
488
489 static int restore_highmem(void)
490 {
491 #ifdef CONFIG_HIGHMEM
492         printk("swsusp: Restoring Highmem\n");
493         while (highmem_copy) {
494                 struct highmem_page *save = highmem_copy;
495                 void *kaddr;
496                 highmem_copy = save->next;
497
498                 kaddr = kmap_atomic(save->page, KM_USER0);
499                 memcpy(kaddr, save->data, PAGE_SIZE);
500                 kunmap_atomic(kaddr, KM_USER0);
501                 free_page((long) save->data);
502                 kfree(save);
503         }
504 #endif
505         return 0;
506 }
507
508
509 static int pfn_is_nosave(unsigned long pfn)
510 {
511         unsigned long nosave_begin_pfn = __pa(&__nosave_begin) >> PAGE_SHIFT;
512         unsigned long nosave_end_pfn = PAGE_ALIGN(__pa(&__nosave_end)) >> PAGE_SHIFT;
513         return (pfn >= nosave_begin_pfn) && (pfn < nosave_end_pfn);
514 }
515
516 /**
517  *      saveable - Determine whether a page should be cloned or not.
518  *      @pfn:   The page
519  *
520  *      We save a page if it's Reserved, and not in the range of pages
521  *      statically defined as 'unsaveable', or if it isn't reserved, and
522  *      isn't part of a free chunk of pages.
523  *      If it is part of a free chunk, we update @pfn to point to the last 
524  *      page of the chunk.
525  */
526
527 static int saveable(struct zone * zone, unsigned long * zone_pfn)
528 {
529         unsigned long pfn = *zone_pfn + zone->zone_start_pfn;
530         unsigned long chunk_size;
531         struct page * page;
532
533         if (!pfn_valid(pfn))
534                 return 0;
535
536         if (!(pfn%1000))
537                 printk(".");
538         page = pfn_to_page(pfn);
539         BUG_ON(PageReserved(page) && PageNosave(page));
540         if (PageNosave(page))
541                 return 0;
542         if (PageReserved(page) && pfn_is_nosave(pfn)) {
543                 pr_debug("[nosave pfn 0x%lx]", pfn);
544                 return 0;
545         }
546         if ((chunk_size = is_head_of_free_region(page))) {
547                 *zone_pfn += chunk_size - 1;
548                 return 0;
549         }
550
551         return 1;
552 }
553
554 static void count_data_pages(void)
555 {
556         struct zone *zone;
557         unsigned long zone_pfn;
558
559         nr_copy_pages = 0;
560
561         for_each_zone(zone) {
562                 if (!is_highmem(zone)) {
563                         for (zone_pfn = 0; zone_pfn < zone->spanned_pages; ++zone_pfn)
564                                 nr_copy_pages += saveable(zone, &zone_pfn);
565                 }
566         }
567 }
568
569
570 static void copy_data_pages(void)
571 {
572         struct zone *zone;
573         unsigned long zone_pfn;
574         struct pbe * pbe = pagedir_nosave;
575         
576         for_each_zone(zone) {
577                 if (!is_highmem(zone))
578                         for (zone_pfn = 0; zone_pfn < zone->spanned_pages; ++zone_pfn) {
579                                 if (saveable(zone, &zone_pfn)) {
580                                         struct page * page;
581                                         page = pfn_to_page(zone_pfn + zone->zone_start_pfn);
582                                         pbe->orig_address = (long) page_address(page);
583                                         /* copy_page is no usable for copying task structs. */
584                                         memcpy((void *)pbe->address, (void *)pbe->orig_address, PAGE_SIZE);
585                                         pbe++;
586                                 }
587                         }
588         }
589 }
590
591
592 static void free_suspend_pagedir_zone(struct zone *zone, unsigned long pagedir)
593 {
594         unsigned long zone_pfn, pagedir_end, pagedir_pfn, pagedir_end_pfn;
595         pagedir_end = pagedir + (PAGE_SIZE << pagedir_order);
596         pagedir_pfn = __pa(pagedir) >> PAGE_SHIFT;
597         pagedir_end_pfn = __pa(pagedir_end) >> PAGE_SHIFT;
598         for (zone_pfn = 0; zone_pfn < zone->spanned_pages; ++zone_pfn) {
599                 struct page *page;
600                 unsigned long pfn = zone_pfn + zone->zone_start_pfn;
601                 if (!pfn_valid(pfn))
602                         continue;
603                 page = pfn_to_page(pfn);
604                 if (!TestClearPageNosave(page))
605                         continue;
606                 else if (pfn >= pagedir_pfn && pfn < pagedir_end_pfn)
607                         continue;
608                 __free_page(page);
609         }
610 }
611
612 void swsusp_free(void)
613 {
614         unsigned long p = (unsigned long)pagedir_save;
615         struct zone *zone;
616         for_each_zone(zone) {
617                 if (!is_highmem(zone))
618                         free_suspend_pagedir_zone(zone, p);
619         }
620         free_pages(p, pagedir_order);
621 }
622
623
624 /**
625  *      calc_order - Determine the order of allocation needed for pagedir_save.
626  *
627  *      This looks tricky, but is just subtle. Please fix it some time.
628  *      Since there are %nr_copy_pages worth of pages in the snapshot, we need
629  *      to allocate enough contiguous space to hold 
630  *              (%nr_copy_pages * sizeof(struct pbe)), 
631  *      which has the saved/orig locations of the page.. 
632  *
633  *      SUSPEND_PD_PAGES() tells us how many pages we need to hold those 
634  *      structures, then we call get_bitmask_order(), which will tell us the
635  *      last bit set in the number, starting with 1. (If we need 30 pages, that
636  *      is 0x0000001e in hex. The last bit is the 5th, which is the order we 
637  *      would use to allocate 32 contiguous pages).
638  *
639  *      Since we also need to save those pages, we add the number of pages that
640  *      we need to nr_copy_pages, and in case of an overflow, do the 
641  *      calculation again to update the number of pages needed. 
642  *
643  *      With this model, we will tend to waste a lot of memory if we just cross
644  *      an order boundary. Plus, the higher the order of allocation that we try
645  *      to do, the more likely we are to fail in a low-memory situtation 
646  *      (though we're unlikely to get this far in such a case, since swsusp 
647  *      requires half of memory to be free anyway).
648  */
649
650
651 static void calc_order(void)
652 {
653         int diff = 0;
654         int order = 0;
655
656         do {
657                 diff = get_bitmask_order(SUSPEND_PD_PAGES(nr_copy_pages)) - order;
658                 if (diff) {
659                         order += diff;
660                         nr_copy_pages += 1 << diff;
661                 }
662         } while(diff);
663         pagedir_order = order;
664 }
665
666
667 /**
668  *      alloc_pagedir - Allocate the page directory.
669  *
670  *      First, determine exactly how many contiguous pages we need and
671  *      allocate them.
672  */
673
674 static int alloc_pagedir(void)
675 {
676         calc_order();
677         pagedir_save = (suspend_pagedir_t *)__get_free_pages(GFP_ATOMIC | __GFP_COLD,
678                                                              pagedir_order);
679         if (!pagedir_save)
680                 return -ENOMEM;
681         memset(pagedir_save, 0, (1 << pagedir_order) * PAGE_SIZE);
682         pagedir_nosave = pagedir_save;
683         return 0;
684 }
685
686
687 /**
688  *      alloc_image_pages - Allocate pages for the snapshot.
689  *
690  */
691
692 static int alloc_image_pages(void)
693 {
694         struct pbe * p;
695         int i;
696
697         for (i = 0, p = pagedir_save; i < nr_copy_pages; i++, p++) {
698                 p->address = get_zeroed_page(GFP_ATOMIC | __GFP_COLD);
699                 if(!p->address)
700                         goto Error;
701                 SetPageNosave(virt_to_page(p->address));
702         }
703         return 0;
704  Error:
705         do { 
706                 if (p->address)
707                         free_page(p->address);
708                 p->address = 0;
709         } while (p-- > pagedir_save);
710         return -ENOMEM;
711 }
712
713
714 /**
715  *      enough_free_mem - Make sure we enough free memory to snapshot.
716  *
717  *      Returns TRUE or FALSE after checking the number of available 
718  *      free pages.
719  */
720
721 static int enough_free_mem(void)
722 {
723         if (nr_free_pages() < (nr_copy_pages + PAGES_FOR_IO)) {
724                 pr_debug("swsusp: Not enough free pages: Have %d\n",
725                          nr_free_pages());
726                 return 0;
727         }
728         return 1;
729 }
730
731
732 /**
733  *      enough_swap - Make sure we have enough swap to save the image.
734  *
735  *      Returns TRUE or FALSE after checking the total amount of swap 
736  *      space avaiable.
737  *
738  *      FIXME: si_swapinfo(&i) returns all swap devices information.
739  *      We should only consider resume_device. 
740  */
741
742 static int enough_swap(void)
743 {
744         struct sysinfo i;
745
746         si_swapinfo(&i);
747         if (i.freeswap < (nr_copy_pages + PAGES_FOR_IO))  {
748                 pr_debug("swsusp: Not enough swap. Need %ld\n",i.freeswap);
749                 return 0;
750         }
751         return 1;
752 }
753
754 static int swsusp_alloc(void)
755 {
756         int error;
757
758         pr_debug("suspend: (pages needed: %d + %d free: %d)\n",
759                  nr_copy_pages, PAGES_FOR_IO, nr_free_pages());
760
761         pagedir_nosave = NULL;
762         if (!enough_free_mem())
763                 return -ENOMEM;
764
765         if (!enough_swap())
766                 return -ENOSPC;
767
768         if ((error = alloc_pagedir())) {
769                 pr_debug("suspend: Allocating pagedir failed.\n");
770                 return error;
771         }
772         if ((error = alloc_image_pages())) {
773                 pr_debug("suspend: Allocating image pages failed.\n");
774                 swsusp_free();
775                 return error;
776         }
777
778         nr_copy_pages_check = nr_copy_pages;
779         pagedir_order_check = pagedir_order;
780         return 0;
781 }
782
783 int suspend_prepare_image(void)
784 {
785         unsigned int nr_needed_pages = 0;
786         int error;
787
788         pr_debug("swsusp: critical section: \n");
789         if (save_highmem()) {
790                 printk(KERN_CRIT "Suspend machine: Not enough free pages for highmem\n");
791                 return -ENOMEM;
792         }
793
794         drain_local_pages();
795         count_data_pages();
796         printk("swsusp: Need to copy %u pages\n",nr_copy_pages);
797         nr_needed_pages = nr_copy_pages + PAGES_FOR_IO;
798
799         error = swsusp_alloc();
800         if (error)
801                 return error;
802         
803         /* During allocating of suspend pagedir, new cold pages may appear. 
804          * Kill them.
805          */
806         drain_local_pages();
807         copy_data_pages();
808
809         /*
810          * End of critical section. From now on, we can write to memory,
811          * but we should not touch disk. This specially means we must _not_
812          * touch swap space! Except we must write out our image of course.
813          */
814
815         printk("swsusp: critical section/: done (%d pages copied)\n", nr_copy_pages );
816         return 0;
817 }
818
819
820 /* It is important _NOT_ to umount filesystems at this point. We want
821  * them synced (in case something goes wrong) but we DO not want to mark
822  * filesystem clean: it is not. (And it does not matter, if we resume
823  * correctly, we'll mark system clean, anyway.)
824  */
825 int swsusp_write(void)
826 {
827         int error;
828         device_resume();
829         lock_swapdevices();
830         error = write_suspend_image();
831         /* This will unlock ignored swap devices since writing is finished */
832         lock_swapdevices();
833         return error;
834
835 }
836
837
838 extern asmlinkage int swsusp_arch_suspend(void);
839 extern asmlinkage int swsusp_arch_resume(void);
840
841
842 asmlinkage int swsusp_save(void)
843 {
844         int error = 0;
845
846         if ((error = swsusp_swap_check()))
847                 return error;
848         return suspend_prepare_image();
849 }
850
851 int swsusp_suspend(void)
852 {
853         int error;
854         if ((error = arch_prepare_suspend()))
855                 return error;
856         local_irq_disable();
857         save_processor_state();
858         error = swsusp_arch_suspend();
859         /* Restore control flow magically appears here */
860         restore_processor_state();
861         restore_highmem();
862         local_irq_enable();
863         return error;
864 }
865
866
867 asmlinkage int swsusp_restore(void)
868 {
869         BUG_ON (nr_copy_pages_check != nr_copy_pages);
870         BUG_ON (pagedir_order_check != pagedir_order);
871         
872         /* Even mappings of "global" things (vmalloc) need to be fixed */
873         __flush_tlb_global();
874         return 0;
875 }
876
877 int swsusp_resume(void)
878 {
879         int error;
880         local_irq_disable();
881         /* We'll ignore saved state, but this gets preempt count (etc) right */
882         save_processor_state();
883         error = swsusp_arch_resume();
884         /* Code below is only ever reached in case of failure. Otherwise
885          * execution continues at place where swsusp_arch_suspend was called
886          */
887         BUG_ON(!error);
888         restore_processor_state();
889         restore_highmem();
890         local_irq_enable();
891         return error;
892 }
893
894
895
896 /* More restore stuff */
897
898 #define does_collide(addr) does_collide_order(pagedir_nosave, addr, 0)
899
900 /*
901  * Returns true if given address/order collides with any orig_address 
902  */
903 static int __init does_collide_order(suspend_pagedir_t *pagedir, unsigned long addr,
904                 int order)
905 {
906         int i;
907         unsigned long addre = addr + (PAGE_SIZE<<order);
908         
909         for (i=0; i < nr_copy_pages; i++)
910                 if ((pagedir+i)->orig_address >= addr &&
911                         (pagedir+i)->orig_address < addre)
912                         return 1;
913
914         return 0;
915 }
916
917 /*
918  * We check here that pagedir & pages it points to won't collide with pages
919  * where we're going to restore from the loaded pages later
920  */
921 static int __init check_pagedir(void)
922 {
923         int i;
924
925         for(i=0; i < nr_copy_pages; i++) {
926                 unsigned long addr;
927
928                 do {
929                         addr = get_zeroed_page(GFP_ATOMIC);
930                         if(!addr)
931                                 return -ENOMEM;
932                 } while (does_collide(addr));
933
934                 (pagedir_nosave+i)->address = addr;
935         }
936         return 0;
937 }
938
939 static int __init swsusp_pagedir_relocate(void)
940 {
941         /*
942          * We have to avoid recursion (not to overflow kernel stack),
943          * and that's why code looks pretty cryptic 
944          */
945         suspend_pagedir_t *old_pagedir = pagedir_nosave;
946         void **eaten_memory = NULL;
947         void **c = eaten_memory, *m, *f;
948         int ret = 0;
949
950         printk("Relocating pagedir ");
951
952         if (!does_collide_order(old_pagedir, (unsigned long)old_pagedir, pagedir_order)) {
953                 printk("not necessary\n");
954                 return check_pagedir();
955         }
956
957         while ((m = (void *) __get_free_pages(GFP_ATOMIC, pagedir_order)) != NULL) {
958                 if (!does_collide_order(old_pagedir, (unsigned long)m, pagedir_order))
959                         break;
960                 eaten_memory = m;
961                 printk( "." ); 
962                 *eaten_memory = c;
963                 c = eaten_memory;
964         }
965
966         if (!m) {
967                 printk("out of memory\n");
968                 ret = -ENOMEM;
969         } else {
970                 pagedir_nosave =
971                         memcpy(m, old_pagedir, PAGE_SIZE << pagedir_order);
972         }
973
974         c = eaten_memory;
975         while (c) {
976                 printk(":");
977                 f = c;
978                 c = *c;
979                 free_pages((unsigned long)f, pagedir_order);
980         }
981         printk("|\n");
982         return check_pagedir();
983 }
984
985 /**
986  *      Using bio to read from swap.
987  *      This code requires a bit more work than just using buffer heads
988  *      but, it is the recommended way for 2.5/2.6.
989  *      The following are to signal the beginning and end of I/O. Bios
990  *      finish asynchronously, while we want them to happen synchronously.
991  *      A simple atomic_t, and a wait loop take care of this problem.
992  */
993
994 static atomic_t io_done = ATOMIC_INIT(0);
995
996 static void start_io(void)
997 {
998         atomic_set(&io_done,1);
999 }
1000
1001 static int end_io(struct bio * bio, unsigned int num, int err)
1002 {
1003         atomic_set(&io_done,0);
1004         return 0;
1005 }
1006
1007 static void wait_io(void)
1008 {
1009         while(atomic_read(&io_done))
1010                 io_schedule();
1011 }
1012
1013
1014 static struct block_device * resume_bdev;
1015
1016 /**
1017  *      submit - submit BIO request.
1018  *      @rw:    READ or WRITE.
1019  *      @off    physical offset of page.
1020  *      @page:  page we're reading or writing.
1021  *
1022  *      Straight from the textbook - allocate and initialize the bio.
1023  *      If we're writing, make sure the page is marked as dirty.
1024  *      Then submit it and wait.
1025  */
1026
1027 static int submit(int rw, pgoff_t page_off, void * page)
1028 {
1029         int error = 0;
1030         struct bio * bio;
1031
1032         bio = bio_alloc(GFP_ATOMIC, 1);
1033         if (!bio)
1034                 return -ENOMEM;
1035         bio->bi_sector = page_off * (PAGE_SIZE >> 9);
1036         bio_get(bio);
1037         bio->bi_bdev = resume_bdev;
1038         bio->bi_end_io = end_io;
1039
1040         if (bio_add_page(bio, virt_to_page(page), PAGE_SIZE, 0) < PAGE_SIZE) {
1041                 printk("swsusp: ERROR: adding page to bio at %ld\n",page_off);
1042                 error = -EFAULT;
1043                 goto Done;
1044         }
1045
1046         if (rw == WRITE)
1047                 bio_set_pages_dirty(bio);
1048         start_io();
1049         submit_bio(rw | (1 << BIO_RW_SYNC), bio);
1050         wait_io();
1051  Done:
1052         bio_put(bio);
1053         return error;
1054 }
1055
1056 int bio_read_page(pgoff_t page_off, void * page)
1057 {
1058         return submit(READ, page_off, page);
1059 }
1060
1061 int bio_write_page(pgoff_t page_off, void * page)
1062 {
1063         return submit(WRITE, page_off, page);
1064 }
1065
1066 /*
1067  * Sanity check if this image makes sense with this kernel/swap context
1068  * I really don't think that it's foolproof but more than nothing..
1069  */
1070
1071 static const char * __init sanity_check(void)
1072 {
1073         dump_info();
1074         if(swsusp_info.version_code != LINUX_VERSION_CODE)
1075                 return "kernel version";
1076         if(swsusp_info.num_physpages != num_physpages)
1077                 return "memory size";
1078         if (strcmp(swsusp_info.uts.sysname,system_utsname.sysname))
1079                 return "system type";
1080         if (strcmp(swsusp_info.uts.release,system_utsname.release))
1081                 return "kernel release";
1082         if (strcmp(swsusp_info.uts.version,system_utsname.version))
1083                 return "version";
1084         if (strcmp(swsusp_info.uts.machine,system_utsname.machine))
1085                 return "machine";
1086         if(swsusp_info.cpus != num_online_cpus())
1087                 return "number of cpus";
1088         return NULL;
1089 }
1090
1091
1092 static int __init check_header(void)
1093 {
1094         const char * reason = NULL;
1095         int error;
1096
1097         if ((error = bio_read_page(swp_offset(swsusp_header.swsusp_info), &swsusp_info)))
1098                 return error;
1099
1100         /* Is this same machine? */
1101         if ((reason = sanity_check())) {
1102                 printk(KERN_ERR "swsusp: Resume mismatch: %s\n",reason);
1103                 return -EPERM;
1104         }
1105         nr_copy_pages = swsusp_info.image_pages;
1106         return error;
1107 }
1108
1109 static int __init check_sig(void)
1110 {
1111         int error;
1112
1113         memset(&swsusp_header, 0, sizeof(swsusp_header));
1114         if ((error = bio_read_page(0, &swsusp_header)))
1115                 return error;
1116         if (!memcmp(SWSUSP_SIG, swsusp_header.sig, 10)) {
1117                 memcpy(swsusp_header.sig, swsusp_header.orig_sig, 10);
1118
1119                 /*
1120                  * Reset swap signature now.
1121                  */
1122                 error = bio_write_page(0, &swsusp_header);
1123         } else { 
1124                 pr_debug(KERN_ERR "swsusp: Invalid partition type.\n");
1125                 return -EINVAL;
1126         }
1127         if (!error)
1128                 pr_debug("swsusp: Signature found, resuming\n");
1129         return error;
1130 }
1131
1132 /**
1133  *      swsusp_read_data - Read image pages from swap.
1134  *
1135  *      You do not need to check for overlaps, check_pagedir()
1136  *      already did that.
1137  */
1138
1139 static int __init data_read(void)
1140 {
1141         struct pbe * p;
1142         int error;
1143         int i;
1144
1145         if ((error = swsusp_pagedir_relocate()))
1146                 return error;
1147
1148         printk( "Reading image data (%d pages): ", nr_copy_pages );
1149         for(i = 0, p = pagedir_nosave; i < nr_copy_pages && !error; i++, p++) {
1150                 if (!(i%100))
1151                         printk( "." );
1152                 error = bio_read_page(swp_offset(p->swap_address),
1153                                   (void *)p->address);
1154         }
1155         printk(" %d done.\n",i);
1156         return error;
1157
1158 }
1159
1160 extern dev_t __init name_to_dev_t(const char *line);
1161
1162 static int __init read_pagedir(void)
1163 {
1164         unsigned long addr;
1165         int i, n = swsusp_info.pagedir_pages;
1166         int error = 0;
1167
1168         pagedir_order = get_bitmask_order(n);
1169
1170         addr =__get_free_pages(GFP_ATOMIC, pagedir_order);
1171         if (!addr)
1172                 return -ENOMEM;
1173         pagedir_nosave = (struct pbe *)addr;
1174
1175         pr_debug("pmdisk: Reading pagedir (%d Pages)\n",n);
1176
1177         for (i = 0; i < n && !error; i++, addr += PAGE_SIZE) {
1178                 unsigned long offset = swp_offset(swsusp_info.pagedir[i]);
1179                 if (offset)
1180                         error = bio_read_page(offset, (void *)addr);
1181                 else
1182                         error = -EFAULT;
1183         }
1184         if (error)
1185                 free_pages((unsigned long)pagedir_nosave, pagedir_order);
1186         return error;
1187 }
1188
1189 static int __init read_suspend_image(void)
1190 {
1191         int error = 0;
1192
1193         if ((error = check_sig()))
1194                 return error;
1195         if ((error = check_header()))
1196                 return error;
1197         if ((error = read_pagedir()))
1198                 return error;
1199         if ((error = data_read()))
1200                 free_pages((unsigned long)pagedir_nosave, pagedir_order);
1201         return error;
1202 }
1203
1204 /**
1205  *      pmdisk_read - Read saved image from swap.
1206  */
1207
1208 int __init swsusp_read(void)
1209 {
1210         int error;
1211
1212         if (!strlen(resume_file))
1213                 return -ENOENT;
1214
1215         resume_device = name_to_dev_t(resume_file);
1216         pr_debug("swsusp: Resume From Partition: %s\n", resume_file);
1217
1218         resume_bdev = open_by_devnum(resume_device, FMODE_READ);
1219         if (!IS_ERR(resume_bdev)) {
1220                 set_blocksize(resume_bdev, PAGE_SIZE);
1221                 error = read_suspend_image();
1222                 blkdev_put(resume_bdev);
1223         } else
1224                 error = PTR_ERR(resume_bdev);
1225
1226         if (!error)
1227                 pr_debug("Reading resume file was successful\n");
1228         else
1229                 pr_debug("pmdisk: Error %d resuming\n", error);
1230         return error;
1231 }