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 2 of 2

Subsystems (53)
lore
Share & tools
lore
#156 lore raw
In reply to Pavel Machek

Hi.

Quoted 21 lines · Pavel Machek

Hi!

Quoted 12 lines
Quoted 4 lines

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.

I realise that it needs further cleanup; that's why I'm submitting it now for comment and not asking 'please apply'. As to patching against swsusp, I'm purposely not doing that. The reason is that suspend2 isn't a bunch of incremental changes to swsusp. It has been redesigned from the ground up and I'd have to pull swsusp to pieces and put it back together to do the same things.

Quoted 6 lines

I'm thus seeking to simply merge the existing code, let Pavel and others get to the point where they're ready to say "Okay, we're satisfied that suspend2 does everything swsusp does and more and better." Then we can remove swsusp. This is the plan that was discussed with Pavel and Andrew ages ago. I've just been slow to get there because I'm doing this part-time voluntary.

Quoted 3 lines

hugang seems to show that it indeed is possible to incrementally turn swsusp into suspend2. I do not think Andrew really wanted it that way, and I thought of that as of neccessary evil.

With some changes, yes. But when you come to using extents or abstracting the method of storage and implementing plugins, it will be ground-up redesign. Of course you might not want to go that far.

Quoted 4 lines

[Okay, at this point I'll understand when you'll put my picture as a texture to some doom3 monster and shoot me thousand times... Lot of work went into suspend2, but in the meantime lot of work went into swsusp1, too...]

Not at all. Perhaps I'm overstating the case or not spending enough time looking at your code, but I don't actually think swsusp has changed a lot in the two years since I started working on this. (Want my picture now? :>)

Quoted 6 lines
Quoted 6 lines
Quoted 3 lines

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

Okay. The changes include:

Quoted 8 lines
Quoted 2 lines

- Almost no BUG() statements. Wherever possible, if something goes wrong, we back out and give the user a perfectly usable system back

Patrick did a lot of work in this area, and there are 10 BUGs() in swsusp just now. [And I do not think "no BUGs()" is a feature -- look at my comments, at one point you just ignored "can not happen condition". That's bad, it can hide real bugs.] I have no reports of swsusp1 going BUG() for users, and that's what counts.

Not sure what you're talking about with the 'can not happen condition'. Regarding real reports, I agree.

Quoted 6 lines
Quoted 3 lines

- Speed: All I/O is asynchronous where possible and readahead used where not. Routines everywhere optimised to get things done as fast as poss. (Think low battery).

I fixed O(n^2) behaviour in swsusp1 (not yet in). I do not think that asynchronous I/O is does that much difference.

Oh, it makes a huge difference once you're not eating all the memory you can. If I submit I/O one at a time, I do 1 or 2 MB/s. With asynchrounous I/O, I can write 70MB/s and read 110MB/s with compression, 58|58 without compression (that's the maximum throughput of the drive I'm using at the moment). If I can streamline things a further, I should be able to lift that write rate further, too.

Quoted 8 lines
Quoted 5 lines

- Reliability. I haven't run the tests for a while, but Michael Frank produced a suite that was used to stress test the software (under 2.4) while running 100s (1000s at least once) of cycles. There have been some significant changes since then, but the software is essentially the same.

Well, swsusp1 is getting a lot of testing too. Is the test-suite somewhere easily available?

I believe Michael is preparing a new version. I assume he'll put it on
https://developer.berlios.de/projects/lstress/ when he's done.

Quoted 6 lines
Quoted 2 lines

- Test bed: Around 10,000 downloads of the 1.0 patch, 2730 to date of the 2.1.5 version I released 2 weeks ago.

Hmm, look at number of downloads of 2.6.9 kernel, I think I win here ;-)))). SuSE9.2 is actually shipping swsusp1 and advertising it as a feature. And it seems to work for people...

:> But not everyone who uses 2.6.9 uses swsusp. :>

Quoted 6 lines
Quoted 4 lines

- Swap file support
- Support for LVM/dm-crypt and siblings
- Support for having device drivers as modules (resume from an initrd/initramfs)

Okay, you win these.

I don't want to have a competition, really. I just want to convince you that I've done some worthwhile work :>

Quoted 11 lines
Quoted 2 lines

- Almost all memory allocations are order 0, making suspend more reliable under load.

I'll have to fix this. Fortunately hugang already has a patch.

Quoted 2 lines

- Designed to save as much of memory as possible rather than as little (making the system more responsive post-resume).

hugang already has a patch, but I'm not 100% sure if I want it in. Yes, people seem to like this feature, but it complicates *design*, quite a lot.

It does. But if there were fundamental flaws in the approach, we would have found them by now. Since you're using bio calls and not swap's own read/write functions, you shouldn't have any problems.

Quoted 6 lines
Quoted 3 lines

- Support for SMP
- Support for preempt
- Support for 4GB highmem (hope to do 64GB soonish)

This works in swsusp1, too. Parts of SMP support need to be rewritten to assembly, but same is probably true for suspend2.

See separate comments - I think it can all stay as C.

Quoted 5 lines

I'm not sure if there are still problems with swsusp1 refrigerator, if so add

- Suspend2 actually works under load

Hopefully, we'll merge the refrigerator changes soon; then you can say that for swsusp1 too.

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
#157 lore raw

Hi!

Quoted 7 lines
Quoted 7 lines
Quoted 6 lines

I'm thus seeking to simply merge the existing code, let Pavel and others get to the point where they're ready to say "Okay, we're satisfied that suspend2 does everything swsusp does and more and better." Then we can remove swsusp. This is the plan that was discussed with Pavel and Andrew ages ago. I've just been slow to get there because I'm doing this part-time voluntary.

Quoted 7 lines
Quoted 3 lines

hugang seems to show that it indeed is possible to incrementally turn swsusp into suspend2. I do not think Andrew really wanted it that way, and I thought of that as of neccessary evil.

With some changes, yes. But when you come to using extents or abstracting the method of storage and implementing plugins, it will be ground-up redesign. Of course you might not want to go that far.

I'd prefer not to get plugins and abstract storage. I'm not sure about extents, but as soon as I can get rid of order-8 allocations, things should be ok.

Quoted 9 lines
Quoted 4 lines

[Okay, at this point I'll understand when you'll put my picture as a texture to some doom3 monster and shoot me thousand times... Lot of work went into suspend2, but in the meantime lot of work went into swsusp1, too...]

Not at all. Perhaps I'm overstating the case or not spending enough time looking at your code, but I don't actually think swsusp has changed a lot in the two years since I started working on this. (Want my picture now? :>)

Well, it was rewriten by Patrick so it actually looks okay, and it started to work for users...

Quoted 7 lines
Quoted 6 lines
Quoted 3 lines

- Speed: All I/O is asynchronous where possible and readahead used where not. Routines everywhere optimised to get things done as fast as poss. (Think low battery).

I fixed O(n^2) behaviour in swsusp1 (not yet in). I do not think that asynchronous I/O is does that much difference.

Quoted 6 lines

Oh, it makes a huge difference once you're not eating all the memory you can. If I submit I/O one at a time, I do 1 or 2 MB/s. With asynchrounous I/O, I can write 70MB/s and read 110MB/s with compression, 58|58 without compression (that's the maximum throughput of the drive I'm using at the moment). If I can streamline things a further, I should be able to lift that write rate further, too.

Okay, 58MB/sec is better than 1MB/sec. I do not think I want the complexity neccessary to get me 70MB/sec.

In some ways, suspend2 is two years ahead of rest of kernel:
* you have interactive debugging
* file compression
* nice splash screen
* plugin interface for transparent network support

Unfortunately, we do not want compression done like that. It would make sense to do compressed-LVM or something like that (that way everyone would get the benefit), but it does not make sense to have it just for suspend2. And we do not want the rest of features, too, unless they work for the rest of kernel.

Quoted 8 lines
Quoted 6 lines
Quoted 2 lines

- Test bed: Around 10,000 downloads of the 1.0 patch, 2730 to date of the 2.1.5 version I released 2 weeks ago.

Hmm, look at number of downloads of 2.6.9 kernel, I think I win here ;-)))). SuSE9.2 is actually shipping swsusp1 and advertising it as a feature. And it seems to work for people...

:> But not everyone who uses 2.6.9 uses swsusp. :>

But they should ;-).

Quoted 9 lines
Quoted 6 lines
Quoted 4 lines

- Swap file support
- Support for LVM/dm-crypt and siblings
- Support for having device drivers as modules (resume from an initrd/initramfs)

Okay, you win these.

I don't want to have a competition, really. I just want to convince you that I've done some worthwhile work :>

You did wonderfull work -- you shown what is possible with suspend2. Now we just need to scale it back to what is practical. It needs not only to work, it also needs to be nice, simple, and easy to maintain.

Quoted 10 lines
Quoted 6 lines
Quoted 2 lines

- Designed to save as much of memory as possible rather than as little (making the system more responsive post-resume).

hugang already has a patch, but I'm not 100% sure if I want it in. Yes, people seem to like this feature, but it complicates *design*, quite a lot.

It does. But if there were fundamental flaws in the approach, we would have found them by now. Since you're using bio calls and not swap's own read/write functions, you shouldn't have any problems.

I believe it has at least one pretty bad flaw: it has hooks all over the place and will be nightmare to maintain. Puting suspend hooks into memory allocation is not nice.

swsusp1 is pretty self-contained. As long as drivers stop the DMA and NMI does nothing wrong, atomic snapshot will indeed be atomic.

Can you list conditions neccessary for suspend2 to work?

Pavel

Signature · 2 lines
People were complaining that M$ turns users into beta-testers...
...jr ghea gurz vagb qrirybcref, naq gurl frrz gb yvxr vg gung jnl!
#158 lore raw

Hi.

Quoted 3 lines · Pavel Machek

I'd prefer not to get plugins and abstract storage. I'm not sure about extents, but as soon as I can get rid of order-8 allocations, things should be ok.

Don't you need more than that? Unless things have changed, you still spend most of your time eating memory so that you only have a few megs (well, maybe a little more) to write to disk. If you do reduce the amount of memory you eat, then you need to work to make the I/O faster.

Quoted 5 lines
Quoted 5 lines
Quoted 4 lines

[Okay, at this point I'll understand when you'll put my picture as a texture to some doom3 monster and shoot me thousand times... Lot of work went into suspend2, but in the meantime lot of work went into swsusp1, too...]

Quoted 7 lines
Quoted 4 lines

Not at all. Perhaps I'm overstating the case or not spending enough time looking at your code, but I don't actually think swsusp has changed a lot in the two years since I started working on this. (Want my picture now? :>)

Well, it was rewriten by Patrick so it actually looks okay, and it started to work for users...

:> Okay.

Quoted 14 lines
Quoted 7 lines
Quoted 6 lines
Quoted 3 lines

- Speed: All I/O is asynchronous where possible and readahead used where not. Routines everywhere optimised to get things done as fast as poss. (Think low battery).

I fixed O(n^2) behaviour in swsusp1 (not yet in). I do not think that asynchronous I/O is does that much difference.

Quoted 6 lines

Oh, it makes a huge difference once you're not eating all the memory you can. If I submit I/O one at a time, I do 1 or 2 MB/s. With asynchrounous I/O, I can write 70MB/s and read 110MB/s with compression, 58|58 without compression (that's the maximum throughput of the drive I'm using at the moment). If I can streamline things a further, I should be able to lift that write rate further, too.

Quoted 2 lines

Okay, 58MB/sec is better than 1MB/sec. I do not think I want the complexity neccessary to get me 70MB/sec.

Fair enough for you, but not everyone can say that. At the end of the day, I'm not writing this code just for me to use, though. Many of the features I've added have been added for the benefit of other people; I assume you'd do the same. Most laptops can't do 58MB/s, so the difference is much bigger. (My original laptop hard drive did 17/s; with compression I think it achieved something close to double that, depending on the data being compressed, of course).

Quoted 11 lines

In some ways, suspend2 is two years ahead of rest of kernel:
* you have interactive debugging
* file compression
* nice splash screen
* plugin interface for transparent network support

Unfortunately, we do not want compression done like that. It would make sense to do compressed-LVM or something like that (that way everyone would get the benefit), but it does not make sense to have it just for suspend2. And we do not want the rest of features, too, unless they work for the rest of kernel.

The cryptoapi provides support for both compression and encryption. I'd happily make use of that, but we still need a way for the user to choose what compression/encryption they want and configure it. I'm not at all adverse to the idea of shifting the lzf compression support into being a cryptoapi plugin. That shouldn't be hard to do precisely because I have the plugin system :>.

Quoted 10 lines
Quoted 8 lines
Quoted 6 lines
Quoted 2 lines

- Test bed: Around 10,000 downloads of the 1.0 patch, 2730 to date of the 2.1.5 version I released 2 weeks ago.

Hmm, look at number of downloads of 2.6.9 kernel, I think I win here ;-)))). SuSE9.2 is actually shipping swsusp1 and advertising it as a feature. And it seems to work for people...

:> But not everyone who uses 2.6.9 uses swsusp. :>

But they should ;-).

I'll beg to differ there :>

Quoted 7 lines
Quoted 7 lines
Quoted 6 lines
Quoted 4 lines

- Swap file support
- Support for LVM/dm-crypt and siblings
- Support for having device drivers as modules (resume from an initrd/initramfs)

Okay, you win these.

Quoted 7 lines
Quoted 2 lines

I don't want to have a competition, really. I just want to convince you that I've done some worthwhile work :>

You did wonderfull work -- you shown what is possible with suspend2. Now we just need to scale it back to what is practical. It needs not only to work, it also needs to be nice, simple, and easy to maintain.

I think it is practical. Apart from the bootsplash support, I don't think I have added any feature because I thought "Hey, this looks like a fun thing to try.". Every feature has been added because it makes suspend faster, more reliable, more user friendly, more versatile or the like. If we want Linux to get adopted by desktop users, it needs to have these features. Making it harder to use by forcing people to reboot to change a parameter or forcing them to do an ls in /dev with obscure parameters (to get the major and minor numbers) when they already know they want /dev/sda1 isn't user friendly. Obviously user friendliness is more important to me than to you. That's fine, but let's agree to differ and let the software be more helpful rather than less.

Quoted 7 lines
Quoted 7 lines
Quoted 6 lines
Quoted 2 lines

- Designed to save as much of memory as possible rather than as little (making the system more responsive post-resume).

hugang already has a patch, but I'm not 100% sure if I want it in. Yes, people seem to like this feature, but it complicates *design*, quite a lot.

Quoted 7 lines
Quoted 3 lines

It does. But if there were fundamental flaws in the approach, we would have found them by now. Since you're using bio calls and not swap's own read/write functions, you shouldn't have any problems.

I believe it has at least one pretty bad flaw: it has hooks all over the place and will be nightmare to maintain. Puting suspend hooks into memory allocation is not nice.

That's a big statement.

"Hooks all over the place" was a phrase first used to refer to the attempts at making freezing more reliable. That's irrelevant now with the simplified three stages to freezing. The hooks are the same as for swsusp1 there.

The hooks you've seen in the rest of the kernel are generally only further supplements to the freezing, so that swsusp should probably have them too.

The hooks in the memory management are minimal and wrapped in unlikely(), so they shouldn't really be a problem in the normal flow of things. While suspend is running, they serve a good and necessary purpose. Using high level routines, we can't guarantee that new slab pages, for example, aren't allocated while we're writing the LRU pages. If you can't be sure of that and don't want to satisfy allocations from a memory pool, you'll need to recheck that your saving all the pages after writing LRU. And if you do that, you might need to allocate more memory for the metadata, which might mean freeing an LRU page or two, which will make your image inconsistent. A memory pool is a simple and effective solution to that issue: we know exactly what pages may be allocated when we do our atomic copy, and we copy them without having to figure out which ones were actually used.

Quoted 4 lines

swsusp1 is pretty self-contained. As long as drivers stop the DMA and NMI does nothing wrong, atomic snapshot will indeed be atomic.

Can you list conditions neccessary for suspend2 to work?

Not really sure what you mean. At the moment, the main hinderance to it working properly is driver model support (USB, DRI, as said previously). That forces us to have a userspace script to compile as modules and stop/unload support around kernel call. Given that these things are done, and that suspend is able to get enough memory to do it's work (almost never a problem), suspend should always work.

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
#159 lore raw

Hi!

Quoted 9 lines
Quoted 3 lines

I'd prefer not to get plugins and abstract storage. I'm not sure about extents, but as soon as I can get rid of order-8 allocations, things should be ok.

Don't you need more than that? Unless things have changed, you still spend most of your time eating memory so that you only have a few megs (well, maybe a little more) to write to disk. If you do reduce the amount of memory you eat, then you need to work to make the I/O faster.

I'm not *that* concerned about speed. Getting rid of order-8 is for preventing "sorry, not enough RAM to suspend to disk".

Quoted 10 lines
Quoted 2 lines

Okay, 58MB/sec is better than 1MB/sec. I do not think I want the complexity neccessary to get me 70MB/sec.

Fair enough for you, but not everyone can say that. At the end of the day, I'm not writing this code just for me to use, though. Many of the features I've added have been added for the benefit of other people; I assume you'd do the same. Most laptops can't do 58MB/s, so the difference is much bigger. (My original laptop hard drive did 17/s; with compression I think it achieved something close to double that, depending on the data being compressed, of course).

I do have too fast machines around me. But notice that compression only does factor-2 speedup. If we wanted to make whole kernel uglier, we could probably achieve factor-2 speedup for any benchmark... just it would be bad idea.

Quoted 12 lines
Quoted 11 lines

In some ways, suspend2 is two years ahead of rest of kernel:
* you have interactive debugging
* file compression
* nice splash screen
* plugin interface for transparent network support

Unfortunately, we do not want compression done like that. It would make sense to do compressed-LVM or something like that (that way everyone would get the benefit), but it does not make sense to have it just for suspend2. And we do not want the rest of features, too, unless they work for the rest of kernel.

Quoted 6 lines

The cryptoapi provides support for both compression and encryption. I'd happily make use of that, but we still need a way for the user to choose what compression/encryption they want and configure it. I'm not at all adverse to the idea of shifting the lzf compression support into being a cryptoapi plugin. That shouldn't be hard to do precisely because I have the plugin system :>.

Actually I'd like to see lzf done at LVM level; that way it is usefull for people not doing suspend, too, and we should not need plugin infrastructure in suspend2 (LVM provides us with that service).

Quoted 10 lines
Quoted 4 lines

You did wonderfull work -- you shown what is possible with suspend2. Now we just need to scale it back to what is practical. It needs not only to work, it also needs to be nice, simple, and easy to maintain.

I think it is practical. Apart from the bootsplash support, I don't think I have added any feature because I thought "Hey, this looks like a fun thing to try.". Every feature has been added because it makes suspend faster, more reliable, more user friendly, more versatile or the like. If we want Linux to get adopted by desktop users, it needs to

I believe you need to say "no" way more often. One user is not enough to justify feature in mainline kernel, and any number of users should not be enough to make GZIP compression supported by suspend2.

Quoted 7 lines

have
these features. Making it harder to use by forcing people to reboot to change a parameter or forcing them to do an ls in /dev with obscure parameters (to get the major and minor numbers) when they already know they want /dev/sda1 isn't user friendly. Obviously user friendliness is more important to me than to you. That's fine, but let's agree to differ and let the software be more helpful rather than less.

Yes, I care about linux being developer-friendly. If it is not user-friendly, distributions will solve it. If it is not developer-friendly, it is dead.

Quoted 15 lines
Quoted 7 lines
Quoted 3 lines

It does. But if there were fundamental flaws in the approach, we would have found them by now. Since you're using bio calls and not swap's own read/write functions, you shouldn't have any problems.

I believe it has at least one pretty bad flaw: it has hooks all over the place and will be nightmare to maintain. Puting suspend hooks into memory allocation is not nice.

That's a big statement.

"Hooks all over the place" was a phrase first used to refer to the attempts at making freezing more reliable. That's irrelevant now with the simplified three stages to freezing. The hooks are the same as for swsusp1 there.

Quoted 7 lines

The hooks you've seen in the rest of the kernel are generally only further supplements to the freezing, so that swsusp should probably have them too.

The hooks in the memory management are minimal and wrapped in unlikely(), so they shouldn't really be a problem in the normal flow of

Yes, they are unlikely(); but still they are hooks into memory managment. They are at least ugly as hell. And no swsusp1 does not this particular set of hooks, and does not need to patch sysrq-S.

Quoted 2 lines

things. While suspend is running, they serve a good and necessary purpose. Using high level routines, we can't guarantee that new slab

They are neccessary because of two-stages LRU saving... I'm trying to argue "two-stages LRU saving is wrong"...

Quoted 11 lines
Quoted 4 lines

swsusp1 is pretty self-contained. As long as drivers stop the DMA and NMI does nothing wrong, atomic snapshot will indeed be atomic.

Can you list conditions neccessary for suspend2 to work?

Not really sure what you mean. At the moment, the main hinderance to it working properly is driver model support (USB, DRI, as said previously). That forces us to have a userspace script to compile as modules and stop/unload support around kernel call. Given that these things are done, and that suspend is able to get enough memory to do it's work (almost never a problem), suspend should always work.

No, assume driver problems are solved.

For swsusp2, you need drivers to stop the DMA, NMI not interfering, sync may not happen after you have saved LRU, memory may not be alocated from slab after you have saved LRU. (something else? This needs to be written down somewhere, and all kernel hackers will need to be carefull not to break these rules. Do you see why it wories me?)

swsusp1 is more self-contained. As long as drivers stop the DMA and NMI does nothing wrong, atomic snapshot will indeed be atomic.

Pavel

Signature · 2 lines
People were complaining that M$ turns users into beta-testers...
...jr ghea gurz vagb qrirybcref, naq gurl frrz gb yvxr vg gung jnl!

A message that is not in the archive (sent off-list or not yet received): [email protected]

#161 lore raw

Hi.

Quoted 10 lines · On Fri, 2004-11-26 at 15:32, [email protected] wrote:
Quoted 5 lines

For swsusp2, you need drivers to stop the DMA, NMI not interfering, sync may not happen after you have saved LRU, memory may not be alocated from slab after you have saved LRU. (something else? This needs to be written down somewhere, and all kernel hackers will need to be carefull not to break these rules. Do you see why it wories me?)

Ok, I got it. I think making LRU safe must sure
1: LRU can't change after saved.
2: LRU memory can't change after saved.
The first one is done, the second we can't sure in current design, can we using COW do it?

2 is simple: LRU doesn't change because everything that would change it is frozen, and the memory pool hooks ensure that scanning of the list doesn't happen while suspending either.

I don't see the point to saving LRU pages separately when you're still eating all the memory you can. You'll have the same number of pages to save, just fewer to copy (and copying takes far less time than saving).

Quoted 2 lines

Pagecaches still in, but disable by default, active using sysctl, I'd like not merge it right now, Hope other chagnes can merge into. :)

Pavel's going to think you are trying to turn swsusp into suspend2!!

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
#162 lore raw

Hi!

Quoted 8 lines

I don't see the point to saving LRU pages separately when you're still eating all the memory you can. You'll have the same number of pages to save, just fewer to copy (and copying takes far less time than saving).

Quoted 2 lines

Pagecaches still in, but disable by default, active using sysctl, I'd like not merge it right now, Hope other chagnes can merge into. :)

Pavel's going to think you are trying to turn swsusp into suspend2!!

Pavel knows that already, but at least hugang is producing small patches ;-).
Pavel

Signature · 2 lines
People were complaining that M$ turns users into beta-testers...
...jr ghea gurz vagb qrirybcref, naq gurl frrz gb yvxr vg gung jnl!
#163 lore raw
In reply to a message not in the archive

Hi!

Quoted 5 lines

Ok, I got it. I think making LRU safe must sure
1: LRU can't change after saved.
2: LRU memory can't change after saved.
The first one is done, the second we can't sure in current design, can we using COW do it?

Userspace processes should be stopped at that point, and you really can't do COW to kernel users.

Quoted 8 lines
Quoted 2 lines

swsusp1 is more self-contained. As long as drivers stop the DMA and NMI does nothing wrong, atomic snapshot will indeed be atomic.

Here is my current patch still relative with your bit diff, only core part here.
1: adding a collide bitmap for speedup collide check, I can't sure
four pages is enough, pavel please check.
2: swith list_for_xxx style
3: corrent calc_nums.

Heh, can you try this after resume?

cat cat [0-9]*/maps | grep / | sed 's:.* /:/:' | sort -u > /dev/null

It should have very similar effect to saving LRU, just in one line of code ;-).

Pavel

