182 Commits

Author SHA1 Message Date
17712883c5 Include new KE headers 2025-09-09 23:24:43 +02:00
5cb6474ade Sync CMakeLists with source tree 2025-09-09 23:22:37 +02:00
4947f788d5 Migrate KE subsystem to C++ 2025-09-09 23:20:50 +02:00
465a23633e Sync CMakeLists with current source tree 2025-09-08 22:39:07 +02:00
7c5d6326f8 Migrate EX subsystem to C++ 2025-09-08 22:35:59 +02:00
3f5f57ef12 Remove leftover test code 2025-09-08 15:44:12 +02:00
4e24b239a4 Fix cmake source path 2025-09-08 15:40:26 +02:00
c8dc2a1407 Migrate AR subsystem to C++ 2025-09-08 15:29:13 +02:00
27fec1bacb Add boot options with on-screen debugging 2025-09-05 21:30:01 +02:00
d8e0e07805 Correct format specifier for partition size to prevent stack corruption 2025-09-04 12:21:04 +02:00
8898a427df Rewrite and clarify kernel subsystem descriptions 2025-09-04 11:16:03 +02:00
7e039c47ae Simplify BlpDebugPutChar return path 2025-09-04 10:56:17 +02:00
c2a4ad026a Implement KD subsystem, add serial & framebuffer debug providers 2025-09-04 10:49:40 +02:00
db81e43525 Add missing forward references for RTL types 2025-09-04 10:28:32 +02:00
9cc776e06a Add generic kernel information support 2025-09-03 21:00:18 +02:00
602da0960c Unify string API parameter types to PCSTR/PCWSTR 2025-09-03 19:54:46 +02:00
9577a39046 Fix initialization block size calculation to account for variable-length kernel parameters 2025-09-03 18:10:42 +02:00
f9fe20ba68 Adjust forward references for HL_FRAMEBUFFER_DATA and HL_SCROLL_REGION_DATA 2025-09-03 16:44:52 +02:00
227da47bfc Add scroll region support and refactor framebuffer handling 2025-09-03 15:06:25 +02:00
9f5daafad9 Unify wide string types across console and debug functions 2025-09-03 10:41:24 +02:00
b2df65f5cc Fix KeDbgPrint prototype to use PCWSTR 2025-09-03 10:29:21 +02:00
d6999fad2f Extend RTL with substring search and character case functions 2025-09-02 21:51:10 +02:00
e4981b52ed Comment RtlTokenizeWideString for clarity 2025-09-02 20:18:33 +02:00
3c25934495 Add explanatory comments to string handling code 2025-09-02 19:31:13 +02:00
e23a4c71a2 Fix framebuffer address calculations by using Pitch and BytesPerPixel 2025-09-02 12:42:06 +02:00
6ee7243e04 Refactor APIC delivery mode handling and unify naming 2025-09-01 19:54:12 +02:00
d45cc5ffe5 Fix incorrect APIC delivery mode definitions 2025-09-01 19:32:29 +02:00
3c8b7cb1f2 Remove unused variable 2025-09-01 19:25:45 +02:00
2e415f6ec2 Remove broadcast INIT IPI 2025-09-01 19:23:02 +02:00
5ff9303bd1 Add debug screen clear at end of kernel initialization 2025-09-01 16:27:28 +02:00
84ac8f00e0 Fix APIC initialization and refine comments 2025-09-01 15:41:06 +02:00
418ff68be4 Add ESP boot support and improve block device enumeration 2025-09-01 14:02:38 +02:00
2d1b6363e6 Add CTRL-B shortcut to boot OS directly from edit menu 2025-09-01 12:43:33 +02:00
34cebf2810 Allow editing boot options using 'e' key 2025-09-01 11:47:36 +02:00
0fa4a175e0 Correct Backspace behavior in input dialog 2025-09-01 11:40:48 +02:00
72a832f190 Fix type mismatch in BlGetEditableOptions OptionsCount parameter 2025-08-30 20:35:01 +02:00
ba65264d1e Remove unnecessary console input buffer reset 2025-08-27 22:21:39 +02:00
2ee33ab229 Refactor BlGetConfigValue to return EFI_STATUS and output value via parameter 2025-08-27 19:44:52 +02:00
1eea654a36 Expose BlGetBootOptionValue, BlGetEditableOptions and BlSetBootOptionValue 2025-08-27 19:26:01 +02:00
c6643125e1 Implement boot entry editor 2025-08-27 19:15:38 +02:00
b68514b176 Limit boot menu entry names to available menu width 2025-08-25 19:03:57 +02:00
960e913222 Optimize boot menu drawing to eliminate screen flickering 2025-08-25 17:56:40 +02:00
e99e563aff Correct .modinfo section parsing 2025-08-25 12:07:49 +02:00
0b40a3fb10 Refactor MMU for multi-paging support and add 5-Level paging 2025-08-23 20:03:56 +02:00
a84ef21571 Adjust LA57 base addresses to prevent overflow 2025-08-21 01:42:36 +02:00
1ef2560ef6 Enable LA57 by invoking the trampoline code 2025-08-21 00:14:49 +02:00
d1b14fccdd Resolve build issues caused by the last commit 2025-08-20 21:08:43 +02:00
88b3a57962 Allow specifying an allocation type when allocating pages 2025-08-20 20:59:31 +02:00
9f6121e9b2 Map the physical page for trampoline code 2025-08-20 20:37:55 +02:00
4a7ea6009d Expose ArEnableExtendedPhysicalAddressing function in XTDK 2025-08-20 20:23:44 +02:00
c4a7df6f38 Extract trampoline code into a separate file 2025-08-20 20:20:35 +02:00
2468d80078 Add trampoline to enable 5-level paging 2025-08-20 00:20:10 +02:00
ebae8c655c Expand CR4, MSR, and EFER register definitions 2025-08-19 23:59:58 +02:00
1a0bc7f65f Update and correct CR4 bit definitions 2025-08-19 21:45:13 +02:00
91a5db2ee4 Implement PML5 support in XtpMapHardwareMemoryPool 2025-08-18 12:13:48 +02:00
b639bf3077 Implement PML5 self-mapping 2025-08-18 11:59:05 +02:00
c409400cbf Correct VA masking in AMD64 page mapping functions 2025-08-18 01:07:28 +02:00
d602038858 Temporarily disable LA57 paging 2025-08-18 00:10:32 +02:00
017b8603d5 Align parameters in PTE manipulation functions 2025-08-17 21:55:21 +02:00
a9dd1eaacd Implement MmpSetPteCaching function for AMD64 architecture 2025-08-17 21:51:43 +02:00
f30d3df5b3 Implement PTE manipulation functions for AMD64 architecture 2025-08-17 21:48:28 +02:00
c3ece4f317 Fix type usage in XtpMapHardwareMemoryPool 2025-08-17 00:51:26 +02:00
1e11acee72 Refactor hardware memory mapping to use page map routine callbacks 2025-08-17 00:47:56 +02:00
57193eecc0 Implement PML2/PML3 page table routines 2025-08-17 00:45:12 +02:00
720d525b95 Assign page map routines 2025-08-17 00:29:28 +02:00
f77f2bbf92 Introduce architecture-specific page map routines 2025-08-17 00:23:19 +02:00
0ed59f223c Relocate page mapping helpers and add PML5 support 2025-08-16 21:07:54 +02:00
de2973ac42 Implement page map info initialization 2025-08-16 20:28:05 +02:00
8491e5fed1 Remove PageMapLevel from the loader information block 2025-08-16 20:18:34 +02:00
6a330e38f2 Consolidate paging-related globals into MmpPageMapInfo 2025-08-16 20:14:18 +02:00
1dcd3fceed Define page map information structure for both supported architectures 2025-08-16 20:08:12 +02:00
5768d4bba6 Prepare for architecture-specific paging initialization 2025-08-16 19:58:00 +02:00
f85fe31b38 Adapt i686 memory mapping to new PML3 types 2025-08-16 00:36:20 +02:00
22f81a106b Update forward declarations for PML2/PML3 types 2025-08-16 00:33:18 +02:00
7e08dc286e Separate types for legacy (PML2) and PAE (PML3) paging 2025-08-16 00:29:20 +02:00
3ca6d04f6b Add definitions for 5-level paging and refactor constants 2025-08-16 00:22:21 +02:00
e57985da8d Rename MM_LA57_SHIFT to MM_P5I_SHIFT for consistency 2025-08-15 20:49:25 +02:00
8a23cc444f Merge branch 'master' into harraiken_mm 2025-08-15 11:30:48 +02:00
2e0a87e596 Use __asm__ to comply with disabled GNU extensions 2025-08-15 11:07:07 +02:00
e8771dfc5b Use __asm__ to comply with disabled GNU extensions 2025-08-15 00:32:56 +02:00
030575592c Revert 'Fix broken HlpInitializeAcpiSystemDescriptionTable implementation' 2025-08-11 23:30:40 +02:00
88fba6d408 revert 'Fix broken HlpInitializeAcpiSystemDescriptionTable declaration' 2025-08-11 23:29:57 +02:00
2375a653fe Resolve potential PDE conflict in non-PAE boot path 2025-08-11 20:59:00 +02:00
bf291613a3 Add debug messages to display PML set by bootloader 2025-08-10 18:07:26 +02:00
406c0a0cd2 Fix broken HlpInitializeAcpiSystemDescriptionTable declaration 2025-08-10 17:48:48 +02:00
c9f9f87973 Fix broken HlpInitializeAcpiSystemDescriptionTable implementation 2025-08-10 17:48:01 +02:00
383d5eeb06 Add missing forward declaration to resolve compile issue 2025-08-10 17:43:27 +02:00
dce2c50b9d Replace hardcoded PML level with dynamic detection using XtpDeterminePagingLevel 2025-08-10 17:39:38 +02:00
e888befee1 Add boot menu entry for booting ExectOS with XPA (eXtended Physical Addressing) disabled 2025-08-10 17:35:37 +02:00
a33a45fc20 Implement paging level detection for AMD64 based on CPUID and boot parameters 2025-08-10 17:27:12 +02:00
23e8be1097 Remove PAE support check to allow both PAE and non-PAE configurations 2025-08-10 17:25:04 +02:00
800810169d Fix XtpDeterminePagingLevel after renaming CPUID requests 2025-08-10 17:19:44 +02:00
eeb5e8d455 Fix broken AcGetApicBase 2025-08-10 17:16:48 +02:00
d806c8e1f2 Resolve compilation errors due to renamed CPUID requests 2025-08-10 17:12:06 +02:00
2ea306097d Resolve compilation errors due to renamed CPUID requests 2025-08-10 17:10:01 +02:00
3472b448c7 Fix broken AcGetApicBase implementation 2025-08-10 17:05:13 +02:00
e62820187d Resolve compilation errors due to updated CPUID requests 2025-08-10 17:01:28 +02:00
a6814aa2a3 Resolve compilation errors due to renamed CPUID requests 2025-08-10 16:59:32 +02:00
560bd8b65e Update CPUID requests 2025-08-10 16:53:45 +02:00
a431816243 Update CPUID requests 2025-08-10 16:52:59 +02:00
574582f977 Add forward declarations for CPUID feature enums 2025-08-10 16:36:32 +02:00
23f022965a Add forward declarations for CPUID feature enums 2025-08-10 16:35:40 +02:00
aef81760d0 Rename enumeration lists 2025-08-10 16:33:36 +02:00
bb5deb10d5 Rename enumeration lists 2025-08-10 16:32:49 +02:00
69d4e0cd84 Add enums for CPU feature flags used in CPUID detection 2025-08-10 16:27:14 +02:00
a9a264252a Add enums for CPU feature flags used in CPUID detection 2025-08-10 16:25:26 +02:00
a539191a33 Implement paging level detection for i686 based on CPUID and boot parameters 2025-08-10 15:42:41 +02:00
3f2496644f Compile bootutil.c 2025-08-10 00:12:01 +02:00
daf8b87832 Expose GetBooleanParameter via loader protocol 2025-08-10 00:10:36 +02:00
a2b9af56dd Add boot utils to loader protocol 2025-08-10 00:07:40 +02:00
8de661494a Add BlGetBooleanParameter declaration 2025-08-10 00:04:25 +02:00
07f2e73a22 Add helper functions used by the boot protocol during system startup 2025-08-09 23:58:52 +02:00
2472cbbff4 Revert 'Simplify and correct hardware pool mapping' 2025-08-09 17:15:35 +02:00
58c2092049 Revert latest changes 2025-08-09 14:53:31 +02:00
311d5e1f5c Simplify and correct hardware pool mapping 2025-08-08 21:49:21 +02:00
39d8f82caf Define MM_HARDWARE_POOL_PAGE_COUNT 2025-08-08 21:44:33 +02:00
d7552f1dce Fix race condition in HlComPortReadLsr
The static local variable RingFlag in HlComPortReadLsr caused shared state across multiple calls and ports, leading to race conditions and incorrect behavior.
2025-08-06 09:01:47 +02:00
9badf36ce0 Add ring indicator field to CPPORT structure 2025-08-05 23:25:30 +02:00
aff069dd1a Add i686-specific implementation of BlpGetNextPageTable supporting PML2 and PML3 2025-08-04 23:28:12 +02:00
f29f2bca74 Add AMD64-specific implementation of BlpGetNextPageTable matching new signature 2025-08-04 23:25:57 +02:00
544ec63d6e Remove global BlpGetNextPageTable implementation in favor of arch-specific versions 2025-08-04 23:22:23 +02:00
ed75060482 Update BlpGetNextPageTable declaration to support multiple levels of PML 2025-08-04 23:01:03 +02:00
1d376486cd Add myself to the list of authors due to significant contributions 2025-08-04 14:34:40 +02:00
1ffddfd0e2 Add non-PAE paging support to BlMapPage 2025-08-04 14:18:21 +02:00
0d3fb550f2 Initialize page directory for non-PAE paging 2025-08-04 14:05:58 +02:00
ca6c913fa7 Clarify PAE state management logic 2025-08-02 18:30:23 +02:00
ca06f9ebb5 Correctly manage PAE state when enabling paging 2025-08-02 18:26:01 +02:00
e6ebac7cda Correct status variable type in XtpMapHardwareMemoryPool 2025-07-30 21:50:36 +02:00
4453b95f5c Correct status variable type in XtpMapHardwareMemoryPool 2025-07-30 21:48:38 +02:00
61d5e36a4e Partially revert previous commit 2025-07-30 17:23:11 +02:00
410b96b58a Zero-initialize Page Directory entries before use 2025-07-30 17:19:37 +02:00
66e136c7d6 Enable paging 2025-07-30 16:58:25 +02:00
d61b48740f Declare CpuRegisters as a local structure instead of a pointer 2025-07-30 16:53:07 +02:00
3607a6d930 Zero-initialize Page Directory entries before use 2025-07-30 16:49:49 +02:00
c8787c3bd6 Zero-initialize Page Directory entries before use 2025-07-30 16:38:17 +02:00
b83c3923da Change artifact URL to show newest builds first for easier access 2025-07-29 18:33:36 +02:00
a694be3795 Ensure all artifacts are published by the pipeline 2025-07-29 18:27:03 +02:00
9eae01cc98 Disable built-in compiler functions 2025-07-29 18:20:20 +02:00
58e3371fac Extend matrix to include release configuration alongside debug 2025-07-29 14:12:02 +02:00
98c3b93c3d Include build type in build dir name 2025-07-29 13:57:47 +02:00
15a81b03d9 Include build type in build dir name and remove misleading symlink 2025-07-29 12:32:31 +02:00
7fce778ee4 Harden BlpDuplicateDevicePath against malformed device paths 2025-07-29 12:15:27 +02:00
b0aabf96b8 Improve device enumeration logic in BlEnumerateBlockDevices
These changes result in a more robust and reliable device enumeration process, better prepared to handle edge cases and non-standard firmware behavior.
2025-07-29 10:44:50 +02:00
486e987b71 Ensure correct boot volume is used by the chainloader 2025-07-29 08:04:33 +02:00
ecaf923e6d Ensure correct boot volume is used to boot XTOS 2025-07-29 08:01:32 +02:00
953de7fb5f Correct default OS selection in boot menu 2025-07-28 21:39:07 +02:00
55ef9bf686 Correct function declaration for BlpFindParentBlockDevice 2025-07-28 19:45:19 +02:00
6823982227 Correctly return parent device in BlpFindParentBlockDevice 2025-07-28 19:43:13 +02:00
ff41b0d4f7 Fix incorrect TSS descriptor limit according to architecture specification 2025-07-28 18:25:47 +02:00
6130a34587 Align stack as required by the ABI 2025-07-28 17:57:16 +02:00
2ca708fe43 Define stack alignment required by the architecture's ABI 2025-07-28 17:53:50 +02:00
d2ce921676 Remove completed item 2025-07-20 16:49:06 +02:00
a81bad32fe Implement scrolling in the boot menu 2025-07-20 16:45:15 +02:00
da3e039a05 Use correct address when clearing COM port buffer
The code was reading from Port->Address to clear the RBR before the field was initialized.
2025-07-20 14:53:04 +02:00
e778a95a01 Use portable affinity mask for the idle process 2025-07-20 12:34:20 +02:00
24b6cc2250 Use portable affinity mask for the idle process
The hardcoded value 0xFFFFFFFF restricted the idle process to the first 32 processors on 64-bit system.
2025-07-20 12:33:10 +02:00
fdf649fcec Correctly initialize the boot stack pointer, as the stack grows downwards 2025-07-19 17:41:38 +02:00
61fcf8e0ec Update readme 2025-07-17 19:58:51 +02:00
d85ed34ce2 Remove duplicated XTchain detection 2025-07-09 10:52:48 +02:00
dcb0b8fb4b Initialize UBSAN mismatch data without relying on memset() 2025-07-09 10:40:15 +02:00
6729d72322 Add missing copyright notice 2025-07-09 10:31:36 +02:00
b229854ae0 Add configuration script for setting up Windows build environment 2025-07-09 10:28:46 +02:00
e0125dda54 Use virtual FAT disk images 2025-01-24 09:19:59 +01:00
7b8f4f15cc Add APIC Logical Destination Register (LDR) shifts and correct APIC delivery mode values 2024-07-23 20:14:06 +02:00
2e7793dc2b Implement HlpGetCpuApicId() routine 2024-07-22 23:31:20 +02:00
2c5b680426 Implement HlpSendIpi() routine 2024-07-22 23:23:55 +02:00
626ece8046 HlReadApicRegister() should return and HlWriteApicRegister() should take ULONGLONG value 2024-07-16 22:36:45 +02:00
088940424d Fix data types and rename some fields to avoid confusion 2024-07-16 16:28:12 +02:00
7abd0f3017 Revert unintentional change 2024-07-14 12:13:56 +02:00
f8519ec09d Rename HlpAcpiSystemInfo global variable to HlpSystemInfo 2024-07-14 12:11:39 +02:00
3bda67be0a Basic ACPI system info initialization code for traversing MADT tables 2024-07-13 21:08:58 +02:00
cb64235953 Use PHYSICAL_ADDRESS data type in MmAllocateHardwareMemory() routine as it is used in MmMapHardwareMemory() as well to avoid the need of data conversion 2024-07-13 15:54:10 +02:00
ceb36ae8ec Add PAGES_TO_SIZE macro definition 2024-07-13 15:39:08 +02:00
94076b7471 Separate image base address per architecture 2024-07-10 22:42:48 +02:00
ebc2607446 Update compiler optimization flags 2024-07-10 17:57:29 +02:00
801cf64f45 Update kernel readme 2024-07-10 16:10:48 +02:00
f52c50242a Correct comment 2024-07-09 22:57:02 +02:00
3f10e1b59e Fix page fault when trying to find ACPI table 2024-07-09 22:47:26 +02:00
47219585d4 Fix pointer operation overflow 2024-07-09 22:40:32 +02:00
e46f2e6116 Ensure that table header is not set before attempting to find ACPI table 2024-07-09 22:36:40 +02:00
3804786e89 All ACPI related structures should be packed 2024-07-07 22:13:34 +02:00
6bcf3e134f Unify naming convention and switch to ULONG in memory map related routines 2024-07-06 22:59:10 +02:00
182 changed files with 10254 additions and 3117 deletions

View File

@@ -7,6 +7,7 @@ jobs:
strategy: strategy:
matrix: matrix:
arch: [amd64, i686] arch: [amd64, i686]
build: [debug, release]
runs-on: oscw runs-on: oscw
container: container:
image: codingworkshop/oscw-runner:latest image: codingworkshop/oscw-runner:latest
@@ -17,7 +18,7 @@ jobs:
fetch-depth: 0 fetch-depth: 0
- name: Build ExectOS - name: Build ExectOS
run: | run: |
echo "charch ${{ matrix.arch }} && ./configure.sh && cd build-${{ matrix.arch }}-xtchain && xbuild -v && xbuild diskimg -v" > build.cmds echo "charch ${{ matrix.arch }} && chbuild ${{ matrix.build }} && ./configure.sh && cd build-${{ matrix.arch }}-${{ matrix.build }} && xbuild -v && xbuild diskimg -v" > build.cmds
xtchain < build.cmds xtchain < build.cmds
- name: Publish binaries - name: Publish binaries
if: ${{ github.ref == 'refs/heads/master' }} if: ${{ github.ref == 'refs/heads/master' }}
@@ -26,8 +27,8 @@ jobs:
OSCW_ARTIFACTS_USERNAME: ${{ secrets.OSCW_ARTIFACTS_USERNAME }} OSCW_ARTIFACTS_USERNAME: ${{ secrets.OSCW_ARTIFACTS_USERNAME }}
OSCW_ARTIFACTS_USERKEY: ${{ secrets.OSCW_ARTIFACTS_USERKEY }} OSCW_ARTIFACTS_USERKEY: ${{ secrets.OSCW_ARTIFACTS_USERKEY }}
run: | run: |
tar -I 'gzip' -cpf ExectOS-$(date +'%Y%m%d')-${GITHUB_SHA:0:10}-${{ matrix.arch }}-bin.tar.gz -C build-${{ matrix.arch }}-xtchain/output/binaries . tar -I 'gzip' -cpf ExectOS-$(date +'%Y%m%d')-${GITHUB_SHA:0:10}-${{ matrix.arch }}-${{ matrix.build }}-bin.tar.gz -C build-${{ matrix.arch }}-${{ matrix.build }}/output/binaries .
tar -I 'gzip' -cpf ExectOS-$(date +'%Y%m%d')-${GITHUB_SHA:0:10}-${{ matrix.arch }}-lib.tar.gz -C build-${{ matrix.arch }}-xtchain/output/library . tar -I 'gzip' -cpf ExectOS-$(date +'%Y%m%d')-${GITHUB_SHA:0:10}-${{ matrix.arch }}-${{ matrix.build }}-lib.tar.gz -C build-${{ matrix.arch }}-${{ matrix.build }}/output/library .
tar -I 'gzip' -cpf ExectOS-$(date +'%Y%m%d')-${GITHUB_SHA:0:10}-${{ matrix.arch }}-sym.tar.gz -C build-${{ matrix.arch }}-xtchain/output/symbols . tar -I 'gzip' -cpf ExectOS-$(date +'%Y%m%d')-${GITHUB_SHA:0:10}-${{ matrix.arch }}-${{ matrix.build }}-sym.tar.gz -C build-${{ matrix.arch }}-${{ matrix.build }}/output/symbols .
gzip -c build-${{ matrix.arch }}-xtchain/output/disk.img > ExectOS-$(date +'%Y%m%d')-${GITHUB_SHA:0:10}-${{ matrix.arch }}.img.gz gzip -c build-${{ matrix.arch }}-${{ matrix.build }}/output/disk.img > ExectOS-$(date +'%Y%m%d')-${GITHUB_SHA:0:10}-${{ matrix.arch }}-${{ matrix.build }}.img.gz
artifact_publish "ExectOS-$(date +'%Y%m%d')-${GITHUB_SHA:0:10}-${{ matrix.arch }}*.gz" ExectOS artifact_publish "ExectOS-$(date +'%Y%m%d')-${GITHUB_SHA:0:10}-${{ matrix.arch }}-${{ matrix.build }}*.gz" ExectOS

View File

@@ -1,8 +1,5 @@
# Detect XTChain toolchain # Minimum CMake version requirement
cmake_minimum_required(VERSION 3.19.0) cmake_minimum_required(VERSION 3.19.0)
if(NOT CMAKE_VERSION MATCHES "XTC")
message(FATAL_ERROR "XTChain not detected or corrupted!")
endif()
# Lowercase target architecture # Lowercase target architecture
string(TOLOWER ${ARCH} ARCH) string(TOLOWER ${ARCH} ARCH)
@@ -44,7 +41,7 @@ set(CMAKE_TOOLCHAIN_FILE "sdk/cmake/toolchain.cmake")
project(EXECTOS) project(EXECTOS)
# Load all the CMake SDK # Load all the CMake SDK
include(sdk/cmake/baseaddress.cmake) include(sdk/cmake/baseaddress/${ARCH}.cmake)
include(sdk/cmake/emulation.cmake) include(sdk/cmake/emulation.cmake)
include(sdk/cmake/functions.cmake) include(sdk/cmake/functions.cmake)
include(sdk/cmake/version.cmake) include(sdk/cmake/version.cmake)

View File

@@ -12,9 +12,6 @@ This is a list of ideas that migh but not must be realized.
- [ ] Rewrite memory mapping and paging support in bootloader to make it more flexible and architecture independent. - [ ] Rewrite memory mapping and paging support in bootloader to make it more flexible and architecture independent.
This should support paging levels, thus allowing to make a use of PML5 on modern AMD64 processors and increasing This should support paging levels, thus allowing to make a use of PML5 on modern AMD64 processors and increasing
the addressable virtual memory from 256TB to 128PB. This is partially done. the addressable virtual memory from 256TB to 128PB. This is partially done.
- [ ] Implement a scrolling mechanism to boot menu allowing to show more boot entries than can fit in the box.
Currently, the limit is not set, nor check, thus adding more menu items will result in positions displayed under
the box.
- [ ] Implement editing boot menu entries directly from the boot menu. Changes should be runtime only (not stored on - [ ] Implement editing boot menu entries directly from the boot menu. Changes should be runtime only (not stored on
disk). disk).

View File

@@ -8,14 +8,14 @@
<a href="https://git.codingworkshop.eu.org/xt-sys/exectos/actions"> <a href="https://git.codingworkshop.eu.org/xt-sys/exectos/actions">
<img alt="Build Status" src="https://codingworkshop.eu.org/actions.php?project=xt-sys/exectos"> <img alt="Build Status" src="https://codingworkshop.eu.org/actions.php?project=xt-sys/exectos">
</a> </a>
<a href="https://artifacts.codingworkshop.eu.org/ExectOS"> <a href="https://artifacts.codingworkshop.eu.org/ExectOS/?C=M&O=D">
<img alt="CI/CD Artifacts" src="https://img.shields.io/badge/Download-%F0%9F%A1%87-blueviolet"> <img alt="CI/CD Artifacts" src="https://img.shields.io/badge/Download-%F0%9F%A1%87-blueviolet">
</a> </a>
<a href="https://git.codingworkshop.eu.org/xt-sys/exectos/src/branch/master/COPYING.md"> <a href="https://git.codingworkshop.eu.org/xt-sys/exectos/src/branch/master/COPYING.md">
<img alt="License" src="https://img.shields.io/badge/License-GPLv3-blue.svg"> <img alt="License" src="https://img.shields.io/badge/License-GPLv3-blue.svg">
</a> </a>
<a href="https://codeium.com/"> <a href="https://exectos.eu.org/ai-assisted">
<img alt="Codeium" src="https://img.shields.io/badge/Powered%20By-Codeium-09B6A2?logo=Codeium"> <img alt="AI Assisted" src="https://img.shields.io/badge/AI-Assisted-darkcyan">
</a> </a>
<a href="https://github.com/sponsors/xt-sys/"> <a href="https://github.com/sponsors/xt-sys/">
<img alt="Sponsor" src="https://img.shields.io/badge/Sponsor-%E2%9D%A4-red?logo=GitHub"> <img alt="Sponsor" src="https://img.shields.io/badge/Sponsor-%E2%9D%A4-red?logo=GitHub">
@@ -69,15 +69,12 @@ design, it requires a modern EFI enabled hardware. It is not possible currently
| xtldr | XTOS boot loader source code | | xtldr | XTOS boot loader source code |
# Build # Build
XTOS can be built only by using [XTChain](https://git.codingworkshop.eu.org/xt-sys/xtchain), a special toolchain XTOS can only be built using [XTchain](https://git.codingworkshop.eu.org/xt-sys/xtchain), a dedicated toolchain designed
prepared for compiling XT software. Currently, there is only a Linux version available, so a Linux distribution or WSL specifically for compiling XT software. XTChain is currently available for both Linux and Windows. Detailed instructions
is needed. If XTChain is already installed and available, then building ExectOS is quiet easy. First, open a terminal on how to configure and run XTChain can be found [here](https://exectos.eu.org/contributing/setting-up-xtchain).
or WSL console and type the following command to launch XTChain build console:
``` With the XTchain environment already running, navigate to the directory containing the ExectOS source code and use the
xtchain following commands to set the target build architecture and configure the sources:
```
While the console is already running, navigate to the directory containing ExectOS source code and use the following
commands to first set target build architecture and configure the sources:
``` ```
charch [i686|amd64] charch [i686|amd64]
chbuild [DEBUG|RELEASE] chbuild [DEBUG|RELEASE]

View File

@@ -40,6 +40,30 @@ SystemPath=multi(0)disk(0)rdisk(0)partition(1)/ExectOS
KernelFile=xtoskrnl.exe KernelFile=xtoskrnl.exe
Parameters=DEBUG=COM1,115200 Parameters=DEBUG=COM1,115200
[ExectOS_FBDEBUG]
SystemName="ExectOS Operating System (FBDEBUG)"
SystemType=XTOS
BootModules=xtos_o
SystemPath=multi(0)disk(0)rdisk(0)partition(1)/ExectOS
KernelFile=xtoskrnl.exe
Parameters=DEBUG=COM1,115200;SCREEN
[ExectOS_NOXPA]
SystemName="ExectOS Operating System (NOXPA)"
SystemType=XTOS
BootModules=xtos_o
SystemPath=multi(0)disk(0)rdisk(0)partition(1)/ExectOS
KernelFile=xtoskrnl.exe
Parameters=DEBUG=COM1,115200 NOXPA
[ExectOS_NOXPA_FBDEBUG]
SystemName="ExectOS Operating System (NOXPA / FBDEBUG)"
SystemType=XTOS
BootModules=xtos_o
SystemPath=multi(0)disk(0)rdisk(0)partition(1)/ExectOS
KernelFile=xtoskrnl.exe
Parameters=DEBUG=COM1,115200;SCREEN NOXPA
[Windows] [Windows]
SystemName="Microsoft Windows 2000" SystemName="Microsoft Windows 2000"
SystemType=NT50 SystemType=NT50

51
configure.ps1 Normal file
View File

@@ -0,0 +1,51 @@
# PROJECT: ExectOS
# LICENSE: See the COPYING.md in the top level directory
# FILE: configure.ps1
# DESCRIPTION: Project configuration script for preparing the build environment
# DEVELOPERS: Aiken Harris <harraiken91@gmail.com>
# Check XTchain
if (-not $env:XTCVER) {
Write-Host "XTChain not detected or corrupted!"
exit 1
}
# Set target architecture
if ($env:TARGET) {
$ARCH = $env:TARGET
} else {
$ARCH = "amd64"
}
# Set target build type
if (-not $env:BUILD_TYPE) {
$env:BUILD_TYPE = "DEBUG"
}
# Set variables
$EXECTOS_SOURCE_DIR = (Get-Location).Path
$EXECTOS_BINARY_DIR = "build-$($ARCH)-$($env:BUILD_TYPE.ToLower())"
# Create directories if needed
if ($EXECTOS_SOURCE_DIR -eq (Get-Location).Path) {
Write-Host "Creating directories in $EXECTOS_BINARY_DIR"
New-Item -ItemType Directory -Path $EXECTOS_BINARY_DIR -Force | Out-Null
Set-Location -Path $EXECTOS_BINARY_DIR
}
# Delete old cache
Remove-Item -Path "CMakeCache.txt" -ErrorAction SilentlyContinue
Remove-Item -Path "host-tools/CMakeCache.txt" -ErrorAction SilentlyContinue
# Configure project using CMake
& cmake -G Ninja -DARCH:STRING=$($ARCH) -DBUILD_TYPE:STRING=$($env:BUILD_TYPE) $EXECTOS_SOURCE_DIR
# Check if configuration succeeded
if ($LASTEXITCODE -ne 0) {
Write-Host "Configure script failed."
exit 1
} else {
"$($ARCH)" | Out-File -Encoding ASCII -NoNewline build.arch
Write-Host "Configure script completed. Enter '$EXECTOS_BINARY_DIR' directory and execute 'xbuild' to build ExectOS."
}

View File

@@ -1,4 +1,10 @@
#!/bin/bash #!/bin/bash
# PROJECT: ExectOS
# LICENSE: See the COPYING.md in the top level directory
# FILE: configure.sh
# DESCRIPTION: Project configuration script for preparing the build environment
# DEVELOPERS: Rafal Kupiec <belliash@codingworkshop.eu.org>
# Check XTCHain # Check XTCHain
if [ "x${XTCVER}" = "x" ]; then if [ "x${XTCVER}" = "x" ]; then
@@ -16,13 +22,12 @@ fi
# Set variables # Set variables
EXECTOS_SOURCE_DIR=$(cd `dirname ${0}` && pwd) EXECTOS_SOURCE_DIR=$(cd `dirname ${0}` && pwd)
EXECTOS_BINARY_DIR=build-${ARCH}-xtchain EXECTOS_BINARY_DIR=build-${ARCH}-${BUILD_TYPE,,}
# Create directories if needed # Create directories if needed
if [ "${EXECTOS_SOURCE_DIR}" = "${PWD}" ]; then if [ "${EXECTOS_SOURCE_DIR}" = "${PWD}" ]; then
echo Creating directories in ${EXECTOS_BINARY_DIR} echo Creating directories in ${EXECTOS_BINARY_DIR}
mkdir -p "${EXECTOS_BINARY_DIR}" mkdir -p "${EXECTOS_BINARY_DIR}"
ln -sf ${EXECTOS_BINARY_DIR} build
cd "${EXECTOS_BINARY_DIR}" cd "${EXECTOS_BINARY_DIR}"
fi fi

View File

@@ -0,0 +1,2 @@
# Set base addresses for all modules
set(BASEADDRESS_XTOSKRNL 0x0000000140000000)

View File

@@ -1,3 +1,2 @@
# Set base addresses for all modules # Set base addresses for all modules
set(BASEADDRESS_XTLDR 0x00010000)
set(BASEADDRESS_XTOSKRNL 0x00400000) set(BASEADDRESS_XTOSKRNL 0x00400000)

View File

@@ -27,22 +27,22 @@ add_custom_target(bochsvm
# This target starts up a QEMU+OVMF virtual machine using KVM accelerator # This target starts up a QEMU+OVMF virtual machine using KVM accelerator
add_custom_target(testkvm add_custom_target(testkvm
DEPENDS diskimg DEPENDS install
COMMAND ${QEMU_COMMAND} -name "ExectOS-${ARCH}-KVM" -machine type=q35,kernel_irqchip=on,accel=kvm,mem-merge=off,vmport=off -enable-kvm -cpu host,-hypervisor,+topoext COMMAND ${QEMU_COMMAND} -name "ExectOS-${ARCH}-KVM" -machine type=q35,kernel_irqchip=on,accel=kvm,mem-merge=off,vmport=off -enable-kvm -cpu host,-hypervisor,+topoext
-smp 2,sockets=1,cores=1,threads=2 -m 4G -overcommit mem-lock=off -rtc clock=host,base=localtime,driftfix=none -smp 2,sockets=1,cores=1,threads=2 -m 4G -overcommit mem-lock=off -rtc clock=host,base=localtime,driftfix=none
-drive file=${EXECTOS_SOURCE_DIR}/sdk/firmware/ovmf_code_${ARCH}.fd,if=pflash,format=raw,unit=0,readonly=on -drive file=${EXECTOS_SOURCE_DIR}/sdk/firmware/ovmf_code_${ARCH}.fd,if=pflash,format=raw,unit=0,readonly=on
-drive file=${EXECTOS_SOURCE_DIR}/sdk/firmware/ovmf_vars_${ARCH}.fd,if=pflash,format=raw,unit=1 -drive file=${EXECTOS_SOURCE_DIR}/sdk/firmware/ovmf_vars_${ARCH}.fd,if=pflash,format=raw,unit=1
-hda ${EXECTOS_BINARY_DIR}/output/disk.img -hda fat:rw:${EXECTOS_BINARY_DIR}/output/binaries
-boot menu=on -d int -M smm=off -no-reboot -no-shutdown -serial stdio -boot menu=on -d int -M smm=off -no-reboot -no-shutdown -serial stdio
VERBATIM USES_TERMINAL) VERBATIM USES_TERMINAL)
# This target starts up a QEMU+OVMF virtual machine using TCG accelerator # This target starts up a QEMU+OVMF virtual machine using TCG accelerator
add_custom_target(testtcg add_custom_target(testtcg
DEPENDS diskimg DEPENDS install
COMMAND ${QEMU_COMMAND} -name "ExectOS-${ARCH}-TCG" -machine type=q35,accel=tcg -cpu max,-hypervisor COMMAND ${QEMU_COMMAND} -name "ExectOS-${ARCH}-TCG" -machine type=q35,accel=tcg -cpu max,-hypervisor
-smp 2,sockets=1,cores=1,threads=2 -m 4G -overcommit mem-lock=off -rtc clock=host,base=localtime,driftfix=none -smp 2,sockets=1,cores=1,threads=2 -m 4G -overcommit mem-lock=off -rtc clock=host,base=localtime,driftfix=none
-drive file=${EXECTOS_SOURCE_DIR}/sdk/firmware/ovmf_code_${ARCH}.fd,if=pflash,format=raw,unit=0,readonly=on -drive file=${EXECTOS_SOURCE_DIR}/sdk/firmware/ovmf_code_${ARCH}.fd,if=pflash,format=raw,unit=0,readonly=on
-drive file=${EXECTOS_SOURCE_DIR}/sdk/firmware/ovmf_vars_${ARCH}.fd,if=pflash,format=raw,unit=1 -drive file=${EXECTOS_SOURCE_DIR}/sdk/firmware/ovmf_vars_${ARCH}.fd,if=pflash,format=raw,unit=1
-hda ${EXECTOS_BINARY_DIR}/output/disk.img -hda fat:rw:${EXECTOS_BINARY_DIR}/output/binaries
-boot menu=on -d int -M smm=off -no-reboot -no-shutdown -serial stdio -boot menu=on -d int -M smm=off -no-reboot -no-shutdown -serial stdio
VERBATIM USES_TERMINAL) VERBATIM USES_TERMINAL)

View File

@@ -20,8 +20,9 @@ set(CMAKE_CXX_EXTENSIONS OFF)
set(CMAKE_C_STANDARD 23) set(CMAKE_C_STANDARD 23)
set(CMAKE_CXX_STANDARD 23) set(CMAKE_CXX_STANDARD 23)
# Disable standard C libraries # Disable standard C and C++ libraries
set(CMAKE_C_STANDARD_LIBRARIES "" CACHE INTERNAL "") set(CMAKE_C_STANDARD_LIBRARIES "" CACHE INTERNAL "")
set(CMAKE_CXX_STANDARD_LIBRARIES "" CACHE INTERNAL "")
# Clean linker flags # Clean linker flags
set(CMAKE_STATIC_LINKER_FLAGS "") set(CMAKE_STATIC_LINKER_FLAGS "")

View File

@@ -11,11 +11,10 @@ endif()
# Set build optimisation # Set build optimisation
if(BUILD_TYPE STREQUAL "DEBUG") if(BUILD_TYPE STREQUAL "DEBUG")
add_compiler_ccxxflags("/Zi") add_compiler_ccxxflags("/GS- /Zi /Ob0 /Od")
add_compiler_ccxxflags("-Ob0 -Od")
add_linker_flags("/DEBUG /INCREMENTAL /OPT:NOREF /OPT:NOICF /PDBSOURCEPATH:build") add_linker_flags("/DEBUG /INCREMENTAL /OPT:NOREF /OPT:NOICF /PDBSOURCEPATH:build")
else() else()
add_compiler_ccxxflags("-Ob2 -Oy") add_compiler_ccxxflags("/GS- /Ob2 /Ot /Ox /Oy")
add_linker_flags("/INCREMENTAL:NO /OPT:REF /OPT:ICF") add_linker_flags("/INCREMENTAL:NO /OPT:REF /OPT:ICF")
endif() endif()
@@ -48,6 +47,9 @@ add_compiler_ccxxflags("-nostdinc -Wno-char-subscripts -Wno-incompatible-library
add_compiler_ccxxflags("-Wno-microsoft-enum-forward-reference -Wno-multichar -Wno-parentheses-equality -Wno-undefined-inline") add_compiler_ccxxflags("-Wno-microsoft-enum-forward-reference -Wno-multichar -Wno-parentheses-equality -Wno-undefined-inline")
add_compiler_ccxxflags("-Wno-gnu-folding-constant") add_compiler_ccxxflags("-Wno-gnu-folding-constant")
# Disable compiler builtins
add_compiler_ccxxflags("-fno-builtin")
# Set debugging symbols output directory # Set debugging symbols output directory
set(CMAKE_PDB_OUTPUT_DIRECTORY "${EXECTOS_BINARY_DIR}/output/symbols") set(CMAKE_PDB_OUTPUT_DIRECTORY "${EXECTOS_BINARY_DIR}/output/symbols")

View File

@@ -1,13 +0,0 @@
## XT Building Kit (XTBK)
The XTBK, or XT Building Kit is a kind of SDK (Software Development Kit) utilized internally by XTOS, the XT Operating
System. It is designed to provide a collection of public functions that are available within the operating system but
not necessarily exposed or accessible to software and driver developers.
Unlike XTDK, which focuses on providing headers for external developers to create kernel mode drivers and user mode
applications, XTBK serves as an extension to XTDK and aids in the code-sharing process between different XTOS
components. This enables the reuse of code across various components of the operating system, resulting in a more
efficient and streamlined development process.
By incorporating XTBK, XTOS can optimize code reuse, particularly in low-level kernel code that can be shared with other
components like the boot loader. This approach helps in reducing code duplication and improving overall code
maintainability. Additionally, it allows for consistent implementation of functionality across different parts of the OS.

View File

@@ -16,26 +16,37 @@
/* Routines used by XTLDR */ /* Routines used by XTLDR */
XTCLINK
XTCDECL XTCDECL
VOID VOID
ArClearInterruptFlag(VOID); ArClearInterruptFlag(VOID);
XTCLINK
XTCDECL XTCDECL
BOOLEAN BOOLEAN
ArCpuId(IN OUT PCPUID_REGISTERS Registers); ArCpuId(IN OUT PCPUID_REGISTERS Registers);
XTCLINK
XTCDECL
VOID
ArEnableExtendedPhysicalAddressing(IN ULONG_PTR PageMap);
XTCLINK
XTCDECL XTCDECL
VOID VOID
ArHalt(VOID); ArHalt(VOID);
XTCLINK
XTCDECL XTCDECL
ULONG_PTR ULONG_PTR
ArReadControlRegister(IN USHORT ControlRegister); ArReadControlRegister(IN USHORT ControlRegister);
XTCLINK
XTCDECL XTCDECL
ULONGLONG ULONGLONG
ArReadModelSpecificRegister(IN ULONG Register); ArReadModelSpecificRegister(IN ULONG Register);
XTCLINK
XTCDECL XTCDECL
VOID VOID
ArWriteControlRegister(IN USHORT ControlRegister, ArWriteControlRegister(IN USHORT ControlRegister,

View File

@@ -39,13 +39,22 @@
#define CR4_PCE 0x00000100 #define CR4_PCE 0x00000100
#define CR4_FXSR 0x00000200 #define CR4_FXSR 0x00000200
#define CR4_XMMEXCPT 0x00000400 #define CR4_XMMEXCPT 0x00000400
#define CR4_UMIP 0x00000800
#define CR4_LA57 0x00001000 #define CR4_LA57 0x00001000
#define CR4_RESERVED1 0x00001800
#define CR4_VMXE 0x00002000 #define CR4_VMXE 0x00002000
#define CR4_SMXE 0x00004000 #define CR4_SMXE 0x00004000
#define CR4_RESERVED2 0x00018000 #define CR4_FSGSBASE 0x00010000
#define CR4_XSAVE 0x00020000 #define CR4_PCIDE 0x00020000
#define CR4_RESERVED3 0xFFFC0000 #define CR4_XSAVE 0x00040000
#define CR4_KL 0x00080000
#define CR4_SMEP 0x00100000
#define CR4_SMAP 0x00200000
#define CR4_PKE 0x00400000
#define CR4_CET 0x00800000
#define CR4_PKS 0x01000000
#define CR4_UINTR 0x02000000
#define CR4_LASS 0x08000000
#define CR4_LAM_SUP 0x10000000
/* Descriptors size */ /* Descriptors size */
#define GDT_ENTRIES 128 #define GDT_ENTRIES 128
@@ -84,6 +93,7 @@
#define X86_MSR_FSBASE 0xC0000100 #define X86_MSR_FSBASE 0xC0000100
#define X86_MSR_GSBASE 0xC0000101 #define X86_MSR_GSBASE 0xC0000101
#define X86_MSR_KERNEL_GSBASE 0xC0000102 #define X86_MSR_KERNEL_GSBASE 0xC0000102
#define X86_MSR_TSC_AUX 0xC0000103
/* Processor features in the EFER MSR */ /* Processor features in the EFER MSR */
#define X86_MSR_EFER_SCE (1 << 0) #define X86_MSR_EFER_SCE (1 << 0)
@@ -91,6 +101,10 @@
#define X86_MSR_EFER_LMA (1 << 10) #define X86_MSR_EFER_LMA (1 << 10)
#define X86_MSR_EFER_NXE (1 << 11) #define X86_MSR_EFER_NXE (1 << 11)
#define X86_MSR_EFER_SVME (1 << 12) #define X86_MSR_EFER_SVME (1 << 12)
#define X86_EFER_LMSLE (1 << 13)
#define X86_EFER_FFXSR (1 << 14)
#define X86_EFER_TCE (1 << 15)
#define X86_EFER_AUTOIBRS (1 << 21)
/* X86 EFLAG bit masks definitions */ /* X86 EFLAG bit masks definitions */
#define X86_EFLAGS_NF_MASK 0x00000000 /* None */ #define X86_EFLAGS_NF_MASK 0x00000000 /* None */
@@ -121,79 +135,255 @@ typedef enum _CPU_VENDOR
CPU_VENDOR_UNKNOWN = 0xFFFFFFFF CPU_VENDOR_UNKNOWN = 0xFFFFFFFF
} CPU_VENDOR, *PCPU_VENDOR; } CPU_VENDOR, *PCPU_VENDOR;
/* CPUID features enumeration list */ /* CPUID extended features (0x80000001) enumeration list */
typedef enum _CPUID_FEATURES typedef enum _CPUID_FEATURES_EXTENDED
{ {
CPUID_FEATURES_ECX_SSE3 = 1 << 0, CPUID_FEATURES_ECX_LAHF_SAHF = 1 << 0,
CPUID_FEATURES_ECX_PCLMUL = 1 << 1, CPUID_FEATURES_ECX_CMP_LEGACY = 1 << 1,
CPUID_FEATURES_ECX_DTES64 = 1 << 2, CPUID_FEATURES_ECX_SVM = 1 << 2,
CPUID_FEATURES_ECX_MONITOR = 1 << 3, CPUID_FEATURES_ECX_EXT_APIC_SPACE = 1 << 3,
CPUID_FEATURES_ECX_DS_CPL = 1 << 4, CPUID_FEATURES_ECX_ALT_MOV_CR8 = 1 << 4,
CPUID_FEATURES_ECX_VMX = 1 << 5, CPUID_FEATURES_ECX_LZCNT = 1 << 5,
CPUID_FEATURES_ECX_SMX = 1 << 6, CPUID_FEATURES_ECX_SSE4A = 1 << 6,
CPUID_FEATURES_ECX_EST = 1 << 7, CPUID_FEATURES_ECX_MISALIGNED_SSE = 1 << 7,
CPUID_FEATURES_ECX_TM2 = 1 << 8, CPUID_FEATURES_ECX_PREFETCHW = 1 << 8,
CPUID_FEATURES_ECX_SSSE3 = 1 << 9, CPUID_FEATURES_ECX_OSVW = 1 << 9,
CPUID_FEATURES_ECX_CID = 1 << 10, CPUID_FEATURES_ECX_IBS = 1 << 10,
CPUID_FEATURES_ECX_SDBG = 1 << 11, CPUID_FEATURES_ECX_XOP = 1 << 11,
CPUID_FEATURES_ECX_FMA = 1 << 12, CPUID_FEATURES_ECX_SKINIT = 1 << 12,
CPUID_FEATURES_ECX_CX16 = 1 << 13, CPUID_FEATURES_ECX_WDT = 1 << 13,
CPUID_FEATURES_ECX_XTPR = 1 << 14, CPUID_FEATURES_ECX_LWP = 1 << 15,
CPUID_FEATURES_ECX_PDCM = 1 << 15, CPUID_FEATURES_ECX_FMA4 = 1 << 16,
CPUID_FEATURES_ECX_PCID = 1 << 17, CPUID_FEATURES_ECX_TCE = 1 << 17,
CPUID_FEATURES_ECX_DCA = 1 << 18, CPUID_FEATURES_ECX_NODEID = 1 << 19,
CPUID_FEATURES_ECX_SSE4_1 = 1 << 19, CPUID_FEATURES_ECX_TBM = 1 << 21,
CPUID_FEATURES_ECX_SSE4_2 = 1 << 20, CPUID_FEATURES_ECX_TOPOLOGY_EXTENSIONS = 1 << 22,
CPUID_FEATURES_ECX_X2APIC = 1 << 21, CPUID_FEATURES_ECX_PERFCTR_EXT_CORE = 1 << 23,
CPUID_FEATURES_ECX_MOVBE = 1 << 22, CPUID_FEATURES_ECX_PERFCTR_EXT_NB = 1 << 24,
CPUID_FEATURES_ECX_POPCNT = 1 << 23, CPUID_FEATURES_ECX_DATA_BREAKPOINT_EXT = 1 << 26,
CPUID_FEATURES_ECX_TSC = 1 << 24, CPUID_FEATURES_ECX_PERF_TSC = 1 << 27,
CPUID_FEATURES_ECX_AES = 1 << 25, CPUID_FEATURES_ECX_PERFCTR_EXT_L2I = 1 << 28,
CPUID_FEATURES_ECX_XSAVE = 1 << 26, CPUID_FEATURES_ECX_MONITORX_MWAITX = 1 << 29,
CPUID_FEATURES_ECX_OSXSAVE = 1 << 27, CPUID_FEATURES_ECX_CODEBP_ADDRMASK_EXT = 1 << 30,
CPUID_FEATURES_ECX_AVX = 1 << 28, CPUID_FEATURES_EDX_SYSCALL_SYSRET = 1 << 11,
CPUID_FEATURES_ECX_F16C = 1 << 29, CPUID_FEATURES_EDX_NX = 1 << 20,
CPUID_FEATURES_ECX_RDRAND = 1 << 30, CPUID_FEATURES_EDX_AMD_MMX_EXT = 1 << 22,
CPUID_FEATURES_ECX_HYPERVISOR = 1 << 31, CPUID_FEATURES_EDX_FFXSR = 1 << 25,
CPUID_FEATURES_EDX_FPU = 1 << 0, CPUID_FEATURES_EDX_1G_PAGES = 1 << 26,
CPUID_FEATURES_EDX_VME = 1 << 1, CPUID_FEATURES_EDX_RDTSCP = 1 << 27,
CPUID_FEATURES_EDX_DE = 1 << 2, CPUID_FEATURES_EDX_LONG_MODE = 1 << 29,
CPUID_FEATURES_EDX_PSE = 1 << 3, CPUID_FEATURES_EDX_3DNOW_EXT = 1 << 30,
CPUID_FEATURES_EDX_TSC = 1 << 4, CPUID_FEATURES_EDX_3DNOW = 1 << 31
CPUID_FEATURES_EDX_MSR = 1 << 5, } CPUID_FEATURES_EXTENDED, *PCPUID_FEATURES_EXTENDED;
CPUID_FEATURES_EDX_PAE = 1 << 6,
CPUID_FEATURES_EDX_MCE = 1 << 7, /* CPUID STD1 features (0x00000001) enumeration list */
CPUID_FEATURES_EDX_CX8 = 1 << 8, typedef enum _CPUID_FEATURES_STANDARD1
CPUID_FEATURES_EDX_APIC = 1 << 9, {
CPUID_FEATURES_EDX_SEP = 1 << 11, CPUID_FEATURES_ECX_SSE3 = 1 << 0,
CPUID_FEATURES_EDX_MTRR = 1 << 12, CPUID_FEATURES_ECX_PCLMUL = 1 << 1,
CPUID_FEATURES_EDX_PGE = 1 << 13, CPUID_FEATURES_ECX_DTES64 = 1 << 2,
CPUID_FEATURES_EDX_MCA = 1 << 14, CPUID_FEATURES_ECX_MONITOR = 1 << 3,
CPUID_FEATURES_EDX_CMOV = 1 << 15, CPUID_FEATURES_ECX_DS_CPL = 1 << 4,
CPUID_FEATURES_EDX_PAT = 1 << 16, CPUID_FEATURES_ECX_VMX = 1 << 5,
CPUID_FEATURES_EDX_PSE36 = 1 << 17, CPUID_FEATURES_ECX_SMX = 1 << 6,
CPUID_FEATURES_EDX_PSN = 1 << 18, CPUID_FEATURES_ECX_EST = 1 << 7,
CPUID_FEATURES_EDX_CLFLUSH = 1 << 19, CPUID_FEATURES_ECX_TM2 = 1 << 8,
CPUID_FEATURES_EDX_DS = 1 << 21, CPUID_FEATURES_ECX_SSSE3 = 1 << 9,
CPUID_FEATURES_EDX_ACPI = 1 << 22, CPUID_FEATURES_ECX_CID = 1 << 10,
CPUID_FEATURES_EDX_MMX = 1 << 23, CPUID_FEATURES_ECX_SDBG = 1 << 11,
CPUID_FEATURES_EDX_FXSR = 1 << 24, CPUID_FEATURES_ECX_FMA = 1 << 12,
CPUID_FEATURES_EDX_SSE = 1 << 25, CPUID_FEATURES_ECX_CX16 = 1 << 13,
CPUID_FEATURES_EDX_SSE2 = 1 << 26, CPUID_FEATURES_ECX_XTPR = 1 << 14,
CPUID_FEATURES_EDX_SS = 1 << 27, CPUID_FEATURES_ECX_PDCM = 1 << 15,
CPUID_FEATURES_EDX_HTT = 1 << 28, CPUID_FEATURES_ECX_PCID = 1 << 17,
CPUID_FEATURES_EDX_TM = 1 << 29, CPUID_FEATURES_ECX_DCA = 1 << 18,
CPUID_FEATURES_EDX_IA64 = 1 << 30, CPUID_FEATURES_ECX_SSE4_1 = 1 << 19,
CPUID_FEATURES_EDX_PBE = 1 << 31 CPUID_FEATURES_ECX_SSE4_2 = 1 << 20,
} CPUID_FEATURES, *PCPUID_FEATURES; CPUID_FEATURES_ECX_X2APIC = 1 << 21,
CPUID_FEATURES_ECX_MOVBE = 1 << 22,
CPUID_FEATURES_ECX_POPCNT = 1 << 23,
CPUID_FEATURES_ECX_TSC = 1 << 24,
CPUID_FEATURES_ECX_AES = 1 << 25,
CPUID_FEATURES_ECX_XSAVE = 1 << 26,
CPUID_FEATURES_ECX_OSXSAVE = 1 << 27,
CPUID_FEATURES_ECX_AVX = 1 << 28,
CPUID_FEATURES_ECX_F16C = 1 << 29,
CPUID_FEATURES_ECX_RDRAND = 1 << 30,
CPUID_FEATURES_ECX_HYPERVISOR = 1 << 31,
CPUID_FEATURES_EDX_FPU = 1 << 0,
CPUID_FEATURES_EDX_VME = 1 << 1,
CPUID_FEATURES_EDX_DE = 1 << 2,
CPUID_FEATURES_EDX_PSE = 1 << 3,
CPUID_FEATURES_EDX_TSC = 1 << 4,
CPUID_FEATURES_EDX_MSR = 1 << 5,
CPUID_FEATURES_EDX_PAE = 1 << 6,
CPUID_FEATURES_EDX_MCE = 1 << 7,
CPUID_FEATURES_EDX_CX8 = 1 << 8,
CPUID_FEATURES_EDX_APIC = 1 << 9,
CPUID_FEATURES_EDX_SEP = 1 << 11,
CPUID_FEATURES_EDX_MTRR = 1 << 12,
CPUID_FEATURES_EDX_PGE = 1 << 13,
CPUID_FEATURES_EDX_MCA = 1 << 14,
CPUID_FEATURES_EDX_CMOV = 1 << 15,
CPUID_FEATURES_EDX_PAT = 1 << 16,
CPUID_FEATURES_EDX_PSE36 = 1 << 17,
CPUID_FEATURES_EDX_PSN = 1 << 18,
CPUID_FEATURES_EDX_CLFLUSH = 1 << 19,
CPUID_FEATURES_EDX_DS = 1 << 21,
CPUID_FEATURES_EDX_ACPI = 1 << 22,
CPUID_FEATURES_EDX_MMX = 1 << 23,
CPUID_FEATURES_EDX_FXSR = 1 << 24,
CPUID_FEATURES_EDX_SSE = 1 << 25,
CPUID_FEATURES_EDX_SSE2 = 1 << 26,
CPUID_FEATURES_EDX_SS = 1 << 27,
CPUID_FEATURES_EDX_HTT = 1 << 28,
CPUID_FEATURES_EDX_TM = 1 << 29,
CPUID_FEATURES_EDX_IA64 = 1 << 30,
CPUID_FEATURES_EDX_PBE = 1 << 31
} CPUID_FEATURES_STANDARD1, *PCPUID_FEATURES_STANDARD1;
/* CPUID STD7 features (0x00000007, subleaf 0) enumeration list */
typedef enum _CPUID_FEATURES_STANDARD7_LEAF0
{
CPUID_FEATURES_EBX_FSGSBASE = 1 << 0,
CPUID_FEATURES_EBX_TSC_ADJUST = 1 << 1,
CPUID_FEATURES_EBX_SGX = 1 << 2,
CPUID_FEATURES_EBX_BMI1 = 1 << 3,
CPUID_FEATURES_EBX_HLE = 1 << 4,
CPUID_FEATURES_EBX_AVX2 = 1 << 5,
CPUID_FEATURES_EBX_FDP_DEPRECATION = 1 << 6,
CPUID_FEATURES_EBX_SMEP = 1 << 7,
CPUID_FEATURES_EBX_BMI2 = 1 << 8,
CPUID_FEATURES_EBX_ERMS = 1 << 9,
CPUID_FEATURES_EBX_INVPCID = 1 << 10,
CPUID_FEATURES_EBX_RTM = 1 << 11,
CPUID_FEATURES_EBX_QOS_MONITORING = 1 << 12,
CPUID_FEATURES_EBX_DEPRECATE_FCS_FDS = 1 << 13,
CPUID_FEATURES_EBX_MPX = 1 << 14,
CPUID_FEATURES_EBX_QOS_ENFORCEMENT = 1 << 15,
CPUID_FEATURES_EBX_AVX512F = 1 << 16,
CPUID_FEATURES_EBX_AVX512DQ = 1 << 17,
CPUID_FEATURES_EBX_RDSEED = 1 << 18,
CPUID_FEATURES_EBX_ADX = 1 << 19,
CPUID_FEATURES_EBX_SMAP = 1 << 20,
CPUID_FEATURES_EBX_AVX512IFMA52 = 1 << 21,
CPUID_FEATURES_EBX_CLFLUSHOPT = 1 << 23,
CPUID_FEATURES_EBX_CLWB = 1 << 24,
CPUID_FEATURES_EBX_PROCESSOR_TRACE = 1 << 25,
CPUID_FEATURES_EBX_AVX512PF = 1 << 26,
CPUID_FEATURES_EBX_AVX512ER = 1 << 27,
CPUID_FEATURES_EBX_AVX512CD = 1 << 28,
CPUID_FEATURES_EBX_SHA = 1 << 29,
CPUID_FEATURES_EBX_AVX512BW = 1 << 30,
CPUID_FEATURES_EBX_AVX512VL = 1 << 31,
CPUID_FEATURES_ECX_PREFETCHWT1 = 1 << 0,
CPUID_FEATURES_ECX_AVX512_VBMI = 1 << 1,
CPUID_FEATURES_ECX_UMIP = 1 << 2,
CPUID_FEATURES_ECX_PKU = 1 << 3,
CPUID_FEATURES_ECX_OSPKE = 1 << 4,
CPUID_FEATURES_ECX_WAITPKG = 1 << 5,
CPUID_FEATURES_ECX_AVX512_VBMI2 = 1 << 6,
CPUID_FEATURES_ECX_CET_SS = 1 << 7,
CPUID_FEATURES_ECX_GFNI = 1 << 8,
CPUID_FEATURES_ECX_VAES = 1 << 9,
CPUID_FEATURES_ECX_VPCLMULQDQ = 1 << 10,
CPUID_FEATURES_ECX_AVX512_VNNI = 1 << 11,
CPUID_FEATURES_ECX_AVX512_BITALG = 1 << 12,
CPUID_FEATURES_ECX_TME = 1 << 13,
CPUID_FEATURES_ECX_AVX512_VPOPCNTDQ = 1 << 14,
CPUID_FEATURES_ECX_LA57 = 1 << 16,
CPUID_FEATURES_ECX_RDPID = 1 << 22,
CPUID_FEATURES_ECX_KEYLOCKER = 1 << 23,
CPUID_FEATURES_ECX_BUS_LOCK_DETECT = 1 << 24,
CPUID_FEATURES_ECX_CLDEMOTE = 1 << 25,
CPUID_FEATURES_ECX_MOVDIRI = 1 << 27,
CPUID_FEATURES_ECX_MOVDIR64B = 1 << 28,
CPUID_FEATURES_ECX_ENQCMD = 1 << 29,
CPUID_FEATURES_ECX_SGX_LAUNCH_CONFIG = 1 << 30,
CPUID_FEATURES_ECX_PKS = 1 << 31,
CPUID_FEATURES_EDX_SGX_KEYS = 1 << 1,
CPUID_FEATURES_EDX_AVX512_4VNNIW = 1 << 2,
CPUID_FEATURES_EDX_AVX512_4FMAPS = 1 << 3,
CPUID_FEATURES_EDX_FAST_SHORT_REP_MOV = 1 << 4,
CPUID_FEATURES_EDX_UINTR = 1 << 5,
CPUID_FEATURES_EDX_AVX512_VPINTERSECT = 1 << 8,
CPUID_FEATURES_EDX_SRBDS_CTRL = 1 << 9,
CPUID_FEATURES_EDX_MD_CLEAR = 1 << 10,
CPUID_FEATURES_EDX_RTM_ALWAYS_ABORT = 1 << 11,
CPUID_FEATURES_EDX_RTM_FORCE_ABORT = 1 << 13,
CPUID_FEATURES_EDX_SERIALIZE = 1 << 14,
CPUID_FEATURES_EDX_HYBRID = 1 << 15,
CPUID_FEATURES_EDX_TSXLDTRK = 1 << 16,
CPUID_FEATURES_EDX_PCONFIG = 1 << 18,
CPUID_FEATURES_EDX_ARCH_LBR = 1 << 19,
CPUID_FEATURES_EDX_CET_IBT = 1 << 20,
CPUID_FEATURES_EDX_AMX_BF16 = 1 << 22,
CPUID_FEATURES_EDX_AVX512_FP16 = 1 << 23,
CPUID_FEATURES_EDX_AMX_TILE = 1 << 24,
CPUID_FEATURES_EDX_AMX_INT8 = 1 << 25,
CPUID_FEATURES_EDX_SCA_IBRS_IBPB = 1 << 26,
CPUID_FEATURES_EDX_SCA_STIBP = 1 << 27,
CPUID_FEATURES_EDX_L1D_FLUSH = 1 << 28,
CPUID_FEATURES_EDX_ARCH_CAPABILITIES_MSR = 1 << 29,
CPUID_FEATURES_EDX_CORE_CAPABILITIES_MSR = 1 << 30,
CPUID_FEATURES_EDX_SCA_SSBD = 1 << 31
} CPUID_FEATURES_STANDARD7_LEAF0, *PCPUID_FEATURES_STANDARD7_LEAF0;
/* CPUID STD7 features (0x00000007, subleaf 1) enumeration list */
typedef enum _CPUID_FEATURES_STANDARD7_LEAF1
{
CPUID_FEATURES_EAX_SHA512 = 1 << 0,
CPUID_FEATURES_EAX_SM3 = 1 << 1,
CPUID_FEATURES_EAX_SM4 = 1 << 2,
CPUID_FEATURES_EAX_RAO_INT = 1 << 3,
CPUID_FEATURES_EAX_AVX_VNNI = 1 << 4,
CPUID_FEATURES_EAX_AVX512_BF16 = 1 << 5,
CPUID_FEATURES_EAX_LASS = 1 << 6,
CPUID_FEATURES_EAX_CMPCCXADD = 1 << 7,
CPUID_FEATURES_EAX_ARCH_PERFMON = 1 << 8,
CPUID_FEATURES_EAX_FAST_ZEROLEN_REP_MOVSB = 1 << 10,
CPUID_FEATURES_EAX_FAST_ZEROLEN_REP_STOSB = 1 << 11,
CPUID_FEATURES_EAX_FAST_ZEROLEN_REP_CMPSB = 1 << 12,
CPUID_FEATURES_EAX_FRED = 1 << 17,
CPUID_FEATURES_EAX_LKGS = 1 << 18,
CPUID_FEATURES_EAX_WRMSRNS = 1 << 19,
CPUID_FEATURES_EAX_NMI_SOURCE_REPORTING = 1 << 20,
CPUID_FEATURES_EAX_AMX_FP16 = 1 << 21,
CPUID_FEATURES_EAX_HRESET = 1 << 22,
CPUID_FEATURES_EAX_AVX_IFMA = 1 << 23,
CPUID_FEATURES_EAX_LAM = 1 << 26,
CPUID_FEATURES_EAX_MSRLIST = 1 << 27,
CPUID_FEATURES_EAX_INVD_DISABLE = 1 << 30,
CPUID_FEATURES_EAX_MOVRS = 1 << 31,
CPUID_FEATURES_EBX_PPIN = 1 << 0,
CPUID_FEATURES_EBX_TSE = 1 << 1,
CPUID_FEATURES_EBX_CPUIDMAXVAL_LIM_RMV = 1 << 3,
CPUID_FEATURES_ECX_MSR_IMM = 1 << 5,
CPUID_FEATURES_EDX_AVX_VNNI_INT8 = 1 << 4,
CPUID_FEATURES_EDX_AVX_NE_CONVERT = 1 << 5,
CPUID_FEATURES_EDX_AMX_COMPLEX = 1 << 8,
CPUID_FEATURES_EDX_AVX_VNNI_INT16 = 1 << 10,
CPUID_FEATURES_EDX_USER_TIMER = 1 << 13,
CPUID_FEATURES_EDX_PREFETCHI = 1 << 14,
CPUID_FEATURES_EDX_USER_MSR = 1 << 15,
CPUID_FEATURES_EDX_UIRET_UIF = 1 << 17,
CPUID_FEATURES_EDX_CET_SSS = 1 << 18,
CPUID_FEATURES_EDX_AVX10 = 1 << 19,
CPUID_FEATURES_EDX_APX = 1 << 21,
CPUID_FEATURES_EDX_MWAIT_AND_LEAF5 = 1 << 23
} CPUID_FEATURES_STANDARD7_LEAF1, *PCPUID_FEATURES_STANDARD7_LEAF1;
/* CPUID requests */ /* CPUID requests */
typedef enum _CPUID_REQUESTS typedef enum _CPUID_REQUESTS
{ {
CPUID_GET_VENDOR_STRING, CPUID_GET_VENDOR_STRING,
CPUID_GET_CPU_FEATURES, CPUID_GET_STANDARD1_FEATURES,
CPUID_GET_TLB, CPUID_GET_TLB_CACHE,
CPUID_GET_SERIAL CPUID_GET_SERIAL,
CPUID_GET_CACHE_TOPOLOGY,
CPUID_GET_MONITOR_MWAIT,
CPUID_GET_POWER_MANAGEMENT,
CPUID_GET_STANDARD7_FEATURES
} CPUID_REQUESTS, *PCPUID_REQUESTS; } CPUID_REQUESTS, *PCPUID_REQUESTS;
/* Processor identification information */ /* Processor identification information */

View File

@@ -16,28 +16,34 @@
/* HAL library routines forward references */ /* HAL library routines forward references */
XTCLINK
XTCDECL XTCDECL
UCHAR UCHAR
HlIoPortInByte(IN USHORT Port); HlIoPortInByte(IN USHORT Port);
XTCLINK
XTCDECL XTCDECL
ULONG ULONG
HlIoPortInLong(IN USHORT Port); HlIoPortInLong(IN USHORT Port);
XTCLINK
XTCDECL XTCDECL
USHORT USHORT
HlIoPortInShort(IN USHORT Port); HlIoPortInShort(IN USHORT Port);
XTCLINK
XTCDECL XTCDECL
VOID VOID
HlIoPortOutByte(IN USHORT Port, HlIoPortOutByte(IN USHORT Port,
IN UCHAR Data); IN UCHAR Data);
XTCLINK
XTCDECL XTCDECL
VOID VOID
HlIoPortOutLong(IN USHORT Port, HlIoPortOutLong(IN USHORT Port,
IN ULONG Value); IN ULONG Value);
XTCLINK
XTCDECL XTCDECL
VOID VOID
HlIoPortOutShort(IN USHORT Port, HlIoPortOutShort(IN USHORT Port,

View File

@@ -42,20 +42,14 @@
#define APIC_DF_FLAT 0xFFFFFFFF #define APIC_DF_FLAT 0xFFFFFFFF
#define APIC_DF_CLUSTER 0x0FFFFFFF #define APIC_DF_CLUSTER 0x0FFFFFFF
/* APIC delivery modes */
#define APIC_DM_FIXED 0
#define APIC_DM_LOWPRIO 1
#define APIC_DM_SMI 2
#define APIC_DM_REMOTE 3
#define APIC_DM_NMI 4
#define APIC_DM_INIT 5
#define APIC_DM_STARTUP 6
#define APIC_DM_EXTINT 7
/* APIC trigger modes */ /* APIC trigger modes */
#define APIC_TGM_EDGE 0 #define APIC_TGM_EDGE 0
#define APIC_TGM_LEVEL 1 #define APIC_TGM_LEVEL 1
/* APIC LDR (Logical Destination Register) shifts */
#define APIC_X2APIC_LDR_SHIFT 16
#define APIC_XAPIC_LDR_SHIFT 24
/* Maximum number of I/O APICs */ /* Maximum number of I/O APICs */
#define APIC_MAX_IOAPICS 64 #define APIC_MAX_IOAPICS 64
@@ -75,6 +69,35 @@
/* Initial stall factor */ /* Initial stall factor */
#define INITIAL_STALL_FACTOR 100 #define INITIAL_STALL_FACTOR 100
/* APIC delivery mode enumeration list */
typedef enum _APIC_DM
{
APIC_DM_FIXED,
APIC_DM_LOWPRIO,
APIC_DM_SMI,
APIC_DM_REMOTE,
APIC_DM_NMI,
APIC_DM_INIT,
APIC_DM_STARTUP,
APIC_DM_EXTINT,
} APIC_DM, *PAPIC_DM;
/* APIC destination short-hand enumeration list */
typedef enum _APIC_DSH
{
APIC_DSH_Destination,
APIC_DSH_Self,
APIC_DSH_AllIncludingSelf,
APIC_DSH_AllExclusingSelf
} APIC_DSH, *PAPIC_DSH;
/* APIC mode list */
typedef enum _APIC_MODE
{
APIC_MODE_COMPAT,
APIC_MODE_X2APIC
} APIC_MODE, *PAPIC_MODE;
/* APIC Register Address Map */ /* APIC Register Address Map */
typedef enum _APIC_REGISTER typedef enum _APIC_REGISTER
{ {
@@ -112,35 +135,6 @@ typedef enum _APIC_REGISTER
APIC_EXT3LVTR = 0x53 /* Extended Interrupt 3 Local Vector Table */ APIC_EXT3LVTR = 0x53 /* Extended Interrupt 3 Local Vector Table */
} APIC_REGISTER, *PAPIC_REGISTER; } APIC_REGISTER, *PAPIC_REGISTER;
/* APIC mode list */
typedef enum _APIC_MODE
{
APIC_MODE_COMPAT,
APIC_MODE_X2APIC
} APIC_MODE, *PAPIC_MODE;
/* APIC destination short-hand enumeration list */
typedef enum _APIC_DSH
{
APIC_DSH_Destination,
APIC_DSH_Self,
APIC_DSH_AllIncludingSelf,
APIC_DSH_AllExclusingSelf
} APIC_DSH, *PAPIC_DSH;
/* APIC message type enumeration list */
typedef enum _APIC_MT
{
APIC_MT_Fixed,
APIC_MT_LowestPriority,
APIC_MT_SMI,
APIC_MT_RemoteRead,
APIC_MT_NMI,
APIC_MT_INIT,
APIC_MT_Startup,
APIC_MT_ExtInt,
} APIC_MT, *PAPIC_MT;
/* I8259 PIC interrupt mode enumeration list */ /* I8259 PIC interrupt mode enumeration list */
typedef enum _PIC_I8259_ICW1_INTERRUPT_MODE typedef enum _PIC_I8259_ICW1_INTERRUPT_MODE
{ {
@@ -213,7 +207,7 @@ typedef union _APIC_COMMAND_REGISTER
struct struct
{ {
ULONGLONG Vector:8; ULONGLONG Vector:8;
ULONGLONG MessageType:3; ULONGLONG DeliveryMode:3;
ULONGLONG DestinationMode:1; ULONGLONG DestinationMode:1;
ULONGLONG DeliveryStatus:1; ULONGLONG DeliveryStatus:1;
ULONGLONG ReservedMBZ:1; ULONGLONG ReservedMBZ:1;
@@ -233,7 +227,7 @@ typedef union _APIC_LVT_REGISTER
struct struct
{ {
ULONG Vector:8; ULONG Vector:8;
ULONG MessageType:3; ULONG DeliveryMode:3;
ULONG Reserved1:1; ULONG Reserved1:1;
ULONG DeliveryStatus:1; ULONG DeliveryStatus:1;
ULONG Reserved2:1; ULONG Reserved2:1;

View File

@@ -18,11 +18,18 @@
#define MM_PAGE_SHIFT 12L #define MM_PAGE_SHIFT 12L
#define MM_PAGE_SIZE 4096 #define MM_PAGE_SIZE 4096
/* Page directory and page base addresses */ /* Page directory and page base addresses for 4-level paging */
#define MM_PTE_BASE 0xFFFFF68000000000UI64 #define MM_PTE_BASE 0xFFFFF68000000000ULL
#define MM_PDE_BASE 0xFFFFF6FB40000000UI64 #define MM_PDE_BASE 0xFFFFF6FB40000000ULL
#define MM_PPE_BASE 0xFFFFF6FB7DA00000UI64 #define MM_PPE_BASE 0xFFFFF6FB7DA00000ULL
#define MM_PXE_BASE 0xFFFFF6FB7DBED000UI64 #define MM_PXE_BASE 0xFFFFF6FB7DBED000ULL
/* Page directory and page base addresses for 5-level paging */
#define MM_PTE_LA57_BASE 0xFFFF000000000000ULL
#define MM_PDE_LA57_BASE 0xFFFF010000000000ULL
#define MM_PPE_LA57_BASE 0xFFFF010800000000ULL
#define MM_PXE_LA57_BASE 0xFFFF010840000000ULL
#define MM_P5E_LA57_BASE 0xFFFF010840200000ULL
/* PTE shift values */ /* PTE shift values */
#define MM_PTE_SHIFT 3 #define MM_PTE_SHIFT 3
@@ -30,7 +37,7 @@
#define MM_PDI_SHIFT 21 #define MM_PDI_SHIFT 21
#define MM_PPI_SHIFT 30 #define MM_PPI_SHIFT 30
#define MM_PXI_SHIFT 39 #define MM_PXI_SHIFT 39
#define MM_LA57_SHIFT 48 #define MM_P5I_SHIFT 48
/* Number of PTEs per page */ /* Number of PTEs per page */
#define MM_PTE_PER_PAGE 512 #define MM_PTE_PER_PAGE 512
@@ -54,7 +61,10 @@
#define MM_HARDWARE_VA_START 0xFFFFFFFFFFC00000ULL #define MM_HARDWARE_VA_START 0xFFFFFFFFFFC00000ULL
/* Maximum physical address used by HAL allocations */ /* Maximum physical address used by HAL allocations */
#define MM_MAXIMUM_PHYSICAL_ADDRESS 0x00000000FFFFFFFF #define MM_MAXIMUM_PHYSICAL_ADDRESS 0x00000000FFFFFFFFULL
/* Trampoline code address */
#define MM_TRAMPOLINE_ADDRESS 0x80000
/* Page size enumeration list */ /* Page size enumeration list */
typedef enum _PAGE_SIZE typedef enum _PAGE_SIZE
@@ -85,6 +95,18 @@ typedef struct _HARDWARE_PTE
ULONGLONG NoExecute:1; ULONGLONG NoExecute:1;
} HARDWARE_PTE, *PHARDWARE_PTE; } HARDWARE_PTE, *PHARDWARE_PTE;
/* Page map information structure definition */
typedef struct _MMPAGEMAP_INFO
{
BOOLEAN Xpa;
ULONGLONG PteBase;
ULONGLONG PdeBase;
ULONGLONG PpeBase;
ULONGLONG PxeBase;
ULONGLONG P5eBase;
ULONG VaBits;
} MMPAGEMAP_INFO, *PMMPAGEMAP_INFO;
/* A Page Table Entry on AMD64 system */ /* A Page Table Entry on AMD64 system */
typedef struct _MMPTE_HARDWARE typedef struct _MMPTE_HARDWARE
{ {

View File

@@ -13,12 +13,15 @@
/* Architecture-specific enumeration lists forward references */ /* Architecture-specific enumeration lists forward references */
typedef enum _APIC_DM APIC_DM, *PAPIC_DM;
typedef enum _APIC_DSH APIC_DSH, *PAPIC_DSH; typedef enum _APIC_DSH APIC_DSH, *PAPIC_DSH;
typedef enum _APIC_MODE APIC_MODE, *PAPIC_MODE; typedef enum _APIC_MODE APIC_MODE, *PAPIC_MODE;
typedef enum _APIC_MT APIC_MT, *PAPIC_MT;
typedef enum _APIC_REGISTER APIC_REGISTER, *PAPIC_REGISTER; typedef enum _APIC_REGISTER APIC_REGISTER, *PAPIC_REGISTER;
typedef enum _CPU_VENDOR CPU_VENDOR, *PCPU_VENDOR; typedef enum _CPU_VENDOR CPU_VENDOR, *PCPU_VENDOR;
typedef enum _CPUID_FEATURES CPUID_FEATURES, *PCPUID_FEATURES; typedef enum _CPUID_FEATURES_EXTENDED CPUID_FEATURES_EXTENDED, *PCPUID_FEATURES_EXTENDED;
typedef enum _CPUID_FEATURES_STANDARD1 CPUID_FEATURES_STANDARD1, *PCPUID_FEATURES_STANDARD1;
typedef enum _CPUID_FEATURES_STANDARD7_LEAF0 CPUID_FEATURES_STANDARD7_LEAF0, *PCPUID_FEATURES_STANDARD7_LEAF0;
typedef enum _CPUID_FEATURES_STANDARD7_LEAF1 CPUID_FEATURES_STANDARD7_LEAF1, *PCPUID_FEATURES_STANDARD7_LEAF1;
typedef enum _CPUID_REQUESTS CPUID_REQUESTS, *PCPUID_REQUESTS; typedef enum _CPUID_REQUESTS CPUID_REQUESTS, *PCPUID_REQUESTS;
typedef enum _PAGE_SIZE PAGE_SIZE, *PPAGE_SIZE; typedef enum _PAGE_SIZE PAGE_SIZE, *PPAGE_SIZE;
typedef enum _PIC_I8259_ICW1_INTERRUPT_MODE PIC_I8259_ICW1_INTERRUPT_MODE, *PPIC_I8259_ICW1_INTERRUPT_MODE; typedef enum _PIC_I8259_ICW1_INTERRUPT_MODE PIC_I8259_ICW1_INTERRUPT_MODE, *PPIC_I8259_ICW1_INTERRUPT_MODE;
@@ -48,6 +51,7 @@ typedef struct _KSWITCH_FRAME KSWITCH_FRAME, *PKSWITCH_FRAME;
typedef struct _KTHREAD_INIT_FRAME KTHREAD_INIT_FRAME, *PKTHREAD_INIT_FRAME; typedef struct _KTHREAD_INIT_FRAME KTHREAD_INIT_FRAME, *PKTHREAD_INIT_FRAME;
typedef struct _KTRAP_FRAME KTRAP_FRAME, *PKTRAP_FRAME; typedef struct _KTRAP_FRAME KTRAP_FRAME, *PKTRAP_FRAME;
typedef struct _KTSS KTSS, *PKTSS; typedef struct _KTSS KTSS, *PKTSS;
typedef struct _MMPAGEMAP_INFO MMPAGEMAP_INFO, *PMMPAGEMAP_INFO;
typedef struct _MMPFN MMPFN, *PMMPFN; typedef struct _MMPFN MMPFN, *PMMPFN;
typedef struct _MMPTE_HARDWARE MMPTE_HARDWARE, *PMMPTE_HARDWARE; typedef struct _MMPTE_HARDWARE MMPTE_HARDWARE, *PMMPTE_HARDWARE;
typedef struct _MMPTE_HARDWARE_LARGEPAGE MMPTE_HARDWARE_LARGEPAGE, *PMMPTE_HARDWARE_LARGEPAGE; typedef struct _MMPTE_HARDWARE_LARGEPAGE MMPTE_HARDWARE_LARGEPAGE, *PMMPTE_HARDWARE_LARGEPAGE;
@@ -63,6 +67,7 @@ typedef union _APIC_BASE_REGISTER APIC_BASE_REGISTER, *PAPIC_BASE_REGISTER;
typedef union _APIC_COMMAND_REGISTER APIC_COMMAND_REGISTER, *PAPIC_COMMAND_REGISTER; typedef union _APIC_COMMAND_REGISTER APIC_COMMAND_REGISTER, *PAPIC_COMMAND_REGISTER;
typedef union _APIC_LVT_REGISTER APIC_LVT_REGISTER, *PAPIC_LVT_REGISTER; typedef union _APIC_LVT_REGISTER APIC_LVT_REGISTER, *PAPIC_LVT_REGISTER;
typedef union _APIC_SPURIOUS_REGISTER APIC_SPURIOUS_REGISTER, *PAPIC_SPURIOUS_REGISTER; typedef union _APIC_SPURIOUS_REGISTER APIC_SPURIOUS_REGISTER, *PAPIC_SPURIOUS_REGISTER;
typedef union _MMPTE MMP5E, *PMMP5E;
typedef union _MMPTE MMPDE, *PMMPDE; typedef union _MMPTE MMPDE, *PMMPDE;
typedef union _MMPTE MMPPE, *PMMPPE; typedef union _MMPTE MMPPE, *PMMPPE;
typedef union _MMPTE MMPTE, *PMMPTE; typedef union _MMPTE MMPTE, *PMMPTE;

View File

@@ -14,6 +14,7 @@
/* XT BootLoader routines forward references */ /* XT BootLoader routines forward references */
XTCLINK
XTCDECL XTCDECL
EFI_STATUS EFI_STATUS
BlGetXtLdrProtocol(IN PEFI_SYSTEM_TABLE SystemTable, BlGetXtLdrProtocol(IN PEFI_SYSTEM_TABLE SystemTable,

View File

@@ -18,10 +18,11 @@
/* EFI XT boot devices */ /* EFI XT boot devices */
#define XTBL_BOOT_DEVICE_UNKNOWN 0x00 #define XTBL_BOOT_DEVICE_UNKNOWN 0x00
#define XTBL_BOOT_DEVICE_CDROM 0x01 #define XTBL_BOOT_DEVICE_ESP 0x01
#define XTBL_BOOT_DEVICE_FLOPPY 0x02 #define XTBL_BOOT_DEVICE_CDROM 0x02
#define XTBL_BOOT_DEVICE_HARDDISK 0x03 #define XTBL_BOOT_DEVICE_FLOPPY 0x04
#define XTBL_BOOT_DEVICE_RAMDISK 0x04 #define XTBL_BOOT_DEVICE_HARDDISK 0x08
#define XTBL_BOOT_DEVICE_RAMDISK 0x10
/* XTLDR Debug Port type definitions */ /* XTLDR Debug Port type definitions */
#define XTBL_DEBUGPORT_SCREEN 1 #define XTBL_DEBUGPORT_SCREEN 1
@@ -43,27 +44,31 @@
typedef LONG (*PBL_GET_MEMTYPE_ROUTINE)(IN EFI_MEMORY_TYPE EfiMemoryType); typedef LONG (*PBL_GET_MEMTYPE_ROUTINE)(IN EFI_MEMORY_TYPE EfiMemoryType);
/* Boot Loader protocol routine pointers */ /* Boot Loader protocol routine pointers */
typedef EFI_STATUS (*PBL_ALLOCATE_PAGES)(IN ULONGLONG Size, OUT PEFI_PHYSICAL_ADDRESS Memory); typedef EFI_STATUS (*PBL_ALLOCATE_PAGES)(IN EFI_ALLOCATE_TYPE AllocationType, IN ULONGLONG Size, OUT PEFI_PHYSICAL_ADDRESS Memory);
typedef EFI_STATUS (*PBL_ALLOCATE_POOL)(IN UINT_PTR Size, OUT PVOID *Memory); typedef EFI_STATUS (*PBL_ALLOCATE_POOL)(IN UINT_PTR Size, OUT PVOID *Memory);
typedef EFI_STATUS (*PBL_BOOTMENU_INITIALIZE_OS_LIST)(OUT PXTBL_BOOTMENU_ITEM *MenuEntries, OUT PULONG EntriesCount, OUT PULONG DefaultId); typedef EFI_STATUS (*PBL_BOOTMENU_INITIALIZE_OS_LIST)(IN ULONG MaxNameLength, OUT PXTBL_BOOTMENU_ITEM *MenuEntries, OUT PULONG EntriesCount, OUT PULONG DefaultId);
typedef BOOLEAN (*PBL_BOOTUTIL_GET_BOOLEAN_PARAMETER)(IN CONST PWCHAR Parameters, IN CONST PWCHAR Needle);
typedef EFI_STATUS (*PBL_BUILD_PAGE_MAP)(IN PXTBL_PAGE_MAPPING PageMap, IN ULONG_PTR SelfMapAddress); typedef EFI_STATUS (*PBL_BUILD_PAGE_MAP)(IN PXTBL_PAGE_MAPPING PageMap, IN ULONG_PTR SelfMapAddress);
typedef EFI_STATUS (*PBL_CLOSE_VOLUME)(IN PEFI_HANDLE VolumeHandle); typedef EFI_STATUS (*PBL_CLOSE_VOLUME)(IN PEFI_HANDLE VolumeHandle);
typedef VOID (*PBL_CLEAR_CONSOLE_LINE)(IN ULONGLONG LineNo); typedef VOID (*PBL_CLEAR_CONSOLE_LINE)(IN ULONGLONG LineNo);
typedef EFI_STATUS (*PBL_CLOSE_XT_PROTOCOL)(IN PEFI_HANDLE Handle, IN PEFI_GUID ProtocolGuid); typedef EFI_STATUS (*PBL_CLOSE_XT_PROTOCOL)(IN PEFI_HANDLE Handle, IN PEFI_GUID ProtocolGuid);
typedef BOOLEAN (*PBL_CONFIG_GET_BOOLEAN_VALUE)(IN CONST PWCHAR ConfigName); typedef BOOLEAN (*PBL_CONFIG_GET_BOOLEAN_VALUE)(IN CONST PWCHAR ConfigName);
typedef PWCHAR (*PBL_CONFIG_GET_VALUE)(IN CONST PWCHAR ConfigName); typedef EFI_STATUS (*PBL_CONFIG_GET_BOOT_OPTION_VALUE)(IN PLIST_ENTRY Options, IN CONST PWCHAR OptionName, OUT PWCHAR *OptionValue);
typedef VOID (*PBL_CONFIG_GET_EDITABLE_OPTIONS)(OUT CONST PWCHAR **OptionsArray, OUT PULONG OptionsCount);
typedef EFI_STATUS (*PBL_CONFIG_GET_VALUE)(IN CONST PWCHAR ConfigName, OUT PWCHAR *ConfigValue);
typedef EFI_STATUS (*PBL_CONFIG_SET_BOOT_OPTION_VALUE)(IN PLIST_ENTRY Options, IN CONST PWCHAR OptionName, IN CONST PWCHAR OptionValue);
typedef VOID (*PBL_CONSOLE_CLEAR_SCREEN)(); typedef VOID (*PBL_CONSOLE_CLEAR_SCREEN)();
typedef VOID (*PBL_CONSOLE_DISABLE_CURSOR)(); typedef VOID (*PBL_CONSOLE_DISABLE_CURSOR)();
typedef VOID (*PBL_CONSOLE_ENABLE_CURSOR)(); typedef VOID (*PBL_CONSOLE_ENABLE_CURSOR)();
typedef VOID (*PBL_CONSOLE_PRINT)(IN PUSHORT Format, IN ...); typedef VOID (*PBL_CONSOLE_PRINT)(IN PCWSTR Format, IN ...);
typedef VOID (*PBL_CONSOLE_QUERY_MODE)(OUT PUINT_PTR ResX, OUT PUINT_PTR ResY); typedef VOID (*PBL_CONSOLE_QUERY_MODE)(OUT PUINT_PTR ResX, OUT PUINT_PTR ResY);
typedef VOID (*PBL_CONSOLE_READ_KEY_STROKE)(OUT PEFI_INPUT_KEY Key); typedef VOID (*PBL_CONSOLE_READ_KEY_STROKE)(OUT PEFI_INPUT_KEY Key);
typedef VOID (*PBL_CONSOLE_RESET_INPUT_BUFFER)(); typedef VOID (*PBL_CONSOLE_RESET_INPUT_BUFFER)();
typedef VOID (*PBL_CONSOLE_SET_ATTRIBUTES)(IN ULONGLONG Attributes); typedef VOID (*PBL_CONSOLE_SET_ATTRIBUTES)(IN ULONGLONG Attributes);
typedef VOID (*PBL_CONSOLE_SET_CURSOR_POSITION)(IN ULONGLONG PosX, IN ULONGLONG PosY); typedef VOID (*PBL_CONSOLE_SET_CURSOR_POSITION)(IN ULONGLONG PosX, IN ULONGLONG PosY);
typedef VOID (*PBL_CONSOLE_WRITE)(IN PUSHORT String); typedef VOID (*PBL_CONSOLE_WRITE)(IN PCWSTR String);
typedef VOID (XTAPI *PBL_COPY_MEMORY)(OUT PVOID Destination, IN PCVOID Source, IN SIZE_T Length); typedef VOID (XTAPI *PBL_COPY_MEMORY)(OUT PVOID Destination, IN PCVOID Source, IN SIZE_T Length);
typedef VOID (*PBL_DEBUG_PRINT)(IN PUSHORT Format, IN ...); typedef VOID (*PBL_DEBUG_PRINT)(IN PCWSTR Format, IN ...);
typedef EFI_STATUS (*PBL_ENTER_FIRMWARE_SETUP)(); typedef EFI_STATUS (*PBL_ENTER_FIRMWARE_SETUP)();
typedef EFI_STATUS (*PBL_EXIT_BOOT_SERVICES)(); typedef EFI_STATUS (*PBL_EXIT_BOOT_SERVICES)();
typedef EFI_STATUS (*PBL_FIND_BOOT_PROTOCOL)(IN PWCHAR SystemType, OUT PEFI_GUID BootProtocolGuid); typedef EFI_STATUS (*PBL_FIND_BOOT_PROTOCOL)(IN PWCHAR SystemType, OUT PEFI_GUID BootProtocolGuid);
@@ -84,7 +89,7 @@ typedef EFI_STATUS (*PBL_INVOKE_BOOT_PROTOCOL)(IN PWCHAR ShortName, IN PLIST_ENT
typedef EFI_STATUS (*PBL_LOCATE_PROTOCOL_HANDLES)(OUT PEFI_HANDLE *Handles, OUT PUINT_PTR Count, IN PEFI_GUID ProtocolGuid); typedef EFI_STATUS (*PBL_LOCATE_PROTOCOL_HANDLES)(OUT PEFI_HANDLE *Handles, OUT PUINT_PTR Count, IN PEFI_GUID ProtocolGuid);
typedef EFI_STATUS (*PBL_LOAD_EFI_IMAGE)(IN PEFI_DEVICE_PATH_PROTOCOL DevicePath, IN PVOID ImageData, IN SIZE_T ImageSize, OUT PEFI_HANDLE ImageHandle); typedef EFI_STATUS (*PBL_LOAD_EFI_IMAGE)(IN PEFI_DEVICE_PATH_PROTOCOL DevicePath, IN PVOID ImageData, IN SIZE_T ImageSize, OUT PEFI_HANDLE ImageHandle);
typedef EFI_STATUS (*PBL_MAP_EFI_MEMORY)(IN OUT PXTBL_PAGE_MAPPING PageMap, IN OUT PVOID *MemoryMapAddress, IN PBL_GET_MEMTYPE_ROUTINE GetMemoryTypeRoutine); typedef EFI_STATUS (*PBL_MAP_EFI_MEMORY)(IN OUT PXTBL_PAGE_MAPPING PageMap, IN OUT PVOID *MemoryMapAddress, IN PBL_GET_MEMTYPE_ROUTINE GetMemoryTypeRoutine);
typedef EFI_STATUS (*PBL_MAP_PAGE)(IN PXTBL_PAGE_MAPPING PageMap, IN UINT_PTR VirtualAddress, IN UINT_PTR PhysicalAddress, IN UINT NumberOfPages); typedef EFI_STATUS (*PBL_MAP_PAGE)(IN PXTBL_PAGE_MAPPING PageMap, IN ULONG_PTR VirtualAddress, IN ULONG_PTR PhysicalAddress, IN ULONG NumberOfPages);
typedef EFI_STATUS (*PBL_MAP_VIRTUAL_MEMORY)(IN OUT PXTBL_PAGE_MAPPING PageMap, IN PVOID VirtualAddress, IN PVOID PhysicalAddress, IN ULONGLONG NumberOfPages, IN LOADER_MEMORY_TYPE MemoryType); typedef EFI_STATUS (*PBL_MAP_VIRTUAL_MEMORY)(IN OUT PXTBL_PAGE_MAPPING PageMap, IN PVOID VirtualAddress, IN PVOID PhysicalAddress, IN ULONGLONG NumberOfPages, IN LOADER_MEMORY_TYPE MemoryType);
typedef EFI_STATUS (*PBL_OPEN_VOLUME)(IN PEFI_DEVICE_PATH_PROTOCOL DevicePath, OUT PEFI_HANDLE DiskHandle, OUT PEFI_FILE_HANDLE *FsHandle); typedef EFI_STATUS (*PBL_OPEN_VOLUME)(IN PEFI_DEVICE_PATH_PROTOCOL DevicePath, OUT PEFI_HANDLE DiskHandle, OUT PEFI_FILE_HANDLE *FsHandle);
typedef EFI_STATUS (*PBL_OPEN_PROTOCOL)(OUT PEFI_HANDLE Handle, OUT PVOID *ProtocolHandler, IN PEFI_GUID ProtocolGuid); typedef EFI_STATUS (*PBL_OPEN_PROTOCOL)(OUT PEFI_HANDLE Handle, OUT PVOID *ProtocolHandler, IN PEFI_GUID ProtocolGuid);
@@ -152,6 +157,7 @@ typedef struct _XTBL_BOOT_PARAMETERS
typedef struct _XTBL_BOOTMENU_ITEM typedef struct _XTBL_BOOTMENU_ITEM
{ {
PWCHAR EntryName; PWCHAR EntryName;
PWCHAR FullName;
PWCHAR ShortName; PWCHAR ShortName;
PLIST_ENTRY Options; PLIST_ENTRY Options;
} XTBL_BOOTMENU_ITEM, *PXTBL_BOOTMENU_ITEM; } XTBL_BOOTMENU_ITEM, *PXTBL_BOOTMENU_ITEM;
@@ -354,9 +360,16 @@ typedef struct _XTBL_LOADER_PROTOCOL
PBL_REGISTER_BOOT_PROTOCOL RegisterProtocol; PBL_REGISTER_BOOT_PROTOCOL RegisterProtocol;
} Boot; } Boot;
struct struct
{
PBL_BOOTUTIL_GET_BOOLEAN_PARAMETER GetBooleanParameter;
} BootUtil;
struct
{ {
PBL_CONFIG_GET_BOOLEAN_VALUE GetBooleanValue; PBL_CONFIG_GET_BOOLEAN_VALUE GetBooleanValue;
PBL_CONFIG_GET_BOOT_OPTION_VALUE GetBootOptionValue;
PBL_CONFIG_GET_EDITABLE_OPTIONS GetEditableOptions;
PBL_CONFIG_GET_VALUE GetValue; PBL_CONFIG_GET_VALUE GetValue;
PBL_CONFIG_SET_BOOT_OPTION_VALUE SetBootOptionValue;
} Config; } Config;
struct struct
{ {

View File

@@ -14,26 +14,32 @@
/* Kernel Executive routines forward references */ /* Kernel Executive routines forward references */
XTCLINK
XTFASTCALL XTFASTCALL
BOOLEAN BOOLEAN
ExAcquireRundownProtection(IN PEX_RUNDOWN_REFERENCE Descriptor); ExAcquireRundownProtection(IN PEX_RUNDOWN_REFERENCE Descriptor);
XTCLINK
XTFASTCALL XTFASTCALL
VOID VOID
ExCompleteRundownProtection(IN PEX_RUNDOWN_REFERENCE Descriptor); ExCompleteRundownProtection(IN PEX_RUNDOWN_REFERENCE Descriptor);
XTCLINK
XTFASTCALL XTFASTCALL
VOID VOID
ExInitializeRundownProtection(IN PEX_RUNDOWN_REFERENCE Descriptor); ExInitializeRundownProtection(IN PEX_RUNDOWN_REFERENCE Descriptor);
XTCLINK
XTFASTCALL XTFASTCALL
VOID VOID
ExReInitializeRundownProtection(IN PEX_RUNDOWN_REFERENCE Descriptor); ExReInitializeRundownProtection(IN PEX_RUNDOWN_REFERENCE Descriptor);
XTCLINK
XTFASTCALL XTFASTCALL
VOID VOID
ExReleaseRundownProtection(IN PEX_RUNDOWN_REFERENCE Descriptor); ExReleaseRundownProtection(IN PEX_RUNDOWN_REFERENCE Descriptor);
XTCLINK
XTFASTCALL XTFASTCALL
VOID VOID
ExWaitForRundownProtectionRelease(IN PEX_RUNDOWN_REFERENCE Descriptor); ExWaitForRundownProtectionRelease(IN PEX_RUNDOWN_REFERENCE Descriptor);

View File

@@ -15,11 +15,13 @@
/* Routines used by XTLDR */ /* Routines used by XTLDR */
XTCLINK
XTCDECL XTCDECL
XTSTATUS XTSTATUS
HlComPortPutByte(IN PCPPORT Port, HlComPortPutByte(IN PCPPORT Port,
IN UCHAR Byte); IN UCHAR Byte);
XTCLINK
XTCDECL XTCDECL
XTSTATUS XTSTATUS
HlInitializeComPort(IN OUT PCPPORT Port, HlInitializeComPort(IN OUT PCPPORT Port,

View File

@@ -187,7 +187,7 @@ typedef struct _GENERIC_ADDRESS
UCHAR BitOffset; UCHAR BitOffset;
UCHAR Reserved; UCHAR Reserved;
PHYSICAL_ADDRESS Address; PHYSICAL_ADDRESS Address;
} GENERIC_ADDRESS, *PGENERIC_ADDRESS; } PACKED GENERIC_ADDRESS, *PGENERIC_ADDRESS;
/* Each ACPI table description header structure */ /* Each ACPI table description header structure */
typedef struct _ACPI_DESCRIPTION_HEADER typedef struct _ACPI_DESCRIPTION_HEADER
@@ -201,14 +201,14 @@ typedef struct _ACPI_DESCRIPTION_HEADER
ULONG OemRevision; ULONG OemRevision;
UCHAR CreatorID[4]; UCHAR CreatorID[4];
ULONG CreatorRev; ULONG CreatorRev;
} ACPI_DESCRIPTION_HEADER, *PACPI_DESCRIPTION_HEADER; } PACKED ACPI_DESCRIPTION_HEADER, *PACPI_DESCRIPTION_HEADER;
/* Each ACPI subtable description header structure */ /* Each ACPI subtable description header structure */
typedef struct _ACPI_SUBTABLE_HEADER typedef struct _ACPI_SUBTABLE_HEADER
{ {
UCHAR Type; UCHAR Type;
UCHAR Length; UCHAR Length;
} ACPI_SUBTABLE_HEADER, *PACPI_SUBTABLE_HEADER; } PACKED ACPI_SUBTABLE_HEADER, *PACPI_SUBTABLE_HEADER;
/* ACPI cache list structure */ /* ACPI cache list structure */
typedef struct _ACPI_CACHE_LIST typedef struct _ACPI_CACHE_LIST
@@ -229,14 +229,14 @@ typedef struct _ACPI_RSDP
ULONGLONG XsdtAddress; ULONGLONG XsdtAddress;
UCHAR XChecksum; UCHAR XChecksum;
UCHAR Reserved[3]; UCHAR Reserved[3];
} ACPI_RSDP, *PACPI_RSDP; } PACKED ACPI_RSDP, *PACPI_RSDP;
/* ACPI Root System Description Table (RSDT) structure */ /* ACPI Root System Description Table (RSDT) structure */
typedef struct _ACPI_RSDT typedef struct _ACPI_RSDT
{ {
ACPI_DESCRIPTION_HEADER Header; ACPI_DESCRIPTION_HEADER Header;
ULONG Tables[]; ULONG Tables[];
} ACPI_RSDT, *PACPI_RSDT; } PACKED ACPI_RSDT, *PACPI_RSDT;
/* ACPI eXtended Root System Description Table (XSDT) structure */ /* ACPI eXtended Root System Description Table (XSDT) structure */
typedef struct _ACPI_XSDT typedef struct _ACPI_XSDT
@@ -303,7 +303,7 @@ typedef struct _ACPI_FADT
GENERIC_ADDRESS XGp1Blk; GENERIC_ADDRESS XGp1Blk;
GENERIC_ADDRESS SleepControlReg; GENERIC_ADDRESS SleepControlReg;
GENERIC_ADDRESS SleepStatusReg; GENERIC_ADDRESS SleepStatusReg;
} ACPI_FADT, *PACPI_FADT; } PACKED ACPI_FADT, *PACPI_FADT;
/* ACPI Multiple APIC Description Table (MADT) structure */ /* ACPI Multiple APIC Description Table (MADT) structure */
typedef struct _ACPI_MADT typedef struct _ACPI_MADT
@@ -312,26 +312,26 @@ typedef struct _ACPI_MADT
ULONG LocalApicAddress; ULONG LocalApicAddress;
ULONG Flags; ULONG Flags;
ULONG ApicTables[]; ULONG ApicTables[];
} ACPI_MADT, *PACPI_MADT; } PACKED ACPI_MADT, *PACPI_MADT;
/* ACPI Local APIC MADT subtable structure */ /* ACPI Local APIC MADT subtable structure */
typedef struct _ACPI_MADT_LOCAL_APIC typedef struct _ACPI_MADT_LOCAL_APIC
{ {
ACPI_SUBTABLE_HEADER Header; ACPI_SUBTABLE_HEADER Header;
UCHAR ProcessorId; UCHAR AcpiId;
UCHAR Id; UCHAR ApicId;
ULONG LapicFlags; ULONG Flags;
} ACPI_MADT_LOCAL_APIC, *PACPI_MADT_LOCAL_APIC; } PACKED ACPI_MADT_LOCAL_APIC, *PACPI_MADT_LOCAL_APIC;
/* ACPI Local X2APIC MADT subtable structure */ /* ACPI Local X2APIC MADT subtable structure */
typedef struct _ACPI_MADT_LOCAL_X2APIC typedef struct _ACPI_MADT_LOCAL_X2APIC
{ {
ACPI_SUBTABLE_HEADER Header; ACPI_SUBTABLE_HEADER Header;
USHORT Reserved; USHORT Reserved;
ULONG Id; ULONG ApicId;
ULONG LapicFlags; ULONG Flags;
ULONG ProcessorId; ULONG AcpiId;
} ACPI_MADT_LOCAL_X2APIC, *PACPI_MADT_LOCAL_X2APIC; } PACKED ACPI_MADT_LOCAL_X2APIC, *PACPI_MADT_LOCAL_X2APIC;
/* ACPI System Information structure */ /* ACPI System Information structure */
typedef struct _ACPI_SYSTEM_INFO typedef struct _ACPI_SYSTEM_INFO
@@ -342,12 +342,12 @@ typedef struct _ACPI_SYSTEM_INFO
ULONG IoApicCount; ULONG IoApicCount;
ULONG IntiCount; ULONG IntiCount;
ULONG LintiCount; ULONG LintiCount;
ULONG ImcrPresent; BOOLEAN ImcrPresent;
ULONG ApicBase; ULONG ApicBase;
PPROCESSOR_IDENTITY CpuInfo; PPROCESSOR_IDENTITY CpuInfo;
ULONG IoApicPhysicalBase[APIC_MAX_IOAPICS]; ULONG IoApicPhysicalBase[APIC_MAX_IOAPICS];
PULONG IoApicVirtualBase[APIC_MAX_IOAPICS]; ULONG IoApicVirtualBase[APIC_MAX_IOAPICS];
ULONG IoApicIntiBase[APIC_MAX_IOAPICS]; ULONG IoApicVectorBase[APIC_MAX_IOAPICS];
} ACPI_SYSTEM_INFO, *PACPI_SYSTEM_INFO; } ACPI_SYSTEM_INFO, *PACPI_SYSTEM_INFO;
/* ACPI Timer information structure */ /* ACPI Timer information structure */
@@ -357,16 +357,17 @@ typedef struct _ACPI_TIMER_INFO
ULONG MsbMask; ULONG MsbMask;
} ACPI_TIMER_INFO, *PACPI_TIMER_INFO; } ACPI_TIMER_INFO, *PACPI_TIMER_INFO;
/* Serial (COM) port initial state */ /* Serial (COM) port state */
typedef struct _CPPORT typedef struct _CPPORT
{ {
PUCHAR Address; PUCHAR Address;
ULONG Baud; ULONG Baud;
USHORT Flags; USHORT Flags;
UCHAR Ring;
} CPPORT, *PCPPORT; } CPPORT, *PCPPORT;
/* HAL framebuffer data structure */ /* Framebuffer data structure */
typedef struct _HAL_FRAMEBUFFER_DATA typedef struct _HL_FRAMEBUFFER_DATA
{ {
BOOLEAN Initialized; BOOLEAN Initialized;
PVOID Address; PVOID Address;
@@ -374,7 +375,7 @@ typedef struct _HAL_FRAMEBUFFER_DATA
UINT Width; UINT Width;
UINT Height; UINT Height;
UINT PixelsPerScanLine; UINT PixelsPerScanLine;
UINT BitsPerPixel; UINT BytesPerPixel;
UINT Pitch; UINT Pitch;
PVOID Font; PVOID Font;
struct struct
@@ -388,14 +389,29 @@ typedef struct _HAL_FRAMEBUFFER_DATA
USHORT ReservedShift; USHORT ReservedShift;
USHORT ReservedSize; USHORT ReservedSize;
} Pixels; } Pixels;
} HAL_FRAMEBUFFER_DATA, *PHAL_FRAMEBUFFER_DATA; } HL_FRAMEBUFFER_DATA, *PHL_FRAMEBUFFER_DATA;
/* Scroll region data structure */
typedef struct _HL_SCROLL_REGION_DATA
{
ULONG Left;
ULONG Top;
ULONG Right;
ULONG Bottom;
ULONG WidthInChars;
ULONG HeightInChars;
ULONG CursorX;
ULONG CursorY;
ULONG BackgroundColor;
ULONG TextColor;
} HL_SCROLL_REGION_DATA, *PHL_SCROLL_REGION_DATA;
/* Processor identity structure */ /* Processor identity structure */
typedef struct _PROCESSOR_IDENTITY typedef struct _PROCESSOR_IDENTITY
{ {
UCHAR Id; ULONG AcpiId;
UCHAR CpuId; ULONG ApicId;
UCHAR CpuNumber; USHORT CpuNumber;
BOOLEAN Bsp; BOOLEAN Bsp;
BOOLEAN Started; BOOLEAN Started;
} PROCESSOR_IDENTITY, *PPROCESSOR_IDENTITY; } PROCESSOR_IDENTITY, *PPROCESSOR_IDENTITY;

View File

@@ -16,26 +16,32 @@
/* Routines used by XTLDR */ /* Routines used by XTLDR */
XTCLINK
XTCDECL XTCDECL
VOID VOID
ArClearInterruptFlag(VOID); ArClearInterruptFlag(VOID);
XTCLINK
XTCDECL XTCDECL
BOOLEAN BOOLEAN
ArCpuId(IN OUT PCPUID_REGISTERS Registers); ArCpuId(IN OUT PCPUID_REGISTERS Registers);
XTCLINK
XTCDECL XTCDECL
VOID VOID
ArHalt(VOID); ArHalt(VOID);
XTCLINK
XTCDECL XTCDECL
ULONG_PTR ULONG_PTR
ArReadControlRegister(IN USHORT ControlRegister); ArReadControlRegister(IN USHORT ControlRegister);
XTCLINK
XTCDECL XTCDECL
ULONGLONG ULONGLONG
ArReadModelSpecificRegister(IN ULONG Register); ArReadModelSpecificRegister(IN ULONG Register);
XTCLINK
XTCDECL XTCDECL
VOID VOID
ArWriteControlRegister(IN USHORT ControlRegister, ArWriteControlRegister(IN USHORT ControlRegister,

View File

@@ -39,13 +39,22 @@
#define CR4_PCE 0x00000100 #define CR4_PCE 0x00000100
#define CR4_FXSR 0x00000200 #define CR4_FXSR 0x00000200
#define CR4_XMMEXCPT 0x00000400 #define CR4_XMMEXCPT 0x00000400
#define CR4_UMIP 0x00000800
#define CR4_LA57 0x00001000 #define CR4_LA57 0x00001000
#define CR4_RESERVED1 0x00001800
#define CR4_VMXE 0x00002000 #define CR4_VMXE 0x00002000
#define CR4_SMXE 0x00004000 #define CR4_SMXE 0x00004000
#define CR4_RESERVED2 0x00018000 #define CR4_FSGSBASE 0x00010000
#define CR4_XSAVE 0x00020000 #define CR4_PCIDE 0x00020000
#define CR4_RESERVED3 0xFFFC0000 #define CR4_XSAVE 0x00040000
#define CR4_KL 0x00080000
#define CR4_SMEP 0x00100000
#define CR4_SMAP 0x00200000
#define CR4_PKE 0x00400000
#define CR4_CET 0x00800000
#define CR4_PKS 0x01000000
#define CR4_UINTR 0x02000000
#define CR4_LASS 0x08000000
#define CR4_LAM_SUP 0x10000000
/* Descriptors size */ /* Descriptors size */
#define GDT_ENTRIES 128 #define GDT_ENTRIES 128
@@ -91,79 +100,255 @@ typedef enum _CPU_VENDOR
CPU_VENDOR_UNKNOWN = 0xFFFFFFFF CPU_VENDOR_UNKNOWN = 0xFFFFFFFF
} CPU_VENDOR, *PCPU_VENDOR; } CPU_VENDOR, *PCPU_VENDOR;
/* CPUID features enumeration list */ /* CPUID extended features (0x80000001) enumeration list */
typedef enum _CPUID_FEATURES typedef enum _CPUID_FEATURES_EXTENDED
{ {
CPUID_FEATURES_ECX_SSE3 = 1 << 0, CPUID_FEATURES_ECX_LAHF_SAHF = 1 << 0,
CPUID_FEATURES_ECX_PCLMUL = 1 << 1, CPUID_FEATURES_ECX_CMP_LEGACY = 1 << 1,
CPUID_FEATURES_ECX_DTES64 = 1 << 2, CPUID_FEATURES_ECX_SVM = 1 << 2,
CPUID_FEATURES_ECX_MONITOR = 1 << 3, CPUID_FEATURES_ECX_EXT_APIC_SPACE = 1 << 3,
CPUID_FEATURES_ECX_DS_CPL = 1 << 4, CPUID_FEATURES_ECX_ALT_MOV_CR8 = 1 << 4,
CPUID_FEATURES_ECX_VMX = 1 << 5, CPUID_FEATURES_ECX_LZCNT = 1 << 5,
CPUID_FEATURES_ECX_SMX = 1 << 6, CPUID_FEATURES_ECX_SSE4A = 1 << 6,
CPUID_FEATURES_ECX_EST = 1 << 7, CPUID_FEATURES_ECX_MISALIGNED_SSE = 1 << 7,
CPUID_FEATURES_ECX_TM2 = 1 << 8, CPUID_FEATURES_ECX_PREFETCHW = 1 << 8,
CPUID_FEATURES_ECX_SSSE3 = 1 << 9, CPUID_FEATURES_ECX_OSVW = 1 << 9,
CPUID_FEATURES_ECX_CID = 1 << 10, CPUID_FEATURES_ECX_IBS = 1 << 10,
CPUID_FEATURES_ECX_SDBG = 1 << 11, CPUID_FEATURES_ECX_XOP = 1 << 11,
CPUID_FEATURES_ECX_FMA = 1 << 12, CPUID_FEATURES_ECX_SKINIT = 1 << 12,
CPUID_FEATURES_ECX_CX16 = 1 << 13, CPUID_FEATURES_ECX_WDT = 1 << 13,
CPUID_FEATURES_ECX_XTPR = 1 << 14, CPUID_FEATURES_ECX_LWP = 1 << 15,
CPUID_FEATURES_ECX_PDCM = 1 << 15, CPUID_FEATURES_ECX_FMA4 = 1 << 16,
CPUID_FEATURES_ECX_PCID = 1 << 17, CPUID_FEATURES_ECX_TCE = 1 << 17,
CPUID_FEATURES_ECX_DCA = 1 << 18, CPUID_FEATURES_ECX_NODEID = 1 << 19,
CPUID_FEATURES_ECX_SSE4_1 = 1 << 19, CPUID_FEATURES_ECX_TBM = 1 << 21,
CPUID_FEATURES_ECX_SSE4_2 = 1 << 20, CPUID_FEATURES_ECX_TOPOLOGY_EXTENSIONS = 1 << 22,
CPUID_FEATURES_ECX_X2APIC = 1 << 21, CPUID_FEATURES_ECX_PERFCTR_EXT_CORE = 1 << 23,
CPUID_FEATURES_ECX_MOVBE = 1 << 22, CPUID_FEATURES_ECX_PERFCTR_EXT_NB = 1 << 24,
CPUID_FEATURES_ECX_POPCNT = 1 << 23, CPUID_FEATURES_ECX_DATA_BREAKPOINT_EXT = 1 << 26,
CPUID_FEATURES_ECX_TSC = 1 << 24, CPUID_FEATURES_ECX_PERF_TSC = 1 << 27,
CPUID_FEATURES_ECX_AES = 1 << 25, CPUID_FEATURES_ECX_PERFCTR_EXT_L2I = 1 << 28,
CPUID_FEATURES_ECX_XSAVE = 1 << 26, CPUID_FEATURES_ECX_MONITORX_MWAITX = 1 << 29,
CPUID_FEATURES_ECX_OSXSAVE = 1 << 27, CPUID_FEATURES_ECX_CODEBP_ADDRMASK_EXT = 1 << 30,
CPUID_FEATURES_ECX_AVX = 1 << 28, CPUID_FEATURES_EDX_SYSCALL_SYSRET = 1 << 11,
CPUID_FEATURES_ECX_F16C = 1 << 29, CPUID_FEATURES_EDX_NX = 1 << 20,
CPUID_FEATURES_ECX_RDRAND = 1 << 30, CPUID_FEATURES_EDX_AMD_MMX_EXT = 1 << 22,
CPUID_FEATURES_ECX_HYPERVISOR = 1 << 31, CPUID_FEATURES_EDX_FFXSR = 1 << 25,
CPUID_FEATURES_EDX_FPU = 1 << 0, CPUID_FEATURES_EDX_1G_PAGES = 1 << 26,
CPUID_FEATURES_EDX_VME = 1 << 1, CPUID_FEATURES_EDX_RDTSCP = 1 << 27,
CPUID_FEATURES_EDX_DE = 1 << 2, CPUID_FEATURES_EDX_LONG_MODE = 1 << 29,
CPUID_FEATURES_EDX_PSE = 1 << 3, CPUID_FEATURES_EDX_3DNOW_EXT = 1 << 30,
CPUID_FEATURES_EDX_TSC = 1 << 4, CPUID_FEATURES_EDX_3DNOW = 1 << 31
CPUID_FEATURES_EDX_MSR = 1 << 5, } CPUID_FEATURES_EXTENDED, *PCPUID_FEATURES_EXTENDED;
CPUID_FEATURES_EDX_PAE = 1 << 6,
CPUID_FEATURES_EDX_MCE = 1 << 7, /* CPUID STD1 features (0x00000001) enumeration list */
CPUID_FEATURES_EDX_CX8 = 1 << 8, typedef enum _CPUID_FEATURES_STANDARD1
CPUID_FEATURES_EDX_APIC = 1 << 9, {
CPUID_FEATURES_EDX_SEP = 1 << 11, CPUID_FEATURES_ECX_SSE3 = 1 << 0,
CPUID_FEATURES_EDX_MTRR = 1 << 12, CPUID_FEATURES_ECX_PCLMUL = 1 << 1,
CPUID_FEATURES_EDX_PGE = 1 << 13, CPUID_FEATURES_ECX_DTES64 = 1 << 2,
CPUID_FEATURES_EDX_MCA = 1 << 14, CPUID_FEATURES_ECX_MONITOR = 1 << 3,
CPUID_FEATURES_EDX_CMOV = 1 << 15, CPUID_FEATURES_ECX_DS_CPL = 1 << 4,
CPUID_FEATURES_EDX_PAT = 1 << 16, CPUID_FEATURES_ECX_VMX = 1 << 5,
CPUID_FEATURES_EDX_PSE36 = 1 << 17, CPUID_FEATURES_ECX_SMX = 1 << 6,
CPUID_FEATURES_EDX_PSN = 1 << 18, CPUID_FEATURES_ECX_EST = 1 << 7,
CPUID_FEATURES_EDX_CLFLUSH = 1 << 19, CPUID_FEATURES_ECX_TM2 = 1 << 8,
CPUID_FEATURES_EDX_DS = 1 << 21, CPUID_FEATURES_ECX_SSSE3 = 1 << 9,
CPUID_FEATURES_EDX_ACPI = 1 << 22, CPUID_FEATURES_ECX_CID = 1 << 10,
CPUID_FEATURES_EDX_MMX = 1 << 23, CPUID_FEATURES_ECX_SDBG = 1 << 11,
CPUID_FEATURES_EDX_FXSR = 1 << 24, CPUID_FEATURES_ECX_FMA = 1 << 12,
CPUID_FEATURES_EDX_SSE = 1 << 25, CPUID_FEATURES_ECX_CX16 = 1 << 13,
CPUID_FEATURES_EDX_SSE2 = 1 << 26, CPUID_FEATURES_ECX_XTPR = 1 << 14,
CPUID_FEATURES_EDX_SS = 1 << 27, CPUID_FEATURES_ECX_PDCM = 1 << 15,
CPUID_FEATURES_EDX_HTT = 1 << 28, CPUID_FEATURES_ECX_PCID = 1 << 17,
CPUID_FEATURES_EDX_TM = 1 << 29, CPUID_FEATURES_ECX_DCA = 1 << 18,
CPUID_FEATURES_EDX_IA64 = 1 << 30, CPUID_FEATURES_ECX_SSE4_1 = 1 << 19,
CPUID_FEATURES_EDX_PBE = 1 << 31 CPUID_FEATURES_ECX_SSE4_2 = 1 << 20,
} CPUID_FEATURES, *PCPUID_FEATURES; CPUID_FEATURES_ECX_X2APIC = 1 << 21,
CPUID_FEATURES_ECX_MOVBE = 1 << 22,
CPUID_FEATURES_ECX_POPCNT = 1 << 23,
CPUID_FEATURES_ECX_TSC = 1 << 24,
CPUID_FEATURES_ECX_AES = 1 << 25,
CPUID_FEATURES_ECX_XSAVE = 1 << 26,
CPUID_FEATURES_ECX_OSXSAVE = 1 << 27,
CPUID_FEATURES_ECX_AVX = 1 << 28,
CPUID_FEATURES_ECX_F16C = 1 << 29,
CPUID_FEATURES_ECX_RDRAND = 1 << 30,
CPUID_FEATURES_ECX_HYPERVISOR = 1 << 31,
CPUID_FEATURES_EDX_FPU = 1 << 0,
CPUID_FEATURES_EDX_VME = 1 << 1,
CPUID_FEATURES_EDX_DE = 1 << 2,
CPUID_FEATURES_EDX_PSE = 1 << 3,
CPUID_FEATURES_EDX_TSC = 1 << 4,
CPUID_FEATURES_EDX_MSR = 1 << 5,
CPUID_FEATURES_EDX_PAE = 1 << 6,
CPUID_FEATURES_EDX_MCE = 1 << 7,
CPUID_FEATURES_EDX_CX8 = 1 << 8,
CPUID_FEATURES_EDX_APIC = 1 << 9,
CPUID_FEATURES_EDX_SEP = 1 << 11,
CPUID_FEATURES_EDX_MTRR = 1 << 12,
CPUID_FEATURES_EDX_PGE = 1 << 13,
CPUID_FEATURES_EDX_MCA = 1 << 14,
CPUID_FEATURES_EDX_CMOV = 1 << 15,
CPUID_FEATURES_EDX_PAT = 1 << 16,
CPUID_FEATURES_EDX_PSE36 = 1 << 17,
CPUID_FEATURES_EDX_PSN = 1 << 18,
CPUID_FEATURES_EDX_CLFLUSH = 1 << 19,
CPUID_FEATURES_EDX_DS = 1 << 21,
CPUID_FEATURES_EDX_ACPI = 1 << 22,
CPUID_FEATURES_EDX_MMX = 1 << 23,
CPUID_FEATURES_EDX_FXSR = 1 << 24,
CPUID_FEATURES_EDX_SSE = 1 << 25,
CPUID_FEATURES_EDX_SSE2 = 1 << 26,
CPUID_FEATURES_EDX_SS = 1 << 27,
CPUID_FEATURES_EDX_HTT = 1 << 28,
CPUID_FEATURES_EDX_TM = 1 << 29,
CPUID_FEATURES_EDX_IA64 = 1 << 30,
CPUID_FEATURES_EDX_PBE = 1 << 31
} CPUID_FEATURES_STANDARD1, *PCPUID_FEATURES_STANDARD1;
/* CPUID STD7 features (0x00000007, subleaf 0) enumeration list */
typedef enum _CPUID_FEATURES_STANDARD7_LEAF0
{
CPUID_FEATURES_EBX_FSGSBASE = 1 << 0,
CPUID_FEATURES_EBX_TSC_ADJUST = 1 << 1,
CPUID_FEATURES_EBX_SGX = 1 << 2,
CPUID_FEATURES_EBX_BMI1 = 1 << 3,
CPUID_FEATURES_EBX_HLE = 1 << 4,
CPUID_FEATURES_EBX_AVX2 = 1 << 5,
CPUID_FEATURES_EBX_FDP_DEPRECATION = 1 << 6,
CPUID_FEATURES_EBX_SMEP = 1 << 7,
CPUID_FEATURES_EBX_BMI2 = 1 << 8,
CPUID_FEATURES_EBX_ERMS = 1 << 9,
CPUID_FEATURES_EBX_INVPCID = 1 << 10,
CPUID_FEATURES_EBX_RTM = 1 << 11,
CPUID_FEATURES_EBX_QOS_MONITORING = 1 << 12,
CPUID_FEATURES_EBX_DEPRECATE_FCS_FDS = 1 << 13,
CPUID_FEATURES_EBX_MPX = 1 << 14,
CPUID_FEATURES_EBX_QOS_ENFORCEMENT = 1 << 15,
CPUID_FEATURES_EBX_AVX512F = 1 << 16,
CPUID_FEATURES_EBX_AVX512DQ = 1 << 17,
CPUID_FEATURES_EBX_RDSEED = 1 << 18,
CPUID_FEATURES_EBX_ADX = 1 << 19,
CPUID_FEATURES_EBX_SMAP = 1 << 20,
CPUID_FEATURES_EBX_AVX512IFMA52 = 1 << 21,
CPUID_FEATURES_EBX_CLFLUSHOPT = 1 << 23,
CPUID_FEATURES_EBX_CLWB = 1 << 24,
CPUID_FEATURES_EBX_PROCESSOR_TRACE = 1 << 25,
CPUID_FEATURES_EBX_AVX512PF = 1 << 26,
CPUID_FEATURES_EBX_AVX512ER = 1 << 27,
CPUID_FEATURES_EBX_AVX512CD = 1 << 28,
CPUID_FEATURES_EBX_SHA = 1 << 29,
CPUID_FEATURES_EBX_AVX512BW = 1 << 30,
CPUID_FEATURES_EBX_AVX512VL = 1 << 31,
CPUID_FEATURES_ECX_PREFETCHWT1 = 1 << 0,
CPUID_FEATURES_ECX_AVX512_VBMI = 1 << 1,
CPUID_FEATURES_ECX_UMIP = 1 << 2,
CPUID_FEATURES_ECX_PKU = 1 << 3,
CPUID_FEATURES_ECX_OSPKE = 1 << 4,
CPUID_FEATURES_ECX_WAITPKG = 1 << 5,
CPUID_FEATURES_ECX_AVX512_VBMI2 = 1 << 6,
CPUID_FEATURES_ECX_CET_SS = 1 << 7,
CPUID_FEATURES_ECX_GFNI = 1 << 8,
CPUID_FEATURES_ECX_VAES = 1 << 9,
CPUID_FEATURES_ECX_VPCLMULQDQ = 1 << 10,
CPUID_FEATURES_ECX_AVX512_VNNI = 1 << 11,
CPUID_FEATURES_ECX_AVX512_BITALG = 1 << 12,
CPUID_FEATURES_ECX_TME = 1 << 13,
CPUID_FEATURES_ECX_AVX512_VPOPCNTDQ = 1 << 14,
CPUID_FEATURES_ECX_LA57 = 1 << 16,
CPUID_FEATURES_ECX_RDPID = 1 << 22,
CPUID_FEATURES_ECX_KEYLOCKER = 1 << 23,
CPUID_FEATURES_ECX_BUS_LOCK_DETECT = 1 << 24,
CPUID_FEATURES_ECX_CLDEMOTE = 1 << 25,
CPUID_FEATURES_ECX_MOVDIRI = 1 << 27,
CPUID_FEATURES_ECX_MOVDIR64B = 1 << 28,
CPUID_FEATURES_ECX_ENQCMD = 1 << 29,
CPUID_FEATURES_ECX_SGX_LAUNCH_CONFIG = 1 << 30,
CPUID_FEATURES_ECX_PKS = 1 << 31,
CPUID_FEATURES_EDX_SGX_KEYS = 1 << 1,
CPUID_FEATURES_EDX_AVX512_4VNNIW = 1 << 2,
CPUID_FEATURES_EDX_AVX512_4FMAPS = 1 << 3,
CPUID_FEATURES_EDX_FAST_SHORT_REP_MOV = 1 << 4,
CPUID_FEATURES_EDX_UINTR = 1 << 5,
CPUID_FEATURES_EDX_AVX512_VPINTERSECT = 1 << 8,
CPUID_FEATURES_EDX_SRBDS_CTRL = 1 << 9,
CPUID_FEATURES_EDX_MD_CLEAR = 1 << 10,
CPUID_FEATURES_EDX_RTM_ALWAYS_ABORT = 1 << 11,
CPUID_FEATURES_EDX_RTM_FORCE_ABORT = 1 << 13,
CPUID_FEATURES_EDX_SERIALIZE = 1 << 14,
CPUID_FEATURES_EDX_HYBRID = 1 << 15,
CPUID_FEATURES_EDX_TSXLDTRK = 1 << 16,
CPUID_FEATURES_EDX_PCONFIG = 1 << 18,
CPUID_FEATURES_EDX_ARCH_LBR = 1 << 19,
CPUID_FEATURES_EDX_CET_IBT = 1 << 20,
CPUID_FEATURES_EDX_AMX_BF16 = 1 << 22,
CPUID_FEATURES_EDX_AVX512_FP16 = 1 << 23,
CPUID_FEATURES_EDX_AMX_TILE = 1 << 24,
CPUID_FEATURES_EDX_AMX_INT8 = 1 << 25,
CPUID_FEATURES_EDX_SCA_IBRS_IBPB = 1 << 26,
CPUID_FEATURES_EDX_SCA_STIBP = 1 << 27,
CPUID_FEATURES_EDX_L1D_FLUSH = 1 << 28,
CPUID_FEATURES_EDX_ARCH_CAPABILITIES_MSR = 1 << 29,
CPUID_FEATURES_EDX_CORE_CAPABILITIES_MSR = 1 << 30,
CPUID_FEATURES_EDX_SCA_SSBD = 1 << 31
} CPUID_FEATURES_STANDARD7_LEAF0, *PCPUID_FEATURES_STANDARD7_LEAF0;
/* CPUID STD7 features (0x00000007, subleaf 1) enumeration list */
typedef enum _CPUID_FEATURES_STANDARD7_LEAF1
{
CPUID_FEATURES_EAX_SHA512 = 1 << 0,
CPUID_FEATURES_EAX_SM3 = 1 << 1,
CPUID_FEATURES_EAX_SM4 = 1 << 2,
CPUID_FEATURES_EAX_RAO_INT = 1 << 3,
CPUID_FEATURES_EAX_AVX_VNNI = 1 << 4,
CPUID_FEATURES_EAX_AVX512_BF16 = 1 << 5,
CPUID_FEATURES_EAX_LASS = 1 << 6,
CPUID_FEATURES_EAX_CMPCCXADD = 1 << 7,
CPUID_FEATURES_EAX_ARCH_PERFMON = 1 << 8,
CPUID_FEATURES_EAX_FAST_ZEROLEN_REP_MOVSB = 1 << 10,
CPUID_FEATURES_EAX_FAST_ZEROLEN_REP_STOSB = 1 << 11,
CPUID_FEATURES_EAX_FAST_ZEROLEN_REP_CMPSB = 1 << 12,
CPUID_FEATURES_EAX_FRED = 1 << 17,
CPUID_FEATURES_EAX_LKGS = 1 << 18,
CPUID_FEATURES_EAX_WRMSRNS = 1 << 19,
CPUID_FEATURES_EAX_NMI_SOURCE_REPORTING = 1 << 20,
CPUID_FEATURES_EAX_AMX_FP16 = 1 << 21,
CPUID_FEATURES_EAX_HRESET = 1 << 22,
CPUID_FEATURES_EAX_AVX_IFMA = 1 << 23,
CPUID_FEATURES_EAX_LAM = 1 << 26,
CPUID_FEATURES_EAX_MSRLIST = 1 << 27,
CPUID_FEATURES_EAX_INVD_DISABLE = 1 << 30,
CPUID_FEATURES_EAX_MOVRS = 1 << 31,
CPUID_FEATURES_EBX_PPIN = 1 << 0,
CPUID_FEATURES_EBX_TSE = 1 << 1,
CPUID_FEATURES_EBX_CPUIDMAXVAL_LIM_RMV = 1 << 3,
CPUID_FEATURES_ECX_MSR_IMM = 1 << 5,
CPUID_FEATURES_EDX_AVX_VNNI_INT8 = 1 << 4,
CPUID_FEATURES_EDX_AVX_NE_CONVERT = 1 << 5,
CPUID_FEATURES_EDX_AMX_COMPLEX = 1 << 8,
CPUID_FEATURES_EDX_AVX_VNNI_INT16 = 1 << 10,
CPUID_FEATURES_EDX_USER_TIMER = 1 << 13,
CPUID_FEATURES_EDX_PREFETCHI = 1 << 14,
CPUID_FEATURES_EDX_USER_MSR = 1 << 15,
CPUID_FEATURES_EDX_UIRET_UIF = 1 << 17,
CPUID_FEATURES_EDX_CET_SSS = 1 << 18,
CPUID_FEATURES_EDX_AVX10 = 1 << 19,
CPUID_FEATURES_EDX_APX = 1 << 21,
CPUID_FEATURES_EDX_MWAIT_AND_LEAF5 = 1 << 23
} CPUID_FEATURES_STANDARD7_LEAF1, *PCPUID_FEATURES_STANDARD7_LEAF1;
/* CPUID requests */ /* CPUID requests */
typedef enum _CPUID_REQUESTS typedef enum _CPUID_REQUESTS
{ {
CPUID_GET_VENDOR_STRING, CPUID_GET_VENDOR_STRING,
CPUID_GET_CPU_FEATURES, CPUID_GET_STANDARD1_FEATURES,
CPUID_GET_TLB, CPUID_GET_TLB_CACHE,
CPUID_GET_SERIAL CPUID_GET_SERIAL,
CPUID_GET_CACHE_TOPOLOGY,
CPUID_GET_MONITOR_MWAIT,
CPUID_GET_POWER_MANAGEMENT,
CPUID_GET_STANDARD7_FEATURES
} CPUID_REQUESTS, *PCPUID_REQUESTS; } CPUID_REQUESTS, *PCPUID_REQUESTS;
/* Processor identification information */ /* Processor identification information */

View File

@@ -16,28 +16,34 @@
/* HAL library routines forward references */ /* HAL library routines forward references */
XTCLINK
XTCDECL XTCDECL
UCHAR UCHAR
HlIoPortInByte(IN USHORT Port); HlIoPortInByte(IN USHORT Port);
XTCLINK
XTCDECL XTCDECL
ULONG ULONG
HlIoPortInLong(IN USHORT Port); HlIoPortInLong(IN USHORT Port);
XTCLINK
XTCDECL XTCDECL
USHORT USHORT
HlIoPortInShort(IN USHORT Port); HlIoPortInShort(IN USHORT Port);
XTCLINK
XTCDECL XTCDECL
VOID VOID
HlIoPortOutByte(IN USHORT Port, HlIoPortOutByte(IN USHORT Port,
IN UCHAR Data); IN UCHAR Data);
XTCLINK
XTCDECL XTCDECL
VOID VOID
HlIoPortOutLong(IN USHORT Port, HlIoPortOutLong(IN USHORT Port,
IN ULONG Value); IN ULONG Value);
XTCLINK
XTCDECL XTCDECL
VOID VOID
HlIoPortOutShort(IN USHORT Port, HlIoPortOutShort(IN USHORT Port,

View File

@@ -47,20 +47,14 @@
#define APIC_DF_FLAT 0xFFFFFFFF #define APIC_DF_FLAT 0xFFFFFFFF
#define APIC_DF_CLUSTER 0x0FFFFFFF #define APIC_DF_CLUSTER 0x0FFFFFFF
/* APIC delivery modes */
#define APIC_DM_FIXED 0
#define APIC_DM_LOWPRIO 1
#define APIC_DM_SMI 2
#define APIC_DM_REMOTE 3
#define APIC_DM_NMI 4
#define APIC_DM_INIT 5
#define APIC_DM_STARTUP 6
#define APIC_DM_EXTINT 7
/* APIC trigger modes */ /* APIC trigger modes */
#define APIC_TGM_EDGE 0 #define APIC_TGM_EDGE 0
#define APIC_TGM_LEVEL 1 #define APIC_TGM_LEVEL 1
/* APIC LDR (Logical Destination Register) shifts */
#define APIC_X2APIC_LDR_SHIFT 16
#define APIC_XAPIC_LDR_SHIFT 24
/* Maximum number of I/O APICs */ /* Maximum number of I/O APICs */
#define APIC_MAX_IOAPICS 64 #define APIC_MAX_IOAPICS 64
@@ -82,6 +76,35 @@
/* Initial stall factor */ /* Initial stall factor */
#define INITIAL_STALL_FACTOR 100 #define INITIAL_STALL_FACTOR 100
/* APIC delivery mode enumeration list */
typedef enum _APIC_DM
{
APIC_DM_FIXED,
APIC_DM_LOWPRIO,
APIC_DM_SMI,
APIC_DM_REMOTE,
APIC_DM_NMI,
APIC_DM_INIT,
APIC_DM_STARTUP,
APIC_DM_EXTINT,
} APIC_DM, *PAPIC_DM;
/* APIC destination short-hand enumeration list */
typedef enum _APIC_DSH
{
APIC_DSH_Destination,
APIC_DSH_Self,
APIC_DSH_AllIncludingSelf,
APIC_DSH_AllExclusingSelf
} APIC_DSH, *PAPIC_DSH;
/* APIC mode list */
typedef enum _APIC_MODE
{
APIC_MODE_COMPAT,
APIC_MODE_X2APIC
} APIC_MODE, *PAPIC_MODE;
/* APIC Register Address Map */ /* APIC Register Address Map */
typedef enum _APIC_REGISTER typedef enum _APIC_REGISTER
{ {
@@ -119,35 +142,6 @@ typedef enum _APIC_REGISTER
APIC_EXT3LVTR = 0x53 /* Extended Interrupt 3 Local Vector Table */ APIC_EXT3LVTR = 0x53 /* Extended Interrupt 3 Local Vector Table */
} APIC_REGISTER, *PAPIC_REGISTER; } APIC_REGISTER, *PAPIC_REGISTER;
/* APIC mode list */
typedef enum _APIC_MODE
{
APIC_MODE_COMPAT,
APIC_MODE_X2APIC
} APIC_MODE, *PAPIC_MODE;
/* APIC destination short-hand enumeration list */
typedef enum _APIC_DSH
{
APIC_DSH_Destination,
APIC_DSH_Self,
APIC_DSH_AllIncludingSelf,
APIC_DSH_AllExclusingSelf
} APIC_DSH, *PAPIC_DSH;
/* APIC message type enumeration list */
typedef enum _APIC_MT
{
APIC_MT_Fixed,
APIC_MT_LowestPriority,
APIC_MT_SMI,
APIC_MT_RemoteRead,
APIC_MT_NMI,
APIC_MT_INIT,
APIC_MT_Startup,
APIC_MT_ExtInt,
} APIC_MT, *PAPIC_MT;
/* I8259 PIC interrupt mode enumeration list */ /* I8259 PIC interrupt mode enumeration list */
typedef enum _PIC_I8259_ICW1_INTERRUPT_MODE typedef enum _PIC_I8259_ICW1_INTERRUPT_MODE
{ {
@@ -220,7 +214,7 @@ typedef union _APIC_COMMAND_REGISTER
struct struct
{ {
ULONGLONG Vector:8; ULONGLONG Vector:8;
ULONGLONG MessageType:3; ULONGLONG DeliveryMode:3;
ULONGLONG DestinationMode:1; ULONGLONG DestinationMode:1;
ULONGLONG DeliveryStatus:1; ULONGLONG DeliveryStatus:1;
ULONGLONG ReservedMBZ:1; ULONGLONG ReservedMBZ:1;
@@ -240,7 +234,7 @@ typedef union _APIC_LVT_REGISTER
struct struct
{ {
ULONG Vector:8; ULONG Vector:8;
ULONG MessageType:3; ULONG DeliveryMode:3;
ULONG Reserved1:1; ULONG Reserved1:1;
ULONG DeliveryStatus:1; ULONG DeliveryStatus:1;
ULONG Reserved2:1; ULONG Reserved2:1;

View File

@@ -28,7 +28,11 @@
#define MM_PDI_SHIFT 21 #define MM_PDI_SHIFT 21
#define MM_PPI_SHIFT 30 #define MM_PPI_SHIFT 30
/* Page directory and page base legacy address */
#define MM_PDE_LEGACY_BASE 0xC0300000
/* PTE legacy shift values */ /* PTE legacy shift values */
#define MM_PTE_LEGACY_SHIFT 2
#define MM_PDI_LEGACY_SHIFT 22 #define MM_PDI_LEGACY_SHIFT 22
/* Minimum number of physical pages needed by the system */ /* Minimum number of physical pages needed by the system */
@@ -49,6 +53,8 @@
/* Maximum physical address used by HAL allocations */ /* Maximum physical address used by HAL allocations */
#define MM_MAXIMUM_PHYSICAL_ADDRESS 0xFFFFFFFF #define MM_MAXIMUM_PHYSICAL_ADDRESS 0xFFFFFFFF
/* Trampoline code address */
#define MM_TRAMPOLINE_ADDRESS 0x80000
/* Page size enumeration list */ /* Page size enumeration list */
typedef enum _PAGE_SIZE typedef enum _PAGE_SIZE
@@ -58,8 +64,26 @@ typedef enum _PAGE_SIZE
Size4M Size4M
} PAGE_SIZE, *PPAGE_SIZE; } PAGE_SIZE, *PPAGE_SIZE;
/* Page Table entry structure definition (with PAE support) */ /* Legacy Page Table entry structure definition (PML2) */
typedef struct _HARDWARE_PTE typedef struct _HARDWARE_LEGACY_PTE
{
ULONG Valid:1;
ULONG Writable:1;
ULONG Owner:1;
ULONG WriteThrough:1;
ULONG CacheDisable:1;
ULONG Accessed:1;
ULONG Dirty:1;
ULONG LargePage:1;
ULONG Global:1;
ULONG CopyOnWrite:1;
ULONG Prototype:1;
ULONG Reserved0:1;
ULONG PageFrameNumber:20;
} HARDWARE_LEGACY_PTE, *PHARDWARE_LEGACY_PTE;
/* Page Table entry structure definition (PML3) */
typedef struct _HARDWARE_MODERN_PTE
{ {
ULONGLONG Valid:1; ULONGLONG Valid:1;
ULONGLONG Writable:1; ULONGLONG Writable:1;
@@ -77,10 +101,117 @@ typedef struct _HARDWARE_PTE
ULONGLONG Reserved1:14; ULONGLONG Reserved1:14;
ULONGLONG SoftwareWsIndex:11; ULONGLONG SoftwareWsIndex:11;
ULONGLONG NoExecute:1; ULONGLONG NoExecute:1;
} HARDWARE_MODERN_PTE, *PHARDWARE_MODERN_PTE;
/* Generic Page Table entry union to abstract PML2 and PML3 formats */
typedef union _HARDWARE_PTE
{
ULONGLONG Long;
HARDWARE_LEGACY_PTE Pml2;
HARDWARE_MODERN_PTE Pml3;
} HARDWARE_PTE, *PHARDWARE_PTE; } HARDWARE_PTE, *PHARDWARE_PTE;
/* Page Table Entry on PAE enabled system */ /* Page map information structure definition */
typedef struct _MMPTE_HARDWARE typedef struct _MMPAGEMAP_INFO
{
BOOLEAN Xpa;
ULONG PteBase;
ULONG PdeBase;
ULONG PdiShift;
ULONG PteShift;
} MMPAGEMAP_INFO, *PMMPAGEMAP_INFO;
/* Legacy Page Table Entry hardware structure definition (PML2) */
typedef struct _MMPML2_PTE_HARDWARE
{
ULONG Valid:1;
ULONG Writable:1;
ULONG Owner:1;
ULONG WriteThrough:1;
ULONG CacheDisable:1;
ULONG Accessed:1;
ULONG Dirty:1;
ULONG LargePage:1;
ULONG Global:1;
ULONG CopyOnWrite:1;
ULONG Prototype:1;
ULONG Write:1;
ULONG PageFrameNumber:20;
} MMPML2_PTE_HARDWARE, *PMMPML2_PTE_HARDWARE;
/* Legacy Page Table Entry list structure definition (PML2) */
typedef struct _MMPML2_PTE_LIST
{
ULONG Valid:1;
ULONG OneEntry:1;
ULONG Reserved0:8;
ULONG Prototype:1;
ULONG Reserved1:1;
ULONG NextEntry:20;
} MMPML2_PTE_LIST, *PMMPML2_PTE_LIST;
/* Legacy Page Table Entry subsection structure definition (PML2) */
typedef struct _MMPML2_PTE_PROTOTYPE
{
ULONG Valid:1;
ULONG ProtoAddressLow:7;
ULONG ReadOnly:1;
ULONG WhichPool:1;
ULONG Prototype:1;
ULONG ProtoAddressHigh:21;
} MMPML2_PTE_PROTOTYPE, *PMMPML2_PTE_PROTOTYPE;
/* Legacy Page Table Entry software structure definition (PML2) */
typedef struct _MMPML2_PTE_SOFTWARE
{
ULONG Valid:1;
ULONG PageFileLow:4;
ULONG Protection:5;
ULONG Prototype:1;
ULONG Transition:1;
ULONG PageFileHigh:20;
} MMPML2_PTE_SOFTWARE, *PMMPML2_PTE_SOFTWARE;
/* Legacy Page Table Entry subsection structure definition (PML2) */
typedef struct _MMPML2_PTE_SUBSECTION
{
ULONG Valid:1;
ULONG SubsectionAddressLow:4;
ULONG Protection:5;
ULONG Prototype:1;
ULONG SubsectionAddressHigh:20;
ULONG WhichPool:1;
} MMPML2_PTE_SUBSECTION, *PMMPML2_PTE_SUBSECTION;
/* Legacy Page Table Entry transition structure definition (PML2) */
typedef struct _MMPML2_PTE_TRANSITION
{
ULONG Valid:1;
ULONG Write:1;
ULONG Owner:1;
ULONG WriteThrough:1;
ULONG CacheDisable:1;
ULONG Protection:5;
ULONG Prototype:1;
ULONG Transition:1;
ULONG PageFrameNumber:20;
} MMPML2_PTE_TRANSITION, *PMMPML2_PTE_TRANSITION;
/* Legacy Page Table Entry union definition (PML2) */
typedef union _MMPML2_PTE
{
ULONG Long;
HARDWARE_PTE Flush;
MMPML2_PTE_HARDWARE Hard;
MMPML2_PTE_PROTOTYPE Proto;
MMPML2_PTE_SOFTWARE Soft;
MMPML2_PTE_TRANSITION Trans;
MMPML2_PTE_SUBSECTION Subsect;
MMPML2_PTE_LIST List;
} MMPML2_PTE, *PMMPML2_PTE;
/* Page Table Entry hardware structure definition (PML3) */
typedef struct _MMPML3_PTE_HARDWARE
{ {
ULONGLONG Valid:1; ULONGLONG Valid:1;
ULONGLONG Writable:1; ULONGLONG Writable:1;
@@ -95,59 +226,59 @@ typedef struct _MMPTE_HARDWARE
ULONGLONG Prototype:1; ULONGLONG Prototype:1;
ULONGLONG Write:1; ULONGLONG Write:1;
ULONGLONG PageFrameNumber:26; ULONGLONG PageFrameNumber:26;
ULONGLONG Reserved1:25; ULONGLONG Reserved0:25;
ULONGLONG NoExecute:1; ULONGLONG NoExecute:1;
} MMPTE_HARDWARE, *PMMPTE_HARDWARE; } MMPML3_PTE_HARDWARE, *PMMPML3_PTE_HARDWARE;
/* Page Table Entry list structure definition (with PAE support) */ /* Page Table Entry list structure definition (PML3) */
typedef struct _MMPTE_LIST typedef struct _MMPML3_PTE_LIST
{ {
ULONGLONG Valid:1; ULONGLONG Valid:1;
ULONGLONG OneEntry:1; ULONGLONG OneEntry:1;
ULONGLONG Reserved1:8; ULONGLONG Reserved0:8;
ULONGLONG Prototype:1; ULONGLONG Prototype:1;
ULONGLONG Reserved2:21; ULONGLONG Reserved1:21;
ULONGLONG NextEntry:32; ULONGLONG NextEntry:32;
} MMPTE_LIST, *PMMPTE_LIST; } MMPML3_PTE_LIST, *PMMPML3_PTE_LIST;
/* Page Table Entry subsection structure definition (with PAE support) */ /* Page Table Entry subsection structure definition (PML3) */
typedef struct _MMPTE_PROTOTYPE typedef struct _MMPML3_PTE_PROTOTYPE
{ {
ULONGLONG Valid:1; ULONGLONG Valid:1;
ULONGLONG Reserved1:7; ULONGLONG Reserved0:7;
ULONGLONG ReadOnly:1; ULONGLONG ReadOnly:1;
ULONGLONG Reserved2:1; ULONGLONG Reserved1:1;
ULONGLONG Prototype:1; ULONGLONG Prototype:1;
ULONGLONG Protection:5; ULONGLONG Protection:5;
ULONGLONG Reserved3:16; ULONGLONG Reserved2:16;
ULONGLONG ProtoAddress:32; ULONGLONG ProtoAddress:32;
} MMPTE_PROTOTYPE, *PMMPTE_PROTOTYPE; } MMPML3_PTE_PROTOTYPE, *PMMPML3_PTE_PROTOTYPE;
/* Page Table Entry software structure definition (with PAE support) */ /* Page Table Entry software structure definition (PML3) */
typedef struct _MMPTE_SOFTWARE typedef struct _MMPML3_PTE_SOFTWARE
{ {
ULONGLONG Valid:1; ULONGLONG Valid:1;
ULONGLONG PageFileLow:4; ULONGLONG PageFileLow:4;
ULONGLONG Protection:5; ULONGLONG Protection:5;
ULONGLONG Prototype:1; ULONGLONG Prototype:1;
ULONGLONG Transition:1; ULONGLONG Transition:1;
ULONGLONG Reserved1:20; ULONGLONG Reserved0:20;
ULONGLONG PageFileHigh:32; ULONGLONG PageFileHigh:32;
} MMPTE_SOFTWARE, *PMMPTE_SOFTWARE; } MMPML3_PTE_SOFTWARE, *PMMPML3_PTE_SOFTWARE;
/* Page Table Entry subsection structure definition (with PAE support) */ /* Page Table Entry subsection structure definition (PML3) */
typedef struct _MMPTE_SUBSECTION typedef struct _MMPML3_PTE_SUBSECTION
{ {
ULONGLONG Valid:1; ULONGLONG Valid:1;
ULONGLONG Reserved1:4; ULONGLONG Reserved0:4;
ULONGLONG Protection:5; ULONGLONG Protection:5;
ULONGLONG Prototype:1; ULONGLONG Prototype:1;
ULONGLONG Reserved2:21; ULONGLONG Reserved1:21;
ULONGLONG SubsectionAddress:32; ULONGLONG SubsectionAddress:32;
} MMPTE_SUBSECTION, *PMMPTE_SUBSECTION; } MMPML3_PTE_SUBSECTION, *PMMPML3_PTE_SUBSECTION;
/* Page Table Entry transition structure definition (with PAE support) */ /* Page Table Entry transition structure definition (PML3) */
typedef struct _MMPTE_TRANSITION typedef struct _MMPML3_PTE_TRANSITION
{ {
ULONGLONG Valid:1; ULONGLONG Valid:1;
ULONGLONG Write:1; ULONGLONG Write:1;
@@ -159,38 +290,28 @@ typedef struct _MMPTE_TRANSITION
ULONGLONG Transition:1; ULONGLONG Transition:1;
ULONGLONG PageFrameNumber:26; ULONGLONG PageFrameNumber:26;
ULONGLONG Unused:26; ULONGLONG Unused:26;
} MMPTE_TRANSITION, *PMMPTE_TRANSITION; } MMPML3_PTE_TRANSITION, *PMMPML3_PTE_TRANSITION;
/* Page Table Entry structure definition (with PAE support) */ /* Page Table Entry union definition (PML3) */
typedef union _MMPTE typedef union _MMPML3_PTE
{ {
ULONGLONG Long; ULONGLONG Long;
HARDWARE_PTE Flush; HARDWARE_PTE Flush;
MMPTE_HARDWARE Hardware; MMPML3_PTE_HARDWARE Hardware;
MMPTE_PROTOTYPE Prototype; MMPML3_PTE_PROTOTYPE Prototype;
MMPTE_SOFTWARE Software; MMPML3_PTE_SOFTWARE Software;
MMPTE_TRANSITION Transition; MMPML3_PTE_TRANSITION Transition;
MMPTE_SUBSECTION Subsection; MMPML3_PTE_SUBSECTION Subsection;
MMPTE_LIST List; MMPML3_PTE_LIST List;
} MMPTE, *PMMPTE; } MMPML3_PTE, *PMMPML3_PTE;
/* Legacy Page Table entry structure definition (without PAE support) */ /* Generic Page Table Entry union to abstract PML2 and PML3 formats */
typedef struct _HARDWARE_LEGACY_PTE typedef union _MMPTE
{ {
ULONG Valid:1; ULONGLONG Long;
ULONG Writable:1; MMPML2_PTE Pml2;
ULONG Owner:1; MMPML3_PTE Pml3;
ULONG WriteThrough:1; } MMPTE, *PMMPTE;
ULONG CacheDisable:1;
ULONG Accessed:1;
ULONG Dirty:1;
ULONG LargePage:1;
ULONG Global:1;
ULONG CopyOnWrite:1;
ULONG Prototype:1;
ULONG Reserved0:1;
ULONG PageFrameNumber:20;
} HARDWARE_LEGACY_PTE, *PHARDWARE_LEGACY_PTE;
/* Page Frame Number structure definition */ /* Page Frame Number structure definition */
typedef struct _MMPFN typedef struct _MMPFN

View File

@@ -13,12 +13,15 @@
/* Architecture-specific enumeration lists forward references */ /* Architecture-specific enumeration lists forward references */
typedef enum _APIC_DM APIC_DM, *PAPIC_DM;
typedef enum _APIC_DSH APIC_DSH, *PAPIC_DSH; typedef enum _APIC_DSH APIC_DSH, *PAPIC_DSH;
typedef enum _APIC_MODE APIC_MODE, *PAPIC_MODE; typedef enum _APIC_MODE APIC_MODE, *PAPIC_MODE;
typedef enum _APIC_MT APIC_MT, *PAPIC_MT;
typedef enum _APIC_REGISTER APIC_REGISTER, *PAPIC_REGISTER; typedef enum _APIC_REGISTER APIC_REGISTER, *PAPIC_REGISTER;
typedef enum _CPU_VENDOR CPU_VENDOR, *PCPU_VENDOR; typedef enum _CPU_VENDOR CPU_VENDOR, *PCPU_VENDOR;
typedef enum _CPUID_FEATURES CPUID_FEATURES, *PCPUID_FEATURES; typedef enum _CPUID_FEATURES_EXTENDED CPUID_FEATURES_EXTENDED, *PCPUID_FEATURES_EXTENDED;
typedef enum _CPUID_FEATURES_STANDARD1 CPUID_FEATURES_STANDARD1, *PCPUID_FEATURES_STANDARD1;
typedef enum _CPUID_FEATURES_STANDARD7_LEAF0 CPUID_FEATURES_STANDARD7_LEAF0, *PCPUID_FEATURES_STANDARD7_LEAF0;
typedef enum _CPUID_FEATURES_STANDARD7_LEAF1 CPUID_FEATURES_STANDARD7_LEAF1, *PCPUID_FEATURES_STANDARD7_LEAF1;
typedef enum _CPUID_REQUESTS CPUID_REQUESTS, *PCPUID_REQUESTS; typedef enum _CPUID_REQUESTS CPUID_REQUESTS, *PCPUID_REQUESTS;
typedef enum _PAGE_SIZE PAGE_SIZE, *PPAGE_SIZE; typedef enum _PAGE_SIZE PAGE_SIZE, *PPAGE_SIZE;
typedef enum _PIC_I8259_ICW1_INTERRUPT_MODE PIC_I8259_ICW1_INTERRUPT_MODE, *PPIC_I8259_ICW1_INTERRUPT_MODE; typedef enum _PIC_I8259_ICW1_INTERRUPT_MODE PIC_I8259_ICW1_INTERRUPT_MODE, *PPIC_I8259_ICW1_INTERRUPT_MODE;
@@ -37,7 +40,7 @@ typedef struct _FN_SAVE_FORMAT FN_SAVE_FORMAT, *PFN_SAVE_FORMAT;
typedef struct _FX_SAVE_AREA FX_SAVE_AREA, *PFX_SAVE_AREA; typedef struct _FX_SAVE_AREA FX_SAVE_AREA, *PFX_SAVE_AREA;
typedef struct _FX_SAVE_FORMAT FX_SAVE_FORMAT, *PFX_SAVE_FORMAT; typedef struct _FX_SAVE_FORMAT FX_SAVE_FORMAT, *PFX_SAVE_FORMAT;
typedef struct _HARDWARE_LEGACY_PTE HARDWARE_LEGACY_PTE, *PHARDWARE_LEGACY_PTE; typedef struct _HARDWARE_LEGACY_PTE HARDWARE_LEGACY_PTE, *PHARDWARE_LEGACY_PTE;
typedef struct _HARDWARE_PTE HARDWARE_PTE, *PHARDWARE_PTE; typedef struct _HARDWARE_MODERN_PTE HARDWARE_MODERN_PTE, *PHARDWARE_MODERN_PTE;
typedef struct _KDESCRIPTOR KDESCRIPTOR, *PKDESCRIPTOR; typedef struct _KDESCRIPTOR KDESCRIPTOR, *PKDESCRIPTOR;
typedef struct _KEXCEPTION_FRAME KEXCEPTION_FRAME, *PKEXCEPTION_FRAME; typedef struct _KEXCEPTION_FRAME KEXCEPTION_FRAME, *PKEXCEPTION_FRAME;
typedef struct _KGDTENTRY KGDTENTRY, *PKGDTENTRY; typedef struct _KGDTENTRY KGDTENTRY, *PKGDTENTRY;
@@ -52,13 +55,20 @@ typedef struct _KSWITCH_FRAME KSWITCH_FRAME, *PKSWITCH_FRAME;
typedef struct _KTHREAD_INIT_FRAME KTHREAD_INIT_FRAME, *PKTHREAD_INIT_FRAME; typedef struct _KTHREAD_INIT_FRAME KTHREAD_INIT_FRAME, *PKTHREAD_INIT_FRAME;
typedef struct _KTRAP_FRAME KTRAP_FRAME, *PKTRAP_FRAME; typedef struct _KTRAP_FRAME KTRAP_FRAME, *PKTRAP_FRAME;
typedef struct _KTSS KTSS, *PKTSS; typedef struct _KTSS KTSS, *PKTSS;
typedef struct _MMPAGEMAP_INFO MMPAGEMAP_INFO, *PMMPAGEMAP_INFO;
typedef struct _MMPFN MMPFN, *PMMPFN; typedef struct _MMPFN MMPFN, *PMMPFN;
typedef struct _MMPTE_HARDWARE MMPTE_HARDWARE, *PMMPTE_HARDWARE; typedef struct _MMPML2_PTE_HARDWARE MMPML2_PTE_HARDWARE, *PMMPML2_PTE_HARDWARE;
typedef struct _MMPTE_LIST MMPTE_LIST, *PMMPTE_LIST; typedef struct _MMPML2_PTE_LIST MMPML2_PTE_LIST, *PMMPML2_PTE_LIST;
typedef struct _MMPTE_PROTOTYPE MMPTE_PROTOTYPE, *PMMPTE_PROTOTYPE; typedef struct _MMPML2_PTE_PROTOTYPE MMPML2_PTE_PROTOTYPE, *PMMPML2_PTE_PROTOTYPE;
typedef struct _MMPTE_SOFTWARE MMPTE_SOFTWARE, *PMMPTE_SOFTWARE; typedef struct _MMPML2_PTE_SOFTWARE MMPML2_PTE_SOFTWARE, *PMMPML2_PTE_SOFTWARE;
typedef struct _MMPTE_SUBSECTION MMPTE_SUBSECTION, *PMMPTE_SUBSECTION; typedef struct _MMPML2_PTE_SUBSECTION MMPML2_PTE_SUBSECTION, *PMMPML2_PTE_SUBSECTION;
typedef struct _MMPTE_TRANSITION MMPTE_TRANSITION, *PMMPTE_TRANSITION; typedef struct _MMPML2_PTE_TRANSITION MMPML2_PTE_TRANSITION, *PMMPML2_PTE_TRANSITION;
typedef struct _MMPML3_PTE_HARDWARE MMPML3_PTE_HARDWARE, *PMMPML3_PTE_HARDWARE;
typedef struct _MMPML3_PTE_LIST MMPML3_PTE_LIST, *PMMPML3_PTE_LIST;
typedef struct _MMPML3_PTE_PROTOTYPE MMPML3_PTE_PROTOTYPE, *PMMPML3_PTE_PROTOTYPE;
typedef struct _MMPML3_PTE_SOFTWARE MMPML3_PTE_SOFTWARE, *PMMPML3_PTE_SOFTWARE;
typedef struct _MMPML3_PTE_SUBSECTION MMPML3_PTE_SUBSECTION, *PMMPML3_PTE_SUBSECTION;
typedef struct _MMPML3_PTE_TRANSITION MMPML3_PTE_TRANSITION, *PMMPML3_PTE_TRANSITION;
typedef struct _THREAD_ENVIRONMENT_BLOCK THREAD_ENVIRONMENT_BLOCK, *PTHREAD_ENVIRONMENT_BLOCK; typedef struct _THREAD_ENVIRONMENT_BLOCK THREAD_ENVIRONMENT_BLOCK, *PTHREAD_ENVIRONMENT_BLOCK;
/* Unions forward references */ /* Unions forward references */
@@ -66,12 +76,15 @@ typedef union _APIC_BASE_REGISTER APIC_BASE_REGISTER, *PAPIC_BASE_REGISTER;
typedef union _APIC_COMMAND_REGISTER APIC_COMMAND_REGISTER, *PAPIC_COMMAND_REGISTER; typedef union _APIC_COMMAND_REGISTER APIC_COMMAND_REGISTER, *PAPIC_COMMAND_REGISTER;
typedef union _APIC_LVT_REGISTER APIC_LVT_REGISTER, *PAPIC_LVT_REGISTER; typedef union _APIC_LVT_REGISTER APIC_LVT_REGISTER, *PAPIC_LVT_REGISTER;
typedef union _APIC_SPURIOUS_REGISTER APIC_SPURIOUS_REGISTER, *PAPIC_SPURIOUS_REGISTER; typedef union _APIC_SPURIOUS_REGISTER APIC_SPURIOUS_REGISTER, *PAPIC_SPURIOUS_REGISTER;
typedef union _HARDWARE_PTE HARDWARE_PTE, *PHARDWARE_PTE;
typedef union _MMPML2_PTE MMPML2_PTE, *PMMPML2_PTE;
typedef union _MMPML3_PTE MMPML3_PTE, *PMMPML3_PTE;
typedef union _MMPTE MMPDE, *PMMPDE; typedef union _MMPTE MMPDE, *PMMPDE;
typedef union _MMPTE MMPPE, *PMMPPE;
typedef union _MMPTE MMPTE, *PMMPTE; typedef union _MMPTE MMPTE, *PMMPTE;
typedef union _PIC_I8259_ICW1 PIC_I8259_ICW1, *PPIC_I8259_ICW1; typedef union _PIC_I8259_ICW1 PIC_I8259_ICW1, *PPIC_I8259_ICW1;
typedef union _PIC_I8259_ICW2 PIC_I8259_ICW2, *PPIC_I8259_ICW2; typedef union _PIC_I8259_ICW2 PIC_I8259_ICW2, *PPIC_I8259_ICW2;
typedef union _PIC_I8259_ICW3 PIC_I8259_ICW3, *PPIC_I8259_ICW3; typedef union _PIC_I8259_ICW3 PIC_I8259_ICW3, *PPIC_I8259_ICW3;
typedef union _PIC_I8259_ICW4 PIC_I8259_ICW4, *PPIC_I8259_ICW4; typedef union _PIC_I8259_ICW4 PIC_I8259_ICW4, *PPIC_I8259_ICW4;
#endif /* __XTDK_I686_XTSTRUCT_H */ #endif /* __XTDK_I686_XTSTRUCT_H */

45
sdk/xtdk/kdtypes.h Normal file
View File

@@ -0,0 +1,45 @@
/**
* PROJECT: ExectOS
* COPYRIGHT: See COPYING.md in the top level directory
* FILE: sdk/xtdk/kdtypes.h
* DESCRIPTION: Kernel Debugger data structures
* DEVELOPERS: Aiken Harris <harraiken91@gmail.com>
*/
#ifndef __XTDK_KDTYPES_H
#define __XTDK_KDTYPES_H
#include <xtbase.h>
#include <xtstruct.h>
#include <rtltypes.h>
/* Number of debug providers */
#define KDBG_PROVIDERS_COUNT 2
/* Debug providers bitmask definitions */
#define DEBUG_PROVIDER_COMPORT 0x00000001
#define DEBUG_PROVIDER_FRAMEBUFFER 0x00000002
/* Kernel routine callbacks */
typedef XTSTATUS (XTAPI *PKD_INIT_ROUTINE)();
typedef VOID (*PKD_PRINT_ROUTINE)(IN PCWSTR Format, IN ...);
/* Debug mode structure definition */
typedef struct _KD_DEBUG_MODE
{
BOOLEAN Enabled;
ULONG Mode;
ULONG ComPortAddress;
ULONG ComPortNumber;
ULONG ComPortBaudRate;
} KD_DEBUG_MODE, *PKD_DEBUG_MODE;
/* Kernel debugger dispatch table structure definition */
typedef struct _KD_DISPATCH_TABLE
{
LIST_ENTRY ListEntry;
RTL_PRINT_CONTEXT PrintContext;
} KD_DISPATCH_TABLE, *PKD_DISPATCH_TABLE;
#endif /* __XTDK_KDTYPES_H */

View File

@@ -16,36 +16,44 @@
/* Kernel services routines forward references */ /* Kernel services routines forward references */
XTCLINK
XTFASTCALL XTFASTCALL
VOID VOID
KeAcquireQueuedSpinLock(IN KSPIN_LOCK_QUEUE_LEVEL LockLevel); KeAcquireQueuedSpinLock(IN KSPIN_LOCK_QUEUE_LEVEL LockLevel);
XTCLINK
XTFASTCALL XTFASTCALL
VOID VOID
KeAcquireSpinLock(IN OUT PKSPIN_LOCK SpinLock); KeAcquireSpinLock(IN OUT PKSPIN_LOCK SpinLock);
XTCLINK
XTAPI XTAPI
XTSTATUS XTSTATUS
KeAcquireSystemResource(IN SYSTEM_RESOURCE_TYPE ResourceType, KeAcquireSystemResource(IN SYSTEM_RESOURCE_TYPE ResourceType,
OUT PSYSTEM_RESOURCE_HEADER *ResourceHeader); OUT PSYSTEM_RESOURCE_HEADER *ResourceHeader);
XTCLINK
XTAPI XTAPI
BOOLEAN BOOLEAN
KeCancelTimer(IN PKTIMER Timer); KeCancelTimer(IN PKTIMER Timer);
XTCLINK
XTFASTCALL XTFASTCALL
KRUNLEVEL KRUNLEVEL
KeGetCurrentRunLevel(VOID); KeGetCurrentRunLevel(VOID);
XTCLINK
XTAPI XTAPI
XTSTATUS XTSTATUS
KeGetSystemResource(IN SYSTEM_RESOURCE_TYPE ResourceType, KeGetSystemResource(IN SYSTEM_RESOURCE_TYPE ResourceType,
OUT PSYSTEM_RESOURCE_HEADER *ResourceHeader); OUT PSYSTEM_RESOURCE_HEADER *ResourceHeader);
XTCLINK
XTAPI XTAPI
BOOLEAN BOOLEAN
KeGetTimerState(IN PKTIMER Timer); KeGetTimerState(IN PKTIMER Timer);
XTCLINK
XTAPI XTAPI
VOID VOID
KeInitializeApc(IN PKAPC Apc, KeInitializeApc(IN PKAPC Apc,
@@ -57,45 +65,54 @@ KeInitializeApc(IN PKAPC Apc,
IN KPROCESSOR_MODE ApcMode, IN KPROCESSOR_MODE ApcMode,
IN PVOID Context); IN PVOID Context);
XTCLINK
XTAPI XTAPI
VOID VOID
KeInitializeDpc(IN PKDPC Dpc, KeInitializeDpc(IN PKDPC Dpc,
IN PKDEFERRED_ROUTINE DpcRoutine, IN PKDEFERRED_ROUTINE DpcRoutine,
IN PVOID DpcContext); IN PVOID DpcContext);
XTCLINK
XTAPI XTAPI
VOID VOID
KeInitializeSemaphore(IN PKSEMAPHORE Semaphore, KeInitializeSemaphore(IN PKSEMAPHORE Semaphore,
IN LONG Count, IN LONG Count,
IN LONG Limit); IN LONG Limit);
XTCLINK
XTAPI XTAPI
VOID VOID
KeInitializeSpinLock(IN PKSPIN_LOCK SpinLock); KeInitializeSpinLock(IN PKSPIN_LOCK SpinLock);
XTCLINK
XTAPI XTAPI
VOID VOID
KeInitializeThreadedDpc(IN PKDPC Dpc, KeInitializeThreadedDpc(IN PKDPC Dpc,
IN PKDEFERRED_ROUTINE DpcRoutine, IN PKDEFERRED_ROUTINE DpcRoutine,
IN PVOID DpcContext); IN PVOID DpcContext);
XTCLINK
XTAPI XTAPI
VOID VOID
KeInitializeTimer(OUT PKTIMER Timer, KeInitializeTimer(OUT PKTIMER Timer,
IN KTIMER_TYPE Type); IN KTIMER_TYPE Type);
XTCLINK
XTFASTCALL XTFASTCALL
VOID VOID
KeLowerRunLevel(IN KRUNLEVEL RunLevel); KeLowerRunLevel(IN KRUNLEVEL RunLevel);
XTCLINK
XTFASTCALL XTFASTCALL
KRUNLEVEL KRUNLEVEL
KeRaiseRunLevel(IN KRUNLEVEL RunLevel); KeRaiseRunLevel(IN KRUNLEVEL RunLevel);
XTCLINK
XTAPI XTAPI
LONG LONG
KeReadSemaphoreState(IN PKSEMAPHORE Semaphore); KeReadSemaphoreState(IN PKSEMAPHORE Semaphore);
XTCLINK
XTAPI XTAPI
LONG LONG
KeReleaseSemaphore(IN PKSEMAPHORE Semaphore, KeReleaseSemaphore(IN PKSEMAPHORE Semaphore,
@@ -103,23 +120,28 @@ KeReleaseSemaphore(IN PKSEMAPHORE Semaphore,
IN LONG Adjustment, IN LONG Adjustment,
IN BOOLEAN Wait); IN BOOLEAN Wait);
XTCLINK
XTFASTCALL XTFASTCALL
VOID VOID
KeReleaseQueuedSpinLock(IN KSPIN_LOCK_QUEUE_LEVEL LockLevel); KeReleaseQueuedSpinLock(IN KSPIN_LOCK_QUEUE_LEVEL LockLevel);
XTCLINK
XTFASTCALL XTFASTCALL
VOID VOID
KeReleaseSpinLock(IN OUT PKSPIN_LOCK SpinLock); KeReleaseSpinLock(IN OUT PKSPIN_LOCK SpinLock);
XTCLINK
XTAPI XTAPI
VOID VOID
KeReleaseSystemResource(IN PSYSTEM_RESOURCE_HEADER ResourceHeader); KeReleaseSystemResource(IN PSYSTEM_RESOURCE_HEADER ResourceHeader);
XTCLINK
XTAPI XTAPI
VOID VOID
KeSetTargetProcessorDpc(IN PKDPC Dpc, KeSetTargetProcessorDpc(IN PKDPC Dpc,
IN CCHAR Number); IN CCHAR Number);
XTCLINK
XTAPI XTAPI
VOID VOID
KeSetTimer(IN PKTIMER Timer, KeSetTimer(IN PKTIMER Timer,
@@ -127,10 +149,12 @@ KeSetTimer(IN PKTIMER Timer,
IN LONG Period, IN LONG Period,
IN PKDPC Dpc); IN PKDPC Dpc);
XTCLINK
XTAPI XTAPI
VOID VOID
KeSignalCallDpcDone(IN PVOID SystemArgument); KeSignalCallDpcDone(IN PVOID SystemArgument);
XTCLINK
XTAPI XTAPI
BOOLEAN BOOLEAN
KeSignalCallDpcSynchronize(IN PVOID SystemArgument); KeSignalCallDpcSynchronize(IN PVOID SystemArgument);

View File

@@ -10,8 +10,18 @@
#define __XTDK_MMTYPES_H #define __XTDK_MMTYPES_H
#include <xtbase.h> #include <xtbase.h>
#include ARCH_HEADER(xtstruct.h)
/* Page map routines structure definition */
typedef CONST STRUCT _CMMPAGEMAP_ROUTINES
{
VOID (XTAPI *ClearPte)(PHARDWARE_PTE PtePointer);
BOOLEAN (XTAPI *PteValid)(PHARDWARE_PTE PtePointer);
VOID (XTAPI *SetPteCaching)(PHARDWARE_PTE PtePointer, BOOLEAN CacheDisable, BOOLEAN WriteThrough);
VOID (XTAPI *SetPte)(PHARDWARE_PTE PtePointer, PFN_NUMBER PageFrameNumber, BOOLEAN Writable);
} CMMPAGEMAP_ROUTINES, *PCMMPAGEMAP_ROUTINES;
/* Color tables structure definition */ /* Color tables structure definition */
typedef struct _MMCOLOR_TABLES typedef struct _MMCOLOR_TABLES
{ {

View File

@@ -83,26 +83,26 @@ RtlCompareMemory(IN PCVOID LeftBuffer,
XTAPI XTAPI
SIZE_T SIZE_T
RtlCompareString(IN CONST PCHAR String1, RtlCompareString(IN PCSTR String1,
IN CONST PCHAR String2, IN PCSTR String2,
IN SIZE_T Length); IN SIZE_T Length);
XTAPI XTAPI
SIZE_T SIZE_T
RtlCompareStringInsensitive(IN CONST PCHAR String1, RtlCompareStringInsensitive(IN PCSTR String1,
IN CONST PCHAR String2, IN PCSTR String2,
IN SIZE_T Length); IN SIZE_T Length);
XTAPI XTAPI
SIZE_T SIZE_T
RtlCompareWideString(IN CONST PWCHAR String1, RtlCompareWideString(IN PCWSTR String1,
IN CONST PWCHAR String2, IN PCWSTR String2,
IN SIZE_T Length); IN SIZE_T Length);
XTAPI XTAPI
SIZE_T SIZE_T
RtlCompareWideStringInsensitive(IN CONST PWCHAR String1, RtlCompareWideStringInsensitive(IN PCWSTR String1,
IN CONST PWCHAR String2, IN PCWSTR String2,
IN SIZE_T Length); IN SIZE_T Length);
XTAPI XTAPI
@@ -134,13 +134,13 @@ RtlCopyMemory(OUT PVOID Destination,
XTAPI XTAPI
VOID VOID
RtlCopyString(IN PCHAR Destination, RtlCopyString(IN PCHAR Destination,
IN PCCHAR Source, IN PCSTR Source,
IN ULONG Length); IN ULONG Length);
XTAPI XTAPI
VOID VOID
RtlCopyWideString(IN PWCHAR Destination, RtlCopyWideString(IN PWCHAR Destination,
IN CONST PWCHAR Source, IN PCWSTR Source,
IN ULONG Length); IN ULONG Length);
XTAPI XTAPI
@@ -161,6 +161,26 @@ RtlFindSetBits(IN PRTL_BITMAP BitMap,
IN ULONG_PTR Length, IN ULONG_PTR Length,
IN ULONG_PTR Index); IN ULONG_PTR Index);
XTAPI
PCSTR
RtlFindString(IN PCSTR Source,
IN PCSTR Search);
XTAPI
PCSTR
RtlFindStringInsensitive(IN PCSTR Source,
IN PCSTR Search);
XTAPI
PCWSTR
RtlFindWideString(IN PCWSTR Source,
IN PCWSTR Search);
XTAPI
PCWSTR
RtlFindWideStringInsensitive(IN PCWSTR Source,
IN PCWSTR Search);
XTAPI XTAPI
XTSTATUS XTSTATUS
RtlFormatWideString(IN PRTL_PRINT_CONTEXT Context, RtlFormatWideString(IN PRTL_PRINT_CONTEXT Context,
@@ -229,13 +249,13 @@ RtlSetMemory(OUT PVOID Destination,
XTAPI XTAPI
SIZE_T SIZE_T
RtlStringLength(IN CONST PCHAR String, RtlStringLength(IN PCSTR String,
IN SIZE_T MaxLength); IN SIZE_T MaxLength);
XTAPI XTAPI
SIZE_T SIZE_T
RtlStringToWideString(OUT PWCHAR Destination, RtlStringToWideString(OUT PWCHAR Destination,
IN CONST PCHAR *Source, IN PCSTR *Source,
IN SIZE_T Length); IN SIZE_T Length);
XTAPI XTAPI
@@ -246,42 +266,58 @@ RtlTestBit(IN PRTL_BITMAP BitMap,
XTAPI XTAPI
PCHAR PCHAR
RtlTokenizeString(IN PCHAR String, RtlTokenizeString(IN PCHAR String,
IN CONST PCHAR Delimiter, IN PCSTR Delimiter,
IN OUT PCHAR *SavePtr); IN OUT PCHAR *SavePtr);
XTAPI XTAPI
PWCHAR PWCHAR
RtlTokenizeWideString(IN PWCHAR String, RtlTokenizeWideString(IN PWCHAR String,
IN CONST PWCHAR Delimiter, IN PCWSTR Delimiter,
IN OUT PWCHAR *SavePtr); IN OUT PWCHAR *SavePtr);
XTAPI XTAPI
PCHAR CHAR
RtlTrimLeftString(IN CONST PCHAR String); RtlToLowerCharacter(IN CHAR Character);
XTAPI XTAPI
PWCHAR WCHAR
RtlTrimLeftWideString(IN CONST PWCHAR String); RtlToLowerWideCharacter(IN WCHAR Character);
XTAPI
CHAR
RtlToUpperCharacter(IN CHAR Character);
XTAPI
WCHAR
RtlToUpperWideCharacter(IN WCHAR Character);
XTAPI XTAPI
PCHAR PCHAR
RtlTrimRightString(IN CONST PCHAR String); RtlTrimLeftString(IN PCHAR String);
XTAPI XTAPI
PWCHAR PWCHAR
RtlTrimRightWideString(IN CONST PWCHAR String); RtlTrimLeftWideString(IN PWCHAR String);
XTAPI XTAPI
PCHAR PCHAR
RtlTrimString(IN CONST PCHAR String); RtlTrimRightString(IN PCHAR String);
XTAPI XTAPI
PWCHAR PWCHAR
RtlTrimWideString(IN CONST PWCHAR String); RtlTrimRightWideString(IN PWCHAR String);
XTAPI
PCHAR
RtlTrimString(IN PCHAR String);
XTAPI
PWCHAR
RtlTrimWideString(IN PWCHAR String);
XTAPI XTAPI
SIZE_T SIZE_T
RtlWideStringLength(IN CONST PWCHAR String, RtlWideStringLength(IN PCWSTR String,
IN SIZE_T MaxLength); IN SIZE_T MaxLength);
XTAPI XTAPI

View File

@@ -7,6 +7,7 @@
*/ */
/* Base XT headers */ /* Base XT headers */
#include <xtcompat.h>
#include <xtdefs.h> #include <xtdefs.h>
#include <xtstatus.h> #include <xtstatus.h>
#include <xttarget.h> #include <xttarget.h>

21
sdk/xtdk/xtcompat.h Normal file
View File

@@ -0,0 +1,21 @@
/**
* PROJECT: ExectOS
* COPYRIGHT: See COPYING.md in the top level directory
* FILE: sdk/xtdk/xtcompat.h
* DESCRIPTION: C/C++ compatibility macros
* DEVELOPERS: Aiken Harris <harraiken91@gmail.com>
*/
#ifndef __XTDK_XTCOMPAT_H
#define __XTDK_XTCOMPAT_H
#ifdef __cplusplus
#define XTCLINK extern "C"
typedef wchar_t wchar;
#else
#define XTCLINK
typedef unsigned short wchar;
#endif
#endif /* __XTDK_XTCOMPAT_H */

View File

@@ -20,7 +20,7 @@
/* XTOS platform debugging macros */ /* XTOS platform debugging macros */
#ifdef DBG #ifdef DBG
#define DEBUG 1 #define DEBUG 1
#define DebugPrint(Format, ...) if(KeDbgPrint) KeDbgPrint(Format, __VA_ARGS__); #define DebugPrint(Format, ...) if(KdPrint) KdPrint(Format, __VA_ARGS__);
#else #else
#define DEBUG 0 #define DEBUG 0
#define DebugPrint(Format, ...) ((VOID)NULL) #define DebugPrint(Format, ...) ((VOID)NULL)

View File

@@ -95,7 +95,8 @@
#define SIGNATURE32(A, B, C, D) (SIGNATURE16(A, B) | (SIGNATURE16(C, D) << 16)) #define SIGNATURE32(A, B, C, D) (SIGNATURE16(A, B) | (SIGNATURE16(C, D) << 16))
#define SIGNATURE64(A, B, C, D, E, F, G, H) (SIGNATURE32(A, B, C, D) | ((UINT64)(SIGNATURE32(E, F, G, H)) << 32)) #define SIGNATURE64(A, B, C, D, E, F, G, H) (SIGNATURE32(A, B, C, D) | ((UINT64)(SIGNATURE32(E, F, G, H)) << 32))
/* XT size to pages conversion macro */ /* XT size <-> pages conversion macro */
#define PAGES_TO_SIZE(Pages) ((Pages) << MM_PAGE_SHIFT)
#define SIZE_TO_PAGES(Size) (((Size) >> MM_PAGE_SHIFT) + (((Size) & (MM_PAGE_MASK)) ? 1 : 0)) #define SIZE_TO_PAGES(Size) (((Size) >> MM_PAGE_SHIFT) + (((Size) & (MM_PAGE_MASK)) ? 1 : 0))
/* Macros for concatenating strings */ /* Macros for concatenating strings */

View File

@@ -89,7 +89,6 @@ typedef struct _FIRMWARE_INFORMATION_BLOCK
typedef struct _LOADER_INFORMATION_BLOCK typedef struct _LOADER_INFORMATION_BLOCK
{ {
PVOID DbgPrint; PVOID DbgPrint;
ULONG PageMapLevel;
} LOADER_INFORMATION_BLOCK, *PLOADER_INFORMATION_BLOCK; } LOADER_INFORMATION_BLOCK, *PLOADER_INFORMATION_BLOCK;
/* Boot Loader memory mapping information */ /* Boot Loader memory mapping information */

View File

@@ -7,6 +7,7 @@
*/ */
/* Base XT headers */ /* Base XT headers */
#include <xtcompat.h>
#include <xtdefs.h> #include <xtdefs.h>
#include <xtstatus.h> #include <xtstatus.h>
#include <xttarget.h> #include <xttarget.h>
@@ -30,6 +31,7 @@
#include <extypes.h> #include <extypes.h>
#include <hltypes.h> #include <hltypes.h>
#include <iotypes.h> #include <iotypes.h>
#include <kdtypes.h>
#include <ketypes.h> #include <ketypes.h>
#include <ldrtypes.h> #include <ldrtypes.h>
#include <mmtypes.h> #include <mmtypes.h>

View File

@@ -59,6 +59,7 @@
#define STATUS_INVALID_PARAMETER ((XTSTATUS) 0xC000000DL) #define STATUS_INVALID_PARAMETER ((XTSTATUS) 0xC000000DL)
#define STATUS_END_OF_FILE ((XTSTATUS) 0xC0000011L) #define STATUS_END_OF_FILE ((XTSTATUS) 0xC0000011L)
#define STATUS_NO_MEMORY ((XTSTATUS) 0xC0000017L) #define STATUS_NO_MEMORY ((XTSTATUS) 0xC0000017L)
#define STATUS_PORT_DISCONNECTED ((XTSTATUS) 0xC0000037L)
#define STATUS_CRC_ERROR ((XTSTATUS) 0xC000003FL) #define STATUS_CRC_ERROR ((XTSTATUS) 0xC000003FL)
#define STATUS_INSUFFICIENT_RESOURCES ((XTSTATUS) 0xC000009AL) #define STATUS_INSUFFICIENT_RESOURCES ((XTSTATUS) 0xC000009AL)
#define STATUS_DEVICE_NOT_READY ((XTSTATUS) 0xC00000A3L) #define STATUS_DEVICE_NOT_READY ((XTSTATUS) 0xC00000A3L)

View File

@@ -50,7 +50,9 @@ typedef enum _KTIMER_TYPE KTIMER_TYPE, *PKTIMER_TYPE;
typedef enum _KUBSAN_DATA_TYPE KUBSAN_DATA_TYPE, *PKUBSAN_DATA_TYPE; typedef enum _KUBSAN_DATA_TYPE KUBSAN_DATA_TYPE, *PKUBSAN_DATA_TYPE;
typedef enum _LOADER_MEMORY_TYPE LOADER_MEMORY_TYPE, *PLOADER_MEMORY_TYPE; typedef enum _LOADER_MEMORY_TYPE LOADER_MEMORY_TYPE, *PLOADER_MEMORY_TYPE;
typedef enum _MODE MODE, *PMODE; typedef enum _MODE MODE, *PMODE;
typedef enum _RTL_VARIABLE_TYPE RTL_VARIABLE_TYPE, *PRTL_VARIABLE_TYPE;
typedef enum _SYSTEM_FIRMWARE_TYPE SYSTEM_FIRMWARE_TYPE, *PSYSTEM_FIRMWARE_TYPE; typedef enum _SYSTEM_FIRMWARE_TYPE SYSTEM_FIRMWARE_TYPE, *PSYSTEM_FIRMWARE_TYPE;
typedef enum _SYSTEM_RESOURCE_TYPE SYSTEM_RESOURCE_TYPE, *PSYSTEM_RESOURCE_TYPE;
typedef enum _WAIT_TYPE WAIT_TYPE, *PWAIT_TYPE; typedef enum _WAIT_TYPE WAIT_TYPE, *PWAIT_TYPE;
/* Structures forward references */ /* Structures forward references */
@@ -69,6 +71,7 @@ typedef struct _ANSI_STRING ANSI_STRING, *PANSI_STRING;
typedef struct _ANSI_STRING32 ANSI_STRING32, *PANSI_STRING32; typedef struct _ANSI_STRING32 ANSI_STRING32, *PANSI_STRING32;
typedef struct _ANSI_STRING64 ANSI_STRING64, *PANSI_STRING64; typedef struct _ANSI_STRING64 ANSI_STRING64, *PANSI_STRING64;
typedef struct _CPPORT CPPORT, *PCPPORT; typedef struct _CPPORT CPPORT, *PCPPORT;
typedef const struct _CMMPAGEMAP_ROUTINES CMMPAGEMAP_ROUTINES, *PCMMPAGEMAP_ROUTINES;
typedef struct _CSTRING CSTRING, *PCSTRING; typedef struct _CSTRING CSTRING, *PCSTRING;
typedef struct _EFI_1394_DEVICE_PATH EFI_1394_DEVICE_PATH, *PEFI_1394_DEVICE_PATH; typedef struct _EFI_1394_DEVICE_PATH EFI_1394_DEVICE_PATH, *PEFI_1394_DEVICE_PATH;
typedef struct _EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR, *PEFI_ACPI_ADDRESS_SPACE_DESCRIPTOR; typedef struct _EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR, *PEFI_ACPI_ADDRESS_SPACE_DESCRIPTOR;
@@ -233,9 +236,12 @@ typedef struct _FIRMWARE_INFORMATION_BLOCK FIRMWARE_INFORMATION_BLOCK, *PFIRMWAR
typedef struct _FLOAT128 FLOAT128, *PFLOAT128; typedef struct _FLOAT128 FLOAT128, *PFLOAT128;
typedef struct _GENERIC_ADDRESS GENERIC_ADDRESS, *PGENERIC_ADDRESS; typedef struct _GENERIC_ADDRESS GENERIC_ADDRESS, *PGENERIC_ADDRESS;
typedef struct _GUID GUID, *PGUID; typedef struct _GUID GUID, *PGUID;
typedef struct _HAL_FRAMEBUFFER_DATA HAL_FRAMEBUFFER_DATA, *PHAL_FRAMEBUFFER_DATA; typedef struct _HL_FRAMEBUFFER_DATA HL_FRAMEBUFFER_DATA, *PHL_FRAMEBUFFER_DATA;
typedef struct _HL_SCROLL_REGION_DATA HL_SCROLL_REGION_DATA, *PHL_SCROLL_REGION_DATA;
typedef struct _KAPC KAPC, *PKAPC; typedef struct _KAPC KAPC, *PKAPC;
typedef struct _KAPC_STATE KAPC_STATE, *PKAPC_STATE; typedef struct _KAPC_STATE KAPC_STATE, *PKAPC_STATE;
typedef struct _KD_DEBUG_MODE KD_DEBUG_MODE, *PKD_DEBUG_MODE;
typedef struct _KD_DISPATCH_TABLE KD_DISPATCH_TABLE, *PKD_DISPATCH_TABLE;
typedef struct _KDPC KDPC, *PKDPC; typedef struct _KDPC KDPC, *PKDPC;
typedef struct _KDPC_DATA KDPC_DATA, *PKDPC_DATA; typedef struct _KDPC_DATA KDPC_DATA, *PKDPC_DATA;
typedef struct _KERNEL_INITIALIZATION_BLOCK KERNEL_INITIALIZATION_BLOCK, *PKERNEL_INITIALIZATION_BLOCK; typedef struct _KERNEL_INITIALIZATION_BLOCK KERNEL_INITIALIZATION_BLOCK, *PKERNEL_INITIALIZATION_BLOCK;
@@ -300,6 +306,9 @@ typedef struct _PECOFF_IMAGE_SECTION_HEADER PECOFF_IMAGE_SECTION_HEADER, *PPECOF
typedef struct _PECOFF_IMAGE_VXD_HEADER PECOFF_IMAGE_VXD_HEADER, *PPECOFF_IMAGE_VXD_HEADER; typedef struct _PECOFF_IMAGE_VXD_HEADER PECOFF_IMAGE_VXD_HEADER, *PPECOFF_IMAGE_VXD_HEADER;
typedef struct _PROCESSOR_IDENTITY PROCESSOR_IDENTITY, *PPROCESSOR_IDENTITY; typedef struct _PROCESSOR_IDENTITY PROCESSOR_IDENTITY, *PPROCESSOR_IDENTITY;
typedef struct _PROCESSOR_POWER_STATE PROCESSOR_POWER_STATE, *PPROCESSOR_POWER_STATE; typedef struct _PROCESSOR_POWER_STATE PROCESSOR_POWER_STATE, *PPROCESSOR_POWER_STATE;
typedef struct _RTL_BITMAP RTL_BITMAP, *PRTL_BITMAP;
typedef struct _RTL_PRINT_CONTEXT RTL_PRINT_CONTEXT, *PRTL_PRINT_CONTEXT;
typedef struct _RTL_PRINT_FORMAT_PROPERTIES RTL_PRINT_FORMAT_PROPERTIES, *PRTL_PRINT_FORMAT_PROPERTIES;
typedef struct _SINGLE_LIST_ENTRY SINGLE_LIST_ENTRY, *PSINGLE_LIST_ENTRY; typedef struct _SINGLE_LIST_ENTRY SINGLE_LIST_ENTRY, *PSINGLE_LIST_ENTRY;
typedef struct _SMBIOS_TABLE_HEADER SMBIOS_TABLE_HEADER, *PSMBIOS_TABLE_HEADER; typedef struct _SMBIOS_TABLE_HEADER SMBIOS_TABLE_HEADER, *PSMBIOS_TABLE_HEADER;
typedef struct _SMBIOS3_TABLE_HEADER SMBIOS3_TABLE_HEADER, *PSMBIOS3_TABLE_HEADER; typedef struct _SMBIOS3_TABLE_HEADER SMBIOS3_TABLE_HEADER, *PSMBIOS3_TABLE_HEADER;

View File

@@ -29,6 +29,7 @@
#define MEMORY_ALIGNMENT 8 #define MEMORY_ALIGNMENT 8
#define MM_USERPAGE_TABLES 1536 #define MM_USERPAGE_TABLES 1536
#define MM_VIRTUAL_PAGESIZE 20 #define MM_VIRTUAL_PAGESIZE 20
#define STACK_ALIGNMENT 4
#elif defined(__amd64__) || defined(__x86_64__) #elif defined(__amd64__) || defined(__x86_64__)
#define _ARCH amd64 #define _ARCH amd64
#define _ARCH_AMD64 1 #define _ARCH_AMD64 1
@@ -43,6 +44,7 @@
#define MEMORY_ALIGNMENT 16 #define MEMORY_ALIGNMENT 16
#define MM_USERPAGE_TABLES 4194304 #define MM_USERPAGE_TABLES 4194304
#define MM_VIRTUAL_PAGESIZE 52 #define MM_VIRTUAL_PAGESIZE 52
#define STACK_ALIGNMENT 16
#else #else
#error Unknown architecture #error Unknown architecture
#endif #endif

View File

@@ -10,6 +10,7 @@
#define __XTDK_XTTYPES_H #define __XTDK_XTTYPES_H
#include <xttarget.h> #include <xttarget.h>
#include <xtcompat.h>
/* Standard C types */ /* Standard C types */
@@ -128,7 +129,7 @@ typedef CHAR SZ, *PSZ;
typedef const CHAR CSZ, *PCSZ; typedef const CHAR CSZ, *PCSZ;
/* UNICODE character types */ /* UNICODE character types */
typedef USHORT WCHAR, *PWCHAR; typedef wchar WCHAR, *PWCHAR;
typedef WCHAR *PWCH, *LPWCH; typedef WCHAR *PWCH, *LPWCH;
typedef const WCHAR *PCWCH, *LPCWCH; typedef const WCHAR *PCWCH, *LPCWCH;
typedef WCHAR *PWSTR, *LPWSTR, *NWPSTR; typedef WCHAR *PWSTR, *LPWSTR, *NWPSTR;

View File

@@ -16,6 +16,7 @@ list(APPEND LIBXTLDR_SOURCE
# Specify list of source code files # Specify list of source code files
list(APPEND XTLDR_SOURCE list(APPEND XTLDR_SOURCE
${XTLDR_SOURCE_DIR}/arch/${ARCH}/memory.c ${XTLDR_SOURCE_DIR}/arch/${ARCH}/memory.c
${XTLDR_SOURCE_DIR}/bootutil.c
${XTLDR_SOURCE_DIR}/config.c ${XTLDR_SOURCE_DIR}/config.c
${XTLDR_SOURCE_DIR}/console.c ${XTLDR_SOURCE_DIR}/console.c
${XTLDR_SOURCE_DIR}/debug.c ${XTLDR_SOURCE_DIR}/debug.c
@@ -49,6 +50,5 @@ set_install_target(xtldr efi/boot)
# Set loader entrypoint and subsystem # Set loader entrypoint and subsystem
set_entrypoint(xtldr "BlStartXtLoader") set_entrypoint(xtldr "BlStartXtLoader")
set_imagebase(xtldr ${BASEADDRESS_XTLDR})
set_linker_map(xtldr TRUE) set_linker_map(xtldr TRUE)
set_subsystem(xtldr efi_application) set_subsystem(xtldr efi_application)

View File

@@ -4,6 +4,7 @@
* FILE: xtldr/arch/amd64/memory.c * FILE: xtldr/arch/amd64/memory.c
* DESCRIPTION: XT Boot Loader AMD64 specific memory management * DESCRIPTION: XT Boot Loader AMD64 specific memory management
* DEVELOPERS: Rafal Kupiec <belliash@codingworkshop.eu.org> * DEVELOPERS: Rafal Kupiec <belliash@codingworkshop.eu.org>
* Aiken Harris <harraiken91@gmail.com>
*/ */
#include <xtldr.h> #include <xtldr.h>
@@ -34,7 +35,7 @@ BlBuildPageMap(IN PXTBL_PAGE_MAPPING PageMap,
EFI_STATUS Status; EFI_STATUS Status;
/* Allocate pages for the Page Map */ /* Allocate pages for the Page Map */
Status = BlAllocateMemoryPages(1, &Address); Status = BlAllocateMemoryPages(AllocateAnyPages, 1, &Address);
if(Status != STATUS_EFI_SUCCESS) if(Status != STATUS_EFI_SUCCESS)
{ {
/* Memory allocation failure */ /* Memory allocation failure */
@@ -53,6 +54,15 @@ BlBuildPageMap(IN PXTBL_PAGE_MAPPING PageMap,
return Status; return Status;
} }
/* Map the trampoline code area */
Status = BlMapVirtualMemory(PageMap, (PVOID)MM_TRAMPOLINE_ADDRESS,(PVOID)MM_TRAMPOLINE_ADDRESS,
1, LoaderFirmwareTemporary);
if(Status != STATUS_EFI_SUCCESS)
{
/* Mapping trampoline code failed */
return Status;
}
/* Get list of XTLDR modules */ /* Get list of XTLDR modules */
ModulesList = BlGetModulesList(); ModulesList = BlGetModulesList();
ModulesListEntry = ModulesList->Flink; ModulesListEntry = ModulesList->Flink;
@@ -149,12 +159,13 @@ BlBuildPageMap(IN PXTBL_PAGE_MAPPING PageMap,
XTCDECL XTCDECL
EFI_STATUS EFI_STATUS
BlMapPage(IN PXTBL_PAGE_MAPPING PageMap, BlMapPage(IN PXTBL_PAGE_MAPPING PageMap,
IN UINT_PTR VirtualAddress, IN ULONG_PTR VirtualAddress,
IN UINT_PTR PhysicalAddress, IN ULONG_PTR PhysicalAddress,
IN UINT NumberOfPages) IN ULONG NumberOfPages)
{ {
PVOID Pml1, Pml2, Pml3, Pml4, Pml5;
SIZE_T Pml1Entry, Pml2Entry, Pml3Entry, Pml4Entry, Pml5Entry; SIZE_T Pml1Entry, Pml2Entry, Pml3Entry, Pml4Entry, Pml5Entry;
PHARDWARE_PTE Pml1, Pml2, Pml3, Pml4, Pml5; PHARDWARE_PTE PmlTable;
SIZE_T PageFrameNumber; SIZE_T PageFrameNumber;
EFI_STATUS Status; EFI_STATUS Status;
@@ -165,7 +176,7 @@ BlMapPage(IN PXTBL_PAGE_MAPPING PageMap,
while(NumberOfPages > 0) while(NumberOfPages > 0)
{ {
/* Calculate the indices in the various Page Tables from the virtual address */ /* Calculate the indices in the various Page Tables from the virtual address */
Pml5Entry = (VirtualAddress & ((ULONGLONG)0x1FF << MM_LA57_SHIFT)) >> MM_LA57_SHIFT; Pml5Entry = (VirtualAddress & ((ULONGLONG)0x1FF << MM_P5I_SHIFT)) >> MM_P5I_SHIFT;
Pml4Entry = (VirtualAddress & ((ULONGLONG)0x1FF << MM_PXI_SHIFT)) >> MM_PXI_SHIFT; Pml4Entry = (VirtualAddress & ((ULONGLONG)0x1FF << MM_PXI_SHIFT)) >> MM_PXI_SHIFT;
Pml3Entry = (VirtualAddress & ((ULONGLONG)0x1FF << MM_PPI_SHIFT)) >> MM_PPI_SHIFT; Pml3Entry = (VirtualAddress & ((ULONGLONG)0x1FF << MM_PPI_SHIFT)) >> MM_PPI_SHIFT;
Pml2Entry = (VirtualAddress & ((ULONGLONG)0x1FF << MM_PDI_SHIFT)) >> MM_PDI_SHIFT; Pml2Entry = (VirtualAddress & ((ULONGLONG)0x1FF << MM_PDI_SHIFT)) >> MM_PDI_SHIFT;
@@ -175,7 +186,7 @@ BlMapPage(IN PXTBL_PAGE_MAPPING PageMap,
if(PageMap->PageMapLevel == 5) if(PageMap->PageMapLevel == 5)
{ {
/* Five level Page Map */ /* Five level Page Map */
Pml5 = ((PHARDWARE_PTE)(PageMap->PtePointer)); Pml5 = PageMap->PtePointer;
/* Get PML4 */ /* Get PML4 */
Status = BlpGetNextPageTable(PageMap, Pml5, Pml5Entry, &Pml4); Status = BlpGetNextPageTable(PageMap, Pml5, Pml5Entry, &Pml4);
@@ -188,7 +199,7 @@ BlMapPage(IN PXTBL_PAGE_MAPPING PageMap,
else else
{ {
/* Four level Page Map */ /* Four level Page Map */
Pml4 = ((PHARDWARE_PTE)(PageMap->PtePointer)); Pml4 = PageMap->PtePointer;
} }
/* Get PML3 */ /* Get PML3 */
@@ -216,9 +227,11 @@ BlMapPage(IN PXTBL_PAGE_MAPPING PageMap,
} }
/* Set paging entry settings */ /* Set paging entry settings */
Pml1[Pml1Entry].PageFrameNumber = PageFrameNumber; PmlTable = (PHARDWARE_PTE)Pml1;
Pml1[Pml1Entry].Valid = 1; RtlZeroMemory(&PmlTable[Pml1Entry], sizeof(HARDWARE_PTE));
Pml1[Pml1Entry].Writable = 1; PmlTable[Pml1Entry].PageFrameNumber = PageFrameNumber;
PmlTable[Pml1Entry].Valid = 1;
PmlTable[Pml1Entry].Writable = 1;
/* Take next virtual address and PFN */ /* Take next virtual address and PFN */
VirtualAddress += EFI_PAGE_SIZE; VirtualAddress += EFI_PAGE_SIZE;
@@ -232,6 +245,81 @@ BlMapPage(IN PXTBL_PAGE_MAPPING PageMap,
return STATUS_EFI_SUCCESS; return STATUS_EFI_SUCCESS;
} }
/**
* Returns next level of the Page Table.
*
* @param PageMap
* Supplies a pointer to the page mapping structure.
*
* @param PageTable
* Supplies a pointer to the current Page Table.
*
* @param Entry
* Supplies an index of the current Page Table entry.
*
* @param NextPageTable
* Supplies a pointer to the memory area where the next Page Table level is returned.
*
* @return This routine returns a status code.
*
* @since XT 1.0
*/
XTCDECL
EFI_STATUS
BlpGetNextPageTable(IN PXTBL_PAGE_MAPPING PageMap,
IN PVOID PageTable,
IN SIZE_T Entry,
OUT PVOID *NextPageTable)
{
EFI_PHYSICAL_ADDRESS Address;
ULONGLONG PmlPointer = 0;
PHARDWARE_PTE PmlTable;
EFI_STATUS Status;
PmlTable = (PHARDWARE_PTE)PageTable;
/* Check if this is a valid table */
if(PmlTable[Entry].Valid)
{
/* Get PML pointer */
PmlPointer = PmlTable[Entry].PageFrameNumber;
PmlPointer <<= EFI_PAGE_SHIFT;
}
else
{
/* Allocate pages for new PML entry */
Status = BlAllocateMemoryPages(AllocateAnyPages, 1, &Address);
if(Status != STATUS_EFI_SUCCESS)
{
/* Memory allocation failure */
return Status;
}
/* Add new memory mapping */
Status = BlMapVirtualMemory(PageMap, NULL, (PVOID)(UINT_PTR)Address, 1, LoaderMemoryData);
if(Status != STATUS_EFI_SUCCESS)
{
/* Memory mapping failure */
return Status;
}
/* Fill allocated memory with zeros */
RtlZeroMemory((PVOID)(ULONGLONG)Address, EFI_PAGE_SIZE);
/* Set paging entry settings */
PmlTable[Entry].PageFrameNumber = Address / EFI_PAGE_SIZE;
PmlTable[Entry].Valid = 1;
PmlTable[Entry].Writable = 1;
PmlPointer = (ULONGLONG)Address;
}
/* Set next Page Map Level (PML) */
*NextPageTable = (PVOID)(ULONGLONG)PmlPointer;
/* Return success */
return STATUS_EFI_SUCCESS;
}
/** /**
* Creates a recursive self mapping for all PML levels. * Creates a recursive self mapping for all PML levels.
* *
@@ -250,26 +338,30 @@ EFI_STATUS
BlpSelfMapPml(IN PXTBL_PAGE_MAPPING PageMap, BlpSelfMapPml(IN PXTBL_PAGE_MAPPING PageMap,
IN ULONG_PTR SelfMapAddress) IN ULONG_PTR SelfMapAddress)
{ {
PHARDWARE_PTE PmlBase;
ULONGLONG PmlIndex; ULONGLONG PmlIndex;
/* Initialize PML base pointer */
PmlBase = (PHARDWARE_PTE)PageMap->PtePointer;
/* Check page map level */ /* Check page map level */
if(PageMap->PageMapLevel == 5) if(PageMap->PageMapLevel == 5)
{ {
/* Self-mapping for PML5 is not supported */ /* Calculate PML index based on provided self map address for PML5 */
BlDebugPrint(L"PML5 self-mapping not supported yet!\n"); PmlIndex = (SelfMapAddress >> MM_P5I_SHIFT) & 0x1FF;
return STATUS_EFI_UNSUPPORTED;
} }
else else
{ {
/* Calculate PML index based on provided self map address */ /* Calculate PML index based on provided self map address for PML4 */
PmlIndex = (SelfMapAddress >> MM_PXI_SHIFT) & 0x1FF; PmlIndex = (SelfMapAddress >> MM_PXI_SHIFT) & 0x1FF;
/* Add self-mapping for PML4 */
((PHARDWARE_PTE)PageMap->PtePointer)[PmlIndex].PageFrameNumber = (UINT_PTR)PageMap->PtePointer / EFI_PAGE_SIZE;
((PHARDWARE_PTE)PageMap->PtePointer)[PmlIndex].Valid = 1;
((PHARDWARE_PTE)PageMap->PtePointer)[PmlIndex].Writable = 1;
} }
/* Add self-mapping */
RtlZeroMemory(&PmlBase[PmlIndex], sizeof(HARDWARE_PTE));
PmlBase[PmlIndex].PageFrameNumber = (UINT_PTR)PageMap->PtePointer / EFI_PAGE_SIZE;
PmlBase[PmlIndex].Valid = 1;
PmlBase[PmlIndex].Writable = 1;
/* Return success */ /* Return success */
return STATUS_EFI_SUCCESS; return STATUS_EFI_SUCCESS;
} }

View File

@@ -4,6 +4,7 @@
* FILE: xtldr/arch/i686/memory.c * FILE: xtldr/arch/i686/memory.c
* DESCRIPTION: XT Boot Loader i686 specific memory management * DESCRIPTION: XT Boot Loader i686 specific memory management
* DEVELOPERS: Rafal Kupiec <belliash@codingworkshop.eu.org> * DEVELOPERS: Rafal Kupiec <belliash@codingworkshop.eu.org>
* Aiken Harris <harraiken91@gmail.com>
*/ */
#include <xtldr.h> #include <xtldr.h>
@@ -31,38 +32,54 @@ BlBuildPageMap(IN PXTBL_PAGE_MAPPING PageMap,
EFI_STATUS Status; EFI_STATUS Status;
ULONG Index; ULONG Index;
/* Allocate pages for the Page Map */ /* Check the page map level to determine which paging structure to create */
Status = BlAllocateMemoryPages(1, &Address); if(PageMap->PageMapLevel == 3)
if(Status != STATUS_EFI_SUCCESS)
{ {
/* Memory allocation failure */ /* Allocate a page for the 3-level page map structure (PAE enabled) */
return Status; Status = BlAllocateMemoryPages(AllocateAnyPages, 1, &Address);
if(Status != STATUS_EFI_SUCCESS)
{
/* Memory allocation failed, cannot proceed with page map creation */
return Status;
}
/* Assign the allocated page to the page map and zero it out */
PageMap->PtePointer = (PVOID)(UINT_PTR)Address;
RtlZeroMemory(PageMap->PtePointer, EFI_PAGE_SIZE);
/* Allocate 4 pages for the Page Directories (PDs) */
Status = BlAllocateMemoryPages(AllocateAnyPages, 4, &DirectoryAddress);
if(Status != STATUS_EFI_SUCCESS)
{
/* Memory allocation failed, cannot proceed with page map creation */
return Status;
}
/* Zero-fill the allocated memory for the Page Directories */
RtlZeroMemory((PVOID)DirectoryAddress, EFI_PAGE_SIZE * 4);
/* Fill the PDPT with pointers to the Page Directories */
for(Index = 0; Index < 4; Index++)
{
RtlZeroMemory(&((PHARDWARE_MODERN_PTE)PageMap->PtePointer)[Index], sizeof(HARDWARE_MODERN_PTE));
((PHARDWARE_MODERN_PTE)PageMap->PtePointer)[Index].PageFrameNumber = DirectoryAddress / EFI_PAGE_SIZE;
((PHARDWARE_MODERN_PTE)PageMap->PtePointer)[Index].Valid = 1;
DirectoryAddress += EFI_PAGE_SIZE;
}
} }
else
/* Assign and zero-fill memory used by page mappings */
PageMap->PtePointer = (PVOID)(UINT_PTR)Address;
RtlZeroMemory(PageMap->PtePointer, EFI_PAGE_SIZE);
/* Allocate pages for the Page Directory */
Status = BlAllocateMemoryPages(4, &DirectoryAddress);
if(Status != STATUS_EFI_SUCCESS)
{ {
/* Memory allocation failure */ /* Allocate a page for the 2-level page map structure (PAE disabled) */
return Status; Status = BlAllocateMemoryPages(AllocateAnyPages, 1, &Address);
} if(Status != STATUS_EFI_SUCCESS)
{
/* Memory allocation failed, cannot proceed with page map creation */
return Status;
}
/* Zero fill memory used by Page Directory */ /* Assign the allocated page to the page map and zero it out */
RtlZeroMemory((PVOID)DirectoryAddress, EFI_PAGE_SIZE * 4); PageMap->PtePointer = (PVOID)(UINT_PTR)Address;
RtlZeroMemory(PageMap->PtePointer, EFI_PAGE_SIZE);
/* Set the page directory into the PDPT and mark it present */
for(Index = 0; Index < 4; Index++)
{
/* Set paging entry settings */
((PHARDWARE_PTE)PageMap->PtePointer)[Index].PageFrameNumber = DirectoryAddress / EFI_PAGE_SIZE;
((PHARDWARE_PTE)PageMap->PtePointer)[Index].Valid = 1;
/* Next valid PFN address */
DirectoryAddress += EFI_PAGE_SIZE;
} }
/* Add page mapping itself to memory mapping */ /* Add page mapping itself to memory mapping */
@@ -73,6 +90,15 @@ BlBuildPageMap(IN PXTBL_PAGE_MAPPING PageMap,
return Status; return Status;
} }
/* Map the trampoline code area */
Status = BlMapVirtualMemory(PageMap, (PVOID)MM_TRAMPOLINE_ADDRESS,(PVOID)MM_TRAMPOLINE_ADDRESS,
1, LoaderFirmwareTemporary);
if(Status != STATUS_EFI_SUCCESS)
{
/* Mapping trampoline code failed */
return Status;
}
/* Get list of XTLDR modules */ /* Get list of XTLDR modules */
ModulesList = BlGetModulesList(); ModulesList = BlGetModulesList();
ModulesListEntry = ModulesList->Flink; ModulesListEntry = ModulesList->Flink;
@@ -169,58 +195,81 @@ BlBuildPageMap(IN PXTBL_PAGE_MAPPING PageMap,
XTCDECL XTCDECL
EFI_STATUS EFI_STATUS
BlMapPage(IN PXTBL_PAGE_MAPPING PageMap, BlMapPage(IN PXTBL_PAGE_MAPPING PageMap,
IN UINT_PTR VirtualAddress, IN ULONG_PTR VirtualAddress,
IN UINT_PTR PhysicalAddress, IN ULONG_PTR PhysicalAddress,
IN UINT NumberOfPages) IN ULONG NumberOfPages)
{ {
SIZE_T Pml1Entry, Pml2Entry, Pml3Entry;
PHARDWARE_PTE Pml1, Pml2, Pml3;
SIZE_T PageFrameNumber; SIZE_T PageFrameNumber;
PVOID Pml1, Pml2, Pml3;
SIZE_T Pml1Entry, Pml2Entry, Pml3Entry;
PHARDWARE_LEGACY_PTE LegacyPmlTable;
PHARDWARE_MODERN_PTE PmlTable;
EFI_STATUS Status; EFI_STATUS Status;
/* Set the Page Frame Number (PFN) */ /* Set the Page Frame Number (PFN) */
PageFrameNumber = PhysicalAddress >> EFI_PAGE_SHIFT; PageFrameNumber = PhysicalAddress >> EFI_PAGE_SHIFT;
/* Do the recursive mapping */ /* Map all requested pages */
while(NumberOfPages > 0) while(NumberOfPages > 0)
{ {
/* Calculate the indices in the various Page Tables from the virtual address */ /* Check the paging mode to use the correct page table structure */
Pml3Entry = (VirtualAddress & ((ULONGLONG)0x1FF << 30)) >> 30;
Pml2Entry = (VirtualAddress & ((ULONGLONG)0x1FF << 21)) >> 21;
Pml1Entry = (VirtualAddress & ((ULONGLONG)0x1FF << 12)) >> 12;
/* Check page map level */
if(PageMap->PageMapLevel == 3) if(PageMap->PageMapLevel == 3)
{ {
/* Three level Page Map */ /* Calculate the indices for PAE page tables */
Pml3 = ((PHARDWARE_PTE)(PageMap->PtePointer)); Pml3Entry = (VirtualAddress >> 30) & 0x3;
Pml2Entry = (VirtualAddress >> 21) & 0x1FF;
Pml1Entry = (VirtualAddress >> 12) & 0x1FF;
/* Get PML2 */ /* Get Page Directory Pointer Table (PML3) */
Pml3 = PageMap->PtePointer;
/* Get Page Directory (PML2) */
Status = BlpGetNextPageTable(PageMap, Pml3, Pml3Entry, &Pml2); Status = BlpGetNextPageTable(PageMap, Pml3, Pml3Entry, &Pml2);
if(Status != STATUS_EFI_SUCCESS) if(Status != STATUS_EFI_SUCCESS)
{ {
/* Memory mapping failure */ /* Failed to get the Page Table, abort mapping */
return Status; return Status;
} }
/* Get Page Table (PML1) */
Status = BlpGetNextPageTable(PageMap, Pml2, Pml2Entry, &Pml1);
if(Status != STATUS_EFI_SUCCESS)
{
/* Failed to get the Page Table, abort mapping */
return Status;
}
/* Set the 64-bit PTE entry */
PmlTable = (PHARDWARE_MODERN_PTE)Pml1;
RtlZeroMemory(&PmlTable[Pml1Entry], sizeof(HARDWARE_MODERN_PTE));
PmlTable[Pml1Entry].PageFrameNumber = PageFrameNumber;
PmlTable[Pml1Entry].Valid = 1;
PmlTable[Pml1Entry].Writable = 1;
} }
else else
{ {
/* Two level Page Map */ /* Calculate the indices for non-PAE page tables */
Pml2 = ((PHARDWARE_PTE)(PageMap->PtePointer)); Pml2Entry = (VirtualAddress >> 22) & 0x3FF;
} Pml1Entry = (VirtualAddress >> 12) & 0x3FF;
/* Get PML1 */ /* Get Page Directory (PML2) */
Status = BlpGetNextPageTable(PageMap, Pml2, Pml2Entry, &Pml1); Pml2 = PageMap->PtePointer;
if(Status != STATUS_EFI_SUCCESS)
{
/* Memory mapping failure */
return Status;
}
/* Set paging entry settings */ /* Get Page Table (PML1) */
Pml1[Pml1Entry].PageFrameNumber = PageFrameNumber; Status = BlpGetNextPageTable(PageMap, Pml2, Pml2Entry, &Pml1);
Pml1[Pml1Entry].Valid = 1; if(Status != STATUS_EFI_SUCCESS)
Pml1[Pml1Entry].Writable = 1; {
/* Failed to get the Page Table, abort mapping */
return Status;
}
/* Set the 32-bit PTE entry */
LegacyPmlTable = (PHARDWARE_LEGACY_PTE)Pml1;
RtlZeroMemory(&LegacyPmlTable[Pml1Entry], sizeof(HARDWARE_LEGACY_PTE));
LegacyPmlTable[Pml1Entry].PageFrameNumber = (UINT32)PageFrameNumber;
LegacyPmlTable[Pml1Entry].Valid = 1;
LegacyPmlTable[Pml1Entry].Writable = 1;
}
/* Take next virtual address and PFN */ /* Take next virtual address and PFN */
VirtualAddress += EFI_PAGE_SIZE; VirtualAddress += EFI_PAGE_SIZE;
@@ -234,6 +283,119 @@ BlMapPage(IN PXTBL_PAGE_MAPPING PageMap,
return STATUS_EFI_SUCCESS; return STATUS_EFI_SUCCESS;
} }
/**
* Returns next level of the Page Table.
*
* @param PageMap
* Supplies a pointer to the page mapping structure.
*
* @param PageTable
* Supplies a pointer to the current Page Table.
*
* @param Entry
* Supplies an index of the current Page Table entry.
*
* @param NextPageTable
* Supplies a pointer to the memory area where the next Page Table level is returned.
*
* @return This routine returns a status code.
*
* @since XT 1.0
*/
XTCDECL
EFI_STATUS
BlpGetNextPageTable(IN PXTBL_PAGE_MAPPING PageMap,
IN PVOID PageTable,
IN SIZE_T Entry,
OUT PVOID *NextPageTable)
{
EFI_PHYSICAL_ADDRESS Address;
ULONGLONG PmlPointer = 0;
EFI_STATUS Status;
PHARDWARE_LEGACY_PTE LegacyPmlTable;
PHARDWARE_MODERN_PTE PmlTable;
BOOLEAN ValidPte = FALSE;
/* Check page map level to determine PTE size */
if(PageMap->PageMapLevel >= 3)
{
/* 64-bit PTE for PML3 (PAE enabled) */
PmlTable = (PHARDWARE_MODERN_PTE)PageTable;
if(PmlTable[Entry].Valid)
{
/* Get page frame number from page table entry */
PmlPointer = PmlTable[Entry].PageFrameNumber;
ValidPte = TRUE;
}
}
else
{
/* 32-bit PTE for PML2 (PAE disabled) */
LegacyPmlTable = (PHARDWARE_LEGACY_PTE)PageTable;
if(LegacyPmlTable[Entry].Valid)
{
/* Get page frame number from page table entry */
PmlPointer = LegacyPmlTable[Entry].PageFrameNumber;
ValidPte = TRUE;
}
}
/* Check if page table entry is valid */
if(ValidPte)
{
/* Calculate the base address of the next page table */
PmlPointer <<= EFI_PAGE_SHIFT;
}
else
{
/* Allocate pages for new PML entry */
Status = BlAllocateMemoryPages(AllocateAnyPages, 1, &Address);
if(Status != STATUS_EFI_SUCCESS)
{
/* Memory allocation failure */
return Status;
}
/* Add new memory mapping */
Status = BlMapVirtualMemory(PageMap, NULL, (PVOID)(UINT_PTR)Address, 1, LoaderMemoryData);
if(Status != STATUS_EFI_SUCCESS)
{
/* Memory mapping failure */
return Status;
}
/* Fill allocated memory with zeros */
RtlZeroMemory((PVOID)(ULONGLONG)Address, EFI_PAGE_SIZE);
/* Set paging entry settings based on level */
if(PageMap->PageMapLevel >= 3)
{
/* 64-bit PTE for PML3 (PAE enabled) */
PmlTable = (PHARDWARE_MODERN_PTE)PageTable;
PmlTable[Entry].PageFrameNumber = Address / EFI_PAGE_SIZE;
PmlTable[Entry].Valid = 1;
PmlTable[Entry].Writable = 1;
}
else
{
/* 32-bit PTE for PML2 (PAE disabled) */
LegacyPmlTable = (PHARDWARE_LEGACY_PTE)PageTable;
LegacyPmlTable[Entry].PageFrameNumber = (UINT32)(Address / EFI_PAGE_SIZE);
LegacyPmlTable[Entry].Valid = 1;
LegacyPmlTable[Entry].Writable = 1;
}
/* Return the address of the new page table */
PmlPointer = (ULONGLONG)Address;
}
/* Set next Page Map Level (PML) */
*NextPageTable = (PVOID)(ULONGLONG)PmlPointer;
/* Return success */
return STATUS_EFI_SUCCESS;
}
/** /**
* Creates a recursive self mapping for all PML levels. * Creates a recursive self mapping for all PML levels.
* *
@@ -252,8 +414,9 @@ EFI_STATUS
BlpSelfMapPml(IN PXTBL_PAGE_MAPPING PageMap, BlpSelfMapPml(IN PXTBL_PAGE_MAPPING PageMap,
IN ULONG_PTR SelfMapAddress) IN ULONG_PTR SelfMapAddress)
{ {
PHARDWARE_LEGACY_PTE LegacyPml;
PHARDWARE_MODERN_PTE Pml;
ULONGLONG PmlIndex; ULONGLONG PmlIndex;
PHARDWARE_PTE Pml;
ULONG Index; ULONG Index;
/* Check page map level */ /* Check page map level */
@@ -263,25 +426,29 @@ BlpSelfMapPml(IN PXTBL_PAGE_MAPPING PageMap,
PmlIndex = (SelfMapAddress >> MM_PDI_SHIFT) & 0x1FF; PmlIndex = (SelfMapAddress >> MM_PDI_SHIFT) & 0x1FF;
/* Get Page Directory */ /* Get Page Directory */
Pml = (PHARDWARE_PTE)(((PHARDWARE_PTE)PageMap->PtePointer)[SelfMapAddress >> MM_PPI_SHIFT].PageFrameNumber * EFI_PAGE_SIZE); Pml = (PHARDWARE_MODERN_PTE)(((PHARDWARE_MODERN_PTE)PageMap->PtePointer)[SelfMapAddress >> MM_PPI_SHIFT].PageFrameNumber * EFI_PAGE_SIZE);
/* Add self-mapping for PML3 (PAE enabled) */ /* Add self-mapping for PML3 (PAE enabled) */
for(Index = 0; Index < 4; Index++) for(Index = 0; Index < 4; Index++)
{ {
Pml[PmlIndex + Index].PageFrameNumber = ((PHARDWARE_PTE)PageMap->PtePointer)[Index].PageFrameNumber; RtlZeroMemory(&Pml[PmlIndex + Index], sizeof(HARDWARE_MODERN_PTE));
Pml[PmlIndex + Index].PageFrameNumber = ((PHARDWARE_MODERN_PTE)PageMap->PtePointer)[Index].PageFrameNumber;
Pml[PmlIndex + Index].Valid = 1; Pml[PmlIndex + Index].Valid = 1;
Pml[PmlIndex + Index].Writable = 1; Pml[PmlIndex + Index].Writable = 1;
} }
} }
else else
{ {
LegacyPml = (PHARDWARE_LEGACY_PTE)PageMap->PtePointer;
/* Calculate PML index based on provided self map address */ /* Calculate PML index based on provided self map address */
PmlIndex = (SelfMapAddress >> MM_PDI_LEGACY_SHIFT); PmlIndex = (SelfMapAddress >> MM_PDI_LEGACY_SHIFT);
/* Add self-mapping for PML2 (PAE disabled) */ /* Add self-mapping for PML2 (PAE disabled) */
((PHARDWARE_LEGACY_PTE)PageMap->PtePointer)[PmlIndex].PageFrameNumber = (UINT_PTR)PageMap->PtePointer / EFI_PAGE_SIZE; RtlZeroMemory(&LegacyPml[PmlIndex], sizeof(HARDWARE_LEGACY_PTE));
((PHARDWARE_LEGACY_PTE)PageMap->PtePointer)[PmlIndex].Valid = 1; LegacyPml[PmlIndex].PageFrameNumber = (UINT_PTR)PageMap->PtePointer / EFI_PAGE_SIZE;
((PHARDWARE_LEGACY_PTE)PageMap->PtePointer)[PmlIndex].Writable = 1; LegacyPml[PmlIndex].Valid = 1;
LegacyPml[PmlIndex].Writable = 1;
} }
/* Return success */ /* Return success */

87
xtldr/bootutil.c Normal file
View File

@@ -0,0 +1,87 @@
/**
* PROJECT: ExectOS
* COPYRIGHT: See COPYING.md in the top level directory
* FILE: xtldr/bootutil.c
* DESCRIPTION: Helper functions used by the boot protocol during system startup
* DEVELOPERS: Aiken Harris <harraiken91@gmail.com>
*/
#include <xtldr.h>
/**
* Checks if a specific option exists in the list of provided boot parameters.
*
* @param Parameters
* A pointer to the wide-character string containing the boot parameters, separated by spaces.
*
* @param Needle
* A pointer to the wide-character string representing the kernel option to find.
*
* @return This routine returns TRUE if the option is found, otherwise FALSE.
*
* @since XT 1.0
*/
XTCDECL
BOOLEAN
BlGetBooleanParameter(IN CONST PWCHAR Parameters,
IN CONST PWCHAR Needle)
{
PWCHAR CurrentPosition, TokenEnd, TokenStart;
SIZE_T NeedleLength, TokenLength;
/* Validate input data and ensure the option is not an empty string */
if(Parameters == NULL || Needle == NULL || *Needle == L'\0')
{
/* One of the parameters was invalid */
return FALSE;
}
CurrentPosition = Parameters;
NeedleLength = RtlWideStringLength(Needle, 0);
/* Iterate through the entire parameters string */
while(*CurrentPosition != L'\0')
{
/* Skip any leading whitespace to find the start of the token */
while(*CurrentPosition == L' ')
{
CurrentPosition++;
}
/* Check if end of the string has been reached */
if(*CurrentPosition == L'\0')
{
/* End of string reached, no more tokens */
break;
}
/* Identify the boundaries of the current token */
TokenStart = CurrentPosition;
TokenEnd = TokenStart;
while(*TokenEnd != L'\0' && *TokenEnd != L' ')
{
TokenEnd++;
}
/* Calculate the length of the token found */
TokenLength = TokenEnd - TokenStart;
/* Compare the token length */
if(TokenLength == NeedleLength)
{
/* Length matches, compare the strings */
if(RtlCompareWideStringInsensitive(TokenStart, Needle, NeedleLength) == 0)
{
/* A match was found */
return TRUE;
}
}
/* Move the position past the current token to continue the search */
CurrentPosition = TokenEnd;
}
/* No match was found */
return FALSE;
}

View File

@@ -4,11 +4,84 @@
* FILE: xtldr/config.c * FILE: xtldr/config.c
* DESCRIPTION: XT Boot Loader Configuration * DESCRIPTION: XT Boot Loader Configuration
* DEVELOPERS: Rafal Kupiec <belliash@codingworkshop.eu.org> * DEVELOPERS: Rafal Kupiec <belliash@codingworkshop.eu.org>
* Aiken Harris <harraiken91@gmail.com>
*/ */
#include <xtldr.h> #include <xtldr.h>
/**
* @brief Retrieves the value of a specific OS boot option from a list.
*
* @param Options
* A pointer to the head of a list of XTBL_CONFIG_ENTRY structures.
*
* @param OptionName
* A pointer to wide string that contains the name of the boot option to retrieve.
*
* @param OptionValue
* A pointer to a variable that receives a pointer to the retrieved boot option's value.
*
* @return This routine returns a status code.
*
* @since XT 1.0
*/
XTCDECL
EFI_STATUS
BlGetBootOptionValue(IN PLIST_ENTRY Options,
IN CONST PWCHAR OptionName,
OUT PWCHAR *OptionValue)
{
PXTBL_CONFIG_ENTRY ConfigEntry;
PLIST_ENTRY ConfigList;
ULONG KeyLength, ValueLength;
EFI_STATUS Status;
/* Assume the option will not be found */
*OptionValue = NULL;
/* Get the length of the option name we are looking for */
KeyLength = RtlWideStringLength(OptionName, 0);
/* Start iterating from the first entry in the options list */
ConfigList = Options->Flink;
while(ConfigList != Options)
{
/* Get the container record for the current config entry */
ConfigEntry = CONTAIN_RECORD(ConfigList, XTBL_CONFIG_ENTRY, Flink);
/* Compare the current entry's name with the requested option name */
if(RtlCompareWideStringInsensitive(ConfigEntry->Name, OptionName, KeyLength) == 0)
{
/* Found the option, now prepare to copy its value */
ValueLength = RtlWideStringLength(ConfigEntry->Value, 0);
/* Allocate memory for the output value string */
Status = BlAllocateMemoryPool((ValueLength + 1) * sizeof(WCHAR), (PVOID *)OptionValue);
if(Status != STATUS_EFI_SUCCESS)
{
/* Memory allocation failure, print debug message and return status code */
BlDebugPrint(L"ERROR: Memory allocation failure (Status Code: 0x%zX)\n", Status);
*OptionValue = NULL;
return Status;
}
/* Copy the value and NULL-terminate the new string */
RtlCopyMemory(*OptionValue, ConfigEntry->Value, ValueLength * sizeof(WCHAR));
(*OptionValue)[ValueLength] = L'\0';
/* Successfully retrieved the option value, return success */
return STATUS_EFI_SUCCESS;
}
/* Move to the next entry in the list */
ConfigList = ConfigList->Flink;
}
/* Option not found */
return STATUS_EFI_NOT_FOUND;
}
/** /**
* Returns a boolean value of the specified configuration key. * Returns a boolean value of the specified configuration key.
* *
@@ -26,7 +99,7 @@ BlGetConfigBooleanValue(IN CONST PWCHAR ConfigName)
PWCHAR Value; PWCHAR Value;
/* Get config value */ /* Get config value */
Value = BlGetConfigValue(ConfigName); BlGetConfigValue(ConfigName, &Value);
/* Check if option is enabled */ /* Check if option is enabled */
if(RtlCompareWideStringInsensitive(Value, L"ENABLED", 0) == 0 || if(RtlCompareWideStringInsensitive(Value, L"ENABLED", 0) == 0 ||
@@ -53,8 +126,9 @@ BlGetConfigBooleanValue(IN CONST PWCHAR ConfigName)
* @since XT 1.0 * @since XT 1.0
*/ */
XTCDECL XTCDECL
PWCHAR EFI_STATUS
BlGetConfigValue(IN CONST PWCHAR ConfigName) BlGetConfigValue(IN CONST PWCHAR ConfigName,
OUT PWCHAR *ConfigValue)
{ {
PXTBL_CONFIG_ENTRY ConfigEntry; PXTBL_CONFIG_ENTRY ConfigEntry;
PLIST_ENTRY ConfigListEntry; PLIST_ENTRY ConfigListEntry;
@@ -62,6 +136,9 @@ BlGetConfigValue(IN CONST PWCHAR ConfigName)
EFI_STATUS Status; EFI_STATUS Status;
PWCHAR Value; PWCHAR Value;
/* Assume the option will not be found */
*ConfigValue = NULL;
/* Get config entry name length */ /* Get config entry name length */
KeyLength = RtlWideStringLength(ConfigName, 0); KeyLength = RtlWideStringLength(ConfigName, 0);
@@ -84,13 +161,14 @@ BlGetConfigValue(IN CONST PWCHAR ConfigName)
{ {
/* Memory allocation failure, return NULL */ /* Memory allocation failure, return NULL */
BlDebugPrint(L"ERROR: Memory allocation failure (Status Code: 0x%zX)\n", Status); BlDebugPrint(L"ERROR: Memory allocation failure (Status Code: 0x%zX)\n", Status);
return NULL; return Status;
} }
/* Copy value and return it */ /* Copy value and return it */
RtlCopyMemory(Value, ConfigEntry->Value, ValueLength * sizeof(WCHAR)); RtlCopyMemory(Value, ConfigEntry->Value, ValueLength * sizeof(WCHAR));
Value[ValueLength] = L'\0'; Value[ValueLength] = L'\0';
return Value; *ConfigValue = Value;
return STATUS_EFI_SUCCESS;
} }
/* Move to the next config entry */ /* Move to the next config entry */
@@ -98,7 +176,157 @@ BlGetConfigValue(IN CONST PWCHAR ConfigName)
} }
/* Config entry not found, return NULL */ /* Config entry not found, return NULL */
return NULL; return STATUS_EFI_NOT_FOUND;
}
/**
* Retrieves the list of user-editable boot options.
*
* @param OptionsArray
* A pointer to a variable that will receive the pointer to the array of editable option names.
*
* @param OptionsCount
* A pointer to a variable that will be updated with the number of elements in the OptionsArray.
*
* @return This routine does not return any value.
*
* @since XT 1.0
*/
XTCDECL
VOID
BlGetEditableOptions(OUT CONST PWCHAR **OptionsArray,
OUT PULONG OptionsCount)
{
ULONG Count = 0;
/* Return a pointer to the global array of editable options */
*OptionsArray = BlpEditableConfigOptions;
/* Calculate the number of elements in the array */
while(BlpEditableConfigOptions[Count])
{
Count++;
}
/* Return the number of elements */
*OptionsCount = Count;
}
/**
* Sets the value of a specific OS boot option in a list, or adds it if it doesn't exist.
*
* @param Options
* A pointer to the head of a list of XTBL_CONFIG_ENTRY structures.
*
* @param OptionName
* A pointer to a wide string that contains the name of the boot option to set.
*
* @param OptionValue
* A pointer to a wide string that contains the new value for the boot option.
*
* @return This routine returns a status code.
*
* @since XT 1.0
*/
XTCDECL
EFI_STATUS
BlSetBootOptionValue(IN PLIST_ENTRY Options,
IN CONST PWCHAR OptionName,
IN CONST PWCHAR OptionValue)
{
PXTBL_CONFIG_ENTRY ConfigEntry;
PLIST_ENTRY ConfigList;
ULONG Length;
EFI_STATUS Status;
/* Get the length of the option name we are looking for */
Length = RtlWideStringLength(OptionName, 0);
/* Start iterating from the first entry in the options list */
ConfigList = Options->Flink;
while(ConfigList != Options)
{
/* Get the container record for the current config entry */
ConfigEntry = CONTAIN_RECORD(ConfigList, XTBL_CONFIG_ENTRY, Flink);
/* Compare the current entry's name with the requested option name */
if(RtlCompareWideStringInsensitive(ConfigEntry->Name, OptionName, Length) == 0)
{
/* Found the option, get its length */
Length = RtlWideStringLength(OptionValue, 0);
/* Reallocate memory for the new value */
Status = BlFreeMemoryPool(ConfigEntry->Value);
if(Status != STATUS_EFI_SUCCESS)
{
/* Failed to free memory, return status code */
return Status;
}
/* Allocate new memory for the updated value */
Status = BlAllocateMemoryPool((Length + 1) * sizeof(WCHAR), (PVOID *)&ConfigEntry->Value);
if(Status != STATUS_EFI_SUCCESS)
{
/* Memory allocation failure, print debug message and return status code */
BlDebugPrint(L"ERROR: Memory allocation failure (Status Code: 0x%zX)\\n", Status);
return Status;
}
/* Copy the value and NULL-terminate the new string */
RtlCopyMemory(ConfigEntry->Value, OptionValue, Length * sizeof(WCHAR));
ConfigEntry->Value[Length] = L'\0';
return STATUS_EFI_SUCCESS;
}
/* Move to the next entry in the list */
ConfigList = ConfigList->Flink;
}
/* Option not found, allocate memory for the new one */
Status = BlAllocateMemoryPool(sizeof(XTBL_CONFIG_ENTRY), (PVOID *)&ConfigEntry);
if(Status != STATUS_EFI_SUCCESS)
{
/* Memory allocation failure, print debug message and return status code */
BlDebugPrint(L"ERROR: Memory allocation failure (Status Code: 0x%zX)\\n", Status);
return Status;
}
/* Allocate memory for the option name */
Length = RtlWideStringLength(OptionName, 0);
Status = BlAllocateMemoryPool((Length + 1) * sizeof(WCHAR), (PVOID *)&ConfigEntry->Name);
if(Status != STATUS_EFI_SUCCESS)
{
/* Memory allocation failure, print debug message and return status code */
BlDebugPrint(L"ERROR: Memory allocation failure (Status Code: 0x%zX)\\n", Status);
BlFreeMemoryPool(ConfigEntry);
return Status;
}
/* Copy the option name and NULL-terminate the new string */
RtlCopyMemory(ConfigEntry->Name, OptionName, Length * sizeof(WCHAR));
ConfigEntry->Name[Length] = L'\0';
/* Allocate memory for the option value */
Length = RtlWideStringLength(OptionValue, 0);
Status = BlAllocateMemoryPool((Length + 1) * sizeof(WCHAR), (PVOID *)&ConfigEntry->Value);
if(Status != STATUS_EFI_SUCCESS)
{
/* Memory allocation failure, print debug message and return status code */
BlDebugPrint(L"ERROR: Memory allocation failure (Status Code: 0x%zX)\\n", Status);
BlFreeMemoryPool(ConfigEntry->Name);
BlFreeMemoryPool(ConfigEntry);
return Status;
}
/* Copy the value and NULL-terminate the new string */
RtlCopyMemory(ConfigEntry->Value, OptionValue, Length * sizeof(WCHAR));
ConfigEntry->Value[Length] = L'\0';
/* Insert the new config entry at the end of the options list */
RtlInsertTailList(Options, &ConfigEntry->Flink);
/* Return success */
return STATUS_EFI_SUCCESS;
} }
/** /**
@@ -110,7 +338,7 @@ BlGetConfigValue(IN CONST PWCHAR ConfigName)
* @param ConfigValue * @param ConfigValue
* Specifies the new configuration value. * Specifies the new configuration value.
* *
* @return This routine returns status code. * @return This routine returns a status code.
* *
* @since XT 1.0 * @since XT 1.0
*/ */
@@ -174,7 +402,7 @@ BlSetConfigValue(IN CONST PWCHAR ConfigName,
/** /**
* Loads and parses XTLDR configuration file. * Loads and parses XTLDR configuration file.
* *
* @return This routine returns status code. * @return This routine returns a status code.
* *
* @since XT 1.0 * @since XT 1.0
*/ */
@@ -453,7 +681,7 @@ BlpParseConfigFile(IN CONST PCHAR RawConfig,
/* Initialize new section and convert its name to wide string */ /* Initialize new section and convert its name to wide string */
RtlInitializeListHead(&Section->Options); RtlInitializeListHead(&Section->Options);
RtlStringToWideString(Section->SectionName, &SectionName, SectionLength); RtlStringToWideString(Section->SectionName, (PCSTR*)&SectionName, SectionLength);
/* Ensure string is NULL-terminated and add new section to the configuration list */ /* Ensure string is NULL-terminated and add new section to the configuration list */
Section->SectionName[SectionLength] = L'\0'; Section->SectionName[SectionLength] = L'\0';
@@ -542,8 +770,8 @@ BlpParseConfigFile(IN CONST PCHAR RawConfig,
} }
/* Convert key and value to wide strings */ /* Convert key and value to wide strings */
RtlStringToWideString(Option->Name, &Key, RtlStringLength(Key, 0) + 1); RtlStringToWideString(Option->Name, (PCSTR*)&Key, RtlStringLength(Key, 0) + 1);
RtlStringToWideString(Option->Value, &Value, RtlStringLength(Value, 0) + 1); RtlStringToWideString(Option->Value, (PCSTR*)&Value, RtlStringLength(Value, 0) + 1);
/* Ensure strings are NULL-terminated and add new option to the list */ /* Ensure strings are NULL-terminated and add new option to the list */
Option->Name[KeyLength] = L'\0'; Option->Name[KeyLength] = L'\0';
@@ -568,7 +796,7 @@ BlpParseConfigFile(IN CONST PCHAR RawConfig,
* @param ConfigData * @param ConfigData
* Provides a buffer to store the data read from the configuration file. * Provides a buffer to store the data read from the configuration file.
* *
* @return This routine returns status code. * @return This routine returns a status code.
* *
* @since XT 1.0 * @since XT 1.0
*/ */
@@ -629,6 +857,7 @@ VOID
BlpUpdateConfiguration(IN PLIST_ENTRY NewConfig) BlpUpdateConfiguration(IN PLIST_ENTRY NewConfig)
{ {
PXTBL_CONFIG_ENTRY ConfigEntry; PXTBL_CONFIG_ENTRY ConfigEntry;
PWCHAR ConfigValue;
PLIST_ENTRY ConfigListEntry, NextListEntry; PLIST_ENTRY ConfigListEntry, NextListEntry;
/* Iterate through new config entries */ /* Iterate through new config entries */
@@ -642,7 +871,8 @@ BlpUpdateConfiguration(IN PLIST_ENTRY NewConfig)
NextListEntry = ConfigListEntry->Flink; NextListEntry = ConfigListEntry->Flink;
/* Make sure config entry does not exist yet */ /* Make sure config entry does not exist yet */
if(BlGetConfigValue(ConfigEntry->Name) == NULL) BlGetConfigValue(ConfigEntry->Name, &ConfigValue);
if(ConfigValue == NULL)
{ {
/* Remove new config entry from input list and put it into global config list */ /* Remove new config entry from input list and put it into global config list */
RtlRemoveEntryList(&ConfigEntry->Flink); RtlRemoveEntryList(&ConfigEntry->Flink);

View File

@@ -95,7 +95,7 @@ BlEnableConsoleCursor()
*/ */
XTCDECL XTCDECL
VOID VOID
BlConsolePrint(IN PUSHORT Format, BlConsolePrint(IN PCWSTR Format,
IN ...) IN ...)
{ {
RTL_PRINT_CONTEXT ConsolePrintContext, SerialPrintContext; RTL_PRINT_CONTEXT ConsolePrintContext, SerialPrintContext;
@@ -138,9 +138,9 @@ BlConsolePrint(IN PUSHORT Format,
*/ */
XTCDECL XTCDECL
VOID VOID
BlConsoleWrite(IN PUSHORT String) BlConsoleWrite(IN PCWSTR String)
{ {
EfiSystemTable->ConOut->OutputString(EfiSystemTable->ConOut, String); EfiSystemTable->ConOut->OutputString(EfiSystemTable->ConOut, (PWSTR)String);
} }
/** /**
@@ -292,9 +292,9 @@ BlSetCursorPosition(IN ULONGLONG PosX,
*/ */
XTCDECL XTCDECL
XTSTATUS XTSTATUS
BlpConsolePutChar(IN USHORT Character) BlpConsolePutChar(IN WCHAR Character)
{ {
USHORT Buffer[2]; WCHAR Buffer[2];
/* Check if character is a newline ('\n') */ /* Check if character is a newline ('\n') */
if(Character == L'\n') if(Character == L'\n')

View File

@@ -24,7 +24,7 @@
*/ */
XTCDECL XTCDECL
VOID VOID
BlDebugPrint(IN PUSHORT Format, BlDebugPrint(IN PCWSTR Format,
IN ...) IN ...)
{ {
RTL_PRINT_CONTEXT ConsolePrintContext, SerialPrintContext; RTL_PRINT_CONTEXT ConsolePrintContext, SerialPrintContext;
@@ -71,17 +71,14 @@ BlDebugPrint(IN PUSHORT Format,
*/ */
XTCDECL XTCDECL
XTSTATUS XTSTATUS
BlpDebugPutChar(IN USHORT Character) BlpDebugPutChar(IN WCHAR Character)
{ {
USHORT Buffer[2]; WCHAR Buffer[2];
/* Write character to the serial console */ /* Write character to the serial console */
Buffer[0] = Character; Buffer[0] = Character;
Buffer[1] = 0; Buffer[1] = 0;
HlComPortPutByte(&BlpStatus.SerialPort, Buffer[0]); return HlComPortPutByte(&BlpStatus.SerialPort, Buffer[0]);
/* Return success */
return STATUS_EFI_SUCCESS;
} }
/** /**
@@ -105,7 +102,7 @@ BlpInitializeDebugConsole()
BaudRate = 0; BaudRate = 0;
/* Get debug configuration */ /* Get debug configuration */
DebugConfiguration = BlGetConfigValue(L"DEBUG"); BlGetConfigValue(L"DEBUG", &DebugConfiguration);
/* Make sure any debug options are provided and debug console is not initialized yet */ /* Make sure any debug options are provided and debug console is not initialized yet */
if(DebugConfiguration && BlpStatus.DebugPort == 0) if(DebugConfiguration && BlpStatus.DebugPort == 0)

View File

@@ -21,6 +21,13 @@ LIST_ENTRY BlpConfig;
/* XT Boot Loader loaded configuration */ /* XT Boot Loader loaded configuration */
LIST_ENTRY BlpConfigSections; LIST_ENTRY BlpConfigSections;
/* List of user-editable boot options */
PWCHAR BlpEditableConfigOptions[] = {
L"BootModules", L"SystemType", L"SystemPath",
L"KernelFile", L"InitrdFile", L"HalFile",
L"Parameters", NULL
};
/* XT Boot Loader protocol */ /* XT Boot Loader protocol */
XTBL_LOADER_PROTOCOL BlpLdrProtocol; XTBL_LOADER_PROTOCOL BlpLdrProtocol;
@@ -41,3 +48,4 @@ EFI_HANDLE EfiImageHandle;
/* EFI System Table */ /* EFI System Table */
PEFI_SYSTEM_TABLE EfiSystemTable; PEFI_SYSTEM_TABLE EfiSystemTable;

View File

@@ -24,6 +24,9 @@ EXTERN LIST_ENTRY BlpConfig;
/* XT Boot Loader loaded configuration */ /* XT Boot Loader loaded configuration */
EXTERN LIST_ENTRY BlpConfigSections; EXTERN LIST_ENTRY BlpConfigSections;
/* List of user-editable boot options */
EXTERN PWCHAR BlpEditableConfigOptions[];
/* XT Boot Loader protocol */ /* XT Boot Loader protocol */
EXTERN XTBL_LOADER_PROTOCOL BlpLdrProtocol; EXTERN XTBL_LOADER_PROTOCOL BlpLdrProtocol;

View File

@@ -18,7 +18,8 @@
/* XTLDR routines forward references */ /* XTLDR routines forward references */
XTCDECL XTCDECL
EFI_STATUS EFI_STATUS
BlAllocateMemoryPages(IN ULONGLONG Pages, BlAllocateMemoryPages(IN EFI_ALLOCATE_TYPE AllocationType,
IN ULONGLONG NumberOfPages,
OUT PEFI_PHYSICAL_ADDRESS Memory); OUT PEFI_PHYSICAL_ADDRESS Memory);
XTCDECL XTCDECL
@@ -50,16 +51,16 @@ BlCloseVolume(IN PEFI_HANDLE VolumeHandle);
XTCDECL XTCDECL
VOID VOID
BlConsolePrint(IN PUSHORT Format, BlConsolePrint(IN PCWSTR Format,
IN ...); IN ...);
XTCDECL XTCDECL
VOID VOID
BlConsoleWrite(IN PUSHORT String); BlConsoleWrite(IN PCWSTR String);
XTCDECL XTCDECL
VOID VOID
BlDebugPrint(IN PUSHORT Format, BlDebugPrint(IN PCWSTR Format,
IN ...); IN ...);
XTCDECL XTCDECL
@@ -70,6 +71,10 @@ XTCDECL
VOID VOID
BlDisplayBootMenu(); BlDisplayBootMenu();
XTCDECL
VOID
BlDisplayEditMenu(IN PXTBL_BOOTMENU_ITEM MenuEntry);
XTCDECL XTCDECL
VOID VOID
BlDisplayErrorDialog(IN PWCHAR Caption, BlDisplayErrorDialog(IN PWCHAR Caption,
@@ -121,26 +126,43 @@ BlFindVolumeDevicePath(IN PEFI_DEVICE_PATH_PROTOCOL FsHandle,
XTCDECL XTCDECL
EFI_STATUS EFI_STATUS
BlFreeMemoryPages(IN ULONGLONG Pages, BlFreeMemoryPages(IN ULONGLONG NumberOfPages,
IN EFI_PHYSICAL_ADDRESS Memory); IN EFI_PHYSICAL_ADDRESS Memory);
XTCDECL XTCDECL
EFI_STATUS EFI_STATUS
BlFreeMemoryPool(IN PVOID Memory); BlFreeMemoryPool(IN PVOID Memory);
XTCDECL
BOOLEAN
BlGetBooleanParameter(IN CONST PWCHAR Parameters,
IN CONST PWCHAR Needle);
XTCDECL
EFI_STATUS
BlGetBootOptionValue(IN PLIST_ENTRY Options,
IN CONST PWCHAR OptionName,
OUT PWCHAR *OptionValue);
XTCDECL XTCDECL
BOOLEAN BOOLEAN
BlGetConfigBooleanValue(IN CONST PWCHAR ConfigName); BlGetConfigBooleanValue(IN CONST PWCHAR ConfigName);
XTCDECL XTCDECL
PWCHAR EFI_STATUS
BlGetConfigValue(IN CONST PWCHAR ConfigName); BlGetConfigValue(IN CONST PWCHAR ConfigName,
OUT PWCHAR *ConfigValue);
XTCDECL XTCDECL
EFI_STATUS EFI_STATUS
BlGetConfigurationTable(IN PEFI_GUID TableGuid, BlGetConfigurationTable(IN PEFI_GUID TableGuid,
OUT PVOID *Table); OUT PVOID *Table);
XTCDECL
VOID
BlGetEditableOptions(OUT CONST PWCHAR **OptionsArray,
OUT PULONG OptionsCount);
XTCDECL XTCDECL
EFI_STATUS EFI_STATUS
BlGetEfiPath(IN PWCHAR SystemPath, BlGetEfiPath(IN PWCHAR SystemPath,
@@ -191,7 +213,8 @@ BlInitializeBootLoader();
XTCDECL XTCDECL
EFI_STATUS EFI_STATUS
BlInitializeBootMenuList(OUT PXTBL_BOOTMENU_ITEM *MenuEntries, BlInitializeBootMenuList(IN ULONG MaxNameLength,
OUT PXTBL_BOOTMENU_ITEM *MenuEntries,
OUT PULONG EntriesCount, OUT PULONG EntriesCount,
OUT PULONG DefaultId); OUT PULONG DefaultId);
@@ -249,9 +272,9 @@ BlMapEfiMemory(IN OUT PXTBL_PAGE_MAPPING PageMap,
XTCDECL XTCDECL
EFI_STATUS EFI_STATUS
BlMapPage(IN PXTBL_PAGE_MAPPING PageMap, BlMapPage(IN PXTBL_PAGE_MAPPING PageMap,
IN UINT_PTR VirtualAddress, IN ULONG_PTR VirtualAddress,
IN UINT_PTR PhysicalAddress, IN ULONG_PTR PhysicalAddress,
IN UINT NumberOfPages); IN ULONG NumberOfPages);
XTCDECL XTCDECL
EFI_STATUS EFI_STATUS
@@ -325,6 +348,12 @@ XTCDECL
VOID VOID
BlResetConsoleInputBuffer(); BlResetConsoleInputBuffer();
XTCDECL
EFI_STATUS
BlSetBootOptionValue(IN PLIST_ENTRY Options,
IN CONST PWCHAR OptionName,
IN CONST PWCHAR OptionValue);
XTCDECL XTCDECL
EFI_STATUS EFI_STATUS
BlSetConfigValue(IN CONST PWCHAR ConfigName, BlSetConfigValue(IN CONST PWCHAR ConfigName,
@@ -389,11 +418,11 @@ BlpActivateSerialIOController();
XTCDECL XTCDECL
XTSTATUS XTSTATUS
BlpConsolePutChar(IN USHORT Character); BlpConsolePutChar(IN WCHAR Character);
XTCDECL XTCDECL
XTSTATUS XTSTATUS
BlpDebugPutChar(IN USHORT Character); BlpDebugPutChar(IN WCHAR Character);
XTCDECL XTCDECL
VOID VOID
@@ -449,6 +478,18 @@ VOID
BlpDrawDialogProgressBar(IN PXTBL_DIALOG_HANDLE Handle, BlpDrawDialogProgressBar(IN PXTBL_DIALOG_HANDLE Handle,
IN UCHAR Percentage); IN UCHAR Percentage);
XTCDECL
VOID
BlpDrawEditMenu(OUT PXTBL_DIALOG_HANDLE Handle);
XTCDECL
EFI_STATUS
BlpDrawEditMenuEntry(IN PXTBL_DIALOG_HANDLE Handle,
IN PWCHAR OptionName,
IN PWCHAR OptionValue,
IN UINT Position,
IN BOOLEAN Highlighted);
XTCDECL XTCDECL
PEFI_DEVICE_PATH_PROTOCOL PEFI_DEVICE_PATH_PROTOCOL
BlpDuplicateDevicePath(IN PEFI_DEVICE_PATH_PROTOCOL DevicePath); BlpDuplicateDevicePath(IN PEFI_DEVICE_PATH_PROTOCOL DevicePath);
@@ -462,7 +503,7 @@ XTCDECL
BOOLEAN BOOLEAN
BlpFindParentBlockDevice(IN PLIST_ENTRY BlockDevices, BlpFindParentBlockDevice(IN PLIST_ENTRY BlockDevices,
IN PEFI_BLOCK_DEVICE_DATA ChildNode, IN PEFI_BLOCK_DEVICE_DATA ChildNode,
OUT PEFI_BLOCK_DEVICE_DATA ParentNode); OUT PEFI_BLOCK_DEVICE_DATA *ParentNode);
XTCDECL XTCDECL
LONG LONG
@@ -484,9 +525,9 @@ BlpGetModuleInfoStrings(IN PWCHAR SectionData,
XTCDECL XTCDECL
EFI_STATUS EFI_STATUS
BlpGetNextPageTable(IN PXTBL_PAGE_MAPPING PageMap, BlpGetNextPageTable(IN PXTBL_PAGE_MAPPING PageMap,
IN PHARDWARE_PTE PageTable, IN PVOID PageTable,
IN SIZE_T Entry, IN SIZE_T Entry,
OUT PHARDWARE_PTE *NextPageTable); OUT PVOID *NextPageTable);
XTCDECL XTCDECL
EFI_STATUS EFI_STATUS

View File

@@ -12,7 +12,7 @@
/** /**
* This routine allocates one or more 4KB pages. * This routine allocates one or more 4KB pages.
* *
* @param Pages * @param NumberOfPages
* The number of contiguous 4KB pages to allocate. * The number of contiguous 4KB pages to allocate.
* *
* @param Memory * @param Memory
@@ -24,10 +24,11 @@
*/ */
XTCDECL XTCDECL
EFI_STATUS EFI_STATUS
BlAllocateMemoryPages(IN ULONGLONG Pages, BlAllocateMemoryPages(IN EFI_ALLOCATE_TYPE AllocationType,
IN ULONGLONG NumberOfPages,
OUT PEFI_PHYSICAL_ADDRESS Memory) OUT PEFI_PHYSICAL_ADDRESS Memory)
{ {
return EfiSystemTable->BootServices->AllocatePages(AllocateAnyPages, EfiLoaderData, Pages, Memory); return EfiSystemTable->BootServices->AllocatePages(AllocationType, EfiLoaderData, NumberOfPages, Memory);
} }
/** /**
@@ -55,7 +56,7 @@ BlAllocateMemoryPool(IN UINT_PTR Size,
/** /**
* This routine frees memory pages. * This routine frees memory pages.
* *
* @param Pages * @param NumberOfPages
* The number of contiguous 4 KB pages to free. * The number of contiguous 4 KB pages to free.
* *
* @param Memory * @param Memory
@@ -67,10 +68,10 @@ BlAllocateMemoryPool(IN UINT_PTR Size,
*/ */
XTCDECL XTCDECL
EFI_STATUS EFI_STATUS
BlFreeMemoryPages(IN ULONGLONG Pages, BlFreeMemoryPages(IN ULONGLONG NumberOfPages,
IN EFI_PHYSICAL_ADDRESS Memory) IN EFI_PHYSICAL_ADDRESS Memory)
{ {
return EfiSystemTable->BootServices->FreePages(Memory, Pages); return EfiSystemTable->BootServices->FreePages(Memory, NumberOfPages);
} }
/** /**
@@ -739,75 +740,3 @@ BlpGetLoaderMemoryType(IN EFI_MEMORY_TYPE EfiMemoryType)
/* Return XTLDR memory type */ /* Return XTLDR memory type */
return MemoryType; return MemoryType;
} }
/**
* Returns next level of the Page Table.
*
* @param PageMap
* Supplies a pointer to the page mapping structure.
*
* @param PageTable
* Supplies a pointer to the current Page Table.
*
* @param Entry
* Supplies an index of the current Page Table entry.
*
* @param NextPageTable
* Supplies a pointer to the memory area where the next Page Table level is returned.
*
* @return This routine returns a status code.
*
* @since XT 1.0
*/
XTCDECL
EFI_STATUS
BlpGetNextPageTable(IN PXTBL_PAGE_MAPPING PageMap,
IN PHARDWARE_PTE PageTable,
IN SIZE_T Entry,
OUT PHARDWARE_PTE *NextPageTable)
{
EFI_PHYSICAL_ADDRESS Address;
ULONGLONG PmlPointer;
EFI_STATUS Status;
/* Check if this is a valid table */
if(PageTable[Entry].Valid)
{
/* Get PML pointer */
PmlPointer = PageTable[Entry].PageFrameNumber;
PmlPointer <<= EFI_PAGE_SHIFT;
}
else
{
/* Allocate pages for new PML entry */
Status = BlAllocateMemoryPages(1, &Address);
if(Status != STATUS_EFI_SUCCESS)
{
/* Memory allocation failure */
return Status;
}
/* Add new memory mapping */
Status = BlMapVirtualMemory(PageMap, NULL, (PVOID)(UINT_PTR)Address, 1, LoaderMemoryData);
if(Status != STATUS_EFI_SUCCESS)
{
/* Memory mapping failure */
return Status;
}
/* Fill allocated memory with zeros */
RtlZeroMemory((PVOID)(ULONGLONG)Address, EFI_PAGE_SIZE);
/* Set paging entry settings */
PageTable[Entry].PageFrameNumber = Address / EFI_PAGE_SIZE;
PageTable[Entry].Valid = 1;
PageTable[Entry].Writable = 1;
PmlPointer = (ULONGLONG)Address;
}
/* Set next Page Map Level (PML) */
*NextPageTable = (PHARDWARE_PTE)(ULONGLONG)PmlPointer;
/* Return success */
return STATUS_EFI_SUCCESS;
}

View File

@@ -185,19 +185,17 @@ XTCDECL
EFI_STATUS EFI_STATUS
AcGetApicBase(OUT PVOID *ApicBase) AcGetApicBase(OUT PVOID *ApicBase)
{ {
PCPUID_REGISTERS CpuRegisters = NULL; CPUID_REGISTERS CpuRegisters;
/* Get CPU features list */ /* Prepare CPUID registers to query for APIC support */
CpuRegisters->Leaf = CPUID_GET_CPU_FEATURES; RtlZeroMemory(&CpuRegisters, sizeof(CPUID_REGISTERS));
CpuRegisters->SubLeaf = 0; CpuRegisters.Leaf = CPUID_GET_STANDARD1_FEATURES;
CpuRegisters->Eax = 0;
CpuRegisters->Ebx = 0; /* Query CPUID */
CpuRegisters->Ecx = 0; ArCpuId(&CpuRegisters);
CpuRegisters->Edx = 0;
ArCpuId(CpuRegisters);
/* Check if APIC present */ /* Check if APIC present */
if((CpuRegisters->Edx & CPUID_FEATURES_EDX_APIC) == 0) if((CpuRegisters.Edx & CPUID_FEATURES_EDX_APIC) == 0)
{ {
/* APIC is not supported by the CPU */ /* APIC is not supported by the CPU */
return STATUS_EFI_UNSUPPORTED; return STATUS_EFI_UNSUPPORTED;

View File

@@ -196,6 +196,7 @@ XtLdrModuleMain(IN EFI_HANDLE ImageHandle,
IN PEFI_SYSTEM_TABLE SystemTable) IN PEFI_SYSTEM_TABLE SystemTable)
{ {
EFI_STATUS Status; EFI_STATUS Status;
PWCHAR Tune;
/* Open the XTLDR protocol */ /* Open the XTLDR protocol */
Status = BlGetXtLdrProtocol(SystemTable, ImageHandle, &XtLdrProtocol); Status = BlGetXtLdrProtocol(SystemTable, ImageHandle, &XtLdrProtocol);
@@ -206,7 +207,8 @@ XtLdrModuleMain(IN EFI_HANDLE ImageHandle,
} }
/* Play the tune set in the configuration */ /* Play the tune set in the configuration */
BpPlayTune(XtLdrProtocol->Config.GetValue(L"TUNE")); XtLdrProtocol->Config.GetValue(L"TUNE", &Tune);
BpPlayTune(Tune);
/* Return success */ /* Return success */
return STATUS_EFI_SUCCESS; return STATUS_EFI_SUCCESS;

View File

@@ -47,7 +47,7 @@ ChBootSystem(IN PXTBL_BOOT_PARAMETERS Parameters)
} }
/* Open EFI volume */ /* Open EFI volume */
Status = XtLdrProtocol->Disk.OpenVolume(NULL, &DiskHandle, &FsHandle); Status = XtLdrProtocol->Disk.OpenVolume(Parameters->DevicePath, &DiskHandle, &FsHandle);
if(Status != STATUS_EFI_SUCCESS) if(Status != STATUS_EFI_SUCCESS)
{ {
/* Failed to open a volume, return error code */ /* Failed to open a volume, return error code */

View File

@@ -409,7 +409,7 @@ PeLoadImage(IN PEFI_FILE_HANDLE FileHandle,
Pages = EFI_SIZE_TO_PAGES(ImageData->FileSize); Pages = EFI_SIZE_TO_PAGES(ImageData->FileSize);
/* Allocate pages */ /* Allocate pages */
Status = XtLdrProtocol->Memory.AllocatePages(Pages, &Address); Status = XtLdrProtocol->Memory.AllocatePages(AllocateAnyPages, Pages, &Address);
if(Status != STATUS_EFI_SUCCESS) if(Status != STATUS_EFI_SUCCESS)
{ {
/* Pages allocation failure */ /* Pages allocation failure */
@@ -472,7 +472,7 @@ PeLoadImage(IN PEFI_FILE_HANDLE FileHandle,
ImageData->ImagePages = EFI_SIZE_TO_PAGES(ImageData->ImageSize); ImageData->ImagePages = EFI_SIZE_TO_PAGES(ImageData->ImageSize);
/* Allocate image pages */ /* Allocate image pages */
Status = XtLdrProtocol->Memory.AllocatePages(ImageData->ImagePages, &Address); Status = XtLdrProtocol->Memory.AllocatePages(AllocateAnyPages, ImageData->ImagePages, &Address);
if(Status != STATUS_EFI_SUCCESS) if(Status != STATUS_EFI_SUCCESS)
{ {
/* Pages reallocation failure */ /* Pages reallocation failure */

View File

@@ -4,11 +4,58 @@
* FILE: xtldr/amd64/memory.c * FILE: xtldr/amd64/memory.c
* DESCRIPTION: EFI memory management for AMD64 target * DESCRIPTION: EFI memory management for AMD64 target
* DEVELOPERS: Rafal Kupiec <belliash@codingworkshop.eu.org> * DEVELOPERS: Rafal Kupiec <belliash@codingworkshop.eu.org>
* Aiken Harris <harraiken91@gmail.com>
*/ */
#include <xtos.h> #include <xtos.h>
/**
* Determines the appropriate paging level (PML) for the AMD64 architecture.
*
* @param Parameters
* A pointer to the wide character string containing the kernel boot parameters.
*
* @return This routine returns the appropriate page map level (5 if LA57 is enabled, 4 otherwise).
*
* @since XT 1.0
*/
XTCDECL
ULONG
XtpDeterminePagingLevel(IN CONST PWCHAR Parameters)
{
CPUID_REGISTERS CpuRegisters;
/* Prepare CPUID registers to query for STD7 features */
RtlZeroMemory(&CpuRegisters, sizeof(CPUID_REGISTERS));
CpuRegisters.Leaf = CPUID_GET_VENDOR_STRING;
/* Query CPUID */
ArCpuId(&CpuRegisters);
/* Verify if the CPU supports the STD7 feature leaf (0x00000007) */
if(CpuRegisters.Eax >= CPUID_GET_STANDARD7_FEATURES)
{
/* Prepare CPUID registers to query for LA57 support */
RtlZeroMemory(&CpuRegisters, sizeof(CPUID_REGISTERS));
CpuRegisters.Leaf = CPUID_GET_STANDARD7_FEATURES;
/* Query CPUID */
ArCpuId(&CpuRegisters);
/* Check if eXtended Physical Addressing (XPA) is enabled and if LA57 is supported by the CPU */
if((CpuRegisters.Ecx & CPUID_FEATURES_ECX_LA57) &&
!(XtLdrProtocol->BootUtil.GetBooleanParameter(Parameters, L"NOXPA")))
{
/* Enable LA57 (PML5) */
return 5;
}
}
/* Disable LA57 and use PML4 by default */
return 4;
}
/** /**
* Maps the page table for hardware layer addess space. * Maps the page table for hardware layer addess space.
* *
@@ -23,25 +70,54 @@ XTCDECL
EFI_STATUS EFI_STATUS
XtpMapHardwareMemoryPool(IN PXTBL_PAGE_MAPPING PageMap) XtpMapHardwareMemoryPool(IN PXTBL_PAGE_MAPPING PageMap)
{ {
PHARDWARE_PTE PdeBase, PpeBase, PxeBase; PHARDWARE_PTE P5eBase, PdeBase, PpeBase, PxeBase;
EFI_PHYSICAL_ADDRESS Address; EFI_PHYSICAL_ADDRESS Address;
XTSTATUS Status; EFI_STATUS Status;
/* Check page map level */ if(PageMap->PageMapLevel == 5)
if(PageMap->PageMapLevel > 4)
{ {
/* PML5 (LA57) is not supported yet */ /* Get P5E (PML5) base address */
return STATUS_EFI_UNSUPPORTED; P5eBase = (PHARDWARE_PTE)PageMap->PtePointer;
}
/* Get PXE (PML4) base address */ /* Check if P5E entry already exists */
PxeBase = ((PHARDWARE_PTE)(PageMap->PtePointer)); if(!P5eBase[(MM_HARDWARE_VA_START >> MM_P5I_SHIFT) & 0x1FF].Valid)
{
/* No valid P5E, allocate memory */
Status = XtLdrProtocol->Memory.AllocatePages(AllocateAnyPages, 1, &Address);
if(Status != STATUS_EFI_SUCCESS)
{
/* Memory allocation failure, return error */
return Status;
}
/* Zero fill memory used by P5E */
RtlZeroMemory((PVOID)Address, EFI_PAGE_SIZE);
/* Make P5E valid */
P5eBase[(MM_HARDWARE_VA_START >> MM_P5I_SHIFT) & 0x1FF].Valid = 1;
P5eBase[(MM_HARDWARE_VA_START >> MM_P5I_SHIFT) & 0x1FF].PageFrameNumber = Address / EFI_PAGE_SIZE;
P5eBase[(MM_HARDWARE_VA_START >> MM_P5I_SHIFT) & 0x1FF].Writable = 1;
/* Set PXE base address */
PxeBase = (PHARDWARE_PTE)(UINT_PTR)Address;
}
else
{
/* Set PXE base address based on existing P5E */
PxeBase = (PHARDWARE_PTE)((P5eBase[(MM_HARDWARE_VA_START >> MM_P5I_SHIFT) & 0x1FF].PageFrameNumber) << EFI_PAGE_SHIFT);
}
}
else
{
/* Get PXE (PML4) base address */
PxeBase = (PHARDWARE_PTE)PageMap->PtePointer;
}
/* Check if PXE entry already exists */ /* Check if PXE entry already exists */
if(!PxeBase[(MM_HARDWARE_VA_START >> MM_PXI_SHIFT) & 0x1FF].Valid) if(!PxeBase[(MM_HARDWARE_VA_START >> MM_PXI_SHIFT) & 0x1FF].Valid)
{ {
/* No valid PXE, allocate memory */ /* No valid PXE, allocate memory */
Status = XtLdrProtocol->Memory.AllocatePages(1, &Address); Status = XtLdrProtocol->Memory.AllocatePages(AllocateAnyPages, 1, &Address);
if(Status != STATUS_EFI_SUCCESS) if(Status != STATUS_EFI_SUCCESS)
{ {
/* Memory allocation failure, return error */ /* Memory allocation failure, return error */
@@ -69,7 +145,7 @@ XtpMapHardwareMemoryPool(IN PXTBL_PAGE_MAPPING PageMap)
if(!PpeBase[(MM_HARDWARE_VA_START >> MM_PPI_SHIFT) & 0x1FF].Valid) if(!PpeBase[(MM_HARDWARE_VA_START >> MM_PPI_SHIFT) & 0x1FF].Valid)
{ {
/* No valid PPE, allocate memory */ /* No valid PPE, allocate memory */
Status = XtLdrProtocol->Memory.AllocatePages(1, &Address); Status = XtLdrProtocol->Memory.AllocatePages(AllocateAnyPages, 1, &Address);
if(Status != STATUS_EFI_SUCCESS) if(Status != STATUS_EFI_SUCCESS)
{ {
/* Memory allocation failure, return error */ /* Memory allocation failure, return error */
@@ -100,7 +176,7 @@ XtpMapHardwareMemoryPool(IN PXTBL_PAGE_MAPPING PageMap)
if(!PdeBase[((MM_HARDWARE_VA_START >> MM_PDI_SHIFT) & 0x1FF) + Index].Valid) if(!PdeBase[((MM_HARDWARE_VA_START >> MM_PDI_SHIFT) & 0x1FF) + Index].Valid)
{ {
/* No valid PDE, allocate memory */ /* No valid PDE, allocate memory */
Status = XtLdrProtocol->Memory.AllocatePages(1, &Address); Status = XtLdrProtocol->Memory.AllocatePages(AllocateAnyPages, 1, &Address);
if(Status != STATUS_EFI_SUCCESS) if(Status != STATUS_EFI_SUCCESS)
{ {
/* Memory allocation failure, return error */ /* Memory allocation failure, return error */
@@ -136,9 +212,12 @@ EFI_STATUS
XtEnablePaging(IN PXTBL_PAGE_MAPPING PageMap) XtEnablePaging(IN PXTBL_PAGE_MAPPING PageMap)
{ {
EFI_STATUS Status; EFI_STATUS Status;
EFI_PHYSICAL_ADDRESS TrampolineAddress;
PXT_TRAMPOLINE_ENTRY TrampolineEntry;
ULONG_PTR TrampolineSize;
/* Build page map */ /* Build page map */
Status = XtLdrProtocol->Memory.BuildPageMap(PageMap, 0xFFFFF6FB7DBED000); Status = XtLdrProtocol->Memory.BuildPageMap(PageMap, (PageMap->PageMapLevel > 4) ? MM_P5E_LA57_BASE : MM_PXE_BASE);
if(Status != STATUS_EFI_SUCCESS) if(Status != STATUS_EFI_SUCCESS)
{ {
/* Failed to build page map */ /* Failed to build page map */
@@ -155,6 +234,29 @@ XtEnablePaging(IN PXTBL_PAGE_MAPPING PageMap)
return Status; return Status;
} }
/* Check the configured page map level to set the LA57 state accordingly */
if(PageMap->PageMapLevel == 5)
{
/* Set the address of the trampoline code below 1MB */
TrampolineAddress = MM_TRAMPOLINE_ADDRESS;
/* Calculate the size of the trampoline code */
TrampolineSize = (ULONG_PTR)ArEnableExtendedPhysicalAddressingEnd - (ULONG_PTR)ArEnableExtendedPhysicalAddressing;
/* Allocate pages for the trampoline */
Status = XtLdrProtocol->Memory.AllocatePages(AllocateAddress, EFI_SIZE_TO_PAGES(TrampolineSize), &TrampolineAddress);
if(Status != STATUS_EFI_SUCCESS)
{
/* Failed to allocate memory for trampoline code */
XtLdrProtocol->Debug.Print(L"Failed to allocate memory for trampoline code (Status code: %zX)\n", Status);
return Status;
}
/* Set the trampoline entry point and copy its code into the allocated buffer */
TrampolineEntry = (PXT_TRAMPOLINE_ENTRY)(UINT_PTR)TrampolineAddress;
RtlCopyMemory(TrampolineEntry, ArEnableExtendedPhysicalAddressing, TrampolineSize);
}
/* Exit EFI Boot Services */ /* Exit EFI Boot Services */
XtLdrProtocol->Debug.Print(L"Exiting EFI boot services\n"); XtLdrProtocol->Debug.Print(L"Exiting EFI boot services\n");
Status = XtLdrProtocol->Util.ExitBootServices(); Status = XtLdrProtocol->Util.ExitBootServices();
@@ -165,8 +267,24 @@ XtEnablePaging(IN PXTBL_PAGE_MAPPING PageMap)
return STATUS_EFI_ABORTED; return STATUS_EFI_ABORTED;
} }
/* Write PML4 to CR3 */ /* Check the configured page map level to set the LA57 state accordingly */
ArWriteControlRegister(3, (UINT_PTR)PageMap->PtePointer); if(PageMap->PageMapLevel == 5)
{
/* Enable Linear Address 57-bit (LA57) extension */
XtLdrProtocol->Debug.Print(L"Enabling Linear Address 57-bit (LA57)\n");
/* Execute the trampoline to enable LA57 and write PML5 to CR3 */
TrampolineEntry((UINT64)PageMap->PtePointer);
}
else
{
/* Disable Linear Address 57-bit (LA57) extension */
XtLdrProtocol->Debug.Print(L"Disabling Linear Address 57-bit (LA57)\n");
/* Write PML4 to CR3 and enable paging */
ArWriteControlRegister(3, (UINT_PTR)PageMap->PtePointer);
ArWriteControlRegister(0, ArReadControlRegister(0) | CR0_PG);
}
/* Return success */ /* Return success */
return STATUS_EFI_SUCCESS; return STATUS_EFI_SUCCESS;

View File

@@ -9,6 +9,41 @@
#include <xtos.h> #include <xtos.h>
/**
* Determines the appropriate paging level (PML) for the i686 architecture.
*
* @param Parameters
* A pointer to the wide character string containing the kernel boot parameters.
*
* @return This routine returns the appropriate page map level (3 if PAE is enabled, 2 otherwise).
*
* @since XT 1.0
*/
XTCDECL
ULONG
XtpDeterminePagingLevel(IN CONST PWCHAR Parameters)
{
CPUID_REGISTERS CpuRegisters;
/* Prepare CPUID registers to query for PAE support */
RtlZeroMemory(&CpuRegisters, sizeof(CPUID_REGISTERS));
CpuRegisters.Leaf = CPUID_GET_STANDARD1_FEATURES;
/* Query CPUID */
ArCpuId(&CpuRegisters);
/* Check if eXtended Physical Addressing (XPA) is enabled and if PAE is supported by the CPU */
if((CpuRegisters.Edx & CPUID_FEATURES_EDX_PAE) &&
!(XtLdrProtocol->BootUtil.GetBooleanParameter(Parameters, L"NOXPA")))
{
/* Enable PAE (PML3) */
return 3;
}
/* Disable PAE and use PML2 by default */
return 2;
}
/** /**
* Maps the page table for hardware layer addess space. * Maps the page table for hardware layer addess space.
* *
@@ -24,11 +59,12 @@ EFI_STATUS
XtpMapHardwareMemoryPool(IN PXTBL_PAGE_MAPPING PageMap) XtpMapHardwareMemoryPool(IN PXTBL_PAGE_MAPPING PageMap)
{ {
EFI_PHYSICAL_ADDRESS Address; EFI_PHYSICAL_ADDRESS Address;
PHARDWARE_PTE PdeBase; PHARDWARE_LEGACY_PTE LegacyPdeBase;
XTSTATUS Status; PHARDWARE_MODERN_PTE PdeBase;
EFI_STATUS Status;
/* Allocate memory */ /* Allocate memory */
Status = XtLdrProtocol->Memory.AllocatePages(1, &Address); Status = XtLdrProtocol->Memory.AllocatePages(AllocateAnyPages, 1, &Address);
if(Status != STATUS_EFI_SUCCESS) if(Status != STATUS_EFI_SUCCESS)
{ {
/* Memory allocation failure, return error */ /* Memory allocation failure, return error */
@@ -38,23 +74,35 @@ XtpMapHardwareMemoryPool(IN PXTBL_PAGE_MAPPING PageMap)
/* Zero fill allocated memory */ /* Zero fill allocated memory */
RtlZeroMemory((PVOID)Address, EFI_PAGE_SIZE); RtlZeroMemory((PVOID)Address, EFI_PAGE_SIZE);
/* Check page map level */ /* Check if PAE is enabled (3-level paging) */
if(PageMap->PageMapLevel == 3) if(PageMap->PageMapLevel == 3)
{ {
/* Get PDE base address (PAE enabled) */ /* Get PDE base address (PAE enabled) */
PdeBase = (PHARDWARE_PTE)(((PHARDWARE_PTE)PageMap->PtePointer)[MM_HARDWARE_VA_START >> MM_PPI_SHIFT].PageFrameNumber << MM_PAGE_SHIFT); PdeBase = (PHARDWARE_MODERN_PTE)(((PHARDWARE_MODERN_PTE)PageMap->PtePointer)[MM_HARDWARE_VA_START >> MM_PPI_SHIFT].PageFrameNumber << MM_PAGE_SHIFT);
/* Make PDE valid */ /* Make PDE valid */
RtlZeroMemory(&PdeBase[(MM_HARDWARE_VA_START >> MM_PDI_SHIFT) & 0x1FF], sizeof(HARDWARE_MODERN_PTE));
PdeBase[(MM_HARDWARE_VA_START >> MM_PDI_SHIFT) & 0x1FF].PageFrameNumber = Address >> MM_PAGE_SHIFT; PdeBase[(MM_HARDWARE_VA_START >> MM_PDI_SHIFT) & 0x1FF].PageFrameNumber = Address >> MM_PAGE_SHIFT;
PdeBase[(MM_HARDWARE_VA_START >> MM_PDI_SHIFT) & 0x1FF].Valid = 1; PdeBase[(MM_HARDWARE_VA_START >> MM_PDI_SHIFT) & 0x1FF].Valid = 1;
PdeBase[(MM_HARDWARE_VA_START >> MM_PDI_SHIFT) & 0x1FF].Writable = 1; PdeBase[(MM_HARDWARE_VA_START >> MM_PDI_SHIFT) & 0x1FF].Writable = 1;
} }
else else
{ {
/* Make PDE valid (PAE disabled) */ /* Get PDE base address (PAE disabled) */
((PHARDWARE_LEGACY_PTE)PageMap->PtePointer)[MM_HARDWARE_VA_START >> MM_PDI_LEGACY_SHIFT].Valid = 1; LegacyPdeBase = (PHARDWARE_LEGACY_PTE)PageMap->PtePointer;
((PHARDWARE_LEGACY_PTE)PageMap->PtePointer)[MM_HARDWARE_VA_START >> MM_PDI_LEGACY_SHIFT].PageFrameNumber = Address >> MM_PAGE_SHIFT;
((PHARDWARE_LEGACY_PTE)PageMap->PtePointer)[MM_HARDWARE_VA_START >> MM_PDI_LEGACY_SHIFT].Writable = 1; /* Check for a conflicting PDE */
if(LegacyPdeBase[MM_HARDWARE_VA_START >> MM_PDI_LEGACY_SHIFT].Valid)
{
/* PDE already exists and is valid, nothing to do */
return STATUS_EFI_SUCCESS;
}
/* Make PDE valid */
RtlZeroMemory(&LegacyPdeBase[MM_HARDWARE_VA_START >> MM_PDI_LEGACY_SHIFT], sizeof(HARDWARE_LEGACY_PTE));
LegacyPdeBase[MM_HARDWARE_VA_START >> MM_PDI_LEGACY_SHIFT].Valid = 1;
LegacyPdeBase[MM_HARDWARE_VA_START >> MM_PDI_LEGACY_SHIFT].PageFrameNumber = Address >> MM_PAGE_SHIFT;
LegacyPdeBase[MM_HARDWARE_VA_START >> MM_PDI_LEGACY_SHIFT].Writable = 1;
} }
/* Return success */ /* Return success */
@@ -75,30 +123,10 @@ XTCDECL
EFI_STATUS EFI_STATUS
XtEnablePaging(IN PXTBL_PAGE_MAPPING PageMap) XtEnablePaging(IN PXTBL_PAGE_MAPPING PageMap)
{ {
PCPUID_REGISTERS CpuRegisters = NULL;
EFI_STATUS Status; EFI_STATUS Status;
/* Prepare CPUID registers */
CpuRegisters->Leaf = CPUID_GET_CPU_FEATURES;
CpuRegisters->SubLeaf = 0;
CpuRegisters->Eax = 0;
CpuRegisters->Ebx = 0;
CpuRegisters->Ecx = 0;
CpuRegisters->Edx = 0;
/* Get CPUID */
ArCpuId(CpuRegisters);
/* Store PAE status from the CPUID results */
if(!(CpuRegisters->Edx & CPUID_FEATURES_EDX_PAE))
{
/* No PAE support */
XtLdrProtocol->Debug.Print(L"ERROR: PAE extension not supported by the CPU\n");
return STATUS_EFI_UNSUPPORTED;
}
/* Build page map */ /* Build page map */
Status = XtLdrProtocol->Memory.BuildPageMap(PageMap, 0xC0000000); Status = XtLdrProtocol->Memory.BuildPageMap(PageMap, MM_PTE_BASE);
if(Status != STATUS_EFI_SUCCESS) if(Status != STATUS_EFI_SUCCESS)
{ {
/* Failed to build page map */ /* Failed to build page map */
@@ -111,7 +139,7 @@ XtEnablePaging(IN PXTBL_PAGE_MAPPING PageMap)
if(Status != STATUS_EFI_SUCCESS) if(Status != STATUS_EFI_SUCCESS)
{ {
/* Failed to map memory for hardware layer */ /* Failed to map memory for hardware layer */
XtLdrProtocol->Debug.Print(L"Failed to map memory for hardware leyer (Status code: %zX)\n", Status); XtLdrProtocol->Debug.Print(L"Failed to map memory for hardware layer (Status code: %zX)\n", Status);
return Status; return Status;
} }
@@ -125,8 +153,22 @@ XtEnablePaging(IN PXTBL_PAGE_MAPPING PageMap)
return STATUS_EFI_ABORTED; return STATUS_EFI_ABORTED;
} }
/* Enable Physical Address Extension (PAE) */ /* Disable paging */
ArWriteControlRegister(4, ArReadControlRegister(4) | CR4_PAE); ArWriteControlRegister(0, ArReadControlRegister(0) & ~CR0_PG);
/* Check the configured page map level to set the PAE state accordingly */
if(PageMap->PageMapLevel == 3)
{
/* Enable Physical Address Extension (PAE) */
XtLdrProtocol->Debug.Print(L"Enabling Physical Address Extension (PAE)\n");
ArWriteControlRegister(4, ArReadControlRegister(4) | CR4_PAE);
}
else
{
/* Disable Physical Address Extension (PAE) */
XtLdrProtocol->Debug.Print(L"Disabling Physical Address Extension (PAE)\n");
ArWriteControlRegister(4, ArReadControlRegister(4) & ~CR4_PAE);
}
/* Write page mappings to CR3 */ /* Write page mappings to CR3 */
ArWriteControlRegister(3, (UINT_PTR)PageMap->PtePointer); ArWriteControlRegister(3, (UINT_PTR)PageMap->PtePointer);

View File

@@ -29,9 +29,15 @@ typedef struct _XT_FRAMEBUFFER_PROTOCOL
/* EFI XT Loader Protocol */ /* EFI XT Loader Protocol */
EXTERN PXTBL_LOADER_PROTOCOL XtLdrProtocol; EXTERN PXTBL_LOADER_PROTOCOL XtLdrProtocol;
/* XTOS trampoline end address to calculate trampoline size */
EXTERN PVOID ArEnableExtendedPhysicalAddressingEnd[];
/* XTOS kernel entry point */ /* XTOS kernel entry point */
typedef VOID (XTAPI *PXT_ENTRY_POINT)(IN PKERNEL_INITIALIZATION_BLOCK BootParameters); typedef VOID (XTAPI *PXT_ENTRY_POINT)(IN PKERNEL_INITIALIZATION_BLOCK BootParameters);
/* XTOS trampoline entry point */
typedef VOID (*PXT_TRAMPOLINE_ENTRY)(UINT64 PageMap);
/* XTOS boot protocol related routines forward references */ /* XTOS boot protocol related routines forward references */
XTCDECL XTCDECL
EFI_STATUS EFI_STATUS
@@ -49,6 +55,10 @@ XTCDECL
LOADER_MEMORY_TYPE LOADER_MEMORY_TYPE
XtConvertEfiMemoryType(IN EFI_MEMORY_TYPE EfiMemoryType); XtConvertEfiMemoryType(IN EFI_MEMORY_TYPE EfiMemoryType);
XTCDECL
ULONG
XtpDeterminePagingLevel(IN CONST PWCHAR Parameters);
XTCDECL XTCDECL
EFI_STATUS EFI_STATUS
XtEnablePaging(IN PXTBL_PAGE_MAPPING PageMap); XtEnablePaging(IN PXTBL_PAGE_MAPPING PageMap);

View File

@@ -75,7 +75,7 @@ XtGetMemoryDescriptorList(IN PXTBL_PAGE_MAPPING PageMap,
Pages = (ULONGLONG)EFI_SIZE_TO_PAGES((PageMap->MapSize + 1) * sizeof(LOADER_MEMORY_DESCRIPTOR)); Pages = (ULONGLONG)EFI_SIZE_TO_PAGES((PageMap->MapSize + 1) * sizeof(LOADER_MEMORY_DESCRIPTOR));
Status = XtLdrProtocol->Memory.AllocatePages(Pages, &Address); Status = XtLdrProtocol->Memory.AllocatePages(AllocateAnyPages, Pages, &Address);
if(Status != STATUS_EFI_SUCCESS) if(Status != STATUS_EFI_SUCCESS)
{ {
return Status; return Status;
@@ -136,7 +136,7 @@ XtGetSystemResourcesList(IN PXTBL_PAGE_MAPPING PageMap,
Pages = (ULONGLONG)EFI_SIZE_TO_PAGES(sizeof(SYSTEM_RESOURCE_ACPI) + sizeof(SYSTEM_RESOURCE_FRAMEBUFFER)); Pages = (ULONGLONG)EFI_SIZE_TO_PAGES(sizeof(SYSTEM_RESOURCE_ACPI) + sizeof(SYSTEM_RESOURCE_FRAMEBUFFER));
Status = XtLdrProtocol->Memory.AllocatePages(Pages, &Address); Status = XtLdrProtocol->Memory.AllocatePages(AllocateAnyPages, Pages, &Address);
if(Status != STATUS_EFI_SUCCESS) if(Status != STATUS_EFI_SUCCESS)
{ {
return Status; return Status;
@@ -323,7 +323,7 @@ XtBootSystem(IN PXTBL_BOOT_PARAMETERS Parameters)
Parameters->KernelFile, Parameters->Parameters); Parameters->KernelFile, Parameters->Parameters);
/* Open EFI volume */ /* Open EFI volume */
Status = XtLdrProtocol->Disk.OpenVolume(NULL, &DiskHandle, &FsHandle); Status = XtLdrProtocol->Disk.OpenVolume(Parameters->DevicePath, &DiskHandle, &FsHandle);
if(Status != STATUS_EFI_SUCCESS) if(Status != STATUS_EFI_SUCCESS)
{ {
/* Failed to open a volume */ /* Failed to open a volume */
@@ -410,7 +410,7 @@ XtpBootSequence(IN PEFI_FILE_HANDLE BootDir,
VirtualAddress = (PVOID)(KSEG0_BASE + KSEG0_KERNEL_BASE); VirtualAddress = (PVOID)(KSEG0_BASE + KSEG0_KERNEL_BASE);
/* Initialize virtual memory mappings */ /* Initialize virtual memory mappings */
XtLdrProtocol->Memory.InitializePageMap(&PageMap, 3, Size4K); XtLdrProtocol->Memory.InitializePageMap(&PageMap, XtpDeterminePagingLevel(Parameters->Parameters), Size4K);
Status = XtLdrProtocol->Memory.MapEfiMemory(&PageMap, &VirtualMemoryArea, NULL); Status = XtLdrProtocol->Memory.MapEfiMemory(&PageMap, &VirtualMemoryArea, NULL);
if(Status != STATUS_EFI_SUCCESS) if(Status != STATUS_EFI_SUCCESS)
@@ -547,12 +547,16 @@ XtpInitializeLoaderBlock(IN PXTBL_PAGE_MAPPING PageMap,
// PVOID RuntimeServices; // PVOID RuntimeServices;
EFI_STATUS Status; EFI_STATUS Status;
UINT BlockPages; UINT BlockPages;
UINT ParametersSize;
/* Calculate size of parameters */
ParametersSize = (RtlWideStringLength(Parameters->Parameters, 0) + 1) * sizeof(WCHAR);
/* Calculate number of pages needed for initialization block */ /* Calculate number of pages needed for initialization block */
BlockPages = EFI_SIZE_TO_PAGES(sizeof(KERNEL_INITIALIZATION_BLOCK)); BlockPages = EFI_SIZE_TO_PAGES(sizeof(KERNEL_INITIALIZATION_BLOCK) + ParametersSize);
/* Allocate memory for kernel initialization block */ /* Allocate memory for kernel initialization block */
Status = XtLdrProtocol->Memory.AllocatePages(BlockPages, &Address); Status = XtLdrProtocol->Memory.AllocatePages(AllocateAnyPages, BlockPages, &Address);
if(Status != STATUS_EFI_SUCCESS) if(Status != STATUS_EFI_SUCCESS)
{ {
/* Memory allocation failure */ /* Memory allocation failure */
@@ -561,7 +565,7 @@ XtpInitializeLoaderBlock(IN PXTBL_PAGE_MAPPING PageMap,
/* Initialize and zero-fill kernel initialization block */ /* Initialize and zero-fill kernel initialization block */
LoaderBlock = (PKERNEL_INITIALIZATION_BLOCK)(UINT_PTR)Address; LoaderBlock = (PKERNEL_INITIALIZATION_BLOCK)(UINT_PTR)Address;
RtlZeroMemory(LoaderBlock, sizeof(KERNEL_INITIALIZATION_BLOCK)); RtlZeroMemory(LoaderBlock, sizeof(KERNEL_INITIALIZATION_BLOCK) + ParametersSize);
/* Set basic loader block properties */ /* Set basic loader block properties */
LoaderBlock->BlockSize = sizeof(KERNEL_INITIALIZATION_BLOCK); LoaderBlock->BlockSize = sizeof(KERNEL_INITIALIZATION_BLOCK);
@@ -571,9 +575,6 @@ XtpInitializeLoaderBlock(IN PXTBL_PAGE_MAPPING PageMap,
/* Set LoaderInformation block properties */ /* Set LoaderInformation block properties */
LoaderBlock->LoaderInformation.DbgPrint = XtLdrProtocol->Debug.Print; LoaderBlock->LoaderInformation.DbgPrint = XtLdrProtocol->Debug.Print;
/* Store page map level */
LoaderBlock->LoaderInformation.PageMapLevel = 3;
/* Attempt to find virtual address of the EFI Runtime Services */ /* Attempt to find virtual address of the EFI Runtime Services */
// Status = XtLdrProtocol->GetVirtualAddress(MemoryMappings, &EfiSystemTable->RuntimeServices->Hdr, &RuntimeServices); // Status = XtLdrProtocol->GetVirtualAddress(MemoryMappings, &EfiSystemTable->RuntimeServices->Hdr, &RuntimeServices);
// if(Status == STATUS_EFI_SUCCESS) // if(Status == STATUS_EFI_SUCCESS)
@@ -590,8 +591,10 @@ XtpInitializeLoaderBlock(IN PXTBL_PAGE_MAPPING PageMap,
// } // }
/* Copy parameters to kernel initialization block */ /* Copy parameters to kernel initialization block */
RtlCopyMemory(LoaderBlock->KernelParameters, Parameters->Parameters, LoaderBlock->KernelParameters = (PWCHAR)((UINT_PTR)*VirtualAddress + sizeof(KERNEL_INITIALIZATION_BLOCK));
(RtlWideStringLength(Parameters->Parameters, 0) + 1) * sizeof(WCHAR)); RtlCopyMemory((PVOID)((UINT_PTR)LoaderBlock + sizeof(KERNEL_INITIALIZATION_BLOCK)),
Parameters->Parameters,
ParametersSize);
/* Map kernel initialization block */ /* Map kernel initialization block */
XtLdrProtocol->Memory.MapVirtualMemory(PageMap, *VirtualAddress, (PVOID)LoaderBlock, XtLdrProtocol->Memory.MapVirtualMemory(PageMap, *VirtualAddress, (PVOID)LoaderBlock,

View File

@@ -749,100 +749,96 @@ BlpGetModuleInfoStrings(IN PWCHAR SectionData,
EFI_STATUS Status; EFI_STATUS Status;
PWCHAR *Array; PWCHAR *Array;
PWCHAR String; PWCHAR String;
ULONG DataSize;
/* Check input parameters */ /* Check input parameters */
InfoStrings = SectionData; InfoStrings = SectionData;
if(!InfoStrings || !SectionSize) if(!InfoStrings || !SectionSize)
{ {
/* Invalid input parameters */ /* Invalid input parameters */
*ModInfo = NULL;
*InfoCount = 0;
return STATUS_EFI_INVALID_PARAMETER; return STATUS_EFI_INVALID_PARAMETER;
} }
/* Skip zero padding */ /* Calculate the size of the data based on the size of the section */
while(InfoStrings[0] == L'\0' && SectionSize > 1) DataSize = SectionSize / sizeof(WCHAR);
/* Skip zero padding at the beginning */
while(DataSize > 0 && *InfoStrings == L'\0')
{ {
/* Get next character and decrement section size */
InfoStrings++; InfoStrings++;
SectionSize--; DataSize--;
} }
/* Make sure there is at least one string available */ /* Make sure there is at least one string available */
if(SectionSize <= 1) if(DataSize < 1)
{ {
/* No strings found */ /* No strings found */
*ModInfo = NULL;
*InfoCount = 0;
return STATUS_EFI_END_OF_FILE; return STATUS_EFI_END_OF_FILE;
} }
/* Count number of strings */ /* Count number of strings */
Index = 0; Index = 0;
Count = 0; Count = 0;
while(Index < SectionSize) while(Index < DataSize)
{ {
/* Get to the next string */ /* Found start of a new string */
if(InfoStrings[Index] != L'\0') Count++;
{
/* Get next character */
Index++;
continue;
}
/* Skip zero padding */ /* Go to the end of the string */
while(InfoStrings[Index] == L'\0' && Index < SectionSize) while(Index < DataSize && InfoStrings[Index] != L'\0')
{
Index++;
}
/* Skip all null terminators */
while(Index < DataSize && InfoStrings[Index] == L'\0')
{ {
/* Get next character */
Index++; Index++;
} }
/* New string found, increment counter */
Count++;
} }
/* Make sure there is no missing string */ /* Allocate memory for the pointer array and the string data */
if(InfoStrings[Index - 1] != L'\0') Status = BlAllocateMemoryPool(sizeof(PWCHAR) * (Count + 1) + (DataSize + 1) * sizeof(WCHAR), (PVOID *)&Array);
{
/* One more string available */
Count++;
}
/* Allocate memory for array of strings */
Status = BlAllocateMemoryPool(SectionSize + 1 + sizeof(PWCHAR) * (Count + 1), (PVOID *)&Array);
if(Status != STATUS_EFI_SUCCESS) if(Status != STATUS_EFI_SUCCESS)
{ {
/* Failed to allocate memory */ /* Failed to allocate memory */
return STATUS_EFI_OUT_OF_RESOURCES; return STATUS_EFI_OUT_OF_RESOURCES;
} }
/* Allocate memory and copy strings read from '.modinfo' section */ /* The string buffer is located right after the pointer array */
BlAllocateMemoryPool(SectionSize, (PVOID*)&String); String = (PWCHAR)(Array + Count + 1);
RtlCopyMemory(String, InfoStrings, SectionSize);
/* Make sure last string is NULL-terminated */ /* Copy the raw string data */
RtlCopyMemory(String, InfoStrings, DataSize * sizeof(WCHAR));
/* Ensure the entire buffer is null-terminated for safety */
String[DataSize] = L'\0';
/* Set the last element of the pointer array to NULL */
Array[Count] = NULL; Array[Count] = NULL;
Array[0] = String;
/* Parse strings into array */ /* Populate the array with pointers to the strings within the buffer */
Index = 0; Index = 0;
ArrayIndex = 1; ArrayIndex = 0;
while(Index < SectionSize && ArrayIndex < Count) while(Index < DataSize && ArrayIndex < Count)
{ {
/* Get to the next string */ /* Set pointer to the beginning of the string */
if(String[Index] != L'\0') Array[ArrayIndex++] = &String[Index];
{
/* Get next character */
Index++;
continue;
}
/* Skip zero padding */ /* Find the end of the current string */
while(InfoStrings[Index] == L'\0' && Index < SectionSize) while(Index < DataSize && String[Index] != L'\0')
{ {
/* Get next character */
Index++; Index++;
} }
/* Push string into array */ /* Skip all null terminators to find the beginning of the next string */
Array[ArrayIndex] = &String[Index]; while(Index < DataSize && String[Index] == L'\0')
ArrayIndex++; {
Index++;
}
} }
/* Return array of strings and its size */ /* Return array of strings and its size */
@@ -872,8 +868,12 @@ BlpInstallXtLoaderProtocol()
BlpLdrProtocol.Boot.InvokeProtocol = BlInvokeBootProtocol; BlpLdrProtocol.Boot.InvokeProtocol = BlInvokeBootProtocol;
BlpLdrProtocol.Boot.RegisterMenu = BlRegisterBootMenu; BlpLdrProtocol.Boot.RegisterMenu = BlRegisterBootMenu;
BlpLdrProtocol.Boot.RegisterProtocol = BlRegisterBootProtocol; BlpLdrProtocol.Boot.RegisterProtocol = BlRegisterBootProtocol;
BlpLdrProtocol.BootUtil.GetBooleanParameter = BlGetBooleanParameter;
BlpLdrProtocol.Config.GetBooleanValue = BlGetConfigBooleanValue; BlpLdrProtocol.Config.GetBooleanValue = BlGetConfigBooleanValue;
BlpLdrProtocol.Config.GetBootOptionValue = BlGetBootOptionValue;
BlpLdrProtocol.Config.GetEditableOptions = BlGetEditableOptions;
BlpLdrProtocol.Config.GetValue = BlGetConfigValue; BlpLdrProtocol.Config.GetValue = BlGetConfigValue;
BlpLdrProtocol.Config.SetBootOptionValue = BlSetBootOptionValue;
BlpLdrProtocol.Console.ClearLine = BlClearConsoleLine; BlpLdrProtocol.Console.ClearLine = BlClearConsoleLine;
BlpLdrProtocol.Console.ClearScreen = BlClearConsoleScreen; BlpLdrProtocol.Console.ClearScreen = BlClearConsoleScreen;
BlpLdrProtocol.Console.DisableCursor = BlDisableConsoleCursor; BlpLdrProtocol.Console.DisableCursor = BlDisableConsoleCursor;

View File

@@ -4,6 +4,7 @@
* FILE: xtldr/textui.c * FILE: xtldr/textui.c
* DESCRIPTION: Text console User Interface (TUI) support for XT Boot Loader * DESCRIPTION: Text console User Interface (TUI) support for XT Boot Loader
* DEVELOPERS: Rafal Kupiec <belliash@codingworkshop.eu.org> * DEVELOPERS: Rafal Kupiec <belliash@codingworkshop.eu.org>
* Aiken Harris <harraiken91@gmail.com>
*/ */
#include <xtldr.h> #include <xtldr.h>
@@ -22,7 +23,9 @@ BlDisplayBootMenu()
{ {
XTBL_DIALOG_HANDLE Handle; XTBL_DIALOG_HANDLE Handle;
PXTBL_BOOTMENU_ITEM MenuEntries = NULL; PXTBL_BOOTMENU_ITEM MenuEntries = NULL;
ULONG Index, NumberOfEntries, HighligtedEntryId; ULONG Index;
ULONG HighligtedEntryId, OldHighligtedEntryId, NumberOfEntries, TopVisibleEntry, VisibleEntries;
BOOLEAN RedrawBootMenu, RedrawEntries;
UINT_PTR EventIndex; UINT_PTR EventIndex;
EFI_EVENT Events[2]; EFI_EVENT Events[2];
EFI_INPUT_KEY Key; EFI_INPUT_KEY Key;
@@ -31,16 +34,30 @@ BlDisplayBootMenu()
LONG TimeOut; LONG TimeOut;
PWCHAR TimeOutString; PWCHAR TimeOutString;
/* Draw boot menu */
BlpDrawBootMenu(&Handle);
/* Initialize boot menu list */ /* Initialize boot menu list */
Status = BlInitializeBootMenuList(&MenuEntries, &NumberOfEntries, &HighligtedEntryId); TopVisibleEntry = 0;
Status = BlInitializeBootMenuList(Handle.Width - 4, &MenuEntries, &NumberOfEntries, &HighligtedEntryId);
if(Status != STATUS_EFI_SUCCESS) if(Status != STATUS_EFI_SUCCESS)
{ {
/* Failed to initialize boot menu list, exit into XTLDR shell */ /* Failed to initialize boot menu list, exit into XTLDR shell */
return; return;
} }
/* Calculate how many entries can be visible in the menu box */
VisibleEntries = Handle.Height - 2;
/* Adjust the view if the default entry is not initially visible */
if(HighligtedEntryId >= VisibleEntries)
{
/* Scroll the view to make the highlighted entry the last visible one */
TopVisibleEntry = HighligtedEntryId - VisibleEntries + 1;
}
/* Get timeout from the configuration */ /* Get timeout from the configuration */
TimeOutString = BlGetConfigValue(L"TIMEOUT"); BlGetConfigValue(L"TIMEOUT", &TimeOutString);
TimeOut = -1; TimeOut = -1;
/* Check if timeout is specified */ /* Check if timeout is specified */
@@ -56,26 +73,43 @@ BlDisplayBootMenu()
} }
} }
/* Set redraw flags to not redraw the menu itself, but fill it with entries */
RedrawBootMenu = FALSE;
RedrawEntries = TRUE;
/* Infinite boot menu loop */ /* Infinite boot menu loop */
while(TRUE) while(TRUE)
{ {
/* Draw boot menu */ /* Redraw boot menu frame if requested */
BlpDrawBootMenu(&Handle); if(RedrawBootMenu)
{
BlpDrawBootMenu(&Handle);
RedrawBootMenu = FALSE;
RedrawEntries = TRUE;
}
/* Sanity check to ensure we do not display more entries than possible */
if(VisibleEntries > NumberOfEntries)
{
VisibleEntries = NumberOfEntries;
}
/* Check if there is anything to show in the boot menu */ /* Check if there is anything to show in the boot menu */
if(NumberOfEntries > 0) { if(NumberOfEntries > 0)
/* Check if all menu entries will fit into the menu box */ {
if(NumberOfEntries > Handle.Height - 2) /* Check if we need to redraw boot menu entries */
if(RedrawEntries)
{ {
/* Too many menu entries, limit entries to match box height (-2 for upper and bottom borders) */ /* Iterate through all menu entries */
NumberOfEntries = Handle.Height - 2; for(Index = 0; Index < VisibleEntries; Index++)
} {
/* Draw menu entry */
BlpDrawBootMenuEntry(&Handle, MenuEntries[TopVisibleEntry + Index].EntryName,
Index, (TopVisibleEntry + Index) == HighligtedEntryId);
}
/* Iterate through all menu entries */ /* Clear redraw entries flag */
for(Index = 0; Index < NumberOfEntries; Index++) RedrawEntries = FALSE;
{
/* Draw menu entry */
BlpDrawBootMenuEntry(&Handle, MenuEntries[Index].EntryName, Index, Index == HighligtedEntryId);
} }
} }
else else
@@ -109,6 +143,9 @@ BlDisplayBootMenu()
/* Flush keyboard buffer out of any keystrokes */ /* Flush keyboard buffer out of any keystrokes */
EfiSystemTable->ConIn->Reset(EfiSystemTable->ConIn, FALSE); EfiSystemTable->ConIn->Reset(EfiSystemTable->ConIn, FALSE);
/* Store old highlighted entry */
OldHighligtedEntryId = HighligtedEntryId;
/* Infinite boot menu event loop */ /* Infinite boot menu event loop */
while(TRUE) while(TRUE)
{ {
@@ -140,7 +177,7 @@ BlDisplayBootMenu()
BlSetConsoleAttributes(Handle.DialogColor | Handle.TextColor); BlSetConsoleAttributes(Handle.DialogColor | Handle.TextColor);
BlClearConsoleLine(Handle.PosY + Handle.Height + 4); BlClearConsoleLine(Handle.PosY + Handle.Height + 4);
BlSetCursorPosition(4, Handle.PosY + Handle.Height + 4); BlSetCursorPosition(4, Handle.PosY + Handle.Height + 4);
BlConsolePrint(L"Booting '%S' now...\n", MenuEntries[HighligtedEntryId].EntryName); BlConsolePrint(L"Booting '%S' now...\n", MenuEntries[HighligtedEntryId].FullName);
/* Boot the highlighted (chosen) OS */ /* Boot the highlighted (chosen) OS */
Status = BlInvokeBootProtocol(MenuEntries[HighligtedEntryId].ShortName, Status = BlInvokeBootProtocol(MenuEntries[HighligtedEntryId].ShortName,
@@ -149,8 +186,9 @@ BlDisplayBootMenu()
{ {
/* Failed to boot OS */ /* Failed to boot OS */
BlDebugPrint(L"ERROR: Failed to boot '%S' (Status Code: 0x%zX)\n", BlDebugPrint(L"ERROR: Failed to boot '%S' (Status Code: 0x%zX)\n",
MenuEntries[HighligtedEntryId].EntryName, Status); MenuEntries[HighligtedEntryId].FullName, Status);
BlDisplayErrorDialog(L"XTLDR", L"Failed to startup the selected Operating System."); BlDisplayErrorDialog(L"XTLDR", L"Failed to startup the selected Operating System.");
RedrawBootMenu = TRUE;
} }
/* Break from boot menu event loop to redraw whole boot menu */ /* Break from boot menu event loop to redraw whole boot menu */
@@ -162,11 +200,23 @@ BlDisplayBootMenu()
if(HighligtedEntryId > 0) if(HighligtedEntryId > 0)
{ {
/* Highlight previous entry */ /* Highlight previous entry */
OldHighligtedEntryId = HighligtedEntryId;
HighligtedEntryId--; HighligtedEntryId--;
BlpDrawBootMenuEntry(&Handle, MenuEntries[HighligtedEntryId + 1].EntryName,
HighligtedEntryId + 1, FALSE); /* Check if we need to scroll the view */
if(HighligtedEntryId < TopVisibleEntry)
{
/* Scroll the view */
TopVisibleEntry = HighligtedEntryId;
RedrawEntries = TRUE;
break;
}
/* Redraw new highlighted entry and the old one */
BlpDrawBootMenuEntry(&Handle, MenuEntries[OldHighligtedEntryId].EntryName,
OldHighligtedEntryId - TopVisibleEntry, FALSE);
BlpDrawBootMenuEntry(&Handle, MenuEntries[HighligtedEntryId].EntryName, BlpDrawBootMenuEntry(&Handle, MenuEntries[HighligtedEntryId].EntryName,
HighligtedEntryId, TRUE); HighligtedEntryId - TopVisibleEntry, TRUE);
} }
} }
else if(Key.ScanCode == 0x02) else if(Key.ScanCode == 0x02)
@@ -175,11 +225,23 @@ BlDisplayBootMenu()
if(HighligtedEntryId < NumberOfEntries - 1) if(HighligtedEntryId < NumberOfEntries - 1)
{ {
/* Highlight next entry */ /* Highlight next entry */
OldHighligtedEntryId = HighligtedEntryId;
HighligtedEntryId++; HighligtedEntryId++;
BlpDrawBootMenuEntry(&Handle, MenuEntries[HighligtedEntryId - 1].EntryName,
HighligtedEntryId - 1, FALSE); /* Check if we need to scroll the view */
if(HighligtedEntryId >= TopVisibleEntry + VisibleEntries)
{
/* Scroll the view */
TopVisibleEntry = HighligtedEntryId - VisibleEntries + 1;
RedrawEntries = TRUE;
break;
}
/* Redraw new highlighted entry and the old one */
BlpDrawBootMenuEntry(&Handle, MenuEntries[OldHighligtedEntryId].EntryName,
OldHighligtedEntryId - TopVisibleEntry, FALSE);
BlpDrawBootMenuEntry(&Handle, MenuEntries[HighligtedEntryId].EntryName, BlpDrawBootMenuEntry(&Handle, MenuEntries[HighligtedEntryId].EntryName,
HighligtedEntryId, TRUE); HighligtedEntryId - TopVisibleEntry, TRUE);
} }
} }
else if(Key.ScanCode == 0x09) else if(Key.ScanCode == 0x09)
@@ -188,12 +250,10 @@ BlDisplayBootMenu()
if(HighligtedEntryId != 0) if(HighligtedEntryId != 0)
{ {
/* Highlight first entry */ /* Highlight first entry */
BlpDrawBootMenuEntry(&Handle, MenuEntries[HighligtedEntryId].EntryName,
HighligtedEntryId, FALSE);
BlpDrawBootMenuEntry(&Handle, MenuEntries[0].EntryName, 0, TRUE);
/* Update highlighted entry ID */
HighligtedEntryId = 0; HighligtedEntryId = 0;
TopVisibleEntry = 0;
RedrawEntries = TRUE;
break;
} }
} }
else if(Key.ScanCode == 0x0A) else if(Key.ScanCode == 0x0A)
@@ -202,13 +262,10 @@ BlDisplayBootMenu()
if(HighligtedEntryId != NumberOfEntries - 1) if(HighligtedEntryId != NumberOfEntries - 1)
{ {
/* Highlight last entry */ /* Highlight last entry */
BlpDrawBootMenuEntry(&Handle, MenuEntries[HighligtedEntryId].EntryName,
HighligtedEntryId, FALSE);
BlpDrawBootMenuEntry(&Handle, MenuEntries[NumberOfEntries - 1].EntryName,
NumberOfEntries - 1, TRUE);
/* Update highlighted entry ID */
HighligtedEntryId = NumberOfEntries - 1; HighligtedEntryId = NumberOfEntries - 1;
TopVisibleEntry = (NumberOfEntries > VisibleEntries) ? (NumberOfEntries - VisibleEntries) : 0;
RedrawEntries = TRUE;
break;
} }
} }
else if(Key.ScanCode == 0x0B) else if(Key.ScanCode == 0x0B)
@@ -231,6 +288,7 @@ BlDisplayBootMenu()
L"Visit https://exectos.eu.org/ for more information."); L"Visit https://exectos.eu.org/ for more information.");
/* Break from boot menu event loop to redraw whole boot menu */ /* Break from boot menu event loop to redraw whole boot menu */
RedrawBootMenu = TRUE;
break; break;
} }
else if(Key.ScanCode == 0x14) else if(Key.ScanCode == 0x14)
@@ -238,6 +296,7 @@ BlDisplayBootMenu()
/* F10 key pressed, reboot into UEFI setup interface */ /* F10 key pressed, reboot into UEFI setup interface */
BlEnterFirmwareSetup(); BlEnterFirmwareSetup();
BlDisplayErrorDialog(L"XTLDR", L"Reboot into firmware setup interface not supported!"); BlDisplayErrorDialog(L"XTLDR", L"Reboot into firmware setup interface not supported!");
RedrawBootMenu = TRUE;
/* Break from boot menu event loop to redraw whole boot menu */ /* Break from boot menu event loop to redraw whole boot menu */
break; break;
@@ -247,6 +306,7 @@ BlDisplayBootMenu()
/* F11 key pressed, reboot the machine */ /* F11 key pressed, reboot the machine */
BlRebootSystem(); BlRebootSystem();
BlDisplayErrorDialog(L"XTLDR", L"Failed to reboot the machine!"); BlDisplayErrorDialog(L"XTLDR", L"Failed to reboot the machine!");
RedrawBootMenu = TRUE;
/* Break from boot menu event loop to redraw whole boot menu */ /* Break from boot menu event loop to redraw whole boot menu */
break; break;
@@ -256,6 +316,7 @@ BlDisplayBootMenu()
/* F12 key pressed, shutdown the machine */ /* F12 key pressed, shutdown the machine */
BlShutdownSystem(); BlShutdownSystem();
BlDisplayErrorDialog(L"XTLDR", L"Failed to shutdown the machine!"); BlDisplayErrorDialog(L"XTLDR", L"Failed to shutdown the machine!");
RedrawBootMenu = TRUE;
/* Break from boot menu event loop to redraw whole boot menu */ /* Break from boot menu event loop to redraw whole boot menu */
break; break;
@@ -263,7 +324,8 @@ BlDisplayBootMenu()
else if(Key.UnicodeChar == 0x65) else if(Key.UnicodeChar == 0x65)
{ {
/* 'e' key pressed, edit the highlighted entry */ /* 'e' key pressed, edit the highlighted entry */
BlDisplayErrorDialog(L"XTLDR", L"Editing boot menu entries is not implemented yet!"); BlDisplayEditMenu(&MenuEntries[HighligtedEntryId]);
RedrawBootMenu = TRUE;
/* Break from boot menu event loop to redraw whole boot menu */ /* Break from boot menu event loop to redraw whole boot menu */
break; break;
@@ -292,7 +354,7 @@ BlDisplayBootMenu()
BlSetConsoleAttributes(Handle.DialogColor | Handle.TextColor); BlSetConsoleAttributes(Handle.DialogColor | Handle.TextColor);
BlClearConsoleLine(Handle.PosY + Handle.Height + 4); BlClearConsoleLine(Handle.PosY + Handle.Height + 4);
BlSetCursorPosition(4, Handle.PosY + Handle.Height + 4); BlSetCursorPosition(4, Handle.PosY + Handle.Height + 4);
BlConsolePrint(L"Booting '%S' now...\n", MenuEntries[HighligtedEntryId].EntryName); BlConsolePrint(L"Booting '%S' now...\n", MenuEntries[HighligtedEntryId].FullName);
/* Disable the timer just in case booting OS fails */ /* Disable the timer just in case booting OS fails */
TimeOut = -1; TimeOut = -1;
@@ -304,8 +366,9 @@ BlDisplayBootMenu()
{ {
/* Failed to boot OS */ /* Failed to boot OS */
BlDebugPrint(L"ERROR: Failed to boot '%S' (Status Code: 0x%zX)\n", BlDebugPrint(L"ERROR: Failed to boot '%S' (Status Code: 0x%zX)\n",
MenuEntries[HighligtedEntryId].EntryName, Status); MenuEntries[HighligtedEntryId].FullName, Status);
BlDisplayErrorDialog(L"XTLDR", L"Failed to startup the selected Operating System."); BlDisplayErrorDialog(L"XTLDR", L"Failed to startup the selected Operating System.");
RedrawBootMenu = TRUE;
} }
break; break;
} }
@@ -314,6 +377,254 @@ BlDisplayBootMenu()
} }
} }
/**
* Displays a simple TUI-based edit menu.
*
* @return This routine does not return any value.
*
* @since XT 1.0
*/
XTCDECL
VOID
BlDisplayEditMenu(IN PXTBL_BOOTMENU_ITEM MenuEntry)
{
ULONG HighligtedOptionId, Index, NumberOfOptions, OldHighligtedOptionId, TopVisibleEntry, VisibleEntries;
XTBL_DIALOG_HANDLE Handle;
BOOLEAN RedrawEditMenu, RedrawEntries;
EFI_INPUT_KEY Key;
UINT_PTR EventIndex;
PWCHAR NewValue, OptionName, OriginalValue, Value, ValueToEdit;
CONST PWCHAR *EditableOptions;
EFI_STATUS Status;
/* Draw edit menu */
BlpDrawEditMenu(&Handle);
/* Get the list of user editable options */
BlGetEditableOptions(&EditableOptions, &NumberOfOptions);
/* Calculate how many entries can be visible in the menu box */
VisibleEntries = Handle.Height - 2;
/* Assume the first option is highlighted by default */
HighligtedOptionId = 0;
OldHighligtedOptionId = 0;
TopVisibleEntry = 0;
/* Set redraw flags to not redraw the menu itself, but fill it with entries */
RedrawEditMenu = FALSE;
RedrawEntries = TRUE;
/* Infinite edit menu loop */
while(TRUE)
{
/* Redraw edit menu frame if requested */
if(RedrawEditMenu)
{
BlpDrawEditMenu(&Handle);
RedrawEditMenu = FALSE;
RedrawEntries = TRUE;
}
/* Sanity check to ensure we do not display more entries than possible */
if(VisibleEntries > NumberOfOptions)
{
VisibleEntries = NumberOfOptions;
}
/* Check if we need to redraw boot menu entries */
if(RedrawEntries)
{
/* Iterate through all menu entries */
for(Index = 0; Index < VisibleEntries; Index++)
{
/* Draw menu entry */
BlGetBootOptionValue(MenuEntry->Options, EditableOptions[TopVisibleEntry + Index], &Value);
BlpDrawEditMenuEntry(&Handle, EditableOptions[TopVisibleEntry + Index], Value, Index,
(TopVisibleEntry + Index) == HighligtedOptionId);
/* Free allocated value string if needed */
if(Value != NULL)
{
BlFreeMemoryPool(Value);
}
}
/* Clear redraw entries flag */
RedrawEntries = FALSE;
}
/* Wait for EFI event and read key stroke */
BlWaitForEfiEvent(1, &EfiSystemTable->ConIn->WaitForKey, &EventIndex);
BlReadKeyStroke(&Key);
/* Check key press scan code */
if(Key.UnicodeChar == 0x0D || Key.UnicodeChar == 0x65)
{
/* ENTER or 'e' key pressed, edit the highlighted option */
OptionName = EditableOptions[HighligtedOptionId];
BlGetBootOptionValue(MenuEntry->Options, OptionName, &OriginalValue);
/* If the original value is NULL, use an empty string for editing */
if(OriginalValue == NULL)
{
ValueToEdit = L"";
}
else
{
ValueToEdit = OriginalValue;
}
/* Display input dialog to edit the option value */
NewValue = ValueToEdit;
BlDisplayInputDialog(OptionName, L"Enter new value:", &NewValue);
/* Check if the value was changed */
if(NewValue != ValueToEdit)
{
/* Update the boot option with the new value and free the old value */
BlSetBootOptionValue(MenuEntry->Options, OptionName, NewValue);
BlFreeMemoryPool(NewValue);
}
/* Free the original value if it was allocated */
if(OriginalValue != NULL)
{
BlFreeMemoryPool(OriginalValue);
}
/* Mark the edit menu for redraw */
RedrawEditMenu = TRUE;
}
else if(Key.ScanCode == 0x01)
{
/* UpArrow key pressed, go to previous entry if possible */
if(HighligtedOptionId > 0)
{
/* Highlight previous entry */
OldHighligtedOptionId = HighligtedOptionId;
HighligtedOptionId--;
/* Check if we need to scroll the view */
if(HighligtedOptionId < TopVisibleEntry)
{
/* Scroll the view */
TopVisibleEntry = HighligtedOptionId;
RedrawEntries = TRUE;
continue;
}
/* Redraw old highlighted entry */
BlGetBootOptionValue(MenuEntry->Options, EditableOptions[OldHighligtedOptionId], &Value);
BlpDrawEditMenuEntry(&Handle, EditableOptions[OldHighligtedOptionId], Value, OldHighligtedOptionId - TopVisibleEntry, FALSE);
/* Free allocated value string if needed */
if(Value != NULL)
{
BlFreeMemoryPool(Value);
}
/* Redraw new highlighted entry */
BlGetBootOptionValue(MenuEntry->Options, EditableOptions[HighligtedOptionId], &Value);
BlpDrawEditMenuEntry(&Handle, EditableOptions[HighligtedOptionId], Value, HighligtedOptionId - TopVisibleEntry, TRUE);
/* Free allocated value string if needed */
if(Value != NULL)
{
BlFreeMemoryPool(Value);
}
}
}
else if(Key.ScanCode == 0x02)
{
/* DownArrow key pressed, go to next entry if possible */
if(HighligtedOptionId < NumberOfOptions - 1)
{
/* Highlight next entry */
OldHighligtedOptionId = HighligtedOptionId;
HighligtedOptionId++;
/* Check if we need to scroll the view */
if(HighligtedOptionId >= TopVisibleEntry + VisibleEntries)
{
/* Scroll the view */
TopVisibleEntry = HighligtedOptionId - VisibleEntries + 1;
RedrawEntries = TRUE;
continue;
}
/* Redraw old highlighted entry */
BlGetBootOptionValue(MenuEntry->Options, EditableOptions[OldHighligtedOptionId], &Value);
BlpDrawEditMenuEntry(&Handle, EditableOptions[OldHighligtedOptionId], Value, OldHighligtedOptionId - TopVisibleEntry, FALSE);
/* Free allocated value string if needed */
if(Value != NULL)
{
BlFreeMemoryPool(Value);
}
/* Redraw new highlighted entry */
BlGetBootOptionValue(MenuEntry->Options, EditableOptions[HighligtedOptionId], &Value);
BlpDrawEditMenuEntry(&Handle, EditableOptions[HighligtedOptionId], Value, HighligtedOptionId - TopVisibleEntry, TRUE);
/* Free allocated value string if needed */
if(Value != NULL)
{
BlFreeMemoryPool(Value);
}
}
}
else if(Key.ScanCode == 0x09)
{
/* PageUp key pressed, go to top entry */
if(HighligtedOptionId != 0)
{
/* Highlight first entry */
HighligtedOptionId = 0;
TopVisibleEntry = 0;
RedrawEntries = TRUE;
}
}
else if(Key.ScanCode == 0x0A)
{
/* PageDown key pressed, go to bottom entry */
if(HighligtedOptionId != NumberOfOptions - 1)
{
/* Highlight last entry */
HighligtedOptionId = NumberOfOptions - 1;
TopVisibleEntry = (NumberOfOptions > VisibleEntries) ? (NumberOfOptions - VisibleEntries) : 0;
RedrawEntries = TRUE;
}
}
else if(Key.UnicodeChar == 0x02)
{
/* CTRL-B key pressed, boot the OS */
BlSetConsoleAttributes(Handle.DialogColor | Handle.TextColor);
BlClearConsoleLine(Handle.PosY + Handle.Height + 4);
BlSetCursorPosition(4, Handle.PosY + Handle.Height + 4);
BlConsolePrint(L"Booting '%S' now...\n", MenuEntry->FullName);
/* Boot the OS */
Status = BlInvokeBootProtocol(MenuEntry->ShortName, MenuEntry->Options);
if(Status != STATUS_SUCCESS)
{
/* Failed to boot OS */
BlDebugPrint(L"ERROR: Failed to boot '%S' (Status Code: 0x%zX)\n", MenuEntry->FullName, Status);
BlDisplayErrorDialog(L"XTLDR", L"Failed to startup the selected Operating System.");
RedrawEditMenu = TRUE;
}
/* Return to the edit menu */
continue;
}
else if(Key.ScanCode == 0x17)
{
/* ESC key pressed, exit edit menu */
break;
}
}
}
/** /**
* Displays a red error dialog box with the specified caption and message. * Displays a red error dialog box with the specified caption and message.
* *
@@ -440,12 +751,11 @@ XTCDECL
VOID VOID
BlDisplayInputDialog(IN PWCHAR Caption, BlDisplayInputDialog(IN PWCHAR Caption,
IN PWCHAR Message, IN PWCHAR Message,
IN PWCHAR *InputFieldText) IN OUT PWCHAR *InputFieldText)
{ {
SIZE_T InputFieldLength, TextCursorPosition, TextIndex, TextPosition; SIZE_T InputFieldLength, TextCursorPosition, TextIndex, TextPosition;
XTBL_DIALOG_HANDLE Handle; XTBL_DIALOG_HANDLE Handle;
PWCHAR InputFieldBuffer; PWCHAR InputFieldBuffer;
SIZE_T BufferLength;
EFI_INPUT_KEY Key; EFI_INPUT_KEY Key;
EFI_STATUS Status; EFI_STATUS Status;
UINT_PTR Index; UINT_PTR Index;
@@ -470,9 +780,11 @@ BlDisplayInputDialog(IN PWCHAR Caption,
Key.ScanCode = 0; Key.ScanCode = 0;
Key.UnicodeChar = 0; Key.UnicodeChar = 0;
/* Get initial input text length and allocate a buffer */ /* Determine input field length */
BufferLength = RtlWideStringLength(*InputFieldText, 0); InputFieldLength = RtlWideStringLength(*InputFieldText, 0);
Status = BlAllocateMemoryPool(BufferLength * sizeof(WCHAR), (PVOID *)&InputFieldBuffer);
/* Allocate a buffer for storing the input field text */
Status = BlAllocateMemoryPool(2048 * sizeof(WCHAR), (PVOID *)&InputFieldBuffer);
if(Status != STATUS_EFI_SUCCESS) if(Status != STATUS_EFI_SUCCESS)
{ {
/* Memory allocation failure, print error message and return */ /* Memory allocation failure, print error message and return */
@@ -482,15 +794,8 @@ BlDisplayInputDialog(IN PWCHAR Caption,
} }
/* Copy input text into edit buffer */ /* Copy input text into edit buffer */
RtlCopyMemory(InputFieldBuffer, *InputFieldText, BufferLength * sizeof(WCHAR)); RtlCopyMemory(InputFieldBuffer, *InputFieldText, InputFieldLength * sizeof(WCHAR));
InputFieldBuffer[BufferLength] = L'\0'; InputFieldBuffer[InputFieldLength] = L'\0';
/* Determine input field length */
InputFieldLength = BufferLength;
if(InputFieldLength > Handle.Width - 8)
{
InputFieldLength = Handle.Width - 8;
}
/* Start at first character */ /* Start at first character */
TextPosition = 0; TextPosition = 0;
@@ -502,7 +807,6 @@ BlDisplayInputDialog(IN PWCHAR Caption,
/* Wait for key press and read key stroke */ /* Wait for key press and read key stroke */
BlWaitForEfiEvent(1, &EfiSystemTable->ConIn->WaitForKey, &Index); BlWaitForEfiEvent(1, &EfiSystemTable->ConIn->WaitForKey, &Index);
BlReadKeyStroke(&Key); BlReadKeyStroke(&Key);
BlResetConsoleInputBuffer();
/* Check key press scan code */ /* Check key press scan code */
if(Key.ScanCode == 0x17) if(Key.ScanCode == 0x17)
@@ -553,12 +857,16 @@ BlDisplayInputDialog(IN PWCHAR Caption,
/* DELETE key pressed, delete character */ /* DELETE key pressed, delete character */
if(Handle.Attributes & XTBL_TUI_DIALOG_ACTIVE_INPUT) if(Handle.Attributes & XTBL_TUI_DIALOG_ACTIVE_INPUT)
{ {
/* Check if buffer is not empty */
if(InputFieldLength > 0 && TextPosition < InputFieldLength) if(InputFieldLength > 0 && TextPosition < InputFieldLength)
{ {
/* Delete character */
RtlMoveMemory(InputFieldBuffer + TextPosition, InputFieldBuffer + TextPosition + 1, RtlMoveMemory(InputFieldBuffer + TextPosition, InputFieldBuffer + TextPosition + 1,
(InputFieldLength - TextPosition) * sizeof(WCHAR)); (InputFieldLength - TextPosition) * sizeof(WCHAR));
/* Decrement length and null terminate string */
InputFieldLength--; InputFieldLength--;
InputFieldBuffer[InputFieldLength] = 0; InputFieldBuffer[InputFieldLength] = L'\0';
} }
} }
} }
@@ -567,13 +875,17 @@ BlDisplayInputDialog(IN PWCHAR Caption,
/* BACKSPACE key pressed, delete character */ /* BACKSPACE key pressed, delete character */
if(Handle.Attributes & XTBL_TUI_DIALOG_ACTIVE_INPUT) if(Handle.Attributes & XTBL_TUI_DIALOG_ACTIVE_INPUT)
{ {
/* Check if buffer is not empty */
if(InputFieldLength > 0 && TextPosition > 0 && TextPosition <= InputFieldLength) if(InputFieldLength > 0 && TextPosition > 0 && TextPosition <= InputFieldLength)
{ {
/* Move memory to overwrite the character to the left of the cursor */
RtlMoveMemory(InputFieldBuffer + TextPosition - 1, InputFieldBuffer + TextPosition,
(InputFieldLength - TextPosition + 1) * sizeof(WCHAR));
/* Decrement length, position and null terminate string */
TextPosition--; TextPosition--;
RtlMoveMemory(InputFieldBuffer + TextPosition, InputFieldBuffer + TextPosition + 1,
(InputFieldLength - TextPosition) * sizeof(WCHAR));
InputFieldLength--; InputFieldLength--;
InputFieldBuffer[InputFieldLength] = 0; InputFieldBuffer[InputFieldLength] = L'\0';
} }
} }
} }
@@ -588,15 +900,23 @@ BlDisplayInputDialog(IN PWCHAR Caption,
/* Other key pressed, add character to the buffer */ /* Other key pressed, add character to the buffer */
if(Handle.Attributes & XTBL_TUI_DIALOG_ACTIVE_INPUT && Key.UnicodeChar != 0) if(Handle.Attributes & XTBL_TUI_DIALOG_ACTIVE_INPUT && Key.UnicodeChar != 0)
{ {
RtlMoveMemory(InputFieldBuffer + TextPosition + 1, InputFieldBuffer + TextPosition, /* Check if buffer is full */
(InputFieldLength - TextPosition) * sizeof(WCHAR)); if(InputFieldLength < 2047)
InputFieldBuffer[TextPosition] = Key.UnicodeChar; {
TextPosition++; /* Insert character at current position */
InputFieldLength++; RtlMoveMemory(InputFieldBuffer + TextPosition + 1, InputFieldBuffer + TextPosition,
InputFieldBuffer[InputFieldLength] = 0; (InputFieldLength - TextPosition) * sizeof(WCHAR));
InputFieldBuffer[TextPosition] = Key.UnicodeChar;
/* Increment length, position and null terminate string */
TextPosition++;
InputFieldLength++;
InputFieldBuffer[InputFieldLength] = L'\0';
}
} }
} }
/* Calculate text index and cursor position */
if(TextPosition > (Handle.Width - 9)) if(TextPosition > (Handle.Width - 9))
{ {
TextIndex = TextPosition - (Handle.Width - 9); TextIndex = TextPosition - (Handle.Width - 9);
@@ -612,6 +932,7 @@ BlDisplayInputDialog(IN PWCHAR Caption,
BlpDrawDialogButton(&Handle); BlpDrawDialogButton(&Handle);
BlpDrawDialogInputField(&Handle, &InputFieldBuffer[TextIndex]); BlpDrawDialogInputField(&Handle, &InputFieldBuffer[TextIndex]);
/* Set cursor position if input field is active */
if(Handle.Attributes & XTBL_TUI_DIALOG_ACTIVE_INPUT) if(Handle.Attributes & XTBL_TUI_DIALOG_ACTIVE_INPUT)
{ {
BlSetCursorPosition(Handle.PosX + 4 + TextCursorPosition, Handle.PosY + Handle.Height - 4); BlSetCursorPosition(Handle.PosX + 4 + TextCursorPosition, Handle.PosY + Handle.Height - 4);
@@ -870,8 +1191,8 @@ BlpDrawBootMenu(OUT PXTBL_DIALOG_HANDLE Handle)
BlSetCursorPosition(0, Handle->PosY + Handle->Height); BlSetCursorPosition(0, Handle->PosY + Handle->Height);
BlSetConsoleAttributes(EFI_TEXT_BGCOLOR_BLACK | EFI_TEXT_FGCOLOR_LIGHTGRAY); BlSetConsoleAttributes(EFI_TEXT_BGCOLOR_BLACK | EFI_TEXT_FGCOLOR_LIGHTGRAY);
BlConsolePrint(L" Use cursors to change the selection. Press ENTER key to boot the chosen\n" BlConsolePrint(L" Use cursors to change the selection. Press ENTER key to boot the chosen\n"
" Operating System, 'e' to edit it before booting or 's' for XTLDR shell.\n" L" Operating System, 'e' to edit it before booting or 's' for XTLDR shell.\n"
" Additional help available after pressing F1 key."); L" Additional help available after pressing F1 key.");
} }
/** /**
@@ -1330,3 +1651,164 @@ BlpDrawDialogProgressBar(IN PXTBL_DIALOG_HANDLE Handle,
BlDisableConsoleCursor(); BlDisableConsoleCursor();
BlConsoleWrite(ProgressBar); BlConsoleWrite(ProgressBar);
} }
/**
* Draws a text-based boot edition menu.
*
* @param Handle
* Supplies a pointer to the edition menu handle.
*
* @return This function does not return any value.
*
* @since XT 1.0
*/
XTCDECL
VOID
BlpDrawEditMenu(OUT PXTBL_DIALOG_HANDLE Handle)
{
/* Query console screen resolution */
BlQueryConsoleMode(&Handle->ResX, &Handle->ResY);
/* Set boot menu parameters */
Handle->Attributes = 0;
Handle->DialogColor = EFI_TEXT_BGCOLOR_BLACK;
Handle->TextColor = EFI_TEXT_FGCOLOR_LIGHTGRAY;
Handle->PosX = 3;
Handle->PosY = 3;
Handle->Width = Handle->ResX - 6;
Handle->Height = Handle->ResY - 10;
/* Clear screen and disable cursor */
BlSetConsoleAttributes(Handle->DialogColor | Handle->TextColor);
BlClearConsoleScreen();
BlDisableConsoleCursor();
/* Check if debugging enabled */
if(DEBUG)
{
/* Print debug version of XTLDR banner */
BlSetCursorPosition((Handle->ResX - 44) / 2, 1);
BlConsolePrint(L"XTLDR Boot Loader v%d.%d (%s-%s)\n",
XTLDR_VERSION_MAJOR, XTLDR_VERSION_MINOR, XTOS_VERSION_DATE, XTOS_VERSION_HASH);
}
else
{
/* Print standard XTLDR banner */
BlSetCursorPosition((Handle->ResX - 22) / 2, 1);
BlConsolePrint(L"XTLDR Boot Loader v%d.%d\n", XTLDR_VERSION_MAJOR, XTLDR_VERSION_MINOR);
}
/* Draw empty dialog box for boot menu */
BlpDrawDialogBox(Handle, L"Edit Options", NULL);
/* Print help message below the edit menu */
BlSetCursorPosition(0, Handle->PosY + Handle->Height);
BlSetConsoleAttributes(EFI_TEXT_BGCOLOR_BLACK | EFI_TEXT_FGCOLOR_LIGHTGRAY);
BlConsolePrint(L" Use cursors to change the selection. Press ENTER key to edit the chosen\n"
L" option, ESC to return to the main boot menu or CTRL-B to boot.\n");
}
/**
* Draws edit menu entry at the specified position.
*
* @param Handle
* Supplies a pointer to the boot menu handle.
*
* @param OptionName
* Supplies a pointer to the buffer containing a part of the menu entry name (an option name).
*
* @param OptionValue
* Supplies a pointer to the buffer containing a part of the menu entry name (an option value).
*
* @param Position
* Specifies entry position on the list in the boot menu.
*
* @param Highlighted
* Specifies whether this entry should be highlighted or not.
*
* @return This routine does not return any value.
*
* @since XT 1.0
*/
XTCDECL
EFI_STATUS
BlpDrawEditMenuEntry(IN PXTBL_DIALOG_HANDLE Handle,
IN PWCHAR OptionName,
IN PWCHAR OptionValue,
IN UINT Position,
IN BOOLEAN Highlighted)
{
BOOLEAN Allocation;
PWCHAR DisplayValue, ShortValue;
UINT Index;
ULONG OptionNameLength, OptionValueLength, OptionWidth;
EFI_STATUS Status;
/* Assume no allocation was made */
Allocation = FALSE;
/* Set display value depending on input */
DisplayValue = (OptionValue != NULL) ? OptionValue : L"";
/* Determine lengths */
OptionNameLength = RtlWideStringLength(OptionName, 0);
OptionValueLength = RtlWideStringLength(DisplayValue, 0);
OptionWidth = Handle->Width - 4 - (OptionNameLength + 2);
/* Check if value needs to be truncated */
if(OptionValueLength > OptionWidth)
{
/* Allocate buffer for new, shortened value */
Status = BlAllocateMemoryPool((OptionWidth + 1) * sizeof(WCHAR), (PVOID *)&ShortValue);
if(Status != STATUS_EFI_SUCCESS)
{
/* Memory allocation failure, print debug message and return */
BlDebugPrint(L"ERROR: Memory allocation failure (Status Code: 0x%zX)\n", Status);
return Status;
}
/* Copy a desired value length into the allocated buffer and append "..." */
RtlCopyMemory(ShortValue, DisplayValue, (OptionWidth - 3) * sizeof(WCHAR));
RtlCopyMemory(ShortValue + OptionWidth - 3, L"...", 3 * sizeof(WCHAR));
ShortValue[OptionWidth] = L'\0';
/* Mark that allocation was made and set new display value */
Allocation = TRUE;
DisplayValue = ShortValue;
}
/* Move cursor to the right position */
BlSetCursorPosition(5, 4 + Position);
/* Check whether this entry should be highlighted */
if(Highlighted)
{
/* Highlight this entry */
BlSetConsoleAttributes(EFI_TEXT_BGCOLOR_LIGHTGRAY | EFI_TEXT_FGCOLOR_BLACK);
}
else
{
/* Set default colors */
BlSetConsoleAttributes(EFI_TEXT_BGCOLOR_BLACK | EFI_TEXT_FGCOLOR_LIGHTGRAY);
}
/* Clear menu entry */
for(Index = 0; Index < Handle->Width - 4; Index++)
{
BlConsolePrint(L" ");
}
/* Print menu entry */
BlSetCursorPosition(5, 4 + Position);
BlConsolePrint(L"%S: %S", OptionName, DisplayValue);
/* Check if allocation was made */
if(Allocation)
{
/* Free allocated memory */
BlFreeMemoryPool(DisplayValue);
}
/* Return success */
return STATUS_EFI_SUCCESS;
}

View File

@@ -4,6 +4,7 @@
* FILE: xtldr/volume.c * FILE: xtldr/volume.c
* DESCRIPTION: XTLDR volume support * DESCRIPTION: XTLDR volume support
* DEVELOPERS: Rafal Kupiec <belliash@codingworkshop.eu.org> * DEVELOPERS: Rafal Kupiec <belliash@codingworkshop.eu.org>
* Aiken Harris <harraiken91@gmail.com>
*/ */
#include <xtldr.h> #include <xtldr.h>
@@ -47,7 +48,11 @@ XTCDECL
EFI_STATUS EFI_STATUS
BlEnumerateBlockDevices() BlEnumerateBlockDevices()
{ {
PEFI_DEVICE_PATH_PROTOCOL LastNode = NULL; EFI_GUID LoadedImageProtocolGuid = EFI_LOADED_IMAGE_PROTOCOL_GUID;
EFI_GUID BlockIoGuid = EFI_BLOCK_IO_PROTOCOL_GUID;
EFI_HANDLE BootDeviceHandle = NULL, DeviceHandle = NULL;
EFI_LOADED_IMAGE_PROTOCOL* LoadedImage;
PEFI_DEVICE_PATH_PROTOCOL DevicePath = NULL, LastNode = NULL;
PEFI_BLOCK_DEVICE_DATA ParentNode = NULL; PEFI_BLOCK_DEVICE_DATA ParentNode = NULL;
PEFI_BLOCK_DEVICE_DATA BlockDeviceData; PEFI_BLOCK_DEVICE_DATA BlockDeviceData;
PEFI_BLOCK_DEVICE BlockDevice; PEFI_BLOCK_DEVICE BlockDevice;
@@ -62,6 +67,18 @@ BlEnumerateBlockDevices()
USHORT DriveType; USHORT DriveType;
ULONG CDCount = 0, FDCount = 0, HDCount = 0, RDCount = 0; ULONG CDCount = 0, FDCount = 0, HDCount = 0, RDCount = 0;
/* Get the device handle of the image that is running */
Status = EfiSystemTable->BootServices->HandleProtocol(EfiImageHandle, &LoadedImageProtocolGuid, (VOID**)&LoadedImage);
if(Status != STATUS_EFI_SUCCESS)
{
/* Failed to get boot device handle */
BlDebugPrint(L"ERROR: Failed to get boot device handle (Status Code: 0x%zX)\n", Status);
return Status;
}
/* Save the boot device handle */
BootDeviceHandle = LoadedImage->DeviceHandle;
/* Initialize list entries */ /* Initialize list entries */
RtlInitializeListHead(&BlockDevices); RtlInitializeListHead(&BlockDevices);
RtlInitializeListHead(&EfiBlockDevices); RtlInitializeListHead(&EfiBlockDevices);
@@ -78,21 +95,42 @@ BlEnumerateBlockDevices()
ListEntry = BlockDevices.Flink; ListEntry = BlockDevices.Flink;
while(ListEntry != &BlockDevices) while(ListEntry != &BlockDevices)
{ {
/* Take block device from the list */ /* Get data for the next discovered device. */
BlockDeviceData = CONTAIN_RECORD(ListEntry, EFI_BLOCK_DEVICE_DATA, ListEntry); BlockDeviceData = CONTAIN_RECORD(ListEntry, EFI_BLOCK_DEVICE_DATA, ListEntry);
PartitionGuid = NULL;
/* Find last node */ /* Find last node */
Status = BlpFindLastBlockDeviceNode(BlockDeviceData->DevicePath, &LastNode); Status = BlpFindLastBlockDeviceNode(BlockDeviceData->DevicePath, &LastNode);
if(Status != STATUS_EFI_SUCCESS) if(Status != STATUS_EFI_SUCCESS)
{ {
/* Skip this device if its last node cannot be found, as it is required for classification */
BlDebugPrint(L"WARNING: Block device last node not found\n"); BlDebugPrint(L"WARNING: Block device last node not found\n");
ListEntry = ListEntry->Flink; ListEntry = ListEntry->Flink;
continue; continue;
} }
/* Set drive type to 'unknown' by default */ /* Initialize drive type before attempting to classify the device */
DriveType = XTBL_BOOT_DEVICE_UNKNOWN; DriveType = XTBL_BOOT_DEVICE_UNKNOWN;
/* Locate the parent for this block device to ensure it is not an orphaned entry */
if(!BlpFindParentBlockDevice(&BlockDevices, BlockDeviceData, &ParentNode))
{
/* Orphaned device found. Log a warning and skip it as it cannot be properly classified */
BlDebugPrint(L"WARNING: No parent device found, skipping orphaned media device path\n");
ListEntry = ListEntry->Flink;
continue;
}
/* Verify that media information is available, as some devices may not report it */
if(!BlockDeviceData->BlockIo->Media)
{
/* The device is unusable without media info, log a warning and skip it */
BlDebugPrint(L"WARNING: Block device is missing media information\n");
ListEntry = ListEntry->Flink;
continue;
}
Media = BlockDeviceData->BlockIo->Media;
/* Check last node type */ /* Check last node type */
if(LastNode->Type == EFI_ACPI_DEVICE_PATH && LastNode->SubType == EFI_ACPI_DP) if(LastNode->Type == EFI_ACPI_DEVICE_PATH && LastNode->SubType == EFI_ACPI_DP)
{ {
@@ -101,65 +139,73 @@ BlEnumerateBlockDevices()
if(AcpiDevice->HID == 0x60441D0 || AcpiDevice->HID == 0x70041D0 || AcpiDevice->HID == 0x70141D1) if(AcpiDevice->HID == 0x60441D0 || AcpiDevice->HID == 0x70041D0 || AcpiDevice->HID == 0x70141D1)
{ {
/* Floppy drive found */ /* Floppy drive found */
Media = BlockDeviceData->BlockIo->Media;
DriveType = XTBL_BOOT_DEVICE_FLOPPY; DriveType = XTBL_BOOT_DEVICE_FLOPPY;
DriveNumber = FDCount++; DriveNumber = FDCount++;
PartitionNumber = 0; PartitionNumber = 0;
/* Print debug message */ /* Print debug message */
BlDebugPrint(L"Found Floppy Disk (DiskNumber: %lu, MediaPresent: %u, RO: %u)\n", BlDebugPrint(L"Found Floppy Disk (DiskNumber: %lu, MediaPresent: %u, RO: %u)\n",
DriveNumber, Media->MediaPresent, Media->ReadOnly); DriveNumber, Media->MediaPresent, Media->ReadOnly);
} }
} }
else if(LastNode->Type == EFI_MEDIA_DEVICE_PATH) else if((LastNode->Type == EFI_MEDIA_DEVICE_PATH && LastNode->SubType == EFI_MEDIA_CDROM_DP) ||
(LastNode->Type == EFI_MESSAGING_DEVICE_PATH &&
(LastNode->SubType == EFI_MESSAGING_ATAPI_DP || LastNode->SubType == EFI_MESSAGING_SATA_DP) &&
Media->MediaPresent && Media->RemovableMedia))
{ {
/* Media device path found */ /* Optical drive found */
if(LastNode->SubType == EFI_MEDIA_CDROM_DP) DriveType = XTBL_BOOT_DEVICE_CDROM;
{ DriveNumber = CDCount++;
/* Optical drive found */ PartitionNumber = 0;
Media = BlockDeviceData->BlockIo->Media;
DriveType = XTBL_BOOT_DEVICE_CDROM;
DriveNumber = CDCount++;
PartitionNumber = 0;
/* Print debug message */ /* Print debug message */
BlDebugPrint(L"Found CD-ROM drive (DriveNumber: %lu, MediaPresent: %u, RemovableMedia: %u, RO: %u)\n", BlDebugPrint(L"Found CD-ROM drive (DriveNumber: %lu, MediaPresent: %u, RemovableMedia: %u, RO: %u)\n",
DriveNumber, Media->MediaPresent, Media->RemovableMedia, Media->ReadOnly); DriveNumber, Media->MediaPresent, Media->RemovableMedia, Media->ReadOnly);
} }
else if(LastNode->SubType == EFI_MEDIA_HARDDRIVE_DP) else if(LastNode->Type == EFI_MEDIA_DEVICE_PATH && LastNode->SubType == EFI_MEDIA_HARDDRIVE_DP)
{ {
/* Hard disk partition found */ /* Hard disk partition found */
Media = BlockDeviceData->BlockIo->Media; HDPath = (PEFI_HARDDRIVE_DEVICE_PATH)LastNode;
HDPath = (PEFI_HARDDRIVE_DEVICE_PATH)LastNode; DriveType = XTBL_BOOT_DEVICE_HARDDISK;
DriveType = XTBL_BOOT_DEVICE_HARDDISK; DriveNumber = (HDPath->PartitionNumber == 1) ? HDCount++ : HDCount - 1;
DriveNumber = (HDPath->PartitionNumber == 1) ? HDCount++ : HDCount - 1; PartitionNumber = HDPath->PartitionNumber;
PartitionNumber = HDPath->PartitionNumber; PartitionGuid = (PEFI_GUID)HDPath->Signature;
PartitionGuid = (PEFI_GUID)HDPath->Signature;
/* Print debug message */ /* Check if this is the EFI System Partition (ESP) */
BlDebugPrint(L"Found Hard Disk partition (DiskNumber: %lu, PartNumber: %lu, " if(BootDeviceHandle != NULL)
L"MBRType: %u, GUID: {%V}, PartSize: %uB)\n",
DriveNumber, PartitionNumber, HDPath->MBRType,
PartitionGuid, HDPath->PartitionSize * Media->BlockSize);
}
else if(LastNode->SubType == EFI_MEDIA_RAMDISK_DP)
{ {
/* RAM disk found */ /* Allocate memory for device path */
Media = BlockDeviceData->BlockIo->Media; DevicePath = BlpDuplicateDevicePath(BlockDeviceData->DevicePath);
DriveType = XTBL_BOOT_DEVICE_RAMDISK; if(DevicePath != NULL)
DriveNumber = RDCount++; {
PartitionNumber = 0; /* Check if this is the boot device */
Status = EfiSystemTable->BootServices->LocateDevicePath(&BlockIoGuid, &DevicePath,
/* Print debug message */ &DeviceHandle);
BlDebugPrint(L"Found RAM Disk (DiskNumber: %lu, MediaPresent: %u)\n", if(Status == STATUS_EFI_SUCCESS && DeviceHandle == BootDeviceHandle)
DriveNumber, Media->MediaPresent); {
/* Mark partition as ESP */
DriveType |= XTBL_BOOT_DEVICE_ESP;
}
}
} }
if(!BlpFindParentBlockDevice(&BlockDevices, BlockDeviceData, ParentNode)) /* Print debug message */
{ BlDebugPrint(L"Found Hard Disk partition (DiskNumber: %lu, PartNumber: %lu, "
BlDebugPrint(L"WARNING: No parent device found, skipping orphaned media device path\n"); L"MBRType: %u, GUID: {%V}, PartSize: %lluB) %S\n",
continue; DriveNumber, PartitionNumber, HDPath->MBRType,
} PartitionGuid, HDPath->PartitionSize * Media->BlockSize,
(DriveType & XTBL_BOOT_DEVICE_ESP) ? L"(ESP)" : L"");
}
else if(LastNode->Type == EFI_MEDIA_DEVICE_PATH && LastNode->SubType == EFI_MEDIA_RAMDISK_DP)
{
/* RAM disk found */
DriveType = XTBL_BOOT_DEVICE_RAMDISK;
DriveNumber = RDCount++;
PartitionNumber = 0;
/* Print debug message */
BlDebugPrint(L"Found RAM Disk (DiskNumber: %lu, MediaPresent: %u)\n",
DriveNumber, Media->MediaPresent);
} }
/* Make sure the device found has valid type set */ /* Make sure the device found has valid type set */
@@ -418,12 +464,26 @@ BlGetVolumeDevicePath(IN PWCHAR SystemPath,
{ {
/* Check if this is the volume we are looking for */ /* Check if this is the volume we are looking for */
Device = CONTAIN_RECORD(ListEntry, EFI_BLOCK_DEVICE, ListEntry); Device = CONTAIN_RECORD(ListEntry, EFI_BLOCK_DEVICE, ListEntry);
if((Device->DriveType == DriveType && Device->DriveNumber == DriveNumber && if(DriveType == XTBL_BOOT_DEVICE_ESP)
Device->PartitionNumber == PartNumber))
{ {
/* Found volume */ /* ESP requested, verify if flag is set for this device */
*DevicePath = Device->DevicePath; if((Device->DriveType & XTBL_BOOT_DEVICE_ESP) != 0)
break; {
/* Found volume */
*DevicePath = Device->DevicePath;
break;
}
}
else
{
if(((Device->DriveType & DriveType) == DriveType) &&
(Device->DriveNumber == DriveNumber) &&
(Device->PartitionNumber == PartNumber))
{
/* Found volume */
*DevicePath = Device->DevicePath;
break;
}
} }
ListEntry = ListEntry->Flink; ListEntry = ListEntry->Flink;
} }
@@ -431,9 +491,9 @@ BlGetVolumeDevicePath(IN PWCHAR SystemPath,
/* Check if volume was found */ /* Check if volume was found */
if(*DevicePath == NULL) if(*DevicePath == NULL)
{ {
/* Failed to find volume */ /* Volume not found */
BlDebugPrint(L"ERROR: Volume (DriveType: %u, DriveNumber: %lu, PartNumber: %lu) not found\n", BlDebugPrint(L"ERROR: Volume (DriveType: %u, DriveNumber: %lu, PartNumber: %lu) not found\n",
DriveType, DriveNumber, PartNumber); DriveType, DriveNumber, PartNumber);
return STATUS_EFI_NOT_FOUND; return STATUS_EFI_NOT_FOUND;
} }
@@ -606,7 +666,7 @@ BlReadFile(IN PEFI_FILE_HANDLE DirHandle,
Pages = EFI_SIZE_TO_PAGES(FileInfo->FileSize); Pages = EFI_SIZE_TO_PAGES(FileInfo->FileSize);
/* Allocate pages */ /* Allocate pages */
Status = BlAllocateMemoryPages(Pages, &Address); Status = BlAllocateMemoryPages(AllocateAnyPages, Pages, &Address);
if(Status != STATUS_EFI_SUCCESS) if(Status != STATUS_EFI_SUCCESS)
{ {
/* Pages allocation failure */ /* Pages allocation failure */
@@ -776,6 +836,12 @@ BlpDissectVolumeArcPath(IN PWCHAR SystemPath,
ArcLength = 10; ArcLength = 10;
*DriveType = XTBL_BOOT_DEVICE_RAMDISK; *DriveType = XTBL_BOOT_DEVICE_RAMDISK;
} }
else if(RtlCompareWideStringInsensitive(SystemPath, L"multi(0)esp(0)", 0) == 0)
{
/* This is ESP */
ArcLength = 14;
*DriveType = XTBL_BOOT_DEVICE_ESP;
}
else if(RtlCompareWideStringInsensitive(SystemPath, L"multi(0)disk(0)", 0) == 0) else if(RtlCompareWideStringInsensitive(SystemPath, L"multi(0)disk(0)", 0) == 0)
{ {
/* This is a multi-disk port */ /* This is a multi-disk port */
@@ -917,17 +983,25 @@ BlpDuplicateDevicePath(IN PEFI_DEVICE_PATH_PROTOCOL DevicePath)
EFI_STATUS Status; EFI_STATUS Status;
UINT Length = 0; UINT Length = 0;
/* Check if the input device path is NULL */
if(!DevicePath)
{
/* Nothing to duplicate */
return NULL;
}
/* Start iterating from the beginning of the device path */
DevicePathNode = DevicePath; DevicePathNode = DevicePath;
/* Get the device path length */ /* Get the device path length */
while(TRUE) while(TRUE)
{ {
Length += *(PUSHORT)DevicePath->Length; Length += *(PUSHORT)DevicePathNode->Length;
if(DevicePathNode->Type == EFI_END_DEVICE_PATH) if(DevicePathNode->Type == EFI_END_DEVICE_PATH)
{ {
break; break;
} }
DevicePathNode = (PEFI_DEVICE_PATH_PROTOCOL)((PUCHAR)DevicePathNode + *(PUSHORT)DevicePath->Length); DevicePathNode = (PEFI_DEVICE_PATH_PROTOCOL)((PUCHAR)DevicePathNode + *(PUSHORT)DevicePathNode->Length);
} }
/* Check length */ /* Check length */
@@ -1016,7 +1090,7 @@ XTCDECL
BOOLEAN BOOLEAN
BlpFindParentBlockDevice(IN PLIST_ENTRY BlockDevices, BlpFindParentBlockDevice(IN PLIST_ENTRY BlockDevices,
IN PEFI_BLOCK_DEVICE_DATA ChildNode, IN PEFI_BLOCK_DEVICE_DATA ChildNode,
OUT PEFI_BLOCK_DEVICE_DATA ParentNode) OUT PEFI_BLOCK_DEVICE_DATA *ParentNode)
{ {
PEFI_DEVICE_PATH_PROTOCOL ChildDevicePath, ParentDevicePath; PEFI_DEVICE_PATH_PROTOCOL ChildDevicePath, ParentDevicePath;
PEFI_BLOCK_DEVICE_DATA BlockDeviceData; PEFI_BLOCK_DEVICE_DATA BlockDeviceData;
@@ -1029,6 +1103,14 @@ BlpFindParentBlockDevice(IN PLIST_ENTRY BlockDevices,
/* Take block device from the list */ /* Take block device from the list */
BlockDeviceData = CONTAIN_RECORD(ListEntry, EFI_BLOCK_DEVICE_DATA, ListEntry); BlockDeviceData = CONTAIN_RECORD(ListEntry, EFI_BLOCK_DEVICE_DATA, ListEntry);
/* A device cannot be its own parent */
if (BlockDeviceData == ChildNode)
{
/* Move to the next device */
ListEntry = ListEntry->Flink;
continue;
}
ChildDevicePath = ChildNode->DevicePath; ChildDevicePath = ChildNode->DevicePath;
ParentDevicePath = BlockDeviceData->DevicePath; ParentDevicePath = BlockDeviceData->DevicePath;
@@ -1039,7 +1121,7 @@ BlpFindParentBlockDevice(IN PLIST_ENTRY BlockDevices,
if(ParentDevicePath->Type == EFI_END_DEVICE_PATH) if(ParentDevicePath->Type == EFI_END_DEVICE_PATH)
{ {
/* Parent device is a match */ /* Parent device is a match */
ParentNode = BlockDeviceData; *ParentNode = BlockDeviceData;
return TRUE; return TRUE;
} }
@@ -1047,10 +1129,11 @@ BlpFindParentBlockDevice(IN PLIST_ENTRY BlockDevices,
ChildLength = *(PUSHORT)ChildDevicePath->Length; ChildLength = *(PUSHORT)ChildDevicePath->Length;
ParentLength = *(PUSHORT)ParentDevicePath->Length; ParentLength = *(PUSHORT)ParentDevicePath->Length;
/* Check if lengths match */ /* Check if nodes match */
if(ChildLength != ParentLength) if((ChildLength != ParentLength) ||
(RtlCompareMemory(ChildDevicePath, ParentDevicePath, ParentLength) != ParentLength))
{ {
/* Lengths do not match, this is not a valid parent */ /* Nodes do not match, this is not a valid parent */
break; break;
} }

View File

@@ -90,16 +90,17 @@ BlInitializeBootLoader()
*/ */
XTCDECL XTCDECL
EFI_STATUS EFI_STATUS
BlInitializeBootMenuList(OUT PXTBL_BOOTMENU_ITEM *MenuEntries, BlInitializeBootMenuList(IN ULONG MaxNameLength,
OUT PXTBL_BOOTMENU_ITEM *MenuEntries,
OUT PULONG EntriesCount, OUT PULONG EntriesCount,
OUT PULONG DefaultId) OUT PULONG DefaultId)
{ {
EFI_GUID VendorGuid = XT_BOOT_LOADER_PROTOCOL_GUID; EFI_GUID VendorGuid = XT_BOOT_LOADER_PROTOCOL_GUID;
PWCHAR DefaultMenuEntry, LastBooted, MenuEntryName; PWCHAR DefaultMenuEntry, LastBooted, MenuEntryName, VisibleName;
PLIST_ENTRY MenuEntrySectionList, MenuEntryList; PLIST_ENTRY MenuEntrySectionList, MenuEntryList;
PXTBL_CONFIG_SECTION MenuEntrySection; PXTBL_CONFIG_SECTION MenuEntrySection;
PXTBL_CONFIG_ENTRY MenuEntryOption; PXTBL_CONFIG_ENTRY MenuEntryOption;
ULONG DefaultOS, NumberOfEntries; ULONG DefaultOS, NameLength,NumberOfEntries;
PXTBL_BOOTMENU_ITEM OsList; PXTBL_BOOTMENU_ITEM OsList;
EFI_STATUS Status; EFI_STATUS Status;
@@ -108,7 +109,7 @@ BlInitializeBootMenuList(OUT PXTBL_BOOTMENU_ITEM *MenuEntries,
NumberOfEntries = 0; NumberOfEntries = 0;
/* Get default menu entry from configuration */ /* Get default menu entry from configuration */
DefaultMenuEntry = BlGetConfigValue(L"DEFAULT"); BlGetConfigValue(L"DEFAULT", &DefaultMenuEntry);
/* Check if configuration allows to use last booted OS */ /* Check if configuration allows to use last booted OS */
if(BlGetConfigBooleanValue(L"KEEPLASTBOOT")) if(BlGetConfigBooleanValue(L"KEEPLASTBOOT"))
@@ -151,7 +152,8 @@ BlInitializeBootMenuList(OUT PXTBL_BOOTMENU_ITEM *MenuEntries,
MenuEntrySection = CONTAIN_RECORD(MenuEntrySectionList, XTBL_CONFIG_SECTION, Flink); MenuEntrySection = CONTAIN_RECORD(MenuEntrySectionList, XTBL_CONFIG_SECTION, Flink);
/* Check if this is the default menu entry */ /* Check if this is the default menu entry */
if(RtlCompareWideStringInsensitive(MenuEntrySection->SectionName, DefaultMenuEntry, 0) == 0) if((RtlWideStringLength(MenuEntrySection->SectionName, 0) == RtlWideStringLength(DefaultMenuEntry, 0)) &&
(RtlCompareWideStringInsensitive(MenuEntrySection->SectionName, DefaultMenuEntry, 0) == 0))
{ {
/* Set default OS ID */ /* Set default OS ID */
DefaultOS = NumberOfEntries; DefaultOS = NumberOfEntries;
@@ -176,10 +178,36 @@ BlInitializeBootMenuList(OUT PXTBL_BOOTMENU_ITEM *MenuEntries,
} }
/* Add OS to the boot menu list */ /* Add OS to the boot menu list */
OsList[NumberOfEntries].EntryName = MenuEntryName; OsList[NumberOfEntries].FullName = MenuEntryName;
OsList[NumberOfEntries].ShortName = MenuEntrySection->SectionName; OsList[NumberOfEntries].ShortName = MenuEntrySection->SectionName;
OsList[NumberOfEntries].Options = &MenuEntrySection->Options; OsList[NumberOfEntries].Options = &MenuEntrySection->Options;
/* Check if the menu entry name fits the maximum length */
NameLength = RtlWideStringLength(MenuEntryName, 0);
if(NameLength > MaxNameLength)
{
/* Menu entry name is too long, allocate memory for shorter name visible in the boot menu */
Status = BlAllocateMemoryPool((MaxNameLength + 1) * sizeof(WCHAR), (PVOID*)&VisibleName);
if(Status != STATUS_EFI_SUCCESS)
{
/* Memory allocation failure */
return STATUS_EFI_OUT_OF_RESOURCES;
}
/* Copy shorter name and append "..." at the end */
RtlCopyMemory(VisibleName, MenuEntryName, (MaxNameLength - 3) * sizeof(WCHAR));
RtlCopyMemory(VisibleName + MaxNameLength - 3, L"...", 3 * sizeof(WCHAR));
VisibleName[MaxNameLength] = L'\0';
/* Set visible menu entry name */
OsList[NumberOfEntries].EntryName = VisibleName;
}
else
{
/* Menu entry name fits the maximum length, use it as is */
OsList[NumberOfEntries].EntryName = MenuEntryName;
}
/* Get next menu entry */ /* Get next menu entry */
MenuEntrySectionList = MenuEntrySectionList->Flink; MenuEntrySectionList = MenuEntrySectionList->Flink;
NumberOfEntries++; NumberOfEntries++;
@@ -363,6 +391,7 @@ EFI_STATUS
BlStartXtLoader(IN EFI_HANDLE ImageHandle, BlStartXtLoader(IN EFI_HANDLE ImageHandle,
IN PEFI_SYSTEM_TABLE SystemTable) IN PEFI_SYSTEM_TABLE SystemTable)
{ {
PWCHAR Modules;
EFI_STATUS Status; EFI_STATUS Status;
/* Set the system table and image handle */ /* Set the system table and image handle */
@@ -427,8 +456,9 @@ BlStartXtLoader(IN EFI_HANDLE ImageHandle,
return Status; return Status;
} }
/* Load boot loader modules */ /* Load all necessary modules */
Status = BlLoadModules(BlGetConfigValue(L"MODULES")); BlGetConfigValue(L"MODULES", &Modules);
Status = BlLoadModules(Modules);
if(Status != STATUS_EFI_SUCCESS) if(Status != STATUS_EFI_SUCCESS)
{ {
/* Failed to load modules */ /* Failed to load modules */

View File

@@ -9,7 +9,8 @@ include_directories(
# Specify list of library source code files # Specify list of library source code files
list(APPEND LIBXTOS_SOURCE list(APPEND LIBXTOS_SOURCE
${XTOSKRNL_SOURCE_DIR}/ar/${ARCH}/cpufunc.c ${XTOSKRNL_SOURCE_DIR}/ar/${ARCH}/boot.S
${XTOSKRNL_SOURCE_DIR}/ar/${ARCH}/cpufunc.cc
${XTOSKRNL_SOURCE_DIR}/hl/cport.c ${XTOSKRNL_SOURCE_DIR}/hl/cport.c
${XTOSKRNL_SOURCE_DIR}/hl/${ARCH}/ioport.c ${XTOSKRNL_SOURCE_DIR}/hl/${ARCH}/ioport.c
${XTOSKRNL_SOURCE_DIR}/rtl/globals.c ${XTOSKRNL_SOURCE_DIR}/rtl/globals.c
@@ -23,11 +24,13 @@ list(APPEND LIBXTOS_SOURCE
# Specify list of kernel source code files # Specify list of kernel source code files
list(APPEND XTOSKRNL_SOURCE list(APPEND XTOSKRNL_SOURCE
${XTOSKRNL_SOURCE_DIR}/ar/${ARCH}/archsup.S ${XTOSKRNL_SOURCE_DIR}/ar/${ARCH}/archsup.S
${XTOSKRNL_SOURCE_DIR}/ar/${ARCH}/cpufunc.c ${XTOSKRNL_SOURCE_DIR}/ar/${ARCH}/boot.S
${XTOSKRNL_SOURCE_DIR}/ar/${ARCH}/globals.c ${XTOSKRNL_SOURCE_DIR}/ar/${ARCH}/cpufunc.cc
${XTOSKRNL_SOURCE_DIR}/ar/${ARCH}/procsup.c ${XTOSKRNL_SOURCE_DIR}/ar/${ARCH}/data.cc
${XTOSKRNL_SOURCE_DIR}/ar/${ARCH}/traps.c ${XTOSKRNL_SOURCE_DIR}/ar/${ARCH}/procsup.cc
${XTOSKRNL_SOURCE_DIR}/ex/rundown.c ${XTOSKRNL_SOURCE_DIR}/ar/${ARCH}/traps.cc
${XTOSKRNL_SOURCE_DIR}/ex/exports.cc
${XTOSKRNL_SOURCE_DIR}/ex/rundown.cc
${XTOSKRNL_SOURCE_DIR}/hl/acpi.c ${XTOSKRNL_SOURCE_DIR}/hl/acpi.c
${XTOSKRNL_SOURCE_DIR}/hl/cport.c ${XTOSKRNL_SOURCE_DIR}/hl/cport.c
${XTOSKRNL_SOURCE_DIR}/hl/fbdev.c ${XTOSKRNL_SOURCE_DIR}/hl/fbdev.c
@@ -37,31 +40,38 @@ list(APPEND XTOSKRNL_SOURCE
${XTOSKRNL_SOURCE_DIR}/hl/${ARCH}/pic.c ${XTOSKRNL_SOURCE_DIR}/hl/${ARCH}/pic.c
${XTOSKRNL_SOURCE_DIR}/hl/${ARCH}/ioport.c ${XTOSKRNL_SOURCE_DIR}/hl/${ARCH}/ioport.c
${XTOSKRNL_SOURCE_DIR}/hl/${ARCH}/runlevel.c ${XTOSKRNL_SOURCE_DIR}/hl/${ARCH}/runlevel.c
${XTOSKRNL_SOURCE_DIR}/ke/apc.c ${XTOSKRNL_SOURCE_DIR}/kd/dbginit.c
${XTOSKRNL_SOURCE_DIR}/ke/dpc.c ${XTOSKRNL_SOURCE_DIR}/kd/dbgio.c
${XTOSKRNL_SOURCE_DIR}/ke/event.c ${XTOSKRNL_SOURCE_DIR}/kd/globals.c
${XTOSKRNL_SOURCE_DIR}/ke/globals.c ${XTOSKRNL_SOURCE_DIR}/ke/${ARCH}/irq.cc
${XTOSKRNL_SOURCE_DIR}/ke/kprocess.c ${XTOSKRNL_SOURCE_DIR}/ke/${ARCH}/krnlinit.cc
${XTOSKRNL_SOURCE_DIR}/ke/krnlinit.c ${XTOSKRNL_SOURCE_DIR}/ke/${ARCH}/kthread.cc
${XTOSKRNL_SOURCE_DIR}/ke/kthread.c ${XTOSKRNL_SOURCE_DIR}/ke/${ARCH}/proc.cc
${XTOSKRNL_SOURCE_DIR}/ke/kubsan.c ${XTOSKRNL_SOURCE_DIR}/ke/apc.cc
${XTOSKRNL_SOURCE_DIR}/ke/panic.c ${XTOSKRNL_SOURCE_DIR}/ke/bootinfo.cc
${XTOSKRNL_SOURCE_DIR}/ke/runlevel.c ${XTOSKRNL_SOURCE_DIR}/ke/crash.cc
${XTOSKRNL_SOURCE_DIR}/ke/semphore.c ${XTOSKRNL_SOURCE_DIR}/ke/data.cc
${XTOSKRNL_SOURCE_DIR}/ke/spinlock.c ${XTOSKRNL_SOURCE_DIR}/ke/dpc.cc
${XTOSKRNL_SOURCE_DIR}/ke/sysres.c ${XTOSKRNL_SOURCE_DIR}/ke/event.cc
${XTOSKRNL_SOURCE_DIR}/ke/timer.c ${XTOSKRNL_SOURCE_DIR}/ke/exports.cc
${XTOSKRNL_SOURCE_DIR}/ke/${ARCH}/irqs.c ${XTOSKRNL_SOURCE_DIR}/ke/kprocess.cc
${XTOSKRNL_SOURCE_DIR}/ke/${ARCH}/krnlinit.c ${XTOSKRNL_SOURCE_DIR}/ke/krnlinit.cc
${XTOSKRNL_SOURCE_DIR}/ke/${ARCH}/kthread.c ${XTOSKRNL_SOURCE_DIR}/ke/kthread.cc
${XTOSKRNL_SOURCE_DIR}/ke/${ARCH}/proc.c ${XTOSKRNL_SOURCE_DIR}/ke/kubsan.cc
${XTOSKRNL_SOURCE_DIR}/ke/runlevel.cc
${XTOSKRNL_SOURCE_DIR}/ke/semphore.cc
${XTOSKRNL_SOURCE_DIR}/ke/spinlock.cc
${XTOSKRNL_SOURCE_DIR}/ke/sysres.cc
${XTOSKRNL_SOURCE_DIR}/ke/timer.cc
${XTOSKRNL_SOURCE_DIR}/mm/globals.c ${XTOSKRNL_SOURCE_DIR}/mm/globals.c
${XTOSKRNL_SOURCE_DIR}/mm/hlpool.c ${XTOSKRNL_SOURCE_DIR}/mm/hlpool.c
${XTOSKRNL_SOURCE_DIR}/mm/init.c ${XTOSKRNL_SOURCE_DIR}/mm/init.c
${XTOSKRNL_SOURCE_DIR}/mm/kpools.c ${XTOSKRNL_SOURCE_DIR}/mm/kpools.c
${XTOSKRNL_SOURCE_DIR}/mm/pages.c ${XTOSKRNL_SOURCE_DIR}/mm/pages.c
${XTOSKRNL_SOURCE_DIR}/mm/${ARCH}/globals.c
${XTOSKRNL_SOURCE_DIR}/mm/${ARCH}/init.c ${XTOSKRNL_SOURCE_DIR}/mm/${ARCH}/init.c
${XTOSKRNL_SOURCE_DIR}/mm/${ARCH}/pages.c ${XTOSKRNL_SOURCE_DIR}/mm/${ARCH}/pages.c
${XTOSKRNL_SOURCE_DIR}/mm/${ARCH}/pmap.c
${XTOSKRNL_SOURCE_DIR}/po/idle.c ${XTOSKRNL_SOURCE_DIR}/po/idle.c
${XTOSKRNL_SOURCE_DIR}/rtl/atomic.c ${XTOSKRNL_SOURCE_DIR}/rtl/atomic.c
${XTOSKRNL_SOURCE_DIR}/rtl/bitmap.c ${XTOSKRNL_SOURCE_DIR}/rtl/bitmap.c

View File

@@ -1,58 +1,68 @@
## XTOSKRNL ## XTOSKRNL
XTOSKRNL is an XT system kernel executable, providing the kernel and executive layers for XTOS kernel space. It is XTOSKRNL is the core kernel executable for ExectOS, providing the fundamental kernel and executive layers that operate
a fundamental part of ExectOS, responsible for various core services like hardware abstraction or memory management. within the XTOS kernel space. It is responsible for various core services, such as hardware abstraction, memory
This kernel, contains the scheduler (called sometimes as Dispatcher), cache, object and memory managers, security management, and process scheduling. The kernel contains the scheduler (sometimes referred to as the Dispatcher), the
manager and other kernel executives described below. cache, object, and memory managers, the security manager, and other executive components described below.
All routines in kernel are prefixed to indicate the kernel subsystem they belong and put inside separate directory. All routines in the kernel are prefixed to indicate the subsystem they belong to, and their source code is organized
This is a list of them: into corresponding directories. These subsystems include:
* Ar - Architecture library * Ar - Architecture-specific Library
* Ex - Kernel Executive * Ex - Kernel Executive
* Hl - Hardware Abstraction Layer (HAL) * Hl - Hardware Layer
* Ke - Core kernel library * Kd - Kernel Debugger
* Mm - Memory manager * Ke - Core Kernel Library
* Mm - Memory Manager
* Po - Plug&Play and Power Manager * Po - Plug&Play and Power Manager
* Rtl - Runtime library * Rtl - Runtime library
### AR: Architecture Library ### AR: Architecture Library
This module contains processor architecture specific functions. This includes enabling and disabling interrupts at This module contains functions specific to the processor architecture. These include routines for enabling and disabling
the processor, getting the address of a page fault, getting CPUID information, and performing very early processor interrupts, retrieving the faulting address on a page fault, querying CPUID information, and performing very early
initialization. This module does not contain any manufacturer or board-specific code, only CPU architecture specific processor initialization. This module contains only CPU architecture-specific code, with no manufacturer or
code. board-specific implementations.
### EX: Kernel Executive ### EX: Kernel Executive
The kernel executive supplies heap management, including support for allocating system memory from paged/non-paged The Kernel Executive provides services for allocating system memory from paged and non-paged pools. It also supplies
pools, as well as synchronization primitives like push locks and fast mutexes, interlocked memory access, and worker synchronization primitives such as pushlocks and fast mutexes, routines for interlocked memory access, and support for
threads. worker threads.
### HL: Hardware Abstraction Layer ### HL: Hardware Layer
Hardware Abstraction Layer (HAL), is a layer between the physical hardware of the computer and the rest of the operating The Hardware Layer is an abstraction layer between the physical hardware and the rest of the operating system. It is
system. It was designed to hide differences in hardware and therefore it provides a consistent platform on which designed to abstract away hardware differences, providing a consistent platform on which the kernel and applications
the system and applications may run. can run.
### KD: Kernel Debugger
The Kernel Debugger (KD) subsystem provides debugging support for the kernel. The KD is initialized early in the boot
process to facilitate debugging from the very beginning of the kernel's execution.
### KE: Kernel Library ### KE: Kernel Library
The kernel implements its core functionality that everything else in the system depends upon. This includes basic The Core Kernel Library implements the core functionality upon which the rest of the system depends. This includes
low-level operations such as routing hardware interrupts. fundamental low-level operations, such as routing hardware interrupts and managing dispatcher objects.
### MM: Memory Manager ### MM: Memory Manager
Memory Manager is one of core subsystems. It manages virtual memory, controls memory protection and the paging of memory The Memory Manager is one of the core subsystems. It manages virtual memory, controls memory protection, and
in and out of physical memory to secondary storage. It also implements a general-purpose allocator of physical memory. handles paging memory between physical RAM and secondary storage. It also implements a general-purpose allocator for
physical memory.
### PO: Plug&Play and Power Manager ### PO: Plug&Play and Power Manager
This subsystem deals with power events, such as power-off, stand-by, or hibernate. It also handles Plug&Play and This subsystem handles power management events, such as shutdown or standby. It also manages Plug and Play (PnP),
supports device detection and installation at boot time. It is responsible for starting and stopping devices on demand. supporting device detection and installation at boot time. Furthermore, it is responsible for starting and stopping
devices on demand.
### RTL: Runtime Library ### RTL: Runtime Library
This is a required static copy of C runtime objects. It includes many utility functions that can be used by native The Runtime Library provides a kernel-mode implementation of common C library functions. It includes many utility
applications. routines, for use by other kernel components.
## Functions Naming Convention ## Function Naming Convention
When naming a kernel functions, certain conventions are used. The function name is usually structured with All kernel functions adhere to a strict naming convention to enhance code readability and maintainability. The structure
&lt;Prefix&gt;&lt;Operation&gt;&lt;Object&gt;. The prefix denotes the module to which it belongs, thus module of a function name is generally composed of three parts: &lt;Prefix&gt;&lt;Operation&gt;&lt;Object&gt;
can be identified simply by the name of the function. Additionally, the prefix identifies the function visibility
as well. Thus all private functions, that should not be used from outside of the module has added "p" suffix to The prefix identifies the component to which the function belongs. Additionally, the prefix indicates the function's
the prefix. For example, KepInitializeStack() routine: visibility. Private functions, which should not be called from outside their own module, have a 'p' appended to their
* Kep - prefix meaning this is private routine belonging to Kernel library (Ke) module, prefix.
* Initialize - operation this function does with the object,
* Stack - the object is stack. For example, consider the **KepInitializeStack()** routine:
* **Kep** - The prefix indicates a private (p) routine belonging to the Core Kernel Library (Ke).
* **Initialize** - The operation performed by the function.
* **Stack** - The object on which the operation is performed.

View File

@@ -13,7 +13,7 @@
/** /**
* This macro creates a trap handler for the specified vector. * Creates a trap handler for the specified vector.
* *
* @param Vector * @param Vector
* Supplies a trap vector number. * Supplies a trap vector number.
@@ -22,9 +22,9 @@
* *
* @since XT 1.0 * @since XT 1.0
*/ */
.macro ArpCreateTrapHandler Vector .macro ArCreateTrapHandler Vector
.global ArpTrap\Vector .global ArTrap\Vector
ArpTrap\Vector: ArTrap\Vector:
/* Push fake error code for non-error vectors */ /* Push fake error code for non-error vectors */
.if \Vector != 8 && \Vector != 10 && \Vector != 11 && \Vector != 12 && \Vector != 13 && \Vector != 14 && \Vector != 17 && \Vector != 30 .if \Vector != 8 && \Vector != 10 && \Vector != 11 && \Vector != 12 && \Vector != 13 && \Vector != 14 && \Vector != 17 && \Vector != 30
push $0 push $0
@@ -113,7 +113,7 @@ KernelMode$\Vector:
/* Push Frame Pointer, clear direction flag and pass to trap dispatcher */ /* Push Frame Pointer, clear direction flag and pass to trap dispatcher */
mov %rsp, %rcx mov %rsp, %rcx
cld cld
call ArpDispatchTrap call ArDispatchTrap
/* Test previous mode and swapgs if needed */ /* Test previous mode and swapgs if needed */
testb $1, TrapPreviousMode(%rbp) testb $1, TrapPreviousMode(%rbp)
@@ -176,6 +176,6 @@ KernelModeReturn$\Vector:
/* Populate common trap handlers */ /* Populate common trap handlers */
.irp i,0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F .irp i,0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F
.irp j,0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F .irp j,0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F
ArpCreateTrapHandler 0x\i\j ArCreateTrapHandler 0x\i\j
.endr .endr
.endr .endr

133
xtoskrnl/ar/amd64/boot.S Normal file
View File

@@ -0,0 +1,133 @@
/**
* PROJECT: ExectOS
* COPYRIGHT: See COPYING.md in the top level directory
* FILE: xtoskrnl/ar/amd64/boot.S
* DESCRIPTION: AMD64-specific boot code for setting up the low-level CPU environment
* DEVELOPERS: Aiken Harris <harraiken91@gmail.com>
*/
#include <amd64/asmsup.h>
.altmacro
.text
/**
* Enables eXtended Physical Addressing (XPA).
*
* @param PageMap
* Supplies a pointer to the page map to be used.
*
* @return This routine does not return any value.
*
* @since XT 1.0
*/
.global ArEnableExtendedPhysicalAddressing
ArEnableExtendedPhysicalAddressing:
/* Save the original CR4 register */
movq %cr4, %rax
/* Save the state of stack pointer and non-volatile registers */
movq %rsp, XpaRegisterSaveArea(%rip)
movq %rbp, XpaRegisterSaveArea+0x08(%rip)
movq %rax, XpaRegisterSaveArea+0x10(%rip)
movq %rbx, XpaRegisterSaveArea+0x18(%rip)
/* Save the original CR0 register */
movq %cr0, %rbp
/* Load temporary GDT required for mode transitions */
leaq XpaTemporaryGdtDesc(%rip), %rax
movq %rax, XpaTemporaryGdtBase(%rip)
lgdtq XpaTemporaryGdtSize(%rip)
/* Load addresses for entering compatibility mode and re-entering long mode */
leaq XpaEnterCompatMode(%rip), %rax
leaq XpaEnterLongMode(%rip), %rbx
/* Push the 32-bit code segment selector and the target address for a far jump */
pushq $GDT_R0_CMCODE
pushq %rax
/* Perform a far return to switch to 32-bit compatibility mode */
lretq
XpaEnterCompatMode:
/* Enter 32-bit compatibility mode */
.code32
/* Store the PageMap pointer on the stack for future use */
pushl %ecx
/* Set the stack segment to the 32-bit data segment selector */
movl $GDT_R0_DATA, %eax
movl %eax, %ss
/* Disable PGE and PCIDE to ensure all TLB entries will be flushed */
movl %cr4, %eax
andl $~(CR4_PGE | CR4_PCIDE), %eax
movl %eax, %cr4
/* Temporarily disable paging */
movl %ebp, %eax
andl $~CR0_PG, %eax
movl %eax, %cr0
/* Disable Long Mode as prerequisite for enabling 5-level paging */
movl $X86_MSR_EFER, %ecx
rdmsr
andl $~X86_MSR_EFER_LME, %eax
wrmsr
/* Transition to 5-level paging (PML5/LA57) */
movl %cr4, %eax
orl $CR4_LA57, %eax
movl %eax, %cr4
/* Restore the PageMap pointer from the stack and load it into CR3 */
popl %ecx
movl %ecx, %cr3
/* Re-enable Long Mode */
movl $X86_MSR_EFER, %ecx
rdmsr
orl $X86_MSR_EFER_LME, %eax
wrmsr
/* Restore CR0 with paging enabled and flush the instruction pipeline */
movl %ebp, %cr0
call XpaFlushInstructions
XpaFlushInstructions:
/* Push the 64-bit code segment selector and the target address for a far jump */
pushl $GDT_R0_CODE
pushl %ebx
/* Perform a far return to switch to 64-bit long mode */
lretl
XpaEnterLongMode:
/* Enter 64-bit long mode */
.code64
/* Restore the stack pointer and non-volatile registers */
movq XpaRegisterSaveArea(%rip), %rsp
movq XpaRegisterSaveArea+8(%rip), %rbp
movq XpaRegisterSaveArea+0x10(%rip), %rax
movq XpaRegisterSaveArea+0x18(%rip), %rbx
/* Restore the original CR4 register with LA57 bit set */
orq $CR4_LA57, %rax
movq %rax, %cr4
/* Return to the caller */
retq
/* Data section for saving registers and temporary GDT */
XpaRegisterSaveArea: .quad 0x0000000000000000, 0x0000000000000000, 0x0000000000000000, 0x0000000000000000
XpaTemporaryGdtSize: .short ArEnableExtendedPhysicalAddressingEnd - XpaTemporaryGdtDesc - 1
XpaTemporaryGdtBase: .quad 0x0000000000000000
XpaTemporaryGdtDesc: .quad 0x0000000000000000, 0x00CF9A000000FFFF, 0x00AF9A000000FFFF, 0x00CF92000000FFFF
.global ArEnableExtendedPhysicalAddressingEnd
ArEnableExtendedPhysicalAddressingEnd:

File diff suppressed because it is too large Load Diff

34
xtoskrnl/ar/amd64/data.cc Normal file
View File

@@ -0,0 +1,34 @@
/**
* PROJECT: ExectOS
* COPYRIGHT: See COPYING.md in the top level directory
* FILE: xtoskrnl/ar/amd64/data.cc
* DESCRIPTION: AMD64 architecture-specific global and static data
* DEVELOPERS: Rafal Kupiec <belliash@codingworkshop.eu.org>
*/
#include <xtos.hh>
/* Architecture-specific Library */
namespace AR
{
/* Initial kernel boot stack */
UCHAR ProcSup::BootStack[KERNEL_STACK_SIZE] = {};
/* Initial kernel fault stack */
UCHAR ProcSup::FaultStack[KERNEL_STACK_SIZE] = {};
/* Initial GDT */
KGDTENTRY ProcSup::InitialGdt[GDT_ENTRIES] = {};
/* Initial IDT */
KIDTENTRY ProcSup::InitialIdt[IDT_ENTRIES] = {};
/* Initial Processor Block */
KPROCESSOR_BLOCK ProcSup::InitialProcessorBlock;
/* Initial TSS */
KTSS ProcSup::InitialTss;
} /* namespace */

View File

@@ -1,28 +0,0 @@
/**
* PROJECT: ExectOS
* COPYRIGHT: See COPYING.md in the top level directory
* FILE: xtoskrnl/ar/amd64/globals.c
* DESCRIPTION: XT architecture library global variables
* DEVELOPERS: Rafal Kupiec <belliash@codingworkshop.eu.org>
*/
#include <xtos.h>
/* Initial GDT */
KGDTENTRY ArInitialGdt[GDT_ENTRIES] = {0};
/* Initial IDT */
KIDTENTRY ArInitialIdt[IDT_ENTRIES] = {0};
/* Initial Processor Block */
KPROCESSOR_BLOCK ArInitialProcessorBlock;
/* Initial TSS */
KTSS ArInitialTss;
/* Initial kernel boot stack */
UCHAR ArKernelBootStack[KERNEL_STACK_SIZE] = {0};
/* Initial kernel fault stack */
UCHAR ArKernelFaultStack[KERNEL_STACK_SIZE] = {0};

View File

@@ -1,121 +1,28 @@
/** /**
* PROJECT: ExectOS * PROJECT: ExectOS
* COPYRIGHT: See COPYING.md in the top level directory * COPYRIGHT: See COPYING.md in the top level directory
* FILE: xtoskrnl/ar/amd64/procsup.c * FILE: xtoskrnl/ar/amd64/procsup.cc
* DESCRIPTION: AMD64 processor functionality support * DESCRIPTION: AMD64 processor functionality support
* DEVELOPERS: Rafal Kupiec <belliash@codingworkshop.eu.org> * DEVELOPERS: Rafal Kupiec <belliash@codingworkshop.eu.org>
*/ */
#include <xtos.h> #include <xtos.hh>
/* Architecture-specific Library */
namespace AR
{
/** /**
* Initializes AMD64 processor specific structures. * Gets the base address of the kernel boot stack.
* *
* @return This routine does not return any value. * @return This routine returns a pointer to the kernel boot stack.
* *
* @since XT 1.0 * @since XT 1.0
*/ */
XTAPI PVOID ProcSup::GetBootStack(VOID)
VOID
ArInitializeProcessor(IN PVOID ProcessorStructures)
{ {
KDESCRIPTOR GdtDescriptor, IdtDescriptor; return (PVOID)BootStack;
PVOID KernelBootStack, KernelFaultStack;
PKPROCESSOR_BLOCK ProcessorBlock;
PKGDTENTRY Gdt;
PKIDTENTRY Idt;
PKTSS Tss;
/* Check if processor structures buffer provided */
if(ProcessorStructures)
{
/* Assign CPU structures from provided buffer */
ArpInitializeProcessorStructures(ProcessorStructures, &Gdt, &Tss, &ProcessorBlock,
&KernelBootStack, &KernelFaultStack);
/* Use global IDT */
Idt = ArInitialIdt;
}
else
{
/* Use initial structures */
Gdt = ArInitialGdt;
Idt = ArInitialIdt;
Tss = &ArInitialTss;
KernelBootStack = &ArKernelBootStack;
KernelFaultStack = &ArKernelFaultStack;
ProcessorBlock = &ArInitialProcessorBlock;
}
/* Initialize processor block */
ArpInitializeProcessorBlock(ProcessorBlock, Gdt, Idt, Tss, KernelFaultStack);
/* Initialize GDT, IDT and TSS */
ArpInitializeGdt(ProcessorBlock);
ArpInitializeIdt(ProcessorBlock);
ArpInitializeTss(ProcessorBlock, KernelBootStack, KernelFaultStack);
/* Set GDT and IDT descriptors */
GdtDescriptor.Base = Gdt;
GdtDescriptor.Limit = (GDT_ENTRIES * sizeof(KGDTENTRY)) - 1;
IdtDescriptor.Base = Idt;
IdtDescriptor.Limit = (IDT_ENTRIES * sizeof(KIDTENTRY)) - 1;
/* Load GDT, IDT and TSS */
ArLoadGlobalDescriptorTable(&GdtDescriptor.Limit);
ArLoadInterruptDescriptorTable(&IdtDescriptor.Limit);
ArLoadTaskRegister((UINT)KGDT_SYS_TSS);
/* Enter passive IRQ level */
HlSetRunLevel(PASSIVE_LEVEL);
/* Initialize segment registers */
ArpInitializeSegments();
/* Set GS base */
ArWriteModelSpecificRegister(X86_MSR_GSBASE, (ULONGLONG)ProcessorBlock);
ArWriteModelSpecificRegister(X86_MSR_KERNEL_GSBASE, (ULONGLONG)ProcessorBlock);
/* Initialize processor registers */
ArpInitializeProcessorRegisters();
/* Identify processor */
ArpIdentifyProcessor();
}
/**
* Updates an existing AMD64 GDT entry with new base address.
*
* @param Gdt
* Supplies a pointer to the GDT.
*
* @param Selector
* Specifies a segment selector of the GDT entry.
*
* @param Base
* Specifies a base address value of the descriptor.
*
* @return This routine does not return any value.
*
* @since XT 1.0
*/
XTAPI
VOID
ArSetGdtEntryBase(IN PKGDTENTRY Gdt,
IN USHORT Selector,
IN ULONG_PTR Base)
{
PKGDTENTRY GdtEntry;
/* Get GDT entry */
GdtEntry = (PKGDTENTRY)((ULONG_PTR)Gdt + (Selector & ~RPL_MASK));
/* Set new GDT descriptor base */
GdtEntry->BaseLow = (Base & 0xFFFF);
GdtEntry->Bytes.BaseMiddle = ((Base >> 16) & 0xFF);
GdtEntry->Bytes.BaseHigh = ((Base >> 24) & 0xFF);
GdtEntry->BaseUpper = (Base >> 32);
} }
/** /**
@@ -128,7 +35,7 @@ ArSetGdtEntryBase(IN PKGDTENTRY Gdt,
*/ */
XTAPI XTAPI
VOID VOID
ArpIdentifyProcessor(VOID) ProcSup::IdentifyProcessor(VOID)
{ {
PKPROCESSOR_CONTROL_BLOCK Prcb; PKPROCESSOR_CONTROL_BLOCK Prcb;
CPUID_REGISTERS CpuRegisters; CPUID_REGISTERS CpuRegisters;
@@ -143,19 +50,19 @@ ArpIdentifyProcessor(VOID)
/* Get CPU vendor by issueing CPUID instruction */ /* Get CPU vendor by issueing CPUID instruction */
RtlZeroMemory(&CpuRegisters, sizeof(CPUID_REGISTERS)); RtlZeroMemory(&CpuRegisters, sizeof(CPUID_REGISTERS));
CpuRegisters.Leaf = CPUID_GET_VENDOR_STRING; CpuRegisters.Leaf = CPUID_GET_VENDOR_STRING;
ArCpuId(&CpuRegisters); CpuFunc::CpuId(&CpuRegisters);
/* Store CPU vendor in processor control block */ /* Store CPU vendor in processor control block */
Prcb->CpuId.Vendor = CpuRegisters.Ebx; Prcb->CpuId.Vendor = (CPU_VENDOR)CpuRegisters.Ebx;
*(PULONG)&Prcb->CpuId.VendorName[0] = CpuRegisters.Ebx; *(PULONG)&Prcb->CpuId.VendorName[0] = CpuRegisters.Ebx;
*(PULONG)&Prcb->CpuId.VendorName[4] = CpuRegisters.Edx; *(PULONG)&Prcb->CpuId.VendorName[4] = CpuRegisters.Edx;
*(PULONG)&Prcb->CpuId.VendorName[8] = CpuRegisters.Ecx; *(PULONG)&Prcb->CpuId.VendorName[8] = CpuRegisters.Ecx;
Prcb->CpuId.VendorName[12] = '\0'; Prcb->CpuId.VendorName[12] = '\0';
/* Get CPU features */ /* Get CPU standard features */
RtlZeroMemory(&CpuRegisters, sizeof(CPUID_REGISTERS)); RtlZeroMemory(&CpuRegisters, sizeof(CPUID_REGISTERS));
CpuRegisters.Leaf = CPUID_GET_CPU_FEATURES; CpuRegisters.Leaf = CPUID_GET_STANDARD1_FEATURES;
ArCpuId(&CpuRegisters); CpuFunc::CpuId(&CpuRegisters);
/* Store CPU signature in processor control block */ /* Store CPU signature in processor control block */
CpuSignature = *(PCPUID_SIGNATURE)&CpuRegisters.Eax; CpuSignature = *(PCPUID_SIGNATURE)&CpuRegisters.Eax;
@@ -195,6 +102,81 @@ ArpIdentifyProcessor(VOID)
/* TODO: Store a list of CPU features in processor control block */ /* TODO: Store a list of CPU features in processor control block */
} }
/**
* Initializes AMD64 processor specific structures.
*
* @return This routine does not return any value.
*
* @since XT 1.0
*/
XTAPI
VOID
ProcSup::InitializeProcessor(IN PVOID ProcessorStructures)
{
KDESCRIPTOR GdtDescriptor, IdtDescriptor;
PVOID KernelBootStack, KernelFaultStack;
PKPROCESSOR_BLOCK ProcessorBlock;
PKGDTENTRY Gdt;
PKIDTENTRY Idt;
PKTSS Tss;
/* Check if processor structures buffer provided */
if(ProcessorStructures)
{
/* Assign CPU structures from provided buffer */
InitializeProcessorStructures(ProcessorStructures, &Gdt, &Tss, &ProcessorBlock,
&KernelBootStack, &KernelFaultStack);
/* Use global IDT */
Idt = InitialIdt;
}
else
{
/* Use initial structures */
Gdt = InitialGdt;
Idt = InitialIdt;
Tss = &InitialTss;
KernelBootStack = &BootStack;
KernelFaultStack = &FaultStack;
ProcessorBlock = &InitialProcessorBlock;
}
/* Initialize processor block */
InitializeProcessorBlock(ProcessorBlock, Gdt, Idt, Tss, KernelFaultStack);
/* Initialize GDT, IDT and TSS */
InitializeGdt(ProcessorBlock);
InitializeIdt(ProcessorBlock);
InitializeTss(ProcessorBlock, KernelBootStack, KernelFaultStack);
/* Set GDT and IDT descriptors */
GdtDescriptor.Base = Gdt;
GdtDescriptor.Limit = (GDT_ENTRIES * sizeof(KGDTENTRY)) - 1;
IdtDescriptor.Base = Idt;
IdtDescriptor.Limit = (IDT_ENTRIES * sizeof(KIDTENTRY)) - 1;
/* Load GDT, IDT and TSS */
CpuFunc::LoadGlobalDescriptorTable(&GdtDescriptor.Limit);
CpuFunc::LoadInterruptDescriptorTable(&IdtDescriptor.Limit);
CpuFunc::LoadTaskRegister((UINT)KGDT_SYS_TSS);
/* Enter passive IRQ level */
HlSetRunLevel(PASSIVE_LEVEL);
/* Initialize segment registers */
InitializeSegments();
/* Set GS base */
CpuFunc::WriteModelSpecificRegister(X86_MSR_GSBASE, (ULONGLONG)ProcessorBlock);
CpuFunc::WriteModelSpecificRegister(X86_MSR_KERNEL_GSBASE, (ULONGLONG)ProcessorBlock);
/* Initialize processor registers */
InitializeProcessorRegisters();
/* Identify processor */
IdentifyProcessor();
}
/** /**
* Initializes the kernel's Global Descriptor Table (GDT). * Initializes the kernel's Global Descriptor Table (GDT).
* *
@@ -207,19 +189,21 @@ ArpIdentifyProcessor(VOID)
*/ */
XTAPI XTAPI
VOID VOID
ArpInitializeGdt(IN PKPROCESSOR_BLOCK ProcessorBlock) ProcSup::InitializeGdt(IN PKPROCESSOR_BLOCK ProcessorBlock)
{ {
/* Initialize GDT entries */ /* Initialize GDT entries */
ArpSetGdtEntry(ProcessorBlock->GdtBase, KGDT_NULL, 0x0, 0x0, KGDT_TYPE_NONE, KGDT_DPL_SYSTEM, 1); SetGdtEntry(ProcessorBlock->GdtBase, KGDT_NULL, 0x0, 0x0, KGDT_TYPE_NONE, KGDT_DPL_SYSTEM, 1);
ArpSetGdtEntry(ProcessorBlock->GdtBase, KGDT_R0_CODE, 0x0, 0x0, KGDT_TYPE_CODE, KGDT_DPL_SYSTEM, 1); SetGdtEntry(ProcessorBlock->GdtBase, KGDT_R0_CODE, 0x0, 0x0, KGDT_TYPE_CODE, KGDT_DPL_SYSTEM, 1);
ArpSetGdtEntry(ProcessorBlock->GdtBase, KGDT_R0_DATA, 0x0, 0x0, KGDT_TYPE_DATA, KGDT_DPL_SYSTEM, 1); SetGdtEntry(ProcessorBlock->GdtBase, KGDT_R0_DATA, 0x0, 0x0, KGDT_TYPE_DATA, KGDT_DPL_SYSTEM, 1);
ArpSetGdtEntry(ProcessorBlock->GdtBase, KGDT_R3_CMCODE, 0x0, 0xFFFFFFFF, KGDT_TYPE_CODE, KGDT_DPL_USER, 2); SetGdtEntry(ProcessorBlock->GdtBase, KGDT_R3_CMCODE, 0x0, 0xFFFFFFFF, KGDT_TYPE_CODE, KGDT_DPL_USER, 2);
ArpSetGdtEntry(ProcessorBlock->GdtBase, KGDT_R3_DATA, 0x0, 0xFFFFFFFF, KGDT_TYPE_DATA, KGDT_DPL_USER, 2); SetGdtEntry(ProcessorBlock->GdtBase, KGDT_R3_DATA, 0x0, 0xFFFFFFFF, KGDT_TYPE_DATA, KGDT_DPL_USER, 2);
ArpSetGdtEntry(ProcessorBlock->GdtBase, KGDT_R3_CODE, 0x0, 0x0, KGDT_TYPE_CODE, KGDT_DPL_USER, 1); SetGdtEntry(ProcessorBlock->GdtBase, KGDT_R3_CODE, 0x0, 0x0, KGDT_TYPE_CODE, KGDT_DPL_USER, 1);
ArpSetGdtEntry(ProcessorBlock->GdtBase, KGDT_SYS_TSS, (ULONG_PTR)ProcessorBlock->TssBase, sizeof(KTSS), AMD64_TSS, KGDT_DPL_SYSTEM, 0); SetGdtEntry(ProcessorBlock->GdtBase, KGDT_SYS_TSS, (ULONG_PTR)ProcessorBlock->TssBase,
ArpSetGdtEntry(ProcessorBlock->GdtBase, KGDT_R3_CMTEB, 0x0, 0x0FFF, KGDT_TYPE_DATA, KGDT_DPL_USER, 2); sizeof(KTSS) - 1, AMD64_TSS, KGDT_DPL_SYSTEM, 0);
ArpSetGdtEntry(ProcessorBlock->GdtBase, KGDT_R0_LDT, 0x0, 0xFFFFFFFF, KGDT_TYPE_CODE, KGDT_DPL_SYSTEM, 0); SetGdtEntry(ProcessorBlock->GdtBase, KGDT_R3_CMTEB, 0x0, 0x0FFF, KGDT_TYPE_DATA, KGDT_DPL_USER, 2);
ArpSetGdtEntry(ProcessorBlock->GdtBase, KGDT_ALIAS, (ULONG_PTR)ProcessorBlock->GdtBase, (GDT_ENTRIES * sizeof(KGDTENTRY)) - 1, KGDT_TYPE_DATA, KGDT_DPL_SYSTEM, 0); SetGdtEntry(ProcessorBlock->GdtBase, KGDT_R0_LDT, 0x0, 0xFFFFFFFF, KGDT_TYPE_CODE, KGDT_DPL_SYSTEM, 0);
SetGdtEntry(ProcessorBlock->GdtBase, KGDT_ALIAS, (ULONG_PTR)ProcessorBlock->GdtBase,
(GDT_ENTRIES * sizeof(KGDTENTRY)) - 1, KGDT_TYPE_DATA, KGDT_DPL_SYSTEM, 0);
} }
/** /**
@@ -234,7 +218,7 @@ ArpInitializeGdt(IN PKPROCESSOR_BLOCK ProcessorBlock)
*/ */
XTAPI XTAPI
VOID VOID
ArpInitializeIdt(IN PKPROCESSOR_BLOCK ProcessorBlock) ProcSup::InitializeIdt(IN PKPROCESSOR_BLOCK ProcessorBlock)
{ {
UINT Vector; UINT Vector;
@@ -242,34 +226,34 @@ ArpInitializeIdt(IN PKPROCESSOR_BLOCK ProcessorBlock)
for(Vector = 0; Vector < IDT_ENTRIES; Vector++) for(Vector = 0; Vector < IDT_ENTRIES; Vector++)
{ {
/* Set the IDT to handle unexpected interrupts */ /* Set the IDT to handle unexpected interrupts */
ArpSetIdtGate(ProcessorBlock->IdtBase, Vector, ArpHandleTrapFF, KGDT_R0_CODE, KIDT_IST_RESERVED, KIDT_ACCESS_RING0); SetIdtGate(ProcessorBlock->IdtBase, Vector, (PVOID)ArTrap0xFF, KGDT_R0_CODE, KIDT_IST_RESERVED, KIDT_ACCESS_RING0);
} }
/* Setup IDT handlers for known interrupts and traps */ /* Setup IDT handlers for known interrupts and traps */
ArpSetIdtGate(ProcessorBlock->IdtBase, 0x00, ArpTrap0x00, KGDT_R0_CODE, KIDT_IST_RESERVED, KIDT_ACCESS_RING0); SetIdtGate(ProcessorBlock->IdtBase, 0x00, (PVOID)ArTrap0x00, KGDT_R0_CODE, KIDT_IST_RESERVED, KIDT_ACCESS_RING0);
ArpSetIdtGate(ProcessorBlock->IdtBase, 0x01, ArpTrap0x01, KGDT_R0_CODE, KIDT_IST_RESERVED, KIDT_ACCESS_RING0); SetIdtGate(ProcessorBlock->IdtBase, 0x01, (PVOID)ArTrap0x01, KGDT_R0_CODE, KIDT_IST_RESERVED, KIDT_ACCESS_RING0);
ArpSetIdtGate(ProcessorBlock->IdtBase, 0x02, ArpTrap0x02, KGDT_R0_CODE, KIDT_IST_PANIC, KIDT_ACCESS_RING0); SetIdtGate(ProcessorBlock->IdtBase, 0x02, (PVOID)ArTrap0x02, KGDT_R0_CODE, KIDT_IST_PANIC, KIDT_ACCESS_RING0);
ArpSetIdtGate(ProcessorBlock->IdtBase, 0x03, ArpTrap0x03, KGDT_R0_CODE, KIDT_IST_RESERVED, KIDT_ACCESS_RING3); SetIdtGate(ProcessorBlock->IdtBase, 0x03, (PVOID)ArTrap0x03, KGDT_R0_CODE, KIDT_IST_RESERVED, KIDT_ACCESS_RING3);
ArpSetIdtGate(ProcessorBlock->IdtBase, 0x04, ArpTrap0x04, KGDT_R0_CODE, KIDT_IST_RESERVED, KIDT_ACCESS_RING3); SetIdtGate(ProcessorBlock->IdtBase, 0x04, (PVOID)ArTrap0x04, KGDT_R0_CODE, KIDT_IST_RESERVED, KIDT_ACCESS_RING3);
ArpSetIdtGate(ProcessorBlock->IdtBase, 0x05, ArpTrap0x05, KGDT_R0_CODE, KIDT_IST_RESERVED, KIDT_ACCESS_RING0); SetIdtGate(ProcessorBlock->IdtBase, 0x05, (PVOID)ArTrap0x05, KGDT_R0_CODE, KIDT_IST_RESERVED, KIDT_ACCESS_RING0);
ArpSetIdtGate(ProcessorBlock->IdtBase, 0x06, ArpTrap0x06, KGDT_R0_CODE, KIDT_IST_RESERVED, KIDT_ACCESS_RING0); SetIdtGate(ProcessorBlock->IdtBase, 0x06, (PVOID)ArTrap0x06, KGDT_R0_CODE, KIDT_IST_RESERVED, KIDT_ACCESS_RING0);
ArpSetIdtGate(ProcessorBlock->IdtBase, 0x07, ArpTrap0x07, KGDT_R0_CODE, KIDT_IST_RESERVED, KIDT_ACCESS_RING0); SetIdtGate(ProcessorBlock->IdtBase, 0x07, (PVOID)ArTrap0x07, KGDT_R0_CODE, KIDT_IST_RESERVED, KIDT_ACCESS_RING0);
ArpSetIdtGate(ProcessorBlock->IdtBase, 0x08, ArpTrap0x08, KGDT_R0_CODE, KIDT_IST_PANIC, KIDT_ACCESS_RING0); SetIdtGate(ProcessorBlock->IdtBase, 0x08, (PVOID)ArTrap0x08, KGDT_R0_CODE, KIDT_IST_PANIC, KIDT_ACCESS_RING0);
ArpSetIdtGate(ProcessorBlock->IdtBase, 0x09, ArpTrap0x09, KGDT_R0_CODE, KIDT_IST_RESERVED, KIDT_ACCESS_RING0); SetIdtGate(ProcessorBlock->IdtBase, 0x09, (PVOID)ArTrap0x09, KGDT_R0_CODE, KIDT_IST_RESERVED, KIDT_ACCESS_RING0);
ArpSetIdtGate(ProcessorBlock->IdtBase, 0x0A, ArpTrap0x0A, KGDT_R0_CODE, KIDT_IST_RESERVED, KIDT_ACCESS_RING0); SetIdtGate(ProcessorBlock->IdtBase, 0x0A, (PVOID)ArTrap0x0A, KGDT_R0_CODE, KIDT_IST_RESERVED, KIDT_ACCESS_RING0);
ArpSetIdtGate(ProcessorBlock->IdtBase, 0x0B, ArpTrap0x0B, KGDT_R0_CODE, KIDT_IST_RESERVED, KIDT_ACCESS_RING0); SetIdtGate(ProcessorBlock->IdtBase, 0x0B, (PVOID)ArTrap0x0B, KGDT_R0_CODE, KIDT_IST_RESERVED, KIDT_ACCESS_RING0);
ArpSetIdtGate(ProcessorBlock->IdtBase, 0x0C, ArpTrap0x0C, KGDT_R0_CODE, KIDT_IST_RESERVED, KIDT_ACCESS_RING0); SetIdtGate(ProcessorBlock->IdtBase, 0x0C, (PVOID)ArTrap0x0C, KGDT_R0_CODE, KIDT_IST_RESERVED, KIDT_ACCESS_RING0);
ArpSetIdtGate(ProcessorBlock->IdtBase, 0x0D, ArpTrap0x0D, KGDT_R0_CODE, KIDT_IST_RESERVED, KIDT_ACCESS_RING0); SetIdtGate(ProcessorBlock->IdtBase, 0x0D, (PVOID)ArTrap0x0D, KGDT_R0_CODE, KIDT_IST_RESERVED, KIDT_ACCESS_RING0);
ArpSetIdtGate(ProcessorBlock->IdtBase, 0x0E, ArpTrap0x0E, KGDT_R0_CODE, KIDT_IST_RESERVED, KIDT_ACCESS_RING0); SetIdtGate(ProcessorBlock->IdtBase, 0x0E, (PVOID)ArTrap0x0E, KGDT_R0_CODE, KIDT_IST_RESERVED, KIDT_ACCESS_RING0);
ArpSetIdtGate(ProcessorBlock->IdtBase, 0x10, ArpTrap0x10, KGDT_R0_CODE, KIDT_IST_RESERVED, KIDT_ACCESS_RING0); SetIdtGate(ProcessorBlock->IdtBase, 0x10, (PVOID)ArTrap0x10, KGDT_R0_CODE, KIDT_IST_RESERVED, KIDT_ACCESS_RING0);
ArpSetIdtGate(ProcessorBlock->IdtBase, 0x11, ArpTrap0x11, KGDT_R0_CODE, KIDT_IST_RESERVED, KIDT_ACCESS_RING0); SetIdtGate(ProcessorBlock->IdtBase, 0x11, (PVOID)ArTrap0x11, KGDT_R0_CODE, KIDT_IST_RESERVED, KIDT_ACCESS_RING0);
ArpSetIdtGate(ProcessorBlock->IdtBase, 0x12, ArpTrap0x12, KGDT_R0_CODE, KIDT_IST_MCA, KIDT_ACCESS_RING0); SetIdtGate(ProcessorBlock->IdtBase, 0x12, (PVOID)ArTrap0x12, KGDT_R0_CODE, KIDT_IST_MCA, KIDT_ACCESS_RING0);
ArpSetIdtGate(ProcessorBlock->IdtBase, 0x13, ArpTrap0x13, KGDT_R0_CODE, KIDT_IST_RESERVED, KIDT_ACCESS_RING0); SetIdtGate(ProcessorBlock->IdtBase, 0x13, (PVOID)ArTrap0x13, KGDT_R0_CODE, KIDT_IST_RESERVED, KIDT_ACCESS_RING0);
ArpSetIdtGate(ProcessorBlock->IdtBase, 0x1F, ArpTrap0x1F, KGDT_R0_CODE, KIDT_IST_RESERVED, KIDT_ACCESS_RING0); SetIdtGate(ProcessorBlock->IdtBase, 0x1F, (PVOID)ArTrap0x1F, KGDT_R0_CODE, KIDT_IST_RESERVED, KIDT_ACCESS_RING0);
ArpSetIdtGate(ProcessorBlock->IdtBase, 0x2C, ArpTrap0x2C, KGDT_R0_CODE, KIDT_IST_RESERVED, KIDT_ACCESS_RING3); SetIdtGate(ProcessorBlock->IdtBase, 0x2C, (PVOID)ArTrap0x2C, KGDT_R0_CODE, KIDT_IST_RESERVED, KIDT_ACCESS_RING3);
ArpSetIdtGate(ProcessorBlock->IdtBase, 0x2D, ArpTrap0x2D, KGDT_R0_CODE, KIDT_IST_RESERVED, KIDT_ACCESS_RING3); SetIdtGate(ProcessorBlock->IdtBase, 0x2D, (PVOID)ArTrap0x2D, KGDT_R0_CODE, KIDT_IST_RESERVED, KIDT_ACCESS_RING3);
ArpSetIdtGate(ProcessorBlock->IdtBase, 0x2F, ArpTrap0x2F, KGDT_R0_CODE, KIDT_IST_RESERVED, KIDT_ACCESS_RING0); SetIdtGate(ProcessorBlock->IdtBase, 0x2F, (PVOID)ArTrap0x2F, KGDT_R0_CODE, KIDT_IST_RESERVED, KIDT_ACCESS_RING0);
ArpSetIdtGate(ProcessorBlock->IdtBase, 0xE1, ArpTrap0xE1, KGDT_R0_CODE, KIDT_IST_RESERVED, KIDT_ACCESS_RING0); SetIdtGate(ProcessorBlock->IdtBase, 0xE1, (PVOID)ArTrap0xE1, KGDT_R0_CODE, KIDT_IST_RESERVED, KIDT_ACCESS_RING0);
} }
/** /**
@@ -293,18 +277,18 @@ ArpInitializeIdt(IN PKPROCESSOR_BLOCK ProcessorBlock)
*/ */
XTAPI XTAPI
VOID VOID
ArpInitializeProcessorBlock(OUT PKPROCESSOR_BLOCK ProcessorBlock, ProcSup::InitializeProcessorBlock(OUT PKPROCESSOR_BLOCK ProcessorBlock,
IN PKGDTENTRY Gdt, IN PKGDTENTRY Gdt,
IN PKIDTENTRY Idt, IN PKIDTENTRY Idt,
IN PKTSS Tss, IN PKTSS Tss,
IN PVOID DpcStack) IN PVOID DpcStack)
{ {
/* Set processor block and processor control block */ /* Set processor block and processor control block */
ProcessorBlock->Self = ProcessorBlock; ProcessorBlock->Self = ProcessorBlock;
ProcessorBlock->CurrentPrcb = &ProcessorBlock->Prcb; ProcessorBlock->CurrentPrcb = &ProcessorBlock->Prcb;
/* Set GDT, IDT and TSS descriptors */ /* Set GDT, IDT and TSS descriptors */
ProcessorBlock->GdtBase = (PVOID)Gdt; ProcessorBlock->GdtBase = (PKGDTENTRY)(PVOID)Gdt;
ProcessorBlock->IdtBase = Idt; ProcessorBlock->IdtBase = Idt;
ProcessorBlock->TssBase = Tss; ProcessorBlock->TssBase = Tss;
ProcessorBlock->Prcb.RspBase = Tss->Rsp0; ProcessorBlock->Prcb.RspBase = Tss->Rsp0;
@@ -322,10 +306,10 @@ ArpInitializeProcessorBlock(OUT PKPROCESSOR_BLOCK ProcessorBlock,
ProcessorBlock->Prcb.ProcessorState.SpecialRegisters.KernelDr7 = 0; ProcessorBlock->Prcb.ProcessorState.SpecialRegisters.KernelDr7 = 0;
/* Set process and thread information */ /* Set process and thread information */
ProcessorBlock->Prcb.CurrentThread = &KeInitialThread.ThreadControlBlock; ProcessorBlock->Prcb.CurrentThread = &(KE::KThread::GetInitialThread())->ThreadControlBlock;
ProcessorBlock->Prcb.CurrentThread->ApcState.Process = &KeInitialProcess.ProcessControlBlock; ProcessorBlock->Prcb.CurrentThread->ApcState.Process = &(KE::KProcess::GetInitialProcess())->ProcessControlBlock;
ProcessorBlock->Prcb.IdleThread = &KeInitialThread.ThreadControlBlock; ProcessorBlock->Prcb.IdleThread = &(KE::KThread::GetInitialThread())->ThreadControlBlock;
ProcessorBlock->Prcb.NextThread = NULL; ProcessorBlock->Prcb.NextThread = nullptr;
/* Set initial MXCSR register value */ /* Set initial MXCSR register value */
ProcessorBlock->Prcb.MxCsr = INITIAL_MXCSR; ProcessorBlock->Prcb.MxCsr = INITIAL_MXCSR;
@@ -343,56 +327,50 @@ ArpInitializeProcessorBlock(OUT PKPROCESSOR_BLOCK ProcessorBlock,
*/ */
XTAPI XTAPI
VOID VOID
ArpInitializeProcessorRegisters(VOID) ProcSup::InitializeProcessorRegisters(VOID)
{ {
ULONGLONG PatAttributes; ULONGLONG PatAttributes;
/* Enable FXSAVE restore */ /* Enable FXSAVE restore */
ArWriteControlRegister(4, ArReadControlRegister(4) | CR4_FXSR); CpuFunc::WriteControlRegister(4, CpuFunc::ReadControlRegister(4) | CR4_FXSR);
/* Enable XMMI exceptions */ /* Enable XMMI exceptions */
ArWriteControlRegister(4, ArReadControlRegister(4) | CR4_XMMEXCPT); CpuFunc::WriteControlRegister(4, CpuFunc::ReadControlRegister(4) | CR4_XMMEXCPT);
/* Set debugger extension */ /* Set debugger extension */
ArWriteControlRegister(4, ArReadControlRegister(4) | CR4_DE); CpuFunc::WriteControlRegister(4, CpuFunc::ReadControlRegister(4) | CR4_DE);
/* Enable large pages */ /* Enable large pages */
ArWriteControlRegister(4, ArReadControlRegister(4) | CR4_PSE); CpuFunc::WriteControlRegister(4, CpuFunc::ReadControlRegister(4) | CR4_PSE);
/* Enable write-protection */ /* Enable write-protection */
ArWriteControlRegister(0, ArReadControlRegister(0) | CR0_WP); CpuFunc::WriteControlRegister(0, CpuFunc::ReadControlRegister(0) | CR0_WP);
/* Set alignment mask */ /* Set alignment mask */
ArWriteControlRegister(0, ArReadControlRegister(0) | CR0_AM); CpuFunc::WriteControlRegister(0, CpuFunc::ReadControlRegister(0) | CR0_AM);
/* Disable FPU monitoring */ /* Disable FPU monitoring */
ArWriteControlRegister(0, ArReadControlRegister(0) & ~CR0_MP); CpuFunc::WriteControlRegister(0, CpuFunc::ReadControlRegister(0) & ~CR0_MP);
/* Disable x87 FPU exceptions */ /* Disable x87 FPU exceptions */
ArWriteControlRegister(0, ArReadControlRegister(0) & ~CR0_NE); CpuFunc::WriteControlRegister(0, CpuFunc::ReadControlRegister(0) & ~CR0_NE);
/* Flush the TLB */ /* Flush the TLB */
ArFlushTlb(); CpuFunc::FlushTlb();
/* Initialize system calls MSR */
ArWriteModelSpecificRegister(X86_MSR_STAR, (((ULONG64)KGDT_R3_CMCODE | RPL_MASK) << 48) | ((ULONG64)KGDT_R0_CODE << 32));
ArWriteModelSpecificRegister(X86_MSR_CSTAR, (ULONG64)&ArpHandleSystemCall32);
ArWriteModelSpecificRegister(X86_MSR_LSTAR, (ULONG64)&ArpHandleSystemCall64);
ArWriteModelSpecificRegister(X86_MSR_FMASK, X86_EFLAGS_IF_MASK | X86_EFLAGS_TF_MASK);
/* Enable system call extensions (SCE) in EFER MSR */
ArWriteModelSpecificRegister(X86_MSR_EFER, ArReadModelSpecificRegister(X86_MSR_EFER) | X86_MSR_EFER_SCE);
/* Initialize system call MSRs */
Traps::InitializeSystemCallMsrs();
/* Enable No-Execute (NXE) in EFER MSR */ /* Enable No-Execute (NXE) in EFER MSR */
ArWriteModelSpecificRegister(X86_MSR_EFER, ArReadModelSpecificRegister(X86_MSR_EFER) | X86_MSR_EFER_NXE); CpuFunc::WriteModelSpecificRegister(X86_MSR_EFER, CpuFunc::ReadModelSpecificRegister(X86_MSR_EFER) | X86_MSR_EFER_NXE);
/* Initialize Page Attribute Table */ /* Initialize Page Attribute Table */
PatAttributes = (PAT_TYPE_WB << 0) | (PAT_TYPE_USWC << 8) | (PAT_TYPE_WEAK_UC << 16) | (PAT_TYPE_STRONG_UC << 24) | PatAttributes = (PAT_TYPE_WB << 0) | (PAT_TYPE_USWC << 8) | (PAT_TYPE_WEAK_UC << 16) | (PAT_TYPE_STRONG_UC << 24) |
(PAT_TYPE_WB << 32) | (PAT_TYPE_USWC << 40) | (PAT_TYPE_WEAK_UC << 48) | (PAT_TYPE_STRONG_UC << 56); (PAT_TYPE_WB << 32) | (PAT_TYPE_USWC << 40) | (PAT_TYPE_WEAK_UC << 48) | (PAT_TYPE_STRONG_UC << 56);
ArWriteModelSpecificRegister(X86_MSR_PAT, PatAttributes); CpuFunc::WriteModelSpecificRegister(X86_MSR_PAT, PatAttributes);
/* Initialize MXCSR register */ /* Initialize MXCSR register */
ArLoadMxcsrRegister(INITIAL_MXCSR); CpuFunc::LoadMxcsrRegister(INITIAL_MXCSR);
} }
/** /**
@@ -422,12 +400,12 @@ ArpInitializeProcessorRegisters(VOID)
*/ */
XTAPI XTAPI
VOID VOID
ArpInitializeProcessorStructures(IN PVOID ProcessorStructures, ProcSup::InitializeProcessorStructures(IN PVOID ProcessorStructures,
OUT PKGDTENTRY *Gdt, OUT PKGDTENTRY *Gdt,
OUT PKTSS *Tss, OUT PKTSS *Tss,
OUT PKPROCESSOR_BLOCK *ProcessorBlock, OUT PKPROCESSOR_BLOCK *ProcessorBlock,
OUT PVOID *KernelBootStack, OUT PVOID *KernelBootStack,
OUT PVOID *KernelFaultStack) OUT PVOID *KernelFaultStack)
{ {
UINT_PTR Address; UINT_PTR Address;
@@ -442,15 +420,15 @@ ArpInitializeProcessorStructures(IN PVOID ProcessorStructures,
*KernelFaultStack = (PVOID)Address; *KernelFaultStack = (PVOID)Address;
/* Assign a space for GDT and advance */ /* Assign a space for GDT and advance */
*Gdt = (PVOID)Address; *Gdt = (PKGDTENTRY)(PVOID)Address;
Address += sizeof(ArInitialGdt); Address += sizeof(InitialGdt);
/* Assign a space for Processor Block and advance */ /* Assign a space for Processor Block and advance */
*ProcessorBlock = (PVOID)Address; *ProcessorBlock = (PKPROCESSOR_BLOCK)(PVOID)Address;
Address += sizeof(ArInitialProcessorBlock); Address += sizeof(InitialProcessorBlock);
/* Assign a space for TSS */ /* Assign a space for TSS */
*Tss = (PVOID)Address; *Tss = (PKTSS)(PVOID)Address;
} }
/** /**
@@ -462,15 +440,15 @@ ArpInitializeProcessorStructures(IN PVOID ProcessorStructures,
*/ */
XTAPI XTAPI
VOID VOID
ArpInitializeSegments(VOID) ProcSup::InitializeSegments(VOID)
{ {
/* Initialize segments */ /* Initialize segments */
ArLoadSegment(SEGMENT_CS, KGDT_R0_CODE); CpuFunc::LoadSegment(SEGMENT_CS, KGDT_R0_CODE);
ArLoadSegment(SEGMENT_DS, KGDT_R3_DATA | RPL_MASK); CpuFunc::LoadSegment(SEGMENT_DS, KGDT_R3_DATA | RPL_MASK);
ArLoadSegment(SEGMENT_ES, KGDT_R3_DATA | RPL_MASK); CpuFunc::LoadSegment(SEGMENT_ES, KGDT_R3_DATA | RPL_MASK);
ArLoadSegment(SEGMENT_FS, KGDT_R3_CMTEB | RPL_MASK); CpuFunc::LoadSegment(SEGMENT_FS, KGDT_R3_CMTEB | RPL_MASK);
ArLoadSegment(SEGMENT_GS, KGDT_R3_DATA | RPL_MASK); CpuFunc::LoadSegment(SEGMENT_GS, KGDT_R3_DATA | RPL_MASK);
ArLoadSegment(SEGMENT_SS, KGDT_R0_DATA); CpuFunc::LoadSegment(SEGMENT_SS, KGDT_R0_DATA);
} }
/** /**
@@ -488,9 +466,9 @@ ArpInitializeSegments(VOID)
*/ */
XTAPI XTAPI
VOID VOID
ArpInitializeTss(IN PKPROCESSOR_BLOCK ProcessorBlock, ProcSup::InitializeTss(IN PKPROCESSOR_BLOCK ProcessorBlock,
IN PVOID KernelBootStack, IN PVOID KernelBootStack,
IN PVOID KernelFaultStack) IN PVOID KernelFaultStack)
{ {
/* Fill TSS with zeroes */ /* Fill TSS with zeroes */
RtlZeroMemory(ProcessorBlock->TssBase, sizeof(KTSS)); RtlZeroMemory(ProcessorBlock->TssBase, sizeof(KTSS));
@@ -532,13 +510,13 @@ ArpInitializeTss(IN PKPROCESSOR_BLOCK ProcessorBlock,
*/ */
XTAPI XTAPI
VOID VOID
ArpSetGdtEntry(IN PKGDTENTRY Gdt, ProcSup::SetGdtEntry(IN PKGDTENTRY Gdt,
IN USHORT Selector, IN USHORT Selector,
IN ULONG_PTR Base, IN ULONG_PTR Base,
IN ULONG Limit, IN ULONG Limit,
IN UCHAR Type, IN UCHAR Type,
IN UCHAR Dpl, IN UCHAR Dpl,
IN UCHAR SegmentMode) IN UCHAR SegmentMode)
{ {
PKGDTENTRY GdtEntry; PKGDTENTRY GdtEntry;
UCHAR Granularity; UCHAR Granularity;
@@ -580,6 +558,40 @@ ArpSetGdtEntry(IN PKGDTENTRY Gdt,
GdtEntry->MustBeZero = 0; GdtEntry->MustBeZero = 0;
} }
/**
* Updates an existing AMD64 GDT entry with new base address.
*
* @param Gdt
* Supplies a pointer to the GDT.
*
* @param Selector
* Specifies a segment selector of the GDT entry.
*
* @param Base
* Specifies a base address value of the descriptor.
*
* @return This routine does not return any value.
*
* @since XT 1.0
*/
XTAPI
VOID
ProcSup::SetGdtEntryBase(IN PKGDTENTRY Gdt,
IN USHORT Selector,
IN ULONG_PTR Base)
{
PKGDTENTRY GdtEntry;
/* Get GDT entry */
GdtEntry = (PKGDTENTRY)((ULONG_PTR)Gdt + (Selector & ~RPL_MASK));
/* Set new GDT descriptor base */
GdtEntry->BaseLow = (Base & 0xFFFF);
GdtEntry->Bytes.BaseMiddle = ((Base >> 16) & 0xFF);
GdtEntry->Bytes.BaseHigh = ((Base >> 24) & 0xFF);
GdtEntry->BaseUpper = (Base >> 32);
}
/** /**
* Fills in a call, interrupt, task or trap gate entry. * Fills in a call, interrupt, task or trap gate entry.
* *
@@ -607,12 +619,12 @@ ArpSetGdtEntry(IN PKGDTENTRY Gdt,
*/ */
XTAPI XTAPI
VOID VOID
ArpSetIdtGate(IN PKIDTENTRY Idt, ProcSup::SetIdtGate(IN PKIDTENTRY Idt,
IN USHORT Vector, IN USHORT Vector,
IN PVOID Handler, IN PVOID Handler,
IN USHORT Selector, IN USHORT Selector,
IN USHORT Ist, IN USHORT Ist,
IN USHORT Access) IN USHORT Access)
{ {
/* Setup the gate */ /* Setup the gate */
Idt[Vector].OffsetLow = ((ULONG_PTR)Handler & 0xFFFF); Idt[Vector].OffsetLow = ((ULONG_PTR)Handler & 0xFFFF);
@@ -624,3 +636,24 @@ ArpSetIdtGate(IN PKIDTENTRY Idt,
Idt[Vector].Selector = Selector; Idt[Vector].Selector = Selector;
Idt[Vector].Type = 0xE; Idt[Vector].Type = 0xE;
} }
} /* namespace */
/* TEMPORARY FOR COMPATIBILITY WITH C CODE */
XTCLINK
XTAPI
PVOID
ArGetBootStack(VOID)
{
return AR::ProcSup::GetBootStack();
}
/* TEMPORARY FOR COMPATIBILITY WITH C CODE */
XTCLINK
XTAPI
VOID
ArInitializeProcessor(IN PVOID ProcessorStructures)
{
AR::ProcSup::InitializeProcessor(ProcessorStructures);
}

View File

@@ -1,14 +1,18 @@
/** /**
* PROJECT: ExectOS * PROJECT: ExectOS
* COPYRIGHT: See COPYING.md in the top level directory * COPYRIGHT: See COPYING.md in the top level directory
* FILE: xtoskrnl/ar/amd64/traps.c * FILE: xtoskrnl/ar/amd64/traps.cc
* DESCRIPTION: AMD64 system traps * DESCRIPTION: AMD64 system traps
* DEVELOPERS: Rafal Kupiec <belliash@codingworkshop.eu.org> * DEVELOPERS: Rafal Kupiec <belliash@codingworkshop.eu.org>
*/ */
#include <xtos.h> #include <xtos.hh>
/* Architecture-specific Library */
namespace AR
{
/** /**
* Dispatches the trap provided by common trap handler. * Dispatches the trap provided by common trap handler.
* *
@@ -21,124 +25,138 @@
*/ */
XTCDECL XTCDECL
VOID VOID
ArpDispatchTrap(IN PKTRAP_FRAME TrapFrame) Traps::DispatchTrap(IN PKTRAP_FRAME TrapFrame)
{ {
/* Check vector and call appropriate handler */ /* Check vector and call appropriate handler */
switch(TrapFrame->Vector) switch(TrapFrame->Vector)
{ {
case 0x00: case 0x00:
/* Divide By Zero exception */ /* Divide By Zero exception */
ArpHandleTrap00(TrapFrame); HandleTrap00(TrapFrame);
break; break;
case 0x01: case 0x01:
/* Debug exception */ /* Debug exception */
ArpHandleTrap01(TrapFrame); HandleTrap01(TrapFrame);
break; break;
case 0x02: case 0x02:
/* Non-Maskable Interrupt (NMI) */ /* Non-Maskable Interrupt (NMI) */
ArpHandleTrap02(TrapFrame); HandleTrap02(TrapFrame);
break; break;
case 0x03: case 0x03:
/* INT3 instruction executed */ /* INT3 instruction executed */
ArpHandleTrap03(TrapFrame); HandleTrap03(TrapFrame);
break; break;
case 0x04: case 0x04:
/* Overflow exception */ /* Overflow exception */
ArpHandleTrap04(TrapFrame); HandleTrap04(TrapFrame);
break; break;
case 0x05: case 0x05:
/* Bound Range Exceeded exception */ /* Bound Range Exceeded exception */
ArpHandleTrap05(TrapFrame); HandleTrap05(TrapFrame);
break; break;
case 0x06: case 0x06:
/* Invalid Opcode exception */ /* Invalid Opcode exception */
ArpHandleTrap06(TrapFrame); HandleTrap06(TrapFrame);
break; break;
case 0x07: case 0x07:
/* Device Not Available exception */ /* Device Not Available exception */
ArpHandleTrap07(TrapFrame); HandleTrap07(TrapFrame);
break; break;
case 0x08: case 0x08:
/* Double Fault exception */ /* Double Fault exception */
ArpHandleTrap08(TrapFrame); HandleTrap08(TrapFrame);
break; break;
case 0x09: case 0x09:
/* Segment Overrun exception */ /* Segment Overrun exception */
ArpHandleTrap09(TrapFrame); HandleTrap09(TrapFrame);
break; break;
case 0x0A: case 0x0A:
/* Invalid TSS exception */ /* Invalid TSS exception */
ArpHandleTrap0A(TrapFrame); HandleTrap0A(TrapFrame);
break; break;
case 0x0B: case 0x0B:
/* Segment Not Present exception */ /* Segment Not Present exception */
ArpHandleTrap0B(TrapFrame); HandleTrap0B(TrapFrame);
break; break;
case 0x0C: case 0x0C:
/* Stack Segment Fault exception */ /* Stack Segment Fault exception */
ArpHandleTrap0C(TrapFrame); HandleTrap0C(TrapFrame);
break; break;
case 0x0D: case 0x0D:
/* General Protection Fault (GPF) exception*/ /* General Protection Fault (GPF) exception*/
ArpHandleTrap0D(TrapFrame); HandleTrap0D(TrapFrame);
break; break;
case 0x0E: case 0x0E:
/* Page Fault exception */ /* Page Fault exception */
ArpHandleTrap0E(TrapFrame); HandleTrap0E(TrapFrame);
break; break;
case 0x10: case 0x10:
/* X87 Floating-Point exception */ /* X87 Floating-Point exception */
ArpHandleTrap10(TrapFrame); HandleTrap10(TrapFrame);
break; break;
case 0x11: case 0x11:
/* Alignment Check exception */ /* Alignment Check exception */
ArpHandleTrap11(TrapFrame); HandleTrap11(TrapFrame);
break; break;
case 0x12: case 0x12:
/* Machine Check exception */ /* Machine Check exception */
ArpHandleTrap12(TrapFrame); HandleTrap12(TrapFrame);
break; break;
case 0x13: case 0x13:
/* SIMD Floating-Point exception */ /* SIMD Floating-Point exception */
ArpHandleTrap13(TrapFrame); HandleTrap13(TrapFrame);
break; break;
case 0x1F: case 0x1F:
/* Software Interrupt at APC level */ /* Software Interrupt at APC level */
ArpHandleTrap1F(TrapFrame); HandleTrap1F(TrapFrame);
break; break;
case 0x2C: case 0x2C:
/* Assertion raised */ /* Assertion raised */
ArpHandleTrap2C(TrapFrame); HandleTrap2C(TrapFrame);
break; break;
case 0x2D: case 0x2D:
/* Debug-Service-Request raised */ /* Debug-Service-Request raised */
ArpHandleTrap2D(TrapFrame); HandleTrap2D(TrapFrame);
break; break;
case 0x2F: case 0x2F:
/* Software Interrupt at DISPATCH level */ /* Software Interrupt at DISPATCH level */
ArpHandleTrap2F(TrapFrame); HandleTrap2F(TrapFrame);
break; break;
case 0xE1: case 0xE1:
/* InterProcessor Interrupt (IPI) */ /* InterProcessor Interrupt (IPI) */
ArpHandleTrapE1(TrapFrame); HandleTrapE1(TrapFrame);
break; break;
default: default:
/* Unknown/Unexpected trap */ /* Unknown/Unexpected trap */
ArpHandleTrapFF(TrapFrame); HandleTrapFF(TrapFrame);
break; break;
} }
} }
/**
* Handles a 32-bit system call.
*
* @return This routine does not return any value.
*
* @since XT 1.0
*/
XTCDECL XTCDECL
VOID VOID
ArpHandleSystemCall32(VOID) Traps::HandleSystemCall32(VOID)
{ {
DebugPrint(L"Handled 32-bit system call!\n"); DebugPrint(L"Handled 32-bit system call!\n");
} }
/**
* Handles a 64-bit system call.
*
* @return This routine does not return any value.
*
* @since XT 1.0
*/
XTCDECL XTCDECL
VOID VOID
ArpHandleSystemCall64(VOID) Traps::HandleSystemCall64(VOID)
{ {
DebugPrint(L"Handled 64-bit system call!\n"); DebugPrint(L"Handled 64-bit system call!\n");
} }
@@ -155,7 +173,7 @@ ArpHandleSystemCall64(VOID)
*/ */
XTCDECL XTCDECL
VOID VOID
ArpHandleTrap00(IN PKTRAP_FRAME TrapFrame) Traps::HandleTrap00(IN PKTRAP_FRAME TrapFrame)
{ {
DebugPrint(L"Handled Division-By-Zero Error (0x00)!\n"); DebugPrint(L"Handled Division-By-Zero Error (0x00)!\n");
for(;;); for(;;);
@@ -173,7 +191,7 @@ ArpHandleTrap00(IN PKTRAP_FRAME TrapFrame)
*/ */
XTCDECL XTCDECL
VOID VOID
ArpHandleTrap01(IN PKTRAP_FRAME TrapFrame) Traps::HandleTrap01(IN PKTRAP_FRAME TrapFrame)
{ {
DebugPrint(L"Handled Debug exception (0x01)!\n"); DebugPrint(L"Handled Debug exception (0x01)!\n");
for(;;); for(;;);
@@ -191,7 +209,7 @@ ArpHandleTrap01(IN PKTRAP_FRAME TrapFrame)
*/ */
XTCDECL XTCDECL
VOID VOID
ArpHandleTrap02(IN PKTRAP_FRAME TrapFrame) Traps::HandleTrap02(IN PKTRAP_FRAME TrapFrame)
{ {
DebugPrint(L"Handled Non-Maskable-Interrupt (0x02)!\n"); DebugPrint(L"Handled Non-Maskable-Interrupt (0x02)!\n");
for(;;); for(;;);
@@ -209,7 +227,7 @@ ArpHandleTrap02(IN PKTRAP_FRAME TrapFrame)
*/ */
XTCDECL XTCDECL
VOID VOID
ArpHandleTrap03(IN PKTRAP_FRAME TrapFrame) Traps::HandleTrap03(IN PKTRAP_FRAME TrapFrame)
{ {
DebugPrint(L"Handled INT3 (0x03)!\n"); DebugPrint(L"Handled INT3 (0x03)!\n");
for(;;); for(;;);
@@ -227,7 +245,7 @@ ArpHandleTrap03(IN PKTRAP_FRAME TrapFrame)
*/ */
XTCDECL XTCDECL
VOID VOID
ArpHandleTrap04(IN PKTRAP_FRAME TrapFrame) Traps::HandleTrap04(IN PKTRAP_FRAME TrapFrame)
{ {
DebugPrint(L"Handled Overflow exception (0x04)!\n"); DebugPrint(L"Handled Overflow exception (0x04)!\n");
for(;;); for(;;);
@@ -245,7 +263,7 @@ ArpHandleTrap04(IN PKTRAP_FRAME TrapFrame)
*/ */
XTCDECL XTCDECL
VOID VOID
ArpHandleTrap05(IN PKTRAP_FRAME TrapFrame) Traps::HandleTrap05(IN PKTRAP_FRAME TrapFrame)
{ {
DebugPrint(L"Handled Bound-Range-Exceeded exception (0x05)!\n"); DebugPrint(L"Handled Bound-Range-Exceeded exception (0x05)!\n");
for(;;); for(;;);
@@ -263,7 +281,7 @@ ArpHandleTrap05(IN PKTRAP_FRAME TrapFrame)
*/ */
XTCDECL XTCDECL
VOID VOID
ArpHandleTrap06(IN PKTRAP_FRAME TrapFrame) Traps::HandleTrap06(IN PKTRAP_FRAME TrapFrame)
{ {
DebugPrint(L"Handled Invalid Opcode exception (0x06)!\n"); DebugPrint(L"Handled Invalid Opcode exception (0x06)!\n");
for(;;); for(;;);
@@ -281,7 +299,7 @@ ArpHandleTrap06(IN PKTRAP_FRAME TrapFrame)
*/ */
XTCDECL XTCDECL
VOID VOID
ArpHandleTrap07(IN PKTRAP_FRAME TrapFrame) Traps::HandleTrap07(IN PKTRAP_FRAME TrapFrame)
{ {
DebugPrint(L"Handled Device Not Available exception (0x07)!\n"); DebugPrint(L"Handled Device Not Available exception (0x07)!\n");
for(;;); for(;;);
@@ -299,7 +317,7 @@ ArpHandleTrap07(IN PKTRAP_FRAME TrapFrame)
*/ */
XTCDECL XTCDECL
VOID VOID
ArpHandleTrap08(IN PKTRAP_FRAME TrapFrame) Traps::HandleTrap08(IN PKTRAP_FRAME TrapFrame)
{ {
DebugPrint(L"Handled Double-Fault exception (0x08)!\n"); DebugPrint(L"Handled Double-Fault exception (0x08)!\n");
for(;;); for(;;);
@@ -317,7 +335,7 @@ ArpHandleTrap08(IN PKTRAP_FRAME TrapFrame)
*/ */
XTCDECL XTCDECL
VOID VOID
ArpHandleTrap09(IN PKTRAP_FRAME TrapFrame) Traps::HandleTrap09(IN PKTRAP_FRAME TrapFrame)
{ {
DebugPrint(L"Handled Segment-Overrun exception (0x09)!\n"); DebugPrint(L"Handled Segment-Overrun exception (0x09)!\n");
for(;;); for(;;);
@@ -335,7 +353,7 @@ ArpHandleTrap09(IN PKTRAP_FRAME TrapFrame)
*/ */
XTCDECL XTCDECL
VOID VOID
ArpHandleTrap0A(IN PKTRAP_FRAME TrapFrame) Traps::HandleTrap0A(IN PKTRAP_FRAME TrapFrame)
{ {
DebugPrint(L"Handled Invalid-TSS exception (0x0A)!\n"); DebugPrint(L"Handled Invalid-TSS exception (0x0A)!\n");
for(;;); for(;;);
@@ -353,7 +371,7 @@ ArpHandleTrap0A(IN PKTRAP_FRAME TrapFrame)
*/ */
XTCDECL XTCDECL
VOID VOID
ArpHandleTrap0B(IN PKTRAP_FRAME TrapFrame) Traps::HandleTrap0B(IN PKTRAP_FRAME TrapFrame)
{ {
DebugPrint(L"Handled Segment-Not-Present exception (0x0B)!\n"); DebugPrint(L"Handled Segment-Not-Present exception (0x0B)!\n");
for(;;); for(;;);
@@ -371,7 +389,7 @@ ArpHandleTrap0B(IN PKTRAP_FRAME TrapFrame)
*/ */
XTCDECL XTCDECL
VOID VOID
ArpHandleTrap0C(IN PKTRAP_FRAME TrapFrame) Traps::HandleTrap0C(IN PKTRAP_FRAME TrapFrame)
{ {
DebugPrint(L"Handled Stack-Segment-Fault exception (0x0C)!\n"); DebugPrint(L"Handled Stack-Segment-Fault exception (0x0C)!\n");
for(;;); for(;;);
@@ -389,7 +407,7 @@ ArpHandleTrap0C(IN PKTRAP_FRAME TrapFrame)
*/ */
XTCDECL XTCDECL
VOID VOID
ArpHandleTrap0D(IN PKTRAP_FRAME TrapFrame) Traps::HandleTrap0D(IN PKTRAP_FRAME TrapFrame)
{ {
DebugPrint(L"Handled General-Protection-Fault (0x0D)!\n"); DebugPrint(L"Handled General-Protection-Fault (0x0D)!\n");
for(;;); for(;;);
@@ -407,7 +425,7 @@ ArpHandleTrap0D(IN PKTRAP_FRAME TrapFrame)
*/ */
XTCDECL XTCDECL
VOID VOID
ArpHandleTrap0E(IN PKTRAP_FRAME TrapFrame) Traps::HandleTrap0E(IN PKTRAP_FRAME TrapFrame)
{ {
DebugPrint(L"Handled Page-Fault exception (0x0E)!\n"); DebugPrint(L"Handled Page-Fault exception (0x0E)!\n");
for(;;); for(;;);
@@ -425,7 +443,7 @@ ArpHandleTrap0E(IN PKTRAP_FRAME TrapFrame)
*/ */
XTCDECL XTCDECL
VOID VOID
ArpHandleTrap10(IN PKTRAP_FRAME TrapFrame) Traps::HandleTrap10(IN PKTRAP_FRAME TrapFrame)
{ {
DebugPrint(L"Handled x87 Floating-Point exception (0x10)!\n"); DebugPrint(L"Handled x87 Floating-Point exception (0x10)!\n");
for(;;); for(;;);
@@ -443,7 +461,7 @@ ArpHandleTrap10(IN PKTRAP_FRAME TrapFrame)
*/ */
XTCDECL XTCDECL
VOID VOID
ArpHandleTrap11(IN PKTRAP_FRAME TrapFrame) Traps::HandleTrap11(IN PKTRAP_FRAME TrapFrame)
{ {
DebugPrint(L"Handled Alignment-Check exception (0x11)!\n"); DebugPrint(L"Handled Alignment-Check exception (0x11)!\n");
for(;;); for(;;);
@@ -461,7 +479,7 @@ ArpHandleTrap11(IN PKTRAP_FRAME TrapFrame)
*/ */
XTCDECL XTCDECL
VOID VOID
ArpHandleTrap12(IN PKTRAP_FRAME TrapFrame) Traps::HandleTrap12(IN PKTRAP_FRAME TrapFrame)
{ {
DebugPrint(L"Handled Machine-Check exception (0x12)!\n"); DebugPrint(L"Handled Machine-Check exception (0x12)!\n");
for(;;); for(;;);
@@ -479,7 +497,7 @@ ArpHandleTrap12(IN PKTRAP_FRAME TrapFrame)
*/ */
XTCDECL XTCDECL
VOID VOID
ArpHandleTrap13(IN PKTRAP_FRAME TrapFrame) Traps::HandleTrap13(IN PKTRAP_FRAME TrapFrame)
{ {
DebugPrint(L"Handled SIMD Floating-Point exception (0x13)!\n"); DebugPrint(L"Handled SIMD Floating-Point exception (0x13)!\n");
for(;;); for(;;);
@@ -497,7 +515,7 @@ ArpHandleTrap13(IN PKTRAP_FRAME TrapFrame)
*/ */
XTCDECL XTCDECL
VOID VOID
ArpHandleTrap1F(IN PKTRAP_FRAME TrapFrame) Traps::HandleTrap1F(IN PKTRAP_FRAME TrapFrame)
{ {
DebugPrint(L"Unhandled software interrupt at APC level (0x1F)!\n"); DebugPrint(L"Unhandled software interrupt at APC level (0x1F)!\n");
} }
@@ -514,7 +532,7 @@ ArpHandleTrap1F(IN PKTRAP_FRAME TrapFrame)
*/ */
XTCDECL XTCDECL
VOID VOID
ArpHandleTrap2C(IN PKTRAP_FRAME TrapFrame) Traps::HandleTrap2C(IN PKTRAP_FRAME TrapFrame)
{ {
DebugPrint(L"Handled Assertion (0x2C)!\n"); DebugPrint(L"Handled Assertion (0x2C)!\n");
for(;;); for(;;);
@@ -532,7 +550,7 @@ ArpHandleTrap2C(IN PKTRAP_FRAME TrapFrame)
*/ */
XTCDECL XTCDECL
VOID VOID
ArpHandleTrap2D(IN PKTRAP_FRAME TrapFrame) Traps::HandleTrap2D(IN PKTRAP_FRAME TrapFrame)
{ {
DebugPrint(L"Handled Debug-Service-Request (0x2D)!\n"); DebugPrint(L"Handled Debug-Service-Request (0x2D)!\n");
for(;;); for(;;);
@@ -550,7 +568,7 @@ ArpHandleTrap2D(IN PKTRAP_FRAME TrapFrame)
*/ */
XTCDECL XTCDECL
VOID VOID
ArpHandleTrap2F(IN PKTRAP_FRAME TrapFrame) Traps::HandleTrap2F(IN PKTRAP_FRAME TrapFrame)
{ {
DebugPrint(L"Unhandled software interrupt at DISPATCH level (0x2F)!\n"); DebugPrint(L"Unhandled software interrupt at DISPATCH level (0x2F)!\n");
} }
@@ -567,7 +585,7 @@ ArpHandleTrap2F(IN PKTRAP_FRAME TrapFrame)
*/ */
XTCDECL XTCDECL
VOID VOID
ArpHandleTrapE1(IN PKTRAP_FRAME TrapFrame) Traps::HandleTrapE1(IN PKTRAP_FRAME TrapFrame)
{ {
DebugPrint(L"Unhandled IPI interrupt (0xE1)!\n"); DebugPrint(L"Unhandled IPI interrupt (0xE1)!\n");
} }
@@ -584,8 +602,49 @@ ArpHandleTrapE1(IN PKTRAP_FRAME TrapFrame)
*/ */
XTCDECL XTCDECL
VOID VOID
ArpHandleTrapFF(IN PKTRAP_FRAME TrapFrame) Traps::HandleTrapFF(IN PKTRAP_FRAME TrapFrame)
{ {
DebugPrint(L"Handled Unexpected-Interrupt (0xFF)!\n"); DebugPrint(L"Handled Unexpected-Interrupt (0xFF)!\n");
for(;;); for(;;);
} }
/**
* Initializes system call MSRs.
*
* @return This routine does not return any value.
*
* @since XT 1.0
*/
XTCDECL
VOID
Traps::InitializeSystemCallMsrs(VOID)
{
/* Initialize system calls MSR */
CpuFunc::WriteModelSpecificRegister(X86_MSR_STAR, (((ULONG64)KGDT_R3_CMCODE | RPL_MASK) << 48) | ((ULONG64)KGDT_R0_CODE << 32));
CpuFunc::WriteModelSpecificRegister(X86_MSR_CSTAR, (ULONG64)&HandleSystemCall32);
CpuFunc::WriteModelSpecificRegister(X86_MSR_LSTAR, (ULONG64)&HandleSystemCall64);
CpuFunc::WriteModelSpecificRegister(X86_MSR_FMASK, X86_EFLAGS_IF_MASK | X86_EFLAGS_TF_MASK);
/* Enable system call extensions (SCE) in EFER MSR */
CpuFunc::WriteModelSpecificRegister(X86_MSR_EFER, CpuFunc::ReadModelSpecificRegister(X86_MSR_EFER) | X86_MSR_EFER_SCE);
}
} /* namespace */
/**
* C-linkage wrapper for dispatching the trap provided by common trap handler.
*
* @param TrapFrame
* Supplies a kernel trap frame pushed by common trap handler on the stack.
*
* @return This routine does not return any value.
*
* @since XT 1.0
*/
XTCLINK
XTCDECL
VOID
ArDispatchTrap(IN PKTRAP_FRAME TrapFrame)
{
AR::Traps::DispatchTrap(TrapFrame);
}

View File

@@ -22,9 +22,9 @@
* *
* @since XT 1.0 * @since XT 1.0
*/ */
.macro ArpCreateTrapHandler Vector .macro ArCreateTrapHandler Vector
.global _ArpTrap\Vector .global _ArTrap\Vector
_ArpTrap\Vector: _ArTrap\Vector:
/* Push fake error code for non-error vectors */ /* Push fake error code for non-error vectors */
.if \Vector != 8 && \Vector != 10 && \Vector != 11 && \Vector != 12 && \Vector != 13 && \Vector != 14 && \Vector != 17 && \Vector != 30 .if \Vector != 8 && \Vector != 10 && \Vector != 11 && \Vector != 12 && \Vector != 13 && \Vector != 14 && \Vector != 17 && \Vector != 30
push $0 push $0
@@ -84,7 +84,7 @@ KernelMode$\Vector:
/* Push Frame Pointer, clear direction flag and pass to trap dispatcher */ /* Push Frame Pointer, clear direction flag and pass to trap dispatcher */
push %esp push %esp
cld cld
call _ArpDispatchTrap call _ArDispatchTrap
/* Clean up the stack */ /* Clean up the stack */
add $4, %esp add $4, %esp
@@ -121,6 +121,6 @@ KernelModeReturn$\Vector:
/* Populate common trap handlers */ /* Populate common trap handlers */
.irp i,0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F .irp i,0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F
.irp j,0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F .irp j,0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F
ArpCreateTrapHandler 0x\i\j ArCreateTrapHandler 0x\i\j
.endr .endr
.endr .endr

14
xtoskrnl/ar/i686/boot.S Normal file
View File

@@ -0,0 +1,14 @@
/**
* PROJECT: ExectOS
* COPYRIGHT: See COPYING.md in the top level directory
* FILE: xtoskrnl/ar/i686/boot.S
* DESCRIPTION: i686-specific boot code for setting up the low-level CPU environment
* DEVELOPERS: Aiken Harris <harraiken91@gmail.com>
*/
#include <amd64/asmsup.h>
.altmacro
.text

File diff suppressed because it is too large Load Diff

40
xtoskrnl/ar/i686/data.cc Normal file
View File

@@ -0,0 +1,40 @@
/**
* PROJECT: ExectOS
* COPYRIGHT: See COPYING.md in the top level directory
* FILE: xtoskrnl/ar/i686/data.cc
* DESCRIPTION: I686 architecture-specific global and static data
* DEVELOPERS: Rafal Kupiec <belliash@codingworkshop.eu.org>
*/
#include <xtos.hh>
/* Architecture-specific Library */
namespace AR
{
/* Initial kernel boot stack */
UCHAR ProcSup::BootStack[KERNEL_STACK_SIZE] = {};
/* Double Fault gate */
UCHAR ProcSup::DoubleFaultTss[KTSS_IO_MAPS];
/* Initial kernel fault stack */
UCHAR ProcSup::FaultStack[KERNEL_STACK_SIZE] = {};
/* Initial GDT */
KGDTENTRY ProcSup::InitialGdt[GDT_ENTRIES] = {};
/* Initial IDT */
KIDTENTRY ProcSup::InitialIdt[IDT_ENTRIES] = {};
/* Initial Processor Block */
KPROCESSOR_BLOCK ProcSup::InitialProcessorBlock;
/* Initial TSS */
KTSS ProcSup::InitialTss;
/* NMI task gate */
UCHAR ProcSup::NonMaskableInterruptTss[KTSS_IO_MAPS];
} /* namespace */

View File

@@ -1,32 +0,0 @@
/**
* PROJECT: ExectOS
* COPYRIGHT: See COPYING.md in the top level directory
* FILE: xtoskrnl/ar/i686/globals.c
* DESCRIPTION: XT architecture library global variables
* DEVELOPERS: Rafal Kupiec <belliash@codingworkshop.eu.org>
*/
#include <xtos.h>
/* Initial GDT */
KGDTENTRY ArInitialGdt[GDT_ENTRIES] = {0};
/* Initial IDT */
KIDTENTRY ArInitialIdt[IDT_ENTRIES] = {0};
/* Initial Processor Block */
KPROCESSOR_BLOCK ArInitialProcessorBlock;
/* Initial TSS */
KTSS ArInitialTss;
/* Double Fault and NMI task gates */
UCHAR ArpDoubleFaultTss[KTSS_IO_MAPS];
UCHAR ArpNonMaskableInterruptTss[KTSS_IO_MAPS];
/* Initial kernel boot stack */
UCHAR ArKernelBootStack[KERNEL_STACK_SIZE] = {0};
/* Initial kernel fault stack */
UCHAR ArKernelFaultStack[KERNEL_STACK_SIZE] = {0};

View File

@@ -1,116 +1,28 @@
/** /**
* PROJECT: ExectOS * PROJECT: ExectOS
* COPYRIGHT: See COPYING.md in the top level directory * COPYRIGHT: See COPYING.md in the top level directory
* FILE: xtoskrnl/ar/i686/procsup.c * FILE: xtoskrnl/ar/i686/procsup.cc
* DESCRIPTION: I686 processor functionality support * DESCRIPTION: I686 processor functionality support
* DEVELOPERS: Rafal Kupiec <belliash@codingworkshop.eu.org> * DEVELOPERS: Rafal Kupiec <belliash@codingworkshop.eu.org>
*/ */
#include <xtos.h> #include <xtos.hh>
/* Architecture-specific Library */
namespace AR
{
/** /**
* Initializes i686 processor specific structures. * Gets the base address of the kernel boot stack.
* *
* @return This routine does not return any value. * @return This routine returns a pointer to the kernel boot stack.
* *
* @since XT 1.0 * @since XT 1.0
*/ */
XTAPI PVOID ProcSup::GetBootStack(VOID)
VOID
ArInitializeProcessor(IN PVOID ProcessorStructures)
{ {
KDESCRIPTOR GdtDescriptor, IdtDescriptor; return (PVOID)BootStack;
PVOID KernelBootStack, KernelFaultStack;
PKPROCESSOR_BLOCK ProcessorBlock;
PKGDTENTRY Gdt;
PKIDTENTRY Idt;
PKTSS Tss;
/* Check if processor structures buffer provided */
if(ProcessorStructures)
{
/* Assign CPU structures from provided buffer */
ArpInitializeProcessorStructures(ProcessorStructures, &Gdt, &Tss, &ProcessorBlock,
&KernelBootStack, &KernelFaultStack);
/* Use global IDT */
Idt = ArInitialIdt;
}
else
{
/* Use initial structures */
Gdt = ArInitialGdt;
Idt = ArInitialIdt;
Tss = &ArInitialTss;
KernelBootStack = &ArKernelBootStack;
KernelFaultStack = &ArKernelFaultStack;
ProcessorBlock = &ArInitialProcessorBlock;
}
/* Initialize processor block */
ArpInitializeProcessorBlock(ProcessorBlock, Gdt, Idt, Tss, KernelFaultStack);
/* Initialize GDT, IDT and TSS */
ArpInitializeGdt(ProcessorBlock);
ArpInitializeIdt(ProcessorBlock);
ArpInitializeTss(ProcessorBlock, KernelBootStack, KernelFaultStack);
/* Set GDT and IDT descriptors */
GdtDescriptor.Base = Gdt;
GdtDescriptor.Limit = (GDT_ENTRIES * sizeof(KGDTENTRY)) - 1;
IdtDescriptor.Base = Idt;
IdtDescriptor.Limit = (IDT_ENTRIES * sizeof(KIDTENTRY)) - 1;
/* Load GDT, IDT and TSS */
ArLoadGlobalDescriptorTable(&GdtDescriptor.Limit);
ArLoadInterruptDescriptorTable(&IdtDescriptor.Limit);
ArLoadTaskRegister((UINT)KGDT_SYS_TSS);
/* Enter passive IRQ level */
HlSetRunLevel(PASSIVE_LEVEL);
/* Initialize segment registers */
ArpInitializeSegments();
/* Initialize processor registers */
ArpInitializeProcessorRegisters();
/* Identify processor */
ArpIdentifyProcessor();
}
/**
* Updates an existing i686 GDT entry with new base address.
*
* @param Gdt
* Supplies a pointer to the GDT.
*
* @param Selector
* Specifies a segment selector of the GDT entry.
*
* @param Base
* Specifies a base address value of the descriptor.
*
* @return This routine does not return any value.
*
* @since XT 1.0
*/
XTAPI
VOID
ArSetGdtEntryBase(IN PKGDTENTRY Gdt,
IN USHORT Selector,
IN ULONG_PTR Base)
{
PKGDTENTRY GdtEntry;
/* Get GDT entry */
GdtEntry = (PKGDTENTRY)((ULONG_PTR)Gdt + (Selector & ~RPL_MASK));
/* Set new GDT descriptor base */
GdtEntry->BaseLow = (Base & 0xFFFF);
GdtEntry->Bytes.BaseMiddle = ((Base >> 16) & 0xFF);
GdtEntry->Bytes.BaseHigh = ((Base >> 24) & 0xFF);
} }
/** /**
@@ -123,7 +35,7 @@ ArSetGdtEntryBase(IN PKGDTENTRY Gdt,
*/ */
XTAPI XTAPI
VOID VOID
ArpIdentifyProcessor(VOID) ProcSup::IdentifyProcessor(VOID)
{ {
PKPROCESSOR_CONTROL_BLOCK Prcb; PKPROCESSOR_CONTROL_BLOCK Prcb;
CPUID_REGISTERS CpuRegisters; CPUID_REGISTERS CpuRegisters;
@@ -141,15 +53,15 @@ ArpIdentifyProcessor(VOID)
ArCpuId(&CpuRegisters); ArCpuId(&CpuRegisters);
/* Store CPU vendor in processor control block */ /* Store CPU vendor in processor control block */
Prcb->CpuId.Vendor = CpuRegisters.Ebx; Prcb->CpuId.Vendor = (CPU_VENDOR)CpuRegisters.Ebx;
*(PULONG)&Prcb->CpuId.VendorName[0] = CpuRegisters.Ebx; *(PULONG)&Prcb->CpuId.VendorName[0] = CpuRegisters.Ebx;
*(PULONG)&Prcb->CpuId.VendorName[4] = CpuRegisters.Edx; *(PULONG)&Prcb->CpuId.VendorName[4] = CpuRegisters.Edx;
*(PULONG)&Prcb->CpuId.VendorName[8] = CpuRegisters.Ecx; *(PULONG)&Prcb->CpuId.VendorName[8] = CpuRegisters.Ecx;
Prcb->CpuId.VendorName[12] = '\0'; Prcb->CpuId.VendorName[12] = '\0';
/* Get CPU features */ /* Get CPU standard features */
RtlZeroMemory(&CpuRegisters, sizeof(CPUID_REGISTERS)); RtlZeroMemory(&CpuRegisters, sizeof(CPUID_REGISTERS));
CpuRegisters.Leaf = CPUID_GET_CPU_FEATURES; CpuRegisters.Leaf = CPUID_GET_STANDARD1_FEATURES;
ArCpuId(&CpuRegisters); ArCpuId(&CpuRegisters);
/* Store CPU signature in processor control block */ /* Store CPU signature in processor control block */
@@ -190,6 +102,77 @@ ArpIdentifyProcessor(VOID)
/* TODO: Store a list of CPU features in processor control block */ /* TODO: Store a list of CPU features in processor control block */
} }
/**
* Initializes i686 processor specific structures.
*
* @return This routine does not return any value.
*
* @since XT 1.0
*/
XTAPI
VOID
ProcSup::InitializeProcessor(IN PVOID ProcessorStructures)
{
KDESCRIPTOR GdtDescriptor, IdtDescriptor;
PVOID KernelBootStack, KernelFaultStack;
PKPROCESSOR_BLOCK ProcessorBlock;
PKGDTENTRY Gdt;
PKIDTENTRY Idt;
PKTSS Tss;
/* Check if processor structures buffer provided */
if(ProcessorStructures)
{
/* Assign CPU structures from provided buffer */
InitializeProcessorStructures(ProcessorStructures, &Gdt, &Tss, &ProcessorBlock,
&KernelBootStack, &KernelFaultStack);
/* Use global IDT */
Idt = InitialIdt;
}
else
{
/* Use initial structures */
Gdt = InitialGdt;
Idt = InitialIdt;
Tss = &InitialTss;
KernelBootStack = &BootStack;
KernelFaultStack = &FaultStack;
ProcessorBlock = &InitialProcessorBlock;
}
/* Initialize processor block */
InitializeProcessorBlock(ProcessorBlock, Gdt, Idt, Tss, KernelFaultStack);
/* Initialize GDT, IDT and TSS */
InitializeGdt(ProcessorBlock);
InitializeIdt(ProcessorBlock);
InitializeTss(ProcessorBlock, KernelBootStack, KernelFaultStack);
/* Set GDT and IDT descriptors */
GdtDescriptor.Base = Gdt;
GdtDescriptor.Limit = (GDT_ENTRIES * sizeof(KGDTENTRY)) - 1;
IdtDescriptor.Base = Idt;
IdtDescriptor.Limit = (IDT_ENTRIES * sizeof(KIDTENTRY)) - 1;
/* Load GDT, IDT and TSS */
CpuFunc::LoadGlobalDescriptorTable(&GdtDescriptor.Limit);
CpuFunc::LoadInterruptDescriptorTable(&IdtDescriptor.Limit);
CpuFunc::LoadTaskRegister((UINT)KGDT_SYS_TSS);
/* Enter passive IRQ level */
HlSetRunLevel(PASSIVE_LEVEL);
/* Initialize segment registers */
InitializeSegments();
/* Initialize processor registers */
InitializeProcessorRegisters();
/* Identify processor */
IdentifyProcessor();
}
/** /**
* Initializes the kernel's Global Descriptor Table (GDT). * Initializes the kernel's Global Descriptor Table (GDT).
* *
@@ -202,23 +185,23 @@ ArpIdentifyProcessor(VOID)
*/ */
XTAPI XTAPI
VOID VOID
ArpInitializeGdt(IN PKPROCESSOR_BLOCK ProcessorBlock) ProcSup::InitializeGdt(IN PKPROCESSOR_BLOCK ProcessorBlock)
{ {
/* Initialize GDT entries */ /* Initialize GDT entries */
ArpSetGdtEntry(ProcessorBlock->GdtBase, KGDT_NULL, 0x0, 0x0, KGDT_TYPE_NONE, KGDT_DPL_SYSTEM, 0); SetGdtEntry(ProcessorBlock->GdtBase, KGDT_NULL, 0x0, 0x0, KGDT_TYPE_NONE, KGDT_DPL_SYSTEM, 0);
ArpSetGdtEntry(ProcessorBlock->GdtBase, KGDT_R0_CODE, 0x0, 0xFFFFFFFF, KGDT_TYPE_CODE, KGDT_DPL_SYSTEM, 2); SetGdtEntry(ProcessorBlock->GdtBase, KGDT_R0_CODE, 0x0, 0xFFFFFFFF, KGDT_TYPE_CODE, KGDT_DPL_SYSTEM, 2);
ArpSetGdtEntry(ProcessorBlock->GdtBase, KGDT_R0_DATA, 0x0, 0xFFFFFFFF, KGDT_TYPE_DATA, KGDT_DPL_SYSTEM, 2); SetGdtEntry(ProcessorBlock->GdtBase, KGDT_R0_DATA, 0x0, 0xFFFFFFFF, KGDT_TYPE_DATA, KGDT_DPL_SYSTEM, 2);
ArpSetGdtEntry(ProcessorBlock->GdtBase, KGDT_R3_CODE, 0x0, 0xFFFFFFFF, KGDT_TYPE_CODE, KGDT_DPL_USER, 2); SetGdtEntry(ProcessorBlock->GdtBase, KGDT_R3_CODE, 0x0, 0xFFFFFFFF, KGDT_TYPE_CODE, KGDT_DPL_USER, 2);
ArpSetGdtEntry(ProcessorBlock->GdtBase, KGDT_R3_DATA, 0x0, 0xFFFFFFFF, KGDT_TYPE_DATA, KGDT_DPL_USER, 2); SetGdtEntry(ProcessorBlock->GdtBase, KGDT_R3_DATA, 0x0, 0xFFFFFFFF, KGDT_TYPE_DATA, KGDT_DPL_USER, 2);
ArpSetGdtEntry(ProcessorBlock->GdtBase, KGDT_SYS_TSS, (ULONG_PTR)ProcessorBlock->TssBase, sizeof(KTSS) - 1, I686_TSS, KGDT_DPL_SYSTEM, 0); SetGdtEntry(ProcessorBlock->GdtBase, KGDT_SYS_TSS, (ULONG_PTR)ProcessorBlock->TssBase, sizeof(KTSS) - 1, I686_TSS, KGDT_DPL_SYSTEM, 0);
ArpSetGdtEntry(ProcessorBlock->GdtBase, KGDT_R0_PB, (ULONG_PTR)ProcessorBlock, sizeof(KPROCESSOR_BLOCK), KGDT_TYPE_DATA, KGDT_DPL_SYSTEM, 2); SetGdtEntry(ProcessorBlock->GdtBase, KGDT_R0_PB, (ULONG_PTR)ProcessorBlock, sizeof(KPROCESSOR_BLOCK), KGDT_TYPE_DATA, KGDT_DPL_SYSTEM, 2);
ArpSetGdtEntry(ProcessorBlock->GdtBase, KGDT_R3_TEB, 0x0, 0xFFF, KGDT_TYPE_DATA | KGDT_DESCRIPTOR_ACCESSED, KGDT_DPL_USER, 2); SetGdtEntry(ProcessorBlock->GdtBase, KGDT_R3_TEB, 0x0, 0xFFF, KGDT_TYPE_DATA | KGDT_DESCRIPTOR_ACCESSED, KGDT_DPL_USER, 2);
ArpSetGdtEntry(ProcessorBlock->GdtBase, KGDT_VDM_TILE, 0x0400, 0xFFFF, KGDT_TYPE_DATA, KGDT_DPL_USER, 0); SetGdtEntry(ProcessorBlock->GdtBase, KGDT_VDM_TILE, 0x0400, 0xFFFF, KGDT_TYPE_DATA, KGDT_DPL_USER, 0);
ArpSetGdtEntry(ProcessorBlock->GdtBase, KGDT_R0_LDT, 0x0, 0x0, KGDT_TYPE_NONE, KGDT_DPL_SYSTEM, 0); SetGdtEntry(ProcessorBlock->GdtBase, KGDT_R0_LDT, 0x0, 0x0, KGDT_TYPE_NONE, KGDT_DPL_SYSTEM, 0);
ArpSetGdtEntry(ProcessorBlock->GdtBase, KGDT_DF_TSS, 0x20000, 0xFFFF, I686_TSS, KGDT_DPL_SYSTEM, 0); SetGdtEntry(ProcessorBlock->GdtBase, KGDT_DF_TSS, 0x20000, 0xFFFF, I686_TSS, KGDT_DPL_SYSTEM, 0);
ArpSetGdtEntry(ProcessorBlock->GdtBase, KGDT_NMI_TSS, 0x20000, 0xFFFF, KGDT_TYPE_CODE, KGDT_DPL_SYSTEM, 0); SetGdtEntry(ProcessorBlock->GdtBase, KGDT_NMI_TSS, 0x20000, 0xFFFF, KGDT_TYPE_CODE, KGDT_DPL_SYSTEM, 0);
ArpSetGdtEntry(ProcessorBlock->GdtBase, KGDT_VDBS, 0xB8000, 0x3FFF, KGDT_TYPE_DATA, KGDT_DPL_SYSTEM, 0); SetGdtEntry(ProcessorBlock->GdtBase, KGDT_VDBS, 0xB8000, 0x3FFF, KGDT_TYPE_DATA, KGDT_DPL_SYSTEM, 0);
ArpSetGdtEntry(ProcessorBlock->GdtBase, KGDT_ALIAS, (ULONG_PTR)ProcessorBlock->GdtBase, (GDT_ENTRIES * sizeof(KGDTENTRY)) - 1, KGDT_TYPE_DATA, KGDT_DPL_SYSTEM, 0); SetGdtEntry(ProcessorBlock->GdtBase, KGDT_ALIAS, (ULONG_PTR)ProcessorBlock->GdtBase, (GDT_ENTRIES * sizeof(KGDTENTRY)) - 1, KGDT_TYPE_DATA, KGDT_DPL_SYSTEM, 0);
} }
/** /**
@@ -233,7 +216,7 @@ ArpInitializeGdt(IN PKPROCESSOR_BLOCK ProcessorBlock)
*/ */
XTAPI XTAPI
VOID VOID
ArpInitializeIdt(IN PKPROCESSOR_BLOCK ProcessorBlock) ProcSup::InitializeIdt(IN PKPROCESSOR_BLOCK ProcessorBlock)
{ {
UINT Vector; UINT Vector;
@@ -241,34 +224,34 @@ ArpInitializeIdt(IN PKPROCESSOR_BLOCK ProcessorBlock)
for(Vector = 0; Vector < IDT_ENTRIES; Vector++) for(Vector = 0; Vector < IDT_ENTRIES; Vector++)
{ {
/* Set the IDT to handle unexpected interrupts */ /* Set the IDT to handle unexpected interrupts */
ArpSetIdtGate(ProcessorBlock->IdtBase, Vector, ArpHandleTrapFF, KGDT_R0_CODE, 0, KIDT_INTERRUPT | KIDT_ACCESS_RING0); SetIdtGate(ProcessorBlock->IdtBase, Vector, (PVOID)ArTrap0xFF, KGDT_R0_CODE, 0, KIDT_INTERRUPT | KIDT_ACCESS_RING0);
} }
/* Setup IDT handlers for known interrupts and traps */ /* Setup IDT handlers for known interrupts and traps */
ArpSetIdtGate(ProcessorBlock->IdtBase, 0x00, ArpTrap0x00, KGDT_R0_CODE, 0, KIDT_INTERRUPT | KIDT_ACCESS_RING0); SetIdtGate(ProcessorBlock->IdtBase, 0x00, (PVOID)ArTrap0x00, KGDT_R0_CODE, 0, KIDT_INTERRUPT | KIDT_ACCESS_RING0);
ArpSetIdtGate(ProcessorBlock->IdtBase, 0x01, ArpTrap0x01, KGDT_R0_CODE, 0, KIDT_INTERRUPT | KIDT_ACCESS_RING0); SetIdtGate(ProcessorBlock->IdtBase, 0x01, (PVOID)ArTrap0x01, KGDT_R0_CODE, 0, KIDT_INTERRUPT | KIDT_ACCESS_RING0);
ArpSetIdtGate(ProcessorBlock->IdtBase, 0x02, ArpTrap0x02, KGDT_R0_CODE, 0, KIDT_INTERRUPT | KIDT_ACCESS_RING0); SetIdtGate(ProcessorBlock->IdtBase, 0x02, (PVOID)ArTrap0x02, KGDT_R0_CODE, 0, KIDT_INTERRUPT | KIDT_ACCESS_RING0);
ArpSetIdtGate(ProcessorBlock->IdtBase, 0x03, ArpTrap0x03, KGDT_R0_CODE, 0, KIDT_INTERRUPT | KIDT_ACCESS_RING3); SetIdtGate(ProcessorBlock->IdtBase, 0x03, (PVOID)ArTrap0x03, KGDT_R0_CODE, 0, KIDT_INTERRUPT | KIDT_ACCESS_RING3);
ArpSetIdtGate(ProcessorBlock->IdtBase, 0x04, ArpTrap0x04, KGDT_R0_CODE, 0, KIDT_INTERRUPT | KIDT_ACCESS_RING3); SetIdtGate(ProcessorBlock->IdtBase, 0x04, (PVOID)ArTrap0x04, KGDT_R0_CODE, 0, KIDT_INTERRUPT | KIDT_ACCESS_RING3);
ArpSetIdtGate(ProcessorBlock->IdtBase, 0x05, ArpTrap0x05, KGDT_R0_CODE, 0, KIDT_INTERRUPT | KIDT_ACCESS_RING0); SetIdtGate(ProcessorBlock->IdtBase, 0x05, (PVOID)ArTrap0x05, KGDT_R0_CODE, 0, KIDT_INTERRUPT | KIDT_ACCESS_RING0);
ArpSetIdtGate(ProcessorBlock->IdtBase, 0x06, ArpTrap0x06, KGDT_R0_CODE, 0, KIDT_INTERRUPT | KIDT_ACCESS_RING0); SetIdtGate(ProcessorBlock->IdtBase, 0x06, (PVOID)ArTrap0x06, KGDT_R0_CODE, 0, KIDT_INTERRUPT | KIDT_ACCESS_RING0);
ArpSetIdtGate(ProcessorBlock->IdtBase, 0x07, ArpTrap0x07, KGDT_R0_CODE, 0, KIDT_INTERRUPT | KIDT_ACCESS_RING0); SetIdtGate(ProcessorBlock->IdtBase, 0x07, (PVOID)ArTrap0x07, KGDT_R0_CODE, 0, KIDT_INTERRUPT | KIDT_ACCESS_RING0);
ArpSetIdtGate(ProcessorBlock->IdtBase, 0x08, ArpTrap0x08, KGDT_R0_CODE, 0, KIDT_INTERRUPT | KIDT_ACCESS_RING0); SetIdtGate(ProcessorBlock->IdtBase, 0x08, (PVOID)ArTrap0x08, KGDT_R0_CODE, 0, KIDT_INTERRUPT | KIDT_ACCESS_RING0);
ArpSetIdtGate(ProcessorBlock->IdtBase, 0x09, ArpTrap0x09, KGDT_R0_CODE, 0, KIDT_INTERRUPT | KIDT_ACCESS_RING0); SetIdtGate(ProcessorBlock->IdtBase, 0x09, (PVOID)ArTrap0x09, KGDT_R0_CODE, 0, KIDT_INTERRUPT | KIDT_ACCESS_RING0);
ArpSetIdtGate(ProcessorBlock->IdtBase, 0x0A, ArpTrap0x0A, KGDT_R0_CODE, 0, KIDT_INTERRUPT | KIDT_ACCESS_RING0); SetIdtGate(ProcessorBlock->IdtBase, 0x0A, (PVOID)ArTrap0x0A, KGDT_R0_CODE, 0, KIDT_INTERRUPT | KIDT_ACCESS_RING0);
ArpSetIdtGate(ProcessorBlock->IdtBase, 0x0B, ArpTrap0x0B, KGDT_R0_CODE, 0, KIDT_INTERRUPT | KIDT_ACCESS_RING0); SetIdtGate(ProcessorBlock->IdtBase, 0x0B, (PVOID)ArTrap0x0B, KGDT_R0_CODE, 0, KIDT_INTERRUPT | KIDT_ACCESS_RING0);
ArpSetIdtGate(ProcessorBlock->IdtBase, 0x0C, ArpTrap0x0C, KGDT_R0_CODE, 0, KIDT_INTERRUPT | KIDT_ACCESS_RING0); SetIdtGate(ProcessorBlock->IdtBase, 0x0C, (PVOID)ArTrap0x0C, KGDT_R0_CODE, 0, KIDT_INTERRUPT | KIDT_ACCESS_RING0);
ArpSetIdtGate(ProcessorBlock->IdtBase, 0x0D, ArpTrap0x0D, KGDT_R0_CODE, 0, KIDT_INTERRUPT | KIDT_ACCESS_RING0); SetIdtGate(ProcessorBlock->IdtBase, 0x0D, (PVOID)ArTrap0x0D, KGDT_R0_CODE, 0, KIDT_INTERRUPT | KIDT_ACCESS_RING0);
ArpSetIdtGate(ProcessorBlock->IdtBase, 0x0E, ArpTrap0x0E, KGDT_R0_CODE, 0, KIDT_INTERRUPT | KIDT_ACCESS_RING0); SetIdtGate(ProcessorBlock->IdtBase, 0x0E, (PVOID)ArTrap0x0E, KGDT_R0_CODE, 0, KIDT_INTERRUPT | KIDT_ACCESS_RING0);
ArpSetIdtGate(ProcessorBlock->IdtBase, 0x10, ArpTrap0x10, KGDT_R0_CODE, 0, KIDT_INTERRUPT | KIDT_ACCESS_RING0); SetIdtGate(ProcessorBlock->IdtBase, 0x10, (PVOID)ArTrap0x10, KGDT_R0_CODE, 0, KIDT_INTERRUPT | KIDT_ACCESS_RING0);
ArpSetIdtGate(ProcessorBlock->IdtBase, 0x11, ArpTrap0x11, KGDT_R0_CODE, 0, KIDT_INTERRUPT | KIDT_ACCESS_RING0); SetIdtGate(ProcessorBlock->IdtBase, 0x11, (PVOID)ArTrap0x11, KGDT_R0_CODE, 0, KIDT_INTERRUPT | KIDT_ACCESS_RING0);
ArpSetIdtGate(ProcessorBlock->IdtBase, 0x12, ArpTrap0x12, KGDT_R0_CODE, 0, KIDT_INTERRUPT | KIDT_ACCESS_RING0); SetIdtGate(ProcessorBlock->IdtBase, 0x12, (PVOID)ArTrap0x12, KGDT_R0_CODE, 0, KIDT_INTERRUPT | KIDT_ACCESS_RING0);
ArpSetIdtGate(ProcessorBlock->IdtBase, 0x13, ArpTrap0x13, KGDT_R0_CODE, 0, KIDT_INTERRUPT | KIDT_ACCESS_RING0); SetIdtGate(ProcessorBlock->IdtBase, 0x13, (PVOID)ArTrap0x13, KGDT_R0_CODE, 0, KIDT_INTERRUPT | KIDT_ACCESS_RING0);
ArpSetIdtGate(ProcessorBlock->IdtBase, 0x2A, ArpTrap0x2A, KGDT_R0_CODE, 0, KIDT_INTERRUPT | KIDT_ACCESS_RING3); SetIdtGate(ProcessorBlock->IdtBase, 0x2A, (PVOID)ArTrap0x2A, KGDT_R0_CODE, 0, KIDT_INTERRUPT | KIDT_ACCESS_RING3);
ArpSetIdtGate(ProcessorBlock->IdtBase, 0x2B, ArpTrap0x2B, KGDT_R0_CODE, 0, KIDT_INTERRUPT | KIDT_ACCESS_RING3); SetIdtGate(ProcessorBlock->IdtBase, 0x2B, (PVOID)ArTrap0x2B, KGDT_R0_CODE, 0, KIDT_INTERRUPT | KIDT_ACCESS_RING3);
ArpSetIdtGate(ProcessorBlock->IdtBase, 0x2C, ArpTrap0x2C, KGDT_R0_CODE, 0, KIDT_INTERRUPT | KIDT_ACCESS_RING3); SetIdtGate(ProcessorBlock->IdtBase, 0x2C, (PVOID)ArTrap0x2C, KGDT_R0_CODE, 0, KIDT_INTERRUPT | KIDT_ACCESS_RING3);
ArpSetIdtGate(ProcessorBlock->IdtBase, 0x2D, ArpTrap0x2D, KGDT_R0_CODE, 0, KIDT_INTERRUPT | KIDT_ACCESS_RING3); SetIdtGate(ProcessorBlock->IdtBase, 0x2D, (PVOID)ArTrap0x2D, KGDT_R0_CODE, 0, KIDT_INTERRUPT | KIDT_ACCESS_RING3);
ArpSetIdtGate(ProcessorBlock->IdtBase, 0x2E, ArpTrap0x2E, KGDT_R0_CODE, 0, KIDT_INTERRUPT | KIDT_ACCESS_RING3); SetIdtGate(ProcessorBlock->IdtBase, 0x2E, (PVOID)ArTrap0x2E, KGDT_R0_CODE, 0, KIDT_INTERRUPT | KIDT_ACCESS_RING3);
} }
/** /**
@@ -292,18 +275,18 @@ ArpInitializeIdt(IN PKPROCESSOR_BLOCK ProcessorBlock)
*/ */
XTAPI XTAPI
VOID VOID
ArpInitializeProcessorBlock(OUT PKPROCESSOR_BLOCK ProcessorBlock, ProcSup::InitializeProcessorBlock(OUT PKPROCESSOR_BLOCK ProcessorBlock,
IN PKGDTENTRY Gdt, IN PKGDTENTRY Gdt,
IN PKIDTENTRY Idt, IN PKIDTENTRY Idt,
IN PKTSS Tss, IN PKTSS Tss,
IN PVOID DpcStack) IN PVOID DpcStack)
{ {
/* Set processor block and processor control block */ /* Set processor block and processor control block */
ProcessorBlock->Self = ProcessorBlock; ProcessorBlock->Self = ProcessorBlock;
ProcessorBlock->CurrentPrcb = &ProcessorBlock->Prcb; ProcessorBlock->CurrentPrcb = &ProcessorBlock->Prcb;
/* Set GDT, IDT and TSS descriptors */ /* Set GDT, IDT and TSS descriptors */
ProcessorBlock->GdtBase = Gdt; ProcessorBlock->GdtBase = (PKGDTENTRY)(PVOID)Gdt;
ProcessorBlock->IdtBase = Idt; ProcessorBlock->IdtBase = Idt;
ProcessorBlock->TssBase = Tss; ProcessorBlock->TssBase = Tss;
@@ -320,10 +303,10 @@ ArpInitializeProcessorBlock(OUT PKPROCESSOR_BLOCK ProcessorBlock,
ProcessorBlock->Prcb.ProcessorState.SpecialRegisters.KernelDr7 = 0; ProcessorBlock->Prcb.ProcessorState.SpecialRegisters.KernelDr7 = 0;
/* Set process and thread information */ /* Set process and thread information */
ProcessorBlock->Prcb.CurrentThread = &KeInitialThread.ThreadControlBlock; ProcessorBlock->Prcb.CurrentThread = &(KE::KThread::GetInitialThread())->ThreadControlBlock;
ProcessorBlock->Prcb.CurrentThread->ApcState.Process = &KeInitialProcess.ProcessControlBlock; ProcessorBlock->Prcb.CurrentThread->ApcState.Process = &(KE::KProcess::GetInitialProcess())->ProcessControlBlock;
ProcessorBlock->Prcb.IdleThread = &KeInitialThread.ThreadControlBlock; ProcessorBlock->Prcb.IdleThread = &(KE::KThread::GetInitialThread())->ThreadControlBlock;
ProcessorBlock->Prcb.NextThread = NULL; ProcessorBlock->Prcb.NextThread = nullptr;
/* Set initial runlevel */ /* Set initial runlevel */
ProcessorBlock->RunLevel = PASSIVE_LEVEL; ProcessorBlock->RunLevel = PASSIVE_LEVEL;
@@ -338,13 +321,13 @@ ArpInitializeProcessorBlock(OUT PKPROCESSOR_BLOCK ProcessorBlock,
*/ */
XTAPI XTAPI
VOID VOID
ArpInitializeProcessorRegisters(VOID) ProcSup::InitializeProcessorRegisters(VOID)
{ {
/* Clear EFLAGS register */ /* Clear EFLAGS register */
ArWriteEflagsRegister(0); CpuFunc::WriteEflagsRegister(0);
/* Enable write-protection */ /* Enable write-protection */
ArWriteControlRegister(0, ArReadControlRegister(0) | CR0_WP); CpuFunc::WriteControlRegister(0, CpuFunc::ReadControlRegister(0) | CR0_WP);
} }
/** /**
@@ -374,12 +357,12 @@ ArpInitializeProcessorRegisters(VOID)
*/ */
XTAPI XTAPI
VOID VOID
ArpInitializeProcessorStructures(IN PVOID ProcessorStructures, ProcSup::InitializeProcessorStructures(IN PVOID ProcessorStructures,
OUT PKGDTENTRY *Gdt, OUT PKGDTENTRY *Gdt,
OUT PKTSS *Tss, OUT PKTSS *Tss,
OUT PKPROCESSOR_BLOCK *ProcessorBlock, OUT PKPROCESSOR_BLOCK *ProcessorBlock,
OUT PVOID *KernelBootStack, OUT PVOID *KernelBootStack,
OUT PVOID *KernelFaultStack) OUT PVOID *KernelFaultStack)
{ {
UINT_PTR Address; UINT_PTR Address;
@@ -394,15 +377,15 @@ ArpInitializeProcessorStructures(IN PVOID ProcessorStructures,
*KernelFaultStack = (PVOID)Address; *KernelFaultStack = (PVOID)Address;
/* Assign a space for GDT and advance */ /* Assign a space for GDT and advance */
*Gdt = (PVOID)Address; *Gdt = (PKGDTENTRY)(PVOID)Address;
Address += sizeof(ArInitialGdt); Address += sizeof(ArInitialGdt);
/* Assign a space for Processor Block and advance */ /* Assign a space for Processor Block and advance */
*ProcessorBlock = (PVOID)Address; *ProcessorBlock = (PKPROCESSOR_BLOCK)(PVOID)Address;
Address += sizeof(ArInitialProcessorBlock); Address += sizeof(ArInitialProcessorBlock);
/* Assign a space for TSS */ /* Assign a space for TSS */
*Tss = (PVOID)Address; *Tss = (PKTSS)(PVOID)Address;
} }
/** /**
@@ -414,13 +397,13 @@ ArpInitializeProcessorStructures(IN PVOID ProcessorStructures,
*/ */
XTAPI XTAPI
VOID VOID
ArpInitializeSegments(VOID) ProcSup::InitializeSegments(VOID)
{ {
/* Initialize segments */ /* Initialize segments */
ArLoadSegment(SEGMENT_CS, KGDT_R0_CODE); CpuFunc::LoadSegment(SEGMENT_CS, KGDT_R0_CODE);
ArLoadSegment(SEGMENT_DS, KGDT_R3_DATA | RPL_MASK); CpuFunc::LoadSegment(SEGMENT_DS, KGDT_R3_DATA | RPL_MASK);
ArLoadSegment(SEGMENT_ES, KGDT_R3_DATA | RPL_MASK); CpuFunc::LoadSegment(SEGMENT_ES, KGDT_R3_DATA | RPL_MASK);
ArLoadSegment(SEGMENT_FS, KGDT_R0_PB); CpuFunc::LoadSegment(SEGMENT_FS, KGDT_R0_PB);
} }
/** /**
@@ -435,9 +418,9 @@ ArpInitializeSegments(VOID)
*/ */
XTAPI XTAPI
VOID VOID
ArpInitializeTss(IN PKPROCESSOR_BLOCK ProcessorBlock, ProcSup::InitializeTss(IN PKPROCESSOR_BLOCK ProcessorBlock,
IN PVOID KernelBootStack, IN PVOID KernelBootStack,
IN PVOID KernelFaultStack) IN PVOID KernelFaultStack)
{ {
/* Clear I/O map */ /* Clear I/O map */
RtlSetMemory(ProcessorBlock->TssBase->IoMaps[0].IoMap, 0xFF, IOPM_FULL_SIZE); RtlSetMemory(ProcessorBlock->TssBase->IoMaps[0].IoMap, 0xFF, IOPM_FULL_SIZE);
@@ -468,8 +451,8 @@ ArpInitializeTss(IN PKPROCESSOR_BLOCK ProcessorBlock,
ProcessorBlock->TssBase->Ss0 = KGDT_R0_DATA; ProcessorBlock->TssBase->Ss0 = KGDT_R0_DATA;
/* Initialize task gates for DoubleFault and NMI traps */ /* Initialize task gates for DoubleFault and NMI traps */
ArpSetDoubleFaultTssEntry(ProcessorBlock, KernelFaultStack); SetDoubleFaultTssEntry(ProcessorBlock, KernelFaultStack);
ArpSetNonMaskableInterruptTssEntry(ProcessorBlock, KernelFaultStack); SetNonMaskableInterruptTssEntry(ProcessorBlock, KernelFaultStack);
} }
/** /**
@@ -484,8 +467,8 @@ ArpInitializeTss(IN PKPROCESSOR_BLOCK ProcessorBlock,
*/ */
XTAPI XTAPI
VOID VOID
ArpSetDoubleFaultTssEntry(IN PKPROCESSOR_BLOCK ProcessorBlock, ProcSup::SetDoubleFaultTssEntry(IN PKPROCESSOR_BLOCK ProcessorBlock,
IN PVOID KernelFaultStack) IN PVOID KernelFaultStack)
{ {
PKGDTENTRY TaskGateEntry, TssEntry; PKGDTENTRY TaskGateEntry, TssEntry;
PKTSS Tss; PKTSS Tss;
@@ -498,20 +481,20 @@ ArpSetDoubleFaultTssEntry(IN PKPROCESSOR_BLOCK ProcessorBlock,
((PKIDTENTRY)TaskGateEntry)->Selector = KGDT_DF_TSS; ((PKIDTENTRY)TaskGateEntry)->Selector = KGDT_DF_TSS;
/* Initialize DoubleFault TSS and set initial state */ /* Initialize DoubleFault TSS and set initial state */
Tss = (PKTSS)ArpDoubleFaultTss; Tss = (PKTSS)DoubleFaultTss;
Tss->IoMapBase = sizeof(KTSS); Tss->IoMapBase = sizeof(KTSS);
Tss->Flags = 0; Tss->Flags = 0;
Tss->LDT = KGDT_R0_LDT; Tss->LDT = KGDT_R0_LDT;
Tss->CR3 = ArReadControlRegister(3); Tss->CR3 = CpuFunc::ReadControlRegister(3);
Tss->Esp = (ULONG_PTR)KernelFaultStack; Tss->Esp = (ULONG_PTR)KernelFaultStack;
Tss->Esp0 = (ULONG_PTR)KernelFaultStack; Tss->Esp0 = (ULONG_PTR)KernelFaultStack;
Tss->Eip = PtrToUlong(ArpHandleTrap08); Tss->Eip = PtrToUlong(ArTrap0x08);
Tss->Cs = KGDT_R0_CODE; Tss->Cs = KGDT_R0_CODE;
Tss->Ds = KGDT_R3_DATA | RPL_MASK; Tss->Ds = KGDT_R3_DATA | RPL_MASK;
Tss->Es = KGDT_R3_DATA | RPL_MASK; Tss->Es = KGDT_R3_DATA | RPL_MASK;
Tss->Fs = KGDT_R0_PB; Tss->Fs = KGDT_R0_PB;
Tss->Ss0 = KGDT_R0_DATA; Tss->Ss0 = KGDT_R0_DATA;
ArStoreSegment(SEGMENT_SS, (PVOID)&Tss->Ss); CpuFunc::StoreSegment(SEGMENT_SS, (PVOID)&Tss->Ss);
/* Setup DoubleFault TSS entry in Global Descriptor Table */ /* Setup DoubleFault TSS entry in Global Descriptor Table */
TssEntry = (PKGDTENTRY)(&(ProcessorBlock->GdtBase[KGDT_DF_TSS / sizeof(KGDTENTRY)])); TssEntry = (PKGDTENTRY)(&(ProcessorBlock->GdtBase[KGDT_DF_TSS / sizeof(KGDTENTRY)]));
@@ -555,13 +538,13 @@ ArpSetDoubleFaultTssEntry(IN PKPROCESSOR_BLOCK ProcessorBlock,
*/ */
XTAPI XTAPI
VOID VOID
ArpSetGdtEntry(IN PKGDTENTRY Gdt, ProcSup::SetGdtEntry(IN PKGDTENTRY Gdt,
IN USHORT Selector, IN USHORT Selector,
IN ULONG_PTR Base, IN ULONG_PTR Base,
IN ULONG Limit, IN ULONG Limit,
IN UCHAR Type, IN UCHAR Type,
IN UCHAR Dpl, IN UCHAR Dpl,
IN UCHAR SegmentMode) IN UCHAR SegmentMode)
{ {
PKGDTENTRY GdtEntry; PKGDTENTRY GdtEntry;
UCHAR Granularity; UCHAR Granularity;
@@ -601,6 +584,39 @@ ArpSetGdtEntry(IN PKGDTENTRY Gdt,
GdtEntry->Bits.Type = (Type & 0x1F); GdtEntry->Bits.Type = (Type & 0x1F);
} }
/**
* Updates an existing i686 GDT entry with new base address.
*
* @param Gdt
* Supplies a pointer to the GDT.
*
* @param Selector
* Specifies a segment selector of the GDT entry.
*
* @param Base
* Specifies a base address value of the descriptor.
*
* @return This routine does not return any value.
*
* @since XT 1.0
*/
XTAPI
VOID
ProcSup::SetGdtEntryBase(IN PKGDTENTRY Gdt,
IN USHORT Selector,
IN ULONG_PTR Base)
{
PKGDTENTRY GdtEntry;
/* Get GDT entry */
GdtEntry = (PKGDTENTRY)((ULONG_PTR)Gdt + (Selector & ~RPL_MASK));
/* Set new GDT descriptor base */
GdtEntry->BaseLow = (Base & 0xFFFF);
GdtEntry->Bytes.BaseMiddle = ((Base >> 16) & 0xFF);
GdtEntry->Bytes.BaseHigh = ((Base >> 24) & 0xFF);
}
/** /**
* Fills in a call, interrupt, task or trap gate entry. * Fills in a call, interrupt, task or trap gate entry.
* *
@@ -628,12 +644,12 @@ ArpSetGdtEntry(IN PKGDTENTRY Gdt,
*/ */
XTAPI XTAPI
VOID VOID
ArpSetIdtGate(IN PKIDTENTRY Idt, ProcSup::SetIdtGate(IN PKIDTENTRY Idt,
IN USHORT Vector, IN USHORT Vector,
IN PVOID Handler, IN PVOID Handler,
IN USHORT Selector, IN USHORT Selector,
IN USHORT Ist, IN USHORT Ist,
IN USHORT Access) IN USHORT Access)
{ {
/* Setup the gate */ /* Setup the gate */
Idt[Vector].Offset = (USHORT)((ULONG)Handler & 0xFFFF); Idt[Vector].Offset = (USHORT)((ULONG)Handler & 0xFFFF);
@@ -654,8 +670,8 @@ ArpSetIdtGate(IN PKIDTENTRY Idt,
*/ */
XTAPI XTAPI
VOID VOID
ArpSetNonMaskableInterruptTssEntry(IN PKPROCESSOR_BLOCK ProcessorBlock, ProcSup::SetNonMaskableInterruptTssEntry(IN PKPROCESSOR_BLOCK ProcessorBlock,
IN PVOID KernelFaultStack) IN PVOID KernelFaultStack)
{ {
PKGDTENTRY TaskGateEntry, TssEntry; PKGDTENTRY TaskGateEntry, TssEntry;
PKTSS Tss; PKTSS Tss;
@@ -668,19 +684,19 @@ ArpSetNonMaskableInterruptTssEntry(IN PKPROCESSOR_BLOCK ProcessorBlock,
((PKIDTENTRY)TaskGateEntry)->Selector = KGDT_NMI_TSS; ((PKIDTENTRY)TaskGateEntry)->Selector = KGDT_NMI_TSS;
/* Initialize NMI TSS and set initial state */ /* Initialize NMI TSS and set initial state */
Tss = (PKTSS)ArpNonMaskableInterruptTss; Tss = (PKTSS)NonMaskableInterruptTss;
Tss->IoMapBase = sizeof(KTSS); Tss->IoMapBase = sizeof(KTSS);
Tss->Flags = 0; Tss->Flags = 0;
Tss->LDT = KGDT_R0_LDT; Tss->LDT = KGDT_R0_LDT;
Tss->CR3 = ArReadControlRegister(3); Tss->CR3 = ArReadControlRegister(3);
Tss->Esp = (ULONG_PTR)KernelFaultStack; Tss->Esp = (ULONG_PTR)KernelFaultStack;
Tss->Esp0 = (ULONG_PTR)KernelFaultStack; Tss->Esp0 = (ULONG_PTR)KernelFaultStack;
Tss->Eip = PtrToUlong(ArpHandleTrap02); Tss->Eip = PtrToUlong(ArTrap0x02);
Tss->Cs = KGDT_R0_CODE; Tss->Cs = KGDT_R0_CODE;
Tss->Ds = KGDT_R3_DATA | RPL_MASK; Tss->Ds = KGDT_R3_DATA | RPL_MASK;
Tss->Es = KGDT_R3_DATA | RPL_MASK; Tss->Es = KGDT_R3_DATA | RPL_MASK;
Tss->Fs = KGDT_R0_PB; Tss->Fs = KGDT_R0_PB;
ArStoreSegment(SEGMENT_SS, (PVOID)&Tss->Ss); CpuFunc::StoreSegment(SEGMENT_SS, (PVOID)&Tss->Ss);
/* Setup NMI TSS entry in Global Descriptor Table */ /* Setup NMI TSS entry in Global Descriptor Table */
TssEntry = (PKGDTENTRY)(&(ProcessorBlock->GdtBase[KGDT_NMI_TSS / sizeof(KGDTENTRY)])); TssEntry = (PKGDTENTRY)(&(ProcessorBlock->GdtBase[KGDT_NMI_TSS / sizeof(KGDTENTRY)]));
@@ -693,3 +709,24 @@ ArpSetNonMaskableInterruptTssEntry(IN PKPROCESSOR_BLOCK ProcessorBlock,
TssEntry->Bits.Present = 1; TssEntry->Bits.Present = 1;
TssEntry->Bits.Type = I686_TSS; TssEntry->Bits.Type = I686_TSS;
} }
} /* namespace */
/* TEMPORARY FOR COMPATIBILITY WITH C CODE */
XTCLINK
XTAPI
PVOID
ArGetBootStack(VOID)
{
return AR::ProcSup::GetBootStack();
}
/* TEMPORARY FOR COMPATIBILITY WITH C CODE */
XTCLINK
XTAPI
VOID
ArInitializeProcessor(IN PVOID ProcessorStructures)
{
AR::ProcSup::InitializeProcessor(ProcessorStructures);
}

View File

@@ -1,14 +1,18 @@
/** /**
* PROJECT: ExectOS * PROJECT: ExectOS
* COPYRIGHT: See COPYING.md in the top level directory * COPYRIGHT: See COPYING.md in the top level directory
* FILE: xtoskrnl/ar/i686/traps.c * FILE: xtoskrnl/ar/i686/traps.cc
* DESCRIPTION: I686 system traps * DESCRIPTION: I686 system traps
* DEVELOPERS: Rafal Kupiec <belliash@codingworkshop.eu.org> * DEVELOPERS: Rafal Kupiec <belliash@codingworkshop.eu.org>
*/ */
#include <xtos.h> #include <xtos.hh>
/* Architecture-specific Library */
namespace AR
{
/** /**
* Dispatches the trap provided by common trap handler. * Dispatches the trap provided by common trap handler.
* *
@@ -21,110 +25,110 @@
*/ */
XTCDECL XTCDECL
VOID VOID
ArpDispatchTrap(IN PKTRAP_FRAME TrapFrame) Traps::DispatchTrap(IN PKTRAP_FRAME TrapFrame)
{ {
/* Check vector and call appropriate handler */ /* Check vector and call appropriate handler */
switch(TrapFrame->Vector) switch(TrapFrame->Vector)
{ {
case 0x00: case 0x00:
/* Divide By Zero exception */ /* Divide By Zero exception */
ArpHandleTrap00(TrapFrame); HandleTrap00(TrapFrame);
break; break;
case 0x01: case 0x01:
/* Debug exception */ /* Debug exception */
ArpHandleTrap01(TrapFrame); HandleTrap01(TrapFrame);
break; break;
case 0x02: case 0x02:
/* Non-Maskable Interrupt (NMI) */ /* Non-Maskable Interrupt (NMI) */
ArpHandleTrap02(TrapFrame); HandleTrap02(TrapFrame);
break; break;
case 0x03: case 0x03:
/* INT3 instruction executed */ /* INT3 instruction executed */
ArpHandleTrap03(TrapFrame); HandleTrap03(TrapFrame);
break; break;
case 0x04: case 0x04:
/* Overflow exception */ /* Overflow exception */
ArpHandleTrap04(TrapFrame); HandleTrap04(TrapFrame);
break; break;
case 0x05: case 0x05:
/* Bound Range Exceeded exception */ /* Bound Range Exceeded exception */
ArpHandleTrap05(TrapFrame); HandleTrap05(TrapFrame);
break; break;
case 0x06: case 0x06:
/* Invalid Opcode exception */ /* Invalid Opcode exception */
ArpHandleTrap06(TrapFrame); HandleTrap06(TrapFrame);
break; break;
case 0x07: case 0x07:
/* Device Not Available exception */ /* Device Not Available exception */
ArpHandleTrap07(TrapFrame); HandleTrap07(TrapFrame);
break; break;
case 0x08: case 0x08:
/* Double Fault exception */ /* Double Fault exception */
ArpHandleTrap08(TrapFrame); HandleTrap08(TrapFrame);
break; break;
case 0x09: case 0x09:
/* Segment Overrun exception */ /* Segment Overrun exception */
ArpHandleTrap09(TrapFrame); HandleTrap09(TrapFrame);
break; break;
case 0x0A: case 0x0A:
/* Invalid TSS exception */ /* Invalid TSS exception */
ArpHandleTrap0A(TrapFrame); HandleTrap0A(TrapFrame);
break; break;
case 0x0B: case 0x0B:
/* Segment Not Present exception */ /* Segment Not Present exception */
ArpHandleTrap0B(TrapFrame); HandleTrap0B(TrapFrame);
break; break;
case 0x0C: case 0x0C:
/* Stack Segment Fault exception */ /* Stack Segment Fault exception */
ArpHandleTrap0C(TrapFrame); HandleTrap0C(TrapFrame);
break; break;
case 0x0D: case 0x0D:
/* General Protection Fault (GPF) exception*/ /* General Protection Fault (GPF) exception*/
ArpHandleTrap0D(TrapFrame); HandleTrap0D(TrapFrame);
break; break;
case 0x0E: case 0x0E:
/* Page Fault exception */ /* Page Fault exception */
ArpHandleTrap0E(TrapFrame); HandleTrap0E(TrapFrame);
break; break;
case 0x10: case 0x10:
/* X87 Floating-Point exception */ /* X87 Floating-Point exception */
ArpHandleTrap10(TrapFrame); HandleTrap10(TrapFrame);
break; break;
case 0x11: case 0x11:
/* Alignment Check exception */ /* Alignment Check exception */
ArpHandleTrap11(TrapFrame); HandleTrap11(TrapFrame);
break; break;
case 0x12: case 0x12:
/* Machine Check exception */ /* Machine Check exception */
ArpHandleTrap12(TrapFrame); HandleTrap12(TrapFrame);
break; break;
case 0x13: case 0x13:
/* SIMD Floating-Point exception */ /* SIMD Floating-Point exception */
ArpHandleTrap13(TrapFrame); HandleTrap13(TrapFrame);
break; break;
case 0x2A: case 0x2A:
/* Tick Count service request */ /* Tick Count service request */
ArpHandleTrap2A(TrapFrame); HandleTrap2A(TrapFrame);
break; break;
case 0x2B: case 0x2B:
/* User-mode callback return */ /* User-mode callback return */
ArpHandleTrap2B(TrapFrame); HandleTrap2B(TrapFrame);
break; break;
case 0x2C: case 0x2C:
/* Assertion raised */ /* Assertion raised */
ArpHandleTrap2C(TrapFrame); HandleTrap2C(TrapFrame);
break; break;
case 0x2D: case 0x2D:
/* Debug-Service-Request raised */ /* Debug-Service-Request raised */
ArpHandleTrap2D(TrapFrame); HandleTrap2D(TrapFrame);
break; break;
case 0x2E: case 0x2E:
/* System call service request */ /* System call service request */
ArpHandleTrap2E(TrapFrame); HandleTrap2E(TrapFrame);
break; break;
default: default:
/* Unknown/Unexpected trap */ /* Unknown/Unexpected trap */
ArpHandleTrapFF(TrapFrame); HandleTrapFF(TrapFrame);
break; break;
} }
} }
@@ -141,7 +145,7 @@ ArpDispatchTrap(IN PKTRAP_FRAME TrapFrame)
*/ */
XTCDECL XTCDECL
VOID VOID
ArpHandleTrap00(IN PKTRAP_FRAME TrapFrame) Traps::HandleTrap00(IN PKTRAP_FRAME TrapFrame)
{ {
DebugPrint(L"Handled Division-By-Zero Error (0x00)!\n"); DebugPrint(L"Handled Division-By-Zero Error (0x00)!\n");
for(;;); for(;;);
@@ -159,7 +163,7 @@ ArpHandleTrap00(IN PKTRAP_FRAME TrapFrame)
*/ */
XTCDECL XTCDECL
VOID VOID
ArpHandleTrap01(IN PKTRAP_FRAME TrapFrame) Traps::HandleTrap01(IN PKTRAP_FRAME TrapFrame)
{ {
DebugPrint(L"Handled Debug exception (0x01)!\n"); DebugPrint(L"Handled Debug exception (0x01)!\n");
for(;;); for(;;);
@@ -177,7 +181,7 @@ ArpHandleTrap01(IN PKTRAP_FRAME TrapFrame)
*/ */
XTCDECL XTCDECL
VOID VOID
ArpHandleTrap02(IN PKTRAP_FRAME TrapFrame) Traps::HandleTrap02(IN PKTRAP_FRAME TrapFrame)
{ {
DebugPrint(L"Handled Non-Maskable-Interrupt (0x02)!\n"); DebugPrint(L"Handled Non-Maskable-Interrupt (0x02)!\n");
for(;;); for(;;);
@@ -195,7 +199,7 @@ ArpHandleTrap02(IN PKTRAP_FRAME TrapFrame)
*/ */
XTCDECL XTCDECL
VOID VOID
ArpHandleTrap03(IN PKTRAP_FRAME TrapFrame) Traps::HandleTrap03(IN PKTRAP_FRAME TrapFrame)
{ {
DebugPrint(L"Handled INT3 (0x03)!\n"); DebugPrint(L"Handled INT3 (0x03)!\n");
for(;;); for(;;);
@@ -213,7 +217,7 @@ ArpHandleTrap03(IN PKTRAP_FRAME TrapFrame)
*/ */
XTCDECL XTCDECL
VOID VOID
ArpHandleTrap04(IN PKTRAP_FRAME TrapFrame) Traps::HandleTrap04(IN PKTRAP_FRAME TrapFrame)
{ {
DebugPrint(L"Handled Overflow exception (0x04)!\n"); DebugPrint(L"Handled Overflow exception (0x04)!\n");
for(;;); for(;;);
@@ -231,7 +235,7 @@ ArpHandleTrap04(IN PKTRAP_FRAME TrapFrame)
*/ */
XTCDECL XTCDECL
VOID VOID
ArpHandleTrap05(IN PKTRAP_FRAME TrapFrame) Traps::HandleTrap05(IN PKTRAP_FRAME TrapFrame)
{ {
DebugPrint(L"Handled Bound-Range-Exceeded exception (0x05)!\n"); DebugPrint(L"Handled Bound-Range-Exceeded exception (0x05)!\n");
for(;;); for(;;);
@@ -249,7 +253,7 @@ ArpHandleTrap05(IN PKTRAP_FRAME TrapFrame)
*/ */
XTCDECL XTCDECL
VOID VOID
ArpHandleTrap06(IN PKTRAP_FRAME TrapFrame) Traps::HandleTrap06(IN PKTRAP_FRAME TrapFrame)
{ {
DebugPrint(L"Handled Invalid Opcode exception (0x06)!\n"); DebugPrint(L"Handled Invalid Opcode exception (0x06)!\n");
for(;;); for(;;);
@@ -267,7 +271,7 @@ ArpHandleTrap06(IN PKTRAP_FRAME TrapFrame)
*/ */
XTCDECL XTCDECL
VOID VOID
ArpHandleTrap07(IN PKTRAP_FRAME TrapFrame) Traps::HandleTrap07(IN PKTRAP_FRAME TrapFrame)
{ {
DebugPrint(L"Handled Device Not Available exception (0x07)!\n"); DebugPrint(L"Handled Device Not Available exception (0x07)!\n");
for(;;); for(;;);
@@ -285,7 +289,7 @@ ArpHandleTrap07(IN PKTRAP_FRAME TrapFrame)
*/ */
XTCDECL XTCDECL
VOID VOID
ArpHandleTrap08(IN PKTRAP_FRAME TrapFrame) Traps::HandleTrap08(IN PKTRAP_FRAME TrapFrame)
{ {
DebugPrint(L"Handled Double-Fault exception (0x08)!\n"); DebugPrint(L"Handled Double-Fault exception (0x08)!\n");
for(;;); for(;;);
@@ -303,7 +307,7 @@ ArpHandleTrap08(IN PKTRAP_FRAME TrapFrame)
*/ */
XTCDECL XTCDECL
VOID VOID
ArpHandleTrap09(IN PKTRAP_FRAME TrapFrame) Traps::HandleTrap09(IN PKTRAP_FRAME TrapFrame)
{ {
DebugPrint(L"Handled Segment-Overrun exception (0x09)!\n"); DebugPrint(L"Handled Segment-Overrun exception (0x09)!\n");
for(;;); for(;;);
@@ -321,7 +325,7 @@ ArpHandleTrap09(IN PKTRAP_FRAME TrapFrame)
*/ */
XTCDECL XTCDECL
VOID VOID
ArpHandleTrap0A(IN PKTRAP_FRAME TrapFrame) Traps::HandleTrap0A(IN PKTRAP_FRAME TrapFrame)
{ {
DebugPrint(L"Handled Invalid-TSS exception (0x0A)!\n"); DebugPrint(L"Handled Invalid-TSS exception (0x0A)!\n");
for(;;); for(;;);
@@ -339,7 +343,7 @@ ArpHandleTrap0A(IN PKTRAP_FRAME TrapFrame)
*/ */
XTCDECL XTCDECL
VOID VOID
ArpHandleTrap0B(IN PKTRAP_FRAME TrapFrame) Traps::HandleTrap0B(IN PKTRAP_FRAME TrapFrame)
{ {
DebugPrint(L"Handled Segment-Not-Present exception (0x0B)!\n"); DebugPrint(L"Handled Segment-Not-Present exception (0x0B)!\n");
for(;;); for(;;);
@@ -357,7 +361,7 @@ ArpHandleTrap0B(IN PKTRAP_FRAME TrapFrame)
*/ */
XTCDECL XTCDECL
VOID VOID
ArpHandleTrap0C(IN PKTRAP_FRAME TrapFrame) Traps::HandleTrap0C(IN PKTRAP_FRAME TrapFrame)
{ {
DebugPrint(L"Handled Stack-Segment-Fault exception (0x0C)!\n"); DebugPrint(L"Handled Stack-Segment-Fault exception (0x0C)!\n");
for(;;); for(;;);
@@ -375,7 +379,7 @@ ArpHandleTrap0C(IN PKTRAP_FRAME TrapFrame)
*/ */
XTCDECL XTCDECL
VOID VOID
ArpHandleTrap0D(IN PKTRAP_FRAME TrapFrame) Traps::HandleTrap0D(IN PKTRAP_FRAME TrapFrame)
{ {
DebugPrint(L"Handled General-Protection-Fault (0x0D)!\n"); DebugPrint(L"Handled General-Protection-Fault (0x0D)!\n");
for(;;); for(;;);
@@ -393,7 +397,7 @@ ArpHandleTrap0D(IN PKTRAP_FRAME TrapFrame)
*/ */
XTCDECL XTCDECL
VOID VOID
ArpHandleTrap0E(IN PKTRAP_FRAME TrapFrame) Traps::HandleTrap0E(IN PKTRAP_FRAME TrapFrame)
{ {
DebugPrint(L"Handled Page-Fault exception (0x0E)!\n"); DebugPrint(L"Handled Page-Fault exception (0x0E)!\n");
for(;;); for(;;);
@@ -411,7 +415,7 @@ ArpHandleTrap0E(IN PKTRAP_FRAME TrapFrame)
*/ */
XTCDECL XTCDECL
VOID VOID
ArpHandleTrap10(IN PKTRAP_FRAME TrapFrame) Traps::HandleTrap10(IN PKTRAP_FRAME TrapFrame)
{ {
DebugPrint(L"Handled x87 Floating-Point exception (0x10)!\n"); DebugPrint(L"Handled x87 Floating-Point exception (0x10)!\n");
for(;;); for(;;);
@@ -429,7 +433,7 @@ ArpHandleTrap10(IN PKTRAP_FRAME TrapFrame)
*/ */
XTCDECL XTCDECL
VOID VOID
ArpHandleTrap11(IN PKTRAP_FRAME TrapFrame) Traps::HandleTrap11(IN PKTRAP_FRAME TrapFrame)
{ {
DebugPrint(L"Handled Alignment-Check exception (0x11)!\n"); DebugPrint(L"Handled Alignment-Check exception (0x11)!\n");
for(;;); for(;;);
@@ -447,7 +451,7 @@ ArpHandleTrap11(IN PKTRAP_FRAME TrapFrame)
*/ */
XTCDECL XTCDECL
VOID VOID
ArpHandleTrap12(IN PKTRAP_FRAME TrapFrame) Traps::HandleTrap12(IN PKTRAP_FRAME TrapFrame)
{ {
DebugPrint(L"Handled Machine-Check exception (0x12)!\n"); DebugPrint(L"Handled Machine-Check exception (0x12)!\n");
for(;;); for(;;);
@@ -465,7 +469,7 @@ ArpHandleTrap12(IN PKTRAP_FRAME TrapFrame)
*/ */
XTCDECL XTCDECL
VOID VOID
ArpHandleTrap13(IN PKTRAP_FRAME TrapFrame) Traps::HandleTrap13(IN PKTRAP_FRAME TrapFrame)
{ {
DebugPrint(L"Handled SIMD Floating-Point exception (0x13)!\n"); DebugPrint(L"Handled SIMD Floating-Point exception (0x13)!\n");
for(;;); for(;;);
@@ -483,7 +487,7 @@ ArpHandleTrap13(IN PKTRAP_FRAME TrapFrame)
*/ */
XTCDECL XTCDECL
VOID VOID
ArpHandleTrap2A(IN PKTRAP_FRAME TrapFrame) Traps::HandleTrap2A(IN PKTRAP_FRAME TrapFrame)
{ {
DebugPrint(L"Unhandled Tick Count service request (0x2A)!\n"); DebugPrint(L"Unhandled Tick Count service request (0x2A)!\n");
} }
@@ -500,7 +504,7 @@ ArpHandleTrap2A(IN PKTRAP_FRAME TrapFrame)
*/ */
XTCDECL XTCDECL
VOID VOID
ArpHandleTrap2B(IN PKTRAP_FRAME TrapFrame) Traps::HandleTrap2B(IN PKTRAP_FRAME TrapFrame)
{ {
DebugPrint(L"Unhandled Callback return service request (0x2B)!\n"); DebugPrint(L"Unhandled Callback return service request (0x2B)!\n");
} }
@@ -517,7 +521,7 @@ ArpHandleTrap2B(IN PKTRAP_FRAME TrapFrame)
*/ */
XTCDECL XTCDECL
VOID VOID
ArpHandleTrap2C(IN PKTRAP_FRAME TrapFrame) Traps::HandleTrap2C(IN PKTRAP_FRAME TrapFrame)
{ {
DebugPrint(L"Handled Assertion (0x2C)!\n"); DebugPrint(L"Handled Assertion (0x2C)!\n");
for(;;); for(;;);
@@ -535,7 +539,7 @@ ArpHandleTrap2C(IN PKTRAP_FRAME TrapFrame)
*/ */
XTCDECL XTCDECL
VOID VOID
ArpHandleTrap2D(IN PKTRAP_FRAME TrapFrame) Traps::HandleTrap2D(IN PKTRAP_FRAME TrapFrame)
{ {
DebugPrint(L"Handled Debug-Service-Request (0x2D)!\n"); DebugPrint(L"Handled Debug-Service-Request (0x2D)!\n");
for(;;); for(;;);
@@ -553,7 +557,7 @@ ArpHandleTrap2D(IN PKTRAP_FRAME TrapFrame)
*/ */
XTCDECL XTCDECL
VOID VOID
ArpHandleTrap2E(IN PKTRAP_FRAME TrapFrame) Traps::HandleTrap2E(IN PKTRAP_FRAME TrapFrame)
{ {
DebugPrint(L"Unhandled system call (0x2E)!\n"); DebugPrint(L"Unhandled system call (0x2E)!\n");
} }
@@ -570,8 +574,28 @@ ArpHandleTrap2E(IN PKTRAP_FRAME TrapFrame)
*/ */
XTCDECL XTCDECL
VOID VOID
ArpHandleTrapFF(IN PKTRAP_FRAME TrapFrame) Traps::HandleTrapFF(IN PKTRAP_FRAME TrapFrame)
{ {
DebugPrint(L"Handled Unexpected-Interrupt (0xFF)!\n"); DebugPrint(L"Handled Unexpected-Interrupt (0xFF)!\n");
for(;;); for(;;);
} }
} /* namespace */
/**
* C-linkage wrapper for dispatching the trap provided by common trap handler.
*
* @param TrapFrame
* Supplies a kernel trap frame pushed by common trap handler on the stack.
*
* @return This routine does not return any value.
*
* @since XT 1.0
*/
XTCLINK
XTCDECL
VOID
ArDispatchTrap(IN PKTRAP_FRAME TrapFrame)
{
AR::Traps::DispatchTrap(TrapFrame);
}

112
xtoskrnl/ex/exports.cc Normal file
View File

@@ -0,0 +1,112 @@
/**
* PROJECT: ExectOS
* COPYRIGHT: See COPYING.md in the top level directory
* FILE: xtoskrnl/ex/exports.cc
* DESCRIPTION: C-compatible API wrappers for exported kernel functions
* DEVELOPERS: Aiken Harris <harraiken91@gmail.com>
*/
#include <xtos.hh>
/**
* Acquires the rundown protection for given descriptor.
*
* @param Descriptor
* Supplies a pointer to the rundown block descriptor.
*
* @return This routine returns TRUE if protection acquired successfully, or FALSE otherwise.
*
* @since NT 5.1
*/
XTFASTCALL
BOOLEAN
ExAcquireRundownProtection(IN PEX_RUNDOWN_REFERENCE Descriptor)
{
return EX::Rundown::AcquireProtection(Descriptor);
}
/**
* Marks the rundown descriptor as completed.
*
* @param Descriptor
* Supplies a pointer to the descriptor to be completed.
*
* @return This routine does not return any value.
*
* @since NT 5.1
*/
XTFASTCALL
VOID
ExCompleteRundownProtection(IN PEX_RUNDOWN_REFERENCE Descriptor)
{
EX::Rundown::CompleteProtection(Descriptor);
}
/**
* Initializes the rundown protection descriptor.
*
* @param Descriptor
* Supplies a pointer to the descriptor to be initialized.
*
* @return This routine does not return any value.
*
* @since NT 5.1
*/
XTFASTCALL
VOID
ExInitializeRundownProtection(IN PEX_RUNDOWN_REFERENCE Descriptor)
{
EX::Rundown::InitializeProtection(Descriptor);
}
/**
* Reinitializes the rundown protection structure after it has been completed.
*
* @param Descriptor
* Supplies a pointer to the descriptor to be reinitialized.
*
* @return This routine does not return any value.
*
* @since NT 5.1
*/
XTFASTCALL
VOID
ExReInitializeRundownProtection(IN PEX_RUNDOWN_REFERENCE Descriptor)
{
EX::Rundown::ReInitializeProtection(Descriptor);
}
/**
* Releases the rundown protection for given descriptor.
*
* @param Descriptor
* Supplies a pointer to the descriptor to be initialized.
*
* @return This routine does not return any value.
*
* @since NT 5.1
*/
XTFASTCALL
VOID
ExReleaseRundownProtection(IN PEX_RUNDOWN_REFERENCE Descriptor)
{
EX::Rundown::ReleaseProtection(Descriptor);
}
/**
* Waits until rundown protection calls are completed.
*
* @param Descriptor
* Supplies a pointer to the rundown block descriptor.
*
* @return This routine does not return any value.
*
* @since NT 5.1
*/
XTFASTCALL
VOID
ExWaitForRundownProtectionRelease(IN PEX_RUNDOWN_REFERENCE Descriptor)
{
EX::Rundown::WaitForProtectionRelease(Descriptor);
}

View File

@@ -1,14 +1,18 @@
/** /**
* PROJECT: ExectOS * PROJECT: ExectOS
* COPYRIGHT: See COPYING.md in the top level directory * COPYRIGHT: See COPYING.md in the top level directory
* FILE: xtoskrnl/ex/rundown.c * FILE: xtoskrnl/ex/rundown.cc
* DESCRIPTION: Rundown protection mechanism * DESCRIPTION: Rundown protection mechanism
* DEVELOPERS: Rafal Kupiec <belliash@codingworkshop.eu.org> * DEVELOPERS: Rafal Kupiec <belliash@codingworkshop.eu.org>
*/ */
#include <xtos.h> #include <xtos.hh>
/* Kernel Executive */
namespace EX
{
/** /**
* Acquires the rundown protection for given descriptor. * Acquires the rundown protection for given descriptor.
* *
@@ -21,7 +25,7 @@
*/ */
XTFASTCALL XTFASTCALL
BOOLEAN BOOLEAN
ExAcquireRundownProtection(IN PEX_RUNDOWN_REFERENCE Descriptor) Rundown::AcquireProtection(IN PEX_RUNDOWN_REFERENCE Descriptor)
{ {
ULONG_PTR CurrentValue, NewValue; ULONG_PTR CurrentValue, NewValue;
@@ -69,7 +73,7 @@ ExAcquireRundownProtection(IN PEX_RUNDOWN_REFERENCE Descriptor)
*/ */
XTFASTCALL XTFASTCALL
VOID VOID
ExCompleteRundownProtection(IN PEX_RUNDOWN_REFERENCE Descriptor) Rundown::CompleteProtection(IN PEX_RUNDOWN_REFERENCE Descriptor)
{ {
RtlAtomicExchangePointer(&Descriptor->Ptr, (PVOID)EX_RUNDOWN_ACTIVE); RtlAtomicExchangePointer(&Descriptor->Ptr, (PVOID)EX_RUNDOWN_ACTIVE);
} }
@@ -86,7 +90,7 @@ ExCompleteRundownProtection(IN PEX_RUNDOWN_REFERENCE Descriptor)
*/ */
XTFASTCALL XTFASTCALL
VOID VOID
ExInitializeRundownProtection(IN PEX_RUNDOWN_REFERENCE Descriptor) Rundown::InitializeProtection(IN PEX_RUNDOWN_REFERENCE Descriptor)
{ {
/* Reset descriptor counter */ /* Reset descriptor counter */
Descriptor->Count = 0; Descriptor->Count = 0;
@@ -104,7 +108,7 @@ ExInitializeRundownProtection(IN PEX_RUNDOWN_REFERENCE Descriptor)
*/ */
XTFASTCALL XTFASTCALL
VOID VOID
ExReInitializeRundownProtection(IN PEX_RUNDOWN_REFERENCE Descriptor) Rundown::ReInitializeProtection(IN PEX_RUNDOWN_REFERENCE Descriptor)
{ {
RtlAtomicExchangePointer(&Descriptor->Ptr, NULL); RtlAtomicExchangePointer(&Descriptor->Ptr, NULL);
} }
@@ -121,7 +125,7 @@ ExReInitializeRundownProtection(IN PEX_RUNDOWN_REFERENCE Descriptor)
*/ */
XTFASTCALL XTFASTCALL
VOID VOID
ExReleaseRundownProtection(IN PEX_RUNDOWN_REFERENCE Descriptor) Rundown::ReleaseProtection(IN PEX_RUNDOWN_REFERENCE Descriptor)
{ {
ULONG_PTR CurrentValue, NewValue; ULONG_PTR CurrentValue, NewValue;
PEX_RUNDOWN_WAIT_BLOCK WaitBlock; PEX_RUNDOWN_WAIT_BLOCK WaitBlock;
@@ -136,7 +140,7 @@ ExReleaseRundownProtection(IN PEX_RUNDOWN_REFERENCE Descriptor)
if(!RtlAtomicDecrement64((PLONG_PTR)&WaitBlock->Count)) if(!RtlAtomicDecrement64((PLONG_PTR)&WaitBlock->Count))
{ {
KeSetEvent(&WaitBlock->WakeEvent, 0, FALSE); KE::Event::SetEvent(&WaitBlock->WakeEvent, 0, FALSE);
} }
break; break;
@@ -172,7 +176,9 @@ ExReleaseRundownProtection(IN PEX_RUNDOWN_REFERENCE Descriptor)
*/ */
XTFASTCALL XTFASTCALL
VOID VOID
ExWaitForRundownProtectionRelease(IN PEX_RUNDOWN_REFERENCE Descriptor) Rundown::WaitForProtectionRelease(IN PEX_RUNDOWN_REFERENCE Descriptor)
{ {
UNIMPLEMENTED; UNIMPLEMENTED;
} }
} /* namespace */

View File

@@ -265,15 +265,22 @@ XTAPI
XTSTATUS XTSTATUS
HlpInitializeAcpiSystemInformation(VOID) HlpInitializeAcpiSystemInformation(VOID)
{ {
PUCHAR MadtTable; PACPI_MADT_LOCAL_X2APIC LocalX2Apic;
PACPI_MADT_LOCAL_APIC LocalApic;
ULONG_PTR MadtTable;
PACPI_MADT Madt; PACPI_MADT Madt;
XTSTATUS Status; XTSTATUS Status;
ULONG CpuCount; USHORT CpuCount;
/* Zero the ACPI system information structure */ /* Allocate memory for ACPI system information structure */
RtlZeroMemory(&HlpAcpiSystemInfo, sizeof(ACPI_SYSTEM_INFO)); Status = HlpInitializeAcpiSystemStructure();
if(Status != STATUS_SUCCESS)
{
/* Failed to allocate memory, return error */
return STATUS_INSUFFICIENT_RESOURCES;
}
/* Get Multi-APIC Description Table (MADT) */ /* Get Multiple APIC Description Table (MADT) */
Status = HlGetAcpiTable(ACPI_MADT_SIGNATURE, (PACPI_DESCRIPTION_HEADER*)&Madt); Status = HlGetAcpiTable(ACPI_MADT_SIGNATURE, (PACPI_DESCRIPTION_HEADER*)&Madt);
if(Status != STATUS_SUCCESS) if(Status != STATUS_SUCCESS)
{ {
@@ -282,38 +289,54 @@ HlpInitializeAcpiSystemInformation(VOID)
} }
/* Set APIC table traverse pointer and initialize number of CPUs */ /* Set APIC table traverse pointer and initialize number of CPUs */
MadtTable = (PUCHAR)Madt->ApicTables; MadtTable = (ULONG_PTR)Madt->ApicTables;
CpuCount = 0; CpuCount = 0;
/* Traverse all MADT tables to get number of processors */ /* Traverse all MADT tables to get system information */
while(MadtTable <= ((PUCHAR)Madt + Madt->Header.Length)) while(MadtTable <= ((ULONG_PTR)Madt + Madt->Header.Length))
{ {
/* Check if this is a local APIC subtable */ /* Check if this is a local APIC subtable */
if((((PACPI_MADT_LOCAL_APIC)MadtTable)->Header.Type == ACPI_MADT_TYPE_LOCAL_APIC) && if((((PACPI_SUBTABLE_HEADER)MadtTable)->Type == ACPI_MADT_TYPE_LOCAL_APIC) &&
(((PACPI_MADT_LOCAL_APIC)MadtTable)->Header.Length == sizeof(ACPI_MADT_LOCAL_APIC))) (((PACPI_SUBTABLE_HEADER)MadtTable)->Length == sizeof(ACPI_MADT_LOCAL_APIC)))
{ {
/* Get local APIC subtable */
LocalApic = (PACPI_MADT_LOCAL_APIC)MadtTable;
/* Make sure, this CPU can be enabled */ /* Make sure, this CPU can be enabled */
if(((PACPI_MADT_LOCAL_APIC)MadtTable)->LapicFlags & ACPI_MADT_PLAOC_ENABLED) if(LocalApic->Flags & ACPI_MADT_PLAOC_ENABLED)
{ {
/* Store CPU number, APIC ID and CPU ID */
HlpSystemInfo.CpuInfo[CpuCount].AcpiId = LocalApic->AcpiId;
HlpSystemInfo.CpuInfo[CpuCount].ApicId = LocalApic->ApicId;
HlpSystemInfo.CpuInfo[CpuCount].CpuNumber = CpuCount;
/* Increment number of CPUs */ /* Increment number of CPUs */
CpuCount++; CpuCount++;
} }
/* Go to the next MADT table */ /* Go to the next MADT table */
MadtTable += ((PACPI_MADT_LOCAL_APIC)MadtTable)->Header.Length; MadtTable += ((PACPI_SUBTABLE_HEADER)MadtTable)->Length;
} }
else if((((PACPI_MADT_LOCAL_X2APIC)MadtTable)->Header.Type == ACPI_MADT_TYPE_LOCAL_X2APIC) && else if((((PACPI_SUBTABLE_HEADER)MadtTable)->Type == ACPI_MADT_TYPE_LOCAL_X2APIC) &&
(((PACPI_MADT_LOCAL_X2APIC)MadtTable)->Header.Length == sizeof(ACPI_MADT_LOCAL_X2APIC))) (((PACPI_SUBTABLE_HEADER)MadtTable)->Length == sizeof(ACPI_MADT_LOCAL_X2APIC)))
{ {
/* Get local X2APIC subtable */
LocalX2Apic = (PACPI_MADT_LOCAL_X2APIC)MadtTable;
/* Make sure, this CPU can be enabled */ /* Make sure, this CPU can be enabled */
if(((PACPI_MADT_LOCAL_X2APIC)MadtTable)->LapicFlags & ACPI_MADT_PLAOC_ENABLED) if(LocalX2Apic->Flags & ACPI_MADT_PLAOC_ENABLED)
{ {
/* Store CPU number, APIC ID and CPU ID */
HlpSystemInfo.CpuInfo[CpuCount].AcpiId = LocalX2Apic->AcpiId;
HlpSystemInfo.CpuInfo[CpuCount].ApicId = LocalX2Apic->ApicId;
HlpSystemInfo.CpuInfo[CpuCount].CpuNumber = CpuCount;
/* Increment number of CPUs */ /* Increment number of CPUs */
CpuCount++; CpuCount++;
} }
/* Go to the next MADT table */ /* Go to the next MADT table */
MadtTable += ((PACPI_MADT_LOCAL_X2APIC)MadtTable)->Header.Length; MadtTable += ((PACPI_SUBTABLE_HEADER)MadtTable)->Length;
} }
else else
{ {
@@ -322,6 +345,105 @@ HlpInitializeAcpiSystemInformation(VOID)
} }
} }
/* Store number of CPUs */
HlpSystemInfo.CpuCount = CpuCount;
/* Return success */
return STATUS_SUCCESS;
}
/**
* Initializes ACPI System Information data structure based on the size of available ACPI data.
*
* @return This routine returns a status code.
*
* @since XT 1.0
*/
XTAPI
XTSTATUS
HlpInitializeAcpiSystemStructure(VOID)
{
PHYSICAL_ADDRESS PhysicalAddress;
PFN_NUMBER PageCount;
ULONG_PTR MadtTable;
PACPI_MADT Madt;
XTSTATUS Status;
ULONG CpuCount;
/* Get Multiple APIC Description Table (MADT) */
Status = HlGetAcpiTable(ACPI_MADT_SIGNATURE, (PACPI_DESCRIPTION_HEADER*)&Madt);
if(Status != STATUS_SUCCESS)
{
/* Failed to get MADT, return error */
return STATUS_NOT_FOUND;
}
/* Set APIC table traverse pointer and initialize number of CPUs */
MadtTable = (ULONG_PTR)Madt->ApicTables;
CpuCount = 0;
/* Traverse all MADT tables to get number of processors */
while(MadtTable <= ((ULONG_PTR)Madt + Madt->Header.Length))
{
/* Check if this is a local APIC subtable */
if((((PACPI_SUBTABLE_HEADER)MadtTable)->Type == ACPI_MADT_TYPE_LOCAL_APIC) &&
(((PACPI_SUBTABLE_HEADER)MadtTable)->Length == sizeof(ACPI_MADT_LOCAL_APIC)))
{
/* Make sure, this CPU can be enabled */
if(((PACPI_MADT_LOCAL_APIC)MadtTable)->Flags & ACPI_MADT_PLAOC_ENABLED)
{
/* Increment number of CPUs */
CpuCount++;
}
/* Go to the next MADT table */
MadtTable += ((PACPI_SUBTABLE_HEADER)MadtTable)->Length;
}
else if((((PACPI_SUBTABLE_HEADER)MadtTable)->Type == ACPI_MADT_TYPE_LOCAL_X2APIC) &&
(((PACPI_SUBTABLE_HEADER)MadtTable)->Length == sizeof(ACPI_MADT_LOCAL_X2APIC)))
{
/* Make sure, this CPU can be enabled */
if(((PACPI_MADT_LOCAL_X2APIC)MadtTable)->Flags & ACPI_MADT_PLAOC_ENABLED)
{
/* Increment number of CPUs */
CpuCount++;
}
/* Go to the next MADT table */
MadtTable += ((PACPI_SUBTABLE_HEADER)MadtTable)->Length;
}
else
{
/* Any other MADT table, try to go to the next one byte-by-byte */
MadtTable += 1;
}
}
/* Zero the ACPI system information structure */
RtlZeroMemory(&HlpSystemInfo, sizeof(ACPI_SYSTEM_INFO));
/* Calculate number of pages needed to store CPU information */
PageCount = SIZE_TO_PAGES(CpuCount * sizeof(PROCESSOR_IDENTITY));
/* Allocate memory for CPU information */
Status = MmAllocateHardwareMemory(PageCount, TRUE, &PhysicalAddress);
if(Status != STATUS_SUCCESS)
{
/* Failed to allocate memory, return error */
return Status;
}
/* Map physical address to the virtual memory area */
Status = MmMapHardwareMemory(PhysicalAddress, PageCount, TRUE, (PVOID *)&HlpSystemInfo.CpuInfo);
if(Status != STATUS_SUCCESS)
{
/* Failed to map memory, return error */
return Status;
}
/* Zero the CPU information structure */
RtlZeroMemory(HlpSystemInfo.CpuInfo, PAGES_TO_SIZE(PageCount));
/* Return success */ /* Return success */
return STATUS_SUCCESS; return STATUS_SUCCESS;
} }
@@ -385,9 +507,13 @@ XTSTATUS
HlpQueryAcpiCache(IN ULONG Signature, HlpQueryAcpiCache(IN ULONG Signature,
OUT PACPI_DESCRIPTION_HEADER *AcpiTable) OUT PACPI_DESCRIPTION_HEADER *AcpiTable)
{ {
PACPI_DESCRIPTION_HEADER TableHeader;
PACPI_CACHE_LIST AcpiCache; PACPI_CACHE_LIST AcpiCache;
PLIST_ENTRY ListEntry; PLIST_ENTRY ListEntry;
/* Initialize variables */
TableHeader = NULL;
/* Iterate through ACPI tables cache list */ /* Iterate through ACPI tables cache list */
ListEntry = HlpAcpiCacheList.Flink; ListEntry = HlpAcpiCacheList.Flink;
while(ListEntry != &HlpAcpiCacheList) while(ListEntry != &HlpAcpiCacheList)
@@ -399,7 +525,7 @@ HlpQueryAcpiCache(IN ULONG Signature,
if(AcpiCache->Header.Signature == Signature) if(AcpiCache->Header.Signature == Signature)
{ {
/* ACPI table found in cache, return it */ /* ACPI table found in cache, return it */
*AcpiTable = &AcpiCache->Header; TableHeader = &AcpiCache->Header;
break; break;
} }
@@ -408,13 +534,14 @@ HlpQueryAcpiCache(IN ULONG Signature,
} }
/* Check if the requested ACPI table was found in the cache */ /* Check if the requested ACPI table was found in the cache */
if(*AcpiTable == NULL) if(TableHeader == NULL)
{ {
/* ACPI table not found in cache, return error */ /* ACPI table not found in cache, return error */
return STATUS_NOT_FOUND; return STATUS_NOT_FOUND;
} }
/* Return success */ /* Return table header and status code */
*AcpiTable = TableHeader;
return STATUS_SUCCESS; return STATUS_SUCCESS;
} }
@@ -452,6 +579,9 @@ HlpQueryAcpiTables(IN ULONG Signature,
return STATUS_INVALID_PARAMETER; return STATUS_INVALID_PARAMETER;
} }
/* Ensure that table header is not set before attempting to find ACPI table */
TableHeader = NULL;
/* Check if DSDT or FACS table requested */ /* Check if DSDT or FACS table requested */
if(Signature == ACPI_DSDT_SIGNATURE || Signature == ACPI_FACS_SIGNATURE) if(Signature == ACPI_DSDT_SIGNATURE || Signature == ACPI_FACS_SIGNATURE)
{ {

View File

@@ -24,9 +24,9 @@ UCHAR
HlIoPortInByte(IN USHORT Port) HlIoPortInByte(IN USHORT Port)
{ {
UCHAR Value; UCHAR Value;
asm volatile("inb %1, %0" __asm__ volatile("inb %1, %0"
: "=a" (Value) : "=a" (Value)
: "Nd" (Port)); : "Nd" (Port));
return Value; return Value;
} }
@@ -45,9 +45,9 @@ ULONG
HlIoPortInLong(IN USHORT Port) HlIoPortInLong(IN USHORT Port)
{ {
ULONG Value; ULONG Value;
asm volatile("inl %1, %0" __asm__ volatile("inl %1, %0"
: "=a" (Value) : "=a" (Value)
: "Nd" (Port)); : "Nd" (Port));
return Value; return Value;
} }
@@ -66,9 +66,9 @@ USHORT
HlIoPortInShort(IN USHORT Port) HlIoPortInShort(IN USHORT Port)
{ {
USHORT Value; USHORT Value;
asm volatile("inw %1, %0" __asm__ volatile("inw %1, %0"
: "=a" (Value) : "=a" (Value)
: "Nd" (Port)); : "Nd" (Port));
return Value; return Value;
} }
@@ -90,10 +90,10 @@ VOID
HlIoPortOutByte(IN USHORT Port, HlIoPortOutByte(IN USHORT Port,
IN UCHAR Value) IN UCHAR Value)
{ {
asm volatile("outb %0, %1" __asm__ volatile("outb %0, %1"
: :
: "a" (Value), : "a" (Value),
"Nd" (Port)); "Nd" (Port));
} }
/** /**
@@ -114,10 +114,10 @@ VOID
HlIoPortOutLong(IN USHORT Port, HlIoPortOutLong(IN USHORT Port,
IN ULONG Value) IN ULONG Value)
{ {
asm volatile("outl %0, %1" __asm__ volatile("outl %0, %1"
: :
: "a" (Value), : "a" (Value),
"Nd" (Port)); "Nd" (Port));
} }
/** /**
@@ -138,8 +138,8 @@ VOID
HlIoPortOutShort(IN USHORT Port, HlIoPortOutShort(IN USHORT Port,
IN USHORT Value) IN USHORT Value)
{ {
asm volatile("outw %0, %1" __asm__ volatile("outw %0, %1"
: :
: "a" (Value), : "a" (Value),
"Nd" (Port)); "Nd" (Port));
} }

View File

@@ -165,7 +165,6 @@ HlComPortReadLsr(IN PCPPORT Port,
IN UCHAR Byte) IN UCHAR Byte)
{ {
UCHAR Lsr, Msr; UCHAR Lsr, Msr;
STATIC UCHAR RingFlag;
/* Read the Line Status Register (LSR) */ /* Read the Line Status Register (LSR) */
Lsr = HlIoPortInByte(PtrToUshort(Port->Address + (ULONG)COMPORT_REG_LSR)); Lsr = HlIoPortInByte(PtrToUshort(Port->Address + (ULONG)COMPORT_REG_LSR));
@@ -175,8 +174,8 @@ HlComPortReadLsr(IN PCPPORT Port,
{ {
/* Check Modem Status Register (MSR) for ring indicator */ /* Check Modem Status Register (MSR) for ring indicator */
Msr = HlIoPortInByte(PtrToUshort(Port->Address + (ULONG)COMPORT_REG_MSR)); Msr = HlIoPortInByte(PtrToUshort(Port->Address + (ULONG)COMPORT_REG_MSR));
RingFlag |= (Msr & COMPORT_MSR_RI) ? 1 : 2; Port->Ring |= (Msr & COMPORT_MSR_RI) ? 1 : 2;
if(RingFlag == 3) if(Port->Ring == 3)
{ {
/* Ring indicator toggled, use modem control */ /* Ring indicator toggled, use modem control */
Port->Flags |= COMPORT_FLAG_MC; Port->Flags |= COMPORT_FLAG_MC;
@@ -277,12 +276,13 @@ HlInitializeComPort(IN OUT PCPPORT Port,
HlIoPortOutByte(PtrToUshort(PortAddress + (ULONG)COMPORT_REG_MCR), COMPORT_MCR_NOM); HlIoPortOutByte(PtrToUshort(PortAddress + (ULONG)COMPORT_REG_MCR), COMPORT_MCR_NOM);
/* Read junk data out of the Receive Buffer Register (RBR) */ /* Read junk data out of the Receive Buffer Register (RBR) */
HlIoPortInByte(PtrToUshort(Port->Address + (ULONG)COMPORT_REG_RBR)); HlIoPortInByte(PtrToUshort(PortAddress + (ULONG)COMPORT_REG_RBR));
/* Store port details */ /* Store port details */
Port->Address = PortAddress; Port->Address = PortAddress;
Port->Baud = BaudRate; Port->Baud = BaudRate;
Port->Flags = Flags; Port->Flags = Flags;
Port->Ring = 0;
/* Return success */ /* Return success */
return STATUS_SUCCESS; return STATUS_SUCCESS;

View File

@@ -4,6 +4,7 @@
* FILE: xtoskrnl/hl/fbdev.c * FILE: xtoskrnl/hl/fbdev.c
* DESCRIPTION: FrameBuffer support * DESCRIPTION: FrameBuffer support
* DEVELOPERS: Rafal Kupiec <belliash@codingworkshop.eu.org> * DEVELOPERS: Rafal Kupiec <belliash@codingworkshop.eu.org>
* Aiken Harris <harraiken91@gmail.com>
*/ */
#include <xtos.h> #include <xtos.h>
@@ -24,9 +25,10 @@ XTAPI
VOID VOID
HlClearScreen(IN ULONG Color) HlClearScreen(IN ULONG Color)
{ {
SIZE_T Line, PositionX, PositionY; ULONG PositionX, PositionY;
ULONG BackgroundColor; ULONG BackgroundColor;
PULONG FrameBuf; PCHAR CurrentLine;
PULONG Pixel;
/* Make sure frame buffer is already initialized */ /* Make sure frame buffer is already initialized */
if(HlpFrameBufferData.Initialized == FALSE) if(HlpFrameBufferData.Initialized == FALSE)
@@ -35,34 +37,102 @@ HlClearScreen(IN ULONG Color)
return; return;
} }
/* Get pointer to frame buffer */ /* Convert background color and get pointer to frame buffer */
FrameBuf = HlpFrameBufferData.Address;
/* Convert background color */
BackgroundColor = HlpRGBColor(Color); BackgroundColor = HlpRGBColor(Color);
CurrentLine = HlpFrameBufferData.Address;
/* Fill the screen with a black box */ /* Fill the screen with the specified color */
for(PositionY = 0; PositionY < HlpFrameBufferData.Height; PositionY++) for(PositionY = 0; PositionY < HlpFrameBufferData.Height; PositionY++, CurrentLine += HlpFrameBufferData.Pitch)
{ {
Line = PositionY * HlpFrameBufferData.PixelsPerScanLine; /* Fill the current line with the specified color */
Pixel = (PULONG)CurrentLine;
for(PositionX = 0; PositionX < HlpFrameBufferData.Width; PositionX++) for(PositionX = 0; PositionX < HlpFrameBufferData.Width; PositionX++)
{ {
FrameBuf[Line + PositionX] = BackgroundColor; /* Set the color of the pixel */
Pixel[PositionX] = BackgroundColor;
} }
} }
} }
/** /**
* Draw a pixel on the screen at the given position and color. * Displays a single character at the current cursor position inside the scroll region.
* *
* @param PositionX * @param Character
* Supplies the X coordinate of the pixel. * Supplies the character to be displayed.
* *
* @param PositionY * @return This routine does not return any value.
* Supplies the Y coordinate of the pixel.
* *
* @param Color * @since XT 1.0
* Specifies the color of the pixel in (A)RGB format. */
XTCDECL
XTSTATUS
HlDisplayCharacter(IN WCHAR Character)
{
PSSFN_FONT_HEADER FbFont;
/* Make sure frame buffer is already initialized */
if(HlpFrameBufferData.Initialized == FALSE)
{
/* Unable to operate on non-initialized frame buffer */
return STATUS_DEVICE_NOT_READY;
}
/* Get font information */
FbFont = (PSSFN_FONT_HEADER)HlpFrameBufferData.Font;
/* Handle special characters */
switch(Character)
{
case L'\n':
/* Move cursor to the beginning of the next line */
HlpScrollRegionData.CursorX = HlpScrollRegionData.Left;
HlpScrollRegionData.CursorY += FbFont->Height;
break;
case L'\t':
/* Move cursor to the next tab stop */
HlpScrollRegionData.CursorX += (8 - (HlpScrollRegionData.CursorX - HlpScrollRegionData.Left) / FbFont->Width % 8) * FbFont->Width;
if (HlpScrollRegionData.CursorX >= HlpScrollRegionData.Right)
{
HlpScrollRegionData.CursorX = HlpScrollRegionData.Left;
HlpScrollRegionData.CursorY += FbFont->Height;
}
break;
default:
/* Draw the character */
HlpDrawCharacter(HlpScrollRegionData.CursorX, HlpScrollRegionData.CursorY, HlpScrollRegionData.TextColor, Character);
/* Advance cursor */
HlpScrollRegionData.CursorX += FbFont->Width;
/* Check if cursor reached end of line */
if(HlpScrollRegionData.CursorX >= HlpScrollRegionData.Right)
{
HlpScrollRegionData.CursorX = HlpScrollRegionData.Left;
HlpScrollRegionData.CursorY += FbFont->Height;
}
break;
}
/* Check if cursor reached end of scroll region */
if(HlpScrollRegionData.CursorY >= HlpScrollRegionData.Bottom)
{
/* Scroll one line up */
HlpScrollRegion();
HlpScrollRegionData.CursorY = HlpScrollRegionData.Bottom - FbFont->Height;
}
/* Return success */
return STATUS_SUCCESS;
}
/**
* Returns the current resolution of the frame buffer display.
*
* @param Width
* A pointer to memory area where the screen width will be stored.
*
* @param Height
* A pointer to memory area where the screen height will be stored.
* *
* @return This routine does not return any value. * @return This routine does not return any value.
* *
@@ -70,31 +140,10 @@ HlClearScreen(IN ULONG Color)
*/ */
XTAPI XTAPI
VOID VOID
HlDrawPixel(IN ULONG PositionX, HlGetFrameBufferResolution(OUT PULONG Width, OUT PULONG Height)
IN ULONG PositionY,
IN ULONG Color)
{ {
SIZE_T FrameBufferIndex; *Width = HlpFrameBufferData.Width;
*Height = HlpFrameBufferData.Height;
/* Make sure frame buffer is already initialized */
if(HlpFrameBufferData.Initialized == FALSE)
{
/* Unable to operate on non-initialized frame buffer */
return;
}
/* Make sure point is not offscreen */
if(PositionX >= HlpFrameBufferData.Width || PositionY >= HlpFrameBufferData.Height || Color > 0xFFFFFFFF)
{
/* Invalid pixel position or color given */
return;
}
/* Calculate the index of the pixel in the frame buffer memory using the provided x and y coordinates */
FrameBufferIndex = 4 * HlpFrameBufferData.PixelsPerScanLine * PositionY + 4 * PositionX;
/* Set the color of the pixel by writing to the corresponding memory location */
*((PULONG)(HlpFrameBufferData.Address + FrameBufferIndex)) = HlpRGBColor(Color);
} }
/** /**
@@ -153,7 +202,7 @@ HlInitializeFrameBuffer(VOID)
HlpFrameBufferData.Address = FrameBufferResource->Header.VirtualAddress; HlpFrameBufferData.Address = FrameBufferResource->Header.VirtualAddress;
HlpFrameBufferData.Width = FrameBufferResource->Width; HlpFrameBufferData.Width = FrameBufferResource->Width;
HlpFrameBufferData.Height = FrameBufferResource->Height; HlpFrameBufferData.Height = FrameBufferResource->Height;
HlpFrameBufferData.BitsPerPixel = FrameBufferResource->BitsPerPixel; HlpFrameBufferData.BytesPerPixel = FrameBufferResource->BitsPerPixel / 8;
HlpFrameBufferData.PixelsPerScanLine = FrameBufferResource->PixelsPerScanLine; HlpFrameBufferData.PixelsPerScanLine = FrameBufferResource->PixelsPerScanLine;
HlpFrameBufferData.Pitch = FrameBufferResource->Pitch; HlpFrameBufferData.Pitch = FrameBufferResource->Pitch;
HlpFrameBufferData.Pixels.BlueShift = FrameBufferResource->Pixels.BlueShift; HlpFrameBufferData.Pixels.BlueShift = FrameBufferResource->Pixels.BlueShift;
@@ -174,7 +223,81 @@ HlInitializeFrameBuffer(VOID)
} }
/** /**
* Puts a wide character on the framebuffer at the given position and color using the SSFN font. * Sets the scrollable region of the screen and calculates character dimensions.
*
* @param Left
* Supplies the left pixel coordinate of the scroll region.
*
* @param Top
* Supplies the top pixel coordinate of the scroll region.
*
* @param Right
* Supplies the right pixel coordinate of the scroll region.
*
* @param Bottom
* Supplies the bottom pixel coordinate of the scroll region.
*
* @return This routine does not return any value.
*
* @since XT 1.0
*/
XTAPI
VOID
HlInitializeScrollRegion(IN ULONG Left,
IN ULONG Top,
IN ULONG Right,
IN ULONG Bottom,
IN ULONG FontColor)
{
PSSFN_FONT_HEADER FbFont;
PCHAR PixelAddress;
/* Make sure frame buffer is already initialized */
if(HlpFrameBufferData.Initialized == FALSE)
{
/* Unable to operate on non-initialized frame buffer */
return;
}
/* Store pixel coordinates of the scroll region */
HlpScrollRegionData.Left = Left;
HlpScrollRegionData.Top = Top;
HlpScrollRegionData.Right = Right;
HlpScrollRegionData.Bottom = Bottom;
/* Get font information */
FbFont = (PSSFN_FONT_HEADER)HlpFrameBufferData.Font;
/* Validate font information */
if(FbFont && FbFont->Width > 0 && FbFont->Height > 0)
{
/* Calculate character dimensions */
HlpScrollRegionData.WidthInChars = (Right - Left) / FbFont->Width;
HlpScrollRegionData.HeightInChars = (Bottom - Top) / FbFont->Height;
/* Ensure the bottom of the scroll region is an exact multiple of the font height */
HlpScrollRegionData.Bottom = HlpScrollRegionData.Top + (HlpScrollRegionData.HeightInChars * FbFont->Height);
}
else
{
/* Fallback to 0 if font info is not available or invalid */
HlpScrollRegionData.WidthInChars = 0;
HlpScrollRegionData.HeightInChars = 0;
}
/* Initialize cursor position and font color */
HlpScrollRegionData.CursorX = HlpScrollRegionData.Left;
HlpScrollRegionData.CursorY = HlpScrollRegionData.Top;
HlpScrollRegionData.TextColor = FontColor;
/* Get the background color by reading the pixel at the top-left corner of the scroll region */
PixelAddress = (PCHAR)HlpFrameBufferData.Address + (Top * HlpFrameBufferData.Pitch) +
(Left * HlpFrameBufferData.BytesPerPixel);
HlpScrollRegionData.BackgroundColor = *((PULONG)PixelAddress);
}
/**
* Draws a character on the framebuffer at the given position and color using the SSFN font.
* *
* @param PositionX * @param PositionX
* Supplies the X coordinate of the character. * Supplies the X coordinate of the character.
@@ -194,10 +317,10 @@ HlInitializeFrameBuffer(VOID)
*/ */
XTAPI XTAPI
VOID VOID
HlPutCharacter(IN ULONG PositionX, HlpDrawCharacter(IN ULONG PositionX,
IN ULONG PositionY, IN ULONG PositionY,
IN ULONG Color, IN ULONG Color,
IN WCHAR WideCharacter) IN WCHAR WideCharacter)
{ {
UINT CurrentFragment, Glyph, GlyphLimit, Index, Line, Mapping; UINT CurrentFragment, Glyph, GlyphLimit, Index, Line, Mapping;
PUCHAR Character, CharacterMapping, Fragment; PUCHAR Character, CharacterMapping, Fragment;
@@ -261,7 +384,8 @@ HlPutCharacter(IN ULONG PositionX,
} }
/* Find the glyph position on the frame buffer and set font color */ /* Find the glyph position on the frame buffer and set font color */
GlyphPixel = (UINT_PTR)HlpFrameBufferData.Address + PositionY * HlpFrameBufferData.Pitch + PositionX * 4; GlyphPixel = (UINT_PTR)HlpFrameBufferData.Address + PositionY * HlpFrameBufferData.Pitch +
PositionX * HlpFrameBufferData.BytesPerPixel;
FontColor = HlpRGBColor(Color); FontColor = HlpRGBColor(Color);
/* Check all kerning fragments */ /* Check all kerning fragments */
@@ -321,7 +445,7 @@ HlPutCharacter(IN ULONG PositionX,
} }
/* Advance pixel pointer */ /* Advance pixel pointer */
Pixel += 4; Pixel += HlpFrameBufferData.BytesPerPixel;
CurrentFragment <<= 1; CurrentFragment <<= 1;
} }
@@ -335,6 +459,52 @@ HlPutCharacter(IN ULONG PositionX,
} }
} }
/**
* Draw a pixel on the screen at the given position and color.
*
* @param PositionX
* Supplies the X coordinate of the pixel.
*
* @param PositionY
* Supplies the Y coordinate of the pixel.
*
* @param Color
* Specifies the color of the pixel in (A)RGB format.
*
* @return This routine does not return any value.
*
* @since XT 1.0
*/
XTAPI
VOID
HlpDrawPixel(IN ULONG PositionX,
IN ULONG PositionY,
IN ULONG Color)
{
PCHAR PixelAddress;
/* Make sure frame buffer is already initialized */
if(HlpFrameBufferData.Initialized == FALSE)
{
/* Unable to operate on non-initialized frame buffer */
return;
}
/* Make sure point is not offscreen */
if(PositionX >= HlpFrameBufferData.Width || PositionY >= HlpFrameBufferData.Height || Color > 0xFFFFFFFF)
{
/* Invalid pixel position or color given */
return;
}
/* Calculate the address of the pixel in the frame buffer memory */
PixelAddress = (PCHAR)HlpFrameBufferData.Address + (PositionY * HlpFrameBufferData.Pitch) +
(PositionX * HlpFrameBufferData.BytesPerPixel);
/* Set the color of the pixel by writing to the corresponding memory location */
*((PULONG)PixelAddress) = HlpRGBColor(Color);
}
/** /**
* Converts color format from (A)RGB one expected by current FrameBuffer. * Converts color format from (A)RGB one expected by current FrameBuffer.
* *
@@ -361,3 +531,62 @@ HlpRGBColor(IN ULONG Color)
return (ULONG)((Blue << HlpFrameBufferData.Pixels.BlueShift) | (Green << HlpFrameBufferData.Pixels.GreenShift) | return (ULONG)((Blue << HlpFrameBufferData.Pixels.BlueShift) | (Green << HlpFrameBufferData.Pixels.GreenShift) |
(Red << HlpFrameBufferData.Pixels.RedShift) | (Reserved << HlpFrameBufferData.Pixels.ReservedShift)); (Red << HlpFrameBufferData.Pixels.RedShift) | (Reserved << HlpFrameBufferData.Pixels.ReservedShift));
} }
/**
* Scrolls the content of the scroll region up by one line.
*
* @return This routine does not return any value.
*
* @since XT 1.0
*/
XTAPI
VOID
HlpScrollRegion(VOID)
{
PCHAR Destination, Source;
PSSFN_FONT_HEADER FbFont;
ULONG Line, PositionX;
ULONG LineBytes;
PULONG Pixel;
/* Make sure frame buffer is already initialized */
if(HlpFrameBufferData.Initialized == FALSE)
{
/* Unable to operate on non-initialized frame buffer */
return;
}
/* Get font information */
FbFont = (PSSFN_FONT_HEADER)HlpFrameBufferData.Font;
/* Calculate bytes per line in the scroll region */
LineBytes = (HlpScrollRegionData.Right - HlpScrollRegionData.Left) * HlpFrameBufferData.BytesPerPixel;
/* Scroll up each scan line in the scroll region */
for(Line = HlpScrollRegionData.Top; Line < HlpScrollRegionData.Bottom - FbFont->Height; Line++)
{
Destination = (PCHAR)HlpFrameBufferData.Address + Line * HlpFrameBufferData.Pitch +
HlpScrollRegionData.Left * HlpFrameBufferData.BytesPerPixel;
/* The source is one full text line (FbFont->Height) below the destination */
Source = (PCHAR)HlpFrameBufferData.Address + (Line + FbFont->Height) * HlpFrameBufferData.Pitch +
HlpScrollRegionData.Left * HlpFrameBufferData.BytesPerPixel;
/* Move each scan line in the scroll region up */
RtlMoveMemory(Destination, Source, LineBytes);
}
/* Clear the last text line */
for(Line = HlpScrollRegionData.Bottom - FbFont->Height; Line < HlpScrollRegionData.Bottom; Line++)
{
/* Get pointer to the start of the scan line to clear */
Pixel = (PULONG)((PCHAR)HlpFrameBufferData.Address + Line * HlpFrameBufferData.Pitch +
HlpScrollRegionData.Left * HlpFrameBufferData.BytesPerPixel);
/* Clear each pixel in the scan line with the background color */
for(PositionX = 0; PositionX < (HlpScrollRegionData.Right - HlpScrollRegionData.Left); PositionX++)
{
Pixel[PositionX] = HlpScrollRegionData.BackgroundColor;
}
}
}

View File

@@ -15,9 +15,6 @@ LIST_ENTRY HlpAcpiCacheList;
/* ACPI Root System Description Pointer (RSDP) */ /* ACPI Root System Description Pointer (RSDP) */
PACPI_RSDP HlpAcpiRsdp; PACPI_RSDP HlpAcpiRsdp;
/* ACPI system information */
ACPI_SYSTEM_INFO HlpAcpiSystemInfo;
/* ACPI timer information */ /* ACPI timer information */
ACPI_TIMER_INFO HlpAcpiTimerInfo; ACPI_TIMER_INFO HlpAcpiTimerInfo;
@@ -28,4 +25,10 @@ KAFFINITY HlpActiveProcessors;
APIC_MODE HlpApicMode; APIC_MODE HlpApicMode;
/* FrameBuffer information */ /* FrameBuffer information */
HAL_FRAMEBUFFER_DATA HlpFrameBufferData; HL_FRAMEBUFFER_DATA HlpFrameBufferData;
/* Scroll region information */
HL_SCROLL_REGION_DATA HlpScrollRegionData;
/* System information */
ACPI_SYSTEM_INFO HlpSystemInfo;

View File

@@ -24,9 +24,9 @@ UCHAR
HlIoPortInByte(IN USHORT Port) HlIoPortInByte(IN USHORT Port)
{ {
UCHAR Value; UCHAR Value;
asm volatile("inb %1, %0" __asm__ volatile("inb %1, %0"
: "=a" (Value) : "=a" (Value)
: "Nd" (Port)); : "Nd" (Port));
return Value; return Value;
} }
@@ -45,9 +45,9 @@ ULONG
HlIoPortInLong(IN USHORT Port) HlIoPortInLong(IN USHORT Port)
{ {
ULONG Value; ULONG Value;
asm volatile("inl %1, %0" __asm__ volatile("inl %1, %0"
: "=a" (Value) : "=a" (Value)
: "Nd" (Port)); : "Nd" (Port));
return Value; return Value;
} }
@@ -66,9 +66,9 @@ USHORT
HlIoPortInShort(IN USHORT Port) HlIoPortInShort(IN USHORT Port)
{ {
USHORT Value; USHORT Value;
asm volatile("inw %1, %0" __asm__ volatile("inw %1, %0"
: "=a" (Value) : "=a" (Value)
: "Nd" (Port)); : "Nd" (Port));
return Value; return Value;
} }
@@ -90,10 +90,10 @@ VOID
HlIoPortOutByte(IN USHORT Port, HlIoPortOutByte(IN USHORT Port,
IN UCHAR Value) IN UCHAR Value)
{ {
asm volatile("outb %0, %1" __asm__ volatile("outb %0, %1"
: :
: "a" (Value), : "a" (Value),
"Nd" (Port)); "Nd" (Port));
} }
/** /**
@@ -114,10 +114,10 @@ VOID
HlIoPortOutLong(IN USHORT Port, HlIoPortOutLong(IN USHORT Port,
IN ULONG Value) IN ULONG Value)
{ {
asm volatile("outl %0, %1" __asm__ volatile("outl %0, %1"
: :
: "a" (Value), : "a" (Value),
"Nd" (Port)); "Nd" (Port));
} }
/** /**
@@ -138,8 +138,8 @@ VOID
HlIoPortOutShort(IN USHORT Port, HlIoPortOutShort(IN USHORT Port,
IN USHORT Value) IN USHORT Value)
{ {
asm volatile("outw %0, %1" __asm__ volatile("outw %0, %1"
: :
: "a" (Value), : "a" (Value),
"Nd" (Port)); "Nd" (Port));
} }

View File

@@ -35,7 +35,7 @@ HlClearApicErrors(VOID)
* @since XT 1.0 * @since XT 1.0
*/ */
XTFASTCALL XTFASTCALL
ULONG ULONGLONG
HlReadApicRegister(IN APIC_REGISTER Register) HlReadApicRegister(IN APIC_REGISTER Register)
{ {
if(HlpApicMode == APIC_MODE_X2APIC) if(HlpApicMode == APIC_MODE_X2APIC)
@@ -81,7 +81,7 @@ HlSendEoi(VOID)
XTFASTCALL XTFASTCALL
VOID VOID
HlWriteApicRegister(IN APIC_REGISTER Register, HlWriteApicRegister(IN APIC_REGISTER Register,
IN ULONG Value) IN ULONGLONG Value)
{ {
if(HlpApicMode == APIC_MODE_X2APIC) if(HlpApicMode == APIC_MODE_X2APIC)
{ {
@@ -112,7 +112,7 @@ HlpCheckX2ApicSupport(VOID)
CPUID_REGISTERS CpuRegisters; CPUID_REGISTERS CpuRegisters;
/* Prepare CPUID registers */ /* Prepare CPUID registers */
CpuRegisters.Leaf = CPUID_GET_CPU_FEATURES; CpuRegisters.Leaf = CPUID_GET_STANDARD1_FEATURES;
CpuRegisters.SubLeaf = 0; CpuRegisters.SubLeaf = 0;
CpuRegisters.Eax = 0; CpuRegisters.Eax = 0;
CpuRegisters.Ebx = 0; CpuRegisters.Ebx = 0;
@@ -133,6 +133,26 @@ HlpCheckX2ApicSupport(VOID)
return TRUE; return TRUE;
} }
/**
* Gets the local APIC ID of the current processor.
*
* @return This routine returns the current processor's local APIC ID.
*
* @since XT 1.0
*/
XTAPI
ULONG
HlpGetCpuApicId(VOID)
{
ULONG ApicId;
/* Read APIC ID register */
ApicId = HlReadApicRegister(APIC_ID);
/* Return logical CPU ID depending on current APIC mode */
return (HlpApicMode == APIC_MODE_COMPAT) ? ((ApicId & 0xFFFFFFFF) >> APIC_XAPIC_LDR_SHIFT) : ApicId;
}
/** /**
* Allows an APIC spurious interrupts to end up. * Allows an APIC spurious interrupts to end up.
* *
@@ -171,24 +191,23 @@ VOID
HlpInitializeApic(VOID) HlpInitializeApic(VOID)
{ {
APIC_SPURIOUS_REGISTER SpuriousRegister; APIC_SPURIOUS_REGISTER SpuriousRegister;
APIC_COMMAND_REGISTER CommandRegister;
APIC_BASE_REGISTER BaseRegister; APIC_BASE_REGISTER BaseRegister;
APIC_LVT_REGISTER LvtRegister; APIC_LVT_REGISTER LvtRegister;
ULONG CpuNumber; ULONG CpuNumber;
/* Check if this is an x2APIC compatible machine */ /* Determine APIC mode (xAPIC compatibility or x2APIC) */
if(HlpCheckX2ApicSupport()) if(HlpCheckX2ApicSupport())
{ {
/* Enable x2APIC */ /* Enable x2APIC mode */
HlpApicMode = APIC_MODE_X2APIC; HlpApicMode = APIC_MODE_X2APIC;
} }
else else
{ {
/* Use xAPIC compatibility mode */ /* Fall back to xAPIC compatibility mode */
HlpApicMode = APIC_MODE_COMPAT; HlpApicMode = APIC_MODE_COMPAT;
} }
/* Get processor number */ /* Get current processor number */
CpuNumber = KeGetCurrentProcessorNumber(); CpuNumber = KeGetCurrentProcessorNumber();
/* Enable the APIC */ /* Enable the APIC */
@@ -198,82 +217,73 @@ HlpInitializeApic(VOID)
BaseRegister.BootStrapProcessor = (CpuNumber == 0) ? 1 : 0; BaseRegister.BootStrapProcessor = (CpuNumber == 0) ? 1 : 0;
ArWriteModelSpecificRegister(APIC_LAPIC_MSR_BASE, BaseRegister.LongLong); ArWriteModelSpecificRegister(APIC_LAPIC_MSR_BASE, BaseRegister.LongLong);
/* Raise APIC task priority (TPR) to mask off all interrupts */ /* Mask all interrupts by raising Task Priority Register (TPR) */
HlWriteApicRegister(APIC_TPR, 0xFF); HlWriteApicRegister(APIC_TPR, 0xFF);
/* xAPIC compatibility mode specific initialization */ /* Perform initialization specific to xAPIC compatibility mode */
if(HlpApicMode == APIC_MODE_COMPAT) if(HlpApicMode == APIC_MODE_COMPAT)
{ {
/* Initialize Destination Format Register with flat model (not supported in x2APIC mode) */ /* Use Flat Model for destination format (not supported in x2APIC) */
HlWriteApicRegister(APIC_DFR, APIC_DF_FLAT); HlWriteApicRegister(APIC_DFR, APIC_DF_FLAT);
/* Set the logical APIC ID (read-only in x2APIC mode) */ /* Set the logical APIC ID for this processor (read-only in x2APIC) */
HlWriteApicRegister(APIC_LDR, (1UL << CpuNumber) << 24); HlWriteApicRegister(APIC_LDR, (1UL << CpuNumber) << 24);
} }
/* Set the spurious interrupt vector */ /* Configure the spurious interrupt vector */
SpuriousRegister.Long = HlReadApicRegister(APIC_SIVR); SpuriousRegister.Long = HlReadApicRegister(APIC_SIVR);
SpuriousRegister.Vector = APIC_VECTOR_SPURIOUS; SpuriousRegister.Vector = APIC_VECTOR_SPURIOUS;
SpuriousRegister.SoftwareEnable = 1; SpuriousRegister.SoftwareEnable = 1;
SpuriousRegister.CoreChecking = 0; SpuriousRegister.CoreChecking = 0;
HlWriteApicRegister(APIC_SIVR, SpuriousRegister.Long); HlWriteApicRegister(APIC_SIVR, SpuriousRegister.Long);
/* Mask LVTR_ERROR first, to prevent local APIC error */ /* Setup the LVT Error entry to deliver APIC errors on a dedicated vector */
HlWriteApicRegister(APIC_ERRLVTR, APIC_VECTOR_ERROR); HlWriteApicRegister(APIC_ERRLVTR, APIC_VECTOR_ERROR);
/* Mask TMRLVTR */ /* Program the APIC timer for periodic mode */
LvtRegister.Long = 0; LvtRegister.Long = 0;
LvtRegister.Mask = 1; LvtRegister.Mask = 1;
LvtRegister.MessageType = APIC_DM_FIXED; LvtRegister.DeliveryMode = APIC_DM_FIXED;
LvtRegister.TimerMode = 1; LvtRegister.TimerMode = 1;
LvtRegister.TriggerMode = APIC_TGM_EDGE; LvtRegister.TriggerMode = APIC_TGM_EDGE;
LvtRegister.Vector = APIC_VECTOR_PROFILE; LvtRegister.Vector = APIC_VECTOR_PROFILE;
HlWriteApicRegister(APIC_TMRLVTR, LvtRegister.Long); HlWriteApicRegister(APIC_TMRLVTR, LvtRegister.Long);
/* Mask PCLVTR */ /* Configure the performance counter overflow */
LvtRegister.Long = 0; LvtRegister.Long = 0;
LvtRegister.Mask = 0; LvtRegister.Mask = 0;
LvtRegister.MessageType = APIC_DM_FIXED; LvtRegister.DeliveryMode = APIC_DM_FIXED;
LvtRegister.TimerMode = 0; LvtRegister.TimerMode = 0;
LvtRegister.TriggerMode = APIC_TGM_EDGE; LvtRegister.TriggerMode = APIC_TGM_EDGE;
LvtRegister.Vector = APIC_VECTOR_PERF; LvtRegister.Vector = APIC_VECTOR_PERF;
HlWriteApicRegister(APIC_PCLVTR, LvtRegister.Long); HlWriteApicRegister(APIC_PCLVTR, LvtRegister.Long);
/* Mask LINT0 */ /* Configure the LINT0 pin */
LvtRegister.Long = 0; LvtRegister.Long = 0;
LvtRegister.Mask = 1; LvtRegister.Mask = 1;
LvtRegister.MessageType = APIC_DM_FIXED; LvtRegister.DeliveryMode = APIC_DM_FIXED;
LvtRegister.TimerMode = 0; LvtRegister.TimerMode = 0;
LvtRegister.TriggerMode = APIC_TGM_EDGE; LvtRegister.TriggerMode = APIC_TGM_EDGE;
LvtRegister.Vector = APIC_VECTOR_SPURIOUS; LvtRegister.Vector = APIC_VECTOR_SPURIOUS;
HlWriteApicRegister(APIC_LINT0, LvtRegister.Long); HlWriteApicRegister(APIC_LINT0, LvtRegister.Long);
/* Mask LINT1 */ /* Configure the LINT1 pin */
LvtRegister.Long = 0; LvtRegister.Long = 0;
LvtRegister.Mask = 0; LvtRegister.Mask = 0;
LvtRegister.MessageType = APIC_DM_NMI; LvtRegister.DeliveryMode = APIC_DM_NMI;
LvtRegister.TimerMode = 0; LvtRegister.TimerMode = 0;
LvtRegister.TriggerMode = APIC_TGM_EDGE; LvtRegister.TriggerMode = APIC_TGM_EDGE;
LvtRegister.Vector = APIC_VECTOR_NMI; LvtRegister.Vector = APIC_VECTOR_NMI;
HlWriteApicRegister(APIC_LINT1, LvtRegister.Long); HlWriteApicRegister(APIC_LINT1, LvtRegister.Long);
/* Mask ICR0 */ /* Register interrupt handlers */
CommandRegister.Long0 = 0;
CommandRegister.DestinationShortHand = APIC_DSH_Destination;
CommandRegister.MessageType = APIC_MT_INIT;
CommandRegister.DestinationMode = 1;
CommandRegister.TriggerMode = APIC_TGM_EDGE;
CommandRegister.Vector = APIC_VECTOR_ZERO;
HlWriteApicRegister(APIC_ICR0, CommandRegister.Long0);
/* Register interrupt handlers once the APIC initialization is done */
KeSetInterruptHandler(APIC_VECTOR_SPURIOUS, HlpHandleApicSpuriousService); KeSetInterruptHandler(APIC_VECTOR_SPURIOUS, HlpHandleApicSpuriousService);
KeSetInterruptHandler(PIC1_VECTOR_SPURIOUS, HlpHandlePicSpuriousService); KeSetInterruptHandler(PIC1_VECTOR_SPURIOUS, HlpHandlePicSpuriousService);
/* Clear errors after enabling vectors */ /* Clear any pre-existing errors */
HlWriteApicRegister(APIC_ESR, 0); HlWriteApicRegister(APIC_ESR, 0);
/* Lower APIC TPR to re-enable interrupts */ /* Re-enable all interrupts by lowering the Task Priority Register */
HlWriteApicRegister(APIC_TPR, 0x00); HlWriteApicRegister(APIC_TPR, 0x00);
} }
@@ -371,3 +381,35 @@ HlpInitializePic(VOID)
/* Initialize legacy PIC */ /* Initialize legacy PIC */
HlpInitializeLegacyPic(); HlpInitializeLegacyPic();
} }
/**
* Sends an IPI (Inter-Processor Interrupt) to the specified CPU.
*
* @param ApicId
* Supplies a CPU APIC ID to send an IPI to.
*
* @param Vector
* Supplies the IPI vector to send.
*
* @return This routine does not return any value.
*
* @since XT 1.0
*/
XTAPI
VOID
HlpSendIpi(ULONG ApicId,
ULONG Vector)
{
/* Check current APIC mode */
if(HlpApicMode == APIC_MODE_X2APIC)
{
/* Send IPI using x2APIC mode */
HlWriteApicRegister(APIC_ICR0, ((ULONGLONG)ApicId << 32) | Vector);
}
else
{
/* Send IPI using xAPIC compatibility mode */
HlWriteApicRegister(APIC_ICR1, ApicId << 24);
HlWriteApicRegister(APIC_ICR0, Vector);
}
}

View File

@@ -25,6 +25,10 @@ XTCDECL
VOID VOID
ArFlushTlb(VOID); ArFlushTlb(VOID);
XTAPI
PVOID
ArGetBootStack(VOID);
XTCDECL XTCDECL
ULONG ULONG
ArGetCpuFlags(VOID); ArGetCpuFlags(VOID);
@@ -431,4 +435,8 @@ XTCDECL
VOID VOID
ArpTrap0xE1(VOID); ArpTrap0xE1(VOID);
XTCDECL
VOID
ArpTrap0xFF(VOID);
#endif /* __XTOSKRNL_AMD64_ARI_H */ #endif /* __XTOSKRNL_AMD64_ARI_H */

View File

@@ -10,6 +10,21 @@
#define __XTOSKRNL_AMD64_ASMSUP_H #define __XTOSKRNL_AMD64_ASMSUP_H
/* Control Register bit definitions */
#define CR0_PG 0x80000000
#define CR4_PGE 0x00000080
#define CR4_LA57 0x00001000
#define CR4_PCIDE 0x00020000
/* GDT selectors */
#define GDT_R0_CMCODE 0x08
#define GDT_R0_CODE 0x10
#define GDT_R0_DATA 0x18
/* MSR registers */
#define X86_MSR_EFER 0xC0000080
#define X86_MSR_EFER_LME (1 << 8)
/* KTRAP_FRAME structure offsets */ /* KTRAP_FRAME structure offsets */
#define TrapXmm0 0 #define TrapXmm0 0
#define TrapXmm1 16 #define TrapXmm1 16

View File

@@ -30,4 +30,10 @@ EXTERN UCHAR ArKernelBootStack[KERNEL_STACK_SIZE];
/* Kernel own fault stack */ /* Kernel own fault stack */
EXTERN UCHAR ArKernelFaultStack[KERNEL_STACK_SIZE]; EXTERN UCHAR ArKernelFaultStack[KERNEL_STACK_SIZE];
/* Page mapping routines for systems using 4-level paging (PML4) */
EXTERN CMMPAGEMAP_ROUTINES MmpPml4Routines;
/* Page mapping routines for systems using 5-level paging (PML5) */
EXTERN CMMPAGEMAP_ROUTINES MmpPml5Routines;
#endif /* __XTOSKRNL_AMD64_GLOBALS_H */ #endif /* __XTOSKRNL_AMD64_GLOBALS_H */

View File

@@ -18,7 +18,7 @@ VOID
HlClearApicErrors(VOID); HlClearApicErrors(VOID);
XTFASTCALL XTFASTCALL
ULONG ULONGLONG
HlReadApicRegister(IN APIC_REGISTER Register); HlReadApicRegister(IN APIC_REGISTER Register);
XTAPI XTAPI
@@ -28,12 +28,16 @@ HlSendEoi(VOID);
XTFASTCALL XTFASTCALL
VOID VOID
HlWriteApicRegister(IN APIC_REGISTER Register, HlWriteApicRegister(IN APIC_REGISTER Register,
IN ULONG Value); IN ULONGLONG Value);
XTAPI XTAPI
BOOLEAN BOOLEAN
HlpCheckX2ApicSupport(VOID); HlpCheckX2ApicSupport(VOID);
XTAPI
ULONG
HlpGetCpuApicId(VOID);
XTCDECL XTCDECL
VOID VOID
HlpHandleApicSpuriousService(VOID); HlpHandleApicSpuriousService(VOID);
@@ -54,6 +58,11 @@ XTAPI
VOID VOID
HlpInitializePic(); HlpInitializePic();
XTAPI
VOID
HlpSendIpi(ULONG ApicId,
ULONG Vector);
XTFASTCALL XTFASTCALL
KRUNLEVEL KRUNLEVEL
HlpTransformApicTprToRunLevel(IN UCHAR Tpr); HlpTransformApicTprToRunLevel(IN UCHAR Tpr);

View File

@@ -55,6 +55,6 @@ KepStartKernel(VOID);
XTAPI XTAPI
VOID VOID
KepSwitchBootStack(IN ULONG_PTR Stack); KepSwitchBootStack();
#endif /* __XTOSKRNL_AMD64_KEI_H */ #endif /* __XTOSKRNL_AMD64_KEI_H */

View File

@@ -13,17 +13,33 @@
/* AMD64 Memory Manager routines forward references */ /* AMD64 Memory Manager routines forward references */
XTAPI
VOID
MmInitializePageMapSupport(VOID);
XTFASTCALL XTFASTCALL
VOID VOID
MmZeroPages(IN PVOID Address, MmZeroPages(IN PVOID Address,
IN ULONG Size); IN ULONG Size);
XTAPI XTAPI
PMMPTE VOID
MmpClearPte(PHARDWARE_PTE PtePointer);
XTAPI
BOOLEAN
MmpGetExtendedPhysicalAddressingStatus(VOID);
XTAPI
PMMP5E
MmpGetP5eAddress(PVOID Address);
XTAPI
PMMPDE
MmpGetPdeAddress(PVOID Address); MmpGetPdeAddress(PVOID Address);
XTAPI XTAPI
PMMPTE PMMPPE
MmpGetPpeAddress(PVOID Address); MmpGetPpeAddress(PVOID Address);
XTAPI XTAPI
@@ -31,7 +47,7 @@ PMMPTE
MmpGetPteAddress(PVOID Address); MmpGetPteAddress(PVOID Address);
XTAPI XTAPI
PMMPTE PMMPXE
MmpGetPxeAddress(PVOID Address); MmpGetPxeAddress(PVOID Address);
XTAPI XTAPI
@@ -40,6 +56,18 @@ MmpInitializeArchitecture(VOID);
XTAPI XTAPI
BOOLEAN BOOLEAN
MmpMemoryExtensionEnabled(VOID); MmpPteValid(PHARDWARE_PTE PtePointer);
XTAPI
VOID
MmpSetPte(PHARDWARE_PTE PtePointer,
PFN_NUMBER PageFrameNumber,
BOOLEAN Writable);
XTAPI
VOID
MmpSetPteCaching(PHARDWARE_PTE PtePointer,
BOOLEAN CacheDisable,
BOOLEAN WriteThrough);
#endif /* __XTOSKRNL_AMD64_MMI_H */ #endif /* __XTOSKRNL_AMD64_MMI_H */

18
xtoskrnl/includes/ar.hh Normal file
View File

@@ -0,0 +1,18 @@
/**
* PROJECT: ExectOS
* COPYRIGHT: See COPYING.md in the top level directory
* FILE: xtoskrnl/includes/ar.hh
* DESCRIPTION:
* DEVELOPERS: Aiken Harris <harraiken91@gmail.com>
*/
#ifndef __XTOSKRNL_AR_HH
#define __XTOSKRNL_AR_HH
#include <xtos.hh>
#include XTOS_ARCH_HEADER(ar, cpufunc.hh)
#include XTOS_ARCH_HEADER(ar, procsup.hh)
#include XTOS_ARCH_HEADER(ar, traps.hh)
#endif /* __XTOSKRNL_AR_HH */

View File

@@ -0,0 +1,62 @@
/**
* PROJECT: ExectOS
* COPYRIGHT: See COPYING.md in the top level directory
* FILE: xtoskrnl/includes/ar/amd64/cpufunc.hh
* DESCRIPTION: Architecture-specific CPU control and utility functions for low-level system operations
* DEVELOPERS: Aiken Harris <harraiken91@gmail.com>
*/
#ifndef __XTOSKRNL_AR_CPUFUNC_HH
#define __XTOSKRNL_AR_CPUFUNC_HH
#include <xtos.hh>
/* Architecture-specific Library */
namespace AR
{
class CpuFunc
{
public:
STATIC XTCDECL VOID ClearInterruptFlag(VOID);
STATIC XTCDECL BOOLEAN CpuId(IN OUT PCPUID_REGISTERS Registers);
STATIC XTCDECL VOID FlushTlb(VOID);
STATIC XTCDECL ULONG GetCpuFlags(VOID);
STATIC XTASSEMBLY XTCDECL ULONG_PTR GetStackPointer(VOID);
STATIC XTCDECL VOID Halt(VOID);
STATIC XTCDECL BOOLEAN InterruptsEnabled(VOID);
STATIC XTCDECL VOID InvalidateTlbEntry(IN PVOID Address);
STATIC XTCDECL VOID LoadGlobalDescriptorTable(IN PVOID Source);
STATIC XTCDECL VOID LoadInterruptDescriptorTable(IN PVOID Source);
STATIC XTCDECL VOID LoadLocalDescriptorTable(IN USHORT Source);
STATIC XTCDECL VOID LoadMxcsrRegister(IN ULONG Source);
STATIC XTCDECL VOID LoadSegment(IN USHORT Segment,
IN ULONG Source);
STATIC XTCDECL VOID LoadTaskRegister(USHORT Source);
STATIC XTCDECL VOID MemoryBarrier(VOID);
STATIC XTCDECL ULONG_PTR ReadControlRegister(IN USHORT ControlRegister);
STATIC XTCDECL ULONG_PTR ReadDebugRegister(IN USHORT DebugRegister);
STATIC XTCDECL ULONGLONG ReadGSQuadWord(ULONG Offset);
STATIC XTCDECL ULONGLONG ReadModelSpecificRegister(IN ULONG Register);
STATIC XTCDECL UINT ReadMxCsrRegister(VOID);
STATIC XTCDECL ULONGLONG ReadTimeStampCounter(VOID);
STATIC XTCDECL VOID ReadWriteBarrier(VOID);
STATIC XTCDECL VOID SetInterruptFlag(VOID);
STATIC XTCDECL VOID StoreGlobalDescriptorTable(OUT PVOID Destination);
STATIC XTCDECL VOID StoreInterruptDescriptorTable(OUT PVOID Destination);
STATIC XTCDECL VOID StoreLocalDescriptorTable(OUT PVOID Destination);
STATIC XTCDECL VOID StoreSegment(IN USHORT Segment,
OUT PVOID Destination);
STATIC XTCDECL VOID StoreTaskRegister(OUT PVOID Destination);
STATIC XTCDECL VOID WriteControlRegister(IN USHORT ControlRegister,
IN UINT_PTR Value);
STATIC XTCDECL VOID WriteDebugRegister(IN USHORT DebugRegister,
IN UINT_PTR Value);
STATIC XTCDECL VOID WriteEflagsRegister(IN UINT_PTR Value);
STATIC XTCDECL VOID WriteModelSpecificRegister(IN ULONG Register,
IN ULONGLONG Value);
STATIC XTCDECL VOID YieldProcessor(VOID);
};
}
#endif /* __XTOSKRNL_AR_CPUFUNC_HH */

Some files were not shown because too many files have changed in this diff Show More