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