I am trying to understand how the physical addresses are allocated when running an OS.
Physical addresses are not allocated, they're already there – it's the RAM.
My question is when the kernel allocates some memory (lets say using kmalloc), who decides what physical memory address range should be mapped for this virtual memory range?
Who: the kernel memory mapping algorithm. So, the kernel.
But before that, someone should allocate/assign some physical pages to be mapped.
As said, the physical memory is the reality that the kernel has to deal with.
The question of how the memory chips are mapped to form a piece-wise contiguous memory range depends on your hardware and its boot process. In desktop or server x86, typically, as you initialize the DRAM controller during boot, firmware (or your bootloader) reads the contents of the DRAM memory modules ("DIMMs") "configuration EEPROM"s and configures the memory controller of your CPU (or the mainboard, depending on the specifics of your hardware) to translate memory address accesses to read and writes for these chips accordingly. On embedded platforms, the RAM configuration might just be baked into the software (e.g., uboot and the Linux kernel initializing hardware using devicetree) and then the memory controller gets configured that way.
So, there's no universal answer here. "How to deal with dynamic memory" is one of the main things that architectures differ in – and that can get pretty detailed and CPU-model-specific, if you remember PAE on i386.
who decides what physical memory address range should be mapped for this virtual memory range?
Let's talk about how: since the kernel, through hardware or firmware interfaces, or through configuration files, knows how much physical memory is where in the physical address space, where the memory mapped IO is, and what memory it's already using, it is able to keep a data structure tracking free physical memory. So, when you call kmalloc
with a specific size, you look for an unused piece of physical memory that fits the size requirement.