Signature · 2 lines
People were complaining that M$ turns users into beta-testers...
...jr ghea gurz vagb qrirybcref, naq gurl frrz gb yvxr vg gung jnl!
#164 lore raw
In reply to Pavel Machek

Hi.

Quoted 6 lines · Pavel Machek

Hi!

Quoted 4 lines
Quoted 3 lines

I'd prefer not to get plugins and abstract storage. I'm not sure about extents, but as soon as I can get rid of order-8 allocations, things should be ok.

Quoted 8 lines
Quoted 5 lines

Don't you need more than that? Unless things have changed, you still spend most of your time eating memory so that you only have a few megs (well, maybe a little more) to write to disk. If you do reduce the amount of memory you eat, then you need to work to make the I/O faster.

I'm not *that* concerned about speed. Getting rid of order-8 is for preventing "sorry, not enough RAM to suspend to disk".

Priority wise, I agree. But given that the order 8 issue is dealt with, speed is important. Particularly when your power just went out and your UPS battery is running down.

Quoted 11 lines
Quoted 10 lines
Quoted 2 lines

Okay, 58MB/sec is better than 1MB/sec. I do not think I want the complexity neccessary to get me 70MB/sec.

Fair enough for you, but not everyone can say that. At the end of the day, I'm not writing this code just for me to use, though. Many of the features I've added have been added for the benefit of other people; I assume you'd do the same. Most laptops can't do 58MB/s, so the difference is much bigger. (My original laptop hard drive did 17/s; with compression I think it achieved something close to double that, depending on the data being compressed, of course).

Quoted 4 lines

I do have too fast machines around me. But notice that compression only does factor-2 speedup. If we wanted to make whole kernel uglier, we could probably achieve factor-2 speedup for any benchmark... just it would be bad idea.

Again, when you're running on limited time, twice as fast is still twice as fast.

Quoted 19 lines
Quoted 12 lines
Quoted 11 lines

In some ways, suspend2 is two years ahead of rest of kernel:
* you have interactive debugging
* file compression
* nice splash screen
* plugin interface for transparent network support

Unfortunately, we do not want compression done like that. It would make sense to do compressed-LVM or something like that (that way everyone would get the benefit), but it does not make sense to have it just for suspend2. And we do not want the rest of features, too, unless they work for the rest of kernel.

Quoted 6 lines

The cryptoapi provides support for both compression and encryption. I'd happily make use of that, but we still need a way for the user to choose what compression/encryption they want and configure it. I'm not at all adverse to the idea of shifting the lzf compression support into being a cryptoapi plugin. That shouldn't be hard to do precisely because I have the plugin system :>.

Quoted 3 lines

Actually I'd like to see lzf done at LVM level; that way it is usefull for people not doing suspend, too, and we should not need plugin infrastructure in suspend2 (LVM provides us with that service).

That ignores that the vast majority of people don't use LVM at the moment. Perhaps you could argue that they should. The other thing is, I'm trying not to make assumptions about how we're writing the image, either. If you want to pipe your image over a network to some server, you should be able to, and not have to implement compression again in the writer for that.

Quoted 11 lines
Quoted 10 lines
Quoted 4 lines

You did wonderfull work -- you shown what is possible with suspend2. Now we just need to scale it back to what is practical. It needs not only to work, it also needs to be nice, simple, and easy to maintain.

I think it is practical. Apart from the bootsplash support, I don't think I have added any feature because I thought "Hey, this looks like a fun thing to try.". Every feature has been added because it makes suspend faster, more reliable, more user friendly, more versatile or the like. If we want Linux to get adopted by desktop users, it needs to

Quoted 3 lines

I believe you need to say "no" way more often. One user is not enough to justify feature in mainline kernel, and any number of users should not be enough to make GZIP compression supported by suspend2.

Okay. Let's say I drop GZIP. I've just asked on the suspend list for good reasons not to do it. I'll be surprised if I get any :> (And I'll ask for proof that they get a higher throughput with GZIP then with LZF!).

I still think the plugin system is useful. It made adding LZF compression and DM support really easy, and also means work can be done on a generic file writer without needing to pull out all of the swapwriter code. It also made making suspend modular far easier, which in turn means you don't have to have the memory in use all the time, when you only really want it the functionality ready to go when you want to power down.

Quoted 15 lines
Quoted 15 lines
Quoted 3 lines

I believe it has at least one pretty bad flaw: it has hooks all over the place and will be nightmare to maintain. Puting suspend hooks into memory allocation is not nice.

That's a big statement.

"Hooks all over the place" was a phrase first used to refer to the attempts at making freezing more reliable. That's irrelevant now with the simplified three stages to freezing. The hooks are the same as for swsusp1 there.

The hooks you've seen in the rest of the kernel are generally only further supplements to the freezing, so that swsusp should probably have them too.

Quoted 7 lines
Quoted 3 lines

The hooks in the memory management are minimal and wrapped in unlikely(), so they shouldn't really be a problem in the normal flow of

Yes, they are unlikely(); but still they are hooks into memory managment. They are at least ugly as hell. And no swsusp1 does not this particular set of hooks, and does not need to patch sysrq-S.

How is ugly defined here? Can you give me an example that does the same thing, but which you consider less ugly?

        if (unlikely(test_suspend_state(SUSPEND_USE_MEMORY_POOL))) {
                suspend2_free_pool_pages(page, order);
                return;
        }

I nearly launched into a flame war, but I'll try to be more gracious than that.

Quoted 5 lines
Quoted 2 lines

things. While suspend is running, they serve a good and necessary purpose. Using high level routines, we can't guarantee that new slab

They are neccessary because of two-stages LRU saving... I'm trying to argue "two-stages LRU saving is wrong"...

I know you are. What I'm not sure about is whether you believe that the user should never have the option of saving a full image of their memory, or whether you think there's a better way to do it.

Quoted 5 lines
Quoted 5 lines
Quoted 4 lines

swsusp1 is pretty self-contained. As long as drivers stop the DMA and NMI does nothing wrong, atomic snapshot will indeed be atomic.

Can you list conditions neccessary for suspend2 to work?

Quoted 8 lines
Quoted 6 lines

Not really sure what you mean. At the moment, the main hinderance to it working properly is driver model support (USB, DRI, as said previously). That forces us to have a userspace script to compile as modules and stop/unload support around kernel call. Given that these things are done, and that suspend is able to get enough memory to do it's work (almost never a problem), suspend should always work.

No, assume driver problems are solved.

Okay.

Quoted 8 lines

For swsusp2, you need drivers to stop the DMA, NMI not interfering, sync may not happen after you have saved LRU, memory may not be alocated from slab after you have saved LRU. (something else? This needs to be written down somewhere, and all kernel hackers will need to be carefull not to break these rules. Do you see why it wories me?)

swsusp1 is more self-contained. As long as drivers stop the DMA and NMI does nothing wrong, atomic snapshot will indeed be atomic.

Syncing may not happen after we've done the atomic copy, but since it is already done when freezing processes, there shouldn't be any dirty data to sync anyway... except for the syslog data from our printks.

The LRU pages can't change, but this shouldn't be a problem because all userspace threads and most of kernel space, including kswapd, kjournald and so on is stopped. The only guys who need to worry about this are the MM guys, and so long as the scanning continues to run via a process, the buddy allocator or a timer (interrupts aren't an option, are they?), that activity will be paused during suspend without them having to add a single line of code.

If bio page I/O was changed to interact with the LRU, we might be in trouble.

Slab _can_ be allocated while we're saving the LRU, but the allocations need to come from pages that we know will be included in the atomic copy. This happens transparently (page allocator), so other kernel hackers don't need to worry about any of these issues. If we use the memory pool idea, everything else that needs to run can run just like normal, without any suspend specific changes. (You might be being confused here by those printks in the slab get-a-new-page code; I guess I forgot to write at the top of that patch that the printks are only there while I'm seeking to determine whether suspend is the cause of some occasional slab corruption I've been seeing. I'm trying to determine whether the pages I see the oops at are ones allocated while writing the image, or not. Unfortunately, it happens so infrequently that I am taking a long time to see.

DMA only needs to be stopped when the drivers are quiesced, which is not a suspend2 specific requirement.

The NMI watchdog turned out not to be a problem at all.

In short, there are no rules that "all kernel hackers" will need to be careful not to break. The main thing constraint added is that we need to be able to stop all changes to the LRU.

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
#165 lore raw

Hi!

Quoted 12 lines
Quoted 8 lines
Quoted 5 lines

Don't you need more than that? Unless things have changed, you still spend most of your time eating memory so that you only have a few megs (well, maybe a little more) to write to disk. If you do reduce the amount of memory you eat, then you need to work to make the I/O faster.

I'm not *that* concerned about speed. Getting rid of order-8 is for preventing "sorry, not enough RAM to suspend to disk".

Priority wise, I agree. But given that the order 8 issue is dealt with, speed is important. Particularly when your power just went out and your UPS battery is running down.

....

Quoted 2 lines

Again, when you're running on limited time, twice as fast is still twice as fast.

My machine suspends in 7 seconds, and that's swsusp1. According to your numbers, suspend2 should suspend it in 1 second and LZE compressed should be .5 second.

I'd say "who cares". 7 seconds seems like fast enough for me. And I'm *not* going to add 2000 lines of code for 500msec speedup during suspend.

Quoted 10 lines
Quoted 3 lines

Actually I'd like to see lzf done at LVM level; that way it is usefull for people not doing suspend, too, and we should not need plugin infrastructure in suspend2 (LVM provides us with that service).

That ignores that the vast majority of people don't use LVM at the moment. Perhaps you could argue that they should. The other thing is, I'm trying not to make assumptions about how we're writing the image, either. If you want to pipe your image over a network to some server, you should be able to, and not have to implement compression again in the writer for that.

Suspend-over-network is obscure-enough feature. Compressed-suspend-over-network is even worse.

BTW my feeling is that if you want to do suspend-over-network, you should just modify nbd to work with suspend2 and stop adding special-purpose code to suspend.

Quoted 25 lines
Quoted 3 lines

I believe you need to say "no" way more often. One user is not enough to justify feature in mainline kernel, and any number of users should not be enough to make GZIP compression supported by suspend2.

Okay. Let's say I drop GZIP. I've just asked on the suspend list for good reasons not to do it. I'll be surprised if I get any :> (And I'll ask for proof that they get a higher throughput with GZIP then with LZF!).

I still think the plugin system is useful. It made adding LZF compression and DM support really easy, and also means work can be done on a generic file writer without needing to pull out all of the swapwriter code. It also made making suspend modular far easier, which in turn means you don't have to have the memory in use all the time, when you only really want it the functionality ready to go when you want to power down.

Quoted 3 lines

Yes, they are unlikely(); but still they are hooks into memory managment. They are at least ugly as hell. And no swsusp1 does not this particular set of hooks, and does not need to patch sysrq-S.

How is ugly defined here? Can you give me an example that does the same thing, but which you consider less ugly?

Quoted 7 lines
        if (unlikely(test_suspend_state(SUSPEND_USE_MEMORY_POOL))) {
                suspend2_free_pool_pages(page, order);
                return;
        }

I nearly launched into a flame war, but I'll try to be more gracious than that.

Memory managment should have no knowledge of suspend2... Imagine every subsystem sprinkling hooks such as this one...

We'd have

	if (unlikely(scsi_is_recovering_from_problem()))
		scsi_free_pool_pages();
	else if (usb_is_unhealthy())
		usb_recover()
	else if (unlikely(test_suspend_state(SUSPEND_USE_MEMORY_POOL))) {
                suspend2_free_pool_pages(page, order);
                return;
        }

and every one hacking memory managment would know about scsi, usb, and suspend2. That's not reasonable way to go.

Quoted 9 lines
Quoted 5 lines
Quoted 2 lines

things. While suspend is running, they serve a good and necessary purpose. Using high level routines, we can't guarantee that new slab

They are neccessary because of two-stages LRU saving... I'm trying to argue "two-stages LRU saving is wrong"...

I know you are. What I'm not sure about is whether you believe that the user should never have the option of saving a full image of their memory, or whether you think there's a better way to do it.

If LRU saving can be done in 300 lines of code with no impact on generic code... that's okay. In the current form it is way too complex to merge.

Quoted 6 lines
Quoted 6 lines

For swsusp2, you need drivers to stop the DMA, NMI not interfering, sync may not happen after you have saved LRU, memory may not be alocated from slab after you have saved LRU. (something else? This needs to be written down somewhere, and all kernel hackers will need to be carefull not to break these rules. Do you see why it wories me?)

Quoted 6 lines
Quoted 2 lines

swsusp1 is more self-contained. As long as drivers stop the DMA and NMI does nothing wrong, atomic snapshot will indeed be atomic.

Syncing may not happen after we've done the atomic copy, but since it is already done when freezing processes, there shouldn't be any dirty data to sync anyway... except for the syslog data from our printks.

??? syslogd is stopped, it can't write anything.

Quoted 7 lines

The LRU pages can't change, but this shouldn't be a problem because all userspace threads and most of kernel space, including kswapd, kjournald and so on is stopped. The only guys who need to worry about this are the MM guys, and so long as the scanning continues to run via a process, the buddy allocator or a timer (interrupts aren't an option, are they?), that activity will be paused during suspend without them having to add a single line of code.

Actually swsusp1 does not need to stop timers, so you have few lines of code added.

Quoted 9 lines

If bio page I/O was changed to interact with the LRU, we might be in trouble.

Slab _can_ be allocated while we're saving the LRU, but the allocations need to come from pages that we know will be included in the atomic copy. This happens transparently (page allocator), so other kernel hackers don't need to worry about any of these issues. If we use the memory pool idea, everything else that needs to run can run just like normal, without any suspend specific changes. (You might be being

Why do you need to allocate from special pool? After LRU is saved, you should write all used kernel pages. Slab are kernel pages, so I do not see why you need to modify it.

Quoted 3 lines

In short, there are no rules that "all kernel hackers" will need to be careful not to break. The main thing constraint added is that we need to be able to stop all changes to the LRU.

Ok, so the "all kernel hackers" rule is "do not change LRU while suspend2 is going on".
Pavel

Signature · 2 lines
People were complaining that M$ turns users into beta-testers...
...jr ghea gurz vagb qrirybcref, naq gurl frrz gb yvxr vg gung jnl!
#166 lore raw
Quoted 10 lines · Pavel Machek
Quoted 2 lines

Again, when you're running on limited time, twice as fast is still twice as fast.

My machine suspends in 7 seconds, and that's swsusp1. According to your numbers, suspend2 should suspend it in 1 second and LZE compressed should be .5 second.

I'd say "who cares". 7 seconds seems like fast enough for me. And I'm *not* going to add 2000 lines of code for 500msec speedup during suspend.

Yupp. Premature optimization is the roo of all evil. swsusp is

a) an absolute slowpath compared to any normal kernel operation, and called extremly seldomly
b) only usefull for a small subset of all linux instances

hacking core code (fastpathes) for speedups there is a really bad idea. If you can speed it up without beeing intrusive all power to you.

Quoted 11 lines
Quoted 4 lines

I'm trying not to make assumptions about how we're writing the image, either. If you want to pipe your image over a network to some server, you should be able to, and not have to implement compression again in the writer for that.

Suspend-over-network is obscure-enough feature. Compressed-suspend-over-network is even worse.

BTW my feeling is that if you want to do suspend-over-network, you should just modify nbd to work with suspend2 and stop adding special-purpose code to suspend.

Honestly I think it's a feature so obscure that we wouldn't ever want to merge it unless it just happens to work as a fallout of a more important feature.

#167 lore raw

Hi!

Quoted 11 lines
Quoted 10 lines
Quoted 2 lines

Again, when you're running on limited time, twice as fast is still twice as fast.

My machine suspends in 7 seconds, and that's swsusp1. According to your numbers, suspend2 should suspend it in 1 second and LZE compressed should be .5 second.

I'd say "who cares". 7 seconds seems like fast enough for me. And I'm *not* going to add 2000 lines of code for 500msec speedup during suspend.

Quoted 8 lines

Yupp. Premature optimization is the roo of all evil. swsusp is

a) an absolute slowpath compared to any normal kernel operation, and called extremly seldomly
b) only usefull for a small subset of all linux instances

hacking core code (fastpathes) for speedups there is a really bad idea. If you can speed it up without beeing intrusive all power to you.

I have to agree here. Swsusp is not really performance critical, almost every other part of kernel is more important.

Pavel

Signature · 2 lines
People were complaining that M$ turns users into beta-testers...
...jr ghea gurz vagb qrirybcref, naq gurl frrz gb yvxr vg gung jnl!
#168 lore raw
In reply to Pavel Machek

Hi.

Quoted 3 lines · Pavel Machek

My machine suspends in 7 seconds, and that's swsusp1. According to your numbers, suspend2 should suspend it in 1 second and LZE compressed should be .5 second.

Seven seconds? How much memory is in use when you start, and how much is actually written to disk? If you're starting with 1GB of RAM in use, I'll sit up and listen, but I suspect you're talking about something closer to 20MB and init S :>

These discussions are getting really unreasonable. "I don't want that feature, therefore it shouldn't be merged" isn't a valid argument. Neither is "Well, I can suspend in seven seconds with hardly any memory in use." If you just don't want suspend2 in the kernel, come out and say it. But please, stop giving me lame arguments (more below deleted rather than replied to).

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
#169 lore raw

Hi!

Quoted 8 lines
Quoted 3 lines

My machine suspends in 7 seconds, and that's swsusp1. According to your numbers, suspend2 should suspend it in 1 second and LZE compressed should be .5 second.

Seven seconds? How much memory is in use when you start, and how much is actually written to disk? If you're starting with 1GB of RAM in use, I'll sit up and listen, but I suspect you're talking about something closer to 20MB and init S :>

It was on .5GB machine, with X running, IIRC. Specify how should I load the system and I'll try it here. swsusp1 got some speedups with O(n^2) killing (not yet merged).

Quoted 5 lines

These discussions are getting really unreasonable. "I don't want that feature, therefore it shouldn't be merged" isn't a valid argument. Neither is "Well, I can suspend in seven seconds with hardly any memory in use." If you just don't want suspend2 in the kernel, come out and say it.

Ok, "I do not want suspend2 in kernel". Not what you'd call suspend2, anyway. I thought that stripping down suspend2 then merging it is reasonable way to go, but now it seems to me that enhancing swsusp1 is easier way to go. At least I'll be able to do it incrementally.

I'm sorry about all the confusion, and you can still get that jpeg for "put pavel into doom3".
Pavel

Signature · 2 lines
People were complaining that M$ turns users into beta-testers...
...jr ghea gurz vagb qrirybcref, naq gurl frrz gb yvxr vg gung jnl!
#170 lore raw

Hi.

Quoted 6 lines · Pavel Machek

Hi!

Quoted 4 lines
Quoted 3 lines

My machine suspends in 7 seconds, and that's swsusp1. According to your numbers, suspend2 should suspend it in 1 second and LZE compressed should be .5 second.

Quoted 8 lines
Quoted 4 lines

Seven seconds? How much memory is in use when you start, and how much is actually written to disk? If you're starting with 1GB of RAM in use, I'll sit up and listen, but I suspect you're talking about something closer to 20MB and init S :>

It was on .5GB machine, with X running, IIRC. Specify how should I load the system and I'll try it here. swsusp1 got some speedups with O(n^2) killing (not yet merged).

So it wrote .5GB of memory in seven seconds, or started with .5GB of RAM in use?

If we want to compare apples with apples, we're going to have to make the only difference which code is run. A normal load on my computer is evolution, cyrus imapd, opera, win4lin running Libronix and a kernel tree in the cache (last image sizes were 1000, 1002, 995, 949 and 910MB). I'm happy to run your sped-up code for some tests, if you'd like. You know where to find mine if you want to make sure I'm not cheating :>

Quoted 10 lines
Quoted 5 lines

These discussions are getting really unreasonable. "I don't want that feature, therefore it shouldn't be merged" isn't a valid argument. Neither is "Well, I can suspend in seven seconds with hardly any memory in use." If you just don't want suspend2 in the kernel, come out and say it.

Ok, "I do not want suspend2 in kernel". Not what you'd call suspend2, anyway. I thought that stripping down suspend2 then merging it is reasonable way to go, but now it seems to me that enhancing swsusp1 is easier way to go. At least I'll be able to do it incrementally.

You'll be able to do that within limits, but once you do seriously given up on the max-half-of-memory limit, you'll need some major redesigning. If that's the way you want to go, okay. Assuming nothing else changes, I'll just keep suspend2 alive outside of the kernel tree until you get sick of users asking, and continue to enhance it.

Quoted 2 lines

I'm sorry about all the confusion, and you can still get that jpeg for "put pavel into doom3".

I'm not taking it personally at all. I did find some of the objections pretty petty and some of the comparisons grossly unfair, but I'm not taking it personally.

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
#171 lore raw

Hi!

Quoted 9 lines
Quoted 9 lines
Quoted 8 lines
Quoted 3 lines

My machine suspends in 7 seconds, and that's swsusp1. According to your numbers, suspend2 should suspend it in 1 second and LZE compressed should be .5 second.

Seven seconds? How much memory is in use when you start, and how much is actually written to disk? If you're starting with 1GB of RAM in use, I'll sit up and listen, but I suspect you're talking about something closer to 20MB and init S :>

Quoted 6 lines
Quoted 3 lines

It was on .5GB machine, with X running, IIRC. Specify how should I load the system and I'll try it here. swsusp1 got some speedups with O(n^2) killing (not yet merged).

So it wrote .5GB of memory in seven seconds, or started with .5GB of RAM in use?

Machine had .5GB total, not surehow much was really used.

Quoted 7 lines

If we want to compare apples with apples, we're going to have to make the only difference which code is run. A normal load on my computer is evolution, cyrus imapd, opera, win4lin running Libronix and a kernel tree in the cache (last image sizes were 1000, 1002, 995, 949 and 910MB). I'm happy to run your sped-up code for some tests, if you'd like. You know where to find mine if you want to make sure I'm not cheating :>

