aboutsummaryrefslogtreecommitdiffstats
path: root/backends/cxxrtl/cxxrtl_capi.h
blob: 2df2b7287f44719b5377b208fa243a6df882cfa1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
/*
 *  yosys -- Yosys Open SYnthesis Suite
 *
 *  Copyright (C) 2020  whitequark <whitequark@whitequark.org>
 *
 *  Permission to use, copy, modify, and/or distribute this software for any
 *  purpose with or without fee is hereby granted.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 *  WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 *  MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 *  ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 *  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 *  ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 *  OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *
 */

#ifndef CXXRTL_CAPI_H
#define CXXRTL_CAPI_H

// This file is a part of the CXXRTL C API. It should be used together with `cxxrtl_capi.cc`.
//
// The CXXRTL C API makes it possible to drive CXXRTL designs using C or any other language that
// supports the C ABI, for example, Python. It does not provide a way to implement black boxes.

#include <stddef.h>
#include <stdint.h>
#include <assert.h>

#ifdef __cplusplus
extern "C" {
#endif

// Opaque reference to a design toplevel.
//
// A design toplevel can only be used to create a design handle.
typedef struct _cxxrtl_toplevel *cxxrtl_toplevel;

// The constructor for a design toplevel is provided as a part of generated code for that design.
// Its prototype matches:
//
// cxxrtl_toplevel <design-name>_create();

// Opaque reference to a design handle.
//
// A design handle is required by all operations in the C API.
typedef struct _cxxrtl_handle *cxxrtl_handle;

// Create a design handle from a design toplevel.
//
// The `design` is consumed by this operation and cannot be used afterwards.
cxxrtl_handle cxxrtl_create(cxxrtl_toplevel design);

// Create a design handle at a given hierarchy position from a design toplevel.
//
// This operation is similar to `cxxrtl_create`, except the full hierarchical name of every object
// is prepended with `root`.
cxxrtl_handle cxxrtl_create_at(cxxrtl_toplevel design, const char *root);

// Release all resources used by a design and its handle.
void cxxrtl_destroy(cxxrtl_handle handle);

// Reinitialize the design, replacing the internal state with the reset values while preserving
// black boxes.
//
// This operation is essentially equivalent to a power-on reset. Values, wires, and memories are
// returned to their reset state while preserving the state of black boxes and keeping all of
// the interior pointers obtained with e.g. `cxxrtl_get` valid.
void cxxrtl_reset(cxxrtl_handle handle);

// Evaluate the design, propagating changes on inputs to the `next` value of internal state and
// output wires.
//
// Returns 1 if the design is known to immediately converge, 0 otherwise.
int cxxrtl_eval(cxxrtl_handle handle);

// Commit the design, replacing the `curr` value of internal state and output wires with the `next`
// value.
//
// Return 1 if any of the `curr` values were updated, 0 otherwise.
int cxxrtl_commit(cxxrtl_handle handle);

// Simulate the design to a fixed point.
//
// Returns the number of delta cycles.
size_t cxxrtl_step(cxxrtl_handle handle);

// Type of a simulated object.
//
// The type of a simulated object indicates the way it is stored and the operations that are legal
// to perform on it (i.e. won't crash the simulation). It says very little about object semantics,
// which is specified through flags.
enum cxxrtl_type {
	// Values correspond to singly buffered netlist nodes, i.e. nodes driven exclusively by
	// combinatorial cells, or toplevel input nodes.
	//
	// Values can be inspected via the `curr` pointer. If the `next` pointer is NULL, the value is
	// driven by a constant and can never be modified. Otherwise, the value can be modified through
	// the `next` pointer (which is equal to `curr` if not NULL). Note that changes to the bits
	// driven by combinatorial cells will be ignored.
	//
	// Values always have depth 1.
	CXXRTL_VALUE = 0,

	// Wires correspond to doubly buffered netlist nodes, i.e. nodes driven, at least in part, by
	// storage cells, or by combinatorial cells that are a part of a feedback path. They are also
	// present in non-optimized builds.
	//
	// Wires can be inspected via the `curr` pointer and modified via the `next` pointer (which are
	// distinct for wires). Note that changes to the bits driven by combinatorial cells will be
	// ignored.
	//
	// Wires always have depth 1.
	CXXRTL_WIRE = 1,

	// Memories correspond to memory cells.
	//
	// Memories can be inspected and modified via the `curr` pointer. Due to a limitation of this
	// API, memories cannot yet be modified in a guaranteed race-free way, and the `next` pointer is
	// always NULL.
	CXXRTL_MEMORY = 2,

	// Aliases correspond to netlist nodes driven by another node such that their value is always
	// exactly equal.
	//
	// Aliases can be inspected via the `curr` pointer. They cannot be modified, and the `next`
	// pointer is always NULL.
	CXXRTL_ALIAS = 3,

	// Outlines correspond to netlist nodes that were optimized in a way that makes them inaccessible
	// outside of a module's `eval()` function. At the highest debug information level, every inlined
	// node has a corresponding outline object.
	//
	// Outlines can be inspected via the `curr` pointer and can never be modified; the `next` pointer
	// is always NULL. Unlike all other objects, the bits of an outline object are meaningful only
	// after a call to `cxxrtl_outline_eval` and until any subsequent modification to the netlist.
	// Observing this requirement is the responsibility of the caller; it is not enforced.
	//
	// Outlines always correspond to combinatorial netlist nodes that are not ports.
	CXXRTL_OUTLINE = 4,

	// More object types may be added in the future, but the existing ones will never change.
};

// Flags of a simulated object.
//
// The flags of a simulated object indicate its role in the netlist:
//  * The flags `CXXRTL_INPUT` and `CXXRTL_OUTPUT` designate module ports.
//  * The flags `CXXRTL_DRIVEN_SYNC`, `CXXRTL_DRIVEN_COMB`, and `CXXRTL_UNDRIVEN` specify
//    the semantics of node state. An object with several of these flags set has different bits
//    follow different semantics.
enum cxxrtl_flag {
	// Node is a module input port.
	//
	// This flag can be set on objects of type `CXXRTL_VALUE` and `CXXRTL_WIRE`. It may be combined
	// with `CXXRTL_OUTPUT`, as well as other flags.
	CXXRTL_INPUT = 1 << 0,

	// Node is a module output port.
	//
	// This flag can be set on objects of type `CXXRTL_WIRE`. It may be combined with `CXXRTL_INPUT`,
	// as well as other flags.
	CXXRTL_OUTPUT = 1 << 1,

	// Node is a module inout port.
	//
	// This flag can be set on objects of type `CXXRTL_WIRE`. It may be combined with other flags.
	CXXRTL_INOUT = (CXXRTL_INPUT|CXXRTL_OUTPUT),

	// Node has bits that are driven by a storage cell.
	//
	// This flag can be set on objects of type `CXXRTL_WIRE`. It may be combined with
	// `CXXRTL_DRIVEN_COMB` and `CXXRTL_UNDRIVEN`, as well as other flags.
	//
	// This flag is set on wires that have bits connected directly to the output of a flip-flop or
	// a latch, and hold its state. Many `CXXRTL_WIRE` objects may not have the `CXXRTL_DRIVEN_SYNC`
	// flag set; for example, output ports and feedback wires generally won't. Writing to the `next`
	// pointer of these wires updates stored state, and for designs without combinatorial loops,
	// capturing the value from every of these wires through the `curr` pointer creates a complete
	// snapshot of the design state.
	CXXRTL_DRIVEN_SYNC = 1 << 2,

	// Node has bits that are driven by a combinatorial cell or another node.
	//
	// This flag can be set on objects of type `CXXRTL_VALUE`, `CXXRTL_WIRE`, and `CXXRTL_OUTLINE`.
	// It may be combined with `CXXRTL_DRIVEN_SYNC` and `CXXRTL_UNDRIVEN`, as well as other flags.
	//
	// This flag is set on objects that have bits connected to the output of a combinatorial cell,
	// or directly to another node. For designs without combinatorial loops, writing to such bits
	// through the `next` pointer (if it is not NULL) has no effect.
	CXXRTL_DRIVEN_COMB = 1 << 3,

	// Node has bits that are not driven.
	//
	// This flag can be set on objects of type `CXXRTL_VALUE` and `CXXRTL_WIRE`. It may be combined
	// with `CXXRTL_DRIVEN_SYNC` and `CXXRTL_DRIVEN_COMB`, as well as other flags.
	//
	// This flag is set on objects that have bits not driven by an output of any cell or by another
	// node, such as inputs and dangling wires.
	CXXRTL_UNDRIVEN = 1 << 4,

	// More object flags may be added in the future, but the existing ones will never change.
};

// Description of a simulated object.
//
// The `curr` and `next` arrays can be accessed directly to inspect and, if applicable, modify
// the bits stored in the object.
struct cxxrtl_object {
	// Type of the object.
	//
	// All objects have the same memory layout determined by `width` and `depth`, but the type
	// determines all other properties of the object.
	uint32_t type; // actually `enum cxxrtl_type`

	// Flags of the object.
	uint32_t flags; // actually bit mask of `enum cxxrtl_flags`

	// Width of the object in bits.
	size_t width;

	// Index of the least significant bit.
	size_t lsb_at;

	// Depth of the object. Only meaningful for memories; for other objects, always 1.
	size_t depth;

	// Index of the first word. Only meaningful for memories; for other objects, always 0;
	size_t zero_at;

	// Bits stored in the object, as 32-bit chunks, least significant bits first.
	//
	// The width is rounded up to a multiple of 32; the padding bits are always set to 0 by
	// the simulation code, and must be always written as 0 when modified by user code.
	// In memories, every element is stored contiguously. Therefore, the total number of chunks
	// in any object is `((width + 31) / 32) * depth`.
	//
	// To allow the simulation to be partitioned into multiple independent units communicating
	// through wires, the bits are double buffered. To avoid race conditions, user code should
	// always read from `curr` and write to `next`. The `curr` pointer is always valid; for objects
	// that cannot be modified, or cannot be modified in a race-free way, `next` is NULL.
	uint32_t *curr;
	uint32_t *next;

	// Opaque reference to an outline. Only meaningful for outline objects.
	//
	// See the documentation of `cxxrtl_outline` for details. When creating a `cxxrtl_object`, set
	// this field to NULL.
	struct _cxxrtl_outline *outline;

	// More description fields may be added in the future, but the existing ones will never change.
};

// Retrieve description of a simulated object.
//
// The `name` is the full hierarchical name of the object in the Yosys notation, where public names
// have a `\` prefix and hierarchy levels are separated by single spaces. For example, if
// the top-level module instantiates a module `foo`, which in turn contains a wire `bar`, the full
// hierarchical name is `\foo \bar`.
//
// The storage of a single abstract object may be split (usually with the `splitnets` pass) into
// many physical parts, all of which correspond to the same hierarchical name. To handle such cases,
// this function returns an array and writes its length to `parts`. The array is sorted by `lsb_at`.
//
// Returns the object parts if it was found, NULL otherwise. The returned parts are valid until
// the design is destroyed.
struct cxxrtl_object *cxxrtl_get_parts(cxxrtl_handle handle, const char *name, size_t *parts);

// Retrieve description of a single part simulated object.
//
// This function is a shortcut for the most common use of `cxxrtl_get_parts`. It asserts that,
// if the object exists, it consists of a single part. If assertions are disabled, it returns NULL
// for multi-part objects.
static inline struct cxxrtl_object *cxxrtl_get(cxxrtl_handle handle, const char *name) {
	size_t parts = 0;
	struct cxxrtl_object *object = cxxrtl_get_parts(handle, name, &parts);
	assert(object == NULL || parts == 1);
	if (object == NULL || parts == 1)
		return object;
	return NULL;
}

// Enumerate simulated objects.
//
// For every object in the simulation, `callback` is called with the provided `data`, the full
// hierarchical name of the object (see `cxxrtl_get` for details), and the object parts.
// The provided `name` and `object` values are valid until the design is destroyed.
void cxxrtl_enum(cxxrtl_handle handle, void *data,
                 void (*callback)(void *data, const char *name,
                                  struct cxxrtl_object *object, size_t parts));

// Opaque reference to an outline.
//
// An outline is a group of outline objects that are evaluated simultaneously. The identity of
// an outline can be compared to determine whether any two objects belong to the same outline.
typedef struct _cxxrtl_outline *cxxrtl_outline;

// Evaluate an outline.
//
// After evaluating an outline, the bits of every outline object contained in it are consistent
// with the current state of the netlist. In general, any further modification to the netlist
// causes every outline object to become stale, after which the corresponding outline must be
// re-evaluated, otherwise the bits read from that object are meaningless.
void cxxrtl_outline_eval(cxxrtl_outline outline);

#ifdef __cplusplus
}
#endif

