RAW32 Release 2.2 documentation


Preface

If you use RAW32 (RAW32.ASM and/or the included examples, compiled or not)
you accept the full responsibility of any damage that RAW32 may cause; I am
not responsible for any damage it may do to any computer you run it on.
Note: I have not encountered a PC on which RAW32 caused any serious damage
(see 'Bugs' section).

You are allowed to use RAW32 for anything except for commercial purposes. I
give these sources away for free, but if you want to use any part of it for
a commercial purpose you are required to contact me first. See 'Final
words' how to contact me.

If you use RAW32 or any part of it in a program you make you are required
to mention the name RAW32 and the source you got it from in the documenta-
tion accompanying the program.


Introduction

This is the second release of RAW32. See 'What's new' section.
I release the source code, because it is hard to find some useful info
about protected mode (PM) programming for beginners. The extender/PM header
is called 'RAW32', because it is intended to use it to program under any
memory configuration as if under a raw system (it also got to have a name
;). With "raw" I mean, access to all the available extended memory using
only two pointers; one that points to the start of the available extended
memory and one that points to the top of the available extended memory.
Under a real raw system the first pointer typically points at 1MB, under
DPMI it can point to anywhere in the address space. So, RAW32 does static
memory allocation, i.e., at starting up it allocates all the memory it can
get and does not free it until the RAW32 program exits. Raw also means that
this is not yet another one of those extenders that implement the DPMI
standard; it does not implement any standard, which is nice when you want
to write PM programs that are just PM and not DPMI (for example, writing
your own OS).

If you want to actually step through a program made with RAW32 use SoftICE
(*that* is a program that can be rightfully called a debugger). I have
mainly used Turbo Debugger - an old version which doesn't have it's own
DPMI server loaded, so I can debug RAW32 also under raw, XMS and VCPI. That
means starting TD, running my program and afterwards using watches to look
at the values of test variables. This is nearly the same thing that
programmers did in the pre-debugger era ;)

RAW32 is not perfect but it is very stable (if real mode callbacks are
disabled) and very well commented. It is based on Thomas Pytel's (Tran)
START32 from which I learned much. START32 supports only a raw system, and
contains some bugs. After figuring out how the PM mechanisms worked I
wanted START32 to work also under XMS, VCPI and finally DPMI. XMS and DPMI
were easy, but VCPI was much more difficult, mostly because of paging.
After some time my version of START32 was very different compared to the
original one so I decided to give it another name and put it on the
internet.
RAW32 does run under Windows (3.1/3.11/95/98), but it is not designed (if
it can be called that) for it. See 'Inner workings' section.


What's new

Bug fixes and changes between RAW32 R2.2 and RAW32 R2.1

changes:
-translated the remaining examples to NASM (except the mouse examples)
-many cosmetic changes
-FPS.ASM contained a minor error; the 2 putpixel macro definitions were
placed after the statements that used them...


Bug fixes and changes between RAW32 R2.1 and RAW32 R2

bugs fixed:
-stack dump routine dumps the stack properly if esp!=200h...
-The interrupt mask registers are restored to the right values under a PL 0
DPMI server.
-Under VCPI the IRQx_vect variables are now initialised to the values
returned by the VCPI server...
-better handling of the situation where one IRQ handler interrupts another
in RM (with RMCBs enabled)

changes:
-added a Netwide Assembler (NASM 0.97) version of RAW32; RAW32 can now be
build without using commercial tools (if you can find a free OMF linker
somewhere)
-changed some ancient comments
-Some jumps that used a pointer variable as target are now hardcoded.
-added some assume directives to avoid some segment overrides with segment
registers other than ds


Bug fixes and changes between the first release of RAW32 and RAW32 R2

bugs fixed:
-setdsc now sets descriptors with RPL <> 0 in the right way
-bug in gateA20; I came across a 486 which required that there is a delay
after the value of the 8042 output port is read.
-bug in _dosshell; can now be called more than once...
-proper virtualization of flags register
-now works under Quarterdeck's VCPI server (VCPIsel0 is a code selector...
of course this says something about M$ not complying with specifications
too ;) I tested only EMM386.EXE's VCPI...
-bug in 32-bit startup code; clearing the NT flag *is* necessary...
-RM_int now loads _e_sp instead of sp (very frustrating to find that one!).
Look at UNDOC.ASM
-stack is used in RM_int/VCPI_int *after* ss:sp is valid...

