xref: /linux/kernel/power/swap.c (revision 1abbef4f51724fb11f09adf0e75275f7cb422a8a)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * linux/kernel/power/swap.c
4  *
5  * This file provides functions for reading the suspend image from
6  * and writing it to a swap partition.
7  *
8  * Copyright (C) 1998,2001-2005 Pavel Machek <pavel@ucw.cz>
9  * Copyright (C) 2006 Rafael J. Wysocki <rjw@sisk.pl>
10  * Copyright (C) 2010-2012 Bojan Smojver <bojan@rexursive.com>
11  */
12 
13 #define pr_fmt(fmt) "PM: " fmt
14 
15 #include <linux/module.h>
16 #include <linux/file.h>
17 #include <linux/delay.h>
18 #include <linux/bitops.h>
19 #include <linux/genhd.h>
20 #include <linux/device.h>
21 #include <linux/bio.h>
22 #include <linux/blkdev.h>
23 #include <linux/swap.h>
24 #include <linux/swapops.h>
25 #include <linux/pm.h>
26 #include <linux/slab.h>
27 #include <linux/lzo.h>
28 #include <linux/vmalloc.h>
29 #include <linux/cpumask.h>
30 #include <linux/atomic.h>
31 #include <linux/kthread.h>
32 #include <linux/crc32.h>
33 #include <linux/ktime.h>
34 
35 #include "power.h"
36 
37 #define HIBERNATE_SIG	"S1SUSPEND"
38 
39 /*
40  * When reading an {un,}compressed image, we may restore pages in place,
41  * in which case some architectures need these pages cleaning before they
42  * can be executed. We don't know which pages these may be, so clean the lot.
43  */
44 static bool clean_pages_on_read;
45 static bool clean_pages_on_decompress;
46 
47 /*
48  *	The swap map is a data structure used for keeping track of each page
49  *	written to a swap partition.  It consists of many swap_map_page
50  *	structures that contain each an array of MAP_PAGE_ENTRIES swap entries.
51  *	These structures are stored on the swap and linked together with the
52  *	help of the .next_swap member.
53  *
54  *	The swap map is created during suspend.  The swap map pages are
55  *	allocated and populated one at a time, so we only need one memory
56  *	page to set up the entire structure.
57  *
58  *	During resume we pick up all swap_map_page structures into a list.
59  */
60 
61 #define MAP_PAGE_ENTRIES	(PAGE_SIZE / sizeof(sector_t) - 1)
62 
63 /*
64  * Number of free pages that are not high.
65  */
66 static inline unsigned long low_free_pages(void)
67 {
68 	return nr_free_pages() - nr_free_highpages();
69 }
70 
71 /*
72  * Number of pages required to be kept free while writing the image. Always
73  * half of all available low pages before the writing starts.
74  */
75 static inline unsigned long reqd_free_pages(void)
76 {
77 	return low_free_pages() / 2;
78 }
79 
80 struct swap_map_page {
81 	sector_t entries[MAP_PAGE_ENTRIES];
82 	sector_t next_swap;
83 };
84 
85 struct swap_map_page_list {
86 	struct swap_map_page *map;
87 	struct swap_map_page_list *next;
88 };
89 
90 /**
91  *	The swap_map_handle structure is used for handling swap in
92  *	a file-alike way
93  */
94 
95 struct swap_map_handle {
96 	struct swap_map_page *cur;
97 	struct swap_map_page_list *maps;
98 	sector_t cur_swap;
99 	sector_t first_sector;
100 	unsigned int k;
101 	unsigned long reqd_free_pages;
102 	u32 crc32;
103 };
104 
105 struct swsusp_header {
106 	char reserved[PAGE_SIZE - 20 - sizeof(sector_t) - sizeof(int) -
107 	              sizeof(u32)];
108 	u32	crc32;
109 	sector_t image;
110 	unsigned int flags;	/* Flags to pass to the "boot" kernel */
111 	char	orig_sig[10];
112 	char	sig[10];
113 } __packed;
114 
115 static struct swsusp_header *swsusp_header;
116 
117 /**
118  *	The following functions are used for tracing the allocated
119  *	swap pages, so that they can be freed in case of an error.
120  */
121 
122 struct swsusp_extent {
123 	struct rb_node node;
124 	unsigned long start;
125 	unsigned long end;
126 };
127 
128 static struct rb_root swsusp_extents = RB_ROOT;
129 
130 static int swsusp_extents_insert(unsigned long swap_offset)
131 {
132 	struct rb_node **new = &(swsusp_extents.rb_node);
133 	struct rb_node *parent = NULL;
134 	struct swsusp_extent *ext;
135 
136 	/* Figure out where to put the new node */
137 	while (*new) {
138 		ext = rb_entry(*new, struct swsusp_extent, node);
139 		parent = *new;
140 		if (swap_offset < ext->start) {
141 			/* Try to merge */
142 			if (swap_offset == ext->start - 1) {
143 				ext->start--;
144 				return 0;
145 			}
146 			new = &((*new)->rb_left);
147 		} else if (swap_offset > ext->end) {
148 			/* Try to merge */
149 			if (swap_offset == ext->end + 1) {
150 				ext->end++;
151 				return 0;
152 			}
153 			new = &((*new)->rb_right);
154 		} else {
155 			/* It already is in the tree */
156 			return -EINVAL;
157 		}
158 	}
159 	/* Add the new node and rebalance the tree. */
160 	ext = kzalloc(sizeof(struct swsusp_extent), GFP_KERNEL);
161 	if (!ext)
162 		return -ENOMEM;
163 
164 	ext->start = swap_offset;
165 	ext->end = swap_offset;
166 	rb_link_node(&ext->node, parent, new);
167 	rb_insert_color(&ext->node, &swsusp_extents);
168 	return 0;
169 }
170 
171 /**
172  *	alloc_swapdev_block - allocate a swap page and register that it has
173  *	been allocated, so that it can be freed in case of an error.
174  */
175 
176 sector_t alloc_swapdev_block(int swap)
177 {
178 	unsigned long offset;
179 
180 	offset = swp_offset(get_swap_page_of_type(swap));
181 	if (offset) {
182 		if (swsusp_extents_insert(offset))
183 			swap_free(swp_entry(swap, offset));
184 		else
185 			return swapdev_block(swap, offset);
186 	}
187 	return 0;
188 }
189 
190 /**
191  *	free_all_swap_pages - free swap pages allocated for saving image data.
192  *	It also frees the extents used to register which swap entries had been
193  *	allocated.
194  */
195 
196 void free_all_swap_pages(int swap)
197 {
198 	struct rb_node *node;
199 
200 	while ((node = swsusp_extents.rb_node)) {
201 		struct swsusp_extent *ext;
202 		unsigned long offset;
203 
204 		ext = rb_entry(node, struct swsusp_extent, node);
205 		rb_erase(node, &swsusp_extents);
206 		for (offset = ext->start; offset <= ext->end; offset++)
207 			swap_free(swp_entry(swap, offset));
208 
209 		kfree(ext);
210 	}
211 }
212 
213 int swsusp_swap_in_use(void)
214 {
215 	return (swsusp_extents.rb_node != NULL);
216 }
217 
218 /*
219  * General things
220  */
221 
222 static unsigned short root_swap = 0xffff;
223 static struct block_device *hib_resume_bdev;
224 
225 struct hib_bio_batch {
226 	atomic_t		count;
227 	wait_queue_head_t	wait;
228 	blk_status_t		error;
229 };
230 
231 static void hib_init_batch(struct hib_bio_batch *hb)
232 {
233 	atomic_set(&hb->count, 0);
234 	init_waitqueue_head(&hb->wait);
235 	hb->error = BLK_STS_OK;
236 }
237 
238 static void hib_end_io(struct bio *bio)
239 {
240 	struct hib_bio_batch *hb = bio->bi_private;
241 	struct page *page = bio_first_page_all(bio);
242 
243 	if (bio->bi_status) {
244 		pr_alert("Read-error on swap-device (%u:%u:%Lu)\n",
245 			 MAJOR(bio_dev(bio)), MINOR(bio_dev(bio)),
246 			 (unsigned long long)bio->bi_iter.bi_sector);
247 	}
248 
249 	if (bio_data_dir(bio) == WRITE)
250 		put_page(page);
251 	else if (clean_pages_on_read)
252 		flush_icache_range((unsigned long)page_address(page),
253 				   (unsigned long)page_address(page) + PAGE_SIZE);
254 
255 	if (bio->bi_status && !hb->error)
256 		hb->error = bio->bi_status;
257 	if (atomic_dec_and_test(&hb->count))
258 		wake_up(&hb->wait);
259 
260 	bio_put(bio);
261 }
262 
263 static int hib_submit_io(int op, int op_flags, pgoff_t page_off, void *addr,
264 		struct hib_bio_batch *hb)
265 {
266 	struct page *page = virt_to_page(addr);
267 	struct bio *bio;
268 	int error = 0;
269 
270 	bio = bio_alloc(GFP_NOIO | __GFP_HIGH, 1);
271 	bio->bi_iter.bi_sector = page_off * (PAGE_SIZE >> 9);
272 	bio_set_dev(bio, hib_resume_bdev);
273 	bio_set_op_attrs(bio, op, op_flags);
274 
275 	if (bio_add_page(bio, page, PAGE_SIZE, 0) < PAGE_SIZE) {
276 		pr_err("Adding page to bio failed at %llu\n",
277 		       (unsigned long long)bio->bi_iter.bi_sector);
278 		bio_put(bio);
279 		return -EFAULT;
280 	}
281 
282 	if (hb) {
283 		bio->bi_end_io = hib_end_io;
284 		bio->bi_private = hb;
285 		atomic_inc(&hb->count);
286 		submit_bio(bio);
287 	} else {
288 		error = submit_bio_wait(bio);
289 		bio_put(bio);
290 	}
291 
292 	return error;
293 }
294 
295 static blk_status_t hib_wait_io(struct hib_bio_batch *hb)
296 {
297 	wait_event(hb->wait, atomic_read(&hb->count) == 0);
298 	return blk_status_to_errno(hb->error);
299 }
300 
301 /*
302  * Saving part
303  */
304 
305 static int mark_swapfiles(struct swap_map_handle *handle, unsigned int flags)
306 {
307 	int error;
308 
309 	hib_submit_io(REQ_OP_READ, 0, swsusp_resume_block,
310 		      swsusp_header, NULL);
311 	if (!memcmp("SWAP-SPACE",swsusp_header->sig, 10) ||
312 	    !memcmp("SWAPSPACE2",swsusp_header->sig, 10)) {
313 		memcpy(swsusp_header->orig_sig,swsusp_header->sig, 10);
314 		memcpy(swsusp_header->sig, HIBERNATE_SIG, 10);
315 		swsusp_header->image = handle->first_sector;
316 		swsusp_header->flags = flags;
317 		if (flags & SF_CRC32_MODE)
318 			swsusp_header->crc32 = handle->crc32;
319 		error = hib_submit_io(REQ_OP_WRITE, REQ_SYNC,
320 				      swsusp_resume_block, swsusp_header, NULL);
321 	} else {
322 		pr_err("Swap header not found!\n");
323 		error = -ENODEV;
324 	}
325 	return error;
326 }
327 
328 /**
329  *	swsusp_swap_check - check if the resume device is a swap device
330  *	and get its index (if so)
331  *
332  *	This is called before saving image
333  */
334 static int swsusp_swap_check(void)
335 {
336 	int res;
337 
338 	if (swsusp_resume_device)
339 		res = swap_type_of(swsusp_resume_device, swsusp_resume_block);
340 	else
341 		res = find_first_swap(&swsusp_resume_device);
342 	if (res < 0)
343 		return res;
344 	root_swap = res;
345 
346 	hib_resume_bdev = blkdev_get_by_dev(swsusp_resume_device, FMODE_WRITE,
347 			NULL);
348 	if (IS_ERR(hib_resume_bdev))
349 		return PTR_ERR(hib_resume_bdev);
350 
351 	res = set_blocksize(hib_resume_bdev, PAGE_SIZE);
352 	if (res < 0)
353 		blkdev_put(hib_resume_bdev, FMODE_WRITE);
354 
355 	return res;
356 }
357 
358 /**
359  *	write_page - Write one page to given swap location.
360  *	@buf:		Address we're writing.
361  *	@offset:	Offset of the swap page we're writing to.
362  *	@hb:		bio completion batch
363  */
364 
365 static int write_page(void *buf, sector_t offset, struct hib_bio_batch *hb)
366 {
367 	void *src;
368 	int ret;
369 
370 	if (!offset)
371 		return -ENOSPC;
372 
373 	if (hb) {
374 		src = (void *)__get_free_page(GFP_NOIO | __GFP_NOWARN |
375 		                              __GFP_NORETRY);
376 		if (src) {
377 			copy_page(src, buf);
378 		} else {
379 			ret = hib_wait_io(hb); /* Free pages */
380 			if (ret)
381 				return ret;
382 			src = (void *)__get_free_page(GFP_NOIO |
383 			                              __GFP_NOWARN |
384 			                              __GFP_NORETRY);
385 			if (src) {
386 				copy_page(src, buf);
387 			} else {
388 				WARN_ON_ONCE(1);
389 				hb = NULL;	/* Go synchronous */
390 				src = buf;
391 			}
392 		}
393 	} else {
394 		src = buf;
395 	}
396 	return hib_submit_io(REQ_OP_WRITE, REQ_SYNC, offset, src, hb);
397 }
398 
399 static void release_swap_writer(struct swap_map_handle *handle)
400 {
401 	if (handle->cur)
402 		free_page((unsigned long)handle->cur);
403 	handle->cur = NULL;
404 }
405 
406 static int get_swap_writer(struct swap_map_handle *handle)
407 {
408 	int ret;
409 
410 	ret = swsusp_swap_check();
411 	if (ret) {
412 		if (ret != -ENOSPC)
413 			pr_err("Cannot find swap device, try swapon -a\n");
414 		return ret;
415 	}
416 	handle->cur = (struct swap_map_page *)get_zeroed_page(GFP_KERNEL);
417 	if (!handle->cur) {
418 		ret = -ENOMEM;
419 		goto err_close;
420 	}
421 	handle->cur_swap = alloc_swapdev_block(root_swap);
422 	if (!handle->cur_swap) {
423 		ret = -ENOSPC;
424 		goto err_rel;
425 	}
426 	handle->k = 0;
427 	handle->reqd_free_pages = reqd_free_pages();
428 	handle->first_sector = handle->cur_swap;
429 	return 0;
430 err_rel:
431 	release_swap_writer(handle);
432 err_close:
433 	swsusp_close(FMODE_WRITE);
434 	return ret;
435 }
436 
437 static int swap_write_page(struct swap_map_handle *handle, void *buf,
438 		struct hib_bio_batch *hb)
439 {
440 	int error = 0;
441 	sector_t offset;
442 
443 	if (!handle->cur)
444 		return -EINVAL;
445 	offset = alloc_swapdev_block(root_swap);
446 	error = write_page(buf, offset, hb);
447 	if (error)
448 		return error;
449 	handle->cur->entries[handle->k++] = offset;
450 	if (handle->k >= MAP_PAGE_ENTRIES) {
451 		offset = alloc_swapdev_block(root_swap);
452 		if (!offset)
453 			return -ENOSPC;
454 		handle->cur->next_swap = offset;
455 		error = write_page(handle->cur, handle->cur_swap, hb);
456 		if (error)
457 			goto out;
458 		clear_page(handle->cur);
459 		handle->cur_swap = offset;
460 		handle->k = 0;
461 
462 		if (hb && low_free_pages() <= handle->reqd_free_pages) {
463 			error = hib_wait_io(hb);
464 			if (error)
465 				goto out;
466 			/*
467 			 * Recalculate the number of required free pages, to
468 			 * make sure we never take more than half.
469 			 */
470 			handle->reqd_free_pages = reqd_free_pages();
471 		}
472 	}
473  out:
474 	return error;
475 }
476 
477 static int flush_swap_writer(struct swap_map_handle *handle)
478 {
479 	if (handle->cur && handle->cur_swap)
480 		return write_page(handle->cur, handle->cur_swap, NULL);
481 	else
482 		return -EINVAL;
483 }
484 
485 static int swap_writer_finish(struct swap_map_handle *handle,
486 		unsigned int flags, int error)
487 {
488 	if (!error) {
489 		flush_swap_writer(handle);
490 		pr_info("S");
491 		error = mark_swapfiles(handle, flags);
492 		pr_cont("|\n");
493 	}
494 
495 	if (error)
496 		free_all_swap_pages(root_swap);
497 	release_swap_writer(handle);
498 	swsusp_close(FMODE_WRITE);
499 
500 	return error;
501 }
502 
503 /* We need to remember how much compressed data we need to read. */
504 #define LZO_HEADER	sizeof(size_t)
505 
506 /* Number of pages/bytes we'll compress at one time. */
507 #define LZO_UNC_PAGES	32
508 #define LZO_UNC_SIZE	(LZO_UNC_PAGES * PAGE_SIZE)
509 
510 /* Number of pages/bytes we need for compressed data (worst case). */
511 #define LZO_CMP_PAGES	DIV_ROUND_UP(lzo1x_worst_compress(LZO_UNC_SIZE) + \
512 			             LZO_HEADER, PAGE_SIZE)
513 #define LZO_CMP_SIZE	(LZO_CMP_PAGES * PAGE_SIZE)
514 
515 /* Maximum number of threads for compression/decompression. */
516 #define LZO_THREADS	3
517 
518 /* Minimum/maximum number of pages for read buffering. */
519 #define LZO_MIN_RD_PAGES	1024
520 #define LZO_MAX_RD_PAGES	8192
521 
522 
523 /**
524  *	save_image - save the suspend image data
525  */
526 
527 static int save_image(struct swap_map_handle *handle,
528                       struct snapshot_handle *snapshot,
529                       unsigned int nr_to_write)
530 {
531 	unsigned int m;
532 	int ret;
533 	int nr_pages;
534 	int err2;
535 	struct hib_bio_batch hb;
536 	ktime_t start;
537 	ktime_t stop;
538 
539 	hib_init_batch(&hb);
540 
541 	pr_info("Saving image data pages (%u pages)...\n",
542 		nr_to_write);
543 	m = nr_to_write / 10;
544 	if (!m)
545 		m = 1;
546 	nr_pages = 0;
547 	start = ktime_get();
548 	while (1) {
549 		ret = snapshot_read_next(snapshot);
550 		if (ret <= 0)
551 			break;
552 		ret = swap_write_page(handle, data_of(*snapshot), &hb);
553 		if (ret)
554 			break;
555 		if (!(nr_pages % m))
556 			pr_info("Image saving progress: %3d%%\n",
557 				nr_pages / m * 10);
558 		nr_pages++;
559 	}
560 	err2 = hib_wait_io(&hb);
561 	stop = ktime_get();
562 	if (!ret)
563 		ret = err2;
564 	if (!ret)
565 		pr_info("Image saving done\n");
566 	swsusp_show_speed(start, stop, nr_to_write, "Wrote");
567 	return ret;
568 }
569 
570 /**
571  * Structure used for CRC32.
572  */
573 struct crc_data {
574 	struct task_struct *thr;                  /* thread */
575 	atomic_t ready;                           /* ready to start flag */
576 	atomic_t stop;                            /* ready to stop flag */
577 	unsigned run_threads;                     /* nr current threads */
578 	wait_queue_head_t go;                     /* start crc update */
579 	wait_queue_head_t done;                   /* crc update done */
580 	u32 *crc32;                               /* points to handle's crc32 */
581 	size_t *unc_len[LZO_THREADS];             /* uncompressed lengths */
582 	unsigned char *unc[LZO_THREADS];          /* uncompressed data */
583 };
584 
585 /**
586  * CRC32 update function that runs in its own thread.
587  */
588 static int crc32_threadfn(void *data)
589 {
590 	struct crc_data *d = data;
591 	unsigned i;
592 
593 	while (1) {
594 		wait_event(d->go, atomic_read(&d->ready) ||
595 		                  kthread_should_stop());
596 		if (kthread_should_stop()) {
597 			d->thr = NULL;
598 			atomic_set(&d->stop, 1);
599 			wake_up(&d->done);
600 			break;
601 		}
602 		atomic_set(&d->ready, 0);
603 
604 		for (i = 0; i < d->run_threads; i++)
605 			*d->crc32 = crc32_le(*d->crc32,
606 			                     d->unc[i], *d->unc_len[i]);
607 		atomic_set(&d->stop, 1);
608 		wake_up(&d->done);
609 	}
610 	return 0;
611 }
612 /**
613  * Structure used for LZO data compression.
614  */
615 struct cmp_data {
616 	struct task_struct *thr;                  /* thread */
617 	atomic_t ready;                           /* ready to start flag */
618 	atomic_t stop;                            /* ready to stop flag */
619 	int ret;                                  /* return code */
620 	wait_queue_head_t go;                     /* start compression */
621 	wait_queue_head_t done;                   /* compression done */
622 	size_t unc_len;                           /* uncompressed length */
623 	size_t cmp_len;                           /* compressed length */
624 	unsigned char unc[LZO_UNC_SIZE];          /* uncompressed buffer */
625 	unsigned char cmp[LZO_CMP_SIZE];          /* compressed buffer */
626 	unsigned char wrk[LZO1X_1_MEM_COMPRESS];  /* compression workspace */
627 };
628 
629 /**
630  * Compression function that runs in its own thread.
631  */
632 static int lzo_compress_threadfn(void *data)
633 {
634 	struct cmp_data *d = data;
635 
636 	while (1) {
637 		wait_event(d->go, atomic_read(&d->ready) ||
638 		                  kthread_should_stop());
639 		if (kthread_should_stop()) {
640 			d->thr = NULL;
641 			d->ret = -1;
642 			atomic_set(&d->stop, 1);
643 			wake_up(&d->done);
644 			break;
645 		}
646 		atomic_set(&d->ready, 0);
647 
648 		d->ret = lzo1x_1_compress(d->unc, d->unc_len,
649 		                          d->cmp + LZO_HEADER, &d->cmp_len,
650 		                          d->wrk);
651 		atomic_set(&d->stop, 1);
652 		wake_up(&d->done);
653 	}
654 	return 0;
655 }
656 
657 /**
658  * save_image_lzo - Save the suspend image data compressed with LZO.
659  * @handle: Swap map handle to use for saving the image.
660  * @snapshot: Image to read data from.
661  * @nr_to_write: Number of pages to save.
662  */
663 static int save_image_lzo(struct swap_map_handle *handle,
664                           struct snapshot_handle *snapshot,
665                           unsigned int nr_to_write)
666 {
667 	unsigned int m;
668 	int ret = 0;
669 	int nr_pages;
670 	int err2;
671 	struct hib_bio_batch hb;
672 	ktime_t start;
673 	ktime_t stop;
674 	size_t off;
675 	unsigned thr, run_threads, nr_threads;
676 	unsigned char *page = NULL;
677 	struct cmp_data *data = NULL;
678 	struct crc_data *crc = NULL;
679 
680 	hib_init_batch(&hb);
681 
682 	/*
683 	 * We'll limit the number of threads for compression to limit memory
684 	 * footprint.
685 	 */
686 	nr_threads = num_online_cpus() - 1;
687 	nr_threads = clamp_val(nr_threads, 1, LZO_THREADS);
688 
689 	page = (void *)__get_free_page(GFP_NOIO | __GFP_HIGH);
690 	if (!page) {
691 		pr_err("Failed to allocate LZO page\n");
692 		ret = -ENOMEM;
693 		goto out_clean;
694 	}
695 
696 	data = vmalloc(array_size(nr_threads, sizeof(*data)));
697 	if (!data) {
698 		pr_err("Failed to allocate LZO data\n");
699 		ret = -ENOMEM;
700 		goto out_clean;
701 	}
702 	for (thr = 0; thr < nr_threads; thr++)
703 		memset(&data[thr], 0, offsetof(struct cmp_data, go));
704 
705 	crc = kmalloc(sizeof(*crc), GFP_KERNEL);
706 	if (!crc) {
707 		pr_err("Failed to allocate crc\n");
708 		ret = -ENOMEM;
709 		goto out_clean;
710 	}
711 	memset(crc, 0, offsetof(struct crc_data, go));
712 
713 	/*
714 	 * Start the compression threads.
715 	 */
716 	for (thr = 0; thr < nr_threads; thr++) {
717 		init_waitqueue_head(&data[thr].go);
718 		init_waitqueue_head(&data[thr].done);
719 
720 		data[thr].thr = kthread_run(lzo_compress_threadfn,
721 		                            &data[thr],
722 		                            "image_compress/%u", thr);
723 		if (IS_ERR(data[thr].thr)) {
724 			data[thr].thr = NULL;
725 			pr_err("Cannot start compression threads\n");
726 			ret = -ENOMEM;
727 			goto out_clean;
728 		}
729 	}
730 
731 	/*
732 	 * Start the CRC32 thread.
733 	 */
734 	init_waitqueue_head(&crc->go);
735 	init_waitqueue_head(&crc->done);
736 
737 	handle->crc32 = 0;
738 	crc->crc32 = &handle->crc32;
739 	for (thr = 0; thr < nr_threads; thr++) {
740 		crc->unc[thr] = data[thr].unc;
741 		crc->unc_len[thr] = &data[thr].unc_len;
742 	}
743 
744 	crc->thr = kthread_run(crc32_threadfn, crc, "image_crc32");
745 	if (IS_ERR(crc->thr)) {
746 		crc->thr = NULL;
747 		pr_err("Cannot start CRC32 thread\n");
748 		ret = -ENOMEM;
749 		goto out_clean;
750 	}
751 
752 	/*
753 	 * Adjust the number of required free pages after all allocations have
754 	 * been done. We don't want to run out of pages when writing.
755 	 */
756 	handle->reqd_free_pages = reqd_free_pages();
757 
758 	pr_info("Using %u thread(s) for compression\n", nr_threads);
759 	pr_info("Compressing and saving image data (%u pages)...\n",
760 		nr_to_write);
761 	m = nr_to_write / 10;
762 	if (!m)
763 		m = 1;
764 	nr_pages = 0;
765 	start = ktime_get();
766 	for (;;) {
767 		for (thr = 0; thr < nr_threads; thr++) {
768 			for (off = 0; off < LZO_UNC_SIZE; off += PAGE_SIZE) {
769 				ret = snapshot_read_next(snapshot);
770 				if (ret < 0)
771 					goto out_finish;
772 
773 				if (!ret)
774 					break;
775 
776 				memcpy(data[thr].unc + off,
777 				       data_of(*snapshot), PAGE_SIZE);
778 
779 				if (!(nr_pages % m))
780 					pr_info("Image saving progress: %3d%%\n",
781 						nr_pages / m * 10);
782 				nr_pages++;
783 			}
784 			if (!off)
785 				break;
786 
787 			data[thr].unc_len = off;
788 
789 			atomic_set(&data[thr].ready, 1);
790 			wake_up(&data[thr].go);
791 		}
792 
793 		if (!thr)
794 			break;
795 
796 		crc->run_threads = thr;
797 		atomic_set(&crc->ready, 1);
798 		wake_up(&crc->go);
799 
800 		for (run_threads = thr, thr = 0; thr < run_threads; thr++) {
801 			wait_event(data[thr].done,
802 			           atomic_read(&data[thr].stop));
803 			atomic_set(&data[thr].stop, 0);
804 
805 			ret = data[thr].ret;
806 
807 			if (ret < 0) {
808 				pr_err("LZO compression failed\n");
809 				goto out_finish;
810 			}
811 
812 			if (unlikely(!data[thr].cmp_len ||
813 			             data[thr].cmp_len >
814 			             lzo1x_worst_compress(data[thr].unc_len))) {
815 				pr_err("Invalid LZO compressed length\n");
816 				ret = -1;
817 				goto out_finish;
818 			}
819 
820 			*(size_t *)data[thr].cmp = data[thr].cmp_len;
821 
822 			/*
823 			 * Given we are writing one page at a time to disk, we
824 			 * copy that much from the buffer, although the last
825 			 * bit will likely be smaller than full page. This is
826 			 * OK - we saved the length of the compressed data, so
827 			 * any garbage at the end will be discarded when we
828 			 * read it.
829 			 */
830 			for (off = 0;
831 			     off < LZO_HEADER + data[thr].cmp_len;
832 			     off += PAGE_SIZE) {
833 				memcpy(page, data[thr].cmp + off, PAGE_SIZE);
834 
835 				ret = swap_write_page(handle, page, &hb);
836 				if (ret)
837 					goto out_finish;
838 			}
839 		}
840 
841 		wait_event(crc->done, atomic_read(&crc->stop));
842 		atomic_set(&crc->stop, 0);
843 	}
844 
845 out_finish:
846 	err2 = hib_wait_io(&hb);
847 	stop = ktime_get();
848 	if (!ret)
849 		ret = err2;
850 	if (!ret)
851 		pr_info("Image saving done\n");
852 	swsusp_show_speed(start, stop, nr_to_write, "Wrote");
853 out_clean:
854 	if (crc) {
855 		if (crc->thr)
856 			kthread_stop(crc->thr);
857 		kfree(crc);
858 	}
859 	if (data) {
860 		for (thr = 0; thr < nr_threads; thr++)
861 			if (data[thr].thr)
862 				kthread_stop(data[thr].thr);
863 		vfree(data);
864 	}
865 	if (page) free_page((unsigned long)page);
866 
867 	return ret;
868 }
869 
870 /**
871  *	enough_swap - Make sure we have enough swap to save the image.
872  *
873  *	Returns TRUE or FALSE after checking the total amount of swap
874  *	space avaiable from the resume partition.
875  */
876 
877 static int enough_swap(unsigned int nr_pages)
878 {
879 	unsigned int free_swap = count_swap_pages(root_swap, 1);
880 	unsigned int required;
881 
882 	pr_debug("Free swap pages: %u\n", free_swap);
883 
884 	required = PAGES_FOR_IO + nr_pages;
885 	return free_swap > required;
886 }
887 
888 /**
889  *	swsusp_write - Write entire image and metadata.
890  *	@flags: flags to pass to the "boot" kernel in the image header
891  *
892  *	It is important _NOT_ to umount filesystems at this point. We want
893  *	them synced (in case something goes wrong) but we DO not want to mark
894  *	filesystem clean: it is not. (And it does not matter, if we resume
895  *	correctly, we'll mark system clean, anyway.)
896  */
897 
898 int swsusp_write(unsigned int flags)
899 {
900 	struct swap_map_handle handle;
901 	struct snapshot_handle snapshot;
902 	struct swsusp_info *header;
903 	unsigned long pages;
904 	int error;
905 
906 	pages = snapshot_get_image_size();
907 	error = get_swap_writer(&handle);
908 	if (error) {
909 		pr_err("Cannot get swap writer\n");
910 		return error;
911 	}
912 	if (flags & SF_NOCOMPRESS_MODE) {
913 		if (!enough_swap(pages)) {
914 			pr_err("Not enough free swap\n");
915 			error = -ENOSPC;
916 			goto out_finish;
917 		}
918 	}
919 	memset(&snapshot, 0, sizeof(struct snapshot_handle));
920 	error = snapshot_read_next(&snapshot);
921 	if (error < (int)PAGE_SIZE) {
922 		if (error >= 0)
923 			error = -EFAULT;
924 
925 		goto out_finish;
926 	}
927 	header = (struct swsusp_info *)data_of(snapshot);
928 	error = swap_write_page(&handle, header, NULL);
929 	if (!error) {
930 		error = (flags & SF_NOCOMPRESS_MODE) ?
931 			save_image(&handle, &snapshot, pages - 1) :
932 			save_image_lzo(&handle, &snapshot, pages - 1);
933 	}
934 out_finish:
935 	error = swap_writer_finish(&handle, flags, error);
936 	return error;
937 }
938 
939 /**
940  *	The following functions allow us to read data using a swap map
941  *	in a file-alike way
942  */
943 
944 static void release_swap_reader(struct swap_map_handle *handle)
945 {
946 	struct swap_map_page_list *tmp;
947 
948 	while (handle->maps) {
949 		if (handle->maps->map)
950 			free_page((unsigned long)handle->maps->map);
951 		tmp = handle->maps;
952 		handle->maps = handle->maps->next;
953 		kfree(tmp);
954 	}
955 	handle->cur = NULL;
956 }
957 
958 static int get_swap_reader(struct swap_map_handle *handle,
959 		unsigned int *flags_p)
960 {
961 	int error;
962 	struct swap_map_page_list *tmp, *last;
963 	sector_t offset;
964 
965 	*flags_p = swsusp_header->flags;
966 
967 	if (!swsusp_header->image) /* how can this happen? */
968 		return -EINVAL;
969 
970 	handle->cur = NULL;
971 	last = handle->maps = NULL;
972 	offset = swsusp_header->image;
973 	while (offset) {
974 		tmp = kzalloc(sizeof(*handle->maps), GFP_KERNEL);
975 		if (!tmp) {
976 			release_swap_reader(handle);
977 			return -ENOMEM;
978 		}
979 		if (!handle->maps)
980 			handle->maps = tmp;
981 		if (last)
982 			last->next = tmp;
983 		last = tmp;
984 
985 		tmp->map = (struct swap_map_page *)
986 			   __get_free_page(GFP_NOIO | __GFP_HIGH);
987 		if (!tmp->map) {
988 			release_swap_reader(handle);
989 			return -ENOMEM;
990 		}
991 
992 		error = hib_submit_io(REQ_OP_READ, 0, offset, tmp->map, NULL);
993 		if (error) {
994 			release_swap_reader(handle);
995 			return error;
996 		}
997 		offset = tmp->map->next_swap;
998 	}
999 	handle->k = 0;
1000 	handle->cur = handle->maps->map;
1001 	return 0;
1002 }
1003 
1004 static int swap_read_page(struct swap_map_handle *handle, void *buf,
1005 		struct hib_bio_batch *hb)
1006 {
1007 	sector_t offset;
1008 	int error;
1009 	struct swap_map_page_list *tmp;
1010 
1011 	if (!handle->cur)
1012 		return -EINVAL;
1013 	offset = handle->cur->entries[handle->k];
1014 	if (!offset)
1015 		return -EFAULT;
1016 	error = hib_submit_io(REQ_OP_READ, 0, offset, buf, hb);
1017 	if (error)
1018 		return error;
1019 	if (++handle->k >= MAP_PAGE_ENTRIES) {
1020 		handle->k = 0;
1021 		free_page((unsigned long)handle->maps->map);
1022 		tmp = handle->maps;
1023 		handle->maps = handle->maps->next;
1024 		kfree(tmp);
1025 		if (!handle->maps)
1026 			release_swap_reader(handle);
1027 		else
1028 			handle->cur = handle->maps->map;
1029 	}
1030 	return error;
1031 }
1032 
1033 static int swap_reader_finish(struct swap_map_handle *handle)
1034 {
1035 	release_swap_reader(handle);
1036 
1037 	return 0;
1038 }
1039 
1040 /**
1041  *	load_image - load the image using the swap map handle
1042  *	@handle and the snapshot handle @snapshot
1043  *	(assume there are @nr_pages pages to load)
1044  */
1045 
1046 static int load_image(struct swap_map_handle *handle,
1047                       struct snapshot_handle *snapshot,
1048                       unsigned int nr_to_read)
1049 {
1050 	unsigned int m;
1051 	int ret = 0;
1052 	ktime_t start;
1053 	ktime_t stop;
1054 	struct hib_bio_batch hb;
1055 	int err2;
1056 	unsigned nr_pages;
1057 
1058 	hib_init_batch(&hb);
1059 
1060 	clean_pages_on_read = true;
1061 	pr_info("Loading image data pages (%u pages)...\n", nr_to_read);
1062 	m = nr_to_read / 10;
1063 	if (!m)
1064 		m = 1;
1065 	nr_pages = 0;
1066 	start = ktime_get();
1067 	for ( ; ; ) {
1068 		ret = snapshot_write_next(snapshot);
1069 		if (ret <= 0)
1070 			break;
1071 		ret = swap_read_page(handle, data_of(*snapshot), &hb);
1072 		if (ret)
1073 			break;
1074 		if (snapshot->sync_read)
1075 			ret = hib_wait_io(&hb);
1076 		if (ret)
1077 			break;
1078 		if (!(nr_pages % m))
1079 			pr_info("Image loading progress: %3d%%\n",
1080 				nr_pages / m * 10);
1081 		nr_pages++;
1082 	}
1083 	err2 = hib_wait_io(&hb);
1084 	stop = ktime_get();
1085 	if (!ret)
1086 		ret = err2;
1087 	if (!ret) {
1088 		pr_info("Image loading done\n");
1089 		snapshot_write_finalize(snapshot);
1090 		if (!snapshot_image_loaded(snapshot))
1091 			ret = -ENODATA;
1092 	}
1093 	swsusp_show_speed(start, stop, nr_to_read, "Read");
1094 	return ret;
1095 }
1096 
1097 /**
1098  * Structure used for LZO data decompression.
1099  */
1100 struct dec_data {
1101 	struct task_struct *thr;                  /* thread */
1102 	atomic_t ready;                           /* ready to start flag */
1103 	atomic_t stop;                            /* ready to stop flag */
1104 	int ret;                                  /* return code */
1105 	wait_queue_head_t go;                     /* start decompression */
1106 	wait_queue_head_t done;                   /* decompression done */
1107 	size_t unc_len;                           /* uncompressed length */
1108 	size_t cmp_len;                           /* compressed length */
1109 	unsigned char unc[LZO_UNC_SIZE];          /* uncompressed buffer */
1110 	unsigned char cmp[LZO_CMP_SIZE];          /* compressed buffer */
1111 };
1112 
1113 /**
1114  * Deompression function that runs in its own thread.
1115  */
1116 static int lzo_decompress_threadfn(void *data)
1117 {
1118 	struct dec_data *d = data;
1119 
1120 	while (1) {
1121 		wait_event(d->go, atomic_read(&d->ready) ||
1122 		                  kthread_should_stop());
1123 		if (kthread_should_stop()) {
1124 			d->thr = NULL;
1125 			d->ret = -1;
1126 			atomic_set(&d->stop, 1);
1127 			wake_up(&d->done);
1128 			break;
1129 		}
1130 		atomic_set(&d->ready, 0);
1131 
1132 		d->unc_len = LZO_UNC_SIZE;
1133 		d->ret = lzo1x_decompress_safe(d->cmp + LZO_HEADER, d->cmp_len,
1134 		                               d->unc, &d->unc_len);
1135 		if (clean_pages_on_decompress)
1136 			flush_icache_range((unsigned long)d->unc,
1137 					   (unsigned long)d->unc + d->unc_len);
1138 
1139 		atomic_set(&d->stop, 1);
1140 		wake_up(&d->done);
1141 	}
1142 	return 0;
1143 }
1144 
1145 /**
1146  * load_image_lzo - Load compressed image data and decompress them with LZO.
1147  * @handle: Swap map handle to use for loading data.
1148  * @snapshot: Image to copy uncompressed data into.
1149  * @nr_to_read: Number of pages to load.
1150  */
1151 static int load_image_lzo(struct swap_map_handle *handle,
1152                           struct snapshot_handle *snapshot,
1153                           unsigned int nr_to_read)
1154 {
1155 	unsigned int m;
1156 	int ret = 0;
1157 	int eof = 0;
1158 	struct hib_bio_batch hb;
1159 	ktime_t start;
1160 	ktime_t stop;
1161 	unsigned nr_pages;
1162 	size_t off;
1163 	unsigned i, thr, run_threads, nr_threads;
1164 	unsigned ring = 0, pg = 0, ring_size = 0,
1165 	         have = 0, want, need, asked = 0;
1166 	unsigned long read_pages = 0;
1167 	unsigned char **page = NULL;
1168 	struct dec_data *data = NULL;
1169 	struct crc_data *crc = NULL;
1170 
1171 	hib_init_batch(&hb);
1172 
1173 	/*
1174 	 * We'll limit the number of threads for decompression to limit memory
1175 	 * footprint.
1176 	 */
1177 	nr_threads = num_online_cpus() - 1;
1178 	nr_threads = clamp_val(nr_threads, 1, LZO_THREADS);
1179 
1180 	page = vmalloc(array_size(LZO_MAX_RD_PAGES, sizeof(*page)));
1181 	if (!page) {
1182 		pr_err("Failed to allocate LZO page\n");
1183 		ret = -ENOMEM;
1184 		goto out_clean;
1185 	}
1186 
1187 	data = vmalloc(array_size(nr_threads, sizeof(*data)));
1188 	if (!data) {
1189 		pr_err("Failed to allocate LZO data\n");
1190 		ret = -ENOMEM;
1191 		goto out_clean;
1192 	}
1193 	for (thr = 0; thr < nr_threads; thr++)
1194 		memset(&data[thr], 0, offsetof(struct dec_data, go));
1195 
1196 	crc = kmalloc(sizeof(*crc), GFP_KERNEL);
1197 	if (!crc) {
1198 		pr_err("Failed to allocate crc\n");
1199 		ret = -ENOMEM;
1200 		goto out_clean;
1201 	}
1202 	memset(crc, 0, offsetof(struct crc_data, go));
1203 
1204 	clean_pages_on_decompress = true;
1205 
1206 	/*
1207 	 * Start the decompression threads.
1208 	 */
1209 	for (thr = 0; thr < nr_threads; thr++) {
1210 		init_waitqueue_head(&data[thr].go);
1211 		init_waitqueue_head(&data[thr].done);
1212 
1213 		data[thr].thr = kthread_run(lzo_decompress_threadfn,
1214 		                            &data[thr],
1215 		                            "image_decompress/%u", thr);
1216 		if (IS_ERR(data[thr].thr)) {
1217 			data[thr].thr = NULL;
1218 			pr_err("Cannot start decompression threads\n");
1219 			ret = -ENOMEM;
1220 			goto out_clean;
1221 		}
1222 	}
1223 
1224 	/*
1225 	 * Start the CRC32 thread.
1226 	 */
1227 	init_waitqueue_head(&crc->go);
1228 	init_waitqueue_head(&crc->done);
1229 
1230 	handle->crc32 = 0;
1231 	crc->crc32 = &handle->crc32;
1232 	for (thr = 0; thr < nr_threads; thr++) {
1233 		crc->unc[thr] = data[thr].unc;
1234 		crc->unc_len[thr] = &data[thr].unc_len;
1235 	}
1236 
1237 	crc->thr = kthread_run(crc32_threadfn, crc, "image_crc32");
1238 	if (IS_ERR(crc->thr)) {
1239 		crc->thr = NULL;
1240 		pr_err("Cannot start CRC32 thread\n");
1241 		ret = -ENOMEM;
1242 		goto out_clean;
1243 	}
1244 
1245 	/*
1246 	 * Set the number of pages for read buffering.
1247 	 * This is complete guesswork, because we'll only know the real
1248 	 * picture once prepare_image() is called, which is much later on
1249 	 * during the image load phase. We'll assume the worst case and
1250 	 * say that none of the image pages are from high memory.
1251 	 */
1252 	if (low_free_pages() > snapshot_get_image_size())
1253 		read_pages = (low_free_pages() - snapshot_get_image_size()) / 2;
1254 	read_pages = clamp_val(read_pages, LZO_MIN_RD_PAGES, LZO_MAX_RD_PAGES);
1255 
1256 	for (i = 0; i < read_pages; i++) {
1257 		page[i] = (void *)__get_free_page(i < LZO_CMP_PAGES ?
1258 						  GFP_NOIO | __GFP_HIGH :
1259 						  GFP_NOIO | __GFP_NOWARN |
1260 						  __GFP_NORETRY);
1261 
1262 		if (!page[i]) {
1263 			if (i < LZO_CMP_PAGES) {
1264 				ring_size = i;
1265 				pr_err("Failed to allocate LZO pages\n");
1266 				ret = -ENOMEM;
1267 				goto out_clean;
1268 			} else {
1269 				break;
1270 			}
1271 		}
1272 	}
1273 	want = ring_size = i;
1274 
1275 	pr_info("Using %u thread(s) for decompression\n", nr_threads);
1276 	pr_info("Loading and decompressing image data (%u pages)...\n",
1277 		nr_to_read);
1278 	m = nr_to_read / 10;
1279 	if (!m)
1280 		m = 1;
1281 	nr_pages = 0;
1282 	start = ktime_get();
1283 
1284 	ret = snapshot_write_next(snapshot);
1285 	if (ret <= 0)
1286 		goto out_finish;
1287 
1288 	for(;;) {
1289 		for (i = 0; !eof && i < want; i++) {
1290 			ret = swap_read_page(handle, page[ring], &hb);
1291 			if (ret) {
1292 				/*
1293 				 * On real read error, finish. On end of data,
1294 				 * set EOF flag and just exit the read loop.
1295 				 */
1296 				if (handle->cur &&
1297 				    handle->cur->entries[handle->k]) {
1298 					goto out_finish;
1299 				} else {
1300 					eof = 1;
1301 					break;
1302 				}
1303 			}
1304 			if (++ring >= ring_size)
1305 				ring = 0;
1306 		}
1307 		asked += i;
1308 		want -= i;
1309 
1310 		/*
1311 		 * We are out of data, wait for some more.
1312 		 */
1313 		if (!have) {
1314 			if (!asked)
1315 				break;
1316 
1317 			ret = hib_wait_io(&hb);
1318 			if (ret)
1319 				goto out_finish;
1320 			have += asked;
1321 			asked = 0;
1322 			if (eof)
1323 				eof = 2;
1324 		}
1325 
1326 		if (crc->run_threads) {
1327 			wait_event(crc->done, atomic_read(&crc->stop));
1328 			atomic_set(&crc->stop, 0);
1329 			crc->run_threads = 0;
1330 		}
1331 
1332 		for (thr = 0; have && thr < nr_threads; thr++) {
1333 			data[thr].cmp_len = *(size_t *)page[pg];
1334 			if (unlikely(!data[thr].cmp_len ||
1335 			             data[thr].cmp_len >
1336 			             lzo1x_worst_compress(LZO_UNC_SIZE))) {
1337 				pr_err("Invalid LZO compressed length\n");
1338 				ret = -1;
1339 				goto out_finish;
1340 			}
1341 
1342 			need = DIV_ROUND_UP(data[thr].cmp_len + LZO_HEADER,
1343 			                    PAGE_SIZE);
1344 			if (need > have) {
1345 				if (eof > 1) {
1346 					ret = -1;
1347 					goto out_finish;
1348 				}
1349 				break;
1350 			}
1351 
1352 			for (off = 0;
1353 			     off < LZO_HEADER + data[thr].cmp_len;
1354 			     off += PAGE_SIZE) {
1355 				memcpy(data[thr].cmp + off,
1356 				       page[pg], PAGE_SIZE);
1357 				have--;
1358 				want++;
1359 				if (++pg >= ring_size)
1360 					pg = 0;
1361 			}
1362 
1363 			atomic_set(&data[thr].ready, 1);
1364 			wake_up(&data[thr].go);
1365 		}
1366 
1367 		/*
1368 		 * Wait for more data while we are decompressing.
1369 		 */
1370 		if (have < LZO_CMP_PAGES && asked) {
1371 			ret = hib_wait_io(&hb);
1372 			if (ret)
1373 				goto out_finish;
1374 			have += asked;
1375 			asked = 0;
1376 			if (eof)
1377 				eof = 2;
1378 		}
1379 
1380 		for (run_threads = thr, thr = 0; thr < run_threads; thr++) {
1381 			wait_event(data[thr].done,
1382 			           atomic_read(&data[thr].stop));
1383 			atomic_set(&data[thr].stop, 0);
1384 
1385 			ret = data[thr].ret;
1386 
1387 			if (ret < 0) {
1388 				pr_err("LZO decompression failed\n");
1389 				goto out_finish;
1390 			}
1391 
1392 			if (unlikely(!data[thr].unc_len ||
1393 			             data[thr].unc_len > LZO_UNC_SIZE ||
1394 			             data[thr].unc_len & (PAGE_SIZE - 1))) {
1395 				pr_err("Invalid LZO uncompressed length\n");
1396 				ret = -1;
1397 				goto out_finish;
1398 			}
1399 
1400 			for (off = 0;
1401 			     off < data[thr].unc_len; off += PAGE_SIZE) {
1402 				memcpy(data_of(*snapshot),
1403 				       data[thr].unc + off, PAGE_SIZE);
1404 
1405 				if (!(nr_pages % m))
1406 					pr_info("Image loading progress: %3d%%\n",
1407 						nr_pages / m * 10);
1408 				nr_pages++;
1409 
1410 				ret = snapshot_write_next(snapshot);
1411 				if (ret <= 0) {
1412 					crc->run_threads = thr + 1;
1413 					atomic_set(&crc->ready, 1);
1414 					wake_up(&crc->go);
1415 					goto out_finish;
1416 				}
1417 			}
1418 		}
1419 
1420 		crc->run_threads = thr;
1421 		atomic_set(&crc->ready, 1);
1422 		wake_up(&crc->go);
1423 	}
1424 
1425 out_finish:
1426 	if (crc->run_threads) {
1427 		wait_event(crc->done, atomic_read(&crc->stop));
1428 		atomic_set(&crc->stop, 0);
1429 	}
1430 	stop = ktime_get();
1431 	if (!ret) {
1432 		pr_info("Image loading done\n");
1433 		snapshot_write_finalize(snapshot);
1434 		if (!snapshot_image_loaded(snapshot))
1435 			ret = -ENODATA;
1436 		if (!ret) {
1437 			if (swsusp_header->flags & SF_CRC32_MODE) {
1438 				if(handle->crc32 != swsusp_header->crc32) {
1439 					pr_err("Invalid image CRC32!\n");
1440 					ret = -ENODATA;
1441 				}
1442 			}
1443 		}
1444 	}
1445 	swsusp_show_speed(start, stop, nr_to_read, "Read");
1446 out_clean:
1447 	for (i = 0; i < ring_size; i++)
1448 		free_page((unsigned long)page[i]);
1449 	if (crc) {
1450 		if (crc->thr)
1451 			kthread_stop(crc->thr);
1452 		kfree(crc);
1453 	}
1454 	if (data) {
1455 		for (thr = 0; thr < nr_threads; thr++)
1456 			if (data[thr].thr)
1457 				kthread_stop(data[thr].thr);
1458 		vfree(data);
1459 	}
1460 	vfree(page);
1461 
1462 	return ret;
1463 }
1464 
1465 /**
1466  *	swsusp_read - read the hibernation image.
1467  *	@flags_p: flags passed by the "frozen" kernel in the image header should
1468  *		  be written into this memory location
1469  */
1470 
1471 int swsusp_read(unsigned int *flags_p)
1472 {
1473 	int error;
1474 	struct swap_map_handle handle;
1475 	struct snapshot_handle snapshot;
1476 	struct swsusp_info *header;
1477 
1478 	memset(&snapshot, 0, sizeof(struct snapshot_handle));
1479 	error = snapshot_write_next(&snapshot);
1480 	if (error < (int)PAGE_SIZE)
1481 		return error < 0 ? error : -EFAULT;
1482 	header = (struct swsusp_info *)data_of(snapshot);
1483 	error = get_swap_reader(&handle, flags_p);
1484 	if (error)
1485 		goto end;
1486 	if (!error)
1487 		error = swap_read_page(&handle, header, NULL);
1488 	if (!error) {
1489 		error = (*flags_p & SF_NOCOMPRESS_MODE) ?
1490 			load_image(&handle, &snapshot, header->pages - 1) :
1491 			load_image_lzo(&handle, &snapshot, header->pages - 1);
1492 	}
1493 	swap_reader_finish(&handle);
1494 end:
1495 	if (!error)
1496 		pr_debug("Image successfully loaded\n");
1497 	else
1498 		pr_debug("Error %d resuming\n", error);
1499 	return error;
1500 }
1501 
1502 /**
1503  *      swsusp_check - Check for swsusp signature in the resume device
1504  */
1505 
1506 int swsusp_check(void)
1507 {
1508 	int error;
1509 
1510 	hib_resume_bdev = blkdev_get_by_dev(swsusp_resume_device,
1511 					    FMODE_READ, NULL);
1512 	if (!IS_ERR(hib_resume_bdev)) {
1513 		set_blocksize(hib_resume_bdev, PAGE_SIZE);
1514 		clear_page(swsusp_header);
1515 		error = hib_submit_io(REQ_OP_READ, 0,
1516 					swsusp_resume_block,
1517 					swsusp_header, NULL);
1518 		if (error)
1519 			goto put;
1520 
1521 		if (!memcmp(HIBERNATE_SIG, swsusp_header->sig, 10)) {
1522 			memcpy(swsusp_header->sig, swsusp_header->orig_sig, 10);
1523 			/* Reset swap signature now */
1524 			error = hib_submit_io(REQ_OP_WRITE, REQ_SYNC,
1525 						swsusp_resume_block,
1526 						swsusp_header, NULL);
1527 		} else {
1528 			error = -EINVAL;
1529 		}
1530 
1531 put:
1532 		if (error)
1533 			blkdev_put(hib_resume_bdev, FMODE_READ);
1534 		else
1535 			pr_debug("Image signature found, resuming\n");
1536 	} else {
1537 		error = PTR_ERR(hib_resume_bdev);
1538 	}
1539 
1540 	if (error)
1541 		pr_debug("Image not found (code %d)\n", error);
1542 
1543 	return error;
1544 }
1545 
1546 /**
1547  *	swsusp_close - close swap device.
1548  */
1549 
1550 void swsusp_close(fmode_t mode)
1551 {
1552 	if (IS_ERR(hib_resume_bdev)) {
1553 		pr_debug("Image device not initialised\n");
1554 		return;
1555 	}
1556 
1557 	blkdev_put(hib_resume_bdev, mode);
1558 }
1559 
1560 /**
1561  *      swsusp_unmark - Unmark swsusp signature in the resume device
1562  */
1563 
1564 #ifdef CONFIG_SUSPEND
1565 int swsusp_unmark(void)
1566 {
1567 	int error;
1568 
1569 	hib_submit_io(REQ_OP_READ, 0, swsusp_resume_block,
1570 		      swsusp_header, NULL);
1571 	if (!memcmp(HIBERNATE_SIG,swsusp_header->sig, 10)) {
1572 		memcpy(swsusp_header->sig,swsusp_header->orig_sig, 10);
1573 		error = hib_submit_io(REQ_OP_WRITE, REQ_SYNC,
1574 					swsusp_resume_block,
1575 					swsusp_header, NULL);
1576 	} else {
1577 		pr_err("Cannot find swsusp signature!\n");
1578 		error = -ENODEV;
1579 	}
1580 
1581 	/*
1582 	 * We just returned from suspend, we don't need the image any more.
1583 	 */
1584 	free_all_swap_pages(root_swap);
1585 
1586 	return error;
1587 }
1588 #endif
1589 
1590 static int __init swsusp_header_init(void)
1591 {
1592 	swsusp_header = (struct swsusp_header*) __get_free_page(GFP_KERNEL);
1593 	if (!swsusp_header)
1594 		panic("Could not allocate memory for swsusp_header\n");
1595 	return 0;
1596 }
1597 
1598 core_initcall(swsusp_header_init);
1599