#endif
ref='#n1195'>1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056
/******************************************************************************
 * xc_domain_restore.c
 *
 * Restore the state of a guest session.
 *
 * Copyright (c) 2003, K A Fraser.
 * Copyright (c) 2006, Intel Corporation
 * Copyright (c) 2007, XenSource Inc.
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms and conditions of the GNU General Public License,
 * version 2, as published by the Free Software Foundation.
 *
 * This program is distributed in the hope it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program; if not, write to the Free Software Foundation, Inc., 59 Temple
 * Place - Suite 330, Boston, MA 02111-1307 USA.
 *
 */

#include <stdlib.h>
#include <unistd.h>

#include "xg_private.h"
#include "xg_save_restore.h"
#include "xc_dom.h"

#include <xen/hvm/ioreq.h>
#include <xen/hvm/params.h>

struct restore_ctx {
    unsigned long max_mfn; /* max mfn of the current host machine */
    unsigned long hvirt_start; /* virtual starting address of the hypervisor */
    unsigned int pt_levels; /* #levels of page tables used by the current guest */
    unsigned long nr_pfns; /* number of 'in use' pfns in the guest (i.e. #P2M entries with a valid mfn) */
    xen_pfn_t *live_p2m; /* Live mapping of the table mapping each PFN to its current MFN. */
    xen_pfn_t *p2m; /* A table mapping each PFN to its new MFN. */
    unsigned no_superpage_mem; /* If have enough continuous memory for super page allocation */
    struct domain_info_context dinfo;
};

