Skip to contentSkip to conversation

Suspend 2 merge

DISCUSSION Nigel Cunningham 21 participants 241 messages Nov 24, 2004 – Dec 14, 2004 2 messages not in the archive Page 1 of 2

Subsystems (53)
lore
Share & tools
lore
#0 lore raw

Hi everyone.

I know that I still have work to do on suspend2, but thought it was high time I got around to properly submitting the code for review, so here goes.

I have it split up into 51 patches, of which most are less than 20k, although there are three 50k patches. Changes to the rest of the kernel tree come first, then the core. The full tree can be found at

http://suspend2.bkbits.net:8080/merge-tree

Regards,

Nigel

Signature · 7 lines
Nigel Cunningham
Pastoral Worker
Christian Reformed Church of Tuggeranong
PO Box 1004, Tuggeranong, ACT 2901

You see, at just the right time, when we were still powerless, Christ
died for the ungodly.		-- Romans 5:6
#1 lore raw

Suspend 2 merge: 7/51: Reboot handler hook.

Nice and simple.

We override swsusp's hook with the suspend2 one. It's not that I want to step on Pavel's toes. Rather, people who go to the trouble of applying suspend2, probably want to use it :>

kernel/sys.c +6 -2
diff -ruN 300-reboot-handler-hook-old/kernel/sys.c 300-reboot-handler-hook-new/kernel/sys.c
@@ -502,10 +502,14 @@
 		machine_restart(buffer);
 		break;
 
-#ifdef CONFIG_SOFTWARE_SUSPEND
+#ifdef CONFIG_SOFTWARE_SUSPEND2
 	case LINUX_REBOOT_CMD_SW_SUSPEND:
 		{
-			int ret = software_suspend();
+			int ret = -EINVAL;
+			if (!(test_suspend_state(SUSPEND_DISABLED))) {
+				suspend_try_suspend();
+				ret = 0;
+			}
 			unlock_kernel();
 			return ret;
 		}
#5 lore raw

Suspend 2 merge: 10/51: Exports for suspend built as modules.

In reply to Nigel Cunningham

New exports for suspend. I've cut them down some as a result of the last review, but could perhaps do more? Would people prefer to see a single struct wrapping exported functions?

The sys_ functions are exported because a while ago, people suggested I use /dev/console to output text that doesn't need to be logged, and I also use /dev/splash for the bootsplash support. These functions were needed in order to get access to those files when we're resuming, and the ioctl for setting up writing text (canon). I'd prefer to use internal routines, but I suppose this way I get the text display on the serial console too :>

Avenrun I'd gladly drop, but apparently sendmail has some ugliness where it won't deliver your mail if the load average gets too high. Guess what suspending to disk does to your load average? (So we save the avenrun values at the start of the cycle and restore them at the end - anyone got a better idea? I'd love to do something different here).

drivers/acpi/hardware/hwsleep.c +4 -0
diff -ruN 400-exports-old/drivers/acpi/hardware/hwsleep.c 400-exports-new/drivers/acpi/hardware/hwsleep.c
@@ -43,6 +43,7 @@
  */
 
 #include <acpi/acpi.h>
+#include <linux/module.h>
 
 #define _COMPONENT          ACPI_HARDWARE
 	 ACPI_MODULE_NAME    ("hwsleep")
@@ -591,3 +592,6 @@
 
 	return_ACPI_STATUS (status);
 }
+
+/* For suspend2 */
+EXPORT_SYMBOL(acpi_leave_sleep_state);
fs/bio.c +1 -0
diff -ruN 400-exports-old/fs/bio.c 400-exports-new/fs/bio.c
@@ -1002,3 +1002,4 @@
 EXPORT_SYMBOL(bio_split_pool);
 EXPORT_SYMBOL(bio_copy_user);
 EXPORT_SYMBOL(bio_uncopy_user);
+EXPORT_SYMBOL(bio_set_pages_dirty);
fs/ioctl.c +2 -3
diff -ruN 400-exports-old/fs/ioctl.c 400-exports-new/fs/ioctl.c
@@ -138,8 +138,7 @@
 
 /*
  * Platforms implementing 32 bit compatibility ioctl handlers in
- * modules need this exported
+ * modules need this exported. So does Suspend2 (when made as
+ * modules), so the export_symbol is now unconditional.
  */
-#ifdef CONFIG_COMPAT
 EXPORT_SYMBOL(sys_ioctl);
-#endif
fs/namei.c +2 -0
diff -ruN 400-exports-old/fs/namei.c 400-exports-new/fs/namei.c
@@ -1649,6 +1649,8 @@
 	return error;
 }
 
+EXPORT_SYMBOL(sys_mkdir);
+
 /*
  * We try to drop the dentry early: we should have
  * a usage count of 2 if we're the only user of this
fs/namespace.c +4 -0
diff -ruN 400-exports-old/fs/namespace.c 400-exports-new/fs/namespace.c
@@ -490,6 +490,8 @@
 	return retval;
 }
 
+EXPORT_SYMBOL(sys_umount);
+
 #ifdef __ARCH_WANT_SYS_OLDUMOUNT
 
 /*
@@ -1187,6 +1189,8 @@
 	return retval;
 }
 
+EXPORT_SYMBOL(sys_mount);
+
 /*
  * Replace the fs->{rootmnt,root} with {mnt,dentry}. Put the old values.
  * It can block. Requires the big lock held.
fs/proc/generic.c +2 -0
diff -ruN 400-exports-old/fs/proc/generic.c 400-exports-new/fs/proc/generic.c
@@ -698,3 +698,5 @@
 out:
 	return;
 }
+
+EXPORT_SYMBOL(proc_match);
fs/read_write.c +1 -0
diff -ruN 400-exports-old/fs/read_write.c 400-exports-new/fs/read_write.c
@@ -314,6 +314,7 @@
 
 	return ret;
 }
+EXPORT_SYMBOL(sys_write);
 
 asmlinkage ssize_t sys_pread64(unsigned int fd, char __user *buf,
 			     size_t count, loff_t pos)
kernel/power/main.c +5 -1
diff -ruN 400-exports-old/kernel/power/main.c 400-exports-new/kernel/power/main.c
@@ -15,7 +15,7 @@
 #include <linux/errno.h>
 #include <linux/init.h>
 #include <linux/pm.h>
-
+#include <linux/module.h>
 
 #include "power.h"
 
@@ -262,3 +262,7 @@
 }
 
 core_initcall(pm_init);
+
+/* For Suspend2 ACPI support */
+EXPORT_SYMBOL(pm_ops);
+EXPORT_SYMBOL(pm_disk_mode);
kernel/sched.c +1 -0
diff -ruN 400-exports-old/kernel/sched.c 400-exports-new/kernel/sched.c
@@ -3798,6 +3798,7 @@
 
 	read_unlock(&tasklist_lock);
 }
+EXPORT_SYMBOL(show_state);
 
 void __devinit init_idle(task_t *idle, int cpu)
 {
kernel/sys.c +2 -0
diff -ruN 400-exports-old/kernel/sys.c 400-exports-new/kernel/sys.c
@@ -523,6 +523,8 @@
 	return 0;
 }
 
+EXPORT_SYMBOL(sys_reboot);
+
 static void deferred_cad(void *dummy)
 {
 	notifier_call_chain(&reboot_notifier_list, SYS_RESTART, NULL);
kernel/timer.c +1 -0
diff -ruN 400-exports-old/kernel/timer.c 400-exports-new/kernel/timer.c
@@ -881,6 +881,7 @@
  * Requires xtime_lock to access.
  */
 unsigned long avenrun[3];
+EXPORT_SYMBOL(avenrun);
 
 /*
  * calc_load - given tick count, update the avenrun load estimates.
mm/page_alloc.c +4 -0
diff -ruN 400-exports-old/mm/page_alloc.c 400-exports-new/mm/page_alloc.c
@@ -2069,3 +2069,7 @@
 
 	return table;
 }
+
+/* Exported for Software Suspend 2 */
+EXPORT_SYMBOL(nr_free_highpages);
+EXPORT_SYMBOL(pgdat_list);
mm/swapfile.c +10 -0
diff -ruN 400-exports-old/mm/swapfile.c 400-exports-new/mm/swapfile.c
@@ -1710,3 +1710,13 @@
 	swap_device_unlock(swapdev);
 	return ret;
 }
+
+/* Functions exported for Software Suspend's swapwriter */
+EXPORT_SYMBOL(swap_free);
+EXPORT_SYMBOL(swap_info);
+EXPORT_SYMBOL(sys_swapoff);
+EXPORT_SYMBOL(sys_swapon);
+EXPORT_SYMBOL(si_swapinfo);
+EXPORT_SYMBOL(map_swap_page);
+EXPORT_SYMBOL(get_swap_page);
+EXPORT_SYMBOL(get_swap_info_struct);
mm/vmscan.c +3 -0
diff -ruN 400-exports-old/mm/vmscan.c 400-exports-new/mm/vmscan.c
@@ -1221,6 +1221,9 @@
 	current->reclaim_state = NULL;
 	return ret;
 }
+
+/* For Suspend2 */	
+EXPORT_SYMBOL(shrink_all_memory);
 #endif
 
 #ifdef CONFIG_HOTPLUG_CPU
#13 lore raw

Suspend 2 merge: 11/51: Export vt functions.

In reply to Nigel Cunningham

On wide > 128 char displays, the text display gets messed up if gotoxy's and gotoxay's variables are signed (I should confirm that this is still the case - it's been a while).

We need to modify kmsg_redirect to see our messages when debugging :>

drivers/char/vt.c +3 -2
diff -ruN 401-export-vt-functions-old/drivers/char/vt.c 401-export-vt-functions-new/drivers/char/vt.c
@@ -913,7 +913,7 @@
  */
 static void gotoxy(int currcons, int new_x, int new_y)
 {
-	int min_y, max_y;
+	unsigned int min_y, max_y;
 
 	if (new_x < 0)
 		x = 0;
@@ -940,7 +940,7 @@
 }
 
 /* for absolute user moves, when decom is set */
-static void gotoxay(int currcons, int new_x, int new_y)
+static void gotoxay(int currcons, unsigned int new_x, unsigned int new_y)
 {
 	gotoxy(currcons, new_x, decom ? (top+new_y) : new_y);
 }
@@ -3312,6 +3312,7 @@
  *	Visible symbols for modules
  */
 
+EXPORT_SYMBOL(kmsg_redirect);
 EXPORT_SYMBOL(color_table);
 EXPORT_SYMBOL(default_red);
 EXPORT_SYMBOL(default_grn);
#14 lore raw

Suspend 2 merge:L 12/51: Disable OOM killer when suspending.

In reply to Nigel Cunningham

When preparing the image, suspend eats all the memory in sight, both to reduce the image size and to improve the reliability of our stats (We've worked hard to make it work reliably under heavy load - 100+). Of course this can result in the OOM killer being triggered, so this simple test stops that happening.

mm/oom_kill.c +4 -0
diff -ruN 501-disable-oom-killer-when-suspending-old/mm/oom_kill.c 501-disable-oom-killer-when-suspending-new/mm/oom_kill.c
@@ -20,6 +20,7 @@
 #include <linux/swap.h>
 #include <linux/timex.h>
 #include <linux/jiffies.h>
+#include <linux/suspend.h>
 
 /* #define DEBUG */
 
@@ -237,6 +238,9 @@
 	static unsigned long first, last, count, lastkill;
 	unsigned long now, since;
 
+	if (test_suspend_state(SUSPEND_FREEZER_ON))
+		return;
+	
 	spin_lock(&oom_lock);
 	now = jiffies;
 	since = now - last;
#18 lore raw

Suspend 2 merge: 13/51: Disable highmem tlb flush for copyback.

In reply to Nigel Cunningham

When we're making/restoring our atomic copy of the image, secondary processors are frozen. Trying an SMP call at that time could thus lead to deadlock. Secondary processors have their tlbs unconditionally flushed when leaving the processor refrigerator, so this doesn't come back to bite us.

mm/highmem.c +5 -1
diff -ruN 502-disable-highmem-tlb-flush-for-copyback-old/mm/highmem.c 502-disable-highmem-tlb-flush-for-copyback-new/mm/highmem.c
@@ -26,6 +26,7 @@
 #include <linux/init.h>
 #include <linux/hash.h>
 #include <linux/highmem.h>
+#include <linux/suspend.h>
 #include <asm/tlbflush.h>
 
 static mempool_t *page_pool, *isa_page_pool;
@@ -94,7 +95,10 @@
 
 		set_page_address(page, NULL);
 	}
-	flush_tlb_kernel_range(PKMAP_ADDR(0), PKMAP_ADDR(LAST_PKMAP));
+	if (test_suspend_state(SUSPEND_FREEZE_SMP))
+		__flush_tlb();
+	else
+		flush_tlb_kernel_range(PKMAP_ADDR(0), PKMAP_ADDR(LAST_PKMAP));
 }
 
 static inline unsigned long map_new_virtual(struct page *page)
#20 lore raw

Suspend 2 merge: 9/51: init/* changes.

In reply to Nigel Cunningham

This patch includes all of the changes to init/*.

There are two main parts:

1) Make name_to_dev_t non init. Why should you need to reboot if all you want to do is change the device you're using to suspend? That's M$'s way :>. Suspend2 allows the user to change the resume2= parameter after booting via a proc entry. Making this code non-__init allows us to use the same code that will be used at boot time to parse that string.

2) Hooks for resuming. Suspend2 functionality can be compiled as modules or built in. Resuming can be activated via an initrd. These hooks allow for all of the combinations of the above. Allowing resuming from within an initrd is important because then you can set up LVM volumes (including encrypted devices), compile drivers for your resume device as modules and so on.

init/do_mounts.c +29 -5
diff -ruN 302-init-hooks-old/init/do_mounts.c 302-init-hooks-new/init/do_mounts.c
@@ -52,7 +52,7 @@
 __setup("ro", readonly);
 __setup("rw", readwrite);
 
-static dev_t __init try_name(char *name, int part)
+static dev_t try_name(char *name, int part)
 {
 	char path[64];
 	char buf[32];
@@ -134,16 +134,21 @@
  *	is mounted on rootfs /sys.
  */
 
-dev_t __init name_to_dev_t(char *name)
+dev_t name_to_dev_t(char *name)
 {
 	char s[32];
 	char *p;
 	dev_t res = 0;
-	int part;
+	int part, mount_result;
 
 #ifdef CONFIG_SYSFS
 	int mkdir_err = sys_mkdir("/sys", 0700);
-	if (sys_mount("sysfs", "/sys", "sysfs", 0, NULL) < 0)
+	/* 
+	 * When changing resume2 parameter for Software Suspend, sysfs may
+	 * already be mounted. 
+	 */
+	mount_result = sys_mount("sysfs", "/sys", "sysfs", 0, NULL);
+	if (mount_result < 0 && mount_result != -EBUSY)
 		goto out;
 #endif
 
@@ -195,7 +200,8 @@
 	res = try_name(s, part);
 done:
 #ifdef CONFIG_SYSFS
-	sys_umount("/sys", 0);
+	if (mount_result >= 0)
+		sys_umount("/sys", 0);
 out:
 	if (!mkdir_err)
 		sys_rmdir("/sys");
@@ -205,6 +211,8 @@
 	res = 0;
 	goto done;
 }
+/* Exported for Software Suspend */
+EXPORT_SYMBOL(name_to_dev_t);
 
 static int __init root_dev_setup(char *line)
 {
@@ -398,9 +406,25 @@
 
 	is_floppy = MAJOR(ROOT_DEV) == FLOPPY_MAJOR;
 
+	/* Suspend2:
+	 * By this point, suspend_early_init has been called to initialise our
+	 * proc interface. If modules are built in, they have registered (all
+	 * of the above via late_initcalls).
+	 * 
+	 * We have not yet looked to see if an image exists, however. If we
+	 * have an initrd, it is expected that the user will have set it up
+	 * to echo > /proc/software_suspend/activate and thus initiate any
+	 * resume. If they don'tdo that, we do it immediately after the initrd
+	 * is finished (major issues if they mount filesystems rw from the
+	 * initrd! - they are warned. If there's no usable initrd, we do our
+	 * check next
+	 */
 	if (initrd_load())
 		goto out;
 
+	if (test_suspend_state(SUSPEND_RESUME_NOT_DONE))
+		software_suspend_try_resume();
+	
 	if (is_floppy && rd_doload && rd_load_disk(0))
 		ROOT_DEV = Root_RAM0;
 
init/do_mounts_initrd.c +8 -1
diff -ruN 302-init-hooks-old/init/do_mounts_initrd.c 302-init-hooks-new/init/do_mounts_initrd.c
@@ -7,6 +7,7 @@
 #include <linux/romfs_fs.h>
 #include <linux/initrd.h>
 #include <linux/sched.h>
+#include <linux/suspend.h>
 
 #include "do_mounts.h"
 
@@ -58,10 +59,16 @@
 
 	pid = kernel_thread(do_linuxrc, "/linuxrc", SIGCHLD);
 	if (pid > 0) {
-		while (pid != sys_wait4(-1, &i, 0, NULL))
+		while (pid != sys_wait4(-1, &i, 0, NULL)) {
 			yield();
+			if (current->flags & PF_FREEZE)
+				refrigerator(PF_FREEZE);
+		}
 	}
 
+	if (test_suspend_state(SUSPEND_RESUME_NOT_DONE))
+		software_suspend_try_resume();
+
 	/* move initrd to rootfs' /old */
 	sys_fchdir(old_fd);
 	sys_mount("/", ".", NULL, MS_MOVE, NULL);
init/main.c +3 -0
diff -ruN 302-init-hooks-old/init/main.c 302-init-hooks-new/init/main.c
@@ -46,6 +46,7 @@
 #include <linux/rmap.h>
 #include <linux/mempolicy.h>
 #include <linux/key.h>
+#include <linux/suspend.h>
 
 #include <asm/io.h>
 #include <asm/bugs.h>
@@ -758,6 +759,8 @@
 	else
 		prepare_namespace();
 
+	clear_suspend_state(SUSPEND_BOOT_TIME);
+
 	/*
 	 * Ok, we have completed the initial bootup, and
 	 * we're essentially up and running. Get rid of the
kernel/power/swsusp.c +1 -1
diff -ruN 302-init-hooks-old/kernel/power/swsusp.c 302-init-hooks-new/kernel/power/swsusp.c
@@ -1168,7 +1168,7 @@
 
 }
 
-extern dev_t __init name_to_dev_t(const char *line);
+extern dev_t name_to_dev_t(char *line);
 
 static int __init read_pagedir(void)
 {
#34 lore raw

Suspend 2 merge: 8/51: /proc/acpi/sleep hook.

In reply to Nigel Cunningham

Same thing as the previous patch, but for /proc/acpi/sleep.

drivers/acpi/sleep/proc.c +11 -0
diff -ruN 301-proc-acpi-sleep-activate-hook-old/drivers/acpi/sleep/proc.c 301-proc-acpi-sleep-activate-hook-new/drivers/acpi/sleep/proc.c
@@ -68,6 +68,17 @@
 		goto Done;
 	}
 	state = simple_strtoul(str, NULL, 0);
+#ifdef CONFIG_SOFTWARE_SUSPEND2
+	/* 
+	 * I used to put this after the CONFIG_SOFTWARE_SUSPEND
+	 * test, but people who compile in suspend2 usually want
+	 * to use it instead of swsusp.   --NC
+	 */
+	if (state == 4) {
+		suspend_try_suspend();
+		goto Done;
+	}
+#endif
 #ifdef CONFIG_SOFTWARE_SUSPEND
 	if (state == 4) {
 		software_suspend();
#36 lore raw

Suspend 2 merge: 4/51: Get module list.

In reply to Nigel Cunningham

This provides access to the list of loaded modules for suspend's debugging output. When a cycle finishes, suspend outputs something the following:

Quoted 20 lines

Please include the following information in bug reports:
- SUSPEND core : 2.1.5.7
- Kernel Version : 2.6.9
- Compiler vers. : 3.3
- Modules loaded : tuner bttv videodev snd_seq_oss snd_seq_midi_event snd_seq snd_pcm_oss snd_mixer_oss snd_intel8x0 snd_ac97_codec snd_pcm snd_timer snd_page_alloc snd_mpu401_uart snd_rawmidi snd_seq_device snd soundcore visor usbserial usblp joydev evdev usbmouse usbhid uhci_hcd usbcore ppp_deflate zlib_deflate zlib_inflate bsd_comp ipt_LOG ipt_state ipt_MASQUERADE iptable_nat ip_conntrack ipt_multiport ipt_REJECT iptable_filter ip_tables ppp_async ppp_generic slhc crc_ccitt video_buf v4l2_common btcx_risc Win4Lin mki_adapter radeon agpgart parport_pc lp parport sg ide_cd sr_mod cdrom floppy af_packet e1000 loop dm_mod tsdev suspend_bootsplash suspend_text suspend_swap suspend_block_io suspend_lzf suspend_core
- Attempt number : 9
- Parameters : 0 2304 32768 1 0 4096 5
- Limits : 261680 pages RAM. Initial boot: 252677.
- Overall expected compression percentage: 0.
- LZF Compressor enabled.

Quoted 8 lines

Compressed 922112000 bytes into 437892038 (52 percent compression).
- Swapwriter active.
Swap available for image: 294868 pages.
- Debugging compiled in.
- Preemptive kernel.
- SMP kernel.
- Highmem Support.
- I/O speed: Write 72 MB/s, Read 119 MB/s.

Including the modules loaded is very helpful for debugging problems.

kernel/module.c +14 -0
diff -ruN 209-get-module-list-old/kernel/module.c 209-get-module-list-new/kernel/module.c
@@ -2105,6 +2105,18 @@
 }
 EXPORT_SYMBOL(module_remove_driver);
 
+int print_module_list_to_buffer(char * buffer, int size)
+{
+	struct module *mod;
+	int pos = 0;
+
+	list_for_each_entry(mod, &modules, list)
+		if (mod->name)
+			pos += snprintf(buffer+pos, size-pos-1, 
+					"%s ", mod->name);
+	return pos;
+}
+
 #ifdef CONFIG_MODVERSIONS
 /* Generate the signature for struct module here, too, for modversions. */
 void struct_module(struct module *mod) { return; }
@@ -2115,3 +2127,5 @@
 struct list_head *kdb_modules = &modules;	/* kdb needs the list of modules */
 #endif	/* CONFIG_KDB */
 
+/* For Suspend2 */
+EXPORT_SYMBOL(print_module_list_to_buffer);
#40 lore raw

Suspend 2 merge: 3/51: e820 table support

In reply to Nigel Cunningham

The first of the 'real' candidates for merging.

This adds support for setting and clearing the Nosave status of pages based on the contents of the e820 table, and clearing Nosave for __init pages when they're freed.

arch/i386/mm/init.c +28 -8
diff -ruN 208-e820-table-support-old/arch/i386/mm/init.c 208-e820-table-support-new/arch/i386/mm/init.c
@@ -27,6 +27,7 @@
 #include <linux/slab.h>
 #include <linux/proc_fs.h>
 #include <linux/efi.h>
+#include <linux/suspend.h>
 
 #include <asm/processor.h>
 #include <asm/system.h>
@@ -266,12 +267,15 @@
 {
 	if (page_is_ram(pfn) && !(bad_ppro && page_kills_ppro(pfn))) {
 		ClearPageReserved(page);
+		ClearPageNosave(page);
 		set_bit(PG_highmem, &page->flags);
 		set_page_count(page, 1);
 		__free_page(page);
 		totalhigh_pages++;
-	} else
+	} else {
 		SetPageReserved(page);
+		SetPageNosave(page);
+	}
 }
 
 #ifndef CONFIG_DISCONTIGMEM
@@ -349,7 +353,7 @@
 #endif
 }
 
-#if defined(CONFIG_PM_DISK) || defined(CONFIG_SOFTWARE_SUSPEND)
+#ifdef CONFIG_PM
 /*
  * Swap suspend & friends need this for resume because things like the intel-agp
  * driver might have split up a kernel 4MB mapping.
@@ -569,6 +573,7 @@
 	int codesize, reservedpages, datasize, initsize;
 	int tmp;
 	int bad_ppro;
+	void * addr;
 
 #ifndef CONFIG_DISCONTIGMEM
 	if (!mem_map)
@@ -599,12 +604,25 @@
 	totalram_pages += __free_all_bootmem();
 
 	reservedpages = 0;
-	for (tmp = 0; tmp < max_low_pfn; tmp++)
-		/*
-		 * Only count reserved RAM pages
-		 */
-		if (page_is_ram(tmp) && PageReserved(pfn_to_page(tmp)))
-			reservedpages++;
+	addr = __va(0);
+	for (tmp = 0; tmp < max_low_pfn; tmp++, addr += PAGE_SIZE) {
+		if (page_is_ram(tmp)) {
+			/*
+			 * Only count reserved RAM pages
+			 */
+			if (PageReserved(mem_map+tmp))
+				reservedpages++;
+			/*
+			 * Mark nosave pages
+			 */
+			if (addr >= (void *)&__nosave_begin && addr < (void *)&__nosave_end)
+				SetPageNosave(mem_map+tmp);
+		} else
+			/*
+			 * Non-RAM pages are always nosave
+			 */
+			SetPageNosave(mem_map+tmp);
+	}
 
 	set_highmem_pages_init(bad_ppro);
 
@@ -703,6 +721,7 @@
 	addr = (unsigned long)(&__init_begin);
 	for (; addr < (unsigned long)(&__init_end); addr += PAGE_SIZE) {
 		ClearPageReserved(virt_to_page(addr));
+		ClearPageNosave(virt_to_page(addr));
 		set_page_count(virt_to_page(addr), 1);
 		free_page(addr);
 		totalram_pages++;
@@ -717,6 +736,7 @@
 		printk (KERN_INFO "Freeing initrd memory: %ldk freed\n", (end - start) >> 10);
 	for (; start < end; start += PAGE_SIZE) {
 		ClearPageReserved(virt_to_page(start));
+		ClearPageNosave(virt_to_page(start));
 		set_page_count(virt_to_page(start), 1);
 		free_page(start);
 		totalram_pages++;
mm/bootmem.c +4 -0
diff -ruN 208-e820-table-support-old/mm/bootmem.c 208-e820-table-support-new/mm/bootmem.c
@@ -279,11 +279,13 @@
 
 			count += BITS_PER_LONG;
 			__ClearPageReserved(page);
+			ClearPageNosave(page);
 			set_page_count(page, 1);
 			for (j = 1; j < BITS_PER_LONG; j++) {
 				if (j + 16 < BITS_PER_LONG)
 					prefetchw(page + j + 16);
 				__ClearPageReserved(page + j);
+				ClearPageNosave(page + j);
 			}
 			__free_pages(page, ffs(BITS_PER_LONG)-1);
 			i += BITS_PER_LONG;
@@ -294,6 +296,7 @@
 				if (v & m) {
 					count++;
 					__ClearPageReserved(page);
+					ClearPageNosave(page);
 					set_page_count(page, 1);
 					__free_page(page);
 				}
@@ -314,6 +317,7 @@
 	for (i = 0; i < ((bdata->node_low_pfn-(bdata->node_boot_start >> PAGE_SHIFT))/8 + PAGE_SIZE-1)/PAGE_SIZE; i++,page++) {
 		count++;
 		__ClearPageReserved(page);
+		ClearPageNosave(page);
 		set_page_count(page, 1);
 		__free_page(page);
 	}
#42 lore raw

Suspend2 merge: 1/51: Device trees

In reply to Nigel Cunningham

This patch allows the device tree to be split up into multiple trees. I don't really expect it to be merged, but it is an important part of suspend at the moment, and I certainly want to see something like it that will allow us to suspend some parts of the device tree and not others. Suspend2 uses it to keep alive the hard drive (or equivalent) that we're writing the image to while suspending other devices, thus improving the consistency of the image written.

I remember from last time this was posted that someone commented on exporting the default device tree; I haven't changed that yet.

drivers/base/power/main.c +19 -5
diff -ruN 205-device-pm-trees-old/drivers/base/power/main.c 205-device-pm-trees-new/drivers/base/power/main.c
@@ -4,6 +4,9 @@
  * Copyright (c) 2003 Patrick Mochel
  * Copyright (c) 2003 Open Source Development Lab
  *
+ * Partial tree additions
+ * Copyright (c) 2004 Nigel Cunningham
+ *
  * This file is released under the GPLv2
  *
  *
@@ -23,10 +26,18 @@
 #include <linux/device.h>
 #include "power.h"
 
-LIST_HEAD(dpm_active);
-LIST_HEAD(dpm_off);
-LIST_HEAD(dpm_off_irq);
-
+struct partial_device_tree default_device_tree =
+{ 
+	.dpm_active	= LIST_HEAD_INIT(default_device_tree.dpm_active),
+	.dpm_off	= LIST_HEAD_INIT(default_device_tree.dpm_off),
+	.dpm_off_irq	= LIST_HEAD_INIT(default_device_tree.dpm_off_irq),
+};
+EXPORT_SYMBOL(default_device_tree);
+
+/* 
+ * One mutex for all trees because we can be moving items
+ * between trees.
+ */
 DECLARE_MUTEX(dpm_sem);
 DECLARE_MUTEX(dpm_list_sem);
 
@@ -77,7 +88,9 @@
 		 dev->bus ? dev->bus->name : "No Bus", dev->kobj.name);
 	atomic_set(&dev->power.pm_users, 0);
 	down(&dpm_list_sem);
-	list_add_tail(&dev->power.entry, &dpm_active);
+	list_add_tail(&dev->power.entry, &default_device_tree.dpm_active);
+	dev->current_list = DEVICE_LIST_DPM_ACTIVE;
+	dev->tree = &default_device_tree;
 	device_pm_set_parent(dev, dev->parent);
 	if ((error = dpm_sysfs_add(dev)))
 		list_del(&dev->power.entry);
@@ -93,6 +106,7 @@
 	dpm_sysfs_remove(dev);
 	device_pm_release(dev->power.pm_parent);
 	list_del_init(&dev->power.entry);
+	dev->current_list = DEVICE_LIST_NONE;
 	up(&dpm_list_sem);
 }
 
drivers/base/power/Makefile +1 -1
diff -ruN 205-device-pm-trees-old/drivers/base/power/Makefile 205-device-pm-trees-new/drivers/base/power/Makefile
@@ -1,5 +1,5 @@
 obj-y			:= shutdown.o
-obj-$(CONFIG_PM)	+= main.o suspend.o resume.o runtime.o sysfs.o
+obj-$(CONFIG_PM)	+= main.o suspend.o resume.o runtime.o sysfs.o tree.o
 
 ifeq ($(CONFIG_DEBUG_DRIVER),y)
 EXTRA_CFLAGS += -DDEBUG
drivers/base/power/power.h +17 -3
diff -ruN 205-device-pm-trees-old/drivers/base/power/power.h 205-device-pm-trees-new/drivers/base/power/power.h
@@ -35,10 +35,22 @@
 /*
  * The PM lists.
  */
-extern struct list_head dpm_active;
-extern struct list_head dpm_off;
-extern struct list_head dpm_off_irq;
 
+struct partial_device_tree 
+{
+	struct list_head dpm_active;
+	struct list_head dpm_off;
+	struct list_head dpm_off_irq;
+};
+
+enum {
+	DEVICE_LIST_NONE,
+	DEVICE_LIST_DPM_ACTIVE,
+	DEVICE_LIST_DPM_OFF,
+	DEVICE_LIST_DPM_OFF_IRQ,
+};
+
+extern struct partial_device_tree default_device_tree;
 
 static inline struct dev_pm_info * to_pm_info(struct list_head * entry)
 {
@@ -64,7 +76,9 @@
  * resume.c
  */
 
+extern void dpm_resume_tree(struct partial_device_tree * tree);
 extern void dpm_resume(void);
+extern void dpm_power_up_tree(struct partial_device_tree * tree);
 extern void dpm_power_up(void);
 extern int resume_device(struct device *);
 
drivers/base/power/resume.c +29 -8
diff -ruN 205-device-pm-trees-old/drivers/base/power/resume.c 205-device-pm-trees-new/drivers/base/power/resume.c
@@ -29,16 +29,17 @@
 
 
 
-void dpm_resume(void)
+void dpm_resume_tree(struct partial_device_tree * tree)
 {
 	down(&dpm_list_sem);
-	while(!list_empty(&dpm_off)) {
-		struct list_head * entry = dpm_off.next;
+	while(!list_empty(&tree->dpm_off)) {
+		struct list_head * entry = tree->dpm_off.next;
 		struct device * dev = to_device(entry);
 
 		get_device(dev);
 		list_del_init(entry);
-		list_add_tail(entry, &dpm_active);
+		list_add_tail(entry, &tree->dpm_active);
+		dev->current_list = DEVICE_LIST_DPM_ACTIVE;
 
 		up(&dpm_list_sem);
 		if (!dev->power.prev_state)
@@ -50,6 +51,11 @@
 }
 
 
+void dpm_resume(void)
+{
+	dpm_resume_tree(&default_device_tree);
+}
+
 /**
  *	device_resume - Restore state of each device in system.
  *
@@ -66,6 +72,14 @@
 
 EXPORT_SYMBOL_GPL(device_resume);
 
+void device_resume_tree(struct partial_device_tree * tree)
+{
+	down(&dpm_sem);
+	dpm_resume_tree(tree);
+	up(&dpm_sem);
+}
+
+EXPORT_SYMBOL(device_resume_tree);
 
 /**
  *	device_power_up_irq - Power on some devices.
@@ -78,20 +92,27 @@
  *	Interrupts must be disabled when calling this.
  */
 
-void dpm_power_up(void)
+void dpm_power_up_tree(struct partial_device_tree * tree)
 {
-	while(!list_empty(&dpm_off_irq)) {
-		struct list_head * entry = dpm_off_irq.next;
+	while(!list_empty(&tree->dpm_off_irq)) {
+		struct list_head * entry = tree->dpm_off_irq.next;
 		struct device * dev = to_device(entry);
 
 		get_device(dev);
 		list_del_init(entry);
-		list_add_tail(entry, &dpm_active);
+		list_add_tail(entry, &tree->dpm_active);
+		dev->current_list = DEVICE_LIST_DPM_ACTIVE;
 		resume_device(dev);
 		put_device(dev);
 	}
 }
+EXPORT_SYMBOL(dpm_power_up_tree);
+
 
+void dpm_power_up(void)
+{
+	dpm_power_up_tree(&default_device_tree);
+}
 
 /**
  *	device_pm_power_up - Turn on all devices that need special attention.
drivers/base/power/shutdown.c +1 -0
diff -ruN 205-device-pm-trees-old/drivers/base/power/shutdown.c 205-device-pm-trees-new/drivers/base/power/shutdown.c
@@ -65,3 +65,4 @@
 	sysdev_shutdown();
 }
 
+EXPORT_SYMBOL(device_shutdown);
drivers/base/power/suspend.c +29 -18

101 lines not on this page · raw message

drivers/base/power/tree.c +105 -0

105 lines not on this page · raw message

drivers/base/sys.c +2 -1
diff -ruN 205-device-pm-trees-old/drivers/base/sys.c 205-device-pm-trees-new/drivers/base/sys.c
@@ -337,7 +337,7 @@
 	}
 	return 0;
 }
-
+EXPORT_SYMBOL(sysdev_suspend);
 
 /**
  *	sysdev_resume - Bring system devices back to life.
@@ -384,6 +384,7 @@
 	}
 	return 0;
 }
+EXPORT_SYMBOL(sysdev_resume);
 
 
 int __init system_bus_init(void)
include/linux/device.h +5 -0
diff -ruN 205-device-pm-trees-old/include/linux/device.h 205-device-pm-trees-new/include/linux/device.h
@@ -285,6 +285,11 @@
 					     override */
 
 	void	(*release)(struct device * dev);
+
+	struct partial_device_tree * tree; /* Which tree of devices this
+					      device is in */
+	int	current_list;		/* Which list within the tree the
+					   device is on (speeds moving) */
 };
 
 static inline struct device *
include/linux/pm.h +15 -2
diff -ruN 205-device-pm-trees-old/include/linux/pm.h 205-device-pm-trees-new/include/linux/pm.h
@@ -235,12 +235,25 @@
 
 extern void device_pm_set_parent(struct device * dev, struct device * parent);
 
+struct partial_device_tree;
+extern struct partial_device_tree default_device_tree;
+
 extern int device_suspend(u32 state);
+extern int device_suspend_tree(u32 state, struct partial_device_tree * tree);
 extern int device_power_down(u32 state);
+extern int device_power_down_tree(u32 state, struct partial_device_tree * tree);
 extern void device_power_up(void);
+extern void device_power_up_tree(struct partial_device_tree * tree);
 extern void device_resume(void);
-
-
+extern void device_resume_tree(struct partial_device_tree * tree);
+extern void device_merge_tree(	struct partial_device_tree * source,
+				struct partial_device_tree * dest);
+extern void device_switch_trees(struct device * dev, struct partial_device_tree * tree);
+extern void dpm_power_up_tree(struct partial_device_tree * tree);
+extern int sysdev_suspend(u32 state);
+extern int sysdev_resume(void);
+extern struct partial_device_tree * device_create_tree(void);
+extern void device_destroy_tree(struct partial_device_tree * tree);
 #endif /* __KERNEL__ */
 
 #endif /* _LINUX_PM_H */
#43 lore raw

Suspend2 merge: 2/51: Find class by name

In reply to Nigel Cunningham

A second patch that shouldn't be needed but is at the moment. It is used to find any framebuffer drivers and add put them in the kept-alive device tree. Once Pavel's improvements to the PM_ states are merged, I hope this will be able to go away.

Not sure if would be helpful elsewhere?

drivers/base/class.c +21 -0
diff -ruN 207-find-class-by-name-old/drivers/base/class.c 207-find-class-by-name-new/drivers/base/class.c
@@ -497,6 +497,25 @@
 	kobject_put(&class_dev->kobj);
 }
 
+struct class * class_find(char * name)
+{
+	struct class * this_class;
+
+	if (!name)
+		return NULL;
+
+	down_read(&class_subsys.rwsem);
+	list_for_each_entry(this_class, &class_subsys.kset.list, subsys.kset.kobj.entry) {
+		if (!(strcmp(this_class->name, name))) {
+			class_get(this_class);
+			up_read(&class_subsys.rwsem);
+			return this_class;
+		}
+	}
+	up_read(&class_subsys.rwsem);
+
+	return NULL;
+}
 
 int class_interface_register(struct class_interface *class_intf)
 {
@@ -579,3 +598,5 @@
 
 EXPORT_SYMBOL_GPL(class_interface_register);
 EXPORT_SYMBOL_GPL(class_interface_unregister);
+
+EXPORT_SYMBOL_GPL(class_find);
include/linux/device.h +1 -0
diff -ruN 207-find-class-by-name-old/include/linux/device.h 207-find-class-by-name-new/include/linux/device.h
@@ -164,6 +164,7 @@
 
 extern struct class * class_get(struct class *);
 extern void class_put(struct class *);
+extern struct class * class_find(char * name);
 
 
 struct class_attribute {
#44 lore raw

Suspend 2 merge: 17/51: Disable MCE checking during suspend.

In reply to Nigel Cunningham

Avoid a potential SMP deadlock here.

arch/i386/kernel/cpu/mcheck/non-fatal.c +3 -1
diff -ruN 506-disable-mce-checking-during-suspend-avoid-smp-deadlock-old/arch/i386/kernel/cpu/mcheck/non-fatal.c 506-disable-mce-checking-during-suspend-avoid-smp-deadlock-new/arch/i386/kernel/cpu/mcheck/non-fatal.c
@@ -17,6 +17,7 @@
 #include <linux/interrupt.h>
 #include <linux/smp.h>
 #include <linux/module.h>
+#include <linux/suspend.h>
 
 #include <asm/processor.h> 
 #include <asm/system.h>
@@ -57,7 +58,8 @@
 
 static void mce_work_fn(void *data)
 { 
-	on_each_cpu(mce_checkregs, NULL, 1, 1);
+	if (!test_suspend_state(SUSPEND_RUNNING))
+		on_each_cpu(mce_checkregs, NULL, 1, 1);
 	schedule_delayed_work(&mce_work, MCE_RATE);
 } 
 
#50 lore raw

Suspend 2 merge: 5/51: Workthread freezer support.

In reply to Nigel Cunningham

This thread adds freezer support for workthreads.

A new parameter in the create_ functions allows the thread to be marked as PF_NOFREEZE. This should only be used for threads that may need to run during writing the image.

In a later patch, you'll see a new SYNCTHREAD flag, used for processes that need to run while we're syncing data to disk, but not for writing the image. That isn't used here because all kernel threads are frozen after we've synced, so it's irrelevant to them.

drivers/acpi/osl.c +1 -1
diff -ruN 210-workthreads-old/drivers/acpi/osl.c 210-workthreads-new/drivers/acpi/osl.c
@@ -90,7 +90,7 @@
 		return AE_NULL_ENTRY;
 	}
 #endif
-	kacpid_wq = create_singlethread_workqueue("kacpid");
+	kacpid_wq = create_singlethread_workqueue("kacpid", 0);
 	BUG_ON(!kacpid_wq);
 
 	return AE_OK;
drivers/block/ll_rw_blk.c +1 -1
diff -ruN 210-workthreads-old/drivers/block/ll_rw_blk.c 210-workthreads-new/drivers/block/ll_rw_blk.c
@@ -3021,7 +3021,7 @@
 
 int __init blk_dev_init(void)
 {
-	kblockd_workqueue = create_workqueue("kblockd");
+	kblockd_workqueue = create_workqueue("kblockd", PF_NOFREEZE);
 	if (!kblockd_workqueue)
 		panic("Failed to create kblockd\n");
 
drivers/char/hvc_console.c +1 -1
diff -ruN 210-workthreads-old/drivers/char/hvc_console.c 210-workthreads-new/drivers/char/hvc_console.c
@@ -757,7 +757,7 @@
 
 	/* Always start the kthread because there can be hotplug vty adapters
 	 * added later. */
-	hvc_task = kthread_run(khvcd, NULL, "khvcd");
+	hvc_task = kthread_run(khvcd, NULL, PF_NOFREEZE, "khvcd");
 	if (IS_ERR(hvc_task)) {
 		panic("Couldn't create kthread for console.\n");
 		put_tty_driver(hvc_driver);
drivers/char/hvcs.c +1 -1
diff -ruN 210-workthreads-old/drivers/char/hvcs.c 210-workthreads-new/drivers/char/hvcs.c
@@ -1420,7 +1420,7 @@
 		return -ENOMEM;
 	}
 
-	hvcs_task = kthread_run(khvcsd, NULL, "khvcsd");
+	hvcs_task = kthread_run(khvcsd, NULL, PF_NOFREEZE, "khvcsd");
 	if (IS_ERR(hvcs_task)) {
 		printk(KERN_ERR "HVCS: khvcsd creation failed.  Driver not loaded.\n");
 		kfree(hvcs_pi_buff);
drivers/macintosh/therm_adt746x.c +1 -1
diff -ruN 210-workthreads-old/drivers/macintosh/therm_adt746x.c 210-workthreads-new/drivers/macintosh/therm_adt746x.c
@@ -394,7 +394,7 @@
 		write_both_fan_speed(th, -1);
 	}
 	
-	thread_therm = kthread_run(monitor_task, th, "kfand");
+	thread_therm = kthread_run(monitor_task, th, 0, "kfand");
 
 	if (thread_therm == ERR_PTR(-ENOMEM)) {
 		printk(KERN_INFO "adt746x: Kthread creation failed\n");
drivers/md/dm-crypt.c +1 -1
diff -ruN 210-workthreads-old/drivers/md/dm-crypt.c 210-workthreads-new/drivers/md/dm-crypt.c
@@ -758,7 +758,7 @@
 	if (!_crypt_io_pool)
 		return -ENOMEM;
 
-	_kcryptd_workqueue = create_workqueue("kcryptd");
+	_kcryptd_workqueue = create_workqueue("kcryptd", PF_NOFREEZE);
 	if (!_kcryptd_workqueue) {
 		r = -ENOMEM;
 		DMERR(PFX "couldn't create kcryptd");
drivers/md/dm-raid1.c +1 -1
diff -ruN 210-workthreads-old/drivers/md/dm-raid1.c 210-workthreads-new/drivers/md/dm-raid1.c
@@ -1233,7 +1233,7 @@
 	if (r)
 		return r;
 
-	_kmirrord_wq = create_workqueue("kmirrord");
+	_kmirrord_wq = create_workqueue("kmirrord", PF_SYNCTHREAD);
 	if (!_kmirrord_wq) {
 		DMERR("couldn't start kmirrord");
 		dm_dirty_log_exit();
drivers/md/kcopyd.c +1 -1
diff -ruN 210-workthreads-old/drivers/md/kcopyd.c 210-workthreads-new/drivers/md/kcopyd.c
@@ -609,7 +609,7 @@
 		return r;
 	}
 
-	_kcopyd_wq = create_singlethread_workqueue("kcopyd");
+	_kcopyd_wq = create_singlethread_workqueue("kcopyd", PF_SYNCTHREAD);
 	if (!_kcopyd_wq) {
 		jobs_exit();
 		up(&kcopyd_init_lock);
drivers/message/i2o/driver.c +1 -1
diff -ruN 210-workthreads-old/drivers/message/i2o/driver.c 210-workthreads-new/drivers/message/i2o/driver.c
@@ -80,7 +80,7 @@
 	pr_debug("Register driver %s\n", drv->name);
 
 	if (drv->event) {
-		drv->event_queue = create_workqueue(drv->name);
+		drv->event_queue = create_workqueue(drv->name, 0);
 		if (!drv->event_queue) {
 			printk(KERN_ERR "i2o: Could not initialize event queue "
 			       "for driver %s\n", drv->name);
drivers/net/wan/sdlamain.c +1 -1
diff -ruN 210-workthreads-old/drivers/net/wan/sdlamain.c 210-workthreads-new/drivers/net/wan/sdlamain.c
@@ -240,7 +240,7 @@
 	printk(KERN_INFO "%s v%u.%u %s\n",
 		fullname, DRV_VERSION, DRV_RELEASE, copyright);
 
-	wanpipe_wq = create_workqueue("wanpipe_wq");
+	wanpipe_wq = create_workqueue("wanpipe_wq", 0);
 	if (!wanpipe_wq)
 		return -ENOMEM;
 
drivers/s390/cio/device.c +4 -3
diff -ruN 210-workthreads-old/drivers/s390/cio/device.c 210-workthreads-new/drivers/s390/cio/device.c
@@ -151,15 +151,16 @@
 	init_waitqueue_head(&ccw_device_init_wq);
 	atomic_set(&ccw_device_init_count, 0);
 
-	ccw_device_work = create_singlethread_workqueue("cio");
+	ccw_device_work = create_singlethread_workqueue("cio", 0);
 	if (!ccw_device_work)
 		return -ENOMEM; /* FIXME: better errno ? */
-	ccw_device_notify_work = create_singlethread_workqueue("cio_notify");
+	ccw_device_notify_work = create_singlethread_workqueue("cio_notify",
+			0);
 	if (!ccw_device_notify_work) {
 		ret = -ENOMEM; /* FIXME: better errno ? */
 		goto out_err;
 	}
-	slow_path_wq = create_singlethread_workqueue("kslowcrw");
+	slow_path_wq = create_singlethread_workqueue("kslowcrw", 0);
 	if (!slow_path_wq) {
 		ret = -ENOMEM; /* FIXME: better errno ? */
 		goto out_err;
drivers/scsi/libata-core.c +1 -1
diff -ruN 210-workthreads-old/drivers/scsi/libata-core.c 210-workthreads-new/drivers/scsi/libata-core.c
@@ -3591,7 +3591,7 @@
 
 static int __init ata_init(void)
 {
-	ata_wq = create_workqueue("ata");
+	ata_wq = create_workqueue("ata", 0);
 	if (!ata_wq)
 		return -ENOMEM;
 
fs/aio.c +1 -1
diff -ruN 210-workthreads-old/fs/aio.c 210-workthreads-new/fs/aio.c
@@ -72,7 +72,7 @@
 	kioctx_cachep = kmem_cache_create("kioctx", sizeof(struct kioctx),
 				0, SLAB_HWCACHE_ALIGN|SLAB_PANIC, NULL, NULL);
 
-	aio_wq = create_workqueue("aio");
+	aio_wq = create_workqueue("aio", 0);
 
 	pr_debug("aio_setup: sizeof(struct page) = %d\n", (int)sizeof(struct page));
 
fs/reiserfs/journal.c +1 -1
diff -ruN 210-workthreads-old/fs/reiserfs/journal.c 210-workthreads-new/fs/reiserfs/journal.c
@@ -2483,7 +2483,7 @@
 
   reiserfs_mounted_fs_count++ ;
   if (reiserfs_mounted_fs_count <= 1)
-    commit_wq = create_workqueue("reiserfs");
+    commit_wq = create_workqueue("reiserfs", PF_SYNCTHREAD);
 
   INIT_WORK(&journal->j_work, flush_async_commits, p_s_sb);
   return 0 ;
fs/xfs/linux-2.6/xfs_buf.c +2 -2
diff -ruN 210-workthreads-old/fs/xfs/linux-2.6/xfs_buf.c 210-workthreads-new/fs/xfs/linux-2.6/xfs_buf.c
@@ -1784,11 +1784,11 @@
 {
 	int		rval;
 
-	pagebuf_logio_workqueue = create_workqueue("xfslogd");
+	pagebuf_logio_workqueue = create_workqueue("xfslogd", PF_SYNCTHREAD);
 	if (!pagebuf_logio_workqueue)
 		return -ENOMEM;
 
-	pagebuf_dataio_workqueue = create_workqueue("xfsdatad");
+	pagebuf_dataio_workqueue = create_workqueue("xfsdatad", PF_SYNCTHREAD);
 	if (!pagebuf_dataio_workqueue) {
 		destroy_workqueue(pagebuf_logio_workqueue);
 		return -ENOMEM;
include/linux/kthread.h +8 -2
diff -ruN 210-workthreads-old/include/linux/kthread.h 210-workthreads-new/include/linux/kthread.h
@@ -25,20 +25,26 @@
  */
 struct task_struct *kthread_create(int (*threadfn)(void *data),
 				   void *data,
+				   unsigned long freezer_flags,
 				   const char namefmt[], ...);
 
 /**
  * kthread_run: create and wake a thread.
  * @threadfn: the function to run until signal_pending(current).
  * @data: data ptr for @threadfn.
+ * @freezer_flags: process flags that should be used for freezing.
+ * 	PF_SYNCTHREAD if needed for syncing data to disk.
+ * 	PF_NOFREEZE if also needed for writing the image.
+ * 	0 otherwise.
  * @namefmt: printf-style name for the thread.
  *
  * Description: Convenient wrapper for kthread_create() followed by
  * wake_up_process().  Returns the kthread, or ERR_PTR(-ENOMEM). */
-#define kthread_run(threadfn, data, namefmt, ...)			   \
+#define kthread_run(threadfn, data, freezer_flags, namefmt, ...)	   \
 ({									   \
 	struct task_struct *__k						   \
-		= kthread_create(threadfn, data, namefmt, ## __VA_ARGS__); \
+		= kthread_create(threadfn, data, freezer_flags, 	   \
+			namefmt, ## __VA_ARGS__);			   \
 	if (!IS_ERR(__k))						   \
 		wake_up_process(__k);					   \
 	__k;								   \
include/linux/workqueue.h +4 -3
diff -ruN 210-workthreads-old/include/linux/workqueue.h 210-workthreads-new/include/linux/workqueue.h
@@ -51,9 +51,10 @@
 	} while (0)
 
 extern struct workqueue_struct *__create_workqueue(const char *name,
-						    int singlethread);
-#define create_workqueue(name) __create_workqueue((name), 0)
-#define create_singlethread_workqueue(name) __create_workqueue((name), 1)
+						    int singlethread,
+						    unsigned long freezer_flag);
+#define create_workqueue(name, flags) __create_workqueue((name), 0, flags)
+#define create_singlethread_workqueue(name, flags) __create_workqueue((name), 1, flags)
 
 extern void destroy_workqueue(struct workqueue_struct *wq);
 
kernel/kmod.c +1 -1
diff -ruN 210-workthreads-old/kernel/kmod.c 210-workthreads-new/kernel/kmod.c
@@ -274,6 +274,6 @@
 
 void __init usermodehelper_init(void)
 {
-	khelper_wq = create_singlethread_workqueue("khelper");
+	khelper_wq = create_singlethread_workqueue("khelper", 0);
 	BUG_ON(!khelper_wq);
 }
kernel/kthread.c +7 -0
diff -ruN 210-workthreads-old/kernel/kthread.c 210-workthreads-new/kernel/kthread.c
@@ -19,6 +19,7 @@
 	/* Information passed to kthread() from keventd. */
 	int (*threadfn)(void *data);
 	void *data;
+	unsigned long freezer_flags;
 	struct completion started;
 
 	/* Result passed back to kthread_create() from keventd. */
@@ -80,6 +81,10 @@
 	/* By default we can run anywhere, unlike keventd. */
 	set_cpus_allowed(current, CPU_MASK_ALL);
 
+	/* Set our freezer flags */
+	current->flags &= ~(PF_SYNCTHREAD | PF_NOFREEZE);
+	current->flags |= create->freezer_flags;
+
 	/* OK, tell user we're spawned, wait for stop or wakeup */
 	__set_current_state(TASK_INTERRUPTIBLE);
 	complete(&create->started);
@@ -115,6 +120,7 @@
 
 struct task_struct *kthread_create(int (*threadfn)(void *data),
 				   void *data,
+				   unsigned long freezer_flags,
 				   const char namefmt[],
 				   ...)
 {
@@ -123,6 +129,7 @@
 
 	create.threadfn = threadfn;
 	create.data = data;
+	create.freezer_flags = freezer_flags;
 	init_completion(&create.started);
 	init_completion(&create.done);
 
kernel/sched.c +2 -2
diff -ruN 210-workthreads-old/kernel/sched.c 210-workthreads-new/kernel/sched.c
@@ -4146,10 +4146,10 @@
 
 	switch (action) {
 	case CPU_UP_PREPARE:
-		p = kthread_create(migration_thread, hcpu, "migration/%d",cpu);
+		p = kthread_create(migration_thread, hcpu, 0,
+				"migration/%d",cpu);
 		if (IS_ERR(p))
 			return NOTIFY_BAD;
-		p->flags |= PF_NOFREEZE;
 		kthread_bind(p, cpu);
 		/* Must be high prio: stop_machine expects to yield to it. */
 		rq = task_rq_lock(p, &flags);
kernel/softirq.c +3 -2
diff -ruN 210-workthreads-old/kernel/softirq.c 210-workthreads-new/kernel/softirq.c
@@ -328,7 +328,6 @@
 static int ksoftirqd(void * __bind_cpu)
 {
 	set_user_nice(current, 19);
-	current->flags |= PF_NOFREEZE;
 
 	set_current_state(TASK_INTERRUPTIBLE);
 
@@ -338,6 +337,8 @@
 
 		__set_current_state(TASK_RUNNING);
 
+		try_to_freeze(PF_FREEZE);
+
 		while (local_softirq_pending()) {
 			/* Preempt disable stops cpu going offline.
 			   If already offline, we'll be on wrong CPU:
@@ -430,7 +431,7 @@
 	case CPU_UP_PREPARE:
 		BUG_ON(per_cpu(tasklet_vec, hotcpu).list);
 		BUG_ON(per_cpu(tasklet_hi_vec, hotcpu).list);
-		p = kthread_create(ksoftirqd, hcpu, "ksoftirqd/%d", hotcpu);
+		p = kthread_create(ksoftirqd, hcpu, PF_NOFREEZE, "ksoftirqd/%d", hotcpu);
 		if (IS_ERR(p)) {
 			printk("ksoftirqd for %i failed\n", hotcpu);
 			return NOTIFY_BAD;
kernel/stop_machine.c +1 -1
diff -ruN 210-workthreads-old/kernel/stop_machine.c 210-workthreads-new/kernel/stop_machine.c
@@ -174,7 +174,7 @@
 	if (cpu == NR_CPUS)
 		cpu = smp_processor_id();
 
-	p = kthread_create(do_stop, &smdata, "kstopmachine");
+	p = kthread_create(do_stop, &smdata, 0, "kstopmachine");
 	if (!IS_ERR(p)) {
 		kthread_bind(p, cpu);
 		wake_up_process(p);
kernel/workqueue.c +12 -9
diff -ruN 210-workthreads-old/kernel/workqueue.c 210-workthreads-new/kernel/workqueue.c
@@ -186,8 +186,6 @@
 	struct k_sigaction sa;
 	sigset_t blocked;
 
-	current->flags |= PF_NOFREEZE;
-
 	set_user_nice(current, -10);
 
 	/* Block and flush all signals */
@@ -208,6 +206,7 @@
 			schedule();
 		else
 			__set_current_state(TASK_RUNNING);
+		try_to_freeze(PF_FREEZE);
 		remove_wait_queue(&cwq->more_work, &wait);
 
 		if (!list_empty(&cwq->worklist))
@@ -277,7 +276,8 @@
 }
 
 static struct task_struct *create_workqueue_thread(struct workqueue_struct *wq,
-						   int cpu)
+						   int cpu,
+						   unsigned long freezer_flags)
 {
 	struct cpu_workqueue_struct *cwq = wq->cpu_wq + cpu;
 	struct task_struct *p;
@@ -292,9 +292,11 @@
 	init_waitqueue_head(&cwq->work_done);
 
 	if (is_single_threaded(wq))
-		p = kthread_create(worker_thread, cwq, "%s", wq->name);
+		p = kthread_create(worker_thread, cwq, freezer_flags, 
+				"%s", wq->name);
 	else
-		p = kthread_create(worker_thread, cwq, "%s/%d", wq->name, cpu);
+		p = kthread_create(worker_thread, cwq, freezer_flags,
+				"%s/%d", wq->name, cpu);
 	if (IS_ERR(p))
 		return NULL;
 	cwq->thread = p;
@@ -302,7 +304,8 @@
 }
 
 struct workqueue_struct *__create_workqueue(const char *name,
-					    int singlethread)
+					    int singlethread,
+					    unsigned long freezer_flags)
 {
 	int cpu, destroy = 0;
 	struct workqueue_struct *wq;
@@ -320,7 +323,7 @@
 	lock_cpu_hotplug();
 	if (singlethread) {
 		INIT_LIST_HEAD(&wq->list);
-		p = create_workqueue_thread(wq, 0);
+		p = create_workqueue_thread(wq, 0, freezer_flags);
 		if (!p)
 			destroy = 1;
 		else
@@ -330,7 +333,7 @@
 		list_add(&wq->list, &workqueues);
 		spin_unlock(&workqueue_lock);
 		for_each_online_cpu(cpu) {
-			p = create_workqueue_thread(wq, cpu);
+			p = create_workqueue_thread(wq, cpu, freezer_flags);
 			if (p) {
 				kthread_bind(p, cpu);
 				wake_up_process(p);
@@ -513,7 +516,7 @@
 void init_workqueues(void)
 {
 	hotcpu_notifier(workqueue_cpu_callback, 0);
-	keventd_wq = create_workqueue("events");
+	keventd_wq = create_workqueue("events", PF_NOFREEZE);
 	BUG_ON(!keventd_wq);
 }
 
mm/pdflush.c +1 -1
diff -ruN 210-workthreads-old/mm/pdflush.c 210-workthreads-new/mm/pdflush.c
@@ -215,7 +215,7 @@
 
 static void start_one_pdflush_thread(void)
 {
-	kthread_run(pdflush, NULL, "pdflush");
+	kthread_run(pdflush, NULL, 0, "pdflush");
 }
 
 static int __init pdflush_init(void)
#52 lore raw

Suspend 2 merge: 16/51: Disable cache reaping during suspend.

In reply to Nigel Cunningham

I have to admit to being a little unsure as to why this is needed, but suspend's reliability is helped a lot by disabling cache reaping while suspending. Perhaps one of the mm guys will be able to enlighten me here. Might be SMP related.

mm/slab.c +4 -1
diff -ruN 505-disable-cache-reaping-during-suspend-old/mm/slab.c 505-disable-cache-reaping-during-suspend-new/mm/slab.c
@@ -92,6 +92,7 @@
 #include	<linux/sysctl.h>
 #include	<linux/module.h>
 #include	<linux/rcupdate.h>
+#include	<linux/suspend.h>
 
 #include	<asm/uaccess.h>
 #include	<asm/cacheflush.h>
@@ -2730,7 +2731,9 @@
 {
 	struct list_head *walk;
 
-	if (down_trylock(&cache_chain_sem)) {
+	if ((unlikely(test_suspend_state(SUSPEND_RUNNING))) ||
+		(down_trylock(&cache_chain_sem))) 
+	{
 		/* Give up. Setup the next iteration. */
 		schedule_delayed_work(&__get_cpu_var(reap_work), REAPTIMEOUT_CPUC + smp_processor_id());
 		return;
#55 lore raw

Suspend 2 merge: 20/51: Timer freezer (experimental).

In reply to Nigel Cunningham

Here's experimental support for freezing timers. It doesn't really freeze them, but rather reschedules the call for a little later. One issue I need to think about is staggering the invocations at resume time, as some of the per CPU timer code seeks to do.

There is debugging code in here so that when it's used (it's off by default at the moment), and a timer that needs to be no_freeze holds up I/O, the user can find out what it is. Other code allows the timer freezer to be disabled on the fly (so you don't have to reboot because of this).

(This could replace the patches above for MCE checking and slab reaping).

diff -ruN 550-timer-freezer-old/drivers/block/ll_rw_blk.c 550-timer-freezer-new/drivers/block/ll_rw_blk.c
--- 550-timer-freezer-old/drivers/block/ll_rw_blk.c 2004-11-24
17:55:30.776567832 +1100
+++ 550-timer-freezer-new/drivers/block/ll_rw_blk.c 2004-11-24
17:23:36.145077968 +1100
@@ -254,6 +254,7 @@

q->unplug_timer.function = blk_unplug_timeout; q->unplug_timer.data = (unsigned long)q;
+ q->unplug_timer.no_freeze = 1;

/*
* by default assume old behaviour and bounce for any highmem page
diff -ruN 550-timer-freezer-old/drivers/input/serio/i8042.c 550-timer-freezer-new/drivers/input/serio/i8042.c
--- 550-timer-freezer-old/drivers/input/serio/i8042.c 2004-11-24
09:52:58.000000000 +1100
+++ 550-timer-freezer-new/drivers/input/serio/i8042.c 2004-11-24
17:23:36.154076600 +1100
@@ -1039,6 +1039,7 @@
dbg_init();

init_timer(&i8042_timer);
+ i8042_timer.no_freeze = 1;
i8042_timer.function = i8042_timer_func;

if (i8042_platform_init())
diff -ruN 550-timer-freezer-old/include/linux/timer.h 550-timer-freezer-new/include/linux/timer.h
--- 550-timer-freezer-old/include/linux/timer.h 2004-11-03
21:54:17.000000000 +1100
+++ 550-timer-freezer-new/include/linux/timer.h 2004-11-24
17:23:36.169074320 +1100
@@ -19,6 +19,8 @@
unsigned long data;

struct tvec_t_base_s *base;
+
+ int no_freeze;
};

#define TIMER_MAGIC 0x4b87ad6e
diff -ruN 550-timer-freezer-old/kernel/timer.c
550-timer-freezer-new/kernel/timer.c
--- 550-timer-freezer-old/kernel/timer.c 2004-11-24 17:55:30.863554608
+1100
+++ 550-timer-freezer-new/kernel/timer.c 2004-11-24 17:55:22.021898744
+1100
@@ -31,6 +31,7 @@
#include <linux/time.h>
#include <linux/jiffies.h>
#include <linux/cpu.h>
+#include <linux/suspend.h>
#include <linux/syscalls.h>

#include <asm/uaccess.h>
@@ -429,6 +430,9 @@
*/
#define INDEX(N) (base->timer_jiffies >> (TVR_BITS + N * TVN_BITS)) &
TVN_MASK

+#define FN_CACHE_SIZE 15
+static void * recent_fns[FN_CACHE_SIZE];
+
static inline void __run_timers(tvec_base_t *base) {
struct timer_list *timer;
@@ -463,7 +467,23 @@
smp_wmb();
timer->base = NULL; spin_unlock_irq(&base->lock);
- fn(data);
+ if (unlikely(test_suspend_state(SUSPEND_TIMER_FREEZER_ON) &&
(!timer->no_freeze))) {
+ int shown = 0, i, copy_start = 0;
+ for (i = 0; i < FN_CACHE_SIZE; i++)
+ if (fn == recent_fns[i]) {
+ shown = i + 1;
+ copy_start = i;
+ break;
+ }
+ for (i = copy_start; i < (FN_CACHE_SIZE - 1); i++)
+ recent_fns[i] = recent_fns[i+1];
+ recent_fns[FN_CACHE_SIZE - 1] = fn;
+ if (!shown) {
+ printk("Timed call of %p delayed while freezer on.\n", fn);
+ }
+ mod_timer(timer, jiffies + HZ);
+ } else
+ fn(data);
spin_lock_irq(&base->lock); goto repeat;
}
diff -ruN 550-timer-freezer-old/net/sched/sch_generic.c 550-timer-freezer-new/net/sched/sch_generic.c
--- 550-timer-freezer-old/net/sched/sch_generic.c 2004-11-24
09:53:13.000000000 +1100
+++ 550-timer-freezer-new/net/sched/sch_generic.c 2004-11-24
17:23:36.189071280 +1100
@@ -210,6 +210,7 @@
init_timer(&dev->watchdog_timer); dev->watchdog_timer.data = (unsigned long)dev; dev->watchdog_timer.function = dev_watchdog;
+ dev->watchdog_timer.no_freeze = 1;
}

void __netdev_watchdog_up(struct net_device *dev)

#56 lore raw

Suspend 2 merge: 34/51: Includes

In reply to Nigel Cunningham

These are the include changes files for suspend2.

I seek to keep this swsusp compatible, but it might be a little out of sync with Pavel's changes.

include/asm-i386/suspend.h +1 -0
diff -ruN 822-includes-old/include/asm-i386/suspend.h 822-includes-new/include/asm-i386/suspend.h
@@ -3,6 +3,7 @@
  * Based on code
  * Copyright 2001 Patrick Mochel <[email protected]>
  */
+#include <linux/errno.h>
 #include <asm/desc.h>
 #include <asm/i387.h>
 
include/linux/suspend.h +246 -49

314 lines not on this page · raw message

kernel/power/block_io.h +52 -0

52 lines not on this page · raw message

kernel/power/pageflags.h +80 -0

80 lines not on this page · raw message

kernel/power/plugins.h +205 -0

205 lines not on this page · raw message

kernel/power/power.h +2 -0
diff -ruN 822-includes-old/kernel/power/power.h 822-includes-new/kernel/power/power.h
@@ -1,6 +1,8 @@
 #include <linux/suspend.h>
 #include <linux/utsname.h>
 
+#include "suspend.h"
+
 /* With SUSPEND_CONSOLE defined, it suspend looks *really* cool, but
    we probably do not take enough locks for switching consoles, etc,
    so bad things might happen.
kernel/power/proc.h +64 -0

64 lines not on this page · raw message

kernel/power/range.h +105 -0

105 lines not on this page · raw message

kernel/power/smp.c +1 -0
diff -ruN 822-includes-old/kernel/power/smp.c 822-includes-new/kernel/power/smp.c
@@ -15,6 +15,7 @@
 #include <linux/module.h>
 #include <asm/atomic.h>
 #include <asm/tlbflush.h>
+#include "suspend.h"
 
 static atomic_t cpu_counter, freeze;
 
kernel/power/suspend.h +298 -0

298 lines not on this page · raw message

kernel/power/swsusp.c +3 -5
diff -ruN 822-includes-old/kernel/power/swsusp.c 822-includes-new/kernel/power/swsusp.c
@@ -36,6 +36,8 @@
  * For TODOs,FIXMEs also look in Documentation/power/swsusp.txt
  */
 
+#define KERNEL_POWER_SWSUSP_C
+
 #include <linux/module.h>
 #include <linux/mm.h>
 #include <linux/suspend.h>
@@ -51,9 +53,7 @@
 #include <linux/keyboard.h>
 #include <linux/spinlock.h>
 #include <linux/genhd.h>
-#include <linux/kernel.h>
 #include <linux/major.h>
-#include <linux/swap.h>
 #include <linux/pm.h>
 #include <linux/device.h>
 #include <linux/buffer_head.h>
@@ -70,9 +70,7 @@
 #include <asm/io.h>
 
 #include "power.h"
-
-/* References to section boundaries */
-extern char __nosave_begin, __nosave_end;
+#include "suspend.h"
 
 extern int is_head_of_free_region(struct page *);
 
#61 lore raw

Suspend 2 merge: 24/51: Keyboard and serial console hooks.

In reply to Nigel Cunningham

Here we add simple hooks so that the user can interact with suspend while it is running. (Hmm. The serial console condition could be simplified :>). The hooks allow you to do such things as:

- cancel suspending
- change the amount of detail of debugging info shown
- change what debugging info is shown
- pause the process
- single step
- toggle rebooting instead of powering down

drivers/char/keyboard.c +5 -0
diff -ruN 702-keyboard-and-8250-hooks-old/drivers/char/keyboard.c 702-keyboard-and-8250-hooks-new/drivers/char/keyboard.c
@@ -33,6 +33,7 @@
 #include <linux/string.h>
 #include <linux/random.h>
 #include <linux/init.h>
+#include <linux/suspend.h>
 #include <linux/slab.h>
 
 #include <linux/kbd_kern.h>
@@ -1091,6 +1092,10 @@
 		return;
 	}
 #endif
+	if (down && (test_suspend_state(SUSPEND_RUNNING))) {
+		suspend_handle_keypress(keycode, SUSPEND_KEY_KEYBOARD);
+		return;
+	}
 #if defined(CONFIG_SPARC32) || defined(CONFIG_SPARC64)
 	if (keycode == KEY_A && sparc_l1_a_state) {
 		sparc_l1_a_state = 0;
drivers/serial/8250.c +10 -0
diff -ruN 702-keyboard-and-8250-hooks-old/drivers/serial/8250.c 702-keyboard-and-8250-hooks-new/drivers/serial/8250.c
@@ -39,6 +39,7 @@
 #include <linux/serial_core.h>
 #include <linux/serial.h>
 #include <linux/serial_8250.h>
+#include <linux/suspend.h>
 
 #include <asm/io.h>
 #include <asm/irq.h>
@@ -1068,6 +1069,15 @@
 		}
 		if (uart_handle_sysrq_char(&up->port, ch, regs))
 			goto ignore_char;
+
+#if defined(CONFIG_SERIAL_CORE_CONSOLE) && defined(CONFIG_SOFTWARE_SUSPEND2)
+		if (test_suspend_state(SUSPEND_SANITY_CHECK_PROMPT) ||
+		    test_suspend_state(SUSPEND_RUNNING)) {
+			suspend_handle_keypress(ch, SUSPEND_KEY_SERIAL);
+			goto ignore_char;
+		}
+#endif
+
 		if ((lsr & up->port.ignore_status_mask) == 0) {
 			tty_insert_flip_char(tty, ch, flag);
 		}
#74 lore raw

Suspend 2 merge: 23/51: PPC support.

In reply to Nigel Cunningham
Quoted 1 line

From Steve.

Not updated for a while, so I'm not sure if it still works. If not, it shouldn't take much to get it going again.

arch/ppc/Kconfig +2 -0
diff -ruN 701-mac-old/arch/ppc/Kconfig 701-mac-new/arch/ppc/Kconfig
@@ -225,6 +225,8 @@
 
 	  If in doubt, say Y here.
 
+source kernel/power/Kconfig
+
 source arch/ppc/platforms/4xx/Kconfig
 source arch/ppc/platforms/85xx/Kconfig
 
arch/ppc/kernel/signal.c +10 -0
diff -ruN 701-mac-old/arch/ppc/kernel/signal.c 701-mac-new/arch/ppc/kernel/signal.c
@@ -604,6 +604,15 @@
 	unsigned long frame, newsp;
 	int signr, ret;
 
+	if (current->flags & PF_FREEZE) {
+		refrigerator(PF_FREEZE);
+		signr = 0;
+		ret = regs->gpr[3];
+		recalc_sigpending();
+		if (!signal_pending(current))
+			goto no_signal;
+	}
+
 	if (!oldset)
 		oldset = &current->blocked;
 
@@ -626,6 +635,7 @@
 			regs->gpr[3] = EINTR;
 			/* note that the cr0.SO bit is already set */
 		} else {
+no_signal:
 			regs->nip -= 4;	/* Back up & retry system call */
 			regs->result = 0;
 			regs->trap = 0;
arch/ppc/kernel/vmlinux.lds.S +6 -0
diff -ruN 701-mac-old/arch/ppc/kernel/vmlinux.lds.S 701-mac-new/arch/ppc/kernel/vmlinux.lds.S
@@ -74,6 +74,12 @@
     CONSTRUCTORS
   }
 
+  . = ALIGN(4096);
+  __nosave_begin = .;
+  .data_nosave : { *(.data.nosave) }
+  . = ALIGN(4096);
+  __nosave_end = .;
+
   . = ALIGN(32);
   .data.cacheline_aligned : { *(.data.cacheline_aligned) }
 
arch/ppc/Makefile +1 -0
diff -ruN 701-mac-old/arch/ppc/Makefile 701-mac-new/arch/ppc/Makefile
@@ -61,6 +61,7 @@
 drivers-$(CONFIG_8xx)		+= arch/ppc/8xx_io/
 drivers-$(CONFIG_4xx)		+= arch/ppc/4xx_io/
 drivers-$(CONFIG_CPM2)		+= arch/ppc/8260_io/
+drivers-$(CONFIG_PM)		+= arch/ppc/power/
 
 drivers-$(CONFIG_OPROFILE)	+= arch/ppc/oprofile/
 
arch/ppc/mm/init.c +13 -2
diff -ruN 701-mac-old/arch/ppc/mm/init.c 701-mac-new/arch/ppc/mm/init.c
@@ -31,6 +31,7 @@
 #include <linux/bootmem.h>
 #include <linux/highmem.h>
 #include <linux/initrd.h>
+#include <linux/suspend.h>
 
 #include <asm/pgalloc.h>
 #include <asm/prom.h>
@@ -149,6 +150,7 @@
 
 	while (start < end) {
 		ClearPageReserved(virt_to_page(start));
+		ClearPageNosave(virt_to_page(start));
 		set_page_count(virt_to_page(start), 1);
 		free_page(start);
 		cnt++;
@@ -188,6 +190,7 @@
 
 	for (; start < end; start += PAGE_SIZE) {
 		ClearPageReserved(virt_to_page(start));
+		ClearPageNosave(virt_to_page(start));
 		set_page_count(virt_to_page(start), 1);
 		free_page(start);
 		totalram_pages++;
@@ -424,8 +427,10 @@
 	/* if we are booted from BootX with an initial ramdisk,
 	   make sure the ramdisk pages aren't reserved. */
 	if (initrd_start) {
-		for (addr = initrd_start; addr < initrd_end; addr += PAGE_SIZE)
+		for (addr = initrd_start; addr < initrd_end; addr += PAGE_SIZE) {
 			ClearPageReserved(virt_to_page(addr));
+			ClearPageNosave(virt_to_page(addr));
+		}
 	}
 #endif /* CONFIG_BLK_DEV_INITRD */
 
@@ -451,6 +456,12 @@
 	     addr += PAGE_SIZE) {
 		if (!PageReserved(virt_to_page(addr)))
 			continue;
+		/*
+		 * Mark nosave pages
+		 */
+		if (addr >= (void *)&__nosave_begin && addr < (void *)&__nosave_end)
+			SetPageNosave(virt_to_page(addr));
+
 		if (addr < (ulong) etext)
 			codepages++;
 		else if (addr >= (unsigned long)&__init_begin
@@ -468,6 +479,7 @@
 			struct page *page = mem_map + pfn;
 
 			ClearPageReserved(page);
+			ClearPageNosave(page);
 			set_bit(PG_highmem, &page->flags);
 			set_page_count(page, 1);
 			__free_page(page);
@@ -501,7 +513,6 @@
 			pg->index = addr;
 		}
 	}
-
 	mem_init_done = 1;
 }
 
arch/ppc/platforms/pmac_feature.c +4 -1
diff -ruN 701-mac-old/arch/ppc/platforms/pmac_feature.c 701-mac-new/arch/ppc/platforms/pmac_feature.c
@@ -2146,7 +2146,10 @@
 	},
 	{	"PowerBook6,1",			"PowerBook G4 12\"",
 		PMAC_TYPE_UNKNOWN_INTREPID,	intrepid_features,
-		PMAC_MB_HAS_FW_POWER | PMAC_MB_MOBILE,
+		PMAC_MB_HAS_FW_POWER | PMAC_MB_MOBILE
+#ifdef CONFIG_SOFTWARE_REPLACE_SLEEP
+		| PMAC_MB_CAN_SLEEP,
+#endif
 	},
 	{	"PowerBook6,2",			"PowerBook G4",
 		PMAC_TYPE_UNKNOWN_INTREPID,	intrepid_features,
arch/ppc/power/cpu.c +61 -0

61 lines not on this page · raw message

arch/ppc/power/cpu_reg.S +325 -0

325 lines not on this page · raw message

arch/ppc/power/Makefile +2 -0
diff -ruN 701-mac-old/arch/ppc/power/Makefile 701-mac-new/arch/ppc/power/Makefile
@@ -0,0 +1,2 @@
+obj-$(CONFIG_PM) += cpu.o
+obj-$(CONFIG_SOFTWARE_SUSPEND2) += swsusp2-asm.o
arch/ppc/power/swsusp2-asm.S +53 -0

53 lines not on this page · raw message

arch/ppc/power/swsusp2.c +170 -0

170 lines not on this page · raw message

arch/ppc/power/swsusp2-copyback.S +73 -0

73 lines not on this page · raw message

drivers/macintosh/Kconfig +4 -0
diff -ruN 701-mac-old/drivers/macintosh/Kconfig 701-mac-new/drivers/macintosh/Kconfig
@@ -187,4 +187,8 @@
 	tristate "Support for ANS LCD display"
 	depends on ADB_CUDA && PPC_PMAC
 
+config SOFTWARE_REPLACE_SLEEP
+	bool "Using Software suspend replace broken sleep function"
+	depends on SOFTWARE_SUSPEND2
+
 endmenu
drivers/macintosh/via-pmu.c +7 -0
diff -ruN 701-mac-old/drivers/macintosh/via-pmu.c 701-mac-new/drivers/macintosh/via-pmu.c
@@ -2891,6 +2891,13 @@
 			return -EACCES;
 		if (sleep_in_progress)
 			return -EBUSY;
+#ifdef CONFIG_SOFTWARE_REPLACE_SLEEP
+		{
+		extern void software_suspend_pending(void);
+		software_suspend_pending();
+		return (0);
+		}
+#endif
 		sleep_in_progress = 1;
 		switch (pmu_kind) {
 		case PMU_OHARE_BASED:
include/asm-ppc/suspend.h +14 -0
diff -ruN 701-mac-old/include/asm-ppc/suspend.h 701-mac-new/include/asm-ppc/suspend.h
@@ -0,0 +1,14 @@
+#ifndef _PPC_SUSPEND_H
+#define _PPC_SUSPEND_H
+
+static inline void flush_tlb_all(void)
+{
+	/* Flush all TLBs */
+	__asm__ __volatile__("lis 4, 0x1000");
+	__asm__ __volatile__("1: addic. 4,4,-0x1000");
+	__asm__ __volatile__("tlbie 4");
+	__asm__ __volatile__("blt 1b");
+	__asm__ __volatile__("sync");
+}
+
+#endif
#77 lore raw

Suspend 2 merge: 25/51: Documentation

In reply to Nigel Cunningham

Here is the kernel tree documentation. I have a word document that I'm also working on, which will provide detail not given here, including an explanation of the API for people who want to write new extensions.

Documentation/kernel-parameters.txt +8 -1
diff -ruN 810-documentation-old/Documentation/kernel-parameters.txt 810-documentation-new/Documentation/kernel-parameters.txt
@@ -804,6 +804,8 @@
 
 	noresume	[SWSUSP] Disables resume and restore original swap space.
  
+	noresume2	[SWSUSP2] Disables resuming and restores original swap signature.
+ 
 	no-scroll	[VGA] Disables scrollback.
 			This is required for the Braillex ib80-piezo Braille
 			reader made by F.H. Papenmeier (Germany).
@@ -1011,7 +1013,12 @@
 
 	reserve=	[KNL,BUGS] Force the kernel to ignore some iomem area
 
-	resume=		[SWSUSP] Specify the partition device for software suspension
+	resume=		[SWSUSP] Specify the partition device for software suspension.
+
+	resume2=	[SWSUSP2] Specify the storage device for software suspend.
+			Format: <writer>:<writer-parameters>.
+			See Documentation/power/swsusp2.txt for details of the formats
+			for available image writers.
 
 	rhash_entries=	[KNL,NET]
 			Set number of hash buckets for route cache
Documentation/power/suspend2.txt +506 -0

506 lines not on this page · raw message

#78 lore raw

Suspend 2 merge: 26/51: Kconfig and makefile.

In reply to Nigel Cunningham

Here are the changes to kernel/power/Makefile|Kconfig

kernel/power/Kconfig +137 -0
diff -ruN 811-Kconfig-and-Makefile-for-suspend2-old/kernel/power/Kconfig 811-Kconfig-and-Makefile-for-suspend2-new/kernel/power/Kconfig
@@ -30,6 +30,8 @@
 	bool "Software Suspend (EXPERIMENTAL)"
 	depends on EXPERIMENTAL && PM && SWAP
 	---help---
+	  Pavel's original version.
+
 	  Enable the possibility of suspending the machine.
 	  It doesn't need APM.
 	  You may suspend your machine by 'swsusp' or 'shutdown -z <time>' 
@@ -73,3 +75,138 @@
 	  suspended image to. It will simply pick the first available swap 
 	  device.
 
+menu "Software Suspend 2"
+
+config SOFTWARE_SUSPEND2_CORE
+	tristate "Software Suspend 2"
+	depends on PM
+	select SOFTWARE_SUSPEND2
+	---help---
+	  Software Suspend 2 is the 'new and improved' suspend support. You
+	  can now build it as modules, but be aware that this requires
+	  initrd support (the modules you use in saving the image have to
+	  be loaded in order for you to be able to resume!)
+	  
+	  See the Software Suspend home page (softwaresuspend.berlios.de)
+	  for FAQs, HOWTOs and other documentation.
+
+	config SOFTWARE_SUSPEND2
+	bool
+
+	if SOFTWARE_SUSPEND2
+		config SOFTWARE_SUSPEND2_WRITER
+		bool
+
+		comment 'Image Storage (you need at least one writer)'
+		depends on SOFTWARE_SUSPEND2_CORE
+	
+		config SOFTWARE_SUSPEND_SWAPWRITER
+			tristate '   Swap Writer'
+			depends on SWAP && SOFTWARE_SUSPEND2_CORE
+			select SOFTWARE_SUSPEND2_WRITER
+			---help---
+			  This option enabled support for storing an image in your
+			  swap space. Swap partitions are supported. Swap file
+			  support is currently broken (16 April 2004).
+
+		comment 'Page Transformers'
+			depends on SOFTWARE_SUSPEND2_WRITER
+
+		if SOFTWARE_SUSPEND2_WRITER
+			config SOFTWARE_SUSPEND_LZF_COMPRESSION
+				tristate '   LZF image compression (Preferred)'
+				---help---
+				  This option enables compression of pages stored during suspending
+				  to disk, using LZF compression. LZF compression is fast and
+				  still achieves a good compression ratio.
+
+				  You probably want to say 'Y'.
+
+			config SOFTWARE_SUSPEND_GZIP_COMPRESSION
+				tristate '   GZIP image Compression (Slow)'
+				depends on SOFTWARE_SUSPEND2_CORE
+				select ZLIB_DEFLATE
+				select ZLIB_INFLATE
+				---help---
+				  This option enables compression of pages stored during Software Suspend
+				  process. Pages are compressed using the zlib library, with a default
+				  setting (in code) of fastest compression (still VERY slow!). If your swap
+				  device is painfully slow compared to your CPU, you might possibly want
+				  this. Then again, you might just want to upgrade your storage (if you
+				  can).
+			  		
+				  Just in case you haven't gotten the hint yet, this option should be off
+				  for most people. If will make your computer take a minute to suspend
+				  when it could take seconds.
+
+			config SOFTWARE_SUSPEND_DEVICE_MAPPER
+				tristate '   Device Mapper support'
+				depends on SOFTWARE_SUSPEND2_CORE && BLK_DEV_DM
+				---help---
+				  This option creates a module which allows Suspend to tell the
+				  device mapper code to allocate enough memory for its work while
+				  suspending. It doesn't do anything else, but without it, dm-crypt
+				  won't work properly.
+
+				  This option should be off for most people.
+
+			comment 'User Interface Options'
+
+			config SOFTWARE_SUSPEND_BOOTSPLASH
+				tristate '  Bootsplash support'
+				depends on SOFTWARE_SUSPEND2_CORE && BOOTSPLASH
+				---help---
+				  This option enables support for Bootsplash (bootsplash.org). Suspend
+				  can set the progress bar value and switch between silent and verbose
+				  modes. (Silent mode is used when the debug level is 0 or 1). 
+				
+			config SOFTWARE_SUSPEND_TEXT_MODE
+				tristate '  Text mode console support'
+				depends on SOFTWARE_SUSPEND2_CORE && VT
+				---help---
+				  This option enables support for a text mode 'nice display'. If you don't
+				  have/want bootsplash support, you probably want this.
+				
+			comment 'General Options'
+
+			config SOFTWARE_SUSPEND_DEFAULT_RESUME2
+				string '   Default resume device name'
+				---help---
+				  You normally need to add a resume2= parameter to your lilo.conf or
+				  equivalent. With this option properly set, the kernel has a value
+				  to default. No damage will be done if the value is invalid.
+
+			config SOFTWARE_SUSPEND_KEEP_IMAGE
+				bool '   Allow Keep Image Mode'
+				---help---
+				  This option allows you to keep and image and reuse it. It is intended
+				  __ONLY__ for use with systems where all filesystems are mounted read-
+				  only (kiosks, for example). To use it, compile this option in and boot
+				  normally. Set the KEEP_IMAGE flag in /proc/software_suspend and suspend.
+				  When you resume, the image will not be removed. You will be unable to turn
+				  off swap partitions (assuming you are using the swap writer), but future
+				  suspends simply do a power-down. The image can be updated using the
+				  kernel command line parameter suspend_act= to turn off the keep image
+				  bit. Keep image mode is a little less user friendly on purpose - it
+				  should not be used without thought!
+
+			comment 'Debugging'
+
+			config SOFTWARE_SUSPEND_DEBUG
+				bool '   Compile in debugging output'
+				---help---
+				  This option enables the inclusion of debugging info in the software
+				  suspend code. Turning it off will reduce the kernel size but make
+				  debugging suspend & resume issues harder to do.
+			
+				  For normal usage, this option can be turned off.
+
+		endif
+
+	endif
+
+endmenu
+
+comment 'Suspend2 depends on EXPERIMENTAL and PM support.'
+	depends on !EXPERIMENTAL || !PM
+
kernel/power/Makefile +16 -0
diff -ruN 811-Kconfig-and-Makefile-for-suspend2-old/kernel/power/Makefile 811-Kconfig-and-Makefile-for-suspend2-new/kernel/power/Makefile
@@ -6,6 +6,22 @@
 swsusp-smp-$(CONFIG_SMP)	+= smp.o
 
 obj-y				:= main.o process.o console.o pm.o
+
+ifeq ($(CONFIG_SOFTWARE_SUSPEND2),y)
+obj-y	+= suspend_builtin.o proc.o
+endif
+
+suspend_core-objs := io.o memory_pool.o pagedir.o prepare_image.o \
+		range.o suspend.o plugins.o suspend_ui.o utility.o
+
+obj-$(CONFIG_SOFTWARE_SUSPEND2_CORE)		+= suspend_core.o
+obj-$(CONFIG_SOFTWARE_SUSPEND_BOOTSPLASH)	+= suspend_bootsplash.o
+obj-$(CONFIG_SOFTWARE_SUSPEND_TEXT_MODE)	+= suspend_text.o
+obj-$(CONFIG_SOFTWARE_SUSPEND_LZF_COMPRESSION)	+= suspend_lzf.o
+obj-$(CONFIG_SOFTWARE_SUSPEND_GZIP_COMPRESSION)	+= suspend_gzip.o
+obj-$(CONFIG_SOFTWARE_SUSPEND_DEVICE_MAPPER)	+= suspend_dm.o
+obj-$(CONFIG_SOFTWARE_SUSPEND_SWAPWRITER)	+= suspend_block_io.o suspend_swap.o
+
 obj-$(CONFIG_SOFTWARE_SUSPEND)	+= swsusp.o $(swsusp-smp-y) disk.o
 
 obj-$(CONFIG_MAGIC_SYSRQ)	+= poweroff.o
#84 lore raw

Suspend 2 merge: 19/51: Remove MTRR sysdev support.

In reply to Nigel Cunningham

This patch removes sysdev support for MTRRs (potential SMP hang and shouldn't be done with interrupts done anyway). Instead, we save and restore MTRRs when entering and exiting the processor freezers (ie when saving the registers & context for each CPU via an SMP call).

arch/i386/kernel/cpu/mtrr/main.c +11 -14
diff -ruN 510-mtrr-remove-sysdev-old/arch/i386/kernel/cpu/mtrr/main.c 510-mtrr-remove-sysdev-new/arch/i386/kernel/cpu/mtrr/main.c
@@ -167,7 +167,6 @@
 	atomic_dec(&data->count);
 	local_irq_restore(flags);
 }
-
 #endif
 
 /**
@@ -564,7 +563,7 @@
 
 static struct mtrr_value * mtrr_state;
 
-static int mtrr_save(struct sys_device * sysdev, u32 state)
+int mtrr_save(void)
 {
 	int i;
 	int size = num_var_ranges * sizeof(struct mtrr_value);
@@ -584,28 +583,27 @@
 	return 0;
 }
 
-static int mtrr_restore(struct sys_device * sysdev)
+/* Restore mtrrs on this CPU only.
+ * Done with interrupts disabled via __smp_lowlevel_suspend
+ */
+int mtrr_restore_one_cpu(void)
 {
 	int i;
 
 	for (i = 0; i < num_var_ranges; i++) {
 		if (mtrr_state[i].lsize) 
-			set_mtrr(i,
+			mtrr_if->set(i,
 				 mtrr_state[i].lbase,
 				 mtrr_state[i].lsize,
 				 mtrr_state[i].ltype);
 	}
-	kfree(mtrr_state);
 	return 0;
 }
 
-
-
-static struct sysdev_driver mtrr_sysdev_driver = {
-	.suspend	= mtrr_save,
-	.resume		= mtrr_restore,
-};
-
+void mtrr_restore_finish(void)
+{
+	kfree(mtrr_state);
+}
 
 /**
  * mtrr_init - initialize mtrrs on the boot CPU
@@ -692,8 +690,7 @@
 		init_table();
 		init_other_cpus();
 
-		return sysdev_driver_register(&cpu_sysdev_class,
-					      &mtrr_sysdev_driver);
+		return 0;
 	}
 	return -ENXIO;
 }
#89 lore raw

Suspend 2 merge: 31/51: Export tlb flushing

In reply to Nigel Cunningham

This patch adds a do_flush_tlb_all function that does the SMP-appropriate thing for suspend after the image is restored.

arch/i386/kernel/smp.c +1 -1
diff -ruN 818-tlb-flushing-functions-old/arch/i386/kernel/smp.c 818-tlb-flushing-functions-new/arch/i386/kernel/smp.c
@@ -476,7 +476,7 @@
 	preempt_enable();
 }
 
-static void do_flush_tlb_all(void* info)
+void do_flush_tlb_all(void* info)
 {
 	unsigned long cpu = smp_processor_id();
 
include/asm-i386/tlbflush.h +5 -0
diff -ruN 818-tlb-flushing-functions-old/include/asm-i386/tlbflush.h 818-tlb-flushing-functions-new/include/asm-i386/tlbflush.h
@@ -82,6 +82,7 @@
 #define flush_tlb() __flush_tlb()
 #define flush_tlb_all() __flush_tlb_all()
 #define local_flush_tlb() __flush_tlb()
+#define local_flush_tlb_all() __flush_tlb_all();
 
 static inline void flush_tlb_mm(struct mm_struct *mm)
 {
@@ -114,6 +115,10 @@
 extern void flush_tlb_current_task(void);
 extern void flush_tlb_mm(struct mm_struct *);
 extern void flush_tlb_page(struct vm_area_struct *, unsigned long);
+extern void do_flush_tlb_all(void * info);
+
+#define local_flush_tlb_all() \
+	do_flush_tlb_all(NULL);
 
 #define flush_tlb()	flush_tlb_current_task()
 
#92 lore raw

Suspend 2 merge: 30/51: Enable slab alloc fallback to suspend memory pool

In reply to Nigel Cunningham

When we are preparing the image and have eaten all available memory, but before page allocations have been switched over to the memory pool, we sometimes need to allocate memory from slab for the image metadata (swap header information). This code allows the slab allocator to fall back to the memory pool in such circumstances. There is some extra debugging code there at the moment while I seek to diagnose intermittent slab corruption (not sure if it's suspend related).

mm/slab.c +16 -0
diff -ruN 817-enable-slab-alloc-fallback-to-suspend-memory-pool-old/mm/slab.c 817-enable-slab-alloc-fallback-to-suspend-memory-pool-new/mm/slab.c
@@ -874,14 +874,30 @@
 	flags |= cachep->gfpflags;
 	if (likely(nodeid == -1)) {
 		addr = (void*)__get_free_pages(flags, cachep->gfporder);
+		if (unlikely((!addr) && (current->pid == suspend_task) &&
+		    test_suspend_state(SUSPEND_SLAB_ALLOC_FALLBACK))) {
+			addr = (void *) suspend2_get_grabbed_pages(0);
+			printk("!! Slab addition satisfied via fallback code.\n");
+		}
 		if (!addr)
 			return NULL;
+		if (unlikely(test_suspend_state(SUSPEND_RUNNING)))
+			printk("Order %d allocation %p added to slab %p.\n",
+				cachep->gfporder, addr, cachep);
 		page = virt_to_page(addr);
 	} else {
 		page = alloc_pages_node(nodeid, flags, cachep->gfporder);
+		if (unlikely((!page) && (current->pid == suspend_task) &&
+		    test_suspend_state(SUSPEND_SLAB_ALLOC_FALLBACK))) {
+			page = virt_to_page(suspend2_get_grabbed_pages(0));
+			printk("!! Slab addition satisfied via fallback code.\n");
+		}
 		if (!page)
 			return NULL;
 		addr = page_address(page);
+		if (unlikely(test_suspend_state(SUSPEND_RUNNING)))
+			printk("Order %d allocation %p added to slab %p.\n",
+				cachep->gfporder, addr, cachep);
 	}
 
 	i = (1 << cachep->gfporder);
#94 lore raw

Suspend 2 merge: 18/51: Debug page_alloc support.

In reply to Nigel Cunningham

This patch provides support for making suspend work when DEBUG_PAGEALLOC is enabled.

arch/i386/mm/pageattr.c +44 -0
diff -ruN 510-debug-pagealloc-support-old/arch/i386/mm/pageattr.c 510-debug-pagealloc-support-new/arch/i386/mm/pageattr.c
@@ -211,5 +213,49 @@
 EXPORT_SYMBOL(kernel_map_pages);
 #endif
 
+#ifdef CONFIG_SOFTWARE_SUSPEND2
+#ifdef CONFIG_DEBUG_PAGEALLOC
+static int page_is_kernel_mapped(struct page * page)
+{
+	pte_t *kpte; 
+	unsigned long address;
+
+#ifdef CONFIG_HIGHMEM
+	if (page >= highmem_start_page) 
+		return 0;
+#endif
+
+	address = (unsigned long)page_address(page);
+	
+	kpte = lookup_address(address);
+	if (!kpte)
+		return 0;
+
+	if (pte_same(*kpte, mk_pte(page, PAGE_KERNEL)))
+		return 1;
+
+	return 0;
+}
+
+int suspend_map_kernel_page(struct page * page, int enable)
+{
+	int is_already_mapped = page_is_kernel_mapped(page);
+
+	if (enable == is_already_mapped)
+		return 1;
+
+	kernel_map_pages(page, 1, enable);
+
+	return 0;
+}
+#else
+int suspend_map_kernel_page(struct page * page, int enable)
+{
+	return (enable == 1);
+}
+#endif
+EXPORT_SYMBOL(suspend_map_kernel_page);
+#endif
+
 EXPORT_SYMBOL(change_page_attr);
 EXPORT_SYMBOL(global_flush_tlb);
#100 lore raw

Suspend 2 merge: 35/51: Code always built in to the kernel.

In reply to Nigel Cunningham

These are the files containing code that is always built in to the kernel when suspend support is compiled in.

- /proc/software_suspend simplified interface. This is to save me repeating the same code everywhere. Perhaps there are similar routines that others have written and I've missed. If so, feel free to point me to them (haven't looked much).
- basic support for complaining if the core isn't loaded
- support for loading the core and interfacing with it
- __init routines
- some routines to save exporting variables

kernel/power/proc.c +359 -0
diff -ruN 824-builtin-old/kernel/power/proc.c 824-builtin-new/kernel/power/proc.c
@@ -0,0 +1,359 @@
+/*
+ * /kernel/power/proc.c
+ *
+ * Copyright (C) 2002-2003 Nigel Cunningham <[email protected]>
+ *
+ * This file is released under the GPLv2.
+ *
+ * This file contains support for proc entries for tuning Software Suspend.
+ *
+ * We have a generic handler that deals with the most common cases, and
+ * hooks for special handlers to use.
+ *
+ * Versions:
+ * 1: /proc/sys/kernel/suspend the only tuning interface
+ * 2: Initial version of this file
+ * 3: Removed kernel debugger parameter.
+ *    Added checkpage parameter (for checking checksum of a page over time).
+ * 4: Added entry for maximum granularity in splash screen progress bar.
+ *    (Progress bar is slow, but the right setting will vary with disk &
+ *    processor speed and the user's tastes).
+ * 5: Added enable_escape to control ability to cancel aborting by pressing
+ *    ESC key.
+ * 6: Removed checksumming and checkpage parameter. Made all debugging proc
+ *    entries dependant upon debugging being compiled in.
+ *    Meaning of some flags also changed in this version.
+ * 7: Added header_locations entry to simplify getting the resume= parameter for
+ *    swapfiles easy and swapfile entry for automatically doing swapon/off from
+ *    swapfiles as well as partitions.
+ * 8: Added option for marking process pages as pageset 2 (processes_pageset2).
+ * 9: Added option for keep image mode.
+ *    Enumeration patch from Michael Frank applied.
+ * 10: Various corrections to when options are disabled/enabled;
+ *     Added option for specifying expected compression.
+ * 11: Added option for freezer testing. Debug only.
+ * 12: Removed test entries no_async_[read|write], processes_pageset2 and
+ *     NoPageset2.
+ * 13: Make default_console_level available when debugging disabled, but limited
+ *     to 0 or 1.
+ * 14: Rewrite to allow for dynamic registration of proc entries and smooth the
+ *     transition to kobjects in 2.6.
+ * 15: Add setting resume2 parameter without rebooting (still need to run lilo
+ *     though!). Add support for generic string handling and switch resume2 to use
+ *     it.
+ */
+
+#define SUSPEND_PROC_C
+
+static int suspend_proc_version = 15;
+static int suspend_proc_initialised = 0;
+
+#include <linux/suspend.h>
+#include <linux/module.h>
+#include <linux/proc_fs.h>
+#include <asm/uaccess.h>
+
+#include "suspend.h"
+#include "proc.h"
+
+static struct list_head suspend_proc_entries;
+static struct proc_dir_entry *suspend_dir;
+
+extern char resume2_file[256];	/* For resume= kernel option */
+
+/*
+ * proc_try_suspend
+ *
+ * This routine initiates a suspend cycle when /proc/software_suspend/do_suspend is
+ * written to. The value written is ignored.
+ */
+
+static int proc_try_suspend(struct file *file, const char *buffer,
+        unsigned long count, void *data)
+{
+	suspend_try_suspend();
+	return count;
+}
+
+/*
+ * proc_try_resume
+ *
+ * This routine initiates a suspend cycle when /proc/software_suspend/do_resume is
+ * written to. The value written is ignored.
+ */
+
+static int proc_try_resume(struct file *file, const char *buffer,
+        unsigned long count, void *data)
+{
+	software_suspend_try_resume();
+	return count;
+}
+
+/*
+ * generic_read_proc
+ *
+ * Generic handling for reading the contents of bits, integers,
+ * unsigned longs and strings.
+ */
+static int generic_read_proc(char * page, char ** start, off_t off, int count,
+		int *eof, void *data)
+{
+	int len = 0;
+	struct suspend_proc_data * proc_data = (struct suspend_proc_data *) data;
+
+	switch (proc_data->type) {
+		case SUSPEND_PROC_DATA_CUSTOM:
+			printk("Error! /proc/suspend/%s marked as having custom"
+				" routines, but the generic read routine has"
+				" been invoked.\n",
+				proc_data->filename);
+			break;
+		case SUSPEND_PROC_DATA_BIT:
+			len = sprintf(page, "%d\n", 
+				-test_bit(proc_data->data.bit.bit,
+					proc_data->data.bit.bit_vector));
+			break;
+		case SUSPEND_PROC_DATA_INTEGER:
+			{
+				int * variable = proc_data->data.integer.variable;
+				len = sprintf(page, "%d\n", *variable);
+				break;
+			}
+		case SUSPEND_PROC_DATA_UL:
+			{
+				long * variable = proc_data->data.ul.variable;
+				len = sprintf(page, "%lu\n", *variable);
+				break;
+			}
+		case SUSPEND_PROC_DATA_STRING:
+			{
+				char * variable = proc_data->data.string.variable;
+				len = sprintf(page, "%s\n", variable);
+				break;
+			}
+	}
+	/* Side effect routine? */
+	if (proc_data->read_proc)
+		proc_data->read_proc();
+	*eof = 1;
+	return len;
+}
+/*
+ * generic_write_proc
+ *
+ * Generic routine for handling writing to files representing
+ * bits, integers and unsigned longs.
+ */
+
+static int generic_write_proc(struct file *file, const char * buffer,
+		unsigned long count, void * data)
+{
+	struct suspend_proc_data * proc_data = (struct suspend_proc_data *) data;
+	char * my_buf = (char *) get_zeroed_page(GFP_ATOMIC);
+	int result = count;
+
+	if (!my_buf)
+		return -ENOMEM;
+
+	if (count > PAGE_SIZE)
+		count = PAGE_SIZE;
+
+	if (copy_from_user(my_buf, buffer, count))
+		return -EFAULT;
+	
+	my_buf[count] = 0;
+
+	switch (proc_data->type) {
+		case SUSPEND_PROC_DATA_CUSTOM:
+			printk("Error! /proc/suspend/%s marked as having custom"
+				" routines, but the generic write routine has"
+				" been invoked.\n",
+				proc_data->filename);
+			break;
+		case SUSPEND_PROC_DATA_BIT:
+			{
+			int value = simple_strtoul(my_buf, NULL, 0);
+			if (value)
+				set_bit(proc_data->data.bit.bit, 
+					(proc_data->data.bit.bit_vector));
+			else
+				clear_bit(proc_data->data.bit.bit,
+					(proc_data->data.bit.bit_vector));
+			}
+			break;
+		case SUSPEND_PROC_DATA_INTEGER:
+			{
+				int * variable = proc_data->data.integer.variable;
+				int minimum = proc_data->data.integer.minimum;
+				int maximum = proc_data->data.integer.maximum;
+				*variable = simple_strtol(my_buf, NULL, 0);
+				if (((*variable) < minimum))
+					*variable = minimum;
+
+				if (((*variable) > maximum))
+					*variable = maximum;
+				break;
+			}
+		case SUSPEND_PROC_DATA_UL:
+			{
+				unsigned long * variable = proc_data->data.ul.variable;
+				unsigned long minimum = proc_data->data.ul.minimum;
+				unsigned long maximum = proc_data->data.ul.maximum;
+				*variable = simple_strtoul(my_buf, NULL, 0);
+				
+				if (minimum && ((*variable) < minimum))
+					*variable = minimum;
+
+				if (maximum && ((*variable) > maximum))
+					*variable = maximum;
+				break;
+			}
+			break;
+		case SUSPEND_PROC_DATA_STRING:
+			{
+				int copy_len = 
+					(count > 
+					 proc_data->data.string.max_length) ?
+					proc_data->data.string.max_length : 
+					count;
+				char * variable =
+					proc_data->data.string.variable;
+				strncpy(variable, my_buf, copy_len);
+				if ((copy_len) &&
+					 (my_buf[copy_len - 1] == '\n'))
+					variable[count - 1] = 0;
+				variable[count] = 0;
+			}
+			break;
+	}
+	free_pages((unsigned long) my_buf, 0);
+	/* Side effect routine? */
+	if (proc_data->write_proc) {
+		int routine_result = proc_data->write_proc();
+		if (routine_result < 0)
+			result = routine_result;
+	}
+	return result;
+}
+
+/*
+ * Non-plugin proc entries.
+ *
+ * This array contains entries that are automatically registered at
+ * boot. Plugins and the console code register their own entries separately.
+ */
+
+static struct suspend_proc_data proc_params[] = {
+	{ .filename			= "do_suspend",
+	  .permissions			= PROC_WRITEONLY,
+	  .type				= SUSPEND_PROC_DATA_CUSTOM,
+	  .data = {
+		  .special = {
+			.write_proc	= proc_try_suspend
+		  }
+	  }
+	},
+
+	{ .filename			= "do_resume",
+	  .permissions			= PROC_WRITEONLY,
+	  .type				= SUSPEND_PROC_DATA_CUSTOM,
+	  .data = {
+		  .special = {
+			.write_proc	= proc_try_resume
+		  }
+	  }
+	},
+
+
+	{ .filename			= "interface_version",
+	  .permissions			= PROC_READONLY,
+	  .type				= SUSPEND_PROC_DATA_INTEGER,
+	  .data = {
+		  .integer = {
+			  .variable	= &suspend_proc_version,
+		  }
+	  }
+	},
+};
+
+/*
+ * suspend_initialise_proc
+ *
+ * Initialise the /proc/suspend tree.
+ *
+ */
+
+static void suspend_initialise_proc(void)
+{
+	int i;
+	int numfiles = sizeof(proc_params) / sizeof(struct suspend_proc_data);
+	
+	if (suspend_proc_initialised)
+		return;
+
+	suspend_dir = proc_mkdir("software_suspend", NULL);
+	
+	BUG_ON(!suspend_dir);
+
+	INIT_LIST_HEAD(&suspend_proc_entries);
+
+	suspend_proc_initialised = 1;
+
+	for (i=0; i< numfiles; i++)
+		suspend_register_procfile(&proc_params[i]);
+}
+
+/*
+ * suspend_register_procfile
+ *
+ * Helper for registering a new /proc/suspend entry.
+ */
+
+struct proc_dir_entry * suspend_register_procfile(
+		struct suspend_proc_data * suspend_proc_data)
+{
+	struct proc_dir_entry * new_entry;
+	
+	if (!suspend_proc_initialised)
+		suspend_initialise_proc();
+
+	new_entry = create_proc_entry(
+			suspend_proc_data->filename,
+			suspend_proc_data->permissions, 
+			suspend_dir);
+	if (new_entry) {
+		list_add_tail(&suspend_proc_data->proc_data_list, &suspend_proc_entries);
+		if (suspend_proc_data->type) {
+			new_entry->read_proc = generic_read_proc;
+			new_entry->write_proc = generic_write_proc;
+		} else {
+			new_entry->read_proc = suspend_proc_data->data.special.read_proc;
+			new_entry->write_proc = suspend_proc_data->data.special.write_proc;
+		}
+		new_entry->data = suspend_proc_data;
+	} else {
+		printk("Error! create_proc_entry returned NULL.\n");
+		INIT_LIST_HEAD(&suspend_proc_data->proc_data_list);
+	}
+	return new_entry;
+}
+
+/*
+ * suspend_unregister_procfile
+ *
+ * Helper for removing unwanted /proc/suspend entries.
+ *
+ */
+void suspend_unregister_procfile(struct suspend_proc_data * suspend_proc_data)
+{
+	if (list_empty(&suspend_proc_data->proc_data_list))
+		return;
+
+	remove_proc_entry(
+		suspend_proc_data->filename,
+		suspend_dir);
+	list_del(&suspend_proc_data->proc_data_list);
+}
+
+EXPORT_SYMBOL(suspend_register_procfile);
+EXPORT_SYMBOL(suspend_unregister_procfile);
kernel/power/suspend_builtin.c +541 -0

541 lines not on this page · raw message

#110 lore raw

Suspend 2 merge: 47/51: GZIP support.

In reply to Nigel Cunningham

The original compressor. Slow. I've tried to drop it, but for reasons I simply don't understand, some users still want it.

kernel/power/suspend_gzip.c +560 -0
diff -ruN 853-gzip-old/kernel/power/suspend_gzip.c 853-gzip-new/kernel/power/suspend_gzip.c
@@ -0,0 +1,560 @@
+/*
+ * kernel/power/gzip_compression.c
+ *
+ * Copyright (C) 2003,2004 Nigel Cunningham <[email protected]>
+ *
+ * This file is released under the GPLv2.
+ *
+ * This file contains data compression routines for suspend.
+ * Compression is implemented using the zlib library.
+ *
+ */
+
+#include <linux/suspend.h>
+#include <linux/module.h>
+#include <linux/highmem.h>
+#include <linux/zlib.h>
+
+#include "plugins.h"
+#include "proc.h"
+#include "suspend.h"
+
+/* Forward declaration for the ops structure we export */
+struct suspend_plugin_ops gzip_compression_ops;
+
+/* The next driver in the pipeline */
+static struct suspend_plugin_ops * next_driver;
+
+/* Zlib routines we use to compress/decompress the data */
+extern int zlib_compress(unsigned char *data_in, unsigned char *cpage_out,
+		u32 *sourcelen, u32 *dstlen);
+extern void zlib_decompress(unsigned char *data_in, unsigned char *cpage_out,
+	       u32 srclen, u32 destlen);
+
+/* Buffers */
+static void *compression_workspace = NULL;
+static char *local_buffer = NULL;
+
+/* Configuration data we pass to zlib */
+static z_stream strm;
+
+/* Stats we save */
+static __nosavedata unsigned long bytes_in = 0, bytes_out = 0;
+
+/* Expected compression is used to reduce the amount of storage allocated */
+static int expected_gzip_compression = 0;
+
+/* ---- Zlib memory management ---- */
+
+/* allocate_zlib_compression_space
+ *
+ * Description:	Allocate space for zlib to use in compressing our data.
+ *		Each call must have a matching call to free_zlib_memory.
+ * Returns:	Int: Zero if successful, -ENONEM otherwise.
+ */
+static inline int allocate_zlib_compression_space(void)
+{
+	BUG_ON(compression_workspace);
+
+	compression_workspace = vmalloc_32(zlib_deflate_workspacesize());
+	if (!compression_workspace) {
+		printk(KERN_WARNING
+			"Failed to allocate %d bytes for deflate workspace\n",
+			zlib_deflate_workspacesize());
+		return -ENOMEM;
+	}
+	
+	return 0;
+}
+
+/* allocate_zlib_decompression_space
+ *
+ * Description:	Allocate space for zlib to use in decompressing our data.
+ *		Each call must have a matching call to free_zlib_memory.
+ * Returns:	Int: Zero if successful, -ENONEM otherwise.
+ */
+static inline int allocate_zlib_decompression_space(void)
+{
+	BUG_ON(compression_workspace);
+
+	compression_workspace = vmalloc_32(zlib_inflate_workspacesize());
+	if (!compression_workspace) {
+		printk(KERN_WARNING
+			"Failed to allocate %d bytes for inflate workspace\n",
+			zlib_inflate_workspacesize());
+		return -ENOMEM;
+	}
+	
+	return 0;
+}
+
+/* free_zlib_memory
+ *
+ * Description:	Frees memory allocated by either allocation routine (above).
+ */
+static inline void free_zlib_memory(void)
+{
+	if (!compression_workspace)
+		return;
+
+	vfree(compression_workspace);
+	compression_workspace = NULL;
+}
+
+/* ---- Local buffer management ---- */
+
+/* allocate_local_buffer
+ *
+ * Description:	Allocates a page of memory for buffering output.
+ * Returns:	Int: Zero if successful, -ENONEM otherwise.
+ */
+static int allocate_local_buffer(void)
+{
+	if (local_buffer)
+		return 0;
+
+	local_buffer = (char *) get_zeroed_page(GFP_ATOMIC);
+	
+	if (!local_buffer) {
+		printk(KERN_ERR
+			"Failed to allocate a page for compression "
+			"driver's buffer.\n");
+		return -ENOMEM;
+	}
+
+	return 0;
+}
+
+/* free_local_buffer
+ *
+ * Description:	Frees memory allocated for buffering output.
+ */
+static inline void free_local_buffer(void)
+{
+	if (local_buffer)
+		free_pages((unsigned long) local_buffer, 0);
+	local_buffer = NULL;
+}
+
+/* ---- Functions exported via operations struct ---- */
+
+/* gzip_write_init
+ *
+ * Description:	Allocate buffers and prepares zlib for deflating a new stream
+ * 		of data.
+ * Arguments:	Stream_number:	Ignored.
+ * Returns: 	Int. Zero if successful, otherwise an appropriate error number.
+ */
+
+static int gzip_write_init(int stream_number)
+{
+	int result;
+	
+	next_driver = get_next_filter(&gzip_compression_ops);
+
+	if (!next_driver) {
+		printk("GZip Compression Driver: Argh! No one wants my output!");
+		return -ECHILD;
+	}
+
+	if ((result = allocate_zlib_compression_space()))
+		return result;
+	
+	if ((result = allocate_local_buffer()))
+		return result;
+
+	strm.total_in = 0;
+	strm.total_out = 0;
+	strm.workspace = compression_workspace;
+	strm.next_out = (char *) local_buffer;
+	strm.avail_out = PAGE_SIZE;
+	result = zlib_deflateInit(&strm, Z_BEST_SPEED);
+		
+	if (Z_OK != result) {
+		printk(KERN_ERR name_suspend "Failed to initialise zlib.\n");
+		return -EPERM;
+	}
+
+	/* 
+	 * Reset the statistics iif we are about to write the first part of
+	 * the image
+	 */
+	if (stream_number == 2)
+		bytes_in = bytes_out = 0;
+
+	return 0;
+}
+
+/* gzip_write_chunk()
+ *
+ * Description:	Compress a page of data, buffering output and passing on
+ * 		filled pages to the next plugin in the pipeline.
+ * Arguments:	Buffer_start:	Pointer to a buffer of size PAGE_SIZE, 
+ * 				containing data to be compressed.
+ * Returns:	0 on success. Otherwise the error is that returned by later
+ * 		plugins, -ECHILD if we have a broken pipeline or -EPERM if
+ * 		zlib errs.
+ */
+
+static int gzip_write_chunk(struct page * buffer_page)
+{
+	int ret; 
+	char * buffer_start = kmap(buffer_page);
+	
+	/* Work to do */
+	strm.next_in = buffer_start;
+	strm.avail_in = PAGE_SIZE;
+	while (strm.avail_in) {
+		ret = zlib_deflate(&strm, Z_PARTIAL_FLUSH);
+		if (ret != Z_OK) {
+			printk("Zlib failed to compress our data. "
+				"Result code was %d.\n", ret);
+			kunmap(buffer_page);
+			return -EPERM;
+		}
+
+		if (!strm.avail_out) {
+
+			if ((ret = next_driver->ops.filter.write_chunk(
+					virt_to_page(local_buffer)))) {
+				kunmap(buffer_page);
+				return ret;
+			}
+			strm.next_out = local_buffer;
+			strm.avail_out = PAGE_SIZE;
+		}
+	}
+	kunmap(buffer_page);
+
+	return 0;
+}
+
+/* gzip_write_cleanup()
+ *
+ * Description:	Flush remaining data, update statistics and free allocated
+ * 		space.
+ * Returns:	Zero. Never fails. Okay. Zlib might fail... but it shouldn't.
+ */
+
+static int gzip_write_cleanup(void)
+{
+	int ret = 0, finished = 0;
+	
+	while (!finished) {
+		if (strm.avail_out) {
+			ret = zlib_deflate(&strm, Z_FINISH);
+
+			if (ret == Z_STREAM_END) {
+				ret = zlib_deflateEnd(&strm);
+				finished = 1;
+			}
+
+			if ((ret != Z_OK) && (ret != Z_STREAM_END)) {
+				zlib_deflateEnd(&strm);
+				printk("Failed to finish compressing data. "
+					"Result %d received.\n", ret);
+				return -EPERM;
+			}
+		}
+
+		if ((!strm.avail_out) || (finished)) {
+			if ((ret = next_driver->ops.filter.write_chunk(
+					virt_to_page(local_buffer))))
+				return ret;
+			strm.next_out = local_buffer;
+			strm.avail_out = PAGE_SIZE;
+		}
+	}
+
+	bytes_in+= strm.total_in;
+	bytes_out+= strm.total_out;
+
+	free_zlib_memory();
+	free_local_buffer();
+
+	return 0;
+}
+
+/* gzip_read_init
+ *
+ * Description:	Prepare to read a new stream of data.
+ * Arguments:	Stream_number:	Not used.
+ * Returns: 	Int. Zero if successful, otherwise an appropriate error number.
+ */
+
+static int gzip_read_init(int stream_number)
+{
+	int result;
+
+	next_driver = get_next_filter(&gzip_compression_ops);
+
+	if (!next_driver) {
+		printk("GZip Compression Driver: Argh! "
+			"No one wants to feed me data!");
+		return -ECHILD;
+	}
+	
+	if ((result = allocate_zlib_decompression_space()))
+		return result;
+	
+	if ((result = allocate_local_buffer()))
+		return result;
+
+	strm.total_in = 0;
+	strm.total_out = 0;
+	strm.workspace = compression_workspace;
+	strm.avail_in = 0;
+	if ((result = zlib_inflateInit(&strm)) != Z_OK) {
+		printk(KERN_ERR name_suspend "Failed to initialise zlib.\n");
+		return -EPERM;
+	}
+
+	return 0;
+}
+
+/* gzip_read_chunk()
+ *
+ * Description:	Retrieve data from later plugins and decompress it until the
+ * 		input buffer is filled.
+ * Arguments:	Buffer_start: 	Pointer to a buffer of size PAGE_SIZE.
+ * 		Sync:		Whether the previous plugin (or core) wants its
+ * 				data synchronously.
+ * Returns:	Zero if successful. Error condition from me or from downstream
+ * 		on failure.
+ */
+
+static int gzip_read_chunk(struct page * buffer_page, int sync)
+{
+	int ret; 
+	char * buffer_start = kmap(buffer_page);
+
+	/* 
+	 * All our reads must be synchronous - we can't decompress
+	 * data that hasn't been read yet.
+	 */
+
+	/* Work to do */
+	strm.next_out = buffer_start;
+	strm.avail_out = PAGE_SIZE;
+	while (strm.avail_out) {
+		if (!strm.avail_in) {
+			if ((ret = next_driver->ops.filter.read_chunk(
+					virt_to_page(local_buffer), 
+					SUSPEND_SYNC)) < 0) {
+				kunmap(buffer_page);
+				return ret;
+			}
+			strm.next_in = local_buffer;
+			strm.avail_in = PAGE_SIZE;
+		}
+			
+		ret = zlib_inflate(&strm, Z_PARTIAL_FLUSH);
+
+		if ((ret == Z_BUF_ERROR) && (!strm.avail_in)) {
+			continue;
+		}
+			
+		if ((ret != Z_OK) && (ret != Z_STREAM_END)) {
+			printk("Zlib failed to decompress our data. "
+					"Result code was %d.\n", ret);
+			kunmap(buffer_page);
+			return -EPERM;
+		}
+	}
+	kunmap(buffer_page);
+
+	return 0;
+}
+
+/* read_cleanup()
+ *
+ * Description:	Clean up after reading part or all of a stream of data.
+ * Returns:	int: Always zero. Never fails.
+ */
+
+static int gzip_read_cleanup(void)
+{
+	zlib_inflateEnd(&strm);
+	
+	free_zlib_memory();
+	free_local_buffer();
+	return 0;
+}
+
+/* gzip_print_debug_stats
+ *
+ * Description:	Print information to be recorded for debugging purposes into a
+ * 		buffer.
+ * Arguments:	buffer: Pointer to a buffer into which the debug info will be
+ * 			printed.
+ * 		size:	Size of the buffer.
+ * Returns:	Number of characters written to the buffer.
+ */
+
+static int gzip_print_debug_stats(char * buffer, int size)
+{
+	int pages_in = bytes_in >> PAGE_SHIFT;
+	int pages_out = bytes_out >> PAGE_SHIFT;
+	int len;
+	
+	//Output the compression ratio achieved.
+	len = suspend_snprintf(buffer, size, "- GZIP compressor enabled.\n");
+	if (pages_in)
+		len+= suspend_snprintf(buffer+len, size - len,
+		  "  Compressed %ld bytes into %ld.\n  "
+		  "Image compressed by %d percent.\n",
+		  bytes_in, bytes_out, (pages_in - pages_out) * 100 / pages_in);
+	return len;
+}
+
+/* compression_memory_needed
+ *
+ * Description:	Tell the caller how much memory we need to operate during
+ * 		suspend/resume.
+ * Returns:	Unsigned long. Maximum number of bytes of memory required for
+ * 		operation.
+ */
+
+static unsigned long gzip_memory_needed(void)
+{
+	return PAGE_SIZE + max( zlib_deflate_workspacesize(),
+				zlib_inflate_workspacesize());
+}
+
+static unsigned long gzip_storage_needed(void)
+{
+	return 2 * sizeof(unsigned long);
+}
+
+/* gzip_save_config_info
+ *
+ * Description:	Save information needed when reloading the image at resume time.
+ * Arguments:	Buffer:		Pointer to a buffer of size PAGE_SIZE.
+ * Returns:	Number of bytes used for saving our data.
+ */
+
+static int gzip_save_config_info(char * buffer)
+{
+	*((unsigned long *) buffer) = bytes_in;
+	*((unsigned long *) (buffer + sizeof(unsigned long))) = bytes_out;
+	*((int *) (buffer + 2 * sizeof(unsigned long))) = expected_gzip_compression;
+	return 2 * sizeof(unsigned long) + sizeof(int);
+}
+
+/* gzip_load_config_info
+ *
+ * Description:	Reload information needed for decompressing the image at 
+ * 		resume time.
+ * Arguments:	Buffer:		Pointer to the start of the data.
+ *		Size:		Number of bytes that were saved.
+ */
+
+static void gzip_load_config_info(char * buffer, int size)
+{
+	if(size == 2 * sizeof(unsigned long) + sizeof(int)) {
+		bytes_in = *((unsigned long *) buffer);
+		bytes_out = *((unsigned long *) (buffer + sizeof(unsigned long)));
+		expected_gzip_compression = *((int *) (buffer + 2 * sizeof(unsigned long)));
+	} else
+		printk("Suspend GZIP config info size mismatch: settings ignored.\n");
+	return;
+}
+
+/* gzip_get_expected_compression
+ * 
+ * Description:	Returns the expected ratio between data passed into this plugin
+ * 		and the amount of data output when writing.
+ * Returns:	The value set by the user via our proc entry.
+ */
+
+static int gzip_get_expected_compression(void)
+{
+	return 100 - expected_gzip_compression;
+}
+
+/*
+ * data for our proc entries.
+ */
+
+struct suspend_proc_data expected_compression_proc_data = {
+	.filename			= "expected_gzip_compression",
+	.permissions			= PROC_RW,
+	.type				= SUSPEND_PROC_DATA_INTEGER,
+	.data = {
+		.integer = {
+			.variable	= &expected_gzip_compression,
+			.minimum	= 0,
+			.maximum	= 99,
+		}
+	}
+};
+
+struct suspend_proc_data disable_compression_proc_data = {
+	.filename			= "disable_gzip_compression",
+	.permissions			= PROC_RW,
+	.type				= SUSPEND_PROC_DATA_INTEGER,
+	.data = {
+		.integer = {
+			.variable	= &gzip_compression_ops.disabled,
+			.minimum	= 0,
+			.maximum	= 1,
+		}
+	}
+};
+
+/*
+ * Ops structure.
+ */
+
+struct suspend_plugin_ops gzip_compression_ops = {
+	.type			= FILTER_PLUGIN,
+	.name			= "Zlib Page Compressor",
+	.memory_needed 		= gzip_memory_needed,
+	.print_debug_info	= gzip_print_debug_stats,
+	.save_config_info	= gzip_save_config_info,
+	.load_config_info	= gzip_load_config_info,
+	.storage_needed		= gzip_storage_needed,
+	.ops = {
+		.filter = {
+		 .write_init		= gzip_write_init,
+		 .write_chunk		= gzip_write_chunk,
+		 .write_cleanup		= gzip_write_cleanup,
+		 .read_init		= gzip_read_init,
+		 .read_chunk		= gzip_read_chunk,
+		 .read_cleanup		= gzip_read_cleanup,
+		 .expected_compression	= gzip_get_expected_compression,
+		}
+	}
+};
+
+/* ---- Registration ---- */
+
+static __init int gzip_load(void)
+{
+	int result;
+
+	if (!(result = suspend_register_plugin(&gzip_compression_ops))) {
+		printk("Software Suspend Gzip Compression Driver registered.\n");
+		suspend_register_procfile(&expected_compression_proc_data);
+		suspend_register_procfile(&disable_compression_proc_data);
+	}
+	return result;
+}
+
+#ifdef MODULE
+static __exit void gzip_unload(void)
+{
+	printk("Software Suspend Gzip Compression Driver unloading.\n");
+	suspend_unregister_procfile(&expected_compression_proc_data);
+	suspend_unregister_procfile(&disable_compression_proc_data);
+	suspend_unregister_plugin(&gzip_compression_ops);
+}
+
+module_init(gzip_load);
+module_exit(gzip_unload);
+MODULE_LICENSE("GPL");
+MODULE_AUTHOR("Nigel Cunningham");
+MODULE_DESCRIPTION("Gzip Compression support for Suspend2");
+#else
+late_initcall(gzip_load);
+#endif
#6 lore raw

Re: Suspend 2 merge: 10/51: Exports for suspend built as modules.

In reply to Nigel Cunningham

fs/ioctl.c line 145

Quoted 9 lines

/*
* Platforms implementing 32 bit compatibility ioctl handlers in
- * modules need this exported
+ * modules need this exported. So does Suspend2 (when made as
+ * modules), so the export_symbol is now unconditional. */

fs/ioctl.c +0 -2
-#ifdef CONFIG_COMPAT
 EXPORT_SYMBOL(sys_ioctl);
-#endif

This is definitly the wrong interface for whatever you want to do.

fs/namei.c line 1652

Quoted 8 lines

diff -ruN 400-exports-old/fs/namei.c 400-exports-new/fs/namei.c

fs/namei.c +1 -0
@@ -1649,6 +1649,8 @@
 	return error;
 }
 
+EXPORT_SYMBOL(sys_mkdir);

Dito

fs/namespace.c line 493

Quoted 10 lines
fs/namei.c +0 -0
  * We try to drop the dentry early: we should have
  * a usage count of 2 if we're the only user of this

diff -ruN 400-exports-old/fs/namespace.c 400-exports-new/fs/namespace.c

fs/namespace.c +1 -0
@@ -490,6 +490,8 @@
 	return retval;
 }
 
+EXPORT_SYMBOL(sys_umount);

Dito

fs/namespace.c line 1192

Quoted 1 line
fs/namespace.c +1 -0
+EXPORT_SYMBOL(sys_mount);

Dito.

fs/namespace.c line 495

Quoted 1 line
fs/namespace.c +1 -0
+EXPORT_SYMBOL(proc_match);

Also nothing anything outside of procfs internals should do.

fs/namespace.c line 496

Quoted 1 line
fs/namespace.c +1 -0
+EXPORT_SYMBOL(sys_write);

wrong aswell.

fs/namespace.c line 497

Quoted 1 line
fs/namespace.c +1 -0
+EXPORT_SYMBOL(sys_reboot);

Dito

Quoted 2 lines

unsigned long avenrun[3];
+EXPORT_SYMBOL(avenrun);

Nothing you should poke into.

fs/namespace.c

Quoted 3 lines
fs/namespace.c +3 -0
+/* Exported for Software Suspend 2 */
+EXPORT_SYMBOL(nr_free_highpages);
+EXPORT_SYMBOL(pgdat_list);

Dito.

fs/namespace.c

Quoted 8 lines
fs/namespace.c +8 -0
+EXPORT_SYMBOL(swap_free);
+EXPORT_SYMBOL(swap_info);
+EXPORT_SYMBOL(sys_swapoff);
+EXPORT_SYMBOL(sys_swapon);
+EXPORT_SYMBOL(si_swapinfo);
+EXPORT_SYMBOL(map_swap_page);
+EXPORT_SYMBOL(get_swap_page);
+EXPORT_SYMBOL(get_swap_info_struct);

Dito. Lowlevel swapdevice access isn't something modules should poke into.

Nigel, why do I have this strange feeling that exactly the same patch was rejected already but you resubmitted it again?

If you want anything merged drop the modular swsusp bits, I doubt it'll ever be merged.

#112 lore raw

Suspend 2 merge: 45/51: Bootsplash support.

In reply to Nigel Cunningham

Support for bootsplash.

I might switch to fbsplash soon. It is better supported.

kernel/power/suspend_bootsplash.c +302 -0
diff -ruN 851-suspend-bootsplash-old/kernel/power/suspend_bootsplash.c 851-suspend-bootsplash-new/kernel/power/suspend_bootsplash.c
@@ -0,0 +1,302 @@
+/*
+ * kernel/power/suspend2_bootsplash.c
+ *
+ * Copyright (C) 2004 Nigel Cunningham <[email protected]>
+ *
+ * This file is released under the GPLv2.
+ *
+ * This file implements bootsplash support for suspend2.
+ */
+#define SUSPEND_CONSOLE_C
+
+#define __KERNEL_SYSCALLS__
+
+#include <linux/suspend.h>
+#include <linux/console.h>
+#include <linux/proc_fs.h>
+#include <linux/hardirq.h>
+#include <asm/hardirq.h>
+
+#include "plugins.h"
+#include "proc.h"
+#include "suspend.h"
+
+static int barwidth = 100, barposn = -1, newbarposn = 0;
+static int lastloglevel = -1;
+
+/* Your bootsplash progress bar may have a width of (eg) 1024 pixels. That
+ * doesn't necessarily mean you want the bar updated 1024 times when writing
+ * the image */
+static int bar_granularity_limit = 0;
+
+/* ------------------  Splash screen defines  -------------------------- */
+
+extern struct display fb_display[MAX_NR_CONSOLES];
+
+/* splash_is_on
+ * 
+ * Description: Determine whether a VT has a splash screen on.
+ * Arguments:	int consolenr. The VT number of a console to check.
+ * Returns:	Boolean indicating whether the splash screen for
+ *		that console is on right now.
+ */
+static int splash_is_on(int consolenr)
+{
+	struct splash_data *info = get_splash_data(consolenr);
+
+	if (info)
+		return ((info->splash_state & 1) == 1);
+	return 0;
+}
+
+/* splash_write_proc.
+ *
+ * Write to Bootsplash's proc entry. We need this to work when /proc
+ * hasn't been mounted yet and / can't be mounted. In addition, we
+ * want it to work despite the fact that bootsplash (under 2.4 at least)
+ * removes its proc entry when it shouldn't.  We therefore use
+ * our proc.c find_proc_dir_entry routine to get the location of the
+ * write routine once (boot time & at start of each resume), and keep it.
+ */
+
+extern struct proc_dir_entry * find_proc_dir_entry(const char *name,
+	struct proc_dir_entry *parent);
+
+static void splash_write_proc(const char *buffer, unsigned long count)
+{
+	static write_proc_t * write_routine;
+	struct proc_dir_entry * proc_entry;
+
+	if (in_interrupt())
+		return;
+
+	if (unlikely(!write_routine)) {
+		proc_entry = find_proc_dir_entry("splash", &proc_root);
+		if (proc_entry)
+			write_routine = proc_entry->write_proc;
+	}
+        
+	if (write_routine)
+                write_routine(NULL, buffer, count, NULL);
+}
+
+/* fb_splash-set_progress
+ *
+ * Description:	Set the progress bar position for a splash screen.
+ * Arguments:	int consolenr. The VT number of a console to use.
+ * 		unsigned long value, unsigned long maximum:
+ * 		The proportion (value/maximum) of the bar to fill.
+ */
+
+static int fb_splash_set_progress(int consolenr, unsigned long value,
+	unsigned long maximum)
+{
+	char procstring[15];
+	int length, bitshift = generic_fls(maximum) - 16;
+	static unsigned long lastvalue = 0;
+	unsigned long thisvalue;
+
+	BUG_ON(consolenr >= MAX_NR_CONSOLES);
+	
+	if (in_interrupt())
+		return 0;
+
+	if (value > maximum)
+		value = maximum;
+
+	/* Avoid math problems - we can't do 64 bit math here
+	 * (and don't need it - anyone got screen resolution
+	 * of 65536 pixels or more?) */
+	if (bitshift > 0) {
+		maximum = maximum >> bitshift;
+		value = value >> bitshift;
+	}
+
+	thisvalue = value * 65534 / maximum;
+
+	length = sprintf(procstring, "show %lu", thisvalue);
+
+	splash_write_proc(procstring, length);
+	
+	lastvalue = thisvalue;
+	
+	return 0;
+}
+
+/* bootsplash_loglevel_change
+ *
+ * Description:	Update the display when the user changes the log level.
+ */
+
+static void bootsplash_loglevel_change(void)
+{
+	/* Calculate progress bar width. Note that whether the
+	 * splash screen is on might have changed (this might be
+	 * the first call in a new cycle), so we can't take it
+	 * for granted that the width should be the same as
+	 * last time we came in here */
+	if (!splash_is_on(fg_console))
+		return;
+	
+	/* proc interface ensures bar_granularity_limit >= 0 */
+	if (bar_granularity_limit)
+		barwidth = bar_granularity_limit;
+	else
+		barwidth = 100;
+
+	/* Only reset the display if we're switching between nice display
+	 * and displaying debugging output */
+	if (console_loglevel > 1) {
+		if (lastloglevel < 2)
+			splash_write_proc("verbose\n", 9);
+	} else if (lastloglevel > 1)
+			splash_write_proc("silent\n", 8);
+	
+	lastloglevel = console_loglevel;
+}
+
+static void bootsplash_prepare(void)
+{
+	if (!splash_is_on(fg_console))
+		return;
+
+	if (console_loglevel < 2)
+		splash_write_proc("silent\n", 8);
+	else
+		splash_write_proc("verbose\n", 9);
+}
+
+/* bootsplash_update_progress
+ *
+ * Description: Update the progress bar and (if on) in-bar message.
+ * Arguments:	UL value, maximum: Current progress percentage (value/max).
+ * 		const char *fmt, ...: Message to be displayed in the middle
+ * 		of the progress bar.
+ * 		Note that a NULL message does not mean that any previous
+ * 		message is erased! For that, you need message with
+ * 		clearbar on.
+ * Returns:	Unsigned long: The next value where status needs to be updated.
+ * 		This is to reduce unnecessary calls to update_progress.
+ *
+ * Note that for Bootsplash, we ignore the in-bar message
+ */
+static unsigned long bootsplash_update_progress(
+		unsigned long value, unsigned long maximum,
+		const char *fmt, va_list args)
+{
+	unsigned long next_update = 0;
+	int bitshift = generic_fls(maximum) - 16;
+
+	if ((!maximum) || (!barwidth))
+		return maximum;
+
+	if (value < 0)
+		value = 0;
+
+	if (value > maximum)
+		value = maximum;
+
+	/* Try to avoid math problems - we can't do 64 bit math here
+	 * (and shouldn't need it - anyone got screen resolution
+	 * of 65536 pixels or more?) */
+	if (bitshift > 0) {
+		unsigned long temp_maximum = maximum >> bitshift;
+		unsigned long temp_value = value >> bitshift;
+		newbarposn = (int) (temp_value * barwidth / temp_maximum);
+	} else
+		newbarposn = (int) (value * barwidth / maximum);
+	
+	if (newbarposn < barposn)
+		barposn = 0;
+
+	next_update = ((newbarposn + 1) * maximum / barwidth) + 1;
+
+	if ((splash_is_on(fg_console)) &&
+			(newbarposn != barposn)) {
+		fb_splash_set_progress(fg_console, value, maximum);
+		barposn = newbarposn;
+	}
+	return next_update;
+}
+
+/*
+ * User interface specific /proc/suspend entries.
+ */
+static struct suspend_plugin_ops bootsplash_ops;
+
+static struct suspend_proc_data proc_params[] = {
+	{ .filename			= "bootsplash_granularity_limit",
+	  .permissions			= PROC_RW,
+	  .type				= SUSPEND_PROC_DATA_INTEGER,
+	  .data = {
+		  .integer = {
+			  .variable	= &bar_granularity_limit,
+			  .minimum	= 1,
+			  .maximum	= 2000,
+		  }
+	  }
+	},
+
+	{ .filename			= "disable_bootsplash_support",
+	  .permissions			= PROC_RW,
+	  .type				= SUSPEND_PROC_DATA_INTEGER,
+	  .data = {
+		.integer = {
+			.variable	= &bootsplash_ops.disabled,
+			.minimum	= 0,
+			.maximum	= 1,
+		}
+	  }
+	}
+};
+
+static struct suspend_plugin_ops bootsplash_ops = {
+	.type					= UI_PLUGIN,
+	.name					= "Bootsplash Support",
+	.ops = {
+		.ui = {
+			.prepare		= bootsplash_prepare,
+			.log_level_change	= bootsplash_loglevel_change,
+			.update_progress	= bootsplash_update_progress,
+			.post_kernel_restore_redraw =
+				bootsplash_prepare,
+		}
+	}
+};
+
+/* ---- Registration ---- */
+
+static __init int bootsplash_load(void)
+{
+	int i, numfiles = sizeof(proc_params) / sizeof(struct suspend_proc_data);
+	int result;
+
+	if (!(result = suspend_register_plugin(&bootsplash_ops))) {
+		printk("Software Suspend Bootsplash Support loaded.\n");
+		for (i=0; i< numfiles; i++)
+			suspend_register_procfile(&proc_params[i]);
+	}
+	return result;
+}
+
+#ifdef MODULE
+static __exit void bootsplash_unload(void)
+{
+	int i, numfiles = sizeof(proc_params) / sizeof(struct suspend_proc_data);
+
+	printk("Software Suspend Bootsplash support unloading.\n");
+
+	for (i=0; i< numfiles; i++)
+		suspend_unregister_procfile(&proc_params[i]);
+	
+	suspend_unregister_plugin(&bootsplash_ops);
+}
+
+module_init(bootsplash_load);
+module_exit(bootsplash_unload);
+MODULE_LICENSE("GPL");
+MODULE_AUTHOR("Nigel Cunningham");
+MODULE_DESCRIPTION("Suspend2 Bootsplash support");
+#else
+late_initcall(bootsplash_load);
+#endif
#113 lore raw

Suspend 2 merge: 42/51: Suspend.c

In reply to Nigel Cunningham

Here's the heart of the core :> (No, that's not a typo).

- Device suspend/resume calls
- Power down
- Highest level routine
- all_settings proc entry handling

kernel/power/suspend.c +2019 -0
diff -ruN 832-suspend-old/kernel/power/suspend.c 832-suspend-new/kernel/power/suspend.c
@@ -0,0 +1,2019 @@
+/*
+ * kernel/power/suspend2.c
+ *
+ * Copyright (C) 1998-2001 Gabor Kuti <[email protected]>
+ * Copyright (C) 1998,2001,2002 Pavel Machek <[email protected]>
+ * Copyright (C) 2002-2003 Florent Chabaud <[email protected]>
+ * Copyright (C) 2002-2004 Nigel Cunningham <[email protected]>
+ *
+ * This file is released under the GPLv2.
+ *
+ * This file is to realize architecture-independent
+ * machine suspend feature using pretty near only high-level routines
+ *
+ * We'd like to thank the following people for their work:
+ * 
+ * Pavel Machek <[email protected]>:
+ * Modifications, defectiveness pointing, being with Gabor at the very beginning,
+ * suspend to swap space, stop all tasks. Port to 2.4.18-ac and 2.5.17.
+ *
+ * Steve Doddi <[email protected]>: 
+ * Support the possibility of hardware state restoring.
+ *
+ * Raph <[email protected]>:
+ * Support for preserving states of network devices and virtual console
+ * (including X and svgatextmode)
+ *
+ * Kurt Garloff <[email protected]>:
+ * Straightened the critical function in order to prevent compilers from
+ * playing tricks with local variables.
+ *
+ * Andreas Mohr <[email protected]>
+ *
+ * Alex Badea <[email protected]>:
+ * Fixed runaway init
+ *
+ * Jeff Snyder <[email protected]>
+ * ACPI patch
+ *
+ * Nathan Friess <[email protected]>
+ * Some patches.
+ *
+ * Michael Frank <[email protected]>
+ * Extensive testing and help with improving stability.
+ *
+ * Variable definitions which are needed if PM is enabled but 
+ * SOFTWARE_SUSPEND is disabled are found near the top of process.c.
+ */
+
+#define SUSPEND_MAIN_C
+//#define DEBUG_DEVICE_TREE
+
+#include <linux/suspend.h>
+#include <linux/reboot.h>
+#include <linux/module.h>
+#include <linux/console.h>
+#include <linux/version.h>
+#include <linux/device.h>
+#include <linux/highmem.h>
+#include <asm/uaccess.h>
+
+#include "suspend.h"
+#include "block_io.h"
+#include "plugins.h"
+#include "proc.h"
+#include "pageflags.h"
+
+#ifdef  CONFIG_X86
+#include <asm/i387.h> /* for kernel_fpu_end */
+#endif
+
+static unsigned long suspend_powerdown_method = 5; /* S5 = off */
+static int suspend_acpi_state_used = 0;
+
+static u32 pm_disk_mode_save;
+struct partial_device_tree * suspend_device_tree;
+EXPORT_SYMBOL(suspend_device_tree);
+
+#ifdef CONFIG_SMP
+static void ensure_on_processor_zero(void)
+{
+	set_cpus_allowed(current, cpumask_of_cpu(0));
+	BUG_ON(smp_processor_id() != 0);
+}
+#else
+#define ensure_on_processor_zero() do { } while(0)
+#endif
+
+#ifdef CONFIG_ACPI
+extern u32 acpi_leave_sleep_state (u8 sleep_state);
+#endif
+
+#ifdef DEBUG_DEVICE_TREE
+#include "../../drivers/base/power/power.h"
+#include <linux/device.h>
+
+void display_device_tree(struct partial_device_tree * tree, char * header)
+{
+	struct device * dev;
+
+	if (header)
+		printk(header);
+	printk(" === Tree %p ===\n\n", tree);
+
+	printk(" -- Active\n");
+	list_for_each_entry(dev, &tree->dpm_active, power.entry) {
+		printk("   %p->%p", dev, dev->parent);
+		printk(" %s\n", dev->kobj.k_name ? dev->kobj.k_name : "<null>");
+	}
+	printk("\n -- DPM Off\n");
+	list_for_each_entry(dev, &tree->dpm_off, power.entry) {
+		printk("   %p->%p", dev, dev->parent);
+		printk(" %s\n", dev->kobj.k_name ? dev->kobj.k_name : "<null>");
+	}
+	
+	printk("\n -- DPM Off IRQ\n");
+	list_for_each_entry(dev, &tree->dpm_off_irq, power.entry) {
+		printk("   %p->%p", dev, dev->parent);
+		printk(" %s\n", dev->kobj.k_name ? dev->kobj.k_name : "<null>");
+	}
+	printk("\n--- Done ---\n");
+}
+#else
+#define display_device_tree(tree, header) do { } while(0)
+#endif
+
+/*	suspend_drivers_resume
+ *	@stage - One of...
+ */
+
+enum {
+	SUSPEND_DRIVERS_USED_DEVICES_IRQS_DISABLED,
+	SUSPEND_DRIVERS_USED_DEVICES_IRQS_ENABLED,
+	SUSPEND_DRIVERS_UNUSED_DEVICES_IRQS_DISABLED,
+	SUSPEND_DRIVERS_UNUSED_DEVICES_IRQS_ENABLED,
+	SUSPEND_DRIVERS_PRE_POWERDOWN,
+};
+
+void suspend_drivers_resume(int stage)
+{
+	switch (stage) {
+		case SUSPEND_DRIVERS_USED_DEVICES_IRQS_DISABLED:
+			BUG_ON(!irqs_disabled());
+			if (!TEST_ACTION_STATE(SUSPEND_DISABLE_SYSDEV_SUPPORT))
+				sysdev_resume();
+			dpm_power_up_tree(suspend_device_tree);
+			break;
+
+		case SUSPEND_DRIVERS_USED_DEVICES_IRQS_ENABLED:
+			BUG_ON(irqs_disabled());
+			display_device_tree(suspend_device_tree,
+				"suspend_drivers_resume stage 1.");
+			device_resume_tree(suspend_device_tree);
+			display_device_tree(suspend_device_tree,
+				"Post resume tree call.");
+			break;
+
+		case SUSPEND_DRIVERS_UNUSED_DEVICES_IRQS_DISABLED:
+			BUG_ON(!irqs_disabled());
+			display_device_tree(&default_device_tree,
+				"suspend_drivers_resume stage 2.\n");
+			dpm_power_up_tree(&default_device_tree);
+			break;
+
+		case SUSPEND_DRIVERS_UNUSED_DEVICES_IRQS_ENABLED:
+			BUG_ON(irqs_disabled());
+			device_resume_tree(&default_device_tree);
+			display_device_tree(&default_device_tree,
+				"Post power up.\n");
+#ifdef CONFIG_ACPI
+			if (suspend_acpi_state_used)
+				acpi_leave_sleep_state(suspend_acpi_state_used);
+#endif
+			display_device_tree(&default_device_tree,
+				"suspend_drivers_resume stage 3.\n");
+			device_resume_tree(&default_device_tree);
+			display_device_tree(&default_device_tree,
+				"Post resume default device tree.\n");
+#ifdef CONFIG_ACPI
+			if (suspend_acpi_state_used &&
+				pm_ops && pm_ops->finish)
+				pm_ops->finish(suspend_acpi_state_used);
+#endif
+			break;
+	}
+}
+
+/*	suspend_drivers_suspend
+ *	@stage - one of:
+ *		1: Power down drivers not used in writing the image
+ *		2: Quiesce drivers used in writing the image
+ *		   (prior to making atomic copy)
+ *		3: Power down drivers used in writing the image and
+ *		   enter the suspend mode if configured to do so.
+ *
+ */
+static int suspend_drivers_suspend(int stage)
+{
+	int result = 0;
+
+	switch (stage) {
+		case SUSPEND_DRIVERS_UNUSED_DEVICES_IRQS_DISABLED:
+			BUG_ON(!irqs_disabled());
+			if (!result)
+				result = device_power_down_tree(
+					PM_SUSPEND_DISK, &default_device_tree);
+			display_device_tree(&default_device_tree,
+				"Post suspend power down device tree.\n");
+			break;
+
+		case SUSPEND_DRIVERS_UNUSED_DEVICES_IRQS_ENABLED:
+			BUG_ON(irqs_disabled());
+			display_device_tree(&default_device_tree,
+				"suspend_drivers_suspend stage 1.\n");
+			result = device_suspend_tree(
+					PM_SUSPEND_DISK, &default_device_tree);
+			break;
+
+		case SUSPEND_DRIVERS_USED_DEVICES_IRQS_DISABLED:
+			BUG_ON(!irqs_disabled());
+			result = device_power_down_tree(PM_SUSPEND_DISK, suspend_device_tree);
+			if (!TEST_ACTION_STATE(SUSPEND_DISABLE_SYSDEV_SUPPORT))
+				sysdev_suspend(PM_SUSPEND_DISK);
+			break;
+
+		case SUSPEND_DRIVERS_USED_DEVICES_IRQS_ENABLED:
+			BUG_ON(irqs_disabled());
+			display_device_tree(suspend_device_tree,
+				"suspend_drivers_suspend stage 2.\n");
+			result = device_suspend_tree(
+					PM_SUSPEND_DISK, suspend_device_tree);
+			display_device_tree(suspend_device_tree,
+				"Post suspend device tree.\n");
+			break;
+
+		case SUSPEND_DRIVERS_PRE_POWERDOWN: /* Power down system */
+			BUG_ON(irqs_disabled());
+			display_device_tree(suspend_device_tree,
+				"suspend_drivers_suspend stage 3.\n");
+
+			result = device_suspend_tree(
+				PM_SUSPEND_DISK, suspend_device_tree);
+			break;
+	}
+	return result;
+}
+
+#ifdef CONFIG_SOFTWARE_SUSPEND_DEBUG
+void show_pcp_lists(void)
+{
+	int cpu, temperature;
+	struct zone *zone;
+
+	for_each_zone(zone) {
+		printk("%s per-cpu:", zone->name);
+
+		if (!zone->present_pages) {
+			printk(" empty\n");
+			continue;
+		} else
+			printk("\n");
+
+		for (cpu = 0; cpu < NR_CPUS; ++cpu) {
+			struct per_cpu_pageset *pageset;
+
+			if (!cpu_possible(cpu))
+				continue;
+
+			pageset = zone->pageset + cpu;
+
+			for (temperature = 0; temperature < 2; temperature++)
+				printk("cpu %d %s: low %d, high %d, batch %d, count %d.\n",
+					cpu,
+					temperature ? "cold" : "hot",
+					pageset->pcp[temperature].low,
+					pageset->pcp[temperature].high,
+					pageset->pcp[temperature].batch,
+					pageset->pcp[temperature].count);
+		}
+	}
+}
+#else
+#define show_pcp_lists() do { } while(0)
+#endif
+
+/* -------------------------------------------------------------------------- */
+
+static int suspend_version_specific_initialise(void)
+{
+	struct class * class;
+	struct class_device * class_dev;
+
+	suspend_save_avenrun();
+
+	PRINTFREEMEM("after draining local pages");
+	suspend_store_free_mem(SUSPEND_FREE_DRAIN_PCP, 0);
+
+	if (TEST_DEBUG_STATE(SUSPEND_FREEZER))
+		show_pcp_lists();
+
+	if (pm_ops) {
+		pm_disk_mode_save = pm_ops->pm_disk_mode;
+		pm_ops->pm_disk_mode = PM_DISK_PLATFORM;
+	}
+			
+	BUG_ON(suspend_device_tree);
+	suspend_device_tree = device_create_tree();
+	if (IS_ERR(suspend_device_tree)) {
+		suspend_device_tree = NULL;
+		return -ENOMEM;
+	}
+
+	/* Now check for graphics class devices, so we can keep the display on while suspending */
+	class = class_find("graphics");
+	if (class) {
+		list_for_each_entry(class_dev, &class->children, node)
+			device_switch_trees(class_dev->dev, suspend_device_tree);
+		class_put(class);
+	}
+	return 0;
+}
+
+static void suspend_version_specific_cleanup(void)
+{
+	suspend_restore_avenrun();
+
+	if (pm_ops) pm_ops->pm_disk_mode = pm_disk_mode_save;
+			
+	if (suspend_device_tree) {
+		device_merge_tree(suspend_device_tree, &default_device_tree);
+		device_destroy_tree(suspend_device_tree);
+		display_device_tree(&default_device_tree,
+			" ==== POST DEVICE MERGE TREE ====\n");
+		suspend_device_tree = NULL;
+	}
+}
+/* Variables to be preserved over suspend */
+int pageset1_sizelow = 0, pageset2_sizelow = 0;
+
+unsigned long orig_mem_free = 0;
+
+extern void do_suspend2_lowlevel(int resume);
+extern unsigned long header_storage_for_plugins(void);
+extern int suspend_initialise_plugin_lists(void);
+extern void suspend_relinquish_console(void);
+extern volatile int suspend_io_time[2][2];
+void empty_suspend_memory_pool(void);
+int read_primary_suspend_image(void);
+extern void display_nosave_pages(void);
+extern int num_writers;
+
+extern void suspend_console_proc_init(void);
+extern void suspend_console_proc_exit(void);
+extern int suspend2_prepare_console(void);
+extern void suspend2_cleanup_console(void);
+
+unsigned long * in_use_map = NULL;
+unsigned long * pageset2_map = NULL;
+unsigned long * checksum_map = NULL;
+#ifdef CONFIG_DEBUG_PAGEALLOC
+unsigned long * unmap_map = NULL;
+#endif
+
+char * debug_info_buffer;
+
+int image_size_limit = 0;
+int max_async_ios = 128;
+
+/* Pagedir.c */
+extern void copy_pageset1(void);
+extern int allocate_local_pageflags(unsigned long ** pagemap, int setnosave);
+extern void free_pagedir(struct pagedir * p);
+extern int free_local_pageflags(unsigned long ** pagemap);
+
+/* Prepare_image.c */
+
+extern int prepare_image(void);
+
+unsigned long forced_ps1_size = 0, forced_ps2_size = 0;
+
+/* proc.c */
+extern int suspend_cleanup_proc(void);
+
+extern int suspend2_register_core(struct suspend2_core_ops * ops_pointer);
+extern void suspend2_unregister_core(void);
+
+#ifdef CONFIG_SOFTWARE_SUSPEND_DEBUG
+
+int suspend_free_mem_values[MAX_FREEMEM_SLOTS][2];
+/* These should match the enumerated type in suspend.h */
+static char * suspend_free_mem_descns[MAX_FREEMEM_SLOTS] = {
+	"Start/End      ", /* 0 */
+	"Console Allocn ",
+	"Drain pcp      ",
+	"InUse map      ",
+	"PS2 map        ",
+	"Checksum map   ", /* 5 */
+	"Reload pages   ",
+	"Init plugins   ",
+	"Memory pool    ",
+	"Freezer        ",
+	"Eat Memory     ", /* 10 */
+	"Syncing        ",
+	"Grabbed Memory ",
+	"Range Pages    ",
+	"Extra PD1 pages",
+	"Writer storage ", /* 15 */
+	"Header storage ",
+	"Checksum pages ",
+	"KStat data     ",
+	"Debug Info     ",
+	"Remove Image   ", /* 20 */
+	"I/O            ",
+	"I/O info       ",
+	"Start one      ",
+};
+
+/* store_free_mem
+ */
+
+
+void suspend_store_free_mem(int slot, int side)
+{
+	static int last_free_mem;
+	int this_free_mem = real_nr_free_pages() + suspend_amount_grabbed +
+			suspend_memory_pool_level(0);
+	int i;
+
+	BUG_ON(slot >= MAX_FREEMEM_SLOTS);
+
+	suspend_message(SUSPEND_MEMORY, SUSPEND_HIGH, 0,
+			"Last free mem was %d. Is now %d. ",
+			last_free_mem, this_free_mem);
+
+	if (slot == 0) {
+		if (!side)
+			for (i = 1; i < MAX_FREEMEM_SLOTS; i++) {
+				suspend_free_mem_values[i][0] = 0;
+				suspend_free_mem_values[i][1] = 0;
+			}
+		suspend_free_mem_values[slot][side] = this_free_mem;
+	} else
+		suspend_free_mem_values[slot][side] += this_free_mem - last_free_mem;
+	last_free_mem = this_free_mem;
+	suspend_message(SUSPEND_MEMORY, SUSPEND_HIGH, 0,
+		"%s value %d now %d.\n",
+		suspend_free_mem_descns[slot],
+		side,
+		suspend_free_mem_values[slot][side]);
+}
+
+/*
+ * display_free_mem
+ */
+static void display_free_mem(void)
+{
+	int i;
+
+
+	if (!TEST_DEBUG_STATE(SUSPEND_MEMORY))
+		return;
+	
+	suspend_message(SUSPEND_MEMORY, SUSPEND_HIGH, 0,
+		"Start:       %7d    End: %7d.\n",
+		suspend_free_mem_values[0][0],
+		suspend_free_mem_values[0][1]);
+	
+	for (i = 1; i < MAX_FREEMEM_SLOTS; i++)
+		if (suspend_free_mem_values[i][0] + suspend_free_mem_values[i][1])
+			suspend_message(SUSPEND_MEMORY, SUSPEND_HIGH, 0,
+				"%s %7d         %7d.\n",
+				suspend_free_mem_descns[i],
+				suspend_free_mem_values[i][0],
+				suspend_free_mem_values[i][1]);
+}
+#endif
+
+/*
+ * save_image
+ * Result code (int): Zero on success, non zero on failure.
+ * Functionality    : High level routine which performs the steps necessary
+ *                    to prepare and save the image after preparatory steps
+ *                    have been taken.
+ * Key Assumptions  : Processes frozen, sufficient memory available, drivers
+ *                    suspended.
+ * Called from      : do_suspend2_suspend_2
+ */
+extern struct pageset_sizes_result recalculate_stats(void);
+extern int write_pageset(struct pagedir * pagedir, int whichtowrite);
+extern int write_image_header(void);
+extern int read_secondary_pagedir(int overwrittenpagesonly);
+
+static int save_image(void)
+{
+	int temp_result;
+
+	if (RAM_TO_SUSPEND > max_mapnr) {
+		prepare_status(1, 1,
+			"Couldn't get enough free pages, on %ld pages short",
+			 RAM_TO_SUSPEND - max_mapnr);
+		goto abort_saving;
+	}
+	
+	suspend_message(SUSPEND_ANY_SECTION, SUSPEND_LOW, 1,
+		" - Final values: %d and %d.\n",
+		pageset1_size, 
+		pageset2_size);
+
+	/* Suspend devices we're not going to use in writing the image */
+	if (active_writer && active_writer->dpm_set_devices)
+		active_writer->dpm_set_devices();
+	suspend_drivers_suspend(SUSPEND_DRIVERS_UNUSED_DEVICES_IRQS_ENABLED);
+	local_irq_disable();
+	suspend_drivers_suspend(SUSPEND_DRIVERS_UNUSED_DEVICES_IRQS_DISABLED);
+	local_irq_enable();
+
+	check_shift_keys(1, "About to write pagedir2.");
+
+	temp_result = write_pageset(&pagedir2, 2);
+	
+	check_shift_keys(1, "About to copy pageset 1.");
+
+	if (temp_result == -1 || TEST_RESULT_STATE(SUSPEND_ABORTED))
+		goto abort_saving;
+
+	prepare_status(1, 0, "Doing atomic copy...");
+	
+	do_suspend2_lowlevel(0);
+
+	return 0;
+abort_saving:
+	suspend_drivers_resume(SUSPEND_DRIVERS_UNUSED_DEVICES_IRQS_ENABLED);
+	local_irq_disable();
+	suspend_drivers_resume(SUSPEND_DRIVERS_UNUSED_DEVICES_IRQS_DISABLED);
+	local_irq_enable();
+
+	return -1;		
+}
+
+int save_image_part1(void)
+{
+	int temp_result;
+	
+	suspend_map_atomic_copy_pages();
+
+	suspend_checksum_calculate_checksums();
+	
+	BUG_ON(!irqs_disabled());
+
+	if (!TEST_ACTION_STATE(SUSPEND_TEST_FILTER_SPEED))
+		copy_pageset1();
+
+	/*
+	 *  ----   FROM HERE ON, NEED TO REREAD PAGESET2 IF ABORTING!!! -----
+	 *  
+	 */
+	
+	suspend_unmap_atomic_copy_pages();
+
+	/* 
+	 * Other processors have waited for me to make the atomic copy of the 
+	 * kernel
+	 */
+
+	smp_continue();
+	
+#ifdef CONFIG_X86
+	kernel_fpu_end();
+#endif
+
+#ifdef CONFIG_PREEMPT
+	preempt_enable_no_resched();
+#endif
+
+	suspend_drivers_resume(SUSPEND_DRIVERS_USED_DEVICES_IRQS_DISABLED);
+	
+	local_irq_enable();
+	suspend_drivers_resume(SUSPEND_DRIVERS_USED_DEVICES_IRQS_ENABLED);
+
+	update_status(pageset2_size, pageset1_size + pageset2_size, NULL);
+	
+	if (TEST_RESULT_STATE(SUSPEND_ABORTED))
+		goto abort_reloading_pagedir_two;
+
+	check_shift_keys(1, "About to write pageset1.");
+
+	/*
+	 * End of critical section.
+	 */
+	
+	suspend_message(SUSPEND_ANY_SECTION, SUSPEND_LOW, 1,
+			"-- Writing pageset1\n");
+
+	temp_result = write_pageset(&pagedir1, 1);
+
+	if (TEST_ACTION_STATE(SUSPEND_TEST_FILTER_SPEED)) {
+		/* We didn't overwrite any memory, so no reread needs to be done. */
+		return -1;
+	}
+
+	if (temp_result == -1 || TEST_RESULT_STATE(SUSPEND_ABORTED))
+		goto abort_reloading_pagedir_two;
+
+	check_shift_keys(1, "About to write header.");
+
+	if (TEST_RESULT_STATE(SUSPEND_ABORTED))
+		goto abort_reloading_pagedir_two;
+
+	temp_result = write_image_header();
+
+	if (temp_result || (TEST_RESULT_STATE(SUSPEND_ABORTED)))
+		goto abort_reloading_pagedir_two;
+
+	check_shift_keys(1, "About to power down or reboot.");
+
+	return 0;
+
+abort_reloading_pagedir_two:
+	temp_result = read_secondary_pagedir(1);
+
+	/* If that failed, we're sunk. Panic! */
+	if (temp_result)
+		panic("Attempt to reload pagedir 2 while aborting "
+				"a suspend failed.");
+
+	return -1;		
+
+}
+
+static void suspend_power_off(void)
+{
+	sys_reboot(LINUX_REBOOT_MAGIC1, LINUX_REBOOT_MAGIC2,
+			LINUX_REBOOT_CMD_POWER_OFF, NULL);
+
+	prepare_status(1, 0, "Probably not capable for powerdown.");
+	while (1)
+		cpu_relax();
+	/* NOTREACHED */
+}
+
+static void suspend_enter_acpi_state(u32 state)
+{
+	suspend_acpi_state_used = state;
+
+	if (pm_ops && pm_ops->prepare) {
+		if (!pm_ops->prepare(state)) {
+			if (pm_ops && pm_ops->enter)
+				pm_ops->enter(state);
+			else 
+				printk("Failed to enter state.\n");
+		} else
+			printk("Prepare ops failed.\n");
+	} else
+		printk("No prepare ops.\n");
+}
+
+/*
+ * suspend_power_down
+ * Functionality   : Powers down or reboots the computer once the image
+ *                   has been written to disk.
+ * Key Assumptions : Able to reboot/power down via code called or that
+ *                   the warning emitted if the calls fail will be visible
+ *                   to the user (ie printk resumes devices).
+ * Called From     : do_suspend2_suspend_2
+ */
+
+extern asmlinkage long sys_reboot(int magic1, int magic2, unsigned int cmd,
+	       void * arg);
+extern void apm_power_off(void);
+
+void suspend_power_down(void)
+{
+	if (TEST_ACTION_STATE(SUSPEND_REBOOT)) {
+		prepare_status(1, 0, "Ready to reboot.");
+		sys_reboot(LINUX_REBOOT_MAGIC1, LINUX_REBOOT_MAGIC2,
+				LINUX_REBOOT_CMD_RESTART, NULL);
+	}
+
+	suspend_drivers_suspend(SUSPEND_DRIVERS_PRE_POWERDOWN);
+
+	if (suspend_powerdown_method == 3) {
+		prepare_status(1, 0, "Seeking to suspend-to-ram.");
+		suspend_enter_acpi_state(PM_SUSPEND_MEM);
+		prepare_status(1, 0, "Entering S3 failed. Using normal powerdown.");
+	} else if (suspend_powerdown_method == 4) {
+		prepare_status(1, 0, "Seeking to enter ACPI suspend-to-disk state.");
+		suspend_enter_acpi_state(PM_SUSPEND_DISK);
+		prepare_status(1, 0, "Entering S4 failed. Using normal powerdown.");
+	} else
+		prepare_status(1, 0, "Powering down.");
+	
+	/* 
+	 * FIXME: At resume, we'll still think we used S4 if we tried it.
+	 * Does it matter?
+	 */
+	suspend_acpi_state_used = 0;
+	suspend_power_off();
+}
+
+/*
+ * do_suspend2_resume_1
+ * Functionality   : Preparatory steps for copying the original kernel back.
+ * Called From     : do_suspend2_lowlevel
+ */
+
+static void do_suspend2_resume_1(void)
+{
+	suspend_message(SUSPEND_ANY_SECTION, SUSPEND_LOW, 1,
+			name_suspend "About to copy pageset1 back...\n");
+
+	if (active_writer && active_writer->dpm_set_devices)
+		active_writer->dpm_set_devices();
+	
+	suspend_drivers_suspend(SUSPEND_DRIVERS_USED_DEVICES_IRQS_ENABLED);
+	suspend_drivers_suspend(SUSPEND_DRIVERS_UNUSED_DEVICES_IRQS_ENABLED);
+	local_irq_disable(); /* irqs might have been re-enabled on us */
+	suspend_drivers_suspend(SUSPEND_DRIVERS_USED_DEVICES_IRQS_DISABLED);
+	local_irq_disable();
+	suspend_drivers_suspend(SUSPEND_DRIVERS_UNUSED_DEVICES_IRQS_DISABLED);
+	local_irq_enable();
+
+	suspend_map_atomic_copy_pages();
+
+	/* Get other cpus ready to restore their original contexts */
+	smp_suspend();
+
+	local_irq_disable();
+
+#ifdef CONFIG_PREEMPT
+	preempt_disable();
+#endif
+
+	barrier();
+	mb();
+
+	MDELAY(2000);
+}
+
+/*
+ * do_suspend2_resume_2
+ * Functionality   : Steps taken after copying back the original kernel at
+ *                   resume.
+ * Key Assumptions : Will be able to read back secondary pagedir (if 
+ *                   applicable).
+ * Called From     : do_suspend2_lowlevel
+ */
+
+static void do_suspend2_resume_2(void)
+{
+	set_suspend_state(SUSPEND_NOW_RESUMING);
+	set_suspend_state(SUSPEND_PAGESET2_NOT_LOADED);
+
+	suspend_unmap_atomic_copy_pages();
+
+#ifdef CONFIG_PREEMPT
+	preempt_enable();
+#endif
+
+	local_irq_disable();
+	suspend_drivers_resume(SUSPEND_DRIVERS_USED_DEVICES_IRQS_DISABLED);
+	local_irq_enable();
+
+	suspend_drivers_resume(SUSPEND_DRIVERS_USED_DEVICES_IRQS_ENABLED);
+
+	suspend_post_restore_redraw();
+
+	check_shift_keys(1, "About to reload secondary pagedir.");
+
+	read_secondary_pagedir(0);
+	clear_suspend_state(SUSPEND_PAGESET2_NOT_LOADED);
+	
+	suspend_checksum_print_differences();
+
+	prepare_status(0, 0, "Cleaning up...");
+
+	clear_suspend_state(SUSPEND_USE_MEMORY_POOL);
+	
+	local_irq_disable();
+	suspend_drivers_resume(SUSPEND_DRIVERS_UNUSED_DEVICES_IRQS_DISABLED);
+	local_irq_enable();
+	suspend_drivers_resume(SUSPEND_DRIVERS_UNUSED_DEVICES_IRQS_ENABLED);
+}
+
+/*
+ * do_suspend2_suspend_1
+ * Functionality   : Steps taken prior to saving CPU state and the image
+ *                   itself.
+ * Called From     : do_suspend2_lowlevel
+ */
+
+static void do_suspend2_suspend_1(void)
+{
+	/* Save other cpu contexts */
+	smp_suspend();
+
+	suspend_drivers_suspend(SUSPEND_DRIVERS_USED_DEVICES_IRQS_ENABLED);
+
+	mb();
+	barrier();
+
+#ifdef CONFIG_PREEMPT
+	preempt_disable();
+#endif
+	local_irq_disable();
+	suspend_drivers_suspend(SUSPEND_DRIVERS_USED_DEVICES_IRQS_DISABLED);
+}
+
+/*
+ * do_suspend2_suspend_2
+ * Functionality   : Steps taken after saving CPU state to save the
+ *                   image and powerdown/reboot or recover on failure.
+ * Key Assumptions : save_image returns zero on success; otherwise we need to
+ *                   clean up and exit. The state on exiting this routine 
+ *                   should be essentially the same as if we have suspended,
+ *                   resumed and reached the end of do_suspend2_resume_2.
+ * Called From     : do_suspend2_lowlevel
+ */
+static void do_suspend2_suspend_2(void)
+{
+	if (!save_image_part1())
+		suspend_power_down();
+
+	if (!TEST_RESULT_STATE(SUSPEND_ABORT_REQUESTED) &&
+	    !TEST_ACTION_STATE(SUSPEND_TEST_FILTER_SPEED) &&
+	    suspend_powerdown_method != 3)
+		printk(KERN_EMERG name_suspend
+			"Suspend failed, trying to recover...\n");
+	MDELAY(1000);
+
+	local_irq_disable();
+	suspend_drivers_resume(SUSPEND_DRIVERS_UNUSED_DEVICES_IRQS_DISABLED);
+	local_irq_enable();
+	suspend_drivers_resume(SUSPEND_DRIVERS_UNUSED_DEVICES_IRQS_ENABLED);
+
+	barrier();
+	mb();
+}
+
+static inline void lru_check_page(struct page * page)
+{
+	if (!PageLRU(page))
+		printk("Page %p/%p in inactivelist but not marked LRU.\n",
+			page, page_address(page));
+}
+
+/* get_debug_info
+ * Functionality:	Store debug info in a buffer.
+ * Called from:		suspend_try_suspend.
+ */
+
+#define SNPRINTF(a...) 	len += suspend_snprintf(debug_info_buffer + len, \
+		PAGE_SIZE - len - 1, ## a)
+
+static int get_suspend_debug_info(void)
+{
+	int len = 0;
+	if (!debug_info_buffer) {
+		debug_info_buffer = (char *) get_zeroed_page(GFP_ATOMIC);
+		if (!debug_info_buffer) {
+			printk("Error! Unable to allocate buffer for"
+					"software suspend debug info.\n");
+			return 0;
+		}
+	}
+
+	SNPRINTF("Please include the following information in bug reports:\n");
+	SNPRINTF("- SUSPEND core   : %s\n", SUSPEND_CORE_VERSION);
+	SNPRINTF("- Kernel Version : %s\n", UTS_RELEASE);
+	SNPRINTF("- Compiler vers. : %d.%d\n", __GNUC__, __GNUC_MINOR__);
+#ifdef CONFIG_MODULES
+	SNPRINTF("- Modules loaded : ");
+	{
+#if LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0)
+		struct module *this_mod;
+		extern struct module *module_list;
+		this_mod = module_list;
+		while (this_mod) {
+			if (this_mod->name)
+				SNPRINTF("%s ", this_mod->name);
+			this_mod = this_mod->next;
+		}
+#else
+		extern int print_module_list_to_buffer(char * buffer, int size);
+		len+= print_module_list_to_buffer(debug_info_buffer + len,
+				PAGE_SIZE - len - 1);
+#endif
+	}
+	SNPRINTF("\n");
+#else
+	SNPRINTF("- No module support.\n");
+#endif
+	SNPRINTF("- Attempt number : %d\n", nr_suspends);
+	if (num_range_pages)
+		SNPRINTF("- Pageset sizes  : %d (%d low) and %d (%d low).\n",
+			pagedir1.lastpageset_size, 
+			pageset1_sizelow,
+			pagedir2.lastpageset_size, 
+			pageset2_sizelow);
+#ifdef CONFIG_SOFTWARE_SUSPEND_DEBUG
+	SNPRINTF("- Parameters     : %ld %ld %ld %d %d %d %ld\n",
+			suspend_result,
+			suspend_action,
+			suspend_debug_state,
+			suspend_default_console_level,
+			image_size_limit,
+			max_async_ios,
+			suspend_powerdown_method);
+#else
+	SNPRINTF("- Parameters     : %ld %ld %d %d %ld\n",
+			suspend_result,
+			suspend_action,
+			image_size_limit,
+			max_async_ios,
+			suspend_powerdown_method);
+#endif
+	if (num_range_pages)
+		SNPRINTF("- Calculations   : Image size: %lu. "
+			"Ram to suspend: %ld.\n",
+			STORAGE_NEEDED(1), RAM_TO_SUSPEND);
+	SNPRINTF("- Limits         : %lu pages RAM. Initial boot: %lu.\n",
+		max_mapnr, orig_mem_free);
+	SNPRINTF("- Overall expected compression percentage: %d.\n",
+			100 - expected_compression_ratio());
+	len+= print_plugin_debug_info(debug_info_buffer + len, 
+			PAGE_SIZE - len - 1);
+#ifdef CONFIG_SOFTWARE_SUSPEND_DEBUG
+	SNPRINTF("- Debugging compiled in.\n");
+#endif
+#ifdef CONFIG_PREEMPT
+	SNPRINTF("- Preemptive kernel.\n");
+#endif
+#ifdef CONFIG_SMP
+	SNPRINTF("- SMP kernel.\n");
+#endif
+#ifdef CONFIG_HIGHMEM
+	SNPRINTF("- Highmem Support.\n");
+#endif
+	if (num_range_pages)
+		SNPRINTF("- Max ranges used: %d ranges in %d pages.\n",
+			max_ranges_used, num_range_pages);
+	if (suspend_io_time[0][1]) {
+		SNPRINTF("- I/O speed: Write %d MB/s",
+			(MB((unsigned long) suspend_io_time[0][0]) * HZ /
+			 suspend_io_time[0][1]));
+		if (suspend_io_time[1][1])
+			SNPRINTF(", Read %d MB/s",
+				(MB((unsigned long) suspend_io_time[1][0]) * HZ /
+				 suspend_io_time[1][1]));
+		SNPRINTF(".\n");
+	}
+	else if (num_range_pages)
+		SNPRINTF("- Suspend cancelled. No I/O speed stats.\n");
+
+	return len;
+}
+
+extern int PageInPagedir(struct pagedir * p, struct page * page);
+static unsigned long display_metadata_page;
+
+static char * state_string[3] = { "Source", "Destination", "Dest/Allocd" };
+
+void __display_metadata_state(int pagedir, int state)
+{
+	int i;
+
+	if (!state)
+		return;
+
+	printk("[ Pagedir %d:", pagedir);
+	for (i=0; i < 3; i++)
+		if (state & (1 << i))
+			printk("%s ", state_string[i]);
+	printk("]");
+}
+
+void display_metadata_state(struct page * page)
+{
+	__display_metadata_state(1, PageInPagedir(&pagedir1, page));
+	__display_metadata_state(2, PageInPagedir(&pagedir2, page));
+	if (PageNosave(page))
+		printk("[ NoSave ]");
+	if (PageReserved(page))
+		printk("[ Reserved ]");
+	if (PageHighMem(page))
+		printk("[ Highmem ]");
+}
+
+void proc_display_metadata_state(void)
+{
+	printk("Page number %lu. Struct page at %p, virt address %p:",
+			display_metadata_page,
+			mem_map + display_metadata_page,
+			page_address(mem_map + display_metadata_page));
+	display_metadata_state(mem_map + display_metadata_page);
+	printk("\n");
+}
+
+/*
+ * debuginfo_read_proc
+ * Functionality   : Displays information that may be helpful in debugging
+ *                   software suspend.
+ */
+int debuginfo_read_proc(char * page, char ** start, off_t off, int count,
+		int *eof, void *data)
+{
+	int info_len, copy_len;
+
+	initialise_suspend_plugins();
+	info_len = get_suspend_debug_info();
+	cleanup_suspend_plugins();
+
+	copy_len = min(info_len - (int) off, count);
+	if (copy_len < 0)
+		copy_len = 0;
+
+	if (copy_len) {
+		memcpy(page, debug_info_buffer + off, copy_len);
+		*start = page;
+	} 
+
+	if (copy_len + off == info_len)
+		*eof = 1;
+
+	free_pages((unsigned long) debug_info_buffer, 0);
+	debug_info_buffer = NULL;
+	return copy_len;
+}
+
+static int get_suspend_debug_info(void);
+
+static int allocate_bitmaps(void)
+{
+	suspend_message(SUSPEND_MEMORY, SUSPEND_VERBOSE, 1,
+			"Allocating in_use_map\n");
+	if (allocate_local_pageflags(&in_use_map, 1))
+		return 1;
+	
+	suspend_store_free_mem(SUSPEND_FREE_IN_USE_MAP, 0);
+	PRINTFREEMEM("after allocating in_use_map");
+	
+	if (allocate_local_pageflags(&pageset2_map, 1))
+		return 1;
+
+	suspend_store_free_mem(SUSPEND_FREE_PS2_MAP, 0);
+	PRINTFREEMEM("after allocating pageset2 map");
+	
+#ifdef CONFIG_DEBUG_PAGEALLOC
+	if (allocate_local_pageflags(&unmap_map, 1))
+		return 1;
+
+	suspend_store_free_mem(SUSPEND_FREE_UNMAP_MAP, 0);
+	PRINTFREEMEM("after allocating unmap map");
+#endif	
+	
+	suspend_store_free_mem(4, 0);
+	
+	return 0;
+}
+
+static void free_metadata(void)
+{
+	put_rangepages_list();
+
+	free_ranges();
+	suspend_store_free_mem(SUSPEND_FREE_RANGE_PAGES, 1);
+	PRINTFREEMEM("after freeing ranges");
+
+	free_local_pageflags(&pageset2_map);
+	PRINTFREEMEM("after freeing pageset2 map");
+	suspend_store_free_mem(SUSPEND_FREE_PS2_MAP, 1);
+
+	free_local_pageflags(&in_use_map);
+	PRINTFREEMEM("after freeing inuse map");
+	suspend_store_free_mem(SUSPEND_FREE_IN_USE_MAP, 1);
+}
+
+/*
+ * software_suspend_pending
+ * Functionality   : First level of code for software suspend invocations.
+ *                   Stores and restores load averages (to avoid a spike),
+ *                   allocates bitmaps, freezes processes and eats memory
+ *                   as required before suspending drivers and invoking
+ *                   the 'low level' code to save the state to disk.
+ *                   By the time we return from do_suspend2_lowlevel, we
+ *                   have either failed to save the image or successfully
+ *                   suspended and reloaded the image. The difference can
+ *                   be discerned by checking SUSPEND_ABORTED.
+ * Called From     : 
+ */
+
+extern void free_pageset_size_bloat(void);
+
+void do_activate(void)
+{
+	int i;
+
+        /* Suspend always runs on processor 0 */ 
+	ensure_on_processor_zero();
+
+	display_nosave_pages();
+
+#ifdef CONFIG_SOFTWARE_SUSPEND_KEEP_IMAGE
+	if (TEST_RESULT_STATE(SUSPEND_KEPT_IMAGE)) {
+		if (TEST_ACTION_STATE(SUSPEND_KEEP_IMAGE)) {
+			printk("Image already stored:"
+				" powering down immediately.");
+			suspend_power_down();
+			return;	/* It might now, but just in case we're using S3*/
+		} else {
+			printk("Invalidating previous image.\n");
+			active_writer->ops.writer.invalidate_image();
+		}
+	}
+#endif
+
+	printk(name_suspend "Initiating a software suspend cycle.\n");
+	set_suspend_state(SUSPEND_RUNNING);
+
+	max_ranges_used = 0;
+	nr_suspends++;
+	clear_suspend_state(SUSPEND_NOW_RESUMING);
+	
+	suspend_io_time[0][0] = suspend_io_time[0][1] = suspend_io_time[1][0] =
+		suspend_io_time[1][1] = 0;
+
+	PRINTFREEMEM("at start of do_activate");
+	suspend_store_free_mem(SUSPEND_FREE_BASE, 0);
+
+	suspend2_prepare_console();
+
+	free_metadata();	/* We might have kept it */
+
+	if (suspend_version_specific_initialise())
+		goto out;
+
+	if (allocate_bitmaps())
+		goto out;
+	
+	PRINTFREEMEM("after allocating bitmaps");
+
+	display_nosave_pages();
+
+	set_chain_names(&pagedir1);
+	set_chain_names(&pagedir2);
+
+	if (initialise_suspend_plugins())
+		goto out;
+
+	PRINTFREEMEM("after initialising plugins");
+	suspend_store_free_mem(SUSPEND_FREE_INIT_PLUGINS, 0);
+
+	/* Free up memory if necessary */
+	suspend_message(SUSPEND_ANY_SECTION, SUSPEND_VERBOSE, 1,
+			"Preparing image.\n");
+	if (prepare_image() || TEST_RESULT_STATE(SUSPEND_ABORTED))
+		goto out;
+
+	PRINTFREEMEM("after preparing image");
+
+	if (TEST_ACTION_STATE(SUSPEND_FREEZER_TEST))
+		goto out;
+
+	display_nosave_pages();
+
+	if (!TEST_RESULT_STATE(SUSPEND_ABORTED)) {
+		prepare_status(1, 0, "Starting to save the image..");
+		save_image();
+	}
+	
+out:
+	free_pageset_size_bloat();
+
+	PRINTFREEMEM("at 'out'");
+
+	i = get_suspend_debug_info();
+
+	suspend_store_free_mem(SUSPEND_FREE_DEBUG_INFO, 0);
+
+	clear_suspend_state(SUSPEND_USE_MEMORY_POOL);
+
+	free_pagedir(&pagedir2);
+	PRINTFREEMEM("after freeing pagedir 1");
+	free_pagedir(&pagedir1);
+	PRINTFREEMEM("after freeing pagedir 2");
+	
+#ifdef CONFIG_SOFTWARE_SUSPEND_KEEP_IMAGE
+	if (TEST_ACTION_STATE(SUSPEND_KEEP_IMAGE) &&
+	    !TEST_ACTION_STATE(SUSPEND_ABORTED)) {
+		suspend_message(SUSPEND_ANY_SECTION, SUSPEND_LOW, 1,
+			name_suspend "Not invalidating the image due "
+			"to Keep Image being enabled.\n");
+		SET_RESULT_STATE(SUSPEND_KEPT_IMAGE);
+	} else
+#endif
+		active_writer->ops.writer.invalidate_image();
+
+	empty_suspend_memory_pool();
+	PRINTFREEMEM("after freeing memory pool");
+	suspend_store_free_mem(SUSPEND_FREE_MEM_POOL, 1);
+
+	if (!TEST_ACTION_STATE(SUSPEND_KEEP_METADATA))
+		free_metadata();
+
+#ifdef CONFIG_DEBUG_PAGE_ALLOC
+	free_local_pageflags(&unmap_map);
+	PRINTFREEMEM("after freeing unmap map");
+	suspend_store_free_mem(SUSPEND_UNMAP_MAP, 1);
+#endif
+
+	if (debug_info_buffer) {
+		/* Printk can only handle 1023 bytes, including
+		 * its level mangling. */
+		for (i = 0; i < 3; i++)
+			printk("%s", debug_info_buffer + (1023 * i));
+		free_pages((unsigned long) debug_info_buffer, 0);
+		debug_info_buffer = NULL;
+	}
+
+	PRINTFREEMEM("after freeing debug info buffer");
+	suspend_store_free_mem(SUSPEND_FREE_DEBUG_INFO, 1);
+	
+	cleanup_suspend_plugins();
+
+	PRINTFREEMEM("after cleaning up suspend plugins");
+	suspend_store_free_mem(SUSPEND_FREE_INIT_PLUGINS, 1);
+	
+	suspend_version_specific_cleanup();
+
+	display_nosave_pages();
+
+	thaw_processes(FREEZER_ALL_THREADS);
+
+	PRINTFREEMEM("after thawing processes");
+	suspend_store_free_mem(SUSPEND_FREE_FREEZER, 1);
+
+	suspend_store_free_mem(SUSPEND_FREE_BASE, 1);
+#ifdef CONFIG_SOFTWARE_SUSPEND_DEBUG
+	display_free_mem();
+#endif
+
+	clear_suspend_state(SUSPEND_RUNNING);
+	PRINTFREEMEM("at end of do_activate");
+#ifdef CONFIG_PREEMPT
+#endif
+	suspend2_cleanup_console();
+
+}
+
+int attempt_to_parse_resume_device(void)
+{
+	struct list_head *writer;
+	struct suspend_plugin_ops * this_writer;
+	int result = 0;
+	mm_segment_t oldfs;
+
+	oldfs = get_fs(); set_fs(KERNEL_DS);
+
+	active_writer = NULL;
+	clear_suspend_state(SUSPEND_RESUME_DEVICE_OK);
+	set_suspend_state(SUSPEND_DISABLED);
+
+	if (!num_writers) {
+		printk(name_suspend "No writers have been registered.\n");
+		goto out;
+	}
+	
+	if (!resume2_file[0]) {
+		result = -EINVAL;
+		goto out;
+	}
+
+	list_for_each(writer, &suspend_writers) {
+		this_writer = list_entry(writer, struct suspend_plugin_ops,
+				ops.writer.writer_list);
+
+		/* 
+		 * Not sure why you'd want to disable a writer, but
+		 * we should honour the flag if we're providing it
+		 */
+		if (this_writer->disabled) {
+			printk(name_suspend
+					"Writer '%s' is disabled. Ignoring it.\n",
+					this_writer->name);
+			continue;
+		}
+
+		result = this_writer->ops.writer.parse_image_location(
+				resume2_file, (num_writers == 1));
+
+		switch (result) {
+			case -EINVAL:
+				/* 
+				 * For this writer, but not a valid 
+				 * configuration
+				 */
+
+				printk(name_suspend
+					"Not able to successfully parse this "
+					"resume device. Suspending disabled.\n");
+				goto out;
+
+			case 0:
+				/*
+				 * For this writer and valid.
+				 */
+
+				active_writer = this_writer;
+
+				/* We may not have any filters compiled in */
+
+				set_suspend_state(SUSPEND_RESUME_DEVICE_OK);
+				clear_suspend_state(SUSPEND_DISABLED);
+				printk(name_suspend "Suspending enabled.\n");
+				goto out;
+
+			case 1:
+				/*
+				 * Not for this writer. Try the next one.
+				 */
+
+				break;
+		}
+	}
+	printk(name_suspend "No matching writer found. Suspending disabled.\n");
+	result = -EINVAL;
+out:
+	clear_suspend_state(SUSPEND_RUNNING);
+	set_fs(oldfs);
+	return result;
+}
+
+/* 
+ * 
+ */
+
+static void __suspend2_verify_checksums(void)
+{
+	if (checksum_plugin)
+		checksum_plugin->ops.checksum.check_checksums();
+}
+
+#define ALL_SETTINGS_VERSION 2
+
+/*
+ * suspend_write_compat_proc.
+ *
+ * This entry allows all of the settings to be set at once. 
+ * It was originally for compatibility with pre- /proc/suspend
+ * versions, but has been retained because it makes saving and
+ * restoring the configuration simpler.
+ */
+static int suspend_write_compat_proc(struct file *file, const char * buffer,
+		unsigned long count, void * data)
+{
+	char * buf1 = (char *) get_zeroed_page(GFP_ATOMIC), *curbuf, *lastbuf;
+	char * buf2 = (char *) get_zeroed_page(GFP_ATOMIC); 
+	int i, file_offset = 0, used_size = 0, reparse_resume_device = 0;
+	unsigned long nextval;
+	struct suspend_plugin_ops * plugin;
+	struct plugin_header * plugin_header = NULL;
+
+	if ((!buf1) || (!buf2))
+		return -ENOMEM;
+
+	while (file_offset < count) {
+		int length = count - file_offset;
+		if (length > (PAGE_SIZE - used_size))
+			length = PAGE_SIZE - used_size;
+
+		if (copy_from_user(buf1 + used_size, buffer + file_offset, length))
+			return -EFAULT;
+
+		curbuf = buf1;
+
+		if (!file_offset) {
+			/* Integers first */
+			for (i = 0; i < 8; i++) {
+				if (!*curbuf)
+					break;
+				lastbuf = curbuf;
+				nextval = simple_strtoul(curbuf, &curbuf, 0);
+				if (curbuf == lastbuf)
+					break;
+				switch (i) {
+					case 0:
+						if (nextval != ALL_SETTINGS_VERSION) {
+							printk("Error loading saved settings. This data is for version %ld, but kernel module uses format %d.\n",
+									nextval, ALL_SETTINGS_VERSION);
+							goto out;
+						}
+					case 1:
+						suspend_result = nextval;
+						break;
+					case 2:
+						suspend_action = nextval;
+						break;
+					case 3:
+#ifdef CONFIG_SOFTWARE_SUSPEND_DEBUG
+						suspend_debug_state = nextval;
+#endif
+						break;
+					case 4:
+						suspend_default_console_level = nextval;
+#ifndef CONFIG_SOFTWARE_SUSPEND_DEBUG
+						if (suspend_default_console_level > 1)
+							suspend_default_console_level = 1;
+#endif
+						break;
+					case 5:
+						image_size_limit = nextval;
+						break;
+					case 6:
+						max_async_ios = nextval;
+						if (max_async_ios > MAX_READAHEAD)
+							max_async_ios = MAX_READAHEAD;
+						if (max_async_ios < 1)
+							max_async_ios = 1;
+						break;
+					case 7:
+#ifdef CONFIG_ACPI
+						suspend_powerdown_method = nextval;
+						if (suspend_powerdown_method < 3)
+							suspend_powerdown_method = 3;
+						if (suspend_powerdown_method > 5)
+#endif
+							suspend_powerdown_method = 5;
+						break;
+				}
+
+				curbuf++;
+				while (*curbuf == ' ')
+					curbuf++;
+			}
+
+			if (count <= (curbuf - buf1))
+				goto out;
+			else {
+				list_for_each_entry(plugin, &suspend_plugins, plugin_list)
+					plugin->disabled = 1;
+			}
+		}
+
+		if (((unsigned long) curbuf  & ~PAGE_MASK) + sizeof(plugin_header) > PAGE_SIZE)
+			goto shift_buffer;
+		
+		/* Plugins */
+		plugin_header = (struct plugin_header *) curbuf;
+
+		if (((unsigned long) curbuf & ~PAGE_MASK) + sizeof(plugin_header) + plugin_header->data_length  > PAGE_SIZE)
+			goto shift_buffer;
+		
+		if (plugin_header->magic != 0xADEDC0DE) {
+			printk("Bad plugin data magic.\n");
+			break;
+		}
+
+		plugin = find_plugin_given_name(plugin_header->name);
+
+		if (plugin) {	/* May validly have config saved for a plugin not now loaded */
+			if ((plugin->type == WRITER_PLUGIN) &&
+			    ((!active_writer && plugin->disabled && !plugin_header->disabled) ||
+			     (active_writer == plugin && plugin_header->disabled)))
+				reparse_resume_device = 1;
+			plugin->disabled = plugin_header->disabled;
+			if (plugin_header->data_length)
+				plugin->load_config_info(curbuf + sizeof(struct plugin_header), 
+						plugin_header->data_length);
+		} else
+			printk("Data for plugin %s not used because not currently loaded.\n", plugin_header->name);
+
+		curbuf += sizeof(struct plugin_header) + plugin_header->data_length;
+
+shift_buffer:
+		if (!(curbuf - buf1))
+			break;
+
+		file_offset += curbuf - buf1;
+		
+		used_size = PAGE_SIZE + buf1 - curbuf;
+		memcpy(buf2, curbuf, used_size);
+		memcpy(buf1, buf2, used_size);
+	}
+out:
+	free_pages((unsigned long) buf1, 0);
+	free_pages((unsigned long) buf2, 0);
+	
+	if (reparse_resume_device) {
+		printk("Active writer disabled or no active writer and one or more just enabled. Reparsing resume device.\n");
+		attempt_to_parse_resume_device();
+	}
+	
+	return count;
+}
+
+/*
+ * suspend_read_compat_proc.
+ *
+ * Like it's _write_ sibling, this entry allows all of the settings
+ * to be read at once.
+ * It too was originally for compatibility with pre- /proc/suspend
+ * versions, but has been retained because it makes saving and
+ * restoring the configuration simpler.
+ */
+static int suspend_read_compat_proc(char * page, char ** start, off_t off, int count,
+		int *eof, void *data)
+{
+	struct suspend_plugin_ops * this_plugin;
+	char * buffer = (char *) get_zeroed_page(GFP_ATOMIC);
+	int index = 1, file_pos = 0, page_offset = 0, len;
+	int copy_len = 0;
+	struct plugin_header plugin_header;
+
+	if (!buffer) {
+		printk("Failed to allocate a buffer for getting "
+				"plugin configuration info.\n");
+		return -ENOMEM;
+	}
+		
+	plugin_header.magic = 0xADEDC0DE;
+
+	len = sprintf(buffer, "%d %ld %ld %ld %d %d %d %ld\n",
+			ALL_SETTINGS_VERSION,
+			suspend_result,
+			suspend_action,
+			suspend_debug_state,
+			suspend_default_console_level,
+			image_size_limit,
+			max_async_ios,
+			suspend_powerdown_method);
+
+	if (len >= off) {
+		copy_len = (len < off + count) ? len - off : count - off;
+		memcpy(page, buffer + off, copy_len);
+		page_offset+= copy_len;
+	}
+
+	file_pos += len;
+
+	/* 
+	 * We have to know which data goes with which plugin, so we at
+	 * least write a length of zero for a plugin. Note that we are
+	 * also assuming every plugin's config data takes <= PAGE_SIZE.
+	 */
+
+	/* For each plugin (in registration order) */
+	list_for_each_entry(this_plugin, &suspend_plugins, plugin_list) {
+
+		/* Get the data from the plugin */
+		if (this_plugin->save_config_info) {
+			plugin_header.data_length = this_plugin->save_config_info(buffer);
+		} else
+			plugin_header.data_length = 0;
+
+		if (file_pos > (off + count)) {
+			file_pos += sizeof(struct plugin_header) + plugin_header.data_length;
+			continue;
+		}
+
+		len = 0;
+		if ((file_pos + sizeof(struct plugin_header) >= off) &&
+		    (file_pos < (off + count))) {
+
+			/* Save the details of the plugin */
+			memcpy(plugin_header.name, this_plugin->name, 
+					SUSPEND_MAX_PLUGIN_NAME_LENGTH);
+			plugin_header.disabled = this_plugin->disabled;
+			plugin_header.type = this_plugin->type;
+			plugin_header.index = index++;
+			
+			copy_len = sizeof(struct plugin_header);
+
+			if (copy_len + page_offset > count)
+				copy_len = count - page_offset;
+
+			memcpy(page + page_offset,
+				 ((char *) &plugin_header) + off + page_offset - file_pos,
+				 copy_len);	 
+
+			page_offset += copy_len;
+		}
+
+		file_pos += sizeof(struct plugin_header);
+
+		if (plugin_header.data_length && (file_pos >= off) && (file_pos < (off + count))) {
+			copy_len = plugin_header.data_length;
+
+			if (copy_len + page_offset > count + off)
+				copy_len = count - page_offset;
+			
+			memcpy(page + page_offset,
+				 buffer,
+				 copy_len);	 
+
+			page_offset += copy_len;
+
+		}
+
+		file_pos += plugin_header.data_length;
+		
+	}
+	free_pages((unsigned long) buffer, 0);
+	if (page_offset < count)
+		*eof = 1;
+	return page_offset;
+}
+
+extern int initialise_suspend_plugins(void);
+extern void cleanup_suspend_plugins(void);
+static char suspend_core_version[] = SUSPEND_CORE_VERSION;
+
+static int resume2_write_proc(void)
+{
+	mm_segment_t	oldfs;
+
+	oldfs = get_fs(); set_fs(KERNEL_DS);
+	initialise_suspend_plugins();
+	attempt_to_parse_resume_device();
+	cleanup_suspend_plugins();
+	set_fs(oldfs);
+	return 0;
+}
+
+/*
+ * Core proc entries that aren't built in.
+ *
+ * This array contains entries that are automatically registered at
+ * boot. Plugins and the console code register their own entries separately.
+ */
+
+static struct suspend_proc_data proc_params[] = {
+	{ .filename			= "all_settings",
+	  .permissions			= PROC_RW,
+	  .type				= SUSPEND_PROC_DATA_CUSTOM,
+	  .data = {
+		  .special = {
+	  		 .read_proc	= suspend_read_compat_proc,
+			 .write_proc	= suspend_write_compat_proc,
+		  }
+	  }
+	},
+
+	{ .filename			= "debug_info",
+	  .permissions			= PROC_READONLY,
+	  .type				= SUSPEND_PROC_DATA_CUSTOM,
+	  .data = {
+		  .special = {
+			  .read_proc	= debuginfo_read_proc,
+		  }
+	  }
+	},
+	
+	{ .filename			= "disable_sysdev_suspend",
+	  .permissions			= PROC_RW,
+	  .type				= SUSPEND_PROC_DATA_BIT,
+	  .data = {
+		  .bit = {
+			  .bit_vector	= &suspend_action,
+			  .bit		= SUSPEND_DISABLE_SYSDEV_SUPPORT,
+		  }
+	  }
+	},
+
+	{ .filename			= "freeze_timers",
+	  .permissions			= PROC_RW,
+	  .type				= SUSPEND_PROC_DATA_BIT,
+	  .data = {
+		  .bit = {
+			  .bit_vector	= &suspend_action,
+			  .bit		= SUSPEND_FREEZE_TIMERS,
+		  }
+	  }
+	},
+
+	{ .filename			= "image_size_limit",
+	  .permissions			= PROC_RW,
+	  .type				= SUSPEND_PROC_DATA_INTEGER,
+	  .data = {
+		  .integer = {
+			  .variable	= &image_size_limit,
+			  .minimum	= -2,
+			  .maximum	= 32767,
+		  }
+	  }
+	},
+
+	{ .filename			= "last_result",
+	  .permissions			= PROC_READONLY,
+	  .type				= SUSPEND_PROC_DATA_UL,
+	  .data = {
+		  .ul = {
+			  .variable	=  &suspend_result,
+		  }
+	  }
+	},
+	
+	{ .filename			= "reboot",
+	  .permissions			= PROC_RW,
+	  .type				= SUSPEND_PROC_DATA_BIT,
+	  .data = {
+		  .bit = {
+			  .bit_vector	= &suspend_action,
+			  .bit		= SUSPEND_REBOOT,
+		  }
+	  }
+	},
+	  
+	{ .filename			= "resume2",
+	  .permissions			= PROC_RW,
+	  .type				= SUSPEND_PROC_DATA_STRING,
+	  .data = {
+		  .string = {
+			  .variable	= resume2_file,
+			  .max_length	= 255,
+		  }
+	  },
+	  .write_proc	= resume2_write_proc,
+	},
+
+
+	{ .filename			= "version",
+	  .permissions			= PROC_READONLY,
+	  .type				= SUSPEND_PROC_DATA_STRING,
+	  .data = {
+		  .string = {
+			  .variable	= suspend_core_version,
+		  }
+	  }
+	},
+
+#ifdef CONFIG_SOFTWARE_SUSPEND_DEBUG
+	{ .filename			= "freezer_test",
+	  .permissions			= PROC_RW,
+	  .type				= SUSPEND_PROC_DATA_BIT,
+	  .data = {
+		  .bit = {
+			  .bit_vector	= &suspend_action,
+			  .bit		= SUSPEND_FREEZER_TEST,
+		  }
+	  }
+	},
+
+	{ .filename			= "keep_metadata",
+	  .permissions			= PROC_RW,
+	  .type				= SUSPEND_PROC_DATA_BIT,
+	  .data = {
+		  .bit = {
+			  .bit_vector	= &suspend_action,
+			  .bit		= SUSPEND_KEEP_METADATA,
+		  }
+	  }
+	},
+
+	{ .filename			= "test_filter_speed",
+	  .permissions			= PROC_RW,
+	  .type				= SUSPEND_PROC_DATA_BIT,
+	  .data = {
+		  .bit = {
+			  .bit_vector	= &suspend_action,
+			  .bit		= SUSPEND_TEST_FILTER_SPEED,
+		  }
+	  }
+	},
+
+	{ .filename			= "slow",
+	  .permissions			= PROC_RW,
+	  .type				= SUSPEND_PROC_DATA_BIT,
+	  .data = {
+		  .bit = {
+			  .bit_vector	= &suspend_action,
+			  .bit		= SUSPEND_SLOW,
+		  }
+	  }
+	},
+	
+	{ .filename			= "display_metadata_page",
+	  .permissions			= PROC_RW,
+	  .type				= SUSPEND_PROC_DATA_UL,
+	  .data = {
+		  .ul = {
+			  .variable	= &display_metadata_page,
+		  }
+	  }
+	},
+#endif
+	  
+	{ .filename			= "forced_pageset1_size",
+	  .permissions			= PROC_RW,
+	  .type				= SUSPEND_PROC_DATA_UL,
+	  .data = {
+		  .ul = {
+			  .variable	= &forced_ps1_size,
+		  }
+	  }
+	},
+
+	{ .filename			= "forced_pageset2_size",
+	  .permissions			= PROC_RW,
+	  .type				= SUSPEND_PROC_DATA_UL,
+	  .data = {
+		  .ul = {
+			  .variable	= &forced_ps2_size,
+		  }
+	  }
+	},
+
+#if defined(CONFIG_ACPI)
+	{ .filename			= "powerdown_method",
+	  .permissions			= PROC_RW,
+	  .type				= SUSPEND_PROC_DATA_UL,
+	  .data = {
+		  .ul = {
+			  .variable	= &suspend_powerdown_method,
+			  .minimum	= 3,
+			  .maximum	= 5,
+		  }
+	  }
+	},
+#endif
+
+#ifdef CONFIG_SOFTWARE_SUSPEND_KEEP_IMAGE
+	{ .filename			= "keep_image",
+	  .permissions			= PROC_RW,
+	  .type				= SUSPEND_PROC_DATA_BIT,
+	  .data = {
+		  .bit = {
+			  .bit_vector	= &suspend_action,
+			  .bit		= SUSPEND_KEEP_IMAGE,
+		  }
+	  }
+	},
+#endif
+};
+
+extern int debuginfo_read_proc(char * page, char ** start, off_t off, int count,
+		int *eof, void *data);
+
+/*
+ * Called from init kernel_thread.
+ * We check if we have an image and if so we try to resume.
+ * We also start ksuspendd if configuration looks right.
+ */
+
+extern int freeze_processes(int no_progress);
+
+static int do_resume(void)
+{
+	int ret = 0;
+	int read_image_result = 0;
+
+	/* Suspend always runs on processor 0 */
+	ensure_on_processor_zero();
+
+	if (sizeof(swp_entry_t) != sizeof(long)) {
+		printk(KERN_WARNING name_suspend
+			"The size of swp_entry_t != size of long. "
+			"Please report this!\n");
+		return ret;
+	}
+	
+	set_suspend_state(SUSPEND_RUNNING);
+
+	if (!resume2_file[0])
+		printk(KERN_WARNING name_suspend
+			"You need to use a resume2= command line parameter to "
+			"tell Software Suspend 2 where to look for an image.\n");
+
+	if (!(test_suspend_state(SUSPEND_RESUME_DEVICE_OK)))
+		attempt_to_parse_resume_device();
+
+	if (!(test_suspend_state(SUSPEND_RESUME_DEVICE_OK))) {
+		/* 
+		 * Without a usable storage device we can do nothing - 
+		 * even if noresume is given
+		 */
+
+		if (!num_writers)
+			printk(KERN_ALERT name_suspend
+				"No writers have been registered.\n");
+		else
+			printk(KERN_ALERT name_suspend
+				"Missing or invalid storage location "
+				"(resume2= parameter). Please correct and "
+				"rerun lilo (or equivalent) before "
+				"suspending.\n");
+		clear_suspend_state(SUSPEND_RUNNING);
+		return ret;
+	}
+
+	/* We enable the possibility of machine suspend */
+	orig_mem_free = real_nr_free_pages();
+
+	suspend_task = current->pid;
+
+	read_image_result = read_primary_suspend_image(); /* non fatal error ignored */
+
+	if (test_suspend_state(SUSPEND_NORESUME_SPECIFIED))
+		printk(KERN_WARNING name_suspend "Resuming disabled as requested.\n");
+
+	if (read_image_result) {
+		suspend_task = 0;
+		clear_suspend_state(SUSPEND_RUNNING);
+		return ret;
+	}
+
+	/* 
+	 * Ensure our suspend device tree is configured (2.6) as
+	 * at suspend time
+	 */
+	
+	suspend_version_specific_initialise();
+
+	freeze_processes(1);
+
+	prepare_status(0, 0,
+		"Copying original kernel back (no status - sensitive!)...");
+	
+	do_suspend2_lowlevel(1);
+	BUG();
+
+	return ret;
+}
+
+extern int suspend_plugin_keypress(unsigned int keycode);
+extern void request_abort_suspend(void);
+extern void schedule_suspend_message(int message_number);
+
+int suspend_keypress(unsigned int keycode)
+{
+	/* These keys work even if no output is enabled.
+	 * (To get this far, we must be suspending or resuming).
+	 */
+	switch (keycode) {
+		case 27:
+			/* Abort suspend */
+			if (TEST_ACTION_STATE(SUSPEND_CAN_CANCEL))
+				request_abort_suspend();
+			break;
+		case 114:
+			/* Otherwise, if R pressed, toggle rebooting */
+			suspend_action ^= (1 << SUSPEND_REBOOT);
+			schedule_suspend_message(2);
+			break;
+		default:
+			return suspend_plugin_keypress(keycode);
+	}
+	return 1;
+}
+
+extern void suspend_early_boot_message_plugins(void);
+extern void cleanup_finished_suspend_io(void);
+
+struct suspend2_core_ops core_ops = {
+	.do_suspend = do_activate,
+	.do_resume = do_resume,
+	.resume1 = do_suspend2_resume_1, 
+	.resume2 = do_suspend2_resume_2, 
+	.suspend1 = do_suspend2_suspend_1, 
+	.suspend2 = do_suspend2_suspend_2, 
+	.free_pool_pages = free_suspend_pool_pages,
+	.get_pool_pages = get_suspend_pool_pages,
+	.get_grabbed_pages = get_grabbed_pages,
+	.cleanup_finished_io = cleanup_finished_suspend_io,
+	.suspend_message = __suspend_message,
+	.update_status = update_status,
+	.prepare_status = prepare_status,
+	.schedule_message = schedule_suspend_message,
+	.early_boot_plugins = suspend_early_boot_message_plugins,
+	.keypress = suspend_keypress,
+	.verify_checksums = __suspend2_verify_checksums,
+};
+
+static struct proc_dir_entry *compat_parent;
+extern void suspend_memory_pool_init(void);
+
+static __init int core_load(void)
+{
+	int i, numfiles = sizeof(proc_params) / sizeof(struct suspend_proc_data);
+
+	if (suspend2_register_core(&core_ops))
+		return -EBUSY;
+
+	printk("Software Suspend Core.\n");
+	for (i=0; i< numfiles; i++)
+		suspend_register_procfile(&proc_params[i]);
+
+	suspend_console_proc_init();
+
+	suspend_memory_pool_init();
+
+#if LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0)
+	return 0;
+#else
+	return (!!compat_parent);
+#endif
+}
+
+#ifdef MODULE
+static __exit void core_unload(void)
+{
+	int i, numfiles = sizeof(proc_params) / sizeof(struct suspend_proc_data);
+
+	printk("Software Suspend Core unloading.\n");
+	suspend_console_proc_exit();
+
+	for (i=0; i< numfiles; i++)
+		suspend_unregister_procfile(&proc_params[i]);
+
+	suspend2_unregister_core();
+}
+
+module_init(core_load);
+module_exit(core_unload);
+MODULE_LICENSE("GPL");
+MODULE_AUTHOR("Nigel Cunningham");
+MODULE_DESCRIPTION("Suspend2 core");
+#else
+late_initcall(core_load);
+#endif
+EXPORT_SYMBOL(checksum_map);
+EXPORT_SYMBOL(attempt_to_parse_resume_device);
#117 lore raw

Suspend 2 merge: 37/51: Memory pool support.

In reply to Nigel Cunningham

This is the memory pool support. It handles all pages freed and allocated between the preparation of the image and the completion of resuming, except prior to restoring the original kernel at resume time. It is designed for speed and to match the fact that suspend2 just about exclusively uses order 0 allocations. ("Just about" is why a couple of order one and two allocations are also available).

kernel/power/memory_pool.c +378 -0
diff -ruN 827-memory-pool-old/kernel/power/memory_pool.c 827-memory-pool-new/kernel/power/memory_pool.c
@@ -0,0 +1,378 @@
+/*
+ * kernel/power/memory_pool.c
+ *  
+ * Copyright (C) 2003,2004 Nigel Cunningham <[email protected]>
+ *
+ * This file is released under the GPLv2.
+ *
+ * It contains routines for managing the memory pool during software suspend
+ * operation.
+ * 
+ * The memory pool is a pool of pages from which page allocations
+ * are satisfied while we are suspending, and into which freed pages are
+ * released. In this way, we can keep the image size static and consistent
+ * while still using normal I/O routines to save the image and while saving
+ * the image in two parts.
+ * 
+ * During suspend, almost all of the page allocations are order zero. Provision
+ * is made for one order one and one order two allocation. This provision is 
+ * utilised by the swapwriter for allocating memory which is used for structures
+ * containing header page. (It could be made to use order zero allocations; this
+ * just hasn't been done yet).
+ */
+
+#define SUSPEND_MEMORY_POOL_C
+
+#include <linux/suspend.h>
+#include <linux/module.h>
+#include <linux/highmem.h>
+
+#include "suspend.h"
+#include "plugins.h"
+#include "pageflags.h"
+
+/* We keep high memory pages that are freed, but don't use them */
+struct memory_pool {
+	struct list_head contents[MAX_ORDER];
+	int level[MAX_ORDER];
+};
+
+static struct memory_pool normal_pool, highmem_pool;
+
+static int suspend_pool_level_limit[MAX_ORDER];
+static spinlock_t suspend_memory_pool_lock = SPIN_LOCK_UNLOCKED;
+
+static int min_pool_level = 0;
+
+#ifdef CONFIG_SOFTWARE_SUSPEND_DEBUG
+/* display_memory_pool_pages()
+ *
+ * Description:	Display the current contents of the memory pool.
+ */	
+static void __display_memory_pool_pages(struct memory_pool * pool)
+{
+	int order;
+
+	for (order = 0; order < MAX_ORDER; order++) {
+		struct page * page;
+		int index = 0;
+		suspend_message(SUSPEND_MEM_POOL, SUSPEND_VERBOSE, 1,
+				"- Order %d:\n", order);
+		list_for_each_entry(page, &pool->contents[order], lru) {
+			suspend_message(SUSPEND_MEM_POOL, SUSPEND_VERBOSE, 1,
+					"[%p] ", page);
+			index++;
+			if (!(index%8))
+				suspend_message(SUSPEND_MEM_POOL, SUSPEND_VERBOSE, 1,
+					"\n");
+		}
+
+		if (pool->level[order])
+			suspend_message(SUSPEND_MEM_POOL, SUSPEND_VERBOSE, 1,
+					"(%d entries)\n", pool->level[order]);
+		else
+			suspend_message(SUSPEND_MEM_POOL, SUSPEND_VERBOSE, 1,
+					"(empty)\n");
+	}
+}
+
+void display_memory_pool_pages(void)
+{
+	if (!TEST_DEBUG_STATE(SUSPEND_MEM_POOL))
+		return;
+
+	suspend_message(SUSPEND_MEM_POOL, SUSPEND_VERBOSE, 1, "Memory pool:\n");
+	suspend_message(SUSPEND_MEM_POOL, SUSPEND_VERBOSE, 1, "Normal pages:\n");
+	__display_memory_pool_pages(&normal_pool);
+	suspend_message(SUSPEND_MEM_POOL, SUSPEND_VERBOSE, 1, "High pages:\n");
+	__display_memory_pool_pages(&highmem_pool);
+}
+#else
+#define display_memory_pool_pages() do { } while(0)
+#endif
+
+__init void initialise_pool(struct memory_pool * pool)
+{
+	int i;
+
+	for (i = 0; i < MAX_ORDER; i++) {
+		pool->level[i] = 0;
+		INIT_LIST_HEAD(&pool->contents[i]);
+	}
+
+	suspend_pool_level_limit[1] = 1;
+	suspend_pool_level_limit[2] = 1;
+}
+
+__init void suspend_memory_pool_init(void)
+{
+	/* Initialise lists */
+	initialise_pool(&normal_pool);
+	initialise_pool(&highmem_pool);
+}
+
+/* get_from_pool()
+ *
+ * Description: Remove head of a pool list
+ */
+
+static struct page * get_from_pool(struct memory_pool * pool, int order)
+{
+	struct page * page;
+	int j;
+
+	if (!pool->level[order])
+		return 0;
+
+	page = list_entry(pool->contents[order].next, struct page, lru);
+	list_del_init(&page->lru);
+	pool->level[order]--;
+
+	for (j = 0; j < (1 << order); j++)
+		ClearPageChecksumIgnore(page + j);
+
+	if (page_count(page) != 1)
+		printk("Error getting page %p from memory pool. "
+			"Page count is %d (should be 1).\n",
+			page,
+			page_count(page));
+
+	BUG_ON(PageLRU(page) || PageActive(page));
+
+	display_memory_pool_pages();
+	suspend_message(SUSPEND_MEM_POOL, SUSPEND_MEDIUM, 0,
+			"\r%4d %4d %4d.",
+			normal_pool.level[0],
+			normal_pool.level[1],
+			normal_pool.level[2]);
+
+	return page;
+}
+
+/* add_to_pool()
+ *
+ * Description: Insert new head in a pool list
+ */
+
+static void add_to_pool(struct memory_pool * pool, int order, struct page * this)
+{
+	int j;
+
+	pool->level[order]++;
+	list_add(&this->lru, &pool->contents[order]);
+	for (j = 0; j < (1 << order); j++)
+		SetPageChecksumIgnore(this + j);
+	
+	display_memory_pool_pages();
+	suspend_message(SUSPEND_MEM_POOL, SUSPEND_MEDIUM, 0,
+			"\r%4d %4d %4d.",
+			normal_pool.level[0],
+			normal_pool.level[1],
+			normal_pool.level[2]);
+}
+
+/* suspend_memory_pool_level()
+ *
+ * Description:	Returns the number of pages currently in the pool.
+ * Returns:	Int.		Number of pages in the pool.
+ */
+int suspend_memory_pool_level(int only_lowmem)
+{
+	int order, sum = 0;
+
+	for (order = 0; order < MAX_ORDER; order++)
+		sum += normal_pool.level[order] * (1 << order);
+
+	if (!only_lowmem)
+		for (order = 0; order < MAX_ORDER; order++)
+			sum += highmem_pool.level[order] * (1 << order);
+	return sum;
+}
+
+/* fill_suspend_memory_pool()
+ *
+ * Description:	Fill the memory pool from the main free memory pool in the
+ * 		first instance, or grabbed pages if that fails.
+ * 		We allocate @sizesought order 0 pages, plus 1 each
+ * 		of the higher order allocations.
+ * Arguments:	int.		Number of order zero pages requested.
+ * Returns:	int.		Number of order zero pages obtained.
+ */
+int fill_suspend_memory_pool(int sizesought)
+{
+	int i = 0, order, orig_state = 
+		test_suspend_state(SUSPEND_USE_MEMORY_POOL);
+	unsigned long *this = NULL;
+	unsigned long flags;
+
+	spin_lock_irqsave(&suspend_memory_pool_lock, flags);
+
+	/* Pools must not be active for this to work */
+	clear_suspend_state(SUSPEND_USE_MEMORY_POOL);
+
+	suspend_pool_level_limit[0] = sizesought;
+
+	for (order = MAX_ORDER; order >= 0; order--) {
+		int wanted = suspend_pool_level_limit[order] -
+			normal_pool.level[order];
+		for (i = normal_pool.level[order]; 
+				i < suspend_pool_level_limit[order]; i++) {
+			this = (unsigned long *) get_grabbed_pages(order);
+			if (!this) {
+				suspend_message(SUSPEND_MEM_POOL, SUSPEND_ERROR, 1,
+					"%d order %d pages wanted for suspend "
+					"memory pool, got %d.\n",
+					wanted, order, i - 1);
+				break;
+			}
+			add_to_pool(&normal_pool, order, virt_to_page(this));
+		}
+	}
+
+	if (orig_state)
+		set_suspend_state(SUSPEND_USE_MEMORY_POOL);
+
+	min_pool_level = normal_pool.level[0];
+
+	spin_unlock_irqrestore(&suspend_memory_pool_lock, flags);
+
+	return 0;
+}
+
+/* empty_suspend_memory_pool()
+ *
+ * Description:	Drain our memory pool.
+ */
+void __empty_suspend_memory_pool(struct memory_pool * pool)
+{
+	int order;
+	struct page * this;
+
+	for (order = 0; order < MAX_ORDER; order++)
+		while ((this = get_from_pool(pool, order)))
+			__free_pages(this, order);
+
+	suspend_message(SUSPEND_MEM_POOL, SUSPEND_LOW, 1,
+		"Min pool level was %d/%d.\n", min_pool_level, suspend_pool_level_limit[0]);
+}
+
+void empty_suspend_memory_pool(void)
+{
+	unsigned long flags;
+
+	spin_lock_irqsave(&suspend_memory_pool_lock, flags);
+
+	display_memory_pool_pages();
+	
+	/* Pool must not be active for this to work */
+	clear_suspend_state(SUSPEND_USE_MEMORY_POOL);
+
+	__empty_suspend_memory_pool(&normal_pool);
+	__empty_suspend_memory_pool(&highmem_pool);
+	
+	spin_unlock_irqrestore(&suspend_memory_pool_lock, flags);
+}
+
+/* get_suspend_pool_pages()
+ * 
+ * Description:	Our equivalent to __alloc_pages (minus zone mask).
+ * 		May be called from interrupt context.
+ * Arguments:	unsigned int:	Mask. We really only care about __GFP_WAIT.
+ * 				We're giving normal zone pages regardless.
+ * 		order:		The number of pages (1 << order) wanted.
+ * Returns:	struct page *:	Pointer (possibly NULL) to pages allocated.
+ */
+struct page * get_suspend_pool_pages(unsigned int gfp_mask, unsigned int order)
+{
+	unsigned long flags;
+	struct page * page;
+
+	if (order > 0) {
+		spin_lock_irqsave(&suspend_memory_pool_lock, flags);
+		if (!normal_pool.level[order]) {
+			printk("No order %d allocation available.\n",
+					order);
+			display_memory_pool_pages();
+			spin_unlock_irqrestore(
+					&suspend_memory_pool_lock,
+					flags);
+			return NULL;
+		}
+		goto check_and_return;
+	}
+
+try_again:
+	if ((!normal_pool.level[order]) && (!(gfp_mask & __GFP_WAIT))) {
+		spin_lock_irqsave(&suspend_memory_pool_lock, flags);
+		display_memory_pool_pages();
+		spin_unlock_irqrestore(&suspend_memory_pool_lock, flags);
+		return NULL;
+	}
+
+	while(!normal_pool.level[order]) {
+		if (active_writer->ops.writer.wait_on_io)
+			active_writer->ops.writer.wait_on_io(0);
+		schedule();
+	}
+
+	spin_lock_irqsave(&suspend_memory_pool_lock, flags);
+	if (!normal_pool.level[order]) {
+		spin_unlock_irqrestore(&suspend_memory_pool_lock, flags);
+		goto try_again;
+	}
+check_and_return:
+	page = get_from_pool(&normal_pool, order);
+	
+	if (normal_pool.level[0] < min_pool_level)
+		min_pool_level = normal_pool.level[0];
+	if (!normal_pool.level[0])
+		printk("Normal pool empty.\n");
+
+	spin_unlock_irqrestore(&suspend_memory_pool_lock, flags);
+	
+	return page;
+}
+
+/* free_suspend_pool_pages()
+ *
+ * Description:	Our equivalent to  __free_pages. Put freed pages into the pool.
+ * 		HighMem pages do still get freed to the normal pool because they
+ * 		aren't going to affect the consistency of our image - worse case,
+ * 		we write a few free pages.
+ * Arguments:	Struct page *:	First page to be freed.
+ * 		Unsigned int:	Size of allocation being freed.
+ */
+void free_suspend_pool_pages(struct page *page, unsigned int order)
+{
+	unsigned long flags;
+	int i;
+	struct memory_pool * pool = &normal_pool;
+
+	suspend_message(SUSPEND_MEM_POOL, SUSPEND_VERBOSE, 1, 
+		"Freeing page %p (%p), order %d.\n",
+		page_address(page), page, order);
+	
+	if (PageHighMem(page))
+		pool = &highmem_pool;
+
+#ifdef CONFIG_MMU
+	set_page_count(page, 1);
+#else
+	for (i = 0; i < (1 << order); i++)
+		set_page_count(page + i, 1);
+#endif
+	if (pool == &normal_pool) {
+		char * address = page_address(page);
+		for (i = 0; i < (1 << order); i++) {
+			clear_page(address);
+			address += PAGE_SIZE;
+		}
+	}
+
+	spin_lock_irqsave(&suspend_memory_pool_lock, flags);
+	add_to_pool(pool, order, page);
+	spin_unlock_irqrestore(&suspend_memory_pool_lock, flags);
+	return;
+}
+
+EXPORT_SYMBOL(suspend_memory_pool_level);
#119 lore raw

Suspend 2 merge: 33/51: More documentation.

In reply to Nigel Cunningham

More documentation for suspend. The internals.txt file is still to be completed (and a bit out of date, too!).

Documentation/power/internals.txt +364 -0
diff -ruN 821-docs-old/Documentation/power/internals.txt 821-docs-new/Documentation/power/internals.txt
@@ -0,0 +1,364 @@
+		Software Suspend 2.0 Internal Documentation.
+				Version 1
+
+1.  Introduction.
+
+    Software Suspend 2.0 is an addition to the Linux Kernel, designed to
+    allow the user to quickly shutdown and quickly boot a computer, without
+    needing to close documents or programs. It is equivalent to the
+    hibernate facility in some laptops. This implementation, however,
+    requires no special BIOS or hardware support.
+
+    The code in these files is based upon the original implementation
+    prepared by Gabor Kuti and additional work by Pavel Machek and a
+    host of others. This code has been substantially reworked by Nigel
+    Cunningham, again with the help and testing of many others, not the
+    least of whom is Michael Frank, At its heart, however, the operation is
+    essentially the same as Gabor's version.
+
+2.  Overview of operation.
+
+    The basic sequence of operations is as follows:
+
+	a. Quiesce all other activity.
+	b. Ensure enough memory and storage space are available, and attempt
+	   to free memory/storage if necessary.
+	c. Allocate the required memory and storage space.
+	d. Write the image.
+	e. Power down.
+
+    There are a number of complicating factors which mean that things are
+    not as simple as the above would imply, however...
+
+    o The activity of each process must be stopped at a point where it will
+    not be holding locks necessary for saving the image, or unexpectedly
+    restart operations due to something like a timeout and thereby make
+    our image inconsistent.
+
+    o It is desirous that we sync outstanding I/O to disk before calculating
+    image statistics. This reduces corruption if one should suspend but
+    then not resume, and also makes later parts of the operation safer (see
+    below).
+
+    o We need to get as close as we can to an atomic copy of the data.
+    Inconsistencies in the image will result inconsistent memory contents at
+    resume time, and thus in instability of the system and/or file system
+    corruption. This would appear to imply a maximum image size of one half of
+    the amount of RAM, but we have a solution... (again, below).
+
+    o In 2.6, we must play nicely with the other suspend-to-disk
+    implementations.
+
+3.  Detailed description of internals.
+
+    a. Quiescing activity.
+
+    Safely quiescing the system is achieved in a number of steps. First, we
+    wait for existing activity to complete, while holding new activity until
+    post-resume. Second, we sync unwritten buffers. Third, we send a
+    'pseudo-signal' to all processes that have not yet entered the
+    'refrigerator' but should be frozen, causing them to be refrigerated.
+
+    Waiting for existing activity to complete is achieved by using hooks at
+    the beginning and end of critical paths in the kernel code. When a process
+    enters a section where it cannot be safely refrigerated, the process flag
+    PF_FRIDGE_WAIT is set from the SWSUSP_ACTIVITY_STARTING macro. In the same
+    routine, at completion of the critical region, a SWSUSP_ACTIVITY_END macro
+    resets the flag. The _STARTING and _ENDING macros also atomically adjust
+    the global counter swsusp_num_active. While the counter is non-zero, 
+    Software Suspend's freezer will wait.
+
+    These macros serve two other additional purposes. Local variables are used
+    to ensure that processes can safely pass through multiple  _STARTING and
+    _ENDING macros, and checks are made to ensure that the freezer is not
+    waiting for activity to finish. If a process wants to start on a critical
+    path when Suspend is waiting for activity to finish, it will be held at the
+    start of the critical path and refrigerated earlier than would normally be
+    the case. It will be allowed to continue operation after the Suspend cycle
+    is finished or aborted.
+
+    A process in a critical path may also have a section where it releases
+    locks and can be safely stopped until post-resume. For these cases, the
+    SWSUSP_ACTIVITY_PAUSING and _RESTARTING macros may be used. They function
+    in a similar manner to the _STARTING and _ENDING macros.
+
+    Finally, we remember that some threads may be necessary for syncing data to
+    storage. These threads have PF_SYNCTHREAD set, and may use the special macro
+    SWSUSP_ACTIVITY_SYNCTHREAD_PAUSING to indicate that Suspend can safely
+    continue, while not themselves entering the refrigerator.
+
+    Once activity is stopped, Suspend will initiate a fsync of all devices.
+    This aims to increase the integrity of the disk state, just in case
+    something should go wrong.
+
+    During the initial stage, Suspend indicates its desire that processes be
+    stopped by setting the FREEZE_NEW_ACTIVITY bit of swsusp_state.  Once the
+    sync is complete, SYNCTHREAD processes no longer need to run. The
+    FREEZE_UNREFRIGERATED bit is now set, causing them to be refrigerated as
+    well, should they attempt to start new activity. (There should be nothing
+    for them to do, but just-in-case).
+
+    Suspend can now put remaining processes in the refrigerator without fear
+    of deadlocking or leaving dirty data unsynced. The refrigerator is a
+    procedure where processes wait until the cycle is complete. While in there,
+    we can be sure that they will not perform activity that will make our
+    image inconsistent. Processes enter the refrigerator either by being
+    caught at one of the previously mentioned hooks, or by receiving a 'pseudo-
+    signal' from Suspend at this stage. I call it a pseudo signal because
+    signal_wake_up is called for the process when it actually hasn't been
+    signalled. A special hook in the signal handler then calls the refrigerator.
+    The refrigerator, in turn, recalculates the signal pending status to
+    ensure no ill effects result.
+
+    Not all processes are refrigerated. The Suspend thread itself, of course,
+    is one such thread. Others are flagged by setting PF_NOFREEZE, usually
+    because they are needed during suspend.
+
+    In 2.4, the dosexec thread (Win4Lin) is treated specially. It does not
+    handle us even pretending to send it a signal. This is worked-around by
+    us adjusting the can_schedule() macro in schedule.c to stop the task from
+    being scheduled during suspend. Ugly, but it works. The 2.6 version of
+    Win4Lin has been made compatible.
+
+    b. Ensure enough memory & storage are available.
+    c. Allocate the required memory and storage space.
+
+    These steps are merged together in the prepare_image function, found in
+    prepare_image.c. The functions are merged because of the cyclical nature
+    of the problem of calculating how much memory and storage is needed. Since
+    the data structures containing the information about the image must
+    themselves take memory and use storage, the amount of memory and storage
+    required changes as we prepare the image. Since the changes are not large,
+    only one or two iterations will be required to achieve a solution.
+
+    d. Write the image.
+
+    We previously mentioned the need to create an atomic copy of the data, and
+    the half-of-memory limitation that is implied in this. This limitation is
+    circumvented by dividing the memory to be saved into two parts, called
+    pagesets.
+
+    Pageset2 contains the page cache - the pages on the active and inactive
+    lists. These pages are saved first and reloaded last. While saving these
+    pages, the swapwriter plugin carefully ensures that the work of writing
+    the pages doesn't make the image inconsistent. Pages added to the LRU
+    lists are immediately shot down, and careful accounting for available
+    memory aids debugging. No atomic copy of these pages needs to be made.
+
+    Writing the image requires memory, of course, and at this point we have
+    also not yet suspended the drivers. To avoid the possibility of remaining
+    activity corrupting the image, we allocate a special memory pool. Calls
+    to __alloc_pages and __free_pages_ok are then diverted to use our memory
+    pool. Pages in the memory pool are saved as part of pageset1 regardless of
+    whether or not they are used.
+
+    Once pageset2 has been saved, we suspend the drivers and save the CPU
+    context before making an atomic copy of pageset1, resuming the drivers
+    and saving the atomic copy. After saving the two pagesets, we just need to
+    save our metadata before powering down.
+
+    Having saved pageset2 pages, we can safely overwrite their contents with
+    the atomic copy of pageset1. This is how we manage to overcome the half of
+    memory limitation. Pageset2 is normally far larger than pageset1, and
+    pageset1 is normally much smaller than half of the memory, with the result
+    that pageset2 pages can be safely overwritten with the atomic copy of
+    pageset1. This is where we need to be careful about syncing, however.
+    Pageset2 will probably contain filesystem meta data. If this is overwritten
+    with pageset1 and then a sync occurs, the filesystem will be corrupted -
+    at least until resume time and another sync of the restored data. Since
+    there is a possibility that the user might not resume or (may it never be!)
+    that suspend might oops, we do our utmost to avoid syncing filesystems after
+    copying pageset1.
+
+    e. Power down.
+
+    Powering down uses standard kernel routines. Prior to this, however, we
+    suspend drivers again, ensuring that write caches are flushed.
+
+4.  The method of writing the image.
+
+    Software Suspend 2.0rc3 and later contain an internal API which is
+    designed to simplify the implementation of new methods of transforming
+    the image to be written and writing the image itself. Prior to rc3,
+    compression support was inlined in the image writing code, and the data
+    structures and code for managing swap were intertwined with the rest of
+    the code. A number of people had expressed interest in implementing
+    image encryption, and alternative methods of storing the image. This
+    internal API makes that possible by implementing 'plugins'.
+
+    A plugin is a single file which encapsulates the functionality needed
+    to transform a pageset of data (encryption or compression, for example),
+    or to write the pageset to a device. The former type of plugin is called
+    a 'page-transformer', the later a 'writer'.
+
+    Plugins are linked together in pipeline fashion. There may be zero or more
+    page transformers in a pipeline, and there is always exactly one writer.
+    The pipeline follows this pattern:
+
+		---------------------------------
+		|     Software Suspend Core     |
+		---------------------------------
+				|
+				|
+		---------------------------------
+		|	Page transformer 1	|
+		---------------------------------
+				|
+				|
+		---------------------------------
+		|	Page transformer 2	|
+		---------------------------------
+				|
+				|
+		---------------------------------
+		|            Writer		|
+		---------------------------------
+
+    During the writing of an image, the core code feeds pages one at a time
+    to the first plugin. This plugin performs whatever transformations it
+    implements on the incoming data, completely consuming the incoming data and
+    feeding output in a similar manner to the next plugin. A plugin may buffer
+    its output.
+
+    During reading, the pipeline works in the reverse direction. The core code
+    calls the first plugin with the address of a buffer which should be filled.
+    (Note that the buffer size is always PAGE_SIZE at this time). This plugin
+    will in turn request data from the next plugin and so on down until the
+    writer is made to read from the stored image.
+
+    Part of definition of the structure of a plugin thus looks like this:
+
+	/* Writing the image proper */
+	int (*write_init) (int stream_number);
+	int (*write_chunk) (char * buffer_start);
+	int (*write_cleanup) (void);
+
+	/* Reading the image proper */
+	int (*read_init) (int stream_number);
+	int (*read_chunk) (char * buffer_start, int sync);
+	int (*read_cleanup) (void);
+
+    It should be noted that the _cleanup routines may be called before the
+    full stream of data has been read or written. While writing the image,
+    the user may (depending upon settings) choose to abort suspending, and
+    if we are in the midst of writing the last portion of the image, a portion
+    of the second pageset may be reread.
+
+    In addition to the above routines for writing the data, all plugins have a
+    number of other routines:
+
+    TYPE indicates whether the plugin is a page transformer or a writer.
+    #define TRANSFORMER_PLUGIN 1
+    #define WRITER_PLUGIN 2
+
+    NAME is the name of the plugin, used in generic messages.
+
+    PLUGIN_LIST is used to link the plugin into the list of all plugins.
+
+    MEMORY_NEEDED returns the number of pages of memory required by the plugin
+    to do its work.
+
+    STORAGE_NEEDED returns the number of pages in the suspend header required
+    to store the plugin's configuration data.
+
+    PRINT_DEBUG_INFO fills a buffer with information to be displayed about the
+    operation or settings of the plugin.
+
+    SAVE_CONFIG_INFO returns a buffer of PAGE_SIZE or smaller (the size is the
+    return code), containing the plugin's configuration info. This information
+    will be written in the image header and restored at resume time. Since this
+    buffer is allocated after the atomic copy of the kernel is made, you don't
+    need to worry about the buffer being freed.
+
+    LOAD_CONFIG_INFO gives the plugin a pointer to the the configuration info
+    which was saved during suspending. Once again, the plugin doesn't need to
+    worry about freeing the buffer. The kernel will be overwritten with the
+    original kernel, so no memory leak will occur.
+
+    OPS contains the operations specific to transformers and writers. These are
+    described below.
+
+    The complete definition of struct swsusp_plugin_ops is:
+
+	struct swsusp_plugin_ops {
+		/* Functions common to transformers and writers */
+		int type;
+		char * name;
+		struct list_head plugin_list;
+		unsigned long (*memory_needed) (void);
+		unsigned long (*storage_needed) (void);
+		int (*print_debug_info) (char * buffer, int size);
+		int (*save_config_info) (char * buffer);
+		void (*load_config_info) (char * buffer, int len);
+	
+		/* Writing the image proper */
+		int (*write_init) (int stream_number);
+		int (*write_chunk) (char * buffer_start);
+		int (*write_cleanup) (void);
+
+		/* Reading the image proper */
+		int (*read_init) (int stream_number);
+		int (*read_chunk) (char * buffer_start, int sync);
+		int (*read_cleanup) (void);
+
+		union {
+			struct swsusp_transformer_ops transformer;
+			struct swsusp_writer_ops writer;
+		} ops;
+	};
+
+
+	The operations specific to transformers are few in number:
+
+	struct swsusp_transformer_ops {
+		int (*expected_compression) (void);
+		struct list_head transformer_list;
+	};
+
+	Expected compression returns the expected ratio between the amount of
+	data sent to this plugin and the amount of data it passes to the next
+	plugin. The value is used by the core code to calculate the amount of
+	space required to write the image. If the ratio is not achieved, the
+	writer will complain when it runs out of space with data still to
+	write, and the core code will abort the suspend.
+
+	transformer_list links together page transformers, in the order in
+	which they register, which is in turn determined by order in the
+	Makefile.
+	
+	There are many more operations specific to a writer:
+
+	struct swsusp_writer_ops {
+
+		long (*storage_available) (void);
+	
+		unsigned long (*storage_allocated) (void);
+		
+		int (*release_storage) (void);
+
+		long (*allocate_header_space) (unsigned long space_requested);
+		int (*allocate_storage) (unsigned long space_requested);
+
+		int (*write_header_init) (void);
+		int (*write_header_chunk) (char * buffer_start, int buffer_size);
+		int (*write_header_cleanup) (void);
+
+		int (*read_header_init) (void);
+		int (*read_header_chunk) (char * buffer_start, int buffer_size);
+		int (*read_header_cleanup) (void);
+
+		int (*prepare_save) (void);
+		int (*post_load) (void);
+
+		int (*parse_image_location) (char * buffer);
+
+		int (*image_exists) (void);
+
+		int (*invalidate_image) (void);
+
+		int (*wait_on_io) (int flush_all);
+
+		struct list_head writer_list;
+	};
+
+	STORAGE_AVAILABLE is 
Documentation/power/todo.txt +19 -0
diff -ruN 821-docs-old/Documentation/power/todo.txt 821-docs-new/Documentation/power/todo.txt
@@ -0,0 +1,19 @@
+Suspend2 todo list
+
+20041021
+  2.1 known issues:
+  ----------------
+- NFS support missing
+- Encryption support missing
+- DRI support for 2.4 & 2.6
+- USB support under 2.4 and 2.6
+- Incomplete support in other drivers
+- No support for discontig memory
+- Currently requires PSE extension (/proc/cpuinfo)
+- Highmem >4GB not supported
+
+20040107
+- Further cleaning up.
+
+20031216
+- Include progress-bar-granularity in all_settings.
#120 lore raw

Suspend 2 merge: 22/51: Suspend2 lowlevel code.

In reply to Nigel Cunningham

Lowlevel code for i386. This is the code responsible for saving and restoring CPU state, and for restoring the original kernel (except LRU pages, which are loaded afterwards).

arch/i386/power/Makefile +3 -1
diff -ruN 700-suspend2-lowlevel-old/arch/i386/power/Makefile 700-suspend2-lowlevel-new/arch/i386/power/Makefile
@@ -1,2 +1,4 @@
-obj-$(CONFIG_PM)		+= cpu.o
+CFLAGS_suspend2.o = -O0
+
+obj-$(CONFIG_PM)		+= cpu.o suspend2.o
 obj-$(CONFIG_SOFTWARE_SUSPEND)	+= swsusp.o
arch/i386/power/suspend2.c +639 -0

639 lines not on this page · raw message

#128 lore raw

Suspend 2 merge: 14/51: Disable page alloc failure message when suspending

In reply to Nigel Cunningham

While eating memory, we will potentially trigger this a lot. We therefore disable the message when suspending.

mm/page_alloc.c +4 -1
diff -ruN 503-disable-page-alloc-warnings-while-suspending-old/mm/page_alloc.c 503-disable-page-alloc-warnings-while-suspending-new/mm/page_alloc.c
@@ -725,7 +725,10 @@
 	}
 
 nopage:
-	if (!(gfp_mask & __GFP_NOWARN) && printk_ratelimit()) {
+	if ((!(gfp_mask & __GFP_NOWARN)) && 
+		(!test_suspend_state(SUSPEND_RUNNING)) &&
+		printk_ratelimit()) {
+
 		printk(KERN_WARNING "%s: page allocation failure."
 			" order:%d, mode:0x%x\n",
 			p->comm, order, gfp_mask);
#139 lore raw

Suspend 2 merge: 15/51: Disable pdflush during suspend.

In reply to Nigel Cunningham

Here we disable pdflush once we've finished syncing data to disk. We might be writing to a swap file, and don't want to corrupt the user's disk by writing invalid data to their superblock.

mm/page-writeback.c +9 -0
diff -ruN 504-disable-pdflush-during-suspend-old/mm/page-writeback.c 504-disable-pdflush-during-suspend-new/mm/page-writeback.c
@@ -29,6 +29,7 @@
 #include <linux/sysctl.h>
 #include <linux/cpu.h>
 #include <linux/syscalls.h>
+#include <linux/suspend.h>
 
 /*
  * The maximum number of pages to writeout in a single bdflush/kupdate
@@ -369,6 +370,12 @@
 		.for_kupdate	= 1,
 	};
 
+	if (test_suspend_state(SUSPEND_DISABLE_SYNCING)) {
+		start_jif = jiffies;
+		next_jif = start_jif + (dirty_writeback_centisecs * HZ) / 100;
+		goto out;
+	}
+
 	sync_supers();
 
 	get_writeback_state(&wbs);
@@ -389,6 +396,8 @@
 		}
 		nr_to_write -= MAX_WRITEBACK_PAGES - wbc.nr_to_write;
 	}
+
+out:
 	if (time_before(next_jif, jiffies + HZ))
 		next_jif = jiffies + HZ;
 	if (dirty_writeback_centisecs)
#140 lore raw

Suspend 2 merge: 21/51: Refrigerator upgrade.

In reply to Nigel Cunningham

Here's the suspend2 version of the process refrigerator. We do things in three steps:

1. Freeze userspace threads (p->mm != NULL) that don't have PF_SYNCTHREAD. This should stop new I/O being submitted.
2. Let data get synced to disk and run our own sys_sync just in case no one else was. PF_SYNCTHREAD is given to processes when they begin a sys_sync (or sibling) and removed when they exit the call, so no sync operations were hung under step 1. After this we set the DISABLE_SYNCING flag to stop further syncs.
3. Since kernel threads that don't have PF_NOFREEZE.

Included in this patch is a new try_to_freeze() macro Andrew M suggested a while back. The refrigerator declarations are put in sched.h to save extra includes of suspend.h.

Changes to keep swsusp working are included.

Note that you can also thaw just the kernel threads; this allows syncing while eating memory.

arch/arm/kernel/signal.c +1 -4
diff -ruN 582-refrigerator-old/arch/arm/kernel/signal.c 582-refrigerator-new/arch/arm/kernel/signal.c
@@ -12,7 +12,6 @@
 #include <linux/signal.h>
 #include <linux/ptrace.h>
 #include <linux/personality.h>
-#include <linux/suspend.h>
 
 #include <asm/cacheflush.h>
 #include <asm/ucontext.h>
@@ -689,10 +688,8 @@
 	if (!user_mode(regs))
 		return 0;
 
-	if (current->flags & PF_FREEZE) {
-		refrigerator(0);
+	if (try_to_freeze(0))
 		goto no_signal;
-	}
 
 	if (current->ptrace & PT_SINGLESTEP)
 		ptrace_cancel_bpt(current);
arch/i386/kernel/io_apic.c +1 -0
diff -ruN 582-refrigerator-old/arch/i386/kernel/io_apic.c 582-refrigerator-new/arch/i386/kernel/io_apic.c
@@ -575,6 +575,7 @@
 	for ( ; ; ) {
 		set_current_state(TASK_INTERRUPTIBLE);
 		time_remaining = schedule_timeout(time_remaining);
+		try_to_freeze(PF_FREEZE);
 		if (time_after(jiffies,
 				prev_balance_time+balanced_irq_interval)) {
 			do_irq_balance();
arch/i386/kernel/signal.c +1 -4
diff -ruN 582-refrigerator-old/arch/i386/kernel/signal.c 582-refrigerator-new/arch/i386/kernel/signal.c
@@ -18,7 +18,6 @@
 #include <linux/unistd.h>
 #include <linux/stddef.h>
 #include <linux/personality.h>
-#include <linux/suspend.h>
 #include <linux/ptrace.h>
 #include <linux/elf.h>
 #include <asm/processor.h>
@@ -596,10 +595,8 @@
 		return 1;
 #endif
 
-	if (current->flags & PF_FREEZE) {
-		refrigerator(0);
+	if (try_to_freeze(PF_FREEZE) && !signal_pending(current))
 		goto no_signal;
-	}
 
 	if (!oldset)
 		oldset = &current->blocked;
arch/mips/kernel/irixsig.c +1 -4
diff -ruN 582-refrigerator-old/arch/mips/kernel/irixsig.c 582-refrigerator-new/arch/mips/kernel/irixsig.c
@@ -13,7 +13,6 @@
 #include <linux/smp_lock.h>
 #include <linux/time.h>
 #include <linux/ptrace.h>
-#include <linux/suspend.h>
 
 #include <asm/ptrace.h>
 #include <asm/uaccess.h>
@@ -182,10 +181,8 @@
 	if (!user_mode(regs))
 		return 1;
 
-	if (current->flags & PF_FREEZE) {
-		refrigerator(0);
+	if (try_to_freeze(0))
 		goto no_signal;
-	}
 
 	if (!oldset)
 		oldset = &current->blocked;
arch/mips/kernel/signal32.c +1 -4
diff -ruN 582-refrigerator-old/arch/mips/kernel/signal32.c 582-refrigerator-new/arch/mips/kernel/signal32.c
@@ -18,7 +18,6 @@
 #include <linux/wait.h>
 #include <linux/ptrace.h>
 #include <linux/compat.h>
-#include <linux/suspend.h>
 #include <linux/bitops.h>
 
 #include <asm/asm.h>
@@ -700,10 +699,8 @@
 	if (!user_mode(regs))
 		return 1;
 
-	if (current->flags & PF_FREEZE) {
-		refrigerator(0);
+	if (try_to_freeze(0))
 		goto no_signal;
-	}
 
 	if (!oldset)
 		oldset = &current->blocked;
arch/mips/kernel/signal.c +1 -4
diff -ruN 582-refrigerator-old/arch/mips/kernel/signal.c 582-refrigerator-new/arch/mips/kernel/signal.c
@@ -18,7 +18,6 @@
 #include <linux/errno.h>
 #include <linux/wait.h>
 #include <linux/ptrace.h>
-#include <linux/suspend.h>
 #include <linux/unistd.h>
 #include <linux/bitops.h>
 
@@ -551,10 +550,8 @@
 	if (!user_mode(regs))
 		return 1;
 
-	if (current->flags & PF_FREEZE) {
-		refrigerator(0);
+	if (try_to_freeze(0))
 		goto no_signal;
-	}
 
 	if (!oldset)
 		oldset = &current->blocked;
arch/sh/kernel/signal.c +1 -4
diff -ruN 582-refrigerator-old/arch/sh/kernel/signal.c 582-refrigerator-new/arch/sh/kernel/signal.c
@@ -24,7 +24,6 @@
 #include <linux/tty.h>
 #include <linux/personality.h>
 #include <linux/binfmts.h>
-#include <linux/suspend.h>
 
 #include <asm/ucontext.h>
 #include <asm/uaccess.h>
@@ -579,10 +578,8 @@
 	if (!user_mode(regs))
 		return 1;
 
-	if (current->flags & PF_FREEZE) {
-		refrigerator(0);
+	if (try_to_freeze(0))
 		goto no_signal;
-	}
 
 	if (!oldset)
 		oldset = &current->blocked;
arch/sh64/kernel/signal.c +1 -3
diff -ruN 582-refrigerator-old/arch/sh64/kernel/signal.c 582-refrigerator-new/arch/sh64/kernel/signal.c
@@ -701,10 +701,8 @@
 	if (!user_mode(regs))
 		return 1;
 
-	if (current->flags & PF_FREEZE) {
-		refrigerator(0);
+	if (try_to_freeze(0))
 		goto no_signal;
-		}
 
 	if (!oldset)
 		oldset = &current->blocked;
arch/x86_64/kernel/signal.c +1 -4
diff -ruN 582-refrigerator-old/arch/x86_64/kernel/signal.c 582-refrigerator-new/arch/x86_64/kernel/signal.c
@@ -24,7 +24,6 @@
 #include <linux/stddef.h>
 #include <linux/personality.h>
 #include <linux/compiler.h>
-#include <linux/suspend.h>
 #include <asm/ucontext.h>
 #include <asm/uaccess.h>
 #include <asm/i387.h>
@@ -417,10 +416,8 @@
 		return 1;
 	} 	
 
-	if (current->flags & PF_FREEZE) {
-		refrigerator(0);
+	if (try_to_freeze(0))
 		goto no_signal;
-	}
 
 	if (!oldset)
 		oldset = &current->blocked;
drivers/ieee1394/ieee1394_core.c +8 -7
diff -ruN 582-refrigerator-old/drivers/ieee1394/ieee1394_core.c 582-refrigerator-new/drivers/ieee1394/ieee1394_core.c
@@ -32,7 +32,6 @@
 #include <linux/bitops.h>
 #include <linux/kdev_t.h>
 #include <linux/skbuff.h>
-#include <linux/suspend.h>
 
 #include <asm/byteorder.h>
 #include <asm/semaphore.h>
@@ -1030,15 +1029,17 @@
 
 	daemonize("khpsbpkt");
 
-	while (!down_interruptible(&khpsbpkt_sig)) {
-		if (khpsbpkt_kill)
+	while (1) {
+		if (down_interruptible(&khpsbpkt_sig)) {
+			if (try_to_freeze(0))
+				continue;
+			printk("khpsbpkt: received unexpected signal?!\n" );
 			break;
-
-		if (current->flags & PF_FREEZE) {
-			refrigerator(0);
-			continue;
 		}
 
+		if (khpsbpkt_kill)
+			break;
+
 		while ((skb = skb_dequeue(&hpsbpkt_queue)) != NULL) {
 			packet = (struct hpsb_packet *)skb->data;
 
drivers/ieee1394/nodemgr.c +3 -4
diff -ruN 582-refrigerator-old/drivers/ieee1394/nodemgr.c 582-refrigerator-new/drivers/ieee1394/nodemgr.c
@@ -19,7 +19,6 @@
 #include <linux/delay.h>
 #include <linux/pci.h>
 #include <linux/moduleparam.h>
-#include <linux/suspend.h>
 #include <asm/atomic.h>
 
 #include "ieee1394_types.h"
@@ -1480,10 +1479,8 @@
 
 		if (down_interruptible(&hi->reset_sem) ||
 		    down_interruptible(&nodemgr_serialize)) {
-			if (current->flags & PF_FREEZE) {
-				refrigerator(0);
+			if (try_to_freeze(PF_FREEZE))
 				continue;
-			}
 			printk("NodeMgr: received unexpected signal?!\n" );
 			break;
 		}
@@ -1498,6 +1495,8 @@
 		for (i = 0; i < 4 ; i++) {
 			set_current_state(TASK_INTERRUPTIBLE);
 			if (msleep_interruptible(63)) {
+				if (try_to_freeze(PF_FREEZE))
+					continue;
 				up(&nodemgr_serialize);
 				goto caught_signal;
 			}
drivers/input/serio/serio.c +1 -3
diff -ruN 582-refrigerator-old/drivers/input/serio/serio.c 582-refrigerator-new/drivers/input/serio/serio.c
@@ -34,7 +34,6 @@
 #include <linux/completion.h>
 #include <linux/sched.h>
 #include <linux/smp_lock.h>
-#include <linux/suspend.h>
 #include <linux/slab.h>
 
 MODULE_AUTHOR("Vojtech Pavlik <[email protected]>");
@@ -225,8 +224,7 @@
 	do {
 		serio_handle_events();
 		wait_event_interruptible(serio_wait, !list_empty(&serio_event_list));
-		if (current->flags & PF_FREEZE)
-			refrigerator(PF_FREEZE);
+		try_to_freeze(PF_FREEZE);
 	} while (!signal_pending(current));
 
 	printk(KERN_DEBUG "serio: kseriod exiting\n");
drivers/md/md.c +1 -3
diff -ruN 582-refrigerator-old/drivers/md/md.c 582-refrigerator-new/drivers/md/md.c
@@ -36,7 +36,6 @@
 #include <linux/sysctl.h>
 #include <linux/devfs_fs_kernel.h>
 #include <linux/buffer_head.h> /* for invalidate_bdev */
-#include <linux/suspend.h>
 
 #include <linux/init.h>
 
@@ -2761,6 +2760,7 @@
 	 */
 
 	daemonize(thread->name, mdname(thread->mddev));
+	current->flags |= PF_NOFREEZE;
 
 	current->exit_signal = SIGCHLD;
 	allow_signal(SIGKILL);
@@ -2785,8 +2785,6 @@
 
 		wait_event_interruptible(thread->wqueue,
 					 test_bit(THREAD_WAKEUP, &thread->flags));
-		if (current->flags & PF_FREEZE)
-			refrigerator(PF_FREEZE);
 
 		clear_bit(THREAD_WAKEUP, &thread->flags);
 
drivers/media/video/msp3400.c +5 -2
diff -ruN 582-refrigerator-old/drivers/media/video/msp3400.c 582-refrigerator-new/drivers/media/video/msp3400.c
@@ -741,6 +741,7 @@
 {
 	DECLARE_WAITQUEUE(wait, current);
 
+again:
 	add_wait_queue(&msp->wq, &wait);
 	if (!kthread_should_stop()) {
 		if (timeout < 0) {
@@ -756,9 +757,11 @@
 #endif
 		}
 	}
-	if (current->flags & PF_FREEZE)
-		refrigerator(PF_FREEZE);
 	remove_wait_queue(&msp->wq, &wait);
+
+	if (try_to_freeze(PF_FREEZE))
+		goto again;
+
 	return msp->restart;
 }
 
drivers/media/video/tvaudio.c +1 -0
diff -ruN 582-refrigerator-old/drivers/media/video/tvaudio.c 582-refrigerator-new/drivers/media/video/tvaudio.c
@@ -285,6 +285,7 @@
 			schedule();
 		}
 		remove_wait_queue(&chip->wq, &wait);
+		try_to_freeze(PF_FREEZE);
 		if (chip->done || signal_pending(current))
 			break;
 		dprintk("%s: thread wakeup\n", i2c_clientname(&chip->c));
drivers/mtd/mtd_blkdevs.c +2 -0
diff -ruN 582-refrigerator-old/drivers/mtd/mtd_blkdevs.c 582-refrigerator-new/drivers/mtd/mtd_blkdevs.c
@@ -113,6 +113,8 @@
 			schedule();
 			remove_wait_queue(&tr->blkcore_priv->thread_wq, &wait);
 
+			try_to_freeze(PF_FREEZE);
+
 			spin_lock_irq(rq->queue_lock);
 
 			continue;
drivers/net/8139too.c +1 -3
diff -ruN 582-refrigerator-old/drivers/net/8139too.c 582-refrigerator-new/drivers/net/8139too.c
@@ -108,7 +108,6 @@
 #include <linux/mii.h>
 #include <linux/completion.h>
 #include <linux/crc32.h>
-#include <linux/suspend.h>
 #include <asm/io.h>
 #include <asm/uaccess.h>
 #include <asm/irq.h>
@@ -1624,8 +1623,7 @@
 		do {
 			timeout = interruptible_sleep_on_timeout (&tp->thr_wait, timeout);
 			/* make swsusp happy with our thread */
-			if (current->flags & PF_FREEZE)
-				refrigerator(PF_FREEZE);
+			try_to_freeze(PF_FREEZE);
 		} while (!signal_pending (current) && (timeout > 0));
 
 		if (signal_pending (current)) {
drivers/net/irda/sir_kthread.c +1 -5
diff -ruN 582-refrigerator-old/drivers/net/irda/sir_kthread.c 582-refrigerator-new/drivers/net/irda/sir_kthread.c
@@ -19,7 +19,6 @@
 #include <linux/smp_lock.h>
 #include <linux/completion.h>
 #include <linux/delay.h>
-#include <linux/suspend.h>
 
 #include <net/irda/irda.h>
 
@@ -113,6 +112,7 @@
 	DECLARE_WAITQUEUE(wait, current);
 
 	daemonize("kIrDAd");
+	current->flags |= PF_NOFREEZE;
 
 	irda_rq_queue.thread = current;
 
@@ -135,10 +135,6 @@
 			__set_task_state(current, TASK_RUNNING);
 		remove_wait_queue(&irda_rq_queue.kick, &wait);
 
-		/* make swsusp happy with our thread */
-		if (current->flags & PF_FREEZE)
-			refrigerator(PF_FREEZE);
-
 		run_irda_queue();
 	}
 
drivers/net/irda/stir4200.c +0 -1
diff -ruN 582-refrigerator-old/drivers/net/irda/stir4200.c 582-refrigerator-new/drivers/net/irda/stir4200.c
@@ -46,7 +46,6 @@
 #include <linux/time.h>
 #include <linux/skbuff.h>
 #include <linux/netdevice.h>
-#include <linux/suspend.h>
 #include <linux/slab.h>
 #include <linux/delay.h>
 #include <linux/usb.h>
drivers/net/wireless/airo.c +1 -3
diff -ruN 582-refrigerator-old/drivers/net/wireless/airo.c 582-refrigerator-new/drivers/net/wireless/airo.c
@@ -33,7 +33,6 @@
 #include <linux/string.h>
 #include <linux/timer.h>
 #include <linux/interrupt.h>
-#include <linux/suspend.h>
 #include <linux/in.h>
 #include <linux/bitops.h>
 #include <asm/io.h>
@@ -2918,8 +2917,7 @@
 			flush_signals(current);
 
 		/* make swsusp happy with our thread */
-		if (current->flags & PF_FREEZE)
-			refrigerator(PF_FREEZE);
+		try_to_freeze(PF_FREEZE);
 
 		if (test_bit(JOB_DIE, &ai->flags))
 			break;
drivers/pcmcia/cs.c +1 -3
diff -ruN 582-refrigerator-old/drivers/pcmcia/cs.c 582-refrigerator-new/drivers/pcmcia/cs.c
@@ -48,7 +48,6 @@
 #include <linux/pm.h>
 #include <linux/pci.h>
 #include <linux/device.h>
-#include <linux/suspend.h>
 #include <asm/system.h>
 #include <asm/irq.h>
 
@@ -718,8 +717,7 @@
 		}
 
 		schedule();
-		if (current->flags & PF_FREEZE)
-			refrigerator(PF_FREEZE);
+		try_to_freeze(PF_FREEZE);
 
 		if (!skt->thread)
 			break;
drivers/pcmcia/socket_sysfs.c +0 -1
diff -ruN 582-refrigerator-old/drivers/pcmcia/socket_sysfs.c 582-refrigerator-new/drivers/pcmcia/socket_sysfs.c
@@ -25,7 +25,6 @@
 #include <linux/pm.h>
 #include <linux/pci.h>
 #include <linux/device.h>
-#include <linux/suspend.h>
 #include <asm/system.h>
 #include <asm/irq.h>
 
drivers/pnp/pnpbios/core.c +4 -0
diff -ruN 582-refrigerator-old/drivers/pnp/pnpbios/core.c 582-refrigerator-new/drivers/pnp/pnpbios/core.c
@@ -179,6 +179,10 @@
 		 * Poll every 2 seconds
 		 */
 		msleep_interruptible(2000);
+
+		if(current->flags & PF_FREEZE)
+			refrigerator(PF_FREEZE);
+
 		if(signal_pending(current))
 			break;
 
drivers/scsi/libata-core.c +0 -1
diff -ruN 582-refrigerator-old/drivers/scsi/libata-core.c 582-refrigerator-new/drivers/scsi/libata-core.c
@@ -35,7 +35,6 @@
 #include <linux/timer.h>
 #include <linux/interrupt.h>
 #include <linux/completion.h>
-#include <linux/suspend.h>
 #include <linux/workqueue.h>
 #include <scsi/scsi.h>
 #include "scsi.h"
drivers/usb/core/hub.c +1 -3
diff -ruN 582-refrigerator-old/drivers/usb/core/hub.c 582-refrigerator-new/drivers/usb/core/hub.c
@@ -26,7 +26,6 @@
 #include <linux/ioctl.h>
 #include <linux/usb.h>
 #include <linux/usbdevice_fs.h>
-#include <linux/suspend.h>
 
 #include <asm/semaphore.h>
 #include <asm/uaccess.h>
@@ -2713,8 +2712,7 @@
 	do {
 		hub_events();
 		wait_event_interruptible(khubd_wait, !list_empty(&hub_event_list)); 
-		if (current->flags & PF_FREEZE)
-			refrigerator(PF_FREEZE);
+		try_to_freeze(PF_FREEZE);
 	} while (!signal_pending(current));
 
 	pr_debug ("%s: khubd exiting\n", usbcore_name);
drivers/w1/w1.c +2 -5
diff -ruN 582-refrigerator-old/drivers/w1/w1.c 582-refrigerator-new/drivers/w1/w1.c
@@ -32,7 +32,6 @@
 #include <linux/device.h>
 #include <linux/slab.h>
 #include <linux/sched.h>
-#include <linux/suspend.h>
 
 #include "w1.h"
 #include "w1_io.h"
@@ -628,8 +627,7 @@
 		timeout = w1_timeout*HZ;
 		do {
 			timeout = interruptible_sleep_on_timeout(&w1_control_wait, timeout);
-			if (current->flags & PF_FREEZE)
-				refrigerator(PF_FREEZE);
+			try_to_freeze(PF_FREEZE);
 		} while (!signal_pending(current) && (timeout > 0));
 
 		if (signal_pending(current))
@@ -701,8 +699,7 @@
 		timeout = w1_timeout*HZ;
 		do {
 			timeout = interruptible_sleep_on_timeout(&dev->kwait, timeout);
-			if (current->flags & PF_FREEZE)
-				refrigerator(PF_FREEZE);
+			try_to_freeze(PF_FREEZE);
 		} while (!signal_pending(current) && (timeout > 0));
 
 		if (signal_pending(current))
fs/afs/kafsasyncd.c +2 -0
diff -ruN 582-refrigerator-old/fs/afs/kafsasyncd.c 582-refrigerator-new/fs/afs/kafsasyncd.c
@@ -116,6 +116,8 @@
 		remove_wait_queue(&kafsasyncd_sleepq, &myself);
 		set_current_state(TASK_RUNNING);
 
+		try_to_freeze(PF_FREEZE);
+
 		/* discard pending signals */
 		afs_discard_my_signals();
 
fs/afs/kafstimod.c +2 -0
diff -ruN 582-refrigerator-old/fs/afs/kafstimod.c 582-refrigerator-new/fs/afs/kafstimod.c
@@ -91,6 +91,8 @@
 			complete_and_exit(&kafstimod_dead, 0);
 		}
 
+		try_to_freeze(PF_FREEZE);
+
 		/* discard pending signals */
 		afs_discard_my_signals();
 
fs/buffer.c +54 -2

145 lines not on this page · raw message

fs/jbd/journal.c +1 -0
diff -ruN 582-refrigerator-old/fs/jbd/journal.c 582-refrigerator-new/fs/jbd/journal.c
@@ -130,6 +130,7 @@
 	current_journal = journal;
 
 	daemonize("kjournald");
+	current->flags |= PF_SYNCTHREAD;
 
 	/* Set up an interval timer which can be used to trigger a
            commit wakeup after the commit interval expires */
fs/jffs/intrep.c +4 -0
diff -ruN 582-refrigerator-old/fs/jffs/intrep.c 582-refrigerator-new/fs/jffs/intrep.c
@@ -3338,6 +3338,7 @@
 	D1(int i = 1);
 
 	daemonize("jffs_gcd");
+	current->flags |= PF_SYNCTHREAD;
 
 	c->gc_task = current;
 
@@ -3373,6 +3374,9 @@
 			siginfo_t info;
 			unsigned long signr = 0;
 
+			if (try_to_freeze(PF_FREEZE))
+				continue;
+
 			spin_lock_irq(&current->sighand->siglock);
 			signr = dequeue_signal(current, &current->blocked, &info);
 			spin_unlock_irq(&current->sighand->siglock);
fs/jffs2/background.c +1 -6
diff -ruN 582-refrigerator-old/fs/jffs2/background.c 582-refrigerator-new/fs/jffs2/background.c
@@ -15,7 +15,6 @@
 #include <linux/jffs2.h>
 #include <linux/mtd/mtd.h>
 #include <linux/completion.h>
-#include <linux/suspend.h>
 #include "nodelist.h"
 
 
@@ -93,12 +92,8 @@
 			schedule();
 		}
 
-		if (current->flags & PF_FREEZE) {
-			refrigerator(0);
-			/* refrigerator() should recalc sigpending for us
-			   but doesn't. No matter - allow_signal() will. */
+		if (try_to_freeze(0))
 			continue;
-		}
 
 		cond_resched();
 
fs/jfs/jfs_logmgr.c +1 -0
diff -ruN 582-refrigerator-old/fs/jfs/jfs_logmgr.c 582-refrigerator-new/fs/jfs/jfs_logmgr.c
@@ -2316,6 +2316,7 @@
 	struct lbuf *bp;
 
 	daemonize("jfsIO");
+	current->flags |= PF_SYNCTHREAD;
 
 	complete(&jfsIOwait);
 
fs/jfs/jfs_txnmgr.c +1 -1
diff -ruN 582-refrigerator-old/fs/jfs/jfs_txnmgr.c 582-refrigerator-new/fs/jfs/jfs_txnmgr.c
@@ -47,7 +47,6 @@
 #include <linux/vmalloc.h>
 #include <linux/smp_lock.h>
 #include <linux/completion.h>
-#include <linux/suspend.h>
 #include <linux/module.h>
 #include <linux/moduleparam.h>
 #include "jfs_incore.h"
@@ -2727,6 +2726,7 @@
 	struct jfs_sb_info *sbi;
 
 	daemonize("jfsCommit");
+	current->flags |= PF_SYNCTHREAD;
 
 	complete(&jfsIOwait);
 
fs/lockd/clntlock.c +2 -0
diff -ruN 582-refrigerator-old/fs/lockd/clntlock.c 582-refrigerator-new/fs/lockd/clntlock.c
@@ -200,6 +200,7 @@
 	struct inode *inode;
 
 	daemonize("%s-reclaim", host->h_name);
+	current->flags |= PF_SYNCTHREAD;
 	allow_signal(SIGKILL);
 
 	/* This one ensures that our parent doesn't terminate while the
@@ -222,6 +223,7 @@
 
 		fl->fl_u.nfs_fl.flags &= ~NFS_LCK_RECLAIM;
 		nlmclnt_reclaim(host, fl);
+		try_to_freeze(PF_FREEZE);
 		if (signalled())
 			break;
 		goto restart;
fs/lockd/clntproc.c +1 -0
diff -ruN 582-refrigerator-old/fs/lockd/clntproc.c 582-refrigerator-new/fs/lockd/clntproc.c
@@ -310,6 +310,7 @@
 	prepare_to_wait(queue, &wait, TASK_INTERRUPTIBLE);
 	if (!signalled ()) {
 		schedule_timeout(NLMCLNT_GRACE_WAIT);
+		try_to_freeze(PF_FREEZE);
 		if (!signalled ())
 			status = 0;
 	}
fs/lockd/svc.c +3 -0
diff -ruN 582-refrigerator-old/fs/lockd/svc.c 582-refrigerator-new/fs/lockd/svc.c
@@ -112,6 +112,7 @@
 	up(&lockd_start);
 
 	daemonize("lockd");
+	current->flags |= PF_SYNCTHREAD;
 
 	/* Process request with signals blocked, but allow SIGKILL.  */
 	allow_signal(SIGKILL);
@@ -135,6 +136,8 @@
 	while ((nlmsvc_users || !signalled()) && nlmsvc_pid == current->pid) {
 		long timeout = MAX_SCHEDULE_TIMEOUT;
 
+		try_to_freeze(PF_SYNCTHREAD);
+
 		if (signalled()) {
 			flush_signals(current);
 			if (nlmsvc_ops) {
fs/nfsd/nfssvc.c +1 -0
diff -ruN 582-refrigerator-old/fs/nfsd/nfssvc.c 582-refrigerator-new/fs/nfsd/nfssvc.c
@@ -180,6 +180,7 @@
 	/* Lock module and set up kernel thread */
 	lock_kernel();
 	daemonize("nfsd");
+	current->flags |= PF_SYNCTHREAD;
 
 	/* After daemonize() this kernel thread shares current->fs
 	 * with the init process. We need to create files with a
fs/reiserfs/journal.c +0 -1
diff -ruN 582-refrigerator-old/fs/reiserfs/journal.c 582-refrigerator-new/fs/reiserfs/journal.c
@@ -50,7 +50,6 @@
 #include <linux/stat.h>
 #include <linux/string.h>
 #include <linux/smp_lock.h>
-#include <linux/suspend.h>
 #include <linux/buffer_head.h>
 #include <linux/workqueue.h>
 #include <linux/writeback.h>
fs/xfs/linux-2.6/xfs_buf.c +2 -5
diff -ruN 582-refrigerator-old/fs/xfs/linux-2.6/xfs_buf.c 582-refrigerator-new/fs/xfs/linux-2.6/xfs_buf.c
@@ -51,7 +51,6 @@
 #include <linux/sysctl.h>
 #include <linux/proc_fs.h>
 #include <linux/workqueue.h>
-#include <linux/suspend.h>
 #include <linux/percpu.h>
 
 #include "xfs_linux.h"
@@ -1657,7 +1656,7 @@
 
 	/*  Set up the thread  */
 	daemonize("xfsbufd");
-	current->flags |= PF_MEMALLOC;
+	current->flags |= PF_MEMALLOC | PF_SYNCTHREAD;
 
 	pagebuf_daemon_task = current;
 	pagebuf_daemon_active = 1;
@@ -1665,9 +1664,7 @@
 
 	INIT_LIST_HEAD(&tmp);
 	do {
-		/* swsusp */
-		if (current->flags & PF_FREEZE)
-			refrigerator(PF_FREEZE);
+		try_to_freeze(PF_FREEZE);
 
 		set_current_state(TASK_INTERRUPTIBLE);
 		schedule_timeout((xfs_buf_timer_centisecs * HZ) / 100);
fs/xfs/linux-2.6/xfs_super.c +2 -3
diff -ruN 582-refrigerator-old/fs/xfs/linux-2.6/xfs_super.c 582-refrigerator-new/fs/xfs/linux-2.6/xfs_super.c
@@ -71,7 +71,6 @@
 #include <linux/namei.h>
 #include <linux/init.h>
 #include <linux/mount.h>
-#include <linux/suspend.h>
 #include <linux/writeback.h>
 
 STATIC struct quotactl_ops linvfs_qops;
@@ -472,6 +471,7 @@
 	struct vfs_sync_work	*work, *n;
 
 	daemonize("xfssyncd");
+	current->flags |= PF_SYNCTHREAD;
 
 	vfsp->vfs_sync_work.w_vfs = vfsp;
 	vfsp->vfs_sync_work.w_syncer = vfs_sync_worker;
@@ -485,8 +485,7 @@
 		set_current_state(TASK_INTERRUPTIBLE);
 		timeleft = schedule_timeout(timeleft);
 		/* swsusp */
-		if (current->flags & PF_FREEZE)
-			refrigerator(PF_FREEZE);
+		try_to_freeze(PF_FREEZE);
 		if (vfsp->vfs_flag & VFS_UMOUNT)
 			break;
 
include/linux/sched.h +35 -1
diff -ruN 582-refrigerator-old/include/linux/sched.h 582-refrigerator-new/include/linux/sched.h
@@ -19,6 +19,7 @@
 #include <asm/page.h>
 #include <asm/ptrace.h>
 #include <asm/mmu.h>
+#include <asm/current.h>
 
 #include <linux/smp.h>
 #include <linux/sem.h>
@@ -701,7 +702,7 @@
 #define PF_MEMDIE	0x00001000	/* Killed for out-of-memory */
 #define PF_FLUSHER	0x00002000	/* responsible for disk writeback */
 
-#define PF_FREEZE	0x00004000	/* this task should be frozen for suspend */
+#define PF_FREEZE	0x00004000	/* this task is being frozen for suspend now */
 #define PF_NOFREEZE	0x00008000	/* this thread should not be frozen */
 #define PF_FROZEN	0x00010000	/* frozen for system suspend */
 #define PF_FSTRANS	0x00020000	/* inside a filesystem transaction */
@@ -710,6 +711,8 @@
 #define PF_LESS_THROTTLE 0x00100000	/* Throttle me less: I clean memory */
 #define PF_SYNCWRITE	0x00200000	/* I am doing a sync write */
 #define PF_BORROWED_MM	0x00400000	/* I am a kthread doing use_mm */
+#define PF_SYNCTHREAD	0x00800000	/* this thread can start activity during the 
+					   early part of freezing processes */
 
 #ifdef CONFIG_SMP
 extern int set_cpus_allowed(task_t *p, cpumask_t new_mask);
@@ -720,6 +723,29 @@
 }
 #endif
 
+/* try_to_freeze
+ *
+ * Checks whether we need to enter the refrigerator
+ * and returns 1 if we did so.
+ */
+#ifdef CONFIG_PM
+extern void refrigerator(unsigned long);
+
+static inline int try_to_freeze(unsigned long refrigerator_flags)
+{
+	if (unlikely(current->flags & PF_FREEZE)) {
+		refrigerator(refrigerator_flags);
+		return 1;
+	} else
+		return 0;
+}
+#else
+static inline int try_to_freeze(unsigned long refrigerator_flags)
+{
+	return 0;
+}
+#endif
+
 extern unsigned long long sched_clock(void);
 
 /* sched_exec is called by processes performing an exec */
@@ -1119,6 +1145,14 @@
 
 #endif
 
+#ifdef CONFIG_PM
+extern void refrigerator(unsigned long);
+extern unsigned int suspend_task;
+#else
+#define refrigerator(a)			do { } while(0)
+#define suspend_task (0)
+#endif
+
 #endif /* __KERNEL__ */
 
 #endif
kernel/exit.c +3 -0
diff -ruN 582-refrigerator-old/kernel/exit.c 582-refrigerator-new/kernel/exit.c
@@ -15,6 +15,7 @@
 #include <linux/module.h>
 #include <linux/completion.h>
 #include <linux/personality.h>
+#include <linux/suspend.h>
 #include <linux/tty.h>
 #include <linux/namespace.h>
 #include <linux/key.h>
@@ -802,6 +803,8 @@
 		panic("Attempted to kill init!");
 	if (tsk->io_context)
 		exit_io_context();
+	if (unlikely(test_suspend_state(SUSPEND_FREEZER_ON)))
+		refrigerator(0);
 	tsk->flags |= PF_EXITING;
 	del_timer_sync(&tsk->real_timer);
 
kernel/fork.c +5 -0
diff -ruN 582-refrigerator-old/kernel/fork.c 582-refrigerator-new/kernel/fork.c
@@ -39,6 +39,7 @@
 #include <linux/audit.h>
 #include <linux/profile.h>
 #include <linux/rmap.h>
+#include <linux/suspend.h>
 
 #include <asm/pgtable.h>
 #include <asm/pgalloc.h>
@@ -1125,6 +1126,10 @@
 	int trace = 0;
 	long pid = alloc_pidmap();
 
+
+	if (unlikely(test_suspend_state(SUSPEND_FREEZER_ON)))
+		refrigerator(0);
+
 	if (pid < 0)
 		return -EAGAIN;
 	if (unlikely(current->ptrace)) {
kernel/power/disk.c +3 -3
diff -ruN 582-refrigerator-old/kernel/power/disk.c 582-refrigerator-new/kernel/power/disk.c
@@ -116,7 +116,7 @@
 	device_resume();
 	platform_finish();
 	enable_nonboot_cpus();
-	thaw_processes();
+	thaw_processes(FREEZER_ALL_THREADS);
 	pm_restore_console();
 }
 
@@ -128,7 +128,7 @@
 	pm_prepare_console();
 
 	sys_sync();
-	if (freeze_processes()) {
+	if (freeze_processes(1)) {
 		error = -EBUSY;
 		goto Thaw;
 	}
@@ -152,7 +152,7 @@
 	platform_finish();
  Thaw:
 	enable_nonboot_cpus();
-	thaw_processes();
+	thaw_processes(FREEZER_ALL_THREADS);
 	pm_restore_console();
 	return error;
 }
kernel/power/main.c +3 -3
diff -ruN 582-refrigerator-old/kernel/power/main.c 582-refrigerator-new/kernel/power/main.c
@@ -55,7 +55,7 @@
 
 	pm_prepare_console();
 
-	if (freeze_processes()) {
+	if (freeze_processes(1)) {
 		error = -EAGAIN;
 		goto Thaw;
 	}
@@ -72,7 +72,7 @@
 	if (pm_ops->finish)
 		pm_ops->finish(state);
  Thaw:
-	thaw_processes();
+	thaw_processes(FREEZER_ALL_THREADS);
 	pm_restore_console();
 	return error;
 }
@@ -107,7 +107,7 @@
 	device_resume();
 	if (pm_ops && pm_ops->finish)
 		pm_ops->finish(state);
-	thaw_processes();
+	thaw_processes(FREEZER_ALL_THREADS);
 	pm_restore_console();
 }
 
kernel/power/power.h +2 -2
diff -ruN 582-refrigerator-old/kernel/power/power.h 582-refrigerator-new/kernel/power/power.h
@@ -45,8 +45,8 @@
 
 extern struct subsystem power_subsys;
 
-extern int freeze_processes(void);
-extern void thaw_processes(void);
+extern int freeze_processes(int no_progress);
+extern void thaw_processes(int which_threads);
 
 extern int pm_prepare_console(void);
 extern void pm_restore_console(void);
kernel/power/process.c +473 -73

594 lines not on this page · raw message

kernel/signal.c +3 -2
diff -ruN 582-refrigerator-old/kernel/signal.c 582-refrigerator-new/kernel/signal.c
@@ -2178,10 +2178,11 @@
 			sigandsets(&current->blocked, &current->blocked, &these);
 			recalc_sigpending();
 			spin_unlock_irq(&current->sighand->siglock);
-
 			current->state = TASK_INTERRUPTIBLE;
 			timeout = schedule_timeout(timeout);
-
+			if (current->flags & PF_FREEZE) {
+				refrigerator(PF_FREEZE);
+			}
 			spin_lock_irq(&current->sighand->siglock);
 			sig = dequeue_signal(current, &these, &info);
 			current->blocked = current->real_blocked;
mm/pdflush.c +2 -4
diff -ruN 582-refrigerator-old/mm/pdflush.c 582-refrigerator-new/mm/pdflush.c
@@ -17,7 +17,6 @@
 #include <linux/gfp.h>
 #include <linux/init.h>
 #include <linux/module.h>
-#include <linux/suspend.h>
 #include <linux/fs.h>		// Needed by writeback.h
 #include <linux/writeback.h>	// Prototypes pdflush_operation()
 #include <linux/kthread.h>
@@ -90,7 +89,7 @@
 
 static int __pdflush(struct pdflush_work *my_work)
 {
-	current->flags |= PF_FLUSHER;
+	current->flags |= (PF_FLUSHER | PF_SYNCTHREAD);
 	my_work->fn = NULL;
 	my_work->who = current;
 	INIT_LIST_HEAD(&my_work->list);
@@ -106,8 +105,7 @@
 		spin_unlock_irq(&pdflush_lock);
 
 		schedule();
-		if (current->flags & PF_FREEZE) {
-			refrigerator(PF_FREEZE);
+		if (try_to_freeze(PF_FREEZE)) {
 			spin_lock_irq(&pdflush_lock);
 			continue;
 		}
mm/vmscan.c +1 -3
diff -ruN 582-refrigerator-old/mm/vmscan.c 582-refrigerator-new/mm/vmscan.c
@@ -21,7 +21,6 @@
 #include <linux/highmem.h>
 #include <linux/file.h>
 #include <linux/writeback.h>
-#include <linux/suspend.h>
 #include <linux/blkdev.h>
 #include <linux/buffer_head.h>	/* for try_to_release_page(),
 					buffer_heads_over_limit */
@@ -1170,8 +1169,7 @@
 	tsk->flags |= PF_MEMALLOC|PF_KSWAPD;
 
 	for ( ; ; ) {
-		if (current->flags & PF_FREEZE)
-			refrigerator(PF_FREEZE);
+		try_to_freeze(PF_FREEZE);
 		prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
 		schedule();
 		finish_wait(&pgdat->kswapd_wait, &wait);
net/bluetooth/rfcomm/core.c +2 -0
diff -ruN 582-refrigerator-old/net/bluetooth/rfcomm/core.c 582-refrigerator-new/net/bluetooth/rfcomm/core.c
@@ -1726,6 +1726,8 @@
 			schedule();
 		}
 
+		try_to_freeze(PF_FREEZE);
+
 		/* Process stuff */
 		clear_bit(RFCOMM_SCHED_WAKEUP, &rfcomm_event);
 		rfcomm_process_sessions();
net/rxrpc/krxiod.c +2 -0
diff -ruN 582-refrigerator-old/net/rxrpc/krxiod.c 582-refrigerator-new/net/rxrpc/krxiod.c
@@ -138,6 +138,8 @@
 
 		_debug("### End Work");
 
+		try_to_freeze(PF_FREEZE);
+
                 /* discard pending signals */
 		rxrpc_discard_my_signals();
 
net/rxrpc/krxsecd.c +2 -0
diff -ruN 582-refrigerator-old/net/rxrpc/krxsecd.c 582-refrigerator-new/net/rxrpc/krxsecd.c
@@ -107,6 +107,8 @@
 
 		_debug("### End Inbound Calls");
 
+		try_to_freeze(PF_FREEZE);
+
                 /* discard pending signals */
 		rxrpc_discard_my_signals();
 
net/rxrpc/krxtimod.c +2 -0
diff -ruN 582-refrigerator-old/net/rxrpc/krxtimod.c 582-refrigerator-new/net/rxrpc/krxtimod.c
@@ -90,6 +90,8 @@
 			complete_and_exit(&krxtimod_dead, 0);
 		}
 
+		try_to_freeze(PF_FREEZE);
+
 		/* discard pending signals */
 		rxrpc_discard_my_signals();
 
net/sunrpc/sched.c +0 -1
diff -ruN 582-refrigerator-old/net/sunrpc/sched.c 582-refrigerator-new/net/sunrpc/sched.c
@@ -18,7 +18,6 @@
 #include <linux/smp.h>
 #include <linux/smp_lock.h>
 #include <linux/spinlock.h>
-#include <linux/suspend.h>
 
 #include <linux/sunrpc/clnt.h>
 #include <linux/sunrpc/xprt.h>
net/sunrpc/svcsock.c +2 -3
diff -ruN 582-refrigerator-old/net/sunrpc/svcsock.c 582-refrigerator-new/net/sunrpc/svcsock.c
@@ -31,7 +31,6 @@
 #include <linux/slab.h>
 #include <linux/netdevice.h>
 #include <linux/skbuff.h>
-#include <linux/suspend.h>
 #include <net/sock.h>
 #include <net/checksum.h>
 #include <net/ip.h>
@@ -1187,6 +1186,7 @@
 	arg->len = (pages-1)*PAGE_SIZE;
 	arg->tail[0].iov_len = 0;
 	
+	try_to_freeze(PF_FREEZE);
 	if (signalled())
 		return -EINTR;
 
@@ -1227,8 +1227,7 @@
 
 		schedule_timeout(timeout);
 
-		if (current->flags & PF_FREEZE)
-			refrigerator(PF_FREEZE);
+		try_to_freeze(PF_FREEZE);
 
 		spin_lock_bh(&serv->sv_lock);
 		remove_wait_queue(&rqstp->rq_wait, &wait);
#152 lore raw

Suspend 2 merge: 41/51: Ranges (extents).

In reply to Nigel Cunningham

This is the heart of our metadata storage.

The comments at the top of range.c say it all. Ranges are used to store the which pages are in which pageset. The swapwriter uses them to store which swap addresses are allocated and what block numbers on the swap devices those addresses map to (we can't swapon at resume time to find out).

kernel/power/range.c +784 -0
diff -ruN 831-range-old/kernel/power/range.c 831-range-new/kernel/power/range.c
@@ -0,0 +1,784 @@
+/* Suspend2 routines for manipulating ranges.
+ *
+ * (C) 2003-2004 Nigel Cunningham <[email protected]>
+ *
+ * Distributed under GPLv2.
+ * 
+ * These encapsulate the manipulation of ranges. I learnt after writing this
+ * code that ranges are more commonly called extents. They work like this:
+ *
+ * A lot of the data that suspend saves involves continguous ranges of memory
+ * or storage. Let's say that we're storing data on disk in blocks 1-32768 and
+ * 49152-49848 of a swap partition. Rather than recording 1, 2, 3... in arrays
+ * pointing to the locations, we simply use:
+ *
+ * struct range {
+ * 	unsigned long min;
+ * 	unsigned long max;
+ * 	struct range * next;
+ * }
+ *
+ * We can then store 1-32768 and 49152-49848 in 2 struct ranges, using 24 bytes
+ * instead of something like 133,860. This is of course inefficient where a range
+ * covers only one or two values, but the benefits gained by the much larger
+ * ranges more than outweight these instances.
+ *
+ * Whole pages are allocated to store ranges, with unused structs being chained
+ * together and linked into an unused_ranges list:
+ *
+ * struct range * unused_ranges; (just below).
+ *
+ * We can fit 341 ranges in a 4096 byte page (rangepage), with 4 bytes left over.
+ * These four bytes, referred to as the RangePageLink, are used to link the pages
+ * together. The RangePageLink is a pointer to the next page, or'd with the index
+ * number of the page.
+ *
+ * RangePages are stored in the header of the suspend image. For portability
+ * between suspend time and resume time, we 'relativise' the contents of each page
+ * before writing them to disk. That is, each .next and each RangePageLink is
+ * changed to point not to an absolute location, but to the relative location in
+ * the list of pages. This makes all the information valid and usable (after it
+ * has been absolutised again, of course) regardless of where it is reloaded to
+ * at resume time.
+ */
+
+#include <linux/kernel.h>
+#include <linux/module.h>
+#include <linux/suspend.h>
+#include <linux/mm.h>
+
+#include "pageflags.h"
+#include "suspend.h"
+
+struct range * unused_ranges = NULL;
+int nr_unused_ranges = 0;
+int max_ranges_used = 0;
+int num_range_pages = 0;
+static unsigned long ranges_allocated = 0;
+struct range * first_range_page = NULL, * last_range_page = NULL;
+
+/* Add_range_pages
+ *
+ * Allocates and initialises new pages for storing ranges.
+ * Returns 1 on failure to get a page.
+ * Otherwise adds the new pages to the unused_ranges pool and returns 0.
+ * During resuming, it ensures the page added doesn't collide with memory that
+ * will be overwritten when copying the original kernel back.
+ */
+
+static int add_range_pages(int number_requested)
+{
+	int i, j;
+	struct range * ranges;
+	void **eaten_memory = NULL, **this;
+
+	for (j = 0; j < number_requested; j++) {
+		if (test_suspend_state(SUSPEND_NOW_RESUMING)) {
+			struct page * pageaddr;
+			/* Make sure page doesn't collide when we're resuming */
+			while ((this = (void **) get_zeroed_page(GFP_ATOMIC))) {
+				pageaddr = virt_to_page(this);
+				if (!PageInUse(pageaddr))
+					break;
+				*this = eaten_memory;
+				eaten_memory = this;
+			}
+			// Free unwanted memory
+			while(eaten_memory) {
+				this = eaten_memory;
+				eaten_memory = *eaten_memory;
+				free_page((unsigned long) this);
+			}
+		} else
+			this = (void *) get_grabbed_pages(0);
+
+		if (!this)
+			return 1;
+
+		num_range_pages++;
+		if (!first_range_page)
+			first_range_page = (struct range *) this;
+		if (last_range_page)
+			*RANGEPAGELINK(last_range_page) |= (unsigned long) this;
+		*RANGEPAGELINK(this) = num_range_pages;
+		last_range_page = (struct range *) this;
+		ranges = (struct range *) this;
+		for (i = 0; i < RANGES_PER_PAGE; i++)
+			(ranges+i)->next = (ranges+i+1);
+		(ranges + i - 1)->next = unused_ranges;
+		unused_ranges = ranges;
+		nr_unused_ranges += i;
+	}
+	return 0;
+}
+
+
+/* 
+ * Free ranges.
+ *
+ * Frees pages allocated by add_range_pages()
+ *
+ * Checks that all ranges allocated have been freed and emits a warning if this
+ * is not true.
+ */
+
+int free_ranges(void)
+{
+	int i;
+	struct range * this_range_page = first_range_page, 
+		* next_range_page = NULL;
+
+	if (ranges_allocated)
+		printk(" *** Warning: %ld ranges still allocated when "
+				"free_ranges() called.\n", ranges_allocated);
+
+	for (i = 0; i < num_range_pages; i++) {
+		next_range_page = (struct range *) 
+			(((unsigned long)
+			  (*RANGEPAGELINK(this_range_page))) & PAGE_MASK);
+		free_pages((unsigned long) this_range_page, 0);
+		this_range_page = next_range_page;
+	}
+
+	nr_unused_ranges = num_range_pages = ranges_allocated = 0;
+	unused_ranges = last_range_page = first_range_page = NULL;
+
+	return 0;
+}
+
+/* get_range
+ *
+ * Returns a free range, having removed it from the unused list and having
+ * incremented the usage count. May imply allocating a new page and may
+ * therefore fail, returning NULL instead.
+ * 
+ * No locking. This is because we are only called from suspend, which is single
+ * threaded.
+ */
+
+static struct range * get_range(void)
+{
+	struct range * result;
+	
+	if ((!unused_ranges) && (add_range_pages(1)))
+		return NULL;
+
+	result = unused_ranges;
+	unused_ranges = unused_ranges->next;
+	nr_unused_ranges--;
+	ranges_allocated++;
+	if (ranges_allocated > max_ranges_used)
+		max_ranges_used++;
+	result->minimum = result->maximum = 0;
+	result->next = NULL;
+	return result;
+}
+
+/*
+ * put_range.
+ *
+ * Returns a range to the pool of unused pages and decrements the usage count.
+ *
+ * Assumes unlinking is done by the caller.
+ */
+void put_range(struct range * range)
+{
+	if (!range) {
+		printk("Error! put_range called with NULL range.\n");
+		return;
+	}
+	range->minimum = range->maximum = 0;
+	range->next = unused_ranges;
+	unused_ranges = range;
+	ranges_allocated--;
+	nr_unused_ranges++;
+}
+
+/*
+ * put_range_chain.
+ *
+ * Returns a whole chain of ranges to the unused pool.
+ */
+void put_range_chain(struct rangechain * chain)
+{
+	int count = 0;
+	struct range * this;
+
+	if (chain->first) {
+		this = chain->first;
+		while (this) {
+			this->minimum = this->maximum = 0;
+			this=this->next;
+		}
+		chain->last->next = unused_ranges;
+		unused_ranges = chain->first;
+		count = chain->allocs - chain->frees;
+		ranges_allocated -= count;
+		nr_unused_ranges += count;
+
+		chain->first = NULL;
+		chain->last = NULL;
+		chain->size = 0;
+		chain->allocs = 0;
+		chain->frees = 0;
+		chain->timesusedoptimisation = 0;
+		chain->lastaccessed = NULL; /* Invalidate optimisation info */
+		chain->prevtolastaccessed = NULL;
+		chain->prevtoprev = NULL;
+	}
+}
+
+/* print_chain.
+ *
+ * Displays the contents of a chain.
+ *
+ * printmethod:
+ * 0: integer
+ * 1: hex
+ * 2: page number
+ */
+void print_chain(int debuglevel, struct rangechain * chain, int printmethod)
+{
+	struct range * this = chain->first;
+	int count = 0, size = 0;
+	
+	if ((console_loglevel < debuglevel) || (!this) ||
+			(!TEST_DEBUG_STATE(SUSPEND_RANGES)))
+		return;
+
+	if (!chain->name)
+		suspend_message(SUSPEND_RANGES, debuglevel, 1, "Chain %p\n", chain);
+	else
+		suspend_message(SUSPEND_RANGES, debuglevel, 1, "%s\n", chain->name);
+	
+	while (this) {
+		/*
+		 * 'This' is printed separately so it is displayed if an oops
+		 * results.
+		 */
+		switch (printmethod) {
+			case 0:
+				suspend_message(SUSPEND_RANGES, debuglevel, 1, "(%p) ",
+					this);
+				suspend_message(SUSPEND_RANGES, debuglevel, 1, "%lx-%lx; ",
+					this->minimum, this->maximum);
+				break;
+			case 1:
+				suspend_message(SUSPEND_RANGES, debuglevel, 1, "(%p)",
+					this);
+				suspend_message(SUSPEND_RANGES, debuglevel, 1, "%lu-%lu; ",
+					this->minimum, this->maximum);
+				break;
+			case 2:
+				suspend_message(SUSPEND_RANGES, debuglevel, 1, "(%p)",
+					this);
+				suspend_message(SUSPEND_RANGES, debuglevel, 1, "%p-%p; ",
+					page_address(mem_map+this->minimum),
+					page_address(mem_map+this->maximum) +
+						PAGE_SIZE - 1);
+				break;
+		}
+		size+= this->maximum - this->minimum + 1;
+		this = this->next;
+		count++;
+		if (!(count%4))
+			suspend_message(SUSPEND_RANGES, debuglevel, 1, "\n");
+	}
+	
+	if ((count%4))
+		suspend_message(SUSPEND_RANGES, debuglevel, 1, "\n");
+
+	suspend_message(SUSPEND_RANGES, debuglevel, 1,"%d entries/%ld allocated. "
+			"Allocated %d and freed %d. Size %d.",
+			count, 
+			ranges_allocated,
+			chain->allocs,
+			chain->frees,
+			size);
+	if (count != (chain->allocs - chain->frees)) {
+		chain->debug = 1;
+		check_shift_keys(1, "Discrepancy in chain.");
+	}
+	suspend_message(SUSPEND_RANGES, debuglevel, 1, "\n");
+}
+
+/*
+ * add_to_range_chain.
+ *
+ * Takes a value to be stored and a pointer to a chain and adds the value to 
+ * the range chain, merging with an existing range or  adding a new entry as
+ * necessary. Ranges  are stored in increasing order.
+ *
+ * Values should be consecutive, and so may need to be transformed first. (eg
+ * for pages, would want to call with page-mem_map).
+ *
+ * Important optimisation:
+ * We store in the chain info the location of the last range accessed or added
+ * (and its previous). If the next value is outside this range by one, we start
+ * from the previous entry instead of the start of the chain. In cases of heavy
+ * fragmentation, this saves a lot of time searching.
+ * 
+ * Returns:
+ * 0 if successful
+ * 1 if the value is already included.
+ * 2 if unable to allocate memory.
+ * 3 if fall out bottom (shouldn't happen).
+ */
+
+int add_to_range_chain(struct rangechain * chain, unsigned long value)
+{
+	struct range * this, * prev = NULL, * prevtoprev = NULL;
+	int usedoptimisation = 0;
+	
+	if (!chain->first) {	/* Empty */
+		chain->last = chain->first = get_range();
+		if (!chain->first) {
+			printk("Error unable to allocate the first range for "
+					"the chain.\n");
+			return 2;
+		}
+		chain->allocs++;
+		chain->first->maximum = value;
+		chain->first->minimum = value;
+		chain->size++;
+		return 0;
+	}
+	
+	this = chain->first;
+
+	if (chain->lastaccessed && chain->prevtolastaccessed &&
+		       chain->prevtoprev) {
+		if ((value + 1) == chain->lastaccessed->minimum) {
+			prev = chain->prevtoprev;
+			this = chain->prevtolastaccessed;
+			usedoptimisation = 1;
+		} else if (((value - 1) == chain->lastaccessed->maximum)) {
+			prev = chain->prevtolastaccessed;
+			this = chain->lastaccessed;
+			usedoptimisation = 1;
+		}
+	}
+
+	while (this) {
+		/* Need new entry prior to this? */
+		if ((value + 1) < this->minimum) {
+			struct range * new = get_range();
+			if (!new)
+				return 2;
+			chain->allocs++;
+			new->minimum = value;
+			new->maximum = value;
+			new->next = this;
+			/* Prior to start of chain? */
+			if (!prev)
+				chain->first = new;
+			else
+				prev->next = new;
+			if (!usedoptimisation) {
+				chain->prevtoprev = prevtoprev;
+				chain->prevtolastaccessed = prev;
+				chain->lastaccessed = new;
+			}
+			chain->size++;
+			return 0;
+		}
+
+		if ((this->minimum <= value) && (this->maximum >= value)) {
+			if (chain->name)
+				printk("%s:", chain->name);
+			else
+				printk("%p:", chain);
+				printk("Trying to add a value (%ld/0x%lx) already "
+				"included in chain.\n",
+				value, value);
+			print_chain(SUSPEND_ERROR, chain, 0);
+			check_shift_keys(1, NULL);
+			return 1;
+		}
+		if ((value + 1) == this->minimum) {
+			this->minimum = value;
+			if (!usedoptimisation) {
+				chain->prevtoprev = prevtoprev;
+				chain->prevtolastaccessed = prev;
+				chain->lastaccessed = this;
+			}
+			chain->size++;
+			return 0;
+		}
+		if ((value - 1) == this->maximum) {
+			if ((this->next) && 
+					(this->next->minimum == value + 1)) {
+				struct range * oldnext = this->next;
+				this->maximum = this->next->maximum;
+				this->next = this->next->next;
+				if ((chain->last) == oldnext)
+					chain->last = this;
+				put_range(oldnext);
+				/* Invalidate optimisation info */
+				chain->lastaccessed = NULL;	
+				chain->frees++;
+				if (!usedoptimisation) {
+					chain->prevtoprev = prevtoprev;
+					chain->prevtolastaccessed = prev;
+					chain->lastaccessed = this;
+				}
+				chain->size++;
+				return 0;
+			} 
+			this->maximum = value;
+			if (!usedoptimisation) {
+				chain->prevtoprev = prevtoprev;
+				chain->prevtolastaccessed = prev;
+				chain->lastaccessed = this;
+			}
+			chain->size++;
+			return 0;
+		}
+		if (!this->next) {
+			struct range * new = get_range();
+			if (!new) {
+				printk("Error unable to append a new range to "
+						"the chain.\n");
+				return 2;
+			}
+			chain->allocs++;
+			new->minimum = value;
+			new->maximum = value;
+			new->next = NULL;
+			this->next = new;
+			chain->last = new;
+			if (!usedoptimisation) {
+				chain->prevtoprev = prev;
+				chain->prevtolastaccessed = this;
+				chain->lastaccessed = new;
+			}
+			chain->size++;
+			return 0;
+		}
+		prevtoprev = prev;
+		prev = this;
+		this = this->next;
+	}
+	printk("\nFell out the bottom of add_to_range_chain. This shouldn't "
+			"happen!\n");
+	SET_RESULT_STATE(SUSPEND_ABORTED);
+	return 3;
+}
+
+/* append_range
+ * Used where we know a range is to be added to the end of the list
+ * and does not need merging with the current last range.
+ * (count_data_pages only at the moment)
+ */
+
+int append_range_to_range_chain(struct rangechain * chain, 
+		unsigned long minimum, unsigned long maximum)
+{
+	struct range * newrange = NULL;
+
+	newrange = get_range();
+	if (!newrange) {
+		printk("Error unable to append a new range to the chain.\n");
+		return 2;
+	}
+
+	chain->allocs++;
+	chain->size+= (maximum - minimum + 1);
+	newrange->minimum = minimum;
+	newrange->maximum = maximum;
+	newrange->next = NULL;
+
+	if (chain->last) {
+		chain->last->next = newrange;
+		chain->last = newrange;
+	} else 
+		chain->last = chain->first = newrange;
+
+	/* No need to reset optimisation info since added to end */
+	return 0;
+}
+
+int append_to_range_chain(int chain, unsigned long min, unsigned long max)
+{
+	int result = 0;
+
+	switch (chain) {
+		case 0:
+			return 0;
+		case 1:
+			result = append_range_to_range_chain(
+					&pagedir1.origranges, min, max);
+			break;
+		case 2:
+			result = append_range_to_range_chain(
+					&pagedir2.origranges, min, max);
+			if (!result)
+				result = append_range_to_range_chain(
+					&pagedir1.destranges, min, max);
+	}
+	return result;
+}
+
+/* -------------- Routines for relativising and absoluting ranges -------------
+ *
+ * Prepare rangesets for save by translating addresses to relative indices.
+ */
+void relativise_ranges(void)
+{
+	struct range * this_range_page = first_range_page;
+	int i;
+	
+	while (this_range_page) {
+		struct range * this_range = this_range_page;
+		for (i = 0; i < RANGES_PER_PAGE; i++) {
+			if (this_range->next) {
+				struct range * orig = this_range->next;
+				this_range->next =
+					RANGE_RELATIVE(this_range->next);
+				suspend_message(SUSPEND_RANGES, SUSPEND_VERBOSE, 1,
+					"Relativised range %d on this page is %p. Absolutised range is %p.\n",
+					i, this_range->next, orig);
+			}
+			this_range++;
+		}
+		this_range_page = (struct range *)
+			((*RANGEPAGELINK(this_range_page)) & PAGE_MASK);
+	}
+}
+
+/* Convert ->next pointers for ranges back to absolute values.
+ * The issue is finding out what page the absolute value is now at.
+ * If we use an array of values, we gain speed, but then we need to
+ * be able to allocate contiguous pages. Fortunately, this is done
+ * prior to loading pagesets, so we can just allocate the pages
+ * needed, set up our array and use it and then discard the data
+ * before we exit.
+ */
+
+void absolutise_ranges()
+{
+	struct range * this_range_page = first_range_page;
+	int i;
+	
+	while (this_range_page) {
+		struct range * this_range = this_range_page;
+		for (i = 0; i < RANGES_PER_PAGE; i++) {
+			if (this_range->next) {
+				struct range * orig = this_range->next;
+				this_range->next = 
+					RANGE_ABSOLUTE(this_range->next);
+				suspend_message(SUSPEND_RANGES, SUSPEND_VERBOSE, 1,
+					"Relativised range %d on this page is %p. Absolutised range is %p.\n",
+					i, orig, this_range->next);
+			}
+			this_range++;
+		}
+		this_range_page = (struct range *)
+			((*RANGEPAGELINK(this_range_page)) & PAGE_MASK);
+	}
+}
+
+void absolutise_chain(struct rangechain * chain)
+{
+	if (chain->first)
+		chain->first = RANGE_ABSOLUTE(chain->first);
+	if (chain->last)
+		chain->last = RANGE_ABSOLUTE(chain->last);
+	if (chain->lastaccessed)
+		chain->lastaccessed = RANGE_ABSOLUTE(chain->lastaccessed);
+	if (chain->prevtolastaccessed)
+		chain->prevtolastaccessed =
+			RANGE_ABSOLUTE(chain->prevtolastaccessed);
+	if (chain->prevtoprev)
+		chain->prevtoprev =
+			RANGE_ABSOLUTE(chain->prevtoprev);
+}
+
+void relativise_chain(struct rangechain * chain)
+{
+	if (chain->first)
+		chain->first = RANGE_RELATIVE(chain->first);
+	if (chain->last)
+		chain->last = RANGE_RELATIVE(chain->last);
+	if (chain->lastaccessed)
+		chain->lastaccessed = RANGE_RELATIVE(chain->lastaccessed);
+	if (chain->prevtolastaccessed)
+		chain->prevtolastaccessed =
+			RANGE_RELATIVE(chain->prevtolastaccessed);
+	if (chain->prevtoprev)
+		chain->prevtoprev = RANGE_RELATIVE(chain->prevtoprev);
+}
+
+/*
+ * Each page in the rangepages lists starts with a pointer to the next page
+ * containing the list. This lets us only use order zero allocations.
+ */
+#define POINTERS_PER_PAGE ((PAGE_SIZE / sizeof(void *)) - 1)
+static unsigned long * range_pagelist = NULL;
+
+unsigned long * get_rangepages_list_entry(int index)
+{
+	int pagenum, offset, i;
+	unsigned long * current_list_page = range_pagelist;
+
+	BUG_ON(index > num_range_pages);
+
+	pagenum = index / POINTERS_PER_PAGE;
+	offset = index - (pagenum * POINTERS_PER_PAGE);
+
+	for (i = 0; i < pagenum; i++)
+		current_list_page = *((unsigned long **) current_list_page);
+
+	return (unsigned long *) current_list_page[offset];
+}
+
+int get_rangepages_list(void)
+{
+	struct range * this_range_page = first_range_page;
+	int i, j, pages_needed, num_in_this_page;
+	unsigned long * current_list_page = range_pagelist;
+	unsigned long * prev_list_page = NULL;
+
+	pages_needed =
+		((num_range_pages + POINTERS_PER_PAGE - 1) / POINTERS_PER_PAGE);
+	
+	for (i = 0; i < pages_needed; i++) {
+		int page_start = i * POINTERS_PER_PAGE;
+		
+		if (!current_list_page) {
+			current_list_page =
+				(unsigned long *) get_grabbed_pages(0);
+			if (!current_list_page)
+				current_list_page = (unsigned long *) get_zeroed_page(GFP_ATOMIC);
+			if (!current_list_page) {
+				abort_suspend("Unable to allocate memory for a range pages list.");
+				printk("Number of range pages is %d.\n", num_range_pages);
+				return -ENOMEM;
+			}
+
+			current_list_page[0] = 0;
+			if (!prev_list_page)
+				range_pagelist = current_list_page;
+			else {
+				*prev_list_page = (unsigned long) current_list_page;
+				prev_list_page = current_list_page;
+			}
+		}
+	
+		num_in_this_page = num_range_pages - page_start;
+		if (num_in_this_page > POINTERS_PER_PAGE)
+			num_in_this_page = POINTERS_PER_PAGE;
+		
+		for (j = 1; j <= num_in_this_page; j++) {
+			current_list_page[j] = (unsigned long) this_range_page;
+
+			this_range_page = (struct range *) (((unsigned long)
+				(*RANGEPAGELINK(this_range_page))) & PAGE_MASK);
+		}
+		
+		for (j = (num_in_this_page + 1); j <= POINTERS_PER_PAGE; j++)
+			current_list_page[j] = 0;
+
+		if ((num_range_pages - page_start) > POINTERS_PER_PAGE)
+			current_list_page = (unsigned long *) current_list_page[0];
+	}
+
+	return 0;
+}
+
+void put_rangepages_list(void)
+{
+	unsigned long * last;
+
+	while (range_pagelist) {
+		last = range_pagelist;
+		range_pagelist = *((unsigned long **) range_pagelist);
+		free_pages((unsigned long) last, 0);
+	}
+}
+
+int PageRangePage(char * seeking)
+{
+	int i;
+	
+	for (i = 1; i <= num_range_pages; i++)
+		if (get_rangepages_list_entry(i) == 
+			(unsigned long *) seeking)
+			return 1;
+
+	return 0;
+}
+/* relocate_rangepages
+ * 
+ * Called at the start of resuming. As well as absolutising pages, we need
+ * to ensure they won't be overwritten by the kernel we're restoring. 
+ */
+int relocate_rangepages()
+{
+	void **eaten_memory = NULL;
+	void **c = eaten_memory, *m = NULL, *f;
+	int oom = 0, i, numeaten = 0;
+	unsigned long * prev_page = NULL;
+
+	for (i = 1; i <= num_range_pages; i++) {
+		int this_collides = 0;
+		unsigned long * this_page = get_rangepages_list_entry(i);
+
+		this_collides = PageInUse(virt_to_page(this_page));
+
+		if (!this_collides) {
+			prev_page = this_page;
+			continue;
+		}
+
+		while ((m = (void *) get_zeroed_page(GFP_ATOMIC))) {
+			memset(m, 0, PAGE_SIZE);
+			if (!PageInUse(virt_to_page(m))) {
+				copy_page(m, (void *) this_page);
+				free_page((unsigned long) this_page);
+				if (i == 1)
+					first_range_page = m;
+				else
+					*RANGEPAGELINK(prev_page) =
+						(i | (unsigned long) m);
+				prev_page = m;
+				break;
+			}
+			numeaten++;
+			eaten_memory = m;
+			*eaten_memory = c;
+			c = eaten_memory;
+		}
+
+		if (!m) {
+			printk("\nRan out of memory trying to relocate "
+				"rangepages (tried %d pages).\n", numeaten);
+			oom = 1;
+			break;
+		}
+	}
+		
+	c = eaten_memory;
+	while(c) {
+		f = c;
+		c = *c;
+		if (f)
+			free_pages((unsigned long) f, 0);
+	}
+	eaten_memory = NULL;
+	
+	if (oom) 
+		return -ENOMEM;
+	else
+		return 0;
+}
+
+EXPORT_SYMBOL(put_rangepages_list);
+EXPORT_SYMBOL(get_rangepages_list);
+EXPORT_SYMBOL(get_rangepages_list_entry);
+EXPORT_SYMBOL(absolutise_chain);
+EXPORT_SYMBOL(relativise_chain);
+EXPORT_SYMBOL(put_range);
+EXPORT_SYMBOL(put_range_chain);
+EXPORT_SYMBOL(add_to_range_chain);
+EXPORT_SYMBOL(PageRangePage);
#62 lore raw

Re: Suspend 2 merge: 24/51: Keyboard and serial console hooks.

In reply to Nigel Cunningham
Quoted 10 lines · Nigel Cunningham

Here we add simple hooks so that the user can interact with suspend while it is running. (Hmm. The serial console condition could be simplified :>). The hooks allow you to do such things as:

- cancel suspending
- change the amount of detail of debugging info shown
- change what debugging info is shown
- pause the process
- single step
- toggle rebooting instead of powering down

And why would we want this? If the users calls the suspend call he surely wants to suspend, right?

After all we don't have inkernel hooks to allow a user to read instead write after calling sys_write.

#153 lore raw
In reply to Nigel Cunningham
Quoted 9 lines · Nigel Cunningham

Hi everyone.

I know that I still have work to do on suspend2, but thought it was high time I got around to properly submitting the code for review, so here goes.

I have it split up into 51 patches, of which most are less than 20k, although there are three 50k patches. Changes to the rest of the kernel tree come first, then the core. The full tree can be found at

Your way of merging looks rather wrong. Please submit changes against the current swsusp code that introduce one feature after another to bring it at the level you want. You'll surely have to rewrok it a lot until all reviewers are happy.

And most importantly for each patch explain exactly what feature it implements and why, etc.. "swsusp2" tells exactly nothing about the changed you do.

#186 lore raw

Suspend 2 merge: 36/51: Highlevel I/O routines.

In reply to Nigel Cunningham

Highlevel routines for doing I/O. These routines are designed to know nothing about how and where the data is actually saved. Here, we just focus on asking our writer to write data for us and get it back from storage.

kernel/power/io.c +1095 -0
diff -ruN 826-io-old/kernel/power/io.c 826-io-new/kernel/power/io.c
@@ -0,0 +1,1095 @@
+/*
+ * kernel/power/io.c
+ *
+ * Copyright (C) 1998-2001 Gabor Kuti <[email protected]>
+ * Copyright (C) 1998,2001,2002 Pavel Machek <[email protected]>
+ * Copyright (C) 2002-2003 Florent Chabaud <[email protected]>
+ * Copyright (C) 2002-2004 Nigel Cunningham <[email protected]>
+ *
+ * This file is released under the GPLv2.
+ *
+ * It contains high level IO routines for suspend.
+ *
+ */
+
+#define SUSPEND_IO_C
+
+#include <linux/suspend.h>
+#include <linux/version.h>
+#include <linux/mm.h>
+#include <linux/utsname.h>
+
+#include "suspend.h"
+#include "plugins.h"
+
+/* Variables saved in the suspend header */
+extern unsigned long orig_mem_free;
+extern int suspend_act_used;
+extern int suspend_lvl_used;
+extern int suspend_dbg_used;
+extern volatile int suspend_io_time[2][2];
+
+extern struct pagedir __nosavedata pagedir_resume;
+extern struct range * unused_ranges;
+extern int suspend2_prepare_console(void);
+
+/* Routines we call when reloading the original kernel */
+extern void warmup_collision_cache(void);
+extern int get_pageset1_load_addresses(void);
+
+extern void get_next_pbe(struct pbe2 * pbe);
+extern void get_first_pbe(struct pbe2 * pbe, struct pagedir * pagedir);
+
+static void noresume_reset_plugins(void);
+
+/* cleanup_finished_suspend_io
+ *
+ * Description:	Very simple helper function to save #including all the
+ * 		suspend code in fs/buffer.c and anywhere else we might
+ * 		want to wait on suspend I/O in future.
+ */
+
+void cleanup_finished_suspend_io(void)
+{
+	active_writer->ops.writer.wait_on_io(0);
+}
+
+/* fill_suspend_header()
+ * 
+ * Description:	Fill the suspend header structure.
+ * Arguments:	struct suspend_header: Header data structure to be filled.
+ */
+
+static __inline__ void fill_suspend_header(struct suspend_header *sh)
+{
+	int i;
+	
+	memset((char *)sh, 0, sizeof(*sh));
+
+	sh->version_code = LINUX_VERSION_CODE;
+	sh->num_physpages = num_physpages;
+	sh->orig_mem_free = orig_mem_free;
+	strncpy(sh->machine, system_utsname.machine, 65);
+	strncpy(sh->version, system_utsname.version, 65);
+	sh->num_cpus = num_online_cpus();
+	sh->page_size = PAGE_SIZE;
+	sh->pagedir = pagedir1;
+	sh->pagedir.origranges.first = pagedir1.origranges.first;
+	sh->pagedir.destranges.first = pagedir1.destranges.first;
+	sh->pagedir.allocdranges.first = pagedir1.allocdranges.first;
+	sh->unused_ranges = unused_ranges;
+	sh->num_range_pages = num_range_pages;
+	sh->pageset_2_size = pagedir2.pageset_size;
+	sh->param0 = suspend_result;
+	sh->param1 = suspend_action;
+#ifdef CONFIG_SOFTWARE_SUSPEND_DEBUG
+	sh->param2 = suspend_debug_state;
+#endif
+	sh->param3 = console_loglevel;
+	for (i = 0; i < 4; i++)
+		sh->io_time[i/2][i%2] =
+		       suspend_io_time[i/2][i%2];
+}
+
+/* write_pageset()
+ *
+ * Description:	Write a pageset to disk.
+ * Arguments:	pagedir:	Pointer to the pagedir to be saved.
+ * 		whichtowrite:	Controls what debugging output is printed.
+ * Returns:	Zero on success or -1 on failure.
+ */
+
+int write_pageset(struct pagedir * pagedir, int whichtowrite)
+{
+	int nextupdate = 0, size, ret = 0, i, base = 0;
+	int barmax = pagedir1.pageset_size + pagedir2.pageset_size;
+	int start_time, end_time;
+	long error = 0;
+	struct pbe2 pbe;
+	unsigned int origfree = real_nr_free_pages();
+	struct suspend_plugin_ops * this_filter, * first_filter = get_next_filter(NULL);
+
+	PRINTFREEMEM("at start of write pageset");
+
+	size = pagedir->pageset_size;
+	if (!size)
+		return 0;
+
+	if (whichtowrite == 1) {
+		prepare_status(1, 0, "Writing kernel & process data...");
+		base = pagedir2.pageset_size;
+	} else {
+		prepare_status(1, 1, "Writing caches...");
+	}	
+	
+	start_time = jiffies;
+
+	/* Initialise page transformers */
+	list_for_each_entry(this_filter, &suspend_filters, ops.filter.filter_list) {
+		if (this_filter->disabled)
+			continue;
+		if (this_filter->ops.filter.write_init)
+			this_filter->ops.filter.write_init(whichtowrite);
+	}
+
+	PRINTFREEMEM("after initialising page transformers");
+
+	/* Initialise writer */
+	active_writer->ops.filter.write_init(whichtowrite);
+	PRINTFREEMEM("after initialising writer");
+
+	get_first_pbe(&pbe, pagedir);
+
+	/* Write the data */
+	for (i=0; i<size; i++) {
+		int was_mapped = 0;
+		/* Status update */
+		if (!(i&0x1FF)) 
+			suspend_message(SUSPEND_IO, SUSPEND_LOW, 1, ".");
+		if (((i+base) >= nextupdate) || 
+				(!(i%(1 << (20 - PAGE_SHIFT)))))
+			nextupdate = update_status(i + base, barmax, 
+				" %d/%d MB ", MB(base+i+1), MB(barmax));
+		if ((i == (size - 5)) &&
+			TEST_ACTION_STATE(SUSPEND_PAUSE_NEAR_PAGESET_END))
+			check_shift_keys(1, "Five more pages to write.");
+		suspend_message(SUSPEND_IO, SUSPEND_VERBOSE, 1,
+				"Submitting page %d/%d.\n", i, size);
+
+		/* Write */
+		was_mapped = suspend_map_kernel_page(pbe.address, 1);
+		if (TEST_ACTION_STATE(SUSPEND_TEST_FILTER_SPEED))
+			ret = first_filter->ops.filter.write_chunk(pbe.origaddress);
+		else
+			ret = first_filter->ops.filter.write_chunk(pbe.address);
+		if (!was_mapped)
+			suspend_map_kernel_page(pbe.address, 0);
+
+		if (ret) {
+			printk("Write chunk returned %d.\n", ret);
+			abort_suspend("Failed to write a chunk of the "
+					"image.");
+			error = -1;
+			goto write_pageset_free_buffers;
+		}
+
+		/* Interactivity */
+		check_shift_keys(0, NULL);
+
+		if (TEST_RESULT_STATE(SUSPEND_ABORTED)) {
+			abort_suspend("Aborting as requested.");
+			error = -1;
+			goto write_pageset_free_buffers;
+		}
+
+		/* Prepare next */
+		get_next_pbe(&pbe);
+	}
+
+	update_status(base+size, barmax, " %d/%d MB ",
+			MB(base+size), MB(barmax));
+	suspend_message(SUSPEND_IO, SUSPEND_LOW, 1, "|\n");
+	PRINTFREEMEM("after writing data");
+
+write_pageset_free_buffers:
+	
+	/* Flush data and cleanup */
+	list_for_each_entry(this_filter, &suspend_filters, ops.filter.filter_list) {
+		if (this_filter->disabled)
+			continue;
+		if (this_filter->ops.filter.write_cleanup)
+			this_filter->ops.filter.write_cleanup();
+	}
+	PRINTFREEMEM("after cleaning up transformers");
+	active_writer->ops.writer.write_cleanup();
+	PRINTFREEMEM("after cleaning up writer");
+
+	/* Statistics */
+	end_time = jiffies;
+	
+	if ((end_time - start_time) && (!TEST_RESULT_STATE(SUSPEND_ABORTED))) {
+		suspend_message(SUSPEND_IO, SUSPEND_LOW, 1,
+			"Time to write data: %d pages in %d jiffies => "
+			"MB written per second: %lu.\n", 
+			size,
+			(end_time - start_time), 
+			(MB((unsigned long) size) * HZ / (end_time - start_time)));
+		suspend_io_time[0][0] += size,
+		suspend_io_time[0][1] += (end_time - start_time);
+	}
+
+	PRINTFREEMEM("at end of write pageset");
+
+	/* Sanity checking */
+	if (real_nr_free_pages() != origfree) {
+		abort_suspend("Number of free pages at start and end of write "
+			"pageset don't match! (%d != %d)",
+			origfree, real_nr_free_pages());
+	}
+
+	suspend_store_free_mem(SUSPEND_FREE_IO, 0);
+	return error;
+}
+
+/* read_pageset()
+ *
+ * Description:	Read a pageset from disk.
+ * Arguments:	pagedir:	Pointer to the pagedir to be saved.
+ * 		whichtowrite:	Controls what debugging output is printed.
+ * 		overwrittenpagesonly: Whether to read the whole pageset or
+ * 		only part.
+ * Returns:	Zero on success or -1 on failure.
+ */
+
+int read_pageset(struct pagedir * pagedir, int whichtoread,
+		int overwrittenpagesonly)
+{
+	int nextupdate = 0, result = 0, base = 0;
+	int start_time, end_time, finish_at = pagedir->pageset_size;
+	int barmax = pagedir1.pageset_size + pagedir2.pageset_size;
+	int i;
+	struct pbe2 pbe;
+	struct suspend_plugin_ops * this_filter, * first_filter = get_next_filter(NULL);
+
+	PRINTFREEMEM("at start of read pageset");
+
+	if (whichtoread == 1) {
+		prepare_status(1, 1, "Reading kernel & process data...");
+	} else {
+		prepare_status(1, 0, "Reading caches...");
+		if (overwrittenpagesonly)
+			barmax = finish_at = min(pageset1_size, pageset2_size);
+		else {
+			base = pagedir1.pageset_size;
+		}
+	}	
+	
+	start_time=jiffies;
+
+	/* Initialise page transformers */
+	list_for_each_entry(this_filter, &suspend_filters, ops.filter.filter_list) {
+		if (this_filter->disabled)
+			continue;
+		if (this_filter->ops.filter.read_init && 
+				this_filter->ops.filter.read_init(whichtoread)) {
+			abort_suspend("Failed to initialise a filter.");
+			result = 1;
+			goto read_pageset_free_buffers;
+		}
+	}
+
+	/* Initialise writer */
+	if (active_writer->ops.writer.read_init(whichtoread)) {
+		abort_suspend("Failed to initialise the writer."); 
+		result = 1;
+		goto read_pageset_free_buffers;
+	}
+
+	get_first_pbe(&pbe, pagedir);
+
+	suspend_message(SUSPEND_IO, SUSPEND_LOW, 1,
+		"Attempting to read %d pages.\n", finish_at);
+
+	/* Read the pages */
+	for (i=0; i< finish_at; i++) {
+		int was_mapped = 0;
+		/* Status */
+		if (!(i&0x1FF)) 
+			suspend_message(SUSPEND_IO, SUSPEND_LOW, 1, ".");
+		if (((i+base) >= nextupdate) ||
+				(!(i%(1 << (20 - PAGE_SHIFT)))))
+			nextupdate = update_status(i+base, barmax,
+				" %d/%d MB ", MB(base+i+1), MB(barmax));
+		if ((i == (finish_at - 5)) &&
+			TEST_ACTION_STATE(SUSPEND_PAUSE_NEAR_PAGESET_END))
+			check_shift_keys(1, "Five more pages to read.");
+		suspend_message(SUSPEND_IO, SUSPEND_VERBOSE, 1,
+				"Submitting page %d/%d.\n", i, finish_at);
+
+		was_mapped = suspend_map_kernel_page(pbe.address, 1);
+		result = first_filter->ops.filter.read_chunk(pbe.address, SUSPEND_ASYNC);
+		if (!was_mapped)
+			suspend_map_kernel_page(pbe.address, 0);
+
+		if (result) {
+			panic("Failed to read chunk %d/%d of the image.",
+					i, finish_at);
+			goto read_pageset_free_buffers;
+		}
+
+		/* Interactivity*/
+		check_shift_keys(0, NULL);
+
+		/* Prepare next */
+		get_next_pbe(&pbe);
+	}
+
+	update_status(base+finish_at, barmax, " %d/%d MB ",
+			MB(base+finish_at), MB(barmax));
+	suspend_message(SUSPEND_IO, SUSPEND_LOW, 1, "|\n");
+
+read_pageset_free_buffers:
+
+	/* Finish I/O, flush data and cleanup reads. */
+	list_for_each_entry(this_filter, &suspend_filters, ops.filter.filter_list) {
+		if (this_filter->disabled)
+			continue;
+		if (this_filter->ops.filter.read_cleanup &&
+				this_filter->ops.filter.read_cleanup()) {
+			abort_suspend("Failed to cleanup a filter.");
+			result = 1;
+		}
+	}
+
+	if (active_writer->ops.writer.read_cleanup()) {
+		abort_suspend("Failed to cleanup the writer.");
+		result = 1;
+	}
+
+	/* Statistics */
+	end_time=jiffies;
+	if ((end_time - start_time) && (!TEST_RESULT_STATE(SUSPEND_ABORTED))) {
+		suspend_message(SUSPEND_IO, SUSPEND_LOW, 1,
+			"Time to read data: %d pages in %d jiffies => "
+			"MB read per second: %lu.\n",
+			finish_at,
+			(end_time - start_time), 
+			(MB((unsigned long) finish_at) * HZ / 
+			 	(end_time - start_time)));
+		suspend_io_time[1][0] += finish_at,
+		suspend_io_time[1][1] += (end_time - start_time);
+	}
+
+	PRINTFREEMEM("at end of read pageset");
+
+	suspend_store_free_mem(SUSPEND_FREE_IO, 1);
+	return result;
+}
+
+/* write_plugin_configs()
+ *
+ * Description:	Store the configuration for each plugin in the image header.
+ * Returns:	Int: Zero on success, Error value otherwise.
+ */
+static int write_plugin_configs(void)
+{
+	struct suspend_plugin_ops * this_plugin;
+	char * buffer = (char *) get_zeroed_page(GFP_ATOMIC);
+	int len, index = 1;
+	struct plugin_header plugin_header;
+
+	if (!buffer) {
+		printk("Failed to allocate a buffer for saving "
+				"plugin configuration info.\n");
+		return -ENOMEM;
+	}
+		
+	/* 
+	 * We have to know which data goes with which plugin, so we at
+	 * least write a length of zero for a plugin. Note that we are
+	 * also assuming every plugin's config data takes <= PAGE_SIZE.
+	 */
+
+	/* For each plugin (in registration order) */
+	list_for_each_entry(this_plugin, &suspend_plugins, plugin_list) {
+
+		/* Get the data from the plugin */
+		len = 0;
+		if (this_plugin->save_config_info)
+			len = this_plugin->save_config_info(buffer);
+
+		/* Save the details of the plugin */
+		plugin_header.disabled = this_plugin->disabled;
+		plugin_header.type = this_plugin->type;
+		plugin_header.index = index++;
+		strncpy(plugin_header.name, this_plugin->name, 
+					sizeof(plugin_header.name));
+		active_writer->ops.writer.write_header_chunk(
+				(char *) &plugin_header,
+				sizeof(plugin_header));
+
+		/* Save the size of the data and any data returned */
+		active_writer->ops.writer.write_header_chunk((char *) &len,
+				sizeof(int));
+		if (len)
+			active_writer->ops.writer.write_header_chunk(
+					buffer, len);
+	}
+
+	/* Write a blank header to terminate the list */
+	plugin_header.name[0] = '\0';
+	active_writer->ops.writer.write_header_chunk(
+			(char *) &plugin_header,
+			sizeof(plugin_header));
+
+	free_pages((unsigned long) buffer, 0);
+	return 0;
+}
+
+/* read_plugin_configs()
+ *
+ * Description:	Reload plugin configurations from the image header.
+ * Returns:	Int. Zero on success, error value otherwise.
+ */
+
+static int read_plugin_configs(void)
+{
+	struct suspend_plugin_ops * this_plugin;
+	char * buffer = (char *) get_zeroed_page(GFP_ATOMIC);
+	int len, result = 0;
+	struct plugin_header plugin_header;
+
+	if (!buffer) {
+		printk("Failed to allocate a buffer for reloading plugin "
+				"configuration info.\n");
+		return -ENOMEM;
+	}
+		
+	/* All plugins are initially disabled. That way, if we have a plugin
+	 * loaded now that wasn't loaded when we suspended, it won't be used
+	 * in trying to read the data.
+	 */
+	list_for_each_entry(this_plugin, &suspend_plugins, plugin_list)
+		this_plugin->disabled = 1;
+	
+	/* Get the first plugin header */
+	result = active_writer->ops.writer.read_header_chunk(
+			(char *) &plugin_header, sizeof(plugin_header));
+	if (!result) {
+		printk("Failed to read the next plugin header.\n");
+		free_pages((unsigned long) buffer, 0);
+		return -EINVAL;
+	}
+
+	/* For each plugin (in registration order) */
+	while (plugin_header.name[0]) {
+		
+		/* Find the plugin */
+		this_plugin = find_plugin_given_name(plugin_header.name);
+		
+		if (!this_plugin) {
+			/* 
+			 * Is it used? Only need to worry about filters. The active
+			 * writer must be loaded!
+			 */
+			if ((!plugin_header.disabled) && (plugin_header.type == FILTER_PLUGIN)) {
+				suspend_early_boot_message(1, "It looks like we need plugin %s for reading the image "
+						"but it hasn't been registered.\n",
+						plugin_header.name);
+				if (!(test_suspend_state(SUSPEND_CONTINUE_REQ))) {
+					active_writer->ops.writer.invalidate_image();
+					result = -EINVAL;
+					noresume_reset_plugins();
+					free_pages((unsigned long) buffer, 0);
+					return -EINVAL;
+				}
+			} else
+				printk("Plugin %s configuration data found, but the plugin "
+					"hasn't registered. Looks like it was disabled, so "
+					"we're ignoring it's data.",
+					plugin_header.name);
+		}
+		
+		/* Get the length of the data (if any) */
+		result = active_writer->ops.writer.read_header_chunk(
+				(char *) &len, sizeof(int));
+		if (!result) {
+			printk("Failed to read the length of the plugin %s's"
+					" configuration data.\n",
+					plugin_header.name);
+			free_pages((unsigned long) buffer, 0);
+			return -EINVAL;
+		}
+
+		/* Read any data and pass to the plugin (if we found one) */
+		if (len) {
+			active_writer->ops.writer.read_header_chunk(buffer, len);
+			if (this_plugin) {
+				if (!this_plugin->save_config_info) {
+					printk("Huh? Plugin %s appears to have a "
+						"save_config_info, but not a "
+						"load_config_info function!\n",
+						this_plugin->name);
+				} else
+					this_plugin->load_config_info(buffer, len);
+			}
+		}
+
+		if (this_plugin) {
+			/* Now move this plugin to the tail of its lists. This will put it
+			 * in order. Any new plugins will end up at the top of the lists.
+			 * They should have been set to disabled when loaded (people will
+			 * normally not edit an initrd to load a new module and then
+			 * suspend without using it!).
+			 */
+
+			suspend_move_plugin_tail(this_plugin);
+
+			/* 
+			 * We apply the disabled state; plugins don't need to save whether they
+			 * were disabled and if they do, we override them anyway.
+			 */
+			this_plugin->disabled = plugin_header.disabled;
+		}
+
+		/* Get the next plugin header */
+		result = active_writer->ops.writer.read_header_chunk(
+				(char *) &plugin_header, sizeof(plugin_header));
+
+		if (!result) {
+			printk("Failed to read the next plugin header.\n");
+			free_pages((unsigned long) buffer, 0);
+			return -EINVAL;
+		}
+
+	}
+
+	free_pages((unsigned long) buffer, 0);
+	return 0;
+}
+
+/* write_image_header()
+ *
+ * Description:	Write the image header after write the image proper.
+ * Returns:	Int. Zero on success or -1 on failure.
+ */
+
+int write_image_header(void)
+{
+	int i, nextupdate = 0, ret;
+	int total = pagedir1.pageset_size+pagedir2.pageset_size+2;
+	int progress = total-1;
+	char * header_buffer = NULL;
+
+	/* First, relativise all range information */
+	if (get_rangepages_list())
+		return -1;
+
+	if (unused_ranges)
+		unused_ranges = RANGE_RELATIVE(unused_ranges);
+	
+	relativise_chain(&pagedir1.origranges);
+	relativise_chain(&pagedir1.destranges);
+	relativise_chain(&pagedir1.allocdranges);
+
+	if ((ret = active_writer->ops.writer.prepare_save_ranges())) {
+		abort_suspend("Active writer's prepare_save_ranges "
+				"function failed.");
+		goto write_image_header_abort1;
+	}
+
+	relativise_ranges();
+
+	/* Now prepare to write the header */
+	if ((ret = active_writer->ops.writer.write_header_init())) {
+		abort_suspend("Active writer's write_header_init"
+				" function failed.");
+		goto write_image_header_abort2;
+	}
+
+	/* Get a buffer */
+	header_buffer = (char *) get_zeroed_page(GFP_ATOMIC);
+	if (!header_buffer) {
+		abort_suspend("Out of memory when trying to get page "
+				"for header!");
+		goto write_image_header_abort3;
+	}
+
+	/* Write the meta data */
+	fill_suspend_header((struct suspend_header *) header_buffer);
+	active_writer->ops.writer.write_header_chunk(header_buffer,
+			sizeof(struct suspend_header));
+
+	/* Write plugin configurations */
+	if ((ret = write_plugin_configs())) {
+		abort_suspend("Failed to write plugin configs.");
+		goto write_image_header_abort3;
+	}
+
+	/* Write range pages */
+	suspend_message(SUSPEND_HEADER, SUSPEND_LOW, 1,
+		name_suspend "Writing %d range pages.\n",
+		num_range_pages);
+
+	for (i=1; i<=num_range_pages; i++) {
+		unsigned long * this_range_page = get_rangepages_list_entry(i);
+		/* Status update */
+		suspend_message(SUSPEND_HEADER, SUSPEND_VERBOSE, 1, "%d/%d: %p.\n",
+			i, num_range_pages, this_range_page);
+
+		if (i >= nextupdate)
+			nextupdate = update_status(progress + i, total, NULL);
+
+		/* Check for aborting/pausing */
+		check_shift_keys(0, NULL);
+
+		if (TEST_RESULT_STATE(SUSPEND_ABORTED)) {
+			abort_suspend("Aborting as requested.");
+			goto write_image_header_abort3;
+		}
+		
+		/* Write one range page */
+		active_writer->ops.writer.write_header_chunk(
+				(char *) this_range_page, PAGE_SIZE);
+		
+		if (ret) {
+			abort_suspend("Failed writing a page. "
+					"Error number was %d.", ret);
+			goto write_image_header_abort3;
+		}
+	}
+
+	update_status(total - 1, total, NULL);
+
+	/* Flush data and let writer cleanup */
+	if (active_writer->ops.writer.write_header_cleanup()) {
+		abort_suspend("Failed to cleanup writing header.");
+		goto write_image_header_abort2;
+	}
+
+	if (TEST_RESULT_STATE(SUSPEND_ABORTED))
+		goto write_image_header_abort2;
+
+	suspend_message(SUSPEND_IO, SUSPEND_VERBOSE, 1, "|\n");
+	update_status(total, total, NULL);
+
+	MDELAY(1000);
+	free_pages((unsigned long) header_buffer, 0);
+
+	return 0;
+
+	/* 
+	 * Aborting. We need to...
+	 * - let the writer cleanup (if necessary)
+	 * - revert ranges to absolute values
+	 */
+write_image_header_abort3:
+	active_writer->ops.writer.write_header_cleanup();
+	
+write_image_header_abort2:
+	absolutise_ranges();
+
+	put_rangepages_list();
+
+	if (active_writer->ops.writer.post_load_ranges)
+		active_writer->ops.writer.post_load_ranges();
+
+write_image_header_abort1:
+	if (get_rangepages_list())
+		panic("Unable to allocate rangepageslist.");
+
+	absolutise_chain(&pagedir1.origranges);
+	absolutise_chain(&pagedir1.destranges);
+	absolutise_chain(&pagedir1.allocdranges);
+
+	put_rangepages_list();
+
+	free_pages((unsigned long) header_buffer, 0);
+	return -1;
+}
+
+extern int suspend_early_boot_message(int can_erase_image, char *reason, ...);
+
+/* sanity_check()
+ *
+ * Description:	Perform a few checks, seeking to ensure that the kernel being
+ * 		booted matches the one suspended. They need to match so we can
+ * 		be _sure_ things will work. It is not absolutely impossible for
+ * 		resuming from a different kernel to work, just not assured.
+ * Arguments:	Struct suspend_header. The header which was saved at suspend
+ * 		time.
+ */
+static int sanity_check(struct suspend_header *sh)
+{
+	if (sh->version_code != LINUX_VERSION_CODE)
+		return suspend_early_boot_message(1, "Incorrect kernel version");
+	
+	if (sh->num_physpages != num_physpages)
+		return suspend_early_boot_message(1, "Incorrect memory size");
+
+	if (strncmp(sh->machine, system_utsname.machine, 65))
+		return suspend_early_boot_message(1, "Incorrect machine type");
+
+	if (strncmp(sh->version, system_utsname.version, 65))
+		return suspend_early_boot_message(1, "Incorrect version");
+
+	if (sh->num_cpus != num_online_cpus())
+		return suspend_early_boot_message(1, "Incorrect number of cpus");
+
+	if (sh->page_size != PAGE_SIZE)
+		return suspend_early_boot_message(1, "Incorrect PAGE_SIZE");
+
+	return 0;
+}
+
+/* noresume_reset_plugins
+ *
+ * Description:	When we read the start of an image, plugins (and especially the
+ * 		active writer) might need to reset data structures if we decide
+ * 		to invalidate the image rather than resuming from it.
+ */
+
+static void noresume_reset_plugins(void)
+{
+	struct suspend_plugin_ops * this_plugin;
+	
+	list_for_each_entry(this_plugin, &suspend_plugins, plugin_list) {
+		if (this_plugin->ops.filter.noresume_reset)
+			this_plugin->ops.filter.noresume_reset();
+	}
+}
+
+/* __read_primary_suspend_image
+ *
+ * Description:	Test for the existence of an image and attempt to load it.
+ * Returns:	Int. Zero if image found and pageset1 successfully loaded.
+ * 		Error if no image found or loaded.
+ */
+static int __read_primary_suspend_image(void)
+{			
+	int i, result = 0;
+	char * header_buffer = (char *) get_zeroed_page(GFP_ATOMIC);
+	struct suspend_header * suspend_header;
+	struct range * last_range_page = NULL;
+
+	if (!header_buffer)
+		return -ENOMEM;
+	
+	set_suspend_state(SUSPEND_RUNNING);
+
+	/* Check for an image */
+	if (!(result = active_writer->ops.writer.image_exists())) {
+		result = -ENODATA;
+		noresume_reset_plugins();
+		goto out;
+	}
+
+	/* Check for noresume command line option */
+	if (test_suspend_state(SUSPEND_NORESUME_SPECIFIED)) {
+		active_writer->ops.writer.invalidate_image();
+		result = -EINVAL;
+		noresume_reset_plugins();
+		goto out;
+	}
+
+	/* Check whether we've resumed before */
+	if (test_suspend_state(SUSPEND_RESUMED_BEFORE)) {
+		suspend_early_boot_message(1, NULL);
+		if (!(test_suspend_state(SUSPEND_CONTINUE_REQ))) {
+			active_writer->ops.writer.invalidate_image();
+			result = -EINVAL;
+			noresume_reset_plugins();
+			goto out;
+		}
+	}
+
+	clear_suspend_state(SUSPEND_CONTINUE_REQ);
+
+	/* 
+	 * Prepare the active writer for reading the image header. The
+	 * activate writer might read its own configuration or set up
+	 * a network connection here.
+	 * 
+	 * NB: This call may never return because there might be a signature
+	 * for a different image such that we warn the user and they choose
+	 * to reboot. (If the device ids look erroneous (2.4 vs 2.6) or the
+	 * location of the image might be unavailable if it was stored on a
+	 * network connection.
+	 */
+
+	if ((result = active_writer->ops.writer.read_header_init())) {
+		noresume_reset_plugins();
+		goto out;
+	}
+	
+	/* Read suspend header */
+	if ((result = active_writer->ops.writer.read_header_chunk(
+			header_buffer, sizeof(struct suspend_header))) < 0) {
+		noresume_reset_plugins();
+		goto out;
+	}
+	
+	suspend_header = (struct suspend_header *) header_buffer;
+
+	/*
+	 * NB: This call may also result in a reboot rather than returning.
+	 */
+
+	if (sanity_check(suspend_header)) { /* Is this the same machine? */
+		active_writer->ops.writer.invalidate_image();
+		result = -EINVAL;
+		noresume_reset_plugins();
+		goto out;
+	}
+
+	/*
+	 * ---------------------------------------------------- 
+	 * We have an image and it looks like it will load okay.
+	 * ---------------------------------------------------- 
+	 */
+
+	/* Get metadata from header. Don't override commandline parameters.
+	 *
+	 * We don't need to save the image size limit because it's not used
+	 * during resume and will be restored with the image anyway.
+	 */
+	
+	orig_mem_free = suspend_header->orig_mem_free;
+	memcpy((char *) &pagedir_resume,
+		(char *) &suspend_header->pagedir, sizeof(pagedir_resume));
+	unused_ranges = suspend_header->unused_ranges;
+	num_range_pages = suspend_header->num_range_pages;
+	suspend_result = suspend_header->param0;
+	if (!suspend_act_used)
+		suspend_action = suspend_header->param1;
+#ifdef CONFIG_SOFTWARE_SUSPEND_DEBUG
+	if (!suspend_dbg_used)
+		suspend_debug_state = suspend_header->param2;
+#endif
+	if (!suspend_lvl_used)
+		suspend_default_console_level = console_loglevel = suspend_header->param3;
+	clear_suspend_state(SUSPEND_IGNORE_LOGLEVEL);
+	pagedir1.pageset_size = pagedir_resume.pageset_size;
+	pagedir2.pageset_size = suspend_header->pageset_2_size;
+	for (i = 0; i < 4; i++)
+		suspend_io_time[i/2][i%2] =
+			suspend_header->io_time[i/2][i%2];
+
+	set_suspend_state(SUSPEND_NOW_RESUMING);
+
+	/* Read plugin configurations */
+	if ((result = read_plugin_configs())) {
+		noresume_reset_plugins();
+		num_range_pages = pagedir1.pageset_size =
+			pagedir2.pageset_size = 0;
+		unused_ranges = NULL;
+		goto out;
+	}
+
+	suspend2_prepare_console();
+
+	/* Read range pages */
+	check_shift_keys(1, "About to read pagedir.");
+
+	for (i=0; i < num_range_pages; i++) {
+		/* Get a page into which we will load the data */
+		struct range * this_range_page = 
+			(struct range *) get_zeroed_page(GFP_ATOMIC);
+		if (!this_range_page) {
+			abort_suspend("Unable to allocate a pagedir.");
+			result = -ENOMEM;
+			noresume_reset_plugins();
+			goto outfreeingrangepages;
+		}
+
+		/* Link to previous page */
+		if (i == 0)
+			first_range_page = this_range_page;
+		else
+			*RANGEPAGELINK(last_range_page) =
+				(i | (unsigned long) this_range_page);
+
+		/* Read this page */
+		if ((result = active_writer->ops.writer.read_header_chunk(
+				(char *) this_range_page, PAGE_SIZE)) < 0) {
+			printk("Active writer's read_header_chunk routine "
+					"returned %d.\n", result);
+			free_page((unsigned long) this_range_page);
+			noresume_reset_plugins();
+			goto outfreeingrangepages;
+		}
+		
+		last_range_page = this_range_page;
+	}
+	
+	/* Set the last page's link to its index */
+	*RANGEPAGELINK(last_range_page) = i;
+
+	/* Clean up after reading the header */
+	if ((result = active_writer->ops.writer.read_header_cleanup())) {
+		noresume_reset_plugins();
+		goto outfreeingrangepages;
+	}
+
+	/* Okay.
+	 *
+	 * Now we need to move the range pages to a place such that they won't
+	 * get overwritten while being used when copying the original kernel
+	 * back. To achieve this, we need to absolutise them where they are
+	 * now, prepare a bitmap of pages that collide and then relativise the
+	 * range pages again. Having done that, we can relocate the range
+	 * pages so that they don't collide with the image being restored,
+	 * and absolutise them in that location.
+	 */
+	
+	if (get_rangepages_list()) {
+		result = -ENOMEM;
+		noresume_reset_plugins();
+		goto outfreeingrangepages;
+	}
+	
+	/* Absolutise ranges so they can be used for building the map of
+	 * pages that will be overwritten. */
+	absolutise_ranges();
+	absolutise_chain(&pagedir_resume.origranges);
+
+	/* Mark the pages used by the current and original kernels */
+ 	warmup_collision_cache();
+
+	/* Prepare to move the pages so they don't conflict */
+	relativise_chain(&pagedir_resume.origranges);
+	relativise_ranges();
+ 
+	/* Relocate the pages */
+	relocate_rangepages();
+
+	/* Make sure the rangepages list is correct */
+	put_rangepages_list();
+	get_rangepages_list();
+
+	/* Absolutise in final place */
+	absolutise_ranges();
+	
+	/* Done.
+	 *
+	 * Now we can absolutise all the pointers to the range chains.
+	 */
+
+	set_chain_names(&pagedir_resume);
+	
+	absolutise_chain(&pagedir_resume.origranges);
+	
+	/*
+	 * We don't want the original destination ranges (the locations where
+	 * the atomic copy of pageset1 was stored at suspend time); we release
+	 * the chain's elements before getting new ones. (The kernel running
+	 * right now could be using pages that were free when we suspended).
+	 */
+
+	absolutise_chain(&pagedir_resume.destranges);
+	
+	absolutise_chain(&pagedir_resume.allocdranges);
+
+	if (unused_ranges)
+		unused_ranges = RANGE_ABSOLUTE(unused_ranges);
+	
+	put_rangepages_list();
+
+	/* 
+	 * The active writer should be using chains to record where it stored
+	 * the data. Give it a chance to absolutise them.
+	 */
+	if (active_writer->ops.writer.post_load_ranges)
+		active_writer->ops.writer.post_load_ranges();
+
+	/* 
+	 * Get the addresses of pages into which we will load the kernel to
+	 * be copied back
+	 */
+	put_range_chain(&pagedir_resume.destranges);
+
+	if (get_pageset1_load_addresses()) {
+		result = -ENOMEM;
+		noresume_reset_plugins();
+		goto outfreeingrangepages;
+	}
+
+	/* Read the original kernel back */
+	check_shift_keys(1, "About to read pageset 1.");
+
+	if (read_pageset(&pagedir_resume, 1, 0)) {
+		prepare_status(1, 1, "Failed to read pageset 1.");
+		result = -EPERM;
+		noresume_reset_plugins();
+		goto outfreeingrangepages;
+	}
+
+	PRINTFREEMEM("after loading image.");
+	check_shift_keys(1, "About to restore original kernel.");
+	result = 0;
+
+	if (active_writer->ops.writer.mark_resume_attempted)
+		active_writer->ops.writer.mark_resume_attempted();
+
+out:
+	free_pages((unsigned long) header_buffer, 0);
+	return result;
+outfreeingrangepages:
+	//FIXME Test i post loop and reset memory structures.
+	{
+		int j;
+		struct range * this_range_page = first_range_page;
+		struct range * next_range_page;
+		for (j = 0; j < i; j++) {
+			next_range_page = (struct range *) 
+				(((unsigned long)
+				  *RANGEPAGELINK(this_range_page)) & PAGE_MASK);
+			free_page((unsigned long) this_range_page);
+			this_range_page = next_range_page;
+		}
+	}
+	goto out;
+}
+
+/* read_primary_suspend_image()
+ *
+ * Description:	Attempt to read the header and pageset1 of a suspend image.
+ * 		Handle the outcome, complaining where appropriate.
+ */
+int read_primary_suspend_image(void)
+{
+	int error;
+
+	error = __read_primary_suspend_image();
+
+	switch (error) {
+		case 0:
+		case -ENODATA:
+		case -EINVAL:	/* non fatal error */
+			MDELAY(1000);
+			return error;
+		case -EIO:
+			printk(KERN_CRIT name_suspend "I/O error\n");
+			break;
+		case -ENOENT:
+			printk(KERN_CRIT name_suspend "No such file or directory\n");
+			break;
+		case -EPERM:
+			printk(KERN_CRIT name_suspend "Sanity check error\n");
+			break;
+		default:
+			printk(KERN_CRIT name_suspend "Error %d resuming\n", error);
+			break;
+	}
+	abort_suspend("Error %d in read_primary_suspend_image",error);
+	return error;
+}
+
+/* read_secondary_pagedir()
+ *
+ * Description:	Read in part or all of pageset2 of an image, depending upon
+ * 		whether we are suspending and have only overwritten a portion
+ * 		with pageset1 pages, or are resuming and need to read them 
+ * 		all.
+ * Arguments:	Int. Boolean. Read only pages which would have been
+ * 		overwritten by pageset1?
+ * Returns:	Int. Zero if no error, otherwise the error value.
+ */
+int read_secondary_pagedir(int overwrittenpagesonly)
+{
+	int result = 0;
+
+	if (!pageset2_size)
+		return 0;
+
+	suspend_message(SUSPEND_IO, SUSPEND_VERBOSE, 1,
+		      "Beginning of read_secondary_pagedir: ");
+
+	result = read_pageset(&pagedir2, 2, overwrittenpagesonly);
+
+	update_status(100, 100, NULL);
+	check_shift_keys(1, "Pagedir 2 read.");
+
+	suspend_message(SUSPEND_IO, SUSPEND_VERBOSE, 1, "\n");
+	return result;
+}
#129 lore raw

Re: Suspend 2 merge: 14/51: Disable page alloc failure message when suspending

In reply to Nigel Cunningham
Quoted 2 lines · Nigel Cunningham

While eating memory, we will potentially trigger this a lot. We therefore disable the message when suspending.

So call the allocator with __GFP_NOWARN

#189 lore raw

Suspend 2 merge: 49/51: Checksumming

In reply to Nigel Cunningham

A plugin for verifying the consistency of an image. Working with kdb, it can look up the locations of variations. There will always be some variations shown, simply because we're touching memory before we get here and as we check the image.

kernel/power/Kconfig +9 -0
diff -ruN 855-checksumming-old/kernel/power/Kconfig 855-checksumming-new/kernel/power/Kconfig
@@ -206,6 +206,15 @@
 			
 				  For normal usage, this option can be turned off.
 
+			config SOFTWARE_SUSPEND_CHECKSUMS
+				tristate '   Compile checksum module'
+				depends on SOFTWARE_SUSPEND2_CORE
+				---help---
+				  This option enables compilation of a checksumming module, which can
+				  be used to verify the correct operation of suspend.
+			
+				  For normal usage, this option can be turned off.
+
 		endif
 
 	endif
kernel/power/Makefile +1 -0
diff -ruN 855-checksumming-old/kernel/power/Makefile 855-checksumming-new/kernel/power/Makefile
@@ -21,6 +21,7 @@
 obj-$(CONFIG_SOFTWARE_SUSPEND_GZIP_COMPRESSION)	+= suspend_gzip.o
 obj-$(CONFIG_SOFTWARE_SUSPEND_DEVICE_MAPPER)	+= suspend_dm.o
 obj-$(CONFIG_SOFTWARE_SUSPEND_SWAPWRITER)	+= suspend_block_io.o suspend_swap.o
+obj-$(CONFIG_SOFTWARE_SUSPEND_CHECKSUMS)	+= suspend_checksums.o
 
 obj-$(CONFIG_SOFTWARE_SUSPEND)	+= swsusp.o $(swsusp-smp-y) disk.o
 
kernel/power/suspend_checksums.c +610 -0

610 lines not on this page · raw message

#203 lore raw

Suspend 2 merge: 28/51: Suspend memory pool hooks.

In reply to Nigel Cunningham

We save the image in two pages (LRU and the rest). In order to maintain a consistent image, we satisfy all page allocations from our own memory pool while saving the image and reloading the LRU. This allows us to safely use high level routines which might allocate slab etc and not free it again by the time we do our atomic copy. We simply save all of the pages in the pool when making our atomic copy of the non-LRU pages, without having to worry about exactly how they were or weren't used.

mm/page_alloc.c +24 -0
diff -ruN 815-add-suspend-memory-pool-hooks-old/mm/page_alloc.c 815-add-suspend-memory-pool-hooks-new/mm/page_alloc.c
@@ -277,6 +277,11 @@
 
 	arch_free_page(page, order);
 
+	if (unlikely(test_suspend_state(SUSPEND_USE_MEMORY_POOL))) {
+		suspend2_free_pool_pages(page, order);
+		return;
+	}
+
 	mod_page_state(pgfree, 1 << order);
 	for (i = 0 ; i < (1 << order) ; ++i)
 		free_pages_check(__FUNCTION__, page + i);
@@ -507,6 +512,11 @@
 
 	arch_free_page(page, 0);
 
+	if (unlikely(test_suspend_state(SUSPEND_USE_MEMORY_POOL))) {
+		suspend2_free_pool_pages(page, 0);
+		return;
+	}
+
 	kernel_map_pages(page, 1, 0);
 	inc_page_state(pgfree);
 	if (PageAnon(page))
@@ -609,6 +619,20 @@
 	int do_retry;
 	int can_try_harder;
 
+	if (unlikely(test_suspend_state(SUSPEND_USE_MEMORY_POOL))) {
+		/*
+		 * When pool enabled, processes get allocations
+		 * from a special pool so the image size doesn't
+		 * vary (all the pages in the pool are saved, 
+		 * used or not).
+		 *
+		 * The only process that should be running is
+		 * suspend, so the demand should be very
+		 * predicatable.
+		 */
+		return suspend2_get_pool_pages(gfp_mask, order);
+	}
+
 	might_sleep_if(wait);
 
 	/*
#205 lore raw

Suspend 2 merge: 43/51: Utility functions.

In reply to Nigel Cunningham

These are the routines that I think could possibly be useful elsewhere too.

- A snprintf routine that returns the number of bytes actually put into the buffer, not the number that would have been put in if the buffer was big enough.
- Routine for finding a proc dir entry (we use it to find /proc/splash when)
- Support routines for dynamically allocated pageflags. Save those precious bits!

kernel/power/utility.c +152 -0
diff -ruN 834-utility-old/kernel/power/utility.c 834-utility-new/kernel/power/utility.c
@@ -0,0 +1,152 @@
+/*
+ * kernel/power/utility.c
+ *
+ * Copyright (C) 2004 Nigel Cunningham <[email protected]>
+ * 
+ * This file is released under the GPLv2.
+ *
+ * Routines that only suspend uses at the moment, but which might move
+ * when we merge because they're generic.
+ */
+
+#include <linux/kernel.h>
+#include <linux/module.h>
+#include <linux/mm.h>
+#include <linux/proc_fs.h>
+#include <asm/string.h>
+
+#include "pageflags.h"
+
+extern int suspend_snprintf(char * buffer, int buffer_size, const char *fmt, ...);
+extern struct proc_dir_entry * find_proc_dir_entry(const char *name, struct proc_dir_entry *parent);
+
+/*
+ * suspend_snprintf
+ *
+ * Functionality    : Print a string with parameters to a buffer of a 
+ *                    limited size. Unlike vsnprintf, we return the number
+ *                    of bytes actually put in the buffer, not the number
+ *                    that would have been put in if it was big enough.
+ */
+int suspend_snprintf(char * buffer, int buffer_size, const char *fmt, ...)
+{
+	int result;
+	va_list args;
+
+	if (!buffer_size) {
+		return 0;
+	}
+
+	va_start(args, fmt);
+	result = vsnprintf(buffer, buffer_size, fmt, args);
+	va_end(args);
+
+	if (result > buffer_size) {
+		return buffer_size;
+	}
+
+	return result;
+}
+
+/* 
+ * find_proc_dir_entry.
+ *
+ * Based on remove_proc_entry.
+ * This will go shortly, once user space utilities
+ * are updated to look at /proc/suspend/all_settings.
+ */
+
+struct proc_dir_entry * find_proc_dir_entry(const char *name, struct proc_dir_entry *parent)
+{
+	struct proc_dir_entry **p;
+	int len;
+
+	len = strlen(name);
+	for (p = &parent->subdir; *p; p=&(*p)->next ) {
+		if (proc_match(len, name, *p)) {
+			return *p;
+		}
+	}
+	return NULL;
+}
+
+/* ------------- Dynamically Allocated Page Flags --------------- */
+
+#define BITS_PER_PAGE (PAGE_SIZE * 8)
+#define PAGES_PER_BITMAP ((max_mapnr + BITS_PER_PAGE - 1) / BITS_PER_PAGE)
+#define BITMAP_ORDER (get_bitmask_order((PAGES_PER_BITMAP) - 1))
+
+/* clear_map
+ *
+ * Description:	Clear an array used to store local page flags.
+ * Arguments:	unsigned long *:	The pagemap to be cleared.
+ */
+
+void clear_map(unsigned long * pagemap)
+{
+	int size = (1 << BITMAP_ORDER) * PAGE_SIZE;
+	
+	memset(pagemap, 0, size);
+}
+
+/* allocate_local_pageflags
+ *
+ * Description:	Allocate a bitmap for local page flags.
+ * Arguments:	unsigned long **:	Pointer to the bitmap.
+ * 		int:			Whether to set nosave flags for the
+ * 					newly allocated pages.
+ * Note:	This looks suboptimal, but remember that we might be allocating
+ * 		the Nosave bitmap here.
+ */
+int allocate_local_pageflags(unsigned long ** pagemap, int setnosave)
+{
+	unsigned long * check;
+	int i;
+	if (*pagemap) {
+		printk("Error. Local pageflags map already allocated.\n");
+		clear_map(*pagemap);
+	} else {
+		check = (unsigned long *) __get_free_pages(GFP_ATOMIC,
+				BITMAP_ORDER);
+		if (!check) {
+			printk("Error. Unable to allocate memory for local page flags.");
+			return 1;
+		}
+		clear_map(check);
+		*pagemap = check;
+		if (setnosave) {
+			struct page * firstpage = 
+				virt_to_page((unsigned long) check);
+			for (i = 0; i < (1 << BITMAP_ORDER); i++)
+				SetPageNosave(firstpage + i);
+		}
+	}
+	return 0;
+}
+
+/* freemap
+ *
+ * Description:	Free a local pageflags bitmap.
+ * Arguments:	unsigned long **: Pointer to the bitmap being freed.
+ * Note:	Map being freed might be Nosave.
+ */
+int free_local_pageflags(unsigned long ** pagemap)
+{
+	int i;
+	if (!*pagemap)
+		return 1;
+	else {
+		struct page * firstpage =
+			virt_to_page((unsigned long) *pagemap);
+		for (i = 0; i < (1 << BITMAP_ORDER); i++)
+			ClearPageNosave(firstpage + i);
+		free_pages((unsigned long) *pagemap, BITMAP_ORDER);
+		*pagemap = NULL;
+		return 0;
+	}
+}
+
+EXPORT_SYMBOL(suspend_snprintf);
+EXPORT_SYMBOL(allocate_local_pageflags);
+EXPORT_SYMBOL(free_local_pageflags);
+EXPORT_SYMBOL(find_proc_dir_entry);
#210 lore raw

Suspend 2 merge: 27/51: Block I/O module.

In reply to Nigel Cunningham

This is the code that does all the really hard work in reading and writing the image. It provides full asynchronous I/O, and in combination with the layer above, readahead where I/O needs to be synchronous (image decompression). I/O is also batched to further improve throughput. Some of the key parameters are user tunable, as the best setting varies from computer to computer.

kernel/power/suspend_block_io.c +827 -0
diff -ruN 812-suspend2-block-io-module-old/kernel/power/suspend_block_io.c 812-suspend2-block-io-module-new/kernel/power/suspend_block_io.c
@@ -0,0 +1,827 @@
+/*
+ * block_io.c
+ *
+ * Copyright 2004 Nigel Cunningham <[email protected]>
+ *
+ * Distributed under GPLv2.
+ * 
+ * This file contains block io functions for suspend2. These are
+ * used by the swapwriter and it is planned that they will also
+ * be used by the NFSwriter.
+ *
+ */
+
+#include <linux/suspend.h>
+#include <linux/module.h>
+#include <linux/highmem.h>
+#include <linux/blkdev.h>
+#include <linux/bio.h>
+#include <linux/kthread.h>
+
+#include "suspend.h"
+#include "block_io.h"
+#include "proc.h"
+#include "plugins.h"
+
+/* Bits in struct io_info->flags */
+#define IO_WRITING 1
+#define IO_RESTORE_PAGE_PROT 2
+#define IO_AWAITING_READ 3
+#define IO_AWAITING_WRITE 4
+#define IO_CLEANUP_IN_PROGRESS 5
+#define IO_HANDLE_PAGE_PROT 6
+
+#define USE_KEVENTD
+//#define TUNE_BATCHING
+
+/*
+ * ---------------------------------------------------------------
+ *
+ *     IO in progress information storage and helpers
+ *
+ * ---------------------------------------------------------------
+ */
+
+struct io_info {
+	struct bio * sys_struct;
+	long blocks[PAGE_SIZE/512];
+	struct page * buffer_page;
+	struct page * data_page;
+	unsigned long flags;
+	struct block_device * dev;
+	int blocks_used;
+	int block_size;
+	struct list_head list;
+	int readahead_index;
+	struct work_struct work;
+};
+
+static LIST_HEAD(ioinfo_free);
+static LIST_HEAD(ioinfo_ready_for_cleanup);
+static LIST_HEAD(ioinfo_busy);
+static LIST_HEAD(ioinfo_submit_batch);
+static spinlock_t ioinfo_lists_lock = SPIN_LOCK_UNLOCKED;
+
+static int submit_batch = 0, submit_batch_size = 32;
+static void submit_batched(void);
+
+struct task_struct * suspend_bio_task;
+
+/* [Max] number of I/O operations pending */
+static atomic_t outstanding_io;
+static int max_outstanding_io = 0;
+static int buffer_allocs, buffer_frees;
+
+/* [Max] number of pages used for above struct */
+static int infopages = 0;
+static int maxinfopages = 0;
+
+static volatile unsigned long suspend_readahead_flags[((MAX_READAHEAD + (8 * sizeof(unsigned long) - 1)) / (8 * sizeof(unsigned long)))];
+static spinlock_t suspend_readahead_flags_lock = SPIN_LOCK_UNLOCKED;
+static struct page * suspend_readahead_pages[MAX_READAHEAD];
+
+static unsigned long nr_schedule_calls[6];
+static unsigned long bio_jiffies = 0;
+
+static char * sch_caller[] = {
+	"get_io_info_struct       ",
+	"suspend_finish_all_io    ",
+	"wait_on_one_page         ",
+	"submit                   ",
+	"start_one                ",
+	"suspend_wait_on_readahead",
+};
+
+static void suspend_io_cleanup(void * data);
+
+static void do_bio_wait(int caller)
+{
+#ifndef USE_KEVENTD
+	int num_cleaned = 0;
+	struct io_info * this, * next = NULL;
+#endif
+	int device;
+
+	nr_schedule_calls[caller]++;
+	
+	/* Don't want to wait on I/O we haven't submitted! */
+	submit_batched();
+
+#ifndef USE_KEVENTD
+	if (!list_empty(&ioinfo_ready_for_cleanup))
+		list_for_each_entry_safe(this, next, &ioinfo_ready_for_cleanup, list) {
+			suspend_io_cleanup((void *) this);
+			num_cleaned++;
+			if (num_cleaned == 32)
+				break;
+		}
+#endif
+	for (device = 0; device < MAX_SWAPFILES; device++) {
+		struct block_device * bdev = swap_info[device].bdev;
+		if (bdev) {
+			request_queue_t * q = bdev_get_queue(bdev);
+			if (q && q->unplug_fn)
+				q->unplug_fn(q);
+		}
+		/* kblockd_flush(); io_schedule(); */
+	}
+	schedule();
+}
+
+/*
+ * cleanup_one
+ * 
+ * Description: Clean up after completing I/O on a page.
+ * Arguments:	struct io_info:	Data for I/O to be completed.
+ */
+static inline void cleanup_one(struct io_info * io_info)
+{
+	struct page * buffer_page;
+	struct page * data_page;
+	char *buffer_address, *data_address;
+	int reading;
+
+	buffer_page = io_info->buffer_page;
+	data_page = io_info->data_page;
+
+	/* 
+	 * Already being cleaned up? Can't happen while we're single
+	 * threaded, but a good check for later.
+	 */
+	
+	if (test_and_set_bit(IO_CLEANUP_IN_PROGRESS, &io_info->flags))
+		return;
+
+	reading = test_bit(IO_AWAITING_READ, &io_info->flags);
+	suspend_message(SUSPEND_WRITER, SUSPEND_HIGH, 0,
+		"Cleanup IO: [%p]\n", 
+		io_info);
+
+	if (reading && io_info->readahead_index == -1) {
+		/*
+		 * Copy the page we read into the buffer our caller provided.
+		 */
+		data_address = (char *) kmap(data_page);
+		buffer_address = (char *) kmap(buffer_page);
+		memcpy(data_address, buffer_address, PAGE_SIZE);
+		flush_dcache_page(data_page);
+		kunmap(data_page);
+		kunmap(buffer_page);
+	
+	}
+
+	if (!reading || io_info->readahead_index == -1) {
+		/* Sanity check */
+		if (page_count(buffer_page) != 2)
+			printk(KERN_EMERG "Cleanup IO: Page count is %d. Not good!\n",
+					page_count(buffer_page));
+		put_page(buffer_page);
+		__free_pages(buffer_page, 0);
+		buffer_frees++;
+	} else
+		put_page(buffer_page);
+	
+	atomic_dec(&outstanding_io);
+	bio_put(io_info->sys_struct);
+	io_info->sys_struct = NULL;
+	io_info->flags = 0;
+}
+
+/*
+ * get_io_info_struct
+ *
+ * Description:	Get an I/O struct.
+ * Returns:	Pointer to the struct prepared for use.
+ */
+static struct io_info * get_io_info_struct(void)
+{
+	unsigned long newpage = 0, flags;
+	struct io_info * this = NULL;
+	int remaining = 0;
+
+	do {
+		/* Have we reached our number-of-IOs-activate-at-one limit? */
+		if ((max_async_ios) && (atomic_read(&outstanding_io) >= max_async_ios)) {
+			do_bio_wait(0);
+			continue;
+		}
+
+		/* Can start a new I/O. Is there a free one? */
+		if (!list_empty(&ioinfo_free)) {
+			/* Yes. Grab it. */
+			spin_lock_irqsave(&ioinfo_lists_lock, flags);
+			break;
+		}
+
+		/* No. Need to allocate a new page for I/O info structs. */
+		newpage = get_zeroed_page(GFP_ATOMIC);
+		if (!newpage)
+			continue;
+
+		suspend_message(SUSPEND_MEMORY, SUSPEND_VERBOSE, 0,
+				"[NewIOPage %lx]", newpage);
+		infopages++;
+		if (infopages > maxinfopages)
+			maxinfopages++;
+
+		/* Prepare the new page for use. */
+		this = (struct io_info *) newpage;
+		remaining = PAGE_SIZE;
+		spin_lock_irqsave(&ioinfo_lists_lock, flags);
+		while (remaining >= (sizeof(struct io_info))) {
+			list_add_tail(&this->list, &ioinfo_free);
+			this = (struct io_info *) (((char *) this) + 
+					sizeof(struct io_info));
+			remaining -= sizeof(struct io_info);
+		}
+		break;
+	} while (1);
+
+	/* We have an I/O info struct. Move it to the busy list. */
+	this = list_entry(ioinfo_free.next, struct io_info, list);
+	list_move_tail(&this->list, &ioinfo_busy);
+	spin_unlock_irqrestore(&ioinfo_lists_lock, flags);
+	return this;
+}
+
+/*
+ * suspend_finish_all_io
+ *
+ * Description:	Finishes all IO and frees all IO info struct pages.
+ */
+static void suspend_finish_all_io(void)
+{
+	struct io_info * this, * next = NULL;
+	unsigned long flags;
+
+	/* Submit any pending write batch */
+	submit_batched();
+
+	/* Wait for all I/O to complete. */
+	while (atomic_read(&outstanding_io))
+		do_bio_wait(1);
+
+	/*
+	 * We're single threaded and all I/O is completed, so we shouldn't
+	 * need to use the spinlock, but let's be safe.
+	 */
+	spin_lock_irqsave(&ioinfo_lists_lock, flags);
+	
+	/* 
+	 * Two stages, to avoid using freed pages.
+	 *
+	 * First free all io_info structs on a page except the first.
+	 */
+	list_for_each_entry_safe(this, next, &ioinfo_free, list) {
+		if (((unsigned long) this) & ~PAGE_MASK)
+			list_del(&this->list);
+	}
+
+	/* 
+	 * Now we have only one reference to each page, and can safely
+	 * free pages, knowing we're not going to be trying to access the
+	 * same page after freeing it.
+	 */
+	list_for_each_entry_safe(this, next, &ioinfo_free, list) {
+		list_del(&this->list);
+		free_pages((unsigned long) this, 0);
+		infopages--;
+		suspend_message(SUSPEND_MEMORY, SUSPEND_VERBOSE, 0,
+				"[FreedIOPage %lx]", this);
+	}
+	
+	spin_unlock_irqrestore(&ioinfo_lists_lock, flags);
+}
+
+/*
+ * wait_on_one_page
+ *
+ * Description:	Wait for a particular I/O to complete.
+ */
+static void wait_on_one_page(struct io_info * io_info)
+{
+	do { do_bio_wait(2); } while (io_info->flags);
+}
+
+/*
+ * suspend_reset_io_stats
+ *
+ * Description:	Reset all our sanity-checking statistics.
+ */
+static void suspend_reset_io_stats(void)
+{
+	int i;
+	
+	max_outstanding_io = 0;
+	maxinfopages = 0;
+	buffer_allocs = buffer_frees = 0;
+	
+	for (i = 0; i < 6; i++)
+		nr_schedule_calls[i] = 0;
+	bio_jiffies = 0;
+}
+
+/*
+ * suspend_check_io_stats
+ *
+ * Description:	Check that our statistics look right and print
+ * 		any debugging info wanted.
+ */
+static void suspend_check_io_stats(void)
+{
+	int i;
+
+	BUG_ON(atomic_read(&outstanding_io));
+	BUG_ON(infopages);
+	BUG_ON(buffer_allocs != buffer_frees);
+	BUG_ON(!list_empty(&ioinfo_busy));
+	BUG_ON(!list_empty(&ioinfo_ready_for_cleanup));
+	BUG_ON(!list_empty(&ioinfo_free));
+
+	if (atomic_read(&outstanding_io))
+		suspend_message(SUSPEND_WRITER, SUSPEND_MEDIUM, 0,
+			"Outstanding_io after writing is %d.\n",
+			atomic_read(&outstanding_io));
+	suspend_message(SUSPEND_WRITER, SUSPEND_LOW, 0,
+			"Maximum outstanding_io was %d.\n",
+			max_outstanding_io);
+	if (infopages)
+		suspend_message(SUSPEND_WRITER, SUSPEND_MEDIUM, 0,
+				"Info pages is %d.\n",
+				infopages);
+	suspend_message(SUSPEND_WRITER, SUSPEND_LOW, 0,
+			"Max info pages was %d.\n",
+			maxinfopages);
+	if (buffer_allocs != buffer_frees)
+		suspend_message(SUSPEND_WRITER, SUSPEND_MEDIUM, 0,
+			"Buffer allocs (%d) != buffer frees (%d)",
+				buffer_allocs,
+				buffer_frees);
+	for(i = 0; i < 6; i++)
+		suspend_message(SUSPEND_WRITER, SUSPEND_MEDIUM, 0,
+			"Nr schedule calls %s: %lu.\n", sch_caller[i], nr_schedule_calls[i]);
+	suspend_message(SUSPEND_WRITER, SUSPEND_MEDIUM, 0,
+		"Jiffies waiting for bio calls:%lu.\n", bio_jiffies);
+}
+
+/* suspend_io_cleanup
+ */
+
+static void suspend_io_cleanup(void * data)
+{
+	struct io_info * io_info = (struct io_info *) data;
+	int readahead_index;
+	unsigned long flags;
+
+	/*
+	 * If this I/O was a readahead, remember its index.
+	 */
+	readahead_index = io_info->readahead_index;
+
+	/*
+	 * Do the cleanup.
+	 */
+	cleanup_one(io_info);
+
+	/*
+	 * Record the readahead as done.
+	 */
+	if (readahead_index > -1) {
+		int index = readahead_index/(8 * sizeof(unsigned long));
+		int bit = readahead_index - (index * 8 * sizeof(unsigned long));
+		spin_lock_irqsave(&suspend_readahead_flags_lock, flags);
+		set_bit(bit, &suspend_readahead_flags[index]);
+		spin_unlock_irqrestore(&suspend_readahead_flags_lock, flags);
+	}
+
+	/*
+	 * Add it to the free list.
+	 */
+	spin_lock_irqsave(&ioinfo_lists_lock, flags);
+	list_move_tail(&io_info->list, &ioinfo_free);
+	spin_unlock_irqrestore(&ioinfo_lists_lock, flags);
+}
+
+/*
+ * suspend_end_bio
+ *
+ * Description:	Function called by block driver from interrupt context when I/O
+ * 		is completed. This is the reason we use spinlocks in
+ * 		manipulating the io_info lists. 		
+ * 		Nearly the fs/buffer.c version, but we want to mark the page as 
+ * 		done in our own structures too.
+ */
+
+static int suspend_end_bio(struct bio * bio, unsigned int num, int err)
+{
+	struct io_info *io_info = (struct io_info *) bio->bi_private;
+	unsigned long flags;
+
+	spin_lock_irqsave(&ioinfo_lists_lock, flags);
+	list_move_tail(&io_info->list, &ioinfo_ready_for_cleanup);
+	spin_unlock_irqrestore(&ioinfo_lists_lock, flags);
+
+#ifdef USE_KEVENTD
+	INIT_WORK(&io_info->work, suspend_io_cleanup, (void *) io_info);
+	schedule_work(&io_info->work);
+#endif
+	return 0;
+}
+
+/**
+ *	submit - submit BIO request.
+ *	@rw:	READ or WRITE.
+ *	@io_info: IO info structure.
+ *
+ *	Straight from the textbook - allocate and initialize the bio.
+ *	If we're writing, make sure the page is marked as dirty.
+ *	Then submit it and carry on.
+ */
+
+static int submit(int rw, struct io_info * io_info)
+{
+	int error = 0;
+	struct bio * bio = NULL;
+	unsigned long j1 = jiffies;
+
+	while (!bio) {
+		bio = bio_alloc(GFP_ATOMIC,1);
+		if (!bio)
+			do_bio_wait(3);
+	}
+
+	bio->bi_sector = io_info->blocks[0] << (PAGE_SHIFT - 9);
+	bio->bi_bdev = io_info->dev;
+	bio->bi_private = io_info;
+	bio->bi_end_io = suspend_end_bio;
+	io_info->sys_struct = bio;
+
+	if (bio_add_page(bio, io_info->buffer_page, PAGE_SIZE, 0) < PAGE_SIZE) {
+		printk("ERROR: adding page to bio at %ld\n",
+				io_info->blocks[0]);
+		bio_put(bio);
+		return -EFAULT;
+	}
+
+	if (rw == WRITE)
+		bio_set_pages_dirty(bio);
+	submit_bio(rw,bio);
+	bio_jiffies += jiffies - j1;
+	return error;
+}
+
+/*
+ * suspend_set_block_size
+ *
+ * Description: Set the blocksize for a bdev. This is a separate function
+ * 		because we have different versions for 2.4 and 2.6.
+ */
+static int suspend_set_block_size(struct block_device * bdev, int size)
+{
+	return set_blocksize(bdev, size);
+}
+
+static int suspend_get_block_size(struct block_device * bdev)
+{
+	return block_size(bdev);
+}
+
+/* 
+ * We don't need to worry about new requests being added to the list;
+ * we're called from process context 
+ */
+static void submit_batched(void)
+{
+	unsigned long flags;
+	struct io_info * this, * next = NULL;
+	
+	list_for_each_entry_safe(this, next, &ioinfo_submit_batch, list) {
+		spin_lock_irqsave(&ioinfo_lists_lock, flags);
+		list_move_tail(&this->list, &ioinfo_busy);
+		spin_unlock_irqrestore(&ioinfo_lists_lock, flags);
+		if (test_bit(IO_AWAITING_READ, &this->flags))
+			submit(READ, this);
+		else
+			submit(WRITE, this);
+	}
+	submit_batch = 0;
+}
+static void add_to_batch(struct io_info * io_info)
+{
+	unsigned long flags;
+	
+	spin_lock_irqsave(&ioinfo_lists_lock, flags);
+	/* We have an I/O info struct. Move it to the batch list. */
+	list_move_tail(&io_info->list, &ioinfo_submit_batch);
+	spin_unlock_irqrestore(&ioinfo_lists_lock, flags);
+
+	submit_batch++;
+
+	if (submit_batch == submit_batch_size)
+		submit_batched();
+}
+/*
+ * start_one
+ *
+ * Description:	Prepare and start a read or write operation.
+ * 		Note that we use our own buffer for reading or writing.
+ * 		This simplifies doing readahead and asynchronous writing.
+ * 		We can begin a read without knowing the location into which
+ * 		the data will eventually be placed, and the buffer passed
+ * 		for a write can be reused immediately (essential for the
+ * 		plugins system).
+ * 		Failure? What's that?
+ * Returns:	The io_info struct created.
+ */
+static struct io_info * start_one(int rw, struct submit_params * submit_info)
+{
+	struct io_info * io_info = get_io_info_struct();
+	unsigned long buffer_virt = 0;
+	char * to, * from;
+	struct page * buffer_page;
+	int i;
+
+	if (!io_info)
+		return NULL;
+
+	/* Get our local buffer */
+	suspend_message(SUSPEND_WRITER, SUSPEND_HIGH, 1,
+			"Start_IO: [%p]", io_info);
+	
+	/* Copy settings to the io_info struct */
+	io_info->data_page = submit_info->page;
+	io_info->readahead_index = submit_info->readahead_index;
+
+	if (io_info->readahead_index == -1) {
+		while (!(buffer_virt = get_zeroed_page(GFP_ATOMIC)))
+			do_bio_wait(4);
+
+		buffer_allocs++;
+		suspend_message(SUSPEND_WRITER, SUSPEND_HIGH, 0,
+				"[ALLOC BUFFER]->%d",
+				real_nr_free_pages());
+		buffer_page = virt_to_page(buffer_virt);
+	
+		io_info->buffer_page = buffer_page;
+	} else {
+		unsigned long flags;
+		int index = io_info->readahead_index/(8 * sizeof(unsigned long));
+		int bit = io_info->readahead_index - index * 8 * sizeof(unsigned long);
+
+		spin_lock_irqsave(&suspend_readahead_flags_lock, flags);
+		clear_bit(bit, &suspend_readahead_flags[index]);
+		spin_unlock_irqrestore(&suspend_readahead_flags_lock, flags);
+
+		io_info->buffer_page = buffer_page = submit_info->page;
+	}
+
+	/* If writing, copy our data. The data is probably in
+	 * lowmem, but we cannot be certain. If there is no
+	 * compression/encryption, we might be passed the
+	 * actual source page's address. */
+	if (rw == WRITE) {
+		set_bit(IO_WRITING, &io_info->flags);
+
+		to = (char *) buffer_virt;
+		from = kmap_atomic(io_info->data_page, KM_USER1);
+		memcpy(to, from, PAGE_SIZE);
+		flush_dcache_page(io_info->data_page);
+		flush_dcache_page(buffer_page);
+		kunmap_atomic(from, KM_USER1);
+	}
+
+	/* Submit the page */
+	get_page(buffer_page);
+	
+	io_info->dev = submit_info->dev;
+	for (i = 0; i < submit_info->blocks_used; i++)
+		io_info->blocks[i] = submit_info->blocks[i];
+	io_info->blocks_used = submit_info->blocks_used;
+	io_info->block_size = PAGE_SIZE / submit_info->blocks_used;
+
+	if (rw == READ)
+		set_bit(IO_AWAITING_READ, &io_info->flags);
+	else
+		set_bit(IO_AWAITING_WRITE, &io_info->flags);
+
+	suspend_message(SUSPEND_WRITER, SUSPEND_HIGH, 1,
+			"-> (PRE BRW) %d\n",
+			real_nr_free_pages());
+
+	if (submit_batch_size > 1)
+		add_to_batch(io_info);
+	else
+	 	submit(rw, io_info);
+	
+	atomic_inc(&outstanding_io);
+	if (atomic_read(&outstanding_io) > max_outstanding_io)
+		max_outstanding_io++;
+	
+	return io_info;
+}
+
+static int suspend_do_io(int rw, 
+		struct submit_params * submit_info, int syncio)
+{
+	struct io_info * io_info = start_one(rw, submit_info);
+	if (!io_info)
+		return 1;
+	else if (syncio)
+		wait_on_one_page(io_info);
+
+	/* If we were the only one, clean everything up */
+	if (!atomic_read(&outstanding_io))
+		suspend_finish_all_io();
+	return 0;
+} 
+
+/* We used to use bread here, but it doesn't correctly handle
+ * blocksize != PAGE_SIZE. Now we create a submit_info to get the data we
+ * want and use our normal routines (synchronously).
+ */
+
+static int suspend_bdev_page_io(int rw, struct block_device * bdev, long pos,
+		struct page * page)
+{
+	struct submit_params submit_info;
+
+	submit_info.page = page;
+	submit_info.dev = bdev;
+
+	submit_info.blocks[0] = pos;
+	submit_info.blocks_used = 1;
+	submit_info.readahead_index = -1;
+	return suspend_do_io(rw, &submit_info, 1);
+}
+
+/*
+ * wait_on_readahead
+ *
+ * Wait until a particular readahead is ready.
+ */
+static void suspend_wait_on_readahead(int readahead_index)
+{
+	int index = readahead_index/(8 * sizeof(unsigned long));
+	int bit = readahead_index - index * 8 * sizeof(unsigned long);
+
+	/* read_ahead_index is the one we want to return */
+	while (!test_bit(bit, &suspend_readahead_flags[index]))
+		do_bio_wait(5);
+}
+
+/*
+ * readahead_done
+ *
+ * Returns whether the readahead requested is ready.
+ */
+
+static int suspend_readahead_ready(int readahead_index)
+{
+	int index = readahead_index/(8 * sizeof(unsigned long));
+	int bit = readahead_index - (index * 8 * sizeof(unsigned long));
+
+	return test_bit(bit, &suspend_readahead_flags[index]);
+}
+
+/* suspend_readahead_prepare
+ * Set up for doing readahead on an image */
+static int suspend_prepare_readahead(int index)
+{
+	unsigned long new_page = get_zeroed_page(GFP_ATOMIC);
+
+	if(!new_page) {
+		printk("No page for readahead %d.\n", index);
+		return -ENOMEM;
+	}
+
+	suspend_bio_ops.readahead_pages[index] = virt_to_page(new_page);
+	return 0;
+}
+
+/* suspend_readahead_cleanup
+ * Clean up structures used for readahead */
+static void suspend_cleanup_readahead(int page)
+{
+	__free_pages(suspend_bio_ops.readahead_pages[page], 0);
+	suspend_bio_ops.readahead_pages[page] = 0;
+	return;
+}
+
+static unsigned long suspend_bio_memory_needed(void)
+{
+	return (REAL_MAX_ASYNC * (PAGE_SIZE + sizeof(struct request) +
+				sizeof(struct bio) + sizeof(struct io_info)));
+}
+
+#if 0
+static int suspend_bio_kthread(void * data)
+{
+	return 0;
+}
+
+static int start_suspend_bio_thread(void)
+{
+	
+	suspend_bio_task = kthread_run(suspend_bio_kthread, NULL,
+		PF_NOFREEZE, "suspend_bio");
+
+	if (IS_ERR(suspend_bio_task)) {
+		printk("suspend_bio thread could not be started.\n");
+		return -EPERM;
+	}
+
+	return 0;
+}
+
+static void end_suspend_bio_thread(void)
+{
+}
+#endif
+
+static struct suspend_proc_data proc_params[] = {
+	{ .filename			= "async_io_limit", 
+	  .permissions			= PROC_RW,
+	  .type				= SUSPEND_PROC_DATA_INTEGER,
+	  .data = {
+		  .integer = {
+			  .variable	= &max_async_ios,
+			  .minimum	= 1,
+			  .maximum	= MAX_READAHEAD,
+		  }
+	  }
+	},
+	
+#ifdef CONFIG_SOFTWARE_SUSPEND_DEBUG
+#ifdef TUNE_BATCHING
+	{ .filename			= "submit_batch_size", 
+	  .permissions			= PROC_RW,
+	  .type				= SUSPEND_PROC_DATA_INTEGER,
+	  .data = {
+		  .integer = {
+			  .variable	= &submit_batch_size,
+			  .minimum	= 1,
+			  .maximum	= 512,
+		  }
+	  }
+	},
+#endif
+#endif
+};
+
+struct suspend_bio_ops suspend_bio_ops = {
+	.set_block_size = suspend_set_block_size,
+	.get_block_size = suspend_get_block_size,
+	.submit_io = suspend_do_io,
+	.bdev_page_io = suspend_bdev_page_io,
+	.prepare_readahead = suspend_prepare_readahead,
+	.cleanup_readahead = suspend_cleanup_readahead,
+	.readahead_pages = suspend_readahead_pages,
+	.wait_on_readahead = suspend_wait_on_readahead,
+	.check_io_stats = suspend_check_io_stats,
+	.reset_io_stats = suspend_reset_io_stats,
+	.finish_all_io = suspend_finish_all_io,
+	.readahead_ready = suspend_readahead_ready,
+};
+
+EXPORT_SYMBOL(suspend_bio_ops);
+
+static struct suspend_plugin_ops suspend_blockwriter_ops = 
+{
+	.name					= "Block I/O",
+	.type					= MISC_PLUGIN,
+	//.initialise				= start_suspend_bio_thread,
+	//.cleanup				= end_suspend_bio_thread,
+	.memory_needed				= suspend_bio_memory_needed,
+};
+
+static __init int suspend_block_io_load(void)
+{
+	int i, numfiles = sizeof(proc_params) / sizeof(struct suspend_proc_data);
+	int result;
+
+	if (!(result = suspend_register_plugin(&suspend_blockwriter_ops))) {
+		for (i=0; i< numfiles; i++)
+			suspend_register_procfile(&proc_params[i]);
+	}
+
+	return result;
+}
+
+#ifdef MODULE
+static __exit void suspend_block_io_unload(void)
+{
+	int i, numfiles = sizeof(proc_params) / sizeof(struct suspend_proc_data);
+
+	for (i=0; i< numfiles; i++)
+		suspend_unregister_procfile(&proc_params[i]);
+	suspend_unregister_plugin(&suspend_blockwriter_ops);
+}
+
+module_init(suspend_block_io_load);
+module_exit(suspend_block_io_unload);
+MODULE_LICENSE("GPL");
+MODULE_AUTHOR("Nigel Cunningham");
+MODULE_DESCRIPTION("Suspend2 block io functions");
+#else
+late_initcall(suspend_block_io_load);
+#endif
#211 lore raw

Suspend 2 merge: 29/51: Clear swapfile bdev in swapoff.

In reply to Nigel Cunningham

Suspend uses the bdev field as its means of telling which swap devices are in use. (This info needs to be used at resume time without actually doing the swapon[s] again). In order to avoid an oops in the suspend code if the user turns off a swap device, this small addition is necessary. (If you want the long explanation, feel free to ask!)

mm/swapfile.c +1 -0
diff -ruN 816-clear-swapfile-bdev-in-swapoff-old/mm/swapfile.c 816-clear-swapfile-bdev-in-swapoff-new/mm/swapfile.c
@@ -1179,6 +1179,7 @@
 	swap_file = p->swap_file;
 	p->swap_file = NULL;
 	p->max = 0;
+	p->bdev = NULL;
 	swap_map = p->swap_map;
 	p->swap_map = NULL;
 	p->flags = 0;
#90 lore raw

Re: Suspend 2 merge: 31/51: Export tlb flushing

In reply to Nigel Cunningham

--Nigel Cunningham <[email protected]> wrote (on Wednesday, November 24, 2004 23:59:50 +1100):

Quoted 2 lines

This patch adds a do_flush_tlb_all function that does the SMP-appropriate thing for suspend after the image is restored.

Is software suspend only designed for i386, or is that the only arch that didn't have such a function already? Seems like too low a level to be exporting to me.

M.

Quoted 43 lines

diff -ruN 818-tlb-flushing-functions-old/arch/i386/kernel/smp.c 818-tlb-flushing-functions-new/arch/i386/kernel/smp.c

arch/i386/kernel/smp.c +1 -1
@@ -476,7 +476,7 @@
 	preempt_enable();
 }
 
-static void do_flush_tlb_all(void* info)
+void do_flush_tlb_all(void* info)
 {
 	unsigned long cpu = smp_processor_id();
 

diff -ruN 818-tlb-flushing-functions-old/include/asm-i386/tlbflush.h 818-tlb-flushing-functions-new/include/asm-i386/tlbflush.h

include/asm-i386/tlbflush.h +5 -1
@@ -82,6 +82,7 @@
 #define flush_tlb() __flush_tlb()
 #define flush_tlb_all() __flush_tlb_all()
 #define local_flush_tlb() __flush_tlb()
+#define local_flush_tlb_all() __flush_tlb_all();
 
 static inline void flush_tlb_mm(struct mm_struct *mm)
 {
@@ -114,6 +115,10 @@
 extern void flush_tlb_current_task(void);
 extern void flush_tlb_mm(struct mm_struct *);
 extern void flush_tlb_page(struct vm_area_struct *, unsigned long);
+extern void do_flush_tlb_all(void * info);
+
+#define local_flush_tlb_all() \
+	do_flush_tlb_all(NULL);
 
 #define flush_tlb()	flush_tlb_current_task()
 
 
 
-

To unsubscribe from this list: send the line "unsubscribe linux-kernel" in the body of a message to [email protected]
More majordomo info at http://vger.kernel.org/majordomo-info.html
Please read the FAQ at http://www.tux.org/lkml/

#8 lore raw

Re: Suspend 2 merge: 10/51: Exports for suspend built as modules.

In reply to Nigel Cunningham

kernel/sched.c line 3801

Quoted 11 lines · Nigel Cunningham

New exports for suspend. I've cut them down some as a result of the last review, but could perhaps do more? Would people prefer to see a single struct wrapping exported functions?

kernel/sched.c +1 -0
@@ -3798,6 +3798,7 @@
 
 	read_unlock(&tasklist_lock);
 }
+EXPORT_SYMBOL(show_state);

this one is ok i think, but make it EXPORT_SYMBOL_GPL() please.

Ingo

#35 lore raw

Re: Suspend 2 merge: 8/51: /proc/acpi/sleep hook.

In reply to Nigel Cunningham
Quoted 1 line · Nigel Cunningham

Same thing as the previous patch, but for /proc/acpi/sleep.

And again totally bogus. Make sure swsusp and swsusp2 export the same interface. Preferably the old one, but if it absolutely doesn't fit your needs submit a patch to switch the old code to the new interface first.

#79 lore raw

Re: Suspend 2 merge: 26/51: Kconfig and makefile.

In reply to Nigel Cunningham

Hi,

Quoted 12 lines · Nigel Cunningham
kernel/power/Kconfig +12 -0
+menu "Software Suspend 2"
+
+config SOFTWARE_SUSPEND2_CORE
+	tristate "Software Suspend 2"
+	depends on PM
+	select SOFTWARE_SUSPEND2
+	---help---
+	  Software Suspend 2 is the 'new and improved' suspend support. You
+	  can now build it as modules, but be aware that this requires
+	  initrd support (the modules you use in saving the image have to
+	  be loaded in order for you to be able to resume!)
+	  

kernel/power/Kconfig line 99

Quoted 10 lines
kernel/power/Kconfig +10 -0
+	  See the Software Suspend home page (softwaresuspend.berlios.de)
+	  for FAQs, HOWTOs and other documentation.
+
+	config SOFTWARE_SUSPEND2
+	bool
+
+	if SOFTWARE_SUSPEND2
+		config SOFTWARE_SUSPEND2_WRITER
+		bool
+

Please don't use such indentations.
There is no need to use to select here either. If you really want to make it modular (and you can convince Christoph), you want to do something like this:

config SOFTWARE_SUSPEND2
tristate "Software Suspend 2"
depends on PM

config SOFTWARE_SUSPEND2_BUILTIN
def_bool SOFTWARE_SUSPEND2

and let everything else depend on SOFTWARE_SUSPEND2.

kernel/power/Kconfig line 106

Quoted 4 lines
kernel/power/Kconfig +4 -0
+		config SOFTWARE_SUSPEND_SWAPWRITER
+			tristate '   Swap Writer'
+			depends on SWAP && SOFTWARE_SUSPEND2_CORE
+			select SOFTWARE_SUSPEND2_WRITER

This select is also bogus.

kernel/power/Makefile line 12

Quoted 4 lines
kernel/power/Makefile +4 -0
+
+ifeq ($(CONFIG_SOFTWARE_SUSPEND2),y)
+obj-y	+= suspend_builtin.o proc.o
+endif

Use SOFTWARE_SUSPEND2_BUILTIN here without the ifeq.

bye, Roman

#212 lore raw

Suspend 2 merge: 40/51: Prepare image

In reply to Nigel Cunningham

This file contains the main routines used to prepare an image. Note that this is potentially an iterative process: our allocation of metadata for the image we know about may change the characteristics of the image and require the allocation of a few extra pages. The number of iterations is definitely bound (and the user can always press escape - if they've enabled it - to cancel if I was wrong here).

We account for every page of memory. They are either:

- LRU -> pageset 2
- allocated for memory pool -> pageset 1
- otherwise used -> pageset 1
- unused and not allocated for memory pool -> not saved
- used but marked NoSave -> not saved

Plugins tell us how much memory they need, and we put that much plus a little more in the memory pool. (Can't account for device drivers).

kernel/power/prepare_image.c +1050 -0
diff -ruN 830-prepare-image-old/kernel/power/prepare_image.c 830-prepare-image-new/kernel/power/prepare_image.c
@@ -0,0 +1,1050 @@
+/*
+ * kernel/power/prepare_image.c
+ *
+ * Copyright (C) 2003-2004 Nigel Cunningham <[email protected]>
+ *
+ * This file is released under the GPLv2.
+ *
+ * We need to eat memory until we can:
+ * 1. Perform the save without changing anything (RAM_NEEDED < max_mapnr)
+ * 2. Fit it all in available space (active_writer->available_space() >= STORAGE_NEEDED)
+ * 3. Reload the pagedir and pageset1 to places that don't collide with their
+ *    final destinations, not knowing to what extent the resumed kernel will
+ *    overlap with the one loaded at boot time. I think the resumed kernel should overlap
+ *    completely, but I don't want to rely on this as it is an unproven assumption. We
+ *    therefore assume there will be no overlap at all (worse case).
+ * 4. Meet the user's requested limit (if any) on the size of the image.
+ *    The limit is in MB, so pages/256 (assuming 4K pages).
+ *
+ *    (Final test in save_image doesn't use EATEN_ENOUGH_MEMORY)
+ */
+
+#define SUSPEND_PREPARE_IMAGE_C
+
+#include <linux/kernel.h>
+#include <linux/module.h>
+#include <linux/suspend.h>
+#include <linux/highmem.h>
+#include <linux/notifier.h>
+
+#include "suspend.h"
+#include "pageflags.h"
+#include "plugins.h"
+#include "proc.h"
+
+extern int pageset1_sizelow, pageset2_sizelow;
+extern unsigned long orig_mem_free;
+extern void mark_pages_for_pageset2(void);
+extern int image_size_limit;
+extern int fill_suspend_memory_pool(int sizesought);
+
+int suspend_amount_grabbed = 0;
+static int arefrozen = 0, numnosave = 0;
+static int header_space_allocated = 0;
+extern unsigned long forced_ps1_size, forced_ps2_size;
+
+/*
+ * generate_free_page_map
+ *
+ * Description:	This routine generates a bitmap of free pages from the
+ * 		lists used by the memory manager. We then use the bitmap
+ * 		to quickly calculate which pages to save and in which
+ * 		pagesets.
+ */
+static void generate_free_page_map(void) 
+{
+	int i, order, loop, cpu;
+	struct page * page;
+	unsigned long flags;
+	struct zone *zone;
+	struct per_cpu_pageset *pset;
+
+	for(i=0; i < max_mapnr; i++)
+		SetPageInUse(mem_map+i);
+	
+	for_each_zone(zone) {
+		if (!zone->present_pages)
+			continue;
+		spin_lock_irqsave(&zone->lock, flags);
+		for (order = MAX_ORDER - 1; order >= 0; --order) {
+			list_for_each_entry(page, &zone->free_area[order].free_list, lru)
+				for(loop=0; loop < (1 << order); loop++) {
+					ClearPageInUse(page+loop);
+					ClearPagePageset2(page+loop);
+				}
+		}
+
+		
+		for (cpu = 0; cpu < NR_CPUS; cpu++) {
+			if (!cpu_possible(cpu))
+				continue;
+
+			pset = &zone->pageset[cpu];
+
+			for (i = 0; i < ARRAY_SIZE(pset->pcp); i++) {
+				struct per_cpu_pages *pcp;
+				struct page * page;
+
+				pcp = &pset->pcp[i];
+				list_for_each_entry(page, &pcp->list, lru) {
+					ClearPageInUse(page);
+					ClearPagePageset2(page);
+				}
+			}
+		}
+		
+		spin_unlock_irqrestore(&zone->lock, flags);
+	}
+}
+
+/* size_of_free_region
+ * 
+ * Description:	Return the number of pages that are free, beginning with and 
+ * 		including this one.
+ */
+static int size_of_free_region(struct page * page)
+{
+	struct page * posn = page;
+
+	while (((posn-mem_map) < max_mapnr) && (!PageInUse(posn))) 
+		posn++;
+	return (posn - page);
+}
+
+static void display_reserved_pages(void)
+{
+	int loop;
+	int rangemin = -1;
+
+	for (loop = 0; loop < max_mapnr; loop++) {
+		if (PageReserved(mem_map+loop)) {
+			if (rangemin == -1)
+				rangemin = loop;
+		} else {
+			if (rangemin > -1) {
+				printk("Reserved pages from %p to %p.\n",
+					page_address(mem_map+rangemin),
+					((char *) page_address(mem_map + loop)) - 1);
+				rangemin = -1;
+			}
+		}
+	}
+
+	if (rangemin > -1)
+		printk("Reserved pages from %p to %p.\n",
+			page_address(mem_map+rangemin),
+			((char *) page_address(mem_map + max_mapnr)) - 1);
+}
+
+/* 
+ * Description:	Display which pages are marked Nosave.
+ */
+void display_nosave_pages(void)
+{
+	int loop;
+	int rangemin = -1;
+
+	if (!TEST_DEBUG_STATE(SUSPEND_NOSAVE))
+		return;
+
+	display_reserved_pages();
+
+	for (loop = 0; loop < max_mapnr; loop++) {
+		if (PageNosave(mem_map+loop)) {
+			if (rangemin == -1)
+				rangemin = loop;
+		} else {
+			if (rangemin > -1) {
+				printk("Nosave pages from %p to %p.\n",
+					page_address(mem_map+rangemin),
+					((char *) page_address(mem_map + loop)) - 1);
+				rangemin = -1;
+			}
+		}
+	}
+
+	if (rangemin > -1)
+		printk("Nosave pages from %p to %p.\n",
+			page_address(mem_map+rangemin),
+			((char *) page_address(mem_map + max_mapnr)) - 1);
+}
+
+/*
+ * count_data_pages
+ *
+ * This routine generates our lists of pages to be stored in each
+ * pageset. Since we store the data using ranges, and adding new
+ * ranges might allocate a new range page, this routine may well
+ * be called more than once.
+ */
+static struct pageset_sizes_result count_data_pages(void)
+{
+	int chunk_size, loop, numfree = 0;
+	int ranges = 0, currentrange = 0;
+	int usepagedir2;
+	int rangemin = 0;
+	struct pageset_sizes_result result;
+	struct range * rangepointer;
+	unsigned long value;
+#ifdef CONFIG_HIGHMEM
+	unsigned long highstart_pfn = get_highstart_pfn();
+#endif
+
+	result.size1 = 0;
+	result.size1low = 0;
+	result.size2 = 0;
+	result.size2low = 0;
+	result.needmorespace = 0;
+
+	numnosave = 0;
+
+	put_range_chain(&pagedir1.origranges);
+	put_range_chain(&pagedir1.destranges);
+	put_range_chain(&pagedir2.origranges);
+	pagedir2.destranges.first = NULL;
+	pagedir2.destranges.size = 0;
+
+	generate_free_page_map();
+
+	if (TEST_RESULT_STATE(SUSPEND_ABORTED)) {
+		result.size1 = -1;
+		result.size1low = -1;
+		result.size2 = -1;
+		result.size2low = -1;
+		result.needmorespace = 0;
+		return result;
+	}
+
+	if (max_mapnr != num_physpages) {
+		abort_suspend("Max_mapnr is not equal to num_physpages.");
+		result.size1 = -1;
+		result.size1low = -1;
+		result.size2 = -1;
+		result.size2low = -1;
+		result.needmorespace = 0;
+		return result;
+	}
+	/*
+	 * Pages not to be saved are marked Nosave irrespective of being reserved
+	 */
+	for (loop = 0; loop < max_mapnr; loop++) {
+		if (PageNosave(mem_map+loop)) {
+			numnosave++;
+			if (currentrange) {
+				append_to_range_chain(currentrange, rangemin, loop - 1);
+				rangemin = loop;
+				currentrange = 0;
+			}
+			continue;
+		}
+
+		if (!PageReserved(mem_map+loop)) {
+			if ((chunk_size=size_of_free_region(mem_map+loop))!=0) {
+				if (currentrange) {
+					append_to_range_chain(currentrange, rangemin, loop - 1);
+					rangemin = loop;
+					currentrange = 0;
+				}
+				numfree += chunk_size;
+				loop += chunk_size - 1;
+				continue;
+			}
+		} else {
+#ifdef CONFIG_HIGHMEM
+			if (loop >= highstart_pfn) {
+				/* HighMem pages may be marked Reserved. We ignore them. */
+				numnosave++;
+				if (currentrange) {
+					append_to_range_chain(currentrange, rangemin, loop - 1);
+					rangemin = loop;
+					currentrange = 0;
+				}
+				continue;
+			}
+#endif
+		};
+
+		usepagedir2 = !!PagePageset2(mem_map+loop);
+
+		if (currentrange != (1 + usepagedir2)) {
+			if (currentrange)
+				append_to_range_chain(currentrange, rangemin, loop - 1);
+			currentrange = usepagedir2 + 1;
+			rangemin = loop;
+			ranges++;
+		}
+		
+		if (usepagedir2) {
+			result.size2++;
+			if (!PageHighMem(mem_map+loop))
+				result.size2low++;
+		} else {
+			result.size1++;
+			if (!PageHighMem(mem_map+loop))
+				result.size1low++;
+		}
+	}
+	
+	if (currentrange)
+		append_to_range_chain(currentrange, rangemin, loop - 1);
+
+	if ((pagedir1.pageset_size) && (result.size1 > pagedir1.pageset_size))
+		result.needmorespace = 1;
+	if ((pagedir2.pageset_size) && (result.size2 > pagedir2.pageset_size))
+		result.needmorespace = 1;
+	suspend_message(SUSPEND_RANGES, SUSPEND_MEDIUM, 0, "Counted %d ranges.\n", ranges);
+	pagedir2.destranges.first = pagedir2.origranges.first;
+	pagedir2.destranges.size = pagedir2.origranges.size;
+	range_for_each(&pagedir1.allocdranges, rangepointer, value) {
+		add_to_range_chain(&pagedir1.destranges, value);
+	}
+
+	suspend_message(SUSPEND_EAT_MEMORY, SUSPEND_MEDIUM, 0,
+		"Count data pages: Set1 (%d) + Set2 (%d) + Nosave (%d) + NumFree (%d) = %d.\n",
+		result.size1, result.size2, numnosave, numfree,
+		result.size1 + result.size2 + numnosave + numfree);
+	return result;
+}
+
+/* amount_needed
+ *
+ * Calculates the amount by which the image size needs to be reduced to meet
+ * our constraints.
+ */
+static int amount_needed(int use_image_size_limit)
+{
+
+	int max1 = max( (int) (RAM_TO_SUSPEND - real_nr_free_pages() - 
+			  nr_free_highpages() - suspend_amount_grabbed),
+			((int) (STORAGE_NEEDED(1) -  
+			  active_writer->ops.writer.storage_available())));
+	if (use_image_size_limit)
+		return max( max1,
+			    (image_size_limit > 0) ? 
+			    ((int) (STORAGE_NEEDED(1) - (image_size_limit << 8))) : 0);
+	return max1;
+}
+
+#define EATEN_ENOUGH_MEMORY() (amount_needed(1) < 1)
+unsigned long storage_available = 0;
+
+/* display_stats
+ *
+ * Display the vital statistics.
+ */
+#ifdef CONFIG_SOFTWARE_SUSPEND_DEBUG
+static void display_stats(void)
+{ 
+	unsigned long storage_allocated = active_writer->ops.writer.storage_allocated();
+	suspend_message(SUSPEND_EAT_MEMORY, SUSPEND_MEDIUM, 1,
+		"Free:%d+%d+%d=%d(%d). Sets:%d(%d),%d(%d). Header:%d. Nosave:%d-%d-%d=%d. Storage:%d/%lu(%lu). Needed:%d|%d|%d.\n", 
+		
+		/* Free */
+		real_nr_free_pages(), suspend_amount_grabbed, suspend_memory_pool_level(0),
+		real_nr_free_pages() + suspend_amount_grabbed + suspend_memory_pool_level(0),
+		real_nr_free_pages() - nr_free_highpages(),
+		
+		/* Sets */
+		pageset1_size, pageset1_sizelow,
+		pageset2_size, pageset2_sizelow,
+
+		/* Header */
+		num_range_pages,
+
+		/* Nosave */
+		numnosave, pagedir1.allocdranges.size, suspend_amount_grabbed,
+		numnosave - pagedir1.allocdranges.size - suspend_amount_grabbed,
+
+		/* Storage - converted to pages for comparison */
+		storage_allocated,
+		STORAGE_NEEDED(1),
+		storage_available,
+
+		/* Needed */
+		RAM_TO_SUSPEND - real_nr_free_pages() - nr_free_highpages() - suspend_amount_grabbed,
+		STORAGE_NEEDED(1) - storage_available, 
+		(image_size_limit > 0) ? (STORAGE_NEEDED(1) - (image_size_limit << 8)) : 0);
+}
+#else
+#define display_stats() do { } while(0)
+#endif
+
+struct bloat_pages {
+	struct bloat_pages * next;
+	int order;
+};
+
+static struct bloat_pages * bloat_pages = NULL;
+
+void free_pageset_size_bloat(void)
+{
+	while (bloat_pages) {
+		struct bloat_pages * next = bloat_pages->next;
+		free_pages((unsigned long) bloat_pages, bloat_pages->order);
+		bloat_pages = next;
+	}
+}
+
+#define redo_counts() \
+{ \
+	suspend_message(SUSPEND_PAGESETS, SUSPEND_VERBOSE, 1, \
+		"Recalculating counts. Currently %ld & %ld. ", \
+		ps1_get, ps2_get);  \
+	result = count_data_pages(); \
+	if (forced_ps1_size) \
+		ps1_get = forced_ps1_size - result.size1 - drop_one; \
+	if (forced_ps2_size) \
+		ps2_get = forced_ps2_size - result.size2; \
+	suspend_message(SUSPEND_PAGESETS, SUSPEND_VERBOSE, 1, \
+		"Now %ld and %ld.\n", ps1_get, ps2_get); \
+}
+
+void increase_pageset_size(struct pageset_sizes_result result)
+{
+	long ps1_get = 0, ps2_get = 0, order, j;
+	int drop_one = 0;
+
+	if (forced_ps1_size)
+		ps1_get = forced_ps1_size - result.size1;
+
+	suspend_message(SUSPEND_PAGESETS, SUSPEND_HIGH, 1,
+		"1: Forced size = %ld. Have %d -> ps1_get = %ld.\n",
+		forced_ps1_size, result.size1, ps1_get);
+	
+	/* 
+	 * We can make ps2 size exactly what was requested, but
+	 * not both.
+	 */
+	if (forced_ps2_size) {
+		ps2_get = forced_ps2_size - result.size2;
+		suspend_message(SUSPEND_PAGESETS, SUSPEND_HIGH, 1,
+			"2: Forced size = %ld. Have %d -> ps2_get = %ld.\n",
+			forced_ps2_size, result.size2, ps2_get);
+
+		if (ps2_get > 0) {
+			order = generic_fls(ps2_get);
+			if (order >= MAX_ORDER)
+				order = MAX_ORDER - 1;
+
+			while(ps2_get > 0) {
+				struct page * newpage;
+				unsigned long virt;
+				struct bloat_pages * link;
+			
+				if ((ps1_get - (1 << order)) < (1 << order))
+					redo_counts();
+				
+				while ((1 << order) > (ps2_get))
+					order--;
+
+				virt = get_grabbed_pages(order);
+
+				while ((!virt) && (order > 0)) {
+					order--;
+					if ((ps1_get - (1 << order)) < (1 << order))
+						redo_counts();
+					virt = get_grabbed_pages(order);
+				}
+
+				if (!virt) {
+					suspend_message(SUSPEND_PAGESETS, SUSPEND_MEDIUM, 1,
+						" Failed to allocate enough memory for"
+						" requested pageset sizes.\n");
+					return;
+				}
+	
+				newpage = virt_to_page(virt);
+				for (j = 0; j < (1 << order); j++)
+					SetPagePageset2(newpage + j);
+
+				link = (struct bloat_pages *) virt;
+				link->next = bloat_pages;
+				link->order = order;
+				bloat_pages = link;
+
+				ps2_get -= (1 << order);
+				suspend_message(SUSPEND_PAGESETS, SUSPEND_VERBOSE, 1,
+					"Allocated %d for ps2. To get %ld.\n",
+					1 << order, ps2_get);
+			}
+		} else
+		{
+			/* Here, we're making ps2 pages into ps1 pages */
+			int i;
+
+			suspend_message(SUSPEND_PAGESETS, SUSPEND_HIGH, 1,
+				"Moving %ld ps2 pages to ps1.\n", -ps2_get);
+			for (i = 0; i < max_mapnr; i++) {
+				if PagePageset2(mem_map + i) {
+					ClearPagePageset2(mem_map + i);
+					ps2_get++;
+					ps1_get--;
+				}
+				if (!ps2_get)
+					break;
+			}
+		}
+	} else {
+		suspend_message(SUSPEND_PAGESETS, SUSPEND_HIGH, 1,
+			"2: Forced size = %ld. Have %d -> ps2_get = %ld.\n",
+			forced_ps2_size, result.size2, ps2_get);
+	}
+	
+	if (ps1_get > 0) {
+
+		suspend_message(SUSPEND_PAGESETS, SUSPEND_HIGH, 1,
+			"Still to get %ld pages for ps1.\n", ps1_get);
+		
+		/* We might allocate an extra range page later. */
+		if (ps1_get > 1) {
+			suspend_message(SUSPEND_PAGESETS, SUSPEND_VERBOSE, 1,
+				"Reducing ps1_get by one.\n");
+			drop_one = 1;
+			ps1_get--;
+		}
+		
+		order = generic_fls(ps1_get);
+		if (order >= MAX_ORDER)
+			order = MAX_ORDER - 1;
+
+		while(ps1_get > 0) {
+			unsigned long virt;
+			struct bloat_pages * link;
+		
+			if ((ps1_get - (1 << order)) < (1 << order))
+				redo_counts();
+				
+			while ((1 << order) > (ps1_get))
+				order--;
+
+			virt = get_grabbed_pages(order);
+
+			while ((!virt) && (order > 0)) {
+				order--;
+				if ((ps1_get - (1 << order)) < (1 << order))
+					redo_counts();
+				virt = get_grabbed_pages(order);
+			}
+
+			if (!virt) {
+				suspend_message(SUSPEND_PAGESETS, SUSPEND_VERBOSE, 1,
+					"Couldn't get enough pages. Need %ld more.\n",
+					ps1_get);
+				return;
+			}
+	
+			link = (struct bloat_pages *) virt;
+			link->next = bloat_pages;
+			link->order = order;
+			bloat_pages = link;
+
+			ps1_get -= (1 << order);
+			suspend_message(SUSPEND_PAGESETS, SUSPEND_VERBOSE, 1,
+				"Allocated %d for ps1. To get %ld.\n", 1 << order, ps1_get);
+		}
+	}
+	suspend_message(SUSPEND_PAGESETS, SUSPEND_VERBOSE, 1,
+		"Exiting increase pageset size.\n\n");
+}
+
+/*
+ * Eaten is the number of pages which have been eaten.
+ * Pagedirincluded is the number of pages which have been allocated for the pagedir.
+ */
+extern int allocate_extra_pagedir_memory(struct pagedir * p, int pageset_size, int alloc_from);
+
+struct pageset_sizes_result recalculate_stats(void) 
+{
+	struct pageset_sizes_result result;
+
+	mark_pages_for_pageset2();  /* Need to call this before getting pageset1_size! */
+	result = count_data_pages();
+	suspend_message(SUSPEND_PAGESETS, SUSPEND_VERBOSE, 1,
+		"Forced sizes %ld and %ld. Result %d and %d.\n",
+		forced_ps1_size, forced_ps2_size,
+		result.size1, result.size2);
+	if ((forced_ps1_size && forced_ps1_size != result.size1) || 
+	    (forced_ps2_size && forced_ps2_size != result.size2)) {
+		increase_pageset_size(result);
+		result = count_data_pages();
+	}
+	pageset1_sizelow = result.size1low;
+	pageset2_sizelow = result.size2low;
+	pagedir1.lastpageset_size = pageset1_size = result.size1;
+	pagedir2.lastpageset_size = pageset2_size = result.size2;
+	storage_available = active_writer->ops.writer.storage_available();
+	suspend_store_free_mem(SUSPEND_FREE_RANGE_PAGES, 0);
+	return result;
+}
+
+/* update_image
+ *
+ * Allocate [more] memory and storage for the image.
+ * Remember, this is iterative!
+ */
+static int update_image(void) 
+{ 
+	struct pageset_sizes_result result;
+	int iteration = 0, orig_num_range_pages;
+
+	result = recalculate_stats();
+
+	suspend_store_free_mem(SUSPEND_FREE_RANGE_PAGES, 0);
+
+	do {
+		iteration++;
+
+		orig_num_range_pages = num_range_pages;
+
+		suspend_message(SUSPEND_ANY_SECTION, SUSPEND_LOW, 1,
+				"-- Iteration %d.\n", iteration);
+
+		if (suspend_allocate_checksum_pages()) {
+			suspend_message(SUSPEND_ANY_SECTION, SUSPEND_LOW, 1,
+				"Still need to get more pages for checksum pages.\n");
+			return 1;
+		}
+
+		if (allocate_extra_pagedir_memory(&pagedir1, pageset1_size, pageset2_sizelow)) {
+			suspend_message(SUSPEND_ANY_SECTION, SUSPEND_LOW, 1,
+				"Still need to get more pages for pagedir 1.\n");
+			return 1;
+		}
+
+		if (active_writer->ops.writer.allocate_storage(MAIN_STORAGE_NEEDED(1))) {
+			suspend_message(SUSPEND_ANY_SECTION, SUSPEND_LOW, 1,
+				"Still need to get more storage space for the image proper.\n");
+			suspend_store_free_mem(SUSPEND_FREE_WRITER_STORAGE, 0);
+			return 1;
+		}
+
+		suspend_store_free_mem(SUSPEND_FREE_WRITER_STORAGE, 0);
+
+		set_suspend_state(SUSPEND_SLAB_ALLOC_FALLBACK);
+
+		if (active_writer->ops.writer.allocate_header_space(HEADER_STORAGE_NEEDED)) {
+			suspend_message(SUSPEND_ANY_SECTION, SUSPEND_LOW, 1,
+				"Still need to get more storage space for header.\n");
+			return 1;
+		}
+
+		header_space_allocated = HEADER_STORAGE_NEEDED;
+
+		clear_suspend_state(SUSPEND_SLAB_ALLOC_FALLBACK);
+
+		/* 
+		 * Allocate remaining storage space, if possible, up to the
+		 * maximum we know we'll need. It's okay to allocate the
+		 * maximum if the writer is the swapwriter, but
+		 * we don't want to grab all available space on an NFS share.
+		 * We therefore ignore the expected compression ratio here,
+		 * thereby trying to allocate the maximum image size we could
+		 * need (assuming compression doesn't expand the image), but
+		 * don't complain if we can't get the full amount we're after.
+		 */
+
+		active_writer->ops.writer.allocate_storage(
+			max((long)(active_writer->ops.writer.storage_available() -
+				active_writer->ops.writer.storage_allocated()),
+			     (long)(HEADER_STORAGE_NEEDED + MAIN_STORAGE_NEEDED(1))));
+
+		suspend_store_free_mem(SUSPEND_FREE_WRITER_STORAGE, 0);
+
+		result = recalculate_stats();
+		display_stats();
+
+	} while (((orig_num_range_pages < num_range_pages) || 
+		   result.needmorespace ||
+		   header_space_allocated < HEADER_STORAGE_NEEDED ||
+		   active_writer->ops.writer.storage_allocated() < (HEADER_STORAGE_NEEDED + MAIN_STORAGE_NEEDED(1))) 
+		 && (!TEST_RESULT_STATE(SUSPEND_ABORTED)));
+	
+	suspend_message(SUSPEND_ANY_SECTION, SUSPEND_MEDIUM, 1, "-- Exit loop.\n");
+
+	return (amount_needed(0) > 0);
+}
+
+/* ----------------------- Memory grabbing --------------------------
+ *
+ * All of the memory that is available, we grab.
+ * This enables us to get the image size down, even when other
+ * processes might be trying to increase their memory usage. (We
+ * have a hook to disable the OOM killer).
+ *
+ * At the same time, suspend's own routines get memory from this
+ * pool, and so does slab growth. Only get_zeroed_page and siblings
+ * see no memory available.
+ */
+
+static spinlock_t suspend_grabbed_memory_lock = SPIN_LOCK_UNLOCKED;
+
+struct eaten_memory_t
+{
+	void * next;
+};
+
+struct eaten_memory_t *eaten_memory[MAX_ORDER];
+
+static void __grab_free_memory(void)
+{
+	int order, k;
+
+	/*
+	 * First, quickly eat all memory that's already free.
+	 */
+	
+	for (order = MAX_ORDER - 1; order > -1; order--) {
+		struct eaten_memory_t *prev = eaten_memory[order];
+		eaten_memory[order] = (struct eaten_memory_t *) __get_free_pages(GFP_ATOMIC, order);
+		while (eaten_memory[order]) {
+			struct page * page = virt_to_page(eaten_memory[order]);
+			eaten_memory[order]->next = prev;
+			prev = eaten_memory[order];
+			suspend_amount_grabbed += (1 << order);
+			for (k=0; k < (1 << order); k++) {
+				SetPageNosave(page + k);
+				ClearPagePageset2(page + k);
+			}
+			eaten_memory[order] = (struct eaten_memory_t *) __get_free_pages(GFP_ATOMIC, order);
+		}
+		eaten_memory[order] = prev;
+	}
+}
+
+static void grab_free_memory(void)
+{
+	unsigned long flags;
+	
+	spin_lock_irqsave(&suspend_grabbed_memory_lock, flags);
+	__grab_free_memory();
+	spin_unlock_irqrestore(&suspend_grabbed_memory_lock, flags);
+}
+
+static void free_grabbed_memory(void)
+{
+	struct eaten_memory_t *next = NULL, *this = NULL;
+	int j, num_freed = 0, order;
+	unsigned long flags;
+
+	spin_lock_irqsave(&suspend_grabbed_memory_lock, flags);
+
+	/* Free all eaten pages immediately */
+	for (order = MAX_ORDER - 1; order > -1; order--) {
+		this=eaten_memory[order];
+		while(this) {
+			struct page * page = virt_to_page(this);
+			next = this->next;
+			for (j=0; j < (1 << order); j++)
+				ClearPageNosave(page + j);
+			free_pages((unsigned long) this, order);
+			num_freed+= (1 << order);
+			this = next;
+		}
+		eaten_memory[order] = NULL;
+	}
+	suspend_amount_grabbed -= num_freed;
+	BUG_ON(suspend_amount_grabbed);
+	spin_unlock_irqrestore(&suspend_grabbed_memory_lock, flags);
+}
+
+unsigned long get_grabbed_pages(int order)
+{
+	unsigned long this = (unsigned long) eaten_memory[order];
+	int alternative, j;
+	unsigned long flags;
+	struct page * page;
+
+	/* Get grabbed lowmem pages for suspend's use */
+	spin_lock_irqsave(&suspend_grabbed_memory_lock, flags);
+
+try_again:	
+	if (this) {
+		page = virt_to_page(this);
+		eaten_memory[order] = eaten_memory[order]->next;
+		for (j=0; j < (1 << order); j++) {
+			ClearPageNosave(page + j);
+			ClearPagePageset2(page + j);
+			clear_page(page_address(page + j));
+		}
+		suspend_amount_grabbed -= (1 << order);
+		spin_unlock_irqrestore(&suspend_grabbed_memory_lock, flags);
+		return this;
+	}
+
+	alternative = order+1;
+	while ((!eaten_memory[alternative]) && (alternative < MAX_ORDER))
+		alternative++;
+
+	/* Maybe we didn't eat any memory - try normal get */
+	if (alternative == MAX_ORDER) {
+		this = __get_free_pages(GFP_ATOMIC, order);
+		if (this) {
+			page = virt_to_page(this);
+			for (j=0; j < (1 << order); j++) {
+				clear_page((char *) this + j * PAGE_SIZE);
+				ClearPagePageset2(page + j);
+			}
+		}
+		spin_unlock_irqrestore(&suspend_grabbed_memory_lock, flags);
+		return this;
+	}
+
+	{
+		unsigned long virt = (unsigned long) eaten_memory[alternative];
+		page = virt_to_page(eaten_memory[alternative]);
+		eaten_memory[alternative] = eaten_memory[alternative]->next;
+		for (j=0; j < (1 << (alternative)); j++) {
+			ClearPageNosave(page + j);
+			clear_page(page_address(page + j));
+			ClearPagePageset2(page + j);
+		}
+		free_pages(virt, alternative);
+		suspend_amount_grabbed -= (1 << alternative);
+	}
+
+	/* Get the chunk we want to return. May fail if something grabs
+	 * the memory before us. */
+	this = __get_free_pages(GFP_ATOMIC, order);
+	if (!this)
+		goto try_again;
+
+	page = virt_to_page(this);
+
+	/* Grab the rest */
+	__grab_free_memory();
+	
+	spin_unlock_irqrestore(&suspend_grabbed_memory_lock, flags);
+
+	return this;
+}
+
+/* --------------------------------------------------------------------------- */
+
+extern int freeze_processes(int no_progress);
+
+static int attempt_to_freeze(void)
+{
+	int result;
+	
+	/* Stop processes before checking again */
+	thaw_processes(FREEZER_ALL_THREADS);
+	prepare_status(1, 1, "Freezing processes");
+	result = freeze_processes(0);
+	suspend_message(SUSPEND_FREEZER, SUSPEND_VERBOSE, 0, "- Freeze_processes returned %d.\n",
+		result);
+
+	if (result) {
+		SET_RESULT_STATE(SUSPEND_ABORTED);
+		SET_RESULT_STATE(SUSPEND_FREEZING_FAILED);
+	} else
+		arefrozen = 1;
+
+	return result;
+}
+
+extern asmlinkage long sys_sync(void);
+
+static int eat_memory(void)
+{
+	int orig_memory_still_to_eat, last_amount_needed = 0, times_criteria_met = 0;
+	int free_flags = 0, did_eat_memory = 0;
+	
+	/*
+	 * Note that if we have enough storage space and enough free memory, we may
+	 * exit without eating anything. We give up when the last 10 iterations ate
+	 * no extra pages because we're not going to get much more anyway, but
+	 * the few pages we get will take a lot of time.
+	 *
+	 * We freeze processes before beginning, and then unfreeze them if we
+	 * need to eat memory until we think we have enough. If our attempts
+	 * to freeze fail, we give up and abort.
+	 */
+
+	/* ----------- Stage 1: Freeze Processes ------------- */
+
+	
+	prepare_status(0, 1, "Eating memory.");
+
+	recalculate_stats();
+	display_stats();
+
+	orig_memory_still_to_eat = amount_needed(1);
+	last_amount_needed = orig_memory_still_to_eat;
+
+	switch (image_size_limit) {
+		case -1: /* Don't eat any memory */
+			if (orig_memory_still_to_eat) {
+				SET_RESULT_STATE(SUSPEND_ABORTED);
+				SET_RESULT_STATE(SUSPEND_WOULD_EAT_MEMORY);
+			}
+			break;
+		case -2:  /* Free caches only */
+			free_flags = GFP_NOIO | __GFP_HIGHMEM;
+			break;
+		default:
+			free_flags = GFP_ATOMIC | __GFP_HIGHMEM;
+	}
+		
+	/* ----------- Stage 2: Eat memory ------------- */
+
+	while (((!EATEN_ENOUGH_MEMORY()) || (image_size_limit == -2)) && (!TEST_RESULT_STATE(SUSPEND_ABORTED)) && (times_criteria_met < 10)) {
+		int amount_freed;
+		int amount_wanted = orig_memory_still_to_eat - amount_needed(1);
+		if (amount_wanted < 1)
+			amount_wanted = 1; /* image_size_limit == -2 */
+
+		suspend_message(SUSPEND_EAT_MEMORY, SUSPEND_VERBOSE, 1,
+			"Times met criteria is %d.\n", times_criteria_met);
+		if (orig_memory_still_to_eat)
+			update_status(orig_memory_still_to_eat - amount_needed(1), orig_memory_still_to_eat, " Image size %d ", MB(STORAGE_NEEDED(1)));
+		else
+			update_status(0, 1, "Image size %d ", MB(STORAGE_NEEDED(1)));
+		
+		if ((last_amount_needed - amount_needed(1)) < 10)
+			times_criteria_met++;
+		else
+			times_criteria_met = 0;
+		last_amount_needed = amount_needed(1);
+		amount_freed = shrink_all_memory(last_amount_needed);
+		suspend_message(SUSPEND_EAT_MEMORY, SUSPEND_VERBOSE, 1,
+			"Given %d, shrink_all_memory returned %d.\n", last_amount_needed, amount_freed);
+		grab_free_memory();
+		recalculate_stats();
+		display_stats();
+
+		did_eat_memory = 1;
+
+		check_shift_keys(0, NULL);
+	}
+
+	grab_free_memory();
+	
+	suspend_message(SUSPEND_EAT_MEMORY, SUSPEND_VERBOSE, 1,
+		"Out of main eat memory loop.\n");
+
+	if (did_eat_memory) {
+		unsigned long orig_state = get_suspend_state();
+		suspend_message(SUSPEND_EAT_MEMORY, SUSPEND_VERBOSE, 1,
+			"Ate memory; letting kjournald etc run.\n");
+		clear_suspend_state(SUSPEND_USE_MEMORY_POOL);
+		thaw_processes(FREEZER_KERNEL_THREADS);
+		/* Freeze_processes will call sys_sync too */
+		freeze_processes(1);
+		grab_free_memory();
+		restore_suspend_state(orig_state);
+		recalculate_stats();
+		display_stats();
+	}
+
+	suspend_message(SUSPEND_EAT_MEMORY, 1, SUSPEND_VERBOSE, "\n");
+	
+	suspend_message(SUSPEND_EAT_MEMORY, SUSPEND_VERBOSE, 1,
+		"(Freezer exit:) Swap needed calculated as (%d+%d)*%d/100+%d+1+%d=%d.\n",
+		pageset1_size,
+		pageset2_size,
+		expected_compression_ratio(),
+		num_range_pages,
+	 	HEADER_STORAGE_NEEDED,
+		STORAGE_NEEDED(1));
+
+	/* Blank out image size display */
+	update_status(100, 100, "                   ");
+
+	/* Include image size limit when checking what to report */
+	if (amount_needed(1) > 0) 
+		SET_RESULT_STATE(SUSPEND_UNABLE_TO_FREE_ENOUGH_MEMORY);
+
+	/* But don't include it when deciding whether to abort (soft limit) */
+	if ((amount_needed(0) > 0)) {
+		printk("Unable to free sufficient memory to suspend. Still need %d pages. "
+			"You may be able to avoid this problem by reducing the async_io_limit\n",
+			amount_needed(1));
+		SET_RESULT_STATE(SUSPEND_ABORTED);
+	}
+	
+	check_shift_keys(1, "Memory eating completed.");
+	return 0;
+}
+
+/* prepare_image
+ *
+ * Entry point to the whole image preparation section.
+ *
+ * We do four things:
+ * - Freeze processes;
+ * - Ensure image size constraints are met;
+ * - Complete all the preparation for saving the image,
+ *   including allocation of storage. The only memory
+ *   that should be needed when we're finished is that
+ *   for actually storing the image (and we know how
+ *   much is needed for that because the plugins tell
+ *   us).
+ * - Make sure that all dirty buffers are written out.
+ */
+int prepare_image(void)
+{
+	int result = 1, sizesought;
+
+	arefrozen = 0;
+
+	header_space_allocated = 0;
+
+	sizesought = 100 + memory_for_plugins();
+
+	PRINTFREEMEM("prior to filling the memory pool");
+	
+	if (fill_suspend_memory_pool(sizesought))
+		return 1;
+
+	PRINTFREEMEM("after filling the memory pool");
+	suspend_store_free_mem(SUSPEND_FREE_MEM_POOL, 0);
+	
+	if (attempt_to_freeze())
+		return 1;
+
+	PRINTFREEMEM("after freezing processes");
+	suspend_store_free_mem(SUSPEND_FREE_FREEZER, 0);
+	
+	if (!active_writer->ops.writer.storage_available()) {
+		printk(KERN_ERR "You need some storage available to be able to suspend.\n");
+		SET_RESULT_STATE(SUSPEND_ABORTED);
+		SET_RESULT_STATE(SUSPEND_NOSTORAGE_AVAILABLE);
+		return 1;
+	}
+
+	do {
+		if (eat_memory() || TEST_RESULT_STATE(SUSPEND_ABORTED))
+			break;
+
+		PRINTFREEMEM("after eating memory");
+		suspend_store_free_mem(SUSPEND_FREE_EAT_MEMORY, 0);
+	
+		/* Top up */
+		if (fill_suspend_memory_pool(sizesought))
+			continue;
+	
+		PRINTFREEMEM("after refilling memory pool");
+		suspend_store_free_mem(SUSPEND_FREE_MEM_POOL, 0);
+	
+		result = update_image();
+		PRINTFREEMEM("after updating the image");
+
+	} while ((result) && (!TEST_RESULT_STATE(SUSPEND_ABORTED)) &&
+		(!TEST_RESULT_STATE(SUSPEND_UNABLE_TO_FREE_ENOUGH_MEMORY)));
+
+	PRINTFREEMEM("after preparing image");
+
+	/* Release memory that has been eaten */
+	free_grabbed_memory();
+	
+	PRINTFREEMEM("after freeing grabbed memory");
+	suspend_store_free_mem(SUSPEND_FREE_GRABBED_MEMORY, 1);
+	
+	set_suspend_state(SUSPEND_USE_MEMORY_POOL);
+
+	check_shift_keys(1, "Image preparation complete.");
+
+	return result;
+}
+
+EXPORT_SYMBOL(suspend_amount_grabbed);
#114 lore raw

Re: Suspend 2 merge: 42/51: Suspend.c

In reply to Nigel Cunningham
Quoted 6 lines · Nigel Cunningham

Here's the heart of the core :> (No, that's not a typo).

- Device suspend/resume calls
- Power down
- Highest level routine
- all_settings proc entry handling

This isn't the only patch (the utility.c file is another one) which introduces functions/helpers which are subsystem specific (like ACPI) but somehow land up in the same file with a suspend_ prefix. I understand that it'll be more work but can you get them integrated with the subsystem in question?

Thanks,
Zwane

#95 lore raw

Re: Suspend 2 merge: 18/51: Debug page_alloc support.

In reply to Nigel Cunningham

arch/i386/mm/pageattr.c line 226

Quoted 4 lines · Nigel Cunningham
arch/i386/mm/pageattr.c +4 -0
+#ifdef CONFIG_HIGHMEM
+	if (page >= highmem_start_page) 
+		return 0;
+#endif

There's a patch pending in -mm to kill highmem_start_page. Please use PageHighMem().

-- Dave

#213 lore raw

Suspend 2 merge: 6/51

In reply to Nigel Cunningham

Ooh.

6/51 is missing.

Let's just say I can't count. I've checked the directory and the reboot handler is the next one after workthreads :>

Nigel

Signature · 7 lines
Nigel Cunningham
Pastoral Worker
Christian Reformed Church of Tuggeranong
PO Box 1004, Tuggeranong, ACT 2901

You see, at just the right time, when we were still powerless, Christ
died for the ungodly.		-- Romans 5:6
#214 lore raw

Suspend 2 merge: 39/51: Plugins support.

In reply to Nigel Cunningham

A plugin is an extension to suspend, but not necessarily a module (I'm trying to avoid confusing the terms). Plugins can make transformations on pages of memory in the image (compress/encrypt...), write the image (swapwriter, eg), provide I/O facilities (bootsplash/textmode) or be 'miscellaneous' (blockwriter that does the hard work for the swapwriter, device mapper plugin that simply ensures enough memory is available for the device mapper given the async I/O limit set).

This file handles registration & removal of plugins, as well as invocation of some of the routines.

kernel/power/plugins.c +372 -0
diff -ruN 829-plugins-old/kernel/power/plugins.c 829-plugins-new/kernel/power/plugins.c
@@ -0,0 +1,372 @@
+/*
+ * kernel/power/plugin.c
+ *
+ * Copyright (C) 2004 Nigel Cunningham <[email protected]>
+ *
+ */
+
+#include <linux/suspend.h>
+#include <linux/module.h>
+
+#include "suspend.h"
+#include "plugins.h"
+
+struct list_head suspend_filters, suspend_writers, suspend_plugins, suspend_ui;
+int num_filters = 0, num_writers = 0, num_ui = 0, num_plugins = 0;
+struct suspend_plugin_ops * active_writer = NULL;
+struct suspend_plugin_ops * checksum_plugin = NULL;
+
+/*
+ * header_storage_for_plugins
+ *
+ * Returns the amount of space needed to store configuration
+ * data needed by the plugins prior to copying back the original
+ * kernel. We can exclude data for pageset2 because it will be
+ * available anyway once the kernel is copied back.
+ */
+unsigned long header_storage_for_plugins(void)
+{
+	struct suspend_plugin_ops * this_plugin;
+	unsigned long bytes = 0;
+	
+	list_for_each_entry(this_plugin, &suspend_plugins, plugin_list) {
+		if (this_plugin->disabled)
+			continue;
+		if (this_plugin->storage_needed)
+			bytes += this_plugin->storage_needed();
+	}
+
+	return bytes;
+}
+
+/*
+ * expected_compression_ratio
+ *
+ * Returns the expected ratio between the amount of memory
+ * to be saved and the amount of space required on the
+ * storage device.
+ */
+int expected_compression_ratio(void)
+{
+	struct suspend_plugin_ops * this_filter;
+	unsigned long ratio = 100;
+	
+	list_for_each_entry(this_filter, &suspend_filters, ops.filter.filter_list) {
+		if (this_filter->disabled)
+			continue;
+		if (this_filter->ops.filter.expected_compression)
+			ratio = ratio * this_filter->ops.filter.expected_compression() / 100;
+	}
+
+	return (int) ratio;
+}
+
+/*
+ * memory_for_plugins
+ *
+ * Returns the amount of memory requested by plugins for
+ * doing their work during the cycle.
+ */
+
+unsigned long memory_for_plugins(void)
+{
+	unsigned long bytes = 0;
+	struct suspend_plugin_ops * this_plugin;
+
+	list_for_each_entry(this_plugin, &suspend_plugins, plugin_list) {
+		if (this_plugin->disabled)
+			continue;
+		if (this_plugin->memory_needed)
+			bytes += this_plugin->memory_needed();
+	}
+
+	return ((bytes + PAGE_SIZE - 1) >> PAGE_SHIFT);
+}
+
+/* suspend_early_boot_message_plugins
+ *
+ * Call early_boot_message methods for plugins.
+ */
+void suspend_early_boot_message_plugins(void)
+{
+	struct suspend_plugin_ops * this_plugin;
+
+	list_for_each_entry(this_plugin, &suspend_ui, ops.ui.ui_list) {
+		if (this_plugin->disabled)
+			continue;
+		if (this_plugin->ops.ui.early_boot_message_prep)
+			this_plugin->ops.ui.early_boot_message_prep();
+	}
+}
+
+/* suspend_plugin_keypress
+ *
+ * Pass the keycode to plugins until one handles it.
+ */
+void suspend_plugin_keypress(unsigned int keycode)
+{
+	struct suspend_plugin_ops * this_plugin;
+
+	list_for_each_entry(this_plugin, &suspend_ui, ops.ui.ui_list) {
+		if (this_plugin->disabled)
+			continue;
+		if (this_plugin->ops.ui.keypress)
+			if (this_plugin->ops.ui.keypress(keycode))
+				return;
+	}
+}
+
+/* post_kernel_restore_redraw
+ *
+ * Call UI plugins to allow them to redraw the screen after a restoration
+ * of the original kernel
+ */
+
+void suspend_post_restore_redraw(void)
+{
+	struct suspend_plugin_ops * this_plugin;
+
+	list_for_each_entry(this_plugin, &suspend_ui, ops.ui.ui_list) {
+		if (this_plugin->disabled)
+			continue;
+		if (this_plugin->ops.ui.post_kernel_restore_redraw)
+			this_plugin->ops.ui.post_kernel_restore_redraw();
+	}
+}
+
+
+/* find_plugin_given_name
+ * Functionality :	Return a plugin (if found), given a pointer
+ * 			to its name
+ */
+
+struct suspend_plugin_ops * find_plugin_given_name(char * name)
+{
+	struct suspend_plugin_ops * this_plugin, * found_plugin = NULL;
+	
+	list_for_each_entry(this_plugin, &suspend_plugins, plugin_list) {
+		if (!strcmp(name, this_plugin->name)) {
+			found_plugin = this_plugin;
+			break;
+		}			
+	}
+
+	return found_plugin;
+}
+
+/*
+ * print_plugin_debug_info
+ * Functionality   : Get debugging info from plugins into a buffer.
+ */
+int print_plugin_debug_info(char * buffer, int buffer_size)
+{
+	struct suspend_plugin_ops *this_plugin;
+	int len = 0;
+
+	list_for_each_entry(this_plugin, &suspend_plugins, plugin_list) {
+		if (this_plugin->disabled)
+			continue;
+		if (this_plugin->print_debug_info) {
+			int result;
+			result = this_plugin->print_debug_info(buffer + len, 
+					buffer_size - len);
+			len += result;
+		}
+	}
+
+	return len;
+}
+
+extern int attempt_to_parse_resume_device(void);
+
+int suspend_initialise_plugin_lists(void) {
+	INIT_LIST_HEAD(&suspend_filters);
+	INIT_LIST_HEAD(&suspend_writers);
+	INIT_LIST_HEAD(&suspend_ui);
+	INIT_LIST_HEAD(&suspend_plugins);
+	return 0;
+}
+
+int suspend_register_plugin(struct suspend_plugin_ops * plugin)
+{
+	if (!num_plugins)
+		suspend_initialise_plugin_lists();
+	
+	if (find_plugin_given_name(plugin->name))
+		return -EBUSY;
+
+	switch (plugin->type) {
+		case FILTER_PLUGIN:
+			list_add_tail(&plugin->ops.filter.filter_list,
+					&suspend_filters);
+			num_filters++;
+			break;
+
+		case WRITER_PLUGIN:
+			list_add_tail(&plugin->ops.writer.writer_list,
+					&suspend_writers);
+			num_writers++;
+			if ((!active_writer) &&
+			    (!(test_suspend_state(SUSPEND_BOOT_TIME))))
+				attempt_to_parse_resume_device();
+			break;
+
+		case UI_PLUGIN:
+			list_add_tail(&plugin->ops.ui.ui_list,
+					&suspend_ui);
+			num_ui++;
+			break;
+
+		case MISC_PLUGIN:
+			break;
+
+		case CHECKSUM_PLUGIN:
+			if (!checksum_plugin)
+				checksum_plugin = plugin;
+			else
+				printk("Checksum plugin already registered!");
+			break;
+				
+		default:
+			printk("Hmmm. Plugin '%s' has an invalid type."
+				" It has been ignored.\n", plugin->name);
+			return -EINVAL;
+	}
+	list_add_tail(&plugin->plugin_list, &suspend_plugins);
+	num_plugins++;
+
+	return 0;	
+}
+
+void suspend_unregister_plugin(struct suspend_plugin_ops * plugin)
+{
+	switch (plugin->type) {
+		case FILTER_PLUGIN:
+			list_del(&plugin->ops.filter.filter_list);
+			num_filters--;
+			break;
+
+		case WRITER_PLUGIN:
+			list_del(&plugin->ops.writer.writer_list);
+			num_writers--;
+			if (active_writer == plugin)
+				attempt_to_parse_resume_device();
+			break;
+		
+		case UI_PLUGIN:
+			list_del(&plugin->ops.ui.ui_list);
+			num_ui--;
+			break;
+		
+		case MISC_PLUGIN:
+			break;
+
+		case CHECKSUM_PLUGIN:
+			if (plugin == checksum_plugin)
+				checksum_plugin = NULL;
+			break;
+		default:
+			printk("Hmmm. Plugin '%s' has an invalid type."
+				" It has been ignored.\n", plugin->name);
+			return;
+	}
+	list_del(&plugin->plugin_list);
+	num_plugins--;
+}
+
+void suspend_move_plugin_tail(struct suspend_plugin_ops * plugin)
+{
+	switch (plugin->type) {
+		case FILTER_PLUGIN:
+			if (num_filters > 1)
+				list_move_tail(&plugin->ops.filter.filter_list,
+						&suspend_filters);
+			break;
+
+		case WRITER_PLUGIN:
+			if (num_writers > 1)
+				list_move_tail(&plugin->ops.writer.writer_list,
+						&suspend_writers);
+			break;
+		
+		case UI_PLUGIN:
+			if (num_ui > 1)
+				list_move_tail(&plugin->ops.ui.ui_list,
+						&suspend_ui);
+			break;
+		
+		case MISC_PLUGIN:
+			break;
+		default:
+			printk("Hmmm. Plugin '%s' has an invalid type."
+				" It has been ignored.\n", plugin->name);
+			return;
+	}
+	if ((num_filters + num_writers + num_ui) > 1)
+		list_move_tail(&plugin->plugin_list, &suspend_plugins);
+}
+
+int initialise_suspend_plugins(void)
+{
+	struct suspend_plugin_ops * this_plugin;
+	int result;
+	
+	list_for_each_entry(this_plugin, &suspend_plugins, plugin_list) {
+		if (this_plugin->disabled)
+			continue;
+		if (this_plugin->initialise) {
+			suspend_message(SUSPEND_MEMORY, SUSPEND_MEDIUM, 1,
+				"Initialising plugin %s.\n",
+				this_plugin->name);
+			if ((result = this_plugin->initialise()))
+				return result;
+		}
+		PRINTFREEMEM("after initialising plugin");
+	}
+
+	return 0;
+}
+
+void cleanup_suspend_plugins(void)
+{
+	struct suspend_plugin_ops * this_plugin;
+	
+	list_for_each_entry(this_plugin, &suspend_plugins, plugin_list) {
+		if (this_plugin->disabled)
+			continue;
+		if (this_plugin->cleanup) {
+			suspend_message(SUSPEND_MEMORY, SUSPEND_MEDIUM, 1,
+				"Cleaning up plugin %s.\n",
+				this_plugin->name);
+			this_plugin->cleanup();
+			PRINTFREEMEM("after cleaning up plugin");
+		}
+	}
+}
+
+struct suspend_plugin_ops * 
+get_next_filter(struct suspend_plugin_ops * filter_sought)
+{
+	struct suspend_plugin_ops * last_filter = NULL, *this_filter = NULL;
+
+	list_for_each_entry(this_filter, &suspend_filters, ops.filter.filter_list) {
+		if (this_filter->disabled)
+			continue;
+		if ((last_filter == filter_sought) || (!filter_sought))
+			return this_filter;
+		last_filter = this_filter;
+	}
+
+	return active_writer;
+}
+
+EXPORT_SYMBOL(get_next_filter);
+EXPORT_SYMBOL(suspend_register_plugin);
+EXPORT_SYMBOL(suspend_unregister_plugin);
+EXPORT_SYMBOL(max_async_ios);
+EXPORT_SYMBOL(active_writer);
+EXPORT_SYMBOL(suspend_filters);
+#ifdef CONFIG_SOFTWARE_SUSPEND_DEBUG
+EXPORT_SYMBOL(suspend_store_free_mem);
+#endif
+EXPORT_SYMBOL(suspend_post_restore_redraw);
#215 lore raw

Suspend 2 merge: 32/51: Make show task non-static.

In reply to Nigel Cunningham

This is used to show the state of a task when a process fails to enter the refrigerator.

kernel/sched.c +1 -2
diff -ruN 819-export-show-task-old/kernel/sched.c 819-export-show-task-new/kernel/sched.c
@@ -32,7 +32,6 @@
 #include <linux/security.h>
 #include <linux/notifier.h>
 #include <linux/profile.h>
-#include <linux/suspend.h>
 #include <linux/blkdev.h>
 #include <linux/delay.h>
 #include <linux/smp.h>
@@ -3719,7 +3718,7 @@
 	return list_entry(p->sibling.next,struct task_struct,sibling);
 }
 
-static void show_task(task_t * p)
+void show_task(task_t * p)
 {
 	task_t *relative;
 	unsigned state;
#216 lore raw

Suspend 2 merge: 38/51: Page directory support.

In reply to Nigel Cunningham

A pageset is a group of pages that are saved as part of the image. Suspend uses two pagesets: pageset2 contains the LRU pages and pageset1 contains all other pages saved. A pagedir is the original name for pagesets. I use it more to refer to the metadata for the pageset.

Note that all of our metadata is actually stored in extents (I called them ranges before I knew what an extent was). The struct pbe2 is an abstraction of this data, roughly equivalent to the pbes that swsusp uses (hence the name) and the *pbe* functions at the top of this file.

Here we also have the code for making our atomic copy when suspending, allocating and freeing the metadata and working to ensure the copy of pagedir1 loaded at resume time doesn't get overwritten by itself ('collide') as we restore the kernel.

kernel/power/pagedir.c +532 -0
diff -ruN 828-pagedir-old/kernel/power/pagedir.c 828-pagedir-new/kernel/power/pagedir.c
@@ -0,0 +1,532 @@
+/*
+ * kernel/power/pagedir.c
+ *
+ * Copyright (C) 1998-2001 Gabor Kuti <[email protected]>
+ * Copyright (C) 1998,2001,2002 Pavel Machek <[email protected]>
+ * Copyright (C) 2002-2003 Florent Chabaud <[email protected]>
+ * Copyright (C) 2002-2004 Nigel Cunningham <[email protected]>
+ *
+ * This file is released under the GPLv2.
+ *
+ * Routines for handling pagesets.
+ * Note that pbes aren't actually stored as such. They're stored as
+ * ranges (extents is the term, I'm told).
+ */
+
+#define SUSPEND_PAGEDIR_C
+#include <linux/suspend.h>
+#include <linux/highmem.h>
+#include <linux/module.h>
+
+extern struct pagedir pagedir1, pagedir2, pagedir_resume;
+
+#include "suspend.h"
+#include "pageflags.h"
+
+/* setup_pbe_variable
+ *
+ * Description:	Set up one variable in a page backup entry from the range list.
+ * Arguments:	unsigned long:		The variable which will contain the 
+ * 					value.
+ * 		struct range**:		Address of the pointer to the current
+ * 					range.
+ * 		struct rangechain*:	Address of the rangechain we are 
+ * 					traversing.
+ */
+static inline void setup_pbe_variable(unsigned long * variable, struct range ** currentrange,
+		struct rangechain * chain)
+{
+	*currentrange = chain->first;
+	if (chain->first)
+		*variable = chain->first->minimum;
+	else
+		*variable = 0;
+}
+
+/* get_first_pbe
+ *
+ * Description:	Get the first page backup entry for a pagedir.
+ * Arguments:	struct pbe2 *:	Address of the page backup entry we're 
+ * 				populating.
+ * 		struct pagedir: Pagedir providing the data.
+ */
+void get_first_pbe(struct pbe2 * pbe, struct pagedir * pagedir)
+{
+	unsigned long currentorig, currentaddress;
+
+	pbe->pagedir = pagedir;
+
+	/* Get raw initial values */
+	setup_pbe_variable((unsigned long *) &pbe->origaddress, 
+			&pbe->currentorigrange, &pagedir->origranges);
+	setup_pbe_variable((unsigned long *) &pbe->address,
+			&pbe->currentdestrange, &pagedir->destranges);
+
+	/* Convert to range values */
+	currentorig = (unsigned long) pbe->origaddress;
+	currentaddress = (unsigned long) pbe->address;
+
+	pbe->origaddress = mem_map + currentorig;
+	pbe->address = mem_map + currentaddress;
+
+	if ((currentaddress < 0) || (currentaddress > max_mapnr))
+		panic("Argh! Destination range value %ld is invalid!",
+				currentaddress);
+}
+
+/* get_next_pbe
+ *
+ * Description:	Get the next page backup entry in a pagedir.
+ * Arguments:	struct pbe2 *:	Address of the pbe we're updating.
+ */
+void get_next_pbe(struct pbe2 * pbe)
+{
+	unsigned long currentorig, currentaddress;
+
+	/* Convert to range values */
+	currentorig = (pbe->origaddress - mem_map);
+	currentaddress = (pbe->address - mem_map);
+
+	/* Update values */
+	GET_RANGE_NEXT(pbe->currentorigrange, currentorig);
+	GET_RANGE_NEXT(pbe->currentdestrange, currentaddress);
+	
+	pbe->origaddress = mem_map + currentorig;
+	pbe->address = mem_map + currentaddress;
+}
+
+/*
+ * --------------------------------------------------------------------------------------
+ *
+ * 	Local Page Flags routines.
+ *
+ * 	Rather than using the rare and precious flags in struct page, we allocate
+ * 	our own bitmaps dynamically.
+ * 
+ */
+
+/* ------------------------------------------------------------------------- */
+
+/* copy_pageset1
+ *
+ * Description:	Make the atomic copy of pageset1. We can't use copy_page (as we
+ * 		once did) because we can't be sure what side effects it has. On
+ * 		my old Duron, with 3DNOW, kernel_fpu_begin increments preempt
+ * 		count, making our preempt count at resume time 4 instead of 3.
+ * 		
+ * 		We don't want to call kmap_atomic unconditionally because it has
+ * 		the side effect of incrementing the preempt count, which will
+ * 		leave it one too high post resume (the page containing the
+ * 		preempt count will be copied after its incremented. This is
+ * 		essentially the same problem.
+ */
+
+void copy_pageset1(void)
+{
+	int i = 0;
+	struct pbe2 pbe;
+
+	get_first_pbe(&pbe, &pagedir1);
+
+	for (i = 0; i < pageset1_size; i++) {
+		int loop;
+		unsigned long * origpage;
+		unsigned long * copypage = page_address(pbe.address);
+
+	       	if (PageHighMem(pbe.origaddress))
+			origpage = kmap_atomic(pbe.origaddress, KM_USER1);
+		else
+			origpage = page_address(pbe.origaddress);
+
+		for (loop=0; loop < (PAGE_SIZE / sizeof(unsigned long)); loop++)
+			*(copypage + loop) = *(origpage + loop);
+	       	if (PageHighMem(pbe.origaddress))
+			kunmap_atomic(origpage, KM_USER1);
+
+		get_next_pbe(&pbe);
+	}
+}
+
+#ifdef CONFIG_DEBUG_PAGEALLOC
+void suspend_map_atomic_copy_pages(void)
+{
+	int i = 0;
+	struct pbe2 pbe;
+
+	get_first_pbe(&pbe, &pagedir1);
+
+	for (i = 0; i < pageset1_size; i++) {
+		int orig_was_mapped = 1, copy_was_mapped = 1;
+
+	       	if (!PageHighMem(pbe.origaddress)) {
+			orig_was_mapped = suspend_map_kernel_page(pbe.origaddress, 1);
+			if (!orig_was_mapped)
+				SetPageUnmap(pbe.origaddress);
+		}
+		copy_was_mapped = suspend_map_kernel_page(pbe.address, 1);
+		if (!copy_was_mapped)
+			SetPageUnmap(pbe.address);
+
+		get_next_pbe(&pbe);
+	}
+}
+
+void suspend_unmap_atomic_copy_pages(void)
+{
+	int i;
+	for (i = 0; i < max_mapnr; i++)
+		if (PageUnmap(mem_map + i))
+			suspend_map_kernel_page(mem_map + i, 0);
+}
+#endif
+
+/* free_pagedir
+ *
+ * Description:	Free a previously allocated pagedir.
+ * Arguments:	struct pagedir *:	Pointer to the pagedir being freed.
+ */
+void free_pagedir(struct pagedir * p)
+{
+	PRINTFREEMEM("at start of free_pagedir");
+
+	if (p->allocdranges.first) {
+		/* Free allocated pages */
+		struct range * rangepointer;
+		unsigned long pagenumber;
+		range_for_each(&p->allocdranges, rangepointer, pagenumber) {
+			ClearPageNosave(mem_map+pagenumber);
+			free_page((unsigned long) page_address(mem_map+pagenumber));
+		}
+	}
+
+	suspend_store_free_mem(SUSPEND_FREE_EXTRA_PD1, 1);
+
+	/* For pagedir 2, destranges == origranges */
+	if (p->pagedir_num == 2)
+		p->destranges.first = NULL;
+	
+	put_range_chain(&p->origranges);
+	put_range_chain(&p->destranges);
+	put_range_chain(&p->allocdranges);
+
+	PRINTFREEMEM("at end of free_pagedir");
+	suspend_message(SUSPEND_PAGESETS, SUSPEND_MEDIUM, 0,
+			"Pageset size was %d.\n", p->pageset_size);
+	p->pageset_size = 0;
+}
+
+/* PageInPagedir
+ *
+ * Description:	Determine whether a page is in a pagedir.
+ * Arguments:	struct pagedir *	The pagedir to search.
+ * 		struct page *		The page to look for.
+ * Result:	int			Bitmap of state:
+ * 					Bit 0: Source page
+ * 					Bit 1: Dest page
+ * 					Bit 2: Allocated
+ * 					(Should only result in 0, 1, 2 or 6).
+ */
+
+int PageInPagedir(struct pagedir * p, struct page * page)
+{
+	int page_sought = page_to_pfn(page);
+	int result = 0;
+
+	if (p->origranges.first) {
+		struct range * rangepointer;
+		unsigned long pagenumber;
+		range_for_each(&p->origranges, rangepointer, pagenumber) {
+			if (pagenumber == page_sought)
+				result |=  1;
+			if (pagenumber >= page_sought)
+				break;
+		}
+	}
+
+	if (p->destranges.first) {
+		/* Free allocated pages */
+		struct range * rangepointer;
+		unsigned long pagenumber;
+		range_for_each(&p->destranges, rangepointer, pagenumber) {
+			if (pagenumber == page_sought)
+				result |= 2;
+			if (pagenumber >= page_sought)
+				break;
+		}
+	}
+
+	if (p->allocdranges.first) {
+		/* Free allocated pages */
+		struct range * rangepointer;
+		unsigned long pagenumber;
+		range_for_each(&p->allocdranges, rangepointer, pagenumber) {
+			if (pagenumber == page_sought)
+				result |= 4;
+			if (pagenumber >= page_sought)
+				break;
+		}
+	}
+
+	return result;
+}
+
+/* allocate_extra_pagedir_memory
+ *
+ * Description:	Allocate memory for making the atomic copy of pagedir1 in the
+ * 		case where it is bigger than pagedir2.
+ * Arguments:	struct pagedir *: 	The pagedir for which we should 
+ * 					allocate memory.
+ * 		int:			Size of pageset 1.
+ * 		int:			Size of pageset 2.
+ * Result:	int. Zero on success. One if unable to allocate enough memory.
+ */
+int allocate_extra_pagedir_memory(struct pagedir * p, int pageset_size,
+		int alloc_from)
+{
+	int num_to_alloc = pageset_size - alloc_from - p->allocdranges.size;
+	int j, order;
+
+	prepare_status(0, 0, "Preparing page directory.");
+
+	PRINTFREEMEM("at start of allocate_extra_pagedir_memory");
+
+	if (num_to_alloc < 1)
+		num_to_alloc = 0;
+
+	if (num_to_alloc) {
+		int num_added = 0, numnosaveallocated=0;
+		int origallocd = alloc_from + p->allocdranges.size;
+	
+		PRINTFREEMEM("prior to attempt");
+
+		order = generic_fls(num_to_alloc);
+		if (order >= MAX_ORDER)
+			order = MAX_ORDER - 1;
+
+		while (num_added < num_to_alloc) {
+			struct page * newpage;
+			unsigned long virt;
+			
+			while ((1 << order) > (num_to_alloc - num_added))
+				order--;
+
+			virt = get_grabbed_pages(order);
+			while ((!virt) && (order > 0)) {
+				order--;
+				virt = get_grabbed_pages(order);
+			}
+
+			if (!virt) {
+				p->pageset_size += num_added;
+				suspend_message(SUSPEND_PAGESETS, SUSPEND_VERBOSE, 1,
+					"   Allocated (extra) memory for pages"
+					" from %d-%d (%d pages).\n",
+					origallocd + 1, pageset_size, 
+					pageset_size - origallocd);
+				printk("Couldn't get enough yet."
+						" %d pages short.\n",
+						num_to_alloc - num_added);
+				PRINTFREEMEM("at abort of "
+					"allocate_extra_pagedir_memory");
+				suspend_store_free_mem(SUSPEND_FREE_EXTRA_PD1, 0);
+				return 1;
+			}
+
+			newpage = virt_to_page(virt);
+			suspend_store_free_mem(SUSPEND_FREE_EXTRA_PD1, 0);
+			for (j = 0; j < (1 << order); j++) {
+				SetPageNosave(newpage + j);
+				/* Pages will be freed one at a time. */
+				set_page_count(newpage + j, 1);
+				add_to_range_chain(&p->allocdranges, newpage - mem_map + j);
+				numnosaveallocated++;
+			}
+			suspend_store_free_mem(SUSPEND_FREE_RANGE_PAGES, 0);
+			num_added+= (1 << order);
+		}
+		suspend_message(SUSPEND_PAGESETS, SUSPEND_VERBOSE, 1,
+			"   Allocated (extra) memory for pages "
+			"from %d-%d (%d pages).\n",
+			origallocd + 1, pageset_size, 
+			pageset_size - origallocd);
+	}
+
+	p->pageset_size = pageset_size;
+
+	suspend_store_free_mem(SUSPEND_FREE_EXTRA_PD1, 0);
+	PRINTFREEMEM("at end of allocate_extra_pagedir_memory");
+	return 0;
+}
+
+/* mark_pages_for_pageset2
+ *
+ * Description:	Mark unshared pages in processes not needed for suspend as
+ * 		being able to be written out in a separate pagedir.
+ * 		HighMem pages are simply marked as pageset2. They won't be
+ * 		needed during suspend.
+ */
+
+void mark_pages_for_pageset2(void)
+{
+	int i, numpageset2 = 0;
+	struct zone * zone;
+	unsigned long flags;
+
+	if (max_mapnr != num_physpages) {
+		abort_suspend("mapnr is not expected");
+		return;
+	}
+	
+	clear_map(pageset2_map);
+
+	/* 
+	 * Note that we don't clear the map to begin with!
+	 * This is because if we eat memory, we loose track
+	 * of LRU pages that are still in use but taken off
+	 * the LRU. If I can figure out how the VM keeps
+	 * track of them, I might be able to tweak this a
+	 * little further and decrease pageset one's size
+	 * further.
+	 *
+	 * (Memory grabbing clears the pageset2 flag on
+	 * pages that are really freed!).
+	 */
+	
+	/* Add LRU pages */
+	for_each_zone(zone) {
+		spin_lock_irqsave(&zone->lru_lock, flags);
+		if (zone->nr_inactive) {
+			struct page * page;
+			list_for_each_entry(page, &zone->inactive_list, lru)
+				SetPagePageset2(page);
+		}
+		if (zone->nr_active) {
+			struct page * page;
+			list_for_each_entry(page, &zone->active_list, lru)
+				SetPagePageset2(page);
+		}
+		spin_unlock_irqrestore(&zone->lru_lock, flags);
+	}
+
+
+	/* Ensure range pages are not Pageset2 */
+	if (num_range_pages) {
+		if (get_rangepages_list())
+			return;
+
+		for (i = 1; i <= num_range_pages; i++) {
+			struct page * page;
+			page = virt_to_page(get_rangepages_list_entry(i));
+			// Must be assigned by the time recalc stats is called
+			if (PagePageset2(page)) {
+				suspend_message(SUSPEND_PAGESETS, SUSPEND_ERROR, 1,
+					"Pagedir[%d] was marked as pageset2 -"
+					" unmarking.\n", i);
+				ClearPagePageset2(page);
+				numpageset2--;
+			}
+		}
+	}
+
+	/* Finally, ensure that Slab pages are not Pageset2. */
+
+	for (i = 0; i < max_mapnr; i++) {
+		if (PageSlab(mem_map+i)) {
+			if (TestAndClearPagePageset2(mem_map+i)) {
+				//suspend_message(SUSPEND_PAGESETS, SUSPEND_ERROR, 1,
+				printk(
+					"Found page %d is slab page "
+						"but marked pageset 2.\n", i);
+				numpageset2--;
+			}
+		}
+	}
+}
+
+/* warmup_collision_cache
+ *
+ * Description:	Mark the pages which are used by the original kernel.
+ */
+void warmup_collision_cache(void) {
+	int i;
+	struct range * rangepointer = NULL;
+	unsigned long pagenumber;
+	
+	/* Allocatemap doesn't get deallocated because it's forgotten when we
+	 * copy PageDir1 back. It doesn't matter if it collides because it is
+	 * not used during the copy back itself.
+	 */
+	allocate_local_pageflags(&in_use_map, 0);
+	suspend_message(SUSPEND_IO, SUSPEND_VERBOSE, 1, "Setting up pagedir cache...");
+	for (i = 0; i < max_mapnr; i++)
+		ClearPageInUse(mem_map+i);
+
+	range_for_each(&pagedir_resume.origranges, rangepointer, pagenumber)
+		SetPageInUse(mem_map+pagenumber);
+}
+
+/* get_pageset1_load_addresses
+ * 
+ * Description: We check here that pagedir & pages it points to won't collide
+ * 		with pages where we're going to restore from the loaded pages
+ * 		later.
+ * Returns:	Zero on success, one if couldn't find enough pages (shouldn't
+ * 		happen).
+ */
+
+int get_pageset1_load_addresses(void)
+{
+	int i, nrdone = 0, result = 0;
+	void **eaten_memory = NULL, **this;
+	struct page * pageaddr = NULL;
+
+	/*
+	 * Because we're trying to make this work when we're saving as much
+	 * memory as possible we need to remember the pages we reject here
+	 * and then free them when we're done.
+	 */
+	
+	for(i=0; i < pagedir_resume.pageset_size; i++) {
+		while ((this = (void *) get_zeroed_page(GFP_ATOMIC))) {
+			memset(this, 0, PAGE_SIZE);
+			pageaddr = virt_to_page(this);
+			if (!PageInUse(pageaddr)) {
+				break;
+			}
+			*this = eaten_memory;
+			eaten_memory = this;
+		}
+		if (!this) {
+			abort_suspend("Error: Ran out of memory seeking locations for reloading data.");
+			result = 1;
+			break;
+		}
+		add_to_range_chain(&pagedir_resume.destranges, pageaddr - mem_map);
+		nrdone++;
+	}
+
+	/* Free unwanted memory */
+	while(eaten_memory) {
+		this = eaten_memory;
+		eaten_memory = *eaten_memory;
+		free_page((unsigned long) this);
+	}
+	
+	return result;
+}
+
+/* set_chain_names
+ *
+ * Description:	Set the chain names for a pagedir. (For debugging).
+ * Arguments:	struct pagedir: The pagedir on which we want to set the names.
+ */
+
+void set_chain_names(struct pagedir * p)
+{
+	p->origranges.name = "original addresses";
+	p->destranges.name =  "destination addresses";
+	p->allocdranges.name = "allocated addresses";
+}
+
+EXPORT_SYMBOL(get_first_pbe);
+EXPORT_SYMBOL(get_next_pbe);
#217 lore raw

Suspend 2 merge: 51/51: Notes

In reply to Nigel Cunningham

When I started, I thought I did have 51 patches, really! One of them turned out to be a couple of things I intend to reverse :>

In posting all of this, I recognise of course that no one else understands how it all fits together. I'm hoping that those who care enough will ask questions that I'll happily answer, learn from and through which I'll improve the code.

For now, though, I'm going to bed.

Looking forward to your feedback... and hoping not too many people fail to appreciate the volume of patches I've sent!

Nigel

#221 lore raw

Suspend 2 merge: 50/51: Device mapper support.

In reply to Nigel Cunningham

This is the device mapper support plugin. Its sole purpose is to ensure that the device mapper allocates enough memory to process all of the I/O we want to throw at it.

drivers/md/dm-io.c +7 -9
diff -ruN 856-suspend-dm-old/drivers/md/dm-io.c 856-suspend-dm-new/drivers/md/dm-io.c
@@ -214,15 +214,6 @@
  *---------------------------------------------------------------*/
 static struct bio_set _bios;
 
-/* FIXME: can we shrink this ? */
-struct io {
-	unsigned long error;
-	atomic_t count;
-	struct task_struct *sleeper;
-	io_notify_fn callback;
-	void *context;
-};
-
 /*
  * io contexts are only dynamically allocated for asynchronous
  * io.  Since async io is likely to be the majority of io we'll
@@ -247,6 +238,13 @@
 	return 4 * pages;	/* too many ? */
 }
 
+/* Wrapper for exporting this, as suspend2 dm helper code needs this */
+unsigned int dm_pages_to_ios(unsigned int pages)
+{
+	return pages_to_ios(pages);
+}
+EXPORT_SYMBOL(dm_pages_to_ios);
+
 static int resize_pool(unsigned int new_ios)
 {
 	int r = 0;
drivers/md/dm-io.h +18 -0
diff -ruN 856-suspend-dm-old/drivers/md/dm-io.h 856-suspend-dm-new/drivers/md/dm-io.h
@@ -8,6 +8,7 @@
 #define _DM_IO_H
 
 #include "dm.h"
+#include <linux/bio.h>
 
 /* FIXME make this configurable */
 #define DM_MAX_IO_REGIONS 8
@@ -30,6 +31,18 @@
  */
 typedef void (*io_notify_fn)(unsigned long error, void *context);
 
+/*
+ * Moved here from dm-io.c, as suspend2 dm code needs it
+ */
+/* FIXME: can we shrink this ? */
+struct io {
+        unsigned long error;
+        atomic_t count;
+        struct task_struct *sleeper;
+        io_notify_fn callback;
+        void *context;
+};
+
 
 /*
  * Before anyone uses the IO interface they should call
@@ -42,6 +55,11 @@
 void dm_io_put(unsigned int num_pages);
 
 /*
+ * The suspend2 dm helper code needs this one
+ */
+unsigned int dm_pages_to_ios(unsigned int pages);
+
+/*
  * Synchronous IO.
  *
  * Please ensure that the rw flag in the next two functions is
kernel/power/suspend_dm.c +136 -0

136 lines not on this page · raw message