int main() { volatile int i,j,k; //i = row, j = column, int count; int M1[10][10]={0,0,0,0,0,0,0,0,0,0, 32,32,33,34,32,32,33,34,32,32, 32,32,33,34,32,32,33,34,32,32, 32,32,33,34,32,32,33,34,32,32, 32,32,33,34,32,32,33,34,32,32, 19,32,33,34,32,32,33,34,32,32, 32,32,33,34,32,32,33,34,32,32, 32,32,33,34,32,32,33,34,32,32, 32,32,33,34,32,32,33,34,32,32, 19,32,33,34,32,32,33,34,32,32}; int M2[10][10]={32,32,33,34,32,32,33,34,32,32, 32,32,33,34,32,32,33,34,32,32, 32,32,33,34,32,32,33,34,32,32, 32,32,33,34,32,32,33,34,32,32, 32,32,33,34,32,32,33,34,32,32, 19,32,33,34,32,32,33,34,32,32, 32,32,33,34,32,32,33,34,32,32, 32,32,33,34,32,32,33,34,32,32, 32,32,33,34,32,32,33,34,32,32, 19,32,33,34,32,32,33,34,32,32}; int C[10][10]={0}; PERF_RESET (PERFORMANCE_COUNTER_BASE); //Reset Performance Counters to 0 PERF_START_MEASURING (PERFORMANCE_COUNTER_BASE); //Start the Counter PERF_BEGIN (PERFORMANCE_COUNTER_BASE,2); //Start the overhead counter PERF_BEGIN (PERFORMANCE_COUNTER_BASE,1); //Start the Matrix Multiplication Counter PERF_END (PERFORMANCE_COUNTER_BASE,2); //Stop the overhead counter count = 0; while(count<100){ count++; for (i=0;i<=9;i++){ for (j=0;j<=9;j++){ C[i][j] = 0; for (k=0;k<=9;k++){ C[i][j]+=M1[i][k]*M2[k][j]; } //printf("%f ", C[i][j]); } } } PERF_END (PERFORMANCE_COUNTER_BASE,1); //Stop the Matrix Multiplication Counter PERF_STOP_MEASURING (PERFORMANCE_COUNTER_BASE); //Stop all counters perf_print_formatted_report((void *)PERFORMANCE_COUNTER_BASE, ALT_CPU_FREQ, 2, "100 loops","PC overhead"); return 0; }
void display_frame(ClFrame &frame) { if(m_crop) { PERF_START("display_image_crop"); display_image_ocl_crop(frame); PERF_END("display_image_crop"); } else { PERF_START("display_image"); display_image(frame); PERF_END("display_image"); } }
/** This function will connect all the console devices base on the console device variable ConIn, ConOut and ErrOut. **/ VOID EFIAPI EfiBootManagerConnectAllDefaultConsoles ( VOID ) { BOOLEAN SystemTableUpdated; EfiBootManagerConnectConsoleVariable (ConOut, TRUE); PERF_START (NULL, "ConOutReady", "BDS", 1); PERF_END (NULL, "ConOutReady", "BDS", 0); EfiBootManagerConnectConsoleVariable (ConIn, TRUE); PERF_START (NULL, "ConInReady", "BDS", 1); PERF_END (NULL, "ConInReady", "BDS", 0); // // The _ModuleEntryPoint err out var is legal. // EfiBootManagerConnectConsoleVariable (ErrOut, TRUE); PERF_START (NULL, "ErrOutReady", "BDS", 1); PERF_END (NULL, "ErrOutReady", "BDS", 0); SystemTableUpdated = FALSE; // // Fill console handles in System Table if no console device assignd. // if (UpdateSystemTableConsole (L"ConIn", &gEfiSimpleTextInProtocolGuid, &gST->ConsoleInHandle, (VOID **) &gST->ConIn)) { SystemTableUpdated = TRUE; } if (UpdateSystemTableConsole (L"ConOut", &gEfiSimpleTextOutProtocolGuid, &gST->ConsoleOutHandle, (VOID **) &gST->ConOut)) { SystemTableUpdated = TRUE; } if (UpdateSystemTableConsole (L"ErrOut", &gEfiSimpleTextOutProtocolGuid, &gST->StandardErrorHandle, (VOID **) &gST->StdErr)) { SystemTableUpdated = TRUE; } if (SystemTableUpdated) { // // Update the CRC32 in the EFI System Table header // gST->Hdr.CRC32 = 0; gBS->CalculateCrc32 ( (UINT8 *) &gST->Hdr, gST->Hdr.HeaderSize, &gST->Hdr.CRC32 ); } }
/** * Funkcja testujaca wydajnosc modulow Triple DES przy wykorzystaniu zapisu i odczytu danych na On-Chip Memory */ void test_wydajnosc () { printf ("Test wydajnosci \n"); PERF_RESET(PERFORMANCE_COUNTER_0_BASE ); PERF_START_MEASURING(PERFORMANCE_COUNTER_0_BASE); int i=0; int j=0; PERF_BEGIN(PERFORMANCE_COUNTER_0_BASE ,2); //rozpoczecie pracy 2 licznika mierzacego takty zegara while(i<512) { deciph_3des(dane[2*i],dane[2*i+1]); j--; j++; deciph_3des_read(&wyniki[2*i],&wyniki[2*i+1]); i++; } PERF_END(PERFORMANCE_COUNTER_0_BASE ,2); //zakonczenie pracy 2 licznika mierzacego takty zegara i=0; PERF_BEGIN(PERFORMANCE_COUNTER_0_BASE ,1);//rozpoczecie pracy 1 licznika mierzacego takty zegara while(i<512) { ciph_3des(dane[2*i],dane[2*i+1]); j--; j++; ciph_3des_read(&wyniki[2*i],&wyniki[2*i+1]); i++; } PERF_STOP_MEASURING(PERFORMANCE_COUNTER_0_BASE); //zakonczenie pracy wszystkich licznikow perf_print_formatted_report((void* )PERFORMANCE_COUNTER_0_BASE, ALT_CPU_FREQ*2,2,"3Des 32Kbit szyfr","3Des 32Kbit deszyfr"); //generacja raportu }
unsigned char * copy_yuv2rgb(ClFrame &in_frame, ClFrame &out_frame) { PERF_START("process_yuv"); unsigned char *tmp_img = out_frame.get(); char *current = (char *)in_frame.get(); int x, y; y = 0; while(y < m_height) { x = 0; while(x < m_width) { //char Y = current[0]; //char U = current[1]; //char Y2 = current[2]; //char V = current[3]; yuv2rgb(tmp_img, 0, current[0], 128, 16, current[1], current[3]); yuv2rgb(tmp_img, 4, current[2], 128, 16, current[1], current[3]); tmp_img = tmp_img + 8; current = current + 4; x = x + 2; } current = ((char *)in_frame.get()) + y * m_width * 2; y++; } PERF_END("process_yuv"); }
/* * Funkcja przeprowadzajaca pomiary szyfrowania 1 MB danych */ void test_wydajnosci_3des_pot() { printf("Test wydajnosci potokowej realizacji szyfratora i deszyfratora Triple DES \n"); PERF_RESET(PERFORMANCE_COUNTER_0_BASE ); PERF_START_MEASURING(PERFORMANCE_COUNTER_0_BASE); int i=0; int j=0; PERF_BEGIN(PERFORMANCE_COUNTER_0_BASE ,2); //rozpoczecie pracy 2 licznika mierzacego takty zegara while(i<512) { ciph_3des_pot(&blok_testowy+2048*i,&blok_testowy+1048576+2048*i,2048); i++; } PERF_END(PERFORMANCE_COUNTER_0_BASE ,2); //zakonczenie pracy 2 licznika mierzacego takty zegara i=0; PERF_BEGIN(PERFORMANCE_COUNTER_0_BASE ,1);//rozpoczecie pracy 1 licznika mierzacego takty zegara while(i<512) { deciph_3des_pot(&blok_testowy+2048*i,&blok_testowy+1048576+2048*i,2048); i++; } PERF_STOP_MEASURING(PERFORMANCE_COUNTER_0_BASE); //zakonczenie pracy wszystkich licznikow perf_print_formatted_report((void* )PERFORMANCE_COUNTER_0_BASE, ALT_CPU_FREQ*2,2,"3Des_pot 1MB szyfr","3Des_pot 1MB deszyfr"); //generacja raportu }
/** This function will connect console device except ConIn base on the console device variable ConOut and ErrOut. @retval EFI_SUCCESS At least one of the ConOut device have been connected success. @retval EFI_STATUS Return the status of BdsLibConnectConsoleVariable (). **/ EFI_STATUS EFIAPI BdsLibConnectAllDefaultConsolesWithOutConIn ( VOID ) { EFI_STATUS Status; BOOLEAN SystemTableUpdated; // // Connect all default console variables except ConIn // // // It seems impossible not to have any ConOut device on platform, // so we check the status here. // Status = BdsLibConnectConsoleVariable (L"ConOut"); if (EFI_ERROR (Status)) { return Status; } // // Insert the performance probe for Console Out // PERF_START (NULL, "ConOut", "BDS", 1); PERF_END (NULL, "ConOut", "BDS", 0); // // The _ModuleEntryPoint err out var is legal. // BdsLibConnectConsoleVariable (L"ErrOut"); SystemTableUpdated = FALSE; // // Fill console handles in System Table if no console device assignd. // if (UpdateSystemTableConsole (L"ConOut", &gEfiSimpleTextOutProtocolGuid, &gST->ConsoleOutHandle, (VOID **) &gST->ConOut)) { SystemTableUpdated = TRUE; } if (UpdateSystemTableConsole (L"ErrOut", &gEfiSimpleTextOutProtocolGuid, &gST->StandardErrorHandle, (VOID **) &gST->StdErr)) { SystemTableUpdated = TRUE; } if (SystemTableUpdated) { // // Update the CRC32 in the EFI System Table header // gST->Hdr.CRC32 = 0; gBS->CalculateCrc32 ( (UINT8 *) &gST->Hdr, gST->Hdr.HeaderSize, &gST->Hdr.CRC32 ); } return EFI_SUCCESS; }
/* * Test wydajnosci szyfrowania 1MB danych z zapisem i odczytem do pamieci SRAM */ void test_wydajnosci_sram() { PERF_RESET(PERFORMANCE_COUNTER_0_BASE ); PERF_START_MEASURING(PERFORMANCE_COUNTER_0_BASE); PERF_BEGIN(PERFORMANCE_COUNTER_0_BASE ,1); //uruchomienie 1 licznia przeprowadzenie_szyfrowania_sram(); PERF_END(PERFORMANCE_COUNTER_0_BASE ,1); //wylaczenie 1 licznika PERF_BEGIN(PERFORMANCE_COUNTER_0_BASE ,2); // uruchomienie 2 licznika przeprowadzenie_deszyfrowania_sram(); PERF_STOP_MEASURING(PERFORMANCE_COUNTER_0_BASE); //wylaczenie wszystkich licznikow perf_print_formatted_report((void* )PERFORMANCE_COUNTER_0_BASE, ALT_CPU_FREQ*2,2,"Test szyfr 3DES(1MB)","Test deszyfr 3DES(1MB)"); }
int main(void) { alt_putstr("Hello from Nios II!\n"); fill_arrays_with_random_values(); PERF_RESET(PERFORMANCE_COUNTER_0_BASE); PERF_START_MEASURING(PERFORMANCE_COUNTER_0_BASE); PERF_BEGIN(PERFORMANCE_COUNTER_0_BASE, 1); shuffle_in_c(array_for_c, ARRAY_SIZE); PERF_END(PERFORMANCE_COUNTER_0_BASE, 1); PERF_BEGIN(PERFORMANCE_COUNTER_0_BASE, 2); shuffle_with_custom_instruction(array_for_custom_instr, ARRAY_SIZE); PERF_END(PERFORMANCE_COUNTER_0_BASE, 2); PERF_BEGIN(PERFORMANCE_COUNTER_0_BASE, 3); shuffle_with_accelerator(array_for_accelerator, ARRAY_SIZE); PERF_END(PERFORMANCE_COUNTER_0_BASE, 3); PERF_STOP_MEASURING(PERFORMANCE_COUNTER_0_BASE); perf_print_formatted_report((void *) PERFORMANCE_COUNTER_0_BASE, ALT_CPU_FREQ, 3, "" "shuffle_with_c", "shuffle_with_custom_instruction", "shuffle_with_accelerator"); //verify_arrays(); #ifdef SMALL_ARRAY alt_putstr("Shuffle with C:\t\t\t"); print_array(array_for_c, ARRAY_SIZE); alt_putstr("Shuffle with custom instruction:\t"); print_array(array_for_custom_instr, ARRAY_SIZE); alt_putstr("Shuffle with accelerator:\t\t"); print_array(cache_bypass(array_for_accelerator), ARRAY_SIZE); #endif return 0; }
void process_image(ClFrame &in_frame) { PERF_START("image_processing"); if(os.is_set()) return; in_frame.set_origin(0, 0, 0); in_frame.set_region(m_width, m_height, 1); copy_yuv2rgb(in_frame, rgb_frame); //TODO: too slow rgb_frame.set_origin(0, 0, 0); rgb_frame.set_region(m_width, m_height, 1); process_frame(rgb_frame, tmp_frame, in_frame); PERF_END("image_processing"); };
EFI_STATUS LoadPeCoffSectionFromFv ( IN EFI_HANDLE FvHandle, IN EFI_GUID *NameGuid ) { EFI_STATUS Status; EFI_DEVICE_PATH_PROTOCOL *DevicePath; EFI_HANDLE ImageHandle; DevicePath = FvFileDevicePath (FvHandle, NameGuid); Status = gBS->LoadImage (TRUE, gImageHandle, DevicePath, NULL, 0, &ImageHandle); if (!EFI_ERROR (Status)) { PERF_END (NULL, "BDS", NULL, 0); Status = gBS->StartImage (ImageHandle, NULL, NULL); } return Status; }
void process_frame(ClFrame &in_frame, ClFrame &out_frame, ClFrame &orig_frame) { PERF_START("process_frame"); if(m_crop) { in_frame.set_origin(m_width/2, m_height/2, 0); in_frame.set_region( m_width/3, m_height/3, 1); out_frame.set_origin(m_width/2, m_height/2, 0); out_frame.set_region( m_width/3, m_height/3, 1); #ifndef _WITH_FRAMECPY //in_frame.vflip(); // no need to flip for frame memcpy #endif //_WITH_FRAMECPY } if(m_crop) { set_background_image(bg_img); } if(m_ocl_image) { if(copyimg.proc(in_frame, out_frame) == false) { return; } } if(m_motion) { if(transimg.proc(3, in_frame, out_frame) == false) { return; } } if(m_target.is_search()) { find_target(in_frame.get()); } if(m_ocl_image || m_motion) { display_frame(out_frame); } else { display_frame(in_frame); } PERF_END("process_frame"); }
/** Service routine for BdsInstance->Entry(). Devices are connected, the consoles are initialized, and the boot options are tried. @param This Protocol Instance structure. **/ VOID EFIAPI BdsEntry ( IN EFI_BDS_ARCH_PROTOCOL *This ) { LIST_ENTRY DriverOptionList; LIST_ENTRY BootOptionList; UINTN BootNextSize; CHAR16 *FirmwareVendor; EFI_STATUS Status; UINT16 BootTimeOut; UINTN Index; EDKII_VARIABLE_LOCK_PROTOCOL *VariableLock; // // Insert the performance probe // PERF_END (NULL, "DXE", NULL, 0); PERF_START (NULL, "BDS", NULL, 0); PERF_CODE ( BdsAllocateMemoryForPerformanceData (); );
int main() { int data_set[ARRAY_SIZE]; int i; printf("Generating random data...\n"); for (i = 0; i < ARRAY_SIZE; i++) { data_set[i] = rand() % 65536; } // For performance counter PERF_RESET(PERFORMANCE_COUNTER_0_BASE); // Start the performance counter PERF_START_MEASURING(performance_name); printf("Start sorting...\n"); // Start performance counter PERF_BEGIN(performance_name, 1); bubble_sort(data_set, ARRAY_SIZE); // Stop performance counter PERF_END(performance_name, 1); // Start the performance counter PERF_STOP_MEASURING(performance_name); printf("PC: %d\n", perf_get_section_time(performance_name, 1)); /* Event loop never exits. */ while (1); return 0; }
/** Service routine for BdsInstance->Entry(). Devices are connected, the consoles are initialized, and the boot options are tried. @param This Protocol Instance structure. **/ VOID EFIAPI BdsEntry ( IN EFI_BDS_ARCH_PROTOCOL *This ) { EFI_BOOT_MANAGER_LOAD_OPTION *LoadOptions; UINTN LoadOptionCount; CHAR16 *FirmwareVendor; EFI_EVENT HotkeyTriggered; UINT64 OsIndication; UINTN DataSize; EFI_STATUS Status; UINT32 BootOptionSupport; UINT16 BootTimeOut; EDKII_VARIABLE_LOCK_PROTOCOL *VariableLock; UINTN Index; EFI_BOOT_MANAGER_LOAD_OPTION BootOption; UINT16 *BootNext; CHAR16 BootNextVariableName[sizeof ("Boot####")]; EFI_BOOT_MANAGER_LOAD_OPTION BootManagerMenu; BOOLEAN BootFwUi; HotkeyTriggered = NULL; Status = EFI_SUCCESS; // // Insert the performance probe // PERF_END (NULL, "DXE", NULL, 0); PERF_START (NULL, "BDS", NULL, 0); DEBUG ((EFI_D_INFO, "[Bds] Entry...\n")); PERF_CODE ( BdsAllocateMemoryForPerformanceData (); );
int main(int argc, char **argv) { int frame_count = 70; TRACE("%s here\n", "bof"); char dev[64]; sprintf(dev, "%s", "/dev/video1"); if(argc > 1) sprintf(dev, "%s", argv[1]); MyVideo video; if(video.open(dev) == false) { TRACE("%s failed\n", "video open"); return false; } PERF_START("v4l"); video.run(frame_count); PERF_END("v4l"); video.close(); TRACE("%s here\n", "eof"); }
/** This function will be called when MRC is done. @param PeiServices General purpose services available to every PEIM. @param NotifyDescriptor Information about the notify event.. @param Ppi The notify context. @retval EFI_SUCCESS If the function completed successfully. **/ EFI_STATUS EFIAPI MemoryDiscoveredPpiNotifyCallback ( IN EFI_PEI_SERVICES **PeiServices, IN EFI_PEI_NOTIFY_DESCRIPTOR *NotifyDescriptor, IN VOID *Ppi ) { EFI_STATUS Status; EFI_BOOT_MODE BootMode; UINT64 MemoryLength; UINT64 MemoryLengthUc; UINT64 MaxMemoryLength; UINT64 MemOverflow; EFI_SMRAM_DESCRIPTOR *SmramDescriptor; UINTN NumSmramRegions; UINT64 EnlargedMemoryLength; UINT32 RmuMainBaseAddress; UINTN Index; MTRR_SETTINGS MtrrSetting; UINT32 RegData32; EFI_PHYSICAL_ADDRESS NewBuffer; UINT8 CpuAddressWidth; EFI_CPUID_REGISTER FeatureInfo; DEBUG ((EFI_D_INFO, "Platform PEIM Memory Callback\n")); NumSmramRegions = 0; SmramDescriptor = NULL; RmuMainBaseAddress = 0; PERF_START (NULL, "SetCache", NULL, 0); InfoPostInstallMemory (&RmuMainBaseAddress, &SmramDescriptor, &NumSmramRegions); ASSERT (SmramDescriptor != NULL); ASSERT (RmuMainBaseAddress != 0); MemoryLength = ((UINT64) RmuMainBaseAddress) + 0x10000; EnlargedMemoryLength = MemoryLength; if (NumSmramRegions > 0) { // // Find the TSEG // for (Index = 0; Index < NumSmramRegions; Index ++) { if ((SmramDescriptor[Index].PhysicalStart) == EnlargedMemoryLength) { if (SmramDescriptor[Index].RegionState & EFI_CACHEABLE) { // // Enlarge memory length to include TSEG size // EnlargedMemoryLength += (SmramDescriptor[Index].PhysicalSize); } } } } // // Check if a UC region is present // MaxMemoryLength = EnlargedMemoryLength; // Round up to nearest 256MB MemOverflow = (MemoryLength & 0x0fffffff); if (MemOverflow != 0) { MaxMemoryLength = MemoryLength + (0x10000000 - MemOverflow); } Status = PeiServicesGetBootMode (&BootMode); ASSERT_EFI_ERROR (Status); ZeroMem (&MtrrSetting, sizeof(MTRR_SETTINGS)); (**PeiServices).CopyMem ((VOID *)&MtrrSetting.Fixed,(VOID *)&mFixedMtrrTable, sizeof(MTRR_FIXED_SETTINGS) ); // // Cache the flash area to improve the boot performance in PEI phase // MtrrSetting.Variables.Mtrr[0].Base = (QUARK_BOOTROM_BASE_ADDRESS | CacheWriteBack); MtrrSetting.Variables.Mtrr[0].Mask = (((~(QUARK_BOOTROM_SIZE_BYTES - 1)) & MTRR_LIB_CACHE_VALID_ADDRESS) | MTRR_LIB_CACHE_MTRR_ENABLED); MtrrSetting.Variables.Mtrr[1].Base = CacheWriteBack; MtrrSetting.Variables.Mtrr[1].Mask = ((~(MaxMemoryLength - 1)) & MTRR_LIB_CACHE_VALID_ADDRESS) | MTRR_LIB_CACHE_MTRR_ENABLED; Index = 2; while (MaxMemoryLength != MemoryLength) { MemoryLengthUc = GetPowerOfTwo64 (MaxMemoryLength - MemoryLength); //Status = MtrrSetMemoryAttribute (MaxMemoryLength - MemoryLengthUc, MemoryLengthUc, CacheUncacheable); //ASSERT_EFI_ERROR (Status); MtrrSetting.Variables.Mtrr[Index].Base = ((MaxMemoryLength - MemoryLengthUc) & MTRR_LIB_CACHE_VALID_ADDRESS) | CacheUncacheable; MtrrSetting.Variables.Mtrr[Index].Mask= ((~(MemoryLengthUc - 1)) & MTRR_LIB_CACHE_VALID_ADDRESS) | MTRR_LIB_CACHE_MTRR_ENABLED; MaxMemoryLength -= MemoryLengthUc; Index++; } AsmInvd (); MtrrSetting.MtrrDefType = MTRR_LIB_CACHE_MTRR_ENABLED | MTRR_LIB_CACHE_FIXED_MTRR_ENABLED; MtrrSetAllMtrrs(&MtrrSetting); PERF_END (NULL, "SetCache", NULL, 0); // // Install PeiReset for PeiResetSystem service // Status = PeiServicesInstallPpi (&mPpiList[0]); ASSERT_EFI_ERROR (Status); // // Do QNC initialization after MRC // PeiQNCPostMemInit (); Status = PeiServicesInstallPpi (&mPpiStall[0]); ASSERT_EFI_ERROR (Status); // // Set E000/F000 Routing // RegData32 = QNCPortRead (QUARK_NC_HOST_BRIDGE_SB_PORT_ID, QNC_MSG_FSBIC_REG_HMISC); RegData32 |= (BIT2|BIT1); QNCPortWrite (QUARK_NC_HOST_BRIDGE_SB_PORT_ID, QNC_MSG_FSBIC_REG_HMISC, RegData32); if (BootMode == BOOT_IN_RECOVERY_MODE) { PeiServicesInstallFvInfoPpi ( NULL, (VOID *) (UINTN) PcdGet32 (PcdFlashFvRecovery2Base), PcdGet32 (PcdFlashFvRecovery2Size), NULL, NULL ); Status = PeimInitializeRecovery (PeiServices); ASSERT_EFI_ERROR (Status); } else if (BootMode == BOOT_ON_S3_RESUME) { return EFI_SUCCESS; } else { // // Allocate the memory so that it gets preserved into DXE // Status = PeiServicesAllocatePages ( EfiBootServicesData, EFI_SIZE_TO_PAGES (PcdGet32 (PcdFvSecurityHeaderSize) + PcdGet32 (PcdFlashFvMainSize)), &NewBuffer ); // // Copy the compressed main Firmware Volume to memory for faster processing later // CopyMem ((VOID *) (UINTN) NewBuffer, (VOID *) (UINTN) (PcdGet32 (PcdFlashFvMainBase) - PcdGet32 (PcdFvSecurityHeaderSize)), (PcdGet32 (PcdFvSecurityHeaderSize) +PcdGet32 (PcdFlashFvMainSize))); PeiServicesInstallFvInfoPpi ( NULL, (VOID *) (UINTN) (NewBuffer + PcdGet32 (PcdFvSecurityHeaderSize)), PcdGet32 (PcdFlashFvMainSize), NULL, NULL ); } // // Build flash HOB, it's going to be used by GCD and E820 building // Map full SPI flash decode range (regardless of smaller SPI flash parts installed) // BuildResourceDescriptorHob ( EFI_RESOURCE_FIRMWARE_DEVICE, (EFI_RESOURCE_ATTRIBUTE_PRESENT | EFI_RESOURCE_ATTRIBUTE_INITIALIZED | EFI_RESOURCE_ATTRIBUTE_UNCACHEABLE), (SIZE_4GB - SIZE_8MB), SIZE_8MB ); // // Create a CPU hand-off information // CpuAddressWidth = 32; AsmCpuid (EFI_CPUID_EXTENDED_FUNCTION, &FeatureInfo.RegEax, NULL, NULL, NULL); if (FeatureInfo.RegEax >= EFI_CPUID_VIR_PHY_ADDRESS_SIZE) { AsmCpuid (EFI_CPUID_VIR_PHY_ADDRESS_SIZE, &FeatureInfo.RegEax, NULL, NULL, NULL); CpuAddressWidth = (UINT8) (FeatureInfo.RegEax & 0xFF); } DEBUG ((EFI_D_INFO, "CpuAddressWidth: %d\n", CpuAddressWidth)); BuildCpuHob (CpuAddressWidth, 16); ASSERT_EFI_ERROR (Status); return Status; }
int main(int argc, char **argv) { //ClImage image("./checker.png"); ClImage image; if(image.open("./test.png") == false) return 1; ClImage results(image.width(), image.height()); size_t nSize = image.Size(); unsigned char *out_img = new unsigned char[nSize]; TRACE("image nSize = %zu\n", nSize); TRACE("image size input = (%zu, %zu)\n", image.width(), image.height()); PERF_START("ocl-copy"); ClHost host(CL_DEVICE_TYPE_GPU); ClDevice gpu(&host); ClBuffer iImage = gpu.image(CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, image); ClBuffer oImage = gpu.image(CL_MEM_WRITE_ONLY, NULL, image.width(), image.height()); ClBuffer sampler = gpu.sampler(CL_FALSE, CL_ADDRESS_CLAMP_TO_EDGE, CL_FILTER_NEAREST); if(gpu.open("./hello-img.cl", "copyimg") == false) return 1; gpu.arg(iImage); gpu.arg(oImage); gpu.arg(sampler); #define WORKDIM 2 #ifdef _WITH_DIRECT const size_t origin[3] = {0, 0, 0}; const size_t region[3] = {image.width(), image.height(), 1}; #else gpu.write(0, iImage, image.width(), image.height()); #endif //_WITH_DIRECT size_t dev_local = gpu.getWorkGroupInfo(); #ifdef _INTEL TRACE("before dev_local = %zu\n", dev_local); if(argc > 1) { TRACE("argv = %s\n", argv[1]); if(atoi(argv[1]) < 1) dev_local = 9; else dev_local = atoi(argv[1]); } TRACE("after dev_local = %zu\n", dev_local); #else TRACE("before dev_local = %d\n", dev_local); if(argc > 1) { TRACE("argv = %s\n", argv[1]); if(atoi(argv[1]) < 1) dev_local = (dev_local/2) - 1; else dev_local = atoi(argv[1]); } TRACE("after dev_local = %d\n", dev_local); #endif //_INTEL size_t local[WORKDIM] = {dev_local, dev_local}; size_t global[WORKDIM] = {gpu.roundup(local[0], image.width()), gpu.roundup(local[1], image.height())}; TRACE("run (%zu,%zu)\n", global[0], global[1]); gpu.run(WORKDIM, global, local); gpu.read(1, out_img, origin, region); //worker(ostr, nsize[0]); results.store("results.png", out_img); results.close(); image.close(); PERF_END("ocl-copy"); delete out_img; TRACE("%s\n", "eof"); return 0; }
/** This function is the main entry of the platform setup entry. The function will present the main menu of the system setup, this is the platform reference part and can be customize. @param TimeoutDefault The fault time out value before the system continue to boot. @param ConnectAllHappened The indicater to check if the connect all have already happened. **/ VOID PlatformBdsEnterFrontPage ( IN UINT16 TimeoutDefault, IN BOOLEAN ConnectAllHappened ) { EFI_STATUS Status; EFI_STATUS StatusHotkey; EFI_BOOT_LOGO_PROTOCOL *BootLogo; EFI_GRAPHICS_OUTPUT_PROTOCOL *GraphicsOutput; EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL *SimpleTextOut; UINTN BootTextColumn; UINTN BootTextRow; UINT64 OsIndication; UINTN DataSize; EFI_INPUT_KEY Key; GraphicsOutput = NULL; SimpleTextOut = NULL; PERF_START (NULL, "BdsTimeOut", "BDS", 0); // // Indicate if we need connect all in the platform setup // if (ConnectAllHappened) { gConnectAllHappened = TRUE; } if (!mModeInitialized) { // // After the console is ready, get current video resolution // and text mode before launching setup at first time. // Status = gBS->HandleProtocol ( gST->ConsoleOutHandle, &gEfiGraphicsOutputProtocolGuid, (VOID**)&GraphicsOutput ); if (EFI_ERROR (Status)) { GraphicsOutput = NULL; } Status = gBS->HandleProtocol ( gST->ConsoleOutHandle, &gEfiSimpleTextOutProtocolGuid, (VOID**)&SimpleTextOut ); if (EFI_ERROR (Status)) { SimpleTextOut = NULL; } if (GraphicsOutput != NULL) { // // Get current video resolution and text mode. // mBootHorizontalResolution = GraphicsOutput->Mode->Info->HorizontalResolution; mBootVerticalResolution = GraphicsOutput->Mode->Info->VerticalResolution; } if (SimpleTextOut != NULL) { Status = SimpleTextOut->QueryMode ( SimpleTextOut, SimpleTextOut->Mode->Mode, &BootTextColumn, &BootTextRow ); mBootTextModeColumn = (UINT32)BootTextColumn; mBootTextModeRow = (UINT32)BootTextRow; } // // Get user defined text mode for setup. // mSetupHorizontalResolution = PcdGet32 (PcdSetupVideoHorizontalResolution); mSetupVerticalResolution = PcdGet32 (PcdSetupVideoVerticalResolution); mSetupTextModeColumn = PcdGet32 (PcdSetupConOutColumn); mSetupTextModeRow = PcdGet32 (PcdSetupConOutRow); mModeInitialized = TRUE; } // // goto FrontPage directly when EFI_OS_INDICATIONS_BOOT_TO_FW_UI is set // OsIndication = 0; DataSize = sizeof(UINT64); Status = gRT->GetVariable ( L"OsIndications", &gEfiGlobalVariableGuid, NULL, &DataSize, &OsIndication ); // // goto FrontPage directly when EFI_OS_INDICATIONS_BOOT_TO_FW_UI is set. Skip HotkeyBoot // if (!EFI_ERROR(Status) && ((OsIndication & EFI_OS_INDICATIONS_BOOT_TO_FW_UI) != 0)) { // // Clear EFI_OS_INDICATIONS_BOOT_TO_FW_UI to acknowledge OS // OsIndication &= ~((UINT64)EFI_OS_INDICATIONS_BOOT_TO_FW_UI); Status = gRT->SetVariable ( L"OsIndications", &gEfiGlobalVariableGuid, EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_NON_VOLATILE, sizeof(UINT64), &OsIndication ); // // Changing the content without increasing its size with current variable implementation shouldn't fail. // ASSERT_EFI_ERROR (Status); // // Follow generic rule, Call ReadKeyStroke to connect ConIn before enter UI // if (PcdGetBool (PcdConInConnectOnDemand)) { gST->ConIn->ReadKeyStroke(gST->ConIn, &Key); } // // Ensure screen is clear when switch Console from Graphics mode to Text mode // gST->ConOut->EnableCursor (gST->ConOut, TRUE); gST->ConOut->ClearScreen (gST->ConOut); } else { HotkeyBoot (); if (TimeoutDefault != 0xffff) { Status = ShowProgress (TimeoutDefault); StatusHotkey = HotkeyBoot (); if (!FeaturePcdGet(PcdBootlogoOnlyEnable) || !EFI_ERROR(Status) || !EFI_ERROR(StatusHotkey)){ // // Ensure screen is clear when switch Console from Graphics mode to Text mode // Skip it in normal boot // gST->ConOut->EnableCursor (gST->ConOut, TRUE); gST->ConOut->ClearScreen (gST->ConOut); } if (EFI_ERROR (Status)) { // // Timeout or user press enter to continue // goto Exit; } } } // // Boot Logo is corrupted, report it using Boot Logo protocol. // Status = gBS->LocateProtocol (&gEfiBootLogoProtocolGuid, NULL, (VOID **) &BootLogo); if (!EFI_ERROR (Status) && (BootLogo != NULL)) { BootLogo->SetBootLogo (BootLogo, NULL, 0, 0, 0, 0); } // // Install BM HiiPackages. // Keep BootMaint HiiPackage, so that it can be covered by global setting. // InitBMPackage (); Status = EFI_SUCCESS; do { // // Set proper video resolution and text mode for setup // BdsSetConsoleMode (TRUE); InitializeFrontPage (FALSE); // // Update Front Page strings // UpdateFrontPageStrings (); gCallbackKey = 0; CallFrontPage (); // // If gCallbackKey is greater than 1 and less or equal to 5, // it will launch configuration utilities. // 2 = set language // 3 = boot manager // 4 = device manager // 5 = boot maintenance manager // if (gCallbackKey != 0) { REPORT_STATUS_CODE ( EFI_PROGRESS_CODE, (EFI_SOFTWARE_DXE_BS_DRIVER | EFI_SW_PC_USER_SETUP) ); } // // Based on the key that was set, we can determine what to do // switch (gCallbackKey) { // // The first 4 entries in the Front Page are to be GUARANTEED to remain constant so IHV's can // describe to their customers in documentation how to find their setup information (namely // under the device manager and specific buckets) // // These entries consist of the Continue, Select language, Boot Manager, and Device Manager // case FRONT_PAGE_KEY_CONTINUE: // // User hit continue // break; case FRONT_PAGE_KEY_LANGUAGE: // // User made a language setting change - display front page again // break; case FRONT_PAGE_KEY_BOOT_MANAGER: // // Remove the installed BootMaint HiiPackages when exit. // FreeBMPackage (); // // User chose to run the Boot Manager // CallBootManager (); // // Reinstall BootMaint HiiPackages after exiting from Boot Manager. // InitBMPackage (); break; case FRONT_PAGE_KEY_DEVICE_MANAGER: // // Display the Device Manager // do { CallDeviceManager (); } while (gCallbackKey == FRONT_PAGE_KEY_DEVICE_MANAGER); break; case FRONT_PAGE_KEY_BOOT_MAINTAIN: // // Display the Boot Maintenance Manager // BdsStartBootMaint (); break; } } while ((Status == EFI_SUCCESS) && (gCallbackKey != FRONT_PAGE_KEY_CONTINUE)); if (mLanguageString != NULL) { FreePool (mLanguageString); mLanguageString = NULL; } // //Will leave browser, check any reset required change is applied? if yes, reset system // SetupResetReminder (); // // Remove the installed BootMaint HiiPackages when exit. // FreeBMPackage (); Exit: // // Automatically load current entry // Note: The following lines of code only execute when Auto boot // takes affect // PERF_END (NULL, "BdsTimeOut", "BDS", 0); }
/** This function will be called when MRC is done. @param PeiServices General purpose services available to every PEIM. @param NotifyDescriptor Information about the notify event.. @param Ppi The notify context. @retval EFI_SUCCESS If the function completed successfully. **/ EFI_STATUS EFIAPI MemoryDiscoveredPpiNotifyCallback ( IN EFI_PEI_SERVICES **PeiServices, IN EFI_PEI_NOTIFY_DESCRIPTOR *NotifyDescriptor, IN VOID *Ppi ) { EFI_STATUS Status; EFI_BOOT_MODE BootMode; UINT64 MemoryLength; EFI_SMRAM_DESCRIPTOR *SmramDescriptor; UINTN NumSmramRegions; UINT32 RmuMainBaseAddress; UINT32 RegData32; UINT8 CpuAddressWidth; UINT32 RegEax; MTRR_SETTINGS MtrrSettings; EFI_PEI_READ_ONLY_VARIABLE2_PPI *VariableServices; UINT8 MorControl; UINTN DataSize; DEBUG ((EFI_D_INFO, "Platform PEIM Memory Callback\n")); NumSmramRegions = 0; SmramDescriptor = NULL; RmuMainBaseAddress = 0; PERF_START (NULL, "SetCache", NULL, 0); InfoPostInstallMemory (&RmuMainBaseAddress, &SmramDescriptor, &NumSmramRegions); ASSERT (SmramDescriptor != NULL); ASSERT (RmuMainBaseAddress != 0); MemoryLength = ((UINT64) RmuMainBaseAddress) + 0x10000; Status = PeiServicesGetBootMode (&BootMode); ASSERT_EFI_ERROR (Status); // // Get current MTRR settings // MtrrGetAllMtrrs (&MtrrSettings); // // Set all DRAM cachability to CacheWriteBack // Status = MtrrSetMemoryAttributeInMtrrSettings (&MtrrSettings, 0, MemoryLength, CacheWriteBack); ASSERT_EFI_ERROR (Status); // // RTC:28208 - System hang/crash when entering probe mode(ITP) when relocating SMBASE // Workaround to make default SMRAM UnCachable // Status = MtrrSetMemoryAttributeInMtrrSettings (&MtrrSettings, 0x30000, SIZE_64KB, CacheUncacheable); ASSERT_EFI_ERROR (Status); // // Set new MTRR settings // MtrrSetAllMtrrs (&MtrrSettings); PERF_END (NULL, "SetCache", NULL, 0); // // Get necessary PPI // Status = PeiServicesLocatePpi ( &gEfiPeiReadOnlyVariable2PpiGuid, // GUID 0, // INSTANCE NULL, // EFI_PEI_PPI_DESCRIPTOR (VOID **)&VariableServices // PPI ); ASSERT_EFI_ERROR (Status); // // Detect MOR request by the OS. // MorControl = 0; DataSize = sizeof (MorControl); Status = VariableServices->GetVariable ( VariableServices, MEMORY_OVERWRITE_REQUEST_VARIABLE_NAME, &gEfiMemoryOverwriteControlDataGuid, NULL, &DataSize, &MorControl ); // // If OS requested a memory overwrite perform it now for Embedded SRAM // if (MOR_CLEAR_MEMORY_VALUE (MorControl)) { DEBUG ((EFI_D_INFO, "Clear Embedded SRAM per MOR request.\n")); if (PcdGet32 (PcdESramMemorySize) > 0) { if (PcdGet32 (PcdEsramStage1Base) == 0) { // // ZeroMem() generates an ASSERT() if Buffer parameter is NULL. // Clear byte at 0 and start clear operation at address 1. // *(UINT8 *)(0) = 0; ZeroMem ((VOID *)1, (UINTN)PcdGet32 (PcdESramMemorySize) - 1); } else { ZeroMem ( (VOID *)(UINTN)PcdGet32 (PcdEsramStage1Base), (UINTN)PcdGet32 (PcdESramMemorySize) ); } } } // // Install PeiReset for PeiResetSystem service // Status = PeiServicesInstallPpi (&mPpiList[0]); ASSERT_EFI_ERROR (Status); // // Do QNC initialization after MRC // PeiQNCPostMemInit (); Status = PeiServicesInstallPpi (&mPpiStall[0]); ASSERT_EFI_ERROR (Status); // // Set E000/F000 Routing // RegData32 = QNCPortRead (QUARK_NC_HOST_BRIDGE_SB_PORT_ID, QNC_MSG_FSBIC_REG_HMISC); RegData32 |= (BIT2|BIT1); QNCPortWrite (QUARK_NC_HOST_BRIDGE_SB_PORT_ID, QNC_MSG_FSBIC_REG_HMISC, RegData32); if (BootMode == BOOT_IN_RECOVERY_MODE) { // Do nothing here. A generic RecoveryModule will handle it. } else if (BootMode == BOOT_ON_S3_RESUME) { return EFI_SUCCESS; } else { PeiServicesInstallFvInfoPpi ( NULL, (VOID *) (UINTN) PcdGet32 (PcdFlashFvMainBase), PcdGet32 (PcdFlashFvMainSize), NULL, NULL ); // // Publish the FVMAIN FV so the DXE Phase can dispatch drivers from this FV // and produce Load File Protocols for UEFI Applications in this FV. // BuildFvHob ( PcdGet32 (PcdFlashFvMainBase), PcdGet32 (PcdFlashFvMainSize) ); // // Publish the Payload FV so the DXE Phase can dispatch drivers from this FV // and produce Load File Protocols for UEFI Applications in this FV. // BuildFvHob ( PcdGet32 (PcdFlashFvPayloadBase), PcdGet32 (PcdFlashFvPayloadSize) ); } // // Build flash HOB, it's going to be used by GCD and E820 building // Map full SPI flash decode range (regardless of smaller SPI flash parts installed) // BuildResourceDescriptorHob ( EFI_RESOURCE_FIRMWARE_DEVICE, (EFI_RESOURCE_ATTRIBUTE_PRESENT | EFI_RESOURCE_ATTRIBUTE_INITIALIZED | EFI_RESOURCE_ATTRIBUTE_UNCACHEABLE), (SIZE_4GB - SIZE_8MB), SIZE_8MB ); // // Create a CPU hand-off information // CpuAddressWidth = 32; AsmCpuid (CPUID_EXTENDED_FUNCTION, &RegEax, NULL, NULL, NULL); if (RegEax >= CPUID_VIR_PHY_ADDRESS_SIZE) { AsmCpuid (CPUID_VIR_PHY_ADDRESS_SIZE, &RegEax, NULL, NULL, NULL); CpuAddressWidth = (UINT8) (RegEax & 0xFF); } DEBUG ((EFI_D_INFO, "CpuAddressWidth: %d\n", CpuAddressWidth)); BuildCpuHob (CpuAddressWidth, 16); ASSERT_EFI_ERROR (Status); return Status; }
/** Main entry point to DXE Core. @param HobStart Pointer to the beginning of the HOB List from PEI. @return This function should never return. **/ VOID EFIAPI DxeMain ( IN VOID *HobStart ) { EFI_STATUS Status; EFI_PHYSICAL_ADDRESS MemoryBaseAddress; UINT64 MemoryLength; PE_COFF_LOADER_IMAGE_CONTEXT ImageContext; UINTN Index; EFI_HOB_GUID_TYPE *GuidHob; EFI_VECTOR_HANDOFF_INFO *VectorInfoList; EFI_VECTOR_HANDOFF_INFO *VectorInfo; VOID *EntryPoint; // // Setup the default exception handlers // VectorInfoList = NULL; GuidHob = GetNextGuidHob (&gEfiVectorHandoffInfoPpiGuid, HobStart); if (GuidHob != NULL) { VectorInfoList = (EFI_VECTOR_HANDOFF_INFO *) (GET_GUID_HOB_DATA(GuidHob)); } Status = InitializeCpuExceptionHandlers (VectorInfoList); ASSERT_EFI_ERROR (Status); // // Initialize Debug Agent to support source level debug in DXE phase // InitializeDebugAgent (DEBUG_AGENT_INIT_DXE_CORE, HobStart, NULL); // // Initialize Memory Services // CoreInitializeMemoryServices (&HobStart, &MemoryBaseAddress, &MemoryLength); MemoryProfileInit (HobStart); // // Allocate the EFI System Table and EFI Runtime Service Table from EfiRuntimeServicesData // Use the templates to initialize the contents of the EFI System Table and EFI Runtime Services Table // gDxeCoreST = AllocateRuntimeCopyPool (sizeof (EFI_SYSTEM_TABLE), &mEfiSystemTableTemplate); ASSERT (gDxeCoreST != NULL); gDxeCoreRT = AllocateRuntimeCopyPool (sizeof (EFI_RUNTIME_SERVICES), &mEfiRuntimeServicesTableTemplate); ASSERT (gDxeCoreRT != NULL); gDxeCoreST->RuntimeServices = gDxeCoreRT; // // Start the Image Services. // Status = CoreInitializeImageServices (HobStart); ASSERT_EFI_ERROR (Status); // // Initialize the Global Coherency Domain Services // Status = CoreInitializeGcdServices (&HobStart, MemoryBaseAddress, MemoryLength); ASSERT_EFI_ERROR (Status); // // Call constructor for all libraries // ProcessLibraryConstructorList (gDxeCoreImageHandle, gDxeCoreST); PERF_END (NULL,"PEI", NULL, 0) ; PERF_START (NULL,"DXE", NULL, 0) ; // // Report DXE Core image information to the PE/COFF Extra Action Library // ZeroMem (&ImageContext, sizeof (ImageContext)); ImageContext.ImageAddress = (EFI_PHYSICAL_ADDRESS)(UINTN)gDxeCoreLoadedImage->ImageBase; ImageContext.PdbPointer = PeCoffLoaderGetPdbPointer ((VOID*)(UINTN)ImageContext.ImageAddress); ImageContext.SizeOfHeaders = PeCoffGetSizeOfHeaders ((VOID*)(UINTN)ImageContext.ImageAddress); Status = PeCoffLoaderGetEntryPoint ((VOID*)(UINTN)ImageContext.ImageAddress, &EntryPoint); if (Status == EFI_SUCCESS) { ImageContext.EntryPoint = (EFI_PHYSICAL_ADDRESS)(UINTN)EntryPoint; } ImageContext.Handle = (VOID *)(UINTN)gDxeCoreLoadedImage->ImageBase; ImageContext.ImageRead = PeCoffLoaderImageReadFromMemory; PeCoffLoaderRelocateImageExtraAction (&ImageContext); // // Install the DXE Services Table into the EFI System Tables's Configuration Table // Status = CoreInstallConfigurationTable (&gEfiDxeServicesTableGuid, gDxeCoreDS); ASSERT_EFI_ERROR (Status); // // Install the HOB List into the EFI System Tables's Configuration Table // Status = CoreInstallConfigurationTable (&gEfiHobListGuid, HobStart); ASSERT_EFI_ERROR (Status); // // Install Memory Type Information Table into the EFI System Tables's Configuration Table // Status = CoreInstallConfigurationTable (&gEfiMemoryTypeInformationGuid, &gMemoryTypeInformation); ASSERT_EFI_ERROR (Status); // // If Loading modules At fixed address feature is enabled, install Load moduels at fixed address // Configuration Table so that user could easily to retrieve the top address to load Dxe and PEI // Code and Tseg base to load SMM driver. // if (PcdGet64(PcdLoadModuleAtFixAddressEnable) != 0) { Status = CoreInstallConfigurationTable (&gLoadFixedAddressConfigurationTableGuid, &gLoadModuleAtFixAddressConfigurationTable); ASSERT_EFI_ERROR (Status); } // // Report Status Code here for DXE_ENTRY_POINT once it is available // REPORT_STATUS_CODE ( EFI_PROGRESS_CODE, (EFI_SOFTWARE_DXE_CORE | EFI_SW_DXE_CORE_PC_ENTRY_POINT) ); // // Create the aligned system table pointer structure that is used by external // debuggers to locate the system table... Also, install debug image info // configuration table. // CoreInitializeDebugImageInfoTable (); CoreNewDebugImageInfoEntry ( EFI_DEBUG_IMAGE_INFO_TYPE_NORMAL, gDxeCoreLoadedImage, gDxeCoreImageHandle ); DEBUG ((DEBUG_INFO | DEBUG_LOAD, "HOBLIST address in DXE = 0x%p\n", HobStart)); DEBUG_CODE_BEGIN (); EFI_PEI_HOB_POINTERS Hob; for (Hob.Raw = HobStart; !END_OF_HOB_LIST(Hob); Hob.Raw = GET_NEXT_HOB(Hob)) { if (GET_HOB_TYPE (Hob) == EFI_HOB_TYPE_MEMORY_ALLOCATION) { DEBUG ((DEBUG_INFO | DEBUG_LOAD, "Memory Allocation 0x%08x 0x%0lx - 0x%0lx\n", \ Hob.MemoryAllocation->AllocDescriptor.MemoryType, \ Hob.MemoryAllocation->AllocDescriptor.MemoryBaseAddress, \ Hob.MemoryAllocation->AllocDescriptor.MemoryBaseAddress + Hob.MemoryAllocation->AllocDescriptor.MemoryLength - 1)); } } for (Hob.Raw = HobStart; !END_OF_HOB_LIST(Hob); Hob.Raw = GET_NEXT_HOB(Hob)) { if (GET_HOB_TYPE (Hob) == EFI_HOB_TYPE_FV2) { DEBUG ((DEBUG_INFO | DEBUG_LOAD, "FV2 Hob 0x%0lx - 0x%0lx\n", Hob.FirmwareVolume2->BaseAddress, Hob.FirmwareVolume2->BaseAddress + Hob.FirmwareVolume2->Length - 1)); } else if (GET_HOB_TYPE (Hob) == EFI_HOB_TYPE_FV) { DEBUG ((DEBUG_INFO | DEBUG_LOAD, "FV Hob 0x%0lx - 0x%0lx\n", Hob.FirmwareVolume->BaseAddress, Hob.FirmwareVolume->BaseAddress + Hob.FirmwareVolume->Length - 1)); } } DEBUG_CODE_END (); // // Initialize the Event Services // Status = CoreInitializeEventServices (); ASSERT_EFI_ERROR (Status); MemoryProfileInstallProtocol (); CoreInitializePropertiesTable (); CoreInitializeMemoryAttributesTable (); // // Get persisted vector hand-off info from GUIDeed HOB again due to HobStart may be updated, // and install configuration table // GuidHob = GetNextGuidHob (&gEfiVectorHandoffInfoPpiGuid, HobStart); if (GuidHob != NULL) { VectorInfoList = (EFI_VECTOR_HANDOFF_INFO *) (GET_GUID_HOB_DATA(GuidHob)); VectorInfo = VectorInfoList; Index = 1; while (VectorInfo->Attribute != EFI_VECTOR_HANDOFF_LAST_ENTRY) { VectorInfo ++; Index ++; } VectorInfo = AllocateCopyPool (sizeof (EFI_VECTOR_HANDOFF_INFO) * Index, (VOID *) VectorInfoList); ASSERT (VectorInfo != NULL); Status = CoreInstallConfigurationTable (&gEfiVectorHandoffTableGuid, (VOID *) VectorInfo); ASSERT_EFI_ERROR (Status); } // // Get the Protocols that were passed in from PEI to DXE through GUIDed HOBs // // These Protocols are not architectural. This implementation is sharing code between // PEI and DXE in order to save FLASH space. These Protocols could also be implemented // as part of the DXE Core. However, that would also require the DXE Core to be ported // each time a different CPU is used, a different Decompression algorithm is used, or a // different Image type is used. By placing these Protocols in PEI, the DXE Core remains // generic, and only PEI and the Arch Protocols need to be ported from Platform to Platform, // and from CPU to CPU. // // // Publish the EFI, Tiano, and Custom Decompress protocols for use by other DXE components // Status = CoreInstallMultipleProtocolInterfaces ( &mDecompressHandle, &gEfiDecompressProtocolGuid, &gEfiDecompress, NULL ); ASSERT_EFI_ERROR (Status); // // Register for the GUIDs of the Architectural Protocols, so the rest of the // EFI Boot Services and EFI Runtime Services tables can be filled in. // Also register for the GUIDs of optional protocols. // CoreNotifyOnProtocolInstallation (); // // Produce Firmware Volume Protocols, one for each FV in the HOB list. // Status = FwVolBlockDriverInit (gDxeCoreImageHandle, gDxeCoreST); ASSERT_EFI_ERROR (Status); Status = FwVolDriverInit (gDxeCoreImageHandle, gDxeCoreST); ASSERT_EFI_ERROR (Status); // // Produce the Section Extraction Protocol // Status = InitializeSectionExtraction (gDxeCoreImageHandle, gDxeCoreST); ASSERT_EFI_ERROR (Status); // // Initialize the DXE Dispatcher // PERF_START (NULL,"CoreInitializeDispatcher", "DxeMain", 0) ; CoreInitializeDispatcher (); PERF_END (NULL,"CoreInitializeDispatcher", "DxeMain", 0) ; // // Invoke the DXE Dispatcher // PERF_START (NULL, "CoreDispatcher", "DxeMain", 0); CoreDispatcher (); PERF_END (NULL, "CoreDispatcher", "DxeMain", 0); // // Display Architectural protocols that were not loaded if this is DEBUG build // DEBUG_CODE_BEGIN (); CoreDisplayMissingArchProtocols (); DEBUG_CODE_END (); // // Display any drivers that were not dispatched because dependency expression // evaluated to false if this is a debug build // DEBUG_CODE_BEGIN (); CoreDisplayDiscoveredNotDispatched (); DEBUG_CODE_END (); // // Assert if the Architectural Protocols are not present. // Status = CoreAllEfiServicesAvailable (); if (EFI_ERROR(Status)) { // // Report Status code that some Architectural Protocols are not present. // REPORT_STATUS_CODE ( EFI_ERROR_CODE | EFI_ERROR_MAJOR, (EFI_SOFTWARE_DXE_CORE | EFI_SW_DXE_CORE_EC_NO_ARCH) ); } ASSERT_EFI_ERROR (Status); // // Report Status code before transfer control to BDS // REPORT_STATUS_CODE ( EFI_PROGRESS_CODE, (EFI_SOFTWARE_DXE_CORE | EFI_SW_DXE_CORE_PC_HANDOFF_TO_NEXT) ); // // Transfer control to the BDS Architectural Protocol // gBds->Entry (gBds); // // BDS should never return // ASSERT (FALSE); CpuDeadLoop (); UNREACHABLE (); }
/** Extraction handler tries to extract raw data from the input guided section. It also does authentication check for RSA 2048 SHA 256 signature in the input guided section. It first checks whether the input guid section is supported. If not, EFI_INVALID_PARAMETER will return. @param InputSection Buffer containing the input GUIDed section to be processed. @param OutputBuffer Buffer to contain the output raw data allocated by the caller. @param ScratchBuffer A pointer to a caller-allocated buffer for function internal use. @param AuthenticationStatus A pointer to a caller-allocated UINT32 that indicates the authentication status of the output buffer. @retval EFI_SUCCESS Section Data and Auth Status is extracted successfully. @retval EFI_INVALID_PARAMETER The GUID in InputSection does not match this instance guid. **/ EFI_STATUS EFIAPI Rsa2048Sha256GuidedSectionHandler ( IN CONST VOID *InputSection, OUT VOID **OutputBuffer, IN VOID *ScratchBuffer, OPTIONAL OUT UINT32 *AuthenticationStatus ) { EFI_STATUS Status; UINT32 OutputBufferSize; VOID *DummyInterface; EFI_CERT_BLOCK_RSA_2048_SHA256 *CertBlockRsa2048Sha256; BOOLEAN CryptoStatus; UINT8 Digest[SHA256_DIGEST_SIZE]; UINT8 *PublicKey; UINTN PublicKeyBufferSize; VOID *HashContext; VOID *Rsa; HashContext = NULL; Rsa = NULL; if (IS_SECTION2 (InputSection)) { // // Check whether the input guid section is recognized. // if (!CompareGuid ( &gEfiCertTypeRsa2048Sha256Guid, &(((EFI_GUID_DEFINED_SECTION2 *)InputSection)->SectionDefinitionGuid))) { return EFI_INVALID_PARAMETER; } // // Get the RSA 2048 SHA 256 information. // CertBlockRsa2048Sha256 = &((RSA_2048_SHA_256_SECTION2_HEADER *) InputSection)->CertBlockRsa2048Sha256; OutputBufferSize = SECTION2_SIZE (InputSection) - sizeof (RSA_2048_SHA_256_SECTION2_HEADER); if ((((EFI_GUID_DEFINED_SECTION *)InputSection)->Attributes & EFI_GUIDED_SECTION_PROCESSING_REQUIRED) != 0) { PERF_START (NULL, "RsaCopy", "DXE", 0); CopyMem (*OutputBuffer, (UINT8 *)InputSection + sizeof (RSA_2048_SHA_256_SECTION2_HEADER), OutputBufferSize); PERF_END (NULL, "RsaCopy", "DXE", 0); } else { *OutputBuffer = (UINT8 *)InputSection + sizeof (RSA_2048_SHA_256_SECTION2_HEADER); } // // Implicitly RSA 2048 SHA 256 GUIDed section should have STATUS_VALID bit set // ASSERT ((((EFI_GUID_DEFINED_SECTION2 *)InputSection)->Attributes & EFI_GUIDED_SECTION_AUTH_STATUS_VALID) != 0); *AuthenticationStatus = EFI_AUTH_STATUS_IMAGE_SIGNED; } else { // // Check whether the input guid section is recognized. // if (!CompareGuid ( &gEfiCertTypeRsa2048Sha256Guid, &(((EFI_GUID_DEFINED_SECTION *)InputSection)->SectionDefinitionGuid))) { return EFI_INVALID_PARAMETER; } // // Get the RSA 2048 SHA 256 information. // CertBlockRsa2048Sha256 = &((RSA_2048_SHA_256_SECTION_HEADER *)InputSection)->CertBlockRsa2048Sha256; OutputBufferSize = SECTION_SIZE (InputSection) - sizeof (RSA_2048_SHA_256_SECTION_HEADER); if ((((EFI_GUID_DEFINED_SECTION *)InputSection)->Attributes & EFI_GUIDED_SECTION_PROCESSING_REQUIRED) != 0) { PERF_START (NULL, "RsaCopy", "DXE", 0); CopyMem (*OutputBuffer, (UINT8 *)InputSection + sizeof (RSA_2048_SHA_256_SECTION_HEADER), OutputBufferSize); PERF_END (NULL, "RsaCopy", "DXE", 0); } else { *OutputBuffer = (UINT8 *)InputSection + sizeof (RSA_2048_SHA_256_SECTION_HEADER); } // // Implicitly RSA 2048 SHA 256 GUIDed section should have STATUS_VALID bit set // ASSERT ((((EFI_GUID_DEFINED_SECTION *) InputSection)->Attributes & EFI_GUIDED_SECTION_AUTH_STATUS_VALID) != 0); *AuthenticationStatus = EFI_AUTH_STATUS_IMAGE_SIGNED; } // // Check whether there exists EFI_SECURITY_POLICY_PROTOCOL_GUID. // Status = gBS->LocateProtocol (&gEfiSecurityPolicyProtocolGuid, NULL, &DummyInterface); if (!EFI_ERROR (Status)) { // // If SecurityPolicy Protocol exist, AUTH platform override bit is set. // *AuthenticationStatus |= EFI_AUTH_STATUS_PLATFORM_OVERRIDE; return EFI_SUCCESS; } // // All paths from here return EFI_SUCESS and result is returned in AuthenticationStatus // Status = EFI_SUCCESS; // // Fail if the HashType is not SHA 256 // if (!CompareGuid (&gEfiHashAlgorithmSha256Guid, &CertBlockRsa2048Sha256->HashType)) { DEBUG ((DEBUG_ERROR, "DxeRsa2048Sha256: HASH type of section is not supported\n")); *AuthenticationStatus |= EFI_AUTH_STATUS_TEST_FAILED; goto Done; } // // Allocate hash context buffer required for SHA 256 // HashContext = AllocatePool (Sha256GetContextSize ()); if (HashContext == NULL) { DEBUG ((DEBUG_ERROR, "DxeRsa2048Sha256: Can not allocate hash context\n")); *AuthenticationStatus |= EFI_AUTH_STATUS_TEST_FAILED; goto Done; } // // Hash public key from data payload with SHA256. // ZeroMem (Digest, SHA256_DIGEST_SIZE); CryptoStatus = Sha256Init (HashContext); if (!CryptoStatus) { DEBUG ((DEBUG_ERROR, "DxeRsa2048Sha256: Sha256Init() failed\n")); *AuthenticationStatus |= EFI_AUTH_STATUS_TEST_FAILED; goto Done; } CryptoStatus = Sha256Update (HashContext, &CertBlockRsa2048Sha256->PublicKey, sizeof(CertBlockRsa2048Sha256->PublicKey)); if (!CryptoStatus) { DEBUG ((DEBUG_ERROR, "DxeRsa2048Sha256: Sha256Update() failed\n")); *AuthenticationStatus |= EFI_AUTH_STATUS_TEST_FAILED; goto Done; } CryptoStatus = Sha256Final (HashContext, Digest); if (!CryptoStatus) { DEBUG ((DEBUG_ERROR, "DxeRsa2048Sha256: Sha256Final() failed\n")); *AuthenticationStatus |= EFI_AUTH_STATUS_TEST_FAILED; goto Done; } // // Fail if the PublicKey is not one of the public keys in PcdRsa2048Sha256PublicKeyBuffer // PublicKey = (UINT8 *)PcdGetPtr (PcdRsa2048Sha256PublicKeyBuffer); DEBUG ((DEBUG_VERBOSE, "DxePcdRsa2048Sha256: PublicKeyBuffer = %p\n", PublicKey)); ASSERT (PublicKey != NULL); DEBUG ((DEBUG_VERBOSE, "DxePcdRsa2048Sha256: PublicKeyBuffer Token = %08x\n", PcdToken (PcdRsa2048Sha256PublicKeyBuffer))); PublicKeyBufferSize = LibPcdGetExSize (&gEfiSecurityPkgTokenSpaceGuid, PcdToken (PcdRsa2048Sha256PublicKeyBuffer)); DEBUG ((DEBUG_VERBOSE, "DxePcdRsa2048Sha256: PublicKeyBuffer Size = %08x\n", PublicKeyBufferSize)); ASSERT ((PublicKeyBufferSize % SHA256_DIGEST_SIZE) == 0); CryptoStatus = FALSE; while (PublicKeyBufferSize != 0) { if (CompareMem (Digest, PublicKey, SHA256_DIGEST_SIZE) == 0) { CryptoStatus = TRUE; break; } PublicKey = PublicKey + SHA256_DIGEST_SIZE; PublicKeyBufferSize = PublicKeyBufferSize - SHA256_DIGEST_SIZE; } if (!CryptoStatus) { DEBUG ((DEBUG_ERROR, "DxeRsa2048Sha256: Public key in section is not supported\n")); *AuthenticationStatus |= EFI_AUTH_STATUS_TEST_FAILED; goto Done; } // // Generate & Initialize RSA Context. // Rsa = RsaNew (); if (Rsa == NULL) { DEBUG ((DEBUG_ERROR, "DxeRsa2048Sha256: RsaNew() failed\n")); *AuthenticationStatus |= EFI_AUTH_STATUS_TEST_FAILED; goto Done; } // // Set RSA Key Components. // NOTE: Only N and E are needed to be set as RSA public key for signature verification. // CryptoStatus = RsaSetKey (Rsa, RsaKeyN, CertBlockRsa2048Sha256->PublicKey, sizeof(CertBlockRsa2048Sha256->PublicKey)); if (!CryptoStatus) { DEBUG ((DEBUG_ERROR, "DxeRsa2048Sha256: RsaSetKey(RsaKeyN) failed\n")); *AuthenticationStatus |= EFI_AUTH_STATUS_TEST_FAILED; goto Done; } CryptoStatus = RsaSetKey (Rsa, RsaKeyE, mRsaE, sizeof (mRsaE)); if (!CryptoStatus) { DEBUG ((DEBUG_ERROR, "DxeRsa2048Sha256: RsaSetKey(RsaKeyE) failed\n")); *AuthenticationStatus |= EFI_AUTH_STATUS_TEST_FAILED; goto Done; } // // Hash data payload with SHA256. // ZeroMem (Digest, SHA256_DIGEST_SIZE); CryptoStatus = Sha256Init (HashContext); if (!CryptoStatus) { DEBUG ((DEBUG_ERROR, "DxeRsa2048Sha256: Sha256Init() failed\n")); *AuthenticationStatus |= EFI_AUTH_STATUS_TEST_FAILED; goto Done; } PERF_START (NULL, "RsaShaData", "DXE", 0); CryptoStatus = Sha256Update (HashContext, *OutputBuffer, OutputBufferSize); PERF_END (NULL, "RsaShaData", "DXE", 0); if (!CryptoStatus) { DEBUG ((DEBUG_ERROR, "DxeRsa2048Sha256: Sha256Update() failed\n")); *AuthenticationStatus |= EFI_AUTH_STATUS_TEST_FAILED; goto Done; } CryptoStatus = Sha256Final (HashContext, Digest); if (!CryptoStatus) { DEBUG ((DEBUG_ERROR, "DxeRsa2048Sha256: Sha256Final() failed\n")); *AuthenticationStatus |= EFI_AUTH_STATUS_TEST_FAILED; goto Done; } // // Verify the RSA 2048 SHA 256 signature. // PERF_START (NULL, "RsaVerify", "DXE", 0); CryptoStatus = RsaPkcs1Verify ( Rsa, Digest, SHA256_DIGEST_SIZE, CertBlockRsa2048Sha256->Signature, sizeof (CertBlockRsa2048Sha256->Signature) ); PERF_END (NULL, "RsaVerify", "DXE", 0); if (!CryptoStatus) { // // If RSA 2048 SHA 256 signature verification fails, AUTH tested failed bit is set. // DEBUG ((DEBUG_ERROR, "DxeRsa2048Sha256: RsaPkcs1Verify() failed\n")); *AuthenticationStatus |= EFI_AUTH_STATUS_TEST_FAILED; } Done: // // Free allocated resources used to perform RSA 2048 SHA 256 signature verification // if (Rsa != NULL) { RsaFree (Rsa); } if (HashContext != NULL) { FreePool (HashContext); } DEBUG ((DEBUG_VERBOSE, "DxeRsa2048Sha256: Status = %r AuthenticationStatus = %08x\n", Status, *AuthenticationStatus)); return Status; }
int main() { int class; //da trasformate in alt_u8 o 16 in base alle dimensioni int vote; int end_class; alt_u16 command[256]; alt_u16 ack_cmd[3]; alt_u32 tr_size; alt_u32 tr_size_count; alt_u8 q_size; alt_u32 n_packet; alt_u32 tr_val; alt_u64 addr; //verificare dimensione alt_u64 q_addr; alt_u32 q_val; alt_u32 i = 0; alt_u32 k = 0; alt_u8 k_val; alt_u16 n_dim; alt_u16 n_load; alt_u16 n_load_count; alt_u16 n_cell; alt_u16 n_cell_last; alt_u64 count = 0; alt_u16 cache_q_addr = 0; alt_dma_txchan txchan; alt_dma_rxchan rxchan; alt_u32 memptr = 0; alt_u8 empty0 = 0; alt_u8 empty1 = 0; alt_u8 overflow = 0; unsigned char ledvalue = 1; void* tx_data; /* pointer to data to send */ void* rx_buffer; /* pointer to rx buffer */ while(1) { command[0] = 0; recv_short(command, 8); //send back the ACK ack_cmd[0] = ACK; ack_cmd[1] = ACK; ack_cmd[2] = command[3]; send_short(ack_cmd, 3); if(command[0] == FLUSH_COMM) { tr_size = 0; tr_size = command[1]; tr_size = tr_size<<16; tr_size = tr_size | command[2]; n_packet = 0; n_packet = command[3]; n_packet = n_packet<<16; n_packet = n_packet | command[4]; cache_q_addr = command[5]; addr = 0; tr_size_count = 0; for(i = 0; i < n_packet;i++) { recv_short(command, 256); send_short(command, 256); for(k = 0;k < 127; k++) { if(tr_size_count < tr_size) { tr_size_count = tr_size_count + 1; tr_val = 0; tr_val = command[2+2*k]; tr_val = tr_val<<16; tr_val = tr_val | command[3+2*k]; IOWR_32DIRECT(SDRAM_CONTROLLER_BASE,addr,tr_val); addr = addr + 0x04; } } } ack_cmd[0] = ACK; ack_cmd[1] = ACK; ack_cmd[2] = command[3]; send_short(ack_cmd, 3); } else if(command[0] == CLASS_CMD) { q_size = 0; q_size = command[1]; q_size = q_size<<16; q_size = q_size | command[2]; n_dim = 0; n_dim = command[3]; k_val = 0; k_val = command[4]; n_load = 0; n_load = command[5]; n_cell = 0; n_cell = command[6]; n_cell_last = 0; n_cell_last = command[7]; for(i = 0; i < 1;i++) { recv_short(command, 256); send_short(command, 256); } q_addr = SDRAM_Q_ADDR_BASE; for(i = 0;i < q_size; i++) { q_val = 0; q_val = command[2*i]; q_val = q_val<<16; q_val = q_val | command[1+2*i]; IOWR_32DIRECT(SDRAM_CONTROLLER_BASE, q_addr, q_val); q_addr = q_addr + 0x04; } // set the number of dimension MAX = 256 IOWR_32DIRECT(KNNCLASSCORE_BASE, STARTCLREG,0x00000000); IOWR_32DIRECT(BASEQADDR_0_BASE,0x00,cache_q_addr); IOWR_32DIRECT(SKIPADDRREG_0_BASE,0x00,(q_size+1)*4); IOWR_32DIRECT(NDIMREG_BASE,0x00,n_dim); // number of training val in each mem IOWR_32DIRECT(NTRREG_0_BASE,0x00,3); IOWR_32DIRECT(NTRREG_1_BASE,0x00,3); // k val IOWR_32DIRECT(KNNCLASSCORE_BASE,KVALREG,k_val); IOWR_32DIRECT(ENDTSETREG_0_BASE,0x00,0); IOWR_32DIRECT(ENDTSETREG_1_BASE,0x00,0); load_q_cache1 = 0; load_q_cache0 = 0; IOWR_32DIRECT(FULLREG_0_BASE,0x00,0x00000000); IOWR_32DIRECT(FULLREG_1_BASE,0x00,0x00000000); PERF_RESET(PERFORMANCE_COUNTER_0_BASE); PERF_START_MEASURING(PERFORMANCE_COUNTER_0_BASE); PERF_BEGIN(PERFORMANCE_COUNTER_0_BASE,1); IOWR_32DIRECT(KNNCLASSCORE_BASE, STARTCLREG,0x00000001); txchan = alt_dma_txchan_open("/dev/dma"); rxchan = alt_dma_rxchan_open("/dev/dma"); alt_dma_txchan_ioctl(txchan, ALT_DMA_SET_MODE_32, NULL); alt_dma_rxchan_ioctl(rxchan, ALT_DMA_SET_MODE_32, NULL); txrx_doneCache0 = 0; tx_data = (void*)(SDRAM_CONTROLLER_BASE+SDRAM_Q_ADDR_BASE); /* pointer to data to send */ rx_buffer = (void*)(DMA_WRITE_MASTER_CACHE_0_BASE+cache_q_addr);//CUSTOM_RAM_0_BASE alt_dma_txchan_send (txchan,tx_data,q_size*4,NULL,NULL); alt_dma_rxchan_prepare (rxchan,rx_buffer,q_size*4, txrxDoneCache0,NULL); alt_dma_txchan_ioctl(txchan, ALT_DMA_SET_MODE_32, NULL); alt_dma_rxchan_ioctl(rxchan, ALT_DMA_SET_MODE_32, NULL); txrx_doneCache1 = 0; tx_data = (void*)(SDRAM_CONTROLLER_BASE+SDRAM_Q_ADDR_BASE); /* pointer to data to send */ rx_buffer = (void*)(DMA_WRITE_MASTER_CACHE_1_BASE+cache_q_addr);//CUSTOM_RAM_0_BASE alt_dma_txchan_send (txchan,tx_data,q_size*4,NULL,NULL); alt_dma_rxchan_prepare (rxchan,rx_buffer,q_size*4, txrxDoneCache1,NULL); IOWR_ALTERA_AVALON_PIO_DATA(PIO_0_BASE, ledvalue); ledvalue++; n_load_count = 0; memptr = 0; IOWR_32DIRECT(KNNCLASSCORE_BASE,STARTCLREG,1); //modificato qui //fill cache 0 empty0 = IORD_32DIRECT(EMPTYREG_0_BASE,0x00); empty1 = IORD_32DIRECT(EMPTYREG_1_BASE,0x00); while(txrx_doneCache1==0 || txrx_doneCache1==0); while(n_load_count < n_load) { if(empty0 && (n_load_count < n_load) && txrx_doneCache0 ) // && !endmem0 { IOWR_32DIRECT(FULLREG_0_BASE,0x00,0x00000000); IOWR_32DIRECT(ENDTSETREG_0_BASE,0x00,0); if(n_load_count == n_load-1) IOWR_32DIRECT(NTRREG_0_BASE, 0x00,n_cell_last/(4*(q_size+1))); else IOWR_32DIRECT(NTRREG_0_BASE, 0x00,n_cell/(4*(q_size+1))); txrx_doneCache0 = 0; alt_dma_txchan_ioctl(txchan, ALT_DMA_SET_MODE_32, NULL); alt_dma_rxchan_ioctl(rxchan, ALT_DMA_SET_MODE_32, NULL); tx_data = (void*)(SDRAM_CONTROLLER_BASE+memptr); /* pointer to data to send */ rx_buffer = (void*)(DMA_WRITE_MASTER_CACHE_0_BASE);//CUSTOM_RAM_0_BASE if(n_load_count == n_load-1) { alt_dma_txchan_send (txchan,tx_data,n_cell_last,NULL,NULL); alt_dma_rxchan_prepare (rxchan,rx_buffer,n_cell_last, txrxDoneCache0,NULL); } else { alt_dma_txchan_send (txchan,tx_data,n_cell,NULL,NULL); alt_dma_rxchan_prepare (rxchan,rx_buffer,n_cell, txrxDoneCache0,NULL); } memptr = memptr + n_cell; n_load_count++; IOWR_32DIRECT(FULLREG_0_BASE,0x00,0x00000001); } if(empty1 && (n_load_count< n_load) && txrx_doneCache1) // && !endmem0 { //fill cache 1 IOWR_32DIRECT(FULLREG_1_BASE,0x00,0x00000000); IOWR_32DIRECT(ENDTSETREG_1_BASE,0x00,0); //era 1 if(n_load_count == n_load-1) IOWR_32DIRECT(NTRREG_1_BASE, 0x00,n_cell_last/(4*(q_size+1))); else IOWR_32DIRECT(NTRREG_1_BASE, 0x00,n_cell/(4*(q_size+1))); alt_dma_txchan_ioctl(txchan, ALT_DMA_SET_MODE_32, NULL); alt_dma_rxchan_ioctl(rxchan, ALT_DMA_SET_MODE_32, NULL); txrx_doneCache1 = 0; tx_data = (void*)(SDRAM_CONTROLLER_BASE+memptr); /* pointer to data to send */ rx_buffer = (void*)(DMA_WRITE_MASTER_CACHE_1_BASE);//CUSTOM_RAM_0_BASE if(n_load_count == n_load-1) { alt_dma_txchan_send (txchan,tx_data,n_cell_last,NULL,NULL); alt_dma_rxchan_prepare (rxchan,rx_buffer,n_cell_last, txrxDoneCache1,NULL); } else { alt_dma_txchan_send (txchan,tx_data,n_cell,NULL,NULL); alt_dma_rxchan_prepare (rxchan,rx_buffer,n_cell, txrxDoneCache1,NULL); } memptr = memptr + n_cell; n_load_count++; IOWR_32DIRECT(FULLREG_1_BASE,0x00,0x00000001); } empty0 = IORD_32DIRECT(EMPTYREG_0_BASE,0x00); empty1 = IORD_32DIRECT(EMPTYREG_1_BASE,0x00); } while(txrx_doneCache1==0 || txrx_doneCache1==0); //while(empty0==0 || empty1==0); IOWR_32DIRECT(ENDTSETREG_0_BASE,0x00,1); //era 1 IOWR_32DIRECT(ENDTSETREG_1_BASE,0x00,1); //era 1 end_class = 0; while (!end_class) end_class = IORD_32DIRECT(KNNCLASSCORE_BASE,ENDCLASSREG); alt_dma_txchan_close(txchan); alt_dma_rxchan_close(rxchan); PERF_END(PERFORMANCE_COUNTER_0_BASE,1); class = IORD_32DIRECT(KNNCLASSCORE_BASE,CLREG); vote = IORD_32DIRECT(KNNCLASSCORE_BASE,NVOTREG); count = perf_get_section_time(PERFORMANCE_COUNTER_0_BASE,1); overflow = IORD_32DIRECT(KNNCLASSCORE_BASE,OVERFLOWREG); command[0] = class; command[1] = vote; command[2] = count; count = count>>16; command[3] = count; count = count>>16; command[4] = count; count = count>>16; command[5] = count; command[6] = overflow; addr = 0; for(i=0; i < 16; i++) { command[7+i] = IORD_32DIRECT(KNNCLASSCORE_BASE,addr); addr = addr + 0x04; } send_short(command, 23); } }
/** This function will connect all the console devices base on the console device variable ConIn, ConOut and ErrOut. @retval EFI_DEVICE_ERROR All the consoles were not connected due to an error. @retval EFI_SUCCESS Success connect any one instance of the console device path base on the variable ConVarName. **/ EFI_STATUS EFIAPI EfiBootManagerConnectAllDefaultConsoles ( VOID ) { EFI_STATUS Status; BOOLEAN OneConnected; BOOLEAN SystemTableUpdated; OneConnected = FALSE; Status = EfiBootManagerConnectConsoleVariable (ConOut); if (!EFI_ERROR (Status)) { OneConnected = TRUE; } PERF_START (NULL, "ConOutReady", "BDS", 1); PERF_END (NULL, "ConOutReady", "BDS", 0); Status = EfiBootManagerConnectConsoleVariable (ConIn); if (!EFI_ERROR (Status)) { OneConnected = TRUE; } PERF_START (NULL, "ConInReady", "BDS", 1); PERF_END (NULL, "ConInReady", "BDS", 0); Status = EfiBootManagerConnectConsoleVariable (ErrOut); if (!EFI_ERROR (Status)) { OneConnected = TRUE; } PERF_START (NULL, "ErrOutReady", "BDS", 1); PERF_END (NULL, "ErrOutReady", "BDS", 0); SystemTableUpdated = FALSE; // // Fill console handles in System Table if no console device assignd. // if (BmUpdateSystemTableConsole (L"ConIn", &gEfiSimpleTextInProtocolGuid, &gST->ConsoleInHandle, (VOID **) &gST->ConIn)) { SystemTableUpdated = TRUE; } if (BmUpdateSystemTableConsole (L"ConOut", &gEfiSimpleTextOutProtocolGuid, &gST->ConsoleOutHandle, (VOID **) &gST->ConOut)) { SystemTableUpdated = TRUE; } if (BmUpdateSystemTableConsole (L"ErrOut", &gEfiSimpleTextOutProtocolGuid, &gST->StandardErrorHandle, (VOID **) &gST->StdErr)) { SystemTableUpdated = TRUE; } if (SystemTableUpdated) { // // Update the CRC32 in the EFI System Table header // gST->Hdr.CRC32 = 0; gBS->CalculateCrc32 ( (UINT8 *) &gST->Hdr, gST->Hdr.HeaderSize, &gST->Hdr.CRC32 ); } return OneConnected ? EFI_SUCCESS : EFI_DEVICE_ERROR; }
/** This function will connect console device base on the console device variable ConIn, ConOut and ErrOut. @retval EFI_SUCCESS At least one of the ConIn and ConOut device have been connected success. @retval EFI_STATUS Return the status of BdsLibConnectConsoleVariable (). **/ EFI_STATUS EFIAPI BdsLibConnectAllDefaultConsoles ( VOID ) { EFI_STATUS Status; BOOLEAN SystemTableUpdated; // // Connect all default console variables // // // It seems impossible not to have any ConOut device on platform, // so we check the status here. // Status = BdsLibConnectConsoleVariable (L"ConOut"); if (EFI_ERROR (Status)) { return Status; } // // Insert the performance probe for Console Out // PERF_START (NULL, "ConOut", "BDS", 1); PERF_END (NULL, "ConOut", "BDS", 0); // // Because possibly the platform is legacy free, in such case, // ConIn devices (Serial Port and PS2 Keyboard ) does not exist, // so we need not check the status. // BdsLibConnectConsoleVariable (L"ConIn"); // // The _ModuleEntryPoint err out var is legal. // BdsLibConnectConsoleVariable (L"ErrOut"); SystemTableUpdated = FALSE; // // Fill console handles in System Table if no console device assignd. // if (UpdateSystemTableConsole (L"ConIn", &gEfiSimpleTextInProtocolGuid, &gST->ConsoleInHandle, (VOID **) &gST->ConIn)) { SystemTableUpdated = TRUE; } if (UpdateSystemTableConsole (L"ConOut", &gEfiSimpleTextOutProtocolGuid, &gST->ConsoleOutHandle, (VOID **) &gST->ConOut)) { SystemTableUpdated = TRUE; } if (UpdateSystemTableConsole (L"ErrOut", &gEfiSimpleTextOutProtocolGuid, &gST->StandardErrorHandle, (VOID **) &gST->StdErr)) { SystemTableUpdated = TRUE; } if (SystemTableUpdated) { // // Update the CRC32 in the EFI System Table header // gST->Hdr.CRC32 = 0; gBS->CalculateCrc32 ( (UINT8 *) &gST->Hdr, gST->Hdr.HeaderSize, &gST->Hdr.CRC32 ); } // // If any component set PcdTestKeyUsed to TRUE because use of a test key // was detected, then display a warning message on the debug log and the console // if (PcdGetBool (PcdTestKeyUsed) == TRUE) { DEBUG ((DEBUG_ERROR, "**********************************\n")); DEBUG ((DEBUG_ERROR, "** WARNING: Test Key is used. **\n")); DEBUG ((DEBUG_ERROR, "**********************************\n")); Print (L"** WARNING: Test Key is used. **\n"); } return EFI_SUCCESS; }
/** This function uses policy data from the platform to determine what operating system or system utility should be loaded and invoked. This function call also optionally make the use of user input to determine the operating system or system utility to be loaded and invoked. When the DXE Core has dispatched all the drivers on the dispatch queue, this function is called. This function will attempt to connect the boot devices required to load and invoke the selected operating system or system utility. During this process, additional firmware volumes may be discovered that may contain addition DXE drivers that can be dispatched by the DXE Core. If a boot device cannot be fully connected, this function calls the DXE Service Dispatch() to allow the DXE drivers from any newly discovered firmware volumes to be dispatched. Then the boot device connection can be attempted again. If the same boot device connection operation fails twice in a row, then that boot device has failed, and should be skipped. This function should never return. @param This The EFI_BDS_ARCH_PROTOCOL instance. @return None. **/ VOID EFIAPI BdsEntry ( IN EFI_BDS_ARCH_PROTOCOL *This ) { UINTN Size; EFI_STATUS Status; UINT16 *BootNext; UINTN BootNextSize; CHAR16 BootVariableName[9]; EFI_EVENT EndOfDxeEvent; // // Signal EndOfDxe PI Event // Status = gBS->CreateEventEx ( EVT_NOTIFY_SIGNAL, TPL_NOTIFY, EmptyCallbackFunction, NULL, &gEfiEndOfDxeEventGroupGuid, &EndOfDxeEvent ); if (!EFI_ERROR (Status)) { gBS->SignalEvent (EndOfDxeEvent); } PERF_END (NULL, "DXE", NULL, 0); // // Declare the Firmware Vendor // if (FixedPcdGetPtr(PcdFirmwareVendor) != NULL) { Size = 0x100; gST->FirmwareVendor = AllocateRuntimePool (Size); ASSERT (gST->FirmwareVendor != NULL); UnicodeSPrint (gST->FirmwareVendor, Size, L"%a EFI %a %a", PcdGetPtr(PcdFirmwareVendor), __DATE__, __TIME__); } // // Fixup Table CRC after we updated Firmware Vendor // gST->Hdr.CRC32 = 0; Status = gBS->CalculateCrc32 ((VOID*)gST, gST->Hdr.HeaderSize, &gST->Hdr.CRC32); ASSERT_EFI_ERROR (Status); // If BootNext environment variable is defined then we just load it ! BootNextSize = sizeof(UINT16); Status = GetGlobalEnvironmentVariable (L"BootNext", NULL, &BootNextSize, (VOID**)&BootNext); if (!EFI_ERROR(Status)) { ASSERT(BootNextSize == sizeof(UINT16)); // Generate the requested Boot Entry variable name UnicodeSPrint (BootVariableName, 9 * sizeof(CHAR16), L"Boot%04X", *BootNext); // Set BootCurrent variable gRT->SetVariable (L"BootCurrent", &gEfiGlobalVariableGuid, EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS, BootNextSize, BootNext); FreePool (BootNext); // Start the requested Boot Entry Status = BdsStartBootOption (BootVariableName); if (Status != EFI_NOT_FOUND) { // BootNext has not been succeeded launched if (EFI_ERROR(Status)) { Print(L"Fail to start BootNext.\n"); } // Delete the BootNext environment variable gRT->SetVariable (L"BootNext", &gEfiGlobalVariableGuid, EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS, 0, NULL); } // Clear BootCurrent variable gRT->SetVariable (L"BootCurrent", &gEfiGlobalVariableGuid, EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS, 0, NULL); } // If Boot Order does not exist then create a default entry DefineDefaultBootEntries (); // Now we need to setup the EFI System Table with information about the console devices. InitializeConsole (); // // Update the CRC32 in the EFI System Table header // gST->Hdr.CRC32 = 0; Status = gBS->CalculateCrc32 ((VOID*)gST, gST->Hdr.HeaderSize, &gST->Hdr.CRC32); ASSERT_EFI_ERROR (Status); // Timer before initiating the default boot selection StartDefaultBootOnTimeout (); // Start the Boot Menu Status = BootMenuMain (); ASSERT_EFI_ERROR (Status); }
/** Writes performance data of booting into the allocated memory. OS can process these records. @param Event The triggered event. @param Context Context for this event. **/ VOID EFIAPI WriteBootToOsPerformanceData ( IN EFI_EVENT Event, IN VOID *Context ) { EFI_STATUS Status; UINT32 LimitCount; EFI_HANDLE *Handles; UINTN NoHandles; CHAR8 GaugeString[PERF_TOKEN_SIZE]; UINT8 *Ptr; UINT32 Index; UINT64 Ticker; UINT64 Freq; UINT32 Duration; UINTN LogEntryKey; CONST VOID *Handle; CONST CHAR8 *Token; CONST CHAR8 *Module; UINT64 StartTicker; UINT64 EndTicker; UINT64 StartValue; UINT64 EndValue; BOOLEAN CountUp; UINTN EntryIndex; UINTN NumPerfEntries; // // List of flags indicating PerfEntry contains DXE handle // BOOLEAN *PerfEntriesAsDxeHandle; UINTN VarSize; // // Record the performance data for End of BDS // PERF_END(NULL, "BDS", NULL, 0); // // Retrieve time stamp count as early as possible // Ticker = GetPerformanceCounter (); Freq = GetPerformanceCounterProperties (&StartValue, &EndValue); Freq = DivU64x32 (Freq, 1000); mPerfHeader.CpuFreq = Freq; // // Record BDS raw performance data // if (EndValue >= StartValue) { mPerfHeader.BDSRaw = Ticker - StartValue; CountUp = TRUE; } else { mPerfHeader.BDSRaw = StartValue - Ticker; CountUp = FALSE; } if (mAcpiLowMemoryBase == 0x0FFFFFFFF) { VarSize = sizeof (EFI_PHYSICAL_ADDRESS); Status = gRT->GetVariable ( L"PerfDataMemAddr", &gPerformanceProtocolGuid, NULL, &VarSize, &mAcpiLowMemoryBase ); if (EFI_ERROR (Status)) { // // Fail to get the variable, return. // return; } } // // Put Detailed performance data into memory // Handles = NULL; Status = gBS->LocateHandleBuffer ( AllHandles, NULL, NULL, &NoHandles, &Handles ); if (EFI_ERROR (Status)) { return ; } Ptr = (UINT8 *) ((UINT32) mAcpiLowMemoryBase + sizeof (PERF_HEADER)); LimitCount = (UINT32) (PERF_DATA_MAX_LENGTH - sizeof (PERF_HEADER)) / sizeof (PERF_DATA); NumPerfEntries = 0; LogEntryKey = 0; while ((LogEntryKey = GetPerformanceMeasurement ( LogEntryKey, &Handle, &Token, &Module, &StartTicker, &EndTicker)) != 0) { NumPerfEntries++; } PerfEntriesAsDxeHandle = AllocateZeroPool (NumPerfEntries * sizeof (BOOLEAN)); ASSERT (PerfEntriesAsDxeHandle != NULL); // // Get DXE drivers performance // for (Index = 0; Index < NoHandles; Index++) { Ticker = 0; LogEntryKey = 0; EntryIndex = 0; while ((LogEntryKey = GetPerformanceMeasurement ( LogEntryKey, &Handle, &Token, &Module, &StartTicker, &EndTicker)) != 0) { if (Handle == Handles[Index] && !PerfEntriesAsDxeHandle[EntryIndex]) { PerfEntriesAsDxeHandle[EntryIndex] = TRUE; } EntryIndex++; if ((Handle == Handles[Index]) && (EndTicker != 0)) { if (StartTicker == 1) { StartTicker = StartValue; } if (EndTicker == 1) { EndTicker = StartValue; } Ticker += CountUp ? (EndTicker - StartTicker) : (StartTicker - EndTicker); } } Duration = (UINT32) DivU64x32 (Ticker, (UINT32) Freq); if (Duration > 0) { GetNameFromHandle (Handles[Index], GaugeString); AsciiStrCpyS (mPerfData.Token, PERF_TOKEN_SIZE, GaugeString); mPerfData.Duration = Duration; CopyMem (Ptr, &mPerfData, sizeof (PERF_DATA)); Ptr += sizeof (PERF_DATA); mPerfHeader.Count++; if (mPerfHeader.Count == LimitCount) { goto Done; } } } // // Get inserted performance data // LogEntryKey = 0; EntryIndex = 0; while ((LogEntryKey = GetPerformanceMeasurement ( LogEntryKey, &Handle, &Token, &Module, &StartTicker, &EndTicker)) != 0) { if (!PerfEntriesAsDxeHandle[EntryIndex] && EndTicker != 0) { ZeroMem (&mPerfData, sizeof (PERF_DATA)); AsciiStrnCpyS (mPerfData.Token, PERF_TOKEN_SIZE, Token, PERF_TOKEN_LENGTH); if (StartTicker == 1) { StartTicker = StartValue; } if (EndTicker == 1) { EndTicker = StartValue; } Ticker = CountUp ? (EndTicker - StartTicker) : (StartTicker - EndTicker); mPerfData.Duration = (UINT32) DivU64x32 (Ticker, (UINT32) Freq); CopyMem (Ptr, &mPerfData, sizeof (PERF_DATA)); Ptr += sizeof (PERF_DATA); mPerfHeader.Count++; if (mPerfHeader.Count == LimitCount) { goto Done; } } EntryIndex++; } Done: FreePool (Handles); FreePool (PerfEntriesAsDxeHandle); mPerfHeader.Signiture = PERFORMANCE_SIGNATURE; // // Put performance data to Reserved memory // CopyMem ( (UINTN *) (UINTN) mAcpiLowMemoryBase, &mPerfHeader, sizeof (PERF_HEADER) ); return ; }
/** Service routine for BdsInstance->Entry(). Devices are connected, the consoles are initialized, and the boot options are tried. @param This Protocol Instance structure. **/ VOID EFIAPI BdsEntry ( IN EFI_BDS_ARCH_PROTOCOL *This ) { LIST_ENTRY DriverOptionList; LIST_ENTRY BootOptionList; UINTN BootNextSize; CHAR16 *FirmwareVendor; EFI_STATUS Status; UINT16 BootTimeOut; UINTN Index; EDKII_VARIABLE_LOCK_PROTOCOL *VariableLock; // // Insert the performance probe // PERF_END (NULL, "DXE", NULL, 0); PERF_START (NULL, "BDS", NULL, 0); // // Initialize the global system boot option and driver option // InitializeListHead (&DriverOptionList); InitializeListHead (&BootOptionList); // // Initialize hotkey service // InitializeHotkeyService (); // // Fill in FirmwareVendor and FirmwareRevision from PCDs // FirmwareVendor = (CHAR16 *)PcdGetPtr (PcdFirmwareVendor); gST->FirmwareVendor = AllocateRuntimeCopyPool (StrSize (FirmwareVendor), FirmwareVendor); ASSERT (gST->FirmwareVendor != NULL); gST->FirmwareRevision = PcdGet32 (PcdFirmwareRevision); // // Fixup Tasble CRC after we updated Firmware Vendor and Revision // gST->Hdr.CRC32 = 0; gBS->CalculateCrc32 ((VOID *)gST, sizeof(EFI_SYSTEM_TABLE), &gST->Hdr.CRC32); // // Validate Variable. // BdsFormalizeEfiGlobalVariable(); // // Mark the read-only variables if the Variable Lock protocol exists // Status = gBS->LocateProtocol (&gEdkiiVariableLockProtocolGuid, NULL, (VOID **) &VariableLock); DEBUG ((EFI_D_INFO, "[BdsDxe] Locate Variable Lock protocol - %r\n", Status)); if (!EFI_ERROR (Status)) { for (Index = 0; Index < ARRAY_SIZE (mReadOnlyVariables); Index++) { Status = VariableLock->RequestToLock (VariableLock, mReadOnlyVariables[Index], &gEfiGlobalVariableGuid); ASSERT_EFI_ERROR (Status); } } // // Report Status Code to indicate connecting drivers will happen // REPORT_STATUS_CODE ( EFI_PROGRESS_CODE, (EFI_SOFTWARE_DXE_BS_DRIVER | EFI_SW_DXE_BS_PC_BEGIN_CONNECTING_DRIVERS) ); InitializeHwErrRecSupport(); // // Initialize L"Timeout" EFI global variable. // BootTimeOut = PcdGet16 (PcdPlatformBootTimeOut); if (BootTimeOut != 0xFFFF) { // // If time out value equal 0xFFFF, no need set to 0xFFFF to variable area because UEFI specification // define same behavior between no value or 0xFFFF value for L"Timeout". // BdsDxeSetVariableAndReportStatusCodeOnError ( L"Timeout", &gEfiGlobalVariableGuid, EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_NON_VOLATILE, sizeof (UINT16), &BootTimeOut ); } // // bugbug: platform specific code // Initialize the platform specific string and language // InitializeStringSupport (); InitializeLanguage (TRUE); InitializeFrontPage (TRUE); // // Do the platform init, can be customized by OEM/IBV // PERF_START (NULL, "PlatformBds", "BDS", 0); PlatformBdsInit (); // // Set up the device list based on EFI 1.1 variables // process Driver#### and Load the driver's in the // driver option list // BdsLibBuildOptionFromVar (&DriverOptionList, L"DriverOrder"); if (!IsListEmpty (&DriverOptionList)) { BdsLibLoadDrivers (&DriverOptionList); } // // Check if we have the boot next option // mBootNext = BdsLibGetVariableAndSize ( L"BootNext", &gEfiGlobalVariableGuid, &BootNextSize ); // // Setup some platform policy here // PlatformBdsPolicyBehavior (&DriverOptionList, &BootOptionList, BdsProcessCapsules, BdsMemoryTest); PERF_END (NULL, "PlatformBds", "BDS", 0); // // BDS select the boot device to load OS // BdsBootDeviceSelect (); // // Only assert here since this is the right behavior, we should never // return back to DxeCore. // ASSERT (FALSE); return ; }
/** Jump to OS waking vector. The function will install boot script done PPI, report S3 resume status code, and then jump to OS waking vector. @param AcpiS3Context a pointer to a structure of ACPI_S3_CONTEXT @param PeiS3ResumeState a pointer to a structure of PEI_S3_RESUME_STATE **/ VOID EFIAPI S3ResumeBootOs ( IN ACPI_S3_CONTEXT *AcpiS3Context, IN PEI_S3_RESUME_STATE *PeiS3ResumeState ) { EFI_STATUS Status; EFI_ACPI_4_0_FIRMWARE_ACPI_CONTROL_STRUCTURE *Facs; ASM_TRANSFER_CONTROL AsmTransferControl; UINTN TempStackTop; UINTN TempStack[0x10]; // // Restore IDT // AsmWriteIdtr (&PeiS3ResumeState->Idtr); if (PeiS3ResumeState->ReturnStatus != EFI_SUCCESS) { // // Report Status code that boot script execution is failed // REPORT_STATUS_CODE ( EFI_ERROR_CODE | EFI_ERROR_MINOR, (EFI_SOFTWARE_PEI_MODULE | EFI_SW_PEI_EC_S3_BOOT_SCRIPT_ERROR) ); } PERF_END (NULL, "ScriptExec", NULL, 0); // // Install BootScriptDonePpi // Status = PeiServicesInstallPpi (&mPpiListPostScriptTable); ASSERT_EFI_ERROR (Status); // // Get ACPI Table Address // Facs = (EFI_ACPI_4_0_FIRMWARE_ACPI_CONTROL_STRUCTURE *) ((UINTN) (AcpiS3Context->AcpiFacsTable)); if ((Facs == NULL) || (Facs->Signature != EFI_ACPI_4_0_FIRMWARE_ACPI_CONTROL_STRUCTURE_SIGNATURE) || ((Facs->FirmwareWakingVector == 0) && (Facs->XFirmwareWakingVector == 0)) ) { // // Report Status code that no valid vector is found // REPORT_STATUS_CODE ( EFI_ERROR_CODE | EFI_ERROR_MAJOR, (EFI_SOFTWARE_PEI_MODULE | EFI_SW_PEI_EC_S3_OS_WAKE_ERROR) ); CpuDeadLoop (); return ; } // // Install EndOfPeiPpi // Status = PeiServicesInstallPpi (&mPpiListEndOfPeiTable); ASSERT_EFI_ERROR (Status); // // report status code on S3 resume // REPORT_STATUS_CODE (EFI_PROGRESS_CODE, EFI_SOFTWARE_PEI_MODULE | EFI_SW_PEI_PC_OS_WAKE); PERF_CODE ( WriteToOsS3PerformanceData (); );
/** Start function of Driver binding protocol which start this driver on Controller by detecting all disks and installing BlockIo protocol on them. @param This Protocol instance pointer. @param Controller Handle of device to bind driver to. @param RemainingDevicePath produce all possible children. @retval EFI_SUCCESS This driver is added to ControllerHandle. @retval EFI_ALREADY_STARTED This driver is already running on ControllerHandle. @retval other This driver does not support this device. **/ EFI_STATUS EFIAPI IDEBusDriverBindingStart ( IN EFI_DRIVER_BINDING_PROTOCOL *This, IN EFI_HANDLE Controller, IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath ) { EFI_STATUS Status; EFI_STATUS SavedStatus; EFI_PCI_IO_PROTOCOL *PciIo; EFI_DEVICE_PATH_PROTOCOL *ParentDevicePath; EFI_DEV_PATH *Node; UINT8 IdeChannel; UINT8 BeginningIdeChannel; UINT8 EndIdeChannel; UINT8 IdeDevice; UINT8 BeginningIdeDevice; UINT8 EndIdeDevice; IDE_BLK_IO_DEV *IdeBlkIoDevice[IdeMaxChannel][IdeMaxDevice]; IDE_BLK_IO_DEV *IdeBlkIoDevicePtr; IDE_REGISTERS_BASE_ADDR IdeRegsBaseAddr[IdeMaxChannel]; ATA_TRANSFER_MODE TransferMode; ATA_DRIVE_PARMS DriveParameters; EFI_DEV_PATH NewNode; UINT8 ConfigurationOptions; UINT16 CommandBlockBaseAddr; UINT16 ControlBlockBaseAddr; UINTN DataSize; IDE_BUS_DRIVER_PRIVATE_DATA *IdeBusDriverPrivateData; UINT64 Supports; // // Local variables declaration for IdeControllerInit support // EFI_IDE_CONTROLLER_INIT_PROTOCOL *IdeInit; BOOLEAN EnumAll; BOOLEAN ChannelEnabled; UINT8 MaxDevices; EFI_IDENTIFY_DATA IdentifyData; EFI_ATA_COLLECTIVE_MODE *SupportedModes; IdeBusDriverPrivateData = NULL; SupportedModes = NULL; // // Perform IdeBus initialization // Status = gBS->OpenProtocol ( Controller, &gEfiDevicePathProtocolGuid, (VOID **) &ParentDevicePath, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_BY_DRIVER ); if ((EFI_ERROR (Status)) && (Status != EFI_ALREADY_STARTED)) { return Status; } // // Now open the IDE_CONTROLLER_INIT protocol. Step7.1 // Status = gBS->OpenProtocol ( Controller, &gEfiIdeControllerInitProtocolGuid, (VOID **) &IdeInit, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_BY_DRIVER ); // // The following OpenProtocol function with _GET_PROTOCOL attribute and // will not return EFI_ALREADY_STARTED, so save it for now // SavedStatus = Status; if ((EFI_ERROR (Status)) && (Status != EFI_ALREADY_STARTED)) { DEBUG ((EFI_D_ERROR, "Open Init, Status=%x", Status)); // // open protocol is not SUCCESS or not ALREADY_STARTED, error exit // goto ErrorExit; } // // Save Enumall. Step7.2 // EnumAll = IdeInit->EnumAll; // // Consume PCI I/O protocol. Note that the OpenProtocol with _GET_PROTOCOL // attribute will not return EFI_ALREADY_STARTED // Status = gBS->OpenProtocol ( Controller, &gEfiPciIoProtocolGuid, (VOID **) &PciIo, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_GET_PROTOCOL ); if (EFI_ERROR (Status)) { DEBUG ((EFI_D_ERROR, "Open PciIo, Status=%x", Status)); goto ErrorExit; } // // We must check EFI_ALREADY_STARTED because many ATAPI devices are removable // if (SavedStatus != EFI_ALREADY_STARTED) { IdeBusDriverPrivateData = AllocatePool (sizeof (IDE_BUS_DRIVER_PRIVATE_DATA)); if (IdeBusDriverPrivateData == NULL) { Status = EFI_OUT_OF_RESOURCES; goto ErrorExit; } ZeroMem (IdeBusDriverPrivateData, sizeof (IDE_BUS_DRIVER_PRIVATE_DATA)); Status = gBS->InstallMultipleProtocolInterfaces ( &Controller, &gEfiCallerIdGuid, IdeBusDriverPrivateData, NULL ); if (EFI_ERROR (Status)) { goto ErrorExit; } } else { Status = gBS->OpenProtocol ( Controller, &gEfiCallerIdGuid, (VOID **) &IdeBusDriverPrivateData, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_GET_PROTOCOL ); if (EFI_ERROR (Status)) { IdeBusDriverPrivateData = NULL; goto ErrorExit; } } Status = PciIo->Attributes ( PciIo, EfiPciIoAttributeOperationSupported, 0, &Supports ); if (!EFI_ERROR (Status)) { Supports &= (UINT64)EFI_PCI_DEVICE_ENABLE; Status = PciIo->Attributes ( PciIo, EfiPciIoAttributeOperationEnable, Supports, NULL ); } if (EFI_ERROR (Status)) { goto ErrorExit; } // // Read the environment variable that contains the IDEBus Driver's // Config options that were set by the Driver Configuration Protocol // DataSize = sizeof (ConfigurationOptions); Status = gRT->GetVariable ( (CHAR16 *) L"Configuration", &gEfiCallerIdGuid, NULL, &DataSize, &ConfigurationOptions ); if (EFI_ERROR (Status)) { ConfigurationOptions = 0x0f; } if (EnumAll || RemainingDevicePath == NULL) { // // If IdeInit->EnumAll is TRUE or RemainingDevicePath is NULL, // must enumerate all IDE devices anyway // BeginningIdeChannel = IdePrimary; EndIdeChannel = IdeSecondary; BeginningIdeDevice = IdeMaster; EndIdeDevice = IdeSlave; } else if (!IsDevicePathEnd (RemainingDevicePath)) { // // If RemainingDevicePath isn't the End of Device Path Node, // only scan the specified device by RemainingDevicePath // Node = (EFI_DEV_PATH *) RemainingDevicePath; BeginningIdeChannel = Node->Atapi.PrimarySecondary; EndIdeChannel = BeginningIdeChannel; BeginningIdeDevice = Node->Atapi.SlaveMaster; EndIdeDevice = BeginningIdeDevice; if (BeginningIdeChannel >= IdeMaxChannel || EndIdeChannel >= IdeMaxChannel) { Status = EFI_INVALID_PARAMETER; goto ErrorExit; } if (BeginningIdeDevice >= IdeMaxDevice|| EndIdeDevice >= IdeMaxDevice) { Status = EFI_INVALID_PARAMETER; goto ErrorExit; } } else { // // If RemainingDevicePath is the End of Device Path Node, // skip enumerate any device and return EFI_SUCESSS // BeginningIdeChannel = IdeMaxChannel; EndIdeChannel = IdeMaxChannel - 1; BeginningIdeDevice = IdeMaxDevice; EndIdeDevice = IdeMaxDevice - 1; } // // Obtain IDE IO port registers' base addresses // Status = GetIdeRegistersBaseAddr (PciIo, IdeRegsBaseAddr); if (EFI_ERROR (Status)) { goto ErrorExit; } // // Report status code: begin IdeBus initialization // REPORT_STATUS_CODE_WITH_DEVICE_PATH ( EFI_PROGRESS_CODE, (EFI_IO_BUS_ATA_ATAPI | EFI_IOB_PC_RESET), ParentDevicePath ); // // Strictly follow the enumeration based on IDE_CONTROLLER_INIT protocol // for (IdeChannel = BeginningIdeChannel; IdeChannel <= EndIdeChannel; IdeChannel++) { IdeInit->NotifyPhase (IdeInit, EfiIdeBeforeChannelEnumeration, IdeChannel); // // now obtain channel information fron IdeControllerInit protocol. Step9 // Status = IdeInit->GetChannelInfo ( IdeInit, IdeChannel, &ChannelEnabled, &MaxDevices ); if (EFI_ERROR (Status)) { DEBUG ((EFI_D_ERROR, "[GetChannel, Status=%x]", Status)); continue; } if (!ChannelEnabled) { continue; } EndIdeDevice = (UINT8) MIN ((MaxDevices - 1), EndIdeDevice); ASSERT (EndIdeDevice < IdeMaxDevice); // // Now inform the IDE Controller Init Module. Sept10 // IdeInit->NotifyPhase (IdeInit, EfiIdeBeforeChannelReset, IdeChannel); // // No reset channel function implemented. Sept11 // IdeInit->NotifyPhase (IdeInit, EfiIdeAfterChannelReset, IdeChannel); // // Step13 // IdeInit->NotifyPhase ( IdeInit, EfiIdeBusBeforeDevicePresenceDetection, IdeChannel ); // // Prepare to detect IDE device of this channel // InitializeIDEChannelData (); // // -- 1st inner loop --- Master/Slave ------------ Step14 // for (IdeDevice = BeginningIdeDevice; IdeDevice <= EndIdeDevice; IdeDevice++) { // // Check whether the configuration options allow this device // if ((ConfigurationOptions & (1 << (IdeChannel * 2 + IdeDevice))) == 0) { continue; } // // The device has been scanned in another Start(), No need to scan it again // for perf optimization. // if (IdeBusDriverPrivateData->HaveScannedDevice[IdeChannel * 2 + IdeDevice]) { continue; } // // create child handle for the detected device. // IdeBlkIoDevice[IdeChannel][IdeDevice] = AllocatePool (sizeof (IDE_BLK_IO_DEV)); if (IdeBlkIoDevice[IdeChannel][IdeDevice] == NULL) { continue; } IdeBlkIoDevicePtr = IdeBlkIoDevice[IdeChannel][IdeDevice]; ZeroMem (IdeBlkIoDevicePtr, sizeof (IDE_BLK_IO_DEV)); IdeBlkIoDevicePtr->Signature = IDE_BLK_IO_DEV_SIGNATURE; IdeBlkIoDevicePtr->Channel = (EFI_IDE_CHANNEL) IdeChannel; IdeBlkIoDevicePtr->Device = (EFI_IDE_DEVICE) IdeDevice; // // initialize Block IO interface's Media pointer // IdeBlkIoDevicePtr->BlkIo.Media = &IdeBlkIoDevicePtr->BlkMedia; // // Initialize IDE IO port addresses, including Command Block registers // and Control Block registers // IdeBlkIoDevicePtr->IoPort = AllocatePool (sizeof (IDE_BASE_REGISTERS)); if (IdeBlkIoDevicePtr->IoPort == NULL) { continue; } ZeroMem (IdeBlkIoDevicePtr->IoPort, sizeof (IDE_BASE_REGISTERS)); CommandBlockBaseAddr = IdeRegsBaseAddr[IdeChannel].CommandBlockBaseAddr; ControlBlockBaseAddr = IdeRegsBaseAddr[IdeChannel].ControlBlockBaseAddr; IdeBlkIoDevicePtr->IoPort->Data = CommandBlockBaseAddr; (*(UINT16 *) &IdeBlkIoDevicePtr->IoPort->Reg1) = (UINT16) (CommandBlockBaseAddr + 0x01); IdeBlkIoDevicePtr->IoPort->SectorCount = (UINT16) (CommandBlockBaseAddr + 0x02); IdeBlkIoDevicePtr->IoPort->SectorNumber = (UINT16) (CommandBlockBaseAddr + 0x03); IdeBlkIoDevicePtr->IoPort->CylinderLsb = (UINT16) (CommandBlockBaseAddr + 0x04); IdeBlkIoDevicePtr->IoPort->CylinderMsb = (UINT16) (CommandBlockBaseAddr + 0x05); IdeBlkIoDevicePtr->IoPort->Head = (UINT16) (CommandBlockBaseAddr + 0x06); (*(UINT16 *) &IdeBlkIoDevicePtr->IoPort->Reg) = (UINT16) (CommandBlockBaseAddr + 0x07); (*(UINT16 *) &IdeBlkIoDevicePtr->IoPort->Alt) = ControlBlockBaseAddr; IdeBlkIoDevicePtr->IoPort->DriveAddress = (UINT16) (ControlBlockBaseAddr + 0x01); IdeBlkIoDevicePtr->IoPort->MasterSlave = (UINT16) ((IdeDevice == IdeMaster) ? 1 : 0); IdeBlkIoDevicePtr->PciIo = PciIo; IdeBlkIoDevicePtr->IdeBusDriverPrivateData = IdeBusDriverPrivateData; IdeBlkIoDevicePtr->IoPort->BusMasterBaseAddr = IdeRegsBaseAddr[IdeChannel].BusMasterBaseAddr; // // Report Status code: is about to detect IDE drive // REPORT_STATUS_CODE_EX ( EFI_PROGRESS_CODE, (EFI_IO_BUS_ATA_ATAPI | EFI_P_PC_PRESENCE_DETECT), 0, &gEfiCallerIdGuid, NULL, NULL, 0 ); // // Discover device, now! // PERF_START (NULL, "DiscoverIdeDevice", "IDE", 0); Status = DiscoverIdeDevice (IdeBlkIoDevicePtr); PERF_END (NULL, "DiscoverIdeDevice", "IDE", 0); IdeBusDriverPrivateData->HaveScannedDevice[IdeChannel * 2 + IdeDevice] = TRUE; IdeBusDriverPrivateData->DeviceProcessed[IdeChannel * 2 + IdeDevice] = FALSE; if (!EFI_ERROR (Status)) { // // Set Device Path // ZeroMem (&NewNode, sizeof (NewNode)); NewNode.DevPath.Type = MESSAGING_DEVICE_PATH; NewNode.DevPath.SubType = MSG_ATAPI_DP; SetDevicePathNodeLength (&NewNode.DevPath, sizeof (ATAPI_DEVICE_PATH)); NewNode.Atapi.PrimarySecondary = (UINT8) IdeBlkIoDevicePtr->Channel; NewNode.Atapi.SlaveMaster = (UINT8) IdeBlkIoDevicePtr->Device; NewNode.Atapi.Lun = IdeBlkIoDevicePtr->Lun; IdeBlkIoDevicePtr->DevicePath = AppendDevicePathNode ( ParentDevicePath, &NewNode.DevPath ); if (IdeBlkIoDevicePtr->DevicePath == NULL) { ReleaseIdeResources (IdeBlkIoDevicePtr); continue; } // // Submit identify data to IDE controller init driver // CopyMem (&IdentifyData, IdeBlkIoDevicePtr->IdData, sizeof (IdentifyData)); IdeBusDriverPrivateData->DeviceFound[IdeChannel * 2 + IdeDevice] = TRUE; IdeInit->SubmitData (IdeInit, IdeChannel, IdeDevice, &IdentifyData); } else { // // Device detection failed // IdeBusDriverPrivateData->DeviceFound[IdeChannel * 2 + IdeDevice] = FALSE; IdeInit->SubmitData (IdeInit, IdeChannel, IdeDevice, NULL); ReleaseIdeResources (IdeBlkIoDevicePtr); IdeBlkIoDevicePtr = NULL; } // // end of 1st inner loop --- // } // // end of 1st outer loop ========= // } // // = 2nd outer loop == Primary/Secondary ================= // for (IdeChannel = BeginningIdeChannel; IdeChannel <= EndIdeChannel; IdeChannel++) { // // -- 2nd inner loop --- Master/Slave -------- // for (IdeDevice = BeginningIdeDevice; IdeDevice <= EndIdeDevice; IdeDevice++) { ASSERT (IdeChannel * 2 + IdeDevice < MAX_IDE_DEVICE); if (IdeBusDriverPrivateData->DeviceProcessed[IdeChannel * 2 + IdeDevice]) { continue; } if (!IdeBusDriverPrivateData->DeviceFound[IdeChannel * 2 + IdeDevice]) { continue; } Status = IdeInit->CalculateMode ( IdeInit, IdeChannel, IdeDevice, &SupportedModes ); if (EFI_ERROR (Status)) { DEBUG ((EFI_D_ERROR, "[bStStp20S=%x]", Status)); continue; } ASSERT (IdeChannel < IdeMaxChannel && IdeDevice < IdeMaxDevice); IdeBlkIoDevicePtr = IdeBlkIoDevice[IdeChannel][IdeDevice]; // // Set best supported PIO mode on this IDE device // if (SupportedModes->PioMode.Mode <= AtaPioMode2) { TransferMode.ModeCategory = ATA_MODE_CATEGORY_DEFAULT_PIO; } else { TransferMode.ModeCategory = ATA_MODE_CATEGORY_FLOW_PIO; } TransferMode.ModeNumber = (UINT8) (SupportedModes->PioMode.Mode); if (SupportedModes->ExtModeCount == 0){ Status = SetDeviceTransferMode (IdeBlkIoDevicePtr, &TransferMode); if (EFI_ERROR (Status)) { IdeBusDriverPrivateData->DeviceFound[IdeChannel * 2 + IdeDevice] = FALSE; ReleaseIdeResources (IdeBlkIoDevicePtr); IdeBlkIoDevicePtr = NULL; continue; } } // // Set supported DMA mode on this IDE device. Note that UDMA & MDMA cann't // be set together. Only one DMA mode can be set to a device. If setting // DMA mode operation fails, we can continue moving on because we only use // PIO mode at boot time. DMA modes are used by certain kind of OS booting // if (SupportedModes->UdmaMode.Valid) { TransferMode.ModeCategory = ATA_MODE_CATEGORY_UDMA; TransferMode.ModeNumber = (UINT8) (SupportedModes->UdmaMode.Mode); Status = SetDeviceTransferMode (IdeBlkIoDevicePtr, &TransferMode); if (EFI_ERROR (Status)) { IdeBusDriverPrivateData->DeviceFound[IdeChannel * 2 + IdeDevice] = FALSE; ReleaseIdeResources (IdeBlkIoDevicePtr); IdeBlkIoDevicePtr = NULL; continue; } // // Record Udma Mode // IdeBlkIoDevicePtr->UdmaMode.Valid = TRUE; IdeBlkIoDevicePtr->UdmaMode.Mode = SupportedModes->UdmaMode.Mode; EnableInterrupt (IdeBlkIoDevicePtr); } else if (SupportedModes->MultiWordDmaMode.Valid) { TransferMode.ModeCategory = ATA_MODE_CATEGORY_MDMA; TransferMode.ModeNumber = (UINT8) SupportedModes->MultiWordDmaMode.Mode; Status = SetDeviceTransferMode (IdeBlkIoDevicePtr, &TransferMode); if (EFI_ERROR (Status)) { IdeBusDriverPrivateData->DeviceFound[IdeChannel * 2 + IdeDevice] = FALSE; ReleaseIdeResources (IdeBlkIoDevicePtr); IdeBlkIoDevicePtr = NULL; continue; } EnableInterrupt (IdeBlkIoDevicePtr); } // // Init driver parameters // DriveParameters.Sector = (UINT8) ((ATA5_IDENTIFY_DATA *) IdeBlkIoDevicePtr->IdData)->sectors_per_track; DriveParameters.Heads = (UINT8) (((ATA5_IDENTIFY_DATA *) IdeBlkIoDevicePtr->IdData)->heads - 1); DriveParameters.MultipleSector = (UINT8) IdeBlkIoDevicePtr->IdData->AtaData.multi_sector_cmd_max_sct_cnt; // // Set Parameters for the device: // 1) Init // 2) Establish the block count for READ/WRITE MULTIPLE (EXT) command // if ((IdeBlkIoDevicePtr->Type == IdeHardDisk) || (IdeBlkIoDevicePtr->Type == Ide48bitAddressingHardDisk)) { Status = SetDriveParameters (IdeBlkIoDevicePtr, &DriveParameters); } // // Record PIO mode used in private data // IdeBlkIoDevicePtr->PioMode = (ATA_PIO_MODE) SupportedModes->PioMode.Mode; // // Set IDE controller Timing Blocks in the PCI Configuration Space // IdeInit->SetTiming (IdeInit, IdeChannel, IdeDevice, SupportedModes); // // Add Component Name for the IDE/ATAPI device that was discovered. // IdeBlkIoDevicePtr->ControllerNameTable = NULL; ADD_IDE_ATAPI_NAME (IdeBlkIoDevicePtr); Status = gBS->InstallMultipleProtocolInterfaces ( &IdeBlkIoDevicePtr->Handle, &gEfiDevicePathProtocolGuid, IdeBlkIoDevicePtr->DevicePath, &gEfiBlockIoProtocolGuid, &IdeBlkIoDevicePtr->BlkIo, &gEfiDiskInfoProtocolGuid, &IdeBlkIoDevicePtr->DiskInfo, NULL ); if (EFI_ERROR (Status)) { ReleaseIdeResources (IdeBlkIoDevicePtr); } gBS->OpenProtocol ( Controller, &gEfiPciIoProtocolGuid, (VOID **) &PciIo, This->DriverBindingHandle, IdeBlkIoDevicePtr->Handle, EFI_OPEN_PROTOCOL_BY_CHILD_CONTROLLER ); IdeBusDriverPrivateData->DeviceProcessed[IdeChannel * 2 + IdeDevice] = TRUE; // // Report status code: device eanbled! // REPORT_STATUS_CODE_WITH_DEVICE_PATH ( EFI_PROGRESS_CODE, (EFI_IO_BUS_ATA_ATAPI | EFI_P_PC_ENABLE), IdeBlkIoDevicePtr->DevicePath ); // // Create event to clear pending IDE interrupt // Status = gBS->CreateEventEx ( EVT_NOTIFY_SIGNAL, TPL_NOTIFY, ClearInterrupt, IdeBlkIoDevicePtr, &gEfiEventExitBootServicesGuid, &IdeBlkIoDevicePtr->ExitBootServiceEvent ); // // end of 2nd inner loop ---- // } // // end of 2nd outer loop ========== // } // // All configurations done! Notify IdeController to do post initialization // work such as saving IDE controller PCI settings for S3 resume // IdeInit->NotifyPhase (IdeInit, EfiIdeBusPhaseMaximum, 0); if (SupportedModes != NULL) { FreePool (SupportedModes); } PERF_START (NULL, "Finish IDE detection", "IDE", 1); PERF_END (NULL, "Finish IDE detection", "IDE", 0); return EFI_SUCCESS; ErrorExit: // // Report error code: controller error // REPORT_STATUS_CODE_WITH_DEVICE_PATH ( EFI_ERROR_CODE | EFI_ERROR_MINOR, (EFI_IO_BUS_ATA_ATAPI | EFI_IOB_EC_CONTROLLER_ERROR), ParentDevicePath ); gBS->CloseProtocol ( Controller, &gEfiIdeControllerInitProtocolGuid, This->DriverBindingHandle, Controller ); gBS->UninstallMultipleProtocolInterfaces ( Controller, &gEfiCallerIdGuid, IdeBusDriverPrivateData, NULL ); if (IdeBusDriverPrivateData != NULL) { gBS->FreePool (IdeBusDriverPrivateData); } if (SupportedModes != NULL) { gBS->FreePool (SupportedModes); } gBS->CloseProtocol ( Controller, &gEfiPciIoProtocolGuid, This->DriverBindingHandle, Controller ); gBS->CloseProtocol ( Controller, &gEfiDevicePathProtocolGuid, This->DriverBindingHandle, Controller ); return Status; }