I am trying to make an operating system in C. I've looked it up many times, but couldn't find the answer. How do I check how much RAM a computer has (total, not free or used) in MB. I used a tutorial from CodePulse Here is the file structure if anyone cares: fs
-
The machine's firmware will tell you. If you are using the legacy boot firmware, aka BIOS, look at service 0xE820. If you are using the later firmware, UEFI, look at the gBS->GetMemoryMap call. – fysnet Feb 25 '22 at 23:56
-
"a computer" could be a lot of things... from something like ZX Sepctrum to regular PCs to plenty of other configurations. Consider to [edit] question with that, plus add information on what level you want to "check" - i.e. original PC would scan memory on POST to know how much it is there... – Alexei Levenkov Feb 26 '22 at 00:06
1 Answers
It is quite complex I would say. I'm currently working on a hobby x64 operating-system and I would tend to say that the tutorial you are looking at isn't the best out there. If I were you I'd switch to learning how the bootloader works instead of relying on GRUB and multiboot. Have a look at How do I jump from my own bootloader to my own kernel? which shows a complete legacy bootloader working with the BIOS to load a minimal C kernel. Also, have a look at How does a modern operating system work and how to make one from scratch? to have info on what this kind of bootloader will teach you and how it will improve your knowledge to be able to understand basic things about how x86-64 computers work.
To answer your question taking example on Linux, modern operating-systems don't ask the BIOS for the amount of RAM installed neither UEFI firmware. They either parse the SMBIOS table (which is often not even present) or they, reliably, parse the ACPI tables that have some tables like the DSDT (see https://wiki.osdev.org/DSDT). Parsing this AML encoded ACPI table will allow to detect all the computer's peripherals including the RAM controller and how much actual RAM you have in total.
It is certain that big portions of RAM isn't accessible. For example, if the DSDT tells there is 8GB of RAM installed, you can't rely on that and blindly use all of it in your OS. You need to ask the UEFI firmware (or the legacy BIOS) for a memory map of RAM to determine what is usable RAM and what isn't. Most of the memory map portions can be reclaimed after exiting the firmware interface. For example, the UEFI code and data can be reclaimed to use it because you don't rely on UEFI anymore. Also, most of the memory map can be retrieved by using other techniques such as reading the MCFG and determining where the different PCI configuration spaces are and parsing ACPI to determine where are the different ACPI tables that you should not touch because you will need them during execution of your OS.

- 2,510
- 2
- 6
- 20