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