upgrade to linux 2.6.10-1.12_FC2
[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         unsigned int mod = nr_copy_pages / 100;
298
299         if (!mod)
300                 mod = 1;
301
302         printk( "Writing data to swap (%d pages)...     ", nr_copy_pages );
303         for (i = 0; i < nr_copy_pages && !error; i++) {
304                 if (!(i%mod))
305                         printk( "\b\b\b\b%3d%%", i / mod );
306                 error = write_page((pagedir_nosave+i)->address,
307                                           &((pagedir_nosave+i)->swap_address));
308         }
309         printk("\b\b\b\bdone\n");
310         return error;
311 }
312
313 static void dump_info(void)
314 {
315         pr_debug(" swsusp: Version: %u\n",swsusp_info.version_code);
316         pr_debug(" swsusp: Num Pages: %ld\n",swsusp_info.num_physpages);
317         pr_debug(" swsusp: UTS Sys: %s\n",swsusp_info.uts.sysname);
318         pr_debug(" swsusp: UTS Node: %s\n",swsusp_info.uts.nodename);
319         pr_debug(" swsusp: UTS Release: %s\n",swsusp_info.uts.release);
320         pr_debug(" swsusp: UTS Version: %s\n",swsusp_info.uts.version);
321         pr_debug(" swsusp: UTS Machine: %s\n",swsusp_info.uts.machine);
322         pr_debug(" swsusp: UTS Domain: %s\n",swsusp_info.uts.domainname);
323         pr_debug(" swsusp: CPUs: %d\n",swsusp_info.cpus);
324         pr_debug(" swsusp: Image: %ld Pages\n",swsusp_info.image_pages);
325         pr_debug(" swsusp: Pagedir: %ld Pages\n",swsusp_info.pagedir_pages);
326 }
327
328 static void init_header(void)
329 {
330         memset(&swsusp_info,0,sizeof(swsusp_info));
331         swsusp_info.version_code = LINUX_VERSION_CODE;
332         swsusp_info.num_physpages = num_physpages;
333         memcpy(&swsusp_info.uts,&system_utsname,sizeof(system_utsname));
334
335         swsusp_info.suspend_pagedir = pagedir_nosave;
336         swsusp_info.cpus = num_online_cpus();
337         swsusp_info.image_pages = nr_copy_pages;
338         dump_info();
339 }
340
341 static int close_swap(void)
342 {
343         swp_entry_t entry;
344         int error;
345
346         error = write_page((unsigned long)&swsusp_info,&entry);
347         if (!error) { 
348                 printk( "S" );
349                 error = mark_swapfiles(entry);
350                 printk( "|\n" );
351         }
352         return error;
353 }
354
355 /**
356  *      free_pagedir_entries - Free pages used by the page directory.
357  *
358  *      This is used during suspend for error recovery.
359  */
360
361 static void free_pagedir_entries(void)
362 {
363         int i;
364
365         for (i = 0; i < swsusp_info.pagedir_pages; i++)
366                 swap_free(swsusp_info.pagedir[i]);
367 }
368
369
370 /**
371  *      write_pagedir - Write the array of pages holding the page directory.
372  *      @last:  Last swap entry we write (needed for header).
373  */
374
375 static int write_pagedir(void)
376 {
377         unsigned long addr = (unsigned long)pagedir_nosave;
378         int error = 0;
379         int n = SUSPEND_PD_PAGES(nr_copy_pages);
380         int i;
381
382         swsusp_info.pagedir_pages = n;
383         printk( "Writing pagedir (%d pages)\n", n);
384         for (i = 0; i < n && !error; i++, addr += PAGE_SIZE)
385                 error = write_page(addr, &swsusp_info.pagedir[i]);
386         return error;
387 }
388
389 /**
390  *      write_suspend_image - Write entire image and metadata.
391  *
392  */
393
394 static int write_suspend_image(void)
395 {
396         int error;
397
398         init_header();
399         if ((error = data_write()))
400                 goto FreeData;
401
402         if ((error = write_pagedir()))
403                 goto FreePagedir;
404
405         if ((error = close_swap()))
406                 goto FreePagedir;
407  Done:
408         return error;
409  FreePagedir:
410         free_pagedir_entries();
411  FreeData:
412         data_free();
413         goto Done;
414 }
415
416
417 #ifdef CONFIG_HIGHMEM
418 struct highmem_page {
419         char *data;
420         struct page *page;
421         struct highmem_page *next;
422 };
423
424 struct highmem_page *highmem_copy = NULL;
425
426 static int save_highmem_zone(struct zone *zone)
427 {
428         unsigned long zone_pfn;
429         for (zone_pfn = 0; zone_pfn < zone->spanned_pages; ++zone_pfn) {
430                 struct page *page;
431                 struct highmem_page *save;
432                 void *kaddr;
433                 unsigned long pfn = zone_pfn + zone->zone_start_pfn;
434                 int chunk_size;
435
436                 if (!(pfn%1000))
437                         printk(".");
438                 if (!pfn_valid(pfn))
439                         continue;
440                 page = pfn_to_page(pfn);
441                 /*
442                  * This condition results from rvmalloc() sans vmalloc_32()
443                  * and architectural memory reservations. This should be
444                  * corrected eventually when the cases giving rise to this
445                  * are better understood.
446                  */
447                 if (PageReserved(page)) {
448                         printk("highmem reserved page?!\n");
449                         continue;
450                 }
451                 if ((chunk_size = is_head_of_free_region(page))) {
452                         pfn += chunk_size - 1;
453                         zone_pfn += chunk_size - 1;
454                         continue;
455                 }
456                 save = kmalloc(sizeof(struct highmem_page), GFP_ATOMIC);
457                 if (!save)
458                         return -ENOMEM;
459                 save->next = highmem_copy;
460                 save->page = page;
461                 save->data = (void *) get_zeroed_page(GFP_ATOMIC);
462                 if (!save->data) {
463                         kfree(save);
464                         return -ENOMEM;
465                 }
466                 kaddr = kmap_atomic(page, KM_USER0);
467                 memcpy(save->data, kaddr, PAGE_SIZE);
468                 kunmap_atomic(kaddr, KM_USER0);
469                 highmem_copy = save;
470         }
471         return 0;
472 }
473 #endif /* CONFIG_HIGHMEM */
474
475
476 static int save_highmem(void)
477 {
478 #ifdef CONFIG_HIGHMEM
479         struct zone *zone;
480         int res = 0;
481
482         pr_debug("swsusp: Saving Highmem\n");
483         for_each_zone(zone) {
484                 if (is_highmem(zone))
485                         res = save_highmem_zone(zone);
486                 if (res)
487                         return res;
488         }
489 #endif
490         return 0;
491 }
492
493 static int restore_highmem(void)
494 {
495 #ifdef CONFIG_HIGHMEM
496         printk("swsusp: Restoring Highmem\n");
497         while (highmem_copy) {
498                 struct highmem_page *save = highmem_copy;
499                 void *kaddr;
500                 highmem_copy = save->next;
501
502                 kaddr = kmap_atomic(save->page, KM_USER0);
503                 memcpy(kaddr, save->data, PAGE_SIZE);
504                 kunmap_atomic(kaddr, KM_USER0);
505                 free_page((long) save->data);
506                 kfree(save);
507         }
508 #endif
509         return 0;
510 }
511
512
513 static int pfn_is_nosave(unsigned long pfn)
514 {
515         unsigned long nosave_begin_pfn = __pa(&__nosave_begin) >> PAGE_SHIFT;
516         unsigned long nosave_end_pfn = PAGE_ALIGN(__pa(&__nosave_end)) >> PAGE_SHIFT;
517         return (pfn >= nosave_begin_pfn) && (pfn < nosave_end_pfn);
518 }
519
520 /**
521  *      saveable - Determine whether a page should be cloned or not.
522  *      @pfn:   The page
523  *
524  *      We save a page if it's Reserved, and not in the range of pages
525  *      statically defined as 'unsaveable', or if it isn't reserved, and
526  *      isn't part of a free chunk of pages.
527  *      If it is part of a free chunk, we update @pfn to point to the last 
528  *      page of the chunk.
529  */
530
531 static int saveable(struct zone * zone, unsigned long * zone_pfn)
532 {
533         unsigned long pfn = *zone_pfn + zone->zone_start_pfn;
534         unsigned long chunk_size;
535         struct page * page;
536
537         if (!pfn_valid(pfn))
538                 return 0;
539
540         if (!(pfn%1000))
541                 printk(".");
542         page = pfn_to_page(pfn);
543         BUG_ON(PageReserved(page) && PageNosave(page));
544         if (PageNosave(page))
545                 return 0;
546         if (PageReserved(page) && pfn_is_nosave(pfn)) {
547                 pr_debug("[nosave pfn 0x%lx]", pfn);
548                 return 0;
549         }
550         if ((chunk_size = is_head_of_free_region(page))) {
551                 *zone_pfn += chunk_size - 1;
552                 return 0;
553         }
554
555         return 1;
556 }
557
558 static void count_data_pages(void)
559 {
560         struct zone *zone;
561         unsigned long zone_pfn;
562
563         nr_copy_pages = 0;
564
565         for_each_zone(zone) {
566                 if (!is_highmem(zone)) {
567                         for (zone_pfn = 0; zone_pfn < zone->spanned_pages; ++zone_pfn)
568                                 nr_copy_pages += saveable(zone, &zone_pfn);
569                 }
570         }
571 }
572
573
574 static void copy_data_pages(void)
575 {
576         struct zone *zone;
577         unsigned long zone_pfn;
578         struct pbe * pbe = pagedir_nosave;
579         
580         for_each_zone(zone) {
581                 if (!is_highmem(zone))
582                         for (zone_pfn = 0; zone_pfn < zone->spanned_pages; ++zone_pfn) {
583                                 if (saveable(zone, &zone_pfn)) {
584                                         struct page * page;
585                                         page = pfn_to_page(zone_pfn + zone->zone_start_pfn);
586                                         pbe->orig_address = (long) page_address(page);
587                                         /* copy_page is no usable for copying task structs. */
588                                         memcpy((void *)pbe->address, (void *)pbe->orig_address, PAGE_SIZE);
589                                         pbe++;
590                                 }
591                         }
592         }
593 }
594
595
596 static void free_suspend_pagedir_zone(struct zone *zone, unsigned long pagedir)
597 {
598         unsigned long zone_pfn, pagedir_end, pagedir_pfn, pagedir_end_pfn;
599         pagedir_end = pagedir + (PAGE_SIZE << pagedir_order);
600         pagedir_pfn = __pa(pagedir) >> PAGE_SHIFT;
601         pagedir_end_pfn = __pa(pagedir_end) >> PAGE_SHIFT;
602         for (zone_pfn = 0; zone_pfn < zone->spanned_pages; ++zone_pfn) {
603                 struct page *page;
604                 unsigned long pfn = zone_pfn + zone->zone_start_pfn;
605                 if (!pfn_valid(pfn))
606                         continue;
607                 page = pfn_to_page(pfn);
608                 if (!TestClearPageNosave(page))
609                         continue;
610                 else if (pfn >= pagedir_pfn && pfn < pagedir_end_pfn)
611                         continue;
612                 __free_page(page);
613         }
614 }
615
616 void swsusp_free(void)
617 {
618         unsigned long p = (unsigned long)pagedir_save;
619         struct zone *zone;
620         for_each_zone(zone) {
621                 if (!is_highmem(zone))
622                         free_suspend_pagedir_zone(zone, p);
623         }
624         free_pages(p, pagedir_order);
625 }
626
627
628 /**
629  *      calc_order - Determine the order of allocation needed for pagedir_save.
630  *
631  *      This looks tricky, but is just subtle. Please fix it some time.
632  *      Since there are %nr_copy_pages worth of pages in the snapshot, we need
633  *      to allocate enough contiguous space to hold 
634  *              (%nr_copy_pages * sizeof(struct pbe)), 
635  *      which has the saved/orig locations of the page.. 
636  *
637  *      SUSPEND_PD_PAGES() tells us how many pages we need to hold those 
638  *      structures, then we call get_bitmask_order(), which will tell us the
639  *      last bit set in the number, starting with 1. (If we need 30 pages, that
640  *      is 0x0000001e in hex. The last bit is the 5th, which is the order we 
641  *      would use to allocate 32 contiguous pages).
642  *
643  *      Since we also need to save those pages, we add the number of pages that
644  *      we need to nr_copy_pages, and in case of an overflow, do the 
645  *      calculation again to update the number of pages needed. 
646  *
647  *      With this model, we will tend to waste a lot of memory if we just cross
648  *      an order boundary. Plus, the higher the order of allocation that we try
649  *      to do, the more likely we are to fail in a low-memory situtation 
650  *      (though we're unlikely to get this far in such a case, since swsusp 
651  *      requires half of memory to be free anyway).
652  */
653
654
655 static void calc_order(void)
656 {
657         int diff = 0;
658         int order = 0;
659
660         do {
661                 diff = get_bitmask_order(SUSPEND_PD_PAGES(nr_copy_pages)) - order;
662                 if (diff) {
663                         order += diff;
664                         nr_copy_pages += 1 << diff;
665                 }
666         } while(diff);
667         pagedir_order = order;
668 }
669
670
671 /**
672  *      alloc_pagedir - Allocate the page directory.
673  *
674  *      First, determine exactly how many contiguous pages we need and
675  *      allocate them.
676  */
677
678 static int alloc_pagedir(void)
679 {
680         calc_order();
681         pagedir_save = (suspend_pagedir_t *)__get_free_pages(GFP_ATOMIC | __GFP_COLD,
682                                                              pagedir_order);
683         if (!pagedir_save)
684                 return -ENOMEM;
685         memset(pagedir_save, 0, (1 << pagedir_order) * PAGE_SIZE);
686         pagedir_nosave = pagedir_save;
687         return 0;
688 }
689
690
691 /**
692  *      alloc_image_pages - Allocate pages for the snapshot.
693  *
694  */
695
696 static int alloc_image_pages(void)
697 {
698         struct pbe * p;
699         int i;
700
701         for (i = 0, p = pagedir_save; i < nr_copy_pages; i++, p++) {
702                 p->address = get_zeroed_page(GFP_ATOMIC | __GFP_COLD);
703                 if(!p->address)
704                         goto Error;
705                 SetPageNosave(virt_to_page(p->address));
706         }
707         return 0;
708  Error:
709         do { 
710                 if (p->address)
711                         free_page(p->address);
712                 p->address = 0;
713         } while (p-- > pagedir_save);
714         return -ENOMEM;
715 }
716
717
718 /**
719  *      enough_free_mem - Make sure we enough free memory to snapshot.
720  *
721  *      Returns TRUE or FALSE after checking the number of available 
722  *      free pages.
723  */
724
725 static int enough_free_mem(void)
726 {
727         if (nr_free_pages() < (nr_copy_pages + PAGES_FOR_IO)) {
728                 pr_debug("swsusp: Not enough free pages: Have %d\n",
729                          nr_free_pages());
730                 return 0;
731         }
732         return 1;
733 }
734
735
736 /**
737  *      enough_swap - Make sure we have enough swap to save the image.
738  *
739  *      Returns TRUE or FALSE after checking the total amount of swap 
740  *      space avaiable.
741  *
742  *      FIXME: si_swapinfo(&i) returns all swap devices information.
743  *      We should only consider resume_device. 
744  */
745
746 static int enough_swap(void)
747 {
748         struct sysinfo i;
749
750         si_swapinfo(&i);
751         if (i.freeswap < (nr_copy_pages + PAGES_FOR_IO))  {
752                 pr_debug("swsusp: Not enough swap. Need %ld\n",i.freeswap);
753                 return 0;
754         }
755         return 1;
756 }
757
758 static int swsusp_alloc(void)
759 {
760         int error;
761
762         pr_debug("suspend: (pages needed: %d + %d free: %d)\n",
763                  nr_copy_pages, PAGES_FOR_IO, nr_free_pages());
764
765         pagedir_nosave = NULL;
766         if (!enough_free_mem())
767                 return -ENOMEM;
768
769         if (!enough_swap())
770                 return -ENOSPC;
771
772         if ((error = alloc_pagedir())) {
773                 pr_debug("suspend: Allocating pagedir failed.\n");
774                 return error;
775         }
776         if ((error = alloc_image_pages())) {
777                 pr_debug("suspend: Allocating image pages failed.\n");
778                 swsusp_free();
779                 return error;
780         }
781
782         nr_copy_pages_check = nr_copy_pages;
783         pagedir_order_check = pagedir_order;
784         return 0;
785 }
786
787 int suspend_prepare_image(void)
788 {
789         unsigned int nr_needed_pages;
790         int error;
791
792         pr_debug("swsusp: critical section: \n");
793         if (save_highmem()) {
794                 printk(KERN_CRIT "Suspend machine: Not enough free pages for highmem\n");
795                 restore_highmem();
796                 return -ENOMEM;
797         }
798
799         drain_local_pages();
800         count_data_pages();
801         printk("swsusp: Need to copy %u pages\n",nr_copy_pages);
802         nr_needed_pages = nr_copy_pages + PAGES_FOR_IO;
803
804         error = swsusp_alloc();
805         if (error)
806                 return error;
807         
808         /* During allocating of suspend pagedir, new cold pages may appear. 
809          * Kill them.
810          */
811         drain_local_pages();
812         copy_data_pages();
813
814         /*
815          * End of critical section. From now on, we can write to memory,
816          * but we should not touch disk. This specially means we must _not_
817          * touch swap space! Except we must write out our image of course.
818          */
819
820         printk("swsusp: critical section/: done (%d pages copied)\n", nr_copy_pages );
821         return 0;
822 }
823
824
825 /* It is important _NOT_ to umount filesystems at this point. We want
826  * them synced (in case something goes wrong) but we DO not want to mark
827  * filesystem clean: it is not. (And it does not matter, if we resume
828  * correctly, we'll mark system clean, anyway.)
829  */
830 int swsusp_write(void)
831 {
832         int error;
833         device_resume();
834         lock_swapdevices();
835         error = write_suspend_image();
836         /* This will unlock ignored swap devices since writing is finished */
837         lock_swapdevices();
838         return error;
839
840 }
841
842
843 extern asmlinkage int swsusp_arch_suspend(void);
844 extern asmlinkage int swsusp_arch_resume(void);
845
846
847 asmlinkage int swsusp_save(void)
848 {
849         int error = 0;
850
851         if ((error = swsusp_swap_check())) {
852                 printk(KERN_ERR "swsusp: FATAL: cannot find swap device, try "
853                                 "swapon -a!\n");
854                 return error;
855         }
856         return suspend_prepare_image();
857 }
858
859 int swsusp_suspend(void)
860 {
861         int error;
862         if ((error = arch_prepare_suspend()))
863                 return error;
864         local_irq_disable();
865         save_processor_state();
866         error = swsusp_arch_suspend();
867         /* Restore control flow magically appears here */
868         restore_processor_state();
869         restore_highmem();
870         local_irq_enable();
871         return error;
872 }
873
874
875 asmlinkage int swsusp_restore(void)
876 {
877         BUG_ON (nr_copy_pages_check != nr_copy_pages);
878         BUG_ON (pagedir_order_check != pagedir_order);
879         
880         /* Even mappings of "global" things (vmalloc) need to be fixed */
881         __flush_tlb_global();
882         return 0;
883 }
884
885 int swsusp_resume(void)
886 {
887         int error;
888         local_irq_disable();
889         /* We'll ignore saved state, but this gets preempt count (etc) right */
890         save_processor_state();
891         error = swsusp_arch_resume();
892         /* Code below is only ever reached in case of failure. Otherwise
893          * execution continues at place where swsusp_arch_suspend was called
894          */
895         BUG_ON(!error);
896         restore_processor_state();
897         restore_highmem();
898         local_irq_enable();
899         return error;
900 }
901
902
903
904 /* More restore stuff */
905
906 #define does_collide(addr) does_collide_order(pagedir_nosave, addr, 0)
907
908 /*
909  * Returns true if given address/order collides with any orig_address 
910  */
911 static int __init does_collide_order(suspend_pagedir_t *pagedir, unsigned long addr,
912                 int order)
913 {
914         int i;
915         unsigned long addre = addr + (PAGE_SIZE<<order);
916         
917         for (i=0; i < nr_copy_pages; i++)
918                 if ((pagedir+i)->orig_address >= addr &&
919                         (pagedir+i)->orig_address < addre)
920                         return 1;
921
922         return 0;
923 }
924
925 /*
926  * We check here that pagedir & pages it points to won't collide with pages
927  * where we're going to restore from the loaded pages later
928  */
929 static int __init check_pagedir(void)
930 {
931         int i;
932
933         for(i=0; i < nr_copy_pages; i++) {
934                 unsigned long addr;
935
936                 do {
937                         addr = get_zeroed_page(GFP_ATOMIC);
938                         if(!addr)
939                                 return -ENOMEM;
940                 } while (does_collide(addr));
941
942                 (pagedir_nosave+i)->address = addr;
943         }
944         return 0;
945 }
946
947 static int __init swsusp_pagedir_relocate(void)
948 {
949         /*
950          * We have to avoid recursion (not to overflow kernel stack),
951          * and that's why code looks pretty cryptic 
952          */
953         suspend_pagedir_t *old_pagedir = pagedir_nosave;
954         void **eaten_memory = NULL;
955         void **c = eaten_memory, *m, *f;
956         int ret = 0;
957
958         printk("Relocating pagedir ");
959
960         if (!does_collide_order(old_pagedir, (unsigned long)old_pagedir, pagedir_order)) {
961                 printk("not necessary\n");
962                 return check_pagedir();
963         }
964
965         while ((m = (void *) __get_free_pages(GFP_ATOMIC, pagedir_order)) != NULL) {
966                 if (!does_collide_order(old_pagedir, (unsigned long)m, pagedir_order))
967                         break;
968                 eaten_memory = m;
969                 printk( "." ); 
970                 *eaten_memory = c;
971                 c = eaten_memory;
972         }
973
974         if (!m) {
975                 printk("out of memory\n");
976                 ret = -ENOMEM;
977         } else {
978                 pagedir_nosave =
979                         memcpy(m, old_pagedir, PAGE_SIZE << pagedir_order);
980         }
981
982         c = eaten_memory;
983         while (c) {
984                 printk(":");
985                 f = c;
986                 c = *c;
987                 free_pages((unsigned long)f, pagedir_order);
988         }
989         if (ret)
990                 return ret;
991         printk("|\n");
992         return check_pagedir();
993 }
994
995 /**
996  *      Using bio to read from swap.
997  *      This code requires a bit more work than just using buffer heads
998  *      but, it is the recommended way for 2.5/2.6.
999  *      The following are to signal the beginning and end of I/O. Bios
1000  *      finish asynchronously, while we want them to happen synchronously.
1001  *      A simple atomic_t, and a wait loop take care of this problem.
1002  */
1003
1004 static atomic_t io_done = ATOMIC_INIT(0);
1005
1006 static void start_io(void)
1007 {
1008         atomic_set(&io_done,1);
1009 }
1010
1011 static int end_io(struct bio * bio, unsigned int num, int err)
1012 {
1013         atomic_set(&io_done,0);
1014         return 0;
1015 }
1016
1017 static void wait_io(void)
1018 {
1019         while(atomic_read(&io_done))
1020                 io_schedule();
1021 }
1022
1023
1024 static struct block_device * resume_bdev;
1025
1026 /**
1027  *      submit - submit BIO request.
1028  *      @rw:    READ or WRITE.
1029  *      @off    physical offset of page.
1030  *      @page:  page we're reading or writing.
1031  *
1032  *      Straight from the textbook - allocate and initialize the bio.
1033  *      If we're writing, make sure the page is marked as dirty.
1034  *      Then submit it and wait.
1035  */
1036
1037 static int submit(int rw, pgoff_t page_off, void * page)
1038 {
1039         int error = 0;
1040         struct bio * bio;
1041
1042         bio = bio_alloc(GFP_ATOMIC, 1);
1043         if (!bio)
1044                 return -ENOMEM;
1045         bio->bi_sector = page_off * (PAGE_SIZE >> 9);
1046         bio_get(bio);
1047         bio->bi_bdev = resume_bdev;
1048         bio->bi_end_io = end_io;
1049
1050         if (bio_add_page(bio, virt_to_page(page), PAGE_SIZE, 0) < PAGE_SIZE) {
1051                 printk("swsusp: ERROR: adding page to bio at %ld\n",page_off);
1052                 error = -EFAULT;
1053                 goto Done;
1054         }
1055
1056         if (rw == WRITE)
1057                 bio_set_pages_dirty(bio);
1058         start_io();
1059         submit_bio(rw | (1 << BIO_RW_SYNC), bio);
1060         wait_io();
1061  Done:
1062         bio_put(bio);
1063         return error;
1064 }
1065
1066 int bio_read_page(pgoff_t page_off, void * page)
1067 {
1068         return submit(READ, page_off, page);
1069 }
1070
1071 int bio_write_page(pgoff_t page_off, void * page)
1072 {
1073         return submit(WRITE, page_off, page);
1074 }
1075
1076 /*
1077  * Sanity check if this image makes sense with this kernel/swap context
1078  * I really don't think that it's foolproof but more than nothing..
1079  */
1080
1081 static const char * __init sanity_check(void)
1082 {
1083         dump_info();
1084         if(swsusp_info.version_code != LINUX_VERSION_CODE)
1085                 return "kernel version";
1086         if(swsusp_info.num_physpages != num_physpages)
1087                 return "memory size";
1088         if (strcmp(swsusp_info.uts.sysname,system_utsname.sysname))
1089                 return "system type";
1090         if (strcmp(swsusp_info.uts.release,system_utsname.release))
1091                 return "kernel release";
1092         if (strcmp(swsusp_info.uts.version,system_utsname.version))
1093                 return "version";
1094         if (strcmp(swsusp_info.uts.machine,system_utsname.machine))
1095                 return "machine";
1096         if(swsusp_info.cpus != num_online_cpus())
1097                 return "number of cpus";
1098         return NULL;
1099 }
1100
1101
1102 static int __init check_header(void)
1103 {
1104         const char * reason = NULL;
1105         int error;
1106
1107         if ((error = bio_read_page(swp_offset(swsusp_header.swsusp_info), &swsusp_info)))
1108                 return error;
1109
1110         /* Is this same machine? */
1111         if ((reason = sanity_check())) {
1112                 printk(KERN_ERR "swsusp: Resume mismatch: %s\n",reason);
1113                 return -EPERM;
1114         }
1115         nr_copy_pages = swsusp_info.image_pages;
1116         return error;
1117 }
1118
1119 static int __init check_sig(void)
1120 {
1121         int error;
1122
1123         memset(&swsusp_header, 0, sizeof(swsusp_header));
1124         if ((error = bio_read_page(0, &swsusp_header)))
1125                 return error;
1126         if (!memcmp(SWSUSP_SIG, swsusp_header.sig, 10)) {
1127                 memcpy(swsusp_header.sig, swsusp_header.orig_sig, 10);
1128
1129                 /*
1130                  * Reset swap signature now.
1131                  */
1132                 error = bio_write_page(0, &swsusp_header);
1133         } else { 
1134                 pr_debug(KERN_ERR "swsusp: Suspend partition has wrong signature?\n");
1135                 return -EINVAL;
1136         }
1137         if (!error)
1138                 pr_debug("swsusp: Signature found, resuming\n");
1139         return error;
1140 }
1141
1142 /**
1143  *      swsusp_read_data - Read image pages from swap.
1144  *
1145  *      You do not need to check for overlaps, check_pagedir()
1146  *      already did that.
1147  */
1148
1149 static int __init data_read(void)
1150 {
1151         struct pbe * p;
1152         int error;
1153         int i;
1154         int mod = nr_copy_pages / 100;
1155
1156         if (!mod)
1157                 mod = 1;
1158
1159         if ((error = swsusp_pagedir_relocate()))
1160                 return error;
1161
1162         printk( "Reading image data (%d pages):     ", nr_copy_pages );
1163         for(i = 0, p = pagedir_nosave; i < nr_copy_pages && !error; i++, p++) {
1164                 if (!(i%mod))
1165                         printk( "\b\b\b\b%3d%%", i / mod );
1166                 error = bio_read_page(swp_offset(p->swap_address),
1167                                   (void *)p->address);
1168         }
1169         printk(" %d done.\n",i);
1170         return error;
1171
1172 }
1173
1174 extern dev_t __init name_to_dev_t(const char *line);
1175
1176 static int __init read_pagedir(void)
1177 {
1178         unsigned long addr;
1179         int i, n = swsusp_info.pagedir_pages;
1180         int error = 0;
1181
1182         pagedir_order = get_bitmask_order(n);
1183
1184         addr =__get_free_pages(GFP_ATOMIC, pagedir_order);
1185         if (!addr)
1186                 return -ENOMEM;
1187         pagedir_nosave = (struct pbe *)addr;
1188
1189         pr_debug("pmdisk: Reading pagedir (%d Pages)\n",n);
1190
1191         for (i = 0; i < n && !error; i++, addr += PAGE_SIZE) {
1192                 unsigned long offset = swp_offset(swsusp_info.pagedir[i]);
1193                 if (offset)
1194                         error = bio_read_page(offset, (void *)addr);
1195                 else
1196                         error = -EFAULT;
1197         }
1198         if (error)
1199                 free_pages((unsigned long)pagedir_nosave, pagedir_order);
1200         return error;
1201 }
1202
1203 static int __init read_suspend_image(void)
1204 {
1205         int error = 0;
1206
1207         if ((error = check_sig()))
1208                 return error;
1209         if ((error = check_header()))
1210                 return error;
1211         if ((error = read_pagedir()))
1212                 return error;
1213         if ((error = data_read()))
1214                 free_pages((unsigned long)pagedir_nosave, pagedir_order);
1215         return error;
1216 }
1217
1218 /**
1219  *      pmdisk_read - Read saved image from swap.
1220  */
1221
1222 int __init swsusp_read(void)
1223 {
1224         int error;
1225
1226         if (!strlen(resume_file))
1227                 return -ENOENT;
1228
1229         resume_device = name_to_dev_t(resume_file);
1230         pr_debug("swsusp: Resume From Partition: %s\n", resume_file);
1231
1232         resume_bdev = open_by_devnum(resume_device, FMODE_READ);
1233         if (!IS_ERR(resume_bdev)) {
1234                 set_blocksize(resume_bdev, PAGE_SIZE);
1235                 error = read_suspend_image();
1236                 blkdev_put(resume_bdev);
1237         } else
1238                 error = PTR_ERR(resume_bdev);
1239
1240         if (!error)
1241                 pr_debug("Reading resume file was successful\n");
1242         else
1243                 pr_debug("pmdisk: Error %d resuming\n", error);
1244         return error;
1245 }