Compare commits

..

174 Commits

Author SHA1 Message Date
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
109 changed files with 5912 additions and 1745 deletions

View File

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

View File

@ -1,8 +1,5 @@
# Detect XTChain toolchain
# Minimum CMake version requirement
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
string(TOLOWER ${ARCH} ARCH)
@ -44,7 +41,7 @@ set(CMAKE_TOOLCHAIN_FILE "sdk/cmake/toolchain.cmake")
project(EXECTOS)
# Load all the CMake SDK
include(sdk/cmake/baseaddress.cmake)
include(sdk/cmake/baseaddress/${ARCH}.cmake)
include(sdk/cmake/emulation.cmake)
include(sdk/cmake/functions.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.
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.
- [ ] 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
disk).

View File

@ -8,14 +8,14 @@
<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">
</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">
</a>
<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">
</a>
<a href="https://codeium.com/">
<img alt="Codeium" src="https://img.shields.io/badge/Powered%20By-Codeium-09B6A2?logo=Codeium">
<a href="https://exectos.eu.org/ai-assisted">
<img alt="AI Assisted" src="https://img.shields.io/badge/AI-Assisted-darkcyan">
</a>
<a href="https://github.com/sponsors/xt-sys/">
<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 |
# Build
XTOS can be built only by using [XTChain](https://git.codingworkshop.eu.org/xt-sys/xtchain), a special toolchain
prepared for compiling XT software. Currently, there is only a Linux version available, so a Linux distribution or WSL
is needed. If XTChain is already installed and available, then building ExectOS is quiet easy. First, open a terminal
or WSL console and type the following command to launch XTChain build console:
```
xtchain
```
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:
XTOS can only be built using [XTchain](https://git.codingworkshop.eu.org/xt-sys/xtchain), a dedicated toolchain designed
specifically for compiling XT software. XTChain is currently available for both Linux and Windows. Detailed instructions
on how to configure and run XTChain can be found [here](https://exectos.eu.org/contributing/setting-up-xtchain).
With the XTchain environment already running, navigate to the directory containing the ExectOS source code and use the
following commands to set the target build architecture and configure the sources:
```
charch [i686|amd64]
chbuild [DEBUG|RELEASE]

View File

@ -40,6 +40,30 @@ SystemPath=multi(0)disk(0)rdisk(0)partition(1)/ExectOS
KernelFile=xtoskrnl.exe
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]
SystemName="Microsoft Windows 2000"
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
# 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
if [ "x${XTCVER}" = "x" ]; then
@ -16,13 +22,12 @@ fi
# Set variables
EXECTOS_SOURCE_DIR=$(cd `dirname ${0}` && pwd)
EXECTOS_BINARY_DIR=build-${ARCH}-xtchain
EXECTOS_BINARY_DIR=build-${ARCH}-${BUILD_TYPE,,}
# Create directories if needed
if [ "${EXECTOS_SOURCE_DIR}" = "${PWD}" ]; then
echo Creating directories in ${EXECTOS_BINARY_DIR}
mkdir -p "${EXECTOS_BINARY_DIR}"
ln -sf ${EXECTOS_BINARY_DIR} build
cd "${EXECTOS_BINARY_DIR}"
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(BASEADDRESS_XTLDR 0x00010000)
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
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
-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_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
VERBATIM USES_TERMINAL)
# This target starts up a QEMU+OVMF virtual machine using TCG accelerator
add_custom_target(testtcg
DEPENDS diskimg
DEPENDS install
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
-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
-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
VERBATIM USES_TERMINAL)

View File

@ -11,11 +11,10 @@ endif()
# Set build optimisation
if(BUILD_TYPE STREQUAL "DEBUG")
add_compiler_ccxxflags("/Zi")
add_compiler_ccxxflags("-Ob0 -Od")
add_compiler_ccxxflags("/GS- /Zi /Ob0 /Od")
add_linker_flags("/DEBUG /INCREMENTAL /OPT:NOREF /OPT:NOICF /PDBSOURCEPATH:build")
else()
add_compiler_ccxxflags("-Ob2 -Oy")
add_compiler_ccxxflags("/GS- /Ob2 /Ot /Ox /Oy")
add_linker_flags("/INCREMENTAL:NO /OPT:REF /OPT:ICF")
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-gnu-folding-constant")
# Disable compiler builtins
add_compiler_ccxxflags("-fno-builtin")
# Set debugging symbols output directory
set(CMAKE_PDB_OUTPUT_DIRECTORY "${EXECTOS_BINARY_DIR}/output/symbols")

View File

@ -24,6 +24,10 @@ XTCDECL
BOOLEAN
ArCpuId(IN OUT PCPUID_REGISTERS Registers);
XTCDECL
VOID
ArEnableExtendedPhysicalAddressing(IN ULONG_PTR PageMap);
XTCDECL
VOID
ArHalt(VOID);

View File

@ -39,13 +39,22 @@
#define CR4_PCE 0x00000100
#define CR4_FXSR 0x00000200
#define CR4_XMMEXCPT 0x00000400
#define CR4_UMIP 0x00000800
#define CR4_LA57 0x00001000
#define CR4_RESERVED1 0x00001800
#define CR4_VMXE 0x00002000
#define CR4_SMXE 0x00004000
#define CR4_RESERVED2 0x00018000
#define CR4_XSAVE 0x00020000
#define CR4_RESERVED3 0xFFFC0000
#define CR4_FSGSBASE 0x00010000
#define CR4_PCIDE 0x00020000
#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 */
#define GDT_ENTRIES 128
@ -84,6 +93,7 @@
#define X86_MSR_FSBASE 0xC0000100
#define X86_MSR_GSBASE 0xC0000101
#define X86_MSR_KERNEL_GSBASE 0xC0000102
#define X86_MSR_TSC_AUX 0xC0000103
/* Processor features in the EFER MSR */
#define X86_MSR_EFER_SCE (1 << 0)
@ -91,6 +101,10 @@
#define X86_MSR_EFER_LMA (1 << 10)
#define X86_MSR_EFER_NXE (1 << 11)
#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 */
#define X86_EFLAGS_NF_MASK 0x00000000 /* None */
@ -121,79 +135,255 @@ typedef enum _CPU_VENDOR
CPU_VENDOR_UNKNOWN = 0xFFFFFFFF
} CPU_VENDOR, *PCPU_VENDOR;
/* CPUID features enumeration list */
typedef enum _CPUID_FEATURES
/* CPUID extended features (0x80000001) enumeration list */
typedef enum _CPUID_FEATURES_EXTENDED
{
CPUID_FEATURES_ECX_SSE3 = 1 << 0,
CPUID_FEATURES_ECX_PCLMUL = 1 << 1,
CPUID_FEATURES_ECX_DTES64 = 1 << 2,
CPUID_FEATURES_ECX_MONITOR = 1 << 3,
CPUID_FEATURES_ECX_DS_CPL = 1 << 4,
CPUID_FEATURES_ECX_VMX = 1 << 5,
CPUID_FEATURES_ECX_SMX = 1 << 6,
CPUID_FEATURES_ECX_EST = 1 << 7,
CPUID_FEATURES_ECX_TM2 = 1 << 8,
CPUID_FEATURES_ECX_SSSE3 = 1 << 9,
CPUID_FEATURES_ECX_CID = 1 << 10,
CPUID_FEATURES_ECX_SDBG = 1 << 11,
CPUID_FEATURES_ECX_FMA = 1 << 12,
CPUID_FEATURES_ECX_CX16 = 1 << 13,
CPUID_FEATURES_ECX_XTPR = 1 << 14,
CPUID_FEATURES_ECX_PDCM = 1 << 15,
CPUID_FEATURES_ECX_PCID = 1 << 17,
CPUID_FEATURES_ECX_DCA = 1 << 18,
CPUID_FEATURES_ECX_SSE4_1 = 1 << 19,
CPUID_FEATURES_ECX_SSE4_2 = 1 << 20,
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, *PCPUID_FEATURES;
CPUID_FEATURES_ECX_LAHF_SAHF = 1 << 0,
CPUID_FEATURES_ECX_CMP_LEGACY = 1 << 1,
CPUID_FEATURES_ECX_SVM = 1 << 2,
CPUID_FEATURES_ECX_EXT_APIC_SPACE = 1 << 3,
CPUID_FEATURES_ECX_ALT_MOV_CR8 = 1 << 4,
CPUID_FEATURES_ECX_LZCNT = 1 << 5,
CPUID_FEATURES_ECX_SSE4A = 1 << 6,
CPUID_FEATURES_ECX_MISALIGNED_SSE = 1 << 7,
CPUID_FEATURES_ECX_PREFETCHW = 1 << 8,
CPUID_FEATURES_ECX_OSVW = 1 << 9,
CPUID_FEATURES_ECX_IBS = 1 << 10,
CPUID_FEATURES_ECX_XOP = 1 << 11,
CPUID_FEATURES_ECX_SKINIT = 1 << 12,
CPUID_FEATURES_ECX_WDT = 1 << 13,
CPUID_FEATURES_ECX_LWP = 1 << 15,
CPUID_FEATURES_ECX_FMA4 = 1 << 16,
CPUID_FEATURES_ECX_TCE = 1 << 17,
CPUID_FEATURES_ECX_NODEID = 1 << 19,
CPUID_FEATURES_ECX_TBM = 1 << 21,
CPUID_FEATURES_ECX_TOPOLOGY_EXTENSIONS = 1 << 22,
CPUID_FEATURES_ECX_PERFCTR_EXT_CORE = 1 << 23,
CPUID_FEATURES_ECX_PERFCTR_EXT_NB = 1 << 24,
CPUID_FEATURES_ECX_DATA_BREAKPOINT_EXT = 1 << 26,
CPUID_FEATURES_ECX_PERF_TSC = 1 << 27,
CPUID_FEATURES_ECX_PERFCTR_EXT_L2I = 1 << 28,
CPUID_FEATURES_ECX_MONITORX_MWAITX = 1 << 29,
CPUID_FEATURES_ECX_CODEBP_ADDRMASK_EXT = 1 << 30,
CPUID_FEATURES_EDX_SYSCALL_SYSRET = 1 << 11,
CPUID_FEATURES_EDX_NX = 1 << 20,
CPUID_FEATURES_EDX_AMD_MMX_EXT = 1 << 22,
CPUID_FEATURES_EDX_FFXSR = 1 << 25,
CPUID_FEATURES_EDX_1G_PAGES = 1 << 26,
CPUID_FEATURES_EDX_RDTSCP = 1 << 27,
CPUID_FEATURES_EDX_LONG_MODE = 1 << 29,
CPUID_FEATURES_EDX_3DNOW_EXT = 1 << 30,
CPUID_FEATURES_EDX_3DNOW = 1 << 31
} CPUID_FEATURES_EXTENDED, *PCPUID_FEATURES_EXTENDED;
/* CPUID STD1 features (0x00000001) enumeration list */
typedef enum _CPUID_FEATURES_STANDARD1
{
CPUID_FEATURES_ECX_SSE3 = 1 << 0,
CPUID_FEATURES_ECX_PCLMUL = 1 << 1,
CPUID_FEATURES_ECX_DTES64 = 1 << 2,
CPUID_FEATURES_ECX_MONITOR = 1 << 3,
CPUID_FEATURES_ECX_DS_CPL = 1 << 4,
CPUID_FEATURES_ECX_VMX = 1 << 5,
CPUID_FEATURES_ECX_SMX = 1 << 6,
CPUID_FEATURES_ECX_EST = 1 << 7,
CPUID_FEATURES_ECX_TM2 = 1 << 8,
CPUID_FEATURES_ECX_SSSE3 = 1 << 9,
CPUID_FEATURES_ECX_CID = 1 << 10,
CPUID_FEATURES_ECX_SDBG = 1 << 11,
CPUID_FEATURES_ECX_FMA = 1 << 12,
CPUID_FEATURES_ECX_CX16 = 1 << 13,
CPUID_FEATURES_ECX_XTPR = 1 << 14,
CPUID_FEATURES_ECX_PDCM = 1 << 15,
CPUID_FEATURES_ECX_PCID = 1 << 17,
CPUID_FEATURES_ECX_DCA = 1 << 18,
CPUID_FEATURES_ECX_SSE4_1 = 1 << 19,
CPUID_FEATURES_ECX_SSE4_2 = 1 << 20,
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 */
typedef enum _CPUID_REQUESTS
{
CPUID_GET_VENDOR_STRING,
CPUID_GET_CPU_FEATURES,
CPUID_GET_TLB,
CPUID_GET_SERIAL
CPUID_GET_STANDARD1_FEATURES,
CPUID_GET_TLB_CACHE,
CPUID_GET_SERIAL,
CPUID_GET_CACHE_TOPOLOGY,
CPUID_GET_MONITOR_MWAIT,
CPUID_GET_POWER_MANAGEMENT,
CPUID_GET_STANDARD7_FEATURES
} CPUID_REQUESTS, *PCPUID_REQUESTS;
/* Processor identification information */

View File

@ -42,20 +42,14 @@
#define APIC_DF_FLAT 0xFFFFFFFF
#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 */
#define APIC_TGM_EDGE 0
#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 */
#define APIC_MAX_IOAPICS 64
@ -75,6 +69,35 @@
/* Initial stall factor */
#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 */
typedef enum _APIC_REGISTER
{
@ -112,35 +135,6 @@ typedef enum _APIC_REGISTER
APIC_EXT3LVTR = 0x53 /* Extended Interrupt 3 Local Vector Table */
} 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 */
typedef enum _PIC_I8259_ICW1_INTERRUPT_MODE
{
@ -213,7 +207,7 @@ typedef union _APIC_COMMAND_REGISTER
struct
{
ULONGLONG Vector:8;
ULONGLONG MessageType:3;
ULONGLONG DeliveryMode:3;
ULONGLONG DestinationMode:1;
ULONGLONG DeliveryStatus:1;
ULONGLONG ReservedMBZ:1;
@ -233,7 +227,7 @@ typedef union _APIC_LVT_REGISTER
struct
{
ULONG Vector:8;
ULONG MessageType:3;
ULONG DeliveryMode:3;
ULONG Reserved1:1;
ULONG DeliveryStatus:1;
ULONG Reserved2:1;

View File

@ -18,11 +18,18 @@
#define MM_PAGE_SHIFT 12L
#define MM_PAGE_SIZE 4096
/* Page directory and page base addresses */
#define MM_PTE_BASE 0xFFFFF68000000000UI64
#define MM_PDE_BASE 0xFFFFF6FB40000000UI64
#define MM_PPE_BASE 0xFFFFF6FB7DA00000UI64
#define MM_PXE_BASE 0xFFFFF6FB7DBED000UI64
/* Page directory and page base addresses for 4-level paging */
#define MM_PTE_BASE 0xFFFFF68000000000ULL
#define MM_PDE_BASE 0xFFFFF6FB40000000ULL
#define MM_PPE_BASE 0xFFFFF6FB7DA00000ULL
#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 */
#define MM_PTE_SHIFT 3
@ -30,7 +37,7 @@
#define MM_PDI_SHIFT 21
#define MM_PPI_SHIFT 30
#define MM_PXI_SHIFT 39
#define MM_LA57_SHIFT 48
#define MM_P5I_SHIFT 48
/* Number of PTEs per page */
#define MM_PTE_PER_PAGE 512
@ -54,7 +61,10 @@
#define MM_HARDWARE_VA_START 0xFFFFFFFFFFC00000ULL
/* 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 */
typedef enum _PAGE_SIZE
@ -85,6 +95,18 @@ typedef struct _HARDWARE_PTE
ULONGLONG NoExecute:1;
} 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 */
typedef struct _MMPTE_HARDWARE
{

View File

@ -13,12 +13,15 @@
/* 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_MODE APIC_MODE, *PAPIC_MODE;
typedef enum _APIC_MT APIC_MT, *PAPIC_MT;
typedef enum _APIC_REGISTER APIC_REGISTER, *PAPIC_REGISTER;
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 _PAGE_SIZE PAGE_SIZE, *PPAGE_SIZE;
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 _KTRAP_FRAME KTRAP_FRAME, *PKTRAP_FRAME;
typedef struct _KTSS KTSS, *PKTSS;
typedef struct _MMPAGEMAP_INFO MMPAGEMAP_INFO, *PMMPAGEMAP_INFO;
typedef struct _MMPFN MMPFN, *PMMPFN;
typedef struct _MMPTE_HARDWARE MMPTE_HARDWARE, *PMMPTE_HARDWARE;
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_LVT_REGISTER APIC_LVT_REGISTER, *PAPIC_LVT_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 MMPPE, *PMMPPE;
typedef union _MMPTE MMPTE, *PMMPTE;

View File

@ -18,10 +18,11 @@
/* EFI XT boot devices */
#define XTBL_BOOT_DEVICE_UNKNOWN 0x00
#define XTBL_BOOT_DEVICE_CDROM 0x01
#define XTBL_BOOT_DEVICE_FLOPPY 0x02
#define XTBL_BOOT_DEVICE_HARDDISK 0x03
#define XTBL_BOOT_DEVICE_RAMDISK 0x04
#define XTBL_BOOT_DEVICE_ESP 0x01
#define XTBL_BOOT_DEVICE_CDROM 0x02
#define XTBL_BOOT_DEVICE_FLOPPY 0x04
#define XTBL_BOOT_DEVICE_HARDDISK 0x08
#define XTBL_BOOT_DEVICE_RAMDISK 0x10
/* XTLDR Debug Port type definitions */
#define XTBL_DEBUGPORT_SCREEN 1
@ -43,27 +44,31 @@
typedef LONG (*PBL_GET_MEMTYPE_ROUTINE)(IN EFI_MEMORY_TYPE EfiMemoryType);
/* 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_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_CLOSE_VOLUME)(IN PEFI_HANDLE VolumeHandle);
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 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_DISABLE_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_READ_KEY_STROKE)(OUT PEFI_INPUT_KEY Key);
typedef VOID (*PBL_CONSOLE_RESET_INPUT_BUFFER)();
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_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 (*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_EXIT_BOOT_SERVICES)();
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_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_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_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);
@ -152,6 +157,7 @@ typedef struct _XTBL_BOOT_PARAMETERS
typedef struct _XTBL_BOOTMENU_ITEM
{
PWCHAR EntryName;
PWCHAR FullName;
PWCHAR ShortName;
PLIST_ENTRY Options;
} XTBL_BOOTMENU_ITEM, *PXTBL_BOOTMENU_ITEM;
@ -354,9 +360,16 @@ typedef struct _XTBL_LOADER_PROTOCOL
PBL_REGISTER_BOOT_PROTOCOL RegisterProtocol;
} Boot;
struct
{
PBL_BOOTUTIL_GET_BOOLEAN_PARAMETER GetBooleanParameter;
} BootUtil;
struct
{
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_SET_BOOT_OPTION_VALUE SetBootOptionValue;
} Config;
struct
{

View File

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

View File

@ -39,13 +39,22 @@
#define CR4_PCE 0x00000100
#define CR4_FXSR 0x00000200
#define CR4_XMMEXCPT 0x00000400
#define CR4_UMIP 0x00000800
#define CR4_LA57 0x00001000
#define CR4_RESERVED1 0x00001800
#define CR4_VMXE 0x00002000
#define CR4_SMXE 0x00004000
#define CR4_RESERVED2 0x00018000
#define CR4_XSAVE 0x00020000
#define CR4_RESERVED3 0xFFFC0000
#define CR4_FSGSBASE 0x00010000
#define CR4_PCIDE 0x00020000
#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 */
#define GDT_ENTRIES 128
@ -91,79 +100,255 @@ typedef enum _CPU_VENDOR
CPU_VENDOR_UNKNOWN = 0xFFFFFFFF
} CPU_VENDOR, *PCPU_VENDOR;
/* CPUID features enumeration list */
typedef enum _CPUID_FEATURES
/* CPUID extended features (0x80000001) enumeration list */
typedef enum _CPUID_FEATURES_EXTENDED
{
CPUID_FEATURES_ECX_SSE3 = 1 << 0,
CPUID_FEATURES_ECX_PCLMUL = 1 << 1,
CPUID_FEATURES_ECX_DTES64 = 1 << 2,
CPUID_FEATURES_ECX_MONITOR = 1 << 3,
CPUID_FEATURES_ECX_DS_CPL = 1 << 4,
CPUID_FEATURES_ECX_VMX = 1 << 5,
CPUID_FEATURES_ECX_SMX = 1 << 6,
CPUID_FEATURES_ECX_EST = 1 << 7,
CPUID_FEATURES_ECX_TM2 = 1 << 8,
CPUID_FEATURES_ECX_SSSE3 = 1 << 9,
CPUID_FEATURES_ECX_CID = 1 << 10,
CPUID_FEATURES_ECX_SDBG = 1 << 11,
CPUID_FEATURES_ECX_FMA = 1 << 12,
CPUID_FEATURES_ECX_CX16 = 1 << 13,
CPUID_FEATURES_ECX_XTPR = 1 << 14,
CPUID_FEATURES_ECX_PDCM = 1 << 15,
CPUID_FEATURES_ECX_PCID = 1 << 17,
CPUID_FEATURES_ECX_DCA = 1 << 18,
CPUID_FEATURES_ECX_SSE4_1 = 1 << 19,
CPUID_FEATURES_ECX_SSE4_2 = 1 << 20,
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, *PCPUID_FEATURES;
CPUID_FEATURES_ECX_LAHF_SAHF = 1 << 0,
CPUID_FEATURES_ECX_CMP_LEGACY = 1 << 1,
CPUID_FEATURES_ECX_SVM = 1 << 2,
CPUID_FEATURES_ECX_EXT_APIC_SPACE = 1 << 3,
CPUID_FEATURES_ECX_ALT_MOV_CR8 = 1 << 4,
CPUID_FEATURES_ECX_LZCNT = 1 << 5,
CPUID_FEATURES_ECX_SSE4A = 1 << 6,
CPUID_FEATURES_ECX_MISALIGNED_SSE = 1 << 7,
CPUID_FEATURES_ECX_PREFETCHW = 1 << 8,
CPUID_FEATURES_ECX_OSVW = 1 << 9,
CPUID_FEATURES_ECX_IBS = 1 << 10,
CPUID_FEATURES_ECX_XOP = 1 << 11,
CPUID_FEATURES_ECX_SKINIT = 1 << 12,
CPUID_FEATURES_ECX_WDT = 1 << 13,
CPUID_FEATURES_ECX_LWP = 1 << 15,
CPUID_FEATURES_ECX_FMA4 = 1 << 16,
CPUID_FEATURES_ECX_TCE = 1 << 17,
CPUID_FEATURES_ECX_NODEID = 1 << 19,
CPUID_FEATURES_ECX_TBM = 1 << 21,
CPUID_FEATURES_ECX_TOPOLOGY_EXTENSIONS = 1 << 22,
CPUID_FEATURES_ECX_PERFCTR_EXT_CORE = 1 << 23,
CPUID_FEATURES_ECX_PERFCTR_EXT_NB = 1 << 24,
CPUID_FEATURES_ECX_DATA_BREAKPOINT_EXT = 1 << 26,
CPUID_FEATURES_ECX_PERF_TSC = 1 << 27,
CPUID_FEATURES_ECX_PERFCTR_EXT_L2I = 1 << 28,
CPUID_FEATURES_ECX_MONITORX_MWAITX = 1 << 29,
CPUID_FEATURES_ECX_CODEBP_ADDRMASK_EXT = 1 << 30,
CPUID_FEATURES_EDX_SYSCALL_SYSRET = 1 << 11,
CPUID_FEATURES_EDX_NX = 1 << 20,
CPUID_FEATURES_EDX_AMD_MMX_EXT = 1 << 22,
CPUID_FEATURES_EDX_FFXSR = 1 << 25,
CPUID_FEATURES_EDX_1G_PAGES = 1 << 26,
CPUID_FEATURES_EDX_RDTSCP = 1 << 27,
CPUID_FEATURES_EDX_LONG_MODE = 1 << 29,
CPUID_FEATURES_EDX_3DNOW_EXT = 1 << 30,
CPUID_FEATURES_EDX_3DNOW = 1 << 31
} CPUID_FEATURES_EXTENDED, *PCPUID_FEATURES_EXTENDED;
/* CPUID STD1 features (0x00000001) enumeration list */
typedef enum _CPUID_FEATURES_STANDARD1
{
CPUID_FEATURES_ECX_SSE3 = 1 << 0,
CPUID_FEATURES_ECX_PCLMUL = 1 << 1,
CPUID_FEATURES_ECX_DTES64 = 1 << 2,
CPUID_FEATURES_ECX_MONITOR = 1 << 3,
CPUID_FEATURES_ECX_DS_CPL = 1 << 4,
CPUID_FEATURES_ECX_VMX = 1 << 5,
CPUID_FEATURES_ECX_SMX = 1 << 6,
CPUID_FEATURES_ECX_EST = 1 << 7,
CPUID_FEATURES_ECX_TM2 = 1 << 8,
CPUID_FEATURES_ECX_SSSE3 = 1 << 9,
CPUID_FEATURES_ECX_CID = 1 << 10,
CPUID_FEATURES_ECX_SDBG = 1 << 11,
CPUID_FEATURES_ECX_FMA = 1 << 12,
CPUID_FEATURES_ECX_CX16 = 1 << 13,
CPUID_FEATURES_ECX_XTPR = 1 << 14,
CPUID_FEATURES_ECX_PDCM = 1 << 15,
CPUID_FEATURES_ECX_PCID = 1 << 17,
CPUID_FEATURES_ECX_DCA = 1 << 18,
CPUID_FEATURES_ECX_SSE4_1 = 1 << 19,
CPUID_FEATURES_ECX_SSE4_2 = 1 << 20,
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 */
typedef enum _CPUID_REQUESTS
{
CPUID_GET_VENDOR_STRING,
CPUID_GET_CPU_FEATURES,
CPUID_GET_TLB,
CPUID_GET_SERIAL
CPUID_GET_STANDARD1_FEATURES,
CPUID_GET_TLB_CACHE,
CPUID_GET_SERIAL,
CPUID_GET_CACHE_TOPOLOGY,
CPUID_GET_MONITOR_MWAIT,
CPUID_GET_POWER_MANAGEMENT,
CPUID_GET_STANDARD7_FEATURES
} CPUID_REQUESTS, *PCPUID_REQUESTS;
/* Processor identification information */

View File

@ -47,20 +47,14 @@
#define APIC_DF_FLAT 0xFFFFFFFF
#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 */
#define APIC_TGM_EDGE 0
#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 */
#define APIC_MAX_IOAPICS 64
@ -82,6 +76,35 @@
/* Initial stall factor */
#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 */
typedef enum _APIC_REGISTER
{
@ -119,35 +142,6 @@ typedef enum _APIC_REGISTER
APIC_EXT3LVTR = 0x53 /* Extended Interrupt 3 Local Vector Table */
} 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 */
typedef enum _PIC_I8259_ICW1_INTERRUPT_MODE
{
@ -220,7 +214,7 @@ typedef union _APIC_COMMAND_REGISTER
struct
{
ULONGLONG Vector:8;
ULONGLONG MessageType:3;
ULONGLONG DeliveryMode:3;
ULONGLONG DestinationMode:1;
ULONGLONG DeliveryStatus:1;
ULONGLONG ReservedMBZ:1;
@ -240,7 +234,7 @@ typedef union _APIC_LVT_REGISTER
struct
{
ULONG Vector:8;
ULONG MessageType:3;
ULONG DeliveryMode:3;
ULONG Reserved1:1;
ULONG DeliveryStatus:1;
ULONG Reserved2:1;

View File

@ -28,7 +28,11 @@
#define MM_PDI_SHIFT 21
#define MM_PPI_SHIFT 30
/* Page directory and page base legacy address */
#define MM_PDE_LEGACY_BASE 0xC0300000
/* PTE legacy shift values */
#define MM_PTE_LEGACY_SHIFT 2
#define MM_PDI_LEGACY_SHIFT 22
/* Minimum number of physical pages needed by the system */
@ -49,6 +53,8 @@
/* Maximum physical address used by HAL allocations */
#define MM_MAXIMUM_PHYSICAL_ADDRESS 0xFFFFFFFF
/* Trampoline code address */
#define MM_TRAMPOLINE_ADDRESS 0x80000
/* Page size enumeration list */
typedef enum _PAGE_SIZE
@ -58,8 +64,26 @@ typedef enum _PAGE_SIZE
Size4M
} PAGE_SIZE, *PPAGE_SIZE;
/* Page Table entry structure definition (with PAE support) */
typedef struct _HARDWARE_PTE
/* Legacy Page Table entry structure definition (PML2) */
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 Writable:1;
@ -77,10 +101,117 @@ typedef struct _HARDWARE_PTE
ULONGLONG Reserved1:14;
ULONGLONG SoftwareWsIndex:11;
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;
/* Page Table Entry on PAE enabled system */
typedef struct _MMPTE_HARDWARE
/* Page map information structure definition */
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 Writable:1;
@ -95,59 +226,59 @@ typedef struct _MMPTE_HARDWARE
ULONGLONG Prototype:1;
ULONGLONG Write:1;
ULONGLONG PageFrameNumber:26;
ULONGLONG Reserved1:25;
ULONGLONG Reserved0:25;
ULONGLONG NoExecute:1;
} MMPTE_HARDWARE, *PMMPTE_HARDWARE;
} MMPML3_PTE_HARDWARE, *PMMPML3_PTE_HARDWARE;
/* Page Table Entry list structure definition (with PAE support) */
typedef struct _MMPTE_LIST
/* Page Table Entry list structure definition (PML3) */
typedef struct _MMPML3_PTE_LIST
{
ULONGLONG Valid:1;
ULONGLONG OneEntry:1;
ULONGLONG Reserved1:8;
ULONGLONG Reserved0:8;
ULONGLONG Prototype:1;
ULONGLONG Reserved2:21;
ULONGLONG Reserved1:21;
ULONGLONG NextEntry:32;
} MMPTE_LIST, *PMMPTE_LIST;
} MMPML3_PTE_LIST, *PMMPML3_PTE_LIST;
/* Page Table Entry subsection structure definition (with PAE support) */
typedef struct _MMPTE_PROTOTYPE
/* Page Table Entry subsection structure definition (PML3) */
typedef struct _MMPML3_PTE_PROTOTYPE
{
ULONGLONG Valid:1;
ULONGLONG Reserved1:7;
ULONGLONG Reserved0:7;
ULONGLONG ReadOnly:1;
ULONGLONG Reserved2:1;
ULONGLONG Reserved1:1;
ULONGLONG Prototype:1;
ULONGLONG Protection:5;
ULONGLONG Reserved3:16;
ULONGLONG Reserved2:16;
ULONGLONG ProtoAddress:32;
} MMPTE_PROTOTYPE, *PMMPTE_PROTOTYPE;
} MMPML3_PTE_PROTOTYPE, *PMMPML3_PTE_PROTOTYPE;
/* Page Table Entry software structure definition (with PAE support) */
typedef struct _MMPTE_SOFTWARE
/* Page Table Entry software structure definition (PML3) */
typedef struct _MMPML3_PTE_SOFTWARE
{
ULONGLONG Valid:1;
ULONGLONG PageFileLow:4;
ULONGLONG Protection:5;
ULONGLONG Prototype:1;
ULONGLONG Transition:1;
ULONGLONG Reserved1:20;
ULONGLONG Reserved0:20;
ULONGLONG PageFileHigh:32;
} MMPTE_SOFTWARE, *PMMPTE_SOFTWARE;
} MMPML3_PTE_SOFTWARE, *PMMPML3_PTE_SOFTWARE;
/* Page Table Entry subsection structure definition (with PAE support) */
typedef struct _MMPTE_SUBSECTION
/* Page Table Entry subsection structure definition (PML3) */
typedef struct _MMPML3_PTE_SUBSECTION
{
ULONGLONG Valid:1;
ULONGLONG Reserved1:4;
ULONGLONG Reserved0:4;
ULONGLONG Protection:5;
ULONGLONG Prototype:1;
ULONGLONG Reserved2:21;
ULONGLONG Reserved1:21;
ULONGLONG SubsectionAddress:32;
} MMPTE_SUBSECTION, *PMMPTE_SUBSECTION;
} MMPML3_PTE_SUBSECTION, *PMMPML3_PTE_SUBSECTION;
/* Page Table Entry transition structure definition (with PAE support) */
typedef struct _MMPTE_TRANSITION
/* Page Table Entry transition structure definition (PML3) */
typedef struct _MMPML3_PTE_TRANSITION
{
ULONGLONG Valid:1;
ULONGLONG Write:1;
@ -159,38 +290,28 @@ typedef struct _MMPTE_TRANSITION
ULONGLONG Transition:1;
ULONGLONG PageFrameNumber:26;
ULONGLONG Unused:26;
} MMPTE_TRANSITION, *PMMPTE_TRANSITION;
} MMPML3_PTE_TRANSITION, *PMMPML3_PTE_TRANSITION;
/* Page Table Entry structure definition (with PAE support) */
typedef union _MMPTE
/* Page Table Entry union definition (PML3) */
typedef union _MMPML3_PTE
{
ULONGLONG Long;
HARDWARE_PTE Flush;
MMPTE_HARDWARE Hardware;
MMPTE_PROTOTYPE Prototype;
MMPTE_SOFTWARE Software;
MMPTE_TRANSITION Transition;
MMPTE_SUBSECTION Subsection;
MMPTE_LIST List;
} MMPTE, *PMMPTE;
MMPML3_PTE_HARDWARE Hardware;
MMPML3_PTE_PROTOTYPE Prototype;
MMPML3_PTE_SOFTWARE Software;
MMPML3_PTE_TRANSITION Transition;
MMPML3_PTE_SUBSECTION Subsection;
MMPML3_PTE_LIST List;
} MMPML3_PTE, *PMMPML3_PTE;
/* Legacy Page Table entry structure definition (without PAE support) */
typedef struct _HARDWARE_LEGACY_PTE
/* Generic Page Table Entry union to abstract PML2 and PML3 formats */
typedef union _MMPTE
{
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;
ULONGLONG Long;
MMPML2_PTE Pml2;
MMPML3_PTE Pml3;
} MMPTE, *PMMPTE;
/* Page Frame Number structure definition */
typedef struct _MMPFN

View File

@ -13,12 +13,15 @@
/* 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_MODE APIC_MODE, *PAPIC_MODE;
typedef enum _APIC_MT APIC_MT, *PAPIC_MT;
typedef enum _APIC_REGISTER APIC_REGISTER, *PAPIC_REGISTER;
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 _PAGE_SIZE PAGE_SIZE, *PPAGE_SIZE;
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_FORMAT FX_SAVE_FORMAT, *PFX_SAVE_FORMAT;
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 _KEXCEPTION_FRAME KEXCEPTION_FRAME, *PKEXCEPTION_FRAME;
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 _KTRAP_FRAME KTRAP_FRAME, *PKTRAP_FRAME;
typedef struct _KTSS KTSS, *PKTSS;
typedef struct _MMPAGEMAP_INFO MMPAGEMAP_INFO, *PMMPAGEMAP_INFO;
typedef struct _MMPFN MMPFN, *PMMPFN;
typedef struct _MMPTE_HARDWARE MMPTE_HARDWARE, *PMMPTE_HARDWARE;
typedef struct _MMPTE_LIST MMPTE_LIST, *PMMPTE_LIST;
typedef struct _MMPTE_PROTOTYPE MMPTE_PROTOTYPE, *PMMPTE_PROTOTYPE;
typedef struct _MMPTE_SOFTWARE MMPTE_SOFTWARE, *PMMPTE_SOFTWARE;
typedef struct _MMPTE_SUBSECTION MMPTE_SUBSECTION, *PMMPTE_SUBSECTION;
typedef struct _MMPTE_TRANSITION MMPTE_TRANSITION, *PMMPTE_TRANSITION;
typedef struct _MMPML2_PTE_HARDWARE MMPML2_PTE_HARDWARE, *PMMPML2_PTE_HARDWARE;
typedef struct _MMPML2_PTE_LIST MMPML2_PTE_LIST, *PMMPML2_PTE_LIST;
typedef struct _MMPML2_PTE_PROTOTYPE MMPML2_PTE_PROTOTYPE, *PMMPML2_PTE_PROTOTYPE;
typedef struct _MMPML2_PTE_SOFTWARE MMPML2_PTE_SOFTWARE, *PMMPML2_PTE_SOFTWARE;
typedef struct _MMPML2_PTE_SUBSECTION MMPML2_PTE_SUBSECTION, *PMMPML2_PTE_SUBSECTION;
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;
/* 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_LVT_REGISTER APIC_LVT_REGISTER, *PAPIC_LVT_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 MMPPE, *PMMPPE;
typedef union _MMPTE MMPTE, *PMMPTE;
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_ICW3 PIC_I8259_ICW3, *PPIC_I8259_ICW3;
typedef union _PIC_I8259_ICW4 PIC_I8259_ICW4, *PPIC_I8259_ICW4;
#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

@ -10,8 +10,18 @@
#define __XTDK_MMTYPES_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 */
typedef struct _MMCOLOR_TABLES
{

View File

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

View File

@ -20,7 +20,7 @@
/* XTOS platform debugging macros */
#ifdef DBG
#define DEBUG 1
#define DebugPrint(Format, ...) if(KeDbgPrint) KeDbgPrint(Format, __VA_ARGS__);
#define DebugPrint(Format, ...) if(KdPrint) KdPrint(Format, __VA_ARGS__);
#else
#define DEBUG 0
#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 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))
/* Macros for concatenating strings */

View File

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

View File

@ -30,6 +30,7 @@
#include <extypes.h>
#include <hltypes.h>
#include <iotypes.h>
#include <kdtypes.h>
#include <ketypes.h>
#include <ldrtypes.h>
#include <mmtypes.h>

View File

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

View File

@ -50,6 +50,7 @@ typedef enum _KTIMER_TYPE KTIMER_TYPE, *PKTIMER_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 _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 _WAIT_TYPE WAIT_TYPE, *PWAIT_TYPE;
@ -69,6 +70,7 @@ typedef struct _ANSI_STRING ANSI_STRING, *PANSI_STRING;
typedef struct _ANSI_STRING32 ANSI_STRING32, *PANSI_STRING32;
typedef struct _ANSI_STRING64 ANSI_STRING64, *PANSI_STRING64;
typedef struct _CPPORT CPPORT, *PCPPORT;
typedef const struct _CMMPAGEMAP_ROUTINES CMMPAGEMAP_ROUTINES, *PCMMPAGEMAP_ROUTINES;
typedef struct _CSTRING CSTRING, *PCSTRING;
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;
@ -233,9 +235,12 @@ typedef struct _FIRMWARE_INFORMATION_BLOCK FIRMWARE_INFORMATION_BLOCK, *PFIRMWAR
typedef struct _FLOAT128 FLOAT128, *PFLOAT128;
typedef struct _GENERIC_ADDRESS GENERIC_ADDRESS, *PGENERIC_ADDRESS;
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_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_DATA KDPC_DATA, *PKDPC_DATA;
typedef struct _KERNEL_INITIALIZATION_BLOCK KERNEL_INITIALIZATION_BLOCK, *PKERNEL_INITIALIZATION_BLOCK;
@ -300,6 +305,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 _PROCESSOR_IDENTITY PROCESSOR_IDENTITY, *PPROCESSOR_IDENTITY;
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 _SMBIOS_TABLE_HEADER SMBIOS_TABLE_HEADER, *PSMBIOS_TABLE_HEADER;
typedef struct _SMBIOS3_TABLE_HEADER SMBIOS3_TABLE_HEADER, *PSMBIOS3_TABLE_HEADER;

View File

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

View File

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

View File

@ -4,6 +4,7 @@
* FILE: xtldr/arch/amd64/memory.c
* DESCRIPTION: XT Boot Loader AMD64 specific memory management
* DEVELOPERS: Rafal Kupiec <belliash@codingworkshop.eu.org>
* Aiken Harris <harraiken91@gmail.com>
*/
#include <xtldr.h>
@ -34,7 +35,7 @@ BlBuildPageMap(IN PXTBL_PAGE_MAPPING PageMap,
EFI_STATUS Status;
/* Allocate pages for the Page Map */
Status = BlAllocateMemoryPages(1, &Address);
Status = BlAllocateMemoryPages(AllocateAnyPages, 1, &Address);
if(Status != STATUS_EFI_SUCCESS)
{
/* Memory allocation failure */
@ -53,6 +54,15 @@ BlBuildPageMap(IN PXTBL_PAGE_MAPPING PageMap,
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 */
ModulesList = BlGetModulesList();
ModulesListEntry = ModulesList->Flink;
@ -149,12 +159,13 @@ BlBuildPageMap(IN PXTBL_PAGE_MAPPING PageMap,
XTCDECL
EFI_STATUS
BlMapPage(IN PXTBL_PAGE_MAPPING PageMap,
IN UINT_PTR VirtualAddress,
IN UINT_PTR PhysicalAddress,
IN UINT NumberOfPages)
IN ULONG_PTR VirtualAddress,
IN ULONG_PTR PhysicalAddress,
IN ULONG NumberOfPages)
{
PVOID Pml1, Pml2, Pml3, Pml4, Pml5;
SIZE_T Pml1Entry, Pml2Entry, Pml3Entry, Pml4Entry, Pml5Entry;
PHARDWARE_PTE Pml1, Pml2, Pml3, Pml4, Pml5;
PHARDWARE_PTE PmlTable;
SIZE_T PageFrameNumber;
EFI_STATUS Status;
@ -165,7 +176,7 @@ BlMapPage(IN PXTBL_PAGE_MAPPING PageMap,
while(NumberOfPages > 0)
{
/* 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;
Pml3Entry = (VirtualAddress & ((ULONGLONG)0x1FF << MM_PPI_SHIFT)) >> MM_PPI_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)
{
/* Five level Page Map */
Pml5 = ((PHARDWARE_PTE)(PageMap->PtePointer));
Pml5 = PageMap->PtePointer;
/* Get PML4 */
Status = BlpGetNextPageTable(PageMap, Pml5, Pml5Entry, &Pml4);
@ -188,7 +199,7 @@ BlMapPage(IN PXTBL_PAGE_MAPPING PageMap,
else
{
/* Four level Page Map */
Pml4 = ((PHARDWARE_PTE)(PageMap->PtePointer));
Pml4 = PageMap->PtePointer;
}
/* Get PML3 */
@ -216,9 +227,11 @@ BlMapPage(IN PXTBL_PAGE_MAPPING PageMap,
}
/* Set paging entry settings */
Pml1[Pml1Entry].PageFrameNumber = PageFrameNumber;
Pml1[Pml1Entry].Valid = 1;
Pml1[Pml1Entry].Writable = 1;
PmlTable = (PHARDWARE_PTE)Pml1;
RtlZeroMemory(&PmlTable[Pml1Entry], sizeof(HARDWARE_PTE));
PmlTable[Pml1Entry].PageFrameNumber = PageFrameNumber;
PmlTable[Pml1Entry].Valid = 1;
PmlTable[Pml1Entry].Writable = 1;
/* Take next virtual address and PFN */
VirtualAddress += EFI_PAGE_SIZE;
@ -232,6 +245,81 @@ BlMapPage(IN PXTBL_PAGE_MAPPING PageMap,
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.
*
@ -250,26 +338,30 @@ EFI_STATUS
BlpSelfMapPml(IN PXTBL_PAGE_MAPPING PageMap,
IN ULONG_PTR SelfMapAddress)
{
PHARDWARE_PTE PmlBase;
ULONGLONG PmlIndex;
/* Initialize PML base pointer */
PmlBase = (PHARDWARE_PTE)PageMap->PtePointer;
/* Check page map level */
if(PageMap->PageMapLevel == 5)
{
/* Self-mapping for PML5 is not supported */
BlDebugPrint(L"PML5 self-mapping not supported yet!\n");
return STATUS_EFI_UNSUPPORTED;
/* Calculate PML index based on provided self map address for PML5 */
PmlIndex = (SelfMapAddress >> MM_P5I_SHIFT) & 0x1FF;
}
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;
/* 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 STATUS_EFI_SUCCESS;
}

View File

@ -4,6 +4,7 @@
* FILE: xtldr/arch/i686/memory.c
* DESCRIPTION: XT Boot Loader i686 specific memory management
* DEVELOPERS: Rafal Kupiec <belliash@codingworkshop.eu.org>
* Aiken Harris <harraiken91@gmail.com>
*/
#include <xtldr.h>
@ -31,38 +32,54 @@ BlBuildPageMap(IN PXTBL_PAGE_MAPPING PageMap,
EFI_STATUS Status;
ULONG Index;
/* Allocate pages for the Page Map */
Status = BlAllocateMemoryPages(1, &Address);
if(Status != STATUS_EFI_SUCCESS)
/* Check the page map level to determine which paging structure to create */
if(PageMap->PageMapLevel == 3)
{
/* Memory allocation failure */
return Status;
/* Allocate a page for the 3-level page map structure (PAE enabled) */
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;
}
}
/* 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)
else
{
/* Memory allocation failure */
return Status;
}
/* Allocate a page for the 2-level page map structure (PAE disabled) */
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 */
RtlZeroMemory((PVOID)DirectoryAddress, EFI_PAGE_SIZE * 4);
/* 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;
/* Assign the allocated page to the page map and zero it out */
PageMap->PtePointer = (PVOID)(UINT_PTR)Address;
RtlZeroMemory(PageMap->PtePointer, EFI_PAGE_SIZE);
}
/* Add page mapping itself to memory mapping */
@ -73,6 +90,15 @@ BlBuildPageMap(IN PXTBL_PAGE_MAPPING PageMap,
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 */
ModulesList = BlGetModulesList();
ModulesListEntry = ModulesList->Flink;
@ -169,58 +195,81 @@ BlBuildPageMap(IN PXTBL_PAGE_MAPPING PageMap,
XTCDECL
EFI_STATUS
BlMapPage(IN PXTBL_PAGE_MAPPING PageMap,
IN UINT_PTR VirtualAddress,
IN UINT_PTR PhysicalAddress,
IN UINT NumberOfPages)
IN ULONG_PTR VirtualAddress,
IN ULONG_PTR PhysicalAddress,
IN ULONG NumberOfPages)
{
SIZE_T Pml1Entry, Pml2Entry, Pml3Entry;
PHARDWARE_PTE Pml1, Pml2, Pml3;
SIZE_T PageFrameNumber;
PVOID Pml1, Pml2, Pml3;
SIZE_T Pml1Entry, Pml2Entry, Pml3Entry;
PHARDWARE_LEGACY_PTE LegacyPmlTable;
PHARDWARE_MODERN_PTE PmlTable;
EFI_STATUS Status;
/* Set the Page Frame Number (PFN) */
PageFrameNumber = PhysicalAddress >> EFI_PAGE_SHIFT;
/* Do the recursive mapping */
/* Map all requested pages */
while(NumberOfPages > 0)
{
/* Calculate the indices in the various Page Tables from the virtual address */
Pml3Entry = (VirtualAddress & ((ULONGLONG)0x1FF << 30)) >> 30;
Pml2Entry = (VirtualAddress & ((ULONGLONG)0x1FF << 21)) >> 21;
Pml1Entry = (VirtualAddress & ((ULONGLONG)0x1FF << 12)) >> 12;
/* Check page map level */
/* Check the paging mode to use the correct page table structure */
if(PageMap->PageMapLevel == 3)
{
/* Three level Page Map */
Pml3 = ((PHARDWARE_PTE)(PageMap->PtePointer));
/* Calculate the indices for PAE page tables */
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);
if(Status != STATUS_EFI_SUCCESS)
{
/* Memory mapping failure */
/* Failed to get the Page Table, abort mapping */
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
{
/* Two level Page Map */
Pml2 = ((PHARDWARE_PTE)(PageMap->PtePointer));
}
/* Calculate the indices for non-PAE page tables */
Pml2Entry = (VirtualAddress >> 22) & 0x3FF;
Pml1Entry = (VirtualAddress >> 12) & 0x3FF;
/* Get PML1 */
Status = BlpGetNextPageTable(PageMap, Pml2, Pml2Entry, &Pml1);
if(Status != STATUS_EFI_SUCCESS)
{
/* Memory mapping failure */
return Status;
}
/* Get Page Directory (PML2) */
Pml2 = PageMap->PtePointer;
/* Set paging entry settings */
Pml1[Pml1Entry].PageFrameNumber = PageFrameNumber;
Pml1[Pml1Entry].Valid = 1;
Pml1[Pml1Entry].Writable = 1;
/* 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 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 */
VirtualAddress += EFI_PAGE_SIZE;
@ -234,6 +283,119 @@ BlMapPage(IN PXTBL_PAGE_MAPPING PageMap,
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.
*
@ -252,8 +414,9 @@ EFI_STATUS
BlpSelfMapPml(IN PXTBL_PAGE_MAPPING PageMap,
IN ULONG_PTR SelfMapAddress)
{
PHARDWARE_LEGACY_PTE LegacyPml;
PHARDWARE_MODERN_PTE Pml;
ULONGLONG PmlIndex;
PHARDWARE_PTE Pml;
ULONG Index;
/* Check page map level */
@ -263,25 +426,29 @@ BlpSelfMapPml(IN PXTBL_PAGE_MAPPING PageMap,
PmlIndex = (SelfMapAddress >> MM_PDI_SHIFT) & 0x1FF;
/* 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) */
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].Writable = 1;
}
}
else
{
LegacyPml = (PHARDWARE_LEGACY_PTE)PageMap->PtePointer;
/* Calculate PML index based on provided self map address */
PmlIndex = (SelfMapAddress >> MM_PDI_LEGACY_SHIFT);
/* Add self-mapping for PML2 (PAE disabled) */
((PHARDWARE_LEGACY_PTE)PageMap->PtePointer)[PmlIndex].PageFrameNumber = (UINT_PTR)PageMap->PtePointer / EFI_PAGE_SIZE;
((PHARDWARE_LEGACY_PTE)PageMap->PtePointer)[PmlIndex].Valid = 1;
((PHARDWARE_LEGACY_PTE)PageMap->PtePointer)[PmlIndex].Writable = 1;
RtlZeroMemory(&LegacyPml[PmlIndex], sizeof(HARDWARE_LEGACY_PTE));
LegacyPml[PmlIndex].PageFrameNumber = (UINT_PTR)PageMap->PtePointer / EFI_PAGE_SIZE;
LegacyPml[PmlIndex].Valid = 1;
LegacyPml[PmlIndex].Writable = 1;
}
/* 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
* DESCRIPTION: XT Boot Loader Configuration
* DEVELOPERS: Rafal Kupiec <belliash@codingworkshop.eu.org>
* Aiken Harris <harraiken91@gmail.com>
*/
#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.
*
@ -26,7 +99,7 @@ BlGetConfigBooleanValue(IN CONST PWCHAR ConfigName)
PWCHAR Value;
/* Get config value */
Value = BlGetConfigValue(ConfigName);
BlGetConfigValue(ConfigName, &Value);
/* Check if option is enabled */
if(RtlCompareWideStringInsensitive(Value, L"ENABLED", 0) == 0 ||
@ -53,8 +126,9 @@ BlGetConfigBooleanValue(IN CONST PWCHAR ConfigName)
* @since XT 1.0
*/
XTCDECL
PWCHAR
BlGetConfigValue(IN CONST PWCHAR ConfigName)
EFI_STATUS
BlGetConfigValue(IN CONST PWCHAR ConfigName,
OUT PWCHAR *ConfigValue)
{
PXTBL_CONFIG_ENTRY ConfigEntry;
PLIST_ENTRY ConfigListEntry;
@ -62,6 +136,9 @@ BlGetConfigValue(IN CONST PWCHAR ConfigName)
EFI_STATUS Status;
PWCHAR Value;
/* Assume the option will not be found */
*ConfigValue = NULL;
/* Get config entry name length */
KeyLength = RtlWideStringLength(ConfigName, 0);
@ -84,13 +161,14 @@ BlGetConfigValue(IN CONST PWCHAR ConfigName)
{
/* Memory allocation failure, return NULL */
BlDebugPrint(L"ERROR: Memory allocation failure (Status Code: 0x%zX)\n", Status);
return NULL;
return Status;
}
/* Copy value and return it */
RtlCopyMemory(Value, ConfigEntry->Value, ValueLength * sizeof(WCHAR));
Value[ValueLength] = L'\0';
return Value;
*ConfigValue = Value;
return STATUS_EFI_SUCCESS;
}
/* Move to the next config entry */
@ -98,7 +176,157 @@ BlGetConfigValue(IN CONST PWCHAR ConfigName)
}
/* 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
* Specifies the new configuration value.
*
* @return This routine returns status code.
* @return This routine returns a status code.
*
* @since XT 1.0
*/
@ -174,7 +402,7 @@ BlSetConfigValue(IN CONST PWCHAR ConfigName,
/**
* Loads and parses XTLDR configuration file.
*
* @return This routine returns status code.
* @return This routine returns a status code.
*
* @since XT 1.0
*/
@ -453,7 +681,7 @@ BlpParseConfigFile(IN CONST PCHAR RawConfig,
/* Initialize new section and convert its name to wide string */
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 */
Section->SectionName[SectionLength] = L'\0';
@ -542,8 +770,8 @@ BlpParseConfigFile(IN CONST PCHAR RawConfig,
}
/* Convert key and value to wide strings */
RtlStringToWideString(Option->Name, &Key, RtlStringLength(Key, 0) + 1);
RtlStringToWideString(Option->Value, &Value, RtlStringLength(Value, 0) + 1);
RtlStringToWideString(Option->Name, (PCSTR*)&Key, RtlStringLength(Key, 0) + 1);
RtlStringToWideString(Option->Value, (PCSTR*)&Value, RtlStringLength(Value, 0) + 1);
/* Ensure strings are NULL-terminated and add new option to the list */
Option->Name[KeyLength] = L'\0';
@ -568,7 +796,7 @@ BlpParseConfigFile(IN CONST PCHAR RawConfig,
* @param ConfigData
* 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
*/
@ -629,6 +857,7 @@ VOID
BlpUpdateConfiguration(IN PLIST_ENTRY NewConfig)
{
PXTBL_CONFIG_ENTRY ConfigEntry;
PWCHAR ConfigValue;
PLIST_ENTRY ConfigListEntry, NextListEntry;
/* Iterate through new config entries */
@ -642,7 +871,8 @@ BlpUpdateConfiguration(IN PLIST_ENTRY NewConfig)
NextListEntry = ConfigListEntry->Flink;
/* 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 */
RtlRemoveEntryList(&ConfigEntry->Flink);

View File

@ -95,7 +95,7 @@ BlEnableConsoleCursor()
*/
XTCDECL
VOID
BlConsolePrint(IN PUSHORT Format,
BlConsolePrint(IN PCWSTR Format,
IN ...)
{
RTL_PRINT_CONTEXT ConsolePrintContext, SerialPrintContext;
@ -138,9 +138,9 @@ BlConsolePrint(IN PUSHORT Format,
*/
XTCDECL
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
XTSTATUS
BlpConsolePutChar(IN USHORT Character)
BlpConsolePutChar(IN WCHAR Character)
{
USHORT Buffer[2];
WCHAR Buffer[2];
/* Check if character is a newline ('\n') */
if(Character == L'\n')

View File

@ -24,7 +24,7 @@
*/
XTCDECL
VOID
BlDebugPrint(IN PUSHORT Format,
BlDebugPrint(IN PCWSTR Format,
IN ...)
{
RTL_PRINT_CONTEXT ConsolePrintContext, SerialPrintContext;
@ -71,17 +71,14 @@ BlDebugPrint(IN PUSHORT Format,
*/
XTCDECL
XTSTATUS
BlpDebugPutChar(IN USHORT Character)
BlpDebugPutChar(IN WCHAR Character)
{
USHORT Buffer[2];
WCHAR Buffer[2];
/* Write character to the serial console */
Buffer[0] = Character;
Buffer[1] = 0;
HlComPortPutByte(&BlpStatus.SerialPort, Buffer[0]);
/* Return success */
return STATUS_EFI_SUCCESS;
return HlComPortPutByte(&BlpStatus.SerialPort, Buffer[0]);
}
/**
@ -105,7 +102,7 @@ BlpInitializeDebugConsole()
BaudRate = 0;
/* 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 */
if(DebugConfiguration && BlpStatus.DebugPort == 0)

View File

@ -21,6 +21,13 @@ LIST_ENTRY BlpConfig;
/* XT Boot Loader loaded configuration */
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 */
XTBL_LOADER_PROTOCOL BlpLdrProtocol;
@ -41,3 +48,4 @@ EFI_HANDLE EfiImageHandle;
/* EFI System Table */
PEFI_SYSTEM_TABLE EfiSystemTable;

View File

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

View File

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

View File

@ -12,7 +12,7 @@
/**
* This routine allocates one or more 4KB pages.
*
* @param Pages
* @param NumberOfPages
* The number of contiguous 4KB pages to allocate.
*
* @param Memory
@ -24,10 +24,11 @@
*/
XTCDECL
EFI_STATUS
BlAllocateMemoryPages(IN ULONGLONG Pages,
BlAllocateMemoryPages(IN EFI_ALLOCATE_TYPE AllocationType,
IN ULONGLONG NumberOfPages,
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.
*
* @param Pages
* @param NumberOfPages
* The number of contiguous 4 KB pages to free.
*
* @param Memory
@ -67,10 +68,10 @@ BlAllocateMemoryPool(IN UINT_PTR Size,
*/
XTCDECL
EFI_STATUS
BlFreeMemoryPages(IN ULONGLONG Pages,
BlFreeMemoryPages(IN ULONGLONG NumberOfPages,
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 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
AcGetApicBase(OUT PVOID *ApicBase)
{
PCPUID_REGISTERS CpuRegisters = NULL;
CPUID_REGISTERS CpuRegisters;
/* Get CPU features list */
CpuRegisters->Leaf = CPUID_GET_CPU_FEATURES;
CpuRegisters->SubLeaf = 0;
CpuRegisters->Eax = 0;
CpuRegisters->Ebx = 0;
CpuRegisters->Ecx = 0;
CpuRegisters->Edx = 0;
ArCpuId(CpuRegisters);
/* Prepare CPUID registers to query for APIC support */
RtlZeroMemory(&CpuRegisters, sizeof(CPUID_REGISTERS));
CpuRegisters.Leaf = CPUID_GET_STANDARD1_FEATURES;
/* Query CPUID */
ArCpuId(&CpuRegisters);
/* 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 */
return STATUS_EFI_UNSUPPORTED;

View File

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

View File

@ -47,7 +47,7 @@ ChBootSystem(IN PXTBL_BOOT_PARAMETERS Parameters)
}
/* Open EFI volume */
Status = XtLdrProtocol->Disk.OpenVolume(NULL, &DiskHandle, &FsHandle);
Status = XtLdrProtocol->Disk.OpenVolume(Parameters->DevicePath, &DiskHandle, &FsHandle);
if(Status != STATUS_EFI_SUCCESS)
{
/* 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);
/* Allocate pages */
Status = XtLdrProtocol->Memory.AllocatePages(Pages, &Address);
Status = XtLdrProtocol->Memory.AllocatePages(AllocateAnyPages, Pages, &Address);
if(Status != STATUS_EFI_SUCCESS)
{
/* Pages allocation failure */
@ -472,7 +472,7 @@ PeLoadImage(IN PEFI_FILE_HANDLE FileHandle,
ImageData->ImagePages = EFI_SIZE_TO_PAGES(ImageData->ImageSize);
/* Allocate image pages */
Status = XtLdrProtocol->Memory.AllocatePages(ImageData->ImagePages, &Address);
Status = XtLdrProtocol->Memory.AllocatePages(AllocateAnyPages, ImageData->ImagePages, &Address);
if(Status != STATUS_EFI_SUCCESS)
{
/* Pages reallocation failure */

View File

@ -4,11 +4,58 @@
* FILE: xtldr/amd64/memory.c
* DESCRIPTION: EFI memory management for AMD64 target
* DEVELOPERS: Rafal Kupiec <belliash@codingworkshop.eu.org>
* Aiken Harris <harraiken91@gmail.com>
*/
#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.
*
@ -23,25 +70,54 @@ XTCDECL
EFI_STATUS
XtpMapHardwareMemoryPool(IN PXTBL_PAGE_MAPPING PageMap)
{
PHARDWARE_PTE PdeBase, PpeBase, PxeBase;
PHARDWARE_PTE P5eBase, PdeBase, PpeBase, PxeBase;
EFI_PHYSICAL_ADDRESS Address;
XTSTATUS Status;
EFI_STATUS Status;
/* Check page map level */
if(PageMap->PageMapLevel > 4)
if(PageMap->PageMapLevel == 5)
{
/* PML5 (LA57) is not supported yet */
return STATUS_EFI_UNSUPPORTED;
}
/* Get P5E (PML5) base address */
P5eBase = (PHARDWARE_PTE)PageMap->PtePointer;
/* Get PXE (PML4) base address */
PxeBase = ((PHARDWARE_PTE)(PageMap->PtePointer));
/* Check if P5E entry already exists */
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 */
if(!PxeBase[(MM_HARDWARE_VA_START >> MM_PXI_SHIFT) & 0x1FF].Valid)
{
/* No valid PXE, allocate memory */
Status = XtLdrProtocol->Memory.AllocatePages(1, &Address);
Status = XtLdrProtocol->Memory.AllocatePages(AllocateAnyPages, 1, &Address);
if(Status != STATUS_EFI_SUCCESS)
{
/* 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)
{
/* No valid PPE, allocate memory */
Status = XtLdrProtocol->Memory.AllocatePages(1, &Address);
Status = XtLdrProtocol->Memory.AllocatePages(AllocateAnyPages, 1, &Address);
if(Status != STATUS_EFI_SUCCESS)
{
/* 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)
{
/* No valid PDE, allocate memory */
Status = XtLdrProtocol->Memory.AllocatePages(1, &Address);
Status = XtLdrProtocol->Memory.AllocatePages(AllocateAnyPages, 1, &Address);
if(Status != STATUS_EFI_SUCCESS)
{
/* Memory allocation failure, return error */
@ -136,9 +212,12 @@ EFI_STATUS
XtEnablePaging(IN PXTBL_PAGE_MAPPING PageMap)
{
EFI_STATUS Status;
EFI_PHYSICAL_ADDRESS TrampolineAddress;
PXT_TRAMPOLINE_ENTRY TrampolineEntry;
ULONG_PTR TrampolineSize;
/* 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)
{
/* Failed to build page map */
@ -155,6 +234,29 @@ XtEnablePaging(IN PXTBL_PAGE_MAPPING PageMap)
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 */
XtLdrProtocol->Debug.Print(L"Exiting EFI boot services\n");
Status = XtLdrProtocol->Util.ExitBootServices();
@ -165,8 +267,24 @@ XtEnablePaging(IN PXTBL_PAGE_MAPPING PageMap)
return STATUS_EFI_ABORTED;
}
/* Write PML4 to CR3 */
ArWriteControlRegister(3, (UINT_PTR)PageMap->PtePointer);
/* Check the configured page map level to set the LA57 state accordingly */
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 STATUS_EFI_SUCCESS;

View File

@ -9,6 +9,41 @@
#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.
*
@ -24,11 +59,12 @@ EFI_STATUS
XtpMapHardwareMemoryPool(IN PXTBL_PAGE_MAPPING PageMap)
{
EFI_PHYSICAL_ADDRESS Address;
PHARDWARE_PTE PdeBase;
XTSTATUS Status;
PHARDWARE_LEGACY_PTE LegacyPdeBase;
PHARDWARE_MODERN_PTE PdeBase;
EFI_STATUS Status;
/* Allocate memory */
Status = XtLdrProtocol->Memory.AllocatePages(1, &Address);
Status = XtLdrProtocol->Memory.AllocatePages(AllocateAnyPages, 1, &Address);
if(Status != STATUS_EFI_SUCCESS)
{
/* Memory allocation failure, return error */
@ -38,23 +74,35 @@ XtpMapHardwareMemoryPool(IN PXTBL_PAGE_MAPPING PageMap)
/* Zero fill allocated memory */
RtlZeroMemory((PVOID)Address, EFI_PAGE_SIZE);
/* Check page map level */
/* Check if PAE is enabled (3-level paging) */
if(PageMap->PageMapLevel == 3)
{
/* 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 */
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].Valid = 1;
PdeBase[(MM_HARDWARE_VA_START >> MM_PDI_SHIFT) & 0x1FF].Writable = 1;
}
else
{
/* Make PDE valid (PAE disabled) */
((PHARDWARE_LEGACY_PTE)PageMap->PtePointer)[MM_HARDWARE_VA_START >> MM_PDI_LEGACY_SHIFT].Valid = 1;
((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;
/* Get PDE base address (PAE disabled) */
LegacyPdeBase = (PHARDWARE_LEGACY_PTE)PageMap->PtePointer;
/* 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 */
@ -75,30 +123,10 @@ XTCDECL
EFI_STATUS
XtEnablePaging(IN PXTBL_PAGE_MAPPING PageMap)
{
PCPUID_REGISTERS CpuRegisters = NULL;
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 */
Status = XtLdrProtocol->Memory.BuildPageMap(PageMap, 0xC0000000);
Status = XtLdrProtocol->Memory.BuildPageMap(PageMap, MM_PTE_BASE);
if(Status != STATUS_EFI_SUCCESS)
{
/* Failed to build page map */
@ -111,7 +139,7 @@ XtEnablePaging(IN PXTBL_PAGE_MAPPING PageMap)
if(Status != STATUS_EFI_SUCCESS)
{
/* 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;
}
@ -125,8 +153,22 @@ XtEnablePaging(IN PXTBL_PAGE_MAPPING PageMap)
return STATUS_EFI_ABORTED;
}
/* Enable Physical Address Extension (PAE) */
ArWriteControlRegister(4, ArReadControlRegister(4) | CR4_PAE);
/* Disable paging */
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 */
ArWriteControlRegister(3, (UINT_PTR)PageMap->PtePointer);

View File

@ -29,9 +29,15 @@ typedef struct _XT_FRAMEBUFFER_PROTOCOL
/* EFI XT Loader Protocol */
EXTERN PXTBL_LOADER_PROTOCOL XtLdrProtocol;
/* XTOS trampoline end address to calculate trampoline size */
EXTERN PVOID ArEnableExtendedPhysicalAddressingEnd[];
/* XTOS kernel entry point */
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 */
XTCDECL
EFI_STATUS
@ -49,6 +55,10 @@ XTCDECL
LOADER_MEMORY_TYPE
XtConvertEfiMemoryType(IN EFI_MEMORY_TYPE EfiMemoryType);
XTCDECL
ULONG
XtpDeterminePagingLevel(IN CONST PWCHAR Parameters);
XTCDECL
EFI_STATUS
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));
Status = XtLdrProtocol->Memory.AllocatePages(Pages, &Address);
Status = XtLdrProtocol->Memory.AllocatePages(AllocateAnyPages, Pages, &Address);
if(Status != STATUS_EFI_SUCCESS)
{
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));
Status = XtLdrProtocol->Memory.AllocatePages(Pages, &Address);
Status = XtLdrProtocol->Memory.AllocatePages(AllocateAnyPages, Pages, &Address);
if(Status != STATUS_EFI_SUCCESS)
{
return Status;
@ -323,7 +323,7 @@ XtBootSystem(IN PXTBL_BOOT_PARAMETERS Parameters)
Parameters->KernelFile, Parameters->Parameters);
/* Open EFI volume */
Status = XtLdrProtocol->Disk.OpenVolume(NULL, &DiskHandle, &FsHandle);
Status = XtLdrProtocol->Disk.OpenVolume(Parameters->DevicePath, &DiskHandle, &FsHandle);
if(Status != STATUS_EFI_SUCCESS)
{
/* Failed to open a volume */
@ -410,7 +410,7 @@ XtpBootSequence(IN PEFI_FILE_HANDLE BootDir,
VirtualAddress = (PVOID)(KSEG0_BASE + KSEG0_KERNEL_BASE);
/* 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);
if(Status != STATUS_EFI_SUCCESS)
@ -547,12 +547,16 @@ XtpInitializeLoaderBlock(IN PXTBL_PAGE_MAPPING PageMap,
// PVOID RuntimeServices;
EFI_STATUS Status;
UINT BlockPages;
UINT ParametersSize;
/* Calculate size of parameters */
ParametersSize = (RtlWideStringLength(Parameters->Parameters, 0) + 1) * sizeof(WCHAR);
/* 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 */
Status = XtLdrProtocol->Memory.AllocatePages(BlockPages, &Address);
Status = XtLdrProtocol->Memory.AllocatePages(AllocateAnyPages, BlockPages, &Address);
if(Status != STATUS_EFI_SUCCESS)
{
/* Memory allocation failure */
@ -561,7 +565,7 @@ XtpInitializeLoaderBlock(IN PXTBL_PAGE_MAPPING PageMap,
/* Initialize and zero-fill kernel initialization block */
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 */
LoaderBlock->BlockSize = sizeof(KERNEL_INITIALIZATION_BLOCK);
@ -571,9 +575,6 @@ XtpInitializeLoaderBlock(IN PXTBL_PAGE_MAPPING PageMap,
/* Set LoaderInformation block properties */
LoaderBlock->LoaderInformation.DbgPrint = XtLdrProtocol->Debug.Print;
/* Store page map level */
LoaderBlock->LoaderInformation.PageMapLevel = 3;
/* Attempt to find virtual address of the EFI Runtime Services */
// Status = XtLdrProtocol->GetVirtualAddress(MemoryMappings, &EfiSystemTable->RuntimeServices->Hdr, &RuntimeServices);
// if(Status == STATUS_EFI_SUCCESS)
@ -590,8 +591,10 @@ XtpInitializeLoaderBlock(IN PXTBL_PAGE_MAPPING PageMap,
// }
/* Copy parameters to kernel initialization block */
RtlCopyMemory(LoaderBlock->KernelParameters, Parameters->Parameters,
(RtlWideStringLength(Parameters->Parameters, 0) + 1) * sizeof(WCHAR));
LoaderBlock->KernelParameters = (PWCHAR)((UINT_PTR)*VirtualAddress + sizeof(KERNEL_INITIALIZATION_BLOCK));
RtlCopyMemory((PVOID)((UINT_PTR)LoaderBlock + sizeof(KERNEL_INITIALIZATION_BLOCK)),
Parameters->Parameters,
ParametersSize);
/* Map kernel initialization block */
XtLdrProtocol->Memory.MapVirtualMemory(PageMap, *VirtualAddress, (PVOID)LoaderBlock,

View File

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

View File

@ -4,6 +4,7 @@
* FILE: xtldr/textui.c
* DESCRIPTION: Text console User Interface (TUI) support for XT Boot Loader
* DEVELOPERS: Rafal Kupiec <belliash@codingworkshop.eu.org>
* Aiken Harris <harraiken91@gmail.com>
*/
#include <xtldr.h>
@ -22,7 +23,9 @@ BlDisplayBootMenu()
{
XTBL_DIALOG_HANDLE Handle;
PXTBL_BOOTMENU_ITEM MenuEntries = NULL;
ULONG Index, NumberOfEntries, HighligtedEntryId;
ULONG Index;
ULONG HighligtedEntryId, OldHighligtedEntryId, NumberOfEntries, TopVisibleEntry, VisibleEntries;
BOOLEAN RedrawBootMenu, RedrawEntries;
UINT_PTR EventIndex;
EFI_EVENT Events[2];
EFI_INPUT_KEY Key;
@ -31,16 +34,30 @@ BlDisplayBootMenu()
LONG TimeOut;
PWCHAR TimeOutString;
/* Draw boot menu */
BlpDrawBootMenu(&Handle);
/* Initialize boot menu list */
Status = BlInitializeBootMenuList(&MenuEntries, &NumberOfEntries, &HighligtedEntryId);
TopVisibleEntry = 0;
Status = BlInitializeBootMenuList(Handle.Width - 4, &MenuEntries, &NumberOfEntries, &HighligtedEntryId);
if(Status != STATUS_EFI_SUCCESS)
{
/* Failed to initialize boot menu list, exit into XTLDR shell */
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 */
TimeOutString = BlGetConfigValue(L"TIMEOUT");
BlGetConfigValue(L"TIMEOUT", &TimeOutString);
TimeOut = -1;
/* 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 */
while(TRUE)
{
/* Draw boot menu */
BlpDrawBootMenu(&Handle);
/* Redraw boot menu frame if requested */
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 */
if(NumberOfEntries > 0) {
/* Check if all menu entries will fit into the menu box */
if(NumberOfEntries > Handle.Height - 2)
if(NumberOfEntries > 0)
{
/* 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) */
NumberOfEntries = Handle.Height - 2;
}
/* Iterate through all menu entries */
for(Index = 0; Index < VisibleEntries; Index++)
{
/* Draw menu entry */
BlpDrawBootMenuEntry(&Handle, MenuEntries[TopVisibleEntry + Index].EntryName,
Index, (TopVisibleEntry + Index) == HighligtedEntryId);
}
/* Iterate through all menu entries */
for(Index = 0; Index < NumberOfEntries; Index++)
{
/* Draw menu entry */
BlpDrawBootMenuEntry(&Handle, MenuEntries[Index].EntryName, Index, Index == HighligtedEntryId);
/* Clear redraw entries flag */
RedrawEntries = FALSE;
}
}
else
@ -109,6 +143,9 @@ BlDisplayBootMenu()
/* Flush keyboard buffer out of any keystrokes */
EfiSystemTable->ConIn->Reset(EfiSystemTable->ConIn, FALSE);
/* Store old highlighted entry */
OldHighligtedEntryId = HighligtedEntryId;
/* Infinite boot menu event loop */
while(TRUE)
{
@ -140,7 +177,7 @@ BlDisplayBootMenu()
BlSetConsoleAttributes(Handle.DialogColor | Handle.TextColor);
BlClearConsoleLine(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 */
Status = BlInvokeBootProtocol(MenuEntries[HighligtedEntryId].ShortName,
@ -149,8 +186,9 @@ BlDisplayBootMenu()
{
/* Failed to boot OS */
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.");
RedrawBootMenu = TRUE;
}
/* Break from boot menu event loop to redraw whole boot menu */
@ -162,11 +200,23 @@ BlDisplayBootMenu()
if(HighligtedEntryId > 0)
{
/* Highlight previous entry */
OldHighligtedEntryId = 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,
HighligtedEntryId, TRUE);
HighligtedEntryId - TopVisibleEntry, TRUE);
}
}
else if(Key.ScanCode == 0x02)
@ -175,11 +225,23 @@ BlDisplayBootMenu()
if(HighligtedEntryId < NumberOfEntries - 1)
{
/* Highlight next entry */
OldHighligtedEntryId = 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,
HighligtedEntryId, TRUE);
HighligtedEntryId - TopVisibleEntry, TRUE);
}
}
else if(Key.ScanCode == 0x09)
@ -188,12 +250,10 @@ BlDisplayBootMenu()
if(HighligtedEntryId != 0)
{
/* Highlight first entry */
BlpDrawBootMenuEntry(&Handle, MenuEntries[HighligtedEntryId].EntryName,
HighligtedEntryId, FALSE);
BlpDrawBootMenuEntry(&Handle, MenuEntries[0].EntryName, 0, TRUE);
/* Update highlighted entry ID */
HighligtedEntryId = 0;
TopVisibleEntry = 0;
RedrawEntries = TRUE;
break;
}
}
else if(Key.ScanCode == 0x0A)
@ -202,13 +262,10 @@ BlDisplayBootMenu()
if(HighligtedEntryId != NumberOfEntries - 1)
{
/* 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;
TopVisibleEntry = (NumberOfEntries > VisibleEntries) ? (NumberOfEntries - VisibleEntries) : 0;
RedrawEntries = TRUE;
break;
}
}
else if(Key.ScanCode == 0x0B)
@ -231,6 +288,7 @@ BlDisplayBootMenu()
L"Visit https://exectos.eu.org/ for more information.");
/* Break from boot menu event loop to redraw whole boot menu */
RedrawBootMenu = TRUE;
break;
}
else if(Key.ScanCode == 0x14)
@ -238,6 +296,7 @@ BlDisplayBootMenu()
/* F10 key pressed, reboot into UEFI setup interface */
BlEnterFirmwareSetup();
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;
@ -247,6 +306,7 @@ BlDisplayBootMenu()
/* F11 key pressed, reboot the machine */
BlRebootSystem();
BlDisplayErrorDialog(L"XTLDR", L"Failed to reboot the machine!");
RedrawBootMenu = TRUE;
/* Break from boot menu event loop to redraw whole boot menu */
break;
@ -256,6 +316,7 @@ BlDisplayBootMenu()
/* F12 key pressed, shutdown the machine */
BlShutdownSystem();
BlDisplayErrorDialog(L"XTLDR", L"Failed to shutdown the machine!");
RedrawBootMenu = TRUE;
/* Break from boot menu event loop to redraw whole boot menu */
break;
@ -263,7 +324,8 @@ BlDisplayBootMenu()
else if(Key.UnicodeChar == 0x65)
{
/* '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;
@ -292,7 +354,7 @@ BlDisplayBootMenu()
BlSetConsoleAttributes(Handle.DialogColor | Handle.TextColor);
BlClearConsoleLine(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 */
TimeOut = -1;
@ -304,8 +366,9 @@ BlDisplayBootMenu()
{
/* Failed to boot OS */
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.");
RedrawBootMenu = TRUE;
}
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.
*
@ -440,12 +751,11 @@ XTCDECL
VOID
BlDisplayInputDialog(IN PWCHAR Caption,
IN PWCHAR Message,
IN PWCHAR *InputFieldText)
IN OUT PWCHAR *InputFieldText)
{
SIZE_T InputFieldLength, TextCursorPosition, TextIndex, TextPosition;
XTBL_DIALOG_HANDLE Handle;
PWCHAR InputFieldBuffer;
SIZE_T BufferLength;
EFI_INPUT_KEY Key;
EFI_STATUS Status;
UINT_PTR Index;
@ -470,9 +780,11 @@ BlDisplayInputDialog(IN PWCHAR Caption,
Key.ScanCode = 0;
Key.UnicodeChar = 0;
/* Get initial input text length and allocate a buffer */
BufferLength = RtlWideStringLength(*InputFieldText, 0);
Status = BlAllocateMemoryPool(BufferLength * sizeof(WCHAR), (PVOID *)&InputFieldBuffer);
/* Determine input field length */
InputFieldLength = RtlWideStringLength(*InputFieldText, 0);
/* Allocate a buffer for storing the input field text */
Status = BlAllocateMemoryPool(2048 * sizeof(WCHAR), (PVOID *)&InputFieldBuffer);
if(Status != STATUS_EFI_SUCCESS)
{
/* Memory allocation failure, print error message and return */
@ -482,15 +794,8 @@ BlDisplayInputDialog(IN PWCHAR Caption,
}
/* Copy input text into edit buffer */
RtlCopyMemory(InputFieldBuffer, *InputFieldText, BufferLength * sizeof(WCHAR));
InputFieldBuffer[BufferLength] = L'\0';
/* Determine input field length */
InputFieldLength = BufferLength;
if(InputFieldLength > Handle.Width - 8)
{
InputFieldLength = Handle.Width - 8;
}
RtlCopyMemory(InputFieldBuffer, *InputFieldText, InputFieldLength * sizeof(WCHAR));
InputFieldBuffer[InputFieldLength] = L'\0';
/* Start at first character */
TextPosition = 0;
@ -502,7 +807,6 @@ BlDisplayInputDialog(IN PWCHAR Caption,
/* Wait for key press and read key stroke */
BlWaitForEfiEvent(1, &EfiSystemTable->ConIn->WaitForKey, &Index);
BlReadKeyStroke(&Key);
BlResetConsoleInputBuffer();
/* Check key press scan code */
if(Key.ScanCode == 0x17)
@ -553,12 +857,16 @@ BlDisplayInputDialog(IN PWCHAR Caption,
/* DELETE key pressed, delete character */
if(Handle.Attributes & XTBL_TUI_DIALOG_ACTIVE_INPUT)
{
/* Check if buffer is not empty */
if(InputFieldLength > 0 && TextPosition < InputFieldLength)
{
/* Delete character */
RtlMoveMemory(InputFieldBuffer + TextPosition, InputFieldBuffer + TextPosition + 1,
(InputFieldLength - TextPosition) * sizeof(WCHAR));
/* Decrement length and null terminate string */
InputFieldLength--;
InputFieldBuffer[InputFieldLength] = 0;
InputFieldBuffer[InputFieldLength] = L'\0';
}
}
}
@ -567,13 +875,17 @@ BlDisplayInputDialog(IN PWCHAR Caption,
/* BACKSPACE key pressed, delete character */
if(Handle.Attributes & XTBL_TUI_DIALOG_ACTIVE_INPUT)
{
/* Check if buffer is not empty */
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--;
RtlMoveMemory(InputFieldBuffer + TextPosition, InputFieldBuffer + TextPosition + 1,
(InputFieldLength - TextPosition) * sizeof(WCHAR));
InputFieldLength--;
InputFieldBuffer[InputFieldLength] = 0;
InputFieldBuffer[InputFieldLength] = L'\0';
}
}
}
@ -588,15 +900,23 @@ BlDisplayInputDialog(IN PWCHAR Caption,
/* Other key pressed, add character to the buffer */
if(Handle.Attributes & XTBL_TUI_DIALOG_ACTIVE_INPUT && Key.UnicodeChar != 0)
{
RtlMoveMemory(InputFieldBuffer + TextPosition + 1, InputFieldBuffer + TextPosition,
(InputFieldLength - TextPosition) * sizeof(WCHAR));
InputFieldBuffer[TextPosition] = Key.UnicodeChar;
TextPosition++;
InputFieldLength++;
InputFieldBuffer[InputFieldLength] = 0;
/* Check if buffer is full */
if(InputFieldLength < 2047)
{
/* Insert character at current position */
RtlMoveMemory(InputFieldBuffer + TextPosition + 1, InputFieldBuffer + TextPosition,
(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))
{
TextIndex = TextPosition - (Handle.Width - 9);
@ -612,6 +932,7 @@ BlDisplayInputDialog(IN PWCHAR Caption,
BlpDrawDialogButton(&Handle);
BlpDrawDialogInputField(&Handle, &InputFieldBuffer[TextIndex]);
/* Set cursor position if input field is active */
if(Handle.Attributes & XTBL_TUI_DIALOG_ACTIVE_INPUT)
{
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);
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"
" Operating System, 'e' to edit it before booting or 's' for XTLDR shell.\n"
" Additional help available after pressing F1 key.");
L" Operating System, 'e' to edit it before booting or 's' for XTLDR shell.\n"
L" Additional help available after pressing F1 key.");
}
/**
@ -1330,3 +1651,164 @@ BlpDrawDialogProgressBar(IN PXTBL_DIALOG_HANDLE Handle,
BlDisableConsoleCursor();
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
* DESCRIPTION: XTLDR volume support
* DEVELOPERS: Rafal Kupiec <belliash@codingworkshop.eu.org>
* Aiken Harris <harraiken91@gmail.com>
*/
#include <xtldr.h>
@ -47,7 +48,11 @@ XTCDECL
EFI_STATUS
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 BlockDeviceData;
PEFI_BLOCK_DEVICE BlockDevice;
@ -62,6 +67,18 @@ BlEnumerateBlockDevices()
USHORT DriveType;
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 */
RtlInitializeListHead(&BlockDevices);
RtlInitializeListHead(&EfiBlockDevices);
@ -78,21 +95,42 @@ BlEnumerateBlockDevices()
ListEntry = BlockDevices.Flink;
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);
PartitionGuid = NULL;
/* Find last node */
Status = BlpFindLastBlockDeviceNode(BlockDeviceData->DevicePath, &LastNode);
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");
ListEntry = ListEntry->Flink;
continue;
}
/* Set drive type to 'unknown' by default */
/* Initialize drive type before attempting to classify the device */
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 */
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)
{
/* Floppy drive found */
Media = BlockDeviceData->BlockIo->Media;
DriveType = XTBL_BOOT_DEVICE_FLOPPY;
DriveNumber = FDCount++;
PartitionNumber = 0;
/* Print debug message */
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 */
if(LastNode->SubType == EFI_MEDIA_CDROM_DP)
{
/* Optical drive found */
Media = BlockDeviceData->BlockIo->Media;
DriveType = XTBL_BOOT_DEVICE_CDROM;
DriveNumber = CDCount++;
PartitionNumber = 0;
/* Optical drive found */
DriveType = XTBL_BOOT_DEVICE_CDROM;
DriveNumber = CDCount++;
PartitionNumber = 0;
/* Print debug message */
BlDebugPrint(L"Found CD-ROM drive (DriveNumber: %lu, MediaPresent: %u, RemovableMedia: %u, RO: %u)\n",
DriveNumber, Media->MediaPresent, Media->RemovableMedia, Media->ReadOnly);
}
else if(LastNode->SubType == EFI_MEDIA_HARDDRIVE_DP)
{
/* Hard disk partition found */
Media = BlockDeviceData->BlockIo->Media;
HDPath = (PEFI_HARDDRIVE_DEVICE_PATH)LastNode;
DriveType = XTBL_BOOT_DEVICE_HARDDISK;
DriveNumber = (HDPath->PartitionNumber == 1) ? HDCount++ : HDCount - 1;
PartitionNumber = HDPath->PartitionNumber;
PartitionGuid = (PEFI_GUID)HDPath->Signature;
/* Print debug message */
BlDebugPrint(L"Found CD-ROM drive (DriveNumber: %lu, MediaPresent: %u, RemovableMedia: %u, RO: %u)\n",
DriveNumber, Media->MediaPresent, Media->RemovableMedia, Media->ReadOnly);
}
else if(LastNode->Type == EFI_MEDIA_DEVICE_PATH && LastNode->SubType == EFI_MEDIA_HARDDRIVE_DP)
{
/* Hard disk partition found */
HDPath = (PEFI_HARDDRIVE_DEVICE_PATH)LastNode;
DriveType = XTBL_BOOT_DEVICE_HARDDISK;
DriveNumber = (HDPath->PartitionNumber == 1) ? HDCount++ : HDCount - 1;
PartitionNumber = HDPath->PartitionNumber;
PartitionGuid = (PEFI_GUID)HDPath->Signature;
/* Print debug message */
BlDebugPrint(L"Found Hard Disk partition (DiskNumber: %lu, PartNumber: %lu, "
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)
/* Check if this is the EFI System Partition (ESP) */
if(BootDeviceHandle != NULL)
{
/* RAM disk found */
Media = BlockDeviceData->BlockIo->Media;
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);
/* Allocate memory for device path */
DevicePath = BlpDuplicateDevicePath(BlockDeviceData->DevicePath);
if(DevicePath != NULL)
{
/* Check if this is the boot device */
Status = EfiSystemTable->BootServices->LocateDevicePath(&BlockIoGuid, &DevicePath,
&DeviceHandle);
if(Status == STATUS_EFI_SUCCESS && DeviceHandle == BootDeviceHandle)
{
/* Mark partition as ESP */
DriveType |= XTBL_BOOT_DEVICE_ESP;
}
}
}
if(!BlpFindParentBlockDevice(&BlockDevices, BlockDeviceData, ParentNode))
{
BlDebugPrint(L"WARNING: No parent device found, skipping orphaned media device path\n");
continue;
}
/* Print debug message */
BlDebugPrint(L"Found Hard Disk partition (DiskNumber: %lu, PartNumber: %lu, "
L"MBRType: %u, GUID: {%V}, PartSize: %lluB) %S\n",
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 */
@ -418,12 +464,26 @@ BlGetVolumeDevicePath(IN PWCHAR SystemPath,
{
/* Check if this is the volume we are looking for */
Device = CONTAIN_RECORD(ListEntry, EFI_BLOCK_DEVICE, ListEntry);
if((Device->DriveType == DriveType && Device->DriveNumber == DriveNumber &&
Device->PartitionNumber == PartNumber))
if(DriveType == XTBL_BOOT_DEVICE_ESP)
{
/* Found volume */
*DevicePath = Device->DevicePath;
break;
/* ESP requested, verify if flag is set for this device */
if((Device->DriveType & XTBL_BOOT_DEVICE_ESP) != 0)
{
/* 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;
}
@ -431,9 +491,9 @@ BlGetVolumeDevicePath(IN PWCHAR SystemPath,
/* Check if volume was found */
if(*DevicePath == NULL)
{
/* Failed to find volume */
/* Volume not found */
BlDebugPrint(L"ERROR: Volume (DriveType: %u, DriveNumber: %lu, PartNumber: %lu) not found\n",
DriveType, DriveNumber, PartNumber);
DriveType, DriveNumber, PartNumber);
return STATUS_EFI_NOT_FOUND;
}
@ -606,7 +666,7 @@ BlReadFile(IN PEFI_FILE_HANDLE DirHandle,
Pages = EFI_SIZE_TO_PAGES(FileInfo->FileSize);
/* Allocate pages */
Status = BlAllocateMemoryPages(Pages, &Address);
Status = BlAllocateMemoryPages(AllocateAnyPages, Pages, &Address);
if(Status != STATUS_EFI_SUCCESS)
{
/* Pages allocation failure */
@ -776,6 +836,12 @@ BlpDissectVolumeArcPath(IN PWCHAR SystemPath,
ArcLength = 10;
*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)
{
/* This is a multi-disk port */
@ -917,17 +983,25 @@ BlpDuplicateDevicePath(IN PEFI_DEVICE_PATH_PROTOCOL DevicePath)
EFI_STATUS Status;
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;
/* Get the device path length */
while(TRUE)
{
Length += *(PUSHORT)DevicePath->Length;
Length += *(PUSHORT)DevicePathNode->Length;
if(DevicePathNode->Type == EFI_END_DEVICE_PATH)
{
break;
}
DevicePathNode = (PEFI_DEVICE_PATH_PROTOCOL)((PUCHAR)DevicePathNode + *(PUSHORT)DevicePath->Length);
DevicePathNode = (PEFI_DEVICE_PATH_PROTOCOL)((PUCHAR)DevicePathNode + *(PUSHORT)DevicePathNode->Length);
}
/* Check length */
@ -1016,7 +1090,7 @@ XTCDECL
BOOLEAN
BlpFindParentBlockDevice(IN PLIST_ENTRY BlockDevices,
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_BLOCK_DEVICE_DATA BlockDeviceData;
@ -1029,6 +1103,14 @@ BlpFindParentBlockDevice(IN PLIST_ENTRY BlockDevices,
/* Take block device from the list */
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;
ParentDevicePath = BlockDeviceData->DevicePath;
@ -1039,7 +1121,7 @@ BlpFindParentBlockDevice(IN PLIST_ENTRY BlockDevices,
if(ParentDevicePath->Type == EFI_END_DEVICE_PATH)
{
/* Parent device is a match */
ParentNode = BlockDeviceData;
*ParentNode = BlockDeviceData;
return TRUE;
}
@ -1047,10 +1129,11 @@ BlpFindParentBlockDevice(IN PLIST_ENTRY BlockDevices,
ChildLength = *(PUSHORT)ChildDevicePath->Length;
ParentLength = *(PUSHORT)ParentDevicePath->Length;
/* Check if lengths match */
if(ChildLength != ParentLength)
/* Check if nodes match */
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;
}

View File

@ -90,16 +90,17 @@ BlInitializeBootLoader()
*/
XTCDECL
EFI_STATUS
BlInitializeBootMenuList(OUT PXTBL_BOOTMENU_ITEM *MenuEntries,
BlInitializeBootMenuList(IN ULONG MaxNameLength,
OUT PXTBL_BOOTMENU_ITEM *MenuEntries,
OUT PULONG EntriesCount,
OUT PULONG DefaultId)
{
EFI_GUID VendorGuid = XT_BOOT_LOADER_PROTOCOL_GUID;
PWCHAR DefaultMenuEntry, LastBooted, MenuEntryName;
PWCHAR DefaultMenuEntry, LastBooted, MenuEntryName, VisibleName;
PLIST_ENTRY MenuEntrySectionList, MenuEntryList;
PXTBL_CONFIG_SECTION MenuEntrySection;
PXTBL_CONFIG_ENTRY MenuEntryOption;
ULONG DefaultOS, NumberOfEntries;
ULONG DefaultOS, NameLength,NumberOfEntries;
PXTBL_BOOTMENU_ITEM OsList;
EFI_STATUS Status;
@ -108,7 +109,7 @@ BlInitializeBootMenuList(OUT PXTBL_BOOTMENU_ITEM *MenuEntries,
NumberOfEntries = 0;
/* Get default menu entry from configuration */
DefaultMenuEntry = BlGetConfigValue(L"DEFAULT");
BlGetConfigValue(L"DEFAULT", &DefaultMenuEntry);
/* Check if configuration allows to use last booted OS */
if(BlGetConfigBooleanValue(L"KEEPLASTBOOT"))
@ -151,7 +152,8 @@ BlInitializeBootMenuList(OUT PXTBL_BOOTMENU_ITEM *MenuEntries,
MenuEntrySection = CONTAIN_RECORD(MenuEntrySectionList, XTBL_CONFIG_SECTION, Flink);
/* 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 */
DefaultOS = NumberOfEntries;
@ -176,10 +178,36 @@ BlInitializeBootMenuList(OUT PXTBL_BOOTMENU_ITEM *MenuEntries,
}
/* Add OS to the boot menu list */
OsList[NumberOfEntries].EntryName = MenuEntryName;
OsList[NumberOfEntries].FullName = MenuEntryName;
OsList[NumberOfEntries].ShortName = MenuEntrySection->SectionName;
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 */
MenuEntrySectionList = MenuEntrySectionList->Flink;
NumberOfEntries++;
@ -363,6 +391,7 @@ EFI_STATUS
BlStartXtLoader(IN EFI_HANDLE ImageHandle,
IN PEFI_SYSTEM_TABLE SystemTable)
{
PWCHAR Modules;
EFI_STATUS Status;
/* Set the system table and image handle */
@ -427,8 +456,9 @@ BlStartXtLoader(IN EFI_HANDLE ImageHandle,
return Status;
}
/* Load boot loader modules */
Status = BlLoadModules(BlGetConfigValue(L"MODULES"));
/* Load all necessary modules */
BlGetConfigValue(L"MODULES", &Modules);
Status = BlLoadModules(Modules);
if(Status != STATUS_EFI_SUCCESS)
{
/* Failed to load modules */

View File

@ -9,6 +9,7 @@ include_directories(
# Specify list of library source code files
list(APPEND LIBXTOS_SOURCE
${XTOSKRNL_SOURCE_DIR}/ar/${ARCH}/boot.S
${XTOSKRNL_SOURCE_DIR}/ar/${ARCH}/cpufunc.c
${XTOSKRNL_SOURCE_DIR}/hl/cport.c
${XTOSKRNL_SOURCE_DIR}/hl/${ARCH}/ioport.c
@ -23,6 +24,7 @@ list(APPEND LIBXTOS_SOURCE
# Specify list of kernel source code files
list(APPEND XTOSKRNL_SOURCE
${XTOSKRNL_SOURCE_DIR}/ar/${ARCH}/archsup.S
${XTOSKRNL_SOURCE_DIR}/ar/${ARCH}/boot.S
${XTOSKRNL_SOURCE_DIR}/ar/${ARCH}/cpufunc.c
${XTOSKRNL_SOURCE_DIR}/ar/${ARCH}/globals.c
${XTOSKRNL_SOURCE_DIR}/ar/${ARCH}/procsup.c
@ -37,10 +39,14 @@ list(APPEND XTOSKRNL_SOURCE
${XTOSKRNL_SOURCE_DIR}/hl/${ARCH}/pic.c
${XTOSKRNL_SOURCE_DIR}/hl/${ARCH}/ioport.c
${XTOSKRNL_SOURCE_DIR}/hl/${ARCH}/runlevel.c
${XTOSKRNL_SOURCE_DIR}/kd/dbginit.c
${XTOSKRNL_SOURCE_DIR}/kd/dbgio.c
${XTOSKRNL_SOURCE_DIR}/kd/globals.c
${XTOSKRNL_SOURCE_DIR}/ke/apc.c
${XTOSKRNL_SOURCE_DIR}/ke/dpc.c
${XTOSKRNL_SOURCE_DIR}/ke/event.c
${XTOSKRNL_SOURCE_DIR}/ke/globals.c
${XTOSKRNL_SOURCE_DIR}/ke/info.c
${XTOSKRNL_SOURCE_DIR}/ke/kprocess.c
${XTOSKRNL_SOURCE_DIR}/ke/krnlinit.c
${XTOSKRNL_SOURCE_DIR}/ke/kthread.c
@ -60,8 +66,10 @@ list(APPEND XTOSKRNL_SOURCE
${XTOSKRNL_SOURCE_DIR}/mm/init.c
${XTOSKRNL_SOURCE_DIR}/mm/kpools.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}/pages.c
${XTOSKRNL_SOURCE_DIR}/mm/${ARCH}/pmap.c
${XTOSKRNL_SOURCE_DIR}/po/idle.c
${XTOSKRNL_SOURCE_DIR}/rtl/atomic.c
${XTOSKRNL_SOURCE_DIR}/rtl/bitmap.c

View File

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

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:

View File

@ -20,7 +20,7 @@ XTCDECL
VOID
ArClearInterruptFlag(VOID)
{
asm volatile("cli");
__asm__ volatile("cli");
}
/**
@ -40,12 +40,12 @@ ArCpuId(IN OUT PCPUID_REGISTERS Registers)
UINT32 MaxLeaf;
/* Get highest function ID available */
asm volatile("cpuid"
: "=a" (MaxLeaf)
: "a" (Registers->Leaf & 0x80000000)
: "rbx",
"rcx",
"rdx");
__asm__ volatile("cpuid"
: "=a" (MaxLeaf)
: "a" (Registers->Leaf & 0x80000000)
: "rbx",
"rcx",
"rdx");
/* Check if CPU supports this command */
if(Registers->Leaf > MaxLeaf)
@ -55,13 +55,13 @@ ArCpuId(IN OUT PCPUID_REGISTERS Registers)
}
/* Execute CPUID function */
asm volatile("cpuid"
: "=a" (Registers->Eax),
"=b" (Registers->Ebx),
"=c" (Registers->Ecx),
"=d" (Registers->Edx)
: "a" (Registers->Leaf),
"c" (Registers->SubLeaf));
__asm__ volatile("cpuid"
: "=a" (Registers->Eax),
"=b" (Registers->Ebx),
"=c" (Registers->Ecx),
"=d" (Registers->Edx)
: "a" (Registers->Leaf),
"c" (Registers->SubLeaf));
/* Return TRUE */
return TRUE;
@ -96,11 +96,11 @@ ArGetCpuFlags(VOID)
ULONG_PTR Flags;
/* Get RFLAGS register */
asm volatile("pushf\n"
"pop %0\n"
: "=rm" (Flags)
:
: "memory");
__asm__ volatile("pushf\n"
"pop %0\n"
: "=rm" (Flags)
:
: "memory");
/* Return flags */
return Flags;
@ -119,11 +119,11 @@ ULONG_PTR
ArGetStackPointer(VOID)
{
/* Get current stack pointer */
asm volatile("movq %%rsp, %%rax\n"
"retq\n"
:
:
:);
__asm__ volatile("movq %%rsp, %%rax\n"
"retq\n"
:
:
:);
}
/**
@ -137,7 +137,7 @@ XTCDECL
VOID
ArHalt(VOID)
{
asm volatile("hlt");
__asm__ volatile("hlt");
}
/**
@ -174,10 +174,10 @@ XTCDECL
VOID
ArInvalidateTlbEntry(IN PVOID Address)
{
asm volatile("invlpg (%0)"
:
: "b" (Address)
: "memory");
__asm__ volatile("invlpg (%0)"
:
: "b" (Address)
: "memory");
}
/**
@ -194,10 +194,10 @@ XTCDECL
VOID
ArLoadGlobalDescriptorTable(IN PVOID Source)
{
asm volatile("lgdt %0"
:
: "m" (*(PSHORT)Source)
: "memory");
__asm__ volatile("lgdt %0"
:
: "m" (*(PSHORT)Source)
: "memory");
}
/**
@ -214,10 +214,10 @@ XTCDECL
VOID
ArLoadInterruptDescriptorTable(IN PVOID Source)
{
asm volatile("lidt %0"
:
: "m" (*(PSHORT)Source)
: "memory");
__asm__ volatile("lidt %0"
:
: "m" (*(PSHORT)Source)
: "memory");
}
/**
@ -234,9 +234,9 @@ XTCDECL
VOID
ArLoadLocalDescriptorTable(IN USHORT Source)
{
asm volatile("lldtw %0"
:
: "g" (Source));
__asm__ volatile("lldtw %0"
:
: "g" (Source));
}
/**
@ -253,9 +253,9 @@ XTCDECL
VOID
ArLoadMxcsrRegister(IN ULONG Source)
{
asm volatile("ldmxcsr %0"
:
: "m" (Source));
__asm__ volatile("ldmxcsr %0"
:
: "m" (Source));
}
/**
@ -280,45 +280,45 @@ ArLoadSegment(IN USHORT Segment,
{
case SEGMENT_CS:
/* Load CS Segment */
asm volatile("mov %0, %%rax\n"
"push %%rax\n"
"lea label(%%rip), %%rax\n"
"push %%rax\n"
"lretq\n"
"label:"
:
: "ri" ((ULONGLONG)Source)
: "rax");
__asm__ volatile("mov %0, %%rax\n"
"push %%rax\n"
"lea label(%%rip), %%rax\n"
"push %%rax\n"
"lretq\n"
"label:"
:
: "ri" ((ULONGLONG)Source)
: "rax");
break;
case SEGMENT_DS:
/* Load DS Segment */
asm volatile("movl %0, %%ds"
:
: "r" (Source));
__asm__ volatile("movl %0, %%ds"
:
: "r" (Source));
break;
case SEGMENT_ES:
/* Load ES Segment */
asm volatile("movl %0, %%es"
:
: "r" (Source));
__asm__ volatile("movl %0, %%es"
:
: "r" (Source));
break;
case SEGMENT_FS:
/* Load FS Segment */
asm volatile("movl %0, %%fs"
:
: "r" (Source));
__asm__ volatile("movl %0, %%fs"
:
: "r" (Source));
break;
case SEGMENT_GS:
/* Load GS Segment */
asm volatile("movl %0, %%gs"
:
: "r" (Source));
__asm__ volatile("movl %0, %%gs"
:
: "r" (Source));
break;
/* Load SS Segment */
case SEGMENT_SS:
asm volatile("movl %0, %%ss"
:
: "r" (Source));
__asm__ volatile("movl %0, %%ss"
:
: "r" (Source));
break;
}
}
@ -337,9 +337,9 @@ XTCDECL
VOID
ArLoadTaskRegister(USHORT Source)
{
asm volatile("ltr %0"
:
: "rm" (Source));
__asm__ volatile("ltr %0"
:
: "rm" (Source));
}
/**
@ -354,9 +354,9 @@ VOID
ArMemoryBarrier(VOID)
{
LONG Barrier;
asm volatile("lock; orl $0, %0;"
:
: "m"(Barrier));
__asm__ volatile("lock; orl $0, %0;"
:
: "m"(Barrier));
}
/**
@ -380,38 +380,38 @@ ArReadControlRegister(IN USHORT ControlRegister)
{
case 0:
/* Read value from CR0 */
asm volatile("mov %%cr0, %0"
: "=r" (Value)
:
: "memory");
__asm__ volatile("mov %%cr0, %0"
: "=r" (Value)
:
: "memory");
break;
case 2:
/* Read value from CR2 */
asm volatile("mov %%cr2, %0"
: "=r" (Value)
:
: "memory");
__asm__ volatile("mov %%cr2, %0"
: "=r" (Value)
:
: "memory");
break;
case 3:
/* Read value from CR3 */
asm volatile("mov %%cr3, %0"
: "=r" (Value)
:
: "memory");
__asm__ volatile("mov %%cr3, %0"
: "=r" (Value)
:
: "memory");
break;
case 4:
/* Read value from CR4 */
asm volatile("mov %%cr4, %0"
: "=r" (Value)
:
: "memory");
__asm__ volatile("mov %%cr4, %0"
: "=r" (Value)
:
: "memory");
break;
case 8:
/* Read value from CR8 */
asm volatile("mov %%cr8, %0"
: "=r" (Value)
:
: "memory");
__asm__ volatile("mov %%cr8, %0"
: "=r" (Value)
:
: "memory");
break;
default:
/* Invalid control register set */
@ -444,43 +444,43 @@ ArReadDebugRegister(IN USHORT DebugRegister)
{
case 0:
/* Read value from DR0 */
asm volatile("mov %%dr0, %0"
: "=r" (Value));
__asm__ volatile("mov %%dr0, %0"
: "=r" (Value));
break;
case 1:
/* Read value from DR1 */
asm volatile("mov %%dr1, %0"
: "=r" (Value));
__asm__ volatile("mov %%dr1, %0"
: "=r" (Value));
break;
case 2:
/* Read value from DR2 */
asm volatile("mov %%dr2, %0"
: "=r" (Value));
__asm__ volatile("mov %%dr2, %0"
: "=r" (Value));
break;
case 3:
/* Read value from DR3 */
asm volatile("mov %%dr3, %0"
: "=r" (Value));
__asm__ volatile("mov %%dr3, %0"
: "=r" (Value));
break;
case 4:
/* Read value from DR4 */
asm volatile("mov %%dr4, %0"
: "=r" (Value));
__asm__ volatile("mov %%dr4, %0"
: "=r" (Value));
break;
case 5:
/* Read value from DR5 */
asm volatile("mov %%dr5, %0"
: "=r" (Value));
__asm__ volatile("mov %%dr5, %0"
: "=r" (Value));
break;
case 6:
/* Read value from DR6 */
asm volatile("mov %%dr6, %0"
: "=r" (Value));
__asm__ volatile("mov %%dr6, %0"
: "=r" (Value));
break;
case 7:
/* Read value from DR7 */
asm volatile("mov %%dr7, %0"
: "=r" (Value));
__asm__ volatile("mov %%dr7, %0"
: "=r" (Value));
break;
default:
/* Invalid debug register set */
@ -509,9 +509,9 @@ ArReadGSQuadWord(ULONG Offset)
ULONGLONG Value;
/* Read quadword from GS segment */
asm volatile("movq %%gs:%a[Offset], %q[Value]"
: [Value] "=r" (Value)
: [Offset] "ir" (Offset));
__asm__ volatile("movq %%gs:%a[Offset], %q[Value]"
: [Value] "=r" (Value)
: [Offset] "ir" (Offset));
return Value;
}
@ -531,10 +531,10 @@ ArReadModelSpecificRegister(IN ULONG Register)
{
ULONG Low, High;
asm volatile("rdmsr"
: "=a" (Low),
"=d" (High)
: "c" (Register));
__asm__ volatile("rdmsr"
: "=a" (Low),
"=d" (High)
: "c" (Register));
return ((ULONGLONG)High << 32) | Low;
}
@ -566,9 +566,9 @@ ArReadTimeStampCounter(VOID)
{
ULONGLONG Low, High;
asm volatile("rdtsc"
: "=a" (Low),
"=d" (High));
__asm__ volatile("rdtsc"
: "=a" (Low),
"=d" (High));
return ((ULONGLONG)High << 32) | Low;
}
@ -584,10 +584,10 @@ XTCDECL
VOID
ArReadWriteBarrier(VOID)
{
asm volatile(""
:
:
: "memory");
__asm__ volatile(""
:
:
: "memory");
}
/**
@ -601,7 +601,7 @@ XTCDECL
VOID
ArSetInterruptFlag(VOID)
{
asm volatile("sti");
__asm__ volatile("sti");
}
/**
@ -618,10 +618,10 @@ XTCDECL
VOID
ArStoreGlobalDescriptorTable(OUT PVOID Destination)
{
asm volatile("sgdt %0"
: "=m" (*(PSHORT)Destination)
:
: "memory");
__asm__ volatile("sgdt %0"
: "=m" (*(PSHORT)Destination)
:
: "memory");
}
/**
@ -638,10 +638,10 @@ XTCDECL
VOID
ArStoreInterruptDescriptorTable(OUT PVOID Destination)
{
asm volatile("sidt %0"
: "=m" (*(PSHORT)Destination)
:
: "memory");
__asm__ volatile("sidt %0"
: "=m" (*(PSHORT)Destination)
:
: "memory");
}
/**
@ -658,10 +658,10 @@ XTCDECL
VOID
ArStoreLocalDescriptorTable(OUT PVOID Destination)
{
asm volatile("sldt %0"
: "=m" (*(PSHORT)Destination)
:
: "memory");
__asm__ volatile("sldt %0"
: "=m" (*(PSHORT)Destination)
:
: "memory");
}
/**
@ -685,28 +685,28 @@ ArStoreSegment(IN USHORT Segment,
switch(Segment)
{
case SEGMENT_CS:
asm volatile("movl %%cs, %0"
: "=r" (*(PUINT)Destination));
__asm__ volatile("movl %%cs, %0"
: "=r" (*(PUINT)Destination));
break;
case SEGMENT_DS:
asm volatile("movl %%ds, %0"
: "=r" (*(PUINT)Destination));
__asm__ volatile("movl %%ds, %0"
: "=r" (*(PUINT)Destination));
break;
case SEGMENT_ES:
asm volatile("movl %%es, %0"
: "=r" (*(PUINT)Destination));
__asm__ volatile("movl %%es, %0"
: "=r" (*(PUINT)Destination));
break;
case SEGMENT_FS:
asm volatile("movl %%fs, %0"
: "=r" (*(PUINT)Destination));
__asm__ volatile("movl %%fs, %0"
: "=r" (*(PUINT)Destination));
break;
case SEGMENT_GS:
asm volatile("movl %%gs, %0"
: "=r" (*(PUINT)Destination));
__asm__ volatile("movl %%gs, %0"
: "=r" (*(PUINT)Destination));
break;
case SEGMENT_SS:
asm volatile("movl %%ss, %0"
: "=r" (*(PUINT)Destination));
__asm__ volatile("movl %%ss, %0"
: "=r" (*(PUINT)Destination));
break;
default:
Destination = NULL;
@ -728,10 +728,10 @@ XTCDECL
VOID
ArStoreTaskRegister(OUT PVOID Destination)
{
asm volatile("str %0"
: "=m" (*(PULONG)Destination)
:
: "memory");
__asm__ volatile("str %0"
: "=m" (*(PULONG)Destination)
:
: "memory");
}
/**
@ -757,38 +757,38 @@ ArWriteControlRegister(IN USHORT ControlRegister,
{
case 0:
/* Write value to CR0 */
asm volatile("mov %0, %%cr0"
:
: "r"(Value)
: "memory");
__asm__ volatile("mov %0, %%cr0"
:
: "r"(Value)
: "memory");
break;
case 2:
/* Write value to CR2 */
asm volatile("mov %0, %%cr2"
:
: "r"(Value)
: "memory");
__asm__ volatile("mov %0, %%cr2"
:
: "r"(Value)
: "memory");
break;
case 3:
/* Write value to CR3 */
asm volatile("mov %0, %%cr3"
:
: "r"(Value)
: "memory");
__asm__ volatile("mov %0, %%cr3"
:
: "r"(Value)
: "memory");
break;
case 4:
/* Write value to CR4 */
asm volatile("mov %0, %%cr4"
:
: "r"(Value)
: "memory");
__asm__ volatile("mov %0, %%cr4"
:
: "r"(Value)
: "memory");
break;
case 8:
/* Write value to CR8 */
asm volatile("mov %0, %%cr8"
:
: "r"(Value)
: "memory");
__asm__ volatile("mov %0, %%cr8"
:
: "r"(Value)
: "memory");
break;
}
}
@ -816,52 +816,52 @@ ArWriteDebugRegister(IN USHORT DebugRegister,
{
case 0:
/* Write value to DR0 */
asm volatile("mov %0, %%dr0"
:
: "r" (Value)
: "memory");
__asm__ volatile("mov %0, %%dr0"
:
: "r" (Value)
: "memory");
case 1:
/* Write value to DR1 */
asm volatile("mov %0, %%dr1"
:
: "r" (Value)
: "memory");
__asm__ volatile("mov %0, %%dr1"
:
: "r" (Value)
: "memory");
case 2:
/* Write value to DR2 */
asm volatile("mov %0, %%dr2"
:
: "r" (Value)
: "memory");
__asm__ volatile("mov %0, %%dr2"
:
: "r" (Value)
: "memory");
case 3:
/* Write value to DR3 */
asm volatile("mov %0, %%dr3"
:
: "r" (Value)
: "memory");
__asm__ volatile("mov %0, %%dr3"
:
: "r" (Value)
: "memory");
case 4:
/* Write value to DR4 */
asm volatile("mov %0, %%dr4"
:
: "r" (Value)
: "memory");
__asm__ volatile("mov %0, %%dr4"
:
: "r" (Value)
: "memory");
case 5:
/* Write value to DR5 */
asm volatile("mov %0, %%dr5"
:
: "r" (Value)
: "memory");
__asm__ volatile("mov %0, %%dr5"
:
: "r" (Value)
: "memory");
case 6:
/* Write value to DR6 */
asm volatile("mov %0, %%dr6"
:
: "r" (Value)
: "memory");
__asm__ volatile("mov %0, %%dr6"
:
: "r" (Value)
: "memory");
case 7:
/* Write value to DR7 */
asm volatile("mov %0, %%dr7"
:
: "r" (Value)
: "memory");
__asm__ volatile("mov %0, %%dr7"
:
: "r" (Value)
: "memory");
}
}
@ -879,10 +879,10 @@ XTCDECL
VOID
ArWriteEflagsRegister(IN UINT_PTR Value)
{
asm volatile("push %0\n"
"popf"
:
: "rim" (Value));
__asm__ volatile("push %0\n"
"popf"
:
: "rim" (Value));
}
/**
@ -906,11 +906,11 @@ ArWriteModelSpecificRegister(IN ULONG Register,
ULONG Low = Value & 0xFFFFFFFF;
ULONG High = Value >> 32;
asm volatile("wrmsr"
:
: "c" (Register),
"a" (Low),
"d" (High));
__asm__ volatile("wrmsr"
:
: "c" (Register),
"a" (Low),
"d" (High));
}
/**
@ -924,8 +924,8 @@ XTCDECL
VOID
ArYieldProcessor(VOID)
{
asm volatile("pause"
:
:
: "memory");
__asm__ volatile("pause"
:
:
: "memory");
}

View File

@ -152,9 +152,9 @@ ArpIdentifyProcessor(VOID)
*(PULONG)&Prcb->CpuId.VendorName[8] = CpuRegisters.Ecx;
Prcb->CpuId.VendorName[12] = '\0';
/* Get CPU features */
/* Get CPU standard features */
RtlZeroMemory(&CpuRegisters, sizeof(CPUID_REGISTERS));
CpuRegisters.Leaf = CPUID_GET_CPU_FEATURES;
CpuRegisters.Leaf = CPUID_GET_STANDARD1_FEATURES;
ArCpuId(&CpuRegisters);
/* Store CPU signature in processor control block */
@ -216,7 +216,7 @@ ArpInitializeGdt(IN PKPROCESSOR_BLOCK ProcessorBlock)
ArpSetGdtEntry(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);
ArpSetGdtEntry(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);
ArpSetGdtEntry(ProcessorBlock->GdtBase, KGDT_SYS_TSS, (ULONG_PTR)ProcessorBlock->TssBase, sizeof(KTSS) - 1, AMD64_TSS, KGDT_DPL_SYSTEM, 0);
ArpSetGdtEntry(ProcessorBlock->GdtBase, KGDT_R3_CMTEB, 0x0, 0x0FFF, KGDT_TYPE_DATA, KGDT_DPL_USER, 2);
ArpSetGdtEntry(ProcessorBlock->GdtBase, KGDT_R0_LDT, 0x0, 0xFFFFFFFF, KGDT_TYPE_CODE, 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);

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

View File

@ -20,7 +20,7 @@ XTCDECL
VOID
ArClearInterruptFlag(VOID)
{
asm volatile("cli");
__asm__ volatile("cli");
}
/**
@ -40,12 +40,12 @@ ArCpuId(IN OUT PCPUID_REGISTERS Registers)
UINT32 MaxLeaf;
/* Get highest function ID available */
asm volatile("cpuid"
: "=a" (MaxLeaf)
: "a" (Registers->Leaf & 0x80000000)
: "rbx",
"rcx",
"rdx");
__asm__ volatile("cpuid"
: "=a" (MaxLeaf)
: "a" (Registers->Leaf & 0x80000000)
: "rbx",
"rcx",
"rdx");
/* Check if CPU supports this command */
if(Registers->Leaf > MaxLeaf)
@ -55,13 +55,13 @@ ArCpuId(IN OUT PCPUID_REGISTERS Registers)
}
/* Execute CPUID function */
asm volatile("cpuid"
: "=a" (Registers->Eax),
"=b" (Registers->Ebx),
"=c" (Registers->Ecx),
"=d" (Registers->Edx)
: "a" (Registers->Leaf),
"c" (Registers->SubLeaf));
__asm__ volatile("cpuid"
: "=a" (Registers->Eax),
"=b" (Registers->Ebx),
"=c" (Registers->Ecx),
"=d" (Registers->Edx)
: "a" (Registers->Leaf),
"c" (Registers->SubLeaf));
/* Return TRUE */
return TRUE;
@ -96,11 +96,11 @@ ArGetCpuFlags(VOID)
ULONG_PTR Flags;
/* Get EFLAGS register */
asm volatile("pushf\n"
"pop %0\n"
: "=rm" (Flags)
:
: "memory");
__asm__ volatile("pushf\n"
"pop %0\n"
: "=rm" (Flags)
:
: "memory");
/* Return flags */
return Flags;
@ -119,11 +119,11 @@ ULONG_PTR
ArGetStackPointer(VOID)
{
/* Get current stack pointer */
asm volatile("mov %%esp, %%eax\n"
"ret\n"
:
:
:);
__asm__ volatile("mov %%esp, %%eax\n"
"ret\n"
:
:
:);
}
/**
@ -137,7 +137,7 @@ XTCDECL
VOID
ArHalt(VOID)
{
asm volatile("hlt");
__asm__ volatile("hlt");
}
/**
@ -174,10 +174,10 @@ XTCDECL
VOID
ArInvalidateTlbEntry(PVOID Address)
{
asm volatile("invlpg (%0)"
:
: "b" (Address)
: "memory");
__asm__ volatile("invlpg (%0)"
:
: "b" (Address)
: "memory");
}
/**
@ -194,10 +194,10 @@ XTCDECL
VOID
ArLoadGlobalDescriptorTable(IN PVOID Source)
{
asm volatile("lgdt %0"
:
: "m" (*(PSHORT)Source)
: "memory");
__asm__ volatile("lgdt %0"
:
: "m" (*(PSHORT)Source)
: "memory");
}
/**
@ -214,10 +214,10 @@ XTCDECL
VOID
ArLoadInterruptDescriptorTable(IN PVOID Source)
{
asm volatile("lidt %0"
:
: "m" (*(PSHORT)Source)
: "memory");
__asm__ volatile("lidt %0"
:
: "m" (*(PSHORT)Source)
: "memory");
}
/**
@ -234,9 +234,9 @@ XTCDECL
VOID
ArLoadLocalDescriptorTable(IN USHORT Source)
{
asm volatile("lldtw %0"
:
: "g" (Source));
__asm__ volatile("lldtw %0"
:
: "g" (Source));
}
/**
@ -261,45 +261,45 @@ ArLoadSegment(IN USHORT Segment,
{
case SEGMENT_CS:
/* Load CS Segment */
asm volatile("mov %0, %%eax\n"
"push %%eax\n"
"lea label, %%eax\n"
"push %%eax\n"
"lret\n"
"label:"
:
: "ri" (Source)
: "eax");
__asm__ volatile("mov %0, %%eax\n"
"push %%eax\n"
"lea label, %%eax\n"
"push %%eax\n"
"lret\n"
"label:"
:
: "ri" (Source)
: "eax");
break;
case SEGMENT_DS:
/* Load DS Segment */
asm volatile("movl %0, %%ds"
:
: "r" (Source));
__asm__ volatile("movl %0, %%ds"
:
: "r" (Source));
break;
case SEGMENT_ES:
/* Load ES Segment */
asm volatile("movl %0, %%es"
:
: "r" (Source));
__asm__ volatile("movl %0, %%es"
:
: "r" (Source));
break;
case SEGMENT_FS:
/* Load FS Segment */
asm volatile("movl %0, %%fs"
:
: "r" (Source));
__asm__ volatile("movl %0, %%fs"
:
: "r" (Source));
break;
case SEGMENT_GS:
/* Load GS Segment */
asm volatile("movl %0, %%gs"
:
: "r" (Source));
__asm__ volatile("movl %0, %%gs"
:
: "r" (Source));
break;
case SEGMENT_SS:
/* Load SS Segment */
asm volatile("movl %0, %%ss"
:
: "r" (Source));
__asm__ volatile("movl %0, %%ss"
:
: "r" (Source));
break;
}
}
@ -318,9 +318,9 @@ XTCDECL
VOID
ArLoadTaskRegister(USHORT Source)
{
asm volatile("ltr %0"
:
: "rm" (Source));
__asm__ volatile("ltr %0"
:
: "rm" (Source));
}
/**
@ -335,10 +335,10 @@ VOID
ArMemoryBarrier(VOID)
{
LONG Barrier;
asm volatile("xchg %%eax, %0"
:
: "m" (Barrier)
: "%eax");
__asm__ volatile("xchg %%eax, %0"
:
: "m" (Barrier)
: "%eax");
}
/**
@ -362,31 +362,31 @@ ArReadControlRegister(IN USHORT ControlRegister)
{
case 0:
/* Read value from CR0 */
asm volatile("mov %%cr0, %0"
: "=r" (Value)
:
: "memory");
__asm__ volatile("mov %%cr0, %0"
: "=r" (Value)
:
: "memory");
break;
case 2:
/* Read value from CR2 */
asm volatile("mov %%cr2, %0"
: "=r" (Value)
:
: "memory");
__asm__ volatile("mov %%cr2, %0"
: "=r" (Value)
:
: "memory");
break;
case 3:
/* Read value from CR3 */
asm volatile("mov %%cr3, %0"
: "=r" (Value)
:
: "memory");
__asm__ volatile("mov %%cr3, %0"
: "=r" (Value)
:
: "memory");
break;
case 4:
/* Read value from CR4 */
asm volatile("mov %%cr4, %0"
: "=r" (Value)
:
: "memory");
__asm__ volatile("mov %%cr4, %0"
: "=r" (Value)
:
: "memory");
break;
default:
/* Invalid control register set */
@ -419,43 +419,43 @@ ArReadDebugRegister(IN USHORT DebugRegister)
{
case 0:
/* Read value from DR0 */
asm volatile("mov %%dr0, %0"
: "=r" (Value));
__asm__ volatile("mov %%dr0, %0"
: "=r" (Value));
break;
case 1:
/* Read value from DR1 */
asm volatile("mov %%dr1, %0"
: "=r" (Value));
__asm__ volatile("mov %%dr1, %0"
: "=r" (Value));
break;
case 2:
/* Read value from DR2 */
asm volatile("mov %%dr2, %0"
: "=r" (Value));
__asm__ volatile("mov %%dr2, %0"
: "=r" (Value));
break;
case 3:
/* Read value from DR3 */
asm volatile("mov %%dr3, %0"
: "=r" (Value));
__asm__ volatile("mov %%dr3, %0"
: "=r" (Value));
break;
case 4:
/* Read value from DR4 */
asm volatile("mov %%dr4, %0"
: "=r" (Value));
__asm__ volatile("mov %%dr4, %0"
: "=r" (Value));
break;
case 5:
/* Read value from DR5 */
asm volatile("mov %%dr5, %0"
: "=r" (Value));
__asm__ volatile("mov %%dr5, %0"
: "=r" (Value));
break;
case 6:
/* Read value from DR6 */
asm volatile("mov %%dr6, %0"
: "=r" (Value));
__asm__ volatile("mov %%dr6, %0"
: "=r" (Value));
break;
case 7:
/* Read value from DR7 */
asm volatile("mov %%dr7, %0"
: "=r" (Value));
__asm__ volatile("mov %%dr7, %0"
: "=r" (Value));
break;
default:
/* Invalid debug register set */
@ -482,9 +482,9 @@ ULONG
ArReadFSDualWord(ULONG Offset)
{
ULONG Value;
asm volatile("movl %%fs:%a[Offset], %k[Value]"
: [Value] "=r" (Value)
: [Offset] "ir" (Offset));
__asm__ volatile("movl %%fs:%a[Offset], %k[Value]"
: [Value] "=r" (Value)
: [Offset] "ir" (Offset));
return Value;
}
@ -504,9 +504,9 @@ ArReadModelSpecificRegister(IN ULONG Register)
{
ULONGLONG Value;
asm volatile("rdmsr"
: "=A" (Value)
: "c" (Register));
__asm__ volatile("rdmsr"
: "=A" (Value)
: "c" (Register));
return Value;
}
@ -537,8 +537,8 @@ ArReadTimeStampCounter(VOID)
{
ULONGLONG Value;
asm volatile("rdtsc"
: "=A" (Value));
__asm__ volatile("rdtsc"
: "=A" (Value));
return Value;
}
@ -554,10 +554,10 @@ XTCDECL
VOID
ArReadWriteBarrier(VOID)
{
asm volatile(""
:
:
: "memory");
__asm__ volatile(""
:
:
: "memory");
}
/**
@ -571,7 +571,7 @@ XTCDECL
VOID
ArSetInterruptFlag(VOID)
{
asm volatile("sti");
__asm__ volatile("sti");
}
/**
@ -588,10 +588,10 @@ XTCDECL
VOID
ArStoreGlobalDescriptorTable(OUT PVOID Destination)
{
asm volatile("sgdt %0"
: "=m" (*(PSHORT)Destination)
:
: "memory");
__asm__ volatile("sgdt %0"
: "=m" (*(PSHORT)Destination)
:
: "memory");
}
/**
@ -608,10 +608,10 @@ XTCDECL
VOID
ArStoreInterruptDescriptorTable(OUT PVOID Destination)
{
asm volatile("sidt %0"
: "=m" (*(PSHORT)Destination)
:
: "memory");
__asm__ volatile("sidt %0"
: "=m" (*(PSHORT)Destination)
:
: "memory");
}
/**
@ -628,10 +628,10 @@ XTCDECL
VOID
ArStoreLocalDescriptorTable(OUT PVOID Destination)
{
asm volatile("sldt %0"
: "=m" (*(PSHORT)Destination)
:
: "memory");
__asm__ volatile("sldt %0"
: "=m" (*(PSHORT)Destination)
:
: "memory");
}
/**
@ -655,28 +655,28 @@ ArStoreSegment(IN USHORT Segment,
switch(Segment)
{
case SEGMENT_CS:
asm volatile("movl %%cs, %0"
: "=r" (*(PUINT)Destination));
__asm__ volatile("movl %%cs, %0"
: "=r" (*(PUINT)Destination));
break;
case SEGMENT_DS:
asm volatile("movl %%ds, %0"
: "=r" (*(PUINT)Destination));
__asm__ volatile("movl %%ds, %0"
: "=r" (*(PUINT)Destination));
break;
case SEGMENT_ES:
asm volatile("movl %%es, %0"
: "=r" (*(PUINT)Destination));
__asm__ volatile("movl %%es, %0"
: "=r" (*(PUINT)Destination));
break;
case SEGMENT_FS:
asm volatile("movl %%fs, %0"
: "=r" (*(PUINT)Destination));
__asm__ volatile("movl %%fs, %0"
: "=r" (*(PUINT)Destination));
break;
case SEGMENT_GS:
asm volatile("movl %%gs, %0"
: "=r" (*(PUINT)Destination));
__asm__ volatile("movl %%gs, %0"
: "=r" (*(PUINT)Destination));
break;
case SEGMENT_SS:
asm volatile("movl %%ss, %0"
: "=r" (*(PUINT)Destination));
__asm__ volatile("movl %%ss, %0"
: "=r" (*(PUINT)Destination));
break;
default:
Destination = NULL;
@ -698,10 +698,10 @@ XTCDECL
VOID
ArStoreTaskRegister(OUT PVOID Destination)
{
asm volatile("str %0"
: "=m" (*(PULONG)Destination)
:
: "memory");
__asm__ volatile("str %0"
: "=m" (*(PULONG)Destination)
:
: "memory");
}
/**
@ -727,31 +727,31 @@ ArWriteControlRegister(IN USHORT ControlRegister,
{
case 0:
/* Write value to CR0 */
asm volatile("mov %0, %%cr0"
:
: "r" (Value)
: "memory");
__asm__ volatile("mov %0, %%cr0"
:
: "r" (Value)
: "memory");
break;
case 2:
/* Write value to CR2 */
asm volatile("mov %0, %%cr2"
:
: "r" (Value)
: "memory");
__asm__ volatile("mov %0, %%cr2"
:
: "r" (Value)
: "memory");
break;
case 3:
/* Write value to CR3 */
asm volatile("mov %0, %%cr3"
:
: "r" (Value)
: "memory");
__asm__ volatile("mov %0, %%cr3"
:
: "r" (Value)
: "memory");
break;
case 4:
/* Write value to CR4 */
asm volatile("mov %0, %%cr4"
:
: "r" (Value)
: "memory");
__asm__ volatile("mov %0, %%cr4"
:
: "r" (Value)
: "memory");
break;
}
}
@ -779,52 +779,52 @@ ArWriteDebugRegister(IN USHORT DebugRegister,
{
case 0:
/* Write value to DR0 */
asm volatile("mov %0, %%dr0"
:
: "r" (Value)
: "memory");
__asm__ volatile("mov %0, %%dr0"
:
: "r" (Value)
: "memory");
case 1:
/* Write value to DR1 */
asm volatile("mov %0, %%dr1"
:
: "r" (Value)
: "memory");
__asm__ volatile("mov %0, %%dr1"
:
: "r" (Value)
: "memory");
case 2:
/* Write value to DR2 */
asm volatile("mov %0, %%dr2"
:
: "r" (Value)
: "memory");
__asm__ volatile("mov %0, %%dr2"
:
: "r" (Value)
: "memory");
case 3:
/* Write value to DR3 */
asm volatile("mov %0, %%dr3"
:
: "r" (Value)
: "memory");
__asm__ volatile("mov %0, %%dr3"
:
: "r" (Value)
: "memory");
case 4:
/* Write value to DR4 */
asm volatile("mov %0, %%dr4"
:
: "r" (Value)
: "memory");
__asm__ volatile("mov %0, %%dr4"
:
: "r" (Value)
: "memory");
case 5:
/* Write value to DR5 */
asm volatile("mov %0, %%dr5"
:
: "r" (Value)
: "memory");
__asm__ volatile("mov %0, %%dr5"
:
: "r" (Value)
: "memory");
case 6:
/* Write value to DR6 */
asm volatile("mov %0, %%dr6"
:
: "r" (Value)
: "memory");
__asm__ volatile("mov %0, %%dr6"
:
: "r" (Value)
: "memory");
case 7:
/* Write value to DR7 */
asm volatile("mov %0, %%dr7"
:
: "r" (Value)
: "memory");
__asm__ volatile("mov %0, %%dr7"
:
: "r" (Value)
: "memory");
}
}
@ -842,10 +842,10 @@ XTCDECL
VOID
ArWriteEflagsRegister(IN UINT_PTR Value)
{
asm volatile("push %0\n"
"popf"
:
: "rim" (Value));
__asm__ volatile("push %0\n"
"popf"
:
: "rim" (Value));
}
/**
@ -866,10 +866,10 @@ VOID
ArWriteModelSpecificRegister(IN ULONG Register,
IN ULONGLONG Value)
{
asm volatile("wrmsr"
:
: "c" (Register),
"A" (Value));
__asm__ volatile("wrmsr"
:
: "c" (Register),
"A" (Value));
}
/**
@ -883,8 +883,8 @@ XTCDECL
VOID
ArYieldProcessor(VOID)
{
asm volatile("pause"
:
:
: "memory");
__asm__ volatile("pause"
:
:
: "memory");
}

View File

@ -147,9 +147,9 @@ ArpIdentifyProcessor(VOID)
*(PULONG)&Prcb->CpuId.VendorName[8] = CpuRegisters.Ecx;
Prcb->CpuId.VendorName[12] = '\0';
/* Get CPU features */
/* Get CPU standard features */
RtlZeroMemory(&CpuRegisters, sizeof(CPUID_REGISTERS));
CpuRegisters.Leaf = CPUID_GET_CPU_FEATURES;
CpuRegisters.Leaf = CPUID_GET_STANDARD1_FEATURES;
ArCpuId(&CpuRegisters);
/* Store CPU signature in processor control block */

View File

@ -265,15 +265,22 @@ XTAPI
XTSTATUS
HlpInitializeAcpiSystemInformation(VOID)
{
PUCHAR MadtTable;
PACPI_MADT_LOCAL_X2APIC LocalX2Apic;
PACPI_MADT_LOCAL_APIC LocalApic;
ULONG_PTR MadtTable;
PACPI_MADT Madt;
XTSTATUS Status;
ULONG CpuCount;
USHORT CpuCount;
/* Zero the ACPI system information structure */
RtlZeroMemory(&HlpAcpiSystemInfo, sizeof(ACPI_SYSTEM_INFO));
/* Allocate memory for ACPI system information structure */
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);
if(Status != STATUS_SUCCESS)
{
@ -282,38 +289,54 @@ HlpInitializeAcpiSystemInformation(VOID)
}
/* Set APIC table traverse pointer and initialize number of CPUs */
MadtTable = (PUCHAR)Madt->ApicTables;
MadtTable = (ULONG_PTR)Madt->ApicTables;
CpuCount = 0;
/* Traverse all MADT tables to get number of processors */
while(MadtTable <= ((PUCHAR)Madt + Madt->Header.Length))
/* Traverse all MADT tables to get system information */
while(MadtTable <= ((ULONG_PTR)Madt + Madt->Header.Length))
{
/* Check if this is a local APIC subtable */
if((((PACPI_MADT_LOCAL_APIC)MadtTable)->Header.Type == ACPI_MADT_TYPE_LOCAL_APIC) &&
(((PACPI_MADT_LOCAL_APIC)MadtTable)->Header.Length == sizeof(ACPI_MADT_LOCAL_APIC)))
if((((PACPI_SUBTABLE_HEADER)MadtTable)->Type == ACPI_MADT_TYPE_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 */
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 */
CpuCount++;
}
/* 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) &&
(((PACPI_MADT_LOCAL_X2APIC)MadtTable)->Header.Length == sizeof(ACPI_MADT_LOCAL_X2APIC)))
else if((((PACPI_SUBTABLE_HEADER)MadtTable)->Type == ACPI_MADT_TYPE_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 */
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 */
CpuCount++;
}
/* Go to the next MADT table */
MadtTable += ((PACPI_MADT_LOCAL_X2APIC)MadtTable)->Header.Length;
MadtTable += ((PACPI_SUBTABLE_HEADER)MadtTable)->Length;
}
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 STATUS_SUCCESS;
}
@ -385,9 +507,13 @@ XTSTATUS
HlpQueryAcpiCache(IN ULONG Signature,
OUT PACPI_DESCRIPTION_HEADER *AcpiTable)
{
PACPI_DESCRIPTION_HEADER TableHeader;
PACPI_CACHE_LIST AcpiCache;
PLIST_ENTRY ListEntry;
/* Initialize variables */
TableHeader = NULL;
/* Iterate through ACPI tables cache list */
ListEntry = HlpAcpiCacheList.Flink;
while(ListEntry != &HlpAcpiCacheList)
@ -399,7 +525,7 @@ HlpQueryAcpiCache(IN ULONG Signature,
if(AcpiCache->Header.Signature == Signature)
{
/* ACPI table found in cache, return it */
*AcpiTable = &AcpiCache->Header;
TableHeader = &AcpiCache->Header;
break;
}
@ -408,13 +534,14 @@ HlpQueryAcpiCache(IN ULONG Signature,
}
/* 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 */
return STATUS_NOT_FOUND;
}
/* Return success */
/* Return table header and status code */
*AcpiTable = TableHeader;
return STATUS_SUCCESS;
}
@ -452,6 +579,9 @@ HlpQueryAcpiTables(IN ULONG Signature,
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 */
if(Signature == ACPI_DSDT_SIGNATURE || Signature == ACPI_FACS_SIGNATURE)
{

View File

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

View File

@ -165,7 +165,6 @@ HlComPortReadLsr(IN PCPPORT Port,
IN UCHAR Byte)
{
UCHAR Lsr, Msr;
STATIC UCHAR RingFlag;
/* Read the Line Status Register (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 */
Msr = HlIoPortInByte(PtrToUshort(Port->Address + (ULONG)COMPORT_REG_MSR));
RingFlag |= (Msr & COMPORT_MSR_RI) ? 1 : 2;
if(RingFlag == 3)
Port->Ring |= (Msr & COMPORT_MSR_RI) ? 1 : 2;
if(Port->Ring == 3)
{
/* Ring indicator toggled, use modem control */
Port->Flags |= COMPORT_FLAG_MC;
@ -277,12 +276,13 @@ HlInitializeComPort(IN OUT PCPPORT Port,
HlIoPortOutByte(PtrToUshort(PortAddress + (ULONG)COMPORT_REG_MCR), COMPORT_MCR_NOM);
/* 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 */
Port->Address = PortAddress;
Port->Baud = BaudRate;
Port->Flags = Flags;
Port->Ring = 0;
/* Return success */
return STATUS_SUCCESS;

View File

@ -4,6 +4,7 @@
* FILE: xtoskrnl/hl/fbdev.c
* DESCRIPTION: FrameBuffer support
* DEVELOPERS: Rafal Kupiec <belliash@codingworkshop.eu.org>
* Aiken Harris <harraiken91@gmail.com>
*/
#include <xtos.h>
@ -24,9 +25,10 @@ XTAPI
VOID
HlClearScreen(IN ULONG Color)
{
SIZE_T Line, PositionX, PositionY;
ULONG PositionX, PositionY;
ULONG BackgroundColor;
PULONG FrameBuf;
PCHAR CurrentLine;
PULONG Pixel;
/* Make sure frame buffer is already initialized */
if(HlpFrameBufferData.Initialized == FALSE)
@ -35,34 +37,102 @@ HlClearScreen(IN ULONG Color)
return;
}
/* Get pointer to frame buffer */
FrameBuf = HlpFrameBufferData.Address;
/* Convert background color */
/* Convert background color and get pointer to frame buffer */
BackgroundColor = HlpRGBColor(Color);
CurrentLine = HlpFrameBufferData.Address;
/* Fill the screen with a black box */
for(PositionY = 0; PositionY < HlpFrameBufferData.Height; PositionY++)
/* Fill the screen with the specified color */
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++)
{
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
* Supplies the X coordinate of the pixel.
* @param Character
* Supplies the character to be displayed.
*
* @param PositionY
* Supplies the Y coordinate of the pixel.
* @return This routine does not return any value.
*
* @param Color
* Specifies the color of the pixel in (A)RGB format.
* @since XT 1.0
*/
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.
*
@ -70,31 +140,10 @@ HlClearScreen(IN ULONG Color)
*/
XTAPI
VOID
HlDrawPixel(IN ULONG PositionX,
IN ULONG PositionY,
IN ULONG Color)
HlGetFrameBufferResolution(OUT PULONG Width, OUT PULONG Height)
{
SIZE_T FrameBufferIndex;
/* 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);
*Width = HlpFrameBufferData.Width;
*Height = HlpFrameBufferData.Height;
}
/**
@ -153,7 +202,7 @@ HlInitializeFrameBuffer(VOID)
HlpFrameBufferData.Address = FrameBufferResource->Header.VirtualAddress;
HlpFrameBufferData.Width = FrameBufferResource->Width;
HlpFrameBufferData.Height = FrameBufferResource->Height;
HlpFrameBufferData.BitsPerPixel = FrameBufferResource->BitsPerPixel;
HlpFrameBufferData.BytesPerPixel = FrameBufferResource->BitsPerPixel / 8;
HlpFrameBufferData.PixelsPerScanLine = FrameBufferResource->PixelsPerScanLine;
HlpFrameBufferData.Pitch = FrameBufferResource->Pitch;
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
* Supplies the X coordinate of the character.
@ -194,10 +317,10 @@ HlInitializeFrameBuffer(VOID)
*/
XTAPI
VOID
HlPutCharacter(IN ULONG PositionX,
IN ULONG PositionY,
IN ULONG Color,
IN WCHAR WideCharacter)
HlpDrawCharacter(IN ULONG PositionX,
IN ULONG PositionY,
IN ULONG Color,
IN WCHAR WideCharacter)
{
UINT CurrentFragment, Glyph, GlyphLimit, Index, Line, Mapping;
PUCHAR Character, CharacterMapping, Fragment;
@ -261,7 +384,8 @@ HlPutCharacter(IN ULONG PositionX,
}
/* 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);
/* Check all kerning fragments */
@ -321,7 +445,7 @@ HlPutCharacter(IN ULONG PositionX,
}
/* Advance pixel pointer */
Pixel += 4;
Pixel += HlpFrameBufferData.BytesPerPixel;
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.
*
@ -361,3 +531,62 @@ HlpRGBColor(IN ULONG Color)
return (ULONG)((Blue << HlpFrameBufferData.Pixels.BlueShift) | (Green << HlpFrameBufferData.Pixels.GreenShift) |
(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) */
PACPI_RSDP HlpAcpiRsdp;
/* ACPI system information */
ACPI_SYSTEM_INFO HlpAcpiSystemInfo;
/* ACPI timer information */
ACPI_TIMER_INFO HlpAcpiTimerInfo;
@ -28,4 +25,10 @@ KAFFINITY HlpActiveProcessors;
APIC_MODE HlpApicMode;
/* 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)
{
UCHAR Value;
asm volatile("inb %1, %0"
: "=a" (Value)
: "Nd" (Port));
__asm__ volatile("inb %1, %0"
: "=a" (Value)
: "Nd" (Port));
return Value;
}
@ -45,9 +45,9 @@ ULONG
HlIoPortInLong(IN USHORT Port)
{
ULONG Value;
asm volatile("inl %1, %0"
: "=a" (Value)
: "Nd" (Port));
__asm__ volatile("inl %1, %0"
: "=a" (Value)
: "Nd" (Port));
return Value;
}
@ -66,9 +66,9 @@ USHORT
HlIoPortInShort(IN USHORT Port)
{
USHORT Value;
asm volatile("inw %1, %0"
: "=a" (Value)
: "Nd" (Port));
__asm__ volatile("inw %1, %0"
: "=a" (Value)
: "Nd" (Port));
return Value;
}
@ -90,10 +90,10 @@ VOID
HlIoPortOutByte(IN USHORT Port,
IN UCHAR Value)
{
asm volatile("outb %0, %1"
:
: "a" (Value),
"Nd" (Port));
__asm__ volatile("outb %0, %1"
:
: "a" (Value),
"Nd" (Port));
}
/**
@ -114,10 +114,10 @@ VOID
HlIoPortOutLong(IN USHORT Port,
IN ULONG Value)
{
asm volatile("outl %0, %1"
:
: "a" (Value),
"Nd" (Port));
__asm__ volatile("outl %0, %1"
:
: "a" (Value),
"Nd" (Port));
}
/**
@ -138,8 +138,8 @@ VOID
HlIoPortOutShort(IN USHORT Port,
IN USHORT Value)
{
asm volatile("outw %0, %1"
:
: "a" (Value),
"Nd" (Port));
__asm__ volatile("outw %0, %1"
:
: "a" (Value),
"Nd" (Port));
}

View File

@ -35,7 +35,7 @@ HlClearApicErrors(VOID)
* @since XT 1.0
*/
XTFASTCALL
ULONG
ULONGLONG
HlReadApicRegister(IN APIC_REGISTER Register)
{
if(HlpApicMode == APIC_MODE_X2APIC)
@ -81,7 +81,7 @@ HlSendEoi(VOID)
XTFASTCALL
VOID
HlWriteApicRegister(IN APIC_REGISTER Register,
IN ULONG Value)
IN ULONGLONG Value)
{
if(HlpApicMode == APIC_MODE_X2APIC)
{
@ -112,7 +112,7 @@ HlpCheckX2ApicSupport(VOID)
CPUID_REGISTERS CpuRegisters;
/* Prepare CPUID registers */
CpuRegisters.Leaf = CPUID_GET_CPU_FEATURES;
CpuRegisters.Leaf = CPUID_GET_STANDARD1_FEATURES;
CpuRegisters.SubLeaf = 0;
CpuRegisters.Eax = 0;
CpuRegisters.Ebx = 0;
@ -133,6 +133,26 @@ HlpCheckX2ApicSupport(VOID)
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.
*
@ -171,24 +191,23 @@ VOID
HlpInitializeApic(VOID)
{
APIC_SPURIOUS_REGISTER SpuriousRegister;
APIC_COMMAND_REGISTER CommandRegister;
APIC_BASE_REGISTER BaseRegister;
APIC_LVT_REGISTER LvtRegister;
ULONG CpuNumber;
/* Check if this is an x2APIC compatible machine */
/* Determine APIC mode (xAPIC compatibility or x2APIC) */
if(HlpCheckX2ApicSupport())
{
/* Enable x2APIC */
/* Enable x2APIC mode */
HlpApicMode = APIC_MODE_X2APIC;
}
else
{
/* Use xAPIC compatibility mode */
/* Fall back to xAPIC compatibility mode */
HlpApicMode = APIC_MODE_COMPAT;
}
/* Get processor number */
/* Get current processor number */
CpuNumber = KeGetCurrentProcessorNumber();
/* Enable the APIC */
@ -198,82 +217,73 @@ HlpInitializeApic(VOID)
BaseRegister.BootStrapProcessor = (CpuNumber == 0) ? 1 : 0;
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);
/* xAPIC compatibility mode specific initialization */
/* Perform initialization specific to xAPIC compatibility mode */
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);
/* 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);
}
/* Set the spurious interrupt vector */
/* Configure the spurious interrupt vector */
SpuriousRegister.Long = HlReadApicRegister(APIC_SIVR);
SpuriousRegister.Vector = APIC_VECTOR_SPURIOUS;
SpuriousRegister.SoftwareEnable = 1;
SpuriousRegister.CoreChecking = 0;
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);
/* Mask TMRLVTR */
/* Program the APIC timer for periodic mode */
LvtRegister.Long = 0;
LvtRegister.Mask = 1;
LvtRegister.MessageType = APIC_DM_FIXED;
LvtRegister.DeliveryMode = APIC_DM_FIXED;
LvtRegister.TimerMode = 1;
LvtRegister.TriggerMode = APIC_TGM_EDGE;
LvtRegister.Vector = APIC_VECTOR_PROFILE;
HlWriteApicRegister(APIC_TMRLVTR, LvtRegister.Long);
/* Mask PCLVTR */
/* Configure the performance counter overflow */
LvtRegister.Long = 0;
LvtRegister.Mask = 0;
LvtRegister.MessageType = APIC_DM_FIXED;
LvtRegister.DeliveryMode = APIC_DM_FIXED;
LvtRegister.TimerMode = 0;
LvtRegister.TriggerMode = APIC_TGM_EDGE;
LvtRegister.Vector = APIC_VECTOR_PERF;
HlWriteApicRegister(APIC_PCLVTR, LvtRegister.Long);
/* Mask LINT0 */
/* Configure the LINT0 pin */
LvtRegister.Long = 0;
LvtRegister.Mask = 1;
LvtRegister.MessageType = APIC_DM_FIXED;
LvtRegister.DeliveryMode = APIC_DM_FIXED;
LvtRegister.TimerMode = 0;
LvtRegister.TriggerMode = APIC_TGM_EDGE;
LvtRegister.Vector = APIC_VECTOR_SPURIOUS;
HlWriteApicRegister(APIC_LINT0, LvtRegister.Long);
/* Mask LINT1 */
/* Configure the LINT1 pin */
LvtRegister.Long = 0;
LvtRegister.Mask = 0;
LvtRegister.MessageType = APIC_DM_NMI;
LvtRegister.DeliveryMode = APIC_DM_NMI;
LvtRegister.TimerMode = 0;
LvtRegister.TriggerMode = APIC_TGM_EDGE;
LvtRegister.Vector = APIC_VECTOR_NMI;
HlWriteApicRegister(APIC_LINT1, LvtRegister.Long);
/* Mask ICR0 */
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 */
/* Register interrupt handlers */
KeSetInterruptHandler(APIC_VECTOR_SPURIOUS, HlpHandleApicSpuriousService);
KeSetInterruptHandler(PIC1_VECTOR_SPURIOUS, HlpHandlePicSpuriousService);
/* Clear errors after enabling vectors */
/* Clear any pre-existing errors */
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);
}
@ -371,3 +381,35 @@ HlpInitializePic(VOID)
/* Initialize legacy PIC */
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

@ -10,6 +10,21 @@
#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 */
#define TrapXmm0 0
#define TrapXmm1 16

View File

@ -30,4 +30,10 @@ EXTERN UCHAR ArKernelBootStack[KERNEL_STACK_SIZE];
/* Kernel own fault stack */
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 */

View File

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

View File

@ -13,17 +13,33 @@
/* AMD64 Memory Manager routines forward references */
XTAPI
VOID
MmInitializePageMapSupport(VOID);
XTFASTCALL
VOID
MmZeroPages(IN PVOID Address,
IN ULONG Size);
XTAPI
PMMPTE
VOID
MmpClearPte(PHARDWARE_PTE PtePointer);
XTAPI
BOOLEAN
MmpGetExtendedPhysicalAddressingStatus(VOID);
XTAPI
PMMP5E
MmpGetP5eAddress(PVOID Address);
XTAPI
PMMPDE
MmpGetPdeAddress(PVOID Address);
XTAPI
PMMPTE
PMMPPE
MmpGetPpeAddress(PVOID Address);
XTAPI
@ -31,7 +47,7 @@ PMMPTE
MmpGetPteAddress(PVOID Address);
XTAPI
PMMPTE
PMMPXE
MmpGetPxeAddress(PVOID Address);
XTAPI
@ -40,6 +56,18 @@ MmpInitializeArchitecture(VOID);
XTAPI
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 */

View File

@ -18,9 +18,6 @@ EXTERN LIST_ENTRY HlpAcpiCacheList;
/* ACPI Root System Description Pointer (RSDP) */
EXTERN PACPI_RSDP HlpAcpiRsdp;
/* ACPI system information */
EXTERN ACPI_SYSTEM_INFO HlpAcpiSystemInfo;
/* ACPI timer information */
EXTERN ACPI_TIMER_INFO HlpAcpiTimerInfo;
@ -31,10 +28,32 @@ EXTERN KAFFINITY HlpActiveProcessors;
EXTERN APIC_MODE HlpApicMode;
/* FrameBuffer information */
EXTERN HAL_FRAMEBUFFER_DATA HlpFrameBufferData;
EXTERN HL_FRAMEBUFFER_DATA HlpFrameBufferData;
/* Scroll region information */
EXTERN HL_SCROLL_REGION_DATA HlpScrollRegionData;
/* System information */
EXTERN ACPI_SYSTEM_INFO HlpSystemInfo;
/* Pointer to DbgPrint() routine */
EXTERN PKD_PRINT_ROUTINE KdPrint;
/* Kernel Debugger mode */
EXTERN KD_DEBUG_MODE KdpDebugMode;
/* Debugger I/O providers initialization routines */
EXTERN PKD_INIT_ROUTINE KdpIoProvidersInitRoutines[KDBG_PROVIDERS_COUNT];
/* List of active I/O providers */
EXTERN LIST_ENTRY KdpProviders;
/* Debugger's serial port handle */
EXTERN CPPORT KdpSerialPort;
/* Pre-defined serial port addresses */
EXTERN ULONG KdpSerialPortList[COMPORT_COUNT];
/* Pointer to boot loader provided DbgPrint() routine */
EXTERN VOID (*KeDbgPrint)(IN PWCHAR Format, IN ...);
/* Kernel initialization block passed by boot loader */
EXTERN PKERNEL_INITIALIZATION_BLOCK KeInitializationBlock;
@ -75,9 +94,6 @@ EXTERN ULONG MmNumberOfPhysicalPages;
/* Old biggest free memory descriptor */
EXTERN LOADER_MEMORY_DESCRIPTOR MmOldFreeDescriptor;
/* Page Map Level */
EXTERN ULONG MmPageMapLevel;
/* Processor structures data (THIS IS A TEMPORARY HACK) */
EXTERN UCHAR MmProcessorStructuresData[MAXIMUM_PROCESSORS][KPROCESSOR_STRUCTURES_SIZE];
@ -87,8 +103,11 @@ EXTERN LOADER_MEMORY_DESCRIPTOR MmpHardwareAllocationDescriptors[MM_HARDWARE_ALL
/* Live address of kernel's hardware heap */
EXTERN PVOID MmpHardwareHeapStart;
/* Architecture-specific memory extension */
EXTERN BOOLEAN MmpMemoryExtension;
/* Information about the current page map */
EXTERN MMPAGEMAP_INFO MmpPageMapInfo;
/* Pointers to page map routines for the current paging mode */
EXTERN PCMMPAGEMAP_ROUTINES MmpPageMapRoutines;
/* Number of used hardware allocation descriptors */
EXTERN ULONG MmpUsedHardwareAllocationDescriptors;

View File

@ -34,11 +34,9 @@ UCHAR
HlComPortReadLsr(IN PCPPORT Port,
IN UCHAR Byte);
XTAPI
VOID
HlDrawPixel(IN ULONG PosX,
IN ULONG PosY,
IN ULONG Color);
XTCDECL
XTSTATUS
HlDisplayCharacter(IN WCHAR Character);
XTAPI
XTSTATUS
@ -49,6 +47,10 @@ XTSTATUS
HlGetAcpiTable(IN ULONG Signature,
OUT PACPI_DESCRIPTION_HEADER *AcpiTable);
XTAPI
VOID
HlGetFrameBufferResolution(OUT PULONG Width, OUT PULONG Height);
XTFASTCALL
KRUNLEVEL
HlGetRunLevel(VOID);
@ -68,15 +70,16 @@ VOID
HlInitializeProcessor(VOID);
XTAPI
XTSTATUS
HlInitializeSystem(VOID);
VOID
HlInitializeScrollRegion(IN ULONG Left,
IN ULONG Top,
IN ULONG Right,
IN ULONG Bottom,
IN ULONG FontColor);
XTAPI
VOID
HlPutCharacter(IN ULONG PositionX,
IN ULONG PositionY,
IN ULONG Color,
IN WCHAR WideCharacter);
XTSTATUS
HlInitializeSystem(VOID);
XTFASTCALL
VOID
@ -86,6 +89,19 @@ XTAPI
VOID
HlpCacheAcpiTable(IN PACPI_DESCRIPTION_HEADER AcpiTable);
XTAPI
VOID
HlpDrawCharacter(IN ULONG PositionX,
IN ULONG PositionY,
IN ULONG Color,
IN WCHAR WideCharacter);
XTAPI
VOID
HlpDrawPixel(IN ULONG PosX,
IN ULONG PosY,
IN ULONG Color);
XTAPI
XTSTATUS
HlpInitializeAcpi(VOID);
@ -102,6 +118,10 @@ XTAPI
XTSTATUS
HlpInitializeAcpiSystemInformation(VOID);
XTAPI
XTSTATUS
HlpInitializeAcpiSystemStructure(VOID);
XTAPI
XTSTATUS
HlpInitializeAcpiTimer(VOID);
@ -120,6 +140,10 @@ XTAPI
ULONG
HlpRGBColor(IN ULONG Color);
XTAPI
VOID
HlpScrollRegion(VOID);
XTAPI
BOOLEAN
HlpValidateAcpiTable(IN PVOID Buffer,

View File

@ -34,4 +34,10 @@ EXTERN UCHAR ArKernelBootStack[KERNEL_STACK_SIZE];
/* Kernel own fault stack */
EXTERN UCHAR ArKernelFaultStack[KERNEL_STACK_SIZE];
/* Page mapping routines for systems using 2-level paging (PML2) */
EXTERN CMMPAGEMAP_ROUTINES MmpPml2Routines;
/* Page mapping routines for systems using 3-level paging (PML3) */
EXTERN CMMPAGEMAP_ROUTINES MmpPml3Routines;
#endif /* __XTOSKRNL_I686_GLOBALS_H */

View File

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

View File

@ -13,15 +13,31 @@
/* i686 Memory Manager routines forward references */
XTAPI
VOID
MmInitializePageMapSupport(VOID);
XTFASTCALL
VOID
MmZeroPages(IN PVOID Address,
IN ULONG Size);
XTAPI
PMMPTE
VOID
MmpClearPte(PHARDWARE_PTE PtePointer);
XTAPI
BOOLEAN
MmpGetExtendedPhysicalAddressingStatus(VOID);
XTAPI
PMMPDE
MmpGetPdeAddress(PVOID Address);
XTAPI
PMMPPE
MmpGetPpeAddress(PVOID Address);
XTAPI
PMMPTE
MmpGetPteAddress(PVOID Address);
@ -32,6 +48,34 @@ MmpInitializeArchitecture(VOID);
XTAPI
BOOLEAN
MmpMemoryExtensionEnabled(VOID);
MmpPml2PteValid(PHARDWARE_PTE PtePointer);
XTAPI
VOID
MmpSetPml2Pte(PHARDWARE_PTE PtePointer,
PFN_NUMBER PageFrameNumber,
BOOLEAN Writable);
XTAPI
VOID
MmpSetPml2PteCaching(PHARDWARE_PTE PtePointer,
BOOLEAN CacheDisable,
BOOLEAN WriteThrough);
XTAPI
BOOLEAN
MmpPml3PteValid(PHARDWARE_PTE PtePointer);
XTAPI
VOID
MmpSetPml3Pte(PHARDWARE_PTE PtePointer,
PFN_NUMBER PageFrameNumber,
BOOLEAN Writable);
XTAPI
VOID
MmpSetPml3PteCaching(PHARDWARE_PTE PtePointer,
BOOLEAN CacheDisable,
BOOLEAN WriteThrough);
#endif /* __XTOSKRNL_I686_MMI_H */

44
xtoskrnl/includes/kdi.h Normal file
View File

@ -0,0 +1,44 @@
/**
* PROJECT: ExectOS
* COPYRIGHT: See COPYING.md in the top level directory
* FILE: xtoskrnl/includes/kdi.h
* DESCRIPTION: Kernel Debugger routines
* DEVELOPERS: Aiken Harris <harraiken91@gmail.com>
*/
#ifndef __XTOSKRNL_KDI_H
#define __XTOSKRNL_KDI_H
#include <xtos.h>
/* Kernel Debugger routines forward references */
XTAPI
XTSTATUS
KdInitializeDebugIoProviders(VOID);
XTAPI
VOID
KdSetPrintRoutine(PVOID DebugPrintRoutine);
XTCDECL
VOID
KdpDebugPrint(PCWSTR Format, ...);
XTAPI
XTSTATUS
KdpDetectDebugPorts(VOID);
XTAPI
XTSTATUS
KdpInitializeFrameBufferProvider(VOID);
XTAPI
XTSTATUS
KdpInitializeSerialPortProvider(VOID);
XTCDECL
XTSTATUS
KdpSerialWriteCharacter(WCHAR Character);
#endif /* __XTOSKRNL_KDI_H */

View File

@ -21,6 +21,15 @@ XTAPI
VOID
KeClearTimer(IN PKTIMER Timer);
XTAPI
SYSTEM_FIRMWARE_TYPE
KeGetFirmwareType(VOID);
XTAPI
XTSTATUS
KeGetKernelParameter(IN PCWSTR ParameterName,
OUT PCWSTR *Parameter);
XTAPI
VOID
KeHaltSystem(VOID);

View File

@ -17,7 +17,7 @@ XTAPI
XTSTATUS
MmAllocateHardwareMemory(IN PFN_NUMBER PageCount,
IN BOOLEAN Aligned,
OUT PULONG_PTR Buffer);
OUT PPHYSICAL_ADDRESS Buffer);
XTAPI
XTSTATUS

View File

@ -15,6 +15,7 @@
/* Kernel specific headers */
#include "globals.h"
#include "hli.h"
#include "kdi.h"
#include "kei.h"
#include "mmi.h"
#include "poi.h"

192
xtoskrnl/kd/dbginit.c Normal file
View File

@ -0,0 +1,192 @@
/**
* PROJECT: ExectOS
* COPYRIGHT: See COPYING.md in the top level directory
* FILE: xtoskrnl/kd/dbginit.c
* DESCRIPTION: Kernel Debugger initialization
* DEVELOPERS: Aiken Harris <harraiken91@gmail.com>
*/
#include <xtos.h>
/**
* Initializes the kernel's debugger I/O providers.
*
* @return This routine returns a status code.
*
* @since XT 1.0
*/
XTAPI
XTSTATUS
KdInitializeDebugIoProviders(VOID)
{
ULONG Index;
XTSTATUS ProviderStatus, Status;
/* Initialize debug providers list */
RtlInitializeListHead(&KdpProviders);
RtlZeroMemory(&KdpDebugMode, sizeof(KD_DEBUG_MODE));
KdpDetectDebugPorts();
/* Iterate over providers initialization routines */
for(Index = 0; Index < KDBG_PROVIDERS_COUNT; Index++)
{
/* Initialize provider */
ProviderStatus = KdpIoProvidersInitRoutines[Index]();
Status = (Status || ProviderStatus);
}
/* Initialize debug print routine */
KdSetPrintRoutine(KdpDebugPrint);
/* Return status code */
return Status;
}
/**
* Configures the kernel's debug print routine by setting a new output handler.
*
* @param DebugPrintRoutine
* Supplies a pointer to the new debug print routine.
*
* @return This routine does not return any value.
*
* @since XT 1.0
*/
XTAPI
VOID
KdSetPrintRoutine(PVOID DebugPrintRoutine)
{
/* Set debug print routine */
KdPrint = DebugPrintRoutine;
}
/**
* Detects and enables the kernel's debug ports based on the 'DEBUG' parameter passed to the kernel.
*
* @return This routine returns a status code.
*
* @since XT 1.0
*/
XTAPI
XTSTATUS
KdpDetectDebugPorts(VOID)
{
PCWSTR DebugOption;
XTSTATUS Status;
/* Get debug parameter */
Status = KeGetKernelParameter(L"DEBUG", &DebugOption);
if(Status != STATUS_SUCCESS)
{
/* Debug parameter not found, disable debugging */
KdpDebugMode.Enabled = FALSE;
return Status;
}
/* Skip parameter name and check if it is set */
DebugOption += 5;
if(*DebugOption != L'=')
{
/* Debug parameter not set, disable debugging */
KdpDebugMode.Enabled = FALSE;
return STATUS_INVALID_PARAMETER;
}
/* Skip '=' symbol */
DebugOption++;
/* Iterate over all debug ports */
while(*DebugOption != L'\0' && *DebugOption != L' ')
{
/* Check what port is set for debugging */
if(RtlCompareWideStringInsensitive(DebugOption, L"COM", 3) == 0)
{
/* Enable serial port debugging mode */
KdpDebugMode.Mode |= DEBUG_PROVIDER_COMPORT;
/* Read COM port number */
DebugOption += 3;
while(*DebugOption >= '0' && *DebugOption <= '9')
{
/* Get port number */
KdpDebugMode.ComPortNumber *= 10;
KdpDebugMode.ComPortNumber += *DebugOption - '0';
DebugOption++;
}
/* Check if custom COM port address supplied */
if(KdpDebugMode.ComPortNumber == 0 && RtlCompareWideStringInsensitive(DebugOption, L":0x", 3) == 0)
{
/* COM port address provided */
DebugOption += 3;
while((*DebugOption >= '0' && *DebugOption <= '9') ||
(*DebugOption >= 'A' && *DebugOption <= 'F') ||
(*DebugOption >= 'a' && *DebugOption <= 'f'))
{
/* Get port address */
KdpDebugMode.ComPortAddress *= 16;
if(*DebugOption >= '0' && *DebugOption <= '9')
{
KdpDebugMode.ComPortAddress += *DebugOption - '0';
}
else if(*DebugOption >= 'A' && *DebugOption <= 'F')
{
KdpDebugMode.ComPortAddress += *DebugOption - 'A' + 10;
}
else if(*DebugOption >= 'a' && *DebugOption <= 'f')
{
KdpDebugMode.ComPortAddress += *DebugOption - 'a' + 10;
}
DebugOption++;
}
}
/* Look for additional COM port parameters */
if(*DebugOption == ',')
{
/* Baud rate provided */
DebugOption++;
while(*DebugOption >= '0' && *DebugOption <= '9')
{
/* Get baud rate */
KdpDebugMode.ComPortBaudRate *= 10;
KdpDebugMode.ComPortBaudRate += *DebugOption - '0';
DebugOption++;
}
}
}
else if(RtlCompareWideStringInsensitive(DebugOption, L"SCREEN", 6) == 0)
{
/* Enable framebuffer debugging mode */
KdpDebugMode.Mode |= DEBUG_PROVIDER_FRAMEBUFFER;
DebugOption += 6;
}
else if(*DebugOption == L';')
{
/* Skip separator */
DebugOption++;
}
else
{
/* Invalid debug option, skip it */
while(*DebugOption != L'\0' && *DebugOption != L' ' && *DebugOption != L';')
{
/* Advance debug option */
DebugOption++;
}
}
}
/* Ensure at least one debug port is enabled */
if(KdpDebugMode.Mode != 0)
{
/* Enable debugging */
KdpDebugMode.Enabled = TRUE;
}
/* Return success */
return STATUS_SUCCESS;
}

175
xtoskrnl/kd/dbgio.c Normal file
View File

@ -0,0 +1,175 @@
/**
* PROJECT: ExectOS
* COPYRIGHT: See COPYING.md in the top level directory
* FILE: xtoskrnl/kd/dbgio.c
* DESCRIPTION: Kernel Debugger I/O routines
* DEVELOPERS: Aiken Harris <harraiken91@gmail.com>
*/
#include <xtos.h>
/**
* Prints a formatted string using the configured debug output providers.
*
* @param Format
* Supplies the format string.
*
* @param ...
* Supplies the variable argument list.
*
* @return This routine does not return any value.
*
* @since XT 1.0
*/
XTCDECL
VOID
KdpDebugPrint(PCWSTR Format, ...)
{
VA_LIST Arguments;
PLIST_ENTRY DispatchTableEntry;
PKD_DISPATCH_TABLE DispatchTable;
/* Initialise the va_list */
VA_START(Arguments, Format);
DispatchTableEntry = KdpProviders.Flink;
while(DispatchTableEntry != &KdpProviders)
{
DispatchTable = CONTAIN_RECORD(DispatchTableEntry, KD_DISPATCH_TABLE, ListEntry);
RtlFormatWideString(&DispatchTable->PrintContext, (PWCHAR)Format, Arguments);
DispatchTableEntry = DispatchTableEntry->Flink;
}
/* Clean up the va_list */
VA_END(Arguments);
}
/**
* Initializes the framebuffer device provider for the kernel debugger.
*
* @return This routine returns a status code.
*
* @since XT 1.0
*/
XTAPI
XTSTATUS
KdpInitializeFrameBufferProvider(VOID)
{
STATIC KD_DISPATCH_TABLE DispatchTable;
ULONG Height, Width;
/* Check if framebuffer provider is enabled */
if(KdpDebugMode.Enabled && (KdpDebugMode.Mode & DEBUG_PROVIDER_FRAMEBUFFER) == 0)
{
/* Screen is not enabled, no need to initialize provider */
return STATUS_PORT_DISCONNECTED;
}
/* Ensure frame buffer is initialized and get FB resolution */
HlInitializeFrameBuffer();
HlGetFrameBufferResolution(&Width, &Height);
/* Print debug message */
DebugPrint(L"Initializing debug console at framebuffer device (%lu x %lu)\n", Width, Height);
/* Initialize scroll region to full screen and white font color */
HlInitializeScrollRegion(0, 0, Width - 1, Height - 1, 0xFFFFFFFF);
/* Initialize screen dispatch table */
DispatchTable.PrintContext.WriteWideCharacter = HlDisplayCharacter;
RtlInsertHeadList(&KdpProviders, &DispatchTable.ListEntry);
/* Return success */
return STATUS_SUCCESS;
}
/**
* Initializes the serial port device provider for the kernel debugger.
*
* @return This routine returns a status code.
*
* @since XT 1.0
*/
XTAPI
XTSTATUS
KdpInitializeSerialPortProvider(VOID)
{
STATIC KD_DISPATCH_TABLE DispatchTable;
XTSTATUS Status;
/* Check if serial port provider is enabled */
if(KdpDebugMode.Enabled && (KdpDebugMode.Mode & DEBUG_PROVIDER_COMPORT) == 0)
{
/* Serial port is not enabled, no need to initialize provider */
return STATUS_PORT_DISCONNECTED;
}
/* Check if custom COM port address supplied */
if(!KdpDebugMode.ComPortAddress)
{
/* We support only a pre-defined number of ports */
if(KdpDebugMode.ComPortNumber > COMPORT_COUNT)
{
/* Fail if wrong/unsupported port used */
return STATUS_INVALID_PARAMETER;
}
/* Check if serial port is set */
if(KdpDebugMode.ComPortNumber == 0)
{
/* Use COM1 by default */
KdpDebugMode.ComPortNumber = 1;
}
/* Set custom port address based on the port number and print debug message */
KdpDebugMode.ComPortAddress = KdpSerialPortList[KdpDebugMode.ComPortNumber - 1];
DebugPrint(L"Initializing debug console at serial port (COM%lu, BaudRate: %lu)\n",
KdpDebugMode.ComPortNumber, KdpDebugMode.ComPortBaudRate);
}
else
{
/* Custom port address supplied, print debug message */
DebugPrint(L"Initializing debug console at serial port (0x%lX, BaudRate: %lu)\n",
KdpDebugMode.ComPortAddress, KdpDebugMode.ComPortBaudRate);
}
/* Initialize COM port */
Status = HlInitializeComPort(&KdpSerialPort, UlongToPtr(KdpDebugMode.ComPortAddress), KdpDebugMode.ComPortBaudRate);
if(Status != STATUS_SUCCESS)
{
/* Serial port initialization failed */
return Status;
}
/* Initialize serial port dispatch table */
DispatchTable.PrintContext.WriteWideCharacter = KdpSerialWriteCharacter;
RtlInsertHeadList(&KdpProviders, &DispatchTable.ListEntry);
/* Return success */
return STATUS_SUCCESS;
}
/**
* Writes a character to the serial console.
*
* @param Character
* The integer promotion of the character to be written.
*
* @return This routine returns a status code.
*
* @since XT 1.0
*/
XTCDECL
XTSTATUS
KdpSerialWriteCharacter(WCHAR Character)
{
WCHAR Buffer[2];
/* Write character to the serial console */
Buffer[0] = Character;
Buffer[1] = 0;
return HlComPortPutByte(&KdpSerialPort, Buffer[0]);
}

31
xtoskrnl/kd/globals.c Normal file
View File

@ -0,0 +1,31 @@
/**
* PROJECT: ExectOS
* COPYRIGHT: See COPYING.md in the top level directory
* FILE: xtoskrnl/kd/globals.c
* DESCRIPTION: Architecture independent global variables related to KD subsystem
* DEVELOPERS: Aiken Harris <harraiken91@gmail.com>
*/
#include <xtos.h>
/* Pointer to DbgPrint() routine */
PKD_PRINT_ROUTINE KdPrint = NULL;
/* Kernel Debugger mode */
KD_DEBUG_MODE KdpDebugMode;
/* Debugger I/O providers initialization routines */
PKD_INIT_ROUTINE KdpIoProvidersInitRoutines[KDBG_PROVIDERS_COUNT] = {
KdpInitializeFrameBufferProvider,
KdpInitializeSerialPortProvider
};
/* List of active I/O providers */
LIST_ENTRY KdpProviders;
/* Debugger's serial port handle */
CPPORT KdpSerialPort;
/* Pre-defined serial port addresses */
ULONG KdpSerialPortList[COMPORT_COUNT] = COMPORT_ADDRESS;

View File

@ -52,6 +52,9 @@ KepInitializeMachine(VOID)
/* Initialize processor */
HlInitializeProcessor();
/* Initialize page map support */
MmInitializePageMapSupport();
}
/**
@ -93,7 +96,7 @@ KepStartKernel(VOID)
RtlInitializeListHead(&KepProcessListHead);
PageDirectory[0] = 0;
PageDirectory[1] = 0;
KeInitializeProcess(CurrentProcess, 0, 0xFFFFFFFF, PageDirectory, FALSE);
KeInitializeProcess(CurrentProcess, 0, MAXULONG_PTR, PageDirectory, FALSE);
CurrentProcess->Quantum = MAXCHAR;
/* Initialize Idle thread */
@ -122,13 +125,13 @@ VOID
KepSwitchBootStack(IN ULONG_PTR Stack)
{
/* Discard old stack frame, switch stack and jump to KepStartKernel() */
asm volatile("mov %0, %%rdx\n"
"xor %%rbp, %%rbp\n"
"mov %%rdx, %%rsp\n"
"sub %1, %%rsp\n"
"jmp KepStartKernel\n"
:
: "m" (Stack),
"i" (FLOATING_SAVE_AREA_SIZE | KEXCEPTION_FRAME_SIZE | KSWITCH_FRAME_SIZE | KRETURN_ADDRESS_SIZE),
"p" (KepStartKernel));
__asm__ volatile("mov %0, %%rdx\n"
"xor %%rbp, %%rbp\n"
"mov %%rdx, %%rsp\n"
"sub %1, %%rsp\n"
"jmp KepStartKernel\n"
:
: "m" (Stack),
"i" (FLOATING_SAVE_AREA_SIZE | KEXCEPTION_FRAME_SIZE | KSWITCH_FRAME_SIZE | KRETURN_ADDRESS_SIZE),
"p" (KepStartKernel));
}

View File

@ -10,7 +10,7 @@
/* Pointer to boot loader provided DbgPrint() routine */
VOID (*KeDbgPrint)(IN PWCHAR Format, IN ...) = NULL;
VOID (*KeDbgPrint)(IN PCWSTR Format, IN ...) = NULL;
/* Kernel initialization block passed by boot loader */
PKERNEL_INITIALIZATION_BLOCK KeInitializationBlock;

View File

@ -52,6 +52,9 @@ KepInitializeMachine(VOID)
/* Initialize processor */
HlInitializeProcessor();
/* Initialize page map support */
MmInitializePageMapSupport();
}
/**
@ -93,7 +96,7 @@ KepStartKernel(VOID)
RtlInitializeListHead(&KepProcessListHead);
PageDirectory[0] = 0;
PageDirectory[1] = 0;
KeInitializeProcess(CurrentProcess, 0, 0xFFFFFFFF, PageDirectory, FALSE);
KeInitializeProcess(CurrentProcess, 0, MAXULONG_PTR, PageDirectory, FALSE);
CurrentProcess->Quantum = MAXCHAR;
/* Initialize Idle thread */
@ -122,15 +125,15 @@ VOID
KepSwitchBootStack(IN ULONG_PTR Stack)
{
/* Discard old stack frame, switch stack, make space for NPX and jump to KepStartKernel() */
asm volatile("mov %0, %%edx\n"
"xor %%ebp, %%ebp\n"
"mov %%edx, %%esp\n"
"sub %1, %%esp\n"
"push %2\n"
"jmp _KepStartKernel@0\n"
:
: "m" (Stack),
"i" (KTRAP_FRAME_ALIGN | KTRAP_FRAME_SIZE | NPX_FRAME_SIZE | KRETURN_ADDRESS_SIZE),
"i" (CR0_EM | CR0_MP | CR0_TS),
"p" (KepStartKernel));
__asm__ volatile("mov %0, %%edx\n"
"xor %%ebp, %%ebp\n"
"mov %%edx, %%esp\n"
"sub %1, %%esp\n"
"push %2\n"
"jmp _KepStartKernel@0\n"
:
: "m" (Stack),
"i" (KTRAP_FRAME_ALIGN | KTRAP_FRAME_SIZE | NPX_FRAME_SIZE | KRETURN_ADDRESS_SIZE),
"i" (CR0_EM | CR0_MP | CR0_TS),
"p" (KepStartKernel));
}

94
xtoskrnl/ke/info.c Normal file
View File

@ -0,0 +1,94 @@
/**
* PROJECT: ExectOS
* COPYRIGHT: See COPYING.md in the top level directory
* FILE: xtoskrnl/ke/info.c
* DESCRIPTION: Generic kernel information support
* DEVELOPERS: Aiken Harris <harraiken91@gmail.com>
*/
#include <xtos.h>
/**
* Retrieves the system firmware type (BIOS or UEFI).
*
* @return This routine returns the type of the system firmware.
*
* @since XT 1.0
*/
XTAPI
SYSTEM_FIRMWARE_TYPE
KeGetFirmwareType(VOID)
{
return KeInitializationBlock->FirmwareInformation.FirmwareType;
}
/**
* Retrieves a pointer to the specified kernel parameter within the kernel parameters list.
*
* @param ParameterName
* Supplies a pointer to a null-terminated wide string specifying the name of the parameter to search for.
*
* @param Parameter
* Supplies a pointer to a variable that receives a pointer to the matching parameter, or NULL if not found.
*
* @return This routine returns a status code.
*
* @since XT 1.0
*/
XTAPI
XTSTATUS
KeGetKernelParameter(IN PCWSTR ParameterName,
OUT PCWSTR *Parameter)
{
PCWSTR KernelParameters,Match, SearchStart;
SIZE_T ParameterNameLength;
/* Get the kernel parameters */
KernelParameters = KeInitializationBlock->KernelParameters;
/* Validate input parameters */
if(!KernelParameters || !ParameterName || !Parameter)
{
/* Invalid input parameters, return error */
return STATUS_INVALID_PARAMETER;
}
/* Get the length of the parameter name we are looking for */
ParameterNameLength = RtlWideStringLength(ParameterName, 0);
if(ParameterNameLength == 0)
{
/* Do not allow empty parameter names */
return STATUS_INVALID_PARAMETER;
}
/* Assume the requested parameter is not present in the kernel parameters */
*Parameter = NULL;
/* Start searching from the beginning of the list */
SearchStart = KernelParameters;
/* Search for the parameter name */
while((Match = RtlFindWideStringInsensitive(SearchStart, ParameterName)))
{
/* Check if the match is at the start of the string or preceded by a space */
if(Match == KernelParameters || *(Match - 1) == L' ')
{
/* Check the character after the match to avoid matching prefixes */
if(Match[ParameterNameLength] == L'\0' ||
Match[ParameterNameLength] == L' ' ||
Match[ParameterNameLength] == L'=')
{
/* A valid parameter was found, return a pointer to it */
*Parameter = Match;
return STATUS_SUCCESS;
}
}
/* The match was a substring of a larger token, continue searching */
SearchStart = Match + 1;
}
/* Parameter not found */
return STATUS_NOT_FOUND;
}

View File

@ -39,7 +39,21 @@ KeStartXtSystem(IN PKERNEL_INITIALIZATION_BLOCK Parameters)
if(DEBUG && KeInitializationBlock->LoaderInformation.DbgPrint)
{
/* Use loader's provided DbgPrint() routine for early printing to serial console */
KeDbgPrint = KeInitializationBlock->LoaderInformation.DbgPrint;
KdSetPrintRoutine(KeInitializationBlock->LoaderInformation.DbgPrint);
DebugPrint(L"Initializing ExectOS v%d.%d for %s\n", XTOS_VERSION_MAJOR, XTOS_VERSION_MINOR, _ARCH_NAME);
}
/* Initialize boot CPU */
ArInitializeProcessor(NULL);
/* Initialize system resources */
KepInitializeSystemResources();
/* Check if debugging enabled */
if(DEBUG)
{
/* Initialize debug I/O */
KdInitializeDebugIoProviders();
}
/* Announce kernel startup */
@ -48,18 +62,12 @@ KeStartXtSystem(IN PKERNEL_INITIALIZATION_BLOCK Parameters)
XTOS_VERSION_BUILD, XTOS_VERSION_ARCH, XTOS_VERSION_HASH,
XTOS_COMPILER_NAME, XTOS_COMPILER_VERSION);
/* Initialize boot CPU */
ArInitializeProcessor(NULL);
/* Initialize system resources */
KepInitializeSystemResources();
/* Architecture specific kernel initialization */
KepInitializeMachine();
/* Raise to HIGH runlevel */
KeRaiseRunLevel(HIGH_LEVEL);
/* Switch boot stack aligning it to 4 byte boundary */
KepSwitchBootStack((ULONG_PTR)&ArKernelBootStack & ~0x3);
/* Switch the boot stack, setting the pointer to the top of the buffer and aligning it as required by the ABI */
KepSwitchBootStack(((ULONG_PTR)&ArKernelBootStack + KERNEL_STACK_SIZE) & ~(STACK_ALIGNMENT - 1));
}

View File

@ -1035,13 +1035,13 @@ VOID
__ubsan_handle_type_mismatch_v1(IN PKUBSAN_TYPE_MISMATCH_DATA_V1 Data,
IN ULONG_PTR Pointer)
{
KUBSAN_TYPE_MISMATCH_DATA MismatchData;
/* Prepare UBSAN type mismatch data in old format */
KUBSAN_TYPE_MISMATCH_DATA MismatchData = {
.Location = Data->Location,
.Type = Data->Type,
.Alignment = 1UL << Data->LogAlignment,
.TypeCheckKind = Data->TypeCheckKind,
};
MismatchData.Alignment = 1UL << Data->LogAlignment;
MismatchData.Location = Data->Location;
MismatchData.Type = Data->Type;
MismatchData.TypeCheckKind = Data->TypeCheckKind;
/* Call UBSAN type mismatch handler */
KepHandleUbsanTypeMismatch(&MismatchData, Pointer);

View File

@ -76,6 +76,6 @@ KePanicEx(IN ULONG Code,
IN ULONG_PTR Parameter3,
IN ULONG_PTR Parameter4)
{
KeDbgPrint(L"Fatal System Error: 0x%08lx\nKernel Panic!\n\n", Code);
KdPrint(L"Fatal System Error: 0x%08lx\nKernel Panic!\n\n", Code);
KeHaltSystem();
}

View File

@ -0,0 +1,26 @@
/**
* PROJECT: ExectOS
* COPYRIGHT: See COPYING.md in the top level directory
* FILE: xtoskrnl/mm/amd64/globals.c
* DESCRIPTION: AMD64-specific global variables for the Memory Manager
* DEVELOPERS: Aiken Harris <harraiken91@gmail.com>
*/
#include <xtos.h>
/* Page mapping routines for systems using 4-level paging (PML4) */
CMMPAGEMAP_ROUTINES MmpPml4Routines = {
.ClearPte = MmpClearPte,
.PteValid = MmpPteValid,
.SetPteCaching = MmpSetPteCaching,
.SetPte = MmpSetPte,
};
/* Page mapping routines for systems using 5-level paging (PML5) */
CMMPAGEMAP_ROUTINES MmpPml5Routines = {
.ClearPte = MmpClearPte,
.PteValid = MmpPteValid,
.SetPteCaching = MmpSetPteCaching,
.SetPte = MmpSetPte,
};

View File

@ -4,89 +4,60 @@
* FILE: xtoskrnl/mm/amd64/init.c
* DESCRIPTION: Architecture specific Memory Manager initialization routines
* DEVELOPERS: Rafal Kupiec <belliash@codingworkshop.eu.org>
* Aiken Harris <harraiken91@gmail.com>
*/
#include <xtos.h>
/**
* Gets the address of the PDE (Page Directory Entry), that maps given address.
* Detects if eXtended Physical Addressing (XPA) is enabled and initializes page map support.
*
* @param Address
* Specifies the address to find the PDE for.
*
* @return This routine returns the address of the PDE.
* @return This routine does not return any value.
*
* @since XT 1.0
*/
XTAPI
PMMPTE
MmpGetPdeAddress(PVOID Address)
VOID
MmInitializePageMapSupport(VOID)
{
ULONGLONG Offset;
/* Check if XPA is enabled */
if(MmpGetExtendedPhysicalAddressingStatus())
{
/* XPA enabled, use LA57 paging (PML5) */
MmpPageMapRoutines = &MmpPml5Routines;
Offset = ((((ULONGLONG)Address & (((ULONGLONG)1 << 48) - 1)) >> MM_PDI_SHIFT) << MM_PTE_SHIFT);
return (PMMPTE)(MM_PDE_BASE + Offset);
}
/* Set PML5 page map information */
MmpPageMapInfo.Xpa = TRUE;
/**
* Gets the address of the PPE (Page Directory Pointer Table Entry), that maps given address.
*
* @param Address
* Specifies the address to find the PPE for.
*
* @return This routine returns the address of the PPE.
*
* @since XT 1.0
*/
XTAPI
PMMPTE
MmpGetPpeAddress(PVOID Address)
{
ULONGLONG Offset;
/* Set PML5 base addresses */
MmpPageMapInfo.PteBase = MM_PTE_LA57_BASE;
MmpPageMapInfo.PdeBase = MM_PDE_LA57_BASE;
MmpPageMapInfo.PpeBase = MM_PPE_LA57_BASE;
MmpPageMapInfo.PxeBase = MM_PXE_LA57_BASE;
MmpPageMapInfo.P5eBase = MM_P5E_LA57_BASE;
Offset = ((((ULONGLONG)Address & (((ULONGLONG)1 << 48) - 1)) >> MM_PPI_SHIFT) << MM_PTE_SHIFT);
return (PMMPTE)(MM_PPE_BASE + Offset);
}
/* PML5 use 57-bit virtual addresses */
MmpPageMapInfo.VaBits = 57;
}
else
{
/* XPA disabled, use LA48 paging (PML4) */
MmpPageMapRoutines = &MmpPml4Routines;
/**
* Gets the address of the PTE (Page Table Entry), that maps given address.
*
* @param Address
* Specifies the address to find the PTE for.
*
* @return This routine returns the address of the PTE.
*
* @since XT 1.0
*/
XTAPI
PMMPTE
MmpGetPteAddress(PVOID Address)
{
ULONGLONG Offset;
/* Set PML4 page map information */
MmpPageMapInfo.Xpa = FALSE;
Offset = ((((ULONGLONG)Address & (((ULONGLONG)1 << 48) - 1)) >> MM_PTI_SHIFT) << MM_PTE_SHIFT);
return (PMMPTE)(MM_PTE_BASE + Offset);
}
/* Set PML4 base addresses */
MmpPageMapInfo.PteBase = MM_PTE_BASE;
MmpPageMapInfo.PdeBase = MM_PDE_BASE;
MmpPageMapInfo.PpeBase = MM_PPE_BASE;
MmpPageMapInfo.PxeBase = MM_PXE_BASE;
MmpPageMapInfo.P5eBase = 0x0;
/**
* Gets the address of the PXE (Extended Page Entry), that maps given address.
*
* @param Address
* Specifies the address to find the PXE for.
*
* @return This routine returns the address of the PXE.
*
* @since XT 1.0
*/
XTAPI
PMMPTE
MmpGetPxeAddress(PVOID Address)
{
ULONGLONG Offset;
Offset = (((ULONGLONG)Address >> MM_PXI_SHIFT) & (MM_PXE_PER_PAGE - 1));
return (PMMPTE)(MM_PXE_BASE + Offset);
/* PML use 48-bit virtual addresses */
MmpPageMapInfo.VaBits = 48;
}
}
/**
@ -102,18 +73,3 @@ MmpInitializeArchitecture(VOID)
{
UNIMPLEMENTED;
}
/**
* Checks if LA57 (PML5) is enabled.
*
* @return This routine returns TRUE if LA57 is enabled, or FALSE otherwise.
*
* @since XT 1.0
*/
XTAPI
BOOLEAN
MmpMemoryExtensionEnabled(VOID)
{
/* Check if LA57 (PML5) is enabled */
return ((ArReadControlRegister(4) & CR4_LA57) != 0) ? TRUE : FALSE;
}

View File

@ -27,16 +27,16 @@ VOID
MmZeroPages(IN PVOID Address,
IN ULONG Size)
{
asm volatile("xor %%rax, %%rax\n"
"mov %0, %%rdi\n"
"mov %1, %%ecx\n"
"shr $3, %%ecx\n"
"rep stosq\n"
:
: "m" (Address),
"m" (Size)
: "rax",
"rdi",
"ecx",
"memory");
__asm__ volatile("xor %%rax, %%rax\n"
"mov %0, %%rdi\n"
"mov %1, %%ecx\n"
"shr $3, %%ecx\n"
"rep stosq\n"
:
: "m" (Address),
"m" (Size)
: "rax",
"rdi",
"ecx",
"memory");
}

216
xtoskrnl/mm/amd64/pmap.c Normal file
View File

@ -0,0 +1,216 @@
/**
* PROJECT: ExectOS
* COPYRIGHT: See COPYING.md in the top level directory
* FILE: xtoskrnl/mm/amd64/pmap.c
* DESCRIPTION: Low-level support for AMD64 page map manipulation
* DEVELOPERS: Aiken Harris <harraiken91@gmail.com>
*/
#include <xtos.h>
/**
* Clears the contents of a page table entry (PTE).
*
* @param PtePointer
* Pointer to the page table entry (PTE) to be cleared.
*
* @return This routine does not return any value.
*
* @since XT 1.0
*/
XTAPI
VOID
MmpClearPte(PHARDWARE_PTE PtePointer)
{
PtePointer->CacheDisable = 0;
PtePointer->PageFrameNumber = 0;
PtePointer->Valid = 0;
PtePointer->Writable = 0;
PtePointer->WriteThrough = 0;
}
/**
* Checks if eXtended Physical Addressing (XPA) is enabled.
*
* @return This routine returns TRUE if LA57 is enabled, or FALSE otherwise.
*
* @since XT 1.0
*/
XTAPI
BOOLEAN
MmpGetExtendedPhysicalAddressingStatus(VOID)
{
/* Check if LA57 is enabled */
return ((ArReadControlRegister(4) & CR4_LA57) != 0) ? TRUE : FALSE;
}
/**
* Gets the address of the P5E (Page Map Level 5 Entry), that maps given address.
*
* @param Address
* Specifies the virtual address for which to retrieve the corresponding P5E.
*
* @return This routine returns the address of the P5E, or NULL if LA57 is not enabled.
*
* @since XT 1.0
*/
XTAPI
PMMP5E
MmpGetP5eAddress(PVOID Address)
{
ULONGLONG Offset;
Offset = ((((ULONGLONG)Address & (((ULONGLONG)1 << MmpPageMapInfo.VaBits) - 1)) >> MM_P5I_SHIFT) << MM_PTE_SHIFT);
return (PMMP5E)((MmpPageMapInfo.P5eBase + Offset) * MmpPageMapInfo.Xpa);
}
/**
* Gets the address of the PDE (Page Directory Entry), that maps given address.
*
* @param Address
* Specifies the virtual address for which to retrieve the corresponding PDE.
*
* @return This routine returns the address of the PDE.
*
* @since XT 1.0
*/
XTAPI
PMMPDE
MmpGetPdeAddress(PVOID Address)
{
ULONGLONG Offset;
Offset = ((((ULONGLONG)Address & (((ULONGLONG)1 << MmpPageMapInfo.VaBits) - 1)) >> MM_PDI_SHIFT) << MM_PTE_SHIFT);
return (PMMPDE)(MmpPageMapInfo.PdeBase + Offset);
}
/**
* Gets the address of the PPE (Page Directory Pointer Table Entry), that maps given address.
*
* @param Address
* Specifies the virtual address for which to retrieve the corresponding PPE.
*
* @return This routine returns the address of the PPE.
*
* @since XT 1.0
*/
XTAPI
PMMPPE
MmpGetPpeAddress(PVOID Address)
{
ULONGLONG Offset;
Offset = ((((ULONGLONG)Address & (((ULONGLONG)1 << MmpPageMapInfo.VaBits) - 1)) >> MM_PPI_SHIFT) << MM_PTE_SHIFT);
return (PMMPPE)(MmpPageMapInfo.PpeBase + Offset);
}
/**
* Gets the address of the PTE (Page Table Entry), that maps given address.
*
* @param Address
* Specifies the virtual address for which to retrieve the corresponding PTE.
*
* @return This routine returns the address of the PTE.
*
* @since XT 1.0
*/
XTAPI
PMMPTE
MmpGetPteAddress(PVOID Address)
{
ULONGLONG Offset;
Offset = ((((ULONGLONG)Address & (((ULONGLONG)1 << MmpPageMapInfo.VaBits) - 1)) >> MM_PTI_SHIFT) << MM_PTE_SHIFT);
return (PMMPTE)(MmpPageMapInfo.PteBase + Offset);
}
/**
* Gets the address of the PXE (Extended Page Entry), that maps given address.
*
* @param Address
* Specifies the virtual address for which to retrieve the corresponding PXE.
*
* @return This routine returns the address of the PXE.
*
* @since XT 1.0
*/
XTAPI
PMMPXE
MmpGetPxeAddress(PVOID Address)
{
ULONGLONG Offset;
Offset = ((((ULONGLONG)Address & (((ULONGLONG)1 << MmpPageMapInfo.VaBits) - 1)) >> MM_PXI_SHIFT) << MM_PTE_SHIFT);
return (PMMPXE)(MmpPageMapInfo.PxeBase + Offset);
}
/**
* Checks whether the given page table entry (PTE) is valid.
*
* @param PtePointer
* Pointer to the page table entry (PTE) to check.
*
* @return Returns TRUE if the entry is valid, FALSE otherwise.
*
* @since XT 1.0
*/
XTAPI
BOOLEAN
MmpPteValid(PHARDWARE_PTE PtePointer)
{
return (BOOLEAN)PtePointer->Valid;
}
/**
* Sets a page table entry (PTE) with the specified physical page and access flags.
*
* @param PtePointer
* Pointer to the page table entry (PTE) to set.
*
* @param PageFrameNumber
* Physical frame number to map.
*
* @param Writable
* Indicates whether the page should be writable.
*
* @return This routine does not return any value.
*
* @since XT 1.0
*/
XTAPI
VOID
MmpSetPte(PHARDWARE_PTE PtePointer,
PFN_NUMBER PageFrameNumber,
BOOLEAN Writable)
{
PtePointer->PageFrameNumber = PageFrameNumber;
PtePointer->Valid = 1;
PtePointer->Writable = Writable;
}
/**
* Sets caching attributes for a page table entry (PTE).
*
* @param PtePointer
* Pointer to the page table entry (PTE) to modify.
*
* @param CacheDisable
* Indicates whether caching should be disabled for this page.
*
* @param WriteThrough
* Indicates whether write-through caching should be enabled.
*
* @return This routine does not return any value.
*
* @since XT 1.0
*/
XTAPI
VOID
MmpSetPteCaching(PHARDWARE_PTE PtePointer,
BOOLEAN CacheDisable,
BOOLEAN WriteThrough)
{
PtePointer->CacheDisable = CacheDisable;
PtePointer->WriteThrough = WriteThrough;
}

View File

@ -24,9 +24,6 @@ ULONG MmNumberOfPhysicalPages;
/* Old biggest free memory descriptor */
LOADER_MEMORY_DESCRIPTOR MmOldFreeDescriptor;
/* Page Map Level */
ULONG MmPageMapLevel;
/* Processor structures data (THIS IS A TEMPORARY HACK) */
UCHAR MmProcessorStructuresData[MAXIMUM_PROCESSORS][KPROCESSOR_STRUCTURES_SIZE] = {0};
@ -36,8 +33,11 @@ LOADER_MEMORY_DESCRIPTOR MmpHardwareAllocationDescriptors[MM_HARDWARE_ALLOCATION
/* Live address of kernel's hardware heap */
PVOID MmpHardwareHeapStart = MM_HARDWARE_HEAP_START_ADDRESS;
/* Architecture-specific memory extension */
BOOLEAN MmpMemoryExtension;
/* Information about the current page map */
MMPAGEMAP_INFO MmpPageMapInfo;
/* Pointers to page map routines for the current paging mode */
PCMMPAGEMAP_ROUTINES MmpPageMapRoutines;
/* Number of used hardware allocation descriptors */
ULONG MmpUsedHardwareAllocationDescriptors = 0;

View File

@ -29,7 +29,7 @@ XTAPI
XTSTATUS
MmAllocateHardwareMemory(IN PFN_NUMBER PageCount,
IN BOOLEAN Aligned,
OUT PULONG_PTR Buffer)
OUT PPHYSICAL_ADDRESS Buffer)
{
PLOADER_MEMORY_DESCRIPTOR Descriptor, ExtraDescriptor, HardwareDescriptor;
PFN_NUMBER Alignment, MaxPage;
@ -37,7 +37,7 @@ MmAllocateHardwareMemory(IN PFN_NUMBER PageCount,
PLIST_ENTRY ListEntry;
/* Assume failure */
*Buffer = 0;
(*Buffer).QuadPart = 0;
/* Calculate maximum page address */
MaxPage = MM_MAXIMUM_PHYSICAL_ADDRESS >> MM_PAGE_SHIFT;
@ -135,7 +135,7 @@ MmAllocateHardwareMemory(IN PFN_NUMBER PageCount,
}
/* Return physical address */
*Buffer = PhysicalAddress;
(*Buffer).QuadPart = PhysicalAddress;
return STATUS_SUCCESS;
}
@ -190,7 +190,7 @@ MmMapHardwareMemory(IN PHYSICAL_ADDRESS PhysicalAddress,
ReturnAddress = (PVOID)(ULONG_PTR)ReturnAddress + MM_PAGE_SIZE;
/* Check if PTE is valid */
if(PtePointer->Valid)
if(MmpPageMapRoutines->PteValid(PtePointer))
{
/* PTE is not available, go to the next one */
BaseAddress = ReturnAddress;
@ -219,9 +219,7 @@ MmMapHardwareMemory(IN PHYSICAL_ADDRESS PhysicalAddress,
PtePointer = (PHARDWARE_PTE)MmpGetPteAddress(BaseAddress);
/* Fill the PTE */
PtePointer->PageFrameNumber = (PFN_NUMBER)(PhysicalAddress.QuadPart >> MM_PAGE_SHIFT);
PtePointer->Valid = 1;
PtePointer->Writable = 1;
MmpPageMapRoutines->SetPte(PtePointer, (PFN_NUMBER)(PhysicalAddress.QuadPart >> MM_PAGE_SHIFT), TRUE);
/* Advance to the next address */
PhysicalAddress.QuadPart += MM_PAGE_SIZE;
@ -268,8 +266,7 @@ MmMarkHardwareMemoryWriteThrough(IN PVOID VirtualAddress,
for(Page = 0; Page < PageCount; Page++)
{
/* Mark pages as CD/WT */
PtePointer->CacheDisable = 1;
PtePointer->WriteThrough = 1;
MmpPageMapRoutines->SetPteCaching(PtePointer, TRUE, TRUE);
PtePointer++;
}
}
@ -302,9 +299,7 @@ MmRemapHardwareMemory(IN PVOID VirtualAddress,
PtePointer = (PHARDWARE_PTE)MmpGetPteAddress(VirtualAddress);
/* Remap the PTE */
PtePointer->PageFrameNumber = (PFN_NUMBER)(PhysicalAddress.QuadPart >> MM_PAGE_SHIFT);
PtePointer->Valid = 1;
PtePointer->Writable = 1;
MmpPageMapRoutines->SetPte(PtePointer, (PFN_NUMBER)(PhysicalAddress.QuadPart >> MM_PAGE_SHIFT), TRUE);
/* Check if TLB needs to be flushed */
if(FlushTlb)
@ -356,11 +351,7 @@ MmUnmapHardwareMemory(IN PVOID VirtualAddress,
for(Page = 0; Page < PageCount; Page++)
{
/* Unmap the PTE and get the next one */
PtePointer->CacheDisable = 0;
PtePointer->Valid = 0;
PtePointer->Writable = 0;
PtePointer->WriteThrough = 0;
PtePointer->PageFrameNumber = 0;
MmpPageMapRoutines->ClearPte(PtePointer);
PtePointer++;
}

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