Okay, I started galeon (no opera here :-(), evolution, xpdf, oowriter. Well, it is not going to be too much "apples-to-apples" since swsusp1 cheats and discards caches (etc). Machine has 1GB memory total, before suspend attempt 800MB were in use. Suspend took 20 seconds, after resume (and some swap-in) 250MB was in use.

Quoted 6 lines
Quoted 6 lines
Quoted 5 lines

These discussions are getting really unreasonable. "I don't want that feature, therefore it shouldn't be merged" isn't a valid argument. Neither is "Well, I can suspend in seven seconds with hardly any memory in use." If you just don't want suspend2 in the kernel, come out and say it.

Quoted 8 lines
Quoted 4 lines

Ok, "I do not want suspend2 in kernel". Not what you'd call suspend2, anyway. I thought that stripping down suspend2 then merging it is reasonable way to go, but now it seems to me that enhancing swsusp1 is easier way to go. At least I'll be able to do it incrementally.

You'll be able to do that within limits, but once you do seriously given up on the max-half-of-memory limit, you'll need some major redesigning. If that's the way you want to go, okay. Assuming nothing else changes,

I'm not sure if I want to do full page-cache saving (and without that, half-of-memory limit does not bite too badly). "Everything is swapped out" problem is actually not limited to swsusp, updatedb overnight tends to have the same effect. Perhaps more generic solution is needed...

cat cat /proc/[0-9]*/maps | grep / | sed 's:.* /:/:' | sort -u > /dev/null

does solve part of the problem. (Another problem is how to actually measure improvements in this area).
Pavel

Signature · 2 lines
People were complaining that M$ turns users into beta-testers...
...jr ghea gurz vagb qrirybcref, naq gurl frrz gb yvxr vg gung jnl!
#172 lore raw

Hi.

Quoted 8 lines · Pavel Machek
Quoted 7 lines

If we want to compare apples with apples, we're going to have to make the only difference which code is run. A normal load on my computer is evolution, cyrus imapd, opera, win4lin running Libronix and a kernel tree in the cache (last image sizes were 1000, 1002, 995, 949 and 910MB). I'm happy to run your sped-up code for some tests, if you'd like. You know where to find mine if you want to make sure I'm not cheating :>

Quoted 5 lines

Okay, I started galeon (no opera here :-(), evolution, xpdf, oowriter. Well, it is not going to be too much "apples-to-apples" since swsusp1 cheats and discards caches (etc). Machine has 1GB memory total, before suspend attempt 800MB were in use. Suspend took 20 seconds, after resume (and some swap-in) 250MB was in use.

Are you able to time up to when the swap in is finished? Without that, we're not really comparing apples with apples, it seems.

Quoted 15 lines
Quoted 6 lines
Quoted 6 lines
Quoted 5 lines

These discussions are getting really unreasonable. "I don't want that feature, therefore it shouldn't be merged" isn't a valid argument. Neither is "Well, I can suspend in seven seconds with hardly any memory in use." If you just don't want suspend2 in the kernel, come out and say it.

Quoted 8 lines
Quoted 4 lines

Ok, "I do not want suspend2 in kernel". Not what you'd call suspend2, anyway. I thought that stripping down suspend2 then merging it is reasonable way to go, but now it seems to me that enhancing swsusp1 is easier way to go. At least I'll be able to do it incrementally.

You'll be able to do that within limits, but once you do seriously given up on the max-half-of-memory limit, you'll need some major redesigning. If that's the way you want to go, okay. Assuming nothing else changes,

Quoted 5 lines

I'm not sure if I want to do full page-cache saving (and without that, half-of-memory limit does not bite too badly). "Everything is swapped out" problem is actually not limited to swsusp, updatedb overnight tends to have the same effect. Perhaps more generic solution is needed...

Would increases in the amount of memory machines have make this bite more and more over time?

I guess the more generic solution would be to abandon using bio calls and have your own device driver that could write the whole image to disk without having to do the atomic copy. You'd have to write a lot of support for drivers, though. I'd find it hard to imagine it being worth the effort.

Quoted 1 line

cat cat /proc/[0-9]*/maps | grep / | sed 's:.* /:/:' | sort -u > /dev/null

What does this do?

Quoted 2 lines

does solve part of the problem. (Another problem is how to actually measure improvements in this area).

Yes; that's always an 'interesting' issue :>

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
#173 lore raw

Hi!

Quoted 8 lines
Quoted 5 lines

I'm not sure if I want to do full page-cache saving (and without that, half-of-memory limit does not bite too badly). "Everything is swapped out" problem is actually not limited to swsusp, updatedb overnight tends to have the same effect. Perhaps more generic solution is needed...

Would increases in the amount of memory machines have make this bite more and more over time?

Actually, it should bite less and less, because ammount of memory actually used does not seem to grow as fast as ammount of memory available. On 4MB machine, I could imagine kernel using >2MB memory and "half-memory-free" trick not working at all. On 1GB machine... well kernel will never use >512MB of memory, so we are safe.

Quoted 5 lines

I guess the more generic solution would be to abandon using bio calls and have your own device driver that could write the whole image to disk without having to do the atomic copy. You'd have to write a lot of support for drivers, though. I'd find it hard to imagine it being worth the effort.

That would mean rewriting half of kernel.

Quoted 3 lines
Quoted 1 line

cat cat /proc/[0-9]*/maps | grep / | sed 's:.* /:/:' | sort -u > /dev/null

What does this do?

Attempts to load all the binaries into memory. Poor man's "make machine responsive after swsusp".
Pavel

Signature · 2 lines
People were complaining that M$ turns users into beta-testers...
...jr ghea gurz vagb qrirybcref, naq gurl frrz gb yvxr vg gung jnl!

A message that is not in the archive (sent off-list or not yet received): [email protected]

#175 lore raw

Hi!

Quoted 11 lines
Quoted 8 lines

For swsusp2, you need drivers to stop the DMA, NMI not interfering, sync may not happen after you have saved LRU, memory may not be alocated from slab after you have saved LRU. (something else? This needs to be written down somewhere, and all kernel hackers will need to be carefull not to break these rules. Do you see why it wories me?)

swsusp1 is more self-contained. As long as drivers stop the DMA and NMI does nothing wrong, atomic snapshot will indeed be atomic.

Here is a grabed memory allocate patch from suspend2, useful for shrink memory in high memory using system.

Sorry, I do not understand. What problem is this solving?
Pavel

Signature · 2 lines
People were complaining that M$ turns users into beta-testers...
...jr ghea gurz vagb qrirybcref, naq gurl frrz gb yvxr vg gung jnl!
#176 lore raw
In reply to Pavel Machek

Hi.

Quoted 2 lines · Pavel Machek

I'm not *that* concerned about speed. Getting rid of order-8 is for preventing "sorry, not enough RAM to suspend to disk".

That's fine, but you're only expressing your preference. I'm going to ignore the other postings from the weekend that essentially say the same thing; there's no point.

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
#177 lore raw
In reply to Nigel Cunningham
Quoted 3 lines · Nigel Cunningham

The cryptoapi provides support for both compression and encryption. I'd happily make use of that, but we still need a way for the user to choose what compression/encryption they want and configure it. I'm not at all

And encryption is in fact much more needed than compression. Remember, you are writing everything in memory (including maybe ssh passphrases or gpg keys) to swap in clear text. Not nice. And i agree that compression is nice to have, too.

Quoted 1 line
Quoted 1 line
Quoted 1 line

:> But not everyone who uses 2.6.9 uses swsusp. :>

and not everyone who downloads suspend2 uses it ;-)

Quoted 3 lines

change a parameter or forcing them to do an ls in /dev with obscure parameters (to get the major and minor numbers) when they already know they want /dev/sda1 isn't user friendly. Obviously user friendliness is

This can easily be done by a userspace helper. You do use the (userspace) X server to display your GUI, don't you?
Putting only the absolutely necessary things into the kernel (the same is true for the interactive resume thing - if someone wants interactive startup at a failing resume, he has to use an initrd, i don't see a problem with that) will probably increase the acceptance a bit :-)

Best regards,

Stefan

#178 lore raw

Hi.

Quoted 6 lines · Stefan Seyfried
Quoted 3 lines · Nigel Cunningham

The cryptoapi provides support for both compression and encryption. I'd happily make use of that, but we still need a way for the user to choose what compression/encryption they want and configure it. I'm not at all

Quoted 8 lines

And encryption is in fact much more needed than compression. Remember, you are writing everything in memory (including maybe ssh passphrases or gpg keys) to swap in clear text. Not nice. And i agree that compression is nice to have, too.

Quoted 1 line
Quoted 1 line
Quoted 1 line

:> But not everyone who uses 2.6.9 uses swsusp. :>

and not everyone who downloads suspend2 uses it ;-)

Yes... I'd say the relative percentage would be much higher, though.

Quoted 6 lines
Quoted 3 lines

change a parameter or forcing them to do an ls in /dev with obscure parameters (to get the major and minor numbers) when they already know they want /dev/sda1 isn't user friendly. Obviously user friendliness is

This can easily be done by a userspace helper. You do use the (userspace) X server to display your GUI, don't you?

No. Not at all. All of userspace is well and truly wedged in a block of ice by then.

Quoted 4 lines

Putting only the absolutely necessary things into the kernel (the same is true for the interactive resume thing - if someone wants interactive startup at a failing resume, he has to use an initrd, i don't see a problem with that) will probably increase the acceptance a bit :-)

That's fine if your initrd is properly configured and you're willing to add extra cruft to the kernel so userspace can get the info it needs, and report what the user wants to do. If, however, you don't use an initrd, you're sunk.

Regarding acceptance, there's no point in getting it accepted into the kernel if we end up with something that's user-unfriendly. I think it will help a lot if we agree that suspend does need to blur the lines between kernel and userspace a little, in the interests of providing software that is superior.

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
#179 lore raw

Hi!

Quoted 5 lines
Quoted 3 lines
Quoted 1 line
Quoted 1 line
Quoted 1 line

:> But not everyone who uses 2.6.9 uses swsusp. :>

and not everyone who downloads suspend2 uses it ;-)

Yes... I'd say the relative percentage would be much higher, though.

Agreed.

Quoted 9 lines
Quoted 6 lines
Quoted 3 lines

change a parameter or forcing them to do an ls in /dev with obscure parameters (to get the major and minor numbers) when they already know they want /dev/sda1 isn't user friendly. Obviously user friendliness is

This can easily be done by a userspace helper. You do use the (userspace) X server to display your GUI, don't you?

No. Not at all. All of userspace is well and truly wedged in a block of ice by then.

I think that was not what Stefan wanted to say.

Quoted 5 lines

Regarding acceptance, there's no point in getting it accepted into the kernel if we end up with something that's user-unfriendly. I think it will help a lot if we agree that suspend does need to blur the lines between kernel and userspace a little, in the interests of providing software that is superior.

I guess we'll have to agree to disagree here. I do not think suspend is special enough to blur the lines...
Pavel

Signature · 2 lines
People were complaining that M$ turns users into beta-testers...
...jr ghea gurz vagb qrirybcref, naq gurl frrz gb yvxr vg gung jnl!
#180 lore raw
In reply to Nigel Cunningham

Hi,

Quoted 5 lines · Nigel Cunningham
Quoted 1 line · Stefan Seyfried

and not everyone who downloads suspend2 uses it ;-)

Yes... I'd say the relative percentage would be much higher, though.

you are probably right here :-)

Quoted 9 lines
Quoted 6 lines
Quoted 3 lines

change a parameter or forcing them to do an ls in /dev with obscure parameters (to get the major and minor numbers) when they already know they want /dev/sda1 isn't user friendly. Obviously user friendliness is

This can easily be done by a userspace helper. You do use the (userspace) X server to display your GUI, don't you?

No. Not at all. All of userspace is well and truly wedged in a block of ice by then.

you are not changing the suspend device after freezing userspace, or i am getting something horribly wrong here.

so if you have 2 choices of an interface:
1) more complex kernel code, but you can do "echo /dev/name > /proc/foo"
2) less complex kernel code, now you have a userspace helper e.g. "suspend_ctl foodev /dev/name" which then does the magic number calculations in userspace and puts the magic number into the kernel.

I think that interface 2) would be preferred by most kernel developers. Especially since this is code only needed on a relatively small subset of all linux installations.

There is a "top" userspace program to parse kernel numbers, we don't have "/proc/top".

Quoted 6 lines
Quoted 4 lines

Putting only the absolutely necessary things into the kernel (the same is true for the interactive resume thing - if someone wants interactive startup at a failing resume, he has to use an initrd, i don't see a problem with that) will probably increase the acceptance a bit :-)

That's fine if your initrd is properly configured and you're willing to

This is something distributions have to take care of.

Quoted 1 line

add extra cruft to the kernel so userspace can get the info it needs,

not much extra cruft is needed. The "echo resume > /sys/power/state" just returns (which it wouldn't if the resume was successful), then you can decide what to do next.

Quoted 2 lines

and report what the user wants to do. If, however, you don't use an initrd, you're sunk.

yes. There are other prerequisites for suspend than using an initrd though (you need a computer :-). If you don't use an initrd, you cannot use the interactive features but have to decide at compile time which way to go if the resume fails. That's life.

Quoted 5 lines

Regarding acceptance, there's no point in getting it accepted into the kernel if we end up with something that's user-unfriendly. I think it will help a lot if we agree that suspend does need to blur the lines between kernel and userspace a little, in the interests of providing software that is superior.

User-friendlyness is an joint effort of kernel and userspace. The user does not care who does the work when he clicks on his "hibernation" Icon in the taskbar. (The same is true for users of an hibernation script). Actually, the thing that makes suspend2 more reliable than swsusp is probably the very good hibernation script (userspace) that saves users the reading of documentation since it automatically unloads all critical modules etc. For me, pavel's later versions as in SUSE 9.2 have worked out of the box on every non-SMP i386 notebook i have laid my hands on in the last 6 months (thanks to userspace taking care of bad modules etc).

Regards,

Stefan

#181 lore raw

Hi.

Quoted 4 lines · Stefan Seyfried
Quoted 4 lines
Quoted 4 lines
Quoted 3 lines

change a parameter or forcing them to do an ls in /dev with obscure parameters (to get the major and minor numbers) when they already know they want /dev/sda1 isn't user friendly. Obviously user friendliness is

Quoted 8 lines
Quoted 5 lines
Quoted 2 lines

This can easily be done by a userspace helper. You do use the (userspace) X server to display your GUI, don't you?

No. Not at all. All of userspace is well and truly wedged in a block of ice by then.

you are not changing the suspend device after freezing userspace, or i am getting something horribly wrong here.

No, it doesn't change once userspace is frozen; you're correct.

Quoted 6 lines

so if you have 2 choices of an interface:
1) more complex kernel code, but you can do "echo /dev/name > /proc/foo"
2) less complex kernel code, now you have a userspace helper e.g. "suspend_ctl foodev /dev/name" which then does the magic number calculations in userspace and puts the magic number into the kernel.

Quoted 6 lines

I think that interface 2) would be preferred by most kernel developers. Especially since this is code only needed on a relatively small subset of all linux installations.

There is a "top" userspace program to parse kernel numbers, we don't have "/proc/top".

Forgive me for asking a stupid question, but why all this fuss when the code is already in the kernel? And isn't really that complex anyway. Instead of whatever for parsing a major and minor, we have

        resume_device = name_to_dev_t(commandline);

Is it really worth all this heat for that call and making two routines (name_to_dev_t and try_name IIRC) not be __init. It seems to me that it's far more complex to create some userspace program to do this stuff.

Quoted 8 lines
Quoted 6 lines
Quoted 4 lines

Putting only the absolutely necessary things into the kernel (the same is true for the interactive resume thing - if someone wants interactive startup at a failing resume, he has to use an initrd, i don't see a problem with that) will probably increase the acceptance a bit :-)

That's fine if your initrd is properly configured and you're willing to

This is something distributions have to take care of.

No; it's something the users will have to take care of. Distro makers might make the process more automated, but in the end it's the user's problem if it doesn't work.

Quoted 6 lines
Quoted 1 line

add extra cruft to the kernel so userspace can get the info it needs,

not much extra cruft is needed. The "echo resume > /sys/power/state" just returns (which it wouldn't if the resume was successful), then you can decide what to do next.

Quoted 7 lines
Quoted 2 lines

and report what the user wants to do. If, however, you don't use an initrd, you're sunk.

yes. There are other prerequisites for suspend than using an initrd though (you need a computer :-). If you don't use an initrd, you cannot use the interactive features but have to decide at compile time which way to go if the resume fails. That's life.

Have you looked at the code for handling this? It's really very simple.

Quoted 6 lines
Quoted 5 lines

Regarding acceptance, there's no point in getting it accepted into the kernel if we end up with something that's user-unfriendly. I think it will help a lot if we agree that suspend does need to blur the lines between kernel and userspace a little, in the interests of providing software that is superior.

Quoted 9 lines

User-friendlyness is an joint effort of kernel and userspace. The user does not care who does the work when he clicks on his "hibernation" Icon in the taskbar. (The same is true for users of an hibernation script). Actually, the thing that makes suspend2 more reliable than swsusp is probably the very good hibernation script (userspace) that saves users the reading of documentation since it automatically unloads all critical modules etc. For me, pavel's later versions as in SUSE 9.2 have worked out of the box on every non-SMP i386 notebook i have laid my hands on in the last 6 months (thanks to userspace taking care of bad modules etc).

Have those boxes had DRI enabled or serious USB usage? I'd be surprised if you haven't run into the same problems we have.

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
#182 lore raw

Hi!

Quoted 5 lines
Quoted 5 lines
Quoted 5 lines
Quoted 4 lines

Putting only the absolutely necessary things into the kernel (the same is true for the interactive resume thing - if someone wants interactive startup at a failing resume, he has to use an initrd, i don't see a problem with that) will probably increase the acceptance a bit :-)

Quoted 7 lines
Quoted 3 lines
Quoted 1 line

That's fine if your initrd is properly configured and you're willing to

This is something distributions have to take care of.

No; it's something the users will have to take care of. Distro makers might make the process more automated, but in the end it's the user's problem if it doesn't work.

Actually, no, its not like that.

User will click icon in KDE, and if it does not suspend & resume properly, distribution has problem to fix. And yes, it works well in SUSE9.2.
Pavel

Signature · 2 lines
People were complaining that M$ turns users into beta-testers...
...jr ghea gurz vagb qrirybcref, naq gurl frrz gb yvxr vg gung jnl!
#183 lore raw

Hi.

Quoted 15 lines · Pavel Machek

Hi!

Quoted 5 lines
Quoted 5 lines
Quoted 5 lines
Quoted 4 lines

Putting only the absolutely necessary things into the kernel (the same is true for the interactive resume thing - if someone wants interactive startup at a failing resume, he has to use an initrd, i don't see a problem with that) will probably increase the acceptance a bit :-)

Quoted 7 lines
Quoted 3 lines
Quoted 1 line

That's fine if your initrd is properly configured and you're willing to

This is something distributions have to take care of.

No; it's something the users will have to take care of. Distro makers might make the process more automated, but in the end it's the user's problem if it doesn't work.

Quoted 5 lines

Actually, no, its not like that.

User will click icon in KDE, and if it does not suspend & resume properly, distribution has problem to fix. And yes, it works well in SUSE9.2.

I didn't know you had support for initramfs and initrd configurations already. You are making progress.

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
#184 lore raw

Hi!

Quoted 13 lines
Quoted 13 lines
Quoted 12 lines
Quoted 8 lines
Quoted 6 lines
Quoted 4 lines

Putting only the absolutely necessary things into the kernel (the same is true for the interactive resume thing - if someone wants interactive startup at a failing resume, he has to use an initrd, i don't see a problem with that) will probably increase the acceptance a bit :-)

That's fine if your initrd is properly configured and you're willing to

This is something distributions have to take care of.

No; it's something the users will have to take care of. Distro makers might make the process more automated, but in the end it's the user's problem if it doesn't work.

Quoted 8 lines
Quoted 5 lines

Actually, no, its not like that.

User will click icon in KDE, and if it does not suspend & resume properly, distribution has problem to fix. And yes, it works well in SUSE9.2.

I didn't know you had support for initramfs and initrd configurations already. You are making progress.

Well, no, not that one.

OTOH for SUSE9.2 these things basically can not happen. (There's no wrong kernel you can click on ;-) -- either you boot normally, then there's just one kernel to boot, or you boot failsafe, and then you want to kill signatures etc.)
Pavel

Signature · 2 lines
People were complaining that M$ turns users into beta-testers...
...jr ghea gurz vagb qrirybcref, naq gurl frrz gb yvxr vg gung jnl!
#185 lore raw

Hi.

Quoted 24 lines · Pavel Machek

Hi!

Quoted 13 lines
Quoted 13 lines
Quoted 12 lines
Quoted 8 lines
Quoted 6 lines
Quoted 4 lines

Putting only the absolutely necessary things into the kernel (the same is true for the interactive resume thing - if someone wants interactive startup at a failing resume, he has to use an initrd, i don't see a problem with that) will probably increase the acceptance a bit :-)

That's fine if your initrd is properly configured and you're willing to

This is something distributions have to take care of.

No; it's something the users will have to take care of. Distro makers might make the process more automated, but in the end it's the user's problem if it doesn't work.

Quoted 8 lines
Quoted 5 lines

Actually, no, its not like that.

User will click icon in KDE, and if it does not suspend & resume properly, distribution has problem to fix. And yes, it works well in SUSE9.2.

I didn't know you had support for initramfs and initrd configurations already. You are making progress.

Quoted 6 lines

Well, no, not that one.

OTOH for SUSE9.2 these things basically can not happen. (There's no wrong kernel you can click on ;-) -- either you boot normally, then there's just one kernel to boot, or you boot failsafe, and then you want to kill signatures etc.)

And it's impossible for you to accidentally select the failsafe?

Anyway, even if it is impossible, you're still only talking about one particular set of circumstances; that's not necessarily the case for everyone else, not should it necessarily be.

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
#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;
+}
#187 lore raw

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

Hi!

Quoted 1 line

+extern volatile int suspend_io_time[2][2];

Why volatile?

Quoted 31 lines
kernel/power/io.c +31 -0
+
+	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);

kernel/power/io.c line 174

Quoted 10 lines
kernel/power/io.c +10 -0
+		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;
+		}

Half of this code seems to be pretty-prints, and performance metering. That should be gone before mainline merge.

Pavel

Signature · 2 lines
People were complaining that M$ turns users into beta-testers...
...jr ghea gurz vagb qrirybcref, naq gurl frrz gb yvxr vg gung jnl!
#188 lore raw

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

Quoted 7 lines · Pavel Machek

Hi!

Quoted 1 line

+extern volatile int suspend_io_time[2][2];

Why volatile?

I think Linus doesn't like this keyword very much. And I also think he said it should not be used.

tom

#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

#190 lore raw

Re: Suspend 2 merge: 49/51: Checksumming

Hi!

Quoted 4 lines

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.

Debugging code, can live as external patch pretty well.
Pavel

Signature · 2 lines
People were complaining that M$ turns users into beta-testers...
...jr ghea gurz vagb qrirybcref, naq gurl frrz gb yvxr vg gung jnl!
#191 lore raw

Re: Suspend 2 merge: 49/51: Checksumming

Hi.

Quoted 8 lines · Pavel Machek

Hi!

Quoted 4 lines

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.

Debugging code, can live as external patch pretty well.

Doesn't most of the kernel have debugging code in it? Maybe not as much, but most of the kernel isn't doing the same thing. Remember we have the option of compiling it out. If it lives as a separate patch, we're just making more work for me (I have to maintain the debug version and then make some transformation on it to get the mainline version).

By the way, I'm really appreciating your interaction over all these points. I was getting worried that I wasn't getting enough. I should say now, too, that I'm away all weekend, so you won't get replies tomorrow and the day after.

Thanks and 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
#192 lore raw

Re: Suspend 2 merge: 49/51: Checksumming

Hi!

Quoted 5 lines
Quoted 5 lines
Quoted 4 lines

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.

Quoted 7 lines
Quoted 1 line

Debugging code, can live as external patch pretty well.

Doesn't most of the kernel have debugging code in it? Maybe not as much, but most of the kernel isn't doing the same thing. Remember we have the option of compiling it out. If it lives as a separate patch, we're just making more work for me (I have to maintain the debug version and then make some transformation on it to get the mainline version).

There's so much of debuging code that it is unreadable. When it is separate file it is not so bad, but you'll have 1000 people going over it "What is this", trying to keep it up-to-date with sparse annotations etc...

Is not it possible to just debug suspend2 and then drop the debugging code, not maintaining it any longer?

Quoted 4 lines

By the way, I'm really appreciating your interaction over all these points. I was getting worried that I wasn't getting enough. I should say now, too, that I'm away all weekend, so you won't get replies tomorrow and the day after.

Well, I worry that now you'll be getting way too much interaction... Anyway have a nice weekend,
Pavel

Signature · 2 lines
People were complaining that M$ turns users into beta-testers...
...jr ghea gurz vagb qrirybcref, naq gurl frrz gb yvxr vg gung jnl!
#193 lore raw

Re: Suspend 2 merge: 49/51: Checksumming

In reply to Nigel Cunningham
Quoted 4 lines · 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.

A while back I suggested checking the last mount time of the mounted local filesystems as a quick and dirty sanity check between loading the image and unfreezing all the processes. (Since a read-only mount shouldn't touch this, triggering swsusp resume from userspace after prodding various hardware shouldn't cause a major problem either...) Does that sound like a good idea?

Haven't had time to look into it myself, though. (Just recently got time enough to bang on busybox again. Somewhere around 2.6.7, software suspend stopped working for me and I haven't even had a chance to track _that_ down yet. Hopefully fixed in 2.6.9 or 2.6.10, I haven't played with it recently...)

Rob

#194 lore raw

Re: Suspend 2 merge: 49/51: Checksumming

Hi.

Quoted 11 lines · Rob Landley
Quoted 4 lines · 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.

A while back I suggested checking the last mount time of the mounted local filesystems as a quick and dirty sanity check between loading the image and unfreezing all the processes. (Since a read-only mount shouldn't touch this, triggering swsusp resume from userspace after prodding various hardware shouldn't cause a major problem either...) Does that sound like a good idea?

If I recall correctly, someone replied that even a read only mount under one filesystem (XFS? Not sure), would replay the journal, so it wasn't a goer.

Quoted 5 lines

Haven't had time to look into it myself, though. (Just recently got time enough to bang on busybox again. Somewhere around 2.6.7, software suspend stopped working for me and I haven't even had a chance to track _that_ down yet. Hopefully fixed in 2.6.9 or 2.6.10, I haven't played with it recently...)

If you mean suspend2, I might be able to help if given more info.

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
#195 lore raw

Re: Suspend 2 merge: 49/51: Checksumming

Quoted 16 lines · Nigel Cunningham

Hi.

Quoted 6 lines · Rob Landley
Quoted 4 lines · 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.

Quoted 6 lines

A while back I suggested checking the last mount time of the mounted local filesystems as a quick and dirty sanity check between loading the image and unfreezing all the processes. (Since a read-only mount shouldn't touch this, triggering swsusp resume from userspace after prodding various hardware shouldn't cause a major problem either...) Does that sound like a good idea?

Quoted 3 lines

If I recall correctly, someone replied that even a read only mount under one filesystem (XFS? Not sure), would replay the journal, so it wasn't a goer.

You could always special case the broken one until they fix it... :)

Quoted 7 lines
Quoted 5 lines

Haven't had time to look into it myself, though. (Just recently got time enough to bang on busybox again. Somewhere around 2.6.7, software suspend stopped working for me and I haven't even had a chance to track _that_ down yet. Hopefully fixed in 2.6.9 or 2.6.10, I haven't played with it recently...)

If you mean suspend2, I might be able to help if given more info.

Nah, the one that's built in. I'll try it again when I upgrade to 2.6.10 in a few days.

Quoted 3 lines

Regards,

Nigel

Rob

#196 lore raw

Re: Suspend 2 merge: 49/51: Checksumming

Hi.

Quoted 17 lines · Rob Landley
Quoted 16 lines · Nigel Cunningham

Hi.

Quoted 12 lines · Rob Landley
Quoted 4 lines · 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.

A while back I suggested checking the last mount time of the mounted local filesystems as a quick and dirty sanity check between loading the image and unfreezing all the processes. (Since a read-only mount shouldn't touch this, triggering swsusp resume from userspace after prodding various hardware shouldn't cause a major problem either...) Does that sound like a good idea?

Quoted 5 lines
Quoted 3 lines

If I recall correctly, someone replied that even a read only mount under one filesystem (XFS? Not sure), would replay the journal, so it wasn't a goer.

You could always special case the broken one until they fix it... :)

Mmm. I wonder how much code that would require us to add. I do like the idea of not interacting where the answer is obvious :>. I still think, however, that interacting when the answer isn't obvious is the right thing to do. Take for example the case where we find an image, but the device numbers look like they belong to 2.4 and we're a 2.6 kernel. We can't read the header (we can't be sure that this is the cause). The user - or their cat - might have selected the wrong boot image unintentionally. Why shouldn't we give them the opportunity to reboot and get the right one?