/*
**
**
*/
#define SUPERPAGE_PFN_SHIFT  9
#define SUPERPAGE_NR_PFNS    (1UL << SUPERPAGE_PFN_SHIFT)

/*
 * Setting bit 31 force to allocate super page even not all pfns come out,
 * bit 30 indicate that not is in a super page tracking.
 */
#define FORCE_SP_SHIFT           31
#define FORCE_SP_MASK            (1UL << FORCE_SP_SHIFT)

#define INVALID_SUPER_PAGE       ((1UL << 30) + 1)
#define SUPER_PAGE_START(pfn)    (((pfn) & (SUPERPAGE_NR_PFNS-1)) == 0 )
#define SUPER_PAGE_TRACKING(pfn) ( (pfn) != INVALID_SUPER_PAGE )
#define SUPER_PAGE_DONE(pfn)     ( SUPER_PAGE_START(pfn) )

static int super_page_populated(struct restore_ctx *ctx, unsigned long pfn)
{
    int i;
    pfn &= ~(SUPERPAGE_NR_PFNS - 1);
    for ( i = pfn; i < pfn + SUPERPAGE_NR_PFNS; i++ )
    {
        if ( ctx->p2m[i] != INVALID_P2M_ENTRY )
            return 1;
    }
    return 0;
}