changes:
-changed the name of several variables (many underscores removed, and the
case of some variable names has been changed)
-setdsc can set descriptors in the LDT
-changed the handling of IRQs; the default IRQ base numbers are maintained
in protected mode. Now the PIC is not reprogrammed on every IRQ. This
solved some unexplainable behaviour like the need to enable IRQs in
VCPIinitPM, the messing up of page table entries, the COM ports that
stopped raising IRQs after some data was recieved etc.
The ugly thing of this is that IDT entries 8-15(14) are shared between IRQs
and exceptions...
'bug_buffer' could also be removed.
nIRQm21 and nIRQma1 aren't necessary anymore; they have been removed too.
-changed DPMI/VCPI/XMS detection order; the check for DPMI is made last.
VCPI, XMS and raw make PL 0 possible, most DPMI hosts not. PL 0 is more
'RAW' ;)
-I came across several PC's where int 15h/eax=e820h enables IF (bug?), so
interrupts are now disabled *after* check_memory.
-dosshell doesn't pass arguments given to a RAW32 program to COMMAND.COM
anymore
-TR contains a valid value at startup under raw and XMS
-The IDT is now build dynamically. I made this change to fully comply with
the VCPI specification without reprogramming the PICs.
-I added real mode callbacks. See 'Inner workings' section.
-Almost all "public" statements in RAW32.ASM have moved to RAW32.INC.
-I have added some examples. See 'Examples' section.


Features

Yes, this little thing even has unique features!
* It supports >64MB systems under all memory configurations. Yes, even
under VCPI with a VCPI server which does not support that (Watcom's DOS/4GW
does not do this for you). See 'Inner workings' section.
* It has a physical to linear memory mapping function as opposed to Tran's
PMODE 3.07...
* New in release 2 is an executable loader that loads RAW32 programs in
extended memory. Now you can make programs that are several MBs in size!
Well, that's it...;)


Inner workings

If you want to know every detail, look in RAW32.ASM; it is very well
commented.

64MB
RAW32 can use >64MB even under VCPI servers that support less (for example
EMM386.EXE that supports 32MB at maximum). It does this by checking if
there is XMS present too when VCPI has been detected. 
With EMM386.EXE this will always be the case, but the VCPI specification is
independent of the XMS specification. XMS supports 64MB (SXMS 4GB). If XMS
is present RAW32 allocates memory through XMS instead of through VCPI. This
is not only nice when you want to access all memory under a VCPI server
that has limitations, it is also *much* faster than allocating memory
VCPI-style at 4KB increments. Under VCPI paging could be - if programs are
loaded high it is - enabled. So, if RAW32 allocates memory through XMS it
creates page table entries for it. The page tables are created in extended
memory, so the precious DOS memory is not wasted (I do not know why CWSDPMI
does not do this); for every MB of memory 1KB of page table entries is
needed...

Windows
It is called RAW32, yet I wanted it to run under Windows too. But many
people would agree with me that Windows is one big bug. RAW32's DPMI code
behaves strictly according to the DPMI 0.9 specification. First it asks how
much memory it can lock, and allocates that amount. Then (this should not
be necessary, but it is) it tries to lock an ever smaller amount until it
succeeds. Under Windows version 3.1 and 3.11 this results in a very
unstable system, i.e., it can hang or reset at any time. Sometimes this can
result in a couple of lost clusters (run ScanDisk (...) and everything
should be ok again). Windows 9x survives, but since it does some - inferior
way of - multitasking, locking all the memory you can get slows down the
system terribly (why does it give a too large amount?!). To make life a
little easier under Windows, remove the semicolon (if present) in front of
the line:
WINFRIENDLY     =       0 
If RAW32 is compiled again, (under Windows) it locks only half the amount
of memory it should be allowed to lock. Another way of being more friendly
towards Windows is by not locking the allocated memory so that Windows can
swap your memory to disk, but than the meaning of raw would be completely
lost...

API
RAW32 has a little API - allocating/setting of descriptors, getting/setting
of interrupt vectors, allocating memory from it's heap, mapping physical
addresses to linear addresses, putting a string to screen and a DOS shell
routine - but it doesn't make sense to copy the headers of those functions
in this document; they speak for themselves. Look at the examples and
headers(!) to see how those routines should be used.