Quoted 10 lines
Quoted 7 lines
Quoted 5 lines

Haven't had time to look into it myself, though. (Just recently got time enough to bang on busybox again. Somewhere around 2.6.7, software suspend stopped working for me and I haven't even had a chance to track _that_ down yet. Hopefully fixed in 2.6.9 or 2.6.10, I haven't played with it recently...)

If you mean suspend2, I might be able to help if given more info.

Nah, the one that's built in. I'll try it again when I upgrade to 2.6.10 in a few days.

Okay.

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
#197 lore raw

Re: Suspend 2 merge: 49/51: Checksumming

Hi!

Quoted 6 lines
Quoted 5 lines
Quoted 3 lines

If I recall correctly, someone replied that even a read only mount under one filesystem (XFS? Not sure), would replay the journal, so it wasn't a goer.

You could always special case the broken one until they fix it... :)

Quoted 9 lines

Mmm. I wonder how much code that would require us to add. I do like the idea of not interacting where the answer is obvious :>. I still think, however, that interacting when the answer isn't obvious is the right thing to do. Take for example the case where we find an image, but the device numbers look like they belong to 2.4 and we're a 2.6 kernel. We can't read the header (we can't be sure that this is the cause). The user - or their cat - might have selected the wrong boot image unintentionally. Why shouldn't we give them the opportunity to reboot and get the right one?

Well, kernel depending on user feedback has some interesting issues... ...like user not speaking english or user using speech output. Thats why pushing "Shall I reboot?" etc prompts into userland is good idea. (Distros probably will not get it right, either, but at least they get a chance.)
Pavel

Signature · 1 line
64 bytes from 195.113.31.123: icmp_seq=28 ttl=51 time=448769.1 ms         
#198 lore raw

Re: Suspend 2 merge: 49/51: Checksumming

Hi.

Quoted 10 lines · Pavel Machek
Quoted 9 lines

Mmm. I wonder how much code that would require us to add. I do like the idea of not interacting where the answer is obvious :>. I still think, however, that interacting when the answer isn't obvious is the right thing to do. Take for example the case where we find an image, but the device numbers look like they belong to 2.4 and we're a 2.6 kernel. We can't read the header (we can't be sure that this is the cause). The user - or their cat - might have selected the wrong boot image unintentionally. Why shouldn't we give them the opportunity to reboot and get the right one?

Quoted 5 lines

Well, kernel depending on user feedback has some interesting issues... ...like user not speaking english or user using speech output. Thats why pushing "Shall I reboot?" etc prompts into userland is good idea. (Distros probably will not get it right, either, but at least they get a chance.)

And if we don't have userspace yet? (No initrd/initramfs).

The language issue is a good point; the whole issue of kernel messages and languages needs a more general solution.

It probably also helps to remember the point to this:
- avoid file system corruption
- give the user a chance to confirm/fix actions that look wrong

Would making interaction a compile time option make you happy? (That said, I'm not looking forward to trying to guess what the system should do in some of these cases if not allowed to ask).

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
#199 lore raw

Re: Suspend 2 merge: 49/51: Checksumming

In reply to Rob Landley

Hi!

Quoted 10 lines
Quoted 4 lines

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.

A while back I suggested checking the last mount time of the mounted local filesystems as a quick and dirty sanity check between loading the image and unfreezing all the processes. (Since a read-only mount shouldn't touch this, triggering swsusp resume from userspace after prodding various hardware shouldn't cause a major problem either...) Does that sound like a good idea?

Yes, it would be good sanity check. ext3 replays journals even on read-only mount so your / will need to be ext2...
Pavel

Signature · 1 line
64 bytes from 195.113.31.123: icmp_seq=28 ttl=51 time=448769.1 ms         
#200 lore raw

Re: Suspend 2 merge: 49/51: Checksumming

Quoted 2 lines · Pavel Machek

Yes, it would be good sanity check. ext3 replays journals even on read-only mount so your / will need to be ext2...

The alternative is to have a userspace application that can check these things without having to replay the log.

Signature · 1 line
Matthew Garrett | [email protected]
#201 lore raw

Re: Suspend 2 merge: 49/51: Checksumming

Hi!

Quoted 5 lines
Quoted 2 lines

Yes, it would be good sanity check. ext3 replays journals even on read-only mount so your / will need to be ext2...

The alternative is to have a userspace application that can check these things without having to replay the log.

Well, that works as long as you do not have your application on ext3 filesystem :-). If your root filesystem is ext2, you have no problem, and whether or not checking is done in kernelspace does not matter.

Well, you could probably mount ext3 as read-only ext2...

Pavel

Signature · 2 lines
People were complaining that M$ turns users into beta-testers...
...jr ghea gurz vagb qrirybcref, naq gurl frrz gb yvxr vg gung jnl!
#202 lore raw

Re: Suspend 2 merge: 49/51: Checksumming

In reply to Pavel Machek
Quoted 9 lines · Pavel Machek
Quoted 6 lines

A while back I suggested checking the last mount time of the mounted local filesystems as a quick and dirty sanity check between loading the image and unfreezing all the processes. (Since a read-only mount shouldn't touch this, triggering swsusp resume from userspace after prodding various hardware shouldn't cause a major problem either...) Does that sound like a good idea?

Yes, it would be good sanity check. ext3 replays journals even on read-only mount so your / will need to be ext2...

Or initramfs.

Quoted 1 line

Pavel

Rob

