BASIC-DOS manages all memory, on every processor, through a built-in driver, CPU$, which is also the only part of BASIC-DOS that knows about descriptors, selectors, and physical memory. CPU$ loads first and determines the processor type, and on a processor that can use protected mode, it manages a table of physical memory blocks covering conventional and extended memory, along with the GDT, the IDT, and the LDTs that sessions use (see The CPU$ Drivers).
On an 80286 or later, unless real mode is requested (by a CPU=8088 line in CONFIG.SYS, or R at the boot message), BASIC-DOS switches to protected mode while its drivers initialize, and stays there (see Protected-Mode Initialization): CPU$, the drivers, and the kernel run at ring 0, and COMMAND.COM, its BASIC programs, and the programs it runs run at ring 3, with each console’s sessions’ memory in an LDT of their own (see Running Programs at Ring 3), and DOS allocates memory from anywhere in conventional or extended memory. Otherwise, as on an 8086 or 8088, the same binaries run in real mode, BASIC-DOS’s most compatible mode, where CPU$ manages memory with a chain of MCBs, as DOS always has, and uses no extra memory (see Mode-Independent Code).
Every demo runs in protected mode on a PC AT, and on a COMPAQ DeskPro 386 with the 80386’s features, except Wolfenstein 3D, an MZ EXE file; the Extended Memory demos also give DOS extended memory to allocate. What doesn’t work in protected mode yet (most notably, MZ EXE files) is listed under Limitations.
Protected mode needs an 80286 or later, at least 256K of conventional memory (after any MEMSIZE= line), and A20 control through the 8042 keyboard controller, as on a PC AT; otherwise (or when real mode is requested; see CPU), BASIC-DOS runs in real mode. Extended memory is a bonus: it adds to the memory that DOS can allocate.
Protected mode is built and tested for the IBM PC AT (80286, with IBM’s revision 3 BIOS), typically with 2Mb of memory: 640K of conventional memory and 1408K of extended memory. On an 80386, CPU$ also uses some of the 80386’s features (see The CPU$ Drivers), which are tested on a COMPAQ DeskPro 386 with 2Mb. Protected mode is the default on those machines, so every demo that boots on one runs in protected mode, except Wolfenstein 3D, whose diskette has a CPU=8088 line, and tools/tests/mmutest.sh runs the protected-mode tests on six machines: a PC XT, a PC AT in real mode, and a PC AT and a DeskPro 386 in protected mode, each both with RING=0 and without it.
BASDEV.COM starts with two CPU$ drivers, of which exactly one stays loaded: the 80386 driver (which also supports the 80286), followed by the 8086 driver. The 80386 driver, which is initialized first, determines the processor type:
It stores the result in CPU_HWTYPE (0:513h) and CPU_TYPE (0:512h), as one of the CPUTYPE_* values in cpu.inc (0 = 8086/8088, 1 = 80186/80188, 2 = 80286, 3 = 80386 or later). A request for real mode (a CPU=8088 line in CONFIG.SYS, which P at the boot message overrides, or R at the boot message), or less than 256K of conventional memory (after any MEMSIZE= line, which the 80386 driver applies by lowering the BIOS’s memory size), makes CPU$ store 0 in CPU_TYPE and act as it does on an 8088, without enabling A20, and so does any later reason not to stay (no A20 control, or a failed test of protected mode); CPU_HWTYPE is still the processor’s own type, for software that must know how the processor runs instructions (eg, DEBUG.COM’s disassembler).
CPU=80286 line, and stores 3 in CPU_TYPE (otherwise, 2): an 80386 TSS (with an I/O permission bitmap that allows no ports, so every I/O instruction at ring 3 still faults, except a V86 machine’s use of the video ports; see V86 Machines), selectors that can cover more than 64K (see CPU_SETLIM), and paging. Either way, an 80386 returns to real mode by clearing PE.Neither can be skipped (devinit ignores SKIP=CPU$), and whichever stays is at 0970h. It provides its functions through DDINT_CPU (0050:0030h), a far jump in low memory like the other DDINT entry points, which fails (with carry set) until CPU$ initializes. It also provides DDINT_GETVEC and DDINT_SETVEC (see Device Drivers), which read and write the real-mode vector table, or in protected mode, CPU$’s IDT.
Call DDINT_CPU with a function number in AH. Physical addresses and lengths are 32-bit byte values: addresses in DX:CX and lengths in SI:DI (high:low). Every function runs with interrupts disabled, preserves BX, SI, DI, BP, DS, and ES, and returns carry clear on success, or carry set with an error code in AX.
| AH | Function | Inputs | Outputs |
|---|---|---|---|
| 00h | CPU_GETINFO | AL = CPU type, AH = CPUF_* flags (bits 6-7 = CPU_HWTYPE), DX:CX = length of largest free block | |
| 01h | CPU_ALLOC | AL = MEMF_* flags, BX = owner (see Owner IDs), SI:DI = length | AX = first selector (0 if MEMF_NONE), DX:CX = address |
| 02h | CPU_FREE | DX:CX = block | |
| 03h | CPU_MAP | AL = MEMF_* flags, DX:CX = address, SI:DI = length (with MEMF_REMAP, BX = selector ID) | AX = first selector, CX = number of selectors, and with MEMF_LDT, DX = the selector’s ID (see Selector IDs) |
| 04h | CPU_UNMAP | BX = first selector, CX = number of selectors (0 = 1), or BX = selector ID | |
| 05h | CPU_QUERY | BX = PMB number (0 = first), or -1 for block DX:CX; ES:DI -> 32-byte buffer | PMB copied to ES:DI |
| 06h | CPU_ALIAS | AL = MEMF_* flags, BX = selector | AX = new selector, DX:CX = base address |
| 07h | CPU_PMODE | (none) | Protected mode, for good: CS, DS, ES, and SS are now selectors for the same memory, and AX = a data selector for the caller’s CS (see Protected-Mode Initialization) |
| 08h | CPU_REALLOC | DX:CX = block, SI:DI = new length | |
| 09h | CPU_MOVE | ES:BX -> MOVEPKT (source address, destination address, and length, all dwords) | |
| 0Ah | CPU_SETBLK | DX:CX = block, AL = MCBTYPE_*, BX = owner (non-zero), ES:SI -> 8-character name (SI = 0 for none) | |
| 0Bh | CPU_FREEALL | BX = owner (see Owner IDs) | |
| 0Ch | CPU_SETLIM | BX = selector, SI:DI = new length (1 to 64K, or on an 80386, any non-zero length) | |
| 0Dh | CPU_SEGINFO | AL = ADDR_* flags, BX = selector (or segment) | DX:CX = base address, AX = limit (or with ADDR_RIGHTS, AL = access rights, AH = extended byte) |
| 0Eh | CPU_RWMEM | AL = ADDR_* flags, BX:SI = address, CX = length, ES:DI -> buffer | |
| 0Fh | CPU_SYSREGS | ES:DI -> 16-byte buffer | GDTR, IDTR, and a V86 machine’s interrupt return address (offset, selector) stored at ES:DI; AX = MSW, CX = LDTR, DX = TR |
| 10h | CPU_SETFAULT | DX:CX = fault handler (0:0 for none) | DX:CX = previous handler |
| 11h | CPU_SETSTACK | DX:CX = ring 0 stack (SS:SP) | DX:CX = previous ring 0 stack |
| 12h | CPU_SETLDT | AL = LDT number | |
| 13h | CPU_V86 | AL = 0: BX = owner, SI:DI = length, DX = video memory’s selector (or 0); AL = 1: BX = machine, ES:DI -> V86REGS; AL = 2 or 3: ES:DI -> V86REGS; AL = 4 or 5: BX = machine, CX = first port, DX = # of ports | AL = 0: AX = machine (its memory’s first selector), DX = its video memory’s segment (or 0); AL = 1: AL = V86X_* exit; AL = 2: the last machine’s registers stored at ES:DI; AL = 3: its registers set from ES:DI; AL = 4: the ports lent to the machine; AL = 5: taken back (see V86 Machines) |
Every function works the same way in either driver and in either mode, so callers needn’t check which is which: in real mode, CPU_ALLOC, CPU_MAP, and CPU_ALIAS return the memory’s segment instead of a selector (CPU_ALLOC returns 0 for a block above 1Mb, and CPU_MAP needs memory below 1Mb that’s paragraph-aligned), a segment is its own alias, and CPU_UNMAP has nothing to do. Errors are ERR_INVALID (eg, a bad function, a zero length, or a selector that isn’t in use), ERR_NOMEMORY (no block big enough, with DX:CX = the length of the largest free block; or no free PMB or descriptors), and ERR_BADADDR (a block that CPU_ALLOC didn’t return).
CPU_GETINFO’s flags are CPUF_PM (01h), set when the processor is in protected mode, CPUF_PMOK (02h), set when the 80386 driver stayed (so CPU_PMODE is available), and CPUF_HWTYPE (C0h), the processor’s own type (CPU_HWTYPE), which AL (CPU_TYPE) understates in real mode.
DDINT_CPU is the entry point in either mode, since a far call through segment 50h has the same address in protected mode (see Mode-Independent Code), and it doesn’t use up an interrupt vector. In protected mode, segment 50h is a DPL 0 code segment, so only ring 0 code (the drivers, the kernel, and programs run with RING=0) can call CPU$; programs at ring 3 use DOS functions instead (eg, DOS_MEM_ALLOC, DOS_UTL_ALIAS, and DOS_UTL_MAPSEG).
Physical memory on a 2Mb PC AT:
| Address | Length | PMB type | Contents |
|---|---|---|---|
| 000000h | 1K | USED | Real-mode interrupt vector table |
| 000400h | 256 | USED | ROM BIOS data area (segment 40h) |
| 000500h | 1136 | USED | BASIC-DOS low memory (also segment 40h, from offset 100h): CPU_TYPE (512h), CPU_HWTYPE (513h), CPU_ARENA (514h), the diskette parameter table (522h), the DDINT entry points (530h, called through segment 50h, starting with DDINT_CPU at 0050:0030h), and two disk buffers |
| 000970h | USED | Drivers: CPU$ (first), NUL, VKD$, …, then BASDOS.COM and its tables | |
| FREE | The rest of conventional memory, except for: | ||
| 08E000h | 8K | SYS | On an 80386, the page directory and a page table for every 4Mb (see Paging), in the same block as: |
| 090000h | 64K | SYS | CPU$ system area (see below) |
| 0A0000h | 384K | RSVD | Video memory, adapter ROMs, and the system ROM (not RAM) |
| 100000h | 1408K | FREE | Extended memory, if any |
| 260000h | End of memory |
On a COMPAQ 80386 machine (eg, a DeskPro 386), the part of its first 1Mb of RAM that isn’t conventional memory (eg, 384K) ends at 16Mb. The ROM BIOS keeps the last 128K (FE0000h), where it copies the ROMs, and describes the rest (COMPAQ Built-in Memory; eg, 256K at FA0000h) with a table in segment F000h, at the offset in F000:FFE0h: unless its first word is FFFFh, its third word is the number of free paragraphs, and its fourth is the paragraph (in F0000h) where they end. CPU$ adds that memory as one more FREE block (with an RSVD block for the addresses between it and extended memory), usable in protected mode like extended memory, and on an 80386, it then needs page tables for all 16Mb (16K more). It leaves the table alone, since nothing that reads it (eg, COMPAQ’s CEMM) runs on BASIC-DOS, and the ROM BIOS rebuilds it on every reset.
The PMB types (PMBTYPE_* in cpu.inc) are FREE (0), USED (1, allocated by CPU_ALLOC), SYS (2), and RSVD (3). The end of conventional memory comes from the BIOS, so a machine with less than 640K (or a MEMSIZE= line) has a larger RSVD block.
CPU$ keeps its data in the last whole 64K of conventional memory (090000h-09FFFFh, with 640K), which is addressable in real mode with a segment (9000h, with 640K), and in protected mode with a selector for the same memory (see Paging), so the same offsets work in both modes:
| Offset | Contents |
|---|---|
| 0000h | Unused (except by the protected-mode test) |
| 0020h | CPU$’s variables |
| 00E0h | GDT: 256 descriptors (the fixed ones first) |
| 08E0h | The protected-mode IDT (256 gates; see Protected-Mode Interrupts) |
| 10E0h | TSS (104 bytes: 80386 format on an 80386, otherwise 80286 format), only for its ring 0 stack |
| 114Eh | PMB table (32 bytes per entry), growing up, and below A0DEh, LDTs, growing down (see Table Growth) |
| A0E0h | GDT: identity selectors A000h-F800h, every 800h (see below), through offset F8E7h |
A PSP’s CALL 5 uses PSP_FCSEG, which in protected mode is SEL_CALL5, a DPL 3 call gate to the far jump at 0:00C0h (a far call through a gate ignores its offset, so PSP_SIZE keeps the value that CP/M programs read as their memory size).
On an 80386 (unless CONFIG.SYS has CPU=80286), protected mode also turns on paging, and maps all of physical memory (the first 4Mb for every page table) at linear address C0000000h, which leaves the lower linear addresses free for other mappings (eg, for V86 machines). The page directory and the page tables are just below the system area, and every page is user-accessible, since segment limits are what protect memory.
Every selector’s base is C0000000h plus the physical address it maps, so selectors for any memory (eg, the identity selectors for video memory and the ROMs) work as before, and the CPU$ functions still take and return physical addresses: CPU_SEGINFO and CPU_ALIAS subtract C0000000h from a base, and DEBUG.COM at ring 3, which reads descriptors directly, uses only bits 0-23 of a base. CPU$ builds the tables during its initialization, and adds C0000000h to the bases of the descriptors that it made until then, after the protected-mode test (which doesn’t use paging); CPU_PMODE then turns on paging along with protected mode, while the low linear addresses still map physical memory, and as soon as every register uses the new mapping, removes the low mapping, so any code that uses a physical address as a linear address faults.
The PMB table and the LDTs share the 36,752 bytes between the TSS and the identity selectors. The PMB table starts at the bottom and is only as long as the blocks it describes, and the LDTs are packed down from the top, with LDT 0 first. Each LDT starts empty, and grows 32 descriptors at a time, up to 256 (all that fits in an owner ID). Moving an LDT doesn’t change any selectors, since they’re indexes. Allocating fails with ERR_NOMEMORY only when the PMB table and the LDTs would meet, or an LDT has all 256 descriptors. An LDT keeps its largest size until the system restarts.
So that long tables don’t delay interrupts, the CPU$ functions that walk or change them (CPU_GETINFO, CPU_ALLOC, CPU_FREE, CPU_MAP, CPU_QUERY, CPU_ALIAS, CPU_REALLOC, CPU_SETBLK, and CPU_FREEALL) run with interrupts on if the caller had them on, holding a session lock (through DDINT_UTIL), so no other session can call CPU$ until they’re done. Interrupts are off only while moving a piece of the PMB table (64 words at a time), while copying a piece of a block that CPU_REALLOC moves (1K at a time), and while moving the active LDT and reloading the LDTR, which is never more than 1K words. Interrupt handlers must not call those functions.
| Selector | Base | Use |
|---|---|---|
| 00h | Null selector | |
| 08h | System area | Data: the system area (so offsets match its real-mode segment) |
| 10h | The active LDT | |
| 18h | 000970h | Code: CPU$ |
| 20h | 000000h | Data: the first 64K (interrupt vectors, BIOS data, BASIC-DOS low memory) |
| 28h | Data: the caller’s stack, while switching modes | |
| 30h, 48h | Data: scratch | |
| 38h | Call gate (DPL 0) to CPU$’s functions (unused, since DDINT_CPU works in either mode) | |
| 40h | 000400h | Data: the BIOS segment (40h), so code that uses segment 40h works in either mode |
| 50h | 000500h | Code: the DDINT segment (50h), so the DDINT entry points have the same addresses in either mode |
| 58h | 000000h | Code: just the CALL 5 jump at 0:00C0h |
| 60h | SEL_CALL5: call gate (DPL 3) for a PSP’s CALL 5 | |
| 68h | System area + 10E0h | The TSS |
| A000h-B800h | A0000h-B8000h | Data: identity selectors for video memory, every 800h, for the BIOS and the drivers (a ring 3 program gets its own selector from VKD$; see Video Memory) |
| C000h-F800h | C0000h-F8000h | Code: identity selectors for the adapter and system ROMs, every 800h, so the ROM BIOS can run at ring 0 with its own segments (eg, F000h) |
Selectors 70h-7F8h (GDT) and 04h-7FCh (the active LDT) are allocated by CPU_ALLOC, CPU_MAP, and CPU_ALIAS. All descriptors are 80286-format (the 80386 fields are zero, except bits 31-24 of the base, for blocks above 16Mb or with paging, and on an 80386, the limit bits that CPU_SETLIM sets) and DPL 0 (unless MEMF_USER is set). The GDT’s limit extends through the identity selectors, so the processor can also read the rest of the system area as descriptors, through selectors 0800h to 9FF8h. So the PMB table and LDTs start at an offset of 6 mod 8, which puts each of those selectors’ access bytes on a byte that never has its present bit set (bits 31-24 of a descriptor’s base, or in a PMB, the top of PMB_ADDR, the high byte of PMB_NSEL, a reserved byte, or the last byte of PMB_NAME, whose bit 7 CPU_SETBLK clears). That way, loading one of those selectors (eg, a real-mode segment by mistake) always faults, and a ring 3 program can’t reach another LDT’s descriptors through the GDT.
The 80386 driver’s arena is a table of Physical Memory Blocks (PMBs) in address order, covering all memory from 0 to the end of extended memory, with the last PMB marked PMBSIG_LAST (‘Z’), like the last MCB:
| Field | Size | Contents |
|---|---|---|
| PMB_SIG | byte | ‘M’, or ‘Z’ for the last PMB |
| PMB_TYPE | byte | PMBTYPE_* |
| PMB_OWNER | word | Owner ID (see Owner IDs), or zero |
| PMB_ADDR | dword | Physical address |
| PMB_LEN | dword | Length, in bytes |
| PMB_SEL | word | First selector (if any) |
| PMB_NSEL | word | Number of selectors |
| PMB_MCBTYPE | byte | Block type (MCBTYPE_*, as in an MCB), or zero |
| (reserved) | byte | |
| PMB_CODE | word | The block’s code alias (see Code Aliases), or zero |
| PMB_V86 | word | A V86 machine’s page number, or zero |
| PMB_SHARE | word | The block whose memory its code alias maps (see MEMF_SHARE), or zero |
| PMB_NAME | 8 bytes | Name of the process (as in an MCB), or zero |
Unlike MCBs, PMBs aren’t stored in front of the memory they describe:
The cost is the room that the table takes in the system area (see Table Growth). The 8086 driver’s arena is the MCB chain itself: programs on an 8086 expect to see MCBs, and conventional memory is all there is. With the 8086 driver, CPU_QUERY describes each MCB with a PMB (whose PMB_SEL is the block’s segment).
For debuggers that can’t call CPU$ (eg, the PCjs Debugger, whose d dos command lists the arena the way DEBUG’s DM does), whichever driver stays stores the real-mode address of its arena in CPU_ARENA (0:514h): the 8086 driver’s first MCB, or the 80386 driver’s PMB table (in the system area, at offset 114Eh); a nonzero offset means it’s the table, since an MCB’s offset is always zero.
From the moment CPU$ initializes, everything that runs during the boot (devinit, each driver, and sysinit) claims the memory it uses from CPU$, and moves memory only with CPU_MOVE, so neither devinit nor sysinit computes a segment from an address. After the boot, DOS’s memory functions are calls to CPU$: DOS_MEM_ALLOC calls CPU_ALLOC (so in protected mode, a block can be anywhere in conventional or extended memory) and CPU_SETBLK, DOS_MEM_FREE calls CPU_FREE, DOS_MEM_REALLOC calls CPU_REALLOC, a program’s blocks are freed with CPU_FREEALL when it ends, and DOS_UTL_QRYMEM (for MEM) uses CPU_QUERY. There’s no MCB chain for programs to walk, other than the 8086 driver’s, and MEM’s total memory (SI_MEMSIZE in SYSINFO) includes extended memory.
To test protected mode, CPU$ switches to it and back. An 80386 returns to real mode by clearing PE. An 80286 can’t, so before switching, CPU$ sets the CMOS shutdown code to 0Ah and stores its return address in 40:67h, and to return, it resets the processor through the 8042, as the BIOS’s own block move (INT 15h function 87h) does; the BIOS sees the shutdown code and jumps through 40:67h without initializing anything else. Because the shutdown code is set before switching, a “triple fault” (which resets the processor) also returns to CPU$, and until the test passes, every gate in the IDT returns to real mode (without a reset, on an 80386), so a bug in protected mode makes the test fail instead of hanging the machine. The test writes and reads back a word at the start of the system area, through its selector; CPU$ stays loaded only if that works; otherwise, it turns A20 back off, and the 8086 driver stays instead.
CPU_PMODE switches to protected mode the same way, but for good: it never returns to real mode.
On an 80286 or later, when the 80386 CPU$ stays loaded, BASIC-DOS switches to protected mode during devinit, right after CPU$ initializes, and never switches back:
RING=0, with CS set to the code alias of its program’s block (see Code Aliases).The kernel’s protected-mode-only code (its fault handler, NE loader, and ring 3 support) comes after the rest of its resident code, so in real mode, it costs no memory.
After CPU_PMODE, every interrupt goes through CPU$’s IDT, and the master PIC is moved from 08h to 78h, next to the slave PIC (70h-77h), so that IRQs 0-7 no longer share vectors with processor exceptions. Its default gates “reflect” each interrupt to the handler in the real-mode vector table, if that’s in the ROM (whose segments are identity selectors, eg, F000h), at ring 0, on the interrupted code’s stack (or for an interrupt from ring 3, its ring 0 stack), so a BIOS call never costs a mode switch:
| IDT entries | DPL | Default handling |
|---|---|---|
| 00h | 3 | Divide errors (DPL 3, since ring 3 code may issue INT 0, as FPU$ does) |
| 01h-02h, 05h-0Fh | 0 | Exceptions: fatal, except the cases below |
| 03h-04h, 10h-6Fh, 80h-FFh | 3 | Software interrupts: the vector’s handler, if it’s in the ROM; otherwise fatal |
| 70h-77h | 0 | IRQs 8-15: vectors 70h-77h’s handlers, if in the ROM; otherwise an EOI |
| 78h-7Fh | 0 | IRQs 0-7: vectors 08h-0Fh’s handlers, if in the ROM; otherwise an EOI |
Ring 3 code can issue software interrupts (eg, INT 21h, or INT 10h, which is reflected to the ROM at ring 0), but an INT at ring 3 for any other exception or an IRQ is a general protection fault.
INT 0Ah), so an exception at ring 0 whose return address follows an INT for its vector is treated as one. Ring 3 code can’t issue those INTs, so at ring 3, vector 05h is always a BOUND fault.LDS SI,[78h] with DS = 0), so a general protection fault with a zero error code, in the ROM, while DS or ES holds a null selector, is retried with a selector for the first 64K. BASIC-DOS’s own code gets no such fix.Any other exception (including a software interrupt with no handler that CPU$ can call; an INT 3 goes to its handler, so a failed DEBUG assertion is handled as in real mode, see Interrupt Vectors) goes to the fault handler (see CPU_SETFAULT), which is the kernel’s unless a debugger has replaced it:
CPU fault vv (EC=xxxx) at cccc:iiii and ends the program with exit code 255 and EXTYPE_FAULT, as it does for a divide error, and the system continues.RING=0), the exception is fatal: CPU$ prints the same CPU fault line, followed by System halted, offers the halt to the fault handler, and unless a debugger takes it, stops the machine.The processor’s exceptions differ in where the saved CS:IP points: a fault (eg, #BR, #UD, #NP, #SS, #GP, #PF, and on an 80286 or later, a divide error) is reported before its instruction completes, with CS:IP at that instruction, so that it can run again once the cause is fixed; a trap (eg, #BP, #OF, a single-step, or any INT n) is reported after its instruction, with CS:IP at the next one; and an abort (a double fault, or a coprocessor overrun) leaves no reliable place to resume. Despite its name, CPU fault reports any exception that CPU$ can’t give to a handler, not just faults: an NMI or an abort, too, and a software interrupt with no handler that CPU$ can call, whose CS:IP is the INT and whose EC is the caller’s AX (eg, its function number). Only after a fault does a retry (eg, DEBUG.COM’s G after a fix) run the instruction that failed.
The drivers and the kernel (everything that runs at ring 0) are the same code in either mode, so they follow these rules:
COMMAND.COM runs at ring 3, so it uses only selectors that the kernel gives it, and asks the kernel or a driver for anything it can’t reach itself:
A protected-mode segment is either code (executable, and at most readable) or data (readable, and perhaps writable), so memory that’s both written and executed needs two selectors. CPU_ALIAS creates the second one: given a selector, it returns a new selector for the same base and limit, with the access rights selected by MEMF_CODE, MEMF_RDONLY, and MEMF_USER, and CPU_UNMAP frees it.
A block’s own code alias (CPU_ALIAS with just MEMF_CODE, for the selector that CPU_ALLOC returned for the block) is created only once, with the block’s DPL, and is freed with the block, so nothing else has to keep track of it (and it must never be freed with CPU_UNMAP). Programs get it from DOS_UTL_ALIAS (27h; see Utility Functions), since ring 3 code can’t call CPU$, and with AL = 1, the same function does the reverse, returning the block’s own selector for its code alias, since a code selector isn’t writable (eg, so that a debugger can store a breakpoint in a program’s code); in real mode, a block’s code alias is its segment.
With MEMF_SHARE as well, and a second block’s own selector in DX, the block’s code alias maps the second block’s memory instead of its own, which PMB_SHARE records; the alias is still freed with the block, and when the last block that shares the second block is freed, CPU$ frees the second block, too. That’s how ring 3 programs share code (see Loading Programs), since the alias can execute and read the code, but not write it.
COMMAND.COM compiles BASIC into code blocks that it allocates as data, and runs them (and transfers from one to another) through their code aliases. Generated code that writes to its own block (eg, a double’s result) gets the block’s data selector from the block itself, rather than from CS.
In protected mode, the DOS_PSP_EXEC functions run COM and NE programs, and on an 80386, LE programs, but not “MZ” EXE files:
X.DLL in the EXT\DLL directory of the system drive (the drive that DOS_MSC_GETPCH returns), or in the directory that a LIBPATH line in CONFIG.SYS names: an NE file marked as a library and PROTMODE, with FIXED segments, whose entry table lists the function as an exported entry. The loader gives the program its own copy of each library’s segments, in blocks that the program’s PSP owns, loads each library once per program (however many modules refer to it, and libraries can refer to each other), and stores each function’s address (a code alias and an offset) wherever the program refers to it. A library’s entry point isn’t called, references by name aren’t supported, and a missing or unsuitable library fails the load with ERR_NOMEMORY. DOSCALLS.DLL is the first library: it provides OS/2’s DOSCALLS functions, at OS/2’s ordinals, as far calls (in the Pascal convention) that it turns into DOS calls, and it has the functions that LINK386 and CL386 (the linker and C compiler for 32-bit programs, which are OS/2 1.x programs) import, and the three that search directories; TESTS\REGRESS\DLLTESTS.EXE calls 24 of them (those in the table without a note that they’re for LINK386 1.01 or CL386, except DosExecPgm):| Ordinal | Function | Notes |
|---|---|---|
| 5 | DosExit | DOS_PSP_RETURN |
| 14 | DosSetSigHandler | CTRL-C signals only: end the program (the default), ignore the signal, or call a handler |
| 33 | DosGetDateTime | (CL386) DOS_MSC_GETTIME and DOS_MSC_GETDATE; there’s no time zone |
| 34, 38, 39 | DosAllocSeg, DosReallocSeg, DosFreeSeg | DOS_MEM_ALLOC, DOS_MEM_REALLOC, and DOS_MEM_FREE; a selector that isn’t a writable segment is refused |
| 43 | DosCreateCSAlias | (CL386) Always fails: a code alias is the kernel’s to make |
| 49 | DosGetMachineMode | Always 1 (OS/2’s value for protected mode), so that a program uses these functions instead of DOS calls and real-mode habits (eg, LINK386 otherwise frees segments it never allocated when it ends early, which faults) |
| 52 | DosDevConfig | (CL386) Every item is 0 (eg, no math coprocessor, so a program leaves floating point to the system) |
| 53 | DosDevIOCtl | Always fails: OS/2’s device control functions aren’t supported |
| 58, 59, 60 | DosChgFilePtr, DosClose, DosDelete | DOS_HDL_SEEK, DOS_HDL_CLOSE, and DOS_DSK_DELETE |
| 61 | DosDupHandle | (CL386) Always fails: BASIC-DOS doesn’t duplicate handles |
| 63, 64, 65 | DosFindClose, DosFindFirst, DosFindNext | DOS_DSK_FFIRST and DOS_DSK_FNEXT, with a find block for each directory handle, so a program can have several searches: the system’s handle (1), or a new one (the selector of a small segment, which DosFindClose frees); each call finds one file, whatever number is asked for, a file’s allocated size is its size, and when there are no files (or no more), the error is OS/2’s ERROR_NO_MORE_FILES (18) |
| 68 | DosNewSize | A zero-length write at the new size; the file’s position doesn’t change |
| 70 | DosOpen | Opens, creates, or replaces a file, as the open flags say; only the open mode’s access bits are used, and opening a drive is refused |
| 71 | DosQCurDir | (LINK386 1.01) DOS_DSK_GETCWD: a drive’s current directory, with no drive or leading backslash |
| 72, 75, 77 | DosQCurDisk, DosQFileMode, DosQHandType | The current drive and a bit for each drive, a file’s attributes, and whether a handle is a file or a device |
| 74, 83 | DosQFileInfo, DosSetFileInfo | (CL386) A handle’s date and time of last write (DOS_HDL_GETTIME and DOS_HDL_SETTIME) and, for DosQFileInfo, its size |
| 81 | DosSelectDisk | (LINK386 1.01) DOS_DSK_SETDRV |
| 85 | DosSetMaxFH | Succeeds for up to 20 handles (a PSP’s), which can’t be increased |
| 89 | DosSetVec | Gets and sets an exception’s interrupt vector |
| 91 | DosGetEnv | (LINK386 1.01) The environment’s selector and the command line’s offset that the program started with |
| 92, 94 | DosGetVersion, DosGetPid | The DOS version, and the program’s PSP as its process ID |
| 120 | DosError | (CL386) Does nothing |
| 136 | DosHugeIncr | (LINK386 1.01) Not a function: an entry whose offset (8) is the difference between the selectors of a huge object’s segments, which there are none of |
| 137, 138 | DosRead, DosWrite | DOS_HDL_READ and DOS_HDL_WRITE |
| 144 | DosExecPgm | Runs a program and waits for it (DOS_PSP_EXEC), with a copy of the environment it’s given (CL386 passes each pass its options there), or the caller’s if there’s none |
A function returns 0 or a DOS error code (which OS/2’s error codes extend), and preserves every other register. os2.inc has OS/2’s values and structures for these functions, and PCALL, a macro that calls one: it pushes the parameters in the order they’re documented, and for ADDR,name, a far pointer to that variable in the program’s automatic data segment (eg, PCALL DOSWRITE,bx,<ds,dx>,cx,ADDR,written). KBDCALLS.DLL, MSG.DLL, and NLS.DLL each have the one function that LINK386 imports from those modules: KbdFlushBuffer (13) discards type-ahead, DosTrueGetMessage (2) never finds a message (BASIC-DOS has no message files), and DosGetDBCSEv (4) reports no double-byte character ranges.
OS/2 programs: an NE file whose header says it’s for OS/2 (NE_OS is NEOS_OS2) needn’t be marked PROTMODE, and it starts as OS/2 would start it, not with DS and ES addressing its PSP. So does a file that isn’t marked PROTMODE and whose header names no operating system (NE_OS is 0), which is what every OS/2 1.0 program is, and what LINK4 makes of a module definitions file without PROTMODE. In an OS/2 program, the header’s self-loading flag means that the program is “bound” (its stub runs it on DOS, too), so it’s ignored, and relocation records that are operating system fixups (which mark floating-point instructions) are skipped. The loader makes the entry point of the program’s copy of DOSCALLS.DLL (which it must import from) the starting address, with the program’s own starting address on its stack; that code, running as part of the program, allocates a new environment block, copies the PSP’s environment strings to it, and adds the command line after them (two strings: the program’s name, which is always “C”, and the command tail), and then starts the program with DS and ES = its automatic data segment (which holds its stack), AX = the new block’s selector, BX = the command line’s offset there, and CX = the data segment’s size. LINK386, the linker for LE programs, is such a program, and runs unmodified (in real mode, an OS/2 program’s file runs its MS-DOS stub, and LINK386’s can’t find its own file on BASIC-DOS). CL386 and its passes are, too (C1_386 and CL386 with their one import by name changed to an ordinal). SRC\SDK’s FIND16 is another, built on BASIC-DOS: a version of FIND.COM that calls only DOSCALLS functions, so the same file runs on OS/2 1.x.
LE programs: on an 80386 with the 80386’s features (CPU_TYPE 3), with programs at ring 3, an LE (“linear executable”) file, which is 32-bit code and data for a flat address space, runs in a flat machine; otherwise, the DOS_PSP_EXEC functions refuse it with ERR_NOMEMORY, like an MZ EXE file (and in real mode, it runs its MS-DOS stub).
TESTS\MISC\PRIMES.EXE is an NE program, linked by LINK4 (see tests/misc/PRIMES.DEF and the build tools), with the real-mode program as its MS-DOS stub, so it runs in either mode. LINK4 makes a segment code only if its class is CODE, and requires a DGROUP.
DEF SEG accepts any segment, which in protected mode isn’t a selector, so COMMAND.COM gets a selector for the segment’s 64K from the kernel (DOS_UTL_MAPSEG; see Utility Functions), which each session keeps one of. The selector is writable for video memory (A000h through BFFFh), and read-only everywhere else, including low memory and the ROMs, so PEEK works, but POKE is an “Illegal function call”. DEF SEG with no segment (BASIC’s own data) is readable and writable, as before. In real mode, none of these restrictions apply.
In protected mode, the identity selectors for video memory are DPL 0, for the BIOS and the drivers, so a ring 3 program that draws directly (eg, COMMAND.COM’s graphics statements) gets a selector from the console’s driver instead: IOCTL_GETMODE with CL = 1 returns VKD$’s LDT selector for the context, which maps the adapter’s video memory (16K for a CGA, or 4K for an MDA), starting at the context’s own page in a text mode, so that offset 0 is the context’s page, as it would be on page 0 (a context on a virtual page gets the adapter’s first page instead). VKD$ creates it with CPU_MAP the first time a program asks, in the LDT of the sessions on that console, and frees it when the context closes, and in between, it decides what the selector maps (see Selector IDs):
The copy starts on a page boundary, so a V86 machine’s pages can follow the selector there, too. In real mode, IOCTL_GETMODE returns the video memory’s segment, and so it does in a V86 machine that V86.COM created with its console’s selector, where the machine’s pages follow the selector. DEF SEG’s selectors (DOS_UTL_MAPSEG) don’t go through the driver, so POKE can still change any console’s video memory.
In protected mode, unless CONFIG.SYS has RING=0 (see CONFIG.SYS), every session’s first program (eg, COMMAND.COM) and every program that the DOS_PSP_EXEC functions start runs at ring 3, with CPU$, the drivers, and the kernel at ring 0, so that a program can use only the memory it’s given, and can’t use privileged instructions.
CPU fault, as it would have at its next instruction. A DS or ES selector that’s gone becomes 0.CPU fault (a handler that can’t be entered gets the default CTRL-C or ABORT response, and an interrupt that can’t be reflected goes to the previous handler). INT 22h’s gate must be DPL 3, for the ring 3 stub described below, so issuing it for any other reason ends the program, too, with the error code of a fault on that gate. Disk and device transfers are checked first, too (DOS_HDL_READ, DOS_HDL_WRITE, and the FCB functions), since a transfer’s physical address ignores the buffer selector’s limit, and a fault in a driver is fatal, and so is the data for each IOCTL that uses DS:SI (the program ends with a CPU fault if it isn’t all in the program’s memory). Any other bad pointer faults in the kernel, which ends the program (see Faults).CPU fault. A BIOS function would run at ring 0, trusting what it was given (eg, disk functions compute a DMA address from a segment value), and a fault in the ROM stops the system. Programs use DOS and the drivers’ IOCTLs instead, and programs that need the BIOS (eg, DISKREAD and DISKWRIT in TOOLS) need RING=0.&, #, or % addresses, and no system registers, and T steps over an INT, as P does.On an 80386 with the 80386’s features (CPU_TYPE 3), CPU_V86 provides V86 machines, which run real-mode code in virtual-8086 mode, at ring 3, for a host program that provides whatever services that code needs; ring 3 programs reach it through DOS_UTL_MAPSEG with AL = 2 (create a machine of BX paragraphs, owned by the current program) and AL = 3 (run machine BX, with ES:DI -> its V86REGS). V86.COM is the host for real-mode DOS programs. The interface is in v86.inc.
Interrupts: an interrupt from virtual-8086 mode needs an 80386 gate, and pushes a 32-bit frame (with the machine’s segment registers), so while a machine runs, its own IDT is loaded (built the first time a machine is created), whose gates (for the exceptions, 00h-11h, and the IRQs, 70h-7Fh) all go to CPU$, and the TSS’s ring 0 stack is the machine’s register context, so that’s where the processor stores its registers. CPU$ then loads the system’s IDT and the TSS’s previous ring 0 stack, and goes back to the stack of the call that ran the machine, where it runs the system’s handler for a hardware interrupt, as if the interrupt had come from there, so the drivers’ handlers (and session switches) work as they always have. The machine gets no hardware interrupts of its own, other than those that its host gives it.
/M switch gives, in K, which is also the memory size in the machine’s copy of the BIOS data), keeps the machine’s memory blocks (MCBs from 710h up, after the 256 bytes at 500h that DOS and programs like BASIC use, and its default handlers at 600h), PSPs, DTA, and vectors itself, loads COM and EXE files (with COMDATA, as BASIC-DOS does), and passes the rest of the DOS and DOSUTIL functions to BASIC-DOS, with selectors for the machine’s DS and ES and the current PSP’s handles in its own PSP_PFT (which BASIC-DOS uses), keeping a count of each SFH’s references, since DOS has no DUP for a new PSP’s copies. The PRINTF functions are rebuilt, since their format strings follow the INT (and %s is a near pointer), as are TOKID and STRSTR, whose data is in the caller’s CS, and LOAD (eg, for a pipeline’s next program, which runs as an ordinary BASIC-DOS program). IOCTL_GETFPU gets a copy of FPU$’s functions in the machine (see fpu.inc), which its programs call directly, and IOCTL_GETMODE with CL = 1 gets the segment of its console’s video memory in the machine (V86.COM gets the selector itself before it creates the machine, and passes it to DOS_UTL_MAPSEG), or an error for another console’s selector, and a CTRLC goes to the machine’s INT 23h vector, which restarts the interrupted call when its handler returns, as DOS does. A far call to DDINT_CPU, DDINT_GETVEC, or DDINT_SETVEC (which are HLTs in the machine, as its default handlers are) gets what the 8086 driver would do for a debugger: the machine’s vectors, CPU_GETINFO (with no free memory), CPU_MAP, CPU_UNMAP, CPU_SEGINFO, CPU_RWMEM, and CPU_QUERY, which describes the machine’s memory below its first MCB (named V86) and then its MCBs, for DEBUG’s DM; every other CPU$ function is invalid. V86.COM combines free blocks when it frees one (as BASIC-DOS does), so MEM reports the same free memory after a program ends as before it ran, and when a program ends, any vector still pointing into its memory gets its default handler again (as BASIC-DOS does; eg, DEBUG’s INT 01h and 03h, if a CTRLC ends it). An INT 10h, 16h, or 17h that reaches a default handler gets the common BIOS video, keyboard, and printer functions (and INT 10h AX = 1A00h, get display combination, when the machine’s BIOS data says that there’s a VGA), done with the console driver’s IOCTLs and DOS’s console and printer functions (so they work on a terminal, too), an INT 11h or 12h gets the equipment or memory size in the machine’s BIOS data, an INT 1Ah gets the system’s tick count (function 00h; the others return with carry set), and DOS_PSP_COPY copies the machine’s current PSP. V86.COM gives its console the machine’s first selector with IOCTL_SETKEYS (CL bit 1), so that VKD$ keeps the keyboard data in the machine’s copy of the BIOS data current, for programs that look there before they call INT 16h (eg, MSBASIC). After a V86X_TICK exit for a timer tick, the tick count in the machine’s BIOS data becomes the system’s (so it stays right, though the machine misses ticks), and the machine is owed as many ticks as its timer would have made since the last one (one, unless a program has set counter 0’s divisor, through ports 40h and 43h, down to 400h; at most 64 are owed). After any V86X_TICK exit, unless the machine’s IF is clear (in which case they wait for the next exit), V86.COM gives the machine the interrupts it’s due, in this order: an INT 09h for the next scan code in its console’s queue, if the program has hooked INT 09h (one scan code per exit, after any E0h/E1h prefixes, so a release never immediately follows its press), the interrupts from a borrowed sound card that SND$ counted (up to 2 at a time), and an INT 08h for each tick it’s owed (up to 16 at a time). It pushes the interrupted frame, and then a frame for each handler after the first, from the last to the second (with IF and TF clear), and runs the machine at the first handler, so each handler’s IRET goes straight into the next one, as if its interrupt had arrived just then, and the last one returns to where the machine was, with no exits in between (at 700 ticks a second, an exit for each would leave little time for the program); only a scan code prefix with another code after it returns to a HLT at STUB_SEG:STUB_VIRQ instead, which exits so that V86.COM can give the next code. VKD$ adds each scan code to the queue (KQ_HEAD, in bios.inc, just below 600h in the machine) while the console that has the machine’s BIOS data (IOCTL_SETKEYS CL bit 1) has focus, and port 60h reads the code of the last INT 09h; a handler that passes the interrupt on to the default vector (a HLT) lets the system’s keys stay readable, while one that keeps it makes V86.COM discard the console’s keys (DOS_TTY_FLUSH) on the next tick, so the system’s keyboard buffer doesn’t fill. The default INT 08h and 1Ch handlers are code in the machine, next to its default-vector HLTs (an INT 1Ch and an IRET, and an IRET; INT 33h’s default is that IRET, too, so programs see no mouse), so that a tick never needs another exit. A machine gets ticks only while its code runs, not during a DOS call that waits (eg, for a key). A V86X_IO exit goes to the handler for its port, from a table of port ranges (a word is two bytes, at that port and the next): the timer (40h-43h, as above), the keyboard (60h-64h), the DMA controller (00h-0Fh and its page registers, 80h-8Fh), which go to SND$ (IOCTL_SNDDMA) if the machine borrowed a sound card, and ports with nothing behind them, which read as FFh (sound cards at 210h-26Fh, the parallel ports, an FM sound card’s, 388h-389h, and without a sound card, the DMA controller’s); a port with no handler ends the program with a CPU fault, as before. When it starts, V86.COM opens SND$, if it’s installed, and borrows its card for the machine (IOCTL_SNDLEND); its handle for SND$ is the last of its 20 (the machine’s programs get the other 19, and closing handle 19 fails), so that DOS closes it when V86.COM ends, however it ends, which gives the card back.A flat machine (CPU_V86 with AL = 6-8; see v86.inc) runs 32-bit code at ring 3, in protected mode, in a linear address space of its own: every address below C0000000h (where the system’s addresses begin; see Paging), of which only the memory that the machine has been given is mapped. Like a V86 machine, it has its own page directory, it runs with the machines’ IDT (whose gates are 80386 gates) and its own ring 0 stack (its register context), and every interrupt takes it back to the call that ran it (CPU_V86 with AL = 1), so the system’s 16-bit interrupt gates, which would lose the upper halves of a 32-bit program’s EIP and ESP, never see 32-bit code, and everything else in the system works as it always has.
LE programs: the kernel loads an LE file (see Loading Programs) into a flat machine whose memory is as large as the file’s objects need, or if there’s more to spare, half of the largest free block, up to 256K. The objects are loaded one after another from 10000h, each starting on a page, whatever addresses the linker gave them (LINK386 1.01 puts each at a multiple of 64K, which would cost 64K of memory apiece): each object’s pages are read (or left zeroed), and each page’s fixup records are applied, which must all be 32-bit offsets to the program’s own objects (what LINK386 makes for a program whose segments are in a group named FLAT), and which are the only references to an object’s address; at most 16 objects, with 4K pages. The program starts at the entry point and stack pointer in its LE header, with DS = SS = its data selector, ES = its PSP’s (16-bit) selector (eg, for its command tail), EDX = its first object’s address, EBX = the address after its last object, and ECX = how much memory follows that.
The program has a PSP, handles, and a parent, like any other, because as far as DOS can tell, it’s a small 16-bit program: its PSP’s block holds the PSP, a little data, and a stack, and its code is a piece of the kernel (mapped by a ring 3 code selector of its own), which runs the machine until the 32-bit code issues an INT 21h, makes that DOS call itself, at ring 3, and runs the machine again. So the kernel needs no 32-bit entry points, and the translation can’t do anything that the program couldn’t. A 32-bit program’s DOS calls work like this:
SRC\SDK’s CRT32.ASM does for C programs).CPU fault vv (EC=xxxx) at cccc:iiiiiiii and ends the program with exit code 255 and EXTYPE_FAULT, as a fault in any other program does.A CTRLC ends the program at its next exit (every timer tick is one). DOS_UTL_MAPSEG with AL = 4 and 5 gives the kernel’s code those two CPU$ functions at ring 3 (see Utility Functions).
The Extended Memory (2Mb) demo is a 2Mb PC AT with a Color Display and three full-screen consoles, one on each page of video memory. The Extended Memory (VT100 Debugger) demo runs the same sessions, with a DEC VT100 on COM2 for DEBUG.COM, and its Debugger page is the same machine with the PCjs Debugger. Each also runs on a 2Mb COMPAQ DeskPro 386 with a VGA (2Mb and VT100), from the same diskette, where CPU$ also uses the 80386’s features (see The CPU$ Drivers). Pressing R at the boot message boots the diskette in real mode instead. Everything after CPU$ initializes runs in protected mode, and COMMAND.COM runs at ring 3, with C: as the default drive. Commands, BASIC programs, and NE programs work (eg, PRIMES.BAS in the third session), but MZ EXE files don’t (see Loading Programs).
In the VT100 demo, DEBUG.COM, loaded as a driver, shows each fault on the VT100, with the registers at the faulting instruction (adding /H to its line in CONFIG.SYS stops it as soon as it’s loaded, so that you can set breakpoints before booting continues). The B: drive has the BASIC-DOS Tests diskette, so B:\TESTS\MISC\FAULT n causes exception n (0, 1, 3-6, 12, or 13), or with -1, a fault in the kernel (a null pointer to a filename), to see how BASIC-DOS responds: DOS reports a divide error (0) or an overflow (4) and ends the program, a single-step trap (1) or a breakpoint (3) resumes (unless DEBUG.COM stops there), and DOS ends the program for the rest (eg, CPU fault 0D), unless DEBUG.COM’s VT command traps the vector.
& (real mode), # (protected mode), % (a linear address), or %% (a physical address), DS selector displays a selector’s descriptor, R also shows the MSW, GDTR, and IDTR (and in protected mode, the LDTR, TR, and each segment register’s base and limit), and LN [address] shows the name of the memory an address is in (see DEBUG.COM).r shows each segment register’s selector with its base and limit in protected mode (eg, CS=0018[000970,FFFF] in CPU$), along with the GDTR, IDTR, LDTR, and TR, and its d dos command lists CPU$’s arena, in either mode (see Physical Memory Arena).RING=0, and DEBUG.COM run as a program has fewer commands at ring 3 (see Running Programs at Ring 3).RING=0.%ls parameter to DOS_UTL_PRINTF can still point to a ring 0 selector, so a ring 3 program can read kernel memory that way (but not write it).
Copyright (c) 2020-2026 Jeff Parsons Released under MIT License