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