#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);
 
 	/*
#204 lore raw

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

Hi!

Quoted 7 lines

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.

Now you know why two pagesets scare me...
Pavel

Signature · 2 lines
People were complaining that M$ turns users into beta-testers...
...jr ghea gurz vagb qrirybcref, naq gurl frrz gb yvxr vg gung jnl!
#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);
#206 lore raw

Re: Suspend 2 merge: 43/51: Utility functions.

Hi!

Quoted 10 lines

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!

How many bits do you need? Two? I'd rather use thow two bits than have yet another abstraction. Also note that it is doing big order allocation.

Pavel

Quoted 85 lines
kernel/power/utility.c +78 -1
+#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);
 
 
-

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/

Signature · 2 lines
People were complaining that M$ turns users into beta-testers...
...jr ghea gurz vagb qrirybcref, naq gurl frrz gb yvxr vg gung jnl!
#207 lore raw

Re: Suspend 2 merge: 43/51: Utility functions.

Hi.

Quoted 13 lines · Pavel Machek

Hi!

Quoted 10 lines

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!

Quoted 3 lines

How many bits do you need? Two? I'd rather use thow two bits than have yet another abstraction. Also note that it is doing big order allocation.

Three if checksumming is enabled IIRC. I'll happily use normal page flags, but we only need them when suspending, and I understood they were rarer than hen's teeth :>

MM guys copied so they can tell me I'm wrong :>

Nigel

Signature · 13 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

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to [email protected].  For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>
#208 lore raw

Re: Suspend 2 merge: 43/51: Utility functions.

Quoted 10 lines · Nigel Cunningham
Quoted 3 lines · Pavel Machek

How many bits do you need? Two? I'd rather use thow two bits than have yet another abstraction. Also note that it is doing big order allocation.

Three if checksumming is enabled IIRC. I'll happily use normal page flags, but we only need them when suspending, and I understood they were rarer than hen's teeth :>

MM guys copied so they can tell me I'm wrong :>

Please remember that, in almost all cases, any use of page->flags can be replaced by a simple list. Is a page marked foo? Well, just traverse this data structure and see if the page is in there. It might be a stinking slow check, but it will *work*.

I think we're up to using 1 bit in the memory hotplug code, but we don't even need that if some operations can be implemented more slowly.

An extreme example:

struct list_head foo;

int PageSuspendFoo(page)

{
	ret = 0;
	lock();
	list_for_each(foo, bar) {
		if (page == bar)
			ret = 1;
	}
	unlock();
	return ret;
}

-- Dave

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in the body to [email protected]. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>

#209 lore raw

Re: Suspend 2 merge: 43/51: Utility functions.

Hi.

Quoted 12 lines · Dave Hansen
Quoted 10 lines · Nigel Cunningham
Quoted 3 lines · Pavel Machek

How many bits do you need? Two? I'd rather use thow two bits than have yet another abstraction. Also note that it is doing big order allocation.

Three if checksumming is enabled IIRC. I'll happily use normal page flags, but we only need them when suspending, and I understood they were rarer than hen's teeth :>

MM guys copied so they can tell me I'm wrong :>

Quoted 7 lines

Please remember that, in almost all cases, any use of page->flags can be replaced by a simple list. Is a page marked foo? Well, just traverse this data structure and see if the page is in there. It might be a stinking slow check, but it will *work*.

I think we're up to using 1 bit in the memory hotplug code, but we don't even need that if some operations can be implemented more slowly.

Yes. That's the way suspending did things initially like checking which pages were free. The bitmap was added to turn O(n^2) into O(n). Since the calculations can potentially be done a few times (as memory is freed so we can suspend), it was a big gain to use a bitmap.

Regards,

Nigel

Signature · 13 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

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to [email protected].  For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>
#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;
#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);
#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

#218 lore raw

Re: Suspend 2 merge: 51/51: Notes

Hi!

Quoted 2 lines

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 :>

:-))))

Quoted 6 lines

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.

I still had not fallen asleep at keyboard, and that is pretty amazing...

It is just too big. suspend2 is small operating system on its own, and that is not good thing :-(.

Pavel

Signature · 2 lines
People were complaining that M$ turns users into beta-testers...
...jr ghea gurz vagb qrirybcref, naq gurl frrz gb yvxr vg gung jnl!
#219 lore raw

Re: Suspend 2 merge: 51/51: Notes

Hi.

Quoted 12 lines · Pavel Machek

Hi!

Quoted 2 lines

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 :>

:-))))

Quoted 5 lines

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.

Quoted 4 lines
Quoted 1 line

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

I still had not fallen asleep at keyboard, and that is pretty amazing...

:>

Quoted 2 lines

It is just too big. suspend2 is small operating system on its own, and that is not good thing :-(.

I feel like you overstate your case a lot. I can see what you mean in some ways, though.

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
#220 lore raw

Re: Suspend 2 merge: 51/51: Notes

Hi!

Quoted 5 lines
Quoted 2 lines

It is just too big. suspend2 is small operating system on its own, and that is not good thing :-(.

I feel like you overstate your case a lot. I can see what you mean in some ways, though.

I just wish I could write Al-Viro-style replies ;-). Or even better have Al Viro saying "no" for me.
Pavel

Signature · 2 lines
People were complaining that M$ turns users into beta-testers...
...jr ghea gurz vagb qrirybcref, naq gurl frrz gb yvxr vg gung jnl!
#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

#222 lore raw

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

Hi!

Quoted 3 lines

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.

This needs to go through dm people....

kernel/power/suspend_dm.c line 92

Quoted 12 lines
kernel/power/suspend_dm.c +12 -0
+static struct suspend_proc_data disable_dm_support_proc_data = {
+	.filename			= "disable_device_mapper_support",
+	.permissions			= PROC_RW,
+	.type				= SUSPEND_PROC_DATA_INTEGER,
+	.data = {
+		.integer = {
+			.variable	= &suspend_dm_ops.disabled,
+			.minimum	= 0,
+			.maximum	= 1,
+		}
+	}
+};

What is this good for? Debugging switch?
Pavel

Signature · 2 lines
People were complaining that M$ turns users into beta-testers...
...jr ghea gurz vagb qrirybcref, naq gurl frrz gb yvxr vg gung jnl!
#223 lore raw

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

Hi.

Quoted 7 lines · Pavel Machek

Hi!

Quoted 3 lines

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.

This needs to go through dm people....

Yes. I'll look for contact details.

Quoted 6 lines
Quoted 6 lines
kernel/power/suspend_dm.c +6 -0
+static struct suspend_proc_data disable_dm_support_proc_data = {
+	.filename			= "disable_device_mapper_support",
+	.permissions			= PROC_RW,
+	.type				= SUSPEND_PROC_DATA_INTEGER,
+	.data = {
+		.integer = {
Quoted 8 lines

kernel/power/suspend_dm.c line 92

Quoted 6 lines
kernel/power/suspend_dm.c +6 -0
+			.variable	= &suspend_dm_ops.disabled,
+			.minimum	= 0,
+			.maximum	= 1,
+		}
+	}
+};

What is this good for? Debugging switch?

Nod. If built as modules, you can of course just rmmod.

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
#225 lore raw

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

Hi.

Quoted 10 lines · Alasdair G Kergon
Quoted 3 lines · Nigel Cunningham
Quoted 1 line · Pavel Machek

This needs to go through dm people....

Yes. I'll look for contact details.

[email protected]
https://www.redhat.com/mailman/listinfo/dm-devel

Exposing dm internals like struct io to the rest of the kernel is unlikely to be the right way to do things.

It's not internals that need to be exposed. Rather, it's the amount of memory needed to work during suspending.

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
#226 lore raw

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

Quoted 1 line · Nigel Cunningham

It's not internals that need to be exposed.

Then why move an internal dm-io structure into a header file and
#include "../../drivers/md/dm-io.h"
from another part of the tree?

Alasdair

Signature · 1 line
[email protected]
#227 lore raw

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

You're right.

My mistake. The code has been improved and I haven't reverted some of the changes in drivers/md to match. I'll do that and make the two exports that are needed (dm_io_get and dm_io_put) into an include/linux/dm.h.

Regards,

Nigel

Quoted 8 lines · Alasdair G Kergon
Quoted 1 line · Nigel Cunningham

It's not internals that need to be exposed.

Then why move an internal dm-io structure into a header file and
#include "../../drivers/md/dm-io.h"
from another part of the tree?

Alasdair

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
#228 lore raw

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

Quoted 4 lines · Nigel Cunningham

My mistake. The code has been improved and I haven't reverted some of the changes in drivers/md to match. I'll do that and make the two exports that are needed (dm_io_get and dm_io_put) into an include/linux/dm.h.

It would be device-mapper.h - or the whole of dm-io.h. The vmalloc comment also looks wrong BTW - it's extra kmalloc GFP_KERNEL memory you're asking for here.

I'd like to understand why you need to call those functions and how it integrates with the rest of what you're doing:
do you have calls to other dm functions in other patches?

Or is this particular change optional, but you have test results showing it to be desirable or necessary in certain cases, maybe indicating a shortcoming within the dm-io code which should be addressed instead?

Alasdair

Signature · 1 line
[email protected]
#229 lore raw

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

Hi.

Quoted 14 lines · Alasdair G Kergon
Quoted 4 lines · Nigel Cunningham

My mistake. The code has been improved and I haven't reverted some of the changes in drivers/md to match. I'll do that and make the two exports that are needed (dm_io_get and dm_io_put) into an include/linux/dm.h.

It would be device-mapper.h - or the whole of dm-io.h. The vmalloc comment also looks wrong BTW - it's extra kmalloc GFP_KERNEL memory you're asking for here.

I'd like to understand why you need to call those functions and how it integrates with the rest of what you're doing:
do you have calls to other dm functions in other patches?

Quoted 6 lines

Or is this particular change optional, but you have test results showing it to be desirable or necessary in certain cases, maybe indicating a shortcoming within the dm-io code which should be addressed instead?

Alasdair

Okay.

Pavel's method of storing the image has an inherent limit: you have to get a consistent image, so you have to make an atomic copy of memory. This implies a maximum image size of half of memory. If you want to save all of your memory when suspending to disk, you simply can't. In order to get around this limitation, I'm saving the image in two parts: LRU pages and 'the rest'. The saving is done using highlevel routines (bio calls, rather than our own polling or whatever drivers), but LRU pages are guaranteed not to change while we're writing the image. We can then use the space occupied by our (saved) LRU pages for the atomic copy.

Prior to saving any of the pages, we generate all of the image meta data, including (of course) the list of pages in both parts of the image. But saving the LRU pages may also result in extra slab pages being allocated, which could make our image inconsistent (they wouldn't get saved, since we've already calculated which pages to save). To get around this problem, we use a memory pool, to and from which all page allocs are satisfied/returned while suspending. The pages in this pool are unconditionally saved, thereby removing the potentiality of having an inconsistent image.

Now the question arises, "How big should the memory pool be?". The answer depends on how much I/O we intend to have on the fly at once (among other things). If, therefore, we we're using DM crypt to do our I/O, it will help if we can either get it to allocate the memory it will need prior to us preparing the metadata, or get from it an amount of memory to include in the pool, given the maximum amount of I/O we intend to have on the fly at once.

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
#230 lore raw

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

[Quick commment only - travelling]

Quoted 5 lines · Nigel Cunningham

If, therefore, we we're using DM crypt to do our
I/O, it will help if we can either get it to allocate the memory it will need prior to us preparing the metadata, or get from it an amount of memory to include in the pool, given the maximum amount of I/O we intend to have on the fly at once.

But where does dm-crypt use dm-io?
dm_get_pages is used by snapshots, mirrors etc.

Alasdair

Signature · 1 line
[email protected]
#231 lore raw

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

Hi.

Quoted 11 lines · Alasdair G Kergon

[Quick commment only - travelling]

Quoted 5 lines · Nigel Cunningham

If, therefore, we we're using DM crypt to do our
I/O, it will help if we can either get it to allocate the memory it will need prior to us preparing the metadata, or get from it an amount of memory to include in the pool, given the maximum amount of I/O we intend to have on the fly at once.

But where does dm-crypt use dm-io?
dm_get_pages is used by snapshots, mirrors etc.

Sorry for the slow reply. The module isn't just for dm-crypt support, but for device mapper support in general. I'm seeking to not make assumptions about what the configuration is, but simply make it support LVM/md.

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
#232 lore raw

Suspend 2 merge: 48/51: Swapwriter

In reply to Nigel Cunningham

This is the swapwriter. It is forms the glue between the highlevel I/O routines in io.c and the blockwriter routines in block_io.c. It is responsible for allocating storage, translating the requests for pages within pagesets into devices and blocks and the like. It is abstracted from the block writer because the plan is that we'll eventually have a generic file writer (ie not using swapspace, but a simple file, possibly on NFS). The swapwriter can automatically swapon and swapoff swapspace for you. Handy if you have a swapdevice you only want to be used for suspending. It understands the swsusp signature so we can play nicely with swsusp (note that the Makefile order is important here: swsusp will balk at our signature, so we need to look first).

kernel/power/suspend_swap.c +1967 -0
diff -ruN 854-swapwriter-old/kernel/power/suspend_swap.c 854-swapwriter-new/kernel/power/suspend_swap.c
@@ -0,0 +1,1967 @@
+/*
+ * Swapwriter.c
+ *
+ * Copyright 2004 Nigel Cunningham <[email protected]>
+ *
+ * Distributed under GPLv2.
+ * 
+ * This file encapsulates functions for usage of swap space as a
+ * backing store.
+ */
+
+#include <linux/suspend.h>
+#include <linux/module.h>
+#include <linux/blkdev.h>
+#include <linux/swapops.h>
+
+#include "suspend.h"
+#include "block_io.h"
+#include "proc.h"
+#include "plugins.h"
+
+#define SIGNATURE_VER 6
+
+/* --- Struct of pages stored on disk */
+
+static struct suspend_plugin_ops swapwriterops;
+
+struct swaplink {
+	char dummy[PAGE_SIZE - sizeof(swp_entry_t)];
+	swp_entry_t next;
+};
+
+union diskpage {
+	union swap_header swh;	/* swh.magic is the only member used */
+	struct swaplink link;
+	struct suspend_header sh;
+};
+
+union p_diskpage {
+	union diskpage *pointer;
+	char *ptr;
+        unsigned long address;
+};
+
+#define SIGNATURE_LENGTH 10
+
+// - Manage swap signature.
+static int prepare_signature(struct submit_params * first_header_page,
+		char * current_header);
+static int parse_signature(char * signature, int restore);
+
+// Higher Level
+static int readahead_index = 0, readahead_submit_index = 0;
+static int readahead_allocs = 0, readahead_frees = 0;
+
+static char * swapwriter_buffer = NULL;
+static int swapwriter_buffer_posn = 0;
+static int swapwriter_page_index = 0;
+static unsigned long * header_link = NULL;
+#define BYTES_PER_HEADER_PAGE (PAGE_SIZE - sizeof(swp_entry_t))
+
+/*
+ * ---------------------------------------------------------------
+ *
+ *     Internal Data Structures
+ *
+ * ---------------------------------------------------------------
+ */
+
+/* header_data contains data that is needed to reload pagedir1, and
+ * is therefore saved in the suspend header.
+ *
+ * Pagedir2 swap comes before pagedir1 swap (save order), and the first swap
+ * entry for pagedir1 to use is set when pagedir2 is written (when we know how
+ * much swap it used). Since this first entry is almost certainly not at the
+ * start of a range, the firstoffset variable below tells us where to start in
+ * the range. All of this means we don't have to worry about getting different
+ * compression ratios for the kernel and cache (when compressing the image).
+ * We can simply allocate one pool of swap (size determined using expected
+ * compression ratio) and use it without worrying whether one pageset
+ * compresses better and the other worse (this is what happens). As long as the
+ * user gets the expected compression right, it will work.
+ */
+
+struct {
+	/* Range chains for swap & blocks */
+	struct rangechain swapranges;
+	struct rangechain block_chain[MAX_SWAPFILES];
+	
+	/* Location of start of pagedir 1 */
+	struct range * pd1start_block_range;
+	unsigned long pd1start_block_offset;
+	int pd1start_chain;
+
+	/* Devices used for swap */
+	dev_t swapdevs[MAX_SWAPFILES];
+	char blocksizes[MAX_SWAPFILES];
+
+	/* Asynchronous I/O limit */
+	int max_async_ios;
+} header_data;
+
+
+dev_t header_device = 0;
+struct block_device * header_block_device = NULL;
+struct range * this_range_page = NULL, * next_range_page = NULL;
+int headerblocksize = PAGE_SIZE;
+int headerblock;
+
+/* For swapfile automatically swapon/off'd. */
+static char swapfilename[256] = "";
+extern asmlinkage long sys_swapon(const char * specialfile, int swap_flags);
+
+int suspend_swapon_status = 0;
+
+/* Must be silent - might be called from cat /proc/suspend/debug_info
+ * Returns 0 if was off, -EBUSY if was on, error value otherwise.
+ */
+static int enable_swapfile(void)
+{
+	int activateswapresult = -EINVAL;
+
+	if (suspend_swapon_status)
+		return 0;
+
+	if (swapfilename[0]) {
+		/* Attempt to swap on with maximum priority */
+		activateswapresult = sys_swapon(swapfilename, 0xFFFF);
+		if ((activateswapresult) && (activateswapresult != -EBUSY))
+			printk(name_suspend
+				"The swapfile/partition specified by "
+				"/proc/suspend/swapfile (%s) could not"
+				" be turned on (error %d). Attempting "
+				"to continue.\n",
+				swapfilename, activateswapresult);
+		if (!activateswapresult)
+			suspend_swapon_status = 1;
+	}
+	return activateswapresult;
+}
+
+extern asmlinkage long sys_swapoff(const char * specialfile);
+/* Returns 0 if was on, -EINVAL if was off, error value otherwise */
+static int disable_swapfile(void)
+{
+	int result = -EINVAL;
+	
+	if (!suspend_swapon_status)
+		return 0;
+
+	if (swapfilename[0]) {
+		result = sys_swapoff(swapfilename);
+		if (result == -EINVAL)
+	 		return 0;	/* Wasn't on */
+		if (!result)
+			suspend_swapon_status = 0;
+	}
+
+	return result;
+}
+
+static int manage_swapfile(int enable)
+{
+	static int result;
+	mm_segment_t	oldfs;
+
+	oldfs = get_fs(); set_fs(KERNEL_DS);
+	if (enable)
+		result = enable_swapfile();
+	else
+		result = disable_swapfile();
+	set_fs(oldfs);
+
+	return result;
+}
+
+/*
+ * ---------------------------------------------------------------
+ *
+ *     Current state.
+ *
+ * ---------------------------------------------------------------
+ */
+
+/* Which pagedir are we saving/reloading? Needed so we can know whether to
+ * remember the last swap entry used at the end of writing pageset2, and
+ * get that location when saving or reloading pageset1.*/
+static int current_stream = 0;
+
+/* Pointer to current swap entry being loaded/saved. */
+static struct range * currentblockrange = NULL;
+static unsigned long currentblockoffset = 0;
+static int currentblockchain = 0;
+static int currentblocksperpage = 0;
+
+/* Header Page Information */
+static int header_pages_allocated = 0;
+static struct submit_params * first_header_submit_info = NULL,
+ * last_header_submit_info = NULL, * current_header_submit_info = NULL;
+
+/*
+ * ---------------------------------------------------------------
+ *
+ *     User Specified Parameters
+ *
+ * ---------------------------------------------------------------
+ */
+
+static int resume_firstblock = 0;
+static int resume_firstblocksize = PAGE_SIZE;
+static dev_t resume_device = 0;
+static struct block_device * resume_block_device = NULL;
+
+/*
+ * ---------------------------------------------------------------
+ *
+ *     Disk I/O routines
+ *
+ * ---------------------------------------------------------------
+ */
+extern char swapfilename[];
+
+extern int expected_compression;
+
+struct sysinfo swapinfo;
+
+#define MARK_SWAP_SUSPEND 0
+#define MARK_SWAP_RESUME 1
+
+static int swapwriter_invalidate_image(void);
+
+static int get_phys_params(swp_entry_t entry)
+{
+	int swapfilenum = swp_type(entry);
+	unsigned long offset = swp_offset(entry);
+	struct swap_info_struct * sis = get_swap_info_struct(swapfilenum);
+	sector_t sector = map_swap_page(sis, offset);
+
+	add_to_range_chain(&header_data.block_chain[swapfilenum], sector);
+	return 1;
+}
+
+static int get_header_params(struct submit_params * headerpage)
+{
+	swp_entry_t entry = headerpage->swap_address;
+	int swapfilenum = swp_type(entry);
+	unsigned long offset = swp_offset(entry);
+	struct swap_info_struct * sis = get_swap_info_struct(swapfilenum);
+	sector_t sector = map_swap_page(sis, offset);
+
+	headerpage->dev = sis->bdev,
+	headerpage->blocks[0] = sector;
+	headerpage->blocks_used = 1;
+	headerpage->readahead_index = -1;
+	return 0;
+}
+
+static inline int get_blocks_per_page(int chain)
+{
+	return 1;
+#if 0
+	int result = PAGE_SIZE /
+		suspend_bio_ops.get_block_size(swap_info[chain].bdev);
+	printk("Block size for chain %d is %d,\n",
+			chain, result);
+	return result;
+#endif
+}
+
+static int try_to_parse_resume_device(char * commandline)
+{
+	resume_device = name_to_dev_t(commandline);
+	if (!resume_device) {
+		if (test_suspend_state(SUSPEND_BOOT_TIME))
+			suspend_early_boot_message(1, "Failed to translate the device name into a device id.\n");
+		else
+			printk(name_suspend "Failed to translate \"%s\" into a device id.\n", commandline);
+		return 1;
+	}
+	
+	resume_block_device = open_by_devnum(resume_device, FMODE_READ);
+
+	if (IS_ERR(resume_block_device)) {
+		printk("Open by devnum returned %p given %x.\n", resume_block_device, resume_device);
+		if (test_suspend_state(SUSPEND_BOOT_TIME))
+			suspend_early_boot_message(1, "Failed to get access to the device on which Software Suspend's header should be found.");
+		else
+			printk("Failed to get access to the device on which Software Suspend's header should be found.\n");
+		return 1;
+	}
+
+	return 0;
+}
+
+static int try_to_parse_header_device(void)
+{
+	header_block_device = open_by_devnum(header_device, FMODE_READ);
+
+	if (IS_ERR(header_block_device)) {
+		if (suspend_early_boot_message(1,
+				"Failed to get access to the "
+				"resume header device.\nYou could be "
+				"booting with a 2.6 kernel when you "
+				"suspended a 2.4 kernel."))
+			swapwriter_invalidate_image();
+
+		return -EINVAL;
+	}
+
+	if (set_blocksize(header_block_device, PAGE_SIZE) < 0) {
+		if (suspend_early_boot_message(1, "Failed to set the blocksize"
+			"for a swap device."))
+				do { } while(0);
+		swapwriter_invalidate_image();
+		return -EINVAL;
+	}
+
+	return 0;
+}
+
+static void open_other_swap_device(int i, dev_t thisdevice)
+{
+	swap_info[i].bdev = open_by_devnum(thisdevice, FMODE_READ);
+	set_blocksize(swap_info[i].bdev, PAGE_SIZE);
+}
+
+static inline char * get_path_for_swapfile(int which, char * path_page)
+{
+	return d_path(	swap_info[which].swap_file->f_dentry,
+			swap_info[which].swap_file->f_vfsmnt,
+			path_page,
+			PAGE_SIZE);
+}
+
+static void swapwriter_noresume_reset(void)
+{
+	int i;
+
+ 	/* 
+	 * If we have read part of the image, we might have filled header_data with
+	 * data that should be zeroed out.
+	 */
+
+	memset((char *) &header_data, 0, sizeof(header_data));
+	for (i = 0; i < MAX_SWAPFILES; i++) {
+		swap_info[i].bdev = NULL;
+	}
+	 
+}
+
+static void swapwriter_dpm_set_devices(void)
+{
+	int i;
+
+	/* Set our device(s) as remaining on. */
+	for (i = 0; i < MAX_SWAPFILES; i++) {
+		if (!swap_info[i].bdev)
+			continue;
+
+		device_switch_trees((swap_info[i].bdev)->bd_disk->driverfs_dev,
+				suspend_device_tree);
+	}
+}
+
+/*
+ *
+ */
+
+int parse_signature(char * header, int restore)
+{
+	int type = -1;
+	
+	if (!memcmp("SWAP-SPACE",header,10))
+		return 0;
+	else if (!memcmp("SWAPSPACE2",header,10))
+		return 1;
+
+	else if (!memcmp("pmdisk", header,6))
+		type = 2;
+	
+	else if (!memcmp("S1SUSP",header,6))
+		type = 4;
+	else if (!memcmp("S2SUSP",header,6))
+		type = 5;
+	
+	else if (!memcmp("1R",header,2))
+		type = 6;
+	else if (!memcmp("2R",header,2))
+		type = 7;
+	
+	else if (!memcmp("std",header,3))
+		type = 8;
+	else if (!memcmp("STD",header,3))
+		type = 9;
+	
+	else if (!memcmp("sd",header,2))
+		type = 10;
+	else if (!memcmp("SD",header,2))
+		type = 11;
+	
+	else if (!memcmp("z",header,1))
+		type = 12;
+	else if (!memcmp("Z",header,1))
+		type = 13;
+	
+	/* 
+	 * Put bdev of suspend header in last byte of swap header
+	 * (unsigned short)
+	 */
+	if (type > 11) {
+		dev_t * header_ptr = (dev_t *) &header[1];
+		unsigned char * headerblocksize_ptr =
+			(unsigned char *) &header[5];
+		unsigned long * headerblock_ptr = (unsigned long *) &header[6];
+		header_device = *header_ptr;
+		/* 
+		 * We are now using the highest bit of the char to indicate
+		 * whether we have attempted to resume from this image before.
+		 */
+		clear_suspend_state(SUSPEND_RESUMED_BEFORE);
+		if (((int) *headerblocksize_ptr) & 0x80)
+			set_suspend_state(SUSPEND_RESUMED_BEFORE);
+		headerblocksize = 512 * (((int) *headerblocksize_ptr) & 0xf);
+		headerblock = *headerblock_ptr;
+	}
+
+	if ((restore) && (type > 5)) {
+		/* We only reset our own signatures */
+		if (type & 1)
+			memcpy(header,"SWAPSPACE2",10);
+		else
+			memcpy(header,"SWAP-SPACE",10);
+	}
+
+	return type;
+}
+
+/*
+ * prepare_signature
+ */
+
+static int prepare_signature(struct submit_params * header_page_info,
+		char * current_header)
+{
+	int current_type = parse_signature(current_header, 0);
+	dev_t * header_ptr = (dev_t *) (&current_header[1]);
+	unsigned char * headerblocksize_ptr =
+		(unsigned char *) (&current_header[5]);
+	unsigned long * headerblock_ptr =
+		(unsigned long *) (&current_header[6]);
+
+	if ((current_type > 1) && (current_type < 6))
+		return 1;
+
+	if (current_type & 1)
+		current_header[0] = 'Z';
+	else
+		current_header[0] = 'z';
+	*header_ptr = header_page_info->dev->bd_dev;
+	*headerblocksize_ptr =
+		(unsigned char) (PAGE_SIZE / 512 / 
+				 header_page_info->blocks_used);
+	/* prev is the first/last swap page of the resume area */
+	*headerblock_ptr = (unsigned long) header_page_info->blocks[0]; 
+	suspend_message(SUSPEND_WRITER, SUSPEND_HIGH, 1,
+			"Saving header block size of %ld (%ld 512 "
+			"byte blocks per page).\n",
+			PAGE_SIZE / header_page_info->blocks_used,
+			PAGE_SIZE / 512 / header_page_info->blocks_used);
+	return 0;
+}
+
+extern int signature_check(char * header, int fix);
+
+static int free_swap_pages_for_header(void)
+{
+	if (!first_header_submit_info)
+		return 1;
+
+	PRINTFREEMEM("at start of free_swap_pages_for_header");
+
+	while (first_header_submit_info) {
+		struct submit_params * next = first_header_submit_info->next;
+		if (first_header_submit_info->swap_address.val)
+			swap_free(first_header_submit_info->swap_address);
+		kfree(first_header_submit_info);
+		first_header_submit_info = next;
+	}
+	
+	suspend_message(SUSPEND_WRITER, SUSPEND_LOW, 1,
+			" Freed %d swap pages in free_swap_pages_for_header.\n",
+			header_pages_allocated);
+	first_header_submit_info = last_header_submit_info = NULL;
+	header_pages_allocated = 0;
+	PRINTFREEMEM("at end of free_swap_pages_for_header");
+	suspend_store_free_mem(SUSPEND_FREE_HEADER_STORAGE, 1);
+	return 0;
+}
+
+static void get_main_pool_phys_params(void)
+{
+	struct range * rangepointer = NULL;
+	unsigned long address;
+	int i;
+	
+	for (i = 0; i < MAX_SWAPFILES; i++)
+		if (header_data.block_chain[i].first)
+			put_range_chain(&header_data.block_chain[i]);
+
+	range_for_each(&header_data.swapranges, rangepointer, address)
+		get_phys_params(range_val_to_swap_entry(address));
+}
+
+extern void put_range(struct range * range);
+
+static unsigned long swapwriter_storage_allocated(void)
+{
+	return (header_data.swapranges.size + header_pages_allocated);
+}
+
+static long swapwriter_storage_available(void)
+{
+	si_swapinfo(&swapinfo);
+	return (swapinfo.freeswap + (long) swapwriter_storage_allocated());
+}
+
+static int swapwriter_initialise(void)
+{
+	manage_swapfile(1);
+	return 0;
+}
+
+static void swapwriter_cleanup(void)
+{
+	manage_swapfile(0);
+}
+
+static int swapwriter_release_storage(void)
+{
+	int i = 0, swapcount = 0;
+
+#ifdef CONFIG_SOFTWARE_SUSPEND_KEEP_IMAGE
+	if ((TEST_ACTION_STATE(SUSPEND_KEEP_IMAGE)) && test_suspend_state(SUSPEND_NOW_RESUMING))
+		return 0;
+#endif
+
+	free_swap_pages_for_header();
+	
+	if (header_data.swapranges.first) {
+		/* Free swap entries */
+		struct range * rangepointer;
+		unsigned long rangevalue;
+		swp_entry_t entry;
+		range_for_each(&header_data.swapranges, rangepointer, 
+				rangevalue) {
+			entry = range_val_to_swap_entry(rangevalue);
+			swap_free(entry);
+
+			swapcount++;
+			check_shift_keys(0, NULL);
+		}
+		put_range_chain(&header_data.swapranges);
+		
+		for (i = 0; i < MAX_SWAPFILES; i++)
+			if (header_data.block_chain[i].first)
+				put_range_chain(&header_data.block_chain[i]);
+	}
+	
+	suspend_message(SUSPEND_WRITER, SUSPEND_MEDIUM, 0,
+			"Freed %d swap pages in free_swap.\n", swapcount);
+
+	return 0;
+}
+
+static long swapwriter_allocate_header_space(unsigned long space_really_requested)
+{
+	/* space_requested was going to be in bytes... not yet */
+	int i, ret = 0;
+	unsigned long space_requested;
+
+	/* 
+	 * Up to here in the process, we haven't taken account of the fact
+	 * that we need an extra four bytes per 4092 bytes written for link
+	 * to the next page on which the header will be written. We factor
+	 * that in here.
+	 */
+	space_requested = ((4096 * space_really_requested + 4091) / 4092);
+	space_requested = (space_requested * 4 + 4091) / 4092;
+	space_requested += space_really_requested;
+	
+	PRINTFREEMEM("at start of allocate_header_space");
+	
+	for (i=(header_pages_allocated+1); i<=space_requested; i++) {
+		struct submit_params * new_submit_param;
+		
+		/* Get a submit structure */
+		new_submit_param = kmalloc(sizeof(struct submit_params), GFP_ATOMIC);
+		
+		if (!new_submit_param) {
+			header_pages_allocated = i - 1;
+			printk("Failed to kmalloc a struct submit param.\n");
+			ret = -ENOMEM;
+			goto out;
+		}
+
+		memset(new_submit_param, 0, sizeof(struct submit_params));
+
+		if (last_header_submit_info) {
+			last_header_submit_info->next = new_submit_param;
+			last_header_submit_info = new_submit_param;
+		} else
+			last_header_submit_info = first_header_submit_info =
+				new_submit_param;
+
+		/* Get swap entry */
+		new_submit_param->swap_address = get_swap_page();
+		
+		if ((!new_submit_param->swap_address.val) &&
+			       (header_data.swapranges.first)) {
+			/*
+			 *  Steal one from pageset swap chain. If, as a result,
+			 *  it is too small, more swap will be allocated or
+			 *  memory eaten.
+			 */
+
+			new_submit_param->swap_address =
+				range_val_to_swap_entry(
+					header_data.swapranges.first->minimum);
+			if (header_data.swapranges.first->minimum <
+					header_data.swapranges.first->maximum)
+				header_data.swapranges.first->minimum++;
+			else {
+				struct range * oldfirst =
+					header_data.swapranges.first;
+				header_data.swapranges.first = oldfirst->next;
+				header_data.swapranges.frees++;
+				header_data.swapranges.prevtoprev =
+				 header_data.swapranges.prevtolastaccessed =
+				 header_data.swapranges.lastaccessed = NULL;
+				if (header_data.swapranges.last == oldfirst)
+					header_data.swapranges.last = NULL;
+				put_range(oldfirst);
+			}
+			
+			header_data.swapranges.size--;
+
+			/*
+			 * Recalculate block chains for main pool.
+			 * We don't assume blocks are at start of a chain and
+			 * don't know how many blocks per swap entry.
+			 */
+			get_main_pool_phys_params();
+		}
+		if (!new_submit_param->swap_address.val) {
+			free_swap_pages_for_header();
+			printk("Unable to allocate swap page for header.\n");
+			ret = -ENOMEM;
+			goto out;
+		}
+		if (get_header_params(new_submit_param)) {
+			printk("Failed to get header parameters.\n");
+			ret = -EFAULT;
+			goto out;
+		}
+		suspend_message(SUSPEND_HEADER, SUSPEND_MEDIUM, 0,
+			" Got header page %d/%d. Dev is %x. Block is %lu. "
+			"Blocksperpage is %d.\n",
+			i, space_requested,
+			new_submit_param->dev,
+			new_submit_param->blocks[0],
+			new_submit_param->blocks_used);
+	}
+	header_pages_allocated = space_requested;
+	suspend_message(SUSPEND_HEADER, SUSPEND_LOW, 1,
+			" Have %d swap pages in swapwriter::"
+			"allocate_header_space.\n",
+			header_pages_allocated);
+out:
+	PRINTFREEMEM("at end of swapwriter::allocate_header_space");
+	suspend_store_free_mem(SUSPEND_FREE_HEADER_STORAGE, 0);
+	return ret;
+}
+
+static int swapwriter_allocate_storage(unsigned long space_requested)
+{
+	int i, swapcount = 0, result = 0;
+	int lastsize = header_data.swapranges.size;
+	int numwanted = (int) (space_requested);
+	int pages_to_get = numwanted - header_data.swapranges.size;
+	
+	if (numwanted < 1)
+		return 0;
+
+	suspend_message(SUSPEND_WRITER, SUSPEND_MEDIUM, 0,
+		"Started with swapranges.size == %d. "
+		"Seeking to allocate %d more.\n",
+		header_data.swapranges.size,
+		pages_to_get);
+
+	for(i=0; i < pages_to_get; i++) {
+		swp_entry_t entry;
+		suspend_message(SUSPEND_WRITER, SUSPEND_VERBOSE, 1, "");
+		entry = get_swap_page();
+		if (!entry.val) {
+			suspend_message(SUSPEND_WRITER, SUSPEND_MEDIUM, 0,
+				"Allocated %d/%d swap pages for main pool "
+				"in allocate_swap.\n",
+				swapcount, numwanted);
+			printk("Unable to allocate enough swap."
+				" Got %d pages of %d wanted.\n",
+				i, pages_to_get);
+			result = -ENOSPC;
+			goto out;
+		}
+		swapcount++;
+		{
+			int result =
+				add_to_range_chain(&header_data.swapranges,
+					       swap_entry_to_range_val(entry));
+			if (result)
+				printk("add_to_range_chain returned %d.\n",
+						result);
+		}
+		if (header_data.swapranges.size != (lastsize + 1))
+			printk("swapranges.size == %d.\n",
+					header_data.swapranges.size);
+		lastsize = header_data.swapranges.size;
+		check_shift_keys(0, NULL);
+		if (TEST_RESULT_STATE(SUSPEND_ABORTED))
+			break;
+	}
+	suspend_message(SUSPEND_WRITER, SUSPEND_MEDIUM, 0,
+		" Allocated %d/%d swap pages in allocate_swap.\n",
+		swapcount, numwanted);
+	
+	suspend_message(SUSPEND_WRITER, SUSPEND_MEDIUM, 0,
+		"Finished with swapranges.size == %d.\n",
+		header_data.swapranges.size);
+
+out:
+	get_main_pool_phys_params();
+	
+	/* Any memory we allocate will be for range pages */
+	suspend_store_free_mem(SUSPEND_FREE_RANGE_PAGES, 0);
+	return result;
+}
+
+static int swapwriter_write_header_chunk(char * buffer, int buffer_size);
+static int header_bytes_written;
+
+static int swapwriter_write_header_init(void)
+{
+	int i;
+
+	header_bytes_written = 0;
+
+	for (i = 0; i < MAX_SWAPFILES; i++)
+		if (swap_info[i].swap_file) {
+			header_data.swapdevs[i] = swap_info[i].bdev->bd_dev;
+			header_data.blocksizes[i] =
+				block_size(swap_info[i].bdev);
+		}
+
+	header_data.max_async_ios = max_async_ios;
+
+	swapwriter_buffer = (char *) get_zeroed_page(GFP_ATOMIC);
+	header_link =
+		(unsigned long *) (swapwriter_buffer + BYTES_PER_HEADER_PAGE);
+	swapwriter_page_index = 1;
+
+	current_header_submit_info = first_header_submit_info;
+	
+	/* Info needed to bootstrap goes at the start of the header.
+	 * First we save the 'header_data' struct, including the number
+	 * of header pages. Then we save the structs containing data needed
+	 * for reading the header pages back.
+	 * Note that even if header pages take more than one page, when we
+	 * read back the info, we will have restored the location of the
+	 * next header page by the time we go to use it.
+	 */
+	swapwriter_write_header_chunk((char *) &header_data, 
+			sizeof(header_data));
+
+	return 0;
+}
+
+static int swapwriter_write_header_chunk(char * buffer, int buffer_size)
+{
+	int bytes_left = buffer_size;
+	
+	/* 
+	 * We buffer the writes until a page is full and to use the last
+	 * sizeof(swp_entry_t) bytes for links between pages. This is 
+	 * totally transparent to the caller.
+	 *
+	 * Note also that buffer_size can be > PAGE_SIZE.
+	 */
+
+	header_bytes_written += buffer_size;
+	
+	suspend_message(SUSPEND_HEADER, SUSPEND_HIGH, 0,
+		"\nStart of write_header_chunk loop with %d bytes to store.\n",
+		buffer_size);
+
+	while (bytes_left) {
+		char * source_start = buffer + buffer_size - bytes_left;
+		char * dest_start = swapwriter_buffer + swapwriter_buffer_posn;
+		int dest_capacity = BYTES_PER_HEADER_PAGE - swapwriter_buffer_posn;
+		swp_entry_t next_header_page;
+		if (bytes_left <= dest_capacity) {
+			suspend_message(SUSPEND_HEADER, SUSPEND_HIGH, 0,
+				"Storing %d bytes from %p-%p in page %d, %p-%p.\n",
+				bytes_left,
+				source_start, source_start + bytes_left - 1,
+				swapwriter_page_index,
+				dest_start, dest_start + bytes_left - 1);
+			memcpy(dest_start, source_start, bytes_left);
+			swapwriter_buffer_posn += bytes_left;
+			return 0;
+		}
+	
+		/* A page is full */
+		suspend_message(SUSPEND_HEADER, SUSPEND_HIGH, 0,
+			"Storing %d bytes from %p-%p in page %d, %p-%p.\n",
+			dest_capacity,
+			source_start, source_start + dest_capacity - 1,
+			swapwriter_page_index,
+			dest_start, dest_start + dest_capacity - 1);
+		memcpy(dest_start, source_start, dest_capacity);
+		bytes_left -= dest_capacity;
+
+		BUG_ON(!current_header_submit_info);
+
+		if (!current_header_submit_info->next) {
+			suspend_message(SUSPEND_HEADER, SUSPEND_HIGH, 0,
+				"This submit_info is the last one. Link zeroed.\n");
+			*header_link = 0;
+		} else {
+			next_header_page =
+				swp_entry(swp_type(
+				current_header_submit_info->next->swap_address),
+				current_header_submit_info->next->blocks[0]);
+
+			*header_link = next_header_page.val;
+		
+			suspend_message(SUSPEND_HEADER, SUSPEND_HIGH, 0,
+				"Header link is at %p. "
+				"Contents set to swap device #%ld, block %ld.\n",
+				header_link,
+				(long) swp_type(next_header_page),
+				swp_offset(next_header_page));
+		}
+
+		suspend_message(SUSPEND_HEADER, SUSPEND_HIGH, 0,
+			"Writing header page %d/%d. "
+			"Dev is %x. Block is %lu. Blocksperpage is %d.\n",
+			swapwriter_page_index, header_pages_allocated,
+			current_header_submit_info->dev->bd_dev,
+			current_header_submit_info->blocks[0],
+			current_header_submit_info->blocks_used);
+		
+		current_header_submit_info->page =
+			virt_to_page(swapwriter_buffer);
+		check_shift_keys(0, NULL);
+		suspend_bio_ops.submit_io(WRITE, current_header_submit_info, 0);
+
+		swapwriter_buffer_posn = 0;
+		swapwriter_page_index++;
+		current_header_submit_info = current_header_submit_info->next;
+	}
+
+	return 0;
+}
+
+static int swapwriter_write_header_cleanup(void)
+{
+	/* Write any unsaved data */
+	if (swapwriter_buffer_posn) {
+		*header_link = 0;
+
+		suspend_message(SUSPEND_HEADER, SUSPEND_HIGH, 0,
+			"Writing header page %d/%d. "
+			"Dev is %x. Block is %lu. Blocksperpage is %d.\n",
+			swapwriter_page_index, header_pages_allocated,
+			current_header_submit_info->dev->bd_dev,
+			current_header_submit_info->blocks[0],
+			current_header_submit_info->blocks_used);
+		
+		current_header_submit_info->page =
+			virt_to_page(swapwriter_buffer);
+		suspend_bio_ops.submit_io(WRITE, 
+				current_header_submit_info, 0);
+	}
+
+	/* Adjust swap header */
+	suspend_bio_ops.bdev_page_io(READ, resume_block_device, resume_firstblock,
+			virt_to_page(swapwriter_buffer));
+
+	prepare_signature(first_header_submit_info,
+		((union swap_header *) swapwriter_buffer)->magic.magic);
+		
+	suspend_bio_ops.bdev_page_io(WRITE, resume_block_device, resume_firstblock,
+			virt_to_page(swapwriter_buffer));
+
+	free_pages((unsigned long) swapwriter_buffer, 0);
+	swapwriter_buffer = NULL;
+	header_link = NULL;
+	
+	suspend_bio_ops.finish_all_io();
+
+	return 0;
+}
+
+/* ------------------------- HEADER READING ------------------------- */
+
+/*
+ * read_header_init()
+ * 
+ * Description:
+ * 1. Attempt to read the device specified with resume2=.
+ * 2. Check the contents of the swap header for our signature.
+ * 3. Warn, ignore, reset and/or continue as appropriate.
+ * 4. If continuing, read the swapwriter configuration section
+ *    of the header and set up block device info so we can read
+ *    the rest of the header & image.
+ *
+ * Returns:
+ * May not return if user choose to reboot at a warning.
+ * -EINVAL if cannot resume at this time. Booting should continue
+ * normally.
+ */
+
+static int swapwriter_read_header_init(void)
+{
+	int i;
+	
+	swapwriter_page_index = 1;
+
+	swapwriter_buffer = (char *) get_zeroed_page(GFP_ATOMIC);
+
+	if (!header_device) {
+		printk("read_header_init called when we haven't "
+				"verified there is an image!\n");
+		return -EINVAL;
+	}
+
+	/* 
+	 * If the header is not on the resume_device, get the resume device first.
+	 */
+	if (header_device != resume_device) {
+		int result = try_to_parse_header_device();
+
+		if (result)
+			return result;
+	} else
+		header_block_device = resume_block_device;
+
+	/* Read swapwriter configuration */
+	suspend_bio_ops.bdev_page_io(READ, header_block_device, headerblock,
+			virt_to_page((unsigned long) swapwriter_buffer));
+	//FIXME Remember location of next page to be read.
+	
+	suspend_message(SUSPEND_WRITER, SUSPEND_HIGH, 0,
+		"Retrieving %d bytes from %x:%x to page %d, %p-%p.\n",
+		header_block_device->bd_dev, headerblock,
+		sizeof(header_data),
+		swapwriter_page_index,
+		swapwriter_buffer, swapwriter_buffer + sizeof(header_data) - 1);
+	memcpy(&header_data, swapwriter_buffer, sizeof(header_data));
+	
+	/* Restore device info */
+	for (i = 0; i < MAX_SWAPFILES; i++) {
+		dev_t thisdevice = header_data.swapdevs[i];
+		
+		suspend_message(SUSPEND_WRITER, SUSPEND_VERBOSE, 1,
+				"Swap device %d is %x.", i, thisdevice);
+		
+		if (!thisdevice)
+			continue;
+
+		if (thisdevice == resume_device) {
+			suspend_message(SUSPEND_WRITER, SUSPEND_VERBOSE, 0,
+					"Resume root device %x", thisdevice);
+			swap_info[i].bdev = resume_block_device;
+			/* Mark as used so the device doesn't get suspended. */
+			swap_info[i].swap_file = (struct file *) 0xffffff;
+			continue;
+		}
+
+		if (thisdevice == header_device) {
+			suspend_message(SUSPEND_WRITER, SUSPEND_VERBOSE, 0,
+					"Resume header device %x", thisdevice);
+			swap_info[i].bdev = header_block_device;
+			/* Mark as used so the device doesn't get suspended. */
+			swap_info[i].swap_file = (struct file *) 0xffffff;
+			continue;
+		}
+
+		open_other_swap_device(i, thisdevice);
+		swap_info[i].swap_file = (struct file *) 0xffffff;
+	}
+
+	max_async_ios =	header_data.max_async_ios;
+
+	swapwriter_buffer_posn = sizeof(header_data);
+
+	return 0;
+}
+
+static int swapwriter_read_header_chunk(char * buffer, int buffer_size)
+{
+	int bytes_left = buffer_size, ret = 0;
+	
+	check_shift_keys(0, "");
+
+	/* Read a chunk of the header */
+	while ((bytes_left) && (!ret)) {
+		swp_entry_t next =
+		   ((union p_diskpage) swapwriter_buffer).pointer->link.next;
+		struct block_device * dev = swap_info[swp_type(next)].bdev;
+		int pos = swp_offset(next);
+		char * dest_start = buffer + buffer_size - bytes_left;
+		char * source_start =
+			swapwriter_buffer + swapwriter_buffer_posn;
+		int source_capacity =
+			BYTES_PER_HEADER_PAGE - swapwriter_buffer_posn;
+
+		if (bytes_left <= source_capacity) {
+			suspend_message(SUSPEND_WRITER, SUSPEND_HIGH, 0,
+				"Retrieving %d bytes from page %d, "
+				"%p-%p into %p-%p.\n",
+				bytes_left,
+				swapwriter_page_index,
+				source_start, source_start + bytes_left - 1,
+				dest_start, dest_start + bytes_left - 1);
+			memcpy(dest_start, source_start, bytes_left);
+			swapwriter_buffer_posn += bytes_left;
+			return buffer_size;
+		}
+
+		/* Next to read the next page */
+		suspend_message(SUSPEND_WRITER, SUSPEND_HIGH, 0,
+			"Retrieving %d bytes from page %d, %p-%p to %p-%p.\n",
+			source_capacity,
+			swapwriter_page_index,
+			source_start, source_start + source_capacity - 1,
+			dest_start, dest_start + source_capacity - 1);
+		memcpy(dest_start, source_start, source_capacity);
+		bytes_left -= source_capacity;
+
+		suspend_message(SUSPEND_WRITER, SUSPEND_HIGH, 0,
+		 "Header link is at %p. Contents set to %lx = "
+		 "swap device #%x, block %d.\n",
+		 &((union p_diskpage) swapwriter_buffer).pointer->link.next,
+		 ((union p_diskpage) swapwriter_buffer).pointer->link.next.val,
+		 dev->bd_dev, pos);
+
+		swapwriter_page_index++;
+
+		suspend_message(SUSPEND_WRITER, SUSPEND_HIGH, 0,
+			"Reading header page %d. Dev is %x. Block is %lu.\n",
+			swapwriter_page_index, dev->bd_dev, pos);
+		
+		suspend_bio_ops.bdev_page_io(READ, dev, pos, virt_to_page(swapwriter_buffer));
+
+		swapwriter_buffer_posn = 0;
+	}
+
+	return buffer_size - bytes_left;
+}
+
+static int swapwriter_read_header_cleanup(void)
+{
+	free_pages((unsigned long) swapwriter_buffer, 0);
+	return 0;
+}
+
+static int swapwriter_prepare_save_ranges(void)
+{
+	int i;
+
+	relativise_chain(&header_data.swapranges);
+	
+	for (i = 0; i < MAX_SWAPFILES; i++)
+		relativise_chain(&header_data.block_chain[i]);
+	
+	header_data.pd1start_block_range =
+		RANGE_RELATIVE(header_data.pd1start_block_range);
+
+	suspend_message(SUSPEND_WRITER, SUSPEND_HIGH, 0,
+		"Pagedir1 firstblockrange is %p.\n",
+		header_data.pd1start_block_range);
+
+	return 0;
+}
+
+static int swapwriter_post_load_ranges(void)
+{
+	int i;
+	
+	if (get_rangepages_list())
+		return -ENOMEM;
+	
+	absolutise_chain(&header_data.swapranges);
+
+	for (i = 0; i < MAX_SWAPFILES; i++)
+		absolutise_chain(&header_data.block_chain[i]);
+
+	header_data.pd1start_block_range =
+		RANGE_ABSOLUTE(header_data.pd1start_block_range);
+	
+	return 0;
+}
+
+static int swapwriter_write_init(int stream_number)
+{
+	if (stream_number == 1) {
+		currentblockrange = header_data.pd1start_block_range;
+		currentblockoffset = header_data.pd1start_block_offset;
+		currentblockchain = header_data.pd1start_chain;
+	} else
+		for (currentblockchain = 0; currentblockchain < MAX_SWAPFILES;
+				currentblockchain++)
+			if (header_data.block_chain[currentblockchain].first) {
+				currentblockrange =
+					header_data.
+					 block_chain[currentblockchain].first;
+				currentblockoffset = currentblockrange->minimum;
+				break;
+			}
+
+	BUG_ON(!currentblockrange);
+
+	currentblocksperpage = PAGE_SIZE / 
+		suspend_bio_ops.get_block_size(swap_info[currentblockchain].bdev);
+
+	suspend_message(SUSPEND_WRITER, SUSPEND_HIGH, 0,
+		"Stream %d beginning from position: chain %d. "
+		"range %p, block %ld.\n",
+		stream_number,
+		currentblockchain, currentblockrange, currentblockoffset);
+	
+	swapwriter_page_index = 1;
+	current_stream = stream_number;
+
+	suspend_bio_ops.reset_io_stats();
+
+	return 0;
+}
+
+static int swapwriter_write_chunk(struct page * buffer_page)
+{
+	int i;
+	struct submit_params submit_params;
+
+	if (TEST_ACTION_STATE(SUSPEND_TEST_FILTER_SPEED))
+		return 0;
+		
+	if (currentblockchain == MAX_SWAPFILES) {
+		printk("Error! We have run out of blocks for writing data.\n");
+		for (i = 0; i < MAX_SWAPFILES; i++) {
+			if (!swap_info[i].swap_file)
+				printk("Swap slot %d is unused.\n", i);
+			else
+				printk("Swap slot %d is device %x.\n",
+						i, swap_info[i].bdev->bd_dev);
+			if (header_data.block_chain[i].size)
+				printk("Chain size for device %d is %d.\n", i,
+					header_data.block_chain[i].size);
+		}
+		return -ENOSPC;
+	}
+	
+	if (!currentblockrange) {
+		do {
+			currentblockchain++;
+		} while ((currentblockchain < MAX_SWAPFILES) &&
+		   (!header_data.block_chain[currentblockchain].first));
+
+		/* We can validly not have a new blockrange. We
+		 * might be compressing data and the user was
+		 * too optimistic in setting the compression
+		 * ratio or we're just copying the pageset. */
+
+		if (currentblockchain == MAX_SWAPFILES) {
+			printk("Argh. Ran out of block chains.\n");
+			return -ENOSPC;
+		}
+				
+		currentblockrange = 
+		 header_data.block_chain[currentblockchain].first;
+		currentblockoffset = currentblockrange->minimum;
+		currentblocksperpage = PAGE_SIZE /
+		  suspend_bio_ops.get_block_size(swap_info[currentblockchain].bdev);
+	}
+
+	submit_params.readahead_index = -1;
+	submit_params.page = buffer_page;
+	submit_params.dev = swap_info[currentblockchain].bdev;
+	submit_params.blocks_used = currentblocksperpage;
+		
+	/* Get the blocks */
+	for (i = 0; i < currentblocksperpage; i++) {
+		submit_params.blocks[i] = currentblockoffset;
+		GET_RANGE_NEXT(currentblockrange, currentblockoffset);
+	}
+
+	suspend_message(SUSPEND_WRITER, SUSPEND_HIGH, 0,
+		"Writing page %d. Dev is %x. Block is %lu. "
+		"Blocksperpage is %d.\n",
+		swapwriter_page_index,
+		submit_params.dev,
+		submit_params.blocks[0],
+		currentblocksperpage);
+		
+	suspend_message(SUSPEND_PAGESETS, SUSPEND_VERBOSE, 1,
+		"page:%d. bdev:%x. blocks (%d):",
+		swapwriter_page_index,
+		submit_params.dev->bd_dev,
+		submit_params.blocks_used);
+
+	for (i = 0; i < currentblocksperpage; i++)
+		suspend_message(SUSPEND_PAGESETS, SUSPEND_VERBOSE, 0,
+			"0x%lx%s",
+			submit_params.blocks[i],
+			((i+1) < currentblocksperpage) ? "," : "\n");
+
+	check_shift_keys(0, NULL);
+
+	suspend_bio_ops.submit_io(WRITE, &submit_params, 0);
+
+	swapwriter_page_index++;
+
+	return 0;
+}
+
+static int swapwriter_write_cleanup(void)
+{
+	if (current_stream == 2) {
+		header_data.pd1start_block_range = currentblockrange;
+		header_data.pd1start_block_offset = currentblockoffset;
+		header_data.pd1start_chain = currentblockchain;
+	}
+	
+	suspend_bio_ops.finish_all_io();
+	
+	suspend_bio_ops.check_io_stats();
+
+	return 0;
+}
+
+static int swapwriter_read_init(int stream_number)
+{
+	int i;
+
+	if (stream_number == 1) {
+		currentblockrange = header_data.pd1start_block_range;
+		currentblockoffset = header_data.pd1start_block_offset;
+		currentblockchain = header_data.pd1start_chain;
+	} else {
+		currentblockrange = NULL;
+		currentblockoffset = 0;
+		currentblockchain = 0;
+		for (currentblockchain = 0; currentblockchain < MAX_SWAPFILES;
+			       currentblockchain++)
+			if (header_data.block_chain[currentblockchain].first) {
+				currentblockrange =
+					header_data.block_chain[currentblockchain].first;
+				currentblockoffset = currentblockrange->minimum;
+				break;
+			}
+
+		if (!currentblockrange){
+			printk("Error! Can't find any block chain data.\n");
+			for (i = 0; i < MAX_SWAPFILES; i++) {
+				if (!swap_info[i].swap_file)
+					printk("Swap slot %d is unused.\n", i);
+				else
+					printk("Swap slot %d is device %x.\n",
+							i, swap_info[i].bdev->bd_dev);
+				if (header_data.block_chain[i].size)
+					printk("Chain size for device %d"
+							" is %d.\n", i,
+					 header_data.block_chain[i].size);
+				printk("First entry in chain at %p.\n",
+					header_data.block_chain[i].first);
+			}
+			BUG_ON(1);
+		}
+	}
+	suspend_message(SUSPEND_WRITER, SUSPEND_MEDIUM, 0,
+		"Stream %d beginning from position: chain %d. "
+			"range %p, block %ld.\n",
+		stream_number,
+		currentblockchain, currentblockrange, currentblockoffset);
+	
+	currentblocksperpage = get_blocks_per_page(currentblockchain);
+
+	swapwriter_page_index = 1;
+
+	suspend_bio_ops.reset_io_stats();
+
+	readahead_index = readahead_submit_index = -1;
+	readahead_allocs = readahead_frees = 0;
+
+	return 0;
+}
+
+static int swapwriter_begin_read_chunk(struct page * page, 
+		int readahead_index, int sync)
+{
+	int i;
+	struct submit_params submit_params;
+
+	if (currentblockchain == MAX_SWAPFILES) {
+		/* Readahead might ask us to read too many blocks */
+		printk("Currentblockchain == MAX_SWAPFILES. Begin_read_chunk returning -ENODATA.\n");
+		return -ENODATA;
+	}
+
+	if (!currentblockrange) {
+		do {
+			currentblockchain++;
+		} while ((!header_data.block_chain[currentblockchain].first) &&
+				(currentblockchain < MAX_SWAPFILES));
+
+		/* We can validly not have a new blockrange. We
+		 * might have allocated exactly the right amount
+		 * of swap for the image and be reading the last
+		 * block now.
+		 */
+
+		if (currentblockchain == MAX_SWAPFILES) {
+			prepare_status(1, 0,
+			  "Currentblockchain == MAX_SWAPFILES and "
+			  "more data to be read. "
+			  "Begin_read_chunk returning -ENOSPC.");
+			return -ENOSPC;
+		}
+				
+		currentblockrange =
+		  header_data.block_chain[currentblockchain].first;
+		currentblockoffset = currentblockrange->minimum;
+		currentblocksperpage = get_blocks_per_page(currentblockchain);
+	}
+	
+	submit_params.readahead_index = readahead_index;
+	submit_params.page = page;
+	submit_params.dev = swap_info[currentblockchain].bdev;
+	submit_params.blocks_used = currentblocksperpage;
+		
+	/* Get the blocks. There is no chance that they span chains. */
+	for (i = 0; i < currentblocksperpage; i++) {
+		submit_params.blocks[i] = currentblockoffset;
+		GET_RANGE_NEXT(currentblockrange, currentblockoffset);
+	}
+
+	suspend_message(SUSPEND_WRITER, SUSPEND_HIGH, 0,
+		"Reading page %d. Dev is %x. Block is %lu. "
+		"Blocksperpage is %d. Page is %p(%lx). Readahead index is %d.",
+		swapwriter_page_index,
+		submit_params.dev,
+		submit_params.blocks[0],
+		currentblocksperpage, 
+		page, page_address(page),
+		readahead_index);
+		
+	suspend_message(SUSPEND_PAGESETS, SUSPEND_VERBOSE, 1,
+		"page:%d. bdev:%x. blocks (%d):",
+		swapwriter_page_index,
+		submit_params.dev->bd_dev,
+		submit_params.blocks_used);
+
+	for (i = 0; i < currentblocksperpage; i++)
+		suspend_message(SUSPEND_PAGESETS, SUSPEND_VERBOSE, 0,
+			"0x%lx%s",
+			submit_params.blocks[i],
+			((i+1) < currentblocksperpage) ? "," : "\n");
+
+	check_shift_keys(0, NULL);
+
+	if ((i = suspend_bio_ops.submit_io(READ, &submit_params, sync)))
+		return -EPERM;
+
+	swapwriter_page_index++;
+
+	check_shift_keys(0, NULL);
+
+	return 0;
+}
+
+/* Note that we ignore the sync parameter. We are implementing
+ * read ahead, and will always wait until our readhead buffer has
+ * been read before returning.
+ */
+
+static int swapwriter_read_chunk(struct page * buffer_page, int sync)
+{
+	static int last_result;
+	unsigned long * virt;
+
+	suspend_message(SUSPEND_WRITER, SUSPEND_HIGH, 0,
+			"At entrance to swapwriter_read_chunk.\n");
+
+	if (sync == SUSPEND_ASYNC)
+		return swapwriter_begin_read_chunk(buffer_page, -1, sync);
+
+	/* Start new readahead while we wait for our page */
+	if (readahead_index == -1) {
+		last_result = 0;
+		readahead_index = readahead_submit_index = 0;
+	}
+
+	/* Start a new readahead? */
+	if (last_result) {
+		/* We failed to submit a read, and have cleaned up
+		 * all the readahead previously submitted */
+		if (readahead_submit_index == readahead_index)
+			return -EPERM;
+		goto wait;
+	}
+	
+	do {
+		if ((test_suspend_state(SUSPEND_USE_MEMORY_POOL)) && (suspend_memory_pool_level(1) < 50))
+			break;
+
+		if (suspend_bio_ops.prepare_readahead(readahead_submit_index))
+			break;
+
+		readahead_allocs++;
+
+		suspend_message(SUSPEND_WRITER, SUSPEND_HIGH, 0,
+			"\nBeginning new readahead %d.\n",
+			readahead_submit_index);
+
+		last_result = swapwriter_begin_read_chunk(
+			suspend_bio_ops.readahead_pages[readahead_submit_index], 
+			readahead_submit_index, SUSPEND_ASYNC);
+		if (last_result) {
+			printk("Begin read chunk for page %d returned %d.\n",
+				readahead_submit_index, last_result);
+			suspend_bio_ops.cleanup_readahead(readahead_submit_index);
+			break;
+		}
+
+		readahead_submit_index++;
+
+		if (readahead_submit_index == max_async_ios)
+			readahead_submit_index = 0;
+
+	} while((!last_result) && (readahead_submit_index != readahead_index) &&
+			(!suspend_bio_ops.readahead_ready(readahead_index)));
+
+wait:
+	suspend_bio_ops.wait_on_readahead(readahead_index);
+
+	virt = kmap_atomic(buffer_page, KM_USER1);
+	suspend_message(SUSPEND_WRITER, SUSPEND_HIGH, 0,
+		"Returned result of readahead %d,"
+		" Copying data from %p to %p.\n", readahead_index,
+		page_address(suspend_bio_ops.readahead_pages[readahead_index]),
+		virt);
+
+	memcpy(virt, page_address(suspend_bio_ops.readahead_pages[readahead_index]),
+			PAGE_SIZE);
+	kunmap_atomic(virt, KM_USER1);
+
+	suspend_bio_ops.cleanup_readahead(readahead_index);
+
+	readahead_frees++;
+
+	readahead_index++;
+	if (readahead_index == max_async_ios)
+		readahead_index = 0;
+
+	return 0;
+}
+
+static int swapwriter_read_cleanup(void)
+{
+	suspend_bio_ops.finish_all_io();
+	while (readahead_index != readahead_submit_index) {
+		suspend_bio_ops.cleanup_readahead(readahead_index);
+		readahead_frees++;
+		readahead_index++;
+		if (readahead_index == max_async_ios)
+			readahead_index = 0;
+	}
+	suspend_bio_ops.check_io_stats();
+	BUG_ON(readahead_allocs != readahead_frees);
+	return 0;
+}
+
+extern unsigned int nr_suspends;
+
+/* swapwriter_invalidate_image
+ * 
+ */
+static int swapwriter_invalidate_image(void)
+{
+	union p_diskpage cur;
+	int result = 0;
+	char newsig[11];
+	
+	cur.address = get_zeroed_page(GFP_ATOMIC);
+	if (!cur.address) {
+		printk("Unable to allocate a page for restoring the swap signature.\n");
+		return -ENOMEM;
+	}
+
+	suspend_store_free_mem(SUSPEND_FREE_INVALIDATE_IMAGE, 0);
+
+	/*
+	 * If nr_suspends == 0, we must be booting, so no swap pages
+	 * will be recorded as used yet.
+	 */
+
+	if (nr_suspends > 0)
+		swapwriter_release_storage();
+
+	/* 
+	 * We don't do a sanity check here: we want to restore the swap 
+	 * whatever version of kernel made the suspend image.
+	 * 
+	 * We need to write swap, but swap may not be enabled so
+	 * we write the device directly
+	 */
+	
+	suspend_bio_ops.bdev_page_io(READ, resume_block_device,
+			resume_firstblock, virt_to_page(cur.pointer));
+
+	result = parse_signature(cur.pointer->swh.magic.magic, 1);
+		
+	if (result < 4)
+		goto out;
+
+	strncpy(newsig, cur.pointer->swh.magic.magic, 10);
+	newsig[10] = 0;
+	suspend_message(SUSPEND_ANY_SECTION, SUSPEND_VERBOSE, 0,
+			"Swap signature will be set to %s.\n", newsig);
+
+	suspend_bio_ops.bdev_page_io(WRITE, resume_block_device, resume_firstblock,
+			virt_to_page(cur.pointer));
+
+	if (!nr_suspends)
+		printk(KERN_WARNING name_suspend "Image invalidated.\n");
+out:
+	suspend_bio_ops.finish_all_io();
+	free_pages(cur.address, 0);
+	suspend_store_free_mem(SUSPEND_FREE_INVALIDATE_IMAGE, 1);
+	return 0;
+}
+
+/*
+ * workspace_size
+ *
+ * Description:
+ * Returns the number of bytes of RAM needed for this
+ * code to do its work. (Used when calculating whether
+ * we have enough memory to be able to suspend & resume).
+ *
+ */
+static unsigned long swapwriter_memory_needed(void)
+{
+	return 1;
+}
+
+/* Print debug info
+ *
+ * Description:
+ */
+
+static int swapwriter_print_debug_stats(char * buffer, int size)
+{
+	int len = 0;
+	struct sysinfo sysinfo;
+	
+	if (active_writer != &swapwriterops) {
+		len = suspend_snprintf(buffer, size, "- Swapwriter inactive.\n");
+		return len;
+	}
+
+	len = suspend_snprintf(buffer, size, "- Swapwriter active.\n");
+	if (swapfilename[0])
+		len+= suspend_snprintf(buffer+len, size-len,
+			"  Attempting to automatically swapon: %s.\n", swapfilename);
+
+	si_swapinfo(&sysinfo);
+	
+	len+= suspend_snprintf(buffer+len, size-len, "  Swap available for image: %ld pages.\n",
+			sysinfo.freeswap + swapwriter_storage_allocated());
+
+	return len;
+}
+
+/*
+ * Storage needed
+ *
+ * Returns amount of space in the swap header required
+ * for the swapwriter's data. This ignores the links between
+ * pages, which we factor in when allocating the space.
+ *
+ * We ensure the space is allocated, but actually save the
+ * data from write_header_init and therefore don't also define a
+ * save_config_info routine.
+ */
+static unsigned long swapwriter_storage_needed(void)
+{
+	return sizeof(header_data);
+}
+
+/*
+ * Image_exists
+ *
+ */
+
+static int swapwriter_image_exists(void)
+{
+	int signature_found;
+	union p_diskpage diskpage;
+	
+	if (!resume_device) {
+		printk("Not even trying to read header because resume_device is not set.\n");
+		return 0;
+	}
+	
+	//PRINTFREEMEM("at start of swapwriter_image_exists.");
+
+	diskpage.address = get_zeroed_page(GFP_ATOMIC);
+
+	/* FIXME: Make sure bdev_page_io handles wrong parameters */
+	suspend_bio_ops.bdev_page_io(READ, resume_block_device, resume_firstblock, virt_to_page(diskpage.ptr));
+	suspend_bio_ops.finish_all_io();
+	signature_found = parse_signature(diskpage.pointer->swh.magic.magic, 0);
+
+	if (signature_found < 2) {
+		printk(KERN_ERR name_suspend "This is normal swap space.\n" );
+		return 0;	/* non fatal error */
+	} else if (signature_found == -1) {
+		printk(KERN_ERR name_suspend "Unable to find a signature. Could you have moved a swap file?\n");
+		return 0;
+	} else if (signature_found < 6) {
+		if ((!(test_suspend_state(SUSPEND_NORESUME_SPECIFIED)))
+				&& suspend_early_boot_message(1, "Detected the signature of an alternate implementation.\n"))
+			set_suspend_state(SUSPEND_NORESUME_SPECIFIED);
+		return 0;
+	} else if ((signature_found >> 1) != SIGNATURE_VER) {
+		if ((!(test_suspend_state(SUSPEND_NORESUME_SPECIFIED))) &&
+				suspend_early_boot_message(1, "Found a different style suspend image signature."))
+			set_suspend_state(SUSPEND_NORESUME_SPECIFIED);
+	}
+
+	return 1;
+}
+
+/*
+ * Mark resume attempted.
+ *
+ * Record that we tried to resume from this image.
+ */
+
+static void swapwriter_mark_resume_attempted(void)
+{
+	union p_diskpage diskpage;
+	int signature_found;
+	
+	if (!resume_device) {
+		printk("Not even trying to record attempt at resuming"
+				" because resume_device is not set.\n");
+		return;
+	}
+	
+	diskpage.address = get_zeroed_page(GFP_ATOMIC);
+
+	/* FIXME: Make sure bdev_page_io handles wrong parameters */
+	suspend_bio_ops.bdev_page_io(READ, resume_block_device, resume_firstblock, virt_to_page(diskpage.ptr));
+	signature_found = parse_signature(diskpage.pointer->swh.magic.magic, 0);
+
+	switch (signature_found) {
+		case 12:
+		case 13:
+			diskpage.pointer->swh.magic.magic[5] |= 0x80;
+			break;
+	}
+	
+	suspend_bio_ops.bdev_page_io(WRITE, resume_block_device, resume_firstblock,
+			virt_to_page(diskpage.ptr));
+	suspend_bio_ops.finish_all_io();
+	free_pages(diskpage.address, 0);
+	return;
+}
+
+/*
+ * Parse Image Location
+ *
+ * Attempt to parse a resume2= parameter.
+ * Swap Writer accepts:
+ * resume2=swap:DEVNAME[:FIRSTBLOCK][@BLOCKSIZE]
+ *
+ * Where:
+ * DEVNAME is convertable to a dev_t by name_to_dev_t
+ * FIRSTBLOCK is the location of the first block in the swap file
+ * (specifying for a swap partition is nonsensical but not prohibited).
+ * BLOCKSIZE is the logical blocksize >= 512 & <= PAGE_SIZE, 
+ * mod 512 == 0 of the device.
+ * Data is validated by attempting to read a swap header from the
+ * location given. Failure will result in swapwriter refusing to
+ * save an image, and a reboot with correct parameters will be
+ * necessary.
+ */
+
+static int swapwriter_parse_image_location(char * commandline, int only_writer)
+{
+	char *thischar, *devstart = NULL, *colon = NULL, *at_symbol = NULL;
+	union p_diskpage diskpage;
+	int signature_found;
+
+	CLEAR_RESULT_STATE(SUSPEND_ABORTED);
+
+	if (strncmp(commandline, "swap:", 5)) {
+		if (!only_writer) {
+			printk(name_suspend "Swapwriter: Image location doesn't begin with 'swap:'\n");
+			return 1;
+		}
+	} else
+		commandline += 5;
+
+	devstart = thischar = commandline;
+	while ((*thischar != ':') && ((thischar - commandline) < 250) && (*thischar))
+		thischar++;
+
+	if (*thischar == ':') {
+		colon = thischar;
+		*colon = 0;
+		thischar++;
+	}
+
+	while ((*thischar != '@') && ((thischar - commandline) < 250) && (*thischar))
+		thischar++;
+
+	if (*thischar == '@') {
+		at_symbol = thischar;
+		*at_symbol = 0;
+	}
+	
+	if (colon)
+		resume_firstblock = (int) simple_strtoul(colon + 1, NULL, 0);
+	else
+		resume_firstblock = 0;
+	printk("Looking for first block of swap header at block %x.\n", resume_firstblock);
+
+	if (at_symbol) {
+		resume_firstblocksize = (int) simple_strtoul(at_symbol + 1, NULL, 0);
+		if (resume_firstblocksize & 0x1FF)
+			printk("Blocksizes are usually a multiple of 512. Don't expect this to work!\n");
+	} else
+		resume_firstblocksize = 4096;
+	printk("Setting logical block size of resume device to %d.\n", resume_firstblocksize);
+	
+	if (try_to_parse_resume_device(devstart))
+		goto invalid;
+
+	if (colon)
+		*colon = ':';
+	if (at_symbol)
+		*at_symbol = '@';
+
+	if ((suspend_bio_ops.get_block_size(resume_block_device) 
+				!= resume_firstblocksize) &&
+	    (suspend_bio_ops.set_block_size(resume_block_device, resume_firstblocksize)
+	    			 == -EINVAL))
+		goto invalid;
+
+	diskpage.address = get_zeroed_page(GFP_ATOMIC);
+	if (suspend_bio_ops.bdev_page_io(READ, resume_block_device, resume_firstblock, virt_to_page(diskpage.ptr))) {
+		printk(KERN_ERR name_suspend "Failed to submit I/O.\n");
+		return -EINVAL;
+	}
+	suspend_bio_ops.finish_all_io();
+	signature_found = parse_signature(diskpage.pointer->swh.magic.magic, 0);
+	free_page((unsigned long) diskpage.address);
+
+	if (signature_found != -1) {
+		printk(KERN_ERR name_suspend "Swap space signature found.\n");
+		return 0;
+	}
+
+	printk(KERN_ERR name_suspend "Sorry. No swap signature found at specified location.\n");
+	return -EINVAL;
+
+invalid:
+	if (colon)
+		*colon = ':';
+	if (at_symbol)
+		*at_symbol = '@';
+	printk(KERN_ERR name_suspend "Sorry. Location looks invalid.\n");
+	return -EINVAL;
+}
+
+int header_locations_read_proc(char * page, char ** start, off_t off, int count,
+		int *eof, void *data)
+{
+	int i, printedpartitionsmessage = 0, len = 0, haveswap = 0, device_block_size;
+	struct inode *swapf = 0;
+	int zone;
+	char * path_page = (char *) __get_free_page(GFP_KERNEL);
+	char * path;
+	int path_len;
+	
+	*eof = 1;
+	if (!page)
+		return 0;
+
+	for (i = 0; i < MAX_SWAPFILES; i++) {
+		if (!swap_info[i].swap_file)
+			continue;
+		
+		if (S_ISBLK(swap_info[i].swap_file->f_dentry->d_inode->i_mode)) {
+			haveswap = 1;
+			if (!printedpartitionsmessage) {
+				len += sprintf(page + len, 
+					"For swap partitions, simply use the format: resume2=swap:/dev/hda1.\n");
+				printedpartitionsmessage = 1;
+			}
+		} else {
+			path_len = 0;
+			
+			path = get_path_for_swapfile(i, path_page);
+			path_len = sprintf(path_page, "%-31s ", path);
+			
+			haveswap = 1;
+			swapf = swap_info[i].swap_file->f_dentry->d_inode;
+			device_block_size = block_size(swap_info[i].bdev);
+			if (!(zone = bmap(swapf,0))) {
+				len+= sprintf(page + len, 
+					"Swapfile %-31s has been corrupted. Reuse mkswap on it and try again.\n",
+					path_page);
+			} else {
+				len+= sprintf(page + len, "For swapfile `%s`, use resume2=swap:/dev/<partition name>:0x%x@%d.\n",
+						path_page,
+						zone, device_block_size);
+			}
+
+		}
+	}
+	
+	if (!haveswap)
+		len = sprintf(page, "You need to turn on swap partitions before examining this file.\n");
+
+	free_pages((unsigned long) path_page, 0);
+	return len;
+}
+
+extern int attempt_to_parse_resume_device(void);
+
+static struct suspend_proc_data swapwriter_proc_data[] = {
+	{
+	 .filename			= "swapfilename",
+	 .permissions			= PROC_RW,
+	 .type				= SUSPEND_PROC_DATA_STRING,
+	 .data = {
+		.string = {
+			.variable	= swapfilename,
+			.max_length	= 255,
+		}
+	 }
+	},
+
+	{
+	 .filename			= "headerlocations",
+	 .permissions			= PROC_READONLY,
+	 .type				= SUSPEND_PROC_DATA_CUSTOM,
+	 .data = {
+		 .special = {
+			.read_proc 	= header_locations_read_proc,
+		}
+	 }
+	},
+
+	{ .filename			= "disable_swapwriter",
+	  .permissions			= PROC_RW,
+	  .type				= SUSPEND_PROC_DATA_INTEGER,
+	  .data = {
+		.integer = {
+			.variable	= &swapwriterops.disabled,
+			.minimum	= 0,
+			.maximum	= 1,
+		}
+	  },
+	  .write_proc = attempt_to_parse_resume_device,
+	}
+};
+
+static struct suspend_plugin_ops swapwriterops = {
+	.type					= WRITER_PLUGIN,
+	.name					= "Swap Writer",
+	.memory_needed				= swapwriter_memory_needed,
+	.print_debug_info			= swapwriter_print_debug_stats,
+	.storage_needed				= swapwriter_storage_needed,
+	.initialise				= swapwriter_initialise,
+	.cleanup				= swapwriter_cleanup,
+	.dpm_set_devices			= swapwriter_dpm_set_devices,
+	.ops = {
+		.writer = {
+		 .write_init		= swapwriter_write_init,
+		 .write_chunk		= swapwriter_write_chunk,
+		 .write_cleanup		= swapwriter_write_cleanup,
+		 .read_init		= swapwriter_read_init,
+		 .read_chunk		= swapwriter_read_chunk,
+		 .read_cleanup		= swapwriter_read_cleanup,
+		 .noresume_reset	= swapwriter_noresume_reset,
+		 .storage_available 	= swapwriter_storage_available,
+		 .storage_allocated	= swapwriter_storage_allocated,
+		 .release_storage	= swapwriter_release_storage,
+		 .allocate_header_space	= swapwriter_allocate_header_space,
+		 .allocate_storage	= swapwriter_allocate_storage,
+		 .image_exists		= swapwriter_image_exists,
+		 .mark_resume_attempted	= swapwriter_mark_resume_attempted,
+		 .write_header_init	= swapwriter_write_header_init,
+		 .write_header_chunk	= swapwriter_write_header_chunk,
+		 .write_header_cleanup	= swapwriter_write_header_cleanup,
+		 .read_header_init	= swapwriter_read_header_init,
+		 .read_header_chunk	= swapwriter_read_header_chunk,
+		 .read_header_cleanup	= swapwriter_read_header_cleanup,
+		 .prepare_save_ranges	= swapwriter_prepare_save_ranges,
+		 .post_load_ranges	= swapwriter_post_load_ranges,
+		 .invalidate_image	= swapwriter_invalidate_image,
+		 .parse_image_location	= swapwriter_parse_image_location,
+		}
+	}
+};
+
+/* ---- Registration ---- */
+static __init int swapwriter_load(void)
+{
+	int result;
+	int i, numfiles = sizeof(swapwriter_proc_data) / sizeof(struct suspend_proc_data);
+	
+	if (!(result = suspend_register_plugin(&swapwriterops))) {
+		printk("Software Suspend Swap Writer registered.\n");
+
+		for (i=0; i< numfiles; i++)
+			suspend_register_procfile(&swapwriter_proc_data[i]);
+	}
+	return result;
+}
+
+#ifdef MODULE
+static __exit void swapwriter_unload(void)
+{
+	int i, numfiles = sizeof(swapwriter_proc_data) / sizeof(struct suspend_proc_data);
+
+	printk("Software Suspend Swap Writer unloading.\n");
+
+	for (i=0; i< numfiles; i++)
+		suspend_unregister_procfile(&swapwriter_proc_data[i]);
+	suspend_unregister_plugin(&swapwriterops);
+}
+
+module_init(swapwriter_load);
+module_exit(swapwriter_unload);
+MODULE_LICENSE("GPL");
+MODULE_AUTHOR("Nigel Cunningham");
+MODULE_DESCRIPTION("Suspend2 swap writer");
+#else
+late_initcall(swapwriter_load);
+#endif
#233 lore raw

