xref: /openbsd-src/sys/kern/subr_hibernate.c (revision 4b6eb3216618dce0560dd5e3c93c58808a233578)
1 /*	$OpenBSD: subr_hibernate.c,v 1.69 2013/11/05 07:38:26 mlarkin Exp $	*/
2 
3 /*
4  * Copyright (c) 2011 Ariane van der Steldt <ariane@stack.nl>
5  * Copyright (c) 2011 Mike Larkin <mlarkin@openbsd.org>
6  *
7  * Permission to use, copy, modify, and distribute this software for any
8  * purpose with or without fee is hereby granted, provided that the above
9  * copyright notice and this permission notice appear in all copies.
10  *
11  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
12  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
13  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
14  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
15  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
16  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
17  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18  */
19 
20 #include <sys/hibernate.h>
21 #include <sys/malloc.h>
22 #include <sys/param.h>
23 #include <sys/tree.h>
24 #include <sys/systm.h>
25 #include <sys/disklabel.h>
26 #include <sys/disk.h>
27 #include <sys/conf.h>
28 #include <sys/buf.h>
29 #include <sys/fcntl.h>
30 #include <sys/stat.h>
31 #include <uvm/uvm.h>
32 #include <uvm/uvm_swap.h>
33 #include <machine/hibernate.h>
34 
35 /*
36  * Hibernate piglet layout information
37  *
38  * The piglet is a scratch area of memory allocated by the suspending kernel.
39  * Its phys and virt addrs are recorded in the signature block. The piglet is
40  * used to guarantee an unused area of memory that can be used by the resuming
41  * kernel for various things. The piglet is excluded during unpack operations.
42  * The piglet size is presently 3*HIBERNATE_CHUNK_SIZE (typically 3*4MB).
43  *
44  * Offset from piglet_base	Purpose
45  * ----------------------------------------------------------------------------
46  * 0				I/O page used during resume
47  * 1*PAGE_SIZE		 	I/O page used during hibernate suspend
48  * 2*PAGE_SIZE		 	I/O page used during hibernate suspend
49  * 3*PAGE_SIZE			copy page used during hibernate suspend
50  * 4*PAGE_SIZE			final chunk ordering list (8 pages)
51  * 12*PAGE_SIZE			piglet chunk ordering list (8 pages)
52  * 20*PAGE_SIZE			temp chunk ordering list (8 pages)
53  * 28*PAGE_SIZE			start of hiballoc area
54  * 108*PAGE_SIZE		end of hiballoc area (80 pages)
55  * ...				unused
56  * HIBERNATE_CHUNK_SIZE		start of hibernate chunk table
57  * 2*HIBERNATE_CHUNK_SIZE	bounce area for chunks being unpacked
58  * 3*HIBERNATE_CHUNK_SIZE	end of piglet
59  */
60 
61 /* Temporary vaddr ranges used during hibernate */
62 vaddr_t hibernate_temp_page;
63 vaddr_t hibernate_copy_page;
64 
65 /* Hibernate info as read from disk during resume */
66 union hibernate_info disk_hiber_info;
67 paddr_t global_pig_start;
68 vaddr_t global_piglet_va;
69 
70 /* #define HIB_DEBUG */
71 #ifdef HIB_DEBUG
72 int	hib_debug = 99;
73 #define DPRINTF(x...)     do { if (hib_debug) printf(x); } while (0)
74 #define DNPRINTF(n,x...)  do { if (hib_debug > (n)) printf(x); } while (0)
75 #else
76 #define DPRINTF(x...)
77 #define DNPRINTF(n,x...)
78 #endif
79 
80 void hibernate_copy_chunk_to_piglet(paddr_t, vaddr_t, size_t);
81 
82 /*
83  * Hib alloc enforced alignment.
84  */
85 #define HIB_ALIGN		8 /* bytes alignment */
86 
87 /*
88  * sizeof builtin operation, but with alignment constraint.
89  */
90 #define HIB_SIZEOF(_type)	roundup(sizeof(_type), HIB_ALIGN)
91 
92 struct hiballoc_entry {
93 	size_t			hibe_use;
94 	size_t			hibe_space;
95 	RB_ENTRY(hiballoc_entry) hibe_entry;
96 };
97 
98 /*
99  * Compare hiballoc entries based on the address they manage.
100  *
101  * Since the address is fixed, relative to struct hiballoc_entry,
102  * we just compare the hiballoc_entry pointers.
103  */
104 static __inline int
105 hibe_cmp(struct hiballoc_entry *l, struct hiballoc_entry *r)
106 {
107 	return l < r ? -1 : (l > r);
108 }
109 
110 RB_PROTOTYPE(hiballoc_addr, hiballoc_entry, hibe_entry, hibe_cmp)
111 
112 /*
113  * Given a hiballoc entry, return the address it manages.
114  */
115 static __inline void *
116 hib_entry_to_addr(struct hiballoc_entry *entry)
117 {
118 	caddr_t addr;
119 
120 	addr = (caddr_t)entry;
121 	addr += HIB_SIZEOF(struct hiballoc_entry);
122 	return addr;
123 }
124 
125 /*
126  * Given an address, find the hiballoc that corresponds.
127  */
128 static __inline struct hiballoc_entry*
129 hib_addr_to_entry(void *addr_param)
130 {
131 	caddr_t addr;
132 
133 	addr = (caddr_t)addr_param;
134 	addr -= HIB_SIZEOF(struct hiballoc_entry);
135 	return (struct hiballoc_entry*)addr;
136 }
137 
138 RB_GENERATE(hiballoc_addr, hiballoc_entry, hibe_entry, hibe_cmp)
139 
140 /*
141  * Allocate memory from the arena.
142  *
143  * Returns NULL if no memory is available.
144  */
145 void *
146 hib_alloc(struct hiballoc_arena *arena, size_t alloc_sz)
147 {
148 	struct hiballoc_entry *entry, *new_entry;
149 	size_t find_sz;
150 
151 	/*
152 	 * Enforce alignment of HIB_ALIGN bytes.
153 	 *
154 	 * Note that, because the entry is put in front of the allocation,
155 	 * 0-byte allocations are guaranteed a unique address.
156 	 */
157 	alloc_sz = roundup(alloc_sz, HIB_ALIGN);
158 
159 	/*
160 	 * Find an entry with hibe_space >= find_sz.
161 	 *
162 	 * If the root node is not large enough, we switch to tree traversal.
163 	 * Because all entries are made at the bottom of the free space,
164 	 * traversal from the end has a slightly better chance of yielding
165 	 * a sufficiently large space.
166 	 */
167 	find_sz = alloc_sz + HIB_SIZEOF(struct hiballoc_entry);
168 	entry = RB_ROOT(&arena->hib_addrs);
169 	if (entry != NULL && entry->hibe_space < find_sz) {
170 		RB_FOREACH_REVERSE(entry, hiballoc_addr, &arena->hib_addrs) {
171 			if (entry->hibe_space >= find_sz)
172 				break;
173 		}
174 	}
175 
176 	/*
177 	 * Insufficient or too fragmented memory.
178 	 */
179 	if (entry == NULL)
180 		return NULL;
181 
182 	/*
183 	 * Create new entry in allocated space.
184 	 */
185 	new_entry = (struct hiballoc_entry*)(
186 	    (caddr_t)hib_entry_to_addr(entry) + entry->hibe_use);
187 	new_entry->hibe_space = entry->hibe_space - find_sz;
188 	new_entry->hibe_use = alloc_sz;
189 
190 	/*
191 	 * Insert entry.
192 	 */
193 	if (RB_INSERT(hiballoc_addr, &arena->hib_addrs, new_entry) != NULL)
194 		panic("hib_alloc: insert failure");
195 	entry->hibe_space = 0;
196 
197 	/* Return address managed by entry. */
198 	return hib_entry_to_addr(new_entry);
199 }
200 
201 /*
202  * Free a pointer previously allocated from this arena.
203  *
204  * If addr is NULL, this will be silently accepted.
205  */
206 void
207 hib_free(struct hiballoc_arena *arena, void *addr)
208 {
209 	struct hiballoc_entry *entry, *prev;
210 
211 	if (addr == NULL)
212 		return;
213 
214 	/*
215 	 * Derive entry from addr and check it is really in this arena.
216 	 */
217 	entry = hib_addr_to_entry(addr);
218 	if (RB_FIND(hiballoc_addr, &arena->hib_addrs, entry) != entry)
219 		panic("hib_free: freed item %p not in hib arena", addr);
220 
221 	/*
222 	 * Give the space in entry to its predecessor.
223 	 *
224 	 * If entry has no predecessor, change its used space into free space
225 	 * instead.
226 	 */
227 	prev = RB_PREV(hiballoc_addr, &arena->hib_addrs, entry);
228 	if (prev != NULL &&
229 	    (void *)((caddr_t)prev + HIB_SIZEOF(struct hiballoc_entry) +
230 	    prev->hibe_use + prev->hibe_space) == entry) {
231 		/* Merge entry. */
232 		RB_REMOVE(hiballoc_addr, &arena->hib_addrs, entry);
233 		prev->hibe_space += HIB_SIZEOF(struct hiballoc_entry) +
234 		    entry->hibe_use + entry->hibe_space;
235 	} else {
236 		/* Flip used memory to free space. */
237 		entry->hibe_space += entry->hibe_use;
238 		entry->hibe_use = 0;
239 	}
240 }
241 
242 /*
243  * Initialize hiballoc.
244  *
245  * The allocator will manage memmory at ptr, which is len bytes.
246  */
247 int
248 hiballoc_init(struct hiballoc_arena *arena, void *p_ptr, size_t p_len)
249 {
250 	struct hiballoc_entry *entry;
251 	caddr_t ptr;
252 	size_t len;
253 
254 	RB_INIT(&arena->hib_addrs);
255 
256 	/*
257 	 * Hib allocator enforces HIB_ALIGN alignment.
258 	 * Fixup ptr and len.
259 	 */
260 	ptr = (caddr_t)roundup((vaddr_t)p_ptr, HIB_ALIGN);
261 	len = p_len - ((size_t)ptr - (size_t)p_ptr);
262 	len &= ~((size_t)HIB_ALIGN - 1);
263 
264 	/*
265 	 * Insufficient memory to be able to allocate and also do bookkeeping.
266 	 */
267 	if (len <= HIB_SIZEOF(struct hiballoc_entry))
268 		return ENOMEM;
269 
270 	/*
271 	 * Create entry describing space.
272 	 */
273 	entry = (struct hiballoc_entry*)ptr;
274 	entry->hibe_use = 0;
275 	entry->hibe_space = len - HIB_SIZEOF(struct hiballoc_entry);
276 	RB_INSERT(hiballoc_addr, &arena->hib_addrs, entry);
277 
278 	return 0;
279 }
280 
281 /*
282  * Zero all free memory.
283  */
284 void
285 uvm_pmr_zero_everything(void)
286 {
287 	struct uvm_pmemrange	*pmr;
288 	struct vm_page		*pg;
289 	int			 i;
290 
291 	uvm_lock_fpageq();
292 	TAILQ_FOREACH(pmr, &uvm.pmr_control.use, pmr_use) {
293 		/* Zero single pages. */
294 		while ((pg = TAILQ_FIRST(&pmr->single[UVM_PMR_MEMTYPE_DIRTY]))
295 		    != NULL) {
296 			uvm_pmr_remove(pmr, pg);
297 			uvm_pagezero(pg);
298 			atomic_setbits_int(&pg->pg_flags, PG_ZERO);
299 			uvmexp.zeropages++;
300 			uvm_pmr_insert(pmr, pg, 0);
301 		}
302 
303 		/* Zero multi page ranges. */
304 		while ((pg = RB_ROOT(&pmr->size[UVM_PMR_MEMTYPE_DIRTY]))
305 		    != NULL) {
306 			pg--; /* Size tree always has second page. */
307 			uvm_pmr_remove(pmr, pg);
308 			for (i = 0; i < pg->fpgsz; i++) {
309 				uvm_pagezero(&pg[i]);
310 				atomic_setbits_int(&pg[i].pg_flags, PG_ZERO);
311 				uvmexp.zeropages++;
312 			}
313 			uvm_pmr_insert(pmr, pg, 0);
314 		}
315 	}
316 	uvm_unlock_fpageq();
317 }
318 
319 /*
320  * Mark all memory as dirty.
321  *
322  * Used to inform the system that the clean memory isn't clean for some
323  * reason, for example because we just came back from hibernate.
324  */
325 void
326 uvm_pmr_dirty_everything(void)
327 {
328 	struct uvm_pmemrange	*pmr;
329 	struct vm_page		*pg;
330 	int			 i;
331 
332 	uvm_lock_fpageq();
333 	TAILQ_FOREACH(pmr, &uvm.pmr_control.use, pmr_use) {
334 		/* Dirty single pages. */
335 		while ((pg = TAILQ_FIRST(&pmr->single[UVM_PMR_MEMTYPE_ZERO]))
336 		    != NULL) {
337 			uvm_pmr_remove(pmr, pg);
338 			atomic_clearbits_int(&pg->pg_flags, PG_ZERO);
339 			uvm_pmr_insert(pmr, pg, 0);
340 		}
341 
342 		/* Dirty multi page ranges. */
343 		while ((pg = RB_ROOT(&pmr->size[UVM_PMR_MEMTYPE_ZERO]))
344 		    != NULL) {
345 			pg--; /* Size tree always has second page. */
346 			uvm_pmr_remove(pmr, pg);
347 			for (i = 0; i < pg->fpgsz; i++)
348 				atomic_clearbits_int(&pg[i].pg_flags, PG_ZERO);
349 			uvm_pmr_insert(pmr, pg, 0);
350 		}
351 	}
352 
353 	uvmexp.zeropages = 0;
354 	uvm_unlock_fpageq();
355 }
356 
357 /*
358  * Allocate the highest address that can hold sz.
359  *
360  * sz in bytes.
361  */
362 int
363 uvm_pmr_alloc_pig(paddr_t *addr, psize_t sz)
364 {
365 	struct uvm_pmemrange	*pmr;
366 	struct vm_page		*pig_pg, *pg;
367 
368 	/*
369 	 * Convert sz to pages, since that is what pmemrange uses internally.
370 	 */
371 	sz = atop(round_page(sz));
372 
373 	uvm_lock_fpageq();
374 
375 	TAILQ_FOREACH(pmr, &uvm.pmr_control.use, pmr_use) {
376 		RB_FOREACH_REVERSE(pig_pg, uvm_pmr_addr, &pmr->addr) {
377 			if (pig_pg->fpgsz >= sz) {
378 				goto found;
379 			}
380 		}
381 	}
382 
383 	/*
384 	 * Allocation failure.
385 	 */
386 	uvm_unlock_fpageq();
387 	return ENOMEM;
388 
389 found:
390 	/* Remove page from freelist. */
391 	uvm_pmr_remove_size(pmr, pig_pg);
392 	pig_pg->fpgsz -= sz;
393 	pg = pig_pg + pig_pg->fpgsz;
394 	if (pig_pg->fpgsz == 0)
395 		uvm_pmr_remove_addr(pmr, pig_pg);
396 	else
397 		uvm_pmr_insert_size(pmr, pig_pg);
398 
399 	uvmexp.free -= sz;
400 	*addr = VM_PAGE_TO_PHYS(pg);
401 
402 	/*
403 	 * Update pg flags.
404 	 *
405 	 * Note that we trash the sz argument now.
406 	 */
407 	while (sz > 0) {
408 		KASSERT(pg->pg_flags & PQ_FREE);
409 
410 		atomic_clearbits_int(&pg->pg_flags,
411 		    PG_PMAP0|PG_PMAP1|PG_PMAP2|PG_PMAP3);
412 
413 		if (pg->pg_flags & PG_ZERO)
414 			uvmexp.zeropages -= sz;
415 		atomic_clearbits_int(&pg->pg_flags,
416 		    PG_ZERO|PQ_FREE);
417 
418 		pg->uobject = NULL;
419 		pg->uanon = NULL;
420 		pg->pg_version++;
421 
422 		/*
423 		 * Next.
424 		 */
425 		pg++;
426 		sz--;
427 	}
428 
429 	/* Return. */
430 	uvm_unlock_fpageq();
431 	return 0;
432 }
433 
434 /*
435  * Allocate a piglet area.
436  *
437  * This is as low as possible.
438  * Piglets are aligned.
439  *
440  * sz and align in bytes.
441  *
442  * The call will sleep for the pagedaemon to attempt to free memory.
443  * The pagedaemon may decide its not possible to free enough memory, causing
444  * the allocation to fail.
445  */
446 int
447 uvm_pmr_alloc_piglet(vaddr_t *va, paddr_t *pa, vsize_t sz, paddr_t align)
448 {
449 	paddr_t			 pg_addr, piglet_addr;
450 	struct uvm_pmemrange	*pmr;
451 	struct vm_page		*pig_pg, *pg;
452 	struct pglist		 pageq;
453 	int			 pdaemon_woken;
454 	vaddr_t			 piglet_va;
455 
456 	/* Ensure align is a power of 2 */
457 	KASSERT((align & (align - 1)) == 0);
458 
459 	pdaemon_woken = 0; /* Didn't wake the pagedaemon. */
460 
461 	/*
462 	 * Fixup arguments: align must be at least PAGE_SIZE,
463 	 * sz will be converted to pagecount, since that is what
464 	 * pmemrange uses internally.
465 	 */
466 	if (align < PAGE_SIZE)
467 		align = PAGE_SIZE;
468 	sz = round_page(sz);
469 
470 	uvm_lock_fpageq();
471 
472 	TAILQ_FOREACH_REVERSE(pmr, &uvm.pmr_control.use, uvm_pmemrange_use,
473 	    pmr_use) {
474 retry:
475 		/*
476 		 * Search for a range with enough space.
477 		 * Use the address tree, to ensure the range is as low as
478 		 * possible.
479 		 */
480 		RB_FOREACH(pig_pg, uvm_pmr_addr, &pmr->addr) {
481 			pg_addr = VM_PAGE_TO_PHYS(pig_pg);
482 			piglet_addr = (pg_addr + (align - 1)) & ~(align - 1);
483 
484 			if (atop(pg_addr) + pig_pg->fpgsz >=
485 			    atop(piglet_addr) + atop(sz))
486 				goto found;
487 		}
488 	}
489 
490 	/*
491 	 * Try to coerce the pagedaemon into freeing memory
492 	 * for the piglet.
493 	 *
494 	 * pdaemon_woken is set to prevent the code from
495 	 * falling into an endless loop.
496 	 */
497 	if (!pdaemon_woken) {
498 		pdaemon_woken = 1;
499 		if (uvm_wait_pla(ptoa(pmr->low), ptoa(pmr->high) - 1,
500 		    sz, UVM_PLA_FAILOK) == 0)
501 			goto retry;
502 	}
503 
504 	/* Return failure. */
505 	uvm_unlock_fpageq();
506 	return ENOMEM;
507 
508 found:
509 	/*
510 	 * Extract piglet from pigpen.
511 	 */
512 	TAILQ_INIT(&pageq);
513 	uvm_pmr_extract_range(pmr, pig_pg,
514 	    atop(piglet_addr), atop(piglet_addr) + atop(sz), &pageq);
515 
516 	*pa = piglet_addr;
517 	uvmexp.free -= atop(sz);
518 
519 	/*
520 	 * Update pg flags.
521 	 *
522 	 * Note that we trash the sz argument now.
523 	 */
524 	TAILQ_FOREACH(pg, &pageq, pageq) {
525 		KASSERT(pg->pg_flags & PQ_FREE);
526 
527 		atomic_clearbits_int(&pg->pg_flags,
528 		    PG_PMAP0|PG_PMAP1|PG_PMAP2|PG_PMAP3);
529 
530 		if (pg->pg_flags & PG_ZERO)
531 			uvmexp.zeropages--;
532 		atomic_clearbits_int(&pg->pg_flags,
533 		    PG_ZERO|PQ_FREE);
534 
535 		pg->uobject = NULL;
536 		pg->uanon = NULL;
537 		pg->pg_version++;
538 	}
539 
540 	uvm_unlock_fpageq();
541 
542 	/*
543 	 * Now allocate a va.
544 	 * Use direct mappings for the pages.
545 	 */
546 
547 	piglet_va = *va = (vaddr_t)km_alloc(sz, &kv_any, &kp_none, &kd_waitok);
548 	if (!piglet_va) {
549 		uvm_pglistfree(&pageq);
550 		return ENOMEM;
551 	}
552 
553 	/*
554 	 * Map piglet to va.
555 	 */
556 	TAILQ_FOREACH(pg, &pageq, pageq) {
557 		pmap_kenter_pa(piglet_va, VM_PAGE_TO_PHYS(pg), UVM_PROT_RW);
558 		piglet_va += PAGE_SIZE;
559 	}
560 	pmap_update(pmap_kernel());
561 
562 	return 0;
563 }
564 
565 /*
566  * Free a piglet area.
567  */
568 void
569 uvm_pmr_free_piglet(vaddr_t va, vsize_t sz)
570 {
571 	paddr_t			 pa;
572 	struct vm_page		*pg;
573 
574 	/*
575 	 * Fix parameters.
576 	 */
577 	sz = round_page(sz);
578 
579 	/*
580 	 * Find the first page in piglet.
581 	 * Since piglets are contiguous, the first pg is all we need.
582 	 */
583 	if (!pmap_extract(pmap_kernel(), va, &pa))
584 		panic("uvm_pmr_free_piglet: piglet 0x%lx has no pages", va);
585 	pg = PHYS_TO_VM_PAGE(pa);
586 	if (pg == NULL)
587 		panic("uvm_pmr_free_piglet: unmanaged page 0x%lx", pa);
588 
589 	/*
590 	 * Unmap.
591 	 */
592 	pmap_kremove(va, sz);
593 	pmap_update(pmap_kernel());
594 
595 	/*
596 	 * Free the physical and virtual memory.
597 	 */
598 	uvm_pmr_freepages(pg, atop(sz));
599 	km_free((void *)va, sz, &kv_any, &kp_none);
600 }
601 
602 /*
603  * Physmem RLE compression support.
604  *
605  * Given a physical page address, return the number of pages starting at the
606  * address that are free.  Clamps to the number of pages in
607  * HIBERNATE_CHUNK_SIZE. Returns 0 if the page at addr is not free.
608  */
609 int
610 uvm_page_rle(paddr_t addr)
611 {
612 	struct vm_page		*pg, *pg_end;
613 	struct vm_physseg	*vmp;
614 	int			 pseg_idx, off_idx;
615 
616 	pseg_idx = vm_physseg_find(atop(addr), &off_idx);
617 	if (pseg_idx == -1)
618 		return 0;
619 
620 	vmp = &vm_physmem[pseg_idx];
621 	pg = &vmp->pgs[off_idx];
622 	if (!(pg->pg_flags & PQ_FREE))
623 		return 0;
624 
625 	/*
626 	 * Search for the first non-free page after pg.
627 	 * Note that the page may not be the first page in a free pmemrange,
628 	 * therefore pg->fpgsz cannot be used.
629 	 */
630 	for (pg_end = pg; pg_end <= vmp->lastpg &&
631 	    (pg_end->pg_flags & PQ_FREE) == PQ_FREE; pg_end++)
632 		;
633 	return min((pg_end - pg), HIBERNATE_CHUNK_SIZE/PAGE_SIZE);
634 }
635 
636 /*
637  * Fills out the hibernate_info union pointed to by hiber_info
638  * with information about this machine (swap signature block
639  * offsets, number of memory ranges, kernel in use, etc)
640  */
641 int
642 get_hibernate_info(union hibernate_info *hiber_info, int suspend)
643 {
644 	int chunktable_size;
645 	struct disklabel dl;
646 	char err_string[128], *dl_ret;
647 
648 	/* Determine I/O function to use */
649 	hiber_info->io_func = get_hibernate_io_function();
650 	if (hiber_info->io_func == NULL)
651 		return (1);
652 
653 	/* Calculate hibernate device */
654 	hiber_info->device = swdevt[0].sw_dev;
655 
656 	/* Read disklabel (used to calculate signature and image offsets) */
657 	dl_ret = disk_readlabel(&dl, hiber_info->device, err_string, 128);
658 
659 	if (dl_ret) {
660 		printf("Hibernate error reading disklabel: %s\n", dl_ret);
661 		return (1);
662 	}
663 
664 	/* Make sure we have a swap partition. */
665 	if (dl.d_partitions[1].p_fstype != FS_SWAP ||
666 	    DL_GETPSIZE(&dl.d_partitions[1]) == 0)
667 		return (1);
668 
669 	hiber_info->secsize = dl.d_secsize;
670 
671 	/* Make sure the signature can fit in one block */
672 	if(sizeof(union hibernate_info) > hiber_info->secsize)
673 		return (1);
674 
675 	/* Magic number */
676 	hiber_info->magic = HIBERNATE_MAGIC;
677 
678 	/* Calculate swap offset from start of disk */
679 	hiber_info->swap_offset = dl.d_partitions[1].p_offset;
680 
681 	/* Calculate signature block location */
682 	hiber_info->sig_offset = DL_GETPOFFSET(&dl.d_partitions[1]) +
683 	    DL_GETPSIZE(&dl.d_partitions[1]) -
684 	    sizeof(union hibernate_info)/hiber_info->secsize;
685 
686 	chunktable_size = HIBERNATE_CHUNK_TABLE_SIZE / hiber_info->secsize;
687 
688 	/* Stash kernel version information */
689 	bzero(&hiber_info->kernel_version, 128);
690 	bcopy(version, &hiber_info->kernel_version,
691 	    min(strlen(version), sizeof(hiber_info->kernel_version)-1));
692 
693 	if (suspend) {
694 		/* Allocate piglet region */
695 		if (uvm_pmr_alloc_piglet(&hiber_info->piglet_va,
696 		    &hiber_info->piglet_pa, HIBERNATE_CHUNK_SIZE*3,
697 		    HIBERNATE_CHUNK_SIZE)) {
698 			printf("Hibernate failed to allocate the piglet\n");
699 			return (1);
700 		}
701 		hiber_info->io_page = (void *)hiber_info->piglet_va;
702 
703 		/*
704 		 * Initialization of the hibernate IO function for drivers
705 		 * that need to do prep work (such as allocating memory or
706 		 * setting up data structures that cannot safely be done
707 		 * during suspend without causing side effects). There is
708 		 * a matching HIB_DONE call performed after the write is
709 		 * completed.
710 		 */
711 		if (hiber_info->io_func(hiber_info->device, 0,
712 		    (vaddr_t)NULL, 0, HIB_INIT, hiber_info->io_page))
713 			goto fail;
714 
715 	} else {
716 		/*
717 		 * Resuming kernels use a regular I/O page since we won't
718 		 * have access to the suspended kernel's piglet VA at this
719 		 * point. No need to free this I/O page as it will vanish
720 		 * as part of the resume.
721 		 */
722 		hiber_info->io_page = malloc(PAGE_SIZE, M_DEVBUF, M_NOWAIT);
723 		if (!hiber_info->io_page)
724 			return (1);
725 	}
726 
727 
728 	if (get_hibernate_info_md(hiber_info))
729 		goto fail;
730 
731 
732 	return (0);
733 fail:
734 	if (suspend)
735 		uvm_pmr_free_piglet(hiber_info->piglet_va,
736 		    HIBERNATE_CHUNK_SIZE * 3);
737 
738 	return (1);
739 }
740 
741 /*
742  * Allocate nitems*size bytes from the hiballoc area presently in use
743  */
744 void *
745 hibernate_zlib_alloc(void *unused, int nitems, int size)
746 {
747 	struct hibernate_zlib_state *hibernate_state;
748 
749 	hibernate_state =
750 	    (struct hibernate_zlib_state *)HIBERNATE_HIBALLOC_PAGE;
751 
752 	return hib_alloc(&hibernate_state->hiballoc_arena, nitems*size);
753 }
754 
755 /*
756  * Free the memory pointed to by addr in the hiballoc area presently in
757  * use
758  */
759 void
760 hibernate_zlib_free(void *unused, void *addr)
761 {
762 	struct hibernate_zlib_state *hibernate_state;
763 
764 	hibernate_state =
765 	    (struct hibernate_zlib_state *)HIBERNATE_HIBALLOC_PAGE;
766 
767 	hib_free(&hibernate_state->hiballoc_arena, addr);
768 }
769 
770 /*
771  * Gets the next RLE value from the image stream
772  */
773 int
774 hibernate_get_next_rle(void)
775 {
776 	int rle, i;
777 	struct hibernate_zlib_state *hibernate_state;
778 
779 	hibernate_state =
780 	    (struct hibernate_zlib_state *)HIBERNATE_HIBALLOC_PAGE;
781 
782 	/* Read RLE code */
783 	hibernate_state->hib_stream.next_out = (char *)&rle;
784 	hibernate_state->hib_stream.avail_out = sizeof(rle);
785 
786 	i = inflate(&hibernate_state->hib_stream, Z_FULL_FLUSH);
787 	if (i != Z_OK && i != Z_STREAM_END) {
788 		/*
789 		 * XXX - this will likely reboot/hang most machines
790 		 *       since the console output buffer will be unmapped,
791 		 *       but there's not much else we can do here.
792 		 */
793 		panic("inflate rle error");
794 	}
795 
796 	/* Sanity check what RLE value we got */
797 	if (rle > HIBERNATE_CHUNK_SIZE/PAGE_SIZE || rle < 0)
798 		panic("invalid RLE code");
799 
800 	if (i == Z_STREAM_END)
801 		rle = -1;
802 
803 	return rle;
804 }
805 
806 /*
807  * Inflate next page of data from the image stream
808  */
809 int
810 hibernate_inflate_page(void)
811 {
812 	struct hibernate_zlib_state *hibernate_state;
813 	int i;
814 
815 	hibernate_state =
816 	    (struct hibernate_zlib_state *)HIBERNATE_HIBALLOC_PAGE;
817 
818 	/* Set up the stream for inflate */
819 	hibernate_state->hib_stream.next_out = (char *)HIBERNATE_INFLATE_PAGE;
820 	hibernate_state->hib_stream.avail_out = PAGE_SIZE;
821 
822 	/* Process next block of data */
823 	i = inflate(&hibernate_state->hib_stream, Z_PARTIAL_FLUSH);
824 	if (i != Z_OK && i != Z_STREAM_END) {
825 		/*
826 		 * XXX - this will likely reboot/hang most machines
827 		 *       since the console output buffer will be unmapped,
828 		 *       but there's not much else we can do here.
829 		 */
830 		panic("inflate error");
831 	}
832 
833 	/* We should always have extracted a full page ... */
834 	if (hibernate_state->hib_stream.avail_out != 0) {
835 		/*
836 		 * XXX - this will likely reboot/hang most machines
837 		 *       since the console output buffer will be unmapped,
838 		 *       but there's not much else we can do here.
839 		 */
840 		panic("incomplete page");
841 	}
842 
843 	return (i == Z_STREAM_END);
844 }
845 
846 /*
847  * Inflate size bytes from src into dest, skipping any pages in
848  * [src..dest] that are special (see hibernate_inflate_skip)
849  *
850  * This function executes while using the resume-time stack
851  * and pmap, and therefore cannot use ddb/printf/etc. Doing so
852  * will likely hang or reset the machine since the console output buffer
853  * will be unmapped.
854  */
855 void
856 hibernate_inflate_region(union hibernate_info *hiber_info, paddr_t dest,
857     paddr_t src, size_t size)
858 {
859 	int end_stream = 0 ;
860 	struct hibernate_zlib_state *hibernate_state;
861 
862 	hibernate_state =
863 	    (struct hibernate_zlib_state *)HIBERNATE_HIBALLOC_PAGE;
864 
865 	hibernate_state->hib_stream.next_in = (char *)src;
866 	hibernate_state->hib_stream.avail_in = size;
867 
868 	do {
869 		/* Flush cache and TLB */
870 		hibernate_flush();
871 
872 		/*
873 		 * Is this a special page? If yes, redirect the
874 		 * inflate output to a scratch page (eg, discard it)
875 		 */
876 		if (hibernate_inflate_skip(hiber_info, dest)) {
877 			hibernate_enter_resume_mapping(
878 			    HIBERNATE_INFLATE_PAGE,
879 			    HIBERNATE_INFLATE_PAGE, 0);
880 		} else {
881 			hibernate_enter_resume_mapping(
882 			    HIBERNATE_INFLATE_PAGE, dest, 0);
883 		}
884 
885 		hibernate_flush();
886 		end_stream = hibernate_inflate_page();
887 
888 		dest += PAGE_SIZE;
889 	} while (!end_stream);
890 }
891 
892 /*
893  * deflate from src into the I/O page, up to 'remaining' bytes
894  *
895  * Returns number of input bytes consumed, and may reset
896  * the 'remaining' parameter if not all the output space was consumed
897  * (this information is needed to know how much to write to disk
898  */
899 size_t
900 hibernate_deflate(union hibernate_info *hiber_info, paddr_t src,
901     size_t *remaining)
902 {
903 	vaddr_t hibernate_io_page = hiber_info->piglet_va + PAGE_SIZE;
904 	struct hibernate_zlib_state *hibernate_state;
905 
906 	hibernate_state =
907 	    (struct hibernate_zlib_state *)HIBERNATE_HIBALLOC_PAGE;
908 
909 	/* Set up the stream for deflate */
910 	hibernate_state->hib_stream.next_in = (caddr_t)src;
911 	hibernate_state->hib_stream.avail_in = PAGE_SIZE - (src & PAGE_MASK);
912 	hibernate_state->hib_stream.next_out = (caddr_t)hibernate_io_page +
913 	    (PAGE_SIZE - *remaining);
914 	hibernate_state->hib_stream.avail_out = *remaining;
915 
916 	/* Process next block of data */
917 	if (deflate(&hibernate_state->hib_stream, Z_PARTIAL_FLUSH) != Z_OK)
918 		panic("hibernate zlib deflate error");
919 
920 	/* Update pointers and return number of bytes consumed */
921 	*remaining = hibernate_state->hib_stream.avail_out;
922 	return (PAGE_SIZE - (src & PAGE_MASK)) -
923 	    hibernate_state->hib_stream.avail_in;
924 }
925 
926 /*
927  * Write the hibernation information specified in hiber_info
928  * to the location in swap previously calculated (last block of
929  * swap), called the "signature block".
930  */
931 int
932 hibernate_write_signature(union hibernate_info *hiber_info)
933 {
934 	/* Write hibernate info to disk */
935 	return (hiber_info->io_func(hiber_info->device, hiber_info->sig_offset,
936 	    (vaddr_t)hiber_info, hiber_info->secsize, HIB_W,
937 	    hiber_info->io_page));
938 }
939 
940 /*
941  * Write the memory chunk table to the area in swap immediately
942  * preceding the signature block. The chunk table is stored
943  * in the piglet when this function is called.
944  *
945  * Return values:
946  *
947  * 0   -  success
948  * EIO -  I/O error writing the chunktable
949  */
950 int
951 hibernate_write_chunktable(union hibernate_info *hiber_info)
952 {
953 	struct hibernate_disk_chunk *chunks;
954 	vaddr_t hibernate_chunk_table_start;
955 	size_t hibernate_chunk_table_size;
956 	daddr_t chunkbase;
957 	int i, err;
958 
959 	hibernate_chunk_table_size = HIBERNATE_CHUNK_TABLE_SIZE;
960 
961 	chunkbase = hiber_info->sig_offset -
962 	    (hibernate_chunk_table_size / hiber_info->secsize);
963 
964 	hibernate_chunk_table_start = hiber_info->piglet_va +
965 	    HIBERNATE_CHUNK_SIZE;
966 
967 	chunks = (struct hibernate_disk_chunk *)(hiber_info->piglet_va +
968 	    HIBERNATE_CHUNK_SIZE);
969 
970 	/* Write chunk table */
971 	for (i = 0; i < hibernate_chunk_table_size; i += MAXPHYS) {
972 		if ((err = hiber_info->io_func(hiber_info->device,
973 		    chunkbase + (i/hiber_info->secsize),
974 		    (vaddr_t)(hibernate_chunk_table_start + i),
975 		    MAXPHYS, HIB_W, hiber_info->io_page))) {
976 			DPRINTF("chunktable write error: %d\n", err);
977 			return (EIO);
978 		}
979 	}
980 
981 	return (0);
982 }
983 
984 /*
985  * Write an empty hiber_info to the swap signature block, which is
986  * guaranteed to not match any valid hiber_info.
987  */
988 int
989 hibernate_clear_signature(void)
990 {
991 	union hibernate_info blank_hiber_info;
992 	union hibernate_info hiber_info;
993 
994 	/* Zero out a blank hiber_info */
995 	bzero(&blank_hiber_info, sizeof(union hibernate_info));
996 
997 	/* Get the signature block location */
998 	if (get_hibernate_info(&hiber_info, 0))
999 		return (1);
1000 
1001 	/* Write (zeroed) hibernate info to disk */
1002 	DPRINTF("clearing hibernate signature block location: %lld\n",
1003 		hiber_info.sig_offset - hiber_info.swap_offset);
1004 	if (hibernate_block_io(&hiber_info,
1005 	    hiber_info.sig_offset - hiber_info.swap_offset,
1006 	    hiber_info.secsize, (vaddr_t)&blank_hiber_info, 1))
1007 		printf("Warning: could not clear hibernate signature\n");
1008 
1009 	return (0);
1010 }
1011 
1012 /*
1013  * Check chunk range overlap when calculating whether or not to copy a
1014  * compressed chunk to the piglet area before decompressing.
1015  *
1016  * returns zero if the ranges do not overlap, non-zero otherwise.
1017  */
1018 int
1019 hibernate_check_overlap(paddr_t r1s, paddr_t r1e, paddr_t r2s, paddr_t r2e)
1020 {
1021 	/* case A : end of r1 overlaps start of r2 */
1022 	if (r1s < r2s && r1e > r2s)
1023 		return (1);
1024 
1025 	/* case B : r1 entirely inside r2 */
1026 	if (r1s >= r2s && r1e <= r2e)
1027 		return (1);
1028 
1029 	/* case C : r2 entirely inside r1 */
1030 	if (r2s >= r1s && r2e <= r1e)
1031 		return (1);
1032 
1033 	/* case D : end of r2 overlaps start of r1 */
1034 	if (r2s < r1s && r2e > r1s)
1035 		return (1);
1036 
1037 	return (0);
1038 }
1039 
1040 /*
1041  * Compare two hibernate_infos to determine if they are the same (eg,
1042  * we should be performing a hibernate resume on this machine.
1043  * Not all fields are checked - just enough to verify that the machine
1044  * has the same memory configuration and kernel as the one that
1045  * wrote the signature previously.
1046  */
1047 int
1048 hibernate_compare_signature(union hibernate_info *mine,
1049     union hibernate_info *disk)
1050 {
1051 	u_int i;
1052 
1053 	if (mine->nranges != disk->nranges) {
1054 		DPRINTF("hibernate memory range count mismatch\n");
1055 		return (1);
1056 	}
1057 
1058 	if (strcmp(mine->kernel_version, disk->kernel_version) != 0) {
1059 		DPRINTF("hibernate kernel version mismatch\n");
1060 		return (1);
1061 	}
1062 
1063 	for (i = 0; i < mine->nranges; i++) {
1064 		if ((mine->ranges[i].base != disk->ranges[i].base) ||
1065 		    (mine->ranges[i].end != disk->ranges[i].end) ) {
1066 			DPRINTF("hib range %d mismatch [%p-%p != %p-%p]\n",
1067 				i, mine->ranges[i].base, mine->ranges[i].end,
1068 				disk->ranges[i].base, disk->ranges[i].end);
1069 			return (1);
1070 		}
1071 	}
1072 
1073 	return (0);
1074 }
1075 
1076 /*
1077  * Transfers xfer_size bytes between the hibernate device specified in
1078  * hib_info at offset blkctr and the vaddr specified at dest.
1079  *
1080  * Separate offsets and pages are used to handle misaligned reads (reads
1081  * that span a page boundary).
1082  *
1083  * blkctr specifies a relative offset (relative to the start of swap),
1084  * not an absolute disk offset
1085  *
1086  */
1087 int
1088 hibernate_block_io(union hibernate_info *hib_info, daddr_t blkctr,
1089     size_t xfer_size, vaddr_t dest, int iswrite)
1090 {
1091 	struct buf *bp;
1092 	struct bdevsw *bdsw;
1093 	int error;
1094 
1095 	bp = geteblk(xfer_size);
1096 	bdsw = &bdevsw[major(hib_info->device)];
1097 
1098 	error = (*bdsw->d_open)(hib_info->device, FREAD, S_IFCHR, curproc);
1099 	if (error) {
1100 		printf("hibernate_block_io open failed\n");
1101 		return (1);
1102 	}
1103 
1104 	if (iswrite)
1105 		bcopy((caddr_t)dest, bp->b_data, xfer_size);
1106 
1107 	bp->b_bcount = xfer_size;
1108 	bp->b_blkno = blkctr;
1109 	CLR(bp->b_flags, B_READ | B_WRITE | B_DONE);
1110 	SET(bp->b_flags, B_BUSY | (iswrite ? B_WRITE : B_READ) | B_RAW);
1111 	bp->b_dev = hib_info->device;
1112 	bp->b_cylinder = 0;
1113 	(*bdsw->d_strategy)(bp);
1114 
1115 	error = biowait(bp);
1116 	if (error) {
1117 		printf("hib block_io biowait error %d blk %lld size %zu\n",
1118 			error, (long long)blkctr, xfer_size);
1119 		error = (*bdsw->d_close)(hib_info->device, 0, S_IFCHR,
1120 		    curproc);
1121 		if (error)
1122 			printf("hibernate_block_io error close failed\n");
1123 		return (1);
1124 	}
1125 
1126 	error = (*bdsw->d_close)(hib_info->device, FREAD, S_IFCHR, curproc);
1127 	if (error) {
1128 		printf("hibernate_block_io close failed\n");
1129 		return (1);
1130 	}
1131 
1132 	if (!iswrite)
1133 		bcopy(bp->b_data, (caddr_t)dest, xfer_size);
1134 
1135 	bp->b_flags |= B_INVAL;
1136 	brelse(bp);
1137 
1138 	return (0);
1139 }
1140 
1141 /*
1142  * Reads the signature block from swap, checks against the current machine's
1143  * information. If the information matches, perform a resume by reading the
1144  * saved image into the pig area, and unpacking.
1145  */
1146 void
1147 hibernate_resume(void)
1148 {
1149 	union hibernate_info hiber_info;
1150 	int s;
1151 
1152 	/* Get current running machine's hibernate info */
1153 	bzero(&hiber_info, sizeof(hiber_info));
1154 	if (get_hibernate_info(&hiber_info, 0)) {
1155 		DPRINTF("couldn't retrieve machine's hibernate info\n");
1156 		return;
1157 	}
1158 
1159 	/* Read hibernate info from disk */
1160 	s = splbio();
1161 
1162 	DPRINTF("reading hibernate signature block location: %lld\n",
1163 		hiber_info.sig_offset - hiber_info.swap_offset);
1164 
1165 	if (hibernate_block_io(&hiber_info,
1166 	    hiber_info.sig_offset - hiber_info.swap_offset,
1167 	    hiber_info.secsize, (vaddr_t)&disk_hiber_info, 0)) {
1168 		DPRINTF("error in hibernate read");
1169 		splx(s);
1170 		return;
1171 	}
1172 
1173 	/* Check magic number */
1174 	if (disk_hiber_info.magic != HIBERNATE_MAGIC) {
1175 		DPRINTF("wrong magic number in hibernate signature: %x\n",
1176 			disk_hiber_info.magic);
1177 		splx(s);
1178 		return;
1179 	}
1180 
1181 	/*
1182 	 * We (possibly) found a hibernate signature. Clear signature first,
1183 	 * to prevent accidental resume or endless resume cycles later.
1184 	 */
1185 	if (hibernate_clear_signature()) {
1186 		DPRINTF("error clearing hibernate signature block\n");
1187 		splx(s);
1188 		return;
1189 	}
1190 
1191 	/*
1192 	 * If on-disk and in-memory hibernate signatures match,
1193 	 * this means we should do a resume from hibernate.
1194 	 */
1195 	if (hibernate_compare_signature(&hiber_info, &disk_hiber_info)) {
1196 		DPRINTF("mismatched hibernate signature block\n");
1197 		splx(s);
1198 		return;
1199 	}
1200 
1201 #ifdef MULTIPROCESSOR
1202 	hibernate_quiesce_cpus();
1203 #endif /* MULTIPROCESSOR */
1204 
1205 	/* Read the image from disk into the image (pig) area */
1206 	if (hibernate_read_image(&disk_hiber_info))
1207 		goto fail;
1208 
1209 	if (config_suspend(TAILQ_FIRST(&alldevs), DVACT_QUIESCE) != 0)
1210 		goto fail;
1211 
1212 	(void) splhigh();
1213 	hibernate_disable_intr_machdep();
1214 	cold = 1;
1215 
1216 	if (config_suspend(TAILQ_FIRST(&alldevs), DVACT_SUSPEND) != 0) {
1217 		cold = 0;
1218 		hibernate_enable_intr_machdep();
1219 		goto fail;
1220 	}
1221 
1222 	pmap_kenter_pa(HIBERNATE_HIBALLOC_PAGE, HIBERNATE_HIBALLOC_PAGE,
1223 	    VM_PROT_ALL);
1224 	pmap_activate(curproc);
1225 
1226 	printf("Unpacking image...\n");
1227 
1228 	/* Switch stacks */
1229 	hibernate_switch_stack_machdep();
1230 
1231 	/* Unpack and resume */
1232 	hibernate_unpack_image(&disk_hiber_info);
1233 
1234 fail:
1235 	splx(s);
1236 	printf("\nUnable to resume hibernated image\n");
1237 }
1238 
1239 /*
1240  * Unpack image from pig area to original location by looping through the
1241  * list of output chunks in the order they should be restored (fchunks).
1242  *
1243  * Note that due to the stack smash protector and the fact that we have
1244  * switched stacks, it is not permitted to return from this function.
1245  */
1246 void
1247 hibernate_unpack_image(union hibernate_info *hiber_info)
1248 {
1249 	struct hibernate_disk_chunk *chunks;
1250 	union hibernate_info local_hiber_info;
1251 	paddr_t image_cur = global_pig_start;
1252 	short i, *fchunks;
1253 	char *pva = (char *)hiber_info->piglet_va;
1254 	struct hibernate_zlib_state *hibernate_state;
1255 
1256 	hibernate_state =
1257 	    (struct hibernate_zlib_state *)HIBERNATE_HIBALLOC_PAGE;
1258 
1259 	/* Mask off based on arch-specific piglet page size */
1260 	pva = (char *)((paddr_t)pva & (PIGLET_PAGE_MASK));
1261 	fchunks = (short *)(pva + (4 * PAGE_SIZE));
1262 
1263 	chunks = (struct hibernate_disk_chunk *)(pva +  HIBERNATE_CHUNK_SIZE);
1264 
1265 	/* Can't use hiber_info that's passed in after this point */
1266 	bcopy(hiber_info, &local_hiber_info, sizeof(union hibernate_info));
1267 
1268 	/*
1269 	 * Point of no return. Once we pass this point, only kernel code can
1270 	 * be accessed. No global variables or other kernel data structures
1271 	 * are guaranteed to be coherent after unpack starts.
1272 	 *
1273 	 * The image is now in high memory (pig area), we unpack from the pig
1274 	 * to the correct location in memory. We'll eventually end up copying
1275 	 * on top of ourself, but we are assured the kernel code here is the
1276 	 * same between the hibernated and resuming kernel, and we are running
1277 	 * on our own stack, so the overwrite is ok.
1278 	 */
1279 	hibernate_activate_resume_pt_machdep();
1280 
1281 	for (i = 0; i < local_hiber_info.chunk_ctr; i++) {
1282 		/* Reset zlib for inflate */
1283 		if (hibernate_zlib_reset(&local_hiber_info, 0) != Z_OK)
1284 			panic("hibernate failed to reset zlib for inflate");
1285 
1286 		hibernate_process_chunk(&local_hiber_info, &chunks[fchunks[i]],
1287 		    image_cur);
1288 
1289 		image_cur += chunks[fchunks[i]].compressed_size;
1290 
1291 	}
1292 
1293 	/*
1294 	 * Resume the loaded kernel by jumping to the MD resume vector.
1295 	 * We won't be returning from this call.
1296 	 */
1297 	hibernate_resume_machdep();
1298 }
1299 
1300 /*
1301  * Bounce a compressed image chunk to the piglet, entering mappings for the
1302  * copied pages as needed
1303  */
1304 void
1305 hibernate_copy_chunk_to_piglet(paddr_t img_cur, vaddr_t piglet, size_t size)
1306 {
1307 	size_t ct, ofs;
1308 	paddr_t src = img_cur;
1309 	vaddr_t dest = piglet;
1310 
1311 	/* Copy first partial page */
1312 	ct = (PAGE_SIZE) - (src & PAGE_MASK);
1313 	ofs = (src & PAGE_MASK);
1314 
1315 	if (ct < PAGE_SIZE) {
1316 		hibernate_enter_resume_mapping(HIBERNATE_INFLATE_PAGE,
1317 			(src - ofs), 0);
1318 		hibernate_flush();
1319 		bcopy((caddr_t)(HIBERNATE_INFLATE_PAGE + ofs), (caddr_t)dest, ct);
1320 		src += ct;
1321 		dest += ct;
1322 	}
1323 	wbinvd();
1324 
1325 	/* Copy remaining pages */
1326 	while (src < size + img_cur) {
1327 		hibernate_enter_resume_mapping(HIBERNATE_INFLATE_PAGE, src, 0);
1328 		hibernate_flush();
1329 		ct = PAGE_SIZE;
1330 		bcopy((caddr_t)(HIBERNATE_INFLATE_PAGE), (caddr_t)dest, ct);
1331 		hibernate_flush();
1332 		src += ct;
1333 		dest += ct;
1334 	}
1335 
1336 	hibernate_flush();
1337 	wbinvd();
1338 }
1339 
1340 /*
1341  * Process a chunk by bouncing it to the piglet, followed by unpacking
1342  */
1343 void
1344 hibernate_process_chunk(union hibernate_info *hiber_info,
1345     struct hibernate_disk_chunk *chunk, paddr_t img_cur)
1346 {
1347 	char *pva = (char *)hiber_info->piglet_va;
1348 
1349 	hibernate_copy_chunk_to_piglet(img_cur,
1350 	 (vaddr_t)(pva + (HIBERNATE_CHUNK_SIZE * 2)), chunk->compressed_size);
1351 
1352 	hibernate_inflate_region(hiber_info, chunk->base,
1353 	    (vaddr_t)(pva + (HIBERNATE_CHUNK_SIZE * 2)),
1354 	    chunk->compressed_size);
1355 }
1356 
1357 /*
1358  * Write a compressed version of this machine's memory to disk, at the
1359  * precalculated swap offset:
1360  *
1361  * end of swap - signature block size - chunk table size - memory size
1362  *
1363  * The function begins by looping through each phys mem range, cutting each
1364  * one into MD sized chunks. These chunks are then compressed individually
1365  * and written out to disk, in phys mem order. Some chunks might compress
1366  * more than others, and for this reason, each chunk's size is recorded
1367  * in the chunk table, which is written to disk after the image has
1368  * properly been compressed and written (in hibernate_write_chunktable).
1369  *
1370  * When this function is called, the machine is nearly suspended - most
1371  * devices are quiesced/suspended, interrupts are off, and cold has
1372  * been set. This means that there can be no side effects once the
1373  * write has started, and the write function itself can also have no
1374  * side effects. This also means no printfs are permitted (since printf
1375  * has side effects.)
1376  *
1377  * Return values :
1378  *
1379  * 0      - success
1380  * EIO    - I/O error occurred writing the chunks
1381  * EINVAL - Failed to write a complete range
1382  * ENOMEM - Memory allocation failure during preparation of the zlib arena
1383  */
1384 int
1385 hibernate_write_chunks(union hibernate_info *hiber_info)
1386 {
1387 	paddr_t range_base, range_end, inaddr, temp_inaddr;
1388 	size_t nblocks, out_remaining, used;
1389 	struct hibernate_disk_chunk *chunks;
1390 	vaddr_t hibernate_io_page = hiber_info->piglet_va + PAGE_SIZE;
1391 	daddr_t blkctr = hiber_info->image_offset, offset = 0;
1392 	int i, err;
1393 	struct hibernate_zlib_state *hibernate_state;
1394 
1395 	hibernate_state =
1396 	    (struct hibernate_zlib_state *)HIBERNATE_HIBALLOC_PAGE;
1397 
1398 	hiber_info->chunk_ctr = 0;
1399 
1400 	/*
1401 	 * Allocate VA for the temp and copy page.
1402 	 *
1403 	 * These will become part of the suspended kernel and will
1404 	 * be freed in hibernate_free, upon resume.
1405 	 */
1406 	hibernate_temp_page = (vaddr_t)km_alloc(PAGE_SIZE, &kv_any,
1407 	    &kp_none, &kd_nowait);
1408 	if (!hibernate_temp_page)
1409 		return (ENOMEM);
1410 
1411 	hibernate_copy_page = (vaddr_t)km_alloc(PAGE_SIZE, &kv_any,
1412 	    &kp_none, &kd_nowait);
1413 	if (!hibernate_copy_page) {
1414 		DPRINTF("out of memory allocating hibernate_copy_page\n");
1415 		return (ENOMEM);
1416 	}
1417 
1418 	pmap_kenter_pa(hibernate_copy_page,
1419 	    (hiber_info->piglet_pa + 3*PAGE_SIZE), VM_PROT_ALL);
1420 
1421 	pmap_activate(curproc);
1422 
1423 	chunks = (struct hibernate_disk_chunk *)(hiber_info->piglet_va +
1424 	    HIBERNATE_CHUNK_SIZE);
1425 
1426 	/* Calculate the chunk regions */
1427 	for (i = 0; i < hiber_info->nranges; i++) {
1428 		range_base = hiber_info->ranges[i].base;
1429 		range_end = hiber_info->ranges[i].end;
1430 
1431 		inaddr = range_base;
1432 
1433 		while (inaddr < range_end) {
1434 			chunks[hiber_info->chunk_ctr].base = inaddr;
1435 			if (inaddr + HIBERNATE_CHUNK_SIZE < range_end)
1436 				chunks[hiber_info->chunk_ctr].end = inaddr +
1437 				    HIBERNATE_CHUNK_SIZE;
1438 			else
1439 				chunks[hiber_info->chunk_ctr].end = range_end;
1440 
1441 			inaddr += HIBERNATE_CHUNK_SIZE;
1442 			hiber_info->chunk_ctr ++;
1443 		}
1444 	}
1445 
1446 	/* Compress and write the chunks in the chunktable */
1447 	for (i = 0; i < hiber_info->chunk_ctr; i++) {
1448 		range_base = chunks[i].base;
1449 		range_end = chunks[i].end;
1450 
1451 		chunks[i].offset = blkctr;
1452 
1453 		/* Reset zlib for deflate */
1454 		if (hibernate_zlib_reset(hiber_info, 1) != Z_OK) {
1455 			DPRINTF("hibernate_zlib_reset failed for deflate\n");
1456 			return (ENOMEM);
1457 		}
1458 
1459 		inaddr = range_base;
1460 
1461 		/*
1462 		 * For each range, loop through its phys mem region
1463 		 * and write out the chunks (the last chunk might be
1464 		 * smaller than the chunk size).
1465 		 */
1466 		while (inaddr < range_end) {
1467 			out_remaining = PAGE_SIZE;
1468 			while (out_remaining > 0 && inaddr < range_end) {
1469 
1470 				/*
1471 				 * Adjust for regions that are not evenly
1472 				 * divisible by PAGE_SIZE or overflowed
1473 				 * pages from the previous iteration.
1474 				 */
1475 				temp_inaddr = (inaddr & PAGE_MASK) +
1476 				    hibernate_copy_page;
1477 
1478 				/* Deflate from temp_inaddr to IO page */
1479 				if (inaddr != range_end) {
1480 					pmap_kenter_pa(hibernate_temp_page,
1481 					    inaddr & PMAP_PA_MASK, VM_PROT_ALL);
1482 
1483 					pmap_activate(curproc);
1484 
1485 					bcopy((caddr_t)hibernate_temp_page,
1486 					    (caddr_t)hibernate_copy_page,
1487 					    PAGE_SIZE);
1488 					inaddr += hibernate_deflate(hiber_info,
1489 					    temp_inaddr, &out_remaining);
1490 				}
1491 
1492 				if (out_remaining == 0) {
1493 					/* Filled up the page */
1494 					nblocks =
1495 					    PAGE_SIZE / hiber_info->secsize;
1496 
1497 					if ((err = hiber_info->io_func(
1498 					    hiber_info->device,
1499 					    blkctr, (vaddr_t)hibernate_io_page,
1500 					    PAGE_SIZE, HIB_W,
1501 					    hiber_info->io_page))) {
1502 						DPRINTF("hib write error %d\n",
1503 							err);
1504 						return (EIO);
1505 					}
1506 
1507 					blkctr += nblocks;
1508 				}
1509 			}
1510 		}
1511 
1512 		if (inaddr != range_end) {
1513 			DPRINTF("deflate range ended prematurely\n");
1514 			return (EINVAL);
1515 		}
1516 
1517 		/*
1518 		 * End of range. Round up to next secsize bytes
1519 		 * after finishing compress
1520 		 */
1521 		if (out_remaining == 0)
1522 			out_remaining = PAGE_SIZE;
1523 
1524 		/* Finish compress */
1525 		hibernate_state->hib_stream.next_in = (caddr_t)inaddr;
1526 		hibernate_state->hib_stream.avail_in = 0;
1527 		hibernate_state->hib_stream.next_out =
1528 		    (caddr_t)hibernate_io_page + (PAGE_SIZE - out_remaining);
1529 
1530 		/* We have an extra output page available for finalize */
1531 		hibernate_state->hib_stream.avail_out =
1532 			out_remaining + PAGE_SIZE;
1533 
1534 		if ((err = deflate(&hibernate_state->hib_stream, Z_FINISH)) !=
1535 		    Z_STREAM_END) {
1536 			DPRINTF("deflate error in output stream: %d\n", err);
1537 			return (EIO);
1538 		}
1539 
1540 		out_remaining = hibernate_state->hib_stream.avail_out;
1541 
1542 		used = 2*PAGE_SIZE - out_remaining;
1543 		nblocks = used / hiber_info->secsize;
1544 
1545 		/* Round up to next block if needed */
1546 		if (used % hiber_info->secsize != 0)
1547 			nblocks ++;
1548 
1549 		/* Write final block(s) for this chunk */
1550 		if ((err = hiber_info->io_func(hiber_info->device, blkctr,
1551 		    (vaddr_t)hibernate_io_page, nblocks*hiber_info->secsize,
1552 		    HIB_W, hiber_info->io_page))) {
1553 			DPRINTF("hib final write error %d\n", err);
1554 			return (EIO);
1555 		}
1556 
1557 		blkctr += nblocks;
1558 
1559 		offset = blkctr;
1560 		chunks[i].compressed_size = (offset - chunks[i].offset) *
1561 		    hiber_info->secsize;
1562 	}
1563 
1564 	return (0);
1565 }
1566 
1567 /*
1568  * Reset the zlib stream state and allocate a new hiballoc area for either
1569  * inflate or deflate. This function is called once for each hibernate chunk.
1570  * Calling hiballoc_init multiple times is acceptable since the memory it is
1571  * provided is unmanaged memory (stolen). We use the memory provided to us
1572  * by the piglet allocated via the supplied hiber_info.
1573  */
1574 int
1575 hibernate_zlib_reset(union hibernate_info *hiber_info, int deflate)
1576 {
1577 	vaddr_t hibernate_zlib_start;
1578 	size_t hibernate_zlib_size;
1579 	char *pva = (char *)hiber_info->piglet_va;
1580 	struct hibernate_zlib_state *hibernate_state;
1581 
1582 	hibernate_state =
1583 	    (struct hibernate_zlib_state *)HIBERNATE_HIBALLOC_PAGE;
1584 
1585 	if(!deflate)
1586 		pva = (char *)((paddr_t)pva & (PIGLET_PAGE_MASK));
1587 
1588 	hibernate_zlib_start = (vaddr_t)(pva + (28 * PAGE_SIZE));
1589 	hibernate_zlib_size = 80 * PAGE_SIZE;
1590 
1591 	bzero((caddr_t)hibernate_zlib_start, hibernate_zlib_size);
1592 	bzero((caddr_t)hibernate_state, PAGE_SIZE);
1593 
1594 	/* Set up stream structure */
1595 	hibernate_state->hib_stream.zalloc = (alloc_func)hibernate_zlib_alloc;
1596 	hibernate_state->hib_stream.zfree = (free_func)hibernate_zlib_free;
1597 
1598 	/* Initialize the hiballoc arena for zlib allocs/frees */
1599 	hiballoc_init(&hibernate_state->hiballoc_arena,
1600 	    (caddr_t)hibernate_zlib_start, hibernate_zlib_size);
1601 
1602 	if (deflate) {
1603 		return deflateInit(&hibernate_state->hib_stream,
1604 		    Z_BEST_SPEED);
1605 	} else
1606 		return inflateInit(&hibernate_state->hib_stream);
1607 }
1608 
1609 /*
1610  * Reads the hibernated memory image from disk, whose location and
1611  * size are recorded in hiber_info. Begin by reading the persisted
1612  * chunk table, which records the original chunk placement location
1613  * and compressed size for each. Next, allocate a pig region of
1614  * sufficient size to hold the compressed image. Next, read the
1615  * chunks into the pig area (calling hibernate_read_chunks to do this),
1616  * and finally, if all of the above succeeds, clear the hibernate signature.
1617  * The function will then return to hibernate_resume, which will proceed
1618  * to unpack the pig image to the correct place in memory.
1619  */
1620 int
1621 hibernate_read_image(union hibernate_info *hiber_info)
1622 {
1623 	size_t compressed_size, disk_size, chunktable_size, pig_sz;
1624 	paddr_t image_start, image_end, pig_start, pig_end;
1625 	struct hibernate_disk_chunk *chunks;
1626 	daddr_t blkctr;
1627 	vaddr_t chunktable = (vaddr_t)NULL;
1628 	paddr_t piglet_chunktable = hiber_info->piglet_pa +
1629 	    HIBERNATE_CHUNK_SIZE;
1630 	int i;
1631 
1632 	pmap_activate(curproc);
1633 
1634 	/* Calculate total chunk table size in disk blocks */
1635 	chunktable_size = HIBERNATE_CHUNK_TABLE_SIZE / hiber_info->secsize;
1636 
1637 	blkctr = hiber_info->sig_offset - chunktable_size -
1638 			hiber_info->swap_offset;
1639 
1640 	chunktable = (vaddr_t)km_alloc(HIBERNATE_CHUNK_TABLE_SIZE, &kv_any,
1641 	    &kp_none, &kd_nowait);
1642 
1643 	if (!chunktable)
1644 		return (1);
1645 
1646 	/* Read the chunktable from disk into the piglet chunktable */
1647 	for (i = 0; i < HIBERNATE_CHUNK_TABLE_SIZE;
1648 	    i += PAGE_SIZE, blkctr += PAGE_SIZE/hiber_info->secsize) {
1649 		pmap_kenter_pa(chunktable + i, piglet_chunktable + i,
1650 		    VM_PROT_ALL);
1651 		pmap_update(pmap_kernel());
1652 		hibernate_block_io(hiber_info, blkctr, PAGE_SIZE,
1653 		    chunktable + i, 0);
1654 	}
1655 
1656 	blkctr = hiber_info->image_offset;
1657 	compressed_size = 0;
1658 
1659 	chunks = (struct hibernate_disk_chunk *)chunktable;
1660 
1661 	for (i = 0; i < hiber_info->chunk_ctr; i++)
1662 		compressed_size += chunks[i].compressed_size;
1663 
1664 	disk_size = compressed_size;
1665 
1666 	printf("unhibernating @ block %lld length %lu blocks\n",
1667 	    hiber_info->sig_offset - chunktable_size,
1668 	    compressed_size);
1669 
1670 	/* Allocate the pig area */
1671 	pig_sz = compressed_size + HIBERNATE_CHUNK_SIZE;
1672 	if (uvm_pmr_alloc_pig(&pig_start, pig_sz) == ENOMEM)
1673 		return (1);
1674 
1675 	pig_end = pig_start + pig_sz;
1676 
1677 	/* Calculate image extents. Pig image must end on a chunk boundary. */
1678 	image_end = pig_end & ~(HIBERNATE_CHUNK_SIZE - 1);
1679 	image_start = pig_start;
1680 
1681 	image_start = image_end - disk_size;
1682 
1683 	hibernate_read_chunks(hiber_info, image_start, image_end, disk_size,
1684 	    chunks);
1685 
1686 	pmap_kremove(chunktable, PAGE_SIZE);
1687 	pmap_update(pmap_kernel());
1688 
1689 	/* Prepare the resume time pmap/page table */
1690 	hibernate_populate_resume_pt(hiber_info, image_start, image_end);
1691 
1692 	return (0);
1693 }
1694 
1695 /*
1696  * Read the hibernated memory chunks from disk (chunk information at this
1697  * point is stored in the piglet) into the pig area specified by
1698  * [pig_start .. pig_end]. Order the chunks so that the final chunk is the
1699  * only chunk with overlap possibilities.
1700  */
1701 int
1702 hibernate_read_chunks(union hibernate_info *hib_info, paddr_t pig_start,
1703     paddr_t pig_end, size_t image_compr_size,
1704     struct hibernate_disk_chunk *chunks)
1705 {
1706 	paddr_t img_index, img_cur, r1s, r1e, r2s, r2e;
1707 	paddr_t copy_start, copy_end, piglet_cur;
1708 	paddr_t piglet_base = hib_info->piglet_pa;
1709 	paddr_t piglet_end = piglet_base + HIBERNATE_CHUNK_SIZE;
1710 	daddr_t blkctr;
1711 	size_t processed, compressed_size, read_size;
1712 	int overlap, found, nchunks, nochunks = 0, nfchunks = 0, npchunks = 0;
1713 	short *ochunks, *pchunks, *fchunks, i, j;
1714 	vaddr_t tempva = (vaddr_t)NULL, hibernate_fchunk_area = (vaddr_t)NULL;
1715 
1716 	global_pig_start = pig_start;
1717 
1718 	pmap_activate(curproc);
1719 
1720 	/*
1721 	 * These mappings go into the resuming kernel's page table, and are
1722 	 * used only during image read. They dissappear from existence
1723 	 * when the suspended kernel is unpacked on top of us.
1724 	 */
1725 	tempva = (vaddr_t)km_alloc(2*PAGE_SIZE, &kv_any, &kp_none, &kd_nowait);
1726 	if (!tempva)
1727 		return (1);
1728 	hibernate_fchunk_area = (vaddr_t)km_alloc(24*PAGE_SIZE, &kv_any,
1729 	    &kp_none, &kd_nowait);
1730 	if (!hibernate_fchunk_area)
1731 		return (1);
1732 
1733 	/* Final output chunk ordering VA */
1734 	fchunks = (short *)hibernate_fchunk_area;
1735 
1736 	/* Piglet chunk ordering VA */
1737 	pchunks = (short *)(hibernate_fchunk_area + (8*PAGE_SIZE));
1738 
1739 	/* Final chunk ordering VA */
1740 	ochunks = (short *)(hibernate_fchunk_area + (16*PAGE_SIZE));
1741 
1742 	/* Map the chunk ordering region */
1743 	for(i=0; i<24 ; i++) {
1744 		pmap_kenter_pa(hibernate_fchunk_area + (i*PAGE_SIZE),
1745 			piglet_base + ((4+i)*PAGE_SIZE), VM_PROT_ALL);
1746 		pmap_update(pmap_kernel());
1747 	}
1748 
1749 	nchunks = hib_info->chunk_ctr;
1750 
1751 	/* Initially start all chunks as unplaced */
1752 	for (i = 0; i < nchunks; i++)
1753 		chunks[i].flags = 0;
1754 
1755 	/*
1756 	 * Search the list for chunks that are outside the pig area. These
1757 	 * can be placed first in the final output list.
1758 	 */
1759 	for (i = 0; i < nchunks; i++) {
1760 		if (chunks[i].end <= pig_start || chunks[i].base >= pig_end) {
1761 			ochunks[nochunks] = i;
1762 			fchunks[nfchunks] = i;
1763 			nochunks++;
1764 			nfchunks++;
1765 			chunks[i].flags |= HIBERNATE_CHUNK_USED;
1766 		}
1767 	}
1768 
1769 	/*
1770 	 * Walk the ordering, place the chunks in ascending memory order.
1771 	 * Conflicts might arise, these are handled next.
1772 	 */
1773 	do {
1774 		img_index = -1;
1775 		found = 0;
1776 		j = -1;
1777 		for (i = 0; i < nchunks; i++)
1778 			if (chunks[i].base < img_index &&
1779 			    chunks[i].flags == 0 ) {
1780 				j = i;
1781 				img_index = chunks[i].base;
1782 			}
1783 
1784 		if (j != -1) {
1785 			found = 1;
1786 			ochunks[nochunks] = j;
1787 			nochunks++;
1788 			chunks[j].flags |= HIBERNATE_CHUNK_PLACED;
1789 		}
1790 	} while (found);
1791 
1792 	img_index = pig_start;
1793 
1794 	/*
1795 	 * Identify chunk output conflicts (chunks whose pig load area
1796 	 * corresponds to their original memory placement location)
1797 	 */
1798 	for (i = 0; i < nochunks ; i++) {
1799 		overlap = 0;
1800 		r1s = img_index;
1801 		r1e = img_index + chunks[ochunks[i]].compressed_size;
1802 		r2s = chunks[ochunks[i]].base;
1803 		r2e = chunks[ochunks[i]].end;
1804 
1805 		overlap = hibernate_check_overlap(r1s, r1e, r2s, r2e);
1806 		if (overlap)
1807 			chunks[ochunks[i]].flags |= HIBERNATE_CHUNK_CONFLICT;
1808 		img_index += chunks[ochunks[i]].compressed_size;
1809 	}
1810 
1811 	/*
1812 	 * Prepare the final output chunk list. Calculate an output
1813 	 * inflate strategy for overlapping chunks if needed.
1814 	 */
1815 	img_index = pig_start;
1816 	for (i = 0; i < nochunks ; i++) {
1817 		/*
1818 		 * If a conflict is detected, consume enough compressed
1819 		 * output chunks to fill the piglet
1820 		 */
1821 		if (chunks[ochunks[i]].flags & HIBERNATE_CHUNK_CONFLICT) {
1822 			copy_start = piglet_base;
1823 			copy_end = piglet_end;
1824 			piglet_cur = piglet_base;
1825 			npchunks = 0;
1826 			j = i;
1827 
1828 			while (copy_start < copy_end && j < nochunks) {
1829 				piglet_cur +=
1830 				    chunks[ochunks[j]].compressed_size;
1831 				pchunks[npchunks] = ochunks[j];
1832 				npchunks++;
1833 				copy_start +=
1834 				    chunks[ochunks[j]].compressed_size;
1835 				img_index += chunks[ochunks[j]].compressed_size;
1836 				i++;
1837 				j++;
1838 			}
1839 
1840 			piglet_cur = piglet_base;
1841 			for (j = 0; j < npchunks; j++) {
1842 				piglet_cur +=
1843 				    chunks[pchunks[j]].compressed_size;
1844 				fchunks[nfchunks] = pchunks[j];
1845 				chunks[pchunks[j]].flags |=
1846 				    HIBERNATE_CHUNK_USED;
1847 				nfchunks++;
1848 			}
1849 		} else {
1850 			/*
1851 			 * No conflict, chunk can be added without copying
1852 			 */
1853 			if ((chunks[ochunks[i]].flags &
1854 			    HIBERNATE_CHUNK_USED) == 0) {
1855 				fchunks[nfchunks] = ochunks[i];
1856 				chunks[ochunks[i]].flags |=
1857 				    HIBERNATE_CHUNK_USED;
1858 				nfchunks++;
1859 			}
1860 			img_index += chunks[ochunks[i]].compressed_size;
1861 		}
1862 	}
1863 
1864 	img_index = pig_start;
1865 	for (i = 0; i < nfchunks; i++) {
1866 		piglet_cur = piglet_base;
1867 		img_index += chunks[fchunks[i]].compressed_size;
1868 	}
1869 
1870 	img_cur = pig_start;
1871 
1872 	for (i = 0; i < nfchunks; i++) {
1873 		blkctr = chunks[fchunks[i]].offset - hib_info->swap_offset;
1874 		processed = 0;
1875 		compressed_size = chunks[fchunks[i]].compressed_size;
1876 
1877 		while (processed < compressed_size) {
1878 			pmap_kenter_pa(tempva, img_cur, VM_PROT_ALL);
1879 			pmap_kenter_pa(tempva + PAGE_SIZE, img_cur+PAGE_SIZE,
1880 			    VM_PROT_ALL);
1881 			pmap_update(pmap_kernel());
1882 
1883 			if (compressed_size - processed >= PAGE_SIZE)
1884 				read_size = PAGE_SIZE;
1885 			else
1886 				read_size = compressed_size - processed;
1887 
1888 			hibernate_block_io(hib_info, blkctr, read_size,
1889 			    tempva + (img_cur & PAGE_MASK), 0);
1890 
1891 			blkctr += (read_size / hib_info->secsize);
1892 
1893 			pmap_kremove(tempva, PAGE_SIZE);
1894 			pmap_kremove(tempva + PAGE_SIZE, PAGE_SIZE);
1895 			processed += read_size;
1896 			img_cur += read_size;
1897 		}
1898 	}
1899 
1900 	pmap_kremove(hibernate_fchunk_area, PAGE_SIZE);
1901 	pmap_kremove((vaddr_t)pchunks, PAGE_SIZE);
1902 	pmap_kremove((vaddr_t)fchunks, PAGE_SIZE);
1903 	pmap_update(pmap_kernel());
1904 
1905 	return (0);
1906 }
1907 
1908 /*
1909  * Hibernating a machine comprises the following operations:
1910  *  1. Calculating this machine's hibernate_info information
1911  *  2. Allocating a piglet and saving the piglet's physaddr
1912  *  3. Calculating the memory chunks
1913  *  4. Writing the compressed chunks to disk
1914  *  5. Writing the chunk table
1915  *  6. Writing the signature block (hibernate_info)
1916  *
1917  * On most architectures, the function calling hibernate_suspend would
1918  * then power off the machine using some MD-specific implementation.
1919  */
1920 int
1921 hibernate_suspend(void)
1922 {
1923 	union hibernate_info hib_info;
1924 	u_long start, end;
1925 
1926 	/*
1927 	 * Calculate memory ranges, swap offsets, etc.
1928 	 * This also allocates a piglet whose physaddr is stored in
1929 	 * hib_info->piglet_pa and vaddr stored in hib_info->piglet_va
1930 	 */
1931 	if (get_hibernate_info(&hib_info, 1)) {
1932 		DPRINTF("failed to obtain hibernate info\n");
1933 		return (1);
1934 	}
1935 
1936 	/* Find a page-addressed region in swap [start,end] */
1937 	if (uvm_hibswap(hib_info.device, &start, &end)) {
1938 		printf("cannot find any swap\n");
1939 		return (1);
1940 	}
1941 
1942 	if (end - start < 1000) {
1943 		printf("%lu\n is too small", end - start);
1944 		return (1);
1945 	}
1946 
1947 	/* Calculate block offsets in swap */
1948 	hib_info.image_offset = ctod(start) + hib_info.swap_offset;
1949 
1950 	/* XXX side effect */
1951 	DPRINTF("hibernate @ block %lld max-length %lu blocks\n",
1952 	    hib_info.image_offset, ctod(end) - ctod(start));
1953 
1954 	pmap_kenter_pa(HIBERNATE_HIBALLOC_PAGE, HIBERNATE_HIBALLOC_PAGE,
1955 		VM_PROT_ALL);
1956 	pmap_activate(curproc);
1957 
1958 	/* Stash the piglet VA so we can free it in the resuming kernel */
1959 	global_piglet_va = hib_info.piglet_va;
1960 
1961 	DPRINTF("hibernate: writing chunks\n");
1962 	if (hibernate_write_chunks(&hib_info)) {
1963 		DPRINTF("hibernate_write_chunks failed\n");
1964 		return (1);
1965 	}
1966 
1967 	DPRINTF("hibernate: writing chunktable\n");
1968 	if (hibernate_write_chunktable(&hib_info)) {
1969 		DPRINTF("hibernate_write_chunktable failed\n");
1970 		return (1);
1971 	}
1972 
1973 	DPRINTF("hibernate: writing signature\n");
1974 	if (hibernate_write_signature(&hib_info)) {
1975 		DPRINTF("hibernate_write_signature failed\n");
1976 		return (1);
1977 	}
1978 
1979 	/* Allow the disk to settle */
1980 	delay(500000);
1981 
1982 	/*
1983 	 * Give the device-specific I/O function a notification that we're
1984 	 * done, and that it can clean up or shutdown as needed.
1985 	 */
1986 	hib_info.io_func(hib_info.device, 0, (vaddr_t)NULL, 0,
1987 	    HIB_DONE, hib_info.io_page);
1988 
1989 	return (0);
1990 }
1991 
1992 /*
1993  * Free items allocated by hibernate_suspend()
1994  */
1995 void
1996 hibernate_free(void)
1997 {
1998 	if (global_piglet_va)
1999 		uvm_pmr_free_piglet(global_piglet_va,
2000 		    3*HIBERNATE_CHUNK_SIZE);
2001 
2002 	if (hibernate_copy_page)
2003 		pmap_kremove(hibernate_copy_page, PAGE_SIZE);
2004 	if (hibernate_temp_page)
2005 		pmap_kremove(hibernate_temp_page, PAGE_SIZE);
2006 
2007 	pmap_update(pmap_kernel());
2008 
2009 	if (hibernate_copy_page)
2010 		km_free((void *)hibernate_copy_page, PAGE_SIZE,
2011 		    &kv_any, &kp_none);
2012 	if (hibernate_temp_page)
2013 		km_free((void *)hibernate_temp_page, PAGE_SIZE,
2014 		    &kv_any, &kp_none);
2015 
2016 	global_piglet_va = 0;
2017 	hibernate_copy_page = 0;
2018 	hibernate_temp_page = 0;
2019 }
2020