/*
 * Break a 2M page and move contents of [extent start, next_pfn-1] to
 * some new allocated 4K pages
 */
static int break_super_page(int xc_handle,
                            uint32_t dom,
                            struct restore_ctx *ctx,
                            xen_pfn_t next_pfn)
{
    xen_pfn_t *page_array, start_pfn, mfn;
    uint8_t *ram_base, *save_buf;
    unsigned long i;
    int tot_pfns, rc = 0;

    tot_pfns = (next_pfn & (SUPERPAGE_NR_PFNS - 1));

    start_pfn = next_pfn & ~(SUPERPAGE_NR_PFNS - 1);
    for ( i = start_pfn; i < start_pfn + SUPERPAGE_NR_PFNS; i++ )
    {
        /* check the 2M page are populated */
        if ( ctx->p2m[i] == INVALID_P2M_ENTRY ) {
            DPRINTF("Previous super page was populated wrongly!\n");
            return 1;
        }
    }

    page_array = (xen_pfn_t*)malloc(tot_pfns * sizeof(xen_pfn_t));
    save_buf = (uint8_t*)malloc(tot_pfns * PAGE_SIZE);

    if ( !page_array || !save_buf )
    {
        ERROR("alloc page_array failed\n");
        errno = ENOMEM;
        rc = 1;
        goto out;
    }

    /* save previous super page contents */
    for ( i = 0; i < tot_pfns; i++ )
    {
        /* only support HVM, as the mfn of the 2M page is missing */
        page_array[i] = start_pfn + i;
    }

    ram_base = xc_map_foreign_pages(xc_handle, dom, PROT_READ,
                                    page_array, tot_pfns);

    if ( ram_base == NULL )
    {
        ERROR("map batch failed\n");
        rc = 1;
        goto out;
    }

    memcpy(save_buf, ram_base, tot_pfns * PAGE_SIZE);
    munmap(ram_base, tot_pfns * PAGE_SIZE);

    /* free the super page */
    if ( xc_domain_memory_decrease_reservation(xc_handle, dom, 1,
                                   SUPERPAGE_PFN_SHIFT, &start_pfn) != 0 )
    {
        ERROR("free 2M page failure @ 0x%ld.\n", next_pfn);
        rc = 1;
        goto out;
    }

    start_pfn = next_pfn & ~(SUPERPAGE_NR_PFNS - 1);
    for ( i = start_pfn; i < start_pfn + SUPERPAGE_NR_PFNS; i++ )
    {
        ctx->p2m[i] = INVALID_P2M_ENTRY;
    }

    for ( i = start_pfn; i < start_pfn + tot_pfns; i++ )
    {
        mfn = i;
        if (xc_domain_memory_populate_physmap(xc_handle, dom, 1, 0,
                                              0, &mfn) != 0)
        {
            ERROR("Failed to allocate physical memory.!\n");
            errno = ENOMEM;
            rc = 1;
            goto out;
        }
        ctx->p2m[i] = mfn;
    }

    /* restore contents */
    for ( i = 0; i < tot_pfns; i++ )
    {
        page_array[i] = start_pfn + i;
    }

    ram_base = xc_map_foreign_pages(xc_handle, dom, PROT_WRITE,
                                    page_array, tot_pfns);
    if ( ram_base == NULL )
    {
        ERROR("map batch failed\n");
        rc = 1;
        goto out;
    }

    memcpy(ram_base, save_buf, tot_pfns * PAGE_SIZE);
    munmap(ram_base, tot_pfns * PAGE_SIZE);

out:
    free(page_array);
    free(save_buf);
    return rc;
}


/*
 * According to pfn list allocate pages: one 2M page or series of 4K pages.
 * Also optimistically allocate a 2M page even when not all pages in the 2M
 * extent come out, and fix it up in next batch:
 * If new pages fit the missing one in the 2M extent, do nothing; Else take
 * place of the original 2M page by some 4K pages.
 */