Re: Suspend 2 merge: 48/51: Swapwriter

Hi!

Quoted 7 lines

This is the swapwriter. It is forms the glue between the highlevel I/O routines in io.c and the blockwriter routines in block_io.c. It is responsible for allocating storage, translating the requests for pages within pagesets into devices and blocks and the like. It is abstracted from the block writer because the plan is that we'll eventually have a generic file writer (ie not using swapspace, but a simple file, possibly

This file alone is bigger than whole swsusp1. That strongly suggests you have too many layers of abstraction in there. Planning for future is nice, but not at this cost.

Pavel

Signature · 2 lines
People were complaining that M$ turns users into beta-testers...
...jr ghea gurz vagb qrirybcref, naq gurl frrz gb yvxr vg gung jnl!
#234 lore raw

Re: Suspend 2 merge: 48/51: Swapwriter

Hi.

Quoted 10 lines · Pavel Machek

Hi!

Quoted 7 lines

This is the swapwriter. It is forms the glue between the highlevel I/O routines in io.c and the blockwriter routines in block_io.c. It is responsible for allocating storage, translating the requests for pages within pagesets into devices and blocks and the like. It is abstracted from the block writer because the plan is that we'll eventually have a generic file writer (ie not using swapspace, but a simple file, possibly

Quoted 3 lines

