; NCR 53c810 driver, main script
; Sponsored by 
;	iX Multiuser Multitasking Magazine
;	hm@ix.de
;
; Copyright 1993, Drew Eckhardt
;      Visionary Computing 
;      (Unix and Linux consulting and custom programming)
;      drew@Colorado.EDU
;      +1 (303) 786-7975
;
; TolerANT and SCSI SCRIPTS are registered trademarks of NCR Corporation.
;
; PRE-ALPHA
;
; For more information, please consult 
;
; NCR 53C810
; PCI-SCSI I/O Processor
; Data Manual
;
; NCR 53C710 
; SCSI I/O Processor
; Programmers Guide
;
; NCR Microelectronics
; 1635 Aeroplaza Drive
; Colorado Springs, CO 80916
; 1+ (719) 578-3400
;
; Toll free literature number
; +1 (800) 334-5454
;
; IMPORTANT : This code is self modifying due to the limitations of 
;	the NCR53c7,8xx series chips.  Persons debugging this code with
;	the remote debugger should take this into account, and NOT set
;	breakpoints in modified instructions.
;
;
; Design:
; The NCR53c7x0 family of SCSI chips are busmasters with an onboard 
; microcontroller using a simple instruction set.   
;
; So, to minimize the effects of interrupt latency, and to maximize 
; throughput, this driver offloads the practical maximum amount 
; of processing to the SCSI chip while still maintaining a common
; structure.
;
; Where tradeoffs were needed between efficiency on the older
; chips and the newer NCR53c800 series, the NCR53c800 series 
; was chosen.
;
; While the NCR53c700 and NCR53c700-66 lacked the facilities to fully
; automate SCSI transfers without host processor intervention, this 
; isn't the case with the NCR53c710 and newer chips which allow 
;
; - reads and writes to the internal registers from within the SCSI
; 	scripts, allowing the SCSI SCRIPTS(tm) code to save processor
; 	state so that multiple threads of execution are possible, and also
; 	provide an ALU for loop control, etc.
; 
; - table indirect addressing for some instructions. This allows 
;	pointers to be located relative to the DSA ((Data Structure
;	Address) register.
;
; These features make it possible to implement a mailbox style interface,
; where the same piece of code is run to handle I/O for multiple threads
; at once minimizing our need to relocate code.  Since the NCR53c700/
; NCR53c800 series have a unique combination of features, making a 
; a standard ingoing/outgoing mailbox system, costly, I've modified it.
;
; - Commands are stored in a linked list, rather than placed in 
; 	arbitrary mailboxes.  This simplifies the amount of processing
;	that must be done by the NCR53c810.
;
; - Mailboxes are a mixture of code and data.  This lets us greatly
; 	simplify the NCR53c810 code and do things that would otherwise
;	not be possible.

;
; Note : the DSA structures must be aligned on 32 bit boundaries,
; since the source and destination of MOVE MEMORY instructions 
; must share the same alignment and this is the alignment of the
; NCR registers.
;

ABSOLUTE dsa_temp_jump_resume = 0	; Patch to dsa_jump_resume
    	    	    	    	    	; 	in current dsa
ABSOLUTE dsa_temp_lun = 0		; Patch to lun for current dsa
ABSOLUTE dsa_temp_dsa_next = 0		; Patch to dsa next for current dsa
ABSOLUTE dsa_temp_sync = 0		; Patch to address of per-target
					;	sync routine
ABSOLUTE dsa_temp_target = 0		; Patch to id for current dsa


#if (CHIP != 700) && (CHIP != 70066)
ENTRY dsa_code_template
dsa_code_template:

; Define DSA structure used for mailboxes

; wrong_dsa loads the DSA register with the value of the dsa_next
; field.
;
wrong_dsa:
;		Patch the MOVE MEMORY INSTRUCTION such that 
;		the destination address is that of the OLD next
;		pointer.
	MOVE MEMORY 4, dsa_temp_dsa_next, reselected_ok + 8

	MOVE dmode_memory_to_ncr TO DMODE	
	MOVE MEMORY 4, dsa_temp_dsa_next, addr_scratch
	MOVE dmode_memory_to_memory TO DMODE
	CALL scratch_to_dsa
	JUMP reselected_check_next

ABSOLUTE dsa_check_reselect = 0
; dsa_check_reselect determines weather or not the current target and
; lun match the current DSA
ENTRY dsa_code_check_reselect
dsa_code_check_reselect:
	MOVE SSID TO SFBR		; SSID contains 3 bit target ID
	JUMP REL (wrong_dsa), IF NOT dsa_temp_target, AND MASK 7
	MOVE dmode_memory_to_ncr TO DMODE
	MOVE MEMORY 1, reselected_identify, addr_sfbr
	JUMP REL (wrong_dsa), IF NOT dsa_temp_lun, AND MASK 7
	MOVE dmode_memory_to_memory TO DMODE
;		Patch the MOVE MEMORY INSTRUCTION such that
;		the source address is that of this dsas
;		next pointer.
	MOVE MEMORY 4, dsa_temp_dsa_next, reselected_ok + 4
	CALL reselected_ok
	CALL dsa_temp_sync	
ENTRY dsa_jump_resume
dsa_jump_resume:
	JUMP 0				; Jump to resume address
ENTRY dsa_zero
dsa_zero:
	MOVE dmode_ncr_to_memory TO DMODE			; 8
	MOVE MEMORY 4, addr_temp, dsa_temp_jump_resume		; 16	
	MOVE dmode_memory_to_memory TO DMODE			; 28
	JUMP dsa_schedule					; 36
ENTRY dsa_code_template_end
dsa_code_template_end:

; Perform sanity check for dsa_fields_start == dsa_code_template_end - 
; dsa_zero, puke.

ABSOLUTE dsa_fields_start =  36	; Sanity marker
				; 	pad 12
ABSOLUTE dsa_next = 48		; len 4 Next DSA
 				; del 4 Previous DSA address
ABSOLUTE dsa_cmnd = 56		; len 4 Scsi_Cmnd * for this thread.
ABSOLUTE dsa_select = 60	; len 4 Device ID, Period, Offset for 
			 	;	table indirect select
ABSOLUTE dsa_msgout = 64	; len 8 table indirect move parameter for 
				;       select message
ABSOLUTE dsa_cmdout = 72	; len 8 table indirect move parameter for 
				;	command
ABSOLUTE dsa_dataout = 80	; len 4 code pointer for dataout
ABSOLUTE dsa_datain = 84	; len 4 code pointer for datain
ABSOLUTE dsa_msgin = 88		; len 8 table indirect move for msgin
ABSOLUTE dsa_status = 96 	; len 8 table indirect move for status byte
ABSOLUTE dsa_msgout_other = 104	; len 8 table indirect for normal message out
				; (Synchronous transfer negotiation, etc).
ABSOLUTE dsa_end = 112

; Linked lists of DSA structures
ABSOLUTE issue_dsa_head = 0	; Linked list of DSAs to issue
ABSOLUTE reconnect_dsa_head = 0	; Link list of DSAs which can reconnect

; These select the source and destination of a MOVE MEMORY instruction
ABSOLUTE dmode_memory_to_memory = 0x0
ABSOLUTE dmode_memory_to_ncr = 0x0
ABSOLUTE dmode_ncr_to_memory = 0x0
ABSOLUTE dmode_ncr_to_ncr = 0x0

ABSOLUTE addr_scratch = 0x0
ABSOLUTE addr_sfbr = 0x0
ABSOLUTE addr_temp = 0x0
#endif /* CHIP != 700 && CHIP != 70066 */

; Interrupts - 
; MSB indicates type
; 0	handle error condition
; 1 	handle message 
; 2 	handle normal condition
; 3	debugging interrupt
; 4 	testing interrupt 
; Next byte indicates specific error

; XXX not yet implemented, I'm not sure if I want to - 
; Next byte indicates the routine the error occurred in
; The LSB indicates the specific place the error occurred
 
ABSOLUTE int_err_unexpected_phase = 0x00000000	; Unexpected phase encountered
ABSOLUTE int_err_selected = 0x00010000		; SELECTED (nee RESELECTED)
ABSOLUTE int_err_unexpected_reselect = 0x00020000 
ABSOLUTE int_err_check_condition = 0x00030000	
ABSOLUTE int_err_no_phase = 0x00040000
ABSOLUTE int_msg_wdtr = 0x01000000		; WDTR message received
ABSOLUTE int_msg_sdtr = 0x01010000		; SDTR received
ABSOLUTE int_msg_1 = 0x01020000			; single byte special message
						; received

ABSOLUTE int_norm_select_complete = 0x02000000	; Select complete, reprogram
						; registers.
ABSOLUTE int_norm_reselect_complete = 0x02010000	; Nexus established
ABSOLUTE int_norm_command_complete = 0x02020000 ; Command complete
ABSOLUTE int_norm_disconnected = 0x02030000	; Disconnected 
ABSOLUTE int_norm_aborted =0x02040000		; Aborted *dsa
ABSOLUTE int_norm_reset = 0x02050000		; Generated BUS reset.
ABSOLUTE int_debug_break = 0x03000000		; Break point
ABSOLUTE int_debug_scheduled = 0x03010000	; new I/O scheduled 
ABSOLUTE int_debug_idle = 0x03020000		; scheduler is idle
ABSOLUTE int_debug_dsa_loaded = 0x03030000	; dsa reloaded
ABSOLUTE int_debug_reselected = 0x03040000	; NCR reselected
ABSOLUTE int_debug_head = 0x03050000		; issue head overwritten

ABSOLUTE int_test_1 = 0x04000000		; Test 1 complete
ABSOLUTE int_test_2 = 0x04010000		; Test 2 complete
ABSOLUTE int_test_3 = 0x04020000		; Test 3 complete
						
EXTERNAL NCR53c7xx_msg_abort 		; Pointer to abort message
EXTERNAL NCR53c7xx_msg_reject 		; Pointer to reject message
EXTERNAL NCR53c7xx_zero			; long with zero in it, use for source
EXTERNAL NCR53c7xx_sink			; long to dump worthless data in

; Pointer to final bytes of multi-byte messages
ABSOLUTE msg_buf = 0

; Pointer to holding area for reselection information
ABSOLUTE reselected_identify = 0
ABSOLUTE reselected_tag = 0

; Request sense command pointer, its a 6 byte command, should
; be constant for all commands since we always want 16 bytes of 
; sense and we don't need to change any fields as we did under 
; SCSI-I when we actually cared about the LUN field.
;EXTERNAL NCR53c7xx_sense		; Request sense command

#if (CHIP != 700) && (CHIP != 70066)
; dsa_schedule  
; PURPOSE : after a DISCONNECT message has been received, and pointers
;	saved, insert the current DSA structure at the head of the 
; 	disconnected queue and fall through to the scheduler.
;
; CALLS : OK
;
; INPUTS : dsa - current DSA structure, reconnect_dsa_head - list
;	of disconnected commands
;
; MODIFIES : SCRATCH, reconnect_dsa_head
; 
; EXITS : always passes control to schedule

ENTRY dsa_schedule
dsa_schedule:

;
; Calculate the address of the next pointer within the DSA 
; structure of the command that is currently disconnecting
;
    CALL dsa_to_scratch
; XXX - we need to deal with the NCR53c710, which lacks an add with
;	carry instruction, by moving around the DSA alignment to avoid
; 	carry in situations like this.
    MOVE SCRATCH0 + dsa_next TO SCRATCH0
    MOVE SCRATCH1 + 0 TO SCRATCH1 WITH CARRY
    MOVE SCRATCH2 + 0 TO SCRATCH2 WITH CARRY
    MOVE SCRATCH3 + 0 TO SCRATCH3 WITH CARRY

; Point the next field of this DSA structure at the current disconnected 
; list
    MOVE dmode_ncr_to_memory TO DMODE
    MOVE MEMORY 4, addr_scratch, dsa_schedule_insert + 8
    MOVE dmode_memory_to_memory TO DMODE
dsa_schedule_insert:
    MOVE MEMORY 4, reconnect_dsa_head, 0 

; And update the head pointer.
    CALL dsa_to_scratch
    MOVE dmode_ncr_to_memory TO DMODE	
    MOVE MEMORY 4, addr_scratch, reconnect_dsa_head
    MOVE dmode_memory_to_memory TO DMODE
    WAIT DISCONNECT

; schedule
; PURPOSE : schedule a new I/O once the bus is free by putting the 
;	address of the next DSA structure in the DSA register.
;
; INPUTS : issue_dsa_head - list of new commands
;
; CALLS : OK
;
; MODIFIES : SCRATCH, DSA 
;
; EXITS : if the issue_dsa_head pointer is non-NULL, control
;	is passed to select.  Otherwise, control is passed to 
;	wait_reselect.


ENTRY schedule
schedule:
    ; Point DSA at the current head of the issue queue.
    MOVE dmode_memory_to_ncr TO DMODE
    MOVE MEMORY 4, issue_dsa_head, addr_scratch
    MOVE dmode_memory_to_memory TO DMODE

    CALL scratch_to_dsa

#if 0
    INT int_debug_dsa_loaded
#endif
    ; Check for a null pointer.
    MOVE DSA0 TO SFBR
    JUMP select, IF NOT 0
    MOVE DSA1 TO SFBR
    JUMP select, IF NOT 0
    MOVE DSA2 TO SFBR
    JUMP select, IF NOT 0
    MOVE DSA3 TO SFBR
    JUMP wait_reselect, IF 0

    
#else /* (CHIP != 700) && (CHIP != 70066) */
#endif /* (CHIP != 700) && (CHIP != 70066) */

;
; select
;
; PURPOSE : establish a nexus for the SCSI command referenced by DSA.
;	On success, the current DSA structure is removed from the issue 
;	queue.  Usually, this is entered as a fall-through from schedule,
;	although the contingent allegiance handling code will write
;	the select entry address to the DSP to restart a command as a 
;	REQUEST SENSE.  A message is sent (usually IDENTIFY, although
;	additional SDTR or WDTR messages may be sent).  COMMAND OUT
;	is handled.
;
; INPUTS : DSA - SCSI command, issue_dsa_head
;
; CALLS : OK
;
; MODIFIES : SCRATCH, issue_dsa_head
;
; EXITS : on reselection or selection, go to select_failed
;	otherwise, fall through to data_transfer.  If a MSG_IN
;	phase occurs before 
;

ENTRY select
select:

#if 0
    INT int_debug_scheduled
#endif
    CLEAR TARGET

; XXX
;
; In effect, SELECTION operations are backgrounded, with execution
; continuing until code which waits for REQ or a fatal interrupt is 
; encountered.
;
; So, for more performance, we could overlap the code which removes 
; the command from the NCRs issue queue with the selection, but 
; at this point I don't want to deal with the error recovery.
;

#if (CHIP != 700) && (CHIP != 70066)
    SELECT ATN FROM dsa_select, select_failed
    JUMP select_msgout, WHEN MSG_OUT
ENTRY select_msgout
select_msgout:
    MOVE FROM dsa_msgout, WHEN MSG_OUT
#else
ENTRY select_msgout
    SELECT ATN 0, select_failed
select_msgout:
    MOVE 0, 0, WHEN MSGOUT
#endif

#if (CHIP != 700) && (CHIP != 70066)

    ; Calculate address of dsa_next field

    CALL dsa_to_scratch

    MOVE SCRATCH0 + dsa_next TO SCRATCH0
    MOVE SCRATCH1 + 0 TO SCRATCH1 WITH CARRY
    MOVE SCRATCH2 + 0 TO SCRATCH2 WITH CARRY
    MOVE SCRATCH3 + 0 TO SCRATCH3 WITH CARRY

    ; Patch memory to memory move
    move dmode_ncr_to_memory TO DMODE
    MOVE MEMORY 4, addr_scratch, issue_remove + 4


    ; And rewrite the issue_dsa_head pointer.
    MOVE dmode_memory_to_memory TO DMODE
issue_remove:
;	The actual UPDATE of the issue_dsa_head variable is 
; 	atomic, with all of the setup code being irrelevant to
;	weather the updated value being the old or new contents of 
;	dsa_next field.
;
; 	To insure synchronization, the host system merely needs to 
;	do a XCHG instruction with interrupts disabled on the 
;	issue_dsa_head memory address.
;
;	The net effect will be that the XCHG instruction will return
;	either a non-NULL value, indicating that the NCR chip will not
;	go into the idle loop when this command DISCONNECTS, or a NULL
;	value indicating that the NCR wrote first and that the Linux
;	code must rewrite the issue_dsa_head pointer and set SIG_P.
;	


    MOVE MEMORY 4, 0, issue_dsa_head
#endif /* (CHIP != 700) && (CHIP != 70066) */
#if 0
INT int_debug_head
#endif

; After a successful selection, we should get either a CMD phase or 
; some transfer request negotiation message.

    JUMP cmdout, WHEN CMD
    INT int_err_unexpected_phase, WHEN NOT MSG_IN 

select_msg_in:
    CALL msg_in, WHEN MSG_IN
    JUMP select_msg_in, WHEN MSG_IN

cmdout:
    INT int_err_unexpected_phase, WHEN NOT CMD
#if (CHIP == 700)
    INT int_norm_selected
#endif
ENTRY cmdout_cmdout
cmdout_cmdout:
#if (CHIP != 700) && (CHIP != 70066)
    MOVE FROM dsa_cmdout, WHEN CMD
#else
    MOVE 0, 0, WHEN CMD
#endif /* (CHIP != 700) && (CHIP != 70066) */

;
; data_transfer  
; other_transfer
;
; PURPOSE : handle the main data transfer for a SCSI command in 
;	two parts.  In the first part, data_transfer, DATA_IN
;	and DATA_OUT phases are allowed, with the user provided
;	code (usually dynamically generated based on the scatter/gather
;	list associated with a SCSI command) called to handle these 
;	phases.
;
;	On completion, the user code passes control to other_transfer
;	which causes DATA_IN and DATA_OUT to result in unexpected_phase
;	interrupts so that data overruns may be trapped.
;
; INPUTS : DSA - SCSI command
;
; CALLS : OK
;
; MODIFIES : SCRATCH
;
; EXITS : if STATUS IN is detected, signifying command completion,
;	the NCR jumps to command_complete.  If MSG IN occurs, a 
;	CALL is made to msg_in.  Otherwise, other_transfer runs in 
;	an infinite loop.
;	

data_transfer:
    INT int_err_unexpected_phase, WHEN CMD
    CALL msg_in, WHEN MSG_IN
    INT int_err_unexpected_phase, WHEN MSG_OUT
    JUMP do_dataout, WHEN DATA_OUT
    JUMP do_datain, WHEN DATA_IN
    JUMP command_complete, WHEN STATUS
    JUMP data_transfer

;
; On NCR53c700 and NCR53c700-66 chips, do_dataout/do_datain are fixed up 
; whenever the nexus changes so it can point to the correct routine for 
; that command.
;

#if (CHIP != 700) && (CHIP != 70066)
; Nasty jump to dsa->dataout
do_dataout:
    CALL dsa_to_scratch
    MOVE SCRATCH0 + dsa_dataout TO SCRATCH0	
    MOVE SCRATCH1 + 0 TO SCRATCH1 WITH CARRY 
    MOVE SCRATCH2 + 0 TO SCRATCH2 WITH CARRY 
    MOVE SCRATCH3 + 0 TO SCRATCH3 WITH CARRY 
    MOVE dmode_ncr_to_memory TO DMODE
    MOVE MEMORY 4, addr_scratch, dataout_to_jump + 4
    MOVE dmode_memory_to_memory TO DMODE
dataout_to_jump:
    MOVE MEMORY 4, 0, dataout_jump + 4 
dataout_jump:
    JUMP 0

; Nasty jump to dsa->dsain
do_datain:
    CALL dsa_to_scratch
    MOVE SCRATCH0 + dsa_datain TO SCRATCH0	
    MOVE SCRATCH1 + 0 TO SCRATCH1 WITH CARRY 
    MOVE SCRATCH2 + 0 TO SCRATCH2 WITH CARRY 
    MOVE SCRATCH3 + 0 TO SCRATCH3 WITH CARRY 
    MOVE dmode_ncr_to_memory TO DMODE
    MOVE MEMORY 4, addr_scratch, datain_to_jump + 4
    MOVE dmode_memory_to_memory TO DMODE		
datain_to_jump:
    MOVE MEMORY 4, 0, datain_jump + 4
datain_jump:
    JUMP 0
#endif /* (CHIP != 700) && (CHIP != 70066) */

;
; other_transfer is exported because it is referenced by dynamically 
; generated code.
;
ENTRY other_transfer
other_transfer:
#if 0
    INT 0x03ffdead
#endif
    INT int_err_unexpected_phase, WHEN CMD
    CALL msg_in, WHEN MSG_IN 
    INT int_err_unexpected_phase, WHEN MSG_OUT
    INT int_err_unexpected_phase, WHEN DATA_OUT
    INT int_err_unexpected_phase, WHEN DATA_IN
    JUMP command_complete, WHEN STATUS
    JUMP other_transfer

;
; msg_in
; munge_msg
;
; PURPOSE : process messages from a target.  msg_in is called when the 
;	caller hasn't read the first byte of the message.  munge_message
;	is called when the caller has read the first byte of the message,
;	and left it in SFBR.
;
;	Various int_* interrupts are generated when the host system
;	needs to intervene, as is the case with SDTR, WDTR, and
;	INITIATE RECOVERY messages.
;
;	When the host system handles one of these interrupts,
;	it can respond by reentering at reject_message, 
;	which rejects the message and returns control to
;	the caller of msg_in or munge_msg, accept_message
;	which clears ACK and returns control, or reply_message
;	which sends the message pointed to by the DSA 
;	msgout_other table indirect field.
;
;	DISCONNECT messages are handled by moving the command
;	to the reconnect_dsa_queue.
;
;	SAVE DATA POINTER and RESTORE DATA POINTERS are currently 
;	treated as NOPS. 
;
; INPUTS : DSA - SCSI COMMAND, SFBR - first byte of message (munge_msg
;	only)
;
; CALLS : NO.  The TEMP register isn't backed up to allow nested calls.
;
; MODIFIES : SCRATCH, DSA on DISCONNECT
;
; EXITS : On receipt of SAVE DATA POINTER, RESTORE POINTERS,
;	and normal return from message handlers running under
;	Linux, control is returned to the caller.  Receipt
;	of DISCONNECT messages pass control to dsa_schedule.
;
ENTRY msg_in
msg_in:
    MOVE 1, msg_buf, WHEN MSG_IN

munge_msg:
    JUMP munge_extended, IF 0x01		; EXTENDED MESSAGE
    JUMP munge_2, IF 0x20, AND MASK 0xdf	; two byte message
;
; I've seen a handful of broken SCSI devices which fail to issue
; a SAVE POINTERS message before disconnecting in the middle of 
; a transfer, assuming that the DATA POINTER will be implicitly 
; restored.  So, we treat the SAVE DATA POINTER message as a NOP.
;
; I've also seen SCSI devices which don't issue a RESTORE DATA
; POINTER message and assume that thats implicit.
;
    JUMP accept_message, IF 0x02		; SAVE DATA POINTER
    JUMP accept_message, IF 0x03		; RESTORE POINTERS 
    JUMP munge_disconnect, IF 0x04		; DISCONNECT
    INT int_msg_1, IF 0x07			; MESSAGE REJECT
    INT int_msg_1, IF 0x0f			; INITIATE RECOVERY
    JUMP reject_message

munge_2:
    JUMP reject_message

munge_save_data_pointer:
    CLEAR ACK
    RETURN

munge_disconnect:
    MOVE SCNTL2 & 0x7f TO SCNTL2
    CLEAR ACK

#if (CHIP != 700) && (CHIP != 70066)
; Pass control to the DSA routine.  Note that we can not call
; dsa_to_scratch here because that would clobber temp, which 
; we must preserve.
    MOVE DSA0 TO SFBR
    MOVE SFBR TO SCRATCH0
    MOVE DSA1 TO SFBR
    MOVE SFBR TO SCRATCH1
    MOVE DSA2 TO SFBR
    MOVE SFBR TO SCRATCH2
    MOVE DSA3 TO SFBR
    MOVE SFBR TO SCRATCH3

    MOVE dmode_ncr_to_memory TO DMODE
    MOVE MEMORY 4, addr_scratch, jump_to_dsa + 4
    MOVE dmode_memory_to_memory TO DMODE
jump_to_dsa:
    JUMP 0
#else
    WAIT DISCONNECT
    INT int_norm_disconnected
#endif

munge_extended:
    CLEAR ACK
    INT int_err_unexpected_phase, WHEN NOT MSG_IN
    MOVE 1, msg_buf + 1, WHEN MSG_IN
    JUMP munge_extended_2, IF 0x02
    JUMP munge_extended_3, IF 0x03 
    JUMP reject_message

munge_extended_2:
    CLEAR ACK
    MOVE 1, msg_buf + 2, WHEN MSG_IN
    JUMP reject_message, IF NOT 0x02	; Must be WDTR
    CLEAR ACK
    MOVE 1, msg_buf + 3, WHEN MSG_IN
    INT int_msg_wdtr

munge_extended_3:
    CLEAR ACK
    MOVE 1, msg_buf + 2, WHEN MSG_IN
    JUMP reject_message, IF NOT 0x01	; Must be SDTR
    CLEAR ACK
    MOVE 2, msg_buf + 3, WHEN MSG_IN
    INT int_msg_sdtr

ENTRY reject_message
reject_message:
    SET ATN
    CLEAR ACK
    MOVE 1, NCR53c7xx_msg_reject, WHEN MSG_OUT
    RETURN

ENTRY accept_message
accept_message:
    CLEAR ACK
    RETURN

ENTRY respond_message
msg_respond:
    SET ATN
    CLEAR ACK
    MOVE FROM dsa_msgout_other, WHEN MSG_OUT
    RETURN

;
; command_complete
;
; PURPOSE : handle command termination when STATUS IN is detected by reading
;	a status byte followed by a command termination message. 
;
;	Normal termination results in an INTFLY instruction, and 
;	the host system can pick out which command terminated by 
;	examining the MESSAGE and STATUS buffers of all currently 
;	executing commands;
;
;	Abnormal (CHECK_CONDITION) termination results in an
;	int_err_check_condition interrupt so that a REQUEST SENSE
;	command can be issued out-of-order so that no other command
;	clears the contingent allegiance condition.
;	
;
; INPUTS : DSA - command	
;
; CALLS : OK
;
; EXITS : On successful termination, control is passed to schedule.
;	On abnormal termination, the user will usually modify the 
;	DSA fields and corresponding buffers and return control
;	to select.
;

ENTRY command_complete
command_complete:
    MOVE FROM dsa_status, WHEN STATUS
#if (CHIP != 700) && (CHIP != 70066)
    MOVE SFBR TO SCRATCH0		; Save status
#endif /* (CHIP != 700) && (CHIP != 70066) */
ENTRY command_complete_msgin
command_complete_msgin:
    MOVE FROM dsa_msgin, WHEN MSG_IN
; Indicate that we should be expecting a disconnect
    MOVE SCNTL2 & 0x7f TO SCNTL2
    CLEAR ACK
#if (CHIP != 700) && (CHIP != 70066)
    MOVE SCRATCH0 TO SFBR			

;
; The SCSI specification states that when a UNIT ATTENTION condition
; is pending, as indicated by a CHECK CONDITION status message,
; the target shall revert to asynchronous transfers.  Since
; synchronous transfers parameters are maintained on a per INITIATOR/TARGET 
; basis, and returning control to our scheduler could work on a command
; running on another lun on that target using the old parameters, we must
; interrupt the host processor to get them changed, or change them ourselves.
;
; Once SCSI-II tagged queueing is implemented, things will be even more
; hairy, since contingent allegiance conditions exist on a per-target/lun
; basis, and issuing a new command with a different tag would clear it.
; In these cases, we must interrupt the host processor to get a request 
; added to the HEAD of the queue with the request sense command, or we
; must automatically issue the request sense command.

#if 0
    JUMP command_failed, IF 0x02
#endif
    INTFLY
#endif /* (CHIP != 700) && (CHIP != 70066) */
    WAIT DISCONNECT
#if (CHIP != 700) && (CHIP != 70066)
    JUMP schedule
command_failed:
    WAIT DISCONNECT
    INT int_err_check_condition
#else
    INT int_norm_command_complete
#endif

;
; wait_reselect
;
; PURPOSE : This is essentially the idle routine, where control lands
;	when there are no new processes to schedule.  wait_reselect
;	waits for reselection, selection, and new commands.
;
;	When a successful reselection occurs, with the aid 
;	of fixed up code in each DSA, wait_reselect walks the 
;	reconnect_dsa_queue, asking each dsa if the target ID
;	and LUN match its.
;
;	If a match is found, a call is made back to reselected_ok,
;	which through the miracles of self modifying code, extracts
;	the found DSA from the reconnect_dsa_queue and then 
;	returns control to the DSAs thread of execution.
;
; INPUTS : NONE
;
; CALLS : OK
;
; MODIFIES : DSA,
;
; EXITS : On successful reselection, control is returned to the 
;	DSA which called reselected_ok.  If the WAIT RESELECT
;	was interrupted by a new commands arrival signaled by 
;	SIG_P, control is passed to schedule.  If the NCR is 
;	selected, the host system is interrupted with an 
;	int_err_selected which is usually responded to by
;	setting DSP to the target_abort address.
    
wait_reselect:
#if 0
    int int_debug_idle
#endif
    WAIT RESELECT wait_reselect_failed

reselected:
    ; Read all data needed to reestablish the nexus - 
    MOVE 1, reselected_identify, WHEN MSG_IN
#if (CHIP != 700) && (CHIP != 70066)
    ; Well add a jump to here after some how determining that 
    ; tagged queueing isn't in use on this device.
reselected_notag:    
    MOVE MEMORY 1, NCR53c7xx_zero, reselected_tag

#ifdef DEBUG
    int int_debug_reselected
#endif

    ; Point DSA at the current head of the disconnected queue.
    MOVE dmode_memory_to_ncr  TO DMODE
    MOVE MEMORY 4, reconnect_dsa_head, addr_scratch
    MOVE dmode_memory_to_memory TO DMODE
    CALL scratch_to_dsa

    ; Fix the update-next pointer so that the reconnect_dsa_head
    ; pointer is the one that will be updated if this DSA is a hit 
    ; and we remove it from the queue.

    MOVE MEMORY 4, reconnect_dsa_head, reselected_ok + 8

ENTRY reselected_check_next
reselected_check_next:
    ; Check for a NULL pointer.
    MOVE DSA0 TO SFBR
    JUMP reselected_not_end, IF NOT 0
    MOVE DSA1 TO SFBR
    JUMP reselected_not_end, IF NOT 0
    MOVE DSA2 TO SFBR
    JUMP reselected_not_end, IF NOT 0
    MOVE DSA3 TO SFBR
    JUMP reselected_not_end, IF NOT 0
    INT int_err_unexpected_reselect

reselected_not_end:
    MOVE DSA0 TO SFBR
    ;
    ; XXX the ALU is only eight bits wide, and the assembler
    ; wont do the dirt work for us.  As long as dsa_check_reselect
    ; is negative, we need to sign extend with 1 bits to the full
    ; 32 bit width os the address.
    ;
    ; A potential work around would be to have a known alignment 
    ; of the DSA structure such that the base address plus 
    ; dsa_check_reselect doesn't require carrying from bytes 
    ; higher than the LSB.
    ;

    MOVE SFBR + dsa_check_reselect TO SCRATCH0
    MOVE DSA1 TO SFBR
    MOVE SFBR + 0xff TO SCRATCH1 WITH CARRY
    MOVE DSA2 TO SFBR
    MOVE SFBR + 0xff TO SCRATCH2 WITH CARRY
    MOVE DSA3 TO SFBR
    MOVE SFBR + 0xff TO SCRATCH3 WITH CARRY

    MOVE dmode_ncr_to_memory TO DMODE
    MOVE MEMORY 4, addr_scratch, reselected_check + 4
    MOVE dmode_memory_to_memory TO DMODE
reselected_check:
    JUMP 0


;
;
reselected_ok:
    MOVE MEMORY 4, 0, 0				; Patched : first word
						; 	is this successful 
						; 	dsa_next
						; Second word is 
						;	unsuccessful dsa_next
    CLEAR ACK					; Accept last message
    RETURN					; Return control to where
#else
    INT int_norm_reselected
#endif /* (CHIP != 700) && (CHIP != 70066) */

selected:
    INT int_err_selected;

;
; A select or reselect failure can be caused by one of two conditions : 
; 1.  SIG_P was set.  This will be the case if the user has written
;	a new value to a previously NULL head of the issue queue.
;
; 2.  The NCR53c810 was selected or reselected by another device.
; 

wait_reselect_failed:
; Reading CTEST2 clears the SIG_P bit in the ISTAT register.
    MOVE CTEST2 & 0x40 TO SFBR	
    JUMP selected, IF NOT 0x40
    JUMP schedule

select_failed:
    MOVE ISTAT & 0x20 TO SFBR
    JUMP reselected, IF NOT 0x20
    MOVE ISTAT & 0xdf TO ISTAT
    JUMP schedule

;
; test_1
; test_2
;
; PURPOSE : run some verification tests on the NCR.  test_1
;	copies test_src to test_dest and interrupts the host
;	processor, testing for cache coherency and interrupt
; 	problems in the processes.
;
;	test_2 runs a command with offsets relative to the 
;	DSA on entry, and is useful for miscellaneous experimentation.
;

; Verify that interrupts are working correctly and that we don't 
; have a cache invalidation problem.

ABSOLUTE test_src = 0, test_dest = 0
ENTRY test_1
test_1:
    MOVE MEMORY 4, test_src, test_dest
    INT int_test_1

;
; Run arbitrary commands, with test code establishing a DSA
;
 
ENTRY test_2
test_2:
    CLEAR TARGET
    SELECT ATN FROM 0, test_2_fail
    JUMP test_2_msgout, WHEN MSG_OUT
ENTRY test_2_msgout
test_2_msgout:
    MOVE FROM 8, WHEN MSG_OUT
    MOVE FROM 16, WHEN CMD 
    MOVE FROM 24, WHEN DATA_IN
    MOVE FROM 32, WHEN STATUS
    MOVE FROM 40, WHEN MSG_IN
    MOVE SCNTL2 & 0x7f TO SCNTL2
    CLEAR ACK
    WAIT DISCONNECT
test_2_fail:
    INT int_test_2

ENTRY debug_break
debug_break:
    INT int_debug_break

;
; initiator_abort
; target_abort
;
; PURPOSE : Abort the currently established nexus from with initiator
;	or target mode.
;
;  

ENTRY target_abort
target_abort:
    SET TARGET
    DISCONNECT
    CLEAR TARGET
    JUMP schedule
    
ENTRY initiator_abort
initiator_abort:
    SET ATN
; In order to abort the currently established nexus, we 
; need to source/sink up to one byte of data in any SCSI phase, 
; since the phase cannot change until REQ transitions 
; false->true
    JUMP no_eat_cmd, WHEN NOT CMD
    MOVE 1, NCR53c7xx_zero, WHEN CMD
no_eat_cmd:
    JUMP no_eat_msg, WHEN NOT MSG_IN
    MOVE 1, NCR53c7xx_sink, WHEN MSG_IN
no_eat_msg:
    JUMP no_eat_data, WHEN NOT DATA_IN
    MOVE 1, NCR53c7xx_sink, WHEN DATA_IN
no_eat_data:
    JUMP no_eat_status, WHEN NOT STATUS
    MOVE 1, NCR53c7xx_sink, WHEN STATUS
no_eat_status:
    JUMP no_source_data, WHEN NOT DATA_OUT
    MOVE 1, NCR53c7xx_zero, WHEN DATA_OUT
no_source_data:
;
; If DSP points here, and a phase mismatch is encountered, we need to 
; do a bus reset.
;
    MOVE 1, NCR53c7xx_msg_abort, WHEN MSG_OUT
    INT int_norm_aborted

;
; dsa_to_scratch
; scratch_to_dsa
;
; PURPOSE :
; 	The NCR chips cannot do a move memory instruction with the DSA register 
; 	as the source or destination.  So, we provide a couple of subroutines
; 	that let us switch between the DSA register and scratch register.
;
; 	Memory moves to/from the DSPS  register also don't work, but we 
; 	don't use them.
;
;

 
dsa_to_scratch:
    MOVE DSA0 TO SFBR
    MOVE SFBR TO SCRATCH0
    MOVE DSA1 TO SFBR
    MOVE SFBR TO SCRATCH1
    MOVE DSA2 TO SFBR
    MOVE SFBR TO SCRATCH2
    MOVE DSA3 TO SFBR
    MOVE SFBR TO SCRATCH3
    RETURN

scratch_to_dsa:
    MOVE SCRATCH0 TO SFBR
    MOVE SFBR TO DSA0
    MOVE SCRATCH1 TO SFBR
    MOVE SFBR TO DSA1
    MOVE SCRATCH2 TO SFBR
    MOVE SFBR TO DSA2
    MOVE SCRATCH3 TO SFBR
    MOVE SFBR TO DSA3
    RETURN
    
