]> glassweightruler.freedombox.rocks Git - Ventoy.git/blobdiff - EDK2/edk2_mod/edk2-edk2-stable201911/MdeModulePkg/Application/Ventoy/Ventoy.c
1.1.07 release
[Ventoy.git] / EDK2 / edk2_mod / edk2-edk2-stable201911 / MdeModulePkg / Application / Ventoy / Ventoy.c
index 857e7415b7c535b0d4db5a7c274de6979baa2b82..0682c74c522caf00f02dd920e1a4768eec4c5ef6 100644 (file)
 #include <Protocol/BlockIo.h>
 #include <Protocol/RamDisk.h>
 #include <Protocol/SimpleFileSystem.h>
+#include <Protocol/DriverBinding.h>
 #include <Ventoy.h>
 
-UINTN g_iso_buf_size = 0;
-BOOLEAN gMemdiskMode = FALSE;
 BOOLEAN gDebugPrint = FALSE;
+BOOLEAN gBootFallBack = FALSE;
+BOOLEAN gDotEfiBoot = FALSE;
 BOOLEAN gLoadIsoEfi = FALSE;
+BOOLEAN gIsoUdf = FALSE;
 ventoy_ram_disk g_ramdisk_param;
 ventoy_chain_head *g_chain;
+void *g_vtoy_img_location_buf;
 ventoy_img_chunk *g_chunk;
+UINT8 *g_os_param_reserved;
 UINT32 g_img_chunk_num;
 ventoy_override_chunk *g_override_chunk;
 UINT32 g_override_chunk_num;
 ventoy_virt_chunk *g_virt_chunk;
 UINT32 g_virt_chunk_num;
 vtoy_block_data gBlockData;
-ventoy_sector_flag *g_sector_flag = NULL;
-UINT32 g_sector_flag_num = 0;
 static grub_env_get_pf grub_env_get = NULL;
-
-EFI_FILE_OPEN g_original_fopen = NULL;
-EFI_FILE_CLOSE g_original_fclose = NULL;
-EFI_SIMPLE_FILE_SYSTEM_PROTOCOL_OPEN_VOLUME g_original_open_volume = NULL;
+static grub_env_set_pf grub_env_set = NULL;
 
 ventoy_grub_param_file_replace *g_file_replace_list = NULL;
 ventoy_efi_file_replace g_efi_file_replace;
 
-CHAR16 gFirstTryBootFile[256] = {0};
+ventoy_grub_param_file_replace *g_img_replace_list = NULL;
+ventoy_efi_file_replace g_img_file_replace[VTOY_MAX_CONF_REPLACE];
 
 CONST CHAR16 gIso9660EfiDriverPath[] = ISO9660_EFI_DRIVER_PATH;
+CONST CHAR16 gUdfEfiDriverPath[] = UDF_EFI_DRIVER_PATH;
+
+BOOLEAN g_fix_windows_1st_cdrom_issue = FALSE;
+
+STATIC BOOLEAN g_hook_keyboard = FALSE;
+
+CHAR16 gFirstTryBootFile[256] = {0};
+
+STATIC EFI_GET_VARIABLE g_org_get_variable = NULL;
+STATIC EFI_EXIT_BOOT_SERVICES g_org_exit_boot_service = NULL;
 
 /* Boot filename */
 UINTN gBootFileStartIndex = 1;
@@ -70,15 +80,30 @@ CONST CHAR16 *gEfiBootFileName[] =
 {
     L"@",
     EFI_REMOVABLE_MEDIA_FILE_NAME,
+#if   defined (MDE_CPU_IA32)
+    L"\\EFI\\BOOT\\GRUBIA32.EFI",
+    L"\\EFI\\BOOT\\BOOTia32.EFI",
+    L"\\EFI\\BOOT\\bootia32.efi",
+    L"\\efi\\boot\\bootia32.efi",
+#elif defined (MDE_CPU_X64)
     L"\\EFI\\BOOT\\GRUBX64.EFI",
     L"\\EFI\\BOOT\\BOOTx64.EFI",
     L"\\EFI\\BOOT\\bootx64.efi",
     L"\\efi\\boot\\bootx64.efi",
+#elif defined (MDE_CPU_ARM)
+    L"\\EFI\\BOOT\\GRUBARM.EFI",
+    L"\\EFI\\BOOT\\BOOTarm.EFI",
+    L"\\EFI\\BOOT\\bootarm.efi",
+    L"\\efi\\boot\\bootarm.efi",
+#elif defined (MDE_CPU_AARCH64)
+    L"\\EFI\\BOOT\\GRUBAA64.EFI",
+    L"\\EFI\\BOOT\\BOOTaa64.EFI",
+    L"\\EFI\\BOOT\\bootaa64.efi",
+    L"\\efi\\boot\\bootaa64.efi",
+#endif
+    
 };
 
-/* EFI block device vendor device path GUID */
-EFI_GUID gVtoyBlockDevicePathGuid = VTOY_BLOCK_DEVICE_PATH_GUID;
-
 VOID EFIAPI VtoyDebug(IN CONST CHAR8  *Format, ...)
 {
     VA_LIST  Marker;
@@ -204,6 +229,15 @@ static void EFIAPI ventoy_dump_chain(ventoy_chain_head *chain)
     debug("os_param->vtoy_img_size=<%llu>",    chain->os_param.vtoy_img_size);
     debug("os_param->vtoy_img_location_addr=<0x%llx>", chain->os_param.vtoy_img_location_addr);
     debug("os_param->vtoy_img_location_len=<%u>",    chain->os_param.vtoy_img_location_len);
+    debug("os_param->vtoy_reserved=<%u %u %u %u %u %u %u>",    
+          g_os_param_reserved[0], 
+          g_os_param_reserved[1], 
+          g_os_param_reserved[2], 
+          g_os_param_reserved[3],
+          g_os_param_reserved[4],
+          g_os_param_reserved[5],
+          g_os_param_reserved[6]
+          );
 
     ventoy_debug_pause();
     
@@ -224,346 +258,180 @@ static void EFIAPI ventoy_dump_chain(ventoy_chain_head *chain)
     ventoy_dump_virt_chunk(chain);
 }
 
