operating-systemx86-16microprocessorsopcode

How OS code gets executed by microprocessor when microprocessor have limited set if instructions / opcodes


I've been trying to understand and did lot of online research but still have doubt:

If processor understands only opcodes (which are limited) then why is it possible to execute operating system code? For example, multitasking, scheduling, for them, there is some module / code in the operating system. If those "codes" aren't "made" by opcodes which a processor understand, then who understands the code (non opcode / "non-standard" code), that is, which is not within the "opcode list" of the processor.


Solution

  • Operating system only uses opcodes that the processor understands. All OS code is made from legal CPU opcodes.

    Modern OSes do require some specific operations to be built into the CPU. For example, to run Linux, the CPU must have at least 2 privilege modes (and opcodes to switch them) and support virtual memory (and opcodes to configure it). If the CPU does not have those opcodes - a modern OS cannot run on such CPU. That's why there is no Linux on Zilog Z80.

    Modern CPUs have some opcodes that only OS can use. Those are usually the opcodes that allow user programs to "break away" from OS rule. When the processor encounters one such opcode - it checks if the current code belongs to OS (how it is done - depends on the CPU). If it does not - the CPU will not perform the action, but will "snitch" to the OS instead. Note: those OS-only opcodes are still built into the CPU! It's just the CPU has additional conditions to check before it runs them.

    Multitasking and scheduling is mostly done with normal opcodes - with only few OS-only opcodes sprinkled in. For example, multitasking on a single core looks like this:

    1. The current program is interrupted to run OS code. This uses CPU's interrupt mechanism and a timer device.
    2. Current state of the program is saved into memory. This is done completely with normal opcodes - you just save all registers that program have access to.
    3. The next program to run is selected. Done with normal opcodes - you just read a list of processes and decide the next according to some rule or point system.
    4. Virtual memory map is switched. Uses OS-only opcodes.
    5. The state of the next program is restored from memory. Normal opcodes.
    6. Jump back to program. OS-only opcode to tell the CPU to switch off OS privilege mode.