win-pvdrivers

changeset 1022:cd72cd0e1c19

hooking debug doesn't survive hibernate under win8. Remove it.
Remove initial balloon down - doesn't work under xen 4.2 without xenbus being loaded
author James Harper <james.harper@bendigoit.com.au>
date Tue Feb 19 15:11:49 2013 +1100 (2013-02-19)
parents 6547b07f3236
children 1ce315b193d1
files xenpci/gnttbl.c xenpci/sources xenpci/xenbus.c xenpci/xenpci.c xenpci/xenpci.def xenpci/xenpci.h xenpci/xenpci_dbgprint.c xenpci/xenpci_export.c xenpci/xenpci_fdo.c xenpci/xenpci_pdo.c
line diff
     1.1 --- a/xenpci/gnttbl.c	Wed Feb 13 23:37:17 2013 +1100
     1.2 +++ b/xenpci/gnttbl.c	Tue Feb 19 15:11:49 2013 +1100
     1.3 @@ -29,7 +29,7 @@ GntTbl_PutRef(PVOID Context, grant_ref_t
     1.4  #if DBG
     1.5    if (xpdd->gnttbl_tag[ref].tag != tag)
     1.6      KdPrint((__DRIVER_NAME "     Grant Entry %d for %.4s doesn't match %.4s\n", ref, (PUCHAR)&tag, (PUCHAR)&xpdd->gnttbl_tag[ref].tag));
     1.7 -  NT_ASSERT(xpdd->gnttbl_tag[ref].tag == tag);
     1.8 +  XN_ASSERT(xpdd->gnttbl_tag[ref].tag == tag);
     1.9    xpdd->gnttbl_tag[ref].tag = 0;
    1.10    xpdd->gnttbl_tag[ref].generation = (ULONG)-1;
    1.11  #endif
    1.12 @@ -54,7 +54,7 @@ GntTbl_GetRef(PVOID Context, ULONG tag)
    1.13  #if DBG
    1.14    if (xpdd->gnttbl_tag[ref].tag)
    1.15      KdPrint((__DRIVER_NAME "     Grant Entry %d for %.4s in use by %.4s\n", ref, (PUCHAR)&tag, (PUCHAR)&xpdd->gnttbl_tag[ref].tag));
    1.16 -  NT_ASSERT(!xpdd->gnttbl_tag[ref].tag);
    1.17 +  XN_ASSERT(!xpdd->gnttbl_tag[ref].tag);
    1.18    xpdd->gnttbl_tag[ref].generation = xpdd->gnttbl_generation;
    1.19    xpdd->gnttbl_tag[ref].tag = tag;
    1.20  #endif
    1.21 @@ -104,7 +104,7 @@ GntTbl_GrantAccess(
    1.22    if (ref == INVALID_GRANT_REF)
    1.23      return ref;
    1.24  
    1.25 -  NT_ASSERT(xpdd->gnttbl_tag[ref].tag == tag);
    1.26 +  XN_ASSERT(xpdd->gnttbl_tag[ref].tag == tag);
    1.27    
    1.28    xpdd->gnttbl_table[ref].frame = frame;
    1.29    xpdd->gnttbl_table[ref].domid = domid;
    1.30 @@ -117,7 +117,7 @@ GntTbl_GrantAccess(
    1.31      KdPrint((__DRIVER_NAME "     Grant Entry %d for %.4s still in use\n", ref, (PUCHAR)&tag));
    1.32  #endif
    1.33    }
    1.34 -  NT_ASSERT(!xpdd->gnttbl_table[ref].flags);
    1.35 +  XN_ASSERT(!xpdd->gnttbl_table[ref].flags);
    1.36  
    1.37    KeMemoryBarrier();
    1.38    readonly *= GTF_readonly;
    1.39 @@ -136,8 +136,8 @@ GntTbl_EndAccess(
    1.40    PXENPCI_DEVICE_DATA xpdd = Context;
    1.41    unsigned short flags, nflags;
    1.42  
    1.43 -  NT_ASSERT(ref != INVALID_GRANT_REF);
    1.44 -  NT_ASSERT(xpdd->gnttbl_tag[ref].tag == tag);
    1.45 +  XN_ASSERT(ref != INVALID_GRANT_REF);
    1.46 +  XN_ASSERT(xpdd->gnttbl_tag[ref].tag == tag);
    1.47    
    1.48    nflags = xpdd->gnttbl_table[ref].flags;
    1.49    do {
    1.50 @@ -178,7 +178,7 @@ GntTbl_Init(PXENPCI_DEVICE_DATA xpdd)
    1.51    int i;
    1.52    int grant_entries;
    1.53  
    1.54 -  NT_ASSERT(KeGetCurrentIrql() <= DISPATCH_LEVEL);
    1.55 +  XN_ASSERT(KeGetCurrentIrql() <= DISPATCH_LEVEL);
    1.56    
    1.57    FUNCTION_ENTER();
    1.58    
    1.59 @@ -193,12 +193,12 @@ GntTbl_Init(PXENPCI_DEVICE_DATA xpdd)
    1.60    xpdd->gnttbl_generation = 0;
    1.61    #endif
    1.62    xpdd->gnttbl_table_copy = ExAllocatePoolWithTag(NonPagedPool, xpdd->grant_frames * PAGE_SIZE, XENPCI_POOL_TAG);
    1.63 -  NT_ASSERT(xpdd->gnttbl_table_copy); // lazy
    1.64 +  XN_ASSERT(xpdd->gnttbl_table_copy); // lazy
    1.65    xpdd->gnttbl_table = ExAllocatePoolWithTag(NonPagedPool, xpdd->grant_frames * PAGE_SIZE, XENPCI_POOL_TAG);
    1.66 -  NT_ASSERT(xpdd->gnttbl_table); // lazy
    1.67 +  XN_ASSERT(xpdd->gnttbl_table); // lazy
    1.68    /* dom0 crashes if we allocate the wrong amount of memory here! */
    1.69    xpdd->gnttbl_mdl = IoAllocateMdl(xpdd->gnttbl_table, xpdd->grant_frames * PAGE_SIZE, FALSE, FALSE, NULL);
    1.70 -  NT_ASSERT(xpdd->gnttbl_mdl); // lazy
    1.71 +  XN_ASSERT(xpdd->gnttbl_mdl); // lazy
    1.72    MmBuildMdlForNonPagedPool(xpdd->gnttbl_mdl);
    1.73  
    1.74    /* make some holes for the grant pages to fill in */
    1.75 @@ -332,7 +332,7 @@ GntTbl_Resume(PXENPCI_DEVICE_DATA xpdd)
    1.76  
    1.77    new_grant_frames = GntTbl_QueryMaxFrames(xpdd);
    1.78    KdPrint((__DRIVER_NAME "     new_grant_frames = %d\n", new_grant_frames));
    1.79 -  NT_ASSERT(new_grant_frames >= xpdd->grant_frames); // lazy
    1.80 +  XN_ASSERT(new_grant_frames >= xpdd->grant_frames); // lazy
    1.81    result = GntTbl_Map(xpdd, 0, xpdd->grant_frames - 1);
    1.82    KdPrint((__DRIVER_NAME "     GntTbl_Map result = %d\n", result));
    1.83    memcpy(xpdd->gnttbl_table, xpdd->gnttbl_table_copy, xpdd->grant_frames * PAGE_SIZE);
     2.1 --- a/xenpci/sources	Wed Feb 13 23:37:17 2013 +1100
     2.2 +++ b/xenpci/sources	Tue Feb 19 15:11:49 2013 +1100
     2.3 @@ -13,8 +13,10 @@ TARGETLIBS=$(TARGETLIBS) $(LIBLFDS_DIR)\
     2.4  TARGETLIBS=$(TARGETLIBS) $(LIBLFDS_DIR)\bin\AMD64\liblfds.lib
     2.5  !ENDIF
     2.6  
     2.7 -AMD64_SOURCES=hypercall.asm dbgprint_hook.asm
     2.8 -I386_SOURCES=tpr_emulate.asm dbgprint_hook.asm
     2.9 +AMD64_SOURCES=hypercall.asm
    2.10 +# dbgprint_hook.asm
    2.11 +I386_SOURCES=tpr_emulate.asm
    2.12 +# dbgprint_hook.asm
    2.13  
    2.14  SOURCES=xenpci.rc xenpci.c xenpci_fdo.c xenpci_pdo.c xenpci_export.c \
    2.15          evtchn.c gnttbl.c xenbus.c memory.c xenpci_device_interface.c \
     3.1 --- a/xenpci/xenbus.c	Wed Feb 13 23:37:17 2013 +1100
     3.2 +++ b/xenpci/xenbus.c	Tue Feb 19 15:11:49 2013 +1100
     3.3 @@ -80,7 +80,7 @@ static void xb_write(
     3.4    
     3.5    //FUNCTION_ENTER();
     3.6  
     3.7 -  ASSERT(len <= XENSTORE_RING_SIZE);
     3.8 +  XN_ASSERT(len <= XENSTORE_RING_SIZE);
     3.9    prod = xpdd->xen_store_interface->req_prod;
    3.10    ptr = data;
    3.11    remaining = len;
    3.12 @@ -175,7 +175,7 @@ XenBus_Read(
    3.13  
    3.14    //KdPrint((__DRIVER_NAME " --> " __FUNCTION__ "\n"));
    3.15  
    3.16 -  ASSERT(KeGetCurrentIrql() < DISPATCH_LEVEL);
    3.17 +  XN_ASSERT(KeGetCurrentIrql() < DISPATCH_LEVEL);
    3.18  
    3.19    rep = xenbus_format_msg_reply(xpdd, XS_READ, xbt, req, ARRAY_SIZE(req));
    3.20    msg = errmsg(rep);
    3.21 @@ -210,7 +210,7 @@ XenBus_Write(
    3.22    struct xsd_sockmsg *rep;
    3.23    char *msg;
    3.24  
    3.25 -  ASSERT(KeGetCurrentIrql() < DISPATCH_LEVEL);
    3.26 +  XN_ASSERT(KeGetCurrentIrql() < DISPATCH_LEVEL);
    3.27  
    3.28    rep = xenbus_format_msg_reply(xpdd, XS_WRITE, xbt, req, ARRAY_SIZE(req));
    3.29    msg = errmsg(rep);
    3.30 @@ -301,7 +301,7 @@ XenBus_Dpc(PVOID ServiceContext)
    3.31      }
    3.32  
    3.33      msg_len = min(rsp_prod - xpdd->xen_store_interface->rsp_cons, sizeof(xsd_sockmsg_t) + xpdd->xb_msg->len - xpdd->xb_msg_offset);
    3.34 -    ASSERT(xpdd->xb_msg_offset + msg_len <= sizeof(xsd_sockmsg_t) + xpdd->xb_msg->len);
    3.35 +    XN_ASSERT(xpdd->xb_msg_offset + msg_len <= sizeof(xsd_sockmsg_t) + xpdd->xb_msg->len);
    3.36      memcpy_from_ring(xpdd->xen_store_interface->rsp,
    3.37        (PUCHAR)xpdd->xb_msg + xpdd->xb_msg_offset,
    3.38        MASK_XENSTORE_IDX(xpdd->xen_store_interface->rsp_cons),
    3.39 @@ -319,7 +319,7 @@ XenBus_Dpc(PVOID ServiceContext)
    3.40      if (xpdd->xb_msg->type != XS_WATCH_EVENT)
    3.41      {
    3.42        /* process reply - only ever one outstanding */
    3.43 -      ASSERT(xpdd->xb_reply == NULL);
    3.44 +      XN_ASSERT(xpdd->xb_reply == NULL);
    3.45        xpdd->xb_reply = xpdd->xb_msg;
    3.46        xpdd->xb_msg = NULL;
    3.47        KeSetEvent(&xpdd->xb_request_complete_event, IO_NO_INCREMENT, FALSE);
    3.48 @@ -382,7 +382,7 @@ XenBus_Init(PXENPCI_DEVICE_DATA xpdd)
    3.49      
    3.50    FUNCTION_ENTER();
    3.51  
    3.52 -  ASSERT(KeGetCurrentIrql() == PASSIVE_LEVEL);
    3.53 +  XN_ASSERT(KeGetCurrentIrql() == PASSIVE_LEVEL);
    3.54  
    3.55    KeInitializeSpinLock(&xpdd->xb_ring_spinlock);
    3.56    ExInitializeFastMutex(&xpdd->xb_request_mutex);
    3.57 @@ -444,7 +444,7 @@ XenBus_Halt(PXENPCI_DEVICE_DATA xpdd)
    3.58  
    3.59    FUNCTION_ENTER();
    3.60    
    3.61 -  ASSERT(KeGetCurrentIrql() < DISPATCH_LEVEL);
    3.62 +  XN_ASSERT(KeGetCurrentIrql() < DISPATCH_LEVEL);
    3.63  
    3.64    /* we need to remove the watches as a watch firing could lead to a XenBus_Read/Write/Printf */
    3.65    for (i = 0; i < MAX_WATCH_ENTRIES; i++)
    3.66 @@ -477,7 +477,7 @@ XenBus_List(
    3.67    char **res;
    3.68    char *msg;
    3.69  
    3.70 -  ASSERT(KeGetCurrentIrql() < DISPATCH_LEVEL);
    3.71 +  XN_ASSERT(KeGetCurrentIrql() < DISPATCH_LEVEL);
    3.72  
    3.73    repmsg = xenbus_format_msg_reply(xpdd, XS_DIRECTORY, xbt, req, ARRAY_SIZE(req));
    3.74    msg = errmsg(repmsg);
    3.75 @@ -595,9 +595,9 @@ XenBus_AddWatch(
    3.76    int i;
    3.77    PXENBUS_WATCH_ENTRY w_entry;
    3.78  
    3.79 -  ASSERT(KeGetCurrentIrql() < DISPATCH_LEVEL);
    3.80 +  XN_ASSERT(KeGetCurrentIrql() < DISPATCH_LEVEL);
    3.81  
    3.82 -  ASSERT(strlen(Path) < ARRAY_SIZE(w_entry->Path));
    3.83 +  XN_ASSERT(strlen(Path) < ARRAY_SIZE(w_entry->Path));
    3.84  
    3.85    ExAcquireFastMutex(&xpdd->xb_watch_mutex);
    3.86  
    3.87 @@ -645,7 +645,7 @@ XenBus_RemWatch(
    3.88    char *msg;
    3.89    int i;
    3.90  
    3.91 -  ASSERT(KeGetCurrentIrql() < DISPATCH_LEVEL);
    3.92 +  XN_ASSERT(KeGetCurrentIrql() < DISPATCH_LEVEL);
    3.93  
    3.94    ExAcquireFastMutex(&xpdd->xb_watch_mutex);
    3.95  
    3.96 @@ -687,7 +687,7 @@ XenBus_StartTransaction(PVOID Context, x
    3.97    struct xsd_sockmsg *rep;
    3.98    char *err;
    3.99  
   3.100 -  ASSERT(KeGetCurrentIrql() < DISPATCH_LEVEL);
   3.101 +  XN_ASSERT(KeGetCurrentIrql() < DISPATCH_LEVEL);
   3.102  
   3.103    rep = xenbus_format_msg_reply(xpdd, XS_TRANSACTION_START, 0, &req, 1);
   3.104    err = errmsg(rep);
   3.105 @@ -744,7 +744,7 @@ XenBus_Printf(
   3.106    char buf[512];
   3.107    char *retval;
   3.108  
   3.109 -  ASSERT(KeGetCurrentIrql() < DISPATCH_LEVEL);
   3.110 +  XN_ASSERT(KeGetCurrentIrql() < DISPATCH_LEVEL);
   3.111  
   3.112    va_start(ap, fmt);
   3.113    RtlStringCbVPrintfA(buf, ARRAY_SIZE(buf), fmt, ap);
     4.1 --- a/xenpci/xenpci.c	Wed Feb 13 23:37:17 2013 +1100
     4.2 +++ b/xenpci/xenpci.c	Tue Feb 19 15:11:49 2013 +1100
     4.3 @@ -103,6 +103,7 @@ XenPci_EvtDeviceAdd_XenPci(WDFDRIVER dri
     4.4    WDFKEY param_key;
     4.5    DECLARE_CONST_UNICODE_STRING(veto_devices_name, L"veto_devices");
     4.6    WDF_DEVICE_POWER_CAPABILITIES power_capabilities;
     4.7 +  PPHYSICAL_MEMORY_RANGE pmr_head, pmr;
     4.8    int i;
     4.9    
    4.10    UNREFERENCED_PARAMETER(driver);
    4.11 @@ -138,8 +139,7 @@ XenPci_EvtDeviceAdd_XenPci(WDFDRIVER dri
    4.12    
    4.13    WDF_OBJECT_ATTRIBUTES_INIT_CONTEXT_TYPE(&device_attributes, XENPCI_DEVICE_DATA);
    4.14    status = WdfDeviceCreate(&device_init, &device_attributes, &device);
    4.15 -  if (!NT_SUCCESS(status))
    4.16 -  {
    4.17 +  if (!NT_SUCCESS(status)) {
    4.18      KdPrint(("Error creating device %08x\n", status));
    4.19      return status;
    4.20    }
    4.21 @@ -148,26 +148,33 @@ XenPci_EvtDeviceAdd_XenPci(WDFDRIVER dri
    4.22    xpdd->wdf_device = device;
    4.23    xpdd->child_list = WdfFdoGetDefaultChildList(device);
    4.24  
    4.25 +  /* this is not a documented function */
    4.26 +  KeInitializeEvent(&xpdd->balloon_event, SynchronizationEvent, FALSE);
    4.27 +  pmr_head = MmGetPhysicalMemoryRanges();
    4.28 +  xpdd->current_memory_kb = 0;
    4.29 +  for (pmr = pmr_head; !(pmr->BaseAddress.QuadPart == 0 && pmr->NumberOfBytes.QuadPart == 0); pmr++) {
    4.30 +    xpdd->current_memory_kb += (ULONG)(pmr->NumberOfBytes.QuadPart / 1024);
    4.31 +  }
    4.32 +  FUNCTION_MSG("current_memory_kb = %d\n", xpdd->current_memory_kb);
    4.33 +  /* round to MB increments because that is what balloon deals in */
    4.34 +  xpdd->current_memory_kb = (xpdd->current_memory_kb + 0x1FF) & 0xFFFFFC00;
    4.35 +  FUNCTION_MSG("current_memory_kb rounded to %d\n", xpdd->current_memory_kb);
    4.36 +
    4.37    ExInitializeFastMutex(&xpdd->suspend_mutex);
    4.38    WdfCollectionCreate(WDF_NO_OBJECT_ATTRIBUTES, &veto_devices);
    4.39    status = WdfDriverOpenParametersRegistryKey(driver, KEY_QUERY_VALUE, WDF_NO_OBJECT_ATTRIBUTES, &param_key);
    4.40 -  if (NT_SUCCESS(status))
    4.41 -  {
    4.42 +  if (NT_SUCCESS(status)) {
    4.43      status = WdfRegistryQueryMultiString(param_key, &veto_devices_name, WDF_NO_OBJECT_ATTRIBUTES, veto_devices);
    4.44 -    if (!NT_SUCCESS(status))
    4.45 -    {
    4.46 +    if (!NT_SUCCESS(status)) {
    4.47        KdPrint(("Error reading parameters/veto_devices value %08x\n", status));
    4.48      }
    4.49      WdfRegistryClose(param_key);
    4.50 -  }
    4.51 -  else
    4.52 -  {
    4.53 +  } else {
    4.54      KdPrint(("Error opening parameters key %08x\n", status));
    4.55    }
    4.56  
    4.57    InitializeListHead(&xpdd->veto_list);
    4.58 -  for (i = 0; i < (int)WdfCollectionGetCount(veto_devices); i++)
    4.59 -  {
    4.60 +  for (i = 0; i < (int)WdfCollectionGetCount(veto_devices); i++) {
    4.61      WDFOBJECT ws;
    4.62      UNICODE_STRING val;
    4.63      ANSI_STRING s;
    4.64 @@ -259,8 +266,7 @@ XenHide_EvtDevicePrepareHardware(WDFDEVI
    4.65  }
    4.66  
    4.67  static BOOLEAN
    4.68 -XenPci_IdSuffixMatches(PWDFDEVICE_INIT device_init, PWCHAR matching_id)
    4.69 -{
    4.70 +XenPci_IdSuffixMatches(PWDFDEVICE_INIT device_init, PWCHAR matching_id) {
    4.71    NTSTATUS status;
    4.72    WDFMEMORY memory;
    4.73    ULONG remaining;
    4.74 @@ -280,33 +286,25 @@ XenPci_IdSuffixMatches(PWDFDEVICE_INIT d
    4.75        continue;
    4.76      ids = WdfMemoryGetBuffer(memory, &ids_length);
    4.77  
    4.78 -    if (!NT_SUCCESS(status))
    4.79 -    {
    4.80 -//      KdPrint((__DRIVER_NAME "     i = %d, status = %x, ids_length = %d\n", i, status, ids_length));
    4.81 +    if (!NT_SUCCESS(status)) {
    4.82        continue;
    4.83      }
    4.84      
    4.85      remaining = (ULONG)ids_length / 2;
    4.86 -    for (ptr = ids; *ptr != 0; ptr += string_length + 1)
    4.87 -    {
    4.88 +    for (ptr = ids; *ptr != 0; ptr += string_length + 1) {
    4.89        RtlStringCchLengthW(ptr, remaining, &string_length);
    4.90        remaining -= (ULONG)string_length + 1;
    4.91 -      if (string_length >= wcslen(matching_id))
    4.92 -      {
    4.93 +      if (string_length >= wcslen(matching_id)) {
    4.94          ptr += string_length - wcslen(matching_id);
    4.95          string_length = wcslen(matching_id);
    4.96        }
    4.97 -//      KdPrint((__DRIVER_NAME "     Comparing '%S' and '%S'\n", ptr, matching_id));
    4.98 -      if (wcscmp(ptr, matching_id) == 0)
    4.99 -      {
   4.100 -        //KdPrint((__DRIVER_NAME " <-- " __FUNCTION__ " (Match)\n"));
   4.101 +      if (wcscmp(ptr, matching_id) == 0) {
   4.102          WdfObjectDelete(memory);
   4.103          return TRUE;
   4.104        }
   4.105      }
   4.106      WdfObjectDelete(memory);
   4.107    }
   4.108 -//  KdPrint((__DRIVER_NAME " <-- " __FUNCTION__ " (No match)\n"));
   4.109    return FALSE;
   4.110  }
   4.111  
   4.112 @@ -395,8 +393,7 @@ ULONG tpr_patch_requested;
   4.113  extern PULONG InitSafeBootMode;
   4.114  
   4.115  VOID
   4.116 -XenPci_HideQemuDevices()
   4.117 -{
   4.118 +XenPci_HideQemuDevices() {
   4.119    #pragma warning(suppress:28138)
   4.120    WRITE_PORT_USHORT(XEN_IOPORT_DEVICE_MASK, (USHORT)qemu_hide_flags_value); //QEMU_UNPLUG_ALL_IDE_DISKS|QEMU_UNPLUG_ALL_NICS);
   4.121    KdPrint((__DRIVER_NAME "     Disabled qemu devices %02x\n", qemu_hide_flags_value));
   4.122 @@ -406,13 +403,11 @@ static BOOLEAN
   4.123  XenPci_CheckHideQemuDevices()
   4.124  {
   4.125    #pragma warning(suppress:28138)
   4.126 -  if (READ_PORT_USHORT(XEN_IOPORT_MAGIC) == 0x49d2)
   4.127 -  {
   4.128 +  if (READ_PORT_USHORT(XEN_IOPORT_MAGIC) == 0x49d2) {
   4.129      #pragma warning(suppress:28138)
   4.130      qemu_protocol_version = READ_PORT_UCHAR(XEN_IOPORT_VERSION);
   4.131      KdPrint((__DRIVER_NAME "     Version = %d\n", qemu_protocol_version));
   4.132 -    switch(qemu_protocol_version)
   4.133 -    {
   4.134 +    switch(qemu_protocol_version) {
   4.135      case 1:
   4.136        #pragma warning(suppress:28138)
   4.137        WRITE_PORT_USHORT(XEN_IOPORT_PRODUCT, XEN_PV_PRODUCT_NUMBER);
   4.138 @@ -562,126 +557,9 @@ XenPci_EvtDriverUnload(WDFDRIVER driver)
   4.139  {
   4.140    UNREFERENCED_PARAMETER(driver);
   4.141    
   4.142 -  #if DBG
   4.143 -  XenPci_UnHookDbgPrint();
   4.144 -  #endif  
   4.145 -}
   4.146 -
   4.147 -/* we need to balloon down very early on in the case of PoD, so things get a little messy */
   4.148 -static PMDL
   4.149 -XenPci_InitialBalloonDown()
   4.150 -{
   4.151 -  PVOID hypercall_stubs;
   4.152 -  domid_t domid = DOMID_SELF;
   4.153 -  ULONG maximum_reservation;
   4.154 -  ULONG current_reservation;
   4.155 -  ULONG extra_kb;
   4.156 -  ULONG ret;
   4.157 -  struct xen_memory_reservation reservation;
   4.158 -  xen_pfn_t *pfns;
   4.159 -  PMDL head = NULL;
   4.160 -  PMDL mdl;
   4.161 -  int i, j;
   4.162 -  ULONG curr_pfns_offset;
   4.163 -  PHYSICAL_ADDRESS alloc_low;
   4.164 -  PHYSICAL_ADDRESS alloc_high;
   4.165 -  PHYSICAL_ADDRESS alloc_skip;
   4.166 -
   4.167 -  FUNCTION_ENTER();
   4.168 -  
   4.169 -  hypercall_stubs = hvm_get_hypercall_stubs();
   4.170 -  if (!hypercall_stubs)
   4.171 -  {
   4.172 -    KdPrint((__DRIVER_NAME "     Failed to copy hypercall stubs. Maybe not running under Xen?\n"));
   4.173 -    FUNCTION_EXIT();
   4.174 -    return NULL;
   4.175 -  }
   4.176 -  if (xen_version_major < 4)
   4.177 -  {
   4.178 -    FUNCTION_MSG("No support for PoD. Cannot do initial balloon down.\n");
   4.179 -    FUNCTION_MSG("Expect a crash if maxmem is set much larger than memory.\n");
   4.180 -    FUNCTION_EXIT();
   4.181 -    return NULL;
   4.182 -  }
   4.183 -  ret = _HYPERVISOR_memory_op(hypercall_stubs, XENMEM_maximum_reservation, &domid);
   4.184 -  KdPrint((__DRIVER_NAME "     XENMEM_maximum_reservation = %d\n", ret));
   4.185 -  maximum_reservation = ret;
   4.186 -  ret = _HYPERVISOR_memory_op(hypercall_stubs, XENMEM_current_reservation, &domid);
   4.187 -  KdPrint((__DRIVER_NAME "     XENMEM_current_reservation = %d\n", ret));
   4.188 -  current_reservation = ret;
   4.189 -
   4.190 -  extra_kb = (maximum_reservation - current_reservation) << 2;
   4.191 -
   4.192 -  alloc_low.QuadPart = 0;
   4.193 -  alloc_high.QuadPart = 0xFFFFFFFFFFFFFFFFULL;
   4.194 -  alloc_skip.QuadPart = PAGE_SIZE;
   4.195 -
   4.196 -  KdPrint((__DRIVER_NAME "     Trying to give %d KB (%d MB) to Xen\n", extra_kb, extra_kb >> 10));
   4.197 -
   4.198 -  /* this code is mostly duplicated from the actual balloon thread... too hard to reuse */
   4.199 -  pfns = ExAllocatePoolWithTag(NonPagedPool, max(BALLOON_UNIT_PAGES, (64 << 8)) * sizeof(xen_pfn_t), XENPCI_POOL_TAG);
   4.200 -  if (!pfns) {
   4.201 -      /* If we can't balloon down then we are going to crash in strange ways later. Better to bug check now. */
   4.202 -      KdPrint((__DRIVER_NAME "     Initial Balloon Down failed - no memory for pfn list\n"));
   4.203 -      #pragma warning(suppress:28159)
   4.204 -      KeBugCheckEx(('X' << 16)|('E' << 8)|('N'), 0x00000003, 0x00000000, 0x00000000, 0x00000000);
   4.205 -  }
   4.206 -  curr_pfns_offset = 0;
   4.207 -  /* this makes sure we balloon up to the next multiple of BALLOON_UNITS_KB */
   4.208 -  for (j = 0; j < (int)extra_kb; j += BALLOON_UNITS_KB)
   4.209 -  {
   4.210 -    #if (NTDDI_VERSION >= NTDDI_WS03SP1)
   4.211 -    /* our contract says that we must zero pages before returning to xen, so we can't use MM_DONT_ZERO_ALLOCATION */
   4.212 -    mdl = MmAllocatePagesForMdlEx(alloc_low, alloc_high, alloc_skip, BALLOON_UNITS_KB * 1024, MmCached, 0);
   4.213 -    #else
   4.214 -    mdl = MmAllocatePagesForMdl(alloc_low, alloc_high, alloc_skip, BALLOON_UNITS_KB * 1024);
   4.215 -    #endif
   4.216 -    if (!mdl || MmGetMdlByteCount(mdl) != BALLOON_UNITS_KB * 1024)
   4.217 -    {
   4.218 -      /* this should actually never happen. If we can't allocate the memory it means windows is using it, and if it was using it we would have crashed already... */
   4.219 -      KdPrint((__DRIVER_NAME "     Initial Balloon Down failed\n"));
   4.220 -      #pragma warning(suppress:28159)
   4.221 -      KeBugCheckEx(('X' << 16)|('E' << 8)|('N'), 0x00000002, extra_kb, j, 0x00000000);
   4.222 -    }
   4.223 -    else
   4.224 -    {
   4.225 -      /* sizeof(xen_pfn_t) may not be the same as PPFN_NUMBER */
   4.226 -      for (i = 0; i < BALLOON_UNIT_PAGES; i++)
   4.227 -      {
   4.228 -        pfns[curr_pfns_offset] = (xen_pfn_t)(MmGetMdlPfnArray(mdl)[i]);
   4.229 -        curr_pfns_offset++;
   4.230 -      }
   4.231 -      if (curr_pfns_offset == (ULONG)max(BALLOON_UNIT_PAGES, (64 << 8)) || j + BALLOON_UNITS_KB > (int)extra_kb)
   4.232 -      {
   4.233 -        reservation.address_bits = 0;
   4.234 -        reservation.extent_order = 0;
   4.235 -        reservation.domid = DOMID_SELF;
   4.236 -        reservation.nr_extents = curr_pfns_offset;
   4.237 -        #pragma warning(disable: 4127) /* conditional expression is constant */
   4.238 -        set_xen_guest_handle(reservation.extent_start, pfns);
   4.239 -        ret = _HYPERVISOR_memory_op(hypercall_stubs, XENMEM_decrease_reservation, &reservation);
   4.240 -        if (ret != curr_pfns_offset)
   4.241 -          FUNCTION_MSG("only decreased %d of %d pages\n", ret, curr_pfns_offset);
   4.242 -        curr_pfns_offset = 0;
   4.243 -      }
   4.244 -      if (head)
   4.245 -      {
   4.246 -        mdl->Next = head;
   4.247 -        head = mdl;
   4.248 -      }
   4.249 -      else
   4.250 -      {
   4.251 -        head = mdl;
   4.252 -      }
   4.253 -    }
   4.254 -//KdPrint((__DRIVER_NAME "     C\n"));
   4.255 -  }
   4.256 -  ExFreePoolWithTag(pfns, XENPCI_POOL_TAG);
   4.257 -  hvm_free_hypercall_stubs(hypercall_stubs);
   4.258 -  
   4.259 -  FUNCTION_EXIT();
   4.260 -  
   4.261 -  return head;
   4.262 +//  #if DBG
   4.263 +//  XenPci_UnHookDbgPrint();
   4.264 +//  #endif  
   4.265  }
   4.266  
   4.267  #if (NTDDI_VERSION >= NTDDI_WS03SP1)  
   4.268 @@ -742,13 +620,6 @@ DriverEntry(PDRIVER_OBJECT DriverObject,
   4.269  
   4.270    FUNCTION_MSG(__DRIVER_NAME " " VER_FILEVERSION_STR "\n");
   4.271  
   4.272 -  #if DBG
   4.273 -  XenPci_HookDbgPrint();
   4.274 -  #endif
   4.275 -
   4.276 -  NT_ASSERT(!balloon_mdl_head);
   4.277 -  balloon_mdl_head = XenPci_InitialBalloonDown();
   4.278 -
   4.279  #if (NTDDI_VERSION >= NTDDI_WS03SP1)
   4.280    status = KeInitializeCrashDumpHeader(DUMP_TYPE_FULL, 0, NULL, 0, &dump_header_size);
   4.281    /* try and allocate contiguous memory as low as possible */
   4.282 @@ -756,7 +627,11 @@ DriverEntry(PDRIVER_OBJECT DriverObject,
   4.283    dump_header_mem_max.QuadPart = 0xFFFFF;
   4.284    while (!dump_header && dump_header_mem_max.QuadPart != 0xFFFFFFFFFFFFFFFF) {
   4.285      dump_header = MmAllocateContiguousMemory(DUMP_HEADER_PREFIX_SIZE + dump_header_size + DUMP_HEADER_SUFFIX_SIZE, dump_header_mem_max);
   4.286 -    dump_header_mem_max.QuadPart = (dump_header_mem_max.QuadPart << 8) | 0xF;
   4.287 +    if (dump_header) {
   4.288 +      FUNCTION_MSG("Allocated crash dump header < 0x%016I64x\n", dump_header_mem_max.QuadPart);
   4.289 +      break;
   4.290 +    }
   4.291 +    dump_header_mem_max.QuadPart = (dump_header_mem_max.QuadPart << 4) | 0xF;
   4.292    }
   4.293    if (dump_header) {
   4.294      status = KeInitializeCrashDumpHeader(DUMP_TYPE_FULL, 0, dump_header + DUMP_HEADER_PREFIX_SIZE, dump_header_size, &dump_header_size);
   4.295 @@ -779,28 +654,25 @@ DriverEntry(PDRIVER_OBJECT DriverObject,
   4.296    WDF_DRIVER_CONFIG_INIT(&config, XenPci_EvtDeviceAdd);
   4.297    config.EvtDriverUnload = XenPci_EvtDriverUnload;
   4.298    status = WdfDriverCreate(DriverObject, RegistryPath, WDF_NO_OBJECT_ATTRIBUTES, &config, &driver);
   4.299 -  if (!NT_SUCCESS(status))
   4.300 -  {
   4.301 +  if (!NT_SUCCESS(status)) {
   4.302      KdPrint((__DRIVER_NAME "     WdfDriverCreate failed with status 0x%x\n", status));
   4.303      FUNCTION_EXIT();
   4.304 -    #if DBG
   4.305 -    XenPci_UnHookDbgPrint();
   4.306 -    #endif
   4.307 +    //#if DBG
   4.308 +    //XenPci_UnHookDbgPrint();
   4.309 +    //#endif
   4.310      return status;
   4.311    }
   4.312    WDF_OBJECT_ATTRIBUTES_INIT(&parent_attributes);
   4.313    parent_attributes.ParentObject = driver;
   4.314    
   4.315    status = WdfDriverOpenParametersRegistryKey(driver, KEY_QUERY_VALUE, &parent_attributes, &param_key);
   4.316 -  if (!NT_SUCCESS(status))
   4.317 -  {
   4.318 +  if (!NT_SUCCESS(status)) {
   4.319      KdPrint(("Error opening parameters key %08x\n", status));
   4.320      goto error;
   4.321    }
   4.322  
   4.323    status = AuxKlibInitialize();
   4.324 -  if(!NT_SUCCESS(status))
   4.325 -  {
   4.326 +  if(!NT_SUCCESS(status)) {
   4.327      KdPrint((__DRIVER_NAME "     AuxKlibInitialize failed %08x\n", status));
   4.328      goto error;
   4.329    }
   4.330 @@ -809,8 +681,7 @@ DriverEntry(PDRIVER_OBJECT DriverObject,
   4.331  
   4.332    RtlInitUnicodeString(&system_start_options, L"failed to read");
   4.333    status = WdfRegistryOpenKey(NULL, &control_key_name, GENERIC_READ, &parent_attributes, &control_key);
   4.334 -  if (NT_SUCCESS(status))
   4.335 -  {
   4.336 +  if (NT_SUCCESS(status)) {
   4.337      status = WdfStringCreate(NULL, &parent_attributes, &wdf_system_start_options);
   4.338      status = WdfRegistryQueryString(control_key, &system_start_options_name, wdf_system_start_options);
   4.339      if (NT_SUCCESS(status))
   4.340 @@ -822,8 +693,7 @@ DriverEntry(PDRIVER_OBJECT DriverObject,
   4.341    
   4.342    always_patch = 0;
   4.343    WdfRegistryQueryULong(param_key, &txt_always_patch_name, &always_patch);
   4.344 -  if (always_patch || (system_start_options.Buffer && wcsstr(system_start_options.Buffer, L"PATCHTPR")))
   4.345 -  {
   4.346 +  if (always_patch || (system_start_options.Buffer && wcsstr(system_start_options.Buffer, L"PATCHTPR"))) {
   4.347      DECLARE_CONST_UNICODE_STRING(verifier_key_name, L"\\Registry\\Machine\\System\\CurrentControlSet\\Control\\Session Manager\\Memory Management");
   4.348      WDFKEY memory_key;
   4.349      ULONG verifier_value;
   4.350 @@ -879,9 +749,6 @@ DriverEntry(PDRIVER_OBJECT DriverObject,
   4.351    return STATUS_SUCCESS;
   4.352  
   4.353  error:
   4.354 -  #if DBG
   4.355 -  XenPci_UnHookDbgPrint();
   4.356 -  #endif
   4.357    KdPrint(("Failed, returning %08x\n", status));
   4.358    FUNCTION_EXIT();
   4.359    return status;
     5.1 --- a/xenpci/xenpci.def	Wed Feb 13 23:37:17 2013 +1100
     5.2 +++ b/xenpci/xenpci.def	Tue Feb 19 15:11:49 2013 +1100
     5.3 @@ -28,4 +28,5 @@ EXPORTS
     5.4   XnReadInt64
     5.5   XnWriteInt64
     5.6  
     5.7 - XnDumpModeHookDebugPrint
     5.8 \ No newline at end of file
     5.9 + XnDebugPrint
    5.10 + XnPrintDump
    5.11 \ No newline at end of file
     6.1 --- a/xenpci/xenpci.h	Wed Feb 13 23:37:17 2013 +1100
     6.2 +++ b/xenpci/xenpci.h	Tue Feb 19 15:11:49 2013 +1100
     6.3 @@ -188,7 +188,7 @@ typedef struct {
     6.4    PKTHREAD balloon_thread;
     6.5    KEVENT balloon_event;
     6.6    BOOLEAN balloon_shutdown;
     6.7 -  ULONG initial_memory_kb;
     6.8 +  //ULONG initial_memory_kb;
     6.9    ULONG current_memory_kb;
    6.10    ULONG target_memory_kb;
    6.11    
    6.12 @@ -377,9 +377,16 @@ VOID XenPci_HighSync(PXENPCI_HIGHSYNC_FU
    6.13  
    6.14  VOID XenPci_PatchKernel(PXENPCI_DEVICE_DATA xpdd, PVOID base, ULONG length);
    6.15  
    6.16 -NTSTATUS XenPci_HookDbgPrint();
    6.17 -NTSTATUS XenPci_UnHookDbgPrint();
    6.18 -VOID XenPci_DumpModeHookDebugPrint();
    6.19 +//NTSTATUS XenPci_HookDbgPrint();
    6.20 +//NTSTATUS XenPci_ReHookDbgPrint();
    6.21 +//NTSTATUS XenPci_UnHookDbgPrint();
    6.22 +//VOID XenPci_DumpModeHookDebugPrint();
    6.23 +#include <stdlib.h>
    6.24 +
    6.25 +NTSTATUS
    6.26 +XenPci_DebugPrintV(PCHAR format, va_list args);
    6.27 +NTSTATUS
    6.28 +XenPci_DebugPrint(PCHAR format, ...);
    6.29  
    6.30  struct xsd_sockmsg *XenBus_Raw(PXENPCI_DEVICE_DATA xpdd, struct xsd_sockmsg *msg);
    6.31  char *XenBus_Read(PVOID Context, xenbus_transaction_t xbt, char *path, char **value);
     7.1 --- a/xenpci/xenpci_dbgprint.c	Wed Feb 13 23:37:17 2013 +1100
     7.2 +++ b/xenpci/xenpci_dbgprint.c	Tue Feb 19 15:11:49 2013 +1100
     7.3 @@ -18,72 +18,29 @@ Foundation, Inc., 51 Franklin Street, Fi
     7.4  */
     7.5  
     7.6  #include "xenpci.h"
     7.7 -#include <aux_klib.h>
     7.8 -
     7.9 -#pragma intrinsic(_enable)
    7.10 -#pragma intrinsic(_disable)
    7.11  
    7.12 -#pragma pack(1)
    7.13 -#ifdef _AMD64_
    7.14 -typedef struct __KIDT_ENTRY
    7.15 -{
    7.16 -  USHORT addr_0_15;
    7.17 -  USHORT selector;
    7.18 -  USHORT access;
    7.19 -  USHORT addr_16_31;
    7.20 -  ULONG  addr_32_63;
    7.21 -  ULONG  reserved;
    7.22 -} IDT_ENTRY, *PIDT_ENTRY;
    7.23 -#else
    7.24 -typedef struct __KIDT_ENTRY
    7.25 -{
    7.26 -  USHORT addr_0_15;
    7.27 -  USHORT selector;
    7.28 -  USHORT access;
    7.29 -  USHORT addr_16_31;
    7.30 -} IDT_ENTRY, *PIDT_ENTRY;
    7.31 -#endif
    7.32 -#pragma pack()
    7.33 -
    7.34 -#pragma pack(2)
    7.35 -typedef struct _IDT
    7.36 -{
    7.37 -  USHORT limit;
    7.38 -  PIDT_ENTRY entries;
    7.39 -} IDT, *PIDT;
    7.40 -#pragma pack()
    7.41 -
    7.42 -/* Not really necessary but keeps PREfast happy */
    7.43 -#if (VER_PRODUCTBUILD >= 7600)
    7.44 -static KBUGCHECK_CALLBACK_ROUTINE XenPci_BugcheckCallback;
    7.45 -#endif
    7.46 -KBUGCHECK_CALLBACK_RECORD callback_record;
    7.47 -
    7.48 -extern VOID Int2dHandlerNew(VOID);
    7.49 -extern PVOID Int2dHandlerOld;
    7.50 -
    7.51 -static BOOLEAN debug_port_enabled = FALSE;
    7.52 +static BOOLEAN last_newline = TRUE;
    7.53  static volatile LONG debug_print_lock = 0;
    7.54  
    7.55 -static BOOLEAN last_newline = TRUE;
    7.56 -
    7.57 -/* This appears to be called with interrupts disabled already, so no need to go to HIGH_LEVEL or anything like that */
    7.58 -static void XenDbgPrint(PCHAR string, ULONG length)
    7.59 -{
    7.60 +NTSTATUS
    7.61 +XenPci_DebugPrintV(PCHAR format, va_list args) {
    7.62 +  NTSTATUS status;
    7.63 +  KIRQL old_irql;
    7.64 +  CHAR buf[512]; /* truncate anything larger */
    7.65    ULONG i;
    7.66    ULONGLONG j;
    7.67    LARGE_INTEGER current_time;
    7.68 -  //KIRQL old_irql = 0;
    7.69  
    7.70 +  status = RtlStringCbVPrintfA(buf, ARRAY_SIZE(buf), format, args);  
    7.71 +  if (status != STATUS_SUCCESS)
    7.72 +    return status;
    7.73 +  KeRaiseIrql(HIGH_LEVEL, &old_irql);
    7.74    /* make sure that each print gets to complete in its entirety */
    7.75    while(InterlockedCompareExchange(&debug_print_lock, 1, 0) == 1)
    7.76      KeStallExecutionProcessor(1);
    7.77 -
    7.78 -  for (i = 0; i < length; i++)
    7.79 -  {
    7.80 +  for (i = 0; i < strlen(buf); i++) {
    7.81      /* only write a timestamp if the last character was a newline */
    7.82 -    if (last_newline)
    7.83 -    {
    7.84 +    if (last_newline) {
    7.85        KeQuerySystemTime(&current_time);
    7.86        current_time.QuadPart /= 10000; /* convert to ms */
    7.87        for (j = 1000000000000000000L; j >= 1; j /= 10)
    7.88 @@ -99,259 +56,22 @@ static void XenDbgPrint(PCHAR string, UL
    7.89        WRITE_PORT_UCHAR(XEN_IOPORT_LOG, ' ');
    7.90      }
    7.91      #pragma warning(suppress:28138)
    7.92 -    WRITE_PORT_UCHAR(XEN_IOPORT_LOG, string[i]);
    7.93 -    last_newline = (string[i] == '\n');
    7.94 +    WRITE_PORT_UCHAR(XEN_IOPORT_LOG, buf[i]);
    7.95 +    last_newline = (buf[i] == '\n');
    7.96    }
    7.97    /* release the lock */
    7.98    InterlockedExchange(&debug_print_lock, 0);
    7.99 -}
   7.100 -
   7.101 -static VOID
   7.102 -XenPci_DbgWriteChar(CHAR c)
   7.103 -{
   7.104 -  #pragma warning(suppress:28138)
   7.105 -  WRITE_PORT_UCHAR(XEN_IOPORT_LOG, c);
   7.106 -}
   7.107 -
   7.108 -static VOID
   7.109 -XenPci_DbgWriteString(PCHAR string)
   7.110 -{
   7.111 -  while (*string)
   7.112 -  {
   7.113 -    #pragma warning(suppress:28138)
   7.114 -    WRITE_PORT_UCHAR(XEN_IOPORT_LOG, *string);
   7.115 -    string++;
   7.116 -  }
   7.117 -}
   7.118 -
   7.119 -static VOID
   7.120 -XenPci_DbgWriteHexByte(UCHAR byte)
   7.121 -{
   7.122 -  char *digits = "0123456789ABCDEF";
   7.123 -  XenPci_DbgWriteChar(digits[byte >> 4]);
   7.124 -  XenPci_DbgWriteChar(digits[byte & 0x0F]);
   7.125 -}
   7.126 -
   7.127 -static VOID
   7.128 -XenPci_DbgWriteULONG(ULONG data)
   7.129 -{
   7.130 -  int i;
   7.131 -  for (i = 0; i < sizeof(data); i++)
   7.132 -    XenPci_DbgWriteHexByte((UCHAR)(data >> ((sizeof(data) - 1 - i) << 3)));
   7.133 -}
   7.134 -
   7.135 -static VOID
   7.136 -XenPci_DbgWriteULONG_PTR(ULONG_PTR data)
   7.137 -{
   7.138 -  int i;
   7.139 -  for (i = 0; i < sizeof(data); i++)
   7.140 -    XenPci_DbgWriteHexByte((UCHAR)(data >> ((sizeof(data) - 1 - i) << 3)));
   7.141 -}
   7.142 -
   7.143 -static VOID
   7.144 -XenPci_BugcheckCallback(PVOID buffer, ULONG length)
   7.145 -{
   7.146 -  NTSTATUS status;
   7.147 -  KBUGCHECK_DATA bugcheck_data;
   7.148 -  
   7.149 -  UNREFERENCED_PARAMETER(buffer);
   7.150 -  UNREFERENCED_PARAMETER(length);
   7.151 -  
   7.152 -  bugcheck_data.BugCheckDataSize  = sizeof(bugcheck_data);
   7.153 -  status = AuxKlibGetBugCheckData(&bugcheck_data);
   7.154 -  if(!NT_SUCCESS(status))
   7.155 -  {
   7.156 -    XenPci_DbgWriteString(__DRIVER_NAME "     AuxKlibGetBugCheckData returned ");
   7.157 -    XenPci_DbgWriteULONG(status);
   7.158 -    XenPci_DbgWriteString("\n");
   7.159 -    return;
   7.160 -  }
   7.161 -  XenPci_DbgWriteString(__DRIVER_NAME "     Bug check 0x");
   7.162 -  XenPci_DbgWriteULONG(bugcheck_data.BugCheckCode);
   7.163 -  XenPci_DbgWriteString(" (0x");
   7.164 -  XenPci_DbgWriteULONG_PTR(bugcheck_data.Parameter1);
   7.165 -  XenPci_DbgWriteString(", 0x");
   7.166 -  XenPci_DbgWriteULONG_PTR(bugcheck_data.Parameter2);
   7.167 -  XenPci_DbgWriteString(", 0x");
   7.168 -  XenPci_DbgWriteULONG_PTR(bugcheck_data.Parameter3);
   7.169 -  XenPci_DbgWriteString(", 0x");
   7.170 -  XenPci_DbgWriteULONG_PTR(bugcheck_data.Parameter4);
   7.171 -  XenPci_DbgWriteString(")\n");
   7.172 -}
   7.173 -
   7.174 -VOID
   7.175 -Int2dHandlerProc(ULONG_PTR dbg_type, PVOID arg2, PVOID arg3, PVOID arg4, PVOID arg5)
   7.176 -{
   7.177 -  CHAR buf[512];
   7.178 -
   7.179 -  switch (dbg_type)
   7.180 -  {
   7.181 -  case 1: /* DbgPrint */
   7.182 -    XenDbgPrint((PCHAR)arg2, (ULONG)(ULONG_PTR)arg3);
   7.183 -    break;
   7.184 -  case 2: /* ASSERT */
   7.185 -  case 3: /* ??? */
   7.186 -  case 4: /* ??? */
   7.187 -    break;
   7.188 -  default:
   7.189 -    RtlStringCbPrintfA(buf, ARRAY_SIZE(buf), "*** %d %08x %08x %08x %08x\n", dbg_type, arg2, arg3, arg4, arg5);
   7.190 -    XenDbgPrint(buf, (ULONG)strlen(buf));
   7.191 -    break;
   7.192 -  }
   7.193 -  return;
   7.194 -}
   7.195 -
   7.196 -static VOID
   7.197 -XenPci_DbgPrintCallback(PSTRING output, ULONG component_id, ULONG level)
   7.198 -{
   7.199 -  UNREFERENCED_PARAMETER(component_id);
   7.200 -  UNREFERENCED_PARAMETER(level);
   7.201 -  
   7.202 -  XenDbgPrint(output->Buffer, output->Length);
   7.203 -}
   7.204 -
   7.205 -#if 0
   7.206 -typedef struct _hook_info {
   7.207 -  PIDT_ENTRY idt_entry;
   7.208 -} hook_info_t;
   7.209 -#endif
   7.210 -
   7.211 -static VOID
   7.212 -XenPci_HookDbgPrint_High(PVOID context)
   7.213 -{
   7.214 -  IDT idt;
   7.215 -  PIDT_ENTRY idt_entry;
   7.216 -
   7.217 -  UNREFERENCED_PARAMETER(context);  
   7.218 - 
   7.219 -  idt.limit = 0;
   7.220 -  __sidt(&idt);
   7.221 -  idt_entry = &idt.entries[0x2D];
   7.222 -  #ifdef _AMD64_ 
   7.223 -  Int2dHandlerOld = (PVOID)((ULONG_PTR)idt_entry->addr_0_15 | ((ULONG_PTR)idt_entry->addr_16_31 << 16) | ((ULONG_PTR)idt_entry->addr_32_63 << 32));
   7.224 -  #else
   7.225 -  Int2dHandlerOld = (PVOID)((ULONG_PTR)idt_entry->addr_0_15 | ((ULONG_PTR)idt_entry->addr_16_31 << 16));
   7.226 -  #endif
   7.227 -  idt_entry->addr_0_15 = (USHORT)(ULONG_PTR)Int2dHandlerNew;
   7.228 -  idt_entry->addr_16_31 = (USHORT)((ULONG_PTR)Int2dHandlerNew >> 16);
   7.229 -  #ifdef _AMD64_ 
   7.230 -  idt_entry->addr_32_63 = (ULONG)((ULONG_PTR)Int2dHandlerNew >> 32);
   7.231 -  #endif
   7.232 -}
   7.233 -
   7.234 -static VOID
   7.235 -XenPci_UnHookDbgPrint_High(PVOID context)
   7.236 -{
   7.237 -  IDT idt;
   7.238 -  PIDT_ENTRY idt_entry;
   7.239 -
   7.240 -  UNREFERENCED_PARAMETER(context);  
   7.241 - 
   7.242 -  idt.limit = 0;
   7.243 -  __sidt(&idt);
   7.244 -  idt_entry = &idt.entries[0x2D];
   7.245 -  idt_entry->addr_0_15 = (USHORT)(ULONG_PTR)Int2dHandlerOld;
   7.246 -  idt_entry->addr_16_31 = (USHORT)((ULONG_PTR)Int2dHandlerOld >> 16);
   7.247 -  #ifdef _AMD64_ 
   7.248 -  idt_entry->addr_32_63 = (ULONG)((ULONG_PTR)Int2dHandlerOld >> 32);
   7.249 -  #endif
   7.250 +  KeLowerIrql(old_irql);
   7.251 +  return status;
   7.252  }
   7.253  
   7.254  NTSTATUS
   7.255 -XenPci_HookDbgPrint()
   7.256 -{
   7.257 -  NTSTATUS status = STATUS_SUCCESS;
   7.258 -
   7.259 -  #pragma warning(suppress:28138)
   7.260 -  if (READ_PORT_USHORT(XEN_IOPORT_MAGIC) == 0x49d2
   7.261 -    #pragma warning(suppress:28138)
   7.262 -    || READ_PORT_USHORT(XEN_IOPORT_MAGIC) == 0xd249)
   7.263 -  {
   7.264 -    //#pragma warning(suppress:4055)
   7.265 -    //DbgSetDebugPrintCallback = (PDBG_SET_DEBUGPRINT_CALLBACK)MmGetSystemRoutineAddress((PUNICODE_STRING)&DbgSetDebugPrintCallbackName);
   7.266 -#if (NTDDI_VERSION >= NTDDI_VISTA)
   7.267 -    KdPrint((__DRIVER_NAME "     DbgSetDebugPrintCallback found\n"));
   7.268 -    status = DbgSetDebugPrintCallback(XenPci_DbgPrintCallback, TRUE);
   7.269 -    if (!NT_SUCCESS(status))
   7.270 -    {
   7.271 -      KdPrint((__DRIVER_NAME "     DbgSetDebugPrintCallback failed - %08x\n", status));
   7.272 -    }
   7.273 -    //DbgSetDebugFilterState(componentid, level, state);
   7.274 -    DbgSetDebugFilterState(DPFLTR_DEFAULT_ID, 0xFFFFFFFF, TRUE);
   7.275 -#else
   7.276 -    KdPrint((__DRIVER_NAME "     DbgSetDebugPrintCallback not found\n"));      
   7.277 -#ifndef _AMD64_ // can't patch IDT on AMD64 unfortunately - results in bug check 0x109
   7.278 -    XenPci_HighSync(XenPci_HookDbgPrint_High, XenPci_HookDbgPrint_High, NULL);
   7.279 -#endif
   7.280 -#endif
   7.281 -  }
   7.282 -  else
   7.283 -  {
   7.284 -    status = STATUS_UNSUCCESSFUL;
   7.285 -  }
   7.286 -
   7.287 -  KeInitializeCallbackRecord(&callback_record);
   7.288 -  if (!KeRegisterBugCheckCallback(&callback_record, XenPci_BugcheckCallback, NULL, 0, (PUCHAR)"XenPci"))
   7.289 -  {
   7.290 -    KdPrint((__DRIVER_NAME "     KeRegisterBugCheckCallback failed\n"));
   7.291 -    status = STATUS_UNSUCCESSFUL;
   7.292 -  }
   7.293 -
   7.294 +XenPci_DebugPrint(PCHAR format, ...) {
   7.295 +  NTSTATUS status;
   7.296 +  va_list args;
   7.297 +  
   7.298 +  va_start(args, format);
   7.299 +  status = XenPci_DebugPrintV(format, args);
   7.300 +  va_end(args);
   7.301    return status;
   7.302 -}
   7.303 -
   7.304 -/* always hook IDT in dump mode - patchguard is turned off so its okay */
   7.305 -/* no need for unhook routine - system is already crashed */
   7.306 -/* only for AMD64 and >= Vista */
   7.307 -VOID
   7.308 -XenPci_DumpModeHookDebugPrint() {
   7.309 -  #if (NTDDI_VERSION >= NTDDI_VISTA)
   7.310 -  #ifdef _AMD64_
   7.311 -  #pragma warning(suppress:28138)
   7.312 -  if (READ_PORT_USHORT(XEN_IOPORT_MAGIC) == 0x49d2
   7.313 -    #pragma warning(suppress:28138)
   7.314 -    || READ_PORT_USHORT(XEN_IOPORT_MAGIC) == 0xd249) {
   7.315 -    //XenPci_HighSync(XenPci_HookDbgPrint_High, XenPci_HookDbgPrint_High, NULL);
   7.316 -    XenPci_HookDbgPrint_High(NULL);
   7.317 -  }
   7.318 -  #endif
   7.319 -  #endif
   7.320 -}
   7.321 -
   7.322 -NTSTATUS
   7.323 -XenPci_UnHookDbgPrint()
   7.324 -{
   7.325 -  NTSTATUS status = STATUS_SUCCESS;
   7.326 -
   7.327 -  #pragma warning(suppress:28138)
   7.328 -  if (READ_PORT_USHORT(XEN_IOPORT_MAGIC) == 0x49d2
   7.329 -    #pragma warning(suppress:28138)
   7.330 -    || READ_PORT_USHORT(XEN_IOPORT_MAGIC) == 0xd249) {
   7.331 -    //#pragma warning(suppress:4055)
   7.332 -    //DbgSetDebugPrintCallback = (PDBG_SET_DEBUGPRINT_CALLBACK)MmGetSystemRoutineAddress((PUNICODE_STRING)&DbgSetDebugPrintCallbackName);
   7.333 -#if (NTDDI_VERSION >= NTDDI_VISTA)
   7.334 -    KdPrint((__DRIVER_NAME "     DbgSetDebugPrintCallback found\n"));
   7.335 -    status = DbgSetDebugPrintCallback(XenPci_DbgPrintCallback, FALSE);
   7.336 -    if (!NT_SUCCESS(status))
   7.337 -    {
   7.338 -      KdPrint((__DRIVER_NAME "     DbgSetDebugPrintCallback failed - %08x\n", status));
   7.339 -    }
   7.340 -    //DbgSetDebugFilterState(componentid, level, state);
   7.341 -    //DbgSetDebugFilterState(DPFLTR_DEFAULT_ID, 0xFFFFFFFF, TRUE);
   7.342 -#else
   7.343 -    KdPrint((__DRIVER_NAME "     DbgSetDebugPrintCallback not found\n"));      
   7.344 -#ifndef _AMD64_ // can't patch IDT on AMD64 unfortunately - results in bug check 0x109
   7.345 -    XenPci_HighSync(XenPci_UnHookDbgPrint_High, XenPci_UnHookDbgPrint_High, NULL);
   7.346 -#endif
   7.347 -#endif
   7.348 -  } else {
   7.349 -    status = STATUS_UNSUCCESSFUL;
   7.350 -  }
   7.351 -  
   7.352 -  if (!KeDeregisterBugCheckCallback(&callback_record)) {
   7.353 -    KdPrint((__DRIVER_NAME "     KeDeregisterBugCheckCallback failed\n"));
   7.354 -    status = STATUS_UNSUCCESSFUL;
   7.355 -  }
   7.356 -
   7.357 -  return status;
   7.358 -}
   7.359 +}
   7.360 \ No newline at end of file
     8.1 --- a/xenpci/xenpci_export.c	Wed Feb 13 23:37:17 2013 +1100
     8.2 +++ b/xenpci/xenpci_export.c	Tue Feb 19 15:11:49 2013 +1100
     8.3 @@ -18,6 +18,7 @@ Foundation, Inc., 51 Franklin Street, Fi
     8.4  */
     8.5  
     8.6  #include "xenpci.h"
     8.7 +#include <aux_klib.h>
     8.8  
     8.9  ULONG
    8.10  XnGetVersion() {
    8.11 @@ -378,8 +379,25 @@ XnGetValue(XN_HANDLE handle, ULONG value
    8.12    }
    8.13  }
    8.14  
    8.15 -/* called by storage devices in dump mode to re-hook DebugPrint */
    8.16 +NTSTATUS
    8.17 +XnDebugPrint(PCHAR format, ...) {
    8.18 +  NTSTATUS status;
    8.19 +  va_list args;
    8.20 +  
    8.21 +  va_start(args, format);
    8.22 +  status = XenPci_DebugPrintV(format, args);
    8.23 +  va_end(args);
    8.24 +
    8.25 +  return status;
    8.26 +}
    8.27 +
    8.28  VOID
    8.29 -XnDumpModeHookDebugPrint() {
    8.30 -  XenPci_DumpModeHookDebugPrint();
    8.31 +XnPrintDump() {
    8.32 +  KBUGCHECK_DATA bugcheck_data;
    8.33 +  
    8.34 +  bugcheck_data.BugCheckDataSize  = sizeof(bugcheck_data);
    8.35 +  AuxKlibGetBugCheckData(&bugcheck_data);
    8.36 +  if (bugcheck_data.BugCheckCode != 0) {
    8.37 +    FUNCTION_MSG("Bug check 0x%08x (0x%p, 0x%p, 0x%p, 0x%p)\n", bugcheck_data.BugCheckCode, bugcheck_data.Parameter1, bugcheck_data.Parameter2, bugcheck_data.Parameter3, bugcheck_data.Parameter4);
    8.38 +  }
    8.39  }
     9.1 --- a/xenpci/xenpci_fdo.c	Wed Feb 13 23:37:17 2013 +1100
     9.2 +++ b/xenpci/xenpci_fdo.c	Tue Feb 19 15:11:49 2013 +1100
     9.3 @@ -25,7 +25,7 @@ Foundation, Inc., 51 Franklin Street, Fi
     9.4  #define SHUTDOWN_PATH "control/shutdown"
     9.5  #define BALLOON_PATH "memory/target"
     9.6  
     9.7 -extern PMDL balloon_mdl_head;
     9.8 +//extern PMDL balloon_mdl_head;
     9.9  
    9.10  /* Not really necessary but keeps PREfast happy */
    9.11  static EVT_WDF_WORKITEM XenPci_SuspendResume;
    9.12 @@ -81,7 +81,7 @@ XenPci_AllocMMIO(PXENPCI_DEVICE_DATA xpd
    9.13    addr.QuadPart += xpdd->platform_mmio_alloc;
    9.14    xpdd->platform_mmio_alloc += len;
    9.15  
    9.16 -  NT_ASSERT(xpdd->platform_mmio_alloc <= xpdd->platform_mmio_len);
    9.17 +  XN_ASSERT(xpdd->platform_mmio_alloc <= xpdd->platform_mmio_len);
    9.18  
    9.19    return addr;
    9.20  }
    9.21 @@ -113,7 +113,7 @@ XenPci_Init(PXENPCI_DEVICE_DATA xpdd)
    9.22  
    9.23    if (!xpdd->hypercall_stubs)
    9.24    {
    9.25 -    NT_ASSERT(KeGetCurrentIrql() <= DISPATCH_LEVEL);
    9.26 +    XN_ASSERT(KeGetCurrentIrql() <= DISPATCH_LEVEL);
    9.27      xpdd->hypercall_stubs = hvm_get_hypercall_stubs();
    9.28    }
    9.29    if (!xpdd->hypercall_stubs)
    9.30 @@ -121,7 +121,7 @@ XenPci_Init(PXENPCI_DEVICE_DATA xpdd)
    9.31  
    9.32    if (!xpdd->shared_info_area)
    9.33    {
    9.34 -    NT_ASSERT(KeGetCurrentIrql() <= DISPATCH_LEVEL);
    9.35 +    XN_ASSERT(KeGetCurrentIrql() <= DISPATCH_LEVEL);
    9.36      /* this should be safe as this part will never be called on resume where IRQL == HIGH_LEVEL */
    9.37      xpdd->shared_info_area_unmapped = XenPci_AllocMMIO(xpdd, PAGE_SIZE);
    9.38      xpdd->shared_info_area = MmMapIoSpace(xpdd->shared_info_area_unmapped,
    9.39 @@ -148,8 +148,7 @@ XenPci_Resume(PXENPCI_DEVICE_DATA xpdd)
    9.40  }
    9.41  
    9.42  static VOID
    9.43 -XenPci_SysrqHandler(char *path, PVOID context)
    9.44 -{
    9.45 +XenPci_SysrqHandler(char *path, PVOID context) {
    9.46    PXENPCI_DEVICE_DATA xpdd = context;
    9.47    char *value;
    9.48    char letter;
    9.49 @@ -163,29 +162,23 @@ XenPci_SysrqHandler(char *path, PVOID co
    9.50  
    9.51    KdPrint((__DRIVER_NAME "     SysRq Value = %s\n", value));
    9.52  
    9.53 -  if (value != NULL && strlen(value) != 0)
    9.54 -  {
    9.55 +  if (value != NULL && strlen(value) != 0) {
    9.56      letter = *value;
    9.57      res = XenBus_Write(xpdd, XBT_NIL, SYSRQ_PATH, "");
    9.58 -    if (res)
    9.59 -    {
    9.60 +    if (res) {
    9.61        KdPrint(("Error writing sysrq path\n"));
    9.62        XenPci_FreeMem(res);
    9.63        return;
    9.64      }
    9.65 -  }
    9.66 -  else
    9.67 -  {
    9.68 +  } else {
    9.69      letter = 0;
    9.70    }
    9.71  
    9.72 -  if (value != NULL)
    9.73 -  {
    9.74 +  if (value != NULL) {
    9.75      XenPci_FreeMem(value);
    9.76    }
    9.77  
    9.78 -  switch (letter)
    9.79 -  {
    9.80 +  switch (letter) {
    9.81    case 0:
    9.82      break;
    9.83    case 'B': /* cause a bug check */
    9.84 @@ -193,7 +186,8 @@ XenPci_SysrqHandler(char *path, PVOID co
    9.85      KeBugCheckEx(('X' << 16)|('E' << 8)|('N'), 0x00000001, 0x00000000, 0x00000000, 0x00000000);
    9.86      break;
    9.87    case 'A': /* cause an assert */
    9.88 -    NT_ASSERT(1 == 0);
    9.89 +    #pragma warning(suppress:28138)
    9.90 +    XN_ASSERT(letter != 'A');
    9.91      break;
    9.92    default:
    9.93      KdPrint(("     Unhandled sysrq letter %c\n", letter));
    9.94 @@ -203,30 +197,6 @@ XenPci_SysrqHandler(char *path, PVOID co
    9.95    FUNCTION_EXIT();
    9.96  }
    9.97  
    9.98 -#if 0
    9.99 -static VOID
   9.100 -XenPci_PrintPendingInterrupts()
   9.101 -{
   9.102 -  PULONG bitmap = (PULONG)0xFFFE0200;
   9.103 -  int i;
   9.104 -  int j;
   9.105 -  ULONG value;
   9.106 -  
   9.107 -  for (i = 0; i < 8; i++)
   9.108 -  {
   9.109 -    value = bitmap[(7 - i) * 4];
   9.110 -    if (value)
   9.111 -    {
   9.112 -      for (j = 0; j < 32; j++)
   9.113 -      {
   9.114 -        if ((value >> j) & 1)
   9.115 -          KdPrint(("     Interrupt pending on pin %d\n", ((7 - i) << 5) | j));
   9.116 -      }
   9.117 -    }
   9.118 -  }
   9.119 -}
   9.120 -#endif
   9.121 -
   9.122  static VOID
   9.123  XenPci_BalloonThreadProc(PVOID StartContext)
   9.124  {
   9.125 @@ -243,41 +213,31 @@ XenPci_BalloonThreadProc(PVOID StartCont
   9.126    int pfn_count;
   9.127    int timeout_ms = 1000;
   9.128    DECLARE_CONST_UNICODE_STRING(low_mem_name, L"\\KernelObjects\\LowMemoryCondition");
   9.129 -  //DECLARE_CONST_UNICODE_STRING(high_commit_name, L"\\KernelObjects\\HighCommitCondition");
   9.130 -  //DECLARE_CONST_UNICODE_STRING(max_commit_name, L"\\KernelObjects\\MaximumCommitCondition");
   9.131    PKEVENT low_mem_event;
   9.132 -  //PKEVENT high_commit_event;
   9.133 -  //PKEVENT max_commit_event;
   9.134    HANDLE low_mem_handle;
   9.135 -  //HANDLE high_commit_handle;
   9.136 -  //HANDLE max_commit_handle;
   9.137 +  BOOLEAN hit_initial_target = FALSE;
   9.138    
   9.139    FUNCTION_ENTER();
   9.140    
   9.141 -  head = balloon_mdl_head;
   9.142 -  balloon_mdl_head = NULL;
   9.143 +  head = NULL;
   9.144  
   9.145    low_mem_event = IoCreateNotificationEvent((PUNICODE_STRING)&low_mem_name, &low_mem_handle);
   9.146    //high_commit_event = IoCreateNotificationEvent((PUNICODE_STRING)&high_commit_name, &high_commit_handle);
   9.147    //max_commit_event = IoCreateNotificationEvent((PUNICODE_STRING)&max_commit_name, &max_commit_handle);
   9.148  
   9.149 -  KdPrint((__DRIVER_NAME "     low_mem_event = %p, state = %d\n", low_mem_event, low_mem_event?KeReadStateEvent(low_mem_event):(ULONG)-1));
   9.150 -  //KdPrint((__DRIVER_NAME "     high_commit_event = %p, state = %d\n", high_commit_event, high_commit_event?KeReadStateEvent(high_commit_event):(ULONG)-1));
   9.151 -  //KdPrint((__DRIVER_NAME "     max_commit_event = %p, state = %d\n", max_commit_event, max_commit_event?KeReadStateEvent(max_commit_event):(ULONG)-1));
   9.152 -  
   9.153 -  for(;;)
   9.154 -  {
   9.155 -    /* back off exponentially if we have adjustments to make, or wait for event if we don't */
   9.156 -    if (xpdd->current_memory_kb != new_target_kb)
   9.157 -    {
   9.158 +  for(;;) {
   9.159 +    /* back off exponentially if we have adjustments to make and we have already hit our initial target, or wait for event if we don't */
   9.160 +    if (xpdd->current_memory_kb != new_target_kb) {
   9.161 +      if (!hit_initial_target) {
   9.162 +        timeout_ms = 0;
   9.163 +      }
   9.164        timeout.QuadPart = WDF_REL_TIMEOUT_IN_MS(timeout_ms);
   9.165        ptimeout = &timeout;
   9.166        timeout_ms <<= 1;
   9.167        if (timeout_ms > 60000)
   9.168          timeout_ms = 60000;
   9.169 -    }
   9.170 -    else
   9.171 -    {
   9.172 +    } else {
   9.173 +      hit_initial_target = TRUE;
   9.174        ptimeout = NULL;
   9.175        timeout_ms = 1000;
   9.176      }
   9.177 @@ -291,16 +251,12 @@ XenPci_BalloonThreadProc(PVOID StartCont
   9.178      // make sure target <= initial
   9.179      // make sure target > some % of initial
   9.180      
   9.181 -    if (xpdd->current_memory_kb == new_target_kb)
   9.182 -    {
   9.183 +    if (xpdd->current_memory_kb == new_target_kb) {
   9.184        KdPrint((__DRIVER_NAME "     No change to memory\n"));
   9.185        continue;
   9.186 -    }
   9.187 -    else if (xpdd->current_memory_kb < new_target_kb)
   9.188 -    {
   9.189 -      KdPrint((__DRIVER_NAME "     Trying to take %d MB from Xen\n", new_target_kb - xpdd->current_memory_kb));
   9.190 -      while ((mdl = head) != NULL && xpdd->current_memory_kb < new_target_kb)
   9.191 -      {
   9.192 +    } else if (xpdd->current_memory_kb < new_target_kb) {
   9.193 +      KdPrint((__DRIVER_NAME "     Trying to take %d KB from Xen\n", new_target_kb - xpdd->current_memory_kb));
   9.194 +      while ((mdl = head) != NULL && xpdd->current_memory_kb < new_target_kb) {
   9.195          pfn_count = ADDRESS_AND_SIZE_TO_SPAN_PAGES(MmGetMdlVirtualAddress(mdl), MmGetMdlByteCount(mdl));
   9.196          pfns = ExAllocatePoolWithTag(NonPagedPool, pfn_count * sizeof(xen_pfn_t), XENPCI_POOL_TAG);
   9.197          /* sizeof(xen_pfn_t) may not be the same as PPFN_NUMBER */
   9.198 @@ -316,10 +272,8 @@ XenPci_BalloonThreadProc(PVOID StartCont
   9.199          //KdPrint((__DRIVER_NAME "     Calling HYPERVISOR_memory_op(XENMEM_populate_physmap) - pfn_count = %d\n", pfn_count));
   9.200          ret = HYPERVISOR_memory_op(xpdd, XENMEM_populate_physmap, &reservation);
   9.201          //KdPrint((__DRIVER_NAME "     populated %d pages\n", ret));
   9.202 -        if (ret < (ULONG)pfn_count)
   9.203 -        {
   9.204 -          if (ret > 0)
   9.205 -          {
   9.206 +        if (ret < (ULONG)pfn_count) {
   9.207 +          if (ret > 0) {
   9.208              /* We hit the Xen hard limit: reprobe. */
   9.209              reservation.nr_extents = ret;
   9.210              ret = HYPERVISOR_memory_op(xpdd, XENMEM_decrease_reservation, &reservation);
   9.211 @@ -335,12 +289,9 @@ XenPci_BalloonThreadProc(PVOID StartCont
   9.212          ExFreePool(mdl);
   9.213          xpdd->current_memory_kb += BALLOON_UNITS_KB;
   9.214        }
   9.215 -    }
   9.216 -    else
   9.217 -    {
   9.218 -      KdPrint((__DRIVER_NAME "     Trying to give %d MB to Xen\n", xpdd->current_memory_kb - new_target_kb));
   9.219 -      while (xpdd->current_memory_kb > new_target_kb)
   9.220 -      {
   9.221 +    } else {
   9.222 +      KdPrint((__DRIVER_NAME "     Trying to give %d KB to Xen\n", xpdd->current_memory_kb - new_target_kb));
   9.223 +      while (xpdd->current_memory_kb > new_target_kb) {
   9.224          PHYSICAL_ADDRESS alloc_low;
   9.225          PHYSICAL_ADDRESS alloc_high;
   9.226          PHYSICAL_ADDRESS alloc_skip;
   9.227 @@ -348,12 +299,8 @@ XenPci_BalloonThreadProc(PVOID StartCont
   9.228          alloc_high.QuadPart = 0xFFFFFFFFFFFFFFFFULL;
   9.229          alloc_skip.QuadPart = 0;
   9.230  
   9.231 -        if (low_mem_event && KeReadStateEvent(low_mem_event))
   9.232 -        {
   9.233 +        if (!hit_initial_target && low_mem_event && KeReadStateEvent(low_mem_event)) {
   9.234            KdPrint((__DRIVER_NAME "     Low memory condition exists. Waiting.\n"));
   9.235 -          //KdPrint((__DRIVER_NAME "     low_mem_event = %p, state = %d\n", low_mem_event, low_mem_event?KeReadStateEvent(low_mem_event):(ULONG)-1));
   9.236 -          //KdPrint((__DRIVER_NAME "     high_commit_event = %p, state = %d\n", high_commit_event, high_commit_event?KeReadStateEvent(high_commit_event):(ULONG)-1));
   9.237 -          //KdPrint((__DRIVER_NAME "     max_commit_event = %p, state = %d\n", max_commit_event, max_commit_event?KeReadStateEvent(max_commit_event):(ULONG)-1));
   9.238            break;
   9.239          }
   9.240  
   9.241 @@ -363,18 +310,14 @@ XenPci_BalloonThreadProc(PVOID StartCont
   9.242          #else
   9.243          mdl = MmAllocatePagesForMdl(alloc_low, alloc_high, alloc_skip, BALLOON_UNITS_KB * 1024);
   9.244          #endif
   9.245 -        if (!mdl)
   9.246 -        {
   9.247 +        if (!mdl) {
   9.248            KdPrint((__DRIVER_NAME "     Allocation failed - try again soon\n"));
   9.249            break;
   9.250 -        }
   9.251 -        else
   9.252 -        {
   9.253 +        } else {
   9.254            int i;
   9.255            ULONG ret;
   9.256            int pfn_count = ADDRESS_AND_SIZE_TO_SPAN_PAGES(MmGetMdlVirtualAddress(mdl), MmGetMdlByteCount(mdl));
   9.257 -          if (pfn_count != BALLOON_UNIT_PAGES)
   9.258 -          {
   9.259 +          if (pfn_count != BALLOON_UNIT_PAGES) {
   9.260              /* we could probably do this better but it will only happen in low memory conditions... */
   9.261              KdPrint((__DRIVER_NAME "     wanted %d pages got %d pages\n", BALLOON_UNIT_PAGES, pfn_count));
   9.262              MmFreePagesFromMdl(mdl);
   9.263 @@ -392,17 +335,12 @@ XenPci_BalloonThreadProc(PVOID StartCont
   9.264            #pragma warning(disable: 4127) /* conditional expression is constant */
   9.265            set_xen_guest_handle(reservation.extent_start, pfns);
   9.266            
   9.267 -          //KdPrint((__DRIVER_NAME "     Calling HYPERVISOR_memory_op(XENMEM_decrease_reservation) - pfn_count = %d\n", pfn_count));
   9.268            ret = HYPERVISOR_memory_op(xpdd, XENMEM_decrease_reservation, &reservation);
   9.269            ExFreePoolWithTag(pfns, XENPCI_POOL_TAG);
   9.270 -          //KdPrint((__DRIVER_NAME "     decreased %d pages\n", ret));
   9.271 -          if (head)
   9.272 -          {
   9.273 +          if (head) {
   9.274              mdl->Next = head;
   9.275              head = mdl;
   9.276 -          }
   9.277 -          else
   9.278 -          {
   9.279 +          } else {
   9.280              head = mdl;
   9.281            }
   9.282            xpdd->current_memory_kb -= BALLOON_UNITS_KB;
   9.283 @@ -411,30 +349,22 @@ XenPci_BalloonThreadProc(PVOID StartCont
   9.284      }
   9.285      KdPrint((__DRIVER_NAME "     Memory = %d, Balloon Target = %d\n", xpdd->current_memory_kb, new_target_kb));
   9.286    }
   9.287 -  //FUNCTION_EXIT();
   9.288  }
   9.289  
   9.290  static VOID
   9.291 -XenPci_BalloonHandler(char *Path, PVOID Data)
   9.292 -{
   9.293 -  WDFDEVICE device = Data;
   9.294 +XenPci_BalloonHandler(char *path, PVOID context) {
   9.295 +  WDFDEVICE device = context;
   9.296    PXENPCI_DEVICE_DATA xpdd = GetXpdd(device);
   9.297    char *value;
   9.298 -  xenbus_transaction_t xbt;
   9.299 -  int retry;
   9.300  
   9.301 -  UNREFERENCED_PARAMETER(Path);
   9.302 +  UNREFERENCED_PARAMETER(path);
   9.303  
   9.304    FUNCTION_ENTER();
   9.305  
   9.306 -  XenBus_StartTransaction(xpdd, &xbt);
   9.307 -
   9.308    XenBus_Read(xpdd, XBT_NIL, BALLOON_PATH, &value);
   9.309    
   9.310 -  if (value == NULL)
   9.311 -  {
   9.312 -    KdPrint((__DRIVER_NAME "     Failed to read value\n"));
   9.313 -    XenBus_EndTransaction(xpdd, xbt, 0, &retry);
   9.314 +  if (value == NULL) {
   9.315 +    FUNCTION_MSG("Failed to read balloon target value\n");
   9.316      FUNCTION_EXIT();
   9.317      return;
   9.318    }
   9.319 @@ -442,9 +372,7 @@ XenPci_BalloonHandler(char *Path, PVOID 
   9.320    if (atoi(value) > 0)
   9.321      xpdd->target_memory_kb = atoi(value);
   9.322  
   9.323 -  KdPrint((__DRIVER_NAME "     target memory value = %d (%s)\n", xpdd->target_memory_kb, value));
   9.324 -
   9.325 -  XenBus_EndTransaction(xpdd, xbt, 0, &retry);
   9.326 +  FUNCTION_MSG("target memory value = %d (%s)\n", xpdd->target_memory_kb, value);
   9.327  
   9.328    XenPci_FreeMem(value);
   9.329  
   9.330 @@ -688,7 +616,7 @@ XenPci_EvtDevicePrepareHardware (WDFDEVI
   9.331  
   9.332    FUNCTION_ENTER();
   9.333    
   9.334 -  NT_ASSERT(WdfCmResourceListGetCount(resources_raw) == WdfCmResourceListGetCount(resources_translated));
   9.335 +  XN_ASSERT(WdfCmResourceListGetCount(resources_raw) == WdfCmResourceListGetCount(resources_translated));
   9.336    
   9.337    for (i = 0; i < WdfCmResourceListGetCount(resources_raw); i++)
   9.338    {
   9.339 @@ -703,11 +631,6 @@ XenPci_EvtDevicePrepareHardware (WDFDEVI
   9.340      case CmResourceTypeMemory:
   9.341        KdPrint((__DRIVER_NAME "     Memory mapped CSR:(%x:%x) Length:(%d)\n", translated_descriptor->u.Memory.Start.LowPart, translated_descriptor->u.Memory.Start.HighPart, translated_descriptor->u.Memory.Length));
   9.342        KdPrint((__DRIVER_NAME "     Memory flags = %04X\n", translated_descriptor->Flags));
   9.343 -#if 0      
   9.344 -      mmio_freelist_free = 0;
   9.345 -      for (j = 0; j < translated_descriptor->u.Memory.Length >> PAGE_SHIFT; j++)
   9.346 -        put_mmio_on_freelist((xpdd->platform_mmio_addr >> PAGE_SHIFT) + j);
   9.347 -#endif
   9.348        xpdd->platform_mmio_addr = translated_descriptor->u.Memory.Start;
   9.349        xpdd->platform_mmio_len = translated_descriptor->u.Memory.Length;
   9.350        xpdd->platform_mmio_flags = translated_descriptor->Flags;
   9.351 @@ -786,28 +709,20 @@ XenPci_EvtDeviceD0Entry(WDFDEVICE device
   9.352      break;  
   9.353    }
   9.354  
   9.355 -  if (previous_state == WdfPowerDevicePrepareForHibernation && qemu_hide_flags_value)
   9.356 -  {
   9.357 +  if (previous_state == WdfPowerDevicePrepareForHibernation && qemu_hide_flags_value) {
   9.358      XenPci_HideQemuDevices();
   9.359    }
   9.360    
   9.361 -  if (previous_state == WdfPowerDeviceD3Final)
   9.362 -  {
   9.363 +  if (previous_state == WdfPowerDeviceD3Final) {
   9.364      XenPci_Init(xpdd);
   9.365 -    if (tpr_patch_requested && !xpdd->tpr_patched)
   9.366 -    {
   9.367 +    if (tpr_patch_requested && !xpdd->tpr_patched) {
   9.368        XenPci_MapHalThenPatchKernel(xpdd);
   9.369        xpdd->tpr_patched = TRUE;
   9.370        xpdd->removable = FALSE;
   9.371      }
   9.372      GntTbl_Init(xpdd);
   9.373      EvtChn_Init(xpdd);
   9.374 -
   9.375 -  // use the memory_op(unsigned int op, void *arg) hypercall to adjust memory
   9.376 -  // use XENMEM_increase_reservation and XENMEM_decrease_reservation
   9.377 -  }
   9.378 -  else
   9.379 -  {
   9.380 +  } else {
   9.381      XenPci_Resume(xpdd);
   9.382      GntTbl_Resume(xpdd);
   9.383      EvtChn_Resume(xpdd);
   9.384 @@ -824,7 +739,6 @@ XenPci_EvtDeviceD0EntryPostInterruptsEna
   9.385    NTSTATUS status = STATUS_SUCCESS;
   9.386    PXENPCI_DEVICE_DATA xpdd = GetXpdd(device);
   9.387    PCHAR response;
   9.388 -  char *value;
   9.389    HANDLE thread_handle;
   9.390  
   9.391    UNREFERENCED_PARAMETER(previous_state);
   9.392 @@ -843,31 +757,18 @@ XenPci_EvtDeviceD0EntryPostInterruptsEna
   9.393  
   9.394      response = XenBus_AddWatch(xpdd, XBT_NIL, "device", XenPci_DeviceWatchHandler, xpdd);
   9.395  
   9.396 -    if (!xpdd->initial_memory_kb)
   9.397 -    {
   9.398 -      XenBus_Read(xpdd, XBT_NIL, BALLOON_PATH, &value);
   9.399 -      if (atoi(value) > 0)
   9.400 -      {
   9.401 -        xpdd->initial_memory_kb = atoi(value);
   9.402 -        xpdd->current_memory_kb = xpdd->initial_memory_kb;
   9.403 -        xpdd->target_memory_kb = xpdd->initial_memory_kb;
   9.404 -      }
   9.405 -      KdPrint((__DRIVER_NAME "     Initial Memory Value = %d (%s)\n", xpdd->initial_memory_kb, value));
   9.406 -      KeInitializeEvent(&xpdd->balloon_event, SynchronizationEvent, FALSE);
   9.407 -      xpdd->balloon_shutdown = FALSE;
   9.408 -      status = PsCreateSystemThread(&thread_handle, THREAD_ALL_ACCESS, NULL, NULL, NULL, XenPci_BalloonThreadProc, xpdd);
   9.409 -      if (!NT_SUCCESS(status))
   9.410 -      {
   9.411 -        KdPrint((__DRIVER_NAME "     Could not start balloon thread\n"));
   9.412 -        return status;
   9.413 -      }
   9.414 -      status = ObReferenceObjectByHandle(thread_handle, THREAD_ALL_ACCESS, NULL, KernelMode, &xpdd->balloon_thread, NULL);
   9.415 -      ZwClose(thread_handle);
   9.416 +    /* prime target as current until the watch gets kicked off */
   9.417 +    xpdd->target_memory_kb = xpdd->current_memory_kb;
   9.418 +    xpdd->balloon_shutdown = FALSE;
   9.419 +    status = PsCreateSystemThread(&thread_handle, THREAD_ALL_ACCESS, NULL, NULL, NULL, XenPci_BalloonThreadProc, xpdd);
   9.420 +    if (!NT_SUCCESS(status)) {
   9.421 +      FUNCTION_MSG("Could not start balloon thread\n");
   9.422 +      return status;
   9.423      }
   9.424      response = XenBus_AddWatch(xpdd, XBT_NIL, BALLOON_PATH, XenPci_BalloonHandler, device);
   9.425 -  }
   9.426 -  else
   9.427 -  {
   9.428 +    status = ObReferenceObjectByHandle(thread_handle, THREAD_ALL_ACCESS, NULL, KernelMode, &xpdd->balloon_thread, NULL);
   9.429 +    ZwClose(thread_handle);
   9.430 +  } else {
   9.431      XenBus_Resume(xpdd);
   9.432      XenPci_ConnectSuspendEvt(xpdd);
   9.433    }
   9.434 @@ -910,8 +811,7 @@ XenPci_EvtDeviceD0ExitPreInterruptsDisab
   9.435      break;  
   9.436    }
   9.437  
   9.438 -  if (target_state == WdfPowerDeviceD3Final)
   9.439 -  {
   9.440 +  if (target_state == WdfPowerDeviceD3Final) {
   9.441      KdPrint((__DRIVER_NAME "     Shutting down threads\n"));
   9.442  
   9.443      xpdd->balloon_shutdown = TRUE;
   9.444 @@ -977,7 +877,7 @@ XenPci_EvtDeviceD0Exit(WDFDEVICE device,
   9.445    }
   9.446  
   9.447    FUNCTION_EXIT();
   9.448 -  
   9.449 +
   9.450    return status;
   9.451  }
   9.452  
    10.1 --- a/xenpci/xenpci_pdo.c	Wed Feb 13 23:37:17 2013 +1100
    10.2 +++ b/xenpci/xenpci_pdo.c	Tue Feb 19 15:11:49 2013 +1100
    10.3 @@ -31,8 +31,6 @@ static EVT_WDF_DEVICE_D0_EXIT XenPciPdo_
    10.4  static EVT_WDF_DEVICE_USAGE_NOTIFICATION XenPciPdo_EvtDeviceUsageNotification;
    10.5  static EVT_WDF_DEVICE_PNP_STATE_CHANGE_NOTIFICATION XenPci_EvtDevicePnpStateChange;
    10.6  
    10.7 -
    10.8 -      
    10.9  /*
   10.10  Called at PASSIVE_LEVEL(?)
   10.11  Called during restore
   10.12 @@ -148,7 +146,7 @@ NTSTATUS
   10.13  XenPciPdo_EvtDeviceD0Entry(WDFDEVICE device, WDF_POWER_DEVICE_STATE previous_state) {
   10.14    NTSTATUS status = STATUS_SUCCESS;
   10.15    PXENPCI_PDO_DEVICE_DATA xppdd = GetXppdd(device);
   10.16 -  //PXENPCI_DEVICE_DATA xpdd = GetXpdd(xppdd->wdf_device_bus_fdo);
   10.17 +  PXENPCI_DEVICE_DATA xpdd = GetXpdd(xppdd->wdf_device_bus_fdo);
   10.18    CHAR path[128];
   10.19    
   10.20    FUNCTION_ENTER();
   10.21 @@ -189,6 +187,12 @@ XenPciPdo_EvtDeviceD0Entry(WDFDEVICE dev
   10.22      return status;
   10.23    }
   10.24  
   10.25 +  if (previous_state == WdfPowerDevicePrepareForHibernation && xppdd->device_callback) {
   10.26 +    FUNCTION_MSG("Restoring watch %s\n", xppdd->device);
   10.27 +    RtlStringCbPrintfA(path, ARRAY_SIZE(path), "%s/state", xppdd->backend_path);
   10.28 +    XenBus_AddWatch(xpdd, XBT_NIL, path, XenPci_BackendStateCallback, xppdd);
   10.29 +  }
   10.30 +
   10.31    if (!NT_SUCCESS(status)) {
   10.32      RtlStringCbPrintfA(path, ARRAY_SIZE(path), "%s/state", xppdd->backend_path);
   10.33      //XenBus_RemWatch(xpdd, XBT_NIL, path, XenPci_BackendStateHandler, device);
   10.34 @@ -206,7 +210,7 @@ NTSTATUS
   10.35  XenPciPdo_EvtDeviceD0Exit(WDFDEVICE device, WDF_POWER_DEVICE_STATE target_state) {
   10.36    NTSTATUS status = STATUS_SUCCESS;
   10.37    PXENPCI_PDO_DEVICE_DATA xppdd = GetXppdd(device);
   10.38 -  //PXENPCI_DEVICE_DATA xpdd = GetXpdd(xppdd->wdf_device_bus_fdo);
   10.39 +  PXENPCI_DEVICE_DATA xpdd = GetXpdd(xppdd->wdf_device_bus_fdo);
   10.40    char path[128];
   10.41    
   10.42    UNREFERENCED_PARAMETER(device);
   10.43 @@ -250,9 +254,12 @@ XenPciPdo_EvtDeviceD0Exit(WDFDEVICE devi
   10.44    }
   10.45    
   10.46    /* Remove watch on backend state */
   10.47 -  RtlStringCbPrintfA(path, ARRAY_SIZE(path), "%s/state", xppdd->backend_path);
   10.48 -  //XenBus_RemWatch(xpdd, XBT_NIL, path, XenPci_BackendStateHandler, device);
   10.49 -  
   10.50 +  /* even if hibernate */
   10.51 +  if (xppdd->device_callback) {
   10.52 +    FUNCTION_MSG("Removing watch %s\n", xppdd->device);
   10.53 +    RtlStringCbPrintfA(path, ARRAY_SIZE(path), "%s/state", xppdd->backend_path);
   10.54 +    XenBus_RemWatch(xpdd, XBT_NIL, path, XenPci_BackendStateCallback, xppdd);
   10.55 +  }
   10.56    FUNCTION_EXIT();
   10.57    
   10.58    return status;