This file alone is bigger than whole swsusp1. That strongly suggests you have too many layers of abstraction in there. Planning for future is nice, but not at this cost.

Not necessarily too many layers of abstraction. It includes swapfile support and there's a bit in there for readahead (plus the debugging you mentioned).

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
#235 lore raw

Suspend 2 merge: 46/51: LZF support.

In reply to Nigel Cunningham

This is LZF support, contributed under a dual license (see below) by Marc Lehmann. It flies! (Those stats in the debug info in an earlier patch were real!).

kernel/power/lzf/lzf_c.c +220 -0
diff -ruN 852-lzf-old/kernel/power/lzf/lzf_c.c 852-lzf-new/kernel/power/lzf/lzf_c.c
@@ -0,0 +1,220 @@
+/*
+ * Copyright (c) 2000-2003 Marc Alexander Lehmann <[email protected]>
+ * 
+ * Redistribution and use in source and binary forms, with or without modifica-
+ * tion, are permitted provided that the following conditions are met:
+ * 
+ *   1.  Redistributions of source code must retain the above copyright notice,
+ *       this list of conditions and the following disclaimer.
+ * 
+ *   2.  Redistributions in binary form must reproduce the above copyright
+ *       notice, this list of conditions and the following disclaimer in the
+ *       documentation and/or other materials provided with the distribution.
+ * 
+ *   3.  The name of the author may not be used to endorse or promote products
+ *       derived from this software without specific prior written permission.
+ * 
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MER-
+ * CHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO
+ * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPE-
+ * CIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
+ * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTH-
+ * ERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * the GNU General Public License version 2 (the "GPL"), in which case the
+ * provisions of the GPL are applicable instead of the above. If you wish to
+ * allow the use of your version of this file only under the terms of the
+ * GPL and not to allow others to use your version of this file under the
+ * BSD license, indicate your decision by deleting the provisions above and
+ * replace them with the notice and other provisions required by the GPL. If
+ * you do not delete the provisions above, a recipient may use your version
+ * of this file under either the BSD or the GPL.
+ */
+
+#define HSIZE (1 << (HLOG))
+
+/*
+ * don't play with this unless you benchmark!
+ * decompression is not dependent on the hash function
+ * the hashing function might seem strange, just believe me
+ * it works ;)
+ */
+#define FRST(p) (((p[0]) << 8) + p[1])
+#define NEXT(v,p) (((v) << 8) + p[2])
+#define IDX(h) ((((h ^ (h << 5)) >> (3*8 - HLOG)) + h*3) & (HSIZE - 1))
+/*
+ * IDX works because it is very similar to a multiplicative hash, e.g.
+ * (h * 57321 >> (3*8 - HLOG))
+ * the next one is also quite good, albeit slow ;)
+ * (int)(cos(h & 0xffffff) * 1e6)
+ */
+
+#if 0
+/* original lzv-like hash function */
+# define FRST(p) (p[0] << 5) ^ p[1]
+# define NEXT(v,p) ((v) << 5) ^ p[2]
+# define IDX(h) ((h) & (HSIZE - 1))
+#endif
+
+#define        MAX_LIT        (1 <<  5)
+#define        MAX_OFF        (1 << 13)
+#define        MAX_REF        ((1 <<  8) + (1 << 3))
+
+/*
+ * compressed format
+ *
+ * 000LLLLL <L+1>    ; literal
+ * LLLOOOOO oooooooo ; backref L
+ * 111OOOOO LLLLLLLL oooooooo ; backref L+7
+ *
+ */
+
+unsigned int
+lzf_compress (const void *const in_data, unsigned int in_len,
+	      void *out_data, unsigned int out_len, void *hbuf)
+{
+  const u8 **htab = hbuf;
+  const u8 **hslot;
+  const u8 *ip = (const u8 *)in_data;
+        u8 *op = (u8 *)out_data;
+  const u8 *in_end  = ip + in_len;
+        u8 *out_end = op + out_len;
+  const u8 *ref;
+
+  unsigned int hval = FRST (ip);
+  unsigned long off;
+           int lit = 0;
+
+#if INIT_HTAB
+# if USE_MEMCPY
+    memset (htab, 0, sizeof (htab));
+# else
+    for (hslot = htab; hslot < htab + HSIZE; hslot++)
+      *hslot++ = ip;
+# endif
+#endif
+
+  for (;;)
+    {
+      if (ip < in_end - 2)
+        {
+          hval = NEXT (hval, ip);
+          hslot = htab + IDX (hval);
+          ref = *hslot; *hslot = ip;
+
+          if (1
+#if INIT_HTAB && !USE_MEMCPY
+              && ref < ip /* the next test will actually take care of this, but this is faster */
+#endif
+              && (off = ip - ref - 1) < MAX_OFF
+              && ip + 4 < in_end
+              && ref > (u8 *)in_data
+#if STRICT_ALIGN
+              && ref[0] == ip[0]
+              && ref[1] == ip[1]
+              && ref[2] == ip[2]
+#else
+              && *(u16 *)ref == *(u16 *)ip
+              && ref[2] == ip[2]
+#endif
+            )
+            {
+              /* match found at *ref++ */
+              unsigned int len = 2;
+              unsigned int maxlen = in_end - ip - len;
+              maxlen = maxlen > MAX_REF ? MAX_REF : maxlen;
+
+              do
+                len++;
+              while (len < maxlen && ref[len] == ip[len]);
+
+              if (op + lit + 1 + 3 >= out_end)
+                return 0;
+
+              if (lit)
+                {
+                  *op++ = lit - 1;
+                  lit = -lit;
+                  do
+                    *op++ = ip[lit];
+                  while (++lit);
+                }
+
+              len -= 2;
+              ip++;
+
+              if (len < 7)
+                {
+                  *op++ = (off >> 8) + (len << 5);
+                }
+              else
+                {
+                  *op++ = (off >> 8) + (  7 << 5);
+                  *op++ = len - 7;
+                }
+
+              *op++ = off;
+
+#if ULTRA_FAST
+              ip += len;
+              hval = FRST (ip);
+              hval = NEXT (hval, ip);
+              htab[IDX (hval)] = ip;
+              ip++;
+#else
+              do
+                {
+                  hval = NEXT (hval, ip);
+                  htab[IDX (hval)] = ip;
+                  ip++;
+                }
+              while (len--);
+#endif
+              continue;
+            }
+        }
+      else if (ip == in_end)
+        break;
+
+      /* one more literal byte we must copy */
+      lit++;
+      ip++;
+
+      if (lit == MAX_LIT)
+        {
+          if (op + 1 + MAX_LIT >= out_end)
+            return 0;
+
+          *op++ = MAX_LIT - 1;
+#if USE_MEMCPY
+          memcpy (op, ip - MAX_LIT, MAX_LIT);
+          op += MAX_LIT;
+          lit = 0;
+#else
+          lit = -lit;
+          do
+            *op++ = ip[lit];
+          while (++lit);
+#endif
+        }
+    }
+
+  if (lit)
+    {
+      if (op + lit + 1 >= out_end)
+	return 0;
+
+      *op++ = lit - 1;
+      lit = -lit;
+      do
+	*op++ = ip[lit];
+      while (++lit);
+    }
+
+  return op - (u8 *) out_data;
+}
kernel/power/lzf/lzf_d.c +98 -0

98 lines not on this page · raw message

kernel/power/suspend_lzf.c +554 -0

554 lines not on this page · raw message

#236 lore raw

Re: Suspend 2 merge: 46/51: LZF support.

Hi Nigel!

Shouldn't LZF code go to lib/ ?

Quoted 3 lines · Nigel Cunningham

This is LZF support, contributed under a dual license (see below) by Marc Lehmann. It flies! (Those stats in the debug info in an earlier patch were real!).

#237 lore raw

Re: Suspend 2 merge: 46/51: LZF support.

Hi.

Quoted 3 lines · Bartlomiej Zolnierkiewicz

Hi Nigel!

Shouldn't LZF code go to lib/ ?

I suppose it could. Will do.

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
#238 lore raw

Re: Suspend 2 merge: 46/51: LZF support.

Quoted 10 lines · Nigel Cunningham

Hi.

Quoted 3 lines · Bartlomiej Zolnierkiewicz

Hi Nigel!

Shouldn't LZF code go to lib/ ?

I suppose it could. Will do.

Regards,

=== include/linux/lzf.h
==================================================================

linux/lzf.h (revision 24483) renamed from linux/lzf.h (revision 24482) +7 -0
@@ -0,0 +1,7 @@
+#ifndef _LZF_H_
+#define _LZF_H_
+
+unsigned int lzf_decompress (const void *const in_data,  unsigned int in_len, void *out_data, unsigned int out_len);
+unsigned int lzf_compress (const void *const in_data, unsigned int in_len, void *out_data, unsigned int out_len, void *hbuf);
+
+#endif

=== lib/lzf_d.c
==================================================================

lzf_d.c (revision 24483) renamed from lzf_d.c (revision 24482) +98 -0

98 lines not on this page · raw message

=== lib/Kconfig
==================================================================

Kconfig (revision 24483) renamed from Kconfig (revision 24482) +3 -0
@@ -30,6 +30,9 @@
 	  require M here.  See Castagnoli93.
 	  Module will be libcrc32c.
 