-EFI_HANDLE EFIAPI ventoy_get_parent_handle(IN EFI_DEVICE_PATH_PROTOCOL *pDevPath)
+static int ventoy_update_image_location(ventoy_os_param *param)
 {
-    EFI_HANDLE Handle = NULL;
     EFI_STATUS Status = EFI_SUCCESS;
-    EFI_DEVICE_PATH_PROTOCOL *pLastNode = NULL;
-    EFI_DEVICE_PATH_PROTOCOL *pCurNode = NULL;
-    EFI_DEVICE_PATH_PROTOCOL *pTmpDevPath = NULL;
-    
-    pTmpDevPath = DuplicateDevicePath(pDevPath);
-    if (!pTmpDevPath)
-    {
-        return NULL;
-    }
+    UINT8 chksum = 0;
+    unsigned int i;
+    unsigned int length;
+    UINTN address = 0;
+    void *buffer = NULL;
+    ventoy_image_location *location = NULL;
+    ventoy_image_disk_region *region = NULL;
+    ventoy_img_chunk *chunk = g_chunk;
 
-    pCurNode = pTmpDevPath;
-    while (!IsDevicePathEnd(pCurNode))
-    {
-        pLastNode = pCurNode;
-        pCurNode = NextDevicePathNode(pCurNode);
-    }
-    if (pLastNode)
+    length = sizeof(ventoy_image_location) + (g_img_chunk_num - 1) * sizeof(ventoy_image_disk_region);
+
+    Status = gBS->AllocatePool(EfiRuntimeServicesData, length + 4096 * 2, &buffer);
+    if (EFI_ERROR(Status) || NULL == buffer)
     {
-        CopyMem(pLastNode, pCurNode, sizeof(EFI_DEVICE_PATH_PROTOCOL));
+        debug("Failed to allocate runtime pool %r\n", Status);
+        return 1;
     }
 
-    pCurNode = pTmpDevPath;
-    Status = gBS->LocateDevicePath(&gEfiDevicePathProtocolGuid, &pCurNode, &Handle);
-    debug("Status:%r Parent Handle:%p DP:%s", Status, Handle, ConvertDevicePathToText(pTmpDevPath, FALSE, FALSE));
-
-    FreePool(pTmpDevPath);
-
-    return Handle;
-}
-
-EFI_STATUS EFIAPI ventoy_block_io_reset 
-(
-    IN EFI_BLOCK_IO_PROTOCOL          *This,
-    IN BOOLEAN                        ExtendedVerification
-) 
-{
-    (VOID)This;
-    (VOID)ExtendedVerification;
-       return EFI_SUCCESS;
-}
-
-STATIC EFI_STATUS EFIAPI ventoy_read_iso_sector
-(
-    IN UINT64                 Sector,
-    IN UINTN                  Count,
-    OUT VOID                 *Buffer
-)
-{
-    EFI_STATUS Status = EFI_SUCCESS;
-    EFI_LBA MapLba = 0;
-    UINT32 i = 0;
-    UINTN secLeft = 0;
-    UINTN secRead = 0;
-    UINT64 ReadStart = 0;
-    UINT64 ReadEnd = 0;
-    UINT64 OverrideStart = 0;
-    UINT64 OverrideEnd= 0;
-    UINT8 *pCurBuf = (UINT8 *)Buffer;
-    ventoy_img_chunk *pchunk = g_chunk;
-    ventoy_override_chunk *pOverride = g_override_chunk;
-    EFI_BLOCK_IO_PROTOCOL *pRawBlockIo = gBlockData.pRawBlockIo;
-
-    debug("read iso sector %lu  count %u", Sector, Count);
-
-    ReadStart = Sector * 2048;
-    ReadEnd = (Sector + Count) * 2048;
+    address = (UINTN)buffer;
+    g_vtoy_img_location_buf = buffer;
 
-    for (i = 0; Count > 0 && i < g_img_chunk_num; i++, pchunk++)
+    if (address % 4096)
     {
-        if (Sector >= pchunk->img_start_sector && Sector <= pchunk->img_end_sector)
-        {
-            if (g_chain->disk_sector_size == 512)
-            {
-                MapLba = (Sector - pchunk->img_start_sector) * 4 + pchunk->disk_start_sector;
-            }
-            else
-            {
-                MapLba = (Sector - pchunk->img_start_sector) * 2048 / g_chain->disk_sector_size + pchunk->disk_start_sector;
-            }
-
-            secLeft = pchunk->img_end_sector + 1 - Sector;
-            secRead = (Count < secLeft) ? Count : secLeft;
+        address += 4096 - (address % 4096);
+    }
 
-            Status = pRawBlockIo->ReadBlocks(pRawBlockIo, pRawBlockIo->Media->MediaId,
-                                     MapLba, secRead * 2048, pCurBuf);
-            if (EFI_ERROR(Status))
-            {
-                debug("Raw disk read block failed %r", Status);
-                return Status;
-            }
+    param->chksum = 0;
+    param->vtoy_img_location_addr = address;
+    param->vtoy_img_location_len = length;
 
-            Count -= secRead;
-            Sector += secRead;
-            pCurBuf += secRead * 2048;
-        }
+    /* update check sum */
+    for (i = 0; i < sizeof(ventoy_os_param); i++)
+    {
+        chksum += *((UINT8 *)param + i);
     }
+    param->chksum = (chksum == 0) ? 0 : (UINT8)(0x100 - chksum);
 
-    if (ReadStart > g_chain->real_img_size_in_bytes)
+    location = (ventoy_image_location *)(unsigned long)(param->vtoy_img_location_addr);
+    if (NULL == location)
     {
-        return EFI_SUCCESS;
+        return 0;
     }
 
-    /* override data */
-    pCurBuf = (UINT8 *)Buffer;
-    for (i = 0; i < g_override_chunk_num; i++, pOverride++)
-    {
-        OverrideStart = pOverride->img_offset;
-        OverrideEnd = pOverride->img_offset + pOverride->override_size;
-    
-        if (OverrideStart >= ReadEnd || ReadStart >= OverrideEnd)
-        {
-            continue;
-        }
+    CopyMem(&location->guid, &param->guid, sizeof(ventoy_guid));
+    location->image_sector_size = gSector512Mode ? 512 : 2048;
+    location->disk_sector_size  = g_chain->disk_sector_size;
+    location->region_count = g_img_chunk_num;
+
+    region = location->regions;
 
-        if (ReadStart <= OverrideStart)
+    if (gSector512Mode)
+    {
+        for (i = 0; i < g_img_chunk_num; i++)
         {
-            if (ReadEnd <= OverrideEnd)
-            {
-                CopyMem(pCurBuf + OverrideStart - ReadStart, pOverride->override_data, ReadEnd - OverrideStart);  
-            }
-            else
-            {
-                CopyMem(pCurBuf + OverrideStart - ReadStart, pOverride->override_data, pOverride->override_size);
-            }
+            region->image_sector_count = chunk->disk_end_sector - chunk->disk_start_sector + 1;
+            region->image_start_sector = chunk->img_start_sector * 4;
+            region->disk_start_sector  = chunk->disk_start_sector;
+            region++;
+            chunk++;
         }
-        else
+    }
+    else
+    {
+        for (i = 0; i < g_img_chunk_num; i++)
         {
-            if (ReadEnd <= OverrideEnd)
-            {
-                CopyMem(pCurBuf, pOverride->override_data + ReadStart - OverrideStart, ReadEnd - ReadStart);     
-            }
-            else
-            {
-                CopyMem(pCurBuf, pOverride->override_data + ReadStart - OverrideStart, OverrideEnd - ReadStart);
-            }
+            region->image_sector_count = chunk->img_end_sector - chunk->img_start_sector + 1;
+            region->image_start_sector = chunk->img_start_sector;
+            region->disk_start_sector  = chunk->disk_start_sector;
+            region++;
+            chunk++;
         }
     }
 
-    return EFI_SUCCESS;    
-}
-
-EFI_STATUS EFIAPI ventoy_block_io_ramdisk_read 
-(
-    IN EFI_BLOCK_IO_PROTOCOL          *This,
-    IN UINT32                          MediaId,
-    IN EFI_LBA                         Lba,
-    IN UINTN                           BufferSize,
-    OUT VOID                          *Buffer
-) 
-{
-    //debug("### ventoy_block_io_ramdisk_read sector:%u count:%u", (UINT32)Lba, (UINT32)BufferSize / 2048);
-
-    (VOID)This;
-    (VOID)MediaId;
-
-    CopyMem(Buffer, (char *)g_chain + (Lba * 2048), BufferSize);
-
-       return EFI_SUCCESS;
+    return 0;
 }
 
-EFI_STATUS EFIAPI ventoy_block_io_read 
-(
-    IN EFI_BLOCK_IO_PROTOCOL          *This,
-    IN UINT32                          MediaId,
-    IN EFI_LBA                         Lba,
-    IN UINTN                           BufferSize,
-    OUT VOID                          *Buffer
-) 
+EFI_HANDLE EFIAPI ventoy_get_parent_handle(IN EFI_DEVICE_PATH_PROTOCOL *pDevPath)
 {
-    UINT32 i = 0;
-    UINT32 j = 0;
-    UINT32 lbacount = 0;
-    UINT32 secNum = 0;
-    UINT64 offset = 0;
-    EFI_LBA curlba = 0;
-    EFI_LBA lastlba = 0;
-    UINT8 *lastbuffer;
-    ventoy_sector_flag *cur_flag;
-    ventoy_virt_chunk *node;
+    EFI_HANDLE Handle = NULL;
+    EFI_STATUS Status = EFI_SUCCESS;
+    EFI_DEVICE_PATH_PROTOCOL *pLastNode = NULL;
+    EFI_DEVICE_PATH_PROTOCOL *pCurNode = NULL;
+    EFI_DEVICE_PATH_PROTOCOL *pTmpDevPath = NULL;
     
-    //debug("### ventoy_block_io_read sector:%u count:%u", (UINT32)Lba, (UINT32)BufferSize / 2048);
-
-    secNum = BufferSize / 2048;
-    offset = Lba * 2048;
-
-    if (offset + BufferSize < g_chain->real_img_size_in_bytes)
-    {
-        return ventoy_read_iso_sector(Lba, secNum, Buffer);
-    }
-
-    if (secNum > g_sector_flag_num)
-    {
-        cur_flag = AllocatePool(secNum * sizeof(ventoy_sector_flag));
-        if (NULL == cur_flag)
-        {
-            return EFI_OUT_OF_RESOURCES;
-        }
-
-        FreePool(g_sector_flag);
-        g_sector_flag = cur_flag;
-        g_sector_flag_num = secNum;
-    }
-
-    for (curlba = Lba, cur_flag = g_sector_flag, j = 0; j < secNum; j++, curlba++, cur_flag++)
+    pTmpDevPath = DuplicateDevicePath(pDevPath);
+    if (!pTmpDevPath)
     {
-        cur_flag->flag = 0;
-        for (node = g_virt_chunk, i = 0; i < g_virt_chunk_num; i++, node++)
-        {
-            if (curlba >= node->mem_sector_start && curlba < node->mem_sector_end)
-            {
-                CopyMem((UINT8 *)Buffer + j * 2048, 
-                       (char *)g_virt_chunk + node->mem_sector_offset + (curlba - node->mem_sector_start) * 2048,
-                       2048);
-                cur_flag->flag = 1;
-                break;
-            }
-            else if (curlba >= node->remap_sector_start && curlba < node->remap_sector_end)
-            {
-                cur_flag->remap_lba = node->org_sector_start + curlba - node->remap_sector_start;
-                cur_flag->flag = 2;
-                break;
-            }
-        }
+        return NULL;
     }
 
-    for (curlba = Lba, cur_flag = g_sector_flag, j = 0; j < secNum; j++, curlba++, cur_flag++)
+    pCurNode = pTmpDevPath;
+    while (!IsDevicePathEnd(pCurNode))
     {
-        if (cur_flag->flag == 2)
-        {
-            if (lastlba == 0)
-            {
-                lastbuffer = (UINT8 *)Buffer + j * 2048;
-                lastlba = cur_flag->remap_lba;
-                lbacount = 1;
-            }
-            else if (lastlba + lbacount == cur_flag->remap_lba)
-            {
-                lbacount++;
-            }
-            else
-            {
-                ventoy_read_iso_sector(lastlba, lbacount, lastbuffer);
-                lastbuffer = (UINT8 *)Buffer + j * 2048;
-                lastlba = cur_flag->remap_lba;
-                lbacount = 1;
-            }
-        }
+        pLastNode = pCurNode;
+        pCurNode = NextDevicePathNode(pCurNode);
     }
-
-    if (lbacount > 0)
+    if (pLastNode)
     {
-        ventoy_read_iso_sector(lastlba, lbacount, lastbuffer);
+        CopyMem(pLastNode, pCurNode, sizeof(EFI_DEVICE_PATH_PROTOCOL));
     }
 
-       return EFI_SUCCESS;
-}
+    pCurNode = pTmpDevPath;
+    Status = gBS->LocateDevicePath(&gEfiDevicePathProtocolGuid, &pCurNode, &Handle);
+    debug("Status:%r Parent Handle:%p DP:%s", Status, Handle, ConvertDevicePathToText(pTmpDevPath, FALSE, FALSE));
 
-EFI_STATUS EFIAPI ventoy_block_io_write 
-(
-    IN EFI_BLOCK_IO_PROTOCOL          *This,
-    IN UINT32                          MediaId,
-    IN EFI_LBA                         Lba,
-    IN UINTN                           BufferSize,
-    IN VOID                           *Buffer
-) 
-{
-    (VOID)This;
-    (VOID)MediaId;
-    (VOID)Lba;
-    (VOID)BufferSize;
-    (VOID)Buffer;
-       return EFI_WRITE_PROTECTED;
-}
+    FreePool(pTmpDevPath);
 
-EFI_STATUS EFIAPI ventoy_block_io_flush(IN EFI_BLOCK_IO_PROTOCOL *This)
-{
-       (VOID)This;
-       return EFI_SUCCESS;
+    return Handle;
 }
 
+STATIC ventoy_ram_disk g_backup_ramdisk_param;
+STATIC ventoy_os_param g_backup_os_param_var;
 
-EFI_STATUS EFIAPI ventoy_fill_device_path(VOID)
-{
-    UINTN NameLen = 0;
-    UINT8 TmpBuf[128] = {0};
-    VENDOR_DEVICE_PATH *venPath = NULL;
-
-    venPath = (VENDOR_DEVICE_PATH *)TmpBuf;
-    NameLen = StrSize(VTOY_BLOCK_DEVICE_PATH_NAME);
-    venPath->Header.Type = HARDWARE_DEVICE_PATH;
-    venPath->Header.SubType = HW_VENDOR_DP;
-    venPath->Header.Length[0] = sizeof(VENDOR_DEVICE_PATH) + NameLen;
-    venPath->Header.Length[1] = 0;
-    CopyMem(&venPath->Guid, &gVtoyBlockDevicePathGuid, sizeof(EFI_GUID));
-    CopyMem(venPath + 1, VTOY_BLOCK_DEVICE_PATH_NAME, NameLen);
-    
-    gBlockData.Path = AppendDevicePathNode(NULL, (EFI_DEVICE_PATH_PROTOCOL *)TmpBuf);
-    gBlockData.DevicePathCompareLen = sizeof(VENDOR_DEVICE_PATH) + NameLen;
-
-    debug("gBlockData.Path=<%s>\n", ConvertDevicePathToText(gBlockData.Path, FALSE, FALSE));
-
-    return EFI_SUCCESS;
-}
 
 EFI_STATUS EFIAPI ventoy_save_ramdisk_param(VOID)
 {
+    UINTN DataSize;
     EFI_STATUS Status = EFI_SUCCESS;
     EFI_GUID VarGuid = VENTOY_GUID;
+
+    DataSize = sizeof(g_backup_ramdisk_param);
+    Status = gRT->GetVariable(L"VentoyRamDisk", &VarGuid, NULL, &DataSize, &g_backup_ramdisk_param);
+    if (!EFI_ERROR(Status))
+    {
+        debug("find previous ramdisk variable <%llu>", g_backup_ramdisk_param.DiskSize);
+    }
     
     Status = gRT->SetVariable(L"VentoyRamDisk", &VarGuid, 
                   EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS,
                   sizeof(g_ramdisk_param), &(g_ramdisk_param));
-    debug("set efi variable %r", Status);
+    debug("set ramdisk variable %r", Status);
 
     return Status;
 }
 
-EFI_STATUS EFIAPI ventoy_del_ramdisk_param(VOID)
+EFI_STATUS EFIAPI ventoy_delete_ramdisk_param(VOID)
 {
     EFI_STATUS Status = EFI_SUCCESS;
     EFI_GUID VarGuid = VENTOY_GUID;
-    
-    Status = gRT->SetVariable(L"VentoyRamDisk", &VarGuid, 
+
+    if (g_backup_ramdisk_param.DiskSize > 0 && g_backup_ramdisk_param.PhyAddr > 0)
+    {
+        Status = gRT->SetVariable(L"VentoyRamDisk", &VarGuid, 
+                  EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS,
+                  sizeof(g_backup_ramdisk_param), &g_backup_ramdisk_param);
+        debug("resotre ramdisk variable %r", Status);
+    }
+    else
+    {
+        Status = gRT->SetVariable(L"VentoyRamDisk", &VarGuid, 
                   EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS,
                   0, NULL);
-    debug("delete efi variable %r", Status);
+        debug("delete ramdisk variable %r", Status);
+    }
 
     return Status;
 }
 
-
-EFI_STATUS EFIAPI ventoy_set_variable(VOID)
+EFI_STATUS EFIAPI ventoy_save_variable(VOID)
 {
+    UINTN DataSize;
     EFI_STATUS Status = EFI_SUCCESS;
     EFI_GUID VarGuid = VENTOY_GUID;
-    
+
+    DataSize = sizeof(g_backup_os_param_var);
+    Status = gRT->GetVariable(L"VentoyOsParam", &VarGuid, NULL, &DataSize, &g_backup_os_param_var);
+    if (!EFI_ERROR(Status))
+    {
+        debug("find previous efi variable <%a>", g_backup_os_param_var.vtoy_img_path);
+    }
+
     Status = gRT->SetVariable(L"VentoyOsParam", &VarGuid, 
                   EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS,
                   sizeof(g_chain->os_param), &(g_chain->os_param));
@@ -576,65 +444,56 @@ EFI_STATUS EFIAPI ventoy_delete_variable(VOID)
 {
     EFI_STATUS Status = EFI_SUCCESS;
     EFI_GUID VarGuid = VENTOY_GUID;
-    
-    Status = gRT->SetVariable(L"VentoyOsParam", &VarGuid, 
-                  EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS,
-                  0, NULL);
-    debug("delete efi variable %r", Status);
-
-    return Status;
-}
-
-
-EFI_STATUS EFIAPI ventoy_install_blockio(IN EFI_HANDLE ImageHandle, IN UINT64 ImgSize)
-{   
-    EFI_STATUS Status = EFI_SUCCESS;
-    EFI_BLOCK_IO_PROTOCOL *pBlockIo = &(gBlockData.BlockIo);
-    
-    ventoy_fill_device_path();
-    
-    gBlockData.Media.BlockSize = 2048;
-    gBlockData.Media.LastBlock = ImgSize / 2048 - 1;
-    gBlockData.Media.ReadOnly = TRUE;
-    gBlockData.Media.MediaPresent = 1;
-    gBlockData.Media.LogicalBlocksPerPhysicalBlock = 1;
-
-       pBlockIo->Revision = EFI_BLOCK_IO_PROTOCOL_REVISION3;
-       pBlockIo->Media = &(gBlockData.Media);
-       pBlockIo->Reset = ventoy_block_io_reset;
 
-    if (gMemdiskMode)
+    if (0 == CompareMem(&(g_backup_os_param_var.guid), &VarGuid, sizeof(EFI_GUID)))
     {
-        pBlockIo->ReadBlocks = ventoy_block_io_ramdisk_read;
+        Status = gRT->SetVariable(L"VentoyOsParam", &VarGuid, 
+                  EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS,
+                  sizeof(g_backup_os_param_var), &(g_backup_os_param_var));
+        debug("restore efi variable %r", Status);
     }
     else
     {
-       pBlockIo->ReadBlocks = ventoy_block_io_read;        
+        Status = gRT->SetVariable(L"VentoyOsParam", &VarGuid, 
+                  EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS,
+                  0, NULL);
+        debug("delete efi variable %r", Status);
     }
-    
-       pBlockIo->WriteBlocks = ventoy_block_io_write;
-       pBlockIo->FlushBlocks = ventoy_block_io_flush;
 
-    Status = gBS->InstallMultipleProtocolInterfaces(&gBlockData.Handle,
-            &gEfiBlockIoProtocolGuid, &gBlockData.BlockIo,
-            &gEfiDevicePathProtocolGuid, gBlockData.Path,
-            NULL);
+    return Status;
+}
 
-    debug("Install protocol %r", Status);
+#if (VENTOY_DEVICE_WARN != 0)
+STATIC VOID ventoy_warn_invalid_device(VOID)
+{
+    STATIC BOOLEAN flag = FALSE;
 
-    if (EFI_ERROR(Status))
+    if (flag)
     {
-        return Status;
+        return;
     }
 
-    Status = gBS->ConnectController(gBlockData.Handle, NULL, NULL, 1);
-    debug("Connect controller %r", Status);
+    flag = TRUE;
+    gST->ConOut->ClearScreen(gST->ConOut);
+    gST->ConOut->OutputString(gST->ConOut, VTOY_WARNING L"\r\n");
+    gST->ConOut->OutputString(gST->ConOut, VTOY_WARNING L"\r\n");
+    gST->ConOut->OutputString(gST->ConOut, VTOY_WARNING L"\r\n\r\n\r\n");
 
-    return EFI_SUCCESS;
-}
+    gST->ConOut->OutputString(gST->ConOut, L"This is NOT a standard Ventoy device and is NOT supported.\r\n\r\n");
+    gST->ConOut->OutputString(gST->ConOut, L"You should follow the official instructions in https://www.ventoy.net\r\n");
+    
+    gST->ConOut->OutputString(gST->ConOut, L"\r\n\r\nWill exit after 10 seconds ...... ");
 
+    sleep(10);
+}
+#else
+STATIC VOID ventoy_warn_invalid_device(VOID)
+{
+    
+}
+#endif
 
-EFI_STATUS EFIAPI ventoy_load_image
+STATIC EFI_STATUS EFIAPI ventoy_load_image
 (
     IN EFI_HANDLE ImageHandle,
     IN EFI_DEVICE_PATH_PROTOCOL *pDevicePath,
@@ -676,6 +535,7 @@ STATIC EFI_STATUS EFIAPI ventoy_find_iso_disk(IN EFI_HANDLE ImageHandle)
     UINTN i = 0;
     UINTN Count = 0;
     UINT64 DiskSize = 0;
+    MBR_HEAD *pMBR = NULL;
     UINT8 *pBuffer = NULL;
     EFI_HANDLE *Handles;
     EFI_STATUS Status = EFI_SUCCESS;
@@ -717,8 +577,21 @@ STATIC EFI_STATUS EFIAPI ventoy_find_iso_disk(IN EFI_HANDLE ImageHandle)
             continue;
         }
 
-        if (CompareMem(g_chain->os_param.vtoy_disk_guid, pBuffer + 0x180, 16) == 0)
+        if (CompareMem(g_chain->os_param.vtoy_disk_guid, pBuffer + 0x180, 16) == 0 &&
+            CompareMem(g_chain->os_param.vtoy_disk_signature, pBuffer + 0x1b8, 4) == 0)
         {
+            pMBR = (MBR_HEAD *)pBuffer;
+            if (g_os_param_reserved[6] == 0 && pMBR->PartTbl[0].FsFlag != 0xEE)
+            {
+                if (pMBR->PartTbl[0].StartSectorId != 2048 ||
+                    pMBR->PartTbl[1].SectorCount != 65536 ||
+                    pMBR->PartTbl[1].StartSectorId != pMBR->PartTbl[0].StartSectorId + pMBR->PartTbl[0].SectorCount)
+                {
+                    debug("Failed to check disk part table");
+                    ventoy_warn_invalid_device();
+                }
+            }
+        
             gBlockData.RawBlockIoHandle = Handles[i];
             gBlockData.pRawBlockIo = pBlockIo;
             gBS->OpenProtocol(Handles[i], &gEfiDevicePathProtocolGuid, 
@@ -727,7 +600,7 @@ STATIC EFI_STATUS EFIAPI ventoy_find_iso_disk(IN EFI_HANDLE ImageHandle)
                               Handles[i],
                               EFI_OPEN_PROTOCOL_GET_PROTOCOL);
             
-            debug("Find Ventoy Disk Handle:%p DP:%s", Handles[i], 
+            debug("Find Ventoy Disk Sig Handle:%p DP:%s", Handles[i], 
                 ConvertDevicePathToText(gBlockData.pDiskDevPath, FALSE, FALSE));
             break;
         }
@@ -745,6 +618,7 @@ STATIC EFI_STATUS EFIAPI ventoy_find_iso_disk(IN EFI_HANDLE ImageHandle)
     }
 }
 
+
 STATIC EFI_STATUS EFIAPI ventoy_find_iso_disk_fs(IN EFI_HANDLE ImageHandle)
 {
     UINTN i = 0;
@@ -806,12 +680,23 @@ STATIC EFI_STATUS EFIAPI ventoy_load_isoefi_driver(IN EFI_HANDLE ImageHandle)
     EFI_HANDLE Image = NULL;
     EFI_STATUS Status = EFI_SUCCESS;
     CHAR16 LogVar[4] = L"5";
-            
-    Status = ventoy_load_image(ImageHandle, gBlockData.pDiskFsDevPath, 
-                               gIso9660EfiDriverPath, 
-                               sizeof(gIso9660EfiDriverPath), 
-                               &Image);
-    debug("load iso efi driver status:%r", Status);
+
+    if (gIsoUdf)
+    {
+        Status = ventoy_load_image(ImageHandle, gBlockData.pDiskFsDevPath, 
+                                   gUdfEfiDriverPath, 
+                                   sizeof(gUdfEfiDriverPath), 
+                                   &Image);
+        debug("load iso UDF efi driver status:%r", Status);
+    }
+    else
+    {
+        Status = ventoy_load_image(ImageHandle, gBlockData.pDiskFsDevPath, 
+                                   gIso9660EfiDriverPath, 
+                                   sizeof(gIso9660EfiDriverPath), 
+                                   &Image);
+        debug("load iso 9660 efi driver status:%r", Status);        
+    }
 
     if (gDebugPrint)
     {
@@ -831,81 +716,120 @@ STATIC EFI_STATUS EFIAPI ventoy_load_isoefi_driver(IN EFI_HANDLE ImageHandle)
     return EFI_SUCCESS;
 }
 
-static int ventoy_update_image_location(ventoy_os_param *param)
+STATIC EFI_STATUS ventoy_proc_img_replace_name(ventoy_grub_param_file_replace *replace)
 {
-    EFI_STATUS Status = EFI_SUCCESS;
-    UINT8 chksum = 0;
-    unsigned int i;
-    unsigned int length;
-    UINTN address = 0;
-    void *buffer = NULL;
-    ventoy_image_location *location = NULL;
-    ventoy_image_disk_region *region = NULL;
-    ventoy_img_chunk *chunk = g_chunk;
-
-    length = sizeof(ventoy_image_location) + (g_img_chunk_num - 1) * sizeof(ventoy_image_disk_region);
+    UINT32 i;
+    char tmp[256];
 
-    Status = gBS->AllocatePool(EfiRuntimeServicesData, length + 4096 * 2, &buffer);
-    if (EFI_ERROR(Status) || NULL == buffer)
+    if (replace->magic != GRUB_IMG_REPLACE_MAGIC)
     {
-        debug("Failed to allocate runtime pool %r\n", Status);
-        return 1;
+        return EFI_SUCCESS;
     }
 
-    address = (UINTN)buffer;
+    if (replace->old_file_name[0][0] == 0)
+    {
+        return EFI_SUCCESS;
+    }
 
-    if (address % 4096)
+    AsciiStrCpyS(tmp, sizeof(tmp), replace->old_file_name[0]);
+    
+    for (i = 0; i < 256 && tmp[i]; i++)
     {
-        address += 4096 - (address % 4096);
+        if (tmp[i] == '/')
+        {
+            tmp[i] = '\\';
+        }
     }
 
-    param->chksum = 0;
-    param->vtoy_img_location_addr = address;
-    param->vtoy_img_location_len = length;
+    AsciiStrCpyS(replace->old_file_name[0], 256, tmp);
+    return EFI_SUCCESS;
+}
 
-    /* update check sum */
-    for (i = 0; i < sizeof(ventoy_os_param); i++)
+EFI_STATUS EFIAPI ventoy_get_variable_wrapper
+(
+    IN     CHAR16                      *VariableName,
+    IN     EFI_GUID                    *VendorGuid,
+    OUT    UINT32                      *Attributes,    OPTIONAL
+    IN OUT UINTN                       *DataSize,
+    OUT    VOID                        *Data           OPTIONAL
+)
+{
+    EFI_STATUS Status = EFI_SUCCESS;
+    
+    Status = g_org_get_variable(VariableName, VendorGuid, Attributes, DataSize, Data);
+    if (StrCmp(VariableName, L"SecureBoot") == 0)
     {
-        chksum += *((UINT8 *)param + i);
+        if ((*DataSize == 1) && Data)
+        {
+            *(UINT8 *)Data = 0;
+        }
     }
-    param->chksum = (chksum == 0) ? 0 : (UINT8)(0x100 - chksum);
 
-    location = (ventoy_image_location *)(unsigned long)(param->vtoy_img_location_addr);
-    if (NULL == location)
+    return Status;
+}
+
+EFI_STATUS EFIAPI ventoy_exit_boot_service_wrapper
+(
+    IN  EFI_HANDLE                   ImageHandle,
+    IN  UINTN                        MapKey
+)
+{
+    if (g_org_get_variable)
     {
-        return 0;
+        gRT->GetVariable = g_org_get_variable;
+        g_org_get_variable = NULL;
     }
+    
+    return g_org_exit_boot_service(ImageHandle, MapKey);
+}
 
-    CopyMem(&location->guid, &param->guid, sizeof(ventoy_guid));
-    location->image_sector_size = 2048;
-    location->disk_sector_size  = g_chain->disk_sector_size;
-    location->region_count = g_img_chunk_num;
-
-    region = location->regions;
+STATIC EFI_STATUS EFIAPI ventoy_disable_secure_boot(IN EFI_HANDLE ImageHandle)
+{
+    UINT8 Value = 0;
+    UINTN DataSize = 1;
+    EFI_STATUS Status = EFI_SUCCESS;
 
-    for (i = 0; i < g_img_chunk_num; i++)
+    Status = gRT->GetVariable(L"SecureBoot", &gEfiGlobalVariableGuid, NULL, &DataSize, &Value);
+    if (!EFI_ERROR(Status))
     {
-        region->image_sector_count = chunk->img_end_sector - chunk->img_start_sector + 1;
-        region->image_start_sector = chunk->img_start_sector;
-        region->disk_start_sector  = chunk->disk_start_sector;
-        region++;
-        chunk++;
+        if (DataSize == 1 && Value == 0)
+        {
+            debug("Current secure boot is off, no need to disable");
+            return EFI_SUCCESS;
+        }
     }
 
-    return 0;
+    debug("ventoy_disable_secure_boot");
+
+    /* step1: wrapper security protocol. */
+    /* Do we still need it since we have been loaded ? */
+    
+    
+    /* step2: fake SecureBoot variable */
+    g_org_exit_boot_service = gBS->ExitBootServices;
+    gBS->ExitBootServices = ventoy_exit_boot_service_wrapper;
+    
+    g_org_get_variable = gRT->GetVariable;
+    gRT->GetVariable = ventoy_get_variable_wrapper;
+
+    return EFI_SUCCESS;
 }
 
+
 STATIC EFI_STATUS EFIAPI ventoy_parse_cmdline(IN EFI_HANDLE ImageHandle)
 {   
     UINT32 i = 0;
     UINT32 old_cnt = 0;
     UINTN size = 0;
     UINT8 chksum = 0;
+    const char *pEnv = NULL;
     CHAR16 *pPos = NULL;
     CHAR16 *pCmdLine = NULL;
     EFI_STATUS Status = EFI_SUCCESS;
     ventoy_grub_param *pGrubParam = NULL;
     EFI_LOADED_IMAGE_PROTOCOL *pImageInfo = NULL;
+    ventoy_chain_head *chain = NULL;
+    ventoy_grub_param_file_replace *replace = NULL;
 
     Status = gBS->HandleProtocol(ImageHandle, &gEfiLoadedImageProtocolGuid, (VOID **)&pImageInfo);
     if (EFI_ERROR(Status))
@@ -922,11 +846,26 @@ STATIC EFI_STATUS EFIAPI ventoy_parse_cmdline(IN EFI_HANDLE ImageHandle)
     {
         gDebugPrint = TRUE;
     }
+    
+    if (StrStr(pCmdLine, L"fallback"))
+    {
+        gBootFallBack = TRUE;
+    }
+    
+    if (StrStr(pCmdLine, L"dotefi"))
+    {
+        gDotEfiBoot = TRUE;
+    }
 
     if (StrStr(pCmdLine, L"isoefi=on"))
     {
         gLoadIsoEfi = TRUE;
     }
+    
+    if (StrStr(pCmdLine, L"iso_udf"))
+    {
+        gIsoUdf = TRUE;
+    }
 
     pPos = StrStr(pCmdLine, L"FirstTry=@");
     if (pPos)
@@ -962,8 +901,20 @@ STATIC EFI_STATUS EFIAPI ventoy_parse_cmdline(IN EFI_HANDLE ImageHandle)
     }
     
     pGrubParam = (ventoy_grub_param *)StrHexToUintn(pPos + StrLen(L"env_param="));
+    grub_env_set = pGrubParam->grub_env_set;
     grub_env_get = pGrubParam->grub_env_get;
+    pEnv = grub_env_get("VTOY_CHKDEV_RESULT_STRING");
+    if (!pEnv)
+    {
+        return EFI_INVALID_PARAMETER;
+    }
 
+    if (pEnv[0] != '0' || pEnv[1] != 0)
+    {
+        ventoy_warn_invalid_device();
+        return EFI_INVALID_PARAMETER;
+    }
+    
     g_file_replace_list = &pGrubParam->file_replace;
     old_cnt = g_file_replace_list->old_file_cnt;
     debug("file replace: magic:0x%x virtid:%u name count:%u <%a> <%a> <%a> <%a>",
@@ -976,21 +927,57 @@ STATIC EFI_STATUS EFIAPI ventoy_parse_cmdline(IN EFI_HANDLE ImageHandle)
         old_cnt > 3 ? g_file_replace_list->old_file_name[3] : ""
         );
 
+    
+    for (i = 0; i < VTOY_MAX_CONF_REPLACE; i++)
+    {
+        replace = pGrubParam->img_replace + i;
+        if (replace->magic == GRUB_IMG_REPLACE_MAGIC)
+        {
+            ventoy_proc_img_replace_name(replace);
+            old_cnt = replace->old_file_cnt;
+            debug("img replace[%d]: magic:0x%x virtid:%u name count:%u <%a> <%a> <%a> <%a>",
+                  i, replace->magic,
+                  replace->new_file_virtual_id,
+                  old_cnt,
+                  old_cnt > 0 ? replace->old_file_name[0] : "",
+                  old_cnt > 1 ? replace->old_file_name[1] : "",
+                  old_cnt > 2 ? replace->old_file_name[2] : "",
+                  old_cnt > 3 ? replace->old_file_name[3] : ""
+                  );
+            g_img_replace_list = pGrubParam->img_replace;
+        }
+    }
+
+    
     pPos = StrStr(pCmdLine, L"mem:");
-    g_chain = (ventoy_chain_head *)StrHexToUintn(pPos + 4);
+    chain = (ventoy_chain_head *)StrHexToUintn(pPos + 4);
 
     pPos = StrStr(pPos, L"size:");
     size = StrDecimalToUintn(pPos + 5);
 
-    debug("memory addr:%p size:%lu", g_chain, size);
+    debug("memory addr:%p size:%lu", chain, size);
+
+    if (StrStr(pCmdLine, L"sector512"))
+    {
+        gSector512Mode = TRUE;
+    }
 
     if (StrStr(pCmdLine, L"memdisk"))
     {
-        g_iso_buf_size = size;
+        g_iso_data_buf = (UINT8 *)chain + sizeof(ventoy_chain_head);
+        g_iso_buf_size = size - sizeof(ventoy_chain_head);
+        debug("memdisk mode iso_buf_size:%u", g_iso_buf_size);
+
+        g_chain = chain;
+        g_os_param_reserved = (UINT8 *)(g_chain->os_param.vtoy_reserved);
         gMemdiskMode = TRUE;
     }
     else
     {
+        debug("This is normal mode");
+        g_chain = AllocatePool(size);
+        CopyMem(g_chain, chain, size);
+    
         g_chunk = (ventoy_img_chunk *)((char *)g_chain + g_chain->img_chunk_offset);
         g_img_chunk_num = g_chain->img_chunk_num;
         g_override_chunk = (ventoy_override_chunk *)((char *)g_chain + g_chain->override_chunk_offset);
@@ -998,6 +985,26 @@ STATIC EFI_STATUS EFIAPI ventoy_parse_cmdline(IN EFI_HANDLE ImageHandle)
         g_virt_chunk = (ventoy_virt_chunk *)((char *)g_chain + g_chain->virt_chunk_offset);
         g_virt_chunk_num = g_chain->virt_chunk_num;
 
+        g_os_param_reserved = (UINT8 *)(g_chain->os_param.vtoy_reserved);
+
+        /* Workaround for Windows & ISO9660 */
+        if (g_os_param_reserved[2] == ventoy_chain_windows && g_os_param_reserved[3] == 0)
+        {
+            g_fixup_iso9660_secover_enable = TRUE;
+        }
+
+        if (g_os_param_reserved[2] == ventoy_chain_windows && g_os_param_reserved[4] != 1)
+        {
+            g_hook_keyboard = TRUE;
+        }
+        
+        if (g_os_param_reserved[5] == 1 && g_os_param_reserved[2] == ventoy_chain_linux)
+        {
+            ventoy_disable_secure_boot(ImageHandle);
+        }
+
+        debug("internal param: secover:%u keyboard:%u", g_fixup_iso9660_secover_enable, g_hook_keyboard);
+
         for (i = 0; i < sizeof(ventoy_os_param); i++)
         {
             chksum += *((UINT8 *)(&(g_chain->os_param)) + i);
@@ -1016,85 +1023,90 @@ STATIC EFI_STATUS EFIAPI ventoy_parse_cmdline(IN EFI_HANDLE ImageHandle)
         }
     }
 
+    g_fix_windows_1st_cdrom_issue = FALSE;
+    if (ventoy_chain_windows == g_os_param_reserved[2] || 
+        ventoy_chain_wim == g_os_param_reserved[2])
+    {
+        if (ventoy_is_cdrom_dp_exist())
+        {
+            debug("fixup the 1st cdrom influences when boot windows ...");
+            g_fix_windows_1st_cdrom_issue = TRUE;
+        }
+    }
+
+    ventoy_debug_pause();
+
     FreePool(pCmdLine);
     return EFI_SUCCESS;
 }
 
-EFI_STATUS EFIAPI ventoy_wrapper_file_open
-(
-    EFI_FILE_HANDLE This, 
-    EFI_FILE_HANDLE *New,
-    CHAR16 *Name, 
-    UINT64 Mode, 
-    UINT64 Attributes
-)
+EFI_STATUS EFIAPI ventoy_clean_env(VOID)
 {
-    UINT32 i = 0;
-    UINT32 j = 0;
-    UINT64 Sectors = 0;
-    EFI_STATUS Status = EFI_SUCCESS;
-    CHAR8 TmpName[256];
-    ventoy_virt_chunk *virt = NULL;
+    FreePool(g_sector_flag);
+    g_sector_flag_num = 0;
 
-    Status = g_original_fopen(This, New, Name, Mode, Attributes);
-    if (EFI_ERROR(Status))
+    if (gLoadIsoEfi && gBlockData.IsoDriverImage)
     {
-        return Status;
+        gBS->UnloadImage(gBlockData.IsoDriverImage);
     }
 
-    if (g_file_replace_list && g_file_replace_list->magic == GRUB_FILE_REPLACE_MAGIC &&
-        g_file_replace_list->new_file_virtual_id < g_virt_chunk_num)
-    {
-        AsciiSPrint(TmpName, sizeof(TmpName), "%s", Name);
-        for (j = 0; j < 4; j++)
-        {
-            if (0 == AsciiStrCmp(g_file_replace_list[i].old_file_name[j], TmpName))
-            {
-                g_original_fclose(*New);
-                *New = &g_efi_file_replace.WrapperHandle;
-                ventoy_wrapper_file_procotol(*New);
+    gBS->DisconnectController(gBlockData.Handle, NULL, NULL);
 
-                virt = g_virt_chunk + g_file_replace_list->new_file_virtual_id;
+    gBS->UninstallMultipleProtocolInterfaces(gBlockData.Handle,
+            &gEfiBlockIoProtocolGuid, &gBlockData.BlockIo,
+            &gEfiDevicePathProtocolGuid, gBlockData.Path,
+            NULL);
 
-                Sectors = (virt->mem_sector_end - virt->mem_sector_start) + (virt->remap_sector_end - virt->remap_sector_start);
-                
-                g_efi_file_replace.BlockIoSectorStart = virt->mem_sector_start;
-                g_efi_file_replace.FileSizeBytes = Sectors * 2048;
+    ventoy_delete_variable();
 
-                if (gDebugPrint)
-                {
-                    debug("## ventoy_wrapper_file_open <%s> BlockStart:%lu Sectors:%lu Bytes:%lu", Name,
-                        g_efi_file_replace.BlockIoSectorStart, Sectors, Sectors * 2048);
-                    sleep(3);
-                }
-                
-                return Status;
-            }
-        }
+    if (g_vtoy_img_location_buf)
+    {
+        FreePool(g_vtoy_img_location_buf);
     }
 
-    return Status;
+    if (!gMemdiskMode)
+    {
+        FreePool(g_chain);        
+    }
+
+    return EFI_SUCCESS;
 }
 
-EFI_STATUS EFIAPI ventoy_wrapper_open_volume
-(
-    IN EFI_SIMPLE_FILE_SYSTEM_PROTOCOL     *This,
-    OUT EFI_FILE_PROTOCOL                 **Root
-)
+STATIC EFI_STATUS ventoy_hook_start(VOID)
 {
-    EFI_STATUS Status = EFI_SUCCESS;
-    
-    Status = g_original_open_volume(This, Root);
-    if (!EFI_ERROR(Status))
+    /* don't add debug print in this function */
+
+    if (g_fix_windows_1st_cdrom_issue)
     {
-        g_original_fopen = (*Root)->Open;
-        g_original_fclose = (*Root)->Close;
-        (*Root)->Open = ventoy_wrapper_file_open;
+        ventoy_hook_1st_cdrom_start();
     }
 
-    return Status;
+    /* let this the last */
+    if (g_hook_keyboard)
+    {
+        ventoy_hook_keyboard_start();
+    }
+
+    return EFI_SUCCESS;
 }
 
+STATIC EFI_STATUS ventoy_hook_stop(VOID)
+{
+    /* don't add debug print in this function */
+
+    if (g_fix_windows_1st_cdrom_issue)
+    {
+        ventoy_hook_1st_cdrom_stop();
+    }
+
+    /* let this the last */
+    if (g_hook_keyboard)
+    {
+        ventoy_hook_keyboard_stop();
+    }
+
+    return EFI_SUCCESS;
+}
 
 EFI_STATUS EFIAPI ventoy_boot(IN EFI_HANDLE ImageHandle)
 {
@@ -1174,16 +1186,20 @@ EFI_STATUS EFIAPI ventoy_boot(IN EFI_HANDLE ImageHandle)
             if (gDebugPrint)
             {
                 gST->ConIn->Reset(gST->ConIn, FALSE);
-                //ventoy_wrapper_system();
             }
-
-            if (g_file_replace_list && g_file_replace_list->magic == GRUB_FILE_REPLACE_MAGIC)
+            
+            if ((g_file_replace_list && g_file_replace_list->magic == GRUB_FILE_REPLACE_MAGIC) || g_img_replace_list)
             {
-                g_original_open_volume = pFile->OpenVolume;
+                ventoy_wrapper_push_openvolume(pFile->OpenVolume);
                 pFile->OpenVolume = ventoy_wrapper_open_volume;
             }
-            
+
+            ventoy_hook_start();
+            /* can't add debug print here */
+            //ventoy_wrapper_system();
             Status = gBS->StartImage(Image, NULL, NULL);
+            ventoy_hook_stop();
+            
             if (EFI_ERROR(Status))
             {
                 debug("Failed to start image %r", Status);
@@ -1197,8 +1213,13 @@ EFI_STATUS EFIAPI ventoy_boot(IN EFI_HANDLE ImageHandle)
 
         if (Find == 0)
         {
+            if (gDotEfiBoot)
+            {
+                break;
+            }
+        
             debug("Fs not found, now wait and retry...");
-            sleep(2);
+            sleep(1);
         }
     }
 
@@ -1210,75 +1231,6 @@ EFI_STATUS EFIAPI ventoy_boot(IN EFI_HANDLE ImageHandle)
     return EFI_SUCCESS;
 }
 
-EFI_STATUS EFIAPI ventoy_clean_env(VOID)
-{
-    FreePool(g_sector_flag);
-    g_sector_flag_num = 0;
-
-    if (gLoadIsoEfi && gBlockData.IsoDriverImage)
-    {
-        gBS->UnloadImage(gBlockData.IsoDriverImage);
-    }
-
-    gBS->DisconnectController(gBlockData.Handle, NULL, NULL);
-
-    gBS->UninstallMultipleProtocolInterfaces(gBlockData.Handle,
-            &gEfiBlockIoProtocolGuid, &gBlockData.BlockIo,
-            &gEfiDevicePathProtocolGuid, gBlockData.Path,
-            NULL);
-
-    ventoy_delete_variable();
-
-    if (g_chain->os_param.vtoy_img_location_addr)
-    {
-        FreePool((VOID *)(UINTN)g_chain->os_param.vtoy_img_location_addr);
-    }
-
-    return EFI_SUCCESS;
-}
-
-EFI_STATUS EFIAPI ventoy_ramdisk_boot(IN EFI_HANDLE ImageHandle)
-{
-    EFI_STATUS Status = EFI_SUCCESS;
-    EFI_RAM_DISK_PROTOCOL *RamDisk = NULL;
-    EFI_DEVICE_PATH_PROTOCOL *DevicePath = NULL;
-
-    debug("RamDisk Boot ...");
-
-    Status = gBS->LocateProtocol(&gEfiRamDiskProtocolGuid, NULL, (VOID **)&RamDisk);
-    if (EFI_ERROR(Status))
-    {
-        debug("Failed to locate ramdisk protocol %r", Status);
-        return Status;
-    }
-    debug("Locate RamDisk Protocol %r ...", Status);
-
-    Status = RamDisk->Register((UINTN)g_chain, (UINT64)g_iso_buf_size, &gEfiVirtualCdGuid, NULL, &DevicePath);
-    if (EFI_ERROR(Status))
-    {
-        debug("Failed to register ramdisk %r", Status);
-        return Status;
-    }
-    
-    debug("Register RamDisk %r ...", Status);
-    debug("RamDisk DevicePath:<%s> ...", ConvertDevicePathToText(DevicePath, FALSE, FALSE));
-
-    ventoy_debug_pause();
-
-    gBlockData.Path = DevicePath;
-    gBlockData.DevicePathCompareLen = GetDevicePathSize(DevicePath) - sizeof(EFI_DEVICE_PATH_PROTOCOL);
-
-    Status = ventoy_boot(ImageHandle);
-    if (EFI_NOT_FOUND == Status)
-    {
-        gST->ConOut->OutputString(gST->ConOut, L"No bootfile found for UEFI!\r\n");
-        gST->ConOut->OutputString(gST->ConOut, L"Maybe the image does not support " VENTOY_UEFI_DESC  L"!\r\n");
-        sleep(300);
-    }
-    
-    return EFI_SUCCESS;
-}
-
 EFI_STATUS EFIAPI VentoyEfiMain
 (
     IN EFI_HANDLE         ImageHandle,
@@ -1286,6 +1238,7 @@ EFI_STATUS EFIAPI VentoyEfiMain
 )
 {
     EFI_STATUS Status = EFI_SUCCESS;
+    EFI_SIMPLE_TEXT_INPUT_EX_PROTOCOL *Protocol;
     
     g_sector_flag_num = 512; /* initial value */
 
@@ -1295,73 +1248,99 @@ EFI_STATUS EFIAPI VentoyEfiMain
         return EFI_OUT_OF_RESOURCES;
     }
 
+    Status = gBS->HandleProtocol(gST->ConsoleInHandle, &gEfiSimpleTextInputExProtocolGuid, (VOID **)&Protocol);
+    if (EFI_SUCCESS == Status)
+    {
+        g_con_simple_input_ex = Protocol;
+    }
+
     gST->ConOut->ClearScreen(gST->ConOut);
     ventoy_clear_input();
 
-    ventoy_parse_cmdline(ImageHandle);
+    Status = ventoy_parse_cmdline(ImageHandle);
+    if (EFI_ERROR(Status))
+    {
+        return Status;
+    }
+
+    ventoy_disable_ex_filesystem();
 
     if (gMemdiskMode)
     {
-        g_ramdisk_param.PhyAddr = (UINT64)(UINTN)g_chain;
+        g_ramdisk_param.PhyAddr = (UINT64)(UINTN)g_iso_data_buf;
         g_ramdisk_param.DiskSize = (UINT64)g_iso_buf_size;
 
         ventoy_save_ramdisk_param();
-        
-        ventoy_install_blockio(ImageHandle, g_iso_buf_size);
-        Status = ventoy_boot(ImageHandle);
-        if (EFI_NOT_FOUND == Status)
-        {
-            gST->ConOut->OutputString(gST->ConOut, L"No bootfile found for UEFI!\r\n");
-            gST->ConOut->OutputString(gST->ConOut, L"Maybe the image does not support " VENTOY_UEFI_DESC  L"!\r\n");
-            sleep(300);
-        }
-
-        ventoy_del_ramdisk_param();
-    }
-    else
-    {
-        ventoy_set_variable();
-        ventoy_find_iso_disk(ImageHandle);
 
         if (gLoadIsoEfi)
         {
+            ventoy_find_iso_disk(ImageHandle);
             ventoy_find_iso_disk_fs(ImageHandle);
             ventoy_load_isoefi_driver(ImageHandle);
         }
-
-        ventoy_debug_pause();
         
-        ventoy_install_blockio(ImageHandle, g_chain->virt_img_size_in_bytes);
-
+        ventoy_install_blockio(ImageHandle, g_iso_buf_size);
         ventoy_debug_pause();
 
         Status = ventoy_boot(ImageHandle);
-        if (EFI_NOT_FOUND == Status)
+        
+        ventoy_delete_ramdisk_param();
+
+        if (gLoadIsoEfi && gBlockData.IsoDriverImage)
+        {
+            gBS->UnloadImage(gBlockData.IsoDriverImage);
+        }
+
+        gBS->DisconnectController(gBlockData.Handle, NULL, NULL);
+        gBS->UninstallMultipleProtocolInterfaces(gBlockData.Handle,
+                &gEfiBlockIoProtocolGuid, &gBlockData.BlockIo,
+                &gEfiDevicePathProtocolGuid, gBlockData.Path,
+                NULL);
+    }
+    else
+    {
+        ventoy_save_variable();
+        Status = ventoy_find_iso_disk(ImageHandle);
+        if (!EFI_ERROR(Status))
         {
-            if (!gLoadIsoEfi)
+            if (gLoadIsoEfi)
             {
-                gLoadIsoEfi = TRUE;
                 ventoy_find_iso_disk_fs(ImageHandle);
                 ventoy_load_isoefi_driver(ImageHandle);
-
-                Status = ventoy_boot(ImageHandle);
             }
 
-            if (EFI_NOT_FOUND == Status)
-            {
-                gST->ConOut->OutputString(gST->ConOut, L"No bootfile found for UEFI!\r\n");
-                gST->ConOut->OutputString(gST->ConOut, L"Maybe the image does not support " VENTOY_UEFI_DESC  L"!\r\n");
-                sleep(60);
-            }
-        }
+            ventoy_debug_pause();
+            
+            ventoy_install_blockio(ImageHandle, g_chain->virt_img_size_in_bytes);
 
+            ventoy_debug_pause();
+
+            Status = ventoy_boot(ImageHandle);
+        }
+        
         ventoy_clean_env();
     }
+
+    if (FALSE == gDotEfiBoot && FALSE == gBootFallBack)
+    {
+        if (EFI_NOT_FOUND == Status)
+        {
+            gST->ConOut->OutputString(gST->ConOut, L"No bootfile found for UEFI!\r\n");
+            gST->ConOut->OutputString(gST->ConOut, L"Maybe the image does not support " VENTOY_UEFI_DESC  L"!\r\n");
+            sleep(30);
+        }
+    }
     
     ventoy_clear_input();
     gST->ConOut->ClearScreen(gST->ConOut);
 
+    if (gDotEfiBoot && (EFI_NOT_FOUND == Status))
+    {
+        grub_env_set("vtoy_dotefi_retry", "YES");            
+    }
+
+    ventoy_enable_ex_filesystem();
+
     return EFI_SUCCESS;
 }
 
-