static int allocate_mfn_list(int xc_handle,
                              uint32_t dom,
                              struct restore_ctx *ctx,
                              unsigned long nr_extents,
                              xen_pfn_t *batch_buf,
                              xen_pfn_t *next_pfn,
                              int superpages)
{
    unsigned int i;
    unsigned long mfn, pfn, sp_pfn;

    /*Check if force super page, then clear it */
    unsigned force_super_page = !!(*next_pfn & FORCE_SP_MASK);
    *next_pfn &= ~FORCE_SP_MASK;

    sp_pfn = *next_pfn;

    if ( !superpages ||
         ctx->no_superpage_mem ||
         !SUPER_PAGE_TRACKING(sp_pfn) )
        goto normal_page;

    if ( !batch_buf )
    {
        /* Break previous 2M page, if 512 pages split across a batch boundary */
        if ( SUPER_PAGE_TRACKING(sp_pfn) &&
             !SUPER_PAGE_DONE(sp_pfn))
        {
            /* break previously allocated super page*/
            if ( break_super_page(xc_handle, dom, ctx, sp_pfn) != 0 )
            {
                ERROR("Break previous super page fail!\n");
                return 1;
            }
        }

        /* follwing pages fit the order in 2M extent */
        return 0;
    }

    /*
     * We try to allocate a 2M page only when:
     * user require this(superpages),
     * AND have enough memory,
     * AND is in the tracking,
     * AND tracked all pages in 2M extent, OR partial 2M extent for speculation
     * AND any page in 2M extent are not populated
     */
    if ( !SUPER_PAGE_DONE(sp_pfn) && !force_super_page )
        goto normal_page;

    pfn = batch_buf[0] & ~XEN_DOMCTL_PFINFO_LTAB_MASK;
    if  ( super_page_populated(ctx, pfn) )
        goto normal_page;

    pfn &= ~(SUPERPAGE_NR_PFNS - 1);
    mfn =  pfn;

    if ( xc_domain_memory_populate_physmap(xc_handle, dom, 1,
                SUPERPAGE_PFN_SHIFT, 0, &mfn) == 0)
    {
        for ( i = pfn; i < pfn + SUPERPAGE_NR_PFNS; i++, mfn++ )
        {
            ctx->p2m[i] = mfn;
        }
        return 0;
    }
    DPRINTF("No 2M page available for pfn 0x%lx, fall back to 4K page.\n",
            pfn);
    ctx->no_superpage_mem = 1;

normal_page:
    if ( !batch_buf )
        return 0;

    /* End the tracking, if want a 2M page but end by 4K pages, */
    *next_pfn = INVALID_SUPER_PAGE;

    for ( i = 0; i < nr_extents; i++ )
    {
        unsigned long pagetype = batch_buf[i] &  XEN_DOMCTL_PFINFO_LTAB_MASK;
        if ( pagetype == XEN_DOMCTL_PFINFO_XTAB )
            continue;

        pfn = mfn = batch_buf[i] & ~XEN_DOMCTL_PFINFO_LTAB_MASK;
        if ( ctx->p2m[pfn] == INVALID_P2M_ENTRY )
        {
            if (xc_domain_memory_populate_physmap(xc_handle, dom, 1, 0,
                        0, &mfn) != 0)
            {
                ERROR("Failed to allocate physical memory.! pfn=0x%lx, mfn=0x%lx.\n",
                        pfn, mfn);
                errno = ENOMEM;
                return 1;
            }
            ctx->p2m[pfn] = mfn;
        }
    }

    return 0;
}