+config LZF
+	tristate "LZF Compress/Decompress Support"
+
 #
 # compression support is select'ed if needed
 #

=== lib/lzf.c
==================================================================

lzf.c (revision 24483) renamed from lzf.c (revision 24482) +46 -0

46 lines not on this page · raw message

=== lib/Makefile
==================================================================

Makefile (revision 24483) renamed from Makefile (revision 24482) +3 -0
@@ -15,6 +15,7 @@
   lib-y += dec_and_lock.o
 endif
 
+
 obj-$(CONFIG_CRC_CCITT)	+= crc-ccitt.o
 obj-$(CONFIG_CRC32)	+= crc32.o
 obj-$(CONFIG_LIBCRC32C)	+= libcrc32c.o
@@ -23,6 +24,8 @@
 obj-$(CONFIG_ZLIB_INFLATE) += zlib_inflate/
 obj-$(CONFIG_ZLIB_DEFLATE) += zlib_deflate/
 
+obj-$(CONFIG_LZF) += lzf.o
+
 hostprogs-y	:= gen_crc32table
 clean-files	:= crc32table.h
 

=== lib/lzf_c.c
==================================================================

lzf_c.c (revision 24483) renamed from lzf_c.c (revision 24482) +220 -0

220 lines not on this page · raw message

Signature · 4 lines
--
Hu Gang / Steve
Linux Registered User 204016
GPG Public Key: http://soulinfo.com/~hugang/hugang.asc
#239 lore raw

Re: Suspend 2 merge: 46/51: LZF support.

Hi,

On Thursday 25 November 2004 01:32 am, [email protected] wrote:
....

Quoted 6 lines
lzf_c.c (revision 24483) renamed from lzf_c.c (revision 24482) +5 -0
+
+  if (lit)
+    {
+      if (op + lit + 1 >= out_end)
+	return 0;

lzf_c.c (revision 24483) line 220

Quoted 10 lines
lzf_c.c (revision 24483) renamed from lzf_c.c (revision 24482) +10 -0
+
+      *op++ = lit - 1;
+      lit = -lit;
+      do
+	*op++ = ip[lit];
+      while (++lit);
+    }
+
+  return op - (u8 *) out_data;
+}

Since this is a completely new file (as far as kernel tree is concerned) could you convert it to proper coding style (braces placement, identation)?

Signature · 1 line
Dmitry
#240 lore raw

Re: Suspend 2 merge: 46/51: LZF support.

Quoted 7 lines · Dmitry Torokhov

Hi,

On Thursday 25 November 2004 01:32 am, [email protected] wrote:
....

Since this is a completely new file (as far as kernel tree is concerned) could you convert it to proper coding style (braces placement, identation)?

Lindent lib/lzf*.c include/linux/lzf*.h

=== include/linux/lzf.h
==================================================================

linux/lzf.h (revision 24489) renamed from linux/lzf.h (revision 24480) +10 -0
@@ -0,0 +1,10 @@
+#ifndef _LZF_H_
+#define _LZF_H_
+
+unsigned int lzf_decompress (const void *const in_data,  unsigned int in_len, void *out_data, unsigned int out_len);
+unsigned int lzf_compress (const void *const in_data, unsigned int in_len, void *out_data, unsigned int out_len, void *hbuf);
+
+char *lzf_new(void);
+void lzf_free(char *);
+
+#endif

=== lib/lzf_d.c
==================================================================

lzf_d.c (revision 24489) renamed from lzf_d.c (revision 24480) +94 -0

94 lines not on this page · raw message

=== lib/Kconfig
==================================================================

Kconfig (revision 24489) renamed from Kconfig (revision 24480) +3 -0
@@ -30,6 +30,9 @@
 	  require M here.  See Castagnoli93.
 	  Module will be libcrc32c.
 
+config LZF
+	tristate "LZF Compress/Decompress Support"
+
 #
 # compression support is select'ed if needed
 #

=== lib/lzf.c
==================================================================

lzf.c (revision 24489) renamed from lzf.c (revision 24480) +61 -0

61 lines not on this page · raw message

=== lib/Makefile
==================================================================

Makefile (revision 24489) renamed from Makefile (revision 24480) +3 -0
@@ -15,6 +15,7 @@
   lib-y += dec_and_lock.o
 endif
 
+
 obj-$(CONFIG_CRC_CCITT)	+= crc-ccitt.o
 obj-$(CONFIG_CRC32)	+= crc32.o
 obj-$(CONFIG_LIBCRC32C)	+= libcrc32c.o
@@ -23,6 +24,8 @@
 obj-$(CONFIG_ZLIB_INFLATE) += zlib_inflate/
 obj-$(CONFIG_ZLIB_DEFLATE) += zlib_deflate/
 
+obj-$(CONFIG_LZF) += lzf.o
+
 hostprogs-y	:= gen_crc32table
 clean-files	:= crc32table.h
 

=== lib/lzf_c.c
==================================================================

lzf_c.c (revision 24489) renamed from lzf_c.c (revision 24480) +209 -0

209 lines not on this page · raw message

--
Hu Gang / Steve
Linux Registered User 204016
GPG Public Key: http://soulinfo.com/~hugang/hugang.asc

#241 lore raw

Re: Suspend 2 merge: 46/51: LZF support.

In reply to Dmitry Torokhov
Quoted 2 lines

Since this is a completely new file (as far as kernel tree is concerned) could you convert it to proper coding style (braces placement, identation)?

While I'm normally a big advocate of sane indentation it looks like these two files are taken unmodified from some external library and are unlike to be modified. Maybe keep them as is to ease a possible future resync (and comparisms with upstream) ?

#242 lore raw

Suspend 2 merge: 44/51: Text UI plugin.

In reply to Nigel Cunningham

Here's our plugin that is used to display text output on the console. When the console loglevel is 0 or 1, the user gets a nice progress bar. Higher levels display increasing levels of debugging output.

kernel/power/suspend_text.c +629 -0
diff -ruN 850-text-ui-old/kernel/power/suspend_text.c 850-text-ui-new/kernel/power/suspend_text.c
@@ -0,0 +1,629 @@
+/*
+ * kernel/power/suspend2_text_display.c
+ *
+ * Copyright (C) 2002-2004 Nigel Cunningham <[email protected]>
+ *
+ * This file is released under the GPLv2.
+ *
+ * Routines for Software Suspend's user interface.
+ * 
+ * The user interface includes support for a text mode 'nice display'.
+ *
+ * The 'nice display' is text based and implements a progress bar and
+ * (optional) textual progress, as well as an overall description of
+ * the current action and the display of a header and the code version.
+ *
+ * It uses /dev/console, and thus also works on a serial console.
+ */
+#define SUSPEND_TEXT_MODE_C
+
+//#define __KERNEL_SYSCALLS__
+
+#include <linux/suspend.h>
+#include <linux/console.h>
+#include <linux/selection.h>
+#include <linux/tty.h>
+#include <linux/vt_kern.h>
+ 
+#include "plugins.h"
+#include "proc.h"
+#include "suspend.h"
+
+/*
+ * The original macros use currcons, which we don't have access to.
+ */
+#undef video_num_columns
+#define video_num_columns	(vc_cons[fg_console].d->vc_cols)
+#undef video_num_lines
+#define video_num_lines		(vc_cons[fg_console].d->vc_rows)
+
+static int barwidth = 0, barposn = -1, newbarposn = 0;
+static int draw_progress_bar = 1;
+static char print_buf[1024];	/* Same as printk - should be safe */
+
+/* We remember the last header that was (or could have been) displayed for
+ * use during log level switches */
+static char lastheader[512];
+static int lastheader_message_len = 0;
+
+static void hide_cursor(void);
+static void unblank_screen_via_file(void);
+
+static int suspend_console_fd = -1;
+static struct termios termios;
+static int lastloglevel = -1;
+
+#ifdef CONFIG_DEVFS_FS
+static int mounted_devfs = 0;
+#endif
+
+#define cond_console_print(chars) \
+	if (suspend_console_fd > -1) { \
+		int count = strlen(chars); \
+		sys_write(suspend_console_fd, chars, count); \
+		hide_cursor(); \
+		unblank_screen_via_file();  \
+	}
+
+static void move_cursor_to(unsigned char * xy)
+{
+	char buf[10];
+	
+	snprintf(buf, 10, "\233%d;%dH", xy[1], xy[0]);
+	cond_console_print(buf);
+}
+
+static void clear_display(void)
+{
+	char buf[4] = "\2332J";
+	unsigned char home[2] = { 0, 0 };
+	
+	cond_console_print(buf);
+	move_cursor_to(home);
+}
+
+static void hide_cursor(void)
+{
+	char buf[6] = "\033[?1c";
+	if (suspend_console_fd > -1)
+		sys_write(suspend_console_fd, buf, 5);
+}
+
+static void restore_cursor(void)
+{
+	char buf[6] = "\033[?0c";
+	if (suspend_console_fd > -1)
+		sys_write(suspend_console_fd, buf, 5);
+}
+
+static void unblank_screen_via_file(void)
+{
+	char buf[6] = "\033[13]";
+	if (suspend_console_fd > -1)
+		sys_write(suspend_console_fd, buf, 5);
+}
+
+/* prepare_status
+ * Description:	Prepare the 'nice display', drawing the header and version,
+ * 		along with the current action and perhaps also resetting the
+ * 		progress bar.
+ * Arguments:	int printalways: Whether to print the action when debugging
+ * 		is on.
+ * 		int clearbar: Whether to reset the progress bar.
+ * 		const char *fmt, ...: The action to be displayed.
+ */
+static void text_prepare_status(int printalways, int clearbar, const char *fmt, va_list args)
+{
+	unsigned char posn[2];
+
+	if (fmt)
+		lastheader_message_len = vsnprintf(lastheader, 512, fmt, args);
+
+	if (console_loglevel >= SUSPEND_ERROR) {
+
+		if (printalways)
+			printk("\n** %s\n", lastheader);
+		return;
+	}
+	
+	barwidth = (video_num_columns - 2 * (video_num_columns / 4) - 2);
+
+	/* Print version */
+	posn[0] = (unsigned char) (0);
+	posn[1] = (unsigned char) (video_num_lines);
+	move_cursor_to(posn);
+	cond_console_print(SUSPEND_CORE_VERSION);
+
+	/* Print header */
+	posn[0] = (unsigned char) ((video_num_columns - 31) / 2);
+	posn[1] = (unsigned char) ((video_num_lines / 3) - 3);
+	move_cursor_to(posn);
+
+	cond_console_print("S O F T W A R E   S U S P E N D");
+		
+	/* Print action */
+	posn[1] = (unsigned char) (video_num_lines / 3);
+	posn[0] = (unsigned char) 0;
+	move_cursor_to(posn);
+	
+	/* Clear old message */
+	for (barposn = 0; barposn < video_num_columns; barposn++) 
+		cond_console_print(" ");
+
+	posn[0] = (unsigned char)
+		((video_num_columns - lastheader_message_len) / 2);
+	move_cursor_to(posn);
+	cond_console_print(lastheader);
+	
+	if (draw_progress_bar) {
+		/* Draw left bracket of progress bar. */
+		posn[0] = (unsigned char) (video_num_columns / 4);
+		posn[1]++;
+		move_cursor_to(posn);
+		cond_console_print("[");
+
+		/* Draw right bracket of progress bar. */
+		posn[0] = (unsigned char) 
+			(video_num_columns - (video_num_columns / 4) - 1);
+		move_cursor_to(posn);
+		cond_console_print("]");
+
+		if (clearbar) {
+			/* Position at start of progress */
+			posn[0] = (unsigned char) (video_num_columns / 4 + 1);
+			move_cursor_to(posn);
+
+			/* Clear bar */
+			for (barposn = 0; barposn < barwidth; barposn++)
+				cond_console_print(" ");
+			move_cursor_to(posn);
+		}
+	}
+	
+	hide_cursor();
+
+	barposn = 0;
+}
+
+/* text_loglevel_change
+ *
+ * Description:	Update the display when the user changes the log level.
+ * Returns:	Boolean indicating whether the level was changed.
+ */
+
+static void text_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 is the same as last time
+	 * we came in here */
+	barwidth = (video_num_columns - 2 * (video_num_columns / 4) - 2);
+	barposn = 0;
+
+	/* Only reset the display if we're switching between nice display
+	 * and displaying debugging output */
+	
+	if (console_loglevel >= SUSPEND_ERROR) {
+		char message[35];
+		if (lastloglevel < SUSPEND_ERROR)
+			clear_display();
+
+		snprintf(message, 35,
+			"Switched to console loglevel %d.\n", 
+			console_loglevel);
+		cond_console_print(message);
+
+		if (lastloglevel < SUSPEND_ERROR) {
+			cond_console_print(lastheader);
+			cond_console_print("\n");
+		}
+	
+	} else if (lastloglevel >= SUSPEND_ERROR) {
+		clear_display();
+	
+		/* Get the nice display or last action [re]drawn */
+		text_prepare_status(1, 0, NULL, NULL);
+	}
+	
+	lastloglevel = console_loglevel;
+}
+/* text_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 prepare_status with
+ * 		clearbar on.
+ * Returns:	Unsigned long: The next value where status needs to be updated.
+ * 		This is to reduce unnecessary calls to text_update_progress.
+ */
+unsigned long text_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;
+	unsigned char posn[2];
+	int message_len = 0;
+
+	if (!barwidth)
+		barwidth = (video_num_columns - 2 * (video_num_columns / 4) - 2);
+
+	if (!maximum)
+		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 ((console_loglevel >= SUSPEND_ERROR) || (!draw_progress_bar))
+		return next_update;
+
+	/* Update bar */
+	if (draw_progress_bar) {
+		posn[1] = (unsigned char) ((video_num_lines / 3) + 1);
+
+		/* Clear bar if at start */
+		if (!barposn) {
+			posn[0] = (unsigned char) (video_num_columns / 4 + 1);
+			move_cursor_to(posn);
+			for (; barposn < barwidth; barposn++)
+				cond_console_print(" ");
+			barposn = 0;
+		}
+		posn[0] = (unsigned char) (video_num_columns / 4 + 1 + barposn);
+		move_cursor_to(posn);
+
+		for (; barposn < newbarposn; barposn++)
+			cond_console_print("-");
+	}
+
+	/* Print string in progress bar on loglevel 1 */
+	if ((fmt) && (console_loglevel)) {
+		message_len = vsnprintf(print_buf, sizeof(print_buf), " ", NULL);
+		message_len += vsnprintf(print_buf + message_len,
+				sizeof(print_buf) - message_len, fmt, args);
+		message_len += vsnprintf(print_buf + message_len,
+				sizeof(print_buf) - message_len, " ", NULL);
+
+		if (message_len) {
+			posn[0] = (unsigned char)
+				((video_num_columns - message_len) / 2);
+			posn[1] = (unsigned char)
+				((video_num_lines / 3) + 1);
+			move_cursor_to(posn);
+			cond_console_print(print_buf);
+		}
+	}
+
+	barposn = newbarposn;
+	hide_cursor();
+	
+	return next_update;
+}
+
+extern asmlinkage long sys_ioctl(unsigned int fd, unsigned int cmd, 
+		unsigned long arg);
+
+static void text_message(unsigned long section, unsigned long level,
+		int normally_logged,
+		const char *fmt, va_list args)
+{
+	int printed_len = 0;
+
+	if ((section) && (!TEST_DEBUG_STATE(section)))
+		return;
+
+	if (level == SUSPEND_STATUS) {
+		text_prepare_status(1, 0, fmt, args);
+		return;
+	}
+	
+	if (level > console_loglevel)
+		return;
+
+	printed_len = vsnprintf(print_buf + printed_len,
+			sizeof(print_buf) - printed_len, fmt, args);
+
+
+	if ((TEST_ACTION_STATE(SUSPEND_LOGALL)) ||
+	    (normally_logged)) {
+		/* If we didn't print anything, don't do the \n anyway! */
+		if (!printed_len)
+			return;
+		printk(print_buf);
+	} else
+		cond_console_print(print_buf);
+}
+/*
+ *
+ */
+
+static void suspend_get_dev_console(void)
+{
+	if (suspend_console_fd > -1)
+		return;
+
+	suspend_console_fd = sys_open("/dev/console", O_RDWR | O_NONBLOCK, 0);
+	if (suspend_console_fd < 0) {
+		sys_mkdir("/dev", 0700);
+#ifdef CONFIG_DEVFS_FS
+		sys_mount("devfs", "/dev", "devfs", 0, NULL);
+		mounted_devfs = 1;
+#endif
+		suspend_console_fd = sys_open("/dev/console", O_RDWR | O_NONBLOCK, 0);
+	}
+	if (suspend_console_fd < 0) {
+		printk("Can't open /dev/console. Error value was %d.\n",
+				suspend_console_fd);
+		suspend_console_fd = -1;
+		return;
+	}
+
+	sys_ioctl(suspend_console_fd, TCGETS, (long)&termios);
+	termios.c_lflag &= ~ICANON;
+	sys_ioctl(suspend_console_fd, TCSETSF, (long)&termios);
+}
+
+/* prepare_console
+ *
+ */
+static void text_prepare_console(void)
+{
+	suspend_get_dev_console();
+
+	if (console_loglevel < 2)
+		clear_display();
+
+	lastloglevel = console_loglevel;
+}
+
+/* cleanup_console
+ *
+ * Description: Close our handle on /dev/console. Must be done
+ * earlier than pm_restore_console to avoid problems with other
+ * processes trying to grab it when thawed.
+ */
+
+static void cleanup_console(void)
+{
+	if (console_loglevel < 2)
+		clear_display();
+	restore_cursor();
+	termios.c_lflag |= ICANON;
+	sys_ioctl(suspend_console_fd, TCSETSF, (long)&termios);
+	sys_close(suspend_console_fd);
+	suspend_console_fd = -1;
+
+#ifdef CONFIG_DEVFS_FS
+	if (mounted_devfs)
+		sys_umount("/dev", 0);
+#endif
+	
+	lastloglevel = -1;
+	return;
+}
+
+static void text_redraw(void)
+{
+	sys_ioctl(suspend_console_fd, TIOCL_BLANKSCREEN, (long)&termios);
+	sys_ioctl(suspend_console_fd, TIOCL_UNBLANKSCREEN, (long)&termios);
+}
+
+static int text_keypress(unsigned int key)
+{
+	switch (key) {
+		case 48:
+			console_loglevel = 0;
+			break;
+		case 49:
+			console_loglevel = 1;
+			break;
+#ifdef CONFIG_SOFTWARE_SUSPEND_DEBUG
+		case 122:
+			/* `: Toggle slow */
+			suspend_action ^= (1 << SUSPEND_SLOW);
+			suspend2_core_ops->schedule_message(7);
+			break;
+		case 1:
+			/* F1: Toggle any section debugging. */
+			suspend_debug_state ^= (1 << SUSPEND_ANY_SECTION);
+			suspend2_core_ops->schedule_message(20);
+			break;
+		case 2:
+			/* F2: Freeze. */
+			suspend_debug_state ^= (1 << SUSPEND_FREEZER);
+			suspend2_core_ops->schedule_message(21);
+			break;
+		case 3:
+			/* F3: Eat Memory */
+			suspend_debug_state ^= (1 << SUSPEND_EAT_MEMORY);
+			suspend2_core_ops->schedule_message(22);
+			break;
+		case 4:
+			/* F4: Pagesets. */
+			suspend_debug_state ^= (1 << SUSPEND_PAGESETS);
+			suspend2_core_ops->schedule_message(23);
+			break;
+		case 5:
+			/* F5: IO. */
+			suspend_debug_state ^= (1 << SUSPEND_IO);
+			suspend2_core_ops->schedule_message(24);
+			break;
+		case 6:
+			/* F6: Bmapping of pages */
+			suspend_debug_state ^= (1 << SUSPEND_BMAP);
+			suspend2_core_ops->schedule_message(25);
+			break;
+		case 7:
+			/* F7: Writer */
+			suspend_debug_state ^= (1 << SUSPEND_WRITER);
+			suspend2_core_ops->schedule_message(26);
+			break;
+		case 8:
+			/* F8: Memory */
+			suspend_debug_state ^= (1 << SUSPEND_MEMORY);
+			suspend2_core_ops->schedule_message(27);
+			break;
+		case 9:
+			/* F9: Ranges */
+			suspend_debug_state ^= (1 << SUSPEND_RANGES);
+			suspend2_core_ops->schedule_message(28);
+			break;
+		case 10:
+			/* F10: Memory Pool */
+			suspend_debug_state ^= (1 << SUSPEND_MEM_POOL);
+			suspend2_core_ops->schedule_message(29);
+			break;
+		case 11:
+			/* F11: Nosave */
+			suspend_debug_state ^= (1 << SUSPEND_NOSAVE);
+			suspend2_core_ops->schedule_message(30);
+			break;
+		case 12:
+			/* F12: Integrity */
+			suspend_debug_state ^= (1 << SUSPEND_INTEGRITY);
+			suspend2_core_ops->schedule_message(31);
+			break;
+		case 112:
+			/* During suspend, toggle pausing with P */
+			suspend_action ^= (1 << SUSPEND_PAUSE);
+			suspend2_core_ops->schedule_message(1);
+			break;
+		case 115:
+			/* Otherwise, if S pressed, toggle single step */
+			suspend_action ^= (1 << SUSPEND_SINGLESTEP);
+			suspend2_core_ops->schedule_message(3);
+			break;
+		case 108:
+			/* Otherwise, if L pressed, toggle logging everything */
+			suspend_action ^= (1 << SUSPEND_LOGALL);
+			suspend2_core_ops->schedule_message(4);
+			break;
+		case 116:
+			/* T: Toggle freezing timers */
+			clear_suspend_state(SUSPEND_TIMER_FREEZER_ON);
+			suspend2_core_ops->schedule_message(99);
+			break;
+		case 50:
+		case 51:
+		case 52:
+		case 53:
+		case 54:
+		case 55:
+		case 56:
+		case 57:
+			console_loglevel = ((key - 48));
+			break;
+#endif
+		default:
+			return 0;
+	}
+	return 1;
+}
+
+/*
+ * User interface specific /proc/suspend entries.
+ */
+
+static struct suspend_plugin_ops text_mode_ops;
+
+static struct suspend_proc_data proc_params[] = {
+	{ .filename			= "text_mode_progress_bar",
+	  .permissions			= PROC_RW,
+	  .type				= SUSPEND_PROC_DATA_INTEGER,
+	  .data = {
+		  .integer = {
+			  .variable	= &draw_progress_bar,
+			  .minimum	= 0,
+			  .maximum	= 1,
+
+		  }
+	  }
+	},
+	
+	{ .filename			= "disable_textmode_support",
+	  .permissions			= PROC_RW,
+	  .type				= SUSPEND_PROC_DATA_INTEGER,
+	  .data = {
+		.integer = {
+			.variable	= &text_mode_ops.disabled,
+			.minimum	= 0,
+			.maximum	= 1,
+		}
+	  }
+	}
+};
+
+static struct suspend_plugin_ops text_mode_ops = {
+	.type					= UI_PLUGIN,
+	.name					= "Text Mode Support",
+	.ops = {
+		.ui = {
+			.prepare		= text_prepare_console,	
+			.log_level_change	= text_loglevel_change,
+			.message		= text_message,
+			.update_progress	= text_update_progress,
+			.cleanup		= cleanup_console,
+			.keypress		= text_keypress,
+			.post_kernel_restore_redraw =
+				text_redraw,
+		}
+	}
+};
+
+/* ---- Registration ---- */
+
+static __init int text_mode_load(void)
+{
+	int i, numfiles = sizeof(proc_params) / sizeof(struct suspend_proc_data);
+	int result;
+
+	if (!(result = suspend_register_plugin(&text_mode_ops))) {
+		printk("Software Suspend text mode support loaded.\n");
+		for (i=0; i< numfiles; i++)
+			suspend_register_procfile(&proc_params[i]);
+	}
+	return result;
+}
+
+#ifdef MODULE
+static __exit void text_mode_unload(void)
+{
+	int i, numfiles = sizeof(proc_params) / sizeof(struct suspend_proc_data);
+
+	printk("Software Suspend text mode support unloading.\n");
+
+	for (i=0; i< numfiles; i++)
+		suspend_unregister_procfile(&proc_params[i]);
+	
+	suspend_unregister_plugin(&text_mode_ops);
+}
+
+module_init(text_mode_load);
+module_exit(text_mode_unload);
+MODULE_LICENSE("GPL");
+MODULE_AUTHOR("Nigel Cunningham");
+MODULE_DESCRIPTION("Suspend2 Text Mode support");
+#else
+late_initcall(text_mode_load);
+#endif