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