static int allocate_physmem(int xc_handle, uint32_t dom,
                            struct restore_ctx *ctx,
                            unsigned long *region_pfn_type, int region_size,
                            unsigned int hvm, xen_pfn_t *region_mfn, int superpages)
{
    int i;
    unsigned long pfn;
    unsigned long pagetype;

    /* Next expected pfn in order to track a possible 2M page */
    static unsigned long required_pfn = INVALID_SUPER_PAGE;

    /* Buffer of pfn list for 2M page, or series of 4K pages */
    xen_pfn_t   *batch_buf;
    unsigned int batch_buf_len;
    struct domain_info_context *dinfo = &ctx->dinfo;

    if ( !superpages )
    {
        batch_buf     = &region_pfn_type[0];
        batch_buf_len = region_size;
        goto alloc_page;
    }

    batch_buf = NULL;
    batch_buf_len = 0;
    /* This loop tracks the possible 2M page */
    for (i = 0; i < region_size; i++)
    {
        pfn      = region_pfn_type[i] & ~XEN_DOMCTL_PFINFO_LTAB_MASK;
        pagetype = region_pfn_type[i] &  XEN_DOMCTL_PFINFO_LTAB_MASK;

        if (pagetype == XEN_DOMCTL_PFINFO_XTAB)
        {
            /* Do not start collecting pfns until get a valid pfn */
            if ( batch_buf_len != 0 )
                batch_buf_len++;
            continue;
        }

        if ( SUPER_PAGE_START(pfn) )
        {
            /* Start of a 2M extent, populate previsous buf */
            if ( allocate_mfn_list(xc_handle, dom, ctx,
                                   batch_buf_len, batch_buf,
                                   &required_pfn, superpages) != 0 )
            {
                errno = ENOMEM;
                return 1;
            }

            /* start new tracking for 2M page */
            batch_buf     = &region_pfn_type[i];
            batch_buf_len = 1;
            required_pfn  = pfn + 1;
        }
        else if ( pfn == required_pfn )
        {
            /* this page fit the 2M extent in order */
            batch_buf_len++;
            required_pfn++;
        }
        else if ( SUPER_PAGE_TRACKING(required_pfn) )
        {
            /* break of a 2M extent, populate previous buf */
            if ( allocate_mfn_list(xc_handle, dom, ctx,
                                   batch_buf_len, batch_buf,
                                   &required_pfn, superpages) != 0 )
            {
                errno = ENOMEM;
                return 1;
            }
            /* start new tracking for a series of 4K pages */
            batch_buf     = &region_pfn_type[i];
            batch_buf_len = 1;
            required_pfn  = INVALID_SUPER_PAGE;
        }
        else
        {
            /* this page is 4K */
            if ( !batch_buf )
                batch_buf = &region_pfn_type[i];
            batch_buf_len++;
        }
    }

    /*
     * populate rest batch_buf in the end.
     * In a speculative way, we allocate a 2M page even when not see all the
     * pages in order(set bit 31). If not require super page support,
     * we can skip the tracking loop and come here directly.
     * Speculative allocation can't be used for PV guest, as we have no mfn to
     * map previous 2M mem range if need break it.
     */
    if ( SUPER_PAGE_TRACKING(required_pfn) &&
         !SUPER_PAGE_DONE(required_pfn) )
    {
        if (hvm)
            required_pfn |= FORCE_SP_MASK;
        else
            required_pfn = INVALID_SUPER_PAGE;
    }

alloc_page:
    if ( batch_buf )
    {
        if ( allocate_mfn_list(xc_handle, dom, ctx,
                    batch_buf_len, batch_buf,
                    &required_pfn,
                    superpages) != 0 )
        {
            errno = ENOMEM;
            return 1;
        }
    }

    for (i = 0; i < region_size; i++)
    {
        pfn      = region_pfn_type[i] & ~XEN_DOMCTL_PFINFO_LTAB_MASK;
        pagetype = region_pfn_type[i] &  XEN_DOMCTL_PFINFO_LTAB_MASK;

        if ( pfn > dinfo->p2m_size )
        {
            ERROR("pfn out of range");
            return 1;
        }
        if (pagetype == XEN_DOMCTL_PFINFO_XTAB)
        {
            region_mfn[i] = ~0UL;
        }
        else 
        {
            if (ctx->p2m[pfn] == INVALID_P2M_ENTRY)
            {
                DPRINTF("Warning: pfn 0x%lx are not allocated!\n", pfn);
                /*XXX:allocate this page?*/
            }

            /* setup region_mfn[] for batch map.
             * For HVM guests, this interface takes PFNs, not MFNs */
            region_mfn[i] = hvm ? pfn : ctx->p2m[pfn]; 
        }
    }
    return 0;
}


/* set when a consistent image is available */
static int completed = 0;

#define HEARTBEAT_MS 500

#ifndef __MINIOS__
static ssize_t read_exact_timed(int fd, void* buf, size_t size)
{
    size_t offset = 0;
    ssize_t len;
    struct timeval tv;
    fd_set rfds;

    while ( offset < size )
    {
        if ( completed ) {
            /* expect a heartbeat every HEARBEAT_MS ms maximum */
            tv.tv_sec = 0;
            tv.tv_usec = HEARTBEAT_MS * 1000;

            FD_ZERO(&rfds);
            FD_SET(fd, &rfds);
            len = select(fd + 1, &rfds, NULL, NULL, &tv);
            if ( !FD_ISSET(fd, &rfds) ) {
                fprintf(stderr, "read_exact_timed failed (select returned %zd)\n", len);
                return -1;
            }
        }

        len = read(fd, buf + offset, size - offset);
        if ( (len == -1) && ((errno == EINTR) || (errno == EAGAIN)) )
            continue;
        if ( len <= 0 )
            return -1;
        offset += len;
    }

    return 0;
}

#define read_exact read_exact_timed