Real mode callbacks
When I wrote the real mode callback code I had not a good VCPI server at my
disposal. With "good" I mean a VCPI server that programs the PICs to base
interrupt values other than 8 and 70h. I assumed a couple of things which
are hopefully right.
1.)
I assume there are no VCPI servers that make things worse than IBM did,
i.e., programming both PICs so that every IRQ IDT entry is shared with an
exception :-)) So, if the master PIC base interrupt is not 8 RAW32 assumes
the IDT entries of IRQs 0-7 and exceptions 8-15 are not shared.
2.)
I assume also that in V86 mode IRQs are intercepted by the VCPI server, and
that the VCPI server calls the conventional real mode vectors of 8 and 70h
(how else could DOS ever run under such a VCPI server?)

I added the real mode callback (RMCB) code so that even in RM the PM IRQ
handlers will be called. When for example RM int 16h is called (which by
the way enables interrupts) while the PIC is programmed to generate IRQ 0
at 1000Hz the original RM IRQ 0 handler will be called at this rate too...
Of course, RAW32 could reprogram the PIT at every IRQ (as System 64(?)
does), but besides that I dislike that and that this solves the problem for
IRQ 0 only (in a way), one can imagine worse scenarios when there is no RM
handler or the RM handler must not be called.
Because the 'execution chain' is quite complex RMCBs are slow, but the nice
thing is that RMCBs are active only when a RM int is called and interrupts
are enabled. By default reflecting IRQs to PM looks like this (better get a
cup of coffee or tea first :)
The RAW32 program calls a RM int with int RMCALL_VECT. If the int handler
enables interrupts (RM_int and VCPI_int disable interrupts) and takes too
long to do it's job or waits for something an IRQ could be generated.
Because the processor is executing in real mode (under VCPI V86 mode, but
the VCPI server should make the system behave like when in RM) and because
RM_int loads the IDTR with a RM compatible value (i.e., base=0
limit=4*256-1), the RM interrupt vector table (IVT) is active. So, the IRQ
vectors through the IVT. IRQs 0-7 correspond with RM ints 8-15, IRQs 8-15
correspond with RM ints 70h-77h.
Now the RMCBs come in action, because init_callbacks changed all these
vectors and made them point to the labels RMcallbackIRQn in the code16
segment of RAW32. If for example IRQ 0 is generated execution arrives at
RMcallbackIRQ0. Then the IRQ base interrupt is loaded to determine which PM
IRQ handler should be called. Under VCPI the PICs could be programmed to
base interrupt values other than 8 and 70h so no assumptions can be made
about the _PM_ int values that are called on an IRQ (see assumption 2 that
I made about VCPI servers). The value obtained in this way is used to find
the selector and offset of the PM IRQ handler.
Then a switch is made to PM and the PM IRQ handler is called. By default
the RAW32 PM IRQ handlers do nothing and just reflect the IRQ back to RM
(i.e., they call the RM IRQ handler). Then things get a bit more complica-
ted. RMcall_int and VCPIcall_int save the stack registers ss:esp (they are
destroyed by RM_int and by switching to V86 mode via the VCPI server) and
restore ss:esp when the RM int returns. But when a RMCB calls the PM IRQ
handler ss:esp points to another stack than when an IRQ is generated while
in PM. Therefore two variables are necessary to save those two stackpoin-
ters (ss:esp). That is why an extra offset is added to ebx (stackoff).
stackoff contains the offset from the first stackpointer variable to the
second if a RMCB called the PM IRQ handler. stackoff has the value 0 if not
a RMCB called the PM IRQ handler (i.e., an IRQ occurred in PM).
If only one variable would be used to save the PM stackpointer, that
variable would contain the proper value as long as no RMCB becomes active.
When a RMCB becomes active the variable would be overwritten without any
problems until the RM int returns and the original PM stack should be
restored. The stack would be restored to the PM stack left when exiting the
RMCB...
When execution has finally arrived at RM_int or VCPI_int a check is made if
it is an IRQ int handler that should be called or a general int handler.
Not that there is any difference, but the RM IRQ vectors now point to the
RMCBs in RAW32 and just doing INT RM_intnum/VCPI_intnum would result in an
infinite loop. So, if a RM IRQ handler must be called a jump is made to
RM_IRQ which calls the appropriate address in orgIVT which contains the
orginal RM IRQ handler addresses (initialized by init_callbacks).
When the RM IRQ handler returns, execution is given back to RM_int/VCPI_int
which returns to RMcall_int/VCPIcall_int which returns to the PM IRQ
handler.
When the PM handler returns, a switch is made back to RM and RAW32 returns
to the RM code that was interrupted by the IRQ.
In short:
IRQ in PM -> PM IRQ handler -> RM IRQ handler -> PM IRQ handler's exit ->
execution in PM continues

