[comp.sys.ibm.pc] Leaving Protected Mode on the 80286

ballou@maypo.berkeley.edu (Kenneth R. Ballou) (08/27/87)

	Several months ago, I was experimenting with protected mode of
the 80286 and produced some demonstration routines to show how to enter
and leave protected mode.  (If anyone is interested in these routines, I
will be happy to send them, or post them if demand seems to warrant it.)

	Here are some fragments of the code.

______________________________________________________________________

This code is executed in real mode before entering protected mode.  The
idea is to save a segment:offset address in the doubleword located at
40H:67H which specifies where you wish to resume operation when returning
from protected mode.  Also, save the current SS:SP in known locations.
(Of course, if you write over any of these locations in protected mode
operation, YOU LOSE!)

; Prepare for the big return.  If the shutdown status byte in CMOS is
; 5, the BIOS will do a far return to the address located at 40H:67H.
; At the time of the return, interrupts will be cleared.

	MOV	AX,40H
	MOV	ES,AX
	MOV	SAVED_SS,SS		; save current SS:SP for re-entry
	MOV	SAVED_SP,SP
	MOV	ES:[0067H],OFFSET BACK	; set up far pointer to re-entry code
	MOV	ES:[0069H],CS

______________________________________________________________________

This is the code called in protected mode to reset the 80286.  Byte 15 in the
CMOS memory contains a "shutdown byte" which tells the BIOS the reason for
the shutdown.  It happens that if this byte is 5, then this is a shutdown
request for returning from protected mode.  After suitable re-initialization
of the hardware, control will be transferred to the location stored at
40H:67H.  (In particular, the memory check is not done.)


SHUTDOWN	PROC	NEAR
	CLI				; probably a good idea
	MOV	AL,8FH			; write CMOS byte F (hex), disable NMI
	OUT	70H,AL			; port 70H:  select CMOS byte address
	MOV	AL,5			; shutdown status 5: just return far
	OUT	71H,AL			; port 71H: read/write CMOS byte
	MOV	AL,0FEH			; a magic cookie, causes 80286 reset
	OUT	64H,AL			; port 64H is connected to the keyboard
	HLT
$SH001:	JMP	$SH001			; wait for reset
SHUTDOWN	ENDP

______________________________________________________________________

Finally, here is the code executed upon returning from protected mode.
The only thing restored is CS:IP.  Interrupts are disabled.

BACK:	MOV	AX,REALDATA		; re-establish DS
	MOV	DS,AX
	MOV	SS,SAVED_SS		; restore the stack
	MOV	SP,SAVED_SP
	MOV	AL,0BCH	; mask to restore keyboard, timer, and disk interrupts
	OUT	21H,AL	; Port 21H talks to the 8259A interrupt controller
	STI		; finally!


-------------------------
Kenneth Ballou		(ballou@bosco.berkeley.edu)