#else
#define read_exact_timed read_exact
#endif
/*
** In the state file (or during transfer), all page-table pages are
** converted into a 'canonical' form where references to actual mfns
** are replaced with references to the corresponding pfns.
** This function inverts that operation, replacing the pfn values with
** the (now known) appropriate mfn values.
*/
static int uncanonicalize_pagetable(int xc_handle, uint32_t dom, struct restore_ctx *ctx,
                                    void *page, int superpages)
{
    int i, pte_last;
    unsigned long pfn;
    uint64_t pte;
    struct domain_info_context *dinfo = &ctx->dinfo;

    pte_last = PAGE_SIZE / ((ctx->pt_levels == 2)? 4 : 8);

    for ( i = 0; i < pte_last; i++ )
    {
        if ( ctx->pt_levels == 2 )
            pte = ((uint32_t *)page)[i];
        else
            pte = ((uint64_t *)page)[i];
        
        /* XXX SMH: below needs fixing for PROT_NONE etc */
        if ( !(pte & _PAGE_PRESENT) )
            continue;
        
        pfn = (pte >> PAGE_SHIFT) & MFN_MASK_X86;

        /* Allocate mfn if necessary */
        if ( ctx->p2m[pfn] == INVALID_P2M_ENTRY )
        {
            unsigned long force_pfn = superpages ? FORCE_SP_MASK : pfn;
            if (allocate_mfn_list(xc_handle, dom, ctx,
                        1, &pfn, &force_pfn, superpages) != 0)
                return 0;
        }
        pte &= ~MADDR_MASK_X86;
        pte |= (uint64_t)ctx->p2m[pfn] << PAGE_SHIFT;

        if ( ctx->pt_levels == 2 )
            ((uint32_t *)page)[i] = (uint32_t)pte;
        else
            ((uint64_t *)page)[i] = (uint64_t)pte;
    }

    return 1;
}


/* Load the p2m frame list, plus potential extended info chunk */
static xen_pfn_t *load_p2m_frame_list(struct restore_ctx *ctx,
    int io_fd, int *pae_extended_cr3, int *ext_vcpucontext)
{
    xen_pfn_t *p2m_frame_list;
    vcpu_guest_context_any_t ctxt;
    xen_pfn_t p2m_fl_zero;
    struct domain_info_context *dinfo = &ctx->dinfo;

    /* Read first entry of P2M list, or extended-info signature (~0UL). */
    if ( read_exact(io_fd, &p2m_fl_zero, sizeof(long)) )
    {
        ERROR("read extended-info signature failed");
        return NULL;
    }
    
    if ( p2m_fl_zero == ~0UL )
    {
        uint32_t tot_bytes;
        
        /* Next 4 bytes: total size of following extended info. */
        if ( read_exact(io_fd, &tot_bytes, sizeof(tot_bytes)) )
        {
            ERROR("read extended-info size failed");
            return NULL;
        }
        
        while ( tot_bytes )
        {
            uint32_t chunk_bytes;
            char     chunk_sig[4];
            
            /* 4-character chunk signature + 4-byte remaining chunk size. */
            if ( read_exact(io_fd, chunk_sig, sizeof(chunk_sig)) ||
                 read_exact(io_fd, &chunk_bytes, sizeof(chunk_bytes)) ||
                 (tot_bytes < (chunk_bytes + 8)) )
            {
                ERROR("read extended-info chunk signature failed");
                return NULL;
            }
            tot_bytes -= 8;

            /* VCPU context structure? */
            if ( !strncmp(chunk_sig, "vcpu", 4) )
            {
                /* Pick a guest word-size and PT depth from the ctxt size */
                if ( chunk_bytes == sizeof (ctxt.x32) )
                {
                    dinfo->guest_width = 4;
                    if ( ctx->pt_levels > 2 ) 
                        ctx->pt_levels = 3; 
                }
                else if ( chunk_bytes == sizeof (ctxt.x64) )
                {
                    dinfo->guest_width = 8;
                    ctx->pt_levels = 4;
                }
                else 
                {
                    ERROR("bad extended-info context size %d", chunk_bytes);
                    return NULL;
                }

                if ( read_exact(io_fd, &ctxt, chunk_bytes) )
                {
                    ERROR("read extended-info vcpu context failed");
                    return NULL;
                }
                tot_bytes -= chunk_bytes;
                chunk_bytes = 0;

                if ( GET_FIELD(&ctxt, vm_assist) 
                     & (1UL << VMASST_TYPE_pae_extended_cr3) )
                    *pae_extended_cr3 = 1;
            }
            else if ( !strncmp(chunk_sig, "extv", 4) )
            {
                *ext_vcpucontext = 1;
            }
            
            /* Any remaining bytes of this chunk: read and discard. */
            while ( chunk_bytes )
            {
                unsigned long sz = MIN(chunk_bytes, sizeof(xen_pfn_t));
                if ( read_exact(io_fd, &p2m_fl_zero, sz) )
                {
                    ERROR("read-and-discard extended-info chunk bytes failed");
                    return NULL;
                }
                chunk_bytes -= sz;
                tot_bytes   -= sz;
            }
        }

        /* Now read the real first entry of P2M list. */
        if ( read_exact(io_fd, &p2m_fl_zero, sizeof(xen_pfn_t)) )
        {
            ERROR("read first entry of p2m_frame_list failed");
            return NULL;
        }
    }

    /* Now that we know the guest's word-size, can safely allocate 
     * the p2m frame list */
    if ( (p2m_frame_list = malloc(P2M_TOOLS_FL_SIZE)) == NULL )
    {
        ERROR("Couldn't allocate p2m_frame_list array");
        return NULL;
    }

    /* First entry has already been read. */
    p2m_frame_list[0] = p2m_fl_zero;
    if ( read_exact(io_fd, &p2m_frame_list[1], 
                    (P2M_FL_ENTRIES - 1) * sizeof(xen_pfn_t)) )
    {
        ERROR("read p2m_frame_list failed");
        return NULL;
    }
    
    return p2m_frame_list;
}