RM int called in PM -> RM int handler -> if too long in RM and ints enabled
-> IRQ in RM -> RMCB -> PM IRQ handler -> RM IRQ handler -> PM IRQ hand-
ler's exit -> RMCB's exit -> execution in RM continues

V86 mode
The whole idea of RMCBs wouldn't be necessary if V86 mode would be used to
handle RM int calls. Actually, I planned to let RAW32 R2 handle them in V86
mode.
Drawback: it's a little slower - an INT instruction versus a complete
V86-monitor. That's why I wanted to make an extra version.
Advantages:
* IRQs always go through RAW32, so no IRQs will be missed (without the
ugliness of RMCBs).
* The same code can be used under raw/XMS/VCPI to handle RM ints
The version I made (not included) works, but has some problems under VCPI -
especially when DOS is loaded high. Then many RM int calls result in things
like execution that ends up in some data area in the HMA or other nice
things :( The dosshell function for example can give nice results...
However, the code is good enough to let most of the examples run that don't
call DOS (with DOS loaded low). Mail me if you want it.
The problem is that handling RM ints via V86 mode under VCPI needs VCPI
implementation specific code. That's not only ugly and incompatible, it's
also difficult to find out the VCPI server specific details :(

Sharing IDT entries between IRQs and exceptions
I don't like this at all about this version of RAW32. Maybe a new version
of RAW32 (if I make one) will handle IRQs in the same way as CWSDPMI does,
i.e., reprogram the PIC to PM compatible values (no sharing) and make the
RM IRQ handlers point to the original ones.


Bugs

Hooking all IRQs in RM somehow doesn't work. You might think this is just
caused by the fact that RAW32 has some bug in the RM->PM->RM code, but it
isn't. It is just as I said: hooking all IRQs in _RM_ somehow doesn't work
;) At least at the PCs that are at my disposal. If you extract the code
that hooks the int vectors, the code that contains the RM IRQ 'handlers'
and the code that restores the RM int vectors again and compile that code
you'll see that sometimes - very often on my computer :( - only pressing
the <censored> Num Lock key can lock up the system. It's even that bad that
on my PC pressing Num Lock generates int 15! That is int 15 and not int 15h
nor IRQ 7!
Therefore RAW32 doesn't hook RM int 15. IRQ 14 (RM int 76h) gave problems
too (copying large files with XCOPY.EXE via dosshell).
If you don't need to be 100% sure that there are no IRQs missed by the PM
handlers just outcomment the line 
RMCB_ON         =       0 
Enabling RMCBs makes RAW32 a bit less stable if the RAW32 program does many
things in RM :(

If you look at the first couple of statements after the label 'start16:'
you see
  mov ah,30h
  int 21h
I don't now why, but somehow this (i.e., a call to a random RM int functi-
on) is needed on my computer under VCPI when DOS is loaded high. The
problem is gone when the check/intitialization order for VCPI/DPMI is
changed; then the int 2fh in check_DPMI does the job. If I load the RAW32
program with TD nothing goes wrong (those are the nicest bugs!). I haven't
seen this bug on other computers. I traced through the code of the ISR, but
I didn't find anything special.

Not a bug but more an imperfection is that the code in RAW32.ASM that
builds the IDT uses the memory starting at code32end (check_memory does
this also, but that can be changed easily). The result is that a RAW32
program that has segments with a name other than code16 or code32 will find
its first segment with another name overwritten at the start. The fix for
this is to create a dummy buffer (256*8 bytes is always enough) in the
first segment with another name so that no code or data will be corrupted
(look at V86-1.ASM).
Another imperfection is that RAW32 doesn't reload all segment registers
before switching to RM when calling a RM int/IRQ. This means that under raw
or XMS all selectors should have a limit > 64KB or an exception 13 could
occur while in RM (look at UNDOC.ASM). All segment registers are given a
value in RM, but as you can see in UNDOC.ASM that doesn't reset the segment
limit that was active in PM. If you want to be able to call a RM int while
one of the segment registers has a limit < 64KB, add some lines in
RMcall_int that load all segment registers with data16sel. By default es
has a limit of 256 bytes and is the only selector that could cause trouble
(guess how I discovered this imperfection ;) Therefore, RMcall_int loads
_es_ with a RM compatible value to access some variables.

Since Windows 3's DPMI is totally lame RAW32 will crash if 'WINFRIENDLY' is
not defined at compile time. See 'Inner workings' section.

If you have solved one of these bugs, know a possible solution or have
found a new bug please mail me.


Examples

If you are in a hurry have a look at DPMIPL0.ASM and LOADER\LOADER.ASM.

HELLO.ASM
'Hello, world!' in bright white on bright blue ;)

