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