typedef struct {
    int ishvm;
    union {
        struct tailbuf_pv {
            unsigned int pfncount;
            unsigned long* pfntab;
            unsigned int vcpucount;
            unsigned char* vcpubuf;
            unsigned char shared_info_page[PAGE_SIZE];
        } pv;
        struct tailbuf_hvm {
            uint64_t magicpfns[3];
            uint32_t hvmbufsize, reclen;
            uint8_t* hvmbuf;
            struct {
                uint32_t magic;
                uint32_t version;
                uint64_t len;
            } qemuhdr;
            uint32_t qemubufsize;
            uint8_t* qemubuf;
        } hvm;
    } u;
} tailbuf_t;

/* read stream until EOF, growing buffer as necssary */
static int compat_buffer_qemu(int fd, struct tailbuf_hvm *buf)
{
    uint8_t *qbuf, *tmp;
    int blen = 0, dlen = 0;
    int rc;

    /* currently save records tend to be about 7K */
    blen = 8192;
    if ( !(qbuf = malloc(blen)) ) {
        ERROR("Error allocating QEMU buffer");
        return -1;
    }

    while( (rc = read(fd, qbuf+dlen, blen-dlen)) > 0 ) {
        DPRINTF("Read %d bytes of QEMU data\n", rc);
        dlen += rc;

        if (dlen == blen) {
            DPRINTF("%d-byte QEMU buffer full, reallocating...\n", dlen);
            blen += 4096;
            tmp = realloc(qbuf, blen);
            if ( !tmp ) {
                ERROR("Error growing QEMU buffer to %d bytes", blen);
                free(qbuf);
                return -1;
            }
            qbuf = tmp;
        }
    }

    if ( rc < 0 ) {
        ERROR("Error reading QEMU data");
        free(qbuf);
        return -1;
    }

    if ( memcmp(qbuf, "QEVM", 4) ) {
        ERROR("Invalid QEMU magic: 0x%08x", *(unsigned long*)qbuf);
        free(qbuf);
        return -1;
    }

    buf->qemubuf = qbuf;
    buf->qemubufsize = dlen;

    return 0;
}

static int buffer_qemu(int fd, struct tailbuf_hvm *buf)
{
    uint32_t qlen;
    uint8_t *tmp;

    if ( read_exact(fd, &qlen, sizeof(qlen)) ) {
        ERROR("Error reading QEMU header length");
        return -1;
    }

    if ( qlen > buf->qemubufsize ) {
        if ( buf->qemubuf) {
            tmp = realloc(buf->qemubuf, qlen);
            if ( tmp )
                buf->qemubuf = tmp;
            else {
                ERROR("Error reallocating QEMU state buffer");
                return -1;
            }
        } else {
            buf->qemubuf = malloc(qlen);
            if ( !buf->qemubuf ) {
                ERROR("Error allocating QEMU state buffer");
                return -1;
            }
        }
    }
    buf->qemubufsize = qlen;

    if ( read_exact(fd, buf->qemubuf, buf->qemubufsize) ) {
        ERROR("Error reading QEMU state");
        return -1;
    }

    return 0;
}

static int dump_qemu(uint32_t dom, struct tailbuf_hvm *buf)
{
    int saved_errno;
    char path[256];
    FILE *fp;

    sprintf(path, "/var/lib/xen/qemu-save.%u", dom);
    fp = fopen(path, "wb");
    if ( !fp )
        return -1;

    DPRINTF("Writing %d bytes of QEMU data\n", buf->qemubufsize);
    if ( fwrite(buf->qemubuf, 1, buf->qemubufsize, fp) != buf->qemubufsize) {
        saved_errno = errno;
        fclose(fp);
        errno = saved_errno;
        return -1;
    }

    fclose(fp);

    return 0;
}

static int buffer_tail_hvm(struct restore_ctx *ctx, struct tailbuf_hvm *buf, int fd,
                           unsigned int max_vcpu_id, uint64_t vcpumap,
                           int ext_vcpucontext)
{
    uint8_t *tmp;
    unsigned char qemusig[21];