FLATVID.ASM
This example shows the basics of using a VBE linear framebuffer.

PLSWITCH.ASM
This example shows some aspects of switching between privilege levels
(PLs).

MULTIT.ASM
This is a little multitasking example ('round robin'). I made it when I
experimented a little with task gates, so it isn't the best source if you
are really interested in multitasking. I tried to keep it simple.
Accompanying RAW32 R2 is a new version which corrects some very stupid
mistakes in the version accompanying the first release of RAW32.

FPS.ASM
This example shows some use of the timer to dynamically measure and display
how many frames can be drawn in some frame drawing loop. I implemented it
this way so that some code can be tested without modifying it much and to
monitor the FPS performance in time.
FPS.ASM contains three different ways to fill a screen with pixels. The
strange thing is that not all PCs (video cards) show the same one as the
fastest.
This example also shows how to use the BIOS fonts to write text to a
graphics screen.

MOUSEx.ASM
MOUSE2.ASM shows some aspects using the mouse by means of RM int 33h calls.
It also shows some graphics palette programming stuff that I added to look
at something nicer than a dull black screen while programming the mouse
examples ;)
MOUSE3.ASM does a little more in that it draws the mouse cursor itself.
MOUSE4.ASM hooks the approriate IRQ to avoid polling as in MOUSE2.ASM and
MOUSE3.ASM.
 
V86-x.ASM
These are two examples that show some aspects of V86 mode. V86-1 shows how
to get into V86 mode and out again. It also shows something I read in the
Intel 80386 Programmer's Reference Manual about calling PM int handlers
from V86 mode (I've never seen this done elsewhere).
V86-2 shows how to handle an RM int called from V86 mode.

DPMIPL0.ASM
This is an example I made after I read about it on the PM mailing list.
Basically I just followed the algorithm given by Vadim Drubetsky (Black
Phantom) with a few improvements (he was talking about DPMI under Windows
which doesn't use the last two entries in the GDT). So credits go to him.
It works under Win 3.x/Win 9x/CWSDPMI/QDPMI and probably under all DPMI
servers that don't have page level protection. To make it work under
Quarterdeck's DPMI just disable ints before going to PL 0.

UNDOC.ASM
This is an example that shows some undocumented behaviour of the 80386 and
above. I knew about the so called 'flat real mode' (or unreal mode etc) and
have used it for a little RM VBE program, but I never really thought about
it until I came across the esp/sp bug. I wrote UNDOC.ASM to test a few
things of the flat real mode. The funny thing was that *all* fields of the
hidden part of a segment register stay active when switching from PM to RM.
That includes the default bit for a data selector as was the case in the
esp/sp bug.

LOADER.ASM
I made this loader with three things in mind:
-to be able to make programs with RAW32 that are larger than 640KB
-do this with TASM(NASM)/TLINK only (no separate RAW32 specific tools)
-do this with as little modifications to a standard RAW32 program source as
possible

Look at FLATVID.ASM in the directory LOADER and compare it with the
'normal' FLATVID.ASM to see an example of what modifications a RAW32
program needs to make it work with the RAW32 loader.

Use the batch file MAKEL.BAT to compile the loader. Use MAKEM.BAT to
compile a RAW32 'module'. A module is just an MZ EXE with a different
extension (RX, to avoid accidental starting of a module) and normally
consists only of 32-bit code. This as opposed to a normal RAW32 program
which has the 16-bit part of RAW32 linked to it.
When LOADER.EXE is started without arguments it tries to load the file
MODULE.RX. If you want it to load another module you can change the default
name in LOADER.ASM or give the module name as an argument, e.g. LOADER
FLATVID.RX.
When making a module you have to follow the following rules:
1.)
Add the following lines to the RAW32 program source
TASM:
NO_EXTERN       =       0
include raw32mod.inc
NASM:
%define NO_EXTERN       0
%include "raw32mod.inc"
2.)
The relocation code of the loader treats the address to which a relocation
item points as a dword. Therefore you must always use 32-bit operands when
loading a segment name (which results in a relocation item) as in
  mov eax,code32
or
  mov var1,seg var2
where code32 is a segment name and var1 a 32-bit variable. If you use a
16-bit operand as the target, 2 bytes in the code will be overwritten by
the relocation code of the loader...
3.)
TASM:
After the 'end' directive you must put 'main' so that the linker will fill
in that label's offset as the entry point in the MZ header. The loader
jumps to the entry point indicated by that field in the header.
NASM:
Change the 'main' label into '..start'.
4.)
The 'main' (NASM: '..start') label must be within the first 64KB of the
RAW32 program. If you have more than 64KB of static data in your program,
just put it somewhere after 'main' ;)
5.)
Because a RAW32 module is loaded in extended mem you can't directly pass
variables in your program's segment to RM BIOS routines. First you have to
allocate a buffer in low memory with getlomem, then copy the data to that
buffer and then pass the address of that buffer to the BIOS routine. Again,
look at FLATVID.ASM in the directory LOADER for an example.
6.)
Relocation items may occur only within the 64KB in a segment and within the
1MB of the module. TLINK won't link your program if this is not the case,
so you won't be surprised, but at least you have been warned.

NASM specific:
7.)
Because NASM uses a stricter (better, I think) convention to distinguish
between offset constants and memory references, all the references to
labels in RAW32.ASM have to be placed between square brackets. This,
because in a RAW32 module these labels refer to far pointers instead of
labels. E.g. "jmp exit" has to be changed into "jmp far [exit]" and "call
putstr" into "call far [putstr]".
8.) 
If the module is very large you need an appropriate compile of NASM (e.g.,
a DJGPP compiled NASM (http://members.xoom.com/dbjh/raw32/nasmdj.zip).
Don't forget to get CWSDPMI.EXE (csdpmi4b.zip) from Simtel or one of it's
mirrors.). If you're desperate use NASMW.EXE...


Credits

Give credit were credit is due, so credits go to
Thomas Pytel (Tran)	tran@phantom.com             	- START32
Adam Seychell		s921880@minyos.xx.rmit.edu.au	- DOS32 v1.2
Desmond Germans (Simm)	germans@cs.vu.nl        	- SYSTEM64 v1.210
              		npgerman@nat.vu.nl
               		nigerman@nat.vu.nl
David Jurgens                               		- HelpPC 2.10
Ralf Brown       	ralf@pobox.com             	- The interrupt list
Herman Dullink          csg669@wing.rug.nl             	- D32
                 	herman.dullink@prgbbs.idn.nl


Final words

If you make something with RAW32 please let me know, I am very interested.
If you have questions about PM programming in general do not mail me but
subscribe to the protected mode mailing list.
To subscribe:
  send mail to: pmode-l-request@phys.uu.nl
  subject: none
  body: subscribe pmode-l email@yourisp.name
To unsubscribe:
  send mail to: pmode-l-request@phys.uu.nl
  subject: none
  body: unsubscribe pmode-l email@yourisp.name
Note: That's PMODE-L (not PMODE-1). Use the 'end' command at the end of
your email to prevent junk at the end of your message to be interpreted as
commands (several free email providers add a signature at the end of your
emails). Use pmode-l@phys.uu.nl to send email to others in the list.
At the risk of labouring the obvious send a mail to Majordomo@phys.uu.nl
with in the body the command 'help' to know which commands the mail server
recognizes.

If you have questions about RAW32 you can send them to me. I would be happy
to answer them :) You can contact me via email at
dbjh@usa.net                       (preferred)
Daniel.Horchner@95.Student.WAU.NL

Danil Hrchner

<end of file>