repo_id
stringlengths 5
115
| size
int64 590
5.01M
| file_path
stringlengths 4
212
| content
stringlengths 590
5.01M
|
|---|---|---|---|
a2stuff/a2d
| 12,232
|
src/extras/awlaunch.system.s
|
;;; ************************************************************
;;; * *
;;; * * AW51Launcher - An AppleWorks File Loader * *
;;; * *
;;; * (For Use with BASIS.SYSTEM by John Brooks) *
;;; * *
;;; * Version 1.0 (for AppleWorks Version 5.1) *
;;; * by Hugh Hood (2018) *
;;; * [Based on prior works by Douglas Gum and Tom Hoover] *
;;; * *
;;; * - A SYSTEM File that Provides - *
;;; * *
;;; * 1. Receives the path and file name of a selected *
;;; * ADB ($19) / AWP ($1A) / ASP ($1B) / TXT ($04) *
;;; * file from BASIS.SYSTEM *
;;; * *
;;; * 2. Moves the passed path and file name to within *
;;; * an UltraMacros Task File compiled macro table *
;;; * *
;;; * 3. Moves the modified compiled macro table into *
;;; * place at $01/EF00 in Aux Memory for use by *
;;; * AppleWorks 5.1 *
;;; * *
;;; * 4. Launches APLWORKS.SYSTEM and instructs it use *
;;; * the compiled macro table previously moved *
;;; * into place instead of the default macro set *
;;; * *
;;; * 5. Upon starting AppleWorks, the UltraMacros code *
;;; * instructs AppleWorks to load the selected *
;;; * file to the AppleWorks Desktop, to leave the *
;;; * user in the file, and then to start the user's *
;;; * default macro set *
;;; * *
;;; * ************** *
;;; * *
;;; * * ASSUMPTIONS MADE BY AW51Launcher * *
;;; * (See ProDOS 8 Technical Reference *
;;; * Manual, Section 5.1.5.1) *
;;; * *
;;; * A. The full pathname to the selected file is *
;;; * passed at $2006+, per the startup protocol *
;;; * *
;;; * B. The full (or partial) pathname to this *
;;; * AW51Launcher system program is stored *
;;; * at $280 *
;;; * *
;;; * C. This AW51Launcher system program is located *
;;; * in the same directory as APLWORKS.SYSTEM *
;;; * *
;;; ************************************************************
;;; ============================================================
;;; Apple II DeskTop Integration
;;;
;;; * Conversion to ca65 syntax and A2D coding style
;;; * Looks on current vol in /<vol>/AW5/APLWORKS.SYSTEM
;;; * For further discussion, see:
;;; https://groups.google.com/g/comp.sys.apple2/c/lFRfyX0llhI
.include "../config.inc"
.include "apple2.inc"
.include "../inc/apple2.inc"
.include "../inc/macros.inc"
.include "../inc/prodos.inc"
.include "../common.inc"
MLIEntry := MLI
;;; AppleWorks
TaskStrup = $11B1+$1000 ; flag to NOT load default
;;; ============================================================
;;; Memory usage:
SYS_PATH := $280 ; populate for AppleWorks startup
IO_BUFFER := $800 ; used to load APLWORKS.SYSTEM
RELOC_TARGET := $1000 ; this code relocates here to run
PATHBUF := $1F00 ; populated with target path
PATHBUF2 := $1F80 ; temporary PREFIX
FILENAME := $1FF0 ; filename is stripped off
;;; ============================================================
.org PRODOS_SYS_START
;;; ============================================================
jmp Start
.byte $EE ; Protocol ID Byte #1
.byte $EE ; Protocol ID Byte #2
.byte $41 ; Buffer Length
path: .res $41,0
;;; ============================================================
Start:
;; Relocate down out of the way of the next system file
copy16 #reloc, STARTLO
copy16 #reloc+sizeof_reloc-1, ENDLO
copy16 #RELOC_TARGET, DESTINATIONLO
ldy #0
jsr MOVE
;; Stash path somewhere safe
ldx path
: lda path,x
and #$7F ; clear high bit (c/o Bitsy Bye)
sta PATHBUF,x
dex
bpl :-
;; Continue in relocated code
jmp RELOC_TARGET
;;; ============================================================
.proc reloc
.org ::RELOC_TARGET
jmp ConstructPath
;;; ============================================================
;;; ============================================================
str_aplworks_path:
PASCAL_STRING "AW5/APLWORKS.SYSTEM"
DEFINE_OPEN_PARAMS open_params, SYS_PATH, IO_BUFFER
DEFINE_READWRITE_PARAMS read_params, PRODOS_SYS_START, $FFFF
DEFINE_CLOSE_PARAMS close_params
DEFINE_GET_PREFIX_PARAMS prefix_params, PATHBUF2
DEFINE_QUIT_PARAMS quit_params
;;; ============================================================
;; * Construct a target path for AppleWorks.
;; * Try to load it. If we fail, just QUIT.
;; * If we were passed a path:
;; * Construct an absolute path using PREFIX.
;; * Split it into dir path and filename.
;; * Patch the macro block with it.
;; * Copy the macro block into AW.
;; * Poke AW to load the macro block.
;; * Invoke AppleWorks.
;; --------------------------------------------------
;; Construct a target path for APLWORKS.SYSTEM at $280
ConstructPath:
;; Append this system file's volume name
ldx #0
ldy #0
: iny
inx
lda SYS_PATH,y
and #$7F ; clear high bit (c/o Bitsy Bye)
sta SYS_PATH,x
cmp #'/'
bne :-
cpy #2
bcc :-
;; Append the relative path
ldy #0
: iny
inx
lda str_aplworks_path,y
sta SYS_PATH,x
cpy str_aplworks_path
bne :-
stx SYS_PATH
;; TODO: Consider GET_FILE_INFO call and checking file_type
;; --------------------------------------------------
;; Try to load APLWORKS.SYSTEM file
MLI_CALL OPEN, open_params
bcs quit
lda open_params::ref_num
sta read_params::ref_num
sta close_params::ref_num
MLI_CALL READ, read_params
pha
MLI_CALL CLOSE, close_params
pla
bcc CheckPath
quit: MLI_CALL QUIT, quit_params
brk
;;; ============================================================
;;; Check to see if we were passed a path. If so:
;;; * Construct an absolute path using PREFIX
;;; * Split it into dir path and filename
;;; * Patch the macro block with it
;;; * Copy the macro block into AW
CheckPath:
lda PATHBUF
bne :+
jmp LaunchAppleWorks ; no path, just launch as-is
:
;; Is `PATHBUF` absolute?
lda PATHBUF+1
cmp #'/'
beq SplitPath ; yes
;; Relative - make `PATHBUF` absolute using PREFIX
MLI_CALL GET_PREFIX, prefix_params
bcc :+
jmp LaunchAppleWorks ; TODO: or QUIT?
:
ldx PATHBUF2 ; `PATHBUF2` is PREFIX
ldy #0 ; Append `PATHBUF`
: iny
inx
lda PATHBUF,y
sta PATHBUF2,x
cpy PATHBUF
bne :-
stx PATHBUF2
: lda PATHBUF2,x ; Copy it into `PATHBUF`
sta PATHBUF,x
dex
bpl :-
;; --------------------------------------------------
;; Split `FILENAME` off of `PATHBUF`
SplitPath:
;; Find last '/'
ldx PATHBUF
: lda PATHBUF,x
cmp #'/'
beq :+
dex
bne :- ; always
: txa
pha ; index of last '/'
;; Copy filename out
ldy #0
: inx
iny
lda PATHBUF,x
sta FILENAME,y
cpx PATHBUF
bne :-
sty FILENAME
;; Update path length
pla ; index of last '/'
tax
dex
stx PATHBUF ; new length
;; --------------------------------------------------
;; Patch `PATHBUF` and `FILENAME` into macros
;; Patch `PATHBUF` into macros
lda #'"' ; " string end delimiter
ldy PATHBUF
sta PassedPath,y
: lda PATHBUF,y
sta PassedPath-1,y
dey
bne :-
;; Patch `FILENAME` into macros
lda #'"' ; " string end delimiter
ldy FILENAME
sta PassedName,y
: lda FILENAME,y
sta PassedName-1,y
dey
bne :-
;; --------------------------------------------------
;; Move macros to $EF00
.scope move_macros
sta ALTZPON
bit ROMIN ; Read ROM; write RAM
bit ROMIN
copy16 #macros, STARTLO
copy16 #macros+sizeof_macros-1, ENDLO
copy16 #$EF00, DESTINATIONLO
ldy #0
jsr MOVE
sta ALTZPOFF
bit ROMIN2 ; Read ROM; no write
.endscope ; move_macros
;; --------------------------------------------------
;; Set flag in SEG.UM to NOT load default macros.
lda #$01
sta TaskStrup
.assert * = LaunchAppleWorks, error, "fall through"
;;; ============================================================
LaunchAppleWorks:
jmp PRODOS_SYS_START
;;; ============================================================
;;; NOTE: This Macro Table Gets Moved to $01/EF00 (UM4.x)
;;; ============================================================
;;; This is a block of UltraMacro macros by Hugh Hood that
;;; load the specified file, passed in as a directory path
;;; and filename.
;;;
;;; Hugh Hood writes:
;;; > Also (for anyone following along at home), in the source code
;;; > within the .shk file I linked I painstakingly de-constructed
;;; > the compiled macro table by using the Merlin DB pseudo opcode
;;; > over and over, line after line. I did that for illustrative
;;; > purposes only.
;;; >
;;; > In normal practice doing this type of thing, I use the
;;; > Merlin32 PUTBIN directive to just place the entire compiled
;;; > task file in memory, and then only copy the macro table ($1000
;;; > bytes), which begins at offset $200 in the file, to $01/EF00.
;;; > Not only is it much simpler to do it that way, it also makes
;;; > revisions to the macros easy to implement.
;;;
;;; In other words, don't try to modify or understand this too much.
;;; The important thing is that there are two "-delimited strings
;;; in there that get patched at runtime.
.proc macros
.incbin "awlaunch_task.bin"
.endproc ; macros
sizeof_macros = .sizeof(macros)
PassedPath := macros + $1A1 ; index of second " in 2nd empty string
PassedName := macros + $1E6 ; index of second " in 3rd empty string
.endproc ; reloc
sizeof_reloc = .sizeof(reloc)
|
a2stuff/a2d
| 29,306
|
src/disk_copy/main.s
|
;;; ============================================================
;;; Disk Copy - Main Memory Segment $0800
;;;
;;; Compiled as part of disk_copy.s
;;; ============================================================
BEGINSEG SegmentMain
.scope main
MLIEntry := MLIRelayImpl
MGTKEntry := auxlc::MGTKRelayImpl
;;; ============================================================
.include "../lib/formatdiskii.s"
;;; ============================================================
default_block_buffer := $1C00 ; if this is changed, update `memory_bitmap`
DEFINE_QUIT_PARAMS quit_params
;; Used only for single device
DEFINE_ON_LINE_PARAMS on_line_params,, on_line_buffer
.struct
.org $300
on_line_buffer .res 16 ; enough for single device
.endstruct
;; Used for enumerating all devices and single device
DEFINE_ON_LINE_PARAMS on_line_params2,, on_line_buffer2
.struct
.org ::kSegmentMainAddress + ::kSegmentMainLength
on_line_buffer2 .res 256 ; enough for all devices
.endstruct
DEFINE_READWRITE_BLOCK_PARAMS block_params, default_block_buffer, 0
;;; This must allow $2000 bytes of contiguous space in the
;;; default memory bitmap.
volume_bitmap := $4000
;;; ============================================================
.proc MLIRelayImpl
params_src := $7E
jsr auxlc::CheckEvents
;; Adjust return address on stack, compute
;; original params address.
pla
sta params_src
clc
adc #<3
tax
pla
sta params_src+1
adc #>3
pha
txa
pha
;; Copy the params here
ldy #3 ; ptr is off by 1
DO
copy8 (params_src),y, params-1,y
dey
WHILE_NOT_ZERO
;; Bank and call
sta ALTZPOFF
bit ROMIN2
jsr MLI
params: .res 3
sta ALTZPON
php
bit LCBANK1
bit LCBANK1
plp
rts
.endproc ; MLIRelayImpl
;;; ============================================================
.proc NoOp
rts
.endproc ; NoOp
;;; ============================================================
;;; Quit back to ProDOS (which will launch DeskTop)
.proc Quit
;; Override in this scope
MLIEntry := MLI
jsr auxlc::StopDeskTop
sta ALTZPOFF
bit ROMIN2
sta SET80STORE ; 80-col firmware expects this
lda #0 ; INIT is not used as that briefly
sta WNDLFT ; displays the dirty text page
sta WNDTOP
lda #80
sta WNDWDTH
lda #24
sta WNDBTM
jsr HOME ; Clear 80-col screen
sta TXTSET ; ... and show it
lda #$95 ; Ctrl-U - disable 80-col firmware
jsr COUT
jsr INIT ; reset text window again
jsr SETVID ; after INIT so WNDTOP is set properly
jsr SETKBD
;; We'd switch back to color mode here, but since we're
;; launching DeskTop there's no point.
jsr ReconnectRAM
MLI_CALL QUIT, quit_params
rts
.endproc ; Quit
;;; ============================================================
.proc FormatDevice
ldx auxlc::dest_drive_index
lda auxlc::drive_unitnum_table,x
sta unit_number
jsr auxlc::IsDiskII
beq disk_ii
;; Get driver address
lda unit_number
jsr DeviceDriverAddress
stax $06
lda #DRIVER_COMMAND_FORMAT
sta DRIVER_COMMAND
lda unit_number
sta DRIVER_UNIT_NUMBER
jmp ($06)
;; Use Disk II-specific code
disk_ii:
unit_number := *+1
lda #SELF_MODIFIED_BYTE
jmp FormatDiskII
.endproc ; FormatDevice
;;; ============================================================
;;; Eject Disk via SmartPort
.proc EjectDiskImpl
DEFINE_SP_CONTROL_PARAMS control_params, 0, list, $04 ; For Apple/UniDisk 3.3: Eject disk
list: .word 0 ; 0 items in list
start:
jsr FindSmartportDispatchAddress
bcs done
stax dispatch
sty control_params::unit_number
;; Do SmartPort call
dispatch := *+1
jsr SELF_MODIFIED
.byte SPCall::Control
.addr control_params
done: rts
.endproc ; EjectDiskImpl
EjectDisk := EjectDiskImpl::start
;;; ============================================================
;;; Identify the disk type by reading the first block.
;;; NOTE: Not used for ProDOS disks.
;;; Inputs: `source_drive_index` must be set
;;; Outputs: sets `source_disk_format`
.proc IdentifySourceNonProDOSDiskType
ldx auxlc::source_drive_index
lda auxlc::drive_unitnum_table,x
sta block_params::unit_num
lda #$00
sta block_params::block_num
sta block_params::block_num+1
jsr ReadBlock
bcs fail
;; Pascal?
jsr auxlc::IsPascalBootBlock
IF_CC
param_call auxlc::GetPascalVolName, on_line_buffer2
copy8 #$C0, auxlc::source_disk_format ; Pascal
rts
END_IF
;; DOS 3.3?
jsr auxlc::IsDOS33BootBlock
IF_CC
copy8 #$80,auxlc::source_disk_format ; DOS 3.3
rts
END_IF
;; Anything else
fail: copy8 #$81, auxlc::source_disk_format ; Other
rts
.endproc ; IdentifySourceNonProDOSDiskType
;;; ============================================================
;;; Reads the volume bitmap (blocks 6 through ...)
.proc ReadVolumeBitmap
;; Number of blocks to copy, divided by 8
block_count_div8 := $08 ; word
lda auxlc::source_drive_index
asl a
tax
copy16 auxlc::block_count_table,x, block_count_div8
lsr16 block_count_div8 ; /= 8
lsr16 block_count_div8
lsr16 block_count_div8
copy16 block_count_div8, auxlc::block_count_div8
bit auxlc::source_disk_format
bmi :+ ; not ProDOS
lda auxlc::disk_copy_flag
bne :+
jmp QuickCopy
:
;; --------------------------------------------------
;; Disk Copy - initialize a fake volume bitmap so that
;; all pages are copied.
.scope
ptr := $06
;; Zero out the volume bitmap
add16 #volume_bitmap, auxlc::block_count_div8, ptr
ldy #0
DO
dec16 ptr
tya
sta (ptr),y
ecmp16 ptr, #volume_bitmap
WHILE_NE
;; Now mark block-pages used in memory bitmap
page := $07 ; high byte of `volume_bitmap` from above
count := $06 ; no longer needed
sty count
loop: lda page
jsr MarkUsedInMemoryBitmap
inc page
inc page
inc count
inc count
lda count
cmp auxlc::block_count_div8+1
beq loop ; TODO: `BLE` macro?
bcc loop
rts
.endscope
;; --------------------------------------------------
;; Quick Copy - load volume bitmap from disk
;; so only used blocks are copied
.proc QuickCopy
copy16 #6, block_params::block_num
ldx auxlc::source_drive_index
lda auxlc::drive_unitnum_table,x
sta block_params::unit_num
copy16 #volume_bitmap, block_params::data_buffer
;; Each volume bitmap block holds $200*8 bits, so keep reading
;; blocks until we've accounted for all blocks on the volume.
DO
lda block_params::data_buffer+1
jsr MarkUsedInMemoryBitmap
jsr ReadBlock
IF_CS
brk ; rude!
END_IF
sub16 block_count_div8, #$200, block_count_div8
RTS_IF_NEG
lda block_count_div8
RTS_IF_ZERO
add16 block_params::data_buffer, #$200, block_params::data_buffer
inc block_params::block_num
WHILE_NOT_ZERO ; always
.endproc ; QuickCopy
.endproc ; ReadVolumeBitmap
;;; ============================================================
;;; Check if device is removable.
;;; Inputs: A=%DSSSnnnn (drive/slot part of unit number)
;;; Outputs: A=$80 if "removable", 0 otherwise
.proc IsDriveEjectableImpl
DEFINE_SP_STATUS_PARAMS status_params, 1, dib_buffer, 3 ; Return Device Information Block (DIB)
dib_buffer := $220
start:
jsr FindSmartportDispatchAddress
IF_CC
stax dispatch
sty status_params::unit_num
;; Do SmartPort call
dispatch := *+1
jsr SELF_MODIFIED
.byte SPCall::Status
.addr status_params
IF_CC
lda dib_buffer+SPDIB::Device_Type_Code
IF_A_EQ #SPDeviceType::Disk35
;; Assume all 3.5" drives are ejectable
return #$80
END_IF
END_IF
END_IF
return #0
.endproc ; IsDriveEjectableImpl
IsDriveEjectable := IsDriveEjectableImpl::start
;;; ============================================================
;;; Input: C = write flag (0=reading, 1=writing)
.proc CopyBlocks
ror write_flag
and #$FF
IF_NEG
copy16 auxlc::start_block_div8, auxlc::block_num_div8
copy8 auxlc::start_block_shift, auxlc::block_num_shift
ldx auxlc::dest_drive_index
ELSE
copy16 auxlc::block_num_div8, auxlc::start_block_div8
copy8 auxlc::block_num_shift, auxlc::start_block_shift
ldx auxlc::source_drive_index
END_IF
lda auxlc::drive_unitnum_table,x
sta block_params::unit_num
lda #7 ; 7 - (n % 8)
sta auxlc::block_index_shift
lda #0
sta auxlc::block_index_div8
sta flag1
sta flag2
beq check ; always
loop:
;; Update displayed counts
bit write_flag
IF_NC
jsr auxlc::IncAndDrawBlocksRead
ELSE
jsr auxlc::IncAndDrawBlocksWritten
END_IF
jsr auxlc::DrawProgressBar
check:
;; Check for keypress
lda KBD
IF_A_EQ #(CHAR_ESCAPE | $80)
bit KBDSTRB
jmp error
END_IF
bit flag1
bmi success
bit flag2
bmi continue
jsr AdvanceToNextBlockIndex
IF_CS
IF_ZERO
cpx #$00
beq success
END_IF
ldy #$80
sty flag1
END_IF
stax mem_block_addr
jsr AdvanceToNextBlock
bcc _ReadOrWriteBlock
IF_ZERO
cpx #$00
beq continue
END_IF
ldy #$80
sty flag2
bne _ReadOrWriteBlock
continue:
return #$80
success:
return #0
error: return #1
.proc _ReadOrWriteBlock
stax block_params::block_num
;; A,X = address in memory
ldx mem_block_addr+1
lda mem_block_addr
;; Y = block number / 8
ldy auxlc::block_index_div8
cpy #$10
bcs need_move
;; --------------------------------------------------
;; read/write block directly to/from main mem buffer
;; $00-$0F = 0/$0000 - 0/$FFFF
bit write_flag
IF_NC
jsr ReadBlockToMain
bmi error
jmp loop
END_IF
jsr WriteBlockFromMain
bmi error
jmp loop
;; --------------------------------------------------
need_move:
cpy #$1D
bcc use_auxmem
cpy #$20
bcs use_lcbank2
;; --------------------------------------------------
;; read/write block to/from aux lcbank1
;; $1D-$1F = 1/$D000 - 1/$FFFF
bit write_flag
IF_NC
jsr ReadBlockToLcbank1
bmi error
jmp loop
END_IF
jsr WriteBlockFromLcbank1
bmi error
jmp loop
;; --------------------------------------------------
;; read/write block to/from aux
;; $10-$1C = 1/$0000 - 1/$CFFF
use_auxmem:
bit write_flag ; 16-28
IF_NC
jsr auxlc::ReadBlockToAuxmem
bmi error
jmp loop
END_IF
jsr auxlc::WriteBlockFromAuxmem
bmi error
jmp loop
;; --------------------------------------------------
;; read/write block to/from aux lcbank2
;; $20+ = 1b/$D000 - 1b/$DFFF
use_lcbank2:
bit write_flag
IF_NC
jsr ReadBlockToLcbank2
bmi error
jmp loop
END_IF
jsr WriteBlockFromLcbank2
bmi error
jmp loop
.endproc ; _ReadOrWriteBlock
flag1: .byte 0 ; ???
flag2: .byte 0 ; ???
write_flag: ; high bit set if writing
.byte 0
mem_block_addr:
.word 0
.endproc ; CopyBlocks
;;; ============================================================
;;; Advance `block_num_div8` and `block_num_shift` to next used
;;; block per volume bitmap.
;;; Inputs: `block_num_div8` and `block_num_shift`
;;; Output: C=0 and A,X=block number if one exists
;;; C=1 and A,X=$0000 if last block reached
.proc AdvanceToNextBlock
repeat: jsr LookupInVolumeBitmap ; A,X=block number, Y=free?
cpy #0
bne free
pha
jsr _Next
pla
rts
free: jsr _Next
bcc repeat ; repeat unless last block
lda #0
tax
rts
.proc _Next
dec auxlc::block_num_shift
bmi :+
not_last:
clc
rts
: lda #7 ; 7 - (n % 8)
sta auxlc::block_num_shift
inc16 auxlc::block_num_div8
ecmp16 auxlc::block_num_div8, auxlc::block_count_div8
bne not_last
sec
rts
.endproc ; _Next
.endproc ; AdvanceToNextBlock
;;; ============================================================
;;; Count active blocks in volume bitmap
;;; Output: A,X = block count
.proc CountActiveBlocksInVolumeBitmap
ptr := $06
count := $08
copy16 #0, count
add16 #volume_bitmap, auxlc::block_count_div8, ptr
ldy #0
DO
dec16 ptr
lda (ptr),y
;; Count 0 bits in byte
eor #$FF
ldx #AS_BYTE(-1)
incr: inx
bloop: asl
bcs incr
bne bloop
txa
clc
adc count
sta count
lda #0
adc count+1
sta count+1
ecmp16 ptr, #volume_bitmap
WHILE_NE
ldax count
rts
.endproc ; CountActiveBlocksInVolumeBitmap
;;; ============================================================
;;; Look up block in volume bitmap
;;; Input: Uses `block_num_div8` and `block_num_shift`
;;; Output: A,X = block number, Y = masked bit from bitmap
.proc LookupInVolumeBitmap
ptr := $06
;; Find byte in volume bitmap
add16 #volume_bitmap, auxlc::block_num_div8, ptr
;; Find bit in volume bitmap
ldy #0
lda (ptr),y
ldx auxlc::block_num_shift
and bit_shift_table,x
tay ; Y = masked bit
;; Now compute block number
hi := $06
lda auxlc::block_num_div8+1
sta hi
lda auxlc::block_num_div8
asl a ; *=8
rol hi
asl a
rol hi
asl a
rol hi
ldx auxlc::block_num_shift
ora table,x
ldx hi
rts
table: .byte 7,6,5,4,3,2,1,0
.endproc ; LookupInVolumeBitmap
;;; ============================================================
.proc AdvanceToNextBlockIndex
jsr ComputeMemoryPageSignature
IF_Y_NE #0
pha
jsr _Next
pla
rts
END_IF
jsr _Next
bcc AdvanceToNextBlockIndex
lda #$00
tax
rts
;;; Advance to next
.proc _Next
dec auxlc::block_index_shift
IF_POS
ok: clc
rts
END_IF
lda #7
sta auxlc::block_index_shift
inc auxlc::block_index_div8
lda auxlc::block_index_div8
cmp #kMemoryBitmapSize
bcc ok
sec
rts
.endproc ; _Next
.endproc ; AdvanceToNextBlockIndex
;;; ============================================================
;;; Compute memory page signature; low nibble is high nibble of
;;; page, high nibble is "bank" (0=main, 1=aux, 2=aux lcbank2)
;;; Input: `block_index_div8` and `block_index_shift`
;;; Output: A,X=address to store block; Y=masked bit from bitmap
.proc ComputeMemoryPageSignature
;; Read from bitmap
ldx auxlc::block_index_div8
lda memory_bitmap,x
ldx auxlc::block_index_shift
and bit_shift_table,x
tay ; Y = masked bit
;; Now compute address to store in memory
lda auxlc::block_index_div8
IF_A_LT #$10
;; $00-$0F is main pages $00...$FE
;; $10-$1F is aux pages $00...$FE
;; $20.... is aux lcbank2 $D000...
calc: asl a ; *= 16
asl a
asl a
asl a
ldx auxlc::block_index_shift
clc
adc table,x
tax
lda #$00
rts
END_IF
IF_A_LT #$20 ; 16-31
sec
sbc #$10
jmp calc
END_IF
sec
sbc #$13
jmp calc
table: .byte $0E, $0C, $0A, $08, $06, $04, $02, $00
.endproc ; ComputeMemoryPageSignature
bit_shift_table:
.byte 1<<0, 1<<1, 1<<2, 1<<3, 1<<4, 1<<5, 1<<6, 1<<7
;;; ============================================================
.proc FreeVolBitmapPages
page_num := $06 ; not a pointer, for once!
lda #>volume_bitmap
sta page_num
lda #0
sta count
loop: lda page_num
jsr _MarkFreeInMemoryBitmap
inc page_num
inc page_num
inc count
inc count
count := *+1
lda #SELF_MODIFIED_BYTE
cmp auxlc::block_count_div8+1
beq loop ; TODO: `BLE` macro?
bcc loop
rts
.proc _MarkFreeInMemoryBitmap
jsr GetBitmapOffsetMask
ora memory_bitmap,y
sta memory_bitmap,y
rts
.endproc ; _MarkFreeInMemoryBitmap
.endproc ; FreeVolBitmapPages
;;; ============================================================
.proc MarkUsedInMemoryBitmap
jsr GetBitmapOffsetMask
eor #$FF
and memory_bitmap,y
sta memory_bitmap,y
rts
.endproc ; MarkUsedInMemoryBitmap
;;; ============================================================
;;; Sets Y to offset in `memory_bitmap`
;;; Sets A to mask bit
;;; e.g. $76 ==> Y = $07
;;; A = %00010000
.proc GetBitmapOffsetMask
pha
lsr a ; /=16
lsr a
lsr a
lsr a
tay
pla
and #$0F
lsr a ; /=2 (1 bit for 2 pages)
tax
lda table,x
rts
table:
.byte 1<<7, 1<<6, 1<<5, 1<<4, 1<<3, 1<<2, 1<<1, 1<<0
.endproc ; GetBitmapOffsetMask
;;; ============================================================
;;; Inputs: A,X = target block
;;; Output: $06/$08 set to A,X, A,X+1; `block_params::data_buffer` init
.proc PrepBlockPtrs
ptr1 := $06
ptr2 := $08 ; one page up
sta ptr1
sta ptr2
stx ptr1+1
stx ptr2+1
inc ptr2+1
copy16 #default_block_buffer, block_params::data_buffer
rts
.endproc ; PrepBlockPtrs
;;; ============================================================
;;; Read block (w/ retries) to main memory
;;; Inputs: A,X=mem address to store it
;;; Outputs: A=0 on success, nonzero otherwise
.proc ReadBlockToMain
stax block_params::data_buffer
FALL_THROUGH_TO ReadBlockWithRetry
.endproc ; ReadBlockToMain
;;; Returns with 0 on success or N=1 on failure
.proc ReadBlockWithRetry
retry: jsr ReadBlock
bcc done
ldx #0 ; reading
jsr auxlc::ShowBlockError
bmi done
bne retry
done: rts
.endproc ; ReadBlockWithRetry
;;; ============================================================
;;; Read block (w/ retries) to aux LCBANK1 memory
;;; Inputs: A,X=mem address to store it
;;; Outputs: A=0 on success, nonzero otherwise
.proc ReadBlockToLcbank1
jsr PrepBlockPtrs
jsr ReadBlockWithRetry
IF_ZERO
jsr CopyFromBlockBuffer
lda #0 ; success
END_IF
rts
.endproc ; ReadBlockToLcbank1
;;; ============================================================
;;; Read block (w/ retries) to aux LCBANK2 memory
;;; Inputs: A,X=mem address to store it
;;; Outputs: A=0 on success, nonzero otherwise
.proc ReadBlockToLcbank2
jsr PrepBlockPtrs
jsr ReadBlockWithRetry
IF_ZERO
bit LCBANK2
bit LCBANK2
jsr CopyFromBlockBuffer
bit LCBANK1
bit LCBANK1
lda #0 ; success
END_IF
rts
.endproc ; ReadBlockToLcbank2
;;; ============================================================
;;; Copies block from `default_block_buffer`
;;; Inputs: $06/$08 point at target pages
.proc CopyFromBlockBuffer
ptr1 := $06
ptr2 := $08 ; one page up
ldy #$FF
iny
DO
lda default_block_buffer,y
sta (ptr1),y
lda default_block_buffer+$100,y
sta (ptr2),y
iny
WHILE_NOT_ZERO
rts
.endproc ; CopyFromBlockBuffer
;;; ============================================================
;;; Write block (w/ retries) from main memory
;;; Inputs: A,X=address to read from
;;; Outputs: A=0 on success, nonzero otherwise
.proc WriteBlockFromMain
stax block_params::data_buffer
FALL_THROUGH_TO WriteBlockWithRetry
.endproc ; WriteBlockFromMain
;;; Input: `block_params::data_buffer` populated
.proc WriteBlockWithRetry
retry: jsr WriteBlock
bcc done
ldx #$80 ; writing
jsr auxlc::ShowBlockError
beq done
bpl retry
done: rts
.endproc ; WriteBlockWithRetry
;;; ============================================================
;;; Write block (w/ retries) from aux LCBANK1 memory
;;; Inputs: A,X=address to read from
;;; Outputs: A=0 on success, nonzero otherwise
.proc WriteBlockFromLcbank1
jsr PrepBlockPtrs
jsr CopyToBlockBuffer
jmp WriteBlockWithRetry
.endproc ; WriteBlockFromLcbank1
;;; ============================================================
;;; Write block (w/ retries) from aux LCBANK2 memory
;;; Inputs: A,X=address to read from
;;; Outputs: A=0 on success, nonzero otherwise
.proc WriteBlockFromLcbank2
jsr PrepBlockPtrs
bit LCBANK2
bit LCBANK2
jsr CopyToBlockBuffer
bit LCBANK1
bit LCBANK1
jmp WriteBlockWithRetry
.endproc ; WriteBlockFromLcbank2
;;; ============================================================
;;; Copies block to `default_block_buffer`
;;; Inputs: $06/$08 point at source pages
.proc CopyToBlockBuffer
ptr1 := $06
ptr2 := $08 ; one page up
ldy #$FF
iny
DO
lda (ptr1),y
sta default_block_buffer,y
lda (ptr2),y
sta default_block_buffer+$100,y
iny
WHILE_NOT_ZERO
rts
.endproc ; CopyToBlockBuffer
;;; ============================================================
.proc CallOnLine2
MLI_CALL ON_LINE, on_line_params2
rts
.endproc ; CallOnLine2
.proc CallOnLine
MLI_CALL ON_LINE, on_line_params
rts
.endproc ; CallOnLine
.proc WriteBlock
MLI_CALL WRITE_BLOCK, block_params
rts
.endproc ; WriteBlock
.proc ReadBlock
MLI_CALL READ_BLOCK, block_params
rts
.endproc ; ReadBlock
;;; ============================================================
;;; Memory Availability Bitmap
;;;
;;; Each bit represents a double-page, enough for one 512-byte
;;; disk block. 1 = available, 0 = reserved.
;;;
;;; Note that the `memory_bitmap` has _lowest_ address represented
;;; by the _highest_ bit in the corresponding byte. So page 0 is
;;; represented as available by %1xxxxxxx, page 1 by %x1xxxxxx, etc.
memory_bitmap:
;; Main memory
.byte %00000000 ; $00-$0F - ZP/Stack/Text, then Disk Copy code...
.byte %00111100 ; $10-$1F - but $14-1B free ($1C = I/O buffer)
.byte %00000000 ; $20-$2F - DHR graphics page
.byte %00000000 ; $30-$3F - DHR graphics page
.byte %11111111 ; $40-$4F - free
.byte %11111111 ; $50-$5F - free
.byte %11111111 ; $60-$6F - free
.byte %11111111 ; $70-$7F - free
.byte %11111111 ; $80-$8F - free
.byte %11111111 ; $90-$9F - free
.byte %11111111 ; $A0-$AF - free
.byte %11111110 ; $B0-$BF - free except $BE/F pages (ProDOS GP)
.byte %00000000 ; $C0-$CF - I/O
.byte %00000000 ; $D0-$DF - ProDOS
.byte %00000000 ; $E0-$EF - ProDOS
.byte %00000000 ; $F0-$FF - ProDOS
;; Aux memory
.byte %00001111 ; $00-$0F - free after ZP/Stack/Text
.byte %11111111 ; $10-$1F - free
.byte %00000000 ; $20-$2F - DHR graphics page
.byte %00000000 ; $30-$3F - DHR graphics page
.byte %00000000 ; $40-$4F - MGTK code
.byte %00000000 ; $50-$5F - MGTK code
.byte %00000000 ; $60-$6F - MGTK code
.byte %00000000 ; $70-$7F - MGTK code
.byte %00000001 ; $80-$8F - MGTK, font (but $8E-$8F free)
.byte %11111111 ; $90-$9F - free
.byte %11111111 ; $A0-$AF - free
.byte %11111111 ; $B0-$BF - free
.byte %00000000 ; $C0-$CF - I/O
.byte %00000000 ; $D0-$DF - Disk Copy code
.byte %00000000 ; $E0-$EF - Disk Copy code
.byte %01111111 ; $F0-$FF - free $F2 and up
;; Aux memory - LCBANK2
.byte %11111111 ; $D0-$DF - free
kMemoryBitmapSize = * - memory_bitmap
.assert DEFAULT_FONT + 1283 < $8E00, error, "Update memory_bitmap if MGTK+font extends past $8E00"
.assert end_of_main <= $1400, error, "Update memory_bitmap if code extends past $1400"
;;; ============================================================
;;; Inputs: A = unit num (DSSS0000), X,Y = driver address
;;; Outputs: X,Y = blocks
.proc GetDeviceBlocksUsingDriver
sta ALTZPOFF
sta DRIVER_UNIT_NUMBER
stxy @driver
lda #$00
sta DRIVER_COMMAND ; $00 = STATUS
sta DRIVER_BUFFER
sta DRIVER_BUFFER+1
sta DRIVER_BLOCK_NUMBER
sta DRIVER_BLOCK_NUMBER+1
@driver := *+1
jsr SELF_MODIFIED
sta ALTZPON
rts
.endproc ; GetDeviceBlocksUsingDriver
;;; ============================================================
;;; On IIgs, force preferred RGB mode. No-op otherwise.
;;; Assert: LCBANK1 is banked in
.proc ResetIIgsRGB
ldx #DeskTopSettings::system_capabilities
jsr ReadSetting
and #DeskTopSettings::kSysCapIsIIgs
beq done
ldx #DeskTopSettings::rgb_color
jsr ReadSetting
bmi color
ldy #$80 ; MONOCOLOR - Mono
lda NEWVIDEO
ora #(1<<5) ; B&W
bne store ; always
color: ldy #$00 ; MONOCOLOR - Color
lda NEWVIDEO
and #<~(1<<5) ; Color
store: sta NEWVIDEO
sty MONOCOLOR
done: rts
.endproc ; ResetIIgsRGB
;;; ============================================================
.include "../lib/smartport.s"
.include "../lib/reconnect_ram.s"
.include "../lib/readwrite_settings.s"
.include "../lib/speed.s"
.include "../lib/bell.s"
;;; ============================================================
end_of_main := *
.endscope ; main
ReadSetting := main::ReadSetting
ENDSEG SegmentMain
|
a2stuff/a2d
| 3,699
|
src/disk_copy/loader.s
|
;;; ============================================================
;;; Disk Copy - $1800 - $19FF
;;;
;;; Compiled as part of disk_copy.s
;;; ============================================================
BEGINSEG Loader
.scope part2
MLIEntry := MLI
jmp start
;;; ============================================================
io_buf := $1C00
load_buf := $4000
DEFINE_OPEN_PARAMS open_params, filename, io_buf
filename: PASCAL_STRING kPathnameDiskCopy
DEFINE_READWRITE_PARAMS read_params, 0, 0
DEFINE_SET_MARK_PARAMS set_mark_params, 0
DEFINE_CLOSE_PARAMS close_params
.byte $00,$00
;;; ============================================================
start:
jsr DisconnectRAM
;; Set stack pointers to arbitrarily low values for use when
;; interrupts occur. DeskTop does not utilize this convention,
;; so the values are set low so that interrupts which do (for
;; example, the IIgs Control Panel) don't trash DeskTop's use
;; of the stacks.
;; See the Apple IIe Technical Reference Manual, pp. 153-154
lda #$41
sta ALTZPON
sta $0100 ; Main stack pointer, in Aux ZP
sta $0101 ; Aux stack pointer, in Aux ZP
sta ALTZPOFF
MLI_CALL OPEN, open_params
jcs fail
lda open_params::ref_num
sta read_params::ref_num
sta set_mark_params::ref_num
copy16 #kSegmentAuxLCOffset, set_mark_params::position
MLI_CALL SET_MARK, set_mark_params
jcs fail
copy16 #load_buf, read_params::data_buffer ; loads to temp address
copy16 #kSegmentAuxLCLength, read_params::request_count
MLI_CALL READ, read_params
bcs fail
jsr CopyToLc
copy16 #kSegmentMainOffset, set_mark_params::position
MLI_CALL SET_MARK, set_mark_params
copy16 #kSegmentMainAddress, read_params::data_buffer
copy16 #kSegmentMainLength, read_params::request_count
MLI_CALL READ, read_params
bcs fail
MLI_CALL CLOSE, close_params
bcs fail
sta ALTZPON
bit LCBANK1
bit LCBANK1
jmp auxlc::start
;;; This mimics the original behavior - just hang if the load fails.
;;; Note that a ProDOS QUIT will likely fail since the installed
;;; routine will try to reload DeskTop.
fail: jmp fail
;;; ============================================================
;;; Copy first chunk to the Language Card
.proc CopyToLc
src := $6
end := $8
dst := $A
;; Bank in AUX LC
sta ALTZPON
bit LCBANK1
bit LCBANK1
txa
asl a
tax
;; Set up pointers
copy16 #load_buf, src
add16 src, #kSegmentAuxLCLength, end
copy16 #kSegmentAuxLCAddress, dst
;; Do the copy
ldy #0
DO
lda (src),y
sta (dst),y
inc src
inc dst
lda src
IF_ZERO
inc src+1
inc dst+1
END_IF
ecmp16 src, end
WHILE_NE
;; Bank in ROM
sta ALTZPOFF
bit ROMIN2
rts
.endproc ; CopyToLc
;;; ============================================================
saved_ram_unitnum := main::saved_ram_unitnum
saved_ram_drvec := main::saved_ram_drvec
saved_ram_buffer: .res 16
.include "../lib/disconnect_ram.s"
;;; ============================================================
.endscope ; part2
ENDSEG Loader
|
a2stuff/a2d
| 68,179
|
src/disk_copy/auxlc.s
|
;;; ============================================================
;;; Disk Copy - Auxiliary LC Segment $D000
;;;
;;; Compiled as part of disk_copy.s
;;; ============================================================
BEGINSEG SegmentAuxLC
.scope auxlc
MGTKEntry := MGTKRelayImpl
kShortcutReadDisk = res_char_button_read_drive_shortcut
;;; ============================================================
;;; number of alert messages
kNumAlertMessages = 11
kAlertMsgInsertSource = 0 ; No bell, *
kAlertMsgInsertDestination = 1 ; No bell, *
kAlertMsgConfirmErase = 2 ; No bell, X,Y = pointer to volume name
kAlertMsgDestinationFormatFail = 3 ; Bell
kAlertMsgFormatError = 4 ; Bell
kAlertMsgDestinationProtected = 5 ; Bell
kAlertMsgConfirmEraseSlotDrive = 6 ; No bell, X = unit number
kAlertMsgCopySuccessful = 7 ; No bell
kAlertMsgCopyFailure = 8 ; No bell
kAlertMsgInsertSourceOrCancel = 9 ; No bell, *
kAlertMsgInsertDestinationOrCancel = 10 ; No bell, *
;;; "Bell" or "No bell" determined by the `MaybeBell` proc.
;;; * = the 'InsertXOrCancel' variants are selected automatically when
;;; InsertX is specified if X flag is non-zero, and the unit number in
;;; Y identifies a removable volume. In that case, the alert will
;;; automatically be dismissed when a disk is inserted.
;;; ============================================================
ASSERT_ADDRESS ::kSegmentAuxLCAddress, "Entry point"
start:
jmp init
;;; ============================================================
;;; Resources
pencopy: .byte MGTK::pencopy
penXOR: .byte MGTK::penXOR
notpencopy: .byte MGTK::notpencopy
.params hilitemenu_params
menu_id := * + 0
.endparams
.params menuselect_params
menu_id := * + 0
menu_item := * + 1
.endparams
.params menukey_params
menu_id := * + 0
menu_item := * + 1
which_key := * + 2
key_mods := * + 3
.endparams
.res 4, 0
.byte 0
.byte 0
.byte 0
.byte 0
.byte 0
;;; ============================================================
;;; Menu definition
kMenuIdApple = 1
kMenuIdFile = 2
kMenuIdOptions = 3
;; Menu bar
DEFINE_MENU_BAR menu_definition, 3
@items: DEFINE_MENU_BAR_ITEM kMenuIdApple, label_apple, menu_apple
DEFINE_MENU_BAR_ITEM kMenuIdFile, label_file, menu_file
DEFINE_MENU_BAR_ITEM kMenuIdOptions, label_facilities, menu_options
ASSERT_RECORD_TABLE_SIZE @items, 3, .sizeof(MGTK::MenuBarItem)
;; Apple menu
DEFINE_MENU menu_apple, 5
@items: DEFINE_MENU_ITEM label_desktop
DEFINE_MENU_SEPARATOR
DEFINE_MENU_ITEM label_copyright1
DEFINE_MENU_ITEM label_copyright2
DEFINE_MENU_ITEM label_copyright3
ASSERT_RECORD_TABLE_SIZE @items, 5, .sizeof(MGTK::MenuItem)
;; File menu
DEFINE_MENU menu_file, 1
@items: DEFINE_MENU_ITEM label_quit, res_char_dc_menu_item_quit_shortcut
ASSERT_RECORD_TABLE_SIZE @items, 1, .sizeof(MGTK::MenuItem)
label_apple:
PASCAL_STRING kGlyphSolidApple
;; Options menu
DEFINE_MENU menu_options, 2
@items: DEFINE_MENU_ITEM label_quick_copy
DEFINE_MENU_ITEM label_disk_copy
ASSERT_RECORD_TABLE_SIZE @items, 2, .sizeof(MGTK::MenuItem)
kMenuItemIdQuickCopy = 1
kMenuItemIdDiskCopy = 2
label_file:
PASCAL_STRING res_string_dc_menu_bar_item_file
label_facilities:
PASCAL_STRING res_string_menu_bar_item_facilities
label_desktop:
PASCAL_STRING .sprintf(res_string_version_format_long, kDeskTopProductName, ::kDeskTopVersionMajor, ::kDeskTopVersionMinor, kDeskTopVersionSuffix)
label_copyright1:
PASCAL_STRING res_string_copyright_line1 ; menu item
label_copyright2:
PASCAL_STRING res_string_copyright_line2 ; menu item
label_copyright3:
PASCAL_STRING res_string_copyright_line3 ; menu item
label_quit:
PASCAL_STRING res_string_dc_menu_item_quit
label_quick_copy:
PASCAL_STRING res_string_menu_item_quick_copy
label_disk_copy:
PASCAL_STRING res_string_dc_menu_item_disk_copy
;;; ============================================================
.params disablemenu_params
menu_id: .byte kMenuIdOptions
disable: .byte 0
.endparams
.params checkitem_params
menu_id: .byte kMenuIdOptions
menu_item: .byte 0
check: .byte 0
.endparams
.include "../lib/event_params.s"
grafport: .tag MGTK::GrafPort
kDialogWindowId = 1
.params getwinport_params
window_id: .byte kDialogWindowId
port: .addr grafport_win
.endparams
grafport_win: .tag MGTK::GrafPort
kDialogWidth = 500
kDialogHeight = 150
kDialogLeft = (::kScreenWidth - kDialogWidth)/2
kDialogTop = (::kScreenHeight - kDialogHeight)/2
.params winfo_dialog
kWindowId = kDialogWindowId
window_id: .byte kWindowId
options: .byte MGTK::Option::dialog_box
title: .addr 0
hscroll: .byte MGTK::Scroll::option_none
vscroll: .byte MGTK::Scroll::option_none
hthumbmax: .byte 0
hthumbpos: .byte 0
vthumbmax: .byte 0
vthumbpos: .byte 0
status: .byte 0
reserved: .byte 0
mincontwidth: .word 150
mincontheight: .word 50
maxcontwidth: .word 500
maxcontheight: .word 140
port:
DEFINE_POINT viewloc, kDialogLeft, kDialogTop
mapbits: .addr MGTK::screen_mapbits
mapwidth: .byte MGTK::screen_mapwidth
reserved2: .byte 0
DEFINE_RECT maprect, 0, 0, kDialogWidth, kDialogHeight
pattern: .res 8, $FF
colormasks: .byte MGTK::colormask_and, MGTK::colormask_or
DEFINE_POINT penloc, 0, 0
penwidth: .byte 1
penheight: .byte 1
penmode: .byte MGTK::pencopy
textback: .byte MGTK::textbg_white
textfont: .addr DEFAULT_FONT
nextwinfo: .addr 0
REF_WINFO_MEMBERS
.endparams
pensize_frame: .byte kBorderDX, kBorderDY
DEFINE_RECT_FRAME rect_frame, kDialogWidth, kDialogHeight
kEraseLeft = 8
kEraseRight = kDialogWidth-8
;; For erasing parts of the window
DEFINE_RECT rect_erase_dialog_upper, kEraseLeft, 20, kEraseRight, 103 ; under title to bottom of buttons
DEFINE_RECT rect_erase_dialog_lower, kEraseLeft, 103, kEraseRight, kDialogHeight-4 ; top of buttons to bottom of dialog
DEFINE_BUTTON dialog_ok_button, winfo_dialog::kWindowId, res_string_button_ok, kGlyphReturn, 350, 90
;; For drawing/updating the dialog title
DEFINE_POINT point_title, kDialogWidth/2, 15
DEFINE_RECT rect_title, kEraseLeft, 4, kEraseRight, 15
DEFINE_RECT rect_erase_select_src, 270, 38, 420, 46
DEFINE_BUTTON read_drive_button, winfo_dialog::kWindowId, res_string_button_read_drive, res_char_button_read_drive_shortcut, 210, 90
DEFINE_LABEL slot_drive_name, res_string_label_slot_drive_name, 20, 28
DEFINE_LABEL select_source, res_string_prompt_select_source, 270, 46
str_select_destination:
PASCAL_STRING res_string_prompt_select_destination
DEFINE_POINT point_status, kDialogWidth/2, 68
DEFINE_RECT rect_status, kEraseLeft, 57, kEraseRight, 68
str_formatting:
PASCAL_STRING res_string_label_status_formatting
str_writing:
PASCAL_STRING res_string_label_status_writing
str_reading:
PASCAL_STRING res_string_label_status_reading
;; Progress bar
kProgressTop = 72
kProgressHeight = 9
kProgressLeft = 16
kProgressWidth = kDialogWidth-kProgressLeft*2
DEFINE_RECT_SZ progress_frame, kProgressLeft-1, kProgressTop-1, kProgressWidth+2, kProgressHeight+2
DEFINE_RECT_SZ progress_bar, kProgressLeft, kProgressTop, kProgressWidth, kProgressHeight
progress_pattern:
.byte %01000100
.byte %00010001
.byte %01000100
.byte %00010001
.byte %01000100
.byte %00010001
.byte %01000100
.byte %00010001
str_unknown:
PASCAL_STRING res_string_unknown
bg_black:
.byte 0
bg_white:
.byte $7F
kListRows = 8 ; number of visible rows
selection_mode_flag:
.byte 0 ; bit7 clear = source; set = destination
kListEntrySlotOffset = 8
kListEntryDriveOffset = 40
kListEntryNameOffset = 65
num_src_drives:
.byte 0
;;; 14 devices = 7 slots * 2 devices/slot (unit $Bx might not be /RAM)
kMaxNumDrives = 14
drive_name_table:
.res kMaxNumDrives * 16, 0
;;; Entries are properly masked (i.e. with `UNIT_NUM_MASK`)
drive_unitnum_table:
.res kMaxNumDrives, 0
;;; Mapping from filtered destination list index to drive_*_table index
destination_index_table:
.res kMaxNumDrives, 0
block_count_table:
.res kMaxNumDrives * 2, 0
source_drive_index: .byte 0
dest_drive_index: .byte 0
str_d: PASCAL_STRING 0
str_s: PASCAL_STRING 0
unit_num: .byte 0
ejectable_flag: .byte 0 ; bit7
;;; Memory index of block, for memory bitmap lookups
block_index_div8: ; block index, divided by 8
.byte 0
block_index_shift: ; 7-(block index mod 8), for bitmap lookups
.byte 0
;;; Actual block number, for volume bitmap lookups
block_num_div8: ; block number, divided by 8
.word 0
block_num_shift: ; 7-(block number mod 8), for bitmap lookups
.byte 0
;;; Remember the block_num_div8/shift for the start of a CopyBlocks read,
;;; for the writing pass.
start_block_div8:
.word 0
start_block_shift:
.byte 0
block_count_div8: ; calculated when reading volume bitmap
.word 0
.params win_frame_rect_params
id: .byte kListBoxWindowId
rect: .tag MGTK::Rect
.endparams
device_name_buf:
.res 18, 0
listbox_enabled_flag: .byte 0 ; bit7
;;; %0xxxxxxx = ProDOS
;;; %10xxxxxx = DOS 3.3
;;; %11xxxxx0 = Pascal
;;; %11xxxxx1 = Other
source_disk_format:
.byte 0
disk_copy_flag: ; bit7 0 = Quick Copy, 1 = Disk Copy
.byte 0
str_2_spaces: PASCAL_STRING " "
str_from_int: PASCAL_STRING "000,000" ; filled in by IntToString
kInfoTextY = 115
kSourceTextY = 125
kDestTextY = 135
kTipTextY = 145
kOverviewTextX = 40
kSlotDriveTextX = 110
kBlocksTextX = 300
DEFINE_LABEL blocks_read, res_string_label_blocks_read, kBlocksTextX, kSourceTextY
DEFINE_LABEL blocks_written, res_string_label_blocks_written, kBlocksTextX, kDestTextY
DEFINE_LABEL blocks_to_transfer, res_string_label_blocks_to_transfer, kBlocksTextX, kInfoTextY
DEFINE_LABEL source, res_string_source, kOverviewTextX, kSourceTextY
DEFINE_LABEL destination, res_string_destination, kOverviewTextX, kDestTextY
DEFINE_POINT point_source_slot_drive, kSlotDriveTextX, kSourceTextY
DEFINE_POINT point_destination_slot_drive, kSlotDriveTextX, kDestTextY
DEFINE_POINT point_disk_copy, kOverviewTextX, kInfoTextY
DEFINE_LABEL select_quit, .sprintf(res_string_label_select_quit, res_string_dc_menu_item_quit, res_string_dc_menu_bar_item_file, ::kGlyphOpenApple, res_char_dc_menu_item_quit_shortcut), kDialogWidth/2, kTipTextY
DEFINE_RECT rect_select_quit, kEraseLeft, kTipTextY-(kSystemFontHeight+2), kEraseRight, kTipTextY
DEFINE_LABEL escape_stop_copy, res_string_escape_stop_copy, kDialogWidth/2, kTipTextY
DEFINE_LABEL error_writing, res_string_error_writing, kOverviewTextX, 102
DEFINE_LABEL error_reading, res_string_error_reading, kOverviewTextX, 92
str_slot_drive_pattern:
PASCAL_STRING res_string_slot_drive_pattern
str_dos33_s_d:
PASCAL_STRING res_string_dos33_s_d_pattern
kStrDOS33SlotOffset = res_const_dos33_s_d_pattern_offset1
kStrDOS33DriveOffset = res_const_dos33_s_d_pattern_offset2
str_dos33_disk_copy:
PASCAL_STRING res_string_dos33_disk_copy
str_pascal_disk_copy:
PASCAL_STRING res_string_pascal_disk_copy
str_prodos_disk_copy:
PASCAL_STRING res_string_prodos_disk_copy
;;; ============================================================
;;; List Box
;;; ============================================================
kListBoxOffsetLeft = 20
kListBoxOffsetTop = 30
kListBoxLeft = kDialogLeft + kListBoxOffsetLeft
kListBoxTop = kDialogTop + kListBoxOffsetTop
kListBoxWidth = 150
kListBoxHeight = kListItemHeight*kListRows-1
kListBoxWindowId = 2
DEFINE_LIST_BOX_WINFO winfo_drive_select, \
kListBoxWindowId, \
kListBoxLeft, \
kListBoxTop, \
kListBoxWidth, \
kListBoxHeight, \
DEFAULT_FONT
DEFINE_LIST_BOX listbox_rec, winfo_drive_select, \
kListRows, SELF_MODIFIED_BYTE, \
DrawListEntryProc, NoOp, NoOp
DEFINE_LIST_BOX_PARAMS lb_params, listbox_rec
num_drives := listbox_rec::num_items
current_drive_selection := listbox_rec::selected_index
DEFINE_POINT list_entry_pos, 0, 0
NoOp: rts
;;; ============================================================
init:
;; DeskTop will have left a no-longer valid port selected,
;; so init a new port before we do anything else.
MGTK_CALL MGTK::InitPort, grafport
MGTK_CALL MGTK::SetPort, grafport
MGTK_CALL MGTK::SetMenu, menu_definition
jsr SetCursorPointer
copy8 #kMenuItemIdQuickCopy, checkitem_params::menu_item
copy8 #MGTK::checkitem_check, checkitem_params::check
MGTK_CALL MGTK::CheckItem, checkitem_params
CLEAR_BIT7_FLAG disk_copy_flag
;; Open dialog window
MGTK_CALL MGTK::OpenWindow, winfo_dialog
jsr SetPortForDialog
MGTK_CALL MGTK::SetPenMode, notpencopy
MGTK_CALL MGTK::SetPenSize, pensize_frame
MGTK_CALL MGTK::FrameRect, rect_frame
InitDialog:
CLEAR_BIT7_FLAG listbox_enabled_flag
copy8 #$FF, current_drive_selection
copy8 #BTK::kButtonStateDisabled, dialog_ok_button::state
copy8 #$81, source_disk_format ; other
copy8 #MGTK::disablemenu_enable, disablemenu_params::disable
MGTK_CALL MGTK::DisableMenu, disablemenu_params
;; --------------------------------------------------
;; Draw dialog window
jsr SetPortForDialog
MGTK_CALL MGTK::SetPenMode, pencopy
MGTK_CALL MGTK::PaintRect, rect_erase_dialog_upper
MGTK_CALL MGTK::PaintRect, rect_erase_dialog_lower
MGTK_CALL MGTK::MoveTo, point_title
ldax #label_quick_copy
bit disk_copy_flag
IF_NS
ldax #label_disk_copy
END_IF
jsr DrawStringCentered
BTK_CALL BTK::Draw, dialog_ok_button
jsr UpdateOKButton
BTK_CALL BTK::Draw, read_drive_button
MGTK_CALL MGTK::MoveTo, slot_drive_name_label_pos
param_call DrawString, slot_drive_name_label_str
MGTK_CALL MGTK::MoveTo, select_source_label_pos
param_call DrawString, select_source_label_str
MGTK_CALL MGTK::MoveTo, select_quit_label_pos
param_call DrawStringCentered, select_quit_label_str
;; --------------------------------------------------
;; Drive select listbox
MGTK_CALL MGTK::OpenWindow, winfo_drive_select
SET_BIT7_FLAG listbox_enabled_flag
jsr SetCursorWatch
jsr EnumerateDevices
copy8 #0, DISK_COPY_INITIAL_UNIT_NUM
jsr GetAllBlockCounts
jsr SetCursorPointer
CLEAR_BIT7_FLAG selection_mode_flag
LBTK_CALL LBTK::Init, lb_params
jsr UpdateOKButton
;; --------------------------------------------------
;; Loop until there's a selection (or drive check)
jsr WaitForSelection
;; Have a source selection
copy8 #MGTK::disablemenu_disable, disablemenu_params::disable
MGTK_CALL MGTK::DisableMenu, disablemenu_params
copy8 current_drive_selection, source_drive_index
jsr SetPortForDialog
MGTK_CALL MGTK::SetPenMode, pencopy
MGTK_CALL MGTK::PaintRect, rect_erase_select_src
MGTK_CALL MGTK::MoveTo, select_source_label_pos
param_call DrawString, str_select_destination
jsr DrawSourceDriveInfo
;; Prepare for destination selection
jsr EnumerateDestinationDevices
SET_BIT7_FLAG selection_mode_flag
LBTK_CALL LBTK::Init, lb_params
jsr UpdateOKButton
;; --------------------------------------------------
;; Loop until there's a selection (or drive check)
jsr WaitForSelection
;; Have a destination selection
tax
copy8 destination_index_table,x, dest_drive_index
CLEAR_BIT7_FLAG listbox_enabled_flag
jsr SetPortForDialog
MGTK_CALL MGTK::SetPenMode, pencopy
MGTK_CALL MGTK::PaintRect, rect_erase_dialog_upper
;; Erase the drive selection listbox
MGTK_CALL MGTK::GetWinFrameRect, win_frame_rect_params
MGTK_CALL MGTK::CloseWindow, winfo_drive_select
MGTK_CALL MGTK::InitPort, grafport
MGTK_CALL MGTK::SetPort, grafport
MGTK_CALL MGTK::PaintRect, win_frame_rect_params::rect
;; Erase tip
jsr SetPortForDialog
MGTK_CALL MGTK::SetPenMode, pencopy
MGTK_CALL MGTK::PaintRect, rect_select_quit
;; --------------------------------------------------
;; Prompt to insert source disk
prompt_insert_source:
ldx #0
lda #kAlertMsgInsertSource ; X=0 means just show alert
jsr ShowAlertDialog
IF_A_NE #kAlertResultOK
jmp InitDialog ; Cancel
END_IF
copy8 #$00, source_disk_format ; ProDOS
;; --------------------------------------------------
;; Check source disk
ldx source_drive_index
copy8 drive_unitnum_table,x, main::on_line_params2::unit_num
jsr main::CallOnLine2
bcc source_is_pro
check_source_error:
cmp #ERR_NOT_PRODOS_VOLUME
bne prompt_insert_source
;; Source is non-ProDOS
jsr main::IdentifySourceNonProDOSDiskType
jsr DrawSourceDriveInfo
jmp check_source_finish
;; Source is ProDOS
source_is_pro:
lda main::on_line_buffer2
and #$0F ; mask off name length
IF_ZERO ; 0 signals error
lda main::on_line_buffer2+1
jmp check_source_error
END_IF
param_call AdjustOnLineEntryCase, main::on_line_buffer2
jsr DrawSourceDriveInfo
check_source_finish:
lda source_drive_index
jsr GetBlockCount
jsr DrawDestinationDriveInfo
jsr DrawCopyFormatType
ldx dest_drive_index
ldy drive_unitnum_table,x
;; --------------------------------------------------
;; Prompt to insert destination disk
ldx #0
lda #kAlertMsgInsertDestination ; X=0 means just show alert
jsr ShowAlertDialog
IF_A_NE #kAlertResultOK
jmp InitDialog ; Cancel
END_IF
jsr SetCursorWatch
;; --------------------------------------------------
;; Check destination disk
ldx dest_drive_index
copy8 drive_unitnum_table,x, main::on_line_params2::unit_num
jsr main::CallOnLine2
bcc dest_is_pro
cmp #ERR_NOT_PRODOS_VOLUME
beq dest_ok
jmp try_format ; Can't even read drive - try formatting
dest_is_pro:
lda main::on_line_buffer2
and #NAME_LENGTH_MASK
bne dest_ok ; 0 signals error
lda main::on_line_buffer2+1
cmp #ERR_NOT_PRODOS_VOLUME
beq dest_ok
jmp try_format ; Some other error - proceed with format
dest_ok:
;; --------------------------------------------------
;; Confirm erasure of the destination disk
lda main::on_line_buffer2
and #NAME_LENGTH_MASK
IF_ZERO
;; Not ProDOS - try to read Pascal name
ldx dest_drive_index
copy8 drive_unitnum_table,x, main::block_params::unit_num
copy16 #0, main::block_params::block_num
copy16 #default_block_buffer, main::block_params::data_buffer
jsr main::ReadBlock
bcs use_sd
jsr IsPascalBootBlock
bcs use_sd
param_call GetPascalVolName, main::on_line_buffer2
ldxy #main::on_line_buffer2
lda #kAlertMsgConfirmErase ; X,Y = ptr to volume name
jmp show
use_sd:
;; No name, use slot/drive
ldx dest_drive_index
lda drive_unitnum_table,x
tax ; slot/drive
lda #kAlertMsgConfirmEraseSlotDrive ; X = unit number
ELSE
param_call AdjustOnLineEntryCase, main::on_line_buffer2
ldxy #main::on_line_buffer2
lda #kAlertMsgConfirmErase ; X,Y = ptr to volume name
END_IF
show: jsr ShowAlertDialog
cmp #kAlertResultOK
beq maybe_format ; OK
jmp InitDialog ; Cancel
;; --------------------------------------------------
;; Format if necessary (and supported)
maybe_format:
bit disk_copy_flag
bmi try_format ; full disk copy
jmp do_copy
try_format:
jsr SetCursorWatch
ldx dest_drive_index
lda drive_unitnum_table,x
jsr IsDiskII
beq format
ldx dest_drive_index
lda drive_unitnum_table,x
jsr main::DeviceDriverAddress ; Z=1 if firmware
stax $06
bne do_copy ; if not firmware, skip these checks
copy8 #$00, $06 ; point at $Cn00
ldy #$FE ; $CnFE
lda ($06),y
and #$08 ; bit 3 = The device supports formatting.
beq do_copy
format: param_call DrawStatus, str_formatting
jsr main::FormatDevice
bcc do_copy
IF_A_NE #ERR_WRITE_PROTECTED
lda #kAlertMsgFormatError ; no args
jsr ShowAlertDialog
.assert kAlertResultTryAgain = 0, error, "Branch assumes enum value"
beq try_format ; Try Again
jmp InitDialog ; Cancel
END_IF
lda #kAlertMsgDestinationProtected ; no args
jsr ShowAlertDialog
.assert kAlertResultTryAgain = 0, error, "Branch assumes enum value"
beq try_format ; Try Again
jmp InitDialog ; Cancel
;; --------------------------------------------------
;; Perform the copy
do_copy:
jsr SetCursorWatch
jsr SetPortForDialog
MGTK_CALL MGTK::SetPenMode, pencopy
MGTK_CALL MGTK::PaintRect, rect_erase_dialog_upper
ldx #kAlertMsgInsertSource
jsr MaybePromptDiskSwap
jsr SetCursorWatch
jsr main::ReadVolumeBitmap
;; Current block
lda #0
sta block_num_div8
sta block_num_div8+1
copy8 #7, block_num_shift ; 7 - (n % 8)
;; Blocks to copy
jsr main::CountActiveBlocksInVolumeBitmap
stax transfer_blocks
jsr DrawTotalBlocks
;; Blocks read/written so far
ldax #AS_WORD(-1)
stax blocks_read
stax blocks_written
jsr IncAndDrawBlocksRead
jsr IncAndDrawBlocksWritten
jsr DrawEscToStopCopyHint
copy_loop:
jsr SetCursorWatch
jsr DrawStatusReading
clc ; reading
jsr main::CopyBlocks
cmp #$01
beq copy_failure
ldx #kAlertMsgInsertDestination
jsr MaybePromptDiskSwap
jsr SetCursorWatch
jsr DrawStatusWriting
sec ; writing
jsr main::CopyBlocks
bmi copy_success
bne copy_failure
ldx #kAlertMsgInsertSource
jsr MaybePromptDiskSwap
jmp copy_loop
copy_success:
jsr SetCursorWatch
jsr main::FreeVolBitmapPages
ldx source_drive_index
lda drive_unitnum_table,x
jsr main::EjectDisk
ldx dest_drive_index
IF_X_NE source_drive_index
lda drive_unitnum_table,x
jsr main::EjectDisk
END_IF
lda #kAlertMsgCopySuccessful ; no args
jsr ShowAlertDialog
jmp InitDialog
copy_failure:
jsr main::FreeVolBitmapPages
lda #kAlertMsgCopyFailure ; no args
jsr ShowAlertDialog
jmp InitDialog
;;; ============================================================
;;; Wait until there's a selection, or refresh drive list --
;;; in which case this doesn't return.
;;; Output: A = selection
.proc WaitForSelection
loop: jsr EventLoop
bmi loop
beq check
MGTK_CALL MGTK::CloseWindow, winfo_drive_select
pla
pla
jmp InitDialog
check: lda current_drive_selection
bmi loop
rts
.endproc ; WaitForSelection
;;; ============================================================
;;; Input: X = message (`kAlertMsgInsertSource` or `kAlertMsgInsertDestination`)
;;; Returns when complete; if canceled, pops return address and runs `InitDialog`
.proc MaybePromptDiskSwap
stx message
lda source_drive_index
IF_A_EQ dest_drive_index
tax ; A = index
lda drive_unitnum_table,x
pha ; A = unit num
jsr main::EjectDisk
pla ; A = unit num
tay ; Y = unit num
message := *+1
lda #SELF_MODIFIED_BYTE
ldx #$80 ; X != 0 means Y=unit number, auto-dismiss
jsr ShowAlertDialog
cmp #kAlertResultOK
IF_NOT_ZERO
pla ; Cancel
pla
jmp InitDialog
END_IF
END_IF
rts
.endproc ; MaybePromptDiskSwap
;;; ============================================================
;;; Wait for and process event
;;; Output: N=1 if should be called again
;;; Z=1 if OK selected, should proceed
;;; Otherwise: Cancel selected (close/re-init dialog)
EventLoop:
loop: jsr SystemTask
MGTK_CALL MGTK::GetEvent, event_params
lda event_params::kind
cmp #MGTK::EventKind::button_down
jeq HandleClick
cmp #MGTK::EventKind::key_down
bne loop
jmp HandleKey
;;; ============================================================
menu_command_table:
;; Apple menu
.addr main::NoOp
.addr main::NoOp
.addr main::NoOp
.addr main::NoOp
.addr main::NoOp
;; File menu
.addr main::Quit
;; Facilities menu
.addr CmdQuickCopy
.addr CmdDiskCopy
menu_offset_table:
.byte 0, 5*2, 6*2
;;; ============================================================
.proc HandleKey
bit listbox_enabled_flag
IF_NS
lda event_params::key
IF_A_EQ_ONE_OF #CHAR_UP, #CHAR_DOWN
sta lb_params::key
copy8 event_params::modifiers, lb_params::modifiers
LBTK_CALL LBTK::Key, lb_params
jsr UpdateOKButton
return #$FF
END_IF
END_IF
lda event_params::modifiers
IF_ZERO
lda event_params::key
IF_A_NE #CHAR_ESCAPE
jmp dialog_shortcuts
END_IF
END_IF
;; Keyboard-based menu selection
copy8 event_params::key, menukey_params::which_key
copy8 event_params::modifiers, menukey_params::key_mods
MGTK_CALL MGTK::MenuKey, menukey_params
FALL_THROUGH_TO HandleMenuSelection
.endproc ; HandleKey
.proc HandleMenuSelection
ldx menuselect_params::menu_id
IF_ZERO
return #$FF
END_IF
;; Compute offset into command table - menu offset + item offset
lda menuselect_params::menu_item ; menu item index is 1-based
asl a
clc
adc menu_offset_table-1,x ; menu id is also 1-based
tax
copy16 menu_command_table-2,x, jump_addr ; 1-based (*2) to 0-based
jsr do_jump
MGTK_CALL MGTK::HiliteMenu, hilitemenu_params
jmp EventLoop
do_jump:
jump_addr := *+1
jmp SELF_MODIFIED
.endproc ; HandleMenuSelection
;;; ============================================================
.proc CmdQuickCopy
bit disk_copy_flag
bpl ret
copy8 #MGTK::checkitem_uncheck, checkitem_params::check
MGTK_CALL MGTK::CheckItem, checkitem_params
copy8 #kMenuItemIdQuickCopy, checkitem_params::menu_item
copy8 #MGTK::checkitem_check, checkitem_params::check
MGTK_CALL MGTK::CheckItem, checkitem_params
CLEAR_BIT7_FLAG disk_copy_flag
jsr SetPortForDialog
MGTK_CALL MGTK::PaintRect, rect_title
MGTK_CALL MGTK::MoveTo, point_title
param_call DrawStringCentered, label_quick_copy
ret: rts
.endproc ; CmdQuickCopy
.proc CmdDiskCopy
bit disk_copy_flag
bmi ret
copy8 #MGTK::checkitem_uncheck, checkitem_params::check
MGTK_CALL MGTK::CheckItem, checkitem_params
copy8 #kMenuItemIdDiskCopy, checkitem_params::menu_item
copy8 #MGTK::checkitem_check, checkitem_params::check
MGTK_CALL MGTK::CheckItem, checkitem_params
SET_BIT7_FLAG disk_copy_flag
jsr SetPortForDialog
MGTK_CALL MGTK::PaintRect, rect_title
MGTK_CALL MGTK::MoveTo, point_title
param_call DrawStringCentered, label_disk_copy
ret: rts
.endproc ; CmdDiskCopy
;;; ============================================================
.proc HandleClick
MGTK_CALL MGTK::FindWindow, findwindow_params
lda findwindow_params::which_area
.assert MGTK::Area::desktop = 0, error, "enum mismatch"
RTS_IF_ZERO
IF_A_EQ #MGTK::Area::menubar
MGTK_CALL MGTK::MenuSelect, menuselect_params
jmp HandleMenuSelection
END_IF
IF_A_NE #MGTK::Area::content
return #$FF
END_IF
lda findwindow_params::window_id
cmp #winfo_dialog::kWindowId
beq HandleDialogClick
IF_A_EQ winfo_drive_select
COPY_STRUCT event_params::coords, lb_params::coords
LBTK_CALL LBTK::Click, lb_params
php
jsr UpdateOKButton
plp
IF_NC
jsr DetectDoubleClick
END_IF
END_IF
rts
.endproc ; HandleClick
;;; ============================================================
.proc UpdateOKButton
lda current_drive_selection
and #$80
.assert BTK::kButtonStateDisabled = $80, error, "const mismatch"
cmp dialog_ok_button::state
beq ret
sta dialog_ok_button::state
BTK_CALL BTK::Hilite, dialog_ok_button
ret: rts
.endproc ; UpdateOKButton
;;; ============================================================
.proc HandleDialogClick
jsr SetPortForDialog
copy8 #winfo_dialog::kWindowId, screentowindow_params::window_id
MGTK_CALL MGTK::ScreenToWindow, screentowindow_params
MGTK_CALL MGTK::MoveTo, screentowindow_params::window
MGTK_CALL MGTK::InRect, dialog_ok_button::rect
IF_NOT_ZERO
BTK_CALL BTK::Track, dialog_ok_button
IF_NC
lda #$00
END_IF
rts
END_IF
MGTK_CALL MGTK::InRect, read_drive_button::rect
IF_NOT_ZERO
BTK_CALL BTK::Track, read_drive_button
IF_NC
lda #$01
END_IF
END_IF
rts
.endproc ; HandleDialogClick
;;; ============================================================
.proc MGTKRelayImpl
params_src := $7E
;; Adjust return address on stack, compute
;; original params address.
pla
sta params_src
clc
adc #<3
tax
pla
sta params_src+1
adc #>3
pha
txa
pha
;; Copy the params here
ldy #3 ; ptr is off by 1
DO
copy8 (params_src),y, params-1,y
dey
WHILE_NOT_ZERO
;; Bank and call
sta RAMRDON
sta RAMWRTON
jsr MGTKAuxEntry
params: .res 3
sta RAMRDOFF
sta RAMWRTOFF
rts
.endproc ; MGTKRelayImpl
;;; ============================================================
.proc dialog_shortcuts
lda event_params::key
jsr ToUpperCase
IF_A_EQ #kShortcutReadDisk
BTK_CALL BTK::Flash, read_drive_button
return #1
END_IF
IF_A_EQ #CHAR_RETURN
BTK_CALL BTK::Flash, dialog_ok_button
bmi ignore ; disabled
return #0
END_IF
ignore: return #$FF
.endproc ; dialog_shortcuts
;;; ============================================================
.proc SetCursorWatch
MGTK_CALL MGTK::SetCursor, MGTK::SystemCursor::watch
rts
.endproc ; SetCursorWatch
;;; ============================================================
.proc SetCursorPointer
MGTK_CALL MGTK::SetCursor, MGTK::SystemCursor::pointer
rts
.endproc ; SetCursorPointer
;;; ============================================================
;;; Populate `drive_name_table` for a non-ProDOS volume
;;; Input: A=unit number
;;; Output: Z=1 if successful
default_block_buffer := main::default_block_buffer
.proc NameNonProDOSVolume
sta main::block_params::unit_num
copy16 #0, main::block_params::block_num
copy16 #default_block_buffer, main::block_params::data_buffer
jsr main::ReadBlock
bcs fail
jsr IsPascalBootBlock
bne try_dos33
;; Find slot for string in table
lda num_drives
jsr GetDriveNameTableSlot
jsr GetPascalVolName
return #$00
fail: return #$FF
try_dos33:
jsr IsDOS33BootBlock
bcs fail
FALL_THROUGH_TO GetDos33VolName
.endproc ; NameNonProDOSVolume
;;; ============================================================
;;; Construct DOS 3.3 volume name (referencing slot/drive)
;;; Uses `str_dos33_s_d` template to construct volume name
;;; Inputs: `num_drives` and `main::block_params::unit_num` are set
;;; Outputs: Nth `drive_name_table` entry is populated
.proc GetDos33VolName
;; Mask off slot and drive, inject into template
lda main::block_params::unit_num
pha
jsr UnitNumToSlotDigit
sta str_dos33_s_d + kStrDOS33SlotOffset
pla
jsr UnitNumToDriveDigit
sta str_dos33_s_d + kStrDOS33DriveOffset
;; Find slot for string in table
ptr := $06
lda num_drives
jsr GetDriveNameTableSlot
stax ptr
;; Copy the string in
ldy str_dos33_s_d
DO
copy8 str_dos33_s_d,y, (ptr),y
dey
WHILE_POS
return #0
.endproc ; GetDos33VolName
;;; ============================================================
;;; Input: A = table index
;;; Output: A,X = address in `drive_name_table`
.proc GetDriveNameTableSlot
asl a
asl a
asl a
asl a
clc
adc #<drive_name_table
tay
lda #>drive_name_table
adc #0
tax
tya
rts
.endproc ; GetDriveNameTableSlot
;;; ============================================================
;;; Check block at `default_block_buffer` for Pascal signature
;;; Output: C=0 if Pascal volume, C=1 otherwise
.proc IsPascalBootBlock
lda default_block_buffer+1
cmp #$E0
bne fail
lda default_block_buffer+2
cmp #$70
beq match
cmp #$60
beq match
fail: sec
rts
match: clc
rts
.endproc ; IsPascalBootBlock
;;; ============================================================
;;; Check block at `default_block_buffer` for DOS 3.3 signature
;;; Output: C=0 if DOS 3.3 volume, C=1 otherwise
.proc IsDOS33BootBlock
lda default_block_buffer+1
cmp #$A5
bne fail
lda default_block_buffer+2
cmp #$27
beq match
fail: sec
rts
match: clc
rts
.endproc ; IsDOS33BootBlock
;;; ============================================================
;;; Get Pascal volume name
;;; Inputs: A,X=destination buffer (16 bytes)
;;; Output: Pascal name, with ':' suffix.
;;; If reading second block fails, just uses " ".
.proc GetPascalVolName
ptr := $06
stax ptr
copy16 #kVolumeDirKeyBlock, main::block_params::block_num
jsr main::ReadBlock
IF_CS
;; Just use a single space as the name
ldy #0
copy8 #1, (ptr),y
iny
copy8 #' ', (ptr),y
rts
END_IF
;; Copy the name out of the block
str_name := default_block_buffer+6
ldy #kMaxFilenameLength
DO
copy8 str_name,y, (ptr),y
dey
WHILE_POS
;; If less than 15 characters, increase len by one
ldy str_name
IF_Y_LT #kMaxFilenameLength
iny
tya
ldy #0
sta (ptr),y
tay
END_IF
;; Replace last char with ':'
copy8 #':', (ptr),y
rts
.endproc ; GetPascalVolName
;;; ============================================================
.include "../lib/inttostring.s"
;; TODO: Move these out of the `auxlc` scope
.include "../toolkits/btk.s"
BTKEntry := btk::BTKEntry
.include "../toolkits/lbtk.s"
LBTKEntry := lbtk::LBTKEntry
;;; ============================================================
.proc DrawString
ptr := $0A
stax ptr
ldy #0
copy8 (ptr),y, ptr+2
inc16 ptr
MGTK_CALL MGTK::DrawText, ptr
rts
.endproc ; DrawString
;;; ============================================================
.proc DrawStringCentered
params := $0A
textptr := params
textlen := params+2
result := params+3
stax textptr
ldy #0
copy8 (textptr),y, textlen
inc16 textptr
MGTK_CALL MGTK::TextWidth, params
lsr16 result
sub16 #0, result, result
lda #0
sta result+2
sta result+3
MGTK_CALL MGTK::Move, result
MGTK_CALL MGTK::DrawText, params
rts
.endproc ; DrawStringCentered
;;; ============================================================
;;; Input: A,X is ON_LINE data buffer entry *including* the
;;; slot/drive bits, not just the name.
;;; Output: entry is length-prefix, case-adjusted
.proc AdjustOnLineEntryCase
ptr := $A
stax ptr
ldy #0
lda (ptr),y
pha
and #UNIT_NUM_MASK ; stash unit number
sta main::block_params::unit_num
pla
and #NAME_LENGTH_MASK
sta (ptr),y ; mask off length
.if kBuildSupportsLowercase
;; --------------------------------------------------
;; Check for GS/OS case bits, apply if found
copy16 #kVolumeDirKeyBlock, main::block_params::block_num
copy16 #default_block_buffer, main::block_params::data_buffer
jsr main::ReadBlock
bcs fallback
case_bits := default_block_buffer + VolumeDirectoryHeader::case_bits
asl16 case_bits
bcc fallback ; High bit set = GS/OS case bits present
ldy #1
DO
asl16 case_bits ; Shift out high byte first
IF_CS
lda (ptr),y
ora #AS_BYTE(~CASE_MASK) ; guarded by `kBuildSupportsLowercase`
sta (ptr),y
END_IF
iny
WHILE_Y_LT #16 ; bits
rts
;; --------------------------------------------------
;; Use heuristic
fallback:
.include "../lib/wordcase.s"
.else
rts
.endif
.endproc ; AdjustOnLineEntryCase
;;; ============================================================
.proc SetPortForDialog
MGTK_CALL MGTK::GetWinPort, getwinport_params
;; ASSERT: Not obscured.
MGTK_CALL MGTK::SetPort, grafport_win
rts
.endproc ; SetPortForDialog
;;; ============================================================
;;; Called with A = index, X,Y = addr of drawing pos (MGTK::Point)
.proc DrawListEntryProc
pha
pt_ptr := $06
stxy pt_ptr
ldy #.sizeof(MGTK::Point)-1
DO
copy8 (pt_ptr),y, list_entry_pos,y
dey
WHILE_POS
pla
bit selection_mode_flag ; source or destination?
IF_NS
tax ; indirection for destination
lda destination_index_table,x
END_IF
jmp DrawDeviceListEntry
.endproc ; DrawListEntryProc
;;; ============================================================
;;; Populates `num_drives`, `drive_unitnum_table` and `drive_name_table`
.proc EnumerateDevices
copy8 #0, main::on_line_params2::unit_num
jsr main::CallOnLine2
IF_CS
brk ; rude!
END_IF
on_line_ptr := $06
lda #0
sta device_index
sta num_drives
loop: lda device_index ; <16
asl a ; *=16 (each record is 16 bytes)
asl a
asl a
asl a
clc
adc #<main::on_line_buffer2
sta on_line_ptr
lda #0
adc #>main::on_line_buffer2
sta on_line_ptr+1
;; Check first byte of record
ldy #0
lda (on_line_ptr),y
and #NAME_LENGTH_MASK
bne is_prodos
lda (on_line_ptr),y ; 0?
beq done ; done!
iny ; name_len=0 signifies an error
lda (on_line_ptr),y ; error code in second byte
cmp #ERR_DEVICE_NOT_CONNECTED
bne non_prodos
dey
lda (on_line_ptr),y
jsr IsDiskII
jne next_device
lda #ERR_DEVICE_NOT_CONNECTED
bne non_prodos ; always
done: rts
non_prodos:
pha
ldy #0
lda (on_line_ptr),y
and #UNIT_NUM_MASK
ldx num_drives
sta drive_unitnum_table,x
pla
IF_A_EQ #ERR_NOT_PRODOS_VOLUME
lda drive_unitnum_table,x
jsr NameNonProDOSVolume
beq next
END_IF
;; Unknown
lda num_drives
jsr GetDriveNameTableSlot
stax $06
ldy str_unknown
DO
copy8 str_unknown,y, ($06),y
dey
WHILE_POS
next: inc num_drives
jmp next_device
;; Valid ProDOS volume
is_prodos:
ldy #0
lda (on_line_ptr),y
and #UNIT_NUM_MASK
ldx num_drives
sta drive_unitnum_table,x
IF_A_EQ DISK_COPY_INITIAL_UNIT_NUM
copy8 num_drives, current_drive_selection
END_IF
name_ptr := $08
ldax on_line_ptr
jsr AdjustOnLineEntryCase
lda num_drives
jsr GetDriveNameTableSlot
stax name_ptr
ldy #kMaxFilenameLength
DO
copy8 (on_line_ptr),y, (name_ptr),y
dey
WHILE_POS
inc num_drives
next_device:
inc device_index
lda device_index
cmp #kMaxNumDrives+1
jne loop
rts
device_index:
.byte 0
.endproc ; EnumerateDevices
;;; ============================================================
;;; Sets `num_drives` to the number of plausible destination devices,
;;; and populates `destination_index_table`. Also clears selection.
.proc EnumerateDestinationDevices
;; Stash source drive details
lda current_drive_selection
asl a
tax
copy16 block_count_table,x, src_block_count
copy8 num_drives, num_src_drives
lda #0
sta num_drives
sta index
loop: lda index
;; Compare block counts
asl a
tax
ecmp16 block_count_table,x, src_block_count
bne next
;; Same - add it
lda index
ldx num_drives
sta destination_index_table,x
;; Keep going
inc num_drives
next: inc index
lda index
cmp num_src_drives
beq finish
jmp loop
;; Clear selection
finish: copy8 #$FF, current_drive_selection
rts
index: .byte 0
src_block_count:
.word 0
.endproc ; EnumerateDestinationDevices
;;; ============================================================
.proc DrawDeviceListEntry
sta device_index
ldx device_index
lda drive_unitnum_table,x
jsr PrepSDStrings
;; Slot
copy8 #kListEntrySlotOffset, list_entry_pos+MGTK::Point::xcoord
MGTK_CALL MGTK::MoveTo, list_entry_pos
param_call DrawString, str_s
;; Drive
copy8 #kListEntryDriveOffset, list_entry_pos+MGTK::Point::xcoord
MGTK_CALL MGTK::MoveTo, list_entry_pos
param_call DrawString, str_d
;; Name
copy8 #kListEntryNameOffset, list_entry_pos+MGTK::Point::xcoord
MGTK_CALL MGTK::MoveTo, list_entry_pos
lda device_index
jsr GetDriveNameTableSlot
jmp DrawString
device_index:
.byte 0
.endproc ; DrawDeviceListEntry
;;; ============================================================
;;; Populate block_count_table across all devices
.proc GetAllBlockCounts
copy8 #0, index
DO
jsr GetBlockCount
inc index
lda index
WHILE_A_NE num_drives
rts
index: .byte 0
.endproc ; GetAllBlockCounts
;;; ============================================================
;;; Inputs: A = device index
;;; Outputs: block_count_table (word) set to block count
.proc GetBlockCount
;; Special case Disk II devices, since we may be formatting non-ProDOS
;; disks the driver can't interrogate.
pha
tax ; X is device index
lda drive_unitnum_table,x
jsr IsDiskII
beq disk_ii
pla
pha
tax
lda drive_unitnum_table,x
jsr main::DeviceDriverAddress ; Z=1 if firmware
stax $06
jmp use_driver
;; Disk II - always 280 blocks
disk_ii:
pla
asl a
tax
copy16 #280, block_count_table,x
rts
;; Use device driver
use_driver:
pla
pha
tax
lda drive_unitnum_table,x
ldxy $06
jsr main::GetDeviceBlocksUsingDriver
stx tmp ; blocks available low
pla
asl a
tax
copy8 tmp, block_count_table,x
tya ; blocks available high
sta block_count_table+1,x
rts
tmp: .byte 0
.endproc ; GetBlockCount
;;; ============================================================
.proc DrawStatus
pha
txa
pha
jsr SetPortForDialog
MGTK_CALL MGTK::PaintRect, rect_status
MGTK_CALL MGTK::MoveTo, point_status
pla
tax
pla
jmp DrawStringCentered
.endproc ; DrawStatus
.proc DrawStatusWriting
param_call DrawStatus, str_writing
jmp DrawProgressBar
.endproc ; DrawStatusWriting
.proc DrawStatusReading
param_call DrawStatus, str_reading
jmp DrawProgressBar
.endproc ; DrawStatusReading
.proc DrawTotalBlocks
jsr IntToStringWithSeparators
jsr SetPortForDialog
MGTK_CALL MGTK::MoveTo, blocks_to_transfer_label_pos
param_call DrawString, blocks_to_transfer_label_str
jmp DrawIntString
.endproc ; DrawTotalBlocks
.proc IncAndDrawBlocksRead
jsr SetPortForDialog
inc16 blocks_read
ldax blocks_read
jsr IntToStringWithSeparators
MGTK_CALL MGTK::MoveTo, blocks_read_label_pos
param_call DrawString, blocks_read_label_str
jmp DrawIntString
.endproc ; IncAndDrawBlocksRead
.proc IncAndDrawBlocksWritten
jsr SetPortForDialog
inc16 blocks_written
ldax blocks_written
jsr IntToStringWithSeparators
MGTK_CALL MGTK::MoveTo, blocks_written_label_pos
param_call DrawString, blocks_written_label_str
FALL_THROUGH_TO DrawIntString
.endproc ; IncAndDrawBlocksWritten
.proc DrawIntString
param_call DrawString, str_from_int
param_jump DrawString, str_2_spaces
.endproc ; DrawIntString
blocks_read:
.word 0
blocks_written:
.word 0
transfer_blocks:
.word 0
.params progress_muldiv_params
number: .word kProgressWidth ; (in) constant
numerator: .word 0 ; (in) populated dynamically
denominator: .word 0 ; (in) populated dynamically
result: .word 0 ; (out)
remainder: .word 0 ; (out)
.endparams
.proc DrawProgressBar
MGTK_CALL MGTK::SetPenMode, notpencopy
MGTK_CALL MGTK::FrameRect, progress_frame
copy16 transfer_blocks, progress_muldiv_params::denominator
;; read+written will not fit in 16 bits if total is > $7FFF
;; so scale appropriately
tmp_read := $06
tmp_written := $08
copy16 blocks_read, tmp_read
copy16 blocks_written, tmp_written
bit progress_muldiv_params::denominator+1
IF_NC
;; Use (read + written) / total*2
asl16 progress_muldiv_params::denominator
ELSE
;; Use ((read + written) / 2) / total
lsr16 tmp_read
lsr16 tmp_written
END_IF
add16 tmp_read, tmp_written, progress_muldiv_params::numerator
MGTK_CALL MGTK::MulDiv, progress_muldiv_params
add16 progress_bar::x1, progress_muldiv_params::result, progress_bar::x2
MGTK_CALL MGTK::SetPenMode, pencopy
MGTK_CALL MGTK::SetPattern, progress_pattern
MGTK_CALL MGTK::PaintRect, progress_bar
rts
.endproc ; DrawProgressBar
;;; ============================================================
.proc DrawSourceDriveInfo
jsr SetPortForDialog
MGTK_CALL MGTK::MoveTo, source_label_pos
param_call DrawString, source_label_str
ldx source_drive_index
lda drive_unitnum_table,x
jsr PrepSDStrings
MGTK_CALL MGTK::MoveTo, point_source_slot_drive
param_call DrawString, str_slot_drive_pattern
bit source_disk_format
bpl show_name ; ProDOS
bvc :+ ; DOS 3.3
lda source_disk_format
and #$0F
beq show_name ; Pascal
: rts
show_name:
param_call DrawString, str_2_spaces
COPY_STRING main::on_line_buffer2, device_name_buf
param_call DrawString, device_name_buf
rts
.endproc ; DrawSourceDriveInfo
;;; ============================================================
.proc DrawDestinationDriveInfo
jsr SetPortForDialog
MGTK_CALL MGTK::MoveTo, destination_label_pos
param_call DrawString, destination_label_str
ldx dest_drive_index
lda drive_unitnum_table,x
jsr PrepSDStrings
MGTK_CALL MGTK::MoveTo, point_destination_slot_drive
param_call DrawString, str_slot_drive_pattern
rts
.endproc ; DrawDestinationDriveInfo
;;; ============================================================
.proc DrawCopyFormatType
jsr SetPortForDialog
MGTK_CALL MGTK::MoveTo, point_disk_copy
bit source_disk_format
IF_NC ; ProDOS
param_call DrawString, str_prodos_disk_copy
rts
END_IF
IF_VC ; DOS 3.3
param_call DrawString, str_dos33_disk_copy
rts
END_IF
lda source_disk_format
and #$0F
IF_ZERO ; Pascal
param_call DrawString, str_pascal_disk_copy
END_IF
rts
.endproc ; DrawCopyFormatType
.proc DrawEscToStopCopyHint
jsr SetPortForDialog
MGTK_CALL MGTK::MoveTo, escape_stop_copy_label_pos
param_call DrawStringCentered, escape_stop_copy_label_str
rts
.endproc ; DrawEscToStopCopyHint
;;; ============================================================
;;; Inputs: A = error code, X = writing flag
;;; Outputs: A=0 for ok, 1 for retry, $80 for cancel
.proc ShowBlockError
stx err_writing_flag
IF_A_EQ #ERR_WRITE_PROTECTED
jsr main::Bell
lda #kAlertMsgDestinationProtected ; no args
jsr ShowAlertDialog
.assert kAlertResultCancel <> 0, error, "Branch assumes enum value"
IF_ZERO
jsr DrawStatusWriting ; Try Again
return #1
END_IF
jsr main::FreeVolBitmapPages
return #$80
END_IF
jsr main::Bell
jsr SetPortForDialog
lda main::block_params::block_num
ldx main::block_params::block_num+1
jsr IntToStringWithSeparators
lda err_writing_flag
IF_ZERO
MGTK_CALL MGTK::MoveTo, error_reading_label_pos
param_call DrawString, error_reading_label_str
jsr DrawIntString
return #0
END_IF
MGTK_CALL MGTK::MoveTo, error_writing_label_pos
param_call DrawString, error_writing_label_str
jsr DrawIntString
return #0
err_writing_flag:
.byte 0
.endproc ; ShowBlockError
;;; ============================================================
;;; Read block (w/ retries) to aux memory
;;; Inputs: A,X=mem address to store it
;;; Outputs: A=0 on success, nonzero otherwise
.proc ReadBlockToAuxmem
ptr1 := $06
ptr2 := $08 ; one page up
jsr main::PrepBlockPtrs
;; Read block
jsr main::ReadBlockWithRetry
bmi ret
;; Copy block from main to aux
sta RAMRDOFF
sta RAMWRTON
ldy #$00
DO
copy8 default_block_buffer,y, (ptr1),y
copy8 default_block_buffer+$100,y, (ptr2),y
iny
WHILE_NOT_ZERO
sta RAMRDOFF
sta RAMWRTOFF
lda #0
ret: rts
.endproc ; ReadBlockToAuxmem
;;; ============================================================
;;; Write block (w/ retries) from aux memory
;;; Inputs: A,X=address to read from
;;; Outputs: A=0 on success, nonzero otherwise
.proc WriteBlockFromAuxmem
ptr1 := $06
ptr2 := $08 ; one page up
jsr main::PrepBlockPtrs
;; Copy block aux to main
sta RAMRDON
sta RAMWRTOFF
ldy #$00
DO
copy8 (ptr1),y, default_block_buffer,y
copy8 (ptr2),y, default_block_buffer+$100,y
iny
WHILE_NOT_ZERO
sta RAMRDOFF
sta RAMWRTOFF
;; Write block
jmp main::WriteBlockWithRetry
.endproc ; WriteBlockFromAuxmem
;;; ============================================================
;;; Input: A = unit number (i.e. %DSSSxxxx)
;;; Output: `str_slot_drive_pattern` populated
.proc PrepSDStrings
pha
jsr UnitNumToSlotDigit
sta str_s + 1
sta str_slot_drive_pattern + res_const_slot_drive_pattern_offset1
pla
jsr UnitNumToDriveDigit
sta str_d + 1
sta str_slot_drive_pattern + res_const_slot_drive_pattern_offset2
rts
.endproc ; PrepSDStrings
;;; Input: A = unit number (i.e. %DSSSxxxx)
;;; Output: A = ASCII digit '0' ... '7'
.proc UnitNumToSlotDigit
and #$70 ; A = %0SSS0000
lsr a ; A = %00SSS000
lsr a ; A = %000SSS00
lsr a ; A = %0000SSS0
lsr a ; A = %00000SSS
ora #'0'
rts
.endproc ; UnitNumToSlotDigit
;;; Input: A = unit number (i.e. %DSSSxxxx)
;;; Output: A = ASCII digit '1' or '2'
.proc UnitNumToDriveDigit
and #$80 ; A = %D0000000
asl a ; A = %00000000, C = D
rol a ; A = %0000000D, C = 0
adc #'1' ; no need to CLC
rts
.endproc ; UnitNumToDriveDigit
;;; ============================================================
.proc ShowAlertDialogImpl
;;; --------------------------------------------------
;;; Messages
str_insert_source:
PASCAL_STRING res_string_prompt_insert_source
str_insert_dest:
PASCAL_STRING res_string_prompt_insert_destination
str_confirm_erase:
PASCAL_STRING res_string_prompt_erase_prefix
str_confirm_erase_buf: .res 18, 0
kLenConfirmErase = .strlen(res_string_prompt_erase_prefix)
str_confirm_erase_suffix:
PASCAL_STRING res_string_prompt_erase_suffix
str_dest_format_fail:
PASCAL_STRING res_string_errmsg_dest_format_fail
str_format_error:
PASCAL_STRING res_string_errmsg_format_error
str_dest_protected:
PASCAL_STRING res_string_errmsg_dest_protected
;;; This string is seen when copying over a non-ProDOS/non-Pascal disk.
str_confirm_erase_sd:
PASCAL_STRING res_string_prompt_erase_slot_drive_pattern
kStrConfirmEraseSDSlotOffset = res_const_prompt_erase_slot_drive_pattern_offset1
kStrConfirmEraseSDDriveOffset = res_const_prompt_erase_slot_drive_pattern_offset2
str_copy_success:
PASCAL_STRING res_string_label_status_copy_success
str_copy_fail:
PASCAL_STRING res_string_label_status_copy_fail
str_insert_source_or_cancel:
PASCAL_STRING res_string_prompt_insert_source_or_cancel
str_insert_dest_or_cancel:
PASCAL_STRING res_string_prompt_insert_dest_or_cancel
alert_table:
.byte kAlertMsgInsertSource
.byte kAlertMsgInsertDestination
.byte kAlertMsgConfirmErase
.byte kAlertMsgDestinationFormatFail
.byte kAlertMsgFormatError
.byte kAlertMsgDestinationProtected
.byte kAlertMsgConfirmEraseSlotDrive
.byte kAlertMsgCopySuccessful
.byte kAlertMsgCopyFailure
.byte kAlertMsgInsertSourceOrCancel
.byte kAlertMsgInsertDestinationOrCancel
ASSERT_TABLE_SIZE alert_table, auxlc::kNumAlertMessages
message_table:
.addr str_insert_source
.addr str_insert_dest
.addr str_confirm_erase
.addr str_dest_format_fail
.addr str_format_error
.addr str_dest_protected
.addr str_confirm_erase_sd
.addr str_copy_success
.addr str_copy_fail
.addr str_insert_source_or_cancel
.addr str_insert_dest_or_cancel
ASSERT_ADDRESS_TABLE_SIZE message_table, auxlc::kNumAlertMessages
alert_button_options_table:
.byte AlertButtonOptions::OKCancel ; kAlertMsgInsertSource
.byte AlertButtonOptions::OKCancel ; kAlertMsgInsertDestination
.byte AlertButtonOptions::OKCancel ; kAlertMsgConfirmErase
.byte AlertButtonOptions::OK ; kAlertMsgDestinationFormatFail
.byte AlertButtonOptions::TryAgainCancel ; kAlertMsgFormatError
.byte AlertButtonOptions::TryAgainCancel ; kAlertMsgDestinationProtected
.byte AlertButtonOptions::OKCancel ; kAlertMsgConfirmEraseSlotDrive
.byte AlertButtonOptions::OK ; kAlertMsgCopySuccessful
.byte AlertButtonOptions::OK ; kAlertMsgCopyFailure
.byte AlertButtonOptions::OK ; kAlertMsgInsertSourceOrCancel
.byte AlertButtonOptions::OK ; kAlertMsgInsertDestinationOrCancel
ASSERT_TABLE_SIZE alert_button_options_table, auxlc::kNumAlertMessages
alert_options_table:
.byte 0 ; kAlertMsgInsertSource
.byte 0 ; kAlertMsgInsertDestination
.byte 0 ; kAlertMsgConfirmErase
.byte AlertOptions::Beep ; kAlertMsgDestinationFormatFail
.byte AlertOptions::Beep ; kAlertMsgFormatError
.byte AlertOptions::Beep ; kAlertMsgDestinationProtected
.byte 0 ; kAlertMsgConfirmEraseSlotDrive
.byte 0 ; kAlertMsgCopySuccessful
.byte 0 ; kAlertMsgCopyFailure
.byte 0 ; kAlertMsgInsertSourceOrCancel
.byte 0 ; kAlertMsgInsertDestinationOrCancel
ASSERT_TABLE_SIZE alert_options_table, auxlc::kNumAlertMessages
.params alert_params
text: .addr 0
buttons: .byte 0 ; AlertButtonOptions
options: .byte 0 ; AlertOptions
.endparams
start:
pha ; A = alert id
CLEAR_BIT7_FLAG ejectable_flag
;; --------------------------------------------------
;; Determine alert options
pla ; A = alert id
.assert kAlertMsgInsertSource = 0, error, "enum mismatch"
IF_EQ ; kAlertMsgInsertSource
cpx #0
beq find_in_alert_table
jsr _IsDriveEjectable
beq find_in_alert_table ; nope, stick with kAlertMsgInsertSource
lda #kAlertMsgInsertSourceOrCancel
bne find_in_alert_table ; always
END_IF
IF_A_EQ #kAlertMsgInsertDestination
cpx #0
beq find_in_alert_table
jsr _IsDriveEjectable
IF_NOT_ZERO
lda #kAlertMsgInsertDestinationOrCancel
bne find_in_alert_table ; always
END_IF
lda #kAlertMsgInsertDestination
bne find_in_alert_table ; always
END_IF
IF_A_EQ #kAlertMsgConfirmErase
jsr _AppendToConfirmErase
lda #kAlertMsgConfirmErase
bne find_in_alert_table ; always
END_IF
IF_A_EQ #kAlertMsgConfirmEraseSlotDrive
jsr _SetConfirmEraseSdSlotDrive
lda #kAlertMsgConfirmEraseSlotDrive
FALL_THROUGH_TO find_in_alert_table
END_IF
find_in_alert_table:
;; A = alert id; search table to determine index
ldy #0
DO
cmp alert_table,y
beq :+
iny
WHILE_Y_NE #kNumAlertMessages
ldy #0 ; default
:
;; Y = index
tya
asl a
tay
copy16 message_table,y, alert_params::text
tya
lsr a
tay
copy8 alert_button_options_table,y, alert_params::buttons
copy8 alert_options_table,y, alert_params::options
param_jump Alert, alert_params
;;; --------------------------------------------------
;;; Inputs: X,Y = volume name
.proc _AppendToConfirmErase
ptr := $06
stxy ptr
ldy #$00
lda (ptr),y
pha
tay
DO
copy8 (ptr),y, str_confirm_erase_buf-1,y
dey
WHILE_NOT_ZERO
pla
clc
adc #kLenConfirmErase
tay
ldx #0
DO
iny
inx
copy8 str_confirm_erase_suffix,x, str_confirm_erase,y
WHILE_X_NE str_confirm_erase_suffix
sty str_confirm_erase
rts
.endproc ; _AppendToConfirmErase
;;; --------------------------------------------------
;;; Inputs: X = %DSSSxxxx
.proc _SetConfirmEraseSdSlotDrive
txa
jsr UnitNumToSlotDigit
sta str_confirm_erase_sd + kStrConfirmEraseSDSlotOffset
txa
jsr UnitNumToDriveDigit
sta str_confirm_erase_sd + kStrConfirmEraseSDDriveOffset
rts
.endproc ; _SetConfirmEraseSdSlotDrive
;;; --------------------------------------------------
;;; Y = unit number
;;; If ejectable, sets `ejectable_flag`
.proc _IsDriveEjectable
sty unit_num
tya
jsr main::IsDriveEjectable
IF_NS
sta ejectable_flag
END_IF
rts
.endproc ; _IsDriveEjectable
.endproc ; ShowAlertDialogImpl
ShowAlertDialog := ShowAlertDialogImpl::start
;;; ============================================================
.scope alert_dialog
alert_grafport := grafport
Bell := main::Bell
AD_EJECTABLE = 1
.include "../lib/alert_dialog.s"
;;; ============================================================
;;; Poll the drive in `unit_num` until a disk is inserted, or
;;; the Escape key is pressed.
;;; Output: A = 0 if disk inserted, $80 if Escape pressed
.proc WaitForDiskOrEsc
@retry:
;; Poll drive until something is present
;; (either a ProDOS disk or a non-ProDOS disk)
copy8 unit_num, main::on_line_params::unit_num
jsr main::CallOnLine
bcc done
cmp #ERR_NOT_PRODOS_VOLUME
beq done
lda main::on_line_buffer
and #NAME_LENGTH_MASK
bne done
lda main::on_line_buffer+1
cmp #ERR_NOT_PRODOS_VOLUME
beq done
jsr SystemTask
MGTK_CALL MGTK::GetEvent, Alert::event_params
lda Alert::event_kind
cmp #MGTK::EventKind::key_down
bne @retry
lda Alert::event_key
cmp #CHAR_ESCAPE
bne @retry
return #$80
done: return #$00
.endproc ; WaitForDiskOrEsc
.endscope ; alert_dialog
Alert := alert_dialog::Alert
;;; ============================================================
;;; Called by main and nested event loops to do periodic tasks.
;;; Returns 0 if the periodic tasks were run.
.proc SystemTask
kMaxCounter = $E0 ; arbitrary
inc loop_counter
inc loop_counter
loop_counter := *+1
lda #SELF_MODIFIED_BYTE
cmp #kMaxCounter
IF_GE
copy8 #0, loop_counter
jsr main::ResetIIgsRGB ; in case it was reset by control panel
END_IF
lda loop_counter
rts
.endproc ; SystemTask
.include "../lib/is_diskii.s"
.include "../lib/doubleclick.s"
.include "../lib/uppercase.s"
;;; ============================================================
.proc CheckEvents
MGTK_CALL MGTK::CheckEvents
rts
.endproc ; CheckEvents
;;; ============================================================
.proc StopDeskTop
MGTK_CALL MGTK::StopDeskTop
rts
.endproc ; StopDeskTop
;;; ============================================================
.assert * <= $F200, error, "Update memory_bitmap if code extends past $F200"
.endscope ; auxlc
ENDSEG SegmentAuxLC
|
a2stuff/a2d
| 1,446
|
src/disk_copy/disk_copy.s
|
.include "../config.inc"
BTK_SHORT = 1
.include "apple2.inc"
.include "opcodes.inc"
.include "../inc/apple2.inc"
.include "../inc/macros.inc"
.include "../inc/prodos.inc"
.include "../inc/smartport.inc"
.include "../mgtk/mgtk.inc"
.include "../common.inc"
.include "../toolkits/btk.inc"
.include "../toolkits/lbtk.inc"
.include "../lib/alert_dialog.inc"
.include "disk_copy.inc"
;;; ============================================================
;;; Memory Constants
;;; MGTK - left over in Aux by DeskTop
MGTKAuxEntry := $4000
;;; Font - left over in Aux by DeskTop
DEFAULT_FONT := $8800
;;; ============================================================
;;; File Structure
;;; ============================================================
INITSEG 0
DEFSEG Loader, DISK_COPY_BOOTSTRAP, kDiskCopyBootstrapLength
DEFSEG SegmentAuxLC, $D000, $2200
DEFSEG SegmentMain, $0800, $0C00
;; Update `memory_bitmap` in main.s if these change!
;;; ============================================================
;;; Disk Copy module
;;; ============================================================
RESOURCE_FILE "disk_copy.res"
PREDEFINE_SCOPE ::auxlc
PREDEFINE_SCOPE ::main
.include "loader.s"
.include "auxlc.s"
.include "main.s"
|
a2stuff/a2d
| 451,954
|
src/desktop/main.s
|
;;; ============================================================
;;; Desktop - Main Memory Segment
;;;
;;; Compiled as part of desktop.s
;;; ============================================================
.include "../disk_copy/disk_copy.inc"
;;; ============================================================
;;; Segment loaded into MAIN $4000-$BEFF
;;; ============================================================
BEGINSEG SegmentDeskTopMain
.scope main
MLIEntry := MLIRelayImpl
MGTKEntry := ::MGTKRelayImpl
LETKEntry := LETKRelayImpl
BTKEntry := BTKRelayImpl
LBTKEntry := LBTKRelayImpl
ITKEntry := ITKRelayImpl
src_path_buf := INVOKER_PREFIX
dst_path_buf := $1F80
;; Jump table
;; Entries marked with * are used by DAs
;; "Exported" by desktop.inc
JT_MGTK_CALL: jmp ::MGTKRelayImpl ; *
JT_MLI_CALL: jmp MLIRelayImpl ; *
JT_CLEAR_UPDATES: jmp ClearUpdates ; *
JT_SYSTEM_TASK: jmp SystemTask ; *
JT_ACTIVATE_WINDOW: jmp ActivateAndRefreshWindow ; *
JT_SHOW_ALERT: jmp ShowAlert ; *
JT_SHOW_ALERT_PARAMS: jmp ShowAlertStruct ; *
JT_LAUNCH_FILE: jmp LaunchFileWithPath
JT_SHOW_FILE: jmp ShowFileWithPath ; *
JT_RESTORE_OVL: jmp RestoreDynamicRoutine ; *
JT_COLOR_MODE: jmp SetColorMode ; *
JT_MONO_MODE: jmp SetMonoMode ; *
JT_RGB_MODE: jmp SetRGBMode ; *
JT_RESTORE_SYS: jmp RestoreSystem ; *
JT_GET_SEL_COUNT: jmp GetSelectionCount ; *
JT_GET_SEL_ICON: jmp GetSelectedIcon ; *
JT_GET_SEL_WIN: jmp GetSelectionWindow ; *
JT_GET_WIN_PATH: jmp GetWindowPath ; *
JT_HILITE_MENU: jmp ToggleMenuHilite ; *
JT_ADJUST_FILEENTRY: jmp AdjustFileEntryCase ; *
JT_ADJUST_ONLINEENTRY: jmp AdjustOnLineEntryCase ; *
JT_GET_RAMCARD_FLAG: jmp GetCopiedToRAMCardFlag ; *
JT_GET_ORIG_PREFIX: jmp CopyDeskTopOriginalPrefix ; *
JT_BELL: jmp Bell ; *
JT_SLOW_SPEED: jmp SlowSpeed ; *
JT_RESUME_SPEED: jmp ResumeSpeed ; *
JT_READ_SETTING: jmp ReadSetting ; *
JT_GET_TICKS: jmp GetTickCount ; *
ASSERT_EQUALS ::JUMP_TABLE_LAST, *
.macro PROC_USED_IN_OVERLAY
.assert * < OVERLAY_BUFFER || * >= OVERLAY_BUFFER + kOverlayBufferSize, error, "Routine used by overlays in overlay zone"
.endmacro
;;; ============================================================
;;; Main event loop for the application
.proc MainLoop
;; Poll drives every Nth time `SystemTask` does its thing.
;; At 1MHz on a //e this is about once every 3 seconds.
kDrivePollFrequency = 35
;; Close any windows that are not longer valid, if necessary
jsr ValidateWindows
;; Enable/disable menu items, based on windows/selection
jsr UpdateMenuItemStates
;; Can loop to here if no state changed
loop:
jsr SystemTask
IF_ZS
;; Maybe poll drives for updates
dec counter
IF_NEG
copy8 #kDrivePollFrequency, counter
jsr CheckDiskInsertedEjected
jmp MainLoop
END_IF
END_IF
;; Get an event
jsr GetNextEvent
;; Did the mouse move?
IF_A_EQ #kEventKindMouseMoved
jsr ClearTypeDown ; always returns Z=1
beq loop ; just to `loop` because no state change
END_IF
;; Is it a key down event?
IF_A_EQ #MGTK::EventKind::key_down
jsr HandleKeydown
jmp MainLoop
END_IF
;; Is it a button-down event? (including w/ modifiers)
IF_A_EQ_ONE_OF #MGTK::EventKind::button_down, #MGTK::EventKind::apple_key
jsr HandleClick
jsr ClearTypeDown ; always returns Z=1
beq MainLoop ; always
END_IF
;; Is it an update event?
IF_A_EQ #MGTK::EventKind::update
jsr ClearUpdatesSkipGet
END_IF
jmp loop
counter:
.byte 0
.endproc ; MainLoop
;;; ============================================================
;;; Clear Updates
;;; MGTK sends a update event when a window needs to be redrawn
;;; because it was revealed by another operation (e.g. close).
;;; This is called implicitly during the main loop if an update
;;; event is seen, and also explicitly following operations
;;; (e.g. a window close followed by a nested loop or slow
;;; file operation).
.proc ClearUpdates
DO
jsr PeekEvent
lda event_params::kind
BREAK_IF_A_NE #MGTK::EventKind::update
jsr GetEvent ; no need to synthesize events
;;; If caller already called GetEvent, start here.
skip_get:
MGTK_CALL MGTK::BeginUpdate, event_params::window_id
CONTINUE_IF_NOT_ZERO ; obscured
lda event_params::window_id
IF_ZERO
;; Desktop
ITK_CALL IconTK::DrawAll, event_params::window_id
ELSE_IF_A_LT #kMaxDeskTopWindows+1; 1...max are ours
;; Directory Window
jsr UpdateWindow
END_IF
MGTK_CALL MGTK::EndUpdate
WHILE_ZERO ; always
rts
.endproc ; ClearUpdates
ClearUpdatesSkipGet := ClearUpdates::skip_get
;;; ============================================================
;;; Called by main and nested event loops to do periodic tasks.
;;; Returns 0 if the periodic tasks were run.
PROC_USED_IN_OVERLAY
.proc SystemTask
inc24 tick_counter
inc loop_counter
inc loop_counter
loop_counter := *+1
lda #SELF_MODIFIED_BYTE
IF_A_GE periodic_task_delay ; for per-machine timing
copy8 #0, loop_counter
jsr ShowClock
jsr ResetIIgsRGB ; in case it was reset by control panel
END_IF
lda loop_counter
rts
.endproc ; SystemTask
;;; ============================================================
.proc GetTickCount
lda tick_counter
ldx tick_counter+1
ldy tick_counter+2
rts
.endproc ; GetTickCount
tick_counter:
.faraddr 0
;;; ============================================================
;;; Inputs: A = `window_id` from `update` event
.proc UpdateWindow
sta getwinport_params::window_id
jsr LoadWindowEntryTable
;; `DrawWindowHeader` and `AdjustUpdatePortForEntries` rely on
;; `window_grafport` for dimensions
MGTK_CALL MGTK::GetWinPort, getwinport_params
;; This correctly uses the clipped port provided by BeginUpdate.
jsr DrawWindowHeader
jsr AdjustUpdatePortForEntries
jmp DrawWindowEntries
.endproc ; UpdateWindow
;;; ============================================================
;;; Menu Dispatch
.proc HandleKeydown
;; Handle accelerator keys
lda event_params::modifiers
bne modifiers ; either Open-Apple or Solid-Apple ?
;; --------------------------------------------------
;; No modifiers
lda event_params::key
jsr CheckTypeDown
RTS_IF_ZERO
jsr ClearTypeDown
lda event_params::key
cmp #CHAR_LEFT
jeq KeyboardHighlightLeft
cmp #CHAR_UP
jeq KeyboardHighlightUp
cmp #CHAR_RIGHT
jeq KeyboardHighlightRight
cmp #CHAR_DOWN
jeq KeyboardHighlightDown
cmp #CHAR_TAB
jeq KeyboardHighlightAlpha
cmp #'`'
jeq KeyboardHighlightAlphaNext ; like Tab
cmp #'~'
jeq KeyboardHighlightAlphaPrev ; like Shift+Tab
jmp menu_accelerators
;; --------------------------------------------------
;; Modifiers
modifiers:
jsr ClearTypeDown
lda event_params::modifiers
IF_A_EQ #3 ; both Open-Apple + Solid-Apple ?
;; Double-modifier shortcuts
lda event_params::key
jsr ToUpperCase
cmp #res_char_menu_item_open_shortcut
jeq CmdOpenThenCloseCurrent
cmp #CHAR_DOWN
jeq CmdOpenThenCloseCurrent
cmp #CHAR_UP
jeq CmdOpenParentThenCloseCurrent
cmp #kShortcutCloseWindow
jeq CmdCloseAll
cmp #CHAR_CTRL_F
jeq CmdFlipScreen
rts
END_IF
;; Non-menu keys
lda event_params::key
jsr ToUpperCase
cmp #CHAR_DOWN ; Apple-Down (Open)
jeq CmdOpenFromKeyboard
cmp #CHAR_UP ; Apple-Up (Open Parent)
jeq CmdOpenParent
ldx active_window_id
IF_NOT_ZERO
cmp #kShortcutGrowWindow ; Apple-G (Resize)
jeq CmdResize
cmp #kShortcutMoveWindow ; Apple-M (Move)
jeq CmdMove
cmp #kShortcutScrollWindow ; Apple-S (Scroll)
jeq CmdScroll
IF_A_EQ_ONE_OF #'`', #'~', #CHAR_TAB ; Apple-`, Shift-Apple-`, Apple-Tab (Cycle Windows)
jmp CmdCycleWindows
END_IF
END_IF
;; Not one of our shortcuts - check for menu keys
;; (shortcuts or entering keyboard menu mode)
menu_accelerators:
copy8 event_params::key, menu_click_params::which_key
copy8 event_params::modifiers, menu_click_params::key_mods
CLEAR_BIT7_FLAG menu_modified_click_flag ; note that source is not Apple+click
MGTK_CALL MGTK::MenuKey, menu_click_params
FALL_THROUGH_TO MenuDispatch
.endproc ; HandleKeydown
.proc MenuDispatch
ldx menu_click_params::menu_id ; X = menu id (1-based)
RTS_IF_ZERO
copy8 offset_table-1,x, tmp ; A = `dispatch_table` offset for that menu
lda menu_click_params::item_num ; A = menu item id (1-based)
asl a ; *= 2; Assert: C=0
tmp := *+1
adc #SELF_MODIFIED_BYTE
tax
copy16 dispatch_table-2,x, proc_addr
jsr call_proc
MGTK_CALL MGTK::HiliteMenu, menu_click_params
copy8 #0, menu_click_params::menu_id ; for `ToggleMenuHilite`
rts
call_proc:
tsx
stx saved_stack
proc_addr := *+1
jmp SELF_MODIFIED
;; Keep in sync with aux::menu_item_id_*
;; jump table for menu item handlers
dispatch_table:
;; Apple menu (1)
menu1_start := *
.addr CmdAbout
.addr CmdAboutThisApple
.addr 0 ; --------
.repeat ::kMaxDeskAccCount
.addr CmdDeskAcc
.endrepeat
ASSERT_ADDRESS_TABLE_SIZE menu1_start, ::kMenuSizeApple
;; File menu (2)
menu2_start := *
.addr CmdNewFolder
.addr CmdOpen
.addr CmdClose
.addr CmdCloseAll
.addr 0 ; --------
.addr CmdGetInfo
.addr CmdRename
.addr CmdDuplicate
.addr 0 ; --------
.addr CmdCopySelection
.addr CmdDeleteSelection
.addr 0 ; --------
.addr CmdQuit
ASSERT_ADDRESS_TABLE_SIZE menu2_start, ::kMenuSizeFile
;; Edit menu (3)
menu3_start := *
.addr CmdCut
.addr CmdCopy
.addr CmdPaste
.addr CmdClear
.addr 0 ; --------
.addr CmdSelectAll
ASSERT_ADDRESS_TABLE_SIZE menu3_start, ::kMenuSizeEdit
;; View menu (4)
menu4_start := *
.addr CmdViewBy
.addr CmdViewBy
.addr CmdViewBy
.addr CmdViewBy
.addr CmdViewBy
.addr CmdViewBy
ASSERT_ADDRESS_TABLE_SIZE menu4_start, ::kMenuSizeView
;; Special menu (5)
menu5_start := *
.addr CmdCheckAllDrives
.addr CmdCheckDrive
.addr CmdEject
.addr 0 ; --------
.addr CmdFormatDisk
.addr CmdEraseDisk
.addr CmdDiskCopy
.addr 0 ; --------
.addr CmdMakeLink
.addr CmdShowLink
ASSERT_ADDRESS_TABLE_SIZE menu5_start, ::kMenuSizeSpecial
;; Startup menu (6)
menu6_start := *
.addr CmdStartupItem
.addr CmdStartupItem
.addr CmdStartupItem
.addr CmdStartupItem
.addr CmdStartupItem
.addr CmdStartupItem
.addr CmdStartupItem
ASSERT_ADDRESS_TABLE_SIZE menu6_start, ::kMenuSizeStartup
;; Selector menu (7)
menu7_start := *
.addr CmdSelectorAction
.addr CmdSelectorAction
.addr CmdSelectorAction
.addr CmdSelectorAction
.addr 0 ; --------
.addr CmdSelectorItem
.addr CmdSelectorItem
.addr CmdSelectorItem
.addr CmdSelectorItem
.addr CmdSelectorItem
.addr CmdSelectorItem
.addr CmdSelectorItem
.addr CmdSelectorItem
ASSERT_ADDRESS_TABLE_SIZE menu7_start, ::kMenuSizeSelector
menu_end := *
;; indexed by menu id-1
offset_table:
.byte menu1_start - dispatch_table
.byte menu2_start - dispatch_table
.byte menu3_start - dispatch_table
.byte menu4_start - dispatch_table
.byte menu5_start - dispatch_table
.byte menu6_start - dispatch_table
.byte menu7_start - dispatch_table
.byte menu_end - dispatch_table
ASSERT_TABLE_SIZE offset_table, ::kMenuNumItems+1
.endproc ; MenuDispatch
;;; ============================================================
;;; Handle click
.proc HandleClick
tsx
stx saved_stack
MGTK_CALL MGTK::FindWindow, findwindow_params
lda findwindow_params::which_area
IF_ZERO
;; Click on desktop
lda #0
sta clicked_window_id
sta findwindow_params::window_id
ITK_CALL IconTK::FindIcon, event_params::coords
lda findicon_params::which_icon
jne _IconClick
lda #0
jmp DragSelect
END_IF
IF_A_EQ #MGTK::Area::menubar ; menu?
;; Maybe clock?
lda MACHID
and #kMachIDHasClock
IF_NE
cmp16 event_params::xcoord, #460 ; TODO: Hard coded?
IF_GE
param_jump InvokeDeskAccWithIcon, $FF, str_date_and_time
END_IF
END_IF
;; Note if menu showing via modified click
jsr ModifierDown
sta menu_modified_click_flag
MGTK_CALL MGTK::MenuSelect, menu_click_params
;; But allow double-modifier click or shortcut too
lda BUTN0
and BUTN1
ora menu_modified_click_flag
sta menu_modified_click_flag
jmp MenuDispatch
END_IF
jsr window_click
lda selected_icon_count
IF_ZERO
;; Try to select the window's parent icon.
lda active_window_id
IF_NOT_ZERO
jsr GetWindowPath
jsr IconToAnimate
jmp SelectIcon
END_IF
END_IF
rts
;; --------------------------------------------------
window_click:
IF_A_NE #MGTK::Area::content
pha ; A = MGTK::Area::*
;; Activate if needed
lda findwindow_params::window_id
jsr ActivateWindow ; no-op if already active
pla ; A = MGTK::Area::*
cmp #MGTK::Area::dragbar
jeq DoWindowDrag
cmp #MGTK::Area::grow_box
jeq DoWindowResize
cmp #MGTK::Area::close_box
jeq HandleCloseClick
rts
END_IF
;;; --------------------------------------------------
.scope _ContentClick
lda findwindow_params::window_id
sta clicked_window_id
sta findcontrolex_params::window_id
MGTK_CALL MGTK::FindControlEx, findcontrolex_params
lda findcontrol_params::which_ctl
ASSERT_EQUALS MGTK::Ctl::not_a_control, 0
IF_ZERO
;; Ignore clicks in the header area
copy8 clicked_window_id, screentowindow_params::window_id
MGTK_CALL MGTK::ScreenToWindow, screentowindow_params
lda screentowindow_params::windowy
IF_A_LT #kWindowHeaderHeight
jmp _ActivateClickedWindow ; no-op if already active
END_IF
;; On an icon?
copy8 clicked_window_id, findicon_params::window_id
ITK_CALL IconTK::FindIcon, findicon_params
lda findicon_params::which_icon
jne _IconClick
;; Not an icon - maybe a drag?
jsr _ActivateClickedWindow ; no-op if already active
lda active_window_id
jmp DragSelect
END_IF
;; --------------------------------------------------
;; If not the active window, just activate it
lda clicked_window_id
cmp active_window_id
jne ActivateWindow
lda findcontrol_params::which_ctl
RTS_IF_A_EQ #MGTK::Ctl::dead_zone
IF_A_EQ #MGTK::Ctl::vertical_scroll_bar
;; Vertical scrollbar
;; Thumb?
ldy findcontrol_params::which_part
cpy #MGTK::Part::thumb
beq _TrackThumb
;; Other parts
lda v_proc_lo-1,y ; A = proc lo
ldx v_proc_hi-1,y ; X = proc hi
bne _DoScrollbarPart ; always; Y = part
END_IF
;; Horizontal scrollbar
;; Thumb?
ldy findcontrol_params::which_part
cpy #MGTK::Part::thumb
beq _TrackThumb
;; Other parts
lda h_proc_lo-1,y ; A = proc hi
ldx h_proc_hi-1,y ; X = proc hi
FALL_THROUGH_TO _DoScrollbarPart ; Y = part
;;; ------------------------------------------------------------
;;; Input: A,X = proc, Y = part
.proc _DoScrollbarPart
stax proc
sty part
copy8 findcontrol_params::which_ctl, ctl
DO
;; Dispatch to handler
proc := *+1
jsr SELF_MODIFIED
;; Check for control repeat
jsr PeekEvent
lda event_params::kind
BREAK_IF_A_NE #MGTK::EventKind::drag
MGTK_CALL MGTK::FindControl, findcontrol_params
lda findcontrol_params::which_ctl
ctl := *+1
cmp #SELF_MODIFIED_BYTE
BREAK_IF_NE
lda findcontrol_params::which_part
part := *+1
cmp #SELF_MODIFIED_BYTE
WHILE_EQ
rts
.endproc ; _DoScrollbarPart
v_proc_lo: .lobytes ScrollUp, ScrollDown, ScrollPageUp, ScrollPageDown
v_proc_hi: .hibytes ScrollUp, ScrollDown, ScrollPageUp, ScrollPageDown
h_proc_lo: .lobytes ScrollLeft, ScrollRight, ScrollPageLeft, ScrollPageRight
h_proc_hi: .hibytes ScrollLeft, ScrollRight, ScrollPageLeft, ScrollPageRight
;;; ------------------------------------------------------------
.proc _TrackThumb
copy8 findcontrol_params::which_ctl, trackthumb_params::which_ctl
MGTK_CALL MGTK::TrackThumb, trackthumb_params
lda trackthumb_params::thumbmoved
RTS_IF_ZERO
lda trackthumb_params::which_ctl
cmp #MGTK::Ctl::vertical_scroll_bar
jeq ScrollTrackVThumb
jmp ScrollTrackHThumb
.endproc ; _TrackThumb
.endscope ; _ContentClick
;;; ------------------------------------------------------------
;;; Handle a click on an icon, either windowed or desktop. They
;;; are processed the same way, unless a drag occurs.
;;; Input: A = icon
;;; `findicon_params::which_icon` and `findicon_params::window_id`
;;; must still be populated
.proc _IconClick
pha
jsr GetSingleSelectedIcon
sta prev_selected_icon
pla
jsr IsIconSelected
IF_EQ
;; --------------------------------------------------
;; Icon was already selected
jsr ExtendSelectionModifierDown
IF_NS
;; Modifier down - remove from selection
lda findicon_params::which_icon
jsr UnhighlightAndDeselectIcon
jmp _ActivateClickedWindow ; no-op if already active
END_IF
ELSE
;; --------------------------------------------------
;; Icon was not already selected
jsr ExtendSelectionModifierDown
IF_NS
;; Modifier down - add to selection
;; ...if there is a selection, and it is same window
lda selected_icon_count
IF_NOT_ZERO
lda findicon_params::window_id
IF_A_EQ selected_window_id
lda findicon_params::which_icon
jsr AddIconToSelection
jmp :+
END_IF
END_IF
END_IF
;; Otherwise, replace selection with clicked icon
lda findicon_params::which_icon
jsr SelectIcon
:
END_IF
;; --------------------------------------------------
;; Stash initial coords so dragging is accurate,
;; and check for double-click
COPY_STRUCT event_params::coords, drag_drop_params::coords
jsr DetectDoubleClick
IF_NC
jsr _ActivateClickedWindow ; no-op if already active
jmp CmdOpenFromDoubleClick
END_IF
;; --------------------------------------------------
;; Drag of icon?
copy8 findicon_params::which_icon, drag_drop_params::icon
ITK_CALL IconTK::DragHighlighted, drag_drop_params
RTS_IF_A_EQ #IconTK::kDragResultCanceled
IF_A_EQ #IconTK::kDragResultNotADrag
jsr _ActivateClickedWindow ; no-op if already active
jmp _CheckRenameClick
END_IF
;; ----------------------------------------
IF_A_EQ #IconTK::kDragResultMove
jsr RedrawSelectedIcons
jsr _ActivateClickedWindow ; no-op if already active
lda selected_window_id
RTS_IF_ZERO
jmp ScrollUpdate
END_IF
;; ----------------------------------------
;; File drop on same window:
;; * No modifiers - move (see `kDragResultMove` case above)
;; * Single modifier - duplicate
;; * Double modifiers - make link
;; Volume drop on desktop:
;; * No modifiers - move (see `kDragResultMove` case above)
;; * Single modifier - ignore
;; * Double modifiers - ignore
IF_A_EQ #IconTK::kDragResultMoveModified
lda selected_window_id
RTS_IF_ZERO
jsr _ActivateClickedWindow
;; File drop on same window, but with modifier(s) down so not a move
jsr GetSingleSelectedIcon
RTS_IF_ZERO
;; Double modifier?
lda BUTN0
and BUTN1
IF_NS
jsr SetPathBuf4FromDragDropResult
RTS_IF_CS ; failure, e.g. path too long
jmp MakeLinkInTarget
END_IF
;; Single modifier
jmp CmdDuplicate
END_IF
;; ----------------------------------------
;; A = `IconTK::kDragResultDrop`
;; File drop on target:
;; * No modifiers - copy/move (depending on other/same vol)
;; * Single modifier - copy/move (ditto, but opposite)
;; * Double modifiers - make link
;; Volume drop on target:
;; * No modifiers - copy
;; * Single modifier - copy
;; * Double modifiers - make link
lda drag_drop_params::target
;; Trash?
IF_A_EQ trash_icon_num
lda selected_window_id
jeq CmdEject
jmp CmdDeleteSelection
END_IF
;; Desktop?
RTS_IF_A_EQ #$80 ; ignore
;; Path for target
jsr SetPathBuf4FromDragDropResult
RTS_IF_CS ; failure, e.g. path too long
;; Double modifier?
lda BUTN0
and BUTN1
IF_NS
jsr GetSingleSelectedIcon
RTS_IF_ZERO
jmp MakeLinkInTarget
END_IF
;; Copy/Move
jsr DoCopyOrMoveSelection
jmp _PerformPostDropUpdates
.endproc ; _IconClick
;;; ------------------------------------------------------------
;;; Used during icon click to trigger rename
prev_selected_icon:
.byte 0
;;; Prior to processing the click, `prev_selected_icon` should
;;; be set to the result of `GetSingleSelectedIcon`.
.proc _CheckRenameClick
jsr GetSingleSelectedIcon
IF_A_EQ prev_selected_icon
IF_A_NE trash_icon_num
sta icon_param
ITK_CALL IconTK::GetRenameRect, icon_param
MGTK_CALL MGTK::MoveTo, event_params::coords
MGTK_CALL MGTK::InRect, tmp_rect
jne CmdRename
END_IF
END_IF
rts
.endproc ; _CheckRenameClick
;;;------------------------------------------------------------
;;; After an icon drop (file or volume), update any affected
;;; windows.
;;; Inputs: A = `kOperationXYZ`, and `drag_drop_params::target`
.proc _PerformPostDropUpdates
;; --------------------------------------------------
;; (1/4) Canceled?
RTS_IF_A_EQ #kOperationCanceled
;; --------------------------------------------------
;; (2/4) Was a move?
;; NOTE: Only applies in file icon case.
PREDEFINE_SCOPE ::main::operations
bit operations::move_flags
IF_NS
;; Update source vol's contents
jsr MaybeStashDropTargetName ; in case target is in window...
jsr UpdateActivateAndRefreshSelectedWindow
jsr MaybeUpdateDropTargetFromName ; ...restore after update.
END_IF
;; --------------------------------------------------
;; (3/4) Dropped on icon?
lda drag_drop_params::target
IF_NC
;; Yes, on an icon; update used/free for same-vol windows
pha
jsr GetIconPath ; `path_buf3` set to path, A=0 on success
IF_ZERO
param_call UpdateUsedFreeViaPath, path_buf3
END_IF
pla
jsr FindWindowIndexForDirIcon ; X = window id-1 if found
IF_EQ
inx
txa
jmp ActivateAndRefreshWindowOrClose
END_IF
rts
END_IF
;; --------------------------------------------------
;; (4/4) Dropped on window!
and #$7F ; mask off window number
jmp UpdateActivateAndRefreshWindow
.endproc ; _PerformPostDropUpdates
.proc _ActivateClickedWindow
window_id := *+1
lda #SELF_MODIFIED_BYTE
FALL_THROUGH_TO ActivateWindow
.endproc ; _ActivateClickedWindow
clicked_window_id := _ActivateClickedWindow::window_id
.endproc ; HandleClick
;;; ============================================================
;;; Activate the window, draw contents, and update menu items
;;; No-op if the window is already active, or if 0 passed.
;;; Inputs: A = window id to activate
.proc ActivateWindow
RTS_IF_A_EQ active_window_id
RTS_IF_A_EQ #0
;; Make the window active.
sta active_window_id
MGTK_CALL MGTK::SelectWindow, active_window_id
;; Repaint the contents
jsr UpdateWindowUsedFreeDisplayValues
jsr LoadActiveWindowEntryTable
FALL_THROUGH_TO DrawCachedWindowHeaderAndEntries
.endproc ; ActivateWindow
;;; ============================================================
.proc DrawCachedWindowHeaderAndEntries
lda cached_window_id
jsr UnsafeSetPortFromWindowId ; CHECKED
IF_ZERO
jsr DrawWindowHeader
jsr AdjustWindowPortForEntries
jsr DrawWindowEntries
END_IF
rts
.endproc ; DrawCachedWindowHeaderAndEntries
;;; ============================================================
;;; Redraw the active window's entries. The header is not redrawn.
.proc ClearAndDrawActiveWindowEntries
lda active_window_id
jsr UnsafeSetPortFromWindowIdAndAdjustForEntries ; CHECKED
IF_ZERO
MGTK_CALL MGTK::PaintRect, window_grafport+MGTK::GrafPort::maprect
jsr DrawWindowEntries
END_IF
rts
.endproc ; ClearAndDrawActiveWindowEntries
;;; ============================================================
;;; Used only for file windows; adjusts port to account for header.
;;; Returns 0 if ok, `MGTK::Error::window_obscured` if the window is obscured.
.proc UnsafeSetPortFromWindowIdAndAdjustForEntries
sta getwinport_params::window_id
MGTK_CALL MGTK::GetWinPort, getwinport_params
IF_ZERO ; not MGTK::Error::window_obscured
jsr AdjustWindowPortForEntries
END_IF
rts
.endproc ; UnsafeSetPortFromWindowIdAndAdjustForEntries
;;; Used for all sorts of windows, not just file windows.
;;; For file windows, used for drawing headers (sometimes);
;;; Returns 0 if ok, `MGTK::Error::window_obscured` if the window is obscured.
.proc UnsafeSetPortFromWindowId
sta getwinport_params::window_id
MGTK_CALL MGTK::GetWinPort, getwinport_params
IF_ZERO ; not MGTK::Error::window_obscured
MGTK_CALL MGTK::SetPort, window_grafport
END_IF
rts
.endproc ; UnsafeSetPortFromWindowId
;;; Used for windows that can never be obscured (e.g. dialogs)
PROC_USED_IN_OVERLAY
.proc SafeSetPortFromWindowId
sta getwinport_params::window_id
MGTK_CALL MGTK::GetWinPort, getwinport_params
;; ASSERT: Result is not MGTK::Error::window_obscured
MGTK_CALL MGTK::SetPort, window_grafport
rts
.endproc ; SafeSetPortFromWindowId
;;; ============================================================
;;; Update table tracking disk-in-device status, determine if
;;; there was a change (insertion or ejection).
;;; Output: 0 if no change,
.proc CheckDiskInsertedEjected
lda disk_in_device_table
IF_NOT_ZERO
jsr CheckDisksInDevices
ldx disk_in_device_table
DO
lda disk_in_device_table,x
cmp last_disk_in_devices_table,x
bne changed
dex
WHILE_NOT_ZERO
END_IF
return #0
changed:
copy8 disk_in_device_table,x, last_disk_in_devices_table,x
lda removable_device_table,x
ldy DEVCNT
DO
cmp DEVLST,y
beq found
dey
WHILE_POS
rts
found:
tya
ldy #$80 ; Y = show unexpected errors flag (do)
jmp CheckDriveByIndex ; A = DEVLST index
.endproc ; CheckDiskInsertedEjected
;;; ============================================================
kMaxRemovableDevices = ::kMaxVolumes
removable_device_table:
.byte 0 ; num entries
.res kMaxRemovableDevices, 0
;;; Updated by `CheckDisksInDevices`
disk_in_device_table:
.byte 0 ; num entries
.res kMaxRemovableDevices, 0
;;; Snapshot of previous results; used to detect changes.
last_disk_in_devices_table:
.byte 0 ; num entries
.res kMaxRemovableDevices, 0
;;; ============================================================
;;; Preserves Y
.proc CheckDisksInDevices
status_buffer := $800
tya ; preserve Y
pha
ldx removable_device_table
IF_NOT_ZERO
stx disk_in_device_table
DO
lda removable_device_table,x
jsr check_disk_in_drive
sta disk_in_device_table,x
dex
WHILE_NOT_ZERO
END_IF
pla
tay ; restore Y
rts
;;; Input: A = unit_number
;;; Preserves X
check_disk_in_drive:
tay ; Y = unit_number
txa ; preserve X
pha
tya ; A = unit_number
jsr FindSmartportDispatchAddress
IF_CC ; is SmartPort
stax dispatch
sty status_params::unit_num
;; Execute SmartPort call
dispatch := *+1
jsr SELF_MODIFIED
.byte SPCall::Status
.addr status_params
lda status_buffer
and #$10 ; general status byte, $10 = disk in drive
IF_NOT_ZERO
ldy #$FF ; is SmartPort and disk in drive
bne finish ; always
END_IF
END_IF
ldy #0 ; not SmartPort or no disk in drive
finish: pla
tax ; restore X
tya ; A = result
rts
;; params for call
DEFINE_SP_STATUS_PARAMS status_params, 1, status_buffer, 0
.endproc ; CheckDisksInDevices
;;; ============================================================
.proc UpdateMenuItemStates
;; Flags, or'd together to represent current state
kWindowOpen = %00000001
kHasShortcuts = %00000010
kHasSelection = %00000100
kSingleSel = %00001000
kFileSel = %00010000
kVolSel = %00100000
kLinkSel = %01000000
;; --------------------------------------------------
;; Windows
jsr _UncheckViewMenuItem
lda active_window_id
IF_NOT_ZERO
jsr GetActiveWindowViewBy
and #DeskTopSettings::kViewByIndexMask
tax
inx
stx checkitem_params::menu_item
jsr _CheckViewMenuItem
lda #kWindowOpen ; A = flags (initial value)
ldx #MGTK::disablemenu_enable
ELSE
lda #0 ; A = flags (initial value)
ldx #MGTK::disablemenu_disable
END_IF
pha ; A = flags
stx disablemenu_params::disable
MGTK_CALL MGTK::DisableMenu, disablemenu_params
pla ; A = flags
;; --------------------------------------------------
;; Selector List
ldx num_selector_list_items
IF_NOT_ZERO
ora #kHasShortcuts ; A = flags
END_IF
;; --------------------------------------------------
;; Selected Icons
ldx selected_icon_count
IF_NOT_ZERO
;; Single?
IF_X_EQ #1
ldx selected_icon_list ; X = icon id
cpx trash_icon_num
beq set_flags ; trash only - treat as no selection
ora #kSingleSel ; A = flags
;; Link?
pha ; A = flags
txa ; A = icon id
jsr GetIconEntry
ptr := $06
stax ptr
ldy #IconEntry::type
lda (ptr),y
tax ; X = icon type
pla ; A = flags
IF_X_EQ #IconType::link
ora #kLinkSel ; A = flags
END_IF
END_IF
;; Files or Volumes?
ldx selected_window_id ; In a window?
IF_NOT_ZERO
ora #kHasSelection | kFileSel ; A = flags
ELSE
ora #kHasSelection | kVolSel ; A = flags
END_IF
END_IF
set_flags:
sta flags
;; --------------------------------------------------
;; Update the menus
ldy #0
DO
lda table,y ; menu_id
RTS_IF_ZERO ; sentinel
sta disableitem_params::menu_id
iny
lda table,y ; menu_item
sta disableitem_params::menu_item
iny
ldx #MGTK::disableitem_disable
lda table,y ; flags
flags := *+1
and #SELF_MODIFIED_BYTE
IF_A_EQ table,y
ldx #MGTK::disableitem_enable
END_IF
stx disableitem_params::disable
iny
tya
pha
MGTK_CALL MGTK::DisableItem, disableitem_params
pla
tay
WHILE_NOT_ZERO ; always
;; menu id, item id, required flags
table:
.byte kMenuIdFile, aux::kMenuItemIdNewFolder, kWindowOpen
.byte kMenuIdFile, aux::kMenuItemIdOpen, kHasSelection
.byte kMenuIdFile, aux::kMenuItemIdClose, kWindowOpen
.byte kMenuIdFile, aux::kMenuItemIdCloseAll, kWindowOpen
.byte kMenuIdFile, aux::kMenuItemIdGetInfo, kHasSelection
.byte kMenuIdFile, aux::kMenuItemIdRenameIcon, kSingleSel
.byte kMenuIdFile, aux::kMenuItemIdDuplicate, kSingleSel | kFileSel
.byte kMenuIdFile, aux::kMenuItemIdCopySelection, kHasSelection
.byte kMenuIdFile, aux::kMenuItemIdDeleteFile, kFileSel
.byte kMenuIdEdit, aux::kMenuItemIdCut, kSingleSel
.byte kMenuIdEdit, aux::kMenuItemIdCopy, kSingleSel
.byte kMenuIdEdit, aux::kMenuItemIdPaste, kSingleSel
.byte kMenuIdEdit, aux::kMenuItemIdClear, kSingleSel
.byte kMenuIdSpecial, aux::kMenuItemIdCheckDrive, kVolSel
.byte kMenuIdSpecial, aux::kMenuItemIdEject, kVolSel
.byte kMenuIdSpecial, aux::kMenuItemIdMakeLink, kSingleSel | kFileSel
.byte kMenuIdSpecial, aux::kMenuItemIdShowOriginal, kLinkSel
.byte kMenuIdSelector, kMenuItemIdSelectorEdit, kHasShortcuts
.byte kMenuIdSelector, kMenuItemIdSelectorDelete, kHasShortcuts
.byte kMenuIdSelector, kMenuItemIdSelectorRun, kHasShortcuts
.byte 0 ; sentinel
;;; ------------------------------------------------------------
;;; Inputs: A = MGTK::checkitem_check or MGTK::checkitem_uncheck
;;; Assumes checkitem_params::menu_item has been updated or is last checked.
.proc _CheckViewMenuItemImpl
ENTRY_POINTS_FOR_A check, MGTK::checkitem_check, uncheck, MGTK::checkitem_uncheck
sta checkitem_params::check
MGTK_CALL MGTK::CheckItem, checkitem_params
rts
.endproc ; _CheckViewMenuItemImpl
_CheckViewMenuItem := _CheckViewMenuItemImpl::check
_UncheckViewMenuItem := _CheckViewMenuItemImpl::uncheck
.endproc ; UpdateMenuItemStates
;;; ============================================================
;;; Common re-used param blocks
DEFINE_GET_FILE_INFO_PARAMS file_info_params, SELF_MODIFIED
DEFINE_GET_FILE_INFO_PARAMS src_file_info_params, src_path_buf
DEFINE_GET_FILE_INFO_PARAMS dst_file_info_params, dst_path_buf
.assert src_path_buf = INVOKER_PREFIX, error, "Params re-use"
;;; Call GET_FILE_INFO on path at A,X; results are in `file_info_params`
;;; Output: MLI result (carry/zero flag, etc)
.proc GetFileInfo
stax file_info_params::pathname
MLI_CALL GET_FILE_INFO, file_info_params
rts
.endproc ; GetFileInfo
;;; Call GET_FILE_INFO on file at `src_path_buf` a.k.a. `INVOKER_PREFIX`
;;; Output: MLI result (carry/zero flag, etc), `src_file_info_params` populated
.proc GetSrcFileInfo
MLI_CALL GET_FILE_INFO, src_file_info_params
rts
.endproc ; GetSrcFileInfo
;;; Call SET_FILE_INFO on file at `src_path_buf` a.k.a. `INVOKER_PREFIX`
;;; Input: `src_file_info_params` used
;;; Output: MLI result (carry/zero flag, etc)
.proc SetSrcFileInfo
copy8 #7, src_file_info_params::param_count ; SET_FILE_INFO
MLI_CALL SET_FILE_INFO, src_file_info_params
pha
copy8 #$A, src_file_info_params::param_count ; GET_FILE_INFO
pla
rts
.endproc ; SetSrcFileInfo
;;; Call GET_FILE_INFO on file at `dst_path_buf`
;;; Output: MLI result (carry/zero flag, etc), `dst_file_info_params` populated
.proc GetDstFileInfo
MLI_CALL GET_FILE_INFO, dst_file_info_params
rts
.endproc ; GetDstFileInfo
;;; ============================================================
;;; Additional path buffer used by a handful of locations where
;;; MLI calls require it to be in main memory.
;;; * Prefer `src_path_buf` unless it's already in use
;;; * Prefer `dst_path_buf`, but it's inside `IO_BUFFER`
tmp_path_buf:
.res ::kPathBufferSize, 0
;;; ============================================================
;;; Launch file (File > Open, Selector menu, or double-click)
;;; Inputs: Path in `src_path_buf` (a.k.a. `INVOKER_PREFIX`)
.proc LaunchFileWithPath
clc
bcc :+ ; always
sys_disk:
sec
: ror sys_prompt_flag
jsr SetCursorWatch ; before invoking
;; Easiest to assume absolute path later.
jsr _MakeSrcPathAbsolute ; Trashes `INVOKER_INTERPRETER`
;; Assume no interpreter to start
lda #0
sta INVOKER_INTERPRETER
sta INVOKER_BITSY_COMPAT
;; Get the file info to determine type.
retry: jsr GetSrcFileInfo
IF_CS
sys_prompt_flag := *+1
lda #SELF_MODIFIED_BYTE
jpl ShowAlert
lda #kErrInsertSystemDisk
jsr ShowAlert
cmp #kAlertResultOK
beq retry ; ok, so try again
rts ; cancel, so fail
END_IF
;; Check file type.
ldax #src_path_buf
jsr DetermineIconType ; uses passed name and `src_file_info_params`
;; Handler based on type
asl ; *= 4
asl
tax
copy16 invoke_table,x, handler
lda invoke_table+2,x
pha
lda invoke_table+3,x
tax
pla
handler := *+1
jmp SELF_MODIFIED
;; --------------------------------------------------
;; Fallback - try BASIS.SYSTEM
fallback:
jsr _CheckBasisSystem ; Is fallback BASIS.SYSTEM present?
IF_CC ; yes, continue below
SET_BIT7_FLAG INVOKER_BITSY_COMPAT
bmi launch ; always
END_IF
param_jump ShowAlertParams, AlertButtonOptions::OK, aux::str_alert_cannot_open
;; --------------------------------------------------
;; Launch interpreter (system file that accepts path).
interpreter:
ptr1 := $06
stax ptr1 ; save for later
;; Is the interpreter where we expect it?
jsr GetFileInfo
jcs SetCursorPointer ; nope, just ignore
;; Construct absolute path
ldax ptr1
jsr _MakeRelPathAbsoluteIntoInvokerInterpreter
FALL_THROUGH_TO launch
;; --------------------------------------------------
;; Generic launch
launch:
param_call IconToAnimate, src_path_buf
ldx #$FF ; desktop
jsr AnimateWindowOpen
param_call UpcaseString, INVOKER_PREFIX
param_call UpcaseString, INVOKER_INTERPRETER
jsr SplitInvokerPath
copy16 #INVOKER, reset_and_invoke_target
jmp ResetAndInvoke
;; --------------------------------------------------
;; BASIC program
basic: jsr _CheckBasicSystem ; Only launch if BASIC.SYSTEM is found
jcc launch
lda #kErrBasicSysNotFound
jmp ShowAlert
;; --------------------------------------------------
;; Binary file
binary:
lda menu_click_params::menu_id ; From a menu (File, Selector)
jne launch
jsr ModifierDown ; Otherwise, only launch if a button is down
jmi launch
param_call ShowAlertParams, AlertButtonOptions::OKCancel, aux::str_alert_confirm_running
cmp #kAlertResultOK
jeq launch
jmp SetCursorPointer ; after not launching BIN
;;; --------------------------------------------------
.macro INVOKE_TABLE_ENTRY handler, param
.addr handler
.addr param
.endmacro
invoke_table := * - (4 * IconType::VOL_COUNT)
;; Volume types skipped via above math; GET_FILE_INFO yields
;; `FT_DIRECTORY` which maps to a folder
INVOKE_TABLE_ENTRY fallback, 0 ; generic
INVOKE_TABLE_ENTRY _InvokePreview, str_preview_txt ; text
INVOKE_TABLE_ENTRY binary, 0 ; binary
INVOKE_TABLE_ENTRY _InvokePreview, str_preview_fot ; graphics
INVOKE_TABLE_ENTRY fallback, 0 ; animation
INVOKE_TABLE_ENTRY _InvokePreview, str_preview_mus ; music
INVOKE_TABLE_ENTRY interpreter, str_preview_pt3 ; tracker
INVOKE_TABLE_ENTRY fallback, 0 ; audio
INVOKE_TABLE_ENTRY interpreter, str_tts ; speech
INVOKE_TABLE_ENTRY _InvokePreview, str_preview_fnt ; font
INVOKE_TABLE_ENTRY fallback, 0 ; relocatable
INVOKE_TABLE_ENTRY fallback, 0 ; command
INVOKE_TABLE_ENTRY _OpenFolder, 0 ; folder
INVOKE_TABLE_ENTRY _OpenFolder, 0 ; system_folder
INVOKE_TABLE_ENTRY fallback, 0 ; iigs
INVOKE_TABLE_ENTRY interpreter, str_awlauncher ; appleworks_wp
INVOKE_TABLE_ENTRY interpreter, str_awlauncher ; appleworks_sp
INVOKE_TABLE_ENTRY interpreter, str_awlauncher ; appleworks_db
INVOKE_TABLE_ENTRY interpreter, str_unshrink ; archive
INVOKE_TABLE_ENTRY interpreter, str_binscii ; encoded
INVOKE_TABLE_ENTRY _InvokeLink, 0 ; link
INVOKE_TABLE_ENTRY InvokeDeskAccByPath, 0 ; desk_accessory
INVOKE_TABLE_ENTRY basic, 0 ; basic
INVOKE_TABLE_ENTRY interpreter, str_intbasic ; intbasic
INVOKE_TABLE_ENTRY fallback, 0 ; variables
INVOKE_TABLE_ENTRY launch, 0 ; system
INVOKE_TABLE_ENTRY launch, 0 ; application
;; Small Icon types skipped via math below
ASSERT_RECORD_TABLE_SIZE invoke_table, IconType::COUNT - IconType::SMALL_COUNT, 4
;;; --------------------------------------------------
;;; Check `src_path_buf`'s ancestors to see if the desired interpreter
;;; (BASIC.SYSTEM or BASIS.SYSTEM) is present.
;;; Input: `src_path_buf` set to target path
;;; Output: C=0 if found, C=1 if not found
.proc _CheckBasixSystemImpl
launch_path := INVOKER_PREFIX
interp_path := INVOKER_INTERPRETER
;; "BASI?" -> "BASIC", "BASI?" -> "BASIS"
ENTRY_POINTS_FOR_A basic, 'C', basis, 'S'
sta str_basix_system + kBSOffset
;; Start off with `interp_path` = `launch_path`
COPY_STRING launch_path, interp_path
;; Pop off a path segment.
DO
param_call RemovePathSegment, interp_path
BREAK_IF_A_LT #2
inc interp_path ; restore trailing '/'
;; Append BASI?.SYSTEM to path and check for file.
param_call _AppendToInvokerInterpreter, str_basix_system
param_call GetFileInfo, interp_path
bcc ret
param_call RemovePathSegment, interp_path
WHILE_NOT_ZERO ; always
copy8 #0, interp_path ; null out the path
sec
ret: rts
.endproc ; _CheckBasixSystemImpl
_CheckBasisSystem := _CheckBasixSystemImpl::basis
.proc _CheckBasicSystem
ldax #str_extras_basic
jsr _MakeRelPathAbsoluteIntoInvokerInterpreter
param_call GetFileInfo, INVOKER_INTERPRETER
jcs _CheckBasixSystemImpl::basic ; nope, look relative to launch path
rts
.endproc ; _CheckBasicSystem
;;; --------------------------------------------------
;;; Input: A,X = relative path to append
;;; Output: `INVOKER_INTERPRETER` has absolute path
.proc _MakeRelPathAbsoluteIntoInvokerInterpreter
pha
txa
pha
MLI_CALL GET_PREFIX, get_prefix_params
pla
tax
pla
FALL_THROUGH_TO _AppendToInvokerInterpreter
.endproc ; _MakeRelPathAbsoluteIntoInvokerInterpreter
;;; --------------------------------------------------
;;; Input: A,X = relative path to append
;;; Output: `INVOKER_INTERPRETER` updated
.proc _AppendToInvokerInterpreter
jsr PushPointers
ptr1 := $06
len := $08
stax ptr1
ldy #0
ldx INVOKER_INTERPRETER
copy8 (ptr1),y, len
DO
iny
inx
copy8 (ptr1),y, INVOKER_INTERPRETER,x
WHILE_Y_NE len
stx INVOKER_INTERPRETER
jsr PopPointers ; do not tail-call optimize!
rts
.endproc ; _AppendToInvokerInterpreter
;;; --------------------------------------------------
.proc _OpenFolder
tsx
stx saved_stack
jsr OpenWindowForPath
jmp SetCursorPointer ; after opening folder
.endproc ; _OpenFolder
;;; --------------------------------------------------
;;; Invoke a Preview DA
;;; Inputs: A,X = relative path to DA; `src_path_buf` is file to preview
.proc _InvokePreview
pha
txa
pha
param_call IconToAnimate, src_path_buf
tay
pla
tax
pla
jmp InvokeDeskAccWithIcon
.endproc ; _InvokePreview
;;; --------------------------------------------------
.proc _InvokeLink
jsr ReadLinkFile
RTS_IF_CS
jmp LaunchFileWithPath
.endproc ; _InvokeLink
;;; --------------------------------------------------
;;; Trashes: `INVOKER_INTERPRETER`
.proc _MakeSrcPathAbsolute
;; Already absolute?
lda src_path_buf+1
IF_A_NE #'/'
;; Get prefix and append path
ldax #src_path_buf
jsr _MakeRelPathAbsoluteIntoInvokerInterpreter
;; Copy back to original buffer
param_call CopyToSrcPath, INVOKER_INTERPRETER
END_IF
rts
.endproc ; _MakeSrcPathAbsolute
;;; --------------------------------------------------
DEFINE_GET_PREFIX_PARAMS get_prefix_params, INVOKER_INTERPRETER
.endproc ; LaunchFileWithPath
LaunchFileWithPathOnSystemDisk := LaunchFileWithPath::sys_disk
;;; ============================================================
;;; Inputs: `src_path_buf` has path to LNK file
;;; Output: C=0, `src_path_buf` has target on success
;;; C=1 and alert is shown on error
.proc ReadLinkFile
read_buf := $800
MLI_CALL OPEN, open_params
bcs err
lda open_params::ref_num
sta read_params::ref_num
sta close_params::ref_num
MLI_CALL READ, read_params
php
MLI_CALL CLOSE, close_params
plp
bcs err
lda read_params::trans_count
IF_A_GE #kLinkFilePathLengthOffset
ldx #kCheckHeaderLength-1
DO
lda read_buf,x
cmp check_header,x
bne bad
dex
WHILE_POS
param_call CopyToSrcPath, read_buf + kLinkFilePathLengthOffset
clc
rts
END_IF
bad: lda #kErrUnknown
err: jsr ShowAlert
sec
rts
check_header:
.byte kLinkFileSig1Value, kLinkFileSig2Value, kLinkFileCurrentVersion
kCheckHeaderLength = * - check_header
DEFINE_OPEN_PARAMS open_params, src_path_buf, $1C00
DEFINE_READWRITE_PARAMS read_params, read_buf, kLinkFileMaxSize
DEFINE_CLOSE_PARAMS close_params
.endproc ; ReadLinkFile
;;; ============================================================
;;; Uppercase a string
;;; Input: A,X = Address
;;; Trashes $06
PROC_USED_IN_OVERLAY
.proc UpcaseString
ptr := $06
stax ptr
ldy #$00
lda (ptr),y
IF_NOT_ZERO
tay
DO
lda (ptr),y
jsr ToUpperCase
sta (ptr),y
dey
WHILE_NOT_ZERO
END_IF
rts
.endproc ; UpcaseString
;;; ============================================================
;;; Inputs: Character in A
;;; Outputs: Z=1 if alpha, 0 otherwise
;;; A is trashed
.proc IsAlpha
jsr ToUpperCase
cmp #'A'
bcc nope
cmp #'Z'+1
bcs nope
lda #0
rts
nope: lda #$FF
rts
.endproc ; IsAlpha
;;; ============================================================
kBSOffset = 5 ; Offset of 'x' in BASIx.SYSTEM
str_basix_system:
PASCAL_STRING "BASIx.SYSTEM"
str_extras_basic:
PASCAL_STRING .concat(kFilenameExtrasDir, "/BASIC.system")
str_intbasic:
PASCAL_STRING .concat(kFilenameExtrasDir, "/IntBASIC.system")
str_about_this_apple:
PASCAL_STRING .concat(kFilenameModulesDir, "/this.apple")
str_tts:
PASCAL_STRING .concat(kFilenameExtrasDir, "/TTS.system")
str_awlauncher:
PASCAL_STRING .concat(kFilenameExtrasDir, "/AWLaunch.system")
str_unshrink:
PASCAL_STRING .concat(kFilenameExtrasDir, "/UnShrink")
str_binscii:
PASCAL_STRING .concat(kFilenameExtrasDir, "/BinSCII")
str_preview_fot:
PASCAL_STRING .concat(kFilenameModulesDir, "/show.image.file")
str_preview_fnt:
PASCAL_STRING .concat(kFilenameModulesDir, "/show.font.file")
str_preview_txt:
PASCAL_STRING .concat(kFilenameModulesDir, "/show.text.file")
str_preview_mus:
PASCAL_STRING .concat(kFilenameModulesDir, "/show.duet.file")
str_preview_pt3:
PASCAL_STRING .concat(kFilenameExtrasDir, "/PT3PLR.system")
;;; ============================================================
str_empty:
PASCAL_STRING ""
;;; ============================================================
;;; Aux $D000-$DFFF b2 holds FileRecord entries. These are stored
;;; with a one byte length prefix, then sequential FileRecords.
;;; Not counting the prefix, this gives room for 128 entries.
;;; Only 127 icons are supported and volumes don't get entries,
;;; so this is enough.
;;; `window_id_to_filerecord_list_*` maps win id to list num
;;; `window_filerecord_table` maps from list num to address
file_records_buffer := $D000
kFileRecordsBufferLen = $1000
.assert kFileRecordsBufferLen > .sizeof(FileRecord) * kMaxIconCount, error, "Size mismatch"
;;; This tracks the start of free space.
filerecords_free_start:
.word file_records_buffer
;;; ============================================================
.proc RestoreDeviceList
ldx devlst_backup
inx ; include the count itself
DO
copy8 devlst_backup,x, DEVLST-1,x ; DEVCNT is at DEVLST-1
dex
WHILE_POS
rts
.endproc ; RestoreDeviceList
;;; Backup copy of DEVLST made before reordering and detaching offline devices
devlst_backup:
.res ::kMaxDevListSize+1, 0 ; +1 for DEVCNT itself
;;; ============================================================
.proc CmdSelectorAction
;; If adding, try to default to the current selection.
lda menu_click_params::item_num
IF_A_EQ #kMenuItemIdSelectorAdd
copy8 #0, path_buf0
;; If there's a selection, put it in `path_buf0`
lda selected_icon_count
IF_NOT_ZERO
lda selected_icon_list
jsr GetIconPath ; `path_buf3` set to path; A=0 on success
jne ShowAlert ; too long
param_call CopyToBuf0, path_buf3
END_IF
END_IF
lda #kDynamicRoutineShortcutPick
jsr LoadDynamicRoutine
bmi done
lda menu_click_params::item_num
IF_A_LT #SelectorAction::delete
;; Add or Edit - need more overlays
lda #kDynamicRoutineShortcutEdit
jsr LoadDynamicRoutine
bmi done
lda #kDynamicRoutineFileDialog ; file dialog
jsr LoadDynamicRoutine
bmi done
END_IF
;; Invoke routine
lda menu_click_params::item_num
jsr SelectorPickOverlay::Exec
sta result
;; Restore from overlays
;; (restore from file dialog overlay handled in picker overlay)
lda #kDynamicRoutineRestoreSP ; restore from picker dialog
jsr RestoreDynamicRoutine
bit result
bmi done ; N=1 for Cancel
lda menu_click_params::item_num
IF_A_EQ #SelectorAction::run
;; "Run" command
result := *+1
lda #SELF_MODIFIED_BYTE
bpl InvokeSelectorEntry ; always
END_IF
done: rts
.endproc ; CmdSelectorAction
;;; ============================================================
.proc CmdSelectorItem
lda menu_click_params::item_num
sec
sbc #kSelectorMenuFixedItems + 1 ; make 0 based
FALL_THROUGH_TO InvokeSelectorEntry
.endproc ; CmdSelectorItem
;;; ============================================================
;;; A = `entry_num`
.proc InvokeSelectorEntry
ptr := $06
entry_path := tmp_path_buf
sta entry_num
;; Stash path, which may be from the picker (if not in the
;; primary list) and may be trashed (if the entry is copied
;; to RAMCard later.
jsr _SetEntryPathPtr
param_call CopyPtr1ToBuf, entry_path
;; Is there a RAMCard at all?
jsr GetCopiedToRAMCardFlag
beq use_entry_path ; no RAMCard, skip
;; Look at the entry's flags
lda entry_num
jsr _SetEntryPtr
ldy #kSelectorEntryFlagsOffset ; flag byte following name
lda (ptr),y
ASSERT_EQUALS ::kSelectorEntryCopyOnBoot, 0
beq on_boot
cmp #kSelectorEntryCopyNever
beq use_entry_path ; not copied
;; --------------------------------------------------
;; `kSelectorEntryCopyOnUse`
ldx entry_num
jsr GetEntryCopiedToRAMCardFlag
bmi use_ramcard_path ; already copied!
;; Need to copy to RAMCard
jsr _PrepEntryCopyPaths
jsr DoCopyToRAM
RTS_IF_A_EQ #kOperationCanceled
IF_A_EQ #kOperationFailed
param_call CopyRAMCardPrefix, path_buf4
jmp RefreshWindowForPathBuf4
END_IF
;; Success!
ldx entry_num
lda #$FF
jsr SetEntryCopiedToRAMCardFlag
jmp use_ramcard_path
;; --------------------------------------------------
;; `kSelectorEntryCopyOnBoot`
on_boot:
ldx entry_num
jsr GetEntryCopiedToRAMCardFlag
bpl use_entry_path ; wasn't copied!
FALL_THROUGH_TO use_ramcard_path
;; --------------------------------------------------
;; Copied to RAMCard - use copied path
use_ramcard_path:
jsr _ComposeRAMCardEntryPath
stax ptr
jmp launch
;; --------------------------------------------------
;; Not copied to RAMCard - just use entry's path
use_entry_path:
copy16 #entry_path, ptr
FALL_THROUGH_TO launch
launch: param_call CopyPtr1ToBuf, INVOKER_PREFIX
jmp LaunchFileWithPath
entry_num:
.byte 0
;;; --------------------------------------------------
;;; Input: `entry_path` is populated
;;; Output: paths prepared for `DoCopyToRAM`
.proc _PrepEntryCopyPaths
entry_original_path := $800
entry_ramcard_path := $840
COPY_STRING entry_path, entry_original_path
;; Copy "down loaded" path to `entry_ramcard_path`
jsr _ComposeRAMCardEntryPath
stax ptr
param_call CopyPtr1ToBuf, entry_ramcard_path
;; Strip segment off path at `entry_original_path`
;; e.g. "/VOL/MOUSEPAINT/MP.SYSTEM" -> "/VOL/MOUSEPAINT"
param_call RemovePathSegment, entry_original_path
;; Strip segment off path at `entry_ramcard_path`
;; e.g. "/RAM/MOUSEPAINT/MP.SYSTEM" -> "/RAM/MOUSEPAINT"
param_call RemovePathSegment, entry_ramcard_path
;; Further prepare paths for copy
copy16 #entry_original_path, $06
copy16 #entry_ramcard_path, $08
jmp CopyPathsFromPtrsToBufsAndSplitName
.endproc ; _PrepEntryCopyPaths
;;; --------------------------------------------------
;;; Compose path using RAM card prefix plus last two segments of path
;;; (e.g. "/RAM" + "/MOUSEPAINT/MP.SYSTEM") into `src_path_buf`
;;; Input: `entry_path` is populated
;;; Output: A,X = `src_path_buf`
.proc _ComposeRAMCardEntryPath
;; Initialize buffer
param_call CopyRAMCardPrefix, src_path_buf
ldy entry_path
;; Walk back one segment
DO
lda entry_path,y
BREAK_IF_A_EQ #'/'
dey
WHILE_NOT_ZERO
dey
;; Walk back a second segment
DO
lda entry_path,y
BREAK_IF_A_EQ #'/'
dey
WHILE_NOT_ZERO
dey
;; Append last two segments to `src_path_buf`
ldx src_path_buf
DO
inx
iny
copy8 entry_path,y, src_path_buf,x
WHILE_Y_NE entry_path
stx src_path_buf
ldax #src_path_buf
rts
.endproc ; _ComposeRAMCardEntryPath
;;; --------------------------------------------------
;;; Input: A = entry num
;;; Output: $06 points at entry
;;; NOTE: If in the "primary" list, points at the permanently loaded
;;; copy. Otherwise, assumes the picker just ran and points at the
;;; temporarily loaded copy.
.proc _SetEntryPtr
ptr := $06
IF_A_LT #kSelectorListNumPrimaryRunListEntries
jsr ATimes16
addax #run_list_entries, ptr
rts
END_IF
jsr ATimes16
addax #SELECTOR_FILE_BUF + kSelectorListEntriesOffset, ptr
rts
.endproc ; _SetEntryPtr
;;; --------------------------------------------------
;;; Input: A = entry num
;;; Output: $06 points at entry path
;;; NOTE: If in the "primary" list, points at the permanently loaded
;;; copy. Otherwise, assumes the picker just ran and points at the
;;; temporarily loaded copy.
.proc _SetEntryPathPtr
ptr := $06
IF_A_LT #kSelectorListNumPrimaryRunListEntries
jsr ATimes64
addax #run_list_paths, ptr
rts
END_IF
jsr ATimes64
addax #SELECTOR_FILE_BUF + kSelectorListPathsOffset, ptr
rts
.endproc ; _SetEntryPathPtr
.endproc ; InvokeSelectorEntry
;;; ============================================================
;;; Copy the string at $06 to target at A,X
;;; Inputs: Source string at $06, target buffer at A,X
;;; Output: String length in A
PROC_USED_IN_OVERLAY
.proc CopyPtr1ToBuf
ptr1 := $06
stax addr
ldy #0
lda (ptr1),y
tay
DO
lda (ptr1),y
addr := *+1
sta SELF_MODIFIED,y
dey
WHILE_POS
rts
.endproc ; CopyPtr1ToBuf
;;; Copy the string at $08 to target at A,X
;;; Inputs: Source string at $08, target buffer at A,X
;;; Output: String length in A
.proc CopyPtr2ToBuf
ptr2 := $08
stax addr
ldy #0
lda (ptr2),y
tay
DO
lda (ptr2),y
addr := *+1
sta SELF_MODIFIED,y
dey
WHILE_POS
rts
.endproc ; CopyPtr2ToBuf
;;; ============================================================
CmdAbout := AboutDialogProc
;;; ============================================================
.proc CmdAboutThisApple
param_jump InvokeDeskAccWithIcon, $FF, str_about_this_apple
.endproc ; CmdAboutThisApple
;;; ============================================================
.proc CmdDeskAccImpl
ptr := $6
len := $8
path := INVOKER_PREFIX
str_desk_acc:
PASCAL_STRING .concat(kFilenameDADir, "/")
start: jsr SetCursorWatch ; before loading DA
;; Append DA directory name
param_call CopyToSrcPath, str_desk_acc
;; Find DA name
lda menu_click_params::item_num ; menu item index (1-based)
sec
sbc #kAppleMenuFixedItems+1
tay
ldax #kDAMenuItemSize
jsr Multiply_16_8_16
addax #desk_acc_names, ptr
;; Append name to path
ldx path
ldy #0
copy8 ($06),y, len
DO
inx
skip: iny
lda ($06),y
cmp #' ' ; Convert spaces back to periods
bcc skip ; Ignore control characters (i.e. folder glyphs)
IF_EQ
lda #'.'
END_IF
sta path,x
WHILE_Y_NE len
stx path
;; Allow arbitrary types in menu (e.g. folders)
jmp LaunchFileWithPathOnSystemDisk
.endproc ; CmdDeskAccImpl
CmdDeskAcc := CmdDeskAccImpl::start
;;; ============================================================
;;; Invoke a DA, with path set to first file selection
;;; Input: `src_path_buf` has DA absolute path
.proc InvokeDeskAccByPath
;; * Can't use `dst_path_buf` as it is within DA_IO_BUFFER
;; * Can't use `src_path_buf` as it holds file selection
COPY_STRING src_path_buf, tmp_path_buf ; Use this to launch the DA
copy8 #0, src_path_buf ; Signal no file selection
;; As a convenience for DAs, pass path to first selected icon.
lda selected_icon_count
IF_NOT_ZERO
lda selected_icon_list ; first selected icon
IF_A_NE trash_icon_num ; ignore trash
jsr GetIconPath ; `path_buf3` set to path; A=0 on success
jne ShowAlert ; too long
param_call CopyToSrcPath, path_buf3
END_IF
END_IF
param_call IconToAnimate, tmp_path_buf
tay
ldax #tmp_path_buf
FALL_THROUGH_TO InvokeDeskAccWithIcon
.endproc ; InvokeDeskAccByPath
;;; ============================================================
;;; Invoke Desk Accessory
;;; Input: A,X = DA pathname (relative is OK)
;;; Y = icon id to animate ($FF for none)
.proc InvokeDeskAccWithIcon
stax open_params::pathname
tya
sta icon ; can't use stack, as DAs can modify
IF_NC
ldx #$FF ; desktop
jsr AnimateWindowOpen
END_IF
;; Load the DA
retry: MLI_CALL OPEN, open_params
IF_CS
lda #kErrInsertSystemDisk
jsr ShowAlert
cmp #kAlertResultOK
beq retry ; ok, so try again
rts ; cancel, so fail
END_IF
lda open_params::ref_num
sta read_header_params::ref_num
sta read_params::ref_num
sta close_params::ref_num
MLI_CALL READ, read_header_params
lda DAHeader::aux_length
ora DAHeader::aux_length+1
beq main
;; Aux memory segment
copy16 DAHeader::aux_length, read_params::request_count
MLI_CALL READ, read_params
copy16 #DA_LOAD_ADDRESS, STARTLO
copy16 #DA_LOAD_ADDRESS, DESTINATIONLO
add16 #DA_LOAD_ADDRESS-1, DAHeader::aux_length, ENDLO
sec ; main>aux
jsr AUXMOVE
;; Main memory segment
main: copy16 DAHeader::main_length, read_params::request_count
MLI_CALL READ, read_params
MLI_CALL CLOSE, close_params
;; Invoke it
jsr SetCursorPointer ; before invoking DA
jsr DA_LOAD_ADDRESS
;; Restore state
jsr InitSetDesktopPort ; DA's port destroyed, set something real as current
jsr ShowClockForceUpdate
jsr ClearUpdates
icon := *+1
lda #SELF_MODIFIED_BYTE
IF_NC
ldx #$FF ; desktop
jsr AnimateWindowClose
END_IF
jmp SetCursorPointer ; after invoking DA
.params DAHeader
aux_length: .word 0
main_length: .word 0
.endparams
DEFINE_OPEN_PARAMS open_params, 0, DA_IO_BUFFER
DEFINE_READWRITE_PARAMS read_header_params, DAHeader, .sizeof(DAHeader)
DEFINE_READWRITE_PARAMS read_params, DA_LOAD_ADDRESS, kDAMaxSize
DEFINE_CLOSE_PARAMS close_params
.endproc ; InvokeDeskAccWithIcon
;;; ============================================================
;;; Inputs: A,X = absolute path
;;; Outputs: A = icon to animate (path or volume)
.proc IconToAnimate
jsr PushPointers
ptr := $06
stax ptr
;; Is the file represented by an icon?
jsr FindIconForPath
IF_ZERO
;; No, just use volume path
;; Save length
ldy #0
lda (ptr),y
pha
param_call_indirect MakeVolumePath, ptr
param_call_indirect FindIconForPath, ptr
tax
;; Restore length
pla
ldy #0
sta (ptr),y
txa
END_IF
jsr PopPointers ; do not tail-call optimize!
rts
.endproc ; IconToAnimate
;;; ============================================================
;;; Reduce an absolute path to just the volume path. If already a
;;; volume path, the length is not changed.
;;; e.g. "/VOL/DIR/FILE" to "/VOL"
;;; Inputs: A,X = vol
;;; Note: length is modified, but buffer otherwise unchanged
.proc MakeVolumePath
jsr PushPointers
ptr := $06
pathlen := $08
stax ptr
ldy #0
copy8 (ptr),y, pathlen
iny ; start at 2nd character
DO
iny
cpy pathlen
beq :+
lda (ptr),y
WHILE_A_NE #'/'
dey
:
tya
ldy #0
sta (ptr),y
jsr PopPointers ; do not tail-call optimize!
rts
.endproc ; MakeVolumePath
;;; ============================================================
.proc CmdCopySelection
lda #kDynamicRoutineFileDialog
jsr LoadDynamicRoutine
RTS_IF_NS
lda #kDynamicRoutineFileCopy
jsr LoadDynamicRoutine
RTS_IF_NS
jsr ::FileCopyOverlay::Run
pha ; A = dialog result
lda #kDynamicRoutineRestoreFD
jsr RestoreDynamicRoutine
jsr PushPointers ; $06 = dst
jsr ClearUpdates ; following picker dialog close
jsr PopPointers ; $06 = dst
pla ; A = dialog result
RTS_IF_NS
;; --------------------------------------------------
;; Try the copy
param_call CopyPtr1ToBuf, path_buf4
jsr DoCopySelection
RTS_IF_A_EQ #kOperationCanceled
FALL_THROUGH_TO RefreshWindowForPathBuf4
.endproc ; CmdCopySelection
;;; ============================================================
.proc RefreshWindowForPathBuf4
;; See if there's a window we should activate later.
param_call FindWindowForPath, path_buf4
pha ; save for later
;; Update cached used/free for all same-volume windows
param_call UpdateUsedFreeViaPath, path_buf4
;; Select/refresh window if there was one
pla
jne ActivateAndRefreshWindowOrClose
rts
.endproc ; RefreshWindowForPathBuf4
;;; ============================================================
;;; Copy string at ($6) to `path_buf3`, string at ($8) to `path_buf4`,
;;; split filename off `path_buf4` and store in `filename_buf`
.proc CopyPathsFromPtrsToBufsAndSplitName
;; Copy string at $6 to `path_buf3`
param_call CopyPtr1ToBuf, path_buf3
;; Copy string at $8 to `path_buf4`
param_call CopyPtr2ToBuf, path_buf4
FALL_THROUGH_TO SplitPathBuf4
.endproc ; CopyPathsFromPtrsToBufsAndSplitName
;;; Split filename off `path_buf4` and store in `filename_buf`
;;; If a volume name, splits off leading "/" (e.g. "/VOL" to "/" and "VOL")
.proc SplitPathBuf4
param_call FindLastPathSegment, path_buf4
IF_Y_NE path_buf4
tya ; Y = position of last '/'
pha
;; Shorter, so file - Copy filename part to buf
ldx #1
iny ; +1 for length byte
iny ; +1 to skip past '/'
DO
copy8 path_buf4,y, filename_buf,x
BREAK_IF_Y_EQ path_buf4
iny
inx
WHILE_NOT_ZERO
stx filename_buf
;; And remove from `path_buf4`
pla
tay ; Y = position of last '/'
sty path_buf4
rts
END_IF
;; Unchanged, so volume - Copy, removing leading slash
dey
sty filename_buf
DO
copy8 path_buf4+1,y, filename_buf,y
dey
WHILE_NOT_ZERO
copy8 #1, path_buf4
rts
.endproc ; SplitPathBuf4
;;; ============================================================
;;; Split filename off `INVOKER_PREFIX` into `INVOKER_FILENAME`
;;; Assert: `INVOKER_PREFIX` is a file path not volume path
.proc SplitInvokerPath
param_call FindLastPathSegment, INVOKER_PREFIX ; point Y at last '/'
tya
pha
ldx #1
iny ; +1 for length byte
iny ; +1 to skip past '/'
DO
copy8 INVOKER_PREFIX,y, INVOKER_FILENAME,x
BREAK_IF_Y_EQ INVOKER_PREFIX
iny
inx
WHILE_NOT_ZERO ; always
stx INVOKER_FILENAME
pla
sta INVOKER_PREFIX
rts
.endproc ; SplitInvokerPath
;;; ============================================================
.proc CmdOpen
ptr := $06
selected_icon_count_copy := $1F80
selected_icon_list_copy := $1F81
.assert selected_icon_list_copy + kMaxIconCount <= $2000, error, "overlap"
;; --------------------------------------------------
;; Entry point from menu
;; Close after open only if from real menu, and modifier is down.
lda #0
bit menu_modified_click_flag
IF_NS
lda selected_window_id
END_IF
sta window_id_to_close
jmp common
;; --------------------------------------------------
;; Entry point from OA+SA+O / OA+SA+Down
open_then_close_current:
lda selected_icon_count
RTS_IF_ZERO
copy8 selected_window_id, window_id_to_close
jmp common
;; --------------------------------------------------
;; Entry point from Apple+Down
;; Never close after open only.
from_keyboard:
lda selected_icon_count
RTS_IF_ZERO
copy8 #0, window_id_to_close
jmp common
;; --------------------------------------------------
;; Entry point from double-click
;; Close after open if modifier is down.
from_double_click:
copy8 #0, window_id_to_close
jsr ModifierDown
IF_NS
copy8 selected_window_id, window_id_to_close
END_IF
FALL_THROUGH_TO common
;; --------------------------------------------------
common:
CLEAR_BIT7_FLAG dir_flag
;; Make a copy of selection
ldx selected_icon_count
stx selected_icon_count_copy
DO
copy8 selected_icon_list-1,x, selected_icon_list_copy-1,x
dex
WHILE_NOT_ZERO
;; Iterate selected icons
ldx #0
DO
cpx selected_icon_count_copy
bne next
;; Finish up...
;; Were any directories opened?
dir_flag := *+1
lda #SELF_MODIFIED_BYTE ; bit7
IF_NS
;; Maybe close the previously active window, depending on source/modifiers
jsr MaybeCloseWindowAfterOpen
END_IF
rts
next: txa
pha ; A = index
lda selected_icon_list_copy,x
;; Trash?
cmp trash_icon_num
beq next_icon
pha ; A = icon id
;; Look at flags...
jsr GetIconEntry
stax ptr
ldy #IconEntry::win_flags
lda (ptr),y
and #kIconEntryFlagsDropTarget ; folder or volume?
beq maybe_open_file ; nope
;; Directory
SET_BIT7_FLAG dir_flag
pla ; A = icon id
jsr OpenWindowForIcon
next_icon:
pla ; A = index
tax
inx
WHILE_NOT_ZERO ; always
;; File (executable or data)
maybe_open_file:
pla ; A = icon id
tax ; X = icon id
lda selected_icon_count_copy
cmp #2 ; multiple files open?
bcs next_icon ; don't try to invoke
pla ; A = index; no longer needed
txa ; A = icon id
jsr GetIconPath ; `path_buf3` set to path; A=0 on success
jne ShowAlert ; too long
param_call CopyToSrcPath, path_buf3
jmp LaunchFileWithPath
.endproc ; CmdOpen
CmdOpenThenCloseCurrent := CmdOpen::open_then_close_current
CmdOpenFromDoubleClick := CmdOpen::from_double_click
CmdOpenFromKeyboard := CmdOpen::from_keyboard
;;; ============================================================
;;; Close parent window after open, if needed. Done by activating then closing.
;;; Input: `window_id_to_close` set by caller.
;;; Modifies `findwindow_params::window_id`
.proc MaybeCloseWindowAfterOpen
lda window_id_to_close
IF_NOT_ZERO
jsr CloseSpecifiedWindow
END_IF
rts
.endproc ; MaybeCloseWindowAfterOpen
;;; Parent window to close
window_id_to_close:
.byte 0
;;; ============================================================
.proc CmdOpenParentImpl
close_current:
lda active_window_id
SKIP_NEXT_2_BYTE_INSTRUCTION
normal: lda #0
sta window_id_to_close
lda active_window_id
beq done
jsr GetWindowPath
jsr CopyToSrcPath
;; Try removing last segment
param_call FindLastPathSegment, src_path_buf ; point Y at last '/'
cpy src_path_buf
beq volume
;; --------------------------------------------------
;; Windowed
;; Calc the name
.assert src_path_buf = INVOKER_PREFIX, error, "mismatch"
jsr SplitInvokerPath
;; Try to open by path.
tsx
stx saved_stack
jsr OpenWindowForPath
jsr MaybeCloseWindowAfterOpen
;; Select by name (if not already done via close)
lda selected_icon_count
IF_ZERO
param_call SelectFileIconByName, INVOKER_FILENAME
END_IF
done: rts
;; --------------------------------------------------
;; Find volume icon by name and select it.
volume:
jsr MaybeCloseWindowAfterOpen
param_call FindIconForPath, src_path_buf
IF_NOT_ZERO
jsr SelectIconAndEnsureVisible
END_IF
rts
.endproc ; CmdOpenParentImpl
CmdOpenParent := CmdOpenParentImpl::normal
CmdOpenParentThenCloseCurrent := CmdOpenParentImpl::close_current
;;; ============================================================
;;; Assert: Window open
.proc CmdClose
bit menu_modified_click_flag
bmi CmdCloseAll
jmp CloseActiveWindow
.endproc ; CmdClose
;;; ============================================================
.proc CmdCloseAll
repeat:
lda active_window_id ; current window
RTS_IF_ZERO ; nope, done!
jsr CloseActiveWindow ; close it...
jmp repeat ; and try again
.endproc ; CmdCloseAll
;;; ============================================================
.proc CmdDiskCopyImpl
DEFINE_OPEN_PARAMS open_params, str_disk_copy, IO_BUFFER
DEFINE_READWRITE_PARAMS read_params, DISK_COPY_BOOTSTRAP, kDiskCopyBootstrapLength
DEFINE_CLOSE_PARAMS close_params
str_disk_copy:
PASCAL_STRING kPathnameDiskCopy
start:
retry:
;; Do this now since we'll use up the space later.
jsr SaveWindows
;; Smuggle through the selected unit, if any.
jsr GetSelectedUnitNum
sta DISK_COPY_INITIAL_UNIT_NUM
MLI_CALL OPEN, open_params
IF_CS
lda #kErrInsertSystemDisk
jsr ShowAlert
cmp #kAlertResultOK
beq retry ; ok, so try again
rts ; cancel, so fail
END_IF
lda open_params::ref_num
sta read_params::ref_num
sta close_params::ref_num
MLI_CALL READ, read_params
MLI_CALL CLOSE, close_params
;; Successful - start to clean up
ITK_CALL IconTK::FreeAll, 0 ; volume icons
MGTK_CALL MGTK::CloseAll
MGTK_CALL MGTK::SetZP1, setzp_params_preserve
;; Did we detach S3D2 /RAM?
;; NOTE: ReconnectRAM is not used here because (1) it will be
;; disconnected immediately by Disk Copy anyway and (2) we
;; don't want to trash MGTK in aux memory. We restore just
;; enough for Disk Copy to disconnect/reconnect properly.
lda saved_ram_unitnum
IF_NE
inc DEVCNT
ldx DEVCNT
sta DEVLST,x
copy16 saved_ram_drvec, RAMSLOT
END_IF
;; Restore modified ProDOS state
jsr RestoreDeviceList
;; Set up banks for ProDOS usage
sta ALTZPOFF
bit ROMIN2
jmp DISK_COPY_BOOTSTRAP
.endproc ; CmdDiskCopyImpl
CmdDiskCopy := CmdDiskCopyImpl::start
;;; ============================================================
;;; Assert: There is an active window
.proc CmdNewFolderImpl
;; access = destroy/rename/write/read
DEFINE_CREATE_PARAMS create_params, src_path_buf, ACCESS_DEFAULT, FT_DIRECTORY,, ST_LINKED_DIRECTORY
start:
;; Create with current date
MLI_CALL GET_TIME
COPY_STRUCT DateTime, DATELO, create_params::create_date
;; --------------------------------------------------
;; Determine the name to use
;; Start with generic folder name
COPY_STRING str_new_folder, stashed_name
;; Repeat to find a free name
retry: lda active_window_id
jsr GetWindowPath
jsr CopyToSrcPath
param_call AppendFilenameToSrcPath, stashed_name
jsr GetSrcFileInfo
bcc spin
cmp #ERR_FILE_NOT_FOUND
beq create
bne error
spin: jsr SpinName
jmp retry
;; --------------------------------------------------
;; Try creating the folder
create:
MLI_CALL CREATE, create_params
bcs error
;; Update cached used/free for all same-volume windows and refresh
lda active_window_id
jsr UpdateActivateAndRefreshWindow
RTS_IF_NE
;; Select and rename the file
jmp TriggerRenameForFileIconWithStashedName
;; --------------------------------------------------
error:
ldx #AlertButtonOptions::OK
jmp ShowAlertOption
.endproc ; CmdNewFolderImpl
CmdNewFolder := CmdNewFolderImpl::start
;;; ============================================================
;;; Select and scroll into view an icon in the active window.
;;; Inputs: A,X = name
;;; Output: C=0 on success
;;; Trashes $06
.proc SelectFileIconByName
ldy active_window_id
jsr FindIconByName
IF_ZERO ; not found
sec
rts
END_IF
jsr SelectIconAndEnsureVisible
clc
rts
.endproc ; SelectFileIconByName
;;; ============================================================
;;; Find an icon by name in the given window.
;;; Inputs: Y = window id, A,X = name
;;; Outputs: Z=0, A = icon id (or Z=1, A=0 if not found)
;;; Preserves $06/$08
.proc FindIconByName
ptr_name := $06
;; TODO: Do we need to save pointers?
jsr PushPointers
stax ptr_name
lda cached_window_id
pha ; A = previous `cached_window_id`
tya
jsr LoadWindowEntryTable
jsr FindIconByNameInCachedWindow
sta icon
pla ; A = previous `cached_window_id`
jsr LoadWindowEntryTable
jsr PopPointers
icon := *+1
lda #SELF_MODIFIED_BYTE
rts
.endproc ; FindIconByName
;;; ============================================================
;;; Input: $06 has name
;;; Output: A = icon id (and Z=0), or A=0 and Z=1 if not found
;;; Trashes $08
.proc FindIconByNameInCachedWindow
ptr_name := $06
ptr_icon_name := $08
;; Iterate icons
copy8 #0, index
DO
index := *+1
ldx #SELF_MODIFIED_BYTE
IF_X_EQ cached_window_entry_count
;; Not found
lda #0
rts
END_IF
;; Compare with name from dialog
lda cached_window_entry_list,x
IF_A_NE trash_icon_num
jsr GetIconName
stax ptr_icon_name
jsr CompareStrings
IF_EQ
;; Match!
ldx index
lda cached_window_entry_list,x
rts
END_IF
END_IF
inc index
WHILE_NOT_ZERO ; always
.endproc ; FindIconByNameInCachedWindow
;;; ============================================================
;;; Save/Restore drop target icon ID in case the window was rebuilt.
;;; Inputs: `drag_drop_params::target`
;;; Assert: If target is a file icon, icon is in active window.
;;; Trashes $06
.proc MaybeStashDropTargetName
;; Flag as not stashed
copy8 #0, stashed_name
;; Is the target an icon?
lda drag_drop_params::target
IF_NC ; high bit clear = icon
;; Is the target in a window?
jsr GetIconWindow
IF_NOT_ZERO
;; Stash name
ptr1 := $06
lda drag_drop_params::target
jsr GetIconName
stax ptr1
param_call CopyPtr1ToBuf, stashed_name
END_IF
END_IF
rts
.endproc ; MaybeStashDropTargetName
;;; Outputs: `drag_drop_params::target` updated if needed
;;; Assert: `MaybeStashDropTargetName` was previously called
;;; Trashes $06
.proc MaybeUpdateDropTargetFromName
;; Did we previously stash an icon's name?
lda stashed_name
IF_NOT_ZERO
;; Try to find the icon by name.
ldy active_window_id
param_call FindIconByName, stashed_name
IF_NOT_ZERO
;; Update drop target with new icon id.
sta drag_drop_params::target
END_IF
END_IF
rts
.endproc ; MaybeUpdateDropTargetFromName
stashed_name:
.res 16, 0
;;; ============================================================
;;; Take the name in `stashed_name` and "increment it":
;;; * If ends in dot-digits, increment (adjusting length if needed)
;;; * Otherwise, append ".2" (shrinking if needed)
;;; Trashes $10...$1F
.proc SpinName
digits := $10
;; Zero out counter (a digit string, in reverse)
lda #'0'
ldy #15
DO
sta digits,y
dey
WHILE_NOT_ZERO
;; While digits, pop from string (X=len) onto digits (Y=len)
ldx stashed_name
DO
lda stashed_name,x
BREAK_IF_A_LT #'0'
BREAK_IF_A_GE #'9'+1
iny
sta digits,y ; stash digits as we go
dex
WHILE_NOT_ZERO ; always (name must start w/ letter)
;; Did the string end with '.' then digits?
cmp #'.' ; dot before numbers?
bne just_append
cpy #0 ; any digits found?
beq just_append
;; Truncate the '.', and increment the digits
dex
stx stashed_name
sty digits
ldx #0 ; increment
DO
DO
inc digits+1,x
lda digits+1,x
cmp #'9'+1
bne concatenate ; done
copy8 #'0', digits+1,x
inx
WHILE_X_NE digits
inc digits
WHILE_X_NE #13 ; max of 13 digits
beq SpinName ; restart
;; --------------------------------------------------
just_append:
copy8 #1, digits
copy8 #'2', digits+1
FALL_THROUGH_TO concatenate
;; --------------------------------------------------
concatenate:
lda #14
sec
sbc digits
IF_A_LT stashed_name
sta stashed_name
END_IF
ldx stashed_name
inx
copy8 #'.', stashed_name,x
ldy digits
DO
lda digits,y
inx
sta stashed_name,x
dey
WHILE_NOT_ZERO
stx stashed_name
rts
.endproc ; SpinName
;;; ============================================================
;;; Input: Icon number in A.
;;; Assert: Icon in active window.
.proc ScrollIconIntoView
pha
jsr LoadActiveWindowEntryTable
pla
sta icon_param
;; Map coordinates to window
pha ; A = icon
jsr IconScreenToWindow
;; Grab the icon bounds
ITK_CALL IconTK::GetIconBounds, icon_param ; inits `tmp_rect`
;; Restore coordinates
pla ; A = icon
jsr IconWindowToScreen
viewport := window_grafport+MGTK::GrafPort::maprect
;; Get the viewport, and adjust for header
jsr ApplyActiveWinfoToWindowGrafport
add16_8 viewport+MGTK::Rect::y1, #kWindowHeaderHeight - 1
;; Padding
MGTK_CALL MGTK::InflateRect, bbox_pad_tmp_rect
;; --------------------------------------------------
;; Adjustments
delta := $06
dirty := $08
copy8 #0, dirty
ldx #2 ; loop over dimensions
DO
;; Is left of icon beyond window? If so, adjust by delta (negative)
sub16 tmp_rect::topleft,x, viewport+MGTK::Rect::topleft,x, delta
bmi adjust
;; Is right of icon beyond window? If so, adjust by delta (positive)
sub16 tmp_rect::bottomright,x, viewport+MGTK::Rect::bottomright,x, delta
bmi done
adjust:
lda delta
ora delta+1
IF_NOT_ZERO
inc dirty
add16 viewport+MGTK::Rect::topleft,x, delta, viewport+MGTK::Rect::topleft,x
add16 viewport+MGTK::Rect::bottomright,x, delta, viewport+MGTK::Rect::bottomright,x
END_IF
done:
dex ; next dimension
dex
WHILE_POS
lda dirty
IF_NOT_ZERO
;; Apply the viewport (accounting for header)
sub16_8 viewport+MGTK::Rect::y1, #kWindowHeaderHeight - 1
jsr AssignActiveWindowCliprectAndUpdateCachedIcons
jsr ClearAndDrawActiveWindowEntries
jsr ScrollUpdate
END_IF
rts
.endproc ; ScrollIconIntoView
;;; ============================================================
.proc CmdCheckOrEjectImpl
ENTRY_POINTS_FOR_BIT7_FLAG eject, check, eject_flag
;; Ensure that volumes are selected
lda selected_window_id
IF_NOT_ZERO
done: rts
END_IF
;; And if there's only one, it's not Trash
jsr GetSingleSelectedIcon
cmp trash_icon_num ; if it's Trash, skip it
beq done
ldx selected_icon_count
stx selection_count_copy
DO
copy8 selected_icon_list-1,x, selection_list_copy-1,x
dex
WHILE_NOT_ZERO
;; If ejecting, clear selection
bit eject_flag
IF_NS
jsr ClearSelection
END_IF
;; Iterate the recorded volumes
ldx #0 ; X = index
DO
txa ; A = index
pha
lda selection_list_copy,x
IF_A_NE trash_icon_num
ldy #$80 ; Y = show unexpected errors flag (do)
bit eject_flag
IF_NS
pha
jsr SmartportEject
pla
ldy #$00 ; Y = show unexpected errors flag (don't)
END_IF
jsr CheckDriveByIconNumber ; A = icon number
END_IF
pla ; A = index
tax ; X = index
inx
WHILE_X_NE selection_count_copy
rts
eject_flag:
.byte 0
selection_count_copy:
.byte 0
selection_list_copy:
.res ::kMaxVolumes
.endproc ; CmdCheckOrEjectImpl
CmdEject := CmdCheckOrEjectImpl::eject
CmdCheckDrive := CmdCheckOrEjectImpl::check
;;; ============================================================
.proc CmdQuitImpl
;; Override within this scope
MLIEntry := MLI
quit_code_io := $800
quit_code_addr := $1000
quit_code_size := $400
DEFINE_OPEN_PARAMS open_params, str_quit_code, quit_code_io
DEFINE_READWRITE_PARAMS read_params, quit_code_addr, quit_code_size
DEFINE_CLOSE_PARAMS close_params
DEFINE_QUIT_PARAMS quit_params
str_quit_code:
PASCAL_STRING kPathnameQuitSave
ResetHandler:
;; Restore DeskTop Main expected state...
sta ALTZPON
bit LCBANK1
bit LCBANK1
start:
;; Restore system state: devices, /RAM, ROM/ZP banks.
jsr RestoreSystem
;; Load and run/reinstall previous QUIT handler.
MLI_CALL OPEN, open_params
bcs fail
lda open_params::ref_num
sta read_params::ref_num
sta close_params::ref_num
MLI_CALL READ, read_params
MLI_CALL CLOSE, close_params
jmp quit_code_addr
fail: MLI_CALL QUIT, quit_params
brk
.endproc ; CmdQuitImpl
CmdQuit := CmdQuitImpl::start
ResetHandler := CmdQuitImpl::ResetHandler
;;; ============================================================
;;; Exit DHR, restore device list, reformat /RAM.
;;; Returns with ALTZPOFF and ROM banked in.
.proc RestoreSystem
CLEAR_BIT7_FLAG main::mli_relay_checkevents_flag
jsr SaveWindows
MGTK_CALL MGTK::StopDeskTop
;; Switch back to main ZP/LC, preserving return address.
pla
tax
pla
sta ALTZPOFF
pha
txa
pha
;; Exit graphics mode entirely
bit ROMIN2
sta SET80STORE ; 80-col firmware expects this
lda #0 ; INIT is not used as that briefly
sta WNDLFT ; displays the dirty text page
sta WNDTOP
copy8 #80, WNDWDTH
copy8 #24, WNDBTM
jsr HOME ; Clear 80-col screen
sta TXTSET ; ... and show it
lda #$95 ; Ctrl-U - disable 80-col firmware
jsr COUT
jsr INIT ; reset text window again
jsr SETVID ; after INIT so WNDTOP is set properly
jsr SETKBD
;; Switch back to color DHR mode now that screen is blank
bit LCBANK1
bit LCBANK1
sta ALTZPON
jsr SetColorMode ; depends on state in Aux LC
sta CLR80VID ; back off, after `SetColorMode` call
sta DHIRESOFF
sta ALTZPOFF
bit ROMIN2
jsr ReconnectRAM
jmp RestoreDeviceList
.endproc ; RestoreSystem
;;; ============================================================
menu_item_to_view_by:
.byte DeskTopSettings::kViewByIcon
.byte DeskTopSettings::kViewBySmallIcon
.byte DeskTopSettings::kViewByName
.byte DeskTopSettings::kViewByDate
.byte DeskTopSettings::kViewBySize
.byte DeskTopSettings::kViewByType
;;; Assert: Window is open
.proc CmdViewBy
jsr GetActiveWindowViewBy
sta current
ldx menu_click_params::item_num
lda menu_item_to_view_by-1,x
;; Is this a change?
current := *+1
cmp #SELF_MODIFIED_BYTE
RTS_IF_EQ
;; Update view menu/table
ldx active_window_id
sta win_view_by_table-1,x
FALL_THROUGH_TO RefreshViewPreserveSelection
.endproc ; CmdViewBy
;;; ============================================================
.proc RefreshViewImpl
;;; Entry point when view needs refreshing, e.g. rename when sorted.
entry2:
;; Selection not preserved in other entry points
;; because file records are not retained.
jsr _PreserveSelection
;; Destroy existing icons
jsr LoadActiveWindowEntryTable
jsr RemoveAndFreeCachedWindowIcons
;;; Entry point when refreshing window contents
entry3:
;; Clear selection if in the window
lda selected_window_id
IF_A_EQ active_window_id
lda #0
sta selected_icon_count
sta selected_window_id
END_IF
;; Reset the viewport
jsr ResetActiveWindowViewport ; Must precede icon creation
;; Create the icons
jsr LoadActiveWindowEntryTable
jsr InitWindowEntriesAndIcons
jsr AdjustViewportForNewIcons
jsr _RestoreSelection
jsr ClearAndDrawActiveWindowEntries
jmp ScrollUpdate
;;; --------------------------------------------------
;;; Preserves selection by replacing selected icon ids
;;; with their corresponding record indexes, which remain
;;; valid across view changes.
.proc _PreserveSelection
lda selected_window_id
IF_A_EQ active_window_id
lda selected_icon_count
IF_NOT_ZERO
sta selection_preserved_count
;; For each selected icon, replace icon number
;; with its corresponding file record number.
DO
ldx selected_icon_count
lda selected_icon_list-1,x
jsr GetIconRecordNum
ldx selected_icon_count
sta selected_icon_list-1,x
dec selected_icon_count
WHILE_NOT_ZERO
copy8 #0, selected_window_id
END_IF
END_IF
rts
.endproc ; _PreserveSelection
;;; --------------------------------------------------
;;; Restores selection after a view change, reversing what
;;; `_PreserveSelection` did.
.proc _RestoreSelection
lda selection_preserved_count
IF_NOT_ZERO
;; For each record num in the list, find and
;; highlight the corresponding icon.
DO
ldx selected_icon_count
lda selected_icon_list,x
jsr FindIconForRecordNum
jsr AddToSelectionList
sta icon_param
ITK_CALL IconTK::HighlightIcon, icon_param
dec selection_preserved_count
WHILE_NOT_ZERO
copy8 cached_window_id, selected_window_id
END_IF
rts
.endproc ; _RestoreSelection
selection_preserved_count:
.byte 0
.endproc ; RefreshViewImpl
RefreshViewPreserveSelection := RefreshViewImpl::entry2
RefreshView := RefreshViewImpl::entry3
;;; ============================================================
;;; Find the icon for the cached window's given record index.
;;; Input: A = record index in cached window
;;; Output: A = icon id
;;; Assert: there is a match, window has entries
;;; Trashes $06
.proc FindIconForRecordNum
sta record_num
copy8 cached_window_entry_count, index
DO
index := *+1
ldx #SELF_MODIFIED_BYTE
lda cached_window_entry_list-1,x
jsr GetIconRecordNum
record_num := *+1
cmp #SELF_MODIFIED_BYTE
BREAK_IF_EQ
dec index
WHILE_POS
ldx index
lda cached_window_entry_list-1,x
rts
.endproc ; FindIconForRecordNum
;;; ============================================================
;;; Retrieve the window id for a given icon.
;;; Input: A = icon id
;;; Output: A = window id (0=desktop)
.proc GetIconWindow
jsr PushPointers
jsr GetIconEntry
ptr := $06
stax ptr
ldy #IconEntry::win_flags
lda (ptr),y
and #kIconEntryWinIdMask
jsr PopPointers ; do not tail-call optimize!
rts
.endproc ; GetIconWindow
;;; ============================================================
.proc RemoveAndFreeCachedWindowIcons
lda icon_count
sec
sbc cached_window_entry_count
sta icon_count
ITK_CALL IconTK::FreeAll, cached_window_id
;; Remove any associations with windows
ldx cached_window_entry_count
IF_NOT_ZERO
DO
txa ; X = index+1
pha ; A = index+1
lda cached_window_entry_list-1,x
jsr FindWindowIndexForDirIcon ; X = window id-1 if found
IF_EQ
copy8 #kWindowToDirIconNone, window_to_dir_icon_table,x
END_IF
pla ; A = index+1
tax ; X = index+1
dex
WHILE_NOT_ZERO
END_IF
rts
.endproc ; RemoveAndFreeCachedWindowIcons
;;; ============================================================
.proc CmdFormatEraseDiskImpl
ENTRY_POINTS_FOR_A format, FormatEraseAction::format, erase, FormatEraseAction::erase
sta action
jsr GetSelectedUnitNum
sta unit_num
exec: lda #kDynamicRoutineFormatErase
jsr LoadDynamicRoutine
RTS_IF_NS
unit_num := *+1
ldx #SELF_MODIFIED_BYTE
action := *+1
lda #SELF_MODIFIED_BYTE
jsr ::FormatEraseOverlay::Exec
RTS_IF_NOT_ZERO
txa
ldy #$00 ; Y = show unexpected errors flag (don't)
jmp CheckDriveByUnitNumber ; A = unit number
unit: sta unit_num
copy8 #FormatEraseAction::format, action
bne exec ; always
.endproc ; CmdFormatEraseDiskImpl
CmdFormatDisk := CmdFormatEraseDiskImpl::format
CmdEraseDisk := CmdFormatEraseDiskImpl::erase
FormatUnitNum := CmdFormatEraseDiskImpl::unit
;;; ============================================================
;;; Inputs: A=unit number if a single volume is selected, 0 otherwise
.proc GetSelectedUnitNum
;; Get single selected volume icon (or fail)
lda selected_window_id
bne fail ; not the desktop
jsr GetSingleSelectedIcon
beq fail
jsr IconToDeviceIndex
beq found
fail: lda #0
rts
found: lda DEVLST,x
and #UNIT_NUM_MASK
rts
.endproc ; GetSelectedUnitNum
;;; ============================================================
;;; Input: A = icon id
;;; Output: if found, Z=1 and X = index in DEVLST; Z=0 otherwise
.proc IconToDeviceIndex
ldx #kMaxVolumes-1
DO
BREAK_IF_A_EQ device_to_icon_map,x
dex
WHILE_POS
ret: rts
.endproc ; IconToDeviceIndex
;;; ============================================================
;;; Assert: Icon(s) selected
.proc CmdGetInfo
jsr DoGetInfo
IF_NS
;; Selected items were modified (e.g. locked), so refresh
lda selected_window_id
IF_NOT_ZERO ; windowed (not desktop); refresh needed
cmp active_window_id
jeq ClearAndDrawActiveWindowEntries ; active - just repaint
jmp ActivateWindow ; inactive - activate, it will repaint
END_IF
END_IF
rts
.endproc ; CmdGetInfo
;;; ============================================================
;;; Assert: File(s) are selected
.proc CmdDeleteSelection
jsr DoDeleteSelection
RTS_IF_A_EQ #kOperationCanceled
SET_BIT7_FLAG validate_windows_flag
jmp UpdateActivateAndRefreshSelectedWindow
.endproc ; CmdDeleteSelection
;;; ============================================================
;;; Assert: Single icon selected, and it's not Trash
.proc CmdCopy
lda selected_icon_list
jsr GetIconName
stax $06
param_jump CopyPtr1ToBuf, clipboard
.endproc ; CmdCopy
.proc CmdPaste
;; MacOS 6 behavior - no-op if clipboard is empty
lda clipboard
RTS_IF_EQ
ldax #clipboard
ASSERT_NOT_EQUALS .hibyte(clipboard), 0
bne CmdRenameWithDefaultNameGiven
.endproc ; CmdPaste
.proc CmdCut
jsr CmdCopy
FALL_THROUGH_TO CmdClear
.endproc ; CmdCut
.proc CmdClear
ldax #str_empty
ASSERT_NOT_EQUALS .hibyte(str_empty), 0
beq CmdRenameWithDefaultNameGiven
.endproc ; CmdClear
;;; ============================================================
.proc TriggerRenameForFileIconWithStashedName
param_call SelectFileIconByName, stashed_name
FALL_THROUGH_TO CmdRename
.endproc ; TriggerRenameForFileIconWithStashedName
;;; ============================================================
;;; Assert: Single icon selected, and it's not Trash
.proc CmdRename
;; Dialog will use this field (populated in `DoRename`) as default
ldax #old_name_buf
;; ... but callers can override and use this entry point instead.
ep2:
jsr DoRename
pha ; A = result
;; If selection in non-active window, activate it
lda selected_window_id
jsr ActivateWindow ; no-op if already active, or 0
;; If selection is in a window with View > by Name, refresh
lda selected_window_id
IF_NE
jsr GetSelectionViewBy
IF_A_EQ #DeskTopSettings::kViewByName
txa ; X = window id
jsr RefreshViewPreserveSelection
lda selected_icon_list
jsr ScrollIconIntoView
ELSE
;; Scrollbars may need adjusting
jsr ScrollUpdate
END_IF
END_IF
pla ; A = result
IF_NS ; N = window renamed
;; TODO: Avoid repainting everything
MGTK_CALL MGTK::RedrawDeskTop
END_IF
rts
.endproc ; CmdRename
CmdRenameWithDefaultNameGiven := CmdRename::ep2 ; A,X = name
;;; ============================================================
;;; Assert: Single file icon selected
.proc CmdDuplicate
;; --------------------------------------------------
;; Determine the name to use
;; Start with original name
lda selected_icon_list
jsr GetIconName
stax $06
param_call CopyPtr1ToBuf, stashed_name
;; Construct src path
jsr GetSelectionWindow
jsr GetWindowPath
jsr CopyToSrcPath
param_call AppendFilenameToSrcPath, stashed_name
;; Repeat to find a free name
spin: jsr GetSelectionWindow
jsr GetWindowPath
jsr CopyToDstPath
jsr SpinName
param_call AppendFilenameToDstPath, stashed_name
jsr GetDstFileInfo
bcc spin
cmp #ERR_FILE_NOT_FOUND
bne error
;; --------------------------------------------------
;; Try copying the file
copy16 #src_path_buf, $06
copy16 #dst_path_buf, $08
jsr CopyPathsFromPtrsToBufsAndSplitName
jsr DoCopyFile
sta result
RTS_IF_A_EQ #kOperationCanceled
;; Update name case bits on disk, if possible.
param_call CopyToSrcPath, dst_path_buf
jsr ApplyCaseBits ; applies `stashed_name` to `src_path_buf`
;; Update cached used/free for all same-volume windows, and refresh
lda selected_window_id
jsr UpdateActivateAndRefreshWindow
RTS_IF_NE
;; If operation failed, then just leave the default name.
result := *+1
lda #SELF_MODIFIED_BYTE
ASSERT_NOT_EQUALS kOperationFailed, 0
RTS_IF_NOT_ZERO
;; Select and rename the file
jmp TriggerRenameForFileIconWithStashedName
;; --------------------------------------------------
error:
ldx #AlertButtonOptions::OK
jmp ShowAlertOption
.endproc ; CmdDuplicate
;;; ============================================================
;;; Handle keyboard-based icon selection ("highlighting")
.proc KeyboardHighlightImpl
;;; Local variables on ZP
PARAM_BLOCK, $50
delta .byte
END_PARAM_BLOCK
;; ----------------------------------------
;; Next/prev in sorted order
;; Tab / Shift+Tab
alpha: jsr ShiftDown
bpl a_next
FALL_THROUGH_TO a_prev
ENTRY_POINTS_FOR_A a_prev, AS_BYTE(-1), a_next, 1
sta delta
jsr GetKeyboardSelectableIconsSorted
jmp common
;; ----------------------------------------
;; Arrows - next/prev in icon order
ENTRY_POINTS_FOR_A prev, AS_BYTE(-1), next, 1
sta delta
jsr GetKeyboardSelectableIcons
FALL_THROUGH_TO common
;;; --------------------------------------------------
;;; Figure out current selected index, based on selection.
common:
;; First byte is icon count. Rest is a list of selectable icons.
buffer := $1800
;; Anything selectable?
lda buffer
beq ret
lda selected_icon_count
beq fallback
;; Try to find actual selection in our list
lda selected_icon_list ; Only consider first, otherwise N^2
ldx buffer ; count
dex ; index
DO
cmp buffer+1,x
beq pick_next_prev
dex
WHILE_POS
;; If not in our list, use a fallback.
fallback:
ldx #0
ldy delta
IF_NEG
ldx buffer
dex
END_IF
bpl select_index ; always
;; There was a selection; pick prev/next based on keypress.
pick_next_prev:
txa
clc
adc delta ; +1 or -1
cmp buffer
bcs ret ; handles >= max or < 0
tax
FALL_THROUGH_TO select_index
select_index:
lda buffer+1,x
jmp SelectIconAndEnsureVisible
ret: rts
.endproc ; KeyboardHighlightImpl
KeyboardHighlightPrev := KeyboardHighlightImpl::prev
KeyboardHighlightNext := KeyboardHighlightImpl::next
KeyboardHighlightAlpha := KeyboardHighlightImpl::alpha
KeyboardHighlightAlphaPrev := KeyboardHighlightImpl::a_prev
KeyboardHighlightAlphaNext := KeyboardHighlightImpl::a_next
;;; ============================================================
.proc KeyboardHighlightSpatialImpl
;;; Local variables on ZP
PARAM_BLOCK, $50
dir .byte
index .byte
cur_icon .byte
icon_rect .tag MGTK::Rect
best_icon .byte
best_value .word
END_PARAM_BLOCK
ASSERT_EQUALS icon_rect, cur_icon+1, "Must be adjacent"
kDirLeft = 0
kDirRight = 1
kDirUp = 2
kDirDown = 3
ENTRY_POINTS_FOR_A left, kDirLeft, right, kDirRight, up, kDirUp, down, kDirDown
sta dir
;;; --------------------------------------------------
;;; If a list view, use index-based logic
jsr GetActiveWindowViewBy ; N=0 is icon view, N=1 is list view
IF_NS
lda dir
cmp #kDirUp
beq KeyboardHighlightPrev
bcs KeyboardHighlightNext
rts ; ignore if left/right
END_IF
;;; --------------------------------------------------
;;; Identify a starting icon
jsr LoadActiveWindowEntryTable
lda selected_icon_count
jeq fallback
lda active_window_id
cmp selected_window_id
jne fallback
copy8 selected_icon_list, icon_param ; use first
;;; --------------------------------------------------
;;; Get bounds
ITK_CALL IconTK::GetBitmapRect, icon_param ; inits `tmp_rect`
;;; --------------------------------------------------
;;; Extend rect, based on dir
kDelta = 1024
;; For relevant dir, determine:
;; A,X = delta (positive or negative)
;; Y = offset into `tmp_rect`
ldy dir
lda rect_deltas_lo,y
ldx rect_deltas_hi,y
pha
lda far_offsets,y
tay
pla
;; `tmp_rect`,y += A,X
clc
adc tmp_rect,y
sta tmp_rect,y
txa
iny
adc tmp_rect,y
sta tmp_rect,y
;;; --------------------------------------------------
;;; Iterate over icons, consider any in rect
lda #0
sta best_icon
sta index
DO
ldx index
BREAK_IF_X_EQ cached_window_entry_count
lda cached_window_entry_list,x
sta cur_icon
sta icon_param
jsr IsIconSelected
beq next_icon
ITK_CALL IconTK::IconInRect, icon_param ; tests against `tmp_rect`
beq next_icon
;; NOTE: This is the only IconTK call which passes a param block
;; on the zero page; it must not collide with IconTK's own use
;; of the zero page.
ITK_CALL IconTK::GetIconBounds, cur_icon ; result in `icon_rect`
ldx dir
ldy near_offsets,x ; y = MGTK::Rect member offset
;; If icon's near edge < selected icon's near edge, ignore
scmp16 icon_rect,y, tmp_rect,y
eor compare_order,x ; flip result if needed
bmi next_icon
;; Any other candidates so far?
lda best_icon
beq best
;; If icon's near edge > `best_value`, ignore
scmp16 icon_rect,y, best_value
eor compare_order,x ; flip result if needed
bpl next_icon
best:
copy8 cur_icon, best_icon
copy16 icon_rect,y, best_value
next_icon:
inc index
WHILE_NOT_ZERO ; always
finish_loop:
lda best_icon
bne select
ret: rts
;;; Tables indexed by `kDirXXX`
rect_deltas_lo: .byte <AS_WORD(-kDelta), <kDelta, <AS_WORD(-kDelta), <kDelta
rect_deltas_hi: .byte >AS_WORD(-kDelta), >kDelta, >AS_WORD(-kDelta), >kDelta
far_offsets: .byte MGTK::Rect::x1, MGTK::Rect::x2, MGTK::Rect::y1, MGTK::Rect::y2
near_offsets: .byte MGTK::Rect::x2, MGTK::Rect::x1, MGTK::Rect::y2, MGTK::Rect::y1
compare_order: .byte $80, $00, $80, $00
;;; --------------------------------------------------
;;; If there was no (usable) selection, pick icon from active window.
fallback:
ldy cached_window_entry_count
beq ret
;; Default to first (X) / last (Y) icon
ldx #0
dey
lda active_window_id
IF_ZERO
;; ...except on desktop, since first is Trash.
tay ; make last (Y) be Trash (0)
inx ; and first (X) be 1st volume icon
IF_X_EQ cached_window_entry_count ; unless there isn't one
dex
END_IF
END_IF
ror dir ; C = 1 if right/down
lda cached_window_entry_list,x
IF_CC
lda cached_window_entry_list,y
END_IF
select:
jmp SelectIconAndEnsureVisible
.endproc ; KeyboardHighlightSpatialImpl
KeyboardHighlightLeft := KeyboardHighlightSpatialImpl::left
KeyboardHighlightRight := KeyboardHighlightSpatialImpl::right
KeyboardHighlightDown := KeyboardHighlightSpatialImpl::down
KeyboardHighlightUp := KeyboardHighlightSpatialImpl::up
;;; ============================================================
;;; Type Down Selection
;;; Output: Z=1 (always)
.proc ClearTypeDown
copy8 #0, typedown_buf
rts
.endproc ; ClearTypeDown
;;; Returns Z=1 if consumed, Z=0 otherwise.
.proc CheckTypeDown
jsr ToUpperCase
cmp #'A'
bcc :+
cmp #'Z'+1
bcc file_char
: ldx typedown_buf
beq not_file_char
cmp #'.'
beq file_char
cmp #'0'
bcc not_file_char
cmp #'9'+1
bcc file_char
not_file_char:
return #$FF ; Z=0 to ignore
file_char:
ldx typedown_buf
RTS_IF_X_EQ #kMaxFilenameLength ; Z=1 to consume
inx
stx typedown_buf
sta typedown_buf,x
;; Collect and sort the potential type-down matches
jsr GetKeyboardSelectableIconsSorted
lda num_filenames
IF_NOT_ZERO
;; Find a match.
jsr _FindMatch
;; Icon to select
tax
copy8 table,x, icon ; index to icon
;; Already the selection?
jsr GetSingleSelectedIcon
IF_A_NE icon
;; Update the selection.
icon := *+1
lda #SELF_MODIFIED_BYTE
jsr SelectIconAndEnsureVisible
END_IF
END_IF
lda #0
rts
num_filenames := $1800
table := $1801
;;; Find the substring match for `typedown_buf`, or the next
;;; match in lexicographic order, or the last item in the table.
.proc _FindMatch
ptr := $06
len := $08
copy8 #0, index
DO
index := *+1
lda #SELF_MODIFIED_BYTE
jsr GetNthSelectableIconName
stax ptr
;; NOTE: Can't use `CompareStrings` as we want to match
;; on subset-or-equals.
ldy #0
copy8 (ptr),y, len
ldy #1
cloop: lda (ptr),y
jsr ToUpperCase
cmp typedown_buf,y
bcc next
beq :+ ; TODO: `BGT` ?
bcs found
:
cpy typedown_buf
beq found
iny
cpy len
bcc cloop ; TODO: `BLE` ?
beq cloop
next: inc index
lda index
WHILE_A_NE num_filenames
dec index
found: return index
.endproc ; _FindMatch
.endproc ; CheckTypeDown
;;; Length plus filename
typedown_buf:
.res 16, 0
;;; ============================================================
;;; Build list of keyboard-selectable icons.
;;; This is all icons in active window.
;;; Output: Buffer at $1800 (length prefixed)
;;; X = number of icons
.proc GetKeyboardSelectableIcons
buffer := $1800
jsr LoadActiveWindowEntryTable
ldx #0
DO
BREAK_IF_X_EQ cached_window_entry_count
copy8 cached_window_entry_list,x, buffer+1,x
inx
WHILE_NE ; always
stx buffer
rts
.endproc ; GetKeyboardSelectableIcons
;;; Gather the keyboard-selectable icons into buffer at $1800, and
;;; sort them by name.
;;; Output: Buffer at $1800 (length prefixed)
.proc GetKeyboardSelectableIconsSorted
buffer := $1800
ptr1 := $06
ptr2 := $08
jsr GetKeyboardSelectableIcons
RTS_IF_X_LT #2
;; Selection sort. In each outer iteration, the highest
;; remaining element is moved to the end of the unsorted
;; region, and the region is reduced by one. O(n^2)
dex
stx outer
DO
outer := *+1
lda #SELF_MODIFIED_BYTE
jsr GetNthSelectableIconName
stax ptr2
copy8 #0, inner
DO
inner := *+1
lda #SELF_MODIFIED_BYTE
jsr GetNthSelectableIconName
stax ptr1
jsr CompareStrings
IF_GE
;; Swap
ldx inner
ldy outer
swap8 buffer+1,x, buffer+1,y
tya
jsr GetNthSelectableIconName
stax ptr2
END_IF
inc inner
lda inner
WHILE_A_NE outer
dec outer
WHILE_NOT_ZERO
rts
.endproc ; GetKeyboardSelectableIconsSorted
;;; Assuming selectable icon buffer at $1800 is populated by the
;;; above functions, return ptr to nth icon's name in A,X
;;; Input: A = index
;;; Output: A,X = icon name pointer
.proc GetNthSelectableIconName
buffer := $1800
tax
lda buffer+1,x ; A = icon num
jmp GetIconName
.endproc ; GetNthSelectableIconName
;;; ============================================================
;;; Compare strings at $06 (1) and $08 (2). Case insensitive.
;;; Returns C=0 for 1<2 , C=1 for 1>=2, Z=1 for 1=2
.proc CompareStrings
ptr1 := $06
ptr2 := $08
ldy #0
copy8 (ptr1),y, len1
copy8 (ptr2),y, len2
iny
DO
lda (ptr2),y
jsr ToUpperCase
sta char
lda (ptr1),y
jsr ToUpperCase
char := *+1
cmp #SELF_MODIFIED_BYTE
bne ret ; differ at Yth character
;; End of string 1?
len1 := *+1
cpy #SELF_MODIFIED_BYTE
IF_EQ
cpy len2 ; 1<2 or 1=2 ?
rts
END_IF
;; End of string 2?
len2 := *+1
cpy #SELF_MODIFIED_BYTE
beq gt ; 1>2
iny
WHILE_NOT_ZERO ; always
gt: lda #$FF ; Z=0
sec
ret: rts
.endproc ; CompareStrings
;;; ============================================================
;;; Replace selection with the specified icon. The icon's
;;; window is activated if necessary. If windowed, it is scrolled
;;; into view.
;;; Inputs: A = icon id
.proc SelectIconAndEnsureVisible
;; No-op if already single selected icon
ldy selected_icon_count
dey
bne continue
cmp selected_icon_list
beq ret
continue:
pha
jsr ClearSelection
pla
pha
jsr GetIconWindow
jsr ActivateWindow ; no-op if already active, or 0
pla
sta icon_param
ITK_CALL IconTK::HighlightIcon, icon_param
;; Find icon's window, and set selection
lda icon_param
jsr GetIconWindow
sta selected_window_id
copy8 #1, selected_icon_count
copy8 icon_param, selected_icon_list
;; If windowed, ensure it is visible
lda selected_window_id
IF_NOT_ZERO
lda selected_icon_list
jsr ScrollIconIntoView
END_IF
ITK_CALL IconTK::DrawIcon, selected_icon_list
ret: rts
.endproc ; SelectIconAndEnsureVisible
;;; ============================================================
.proc CmdSelectAll
jsr ClearSelection
jsr LoadActiveWindowEntryTable
lda cached_window_entry_count
beq finish ; nothing to select!
ldx cached_window_entry_count
dex
DO
copy8 cached_window_entry_list,x, selected_icon_list,x
dex
WHILE_POS
copy8 cached_window_entry_count, selected_icon_count
copy8 active_window_id, selected_window_id
;; --------------------------------------------------
;; Mark all icons as highlighted
ldx #0
DO
txa
pha
copy8 selected_icon_list,x, icon_param
ITK_CALL IconTK::HighlightIcon, icon_param
pla
tax
inx
WHILE_X_NE selected_icon_count
;; --------------------------------------------------
;; Repaint the icons
;; Assert: `selected_window_id` == `active_window_id`
;; Assert: `selected_window_id` == `cached_window_id`
lda selected_window_id
IF_ZERO
jsr InitSetDesktopPort
ELSE
jsr UnsafeSetPortFromWindowIdAndAdjustForEntries ; CHECKED
END_IF
IF_ZERO ; Skip drawing if obscured
jsr CachedIconsScreenToWindow
ITK_CALL IconTK::DrawAll, cached_window_id ; CHECKED
jsr CachedIconsWindowToScreen
END_IF
finish: rts
.endproc ; CmdSelectAll
;;; ============================================================
;;; Cycle Through Windows
;;; Input: A = Key used; '~' is reversed
.proc CmdCycleWindows
tay
;; Need at least two windows to cycle.
lda num_open_windows
IF_A_GE #2
cpy #'~'
beq reverse
jsr ShiftDown
bmi reverse
;; TODO: Using this table as the source is a little odd.
;; Ideally would be doing send-front-to-back/bring-back-to-front
;; but maintaining order would be tricky.
;; --------------------------------------------------
;; Search upwards through window-icon map to find next.
;; ID is 1-based, table is 0-based, so don't need to start
;; with an increment
ldx active_window_id
DO
IF_X_EQ #kMaxDeskTopWindows
ldx #0
END_IF
lda window_to_dir_icon_table,x
bne found ; not `kWindowToDirIconFree`
inx
WHILE_NOT_ZERO ; always
;; --------------------------------------------------
;; Search downwards through window-icon map to find next.
;; ID is 1-based, table is 0-based, start with decrements.
reverse:
ldx active_window_id
dex
DO
dex
IF_NEG
ldx #kMaxDeskTopWindows-1
END_IF
lda window_to_dir_icon_table,x
WHILE_ZERO ; is `kWindowToDirIconFree`
FALL_THROUGH_TO found
found: inx
txa
jmp ActivateWindow
END_IF
rts
.endproc ; CmdCycleWindows
;;; ============================================================
;;; Flip Screen
.proc CmdFlipScreen
JSR_TO_AUX aux::FlipMGTKHiresTable
MGTK_CALL MGTK::RedrawDeskTop
MGTK_CALL MGTK::DrawMenuBar
rts
.endproc ; CmdFlipScreen
;;; ============================================================
;;; Keyboard-based scrolling of window contents
.proc CmdScroll
repeat: jsr GetEvent ; no need to synthesize events
cmp #MGTK::EventKind::button_down
beq done
cmp #MGTK::EventKind::key_down
bne repeat
lda event_params::key
IF_A_EQ_ONE_OF #CHAR_RETURN, #CHAR_ESCAPE
done: rts
END_IF
IF_A_EQ #CHAR_RIGHT
jsr ScrollRight
jmp repeat
END_IF
IF_A_EQ #CHAR_LEFT
jsr ScrollLeft
jmp repeat
END_IF
IF_A_EQ #CHAR_DOWN
jsr ScrollDown
jmp repeat
END_IF
cmp #CHAR_UP
bne repeat
jsr ScrollUp
jmp repeat
.endproc ; CmdScroll
;;; ============================================================
;;; Centralized logic for scrolling directory windows
.scope ScrollManager
;;; Terminology:
;;; * "offset" - When the icons would fit entirely within the viewport
;;; (for a given dimension) but the viewport is offset so a scrollbar
;;; must still be shown.
;;; Effective viewport ("Effective" discounts the window header.)
viewport := window_grafport+MGTK::GrafPort::maprect
;;; Local variables on ZP
PARAM_BLOCK, $50
;;; `ubox` is a union of the effective viewport and icon bounding box
ubox .tag MGTK::Rect
;;; Effective dimensions of the viewport
width .word
height .word
;;; Initial effective viewport top/left
old .tag MGTK::Point
;;; Increment/decrement sizes (depends on view type)
tick_h .byte
tick_v .byte
tmpw .word
END_PARAM_BLOCK
dimensions := width
;;; --------------------------------------------------
;;; Compute the necessary data for scroll operations:
;;; * `viewport` - effective viewport of active window
;;; * `ubox` - union of icon bounding box and viewport
;;; * `tick_h` and `tick_v` sizes (based on view type)
;;; * `width` and `height` of the effective viewport
;;; * `old` - initial top/left of viewport (to detect changes)
_Preamble:
jsr LoadActiveWindowEntryTable
jsr GetActiveWindowViewBy ; N=0 is icon view, N=1 is list view
IF_NC
;; Icon view
ldx #kIconViewScrollTickH
ldy #kIconViewScrollTickV
ELSE
;; List view
ldx #kListViewScrollTickH
ldy #kListViewScrollTickV
END_IF
stx tick_h
sty tick_v
;; Compute effective viewport
jsr ApplyActiveWinfoToWindowGrafport
add16_8 viewport+MGTK::Rect::y1, #kWindowHeaderHeight - 1
COPY_STRUCT MGTK::Point, viewport+MGTK::Rect::topleft, old
sub16 viewport+MGTK::Rect::x2, viewport+MGTK::Rect::x1, width
sub16 viewport+MGTK::Rect::y2, viewport+MGTK::Rect::y1, height
lda cached_window_entry_count
IF_ZERO
;; If no icons in window, the viewport is fine.
COPY_STRUCT MGTK::Rect, viewport, ubox
rts
END_IF
;; Make `ubox` bound both viewport and icons; needed to ensure
;; offset cases are handled.
jsr CachedIconsScreenToWindow
jsr ComputeIconsBBox
jsr CachedIconsWindowToScreen
MGTK_CALL MGTK::UnionRects, unionrects_viewport_iconbb
COPY_BLOCK iconbb_rect, ubox
rts
;;; --------------------------------------------------
;;; When arrow increment is clicked:
;;; 1. vp.hi += tick
;;; 2. goto _Clamp_hi
.proc ArrowRight
jsr _Preamble
add16_8 viewport+MGTK::Rect::x2, tick_h
jmp _Clamp_x2
.endproc ; ArrowRight
.proc ArrowDown
jsr _Preamble
add16_8 viewport+MGTK::Rect::y2, tick_v
jmp _Clamp_y2
.endproc ; ArrowDown
;;; --------------------------------------------------
;;; When arrow decrement is clicked:
;;; 1. vp.lo -= tick
;;; 2. goto _Clamp_lo
.proc ArrowLeft
jsr _Preamble
sub16_8 viewport+MGTK::Rect::x1, tick_h
jmp _Clamp_x1
.endproc ; ArrowLeft
.proc ArrowUp
jsr _Preamble
sub16_8 viewport+MGTK::Rect::y1, tick_v
jmp _Clamp_y1
.endproc ; ArrowUp
;;; --------------------------------------------------
;;; When page increment area is clicked:
;;; 1. vp.hi += size
;;; 2. goto _Clamp_hi
.proc PageRight
jsr _Preamble
add16 viewport+MGTK::Rect::x2, width, viewport+MGTK::Rect::x2
jmp _Clamp_x2
.endproc ; PageRight
.proc PageDown
jsr _Preamble
add16_8 viewport+MGTK::Rect::y2, height
jmp _Clamp_y2
.endproc ; PageDown
;;; --------------------------------------------------
;;; When page decrement area is clicked:
;;; 1. vp.lo -= size
;;; 2. goto _Clamp_lo
.proc PageLeft
jsr _Preamble
sub16 viewport+MGTK::Rect::x1, width, viewport+MGTK::Rect::x1
jmp _Clamp_x1
.endproc ; PageLeft
.proc PageUp
jsr _Preamble
sub16_8 viewport+MGTK::Rect::y1, height
jmp _Clamp_y1
.endproc ; PageUp
;;; --------------------------------------------------
;;; When thumb is moved by user:
;;; 1. vp.lo = ubox.lo + (ubox.hi - ubox.lo - size) * (newpos / thumb.max)
;;; 2. vp.hi = vp.lo + size
;;; 3. goto update
.proc TrackHThumb
jsr _Preamble
sub16 ubox+MGTK::Rect::x2, ubox+MGTK::Rect::x1, tmpw
sub16 tmpw, width, track_muldiv_params::number
jsr _TrackMulDiv
add16 track_muldiv_params::result, ubox+MGTK::Rect::x1, viewport+MGTK::Rect::x1
add16 viewport+MGTK::Rect::x1, width, viewport+MGTK::Rect::x2
jmp _MaybeUpdateHThumb
.endproc ; TrackHThumb
.proc TrackVThumb
jsr _Preamble
sub16 ubox+MGTK::Rect::y2, ubox+MGTK::Rect::y1, tmpw
sub16 tmpw, height, track_muldiv_params::number
jsr _TrackMulDiv
add16 track_muldiv_params::result, ubox+MGTK::Rect::y1, viewport+MGTK::Rect::y1
add16 viewport+MGTK::Rect::y1, height, viewport+MGTK::Rect::y2
jmp _MaybeUpdateVThumb
.endproc ; TrackVThumb
.proc _TrackMulDiv
copy8 trackthumb_params::thumbpos, track_muldiv_params::numerator
MGTK_CALL MGTK::MulDiv, track_muldiv_params
rts
.endproc ; _TrackMulDiv
;;; --------------------------------------------------
;;; _Clamp_hi:
;;; 1. if vp.hi > ubox.hi: vp.hi = ubox.hi
;;; 2. vp.lo = vp.hi - size
;;; 3. goto update
.proc _Clamp_hi
scmp16 viewport+MGTK::Rect::bottomright,x, ubox+MGTK::Rect::bottomright,x
IF_POS
copy16 ubox+MGTK::Rect::bottomright,x, viewport+MGTK::Rect::bottomright,x
END_IF
sub16 viewport+MGTK::Rect::bottomright,x, dimensions,x, viewport+MGTK::Rect::topleft,x
rts
.endproc ; _Clamp_hi
.proc _Clamp_x2
ldx #0
jsr _Clamp_hi
jmp _MaybeUpdateHThumb
.endproc ; _Clamp_x2
.proc _Clamp_y2
ldx #2
jsr _Clamp_hi
jmp _MaybeUpdateVThumb
.endproc ; _Clamp_y2
;;; --------------------------------------------------
;;; _Clamp_lo:
;;; 1. if vp.lo < ubox.lo: vp.lo = ubox.lo
;;; 2. vp.hi = vp.lo + size
;;; 3. goto update
.proc _Clamp_lo
scmp16 viewport+MGTK::Rect::topleft,x, ubox+MGTK::Rect::topleft,x
IF_NEG
copy16 ubox+MGTK::Rect::topleft,x, viewport+MGTK::Rect::topleft,x
END_IF
add16 viewport+MGTK::Rect::topleft,x, dimensions,x, viewport+MGTK::Rect::bottomright,x
rts
.endproc ; _Clamp_lo
.proc _Clamp_x1
ldx #0
jsr _Clamp_lo
jmp _MaybeUpdateHThumb
.endproc ; _Clamp_x1
.proc _Clamp_y1
ldx #2
jsr _Clamp_lo
jmp _MaybeUpdateVThumb
.endproc ; _Clamp_y1
;;; --------------------------------------------------
;;; Following above gestures, determine if the viewport
;;; has changed and if so update the thumb.
;;;
;;; 1. if vp.lo != old:
;;; 1. newpos = (vp.lo - ubox.lo) / (ubox.hi - ubox.lo - size) * thumb.max
;;; 2. if newpos != thumb.pos: update thumb
;;; 3. redraw
.proc _MaybeUpdateHThumb
ecmp16 viewport+MGTK::Rect::x1, old+MGTK::Point::xcoord
IF_NE
jsr _SetHThumbFromViewport
jsr _UpdateViewport
jsr ClearAndDrawActiveWindowEntries
;; Handle offset case - may be able to deactivate scrollbar now
jsr _Preamble ; Need updated `ubox` and `maprect`
scmp16 ubox+MGTK::Rect::x1, viewport+MGTK::Rect::x1
IF_POS
scmp16 viewport+MGTK::Rect::x2, ubox+MGTK::Rect::x2
IF_POS
ldx #MGTK::Ctl::horizontal_scroll_bar
lda #MGTK::activatectl_deactivate
jsr _ActivateCtl
END_IF
END_IF
END_IF
rts
.endproc ; _MaybeUpdateHThumb
.proc _MaybeUpdateVThumb
ecmp16 viewport+MGTK::Rect::y1, old+MGTK::Point::ycoord
IF_NE
jsr _SetVThumbFromViewport
jsr _UpdateViewport
jsr ClearAndDrawActiveWindowEntries
;; Handle offset case - may be able to deactivate scrollbar now
jsr _Preamble ; Need updated `ubox` and `maprect`
scmp16 ubox+MGTK::Rect::y1, viewport+MGTK::Rect::y1
IF_POS
scmp16 viewport+MGTK::Rect::y2, ubox+MGTK::Rect::y2
IF_POS
ldx #MGTK::Ctl::vertical_scroll_bar
lda #MGTK::activatectl_deactivate
jsr _ActivateCtl
END_IF
END_IF
END_IF
rts
.endproc ; _MaybeUpdateVThumb
;;; Set hthumb position relative to `maprect` and `ubox`.
.proc _SetHThumbFromViewport
sub16 viewport+MGTK::Rect::x1, ubox+MGTK::Rect::x1, setthumb_muldiv_params::number
sub16 ubox+MGTK::Rect::x2, ubox+MGTK::Rect::x1, tmpw
sub16 tmpw, width, setthumb_muldiv_params::denominator
MGTK_CALL MGTK::MulDiv, setthumb_muldiv_params
lda setthumb_muldiv_params::result
ldx #MGTK::Ctl::horizontal_scroll_bar
jmp _UpdateThumb
.endproc ; _SetHThumbFromViewport
;;; Set vthumb position relative to `maprect` and `ubox`.
.proc _SetVThumbFromViewport
sub16 viewport+MGTK::Rect::y1, ubox+MGTK::Rect::y1, setthumb_muldiv_params::number
sub16 ubox+MGTK::Rect::y2, ubox+MGTK::Rect::y1, tmpw
sub16 tmpw, height, setthumb_muldiv_params::denominator
MGTK_CALL MGTK::MulDiv, setthumb_muldiv_params
lda setthumb_muldiv_params::result
ldx #MGTK::Ctl::vertical_scroll_bar
jmp _UpdateThumb
.endproc ; _SetVThumbFromViewport
;;; --------------------------------------------------
;;; Apply `maprect` back to active window's GrafPort
.proc _UpdateViewport
;; Restore header to viewport
sub16_8 viewport+MGTK::Rect::y1, #kWindowHeaderHeight - 1
jmp AssignActiveWindowCliprectAndUpdateCachedIcons
.endproc ; _UpdateViewport
;;; --------------------------------------------------
;;; Check contents against window size, and activate/deactivate
;;; horizontal and vertical scrollbars as needed.
.proc ActivateCtlsSetThumbs
jsr _Preamble
scmp16 ubox+MGTK::Rect::x1, viewport+MGTK::Rect::x1
bmi activate_hscroll
scmp16 viewport+MGTK::Rect::x2, ubox+MGTK::Rect::x2
bmi activate_hscroll
;; deactivate horizontal scrollbar
ldx #MGTK::Ctl::horizontal_scroll_bar
lda #MGTK::activatectl_deactivate
jsr _ActivateCtl
jmp check_vscroll
activate_hscroll:
;; activate horizontal scrollbar
ldx #MGTK::Ctl::horizontal_scroll_bar
lda #MGTK::activatectl_activate
jsr _ActivateCtl
jsr _SetHThumbFromViewport
FALL_THROUGH_TO check_vscroll
;; --------------------------------------------------
check_vscroll:
scmp16 ubox+MGTK::Rect::y1, viewport+MGTK::Rect::y1
bmi activate_vscroll
scmp16 viewport+MGTK::Rect::y2, ubox+MGTK::Rect::y2
bmi activate_vscroll
;; deactivate vertical scrollbar
ldx #MGTK::Ctl::vertical_scroll_bar
lda #MGTK::activatectl_deactivate
jmp _ActivateCtl
activate_vscroll:
;; activate vertical scrollbar
ldx #MGTK::Ctl::vertical_scroll_bar
lda #MGTK::activatectl_activate
jsr _ActivateCtl
jmp _SetVThumbFromViewport
.endproc ; ActivateCtlsSetThumbs
;;; --------------------------------------------------
;;; Inputs: A=activate/deactivate, X=which_ctl
.proc _ActivateCtl
stx activatectl_params::which_ctl
sta activatectl_params::activate
MGTK_CALL MGTK::ActivateCtl, activatectl_params
rts
.endproc ; _ActivateCtl
;;; --------------------------------------------------
;;; Inputs: A=thumbpos, X=which_ctl
.proc _UpdateThumb
sta updatethumb_params::thumbpos
stx updatethumb_params::which_ctl
MGTK_CALL MGTK::UpdateThumb, updatethumb_params
rts
.endproc ; _UpdateThumb
.endscope ; ScrollManager
;;; Handle scroll gestures
ScrollLeft := ScrollManager::ArrowLeft
ScrollUp := ScrollManager::ArrowUp
ScrollRight := ScrollManager::ArrowRight
ScrollDown := ScrollManager::ArrowDown
ScrollPageLeft := ScrollManager::PageLeft
ScrollPageUp := ScrollManager::PageUp
ScrollPageRight := ScrollManager::PageRight
ScrollPageDown := ScrollManager::PageDown
ScrollTrackHThumb := ScrollManager::TrackHThumb
ScrollTrackVThumb := ScrollManager::TrackVThumb
;;; Update the scrollbar activation state and thumb positions for
;;; both horizontal and vertical scrollbars, based on the window's
;;; viewport and contents.
ScrollUpdate := ScrollManager::ActivateCtlsSetThumbs
;;; ============================================================
.proc CmdCheckAllDrives
;; Enumerate DEVLST in reverse order (most important volumes first)
ldx DEVCNT ; X = index
DO
txa ; A = index
pha
ldy #$80 ; Y = show unexpected errors flag (do)
jsr CheckDriveByIndex ; A = DEVLST index
pla ; A = index
tax ; X = index
dex
WHILE_POS
rts
.endproc ; CmdCheckAllDrives
;;; ============================================================
pending_alert:
.byte 0
;;; ============================================================
;;; Check > [drive] command - obsolete, but core still used
;;; following Format (etc)
;;;
.proc CheckDriveImpl
;;; --------------------------------------------------
;;; After a Format/Erase action
;;; Input: A = unit number, Y = show unexpected errors flag
by_unit_number:
;; Map unit number to index in DEVLST
sta compare
ldx DEVCNT
DO
lda DEVLST,x
and #UNIT_NUM_MASK
compare := *+1
cmp #SELF_MODIFIED_BYTE
beq common
dex
WHILE_POS ; always
;;; --------------------------------------------------
;;; After an Open/Eject/Rename action
;;; Input: A = icon id, Y = show unexpected errors flag
by_icon_number:
;; Map icon number to index in DEVLST
jsr IconToDeviceIndex
RTS_IF_NOT_ZERO ; Not found - not a volume icon
beq common ; always
;;; --------------------------------------------------
;;; After polling drives
;;; Input: A = DEVLST index, Y = show unexpected errors flag
by_index:
tax ; X = index
FALL_THROUGH_TO common
;;; --------------------------------------------------
common:
stx devlst_index
sty show_unexpected_errors_flag
;; --------------------------------------------------
;; Close any associated windows
lda device_to_icon_map,x
IF_NOT_ZERO
;; A = icon number
jsr GetIconName
stax $06
path_buf := $1F00
;; Copy volume path to $1F00
param_call CopyPtr1ToBuf, path_buf+1
;; Find all windows with path as prefix, and close them.
sta path_buf
inc path_buf
copy8 #'/', path_buf+1
close_loop:
;; NOTE: This is called within loop because the list
;; (`found_windows_count` / `found_windows_list`) is trashed
;; during close when animating window.
param_call FindWindowsForPrefix, path_buf
ldx found_windows_count
IF_NOT_ZERO
lda found_windows_list-1,x
jsr CloseSpecifiedWindow
jmp close_loop
END_IF
END_IF
;; --------------------------------------------------
;; If there was an existing icon, destroy it
jsr ClearSelection
jsr LoadDesktopEntryTable
ldy devlst_index
copy8 device_to_icon_map,y, icon_param
IF_NOT_ZERO
jsr RemoveIconFromWindow
dec icon_count
lda icon_param
jsr FreeDesktopIconPosition
ITK_CALL IconTK::EraseIcon, icon_param
ITK_CALL IconTK::FreeIcon, icon_param
jsr StoreWindowEntryTable
END_IF
;; --------------------------------------------------
;; Try to create a new volume icon
ldy devlst_index
lda DEVLST,y
;; NOTE: Not masked with `UNIT_NUM_MASK`, for `CreateVolumeIcon`.
jsr CreateVolumeIcon ; A = unmasked unit num, Y = device index
IF_ZERO
ldx cached_window_entry_count
copy8 cached_window_entry_list-1,x, icon_param
ITK_CALL IconTK::DrawIcon, icon_param
jmp StoreWindowEntryTable
END_IF
;; --------------------------------------------------
;; Error cases:
;; Always show this error
cmp #ERR_DUPLICATE_VOLUME
beq show_error
;; Per Technical Note: ProDOS #21
;; https://prodos8.com/docs/technote/21/
;; `ERR_DEVICE_OFFLINE`: "... there is no disk in the drive."
;; ... so ignore
cmp #ERR_DEVICE_OFFLINE
beq ret
;; `ERR_IO_ERROR`: "... the disk in the drive is either
;; damaged or blank (not formatted)." - but this seems to be
;; returned for empty Disk II and SmartPort devices, so we
;; ignore it.
cmp #ERR_IO_ERROR
beq ret
IF_A_EQ #ERR_NOT_PRODOS_VOLUME
param_call ShowAlertParams, AlertButtonOptions::OKCancel, aux::str_alert_unreadable_format
cmp #kAlertResultCancel
beq ret
ldy devlst_index
lda DEVLST,y
and #UNIT_NUM_MASK
jmp FormatUnitNum
END_IF
;; Show an alert for other errors only if requested by the
;; caller. The history here is that an error should only be
;; shown if there is an unexpected type of error (i.e. not one
;; of the above) when polling or as explicit command
;; (originally Check > Slot S drive D).
bit show_unexpected_errors_flag
bmi show_error
ret: rts
;; --------------------------------------------------
show_error:
jmp ShowAlert
;; --------------------------------------------------
devlst_index:
.byte 0
show_unexpected_errors_flag:
.byte 0
.endproc ; CheckDriveImpl
CheckDriveByIndex := CheckDriveImpl::by_index
CheckDriveByUnitNumber := CheckDriveImpl::by_unit_number
CheckDriveByIconNumber := CheckDriveImpl::by_icon_number
;;; ============================================================
.proc CmdStartupItem
ldx menu_click_params::item_num
lda startup_slot_table-1,x
ora #>$C000 ; compute $Cn00
sta reset_and_invoke_target+1
lda #<$C000
sta reset_and_invoke_target
FALL_THROUGH_TO ResetAndInvoke
.endproc ; CmdStartupItem
;; also invoked by launcher code
.proc ResetAndInvoke
;; Restore system state: devices, /RAM, ROM/ZP banks.
jsr RestoreSystem
;; also used by launcher code
target := *+1
jmp SELF_MODIFIED
.endproc ; ResetAndInvoke
reset_and_invoke_target := ResetAndInvoke::target
;;; ============================================================
.proc CmdMakeLinkImpl
;;; Param block written out as new link file
PARAM_BLOCK link_struct, $800
sig1 .byte
sig2 .byte
ver .byte
path .byte
END_PARAM_BLOCK
header: .byte kLinkFileSig1Value, kLinkFileSig2Value, kLinkFileCurrentVersion
kHeaderSize = * - header
.define kAliasSuffix ".alias"
suffix: .byte kAliasSuffix
DEFINE_CREATE_PARAMS create_params, dst_path_buf, ACCESS_DEFAULT, FT_LINK, kLinkFileAuxType
DEFINE_OPEN_PARAMS open_params, dst_path_buf, IO_BUFFER
DEFINE_READWRITE_PARAMS write_params, link_struct, 0
DEFINE_CLOSE_PARAMS close_params
;; --------------------------------------------------
;; Stash target directory name
;;; Entry point where selection's window is used as target path
target_selection:
jsr GetSelectionWindow
jsr GetWindowPath
jsr CopyToBuf4
;;; Entry point where caller sets `path_buf4`
arbitrary_target:
;; --------------------------------------------------
;; Prep struct for writing
lda selected_icon_list
jsr GetIconPath ; `path_buf3` set to path; A=0 on success
jne ShowAlert ; too long
ldx #kHeaderSize-1
DO
copy8 header,x, link_struct,x
dex
WHILE_POS
COPY_STRING path_buf3, link_struct::path
lda link_struct::path
clc
adc #link_struct::path-link_struct+1
sta write_params::request_count
;; --------------------------------------------------
;; Determine the name to use
;; Start with original name
lda selected_icon_list
jsr GetIconName
stax $06
param_call CopyPtr1ToBuf, stashed_name
;; Append ".alias"
lda stashed_name
clc
adc #.strlen(kAliasSuffix)
IF_A_GE #kMaxFilenameLength+1
lda #kMaxFilenameLength
END_IF
tax
sta stashed_name
ldy #.strlen(kAliasSuffix)-1
DO
copy8 suffix,y, stashed_name,x
dex
dey
WHILE_POS
;; Repeat to find a free name
retry: param_call CopyToDstPath, path_buf4
param_call AppendFilenameToDstPath, stashed_name
jsr GetDstFileInfo
IF_CS
cmp #ERR_FILE_NOT_FOUND
beq create
bne err
END_IF
jsr SpinName
jmp retry
;; --------------------------------------------------
;; Create and write link file
create:
MLI_CALL CREATE, create_params
bcs err
MLI_CALL OPEN, open_params
bcs err
lda open_params::ref_num
sta write_params::ref_num
sta close_params::ref_num
MLI_CALL WRITE, write_params
php
MLI_CALL CLOSE, close_params
plp
bcs err
;; Update name case bits on disk, if possible.
param_call CopyToSrcPath, dst_path_buf
jsr ApplyCaseBits ; applies `stashed_name` to `src_path_buf`
;; --------------------------------------------------
;; Update cached used/free for all same-volume windows, and refresh
param_call UpdateUsedFreeViaPath, dst_path_buf
jsr ShowFileWithPath
RTS_IF_CS
;; Select and rename the file
jmp TriggerRenameForFileIconWithStashedName
;; --------------------------------------------------
err: jmp ShowAlert
.endproc ; CmdMakeLinkImpl
CmdMakeLink := CmdMakeLinkImpl::target_selection
MakeLinkInTarget := CmdMakeLinkImpl::arbitrary_target
;;; ============================================================
.proc CmdShowLink
;; Assert: single LNK file icon selected
jsr GetSingleSelectedIcon
jsr GetIconPath ; `path_buf3` set to path, A=0 on success
bne alert ; too long
param_call CopyToSrcPath, path_buf3
jsr ReadLinkFile
RTS_IF_CS
;; File or volume?
param_call FindLastPathSegment, src_path_buf ; point Y at last '/'
cpy src_path_buf
jne ShowFileWithPath
;; Volume
param_call FindIconForPath, src_path_buf
jne SelectIconAndEnsureVisible
lda #ERR_VOL_NOT_FOUND
alert: jmp ShowAlert
.endproc ; CmdShowLink
;;; ============================================================
;;; Given a window, update used/free data for all same-volume windows,
;;; then activate the window (if needed) and refresh the contents
;;; (closing on error).
;;; Same inputs/outputs as `ActivateAndRefreshWindowOrClose`
.proc UpdateActivateAndRefreshSelectedWindow
lda selected_window_id
FALL_THROUGH_TO UpdateActivateAndRefreshWindow
.endproc ; UpdateActivateAndRefreshSelectedWindow
.proc UpdateActivateAndRefreshWindow
pha
jsr GetWindowPath ; into A,X
jsr UpdateUsedFreeViaPath
pla
jmp ActivateAndRefreshWindowOrClose
.endproc ; UpdateActivateAndRefreshWindow
;;; ============================================================
;;; Input: A = icon id
;;; NOTE: It does not activate the icon's window, or scroll the icon
;;; into view.
.proc SelectIcon
pha
jsr ClearSelection
pla
pha
jsr GetIconWindow
sta selected_window_id
pla
FALL_THROUGH_TO AddIconToSelection
.endproc ; SelectIcon
;;; ============================================================
;;; Add specified icon to selection list, mark it highlighted, and redraw.
;;; NOTE: This increments `selected_icon_count` and does NOT change
;;; `selected_window_id`
;;; Input: A = icon number
;;; Assert: Icon is in active window/desktop, `selected_window_id` is set.
.proc AddIconToSelection
sta icon_param
ITK_CALL IconTK::HighlightIcon, icon_param
ITK_CALL IconTK::DrawIcon, icon_param
lda icon_param
FALL_THROUGH_TO AddToSelectionList
.endproc ; AddIconToSelection
;;; ============================================================
;;; Add specified icon to `selected_icon_list`
;;; Inputs: A = icon_num
;;; Outputs: A is not modified
;;; Assert: icon is not present in the list.
;;; NOTE: Does not modify `selected_window_id`.
.proc AddToSelectionList
ldx selected_icon_count
sta selected_icon_list,x
inc selected_icon_count
rts
.endproc ; AddToSelectionList
;;; ============================================================
;;; Remove specified icon from selection list, and redraw.
;;; Input: A = icon number
;;; Assert: Must be in selection list.
.proc UnhighlightAndDeselectIcon
sta icon_param
ITK_CALL IconTK::UnhighlightIcon, icon_param
ITK_CALL IconTK::DrawIcon, icon_param
lda icon_param
FALL_THROUGH_TO RemoveFromSelectionList
.endproc ; UnhighlightAndDeselectIcon
;;; ============================================================
;;; Remove specified icon from `selected_icon_list`
;;; Inputs: A = icon_num
;;; Assert: icon is present in the list.
;;; NOTE: Clears `selected_window_id` if count drops to 0.
.proc RemoveFromSelectionList
;; Find index in list
ldx selected_icon_count
DO
dex
WHILE_A_NE selected_icon_list,x
;; Move everything down
DO
copy8 selected_icon_list+1,x, selected_icon_list,x
inx
WHILE_X_NE selected_icon_count
dec selected_icon_count
IF_ZERO
copy8 #0, selected_window_id
END_IF
rts
.endproc ; RemoveFromSelectionList
;;; ============================================================
;;; Calls `ActivateAndRefreshWindow` - on failure (e.g. too
;;; many files) the window is closed.
;;; Input: A = window id
;;; Output: A=0/Z=1/N=0 on success, A=$FF/Z=0/N=1 on failure
.proc ActivateAndRefreshWindowOrClose
pha ; A = window id
jsr _TryActivateAndRefreshWindow
pla ; A = window id
bit exception_flag
IF_NC
return #0
END_IF
inc num_open_windows ; was decremented on failure
jsr CloseSpecifiedWindow ; A = window id
return #$FF
.proc _TryActivateAndRefreshWindow
SET_BIT7_FLAG exception_flag ; set bit7, preserving A
tsx
stx saved_stack
jsr ActivateAndRefreshWindow
CLEAR_BIT7_FLAG exception_flag ; clear bit7, preserving A
rts
.endproc ; _TryActivateAndRefreshWindow
exception_flag:
.byte 0
.endproc ; ActivateAndRefreshWindowOrClose
;;; ============================================================
.proc ActivateAndRefreshWindow
pha ; A = window_id
;; Clear selection
jsr ClearSelection
;; Bring window to front if needed
pla ; A = window_id
IF_A_NE active_window_id
sta active_window_id
MGTK_CALL MGTK::SelectWindow, active_window_id
END_IF
;; Clear background
lda active_window_id
jsr UnsafeSetPortFromWindowId ; CHECKED
pha ; A = obscured?
IF_ZERO ; skip if obscured
MGTK_CALL MGTK::PaintRect, window_grafport+MGTK::GrafPort::maprect
END_IF
;; Remove old FileRecords
lda active_window_id
pha ; A = `active_window_id`
jsr RemoveWindowFileRecords
;; Remove old icons
jsr LoadActiveWindowEntryTable
jsr RemoveAndFreeCachedWindowIcons
jsr ClearActiveWindowEntryCount
;; Copy window path to `src_path_buf`
pla ; A = `active_window_id`
pha ; A = `active_window_id`
jsr GetWindowPath
jsr CopyToSrcPath
;; Load new FileRecords
pla ; A = `active_window_id`
jsr CreateFileRecordsForWindow
;; Draw header
jsr UpdateWindowUsedFreeDisplayValues
pla ; A = obscured?
IF_ZERO ; skip if obscured
jsr LoadActiveWindowEntryTable
jsr DrawWindowHeader
END_IF
;; Create icons and draw contents
jmp RefreshView
.endproc ; ActivateAndRefreshWindow
;;; ============================================================
;;; Drag Selection
;;; Inputs: A = window_id (0 for desktop)
;;; Assert: `cached_window_id` == A
.proc DragSelect
PARAM_BLOCK, $10
window_id .byte ; 0 = desktop, assumed to be active otherwise
delta .tag MGTK::Point
initial_pos .tag MGTK::Point
last_pos .tag MGTK::Point
END_PARAM_BLOCK
sta window_id
jsr LoadWindowEntryTable
lda window_id
IF_NOT_ZERO
;; Map initial event coordinates
jsr _CoordsScreenToWindow
END_IF
;; Stash initial coords
ldx #.sizeof(MGTK::Point)-1
DO
lda event_params::coords,x
sta tmp_rect::topleft,x
sta tmp_rect::bottomright,x
sta initial_pos,x
dex
WHILE_POS
;; Is this actually a drag?
jsr PeekEvent
lda event_params::kind
IF_A_NE #MGTK::EventKind::drag
;; No, just a click; optionally clear selection
jsr ExtendSelectionModifierDown
jpl ClearSelection ; don't clear if mis-clicking
rts
END_IF
;; --------------------------------------------------
;; Prep selection
lda window_id
cmp selected_window_id
bne clear
jsr ExtendSelectionModifierDown
bmi :+
clear: jsr ClearSelection
:
;; --------------------------------------------------
;; Set up drawing port, draw initial rect
lda window_id
IF_NOT_ZERO
jsr UnsafeSetPortFromWindowIdAndAdjustForEntries ; ASSERT: not obscured
ELSE
jsr InitSetDesktopPort
END_IF
jsr FrameTmpRect
;; --------------------------------------------------
;; Event loop
event_loop:
;; Done the drag?
jsr PeekEvent
lda event_params::kind
IF_A_NE #MGTK::EventKind::drag
jsr FrameTmpRect
;; Process all icons in window
ldx #0 ; X = index
DO
RTS_IF_X_EQ cached_window_entry_count
txa
pha ; A = index
;; Check if icon should be selected
copy8 cached_window_entry_list,x, icon_param
lda window_id
IF_NOT_ZERO
lda icon_param
jsr IconScreenToWindow
END_IF
ITK_CALL IconTK::IconInRect, icon_param
beq done_icon
;; Already selected?
lda icon_param
jsr IsIconSelected
IF_NE
;; Highlight and add to selection
;; NOTE: Does not use `AddIconToSelection` because we perform
;; a more optimized drawing below.
ITK_CALL IconTK::HighlightIcon, icon_param
lda icon_param
jsr AddToSelectionList
copy8 window_id, selected_window_id
ELSE
;; Unhighlight and remove from selection
ITK_CALL IconTK::UnhighlightIcon, icon_param
lda icon_param
jsr RemoveFromSelectionList
END_IF
lda window_id
IF_ZERO
ITK_CALL IconTK::DrawIcon, icon_param
ELSE
ITK_CALL IconTK::DrawIconRaw, icon_param ; CHECKED (drag select)
END_IF
done_icon:
lda window_id
IF_NOT_ZERO
lda icon_param
jsr IconWindowToScreen
END_IF
pla ; A = index
tax ; X = index
inx
WHILE_NOT_ZERO ; always
END_IF
;; --------------------------------------------------
;; Check movement threshold
lda window_id
IF_NOT_ZERO
jsr _CoordsScreenToWindow
END_IF
ldx #2 ; loop over dimensions
DO
sub16 event_params::coords,x, last_pos,x, delta,x
lda delta+1,x
IF_NEG
lda delta,x ; negate
eor #$FF
sta delta,x
inc delta,x
END_IF
;; TODO: Experiment with making this lower.
kDragBoundThreshold = 5
lda delta,x
cmp #kDragBoundThreshold
bcs beyond
dex ; next dimension
dex
WHILE_POS
jmp event_loop
;; Beyond threshold; erase rect
beyond:
jsr FrameTmpRect
COPY_STRUCT event_params::coords, last_pos
;; --------------------------------------------------
;; Figure out coords for rect's left/top/bottom/right
ldx #2 ; loop over dimensions
DO
scmp16 event_params::coords,x, initial_pos,x
IF_NEG
copy16 event_params::coords,x, tmp_rect::topleft,x
copy16 initial_pos,x, tmp_rect::bottomright,x
ELSE
copy16 initial_pos,x, tmp_rect::topleft,x
copy16 event_params::coords,x, tmp_rect::bottomright,x
END_IF
dex ; next dimension
dex
WHILE_POS
jsr FrameTmpRect
jmp event_loop
.proc _CoordsScreenToWindow
jsr PushPointers
jsr PrepActiveWindowScreenMapping
;; Point at an imaginary `IconEntry`, to map
;; `event_params::coords` from screen to window.
ldax #(event_params::coords - IconEntry::iconx)
jsr IconPtrScreenToWindow
jsr PopPointers ; do not tail-call optimise!
rts
.endproc ; _CoordsScreenToWindow
.endproc ; DragSelect
;;; ============================================================
;;; Initiate keyboard-based window moving
.proc CmdMove
MGTK_CALL MGTK::KeyboardMouse
FALL_THROUGH_TO DoWindowDrag
.endproc ; CmdMove
;;; ============================================================
.proc DoWindowDrag
copy8 active_window_id, dragwindow_params::window_id
jsr LoadActiveWindowEntryTable
jsr CachedIconsScreenToWindow
MGTK_CALL MGTK::DragWindow, dragwindow_params
;; `dragwindow_params::moved` is not checked; harmless if it didn't.
jmp CachedIconsWindowToScreen
.endproc ; DoWindowDrag
;;; ============================================================
;;; Initiate keyboard-based resizing
.proc CmdResize
MGTK_CALL MGTK::KeyboardMouse
FALL_THROUGH_TO DoWindowResize
.endproc ; CmdResize
;;; ============================================================
.proc DoWindowResize
copy8 active_window_id, event_params
MGTK_CALL MGTK::GrowWindow, event_params
jmp ScrollUpdate
.endproc ; DoWindowResize
;;; ============================================================
.proc HandleCloseClick
lda active_window_id
MGTK_CALL MGTK::TrackGoAway, trackgoaway_params
lda trackgoaway_params::goaway
RTS_IF_ZERO
;; If modifier is down, close all windows
jsr ModifierDown
jmi CmdCloseAll
FALL_THROUGH_TO CloseActiveWindow
.endproc ; HandleCloseClick
;;; Close the active window
.proc CloseActiveWindow
lda active_window_id
FALL_THROUGH_TO CloseSpecifiedWindow
.endproc ; CloseActiveWindow
;;; Inputs: A = window_id
.proc CloseSpecifiedWindow
icon_ptr := $06
jsr LoadWindowEntryTable
jsr ClearSelection
jsr RemoveAndFreeCachedWindowIcons
dec num_open_windows
jsr ClearAndStoreCachedWindowEntryTable
MGTK_CALL MGTK::CloseWindow, cached_window_id
;; --------------------------------------------------
;; Do we have a parent icon for this window?
lda #0
ldx cached_window_id
ldy window_to_dir_icon_table-1,x
IF_NC ; is not `kWindowToDirIconNone`
tya
END_IF
sta icon
;; --------------------------------------------------
;; Animate closing
lda cached_window_id
jsr GetWindowPath
jsr IconToAnimate
pha ; A = animation icon
ldx cached_window_id
jsr AnimateWindowClose ; A = icon id, X = window id
;; --------------------------------------------------
;; Tidy up after closing window
lda cached_window_id
jsr RemoveWindowFileRecords
ldx cached_window_id
ASSERT_EQUALS ::kWindowToDirIconFree, 0
ASSERT_EQUALS DeskTopSettings::kViewByIcon, 0
copy8 #0, window_to_dir_icon_table-1,x ; `kWindowToDirIconFree`
;; Was it the active window?
lda cached_window_id
IF_A_EQ active_window_id
;; Yes, record the new one
MGTK_CALL MGTK::FrontWindow, active_window_id
END_IF
jsr ClearUpdates ; following CloseWindow above
;; --------------------------------------------------
;; Clean up the parent icon (if any)
icon := *+1
lda #SELF_MODIFIED_BYTE
IF_NE
jsr MarkIconNotDimmedNoDraw
;; Assert: `icon` == `anim_icon`, and will get redrawn next.
END_IF
;; --------------------------------------------------
;; Select the ancestor icon that was animated into
pla ; A = animation icon
jmp SelectIcon
.endproc ; CloseSpecifiedWindow
;;; ============================================================
;;; Check windows and close any where the backing volume/file no
;;; longer exists.
;;; Set bit7 to run a validation pass and close as needed.
validate_windows_flag:
.byte 0
.proc ValidateWindows
bit validate_windows_flag
IF_NS
CLEAR_BIT7_FLAG validate_windows_flag
copy8 #kMaxDeskTopWindows, window_id
DO
;; Check if the window is in use
window_id := *+1
ldx #SELF_MODIFIED_BYTE
lda window_to_dir_icon_table-1,x
IF_NOT_ZERO ; isn't `kWindowToDirIconFree`
;; Get and copy its path somewhere useful
txa
jsr GetWindowPath
jsr CopyToSrcPath
;; See if it exists
jsr GetSrcFileInfo
IF_CS
;; Nope - close the window
lda window_id
jsr CloseSpecifiedWindow
END_IF
END_IF
dec window_id
WHILE_NOT_ZERO
END_IF
rts
.endproc ; ValidateWindows
;;; ============================================================
.proc ApplyActiveWinfoToWindowGrafport
lda active_window_id
FALL_THROUGH_TO ApplyWinfoToWindowGrafport
.endproc ; ApplyActiveWinfoToWindowGrafport
.proc ApplyWinfoToWindowGrafport
ptr := $06
jsr GetWindowPtr
addax #MGTK::Winfo::port, ptr
ldy #.sizeof(MGTK::GrafPort) - 1
DO
copy8 (ptr),y, window_grafport,y
dey
WHILE_POS
rts
.endproc ; ApplyWinfoToWindowGrafport
;;; NOTE: Does not update icon positions, so only use in empty windows.
.proc ResetActiveWindowViewport
jsr ApplyActiveWinfoToWindowGrafport
ldx #2 ; loop over dimensions
DO
viewport := window_grafport+MGTK::GrafPort::maprect
sub16 viewport+MGTK::Rect::bottomright,x, viewport+MGTK::Rect::topleft,x, viewport+MGTK::Rect::bottomright,x
copy16 #0, viewport+MGTK::Rect::topleft,x
dex ; next dimension
dex
WHILE_POS
FALL_THROUGH_TO AssignActiveWindowCliprect
.endproc ; ResetActiveWindowViewport
.proc AssignActiveWindowCliprect
ptr := $6
lda active_window_id
jsr GetWindowPtr
stax ptr
ldy #MGTK::Winfo::port + MGTK::GrafPort::maprect + .sizeof(MGTK::Rect)-1
ldx #.sizeof(MGTK::Rect)-1
DO
copy8 window_grafport+MGTK::GrafPort::maprect,x, (ptr),y
dey
dex
WHILE_POS
rts
.endproc ; AssignActiveWindowCliprect
.proc AssignActiveWindowCliprectAndUpdateCachedIcons
jsr CachedIconsScreenToWindow
jsr AssignActiveWindowCliprect
jmp CachedIconsWindowToScreen
.endproc ; AssignActiveWindowCliprectAndUpdateCachedIcons
;;; ============================================================
;;; If there's a single icon selected, return it. Otherwise,
;;; return zero.
;;; Z=0 and A=icon num if only one, Z=0 and A=0 otherwise
.proc GetSingleSelectedIcon
lda selected_icon_count
IF_A_NE #1
lda #0
rts
END_IF
lda selected_icon_list
rts
.endproc ; GetSingleSelectedIcon
;;; ============================================================
;;; Open a folder/volume, either by icon or path
;;; `OpenWindowForIcon`
;;; Input: A = icon
;;; `OpenWindowForPath`
;;; Input: `src_path_buf` populated
;;; Note: stack will be restored via `saved_stack` on failure
.proc OpenWindowImpl
;; --------------------------------------------------
;; A = icon, `src_path_buf` not set
for_icon:
sta icon_param ; stash for later
;; Already an open window for the icon?
jsr FindWindowIndexForDirIcon
IF_EQ
inx
txa
jmp ActivateWindow ; no-op if already active
END_IF
;; Compute the path, if it fits
lda icon_param
jsr GetIconPath ; `path_buf3` set to path, A=0 on success
IF_NOT_ZERO
jsr ShowAlert ; A has error if `GetIconPath` fails
ldx saved_stack
txs
rts
END_IF
param_call CopyToSrcPath, path_buf3 ; set `src_path_buf`
jmp no_win
;; --------------------------------------------------
;; `src_path_buf` set by caller
for_path:
jsr ClearSelection
copy8 #kWindowToDirIconNone, icon_param
;; Already an open window for the path?
jsr FindWindowForSrcPath
jne ActivateWindow ; no-op if already active
;; Find icon, if it exists
param_call FindIconForPath, src_path_buf
IF_NOT_ZERO
sta icon_param
END_IF
FALL_THROUGH_TO no_win
;; --------------------------------------------------
;; No window - need to open one.
;; `src_path_buf` has path
;; `icon_param` has icon (or `kWindowToDirIconNone`)
ptr := $06
no_win:
;; Is there a free window?
lda num_open_windows
IF_A_GE #kMaxDeskTopWindows
;; Nope, show error.
param_call ShowAlertParams, AlertButtonOptions::OK, aux::str_warning_too_many_windows
ldx saved_stack
txs
rts
END_IF
;; Search window-icon map to find an unused window.
ldx #0
DO
lda window_to_dir_icon_table,x
BREAK_IF_ZERO ; is `kWindowToDirIconFree`
inx
WHILE_NOT_ZERO ; always
;; Map the window to its source icon
copy8 icon_param, window_to_dir_icon_table,x ; possibly `kWindowToDirIconNone` if opening via path
inx ; 0-based to 1-based
txa
jsr LoadWindowEntryTable
;; Update View and other menus
inc num_open_windows
ldx #DeskTopSettings::default_view
jsr ReadSetting
sta initial_view_by
lda icon_param
IF_NC ; no source icon, use default
jsr GetIconWindow
IF_NOT_ZERO ; not windowed, use default
tax
copy8 win_view_by_table-1,x, initial_view_by
END_IF
END_IF
ldx cached_window_id
initial_view_by := *+1
lda #SELF_MODIFIED_BYTE
sta win_view_by_table-1,x
;; This ensures `ptr` points at IconEntry (real or virtual)
;; and marks/paints the icon (if there is one) as dimmed.
jsr _UpdateIcon
;; Set path (using `ptr`), size, contents, and volume free/used.
jsr _PrepareNewWindow
;; Create the window
lda cached_window_id
jsr GetWindowPtr ; A,X points at Winfo
stax @addr
MGTK_CALL MGTK::OpenWindow, 0, @addr
jsr DrawCachedWindowHeaderAndEntries
jmp ScrollUpdate
;;; Common code to update the dir (vol/folder) icon.
;;; * If `icon_param` is valid:
;;; Points `ptr` at IconEntry, marks it open and repaints it, and sets `ptr`.
;;; * Otherwise:
;;; Points `ptr` at a virtual IconEntry, to allow referencing the icon name.
.proc _UpdateIcon
lda icon_param ; set to `kWindowToDirIconNone` if opening via path
jpl MarkIconDimmed
;; Find last '/'
ldy src_path_buf
DO
lda src_path_buf,y
BREAK_IF_A_EQ #'/'
dey
WHILE_POS
;; Start building string
ldx #0
DO
iny
inx
copy8 src_path_buf,y, filename_buf,x
WHILE_Y_NE src_path_buf
stx filename_buf
;; Adjust ptr as if it's pointing at an IconEntry
copy16 #filename_buf - IconEntry::name, ptr
rts
.endproc ; _UpdateIcon
;;; ------------------------------------------------------------
;;; Set up path and coords for new window, contents and free/used.
;;; Inputs: IconEntry pointer in $06, new window id in `cached_window_id`,
;;; `src_path_buf` has full path
;;; Outputs: Winfo configured, window path table entry set
.proc _PrepareNewWindow
icon_ptr := $06
;; Copy icon name to window title
.scope
name_ptr := icon_ptr
title_ptr := $08
jsr PushPointers
lda cached_window_id
jsr GetWindowTitle
stax title_ptr
add16_8 icon_ptr, #IconEntry::name, name_ptr
ldy #kMaxFilenameLength
DO
copy8 (name_ptr),y, (title_ptr),y
dey
WHILE_POS
jsr PopPointers
.endscope
;; --------------------------------------------------
path_ptr := $08
;; Copy previously composed path into window path
lda cached_window_id
jsr GetWindowPath
stax path_ptr
ldy src_path_buf
DO
copy8 src_path_buf,y, (path_ptr),y
dey
WHILE_POS
;; --------------------------------------------------
winfo_ptr := $06
;; Set window coordinates
lda cached_window_id
jsr GetWindowPtr
stax winfo_ptr
ldy #MGTK::Winfo::port + MGTK::GrafPort::viewloc
;; xcoord = (window_id-1) * 16 + kWindowXOffset
;; ycoord = (window_id-1) * 8 + kWindowYOffset
lda cached_window_id
sec
sbc #1 ; * 16
asl a
asl a
asl a
asl a
pha
adc #kWindowXOffset
sta (winfo_ptr),y ; viewloc::xcoord
iny
copy8 #0, (winfo_ptr),y
iny
pla
lsr a ; / 2
clc
adc #kWindowYOffset
sta (winfo_ptr),y ; viewloc::ycoord
iny
copy8 #0, (winfo_ptr),y
;; Map rect (initially empty, size assigned in `ComputeInitialWindowSize`)
lda #0
ldy #MGTK::Winfo::port + MGTK::GrafPort::maprect + .sizeof(MGTK::Rect)-1
ldx #.sizeof(MGTK::Rect)-1
DO
sta (winfo_ptr),y
dey
dex
WHILE_POS
;; --------------------------------------------------
;; Scrollbars - start off inactive but ready to go
lda #MGTK::Scroll::option_present | MGTK::Scroll::option_thumb
ldy #MGTK::Winfo::hscroll
sta (winfo_ptr),y
ASSERT_EQUALS MGTK::Winfo::vscroll, MGTK::Winfo::hscroll + 1
iny
sta (winfo_ptr),y
;; --------------------------------------------------
;; Read FileRecords
lda cached_window_id
jsr CreateFileRecordsForWindow
;; --------------------------------------------------
;; Update used/free table
lda icon_param ; set to `kWindowToDirIconNone` if opening via path
IF_NC
;; If a windowed icon, source from that
jsr GetIconWindow
IF_NOT_ZERO
;; Windowed (folder) icon
asl a
tax
copy16 window_k_used_table-2,x, vol_kb_used ; 1-based to 0-based
copy16 window_k_free_table-2,x, vol_kb_free
END_IF
END_IF
;; Used cached window's details, which are correct now.
lda cached_window_id
asl a
tax
copy16 vol_kb_used, window_k_used_table-2,x ; 1-based to 0-based
copy16 vol_kb_free, window_k_free_table-2,x
copy16 window_k_used_table-2,x, window_draw_k_used_table-2,x ; 1-based to 0-based
copy16 window_k_free_table-2,x, window_draw_k_free_table-2,x
;; --------------------------------------------------
;; Create window and icons
bit copy_new_window_bounds_flag
IF_NS
;; DeskTopSettings::kViewByXXX
ldx cached_window_id
copy8 new_window_view_by, win_view_by_table-1,x
;; viewloc
ldy #MGTK::Winfo::port + MGTK::GrafPort::viewloc + .sizeof(MGTK::Point)-1
ldx #.sizeof(MGTK::Point)-1
DO
copy8 new_window_viewloc,x, (winfo_ptr),y
dey
dex
WHILE_POS
;; maprect
ldy #MGTK::Winfo::port + MGTK::GrafPort::maprect + .sizeof(MGTK::Rect)-1
ldx #.sizeof(MGTK::Rect)-1
DO
copy8 new_window_maprect,x, (winfo_ptr),y
dey
dex
WHILE_POS
END_IF
jsr InitWindowEntriesAndIcons
bit copy_new_window_bounds_flag
IF_NC
jsr ComputeInitialWindowSize
jsr AdjustViewportForNewIcons
END_IF
;; --------------------------------------------------
;; Animate the window being opened
lda cached_window_id
jsr GetWindowPath
jsr IconToAnimate
ldx cached_window_id
jsr AnimateWindowOpen
rts
.endproc ; _PrepareNewWindow
.endproc ; OpenWindowImpl
OpenWindowForIcon := OpenWindowImpl::for_icon
OpenWindowForPath := OpenWindowImpl::for_path
;;; ============================================================
;;; Marks icon as open and repaints it.
;;; Input: A = icon id
;;; Output: `ptr` ($06) points at IconEntry
.proc MarkIconDimmed
sta icon_param ; Needed for `IconTK::DrawIcon` call below
ptr := $06
jsr GetIconEntry
stax ptr
;; Set dimmed flag
ldy #IconEntry::state
lda (ptr),y
ora #kIconEntryStateDimmed
sta (ptr),y
ITK_CALL IconTK::DrawIcon, icon_param
rts
.endproc ; MarkIconDimmed
;;; ============================================================
;;; Mark the icon as not open; does not redraw as not all clients need
;;; it, e.g. if they will subsequently select the icon.
;;; Input: A = `icon_id`
;;; Trashes $06
.proc MarkIconNotDimmedNoDraw
ptr := $06
jsr GetIconEntry
stax ptr
;; Clear dimmed flag
ldy #IconEntry::state
lda (ptr),y
and #AS_BYTE(~kIconEntryStateDimmed)
sta (ptr),y
;; Redrawing is left to caller
rts
.endproc ; MarkIconNotDimmedNoDraw
;;; ============================================================
;;; Used when recovering from a failed open (bad path, too many icons, etc)
;;; Inputs: `icon_param` points at icon
.proc MarkIconNotDimmed
icon_ptr := $6
;; Find open window for the icon
lda icon_param
beq ret
jsr FindWindowIndexForDirIcon ; X = window id-1 if found
IF_EQ
;; If found, remove from the table.
copy8 #kWindowToDirIconFree, window_to_dir_icon_table,x
END_IF
;; Update the icon and redraw
lda icon_param
jsr MarkIconNotDimmedNoDraw
ITK_CALL IconTK::DrawIcon, icon_param
ret: rts
.endproc ; MarkIconNotDimmed
;;; ============================================================
;;; Give a file path, tries to open/show a window for the containing
;;; directory, and if successful select/show the file.
;;; Input: `INVOKER_PREFIX` has full path to file
;;; Output: C=0 on success
;;; Assert: Path is not a volume path
.proc ShowFileWithPath
jsr SplitInvokerPath
copy8 num_open_windows, old
tsx
stx saved_stack
jsr OpenWindowForPath
;; If an existing window was shown, refresh the contents.
lda num_open_windows
old := *+1
cmp #SELF_MODIFIED_BYTE
IF_EQ
lda active_window_id
jsr ActivateAndRefreshWindowOrClose
bne err
END_IF
param_call SelectFileIconByName, INVOKER_FILENAME
clc
rts
err: sec
rts
.endproc ; ShowFileWithPath
;;; ============================================================
;;; Find an icon for a given path. May be volume or in any window.
;;;
;;; Inputs: A,X has path
;;; Output: A=icon id and Z=0 if found, Z=1 if no match
;;; Trashes $06 and `path_buf4`
.proc FindIconForPath
jsr CopyToBuf4
param_call FindLastPathSegment, path_buf4
IF_Y_EQ path_buf4 ; was there a filename?
;; Volume - make it a filename
ldx path_buf4 ; Strip '/'
dex
stx path_buf4+1
ldax #path_buf4+1 ; A,X=volname
ldy #0 ; 0=desktop
ELSE
;; File - need to see if there's a window
jsr SplitPathBuf4
param_call FindWindowForPath, path_buf4
RTS_IF_ZERO ; no matching window
tay ; Y=window id
ldax #filename_buf ; A,X=filename
END_IF
jmp FindIconByName
.endproc ; FindIconForPath
;;; ============================================================
;;; Draw all entries (icons or list items) in (cached) window
.assert * < OVERLAY_BUFFER || * >= $6000, error, "Routine used when clearing updates in overlay zone"
.proc DrawWindowEntries
;; --------------------------------------------------
;; Icons
;; Map icons to window space
jsr CachedIconsScreenToWindow
ITK_CALL IconTK::DrawAll, cached_window_id
.ifdef DEBUG
jsr ComputeIconsBBox
COPY_BLOCK iconbb_rect, tmp_rect
jsr FrameTmpRect
.endif
;; Map icons back to screen space
jsr CachedIconsWindowToScreen
;; --------------------------------------------------
;; List View Columns
jsr GetCachedWindowViewBy ; N=0 is icon view, N=1 is list view
IF_NS
;; Find FileRecord list
lda cached_window_id
jsr GetFileRecordListForWindow
stax file_record_ptr ; points at head of list (entry count)
inc16 file_record_ptr ; now points at first entry in list
;; First row
ldax #kListViewFirstBaseline
stax pos_col::ycoord
;; Draw each list view row
ldx #0 ; X = index
rloop: cpx cached_window_entry_count
beq done
txa ; A = index
pha
lda cached_window_entry_list,x
;; Look up file record number
jsr GetIconRecordNum
jsr DrawListViewRow
MGTK_CALL MGTK::CheckEvents
pla ; A = index
tax ; X = index
inx
jmp rloop
END_IF
;; --------------------------------------------------
done:
rts
.endproc ; DrawWindowEntries
;;; ============================================================
;;; Retrieve the `IconEntry::record_num` for a given icon.
;;; Input: A = icon id
;;; Output: A = icon's record index in its window
;;; Trashes $06
.assert * < OVERLAY_BUFFER || * >= $6000, error, "Routine used when clearing updates in overlay zone"
.proc GetIconRecordNum
jsr GetIconEntry
ptr := $06
stax ptr
ldy #IconEntry::record_num
lda (ptr),y
rts
.endproc ; GetIconRecordNum
;;; ============================================================
.proc ClearSelection
lda selected_icon_count
RTS_IF_ZERO
;; --------------------------------------------------
;; Mark the icons as not highlighted
ldx #0
DO
txa
pha
copy8 selected_icon_list,x, icon_param
ITK_CALL IconTK::UnhighlightIcon, icon_param
pla
tax
inx
WHILE_X_NE selected_icon_count
;; --------------------------------------------------
;; Repaint the icons
jsr RedrawSelectedIcons
;; --------------------------------------------------
;; Clear selection list
lda #0
sta selected_icon_count
sta selected_window_id
rts
.endproc ; ClearSelection
;;; ============================================================
;;; Repaint all selected icons. This uses a fast path if selection
;;; is in the active window, since a clipped port is sufficient.
;;; Otherwise, IconTK's smart (but slow) clipping is used.
.proc RedrawSelectedIcons
lda selected_window_id
IF_NOT_ZERO ; Desktop
IF_A_EQ active_window_id
;; --------------------------------------------------
;; Fast path. Since selection is in the top-most window,
;; drawing can be done using `IconTK::DrawIconRaw` in a
;; clipped port.
jsr UnsafeSetPortFromWindowIdAndAdjustForEntries ; CHECKED
RTS_IF_NOT_ZERO ; obscured
jsr PushPointers
jsr PrepActiveWindowScreenMapping
ldx #0
DO
txa
pha ; A = index
copy8 selected_icon_list,x, icon_param
pha ; A = icon id
jsr GetIconEntry
jsr IconPtrScreenToWindow
ITK_CALL IconTK::DrawIconRaw, icon_param ; CHECKED
pla ; A = icon id
jsr GetIconEntry
jsr IconPtrWindowToScreen
pla ; A = index
tax
inx
WHILE_X_NE selected_icon_count
jsr PopPointers ; do not tail-call optimize!
rts
END_IF
END_IF
;; --------------------------------------------------
;; Slow path. This uses `IconTK::DrawIcon` which clips icons
;; against overlapping windows.
ldx #0
DO
txa
pha
copy8 selected_icon_list,x, icon_param
ITK_CALL IconTK::DrawIcon, icon_param
pla
tax
inx
WHILE_X_NE selected_icon_count
rts
.endproc ; RedrawSelectedIcons
;;; ============================================================
.assert * < OVERLAY_BUFFER || * >= $6000, error, "Routine used when clearing updates in overlay zone"
.proc CachedIconsScreenToWindow
param_jump _CachedIconsXToY, IconPtrScreenToWindow
.endproc ; CachedIconsScreenToWindow
;;; ============================================================
.assert * < OVERLAY_BUFFER || * >= $6000, error, "Routine used when clearing updates in overlay zone"
.proc CachedIconsWindowToScreen
param_jump _CachedIconsXToY, IconPtrWindowToScreen
.endproc ; CachedIconsWindowToScreen
;;; ============================================================
;;; Inputs: A,X = proc to call for each icon
;;; Note: No-op if `cached_window_id` = 0 (desktop)
.assert * < OVERLAY_BUFFER || * >= $6000, error, "Routine used when clearing updates in overlay zone"
.proc _CachedIconsXToY
stax proc
jsr PushPointers
lda cached_window_id
IF_NOT_ZERO
jsr PrepWindowScreenMapping
ldx #0 ; X = index
DO
BREAK_IF_X_EQ cached_window_entry_count
txa
pha ; A = index
lda cached_window_entry_list,x
jsr GetIconEntry
proc := *+1
jsr SELF_MODIFIED
pla ; A = index
tax ; X = index
inx
WHILE_NOT_ZERO
END_IF
jsr PopPointers ; do not tail-call optimize!
rts
.endproc ; _CachedIconsXToY
;;; ============================================================
;;; Adjust grafport for header.
.proc AdjustWindowPortForEntries
add16_8 window_grafport+MGTK::GrafPort::viewloc+MGTK::Point::ycoord, #kWindowHeaderHeight
add16_8 window_grafport+MGTK::GrafPort::maprect+MGTK::Rect::y1, #kWindowHeaderHeight
MGTK_CALL MGTK::SetPort, window_grafport
rts
.endproc ; AdjustWindowPortForEntries
;;; ============================================================
.proc UpdateWindowUsedFreeDisplayValues
lda active_window_id
asl
tax
copy16 window_k_used_table-2,x, window_draw_k_used_table-2,x ; 1-based to 0-based
copy16 window_k_free_table-2,x, window_draw_k_free_table-2,x
rts
.endproc ; UpdateWindowUsedFreeDisplayValues
;;; ============================================================
;;; Refresh vol used/free for windows of same volume as path in A,X.
;;; Input: A = window id
.proc UpdateUsedFreeViaPath
ptr := $6
stax ptr
jsr PushPointers ; save $06 = path
;; Save original length
ldy #0
lda (ptr),y
pha
param_call_indirect MakeVolumePath, ptr
;; Update `found_windows_count` and `found_windows_list`
param_call_indirect FindWindowsForPrefix, ptr
;; Restore path length
pla
ldy #0
sta (ptr),y
;; Determine if there are windows to update
jsr PopPointers ; $06 = vol path
ldax ptr
jsr CopyToSrcPath
jsr GetVolUsedFreeViaPath
IF_ZS
ldy found_windows_count
IF_NOT_ZERO
DO
lda found_windows_list-1,y
asl a
tax
copy16 vol_kb_used, window_k_used_table-2,x ; 1-based to 0-based
copy16 vol_kb_free, window_k_free_table-2,x
dey
WHILE_NOT_ZERO
END_IF
END_IF
rts
.endproc ; UpdateUsedFreeViaPath
;;; ============================================================
;;; Find position of last segment of path at (A,X), return in Y.
;;; For "/a/b", Y points at "/b"; if volume path, unchanged.
.proc FindLastPathSegment
ptr := $A
stax ptr
;; Find last slash in string
ldy #0
lda (ptr),y
tay
DO
lda (ptr),y
cmp #'/'
beq slash
dey
WHILE_POS
;; Oops - no slash
ldy #1
;; Restore original string
restore:
dey
lda (ptr),y
tay
rts
;; Are we left with "/" ?
slash: cpy #1
beq restore
dey
rts
.endproc ; FindLastPathSegment
;;; ============================================================
.proc FindWindowForSrcPath
ldax #src_path_buf
FALL_THROUGH_TO FindWindowForPath
.endproc ; FindWindowForSrcPath
;;; ============================================================
;;; `FindWindowForPath`
;;; Inputs: A,X = string
;;; Output: A = window id (0 if no match)
;;;
;;; `FindWindowsForPrefix`
;;; Inputs: A,X = string
;;; Outputs: `found_windows_count` and `found_windows_list` are updated
.proc FindWindowsImpl
ptr1 := $6
ptr2 := $8
exact: sec
bcs start ; always
prefix: clc
start: stax ptr1
ror exact_match_flag
lda #0
sta found_windows_count
sta window_num
DO
inc window_num
window_num := *+1
lda #SELF_MODIFIED_BYTE
IF_A_GE #kMaxDeskTopWindows+1 ; directory windows are 1-8
bit exact_match_flag
IF_NS
lda #0
END_IF
rts
END_IF
check_window:
tax
lda window_to_dir_icon_table-1,x
ASSERT_EQUALS ::kWindowToDirIconFree, 0
CONTINUE_IF_ZERO
lda window_num
jsr GetWindowPath
stax ptr2
bit exact_match_flag
IF_NS
jsr CompareStrings ; Z=1 if equal
CONTINUE_IF_ZC
return window_num
END_IF
jsr IsPathPrefixOf ; Z=0 if prefix
CONTINUE_IF_ZS
ldx found_windows_count
copy8 window_num, found_windows_list,x
inc found_windows_count
WHILE_NOT_ZERO ; always
exact_match_flag:
.byte 0
.endproc ; FindWindowsImpl
FindWindowForPath := FindWindowsImpl::exact
FindWindowsForPrefix := FindWindowsImpl::prefix
found_windows_count:
.byte 0
found_windows_list:
.res 8
;;; ============================================================
.proc CreateFileRecordsForWindowImpl
DEFINE_OPEN_PARAMS open_params, src_path_buf, $800
dir_buffer := $C00
DEFINE_READWRITE_PARAMS read_params, dir_buffer, $200
DEFINE_CLOSE_PARAMS close_params
;;; Copy of data from directory header
.params dir_header
entry_length: .byte 0
entries_per_block: .byte 0
file_count: .word 0
.endparams
index_in_block: .byte 0
index_in_dir: .byte 0
record_count: .byte 0
.proc _Start
sta window_id
jsr PushPointers
jsr SetCursorWatch ; before loading directory
jsr _DoOpen
lda open_params::ref_num
sta read_params::ref_num
sta close_params::ref_num
jsr _DoRead
jsr GetVolUsedFreeViaPath ; uses `src_path_buf`
ldx #0
DO
copy8 dir_buffer+SubdirectoryHeader::entry_length,x, dir_header,x
inx
WHILE_X_NE #.sizeof(dir_header)
;; Is there room for the files?
lda dir_header::file_count+1 ; > 255?
bne too_many_files ; yep, definitely not enough room
;; How many more icons can we allocate?
lda #kMaxIconCount - 2 ; -1 for `DEVCNT` off-by-one, -1 for Trash
sec
sbc icon_count ; actual number in use
clc
adc window_entry_count_table ; but don't count desktop icons...
sec
sbc DEVCNT ; count _potential_ number of desktop icons
;; Can we fit them all?
cmp dir_header::file_count
bcs enough_room
too_many_files:
jsr _DoClose
;; Show error, unless this is during window restore.
bit suppress_error_on_open_flag
IF_NC
ldax #aux::str_warning_window_must_be_closed ; too many files to show
ldy active_window_id ; is a window open?
IF_ZERO
ldax #aux::str_warning_too_many_files ; suggest closing a window
END_IF
ldy #AlertButtonOptions::OK
jsr ShowAlertParams ; A,X = string, Y = AlertButtonOptions
END_IF
clc ; check vol flag (no)
jmp _HandleFailure
enough_room:
record_ptr := $06
copy16 filerecords_free_start, record_ptr
;; Append entry to list
lda window_id_to_filerecord_list_count ; get pointer offset
asl a
tax
copy16 record_ptr, window_filerecord_table,x ; update pointer table
ldx window_id_to_filerecord_list_count ; get window id offset
window_id := *+1
lda #SELF_MODIFIED_BYTE
sta window_id_to_filerecord_list_entries,x ; update window id list
inc window_id_to_filerecord_list_count
copy8 #AS_BYTE(-1), index_in_dir ; immediately incremented
copy8 #0, index_in_block
copy8 #0, record_count
jsr PushPointers ; save initial `record_ptr`
entry_ptr := $08
copy16 #dir_buffer + SubdirectoryHeader::storage_type_name_length, entry_ptr
;; Advance past entry count
inc16 record_ptr
;; Record is temporarily constructed at $1F00 then copied into place.
record := $1F00
do_entry:
inc index_in_dir
lda index_in_dir
cmp dir_header::file_count
jeq finish
next: inc index_in_block
lda index_in_block
IF_A_NE dir_header::entries_per_block
add16_8 entry_ptr, dir_header::entry_length
ELSE
copy8 #$00, index_in_block
copy16 #$0C04, entry_ptr
jsr _DoRead
END_IF
ldx #$00
ldy #$00
lda (entry_ptr),y
and #NAME_LENGTH_MASK
beq next ; inactive entry
sta record,x ; name length
ldx #DeskTopSettings::options
jsr ReadSetting
and #DeskTopSettings::kOptionsShowInvisible
IF_ZERO
ldy #FileEntry::access
lda (entry_ptr),y
and #ACCESS_I
bne do_entry
END_IF
inc record_count
param_call_indirect AdjustFileEntryCase, entry_ptr
;; Copy fields from `FileEntry` to `FileRecord`
;; (name length handled above, hence off-by-ones)
ldx #1
DO
ldy file_entry_to_file_record_mapping_table-1,x
copy8 (entry_ptr),y, record,x
inx
WHILE_X_NE #.sizeof(FileRecord)
;; Copy entry composed at $1F00 to buffer in Aux LC Bank 2
bit LCBANK2
bit LCBANK2
ldy #.sizeof(FileRecord)-1
DO
copy8 record,y, (record_ptr),y
dey
WHILE_POS
bit LCBANK1
bit LCBANK1
add16_8 record_ptr, #.sizeof(FileRecord)
jmp do_entry
finish: copy16 record_ptr, filerecords_free_start
;; Store record count
jsr PopPointers ; restore `record_ptr` to list start
bit LCBANK2
bit LCBANK2
lda record_count
ldy #0
sta (record_ptr),y
bit LCBANK1
bit LCBANK1
jsr _DoClose
jsr SetCursorPointer ; after loading directory
jsr PopPointers ; do not tail-call optimise!
rts
;;; index is offset in `FileRecord`-1, value is offset in `FileEntry`
file_entry_to_file_record_mapping_table:
;; name length needs masking and is handled separately
.repeat ::kMaxFilenameLength,i
.byte FileEntry::file_name+i
.endrepeat
.byte FileEntry::file_type
.byte FileEntry::blocks_used+0
.byte FileEntry::blocks_used+1
.byte FileEntry::creation_date+0
.byte FileEntry::creation_date+1
.byte FileEntry::creation_date+2
.byte FileEntry::creation_date+3
.byte FileEntry::mod_date+0
.byte FileEntry::mod_date+1
.byte FileEntry::mod_date+2
.byte FileEntry::mod_date+3
.byte FileEntry::access
.byte FileEntry::header_pointer+0
.byte FileEntry::header_pointer+1
.byte FileEntry::aux_type+0
.byte FileEntry::aux_type+1
ASSERT_TABLE_SIZE file_entry_to_file_record_mapping_table, .sizeof(FileRecord)-1
.endproc ; _Start
;;; --------------------------------------------------
.proc _DoOpen
MLI_CALL OPEN, open_params
IF_CS
;; Show error, unless this is during window restore.
bit suppress_error_on_open_flag
IF_NC
jsr ShowAlert
END_IF
sec ; check vol flag (yes)
jmp _HandleFailure
END_IF
rts
.endproc ; _DoOpen
suppress_error_on_open_flag:
.byte 0
;;; --------------------------------------------------
.proc _DoRead
MLI_CALL READ, read_params
rts
.endproc ; _DoRead
.proc _DoClose
MLI_CALL CLOSE, close_params
rts
.endproc ; _DoClose
;;; Input: A = check vol flag
.proc _HandleFailure
php ; C = check vol flag
;; If opening an icon, need to reset icon state.
bit icon_param ; Were we opening a path? (N=1)
IF_NC
jsr MarkIconNotDimmed
END_IF
;; A window was allocated but unused, so restore the count.
dec num_open_windows
;; A table entry was possibly allocated - free it.
ldy cached_window_id
IF_NOT_ZERO
lda #kWindowToDirIconFree
sta window_to_dir_icon_table-1,y
sta cached_window_id
END_IF
plp ; C = check vol flag
IF_CS
lda selected_window_id
IF_ZERO
;; Volume icon - check that it's still valid.
lda icon_param
ldy #$00 ; Y = show unexpected errors flag (don't)
jsr CheckDriveByIconNumber ; A = icon id
END_IF
END_IF
;; And return via saved stack.
jsr SetCursorPointer
ldx saved_stack
txs
.endproc ; _HandleFailure
;;; --------------------------------------------------
.endproc ; CreateFileRecordsForWindowImpl
CreateFileRecordsForWindow := CreateFileRecordsForWindowImpl::_Start
;;; ============================================================
;;; Inputs: `src_path_buf` set to full path (not modified)
;;; Outputs: Z=1 on success, `vol_kb_used` and `vol_kb_free` updated.
;;; TODO: Skip if same-vol windows already have data.
.proc GetVolUsedFreeViaPath
lda src_path_buf
pha ; A = original length
;; Strip to vol name - either end of string or next slash
param_call MakeVolumePath, src_path_buf
;; Get volume information
jsr GetSrcFileInfo
pla ; A = original length
sta src_path_buf
IF_CS
return #$FF ; failure
END_IF
;; aux = total blocks
copy16 src_file_info_params::blocks_used, vol_kb_used
;; total - used = free
sub16 src_file_info_params::aux_type, vol_kb_used, vol_kb_free
;; Blocks to K
lsr16 vol_kb_free
lsr16 vol_kb_used
return #0 ; success
.endproc ; GetVolUsedFreeViaPath
vol_kb_free: .word 0
vol_kb_used: .word 0
;;; ============================================================
;;; Remove the FileRecord entries for a window, and free/compact
;;; the space.
;;; A = window id
.proc RemoveWindowFileRecords
;; Find address of FileRecord list
jsr FindIndexInFileRecordListEntries
RTS_IF_ZC
;; Move list entries down by one
stx index
dex
DO
inx
copy8 window_id_to_filerecord_list_entries+1,x, window_id_to_filerecord_list_entries,x
WHILE_X_NE window_id_to_filerecord_list_count
;; List is now shorter by one...
dec window_id_to_filerecord_list_count
;; Was that the last one?
index := *+1
lda #SELF_MODIFIED_BYTE
IF_A_EQ window_id_to_filerecord_list_count
asl a ; so update the start of free space
tax
copy16 window_filerecord_table,x, filerecords_free_start
rts ; and done!
END_IF
;; --------------------------------------------------
;; Compact FileRecords
ptr_src := $08
ptr_dst := $06
deltam := $0A ; memory delta
size := $0C ; size of a window's list
;; Need to compact FileRecords space - shift memory down.
;; +----------+------+----------+---------+
;; |##########|xxxxxx|mmmmmmmmmm| |
;; +----------+------+----------+---------+
;; 1 2 3
;; 1 = ptr_dst (start of newly freed space)
;; 2 = ptr_src (next list)
;; 3 = filerecords_free_start (top of used space)
;; x = freed, m = moved, # = unchanged
lda index
asl a
tax
copy16 window_filerecord_table,x, ptr_dst
inx
inx
copy16 window_filerecord_table,x, ptr_src
ldy #0
jsr PushPointers
DO
bit LCBANK2
bit LCBANK2
copy8 (ptr_src),y, (ptr_dst),y
bit LCBANK1
bit LCBANK1
inc16 ptr_dst
inc16 ptr_src
;; All the way to top of used space
ecmp16 ptr_src, filerecords_free_start
WHILE_NE
jsr PopPointers ; do not tail-call optimise!
;; Offset affected list pointers down
lda window_id_to_filerecord_list_count
asl a
tax
sub16 filerecords_free_start, window_filerecord_table,x, deltam
inc index
DO
lda index
BREAK_IF_A_EQ window_id_to_filerecord_list_count
lda index
asl a
tax
sub16 window_filerecord_table+2,x, window_filerecord_table,x, size
add16 window_filerecord_table-2,x, size, window_filerecord_table,x
inc index
WHILE_NOT_ZERO ; always
;; Update "start of free memory" pointer
lda window_id_to_filerecord_list_count
asl a
tax
add16 window_filerecord_table-2,x, deltam, filerecords_free_start
rts
.endproc ; RemoveWindowFileRecords
copy_new_window_bounds_flag:
.byte 0
;;; ============================================================
;;; Compute the window initial size for `cached_window_id`,
;;; based on icons bounding box.
;;; Output: Updates the Winfo record's maprect right/bottom.
.proc ComputeInitialWindowSize
jsr PushPointers
;; NOTE: Coordinates (screen vs. window) doesn't matter
;; Results in `iconbb_rect` are ignored if window is empty
jsr ComputeIconsBBox
winfo_ptr := $06
lda cached_window_id
jsr GetWindowPtr
stax winfo_ptr
;; convert right/bottom to width/height
bbox_dx := iconbb_rect+MGTK::Rect::x2
bbox_dy := iconbb_rect+MGTK::Rect::y2
sub16 bbox_dx, iconbb_rect+MGTK::Rect::x1, bbox_dx
ldy #MGTK::Winfo::port + MGTK::GrafPort::viewloc + MGTK::Point::ycoord
sub16in bbox_dy, (winfo_ptr),y, bbox_dy
;; --------------------------------------------------
;; Width
lda cached_window_entry_count
beq use_minw ; `iconbb_rect` is bogus if there are no icons
;; Check if width is < min or > max
cmp16 bbox_dx, #kMinWindowWidth
bcc use_minw
cmp16 bbox_dx, #kMaxWindowWidth
bcs use_maxw
ldax bbox_dx
bcc assign_width ; always
use_minw:
ldax #kMinWindowWidth
ASSERT_EQUALS .hibyte(::kMinWindowWidth), 0
beq assign_width ; always
use_maxw:
ldax #kMaxWindowWidth
assign_width:
ldy #MGTK::Winfo::port + MGTK::GrafPort::maprect + MGTK::Rect::x2
sta (winfo_ptr),y
txa
iny
sta (winfo_ptr),y
;; --------------------------------------------------
;; Height
lda cached_window_entry_count
beq use_minh ; `iconbb_rect` is bogus if there are no icons
;; Check if height is < min or > max
cmp16 bbox_dy, #kMinWindowHeight
bcc use_minh
cmp16 bbox_dy, #kMaxWindowHeight
bcs use_maxh
ldax bbox_dy
bcc assign_height ; always
use_minh:
ldax #kMinWindowHeight
ASSERT_EQUALS .hibyte(::kMinWindowHeight), 0
beq assign_height ; always
use_maxh:
ldax #kMaxWindowHeight
assign_height:
ldy #MGTK::Winfo::port + MGTK::GrafPort::maprect + MGTK::Rect::y2
sta (winfo_ptr),y
txa
iny
sta (winfo_ptr),y
;; Finished
jsr PopPointers ; do not tail-call optimise!
rts
.endproc ; ComputeInitialWindowSize
;;; ============================================================
;;; For a newly populated window (new or refreshed), adjust the
;;; viewport so that the icon bbox is in the top-left, rather
;;; than being offset arbitrarily.
;;; Inputs: `cached_window_id` is accurate
.proc AdjustViewportForNewIcons
;; No-op if window is empty
lda cached_window_entry_count
IF_NOT_ZERO
;; Screen space
jsr ComputeIconsBBox
winfo_ptr := $06
tmpw := $08
lda cached_window_id
jsr GetWindowPtr
stax winfo_ptr
;; Adjust view bounds of new window so it matches icon bounding box.
;; (Only done for width because height is treated as fixed.)
jsr CachedIconsScreenToWindow
ldy #MGTK::Winfo::port + MGTK::GrafPort::viewloc + MGTK::Point::xcoord
sub16in iconbb_rect+MGTK::Rect::x1, (winfo_ptr),y, tmpw
ldy #MGTK::Winfo::port + MGTK::GrafPort::maprect + MGTK::Rect::x1
add16in (winfo_ptr),y, tmpw, (winfo_ptr),y
ldy #MGTK::Winfo::port + MGTK::GrafPort::maprect + MGTK::Rect::x2
add16in (winfo_ptr),y, tmpw, (winfo_ptr),y
jsr CachedIconsWindowToScreen
END_IF
rts
.endproc ; AdjustViewportForNewIcons
;;; ============================================================
;;; Map file type (etc) to icon type
;;; Input: `src_file_info_params` (`file_type`, `aux_type`, `blocks_used`) and A,X = filename
;;; Output: A is IconType to use (for icons, open/preview, etc)
.proc DetermineIconType
ptr := $06
flags := $08
ptr_filename := $0A
file_type := src_file_info_params::file_type
aux_type := src_file_info_params::aux_type
blocks_used := src_file_info_params::blocks_used
stax ptr_filename
jsr PushPointers
copy16 #icontype_table, ptr
loop: ldy #ICTRecord::mask ; $00 if done
lda (ptr),y
IF_A_EQ #kICTSentinel
jsr PopPointers
lda #IconType::generic
rts
END_IF
;; Check type (with mask)
and file_type ; A = type & mask
iny ; ASSERT: Y = ICTRecord::filetype
ASSERT_EQUALS ICTRecord::filetype, ICTRecord::mask+1
cmp (ptr),y ; type check
jne next
;; Flags
iny ; ASSERT: Y = ICTRecord::flags
ASSERT_EQUALS ICTRecord::flags, ICTRecord::filetype+1
copy8 (ptr),y, flags
;; Does Aux Type matter, and if so does it match?
bit flags
IF_NS ; bit 7 = compare aux
iny ; ASSERT: Y = FTORecord::aux_suf
ASSERT_EQUALS ICTRecord::aux_suf, ICTRecord::flags+1
lda aux_type
cmp (ptr),y
bne next
iny
lda aux_type+1
cmp (ptr),y
bne next
END_IF
;; Does Block Count matter, and if so does it match?
bit flags
IF_VS ; bit 6 = compare blocks
ldy #ICTRecord::blocks
lda blocks_used
cmp (ptr),y
bne next
iny
lda blocks_used+1
cmp (ptr),y
bne next
END_IF
;; Filename suffix?
lda flags
and #ICT_FLAGS_SUFFIX
IF_NOT_ZERO
;; Set up pointers to suffix and filename
ptr_suffix := $08
ldy #ICTRecord::aux_suf
copy16in (ptr),y, ptr_suffix
;; Start at the end of the strings
ldy #0
copy8 (ptr_suffix),y, suffix_pos
copy8 (ptr_filename),y, filename_pos
;; Case-insensitive compare each character
DO
filename_pos := *+1
ldy #SELF_MODIFIED_BYTE
lda (ptr_filename),y
jsr ToUpperCase
suffix_pos := *+1
ldy #SELF_MODIFIED_BYTE
cmp (ptr_suffix),y ; already uppercase
bne next ; no match
;; Move to previous characters
dec suffix_pos
BREAK_IF_ZERO ; if we ran out of suffix, it's a match
dec filename_pos
beq next ; but if we ran out of filename, it's not
WHILE_NOT_ZERO ; otherwise, keep going
END_IF
;; Have a match
ldy #ICTRecord::icontype
lda (ptr),y
jsr PopPointers
rts
;; Next entry
next: add16_8 ptr, #.sizeof(ICTRecord)
jmp loop
.endproc ; DetermineIconType
;;; ============================================================
;;; Input: $08 = `FileRecord` pointer
.proc FileRecordToSrcFileInfo
file_record := $08
ldy #FileRecord::file_type
copy8 (file_record),y, src_file_info_params::file_type
ldy #FileRecord::aux_type
copy16in (file_record),y, src_file_info_params::aux_type
ldy #FileRecord::blocks
copy16in (file_record),y, src_file_info_params::blocks_used
rts
.endproc ; FileRecordToSrcFileInfo
;;; ============================================================
;;; Draw header (items/K in disk/K available/lines) for `cached_window_id`
.assert * < OVERLAY_BUFFER || * >= $6000, error, "Routine used when clearing updates in overlay zone"
.proc DrawWindowHeader
;;; Local variables on ZP
PARAM_BLOCK, $50
num_items .word
k_in_disk .word
k_available .word
width_num_items .word
width_k_in_disk .word
width_k_available .word
ptr_str_items_suffix .addr
END_PARAM_BLOCK
;; --------------------------------------------------
;; Separator Lines
viewport := window_grafport+MGTK::GrafPort::maprect
;; x coords
copy16 viewport+MGTK::Rect::x1, header_line_left::xcoord
copy16 viewport+MGTK::Rect::x2, header_line_right::xcoord
;; y coords
lda viewport+MGTK::Rect::y1
clc
adc #kWindowHeaderHeight - 3
sta header_line_left::ycoord
sta header_line_right::ycoord
lda viewport+MGTK::Rect::y1+1
adc #0
sta header_line_left::ycoord+1
sta header_line_right::ycoord+1
;; Draw top line
MGTK_CALL MGTK::MoveTo, header_line_left
jsr SetPenModeNotCopy
MGTK_CALL MGTK::LineTo, header_line_right
;; Offset down by 2px
lda header_line_left::ycoord
clc
adc #2
sta header_line_left::ycoord
sta header_line_right::ycoord
lda header_line_left::ycoord+1
adc #0
sta header_line_left::ycoord+1
sta header_line_right::ycoord+1
;; Draw bottom line
MGTK_CALL MGTK::MoveTo, header_line_left
MGTK_CALL MGTK::LineTo, header_line_right
;; --------------------------------------------------
;; Labels (Items/K in disk/K available)
;; Cache values
lda cached_window_id
jsr GetFileRecordCountForWindow
ldx #0
stax num_items
tay
ldax #str_items_suffix
IF_Y_EQ #1
ldax #str_item_suffix
END_IF
stax ptr_str_items_suffix
ldx cached_window_id
dex ; index 0 is window 1
txa
asl a
tay
lda window_draw_k_used_table,y
ldx window_draw_k_used_table+1,y
stax k_in_disk
lda window_draw_k_free_table,y
ldx window_draw_k_free_table+1,y
stax k_available
;; Measure strings
ldax num_items
jsr _MeasureIntString
stax width_num_items
param_call_indirect _MeasureString, ptr_str_items_suffix
addax width_num_items
ldax k_in_disk
jsr _MeasureIntString
stax width_k_in_disk
param_call _MeasureString, str_k_in_disk
addax width_k_in_disk
ldax k_available
jsr _MeasureIntString
stax width_k_available
param_call _MeasureString, str_k_available
addax width_k_available
;; Determine gap for centering
gap := header_text_delta::xcoord
sub16 viewport+MGTK::Rect::x2, viewport+MGTK::Rect::x1, gap ; window width
sub16_8 gap, #kWindowHeaderInsetX * 2, gap ; minus left/right insets
sub16 gap, width_num_items, gap ; minus width of all text
sub16 gap, width_k_in_disk, gap
sub16 gap, width_k_available, gap
asr16 gap ; divided evenly
scmp16 #kWindowHeaderSpacingX, gap ; is it below the minimum?
IF_POS
copy16 #kWindowHeaderSpacingX, gap ; yes, use the minimum
END_IF
;; Draw "XXX items"
add16_8 viewport+MGTK::Rect::x1, #kWindowHeaderInsetX, header_text_pos::xcoord
add16_8 viewport+MGTK::Rect::y1, #kWindowHeaderHeight-5, header_text_pos::ycoord
MGTK_CALL MGTK::MoveTo, header_text_pos
ldax num_items
jsr _DrawIntString
param_call_indirect DrawString, ptr_str_items_suffix
;; Draw "XXXK in disk"
MGTK_CALL MGTK::Move, header_text_delta
ldax k_in_disk
jsr _DrawIntString
param_call DrawString, str_k_in_disk
;; Draw "XXXK available"
MGTK_CALL MGTK::Move, header_text_delta
ldax k_available
jsr _DrawIntString
param_jump DrawString, str_k_available
.proc _DrawIntString
jsr IntToStringWithSeparators
param_jump DrawString, str_from_int
.endproc ; _DrawIntString
.proc _MeasureIntString
jsr IntToStringWithSeparators
ldax #str_from_int
FALL_THROUGH_TO _MeasureString
.endproc ; _MeasureIntString
;;; Measure text, pascal string address in A,X; result in A,X
;;; String must be in LC area (visible to both main and aux code)
.proc _MeasureString
ptr := $6
len := $8
result := $9
stax ptr
ldy #0
copy8 (ptr),y, len
inc16 ptr
MGTK_CALL MGTK::TextWidth, ptr
ldax result
rts
.endproc ; _MeasureString
.endproc ; DrawWindowHeader
;;; ============================================================
;;; Compute bounding box for icons within cached window
;;; Inputs: `cached_window_id` is set
;;; Outputs: `iconbb_rect` updated (unless cached window is empty)
.proc ComputeIconsBBox
lda cached_window_entry_count
RTS_IF_ZERO
;; --------------------------------------------------
;; For each icon...
copy8 #0, icon_num
DO
icon_num := *+1
ldx #SELF_MODIFIED_BYTE
BREAK_IF_X_EQ cached_window_entry_count
;; Get the bounds
copy8 cached_window_entry_list,x, icon_param
ITK_CALL IconTK::GetIconBounds, icon_param ; inits `tmp_rect`
jsr GetCachedWindowViewBy
ASSERT_EQUALS DeskTopSettings::kViewByIcon, 0
IF_ZERO
;; Pretend icon is max height
sub16 tmp_rect::y2, #kMaxIconTotalHeight, tmp_rect::y1
END_IF
lda icon_num
IF_ZERO
;; First icon (index 0) - just use its coordinates as min/max
COPY_BLOCK tmp_rect, iconbb_rect
ELSE
;; Expand bounding rect to encompass icon's rect
MGTK_CALL MGTK::UnionRects, unionrects_tmp_iconbb
END_IF
inc icon_num
WHILE_NOT_ZERO ; always
;; --------------------------------------------------
;; List view?
jsr GetCachedWindowViewBy ; N=0 is icon view, N=1 is list view
IF_NS
;; max.x = kListViewWidth
add16 iconbb_rect::x1, #kListViewWidth, iconbb_rect::x2
END_IF
;; Add padding around bbox
MGTK_CALL MGTK::InflateRect, bbox_pad_iconbb_rect
rts
.endproc ; ComputeIconsBBox
;;; ============================================================
;;; Prepares a window's set of entries - before icon creation
;;; (or in views without icons) these are `FileRecord` indexes.
;;; In list views these are subsequently sorted. When icons are
;;; created, this order is used but the list is re-populated
;;; with icon numbers.
;;;
;;; Inputs: `cached_window_id` is set
;;; Outputs: Populates `cached_window_entry_count` with count and
;;; `cached_window_entry_list` with indexes 1...N
;;; Assert: LCBANK1 is active
.proc InitWindowEntriesAndIcons
;; --------------------------------------------------
;; Create generic entries for window
jsr PushPointers
;; Get the entry count via FileRecord list
lda cached_window_id
jsr GetFileRecordCountForWindow
;; Store the count
sta cached_window_entry_count
;; Init the entries, monotonically increasing
tax
IF_NOT_ZERO
DO
txa
sta cached_window_entry_list-1,x ; entries are 1-based
dex
WHILE_NOT_ZERO
END_IF
jsr PopPointers ; do not tail-call optimize!
;; --------------------------------------------------
;; Sort (if needed)
jsr GetCachedWindowViewBy ; N=0 is icon view, N=1 is list view
IF_NS
jsr SortRecords
END_IF
;; --------------------------------------------------
;; Create icons
jsr _CreateIconsForWindow
jmp StoreWindowEntryTable
;;; ------------------------------------------------------------
;;; File Icon Entry Construction
;;; Inputs: `cached_window_id` must be set
.proc _CreateIconsForWindow
;;; Local variables on ZP
PARAM_BLOCK, $50
icon_type .addr
icon_flags .byte
icon_height .word
;; Updated based on view type
initial_xcoord .word
icons_this_row .byte
;; Initial values when populating a list view
icons_per_row .byte
col_spacing .byte
row_spacing .byte
icon_coords .tag MGTK::Point
END_PARAM_BLOCK
init_view := icons_per_row
init_view_size = 3 + .sizeof(MGTK::Point)
jsr PushPointers
;; Select the template
jsr GetCachedWindowViewBy ; N=0 is icon view, N=1 is list view
IF_NS
ldy #init_list_view - init_views + init_view_size-1
ELSE
ASSERT_EQUALS DeskTopSettings::kViewByIcon, 0
IF_ZERO
ldy #init_icon_view - init_views + init_view_size-1
ELSE
ldy #init_smicon_view - init_views + init_view_size-1
END_IF
END_IF
;; Populate the initial values from the template
ldx #init_view_size-1
DO
copy8 init_views,y, init_view,x
dey
dex
WHILE_POS
;; Init/zero out the rest of the state
copy16 icon_coords+MGTK::Point::xcoord, initial_xcoord
lda #0
sta icons_this_row
;; Copy `cached_window_entry_list` to temp location
record_order_list := $800
ldx cached_window_entry_count
stx num_files
dex
DO
copy8 cached_window_entry_list,x, record_order_list,x
dex
WHILE_POS
copy8 #0, cached_window_entry_count
;; Get base pointer to records
lda cached_window_id
jsr GetFileRecordListForWindow
addax #1, records_base_ptr ; first byte in list is the list size
copy8 cached_window_id, active_window_id
;; Loop over files, creating icon for each
ldx #0 ; X = index
DO
num_files := *+1
cpx #SELF_MODIFIED_BYTE
BREAK_IF_EQ
txa ; A = index
pha
;; Get record from ordered list
lda record_order_list,x
tax ; 1-based to 0-based
dex
txa
pha ; A = record_num-1
ASSERT_EQUALS .sizeof(FileRecord), 32
jsr ATimes32 ; A,X = A * 32
record_ptr := $08
addax records_base_ptr, record_ptr
pla ; A = record_num-1
jsr _AllocAndPopulateFileIcon
pla ; A = index
tax ; X = index
inx
WHILE_NOT_ZERO ; always
jsr CachedIconsWindowToScreen
jsr PopPointers ; do not tail-call optimise!
rts
;; Templates for populating initial values, based on view type
init_views:
init_list_view:
.byte 1, 0, kListItemHeight
.word kListViewInitialLeft, kListViewInitialTop
ASSERT_EQUALS * - init_list_view, init_view_size
init_icon_view:
.byte kIconViewIconsPerRow, kIconViewSpacingX, kIconViewSpacingY
.word kIconViewInitialLeft, kIconViewInitialTop
ASSERT_EQUALS * - init_icon_view, init_view_size
init_smicon_view:
.byte kSmallIconViewIconsPerRow, kSmallIconViewSpacingX, kSmallIconViewSpacingY
.word kSmallIconViewInitialLeft, kSmallIconViewInitialTop
ASSERT_EQUALS * - init_smicon_view, init_view_size
records_base_ptr:
.word 0
;;; ============================================================
;;; Create icon
;;; Inputs: A = record_num, $08 = `FileRecord`
.proc _AllocAndPopulateFileIcon
icon_entry := $06
file_record := $08
name_tmp := $1800
pha ; A = record_num
inc icon_count
ITK_CALL IconTK::AllocIcon, get_icon_entry_params
copy16 get_icon_entry_params::addr, icon_entry
copy8 get_icon_entry_params::id, icon_num
ldx cached_window_entry_count
inc cached_window_entry_count
sta cached_window_entry_list,x
;; Assign record number
pla ; A = record_num
ldy #IconEntry::record_num
sta (icon_entry),y
;; Bank in the `FileRecord` entries
bit LCBANK2
bit LCBANK2
;; Copy the name out
ASSERT_EQUALS FileRecord::name, 0
ldy #kMaxFilenameLength
DO
copy8 (file_record),y, name_tmp,y
dey
WHILE_POS
;; Copy out file metadata needed to determine icon type
jsr FileRecordToSrcFileInfo ; uses `FileRecord` ptr in $08
;; Done with `FileRecord` entries
bit LCBANK1
bit LCBANK1
;; Determine icon type
jsr GetCachedWindowViewBy
sta view_by
ldax #name_tmp
jsr DetermineIconType ; uses passed name and `src_file_info_params`
view_by := *+1
ldy #SELF_MODIFIED_BYTE
jsr _FindIconDetailsForIconType
;; Copy name into `IconEntry`
ldy #IconEntry::name + kMaxFilenameLength
ldx #kMaxFilenameLength
DO
copy8 name_tmp,x, (icon_entry),y
dey
dex
WHILE_POS
;; Assign location
ldy #IconEntry::iconx + .sizeof(MGTK::Point) - 1
ldx #.sizeof(MGTK::Point) - 1
DO
copy8 icon_coords,x, (icon_entry),y
dey
dex
WHILE_POS
jsr GetCachedWindowViewBy
ASSERT_EQUALS DeskTopSettings::kViewByIcon, 0
IF_ZERO
;; Icon view: include y-offset
ldy #IconEntry::icony
sub16in (icon_entry),y, icon_height, (icon_entry),y
END_IF
;; Next col
add16_8 icon_coords+MGTK::Point::xcoord, col_spacing
inc icons_this_row
;; Next row?
lda icons_this_row
IF_A_EQ icons_per_row
add16_8 icon_coords+MGTK::Point::ycoord, row_spacing
copy16 initial_xcoord, icon_coords+MGTK::Point::xcoord
copy8 #0, icons_this_row
END_IF
;; Assign `IconEntry::win_flags`
lda cached_window_id
ora icon_flags
ldy #IconEntry::win_flags
sta (icon_entry),y
;; Assign `IconEntry::type`
ldy #IconEntry::type
copy8 icon_type, (icon_entry),y
;; If folder, see if there's an associated window
lda src_file_info_params::file_type
IF_A_EQ #FT_DIRECTORY
icon_num := *+1
lda #SELF_MODIFIED_BYTE
jsr GetIconPath ; `path_buf3` set to path; A=0 on success
IF_ZERO
jsr PushPointers
param_call FindWindowForPath, path_buf3
jsr PopPointers
tax ; A = window id, 0 if none
IF_NOT_ZERO
copy8 icon_num, window_to_dir_icon_table-1,x
;; Update `IconEntry::state`
ldy #IconEntry::state ; mark as dimmed
lda (icon_entry),y
ora #kIconEntryStateDimmed
sta (icon_entry),y
END_IF
END_IF
END_IF
rts
.endproc ; _AllocAndPopulateFileIcon
;;; ============================================================
;;; Inputs: A = `IconType` member, Y = `DeskTopSettings::kViewByXXX` value
;;; Outputs: Populates `icon_flags`, `icon_type`, `icon_height`
.proc _FindIconDetailsForIconType
ptr := $6
sty view_by
jsr PushPointers
;; For populating `IconEntry::win_flags`
tay ; Y = `IconType`
copy8 icontype_iconentryflags_table,y, icon_flags
;; Adjust type and flags based on view
view_by := *+1
lda #SELF_MODIFIED_BYTE
ASSERT_EQUALS DeskTopSettings::kViewByIcon, 0
IF_NOT_ZERO
;; List View / Small Icon View
php
lda icon_flags
ora #kIconEntryFlagsSmall
plp
IF_NS
ora #kIconEntryFlagsFixed
END_IF
sta icon_flags
lda icontype_to_smicon_table,y
tay
END_IF
;; For populating `IconEntry::type`
sty icon_type
;; Icon height will be needed too
tya
asl ; *= 2
tay
ldax type_icons_table,y
stax ptr
ldy #IconResource::maprect + MGTK::Rect::y2
copy16in (ptr),y, icon_height
jsr PopPointers ; do not tail-call optimise!
rts
.endproc ; _FindIconDetailsForIconType
.endproc ; _CreateIconsForWindow
.endproc ; InitWindowEntriesAndIcons
;;; ============================================================
;;; Fetch the entry count for a window; valid after `CreateFileRecordsForWindow`,
;;; does not depend on icon creation state.
;;; Input: A = window_od
;;; Output: A = entry count
;;; Trashes $06
.proc GetFileRecordCountForWindow
ptr := $06
jsr GetFileRecordListForWindow
stax ptr
bit LCBANK2
bit LCBANK2
ldy #0
lda (ptr),y ; count (at head of list)
bit LCBANK1
bit LCBANK1
rts
.endproc ; GetFileRecordCountForWindow
;;; ============================================================
;;; Populates and sorts `cached_window_entry_list`.
;;; Assumes `InitCachedWindowEntries` has been invoked
;;; (`cached_window_entry_count` is valid, etc)
;;; Inputs: A=DeskTopSettings::kViewBy* for `cached_window_id`
.proc SortRecords
ptr := $06
list_start_ptr := $801
num_records := $803
scratch_space := $804 ; can be used by comparison funcs
sta _CompareFileRecords_sort_by
lda cached_window_entry_count
RTS_IF_A_LT #2 ; can't sort < 2 records
sta num_records
lda cached_window_id
jsr GetFileRecordListForWindow
stax ptr ; point past the count
stax list_start_ptr
inc16 ptr
inc16 list_start_ptr
;; --------------------------------------------------
;; Selection sort
ptr1 := $06
ptr2 := $08
ldx num_records
dex
stx outer
DO
outer := *+1
lda #SELF_MODIFIED_BYTE
jsr _CalcPtr
stax ptr2
copy8 #0, inner
DO
inner := *+1
lda #SELF_MODIFIED_BYTE
jsr _CalcPtr
stax ptr1
bit LCBANK2
bit LCBANK2
jsr _CompareFileRecords
php
bit LCBANK1
bit LCBANK1
plp
IF_GE
;; Swap
ldx inner
ldy outer
swap8 cached_window_entry_list,x, cached_window_entry_list,y
lda outer
jsr _CalcPtr
stax ptr2
END_IF
inc inner
lda inner
WHILE_A_NE outer
dec outer
WHILE_NOT_ZERO
rts
;;; --------------------------------------------------
;;; Input: A = index in list being sorted
;;; Output: A,X = pointer to FileRecord
.proc _CalcPtr
;; Map from sorting list index to FileRecord index
tax
ldy cached_window_entry_list,x
dey ; 1-based to 0-based
tya
;; Calculate the pointer
ASSERT_EQUALS .sizeof(FileRecord), 32
jsr ATimes32
clc
adc list_start_ptr
pha
txa
adc list_start_ptr+1
tax
pla
rts
.endproc ; _CalcPtr
;;; --------------------------------------------------
;;; Inputs: $06 and $08 point at FileRecords
;;; Assert: LCBANK2 banked in so FileRecords are visible
.proc _CompareFileRecords
ptr1 := $06
ptr2 := $08
;; Set by caller
sort_by := *+1
lda #SELF_MODIFIED_BYTE
IF_A_EQ #DeskTopSettings::kViewByName
ASSERT_EQUALS FileRecord::name, 0
jmp CompareStrings
END_IF
IF_A_EQ #DeskTopSettings::kViewByDate
PARAM_BLOCK scratch, $804 ; `scratch_space`
date_a .tag DateTime
date_b .tag DateTime
parsed_a .tag ParsedDateTime
parsed_b .tag ParsedDateTime
END_PARAM_BLOCK
;; Copy the dates somewhere easier to work with
ldy #FileRecord::modification_date + .sizeof(DateTime)-1
ldx #.sizeof(DateTime)-1
DO
copy8 (ptr2),y, scratch::date_a,x ; order descending
copy8 (ptr1),y, scratch::date_b,x
dey
dex
WHILE_POS
;; Crack the ProDOS values into more useful structs, and
;; handle various year encodings.
ptr := $0A
copy16 #scratch::parsed_a, ptr
ldax #scratch::date_a
jsr ParseDatetime
copy16 #scratch::parsed_b, ptr
ldax #scratch::date_b
jsr ParseDatetime
;; Compare member-wise
ecmp16 scratch::parsed_a + ParsedDateTime::year, scratch::parsed_b + ParsedDateTime::year
bne done
lda scratch::parsed_a + ParsedDateTime::month
cmp scratch::parsed_b + ParsedDateTime::month
bne done
lda scratch::parsed_a + ParsedDateTime::day
cmp scratch::parsed_b + ParsedDateTime::day
bne done
lda scratch::parsed_a + ParsedDateTime::hour
cmp scratch::parsed_b + ParsedDateTime::hour
bne done
lda scratch::parsed_a + ParsedDateTime::minute
cmp scratch::parsed_b + ParsedDateTime::minute
done: rts
END_IF
IF_A_EQ #DeskTopSettings::kViewBySize
;; Copy sizes somewhere convenient
size1 := $804
size2 := $806
ldy #FileRecord::blocks
copy8 (ptr1),y, size1
copy8 (ptr2),y, size2
iny
copy8 (ptr1),y, size1+1
copy8 (ptr2),y, size2+1
;; Treat directories as 0
ldy #FileRecord::file_type
lda (ptr1),y
IF_A_EQ #FT_DIRECTORY
copy16 #0, size1
END_IF
lda (ptr2),y
IF_A_EQ #FT_DIRECTORY
copy16 #0, size2
END_IF
;; Compare!
cmp16 size2, size1 ; order descending
rts
END_IF
;; Assert: DeskTopSettings::kViewByType
ldy #FileRecord::file_type
lda (ptr1),y
jsr _ComposeFileTypeStringForSorting
COPY_STRING str_file_type, scratch
ldy #FileRecord::file_type
lda (ptr2),y
jsr _ComposeFileTypeStringForSorting
bit LCBANK1
bit LCBANK1
jsr PushPointers
copy16 #scratch, $06
copy16 #str_file_type, $08
jsr CompareStrings
jsr PopPointers
bit LCBANK2
bit LCBANK2
rts
.endproc ; _CompareFileRecords
_CompareFileRecords_sort_by := _CompareFileRecords::sort_by
.proc _ComposeFileTypeStringForSorting
jsr ComposeFileTypeString
lda str_file_type+1
IF_A_EQ #'$'
copy8 #$FF, str_file_type+1
END_IF
rts
.endproc ; _ComposeFileTypeStringForSorting
.endproc ; SortRecords
;;; ============================================================
;;; A = entry number
.assert * < OVERLAY_BUFFER || * >= $6000, error, "Routine used when clearing updates in overlay zone"
.proc DrawListViewRow
ptr := $06
ASSERT_EQUALS .sizeof(FileRecord), 32
jsr ATimes32 ; A,X = A * 32
addax file_record_ptr, ptr
;; Copy into more convenient location (LCBANK1)
bit LCBANK2
bit LCBANK2
ldy #.sizeof(FileRecord)-1
DO
copy8 (ptr),y, list_view_filerecord,y
dey
WHILE_POS
bit LCBANK1
bit LCBANK1
viewport := window_grafport+MGTK::GrafPort::maprect
;; Below bottom?
scmp16 pos_col::ycoord, viewport+MGTK::Rect::y2
bpl ret
add16 pos_col::ycoord, #kListViewRowHeight, pos_col::ycoord
;; Above top?
scmp16 pos_col::ycoord, viewport+MGTK::Rect::y1
bpl in_range
ret: rts
;; Draw it!
in_range:
ldax #kColLock
jsr set_pos
jsr _PrepareColLock
param_call DrawString, text_buffer2
ldax #kColType
jsr set_pos
jsr _PrepareColType
param_call DrawString, text_buffer2
ldax #kColSize
jsr set_pos
jsr _PrepareColSize
param_call DrawStringRight, text_buffer2
ldax #kColDate
jsr set_pos
jsr ComposeDateString
param_jump DrawString, text_buffer2
set_pos:
stax pos_col::xcoord
MGTK_CALL MGTK::MoveTo, pos_col
rts
;;; ============================================================
.proc _PrepareColType
file_type := list_view_filerecord + FileRecord::file_type
lda file_type
jsr ComposeFileTypeString
COPY_BYTES 4, str_file_type, text_buffer2 ; 3 characters + length
rts
.endproc ; _PrepareColType
.proc _PrepareColLock
copy8 #0, text_buffer2
access := list_view_filerecord + FileRecord::access
lda access
and #ACCESS_DEFAULT
IF_A_NE #ACCESS_DEFAULT
inc text_buffer2
copy8 #kGlyphLock, text_buffer2+1
END_IF
rts
.endproc ; _PrepareColLock
.proc _PrepareColSize
file_type := list_view_filerecord + FileRecord::file_type
lda file_type
IF_A_EQ #FT_DIRECTORY
copy8 #1, text_buffer2
copy8 #'-', text_buffer2+1
rts
END_IF
blocks := list_view_filerecord + FileRecord::blocks
ldax blocks
FALL_THROUGH_TO ComposeSizeString
.endproc ; _PrepareColSize
.endproc ; DrawListViewRow
;;; ============================================================
;;; Populate `text_buffer2` with "12,345K"
;;; Trashes: $06
.assert * < OVERLAY_BUFFER || * >= $6000, error, "Routine used when clearing updates in overlay zone"
.proc ComposeSizeString
value := $06
stax value ; size in 512-byte blocks
ldx #DeskTopSettings::intl_deci_sep
jsr ReadSetting
sta deci_sep
CLEAR_BIT7_FLAG frac_flag
cmp16 value, #20
IF_LT
lsr16 value ; Convert blocks to K, rounding up
ror frac_flag ; If < 10k and odd, show ".5" suffix"
ELSE
lsr16 value ; Convert blocks to K, rounding up
IF_CS ; NOTE: divide then maybe inc, rather than
inc16 value ; always inc then divide, to handle $FFFF
END_IF
END_IF
ldax value
jsr IntToStringWithSeparators
ldx #0
;; Append number
ldy #0
DO
copy8 str_from_int+1,y, text_buffer2+1,x
iny
inx
WHILE_Y_NE str_from_int
;; Append ".5" if needed
frac_flag := *+1
lda #SELF_MODIFIED_BYTE ; bit7
IF_NS
deci_sep := *+1
lda #SELF_MODIFIED_BYTE
sta text_buffer2+1,x
inx
copy8 #'5', text_buffer2+1,x
inx
END_IF
;; Append suffix
ldy #0
DO
copy8 str_kb_suffix+1, y, text_buffer2+1,x
iny
inx
WHILE_Y_NE str_kb_suffix
stx text_buffer2
rts
.endproc ; ComposeSizeString
;;; ============================================================
.assert * < OVERLAY_BUFFER || * >= $6000, error, "Routine used when clearing updates in overlay zone"
.proc ComposeDateString
copy8 #0, text_buffer2
copy16 #text_buffer2, $8
lda datetime_for_conversion ; any bits set?
ora datetime_for_conversion+1
bne append_date_strings
sta month ; 0 is "no date" string
jmp _AppendMonthString
append_date_strings:
copy16 #parsed_date, $0A
ldax #datetime_for_conversion
jsr ParseDatetime
jsr _AppendDateString
param_call _ConcatenateDatePart, str_at
param_call MakeTimeString, parsed_date
param_jump _ConcatenateDatePart, str_time
tmp_date := $0A
.proc _AppendDateString
ecmp16 datetime_for_conversion, DATELO
IF_EQ
param_jump _ConcatenateDatePart, str_today
END_IF
copy16 datetime_for_conversion, tmp_date
jsr _DecP8Date
ecmp16 DATELO, tmp_date
IF_EQ
param_jump _ConcatenateDatePart, str_tomorrow
END_IF
copy16 DATELO, tmp_date
jsr _DecP8Date
ecmp16 datetime_for_conversion, tmp_date
IF_EQ
param_jump _ConcatenateDatePart, str_yesterday
END_IF
ldx #DeskTopSettings::intl_date_order
jsr ReadSetting
ASSERT_EQUALS DeskTopSettings::kDateOrderMDY, 0
IF_EQ
;; Month Day, Year
jsr _AppendMonthString
param_call _ConcatenateDatePart, str_space
jsr _AppendDayString
param_call _ConcatenateDatePart, str_comma
ELSE
;; Day Month Year
jsr _AppendDayString
param_call _ConcatenateDatePart, str_space
jsr _AppendMonthString
param_call _ConcatenateDatePart, str_space
END_IF
jmp _AppendYearString
.endproc ; _AppendDateString
.proc _AppendDayString
lda day
ldx #0
jsr IntToString
param_jump _ConcatenateDatePart, str_from_int
.endproc ; _AppendDayString
.proc _AppendMonthString
lda month
asl a
tay
ldax month_table,y
jmp _ConcatenateDatePart
.endproc ; _AppendMonthString
.proc _AppendYearString
ldax year
jsr IntToString
param_jump _ConcatenateDatePart, str_from_int
.endproc ; _AppendYearString
year := parsed_date + ParsedDateTime::year
month := parsed_date + ParsedDateTime::month
day := parsed_date + ParsedDateTime::day
hour := parsed_date + ParsedDateTime::hour
min := parsed_date + ParsedDateTime::minute
.proc _ConcatenateDatePart
stax $06
ldy #$00
copy8 ($08),y, concat_len
clc
adc ($06),y
sta ($08),y
copy8 ($06),y, compare_y
DO
inc concat_len
iny
lda ($06),y
sty tmp
concat_len := *+1
ldy #SELF_MODIFIED_BYTE
sta ($08),y
tmp := *+1
ldy #SELF_MODIFIED_BYTE
compare_y := *+1
cpy #SELF_MODIFIED_BYTE
WHILE_LT
rts
.endproc ; _ConcatenateDatePart
.proc _DecP8Date
DATELO := tmp_date
DATEHI := tmp_date+1
;;; ====================================================
;;; DecP8Date - Takes a 16-bit P8 date and
;;; calculates the previous day
;;; ----------------------------------------------------
;;; Written 5/30/2025 by John Brooks as part of the
;;; open-source AppleII Desktop code-golf challenge
;;; 64-bytes
;;; ====================================================
;;; 7 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0
;;; +-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+
;;; DATE: | year | month | day |
;;; +-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+
dec DATELO ; dec day
lda DATELO
and #%00011111 ; day
bne done
lsr DATEHI ; C = month high bit, year in DATEHI
lda DATELO
ror ; A = month * 16
sbc #1*16-1 ; dec month * 16 (-1 for c=0)
bne calc_days
dec DATEHI ; year - 1
IF_NEG
copy8 #99, DATEHI ; wrap to year 99 (not 127)
END_IF
lda #12*16 ; month = december
calc_days:
tax ; X = month * 16
sta DATELO
bpl pre_august
eor #1*16 ; 31 days in odd months 1-7 and in even months 8-12
pre_august:
and #1*16
adc #$f0 ; C=1 if 31-day month (except Feb)
lda #30/2
rol ; A = days in new month, 30 or 31
cpx #2*16 ; Is new month == feb?
bne not_feb
lda DATEHI ; C=1 from cpx above
and #3 ; is year divisible by 4?
beq is_leap
clc ; 28 days if not a leap year
is_leap:
lda #28/2 ; if C=1, 29 day leap year
rol
not_feb:
asl DATELO ; 3 month bits in LO, top bit in C
ora DATELO ; merge day in A with 3 month bits
sta DATELO ; save day & month
rol DATEHI ; save year and month high bit
done:
rts
.endproc ; _DecP8Date
.endproc ; ComposeDateString
;;; ============================================================
;;; Look up an icon address.
;;; Inputs: A = icon number
;;; Output: A,X = IconEntry address
.proc GetIconEntry
sta get_icon_entry_params::id
ITK_CALL IconTK::GetIconEntry, get_icon_entry_params
ldax get_icon_entry_params::addr
rts
.endproc ; GetIconEntry
;;; ============================================================
;;; Look up window.
;;; Inputs: A = window id
;;; Output: A,X = Winfo address
.proc GetWindowPtr
asl a
tax
lda win_table,x
pha
lda win_table+1,x
tax
pla
rts
.endproc ; GetWindowPtr
;;; ============================================================
;;; Look up window path.
;;; Input: A = window_id
;;; Output: A,X = path address
.proc GetWindowPath
asl a
tax
lda window_path_addr_table,x
pha
lda window_path_addr_table+1,x
tax
pla
rts
.endproc ; GetWindowPath
;;; ============================================================
;;; Returns window path or a "/" path if 0=desktop is passed
.proc GetWindowOrRootPath
cmp #0
bne GetWindowPath
ldax #str_root_path
rts
str_root_path: PASCAL_STRING "/"
.endproc ; GetWindowOrRootPath
;;; ============================================================
;;; Look up window title.
;;; Input: A = window_id
;;; Output: A,X = title address
.proc GetWindowTitle
asl a
tax
lda window_title_addr_table,x
pha
lda window_title_addr_table+1,x
tax
pla
rts
.endproc ; GetWindowTitle
;;; ============================================================
;;; Inputs: A = icon id (volume or file)
;;; Outputs: Z=1/A=0/`path_buf3` populated with full path on success
;;; Z=0/A=`ERR_INVALID_PATHNAME` if too long
.proc GetIconPath
jsr PushPointers
name_ptr := $06
win_path_ptr := $08
pha
jsr GetIconName
stax name_ptr
pla
jsr GetIconWindow
IF_ZERO
;; Volume - no base path
copy16 #0, win_path_ptr ; base
ELSE
;; File - window path is base path
jsr GetWindowPath
stax win_path_ptr
;; Is there room?
ldy #0
lda (name_ptr),y
clc
adc (win_path_ptr),y
cmp #kMaxPathLength ; not +1 because we'll add '/'
bcs too_long
END_IF
;; Yes, concatenate
jsr JoinPaths ; $08 = base, $06 = file
lda #0
beq finish ; always
;; No, report error
too_long:
lda #ERR_INVALID_PATHNAME
finish:
jsr PopPointers ; do not tail-call optimise!
rts
.endproc ; GetIconPath
;;; ============================================================
;;; Input: A,X = path to copy
;;; Output: populates `src_path_buf` a.k.a. `INVOKER_PREFIX`
.proc CopyToSrcPath
stax @ptr1
stax @ptr2
ldy #0
@ptr1 := *+1
lda SELF_MODIFIED,y
tay
@ptr2 := *+1
: lda SELF_MODIFIED,y
sta src_path_buf,y
dey
bpl :-
rts
.endproc ; CopyToSrcPath
;;; ============================================================
;;; Input: A,X = path to copy
;;; Output: populates `dst_path_buf`
.proc CopyToDstPath
stax @ptr1
stax @ptr2
ldy #0
@ptr1 := *+1
lda SELF_MODIFIED,y
tay
@ptr2 := *+1
: lda SELF_MODIFIED,y
sta dst_path_buf,y
dey
bpl :-
rts
.endproc ; CopyToDstPath
;;; ============================================================
;;; Input: A,X = path to append
;;; Output: appends '/' and path to `src_path_buf` a.k.a. `INVOKER_PREFIX`
.proc AppendFilenameToSrcPath
stax @ptr1
stax @ptr2
;; Append '/'
ldx src_path_buf
inx
copy8 #'/', src_path_buf,x
;; Append new filename
ldy #0
: inx
iny
@ptr1 := *+1
lda SELF_MODIFIED,y
sta src_path_buf,x
@ptr2 := *+1
cpy SELF_MODIFIED
bne :-
stx src_path_buf
rts
.endproc ; AppendFilenameToSrcPath
;;; ============================================================
;;; Input: A,X = path to append
;;; Output: appends '/' and path to `dst_path_buf`
.proc AppendFilenameToDstPath
stax @ptr1
stax @ptr2
;; Append '/'
ldx dst_path_buf
inx
copy8 #'/', dst_path_buf,x
;; Append new filename
ldy #0
: inx
iny
@ptr1 := *+1
lda SELF_MODIFIED,y
sta dst_path_buf,x
@ptr2 := *+1
cpy SELF_MODIFIED
bne :-
stx dst_path_buf
rts
.endproc ; AppendFilenameToDstPath
;;; ============================================================
;;; Draw text right aligned, pascal string address in A,X
;;; String must be in aux or LC memory.
.proc DrawStringRight
params := $6
textptr := $6
textlen := $8
width := $9
dy := $B
stax textptr
jsr AuxLoad
beq ret
sta textlen
inc16 textptr
MGTK_CALL MGTK::TextWidth, params
sub16 #0, width, width
copy16 #0, dy
MGTK_CALL MGTK::Move, width
MGTK_CALL MGTK::DrawText, params
ret: rts
.endproc ; DrawStringRight
;;; ============================================================
;;; Convert icon's coordinates from window to screen
;;; (icon index in A, active window)
;;; NOTE: Avoid calling in a loop; factor out `PrepActiveWindowScreenMapping`
.proc IconWindowToScreen
jsr PushPointers
pha
jsr PrepActiveWindowScreenMapping
pla
jsr GetIconEntry
jsr IconPtrWindowToScreen
jsr PopPointers ; do not tail-call optimise!
rts
.endproc ; IconWindowToScreen
;;; Convert icon's coordinates from window to screen
;;; Inputs: A,X = `IconEntry`, `PrepActiveWindowScreenMapping` called
;;; Trashes $06
.proc IconPtrWindowToScreen
entry_ptr := $6
stax entry_ptr
;; iconx
ldy #IconEntry::iconx
sub16in (entry_ptr),y, map_delta_x, (entry_ptr),y
;; icony
iny
sub16in (entry_ptr),y, map_delta_y, (entry_ptr),y
rts
.endproc ; IconPtrWindowToScreen
;;; ============================================================
;;; Convert icon's coordinates from screen to window
;;; (icon index in A, active window)
;;; NOTE: Avoid calling in a loop; factor out `PrepActiveWindowScreenMapping`
.proc IconScreenToWindow
jsr PushPointers
pha
jsr PrepActiveWindowScreenMapping
pla
jsr GetIconEntry
jsr IconPtrScreenToWindow
jsr PopPointers ; do not tail-call optimise!
rts
.endproc ; IconScreenToWindow
;;; Convert icon's coordinates from screen to window
;;; Inputs: A,X = `IconEntry`, `PrepActiveWindowScreenMapping` called
;;; Trashes $06
.proc IconPtrScreenToWindow
entry_ptr := $6
stax entry_ptr
;; iconx
ldy #IconEntry::iconx
add16in (entry_ptr),y, map_delta_x, (entry_ptr),y
;; icony
iny
add16in (entry_ptr),y, map_delta_y, (entry_ptr),y
rts
.endproc ; IconPtrScreenToWindow
;;; ============================================================
map_delta_x: .word 0
map_delta_y: .word 0
;;; Inits `map_delta_x` and `map_delta_y` for window/screen mapping
;;; for active window.
;;; Inputs: `active_window_id` set
;;; Trashes: $08
.proc PrepActiveWindowScreenMapping
lda active_window_id
FALL_THROUGH_TO PrepWindowScreenMapping
.endproc ; PrepActiveWindowScreenMapping
.proc PrepWindowScreenMapping
winfo_ptr := $8
jsr GetWindowPtr
stax winfo_ptr
;; Compute delta x
sec
ldy #MGTK::Winfo::port + MGTK::GrafPort::maprect + 0
lda (winfo_ptr),y
ldy #MGTK::Winfo::port + MGTK::GrafPort::viewloc + 0
sbc (winfo_ptr),y
sta map_delta_x
ldy #MGTK::Winfo::port + MGTK::GrafPort::maprect + 1
lda (winfo_ptr),y
ldy #MGTK::Winfo::port + MGTK::GrafPort::viewloc + 1
sbc (winfo_ptr),y
sta map_delta_x+1
;; Compute delta y
sec
ldy #MGTK::Winfo::port + MGTK::GrafPort::maprect + 2
lda (winfo_ptr),y
ldy #MGTK::Winfo::port + MGTK::GrafPort::viewloc + 2
sbc (winfo_ptr),y
sta map_delta_y
ldy #MGTK::Winfo::port + MGTK::GrafPort::maprect + 3
lda (winfo_ptr),y
ldy #MGTK::Winfo::port + MGTK::GrafPort::viewloc + 3
sbc (winfo_ptr),y
sta map_delta_y+1
rts
.endproc ; PrepWindowScreenMapping
;;; ============================================================
;;; Input: A = unmasked unit number
;;; Output: A,X=name (length may be 0), Y =
;;; 0 = Disk II
;;; 1 = RAM Disk (including SmartPort RAM Disk)
;;; 2 = Fixed (e.g. ProFile)
;;; 3 = Removable (e.g. UniDisk 3.5)
;;; 4 = AppleTalk file share
;;;
;;; NOTE: Called from Initializer (init) which resides in $800-$1200+
;;;
;;; Name is hardcoded if Disk II, RAM Disk, or AppleTalk; via SmartPort
;;; (re-cased) if the call succeeds, otherwise pointer to empty string.
;;;
;;; Uses start of $800 as a param buffer
;;; Roughly follows:
;;; Technical Note: ProDOS #21: Identifying ProDOS Devices
;;; https://web.archive.org/web/2007/http://web.pdx.edu/~heiss/technotes/pdos/tn.pdos.21.html
.proc GetDeviceTypeImpl
dib_buffer := $800
DEFINE_SP_STATUS_PARAMS status_params, 1, dib_buffer, 3 ; Return Device Information Block (DIB)
;; Avoid Initializer memory ($800-$1200)
block_buffer := $1E00
start:
sta block_params::unit_num
;; Special case for RAM.DRV.SYSTEM/RAMAUX.SYSTEM
IF_A_EQ_ONE_OF #kRamDrvSystemUnitNum, #kRamAuxSystemUnitNum
ldax #str_device_type_ramdisk
ldy #IconType::ramdisk
rts
END_IF
;; Special case for VEDRIVE
jsr DeviceDriverAddress
cmp #<kVEDRIVEDriverAddress
bne :+
cpx #>kVEDRIVEDriverAddress
bne :+
vdrive: ldax #str_device_type_vdrive
ldy #IconType::fileshare
rts
:
;; Special case for VSDRIVE
cmp #<kVSDRIVEDriverAddress
bne :+
cpx #>kVSDRIVEDriverAddress
bne :+
sta ALTZPOFF ; peek at Main/LCBANK1
lda VSDRIVE_SIGNATURE_BYTE
sta ALTZPON ; back to Aux/LCBANK1
cmp #kVSDRIVESignatureValue
beq vdrive
:
;; Is Disk II? A dedicated test that takes advantage of the
;; fact that Disk II devices are never remapped.
lda block_params::unit_num
jsr IsDiskII
IF_ZS
ldax #str_device_type_diskii
ldy #IconType::floppy140
rts
END_IF
;; Look up driver address
lda block_params::unit_num
jsr DeviceDriverAddress ; Z=1 if $Cn
bvs is_sp
jne generic ; not $CnXX, unknown type
;; Firmware driver; maybe SmartPort?
is_sp: lda block_params::unit_num
jsr FindSmartportDispatchAddress
bcs not_sp
stax dispatch
sty status_params::unit_num
;; Execute SmartPort call
dispatch := *+1
jsr SELF_MODIFIED
.byte SPCall::Status
.addr status_params
bcs not_sp
;; Trim trailing whitespace (seen in CFFA)
.scope
ldy dib_buffer+SPDIB::ID_String_Length
IF_NOT_ZERO
DO
lda dib_buffer+SPDIB::Device_Name-1,y
BREAK_IF_A_NE #' '
dey
WHILE_NOT_ZERO
END_IF
done: sty dib_buffer+SPDIB::ID_String_Length
.endscope
.if kBuildSupportsLowercase
;; Case-adjust
.scope
ldy dib_buffer+SPDIB::ID_String_Length
IF_NOT_ZERO
dey
IF_NOT_ZERO
;; Look at prior and current character; if both are alpha,
;; lowercase current.
DO
lda dib_buffer+SPDIB::Device_Name-1,y ; Test previous character
jsr IsAlpha
IF_ZS
lda dib_buffer+SPDIB::Device_Name,y ; Adjust this one if also alpha
jsr IsAlpha
IF_ZS
lda dib_buffer+SPDIB::Device_Name,y
ora #AS_BYTE(~CASE_MASK) ; guarded by `kBuildSupportsLowercase`
sta dib_buffer+SPDIB::Device_Name,y
END_IF
END_IF
dey
WHILE_NOT_ZERO
END_IF
END_IF
.endscope
.endif
;; Check device type
;; Technical Note: SmartPort #4: SmartPort Device Types
;; https://web.archive.org/web/2007/http://web.pdx.edu/~heiss/technotes/smpt/tn.smpt.4.html
lda dib_buffer+SPDIB::Device_Type_Code
ASSERT_EQUALS SPDeviceType::MemoryExpansionCard, 0
IF_ZERO ; $00 = Memory Expansion Card (RAM Disk)
ldax #dib_buffer+SPDIB::ID_String_Length
ldy #IconType::ramdisk
rts
END_IF
cmp #SPDeviceType::SCSICDROM
bne test_size
ldax #dib_buffer+SPDIB::ID_String_Length
ldy #IconType::cdrom
rts
;; NOTE: Codes for 3.5" disk ($01) and 5-1/4" disk ($0A) are not trusted
;; since emulators do weird things.
;; TODO: Is that comment about false positives or false negatives?
;; i.e. if $01 or $0A is seen, can that be trusted?
not_sp:
;; Not SmartPort - try AppleTalk
MLI_CALL READ_BLOCK, block_params
IF_A_EQ #ERR_NETWORK_ERROR
ldax #str_device_type_appletalk
ldy #IconType::fileshare
rts
END_IF
;; RAM-based driver or not SmartPort
generic:
copy8 #0, dib_buffer+SPDIB::ID_String_Length
test_size:
;; SmartPort or Generic Block Device
;; Select either 3.5" Floppy or ProFile icon
;; Old heuristic. Invalid on UDC, etc.
;; and #%00001111
;; cmp #DT_REMOVABLE
;; Better heuristic, but still invalid on UDC, Virtual II, etc.
;; and #%00001000 ; bit 3 = is removable?
;; So instead, just display:
;; <= 280 blocks (140k) as a 5.25" floppy
;; <= 1600 blocks (800k) as a 3.5" floppy
kMax525FloppyBlocks = 280
kMax35FloppyBlocks = 1600
lda block_params::unit_num
jsr GetBlockCount
IF_CC
stax blocks
cmp16 blocks, #kMax525FloppyBlocks+1
bcc f525
cmp16 blocks, #kMax35FloppyBlocks+1
bcc f35
END_IF
ldax #dib_buffer+SPDIB::ID_String_Length
ldy #IconType::profile
rts
f525: ldax #dib_buffer+SPDIB::ID_String_Length
ldy #IconType::floppy140
rts
f35: ldax #dib_buffer+SPDIB::ID_String_Length
ldy #IconType::floppy800
rts
DEFINE_READWRITE_BLOCK_PARAMS block_params, block_buffer, kVolumeDirKeyBlock
blocks: .word 0
.endproc ; GetDeviceTypeImpl
GetDeviceType := GetDeviceTypeImpl::start
;;; ============================================================
;;; Get the block count for a given unit number.
;;; Input: A=unit_number
;;; Output: C=0, blocks in A,X on success, C=1 on error
.proc GetBlockCountImpl
;; Use $800 scratch space right after `dib_buffer`
path := $880 ; becomes length-prefixed path
buffer := path+1 ; length overwritten with '/'
DEFINE_ON_LINE_PARAMS on_line_params,, buffer
start: sta on_line_params::unit_num
MLI_CALL ON_LINE, on_line_params
bcs ret
;; Prefix the path with '/'
lda buffer
and #NAME_LENGTH_MASK
clc
adc #1 ; account for '/'
sta path
copy8 #'/', buffer
param_call GetFileInfo, path
bcs ret
ldax file_info_params::aux_type
ret: rts
.endproc ; GetBlockCountImpl
GetBlockCount := GetBlockCountImpl::start
;;; ============================================================
;;; Create Volume Icon
;;; Input: A = unmasked unit number, Y = index in DEVLST
;;; Output: 0 on success, ProDOS error code on failure
;;; Assert: `cached_window_id` == 0
;;;
;;; NOTE: Called from Initializer (init) which resides in $800-$1200
cvi_data_buffer := $800
DEFINE_ON_LINE_PARAMS on_line_params,, cvi_data_buffer
.proc CreateVolumeIcon
sta unit_number ; unmasked, for `GetDeviceType`
sty devlst_index
and #UNIT_NUM_MASK
sta on_line_params::unit_num
MLI_CALL ON_LINE, on_line_params
IF_CS
error:
pha ; A = error
ldy devlst_index ; remove unit from list
copy8 #0, device_to_icon_map,y
pla ; A = error
rts
END_IF
lda cvi_data_buffer ; dr/slot/name_len
and #NAME_LENGTH_MASK
IF_ZERO
lda cvi_data_buffer+1 ; if name len is zero, second byte is error
bne error ; always
END_IF
param_call AdjustOnLineEntryCase, cvi_data_buffer
jsr _CompareNames
bne error ; duplicate
;; --------------------------------------------------
;; Success, proceed with icon creation
icon_ptr := $6
icon_defn_ptr := $8
offset := $A
jsr PushPointers
ITK_CALL IconTK::AllocIcon, get_icon_entry_params
inc icon_count
;; Assign icon number
lda get_icon_entry_params::id
ldy devlst_index
sta device_to_icon_map,y
inc cached_window_entry_count
ldx cached_window_entry_count
sta cached_window_entry_list-1,x
;; Copy name
copy16 get_icon_entry_params::addr, icon_ptr
ldy #IconEntry::name+kMaxFilenameLength
ldx #kMaxFilenameLength
DO
copy8 cvi_data_buffer,x, (icon_ptr),y
dey
dex
WHILE_POS
;; NOTE: Done with `cvi_data_buffer` at this point,
;; so $800 is free.
;; ----------------------------------------
;; Figure out icon
unit_number := *+1
lda #SELF_MODIFIED_BYTE
jsr GetDeviceType ; uses $800 as DIB buffer
tya ; Y = `IconType`
ldy #IconEntry::type
sta (icon_ptr),y
asl ; * 2
tax
copy16 type_icons_table,x, icon_defn_ptr
;; ----------------------------------------
;; Assign icon flags
ldy #IconEntry::win_flags
copy8 #kIconEntryFlagsDropTarget, (icon_ptr),y
;; Invalid record
ldy #IconEntry::record_num
copy8 #$FF, (icon_ptr),y
;; Assign icon coordinates
devlst_index := *+1
ldy #SELF_MODIFIED_BYTE
lda device_to_icon_map,y
jsr AllocDesktopIconPosition
txa
asl ; * 4 = .sizeof(MGTK::Point)
asl
tax
ldy #IconEntry::iconx
DO
copy8 desktop_icon_coords_table,x, (icon_ptr),y
inx
iny
WHILE_Y_NE #IconEntry::iconx + .sizeof(MGTK::Point)
;; Center it horizontally
ldy #IconResource::maprect + MGTK::Rect::x2
copy16in (icon_defn_ptr),y, offset
lsr16 offset ; offset = (icon_width-1) / 2
ldy #IconEntry::iconx
sub16in (icon_ptr),y, offset, (icon_ptr),y
;; Adjust vertically
ldy #IconResource::maprect + MGTK::Rect::y2
copy16in (icon_defn_ptr),y, offset ; offset = (icon_height-1)
ldy #IconEntry::icony
sub16in (icon_ptr),y, offset, (icon_ptr),y
jsr PopPointers
return #0
;;; Compare a volume name against existing volume icons for drives.
;;; Inputs: String to compare against is in `cvi_data_buffer`
;;; Output: A=0 if not a duplicate, ERR_DUPLICATE_VOLUME if there is a duplicate.
.proc _CompareNames
jsr PushPointers
copy16 #cvi_data_buffer, $06
jsr FindIconByNameInCachedWindow
IF_NOT_ZERO
lda #ERR_DUPLICATE_VOLUME
bne finish ; always
END_IF
lda #0
finish: jsr PopPointers ; do not tail-call optimise!
rts
.endproc ; _CompareNames
.endproc ; CreateVolumeIcon
;;; ============================================================
;;; Allocate/Free an icon position on the DeskTop. The position
;;; is used as an index into `desktop_icon_coords_table` to place
;;; icons; `desktop_icon_usage_table` tracks used/free slots.
;;; Input: A = icon num
;;; Output: X = index into `desktop_icon_coords_table` to use
.proc AllocDesktopIconPosition
pha
ldx #AS_BYTE(-1)
DO
inx
lda desktop_icon_usage_table,x
WHILE_NOT_ZERO
pla
sta desktop_icon_usage_table,x
rts
.endproc ; AllocDesktopIconPosition
;;; Input: A = icon num
.proc FreeDesktopIconPosition
ldx #kMaxVolumes-1
DO
dex
WHILE_A_NE desktop_icon_usage_table,x
copy8 #0, desktop_icon_usage_table,x
rts
.endproc ; FreeDesktopIconPosition
;;; ============================================================
.proc RemoveIconFromWindow
ldx cached_window_entry_count
dex
DO
cmp cached_window_entry_list,x
beq remove
dex
WHILE_POS
rts
remove:
copy8 cached_window_entry_list+1,x, cached_window_entry_list,x
inx
cpx cached_window_entry_count
bne remove
dec cached_window_entry_count
rts
.endproc ; RemoveIconFromWindow
;;; ============================================================
;;; Search the window->dir_icon mapping table.
;;; Inputs: A = icon number
;;; Outputs: Z=1 && N=0 if found, X = index (0-7), A unchanged
.proc FindWindowIndexForDirIcon
ldx #kMaxDeskTopWindows-1
DO
BREAK_IF_A_EQ window_to_dir_icon_table,x
dex
WHILE_POS
rts
.endproc ; FindWindowIndexForDirIcon
;;; ============================================================
kMaxAnimationStep = 7
.proc AnimateWindowImpl
ptr := $06
rect_table := $800
ENTRY_POINTS_FOR_BIT7_FLAG close, open, close_flag
sta icon_param
txa ; A = window_id
win_rect := rect_table + kMaxAnimationStep * .sizeof(MGTK::Rect)
icon_rect := rect_table
IF_NS
;; --------------------------------------------------
;; Use desktop rect
copy16 #0, win_rect + MGTK::Rect::x1
copy16 #kMenuBarHeight, win_rect + MGTK::Rect::y1
copy16 #kScreenWidth-1, win_rect + MGTK::Rect::x2
copy16 #kScreenHeight-1, win_rect + MGTK::Rect::y2
ELSE
;; --------------------------------------------------
;; Get window rect - used as last rect
jsr ApplyWinfoToWindowGrafport
;; Convert viewloc and maprect to bounding rect
viewloc := window_grafport+MGTK::GrafPort::viewloc
maprect := window_grafport+MGTK::GrafPort::maprect
COPY_STRUCT MGTK::Point, viewloc, win_rect + MGTK::Rect::topleft
ldx #2 ; loop over dimensions
DO
sub16 maprect+MGTK::Rect::bottomright,x, maprect+MGTK::Rect::topleft,x, win_rect + MGTK::Rect::bottomright,x
add16 win_rect + MGTK::Rect::topleft,x, win_rect + MGTK::Rect::bottomright,x, win_rect + MGTK::Rect::bottomright,x
dex ; next dimension
dex
WHILE_POS
END_IF
;; --------------------------------------------------
;; Get icon position - used as first rect
ITK_CALL IconTK::GetIconBounds, icon_param ; inits `tmp_rect`
COPY_BLOCK tmp_rect, icon_rect
;; --------------------------------------------------
;; Compute intermediate rects
delta := $06
;; Iterate over all 4 rectangle edges
ldy #0 ; Y = offset into MGTK::Rect
DO
sub16 win_rect,y, icon_rect,y, delta
;; Iterate over all N animation steps
ldx #0 ; X = step
DO
txa ; A = step
pha
asr16 delta ; divide by two (signed)
;; Address of target rect
tya ; offset *into* rect
clc
adc table,x ; plus offset *of* rect
tax
;; Apply delta
add16 rect_table,y, delta, rect_table,x
pla ; A = step
tax ; X = step
inx
WHILE_X_NE #kMaxAnimationStep-1
iny
iny
WHILE_Y_NE #.sizeof(MGTK::Rect)
;; --------------------------------------------------
;; Animate it
bit close_flag
IF_NC
jmp AnimateWindowOpenImpl
END_IF
jmp AnimateWindowCloseImpl
close_flag:
.byte 0
table:
.repeat main::kMaxAnimationStep, i
.byte (main::kMaxAnimationStep - 1 - i) * .sizeof(MGTK::Rect)
.endrepeat
.endproc ; AnimateWindowImpl
AnimateWindowClose := AnimateWindowImpl::close
AnimateWindowOpen := AnimateWindowImpl::open
;;; ============================================================
.proc AnimateWindowOpenImpl
;; Loop N = 0 to 13
;; If N in 0..11, draw N
;; If N in 2..13, erase N-2 (i.e. 0..11, 2 behind)
copy8 #0, step
jsr InitSetDesktopPort
DO
;; If N in 0..11, draw N
lda step ; draw the Nth
IF_A_LT #kMaxAnimationStep+1
jsr FrameTableRect
END_IF
;; If N in 2..13, erase N-2 (i.e. 0..11, 2 behind)
lda step
sec
sbc #2 ; erase the (N-2)th
IF_POS
jsr FrameTableRect
END_IF
inc step
step := *+1
lda #SELF_MODIFIED_BYTE
WHILE_A_NE #kMaxAnimationStep+3
rts
.endproc ; AnimateWindowOpenImpl
;;; ============================================================
.proc AnimateWindowCloseImpl
;; Loop N = 11 to -2
;; If N in 0..11, draw N
;; If N in -2..9, erase N+2 (0..11, i.e. 2 behind)
copy8 #kMaxAnimationStep, step
jsr InitSetDesktopPort
DO
;; If N in 0..11, draw N
lda step
IF_POS
jsr FrameTableRect
END_IF
;; If N in -2..9, erase N+2 (0..11, i.e. 2 behind)
lda step
clc
adc #2
IF_A_LT #kMaxAnimationStep+1
jsr FrameTableRect
END_IF
dec step
step := *+1
lda #SELF_MODIFIED_BYTE
cmp #AS_BYTE(-3)
WHILE_NE
rts
.endproc ; AnimateWindowCloseImpl
;;; ============================================================
;;; Inputs: A = rect in `rect_table` to frame
.proc FrameTableRect
rect_table := $800
;; Compute offset into rect table
asl a
asl a
asl a
clc
adc #.sizeof(MGTK::Rect)-1
tax
;; Copy rect to draw
ldy #.sizeof(MGTK::Rect)-1
DO
copy8 rect_table,x, tmp_rect,y
dex
dey
WHILE_POS
FALL_THROUGH_TO FrameTmpRect
.endproc ; FrameTableRect
.proc FrameTmpRect
MGTK_CALL MGTK::SetPattern, checkerboard_pattern
jsr SetPenModeXOR
MGTK_CALL MGTK::FrameRect, tmp_rect
rts
.endproc ; FrameTmpRect
;;; ============================================================
;;; Operations performed on selection
;;;
;;; These operate on the entire selection recursively, e.g.
;;; computing size, deleting, copying, etc., and share common
;;; logic.
;;;
;;; Importantly, the procs in this `operations` scope are modal
;;; operations. This allows this code to be paged out when other modal
;;; operations are performed, such as accessories that need a large
;;; buffer.
;;; ============================================================
.enum PromptResult
ok = 0
cancel = 1
.endenum
;;; ============================================================
;;; For drop onto window/icon, compute target prefix.
;;; Input: `drag_drop_params::target` set
;;; Output: C=0, `path_buf4` populated with target path
;;; C=1 on error (e.g. path too long); alert is shown
.proc SetPathBuf4FromDragDropResult
;; Is drop on a window or an icon?
;; hi bit clear = target is an icon
;; hi bit set = target is a window; get window number
lda drag_drop_params::target
bpl target_is_icon
;; Drop is on a window
and #%01111111 ; get window id
jsr GetWindowPath
jsr CopyToBuf4
clc
rts ; success
;; Drop is on an icon.
target_is_icon:
jsr GetIconPath ; `path_buf3` set to path; A=0 on success
IF_NE
jsr ShowAlert
sec ; failure
rts
END_IF
param_call CopyToBuf4, path_buf3
clc ; success
rts
.endproc ; SetPathBuf4FromDragDropResult
;;; ============================================================
.scope operations
;;; ============================================================
;;; Operations where source/target paths are passed by callers
kOperationFlagsNone = %00000000
kOperationFlagsCheckBadCopy = %01000000
kOperationFlagsCheckVolFree = %10000000
;;; File > Duplicate - for a single file copy
;;; Caller sets `path_buf3` (source) and `path_buf4` (destination)
.proc DoCopyFile
copy8 #kOperationFlagsCheckBadCopy, operation_flags
copy8 #0, move_flags
tsx
stx saved_stack
jsr PrepTraversalCallbacksForEnumeration
jsr OpenCopyProgressDialog
jsr SetDstIsAppleShareFlag ; uses `path_buf4`, may fail
jsr EnumerationProcessSelectedFile
jsr PrepTraversalCallbacksForCopy
FALL_THROUGH_TO DoCopyCommon
.endproc ; DoCopyFile
.proc DoCopyCommon
jsr CopyProcessNotSelectedFile
jsr InvokeOperationCompleteCallback
FALL_THROUGH_TO FinishOperation
.endproc ; DoCopyCommon
FinishOperation:
return #kOperationSucceeded
;;; Shortcuts > Run a Shortcut... w/ "Copy to RAMCard"/"at first use"
;;; Caller sets `path_buf3` (source) and `path_buf4` (destination)
.proc DoCopyToRAM
copy8 #0, move_flags
copy8 #kOperationFlagsCheckVolFree, operation_flags
CLEAR_BIT7_FLAG dst_is_appleshare_flag ; by definition, not AppleShare
tsx
stx saved_stack
jsr PrepTraversalCallbacksForEnumeration
jsr OpenCopyProgressDialog
jsr EnumerationProcessSelectedFile
jsr PrepTraversalCallbacksForDownload
jmp DoCopyCommon
.endproc ; DoCopyToRAM
;;; ============================================================
;;; Operations on selection (source)
;;; File > Copy To...
;;; Drag / Drop (to anything but Trash)
;;; Caller sets `path_buf4` (destination)
.proc DoCopyOrMoveSelection
lda selected_window_id
IF_NOT_ZERO ; dragging volume always copies
jsr GetWindowPath
jsr CheckMoveOrCopy
END_IF
SKIP_NEXT_2_BYTE_INSTRUCTION
ep_always_copy:
lda #0 ; do not convert to `copy8`!
sta move_flags
copy8 #kOperationFlagsCheckBadCopy, operation_flags
tsx
stx saved_stack
jsr PrepTraversalCallbacksForEnumeration
jsr OpenCopyProgressDialog
jsr SetDstIsAppleShareFlag ; uses `path_buf4`, may fail
jmp OperationOnSelection
.endproc ; DoCopyOrMoveSelection
DoCopySelection := DoCopyOrMoveSelection::ep_always_copy
;;; File > Delete
;;; Drag / Drop to Trash (except volumes)
.proc DoDeleteSelection
copy8 #0, move_flags
copy8 #kOperationFlagsNone, operation_flags
tsx
stx saved_stack
jsr PrepTraversalCallbacksForEnumeration
jsr OpenDeleteProgressDialog
FALL_THROUGH_TO OperationOnSelection
.endproc ; DoDeleteSelection
;;; --------------------------------------------------
;;; Start the actual operation
.proc OperationOnSelection
;; Selection is iterated twice, once to get a file count, then
;; again to do the real work.
iterate_selection:
ldx #0
DO
txa ; X = index
pha ; A = index
lda selected_icon_list,x
IF_A_NE trash_icon_num
jsr GetIconPath ; `path_buf3` set to path; A=0 on success
jne ShowErrorAlert ; too long
;; During selection iteration, allow Escape to cancel the operation.
jsr CheckCancel
;; If copy, validate the source vs. target during enumeration phase
;; NOTE: Here rather than in `CopyProcessSelectedFile` because we don't
;; run this for copy using paths (i.e. Duplicate, Copy to RAMCard)
bit do_op_flag
IF_NC
bit operation_flags
ASSERT_EQUALS operations::kOperationFlagsCheckBadCopy, $40
IF_VS
jsr CopyPathsFromBufsToSrcAndDst
;; Check for copying/moving an item into itself.
copy16 #src_path_buf, $06
copy16 #dst_path_buf, $08
jsr IsPathPrefixOf
IF_NE
param_call ShowAlertParams, AlertButtonOptions::OK, aux::str_alert_move_copy_into_self
jmp CloseFilesCancelDialogWithCanceledResult
END_IF
jsr AppendSrcPathLastSegmentToDstPath
;; Check for replacing an item with itself or a descendant.
copy16 #dst_path_buf, $06
copy16 #src_path_buf, $08
jsr IsPathPrefixOf
IF_NE
param_call ShowAlertParams, AlertButtonOptions::OK, aux::str_alert_bad_replacement
jmp CloseFilesCancelDialogWithCanceledResult
END_IF
END_IF
END_IF
jsr OpProcessSelectedFile
END_IF
pla ; A = index
tax ; X = index
inx
WHILE_X_NE selected_icon_count
;; --------------------------------------------------
;; Done icons - did we complete the operation?
bit do_op_flag
IF_NS
jsr InvokeOperationCompleteCallback
return #0
END_IF
;; No, we finished enumerating. Now do the real work.
jsr InvokeOperationConfirmCallback
jsr InvokeOperationPrepTraversalCallback
;; And iterate selection again.
jmp iterate_selection
.endproc ; OperationOnSelection
;;; ============================================================
saved_stack:
.byte 0
operation_flags:
.byte 0
;; bit 7 set = move, clear = copy
;; bit 6 set = same volume move and relink supported
move_flags:
.byte 0
;; bit 7 set = "all" selected in Yes / No / All prompt
all_flag:
.byte 0
;; bit 7 set = destination is an AppleShare (network) drive
dst_is_appleshare_flag:
.byte 0
;;; ============================================================
;;; Memory Map
;;; ...
;;; $1F80 - $1FFF - dst path buffer
;;; $1F00 - $1F7F - unused
;;; $1500 - $1EFF - file data buffer
;;; $1100 - $14FF - dst file I/O buffer
;;; $0D00 - $10FF - src file I/O buffer
;;; $0C00 - $0CFF - dir data buffer
;;; $0800 - $0BFF - src dir I/O buffer
;;; ...
dir_io_buffer := $800 ; 1024 bytes for I/O
dir_data_buffer := $C00 ; 256 bytes for directory data
src_io_buffer := $D00 ; 1024 bytes for I/O
dst_io_buffer := $1100 ; 1024 bytes for I/O
copy_buffer := $1500 ; Read/Write buffer
kCopyBufferSize = $1F00 - copy_buffer
.assert copy_buffer + kCopyBufferSize <= dst_path_buf, error, "Buffer overlap"
.assert (kCopyBufferSize .mod BLOCK_SIZE) = 0, error, "integral number of blocks needed for sparse copies and performance"
;; TODO: Is $800 safe here, given this is called on retry?
DEFINE_ON_LINE_PARAMS on_line_all_drives_params,, $800
block_buffer := copy_buffer
DEFINE_READWRITE_BLOCK_PARAMS block_params, block_buffer, SELF_MODIFIED
DEFINE_READWRITE_BLOCK_PARAMS vol_key_block_params, block_buffer, kVolumeDirKeyBlock
;;; ============================================================
;;; Callbacks used during operations. There are two sets:
;;;
;;; * Callbacks for the overall operation lifecycle
;;; * Callbacks for selection and file system traversal
;;;
;;; These are separate because the latter are swapped out between the
;;; initial enumeration phase and the actual operation phase.
;;; NOTE: These are referenced by indirect JMP and *must not*
;;; cross page boundaries.
PAD_IF_NEEDED_TO_AVOID_PAGE_BOUNDARY
operation_lifecycle_callbacks:
operation_enumeration_callback: .addr SELF_MODIFIED
operation_complete_callback: .addr SELF_MODIFIED
operation_confirm_callback: .addr SELF_MODIFIED
operation_prep_callback: .addr SELF_MODIFIED
kOpLifecycleCallbacksSize = * - operation_lifecycle_callbacks
;;; NOTE: These are referenced by indirect JMP and *must not*
;;; cross page boundaries.
operation_traversal_callbacks:
op_process_selected_file_callback: .addr SELF_MODIFIED
op_process_dir_entry_callback: .addr SELF_MODIFIED
op_finish_directory_callback: .addr SELF_MODIFIED
kOpTraversalCallbacksSize = * - operation_traversal_callbacks
;;; ------------------------------------------------------------
;;; Operation lifecycle callbacks
;;; Called for each file during enumeration; A,X = file count
InvokeOperationEnumerationCallback:
jmp (operation_enumeration_callback)
;;; Called on operation completion (success or failure)
InvokeOperationCompleteCallback:
jmp (operation_complete_callback)
;;; Called once enumeration is complete, to confirm the operation.
InvokeOperationConfirmCallback:
jmp (operation_confirm_callback)
;;; Called once selection enumeration is complete, to prepare for the actual op.
InvokeOperationPrepTraversalCallback:
jmp (operation_prep_callback)
;;; ------------------------------------------------------------
;;; Selection and file system traversal callbacks
;;; Called for each file in the selection
OpProcessSelectedFile:
jmp (op_process_selected_file_callback)
;;; Called for each file in a directory
OpProcessDirectoryEntry:
jmp (op_process_dir_entry_callback)
;;; Called when a directory is complete
OpFinishDirectory:
jmp (op_finish_directory_callback)
;;; ------------------------------------------------------------
DoNothing: rts
;;; bit7=0 for count/size pass, bit7=1 for actual operation
do_op_flag:
.byte 0
;;; ============================================================
;;; Generic Recursive Operation Logic
;;; ============================================================
;;; TODO: Unify with `../lib/recursive_copy.s`
pathname_src := src_path_buf
pathname_dst := dst_path_buf
;;; ============================================================
;;; Directory enumeration parameter blocks and state
;; 4 bytes is .sizeof(SubdirectoryHeader) - .sizeof(FileEntry)
kBlockPointersSize = 4
;; Blocks are 512 bytes, 13 entries of 39 bytes each leaves 5 bytes between.
;; Except first block, directory header is 39+4 bytes, leaving 1 byte, but then
;; block pointers are the next 4.
kMaxPaddingBytes = 5
ASSERT_EQUALS .sizeof(SubdirectoryHeader) - .sizeof(FileEntry), kBlockPointersSize
PARAM_BLOCK, dir_data_buffer
;;; Read buffers
buf_block_pointers .res kBlockPointersSize
buf_padding_bytes .res kMaxPaddingBytes
file_entry .tag FileEntry
;;; State for directory recursion
recursion_depth .byte ; How far down the directory structure are we
entries_per_block .byte ; Number of file entries per directory block
entry_index_in_dir .word
target_index .word
;;; During directory traversal, the number of file entries processed
;;; at the current level is pushed here, so that following a descent
;;; the previous entries can be skipped.
index_stack_lo .res ::kDirStackSize
index_stack_hi .res ::kDirStackSize
stack_index .byte
entry_index_in_block .byte
dir_data_buffer_end .byte
END_PARAM_BLOCK
.assert dir_data_buffer_end - dir_data_buffer <= 256, error, "too big"
DEFINE_OPEN_PARAMS open_src_dir_params, pathname_src, dir_io_buffer
DEFINE_READWRITE_PARAMS read_block_pointers_params, buf_block_pointers, kBlockPointersSize ; For skipping prev/next pointers in directory data
DEFINE_READWRITE_PARAMS read_src_dir_entry_params, file_entry, .sizeof(FileEntry)
DEFINE_READWRITE_PARAMS read_padding_bytes_params, buf_padding_bytes, kMaxPaddingBytes
DEFINE_CLOSE_PARAMS close_src_dir_params
;;; ============================================================
;;; Iterate directory entries
;;; Inputs: `pathname_src` points at source directory
.proc ProcessDirectory
lda #0
sta recursion_depth
sta stack_index
jsr _OpenSrcDir
loop:
jsr _ReadFileEntry
IF_ZERO
param_call AdjustFileEntryCase, file_entry
lda file_entry + FileEntry::storage_type_name_length
beq loop ; deleted
pha ; A = `storage_type_name_length`
;; Requires `storage_type_name_length` to be intact
jsr _ConvertFileEntryToFileInfo
;; Simplify to length-prefixed string
pla ; A = `storage_type_name_length`
and #NAME_LENGTH_MASK
sta file_entry
jsr CheckCancel
CLEAR_BIT7_FLAG entry_err_flag
jsr OpProcessDirectoryEntry
bit entry_err_flag ; don't recurse if the copy failed
bmi loop
lda file_entry + FileEntry::file_type
cmp #FT_DIRECTORY
bne loop ; and don't recurse unless it's a directory
;; Recurse into child directory
jsr _DescendDirectory
inc recursion_depth
bpl loop ; always
END_IF
lda recursion_depth
IF_NOT_ZERO
jsr _AscendDirectory
dec recursion_depth
bpl loop ; always
END_IF
jmp _CloseSrcDir
.endproc ; ProcessDirectory
;;; Set on error during copying of a single file
entry_err_flag: .byte 0 ; bit7
;;; ============================================================
;;; Populate `src_file_info_params` from `file_entry`
.proc _ConvertFileEntryToFileInfo
ldx #kMapSize-1
DO
ldy map,x
copy8 file_entry,y, src_file_info_params::access,x
dex
WHILE_POS
;; Fix `storage_type`
ldx #4
DO
lsr src_file_info_params::storage_type
dex
WHILE_NOT_ZERO
rts
;;; index is offset in `src_file_info_params`, value is offset in `file_entry`
map: .byte FileEntry::access
.byte FileEntry::file_type
.byte FileEntry::aux_type
.byte FileEntry::aux_type+1
.byte FileEntry::storage_type_name_length
.byte FileEntry::blocks_used
.byte FileEntry::blocks_used+1
.byte FileEntry::mod_date
.byte FileEntry::mod_date+1
.byte FileEntry::mod_time
.byte FileEntry::mod_time+1
.byte FileEntry::creation_date
.byte FileEntry::creation_date+1
.byte FileEntry::creation_time
.byte FileEntry::creation_time+1
kMapSize = * - map
.endproc ; _ConvertFileEntryToFileInfo
;;; ============================================================
.proc _PushIndexToStack
ldx stack_index
copy8 target_index, index_stack_lo,x
copy8 target_index+1, index_stack_hi,x
inc stack_index
rts
.endproc ; _PushIndexToStack
;;; ============================================================
.proc _PopIndexFromStack
dec stack_index
ldx stack_index
copy8 index_stack_lo,x, target_index
copy8 index_stack_hi,x, target_index+1
rts
.endproc ; _PopIndexFromStack
;;; ============================================================
;;; Open the source directory for reading, skipping header.
;;; Inputs: `pathname_src` set to dir
.proc _OpenSrcDir
lda #0
sta entry_index_in_dir
sta entry_index_in_dir+1
sta entry_index_in_block
retry: MLI_CALL OPEN, open_src_dir_params
IF_CS
ldx #AlertButtonOptions::TryAgainCancel
jsr ShowAlertOption
ASSERT_EQUALS ::kAlertResultTryAgain, 0
beq retry ; `kAlertResultTryAgain` = 0
jmp CloseFilesCancelDialogWithFailedResult
END_IF
lda open_src_dir_params::ref_num
sta read_block_pointers_params::ref_num
sta read_src_dir_entry_params::ref_num
sta read_padding_bytes_params::ref_num
sta close_src_dir_params::ref_num
;; Skip over prev/next block pointers in header
retry2: MLI_CALL READ, read_block_pointers_params
IF_CS
ldx #AlertButtonOptions::TryAgainCancel
jsr ShowAlertOption
ASSERT_EQUALS ::kAlertResultTryAgain, 0
beq retry2 ; `kAlertResultTryAgain` = 0
jmp CloseFilesCancelDialogWithFailedResult
END_IF
;; Header size is next/prev blocks + a file entry
copy8 #13, entries_per_block ; so `_ReadFileEntry` doesn't immediately advance
jsr _ReadFileEntry ; read the rest of the header
ASSERT_EQUALS .sizeof(SubdirectoryHeader), .sizeof(FileEntry) + 4
copy8 file_entry-4 + SubdirectoryHeader::entries_per_block, entries_per_block
rts
.endproc ; _OpenSrcDir
;;; ============================================================
.proc _CloseSrcDir
retry: MLI_CALL CLOSE, close_src_dir_params
IF_CS
ldx #AlertButtonOptions::TryAgainCancel
jsr ShowAlertOption
ASSERT_EQUALS ::kAlertResultTryAgain, 0
beq retry ; `kAlertResultTryAgain` = 0
jmp CloseFilesCancelDialogWithFailedResult
END_IF
rts
.endproc ; _CloseSrcDir
;;; ============================================================
;;; Read the next file entry in the directory into `file_entry`
;;; NOTE: Also used to read the vol/dir header.
.proc _ReadFileEntry
inc16 entry_index_in_dir
retry: MLI_CALL READ, read_src_dir_entry_params
IF_CS
cmp #ERR_END_OF_FILE
beq eof
ldx #AlertButtonOptions::TryAgainCancel
jsr ShowAlertOption
ASSERT_EQUALS ::kAlertResultTryAgain, 0
beq retry ; `kAlertResultTryAgain` = 0
jmp CloseFilesCancelDialogWithFailedResult
END_IF
inc entry_index_in_block
lda entry_index_in_block
IF_A_GE entries_per_block
;; Advance to first entry in next "block"
copy8 #0, entry_index_in_block
MLI_CALL READ, read_padding_bytes_params
;; TODO: Handle error here?
END_IF
return #0
eof: return #$FF
.endproc ; _ReadFileEntry
;;; ============================================================
;;; Record the current index in the current directory, and
;;; recurse to the child directory in `file_entry`.
.proc _DescendDirectory
copy16 entry_index_in_dir, target_index
jsr _CloseSrcDir
jsr _PushIndexToStack
jsr AppendFileEntryToSrcPath
jmp _OpenSrcDir
.endproc ; _DescendDirectory
;;; ============================================================
;;; Close the current directory and resume iterating in the
;;; parent directory where we left off.
.proc _AscendDirectory
jsr _CloseSrcDir
jsr OpFinishDirectory
jsr RemoveSrcPathSegment
jsr _PopIndexFromStack
jsr _OpenSrcDir
: cmp16 entry_index_in_dir, target_index
IF_LT
jsr _ReadFileEntry
jmp :-
END_IF
rts
.endproc ; _AscendDirectory
;;; ============================================================
;;; Append name at `file_entry` to path at `pathname_src`
.proc AppendFileEntryToSrcPath
param_jump AppendFilenameToSrcPath, file_entry
.endproc ; AppendFileEntryToSrcPath
;;; ============================================================
;;; Remove segment from path at `pathname_src`
.proc RemoveSrcPathSegment
param_jump RemovePathSegment, pathname_src
.endproc ; RemoveSrcPathSegment
;;; ============================================================
;;; Append name at `file_entry` to path at `pathname_dst`
.proc AppendFileEntryToDstPath
param_jump AppendFilenameToDstPath, file_entry
.endproc ; AppendFileEntryToDstPath
;;; ============================================================
;;; Remove segment from path at `pathname_dst`
.proc RemoveDstPathSegment
param_jump RemovePathSegment, pathname_dst
.endproc ; RemoveDstPathSegment
;;; ============================================================
;;; Generic Helpers
;;; ============================================================
;;; Verify that file is not forked (etc); if it is an OK/Cancel alert is shown.
;;; If the user selects cancel, the operation is cancelled.
;;;
;;; Input: A=`storage_type`
;;; Output: C=0 if supported type, C=1 if unsupported but user picks OK.
;;; Exception: If user selects Cancel, `CloseFilesCancelDialogWithFailedResult` is invoked.
.proc ValidateStorageType
IF_A_NE_ALL_OF #ST_VOLUME_DIRECTORY, #ST_LINKED_DIRECTORY
IF_A_GE #ST_TREE_FILE+1 ; only seedling/sapling/tree supported
;; Unsupported type - show error, and either abort or return failure
param_call ShowAlertParams, AlertButtonOptions::OKCancel, aux::str_alert_unsupported_type
jsr SetCursorWatch ; preserves A
cmp #kAlertResultCancel
jeq CloseFilesCancelDialogWithFailedResult
sec
rts
END_IF
END_IF
;; Return success
clc
rts
.endproc ; ValidateStorageType
;;; ============================================================
;;; Input: Destination path in `path_buf4`
;;; Output: `dst_is_appleshare_flag` is set
.proc SetDstIsAppleShareFlag
CLEAR_BIT7_FLAG dst_is_appleshare_flag
;; Issue a `GET_FILE_INFO` on destination to set `DEVNUM`
retry: param_call GetFileInfo, path_buf4
IF_CS
jsr ShowErrorAlertDst
jmp retry
END_IF
;; Try to read a block off device; if AppleShare will fail.
copy8 DEVNUM, vol_key_block_params::unit_num
MLI_CALL READ_BLOCK, vol_key_block_params
IF_A_EQ #ERR_NETWORK_ERROR
SET_BIT7_FLAG dst_is_appleshare_flag
END_IF
rts
.endproc ; SetDstIsAppleShareFlag
;;; ============================================================
;;; "Copy" (including Drag/Drop/Move) files state and logic
;;; ============================================================
;;; ============================================================
;;; File copy parameter blocks
;; Also used by "Delete"
DEFINE_DESTROY_PARAMS destroy_src_params, src_path_buf
DEFINE_DESTROY_PARAMS destroy_dst_params, dst_path_buf
;; Used for both files and directories
DEFINE_CREATE_PARAMS create_params3, dst_path_buf, ACCESS_DEFAULT
DEFINE_OPEN_PARAMS open_src_params, src_path_buf, src_io_buffer
DEFINE_OPEN_PARAMS open_dst_params, dst_path_buf, dst_io_buffer
DEFINE_READWRITE_PARAMS read_src_params, copy_buffer, kCopyBufferSize
DEFINE_READWRITE_PARAMS write_dst_params, copy_buffer, kCopyBufferSize
DEFINE_SET_MARK_PARAMS mark_src_params, 0
DEFINE_SET_MARK_PARAMS mark_dst_params, 0
DEFINE_CLOSE_PARAMS close_src_params
DEFINE_CLOSE_PARAMS close_dst_params
;;; `CopyProcessSelectedFile`
;;; - delegates to `CopyProcessDirectoryEntry`; if op=move, fixes up paths
;;; `CopyProcessDirectoryEntry`
;;; - copies file/directory
;;; `CopyFinishDirectory`
;;; - if dir and op=move, deletes dir
;;; Traversal callbacks for copy operation (`operation_traversal_callbacks`)
operation_traversal_callbacks_for_copy:
.addr CopyProcessSelectedFile
.addr CopyProcessDirectoryEntry
.addr CopyFinishDirectory
ASSERT_TABLE_SIZE operation_traversal_callbacks_for_copy, kOpTraversalCallbacksSize
.proc OpenCopyProgressDialog
COPY_BYTES kOpLifecycleCallbacksSize, operation_lifecycle_callbacks_for_copy, operation_lifecycle_callbacks
jmp OpenProgressDialog
.proc _CopyDialogEnumerationCallback
stax file_count
stax total_count
jsr SetPortForProgressDialog
bit move_flags
IF_NC
param_call DrawProgressDialogLabel, 0, aux::str_copy_copying
ELSE
param_call DrawProgressDialogLabel, 0, aux::str_move_moving
END_IF
jmp DrawFileCountWithSuffix
.endproc ; _CopyDialogEnumerationCallback
;;; Lifecycle callbacks for copy operation (`operation_lifecycle_callbacks`)
operation_lifecycle_callbacks_for_copy:
.addr _CopyDialogEnumerationCallback
.addr CloseProgressDialog
.addr operations::DoNothing
.addr PrepTraversalCallbacksForCopy
ASSERT_TABLE_SIZE operation_lifecycle_callbacks_for_copy, operations::kOpLifecycleCallbacksSize
.endproc ; OpenCopyProgressDialog
;;; ============================================================
.proc PrepTraversalCallbacksForCopy
COPY_BYTES kOpTraversalCallbacksSize, operation_traversal_callbacks_for_copy, operation_traversal_callbacks
CLEAR_BIT7_FLAG operations::all_flag
SET_BIT7_FLAG do_op_flag
rts
.endproc ; PrepTraversalCallbacksForCopy
;;; ============================================================
;;; "Download" - shares heavily with Copy
.proc PrepTraversalCallbacksForDownload
COPY_BYTES kOpTraversalCallbacksSize, operation_traversal_callbacks_for_copy, operation_traversal_callbacks
SET_BIT7_FLAG operations::all_flag
SET_BIT7_FLAG do_op_flag
rts
.endproc ; PrepTraversalCallbacksForDownload
;;; ============================================================
;;; Handle copying of a file.
;;; Calls into the recursion logic of `ProcessDirectory` as necessary.
;;; Used for these operations:
;;; * File > Duplicate (via `not_selected` entry point) - operates on passed path, `operation_flags` = `kOperationFlagsCheckBadCopy`
;;; * Run a Shortcut (via `not_selected` entry point) - operates on passed path, `operation_flags` = `kOperationFlagsCheckVolFree`
;;; * File > Copy To - operates on selection, `operation_flags` = `kOperationFlagsCheckBadCopy`
;;; * Drag/Drop (to non-Trash) - operates on selection, `operation_flags` = `kOperationFlagsCheckBadCopy`
.proc CopyProcessFileImpl
ENTRY_POINTS_FOR_BIT7_FLAG selected, not_selected, use_selection_flag
jsr CopyPathsFromBufsToSrcAndDst
;; If "Copy to RAMCard", make sure there's enough room.
bit operations::operation_flags
ASSERT_EQUALS operations::kOperationFlagsCheckVolFree, $80
IF_NS
jsr CheckVolBlocksFree
END_IF
use_selection_flag := *+1
lda #SELF_MODIFIED_BYTE
IF_NS
;; File > Copy To...
;; Drag/Drop
;; Use last segment of source for destination (e.g. for Copy/Move)
jsr AppendSrcPathLastSegmentToDstPath
ELSE
;; File > Duplicate
;; Shortcuts > Run a Shortcut...
;; Used passed filename for destination (e.g. for Duplicate)
param_call AppendFilenameToDstPath, filename_buf
END_IF
;; Paths are set up - update dialog
jsr CopyUpdateProgress
;; Populate `src_file_info_params`
retry: jsr GetSrcFileInfo
IF_CS
jsr ShowErrorAlert
jmp retry
END_IF
;; Regular file or directory?
lda src_file_info_params::storage_type
IF_A_NE_ALL_OF #ST_VOLUME_DIRECTORY, #ST_LINKED_DIRECTORY
;; --------------------------------------------------
;; File
jsr ValidateStorageType
bcs done
jsr _CopyCreateFile
bcs done
bit move_flags ; same volume relink move?
IF_VS
jmp RelinkFile
END_IF
jsr _CopyNormalFile
jmp MaybeFinishFileMove
END_IF
;; --------------------------------------------------
;; Directory
jsr _CopyCreateFile
bcs done
bit move_flags ; same volume relink move?
IF_VS
jsr RelinkFile
jmp NotifyPathChanged
END_IF
;; Copy directory contents
jsr ProcessDirectory
jsr GetAndApplySrcInfoToDst ; copy modified date/time
jsr MaybeFinishFileMove
bit move_flags
IF_NS
jsr NotifyPathChanged
END_IF
done:
rts
.endproc ; CopyProcessFileImpl
;;; Operations on selection (e.g. drag/drop, File > Copy To..., etc)
CopyProcessSelectedFile := CopyProcessFileImpl::selected
;;; Operations on paths (e.g. File > Duplicate, Copy to RAMCard, etc)
CopyProcessNotSelectedFile := CopyProcessFileImpl::not_selected
;;; ============================================================
;;; Called by `ProcessDirectory` to process a single file
.proc CopyProcessDirectoryEntry
jsr AppendFileEntryToDstPath
jsr AppendFileEntryToSrcPath
jsr CopyUpdateProgress
;; Called with `src_file_info_params` pre-populated
lda src_file_info_params::storage_type
IF_A_NE #ST_LINKED_DIRECTORY
;; --------------------------------------------------
;; File
jsr ValidateStorageType
bcs done
jsr _CopyCreateFile
bcs done
jsr _CopyNormalFile
jsr MaybeFinishFileMove
ELSE
;; --------------------------------------------------
;; Directory
jsr _CopyCreateFile
bcc ok_dir ; leave dst path segment in place for recursion
SET_BIT7_FLAG entry_err_flag
END_IF
;; --------------------------------------------------
done: jsr RemoveDstPathSegment
ok_dir: jsr RemoveSrcPathSegment
rts
.endproc ; CopyProcessDirectoryEntry
;;; ============================================================
;;; If moving, delete src file/directory.
.proc CopyFinishDirectory
jsr GetAndApplySrcInfoToDst ; apply modification date/time
jsr RemoveDstPathSegment
FALL_THROUGH_TO MaybeFinishFileMove
.endproc ; CopyFinishDirectory
.proc MaybeFinishFileMove
;; Copy or move?
bit move_flags
IF_NS
;; Was a move - delete file
retry: MLI_CALL DESTROY, destroy_src_params
IF_CS
IF_A_EQ #ERR_ACCESS_ERROR
jsr UnlockSrcFile
beq retry
rts ; silently leave file
END_IF
jsr ShowErrorAlert
jmp retry
END_IF
END_IF
rts
.endproc ; MaybeFinishFileMove
;;; ============================================================
.proc CopyUpdateProgress
jsr DecrementOpFileCount
stax file_count
jsr SetPortForProgressDialog
param_call CopyToBuf0, src_path_buf
param_call DrawProgressDialogLabel, 1, aux::str_copy_from
jsr DrawTargetFilePath
param_call CopyToBuf0, dst_path_buf
param_call DrawProgressDialogLabel, 2, aux::str_copy_to
jsr DrawDestFilePath
jmp DrawProgressDialogFilesRemaining
.endproc ; CopyUpdateProgress
;;; ============================================================
;;; Used before "Copy to RAMCard", to ensure everything will fit.
.proc CheckVolBlocksFree
retry: jsr GetDstFileInfo
IF_CS
jsr ShowErrorAlertDst
jmp retry
END_IF
sub16 dst_file_info_params::aux_type, dst_file_info_params::blocks_used, blocks_free
cmp16 blocks_free, op_block_count
IF_LT
param_call ShowAlertParams, AlertButtonOptions::OK, aux::str_ramcard_full
jmp CloseFilesCancelDialogWithFailedResult
END_IF
rts
blocks_free:
.word 0
.endproc ; CheckVolBlocksFree
;;; ============================================================
;;; Used when copying a single file.
;;; Assert: `src_file_info_params` is populated
.proc CheckSpaceAndShowPrompt
;; Copying a volume? If so, `src_file_info_params` has total
;; blocks used on the volume, which isn't useful for an
;; incremental copy.
lda src_file_info_params::storage_type
IF_A_EQ #ST_VOLUME_DIRECTORY
clc
rts
END_IF
;; --------------------------------------------------
;; Check how much space is available on the target volume
;; (including space reclaimed if a file will be overwritten)
;; If destination doesn't exist, 0 blocks will be reclaimed.
copy16 #0, existing_size
;; Does destination exist?
retry2: jsr GetDstFileInfo
IF_CS
cmp #ERR_FILE_NOT_FOUND
beq :+
jsr ShowErrorAlertDst ; retry if destination not present
jmp retry2
END_IF
copy16 dst_file_info_params::blocks_used, existing_size
:
;; Compute destination volume path
retry: copy8 dst_path_buf, saved_length
;; Strip to vol name - either end of string or next slash
param_call MakeVolumePath, dst_path_buf
;; Total blocks/used blocks on destination volume
jsr GetDstFileInfo
pha
saved_length := *+1
lda #SELF_MODIFIED_BYTE
sta dst_path_buf
pla
IF_NOT_ZERO
jsr ShowErrorAlertDst
jmp retry
END_IF
;; aux = total blocks
sub16 dst_file_info_params::aux_type, dst_file_info_params::blocks_used, blocks_free
add16 blocks_free, existing_size, blocks_free
;; --------------------------------------------------
;; Check if there is enough room
cmp16 blocks_free, src_file_info_params::blocks_used
IF_GE
clc
rts
END_IF
;; Show appropriate message
ldax #aux::str_large_copy_prompt
bit move_flags
IF_NS
ldax #aux::str_large_move_prompt
END_IF
ldy #AlertButtonOptions::OKCancel
jsr ShowAlertParams ; A,X = string, Y = AlertButtonOptions
jsr SetCursorWatch ; preserves A
cmp #kAlertResultCancel
jeq CloseFilesCancelDialogWithFailedResult
sec
rts
blocks_free:
.word 0
existing_size:
.word 0
.endproc ; CheckSpaceAndShowPrompt
;;; ============================================================
;;; Common implementation used by both `CopyProcessSelectedFile`
;;; and `CopyProcessDirectoryEntry`
;;; Output: C=0 on success, C=1 on failure
.proc _CopyCreateFile
bit move_flags ; same volume relink move?
IF_VC
;; No, verify that there is room.
jsr CheckSpaceAndShowPrompt
RTS_IF_CS
END_IF
;; Copy `file_type`, `aux_type`, and `storage_type`
COPY_BYTES src_file_info_params::storage_type - src_file_info_params::file_type + 1, src_file_info_params::file_type, create_params3::file_type
;; Copy `create_date`/`create_time`
COPY_STRUCT DateTime, src_file_info_params::create_date, create_params3::create_date
jsr _ReadSrcCaseBits
;; If a volume, need to create a subdir instead
lda create_params3::storage_type
IF_A_EQ #ST_VOLUME_DIRECTORY
copy8 #ST_LINKED_DIRECTORY, create_params3::storage_type
END_IF
;; --------------------------------------------------
retry: jsr GetDstFileInfo
bcs create
cmp #ERR_FILE_NOT_FOUND
beq create
;; File exists
lda dst_file_info_params::storage_type
IF_A_EQ #ST_LINKED_DIRECTORY
;; TODO: In the future, prompt and recursively delete
param_call ShowAlertParams, AlertButtonOptions::OK, aux::str_no_overwrite_dir
jsr SetCursorWatch
jmp CloseFilesCancelDialogWithFailedResult
END_IF
;; Prompt to replace
bit operations::all_flag
bmi yes
param_call ShowAlertParams, AlertButtonOptions::YesNoAllCancel, aux::str_exists_prompt
jsr SetCursorWatch ; preserves A
cmp #kAlertResultYes
beq yes
cmp #kAlertResultNo
beq failure
cmp #kAlertResultAll
bne cancel
SET_BIT7_FLAG operations::all_flag
yes:
MLI_CALL DESTROY, destroy_dst_params
bcs retry
;; --------------------------------------------------
;; Create the file
create:
MLI_CALL CREATE, create_params3
bcc success
jsr ShowErrorAlertDst
jmp retry
success:
lda case_bits
ora case_bits+1
IF_NOT_ZERO
jsr _WriteDstCaseBits
END_IF
clc
rts
failure:
sec
rts
cancel: jmp CloseFilesCancelDialogWithFailedResult
;;; ============================================================
;;; Case Bits
;;; Input: `src_file_info_params` pre-populated
.proc _ReadSrcCaseBits
copy16 #0, case_bits ; best effort
lda src_file_info_params::storage_type
IF_A_EQ #ST_VOLUME_DIRECTORY
;; Volume
copy8 DEVNUM, vol_key_block_params::unit_num
MLI_CALL READ_BLOCK, vol_key_block_params
bcs ret
copy16 block_buffer + VolumeDirectoryHeader::case_bits, case_bits
ELSE
;; File
ldax #src_path_buf
jsr GetFileEntryBlock ; leaves $06 pointing at `FileEntry`
bcs ret
entry_ptr := $06
ldy #FileEntry::case_bits
copy16in (entry_ptr),y, case_bits
END_IF
clc ; success
ret: rts
.endproc ; _ReadSrcCaseBits
.proc _WriteDstCaseBits
ldax #dst_path_buf
jsr GetFileEntryBlock
bcs ret
stax block_params::block_num
block_ptr := $06
ldax #block_buffer
jsr GetFileEntryBlockOffset ; Y is already the entry number
stax block_ptr
copy8 DEVNUM, block_params::unit_num
MLI_CALL READ_BLOCK, block_params
bcs ret
ldy #FileEntry::case_bits
copy16in case_bits, (block_ptr),y
MLI_CALL WRITE_BLOCK, block_params
ret: rts
.endproc ; _WriteDstCaseBits
.endproc ; _CopyCreateFile
;;; ============================================================
;;; Relink - swaps source and target, then deletes source.
;;;
;;; Assert: `_CopyCreateFile` has succeeded
.proc RelinkFileImpl
src_block := $800
dst_block := $A00
DEFINE_READWRITE_BLOCK_PARAMS src_block_params, src_block, 0
DEFINE_READWRITE_BLOCK_PARAMS dst_block_params, dst_block, 0
src_entry_num: .byte 0
dst_entry_num: .byte 0
Start: lda DEVNUM
sta src_block_params::unit_num
sta dst_block_params::unit_num
;; --------------------------------------------------
;; Locate the source/destination directory blocks
: ldax #src_path_buf
jsr GetFileEntryBlock
IF_CS
lda #ERR_PATH_NOT_FOUND
jsr ShowErrorAlert
jmp :-
END_IF
stax src_block_params::block_num
sty src_entry_num
: ldax #dst_path_buf
jsr GetFileEntryBlock
IF_CS
lda #ERR_PATH_NOT_FOUND
jsr ShowErrorAlert
jmp :-
END_IF
stax dst_block_params::block_num
sty dst_entry_num
;; --------------------------------------------------
;; Load the directory blocks containing FileEntry records
jsr _ReadBlocks
;; --------------------------------------------------
;; Swap the File Entry fields between the blocks, but
;; leave `header_pointer` unchanged
src_ptr := $06
dst_ptr := $08
;; Point `src_ptr` / `dst_ptr` at `FileEntry` structures
ldax #src_block
ldy src_entry_num
jsr GetFileEntryBlockOffset
stax src_ptr
ldax #dst_block
ldy dst_entry_num
jsr GetFileEntryBlockOffset
stax dst_ptr
;; Swap everything but `header_pointer`
ldy #FileEntry::header_pointer-1
DO
swap8 (src_ptr),y, (dst_ptr),y
dey
WHILE_POS
;; --------------------------------------------------
;; Write out the updated blocks
jsr _WriteBlocks
;; --------------------------------------------------
;; If a subdirectory, need to modify parent links
ldy #FileEntry::storage_type_name_length
lda (src_ptr),y
and #STORAGE_TYPE_MASK
IF_A_EQ #ST_LINKED_DIRECTORY<<4
;; Identify the key blocks of the src/dst file
ldy #FileEntry::key_pointer
copy8 (src_ptr),y, src_block_params::block_num
copy8 (dst_ptr),y, dst_block_params::block_num
iny
copy8 (src_ptr),y, src_block_params::block_num+1
copy8 (dst_ptr),y, dst_block_params::block_num+1
;; Load the key blocks of the source/dest files
jsr _ReadBlocks
;; Swap the `parent_pointer`/`parent_entry_number` fields between subdir headers
ldx #2
DO
swap8 src_block + SubdirectoryHeader::parent_pointer,x, dst_block + SubdirectoryHeader::parent_pointer,x
dex
WHILE_POS
;; Write out the updated key blocks
jsr _WriteBlocks
END_IF
;; --------------------------------------------------
;; Delete the file at the source location.
: MLI_CALL DESTROY, destroy_src_params
IF_CS
jsr ShowErrorAlert
jmp :-
END_IF
rts
;;; --------------------------------------------------
.proc _ReadBlocks
: MLI_CALL READ_BLOCK, src_block_params
IF_CS
jsr ShowErrorAlert
jmp :-
END_IF
: MLI_CALL READ_BLOCK, dst_block_params
IF_CS
jsr ShowErrorAlert
jmp :-
END_IF
rts
.endproc ; _ReadBlocks
;;; --------------------------------------------------
.proc _WriteBlocks
: MLI_CALL WRITE_BLOCK, src_block_params
IF_CS
jsr ShowErrorAlert
jmp :-
END_IF
: MLI_CALL WRITE_BLOCK, dst_block_params
IF_CS
jsr ShowErrorAlert
jmp :-
END_IF
rts
.endproc ; _WriteBlocks
.endproc ; RelinkFileImpl
RelinkFile := RelinkFileImpl::Start
;;; ============================================================
;;; Actual byte-for-byte file copy routine
.proc _CopyNormalFile
lda #0
sta src_dst_exclusive_flag
sta src_eof_flag
sta mark_src_params::position
sta mark_src_params::position+1
sta mark_src_params::position+2
sta mark_dst_params::position
sta mark_dst_params::position+1
sta mark_dst_params::position+2
jsr _OpenSrc
jsr _OpenDstOrFail
IF_NOT_ZERO
;; Destination not available; note it, can prompt later
SET_BIT7_FLAG src_dst_exclusive_flag
END_IF
;; Read
read: jsr _ReadSrc
bit src_dst_exclusive_flag
bpl write
jsr _CloseSrc ; swap if necessary
jsr _OpenDst
MLI_CALL SET_MARK, mark_dst_params
;; Write
write: bit src_eof_flag
bmi eof
jsr _WriteDst
bit src_dst_exclusive_flag
bpl read
jsr _CloseDst ; swap if necessary
jsr _OpenSrc
MLI_CALL SET_MARK, mark_src_params
bcc read
SET_BIT7_FLAG src_eof_flag
jmp read
;; EOF
eof: jsr _CloseDst
bit src_dst_exclusive_flag
IF_NC
jsr _CloseSrc
END_IF
jmp ApplySrcInfoToDst
.proc _OpenSrc
retry: MLI_CALL OPEN, open_src_params
IF_CS
jsr ShowErrorAlert
jmp retry
END_IF
lda open_src_params::ref_num
sta read_src_params::ref_num
sta close_src_params::ref_num
sta mark_src_params::ref_num
rts
.endproc ; _OpenSrc
.proc _OpenDstImpl
ENTRY_POINTS_FOR_BIT7_FLAG fail_ok, no_fail, fail_ok_flag
retry: MLI_CALL OPEN, open_dst_params
IF_CS
fail_ok_flag := *+1
ldy #SELF_MODIFIED_BYTE
IF_NS
cmp #ERR_VOL_NOT_FOUND
beq finish
END_IF
jsr ShowErrorAlertDst
jmp retry
END_IF
finish:
pha ; A = result
lda open_dst_params::ref_num ; harmless if failed
sta write_dst_params::ref_num
sta close_dst_params::ref_num
sta mark_dst_params::ref_num
pla ; A = result, set N and Z
rts
.endproc ; _OpenDstImpl
_OpenDst := _OpenDstImpl::no_fail
_OpenDstOrFail := _OpenDstImpl::fail_ok
.proc _ReadSrc
copy16 #kCopyBufferSize, read_src_params::request_count
retry: MLI_CALL READ, read_src_params
IF_CS
cmp #ERR_END_OF_FILE
beq eof
jsr ShowErrorAlert
jmp retry
END_IF
lda read_src_params::trans_count
ora read_src_params::trans_count+1
bne :+
eof: SET_BIT7_FLAG src_eof_flag
: MLI_CALL GET_MARK, mark_src_params
rts
.endproc ; _ReadSrc
.proc _WriteDst
;; Always start off at start of copy buffer
copy16 read_src_params::data_buffer, write_dst_params::data_buffer
DO
;; Assume we're going to write everything we read. We may
;; later determine we need to write it out block-by-block.
copy16 read_src_params::trans_count, write_dst_params::request_count
;; ProDOS Tech Note #30: AppleShare servers do not support
;; sparse files. https://prodos8.com/docs/technote/30
bit dst_is_appleshare_flag
bmi do_write ; ...and done!
;; Is there less than a full block? If so, just write it.
lda read_src_params::trans_count+1
cmp #.hibyte(BLOCK_SIZE)
bcc do_write ; ...and done!
;; Otherwise we'll go block-by-block, treating all zeros
;; specially.
copy16 #BLOCK_SIZE, write_dst_params::request_count
;; First two blocks are never made sparse. The first block is
;; never sparsely allocated (P8 TRM B.3.6 - Sparse Files) and
;; the transition from seedling to sapling is not handled
;; correctly in all versions of ProDOS.
;; https://prodos8.com/docs/technote/30
;; Assert: mark low byte is $00
lda mark_dst_params::position+1
and #%11111100
ora mark_dst_params::position+2
IF_NOT_ZERO
;; Is this block all zeros? Scan all $200 bytes
;; (Note: coded for size, not speed, since we're I/O bound)
ptr := $06
copy16 write_dst_params::data_buffer, ptr ; first half
ldy #0
tya
DO
ora (ptr),y
iny
WHILE_NOT_ZERO
inc ptr+1 ; second half
DO
ora (ptr),y
iny
WHILE_NOT_ZERO
tay
IF_ZERO
;; Block is all zeros, skip over it
add16_8 mark_dst_params::position+1, #.hibyte(BLOCK_SIZE)
MLI_CALL SET_EOF, mark_dst_params
MLI_CALL SET_MARK, mark_dst_params
jmp next_block
END_IF
END_IF
;; Block is not sparse, write it
jsr do_write
FALL_THROUGH_TO next_block
;; Advance to next block
next_block:
inc write_dst_params::data_buffer+1
inc write_dst_params::data_buffer+1
;; Assert: `read_src_params::trans_count` >= `BLOCK_SIZE`
dec read_src_params::trans_count+1
dec read_src_params::trans_count+1
;; Anything left to write?
lda read_src_params::trans_count
ora read_src_params::trans_count+1
WHILE_NOT_ZERO
rts
do_write:
retry: MLI_CALL WRITE, write_dst_params
IF_CS
jsr ShowErrorAlertDst
jmp retry
END_IF
MLI_CALL GET_MARK, mark_dst_params
rts
.endproc ; _WriteDst
.proc _CloseDst
MLI_CALL CLOSE, close_dst_params
rts
.endproc ; _CloseDst
.proc _CloseSrc
MLI_CALL CLOSE, close_src_params
rts
.endproc ; _CloseSrc
;; Set if src/dst can't be open simultaneously.
src_dst_exclusive_flag:
.byte 0
src_eof_flag:
.byte 0 ; bit7
.endproc ; _CopyNormalFile
;;; ============================================================
;;; "Delete" (Delete/Trash) files dialog state and logic
;;; ============================================================
;;; `DeleteProcessSelectedFile`
;;; - if dir, recurses; delegates to `DeleteFileCommon`; if dir, destroys dir
;;; `DeleteProcessDirectoryEntry`
;;; - if not dir, delegates to `DeleteFileCommon`
;;; `DeleteFinishDirectory`
;;; - destroys dir via `DeleteFileCommon`
;;; Traversal callbacks for delete operation (`operation_traversal_callbacks`)
operation_traversal_callbacks_for_delete:
.addr DeleteProcessSelectedFile
.addr DeleteProcessDirectoryEntry
.addr DeleteFinishDirectory
ASSERT_TABLE_SIZE operation_traversal_callbacks_for_delete, kOpTraversalCallbacksSize
.proc OpenDeleteProgressDialog
COPY_BYTES kOpLifecycleCallbacksSize, operation_lifecycle_callbacks_for_delete, operation_lifecycle_callbacks
jmp OpenProgressDialog
.proc _DeleteDialogEnumerationCallback
stax file_count
stax total_count
jsr SetPortForProgressDialog
param_call DrawProgressDialogLabel, 0, aux::str_delete_count
jmp DrawFileCountWithSuffix
.endproc ; _DeleteDialogEnumerationCallback
.proc _DeleteDialogConfirmCallback
;; `text_input_buf` is used rather than `text_buffer2` due to size
jsr ComposeFileCountString
copy8 #0, text_input_buf
param_call AppendToTextInputBuf, aux::str_delete_confirm_prefix
param_call AppendToTextInputBuf, str_file_count
param_call_indirect AppendToTextInputBuf, ptr_str_files_suffix
param_call AppendToTextInputBuf, aux::str_delete_confirm_suffix
param_call ShowAlertParams, AlertButtonOptions::OKCancel, text_input_buf
jsr SetCursorWatch ; preserves A
cmp #kAlertResultOK
jne CloseFilesCancelDialogWithCanceledResult
rts
.endproc ; _DeleteDialogConfirmCallback
;;; Lifecycle callbacks for delete operation (`operation_lifecycle_callbacks`)
operation_lifecycle_callbacks_for_delete:
.addr _DeleteDialogEnumerationCallback
.addr CloseProgressDialog
.addr _DeleteDialogConfirmCallback
.addr PrepTraversalCallbacksForDelete
ASSERT_TABLE_SIZE operation_lifecycle_callbacks_for_delete, operations::kOpLifecycleCallbacksSize
.endproc ; OpenDeleteProgressDialog
;;; ============================================================
.proc PrepTraversalCallbacksForDelete
COPY_BYTES kOpTraversalCallbacksSize, operation_traversal_callbacks_for_delete, operation_traversal_callbacks
CLEAR_BIT7_FLAG operations::all_flag
SET_BIT7_FLAG do_op_flag
rts
.endproc ; PrepTraversalCallbacksForDelete
;;; ============================================================
;;; Handle deletion of a selected file.
;;; Calls into the recursion logic of `ProcessDirectory` as necessary.
.proc DeleteProcessSelectedFile
jsr CopyPathsFromBufsToSrcAndDst
;; Path is set up - update dialog and populate `src_file_info_params`
jsr DeleteUpdateProgress
retry: jsr GetSrcFileInfo
IF_CS
jsr ShowErrorAlert
jmp retry
END_IF
;; Check if it's a regular file or directory
lda src_file_info_params::storage_type
;; ST_VOLUME_DIRECTORY excluded because volumes are ejected.
IF_A_NE #ST_LINKED_DIRECTORY
jsr ValidateStorageType
bcc do_destroy
rts
END_IF
;; Recurse, and process directory
jsr ProcessDirectory
jsr DeleteRefreshProgress ; update path display
;; ST_VOLUME_DIRECTORY excluded because volumes are ejected.
FALL_THROUGH_TO do_destroy
do_destroy:
FALL_THROUGH_TO DeleteFileCommon
.endproc ; DeleteProcessSelectedFile
;;; ============================================================
;;; Common implementation used by both `DeleteProcessSelectedFile`
;;; and `DeleteProcessDirectoryEntry`
.proc DeleteFileCommon
retry: MLI_CALL DESTROY, destroy_src_params
bcc done
;; Failed - determine why, maybe try to unlock.
;; TODO: If it's a directory, this could be because it's not empty,
;; e.g. if it contained files that could not be deleted.
cmp #ERR_ACCESS_ERROR
bne error
bit operations::all_flag
bmi unlock
param_call ShowAlertParams, AlertButtonOptions::YesNoAllCancel, aux::str_delete_locked_file
jsr SetCursorWatch ; preserves A
cmp #kAlertResultNo
beq done
cmp #kAlertResultYes
beq unlock
cmp #kAlertResultAll
bne :+
SET_BIT7_FLAG operations::all_flag
bmi unlock ; always
: jmp CloseFilesCancelDialogWithFailedResult
unlock: jsr UnlockSrcFile
beq retry
done: rts
error: jsr ShowErrorAlert
jmp retry
.endproc ; DeleteFileCommon
.proc UnlockSrcFile
jsr GetSrcFileInfo
lda src_file_info_params::access
and #ACCESS_D ; destroy enabled bit set?
IF_ZERO ; no, need to unlock
copy8 #ACCESS_DEFAULT, src_file_info_params::access
jsr SetSrcFileInfo
END_IF
rts
.endproc ; UnlockSrcFile
;;; ============================================================
;;; Called by `ProcessDir` to process a single file
.proc DeleteProcessDirectoryEntry
jsr AppendFileEntryToSrcPath
jsr DeleteUpdateProgress
;; Called with `src_file_info_params` pre-populated
;; Directories will be processed separately
lda src_file_info_params::storage_type
cmp #ST_LINKED_DIRECTORY
beq next_file
jsr ValidateStorageType
bcs next_file
jsr DeleteFileCommon
next_file:
jmp RemoveSrcPathSegment
.endproc ; DeleteProcessDirectoryEntry
;;; ============================================================
;;; Delete directory when exiting via traversal
.proc DeleteFinishDirectory
jsr DeleteRefreshProgress
jmp DeleteFileCommon
.endproc ; DeleteFinishDirectory
;;; ============================================================
.proc DeleteUpdateProgress
jsr DecrementOpFileCount
stax file_count
FALL_THROUGH_TO DeleteRefreshProgress
.endproc ; DeleteUpdateProgress
;;; Does not decrement count, just repaints path so that the correct
;;; path is visible if an alert is shown when finishing a directory.
.proc DeleteRefreshProgress
jsr SetPortForProgressDialog
param_call CopyToBuf0, src_path_buf
param_call DrawProgressDialogLabel, 1, aux::str_file_colon
jsr DrawTargetFilePath
jmp DrawProgressDialogFilesRemaining
.endproc ; DeleteRefreshProgress
;;; ============================================================
;;; Most operations start by doing a traversal to just count
;;; the files.
;;; `EnumerationProcessSelectedFile`
;;; - if op=copy, validates; if dir, recurses; delegates to:
;;; `EnumerationProcessDirectoryEntry`
;;; - increments file count; if op=size, sums size
;;; (finishing a directory is a no-op)
;;; Traversal callbacks for size operation (`operation_traversal_callbacks`)
operation_traversal_callbacks_for_enumeration:
.addr EnumerationProcessSelectedFile
.addr EnumerationProcessDirectoryEntry
.addr DoNothing
ASSERT_TABLE_SIZE operation_traversal_callbacks_for_enumeration, kOpTraversalCallbacksSize
.proc PrepTraversalCallbacksForEnumeration
COPY_BYTES kOpTraversalCallbacksSize, operation_traversal_callbacks_for_enumeration, operation_traversal_callbacks
lda #0
sta op_file_count
sta op_file_count+1
sta op_block_count
sta op_block_count+1
sta do_op_flag
rts
.endproc ; PrepTraversalCallbacksForEnumeration
;;; ============================================================
;;; Handle sizing (or just counting) of a selected file.
;;; Calls into the recursion logic of `ProcessDirectory` as necessary.
.proc EnumerationProcessSelectedFile
jsr CopyPathsFromBufsToSrcAndDst
retry: jsr GetSrcFileInfo
IF_CS
jsr ShowErrorAlert
jmp retry
END_IF
;; Visit the key file
lda src_file_info_params::storage_type
pha ; A = `storage_type`
IF_A_EQ #ST_VOLUME_DIRECTORY
copy16 #0, src_file_info_params::blocks_used ; dummy value
END_IF
jsr EnumerationProcessDirectoryEntry
pla ; A = `storage_type`
bit move_flags ; same volume relink move?
RTS_IF_VS
IF_A_EQ_ONE_OF #ST_VOLUME_DIRECTORY, #ST_LINKED_DIRECTORY
jsr ProcessDirectory
END_IF
rts
.endproc ; EnumerationProcessSelectedFile
;;; ============================================================
;;; Called by `ProcessDirectory` to process a single file
;;; Input: `src_file_info_params::blocks_used` populated
.proc EnumerationProcessDirectoryEntry
;; Called with `src_file_info_params` pre-populated
add16 op_block_count, src_file_info_params::blocks_used, op_block_count
inc16 op_file_count
ldax op_file_count
jmp operations::InvokeOperationEnumerationCallback
.endproc ; EnumerationProcessDirectoryEntry
;;; Count of files - increases during enumeration, decreases as
;;; files are processed.
op_file_count:
.word 0
;;; Only used for "Copy to RAMCard" but computed regardless.
op_block_count:
.word 0
;;; ============================================================
.proc DecrementOpFileCount
dec16 op_file_count
ldax op_file_count
rts
.endproc ; DecrementOpFileCount
;;; ============================================================
;;; Copy `path_buf3` to `src_path_buf`, `path_buf4` to `dst_path_buf`
;;; and note last '/' in src.
.proc CopyPathsFromBufsToSrcAndDst
ldy #0
sty src_path_slash_index
dey
;; Copy `path_buf3` to `src_path_buf`
;; ... but record index of last '/'
DO
iny
lda path_buf3,y
IF_A_EQ #'/'
sty src_path_slash_index
END_IF
sta src_path_buf,y
WHILE_Y_NE path_buf3
;; Copy `path_buf4` to `dst_path_buf`
param_jump CopyToDstPath, path_buf4
.endproc ; CopyPathsFromBufsToSrcAndDst
src_path_slash_index:
.byte 0
;;; ============================================================
;;; Assuming CopyPathsFromBufsToSrcAndDst has been called, append
;;; the last path segment of `src_path_buf` to `dst_path_buf`.
;;; Assert: `src_path_slash_index` is set properly.
.proc AppendSrcPathLastSegmentToDstPath
ldx dst_path_buf
ldy src_path_slash_index
dey
DO
iny
inx
copy8 src_path_buf,y, dst_path_buf,x
WHILE_Y_NE src_path_buf
stx dst_path_buf
rts
.endproc ; AppendSrcPathLastSegmentToDstPath
;;; ============================================================
.proc DrawTargetFilePath
jsr SetPenModeCopy
MGTK_CALL MGTK::PaintRect, aux::current_target_file_rect
MGTK_CALL MGTK::MoveTo, aux::current_target_file_pos
jmp DrawDialogPathBuf0
.endproc ; DrawTargetFilePath
.proc DrawDestFilePath
jsr SetPenModeCopy
MGTK_CALL MGTK::PaintRect, aux::current_dest_file_rect
MGTK_CALL MGTK::MoveTo, aux::current_dest_file_pos
jmp DrawDialogPathBuf0
.endproc ; DrawDestFilePath
;;; ============================================================
;;; `file_count` must be populated
.proc DrawFileCountWithSuffix
jsr ComposeFileCountString
param_call DrawString, str_file_count
param_jump_indirect DrawString, ptr_str_files_suffix
.endproc ; DrawFileCountWithSuffix
;;; `file_count` must be populated
.proc DrawProgressDialogFilesRemaining
MGTK_CALL MGTK::MoveTo, progress_dialog_remaining_pos
param_call DrawString, aux::str_files_remaining
jsr ComposeFileCountString
param_call DrawString, str_file_count
param_call DrawString, str_2_spaces
;; Update progress bar
sub16 total_count, file_count, progress_muldiv_params::numerator
copy16 total_count, progress_muldiv_params::denominator
MGTK_CALL MGTK::MulDiv, progress_muldiv_params
add16 progress_muldiv_params::result, progress_dialog_bar_meter::x1, progress_dialog_bar_meter::x2
jsr SetPenModeCopy
MGTK_CALL MGTK::SetPattern, progress_pattern
MGTK_CALL MGTK::PaintRect, progress_dialog_bar_meter
rts
.endproc ; DrawProgressDialogFilesRemaining
;;; ============================================================
;;; If Escape is pressed, abort the operation.
.proc CheckCancel
jsr GetEvent ; no need to synthesize events
IF_A_EQ #MGTK::EventKind::key_down
lda event_params::key
cmp #CHAR_ESCAPE
beq cancel
END_IF
rts
cancel: bit do_op_flag
bpl CloseFilesCancelDialogWithCanceledResult
FALL_THROUGH_TO CloseFilesCancelDialogWithFailedResult
.endproc ; CheckCancel
;;; ============================================================
;;; Closes dialog, closes all open files, and restores stack.
.proc CloseFilesCancelDialogImpl
ENTRY_POINTS_FOR_A failed, kOperationFailed, canceled, kOperationCanceled
sta @result
jsr operations::InvokeOperationCompleteCallback
MLI_CALL CLOSE, close_params
ldx operations::saved_stack ; restore stack, in case recursion was aborted
txs
@result := *+1
lda #SELF_MODIFIED_BYTE
rts
DEFINE_CLOSE_PARAMS close_params
.endproc ; CloseFilesCancelDialogImpl
CloseFilesCancelDialogWithFailedResult := CloseFilesCancelDialogImpl::failed
CloseFilesCancelDialogWithCanceledResult := CloseFilesCancelDialogImpl::canceled
;;; ============================================================
;;; Move or Copy? Compare src/dst paths, same vol = move.
;;; Button down inverts the default action.
;;; Input: A,X = source path
;;; Output: A=bit 7 set if move, clear if copy
;;; bit 6 set if same vol move and block ops supported
.proc CheckMoveOrCopy
src_ptr := $08
dst_buf := path_buf4
stax src_ptr
jsr ModifierDown ; Apple inverts the default
and #%10000000
sta flag
;; Check if same volume
ldy #0
copy8 (src_ptr),y, src_len
iny ; skip leading '/'
bne check ; always
DO
;; Chars the same?
lda (src_ptr),y
jsr ToUpperCase
sta @char
lda dst_buf,y
jsr ToUpperCase
@char := *+1
cmp #SELF_MODIFIED_BYTE
bne no_match
;; Same and a slash?
cmp #'/'
beq match
;; End of src?
src_len := *+1
check: cpy #SELF_MODIFIED_BYTE
IF_GE
cpy dst_buf ; dst also done?
bcs match
lda path_buf4+1,y ; is next char in dst a slash?
bne check_slash ; always
END_IF
IF_Y_GE dst_buf ; src is not done, is dst?
iny
lda (src_ptr),y ; is next char in src a slash?
bne check_slash ; always
END_IF
iny ; next char
WHILE_NOT_ZERO ; always
check_slash:
cmp #'/'
beq match ; if so, same vol
FALL_THROUGH_TO no_match
no_match:
flag := *+1
lda #SELF_MODIFIED_BYTE
ret: rts
match: lda flag
eor #$80
beq ret ; copy
;; Same vol - but are block operations supported?
retry: param_call_indirect GetFileInfo, src_ptr
IF_CS
jsr ShowErrorAlert
jmp retry
END_IF
copy8 DEVNUM, vol_key_block_params::unit_num
MLI_CALL READ_BLOCK, vol_key_block_params
lda #$80 ; bit 7 = move
IF_CC
eor #$40 ; bit 6 = relink supported
END_IF
rts
.endproc ; CheckMoveOrCopy
;;; ============================================================
.proc GetAndApplySrcInfoToDst
jsr GetSrcFileInfo
;; Skip if source is volume; the contents are copied not the
;; item itself, so it doesn't make sense.
lda src_file_info_params::storage_type
RTS_IF_A_EQ #ST_VOLUME_DIRECTORY
FALL_THROUGH_TO ApplySrcInfoToDst
.endproc ; GetAndApplySrcInfoToDst
.proc ApplySrcInfoToDst
COPY_BYTES 11, src_file_info_params::access, dst_file_info_params::access
FALL_THROUGH_TO SetDstFileInfo
.endproc ; ApplySrcInfoToDst
;;; ============================================================
.proc SetDstFileInfo
: copy8 #7, dst_file_info_params::param_count ; SET_FILE_INFO
MLI_CALL SET_FILE_INFO, dst_file_info_params
pha
copy8 #$A, dst_file_info_params::param_count ; GET_FILE_INFO
pla
IF_CS
jsr ShowErrorAlertDst
jmp :-
END_IF
rts
.endproc ; SetDstFileInfo
;;; ============================================================
;;; Show Alert Dialog
;;; A=error. If ERR_VOL_NOT_FOUND or ERR_FILE_NOT_FOUND, will
;;; show "please insert source disk" (or destination, if flag set)
.proc ShowErrorAlertImpl
flag_set:
ldx #$80
SKIP_NEXT_2_BYTE_INSTRUCTION
flag_clear:
ldx #0
stx flag
IF_A_NE_ALL_OF #ERR_VOL_NOT_FOUND, #ERR_PATH_NOT_FOUND
;; if err is "not found" prompt specifically for src/dst disk
jsr ShowAlert
ASSERT_EQUALS ::kAlertResultTryAgain, 0
bne close ; not kAlertResultTryAgain = 0
jmp SetCursorWatch ; undone by `ClosePromptDialog` or `CloseProgressDialog`
END_IF
ldax #aux::str_alert_insert_source_disk
bit flag
IF_NS
ldax #aux::str_alert_insert_destination
END_IF
ldy #AlertButtonOptions::TryAgainCancel
jsr ShowAlertParams ; A,X = string, Y = AlertButtonOptions
ASSERT_EQUALS ::kAlertResultTryAgain, 0
bne close ; not kAlertResultTryAgain = 0
jsr SetCursorWatch ; undone by `ClosePromptDialog` or `CloseProgressDialog`
;; Poll drives before trying again
MLI_CALL ON_LINE, on_line_all_drives_params
rts
close: jmp CloseFilesCancelDialogWithFailedResult
flag: .byte 0
.endproc ; ShowErrorAlertImpl
ShowErrorAlert := ShowErrorAlertImpl::flag_clear
ShowErrorAlertDst := ShowErrorAlertImpl::flag_set
;;; ============================================================
;;; "Get Info" dialog state and logic
;;; ============================================================
;;; NOTE: Inside `operations` scope due to reuse of recursive
;;; directory enumeration logic (`ProcessDirectory` etc)
.scope get_info
DEFINE_READWRITE_BLOCK_PARAMS getinfo_block_params, $800, $A
;;; ============================================================
;;; Get Info
;;; Returns: A has bit7 = 1 if selected items were modified
;;; Assert: At least one icon is selected
.proc DoGetInfo
;; --------------------------------------------------
;; Loop over selected icons
lda #0
sta icon_index
sta result_flag
loop:
icon_index := *+1
ldx #SELF_MODIFIED_BYTE
cpx selected_icon_count
jeq done
lda selected_icon_list,x
cmp trash_icon_num
beq next
;; --------------------------------------------------
;; Get the file / volume info from ProDOS
jsr GetIconPath ; `path_buf3` set to path; A=0 on success
IF_NE
jsr ShowAlert
jmp next
END_IF
param_call CopyToSrcPath, path_buf3
;; Try to get file/volume info
common: jsr GetSrcFileInfo
IF_CS
jsr ShowAlert
cmp #kAlertResultTryAgain
beq common
jmp next
END_IF
;; Special cases for volumes
lda selected_window_id
IF_ZERO
;; Volume - determine write-protect state
CLEAR_BIT7_FLAG write_protected_flag
ldx icon_index
lda selected_icon_list,x
jsr IconToDeviceIndex
IF_ZERO
lda DEVLST,x
and #UNIT_NUM_MASK
sta getinfo_block_params::unit_num
MLI_CALL READ_BLOCK, getinfo_block_params
IF_CC
MLI_CALL WRITE_BLOCK, getinfo_block_params
IF_A_EQ #ERR_WRITE_PROTECTED
SET_BIT7_FLAG write_protected_flag
END_IF
END_IF
END_IF
END_IF
;; --------------------------------------------------
;; Open and populate dialog
jsr _DialogOpen
;; --------------------------------------------------
;; Descendant size/file count
lda src_file_info_params::storage_type
IF_A_EQ_ONE_OF #ST_VOLUME_DIRECTORY, #ST_LINKED_DIRECTORY
jsr SetCursorWatch
jsr _GetDirSize
jsr SetCursorPointer
jsr GetSrcFileInfo ; needed for toggling lock
END_IF
;; --------------------------------------------------
;; Run the dialog, until OK or Cancel
jsr _DialogRun
bne done
next: inc icon_index
jmp loop
done: copy8 #0, path_buf4
lda result_flag
rts
result_flag: ; bit7
.byte 0
vol_used_blocks:
.word 0
vol_total_blocks:
.word 0
write_protected_flag:
.byte 0
;;; ------------------------------------------------------------
;;; Open and populate the dialog
.proc _DialogOpen
CLEAR_BIT7_FLAG has_input_field_flag
lda #kPromptButtonsOKCancel
ldx icon_index
inx
IF_X_EQ selected_icon_count
lda #kPromptButtonsOKOnly
END_IF
jsr OpenPromptWindow
jsr SetPortForDialogWindow
param_call DrawDialogTitle, aux::label_get_info
;; Draw labels
param_call DrawDialogLabel, 1 | DDL_LRIGHT, aux::str_info_name
param_call DrawDialogLabel, 2 | DDL_LRIGHT, aux::str_info_type
param_call DrawDialogLabel, 4 | DDL_LRIGHT, aux::str_info_create
param_call DrawDialogLabel, 5 | DDL_LRIGHT, aux::str_info_mod
lda selected_window_id
IF_ZERO
param_call DrawDialogLabel, 3 | DDL_LRIGHT, aux::str_info_vol_size
param_call DrawDialogLabel, 6 | DDL_LRIGHT, aux::str_info_protected
ELSE
param_call DrawDialogLabel, 3 | DDL_LRIGHT, aux::str_info_file_size
END_IF
;; --------------------------------------------------
;; Name
ldx icon_index
lda selected_icon_list,x
jsr GetIconName
ldy #1 | DDL_VALUE
jsr DrawDialogLabel
;; --------------------------------------------------
;; Type
lda selected_window_id
IF_ZERO
;; Volume
param_call DrawDialogLabel, 2 | DDL_VALUE, aux::str_volume
ELSE
;; File
lda src_file_info_params::file_type
pha
jsr ComposeFileTypeString
COPY_STRING str_file_type, text_input_buf
pla ; A = file type
IF_A_NE #FT_DIRECTORY
ldax src_file_info_params::aux_type
jsr _AppendAuxType
END_IF
param_call DrawDialogLabel, 2 | DDL_VALUE, text_input_buf
END_IF
;; --------------------------------------------------
;; Size/Blocks
;; Compose "12345K" or "12345K / 67890K" string
copy8 #0, text_input_buf
lda selected_window_id ; volume?
beq volume ; yes
;; A file, so just show the size
ldax src_file_info_params::blocks_used
jmp append_size
;; A volume.
volume:
;; ProDOS TRM 4.4.5:
;; "When file information about a volume directory is requested, the
;; total number of blocks on the volume is returned in the aux_type
;; field and the total blocks for all files is returned in blocks_used.
ldax src_file_info_params::blocks_used
stax vol_used_blocks
jsr ComposeSizeString
param_call AppendToTextInputBuf, text_buffer2
param_call AppendToTextInputBuf, aux::str_info_size_slash
;; Load up the total volume size...
ldax src_file_info_params::aux_type
stax vol_total_blocks
;; Compute "12345K" (either volume size or file size)
append_size:
jsr ComposeSizeString
param_call AppendToTextInputBuf, text_buffer2
param_call DrawDialogLabel, 3 | DDL_VALUE, text_input_buf
;; --------------------------------------------------
;; Created date
COPY_STRUCT DateTime, src_file_info_params::create_date, datetime_for_conversion
jsr ComposeDateString
param_call DrawDialogLabel, 4 | DDL_VALUE, text_buffer2
;; --------------------------------------------------
;; Modified date
COPY_STRUCT DateTime, src_file_info_params::mod_date, datetime_for_conversion
jsr ComposeDateString
param_call DrawDialogLabel, 5 | DDL_VALUE, text_buffer2
;; --------------------------------------------------
;; Locked/Protected
lda selected_window_id
IF_ZERO
;; Volume - regular label
ldax #aux::str_info_no
bit write_protected_flag
IF_NS
ldax #aux::str_info_yes
END_IF
ldy #6 | DDL_VALUE
jsr DrawDialogLabel
ELSE
;; File - checkbox control
ldx #BTK::kButtonStateNormal
lda src_file_info_params::access
and #ACCESS_DEFAULT
IF_A_NE #ACCESS_DEFAULT
ldx #BTK::kButtonStateChecked ; locked
END_IF
stx locked_button::state
BTK_CALL BTK::CheckboxDraw, locked_button
;; Assign hooks; reset in `OpenPromptWindow`
copy16 #_HandleClick, main::PromptDialogClickHandlerHook
copy16 #_HandleKey, main::PromptDialogKeyHandlerHook
END_IF
rts
.endproc ; _DialogOpen
;;; ------------------------------------------------------------
;;; Recursively count child files / sizes
.proc _GetDirSize
lda selected_window_id
IF_NOT_ZERO
copy16 #1, file_count
copy16 src_file_info_params::blocks_used, num_blocks
ELSE
copy16 #0, file_count
copy16 #0, num_blocks
END_IF
COPY_BYTES kOpTraversalCallbacksSize, operation_traversal_callbacks_for_getinfo, operation_traversal_callbacks
copy16 #DoNothing, operations::operation_complete_callback ; handle error
tsx
stx operations::saved_stack
jsr ProcessDirectory
jmp _UpdateDirSizeDisplay ; in case 0 files were seen
;;; Traversal callbacks for get info operation (`operation_traversal_callbacks`)
operation_traversal_callbacks_for_getinfo:
.addr DoNothing
.addr _GetInfoProcessDirEntry
.addr DoNothing
ASSERT_TABLE_SIZE operation_traversal_callbacks_for_getinfo, operations::kOpTraversalCallbacksSize
.proc _GetInfoProcessDirEntry
add16 num_blocks, src_file_info_params::blocks_used, num_blocks
inc16 file_count
FALL_THROUGH_TO _UpdateDirSizeDisplay
.endproc ; _GetInfoProcessDirEntry
.proc _UpdateDirSizeDisplay
;; Dir: "<size>K for <count> file(s)"
;; Vol: "<size>K for <count> file(s) / <total>K>"
copy8 #0, text_input_buf
;; "<size>K"
ldax num_blocks
ldy selected_window_id
IF_ZERO
ldax vol_used_blocks
END_IF
jsr ComposeSizeString
param_call AppendToTextInputBuf, text_buffer2
;; " for "
param_call AppendToTextInputBuf, aux::str_info_size_infix
;; "<count> "
jsr ComposeFileCountString
param_call AppendToTextInputBuf, str_file_count
;; "file(s)"
ldax #aux::str_info_size_suffix
ldy file_count+1
IF_ZERO
ldy file_count
IF_Y_EQ #1
ldax #aux::str_info_size_suffix_singular
END_IF
END_IF
jsr AppendToTextInputBuf
lda selected_window_id
IF_ZERO
;; " / "
param_call AppendToTextInputBuf, aux::str_info_size_slash
;; "<total>K"
ldax vol_total_blocks
jsr ComposeSizeString
param_call AppendToTextInputBuf, text_buffer2
END_IF
;; In case it shrank
param_call AppendToTextInputBuf, str_2_spaces
jsr SetPortForDialogWindow
param_jump DrawDialogLabel, 3 | DDL_VALUE, text_input_buf
.endproc ; _UpdateDirSizeDisplay
num_blocks:
.word 0
.endproc ; _GetDirSize
;;; ------------------------------------------------------------
;;; Append aux type (in A,X) to `text_input_buf`
.proc _AppendAuxType
pha
txa
pha
param_call AppendToTextInputBuf, aux::str_auxtype_prefix
;; Append type
pla
jsr do_byte
pla
FALL_THROUGH_TO do_byte
do_byte:
pha
lsr
lsr
lsr
lsr
jsr do_nibble
pla
FALL_THROUGH_TO do_nibble
do_nibble:
and #%00001111
tax
lda hex_digits,x
inc text_input_buf
ldx text_input_buf
sta text_input_buf,x
rts
.endproc ; _AppendAuxType
;;; ------------------------------------------------------------
;;; Input loop and (hooked) event handlers
.proc _DialogRun
DO
jsr PromptInputLoop
WHILE_NS
pha
jsr ClosePromptDialog
pla
rts
.endproc ; _DialogRun
.proc _HandleClick
MGTK_CALL MGTK::InRect, locked_button::rect
IF_NOT_ZERO
jsr _ToggleFileLock
END_IF
return #$FF
.endproc ; _HandleClick
.proc _HandleKey
cmp #CHAR_CTRL_L
beq _ToggleFileLock
rts
.endproc ; _HandleKey
.proc _ToggleFileLock
;; Modify file
lda src_file_info_params::access
bit locked_button::state
IF_NS
;; Unlock
ora #LOCKED_MASK
ELSE
;; Lock
and #AS_BYTE(~LOCKED_MASK)
END_IF
sta src_file_info_params::access
jsr SetSrcFileInfo
bcs ret
;; TODO: Show alert, offer retry on failure?
;; Toggle UI
lda locked_button::state
eor #$80
sta locked_button::state
BTK_CALL BTK::CheckboxUpdate, locked_button
;; Update FileRecord
icon_ptr := $06
file_record_ptr := $08
ldx icon_index
lda selected_icon_list,x
jsr GetIconEntry
stax icon_ptr
jsr SetFileRecordPtrFromIconPtr
bit LCBANK2
bit LCBANK2
lda src_file_info_params::access
ldy #FileRecord::access
sta (file_record_ptr),y
bit LCBANK1
bit LCBANK1
SET_BIT7_FLAG result_flag
ret: return #$FF
.endproc ; _ToggleFileLock
.endproc ; DoGetInfo
.endscope ; get_info
;;; ============================================================
.endscope ; operations
DoCopyOrMoveSelection := operations::DoCopyOrMoveSelection
DoCopySelection := operations::DoCopySelection
DoDeleteSelection := operations::DoDeleteSelection
DoCopyToRAM := operations::DoCopyToRAM
DoCopyFile := operations::DoCopyFile
DoGetInfo := operations::get_info::DoGetInfo
;;; ============================================================
.scope rename
old_name_buf := $1F00
new_name_buf := stashed_name
DEFINE_RENAME_PARAMS rename_params, src_path_buf, dst_path_buf
.params rename_dialog_params
a_prev: .addr old_name_buf
a_path: .addr SELF_MODIFIED_BYTE
.endparams
;;; Inputs: A,X = address of buffer holding previous name
;;; Assert: Single icon selected, and it's not Trash.
.proc DoRenameImpl
start:
stax rename_dialog_params::a_prev
copy8 #0, result_flags
;; Dialog needs base path to ensure new name is valid path
jsr GetSelectionWindow
jsr GetWindowOrRootPath
stax rename_dialog_params::a_path
;; Original path
lda selected_icon_list
jsr GetIconPath ; `path_buf3` set to path; A=0 on success
IF_NE
jsr ShowAlert
return result_flags
END_IF
param_call CopyToSrcPath, path_buf3
;; Copy original name for display/default
lda selected_icon_list
jsr GetIconName
stax $06
param_call CopyPtr1ToBuf, old_name_buf
copy8 selected_icon_list, icon_param
ITK_CALL IconTK::GetRenameRect, icon_param ; populates `tmp_rect`
;; Open the dialog
jsr _DialogOpen
;; Run the dialog
retry: jsr _DialogRun
beq success
;; Failure
fail: return result_flags
;; --------------------------------------------------
;; Success, new name in X,Y
success:
new_name_ptr := $08
stxy new_name_ptr
;; Copy the name somewhere LCBANK-safe
param_call CopyPtr2ToBuf, new_name_buf
;; File or Volume?
lda selected_window_id
IF_NOT_ZERO
jsr GetWindowPath
ELSE
ldax #str_empty
END_IF
;; Copy window path as prefix
jsr CopyToDstPath
;; Append new filename
param_call AppendFilenameToDstPath, new_name_buf
;; Did the name change (ignoring case)?
copy16 #old_name_buf, $06
copy16 #new_name_buf, $08
jsr CompareStrings
beq no_change
;; Already exists? (Mostly for volumes, but works for files as well)
jsr GetDstFileInfo
IF_CC
lda #ERR_DUPLICATE_FILENAME
jsr ShowAlert
jmp retry
END_IF
;; Try to rename
no_change:
;; Update case bits, in memory or on disk
jsr ApplyCaseBits ; applies `stashed_name` to `src_path_buf`
MLI_CALL RENAME, rename_params
bcc finish
;; Failed, maybe retry
jsr ShowAlert ; Alert options depend on specific ProDOS error
ASSERT_EQUALS ::kAlertResultTryAgain, 0
jeq retry ; `kAlertResultTryAgain` = 0
jsr _DialogClose
jmp fail
;; --------------------------------------------------
;; Completed - tear down the dialog...
finish: jsr _DialogClose
;; Erase the icon, in case new name is shorter
copy8 selected_icon_list, icon_param
ITK_CALL IconTK::EraseIcon, icon_param
;; Copy new string in
icon_name_ptr := $06
lda selected_icon_list
jsr GetIconName
stax icon_name_ptr
ldy new_name_buf
DO
copy8 new_name_buf,y, (icon_name_ptr),y
dey
WHILE_POS
;; If not volume, find and update associated FileEntry
lda selected_window_id
jeq end_filerecord_and_icon_update
;; Dig up the index of the icon within the window.
icon_ptr := $06
lda icon_param
jsr GetIconEntry
stax icon_ptr
file_record_ptr := $08
jsr SetFileRecordPtrFromIconPtr
;; Bank in the `FileRecord` entries
bit LCBANK2
bit LCBANK2
;; Copy the new name in
ASSERT_EQUALS FileRecord::name, 0, "Name must be at start of FileRecord"
ldy new_name_buf
DO
copy8 new_name_buf,y, (file_record_ptr),y
dey
WHILE_POS
;; Copy out file metadata needed to determine icon type
jsr FileRecordToSrcFileInfo ; uses `FileRecord` ptr in $08
;; Done with `FileRecord` entries
bit LCBANK1
bit LCBANK1
;; Determine new icon type
jsr GetSelectionViewBy
ASSERT_EQUALS DeskTopSettings::kViewByIcon, 0
IF_ZERO
tmpy := $50
;; Compute bounds of icon bitmap
ITK_CALL IconTK::GetIconBounds, icon_param ; inits `tmp_rect`
copy16 tmp_rect::y2, tmpy
ldax #new_name_buf
jsr DetermineIconType ; uses passed name and `src_file_info_params`
ldy #IconEntry::type
sta (icon_ptr),y
;; Assumes flags will not change, regardless of icon.
;; Update location so bottom (name) is in the same place
ITK_CALL IconTK::GetIconBounds, icon_param ; inits `tmp_rect`
;; A,X = `tmpy` - `tmp_rect::y2` (delta between old and new bottom)
lda tmpy
sec
sbc tmp_rect::y2
pha
lda tmpy+1
sbc tmp_rect::y2+1
tax
pla
;; `icony` += A,X
ldy #IconEntry::icony
clc
adc (icon_ptr),y
sta (icon_ptr),y
txa
iny
adc (icon_ptr),y
sta (icon_ptr),y
END_IF
end_filerecord_and_icon_update:
;; Draw the (maybe new) icon
ITK_CALL IconTK::DrawIcon, icon_param
;; Is there a window for the folder/volume?
jsr FindWindowForSrcPath
IF_NOT_ZERO
dst := $06
;; Update the window title
jsr GetWindowTitle
stax dst
ldy new_name_buf
DO
copy8 new_name_buf,y, (dst),y
dey
WHILE_POS
lda result_flags
ora #$80
sta result_flags
END_IF
;; Update affected window paths, ProDOS prefix
jsr NotifyPathChanged
;; --------------------------------------------------
;; Totally done
return result_flags
;;; N bit ($80) set if a window title was changed
result_flags:
.byte 0
.endproc ; DoRenameImpl
DoRename := DoRenameImpl::start
;;; ============================================================
;;; "Rename" dialog
;;; This uses a minimal dialog window to simulate modeless rename.
.proc _DialogOpen
ldy #LETK::kLineEditOptionsNormal
jsr GetSelectionViewBy
IF_A_EQ #DeskTopSettings::kViewByIcon
ldy #LETK::kLineEditOptionsCentered
END_IF
sty rename_line_edit_rec::options
COPY_STRUCT MGTK::Point, tmp_rect::topleft, winfo_rename_dialog::viewloc
CLEAR_BIT7_FLAG cursor_ibeam_flag
jsr SetCursorPointer
MGTK_CALL MGTK::OpenWindow, winfo_rename_dialog
copy16 rename_dialog_params::a_prev, $08
param_call CopyPtr2ToBuf, text_input_buf
LETK_CALL LETK::Init, rename_le_params
LETK_CALL LETK::Activate, rename_le_params
rts
.endproc ; _DialogOpen
;;; ============================================================
.proc _DialogRun
loop: jsr _InputLoop
bmi loop ; continue?
bne _DialogClose ; canceled!
lda text_input_buf ; treat empty as cancel
beq _DialogClose
;; Validate path length before committing
copy16 rename_dialog_params::a_path, $08
param_call CopyPtr2ToBuf, path_buf0
lda path_buf0 ; full path okay?
clc
adc text_input_buf
IF_A_GE #::kMaxPathLength ; not +1 because we'll add '/'
param_call ShowAlertParams, AlertButtonOptions::OK, aux::str_alert_name_too_long
jmp loop
END_IF
ldxy #text_input_buf
return #0
.endproc ; _DialogRun
;;; ============================================================
.proc _DialogClose
MGTK_CALL MGTK::CloseWindow, winfo_rename_dialog
jsr ClearUpdates ; following CloseWindow
jsr SetCursorPointer ; when closing dialog
return #1
.endproc ; _DialogClose
;;; ============================================================
;;; Outputs: N=0/Z=1 if ok, N=0/Z=0 if canceled; N=1 means call again
.proc _InputLoop
LETK_CALL LETK::Idle, rename_le_params
jsr SystemTask
jsr GetNextEvent
cmp #MGTK::EventKind::button_down
jeq _ClickHandler
cmp #MGTK::EventKind::key_down
jeq _KeyHandler
cmp #kEventKindMouseMoved
bne _InputLoop
;; Check if mouse is over window, change cursor appropriately.
MGTK_CALL MGTK::FindWindow, findwindow_params
lda findwindow_params::which_area
IF_A_EQ #MGTK::Area::content
lda findwindow_params::window_id
IF_A_EQ #winfo_rename_dialog::kWindowId
jsr SetCursorIBeamWithFlag
jmp _InputLoop
END_IF
END_IF
jsr SetCursorPointerWithFlag
jmp _InputLoop
.endproc ; _InputLoop
;;; Click handler for rename dialog
.proc _ClickHandler
MGTK_CALL MGTK::FindWindow, findwindow_params
lda findwindow_params::which_area
IF_A_NE #MGTK::Area::content
return #PromptResult::ok
END_IF
lda findwindow_params::window_id
IF_A_NE #winfo_rename_dialog::kWindowId
return #PromptResult::ok
END_IF
copy8 winfo_rename_dialog, event_params
MGTK_CALL MGTK::ScreenToWindow, screentowindow_params
MGTK_CALL MGTK::MoveTo, screentowindow_params::window
COPY_STRUCT screentowindow_params::window, rename_le_params::coords
LETK_CALL LETK::Click, rename_le_params
return #$FF
.endproc ; _ClickHandler
;;; Key handler for rename dialog
.proc _KeyHandler
copy8 event_params::key, rename_le_params::key
;; Modifiers?
ldx event_params::modifiers
stx rename_le_params::modifiers
bne allow ; pass through modified keys
;; No modifiers
IF_A_EQ #CHAR_RETURN
return #PromptResult::ok
END_IF
IF_A_EQ #CHAR_ESCAPE
return #PromptResult::cancel
END_IF
jsr IsControlChar ; pass through control characters
bcc allow
ldy rename_line_edit_rec+LETK::LineEditRecord::caret_pos
jsr IsFilenameChar
bcs ignore
allow: LETK_CALL LETK::Key, rename_le_params
ignore:
return #$FF
.endproc ; _KeyHandler
.endscope ; rename
DoRename := rename::DoRename
old_name_buf := rename::old_name_buf
;;; ============================================================
;;; Input: $06 has `IconEntry` ptr
;;; Output: $08 has `FileRecord` ptr
.proc SetFileRecordPtrFromIconPtr
icon_ptr := $06
file_record_ptr := $08
ldy #IconEntry::record_num
lda (icon_ptr),y
pha ; A = index of icon in window
;; Find the window's FileRecord list.
lda selected_window_id
jsr GetFileRecordListForWindow
stax file_record_ptr ; points at head of list (entry count)
inc16 file_record_ptr ; now points at first FileRecord in list
;; Look up the FileRecord within the list.
pla ; A = index
ASSERT_EQUALS .sizeof(FileRecord), 32
jsr ATimes32 ; A,X = index * 32
addax file_record_ptr, file_record_ptr
rts
.endproc ; SetFileRecordPtrFromIconPtr
;;; ============================================================
;;; Input: A = icon
;;; Output: A,X = icon name ptr
.proc GetIconName
jsr GetIconEntry
addax8 #IconEntry::name
rts
.endproc ; GetIconName
;;; ============================================================
;;; Concatenate paths.
;;; Inputs: Base path in $08, second path in $06
;;; Output: `path_buf3`
.proc JoinPaths
str1 := $8
str2 := $6
buf := path_buf3
ldx #0
lda str1 ; check for nullptr (volume)
ora str1+1
beq do_str2
ldy #0 ; check for empty string
lda (str1),y
beq do_str2
;; Copy $8 (str1)
sta @len
: iny
inx
copy8 (str1),y, buf,x
@len := *+1
cpy #SELF_MODIFIED_BYTE
bne :-
do_str2:
;; Add path separator
inx
copy8 #'/', buf,x
;; Append $6 (str2)
ldy #0
lda (str2),y
IF_NOT_ZERO
sta @len
: iny
inx
copy8 (str2),y, buf,x
@len := *+1
cpy #SELF_MODIFIED_BYTE
bne :-
END_IF
stx buf
rts
.endproc ; JoinPaths
;;; ============================================================
;;; Inputs: A = icon number
.proc SmartportEject
dib_buffer := ::IO_BUFFER
;; Look up device index by icon number
jsr IconToDeviceIndex
RTS_IF_ZC
lda DEVLST,x ; A = unit_number
;; NOTE: Not masked with `UNIT_NUM_MASK`, `FindSmartportDispatchAddress` handles it.
;; Compute SmartPort dispatch address
jsr FindSmartportDispatchAddress
IF_CC
stax status_dispatch
stax control_dispatch
sty status_params::unit_num
sty control_params::unit_number
;; Execute SmartPort call
status_dispatch := *+1
jsr SELF_MODIFIED
.byte SPCall::Status
.addr status_params
IF_CC
lda dib_buffer+SPDIB::Device_Type_Code
IF_A_EQ #SPDeviceType::Disk35
;; Execute SmartPort call
control_dispatch := *+1
jsr SELF_MODIFIED
.byte SPCall::Control
.addr control_params
END_IF
END_IF
END_IF
rts
DEFINE_SP_STATUS_PARAMS status_params, SELF_MODIFIED_BYTE, dib_buffer, 3 ; Return Device Information Block (DIB)
DEFINE_SP_CONTROL_PARAMS control_params, SELF_MODIFIED_BYTE, list, $04 ; For Apple/UniDisk 3.3: Eject disk
list: .word 0 ; 0 items in list
.endproc ; SmartportEject
;;; ============================================================
;;; Following a rename or move of `src_path_buf` to `dst_path_buf`,
;;; update any affected paths.
;;;
;;; * Window paths (so operations within windows still work)
;;; * ProDOS PREFIX (which points at DeskTop's folder)
;;; * Original PREFIX (if copied to RAMCard)
;;; * Restart PREFIX (in the ProDOS Selector code)
;;;
;;; Assert: The path actually changed.
.proc NotifyPathChanged
;; --------------------------------------------------
;; Update any affected window paths
ldx #kMaxDeskTopWindows
DO
txa
pha
ldy window_to_dir_icon_table-1,x ; X = 1-based id, so -1 to index
IF_NOT_ZERO ; isn't `kWindowToDirIconFree`
jsr GetWindowPath
jsr _MaybeUpdateTargetPath
END_IF
pla
tax
dex
WHILE_NOT_ZERO
;; --------------------------------------------------
;; Update prefixes
path := tmp_path_buf ; depends on `src_path_buf`, `dst_path_buf`
;; ProDOS Prefix
MLI_CALL GET_PREFIX, get_set_prefix_params
param_call _MaybeUpdateTargetPath, path
IF_NE
MLI_CALL SET_PREFIX, get_set_prefix_params
END_IF
;; Original Prefix
jsr GetCopiedToRAMCardFlag
IF_MINUS
sta ALTZPOFF
bit LCBANK2
bit LCBANK2
param_call _MaybeUpdateTargetPath, DESKTOP_ORIG_PREFIX
param_call _MaybeUpdateTargetPath, RAMCARD_PREFIX
sta ALTZPON
bit LCBANK1
bit LCBANK1
END_IF
;; Restart Prefix
sta ALTZPOFF
bit LCBANK2
bit LCBANK2
param_call _MaybeUpdateTargetPath, SELECTOR + QuitRoutine::prefix_buffer_offset
sta ALTZPON
bit LCBANK1
bit LCBANK1
rts
DEFINE_GET_PREFIX_PARAMS get_set_prefix_params, path
;;; ============================================================
;;; Replace `src_path_buf` as the prefix of path at $06 with `dst_path_buf`.
;;; Assert: `src_path_buf` is a prefix of the path at $06!
;;; Inputs: A,X = path to update, `src_path_buf` and `dst_path_buf`,
;;; Outputs: Path updated.
;;; Modifies `tmp_path_buf` and $1F00
;;; NOTE: Sometimes called with LCBANK2; must not assume LCBANK1 present!
;;; Trashes $06
.proc _UpdateTargetPath
dst := $06
old_path := $1F00
new_path := tmp_path_buf ; arbitrary usage of this buffer
stax dst
;; Set `old_path` to the old path (should be `src_path_buf` + suffix)
param_call CopyPtr1ToBuf, old_path
;; Set `new_path` to the new prefix
ldy dst_path_buf
DO
copy8 dst_path_buf,y, new_path,y
dey
WHILE_POS
;; Copy the suffix from `old_path` to `new_path`
ldx src_path_buf
cpx old_path
beq assign ; paths are equal, no copying needed
ldy dst_path_buf
DO
inx ; advance into suffix
iny
copy8 old_path,x, new_path,y
WHILE_X_NE old_path
sty new_path
;; Assign the new window path
assign: ldy new_path
DO
copy8 new_path,y, (dst),y
dey
WHILE_POS
rts
.endproc ; _UpdateTargetPath
;;; ============================================================
;;; Following a rename or move of `src_path_buf` to `dst_path_buf`,
;;; update the target path if needed.
;;;
;;; Inputs: A,X = pointer to path to update
;;; Outputs: Z=0 if updated, Z=1 if no change
;;; NOTE: Sometimes called with LCBANK2; must not assume LCBANK1 present!
;;; Trashes $06, $08
.proc _MaybeUpdateTargetPath
ptr := $08
stax ptr
jsr _MaybeStripSlash
;; Is `src_path_buf` a prefix?
copy16 #src_path_buf, $06
jsr IsPathPrefixOf ; Z=0 if a prefix
php
IF_NE
;; It's a prefix! Do the replacement
param_call_indirect _UpdateTargetPath, ptr
END_IF
jsr _MaybeRestoreSlash
plp ; Z=0 if updated
rts
.proc _MaybeStripSlash
;; Did path end with a '/'? If so, set flag and remove.
ldy #0
sty slash_flag
lda (ptr),y
tay ; Y=target path length
lda (ptr),y
IF_A_EQ #'/'
sta slash_flag ; need to restore it later, but
ldy #0 ; remove the '/' for now
lda (ptr),y
sec
sbc #1
sta (ptr),y
END_IF
rts
.endproc ; _MaybeStripSlash
.proc _MaybeRestoreSlash
;; Restore trailing '/' if needed
slash_flag := *+1 ; non-zero if trailing slash needed
lda #SELF_MODIFIED_BYTE
IF_NOT_ZERO
ldy #0
lda (ptr),y
clc
adc #1
sta (ptr),y
tay
copy8 #'/', (ptr),y
END_IF
rts
.endproc ; _MaybeRestoreSlash
slash_flag := _MaybeRestoreSlash::slash_flag
.endproc ; _MaybeUpdateTargetPath
.endproc ; NotifyPathChanged
;;; ============================================================
;;; Check if $06 is same path or parent of $08.
;;; Returns Z=1 if not, Z=0 if it is.
.proc IsPathPrefixOf
ptr1 := $06
ptr2 := $08
ldy #0
lda (ptr1),y ; Compare string lengths. If the same, need
cmp (ptr2),y ; to compare strings. If `ptr1` > `ptr2`
beq compare ; ('/a/b' vs. '/a'), then it's not a problem.
bcs ok
;; Assert: `ptr1` is shorter then `ptr2`
tay ; See if `ptr2` is possibly a subfolder
iny
lda (ptr2),y ; ('/a/b/c' vs. '/a/b') or a sibling
cmp #'/' ; ('/a/bc' vs. /a/b').
bne ok ; At worst, a sibling - that's okay.
;; Potentially self or a subfolder; compare strings.
compare:
ldy #0
lda (ptr1),y
tay
DO
lda (ptr1),y
jsr ToUpperCase
sta @char
lda (ptr2),y
jsr ToUpperCase
@char := *+1
cmp #SELF_MODIFIED_BYTE
bne ok
dey
WHILE_NOT_ZERO
;; Self or subfolder
return #$FF
ok: return #0
.endproc ; IsPathPrefixOf
;;; ============================================================
;;; Dynamically load parts of Desktop
;;; Call `LoadDynamicRoutine` or `RestoreDynamicRoutine`
;;; with A set to routine number (0-8); routine is loaded
;;; from DeskTop file to target address. Returns with
;;; minus flag set on failure.
;;; Routines are:
;;; 0 = format/erase disk - A$ 800,L$1400 call w/ A = 4 = format, A = 5 = erase
;;; 1 = shortcut picker - A$9000,L$1000
;;; 2 = common file dialog - A$6000,L$1000
;;; 3 = part of copy file - A$7000,L$ 800
;;; 4 = shortcut editor - L$7000,L$ 800
;;; 5 = restore shortcut picker - A$5000,L$1000 (restore $5000...$5FFF)
;;; 6 = restore file dialog - A$6000,L$1400 (restore $6000...$73FF)
;;; 7 = restore buffer - A$5000,L$2800 (restore $5000...$77FF)
;;;
;;; Routines 1-5 need appropriate "restore routines" applied when complete.
PROC_USED_IN_OVERLAY
.proc LoadDynamicRoutineImpl
kNumOverlays = 8
pos_table:
.dword kOverlayFormatEraseOffset
.dword kOverlayShortcutPickOffset, kOverlayFileDialogOffset
.dword kOverlayFileCopyOffset
.dword kOverlayShortcutEditOffset, kOverlayDeskTopRestoreSPOffset
.dword kOverlayDeskTopRestoreFDOffset, kOverlayDeskTopRestoreBufferOffset
ASSERT_RECORD_TABLE_SIZE pos_table, kNumOverlays, 4
len_table:
.word kOverlayFormatEraseLength
.word kOverlayShortcutPickLength, kOverlayFileDialogLength
.word kOverlayFileCopyLength
.word kOverlayShortcutEditLength, kOverlayDeskTopRestoreSPLength
.word kOverlayDeskTopRestoreFDLength, kOverlayDeskTopRestoreBufferLength
ASSERT_RECORD_TABLE_SIZE len_table, kNumOverlays, 2
addr_table:
.word kOverlayFormatEraseAddress
.word kOverlayShortcutPickAddress, kOverlayFileDialogAddress
.word kOverlayFileCopyAddress
.word kOverlayShortcutEditAddress, kOverlayDeskTopRestoreSPAddress
.word kOverlayDeskTopRestoreFDAddress, kOverlayDeskTopRestoreBufferAddress
ASSERT_ADDRESS_TABLE_SIZE addr_table, kNumOverlays
DEFINE_OPEN_PARAMS open_params, str_desktop, IO_BUFFER
str_desktop:
PASCAL_STRING kPathnameDeskTop
DEFINE_SET_MARK_PARAMS set_mark_params, 0
DEFINE_READWRITE_PARAMS read_params, 0, 0
DEFINE_CLOSE_PARAMS close_params
;; Called with routine # in A
load: pha
copy8 #AlertButtonOptions::OKCancel, button_options
ASSERT_NOT_EQUALS AlertButtonOptions::OKCancel, 0
bne :+ ; always
restore:
pha
;; Need to set low bit in this case to override the default.
copy8 #AlertButtonOptions::OK|%00000001, button_options
: jsr SetCursorWatch ; before loading overlay
pla
asl a ; y = A * 2 (to index into word table)
tay
asl a ; x = A * 4 (to index into dword table)
tax
copy8 pos_table+0,x, set_mark_params::position+0
copy8 pos_table+1,x, set_mark_params::position+1
copy8 pos_table+2,x, set_mark_params::position+2
copy16 len_table,y, read_params::request_count
copy16 addr_table,y, read_params::data_buffer
retry: MLI_CALL OPEN, open_params
IF_CS
lda #kErrInsertSystemDisk
button_options := *+1
ldx #SELF_MODIFIED_BYTE
jsr ShowAlertOption
cmp #kAlertResultOK
beq retry
return #$FF ; failed
END_IF
lda open_params::ref_num
sta read_params::ref_num
sta set_mark_params::ref_num
MLI_CALL SET_MARK, set_mark_params
MLI_CALL READ, read_params
MLI_CALL CLOSE, close_params
jmp SetCursorPointer ; after loading overlay
.endproc ; LoadDynamicRoutineImpl
LoadDynamicRoutine := LoadDynamicRoutineImpl::load
RestoreDynamicRoutine := LoadDynamicRoutineImpl::restore
;;; ============================================================
PROC_USED_IN_OVERLAY
;;; A,X = A * 16
.proc ATimes16
ldx #4
bne AShiftX ; always
.endproc ; ATimes16
;;; A,X = A * 32
.proc ATimes32
ldx #5
bne AShiftX ; always
.endproc ; ATimes32
;;; A,X = A * 64
.proc ATimes64
ldx #6
FALL_THROUGH_TO AShiftX
.endproc ; ATimes64
;;; A,X = A << X
.proc AShiftX
ldy #0
sty hi
DO
asl a
rol hi
dex
WHILE_NOT_ZERO
hi := *+1
ldx #SELF_MODIFIED_BYTE
rts
.endproc ; AShiftX
;;; ============================================================
;;; Remove segment from path at A,X
;;; Inputs: A,X = path
;;; Output: A = length
.proc RemovePathSegment
jsr PushPointers
ptr := $06
stax ptr
ldy #0
lda (ptr),y ; length
beq finish
tay
DO
lda (ptr),y
cmp #'/'
beq found
dey
WHILE_NOT_ZERO
iny
found: dey
tya
ldy #0
sta (ptr),y
finish: jsr PopPointers ; do not tail-call optimize!
rts
.endproc ; RemovePathSegment
;;; ============================================================
;;; Given a path and a prospective name, update the filesystem with
;;; the desired case bits, considering type and the option
;;; `DeskTopSettings::kOptionsSetCaseBits`.
;;;
;;; Volume - If option set, write case bits to volume header;
;;; otherwise clear case bits in volume header and recase the string
;;; in memory.
;;;
;;; Regular File - If option set, write case bits to directory entry;
;;; otherwise clear case bits in directory entry and recase the string
;;; in memory.
;;;
;;; AppleWorks File - Write case bits to auxtype. If option set, also
;;; write case bits to directory entry. Otherwise, clear case bits in
;;; directory entry. (The string in memory is never recased, which
;;; makes this not a superset of the regular file case.)
;;;
;;; Inputs: `src_path_buf` is file, `stashed_name` is new name
;;; Outputs: `stashed_name` had "resulting" file case
.proc ApplyCaseBits
param_call CalculateCaseBits, stashed_name
stax case_bits
jsr GetSrcFileInfo
bcs ret
copy8 DEVNUM, block_params::unit_num
lda src_file_info_params::storage_type
IF_A_NE #ST_VOLUME_DIRECTORY
;; --------------------------------------------------
;; File
param_call GetFileEntryBlock, src_path_buf
bcs ret
stax block_params::block_num
block_ptr := $08
param_call GetFileEntryBlockOffset, block_buffer ; Y is already the entry number
stax block_ptr
MLI_CALL READ_BLOCK, block_params
bcs ret
;; Is AppleWorks?
ldy #FileEntry::file_type
lda (block_ptr),y
IF_A_NE_ALL_OF #FT_ADB, #FT_AWP, #FT_ASP
;; --------------------------------------------------
;; Non-AppleWorks file
jsr get_case_bits_per_option_and_adjust_string
ELSE
;; --------------------------------------------------
;; AppleWorks file
;; Per Per File Type Notes: File Type $19 (25) All Auxiliary Types (etc)
;; https://web.archive.org/web/2007/http://web.pdx.edu/~heiss/technotes/ftyp/ftn.19.xxxx.html
;;
;; Like as GS/OS case bits, except:
;; * Shifted left by one bit; low bit is clear
;; * Word is stored byte-swapped
lda case_bits
asl a
tax
lda case_bits+1
rol a
ldy #FileEntry::aux_type
sta (block_ptr),y
txa
iny
sta (block_ptr),y
jsr get_option
IF_ZERO
;; Option not set, so zero case bits; memory string preserved
ldax #0
ELSE
;; Option set, so write case bits as is.
ldax case_bits
END_IF
END_IF
ldy #FileEntry::case_bits
sta (block_ptr),y
iny
txa
sta (block_ptr),y
FALL_THROUGH_TO write_block
write_block:
MLI_CALL WRITE_BLOCK, block_params
ret: rts
END_IF
;; --------------------------------------------------
;; Volume
copy16 #kVolumeDirKeyBlock, block_params::block_num
MLI_CALL READ_BLOCK, block_params
bcs ret
jsr get_case_bits_per_option_and_adjust_string
stax block_buffer + VolumeDirectoryHeader::case_bits
jmp write_block
;; --------------------------------------------------
;; Helpers
;; Returns Z=0 if option set, Z=1 otherwise
get_option:
ldx #DeskTopSettings::options
jsr ReadSetting
and #DeskTopSettings::kOptionsSetCaseBits
rts
;; Returns A,X=case bits if option set, A,X=0 otherwise
get_case_bits_per_option_and_adjust_string:
jsr get_option
IF_ZERO
;; Option not set, so zero case bits, adjust memory string
param_call UpcaseString, stashed_name
param_call AdjustFileNameCase, stashed_name
ldax #0
ELSE
;; Option set, so write case bits as is, leave string alone
ldax case_bits
END_IF
rts
;; --------------------------------------------------
block_buffer := $800
DEFINE_READWRITE_BLOCK_PARAMS block_params, block_buffer, SELF_MODIFIED
.endproc ; ApplyCaseBits
;;; ============================================================
;;; Per Technical Note: GS/OS #8: Filenames With More Than CAPS and Numerals
;;; https://web.archive.org/web/2007/http://web.pdx.edu/~heiss/technotes/gsos/tn.gsos.08.html
;;; Input: A,X = name
;;; Output: A,X = case bits
;;; Trashes: $06/$08
PROC_USED_IN_OVERLAY
.proc CalculateCaseBits
ptr := $06
bits := $08
stax ptr
ldy #15
DO
lda (ptr),y
cmp #'a' ; set C if lowercase
ror bits+1
ror bits
dey
WHILE_NOT_ZERO
sec
ror bits+1
ror bits
ldax bits
rts
.endproc ; CalculateCaseBits
;;; ============================================================
;;; Message handler for OK/Cancel dialog
;;; Outputs: N=0/Z=1 if ok, N=0/Z=0 if canceled; N=1 means call again
PROC_USED_IN_OVERLAY
.proc PromptInputLoop
bit has_input_field_flag
IF_NS
LETK_CALL LETK::Idle, prompt_le_params
END_IF
jsr SystemTask
jsr GetNextEvent
cmp #MGTK::EventKind::button_down
jeq _ClickHandler
cmp #MGTK::EventKind::key_down
jeq _KeyHandler
;; Does the dialog have an input field?
bit has_input_field_flag
bpl PromptInputLoop
cmp #kEventKindMouseMoved
bne PromptInputLoop
;; Check if mouse is over input field, change cursor appropriately.
copy8 winfo_prompt_dialog, screentowindow_params::window_id
MGTK_CALL MGTK::ScreenToWindow, screentowindow_params
MGTK_CALL MGTK::MoveTo, screentowindow_params::window
MGTK_CALL MGTK::InRect, name_input_rect
ASSERT_EQUALS MGTK::inrect_outside, 0
beq out
jsr SetCursorIBeamWithFlag ; toggling in prompt dialog
jmp PromptInputLoop
out: jsr SetCursorPointerWithFlag ; toggling in prompt dialog
jmp PromptInputLoop
;;; Click handler for prompt dialog
.proc _ClickHandler
MGTK_CALL MGTK::FindWindow, findwindow_params
lda findwindow_params::which_area
IF_A_NE #MGTK::Area::content
return #$FF
END_IF
lda findwindow_params::window_id
IF_A_NE #winfo_prompt_dialog::kWindowId
return #$FF
END_IF
copy8 winfo_prompt_dialog, event_params
MGTK_CALL MGTK::ScreenToWindow, screentowindow_params
MGTK_CALL MGTK::MoveTo, screentowindow_params::window
MGTK_CALL MGTK::InRect, ok_button::rect
IF_NOT_ZERO
BTK_CALL BTK::Track, ok_button
IF_NC
lda #PromptResult::ok
END_IF
rts
END_IF
bit prompt_button_flags
IF_NC
MGTK_CALL MGTK::InRect, cancel_button::rect
IF_NOT_ZERO
BTK_CALL BTK::Track, cancel_button
IF_NC
lda #PromptResult::cancel
END_IF
rts
END_IF
END_IF
bit has_input_field_flag
IF_NC
lda #$FF ; in case handler is just RTS
jmp (PromptDialogClickHandlerHook)
END_IF
;; Was click inside text box?
MGTK_CALL MGTK::InRect, name_input_rect
IF_NOT_ZERO
COPY_STRUCT screentowindow_params::window, prompt_le_params::coords
LETK_CALL LETK::Click, prompt_le_params
END_IF
return #$FF
.endproc ; _ClickHandler
;;; Key handler for prompt dialog
.proc _KeyHandler
copy8 event_params::key, prompt_le_params::key
ldx event_params::modifiers
stx prompt_le_params::modifiers
IF_NOT_ZERO
;; Modifiers
bit has_input_field_flag
IF_NS
LETK_CALL LETK::Key, prompt_le_params
jsr UpdateOKButton
ELSE
jsr KeyHookRelay
return #$FF
END_IF
ELSE
;; No modifiers
cmp #CHAR_RETURN
beq _HandleKeyOK
IF_A_EQ #CHAR_ESCAPE
bit prompt_button_flags
bpl _HandleKeyCancel
bmi _HandleKeyOK ; always
END_IF
bit has_input_field_flag
IF_NS
jsr IsControlChar ; pass through control characters
bcc allow
ldy prompt_line_edit_rec+LETK::LineEditRecord::caret_pos
jsr IsFilenameChar
bcs ignore
allow: LETK_CALL LETK::Key, prompt_le_params
jsr UpdateOKButton
ignore:
ELSE
jsr KeyHookRelay
return #$FF
END_IF
END_IF
return #$FF
;; --------------------------------------------------
KeyHookRelay:
jmp (PromptDialogKeyHandlerHook)
.proc _HandleKeyOK
BTK_CALL BTK::Flash, ok_button
IF_NS
return #$FF ; ignore
END_IF
return #PromptResult::ok
.endproc ; _HandleKeyOK
.proc _HandleKeyCancel
BTK_CALL BTK::Flash, cancel_button
return #PromptResult::cancel
.endproc ; _HandleKeyCancel
.endproc ; _KeyHandler
.endproc ; PromptInputLoop
;;; NOTE: These are referenced by indirect JMP and *must not*
;;; cross page boundaries.
PAD_IF_NEEDED_TO_AVOID_PAGE_BOUNDARY
PromptDialogClickHandlerHook:
.addr SELF_MODIFIED
PAD_IF_NEEDED_TO_AVOID_PAGE_BOUNDARY
PromptDialogKeyHandlerHook:
.addr SELF_MODIFIED
;;; ============================================================
;;; Input: A=character
;;; Output: C=0 if control, C=1 if not
.proc IsControlChar
cmp #CHAR_DELETE
bcs yes
cmp #' '
rts ; C=0 (if less) or 1
yes: clc ; C=0
rts
.endproc ; IsControlChar
;;; ============================================================
;;; Input: A=character, Y=caret_pos
;;; Output: C=0 if valid filename character, C=1 otherwise
.proc IsFilenameChar
cmp #'.'
beq allow_if_not_first
cmp #'0'
bcc ignore
cmp #'9'+1
bcc allow_if_not_first
cmp #'A'
bcc ignore
cmp #'Z'+1
bcc allow
.if kBuildSupportsLowercase
cmp #'a'
bcc ignore
cmp #'z'+1
bcc allow
.endif
bcs ignore ; always
allow_if_not_first:
cpy #0
beq ignore
allow: clc
rts
ignore: sec
rts
.endproc ; IsFilenameChar
;;; ============================================================
;;; "About" dialog
.proc AboutDialogProc
MGTK_CALL MGTK::OpenWindow, winfo_about_dialog
lda #winfo_about_dialog::kWindowId
jsr SafeSetPortFromWindowId
param_call DrawDialogFrame, aux::about_dialog_frame_rect
jsr SetPenModeXOR
param_call DrawDialogTitle, aux::str_about1
param_call DrawDialogLabel, 1 | DDL_CENTER, aux::str_about2
param_call DrawDialogLabel, 2 | DDL_CENTER, aux::str_about3
param_call DrawDialogLabel, 3 | DDL_CENTER, aux::str_about4
param_call DrawDialogLabel, 5 | DDL_CENTER, aux::str_about5
param_call DrawDialogLabel, 6 | DDL_CENTER, aux::str_about6
param_call DrawDialogLabel, 7 | DDL_CENTER, aux::str_about7
param_call DrawDialogLabel, 9, aux::str_about8
param_call DrawDialogLabel, 9 | DDL_RIGHT, aux::str_about9
DO
jsr SystemTask
jsr GetNextEvent
BREAK_IF_A_EQ #MGTK::EventKind::button_down
WHILE_A_NE #MGTK::EventKind::key_down
MGTK_CALL MGTK::CloseWindow, winfo_about_dialog
jmp ClearUpdates ; following CloseWindow
.endproc ; AboutDialogProc
;;; ============================================================
PROC_USED_IN_OVERLAY
.proc SetCursorPointerWithFlag
bit cursor_ibeam_flag
IF_NS
jsr SetCursorPointer ; toggle routine
CLEAR_BIT7_FLAG cursor_ibeam_flag
END_IF
rts
.endproc ; SetCursorPointerWithFlag
.proc SetCursorIBeamWithFlag
bit cursor_ibeam_flag
IF_NC
MGTK_CALL MGTK::SetCursor, MGTK::SystemCursor::ibeam
SET_BIT7_FLAG cursor_ibeam_flag
END_IF
rts
.endproc ; SetCursorIBeamWithFlag
cursor_ibeam_flag: ; high bit set if I-beam, clear if pointer
.byte 0
;;; ============================================================
.proc OpenProgressDialog
MGTK_CALL MGTK::OpenWindow, winfo_progress_dialog
jsr SetPortForProgressDialog
param_call DrawDialogFrame, aux::progress_dialog_frame_rect
MGTK_CALL MGTK::FrameRect, progress_dialog_bar_frame
jmp SetCursorWatch ; undone by `CloseProgressDialog`
.endproc ; OpenProgressDialog
;;; ============================================================
.proc SetPortForProgressDialog
lda #winfo_progress_dialog::kWindowId
jmp SafeSetPortFromWindowId
.endproc ; SetPortForProgressDialog
;;; ============================================================
.proc CloseProgressDialog
MGTK_CALL MGTK::CloseWindow, winfo_progress_dialog::window_id
jsr ClearUpdates ; following CloseWindow
jmp SetCursorPointer ; when closing dialog
.endproc ; CloseProgressDialog
;;; ============================================================
;;; Draw Progress Dialog Label
;;; A,X = string
;;; Y = row number (0, 1, 2, ... )
.proc DrawProgressDialogLabel
pha
txa
pha
;; y = base + aux::kDialogLabelHeight * line
tya ; low byte
ldx #0 ; high byte
ldy #aux::kDialogLabelHeight
jsr Multiply_16_8_16
addax #kProgressDialogLabelBaseY, progress_dialog_label_pos::ycoord
MGTK_CALL MGTK::MoveTo, progress_dialog_label_pos
pla
tax
pla
jmp DrawString
.endproc ; DrawProgressDialogLabel
;;; ============================================================
.proc DrawDialogPathBuf0
ldax #path_buf0
FALL_THROUGH_TO DrawDialogPath
.endproc ; DrawDialogPathBuf0
.include "../lib/drawdialogpath.s"
;;; ============================================================
;;; Save/Restore window state at shutdown/launch
.scope save_restore_windows
desktop_file_io_buf := IO_BUFFER
desktop_file_data_buf := $1800
kFileSize = 1 + 8 * .sizeof(DeskTopFileItem) + 1
DEFINE_CREATE_PARAMS create_params, str_desktop_file, ACCESS_DEFAULT, $F1
DEFINE_OPEN_PARAMS open_params, str_desktop_file, desktop_file_io_buf
DEFINE_READWRITE_PARAMS rw_params, desktop_file_data_buf, kFileSize
DEFINE_CLOSE_PARAMS close_params
str_desktop_file:
PASCAL_STRING kPathnameDeskTopState
.proc Save
data_ptr := $06
winfo_ptr := $08
;; Write file format version byte
copy8 #kDeskTopFileVersion, desktop_file_data_buf
copy16 #desktop_file_data_buf+1, data_ptr
;; Get first window pointer
MGTK_CALL MGTK::FrontWindow, window_id
lda window_id
beq finish
jsr GetWindowPtr
stax winfo_ptr
copy8 #0, depth
;; Is there a lower window?
recurse_down:
next_ptr := $0A
ldy #MGTK::Winfo::nextwinfo
copy16in (winfo_ptr),y, next_ptr
ora next_ptr
beq recurse_up ; Nope - just finish.
;; Yes, recurse
inc depth
lda winfo_ptr
pha
lda winfo_ptr+1
pha
copy16 next_ptr, winfo_ptr
jmp recurse_down
recurse_up:
jsr _WriteWindowInfo
depth := *+1 ; Last window?
lda #SELF_MODIFIED_BYTE
beq finish ; Yes - we're done!
dec depth ; No, pop the stack and write the next
pla
sta winfo_ptr+1
pla
sta winfo_ptr
jmp recurse_up
finish: ldy #0 ; Write sentinel
tay
sta (data_ptr),y
;; Write out file, to current prefix.
jsr WriteOutFile
;; If DeskTop was copied to RAMCard, also write to original prefix.
jsr GetCopiedToRAMCardFlag
bpl exit
;; * Can't use `src_path_buf`, that's holding external path to invoke
;; * Can't use `dst_path_buf`, that's inside `IO_BUFFER`
param_call CopyDeskTopOriginalPrefix, tmp_path_buf
;; Append '/'
ldy tmp_path_buf
iny
copy8 #'/', tmp_path_buf,y
;; Append filename
ldx #0
DO
inx
iny
copy8 str_desktop_file,x, tmp_path_buf,y
WHILE_X_NE str_desktop_file
sty tmp_path_buf
;; Write the file
ldax #tmp_path_buf
stax create_params::pathname
stax open_params::pathname
jsr WriteOutFile
exit: rts
.proc _WriteWindowInfo
path_ptr := $0A
;; Find name
ldy #MGTK::Winfo::window_id
lda (winfo_ptr),y
pha ; A = window_id
jsr GetWindowPath
stax path_ptr
;; Copy path in
ASSERT_EQUALS DeskTopFileItem::window_path, 0
ldy #::kPathBufferSize-1
DO
copy8 (path_ptr),y, (data_ptr),y
dey
WHILE_POS
;; Copy view_by in
pla ; A = window_id
tax
lda win_view_by_table-1,x
ldy #DeskTopFileItem::view_by
sta (data_ptr),y
;; Location - copy to `new_window_viewloc` as a temp location, then into data
ldy #MGTK::Winfo::port + MGTK::GrafPort::viewloc + .sizeof(MGTK::Point)-1
ldx #.sizeof(MGTK::Point)-1
DO
copy8 (winfo_ptr),y, new_window_viewloc,x
dey
dex
WHILE_POS
ldy #DeskTopFileItem::viewloc+.sizeof(MGTK::Point)-1
ldx #.sizeof(MGTK::Point)-1
DO
copy8 new_window_viewloc,x, (data_ptr),y
dey
dex
WHILE_POS
;; Bounds - copy to `new_window_maprect` as a temp location, then into data
ldy #MGTK::Winfo::port + MGTK::GrafPort::maprect + .sizeof(MGTK::Rect)-1
ldx #.sizeof(MGTK::Rect)-1
DO
copy8 (winfo_ptr),y, new_window_maprect,x
dey
dex
WHILE_POS
ldy #DeskTopFileItem::maprect+.sizeof(MGTK::Rect)-1
ldx #.sizeof(MGTK::Rect)-1
DO
copy8 new_window_maprect,x, (data_ptr),y
dey
dex
WHILE_POS
;; Offset to next entry
add16_8 data_ptr, #.sizeof(DeskTopFileItem)
rts
.endproc ; _WriteWindowInfo
window_id := findwindow_params::window_id
.endproc ; Save
.proc Open
MLI_CALL OPEN, open_params
rts
.endproc ; Open
.proc Close
MLI_CALL CLOSE, close_params
rts
.endproc ; Close
.proc WriteOutFile
MLI_CALL CREATE, create_params
jsr Open
IF_CC
lda open_params::ref_num
sta rw_params::ref_num
sta close_params::ref_num
MLI_CALL WRITE, rw_params
jsr Close
END_IF
rts
.endproc ; WriteOutFile
.endscope ; save_restore_windows
SaveWindows := save_restore_windows::Save
;;; ============================================================
;;; Find the FileEntry for a file within the containing
;;; directory, providing the block number and offset.
;;;
;;; The intended use is to modify properties of files that
;;; GET/SET_FILE_INFO MLI calls can't, such as:
;;; * Modifying the `version`/`min_version` bytes, which are
;;; used by GS/OS to store filename case bits.
;;; * Modifying the `key_pointer` and other sensitive fields,
;;; e.g. to allow relinking files.
;;; * Updating a subdirectory's key block's `parent_pointer`
;;; and `parent_entry_number` fields.
;;;
;;; Input: A,X = path
;;; Output: C=0, A,X=block, Y=entry on success; C=1 on error
;;; If successful, $06 points at `FileEntry` in block buffer
.proc GetFileEntryBlock
;;; Memory Map
io_buf := $1000 ; $1000-$13FF
block_buf := $1400 ; $1400-$15FF
path_buf := $1600
filename := $1670
entry_num := $1680 ; (byte) entry number in current block
current_block := $1681 ; (word) current block number
saw_header_flag := $1683 ; (byte) indicates header entry seen
kEntriesPerBlock = $0D
ptr := $06
stax ptr
param_call CopyPtr1ToBuf, path_buf
;; Clear out pointer to next block; used to identify
;; the current block.
lda #0
sta block_buf+2
sta block_buf+3
sta saw_header_flag
;; --------------------------------------------------
;; Split path into dir path and filename
ldy path_buf
DO
lda path_buf,y ; find last '/'
BREAK_IF_A_EQ #'/'
inx ; length of filename
dey
WHILE_NOT_ZERO
dey ; length not including '/'
IF_ZERO
sec ; was a volume path - failure
rts
END_IF
tya
pha ; A = new path length
iny
ldx #0 ; copy out filename
DO
inx
iny
lda path_buf,y
jsr ToUpperCase
sta filename,x
WHILE_Y_NE path_buf
stx filename
pla ; A = new path length
sta path_buf
;; --------------------------------------------------
;; Open directory, search blocks for filename
JUMP_TABLE_MLI_CALL OPEN, open_params
jcs exit
lda open_params::ref_num
sta read_params::ref_num
sta close_params::ref_num
next_block:
;; This is the block we're about to read; save for later.
copy16 block_buf+2, current_block
JUMP_TABLE_MLI_CALL READ, read_params
bcs close
copy8 #AS_BYTE(-1), entry_num
entry_ptr := $06
copy16 #(block_buf+4 - .sizeof(FileEntry)), entry_ptr
next_entry:
;; Advance to next entry
lda entry_num
cmp #kEntriesPerBlock
beq next_block
inc entry_num
add16_8 entry_ptr, #.sizeof(FileEntry)
;; Header?
lda saw_header_flag
IF_ZERO
inc saw_header_flag
bne next_entry ; always
END_IF
;; Active entry?
ldy #FileEntry::storage_type_name_length
lda (entry_ptr),y
beq next_entry
tax ; X = `storage_type_name_length`
;; Is this the first block? Get block num from entry's pointer.
lda current_block
ora current_block+1
IF_ZERO
ldy #FileEntry::header_pointer
copy16in (entry_ptr),y, current_block
END_IF
;; See if this is the file we're looking for
txa ; A = `storage_type_name_length`
and #NAME_LENGTH_MASK
cmp filename
bne next_entry
tay
ASSERT_EQUALS FileEntry::file_name, 1
DO
lda (entry_ptr),y
cmp filename,y
bne next_entry
dey
WHILE_NOT_ZERO
;; Match!
clc
close: php
JUMP_TABLE_MLI_CALL CLOSE, close_params
plp
exit:
;; Only valid if C=0
ldax current_block
ldy entry_num
rts
DEFINE_OPEN_PARAMS open_params, path_buf, io_buf
DEFINE_READWRITE_PARAMS read_params, block_buf, BLOCK_SIZE
DEFINE_CLOSE_PARAMS close_params
.endproc ; GetFileEntryBlock
;;; ============================================================
;;; After calling `GetFileEntryBlock`, this can be used to translate
;;; the entry number in Y into the address of the corresponding
;;; `FileEntry` with a memory buffer for the block.
;;; Inputs: A,X = directory block, Y = entry number in block
;;; Outputs: A,X = pointer to `FileEntry`
.proc GetFileEntryBlockOffset
;; Skip prev/next block pointers
addax8 #4
;; Iterate through entries
IF_Y_NE #0
DO
addax8 #.sizeof(FileEntry)
dey
WHILE_NOT_ZERO
END_IF
rts
.endproc ; GetFileEntryBlockOffset
;;; ============================================================
;;;
;;; Routines beyond this point are used by overlays
;;;
;;; ============================================================
PROC_USED_IN_OVERLAY
;;; ============================================================
mli_relay_checkevents_flag: ; bit7
.byte 0
.proc MLIRelayImpl
params_src := $7E
;; Since this is likely to be I/O bound, process events
;; so the mouse stays responsive.
bit mli_relay_checkevents_flag
IF_NS
MGTK_CALL MGTK::CheckEvents
END_IF
;; Adjust return address on stack, compute
;; original params address.
pla
sta params_src
clc
adc #<3
tax
pla
sta params_src+1
adc #>3
pha
txa
pha
;; Copy the params here
ldy #3 ; ptr is off by 1
DO
copy8 (params_src),y, params-1,y
dey
WHILE_NOT_ZERO
;; Bank and call
sta ALTZPOFF
bit ROMIN2
jsr MLI
params: .res 3
sta ALTZPON
php
bit LCBANK1
bit LCBANK1
plp
rts
.endproc ; MLIRelayImpl
;;; ============================================================
;;; Preserves A
PROC_USED_IN_OVERLAY
.proc SetCursorWatch
pha
MGTK_CALL MGTK::SetCursor, MGTK::SystemCursor::watch
pla
rts
.endproc ; SetCursorWatch
PROC_USED_IN_OVERLAY
.proc SetCursorPointer
MGTK_CALL MGTK::SetCursor, MGTK::SystemCursor::pointer
rts
.endproc ; SetCursorPointer
;;; ============================================================
;;; Inputs: A = new `prompt_button_flags` value
PROC_USED_IN_OVERLAY
.proc OpenPromptWindow
sta prompt_button_flags
copy8 #0, text_input_buf
copy8 #BTK::kButtonStateNormal, ok_button::state
lda #0
sta has_input_field_flag
sta has_device_picker_flag
sta cursor_ibeam_flag
jsr SetCursorPointer
copy16 #NoOp, PromptDialogClickHandlerHook
copy16 #NoOp, PromptDialogKeyHandlerHook
MGTK_CALL MGTK::OpenWindow, winfo_prompt_dialog
jsr SetPortForDialogWindow
param_call DrawDialogFrame, aux::prompt_dialog_frame_rect
BTK_CALL BTK::Draw, ok_button
bit prompt_button_flags
IF_NC
BTK_CALL BTK::Draw, cancel_button
END_IF
rts
.endproc ; OpenPromptWindow
;;; ============================================================
PROC_USED_IN_OVERLAY
.proc SetPortForDialogWindow
lda #winfo_prompt_dialog::kWindowId
jmp SafeSetPortFromWindowId
.endproc ; SetPortForDialogWindow
;;; ============================================================
;;; Draw dialog label.
;;; A,X has pointer to DrawText params block
;;; Y has row number (1, 2, ... ) in low nibble, alignment in top nibble
DDL_LEFT = $00 ; Left aligned relative to `kDialogLabelDefaultX`
DDL_VALUE = $10 ; Left aligned relative to `kDialogValueLeft`
DDL_CENTER = $20 ; centered within dialog
DDL_RIGHT = $30 ; Right aligned
DDL_LRIGHT = $40 ; Right aligned relative to `kDialogLabelRightX`
PROC_USED_IN_OVERLAY
.proc DrawDialogLabel
textwidth_params := $8
textptr := $8
textlen := $A
result := $B
ptr := $6
stx ptr+1
sta ptr
tya
and #%00001111
sta row
tya
and #%11110000 ; A = flags
beq calc_y ; DDL_LEFT
IF_A_EQ #DDL_VALUE
copy16 #kDialogValueLeft, dialog_label_pos::xcoord
ASSERT_EQUALS .hibyte(::kDialogValueLeft), 0
beq calc_y
END_IF
;; Compute text width
pha ; A = flags
ldxy ptr
inxy
stxy textptr
ldax ptr
jsr AuxLoad
sta textlen
MGTK_CALL MGTK::TextWidth, textwidth_params
pla ; A = flags
IF_A_EQ #DDL_CENTER
sub16 #kPromptDialogWidth, result, dialog_label_pos::xcoord
lsr16 dialog_label_pos::xcoord
jmp calc_y
END_IF
IF_A_EQ #DDL_RIGHT
sub16 #kPromptDialogWidth - kDialogLabelDefaultX, result, dialog_label_pos::xcoord
ELSE
;; DDL_LRIGHT
sub16 #kDialogLabelRightX, result, dialog_label_pos::xcoord
END_IF
calc_y:
;; y = base + aux::kDialogLabelHeight * line
row := *+1
lda #SELF_MODIFIED_BYTE ; low byte
ldx #0 ; high byte
ldy #aux::kDialogLabelHeight
jsr Multiply_16_8_16
addax #aux::kDialogLabelBaseY, dialog_label_pos::ycoord
MGTK_CALL MGTK::MoveTo, dialog_label_pos
param_call_indirect DrawString, ptr
;; Restore default X position
copy16 #kDialogLabelDefaultX, dialog_label_pos::xcoord
rts
.endproc ; DrawDialogLabel
;;; ============================================================
PROC_USED_IN_OVERLAY
.proc UpdateOKButton
bit has_device_picker_flag
IF_NS
lda #0
jsr ::FormatEraseOverlay::ValidSelection ; preserves A
bpl set_state
lda #$80
bne set_state ; always
END_IF
bit has_input_field_flag
bpl ret
lda #BTK::kButtonStateNormal
ldx text_input_buf
IF_ZERO
lda #BTK::kButtonStateChecked
END_IF
set_state:
IF_A_NE ok_button::state
sta ok_button::state
BTK_CALL BTK::Hilite, ok_button
END_IF
ret: rts
.endproc ; UpdateOKButton
;;; ============================================================
;;; Draw text, pascal string address in A,X
;;; String must be in aux or LC memory.
PROC_USED_IN_OVERLAY
.proc DrawString
params := $6
textptr := $6
textlen := $8
stax textptr
jsr AuxLoad
IF_NOT_ZERO
sta textlen
inc16 textptr
MGTK_CALL MGTK::DrawText, params
END_IF
rts
.endproc ; DrawString
;;; ============================================================
PROC_USED_IN_OVERLAY
.proc DrawDialogTitle
text_params := $6
text_addr := text_params + 0
text_length := text_params + 2
text_width := text_params + 3
stax text_addr ; input is length-prefixed string
jsr AuxLoad
sta text_length
inc16 text_addr ; point past length byte
MGTK_CALL MGTK::TextWidth, text_params
sub16 #kPromptDialogWidth, text_width, pos_dialog_title::xcoord
lsr16 pos_dialog_title::xcoord ; /= 2
MGTK_CALL MGTK::MoveTo, pos_dialog_title
MGTK_CALL MGTK::DrawText, text_params
rts
.endproc ; DrawDialogTitle
;;; ============================================================
PROC_USED_IN_OVERLAY
.proc NoOp
rts
.endproc ; NoOp
;;; ============================================================
;;; Adjusted to point at file/files (singular/plural)
ptr_str_files_suffix:
.addr str_files_suffix
;;; ============================================================
;;; Populate `str_file_count` based on `file_count`. As a side
;;; effect, adjusts `ptr_str_files_suffix` as well, on the
;;; assumption it may be output as well.
.proc ComposeFileCountString
;; Populate `str_file_count`
ldax file_count
jsr IntToStringWithSeparators
ldx #0
DO
inx
copy8 str_from_int,x, str_file_count,x
WHILE_X_NE str_from_int
inx
copy8 #' ', str_file_count,x
stx str_file_count
;; Adjust `ptr_str_files_suffix`
lda file_count+1 ; > 255?
IF_ZERO
lda file_count
IF_A_EQ #1
copy16 #str_file_suffix, ptr_str_files_suffix ; singular
rts
END_IF
END_IF
copy16 #str_files_suffix, ptr_str_files_suffix ; plural
rts
.endproc ; ComposeFileCountString
;;; ============================================================
;;; Input: A,X = string to copy
;;; Trashes: $06
PROC_USED_IN_OVERLAY
.proc CopyToBuf0
ptr1 := $06
stax ptr1
param_jump CopyPtr1ToBuf, path_buf0
.endproc ; CopyToBuf0
;;; ============================================================
;;; Input: A,X = string to copy
;;; Trashes: $06
.proc CopyToBuf4
ptr1 := $06
stax ptr1
param_jump CopyPtr1ToBuf, path_buf4
.endproc ; CopyToBuf4
;;; ============================================================
PROC_USED_IN_OVERLAY
;;; Wrapper for `MGTK::GetEvent`, returns the `EventKind` in A
.proc GetEvent
MGTK_CALL MGTK::GetEvent, event_params
lda event_params::kind
rts
.endproc ; GetEvent
.proc PeekEvent
MGTK_CALL MGTK::PeekEvent, event_params
rts
.endproc ; PeekEvent
.proc SetPenModeXOR
MGTK_CALL MGTK::SetPenMode, penXOR
rts
.endproc ; SetPenModeXOR
.proc SetPenModeCopy
MGTK_CALL MGTK::SetPenMode, pencopy
rts
.endproc ; SetPenModeCopy
.proc SetPenModeNotCopy
MGTK_CALL MGTK::SetPenMode, notpencopy
rts
.endproc ; SetPenModeNotCopy
.proc DrawDialogFrame
stax addr
jsr SetPenModeNotCopy
MGTK_CALL MGTK::SetPenSize, pensize_frame
MGTK_CALL MGTK::FrameRect, SELF_MODIFIED, addr
MGTK_CALL MGTK::SetPenSize, pensize_normal
rts
.endproc ; DrawDialogFrame
;;; ============================================================
.proc InitSetDesktopPort
MGTK_CALL MGTK::InitPort, desktop_grafport
;; Exclude menu bar
ldax #kMenuBarHeight
stax desktop_grafport + MGTK::GrafPort::viewloc + MGTK::Point::ycoord
stax desktop_grafport + MGTK::GrafPort::maprect + MGTK::Rect::y1
MGTK_CALL MGTK::SetPort, desktop_grafport
rts
.endproc ; InitSetDesktopPort
;;; ============================================================
.proc ClosePromptDialog
MGTK_CALL MGTK::CloseWindow, winfo_prompt_dialog
jsr ClearUpdates ; following CloseWindow
jmp SetCursorPointer ; when closing dialog
.endproc ; ClosePromptDialog
;;; ============================================================
;;; Output: A = number of selected icons
.proc GetSelectionCount
lda selected_icon_count
rts
.endproc ; GetSelectionCount
;;; ============================================================
;;; Input: A = index in selection
;;; Output: A,X = IconEntry address
.proc GetSelectedIcon
tax
lda selected_icon_list,x
jmp GetIconEntry
.endproc ; GetSelectedIcon
;;; ============================================================
;;; Output: A = window with selection, 0 if desktop
.proc GetSelectionWindow
lda selected_window_id
rts
.endproc ; GetSelectionWindow
;;; ============================================================
;;; Determine if an icon is in the current selection.
;;; Inputs: A=icon number
;;; Outputs: Z=1 if found, X=index in `selected_icon_list`
;;; X modified, A,Y preserved
.proc IsIconSelected
;; TODO: Update to use highlight bit in IconEntry::state
ldx selected_icon_count
IF_NOT_ZERO
dex
DO
cmp selected_icon_list,x
beq done ; found it!
dex
WHILE_POS
END_IF
ldx #$FF ; clear Z = failure
done: rts
.endproc ; IsIconSelected
;;; ============================================================
;;; Inputs: A = window id
;;; Outputs: Z = 1 if found, and X = index in `window_id_to_filerecord_list_entries`
.assert * < OVERLAY_BUFFER || * >= $6000, error, "Routine used when clearing updates in overlay zone"
.proc FindIndexInFileRecordListEntries
ldx window_id_to_filerecord_list_count
dex
DO
BREAK_IF_A_EQ window_id_to_filerecord_list_entries,x
dex
WHILE_POS
rts
.endproc ; FindIndexInFileRecordListEntries
;;; Input: A = window_id
;;; Output: A,X = address of FileRecord list (first entry is length)
;;; Assert: Window is found in list.
.assert * < OVERLAY_BUFFER || * >= $6000, error, "Routine used when clearing updates in overlay zone"
.proc GetFileRecordListForWindow
jsr FindIndexInFileRecordListEntries
txa
asl
tax
lda window_filerecord_table,x
pha
lda window_filerecord_table+1,x
tax
pla
rts
.endproc ; GetFileRecordListForWindow
;;; ============================================================
;;; Outputs: A = DeskTopSettings::kViewBy* value for active window, X = window id
;;; If DeskTopSettings::kViewByIcon, Z=1 and N=0; otherwise Z=0 and N=1
;;; Assert: There is an active window
.proc GetActiveWindowViewBy
ldx active_window_id
lda win_view_by_table-1,x
rts
.endproc ; GetActiveWindowViewBy
;;; Assert: There is a cached window
.assert * < OVERLAY_BUFFER || * >= $6000, error, "Routine used when clearing updates in overlay zone"
.proc GetCachedWindowViewBy
ldx cached_window_id
lda win_view_by_table-1,x
rts
.endproc ; GetCachedWindowViewBy
;;; Assert: There is a selection.
;;; NOTE: This variant works even if selection is on desktop
;;; Preserves Y
.proc GetSelectionViewBy
ldx selected_window_id
lda win_view_by_table-1,x
rts
.endproc ; GetSelectionViewBy
;;; ============================================================
PROC_USED_IN_OVERLAY
.proc ToggleMenuHilite
lda menu_click_params::menu_id
IF_NOT_ZERO
MGTK_CALL MGTK::HiliteMenu, menu_click_params
END_IF
rts
.endproc ; ToggleMenuHilite
;;; ============================================================
;;; Test if either modifier (Open-Apple or Solid-Apple) is down.
;;; Output: A=high bit/N flag set if either is down.
PROC_USED_IN_OVERLAY
.proc ModifierDown
lda BUTN0
ora BUTN1
rts
.endproc ; ModifierDown
;;; Test if either primary modifier (Open-Apple) or shift is down,
;;; (if shift key can be detected).
;;; Output: A=high bit/N flag set if either is down.
.proc ExtendSelectionModifierDown
;; IIgs? Use KEYMODREG instead
ldx #DeskTopSettings::system_capabilities
jsr ReadSetting
and #DeskTopSettings::kSysCapIsIIgs
bne iigs
jsr TestShiftMod ; Shift key state, if detectable
ora BUTN0 ; Either way, check button state
rts
;; IIgs - do everything using one I/O location
iigs: lda KEYMODREG
and #%10000001 ; bit 7 = Command (OA), bit 0 = Shift
beq ret
lda #$80
ret: rts
.endproc ; ExtendSelectionModifierDown
;;; Test if shift is down (if it can be detected).
;;; Output: A=high bit/N flag set if down.
PROC_USED_IN_OVERLAY
.proc ShiftDown
ldx #DeskTopSettings::system_capabilities
jsr ReadSetting
and #DeskTopSettings::kSysCapIsIIgs
beq TestShiftMod ; no, rely on shift key mod
lda KEYMODREG ; On IIgs, use register instead
and #%00000001 ; bit 7 = Command (OA), bit 0 = Shift
beq ret
lda #$80
ret: rts
.endproc ; ShiftDown
;;; Compare the shift key mod state. Returns high bit set if
;;; not the initial state (i.e. Shift key is likely down), if
;;; detectable.
.proc TestShiftMod
ldx #DeskTopSettings::system_capabilities
jsr ReadSetting
;; If a IIe, maybe use shift key mod
;; Not IIc/Laser 128 as BUTN2 set when mouse button clicked
and #DeskTopSettings::kSysCapIsIIc | DeskTopSettings::kSysCapIsLaser128
IF_ZERO
;; It's a IIe, compare shift key state
lda pb2_initial_state ; if shift key mod installed, %1xxxxxxx
eor BUTN2 ; ... and if shift is down, %0xxxxxxx
END_IF
rts
.endproc ; TestShiftMod
;;; ============================================================
;;; Window Entry Tables
;;; ============================================================
.assert * < OVERLAY_BUFFER || * >= $6000, error, "Routine used when clearing updates in overlay zone"
;;; Input: A = window_id (0=desktop)
.proc LoadWindowEntryTable
sta cached_window_id
;; Load count & entries
tax
copy8 window_entry_count_table,x, cached_window_entry_count
IF_NOT_ZERO
lda window_entry_offset_table,x
tax ; X = offset in table
ldy #0 ; Y = index in win
DO
copy8 window_entry_table,x, cached_window_entry_list,y
inx
iny
cpy cached_window_entry_count
WHILE_NE
END_IF
rts
.endproc ; LoadWindowEntryTable
.proc ClearActiveWindowEntryCount
jsr LoadActiveWindowEntryTable
FALL_THROUGH_TO ClearAndStoreCachedWindowEntryTable
.endproc ; ClearActiveWindowEntryCount
.proc ClearAndStoreCachedWindowEntryTable
copy8 #0, cached_window_entry_count
FALL_THROUGH_TO StoreWindowEntryTable
.endproc ; ClearAndStoreCachedWindowEntryTable
;;; Assert: `cached_window_id` and `icon_count` is up-to-date
.proc StoreWindowEntryTable
lda cached_window_id
cmp #kMaxDeskTopWindows ; last window?
beq done_shift ; yes, no need to shift
;; Compute delta to shift up (or down)
tax ; X = window_id
lda cached_window_entry_count
sec
sbc window_entry_count_table,x ; A = amount to shift up (may be <0)
beq done_shift
sta delta
;; Offset entries by delta
bmi shift_down
;; Shift up
inx ; X = next window_id
copy8 window_entry_offset_table,x, last
ldy icon_count ; Y = new offset
tya
sec
sbc delta
tax ; X = old offset
: copy8 window_entry_table,x, window_entry_table,y
last := *+1
cpx #SELF_MODIFIED_BYTE
beq shift_offsets
dex
dey
jmp :-
shift_down:
;; Shift down
inx ; X = next window_id
lda window_entry_offset_table,x
tax ; X = old offset
clc
adc delta
tay ; Y = new offset
: copy8 window_entry_table,x, window_entry_table,y
cpy icon_count
beq shift_offsets
inx
iny
jmp :-
shift_offsets:
;; Update offsets table by delta
ldx cached_window_id
inx
DO
lda window_entry_offset_table,x
clc
delta := *+1
adc #SELF_MODIFIED_BYTE
sta window_entry_offset_table,x
inx
WHILE_X_NE #kMaxDeskTopWindows+1
done_shift:
;; Store count & entries
ldx cached_window_id
copy8 cached_window_entry_count, window_entry_count_table,x
IF_NOT_ZERO
lda window_entry_offset_table,x
tax ; X = offset in table
ldy #0 ; Y = index in win
DO
copy8 cached_window_entry_list,y, window_entry_table,x
inx
iny
cpy cached_window_entry_count
WHILE_NE
END_IF
rts
.endproc ; StoreWindowEntryTable
window_entry_count_table: .res ::kMaxDeskTopWindows+1, 0
window_entry_offset_table: .res ::kMaxDeskTopWindows+1, 0
window_entry_table: .res ::kMaxIconCount+1, 0
;;; NOTE: +1 in above is to address an off-by-one case in the shift-up
;;; logic with 127 icons. A simpler fix may be possible, see commit
;;; 41ebde49 for another attempt, but that introduces other issues.
.assert * < OVERLAY_BUFFER || * >= $6000, error, "Routine used when clearing updates in overlay zone"
.proc LoadActiveWindowEntryTable
lda active_window_id
jmp LoadWindowEntryTable
.endproc ; LoadActiveWindowEntryTable
.proc LoadDesktopEntryTable
lda #0
jmp LoadWindowEntryTable
.endproc ; LoadDesktopEntryTable
;;; ============================================================
;;; A,X = A,X * Y
;;; Uses $10..$19
.proc Multiply_16_8_16
PARAM_BLOCK muldiv_params, $10
number .word ; (in)
numerator .word ; (in)
denominator .word ; (in)
result .word ; (out)
remainder .word ; (out)
END_PARAM_BLOCK
;; number = A,X
stax muldiv_params::number
;; numerator = Y
sty muldiv_params::numerator ; lo
ldy #0
sty muldiv_params::numerator+1 ; hi
;; denominator = 1
sty muldiv_params::denominator+1 ; hi
iny
sty muldiv_params::denominator ; lo
MGTK_CALL MGTK::MulDiv, muldiv_params
ldax muldiv_params::result
rts
.endproc ; Multiply_16_8_16
;;; ============================================================
;;; Library Routines
;;; ============================================================
.assert * >= OVERLAY_BUFFER + kOverlayBufferSize, error, "Routines used by overlays in overlay zone"
RC_AUXMEM = 1
RC_LCBANK = 1
.include "../lib/ramcard.s"
ADJUSTCASE_BLOCK_BUFFER := IO_BUFFER
.include "../lib/adjustfilecase.s"
.include "../lib/smartport.s"
.include "../lib/menuclock.s"
.include "../lib/inttostring.s"
.include "../lib/filetypestring.s"
.include "../lib/datetime.s"
.include "../lib/is_diskii.s"
.include "../lib/doubleclick.s"
.include "../lib/reconnect_ram.s"
.include "../lib/readwrite_settings.s"
.include "../lib/get_next_event.s"
.include "../lib/monocolor.s"
.include "../lib/speed.s"
.include "../lib/bell.s"
.include "../lib/uppercase.s"
;;; ============================================================
;;; Resources (that are only used from Main, i.e. not MGTK)
;;; ============================================================
;;; Window paths
;;; 8 entries; each entry is kPathBufferSize bytes long
;;; * length-prefixed path string (no trailing /)
;;; Windows 1...8 (since 0 is desktop)
window_path_table:
.res (::kMaxDeskTopWindows * ::kPathBufferSize), 0
;;; Table of desktop window path addresses
window_path_addr_table:
.addr $0000
.repeat ::kMaxDeskTopWindows,i
.addr window_path_table+i*kPathBufferSize
.endrepeat
ASSERT_ADDRESS_TABLE_SIZE window_path_addr_table, ::kMaxDeskTopWindows + 1
;;; ============================================================
;;; Window used/free (in kilobytes)
;;; Two tables, 8 entries each
;;; Windows 1...8 (since 0 is desktop)
window_k_used_table: .res ::kMaxDeskTopWindows*2, 0
window_k_free_table: .res ::kMaxDeskTopWindows*2, 0
;;; To avoid artifacts, the values drawn are only updated when
;;; a window becomes active.
window_draw_k_used_table: .res ::kMaxDeskTopWindows*2, 0
window_draw_k_free_table: .res ::kMaxDeskTopWindows*2, 0
;;; ============================================================
icontype_table:
;; Types where suffix shouldn't override other metadata
DEFINE_ICTRECORD $FF, FT_DIRECTORY, ICT_FLAGS_AUX, $8000, 0, IconType::system_folder ; $0F
DEFINE_ICTRECORD $FF, FT_DIRECTORY, ICT_FLAGS_NONE, 0, 0, IconType::folder ; $0F
;; Types entirely defined by file suffix
DEFINE_ICTRECORD 0, 0, ICT_FLAGS_SUFFIX, str_shk_suffix, 0, IconType::archive ; NuFX
DEFINE_ICTRECORD 0, 0, ICT_FLAGS_SUFFIX, str_bny_suffix, 0, IconType::archive ; Binary II
DEFINE_ICTRECORD 0, 0, ICT_FLAGS_SUFFIX, str_bxy_suffix, 0, IconType::archive ; NuFX in Binary II
DEFINE_ICTRECORD 0, 0, ICT_FLAGS_SUFFIX, str_a2fc_suffix, 0, IconType::graphics ; Apple II Full Color
DEFINE_ICTRECORD 0, 0, ICT_FLAGS_SUFFIX, str_a2fm_suffix, 0, IconType::graphics ; Apple II Full Monochrome
DEFINE_ICTRECORD 0, 0, ICT_FLAGS_SUFFIX, str_a2lc_suffix, 0, IconType::graphics ; Apple II Low Color
DEFINE_ICTRECORD 0, 0, ICT_FLAGS_SUFFIX, str_a2hr_suffix, 0, IconType::graphics ; Apple II High Resolution
DEFINE_ICTRECORD 0, 0, ICT_FLAGS_SUFFIX, str_bsc_suffix, 0, IconType::encoded ; BinSCII
DEFINE_ICTRECORD 0, 0, ICT_FLAGS_SUFFIX, str_bsq_suffix, 0, IconType::encoded ; BinSCII - ShrinkIt
DEFINE_ICTRECORD 0, 0, ICT_FLAGS_SUFFIX, str_btc_suffix, 0, IconType::audio ; Binary Time Constant Audio
DEFINE_ICTRECORD 0, 0, ICT_FLAGS_SUFFIX, str_zc_suffix, 0, IconType::audio ; Zero-Crossing Audio
DEFINE_ICTRECORD 0, 0, ICT_FLAGS_SUFFIX, str_pt3_suffix, 0, IconType::tracker ; Vortex Tracker PT3
;; Binary files ($06) identified as graphics (hi-res, double hi-res, minipix)
DEFINE_ICTRECORD $FF, FT_BINARY, ICT_FLAGS_AUX|ICT_FLAGS_BLOCKS, $2000, 17, IconType::graphics ; HR image as FOT
DEFINE_ICTRECORD $FF, FT_BINARY, ICT_FLAGS_AUX|ICT_FLAGS_BLOCKS, $4000, 17, IconType::graphics ; HR image as FOT
DEFINE_ICTRECORD $FF, FT_BINARY, ICT_FLAGS_AUX|ICT_FLAGS_BLOCKS, $2000, 33, IconType::graphics ; DHR image as FOT
DEFINE_ICTRECORD $FF, FT_BINARY, ICT_FLAGS_AUX|ICT_FLAGS_BLOCKS, $4000, 33, IconType::graphics ; DHR image as FOT
DEFINE_ICTRECORD $FF, FT_BINARY, ICT_FLAGS_AUX|ICT_FLAGS_BLOCKS, $5800, 3, IconType::graphics ; Minipix as FOT
DEFINE_ICTRECORD $FF, FT_BINARY, ICT_FLAGS_AUX|ICT_FLAGS_BLOCKS, $400, 3, IconType::graphics ; LR image as FOT
DEFINE_ICTRECORD $FF, FT_BINARY, ICT_FLAGS_AUX|ICT_FLAGS_BLOCKS, $400, 5, IconType::graphics ; DLR image as FOT
;; Simple Mappings
DEFINE_ICTRECORD $FF, FT_TEXT, ICT_FLAGS_NONE, 0, 0, IconType::text ; $04
DEFINE_ICTRECORD $FF, FT_BINARY, ICT_FLAGS_NONE, 0, 0, IconType::binary ; $06
DEFINE_ICTRECORD $FF, FT_FONT, ICT_FLAGS_NONE, 0, 0, IconType::font ; $07
DEFINE_ICTRECORD $FF, FT_GRAPHICS, ICT_FLAGS_NONE, 0, 0, IconType::graphics ; $08
DEFINE_ICTRECORD $FF, FT_ADB, ICT_FLAGS_NONE, 0, 0, IconType::appleworks_db ; $19
DEFINE_ICTRECORD $FF, FT_AWP, ICT_FLAGS_NONE, 0, 0, IconType::appleworks_wp ; $1A
DEFINE_ICTRECORD $FF, FT_ASP, ICT_FLAGS_NONE, 0, 0, IconType::appleworks_sp ; $1B
DEFINE_ICTRECORD $FF, FT_CMD, ICT_FLAGS_NONE, 0, 0, IconType::command ; $F0
DEFINE_ICTRECORD $FF, FT_INT, ICT_FLAGS_NONE, 0, 0, IconType::intbasic ; $FA
DEFINE_ICTRECORD $FF, FT_IVR, ICT_FLAGS_NONE, 0, 0, IconType::variables ; $FB
DEFINE_ICTRECORD $FF, FT_BASIC, ICT_FLAGS_NONE, 0, 0, IconType::basic ; $FC
DEFINE_ICTRECORD $FF, FT_VAR, ICT_FLAGS_NONE, 0, 0, IconType::variables ; $FD
DEFINE_ICTRECORD $FF, FT_REL, ICT_FLAGS_NONE, 0, 0, IconType::relocatable ; $FE
DEFINE_ICTRECORD $FF, FT_SYSTEM, ICT_FLAGS_SUFFIX, str_sys_suffix, 0, IconType::application ; $FF
DEFINE_ICTRECORD $FF, FT_SYSTEM, ICT_FLAGS_NONE, 0, 0, IconType::system ; $FF
DEFINE_ICTRECORD $FF, FT_ANIMATION, ICT_FLAGS_NONE, 0, 0, IconType::animation ; $5B ANM
DEFINE_ICTRECORD $FF, FT_SOUND, ICT_FLAGS_NONE, 0, 0, IconType::audio ; $D8 SND
DEFINE_ICTRECORD $FF, FT_MUSIC, ICT_FLAGS_NONE, 0, 0, IconType::music ; $D5 MUS
DEFINE_ICTRECORD $FF, FT_ARCHIVE, ICT_FLAGS_AUX, $8002, 0, IconType::archive ; NuFX
DEFINE_ICTRECORD $FF, FT_LINK, ICT_FLAGS_AUX, kLinkFileAuxType, 0, IconType::link ; $E1 LNK
DEFINE_ICTRECORD $FF, FT_SPEECH, ICT_FLAGS_AUX, $0001, 0, IconType::speech ; $D9 Speech
;; IIgs-Specific Files (ranges)
DEFINE_ICTRECORD $F0, $50, ICT_FLAGS_NONE, 0, 0, IconType::iigs ; IIgs General $5x
DEFINE_ICTRECORD $F0, $A0, ICT_FLAGS_NONE, 0, 0, IconType::iigs ; IIgs BASIC $Ax
DEFINE_ICTRECORD $FF, FT_S16, ICT_FLAGS_NONE, 0, 0, IconType::application ; IIgs System $B3
DEFINE_ICTRECORD $F0, $B0, ICT_FLAGS_NONE, 0, 0, IconType::iigs ; IIgs System $Bx
DEFINE_ICTRECORD $FF, FT_PNT, ICT_FLAGS_AUX, $0001, 0, IconType::graphics ; IIgs Pkd SHR $C0
DEFINE_ICTRECORD $FF, FT_PIC, ICT_FLAGS_AUX, $0000, 0, IconType::graphics ; IIgs SHR $C1
DEFINE_ICTRECORD $F0, $C0, ICT_FLAGS_NONE, 0, 0, IconType::iigs ; IIgs Graphics $Cx
;; Desk Accessories/Applets $F1/$0642 and $F1/$8642
DEFINE_ICTRECORD $FF, kDAFileType, ICT_FLAGS_AUX, kDAFileAuxType, 0, IconType::desk_accessory
DEFINE_ICTRECORD $FF, kDAFileType, ICT_FLAGS_AUX, kDAFileAuxType|$8000, 0, IconType::desk_accessory
.byte kICTSentinel
;;; Suffixes (must be uppercase)
str_sys_suffix: ; SYS files with .SYSTEM suffix are given "application" icon
PASCAL_STRING ".SYSTEM"
str_shk_suffix: ; ShrinkIt NuFX files, that have lost their type info.
PASCAL_STRING ".SHK"
str_bny_suffix: ; Binary II files, which contain metadata as a header
PASCAL_STRING ".BNY" ; (pronounced "bunny", per A2-Central, Vol 5. No. 7, Aug 1989 )
str_bxy_suffix: ; ShrinkIt NuFX files, in a Binary II package
PASCAL_STRING ".BXY" ; (pronounced "boxy", per A2-Central, Vol 5. No. 7, Aug 1989 )
str_a2fc_suffix: ; Double-hires ("Apple II Full Color")
PASCAL_STRING ".A2FC"
str_a2fm_suffix: ; Double-hires ("Apple II Full Mono") - Bmp2DHR uses this
PASCAL_STRING ".A2FM"
str_a2lc_suffix: ; Single-hires ("Apple II Low Color")
PASCAL_STRING ".A2LC"
str_a2hr_suffix: ; Single-hires B&W ("Apple II High Resolution")
PASCAL_STRING ".A2HR"
str_zc_suffix: ; "Zero-Crossing" Audio
PASCAL_STRING ".ZC"
str_btc_suffix: ; "Binary Time Constant" Audio
PASCAL_STRING ".BTC"
str_bsc_suffix: ; BinSCII
PASCAL_STRING ".BSC"
str_bsq_suffix: ; BinSCII - ShrinkIt
PASCAL_STRING ".BSQ"
str_pt3_suffix: ; Vortex Tracker PT3
PASCAL_STRING ".PT3"
;;; ============================================================
;;; DeskTop icon placement
;;; +-------------------------+
;;; | 1 |
;;; | 2 |
;;; | 3 |
;;; | 4 |
;;; | 14 13 12 11 5 |
;;; | 10 9 8 7 6 Trash |
;;; +-------------------------+
kVolIconDeltaY = 29
kVolIconDeltaX = 90
;; Volume icons are positioned at:
;; * pos_x - ((icon_width-1) / 2)
;; * pos_y - (icon_height-1)
;; The "-1" is because the bitmap's x2/y2 are used, not w/h.
;; So the coordinates represent the center-bottom of the
;; bitmap.
kVolIconRow1 = 30
kVolIconRow2 = kVolIconRow1 + kVolIconDeltaY*1
kVolIconRow3 = kVolIconRow1 + kVolIconDeltaY*2
kVolIconRow4 = kVolIconRow1 + kVolIconDeltaY*3
kVolIconRow5 = kVolIconRow1 + kVolIconDeltaY*4
kVolIconRow6 = kVolIconRow1 + kVolIconDeltaY*5 + 2
kVolIconCol1 = 516
kVolIconCol2 = kVolIconCol1 - kVolIconDeltaX*1
kVolIconCol3 = kVolIconCol1 - kVolIconDeltaX*2
kVolIconCol4 = kVolIconCol1 - kVolIconDeltaX*3
kVolIconCol5 = kVolIconCol1 - kVolIconDeltaX*4
kVolIconCol6 = kVolIconCol1 - kVolIconDeltaX*5
;; Trash icon is positioned at exactly these coordinates:
kTrashIconX = kVolIconCol1 - ((kTrashIconWidth-1) / 2)
kTrashIconY = kVolIconRow6 - (kTrashIconHeight-1)
desktop_icon_coords_table:
.word kVolIconCol1, kVolIconRow1 ; 1
.word kVolIconCol1, kVolIconRow2 ; 2
.word kVolIconCol1, kVolIconRow3 ; 3
.word kVolIconCol1, kVolIconRow4 ; 4
.word kVolIconCol1, kVolIconRow5 ; 5
.word kVolIconCol2, kVolIconRow6 ; 6
.word kVolIconCol3, kVolIconRow6 ; 7
.word kVolIconCol4, kVolIconRow6 ; 8
.word kVolIconCol5, kVolIconRow6 ; 9
.word kVolIconCol6, kVolIconRow6 ; 10
.word kVolIconCol2, kVolIconRow5 ; 11
.word kVolIconCol3, kVolIconRow5 ; 12
.word kVolIconCol4, kVolIconRow5 ; 13
.word kVolIconCol5, kVolIconRow5 ; 14
ASSERT_RECORD_TABLE_SIZE desktop_icon_coords_table, ::kMaxVolumes, .sizeof(MGTK::Point)
;;; Which icon positions are in use. 0=free, icon number otherwise
desktop_icon_usage_table:
.res ::kMaxVolumes, 0
;;; ============================================================
.assert * < OVERLAY_BUFFER || * >= $6000, error, "Routine used when clearing updates in overlay zone"
;;; FileRecord for list view
list_view_filerecord:
.tag FileRecord
;;; Used elsewhere for converting date to string
datetime_for_conversion := list_view_filerecord + FileRecord::modification_date
;;; ============================================================
saved_stack:
.byte 0
case_bits: .word 0
;;; Holds a single filename
clipboard:
.res 16, 0
path_buf4:
.res ::kPathBufferSize, 0
path_buf3:
.res ::kPathBufferSize, 0
filename_buf:
.res 16, 0
;;; ============================================================
;; index is device number (in DEVLST), value is icon number
device_to_icon_map:
.res ::kMaxVolumes, 0
;;; Window to file record mapping list. Each entry is a window
;;; id. Position in the list is the same as position in the
;;; subsequent file record list.
window_id_to_filerecord_list_count:
.byte 0
window_id_to_filerecord_list_entries:
.res ::kMaxDeskTopWindows, 0 ; 8 entries + length
;;; Mapping from position in above table to FileRecord entry
window_filerecord_table:
.res ::kMaxDeskTopWindows*2
;;; ============================================================
startup_slot_table:
.res 7, 0 ; maps menu item index (0-based) to slot number
;;; ============================================================
;;; Assigned during startup
trash_icon_num: .byte 0
;;; ============================================================
hex_digits:
.byte "0123456789ABCDEF"
;;; ============================================================
;;; High bit set if menu dispatch via mouse with option, clear otherwise.
menu_modified_click_flag:
.byte 0
;;; ============================================================
;;; Map IconType to other icon/details
;;; Table mapping IconType to kIconEntryFlags*
icontype_iconentryflags_table := * - IconType::VOL_COUNT
;; Volume types skipped via above math.
.byte 0 ; generic
.byte 0 ; text
.byte 0 ; binary
.byte 0 ; graphics
.byte 0 ; animation
.byte 0 ; music
.byte 0 ; tracker
.byte 0 ; audio
.byte 0 ; speech
.byte 0 ; font
.byte 0 ; relocatable
.byte 0 ; command
.byte kIconEntryFlagsDropTarget ; folder
.byte kIconEntryFlagsDropTarget ; system_folder
.byte 0 ; iigs
.byte 0 ; appleworks_db
.byte 0 ; appleworks_wp
.byte 0 ; appleworks_sp
.byte 0 ; archive
.byte 0 ; encoded
.byte 0 ; link
.byte 0 ; desk_accessory
.byte 0 ; basic
.byte 0 ; intbasic
.byte 0 ; variables
.byte 0 ; system
.byte 0 ; application
;; Small Icon types skipped via math below
ASSERT_TABLE_SIZE icontype_iconentryflags_table, IconType::COUNT - IconType::SMALL_COUNT
icontype_to_smicon_table := * - IconType::VOL_COUNT
;; Volume types skipped via above math
.byte IconType::small_generic ; generic
.byte IconType::small_generic ; text
.byte IconType::small_generic ; binary
.byte IconType::small_generic ; graphics
.byte IconType::small_generic ; animation/video
.byte IconType::small_generic ; music
.byte IconType::small_generic ; tracker
.byte IconType::small_generic ; audio
.byte IconType::small_generic ; speech
.byte IconType::small_generic ; font
.byte IconType::small_generic ; relocatable
.byte IconType::small_generic ; command
.byte IconType::small_folder ; folder
.byte IconType::small_folder ; system_folder
.byte IconType::small_generic ; iigs
.byte IconType::small_generic ; appleworks_db
.byte IconType::small_generic ; appleworks_wp
.byte IconType::small_generic ; appleworks_sp
.byte IconType::small_generic ; archive
.byte IconType::small_generic ; encoded
.byte IconType::small_generic ; link
.byte IconType::small_generic ; desk_accessory
.byte IconType::small_generic ; basic
.byte IconType::small_generic ; intbasic
.byte IconType::small_generic ; variables
.byte IconType::small_generic ; system
.byte IconType::small_generic ; application
;; Small Icon types skipped via math below
ASSERT_TABLE_SIZE icontype_to_smicon_table, IconType::COUNT - IconType::SMALL_COUNT
;;; ============================================================
;;; Shortcut ("run list") paths
run_list_paths:
.res ::kMaxRunListEntries * ::kSelectorListPathLength, 0
;;; ============================================================
;;; Localized strings (may change length)
;;; ============================================================
str_device_type_diskii:
PASCAL_STRING res_string_volume_type_disk_ii
str_device_type_ramdisk:
PASCAL_STRING res_string_volume_type_ramcard
str_device_type_appletalk:
PASCAL_STRING res_string_volume_type_fileshare
str_device_type_vdrive:
PASCAL_STRING res_string_volume_type_vdrive
str_new_folder:
PASCAL_STRING res_string_new_folder_default
str_date_and_time:
PASCAL_STRING .concat(kFilenameDADir, "/", res_filename_control_panels, "/", res_filename_date_and_time)
;;; ============================================================
.endscope ; main
;;; ============================================================
;;; "Exports" from lib/ routines (mostly)
ReadSetting := main::ReadSetting
WriteSetting := main::WriteSetting
GetNextEvent := main::GetNextEvent
SystemTask := main::SystemTask
Bell := main::Bell
Multiply_16_8_16 := main::Multiply_16_8_16
DetectDoubleClick := main::DetectDoubleClick
AdjustOnLineEntryCase := main::AdjustOnLineEntryCase
AdjustFileEntryCase := main::AdjustFileEntryCase
;;; ============================================================
ENDSEG SegmentDeskTopMain
|
a2stuff/a2d
| 7,799
|
src/desktop/loader.s
|
;;; ============================================================
;;; Loader
;;;
;;; Compiled as part of desktop.s
;;; ============================================================
;;; This chunk is invoked at $2000 after the quit handler has been invoked
;;; and updated itself. Using the segment_*_tables below, this loads the
;;; DeskTop application into various parts of main, aux, and bank-switched
;;; memory, then invokes the DeskTop initialization routine.
BEGINSEG SegmentLoader
.scope InstallSegments
MLIEntry := MLI
jmp start
DEFINE_OPEN_PARAMS open_params, filename, $3000
DEFINE_READWRITE_PARAMS read_params, 0, 0
DEFINE_CLOSE_PARAMS close_params
DEFINE_SET_MARK_PARAMS set_mark_params, 0
filename:
PASCAL_STRING kPathnameDeskTop
;;; Consecutive segments are loaded, `size` bytes are loaded at `addr`
;;; then relocated to `dest` according to `type`.
;;; Segments are:
;;; $4000 aux - MGTK and DeskTop code
;;; $D000 aux/banked - DeskTop code callable from main, and resources
;;; $4000 main - more DeskTop code
;;; $0800 main - DeskTop initialization code; later overwritten by DAs, etc
;;; $0290 main - Routine to invoke other programs
kNumSegments = 5
segment_addr_table_low: ; Temporary load addresses
.byte <$3F00,<$4000 ; loaded here and then moved into Aux / LC banks
.byte <kSegmentDeskTopMainAddress,<kSegmentInitializerAddress,<kSegmentInvokerAddress ; "moved" in place
ASSERT_TABLE_SIZE segment_addr_table_low, kNumSegments
segment_addr_table_high: ; Temporary load addresses
.byte >$3F00,>$4000 ; loaded here and then moved into Aux / LC banks
.byte >kSegmentDeskTopMainAddress,>kSegmentInitializerAddress,>kSegmentInvokerAddress ; "moved" in place
ASSERT_TABLE_SIZE segment_addr_table_high, kNumSegments
segment_dest_table_low: ; Runtime addresses (moved here)
.byte <kSegmentDeskTopAuxAddress,<kSegmentDeskTopLCAddress
.byte 0,0,0 ; loaded directly into final address, no need to move
ASSERT_TABLE_SIZE segment_dest_table_low, kNumSegments
segment_dest_table_high: ; Runtime addresses (moved here)
.byte >kSegmentDeskTopAuxAddress,>kSegmentDeskTopLCAddress
.byte 0,0,0 ; loaded directly into final address, no need to move
ASSERT_TABLE_SIZE segment_dest_table_high, kNumSegments
segment_size_table_low:
.byte <kSegmentDeskTopAuxLength,<kSegmentDeskTopLCLength
.byte <kSegmentDeskTopMainLength,<kSegmentInitializerLength,<kSegmentInvokerLength
ASSERT_TABLE_SIZE segment_size_table_low, kNumSegments
segment_size_table_high:
.byte >kSegmentDeskTopAuxLength,>kSegmentDeskTopLCLength
.byte >kSegmentDeskTopMainLength,>kSegmentInitializerLength,>kSegmentInvokerLength
ASSERT_TABLE_SIZE segment_size_table_high, kNumSegments
segment_offset_table_low:
.byte <kSegmentDeskTopAuxOffset,<kSegmentDeskTopLCOffset
.byte <kSegmentDeskTopMainOffset,<kSegmentInitializerOffset,<kSegmentInvokerOffset
ASSERT_TABLE_SIZE segment_offset_table_low, kNumSegments
segment_offset_table_high:
.byte >kSegmentDeskTopAuxOffset,>kSegmentDeskTopLCOffset
.byte >kSegmentDeskTopMainOffset,>kSegmentInitializerOffset,>kSegmentInvokerOffset
ASSERT_TABLE_SIZE segment_offset_table_high, kNumSegments
segment_offset_table_bank:
.byte ^kSegmentDeskTopAuxOffset,^kSegmentDeskTopLCOffset
.byte ^kSegmentDeskTopMainOffset,^kSegmentInitializerOffset,^kSegmentInvokerOffset
ASSERT_TABLE_SIZE segment_offset_table_bank, kNumSegments
segment_type_table: ; 0 = main, 1 = aux, 2 = banked (aux)
.byte 1,2,0,0,0
ASSERT_TABLE_SIZE segment_type_table, kNumSegments
start:
;; Old ProDOS leaves interrupts inhibited on start.
;; Do this for good measure.
cli
jsr DetectMousetext
jsr InitProgress
;; Open this system file
MLI_CALL OPEN, open_params
IF_CS
brk ; crash
END_IF
lda open_params::ref_num
sta set_mark_params::ref_num
sta read_params::ref_num
copy8 #0, segment_num
loop: jsr UpdateProgress
segment_num := * + 1
ldx #0
cpx #kNumSegments
bne continue
;; Close
MLI_CALL CLOSE, close_params
IF_CS
brk ; crash
END_IF
jmp kSegmentInitializerAddress
continue:
copy8 segment_offset_table_low,x, set_mark_params::position+0
copy8 segment_offset_table_high,x, set_mark_params::position+1
copy8 segment_offset_table_bank,x, set_mark_params::position+2
MLI_CALL SET_MARK, set_mark_params
IF_CS
brk ; crash
END_IF
copylohi segment_addr_table_low,x, segment_addr_table_high,x, read_params::data_buffer
copylohi segment_size_table_low,x, segment_size_table_high,x, read_params::request_count
MLI_CALL READ, read_params
IF_CS
brk ; crash
END_IF
ldx segment_num
inc segment_num
lda segment_type_table,x
beq loop ; type 0 = main, so done
cmp #2 ; carry set if banked, clear if aux
IF_CS
;; Handle bank-switched memory segment
;; Disable interrupts, since we may overwrite IRQ vector
php
sei
sta ALTZPON
bit LCBANK1
bit LCBANK1
COPY_BYTES kIntVectorsSize, VECTORS, vector_buf
ldx segment_num
dex
;; Set stack pointers to arbitrarily low values for use when
;; interrupts occur. DeskTop does not utilize this convention,
;; so the values are set low so that interrupts which do (for
;; example, the IIgs Control Panel) don't trash DeskTop's use
;; of the stacks.
lda #$80
sta $0100 ; Main stack pointer, in Aux ZP
sta $0101 ; Aux stack pointer, in Aux ZP
END_IF
src := $6
dst := $8
ldy #0
sty src
ldy segment_dest_table_low,x
sty dst
ldy segment_dest_table_high,x
sty dst+1
ldy read_params::data_buffer+1
sty src+1
ldy segment_size_table_high,x ; Y = number of pages
lda segment_size_table_low,x ; fractional?
IF_NOT_ZERO
iny ; if so, round up
END_IF
tya
tax ; X = number of pages to copy
sta RAMWRTON
jsr CopySegment
sta RAMWRTOFF
IF_CS ; carry set if banked
COPY_BYTES kIntVectorsSize, vector_buf, VECTORS
sta ALTZPOFF
bit ROMIN2
plp
END_IF
jmp loop
vector_buf:
.res ::kIntVectorsSize, 0
;; Handle banked/aux memory segment
;; Corresponding vectors are set before call
.proc CopySegment
ldy #0
DO
copy8 (src),y, (dst),y
iny
CONTINUE_IF_NOT_ZERO
inc src+1
inc dst+1
dex
WHILE_NOT_ZERO
rts
.endproc ; CopySegment
;;; ============================================================
kProgressStops = kNumSegments + 1
.include "../lib/loader_progress.s"
;;; ============================================================
.endscope ; InstallSegments
;;; ============================================================
ENDSEG SegmentLoader
|
a2stuff/a2d
| 31,781
|
src/desktop/init.s
|
;;; ============================================================
;;; DeskTop - Initialization
;;;
;;; Compiled as part of desktop.s
;;; ============================================================
;;; ============================================================
;;; Segment loaded into MAIN $800-$FFF
;;; ============================================================
;;; Main Aux
;;; :.............: :.............:
;;; |.............| |.............|
;;; |.............| |.............|
;;; |.Graphics....| |.Graphics....|
;;; $2000 +-------------+ +-------------+
;;; | I/O Buffer | | |
;;; $1C00 +-------------+ | |
;;; | | | |
;;; | | | |
;;; | | | |
;;; | | | |
;;; | | | |
;;; $1600 +-------------+ | |
;;; | Data Buffer | | |
;;; $1200 +-------------+ | |
;;; | | | |
;;; | Code | | |
;;; $0800 +-------------+ +-------------+
;;; |.............| |.............|
;;; :.............: :.............:
;;; NOTE: if DeskTop file is extended in length, there is room for
;;; this segment to grow by moving buffers up by a few pages.
;;; Init sequence - machine identification, etc
;;;
;;; * Hook reset vector
;;; * Clear hires screen
;;; * Detect machine type
;;; * Preserve DEVLST, remove /RAM
;;; * Initialize MGTK, with saved settings
;;; * Load selector list, populate Selector menu
;;; * Enumerate desk accessories, populate Apple menu
;;; * Compute label widths
;;; * Create desktop icons, populate device name table
;;; * Populate startup menu
;;; * Identify removable disks, for later polling
;;; * Configure MGTK
;;; * Restore saved windows
BEGINSEG SegmentInitializer
.scope init
MLIEntry := main::MLIRelayImpl
MGTKEntry := MGTKRelayImpl
ITKEntry := ITKRelayImpl
data_buf := $1200
kDataBufferSize = $400
start:
;;; ============================================================
;;; Set the reset vector to cold start
.scope hook_reset_vector
;; Main hook
lda #<main::ResetHandler
sta SOFTEV
lda #>main::ResetHandler
sta SOFTEV+1
eor #$A5
sta SOFTEV+2
.endscope ; hook_reset_vector
;;; ============================================================
;;; Clear DHR screen to black before it is shown
jsr ClearDHRToBlack
;;; ============================================================
;;; Detect Machine Type - set flags and periodic task delay
;;; NOTE: Starts with ROM paged in, exits with LCBANK1 paged in.
.scope machine_type
;; See Apple II Miscellaneous #7: Apple II Family Identification
;; Now stash the bytes we need
copy8 VERSION, tmp_version ; $06 = IIe or later
copy8 ZIDBYTE, tmp_idbyte ; $00 = IIc or later
;; ... and page in LCBANK1
sta ALTZPON
bit LCBANK1
bit LCBANK1
;; State needed by MGTK
tmp_version := *+1
lda #SELF_MODIFIED_BYTE
sta startdesktop_params::machine
tmp_idbyte := *+1
lda #SELF_MODIFIED_BYTE
sta startdesktop_params::subid
;; Model?
ldx #DeskTopSettings::system_capabilities
jsr ReadSetting
tax ; A = X = kSysCapXYZ bitmap
ora #DeskTopSettings::kSysCapIsIIgs | DeskTopSettings::kSysCapIsLaser128
IF_NOT_ZERO
lda #kPeriodicTaskDelayIIgs
bne end ; always
END_IF
txa ; A = X = kSysCapXYZ bitmap
ora #DeskTopSettings::kSysCapIsIIc
IF_NOT_ZERO
lda #kPeriodicTaskDelayIIc
bne end ; always
END_IF
;; Default
lda #kPeriodicTaskDelayIIe
end:
sta periodic_task_delay
;; Fall through
.endscope ; machine_type
;;; ============================================================
;;; Snapshot state of PB2 (shift key mod)
.scope pb2_state
copy8 BUTN2, pb2_initial_state
;; fall through
.endscope ; pb2_state
;;; ============================================================
;;; Back up DEVLST
.scope
;; Make a copy of the original device list
.assert DEVLST = DEVCNT+1, error, "DEVCNT must precede DEVLST"
ldx DEVCNT ; number of devices
inx ; include DEVCNT itself
DO
copy8 DEVLST-1,x, main::devlst_backup,x ; DEVCNT is at DEVLST-1
dex
WHILE_POS
;; fall through
.endscope
;;; ============================================================
;;; Make startup volume first in list
.scope
;; Find the startup volume's unit number
copy8 DEVNUM, target
jsr main::GetCopiedToRAMCardFlag
IF_NS
param_call main::CopyDeskTopOriginalPrefix, INVOKER_PREFIX
MLI_CALL GET_FILE_INFO, main::src_file_info_params
IF_CC
copy8 DEVNUM, target
END_IF
END_IF
;; Find the device's index in the list
ldx #0
DO
lda DEVLST,x
and #UNIT_NUM_MASK ; to compare against DEVNUM
target := *+1
cmp #SELF_MODIFIED_BYTE
beq found
inx
WHILE_X_LT DEVCNT
bcs done ; last one or not found
;; Save it
found: ldy DEVLST,x
;; Move everything up
DO
copy8 DEVLST+1,x, DEVLST,x
inx
WHILE_X_NE DEVCNT
;; Place it at the end
tya
sta DEVLST,x
done:
.endscope
;;; ============================================================
jsr DisconnectRAM
;;; ============================================================
;;; Initialize MGTK
.scope
;; Copy pattern from settings to somewhere MGTK can see
tmp_pattern := $00
ldx #DeskTopSettings::pattern + .sizeof(MGTK::Pattern)-1
DO
jsr ReadSetting
sta tmp_pattern - DeskTopSettings::pattern,x
dex
WHILE_X_NE #AS_BYTE(DeskTopSettings::pattern-1)
MGTK_CALL MGTK::SetZP1, setzp_params_nopreserve
MGTK_CALL MGTK::SetDeskPat, tmp_pattern
MGTK_CALL MGTK::StartDeskTop, startdesktop_params
MGTK_CALL MGTK::InitMenu, initmenu_params
jsr main::SetRGBMode
MGTK_CALL MGTK::SetMenu, aux::desktop_menu
jsr main::ShowClock
lda startdesktop_params::slot_num
IF_ZERO
ldx #DeskTopSettings::options
jsr ReadSetting
ora #DeskTopSettings::kOptionsShowShortcuts
jsr WriteSetting
END_IF
SET_BIT7_FLAG main::mli_relay_checkevents_flag
;; --------------------------------------------------
;; Cursor tracking
;; Doubled if option selected
ldx #DeskTopSettings::mouse_tracking
jsr ReadSetting
IF_NOT_ZERO
inc scalemouse_params::x_exponent
inc scalemouse_params::y_exponent
END_IF
;; Also doubled if a IIc
ldx #DeskTopSettings::system_capabilities
jsr ReadSetting
and #DeskTopSettings::kSysCapIsIIc
IF_NOT_ZERO
inc scalemouse_params::x_exponent
inc scalemouse_params::y_exponent
END_IF
MGTK_CALL MGTK::ScaleMouse, scalemouse_params
;; --------------------------------------------------
MGTK_CALL MGTK::SetCursor, MGTK::SystemCursor::watch
MGTK_CALL MGTK::ShowCursor
;; fall through
.endscope
;;; ============================================================
;;; Initialize IconTK
.scope
ITK_CALL IconTK::InitToolKit, itkinit_params
FALL_THROUGH_TO CreateTrashIcon
.endscope
;;; ============================================================
.proc CreateTrashIcon
ptr := $6
copy8 #0, cached_window_id
lda #1
sta cached_window_entry_count
sta icon_count
ITK_CALL IconTK::AllocIcon, get_icon_entry_params
lda get_icon_entry_params::id
sta main::trash_icon_num
sta cached_window_entry_list
sta icon_param
ldax get_icon_entry_params::addr
stax ptr
;; Trash is a drop target
ldy #IconEntry::win_flags
copy8 #kIconEntryFlagsDropTarget|kIconEntryFlagsNotDropSource, (ptr),y
ldy #IconEntry::iconx
copy16in #main::kTrashIconX, (ptr),y
ldy #IconEntry::icony
copy16in #main::kTrashIconY, (ptr),y
ldy #IconEntry::type
copy8 #IconType::trash, (ptr),y
iny
ldx #0
DO
copy8 trash_name,x, (ptr),y
iny
inx
WHILE_X_NE trash_name
copy8 trash_name,x, (ptr),y
ITK_CALL IconTK::DrawIcon, icon_param
FALL_THROUGH_TO LoadSelectorList
.endproc ; CreateTrashIcon
;;; ============================================================
;;; See docs/Selector_List_Format.md for file format
.proc LoadSelectorList
ptr1 := $6
ptr2 := $8
selector_list_io_buf := IO_BUFFER
selector_list_data_buf := data_buf
.assert kSelectorListShortSize <= kDataBufferSize, error, "Buffer size error"
MGTK_CALL MGTK::CheckEvents
copy8 #0, index
jsr _ReadSelectorList
bne done
lda selector_list_data_buf + kSelectorListNumPrimaryRunListOffset
clc
adc selector_list_data_buf + kSelectorListNumSecondaryRunListOffset
sta num_selector_list_items
copy8 selector_list_data_buf, count
loop: lda index
cmp count
beq done
;; Copy entry name into place
jsr main::ATimes16
addax #selector_list_data_buf + kSelectorListEntriesOffset, ptr1
lda index
jsr main::ATimes16
addax #run_list_entries, ptr2
jsr _CopyPtr1ToPtr2
;; Copy entry flags into place
ldy #15
copy8 (ptr1),y, (ptr2),y
;; Copy entry path into place
lda index
jsr main::ATimes64
addax #selector_list_data_buf + kSelectorListPathsOffset, ptr1
lda index
jsr main::ATimes64
addax #main::run_list_paths, ptr2
jsr _CopyPtr1ToPtr2
inc index
inc selector_menu
jmp loop
done:
;; No separator if it is last
lda selector_menu
IF_A_EQ #kSelectorMenuFixedItems
dec selector_menu
END_IF
jmp end_of_scope
index: .byte 0
count: .byte 0
;;; --------------------------------------------------
.proc _CopyPtr1ToPtr2
ptr1 := $06
ptr2 := $08
ldy #0
lda (ptr1),y
tay
DO
copy8 (ptr1),y, (ptr2),y
dey
WHILE_POS
rts
.endproc ; _CopyPtr1ToPtr2
;;; --------------------------------------------------
DEFINE_OPEN_PARAMS open_params, str_selector_list, selector_list_io_buf
str_selector_list:
PASCAL_STRING kPathnameSelectorList
DEFINE_READWRITE_PARAMS read_params, selector_list_data_buf, kSelectorListShortSize
DEFINE_CLOSE_PARAMS close_params
.proc _ReadSelectorList
MLI_CALL OPEN, open_params
bcs not_found
lda open_params::ref_num
sta read_params::ref_num
MLI_CALL READ, read_params
MLI_CALL CLOSE, close_params
rts
not_found:
;; Clear buffer
ptr := $06
copy16 #selector_list_data_buf, ptr
ldx #>kSelectorListShortSize ; number of pages
lda #0
DO
ldy #0
DO
sta (ptr),y
dey
WHILE_NOT_ZERO
inc ptr+1
dex
WHILE_NOT_ZERO
rts
.endproc ; _ReadSelectorList
end_of_scope := *
.endproc ; LoadSelectorList
;;; ============================================================
;;; Enumerate Desk Accessories
.scope
MGTK_CALL MGTK::CheckEvents
read_dir_buffer := data_buf
;; Does the directory exist?
MLI_CALL GET_FILE_INFO, get_file_info_params
jcs end
lda get_file_info_params::file_type
cmp #FT_DIRECTORY
beq open_dir
jmp end
open_dir:
MLI_CALL OPEN, open_params
lda open_params::ref_num
sta read_params::ref_num
sta close_params::ref_num
MLI_CALL READ, read_params
lda #0
sta entry_num
sta desk_acc_num
copy8 #1, entry_in_block ; First block has header instead of entry
lda read_dir_buffer + SubdirectoryHeader::file_count
and #$7F
sta file_count
copy8 read_dir_buffer + SubdirectoryHeader::entries_per_block, entries_per_block
copy8 read_dir_buffer + SubdirectoryHeader::entry_length, entry_length
dir_ptr := $06
da_ptr := $08
copy16 #read_dir_buffer + .sizeof(SubdirectoryHeader), dir_ptr
process_block:
param_call_indirect AdjustFileEntryCase, dir_ptr
ldy #FileEntry::storage_type_name_length
lda (dir_ptr),y
and #NAME_LENGTH_MASK
jeq next_entry
inc entry_num
;; Hide invisible files
ldy #FileEntry::access
lda (dir_ptr),y
and #ACCESS_I
jne next_entry
ldy #FileEntry::file_type
lda (dir_ptr),y
IF_A_EQ #kDAFileType ; DA? (must match type/auxtype)
ldy #FileEntry::aux_type
lda (dir_ptr),y
cmp #<kDAFileAuxType
jne next_entry
iny
lda (dir_ptr),y
cmp #>kDAFileAuxType
jne next_entry
END_IF
;; Allow anything else
;; Compute slot in DA name table
ldy desk_acc_num
ldax #kDAMenuItemSize
jsr Multiply_16_8_16
addax #desk_acc_names, da_ptr
;; Copy name
ldy #FileEntry::storage_type_name_length
lda (dir_ptr),y
and #NAME_LENGTH_MASK
sta name_buf
tay
DO
copy8 (dir_ptr),y, name_buf,y
dey
WHILE_NOT_ZERO
;; If a directory, prepend name with folder glyphs
ldy #FileEntry::file_type
lda (dir_ptr),y
IF_A_EQ #FT_DIRECTORY ; Directory?
ldy name_buf
DO
copy8 name_buf,y, name_buf+3,y
dey
WHILE_NOT_ZERO
copy8 #kGlyphFolderLeft, name_buf+1
copy8 #kGlyphFolderRight, name_buf+2
copy8 #kGlyphSpacer, name_buf+3
inc name_buf
inc name_buf
inc name_buf
END_IF
;; Convert periods to spaces, copy into menu
ldy #0
copy8 name_buf,y, (da_ptr),y
tay
DO
lda name_buf,y
IF_A_EQ #'.'
lda #' '
END_IF
sta (da_ptr),y
dey
WHILE_NOT_ZERO
inc desk_acc_num
inc apple_menu ; number of menu items
next_entry:
;; Room for more DAs?
lda desk_acc_num
cmp #kMaxDeskAccCount
jcs close_dir
;; Any more entries in dir?
lda entry_num
cmp file_count
jeq close_dir
;; Any more entries in block?
inc entry_in_block
lda entry_in_block
IF_A_EQ entries_per_block
MLI_CALL READ, read_params
copy16 #read_dir_buffer + 4, dir_ptr
copy8 #0, entry_in_block
jmp process_block
END_IF
add16_8 dir_ptr, entry_length
jmp process_block
close_dir:
MLI_CALL CLOSE, close_params
jmp end
DEFINE_OPEN_PARAMS open_params, str_desk_acc, IO_BUFFER
.assert BLOCK_SIZE <= kDataBufferSize, error, "Buffer size error"
DEFINE_READWRITE_PARAMS read_params, read_dir_buffer, BLOCK_SIZE
DEFINE_GET_FILE_INFO_PARAMS get_file_info_params, str_desk_acc
DEFINE_CLOSE_PARAMS close_params
str_desk_acc:
PASCAL_STRING kFilenameDADir
file_count: .byte 0
entry_num: .byte 0
desk_acc_num: .byte 0
entry_length: .byte 0
entries_per_block: .byte 0
entry_in_block: .byte 0
name_buf: .res ::kDAMenuItemSize, 0
end:
;; No separator if it is last
lda apple_menu
IF_A_EQ #kAppleMenuFixedItems
dec apple_menu
END_IF
.endscope
;;; ============================================================
;;; Populate volume icons
.scope
copy8 #0, main::pending_alert
;; Enumerate DEVLST in reverse order (most important volumes first)
copy8 DEVCNT, device_index
DO
device_index := *+1
ldy #SELF_MODIFIED_BYTE
lda DEVLST,y
pha ; A = unmasked unit number
jsr main::CreateVolumeIcon ; A = unmasked unit number, Y = device index
IF_A_EQ #ERR_DEVICE_NOT_CONNECTED
;; If device is not connected, remove it from DEVLST
;; unless it's a Disk II.
pla ; A = unmasked unit number
pha ; A = unmasked unit number
;; NOTE: Not masked with `UNIT_NUM_MASK`, `IsDiskII` handles it.
jsr main::IsDiskII
beq done_create ; skip
ldx device_index
jsr _RemoveDevice
jmp next
END_IF
IF_A_EQ #ERR_DUPLICATE_VOLUME
copy8 #kErrDuplicateVolName, main::pending_alert
END_IF
done_create:
ldx cached_window_entry_count
copy8 cached_window_entry_list-1,x, icon_param
ITK_CALL IconTK::DrawIcon, icon_param
next:
pla
dec device_index
WHILE_POS
copy8 #0, cached_window_id
jsr main::StoreWindowEntryTable
jmp end_of_scope
;;; Remove device num in X from devices list
.proc _RemoveDevice
dex
DO
inx
copy8 DEVLST+1,x, DEVLST,x
copy8 main::device_to_icon_map+1,x, main::device_to_icon_map,x
cpx DEVCNT
WHILE_NOT_ZERO
dec DEVCNT
;; ProDOS requires an ON_LINE call after a device is
;; disconnected in order to clean up the VCB entry. However,
;; we only remove devices here if the device already failed an
;; ON_LINE call with `ERR_DEVICE_NOT_CONNECTED` so it should
;; not be necessary.
rts
.endproc ; _RemoveDevice
end_of_scope := *
FALL_THROUGH_TO PopulateDeviceNames
.endscope
;;; ============================================================
;;; This section populates `device_name_table` - it determines which
;;; device type string to use, and fills in slot and drive as
;;; appropriate. Used in the Format/Erase disk dialog.
.proc PopulateDeviceNames
;; Enumerate DEVLST in reverse order (most important volumes first)
ldy DEVCNT
DO
tya ; Y = index
pha ; A = index
devname_ptr := $08
asl a
tax
copy16 device_name_table,x, devname_ptr
lda DEVLST,y
pha ; A = unmasked unit number
src := $06
jsr main::GetDeviceType ; A = unmasked unit number
stax src ; A,X = device name (may be empty)
;; Empty?
ldy #0
lda (src),y
IF_ZERO
copy16 #str_volume_type_unknown, src
END_IF
;; Set final length
lda (src),y ; Y = 0
clc
adc #kSDPrefixLength
sta str_sdname_buffer
;; Copy string into template, after prefix
lda (src),y ; Y = 0
tay ; Y = length
DO
copy8 (src),y, str_sdname_buffer + kSDPrefixLength,y
dey
WHILE_NOT_ZERO ; leave length alone
;; Insert Slot #
pla ; A = unmasked unit number
pha ; A = unmasked unit number
and #UNIT_NUM_SLOT_MASK
lsr a ; 00111000
lsr a ; 00011100
lsr a ; 00001110
lsr a ; 00000111
ora #'0'
sta str_sdname_buffer + kDeviceTemplateSlotOffset
;; Insert Drive #
pla ; A = unmasked unit number
rol a ; set carry to drive - 1
lda #0 ; 0 + carry + '1'
adc #'1' ; convert to '1' or '2'
sta str_sdname_buffer + kDeviceTemplateDriveOffset
;; Copy name into table
ldy str_sdname_buffer
DO
copy8 str_sdname_buffer,y, (devname_ptr),y
dey
WHILE_POS
pla ; A = index
tay ; Y = index
dey
WHILE_POS
FALL_THROUGH_TO PopulateStartupMenu
.endproc ; PopulateDeviceNames
;;; ============================================================
.proc PopulateStartupMenu
slot_ptr := $06 ; pointed at $Cn00
table_ptr := $08 ; points into slot_string_table
copy8 #7, slot
copy8 #0, slot_ptr
tax ; X = menu entry
;; Identify ProDOS device in slot by ID bytes
DO
lda slot
ora #$C0 ; hi byte of $Cn00
sta slot_ptr+1
ldy #$01 ; $Cn01 == $20 ?
lda (slot_ptr),y
cmp #$20
bne next
ldy #$03 ; $Cn03 == $00 ?
lda (slot_ptr),y
cmp #$00
bne next
ldy #$05 ; $Cn05 == $03 ?
lda (slot_ptr),y
cmp #$03
bne next
;; It is a ProDOS device - prepare menu item.
copy8 slot, main::startup_slot_table,x
txa ; pointer to nth sNN string
pha
asl a
tax
copy16 slot_string_table,x, table_ptr
ldy #kStartupMenuItemSlotOffset
lda slot
ora #'0'
sta (table_ptr),y
pla
tax
inx
next: dec slot
WHILE_NOT_ZERO
;; Set number of menu items.
stx startup_menu
jmp end_of_scope
slot: .byte 0
slot_string_table:
.addr startup_menu_item_1
.addr startup_menu_item_2
.addr startup_menu_item_3
.addr startup_menu_item_4
.addr startup_menu_item_5
.addr startup_menu_item_6
.addr startup_menu_item_7
ASSERT_ADDRESS_TABLE_SIZE slot_string_table, ::kMenuSizeStartup
end_of_scope := *
FALL_THROUGH_TO InitializeDisksInDevicesTables
.endproc ; PopulateStartupMenu
;;; ============================================================
;;; Enumerate DEVLST and find removable devices; build a list of
;;; these, and check to see which have disks in them. The list
;;; will be polled periodically to detect changes and refresh.
;;; List is built in DEVLST order since processing is in
;;; `CheckDisksInDevices` (etc) is done in reverse order.
;;;
;;; Some hardware (machine/slot) combinations are filtered out
;;; due to known-buggy firmware.
.proc InitializeDisksInDevicesTables
slot_ptr := $0A
lda #0
sta count
sta index
DO
ldy index
lda DEVLST,y
;; NOTE: Not masked with `UNIT_NUM_MASK`, `DeviceDriverAddress` handles it.
sta unit_num
jsr main::DeviceDriverAddress
bvs append ; remapped SmartPort, it's usable
bne next ; if RAM-based driver (not $CnXX), skip
stx slot_ptr+1 ; just need high byte ($Cn)
copy8 #0, slot_ptr ; make $Cn00
ldy #$FF ; Firmware ID byte
lda (slot_ptr),y ; $CnFF: $00=Disk II, $FF=13-sector, else=block
beq next
dey
lda (slot_ptr),y ; $CnFE: Status Byte
bmi append ; bit 7 - Medium is removable
next: inc index
lda DEVCNT ; continue while index <= DEVCNT
WHILE_A_GE index
lda count
sta main::removable_device_table
sta main::disk_in_device_table
jsr main::CheckDisksInDevices
;; Make copy of table
ldx main::disk_in_device_table
IF_NOT_ZERO
DO
copy8 main::disk_in_device_table,x, main::last_disk_in_devices_table,x
dex
WHILE_POS
END_IF
jmp end_of_scope
DEFINE_SP_STATUS_PARAMS status_params, SELF_MODIFIED_BYTE, dib_buffer, 3 ; Return Device Information Block (DIB)
dib_buffer := ::IO_BUFFER
;; Maybe add device to the removable device table
append:
;; Do SmartPort STATUS call to filter out 5.25 devices
lda unit_num
jsr main::FindSmartportDispatchAddress
bcs next ; can't determine address - skip it!
stax dispatch
sty status_params::unit_num
;; Don't issue STATUS calls to IIc Plus Slot 5 firmware, as it causes
;; the motor to spin. https://github.com/a2stuff/a2d/issues/25
ldx #DeskTopSettings::system_capabilities
jsr ReadSetting
and #DeskTopSettings::kSysCapIsIIcPlus
IF_NOT_ZERO
lda dispatch+1
and #%00001111 ; mask off slot
cmp #$05 ; is it slot 5?
beq next ; if so, ignore
END_IF
;; Don't issue STATUS calls to Laser 128 Slot 7 firmware, as it causes
;; hangs in some cases. https://github.com/a2stuff/a2d/issues/138
ldx #DeskTopSettings::system_capabilities
jsr ReadSetting
and #DeskTopSettings::kSysCapIsLaser128
IF_NOT_ZERO
lda dispatch+1 ; $Cs
and #%00001111 ; mask off slot
cmp #$07 ; is it slot 7?
beq next ; if so, skip it!
END_IF
dispatch := *+1
jsr SELF_MODIFIED
.byte SPCall::Status
.addr status_params
bcs next ; call failed - skip it!
lda dib_buffer+SPDIB::Device_Type_Code
cmp #SPDeviceType::Disk525
beq next ; is 5.25 - skip it!
;; Append the device
inc count
ldx count
copy8 unit_num, main::removable_device_table,x
bne next ; always
index: .byte 0
count: .byte 0
unit_num:
.byte 0
end_of_scope := *
FALL_THROUGH_TO FinalSetup
.endproc ; InitializeDisksInDevicesTables
;;; ============================================================
.proc FinalSetup
;; Final MGTK configuration
MGTK_CALL MGTK::CheckEvents
MGTK_CALL MGTK::SetCursor, MGTK::SystemCursor::pointer
copy8 #0, active_window_id
;; Restore state from previous session
jsr RestoreWindows
;; Display any pending error messages
lda main::pending_alert
IF_NOT_ZERO
tay
jsr ShowAlert
END_IF
;; And start pumping events
jmp main::MainLoop
.endproc ; FinalSetup
;;; ============================================================
.proc RestoreWindows
data_ptr := $06
jsr main::save_restore_windows::Open
jcs exit
lda main::save_restore_windows::open_params::ref_num
sta main::save_restore_windows::rw_params::ref_num
sta main::save_restore_windows::close_params::ref_num
MLI_CALL READ, main::save_restore_windows::rw_params
jsr main::save_restore_windows::Close
;; Validate file format version byte
lda main::save_restore_windows::desktop_file_data_buf
cmp #kDeskTopFileVersion
jne exit
copy16 #main::save_restore_windows::desktop_file_data_buf+1, data_ptr
loop: ldy #0
lda (data_ptr),y
beq exit
tay
DO
copy8 (data_ptr),y, INVOKER_PREFIX,y
dey
WHILE_POS
jsr PushPointers
;; Is there a matching volume icon? (If not, skip)
ldx #1 ; past leading '/'
DO
lda INVOKER_PREFIX+1,x
BREAK_IF_A_EQ #'/' ; look for next '/'
inx
WHILE_X_NE INVOKER_PREFIX
dex
stx INVOKER_PREFIX+1 ; overwrite leading '/' with length
param_call main::FindIconByName, 0, INVOKER_PREFIX+1 ; 0=desktop
beq next
copy8 #'/', INVOKER_PREFIX+1 ; restore leading '/'
;; Copy view type to `new_window_view_by`
ldy #DeskTopFileItem::view_by
copy8 (data_ptr),y, new_window_view_by
;; Copy loc to `new_window_viewloc`
ldy #DeskTopFileItem::viewloc+.sizeof(MGTK::Point)-1
ldx #.sizeof(MGTK::Point)-1
DO
copy8 (data_ptr),y, new_window_viewloc,x
dey
dex
WHILE_POS
;; Copy bounds to `new_window_maprect`
ldy #DeskTopFileItem::maprect+.sizeof(MGTK::Rect)-1
ldx #.sizeof(MGTK::Rect)-1
DO
copy8 (data_ptr),y, new_window_maprect,x
dey
dex
WHILE_POS
lda #$80
sta main::copy_new_window_bounds_flag
sta main::CreateFileRecordsForWindowImpl::suppress_error_on_open_flag
jsr _MaybeOpenWindow
lda #0
sta main::copy_new_window_bounds_flag
sta main::CreateFileRecordsForWindowImpl::suppress_error_on_open_flag
next: jsr PopPointers
add16_8 data_ptr, #.sizeof(DeskTopFileItem)
jmp loop
exit: jmp main::LoadDesktopEntryTable
.proc _MaybeOpenWindow
;; Save stack for restore on error. If the call
;; fails, the routine will restore the stack then
;; rts, returning to our caller.
tsx
stx main::saved_stack
jmp main::OpenWindowForPath
.endproc ; _MaybeOpenWindow
.endproc ; RestoreWindows
;;; ============================================================
kDeviceTemplateSlotOffset = res_const_sd_prefix_pattern_offset1
kDeviceTemplateDriveOffset = res_const_sd_prefix_pattern_offset2
kSDPrefixLength = .strlen(res_string_sd_prefix_pattern)
str_sdname_buffer:
PASCAL_STRING res_string_sd_prefix_pattern ; "S#,D#: " prefix
.res 16, 0 ; space for actual name
str_volume_type_unknown:
PASCAL_STRING res_string_volume_type_unknown
trash_name: PASCAL_STRING res_string_trash_icon_name
;;; ============================================================
.include "../lib/clear_dhr.s"
saved_ram_unitnum := main::saved_ram_unitnum
saved_ram_drvec := main::saved_ram_drvec
saved_ram_buffer := IO_BUFFER
.include "../lib/disconnect_ram.s"
;;; ============================================================
.endscope ; init
ENDSEG SegmentInitializer
|
a2stuff/a2d
| 31,108
|
src/desktop/ovl_format_erase.s
|
;;; ============================================================
;;; Overlay for Format/Erase
;;;
;;; Compiled as part of desktop.s
;;; ============================================================
BEGINSEG OverlayFormatErase
.scope FormatEraseOverlay
;;; Memory Map
;;; ...
;;; $1E00 - $1FFF - unused/preserved
;;; $1C00 - $1DFF - `read_buffer` (for checking target format)
;;; $1A00 - $1BFF - `block_buffer` (for writing)
;;; $1700 - $19FF - unused/preserved
;;; $0800 - $16FF - overlay code
;;; ...
MLIEntry := main::MLIRelayImpl
MGTKEntry := MGTKRelayImpl
LETKEntry := LETKRelayImpl
BTKEntry := BTKRelayImpl
OPTKEntry := OPTKRelayImpl
block_buffer := $1A00
read_buffer := $1C00
ovl_string_buf := path_buf0
kDefaultFloppyBlocks = 280
;;; ============================================================
;; This must be page-aligned.
.include "../lib/formatdiskii.s"
;;; ============================================================
;;; A = operation (Format/Erase); X = unit num (or 0)
Exec:
cmp #FormatEraseAction::format
jeq FormatDisk
jmp EraseDisk
;;; ============================================================
;;; Show the device prompt, name prompt, and confirmation.
;;; Input: C=operation flag, 1=erase, 0=format
;;; X=unit num, or 0 to prompt for device
;;; Output: C=0, A=unit_num on success, C=1 if canceled.
.proc PromptForDeviceAndName
ror erase_flag ; C into bit7
stx unit_num
;; --------------------------------------------------
;; Prompt for device
.scope
CLEAR_BIT7_FLAG has_input_field_flag
lda #kPromptButtonsOKCancel
jsr main::OpenPromptWindow ; A = `prompt_button_flags`
jsr main::SetPortForDialogWindow
ldax #aux::label_format_disk
bit erase_flag
IF_NS
ldax #aux::label_erase_disk
END_IF
jsr main::DrawDialogTitle
lda unit_num
bne skip_select
MGTK_CALL MGTK::MoveTo, vol_picker_select_pos
ldax #aux::str_select_format
bit erase_flag
IF_NS
ldax #aux::str_select_erase
END_IF
jsr main::DrawString
jsr main::SetPenModeNotCopy
MGTK_CALL MGTK::MoveTo, vol_picker_line1_start
MGTK_CALL MGTK::LineTo, vol_picker_line1_end
MGTK_CALL MGTK::MoveTo, vol_picker_line2_start
MGTK_CALL MGTK::LineTo, vol_picker_line2_end
copy8 #$FF, vol_picker_record::selected_index
copy16 #HandleClick, main::PromptDialogClickHandlerHook
copy16 #HandleKey, main::PromptDialogKeyHandlerHook
SET_BIT7_FLAG has_device_picker_flag
OPTK_CALL OPTK::Draw, vol_picker_params
jsr main::UpdateOKButton
DO
jsr main::PromptInputLoop
WHILE_NS ; not done
jne cancel ; cancel
jsr GetSelectedUnitNum
sta unit_num
.endscope
skip_select:
;; --------------------------------------------------
;; Prompt for name
.scope
ldax #main::NoOp
stax main::PromptDialogClickHandlerHook
stax main::PromptDialogKeyHandlerHook
jsr SetPortAndClear
jsr main::SetPenModeNotCopy
MGTK_CALL MGTK::FrameRect, name_input_rect
SET_BIT7_FLAG has_input_field_flag
copy8 #0, text_input_buf
CLEAR_BIT7_FLAG has_device_picker_flag
param_call main::DrawDialogLabel, 2, aux::str_location
;; Find `DEVLST` index of selected/specified device
ldx #AS_BYTE(-1)
DO
inx
lda DEVLST,x
and #UNIT_NUM_MASK
WHILE_A_NE unit_num
;; NOTE: Assertion violation if not found
txa
jsr GetDeviceNameForIndex
jsr main::DrawString
param_call main::DrawDialogLabel, 4, aux::str_new_volume
LETK_CALL LETK::Init, prompt_le_params
LETK_CALL LETK::Activate, prompt_le_params
jsr main::UpdateOKButton
loop2:
jsr main::PromptInputLoop
bmi loop2 ; not done
bne cancel ; cancel
jsr main::SetCursorPointerWithFlag
;; Check for conflicting name
ldxy #text_input_buf
lda unit_num
jsr CheckConflictingVolumeName
bcc :+
lda #ERR_DUPLICATE_FILENAME
jsr ShowAlert
jmp loop2
:
.endscope
;; --------------------------------------------------
;; Confirm operation
.scope
COPY_STRING text_input_buf, main::filename_buf
CLEAR_BIT7_FLAG has_input_field_flag
jsr SetPortAndClear
MGTK_CALL MGTK::PaintRect, ok_button::rect
MGTK_CALL MGTK::PaintRect, cancel_button::rect
lda unit_num
jsr GetVolName ; populates `ovl_string_buf`
copy8 #0, text_input_buf
param_call AppendToTextInputBuf, aux::str_confirm_erase_prefix
param_call AppendToTextInputBuf, ovl_string_buf
param_call AppendToTextInputBuf, aux::str_confirm_erase_suffix
param_call ShowAlertParams, AlertButtonOptions::OKCancel, text_input_buf
cmp #kAlertResultOK
jne cancel
.endscope
;; Confirmed!
unit_num := *+1
lda #SELF_MODIFIED_BYTE
clc
rts
cancel:
sec
rts
;;; High bit set if erase, otherwise format.
erase_flag:
.byte 0
.endproc ; PromptForDeviceAndName
;;; ============================================================
;;; Format Disk
.proc FormatDisk
clc ; C=0 = format
jsr PromptForDeviceAndName
bcs finish
sta unit_num
;; --------------------------------------------------
;; Proceed with format
retry:
jsr SetPortAndClear
param_call main::DrawDialogLabel, 1, aux::str_formatting
param_call main::DrawDialogLabel, 7, aux::str_tip_prodos
jsr main::SetCursorWatch
unit_num := *+1
lda #SELF_MODIFIED_BYTE
jsr CheckSupportsFormat
and #$FF
bne l9
lda unit_num
jsr FormatUnit
bcs l12
l9:
lda unit_num
jmp ::FormatEraseOverlay::EraseDisk::EP2
l12: pha
jsr main::SetCursorPointer
pla
IF_A_EQ #ERR_WRITE_PROTECTED
jsr ShowAlert
ASSERT_NOT_EQUALS ::kAlertResultCancel, 0
bne finish ; `kAlertResultCancel` = 1
beq retry ; `kAlertResultTryAgain` = 0
END_IF
param_call ShowAlertParams, AlertButtonOptions::TryAgainCancel, aux::str_formatting_error
cmp #kAlertResultCancel
bne retry
finish:
pha
jsr main::SetCursorPointer
MGTK_CALL MGTK::CloseWindow, winfo_prompt_dialog
jsr main::ClearUpdates
ldx unit_num
pla
rts
.endproc ; FormatDisk
;;; ============================================================
;;; Erase Disk
.proc EraseDisk
sec ; C=1 = erase
jsr PromptForDeviceAndName
bcs finish
;;; Entry point used after `FormatDisk`
EP2:
sta unit_num
;; --------------------------------------------------
;; Proceed with erase
retry:
jsr SetPortAndClear
param_call main::DrawDialogLabel, 1, aux::str_erasing
param_call main::DrawDialogLabel, 7, aux::str_tip_prodos
jsr main::SetCursorWatch
ldxy #main::filename_buf
unit_num := *+1
lda #SELF_MODIFIED_BYTE
jsr WriteHeaderBlocks
pha
jsr main::SetCursorPointer
pla
IF_ZERO
lda #$00
beq finish ; always
END_IF
IF_A_EQ #ERR_WRITE_PROTECTED
jsr ShowAlert
ASSERT_NOT_EQUALS ::kAlertResultCancel, 0
bne finish ; `kAlertResultCancel` = 1
beq retry ; `kAlertResultTryAgain` = 0
END_IF
param_call ShowAlertParams, AlertButtonOptions::TryAgainCancel, aux::str_erasing_error
cmp #kAlertResultCancel
bne retry
finish:
pha
jsr main::SetCursorPointer
MGTK_CALL MGTK::CloseWindow, winfo_prompt_dialog
jsr main::ClearUpdates
ldx unit_num
pla
rts
.endproc ; EraseDisk
;;; ============================================================
.proc SetPortAndClear
jsr main::SetPortForDialogWindow
MGTK_CALL MGTK::PaintRect, aux::clear_dialog_labels_rect
rts
.endproc ; SetPortAndClear
;;; ============================================================
;;; Output: N=0 if there is a valid selection, N=1 if no selection
;;; A,X,Y unmodified
.proc ValidSelection
bit vol_picker_record::selected_index
rts
.endproc ; ValidSelection
;;; ============================================================
.proc HandleClick
COPY_STRUCT screentowindow_params::window, vol_picker_params::coords
OPTK_CALL OPTK::Click, vol_picker_params
IF_NC
jsr DetectDoubleClick
IF_NC
pha
BTK_CALL BTK::Flash, ok_button
pla
END_IF
END_IF
rts
.endproc ; HandleClick
;;; ============================================================
.proc HandleKey
IF_A_EQ_ONE_OF #CHAR_UP, #CHAR_DOWN, #CHAR_LEFT, #CHAR_RIGHT
sta vol_picker_params::key
OPTK_CALL OPTK::Key, vol_picker_params
END_IF
return #$FF
.endproc ; HandleKey
;;; ============================================================
;;; Input: A = index
;;; Output: N=0 if valid entry
.proc IsEntryCallback
cmp DEVCNT ; num volumes - 1
beq yes ; TODO: `BGT` ?
bcs no
yes: lda #$00
rts
no: lda #$80
rts
.endproc ; IsEntryCallback
.proc DrawEntryCallback
;; Reverse order, so boot volume is first
sta index
lda DEVCNT
sec
index := *+1
sbc #SELF_MODIFIED_BYTE
jsr GetDeviceNameForIndex
jmp main::DrawString
.endproc ; DrawEntryCallback
.proc SelChangeCallback
jmp main::UpdateOKButton
.endproc ; SelChangeCallback
;;; ============================================================
;;; Input: A = index in `DEVLST`
;;; Output: A,X = device name
.proc GetDeviceNameForIndex
asl a
tay
ldax device_name_table,y ; now A,X has pointer
rts
.endproc ; GetDeviceNameForIndex
;;; ============================================================
;;; Gets the selected unit number from `DEVLST`
;;; Output: A = unit number (with low nibble intact)
;;; Assert: `vol_picker_record::selected_index` is valid (i.e. not $FF)
.proc GetSelectedUnitNum
;; Reverse order, so boot volume is first
lda DEVCNT
sec
sbc vol_picker_record::selected_index
tax
lda DEVLST,x
and #UNIT_NUM_MASK
rts
.endproc ; GetSelectedUnitNum
;;; ============================================================
;;; Inputs: A = unit number (no need to mask off low nibble), X,Y = name
;;; Outputs: C=1 if there's a duplicate, C=0 otherwise
.proc CheckConflictingVolumeName
ptr := $06
stxy ptr
sta unit_num
;; Copy name, prepending '/'
ldy #0
lda (ptr),y
tay
DO
copy8 (ptr),y, path+1,y
dey
WHILE_POS
clc
adc #1
sta path
copy8 #'/', path+1
MLI_CALL GET_FILE_INFO, get_file_info_params
IF_CC
;; A volume with that name exists... but is it the one
;; we're about to format/erase?
lda DEVNUM
unit_num := *+1
cmp #SELF_MODIFIED_BYTE
IF_NE
;; Not the same device, so a match. Return C=1
sec
rts
END_IF
END_IF
;; No match we care about, so return C=0.
clc
rts
.endproc ; CheckConflictingVolumeName
;;; ============================================================
;; Used to get current volume name (if a ProDOS volume)
DEFINE_ON_LINE_PARAMS on_line_params,, on_line_buffer
DEFINE_READWRITE_BLOCK_PARAMS read_block_params, read_buffer, 0
DEFINE_READWRITE_BLOCK_PARAMS write_block_params, prodos_loader_blocks, 0
;; Used to check for existing volume with same name
DEFINE_GET_FILE_INFO_PARAMS get_file_info_params, path
on_line_buffer:
path:
.res 17,0 ; length + '/' + 15-char name
;;; ============================================================
;;; Get driver address
;;; Input: A = unit number (no need to mask off low nibble)
;;; Output: A,X = driver address
.proc GetDriverAddress
and #UNIT_NUM_MASK ; DSSS0000 after masking
lsr ; 0DSSS000
lsr ; 00DSSS00
lsr ; 000DSSS0
tax
lda DEVADR,x ; low byte of driver address
pha
inx
lda DEVADR,x ; high byte of driver address
tax
pla
rts
.endproc ; GetDriverAddress
;;; ============================================================
;;; Format disk
;;; Input: A = unit number
.proc FormatUnit
sta unit_num
jsr main::IsDiskII
IF_EQ
;; Format as Disk II
lda unit_num
jmp FormatDiskII
END_IF
;; Format using driver
lda unit_num
jsr GetDriverAddress
stax driver_addr
sta ALTZPOFF ; Main ZP/LCBANKs
copy8 #DRIVER_COMMAND_FORMAT, DRIVER_COMMAND
unit_num := *+1
lda #SELF_MODIFIED_BYTE
sta DRIVER_UNIT_NUMBER
driver_addr := *+1
jsr SELF_MODIFIED
sta ALTZPON ; Aux ZP/LCBANKs
rts
.endproc ; FormatUnit
;;; ============================================================
;;; Check if the device supports formatting
;;; Input: A = unit number (with low nibble intact)
;;; Output: A=0/Z=1/N=0 if yes, A=$FF/Z=0/N=1 if no
.proc CheckSupportsFormat
sta unit_num
jsr main::IsDiskII
IF_NE
;; Check if the driver is firmware ($CnXX).
lda unit_num
jsr GetDriverAddress
stx addr+1 ; self-modify address below
txa ; high byte
and #$F0 ; look at high nibble
cmp #$C0 ; firmware? ($Cn)
IF_EQ ; TODO: Should we guess yes or no here???
;; Check the firmware status byte
addr := *+1
lda $C0FE ; $CnFE, high byte is self-modified above
and #%00001000 ; Bit 3 = Supports format
IF_ZERO
return #$FF ; no, does not support format
END_IF
END_IF
END_IF
return #$00 ; yes, supports format
unit_num:
.byte 0
.endproc ; CheckSupportsFormat
;;; ============================================================
;;; Write the loader, volume directory, and volume bitmap
;;; Inputs: A = unit number, X,Y = volume name
.proc WriteHeaderBlocks
sta unit_num
sta write_block_params::unit_num
stxy $06
;; Copy name into volume directory key block data
param_call main::CopyPtr1ToBuf, vol_name_buf
ldx #DeskTopSettings::options
jsr ReadSetting
and #DeskTopSettings::kOptionsSetCaseBits
IF_ZERO
ldax #0
ELSE
param_call_indirect main::CalculateCaseBits, $06
END_IF
stax case_bits
param_call main::UpcaseString, vol_name_buf
;; --------------------------------------------------
;; Get the block count for the device
;; Check if it's a Disk II
lda unit_num
jsr main::IsDiskII
IF_NE
;; Not Disk II - use the driver.
lda unit_num
jsr GetDriverAddress
stax @driver
sta ALTZPOFF ; Main ZP/LCBANKs
copy8 #DRIVER_COMMAND_STATUS, DRIVER_COMMAND
copy8 unit_num, DRIVER_UNIT_NUMBER
copy16 #0, DRIVER_BLOCK_NUMBER
@driver := *+1
jsr SELF_MODIFIED
sta ALTZPON ; Aux ZP/LCBANKs
bcc got_blocks ; success
jmp fail ; failure
END_IF
ldxy #kDefaultFloppyBlocks
got_blocks:
stxy total_blocks
;; --------------------------------------------------
;; Loader blocks
;; Write first block of loader
copy16 #prodos_loader_blocks, write_block_params::data_buffer
copy16 #0, write_block_params::block_num
MLI_CALL WRITE_BLOCK, write_block_params
jcs fail2
;; Write second block of loader
inc write_block_params::block_num ; next block needs...
inc write_block_params::data_buffer+1 ; next $200 of data
inc write_block_params::data_buffer+1
jsr WriteBlockAndZero
;; --------------------------------------------------
;; Volume directory key block
copy16 #block_buffer, write_block_params::data_buffer
copy8 #3, block_buffer+2 ; block 2, points at 3
ldy vol_name_buf ; volume name
tya
ora #ST_VOLUME_DIRECTORY << 4
sta block_buffer + VolumeDirectoryHeader::storage_type_name_length
DO
copy8 vol_name_buf,y, block_buffer + VolumeDirectoryHeader::file_name - 1,y
dey
WHILE_NOT_ZERO
ldy #kNumKeyBlockHeaderBytes-1 ; other header bytes
DO
copy8 key_block_header_bytes,y, block_buffer+kKeyBlockHeaderOffset,y
dey
WHILE_POS
MLI_CALL GET_TIME ; Apply timestamp
ldy #3
DO
copy8 DATELO,y, block_buffer + VolumeDirectoryHeader::creation_date,y
dey
WHILE_POS
copy16 case_bits, block_buffer + VolumeDirectoryHeader::case_bits
jsr WriteBlockAndZero
;; Subsequent volume directory blocks (4 total)
copy8 #2, block_buffer ; block 3, points at 2 and 4
copy8 #4, block_buffer+2
jsr WriteBlockAndZero
copy8 #3, block_buffer ; block 4, points at 3 and 5
copy8 #5, block_buffer+2
jsr WriteBlockAndZero
copy8 #4, block_buffer ; block 4, points back at 4
jsr WriteBlockAndZero
;; --------------------------------------------------
;; Bitmap blocks
;; Do a bunch of preliminary math to make building the volume bitmap easier
lda total_blocks ; A lot of the math is affected by off-by-one problems that
bne :+ ; vanish if you decrease the blocks by one (go from "how many"
dec total_blocks+1 ; to "last block number")
: dec total_blocks
lda total_blocks ; Take the remainder of the last block number modulo 8
and #$07
tax ; Convert that remainder to a bitmask of "n+1" set high-endian bits
lda bitmask,x ; using a lookup table and store it for later
sta last_byte ; This value will go at the end of the bitmap
lsr16 total_blocks ; Divide the last block number by 8 in-place
lsr16 total_blocks ; This will become the in-block offset to the last
lsr16 total_blocks ; byte shortly
lda total_blocks+1 ; Divide the last block number again by 512 (high byte/2) in-register to get
lsr a ; the base number of bitmap blocks needed minus 1
clc ; Finally, add 6 to account for the 6 blocks used by the boot blocks (2)
adc #6 ; and volume directory (4) to get the block number of the last VBM block
sta lastblock ; This final result should ONLY fall in the range of 6-21
lda total_blocks+1 ; Mask off the last block's "partial" byte count - this is now the offset to the
and #$01 ; last byte in the last VBM block. All other blocks get filled with 512 $FF's
sta total_blocks+1
;; Main loop to build the volume bitmap
DO
jsr _BuildBlock ; Build a bitmap for the current block
lda write_block_params::block_num+1 ; Are we at a block >255?
bne fail ; Then something's gone horribly wrong and we need to stop
lda write_block_params::block_num
cmp #6 ; Are we anywhere other than block 6?
bne gowrite ; Then go ahead and write the bitmap block as-is
;; Block 6 - Set up the volume bitmap to protect the blocks at the beginning of the volume
copy8 #$01, block_buffer ; Mark blocks 0-6 in use
lda lastblock ; What's the last block we need to protect?
cmp #7
bcc gowrite ; If it's less than 7, default to always protecting 0-6
copy8 #$00, block_buffer ; Otherwise (>=7) mark blocks 0-7 as "in use"
lda lastblock ; and check again
IF_A_LT #15 ; Is it 15 or more? Skip ahead.
and #$07 ; Otherwise (7-14) take the low three bits
tax
lda freemask,x ; convert them to the correct VBM value using a lookup table
sta block_buffer+1 ; put it in the bitmap
bcc gowrite ; and write the block
END_IF
copy8 #$00, block_buffer+1 ; (>=15) Mark blocks 8-15 as "in use"
lda lastblock ; Then finally
and #$07 ; take the low three bits
tax
lda freemask,x ; convert them to the correct VBM value using a lookup table
sta block_buffer+2 ; put it in the bitmap, and fall through to the write
;; Call the write/increment/zero routine, and loop back if we're not done
gowrite:
jsr WriteBlockAndZero
lda lastblock
WHILE_A_GE write_block_params::block_num
;; Success
lda #$00
sta $08
clc
rts
fail: sec
rts
unit_num:
.byte 0
;;; Values with "n+1" (1-8) high-endian bits set
bitmask:
.byte $80,$C0,$E0,$F0,$F8,$FC,$FE,$FF
;;; Special mask values for setting up block 6 /NOTE OFF-BY-ONE/
freemask:
.byte $7F,$3F,$1F,$0F,$07,$03,$01,$FF
;;; Contents of the last byte of the VBM
last_byte:
.byte $00
;;; Block number of the last VBM block
lastblock:
.byte 6
;;; ============================================================
;;; Build a single block of the VBM. These blocks are all filled with
;;; 512 $FF values, except for the last block in the entire VBM, which
;;; gets cleared to $00's following the final byte position.
.proc _BuildBlock
ldy #$00
lda #$FF
DO
sta block_buffer,y ; Fill this entire block
sta block_buffer+$100,y ; with $FF bytes
iny
WHILE_NOT_ZERO
lda write_block_params::block_num
cmp lastblock ; Is this the last block?
bne builddone ; No, then just use the full block of $FF's
ldy total_blocks ; Get the offset to the last byte that needs to be updated
lda total_blocks+1
bne secondhalf ; Is it in the first $100 or the second $100?
lda last_byte ; Updating the first half
sta block_buffer,y ; Put the last byte in the right location
lda #$00
iny
beq zerosecond ; Was that the end of the first half?
zerofirst:
sta block_buffer,y ; Clear the remainder of the first half
iny
bne zerofirst
beq zerosecond ; Then go clear ALL of the second half
secondhalf:
lda last_byte ; Updating the second half
sta block_buffer+$100,y ; Put the last byte in the right location
lda #$00
iny
beq builddone ; Was that the end of the second half?
zerosecond:
sta block_buffer+$100,y ; Clear the remainder of the second half
iny
bne zerosecond
builddone:
rts ; And we're done
.endproc ; _BuildBlock
.endproc ; WriteHeaderBlocks
;;; ============================================================
pop_and_fail:
pla
pla
fail2:
sec
rts
;;; ============================================================
.proc WriteBlockAndZero
MLI_CALL WRITE_BLOCK, write_block_params
bcs pop_and_fail
jsr zero_buffers
inc write_block_params::block_num
rts
zero_buffers:
ldy #0
tya
DO
sta block_buffer,y
sta block_buffer+$100,y
dey
WHILE_NOT_ZERO
rts
.endproc ; WriteBlockAndZero
;;; ============================================================
;;; Part of volume directory block at offset $22
;;; $22 = access $C3
;;; $23 = entry_length $27
;;; $24 = entries_per_block $0D
;;; $25 = file_count 0
;;; $27 = bit_map_pointer 6
;;; $29 = total_blocks
kNumKeyBlockHeaderBytes = .sizeof(VolumeDirectoryHeader) - VolumeDirectoryHeader::access
kKeyBlockHeaderOffset = VolumeDirectoryHeader::access
key_block_header_bytes:
.byte $C3,$27,$0D
.word 0
.word 6
total_blocks:
.word kDefaultFloppyBlocks
ASSERT_TABLE_SIZE key_block_header_bytes, kNumKeyBlockHeaderBytes
vol_name_buf:
.res 16,0
case_bits:
.word 0
;;; ============================================================
;;; ProDOS Loader
;;; ============================================================
prodos_loader_blocks:
.incbin "../inc/pdload.dat"
.assert * - prodos_loader_blocks = $400, error, "Bad data"
;;; ============================================================
;;; Note that code from around this point is overwritten when
;;; `block_buffer` is used, so only place routines not used after
;;; writing starts are placed here. The overlay will be reloaded
;;; for subsequent format/erase operations.
;;; ============================================================
;;; Get a volume name for a non-ProDOS disk given a unit number.
;;; Input: A = unit number
;;; Output: `ovl_string_buf` is populated.
.proc GetNonProDOSVolName
kPascalSig1 = $E0
kPascalSig2a = $70
kPascalSig2b = $60
kDOS33Sig1 = $A5
kDOS33Sig2 = $27
;; Read block 0
sta read_block_params::unit_num
copy16 #0, read_block_params::block_num
MLI_CALL READ_BLOCK, read_block_params
IF_CC
lda read_buffer + 1
IF_A_NE #kPascalSig1 ; DOS 3.3?
jmp maybe_dos ; Maybe...
END_IF
lda read_buffer + 2
cmp #kPascalSig2a
beq pascal
cmp #kPascalSig2b
beq pascal
FALL_THROUGH_TO unknown
END_IF
;; Unknown, just use slot and drive
unknown:
lda read_block_params::unit_num
jsr _GetSlotChar
sta the_disk_in_slot_label + kTheDiskInSlotSlotCharOffset
lda read_block_params::unit_num
jsr _GetDriveChar
sta the_disk_in_slot_label + kTheDiskInSlotDriveCharOffset
ldx the_disk_in_slot_label
DO
copy8 the_disk_in_slot_label,x, ovl_string_buf,x
dex
WHILE_POS
rts
;; Pascal
pascal: param_call pascal_disk, ovl_string_buf
jmp EnquoteStringBuf
;; Maybe DOS 3.3, not sure yet...
maybe_dos:
cmp #kDOS33Sig1
bne unknown
lda read_buffer + 2
cmp #kDOS33Sig2
bne unknown
;; DOS 3.3, use slot and drive
lda read_block_params::unit_num
jsr _GetSlotChar
sta the_dos_33_disk_label + kTheDos33DiskSlotCharOffset
lda read_block_params::unit_num
jsr _GetDriveChar
sta the_dos_33_disk_label + kTheDos33DiskDriveCharOffset
COPY_STRING the_dos_33_disk_label, ovl_string_buf
rts
.proc _GetSlotChar
and #$70
lsr a
lsr a
lsr a
lsr a
clc
adc #'0'
rts
.endproc ; _GetSlotChar
.proc _GetDriveChar
and #$80
asl a
rol a
adc #'1'
rts
.endproc ; _GetDriveChar
;;; Handle Pascal disk - name suffixed with ':'
pascal_disk:
copy16 #kVolumeDirKeyBlock, read_block_params::block_num
MLI_CALL READ_BLOCK, read_block_params
IF_CS
;; Pascal disk, empty name - use " :" (weird, but okay?)
copy8 #2, ovl_string_buf
copy8 #' ', ovl_string_buf+1
copy8 #':', ovl_string_buf+2
rts
END_IF
;; Pascal disk, use name
lda read_buffer + 6
tax
DO
copy8 read_buffer + 6,x, ovl_string_buf,x
dex
WHILE_POS
inc ovl_string_buf
ldx ovl_string_buf
copy8 #':', ovl_string_buf,x
rts
.endproc ; GetNonProDOSVolName
;;; ============================================================
;;; Get a volume name, for ProDOS or non-ProDOS disk.
;;; Input: A = unit number
;;; Output: `ovl_string_buf` is populated
.proc GetVolName
sta on_line_params::unit_num
MLI_CALL ON_LINE, on_line_params
bcs non_pro
lda on_line_buffer
and #NAME_LENGTH_MASK
beq non_pro
param_call AdjustOnLineEntryCase, on_line_buffer
ldx on_line_buffer
DO
copy8 on_line_buffer,x, ovl_string_buf,x
dex
WHILE_POS
jmp EnquoteStringBuf
non_pro:
lda on_line_params::unit_num
jmp GetNonProDOSVolName
.endproc ; GetVolName
;;; ============================================================
.proc EnquoteStringBuf
ldx ovl_string_buf
DO
copy8 ovl_string_buf,x, ovl_string_buf+1,x
dex
WHILE_NOT_ZERO
ldx ovl_string_buf
inx
inx
lda #'"' ; " (balance quotes for some text editors)
sta ovl_string_buf,x
sta ovl_string_buf+1
stx ovl_string_buf
rts
.endproc ; EnquoteStringBuf
;;; ============================================================
.endscope ; FormatEraseOverlay
ENDSEG OverlayFormatErase
|
a2stuff/a2d
| 1,621
|
src/desktop/ovl_file_copy.s
|
;;; ============================================================
;;; Overlay for File Copy
;;;
;;; Compiled as part of desktop.s
;;; ============================================================
BEGINSEG OverlayFileCopy
.scope FileCopyOverlay
.proc Run
tsx
stx saved_stack
jsr file_dialog::Init
SET_BIT7_FLAG file_dialog::only_show_dirs_flag
copy8 #file_dialog::kSelectionOptionalUnlessRoot, file_dialog::selection_requirement_flags
param_call file_dialog::OpenWindow, label_copy_selection
jsr file_dialog::InitPathWithDefaultDevice
jsr file_dialog::UpdateListFromPath
COPY_BYTES file_dialog::kJumpTableSize, jt_callbacks, file_dialog::jump_table
jmp file_dialog::EventLoop
.endproc ; Run
saved_stack:
.byte 0
jt_callbacks:
jmp HandleOK
jmp HandleCancel
.assert * - jt_callbacks = file_dialog::kJumpTableSize, error, "Table size error"
;;; ============================================================
.proc HandleOK
param_call file_dialog::GetPath, path_buf0
jsr file_dialog::CloseWindow
copy16 #path_buf0, $6
ldx saved_stack
txs
return #$00
.endproc ; HandleOK
;;; ============================================================
.proc HandleCancel
jsr file_dialog::CloseWindow
ldx saved_stack
txs
return #$FF
.endproc ; HandleCancel
;;; ============================================================
.endscope ; FileCopyOverlay
ENDSEG OverlayFileCopy
|
a2stuff/a2d
| 29,716
|
src/desktop/ovl_selector_pick.s
|
;;; ============================================================
;;; Overlay for Selector Picker
;;;
;;; Compiled as part of desktop.s
;;; ============================================================
;;; See docs/Selector_List_Format.md for file format
BEGINSEG OverlayShortcutPick
.scope SelectorPickOverlay
MLIEntry := main::MLIRelayImpl
MGTKEntry := MGTKRelayImpl
BTKEntry := BTKRelayImpl
OPTKEntry := OPTKRelayImpl
io_buf := $0800
selector_list := SELECTOR_FILE_BUF
Exec:
sta selector_action
ldx #$FF
stx clean_flag ; set "clean"
cmp #SelectorAction::add
beq DoAdd
jmp Init
.proc Exit
pha
lda clean_flag
bpl check_about_saving ; dirty, check about saving
finish: pla
ret: rts
check_about_saving:
lda selector_list + kSelectorListNumPrimaryRunListOffset
clc
adc selector_list + kSelectorListNumSecondaryRunListOffset
sta num_selector_list_items
jsr main::GetCopiedToRAMCardFlag
cmp #$80
bne finish
jsr WriteFileToOriginalPrefix
pla
rts
.endproc ; Exit
;;; ============================================================
DoAdd: ldx #kRunListPrimary
lda selector_menu
IF_A_GE #kSelectorMenuFixedItems + 8
inx
END_IF
lda #$00
sta text_input_buf ; clear name, but leave path alone
ldy #kCopyNever | $80 ; high bit set = Add
;; A = (obsolete, was dialog type)
;; Y = is_add_flag | copy_when
;; X = which_run_list
jsr ::SelectorEditOverlay::Run
pha
txa
pha
tya
pha
lda #kDynamicRoutineRestoreFD
jsr main::RestoreDynamicRoutine
jsr main::ClearUpdates ; Add File Dialog close
pla
tay
pla
tax
pla
bne Exit
inc clean_flag ; mark as "dirty"
stx which_run_list
sty copy_when
lda #$00
: dey
beq :+
sec
ror a
jmp :-
:
sta copy_when
jsr ReadFile
IF_NEG
jmp Exit::ret
END_IF
copy16 selector_list, num_primary_run_list_entries
lda which_run_list
IF_A_EQ #kRunListPrimary
lda num_primary_run_list_entries
cmp #kSelectorListNumPrimaryRunListEntries
beq ShowFullAlert
ldy copy_when ; Flags
lda num_primary_run_list_entries
inc selector_list + kSelectorListNumPrimaryRunListOffset
jsr AssignEntryData
jsr WriteFile
IF_NEG
jmp Exit::ret
END_IF
jmp Exit
END_IF
lda num_secondary_run_list_entries
IF_A_NE #kSelectorListNumSecondaryRunListEntries
ldy copy_when ; Flags
lda num_secondary_run_list_entries
clc
adc #kSelectorListNumPrimaryRunListEntries
jsr AssignSecondaryRunListEntryData
inc selector_list + kSelectorListNumSecondaryRunListOffset
jsr WriteFile
IF_NEG
jmp Exit::ret
END_IF
jmp Exit
END_IF
ShowFullAlert:
param_call ShowAlertParams, AlertButtonOptions::OK, aux::str_warning_selector_list_full
dec clean_flag ; reset to "clean"
jmp Exit::ret
which_run_list:
.byte 0
copy_when:
.byte 0
;;; ============================================================
.proc Init
lda #$00
sta num_primary_run_list_entries
sta num_secondary_run_list_entries
copy8 #$FF, shortcut_picker_record::selected_index
copy8 #BTK::kButtonStateDisabled, entry_picker_ok_button::state
jsr OpenWindow
jsr ReadFile
IF_NS
jmp DoCancel
END_IF
copy8 selector_list + kSelectorListNumPrimaryRunListOffset, num_primary_run_list_entries
copy8 selector_list + kSelectorListNumSecondaryRunListOffset, num_secondary_run_list_entries
jsr PopulateEntriesFlagTable
OPTK_CALL OPTK::Draw, shortcut_picker_params
FALL_THROUGH_TO dialog_loop
.endproc ; Init
dialog_loop:
jsr EventLoop
bmi dialog_loop ; N set = nothing selected, re-enter loop
jne DoCancel ; Z set = OK selected
;; Which action are we?
lda shortcut_picker_record::selected_index
bmi dialog_loop
lda selector_action
cmp #SelectorAction::edit
jeq DoEdit
cmp #SelectorAction::delete
beq DoDelete
cmp #SelectorAction::run
bne dialog_loop
jmp DoRun
;;; ============================================================
.proc DoDelete
jsr main::SetCursorWatch
lda shortcut_picker_record::selected_index
jsr RemoveEntry
IF_ZS ; Z set on success
inc clean_flag ; mark as "dirty"
END_IF
jsr main::SetCursorPointer
jmp DoCancel
.endproc ; DoDelete
;;; ============================================================
.proc DoEdit
jsr CloseWindow
lda shortcut_picker_record::selected_index
jsr GetFileEntryAddr
stax $06
param_call main::CopyPtr1ToBuf, text_input_buf
ldy #kSelectorEntryFlagsOffset
lda ($06),y
sta flags
lda shortcut_picker_record::selected_index
jsr GetFilePathAddr
jsr main::CopyToBuf0
ldx #kRunListPrimary
lda shortcut_picker_record::selected_index
cmp #kSelectorListNumPrimaryRunListEntries
IF_GE
inx ; #kRunListSecondary
END_IF
;; Map to `kSelectorEntryCopyOnBoot` to `kCopyOnBoot` etc
.define swizzle(n) (n >> 7) + 1 + (n > 127)
.assert swizzle kSelectorEntryCopyOnBoot = kCopyOnBoot, error, "const mismatch"
.assert swizzle kSelectorEntryCopyOnUse = kCopyOnUse, error, "const mismatch"
.assert swizzle kSelectorEntryCopyNever = kCopyNever, error, "const mismatch"
clc
lda flags
rol a
rol a
adc #1
tay
;; A = (obsolete, was dialog type)
;; Y = is_add_flag | copy_when
;; X = which_run_list
jsr ::SelectorEditOverlay::Run
pha
txa
pha
tya
pha
lda #kDynamicRoutineRestoreFD
jsr main::RestoreDynamicRoutine
jsr main::ClearUpdates ; Edit File Dialog close
pla
tay
pla
tax
pla
RTS_IF_NOT_ZERO
inc clean_flag ; mark as "dirty"
stx which_run_list
;; Map to `kCopyOnBoot` to `kSelectorEntryCopyOnBoot` etc
lda copy_when_conversion_table-1,y
sta copy_when
jsr ReadFile
IF_NS
jmp CloseWindow
END_IF
lda shortcut_picker_record::selected_index
IF_A_GE #kSelectorListNumPrimaryRunListEntries
;; Was on secondary run list - is it still?
lda which_run_list
cmp #kRunListSecondary
beq reuse_same_index
lda num_primary_run_list_entries
IF_A_EQ #kSelectorListNumPrimaryRunListEntries
jmp ShowFullAlert
END_IF
lda shortcut_picker_record::selected_index
jsr RemoveEntry
IF_ZC
jmp CloseWindow
END_IF
;; Compute new index
ldx num_primary_run_list_entries
inc num_primary_run_list_entries
inc selector_list + kSelectorListNumPrimaryRunListOffset
txa
ELSE
;; Was on primary run list - is it still?
lda which_run_list
cmp #kRunListPrimary
beq reuse_same_index
lda num_secondary_run_list_entries
IF_A_EQ #kSelectorListNumSecondaryRunListEntries
jmp ShowFullAlert
END_IF
lda shortcut_picker_record::selected_index
jsr RemoveEntry
IF_ZC
jmp CloseWindow
END_IF
;; Compute new index
ldx num_secondary_run_list_entries
inc num_secondary_run_list_entries
inc selector_list + kSelectorListNumSecondaryRunListOffset
lda num_secondary_run_list_entries
clc
adc #$07
jmp :+
reuse_same_index:
lda shortcut_picker_record::selected_index
:
END_IF
ldy copy_when
jsr AssignEntryData
jsr WriteFile
IF_ZC
jmp CloseWindow
END_IF
jsr main::SetCursorPointer
jmp Exit
flags: .byte 0
;; Index is kCopyXXX-1, value is kSelectorEntryCopyXXX
copy_when_conversion_table:
.byte kSelectorEntryCopyOnBoot
.byte kSelectorEntryCopyOnUse
.byte kSelectorEntryCopyNever
.endproc ; DoEdit
;;; ============================================================
.proc DoRun
jsr CloseWindow
jsr main::ClearUpdates ; Run dialog OK
lda shortcut_picker_record::selected_index
rts
.endproc ; DoRun
;;; ============================================================
;;; Cancel from Edit, Delete, or Run
;;; Also OK from Delete (since that closes immediately)
.proc DoCancel
lda selector_action
IF_A_EQ #SelectorAction::edit
lda #kDynamicRoutineRestoreFD
jsr main::RestoreDynamicRoutine
END_IF
jsr CloseWindow
jsr main::ClearUpdates
lda #$FF
jmp Exit
.endproc ; DoCancel
;;; ============================================================
.proc CloseWindow
MGTK_CALL MGTK::CloseWindow, winfo_entry_picker
rts
.endproc ; CloseWindow
;;; ============================================================
num_primary_run_list_entries:
.byte 0
num_secondary_run_list_entries:
.byte 0
selector_action:
.byte 0
clean_flag: ; high bit set if "clean", cleared if "dirty"
.byte 0 ; and should save to original prefix
;;; ============================================================
.proc OpenWindow
MGTK_CALL MGTK::OpenWindow, winfo_entry_picker
lda #winfo_entry_picker::kWindowId
jsr main::SafeSetPortFromWindowId
jsr main::SetPenModeNotCopy
MGTK_CALL MGTK::SetPenSize, pensize_frame
MGTK_CALL MGTK::FrameRect, entry_picker_frame_rect
MGTK_CALL MGTK::SetPenSize, pensize_normal
MGTK_CALL MGTK::MoveTo, entry_picker_line1_start
MGTK_CALL MGTK::LineTo, entry_picker_line1_end
MGTK_CALL MGTK::MoveTo, entry_picker_line2_start
MGTK_CALL MGTK::LineTo, entry_picker_line2_end
BTK_CALL BTK::Draw, entry_picker_ok_button
BTK_CALL BTK::Draw, entry_picker_cancel_button
lda selector_action
IF_A_EQ #SelectorAction::edit
param_jump DrawTitleCentered, label_edit
END_IF
IF_A_EQ #SelectorAction::delete
param_jump DrawTitleCentered, label_del
END_IF
param_jump DrawTitleCentered, label_run
.endproc ; OpenWindow
;;; ============================================================
.proc DrawTitleCentered
text_params := $6
text_addr := text_params + 0
text_length := text_params + 2
text_width := text_params + 3
stax text_addr ; input is length-prefixed string
ldy #0
lda (text_addr),y
sta text_length
inc16 text_addr ; point past length byte
MGTK_CALL MGTK::TextWidth, text_params
sub16 #winfo_entry_picker::kWidth, text_width, pos_dialog_title::xcoord
lsr16 pos_dialog_title::xcoord ; /= 2
MGTK_CALL MGTK::MoveTo, pos_dialog_title
MGTK_CALL MGTK::DrawText, text_params
rts
.endproc ; DrawTitleCentered
;;; ============================================================
;;; When returning from event loop:
;;; N = nothing selected, re-enter loop
;;; Z = OK selected
;;; Otherwise: Cancel selected
.proc EventLoop
jsr SystemTask
jsr main::GetEvent
cmp #MGTK::EventKind::button_down
jeq handle_button
cmp #MGTK::EventKind::key_down
bne EventLoop
jmp HandleKey
handle_button:
MGTK_CALL MGTK::FindWindow, findwindow_params
lda findwindow_params::which_area
IF_ZERO
return #$FF
END_IF
IF_A_NE #MGTK::Area::content
return #$FF
END_IF
lda findwindow_params::window_id
IF_A_NE winfo_entry_picker
return #$FF
END_IF
lda #winfo_entry_picker::kWindowId
sta screentowindow_params::window_id
MGTK_CALL MGTK::ScreenToWindow, screentowindow_params
MGTK_CALL MGTK::MoveTo, screentowindow_params::window
MGTK_CALL MGTK::InRect, entry_picker_ok_button::rect
IF_NOT_ZERO
BTK_CALL BTK::Track, entry_picker_ok_button
IF_NC
lda #$00 ; OK selected
END_IF
rts
END_IF
MGTK_CALL MGTK::InRect, entry_picker_cancel_button::rect
IF_NOT_ZERO
BTK_CALL BTK::Track, entry_picker_cancel_button
IF_NC
lda #$01 ; cancel selected
END_IF
rts
END_IF
COPY_STRUCT screentowindow_params::window, shortcut_picker_params::coords
OPTK_CALL OPTK::Click, shortcut_picker_params
IF_NC
jsr DetectDoubleClick
IF_NC
pha
BTK_CALL BTK::Flash, entry_picker_ok_button
pla
END_IF
END_IF
rts
.endproc ; EventLoop
;;; ============================================================
;;; Key down handler
.proc HandleKey
lda event_params::modifiers
IF_A_EQ #MGTK::event_modifier_solid_apple
return #$FF
END_IF
lda event_params::key
cmp #CHAR_RETURN
jeq HandleKeyReturn
cmp #CHAR_ESCAPE
jeq HandleKeyEscape
lda num_primary_run_list_entries
ora num_secondary_run_list_entries
IF_NE
lda event_params::key
IF_A_EQ_ONE_OF #CHAR_UP, #CHAR_DOWN, #CHAR_LEFT, #CHAR_RIGHT
sta shortcut_picker_params::key
OPTK_CALL OPTK::Key, shortcut_picker_params
END_IF
END_IF
return #$FF
.endproc ; HandleKey
;;; ============================================================
.proc HandleKeyReturn
BTK_CALL BTK::Flash, entry_picker_ok_button
IF_NS
return #$FF ; ignore
END_IF
return #0
.endproc ; HandleKeyReturn
;;; ============================================================
.proc HandleKeyEscape
BTK_CALL BTK::Flash, entry_picker_cancel_button
return #1
.endproc ; HandleKeyEscape
;;; ============================================================
.proc UpdateOKButton
lda #BTK::kButtonStateNormal
bit shortcut_picker_record::selected_index
IF_NS
lda #BTK::kButtonStateDisabled
END_IF
IF_A_NE entry_picker_ok_button::state
sta entry_picker_ok_button::state
BTK_CALL BTK::Hilite, entry_picker_ok_button
END_IF
rts
.endproc ; UpdateOKButton
;;; ============================================================
.proc PopulateEntriesFlagTable
ldx #kSelectorListNumEntries - 1
lda #$FF
DO
sta entries_flag_table,x
dex
WHILE_POS
ldx #0
DO
BREAK_IF_X_EQ num_primary_run_list_entries
txa
sta entries_flag_table,x
inx
WHILE_NOT_ZERO
ldx #0
DO
BREAK_IF_X_EQ num_secondary_run_list_entries
txa
clc
adc #8
sta entries_flag_table+8,x
inx
WHILE_NOT_ZERO
rts
.endproc ; PopulateEntriesFlagTable
;;; Table for 24 entries; index (0...23) if in use, $FF if empty
entries_flag_table:
.res ::kSelectorListNumEntries, 0
;;; ============================================================
;;; Assigns name, flags, and path to an entry in the file buffer
;;; and (if it's in the primary run list) also updates the
;;; resource data (used for menus, etc).
;;; Inputs: A=entry index, Y=new flags
;;; `text_input_buf` is name, `path_buf0` is path
.proc AssignEntryData
cmp #8
jcs AssignSecondaryRunListEntryData
sta index
tya ; flags
pha
ptr_file = $06 ; pointer into file buffer
;; Assign name in `text_input_buf` to file
lda index
jsr GetFileEntryAddr
stax ptr_file
ldy text_input_buf
DO
copy8 text_input_buf,y, (ptr_file),y
dey
WHILE_POS
;; Assign flags to file
ldy #kSelectorEntryFlagsOffset
pla
sta (ptr_file),y
;; Assign path in `path_buf0` to file
lda index
jsr GetFilePathAddr
stax ptr_file
ldy path_buf0
DO
copy8 path_buf0,y, (ptr_file),y
dey
WHILE_POS
jsr UpdateMenuResources
rts
index: .byte 0
.endproc ; AssignEntryData
;;; ============================================================
;;; Assigns name, flags, and path to an entry in the file buffer.
;;; Inputs: A=entry index, Y=new flags
;;; `text_input_buf` is name, `path_buf0` is path
.proc AssignSecondaryRunListEntryData
ptr := $06
sta index
tya ; Y = entry flags
pha
;; Compute entry address
lda index
jsr GetFileEntryAddr
stax ptr
;; Assign name
ldy text_input_buf
DO
copy8 text_input_buf,y, (ptr),y
dey
WHILE_POS
;; Assign flags
ldy #kSelectorEntryFlagsOffset
pla
sta (ptr),y
;; Assign path
lda index
jsr GetFilePathAddr
stax ptr
ldy path_buf0
DO
copy8 path_buf0,y, (ptr),y
dey
WHILE_POS
rts
index: .byte 0
.endproc ; AssignSecondaryRunListEntryData
;;; ============================================================
;;; Removes the specified entry, shifting later entries down as
;;; needed. Writes the file when done. Handles both the file
;;; buffer and resource data (used for menus, etc.)
;;; Inputs: Entry in A
.proc RemoveEntry
ptr1 := $06
ptr2 := $08
sta index
cmp #8
bcc run_list
jmp secondary_run_list
;; Primary run list
run_list:
.scope
tax
inx
cpx num_primary_run_list_entries
bne loop
finish:
dec selector_list + kSelectorListNumPrimaryRunListOffset
dec num_primary_run_list_entries
jsr UpdateMenuResources
jmp WriteFile
loop: lda index
cmp num_primary_run_list_entries
beq finish
jsr MoveEntryDown
inc index
jmp loop
.endscope
;; --------------------------------------------------
secondary_run_list:
.scope
sec
sbc #ptr1+1
cmp num_secondary_run_list_entries
bne loop
dec selector_list + kSelectorListNumSecondaryRunListOffset
dec num_secondary_run_list_entries
jmp WriteFile
loop: lda index
sec
sbc #ptr2
IF_A_EQ num_secondary_run_list_entries
dec selector_list + kSelectorListNumSecondaryRunListOffset
dec num_secondary_run_list_entries
jmp WriteFile
END_IF
lda index
jsr MoveEntryDown
inc index
jmp loop
.endscope
index: .byte 0
;;; Move an entry (in the file buffer) down by one.
;;; A=entry index
.proc MoveEntryDown
;; Copy entry (in file buffer) down by one
jsr GetFileEntryAddr
stax ptr1
add16 ptr1, #kSelectorListNameLength, ptr2
ldy #0
lda (ptr2),y
tay
DO
copy8 (ptr2),y, (ptr1),y
dey
WHILE_POS
;; And flags
ldy #kSelectorEntryFlagsOffset
lda (ptr2),y
sta (ptr1),y
;; Copy path (in file buffer) down by one
lda index
jsr GetFilePathAddr
stax ptr1
add16 ptr1, #kSelectorListPathLength, ptr2
ldy #0
lda (ptr2),y
tay
DO
copy8 (ptr2),y, (ptr1),y
dey
WHILE_POS
rts
.endproc ; MoveEntryDown
.endproc ; RemoveEntry
;;; ============================================================
;;; Update menu from the file data, following an add/edit/remove.
.proc UpdateMenuResources
ptr_file = $06 ; pointer into file buffer
ptr_res = $08 ; pointer into resource data
lda selector_list + kSelectorListNumPrimaryRunListOffset
sta index
loop: dec index
bmi finish
;; Name
lda index
jsr GetFileEntryAddr
stax ptr_file
lda index
jsr GetResourceEntryAddr
stax ptr_res
jsr _CopyString
;; Flags
ldy #kSelectorEntryFlagsOffset
lda (ptr_file),y
sta (ptr_res),y
;; Path
lda index
jsr GetFilePathAddr
stax ptr_file
lda index
jsr GetResourcePathAddr
stax ptr_res
jsr _CopyString
jmp loop
finish:
;; Menu size
lda selector_list + kSelectorListNumPrimaryRunListOffset
clc
adc #kSelectorMenuFixedItems
sta selector_menu
;; No separator if it is last
IF_A_EQ #kSelectorMenuFixedItems
dec selector_menu
END_IF
;; Re-initialize the menu so that new widths can be pre-computed.
;; That will un-hilite the Selector menu, so re-hilite it so
;; it un-hilites correctly when finally dismissed.
MGTK_CALL MGTK::SetMenu, aux::desktop_menu
jsr main::ToggleMenuHilite
jsr main::ShowClockForceUpdate
rts
;;; Copy the string at `ptr_file` to `ptr_res`.
.proc _CopyString
ldy #0
lda (ptr_file),y
tay
DO
copy8 (ptr_file),y, (ptr_res),y
dey
WHILE_POS
rts
.endproc ; _CopyString
index: .byte 0
.endproc ; UpdateMenuResources
;;; ============================================================
;;; Entry name address in the file buffer
;;; Input: A = Entry
;;; Output: A,X = Address
.proc GetFileEntryAddr
addr := selector_list + kSelectorListEntriesOffset
jsr main::ATimes16
clc
adc #<addr
tay
txa
adc #>addr
tax
tya
rts
.endproc ; GetFileEntryAddr
;;; ============================================================
;;; Path address in the file buffer
;;; Input: A = Entry
;;; Output: A,X = Address
.proc GetFilePathAddr
addr := selector_list + kSelectorListPathsOffset
jsr main::ATimes64
clc
adc #<addr
tay
txa
adc #>addr
tax
tya
rts
.endproc ; GetFilePathAddr
;;; ============================================================
;;; Entry name address in the resource block (used for menu items)
;;; Input: A = Entry
;;; Output: A,X = Address
.proc GetResourceEntryAddr
jsr main::ATimes16
clc
adc #<run_list_entries
tay
txa
adc #>run_list_entries
tax
tya
rts
.endproc ; GetResourceEntryAddr
;;; ============================================================
;;; Path address in the resource block (used for invoking)
;;; Input: A = Entry
;;; Output: A,X = Address
.proc GetResourcePathAddr
jsr main::ATimes64
clc
adc #<main::run_list_paths
tay
txa
adc #>main::run_list_paths
tax
tya
rts
.endproc ; GetResourcePathAddr
;;; ============================================================
;;; Write out SELECTOR.LIST file, using original prefix.
;;; Used if DeskTop was copied to RAMCard.
filename_buffer := $1C00
DEFINE_CREATE_PARAMS create_origpfx_params, filename_buffer, ACCESS_DEFAULT, $F1
DEFINE_OPEN_PARAMS open_origpfx_params, filename_buffer, io_buf
DEFINE_CREATE_PARAMS create_curpfx_params, filename, ACCESS_DEFAULT, $F1
DEFINE_OPEN_PARAMS open_curpfx_params, filename, io_buf
filename:
PASCAL_STRING kPathnameSelectorList
DEFINE_READWRITE_PARAMS read_params, selector_list, kSelectorListBufSize
DEFINE_READWRITE_PARAMS write_params, selector_list, kSelectorListBufSize
DEFINE_CLOSE_PARAMS close_params
.proc WriteFileToOriginalPrefix
param_call main::CopyDeskTopOriginalPrefix, filename_buffer
inc filename_buffer ; Append '/' separator
ldx filename_buffer
lda #'/'
sta filename_buffer,x
ldx #$00 ; Append filename
ldy filename_buffer
DO
inx
iny
copy8 filename,x, filename_buffer,y
WHILE_X_NE filename
sty filename_buffer
copy8 #0, second_try_flag
retry: MLI_CALL CREATE, create_origpfx_params
MLI_CALL OPEN, open_origpfx_params
bcc write
;; First time - ask if we should even try.
lda second_try_flag
IF_ZERO
inc second_try_flag
lda #kErrSaveChanges
jsr ShowAlert
cmp #kAlertResultOK
beq retry
bne cancel ; always
END_IF
;; Second time - prompt to insert.
lda #kErrInsertSystemDisk
jsr ShowAlert
cmp #kAlertResultOK
beq retry
cancel: rts
write: lda open_origpfx_params::ref_num
sta write_params::ref_num
sta close_params::ref_num
@retry: MLI_CALL WRITE, write_params
bcc close
jsr ShowAlert
ASSERT_EQUALS ::kAlertResultTryAgain, 0
beq @retry ; `kAlertResultTryAgain` = 0
close: MLI_CALL CLOSE, close_params
rts
second_try_flag: ; 0 or 1, updated with INC
.byte 0
.endproc ; WriteFileToOriginalPrefix
;;; ============================================================
;;; Read SELECTOR.LIST file (using current prefix)
.proc ReadFile
retry: MLI_CALL OPEN, open_curpfx_params
bcc read
cmp #ERR_FILE_NOT_FOUND
beq not_found
lda #kErrInsertSystemDisk
jsr ShowAlert
cmp #kAlertResultOK
beq retry
return #$FF ; failure
read: lda open_curpfx_params::ref_num
sta read_params::ref_num
sta close_params::ref_num
MLI_CALL READ, read_params
php
pha
MLI_CALL CLOSE, close_params
pla
plp
rts
not_found:
;; Clear buffer
ptr := $06
copy16 #selector_list, ptr
ldx #>kSelectorListBufSize ; number of pages
lda #0
DO
ldy #0
DO
sta (ptr),y
dey
WHILE_NOT_ZERO
inc ptr+1
dex
WHILE_NOT_ZERO
return #0
.endproc ; ReadFile
;;; ============================================================
;;; Write SELECTOR.LIST file (using current prefix)
.proc WriteFile
@retry:
MLI_CALL CREATE, create_curpfx_params
MLI_CALL OPEN, open_curpfx_params
bcc write
lda #kErrInsertSystemDisk
jsr ShowAlert
cmp #kAlertResultOK
beq @retry
return #$FF
write: lda open_curpfx_params::ref_num
sta write_params::ref_num
sta close_params::ref_num
@retry: MLI_CALL WRITE, write_params
bcc close
jsr ShowAlert
ASSERT_EQUALS ::kAlertResultTryAgain, 0
beq @retry ; `kAlertResultTryAgain` = 0
close: MLI_CALL CLOSE, close_params
rts
.endproc ; WriteFile
;;; ============================================================
.proc IsEntryCallback
tay
ldx entries_flag_table,y
rts
.endproc ; IsEntryCallback
.proc DrawEntryCallback
addr := selector_list + kSelectorListEntriesOffset
jsr main::ATimes16
clc
adc #<addr
pha
txa
adc #>addr
tax
pla
ptr1 := $06
stax ptr1
param_call main::CopyPtr1ToBuf, text_buffer2
param_jump main::DrawString, text_buffer2
.endproc ; DrawEntryCallback
.proc SelChangeCallback
jmp UpdateOKButton
.endproc ; SelChangeCallback
;;; ============================================================
.endscope ; SelectorPickOverlay
ENDSEG OverlayShortcutPick
|
a2stuff/a2d
| 23,538
|
src/desktop/auxmem.s
|
;;; ============================================================
;;; DeskTop - Aux Memory Segment
;;;
;;; Compiled as part of desktop.s
;;; ============================================================
;;; ============================================================
;;; Segment loaded into AUX $4000-$BFFF
;;; ============================================================
BEGINSEG SegmentDeskTopAux
.scope aux
;; Fixed location entry points
ASSERT_EQUALS *, ::MGTKAuxEntry, "entry point"
jmp MGTKEntry
ASSERT_EQUALS *, ::BTKAuxEntry, "entry point"
jmp aux::btk::BTKEntry
ASSERT_EQUALS *, ::LETKAuxEntry, "entry point"
jmp aux::letk::LETKEntry
ASSERT_EQUALS *, ::LBTKAuxEntry, "entry point"
jmp lbtk::LBTKEntry
ASSERT_EQUALS *, ::OPTKAuxEntry, "entry point"
jmp optk::OPTKEntry
;;; ============================================================
;;; MouseGraphics ToolKit - fixed location for DAs to reference
;;; ============================================================
MLIEntry := MLI ; TODO: this makes no sense - wrong bank!
MGTKEntry := *
.include "../mgtk/mgtk.s"
;;; ============================================================
;;; Default Font - fixed location for DAs to reference
;;; ============================================================
ASSERT_ADDRESS ::DEFAULT_FONT
.incbin .concat("../../out/System.", kBuildLang, ".font")
;;; ============================================================
;;; Other ToolKits - floating location (DAs have indirections)
;;; ============================================================
ReadSetting := ReadSettingFromAux
.include "../toolkits/icontk.s"
ITKEntry := icontk::ITKEntry
.include "../toolkits/letk.s"
.include "../toolkits/btk.s"
.include "../toolkits/lbtk.s"
.include "../toolkits/optk.s"
;;; ============================================================
;;; Resources
;;; ============================================================
;;; ============================================================
;;; Menus
label_apple:
PASCAL_STRING kGlyphSolidApple
label_file:
PASCAL_STRING res_string_menu_bar_item_file
label_edit:
PASCAL_STRING res_string_menu_bar_item_edit
label_view:
PASCAL_STRING res_string_menu_bar_item_view
label_special:
PASCAL_STRING res_string_menu_bar_item_special
label_startup:
PASCAL_STRING res_string_menu_bar_item_startup
label_selector:
PASCAL_STRING res_string_menu_bar_item_selector
label_new_folder:
PASCAL_STRING res_string_menu_item_new_folder
label_open:
PASCAL_STRING res_string_menu_item_open
label_close:
PASCAL_STRING res_string_menu_item_close
label_close_all:
PASCAL_STRING res_string_menu_item_close_all
label_delete_selection:
PASCAL_STRING res_string_menu_item_delete_selection
label_eject:
PASCAL_STRING res_string_menu_item_eject
label_quit:
PASCAL_STRING res_string_menu_item_quit
label_cut:
PASCAL_STRING res_string_menu_item_cut
label_copy:
PASCAL_STRING res_string_menu_item_copy
label_paste:
PASCAL_STRING res_string_menu_item_paste
label_clear:
PASCAL_STRING res_string_menu_item_clear
label_select_all:
PASCAL_STRING res_string_menu_item_select_all
label_by_icon:
PASCAL_STRING res_string_menu_item_by_icon
label_by_small_icon:
PASCAL_STRING res_string_menu_item_by_small_icon
label_by_name:
PASCAL_STRING res_string_menu_item_by_name
label_by_date:
PASCAL_STRING res_string_menu_item_by_date
label_by_size:
PASCAL_STRING res_string_menu_item_by_size
label_by_type:
PASCAL_STRING res_string_menu_item_by_type
label_check_all_drives:
PASCAL_STRING res_string_menu_item_check_all_drives
label_check_drive:
PASCAL_STRING res_string_menu_item_check_drive
label_format_disk:
PASCAL_STRING res_string_menu_item_format_disk
label_erase_disk:
PASCAL_STRING res_string_menu_item_erase_disk
label_disk_copy:
PASCAL_STRING res_string_menu_item_disk_copy
label_get_info:
PASCAL_STRING res_string_menu_item_get_info
label_rename_icon:
PASCAL_STRING res_string_menu_item_rename_icon
label_duplicate_icon:
PASCAL_STRING res_string_menu_item_duplicate
label_make_link:
PASCAL_STRING res_string_menu_item_make_link
label_show_link:
PASCAL_STRING res_string_menu_item_show_original
;; Menu bar
DEFINE_MENU_BAR desktop_menu, kMenuNumItems
@items: DEFINE_MENU_BAR_ITEM kMenuIdApple, label_apple, apple_menu
DEFINE_MENU_BAR_ITEM kMenuIdFile, label_file, file_menu
DEFINE_MENU_BAR_ITEM kMenuIdEdit, label_edit, edit_menu
DEFINE_MENU_BAR_ITEM kMenuIdView, label_view, view_menu
DEFINE_MENU_BAR_ITEM kMenuIdSpecial, label_special, special_menu
DEFINE_MENU_BAR_ITEM kMenuIdStartup, label_startup, startup_menu
DEFINE_MENU_BAR_ITEM kMenuIdSelector, label_selector, selector_menu
ASSERT_RECORD_TABLE_SIZE @items, ::kMenuNumItems, .sizeof(MGTK::MenuBarItem)
;; File menu
DEFINE_MENU file_menu, kMenuSizeFile
@items: DEFINE_MENU_ITEM label_new_folder, res_char_menu_item_new_folder_shortcut
DEFINE_MENU_ITEM label_open, res_char_menu_item_open_shortcut
DEFINE_MENU_ITEM label_close, res_char_shortcut_close
DEFINE_MENU_ITEM label_close_all
DEFINE_MENU_SEPARATOR
DEFINE_MENU_ITEM label_get_info, res_char_menu_item_get_info_shortcut
DEFINE_MENU_ITEM_NOMOD label_rename_icon, CHAR_RETURN, CHAR_RETURN
DEFINE_MENU_ITEM label_duplicate_icon, res_char_menu_item_duplicate_shortcut
DEFINE_MENU_SEPARATOR
DEFINE_MENU_ITEM label_copy_selection
DEFINE_MENU_ITEM label_delete_selection, $7F
DEFINE_MENU_SEPARATOR
DEFINE_MENU_ITEM label_quit, res_char_menu_item_quit_shortcut
ASSERT_RECORD_TABLE_SIZE @items, ::kMenuSizeFile, .sizeof(MGTK::MenuItem)
kMenuItemIdNewFolder = 1
kMenuItemIdOpen = 2
kMenuItemIdClose = 3
kMenuItemIdCloseAll = 4
;; --------------------
kMenuItemIdGetInfo = 6
kMenuItemIdRenameIcon = 7
kMenuItemIdDuplicate = 8
;; --------------------
kMenuItemIdCopySelection = 10
kMenuItemIdDeleteFile = 11
;; --------------------
kMenuItemIdQuit = 13
;; Edit menu
DEFINE_MENU edit_menu, kMenuSizeEdit
@items: DEFINE_MENU_ITEM label_cut, res_char_menu_item_cut_shortcut
DEFINE_MENU_ITEM label_copy, res_char_menu_item_copy_shortcut
DEFINE_MENU_ITEM label_paste, res_char_menu_item_paste_shortcut
DEFINE_MENU_ITEM label_clear
DEFINE_MENU_SEPARATOR
DEFINE_MENU_ITEM label_select_all, res_char_menu_item_select_all_shortcut
ASSERT_RECORD_TABLE_SIZE @items, ::kMenuSizeEdit, .sizeof(MGTK::MenuItem)
kMenuItemIdCut = 1
kMenuItemIdCopy = 2
kMenuItemIdPaste = 3
kMenuItemIdClear = 4
;; --------------------
kMenuItemIdSelectAll = 6
;; View menu
DEFINE_MENU view_menu, kMenuSizeView
@items: DEFINE_MENU_ITEM label_by_icon
DEFINE_MENU_ITEM label_by_small_icon
DEFINE_MENU_ITEM label_by_name
DEFINE_MENU_ITEM label_by_date
DEFINE_MENU_ITEM label_by_size
DEFINE_MENU_ITEM label_by_type
ASSERT_RECORD_TABLE_SIZE @items, ::kMenuSizeView, .sizeof(MGTK::MenuItem)
kMenuItemIdViewByIcon = 1
kMenuItemIdViewBySmallIcon = 2
kMenuItemIdViewByName = 3
kMenuItemIdViewByDate = 4
kMenuItemIdViewBySize = 5
kMenuItemIdViewByType = 6
;; Special menu
DEFINE_MENU special_menu, kMenuSizeSpecial
@items: DEFINE_MENU_ITEM label_check_all_drives
DEFINE_MENU_ITEM label_check_drive
DEFINE_MENU_ITEM label_eject, res_char_menu_item_eject_shortcut
DEFINE_MENU_SEPARATOR
DEFINE_MENU_ITEM label_format_disk
DEFINE_MENU_ITEM label_erase_disk
DEFINE_MENU_ITEM label_disk_copy
DEFINE_MENU_SEPARATOR
DEFINE_MENU_ITEM label_make_link
DEFINE_MENU_ITEM label_show_link
ASSERT_RECORD_TABLE_SIZE @items, ::kMenuSizeSpecial, .sizeof(MGTK::MenuItem)
kMenuItemIdCheckAll = 1
kMenuItemIdCheckDrive = 2
kMenuItemIdEject = 3
;; --------------------
kMenuItemIdFormatDisk = 5
kMenuItemIdEraseDisk = 6
kMenuItemIdDiskCopy = 7
;; --------------------
kMenuItemIdMakeLink = 9
kMenuItemIdShowOriginal = 10
;;; ============================================================
kDialogLabelHeight = kSystemFontHeight+1
kDialogTitleY = 17
kDialogLabelBaseY = 23
kDialogLabelRow1 = kDialogLabelBaseY + kDialogLabelHeight * 1
kDialogLabelRow2 = kDialogLabelBaseY + kDialogLabelHeight * 2
kDialogLabelRow3 = kDialogLabelBaseY + kDialogLabelHeight * 3
kDialogLabelRow4 = kDialogLabelBaseY + kDialogLabelHeight * 4
kDialogLabelRow5 = kDialogLabelBaseY + kDialogLabelHeight * 5
kDialogLabelRow6 = kDialogLabelBaseY + kDialogLabelHeight * 6
;;; ============================================================
;;; Prompt dialog resources
DEFINE_RECT_FRAME prompt_dialog_frame_rect, kPromptDialogWidth, kPromptDialogHeight
kPromptDialogInsetLeft = 8
kPromptDialogInsetTop = 20
kPromptDialogInsetRight = 8
kPromptDialogInsetBottom = 20
DEFINE_RECT clear_dialog_labels_rect, kPromptDialogInsetLeft, kPromptDialogInsetTop, kPromptDialogWidth-kPromptDialogInsetRight, kPromptDialogHeight-kPromptDialogInsetBottom
;;; ============================================================
;;; Progress dialog resources
kProgressDialogWidth = 400
kProgressDialogHeight = 58
kProgressDialogLabelRow0 = kProgressDialogLabelBaseY + aux::kDialogLabelHeight * 0
kProgressDialogLabelRow1 = kProgressDialogLabelBaseY + aux::kDialogLabelHeight * 1
kProgressDialogLabelRow2 = kProgressDialogLabelBaseY + aux::kDialogLabelHeight * 2
DEFINE_RECT_FRAME progress_dialog_frame_rect, kProgressDialogWidth, kProgressDialogHeight
DEFINE_POINT current_target_file_pos, kProgressDialogPathLeft, kProgressDialogLabelRow1
DEFINE_POINT current_dest_file_pos, kProgressDialogPathLeft, kProgressDialogLabelRow2
DEFINE_RECT current_target_file_rect, kProgressDialogPathLeft, kProgressDialogLabelRow0+1, kProgressDialogPathLeft + kProgressDialogPathWidth, kProgressDialogLabelRow1
DEFINE_RECT current_dest_file_rect, kProgressDialogPathLeft, kProgressDialogLabelRow1+1, kProgressDialogPathLeft + kProgressDialogPathWidth, kProgressDialogLabelRow2
;;; ============================================================
;;; "About" dialog resources
kAboutDialogWidth = 400
kAboutDialogHeight = 120
DEFINE_RECT_FRAME about_dialog_frame_rect, kAboutDialogWidth, kAboutDialogHeight
str_about1: PASCAL_STRING kDeskTopProductName
str_about2: PASCAL_STRING res_string_copyright_line1
str_about3: PASCAL_STRING res_string_copyright_line2
str_about4: PASCAL_STRING res_string_copyright_line3
str_about5: PASCAL_STRING res_string_about_text_line5
str_about6: PASCAL_STRING res_string_about_text_line6
str_about7: PASCAL_STRING res_string_about_text_line7
str_about8: PASCAL_STRING kBuildDate
str_about9: PASCAL_STRING .sprintf(res_string_noprod_version_format_long,::kDeskTopVersionMajor,::kDeskTopVersionMinor,kDeskTopVersionSuffix)
str_files_remaining:
PASCAL_STRING res_string_label_files_remaining
;; "Copy File" dialog strings
str_copy_copying:
PASCAL_STRING res_string_copy_label_status
str_copy_from:
PASCAL_STRING res_string_copy_label_from
str_copy_to:
PASCAL_STRING res_string_copy_label_to
;; "Move File" dialog strings
str_move_moving:
PASCAL_STRING res_string_move_label_status
str_exists_prompt:
PASCAL_STRING res_string_prompt_overwrite
str_large_copy_prompt:
PASCAL_STRING res_string_errmsg_too_large_to_copy
str_large_move_prompt:
PASCAL_STRING res_string_errmsg_too_large_to_move
str_no_overwrite_dir:
PASCAL_STRING res_string_errmsg_overwrite_dir
;; "Delete" dialog strings
str_delete_confirm_prefix:
PASCAL_STRING res_string_prompt_delete_confirm_prefix
str_delete_confirm_suffix:
PASCAL_STRING res_string_prompt_delete_confirm_suffix
str_delete_count:
PASCAL_STRING res_string_label_delete_count
str_file_colon:
PASCAL_STRING res_string_label_file
str_delete_locked_file:
PASCAL_STRING res_string_delete_prompt_locked_file
;; "Get Info" dialog strings
str_info_name:
PASCAL_STRING res_string_get_info_label_name
str_info_file_size:
PASCAL_STRING res_string_get_info_label_file_size
str_info_create:
PASCAL_STRING res_string_get_info_label_create
str_info_mod:
PASCAL_STRING res_string_get_info_label_mod
str_info_type:
PASCAL_STRING res_string_get_info_label_type
str_info_protected:
PASCAL_STRING res_string_get_info_label_protected
str_info_vol_size:
PASCAL_STRING res_string_get_info_label_vol_size
str_info_yes:
PASCAL_STRING res_string_get_info_label_yes
str_info_no:
PASCAL_STRING res_string_get_info_label_no
str_info_size_infix:
PASCAL_STRING res_string_get_info_label_size_infix
str_info_size_suffix:
PASCAL_STRING res_string_get_info_label_size_suffix
str_info_size_suffix_singular:
PASCAL_STRING res_string_get_info_label_size_suffix_singular
str_info_size_slash:
PASCAL_STRING res_string_get_info_label_size_slash
str_auxtype_prefix:
PASCAL_STRING res_string_auxtype_prefix
str_volume:
PASCAL_STRING res_string_volume
;; Format / Erase dialog strings
str_select_format:
PASCAL_STRING res_string_format_disk_label_select
str_location:
PASCAL_STRING res_string_format_disk_label_location
str_new_volume:
PASCAL_STRING res_string_format_disk_label_enter_name
str_formatting:
PASCAL_STRING res_string_format_disk_status_formatting
str_formatting_error:
PASCAL_STRING res_string_format_disk_error
str_select_erase:
PASCAL_STRING res_string_erase_disk_label_select
str_confirm_erase_prefix:
PASCAL_STRING res_string_erase_disk_prompt_erase_prefix
str_confirm_erase_suffix:
PASCAL_STRING res_string_erase_disk_prompt_erase_suffix
str_erasing:
PASCAL_STRING res_string_erase_disk_status_erasing
str_erasing_error:
PASCAL_STRING res_string_erase_disk_error
str_tip_prodos:
PASCAL_STRING res_string_tip_copy_prodos
;;; Miscellaneous alert strings
str_ramcard_full:
PASCAL_STRING res_string_download_error_ramcard_full
str_warning_selector_list_full:
PASCAL_STRING res_string_warning_selector_list_full
;;; The same string is used for both of these cases as the second case
;;; (a single directory with too many items) is very difficult to hit.
str_warning_too_many_files: ; alt: `res_string_warning_too_many_files`
str_warning_window_must_be_closed:
PASCAL_STRING res_string_warning_window_must_be_closed
str_warning_too_many_windows:
PASCAL_STRING res_string_warning_too_many_windows
str_alert_confirm_running:
PASCAL_STRING res_string_alert_confirm_running
str_alert_bad_replacement:
PASCAL_STRING res_string_alert_bad_replacement
str_alert_unsupported_type:
PASCAL_STRING res_string_alert_unsupported_type
str_alert_move_copy_into_self:
PASCAL_STRING res_string_alert_move_copy_into_self
str_alert_cannot_open:
PASCAL_STRING res_string_alert_cannot_open
str_alert_name_too_long:
PASCAL_STRING res_string_alert_name_too_long
str_alert_insert_source_disk:
PASCAL_STRING res_string_alert_insert_source_disk
str_alert_insert_destination:
PASCAL_STRING res_string_alert_insert_destination
str_alert_unreadable_format:
PASCAL_STRING res_string_alert_unreadable_format
;;; ============================================================
;;; Show Alert Dialog
;;; Call show_alert_dialog with prompt number A, options in X
;;; Options:
;;; 0 = use defaults for alert number; otherwise, look at top 2 bits
;;; %0....... e.g. $01 = OK
;;; %10...... e.g. $80 = Try Again, Cancel
;;; %11...... e.g. $C0 = OK, Cancel
;;; Return value:
;;; 0 = Try Again
;;; 1 = Cancel
;;; 2 = OK
.proc AlertByIdImpl
;;; --------------------------------------------------
;;; Messages
err_unknown: ; kErrUnknown
PASCAL_STRING res_string_errmsg_00
err_27: PASCAL_STRING res_string_errmsg_27
err_28: PASCAL_STRING res_string_errmsg_28
err_2B: PASCAL_STRING res_string_errmsg_2B
err_40: PASCAL_STRING res_string_errmsg_40
err_44: PASCAL_STRING res_string_errmsg_44
err_45: PASCAL_STRING res_string_errmsg_45
err_46: PASCAL_STRING res_string_errmsg_46
err_47: PASCAL_STRING res_string_errmsg_47
err_48: PASCAL_STRING res_string_errmsg_48
err_49: PASCAL_STRING res_string_errmsg_49
err_4E: PASCAL_STRING res_string_errmsg_4E
err_52: PASCAL_STRING res_string_errmsg_52
err_57: PASCAL_STRING res_string_errmsg_57
;;; Below are internal (not ProDOS MLI) error codes.
err_insert_system_disk: ; kErrInsertSystemDisk
PASCAL_STRING res_string_warning_insert_system_disk
err_save_changes: ; kErrSaveChanges
PASCAL_STRING res_string_warning_save_changes
err_no_windows: ; kErrNoWindowsOpen
PASCAL_STRING res_string_alert_no_windows_open
err_duplicate_volumes: ; kErrDuplicateVolName
PASCAL_STRING res_string_alert_duplicate_volume_names
err_no_basic_system: ; kErrBasicSysNotFound
PASCAL_STRING res_string_alert_basic_system_not_found
;; number of alert messages
kNumAlerts = 19
;; message number-to-index table
;; (look up by scan to determine index)
alert_table:
.byte kErrUnknown
;; ProDOS MLI error codes:
.byte ERR_IO_ERROR, ERR_DEVICE_NOT_CONNECTED, ERR_WRITE_PROTECTED
.byte ERR_INVALID_PATHNAME, ERR_PATH_NOT_FOUND, ERR_VOL_NOT_FOUND
.byte ERR_FILE_NOT_FOUND, ERR_DUPLICATE_FILENAME, ERR_OVERRUN_ERROR
.byte ERR_VOLUME_DIR_FULL, ERR_ACCESS_ERROR, ERR_NOT_PRODOS_VOLUME
.byte ERR_DUPLICATE_VOLUME
;; Internal error codes:
.byte kErrInsertSystemDisk
.byte kErrSaveChanges
.byte kErrNoWindowsOpen
.byte kErrDuplicateVolName
.byte kErrBasicSysNotFound
ASSERT_TABLE_SIZE alert_table, kNumAlerts
;; alert index to string address
message_table_low:
.byte <err_unknown
.byte <err_27,<err_28,<err_2B,<err_40,<err_44,<err_45,<err_46
.byte <err_47,<err_48,<err_49,<err_4E,<err_52,<err_57
.byte <err_insert_system_disk
.byte <err_save_changes
.byte <err_no_windows
.byte <err_duplicate_volumes
.byte <err_no_basic_system
ASSERT_TABLE_SIZE message_table_low, kNumAlerts
message_table_high:
.byte >err_unknown
.byte >err_27,>err_28,>err_2B,>err_40,>err_44,>err_45,>err_46
.byte >err_47,>err_48,>err_49,>err_4E,>err_52,>err_57
.byte >err_insert_system_disk
.byte >err_save_changes
.byte >err_no_windows
.byte >err_duplicate_volumes
.byte >err_no_basic_system
ASSERT_TABLE_SIZE message_table_high, kNumAlerts
alert_options_table:
.byte AlertButtonOptions::OK ; kErrUnknown
.byte AlertButtonOptions::OK ; ERR_IO_ERROR
.byte AlertButtonOptions::OK ; ERR_DEVICE_NOT_CONNECTED
.byte AlertButtonOptions::TryAgainCancel ; ERR_WRITE_PROTECTED
.byte AlertButtonOptions::OK ; ERR_INVALID_PATHNAME
.byte AlertButtonOptions::TryAgainCancel ; ERR_PATH_NOT_FOUND
.byte AlertButtonOptions::OK ; ERR_VOL_NOT_FOUND
.byte AlertButtonOptions::OK ; ERR_FILE_NOT_FOUND
.byte AlertButtonOptions::OK ; ERR_DUPLICATE_FILENAME
.byte AlertButtonOptions::OK ; ERR_OVERRUN_ERROR
.byte AlertButtonOptions::OK ; ERR_VOLUME_DIR_FULL
.byte AlertButtonOptions::OK ; ERR_ACCESS_ERROR
.byte AlertButtonOptions::OK ; ERR_NOT_PRODOS_VOLUME
.byte AlertButtonOptions::OK ; ERR_DUPLICATE_VOLUME
.byte AlertButtonOptions::OKCancel ; kErrInsertSystemDisk
.byte AlertButtonOptions::OKCancel ; kErrSaveChanges
.byte AlertButtonOptions::OK ; kErrNoWindowsOpen
.byte AlertButtonOptions::OK ; kErrDuplicateVolName
.byte AlertButtonOptions::OK ; kErrBasicSysNotFound
ASSERT_TABLE_SIZE alert_options_table, kNumAlerts
start:
;; --------------------------------------------------
;; Process options, populate `alert_params`
;; A = alert, X = options
;; Search for alert in table, set Y to index
ldy #kNumAlerts-1
DO
cmp alert_table,y
beq :+
dey
WHILE_POS
iny ; default
:
;; Look up message
copylohi message_table_low,y, message_table_high,y, alert_params+AlertParams::text
;; If options is 0, use table value; otherwise,
;; mask off low bit and it's the action (N and V bits)
;; %00000000 = Use default options
;; %0....... e.g. $01 = OK
;; %10...... e.g. $80 = Try Again, Cancel
;; %11...... e.g. $C0 = OK, Cancel
IF_X_NE #0
txa
and #$FE ; ignore low bit, e.g. treat $01 as $00
sta alert_params+AlertParams::buttons
ELSE
copy8 alert_options_table,y, alert_params+AlertParams::buttons
END_IF
copy8 #AlertOptions::Beep|AlertOptions::SaveBack, alert_params+AlertParams::options
ldax #alert_params
FALL_THROUGH_TO Alert
.endproc ; AlertByIdImpl
AlertById := AlertByIdImpl::start
;;; ============================================================
;;; Display alert
;;; Inputs: A,X=alert_params structure
;;; { .addr text, .byte AlertButtonOptions, .byte AlertOptions }
SystemTask = SystemTaskFromAux
alert_grafport = desktop_grafport
AD_SAVEBG = 1
AD_YESNOALL = 1
Bell := BellFromAux
BTKEntry := BTKAuxEntry
LBTKEntry := LBTKAuxEntry
.include "../lib/alert_dialog.s"
;;; ============================================================
.proc FlipMGTKHiresTable
ldy #0
ldx #kScreenHeight-1
DO
swap8 mgtk::hires_table_lo,x, mgtk::hires_table_lo,y
swap8 mgtk::hires_table_hi,x, mgtk::hires_table_hi,y
dex
iny
WHILE_Y_NE #kScreenHeight/2
rts
.endproc ; FlipMGTKHiresTable
;;; ============================================================
.endscope ; aux
ENDSEG SegmentDeskTopAux
|
a2stuff/a2d
| 9,793
|
src/desktop/lc.s
|
;;; ============================================================
;;; DeskTop - "Language Card" Segment
;;;
;;; Compiled as part of desktop.s
;;; ============================================================
;;; ============================================================
;;; Segment loaded into AUX $D000-$D1FF
;;; ============================================================
BEGINSEG SegmentDeskTopLC
;;; ============================================================
;;; Exported entry points for main>aux and aux>main calls
ASSERT_EQUALS *, CallMainToAux, "entry point"
.proc CallMainToAuxImpl
stax call_addr
jsr BankInAux
call_addr := *+1
jsr SELF_MODIFIED
jmp BankInMain
.endproc ; CallMainToAuxImpl
ASSERT_EQUALS *, CallAuxToMain, "entry point"
.proc CallAuxToMainImpl
stax call_addr
jsr BankInMain
call_addr := *+1
jsr SELF_MODIFIED
jmp BankInAux
.endproc ; CallAuxToMainImpl
ASSERT_EQUALS *, ReadSettingFromAux, "entry point"
.proc ReadSettingFromAuxImpl
jsr BankInMain
jsr ReadSetting
jmp BankInAux
.endproc ; ReadSettingFromAuxImpl
ASSERT_EQUALS *, WriteSettingFromAux, "entry point"
.proc WriteSettingFromAuxImpl
jsr BankInMain
jsr WriteSetting
jmp BankInAux
.endproc ; WriteSettingFromAuxImpl
;;; ============================================================
;;; Common code for main>aux relays with MLI-style params
;;; Inputs: A,X = target address
;;; Uses $7E/$7F
.proc ParamsRelayImpl
params_src := $7E
stax call_addr
;; Adjust return address on stack, compute
;; original params address.
pla
sta params_src
clc
adc #<3
tax
pla
sta params_src+1
adc #>3
pha
txa
pha
;; Copy the params here
ldy #3 ; ptr is off by 1
DO
copy8 (params_src),y, params-1,y
dey
WHILE_NOT_ZERO
;; Bank and call
jsr BankInAux
call_addr := * + 1
jsr SELF_MODIFIED
params: .res 3
jmp BankInMain
.endproc ; ParamsRelayImpl
;;; ============================================================
;;; MGTK call from main>aux, MLI-style params
.proc MGTKRelayImpl
ldax #MGTKAuxEntry
jmp ParamsRelayImpl
.endproc ; MGTKRelayImpl
;;; ============================================================
;;; IconTK call from main>aux, MLI-style params
.proc ITKRelayImpl
ldax #aux::ITKEntry
jmp ParamsRelayImpl
.endproc ; ITKRelayImpl
;;; ============================================================
;;; LineEditTK call from main>aux, MLI-style params
.proc LETKRelayImpl
ldax #aux::letk::LETKEntry
jmp ParamsRelayImpl
.endproc ; LETKRelayImpl
;;; ============================================================
;;; ButtonTK call from main>aux, MLI-style params
.proc BTKRelayImpl
ldax #aux::btk::BTKEntry
jmp ParamsRelayImpl
.endproc ; BTKRelayImpl
;;; ============================================================
;;; ListBoxTK call from main>aux, MLI-style params
.proc LBTKRelayImpl
ldax #aux::lbtk::LBTKEntry
jmp ParamsRelayImpl
.endproc ; LBTKRelayImpl
;;; ============================================================
;;; OptionPickerTK call from main>aux, MLI-style params
.proc OPTKRelayImpl
ldax #aux::optk::OPTKEntry
jmp ParamsRelayImpl
.endproc ; OPTKRelayImpl
;;; ============================================================
;;; Within an update event, adjust the update port of a window after
;;; the header has been drawn, if needed, so that the window contents
;;; are appropriately clipped.
;;;
;;; Assert: Within a `BeginUpdate`...`EndUpdate` sequence with port set
;;; Assert: `window_grafport` is set to window's raw port
.proc AdjustUpdatePortForEntries
port_ptr := $06
tmpw := $08
jsr BankInAux
MGTKEntry := aux::MGTKEntry
MGTK_CALL MGTK::GetPort, port_ptr
;; Copy somewhere easier to work with
ldy #.sizeof(MGTK::GrafPort)-1
DO
copy8 (port_ptr),y, desktop_grafport,y
dey
WHILE_POS
;; Determine if the update's maprect is already below the header; if
;; not, we need to offset the maprect below the header to prevent
;; icons from drawing over the header when vertically scrolled.
sub16 desktop_grafport+MGTK::GrafPort::viewloc+MGTK::Point::ycoord, window_grafport+MGTK::GrafPort::viewloc+MGTK::Point::ycoord, tmpw
scmp16 tmpw, #kWindowHeaderHeight
IF_NEG
;; Adjust grafport to account for header
add16 window_grafport+MGTK::GrafPort::viewloc+MGTK::Point::ycoord, #kWindowHeaderHeight, desktop_grafport+MGTK::GrafPort::viewloc+MGTK::Point::ycoord
add16 window_grafport+MGTK::GrafPort::maprect+MGTK::Rect::y1, #kWindowHeaderHeight, desktop_grafport+MGTK::GrafPort::maprect+MGTK::Rect::y1
MGTK_CALL MGTK::SetPort, desktop_grafport
END_IF
jmp BankInMain
.endproc ; AdjustUpdatePortForEntries
;;; ============================================================
;;; From MAIN, load AUX (A,X) into A
;;; Assert: Main is banked in
.proc AuxLoad
stax op+1
sta RAMRDON
op: lda SELF_MODIFIED
sta RAMRDOFF
rts
.endproc ; AuxLoad
;;; ============================================================
;;; From MAIN, show alert
;;; Assert: Main is banked in
;;; A=alert number, with default options
.proc ShowAlert
ldx #$00
FALL_THROUGH_TO ShowAlertOption
.endproc ; ShowAlert
;;; A=alert number, X=custom options
.proc ShowAlertOption
jsr BankInAux
jsr aux::AlertById
jmp BankInMain
.endproc ; ShowAlertOption
;;; A,X = string
;;; Y = `AlertButtonOptions`
.proc ShowAlertParams
jsr BankInAux
stax alert_params+AlertParams::text
sty alert_params+AlertParams::buttons
copy8 #AlertOptions::Beep|AlertOptions::SaveBack, alert_params+AlertParams::options
param_call aux::Alert, alert_params
jmp BankInMain
.endproc ; ShowAlertParams
;;; A,X = `AlertParams` struct
.proc ShowAlertStruct
jsr BankInAux
jsr aux::Alert
jmp BankInMain
.endproc ; ShowAlertStruct
;;; ============================================================
;;; Bell
;;; Assert: Aux is banked in
.proc BellFromAux
jsr BankInMain
jsr Bell
jmp BankInAux
.endproc ; BellFromAux
;;; ============================================================
;;; Yield from a nested event loop, for periodic tasks.
;;; Assert: Aux is banked in
.proc SystemTaskFromAux
jsr BankInMain
jsr SystemTask
jmp BankInAux
.endproc ; SystemTaskFromAux
;;; ============================================================
;;; Helpers for banking in Aux/Main $200-$BFFF.
;;; (These save 3 bytes per call.)
.proc BankInAux
sta RAMRDON
sta RAMWRTON
rts
.endproc ; BankInAux
.proc BankInMain
sta RAMRDOFF
sta RAMWRTOFF
rts
.endproc ; BankInMain
;;; ============================================================
;;; Pushes two words from $6/$8 to stack; preserves A,X,Y
.proc PushPointers
;; Stash A,X
sta a_save
stx x_save
;; Stash return address
pla
sta lo
pla
sta hi
;; Copy 4 bytes from $8 to stack
ldx #AS_BYTE(-4)
DO
lda $06 + 4,x
pha
inx
WHILE_NOT_ZERO
;; Restore return address
hi := *+1
lda #SELF_MODIFIED_BYTE
pha
lo := *+1
lda #SELF_MODIFIED_BYTE
pha
;; Restore A,X
x_save := *+1
ldx #SELF_MODIFIED_BYTE
a_save := *+1
lda #SELF_MODIFIED_BYTE
rts
.endproc ; PushPointers
;;; ============================================================
;;; Pops two words from stack to $6/$8; preserves A,X,Y
.proc PopPointers
;; Stash A,X
sta a_save
stx x_save
;; Stash return address
pla
sta lo
pla
sta hi
;; Copy 4 bytes from stack to $6
ldx #3
DO
pla
sta $06,x
dex
WHILE_POS
;; Restore return address to stack
hi := *+1
lda #SELF_MODIFIED_BYTE
pha
lo := *+1
lda #SELF_MODIFIED_BYTE
pha
;; Restore A,X
x_save := *+1
ldx #SELF_MODIFIED_BYTE
a_save := *+1
lda #SELF_MODIFIED_BYTE
rts
.endproc ; PopPointers
;;; ============================================================
;;; From main, concatenate aux-visible string to `text_input_buf`
;;; Assert: Main is banked in
.proc AppendToTextInputBuf
jsr BankInAux
jsr PushPointers
ptr := $06
stax ptr
ldy #0
lda (ptr),y
sta len
iny
ldx text_input_buf
inx
DO
copy8 (ptr),y, text_input_buf,x
len := *+1
cpy #SELF_MODIFIED_BYTE
BREAK_IF_EQ
inx
iny
WHILE_NOT_ZERO ; always
stx text_input_buf
jsr PopPointers
jmp BankInMain
.endproc ; AppendToTextInputBuf
;;; ============================================================
.include "res.s"
ENDSEG SegmentDeskTopLC
|
a2stuff/a2d
| 10,188
|
src/desktop/ovl_selector_edit.s
|
;;; ============================================================
;;; Overlay for Selector Edit - drives File Picker dialog
;;;
;;; Compiled as part of desktop.s
;;; ============================================================
BEGINSEG OverlayShortcutEdit
;;; Constants specific to this dialog and used by the caller. These
;;; correspond to properties of `docs/Selector_List_Format.md` but are
;;; specific to this dialog and the caller.
kRunListPrimary = 1 ; entry is in first 8 (menu and dialog)
kRunListSecondary = 2 ; entry is in second 16 (dialog only)
kCopyOnBoot = 1 ; corresponds to `kSelectorEntryCopyOnBoot`
kCopyOnUse = 2 ; corresponds to `kSelectorEntryCopyOnUse`
kCopyNever = 3 ; corresponds to `kSelectorEntryCopyNever`
.scope SelectorEditOverlay
MLIEntry := main::MLIRelayImpl
MGTKEntry := MGTKRelayImpl
BTKEntry := BTKRelayImpl
.proc Run
;; A = (obsolete, was dialog type)
;; Y = is_add_flag | copy_when
;; X = which_run_list
stx which_run_list
sty is_add_flag
tya
and #$7F
sta copy_when
tsx
stx saved_stack
jsr file_dialog::Init
SET_BIT7_FLAG file_dialog::extra_controls_flag
copy8 #file_dialog::kSelectionRequiredDirsOK, file_dialog::selection_requirement_flags
lda #BTK::kButtonStateNormal
sta primary_run_list_button::state
sta secondary_run_list_button::state
sta at_first_boot_button::state
sta at_first_use_button::state
sta never_button::state
ldax #label_edit
bit is_add_flag
IF_NS
ldax #label_add
END_IF
jsr file_dialog::OpenWindow
jsr DrawControls
COPY_BYTES file_dialog::kJumpTableSize, jt_callbacks, file_dialog::jump_table
lda which_run_list
sec
jsr UpdateRunListButton
lda copy_when
sec
jsr DrawCopyWhenButton
copy16 #HandleClick, file_dialog::click_handler_hook
copy16 #HandleKey, file_dialog::key_handler_hook
copy8 #kSelectorMaxNameLength, file_dialog_res::line_edit::max_length
;; If we were passed a path (`path_buf0`), prep the file dialog with it.
lda path_buf0
IF_ZERO
jsr file_dialog::InitPathWithDefaultDevice
ELSE
COPY_STRING path_buf0, file_dialog::path_buf
;; Strip to parent directory
jsr file_dialog::StripPathBufSegment
;; And populate `buffer` with filename
ldx file_dialog::path_buf
inx
ldy #0
DO
inx
iny
copy8 path_buf0,x, buffer,y
WHILE_X_NE path_buf0
sty buffer
END_IF
param_call file_dialog::UpdateListFromPathAndSelectFile, buffer
jmp file_dialog::EventLoop
buffer: .res 16, 0
.endproc ; Run
;;; ============================================================
.proc DrawControls
MGTK_CALL MGTK::SetPort, file_dialog_res::winfo::port
param_call file_dialog::DrawLineEditLabel, enter_the_name_to_appear_label
MGTK_CALL MGTK::MoveTo, add_a_new_entry_to_label_pos
param_call main::DrawString, add_a_new_entry_to_label_str
MGTK_CALL MGTK::MoveTo, down_load_label_pos
param_call main::DrawString, down_load_label_str
BTK_CALL BTK::RadioDraw, primary_run_list_button
BTK_CALL BTK::RadioDraw, secondary_run_list_button
BTK_CALL BTK::RadioDraw, at_first_boot_button
BTK_CALL BTK::RadioDraw, at_first_use_button
BTK_CALL BTK::RadioDraw, never_button
rts
.endproc ; DrawControls
;;; ============================================================
saved_stack:
.byte 0
jt_callbacks:
jmp HandleOK
jmp HandleCancel
.assert * - jt_callbacks = file_dialog::kJumpTableSize, error, "Table size error"
;;; ============================================================
;;; Close window and finish (via saved_stack) if OK
;;; Outputs: A = 0 if OK
;;; X = which run list (1=primary, 2=secondary)
;;; Y = copy when (1=boot, 2=use, 3=never)
DEFINE_GET_FILE_INFO_PARAMS get_file_info_params, main::tmp_path_buf
.proc HandleOK
param_call file_dialog::GetPath, path_buf0
param_call file_dialog::GetPath, main::tmp_path_buf
;; If name is empty, use last path segment
lda text_input_buf
IF_ZERO
ldx path_buf0
DO
lda path_buf0,x
BREAK_IF_A_EQ #'/'
dex
WHILE_NOT_ZERO ; always, since path is valid
inx
ldy #1
DO
copy8 path_buf0,x, text_input_buf,y
BREAK_IF_X_EQ path_buf0
inx
iny
WHILE_NOT_ZERO ; always
;; Truncate if necessary
cpy #kSelectorMaxNameLength+1
IF_GE
ldy #kSelectorMaxNameLength
END_IF
sty text_input_buf
END_IF
;; Disallow copying some types to ramcard
lda copy_when
cmp #kCopyNever
beq ok
MLI_CALL GET_FILE_INFO, get_file_info_params
bcs alert
;; Volume?
lda get_file_info_params::storage_type
cmp #ST_VOLUME_DIRECTORY
beq invalid
;; Link?
lda get_file_info_params::file_type
cmp #FT_LINK
beq invalid
ok: jsr file_dialog::CloseWindow
ldx saved_stack
txs
ldx which_run_list
ldy copy_when
return #0
invalid:
lda #ERR_INVALID_PATHNAME
alert: jmp ShowAlert
.endproc ; HandleOK
;;; ============================================================
.proc HandleCancel
jsr file_dialog::CloseWindow
ldx saved_stack
txs
return #$FF
.endproc ; HandleCancel
;;; ============================================================
which_run_list:
.byte 0
copy_when:
.byte 0
is_add_flag: ; high bit set = Add, clear = Edit
.byte 0
;;; ============================================================
.proc HandleClick
MGTK_CALL MGTK::InRect, primary_run_list_button::rect
jne ClickPrimaryRunListCtrl
MGTK_CALL MGTK::InRect, secondary_run_list_button::rect
jne ClickSecondaryRunListCtrl
MGTK_CALL MGTK::InRect, at_first_boot_button::rect
jne ClickAtFirstBootCtrl
MGTK_CALL MGTK::InRect, at_first_use_button::rect
jne ClickAtFirstUseCtrl
MGTK_CALL MGTK::InRect, never_button::rect
jne ClickNeverCtrl
return #0
.endproc ; HandleClick
.proc ClickPrimaryRunListCtrl
lda which_run_list
IF_A_NE #kRunListPrimary
clc
jsr UpdateRunListButton
copy8 #kRunListPrimary, which_run_list
sec
jsr UpdateRunListButton
END_IF
return #$FF
.endproc ; ClickPrimaryRunListCtrl
.proc ClickSecondaryRunListCtrl
lda which_run_list
IF_A_NE #kRunListSecondary
clc
jsr UpdateRunListButton
copy8 #kRunListSecondary, which_run_list
sec
jsr UpdateRunListButton
END_IF
return #$FF
.endproc ; ClickSecondaryRunListCtrl
.proc ClickAtFirstBootCtrl
lda copy_when
IF_A_NE #kCopyOnBoot
clc
jsr DrawCopyWhenButton
lda #kCopyOnBoot
sta copy_when
sec
jsr DrawCopyWhenButton
END_IF
return #$FF
.endproc ; ClickAtFirstBootCtrl
.proc ClickAtFirstUseCtrl
lda copy_when
IF_A_NE #kCopyOnUse
clc
jsr DrawCopyWhenButton
lda #kCopyOnUse
sta copy_when
sec
jsr DrawCopyWhenButton
END_IF
return #$FF
.endproc ; ClickAtFirstUseCtrl
.proc ClickNeverCtrl
lda copy_when
IF_A_NE #kCopyNever
clc
jsr DrawCopyWhenButton
lda #kCopyNever
sta copy_when
sec
jsr DrawCopyWhenButton
END_IF
return #$FF
.endproc ; ClickNeverCtrl
;;; ============================================================
.proc UpdateRunListButton
ldx #BTK::kButtonStateNormal
IF_CS
ldx #BTK::kButtonStateChecked
END_IF
IF_A_EQ #kRunListPrimary
stx primary_run_list_button::state
BTK_CALL BTK::RadioUpdate, primary_run_list_button
ELSE
stx secondary_run_list_button::state
BTK_CALL BTK::RadioUpdate, secondary_run_list_button
END_IF
rts
.endproc ; UpdateRunListButton
.proc DrawCopyWhenButton
ldx #BTK::kButtonStateNormal
IF_CS
ldx #BTK::kButtonStateChecked
END_IF
IF_A_EQ #kCopyOnBoot
stx at_first_boot_button::state
BTK_CALL BTK::RadioUpdate, at_first_boot_button
rts
END_IF
IF_A_EQ #kCopyOnUse
stx at_first_use_button::state
BTK_CALL BTK::RadioUpdate, at_first_use_button
rts
END_IF
stx never_button::state
BTK_CALL BTK::RadioUpdate, never_button
rts
.endproc ; DrawCopyWhenButton
;;; ============================================================
.proc HandleKey
lda event_params::modifiers
RTS_IF_ZERO
lda event_params::key
cmp #res_char_shortcut_apple_1
jeq ClickPrimaryRunListCtrl
cmp #res_char_shortcut_apple_2
jeq ClickSecondaryRunListCtrl
cmp #res_char_shortcut_apple_3
jeq ClickAtFirstBootCtrl
cmp #res_char_shortcut_apple_4
jeq ClickAtFirstUseCtrl
cmp #res_char_shortcut_apple_5
jeq ClickNeverCtrl
rts
.endproc ; HandleKey
;;; ============================================================
.endscope ; SelectorEditOverlay
ENDSEG OverlayShortcutEdit
|
a2stuff/a2d
| 76,107
|
src/desktop/res.s
|
;;; ============================================================
;;; DeskTop - Resources
;;;
;;; Compiled as part of desktop.s
;;; ============================================================
pencopy: .byte MGTK::pencopy
penXOR: .byte MGTK::penXOR
notpencopy: .byte MGTK::notpencopy
;;; ============================================================
;;; Re-used param space for events/queries (10 bytes)
.include "../lib/event_params.s"
;;; ============================================================
.params getwinport_params
window_id: .byte 0
a_grafport: .addr window_grafport
.endparams
;;; GrafPort used specifically for operations that draw into windows.
window_grafport: .tag MGTK::GrafPort
;;; GrafPort used for nearly all operations. Usually re-initialized
;;; before use.
desktop_grafport: .tag MGTK::GrafPort
;;; ============================================================
;; Copies of ROM bytes used for machine identification
.params startdesktop_params
machine: .byte $06 ; ROM FBB3 ($06 = IIe or later)
subid: .byte $EA ; ROM FBC0 ($EA = IIe, $E0 = IIe enh/IIgs, $00 = IIc/IIc+)
op_sys: .byte 0 ; 0=ProDOS
slot_num: .byte 0 ; Mouse slot, 0 = search
use_interrupts: .byte 0 ; 0=passive
systextfont: .addr DEFAULT_FONT
savearea: .addr SAVE_AREA_BUFFER
savesize: .word kSaveAreaSize
.endparams
;;; Shift key mod sets PB2 if shift is *not* down. Since we can't detect
;;; the mod, snapshot on init (and assume shift is not down) and XOR.
pb2_initial_state:
.byte 0
.params initmenu_params
open_char: .byte kGlyphOpenApple
solid_char: .byte kGlyphSolidApple
ASSERT_EQUALS (solid_char - open_char), 1, "solid_char must follow open_char immediately"
check_char: .byte kGlyphCheckmark
control_char: .byte '^'
.endparams
setzp_params_nopreserve: ; performance over convenience
.byte MGTK::zp_overwrite ; set at startup
setzp_params_preserve: ; convenience over performance
.byte MGTK::zp_preserve ; used while DAs are running
.params trackgoaway_params
goaway:.byte 0
.endparams
;;; Every event loop tick, a counter is incremented (by 3); when it passes
;;; this value, periodic tasks are run (e.g. drawing the clock, checking
;;; for new devices, etc).
periodic_task_delay:
.byte 0
;;; This delay is initialized to a machine-specific value. TODO: Why???
kPeriodicTaskDelayIIe = $96
kPeriodicTaskDelayIIc = $FA
kPeriodicTaskDelayIIgs = $FD
.params scalemouse_params
x_exponent: .byte 1 ; MGTK default is x 2:1 and y 1:1
y_exponent: .byte 0 ; ... doubled on IIc / IIc+
.endparams
num_selector_list_items:
.byte 0
;;; Generic path buffer. In file dialog, used as current path.
path_buf0:
.res kPathBufferSize, 0
;;; Generic path buffer. Used primarily as line edit text content,
;;; and for composing long alert messages.
text_input_buf:
.res 128, 0
;;; ============================================================
.params winfo_rename_dialog
kWindowId = $12
kWidth = kIconRenameLineEditWidth
kHeight = kTextBoxHeight - 2
window_id: .byte kWindowId
options: .byte MGTK::Option::dialog_box
title: .addr 0
hscroll: .byte MGTK::Scroll::option_none
vscroll: .byte MGTK::Scroll::option_none
hthumbmax: .byte 0
hthumbpos: .byte 0
vthumbmax: .byte 0
vthumbpos: .byte 0
status: .byte 0
reserved: .byte 0
mincontwidth: .word 150
mincontheight: .word 50
maxcontwidth: .word 500
maxcontheight: .word 140
port:
DEFINE_POINT viewloc, SELF_MODIFIED, SELF_MODIFIED
mapbits: .addr MGTK::screen_mapbits
mapwidth: .byte MGTK::screen_mapwidth
reserved2: .byte 0
DEFINE_RECT maprect, 0, 0, kWidth, kHeight
pattern: .res 8, $FF
colormasks: .byte MGTK::colormask_and, MGTK::colormask_or
DEFINE_POINT penloc, 0, 0
penwidth: .byte 1
penheight: .byte 1
penmode: .byte MGTK::pencopy
textback: .byte MGTK::textbg_white
textfont: .addr DEFAULT_FONT
nextwinfo: .addr 0
REF_WINFO_MEMBERS
.endparams
DEFINE_LINE_EDIT rename_line_edit_rec, winfo_rename_dialog::kWindowId, text_input_buf, 0, -1, kIconRenameLineEditWidth, kMaxFilenameLength
DEFINE_LINE_EDIT_PARAMS rename_le_params, rename_line_edit_rec
;;; ============================================================
;;; Dialog used for:
;;; * File > Get Info
;;; * Special > Format Disk...
;;; * Special > Erase Disk...
kPromptDialogWidth = 400
kPromptDialogHeight = 107
kPromptDialogLeft = (kScreenWidth - kPromptDialogWidth) / 2
kPromptDialogTop = (kScreenHeight - kPromptDialogHeight) / 2
.params winfo_prompt_dialog
kWindowId = $13
kWidth = kPromptDialogWidth
kHeight = kPromptDialogHeight
window_id: .byte kWindowId
options: .byte MGTK::Option::dialog_box
title: .addr 0
hscroll: .byte MGTK::Scroll::option_none
vscroll: .byte MGTK::Scroll::option_none
hthumbmax: .byte 0
hthumbpos: .byte 0
vthumbmax: .byte 0
vthumbpos: .byte 0
status: .byte 0
reserved: .byte 0
mincontwidth: .word 150
mincontheight: .word 50
maxcontwidth: .word 500
maxcontheight: .word 140
port:
DEFINE_POINT viewloc, kPromptDialogLeft, kPromptDialogTop
mapbits: .addr MGTK::screen_mapbits
mapwidth: .byte MGTK::screen_mapwidth
reserved2: .byte 0
DEFINE_RECT maprect, 0, 0, kWidth, kHeight
pattern: .res 8, $FF
colormasks: .byte MGTK::colormask_and, MGTK::colormask_or
DEFINE_POINT penloc, 0, 0
penwidth: .byte 1
penheight: .byte 1
penmode: .byte MGTK::pencopy
textback: .byte MGTK::textbg_white
textfont: .addr DEFAULT_FONT
nextwinfo: .addr 0
REF_WINFO_MEMBERS
.endparams
kDialogLabelDefaultX = 40
kDialogLabelRightX = 160
kDialogValueLeft = 170
kNameInputLeft = kDialogLabelDefaultX
kNameInputTop = 67
kNameInputWidth = 320
DEFINE_RECT_SZ name_input_rect, kNameInputLeft, kNameInputTop, kNameInputWidth, kTextBoxHeight
DEFINE_POINT pos_dialog_title, 0, aux::kDialogTitleY
DEFINE_POINT dialog_label_pos, kDialogLabelDefaultX, 0
kPromptWindowId = winfo_prompt_dialog::kWindowId
DEFINE_BUTTON ok_button, kPromptWindowId, res_string_button_ok, kGlyphReturn, 260, kPromptDialogHeight-19
DEFINE_BUTTON cancel_button, kPromptWindowId, res_string_button_cancel, res_string_button_cancel_shortcut, 40, kPromptDialogHeight-19
DEFINE_BUTTON locked_button, kPromptWindowId, res_string_get_info_checkbox_locked, res_string_get_info_shortcut_locked, kDialogValueLeft, aux::kDialogLabelRow5+2
;;; $00 = ok/cancel
;;; $80 = ok (only)
prompt_button_flags:
.byte 0
has_input_field_flag:
.byte 0
has_device_picker_flag: ; bit7 set when prompt is showing device picker
.byte 0
;;; ============================================================
.params winfo_progress_dialog
kWindowId = $11
kWidth = aux::kProgressDialogWidth
kHeight = aux::kProgressDialogHeight
kLeft = (kScreenWidth - kWidth) / 2
kTop = (kScreenHeight - kHeight) / 6
window_id: .byte kWindowId
options: .byte MGTK::Option::dialog_box
title: .addr 0
hscroll: .byte MGTK::Scroll::option_none
vscroll: .byte MGTK::Scroll::option_none
hthumbmax: .byte 0
hthumbpos: .byte 0
vthumbmax: .byte 0
vthumbpos: .byte 0
status: .byte 0
reserved: .byte 0
mincontwidth: .word 150
mincontheight: .word 50
maxcontwidth: .word 500
maxcontheight: .word 140
port:
DEFINE_POINT viewloc, kLeft, kTop
mapbits: .addr MGTK::screen_mapbits
mapwidth: .byte MGTK::screen_mapwidth
reserved2: .byte 0
DEFINE_RECT maprect, 0, 0, kWidth, kHeight
pattern: .res 8, $FF
colormasks: .byte MGTK::colormask_and, MGTK::colormask_or
DEFINE_POINT penloc, 0, 0
penwidth: .byte 1
penheight: .byte 1
penmode: .byte MGTK::pencopy
textback: .byte MGTK::textbg_white
textfont: .addr DEFAULT_FONT
nextwinfo: .addr 0
REF_WINFO_MEMBERS
.endparams
kProgressDialogPathLeft = 60
kProgressDialogPathWidth = winfo_progress_dialog::kWidth - kProgressDialogPathLeft - kProgressDialogLabelDefaultX
kProgressDialogLabelDefaultX = 25
kProgressDialogLabelBaseY = 17
DEFINE_POINT progress_dialog_label_pos, kProgressDialogLabelDefaultX, 0
DEFINE_POINT progress_dialog_remaining_pos, aux::kProgressDialogWidth/2, aux::kProgressDialogLabelRow0
kProgressBarTop = 41
kProgressBarWidth = winfo_progress_dialog::kWidth - kProgressDialogLabelDefaultX*2
kProgressBarHeight = 7
DEFINE_RECT_SZ progress_dialog_bar_frame, kProgressDialogLabelDefaultX-1, kProgressBarTop-1, kProgressBarWidth+2, kProgressBarHeight+2
DEFINE_RECT_SZ progress_dialog_bar_meter, kProgressDialogLabelDefaultX, kProgressBarTop, kProgressBarWidth,kProgressBarHeight
progress_pattern:
.byte %01000100
.byte %00010001
.byte %01000100
.byte %00010001
.byte %01000100
.byte %00010001
.byte %01000100
.byte %00010001
.params progress_muldiv_params
number: .word kProgressBarWidth ; (in) constant
numerator: .word 0 ; (in) populated dynamically
denominator: .word 0 ; (in) populated dynamically
result: .word 0 ; (out)
remainder: .word 0 ; (out)
REF_MULDIV_MEMBERS
.endparams
;;; ============================================================
;;; "About Apple II DeskTop" Dialog
.params winfo_about_dialog
kWindowId = $18
kWidth = aux::kAboutDialogWidth
kHeight = aux::kAboutDialogHeight
window_id: .byte kWindowId
options: .byte MGTK::Option::dialog_box
title: .addr 0
hscroll: .byte MGTK::Scroll::option_none
vscroll: .byte MGTK::Scroll::option_none
hthumbmax: .byte 0
hthumbpos: .byte 0
vthumbmax: .byte 0
vthumbpos: .byte 0
status: .byte 0
reserved: .byte 0
mincontwidth: .word 150
mincontheight: .word 50
maxcontwidth: .word 500
maxcontheight: .word 140
port:
DEFINE_POINT viewloc, (kScreenWidth - kWidth) / 2, (kScreenHeight - kHeight) / 2
mapbits: .addr MGTK::screen_mapbits
mapwidth: .byte MGTK::screen_mapwidth
reserved2: .byte 0
DEFINE_RECT maprect, 0, 0, kWidth, kHeight
pattern: .res 8, $FF
colormasks: .byte MGTK::colormask_and, MGTK::colormask_or
DEFINE_POINT penloc, 0, 0
penwidth: .byte 1
penheight: .byte 1
penmode: .byte MGTK::pencopy
textback: .byte MGTK::textbg_white
textfont: .addr DEFAULT_FONT
nextwinfo: .addr 0
REF_WINFO_MEMBERS
.endparams
;;; ============================================================
;;; Dialog for Edit/Delete/Run a Shortcut...
.params winfo_entry_picker
kWindowId = $1B
kWidth = 350
kHeight = 126
window_id: .byte kWindowId
options: .byte MGTK::Option::dialog_box
title: .addr 0
hscroll: .byte MGTK::Scroll::option_none
vscroll: .byte MGTK::Scroll::option_none
hthumbmax: .byte 0
hthumbpos: .byte 0
vthumbmax: .byte 0
vthumbpos: .byte 0
status: .byte 0
reserved: .byte 0
mincontwidth: .word 150
mincontheight: .word 50
maxcontwidth: .word 500
maxcontheight: .word 140
port:
DEFINE_POINT viewloc, (kScreenWidth - kWidth) / 2, (kScreenHeight - kHeight) / 2
mapbits: .addr MGTK::screen_mapbits
mapwidth: .byte MGTK::screen_mapwidth
reserved2: .byte 0
DEFINE_RECT maprect, 0, 0, kWidth, kHeight
pattern: .res 8, $FF
colormasks: .byte MGTK::colormask_and, MGTK::colormask_or
DEFINE_POINT penloc, 0, 0
penwidth: .byte 1
penheight: .byte 1
penmode: .byte MGTK::pencopy
textback: .byte MGTK::textbg_white
textfont: .addr DEFAULT_FONT
nextwinfo: .addr 0
REF_WINFO_MEMBERS
.endparams
pensize_normal: .byte 1, 1
pensize_frame: .byte kBorderDX, kBorderDY
DEFINE_RECT_FRAME entry_picker_frame_rect, winfo_entry_picker::kWidth, winfo_entry_picker::kHeight
;; Options control metrics
kShortcutPickerCols = 3
kShortcutPickerRows = 8
kShortcutPickerLeft = (winfo_entry_picker::kWidth - kShortcutPickerItemWidth * kShortcutPickerCols + 1) / 2
kShortcutPickerTop = 24
kShortcutPickerItemWidth = 104
kShortcutPickerItemHeight = kListItemHeight
kShortcutPickerTextHOffset = 10
kShortcutPickerTextVOffset = kShortcutPickerItemHeight - 1
DEFINE_OPTION_PICKER shortcut_picker_record, winfo_entry_picker::kWindowId, kShortcutPickerLeft, kShortcutPickerTop, kShortcutPickerRows, kShortcutPickerCols, kShortcutPickerItemWidth, kShortcutPickerItemHeight, kShortcutPickerTextHOffset, kShortcutPickerTextVOffset, ShortcutPickerIsEntryCallback, ShortcutPickerDrawEntryCallback, ShortcutPickerSelChangeCallback
DEFINE_OPTION_PICKER_PARAMS shortcut_picker_params, shortcut_picker_record
;;; OPTK callbacks need to be aux-callable, so use these relays
ShortcutPickerIsEntryCallback:
jsr BankInMain
jsr SelectorPickOverlay::IsEntryCallback
jmp BankInAux
ShortcutPickerDrawEntryCallback:
jsr BankInMain
jsr SelectorPickOverlay::DrawEntryCallback
jmp BankInAux
ShortcutPickerSelChangeCallback:
jsr BankInMain
jsr SelectorPickOverlay::SelChangeCallback
jmp BankInAux
;; Line endpoints
DEFINE_POINT entry_picker_line1_start, kBorderDX*2, 22
DEFINE_POINT entry_picker_line1_end, winfo_entry_picker::kWidth - kBorderDX*2, 22
DEFINE_POINT entry_picker_line2_start, kBorderDX*2, winfo_entry_picker::kHeight-21
DEFINE_POINT entry_picker_line2_end, winfo_entry_picker::kWidth - kBorderDX*2, winfo_entry_picker::kHeight-21
DEFINE_BUTTON entry_picker_ok_button, winfo_entry_picker::kWindowId, res_string_button_ok, kGlyphReturn, 210, winfo_entry_picker::kHeight-18
DEFINE_BUTTON entry_picker_cancel_button, winfo_entry_picker::kWindowId, res_string_button_cancel, res_string_button_cancel_shortcut, 40, winfo_entry_picker::kHeight-18
;;; ============================================================
;;; Format/Erase dialogs
;; Options control metrics
kVolPickerCols = 3
kVolPickerRows = 5
.assert kMaxDevListSize <= kVolPickerRows * kVolPickerCols, error, "can't fit all vols"
kVolPickerLeft = (winfo_prompt_dialog::kWidth - kVolPickerItemWidth * kVolPickerCols + 1) / 2
kVolPickerTop = 34
kVolPickerItemWidth = 127
kVolPickerItemHeight = kListItemHeight
kVolPickerTextHOffset = 1
kVolPickerTextVOffset = kVolPickerItemHeight-1
DEFINE_OPTION_PICKER vol_picker_record, winfo_prompt_dialog::kWindowId, kVolPickerLeft, kVolPickerTop, kVolPickerRows, kVolPickerCols, kVolPickerItemWidth, kVolPickerItemHeight, kVolPickerTextHOffset, kVolPickerTextVOffset, VolPickerIsEntryCallback, VolPickerDrawEntryCallback, VolPickerSelChangeCallback
DEFINE_OPTION_PICKER_PARAMS vol_picker_params, vol_picker_record
;;; OPTK callbacks need to be aux-callable, so use these relays
VolPickerIsEntryCallback:
jsr BankInMain
jsr FormatEraseOverlay::IsEntryCallback
jmp BankInAux
VolPickerDrawEntryCallback:
jsr BankInMain
jsr FormatEraseOverlay::DrawEntryCallback
jmp BankInAux
VolPickerSelChangeCallback:
jsr BankInMain
jsr FormatEraseOverlay::SelChangeCallback
jmp BankInAux
;; Label pos
DEFINE_POINT vol_picker_select_pos, kDialogLabelDefaultX, kVolPickerTop - 4
;; Line endpoints
DEFINE_POINT vol_picker_line1_start, 7, kVolPickerTop - 2
DEFINE_POINT vol_picker_line1_end, winfo_prompt_dialog::kWidth - 8, kVolPickerTop - 2
DEFINE_POINT vol_picker_line2_start, 7, winfo_prompt_dialog::kHeight-22
DEFINE_POINT vol_picker_line2_end, winfo_prompt_dialog::kWidth - 8, winfo_prompt_dialog::kHeight-22
the_dos_33_disk_label:
PASCAL_STRING res_string_the_dos_33_disk_suffix_pattern
kTheDos33DiskSlotCharOffset = res_const_the_dos_33_disk_suffix_pattern_offset1
kTheDos33DiskDriveCharOffset = res_const_the_dos_33_disk_suffix_pattern_offset2
the_disk_in_slot_label:
PASCAL_STRING res_string_the_disk_in_slot_suffix_pattern
kTheDiskInSlotSlotCharOffset = res_const_the_disk_in_slot_suffix_pattern_offset1
kTheDiskInSlotDriveCharOffset = res_const_the_disk_in_slot_suffix_pattern_offset2
;;; ============================================================
;;; Name prompt dialog (used for Format/Erase)
DEFINE_LINE_EDIT prompt_line_edit_rec, winfo_prompt_dialog::kWindowId, text_input_buf, kNameInputLeft, kNameInputTop, kNameInputWidth, kMaxFilenameLength
DEFINE_LINE_EDIT_PARAMS prompt_le_params, prompt_line_edit_rec
;;; ============================================================
str_file_suffix:
PASCAL_STRING res_string_file_suffix
str_files_suffix:
PASCAL_STRING res_string_files_suffix
str_file_count: ; populated with number of files
PASCAL_STRING " ##,### "
;;; Used as suffix to handle `str_file_count` shrinking
str_2_spaces:
PASCAL_STRING " "
str_kb_suffix:
PASCAL_STRING res_string_kb_suffix ; suffix for kilobytes
file_count:
.word 0
total_count:
.word 0
;;; ============================================================
FONT := DEFAULT_FONT
FD_EXTENDED = 1
.include "../lib/file_dialog_res.s"
;;; ============================================================
;;; Resources for Add/Edit a Shortcut dialog
enter_the_name_to_appear_label:
PASCAL_STRING res_string_selector_label_enter_name
kRadioButtonLeft = 332
kFDWinId = file_dialog_res::kFilePickerDlgWindowID
DEFINE_LABEL add_a_new_entry_to, res_string_selector_label_add_a_new_entry_to, 329, 35
DEFINE_BUTTON primary_run_list_button, kFDWinId, res_string_selector_label_primary_run_list, res_string_shortcut_apple_1, kRadioButtonLeft, 37
DEFINE_BUTTON secondary_run_list_button, kFDWinId, res_string_selector_label_secondary_run_list, res_string_shortcut_apple_2, kRadioButtonLeft, 47
DEFINE_LABEL down_load, res_string_selector_label_download, 329, 69
DEFINE_BUTTON at_first_boot_button, kFDWinId, res_string_selector_label_at_first_boot, res_string_shortcut_apple_3, kRadioButtonLeft, 71
DEFINE_BUTTON at_first_use_button, kFDWinId, res_string_selector_label_at_first_use, res_string_shortcut_apple_4, kRadioButtonLeft, 81
DEFINE_BUTTON never_button, kFDWinId, res_string_selector_label_never, res_string_shortcut_apple_5, kRadioButtonLeft, 91
;;; ============================================================
label_copy_selection:
PASCAL_STRING res_string_menu_item_copy_selection
;;; ============================================================
str_jan:PASCAL_STRING res_string_month_name_1
str_feb:PASCAL_STRING res_string_month_name_2
str_mar:PASCAL_STRING res_string_month_name_3
str_apr:PASCAL_STRING res_string_month_name_4
str_may:PASCAL_STRING res_string_month_name_5
str_jun:PASCAL_STRING res_string_month_name_6
str_jul:PASCAL_STRING res_string_month_name_7
str_aug:PASCAL_STRING res_string_month_name_8
str_sep:PASCAL_STRING res_string_month_name_9
str_oct:PASCAL_STRING res_string_month_name_10
str_nov:PASCAL_STRING res_string_month_name_11
str_dec:PASCAL_STRING res_string_month_name_12
month_table:
.addr str_no_date
.addr str_jan,str_feb,str_mar,str_apr,str_may,str_jun
.addr str_jul,str_aug,str_sep,str_oct,str_nov,str_dec
ASSERT_ADDRESS_TABLE_SIZE month_table, 13
str_no_date:
PASCAL_STRING res_string_no_date
str_space:
PASCAL_STRING " "
str_comma:
PASCAL_STRING res_string_comma_infix
str_at:
PASCAL_STRING res_string_at_infix
str_today:
PASCAL_STRING res_string_today
str_yesterday:
PASCAL_STRING res_string_yesterday
str_tomorrow:
PASCAL_STRING res_string_tomorrow
;;; ============================================================
;;; Shortcuts ("run list")
;; Buffer for Run List entries
kMaxRunListEntries = 8
;;; Names (used in menus, must be visible to MGTK in Aux)
run_list_entries:
.res kMaxRunListEntries * 16, 0
;;; ============================================================
;;; Window & Icon State
;;; ============================================================
;; Used when restoring windows
DEFINE_POINT new_window_viewloc, 0,0
DEFINE_RECT new_window_maprect, 0,0,0,0
new_window_view_by: .byte 0
;; Total number of icons
icon_count:
.byte 0
;;; Copy out of `window_entry_table` of icon list for active window (0=desktop)
;; which window buffer is copied
;; (see `window_entry_count_table`, `window_entry_list_table`)
cached_window_id: .byte 0
;; number of entries in copied window
cached_window_entry_count:.byte 0
;; list of entries (icons or file entry numbers) in copied window
cached_window_entry_list: .res kMaxIconCount, 0
;;; Index of window with selection (0=desktop)
selected_window_id:
.byte 0
;;; Number of selected icons
selected_icon_count:
.byte 0
;;; Indexes of selected icons (global, not w/in window)
selected_icon_list:
.res kMaxIconCount, 0
;;; Table of desktop window `Winfo` addresses
win_table:
.addr 0
.repeat ::kMaxDeskTopWindows,i
.addr .ident(.sprintf("winfo%d",i+1))
.endrepeat
ASSERT_ADDRESS_TABLE_SIZE win_table, kMaxDeskTopWindows + 1
;;; ============================================================
;;; IconTK initialization parameters
.params itkinit_params
headersize: .byte kWindowHeaderHeight
a_polybuf: .addr SAVE_AREA_BUFFER
bufsize: .word kSaveAreaSize
a_typemap: .addr type_icons_table
a_heap: .addr icon_entries
.endproc
;;; Table mapping IconType to IconResource
type_icons_table:
;; Volumes
.addr trash_icon ; trash
.addr floppy140_icon ; floppy140
.addr ramdisk_icon ; ramdisk
.addr profile_icon ; profile
.addr floppy800_icon ; floppy800
.addr fileshare_icon ; fileshare
.addr cdrom_icon ; cdrom
;; Files
.addr gen ; generic
.addr txt ; text
.addr bin ; binary
.addr fot ; graphics
.addr anm ; animation
.addr mus ; music
.addr mus ; tracker
.addr snd ; audio
.addr tts ; speech
.addr fnt ; font
.addr rel ; relocatable
.addr cmd ; command
.addr dir ; folder
.addr sdr ; system_folder
.addr src ; iigs
.addr adb ; appleworks_db
.addr awp ; appleworks_wp
.addr asp ; appleworks_sp
.addr arc ; archive
.addr arc ; encoded
.addr lnk ; link
.addr a2d ; desk_accessory
.addr bas ; basic
.addr int ; intbasic
.addr var ; variables
.addr sys ; system
.addr app ; application
;; Small icons
.addr sm_gen
.addr sm_dir
ASSERT_ADDRESS_TABLE_SIZE type_icons_table, IconType::COUNT
;;; Used for multiple IconTK calls:
;;; * IconTK::EraseIcon
;;; * IconTK::HighlightIcon
;;; * IconTK::IconInRect (with following `tmp_rect`)
;;; * IconTK::DrawIcon
;;; * IconTK::FreeIcon
;;; * IconTK::UnhighlightIcon
;;; * IconTK::GetIconBounds (with following `tmp_rect`)
;;; * IconTK::GetRenameRect (with following `tmp_rect`)
icon_param: .byte 0
;; Used for all sorts of temporary work
;; * follows icon_param for IconTK::IconInRect call
;; * used for saving/restoring window bounds to/from file
;; * used for icon clipping
;; * used for window frame zoom animation
ASSERT_ADDRESS icon_param+1
DEFINE_RECT tmp_rect, 0, 0, 0, 0
;;; Used by IconTK::AllocIcon and IconTK::GetIconEntry
;;; TODO: See if we can use `icon_param` for this
.params get_icon_entry_params
id: .byte 0
addr: .addr 0
.endparams
;;; Used by DeskTop to pad `tmp_rect`
.params bbox_pad_tmp_rect
.addr tmp_rect
.word kIconBBoxPaddingX, kIconBBoxPaddingY
.endparams
;;; Used by DeskTop to compute bounding box for icons
DEFINE_RECT iconbb_rect, 0, 0, 0, 0
;;; Used by DeskTop to pad/expand `iconbb_rect`
.params bbox_pad_iconbb_rect
.addr iconbb_rect
.word kIconBBoxPaddingX, kIconBBoxPaddingY
.endparams
.params unionrects_tmp_iconbb
.addr tmp_rect
.addr iconbb_rect
.endparams
;;; Used by DeskTop to expand `iconbb_rect` in `ScrollManager`
.params unionrects_viewport_iconbb
.addr window_grafport+MGTK::GrafPort::maprect
.addr iconbb_rect
.endparams
;;; ============================================================
;;; Alerts
alert_params: .tag AlertParams
;;; ============================================================
.params menu_click_params ; used for MGTK::MenuKey as well
menu_id: .byte 0
item_num: .byte 0
which_key: .byte 0
key_mods: .byte 0
.endparams
.params checkitem_params
menu_id: .byte kMenuIdView
menu_item: .byte 0
check: .byte 0
.endparams
.params disablemenu_params
menu_id: .byte kMenuIdView
disable: .byte 0
.endparams
.params disableitem_params
menu_id: .byte 0
menu_item: .byte 0
disable: .byte 0
.endparams
;; Startup menu
DEFINE_MENU startup_menu, kMenuSizeStartup
@items: DEFINE_MENU_ITEM startup_menu_item_1
DEFINE_MENU_ITEM startup_menu_item_2
DEFINE_MENU_ITEM startup_menu_item_3
DEFINE_MENU_ITEM startup_menu_item_4
DEFINE_MENU_ITEM startup_menu_item_5
DEFINE_MENU_ITEM startup_menu_item_6
DEFINE_MENU_ITEM startup_menu_item_7
ASSERT_RECORD_TABLE_SIZE @items, kMenuSizeStartup, .sizeof(MGTK::MenuItem)
;;; ============================================================
;;; Device Names (populated at startup using templates in init.s)
device_name_table:
.repeat kMaxVolumes+1, i
.addr .ident(.sprintf("dev%ds", i))
.endrepeat
ASSERT_ADDRESS_TABLE_SIZE device_name_table, kMaxVolumes + 1
kDeviceNameLength = 1 + 16 + .strlen(res_string_sd_prefix_pattern)
.repeat kMaxVolumes+1, i
.ident(.sprintf("dev%ds", i)) := *
.res kDeviceNameLength, 0
.endrepeat
;;; Startup menu items (populated by slot scan at startup)
startup_menu_item_1: PASCAL_STRING res_string_menu_item_slot_pattern
startup_menu_item_2: PASCAL_STRING res_string_menu_item_slot_pattern
startup_menu_item_3: PASCAL_STRING res_string_menu_item_slot_pattern
startup_menu_item_4: PASCAL_STRING res_string_menu_item_slot_pattern
startup_menu_item_5: PASCAL_STRING res_string_menu_item_slot_pattern
startup_menu_item_6: PASCAL_STRING res_string_menu_item_slot_pattern
startup_menu_item_7: PASCAL_STRING res_string_menu_item_slot_pattern
kStartupMenuItemSlotOffset = res_const_menu_item_slot_pattern_offset1
;;; ============================================================
;; Shortcuts menu
DEFINE_MENU selector_menu, kSelectorMenuFixedItems
@items: DEFINE_MENU_ITEM label_add
DEFINE_MENU_ITEM label_edit
DEFINE_MENU_ITEM label_del
DEFINE_MENU_ITEM label_run, '0'
DEFINE_MENU_SEPARATOR
.repeat kMaxRunListEntries, i
DEFINE_MENU_ITEM run_list_entries + i * $10, ('0'+i+1)
.endrepeat
.assert 5 + kMaxRunListEntries = kMenuSizeSelector, error, "Menu size mismatch"
ASSERT_RECORD_TABLE_SIZE @items, kMenuSizeSelector, .sizeof(MGTK::MenuItem)
kMenuItemIdSelectorAdd = 1
kMenuItemIdSelectorEdit = 2
kMenuItemIdSelectorDelete = 3
kMenuItemIdSelectorRun = 4
ASSERT_EQUALS ::kMenuItemIdSelectorAdd, SelectorAction::add
ASSERT_EQUALS ::kMenuItemIdSelectorEdit, SelectorAction::edit
ASSERT_EQUALS ::kMenuItemIdSelectorDelete, SelectorAction::delete
ASSERT_EQUALS ::kMenuItemIdSelectorRun, SelectorAction::run
label_add:
PASCAL_STRING res_string_menu_item_add_entry ; also dialog title
label_edit:
PASCAL_STRING res_string_menu_item_edit_entry ; also dialog title
label_del:
PASCAL_STRING res_string_menu_item_delete_entry ; also dialog title
label_run:
PASCAL_STRING res_string_menu_item_run_entry ; also dialog title
kDAMenuItemSize = 19 ; length (1) + filename (15) + folder glyphs prefix (3)
;; Apple menu
DEFINE_MENU apple_menu, kAppleMenuFixedItems
@items: DEFINE_MENU_ITEM label_about
DEFINE_MENU_ITEM label_about_this_apply
DEFINE_MENU_SEPARATOR
.repeat kMaxDeskAccCount, i
DEFINE_MENU_ITEM desk_acc_names + i * kDAMenuItemSize
.endrepeat
.assert 3 + kMaxDeskAccCount = kMenuSizeApple, error, "Menu size mismatch"
ASSERT_RECORD_TABLE_SIZE @items, kMenuSizeApple, .sizeof(MGTK::MenuItem)
label_about:
PASCAL_STRING res_string_menu_item_about
label_about_this_apply:
PASCAL_STRING res_string_menu_item_about_this_apple
desk_acc_names:
.res kMaxDeskAccCount * kDAMenuItemSize, 0
window_title_addr_table:
.addr 0
.repeat ::kMaxDeskTopWindows,i
.addr .ident(.sprintf("winfo%dtitle",i+1))
.endrepeat
ASSERT_ADDRESS_TABLE_SIZE window_title_addr_table, kMaxDeskTopWindows + 1
;;; `win_view_by_table` is indexed by window id - 1; allow referencing
;;; the desktop (window id 0), which is always icon view.
.byte DeskTopSettings::kViewByIcon
win_view_by_table:
.res kMaxDeskTopWindows, 0
DEFINE_POINT pos_col, 0, 0
kColSize = 180 ; right-aligned
kColLock = 186
kColType = 200
kColDate = 231
;;; Scratch buffer visible to MGTK, primarily used for list view columns.
kTextBuffer2Len = 49
text_buffer2: .res kTextBuffer2Len, 0
file_record_ptr:
.addr 0
;;; ============================================================
.macro WINFO_DEFN id, label, buflabel
.params label
window_id: .byte id
options: .byte MGTK::Option::go_away_box | MGTK::Option::grow_box
title: .addr buflabel
hscroll: .byte MGTK::Scroll::option_normal
vscroll: .byte MGTK::Scroll::option_normal
hthumbmax: .byte kScrollThumbMax
hthumbpos: .byte 0
vthumbmax: .byte kScrollThumbMax
vthumbpos: .byte 0
status: .byte 0
reserved: .byte 0
mincontwidth: .word 170
mincontheight: .word 50
maxcontwidth: .word 545
maxcontheight: .word 175
port:
DEFINE_POINT viewloc, 20, 27
mapbits: .addr MGTK::screen_mapbits
mapwidth: .byte MGTK::screen_mapwidth
reserved2: .byte 0
DEFINE_RECT maprect, 0, 0, 440, 120
pattern: .res 8, $FF
colormasks: .byte MGTK::colormask_and, MGTK::colormask_or
DEFINE_POINT penloc, 0, 0
penwidth: .byte 1
penheight: .byte 1
penmode: .byte MGTK::pencopy
textback: .byte MGTK::textbg_white
textfont: .addr DEFAULT_FONT
nextwinfo: .addr 0
REF_WINFO_MEMBERS
.endparams
buflabel: .res 16, 0
.endmacro
.repeat ::kMaxDeskTopWindows,i
WINFO_DEFN i+1, .ident(.sprintf("winfo%d",i+1)), .ident(.sprintf("winfo%dtitle",i+1))
.endrepeat
;;; ============================================================
;;; Resources for window header (Items/K in disk/K available)
str_item_suffix:
PASCAL_STRING res_string_window_header_item_suffix
str_items_suffix:
PASCAL_STRING res_string_window_header_items_suffix
DEFINE_POINT header_text_pos, 0, 0
DEFINE_POINT header_text_delta, 0, 0
DEFINE_POINT header_line_left, 0, 0
DEFINE_POINT header_line_right, 0, 0
str_k_in_disk:
PASCAL_STRING res_string_window_header_k_used_suffix ; suffix for disk space used
str_k_available:
PASCAL_STRING res_string_window_header_k_available_suffix ; suffix for disk space available
str_from_int: ; populated by IntToString
PASCAL_STRING "000,000" ; 6 digits plus thousands separator
;;; Selection drag/drop icon/target, and coords
.params drag_drop_params
icon:
target: .byte 0
DEFINE_POINT coords, 0, 0
.endparams
;;; ============================================================
;;; Resources for scrollbar calculations
.params track_muldiv_params
number: .word 0 ; (in) populated dynamically
numerator: .word 0 ; (in) populated dynamically
denominator: .word kScrollThumbMax ; (in) constant
result: .word 0 ; (out)
remainder: .word 0 ; (out)
REF_MULDIV_MEMBERS
.endparams
.params setthumb_muldiv_params
number: .word 0 ; (in) populated dynamically
numerator: .word kScrollThumbMax ; (in) constant
denominator: .word 0 ; (in) populated dynamically
result: .word 0 ; (out)
remainder: .word 0 ; (out)
REF_MULDIV_MEMBERS
.endparams
;;; ============================================================
active_window_id:
.byte 0
kWindowToDirIconFree = $00 ; window not in use
kWindowToDirIconNone = $FF ; no icon
;;; Otherwise, dir (vol/folder) icon associated with window.
window_to_dir_icon_table:
.res kMaxDeskTopWindows, kWindowToDirIconFree
num_open_windows:
.byte 0
;;; ============================================================
solid_pattern:
.res 8, $FF
checkerboard_pattern:
.byte %01010101
.byte %10101010
.byte %01010101
.byte %10101010
.byte %01010101
.byte %10101010
.byte %01010101
.byte %10101010
;;; ============================================================
;;; Resources for clock on menu bar
DEFINE_POINT pos_clock, kScreenWidth - 11, 10
str_time:
PASCAL_STRING "00:00 XM"
str_4_spaces:
PASCAL_STRING " "
dow_strings:
PASCAL_STRING res_string_weekday_abbrev_1, 3
PASCAL_STRING res_string_weekday_abbrev_2, 3
PASCAL_STRING res_string_weekday_abbrev_3, 3
PASCAL_STRING res_string_weekday_abbrev_4, 3
PASCAL_STRING res_string_weekday_abbrev_5, 3
PASCAL_STRING res_string_weekday_abbrev_6, 3
PASCAL_STRING res_string_weekday_abbrev_7, 3
ASSERT_RECORD_TABLE_SIZE dow_strings, 7, 4
parsed_date:
.tag ParsedDateTime
;;; GrafPort used when drawing the clock
clock_grafport:
.tag MGTK::GrafPort
;;; Used to save the current GrafPort while drawing the clock.
.params getport_params
portptr: .addr 0
.endparams
;;; ============================================================
;;; Icon Resources - File Type Icons
;;; ============================================================
;;; These need to be visible to both Main and Aux. Main uses them for
;;; placing icons during creation, and Aux uses them when rendering
;;; the icons.
DEFINE_ICON_RESOURCE gen, generic_icon, 4, 25, 15, generic_mask
DEFINE_ICON_RESOURCE src, iigs_file_icon, 4, 25, 15, generic_mask
DEFINE_ICON_RESOURCE rel, rel_file_icon, 4, 27, 14, binary_mask
DEFINE_ICON_RESOURCE cmd, cmd_file_icon, 4, 27, 8, graphics_mask
DEFINE_ICON_RESOURCE txt, text_icon, 4, 25, 15, generic_mask
DEFINE_ICON_RESOURCE bin, binary_icon, 4, 27, 14, binary_mask
DEFINE_ICON_RESOURCE dir, folder_icon, 4, 27, 11, folder_mask
DEFINE_ICON_RESOURCE sdr, system_folder_icon, 4, 27, 11, folder_mask
DEFINE_ICON_RESOURCE sys, sys_icon, 4, 27, 17, sys_mask
DEFINE_ICON_RESOURCE bas, basic_icon, 4, 27, 14, basic_mask
DEFINE_ICON_RESOURCE int, intbasic_icon, 4, 27, 14, basic_mask
DEFINE_ICON_RESOURCE fot, graphics_icon, 4, 27, 12, graphics_mask
DEFINE_ICON_RESOURCE anm, video_icon, 4, 26, 12, graphics_mask
DEFINE_ICON_RESOURCE mus, music_icon, 4, 25, 15, generic_mask
DEFINE_ICON_RESOURCE snd, audio_icon, 4, 25, 15, generic_mask
DEFINE_ICON_RESOURCE tts, tts_icon, 4, 25, 15, generic_mask
DEFINE_ICON_RESOURCE adb, adb_icon, 4, 25, 15, generic_mask
DEFINE_ICON_RESOURCE awp, awp_icon, 4, 25, 15, generic_mask
DEFINE_ICON_RESOURCE asp, asp_icon, 4, 25, 15, generic_mask
DEFINE_ICON_RESOURCE arc, archive_icon, 4, 25, 14, archive_mask
DEFINE_ICON_RESOURCE lnk, lnk_icon, 3, 19, 10, graphics_mask
DEFINE_ICON_RESOURCE a2d, a2d_file_icon, 4, 25, 15, generic_mask
DEFINE_ICON_RESOURCE fnt, font_icon, 4, 25, 15, generic_mask
DEFINE_ICON_RESOURCE app, app_icon, 5, 34, 16, app_mask
DEFINE_ICON_RESOURCE var, var_file_icon, 4, 25, 15, generic_mask
;;; ============================================================
generic_icon: ; Generic
PIXELS "####################......"
PIXELS "#................#..##...."
PIXELS "#................#....##.."
PIXELS "#................#......##"
PIXELS "#................#########"
PIXELS "#........................#"
PIXELS "#........................#"
PIXELS "#........................#"
PIXELS "#........................#"
PIXELS "#........................#"
PIXELS "#........................#"
PIXELS "#........................#"
PIXELS "#........................#"
PIXELS "#........................#"
PIXELS "#........................#"
PIXELS "##########################"
;; Generic mask is re-used for multiple "document" types
generic_mask:
PIXELS "####################......"
PIXELS "######################...."
PIXELS "########################.."
PIXELS "##########################"
PIXELS "##########################"
PIXELS "##########################"
PIXELS "##########################"
PIXELS "##########################"
PIXELS "##########################"
PIXELS "##########################"
PIXELS "##########################"
PIXELS "##########################"
PIXELS "##########################"
PIXELS "##########################"
PIXELS "##########################"
PIXELS "##########################"
iigs_file_icon: ; IIgs-specific files
PIXELS "####################......"
PIXELS "#................#..##...."
PIXELS "#................#....##.."
PIXELS "#................#......##"
PIXELS "#.#####.#####....#########"
PIXELS "#...#.....#..............#"
PIXELS "#...#.....#..............#"
PIXELS "#...#.....#..............#"
PIXELS "#...#.....#....###...##..#"
PIXELS "#...#.....#...#.....#....#"
PIXELS "#...#.....#...#..##..##..#"
PIXELS "#...#.....#...#...#....#.#"
PIXELS "#.#####.#####..###...##..#"
PIXELS "#........................#"
PIXELS "#........................#"
PIXELS "##########################"
;; shares `generic_mask`
rel_file_icon: ; Relocatable
PIXELS ".............##............."
PIXELS "...........##..##..........."
PIXELS ".........##......##........."
PIXELS ".......##..........##......."
PIXELS ".....##..............##....."
PIXELS "...##..####..####.#....##..."
PIXELS ".##....#...#.#....#......##."
PIXELS "#......#####.###..#........#"
PIXELS ".##....#..#..#....#......##."
PIXELS "...##..#...#.####.####.##..."
PIXELS ".....##..............##....."
PIXELS ".......##..........##......."
PIXELS ".........##......##........."
PIXELS "...........##..##..........."
PIXELS ".............##............."
;; shares binary_mask
cmd_file_icon: ; ProDOS Command
PIXELS "............................"
PIXELS "..##########................"
PIXELS "........####....##..##..##.."
PIXELS "........####......##..##...."
PIXELS "........####....##..##..##.."
PIXELS "........####......##..##...."
PIXELS "........####....##..##..##.."
PIXELS "..##########................"
PIXELS "............................"
;; shares top part of graphics_mask
text_icon: ; Text File
PIXELS "####################......"
PIXELS "#................#..##...."
PIXELS "#.....###.####.###....##.."
PIXELS "#................#......##"
PIXELS "#..###.##.###.##.#########"
PIXELS "#........................#"
PIXELS "#..#####.###.######......#"
PIXELS "#........................#"
PIXELS "#........................#"
PIXELS "#.....#####.###.##.####..#"
PIXELS "#........................#"
PIXELS "#..##.####.###.##.#####..#"
PIXELS "#........................#"
PIXELS "#..#####.##.##.###.####..#"
PIXELS "#........................#"
PIXELS "##########################"
;; shares generic_mask
binary_icon: ; Binary File
PIXELS ".............##............."
PIXELS "...........##..##..........."
PIXELS ".........##......##........."
PIXELS ".......##..........##......."
PIXELS ".....##..............##....."
PIXELS "...##....##.....##.....##..."
PIXELS ".##.....#..#...#.#.......##."
PIXELS "#.......#..#.....#.........#"
PIXELS ".##.....#..#.....#.......##."
PIXELS "...##....##......#.....##..."
PIXELS ".....##..............##....."
PIXELS ".......##..........##......."
PIXELS ".........##......##........."
PIXELS "...........##..##..........."
PIXELS ".............##............."
binary_mask:
PIXELS "............................"
PIXELS ".............##............."
PIXELS "...........######..........."
PIXELS ".........##########........."
PIXELS ".......##############......."
PIXELS ".....##################....."
PIXELS "...######################..."
PIXELS ".##########################."
PIXELS "...######################..."
PIXELS ".....##################....."
PIXELS ".......##############......."
PIXELS ".........##########........."
PIXELS "...........######..........."
PIXELS ".............##............."
PIXELS "............................"
folder_icon: ; Folder
PIXELS "..###########..............."
PIXELS ".#...........#.............."
PIXELS ".##########################."
PIXELS "#..........................#"
PIXELS "#..........................#"
PIXELS "#..........................#"
PIXELS "#..........................#"
PIXELS "#..........................#"
PIXELS "#..........................#"
PIXELS "#..........................#"
PIXELS "#..........................#"
PIXELS ".##########################."
system_folder_icon: ; System Folder
PIXELS "..###########..............."
PIXELS ".#...........#.............."
PIXELS ".##########################."
PIXELS "#..............##..........#"
PIXELS "#.............##...........#"
PIXELS "#..........##...##.........#"
PIXELS "#........###########.......#"
PIXELS "#.......#########..........#"
PIXELS "#.......############.......#"
PIXELS "#........##########........#"
PIXELS "#.........###..###.........#"
PIXELS ".##########################."
folder_mask:
PIXELS "..###########..............."
PIXELS ".#############.............."
PIXELS ".##########################."
PIXELS "############################"
PIXELS "############################"
PIXELS "############################"
PIXELS "############################"
PIXELS "############################"
PIXELS "############################"
PIXELS "############################"
PIXELS "############################"
PIXELS ".##########################."
sys_icon: ; System (no .SYSTEM suffix)
PIXELS ".##########################."
PIXELS "##........................##"
PIXELS "##..####################..##"
PIXELS "##..##................##..##"
PIXELS "##..##.##..##..##.....##..##"
PIXELS "##..##................##..##"
PIXELS "##..##.##..##.........##..##"
PIXELS "##..##................##..##"
PIXELS "##..##................##..##"
PIXELS "##..####################..##"
PIXELS "##........................##"
PIXELS ".##########################."
PIXELS "##........................##"
PIXELS "##..##....................##"
PIXELS "##........................##"
PIXELS "############################"
PIXELS "##........................##"
PIXELS ".##########################."
sys_mask:
PIXELS "............................"
PIXELS "..########################.."
PIXELS "..########################.."
PIXELS "..########################.."
PIXELS "..########################.."
PIXELS "..########################.."
PIXELS "..########################.."
PIXELS "..########################.."
PIXELS "..########################.."
PIXELS "..########################.."
PIXELS "..########################.."
PIXELS "............................"
PIXELS "..########################.."
PIXELS "..########################.."
PIXELS "..########################.."
PIXELS "..########################.."
PIXELS "..########################.."
PIXELS "............................"
basic_icon: ; BASIC Program
PIXELS ".............##............."
PIXELS "...........##..##..........."
PIXELS ".........##......##........."
PIXELS ".......##..........##......."
PIXELS "............................"
PIXELS ".#####...###...####.#..####."
PIXELS ".#....#.#...#.#.....#.#....."
PIXELS ".#####..#####..###..#.#....."
PIXELS ".#....#.#...#.....#.#.#....."
PIXELS ".#####..#...#.####..#..####."
PIXELS "............................"
PIXELS ".......##..........##......."
PIXELS ".........##......##........."
PIXELS "...........##..##..........."
PIXELS ".............##............."
basic_mask:
PIXELS "............................"
PIXELS ".............##............."
PIXELS "...........######..........."
PIXELS ".........##########........."
PIXELS "############################"
PIXELS "############################"
PIXELS "############################"
PIXELS "############################"
PIXELS "############################"
PIXELS "############################"
PIXELS "############################"
PIXELS ".........##########........."
PIXELS "...........######..........."
PIXELS ".............##............."
PIXELS "............................"
intbasic_icon:
PIXELS ".............##............."
PIXELS "...........##..##..........."
PIXELS ".........##......##........."
PIXELS ".......##..........##......."
PIXELS "............................"
PIXELS ".##....####....##..########."
PIXELS ".##....##.##...##.....##...."
PIXELS ".###...##..##..###....###..."
PIXELS ".###...###..##.###....###..."
PIXELS ".###...###...#####....###..."
PIXELS "............................"
PIXELS ".......##..........##......."
PIXELS ".........##......##........."
PIXELS "...........##..##..........."
PIXELS ".............##............."
;; shares `basic_mask`
graphics_icon: ; Graphics
PIXELS "############################"
PIXELS "#..........................#"
PIXELS "#...##.....................#"
PIXELS "#..####............##......#"
PIXELS "#...##............####.....#"
PIXELS "#.........##.....######....#"
PIXELS "#.......######..########...#"
PIXELS "#....####################..#"
PIXELS "#..######################..#"
PIXELS "#..######################..#"
PIXELS "#..######################..#"
PIXELS "#..........................#"
PIXELS "############################"
graphics_mask:
PIXELS "############################"
PIXELS "############################"
PIXELS "############################"
PIXELS "############################"
PIXELS "############################"
PIXELS "############################"
PIXELS "############################"
PIXELS "############################"
PIXELS "############################"
PIXELS "############################"
PIXELS "############################"
PIXELS "############################"
PIXELS "############################"
video_icon:
PIXELS "###########################"
PIXELS "##...##...##...##...##...##"
PIXELS "###########################"
PIXELS "#.........................#"
PIXELS "#.........##..............#"
PIXELS "#.........#####...........#"
PIXELS "#.........#######.........#"
PIXELS "#.........#####...........#"
PIXELS "#.........##..............#"
PIXELS "#.........................#"
PIXELS "###########################"
PIXELS "##...##...##...##...##...##"
PIXELS "###########################"
;; shares left part of graphics_mask
music_icon: ; Music
PIXELS "####################......"
PIXELS "#................#..##...."
PIXELS "#................#....##.."
PIXELS "#................#......##"
PIXELS "#................#########"
PIXELS "#............#####.......#"
PIXELS "#.......##########.......#"
PIXELS "#.......######...#.......#"
PIXELS "#.......#........#.......#"
PIXELS "#.......#........#.......#"
PIXELS "#.......#.....####.......#"
PIXELS "#....####....#####.......#"
PIXELS "#...#####.....###........#"
PIXELS "#....###.................#"
PIXELS "#........................#"
PIXELS "##########################"
audio_icon:
PIXELS "####################......"
PIXELS "#................#..##...."
PIXELS "#................#....##.."
PIXELS "#................#......##"
PIXELS "#................#########"
PIXELS "#........................#"
PIXELS "#........##........#.....#"
PIXELS "#......##.#.....#...#....#"
PIXELS "#..####...#..#...#...#...#"
PIXELS "#..#......#...#..#...#...#"
PIXELS "#..#......#...#..#...#...#"
PIXELS "#..####...#..#...#...#...#"
PIXELS "#......##.#.....#...#....#"
PIXELS "#........##........#.....#"
PIXELS "#........................#"
PIXELS "##########################"
tts_icon: ; Text-to-Speech
PIXELS "####################......"
PIXELS "#..........#.....#..##...."
PIXELS "#..........#.....#....##.."
PIXELS "#...##.....#.....#......##"
PIXELS "#...##.....#.....#########"
PIXELS "#..........#.............#"
PIXELS "#..........#.............#"
PIXELS "#......#####.......#.....#"
PIXELS "#........#......#...#....#"
PIXELS "#........#...#...#...#...#"
PIXELS "#....#####....#..#...#...#"
PIXELS "#........#....#..#...#...#"
PIXELS "#........#...#...#...#...#"
PIXELS "##########......#...#....#"
PIXELS "#..................#.....#"
PIXELS "##########################"
adb_icon: ; AppleWorks Database
PIXELS "####################......"
PIXELS "#................#..##...."
PIXELS "#...##...#...#...#....##.."
PIXELS "#..#..#..#.#.#...#......##"
PIXELS "#..####..#.#.#...#########"
PIXELS "#..#..#...#.#............#"
PIXELS "#........................#"
PIXELS "#..######..#####..#####..#"
PIXELS "#........................#"
PIXELS "#..####################..#"
PIXELS "#........................#"
PIXELS "#..######..#####..#####..#"
PIXELS "#........................#"
PIXELS "#..######..#####..#####..#"
PIXELS "#........................#"
PIXELS "##########################"
;; shares `generic_mask`
awp_icon: ; AppleWorks Word Processing
PIXELS "####################......"
PIXELS "#................#..##...."
PIXELS "#...##...#...#...#....##.."
PIXELS "#..#..#..#.#.#...#......##"
PIXELS "#..####..#.#.#...#########"
PIXELS "#..#..#...#.#............#"
PIXELS "#........................#"
PIXELS "#......####..###..#####..#"
PIXELS "#........................#"
PIXELS "#...####..#####..#####...#"
PIXELS "#........................#"
PIXELS "#...######..#####..###...#"
PIXELS "#........................#"
PIXELS "#...###..###..####..##...#"
PIXELS "#........................#"
PIXELS "##########################"
asp_icon: ; AppleWorks Spreadsheet
PIXELS "####################......"
PIXELS "#................#..##...."
PIXELS "#...##...#...#...#....##.."
PIXELS "#..#..#..#.#.#...#......##"
PIXELS "#..####..#.#.#...#########"
PIXELS "#..#..#...#.#............#"
PIXELS "#........................#"
PIXELS "#...##################...#"
PIXELS "#...##..#..#..#..#..##...#"
PIXELS "#...##################...#"
PIXELS "#...##..#..#..#..#..##...#"
PIXELS "#...##################...#"
PIXELS "#...##..#..#..#..#..##...#"
PIXELS "#...##################...#"
PIXELS "#........................#"
PIXELS "##########################"
;; shares `generic_mask`
archive_icon: ; Archive
PIXELS ".......##############....."
PIXELS ".......#...........#.##..."
PIXELS "....####...........#...##."
PIXELS "....#..#...........######."
PIXELS ".####..#................#."
PIXELS ".#..#..#................#."
PIXELS "##########################"
PIXELS "##########################"
PIXELS "##########################"
PIXELS ".#..#..#................#."
PIXELS ".#..#..##################."
PIXELS ".#..#................#...."
PIXELS ".#..##################...."
PIXELS ".#................#......."
PIXELS ".##################......."
archive_mask:
PIXELS ".......##############....."
PIXELS ".......################..."
PIXELS "....#####################."
PIXELS "....#####################."
PIXELS ".########################."
PIXELS ".########################."
PIXELS "##########################"
PIXELS "##########################"
PIXELS "##########################"
PIXELS ".########################."
PIXELS ".########################."
PIXELS ".#####################...."
PIXELS ".#####################...."
PIXELS ".##################......."
PIXELS ".##################......."
a2d_file_icon: ; Desk Accessory
PIXELS "####################......"
PIXELS "#................#..##...."
PIXELS "#................#....##.."
PIXELS "#................#......##"
PIXELS "#................#########"
PIXELS "#............##..........#"
PIXELS "#...........##...........#"
PIXELS "#.......###...###........#"
PIXELS "#.....#############......#"
PIXELS "#....###########.........#"
PIXELS "#....###########.........#"
PIXELS "#....##############......#"
PIXELS "#.....############.......#"
PIXELS "#......####..####........#"
PIXELS "#........................#"
PIXELS "##########################"
;; shares `generic_mask`
font_icon: ; Font
PIXELS "####################......"
PIXELS "#................#..##...."
PIXELS "#................#....##.."
PIXELS "#................#......##"
PIXELS "#......##........#########"
PIXELS "#......##................#"
PIXELS "#.....####...............#"
PIXELS "#.....#.##........####...#"
PIXELS "#....##..##......##.###..#"
PIXELS "#....#...##..........##..#"
PIXELS "#...########.....######..#"
PIXELS "#...#.....##....##...##..#"
PIXELS "#..##......##...##...##..#"
PIXELS "#.####....####...#######.#"
PIXELS "#........................#"
PIXELS "##########################"
;; shares `generic_mask`
app_icon: ; System (with .SYSTEM suffix)
PIXELS "................##................"
PIXELS "..............##..##.............."
PIXELS "............##......##............"
PIXELS "..........##..........##.........."
PIXELS "........##..............##........"
PIXELS "......##..................##......"
PIXELS "....##......................##...."
PIXELS "..##................######....##.."
PIXELS "##................##......##....##"
PIXELS "..##............##...###....####.."
PIXELS "....##.....###############....####"
PIXELS "......##.......##....##.......####"
PIXELS "........##.......###..........####"
PIXELS "..........##........##############"
PIXELS "............##......##........####"
PIXELS "..............##..##.............."
PIXELS "................##................"
app_mask:
PIXELS "................##................"
PIXELS "..............######.............."
PIXELS "............##########............"
PIXELS "..........##############.........."
PIXELS "........##################........"
PIXELS "......######################......"
PIXELS "....##########################...."
PIXELS "..##############################.."
PIXELS "##################################"
PIXELS "..###############################."
PIXELS "....############################.."
PIXELS "......##########################.."
PIXELS "........##################..####.."
PIXELS "..........###############........."
PIXELS "............##########............"
PIXELS "..............######.............."
PIXELS "................##................"
var_file_icon: ; Applesoft/IntBASIC variables
PIXELS "####################......"
PIXELS "#................#..##...."
PIXELS "#...###..........#....##.."
PIXELS "#..#...#..#####..#......##"
PIXELS "#..#####.........#########"
PIXELS "#..#...#..#####..........#"
PIXELS "#..#...#.................#"
PIXELS "#...........#............#"
PIXELS "#..####....####..........#"
PIXELS "#..#...#..#.#....#####...#"
PIXELS "#..####....###...........#"
PIXELS "#..#...#....#.#..#####...#"
PIXELS "#..####...####...........#"
PIXELS "#...........#............#"
PIXELS "#........................#"
PIXELS "##########################"
lnk_icon:
PIXELS "####################"
PIXELS "#..................#"
PIXELS "#......########....#"
PIXELS "#........######....#"
PIXELS "#......########....#"
PIXELS "#....######..##....#"
PIXELS "#....####..........#"
PIXELS "#....##............#"
PIXELS "#......##..........#"
PIXELS "#..................#"
PIXELS "####################"
;;; Small Icons - use for "View > by XXXX"
;;; Same visibility rules as above.
;;; NOTE: Keep in sync with kGlyphFile* and kGlyphFolder* in the system fonts.
DEFINE_ICON_RESOURCE sm_gen, generic_sm_icon, 2, 13, 7, generic_sm_mask
DEFINE_ICON_RESOURCE sm_dir, folder_sm_icon, 2, 13, 6, folder_sm_mask
generic_sm_icon:
PIXELS "..######......"
PIXELS "..#....###...."
PIXELS "..#....#####.."
PIXELS "..#........#.."
PIXELS "..#........#.."
PIXELS "..#........#.."
PIXELS "..#........#.."
PIXELS "..##########.."
generic_sm_mask:
PIXELS "..######......"
PIXELS "..########...."
PIXELS "..##########.."
PIXELS "..##########.."
PIXELS "..##########.."
PIXELS "..##########.."
PIXELS "..##########.."
PIXELS "..##########.."
folder_sm_icon:
PIXELS ".#####........"
PIXELS "#.....#######."
PIXELS "#............#"
PIXELS "#............#"
PIXELS "#............#"
PIXELS "#............#"
PIXELS "##############"
folder_sm_mask:
PIXELS ".#####........"
PIXELS "#############."
PIXELS "##############"
PIXELS "##############"
PIXELS "##############"
PIXELS "##############"
PIXELS "##############"
;;; ============================================================
;;; Icon Resources - Volume Type Icons
;;; ============================================================
;;; These need to be visible to both Main and Aux. Main uses them for
;;; placing icons during creation, and Aux uses them when rendering
;;; the icons.
;;; 5.25" Floppy Disk
DEFINE_ICON_RESOURCE floppy140_icon, floppy140_pixels, 4, 26, 14, floppy140_mask
;;; RAM Disk
DEFINE_ICON_RESOURCE ramdisk_icon, ramdisk_pixels, 6, 39, 11, ramdisk_mask
;;; 3.5" Floppy Disk
DEFINE_ICON_RESOURCE floppy800_icon, floppy800_pixels, 3, 20, 11, floppy800_mask
;;; Hard Disk
DEFINE_ICON_RESOURCE profile_icon, profile_pixels, 8, 52, 9, profile_mask
;;; File Share
DEFINE_ICON_RESOURCE fileshare_icon, fileshare_pixels, 5, 34, 14, fileshare_mask
;;; CD-ROM
DEFINE_ICON_RESOURCE cdrom_icon, cdrom_pixels, 4, 26, 14, cdrom_mask
;;; Trash Can
kTrashIconWidth = 23
kTrashIconHeight = 18
DEFINE_ICON_RESOURCE trash_icon, trash_pixels, 4, kTrashIconWidth-1, kTrashIconHeight-1, trash_mask
;;; ============================================================
floppy140_pixels: ; 5.25" Floppy Disk
PIXELS "###########################"
PIXELS "##..........###..........##"
PIXELS "##..........###..........##"
PIXELS "##..........###..........##"
PIXELS "##..........###..........##"
PIXELS "##.......................##"
PIXELS "##..........###..........##"
PIXELS "##.........#####.........##"
PIXELS "##..........###..........##"
PIXELS "##.......................##"
PIXELS "##.......................##"
PIXELS "..##.....................##"
PIXELS "##.......................##"
PIXELS "##.......................##"
PIXELS "###########################"
floppy140_mask:
PIXELS "###########################"
PIXELS "###########################"
PIXELS "###########################"
PIXELS "###########################"
PIXELS "###########################"
PIXELS "###########################"
PIXELS "###########################"
PIXELS "###########################"
PIXELS "###########################"
PIXELS "###########################"
PIXELS "###########################"
PIXELS "..#########################"
PIXELS "###########################"
PIXELS "###########################"
PIXELS "###########################"
ramdisk_pixels: ; RAM Disk
PIXELS "...........#############################"
PIXELS "........###...........................##"
PIXELS ".....###..............................##"
PIXELS "..###.................................##"
PIXELS "##.........#####...####..##.....##....##"
PIXELS "##.........##..##.##..##.####.####....##"
PIXELS "##.........#####..######.##.###.##....##"
PIXELS "##.........##..##.##..##.##.....##....##"
PIXELS "##....................................##"
PIXELS "########################..##..##..##..##"
PIXELS "......................##..##..##..##..##"
PIXELS "......................##################"
ramdisk_mask:
PIXELS "...........#############################"
PIXELS "........################################"
PIXELS ".....###################################"
PIXELS "..######################################"
PIXELS "########################################"
PIXELS "########################################"
PIXELS "########################################"
PIXELS "########################################"
PIXELS "########################################"
PIXELS "########################################"
PIXELS "......................##################"
PIXELS "......................##################"
floppy800_pixels: ; 3.5" Floppy Disk
PIXELS "####################."
PIXELS "##...##.......##..###"
PIXELS "##...##.......##...##"
PIXELS "##...###########...##"
PIXELS "##.................##"
PIXELS "##.................##"
PIXELS "##..#############..##"
PIXELS "##..##.........##..##"
PIXELS "##..##.........##..##"
PIXELS "##..##.........##..##"
PIXELS "##..##.........##..##"
PIXELS "#####################"
floppy800_mask:
PIXELS "####################."
PIXELS "#####################"
PIXELS "#####################"
PIXELS "#####################"
PIXELS "#####################"
PIXELS "#####################"
PIXELS "#####################"
PIXELS "#####################"
PIXELS "#####################"
PIXELS "#####################"
PIXELS "#####################"
PIXELS "#####################"
profile_pixels: ; Hard Disk
PIXELS ".###################################################."
PIXELS "##.................................................##"
PIXELS "##.................................................##"
PIXELS "##.................................................##"
PIXELS "##...###...........................................##"
PIXELS "##.................................................##"
PIXELS "##.................................................##"
PIXELS "##.................................................##"
PIXELS ".###################################################."
PIXELS "....###.......................................###...."
profile_mask:
PIXELS ".###################################################."
PIXELS "#####################################################"
PIXELS "#####################################################"
PIXELS "#####################################################"
PIXELS "#####################################################"
PIXELS "#####################################################"
PIXELS "#####################################################"
PIXELS "#####################################################"
PIXELS ".###################################################."
PIXELS "....###.......................................###...."
fileshare_pixels: ; File Share / Network Drive
PIXELS "................##..#########......"
PIXELS "..............##..##........###...."
PIXELS "..########..##......##......#####.."
PIXELS "..##.....#######......##.......##.."
PIXELS "..##............##......##.....##.."
PIXELS "..##............##....##.......##.."
PIXELS "..##............##..##.........##.."
PIXELS ".#################################."
PIXELS ".##.............................##."
PIXELS "..###############################.."
PIXELS "..................##..##..........."
PIXELS ".................###..###.........."
PIXELS "##..##############......#######..##"
PIXELS "....................##............."
PIXELS "##..################..#########..##"
fileshare_mask:
PIXELS "................##..#########......"
PIXELS "..............#################...."
PIXELS "..########..#####################.."
PIXELS "..###############################.."
PIXELS "..###############################.."
PIXELS "..###############################.."
PIXELS "..###############################.."
PIXELS ".#################################."
PIXELS ".#################################."
PIXELS "..###############################.."
PIXELS "..................######..........."
PIXELS ".................########.........."
PIXELS "###################################"
PIXELS "###################################"
PIXELS "####################..#############"
cdrom_pixels:
PIXELS "..........#######.........."
PIXELS "......####.......####......"
PIXELS "....##.....#####.....##...."
PIXELS "..##....##.............##.."
PIXELS ".#....#.....###..........#."
PIXELS ".#.......#...............#."
PIXELS "#...#.......###.......#...#"
PIXELS "#......#...#...#...#......#"
PIXELS "#...#.......###.......#...#"
PIXELS ".#...............#.......#."
PIXELS ".#..........###.....#....#."
PIXELS "..##.............##....##.."
PIXELS "....##.....#####.....##...."
PIXELS "......####.......####......"
PIXELS "..........#######.........."
cdrom_mask:
PIXELS "..........#######.........."
PIXELS "......###############......"
PIXELS "....###################...."
PIXELS "..#######################.."
PIXELS ".#########################."
PIXELS ".#########################."
PIXELS "###########################"
PIXELS "###########################"
PIXELS "###########################"
PIXELS ".#########################."
PIXELS ".#########################."
PIXELS "..#######################.."
PIXELS "....###################...."
PIXELS "......###############......"
PIXELS "..........#######.........."
trash_pixels: ; Trash Can
PIXELS ".......#########......."
PIXELS "......##.......##......"
PIXELS "#######################"
PIXELS "##...................##"
PIXELS "#######################"
PIXELS ".##.................##."
PIXELS ".##..#....#....#....##."
PIXELS ".##...#....#....#...##."
PIXELS ".##...#....#....#...##."
PIXELS ".##...#....#....#...##."
PIXELS ".##...#....#....#...##."
PIXELS ".##...#....#....#...##."
PIXELS ".##...#....#....#...##."
PIXELS ".##...#....#....#...##."
PIXELS ".##...#....#....#...##."
PIXELS ".##..#....#....#....##."
PIXELS ".##.................##."
PIXELS ".#####################."
trash_mask:
PIXELS ".......#########......."
PIXELS "......###########......"
PIXELS "#######################"
PIXELS "#######################"
PIXELS "#######################"
PIXELS ".#####################."
PIXELS ".#####################."
PIXELS ".#####################."
PIXELS ".#####################."
PIXELS ".#####################."
PIXELS ".#####################."
PIXELS ".#####################."
PIXELS ".#####################."
PIXELS ".#####################."
PIXELS ".#####################."
PIXELS ".#####################."
PIXELS ".#####################."
PIXELS ".#####################."
;;; ============================================================
;;; (there's enough room here for 128 files at up to 26 bytes each; index 0 not used)
icon_entries:
.assert ($10000 - *) >= (kMaxIconCount+1) * .sizeof(IconEntry), error, "Not enough room for icons"
|
a2stuff/a2d
| 3,985
|
src/desktop/desktop.s
|
.include "../config.inc"
.include "apple2.inc"
.include "apple2.mac"
.include "opcodes.inc"
.include "../inc/apple2.inc"
.include "../inc/macros.inc"
.include "../inc/prodos.inc"
.include "../inc/smartport.inc"
.include "../mgtk/mgtk.inc"
.include "../toolkits/icontk.inc"
.include "../toolkits/letk.inc"
.include "../toolkits/btk.inc"
.include "../toolkits/lbtk.inc"
.include "../toolkits/optk.inc"
.include "../lib/alert_dialog.inc"
.include "../common.inc"
.include .concat("../desk.acc/res/filenames.res.", kBuildLang)
;;; ============================================================
;;; File Structure
;;; ============================================================
;;; DeskTop is broken into various segments plus dynamically
;;; loaded overlays, all stored in one file. This section
;;; defines the file offsets, load addresses and lengths of each
;;; segment and offset
;; Bootstrap is at $0-$200 in file
kLoaderOffset = $200
;; Segments
INITSEG kLoaderOffset
DEFSEG SegmentLoader, $2000, $0200
DEFSEG SegmentDeskTopAux, $4000, $8000
DEFSEG SegmentDeskTopLC, $D000, $2100
DEFSEG SegmentDeskTopMain, $4000, $6E00
DEFSEG SegmentInitializer, $0800, $0800
DEFSEG SegmentInvoker, $0290, $0160
;; Dynamically loaded overlays
DEFSEG OverlayFormatErase, $0800, $0F00
DEFSEG OverlayShortcutPick, $5000, $0800
DEFSEG OverlayFileDialog, $6000, $0A00
DEFSEG OverlayFileCopy, $7000, $0100
DEFSEG OverlayShortcutEdit, $7000, $0300
;;; These pseudo-overlays restore DeskTop after overlays are used
;;; Restore after OverlayShortcutPick has been used
kOverlayDeskTopRestoreSPLength = kOverlayShortcutPickLength
kOverlayDeskTopRestoreSPAddress = kOverlayShortcutPickAddress
kOverlayDeskTopRestoreSPOffset = kSegmentDeskTopMainOffset + (kOverlayDeskTopRestoreSPAddress - kSegmentDeskTopMainAddress)
;;; Restore after OverlayFileDialog and either OverlayFileCopy or OverlayShortcutEdit has been used
kOverlayDeskTopRestoreFDLength = $1400
kOverlayDeskTopRestoreFDAddress = kOverlayFileDialogAddress
kOverlayDeskTopRestoreFDOffset = kSegmentDeskTopMainOffset + (kOverlayDeskTopRestoreFDAddress - kSegmentDeskTopMainAddress)
.assert (kOverlayFileCopyAddress + kOverlayFileCopyLength) <= (kOverlayDeskTopRestoreFDAddress + kOverlayDeskTopRestoreFDLength), error, "restore coverage"
.assert (kOverlayShortcutEditAddress + kOverlayShortcutEditLength) <= (kOverlayDeskTopRestoreFDAddress + kOverlayDeskTopRestoreFDLength), error, "restore coverage"
;;; Restore after buffer is used by Desk Accessories
kOverlayDeskTopRestoreBufferLength = kOverlayBufferSize
kOverlayDeskTopRestoreBufferAddress = OVERLAY_BUFFER
kOverlayDeskTopRestoreBufferOffset = kSegmentDeskTopMainOffset + (kOverlayDeskTopRestoreBufferAddress - kSegmentDeskTopMainAddress)
;;; ============================================================
;;; DeskTop module
;;; ============================================================
RESOURCE_FILE "desktop.res"
.include "../desktop/desktop.inc"
.include "internal.inc"
.define QR_LOADSTRING res_string_status_loading_desktop
.define QR_FILENAME kPathnameDeskTop
.include "../lib/bootstrap.s"
;; Ensure loader.starts at correct offset from start of file.
.res kSegmentLoaderOffset - (.sizeof(InstallAsQuit) + .sizeof(QuitRoutine))
;; Segments
.include "loader.s"
.include "auxmem.s"
.include "lc.s"
.include "main.s"
.include "init.s"
.include "../lib/invoker.s"
;; Overlays
.include "ovl_format_erase.s"
.include "ovl_selector_pick.s"
.include "ovl_file_dialog.s"
.include "ovl_file_copy.s"
.include "ovl_selector_edit.s"
|
a2stuff/a2d
| 17,750
|
src/toolkits/btk.s
|
;;; ============================================================
;;; Button ToolKit
;;; ============================================================
.scope btk
BTKEntry := *
;;; ============================================================
;;; Zero Page usage (saved/restored around calls)
zp_start := $50
;; BTK doesn't have "command data" - just the button record
kMaxTmpSpace = 10
PARAM_BLOCK, zp_start
;;; Points at call parameters (i.e. ButtonRecord)
params_addr .addr
;;; A temporary copy of the control record
cache .tag BTK::ButtonRecord
;;; Used in `TrackImpl`
down_flag .byte
zp_scratch .res kMaxTmpSpace
;;; For size calculation, not actually used
zp_end .byte
END_PARAM_BLOCK
.assert zp_end <= $78, error, "too big"
kBytesToSave = zp_end - zp_start
;; Aliases for the cache's members:
window_id := cache + BTK::ButtonRecord::window_id
a_label := cache + BTK::ButtonRecord::a_label
a_shortcut := cache + BTK::ButtonRecord::a_shortcut
rect := cache + BTK::ButtonRecord::rect
state := cache + BTK::ButtonRecord::state
;;; ============================================================
.assert BTKEntry = Dispatch, error, "dispatch addr"
.proc Dispatch
;; Adjust stack/stash
pla
sta params_lo
clc
adc #<3
tax
pla
sta params_hi
adc #>3
pha
txa
pha
;; Save ZP
PUSH_BYTES kBytesToSave, zp_start
;; Point `params_addr` at the call site
params_lo := *+1
lda #SELF_MODIFIED_BYTE
sta params_addr
params_hi := *+1
lda #SELF_MODIFIED_BYTE
sta params_addr+1
;; Grab command number
ldy #1 ; Note: rts address is off-by-one
lda (params_addr),y
tax
copylohi jump_table_lo,x, jump_table_hi,x, dispatch
;; Point `params_addr` at actual params
iny
lda (params_addr),y
tax
iny
lda (params_addr),y
sta params_addr+1
stx params_addr
;; Cache static copy of the record in `cache`, for convenience
ldy #.sizeof(BTK::ButtonRecord)-1
: copy8 (params_addr),y, cache,y
dey
bpl :-
;; Invoke the command
dispatch := *+1
jsr SELF_MODIFIED
tay ; A = result
;; Restore ZP
POP_BYTES kBytesToSave, zp_start
tya ; A = result
rts
jump_table_lo:
.lobytes DrawImpl
.lobytes UpdateImpl
.lobytes FlashImpl
.lobytes HiliteImpl
.lobytes TrackImpl
.ifndef BTK_SHORT
.lobytes RadioDrawImpl
.lobytes RadioUpdateImpl
.lobytes CheckboxDrawImpl
.lobytes CheckboxUpdateImpl
.endif ; BTK_SHORT
jump_table_hi:
.hibytes DrawImpl
.hibytes UpdateImpl
.hibytes FlashImpl
.hibytes HiliteImpl
.hibytes TrackImpl
.ifndef BTK_SHORT
.hibytes RadioDrawImpl
.hibytes RadioUpdateImpl
.hibytes CheckboxDrawImpl
.hibytes CheckboxUpdateImpl
.endif ; BTK_SHORT
ASSERT_EQUALS *-jump_table_hi, jump_table_hi-jump_table_lo
.endproc ; Dispatch
;;; ============================================================
penOR: .byte MGTK::penOR
penXOR: .byte MGTK::penXOR
solid_pattern:
.byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF
checkerboard_pattern:
.byte $55, $AA, $55, $AA, $55, $AA, $55, $AA
.params shrink_rect
.addr rect
.word AS_WORD(-1), AS_WORD(-1)
.endparams
.params grow_rect
.addr rect
.word 1, 1
.endparams
;;; ============================================================
;;; Shadows params in Selector's `app` and Disk Copy's `auxlc` scopes.
;;; TODO: Rework scoping to eliminate this.
SUPPRESS_SHADOW_WARNING
.params getwinport_params
window_id: .byte 0
port: .addr grafport_win
.endparams
UNSUPPRESS_SHADOW_WARNING
grafport_win: .tag MGTK::GrafPort
;;; If obscured, execution will not return to the caller.
.proc _SetPort
;; Set the port
lda window_id
beq ret
sta getwinport_params::window_id
MGTK_CALL MGTK::GetWinPort, getwinport_params
bne obscured
MGTK_CALL MGTK::SetPort, grafport_win
beq ret
obscured:
pla
pla
ret:
rts
.endproc ; _SetPort
;;; ============================================================
.proc DrawImpl
jsr _SetPort
FALL_THROUGH_TO UpdateImpl
.endproc ; DrawImpl
;;; ============================================================
.proc UpdateImpl
MGTK_CALL MGTK::SetPattern, solid_pattern
MGTK_CALL MGTK::SetPenMode, penXOR
MGTK_CALL MGTK::FrameRect, rect
beq btk::HiliteImpl::skip_port ; always
.endproc ; UpdateImpl
;;; ============================================================
.proc FlashImpl
;; If disabled, return canceled
bit state
IF_NS
return #$80
END_IF
jsr _SetPort
jsr _Invert
FALL_THROUGH_TO _Invert
.endproc ; FlashImpl
.proc _Invert
MGTK_CALL MGTK::SetPenMode, penXOR
MGTK_CALL MGTK::InflateRect, shrink_rect
MGTK_CALL MGTK::PaintRect, rect
MGTK_CALL MGTK::InflateRect, grow_rect
;; returns MGTK success (A=0/Z=1/N=0)
rts
.endproc ; _Invert
;;; ============================================================
.proc HiliteImpl
jsr _SetPort
skip_port:
pos := $0B
;; Y-offset from bottom for shorter-than-normal buttons, e.g. arrow glyphs
sub16_8 rect+MGTK::Rect::y2, #(kButtonHeight - kButtonTextVOffset), pos+MGTK::Point::ycoord
ldx #DeskTopSettings::options
jsr ReadSetting
and #DeskTopSettings::kOptionsShowShortcuts
IF_NOT_ZERO
;; Draw the string (left aligned)
add16_8 rect+MGTK::Rect::x1, #kButtonTextHOffset, pos+MGTK::Point::xcoord
MGTK_CALL MGTK::MoveTo, pos
jsr _DrawLabel
;; Draw the shortcut (if present, right aligned)
lda a_shortcut
ora a_shortcut+1
IF_NOT_ZERO
@width := $9
jsr _MeasureShortcut
stax @width
sub16_8 rect+MGTK::Rect::x2, #kButtonTextHOffset-2, pos+MGTK::Point::xcoord
sub16 pos+MGTK::Point::xcoord, @width, pos+MGTK::Point::xcoord
MGTK_CALL MGTK::MoveTo, pos
jsr _DrawShortcut
END_IF
ELSE
;; Draw the label (centered)
@width := $9
jsr _MeasureLabel
stax @width
add16 rect+MGTK::Rect::x1, rect+MGTK::Rect::x2, pos+MGTK::Point::xcoord
sub16 pos+MGTK::Point::xcoord, @width, pos+MGTK::Point::xcoord
asr16 pos+MGTK::Point::xcoord
MGTK_CALL MGTK::MoveTo, pos
jsr _DrawLabel
END_IF
bit state
IF_NS
MGTK_CALL MGTK::SetPattern, checkerboard_pattern
MGTK_CALL MGTK::SetPenMode, penOR
MGTK_CALL MGTK::InflateRect, shrink_rect
MGTK_CALL MGTK::PaintRect, rect
END_IF
rts
.endproc ; HiliteImpl
;;; ============================================================
;;; Input: `a_shortcut` points at string
.proc _DrawShortcut
ldax a_shortcut
jmp _DrawString
.endproc ; _DrawShortcut
;;; Input: `a_label` points at string
.proc _DrawLabel
ldax a_label
FALL_THROUGH_TO _DrawString
.endproc ; _DrawLabel
;;; Inputs: A,X points at string
.proc _DrawString
PARAM_BLOCK dt_params, btk::zp_scratch
textptr .addr
textlen .byte
END_PARAM_BLOCK
stax dt_params::textptr
ldy #0
lda (dt_params::textptr),y
IF_NOT_ZERO
sta dt_params::textlen
inc16 dt_params::textptr
MGTK_CALL MGTK::DrawText, dt_params
END_IF
rts
.endproc ; _DrawString
;;; Inputs: `a_shortcut` points at string
;;; Output: A,X = width
.proc _MeasureShortcut
ldax a_shortcut
jmp _MeasureString
.endproc ; _MeasureShortcut
;;; Inputs: `a_label` points at string
;;; Output: A,X = width
.proc _MeasureLabel
ldax a_label
FALL_THROUGH_TO _MeasureString
.endproc ; _MeasureLabel
;;; Inputs: A,X points at string
;;; Output: A,X = width
.proc _MeasureString
PARAM_BLOCK tw_params, btk::zp_scratch
textptr .addr
textlen .byte
width .word
END_PARAM_BLOCK
stax tw_params::textptr
ldy #0
lda (tw_params::textptr),y
IF_ZERO
lda #0
tax
rts
END_IF
sta tw_params::textlen
inc16 tw_params::textptr
MGTK_CALL MGTK::TextWidth, tw_params
ldax tw_params::width
rts
.endproc ; _MeasureString
;;; ============================================================
.proc TrackImpl
;;; Shadows params in Selector's `app` and Disk Copy's `auxlc` scopes.
;;; TODO: Rework scoping to eliminate this.
SUPPRESS_SHADOW_WARNING
;; Use ZP for temporary params
PARAM_BLOCK event_params, btk::zp_scratch
kind .byte
coords .tag MGTK::Point
END_PARAM_BLOCK
.assert .sizeof(event_params) = .sizeof(MGTK::Event), error, "size mismatch"
.assert .sizeof(event_params) <= kMaxTmpSpace, error, "size mismatch"
PARAM_BLOCK screentowindow_params, btk::zp_scratch
window_id .byte
screen .tag MGTK::Point
window .tag MGTK::Point
END_PARAM_BLOCK
.assert screentowindow_params::screen = event_params::coords, error, "mismatch"
.assert .sizeof(screentowindow_params) <= kMaxTmpSpace, error, "size mismatch"
UNSUPPRESS_SHADOW_WARNING
;; If disabled, return canceled
bit state
IF_NS
return #$80
END_IF
jsr _SetPort
;; Initial state
copy8 #0, down_flag
;; Do initial inversion
loop_i: jsr _Invert
;; Event loop
loop: MGTK_CALL MGTK::GetEvent, event_params
lda event_params::kind
cmp #MGTK::EventKind::button_up
beq exit
lda window_id
IF_ZERO
MGTK_CALL MGTK::MoveTo, event_params::coords
ELSE
sta screentowindow_params::window_id
MGTK_CALL MGTK::ScreenToWindow, screentowindow_params
MGTK_CALL MGTK::MoveTo, screentowindow_params::window
END_IF
MGTK_CALL MGTK::InRect, rect
bne inside
lda down_flag ; outside but was inside?
beq toggle
bne loop ; always
inside: lda down_flag ; already depressed?
beq loop
toggle: lda down_flag
eor #$80
sta down_flag
jmp loop_i ; invert and continue
exit: lda down_flag ; was depressed?
IF_ZERO
jsr _Invert
END_IF
;; Note that we want N=0 and Z=1 if clicked, so bits<7 matter.
lda down_flag
rts
.endproc ; TrackImpl
.ifndef BTK_SHORT
;;; ============================================================
notpencopy: .byte MGTK::notpencopy
;;; Padding between radio/checkbox and label
kLabelPadding = 5
.params rb_params
DEFINE_POINT viewloc, 0, 0
mapbits: .addr SELF_MODIFIED
mapwidth: .byte 3
reserved: .byte 0
DEFINE_RECT maprect, 0, 0, BTK::kRadioButtonWidth, BTK::kRadioButtonHeight
REF_MAPINFO_MEMBERS
.endparams
checked_rb_bitmap:
PIXELS "....########...."
PIXELS "..###......###.."
PIXELS "###...####...###"
PIXELS "##..########..##"
PIXELS "##..########..##"
PIXELS "###...####...###"
PIXELS "..###......###.."
PIXELS "....########...."
unchecked_rb_bitmap:
PIXELS "....########...."
PIXELS "..###......###.."
PIXELS "###..........###"
PIXELS "##............##"
PIXELS "##............##"
PIXELS "###..........###"
PIXELS "..###......###.."
PIXELS "....########...."
;;; ============================================================
.proc RadioDrawImpl
jsr _SetPort
;; Initial size is just the button
add16_8 rect+MGTK::Rect::x1, #BTK::kRadioButtonWidth, rect+MGTK::Rect::x2
add16_8 rect+MGTK::Rect::y1, #BTK::kRadioButtonHeight, rect+MGTK::Rect::y2
lda a_label
ora a_label+1
IF_NOT_ZERO
;; Draw the label
pos := $B
add16_8 rect+MGTK::Rect::x1, #kLabelPadding + BTK::kRadioButtonWidth, pos+MGTK::Point::xcoord
add16_8 rect+MGTK::Rect::y1, #kSystemFontHeight - 1, pos+MGTK::Point::ycoord
MGTK_CALL MGTK::MoveTo, pos
jsr _DrawLabel
;; And measure it for hit testing
jsr _MeasureLabel
addax rect+MGTK::Rect::x2
add16_8 rect+MGTK::Rect::x2, #kLabelPadding
add16_8 rect+MGTK::Rect::y2, #kSystemFontHeight - BTK::kRadioButtonHeight
END_IF
jsr _MaybeDrawAndMeasureShortcut
jsr _WriteRectBackToButtonRecord
jmp _DrawRadioBitmap
.endproc ; RadioDrawImpl
;;; ============================================================
.proc RadioUpdateImpl
jsr _SetPort
FALL_THROUGH_TO _DrawRadioBitmap
.endproc ; RadioUpdateImpl
.proc _DrawRadioBitmap
COPY_STRUCT MGTK::Point, rect+MGTK::Rect::topleft, rb_params::viewloc
ldax #unchecked_rb_bitmap
bit state
IF_NS
ldax #checked_rb_bitmap
END_IF
stax rb_params::mapbits
MGTK_CALL MGTK::SetPenMode, notpencopy
MGTK_CALL MGTK::PaintBitsHC, rb_params
rts
.endproc ; _DrawRadioBitmap
;;; ============================================================
.params cb_params
DEFINE_POINT viewloc, 0, 0
mapbits: .addr SELF_MODIFIED
mapwidth: .byte 3
reserved: .byte 0
DEFINE_RECT maprect, 0, 0, BTK::kCheckboxWidth, BTK::kCheckboxHeight
REF_MAPINFO_MEMBERS
.endparams
checked_cb_bitmap:
PIXELS "##################"
PIXELS "####..........####"
PIXELS "##..##......##..##"
PIXELS "##....##..##....##"
PIXELS "##......##......##"
PIXELS "##....##..##....##"
PIXELS "##..##......##..##"
PIXELS "####..........####"
PIXELS "##################"
unchecked_cb_bitmap:
PIXELS "##################"
PIXELS "##..............##"
PIXELS "##..............##"
PIXELS "##..............##"
PIXELS "##..............##"
PIXELS "##..............##"
PIXELS "##..............##"
PIXELS "##..............##"
PIXELS "##################"
;;; ============================================================
.proc CheckboxDrawImpl
jsr _SetPort
;; Initial size is just the button
add16_8 rect+MGTK::Rect::x1, #BTK::kCheckboxWidth, rect+MGTK::Rect::x2
add16_8 rect+MGTK::Rect::y1, #BTK::kCheckboxHeight, rect+MGTK::Rect::y2
lda a_label
ora a_label+1
IF_NOT_ZERO
;; Draw the label
pos := $B
add16_8 rect+MGTK::Rect::x1, #kLabelPadding + BTK::kCheckboxWidth, pos+MGTK::Point::xcoord
add16_8 rect+MGTK::Rect::y1, #kSystemFontHeight, pos+MGTK::Point::ycoord
MGTK_CALL MGTK::MoveTo, pos
jsr _DrawLabel
;; And measure it for hit testing
jsr _MeasureLabel
addax rect+MGTK::Rect::x2
add16_8 rect+MGTK::Rect::x2, #kLabelPadding
add16_8 rect+MGTK::Rect::y2, #kSystemFontHeight - BTK::kCheckboxHeight
END_IF
jsr _MaybeDrawAndMeasureShortcut
jsr _WriteRectBackToButtonRecord
jmp _DrawCheckboxBitmap
.endproc ; CheckboxDrawImpl
;;; ============================================================
.proc CheckboxUpdateImpl
jsr _SetPort
FALL_THROUGH_TO _DrawCheckboxBitmap
.endproc ; CheckboxUpdateImpl
.proc _DrawCheckboxBitmap
COPY_STRUCT MGTK::Point, rect+MGTK::Rect::topleft, cb_params::viewloc
ldax #unchecked_cb_bitmap
bit state
IF_NS
ldax #checked_cb_bitmap
END_IF
stax cb_params::mapbits
MGTK_CALL MGTK::SetPenMode, notpencopy
MGTK_CALL MGTK::PaintBitsHC, cb_params
rts
.endproc ; _DrawCheckboxBitmap
;;; ============================================================
;;; If option is enabled, and if `a_shortcut` is not null,
;;; draw it and add the width to `rect`.
.proc _MaybeDrawAndMeasureShortcut
ldx #DeskTopSettings::options
jsr ReadSetting
and #DeskTopSettings::kOptionsShowShortcuts
IF_NOT_ZERO
lda a_shortcut
ora a_shortcut+1
IF_NOT_ZERO
jsr _DrawShortcut
jsr _MeasureShortcut
addax rect+MGTK::Rect::x2
END_IF
END_IF
rts
.endproc ; _MaybeDrawAndMeasureShortcut
;;; Copies `rect` back into `a_record`
.proc _WriteRectBackToButtonRecord
;; Write rect back to button record
ldx #.sizeof(MGTK::Rect)-1
ldy #BTK::ButtonRecord::rect + .sizeof(MGTK::Rect)-1
DO
copy8 rect,x, (params_addr),y
dey
dex
WHILE_POS
rts
.endproc ; _WriteRectBackToButtonRecord
;;; ============================================================
.endif ; BTK_SHORT
.endscope ; btk
|
a2stuff/a2d
| 24,654
|
src/toolkits/lbtk.s
|
;;; ============================================================
;;; List Box ToolKit
;;; ============================================================
.scope lbtk
LBTKEntry := *
;;; ============================================================
;;; Zero Page usage (saved/restored around calls)
zp_start := $50
kMaxCommandDataSize = 6
kMaxTmpSpace = .sizeof(MGTK::Point) + .sizeof(MGTK::Rect)
PARAM_BLOCK, zp_start
;;; Initially points at the call site, then at passed params
params_addr .addr
;;; Copy of the passed params
command_data .res kMaxCommandDataSize
;;; A temporary copy of the control record is placed here:
lbr_copy .tag LBTK::ListBoxRecord
;;; Other ZP usage
.union
tmp_space .res kMaxTmpSpace
.struct
tmp_point .tag MGTK::Point ; used by `_Draw`
tmp_rect .tag MGTK::Rect ; used by `_Draw`
.endstruct
.endunion
;;; For size calculation, not actually used
zp_end .byte
END_PARAM_BLOCK
.assert zp_end <= $78, error, "too big"
kBytesToSave = zp_end - zp_start
a_record := command_data ; always first element of `command_data`
;; Aliases for the copy's members:
winfo_ptr := lbr_copy + LBTK::ListBoxRecord::winfo
;;; ============================================================
;;; Shadows params in Selector's `app` and Disk Copy's `auxlc` scopes.
;;; TODO: Rework scoping to eliminate this.
SUPPRESS_SHADOW_WARNING
PARAM_BLOCK event_params, lbtk::tmp_space
kind .byte
.union
;;; if `kind` is key_down
.struct
key .byte
modifiers .byte
.endstruct
;;; if `kind` is no_event, button_down/up, drag, or apple_key:
.struct
coords .tag MGTK::Point
.endstruct
.struct
xcoord .word
ycoord .word
.endstruct
;;; if `kind` is update:
.struct
window_id .byte
.endstruct
.endunion
END_PARAM_BLOCK
PARAM_BLOCK setctlmax_params, lbtk::tmp_space
which_ctl .byte
ctlmax .byte
END_PARAM_BLOCK
PARAM_BLOCK activatectl_params, lbtk::tmp_space
which_ctl .byte
activate .byte
END_PARAM_BLOCK
PARAM_BLOCK updatethumb_params, lbtk::tmp_space
which_ctl .byte
thumbpos .byte
END_PARAM_BLOCK
PARAM_BLOCK trackthumb_params, lbtk::tmp_space
which_ctl .byte
mousex .word
mousey .word
thumbpos .byte
thumbmoved .byte
END_PARAM_BLOCK
ASSERT_EQUALS trackthumb_params::mousex, event_params::xcoord
ASSERT_EQUALS trackthumb_params::mousey, event_params::ycoord
ASSERT_EQUALS setctlmax_params::which_ctl, activatectl_params::which_ctl
ASSERT_EQUALS trackthumb_params::which_ctl, activatectl_params::which_ctl
ASSERT_EQUALS updatethumb_params::which_ctl, activatectl_params::which_ctl
PARAM_BLOCK screentowindow_params, lbtk::tmp_space
window_id .byte
.union
screen .tag MGTK::Point
.struct
screenx .word
screeny .word
.endstruct
.endunion
.union
window .tag MGTK::Point
.struct
windowx .word
windowy .word
.endstruct
.endunion
END_PARAM_BLOCK
ASSERT_EQUALS screentowindow_params::screenx, event_params::xcoord
ASSERT_EQUALS screentowindow_params::screeny, event_params::ycoord
PARAM_BLOCK findwindow_params, lbtk::tmp_space+1
mousex .word
mousey .word
which_area .byte
window_id .byte
END_PARAM_BLOCK
ASSERT_EQUALS findwindow_params::mousex, event_params::xcoord
ASSERT_EQUALS findwindow_params::mousey, event_params::ycoord
PARAM_BLOCK findcontrol_params, lbtk::tmp_space+1
mousex .word
mousey .word
which_ctl .byte
which_part .byte
END_PARAM_BLOCK
ASSERT_EQUALS findcontrol_params::mousex, event_params::xcoord
ASSERT_EQUALS findcontrol_params::mousey, event_params::ycoord
UNSUPPRESS_SHADOW_WARNING
;;; ============================================================
.assert LBTKEntry = Dispatch, error, "dispatch addr"
.proc Dispatch
;; Adjust stack/stash
pla
sta params_lo
clc
adc #<3
tax
pla
sta params_hi
adc #>3
pha
txa
pha
;; Save ZP
PUSH_BYTES kBytesToSave, zp_start
;; Point `params_addr` at the call site
params_lo := *+1
lda #SELF_MODIFIED_BYTE
sta params_addr
params_hi := *+1
lda #SELF_MODIFIED_BYTE
sta params_addr+1
;; Grab command number
ldy #1 ; Note: rts address is off-by-one
lda (params_addr),y
tax
copylohi jump_table_lo,x, jump_table_hi,x, dispatch
;; Point `params_addr` at actual params
iny
lda (params_addr),y
tax
iny
lda (params_addr),y
sta params_addr+1
stx params_addr
;; Copy param data to `command_data`
ldy #kMaxCommandDataSize-1
DO
copy8 (params_addr),y, command_data,y
dey
WHILE_POS
;; Cache static copy of the record in `lbr_copy`, for convenience
ldy #.sizeof(LBTK::ListBoxRecord)-1
DO
copy8 (a_record),y, lbr_copy,y
dey
WHILE_POS
;; Invoke the command
dispatch := *+1
jsr SELF_MODIFIED
tay ; A = result
;; Restore ZP
POP_BYTES kBytesToSave, zp_start
tya ; A = result
rts
jump_table_lo:
.lobytes InitImpl
.lobytes ClickImpl
.lobytes KeyImpl
.lobytes SetSelectionImpl
.lobytes SetSizeImpl
jump_table_hi:
.hibytes InitImpl
.hibytes ClickImpl
.hibytes KeyImpl
.hibytes SetSelectionImpl
.hibytes SetSizeImpl
ASSERT_EQUALS *-jump_table_hi, jump_table_hi-jump_table_lo
.endproc ; Dispatch
;;; ============================================================
DrawEntryProc: jmp (lbr_copy + LBTK::ListBoxRecord::draw_entry_proc)
OnSelChange: jmp (lbr_copy + LBTK::ListBoxRecord::on_sel_change)
OnNoChange: jmp (lbr_copy + LBTK::ListBoxRecord::on_no_change)
;;; ============================================================
pencopy: .byte MGTK::pencopy
penXOR: .byte MGTK::penXOR
;;; ============================================================
;;; Call to initialize (or reset) the list. The caller must set
;;; `LBTK::ListBoxRecord::num_items` and `LBTK::ListBoxRecord::selected_index` first.
;;; This procedure will:
;;; * Update the scrollbar, based on `LBTK::ListBoxRecord::num_items`
;;; * Draw the list items
;;; * If `LBTK::ListBoxRecord::selected_index` is not none, that item will
;;; be scrolled into view and highlighted.
.proc InitImpl
PARAM_BLOCK params, lbtk::command_data
a_record .addr
END_PARAM_BLOCK
jsr _EnableScrollbar
lda lbr_copy + LBTK::ListBoxRecord::selected_index
IF_NS
lda #0
END_IF
sec ; force draw
jmp _ScrollIntoView
.endproc ; InitImpl
;;; ============================================================
;;; Call when a button down event occurs on the list Winfo.
;;;
;;; Output: Z=1/A=$00 on click on an item
;;; N=1/A=$FF otherwise
.params divide_params
number: .word 1 ; (in) constant
numerator: .word 0 ; (in) populated dynamically
denominator: .word kListItemHeight ; (in) constant
result: .word 0 ; (out)
remainder: .word 0 ; (out)
REF_MULDIV_MEMBERS
.endparams
.proc ClickImpl
PARAM_BLOCK params, lbtk::command_data
a_record .addr
coords .tag MGTK::Point
END_PARAM_BLOCK
COPY_STRUCT params::coords, event_params::coords
jsr _FindControlIsVerticalScrollBar
IF_EQ
jsr _HandleListScroll
return #$FF ; not an item
END_IF
IF_A_NE #MGTK::Ctl::not_a_control
return #$FF ; not an item
END_IF
ldy #MGTK::Winfo::window_id
copy8 (winfo_ptr),y, screentowindow_params::window_id
MGTK_CALL MGTK::ScreenToWindow, screentowindow_params
ldy #MGTK::Winfo::port+MGTK::GrafPort::maprect+MGTK::Rect::y1
add16in (winfo_ptr),y, screentowindow_params::windowy, screentowindow_params::windowy
copy16 screentowindow_params::windowy, divide_params::numerator
MGTK_CALL MGTK::MulDiv, divide_params
lda divide_params::result
;; Validate
IF_A_GE lbr_copy + LBTK::ListBoxRecord::num_items
lda #$FF
jsr _SetSelectionAndNotify
return #$FF ; not an item
END_IF
;; Update selection (if different)
IF_A_NE lbr_copy + LBTK::ListBoxRecord::selected_index
jsr _SetSelectionAndNotify
ELSE
jsr OnNoChange
END_IF
return #0 ; an item
.endproc ; ClickImpl
;;; ============================================================
;;; Handle scroll bar
.proc _HandleListScrollWithPart
sta findcontrol_params::which_part
FALL_THROUGH_TO _HandleListScroll
.endproc ; _HandleListScrollWithPart
.proc _HandleListScroll
;; Ignore unless vscroll is enabled
ldy #MGTK::Winfo::vscroll
lda (winfo_ptr),y
ASSERT_EQUALS MGTK::Scroll::option_active, %00000001
ror ; C = "active?"
IF_CC
ret: rts
END_IF
lda findcontrol_params::which_part
;; --------------------------------------------------
IF_A_EQ #MGTK::Part::up_arrow
@repeat:
ldy #MGTK::Winfo::vthumbpos
lda (winfo_ptr),y
beq ret
sec
sbc #1
jsr update
lda #MGTK::Part::up_arrow
jsr _CheckControlRepeat
beq @repeat ; always
END_IF
;; --------------------------------------------------
IF_A_EQ #MGTK::Part::down_arrow
@repeat:
ldy #MGTK::Winfo::vthumbpos
lda (winfo_ptr),y
ASSERT_EQUALS MGTK::Winfo::vthumbmax, MGTK::Winfo::vthumbpos - 1
dey ; Y = MGTK::Winfo::vthumbmax
cmp (winfo_ptr),y
beq ret
clc
adc #1
jsr update
lda #MGTK::Part::down_arrow
jsr _CheckControlRepeat
beq @repeat ; always
END_IF
;; --------------------------------------------------
IF_A_EQ #MGTK::Part::page_up
repeat:
ldy #MGTK::Winfo::vthumbpos
lda (winfo_ptr),y
IF_A_LT lbr_copy + LBTK::ListBoxRecord::num_rows
lda #0
SKIP_NEXT_2_BYTE_INSTRUCTION
ASSERT_NOT_EQUALS lbr_copy + LBTK::ListBoxRecord::num_rows, $C0, "bad BIT skip"
END_IF
sbc lbr_copy + LBTK::ListBoxRecord::num_rows
jsr update
lda #MGTK::Part::page_up
jsr _CheckControlRepeat
beq repeat ; always
END_IF
;; --------------------------------------------------
IF_A_EQ #MGTK::Part::page_down
@repeat:
ldy #MGTK::Winfo::vthumbpos
lda (winfo_ptr),y
clc
adc lbr_copy + LBTK::ListBoxRecord::num_rows
ASSERT_EQUALS MGTK::Winfo::vthumbmax, MGTK::Winfo::vthumbpos - 1
dey ; Y = MGTK::Winfo::vthumbmax
cmp (winfo_ptr),y
bcc @do
;; Assert: Y = MGTK::Winfo::vthumbmax
lda (winfo_ptr),y
@do: jsr update
lda #MGTK::Part::page_down
jsr _CheckControlRepeat
beq @repeat ; always
END_IF
;; --------------------------------------------------
;; MGTK::Part::thumb
copy8 #MGTK::Ctl::vertical_scroll_bar, trackthumb_params::which_ctl
MGTK_CALL MGTK::TrackThumb, trackthumb_params
lda trackthumb_params::thumbmoved
beq ret
lda trackthumb_params::thumbpos
FALL_THROUGH_TO update
;; --------------------------------------------------
update: jmp _UpdateThumbAndDraw
.endproc ; _HandleListScroll
;;; ============================================================
;;; Output: Z=1 if repeat, or pops caller off stack otherwise
.proc _CheckControlRepeat
sta ctl
MGTK_CALL MGTK::PeekEvent, event_params
lda event_params::kind
IF_A_EQ #MGTK::EventKind::drag
MGTK_CALL MGTK::GetEvent, event_params
MGTK_CALL MGTK::FindWindow, findwindow_params
lda findwindow_params::window_id
ldy #MGTK::Winfo::window_id
IF_A_EQ (winfo_ptr),y
lda findwindow_params::which_area
IF_A_EQ #MGTK::Area::content
jsr _FindControlIsVerticalScrollBar
IF_EQ
lda findcontrol_params::which_part
ctl := *+1
cmp #SELF_MODIFIED_BYTE
beq ret ; Yes, continue
END_IF
END_IF
END_IF
END_IF
pla
pla
ret: rts
.endproc ; _CheckControlRepeat
;;; ============================================================
;;; Call when a key event occurs, if `LBIsListKey` indicates it
;;; will be handled. This handles scrolling and/or updating
;;; the selection.
.proc KeyImpl
PARAM_BLOCK params, lbtk::command_data
a_record .addr
key .byte
modifiers .byte
END_PARAM_BLOCK
lda lbr_copy + LBTK::ListBoxRecord::num_items
IF_ZERO
ret: rts
END_IF
lda params::key
ldx params::modifiers
;; --------------------------------------------------
;; No modifiers
;; Up/Down move selection
IF_ZERO
IF_A_EQ #CHAR_UP
ldx lbr_copy + LBTK::ListBoxRecord::selected_index
beq ret
IF_NS
ldx lbr_copy + LBTK::ListBoxRecord::num_items
END_IF
dex
txa
bpl _SetSelectionAndNotify ; always
END_IF
;; CHAR_DOWN
ldx lbr_copy + LBTK::ListBoxRecord::selected_index
IF_NS
lda #0
beq _SetSelectionAndNotify ; always
END_IF
inx
cpx lbr_copy + LBTK::ListBoxRecord::num_items
beq ret
txa
bpl _SetSelectionAndNotify ; always
END_IF
;; --------------------------------------------------
;; Double modifiers
;; Home/End move selection to first/last
IF_X_EQ #3
IF_A_EQ #CHAR_UP
lda lbr_copy + LBTK::ListBoxRecord::selected_index
beq ret
lda #0
bpl _SetSelectionAndNotify ; always
END_IF
;; CHAR_DOWN
ldx lbr_copy + LBTK::ListBoxRecord::selected_index
IF_NC
inx
cpx lbr_copy + LBTK::ListBoxRecord::num_items
beq ret
END_IF
ldx lbr_copy + LBTK::ListBoxRecord::num_items
dex
txa
bpl _SetSelectionAndNotify ; always
END_IF
;; --------------------------------------------------
;; Single modifier
IF_A_EQ #CHAR_UP
lda #MGTK::Part::page_up
SKIP_NEXT_2_BYTE_INSTRUCTION
END_IF
;; CHAR_DOWN
lda #MGTK::Part::page_down
jmp _HandleListScrollWithPart
.endproc ; KeyImpl
;;; ============================================================
.proc _SetSelectionAndNotify
jsr _SetSelection
jmp OnSelChange
.endproc ; _SetSelectionAndNotify
;;; ============================================================
.proc SetSelectionImpl
PARAM_BLOCK params, lbtk::command_data
a_record .addr
new_selection .byte
END_PARAM_BLOCK
lda params::new_selection
FALL_THROUGH_TO _SetSelection
.endproc ; SetSelectionImpl
;;; ============================================================
;;; Sets the selected item index. If not none, it is scrolled
;;; into view.
;;; Input: A = new selection (negative if none)
;;; Note: Does not call `OnListSelectionChange`
.proc _SetSelection
pha ; A = new selection
lda lbr_copy + LBTK::ListBoxRecord::selected_index
jsr _HighlightIndex
ldy #LBTK::ListBoxRecord::selected_index
pla ; A = new selection
sta (a_record),y
sta lbr_copy + LBTK::ListBoxRecord::selected_index ; keep copy in sync
IF_NC
clc ; not force draw
bcc _ScrollIntoView ; always
END_IF
rts
.endproc ; _SetSelection
;;; ============================================================
;;; Input: A = row to highlight
.proc _HighlightIndex
cmp #0 ; don't assume caller has flags set
bmi ret
pha ; A = row
jsr _SetPort ; also uses `tmp_rect`
pla ; A = row
ldx #0 ; hi (A=lo)
ldy #kListItemHeight
jsr _Multiply
stax tmp_rect+MGTK::Rect::y1
addax #kListItemHeight-1, tmp_rect+MGTK::Rect::y2
copy16 #0, tmp_rect+MGTK::Rect::x1
copy16 #kScreenWidth, tmp_rect+MGTK::Rect::x2
MGTK_CALL MGTK::SetPenMode, penXOR
MGTK_CALL MGTK::PaintRect, tmp_rect
ret: rts
.endproc ; _HighlightIndex
;;; ============================================================
;;; Call to update `LBTK::ListBoxRecord::num_items` after `LBInit` is called,
;;; to update the scrollbar alone. The list items will not be redrawn.
;;; This is useful if the list is populated asynchronously.
.proc SetSizeImpl
PARAM_BLOCK params, lbtk::command_data
a_record .addr
new_size .byte
END_PARAM_BLOCK
lda params::new_size
ldy #LBTK::ListBoxRecord::num_items
sta (a_record),y
sta lbr_copy + LBTK::ListBoxRecord::num_items ; keep copy in sync
FALL_THROUGH_TO _EnableScrollbar
.endproc ; SetSizeImpl
;;; ============================================================
;;; Enable/disable scrollbar as appropriate; resets thumb pos.
;;; Assert: `LBTK::ListBoxRecord::num_items` is set.
.proc _EnableScrollbar
;; Reset thumb pos
lda #0
jsr _UpdateThumb
lda lbr_copy + LBTK::ListBoxRecord::num_items
cmp lbr_copy + LBTK::ListBoxRecord::num_rows
beq :+ ; TODO: `BGT` ?
bcs greater
:
;; Deactivate
lda #MGTK::activatectl_deactivate
ASSERT_EQUALS MGTK::activatectl_deactivate, 0
beq activate ; always
greater:
;; Set max and activate
lda lbr_copy + LBTK::ListBoxRecord::num_items
sec
sbc lbr_copy + LBTK::ListBoxRecord::num_rows
sta setctlmax_params::ctlmax
MGTK_CALL MGTK::SetCtlMax, setctlmax_params
lda #MGTK::activatectl_activate
activate:
sta activatectl_params::activate
copy8 #MGTK::Ctl::vertical_scroll_bar, activatectl_params::which_ctl
MGTK_CALL MGTK::ActivateCtl, activatectl_params
rts
.endproc ; _EnableScrollbar
;;; ============================================================
;;; Input: A = row to ensure visible; C = force redraw,
;;; even if no scrolling occurred.
;;; Assert: `LBTK::ListBoxRecord::winfo`'s `MGTK::Winfo::vthumbpos` is set.
.proc _ScrollIntoView
force_draw_flag := tmp_space
ror force_draw_flag ; set bit7
ldy #MGTK::Winfo::vthumbpos
cmp (winfo_ptr),y
bcc update
sec
sbc lbr_copy + LBTK::ListBoxRecord::num_rows
clc
adc #1
bmi skip
;; Assert: Y = MGTK::Winfo::vthumbpos
cmp (winfo_ptr),y
beq skip ; TODO: `BGT` ?
bcs update
skip:
lda force_draw_flag
bmi _Draw ; will highlight selection
lda lbr_copy + LBTK::ListBoxRecord::selected_index
jmp _HighlightIndex
update:
jmp _UpdateThumbAndDraw
.endproc ; _ScrollIntoView
;;; ============================================================
;;; Update thumb position.
;;; Input: A = new thumb pos
.proc _UpdateThumb
sta updatethumb_params::thumbpos
copy8 #MGTK::Ctl::vertical_scroll_bar, updatethumb_params::which_ctl
MGTK_CALL MGTK::UpdateThumb, updatethumb_params
rts
.endproc ; _UpdateThumb
;;; ============================================================
;;; Runs `MGTK::FindControl` with coords from `event_params`.
;;; Output: Z=1 if over vertical scrollbar, Z=0 otherwise
.proc _FindControlIsVerticalScrollBar
MGTK_CALL MGTK::FindControl, findcontrol_params
lda findcontrol_params::which_ctl
cmp #MGTK::Ctl::vertical_scroll_bar
rts
.endproc ; _FindControlIsVerticalScrollBar
;;; ============================================================
;;; Adjusts the viewport given the scroll position, and selects
;;; the GrafPort of the control.
.proc _SetPort
ldy #MGTK::Winfo::port+MGTK::GrafPort::maprect+.sizeof(MGTK::Rect)-1
ldx #.sizeof(MGTK::Rect)-1
DO
copy8 (winfo_ptr),y, tmp_rect,x
dey
dex
WHILE_POS
;; Set y2 to height
sub16 tmp_rect+MGTK::Rect::y2, tmp_rect+MGTK::Rect::y1, tmp_rect+MGTK::Rect::y2
ldy #MGTK::Winfo::vthumbpos
lda (winfo_ptr),y
tay
ldax #kListItemHeight
jsr _Multiply
stax tmp_rect+MGTK::Rect::y1
;; Set y2 to bottom
addax tmp_rect+MGTK::Rect::y2, tmp_rect+MGTK::Rect::y2
ldy #MGTK::Winfo::port+MGTK::GrafPort::maprect+.sizeof(MGTK::Rect)-1
ldx #.sizeof(MGTK::Rect)-1
DO
copy8 tmp_rect,x, (winfo_ptr),y
dey
dex
WHILE_POS
add16 winfo_ptr, #MGTK::Winfo::port, setport_addr
MGTK_CALL MGTK::SetPort, SELF_MODIFIED, setport_addr
rts
.endproc ; _SetPort
;;; ============================================================
.proc _UpdateThumbAndDraw
jsr _UpdateThumb
FALL_THROUGH_TO _Draw
.endproc ; _UpdateThumbAndDraw
;;; Calls `DrawListEntryProc` for each entry.
.proc _Draw
jsr _SetPort
add16 winfo_ptr, #MGTK::Winfo::port+MGTK::GrafPort::maprect, rect_addr
MGTK_CALL MGTK::HideCursor
MGTK_CALL MGTK::SetPenMode, pencopy
MGTK_CALL MGTK::PaintRect, SELF_MODIFIED, rect_addr
lda lbr_copy + LBTK::ListBoxRecord::num_items
beq finish
copy8 lbr_copy + LBTK::ListBoxRecord::num_rows, rows
ldy #MGTK::Winfo::vthumbpos
copy8 (winfo_ptr),y, index
copy16 #kListItemTextOffsetX, tmp_point+MGTK::Point::xcoord
ldy #MGTK::Winfo::port+MGTK::GrafPort::maprect+MGTK::Rect::y1
add16in (winfo_ptr),y, #kListItemTextOffsetY, tmp_point+MGTK::Point::ycoord
DO
MGTK_CALL MGTK::MoveTo, tmp_point
index := *+1
lda #SELF_MODIFIED_BYTE
ldxy #tmp_point
jsr DrawEntryProc
add16_8 tmp_point+MGTK::Point::ycoord, #kListItemHeight
lda index
IF_A_EQ lbr_copy + LBTK::ListBoxRecord::selected_index
jsr _HighlightIndex
END_IF
inc index
lda index
BREAK_IF_A_EQ lbr_copy + LBTK::ListBoxRecord::num_items
dec rows
WHILE_NOT_ZERO
finish: MGTK_CALL MGTK::ShowCursor
rts
rows: .byte 0
.endproc ; _Draw
;;; ============================================================
;;; Not in `tmp_space` because denominator and numerator hi are const
.params multiply_params
number: .word 0 ; (in) populated dynamically
numerator: .word 0 ; (in) populated dynamically
denominator: .word 1 ; (in) constant
result: .word 0 ; (out)
remainder: .word 0 ; (out)
REF_MULDIV_MEMBERS
.endparams
;;; A,X = A,X * Y
.proc _Multiply
stax multiply_params::number
sty multiply_params::numerator ; high byte remains 0
MGTK_CALL MGTK::MulDiv, multiply_params
ldax multiply_params::result
rts
.endproc ; _Multiply
;;; ============================================================
.endscope ; lbtk
|
a2stuff/a2d
| 19,987
|
src/toolkits/letk.s
|
;;; ============================================================
;;; LineEdit ToolKit
;;; ============================================================
.scope letk
LETKEntry := *
;;; ============================================================
;;; Zero Page usage (saved/restored around calls)
zp_start := $50
kMaxCommandDataSize = 6
kMaxTmpSpace = .sizeof(MGTK::Point)
PARAM_BLOCK, zp_start
;;; Points at call parameters (i.e. ButtonRecord)
params_addr .addr
;;; Copy of the passed params
command_data .res kMaxCommandDataSize
;;; A temporary copy of the control record
ler_copy .tag LETK::LineEditRecord
;;; Other ZP usage
pos .tag MGTK::Point ; Calculated from rect
text_params .tag MGTK::TextWidthParams
tmp_space .res kMaxTmpSpace
;;; For size calculation, not actually used
zp_end .byte
END_PARAM_BLOCK
.assert zp_end <= $78, error, "too big"
kBytesToSave = zp_end - zp_start
a_record := command_data ; always first element of `command_data`
tmpw := tmp_space
;; Aliases for the copy's members:
window_id := ler_copy + LETK::LineEditRecord::window_id
a_buf := ler_copy + LETK::LineEditRecord::a_buf
rect := ler_copy + LETK::LineEditRecord::rect
max_length := ler_copy + LETK::LineEditRecord::max_length
options := ler_copy + LETK::LineEditRecord::options
;;; ============================================================
.assert LETKEntry = Dispatch, error, "dispatch addr"
.proc Dispatch
;; Adjust stack/stash
pla
sta params_lo
clc
adc #<3
tax
pla
sta params_hi
adc #>3
pha
txa
pha
;; Save ZP
PUSH_BYTES kBytesToSave, zp_start
;; Point `params_addr` at the call site
params_lo := *+1
lda #SELF_MODIFIED_BYTE
sta params_addr
params_hi := *+1
lda #SELF_MODIFIED_BYTE
sta params_addr+1
;; Grab command number
ldy #1 ; Note: rts address is off-by-one
lda (params_addr),y
tax
copylohi jump_table_lo,x, jump_table_hi,x, dispatch
;; Point `params_addr` at actual params
iny
lda (params_addr),y
tax
iny
lda (params_addr),y
sta params_addr+1
stx params_addr
;; Copy param data to `command_data`
ldy #kMaxCommandDataSize-1
: copy8 (params_addr),y, command_data,y
dey
bpl :-
;; Cache static copy of the record in `ler_copy`, for convenience
ldy #.sizeof(LETK::LineEditRecord)-1
: copy8 (a_record),y, ler_copy,y
dey
bpl :-
;; Compute constants
jsr _CalcPos
;; Invoke the command
dispatch := *+1
jsr SELF_MODIFIED
tay ; A = result
;; Restore ZP
POP_BYTES kBytesToSave, zp_start
tya ; A = result
rts
jump_table_lo:
.lobytes InitImpl
.lobytes IdleImpl
.lobytes ActivateImpl
.lobytes DeactivateImpl
.lobytes ClickImpl
.lobytes KeyImpl
.lobytes UpdateImpl
jump_table_hi:
.hibytes InitImpl
.hibytes IdleImpl
.hibytes ActivateImpl
.hibytes DeactivateImpl
.hibytes ClickImpl
.hibytes KeyImpl
.hibytes UpdateImpl
ASSERT_EQUALS *-jump_table_hi, jump_table_hi-jump_table_lo
.endproc ; Dispatch
;;; ============================================================
pencopy: .byte MGTK::pencopy
penXOR: .byte MGTK::penXOR
;;; ============================================================
.proc _CalcPos
;; Default position
add16_8 rect+MGTK::Rect::x1, #kTextBoxTextHOffset-1, pos+MGTK::Point::xcoord
add16_8 rect+MGTK::Rect::y1, #kTextBoxTextVOffset-1, pos+MGTK::Point::ycoord
bit options ; bit7 = centered
IF_NS
add16 rect+MGTK::Rect::x1, rect+MGTK::Rect::x2, pos+MGTK::Point::xcoord
jsr _PrepTextParams
IF_NOT_ZERO
MGTK_CALL MGTK::TextWidth, text_params
END_IF
sub16 pos+MGTK::Point::xcoord, text_params+MGTK::TextWidthParams::width, pos+MGTK::Point::xcoord
lsr16 pos+MGTK::Point::xcoord
END_IF
rts
.endproc ; _CalcPos
;;; ============================================================
.proc InitImpl
PARAM_BLOCK params, letk::command_data
a_record .addr
END_PARAM_BLOCK
.assert a_record = params::a_record, error, "a_record must be first"
lda #0
ldy #LETK::LineEditRecord::active_flag
sta (a_record),y
iny
sta (a_record),y
ASSERT_EQUALS LETK::LineEditRecord::caret_pos - LETK::LineEditRecord::active_flag, 1
iny
sta (a_record),y
ASSERT_EQUALS LETK::LineEditRecord::caret_flag - LETK::LineEditRecord::caret_pos, 1
iny
sta (a_record),y
ASSERT_EQUALS LETK::LineEditRecord::caret_counter - LETK::LineEditRecord::caret_flag, 1
jsr UpdateImpl
FALL_THROUGH_TO _ResetCaretCounter
.endproc ; InitImpl
.proc _ResetCaretCounter
ldx #DeskTopSettings::caret_blink_speed+1
jsr ReadSetting
pha
dex ; `ReadSetting` preserves X
jsr ReadSetting
ldy #LETK::LineEditRecord::caret_counter
sta (a_record),y
iny
pla
sta (a_record),y
rts
.endproc ; _ResetCaretCounter
;;; ============================================================
.proc IdleImpl
PARAM_BLOCK params, letk::command_data
a_record .addr
END_PARAM_BLOCK
.assert a_record = params::a_record, error, "a_record must be first"
ldy #LETK::LineEditRecord::active_flag
lda (a_record),y
IF_NC
ret: rts
END_IF
ldy #LETK::LineEditRecord::caret_counter
sub16in (a_record),y, #1, (a_record),y
lda (a_record),y ; Y = LETK::LineEditRecord::caret_counter+1
dey
ora (a_record),y ; Y = LETK::LineEditRecord::caret_counter
bne ret
jsr _ResetCaretCounter
ldy #LETK::LineEditRecord::caret_flag
lda (a_record),y
eor #$80
sta (a_record),y
FALL_THROUGH_TO _XDrawCaret
.endproc ; IdleImpl
.proc _XDrawCaret
PARAM_BLOCK point, letk::tmp_space
xcoord .word
ycoord .word
END_PARAM_BLOCK
jsr _SetPort
jsr _CalcCaretPos
stax point::xcoord
dec16 point::xcoord ; between characters
copy16 pos + MGTK::Point::ycoord, point::ycoord
MGTK_CALL MGTK::MoveTo, point
MGTK_CALL MGTK::SetPenMode, penXOR
MGTK_CALL MGTK::Line, caret_move
rts
.endproc ; _XDrawCaret
;; Delta from text baseline to top of text, for drawing caret
DEFINE_POINT caret_move, 0, AS_WORD(-kSystemFontHeight)
.proc _HideCaret
ldy #LETK::LineEditRecord::caret_flag
lda (a_record),y
bmi _XDrawCaret
rts
.endproc ; _HideCaret
_ShowCaret := _HideCaret
;;; ============================================================
.params getwinport_params
window_id: .byte 0
port: .addr grafport_win
.endparams
grafport_win: .tag MGTK::GrafPort
.proc _SetPort
;; Set the port
copy8 window_id, getwinport_params::window_id
MGTK_CALL MGTK::GetWinPort, getwinport_params
bne obscured
MGTK_CALL MGTK::SetPort, grafport_win
beq ret
obscured:
pla
pla
ret:
rts
.endproc ; _SetPort
;;; ============================================================
.proc ActivateImpl
PARAM_BLOCK params, letk::command_data
a_record .addr
END_PARAM_BLOCK
.assert a_record = params::a_record, error, "a_record must be first"
;; Idempotent, to allow Activate to be used to just move caret
jsr _HideCaret
;; Move caret to end
jsr _MoveCaretEnd
;; Set active flag
ldy #LETK::LineEditRecord::active_flag
copy8 #$80, (a_record),y
jmp _ShowCaret
.endproc ; ActivateImpl
;;; ============================================================
.proc DeactivateImpl
jsr _HideCaret
ldy #LETK::LineEditRecord::active_flag
lda #0
sta (a_record),y
ldy #LETK::LineEditRecord::caret_flag
sta (a_record),y
rts
.endproc ; DeactivateImpl
;;; ============================================================
;;; Internal proc: used as part of insert/delete procs
.proc _RedrawRightOfCaret
jsr _SetPort
PARAM_BLOCK point, letk::tmp_space
xcoord .word
ycoord .word
END_PARAM_BLOCK
jsr _CalcCaretPos
stax point::xcoord
copy16 pos + MGTK::Point::ycoord, point::ycoord
MGTK_CALL MGTK::MoveTo, point
jsr _PrepTextParams
pha ; A = len
caret_pos := tmpw
ldy #LETK::LineEditRecord::caret_pos
copy8 (a_record),y, caret_pos
add16_8 text_params+MGTK::TextWidthParams::data, caret_pos
pla ; A = len
sec
sbc caret_pos
IF_NOT_ZERO
sta text_params+MGTK::TextWidthParams::length
MGTK_CALL MGTK::DrawText, text_params
END_IF
rts
.endproc ; _RedrawRightOfCaret
;;; ============================================================
;;; Prepare params for a TextWidth or DrawText call
;;; Output: A=length (and Z=1 if empty)
;;; `text_params+MGTK::TextWidthParams::width` set to 0
.proc _PrepTextParams
ldxy a_buf
inxy
stxy text_params+MGTK::TextWidthParams::data
ldy #0
sty text_params+MGTK::TextWidthParams::width
sty text_params+MGTK::TextWidthParams::width+1
copy8 (a_buf),y, text_params+MGTK::TextWidthParams::length
rts
.endproc ; _PrepTextParams
;;; ============================================================
.proc ClickImpl
PARAM_BLOCK params, letk::command_data
a_record .addr
xcoord .word
ycoord .word
END_PARAM_BLOCK
.assert a_record = params::a_record, error, "a_record must be first"
len := tmpw
jsr _PrepTextParams
beq ret
sta len
sub16 params::xcoord, pos + MGTK::Point::xcoord, params::xcoord
IF_MINUS
lda #0
beq set ; always
END_IF
;; Iterate to find the position
lda #0
sta text_params+MGTK::TextWidthParams::width
sta text_params+MGTK::TextWidthParams::width+1
sta text_params+MGTK::TextWidthParams::length
DO
cmp16 text_params+MGTK::TextWidthParams::width, params::xcoord
BREAK_IF_CS
inc text_params+MGTK::TextWidthParams::length
lda text_params+MGTK::TextWidthParams::length
BREAK_IF_A_EQ len
MGTK_CALL MGTK::TextWidth, text_params
WHILE_ZERO ; always
lda text_params+MGTK::TextWidthParams::length
set: pha
jsr _HideCaret
pla
ldy #LETK::LineEditRecord::caret_pos
sta (a_record),y
jsr _ShowCaret
ret: rts
.endproc ; ClickImpl
;;; ============================================================
;;; Move caret one character left.
.proc _MoveCaretLeft
;; Any characters to left of caret?
ldy #LETK::LineEditRecord::caret_pos
lda (a_record),y
beq ret
sec
sbc #1
sta (a_record),y
ret: rts
.endproc ; _MoveCaretLeft
;;; ============================================================
;;; Move caret one character right.
.proc _MoveCaretRight
;; Any characters to right of caret?
ldy #LETK::LineEditRecord::caret_pos
lda (a_record),y ; A = caret_pos
ldy #0
IF_A_NE (a_buf),y
clc
adc #1
ldy #LETK::LineEditRecord::caret_pos
sta (a_record),y
END_IF
rts
.endproc ; _MoveCaretRight
;;; ============================================================
;;; When delete (backspace) is hit
.proc _DeleteLeft
;; Anything to delete?
ldy #LETK::LineEditRecord::caret_pos
lda (a_record),y ; A = caret_pos
IF_NOT_ZERO
sec
sbc #1
sta (a_record),y
jsr _DeleteCharCommon
END_IF
rts
.endproc ; _DeleteLeft
;;; ============================================================
;;; Forward-delete
.proc _DeleteRight
;; Anything to delete?
ldy #LETK::LineEditRecord::caret_pos
lda (a_record),y ; A = caret_pos
ldy #0
IF_A_NE (a_buf),y
jsr _DeleteCharCommon
END_IF
rts
.endproc ; _DeleteRight
;;; ============================================================
;;; Handle a key.
.proc KeyImpl
PARAM_BLOCK params, letk::command_data
a_record .addr
key .byte
modifiers .byte
END_PARAM_BLOCK
.assert a_record = params::a_record, error, "a_record must be first"
MGTK_CALL MGTK::ObscureCursor
jsr _HideCaret
jsr :+
jmp _ShowCaret
: lda params::key
ldx params::modifiers
bne modified
;; Not modified
cmp #CHAR_LEFT
beq _MoveCaretLeft
cmp #CHAR_RIGHT
beq _MoveCaretRight
cmp #CHAR_DELETE
beq _DeleteLeft
cmp #CHAR_CTRL_F
beq _DeleteRight
cmp #CHAR_CLEAR
beq _DeleteLine
cmp #' '
bcs _InsertChar
rts
;; Modified
modified:
cmp #CHAR_LEFT
beq _MoveCaretStart
cmp #CHAR_RIGHT
beq _MoveCaretEnd
rts
.endproc ; KeyImpl
;;; ============================================================
;;; When a non-control key is hit - insert the passed character
.proc _InsertChar
char := tmpw
caret_pos := tmpw+1
sta char
;; Stash current caret pos
ldy #LETK::LineEditRecord::caret_pos
copy8 (a_record),y, caret_pos
;; Is there room?
ldy #0
lda (a_buf),y
IF_A_LT max_length
;; Move everything to right of caret up
tay
DO
BREAK_IF_Y_EQ caret_pos
lda (a_buf),y
iny
sta (a_buf),y
dey
dey
WHILE_NOT_ZERO ; always
;; Insert
lda char
iny
sta (a_buf),y
ldy #0
lda (a_buf),y
clc
adc #1
sta (a_buf),y
bit options ; bit7 = centered
IF_NS
;; Redraw everything
jsr _ClearAndDrawText
ELSE
;; Redraw string to right of old caret position
jsr _RedrawRightOfCaret
END_IF
;; Now move caret to new position
ldy #LETK::LineEditRecord::caret_pos
lda (a_record),y
clc
adc #1
sta (a_record),y
END_IF
ret: rts
.endproc ; _InsertChar
;;; ============================================================
.proc _DeleteLine
;; Anything to delete?
ldy #0
lda (a_buf),y
beq _InsertChar::ret
lda #0
sta (a_buf),y
ldy #LETK::LineEditRecord::caret_pos
sta (a_record),y
jmp _ClearAndDrawText
.endproc ; _DeleteLine
;;; ============================================================
.proc _ClearRect
;; NOTE: Don't include `_SetPort` call in `_ClearRect`
;; because if the port is obscured then `_SetPort` pops
;; the caller!
MGTK_CALL MGTK::SetPenMode, pencopy
MGTK_CALL MGTK::PaintRect, rect
rts
.endproc ; _ClearRect
;;; ============================================================
;;; Move caret to start of input field.
.proc _MoveCaretStart
lda #0
ldy #LETK::LineEditRecord::caret_pos
sta (a_record),y
rts
.endproc ; _MoveCaretStart
;;; ============================================================
;;; Move caret to end of input field.
.proc _MoveCaretEnd
ldy #0
lda (a_buf),y
ldy #LETK::LineEditRecord::caret_pos
sta (a_record),y
rts
.endproc ; _MoveCaretEnd
;;; ============================================================
;;; Common logic for DeleteLeft/DeleteRight
.proc _DeleteCharCommon
len := tmpw
;; Shrink buffer
ldy #0
lda (a_buf),y
sec
sbc #1
sta (a_buf),y
sta len
;; Move everything to the right of the caret down
ldy #LETK::LineEditRecord::caret_pos
lda (a_record),y
tay
DO
BREAK_IF_Y_EQ len
iny
iny
lda (a_buf),y
dey
sta (a_buf),y
WHILE_NE ; always
bit options ; bit7 = centered
IF_NS
;; Redraw everything
jmp _ClearAndDrawText
END_IF
;; Redraw everything to the right of the caret
jsr _RedrawRightOfCaret
jsr _PrepTextParams
IF_NOT_ZERO
MGTK_CALL MGTK::TextWidth, text_params
add16 pos, text_params+MGTK::TextWidthParams::width, rect+MGTK::Rect::x1
END_IF
jmp _ClearRect
.endproc ; _DeleteCharCommon
;;; ============================================================
;;; Output: A,X = X coordinate of caret
.proc _CalcCaretPos
jsr _PrepTextParams
ldy #LETK::LineEditRecord::caret_pos
lda (a_record),y
IF_NOT_ZERO
sta text_params+MGTK::TextWidthParams::length
MGTK_CALL MGTK::TextWidth, text_params
END_IF
lda text_params+MGTK::TextWidthParams::width
clc
adc pos + MGTK::Point::xcoord
tay
lda text_params+MGTK::TextWidthParams::width+1
adc pos + MGTK::Point::xcoord+1
tax
tya
rts
.endproc ; _CalcCaretPos
;;; ============================================================
;;; Clears and redraws text. The caret must be redrawn afterwards
;;; by the caller.
.proc _ClearAndDrawText
jsr _SetPort
jsr _ClearRect
jsr _CalcPos
MGTK_CALL MGTK::MoveTo, pos
jsr _PrepTextParams
IF_NOT_ZERO
MGTK_CALL MGTK::DrawText, text_params
END_IF
rts
.endproc ; _ClearAndDrawText
;;; ============================================================
;;; Redraw the contents of the control; used after a window move or string change.
.proc UpdateImpl
PARAM_BLOCK params, letk::command_data
a_record .addr
END_PARAM_BLOCK
.assert a_record = params::a_record, error, "a_record must be first"
;; Implicitly hides caret
jsr _ClearAndDrawText
;; Fix caret position if string has shrunk
ldy #0
lda (a_buf),y
ldy #LETK::LineEditRecord::caret_pos
cmp (a_record),y ; len >= caret_pos
IF_LT
sta (a_record),y ; no, clamp caret_pos
END_IF
jmp _ShowCaret
.endproc ; UpdateImpl
;;; ============================================================
.endscope ; letk
|
a2stuff/a2d
| 69,991
|
src/toolkits/icontk.s
|
;;; ============================================================
;;; Icon ToolKit
;;; ============================================================
.scope icontk
ITKEntry := *
;;; ============================================================
;;; Zero Page usage (saved/restored around calls)
zp_start := $06
kMaxZPAddress = $50
kMaxCommandDataSize = 9
PARAM_BLOCK, zp_start
;;; Initially points at the call site, then at passed params
params_addr .addr
;;; Copy of the passed params
command_data .res kMaxCommandDataSize
;;; Other ZP usage
generic_ptr .addr
icon_ptr .addr ; Set by `SetIconPtr`, used everywhere
res_ptr .addr ; Set by `GetIconResource`
poly_coords .tag MGTK::Point ; used in `DragHighlighted`
last_coords .tag MGTK::Point ; used in `DragHighlighted`
clip_coords .tag MGTK::Point ; Used for clipped drawing
clip_bounds .tag MGTK::Rect ; Used for clipped drawing
bitmap_rect .tag MGTK::Rect ; populated by `CalcIconRects`
label_rect .tag MGTK::Rect ; populated by `CalcIconRects`
bounding_rect .tag MGTK::Rect ; populated by `CalcIconRects`
rename_rect .tag MGTK::Rect ; populated by `CalcIconRects`
;;; For size calculation, not actually used
zp_end .byte
END_PARAM_BLOCK
.assert zp_end <= kMaxZPAddress, error, "too big"
kBytesToSave = zp_end - zp_start
;;; ============================================================
.assert ITKEntry = Dispatch, error, "dispatch addr"
.proc Dispatch
;; Adjust stack/stash
pla
sta params_lo
clc
adc #<3
tax
pla
sta params_hi
adc #>3
pha
txa
pha
;; Save ZP
PUSH_BYTES kBytesToSave, zp_start
;; Point `params_addr` at the call site
params_lo := *+1
lda #SELF_MODIFIED_BYTE
sta params_addr
params_hi := *+1
lda #SELF_MODIFIED_BYTE
sta params_addr+1
;; Grab command number
ldy #1 ; Note: rts address is off-by-one
lda (params_addr),y
tax
copylohi jump_table_lo,x, jump_table_hi,x, dispatch
;; Point `params_addr` at actual params
iny
lda (params_addr),y
tax
iny
lda (params_addr),y
sta params_addr+1
stx params_addr
.ifdef DEBUG
;; Bad if param block overlaps our zero page useage
cmp16 params_addr, #zp_end
IF_LT
brk
END_IF
.endif ; DEBUG
;; Copy param data to `command_data`
ldy #kMaxCommandDataSize-1
: copy8 (params_addr),y, command_data,y
dey
bpl :-
;; Invoke the command
dispatch := *+1
jsr SELF_MODIFIED
tay ; A = result
;; Restore ZP
POP_BYTES kBytesToSave, zp_start
tya ; A = result
rts
jump_table_lo:
.lobytes InitToolKitImpl
.lobytes AllocIconImpl
.lobytes HighlightIconImpl
.lobytes DrawIconRawImpl
.lobytes FreeIconImpl
.lobytes FreeAllImpl
.lobytes FindIconImpl
.lobytes DragHighlightedImpl
.lobytes UnhighlightIconImpl
.lobytes DrawAllImpl
.lobytes IconInRectImpl
.lobytes EraseIconImpl
.lobytes GetIconBoundsImpl
.lobytes DrawIconImpl
.lobytes GetIconEntryImpl
.lobytes GetRenameRectImpl
.lobytes GetBitmapRectImpl
jump_table_hi:
.hibytes InitToolKitImpl
.hibytes AllocIconImpl
.hibytes HighlightIconImpl
.hibytes DrawIconRawImpl
.hibytes FreeIconImpl
.hibytes FreeAllImpl
.hibytes FindIconImpl
.hibytes DragHighlightedImpl
.hibytes UnhighlightIconImpl
.hibytes DrawAllImpl
.hibytes IconInRectImpl
.hibytes EraseIconImpl
.hibytes GetIconBoundsImpl
.hibytes DrawIconImpl
.hibytes GetIconEntryImpl
.hibytes GetRenameRectImpl
.hibytes GetBitmapRectImpl
ASSERT_EQUALS *-jump_table_hi, jump_table_hi-jump_table_lo
.endproc ; Dispatch
;;; ============================================================
kPolySize = 8
.params poly
num_vertices: .byte kPolySize
lastpoly: .byte 0 ; 0 = last poly
vertices:
DEFINE_POINT v0, 0, 0
DEFINE_POINT v1, 0, 0
DEFINE_POINT v2, 0, 0
DEFINE_POINT v3, 0, 0
DEFINE_POINT v4, 0, 0
DEFINE_POINT v5, 0, 0
DEFINE_POINT v6, 0, 0
DEFINE_POINT v7, 0, 0
.endparams
;;; ============================================================
.params icon_paintbits_params
DEFINE_POINT viewloc, 0, 0
mapbits: .addr 0
mapwidth: .byte 0
reserved: .byte 0
DEFINE_RECT maprect, 0, 0, 0, 0
REF_MAPINFO_MEMBERS
.endparams
.params mask_paintbits_params
DEFINE_POINT viewloc, 0, 0
mapbits: .addr 0
mapwidth: .byte 0
reserved: .byte 0
DEFINE_RECT maprect, 0, 0, 0, 0
REF_MAPINFO_MEMBERS
.endparams
.params textwidth_params
textptr: .addr text_buffer
textlen: .byte 0
result: .word 0
.endparams
settextbg_params := textwidth_params::result + 1 ; re-used
settextbg_white:
.byte MGTK::textbg_white
.params drawtext_params
textptr: .addr text_buffer
textlen: .byte 0
.endparams
;; `text_buffer` contains only the characters; the length
;; is in `drawtext_params::textlen`
text_buffer:
.res 19, 0
white_pattern:
.byte %11111111
.byte %11111111
.byte %11111111
.byte %11111111
.byte %11111111
.byte %11111111
.byte %11111111
.byte %11111111
dark_pattern:
.byte %00010001
.byte %01000100
.byte %00010001
.byte %01000100
.byte %00010001
.byte %01000100
.byte %00010001
.byte %01000100
penOR: .byte MGTK::penOR
penXOR: .byte MGTK::penXOR
penBIC: .byte MGTK::penBIC
;;; ============================================================
;;; Used by `DrawAllImpl` and `EraseIconCommon` (which are not
;;; mutually re-entrant)
.params icon_in_rect_params
icon: .byte 0
rect: .tag MGTK::Rect
.endparams
;;; ============================================================
;;; Icon (i.e. file, volume) details
num_icons: .byte 0
icon_list: .res (::kMaxIconCount+1), 0 ; list of allocated icons (index 0 not used)
icon_ptrs_low: .res (::kMaxIconCount+1), 0 ; addresses of icon details (index 0 not used)
icon_ptrs_high: .res (::kMaxIconCount+1), 0 ; addresses of icon details (index 0 not used)
;;; Input: A = icon number
;;; Output: `icon_ptr` = A,X = address of IconEntry
.proc SetIconPtr
tay
ldx icon_ptrs_high,y
lda icon_ptrs_low,y
stax icon_ptr
rts
.endproc ; SetIconPtr
;;; ============================================================
;;; Initialization parameters passed by client
;;; Vertical offset within windows
header_height: .byte 0
;;; Polygon holding the composite outlines of all icons being dragged.
;;; Re-use the "save area" ($800-$1AFF) since menus won't show during
;;; this kOperation.
polybuf_addr: .addr 0
max_draggable_icons: .byte 0
;;; Mapping of `IconEntry::type` to `IconResource`
typemap_addr: .addr 0
;;; ============================================================
.params peekevent_params
kind: .byte 0 ; spills into next block
.endparams
;;; `findwindow_params::window_id` is used as first part of
;;; GetWinPtr params structure including `window_ptr`.
.params findwindow_params
mousex: .word 0
mousey: .word 0
which_area: .byte 0
window_id: .byte 0
.endparams
window_ptr: .word 0 ; do not move this; see above
ASSERT_EQUALS window_ptr, findwindow_params::window_id + 1, "struct moved"
.params findcontrol_params
mousex: .word 0
mousey: .word 0
which_ctl: .byte 0
which_part: .byte 0
window_id: .byte 0 ; For FindControlEx
.endparams
;;; GrafPort used to draw icon outlines during drag. Set up with the
;;; correct pen and pattern. Does not include the menu bar area.
.params drag_outline_grafport
viewloc: .word 0, kMenuBarHeight
mapbits: .addr MGTK::screen_mapbits
mapwidth: .byte MGTK::screen_mapwidth
reserved: .byte 0
maprect: .word 0, kMenuBarHeight, kScreenWidth-1, kScreenHeight-1
pattern: .byte %01010101
.byte %10101010
.byte %01010101
.byte %10101010
.byte %01010101
.byte %10101010
.byte %01010101
.byte %10101010
colormasks: .byte MGTK::colormask_and, MGTK::colormask_or
penloc: .word 0, 0
penwidth: .byte 1
penheight: .byte 1
penmode: .byte MGTK::penXOR
textback: .byte MGTK::textbg_black
textfont: .addr 0
REF_GRAFPORT_MEMBERS
.endparams
ASSERT_EQUALS .sizeof(drag_outline_grafport), .sizeof(MGTK::GrafPort)
desktop_bounds := drag_outline_grafport::maprect
.params getwinport_params
window_id: .byte 0
a_grafport: .addr icon_grafport
.endparams
icon_grafport: .tag MGTK::GrafPort
;;; ============================================================
;;; InitToolKit
.proc InitToolKitImpl
PARAM_BLOCK params, icontk::command_data
headersize .byte
a_polybuf .addr
bufsize .word
a_typemap .addr
a_heap .addr
END_PARAM_BLOCK
table_ptr := generic_ptr
copy8 params::headersize, header_height
copy16 params::a_polybuf, polybuf_addr
copy16 params::bufsize, bufsize
copy16 params::a_typemap, typemap_addr
copy16 params::a_heap, table_ptr
;; --------------------------------------------------
;; Populate `icon_ptrs_low/high` table
ldx #1
DO
;; Populate table entry
copy8 table_ptr, icon_ptrs_low,x
copy8 table_ptr+1, icon_ptrs_high,x
;; Next entry
add16_8 table_ptr, #.sizeof(IconEntry)
inx
WHILE_X_NE #kMaxIconCount+1 ; allow up to the maximum
;; --------------------------------------------------
;; MaxDraggableItems = BufferSize / kIconPolySize
ldy #0
DO
sub16_8 bufsize, #kIconPolySize
bit bufsize+1
BREAK_IF_NS
iny
WHILE_NOT_ZERO ; always
sty max_draggable_icons
rts
bufsize:
.word 0
.endproc ; InitToolKitImpl
;;; ============================================================
;;; AllocIcon
.proc AllocIconImpl
.struct AllocIconParams
icon .byte ; out
entry .addr ; out
.endstruct
jsr AllocateIcon
ldy #AllocIconParams::icon
sta (params_addr),y
;; Add it to `icon_list`
ldx num_icons
sta icon_list,x
inc num_icons
;; Grab the `IconEntry`, to return it and update it
jsr SetIconPtr
ldy #AllocIconParams::entry
sta (params_addr),y
txa
iny
sta (params_addr),y
;; Initialize IconEntry::state
lda #0
;; ldy #IconEntry::state
ASSERT_EQUALS IconEntry::state, 0
tay
sta (icon_ptr),y
rts
.endproc ; AllocIconImpl
;;; ============================================================
;;; Tests if the passed icon id is in `icon_list`
;;; Inputs: A = icon id
;;; Outputs: Z=1 if found (and X = index), Z=0 otherwise
;;; A is unmodified, X is trashed
.ifdef DEBUG
.proc IsInIconList
ldx num_icons
: dex
bmi done ; X=#$FF, Z=0
cmp icon_list,x
bne :- ; not found
done: rts
.endproc ; IsInIconList
.endif
;;; ============================================================
;;; HighlightIcon
;;; param is pointer to icon id
.proc HighlightIconImpl
PARAM_BLOCK params, icontk::command_data
icon .byte
END_PARAM_BLOCK
;; Pointer to IconEntry
lda params::icon
pha ; A = icon
;; Mark highlighted
jsr GetIconState ; A = state, sets `icon_ptr` too
ora #kIconEntryStateHighlighted
sta (icon_ptr),y
pla ; A = icon
jmp MaybeMoveIconToTop
.endproc ; HighlightIconImpl
;;; ============================================================
;;; FreeIcon
;;; param is pointer to icon number
.proc FreeIconImpl
PARAM_BLOCK params, icontk::command_data
icon .byte
END_PARAM_BLOCK
lda params::icon
.ifdef DEBUG
;; Is it in `icon_list`?
jsr IsInIconList
IF_NOT_ZERO
return #1 ; Not found
END_IF
.endif ; DEBUG
jsr FreeIconCommon ; A = icon id
return #0
.endproc ; FreeIconImpl
;;; ============================================================
;;; Remove the icon
;;; Inputs: A = icon id
.proc FreeIconCommon
;; Remove it
jsr RemoveIconFromList ; returns A unchanged
dec num_icons
;; Mark it as free
jmp FreeIcon
.endproc ; FreeIconCommon
;;; ============================================================
;;; Remove icon from `icon_list` and compact list, but don't
;;; modify `num_icons`; the last entry of the list will be garbage.
;;; Input: A = icon
;;; Output: A unchanged, X = `num_icons`
;;; Assert: icon is in `icon_list`
.proc RemoveIconFromList
pha ; A = icon
;; Find index
ldx num_icons
: dex
cmp icon_list,x
bne :-
;; Shift items down
: copy8 icon_list+1,x, icon_list,x
inx
cpx num_icons
bne :-
pla ; A = icon
rts
.endproc ; RemoveIconFromList
;;; ============================================================
;;; Input: A = icon
;;; Output: Z=0 if fixed, Z=1 if not fixed
.proc IsIconFixed
jsr SetIconPtr
ldy #IconEntry::win_flags
lda (icon_ptr),y
and #kIconEntryFlagsFixed
rts
.endproc ; IsIconFixed
;;; ============================================================
;;; Move icon to end of `icon_list`, i.e. top of z-order, unless
;;; it has `kIconEntryFlagsFixed`.
;;; Input: A = icon
;;; Trashes `icon_ptr`
;;; Assert: icon is in `icon_list`
.proc MaybeMoveIconToTop
pha ; A = icon
jsr IsIconFixed
IF_NOT_ZERO
pla ; discard
rts
END_IF
pla ; A = icon
jsr RemoveIconFromList ; returns with A unchanged, X = `num_icons`
sta icon_list-1,x
rts
.endproc ; MaybeMoveIconToTop
;;; ============================================================
;;; EraseIcon
.proc EraseIconImpl
PARAM_BLOCK params, icontk::command_data
icon .byte
END_PARAM_BLOCK
;; Pointer to IconEntry
lda params::icon
ldx #$80 ; do clip
sec ; do redraw highlighted
jmp EraseIconCommon ; A = icon id, X = clip flag, C = redraw flag
.endproc ; EraseIconImpl
;;; ============================================================
;;; FreeAll
;;; param is window id (0 = desktop)
.proc FreeAllImpl
PARAM_BLOCK params, icontk::command_data
window_id .byte
icon .byte
END_PARAM_BLOCK
ldx num_icons
dex
DO
txa
pha
lda icon_list,x
jsr GetIconWin ; A = window_id
IF_A_EQ params::window_id
pla
pha
tax
lda icon_list,x
jsr FreeIconCommon ; A = icon id
END_IF
pla
tax
dex
WHILE_POS
rts
.endproc ; FreeAllImpl
;;; ============================================================
;;; FindIcon
.proc FindIconImpl
PARAM_BLOCK params, icontk::command_data
coords .tag MGTK::Point
result .byte ; out
window_id .byte
END_PARAM_BLOCK
MGTK_CALL MGTK::MoveTo, params::coords
ldx num_icons
IF_NOT_ZERO
DO
dex
txa
pha
;; Check the icon
lda icon_list,x
jsr GetIconWin ; A = window_id, sets `icon_ptr` too
;; Matching window?
IF_A_EQ params::window_id
;; In poly?
jsr CalcIconPoly ; requires `icon_ptr` set
MGTK_CALL MGTK::InRect, bounding_rect
IF_NOT_ZERO
MGTK_CALL MGTK::InPoly, poly
bne inside ; yes!
END_IF
END_IF
;; Nope, next
pla
tax
WHILE_NOT_ZERO
END_IF
;; Nothing found
lda #0
beq finish ; always
;; Found one!
inside: pla
tax
lda icon_list,x
finish:
ldy #params::result - params
sta (params_addr),y
rts
.endproc ; FindIconImpl
;;; ============================================================
;;; DragHighlighted
.proc DragHighlightedImpl
PARAM_BLOCK params, icontk::command_data
icon .byte ; in/out
coords .tag MGTK::Point
END_PARAM_BLOCK
initial_coords := params::coords
poly_dx := poly_coords + MGTK::Point::xcoord
poly_dy := poly_coords + MGTK::Point::ycoord
;; Copy initial coords to `last_coords`
COPY_STRUCT MGTK::Point, initial_coords, last_coords
lda #0
sta highlight_icon_id
sta trash_flag
;;; Determine if it's a drag or just a click
.scope _DragDetectImpl
peek: MGTK_CALL MGTK::PeekEvent, peekevent_params
lda peekevent_params::kind
IF_A_NE #MGTK::EventKind::drag
lda #IconTK::kDragResultNotADrag
jmp exit_with_a
END_IF
kDragDelta = 5
;; Compute mouse delta
ldx #2 ; loop over dimensions
DO
lda findwindow_params,x
sec
sbc z:last_coords,x
tay
lda findwindow_params+1,x
sbc z:last_coords+1,x
IF_NEG
cpy #AS_BYTE(-kDragDelta)
bcc is_drag ; above threshold, so drag
bcs next ; always
END_IF
cpy #kDragDelta ; above threshold, so drag
bcs is_drag
next: dex
dex
WHILE_POS
bmi peek ; always
.endscope ; _DragDetectImpl
;; --------------------------------------------------
;; Meets the threshold - it is a drag, not just a click.
is_drag:
;; Count number of highlighted icons
copy8 #0, highlight_count
INVOKE_WITH_LAMBDA _IterateHighlightedIcons
;; Count this one, and remember as potentially last
inc highlight_count
sta last_highlighted_icon
;; Also check if Trash, and set flag appropriately
jsr GetIconFlags
and #kIconEntryFlagsNotDropSource
IF_NOT_ZERO
copy8 #$80, trash_flag
END_IF
rts
END_OF_LAMBDA
;; Assert: there are highlighted icons
;; Make sure there's room
lda highlight_count
cmp max_draggable_icons
beq :+ ; equal okay
jcs exit_canceled ; too many
:
lda last_highlighted_icon
jsr GetIconWin
sta source_window_id
;; --------------------------------------------------
;; Build drag polygon
poly_ptr := generic_ptr
copy16 polybuf_addr, poly_ptr
copy8 #$80, poly::lastpoly ; more to follow
INVOKE_WITH_LAMBDA _IterateHighlightedIcons
jsr CalcIconPoly ; sets `res_ptr`
;; Copy poly into place
ldy #kIconPolySize-1
DO
copy8 poly,y, (poly_ptr),y
dey
WHILE_POS
add16_8 poly_ptr, #kIconPolySize
rts
END_OF_LAMBDA
;; Mark last icon
sub16_8 poly_ptr, #kIconPolySize
ldy #1 ; MGTK Polygon "not last" flag
copy8 #0, (poly_ptr),y ; last polygon
copy8 #0, poly::lastpoly ; restore default
;; --------------------------------------------------
jsr _XDrawOutline
peek: MGTK_CALL MGTK::PeekEvent, peekevent_params
lda peekevent_params::kind
cmp #MGTK::EventKind::drag
jne not_drag
;; Escape key?
lda KBD ; MGTK doesn't process keys during drag
IF_A_EQ #CHAR_ESCAPE | $80
bit KBDSTRB ; consume the keypress
copy8 #MGTK::EventKind::key_down, peekevent_params::kind
jmp not_drag
END_IF
;; Coords changed?
ldx #.sizeof(MGTK::Point)-1
DO
lda findwindow_params,x
cmp last_coords,x
bne moved
dex
WHILE_POS
bmi peek ; always
;; --------------------------------------------------
;; Mouse moved - check for (un)highlighting, and
;; update the drag outline.
moved:
jsr _XDrawOutline
;; Check for highlighting changes
bit trash_flag ; Trash is not drop-able, so skip if in selection
bmi update_poly
jsr _FindIconValidateWindow
cmp highlight_icon_id
beq update_poly ; no change
;; No longer over the highlighted icon - unhighlight it
pha
lda highlight_icon_id
IF_NOT_ZERO
jsr _UnhighlightIcon
copy8 #0, highlight_icon_id
END_IF
;; Is the new icon valid?
pla
beq update_poly
jsr _ValidateTargetAndHighlight
update_poly:
;; Update poly coordinates
ldx #2 ; loop over dimensions
DO
sub16 findwindow_params,x, last_coords,x, poly_coords,x
dex ; next dimension
dex
WHILE_POS
COPY_STRUCT MGTK::Point, findwindow_params::mousex, last_coords
copy16 polybuf_addr, poly_ptr
ploop: ldy #2 ; offset in poly to first vertex
DO
add16in (poly_ptr),y, poly_dx, (poly_ptr),y
iny
add16in (poly_ptr),y, poly_dy, (poly_ptr),y
iny
WHILE_Y_NE #kIconPolySize
ldy #1 ; MGTK Polygon "not last" flag
lda (poly_ptr),y
IF_NOT_ZERO
lda poly_ptr
clc
adc #kIconPolySize
sta poly_ptr
bcc ploop
inc poly_ptr+1
bcs ploop ; always
END_IF
jsr _XDrawOutline
jmp peek
;; --------------------------------------------------
;; End of the drag - figure out how to finish up
not_drag:
jsr _XDrawOutline
lda highlight_icon_id
IF_NOT_ZERO
jsr _UnhighlightIcon
END_IF
;; Drag ended by a keystroke?
lda peekevent_params::kind
cmp #MGTK::EventKind::key_down ; cancel?
jeq exit_canceled
;; Drag ended over an icon?
lda highlight_icon_id
jne exit_drop
;; Drag ended over a window or desktop?
MGTK_CALL MGTK::FindWindow, findwindow_params
lda findwindow_params::window_id
pha
ora #$80
sta highlight_icon_id
pla
cmp source_window_id
beq same_window
bit trash_flag
jmi exit_canceled
jmp exit_drop
;; Drag within same window (or desktop)
same_window:
ldx #$80 ; clip (if desktop)
lda findwindow_params::which_area
ASSERT_EQUALS MGTK::Area::desktop, 0
beq move_ok
cmp #MGTK::Area::content
jne exit_canceled ; don't move
jsr _CheckRealContentArea
jcs exit_canceled ; don't move
lda last_highlighted_icon
jsr IsIconFixed ; Z=0 if fixed
jne exit_canceled ; don't move
;; --------------------------------------------------
;; Probably a move within the same window...
ldx #0 ; don't clip (not desktop; unnecessary)
move_ok:
stx ::drag_highlighted_lambda_clip_flag
;; ... but skip if modifier(s) down; allows other gestures.
lda BUTN0
ora BUTN1
IF_NS
lda #IconTK::kDragResultMoveModified
ASSERT_NOT_EQUALS IconTK::kDragResultMoveModified, 0
bne exit_with_a
END_IF
INVOKE_WITH_LAMBDA _IterateHighlightedIcons
::drag_highlighted_lambda_clip_flag := *+1
ldx #SELF_MODIFIED_BYTE
clc ; don't redraw highlighted
jmp EraseIconCommon ; A = icon id, X = clip flag, C = redraw flag
END_OF_LAMBDA
;; --------------------------------------------------
;; Update icons with new positions (based on delta)
ldx #2 ; loop over dimensions
DO
sub16 findwindow_params,x, initial_coords,x, poly_coords,x
dex ; next dimension
dex
WHILE_POS
INVOKE_WITH_LAMBDA _IterateHighlightedIcons
jsr SetIconPtr
ldy #IconEntry::iconx
add16in (icon_ptr),y, poly_dx, (icon_ptr),y
iny
add16in (icon_ptr),y, poly_dy, (icon_ptr),y
rts
END_OF_LAMBDA
lda #IconTK::kDragResultMove
FALL_THROUGH_TO exit_with_a
;; --------------------------------------------------
exit_with_a:
tax ; A = return value
ldy #params::icon - params
copy8 highlight_icon_id, (params_addr),y
txa ; A = return value
rts
exit_drop:
lda #IconTK::kDragResultDrop
ASSERT_EQUALS IconTK::kDragResultDrop, 0
beq exit_with_a
exit_canceled:
lda #IconTK::kDragResultCanceled
ASSERT_NOT_EQUALS IconTK::kDragResultCanceled, 0
bne exit_with_a
;;; ============================================================
;; IconTK::HighlightIcon params
;; also used as the return value
highlight_icon_id: .byte $00
source_window_id: .byte 0 ; source window of drag (0=desktop)
trash_flag: .byte 0 ; if Trash is included in selection
highlight_count:
.byte 0
last_highlighted_icon:
.byte 0
;;; Inputs: A,X = proc; called with A = icon id
;;;
.proc _IterateHighlightedIcons
stax proc
ldx #0
stx index
DO
lda icon_list,x
jsr GetIconState
and #kIconEntryStateHighlighted
IF_NOT_ZERO
ldx index
lda icon_list,x
proc := *+1
jsr SELF_MODIFIED
END_IF
inc index
index := *+1
ldx #SELF_MODIFIED_BYTE
WHILE_X_NE num_icons
rts
.endproc ; _IterateHighlightedIcons
;;; Like `FindIcon`, but validates that the passed coordinates are
;;; in the true content area of the window (not scrollbars/grow box/header)
;;;
;;; Inputs: `findwindow_params` mouse coords populated
;;; Outputs: A = icon (0 if none found), `findwindow_params::window_id` populated
;;; Trashes `generic_ptr`
.proc _FindIconValidateWindow
MGTK_CALL MGTK::FindWindow, findwindow_params
lda findwindow_params::which_area
ASSERT_EQUALS MGTK::Area::desktop, 0
beq desktop
;; --------------------------------------------------
;; In a window - ensure it's in the content area
cmp #MGTK::Area::content
bne fail ; menubar, titlebar, etc
jsr _CheckRealContentArea
bcc find_icon
fail: return #0 ; no icon
;; --------------------------------------------------
;; On desktop - A=0, note that as window_id
desktop:
sta findwindow_params::window_id
;; --------------------------------------------------
;; Is there an icon there?
find_icon:
ITK_CALL IconTK::FindIcon, findwindow_params
lda findwindow_params::which_area ; Icon ID
rts
.endproc ; _FindIconValidateWindow
;;; Dig deeper into FindWindow results to ensure it's really content.
;;; Input: `findwindow_params` populated
;;; Output: C=0 if content, C=1 if non-content
;;; Assert: `FindWindow` was called and returned `Area::content`
;;; Trashes `generic_ptr`
.proc _CheckRealContentArea
COPY_STRUCT MGTK::Point, findwindow_params::mousex, findcontrol_params::mousex
copy8 findwindow_params::window_id, findcontrol_params::window_id
MGTK_CALL MGTK::FindControlEx, findcontrol_params
bne fail
lda findcontrol_params::which_ctl
ASSERT_EQUALS MGTK::Ctl::not_a_control, 0
bne fail ; scrollbar, etc.
;; Ignore if y coord < window's header height
MGTK_CALL MGTK::GetWinPtr, findwindow_params::window_id
win_ptr := generic_ptr
copy16 window_ptr, z:win_ptr
ldy #MGTK::Winfo::port + MGTK::GrafPort::viewloc + MGTK::Point::ycoord
lda (win_ptr),y
copy16in (win_ptr),y, headery
add16_8 headery, header_height
cmp16 findwindow_params::mousey, headery
bcc fail
clc
rts
fail: sec
rts
headery:
.word 0
.endproc ; _CheckRealContentArea
.proc _ValidateTargetAndHighlight
;; Over an icon
sta icon_num
jsr GetIconState ; A = state, sets `icon_ptr` too
;; Highlighted?
;;and #kIconEntryStateHighlighted
ASSERT_EQUALS ::kIconEntryStateHighlighted, $40
asl
bmi done ; Not valid (it's being dragged)
;; Is it a drop target?
;;ldy #IconEntry::win_flags
ASSERT_EQUALS (IconEntry::win_flags - IconEntry::state), 1
iny
lda (icon_ptr),y
;;and #kIconEntryFlagsDropTarget
ASSERT_EQUALS ::kIconEntryFlagsDropTarget, $40
asl
bpl done
;; Highlight it!
icon_num := *+1
lda #SELF_MODIFIED_BYTE
sta highlight_icon_id
jsr _HighlightIcon
done: rts
.endproc ; _ValidateTargetAndHighlight
.proc _XDrawOutline
copy16 polybuf_addr, addr
MGTK_CALL MGTK::SetPort, drag_outline_grafport
MGTK_CALL MGTK::FramePoly, SELF_MODIFIED, addr
rts
.endproc ; _XDrawOutline
.proc _HighlightIcon
ITK_CALL IconTK::HighlightIcon, highlight_icon_id
ITK_CALL IconTK::DrawIcon, highlight_icon_id
rts
.endproc ; _HighlightIcon
.proc _UnhighlightIcon
ITK_CALL IconTK::UnhighlightIcon, highlight_icon_id
ITK_CALL IconTK::DrawIcon, highlight_icon_id
rts
.endproc ; _UnhighlightIcon
.endproc ; DragHighlightedImpl
;;; ============================================================
;;; Input: A = icon number
;;; Output: A = window id (0=desktop), `icon_ptr` set
.proc GetIconWin
jsr GetIconFlags
and #kIconEntryWinIdMask
rts
.endproc ; GetIconWin
;;; Input: A = icon number
;;; Output: A = flags (including window), Y = IconEntry::win_flags, `icon_ptr` set
.proc GetIconFlags
jsr SetIconPtr
ldy #IconEntry::win_flags
lda (icon_ptr),y
rts
.endproc ; GetIconFlags
;;; Input: A = icon number
;;; Output: A = state, Y = IconEntry::state, `icon_ptr` set
.proc GetIconState
jsr SetIconPtr
ldy #IconEntry::state
lda (icon_ptr),y
rts
.endproc ; GetIconState
;;; ============================================================
;;; UnhighlightIcon
;;; param is pointer to IconEntry
.proc UnhighlightIconImpl
PARAM_BLOCK params, icontk::command_data
icon .byte
END_PARAM_BLOCK
;; Pointer to IconEntry
lda params::icon
pha ; A = icon
;; Mark not highlighted
jsr GetIconState ; A = state, sets `icon_ptr` too
and #AS_BYTE(~kIconEntryStateHighlighted)
sta (icon_ptr),y
pla ; A = icon
jmp MaybeMoveIconToTop
.endproc ; UnhighlightIconImpl
;;; ============================================================
;;; IconInRect
.proc IconInRectImplImpl
PARAM_BLOCK params, icontk::command_data
icon .byte
rect .tag MGTK::Rect
END_PARAM_BLOCK
start:
lda params::icon
jsr SetIconPtr
jsr CalcIconRects
;; Compare the rect against both the bitmap and label rects
;; --------------------------------------------------
;; Bitmap
ldx #2 ; loop over dimensions
DO
;; top/left of bitmap > bottom/right of rect --> outside
scmp16 params::rect+MGTK::Rect::bottomright,x, bitmap_rect+MGTK::Rect::topleft,x
bmi :+
;; bottom/right of bitmap < top/left of rect --> outside
scmp16 bitmap_rect+MGTK::Rect::bottomright,x, params::rect+MGTK::Rect::topleft,x
bmi :+
dex ; next dimension
dex
WHILE_POS
bmi inside ; always
:
;; --------------------------------------------------
;; Label
ldx #2 ; loop over dimensions
DO
;; top/left of text > bottom/right of rect --> outside
scmp16 params::rect+MGTK::Rect::bottomright,x, label_rect+MGTK::Rect::topleft,x
bmi outside
;; bottom/right of text < top/left of rect --> outside
scmp16 label_rect+MGTK::Rect::bottomright,x, params::rect+MGTK::Rect::topleft,x
bmi outside
dex ; next dimension
dex
WHILE_POS
inside:
return #1
outside:
return #0
.endproc ; IconInRectImplImpl
IconInRectImpl := IconInRectImplImpl::start
;;; ============================================================
;;; GetIconBounds
.proc GetIconBoundsImpl
PARAM_BLOCK params, icontk::command_data
icon .byte
rect .tag MGTK::Rect ; out
END_PARAM_BLOCK
;; Calc icon bounds
lda params::icon
jsr SetIconPtr
jsr CalcIconBoundingRect
;; Copy rect into out params
ldx #.sizeof(MGTK::Rect)-1
ldy #(params::rect - params) + .sizeof(MGTK::Rect)-1
DO
copy8 bounding_rect,x, (params_addr),y
dey
dex
WHILE_POS
rts
.endproc ; GetIconBoundsImpl
;;; ============================================================
;;; GetRenameRect
.proc GetRenameRectImpl
PARAM_BLOCK params, icontk::command_data
icon .byte
rect .tag MGTK::Rect ; out
END_PARAM_BLOCK
;; Calc icon bounds
ASSERT_EQUALS params::icon, icontk::command_data
jsr GetXYZRectImplHelper
;; Copy rect into out params
ldx #.sizeof(MGTK::Rect)-1
ldy #(params::rect - params) + .sizeof(MGTK::Rect)-1
DO
copy8 rename_rect,x, (params_addr),y
dey
dex
WHILE_POS
rts
.endproc ; GetRenameRectImpl
;;; ============================================================
;;; GetBitmapRect
.proc GetBitmapRectImpl
PARAM_BLOCK params, icontk::command_data
icon .byte
rect .tag MGTK::Rect ; out
END_PARAM_BLOCK
;; Calc icon bounds
ASSERT_EQUALS params::icon, icontk::command_data
jsr GetXYZRectImplHelper
;; Copy rect into out params
ldx #.sizeof(MGTK::Rect)-1
ldy #(params::rect - params) + .sizeof(MGTK::Rect)-1
DO
copy8 bitmap_rect,x, (params_addr),y
dey
dex
WHILE_POS
rts
.endproc ; GetBitmapRectImpl
.proc GetXYZRectImplHelper
lda command_data ; a.k.a. `params::icon`
jsr SetIconPtr
jmp CalcIconRects
.endproc ; GetXYZRectImplHelper
;;; ============================================================
;;; Used by `DrawIcon` and `EraseIcon`. Has bit7 = 0 on first call
;;; to `CalcWindowIntersections` to signal the start of a clipping
;;; sequence. Set bit7 if a subsequent call is needed, and clear
;;; once all drawing is complete.
more_drawing_needed_flag:
.byte 0
;;; Set by some callers of `DrawIconCommon` and `EraseIconCommon`
clip_icons_flag:
.byte 0
;;; Window containing the icon, used during clipping/redrawing
clip_window_id:
.byte 0
;;; ============================================================
;;; DrawIconRaw
;;; * Assumes correct grafport already selected/maprect specified
;;; * Does not erase background
.proc DrawIconRawImpl
lda #0 ; `clip_icons_flag`
jmp DrawIconCommon
.endproc ; DrawIconRawImpl
;;; ============================================================
;;; DrawIcon
;;; * Draws icon clipping against any overlapping windows.
;;; * Does not erase background
.proc DrawIconImpl
jsr InitSetIconPort
lda #$80 ; `clip_icons_flag`
FALL_THROUGH_TO DrawIconCommon
.endproc ; DrawIconImpl
;;; ============================================================
.proc DrawIconCommon
PARAM_BLOCK params, icontk::command_data
icon .byte
END_PARAM_BLOCK
sta clip_icons_flag
;; Slow enough that events should be checked; this allows
;; double-clicks during icon repaints (e.g. deselects)
MGTK_CALL MGTK::CheckEvents
;; Pointer to IconEntry
lda params::icon
jsr SetIconPtr
jsr CalcIconRects
;; Stash some flags
ldy #IconEntry::state
copy8 (icon_ptr),y, state
ASSERT_EQUALS IconEntry::win_flags, IconEntry::state + 1
iny
copy8 (icon_ptr),y, win_flags
;; For quick access
and #kIconEntryWinIdMask
sta clip_window_id
;; copy icon definition bits
jsr GetIconResource ; sets `res_ptr` based on `icon_ptr`
ldy #.sizeof(MGTK::MapInfo) - .sizeof(MGTK::Point) - 1
DO
lda (res_ptr),y
sta icon_paintbits_params::mapbits,y
sta mask_paintbits_params::mapbits,y
dey
WHILE_POS
;; Icon definition is followed by pointer to mask address.
ldy #.sizeof(MGTK::MapInfo) - .sizeof(MGTK::Point)
copy16in (res_ptr),y, mask_paintbits_params::mapbits
;; Determine if we want clipping, based on icon type and flags.
bit clip_icons_flag
bpl _DoPaint ; no clipping, just paint
;; Set up clipping structs and port
lda clip_window_id
IF_ZERO
jsr SetPortForVolIcon
ELSE
jsr SetPortForWinIcon
bne ret ; obscured
END_IF
;; Paint icon iteratively, handling overlapping windows
DO
jsr CalcWindowIntersections
BREAK_IF_CS ; nothing remaining to draw
jsr OffsetPortAndIcon
jsr _DoPaint
jsr OffsetPortAndIcon
bit more_drawing_needed_flag
WHILE_NS
ret: rts
.proc _DoPaint
label_pos := generic_ptr
;; Prep coords
copy16 label_rect+MGTK::Rect::x1, label_pos+MGTK::Point::xcoord
add16_8 label_rect+MGTK::Rect::y1, #kSystemFontHeight-1, label_pos+MGTK::Point::ycoord
ldax bitmap_rect+MGTK::Rect::x1
stax icon_paintbits_params::viewloc::xcoord
stax mask_paintbits_params::viewloc::xcoord
ldax bitmap_rect+MGTK::Rect::y1
stax icon_paintbits_params::viewloc::ycoord
stax mask_paintbits_params::viewloc::ycoord
;; Set text background color
lda #MGTK::textbg_white
ASSERT_EQUALS ::kIconEntryStateHighlighted, $40
bit state ; highlighted?
IF_VS
lda #MGTK::textbg_black
END_IF
sta settextbg_params
MGTK_CALL MGTK::SetTextBG, settextbg_params
MGTK_CALL MGTK::HideCursor
;; --------------------------------------------------
;; Icon
;; Shade (XORs background)
ASSERT_EQUALS ::kIconEntryStateDimmed, $80
bit state
IF_NS
MGTK_CALL MGTK::SetPattern, dark_pattern
jsr _Shade
END_IF
;; Mask (cleared to white or black)
ASSERT_EQUALS ::kIconEntryStateHighlighted, $40
bit state
IF_VS
MGTK_CALL MGTK::SetPenMode, penBIC
ELSE
MGTK_CALL MGTK::SetPenMode, penOR
END_IF
MGTK_CALL MGTK::PaintBitsHC, mask_paintbits_params
;; Shade again (restores background)
ASSERT_EQUALS ::kIconEntryStateDimmed, $80
bit state
IF_NS
jsr _Shade
END_IF
;; Icon (drawn in black or white)
ASSERT_EQUALS ::kIconEntryStateHighlighted, $40
bit state
IF_VS
MGTK_CALL MGTK::SetPenMode, penOR
ELSE
MGTK_CALL MGTK::SetPenMode, penBIC
END_IF
MGTK_CALL MGTK::PaintBitsHC, icon_paintbits_params
;; --------------------------------------------------
;; Label
MGTK_CALL MGTK::MoveTo, label_pos
MGTK_CALL MGTK::DrawText, drawtext_params
MGTK_CALL MGTK::ShowCursor
MGTK_CALL MGTK::SetTextBG, settextbg_white
return #0
.proc _Shade
MGTK_CALL MGTK::SetPenMode, penXOR
MGTK_CALL MGTK::PaintRect, bitmap_rect
rts
.endproc ; _Shade
.endproc ; _DoPaint
state: ; copy of IconEntry::state
.byte 0
win_flags: ; copy of IconEntry::win_flags
.byte 0
.endproc ; DrawIconCommon
;;; ============================================================
;;; Inputs: `icon_ptr` = `IconEntry`
;;; Output: `res_ptr` = `IconResource`
.proc GetIconResource
ldy #IconEntry::type
lda (icon_ptr),y ; A = type
asl ; *= 2
tay ; Y = table offset
;; Re-use `res_ptr` temporarily
copy16 typemap_addr, res_ptr
lda (res_ptr),y
tax
iny
lda (res_ptr),y
sta res_ptr+1
stx res_ptr
rts
.endproc ; GetIconResource
;;; ============================================================
kIconLabelGapV = 2
;;; Input: `icon_ptr` points at icon
;;; Output: Populates `bitmap_rect` and `label_rect` and `text_buffer`
;;; Sets `res_ptr`
.proc CalcIconRects
;; Copy, pad, and measure name
jsr PrepareName
jsr GetIconResource ; sets `res_ptr` based on `icon_ptr`
;; Bitmap top/left - copy from icon entry
ldy #IconEntry::iconx+3
ldx #3
DO
copy8 (icon_ptr),y, bitmap_rect+MGTK::Rect::topleft,x
dey
dex
WHILE_POS
;; Bitmap bottom/right
ldy #IconResource::maprect + MGTK::Rect::x2
add16in bitmap_rect+MGTK::Rect::x1, (res_ptr),y, bitmap_rect+MGTK::Rect::x2
iny
add16in bitmap_rect+MGTK::Rect::y1, (res_ptr),y, bitmap_rect+MGTK::Rect::y2
ldy #IconEntry::win_flags
lda (icon_ptr),y
and #kIconEntryFlagsSmall
IF_NOT_ZERO
;; ----------------------------------------
;; Small icon
;; Label top
copy16 bitmap_rect+MGTK::Rect::y1, label_rect+MGTK::Rect::y1
;; Label bottom
add16_8 label_rect+MGTK::Rect::y1, #kSystemFontHeight+1, label_rect+MGTK::Rect::y2
;; Left edge of label
add16_8 bitmap_rect+MGTK::Rect::x2, #kListViewIconGap-2, label_rect+MGTK::Rect::x1
jsr stash_rename_rect
;; Force bitmap bottom to same height
copy16 label_rect+MGTK::Rect::y2, bitmap_rect+MGTK::Rect::y2
ELSE
;; ----------------------------------------
;; Regular icon
;; Label top
add16_8 bitmap_rect+MGTK::Rect::y2, #kIconLabelGapV, label_rect+MGTK::Rect::y1
;; Label bottom
add16_8 label_rect+MGTK::Rect::y1, #kSystemFontHeight, label_rect+MGTK::Rect::y2
;; Center horizontally
;; Left edge of label
;; text_left = icon_left + icon_width/2 - text_width/2
;; = (icon_left*2 + icon_width - text_width) / 2
;; NOTE: Left is computed before right to match rendering code
copy16 bitmap_rect+MGTK::Rect::x1, label_rect+MGTK::Rect::x1
asl16 label_rect+MGTK::Rect::x1
ldy #IconResource::maprect + MGTK::Rect::x2
add16in label_rect+MGTK::Rect::x1, (res_ptr),y, label_rect+MGTK::Rect::x1
jsr stash_rename_rect
sub16 label_rect+MGTK::Rect::x1, textwidth_params::result, label_rect+MGTK::Rect::x1
asr16 label_rect+MGTK::Rect::x1 ; signed
sub16_8 rename_rect+MGTK::Rect::x1, #kIconRenameLineEditWidth, rename_rect+MGTK::Rect::x1
asr16 rename_rect+MGTK::Rect::x1
END_IF
;; Label right
add16 label_rect+MGTK::Rect::x1, textwidth_params::result, label_rect+MGTK::Rect::x2
add16_8 rename_rect+MGTK::Rect::x1, #kIconRenameLineEditWidth, rename_rect+MGTK::Rect::x2
dec16 rename_rect+MGTK::Rect::y1
rts
stash_rename_rect:
COPY_STRUCT MGTK::Rect, label_rect, rename_rect
rts
.endproc ; CalcIconRects
;;; Input: `icon_ptr` points at icon
;;; Output: Populates `bitmap_rect` and `label_rect` and `bounding_rect`
;;; Sets `res_ptr`
.proc CalcIconBoundingRect
jsr CalcIconRects
COPY_BLOCK bitmap_rect, bounding_rect
;; Union of rectangles (expand `bounding_rect` to encompass `label_rect`)
MGTK_CALL MGTK::UnionRects, unionrects_label_bounding
rts
.endproc ; CalcIconBoundingRect
.params unionrects_label_bounding
.addr label_rect
.addr bounding_rect
.endparams
kIconPolySize = (8 * .sizeof(MGTK::Point)) + 2
;;; Input: `icon_ptr` points at icon
;;; Output: Populates `bitmap_rect` and `label_rect` and `bounding_rect`
;;; and (of course) `poly`
.proc CalcIconPoly
jsr CalcIconBoundingRect
ldy #IconEntry::win_flags
lda (icon_ptr),y
and #kIconEntryFlagsSmall
IF_NOT_ZERO
;; ----------------------------------------
;; Small icon
;; v0/v1/v2/v3/v4 v5
;; +-----------------------+
;; | |
;; | |
;; +-----------------------+
;; v7 v6
;; Start off making all (except v6) the same
ldx #.sizeof(MGTK::Point)-1
DO
lda bitmap_rect+MGTK::Rect::topleft,x
sta poly::v0,x
sta poly::v1,x
sta poly::v2,x
sta poly::v3,x
sta poly::v4,x
sta poly::v5,x
sta poly::v7,x
dex
WHILE_POS
;; Then tweak remaining vertices on right/bottom
ldax label_rect+MGTK::Rect::x2
stax poly::v5::xcoord
stax poly::v6::xcoord
ldax bitmap_rect+MGTK::Rect::y2
stax poly::v6::ycoord
stax poly::v7::ycoord
ELSE
;; ----------------------------------------
;; Normal icon
;; v0 v1
;; +----------+
;; | |
;; | |
;; | |
;; v7 | | v2
;; v6 +-----+ +-----+ v3
;; | |
;; v5 +----------------------+ v4
;; Even vertexes are (mostly) direct copies from rects
;; v0/v2 (and extend bitmap rect down to top of text)
COPY_STRUCT MGTK::Point, bitmap_rect+MGTK::Rect::topleft, poly::v0
copy16 bitmap_rect+MGTK::Rect::x2, poly::v2::xcoord
copy16 label_rect+MGTK::Rect::y1, poly::v2::ycoord
;; v6/v4
COPY_STRUCT MGTK::Point, label_rect+MGTK::Rect::topleft, poly::v6
COPY_STRUCT MGTK::Point, label_rect+MGTK::Rect::bottomright, poly::v4
;; Odd vertexes are combinations
;; v1
copy16 poly::v2::xcoord, poly::v1::xcoord
copy16 poly::v0::ycoord, poly::v1::ycoord
;; v7
copy16 poly::v0::xcoord, poly::v7::xcoord
copy16 poly::v2::ycoord, poly::v7::ycoord
;; v3
copy16 poly::v4::xcoord, poly::v3::xcoord
copy16 poly::v6::ycoord, poly::v3::ycoord
;; v5
copy16 poly::v6::xcoord, poly::v5::xcoord
copy16 poly::v4::ycoord, poly::v5::ycoord
;; ----------------------------------------
END_IF
rts
.endproc ; CalcIconPoly
;;; Copy name from IconEntry (`icon_ptr`) to text_buffer,
;;; with leading/trailing spaces, and measure it.
.proc PrepareName
.assert text_buffer - 1 = drawtext_params::textlen, error, "location mismatch"
dest := drawtext_params::textlen
ldy #.sizeof(IconEntry)
ldx #.sizeof(IconEntry) - IconEntry::name
DO
copy8 (icon_ptr),y, dest + 1,x
dey
dex
WHILE_POS
ldy dest + 1
iny
iny
sty dest
lda #' '
sta dest + 1
sta dest,y
copy8 drawtext_params::textlen, textwidth_params::textlen
MGTK_CALL MGTK::TextWidth, textwidth_params
rts
.endproc ; PrepareName
;;; ============================================================
;;; DrawAll
.proc DrawAllImpl
PARAM_BLOCK params, icontk::command_data
window_id .byte
END_PARAM_BLOCK
;; Get current clip rect
port_ptr := generic_ptr
MGTK_CALL MGTK::GetPort, port_ptr
ldx #.sizeof(MGTK::Rect)-1
ldy #MGTK::MapInfo::maprect + .sizeof(MGTK::Rect)-1
DO
copy8 (port_ptr),y, icon_in_rect_params::rect,x
dey
dex
WHILE_POS
;; Loop over all icons
ldx #AS_BYTE(-1)
DO
inx
BREAK_IF_X_EQ num_icons
txa
pha
copy8 icon_list,x, icon_in_rect_params::icon
;; Is it in the target window?
jsr GetIconWin ; A = window_id, sets `icon_ptr` too
IF_A_EQ params::window_id
;; In maprect?
ITK_CALL IconTK::IconInRect, icon_in_rect_params
IF_NOT_ZERO
ITK_CALL IconTK::DrawIconRaw, icon_in_rect_params::icon
END_IF
END_IF
pla
tax
WHILE_POS ; always
rts
.endproc ; DrawAllImpl
;;; ============================================================
;;; GetIconEntry
.proc GetIconEntryImpl
PARAM_BLOCK params, icontk::command_data
icon .byte ; in
entry .addr ; out
END_PARAM_BLOCK
lda params::icon
jsr SetIconPtr
ldy #params::entry - params
sta (params_addr),y
txa
iny
sta (params_addr),y
rts
.endproc ; GetIconEntryImpl
;;; ============================================================
;;; Erase an icon; redraws overlapping icons as needed
;;; Inputs: A = icon id, X = clip_icons_flag, C = redraw highlighted flag
.proc EraseIconCommon
sta erase_icon_id
stx clip_icons_flag
ror redraw_highlighted_flag ; shift C into high bit
jsr SetIconPtr
jsr CalcIconPoly
jsr InitSetIconPort
ldy #IconEntry::win_flags
lda (icon_ptr),y
and #kIconEntryWinIdMask
sta clip_window_id
sta getwinport_params::window_id
IF_ZERO
jsr SetPortForVolIcon
MGTK_CALL MGTK::GetDeskPat, addr
MGTK_CALL MGTK::SetPattern, SELF_MODIFIED, addr
ELSE
jsr SetPortForWinIcon
RTS_IF_NE ; obscured!
MGTK_CALL MGTK::SetPattern, white_pattern
END_IF
bit clip_icons_flag
IF_NC
MGTK_CALL MGTK::PaintPoly, poly
ELSE
DO
jsr CalcWindowIntersections
BREAK_IF_CS ; nothing remaining to draw
MGTK_CALL MGTK::PaintPoly, poly
bit more_drawing_needed_flag
WHILE_NS
END_IF
FALL_THROUGH_TO _RedrawIconsAfterErase
;;; ============================================================
;;; After erasing an icon, redraw any overlapping icons
.proc _RedrawIconsAfterErase
COPY_BLOCK bounding_rect, icon_in_rect_params::rect
ldx num_icons
DO
dex ; any icons to draw?
RTS_IF_NEG
txa
pha
lda icon_list,x
cmp erase_icon_id
beq next
sta icon_in_rect_params::icon
jsr GetIconWin ; A = window_id, sets `icon_ptr` too
;; Same window?
cmp clip_window_id
bne next
bit redraw_highlighted_flag
IF_NC
ldy #IconEntry::state
lda (icon_ptr),y
and #kIconEntryStateHighlighted
bne next
END_IF
ITK_CALL IconTK::IconInRect, icon_in_rect_params
IF_NOT_ZERO
lda clip_window_id
IF_ZERO
ITK_CALL IconTK::DrawIcon, icon_in_rect_params::icon
ELSE
ITK_CALL IconTK::DrawIconRaw, icon_in_rect_params::icon
END_IF
END_IF
next: pla
tax
WHILE_POS ; always
.endproc ; _RedrawIconsAfterErase
;; For `_RedrawIconsAfterErase`
redraw_highlighted_flag:
.byte 0
erase_icon_id:
.byte 0
.endproc ; EraseIconCommon
;;; ============================================================
;;; This handles drawing icons "behind" windows. It is
;;; done by comparing the bounding rect of the icon (including
;;; label) with windows, and returning a reduced clipping rect.
;;; Since the overlap may be concave, multiple calls may be
;;; necessary; a flag is set if another call is required.
;;;
;;; The algorithm is as follows:
;;;
;;; * Take the bounding box for the icon+label (bounds_*), and
;;; use it as an initial clipping rect.
;;; * Test each corner of the rect.
;;; * If the corner is inside a window, compute the window bounds.
;;; (Complicated by title bars, scroll bars, and borders.)
;;; * Consider each case where a window and rect overlap. There
;;; are 9 cases (8 interesting, one degenerate).
;;; * Reduce the clipping rect to the leftmost exposed portion.
;;; * Recheck the corners, since another window may be overlapped.
;;; * Once a minimal rect is achieved, set a flag indicating if
;;; another call is needed, and return.
;;; * Caller draws the icon into the clipping rect. If flag was
;;; set, the caller calls in again.
;;; * On re-entry, return to the initial bounding box but with
;;; an updated left edge.
;;;
;;; ============================================================
.params portbits
DEFINE_POINT viewloc, 0, 0
mapbits: .addr MGTK::screen_mapbits
mapwidth: .byte MGTK::screen_mapwidth
reserved: .byte 0
DEFINE_RECT maprect, 0, 0, 0, 0
REF_MAPINFO_MEMBERS
.endparams
;;; ============================================================
;;; Sets `res_ptr`
.proc SetPortForVolIcon
jsr CalcIconBoundingRect
;; Will need to clip to screen bounds
COPY_STRUCT MGTK::Rect, desktop_bounds, portbits::maprect
jmp DuplicateClipStructsAndSetPortBits
.endproc ; SetPortForVolIcon
;;; ============================================================
;;; Sets `res_ptr`
.proc SetPortForWinIcon
jsr CalcIconBoundingRect
;; Get window clip rect (in screen space)
copy8 clip_window_id, getwinport_params::window_id
MGTK_CALL MGTK::GetWinPort, getwinport_params ; into `icon_grafport`
RTS_IF_NE ; obscured
viewloc := icon_grafport+MGTK::GrafPort::viewloc
maprect := icon_grafport+MGTK::GrafPort::maprect
ldx #2 ; loop over dimensions
DO
;; Stash, needed to offset port when drawing to get correct patterns
sub16 maprect+MGTK::Rect::topleft,x, viewloc,x, clip_coords,x
;; Adjust `icon_grafport` so that `viewloc` and `maprect` are just
;; a clipping rectangle in screen coords.
sub16 maprect+MGTK::Rect::bottomright,x, maprect+MGTK::Rect::topleft,x, portbits::maprect+MGTK::Rect::bottomright,x
copy16 viewloc,x, portbits::maprect::topleft,x
add16 portbits::maprect+MGTK::Rect::topleft,x, portbits::maprect+MGTK::Rect::bottomright,x, portbits::maprect+MGTK::Rect::bottomright,x
dex ; next dimension
dex
WHILE_POS
;; For window's items/used/free space bar
add16_8 portbits::maprect+MGTK::Rect::y1, header_height
FALL_THROUGH_TO DuplicateClipStructsAndSetPortBits
.endproc ; SetPortForWinIcon
;;; Call with these populated:
;;; * `portbits::maprect` - screen space clip rect
;;; * `bounding_rect` - screen space icon bounds
;;; Output: Z=1 if ready to paint, Z=0 if nothing to draw
.proc DuplicateClipStructsAndSetPortBits
;; Intersect `portbits::maprect` with `bounding_rect`
ldx #2 ; loop over dimensions
DO
scmp16 portbits::maprect::topleft,x, bounding_rect+MGTK::Rect::topleft,x
IF_NEG
copy16 bounding_rect+MGTK::Rect::topleft,x, portbits::maprect::topleft,x
END_IF
scmp16 bounding_rect+MGTK::Rect::bottomright,x, portbits::maprect::bottomright,x
IF_NEG
copy16 bounding_rect+MGTK::Rect::bottomright,x, portbits::maprect::bottomright,x
END_IF
;; Is there anything left?
scmp16 portbits::maprect::bottomright,x, portbits::maprect::topleft,x
bmi empty
dex ; next dimension
dex
WHILE_POS
;; Duplicate structs needed for clipping
COPY_BLOCK portbits::maprect, clip_bounds
COPY_STRUCT portbits::maprect::topleft, portbits::viewloc
MGTK_CALL MGTK::SetPortBits, portbits
rts
empty: return #$FF
.endproc ; DuplicateClipStructsAndSetPortBits
;;; ============================================================
;;; Returns C=0 if a non-degenerate clipping rect is returned, so a
;;; paint call is needed, and `more_drawing_needed_flag` bit7 = 1
;;; if another call to this proc is needed after the paint. Returns
;;; C=1 if no clipping rect remains, so no drawing is needed.
.proc CalcWindowIntersectionsImpl
.params cwi_findwindow_params
mousex: .word 0
mousey: .word 0
which_area: .byte 0
window_id: .byte 0
.endparams
pt_num: .byte 0
;;; Points at corners of icon's bounding rect
;;; pt1 +----+ pt2
;;; | |
;;; pt4 +----+ pt3
DEFINE_POINT pt1, 0, 0
DEFINE_POINT pt2, 0, 0
DEFINE_POINT pt3, 0, 0
DEFINE_POINT pt4, 0, 0
.params getwinframerect_params
window_id: .byte 0
DEFINE_RECT rect, 0, 0, 0, 0
.endparams
stash_r: .word 0
;; Viewport/Cliprect to adjust
vx := portbits::viewloc::xcoord
vy := portbits::viewloc::ycoord
cr_l := portbits::maprect::x1
cr_t := portbits::maprect::y1
cr_r := portbits::maprect::x2
cr_b := portbits::maprect::y2
start: bit more_drawing_needed_flag
bpl reclip
;; --------------------------------------------------
;; Re-entry - pick up where we left off
reentry:
;; cr_l = cr_r + 1
ldxy cr_r
inxy
stxy cr_l
;; cr_t = clip_bounds::y1
;; cr_r = clip_bounds::x2
;; cr_b = clip_bounds::y2
COPY_BYTES 6, clip_bounds+MGTK::Rect::y1, cr_t
;; vy = cr_t
;; Are we (re)starting with a degenerate width? If so we are
;; completely done with this icon.
jsr is_degenerate
IF_NEG
CLEAR_BIT7_FLAG more_drawing_needed_flag
sec
rts
END_IF
;; --------------------------------------------------
;; Reduce the clip rect to the next minimal chunk to paint;
;; may be called multiple times before returning to caller.
reclip:
;; Did we end up with a degenerate width? If so, this clipping
;; rect was exhausted. Start with the next chunk.
jsr is_degenerate
bmi reentry
;; Corners of bounding rect (clockwise from upper-left)
;; pt1::xcoord = pt4::xcoord = cr_l
;; pt1::ycoord = pt2::ycoord = cr_t
;; pt2::xcoord = pt3::xcoord = cr_r
;; pt3::ycoord = pt4::ycoord = cr_b
lda cr_l
sta pt1::xcoord
sta pt4::xcoord
lda cr_l+1
sta pt1::xcoord+1
sta pt4::xcoord+1
lda cr_t
sta pt1::ycoord
sta pt2::ycoord
lda cr_t+1
sta pt1::ycoord+1
sta pt2::ycoord+1
lda cr_r
sta pt2::xcoord
sta pt3::xcoord
lda cr_r+1
sta pt2::xcoord+1
sta pt3::xcoord+1
lda cr_b
sta pt3::ycoord
sta pt4::ycoord
lda cr_b+1
sta pt3::ycoord+1
sta pt4::ycoord+1
copy8 #0, pt_num
next_pt:
;; Done all 4 points?
lda pt_num
cmp #4
bne do_pt
;; --------------------------------------------------
;; Finish up
copy16 cr_l, vx
copy16 cr_t, vy
scmp16 cr_r, clip_bounds+MGTK::Rect::x2
;; if (cr_r < clip_bounds::x2) more drawing is needed
sta more_drawing_needed_flag ; update bit7
MGTK_CALL MGTK::SetPortBits, portbits
clc ; C=0 means clipping rect is valid
rts
;; ==================================================
;; Find window at Nth point, and compute bounds
do_pt: lda pt_num
asl a ; *4 (.sizeof(Point))
asl a
tax
;; Look up window at Nth point
ldy #0
DO
copy8 pt1::xcoord,x, cwi_findwindow_params,y
iny
inx
WHILE_Y_NE #4
inc pt_num
MGTK_CALL MGTK::FindWindow, cwi_findwindow_params
lda cwi_findwindow_params::window_id
cmp clip_window_id
beq next_pt
;; --------------------------------------------------
;; Compute window edges (including non-content area)
win_l := getwinframerect_params::rect::x1
win_t := getwinframerect_params::rect::y1
win_r := getwinframerect_params::rect::x2
win_b := getwinframerect_params::rect::y2
copy8 cwi_findwindow_params::window_id, getwinframerect_params::window_id
MGTK_CALL MGTK::GetWinFrameRect, getwinframerect_params
;; ==================================================
;; At this point, win_r/t/l/b are the window edges,
;; cr_r/t/l/b are the rect we know has at least one
;; corner overlapping the window.
;;
;; Cases (#=icon, %=result, :=window)
;;
;; . 1 :::: 4 :::: 7 ::::
;; . :::: :::: ::::
;; . :::## :##: %#:::
;; . %# %% %#
;; .
;; . 2 :::: 5 :::: 8 ::::
;; . :::#% :##: %#:::
;; . :::#% :##: %#:::
;; . :::: :::: ::::
;; .
;; . %# %% %#
;; . 3 :::## 6 :##: 9 %#:::
;; . :::: :::: ::::
;; . :::: :::: ::::
copy16 cr_r, stash_r ; in case this turns out to be case 2
;; Cases 7/8/9 (and done)
;; if (win_l > cr_l)
;; . cr_r = win_l - 1
scmp16 cr_l, win_l
IF_NEG
sub16 win_l, #1, cr_r
jmp reclip
END_IF
;; Cases 1/2/3 (and continue below)
;; if (cr_r > win_r)
;; . cr_r = win_r
scmp16 win_r, cr_r
IF_NEG
copy16 win_r, cr_r
;; in case 2 this will be reset
END_IF
;; Cases 3/6 (and done)
;; if (win_t > cr_t)
;; . cr_b = win_t - 1
scmp16 cr_t, win_t
IF_NEG
sub16 win_t, #1, cr_b
jmp reclip
END_IF
;; Cases 1/4 (and done)
;; if (win_b < cr_b)
;; . cr_t = win_b + 1
scmp16 win_b, cr_b
IF_NEG
ldxy win_b
inxy
stxy cr_t
jmp reclip
END_IF
;; Case 2
;; if (win_r < stash_r)
;; . cr_l = win_r + 1
;; . cr_r = stash_r
scmp16 stash_r, win_r
IF_POS
ldxy win_r
inxy
stxy cr_l
copy16 stash_r, cr_r
jmp reclip
END_IF
;; Case 5 - done!
;; ... with this clip rect, but whole icon may need more painting.
jmp reentry
;; --------------------------------------------------
is_degenerate:
scmp16 cr_r, cr_l
rts
.endproc ; CalcWindowIntersectionsImpl
CalcWindowIntersections := CalcWindowIntersectionsImpl::start
;;; ============================================================
;;; Used when doing clipped drawing to map viewport and icon
;;; being drawn back to window coordinates, so that shade
;;; patterns are correct.
.proc OffsetPortAndIcon
lda clip_window_id
RTS_IF_ZERO
clip_dx := clip_coords + MGTK::Point::xcoord
clip_dy := clip_coords + MGTK::Point::ycoord
ldxy clip_dx
addxy portbits::maprect::x1
addxy portbits::maprect::x2
addxy bitmap_rect+MGTK::Rect::x1
addxy bitmap_rect+MGTK::Rect::x2 ; `bitmap_rect` used for dimming
addxy label_rect+MGTK::Rect::x1 ; x2 not used for clipping
ldxy clip_dy
addxy portbits::maprect::y1
addxy portbits::maprect::y2
addxy bitmap_rect+MGTK::Rect::y1
addxy bitmap_rect+MGTK::Rect::y2 ; `bitmap_rect` used for dimming
addxy label_rect+MGTK::Rect::y1 ; y2 not used for clipping
MGTK_CALL MGTK::SetPortBits, portbits
;; Invert for the next call
ldx #2 ; loop over dimensions
DO
sub16 #0, clip_coords,x, clip_coords,x
dex ; next dimension
dex
WHILE_POS
rts
.endproc ; OffsetPortAndIcon
;;; ============================================================
;;; Used/Free icon map
;;; ============================================================
;;; Find first available free icon in the map; if
;;; available, mark it and return index+1.
.proc AllocateIcon
;; Search for first byte with a set (available) bit
ldx #0
DO
lda free_icon_map,x
BREAK_IF_NOT_ZERO
inx
WHILE_NOT_ZERO ; always
;; X has byte offset - turn into index
pha ; A = table byte
txa ; X = offset
asl ; *= 8
asl
asl
tax ; X = index
;; Add in the bit offset
pla ; A = table byte
dex
DO
inx
ror
WHILE_CC ; clear = in use
txa
;; Mark it used
pha
jsr IconMapIndexToOffsetMask
eor #$FF
and free_icon_map,x ; clear bit to mark used
sta free_icon_map,x
pla
rts
.endproc ; AllocateIcon
;;; Mark the specified icon as free
.proc FreeIcon
jsr IconMapIndexToOffsetMask
ora free_icon_map,x ; set bit to mark free
sta free_icon_map,x
rts
.endproc ; FreeIcon
;;; Input: A = icon num (1...127)
;;; Output: X = index in `free_icon_map`, A = bit mask (e.g. %0001000)
.proc IconMapIndexToOffsetMask
pha ; A = index
and #7
tax
ldy table,x ; Y = mask
pla ; A = index
lsr ; /= 8
lsr
lsr
tax ; X = offset
tya ; A = mask
rts
table: .byte 1<<0, 1<<1, 1<<2, 1<<3, 1<<4, 1<<5, 1<<6, 1<<7
.endproc ; IconMapIndexToOffsetMask
;;; Each byte represents 8 icons. id 0 is unused.
free_icon_map:
.byte $FE, $FF, $FF, $FF, $FF, $FF, $FF, $FF
.byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF
ASSERT_TABLE_SIZE free_icon_map, (::kMaxIconCount + 7)/8
;;; ============================================================
.proc InitSetIconPort
MGTK_CALL MGTK::InitPort, icon_grafport
MGTK_CALL MGTK::SetPort, icon_grafport
rts
.endproc ; InitSetIconPort
;;; ============================================================
.endscope ; icontk
|
a2stuff/a2d
| 14,245
|
src/toolkits/optk.s
|
;;; ============================================================
;;; Option Picker ToolKit
;;; ============================================================
.scope optk
OPTKEntry := *
;;; ============================================================
;;; Zero Page usage (saved/restored around calls)
zp_start := $50
kMaxCommandDataSize = 6
kMaxTmpSpace = 10 ; MulDiv param size
PARAM_BLOCK, zp_start
;;; Initially points at the call site, then at passed params
params_addr .addr
;;; Copy of the passed params
command_data .res kMaxCommandDataSize
;;; A temporary copy of the control record
opr_copy .tag OPTK::OptionPickerRecord
;;; Other ZP usage
max_entries .byte
max_entries_minus_one .byte
tmp_space .res kMaxTmpSpace
;;; For size calculation, not actually used
zp_end .byte
END_PARAM_BLOCK
.assert zp_end <= $78, error, "too big"
kBytesToSave = zp_end - zp_start
a_record := command_data ; always first element of `command_data`
;; Aliases for the copy's members:
oprc_window_id := opr_copy + OPTK::OptionPickerRecord::window_id
oprc_left := opr_copy + OPTK::OptionPickerRecord::left
oprc_top := opr_copy + OPTK::OptionPickerRecord::top
oprc_num_rows := opr_copy + OPTK::OptionPickerRecord::num_rows
oprc_num_cols := opr_copy + OPTK::OptionPickerRecord::num_cols
oprc_item_width := opr_copy + OPTK::OptionPickerRecord::item_width
oprc_item_height := opr_copy + OPTK::OptionPickerRecord::item_height
oprc_hoffset := opr_copy + OPTK::OptionPickerRecord::hoffset
oprc_voffset := opr_copy + OPTK::OptionPickerRecord::voffset
oprc_selected_index := opr_copy + OPTK::OptionPickerRecord::selected_index
;;; ============================================================
.assert OPTKEntry = Dispatch, error, "dispatch addr"
.proc Dispatch
;; Adjust stack/stash
pla
sta params_lo
clc
adc #<3
tax
pla
sta params_hi
adc #>3
pha
txa
pha
;; Save ZP
PUSH_BYTES kBytesToSave, zp_start
;; Point `params_addr` at the call site
params_lo := *+1
lda #SELF_MODIFIED_BYTE
sta params_addr
params_hi := *+1
lda #SELF_MODIFIED_BYTE
sta params_addr+1
;; Grab command number
ldy #1 ; Note: rts address is off-by-one
lda (params_addr),y
tax
copylohi jump_table_lo,x, jump_table_hi,x, dispatch
;; Point `params_addr` at actual params
iny
lda (params_addr),y
tax
iny
lda (params_addr),y
sta params_addr+1
stx params_addr
;; Copy param data to `command_data`
ldy #kMaxCommandDataSize-1
: copy8 (params_addr),y, command_data,y
dey
bpl :-
;; Cache static copy of the record in `opr_copy`, for convenience
ldy #.sizeof(OPTK::OptionPickerRecord)-1
: copy8 (a_record),y, opr_copy,y
dey
bpl :-
;; Compute constants
lda #0 ; lo
ldx oprc_num_cols ; hi
ldy oprc_num_rows
jsr _Multiply
stx max_entries
dex
stx max_entries_minus_one
;; Invoke the command
dispatch := *+1
jsr SELF_MODIFIED
tay ; A = result
;; Restore ZP
POP_BYTES kBytesToSave, zp_start
tya ; A = result
rts
jump_table_lo:
.lobytes DrawImpl
.lobytes UpdateImpl
.lobytes ClickImpl
.lobytes KeyImpl
.lobytes SetSelectionImpl
jump_table_hi:
.hibytes DrawImpl
.hibytes UpdateImpl
.hibytes ClickImpl
.hibytes KeyImpl
.hibytes SetSelectionImpl
ASSERT_EQUALS *-jump_table_hi, jump_table_hi-jump_table_lo
.endproc ; Dispatch
;;; ============================================================
IsEntryProc: jmp (opr_copy + OPTK::OptionPickerRecord::is_entry_proc)
DrawEntryProc: jmp (opr_copy + OPTK::OptionPickerRecord::draw_entry_proc)
OnSelChange: jmp (opr_copy + OPTK::OptionPickerRecord::on_sel_change)
;;; ============================================================
;;; Shadows params in Selector's `app` and Disk Copy's `auxlc` scopes.
;;; TODO: Rework scoping to eliminate this.
SUPPRESS_SHADOW_WARNING
.params getwinport_params
window_id: .byte 0
port: .addr grafport_win
.endparams
UNSUPPRESS_SHADOW_WARNING
grafport_win: .tag MGTK::GrafPort
.proc _SetPort
copy8 oprc_window_id, getwinport_params::window_id
MGTK_CALL MGTK::GetWinPort, getwinport_params
;; ASSERT: Not obscured.
MGTK_CALL MGTK::SetPort, grafport_win
rts
.endproc ; _SetPort
;;; ============================================================
.proc DrawImpl
jsr _SetPort
FALL_THROUGH_TO UpdateImpl
.endproc ; DrawImpl
;;; ============================================================
.proc UpdateImpl
ldx #0
DO
txa
jsr _CallIsEntryProc ; preserves A, sets N
IF_NC
point := tmp_space
;; Is a real entry - prep to draw it
pha ; A = index
jsr _GetOptionPos ; returns A,X=x , Y=y
addax8 oprc_hoffset
stax point + MGTK::Point::xcoord
tya
ldx #0
addax8 oprc_voffset
stax point + MGTK::Point::ycoord
MGTK_CALL MGTK::MoveTo, point
pla ; A = index
pha ; A = index
jsr DrawEntryProc
pla ; A = index
END_IF
tax ; X = index
inx
WHILE_X_NE max_entries
rts
.endproc ; UpdateImpl
;;; ============================================================
.proc ClickImpl
PARAM_BLOCK params, optk::command_data
a_record .addr
coords .tag MGTK::Point
END_PARAM_BLOCK
xcoord := params::coords + MGTK::Point::xcoord
ycoord := params::coords + MGTK::Point::ycoord
;; Row
sub16 ycoord, oprc_top, ycoord
bmi fail
ldax ycoord
ldy oprc_item_height
jsr _Divide ; A = row
cmp oprc_num_rows
bcs fail
sta row
;; Column
sub16 xcoord, oprc_left, xcoord
bmi fail
ldax xcoord
ldy oprc_item_width
jsr _Divide ; A = col
cmp oprc_num_cols
bcs fail
;; Index
ldx #0 ; hi
ldy oprc_num_rows
jsr _Multiply
clc
row := *+1
adc #SELF_MODIFIED_BYTE
;; Is it valid?
jsr _CallIsEntryProc
IF_NS
lda #$FF
END_IF
jmp _SetSelectionAndNotify
fail: return #$FF
.endproc ; ClickImpl
;;; ============================================================
.proc KeyImpl
PARAM_BLOCK params, optk::command_data
a_record .addr
key .byte
END_PARAM_BLOCK
lda params::key
cmp #CHAR_LEFT
beq _HandleKeyLeft
cmp #CHAR_UP
beq _HandleKeyUp
cmp #CHAR_DOWN
beq _HandleKeyDown
FALL_THROUGH_TO _HandleKeyRight
;;; --------------------------------------------------
.proc _HandleKeyRight
lda oprc_selected_index
IF_NS
lda #0 ; no selection, start at first
sec
sbc oprc_num_rows
END_IF
REPEAT
IF_A_EQ max_entries_minus_one
lda #0 ; last, wrap to first
ELSE
clc
adc oprc_num_rows
END_IF
IF_A_GE max_entries
sec
sbc max_entries_minus_one
END_IF
jsr _CallIsEntryProc
UNTIL_NC
bpl _SetSelectionAndNotify ; always
.endproc ; _HandleKeyRight
;;; --------------------------------------------------
.proc _HandleKeyLeft
lda oprc_selected_index
bmi last ; no selection, start at last
IF_ZERO ; or if first, start at last
last: lda max_entries_minus_one
clc
adc oprc_num_rows
END_IF
REPEAT
sec
sbc oprc_num_rows
IF_NEG
clc
adc max_entries_minus_one
END_IF
jsr _CallIsEntryProc
UNTIL_NC
bpl _SetSelectionAndNotify ; always
.endproc ; _HandleKeyLeft
;;; --------------------------------------------------
.proc _HandleKeyUp
lda oprc_selected_index
IF_NS
lda max_entries ; no selection, start with last
END_IF
IF_EQ
lda max_entries ; first, start with last
END_IF
REPEAT
sec
sbc #1
IF_NEG
lda max_entries
CONTINUE_IF_NE ; always
END_IF
jsr _CallIsEntryProc
UNTIL_NC
bpl _SetSelectionAndNotify ; always
.endproc ; _HandleKeyUp
;;; --------------------------------------------------
.proc _HandleKeyDown
lda oprc_selected_index
IF_NS
lda #AS_BYTE(-1) ; no selection, start at first
END_IF
REPEAT
clc
adc #1
IF_A_EQ max_entries
lda #0
END_IF
jsr _CallIsEntryProc
UNTIL_NC
bpl _SetSelectionAndNotify ; always
.endproc ; _HandleKeyDown
.endproc ; KeyImpl
;;; ============================================================
;;; Input: A=index
;;; Output: A=index, N=0 if valid proc
.proc _CallIsEntryProc
sta save_a
jsr IsEntryProc
php
save_a := *+1
lda #SELF_MODIFIED_BYTE
plp
rts
.endproc ; _CallIsEntryProc
;;; ============================================================
.proc _SetSelectionAndNotify
jsr _SetSelection
jsr OnSelChange
lda oprc_selected_index
rts
.endproc ; _SetSelectionAndNotify
;;; ============================================================
.proc SetSelectionImpl
PARAM_BLOCK params, optk::command_data
a_record .addr
new_selection .byte
END_PARAM_BLOCK
lda params::new_selection
FALL_THROUGH_TO _SetSelection
.endproc ; SetSelectionImpl
;;; ============================================================
.proc _SetSelection
RTS_IF_A_EQ oprc_selected_index ; same as previous?
pha ; A = new selection
jsr _SetPort
lda oprc_selected_index
jsr _HighlightIndex
ldy #OPTK::OptionPickerRecord::selected_index
pla ; A = new selection
sta (a_record),y
sta oprc_selected_index ; keep copy in sync
FALL_THROUGH_TO _HighlightIndex
.endproc ; SetSelectionImpl
;;; ============================================================
;;; Toggle the highlight on an entry in the list
;;; Input: A = entry number (negative if no selection)
.proc _HighlightIndex
bmi ret
rect := tmp_space
jsr _GetOptionPos
stax rect + MGTK::Rect::x1
addax8 oprc_item_width
stax rect + MGTK::Rect::x2
dec16 rect + MGTK::Rect::x2
tya ; y lo
ldx #0 ; y hi
stax rect + MGTK::Rect::y1
addax8 oprc_item_height
stax rect + MGTK::Rect::y2
dec16 rect + MGTK::Rect::y2
MGTK_CALL MGTK::SetPattern, solid_pattern
MGTK_CALL MGTK::SetPenMode, penXOR
MGTK_CALL MGTK::PaintRect, rect
ret: rts
.endproc ; _HighlightIndex
;;; ============================================================
;;; Get the coordinates of an option by index.
;;; Input: A = index
;;; Output: A,X = x coordinate, Y = y coordinate
.proc _GetOptionPos
ldx #0 ; hi
ldy oprc_num_rows
jsr _Divide
sty remainder
ldy oprc_item_width
jsr _Multiply
clc
adc oprc_left
pha ; lo
txa
adc oprc_left+1
pha ; hi
;; Y coordinate
remainder := *+1
lda #SELF_MODIFIED_BYTE ; lo
ldx #0 ; hi
ldy oprc_item_height
jsr _Multiply
clc
adc oprc_top
tay ; Y coord
pla
tax ; X coord hi
pla ; X coord lo
rts
.endproc ; _GetOptionPos
;;; ============================================================
PARAM_BLOCK muldiv_params, optk::tmp_space
number .word ; (in)
numerator .word ; (in)
denominator .word ; (in)
result .word ; (out)
remainder .word ; (out)
END_PARAM_BLOCK
;;; A,X = A,X * Y
.proc _Multiply
stax muldiv_params::number
sty muldiv_params::numerator
copy8 #0, muldiv_params::numerator+1
copy16 #1, muldiv_params::denominator
MGTK_CALL MGTK::MulDiv, muldiv_params
ldax muldiv_params::result
rts
.endproc ; _Multiply
;;; ============================================================
;;; A,X = A,X / Y, Y = remainder
.proc _Divide
stax muldiv_params::numerator
sty muldiv_params::denominator
copy8 #0, muldiv_params::denominator+1
copy16 #1, muldiv_params::number
MGTK_CALL MGTK::MulDiv, muldiv_params
ldax muldiv_params::result
ldy muldiv_params::remainder
rts
.endproc ; _Divide
;;; ============================================================
.endscope ; optk
|
a2-4am/4cade
| 3,683
|
res/attic/callback.s
|
!cpu 6502
!to "callback#061000",plain
*=$1000
WILDCARD = $97
BASEPAGE = $D0
lda $c08b
lda $c08b
ldy #$0D
jsr SearchTrack
!byte $BD,$10,$BF ;LDA $BF10,X
!byte $8D,WILDCARD,WILDCARD ;STA $xxxx,X
!byte $BD,$11,$BF ;LDA $BF11,X
!byte $8D,WILDCARD,WILDCARD ;STA $xxxx,X
!byte $6C
bcs .exit
adc #BASEPAGE
sta patch1+2
sta patch2+2
ldy #(callback_e-callback_b)-1
- lda callback_b,y
sta callback,y
dey
bpl -
txa
adc #$0E
tax
ldy #2
-
patch1 lda $d100,x
sta jmpback,y
lda hookme,y
patch2 sta $d100,x
dex
dey
bpl -
.exit
lda $c082
bcs ++
ldy #0
beq +
- jsr $FDED
iny
+ lda installed,y
bne -
++ rts
hookme jmp callback
installed
!text "INSTALLED"
!byte $8D,00
callback_b
!pseudopc $300 {
callback lda $c081
lda #$D2
jsr $FDED
lda $c08b
lda $c000
bpl +
sec ;error is pressed key
rts
+
jmpback ;!byte $d1,$d1,$d1
}
callback_e
SearchTrack
;set end point for the search
lda #$E0
sta .endvalue+1
lda #$D0
; set high part of initial search position
sta search+2
pla
sta match_buffer1+1
sta match_all+1
pla
sta match_buffer1+2
sta match_all+2
tax
sty match_size1+1
sty match_size2+1
; fetch last byte to improve search speed
match_buffer1
lda $d1d1,y ; modified at runtime
sta check_byte1+1
sta check_byte2+1
; set low part of initial search position
tya
dey
sty cont_search+1
; set return address
clc
adc match_buffer1+1
tay
bcc plus01
inx
plus01
txa
pha
tya
pha
; set match position
inc match_all+1
bne plus02
inc match_all+2
plus02
lda #<cont_search-branch_cont-2
sta branch_cont+1
; search...
cont_search
ldy #$d1 ; modified at runtime
search
lda $d100,y ; modified at runtime
iny
beq check_end
check_byte1
cmp #$d1 ; modified at runtime
bne search
; point to first byte
sty cont_search+1
check_match
tya
match_size1
sbc #$d1 ; modified at runtime
sta match_buffer2+1
ldx search+2
bcs plus03
dex
plus03
stx match_buffer2+2
ldy #$00
match_all
lda $d1d1,y ; modified at runtime
cmp #WILDCARD
beq found_wild
match_buffer2
cmp $d1d1,y ; modified at runtime
branch_cont
bne cont_search
found_wild
iny
match_size2
cpy #$d1 ; modified at runtime
bne match_all
; point to start of match
ldx match_buffer2+1
lda match_buffer2+2
sec
sbc #BASEPAGE
clc
rts
; cold path
check_end
inc search+2
ldx search+2
.endvalue
cpx #$D1
bne check_byte1
ldx #<all_done_set-branch_cont-2
stx branch_cont+1
check_byte2
cmp #$d1 ; modified at runtime
beq check_match
all_done_set
sec
rts
|
a2-4am/4cade
| 1,820
|
res/attic/quick.s
|
!cpu 6502
!to "quick#061000",plain
*=$1000
zpword = $0 ;and $1
zpstring= $2 ;and $3
runningscore= $4 ;and $5
startat = $6
i = $7
tmp = $8
jsr quick
tax
lda #0
jmp $ed24 ;hex to dec
quick
lda #<word
sta zpword
lda #>word
sta zpword+1
lda #<string
sta zpstring
lda #>string
sta zpstring+1
ldy word
cpy string
bne +
- lda (zpword), y
cmp (zpstring), y
bne +
dey
bne -
lda #100
rts
+ lda #0
sta runningscore
sta runningscore+1
ldy #1
sty startat
- sty i
lda (zpword), y
jsr tolower
sta tmp
ldy startat
-- lda (zpstring), y
jsr tolower
cmp tmp
beq +
cpy string
iny
bcc --
lda #0
rts
+ ldx #80
cpy startat
beq +
ldx #10
cpy #1
beq +
dey
lda (zpstring), y
iny
cmp ' '
bne +
ldx #90
+ txa
clc
adc runningscore
sta runningscore
bcc +
inc runningscore+1
+ iny
sty startat
ldy i
cpy word
iny
bcc -
lda runningscore
ldx runningscore+1
ldy string
jsr div
sta tmp
lda runningscore
ldx runningscore+1
ldy word
jsr div
clc
adc tmp
lsr
ldx word+1
cpx string+1
bne +
cmp #85
bcs +
adc #15
+ rts
tolower
cmp #$41
bcc +
cmp #$5b
bcs +
ora #$20
+ rts
div
sta num1
stx num1+1
sty num2
lda #0
sta rem
sta rem+1
ldx #16
- asl num1
rol num1+1
rol rem
rol rem+1
lda rem
sec
sbc num2
bcc +
sta rem
dec rem+1
inc num1
+ dex
bne -
lda num1
rts
rem !byte 0,0
num1 !byte 0,0
num2 !byte 0
word !byte word_e-word_b
word_b
!text "HE"
word_e
string !byte string_e-string_b
string_b
!text "HELLO WORLD"
string_e
|
9front/9front
| 1,211
|
sys/src/ape/lib/ap/power/memset.s
|
TEXT memset(SB),$0
#define BDNZ BC 16,0,
MOVW R3, p+0(FP) /* R3 is pointer */
/*
* performance:
* about 100mbytes/sec (8k blocks) on a 603/105 without L2 cache
* drops to 40mbytes/sec (10k blocks) and 28mbytes/sec with 32k blocks
*/
MOVW n+8(FP), R4 /* R4 is count */
CMP R4, $0
BLE ret
MOVW c+4(FP), R5 /* R5 is char */
/*
* create 16 copies of c in R5 .. R8
*/
RLWNM $0, R5, $0xff, R5
RLWMI $8, R5, $0xff00, R5
RLWMI $16, R5, $0xffff0000, R5
MOVW R5, R6
MOVW R5, R7
MOVW R5, R8
/*
* let STSW do the work for 16 characters or less; aligned and unaligned
*/
CMP R4, $16
BLE out
/*
* store enough bytes to align pointer
*/
ANDCC $7,R3, R9
BEQ l2
SUBC R9, $8, R9
MOVW R9, XER
STSW R5, (R3)
ADD R9, R3
SUB R9, R4
/*
* store 16 at a time while there's room
* STSW was used here originally, but it's `completion serialised'
*/
l2:
SRAWCC $4, R4, R9
BLE out
MOVW R9, CTR
l3:
MOVW R5, 0(R3)
ADD $8, R3, R10
MOVW R6, 4(R3)
MOVW R7, 0(R10)
ADD $8, R10, R3
MOVW R8, 4(R10)
BDNZ l3
RLWNMCC $0, R4, $15, R4 /* residue */
BEQ ret
/*
* store up to 16 bytes from R5 .. R8; aligned and unaligned
*/
out:
MOVW R4, XER
STSW R5, (R3)
ret:
MOVW 0(FP), R3
RETURN
END
|
9front/9front
| 2,479
|
sys/src/ape/lib/ap/power/memmove.s
|
#define BDNZ BC 16,0,
TEXT memmove(SB), $0
BR move
TEXT memcpy(SB), $0
move:
/*
* performance:
* (tba)
*/
MOVW R3, s1+0(FP)
MOVW n+8(FP), R9 /* R9 is count */
MOVW R3, R10 /* R10 is to-pointer */
CMP R9, $0
BEQ ret
BLT trap
MOVW s2+4(FP), R11 /* R11 is from-pointer */
/*
* if no more than 16 bytes, just use one lsw/stsw
*/
CMP R9, $16
BLE fout
ADD R9,R11, R13 /* R13 is end from-pointer */
ADD R9,R10, R12 /* R12 is end to-pointer */
/*
* easiest test is copy backwards if
* destination string has higher mem address
*/
CMPU R10, R11
BGT back
/*
* test if both pointers
* are similarly word aligned
*/
XOR R10,R11, R7
ANDCC $3,R7
BNE fbad
/*
* move a few bytes to align pointers
*/
ANDCC $3,R10,R7
BEQ f2
SUBC R7, $4, R7
SUB R7, R9
MOVW R7, XER
LSW (R11), R16
ADD R7, R11
STSW R16, (R10)
ADD R7, R10
/*
* turn R14 into doubleword count
* copy 16 bytes at a time while there's room.
*/
f2:
SRAWCC $4, R9, R14
BLE fout
MOVW R14, CTR
SUB $4, R11
SUB $4, R10
f3:
MOVWU 4(R11), R16
MOVWU R16, 4(R10)
MOVWU 4(R11), R17
MOVWU R17, 4(R10)
MOVWU 4(R11), R16
MOVWU R16, 4(R10)
MOVWU 4(R11), R17
MOVWU R17, 4(R10)
BDNZ f3
RLWNMCC $0, R9, $15, R9 /* residue */
BEQ ret
ADD $4, R11
ADD $4, R10
/*
* move up to 16 bytes through R16 .. R19; aligned and unaligned
*/
fout:
MOVW R9, XER
LSW (R11), R16
STSW R16, (R10)
BR ret
/*
* loop for unaligned copy, then copy up to 15 remaining bytes
*/
fbad:
SRAWCC $4, R9, R14
BLE f6
MOVW R14, CTR
f5:
LSW (R11), $16, R16
ADD $16, R11
STSW R16, $16, (R10)
ADD $16, R10
BDNZ f5
RLWNMCC $0, R9, $15, R9 /* residue */
BEQ ret
f6:
MOVW R9, XER
LSW (R11), R16
STSW R16, (R10)
BR ret
/*
* whole thing repeated for backwards
*/
back:
CMP R9, $4
BLT bout
XOR R12,R13, R7
ANDCC $3,R7
BNE bout
b1:
ANDCC $3,R13, R7
BEQ b2
MOVBZU -1(R13), R16
MOVBZU R16, -1(R12)
SUB $1, R9
BR b1
b2:
SRAWCC $4, R9, R14
BLE b4
MOVW R14, CTR
b3:
MOVWU -4(R13), R16
MOVWU R16, -4(R12)
MOVWU -4(R13), R17
MOVWU R17, -4(R12)
MOVWU -4(R13), R16
MOVWU R16, -4(R12)
MOVWU -4(R13), R17
MOVWU R17, -4(R12)
BDNZ b3
RLWNMCC $0, R9, $15, R9 /* residue */
BEQ ret
b4:
SRAWCC $2, R9, R14
BLE bout
MOVW R14, CTR
b5:
MOVWU -4(R13), R16
MOVWU R16, -4(R12)
BDNZ b5
RLWNMCC $0, R9, $3, R9 /* residue */
BEQ ret
bout:
CMPU R13, R11
BLE ret
MOVBZU -1(R13), R16
MOVBZU R16, -1(R12)
BR bout
trap:
MOVW $0, R0
MOVW 0(R0), R0
ret:
MOVW s1+0(FP), R3
RETURN
|
9front/9front
| 1,493
|
sys/src/ape/lib/ap/power/memcmp.s
|
TEXT memcmp(SB), $0
#define BDNZ BC 16,0,
MOVW R3, s1+0(FP) /* R3 is pointer1 */
/*
* performance:
* 67mb/sec aligned; 16mb/sec unaligned
*/
MOVW n+8(FP), R4 /* R4 is count */
MOVW s2+4(FP), R5 /* R5 is pointer2 */
/*
* let LSW do the work for 4 characters or less; aligned and unaligned
*/
CMP R4, $0
BLE eq
CMP R4, $4
BLE out
XOR R3, R5, R9
ANDCC $3, R9
BNE l4 /* pointers misaligned; use LSW loop */
/*
* do enough bytes to align pointers
*/
ANDCC $3,R3, R9
BEQ l2
SUBC R9, $4, R9
MOVW R9, XER
LSW (R3), R10
ADD R9, R3
LSW (R5), R14
ADD R9, R5
SUB R9, R4
CMPU R10, R14
BNE ne
/*
* compare 16 at a time
*/
l2:
SRAWCC $4, R4, R9
BLE l4
MOVW R9, CTR
SUB $4, R3
SUB $4, R5
l3:
MOVWU 4(R3), R10
MOVWU 4(R5), R12
MOVWU 4(R3), R11
MOVWU 4(R5), R13
CMPU R10, R12
BNE ne
MOVWU 4(R3), R10
MOVWU 4(R5), R12
CMPU R11, R13
BNE ne
MOVWU 4(R3), R11
MOVWU 4(R5), R13
CMPU R10, R12
BNE ne
CMPU R11, R13
BNE ne
BDNZ l3
ADD $4, R3
ADD $4, R5
RLWNMCC $0, R4, $15, R4 /* residue */
BEQ eq
/*
* do remaining words with LSW; also does unaligned case
*/
l4:
SRAWCC $2, R4, R9
BLE out
MOVW R9, CTR
l5:
LSW (R3), $4, R10
ADD $4, R3
LSW (R5), $4, R11
ADD $4, R5
CMPU R10, R11
BNE ne
BDNZ l5
RLWNMCC $0, R4, $3, R4 /* residue */
BEQ eq
/*
* do remaining bytes with final LSW
*/
out:
MOVW R4, XER
LSW (R3), R10
LSW (R5), R11
CMPU R10, R11
BNE ne
eq:
MOVW $0, R3
RETURN
ne:
MOVW $1, R3
BGE ret
MOVW $-1,R3
ret:
RETURN
END
|
9front/9front
| 3,748
|
sys/src/ape/lib/ap/power/vlop.s
|
#define BDNZ BC 16,0,
/*
* 64/64 division adapted from powerpc compiler writer's handbook
*
* (R3:R4) = (R3:R4) / (R5:R6) (64b) = (64b / 64b)
* quo dvd dvs
*
* Remainder is left in R7:R8
*
* Code comment notation:
* msw = most-significant (high-order) word, i.e. bits 0..31
* lsw = least-significant (low-order) word, i.e. bits 32..63
* LZ = Leading Zeroes
* SD = Significant Digits
*
* R3:R4 = dvd (input dividend); quo (output quotient)
* R5:R6 = dvs (input divisor)
*
* R7:R8 = tmp; rem (output remainder)
*/
TEXT _divu64(SB), $0
MOVW a+0(FP), R3
MOVW a+4(FP), R4
MOVW b+8(FP), R5
MOVW b+12(FP), R6
/* count the number of leading 0s in the dividend */
CMP R3, $0 /* dvd.msw == 0? R3, */
CNTLZW R3, R11 /* R11 = dvd.msw.LZ */
CNTLZW R4, R9 /* R9 = dvd.lsw.LZ */
BNE lab1 /* if(dvd.msw != 0) dvd.LZ = dvd.msw.LZ */
ADD $32, R9, R11 /* dvd.LZ = dvd.lsw.LZ + 32 */
lab1:
/* count the number of leading 0s in the divisor */
CMP R5, $0 /* dvd.msw == 0? */
CNTLZW R5, R9 /* R9 = dvs.msw.LZ */
CNTLZW R6, R10 /* R10 = dvs.lsw.LZ */
BNE lab2 /* if(dvs.msw != 0) dvs.LZ = dvs.msw.LZ */
ADD $32, R10, R9 /* dvs.LZ = dvs.lsw.LZ + 32 */
lab2:
/* determine shift amounts to minimize the number of iterations */
CMP R11, R9 /* compare dvd.LZ to dvs.LZ */
SUBC R11, $64, R10 /* R10 = dvd.SD */
BGT lab9 /* if(dvs > dvd) quotient = 0 */
ADD $1, R9 /* ++dvs.LZ (or --dvs.SD) */
SUBC R9, $64, R9 /* R9 = dvs.SD */
ADD R9, R11 /* (dvd.LZ + dvs.SD) = left shift of dvd for */
/* initial dvd */
SUB R9, R10, R9 /* (dvd.SD - dvs.SD) = right shift of dvd for */
/* initial tmp */
MOVW R9, CTR /* number of iterations = dvd.SD - dvs.SD */
/* R7:R8 = R3:R4 >> R9 */
CMP R9, $32
ADD $-32, R9, R7
BLT lab3 /* if(R9 < 32) jump to lab3 */
SRW R7, R3, R8 /* tmp.lsw = dvd.msw >> (R9 - 32) */
MOVW $0, R7 /* tmp.msw = 0 */
BR lab4
lab3:
SRW R9, R4, R8 /* R8 = dvd.lsw >> R9 */
SUBC R9, $32, R7
SLW R7, R3, R7 /* R7 = dvd.msw << 32 - R9 */
OR R7, R8 /* tmp.lsw = R8 | R7 */
SRW R9, R3, R7 /* tmp.msw = dvd.msw >> R9 */
lab4:
/* R3:R4 = R3:R4 << R11 */
CMP R11,$32
ADDC $-32, R11, R9
BLT lab5 /* (R11 < 32)? */
SLW R9, R4, R3 /* dvd.msw = dvs.lsw << R9 */
MOVW $0, R4 /* dvd.lsw = 0 */
BR lab6
lab5:
SLW R11, R3 /* R3 = dvd.msw << R11 */
SUBC R11, $32, R9
SRW R9, R4, R9 /* R9 = dvd.lsw >> 32 - R11 */
OR R9, R3 /* dvd.msw = R3 | R9 */
SLW R11, R4 /* dvd.lsw = dvd.lsw << R11 */
lab6:
/* restoring division shift and subtract loop */
MOVW $-1, R10
ADDC $0, R7 /* clear carry bit before loop starts */
lab7:
/* tmp:dvd is considered one large register */
/* each portion is shifted left 1 bit by adding it to itself */
/* adde sums the carry from the previous and creates a new carry */
ADDE R4,R4 /* shift dvd.lsw left 1 bit */
ADDE R3,R3 /* shift dvd.msw to left 1 bit */
ADDE R8,R8 /* shift tmp.lsw to left 1 bit */
ADDE R7,R7 /* shift tmp.msw to left 1 bit */
SUBC R6, R8, R11 /* tmp.lsw - dvs.lsw */
SUBECC R5, R7, R9 /* tmp.msw - dvs.msw */
BLT lab8 /* if(result < 0) clear carry bit */
MOVW R11, R8 /* move lsw */
MOVW R9, R7 /* move msw */
ADDC $1, R10, R11 /* set carry bit */
lab8:
BDNZ lab7
ADDE R4,R4 /* quo.lsw (lsb = CA) */
ADDE R3,R3 /* quo.msw (lsb from lsw) */
lab10:
MOVW qp+16(FP), R9
MOVW rp+20(FP), R10
CMP R9, $0
BEQ lab11
MOVW R3, 0(R9)
MOVW R4, 4(R9)
lab11:
CMP R10, $0
BEQ lab12
MOVW R7, 0(R10)
MOVW R8, 4(R10)
lab12:
RETURN
lab9:
/* Quotient is 0 (dvs > dvd) */
MOVW R4, R8 /* rmd.lsw = dvd.lsw */
MOVW R3, R7 /* rmd.msw = dvd.msw */
MOVW $0, R4 /* dvd.lsw = 0 */
MOVW $0, R3 /* dvd.msw = 0 */
BR lab10
|
9front/9front
| 1,282
|
sys/src/ape/lib/ap/sparc/memset.s
|
TEXT memset(SB),$0
/*
* performance:
* (tba)
*/
MOVW R7, 0(FP)
MOVW n+8(FP), R9 /* R9 is count */
MOVW p+0(FP), R10 /* R10 is pointer */
MOVW c+4(FP), R11 /* R11 is char */
ADD R9,R10, R12 /* R12 is end pointer */
/*
* if not at least 4 chars,
* dont even mess around.
* 3 chars to guarantee any
* rounding up to a word
* boundary and 4 characters
* to get at least maybe one
* full word store.
*/
SUBCC $4,R9, R0
BL out
/*
* turn R11 into a word of characters
*/
AND $0xff, R11
SLL $8,R11, R7
OR R7, R11
SLL $16,R11, R7
OR R7, R11
/*
* store one byte at a time until pointer
* is alligned on a word boundary
*/
l1:
ANDCC $3,R10, R0
BE l2
MOVB R11, 0(R10)
ADD $1, R10
JMP l1
/*
* turn R9 into end pointer-15
* store 16 at a time while theres room
*/
l2:
ADD $-15,R12, R9
SUBCC R10,R9, R0
BLEU l4
l3:
MOVW R11, 0(R10)
MOVW R11, 4(R10)
ADD $16, R10
SUBCC R10,R9, R0
MOVW R11, -8(R10)
MOVW R11, -4(R10)
BGU l3
/*
* turn R9 into end pointer-3
* store 4 at a time while theres room
*/
l4:
ADD $-3,R12, R9
l5:
SUBCC R10,R9, R0
BLEU out
MOVW R11, 0(R10)
ADD $4, R10
JMP l5
/*
* last loop, store byte at a time
*/
out:
SUBCC R10,R12, R0
BLEU ret
MOVB R11, 0(R10)
ADD $1, R10
JMP out
ret:
MOVW s1+0(FP), R7
RETURN
|
9front/9front
| 2,430
|
sys/src/ape/lib/ap/sparc/memmove.s
|
TEXT memmove(SB), $0
JMP move
TEXT memcpy(SB), $0
move:
/*
* performance:
* (tba)
*/
MOVW R7, s1+0(FP)
MOVW n+8(FP), R9 /* R9 is count */
MOVW R7, R10 /* R10 is to-pointer */
SUBCC R0,R9, R0
BGE ok
MOVW 0(R0), R0
ok:
MOVW s2+4(FP), R11 /* R11 is from-pointer */
ADD R9,R11, R13 /* R13 is end from-pointer */
ADD R9,R10, R12 /* R12 is end to-pointer */
/*
* easiest test is copy backwards if
* destination string has higher mem address
*/
SUBCC R11,R10, R0
BGU back
/*
* if not at least 4 chars,
* dont even mess around.
* 3 chars to guarantee any
* rounding up to a word
* boundary and 4 characters
* to get at least maybe one
* full word store.
*/
SUBCC $4,R9, R0
BL fout
/*
* test if both pointers
* are similarly word aligned
*/
XOR R10,R11, R7
ANDCC $3,R7, R0
BNE fout
/*
* byte at a time to word align
*/
f1:
ANDCC $3,R10, R0
BE f2
MOVB 0(R11), R16
ADD $1, R11
MOVB R16, 0(R10)
ADD $1, R10
JMP f1
/*
* turn R9 into to-end pointer-15
* copy 16 at a time while theres room.
* R12 is smaller than R13 --
* there are problems if R13 is 0.
*/
f2:
SUB $15,R12, R9
f3:
SUBCC R10,R9, R0
BLEU f4
MOVW 0(R11), R16
MOVW 4(R11), R17
MOVW R16, 0(R10)
MOVW 8(R11), R16
MOVW R17, 4(R10)
MOVW 12(R11), R17
ADD $16, R11
MOVW R16, 8(R10)
MOVW R17, 12(R10)
ADD $16, R10
JMP f3
/*
* turn R9 into to-end pointer-3
* copy 4 at a time while theres room
*/
f4:
SUB $3,R12, R9
f5:
SUBCC R10,R9, R0
BLEU fout
MOVW 0(R11), R16
ADD $4, R11
MOVW R16, 0(R10)
ADD $4, R10
JMP f5
/*
* last loop, copy byte at a time
*/
fout:
SUBCC R11,R13, R0
BLEU ret
MOVB 0(R11), R16
ADD $1, R11
MOVB R16, 0(R10)
ADD $1, R10
JMP fout
/*
* whole thing repeated for backwards
*/
back:
SUBCC $4,R9, R0
BL bout
XOR R12,R13, R7
ANDCC $3,R7, R0
BNE bout
b1:
ANDCC $3,R13, R0
BE b2
MOVB -1(R13), R16
SUB $1, R13
MOVB R16, -1(R12)
SUB $1, R12
JMP b1
b2:
ADD $15,R11, R9
b3:
SUBCC R9,R13, R0
BLEU b4
MOVW -4(R13), R16
MOVW -8(R13), R17
MOVW R16, -4(R12)
MOVW -12(R13), R16
MOVW R17, -8(R12)
MOVW -16(R13), R17
SUB $16, R13
MOVW R16, -12(R12)
MOVW R17, -16(R12)
SUB $16, R12
JMP b3
b4:
ADD $3,R11, R9
b5:
SUBCC R9,R13, R0
BLEU bout
MOVW -4(R13), R16
SUB $4, R13
MOVW R16, -4(R12)
SUB $4, R12
JMP b5
bout:
SUBCC R11,R13, R0
BLEU ret
MOVB -1(R13), R16
SUB $1, R13
MOVB R16, -1(R12)
SUB $1, R12
JMP bout
ret:
MOVW s1+0(FP), R7
RETURN
|
9front/9front
| 1,715
|
sys/src/ape/lib/ap/sparc/memcmp.s
|
#define Bxx BE
TEXT memcmp(SB), $0
/*
* performance:
* (tba)
*/
MOVW R7, 0(FP)
MOVW n+8(FP), R9 /* R9 is count */
MOVW s1+0(FP), R10 /* R10 is pointer1 */
MOVW s2+4(FP), R11 /* R11 is pointer2 */
ADD R9,R10, R12 /* R12 is end pointer1 */
/*
* if not at least 4 chars,
* dont even mess around.
* 3 chars to guarantee any
* rounding up to a word
* boundary and 4 characters
* to get at least maybe one
* full word cmp.
*/
SUBCC $4,R9, R0
BL out
/*
* test if both pointers
* are similarly word alligned
*/
XOR R10,R11, R7
ANDCC $3,R7, R0
BNE out
/*
* byte at a time to word allign
*/
l1:
ANDCC $3,R10, R0
BE l2
MOVB 0(R10), R16
MOVB 0(R11), R17
ADD $1, R10
SUBCC R16,R17, R0
BNE ne
ADD $1, R11
JMP l1
/*
* turn R9 into end pointer1-15
* cmp 16 at a time while theres room
*/
l2:
SUB $15,R12, R9
l3:
SUBCC R10,R9, R0
BLEU l4
MOVW 0(R10), R16
MOVW 0(R11), R17
MOVW 4(R10), R18
SUBCC R16,R17, R0
BNE ne
MOVW 4(R11), R19
MOVW 8(R10), R16
SUBCC R18,R19, R0
BNE ne
MOVW 8(R11), R17
MOVW 12(R10), R18
SUBCC R16,R17, R0
BNE ne
MOVW 12(R11), R19
ADD $16, R10
SUBCC R18,R19, R0
BNE ne
SUBCC R16,R17, R0
BNE ne
ADD $16, R11
JMP l3
/*
* turn R9 into end pointer1-3
* cmp 4 at a time while theres room
*/
l4:
SUB $3,R12, R9
l5:
SUBCC R10,R9, R0
BLEU out
MOVW 0(R10), R16
MOVW 0(R11), R17
ADD $4, R10
SUBCC R16,R17, R0 /* only works because big endian */
BNE ne
ADD $4, R11
JMP l5
/*
* last loop, cmp byte at a time
*/
out:
SUBCC R10,R12, R0
BE zero
MOVB 0(R10), R16
MOVB 0(R11), R17
ADD $1, R10
SUBCC R16,R17, R0
BNE ne
ADD $1, R11
JMP out
ne:
BG plus
MOVW $1, R7
RETURN
plus:
MOVW $-1, R7
RETURN
zero:
MOVW R0, R7
RETURN
|
9front/9front
| 1,115
|
sys/src/ape/lib/ap/sparc/strcpy.s
|
TEXT strcpy(SB), $0
MOVW R7, 0(FP)
MOVW s1+0(FP), R9 /* R9 is to pointer */
MOVW s2+4(FP), R10 /* R10 is from pointer */
/*
* test if both pointers
* are similarly word aligned
*/
XOR R9,R10, R7
ANDCC $3,R7, R0
BNE una
/*
* make byte masks
*/
MOVW $0xff, R17
SLL $8,R17, R16
SLL $16,R17, R13
SLL $24,R17, R12
/*
* byte at a time to word align
*/
al1:
ANDCC $3,R10, R0
BE al2
MOVB (R10), R11
ADD $1, R10
MOVB R11, (R9)
ADD $1, R9
SUBCC R0,R11, R0
BNE al1
JMP out
/*
* word at a time
*/
al2:
ADD $4, R9
MOVW (R10), R11 /* fetch */
ADD $4, R10
ANDCC R12,R11, R0 /* is it byte 0 */
BE b0
ANDCC R13,R11, R0 /* is it byte 1 */
BE b1
ANDCC R16,R11, R0 /* is it byte 2 */
BE b2
MOVW R11, -4(R9) /* store */
ANDCC R17,R11, R0 /* is it byte 3 */
BNE al2
JMP out
b0:
MOVB R0, -4(R9)
JMP out
b1:
SRL $24, R11
MOVB R11, -4(R9)
MOVB R0, -3(R9)
JMP out
b2:
SRL $24,R11, R7
MOVB R7, -4(R9)
SRL $16, R11
MOVB R11, -3(R9)
MOVB R0, -2(R9)
JMP out
una:
MOVB (R10), R11
ADD $1, R10
MOVB R11, (R9)
ADD $1, R9
SUBCC R0,R11, R0
BNE una
out:
MOVW s1+0(FP),R7
RETURN
|
9front/9front
| 5,379
|
sys/src/ape/lib/ap/sparc/muldiv.s
|
/*
* ulong
* _udiv(ulong num, ulong den)
* {
* int i;
* ulong quo;
*
* if(den == 0)
* *(ulong*)-1 = 0;
* quo = num;
* if(quo > 1<<(32-1))
* quo = 1<<(32-1);
* for(i=0; den<quo; i++)
* den <<= 1;
* quo = 0;
* for(; i>=0; i--) {
* quo <<= 1;
* if(num >= den) {
* num -= den;
* quo |= 1;
* }
* den >>= 1;
* }
* return quo::num;
* }
*/
#define NOPROF 1
/*
* calling sequence:
* num: 4(R1)
* den: 8(R1)
* returns
* quo: 4(R1)
* rem: 8(R1)
*/
TEXT _udivmod(SB), NOPROF, $-4
MOVW $(1<<31), R11
MOVW 4(R1), R13 /* numerator */
MOVW 8(R1), R10 /* denominator */
CMP R10, R0
BNE udm20
MOVW R0, -1(R0) /* fault -- divide by zero */
udm20:
MOVW R13, R12
CMP R13, R11
BLEU udm34
MOVW R11, R12
udm34:
MOVW R0, R11
udm38:
CMP R10, R12
BCC udm54
SLL $1, R10
ADD $1, R11
BA udm38
udm54:
MOVW R0, R12
udm58:
CMP R11, R0
BL udm8c
SLL $1, R12
CMP R13, R10
BCS udm7c
SUB R10, R13
OR $1, R12
udm7c:
SRL $1, R10
SUB $1, R11
BA udm58
udm8c:
MOVW R12, 4(R1) /* quotent */
MOVW R13, 8(R1) /* remainder */
JMPL 8(R15)
/*
* save working registers
* and bring in num/den parameters
*/
TEXT _unsarg(SB), NOPROF, $-4
MOVW R10, 12(R1)
MOVW R11, 16(R1)
MOVW R12, 20(R1)
MOVW R13, 24(R1)
MOVW R14, 4(R1)
MOVW 32(R1), R14
MOVW R14, 8(R1)
JMPL 8(R15)
/*
* save working registers
* and bring in absolute value
* of num/den parameters
*/
TEXT _absarg(SB), NOPROF, $-4
MOVW R10, 12(R1)
MOVW R11, 16(R1)
MOVW R12, 20(R1)
MOVW R13, 24(R1)
MOVW R14, 28(R1)
CMP R14, R0
BGE ab1
SUB R14, R0, R14
ab1:
MOVW R14, 4(R1) /* numerator */
MOVW 32(R1), R14
CMP R14, R0
BGE ab2
SUB R14, R0, R14
ab2:
MOVW R14, 8(R1) /* denominator */
JMPL 8(R15)
/*
* restore registers and
* return to original caller
* answer is in R14
*/
TEXT _retarg(SB), NOPROF, $-4
MOVW 12(R1), R10
MOVW 16(R1), R11
MOVW 20(R1), R12
MOVW 24(R1), R13
MOVW 0(R1), R15
ADD $28, R1
JMP 8(R15) /* back to main sequence */
/*
* calling sequence
* num: R14
* den: 8(R1)
* returns
* quo: R14
*/
TEXT _div(SB), NOPROF, $-4
SUB $28, R1 /* 4 reg save, 2 parameters, link */
MOVW R15, 0(R1)
JMPL _absarg(SB)
JMPL _udivmod(SB)
MOVW 4(R1), R14
MOVW 28(R1), R10 /* clean up the sign */
MOVW 32(R1), R11
XORCC R11, R10, R0
BGE div1
SUB R14, R0, R14
div1:
JMPL _retarg(SB)
JMP 8(R15) /* not executed */
/*
* calling sequence
* num: R14
* den: 8(R1)
* returns
* quo: R14
*/
TEXT _divl(SB), NOPROF, $-4
SUB $((4+2+1)*4), R1 /* 4 reg save, 2 parameters, link */
MOVW R15, 0(R1)
JMPL _unsarg(SB)
JMPL _udivmod(SB)
MOVW 4(R1), R14
JMPL _retarg(SB)
JMP 8(R15) /* not executed */
/*
* calling sequence
* num: R14
* den: 8(R1)
* returns
* rem: R14
*/
TEXT _mod(SB), NOPROF, $-4
SUB $28, R1 /* 4 reg save, 2 parameters, link */
MOVW R15, 0(R1)
JMPL _absarg(SB)
JMPL _udivmod(SB)
MOVW 8(R1), R14
MOVW 28(R1), R10 /* clean up the sign */
CMP R10, R0
BGE mod1
SUB R14, R0, R14
mod1:
JMPL _retarg(SB)
JMP 8(R15) /* not executed */
/*
* calling sequence
* num: R14
* den: 8(R1)
* returns
* rem: R14
*/
TEXT _modl(SB), NOPROF, $-4
SUB $28, R1 /* 4 reg save, 2 parameters, link */
MOVW R15, 0(R1)
JMPL _unsarg(SB)
JMPL _udivmod(SB)
MOVW 8(R1), R14
JMPL _retarg(SB)
JMP 8(R15) /* not executed */
/*
* special calling sequence:
* arg1 in R14
* arg2 in 4(R1), will save R9
* nothing in 0(R1), will save R8
* result in R14
*/
TEXT _mul+0(SB), NOPROF, $-4
/*
* exchange stack and registers
*/
MOVW R8, 0(R1)
MOVW 4(R1), R8
MOVW R9, 4(R1)
CMP R14, R8
BLE mul1
MOVW R14, R9
MOVW R8, R14
MOVW R9, R8
mul1:
MOVW R14, Y
ANDNCC $0xFFF, R14, R0
BE mul_shortway
ANDCC R0, R0, R9 /* zero partial product and clear N and V cond's */
/* long multiply */
MULSCC R8, R9, R9 /* 0 */
MULSCC R8, R9, R9 /* 1 */
MULSCC R8, R9, R9 /* 2 */
MULSCC R8, R9, R9 /* 3 */
MULSCC R8, R9, R9 /* 4 */
MULSCC R8, R9, R9 /* 5 */
MULSCC R8, R9, R9 /* 6 */
MULSCC R8, R9, R9 /* 7 */
MULSCC R8, R9, R9 /* 8 */
MULSCC R8, R9, R9 /* 9 */
MULSCC R8, R9, R9 /* 10 */
MULSCC R8, R9, R9 /* 11 */
MULSCC R8, R9, R9 /* 12 */
MULSCC R8, R9, R9 /* 13 */
MULSCC R8, R9, R9 /* 14 */
MULSCC R8, R9, R9 /* 15 */
MULSCC R8, R9, R9 /* 16 */
MULSCC R8, R9, R9 /* 17 */
MULSCC R8, R9, R9 /* 18 */
MULSCC R8, R9, R9 /* 19 */
MULSCC R8, R9, R9 /* 20 */
MULSCC R8, R9, R9 /* 21 */
MULSCC R8, R9, R9 /* 22 */
MULSCC R8, R9, R9 /* 23 */
MULSCC R8, R9, R9 /* 24 */
MULSCC R8, R9, R9 /* 25 */
MULSCC R8, R9, R9 /* 26 */
MULSCC R8, R9, R9 /* 27 */
MULSCC R8, R9, R9 /* 28 */
MULSCC R8, R9, R9 /* 29 */
MULSCC R8, R9, R9 /* 30 */
MULSCC R8, R9, R9 /* 31 */
MULSCC R0, R9, R9 /* 32; shift only */
MOVW Y, R14 /* get low part */
BA mul_return
mul_shortway:
ANDCC R0, R0, R9 /* zero partial product and clear N and V cond's */
MULSCC R8, R9, R9 /* 0 */
MULSCC R8, R9, R9 /* 1 */
MULSCC R8, R9, R9 /* 2 */
MULSCC R8, R9, R9 /* 3 */
MULSCC R8, R9, R9 /* 4 */
MULSCC R8, R9, R9 /* 5 */
MULSCC R8, R9, R9 /* 6 */
MULSCC R8, R9, R9 /* 7 */
MULSCC R8, R9, R9 /* 8 */
MULSCC R8, R9, R9 /* 9 */
MULSCC R8, R9, R9 /* 10 */
MULSCC R8, R9, R9 /* 11 */
MULSCC R0, R9, R9 /* 12; shift only */
MOVW Y, R8
SLL $12, R9
SRL $20, R8
OR R8, R9, R14
mul_return:
MOVW 0(R1), R8
MOVW 4(R1), R9
JMP 8(R15)
|
9front/9front
| 2,423
|
sys/src/ape/lib/ap/sparc/vlop.s
|
TEXT _mulv(SB), $0
MOVW u1+8(FP), R8
MOVW u2+16(FP), R13
MOVW R13, R16 /* save low parts for later */
MOVW R8, R12
/*
* unsigned 32x32 => 64 multiply
*/
CMP R13, R8
BLE mul1
MOVW R12, R13
MOVW R16, R8
mul1:
MOVW R13, Y
ANDNCC $0xFFF, R13, R0
BE mul_shortway
ANDCC R0, R0, R9 /* zero partial product and clear N and V cond's */
/* long multiply */
MULSCC R8, R9, R9 /* 0 */
MULSCC R8, R9, R9 /* 1 */
MULSCC R8, R9, R9 /* 2 */
MULSCC R8, R9, R9 /* 3 */
MULSCC R8, R9, R9 /* 4 */
MULSCC R8, R9, R9 /* 5 */
MULSCC R8, R9, R9 /* 6 */
MULSCC R8, R9, R9 /* 7 */
MULSCC R8, R9, R9 /* 8 */
MULSCC R8, R9, R9 /* 9 */
MULSCC R8, R9, R9 /* 10 */
MULSCC R8, R9, R9 /* 11 */
MULSCC R8, R9, R9 /* 12 */
MULSCC R8, R9, R9 /* 13 */
MULSCC R8, R9, R9 /* 14 */
MULSCC R8, R9, R9 /* 15 */
MULSCC R8, R9, R9 /* 16 */
MULSCC R8, R9, R9 /* 17 */
MULSCC R8, R9, R9 /* 18 */
MULSCC R8, R9, R9 /* 19 */
MULSCC R8, R9, R9 /* 20 */
MULSCC R8, R9, R9 /* 21 */
MULSCC R8, R9, R9 /* 22 */
MULSCC R8, R9, R9 /* 23 */
MULSCC R8, R9, R9 /* 24 */
MULSCC R8, R9, R9 /* 25 */
MULSCC R8, R9, R9 /* 26 */
MULSCC R8, R9, R9 /* 27 */
MULSCC R8, R9, R9 /* 28 */
MULSCC R8, R9, R9 /* 29 */
MULSCC R8, R9, R9 /* 30 */
MULSCC R8, R9, R9 /* 31 */
MULSCC R0, R9, R9 /* 32; shift only; r9 is high part */
/*
* need to correct top word if top bit set
*/
CMP R8, R0
BGE mul_tstlow
ADD R13, R9 /* adjust the high parts */
mul_tstlow:
MOVW Y, R13 /* get low part */
BA mul_done
mul_shortway:
ANDCC R0, R0, R9 /* zero partial product and clear N and V cond's */
MULSCC R8, R9, R9 /* 0 */
MULSCC R8, R9, R9 /* 1 */
MULSCC R8, R9, R9 /* 2 */
MULSCC R8, R9, R9 /* 3 */
MULSCC R8, R9, R9 /* 4 */
MULSCC R8, R9, R9 /* 5 */
MULSCC R8, R9, R9 /* 6 */
MULSCC R8, R9, R9 /* 7 */
MULSCC R8, R9, R9 /* 8 */
MULSCC R8, R9, R9 /* 9 */
MULSCC R8, R9, R9 /* 10 */
MULSCC R8, R9, R9 /* 11 */
MULSCC R0, R9, R9 /* 12; shift only; r9 is high part */
MOVW Y, R8 /* make low part of partial low part & high part */
SLL $12, R9, R13
SRL $20, R8
OR R8, R13
SRA $20, R9 /* high part */
mul_done:
/*
* mul by high halves if needed
*/
MOVW R13, 4(R7)
MOVW u2+12(FP), R11
CMP R11, R0
BE nomul1
MUL R11, R12
ADD R12, R9
nomul1:
MOVW u1+4(FP), R11
CMP R11, R0
BE nomul2
MUL R11, R16
ADD R16, R9
nomul2:
MOVW R9, 0(R7)
RETURN
|
9front/9front
| 1,216
|
sys/src/ape/lib/ap/68020/memmove.s
|
TEXT memmove(SB), $0
move:
MOVL n+8(FP),R0
BEQ return
BGT ok
MOVL 0, R0
ok:
MOVL s1+0(FP),A2
MOVL s2+4(FP),A1
CMPL A2,A1
BHI back
/*
* speed depends on source allignment
* destination allignment is secondary
* byte-at-a-time foreward copy to
* get source (A1) alligned.
*/
f1:
MOVL A1, R1
ANDL $3, R1
BEQ f2
SUBL $1, R0
BLT return
MOVB (A1)+, (A2)+
BRA f1
/*
* quad-long-at-a-time forward copy
*/
f2:
SUBL $16, R0
BLT f3
MOVL (A1)+, (A2)+
MOVL (A1)+, (A2)+
MOVL (A1)+, (A2)+
MOVL (A1)+, (A2)+
BRA f2
/*
* cleanup byte-at-a-time
*/
f3:
ADDL $15, R0
BLT return
f4:
MOVB (A1)+, (A2)+
SUBL $1, R0
BGE f4
BRA return
return:
MOVL s1+0(FP),R0
RTS
/*
* everything the same, but
* copy backwards
*/
back:
ADDL R0, A1
ADDL R0, A2
/*
* byte-at-a-time backward copy to
* get source (A1) alligned.
*/
b1:
MOVL A1, R1
ANDL $3, R1
BEQ b2
SUBL $1, R0
BLT return
MOVB -(A1), -(A2)
BRA b1
/*
* quad-long-at-a-time backward copy
*/
b2:
SUBL $16, R0
BLT b3
MOVL -(A1), -(A2)
MOVL -(A1), -(A2)
MOVL -(A1), -(A2)
MOVL -(A1), -(A2)
BRA b2
/*
* cleanup byte-at-a-time backward
*/
b3:
ADDL $15, R0
BLT return
b4:
MOVB -(A1), -(A2)
SUBL $1, R0
BGE b4
BRA return
|
9front/9front
| 1,209
|
sys/src/ape/lib/ap/68020/memcpy.s
|
TEXT memcpy(SB), $0
MOVL n+8(FP),R0
BEQ return
BGT ok
MOVL 0, R0
ok:
MOVL s1+0(FP),A2
MOVL s2+4(FP),A1
CMPL A2,A1
BHI back
/*
* speed depends on source allignment
* destination allignment is secondary
* byte-at-a-time foreward copy to
* get source (A1) alligned.
*/
f1:
MOVL A1, R1
ANDL $3, R1
BEQ f2
SUBL $1, R0
BLT return
MOVB (A1)+, (A2)+
BRA f1
/*
* quad-long-at-a-time forward copy
*/
f2:
SUBL $16, R0
BLT f3
MOVL (A1)+, (A2)+
MOVL (A1)+, (A2)+
MOVL (A1)+, (A2)+
MOVL (A1)+, (A2)+
BRA f2
/*
* cleanup byte-at-a-time
*/
f3:
ADDL $15, R0
BLT return
f4:
MOVB (A1)+, (A2)+
SUBL $1, R0
BGE f4
BRA return
return:
MOVL s1+0(FP),R0
RTS
/*
* everything the same, but
* copy backwards
*/
back:
ADDL R0, A1
ADDL R0, A2
/*
* byte-at-a-time backward copy to
* get source (A1) alligned.
*/
b1:
MOVL A1, R1
ANDL $3, R1
BEQ b2
SUBL $1, R0
BLT return
MOVB -(A1), -(A2)
BRA b1
/*
* quad-long-at-a-time backward copy
*/
b2:
SUBL $16, R0
BLT b3
MOVL -(A1), -(A2)
MOVL -(A1), -(A2)
MOVL -(A1), -(A2)
MOVL -(A1), -(A2)
BRA b2
/*
* cleanup byte-at-a-time backward
*/
b3:
ADDL $15, R0
BLT return
b4:
MOVB -(A1), -(A2)
SUBL $1, R0
BGE b4
BRA return
|
9front/9front
| 4,188
|
sys/src/ape/lib/ap/arm/memmove.s
|
TS = 0
TE = 1
FROM = 2
N = 3
TMP = 3 /* N and TMP don't overlap */
TMP1 = 4
TEXT memcpy(SB), 1, $-4
TEXT memmove(SB), $0
_memmove:
MOVW R(TS), to+0(FP) /* need to save for return value */
MOVW from+4(FP), R(FROM)
MOVW n+8(FP), R(N)
ADD R(N), R(TS), R(TE) /* to end pointer */
CMP R(FROM), R(TS)
BLS _forward
_back:
ADD R(N), R(FROM) /* from end pointer */
CMP $4, R(N) /* need at least 4 bytes to copy */
BLT _b1tail
_b4align: /* align destination on 4 */
AND.S $3, R(TE), R(TMP)
BEQ _b4aligned
MOVBU.W -1(R(FROM)), R(TMP) /* pre-indexed */
MOVBU.W R(TMP), -1(R(TE)) /* pre-indexed */
B _b4align
_b4aligned: /* is source now aligned? */
AND.S $3, R(FROM), R(TMP)
BNE _bunaligned
ADD $31, R(TS), R(TMP) /* do 32-byte chunks if possible */
_b32loop:
CMP R(TMP), R(TE)
BLS _b4tail
MOVM.DB.W (R(FROM)), [R4-R7]
MOVM.DB.W [R4-R7], (R(TE))
MOVM.DB.W (R(FROM)), [R4-R7]
MOVM.DB.W [R4-R7], (R(TE))
B _b32loop
_b4tail: /* do remaining words if possible */
ADD $3, R(TS), R(TMP)
_b4loop:
CMP R(TMP), R(TE)
BLS _b1tail
MOVW.W -4(R(FROM)), R(TMP1) /* pre-indexed */
MOVW.W R(TMP1), -4(R(TE)) /* pre-indexed */
B _b4loop
_b1tail: /* remaining bytes */
CMP R(TE), R(TS)
BEQ _return
MOVBU.W -1(R(FROM)), R(TMP) /* pre-indexed */
MOVBU.W R(TMP), -1(R(TE)) /* pre-indexed */
B _b1tail
_forward:
CMP $4, R(N) /* need at least 4 bytes to copy */
BLT _f1tail
_f4align: /* align destination on 4 */
AND.S $3, R(TS), R(TMP)
BEQ _f4aligned
MOVBU.P 1(R(FROM)), R(TMP) /* implicit write back */
MOVBU.P R(TMP), 1(R(TS)) /* implicit write back */
B _f4align
_f4aligned: /* is source now aligned? */
AND.S $3, R(FROM), R(TMP)
BNE _funaligned
SUB $31, R(TE), R(TMP) /* do 32-byte chunks if possible */
_f32loop:
CMP R(TMP), R(TS)
BHS _f4tail
MOVM.IA.W (R(FROM)), [R4-R7]
MOVM.IA.W [R4-R7], (R(TS))
MOVM.IA.W (R(FROM)), [R4-R7]
MOVM.IA.W [R4-R7], (R(TS))
B _f32loop
_f4tail:
SUB $3, R(TE), R(TMP) /* do remaining words if possible */
_f4loop:
CMP R(TMP), R(TS)
BHS _f1tail
MOVW.P 4(R(FROM)), R(TMP1) /* implicit write back */
MOVW.P R4, 4(R(TS)) /* implicit write back */
B _f4loop
_f1tail:
CMP R(TS), R(TE)
BEQ _return
MOVBU.P 1(R(FROM)), R(TMP) /* implicit write back */
MOVBU.P R(TMP), 1(R(TS)) /* implicit write back */
B _f1tail
_return:
MOVW to+0(FP), R0
RET
RSHIFT = 4
LSHIFT = 5
OFFSET = 11
BR0 = 6
BW0 = 7
BR1 = 7
BW1 = 8
_bunaligned:
CMP $2, R(TMP) /* is R(TMP) < 2 ? */
MOVW.LT $8, R(RSHIFT) /* (R(n)<<24)|(R(n-1)>>8) */
MOVW.LT $24, R(LSHIFT)
MOVW.LT $1, R(OFFSET)
MOVW.EQ $16, R(RSHIFT) /* (R(n)<<16)|(R(n-1)>>16) */
MOVW.EQ $16, R(LSHIFT)
MOVW.EQ $2, R(OFFSET)
MOVW.GT $24, R(RSHIFT) /* (R(n)<<8)|(R(n-1)>>24) */
MOVW.GT $8, R(LSHIFT)
MOVW.GT $3, R(OFFSET)
ADD $8, R(TS), R(TMP) /* do 8-byte chunks if possible */
CMP R(TMP), R(TE)
BLS _b1tail
BIC $3, R(FROM) /* align source */
MOVW (R(FROM)), R(BR0) /* prime first block register */
_bu8loop:
CMP R(TMP), R(TE)
BLS _bu1tail
MOVW R(BR0)<<R(LSHIFT), R(BW1)
MOVM.DB.W (R(FROM)), [R(BR0)-R(BR1)]
ORR R(BR1)>>R(RSHIFT), R(BW1)
MOVW R(BR1)<<R(LSHIFT), R(BW0)
ORR R(BR0)>>R(RSHIFT), R(BW0)
MOVM.DB.W [R(BW0)-R(BW1)], (R(TE))
B _bu8loop
_bu1tail:
ADD R(OFFSET), R(FROM)
B _b1tail
RSHIFT = 4
LSHIFT = 5
OFFSET = 11
FW0 = 6
FR0 = 7
FW1 = 7
FR1 = 8
_funaligned:
CMP $2, R(TMP)
MOVW.LT $8, R(RSHIFT) /* (R(n+1)<<24)|(R(n)>>8) */
MOVW.LT $24, R(LSHIFT)
MOVW.LT $3, R(OFFSET)
MOVW.EQ $16, R(RSHIFT) /* (R(n+1)<<16)|(R(n)>>16) */
MOVW.EQ $16, R(LSHIFT)
MOVW.EQ $2, R(OFFSET)
MOVW.GT $24, R(RSHIFT) /* (R(n+1)<<8)|(R(n)>>24) */
MOVW.GT $8, R(LSHIFT)
MOVW.GT $1, R(OFFSET)
SUB $8, R(TE), R(TMP) /* do 8-byte chunks if possible */
CMP R(TMP), R(TS)
BHS _f1tail
BIC $3, R(FROM) /* align source */
MOVW.P 4(R(FROM)), R(FR1) /* prime last block register, implicit write back */
_fu8loop:
CMP R(TMP), R(TS)
BHS _fu1tail
MOVW R(FR1)>>R(RSHIFT), R(FW0)
MOVM.IA.W (R(FROM)), [R(FR0)-R(FR1)]
ORR R(FR0)<<R(LSHIFT), R(FW0)
MOVW R(FR0)>>R(RSHIFT), R(FW1)
ORR R(FR1)<<R(LSHIFT), R(FW1)
MOVM.IA.W [R(FW0)-R(FW1)], (R(TS))
B _fu8loop
_fu1tail:
SUB R(OFFSET), R(FROM)
B _f1tail
|
9front/9front
| 1,639
|
sys/src/ape/lib/ap/arm/div.s
|
Q = 0
N = 1
D = 2
CC = 3
TMP = 11
TEXT save<>(SB), 1, $0
MOVW R(Q), 0(FP)
MOVW R(N), 4(FP)
MOVW R(D), 8(FP)
MOVW R(CC), 12(FP)
MOVW R(TMP), R(Q) /* numerator */
MOVW 20(FP), R(D) /* denominator */
CMP $0, R(D)
BNE s1
MOVW -1(R(D)), R(TMP) /* divide by zero fault */
s1: RET
TEXT rest<>(SB), 1, $0
MOVW 0(FP), R(Q)
MOVW 4(FP), R(N)
MOVW 8(FP), R(D)
MOVW 12(FP), R(CC)
/*
* return to caller
* of rest<>
*/
MOVW 0(R13), R14
ADD $20, R13
B (R14)
TEXT div<>(SB), 1, $0
MOVW $32, R(CC)
/*
* skip zeros 8-at-a-time
*/
e1:
AND.S $(0xff<<24),R(Q), R(N)
BNE e2
SLL $8, R(Q)
SUB.S $8, R(CC)
BNE e1
RET
e2:
MOVW $0, R(N)
loop:
/*
* shift R(N||Q) left one
*/
SLL $1, R(N)
CMP $0, R(Q)
ORR.LT $1, R(N)
SLL $1, R(Q)
/*
* compare numerator to denominator
* if less, subtract and set quotent bit
*/
CMP R(D), R(N)
ORR.HS $1, R(Q)
SUB.HS R(D), R(N)
SUB.S $1, R(CC)
BNE loop
RET
TEXT _div(SB), 1, $16
BL save<>(SB)
CMP $0, R(Q)
BGE d1
RSB $0, R(Q), R(Q)
CMP $0, R(D)
BGE d2
RSB $0, R(D), R(D)
d0:
BL div<>(SB) /* none/both neg */
MOVW R(Q), R(TMP)
B out
d1:
CMP $0, R(D)
BGE d0
RSB $0, R(D), R(D)
d2:
BL div<>(SB) /* one neg */
RSB $0, R(Q), R(TMP)
B out
TEXT _mod(SB), 1, $16
BL save<>(SB)
CMP $0, R(D)
RSB.LT $0, R(D), R(D)
CMP $0, R(Q)
BGE m1
RSB $0, R(Q), R(Q)
BL div<>(SB) /* neg numerator */
RSB $0, R(N), R(TMP)
B out
m1:
BL div<>(SB) /* pos numerator */
MOVW R(N), R(TMP)
B out
TEXT _divu(SB), 1, $16
BL save<>(SB)
BL div<>(SB)
MOVW R(Q), R(TMP)
B out
TEXT _modu(SB), 1, $16
BL save<>(SB)
BL div<>(SB)
MOVW R(N), R(TMP)
B out
out:
BL rest<>(SB)
B out
|
9front/9front
| 1,734
|
sys/src/ape/lib/ap/spim/memcmp.s
|
TEXT memcmp(SB), $0
MOVW R1, 0(FP)
/*
* performance:
* alligned about 1.0us/call and 17.4mb/sec
* unalligned is about 3.1mb/sec
*/
MOVW n+8(FP), R3 /* R3 is count */
MOVW s1+0(FP), R4 /* R4 is pointer1 */
MOVW s2+4(FP), R5 /* R5 is pointer2 */
ADDU R3,R4, R6 /* R6 is end pointer1 */
/* TODO(mischief): fix multibyte copy */
JMP out
/*
* if not at least 4 chars,
* dont even mess around.
* 3 chars to guarantee any
* rounding up to a word
* boundary and 4 characters
* to get at least maybe one
* full word cmp.
*/
SGT $4,R3, R1
BNE R1, out
/*
* test if both pointers
* are similarly word alligned
*/
XOR R4,R5, R1
AND $3, R1
BNE R1, out
/*
* byte at a time to word allign
*/
l1:
AND $3,R4, R1
BEQ R1, l2
MOVBU 0(R4), R8
MOVBU 0(R5), R9
ADDU $1, R4
BNE R8,R9, ne
ADDU $1, R5
JMP l1
/*
* turn R3 into end pointer1-15
* cmp 16 at a time while theres room
*/
l2:
ADDU $-15,R6, R3
l3:
SGTU R3,R4, R1
BEQ R1, l4
MOVW 0(R4), R8
MOVW 0(R5), R9
MOVW 4(R4), R10
BNE R8,R9, ne
MOVW 4(R5), R11
MOVW 8(R4), R8
BNE R10,R11, ne1
MOVW 8(R5), R9
MOVW 12(R4), R10
BNE R8,R9, ne
MOVW 12(R5), R11
ADDU $16, R4
BNE R10,R11, ne1
BNE R8,R9, ne
ADDU $16, R5
JMP l3
/*
* turn R3 into end pointer1-3
* cmp 4 at a time while theres room
*/
l4:
ADDU $-3,R6, R3
l5:
SGTU R3,R4, R1
BEQ R1, out
MOVW 0(R4), R8
MOVW 0(R5), R9
ADDU $4, R4
BNE R8,R9, ne /* only works because big endian */
ADDU $4, R5
JMP l5
/*
* last loop, cmp byte at a time
*/
out:
SGTU R6,R4, R1
BEQ R1, ret
MOVBU 0(R4), R8
MOVBU 0(R5), R9
ADDU $1, R4
BNE R8,R9, ne
ADDU $1, R5
JMP out
ne1:
SGTU R10,R11, R1
BNE R1, ret
MOVW $-1,R1
RET
ne:
SGTU R8,R9, R1
BNE R1, ret
MOVW $-1,R1
ret:
RET
END
|
9front/9front
| 1,270
|
sys/src/ape/lib/ap/mips/memset.s
|
TEXT memset(SB),$12
MOVW R1, 0(FP)
/*
* performance:
* about 1us/call and 28mb/sec
*/
MOVW n+8(FP), R3 /* R3 is count */
MOVW p+0(FP), R4 /* R4 is pointer */
MOVW c+4(FP), R5 /* R5 is char */
ADDU R3,R4, R6 /* R6 is end pointer */
/*
* if not at least 4 chars,
* dont even mess around.
* 3 chars to guarantee any
* rounding up to a word
* boundary and 4 characters
* to get at least maybe one
* full word store.
*/
SGT $4,R3, R1
BNE R1, out
/*
* turn R5 into a word of characters
*/
AND $0xff, R5
SLL $8,R5, R1
OR R1, R5
SLL $16,R5, R1
OR R1, R5
/*
* store one byte at a time until pointer
* is alligned on a word boundary
*/
l1:
AND $3,R4, R1
BEQ R1, l2
MOVB R5, 0(R4)
ADDU $1, R4
JMP l1
/*
* turn R3 into end pointer-15
* store 16 at a time while theres room
*/
l2:
ADDU $-15,R6, R3
l3:
SGTU R3,R4, R1
BEQ R1, l4
MOVW R5, 0(R4)
MOVW R5, 4(R4)
ADDU $16, R4
MOVW R5, -8(R4)
MOVW R5, -4(R4)
JMP l3
/*
* turn R3 into end pointer-3
* store 4 at a time while theres room
*/
l4:
ADDU $-3,R6, R3
l5:
SGTU R3,R4, R1
BEQ R1, out
MOVW R5, 0(R4)
ADDU $4, R4
JMP l5
/*
* last loop, store byte at a time
*/
out:
SGTU R6,R4 ,R1
BEQ R1, ret
MOVB R5, 0(R4)
ADDU $1, R4
JMP out
ret:
MOVW s1+0(FP), R1
RET
END
|
9front/9front
| 2,341
|
sys/src/ape/lib/ap/mips/memmove.s
|
TEXT memmove(SB), $0
JMP move
TEXT memcpy(SB), $0
move:
MOVW R1, s1+0(FP)
MOVW n+8(FP), R3 /* R3 is count */
MOVW R1, R4 /* R4 is to-pointer */
SGT R0, R3, R5
BEQ R5, ok
MOVW (R0), R0 /* abort if negative count */
ok:
MOVW s2+4(FP), R5 /* R5 is from-pointer */
ADDU R3,R5, R7 /* R7 is end from-pointer */
ADDU R3,R4, R6 /* R6 is end to-pointer */
/*
* easiest test is copy backwards if
* destination string has higher mem address
*/
SGT $4,R3, R2
SGTU R4,R5, R1
BNE R1, back
/*
* if not at least 4 chars,
* dont even mess around.
* 3 chars to guarantee any
* rounding up to a word
* boundary and 4 characters
* to get at least maybe one
* full word store.
*/
BNE R2, fout
/*
* test if both pointers
* are similarly word aligned
*/
XOR R4,R5, R1
AND $3, R1
BNE R1, fout
/*
* byte at a time to word align
*/
f1:
AND $3,R4, R1
BEQ R1, f2
MOVB 0(R5), R8
ADDU $1, R5
MOVB R8, 0(R4)
ADDU $1, R4
JMP f1
/*
* turn R3 into to-end pointer-15
* copy 16 at a time while theres room.
* R6 is smaller than R7 --
* there are problems if R7 is 0.
*/
f2:
ADDU $-15,R6, R3
f3:
SGTU R3,R4, R1
BEQ R1, f4
MOVW 0(R5), R8
MOVW 4(R5), R9
MOVW R8, 0(R4)
MOVW 8(R5), R8
MOVW R9, 4(R4)
MOVW 12(R5), R9
ADDU $16, R5
MOVW R8, 8(R4)
MOVW R9, 12(R4)
ADDU $16, R4
JMP f3
/*
* turn R3 into to-end pointer-3
* copy 4 at a time while theres room
*/
f4:
ADDU $-3,R6, R3
f5:
SGTU R3,R4, R1
BEQ R1, fout
MOVW 0(R5), R8
ADDU $4, R5
MOVW R8, 0(R4)
ADDU $4, R4
JMP f5
/*
* last loop, copy byte at a time
*/
fout:
BEQ R7,R5, ret
MOVB 0(R5), R8
ADDU $1, R5
MOVB R8, 0(R4)
ADDU $1, R4
JMP fout
/*
* whole thing repeated for backwards
*/
back:
BNE R2, bout
XOR R6,R7, R1
AND $3, R1
BNE R1, bout
b1:
AND $3,R7, R1
BEQ R1, b2
MOVB -1(R7), R8
ADDU $-1, R7
MOVB R8, -1(R6)
ADDU $-1, R6
JMP b1
b2:
ADDU $15,R5, R3
b3:
SGTU R7,R3, R1
BEQ R1, b4
MOVW -4(R7), R8
MOVW -8(R7), R9
MOVW R8, -4(R6)
MOVW -12(R7), R8
MOVW R9, -8(R6)
MOVW -16(R7), R9
ADDU $-16, R7
MOVW R8, -12(R6)
MOVW R9, -16(R6)
ADDU $-16, R6
JMP b3
b4:
ADDU $3,R5, R3
b5:
SGTU R7,R3, R1
BEQ R1, bout
MOVW -4(R7), R8
ADDU $-4, R7
MOVW R8, -4(R6)
ADDU $-4, R6
JMP b5
bout:
BEQ R7,R5, ret
MOVB -1(R7), R8
ADDU $-1, R7
MOVB R8, -1(R6)
ADDU $-1, R6
JMP bout
ret:
MOVW s1+0(FP), R1
RET
END
|
9front/9front
| 1,678
|
sys/src/ape/lib/ap/mips/memcmp.s
|
TEXT memcmp(SB), $0
MOVW R1, 0(FP)
/*
* performance:
* alligned about 1.0us/call and 17.4mb/sec
* unalligned is about 3.1mb/sec
*/
MOVW n+8(FP), R3 /* R3 is count */
MOVW s1+0(FP), R4 /* R4 is pointer1 */
MOVW s2+4(FP), R5 /* R5 is pointer2 */
ADDU R3,R4, R6 /* R6 is end pointer1 */
/*
* if not at least 4 chars,
* dont even mess around.
* 3 chars to guarantee any
* rounding up to a word
* boundary and 4 characters
* to get at least maybe one
* full word cmp.
*/
SGT $4,R3, R1
BNE R1, out
/*
* test if both pointers
* are similarly word alligned
*/
XOR R4,R5, R1
AND $3, R1
BNE R1, out
/*
* byte at a time to word allign
*/
l1:
AND $3,R4, R1
BEQ R1, l2
MOVB 0(R4), R8
MOVB 0(R5), R9
ADDU $1, R4
BNE R8,R9, ne
ADDU $1, R5
JMP l1
/*
* turn R3 into end pointer1-15
* cmp 16 at a time while theres room
*/
l2:
ADDU $-15,R6, R3
l3:
SGTU R3,R4, R1
BEQ R1, l4
MOVW 0(R4), R8
MOVW 0(R5), R9
MOVW 4(R4), R10
BNE R8,R9, ne
MOVW 4(R5), R11
MOVW 8(R4), R8
BNE R10,R11, ne1
MOVW 8(R5), R9
MOVW 12(R4), R10
BNE R8,R9, ne
MOVW 12(R5), R11
ADDU $16, R4
BNE R10,R11, ne1
BNE R8,R9, ne
ADDU $16, R5
JMP l3
/*
* turn R3 into end pointer1-3
* cmp 4 at a time while theres room
*/
l4:
ADDU $-3,R6, R3
l5:
SGTU R3,R4, R1
BEQ R1, out
MOVW 0(R4), R8
MOVW 0(R5), R9
ADDU $4, R4
BNE R8,R9, ne /* only works because big endian */
ADDU $4, R5
JMP l5
/*
* last loop, cmp byte at a time
*/
out:
SGTU R6,R4, R1
BEQ R1, ret
MOVB 0(R4), R8
MOVB 0(R5), R9
ADDU $1, R4
BNE R8,R9, ne
ADDU $1, R5
JMP out
ne1:
SGTU R10,R11, R1
BNE R1, ret
MOVW $-1,R1
RET
ne:
SGTU R8,R9, R1
BNE R1, ret
MOVW $-1,R1
ret:
RET
END
|
9front/9front
| 1,202
|
sys/src/ape/lib/ap/mips/strcpy.s
|
TEXT strcpy(SB), $0
MOVW s2+4(FP),R2 /* R2 is from pointer */
MOVW R1, R3 /* R3 is to pointer */
/*
* align 'from' pointer
*/
l1:
AND $3, R2, R5
ADDU $1, R2
BEQ R5, l2
MOVB -1(R2), R5
ADDU $1, R3
MOVB R5, -1(R3)
BNE R5, l1
RET
/*
* test if 'to' is also alligned
*/
l2:
AND $3,R3, R5
BEQ R5, l4
/*
* copy 4 at a time, 'to' not aligned
*/
l3:
MOVW -1(R2), R4
ADD $4, R2
ADD $4, R3
SRL $24,R4, R5
MOVB R5, -4(R3)
BEQ R5, out
SRL $16,R4, R5
AND $0xff, R5
MOVB R5, -3(R3)
BEQ R5, out
SRL $8,R4, R5
AND $0xff, R5
MOVB R5, -2(R3)
BEQ R5, out
AND $0xff,R4, R5
MOVB R5, -1(R3)
BNE R5, l3
out:
RET
/*
* word at a time both aligned
*/
l4:
MOVW $0xff000000, R7
MOVW $0x00ff0000, R8
l5:
ADDU $4, R3
MOVW -1(R2), R4 /* fetch */
ADDU $4, R2
AND R7,R4, R5 /* is it byte 0 */
AND R8,R4, R6 /* is it byte 1 */
BEQ R5, b0
AND $0xff00,R4, R5 /* is it byte 2 */
BEQ R6, b1
AND $0xff,R4, R6 /* is it byte 3 */
BEQ R5, b2
MOVW R4, -4(R3) /* store */
BNE R6, l5
JMP out
b0:
MOVB $0, -4(R3)
JMP out
b1:
SRL $24, R4
MOVB R4, -4(R3)
MOVB $0, -3(R3)
JMP out
b2:
SRL $24,R4, R5
MOVB R5, -4(R3)
SRL $16, R4
MOVB R4, -3(R3)
MOVB $0, -2(R3)
JMP out
|
9front/9front
| 12,757
|
sys/src/9/omap/l.s
|
/*
* ti omap3530 SoC machine assist
* arm cortex-a8 processor
*
* loader uses R11 as scratch.
* R9 and R10 are used for `extern register' variables.
*
* ARM v7 arch. ref. man. §B1.3.3 that we don't need barriers
* around moves to CPSR.
*/
#include "arm.s"
/*
* MCR and MRC are counter-intuitively named.
* MCR coproc, opcode1, Rd, CRn, CRm[, opcode2] # arm -> coproc
* MRC coproc, opcode1, Rd, CRn, CRm[, opcode2] # coproc -> arm
*/
/*
* Entered here from Das U-Boot or another Plan 9 kernel with MMU disabled.
* Until the MMU is enabled it is OK to call functions provided
* they are within ±32MiB relative and do not require any
* local variables or more than one argument (i.e. there is
* no stack).
*/
TEXT _start(SB), 1, $-4
MOVW $setR12(SB), R12 /* load the SB */
SUB $KZERO, R12
ADD $PHYSDRAM, R12
/* SVC mode, interrupts disabled */
MOVW $(PsrDirq|PsrDfiq|PsrMsvc), R1
MOVW R1, CPSR
BARRIERS
DELAY(printloopret, 1)
WAVE('\r')
DELAY(printloopnl, 1)
WAVE('\n')
/*
* work around errata
*/
MRC CpSC, 0, R1, C(CpCONTROL), C(0), CpAuxctl
ORR $(CpACissue1|CpACldstissue1), R1 /* fight omap35x errata 3.1.1.9 */
ORR $CpACibe, R1 /* enable cp15 invalidate */
ORR $CpACl1pe, R1 /* enable l1 parity checking */
ORR $CpCalign, R1 /* catch alignment errors */
BIC $CpACasa, R1 /* no speculative accesses */
/* go faster with fewer restrictions */
BIC $(CpACcachenopipe|CpACcp15serial|CpACcp15waitidle|CpACcp15pipeflush), R1
MCR CpSC, 0, R1, C(CpCONTROL), C(0), CpAuxctl
ISB
MRC CpSC, 1, R1, C(CpCLD), C(CpCLDl2), CpCLDl2aux
ORR $CpCl2nowralloc, R1 /* fight cortex errata 460075 */
ORR $(CpCl2ecc|CpCl2eccparity), R1
#ifdef TEDIUM
/*
* I don't know why this clobbers the system, but I'm tired
* of arguing with this fussy processor. To hell with it.
*/
MCR CpSC, 1, R1, C(CpCLD), C(CpCLDl2), CpCLDl2aux
ISB
#endif
DELAY(printloops, 1)
WAVE('P')
/*
* disable the MMU & caches
*/
MRC CpSC, 0, R1, C(CpCONTROL), C(0), CpMainctl
BIC $(CpCdcache|CpCicache|CpCmmu), R1
ORR $CpCsbo, R1
BIC $CpCsbz, R1
MCR CpSC, 0, R1, C(CpCONTROL), C(0), CpMainctl
ISB
MRC CpSC, 0, R1, C(CpCONTROL), C(0), CpAuxctl
BIC $CpACl2en, R1 /* turn l2 cache off */
MCR CpSC, 0, R1, C(CpCONTROL), C(0), CpAuxctl
ISB
WAVE('l')
DELAY(printloop3, 1)
WAVE('a')
/* clear Mach */
MOVW $PADDR(MACHADDR), R4 /* address of Mach */
MOVW $0, R0
_machZ:
MOVW R0, (R4)
ADD $4, R4
CMP.S $PADDR(L1+L1X(0)), R4 /* end at top-level page table */
BNE _machZ
/*
* set up the MMU page table
*/
WAVE('n')
/* clear all PTEs first, to provide a default */
// MOVW $PADDR(L1+L1X(0)), R4 /* address of PTE for 0 */
_ptenv0:
ZEROPTE()
CMP.S $PADDR(L1+16*KiB), R4
BNE _ptenv0
DELAY(printloop4, 2)
WAVE(' ')
/*
* set up double map of PHYSDRAM, KZERO to PHYSDRAM for first few MBs,
* but only if KZERO and PHYSDRAM differ.
*/
MOVW $PTEDRAM, R2 /* PTE bits */
MOVW $PHYSDRAM, R3 /* pa */
CMP $KZERO, R3
BEQ no2map
MOVW $PADDR(L1+L1X(PHYSDRAM)), R4 /* address of PTE for PHYSDRAM */
MOVW $DOUBLEMAPMBS, R5
_ptdbl:
FILLPTE()
SUB.S $1, R5
BNE _ptdbl
no2map:
/*
* back up and fill in PTEs for memory at KZERO.
* beagle has 1 bank of 256MB of SDRAM at PHYSDRAM;
* igepv2 has 1 bank of 512MB at PHYSDRAM.
* Map the maximum (512MB).
*/
WAVE('9')
MOVW $PTEDRAM, R2 /* PTE bits */
MOVW $PHYSDRAM, R3
MOVW $PADDR(L1+L1X(KZERO)), R4 /* start with PTE for KZERO */
MOVW $512, R5 /* inner loop count (MBs) */
_ptekrw: /* set PTEs */
FILLPTE()
SUB.S $1, R5 /* decrement inner loop count */
BNE _ptekrw
/*
* back up and fill in PTEs for MMIO
* stop somewhere after uarts
*/
WAVE(' ')
MOVW $PTEIO, R2 /* PTE bits */
MOVW $PHYSIO, R3
MOVW $PADDR(L1+L1X(VIRTIO)), R4 /* start with PTE for VIRTIO */
_ptenv2:
FILLPTE()
CMP.S $PADDR(L1+L1X(PHYSIOEND)), R4
BNE _ptenv2
/* mmu.c sets up the trap vectors later */
/*
* set up a temporary stack; avoid data & bss segments
*/
MOVW $(PHYSDRAM | (128*1024*1024)), R13
/* invalidate caches */
BL cachedinv(SB)
MOVW $KZERO, R0
MCR CpSC, 0, R0, C(CpCACHE), C(CpCACHEinvi), CpCACHEall
ISB
MCR CpSC, 0, R0, C(CpCACHE), C(CpCACHEwb), CpCACHEwait
BARRIERS
WAVE('f')
/*
* turn caches on
*/
MRC CpSC, 0, R1, C(CpCONTROL), C(0), CpAuxctl
ORR $CpACl2en, R1 /* turn l2 cache on */
MCR CpSC, 0, R1, C(CpCONTROL), C(0), CpAuxctl
BARRIERS
MRC CpSC, 0, R1, C(CpCONTROL), C(0), CpMainctl
ORR $(CpCdcache|CpCicache), R1
MCR CpSC, 0, R1, C(CpCONTROL), C(0), CpMainctl
BARRIERS
WAVE('r')
/* set the domain access control */
MOVW $Client, R0
BL dacput(SB)
DELAY(printloop5, 2)
WAVE('o')
/* set the translation table base */
MOVW $PADDR(L1), R0
BL ttbput(SB)
MOVW $0, R0
BL pidput(SB) /* paranoia */
WAVE('m')
/*
* the little dance to turn the MMU on
*/
BL cacheuwbinv(SB)
BL mmuinvalidate(SB)
BL mmuenable(SB)
WAVE(' ')
/* warp the PC into the virtual map */
MOVW $KZERO, R0
BL _r15warp(SB)
/*
* now running at KZERO+something!
*/
MOVW $setR12(SB), R12 /* reload the SB */
/*
* set up temporary stack again, in case we've just switched
* to a new register set.
*/
MOVW $(KZERO|(128*1024*1024)), R13
/* can now execute arbitrary C code */
BL cacheuwbinv(SB)
WAVE('B')
MOVW $PHYSDRAM, R3 /* pa */
CMP $KZERO, R3
BEQ no2unmap
/* undo double map of PHYSDRAM, KZERO & first few MBs */
MOVW $(L1+L1X(PHYSDRAM)), R4 /* addr. of PTE for PHYSDRAM */
MOVW $0, R0
MOVW $DOUBLEMAPMBS, R5
_ptudbl:
ZEROPTE()
SUB.S $1, R5
BNE _ptudbl
no2unmap:
BARRIERS
MOVW $KZERO, R0
MCR CpSC, 0, R0, C(CpTLB), C(CpTLBinvu), CpTLBinv
BARRIERS
#ifdef HIGH_SECURITY /* i.e., not GP omap */
/* hack: set `secure monitor' vector base addr for cortex */
// MOVW $HVECTORS, R0
MOVW $PADDR(L1), R0
SUB $(MACHSIZE+(2*1024)), R0
MCR CpSC, 0, R0, C(CpVECS), C(CpVECSbase), CpVECSmon
ISB
#endif
/*
* call main in C
* pass Mach to main and set up the stack in it
*/
MOVW $(MACHADDR), R0 /* Mach */
MOVW R0, R13
ADD $(MACHSIZE), R13 /* stack pointer */
SUB $4, R13 /* space for link register */
MOVW R0, R10 /* m = MACHADDR */
WAVE('e')
BL main(SB) /* void main(Mach*) */
/*FALLTHROUGH*/
/*
* reset the system
*/
TEXT _reset(SB), 1, $-4
MOVW $(PsrDirq|PsrDfiq|PsrMsvc), R0
MOVW R0, CPSR
BARRIERS
DELAY(printloopr, 2)
WAVE('!')
WAVE('r')
WAVE('e')
WAVE('s')
WAVE('e')
WAVE('t')
WAVE('!')
WAVE('\r')
WAVE('\n')
/* turn the caches off */
BL cacheuwbinv(SB)
MRC CpSC, 0, R0, C(CpCONTROL), C(0), CpMainctl
BIC $(CpCicache|CpCdcache|CpCalign), R0
ORR $CpCsw, R0 /* enable SWP */
MCR CpSC, 0, R0, C(CpCONTROL), C(0), CpMainctl
BARRIERS
/* redo double map of PHYSDRAM, KZERO & first few MBs */
MOVW $PTEDRAM, R2 /* PTE bits */
MOVW $PHYSDRAM, R3 /* pa */
MOVW $(L1+L1X(PHYSDRAM)), R4 /* address of PHYSDRAM's PTE */
MOVW $DOUBLEMAPMBS, R5
_ptrdbl:
FILLPTE()
SUB.S $1, R5
BNE _ptrdbl
MOVW $PHYSDRAM, R0
MCR CpSC, 0, R0, C(CpTLB), C(CpTLBinvu), CpTLBinv
BARRIERS
/* turn the MMU off */
MOVW $PHYSDRAM, R0
BL _r15warp(SB)
BL mmuinvalidate(SB)
BL mmudisable(SB)
/* set new reset vector */
MOVW $HVECTORS, R2
MOVW $0xe59ff018, R3 /* MOVW 0x18(R15), R15 */
MOVW R3, (R2)
BARRIERS
// MOVW $PHYSFLASH, R3 /* TODO */
// MOVW R3, 0x20(R2) /* where $0xe59ff018 jumps to */
/* ...and jump to it */
// MOVW R2, R15 /* software reboot */
_limbo: /* should not get here... */
BL idlehands(SB)
B _limbo /* ... and can't get out */
BL _div(SB) /* hack to load _div, etc. */
TEXT _r15warp(SB), 1, $-4
BIC $KSEGM, R14 /* link reg, will become PC */
ORR R0, R14
BIC $KSEGM, R13 /* SP too */
ORR R0, R13
RET
/*
* `single-element' cache operations.
* in arm arch v7, they operate on all cache levels, so separate
* l2 functions are unnecessary.
*/
TEXT cachedwbse(SB), $-4 /* D writeback SE */
MOVW R0, R2
MOVW CPSR, R3
CPSID /* splhi */
BARRIERS /* force outstanding stores to cache */
MOVW R2, R0
MOVW 4(FP), R1
ADD R0, R1 /* R1 is end address */
BIC $(CACHELINESZ-1), R0 /* cache line start */
_dwbse:
MCR CpSC, 0, R0, C(CpCACHE), C(CpCACHEwb), CpCACHEse
/* can't have a BARRIER here since it zeroes R0 */
ADD $CACHELINESZ, R0
CMP.S R0, R1
BGT _dwbse
B _wait
TEXT cachedwbinvse(SB), $-4 /* D writeback+invalidate SE */
MOVW R0, R2
MOVW CPSR, R3
CPSID /* splhi */
BARRIERS /* force outstanding stores to cache */
MOVW R2, R0
MOVW 4(FP), R1
ADD R0, R1 /* R1 is end address */
BIC $(CACHELINESZ-1), R0 /* cache line start */
_dwbinvse:
MCR CpSC, 0, R0, C(CpCACHE), C(CpCACHEwbi), CpCACHEse
/* can't have a BARRIER here since it zeroes R0 */
ADD $CACHELINESZ, R0
CMP.S R0, R1
BGT _dwbinvse
_wait: /* drain write buffer */
BARRIERS
/* drain L1 write buffer, also drains L2 eviction buffer on sheeva */
MCR CpSC, 0, R0, C(CpCACHE), C(CpCACHEwb), CpCACHEwait
ISB
MOVW R3, CPSR /* splx */
RET
TEXT cachedinvse(SB), $-4 /* D invalidate SE */
MOVW R0, R2
MOVW CPSR, R3
CPSID /* splhi */
BARRIERS /* force outstanding stores to cache */
MOVW R2, R0
MOVW 4(FP), R1
ADD R0, R1 /* R1 is end address */
BIC $(CACHELINESZ-1), R0 /* cache line start */
_dinvse:
MCR CpSC, 0, R0, C(CpCACHE), C(CpCACHEinvd), CpCACHEse
/* can't have a BARRIER here since it zeroes R0 */
ADD $CACHELINESZ, R0
CMP.S R0, R1
BGT _dinvse
B _wait
/*
* enable mmu and high vectors
*/
TEXT mmuenable(SB), 1, $-4
MRC CpSC, 0, R0, C(CpCONTROL), C(0), CpMainctl
ORR $(CpChv|CpCmmu), R0
MCR CpSC, 0, R0, C(CpCONTROL), C(0), CpMainctl
BARRIERS
RET
TEXT mmudisable(SB), 1, $-4
MRC CpSC, 0, R0, C(CpCONTROL), C(0), CpMainctl
BIC $(CpChv|CpCmmu), R0
MCR CpSC, 0, R0, C(CpCONTROL), C(0), CpMainctl
BARRIERS
RET
/*
* If one of these MCR instructions crashes or hangs the machine,
* check your Level 1 page table (at TTB) closely.
*/
TEXT mmuinvalidate(SB), $-4 /* invalidate all */
MOVW CPSR, R2
CPSID /* interrupts off */
BARRIERS
MOVW PC, R0 /* some valid virtual address */
MCR CpSC, 0, R0, C(CpTLB), C(CpTLBinvu), CpTLBinv
BARRIERS
MOVW R2, CPSR /* interrupts restored */
RET
TEXT mmuinvalidateaddr(SB), $-4 /* invalidate single entry */
MCR CpSC, 0, R0, C(CpTLB), C(CpTLBinvu), CpTLBinvse
BARRIERS
RET
TEXT cpidget(SB), 1, $-4 /* main ID */
MRC CpSC, 0, R0, C(CpID), C(0), CpIDid
RET
TEXT cpctget(SB), 1, $-4 /* cache type */
MRC CpSC, 0, R0, C(CpID), C(0), CpIDct
RET
TEXT controlget(SB), 1, $-4 /* control */
MRC CpSC, 0, R0, C(CpCONTROL), C(0), CpMainctl
RET
TEXT ttbget(SB), 1, $-4 /* translation table base */
MRC CpSC, 0, R0, C(CpTTB), C(0), CpTTB0
RET
TEXT ttbput(SB), 1, $-4 /* translation table base */
MCR CpSC, 0, R0, C(CpTTB), C(0), CpTTB0
MCR CpSC, 0, R0, C(CpTTB), C(0), CpTTB1 /* cortex has two */
ISB
RET
TEXT dacget(SB), 1, $-4 /* domain access control */
MRC CpSC, 0, R0, C(CpDAC), C(0)
RET
TEXT dacput(SB), 1, $-4 /* domain access control */
MCR CpSC, 0, R0, C(CpDAC), C(0)
ISB
RET
TEXT fsrget(SB), 1, $-4 /* data fault status */
MRC CpSC, 0, R0, C(CpFSR), C(0), CpDFSR
RET
TEXT ifsrget(SB), 1, $-4 /* instruction fault status */
MRC CpSC, 0, R0, C(CpFSR), C(0), CpIFSR
RET
TEXT farget(SB), 1, $-4 /* fault address */
MRC CpSC, 0, R0, C(CpFAR), C(0x0)
RET
TEXT getpsr(SB), 1, $-4
MOVW CPSR, R0
RET
TEXT getscr(SB), 1, $-4
MRC CpSC, 0, R0, C(CpCONTROL), C(CpCONTROLscr), CpSCRscr
RET
TEXT pidget(SB), 1, $-4 /* address translation pid */
MRC CpSC, 0, R0, C(CpPID), C(0x0)
RET
TEXT pidput(SB), 1, $-4 /* address translation pid */
MCR CpSC, 0, R0, C(CpPID), C(0x0)
ISB
RET
TEXT splhi(SB), 1, $-4
MOVW CPSR, R0
CPSID /* turn off interrupts */
MOVW $(MACHADDR+4), R2 /* save caller pc in Mach */
MOVW R14, 0(R2)
RET
TEXT spllo(SB), 1, $-4 /* start marker for devkprof.c */
MOVW CPSR, R0
CPSIE
RET
TEXT splx(SB), 1, $-4
MOVW $(MACHADDR+0x04), R2 /* save caller pc in Mach */
MOVW R14, 0(R2)
MOVW CPSR, R3
MOVW R0, CPSR /* reset interrupt level */
MOVW R3, R0 /* must return old CPSR */
RET
TEXT spldone(SB), 1, $0 /* end marker for devkprof.c */
RET
TEXT islo(SB), 1, $-4
MOVW CPSR, R0
AND $(PsrDirq), R0
EOR $(PsrDirq), R0
RET
TEXT tas(SB), $-4
TEXT _tas(SB), $-4
MOVW R0,R1
MOVW $1,R0
SWPW R0,(R1) /* fix: deprecated in armv7 */
RET
TEXT clz(SB), $-4
CLZ(0, 0) /* 0 is R0 */
RET
TEXT setlabel(SB), 1, $-4
MOVW R13, 0(R0) /* sp */
MOVW R14, 4(R0) /* pc */
MOVW $0, R0
RET
TEXT gotolabel(SB), 1, $-4
MOVW 0(R0), R13 /* sp */
MOVW 4(R0), R14 /* pc */
MOVW $1, R0
RET
TEXT getcallerpc(SB), 1, $-4
MOVW 0(R13), R0
RET
TEXT idlehands(SB), $-4
BARRIERS
WFI
RET
TEXT coherence(SB), $-4
BARRIERS
RET
#include "cache.v7.s"
|
9front/9front
| 4,898
|
sys/src/9/omap/cache.v7.s
|
/*
* cortex arm arch v7 cache flushing and invalidation
* shared by l.s and rebootcode.s
*/
TEXT cacheiinv(SB), $-4 /* I invalidate */
MOVW $0, R0
MCR CpSC, 0, R0, C(CpCACHE), C(CpCACHEinvi), CpCACHEall /* ok on cortex */
ISB
RET
/*
* set/way operators, passed a suitable set/way value in R0.
*/
TEXT cachedwb_sw(SB), $-4
MCR CpSC, 0, R0, C(CpCACHE), C(CpCACHEwb), CpCACHEsi
RET
TEXT cachedwbinv_sw(SB), $-4
MCR CpSC, 0, R0, C(CpCACHE), C(CpCACHEwbi), CpCACHEsi
RET
TEXT cachedinv_sw(SB), $-4
MCR CpSC, 0, R0, C(CpCACHE), C(CpCACHEinvd), CpCACHEsi
RET
/* set cache size select */
TEXT setcachelvl(SB), $-4
MCR CpSC, CpIDcssel, R0, C(CpID), C(CpIDid), 0
ISB
RET
/* return cache sizes */
TEXT getwayssets(SB), $-4
MRC CpSC, CpIDcsize, R0, C(CpID), C(CpIDid), 0
RET
/*
* l1 cache operations.
* l1 and l2 ops are intended to be called from C, thus need save no
* caller's regs, only those we need to preserve across calls.
*/
TEXT cachedwb(SB), $-4
MOVW.W R14, -8(R13)
MOVW $cachedwb_sw(SB), R0
MOVW $1, R8
BL wholecache(SB)
MOVW.P 8(R13), R15
TEXT cachedwbinv(SB), $-4
MOVW.W R14, -8(R13)
MOVW $cachedwbinv_sw(SB), R0
MOVW $1, R8
BL wholecache(SB)
MOVW.P 8(R13), R15
TEXT cachedinv(SB), $-4
MOVW.W R14, -8(R13)
MOVW $cachedinv_sw(SB), R0
MOVW $1, R8
BL wholecache(SB)
MOVW.P 8(R13), R15
TEXT cacheuwbinv(SB), $-4
MOVM.DB.W [R14], (R13) /* save lr on stack */
MOVW CPSR, R1
CPSID /* splhi */
MOVM.DB.W [R1], (R13) /* save R1 on stack */
BL cachedwbinv(SB)
BL cacheiinv(SB)
MOVM.IA.W (R13), [R1] /* restore R1 (saved CPSR) */
MOVW R1, CPSR
MOVM.IA.W (R13), [R14] /* restore lr */
RET
/*
* l2 cache operations
*/
TEXT l2cacheuwb(SB), $-4
MOVW.W R14, -8(R13)
MOVW $cachedwb_sw(SB), R0
MOVW $2, R8
BL wholecache(SB)
MOVW.P 8(R13), R15
TEXT l2cacheuwbinv(SB), $-4
MOVW.W R14, -8(R13)
MOVW CPSR, R1
CPSID /* splhi */
MOVM.DB.W [R1], (R13) /* save R1 on stack */
MOVW $cachedwbinv_sw(SB), R0
MOVW $2, R8
BL wholecache(SB)
BL l2cacheuinv(SB)
MOVM.IA.W (R13), [R1] /* restore R1 (saved CPSR) */
MOVW R1, CPSR
MOVW.P 8(R13), R15
TEXT l2cacheuinv(SB), $-4
MOVW.W R14, -8(R13)
MOVW $cachedinv_sw(SB), R0
MOVW $2, R8
BL wholecache(SB)
MOVW.P 8(R13), R15
/*
* these shift values are for the Cortex-A8 L1 cache (A=2, L=6) and
* the Cortex-A8 L2 cache (A=3, L=6).
* A = log2(# of ways), L = log2(bytes per cache line).
* see armv7 arch ref p. 1403.
*/
#define L1WAYSH 30
#define L1SETSH 6
#define L2WAYSH 29
#define L2SETSH 6
/*
* callers are assumed to be the above l1 and l2 ops.
* R0 is the function to call in the innermost loop.
* R8 is the cache level (one-origin: 1 or 2).
*
* initial translation by 5c, then massaged by hand.
*/
TEXT wholecache+0(SB), $-4
MOVW R0, R1 /* save argument for inner loop in R1 */
SUB $1, R8 /* convert cache level to zero origin */
/* we may not have the MMU on yet, so map R1 to PC's space */
BIC $KSEGM, R1 /* strip segment from address */
MOVW PC, R2 /* get PC's segment ... */
AND $KSEGM, R2
CMP $0, R2 /* PC segment should be non-zero on omap */
BEQ buggery
ORR R2, R1 /* combine them */
/* drain write buffers */
BARRIERS
MCR CpSC, 0, R0, C(CpCACHE), C(CpCACHEwb), CpCACHEwait
ISB
MOVW CPSR, R2
MOVM.DB.W [R2,R14], (SP) /* save regs on stack */
CPSID /* splhi to make entire op atomic */
/* get cache sizes */
SLL $1, R8, R0 /* R0 = (cache - 1) << 1 */
MCR CpSC, CpIDcssel, R0, C(CpID), C(CpIDid), 0 /* set cache size select */
ISB
MRC CpSC, CpIDcsize, R0, C(CpID), C(CpIDid), 0 /* get cache sizes */
/* compute # of ways and sets for this cache level */
SRA $3, R0, R5 /* R5 (ways) = R0 >> 3 */
AND $1023, R5 /* R5 = (R0 >> 3) & MASK(10) */
ADD $1, R5 /* R5 (ways) = ((R0 >> 3) & MASK(10)) + 1 */
SRA $13, R0, R2 /* R2 = R0 >> 13 */
AND $32767, R2 /* R2 = (R0 >> 13) & MASK(15) */
ADD $1, R2 /* R2 (sets) = ((R0 >> 13) & MASK(15)) + 1 */
/* precompute set/way shifts for inner loop */
CMP $0, R8 /* cache == 1? */
MOVW.EQ $L1WAYSH, R3 /* yes */
MOVW.EQ $L1SETSH, R4
MOVW.NE $L2WAYSH, R3 /* no */
MOVW.NE $L2SETSH, R4
/* iterate over ways */
MOVW $0, R7 /* R7: way */
outer:
/* iterate over sets */
MOVW $0, R6 /* R6: set */
inner:
/* compute set/way register contents */
SLL R3, R7, R0 /* R0 = way << R3 (L?WAYSH) */
ORR R8<<1, R0 /* R0 = way << L?WAYSH | (cache - 1) << 1 */
ORR R6<<R4, R0 /* R0 = way<<L?WAYSH | (cache-1)<<1 |set<<R4 */
BL (R1) /* call set/way operation with R0 */
ADD $1, R6 /* set++ */
CMP R2, R6 /* set >= sets? */
BLT inner /* no, do next set */
ADD $1, R7 /* way++ */
CMP R5, R7 /* way >= ways? */
BLT outer /* no, do next way */
MOVM.IA.W (SP), [R2,R14] /* restore regs */
MOVW R2, CPSR /* splx */
/* drain write buffers */
MCR CpSC, 0, R0, C(CpCACHE), C(CpCACHEwb), CpCACHEwait
ISB
RET
buggery:
WAVE('?')
MOVW PC, R0
// B pczeroseg(SB)
RET
|
9front/9front
| 1,298
|
sys/src/9/omap/lproc.s
|
#include "mem.h"
#include "arm.h"
/*
* This is the first jump from kernel to user mode.
* Fake a return from interrupt.
*
* Enter with R0 containing the user stack pointer.
* UTZERO + 0x20 is always the entry point.
*
*/
TEXT touser(SB), 1, $-4
/* store the user stack pointer into the USR_r13 */
MOVM.DB.W [R0], (R13)
/* avoid the ambiguity described in notes/movm.w. */
// MOVM.S.IA.W (R13), [R13]
MOVM.S (R13), [R13]
ADD $4, R13
/* set up a PSR for user level */
MOVW $(PsrMusr), R0
MOVW R0, SPSR
/* save the PC on the stack */
MOVW $(UTZERO+0x20), R0
MOVM.DB.W [R0], (R13)
/*
* note that 5a's RFE is not the v6 arch. instruction (0xe89d0a00,
* I think), which loads CPSR from the word after the PC at (R13),
* but rather the pre-v6 simulation `MOVM.IA.S.W (R13), [R15]'
* (0xe8fd8000 since MOVM is LDM in this case), which loads CPSR
* not from memory but from SPSR due to `.S'.
*/
RFE
/*
* here to jump to a newly forked process
*/
TEXT forkret(SB), 1, $-4
ADD $(4*15), R13 /* make r13 point to ureg->type */
MOVW 8(R13), R14 /* restore link */
MOVW 4(R13), R0 /* restore SPSR */
MOVW R0, SPSR /* ... */
MOVM.DB.S (R13), [R0-R14] /* restore registers */
ADD $8, R13 /* pop past ureg->{type+psr} */
RFE /* MOVM.IA.S.W (R13), [R15] */
|
9front/9front
| 2,628
|
sys/src/9/omap/arm.s
|
/*
* omap3530 machine assist, definitions
* cortex-a8 processor
*
* loader uses R11 as scratch.
*/
#include "mem.h"
#include "arm.h"
#undef B /* B is for 'botch' */
#define KADDR(pa) (KZERO | ((pa) & ~KSEGM))
#define PADDR(va) (PHYSDRAM | ((va) & ~KSEGM))
#define L1X(va) (((((va))>>20) & 0x0fff)<<2)
#define MACHADDR (L1-MACHSIZE)
#define PTEDRAM (Dom0|L1AP(Krw)|Section|Cached|Buffered)
#define PTEIO (Dom0|L1AP(Krw)|Section)
#define DOUBLEMAPMBS 256 /* megabytes of low dram to double-map */
/* steps on R0 */
#define DELAY(label, mloops) \
MOVW $((mloops)*1000000), R0; \
label: \
SUB.S $1, R0; \
BNE label
/* wave at the user; clobbers R0, R1 & R6; needs R12 (SB) set */
#define WAVE(c) \
BARRIERS; \
MOVW $(c), R1; \
MOVW $PHYSCONS, R6; \
MOVW R1, (R6); \
BARRIERS
/*
* new instructions
*/
#define SMC WORD $0xe1600070 /* low 4-bits are call # (trustzone) */
/* flush branch-target cache; zeroes R0 (cortex) */
#define FLBTC \
MOVW $0, R0; \
MCR CpSC, 0, R0, C(CpCACHE), C(CpCACHEinvi), CpCACHEflushbtc
/* flush one entry of the branch-target cache, va in R0 (cortex) */
#define FLBTSE \
MCR CpSC, 0, R0, C(CpCACHE), C(CpCACHEinvi), CpCACHEflushbtse
/* arm v7 arch defines these */
#define WFI WORD $0xe320f003 /* wait for interrupt */
#define DMB WORD $0xf57ff05f /* data mem. barrier; last f = SY */
#define DSB WORD $0xf57ff04f /* data synch. barrier; last f = SY */
#define ISB WORD $0xf57ff06f /* instr. sync. barrier; last f = SY */
#define NOOP WORD $0xe320f000
#define CLZ(s, d) WORD $(0xe16f0f10 | (d) << 12 | (s)) /* count leading 0s */
#define CPSIE WORD $0xf1080080 /* intr enable: zeroes I bit */
#define CPSID WORD $0xf10c0080 /* intr disable: sets I bit */
/* floating point */
#define VMRS(fp, cpu) WORD $(0xeef00a10 | (fp)<<16 | (cpu)<<12) /* FP → arm */
#define VMSR(cpu, fp) WORD $(0xeee00a10 | (fp)<<16 | (cpu)<<12) /* arm → FP */
/*
* a popular code sequence used to write a pte for va is:
*
* MOVW R(n), TTB[LnX(va)]
* // clean the cache line
* DSB
* // invalidate tlb entry for va
* FLBTC
* DSB
* PFF (now ISB)
*/
/* zeroes R0 */
#define BARRIERS FLBTC; DSB; ISB
/*
* invoked with PTE bits in R2, pa in R3, PTE pointed to by R4.
* fill PTE pointed to by R4 and increment R4 past it.
* increment R3 by a MB. clobbers R1.
*/
#define FILLPTE() \
ORR R3, R2, R1; /* pte bits in R2, pa in R3 */ \
MOVW R1, (R4); \
ADD $4, R4; /* bump PTE address */ \
ADD $MiB, R3; /* bump pa */ \
/* zero PTE pointed to by R4 and increment R4 past it. assumes R0 is 0. */
#define ZEROPTE() \
MOVW R0, (R4); \
ADD $4, R4; /* bump PTE address */
|
9front/9front
| 5,909
|
sys/src/9/omap/lexception.s
|
/*
* arm exception handlers
*/
#include "arm.s"
#undef B /* B is for 'botch' */
/*
* exception vectors, copied by trapinit() to somewhere useful
*/
TEXT vectors(SB), 1, $-4
MOVW 0x18(R15), R15 /* reset */
MOVW 0x18(R15), R15 /* undefined instr. */
MOVW 0x18(R15), R15 /* SWI & SMC */
MOVW 0x18(R15), R15 /* prefetch abort */
MOVW 0x18(R15), R15 /* data abort */
MOVW 0x18(R15), R15 /* reserved */
MOVW 0x18(R15), R15 /* IRQ */
MOVW 0x18(R15), R15 /* FIQ */
TEXT vtable(SB), 1, $-4
WORD $_vsvc(SB) /* reset, in svc mode already */
WORD $_vund(SB) /* undefined, switch to svc mode */
WORD $_vsvc(SB) /* swi, in svc mode already */
WORD $_vpabt(SB) /* prefetch abort, switch to svc mode */
WORD $_vdabt(SB) /* data abort, switch to svc mode */
WORD $_vsvc(SB) /* reserved */
WORD $_virq(SB) /* IRQ, switch to svc mode */
// WORD $_vfiq(SB) /* FIQ, switch to svc mode */
WORD $_virq(SB) /* FIQ, switch to svc mode */
TEXT _vrst(SB), 1, $-4
BL _reset(SB)
TEXT _vsvc(SB), 1, $-4 /* SWI */
MOVW.W R14, -4(R13) /* ureg->pc = interrupted PC */
MOVW SPSR, R14 /* ureg->psr = SPSR */
MOVW.W R14, -4(R13) /* ... */
MOVW $PsrMsvc, R14 /* ureg->type = PsrMsvc */
MOVW.W R14, -4(R13) /* ... */
/* avoid the ambiguity described in notes/movm.w. */
// MOVM.DB.W.S [R0-R14], (R13) /* save user level registers, at end r13 points to ureg */
MOVM.DB.S [R0-R14], (R13) /* save user level registers */
SUB $(15*4), R13 /* r13 now points to ureg */
MOVW $setR12(SB), R12 /* Make sure we've got the kernel's SB loaded */
// MOVW $(KSEG0+16*KiB-MACHSIZE), R10 /* m */
MOVW $(L1-MACHSIZE), R10 /* m */
MOVW 8(R10), R9 /* up */
MOVW R13, R0 /* first arg is pointer to ureg */
SUB $8, R13 /* space for argument+link */
BL syscall(SB)
ADD $(8+4*15), R13 /* make r13 point to ureg->type */
MOVW 8(R13), R14 /* restore link */
MOVW 4(R13), R0 /* restore SPSR */
MOVW R0, SPSR /* ... */
MOVM.DB.S (R13), [R0-R14] /* restore registers */
ADD $8, R13 /* pop past ureg->{type+psr} */
RFE /* MOVM.IA.S.W (R13), [R15] */
TEXT _vund(SB), 1, $-4 /* undefined */
MOVM.IA [R0-R4], (R13) /* free some working space */
MOVW $PsrMund, R0
B _vswitch
TEXT _vpabt(SB), 1, $-4 /* prefetch abort */
MOVM.IA [R0-R4], (R13) /* free some working space */
MOVW $PsrMabt, R0 /* r0 = type */
B _vswitch
TEXT _vdabt(SB), 1, $-4 /* data abort */
MOVM.IA [R0-R4], (R13) /* free some working space */
MOVW $(PsrMabt+1), R0 /* r0 = type */
B _vswitch
TEXT _virq(SB), 1, $-4 /* IRQ */
MOVM.IA [R0-R4], (R13) /* free some working space */
MOVW $PsrMirq, R0 /* r0 = type */
B _vswitch
/*
* come here with type in R0 and R13 pointing above saved [r0-r4].
* we'll switch to SVC mode and then call trap.
*/
_vswitch:
MOVW SPSR, R1 /* save SPSR for ureg */
MOVW R14, R2 /* save interrupted pc for ureg */
MOVW R13, R3 /* save pointer to where the original [R0-R4] are */
/*
* switch processor to svc mode. this switches the banked registers
* (r13 [sp] and r14 [link]) to those of svc mode.
*/
MOVW CPSR, R14
BIC $PsrMask, R14
ORR $(PsrDirq|PsrDfiq|PsrMsvc), R14
MOVW R14, CPSR /* switch! */
AND.S $0xf, R1, R4 /* interrupted code kernel or user? */
BEQ _userexcep
/* here for trap from SVC mode */
MOVM.DB.W [R0-R2], (R13) /* set ureg->{type, psr, pc}; r13 points to ureg->type */
MOVM.IA (R3), [R0-R4] /* restore [R0-R4] from previous mode's stack */
/*
* avoid the ambiguity described in notes/movm.w.
* In order to get a predictable value in R13 after the stores,
* separate the store-multiple from the stack-pointer adjustment.
* We'll assume that the old value of R13 should be stored on the stack.
*/
/* save kernel level registers, at end r13 points to ureg */
// MOVM.DB.W [R0-R14], (R13)
MOVM.DB [R0-R14], (R13)
SUB $(15*4), R13 /* SP now points to saved R0 */
MOVW $setR12(SB), R12 /* Make sure we've got the kernel's SB loaded */
MOVW R13, R0 /* first arg is pointer to ureg */
SUB $(4*2), R13 /* space for argument+link (for debugger) */
MOVW $0xdeaddead, R11 /* marker */
BL trap(SB)
ADD $(4*2+4*15), R13 /* make r13 point to ureg->type */
MOVW 8(R13), R14 /* restore link */
MOVW 4(R13), R0 /* restore SPSR */
MOVW R0, SPSR /* ... */
MOVM.DB (R13), [R0-R14] /* restore registers */
ADD $(4*2), R13 /* pop past ureg->{type+psr} to pc */
RFE /* MOVM.IA.S.W (R13), [R15] */
/* here for trap from USER mode */
_userexcep:
MOVM.DB.W [R0-R2], (R13) /* set ureg->{type, psr, pc}; r13 points to ureg->type */
MOVM.IA (R3), [R0-R4] /* restore [R0-R4] from previous mode's stack */
/* avoid the ambiguity described in notes/movm.w. */
// MOVM.DB.W.S [R0-R14], (R13) /* save kernel level registers, at end r13 points to ureg */
MOVM.DB.S [R0-R14], (R13) /* save kernel level registers */
SUB $(15*4), R13 /* r13 now points to ureg */
MOVW $setR12(SB), R12 /* Make sure we've got the kernel's SB loaded */
// MOVW $(KSEG0+16*KiB-MACHSIZE), R10 /* m */
MOVW $(L1-MACHSIZE), R10 /* m */
MOVW 8(R10), R9 /* up */
MOVW R13, R0 /* first arg is pointer to ureg */
SUB $(4*2), R13 /* space for argument+link (for debugger) */
BL trap(SB)
ADD $(4*2+4*15), R13 /* make r13 point to ureg->type */
MOVW 8(R13), R14 /* restore link */
MOVW 4(R13), R0 /* restore SPSR */
MOVW R0, SPSR /* ... */
MOVM.DB.S (R13), [R0-R14] /* restore registers */
ADD $(4*2), R13 /* pop past ureg->{type+psr} */
RFE /* MOVM.IA.S.W (R13), [R15] */
TEXT _vfiq(SB), 1, $-4 /* FIQ */
RFE /* FIQ is special, ignore it for now */
/*
* set the stack value for the mode passed in R0
*/
TEXT setr13(SB), 1, $-4
MOVW 4(FP), R1
MOVW CPSR, R2
BIC $PsrMask, R2, R3
ORR R0, R3
MOVW R3, CPSR /* switch to new mode */
MOVW R13, R0 /* return old sp */
MOVW R1, R13 /* install new one */
MOVW R2, CPSR /* switch back to old mode */
RET
|
9front/9front
| 4,859
|
sys/src/9/omap/rebootcode.s
|
/*
* omap3530 reboot code
*
* must fit in 11K to avoid stepping on PTEs; see mem.h.
*
* R11 is used by the loader as a temporary, so avoid it.
*/
#include "arm.s"
/*
* Turn off MMU, then copy the new kernel to its correct location
* in physical memory. Then jump to the start of the kernel.
*/
/* main(PADDR(entry), PADDR(code), size); */
TEXT main(SB), 1, $-4
MOVW $setR12(SB), R12
MOVW R0, p1+0(FP) /* destination, passed in R0 */
MOVW CPSR, R0
ORR $(PsrDirq|PsrDfiq), R0
MOVW R0, CPSR /* splhi */
BARRIERS
WAVE('R')
MRC CpSC, 0, R1, C(CpCONTROL), C(0), CpAuxctl
BIC $CpACasa, R1 /* no speculative I access forwarding to mem */
/* slow down */
ORR $(CpACcachenopipe|CpACcp15serial|CpACcp15waitidle|CpACcp15pipeflush), R1
MCR CpSC, 0, R1, C(CpCONTROL), C(0), CpAuxctl
BARRIERS
BL cachesoff(SB)
/* now back in 29- or 26-bit addressing, mainly for SB */
/* double mapping of PHYSDRAM & KZERO now in effect */
/*
* turn the MMU off
*/
WAVE('e')
/* first switch to PHYSDRAM-based addresses */
DMB
MOVW $KSEGM, R7 /* clear segment bits */
MOVW $PHYSDRAM, R0 /* set dram base bits */
BIC R7, R12 /* adjust SB */
ORR R0, R12
BL _r15warp(SB)
/* don't care about saving R14; we're not returning */
/*
* now running in PHYSDRAM segment, not KZERO.
*/
WAVE('b')
SUB $12, SP /* paranoia */
BL cacheuwbinv(SB)
ADD $12, SP /* paranoia */
/* invalidate mmu mappings */
MOVW $KZERO, R0 /* some valid virtual address */
MCR CpSC, 0, R0, C(CpTLB), C(CpTLBinvu), CpTLBinv
BARRIERS
WAVE('o')
MRC CpSC, 0, R0, C(CpCONTROL), C(0)
BIC $(CpCmmu|CpCdcache|CpCicache), R0
MCR CpSC, 0, R0, C(CpCONTROL), C(0) /* mmu off */
BARRIERS
WAVE('o')
/* copy in arguments from stack frame before moving stack */
MOVW p2+4(FP), R4 /* phys source */
MOVW n+8(FP), R5 /* byte count */
MOVW p1+0(FP), R6 /* phys destination */
/* set up a new stack for local vars and memmove args */
MOVW R6, SP /* tiny trampoline stack */
SUB $(0x20 + 4), SP /* back up before a.out header */
// MOVW R14, -48(SP) /* store return addr */
SUB $48, SP /* allocate stack frame */
MOVW R5, 40(SP) /* save count */
MOVW R6, 44(SP) /* save dest/entry */
DELAY(printloop2, 2)
WAVE('t')
MOVW 40(SP), R5 /* restore count */
MOVW 44(SP), R6 /* restore dest/entry */
MOVW R6, 0(SP) /* normally saved LR goes here */
MOVW R6, 4(SP) /* push dest */
MOVW R6, R0
MOVW R4, 8(SP) /* push src */
MOVW R5, 12(SP) /* push size */
BL memmove(SB)
WAVE('-')
/*
* flush caches
*/
BL cacheuwbinv(SB)
WAVE('>')
DELAY(printloopret, 1)
WAVE('\r')
DELAY(printloopnl, 1)
WAVE('\n')
/*
* jump to kernel entry point. Note the true kernel entry point is
* the virtual address KZERO|R6, but this must wait until
* the MMU is enabled by the kernel in l.s
*/
MOVW 44(SP), R6 /* restore R6 (dest/entry) */
ORR R6, R6 /* NOP: avoid link bug */
B (R6)
WAVE('?')
B 0(PC)
/*
* turn the caches off, double map PHYSDRAM & KZERO, invalidate TLBs, revert
* to tiny addresses. upon return, it will be safe to turn off the mmu.
*/
TEXT cachesoff(SB), 1, $-4
MOVM.DB.W [R14,R1-R10], (R13) /* save regs on stack */
MOVW CPSR, R0
ORR $(PsrDirq|PsrDfiq), R0
MOVW R0, CPSR
BARRIERS
SUB $12, SP /* paranoia */
BL cacheuwbinv(SB)
ADD $12, SP /* paranoia */
MRC CpSC, 0, R0, C(CpCONTROL), C(0)
BIC $(CpCicache|CpCdcache), R0
MCR CpSC, 0, R0, C(CpCONTROL), C(0) /* caches off */
BARRIERS
/*
* caches are off
*/
/* invalidate stale TLBs before changing them */
MOVW $KZERO, R0 /* some valid virtual address */
MCR CpSC, 0, R0, C(CpTLB), C(CpTLBinvu), CpTLBinv
BARRIERS
/* redo double map of PHYSDRAM, KZERO */
MOVW $PHYSDRAM, R3
CMP $KZERO, R3
BEQ noun2map
MOVW $(L1+L1X(PHYSDRAM)), R4 /* address of PHYSDRAM's PTE */
MOVW $PTEDRAM, R2 /* PTE bits */
MOVW $DOUBLEMAPMBS, R5
_ptrdbl:
ORR R3, R2, R1 /* first identity-map 0 to 0, etc. */
MOVW R1, (R4)
ADD $4, R4 /* bump PTE address */
ADD $MiB, R3 /* bump pa */
SUB.S $1, R5
BNE _ptrdbl
noun2map:
/*
* flush stale TLB entries
*/
BARRIERS
MOVW $KZERO, R0 /* some valid virtual address */
MCR CpSC, 0, R0, C(CpTLB), C(CpTLBinvu), CpTLBinv
BARRIERS
/* switch back to PHYSDRAM addressing, mainly for SB */
MOVW $KSEGM, R7 /* clear segment bits */
MOVW $PHYSDRAM, R0 /* set dram base bits */
BIC R7, R12 /* adjust SB */
ORR R0, R12
BIC R7, SP
ORR R0, SP
MOVM.IA.W (R13), [R14,R1-R10] /* restore regs from stack */
MOVW $KSEGM, R0 /* clear segment bits */
BIC R0, R14 /* adjust link */
MOVW $PHYSDRAM, R0 /* set dram base bits */
ORR R0, R14
RET
TEXT _r15warp(SB), 1, $-4
BIC R7, R14 /* link */
ORR R0, R14
BIC R7, R13 /* SP */
ORR R0, R13
RET
TEXT panic(SB), 1, $-4 /* stub */
WAVE('?')
RET
TEXT pczeroseg(SB), 1, $-4 /* stub */
RET
#include "cache.v7.s"
|
9front/9front
| 7,822
|
sys/src/9/zynq/l.s
|
#include "mem.h"
#include "io.h"
#define PUTC(c) MOVW $(c), R0; MOVW R0, (R8)
TEXT _start(SB), $-4
MOVW $(KTZERO-KZERO), R13
MOVW $0xE0001030, R8
PUTC('P')
MOVW $0, R0
MOVW R0, R1
MOVW $(CONFADDR-KZERO), R2
_start0:
MOVW.P R0, 4(R1)
CMP.S R1, R2
BNE _start0
PUTC('l')
MOVW $SECSZ, R0
MOVW $(MACHL1(0)-KZERO), R4
MOVW $KZERO, R1
ADD R1>>(SECSH-2), R4, R1
MOVW $(L1SEC|L1CACHED|L1KERRW), R2
MOVW $(-KZERO), R3
_start1:
MOVW.P R2, 4(R1)
ADD R0, R2
CMP.S R2, R3
BGE _start1
PUTC('a')
MOVW $L2SZ, R0
MOVW $VMAP, R1
ADD R1>>(SECSH-2), R4, R1
MOVW $((VMAPL2-KZERO)|L1PT), R2
MOVW $(VMAPL2-KZERO+VMAPL2SZ), R3
_start2:
MOVW.P R2, 4(R1)
ADD R0, R2
CMP.S R2, R3
BGE _start2
MOVW $(UART_BASE|L2VALID|L2DEVICE|L2NOEXEC|L2KERRW), R0
MOVW $(VMAPL2-KZERO), R1
MOVW R0, (R1)
PUTC('n')
MOVW $(MACH(0)-KZERO), R(Rmach)
_start3:
/* enable MMU permission checking */
MOVW $0x55555555, R0
MCR 15, 0, R0, C(3), C(0), 0
MOVW $0, R0
MCR 15, 0, R0, C(8), C(7), 0
DSB
ORR $TTBATTR, R4, R1
MCR 15, 0, R1, C(2), C(0), 0
MOVW $0x20c5047b, R1
MOVW $_virt(SB), R2
PUTC(' ')
MCR 15, 0, R1, C(1), C(0), 0
MOVW R2, R15
TEXT _virt(SB), $-4
DSB
ISB
ADD $KZERO, R(Rmach)
MOVW R(Rmach), R13
ADD $MACHSIZE, R13
MOVW R(Rmach), R0
ADD $12, R0
BL loadsp(SB)
MOVW $vectors(SB), R1
MCR 15, 0, R1, C(12), C(0)
/* enable maths coprocessors in CPACR but disable them in FPEXC */
MRC 15, 0, R0, C(1), C(0), 2
ORR $(15<<20), R0
MCR 15, 0, R0, C(1), C(0), 2
VMRS(0xe, FPEXC, 0)
BIC $(3<<30), R0
VMSR(0xe, 0, FPEXC)
/* enable L1 cache */
MOVW $0, R0
MCR 15, 0, R0, C(7), C(5), 0
MCR 15, 0, R0, C(7), C(5), 6
BL l1dclear(SB)
MRC 15, 0, R0, C(1), C(0), 1
ORR $(1|2|1<<6), R0
MCR 15, 0, R0, C(1), C(0), 1
MRC 15, 0, R0, C(1), C(0), 0
ORR $(3<<11|1<<2), R0
MCR 15, 0, R0, C(1), C(0), 0
DSB
ISB
MOVW $(VMAP+0x30), R8
PUTC('9')
/* kernel Mach* in TPIDRPRW */
MCR 15, 0, R(Rmach), C(13), C(0), 4
MOVW $setR12(SB), R12
MOVW $0, R(Rup)
BL main(SB)
B idlehands(SB)
BL _div(SB) /* hack to load _div */
TEXT mpbootstrap(SB), $-4
MOVW $0xE0001030, R8
PUTC('M')
PUTC('P')
MOVW $(MACH(1)-KZERO), R(Rmach)
MOVW $(MACHL1(1)-KZERO), R4
B _start3
TEXT touser(SB), $-4
CPS(CPSID)
SUB $12, R13
MOVW R0, (R13)
MOVW $0, R1
MOVW R1, 4(R13)
MOVW $(UTZERO+0x20), R1
MOVW R1, 8(R13)
MOVW CPSR, R1
BIC $(PsrMask|PsrDirq|PsrDfiq), R1
ORR $PsrMusr, R1
MOVW R1, SPSR
MOVW $(KTZERO-(15*4)), R0
MOVM.IA (R0), [R0-R12]
MOVM.IA.S (R13), [R13-R14]
ADD $8, R13
MOVM.IA.W.S (R13), [R15]
TEXT forkret(SB), $-4
MOVW (16*4)(R13), R0
MOVW R0, SPSR
MOVM.IA.W (R13), [R0-R12]
MOVM.IA.S (R13), [R13-R14]
ADD $16, R13
DSB
ISB
MOVM.IA.W.S (R13), [R15]
TEXT nope(SB), $-4 // NOPE
MOVW $(VMAP+0x30), R8
PUTC(13)
PUTC(10)
MOVW R14, R7
BL puthex(SB)
PUTC(' ')
PUTC('N')
PUTC('O')
PUTC('P')
PUTC('E')
_nope: B _nope
TEXT loadsp(SB), $0
CPS(CPSMODE | PsrMabt)
MOVW R0, R13
CPS(CPSMODE | PsrMund)
MOVW R0, R13
CPS(CPSMODE | PsrMirq)
MOVW R0, R13
CPS(CPSMODE | PsrMfiq)
MOVW R0, R13
CPS(CPSMODE | PsrMsvc)
RET
TEXT cputhex(SB), $0
MOVW R0, R7
MOVW $(VMAP+0x30), R8
TEXT puthex(SB), $0
_p0:
MOVW -4(R8), R6
AND.S $(1<<3), R6
BEQ _p0
#define DIG MOVW R7>>28, R6; AND $15, R6; ADD $'0', R6; CMP $'9', R6; ADD.GT $7, R6; MOVW R6, (R8); MOVW R7<<4, R7
DIG; DIG; DIG; DIG
DIG; DIG; DIG; DIG
MOVW $13, R6
MOVW R6, (R8)
MOVW $10, R6
MOVW R6, (R8)
RET
TEXT spllo(SB), $-4
MOVW CPSR, R0
CPS(CPSIE)
RET
TEXT splhi(SB), $-4
MOVW R14, 4(R(Rmach))
MOVW CPSR, R0
CPS(CPSID)
RET
TEXT splx(SB), $-4
MOVW R14, 4(R(Rmach))
MOVW R0, R1
MOVW CPSR, R0
MOVW R1, CPSR
RET
TEXT spldone(SB), $-4
RET
TEXT islo(SB), $0
MOVW CPSR, R0
AND $(PsrDirq), R0
EOR $(PsrDirq), R0
RET
TEXT setlabel(SB), $-4
MOVW R13, 0(R0)
MOVW R14, 4(R0)
MOVW $0, R0
RET
TEXT gotolabel(SB), $-4
MOVW 0(R0), R13
MOVW 4(R0), R14
MOVW $1, R0
RET
TEXT cas(SB), $0
TEXT cmpswap(SB), $0
MOVW ov+4(FP), R1
MOVW nv+8(FP), R2
spincas:
LDREX (R0), R3
CMP.S R3, R1
BNE fail
STREX R2, (R0), R4
CMP.S $0, R4
BNE spincas
MOVW $1, R0
DMB
RET
fail:
CLREX
MOVW $0, R0
RET
TEXT tas(SB), $0
TEXT _tas(SB), $0
MOVW $0xDEADDEAD, R2
_tas1:
LDREX (R0), R1
STREX R2, (R0), R3
CMP.S $0, R3
BNE _tas1
MOVW R1, R0
DMB
RET
TEXT coherence(SB), $0
DSB
RET
TEXT idlehands(SB), $0
DSB
WFE
RET
TEXT sendevent(SB), $0
SEV
RET
TEXT ttbget(SB), $0
MRC 15, 0, R0, C(2), C(0), 0
BIC $0x7f, R0
RET
TEXT ttbput(SB), $0
ORR $TTBATTR, R0
MCR 15, 0, R0, C(2), C(0), 0
RET
TEXT flushpg(SB), $0
MCR 15, 0, R0, C(8), C(7), 3
DSB
RET
TEXT flushtlb(SB), $0
MCR 15, 0, R0, C(8), C(3), 0
DSB
RET
TEXT setasid(SB), $0
DSB /* errata */
MCR 15, 0, R0, C(13), C(0), 1
RET
TEXT getifar(SB), $0
MRC 15, 0, R0, C(6), C(0), 2
RET
TEXT getdfar(SB), $0
MRC 15, 0, R0, C(6), C(0), 0
RET
TEXT getifsr(SB), $0
MRC 15, 0, R0, C(5), C(0), 1
RET
TEXT getdfsr(SB), $0
MRC 15, 0, R0, C(5), C(0), 0
RET
TEXT setpmcr(SB), $0
MCR 15, 0, R0, C(9), C(12), 0
RET
TEXT setpmcnten(SB), $0
MCR 15, 0, R0, C(9), C(12), 1
RET
TEXT perfticks(SB), $0
MRC 15, 0, R0, C(9), C(13), 0
RET
TEXT cycles(SB), $0
MRC 15, 0, R1, C(9), C(13), 0
MOVW R1, (R0)
MOVW 24(R(Rmach)), R1
MRC 15, 0, R2, C(9), C(12), 3
AND.S $(1<<31), R2
BEQ _cycles0
MCR 15, 0, R2, C(9), C(12), 3
ADD $1, R1
MOVW R1, 24(R(Rmach))
_cycles0:
MOVW R1, 4(R0)
RET
TEXT fpinit(SB), $0
MOVW $(1<<30), R0
VMSR(0xe, 0, FPEXC)
MOVW $0, R0
VMSR(0xe, 0, FPSCR)
RET
TEXT fprestore(SB), $0
MOVM.IA.W (R0), [R1-R2]
VMSR(0xe, 1, FPEXC)
VMSR(0xe, 2, FPSCR)
WORD $0xecb00b20
WORD $0xecf00b20
RET
TEXT fpsave(SB), $0
VMRS(0xe, FPEXC, 1)
VMRS(0xe, FPSCR, 2)
MOVM.IA.W [R1-R2], (R0)
WORD $0xeca00b20
WORD $0xece00b20
/* wet floor */
TEXT fpoff(SB), $0
TEXT fpclear(SB), $0
MOVW $0, R1
VMSR(0xe, 1, FPEXC)
RET
#define Rnoway R1
#define Rwayinc R2
#define Rmaxway R3
#define Rsetinc R4
#define Rmaxset R5
TEXT l1dclear(SB), $0
MOVW $0, R0
MCR 15, 2, R0, C(0), C(0), 0
MRC 15, 1, R9, C(0), C(0), 0
AND $7, R9, R8
ADD $4, R8
MOVW $1, Rsetinc
MOVW Rsetinc<<R8, Rsetinc
MOVW R9>>13, Rmaxset
AND $0x7fff, Rmaxset
MOVW Rmaxset<<R8, Rmaxset
MOVW R9>>3, R0
AND $0x3ff, R0
MOVW $(1<<31), Rwayinc
MOVW $(1<<31), Rnoway
MOVW R0, Rmaxway
ADD $1, R0
_l1dclear0:
MOVW.S R0>>1, R0
BEQ _l1dclear1
MOVW Rwayinc>>1, Rwayinc
MOVW Rnoway->1, Rnoway
MOVW Rmaxway@>1, Rmaxway
B _l1dclear0
_l1dclear1:
MOVW Rwayinc<<1, Rwayinc
MVN Rnoway<<1, Rnoway
BIC Rnoway, Rmaxway
MOVW $0, R0
_l1dclear2:
MCR 15, 0, R0, C(7), C(14), 2
ADD Rwayinc, R0
CMP.S Rmaxway, R0
BLT _l1dclear2
AND Rnoway, R0
ADD Rsetinc, R0
CMP.S Rmaxset, R0
BLT _l1dclear2
RET
TEXT invalise(SB), $0
MOVW 4(FP), R1
ADD $(LINSIZ - 1), R1
BIC $(LINSIZ - 1), R0
BIC $(LINSIZ - 1), R1
_invalise0:
MCR 15, 0, R0, C(7), C(5), 1
ADD $LINSIZ, R0
CMP.S R1, R0
BLT _invalise0
RET
TEXT cleandse(SB), $0
DSB
MOVW 4(FP), R1
ADD $(LINSIZ - 1), R1
BIC $(LINSIZ - 1), R0
BIC $(LINSIZ - 1), R1
_cleandse0:
MCR 15, 0, R0, C(7), C(10), 1
ADD $LINSIZ, R0
CMP.S R1, R0
BLT _cleandse0
DSB
RET
TEXT invaldse(SB), $0
MOVW 4(FP), R1
ADD $(LINSIZ - 1), R1
BIC $(LINSIZ - 1), R0
BIC $(LINSIZ - 1), R1
_invaldse0:
MCR 15, 0, R0, C(7), C(6), 1
ADD $LINSIZ, R0
CMP.S R1, R0
BLT _invaldse0
DSB
RET
TEXT clinvdse(SB), $0
DSB
MOVW 4(FP), R1
ADD $(LINSIZ - 1), R1
BIC $(LINSIZ - 1), R0
BIC $(LINSIZ - 1), R1
_clinvdse0:
MCR 15, 0, R0, C(7), C(14), 1
ADD $LINSIZ, R0
CMP.S R1, R0
BLT _clinvdse0
DSB
RET
TEXT cleandln(SB), $0
DSB
MCR 15, 0, R0, C(7), C(10), 1
DSB
RET
TEXT invaldln(SB), $0
MCR 15, 0, R0, C(7), C(6), 1
DSB
RET
TEXT clinvdln(SB), $0
DSB
MCR 15, 0, R0, C(7), C(14), 1
DSB
RET
TEXT palookur(SB), $0
MCR 15, 0, R0, C(7), C(8), 2
DSB
MRC 15, 0, R0, C(7), C(4), 0
RET
|
9front/9front
| 1,623
|
sys/src/9/zynq/ltrap.s
|
#include "mem.h"
#include "io.h"
TEXT vectors(SB), $-4
MOVW $_start-KZERO(SB), R15
MOVW $_vexc(SB), R15
MOVW $_vsvc(SB), R15
MOVW $_viabt(SB), R15
MOVW $_vexc(SB), R15
MOVW $vectors(SB), R15
MOVW $_vexc(SB), R15
MOVW $_vexc(SB), R15
TEXT _viabt(SB), $-4
CPS(CPSID)
CLREX
DSB
MOVW R14, 8(R13)
MOVW SPSR, R14
MOVW R14, 4(R13)
MOVW CPSR, R14
AND $0x1e, R14
B _exc
TEXT _vexc(SB), $-4
CPS(CPSID)
CLREX
DSB
MOVW R14, 8(R13)
MOVW SPSR, R14
MOVW R14, 4(R13)
MOVW CPSR, R14
AND $0x1f, R14
_exc:
MOVW R14, 0(R13)
CPS(CPSMODE | PsrMsvc)
SUB $(18*4), R13
MOVM.IA [R0-R14], (R13)
/* get Mach* from TPIDRPRW */
MRC 15, 0, R(Rmach), C(13), C(0), 4
MOVW 8(R(Rmach)), R(Rup)
MOVW $setR12(SB), R12
ADD $12, R(Rmach), R0
MOVM.IA (R0), [R1-R3]
ADD $(15*4), R13, R0
MOVM.IA [R1-R3], (R0)
AND.S $0xf, R2
ADD.NE $(18*4), R13, R0
MOVW.NE R0, (13*4)(R13)
ADD.EQ $(13*4), R13, R0
MOVM.IA.S.EQ [R13-R14], (R0)
MOVW R13, R0
SUB $8, R13
BL trap(SB)
ADD $8, R13
MOVW (16*4)(R13), R0
MOVW R0, SPSR
AND.S $0xf, R0
BEQ _uret
MOVW R(Rmach), (Rmach*4)(R13)
MOVM.IA (R13), [R0-R14]
DSB
MOVM.DB.S (R13), [R15]
TEXT _vsvc(SB), $-4
CLREX
DSB
MOVW.W R14, -4(R13)
MOVW SPSR, R14
MOVW.W R14, -4(R13)
MOVW $PsrMsvc, R14
MOVW.W R14, -4(R13)
MOVM.DB.S [R0-R14], (R13)
SUB $(15*4), R13
/* get Mach* from TPIDRPRW */
MRC 15, 0, R(Rmach), C(13), C(0), 4
MOVW 8(R(Rmach)), R(Rup)
MOVW $setR12(SB), R12
MOVW R13, R0
SUB $8, R13
BL syscall(SB)
ADD $8, R13
MOVW (16*4)(R13), R0
MOVW R0, SPSR
_uret:
MOVM.IA.S (R13), [R0-R14]
ADD $(17*4), R13
DSB
ISB
MOVM.IA.S.W (R13), [R15]
|
9front/9front
| 1,554
|
sys/src/9/xen/xen.s
|
#include "xendefs.h"
#include "mem.h"
#define ENTRY(X) TEXT X(SB), $0
/*
* XXX there's a race in here because we can get an upcall
* betwen the spllo() (in xenupcall) and the rti. This will make
* handlers stack, which could lead to a blown stack. Probably
* not worth fixing (but possibly worth detecting and panicing).
*
* For fun get some popcorn and turn off the lights and read the
* linux solution (search for scrit/ecrit).
*/
ENTRY(hypervisor_callback)
SUBL $8, SP /* space for ecode and trap type */
PUSHL DS /* save DS */
PUSHL $(KDSEL)
POPL DS /* fix up DS */
PUSHL ES /* save ES */
PUSHL $(KDSEL)
POPL ES /* fix up ES */
PUSHL FS /* save the rest of the Ureg struct */
PUSHL GS
PUSHAL
PUSHL SP /* Ureg* argument to trap */
CALL xenupcall+0(SB)
POPL AX
POPAL
POPL GS
POPL FS
POPL ES
POPL DS
ADDL $8, SP /* pop error code and trap type */
IRETL
/* Hypervisor uses this for application faults while it executes.*/
ENTRY(failsafe_callback)
IRETL
PUSHL AX
CALL install_safe_pf_handler(SB)
MOVL 32(SP), BX
MOVW BX, DS
MOVL 36(SP), BX
MOVW BX, ES
MOVL 40(SP), BX
MOVW BX, FS
MOVL 44(SP), BX
MOVW BX, GS
CALL install_normal_pf_handler(SB)
POPL AX
ADDL $16, SP
IRETL
/* xen traps with varying argument counts */
TEXT xencall6(SB), $0
MOVL VDI+20(FP), DI
TEXT xencall5(SB), $0
MOVL VSI+16(FP), SI
TEXT xencall4(SB), $0
MOVL VDX+12(FP), DX
TEXT xencall3(SB), $0
MOVL VCX+8(FP), CX
TEXT xencall2(SB), $0
MOVL VBX+4(FP), BX
TEXT xencall1(SB), $0
MOVL op+0(FP), AX
INT $0x82
RET
|
9front/9front
| 17,921
|
sys/src/9/xen/l.s
|
#include "xendefs.h"
#include "mem.h"
/*
* Some machine instructions not handled by 8[al].
*/
#define OP16 BYTE $0x66
#define DELAY BYTE $0xEB; BYTE $0x00 /* JMP .+2 */
#define CPUID BYTE $0x0F; BYTE $0xA2 /* CPUID, argument in AX */
#define WRMSR BYTE $0x0F; BYTE $0x30 /* WRMSR, argument in AX/DX (lo/hi) */
#define RDTSC BYTE $0x0F; BYTE $0x31 /* RDTSC, result in AX/DX (lo/hi) */
#define RDMSR BYTE $0x0F; BYTE $0x32 /* RDMSR, result in AX/DX (lo/hi) */
#define HLT BYTE $0xF4
#define BSFL BYTE $0xf; BYTE $0xbc; BYTE $0xc0 /* bsfl AX,AX */
/*
* Macros for calculating offsets within the page directory base
* and page tables. Note that these are assembler-specific hence
* the '<<2'.
*/
#define PDO(a) (((((a))>>22) & 0x03FF)<<2)
#define PTO(a) (((((a))>>12) & 0x03FF)<<2)
/*
* Entry point from XEN's "linux" builder.
* At this point RAM from 0..4M ("physical") is mapped at KZERO,
* the kernel is loaded, we're running on a boot stack and a
* boot page table. The start_info structure describes the
* situation, and is pointed to by SI.
* The stack is the highest used address.
*/
TEXT _start(SB), $0
MOVL SP, xentop(SB) /* set global for top of mapped region */
MOVL SI, xenstart(SB) /* set global to start_info_t */
MOVL $0, AX /* clear EFLAGS */
PUSHL AX
POPFL
CALL mmumapcpu0(SB) /* make mapping before using stack */
MOVL $(MACHADDR+MACHSIZE-4), SP /* set stack */
CALL main(SB)
/*
* Park a processor. Should never fall through a return from main to here,
* should only be called by application processors when shutting down.
*/
TEXT idle(SB), $0
_idle:
STI
HLT
JMP _idle
/*
* Read/write various system registers.
* CR4 and the 'model specific registers' should only be read/written
* after it has been determined the processor supports them
*/
TEXT _cycles(SB), $0 /* time stamp counter; cycles since power up */
RDTSC
MOVL vlong+0(FP), CX /* &vlong */
MOVL AX, 0(CX) /* lo */
MOVL DX, 4(CX) /* hi */
RET
TEXT rdmsr(SB), $0 /* model-specific register */
MOVL index+0(FP), CX
RDMSR
MOVL vlong+4(FP), CX /* &vlong */
MOVL AX, 0(CX) /* lo */
MOVL DX, 4(CX) /* hi */
RET
/* Xen doesn't let us do this */
TEXT wrmsr(SB), $0
MOVL $-1, AX
RET
/*
* Try to determine the CPU type which requires fiddling with EFLAGS.
* If the Id bit can be toggled then the CPUID instruction can be used
* to determine CPU identity and features. First have to check if it's
* a 386 (Ac bit can't be set). If it's not a 386 and the Id bit can't be
* toggled then it's an older 486 of some kind.
*
* cpuid(fun, regs[4]);
*/
TEXT cpuid(SB), $0
MOVL $0x240000, AX
PUSHL AX
POPFL /* set Id|Ac */
PUSHFL
POPL BX /* retrieve value */
MOVL $0, AX
PUSHL AX
POPFL /* clear Id|Ac, EFLAGS initialised */
PUSHFL
POPL AX /* retrieve value */
XORL BX, AX
TESTL $0x040000, AX /* Ac */
JZ _cpu386 /* can't set this bit on 386 */
TESTL $0x200000, AX /* Id */
JZ _cpu486 /* can't toggle this bit on some 486 */
MOVL fn+0(FP), AX
CPUID
JMP _cpuid
_cpu486:
MOVL $0x400, AX
JMP _maybezapax
_cpu386:
MOVL $0x300, AX
_maybezapax:
CMPL fn+0(FP), $1
JE _zaprest
XORL AX, AX
_zaprest:
XORL BX, BX
XORL CX, CX
XORL DX, DX
_cpuid:
MOVL regs+4(FP), BP
MOVL AX, 0(BP)
MOVL BX, 4(BP)
MOVL CX, 8(BP)
MOVL DX, 12(BP)
RET
/*
* Floating point.
* Note: the encodings for the FCLEX, FINIT, FSAVE, FSTCW, FSENV and FSTSW
* instructions do NOT have the WAIT prefix byte (i.e. they act like their
* FNxxx variations) so WAIT instructions must be explicitly placed in the
* code as necessary.
*/
#define FPOFF(l) ;\
MOVL CR0, AX ;\
ANDL $0xC, AX /* EM, TS */ ;\
CMPL AX, $0x8 ;\
JEQ l ;\
WAIT ;\
l: ;\
MOVL CR0, AX ;\
ANDL $~0x4, AX /* EM=0 */ ;\
ORL $0x28, AX /* NE=1, TS=1 */ ;\
MOVL AX, CR0
#define FPON ;\
MOVL CR0, AX ;\
ANDL $~0xC, AX /* EM=0, TS=0 */ ;\
MOVL AX, CR0
TEXT fpoff(SB), $0 /* disable */
FPOFF(l1)
RET
TEXT fpinit(SB), $0 /* enable and init */
FPON
FINIT
WAIT
/* setfcr(FPPDBL|FPRNR|FPINVAL|FPZDIV|FPOVFL) */
/* note that low 6 bits are masks, not enables, on this chip */
PUSHW $0x0232
FLDCW 0(SP)
POPW AX
WAIT
RET
TEXT fpx87save0(SB), $0 /* save state and disable */
MOVL p+0(FP), AX
FSAVE 0(AX) /* no WAIT */
FPOFF(l2)
RET
TEXT fpx87restore0(SB), $0 /* enable and restore state */
FPON
MOVL p+0(FP), AX
FRSTOR 0(AX)
WAIT
RET
TEXT fpclear(SB), $0 /* clear pending exceptions */
FPON
FCLEX /* no WAIT */
FPOFF(l3)
RET
TEXT fpssesave(SB), $0 /* save state and disable */
MOVL p+0(FP), AX
FXSAVE 0(AX) /* no WAIT */
FPOFF(l4)
RET
TEXT fpsserestore(SB), $0 /* enable and restore state */
FPON
MOVL p+0(FP), AX
FXRSTOR 0(AX)
WAIT
RET
TEXT ldmxcsr(SB), $0 /* Load MXCSR */
LDMXCSR mxcsr+0(FP)
RET
/*
* Test-And-Set
*/
TEXT tas(SB), $0
TEXT _tas(SB), $0
MOVL $0xDEADDEAD, AX
MOVL lock+0(FP), BX
XCHGL AX, (BX) /* lock->key */
RET
TEXT getstack(SB), $0
MOVL SP, AX
RET
TEXT mb386(SB), $0
POPL AX /* return PC */
PUSHFL
PUSHL CS
PUSHL AX
IRETL
TEXT mb586(SB), $0
XORL AX, AX
CPUID
RET
TEXT sfence(SB), $0
BYTE $0x0f
BYTE $0xae
BYTE $0xf8
RET
TEXT lfence(SB), $0
BYTE $0x0f
BYTE $0xae
BYTE $0xe8
RET
TEXT mfence(SB), $0
BYTE $0x0f
BYTE $0xae
BYTE $0xf0
RET
TEXT xchgw(SB), $0
MOVL v+4(FP), AX
MOVL p+0(FP), BX
XCHGW AX, (BX)
RET
TEXT xchgb(SB), $0
MOVL v+4(FP), AX
MOVL p+0(FP), BX
XCHGB AX, (BX)
RET
TEXT xchgl(SB), $0
MOVL v+4(FP), AX
MOVL p+0(FP), BX
XCHGL AX, (BX)
RET
/* Return the position of the first bit set. Undefined if zero. */
TEXT ffs(SB), $0
MOVL v+0(FP), AX
BSFL
RET
TEXT cmpswap486(SB), $0
MOVL addr+0(FP), BX
MOVL old+4(FP), AX
MOVL new+8(FP), CX
LOCK
BYTE $0x0F; BYTE $0xB1; BYTE $0x0B /* CMPXCHGL CX, (BX) */
JNZ didnt
MOVL $1, AX
RET
didnt:
XORL AX,AX
RET
TEXT mul64fract(SB), $0
MOVL r+0(FP), CX
XORL BX, BX /* BX = 0 */
MOVL a+8(FP), AX
MULL b+16(FP) /* a1*b1 */
MOVL AX, 4(CX) /* r2 = lo(a1*b1) */
MOVL a+8(FP), AX
MULL b+12(FP) /* a1*b0 */
MOVL AX, 0(CX) /* r1 = lo(a1*b0) */
ADDL DX, 4(CX) /* r2 += hi(a1*b0) */
MOVL a+4(FP), AX
MULL b+16(FP) /* a0*b1 */
ADDL AX, 0(CX) /* r1 += lo(a0*b1) */
ADCL DX, 4(CX) /* r2 += hi(a0*b1) + carry */
MOVL a+4(FP), AX
MULL b+12(FP) /* a0*b0 */
ADDL DX, 0(CX) /* r1 += hi(a0*b0) */
ADCL BX, 4(CX) /* r2 += carry */
RET
#define RDRANDAX BYTE $0x0f; BYTE $0xc7; BYTE $0xf0
TEXT rdrand32(SB), $-4
_rloop32:
RDRANDAX
JCC _rloop32
RET
TEXT rdrandbuf(SB), $0
MOVL buf+0(FP), DI
MOVL cnt+4(FP), CX
CLD
MOVL CX, DX
SHRL $2, CX
CMPL CX, $0
JE _rndleft
_rnddwords:
CALL rdrand32(SB)
STOSL
LOOP _rnddwords
_rndleft:
MOVL DX, CX
ANDL $3, CX
CMPL CX, $0
JE _rnddone
_rndbytes:
CALL rdrand32(SB)
STOSB
LOOP _rndbytes
_rnddone:
RET
/*
* label consists of a stack pointer and a PC
*/
TEXT gotolabel(SB), $0
MOVL label+0(FP), AX
MOVL 0(AX), SP /* restore sp */
MOVL 4(AX), AX /* put return pc on the stack */
MOVL AX, 0(SP)
MOVL $1, AX /* return 1 */
RET
TEXT setlabel(SB), $0
MOVL label+0(FP), AX
MOVL SP, 0(AX) /* store sp */
MOVL 0(SP), BX /* store return pc */
MOVL BX, 4(AX)
MOVL $0, AX /* return 0 */
RET
TEXT mwait(SB), $0
MOVL addr+0(FP), AX
MOVL (AX), CX
ORL CX, CX
JNZ _mwaitdone
XORL DX, DX
BYTE $0x0f; BYTE $0x01; BYTE $0xc8 /* MONITOR */
MOVL (AX), CX
ORL CX, CX
JNZ _mwaitdone
XORL AX, AX
BYTE $0x0f; BYTE $0x01; BYTE $0xc9 /* MWAIT */
_mwaitdone:
RET
/*
* Interrupt/exception handling.
* Each entry in the vector table calls either _strayintr or _strayintrx depending
* on whether an error code has been automatically pushed onto the stack
* (_strayintrx) or not, in which case a dummy entry must be pushed before retrieving
* the trap type from the vector table entry and placing it on the stack as part
* of the Ureg structure.
* Exceptions to this are the syscall vector and the page fault
* vector. Syscalls are dispatched seperately. Page faults
* have to take care of the extra cr2 parameter that xen places
* at the top of the stack.
* The size of each entry in the vector table (6 bytes) is known in trapinit().
*/
TEXT _strayintr(SB), $0
PUSHL AX /* save AX */
MOVL 4(SP), AX /* return PC from vectortable(SB) */
JMP intrcommon
TEXT _strayintrx(SB), $0
XCHGL AX, (SP) /* swap AX with vectortable CALL PC */
intrcommon:
PUSHL DS /* save DS */
PUSHL $(KDSEL)
POPL DS /* fix up DS */
MOVBLZX (AX), AX /* trap type -> AX */
XCHGL AX, 4(SP) /* exchange trap type with saved AX */
PUSHL ES /* save ES */
PUSHL $(KDSEL)
POPL ES /* fix up ES */
PUSHL FS /* save the rest of the Ureg struct */
PUSHL GS
PUSHAL
PUSHL SP /* Ureg* argument to trap */
CALL trap(SB)
TEXT forkret(SB), $0
POPL AX
POPAL
POPL GS
POPL FS
POPL ES
POPL DS
ADDL $8, SP /* pop error code and trap type */
IRETL
TEXT vectortable(SB), $0
CALL _strayintr(SB); BYTE $0x00 /* divide error */
CALL _strayintr(SB); BYTE $0x01 /* debug exception */
CALL _strayintr(SB); BYTE $0x02 /* NMI interrupt */
CALL _strayintr(SB); BYTE $0x03 /* breakpoint */
CALL _strayintr(SB); BYTE $0x04 /* overflow */
CALL _strayintr(SB); BYTE $0x05 /* bound */
CALL _strayintr(SB); BYTE $0x06 /* invalid opcode */
CALL _strayintr(SB); BYTE $0x07 /* no coprocessor available */
CALL _strayintrx(SB); BYTE $0x08 /* double fault */
CALL _strayintr(SB); BYTE $0x09 /* coprocessor segment overflow */
CALL _strayintrx(SB); BYTE $0x0A /* invalid TSS */
CALL _strayintrx(SB); BYTE $0x0B /* segment not available */
CALL _strayintrx(SB); BYTE $0x0C /* stack exception */
CALL _strayintrx(SB); BYTE $0x0D /* general protection error */
CALL _strayintrx(SB); BYTE $0x0E /* page fault */
CALL _strayintr(SB); BYTE $0x0F /* */
CALL _strayintr(SB); BYTE $0x10 /* coprocessor error */
CALL _strayintrx(SB); BYTE $0x11 /* alignment check */
CALL _strayintr(SB); BYTE $0x12 /* machine check */
CALL _strayintr(SB); BYTE $0x13
CALL _strayintr(SB); BYTE $0x14
CALL _strayintr(SB); BYTE $0x15
CALL _strayintr(SB); BYTE $0x16
CALL _strayintr(SB); BYTE $0x17
CALL _strayintr(SB); BYTE $0x18
CALL _strayintr(SB); BYTE $0x19
CALL _strayintr(SB); BYTE $0x1A
CALL _strayintr(SB); BYTE $0x1B
CALL _strayintr(SB); BYTE $0x1C
CALL _strayintr(SB); BYTE $0x1D
CALL _strayintr(SB); BYTE $0x1E
CALL _strayintr(SB); BYTE $0x1F
CALL _strayintr(SB); BYTE $0x20 /* VectorLAPIC */
CALL _strayintr(SB); BYTE $0x21
CALL _strayintr(SB); BYTE $0x22
CALL _strayintr(SB); BYTE $0x23
CALL _strayintr(SB); BYTE $0x24
CALL _strayintr(SB); BYTE $0x25
CALL _strayintr(SB); BYTE $0x26
CALL _strayintr(SB); BYTE $0x27
CALL _strayintr(SB); BYTE $0x28
CALL _strayintr(SB); BYTE $0x29
CALL _strayintr(SB); BYTE $0x2A
CALL _strayintr(SB); BYTE $0x2B
CALL _strayintr(SB); BYTE $0x2C
CALL _strayintr(SB); BYTE $0x2D
CALL _strayintr(SB); BYTE $0x2E
CALL _strayintr(SB); BYTE $0x2F
CALL _strayintr(SB); BYTE $0x30
CALL _strayintr(SB); BYTE $0x31
CALL _strayintr(SB); BYTE $0x32
CALL _strayintr(SB); BYTE $0x33
CALL _strayintr(SB); BYTE $0x34
CALL _strayintr(SB); BYTE $0x35
CALL _strayintr(SB); BYTE $0x36
CALL _strayintr(SB); BYTE $0x37
CALL _strayintr(SB); BYTE $0x38
CALL _strayintr(SB); BYTE $0x39
CALL _strayintr(SB); BYTE $0x3A
CALL _strayintr(SB); BYTE $0x3B
CALL _strayintr(SB); BYTE $0x3C
CALL _strayintr(SB); BYTE $0x3D
CALL _strayintr(SB); BYTE $0x3E
CALL _strayintr(SB); BYTE $0x3F
CALL _syscallintr(SB); BYTE $0x40 /* VectorSYSCALL */
CALL _strayintr(SB); BYTE $0x41
CALL _strayintr(SB); BYTE $0x42
CALL _strayintr(SB); BYTE $0x43
CALL _strayintr(SB); BYTE $0x44
CALL _strayintr(SB); BYTE $0x45
CALL _strayintr(SB); BYTE $0x46
CALL _strayintr(SB); BYTE $0x47
CALL _strayintr(SB); BYTE $0x48
CALL _strayintr(SB); BYTE $0x49
CALL _strayintr(SB); BYTE $0x4A
CALL _strayintr(SB); BYTE $0x4B
CALL _strayintr(SB); BYTE $0x4C
CALL _strayintr(SB); BYTE $0x4D
CALL _strayintr(SB); BYTE $0x4E
CALL _strayintr(SB); BYTE $0x4F
CALL _strayintr(SB); BYTE $0x50
CALL _strayintr(SB); BYTE $0x51
CALL _strayintr(SB); BYTE $0x52
CALL _strayintr(SB); BYTE $0x53
CALL _strayintr(SB); BYTE $0x54
CALL _strayintr(SB); BYTE $0x55
CALL _strayintr(SB); BYTE $0x56
CALL _strayintr(SB); BYTE $0x57
CALL _strayintr(SB); BYTE $0x58
CALL _strayintr(SB); BYTE $0x59
CALL _strayintr(SB); BYTE $0x5A
CALL _strayintr(SB); BYTE $0x5B
CALL _strayintr(SB); BYTE $0x5C
CALL _strayintr(SB); BYTE $0x5D
CALL _strayintr(SB); BYTE $0x5E
CALL _strayintr(SB); BYTE $0x5F
CALL _strayintr(SB); BYTE $0x60
CALL _strayintr(SB); BYTE $0x61
CALL _strayintr(SB); BYTE $0x62
CALL _strayintr(SB); BYTE $0x63
CALL _strayintr(SB); BYTE $0x64
CALL _strayintr(SB); BYTE $0x65
CALL _strayintr(SB); BYTE $0x66
CALL _strayintr(SB); BYTE $0x67
CALL _strayintr(SB); BYTE $0x68
CALL _strayintr(SB); BYTE $0x69
CALL _strayintr(SB); BYTE $0x6A
CALL _strayintr(SB); BYTE $0x6B
CALL _strayintr(SB); BYTE $0x6C
CALL _strayintr(SB); BYTE $0x6D
CALL _strayintr(SB); BYTE $0x6E
CALL _strayintr(SB); BYTE $0x6F
CALL _strayintr(SB); BYTE $0x70
CALL _strayintr(SB); BYTE $0x71
CALL _strayintr(SB); BYTE $0x72
CALL _strayintr(SB); BYTE $0x73
CALL _strayintr(SB); BYTE $0x74
CALL _strayintr(SB); BYTE $0x75
CALL _strayintr(SB); BYTE $0x76
CALL _strayintr(SB); BYTE $0x77
CALL _strayintr(SB); BYTE $0x78
CALL _strayintr(SB); BYTE $0x79
CALL _strayintr(SB); BYTE $0x7A
CALL _strayintr(SB); BYTE $0x7B
CALL _strayintr(SB); BYTE $0x7C
CALL _strayintr(SB); BYTE $0x7D
CALL _strayintr(SB); BYTE $0x7E
CALL _strayintr(SB); BYTE $0x7F
CALL _strayintr(SB); BYTE $0x80 /* Vector[A]PIC */
CALL _strayintr(SB); BYTE $0x81
CALL _strayintr(SB); BYTE $0x82
CALL _strayintr(SB); BYTE $0x83
CALL _strayintr(SB); BYTE $0x84
CALL _strayintr(SB); BYTE $0x85
CALL _strayintr(SB); BYTE $0x86
CALL _strayintr(SB); BYTE $0x87
CALL _strayintr(SB); BYTE $0x88
CALL _strayintr(SB); BYTE $0x89
CALL _strayintr(SB); BYTE $0x8A
CALL _strayintr(SB); BYTE $0x8B
CALL _strayintr(SB); BYTE $0x8C
CALL _strayintr(SB); BYTE $0x8D
CALL _strayintr(SB); BYTE $0x8E
CALL _strayintr(SB); BYTE $0x8F
CALL _strayintr(SB); BYTE $0x90
CALL _strayintr(SB); BYTE $0x91
CALL _strayintr(SB); BYTE $0x92
CALL _strayintr(SB); BYTE $0x93
CALL _strayintr(SB); BYTE $0x94
CALL _strayintr(SB); BYTE $0x95
CALL _strayintr(SB); BYTE $0x96
CALL _strayintr(SB); BYTE $0x97
CALL _strayintr(SB); BYTE $0x98
CALL _strayintr(SB); BYTE $0x99
CALL _strayintr(SB); BYTE $0x9A
CALL _strayintr(SB); BYTE $0x9B
CALL _strayintr(SB); BYTE $0x9C
CALL _strayintr(SB); BYTE $0x9D
CALL _strayintr(SB); BYTE $0x9E
CALL _strayintr(SB); BYTE $0x9F
CALL _strayintr(SB); BYTE $0xA0
CALL _strayintr(SB); BYTE $0xA1
CALL _strayintr(SB); BYTE $0xA2
CALL _strayintr(SB); BYTE $0xA3
CALL _strayintr(SB); BYTE $0xA4
CALL _strayintr(SB); BYTE $0xA5
CALL _strayintr(SB); BYTE $0xA6
CALL _strayintr(SB); BYTE $0xA7
CALL _strayintr(SB); BYTE $0xA8
CALL _strayintr(SB); BYTE $0xA9
CALL _strayintr(SB); BYTE $0xAA
CALL _strayintr(SB); BYTE $0xAB
CALL _strayintr(SB); BYTE $0xAC
CALL _strayintr(SB); BYTE $0xAD
CALL _strayintr(SB); BYTE $0xAE
CALL _strayintr(SB); BYTE $0xAF
CALL _strayintr(SB); BYTE $0xB0
CALL _strayintr(SB); BYTE $0xB1
CALL _strayintr(SB); BYTE $0xB2
CALL _strayintr(SB); BYTE $0xB3
CALL _strayintr(SB); BYTE $0xB4
CALL _strayintr(SB); BYTE $0xB5
CALL _strayintr(SB); BYTE $0xB6
CALL _strayintr(SB); BYTE $0xB7
CALL _strayintr(SB); BYTE $0xB8
CALL _strayintr(SB); BYTE $0xB9
CALL _strayintr(SB); BYTE $0xBA
CALL _strayintr(SB); BYTE $0xBB
CALL _strayintr(SB); BYTE $0xBC
CALL _strayintr(SB); BYTE $0xBD
CALL _strayintr(SB); BYTE $0xBE
CALL _strayintr(SB); BYTE $0xBF
CALL _strayintr(SB); BYTE $0xC0
CALL _strayintr(SB); BYTE $0xC1
CALL _strayintr(SB); BYTE $0xC2
CALL _strayintr(SB); BYTE $0xC3
CALL _strayintr(SB); BYTE $0xC4
CALL _strayintr(SB); BYTE $0xC5
CALL _strayintr(SB); BYTE $0xC6
CALL _strayintr(SB); BYTE $0xC7
CALL _strayintr(SB); BYTE $0xC8
CALL _strayintr(SB); BYTE $0xC9
CALL _strayintr(SB); BYTE $0xCA
CALL _strayintr(SB); BYTE $0xCB
CALL _strayintr(SB); BYTE $0xCC
CALL _strayintr(SB); BYTE $0xCD
CALL _strayintr(SB); BYTE $0xCE
CALL _strayintr(SB); BYTE $0xCF
CALL _strayintr(SB); BYTE $0xD0
CALL _strayintr(SB); BYTE $0xD1
CALL _strayintr(SB); BYTE $0xD2
CALL _strayintr(SB); BYTE $0xD3
CALL _strayintr(SB); BYTE $0xD4
CALL _strayintr(SB); BYTE $0xD5
CALL _strayintr(SB); BYTE $0xD6
CALL _strayintr(SB); BYTE $0xD7
CALL _strayintr(SB); BYTE $0xD8
CALL _strayintr(SB); BYTE $0xD9
CALL _strayintr(SB); BYTE $0xDA
CALL _strayintr(SB); BYTE $0xDB
CALL _strayintr(SB); BYTE $0xDC
CALL _strayintr(SB); BYTE $0xDD
CALL _strayintr(SB); BYTE $0xDE
CALL _strayintr(SB); BYTE $0xDF
CALL _strayintr(SB); BYTE $0xE0
CALL _strayintr(SB); BYTE $0xE1
CALL _strayintr(SB); BYTE $0xE2
CALL _strayintr(SB); BYTE $0xE3
CALL _strayintr(SB); BYTE $0xE4
CALL _strayintr(SB); BYTE $0xE5
CALL _strayintr(SB); BYTE $0xE6
CALL _strayintr(SB); BYTE $0xE7
CALL _strayintr(SB); BYTE $0xE8
CALL _strayintr(SB); BYTE $0xE9
CALL _strayintr(SB); BYTE $0xEA
CALL _strayintr(SB); BYTE $0xEB
CALL _strayintr(SB); BYTE $0xEC
CALL _strayintr(SB); BYTE $0xED
CALL _strayintr(SB); BYTE $0xEE
CALL _strayintr(SB); BYTE $0xEF
CALL _strayintr(SB); BYTE $0xF0
CALL _strayintr(SB); BYTE $0xF1
CALL _strayintr(SB); BYTE $0xF2
CALL _strayintr(SB); BYTE $0xF3
CALL _strayintr(SB); BYTE $0xF4
CALL _strayintr(SB); BYTE $0xF5
CALL _strayintr(SB); BYTE $0xF6
CALL _strayintr(SB); BYTE $0xF7
CALL _strayintr(SB); BYTE $0xF8
CALL _strayintr(SB); BYTE $0xF9
CALL _strayintr(SB); BYTE $0xFA
CALL _strayintr(SB); BYTE $0xFB
CALL _strayintr(SB); BYTE $0xFC
CALL _strayintr(SB); BYTE $0xFD
CALL _strayintr(SB); BYTE $0xFE
CALL _strayintr(SB); BYTE $0xFF
|
9front/9front
| 17,292
|
sys/src/9/kw/l.s
|
/*
* sheevaplug machine assist
* arm926ej-s processor at 1.2GHz
*
* loader uses R11 as scratch.
* R9 and R10 are used for `extern register' variables.
*
* ARM v7 arch. ref. man. (I know, this is v5) §B1.3.3 that
* we don't need barriers around moves to CPSR. The ARM v6 manual
* seems to be silent on the subject.
*/
#include "arm.s"
/*
* MCR and MRC are counter-intuitively named.
* MCR coproc, opcode1, Rd, CRn, CRm[, opcode2] # arm -> coproc
* MRC coproc, opcode1, Rd, CRn, CRm[, opcode2] # coproc -> arm
*/
/*
* Entered here from Das U-Boot with MMU disabled.
* Until the MMU is enabled it is OK to call functions provided
* they are within ±32MiB relative and do not require any
* local variables or more than one argument (i.e. there is
* no stack).
*/
TEXT _start(SB), 1, $-4
MOVW $setR12(SB), R12 /* load the SB */
_main:
/* SVC mode, interrupts disabled */
MOVW $(PsrDirq|PsrDfiq|PsrMsvc), R1
MOVW R1, CPSR
BARRIERS
/*
* disable the MMU & caches,
* switch to system permission & 32-bit addresses.
*/
MOVW $(CpCsystem|CpCd32|CpCi32), R1
MCR CpSC, 0, R1, C(CpCONTROL), C(0)
ISB
/*
* disable the Sheevaplug's L2 cache, invalidate all caches
*/
/* flush caches. 926ejs manual says we have to do it iteratively. */
_dwbinv0:
MRC CpSC, 0, PC, C(CpCACHE), C(CpCACHEwbi), CpCACHEtest
BNE _dwbinv0
/* drain L1 write buffer, also drains L2 eviction buffer on sheeva */
BARRIERS
/* make the l2 cache pay attention */
MOVW $(PHYSIO+0x20100), R1 /* CPUCSREG */
MOVW (4*10)(R1), R2
ORR $(1<<3), R2 /* cpu->l2cfg |= L2exists */
MOVW R2, (4*10)(R1)
ISB
/* invalidate l2 cache */
MCR CpSC, CpL2, R0, C(CpTESTCFG), C(CpTCl2inv), CpTCl2all
ISB
/* disable l2 cache. do this while l1 caches are off */
MRC CpSC, CpL2, R1, C(CpTESTCFG), C(CpTCl2cfg), CpTCl2conf
/* disabling write allocation is probably for cortex-a8 errata 460075 */
/* l2 off, no wr alloc, no streaming */
BIC $(CpTCl2ena | CpTCl2wralloc | CpTCldcstream), R1
MCR CpSC, CpL2, R1, C(CpTESTCFG), C(CpTCl2cfg), CpTCl2conf
BARRIERS
/* flush caches. 926ejs manual says we have to do it iteratively. */
_dwbinv1:
MRC CpSC, 0, PC, C(CpCACHE), C(CpCACHEwbi), CpCACHEtest
BNE _dwbinv1
BARRIERS
WAVE('\r')
/* clear Mach */
MOVW $PADDR(MACHADDR), R4 /* address of Mach */
_machZ:
MOVW R0, (R4)
ADD $4, R4 /* bump PTE address */
CMP.S $PADDR(L1+L1X(0)), R4
BNE _machZ
/*
* set up the MMU page table
*/
/* clear all PTEs first, to provide a default */
WAVE('\n')
MOVW $PADDR(L1+L1X(0)), R4 /* address of PTE for 0 */
_ptenv0:
ZEROPTE()
CMP.S $PADDR(L1+16*KiB), R4
BNE _ptenv0
/* double map of PHYSDRAM, KZERO to PHYSDRAM for first few MBs */
MOVW $PTEDRAM, R2 /* PTE bits */
MOVW $PHYSDRAM, R3 /* pa */
MOVW $PADDR(L1+L1X(PHYSDRAM)), R4 /* address of PTE for PHYSDRAM */
MOVW $16, R5
_ptdbl:
FILLPTE()
SUB.S $1, R5
BNE _ptdbl
/*
* back up and fill in PTEs for memory at KZERO
* there is 1 bank of 512MB of SDRAM at PHYSDRAM
*/
MOVW $PTEDRAM, R2 /* PTE bits */
MOVW $PHYSDRAM, R3
MOVW $PADDR(L1+L1X(KZERO)), R4 /* start with PTE for KZERO */
MOVW $512, R5 /* inner loop count */
_ptekrw: /* set PTEs for 512MiB */
FILLPTE()
SUB.S $1, R5
BNE _ptekrw
/*
* back up and fill in PTE for MMIO
*/
MOVW $PTEIO, R2 /* PTE bits */
MOVW $PHYSIO, R3
MOVW $PADDR(L1+L1X(VIRTIO)), R4 /* start with PTE for VIRTIO */
FILLPTE()
/* mmu.c sets up the vectors later */
/*
* set up a temporary stack; avoid data & bss segments
*/
MOVW $(PHYSDRAM | (128*1024*1024)), R13
WAVE('P')
/* set the domain access control */
MOVW $Client, R0
BL dacput(SB)
/* set the translation table base */
MOVW $PADDR(L1), R0
BL ttbput(SB)
MOVW $0, R0
BL pidput(SB) /* paranoia */
/* the little dance to turn the MMU & caches on */
WAVE('l')
BL cacheuwbinv(SB)
BL mmuinvalidate(SB)
BL mmuenable(SB)
WAVE('a')
/* warp the PC into the virtual map */
MOVW $KZERO, R0
BL _r15warp(SB)
/*
* now running at KZERO+something!
*/
MOVW $setR12(SB), R12 /* reload the SB */
/*
* set up temporary stack again, in case we've just switched
* to a new register set.
*/
MOVW $(KZERO|(128*1024*1024)), R13
/* can now execute arbitrary C code */
BL cacheuwbinv(SB)
WAVE('n')
/* undo double map of 0, KZERO */
MOVW $PADDR(L1+L1X(0)), R4 /* address of PTE for 0 */
MOVW $0, R0
MOVW $16, R5
_ptudbl:
MOVW R0, (R4)
ADD $4, R4 /* bump PTE address */
ADD $MiB, R0 /* bump pa */
SUB.S $1, R5
BNE _ptudbl
BARRIERS
MCR CpSC, 0, R0, C(CpTLB), C(CpTLBinvd), CpTLBinvse
MCR CpSC, 0, R0, C(CpTLB), C(CpTLBinvu), CpTLBinv
BARRIERS
WAVE(' ')
/* pass Mach to main and set up the stack */
MOVW $(MACHADDR), R0 /* Mach */
MOVW R0, R13
ADD $(MACHSIZE), R13 /* stack pointer */
SUB $4, R13 /* space for link register */
BL main(SB) /* void main(Mach*) */
/* fall through */
/* not used */
TEXT _reset(SB), 1, $-4
/* turn the caches off */
MOVW $(PsrDirq|PsrDfiq|PsrMsvc), R0
MOVW R0, CPSR
BARRIERS
BL cacheuwbinv(SB)
MRC CpSC, 0, R0, C(CpCONTROL), C(0)
BIC $(CpCwb|CpCicache|CpCdcache|CpCalign), R0
MCR CpSC, 0, R0, C(CpCONTROL), C(0)
BARRIERS
WAVE('R')
/* redo double map of 0, KZERO */
MOVW $(L1+L1X(0)), R4 /* address of PTE for 0 */
MOVW $PTEDRAM, R2 /* PTE bits */
MOVW $0, R3
MOVW $16, R5
_ptrdbl:
ORR R3, R2, R1 /* first identity-map 0 to 0, etc. */
MOVW R1, (R4)
ADD $4, R4 /* bump PTE address */
ADD $MiB, R3 /* bump pa */
SUB.S $1, R5
BNE _ptrdbl
BARRIERS
WAVE('e')
MOVW $0, R0
MCR CpSC, 0, R0, C(CpTLB), C(CpTLBinvd), CpTLBinv
MCR CpSC, 0, R0, C(CpTLB), C(CpTLBinvu), CpTLBinv
BARRIERS
/* back to 29- or 26-bit addressing, mainly for SB */
MRC CpSC, 0, R0, C(CpCONTROL), C(0)
BIC $(CpCd32|CpCi32), R0
MCR CpSC, 0, R0, C(CpCONTROL), C(0)
BARRIERS
/* turn the MMU off */
MOVW $PHYSDRAM, R0
BL _r15warp(SB)
BL mmuinvalidate(SB)
BL mmudisable(SB)
WAVE('s')
/* set new reset vector */
MOVW $0, R2
MOVW $0xe59ff018, R3 /* MOVW 0x18(R15), R15 */
MOVW R3, (R2)
WAVE('e')
MOVW $PHYSBOOTROM, R3
MOVW R3, 0x20(R2) /* where $0xe59ff018 jumps to */
BARRIERS
WAVE('t')
WAVE('\r')
WAVE('\n')
/* ...and jump to it */
MOVW R2, R15 /* software reboot */
_limbo: /* should not get here... */
B _limbo /* ... and can't get out */
BL _div(SB) /* hack to load _div, etc. */
TEXT _r15warp(SB), 1, $-4
BIC $KSEGM, R14
ORR R0, R14
BIC $KSEGM, R13
ORR R0, R13
RET
/* clobbers R1, R6 */
TEXT myputc(SB), 1, $-4
MOVW $PHYSCONS, R6
_busy:
MOVW 20(R6), R1
BIC.S $~(1<<5), R1 /* (x->lsr & LSRthre) == 0? */
BEQ _busy
MOVW R3, (R6) /* print */
ISB
RET
/*
* l1 caches
*/
TEXT l1cacheson(SB), 1, $-4
MOVW CPSR, R5
ORR $(PsrDirq|PsrDfiq), R5, R4
MOVW R4, CPSR /* splhi */
MRC CpSC, 0, R0, C(CpCONTROL), C(0)
ORR $(CpCdcache|CpCicache|CpCwb), R0
MCR CpSC, 0, R0, C(CpCONTROL), C(0)
BARRIERS
MOVW R5, CPSR /* splx */
RET
TEXT l1cachesoff(SB), 1, $-4
MOVM.DB.W [R14], (SP) /* save lr on stack */
MOVW CPSR, R5
ORR $(PsrDirq|PsrDfiq), R5, R4
MOVW R4, CPSR /* splhi */
BL cacheuwbinv(SB)
MRC CpSC, 0, R0, C(CpCONTROL), C(0)
BIC $(CpCdcache|CpCicache|CpCwb), R0
MCR CpSC, 0, R0, C(CpCONTROL), C(0)
BARRIERS
MOVW R5, CPSR /* splx */
MOVM.IA.W (SP), [R14] /* restore lr */
RET
/*
* cache* functions affect only the L1 caches, which are VIVT.
*/
TEXT cachedwb(SB), 1, $-4 /* D writeback */
MOVW CPSR, R3 /* splhi */
ORR $(PsrDirq), R3, R1
MOVW R1, CPSR
BARRIERS /* force outstanding stores to cache */
/* keep writing back dirty cache lines until no more exist */
_dwb:
MRC CpSC, 0, PC, C(CpCACHE), C(CpCACHEwb), CpCACHEtest
BNE _dwb
/* drain L1 write buffer, also drains L2 eviction buffer on sheeva */
BARRIERS
MOVW R3, CPSR /* splx */
RET
TEXT cachedwbse(SB), 1, $-4 /* D writeback SE */
MOVW R0, R2 /* first arg: address */
MOVW CPSR, R3 /* splhi */
ORR $(PsrDirq), R3, R1
MOVW R1, CPSR
BARRIERS /* force outstanding stores to cache */
MOVW 4(FP), R1 /* second arg: size */
// CMP.S $(4*1024), R1
// BGT _dwb
ADD R2, R1
BIC $(CACHELINESZ-1), R2
_dwbse:
MCR CpSC, 0, R2, C(CpCACHE), C(CpCACHEwb), CpCACHEse
ADD $CACHELINESZ, R2
CMP.S R2, R1
BGT _dwbse
/* drain L1 write buffer, also drains L2 eviction buffer on sheeva */
BARRIERS
MOVW R3, CPSR /* splx */
RET
TEXT cachedwbinv(SB), 1, $-4 /* D writeback+invalidate */
MOVW CPSR, R3 /* splhi */
ORR $(PsrDirq), R3, R1
MOVW R1, CPSR
BARRIERS /* force outstanding stores to cache */
/* keep writing back dirty cache lines until no more exist */
_dwbinv:
MRC CpSC, 0, PC, C(CpCACHE), C(CpCACHEwbi), CpCACHEtest
BNE _dwbinv
/* drain L1 write buffer, also drains L2 eviction buffer on sheeva */
BARRIERS
MOVW R3, CPSR /* splx */
RET
TEXT cachedwbinvse(SB), 1, $-4 /* D writeback+invalidate SE */
MOVW R0, R2 /* first arg: address */
MOVW CPSR, R3 /* splhi */
ORR $(PsrDirq), R3, R1
MOVW R1, CPSR
BARRIERS /* force outstanding stores to cache */
MOVW 4(FP), R1 /* second arg: size */
DSB
// CMP.S $(4*1024), R1
// BGT _dwbinv
ADD R2, R1
BIC $(CACHELINESZ-1), R2
_dwbinvse:
MCR CpSC, 0, R2, C(CpCACHE), C(CpCACHEwbi), CpCACHEse
ADD $CACHELINESZ, R2
CMP.S R2, R1
BGT _dwbinvse
/* drain L1 write buffer, also drains L2 eviction buffer on sheeva */
BARRIERS
MOVW R3, CPSR /* splx */
RET
TEXT cachedinvse(SB), 1, $-4 /* D invalidate SE */
MOVW R0, R2 /* first arg: address */
MOVW CPSR, R3 /* splhi */
ORR $(PsrDirq), R3, R1
MOVW R1, CPSR
MOVW 4(FP), R1 /* second arg: size */
DSB
// CMP.S $(4*1024), R1
// BGT _dinv
ADD R2, R1
BIC $(CACHELINESZ-1), R2
_dinvse:
MCR CpSC, 0, R2, C(CpCACHE), C(CpCACHEinvd), CpCACHEse
ADD $CACHELINESZ, R2
CMP.S R2, R1
BGT _dinvse
/* drain L1 write buffer, also drains L2 eviction buffer on sheeva */
BARRIERS
MOVW R3, CPSR /* splx */
RET
TEXT cacheuwbinv(SB), 1, $-4 /* D+I writeback+invalidate */
MOVW CPSR, R3 /* splhi */
ORR $(PsrDirq), R3, R1
MOVW R1, CPSR
BARRIERS /* force outstanding stores to cache */
/* keep writing back dirty cache lines until no more exist */
_uwbinv: /* D writeback+invalidate */
MRC CpSC, 0, PC, C(CpCACHE), C(CpCACHEwbi), CpCACHEtest
BNE _uwbinv
/* drain L1 write buffer, also drains L2 eviction buffer on sheeva */
BARRIERS
MOVW $0, R0 /* I invalidate */
MCR CpSC, 0, R0, C(CpCACHE), C(CpCACHEinvi), CpCACHEall
/* drain L1 write buffer, also drains L2 eviction buffer on sheeva */
BARRIERS
MOVW R3, CPSR /* splx */
RET
TEXT cacheiinv(SB), 1, $-4 /* I invalidate */
BARRIERS
MCR CpSC, 0, R0, C(CpCACHE), C(CpCACHEinvi), CpCACHEall
/* drain L1 write buffer, also drains L2 eviction buffer on sheeva */
BARRIERS
RET
TEXT cachedinv(SB), 1, $-4 /* D invalidate */
_dinv:
BARRIERS
MCR CpSC, 0, R0, C(CpCACHE), C(CpCACHEinvd), CpCACHEall
/* drain L1 write buffer, also drains L2 eviction buffer on sheeva */
BARRIERS
RET
/*
* l2 cache
*
* these functions assume that the necessary l1 cache operations have been
* or will be done explicitly by the caller.
*/
/* enable l2 cache in config coproc. reg. do this while l1 caches are off. */
TEXT l2cachecfgon(SB), 1, $-4
BARRIERS
MCR CpSC, CpL2, R0, C(CpTESTCFG), C(CpTCl2inv), CpTCl2all
BARRIERS
MRC CpSC, CpL2, R1, C(CpTESTCFG), C(CpTCl2cfg), CpTCl2conf
ORR $(CpTCl2ena | CpTCl2prefdis), R1 /* l2 on, prefetch off */
MCR CpSC, CpL2, R1, C(CpTESTCFG), C(CpTCl2cfg), CpTCl2conf
BARRIERS
RET
/* disable l2 cache in config coproc. reg. do this while l1 caches are off. */
TEXT l2cachecfgoff(SB), 1, $-4
BARRIERS
MRC CpSC, CpL2, R1, C(CpTESTCFG), C(CpTCl2cfg), CpTCl2conf
BIC $CpTCl2ena, R1
MCR CpSC, CpL2, R1, C(CpTESTCFG), C(CpTCl2cfg), CpTCl2conf
BARRIERS
MCR CpSC, CpL2, R0, C(CpTESTCFG), C(CpTCl2inv), CpTCl2all
BARRIERS
RET
TEXT l2cacheuwb(SB), 1, $-4 /* L2 unified writeback */
MCR CpSC, CpL2, R0, C(CpTESTCFG), C(CpTCl2flush), CpTCl2all
ISB
RET
TEXT l2cacheuwbse(SB), 1, $-4 /* L2 unified writeback SE */
MOVW R0, R2 /* first arg: address */
MOVW CPSR, R3 /* splhi */
ORR $(PsrDirq), R3, R1
MOVW R1, CPSR
MOVW 4(FP), R1 /* second arg: size */
ADD R2, R1
BIC $(CACHELINESZ-1), R2
_l2wbse:
MCR CpSC, CpL2, R2, C(CpTESTCFG), C(CpTCl2flush), CpTCl2seva
ADD $CACHELINESZ, R2
CMP.S R2, R1
BGT _l2wbse
ISB
MOVW R3, CPSR /* splx */
RET
TEXT l2cacheuwbinv(SB), 1, $-4 /* L2 unified writeback+invalidate */
MOVW CPSR, R3 /* splhi */
ORR $(PsrDirq), R3, R1
MOVW R1, CPSR
MCR CpSC, CpL2, R0, C(CpTESTCFG), C(CpTCl2flush), CpTCl2all
ISB
MCR CpSC, CpL2, R0, C(CpTESTCFG), C(CpTCl2inv), CpTCl2all
ISB
MOVW R3, CPSR /* splx */
RET
TEXT l2cacheuwbinvse(SB), 1, $-4 /* L2 unified writeback+invalidate SE */
MOVW R0, R2 /* first arg: address */
MOVW CPSR, R3 /* splhi */
ORR $(PsrDirq), R3, R1
MOVW R1, CPSR
MOVW 4(FP), R1 /* second arg: size */
ADD R2, R1
BIC $(CACHELINESZ-1), R2
_l2wbinvse:
MCR CpSC, CpL2, R2, C(CpTESTCFG), C(CpTCl2flush), CpTCl2seva
ISB
MCR CpSC, CpL2, R2, C(CpTESTCFG), C(CpTCl2inv), CpTCl2seva
ADD $CACHELINESZ, R2
CMP.S R2, R1
BGT _l2wbinvse
ISB
MOVW R3, CPSR /* splx */
RET
TEXT l2cacheuinv(SB), 1, $-4 /* L2 unified invalidate */
MCR CpSC, CpL2, R0, C(CpTESTCFG), C(CpTCl2inv), CpTCl2all
ISB
RET
TEXT l2cacheuinvse(SB), 1, $-4 /* L2 unified invalidate SE */
MOVW R0, R2 /* first arg: address */
MOVW CPSR, R3 /* splhi */
ORR $(PsrDirq), R3, R1
MOVW R1, CPSR
MOVW 4(FP), R1 /* second arg: size */
ADD R2, R1
BIC $(CACHELINESZ-1), R2
_l2invse:
MCR CpSC, CpL2, R2, C(CpTESTCFG), C(CpTCl2inv), CpTCl2seva
ADD $CACHELINESZ, R2
CMP.S R2, R1
BGT _l2invse
ISB
MOVW R3, CPSR /* splx */
RET
/*
* enable mmu, i and d caches, and high vector
*/
TEXT mmuenable(SB), 1, $-4
MRC CpSC, 0, R0, C(CpCONTROL), C(0)
ORR $(CpChv|CpCmmu|CpCdcache|CpCicache|CpCwb|CpCsystem), R0
BIC $(CpCrom), R0
MCR CpSC, 0, R0, C(CpCONTROL), C(0)
BARRIERS
RET
TEXT mmudisable(SB), 1, $-4
MRC CpSC, 0, R0, C(CpCONTROL), C(0)
BIC $(CpChv|CpCmmu|CpCdcache|CpCicache|CpCwb), R0
MCR CpSC, 0, R0, C(CpCONTROL), C(0)
BARRIERS
RET
TEXT mmuinvalidate(SB), 1, $-4 /* invalidate all */
MOVW $0, R0
MCR CpSC, 0, R0, C(CpTLB), C(CpTLBinvu), CpTLBinv
BARRIERS
RET
TEXT mmuinvalidateaddr(SB), 1, $-4 /* invalidate single entry */
MCR CpSC, 0, R0, C(CpTLB), C(CpTLBinvu), CpTLBinvse
BARRIERS
RET
TEXT cpidget(SB), 1, $-4 /* main ID */
MRC CpSC, 0, R0, C(CpID), C(0), CpIDid
RET
TEXT cpctget(SB), 1, $-4 /* cache type */
MRC CpSC, 0, R0, C(CpID), C(0), CpIDct
RET
TEXT controlget(SB), 1, $-4 /* control */
MRC CpSC, 0, R0, C(CpCONTROL), C(0)
RET
TEXT ttbget(SB), 1, $-4 /* translation table base */
MRC CpSC, 0, R0, C(CpTTB), C(0)
RET
TEXT ttbput(SB), 1, $-4 /* translation table base */
MCR CpSC, 0, R0, C(CpTTB), C(0)
ISB
RET
TEXT dacget(SB), 1, $-4 /* domain access control */
MRC CpSC, 0, R0, C(CpDAC), C(0)
RET
TEXT dacput(SB), 1, $-4 /* domain access control */
MCR CpSC, 0, R0, C(CpDAC), C(0)
ISB
RET
TEXT fsrget(SB), 1, $-4 /* fault status */
MRC CpSC, 0, R0, C(CpFSR), C(0)
RET
TEXT farget(SB), 1, $-4 /* fault address */
MRC CpSC, 0, R0, C(CpFAR), C(0x0)
RET
TEXT pidget(SB), 1, $-4 /* address translation pid */
MRC CpSC, 0, R0, C(CpPID), C(0x0)
RET
TEXT pidput(SB), 1, $-4 /* address translation pid */
MCR CpSC, 0, R0, C(CpPID), C(0x0)
ISB
RET
TEXT splhi(SB), 1, $-4
MOVW $(MACHADDR+4), R2 /* save caller pc in Mach */
MOVW R14, 0(R2)
MOVW CPSR, R0 /* turn off interrupts */
ORR $(PsrDirq), R0, R1
MOVW R1, CPSR
RET
TEXT spllo(SB), 1, $-4
MOVW CPSR, R0
BIC $(PsrDirq), R0, R1
MOVW R1, CPSR
RET
TEXT splx(SB), 1, $-4
MOVW $(MACHADDR+0x04), R2 /* save caller pc in Mach */
MOVW R14, 0(R2)
MOVW R0, R1 /* reset interrupt level */
MOVW CPSR, R0
MOVW R1, CPSR
RET
TEXT splxpc(SB), 1, $-4 /* for iunlock */
MOVW R0, R1
MOVW CPSR, R0
MOVW R1, CPSR
RET
TEXT spldone(SB), 1, $0
RET
TEXT islo(SB), 1, $-4
MOVW CPSR, R0
AND $(PsrDirq), R0
EOR $(PsrDirq), R0
RET
TEXT splfhi(SB), $-4
MOVW CPSR, R0
ORR $(PsrDfiq|PsrDirq), R0, R1
MOVW R1, CPSR
RET
//TEXT splflo(SB), $-4
// MOVW CPSR, R0
// BIC $(PsrDfiq), R0, R1
// MOVW R1, CPSR
// RET
TEXT tas(SB), $-4
TEXT _tas(SB), $-4
MOVW R0,R1
MOVW $1,R0
SWPW R0,(R1) /* fix: deprecated in armv7 */
RET
//TEXT tas32(SB), 1, $-4
// MOVW R0, R1
// MOVW $0xDEADDEAD, R0
// MOVW R0, R3
// SWPW R0, (R1)
// CMP.S R0, R3
// BEQ _tasout
// EOR R3, R3 /* R3 = 0 */
// CMP.S R0, R3
// BEQ _tasout
// MOVW $1, R15 /* abort: lock != 0 && lock != $0xDEADDEAD */
//_tasout:
// RET
TEXT clz(SB), 1, $-4
CLZ(0, 0) /* 0 is R0 */
RET
TEXT setlabel(SB), 1, $-4
MOVW R13, 0(R0) /* sp */
MOVW R14, 4(R0) /* pc */
BARRIERS
MOVW $0, R0
RET
TEXT gotolabel(SB), 1, $-4
MOVW 0(R0), R13 /* sp */
MOVW 4(R0), R14 /* pc */
BARRIERS
MOVW $1, R0
RET
TEXT getcallerpc(SB), 1, $-4
MOVW 0(R13), R0
RET
TEXT _idlehands(SB), 1, $-4
MOVW CPSR, R3
// ORR $PsrDirq, R3, R1 /* splhi */
BIC $PsrDirq, R3, R1 /* spllo */
MOVW R1, CPSR
MOVW $0, R0 /* wait for interrupt */
MCR CpSC, 0, R0, C(CpCACHE), C(CpCACHEintr), CpCACHEwait
ISB
MOVW R3, CPSR /* splx */
RET
TEXT barriers(SB), 1, $-4
BARRIERS
RET
|
9front/9front
| 1,298
|
sys/src/9/kw/lproc.s
|
#include "mem.h"
#include "arm.h"
/*
* This is the first jump from kernel to user mode.
* Fake a return from interrupt.
*
* Enter with R0 containing the user stack pointer.
* UTZERO + 0x20 is always the entry point.
*
*/
TEXT touser(SB), 1, $-4
/* store the user stack pointer into the USR_r13 */
MOVM.DB.W [R0], (R13)
/* avoid the ambiguity described in notes/movm.w. */
// MOVM.S.IA.W (R13), [R13]
MOVM.S (R13), [R13]
ADD $4, R13
/* set up a PSR for user level */
MOVW $(PsrMusr), R0
MOVW R0, SPSR
/* save the PC on the stack */
MOVW $(UTZERO+0x20), R0
MOVM.DB.W [R0], (R13)
/*
* note that 5a's RFE is not the v6 arch. instruction (0xe89d0a00,
* I think), which loads CPSR from the word after the PC at (R13),
* but rather the pre-v6 simulation `MOVM.IA.S.W (R13), [R15]'
* (0xe8fd8000 since MOVM is LDM in this case), which loads CPSR
* not from memory but from SPSR due to `.S'.
*/
RFE
/*
* here to jump to a newly forked process
*/
TEXT forkret(SB), 1, $-4
ADD $(4*15), R13 /* make r13 point to ureg->type */
MOVW 8(R13), R14 /* restore link */
MOVW 4(R13), R0 /* restore SPSR */
MOVW R0, SPSR /* ... */
MOVM.DB.S (R13), [R0-R14] /* restore registers */
ADD $8, R13 /* pop past ureg->{type+psr} */
RFE /* MOVM.IA.S.W (R13), [R15] */
|
9front/9front
| 1,904
|
sys/src/9/kw/arm.s
|
/*
* sheevaplug machine assist, definitions
* arm926ej-s processor at 1.2GHz
*
* loader uses R11 as scratch.
*/
#include "mem.h"
#include "arm.h"
#undef B /* B is for 'botch' */
#define PADDR(a) ((a) & ~KZERO)
#define KADDR(a) (KZERO|(a))
#define L1X(va) (((((va))>>20) & 0x0fff)<<2)
#define MACHADDR (L1-MACHSIZE)
#define PTEDRAM (Dom0|L1AP(Krw)|Section|Cached|Buffered)
#define PTEIO (Dom0|L1AP(Krw)|Section)
/* wave at the user; clobbers R1 & R7; needs R12 (SB) set */
#define WAVE(c) \
ISB; \
MOVW $PHYSCONS, R7; \
MOVW $(c), R1; \
MOVW R1, (R7); \
ISB
/* new instructions */
#define CLZ(s, d) WORD $(0xe16f0f10 | (d) << 12 | (s)) /* count leading 0s */
#define DMB \
MCR CpSC, 0, R0, C(CpCACHE), C(CpCACHEwb), CpCACHEdmbarr
/*
* data synchronisation barrier (formerly drain write buffer).
* waits for cache flushes, eviction buffer drain, tlb flushes,
* branch-prediction flushes, writes to memory; the lot.
* on sheeva, also flushes L2 eviction buffer.
* zeroes R0.
*/
#define DSB \
MOVW $0, R0; \
MCR CpSC, 0, R0, C(CpCACHE), C(CpCACHEwb), CpCACHEwait
/*
* prefetch flush; zeroes R0.
* arm926ej-s manual says we need to sync with l2 cache in isb,
* and uncached load is the easiest way. doesn't seem to matter.
*/
#define ISB \
MOVW $0, R0; \
MCR CpSC, 0, R0, C(CpCACHE), C(CpCACHEinvi), CpCACHEwait
// MOVW (R0), R0; MOVW $0, R0
/* zeroes R0 */
#define BARRIERS ISB; DSB
/*
* invoked with PTE bits in R2, pa in R3, PTE pointed to by R4.
* fill PTE pointed to by R4 and increment R4 past it.
* increment R3 by a MB. clobbers R1.
*/
#define FILLPTE() \
ORR R3, R2, R1; /* pte bits in R2, pa in R3 */ \
MOVW R1, (R4); \
ADD $4, R4; /* bump PTE address */ \
ADD $MiB, R3; /* bump pa */ \
/* zero PTE pointed to by R4 and increment R4 past it. assumes R0 is 0. */
#define ZEROPTE() \
MOVW R0, (R4); \
ADD $4, R4; /* bump PTE address */
|
9front/9front
| 5,909
|
sys/src/9/kw/lexception.s
|
/*
* arm exception handlers
*/
#include "arm.s"
#undef B /* B is for 'botch' */
/*
* exception vectors, copied by trapinit() to somewhere useful
*/
TEXT vectors(SB), 1, $-4
MOVW 0x18(R15), R15 /* reset */
MOVW 0x18(R15), R15 /* undefined instr. */
MOVW 0x18(R15), R15 /* SWI & SMC */
MOVW 0x18(R15), R15 /* prefetch abort */
MOVW 0x18(R15), R15 /* data abort */
MOVW 0x18(R15), R15 /* reserved */
MOVW 0x18(R15), R15 /* IRQ */
MOVW 0x18(R15), R15 /* FIQ */
TEXT vtable(SB), 1, $-4
WORD $_vsvc(SB) /* reset, in svc mode already */
WORD $_vund(SB) /* undefined, switch to svc mode */
WORD $_vsvc(SB) /* swi, in svc mode already */
WORD $_vpabt(SB) /* prefetch abort, switch to svc mode */
WORD $_vdabt(SB) /* data abort, switch to svc mode */
WORD $_vsvc(SB) /* reserved */
WORD $_virq(SB) /* IRQ, switch to svc mode */
// WORD $_vfiq(SB) /* FIQ, switch to svc mode */
WORD $_virq(SB) /* FIQ, switch to svc mode */
TEXT _vrst(SB), 1, $-4
BL _reset(SB)
TEXT _vsvc(SB), 1, $-4 /* SWI */
MOVW.W R14, -4(R13) /* ureg->pc = interrupted PC */
MOVW SPSR, R14 /* ureg->psr = SPSR */
MOVW.W R14, -4(R13) /* ... */
MOVW $PsrMsvc, R14 /* ureg->type = PsrMsvc */
MOVW.W R14, -4(R13) /* ... */
/* avoid the ambiguity described in notes/movm.w. */
// MOVM.DB.W.S [R0-R14], (R13) /* save user level registers, at end r13 points to ureg */
MOVM.DB.S [R0-R14], (R13) /* save user level registers */
SUB $(15*4), R13 /* r13 now points to ureg */
MOVW $setR12(SB), R12 /* Make sure we've got the kernel's SB loaded */
// MOVW $(KSEG0+16*KiB-MACHSIZE), R10 /* m */
MOVW $(L1-MACHSIZE), R10 /* m */
MOVW 8(R10), R9 /* up */
MOVW R13, R0 /* first arg is pointer to ureg */
SUB $8, R13 /* space for argument+link */
BL syscall(SB)
ADD $(8+4*15), R13 /* make r13 point to ureg->type */
MOVW 8(R13), R14 /* restore link */
MOVW 4(R13), R0 /* restore SPSR */
MOVW R0, SPSR /* ... */
MOVM.DB.S (R13), [R0-R14] /* restore registers */
ADD $8, R13 /* pop past ureg->{type+psr} */
RFE /* MOVM.IA.S.W (R13), [R15] */
TEXT _vund(SB), 1, $-4 /* undefined */
MOVM.IA [R0-R4], (R13) /* free some working space */
MOVW $PsrMund, R0
B _vswitch
TEXT _vpabt(SB), 1, $-4 /* prefetch abort */
MOVM.IA [R0-R4], (R13) /* free some working space */
MOVW $PsrMabt, R0 /* r0 = type */
B _vswitch
TEXT _vdabt(SB), 1, $-4 /* data abort */
MOVM.IA [R0-R4], (R13) /* free some working space */
MOVW $(PsrMabt+1), R0 /* r0 = type */
B _vswitch
TEXT _virq(SB), 1, $-4 /* IRQ */
MOVM.IA [R0-R4], (R13) /* free some working space */
MOVW $PsrMirq, R0 /* r0 = type */
B _vswitch
/*
* come here with type in R0 and R13 pointing above saved [r0-r4].
* we'll switch to SVC mode and then call trap.
*/
_vswitch:
MOVW SPSR, R1 /* save SPSR for ureg */
MOVW R14, R2 /* save interrupted pc for ureg */
MOVW R13, R3 /* save pointer to where the original [R0-R4] are */
/*
* switch processor to svc mode. this switches the banked registers
* (r13 [sp] and r14 [link]) to those of svc mode.
*/
MOVW CPSR, R14
BIC $PsrMask, R14
ORR $(PsrDirq|PsrDfiq|PsrMsvc), R14
MOVW R14, CPSR /* switch! */
AND.S $0xf, R1, R4 /* interrupted code kernel or user? */
BEQ _userexcep
/* here for trap from SVC mode */
MOVM.DB.W [R0-R2], (R13) /* set ureg->{type, psr, pc}; r13 points to ureg->type */
MOVM.IA (R3), [R0-R4] /* restore [R0-R4] from previous mode's stack */
/*
* avoid the ambiguity described in notes/movm.w.
* In order to get a predictable value in R13 after the stores,
* separate the store-multiple from the stack-pointer adjustment.
* We'll assume that the old value of R13 should be stored on the stack.
*/
/* save kernel level registers, at end r13 points to ureg */
// MOVM.DB.W [R0-R14], (R13)
MOVM.DB [R0-R14], (R13)
SUB $(15*4), R13 /* SP now points to saved R0 */
MOVW $setR12(SB), R12 /* Make sure we've got the kernel's SB loaded */
MOVW R13, R0 /* first arg is pointer to ureg */
SUB $(4*2), R13 /* space for argument+link (for debugger) */
MOVW $0xdeaddead, R11 /* marker */
BL trap(SB)
ADD $(4*2+4*15), R13 /* make r13 point to ureg->type */
MOVW 8(R13), R14 /* restore link */
MOVW 4(R13), R0 /* restore SPSR */
MOVW R0, SPSR /* ... */
MOVM.DB (R13), [R0-R14] /* restore registers */
ADD $(4*2), R13 /* pop past ureg->{type+psr} to pc */
RFE /* MOVM.IA.S.W (R13), [R15] */
/* here for trap from USER mode */
_userexcep:
MOVM.DB.W [R0-R2], (R13) /* set ureg->{type, psr, pc}; r13 points to ureg->type */
MOVM.IA (R3), [R0-R4] /* restore [R0-R4] from previous mode's stack */
/* avoid the ambiguity described in notes/movm.w. */
// MOVM.DB.W.S [R0-R14], (R13) /* save kernel level registers, at end r13 points to ureg */
MOVM.DB.S [R0-R14], (R13) /* save kernel level registers */
SUB $(15*4), R13 /* r13 now points to ureg */
MOVW $setR12(SB), R12 /* Make sure we've got the kernel's SB loaded */
// MOVW $(KSEG0+16*KiB-MACHSIZE), R10 /* m */
MOVW $(L1-MACHSIZE), R10 /* m */
MOVW 8(R10), R9 /* up */
MOVW R13, R0 /* first arg is pointer to ureg */
SUB $(4*2), R13 /* space for argument+link (for debugger) */
BL trap(SB)
ADD $(4*2+4*15), R13 /* make r13 point to ureg->type */
MOVW 8(R13), R14 /* restore link */
MOVW 4(R13), R0 /* restore SPSR */
MOVW R0, SPSR /* ... */
MOVM.DB.S (R13), [R0-R14] /* restore registers */
ADD $(4*2), R13 /* pop past ureg->{type+psr} */
RFE /* MOVM.IA.S.W (R13), [R15] */
TEXT _vfiq(SB), 1, $-4 /* FIQ */
RFE /* FIQ is special, ignore it for now */
/*
* set the stack value for the mode passed in R0
*/
TEXT setr13(SB), 1, $-4
MOVW 4(FP), R1
MOVW CPSR, R2
BIC $PsrMask, R2, R3
ORR R0, R3
MOVW R3, CPSR /* switch to new mode */
MOVW R13, R0 /* return old sp */
MOVW R1, R13 /* install new one */
MOVW R2, CPSR /* switch back to old mode */
RET
|
9front/9front
| 4,052
|
sys/src/9/kw/rebootcode.s
|
/*
* sheevaplug reboot code
*
* R11 is used by the loader as a temporary, so avoid it.
*/
#include "arm.s"
/*
* Turn off MMU, then copy the new kernel to its correct location
* in physical memory. Then jump to the start of the kernel.
*/
/* main(PADDR(entry), PADDR(code), size); */
TEXT main(SB), 1, $-4
MOVW $setR12(SB), R12
MOVW R0, p1+0(FP) /* destination, passed in R0 */
/* copy in arguments from frame */
MOVW R0, R8 /* entry point */
MOVW p2+4(FP), R9 /* source */
MOVW n+8(FP), R10 /* byte count */
WAVE('R')
BL cachesoff(SB)
/* now back in 29- or 26-bit addressing, mainly for SB */
/* turn the MMU off */
WAVE('e')
MOVW $KSEGM, R7
MOVW $PHYSDRAM, R0
BL _r15warp(SB)
BIC R7, R12 /* SB */
BIC R7, R13 /* SP */
/* don't care about R14 */
WAVE('b')
BL mmuinvalidate(SB)
WAVE('o')
BL mmudisable(SB)
WAVE('o')
MOVW R9, R4 /* restore regs across function calls */
MOVW R10, R5
MOVW R8, R6
/* set up a new stack for local vars and memmove args */
MOVW R6, SP /* tiny trampoline stack */
SUB $(0x20 + 4), SP /* back up before a.out header */
MOVW R14, -48(SP) /* store return addr */
SUB $48, SP /* allocate stack frame */
MOVW R6, 44(SP) /* save dest/entry */
MOVW R5, 40(SP) /* save count */
WAVE('t')
MOVW R6, 0(SP)
MOVW R6, 4(SP) /* push dest */
MOVW R6, R0
MOVW R4, 8(SP) /* push src */
MOVW R5, 12(SP) /* push size */
BL memmove(SB)
MOVW 44(SP), R6 /* restore R6 (dest/entry) */
MOVW 40(SP), R5 /* restore R5 (count) */
WAVE('-')
/*
* flush caches
*/
BL cacheuwbinv(SB)
WAVE('>')
WAVE('\r');
WAVE('\n');
/*
* jump to kernel entry point. Note the true kernel entry point is
* the virtual address KZERO|R6, but this must wait until
* the MMU is enabled by the kernel in l.s
*/
ORR R6, R6 /* NOP: avoid link bug */
B (R6)
/*
* turn the caches off, double map 0 & KZERO, invalidate TLBs, revert to
* tiny addresses. upon return, it will be safe to turn off the mmu.
*/
TEXT cachesoff(SB), 1, $-4
MOVW $(PsrDirq|PsrDfiq|PsrMsvc), R0
MOVW R0, CPSR
MOVW $KADDR(0x100-4), R7 /* just before this code */
MOVW R14, (R7) /* save link */
BL cacheuwbinv(SB)
MRC CpSC, 0, R0, C(CpCONTROL), C(0)
BIC $(CpCwb|CpCicache|CpCdcache|CpCalign), R0
MCR CpSC, 0, R0, C(CpCONTROL), C(0)
BARRIERS
/* redo double map of 0, KZERO */
MOVW $(L1+L1X(PHYSDRAM)), R4 /* address of PTE for 0 */
MOVW $PTEDRAM, R2 /* PTE bits */
// MOVW $PTEIO, R2 /* PTE bits */
MOVW $PHYSDRAM, R3
MOVW $512, R5
_ptrdbl:
ORR R3, R2, R1 /* first identity-map 0 to 0, etc. */
MOVW R1, (R4)
ADD $4, R4 /* bump PTE address */
ADD $MiB, R3 /* bump pa */
SUB.S $1, R5
BNE _ptrdbl
BARRIERS
MOVW $0, R0
MCR CpSC, 0, R0, C(CpTLB), C(CpTLBinvd), CpTLBinv
MCR CpSC, 0, R0, C(CpTLB), C(CpTLBinvu), CpTLBinv
BARRIERS
/* back to 29- or 26-bit addressing, mainly for SB */
MRC CpSC, 0, R0, C(CpCONTROL), C(0)
BIC $(CpCd32|CpCi32), R0
MCR CpSC, 0, R0, C(CpCONTROL), C(0)
BARRIERS
MOVW $KADDR(0x100-4), R7 /* just before this code */
MOVW (R7), R14 /* restore link */
RET
TEXT _r15warp(SB), 1, $-4
BIC $KSEGM, R14
ORR R0, R14
RET
TEXT mmudisable(SB), 1, $-4
MRC CpSC, 0, R0, C(CpCONTROL), C(0)
BIC $(CpChv|CpCmmu|CpCdcache|CpCicache|CpCwb), R0
MCR CpSC, 0, R0, C(CpCONTROL), C(0)
BARRIERS
RET
TEXT mmuinvalidate(SB), 1, $-4 /* invalidate all */
MOVW $0, R0
MCR CpSC, 0, R0, C(CpTLB), C(CpTLBinvu), CpTLBinv
BARRIERS
RET
TEXT cacheuwbinv(SB), 1, $-4 /* D+I writeback+invalidate */
BARRIERS
MOVW CPSR, R3 /* splhi */
ORR $(PsrDirq), R3, R1
MOVW R1, CPSR
_uwbinv: /* D writeback+invalidate */
MRC CpSC, 0, PC, C(CpCACHE), C(CpCACHEwbi), CpCACHEtest
BNE _uwbinv
MOVW $0, R0 /* I invalidate */
MCR CpSC, 0, R0, C(CpCACHE), C(CpCACHEinvi), CpCACHEall
/* drain L1 write buffer, also drains L2 eviction buffer on sheeva */
BARRIERS
MCR CpSC, CpL2, R0, C(CpTESTCFG), C(CpTCl2flush), CpTCl2all
BARRIERS
MCR CpSC, CpL2, R0, C(CpTESTCFG), C(CpTCl2inv), CpTCl2all
BARRIERS
MOVW R3, CPSR /* splx */
RET
|
9front/9front
| 14,584
|
sys/src/9/sgi/l.s
|
#include "mem.h"
#define SP R29
#define NOOP NOR R0, R0, R0
#define WAIT NOOP; NOOP
#define RETURN RET; NOOP
#define CONST(i, v) MOVW $((i) & 0xffff0000), v; OR $((i) & 0xffff), v;
#define GETMACH(r) CONST(MACHADDR, r)
/*
* R4000 instructions
*/
#define ERET WORD $0x42000018
#define LL(base, rt) WORD $((060<<26)|((base)<<21)|((rt)<<16))
#define SC(base, rt) WORD $((070<<26)|((base)<<21)|((rt)<<16))
#define MFC0(src,sel,dst) WORD $(0x40000000|((src)<<11)|((dst)<<16)|(sel))
#define MTC0(src,dst,sel) WORD $(0x40800000|((dst)<<11)|((src)<<16)|(sel))
#define RDHWR(hwr, r) WORD $(0x7c00003b|((hwr)<<11)|((r)<<16))
/*
* cache manipulation
*/
#define CACHE BREAK /* overloaded op-code */
#define PI R((0 /* primary I cache */
#define PD R((1 /* primary D cache */
#define SD R((3 /* secondary combined I/D cache */
#define IWBI (0<<2))) /* index write-back invalidate */
#define ILT (1<<2))) /* index load tag */
#define IST (2<<2))) /* index store tag */
#define CDE (3<<2))) /* create dirty exclusive */
#define HINV (4<<2))) /* hit invalidate */
#define HWBI (5<<2))) /* hit write back invalidate */
#define HWB (6<<2))) /* hit write back */
#define HSV (7<<2))) /* hit set virtual */
NOSCHED
/*
* Boot only processor
*/
TEXT start(SB), $-4
MOVW $setR30(SB), R30
MOVW $CU1, R1
MOVW R1, M(STATUS)
WAIT
MOVW $(0x1C<<7), R1
MOVW R1, FCR31 /* permit only inexact and underflow */
NOOP
MOVD $0.5, F26
SUBD F26, F26, F24
ADDD F26, F26, F28
ADDD F28, F28, F30
MOVD F24, F0
MOVD F24, F2
MOVD F24, F4
MOVD F24, F6
MOVD F24, F8
MOVD F24, F10
MOVD F24, F12
MOVD F24, F14
MOVD F24, F16
MOVD F24, F18
MOVD F24, F20
MOVD F24, F22
MOVW $MACHADDR, R(MACH)
ADDU $(MACHSIZE-BY2V), R(MACH), SP
MOVW R(MACH), R1
clrmach:
MOVW R0, (R1)
ADDU $BY2WD, R1
BNE R1, SP, clrmach
NOOP
MOVW $edata(SB), R1
MOVW $end(SB), R2
clrbss:
MOVB R0, (R1)
ADDU $1, R1
BNE R1, R2, clrbss
NOOP
MOVW R0, 0(R(MACH)) /* m->machno = 0 */
MOVW R0, R(USER) /* up = nil */
JAL main(SB)
NOOP
TEXT arcs(SB), $256
MOVW R24, 0x80(SP)
MOVW R25, 0x84(SP)
MOVW R26, 0x88(SP)
MOVW R27, 0x8C(SP)
MOVW $SPBADDR, R4
MOVW 0x20(R4), R5
ADDU R1, R5
MOVW (R5), R2
MOVW 16(FP), R7
MOVW 12(FP), R6
MOVW 8(FP), R5
MOVW 4(FP), R4
JAL (R2)
NOOP
MOVW $setR30(SB), R30
MOVW 0x80(SP), R24
MOVW 0x84(SP), R25
MOVW 0x88(SP), R26
MOVW 0x8C(SP), R27
MOVW R2, R1
RETURN
/*
* Take first processor into user mode
* - argument is stack pointer to user
*/
TEXT touser(SB), $-4
MOVW M(STATUS), R4
MOVW $(UTZERO+32), R2 /* header appears in text */
MOVW R2, M(EPC)
MOVW R1, SP
AND $(~KMODEMASK), R4
OR $(KUSER|IE|EXL), R4 /* switch to user mode, intrs on, exc */
MOVW R4, M(STATUS) /* " */
WAIT
ERET /* clears EXL */
NOOP
/*
* manipulate interrupts
*/
/* enable an interrupt; bit is in R1 */
TEXT intron(SB), $0
MOVW M(STATUS), R2
WAIT
OR R1, R2
MOVW R2, M(STATUS)
WAIT
RETURN
/* disable an interrupt; bit is in R1 */
TEXT introff(SB), $0
MOVW M(STATUS), R2
WAIT
XOR $-1, R1
AND R1, R2
MOVW R2, M(STATUS)
WAIT
RETURN
TEXT splhi(SB), $0
MOVW R31, 12(R(MACH)) /* save PC in m->splpc */
MOVW M(STATUS), R1
WAIT
AND $~IE, R1, R2
MOVW R2, M(STATUS)
WAIT
RETURN
TEXT splx(SB), $0
MOVW R31, 12(R(MACH)) /* save PC in m->splpc */
MOVW M(STATUS), R2
WAIT
AND $IE, R1
AND $~IE, R2
OR R2, R1
MOVW R1, M(STATUS)
WAIT
RETURN
TEXT spllo(SB), $0
MOVW M(STATUS), R1
WAIT
OR $IE, R1, R2
MOVW R2, M(STATUS)
WAIT
RETURN
TEXT spldone(SB), $0
RETURN
TEXT islo(SB), $0
MOVW M(STATUS), R1
WAIT
AND $IE, R1
RETURN
TEXT coherence(SB), $-4
RETURN
/*
* process switching
*/
TEXT setlabel(SB), $-4
MOVW SP, 0(R1)
MOVW R31, 4(R1)
MOVW R0, R1
RETURN
TEXT gotolabel(SB), $-4
MOVW 0(R1), SP
MOVW 4(R1), R31
MOVW $1, R1
RETURN
/*
* the tlb routines need to be called at splhi.
*/
TEXT getwired(SB),$0
MOVW M(WIRED), R1
RETURN
TEXT setwired(SB),$0
MOVW R1, M(WIRED)
RETURN
TEXT getrandom(SB),$0
MOVW M(RANDOM), R1
RETURN
TEXT getpagemask(SB),$0
MOVW M(PAGEMASK), R1
RETURN
TEXT setpagemask(SB),$0
MOVW R1, M(PAGEMASK)
MOVW R0, R1 /* prevent accidents */
RETURN
TEXT puttlbx(SB), $0 /* puttlbx(index, virt, phys0, phys1, pagemask) */
MOVW 4(FP), R2
MOVW 8(FP), R3
MOVW 12(FP), R4
MOVW $((2*BY2PG-1) & ~0x1fff), R5
MOVW R2, M(TLBVIRT)
MOVW R3, M(TLBPHYS0)
MOVW R4, M(TLBPHYS1)
MOVW R5, M(PAGEMASK)
MOVW R1, M(INDEX)
NOOP
NOOP
TLBWI
NOOP
RETURN
TEXT tlbvirt(SB), $0
MOVW M(TLBVIRT), R1
NOOP
RETURN
TEXT gettlbx(SB), $0 /* gettlbx(index, &entry) */
MOVW 4(FP), R4
MOVW R1, M(INDEX)
NOOP
NOOP
TLBR
NOOP
NOOP
NOOP
MOVW M(TLBVIRT), R1
MOVW M(TLBPHYS0), R2
MOVW M(TLBPHYS1), R3
NOOP
MOVW R1, 0(R4)
MOVW R2, 4(R4)
MOVW R3, 8(R4)
RETURN
TEXT gettlbp(SB), $0 /* gettlbp(tlbvirt, &entry) */
MOVW 4(FP), R5
MOVW R1, M(TLBVIRT)
NOOP
NOOP
NOOP
TLBP
NOOP
NOOP
MOVW M(INDEX), R1
NOOP
BLTZ R1, gettlbp1
TLBR
NOOP
NOOP
NOOP
MOVW M(TLBVIRT), R2
MOVW M(TLBPHYS0), R3
MOVW M(TLBPHYS1), R4
NOOP
MOVW R2, 0(R5)
MOVW R3, 4(R5)
MOVW R4, 8(R5)
gettlbp1:
RETURN
TEXT gettlbvirt(SB), $0 /* gettlbvirt(index) */
MOVW R1, M(INDEX)
NOOP
NOOP
TLBR
NOOP
NOOP
NOOP
MOVW M(TLBVIRT), R1
NOOP
RETURN
/*
* compute stlb hash index.
*
* M(TLBVIRT) [page & asid] in arg, result in arg.
* stir in swizzled asid; we get best results with asid in both high & low bits.
*/
#define STLBHASH(arg, tmp) \
AND $0xFF, arg, tmp; \
SRL $(PGSHIFT+1), arg; \
XOR tmp, arg; \
SLL $(STLBLOG-8), tmp; \
XOR tmp, arg; \
CONST (STLBSIZE-1, tmp); \
AND tmp, arg
TEXT stlbhash(SB), $0 /* for mmu.c */
STLBHASH(R1, R2)
RETURN
TEXT utlbmiss(SB), $-4
GETMACH (R26)
MOVW R27, 12(R26) /* m->splpc = R27 */
MOVW 16(R26), R27
ADDU $1, R27
MOVW R27,16(R26) /* m->tlbfault++ */
MOVW M(TLBVIRT), R27
NOOP
STLBHASH(R27, R26)
/* scale to a byte index (multiply by 12) */
SLL $1, R27, R26 /* × 2 */
ADDU R26, R27 /* × 3 */
SLL $2, R27 /* × 12 */
GETMACH (R26)
MOVW 4(R26), R26
ADDU R26, R27 /* R27 = &m->stb[hash] */
MOVW M(BADVADDR), R26
NOOP
AND $BY2PG, R26
BNE R26, utlbodd /* odd page? */
NOOP
utlbeven:
MOVW 4(R27), R26 /* R26 = m->stb[hash].phys0 */
BEQ R26, stlbm /* nothing cached? do it the hard way */
NOOP
MOVW R26, M(TLBPHYS0)
MOVW 8(R27), R26 /* R26 = m->stb[hash].phys1 */
JMP utlbcom
MOVW R26, M(TLBPHYS1) /* branch delay slot */
utlbodd:
MOVW 8(R27), R26 /* R26 = m->stb[hash].phys1 */
BEQ R26, stlbm /* nothing cached? do it the hard way */
NOOP
MOVW R26, M(TLBPHYS1)
MOVW 4(R27), R26 /* R26 = m->stb[hash].phys0 */
MOVW R26, M(TLBPHYS0)
utlbcom:
WAIT
MOVW M(TLBVIRT), R26
MOVW 0(R27), R27 /* R27 = m->stb[hash].virt */
BEQ R27, stlbm /* nothing cached? do it the hard way */
NOOP
/* is the stlb entry for the right virtual address? */
BNE R26, R27, stlbm /* M(TLBVIRT) != m->stb[hash].virt? */
NOOP
/* if an entry exists, overwrite it, else write a random one */
CONST (PGSZ, R27)
MOVW R27, M(PAGEMASK) /* select page size */
TLBP /* probe tlb */
NOOP
NOOP
MOVW M(INDEX), R26
NOOP
BGEZ R26, utlbindex /* if tlb entry found, rewrite it */
NOOP
MOVW M(RANDOM), R26
MOVW R26, M(INDEX)
utlbindex:
NOOP
NOOP
TLBWI /* write indexed tlb entry */
NOOP
utlbret:
GETMACH (R26)
MOVW 12(R26), R27 /* R27 = m->splpc */
MOVW M(EPC), R26
JMP (R27)
NOOP
stlbm:
GETMACH (R26)
MOVW 12(R26), R27 /* R27 = m->splpc */
/* fall through */
TEXT gevector(SB), $-4
MOVW M(STATUS), R26
WAIT
AND $KUSER, R26
BNE R26, wasuser
MOVW SP, R26 /* delay slot, old SP in R26 */
waskernel:
JMP dosave
SUBU $UREGSIZE, SP /* delay slot, allocate frame on kernel stack */
wasuser: /* get kernel stack for this user process */
GETMACH (SP)
MOVW 8(SP), SP /* m->proc */
SUBU $(UREGSIZE), SP
dosave:
MOVW R31, 0x28(SP)
JAL saveregs(SB)
MOVW R26, 0x10(SP) /* delay slot, save old SP */
GETMACH (R(MACH))
MOVW 8(R(MACH)), R(USER) /* R24 = m->proc */
MOVW $setR30(SB), R30
BEQ R26, dosys /* set by saveregs() */
NOOP
dotrap:
MOVW $forkret(SB), R31
JMP trap(SB)
MOVW 4(SP), R1 /* delay slot, first arg to trap() */
dosys:
JAL syscall(SB)
MOVW 4(SP), R1 /* delay slot, first arg to syscall() */
/* fall through */
TEXT forkret(SB), $-4
JAL restregs(SB) /* restores old PC in R26 */
MOVW 0x14(SP), R1 /* delay slot, CAUSE */
MOVW 0x28(SP), R31
JMP (R27)
MOVW 0x10(SP), SP /* delay slot */
/*
* SP-> 0x00 --- (spill R31)
* 0x04 --- (trap()/syscall() arg1)
* 0x08 status
* 0x0C pc
* 0x10 sp/usp
* 0x14 cause
* 0x18 badvaddr
* 0x1C tlbvirt
* 0x20 hi
* 0x24 lo
* 0x28 r31
* .....
* 0x9c r1
*/
TEXT saveregs(SB), $-4
MOVW R1, 0x9C(SP)
MOVW R2, 0x98(SP)
MOVW M(STATUS), R2
ADDU $8, SP, R1
MOVW R1, 0x04(SP) /* arg to base of regs */
MOVW $~KMODEMASK, R1
AND R2, R1
MOVW R1, M(STATUS) /* so we can take another trap */
MOVW R2, 0x08(SP)
MOVW M(EPC), R2
MOVW M(CAUSE), R1
MOVW R2, 0x0C(SP)
MOVW R1, 0x14(SP)
AND $(EXCMASK<<2), R1
SUBU $(CSYS<<2), R1, R26
BEQ R26, notsaved /* is syscall? */
MOVW R27, 0x34(SP) /* delay slot */
MOVW M(BADVADDR), R1
MOVW M(TLBVIRT), R2
MOVW R1, 0x18(SP)
MOVW R2, 0x1C(SP)
MOVW HI, R1
MOVW LO, R2
MOVW R1, 0x20(SP)
MOVW R2, 0x24(SP)
MOVW R25, 0x3C(SP)
MOVW R24, 0x40(SP)
MOVW R23, 0x44(SP)
MOVW R22, 0x48(SP)
MOVW R21, 0x4C(SP)
MOVW R20, 0x50(SP)
MOVW R19, 0x54(SP)
MOVW R18, 0x58(SP)
MOVW R17, 0x5C(SP)
MOVW R16, 0x60(SP)
MOVW R15, 0x64(SP)
MOVW R14, 0x68(SP)
MOVW R13, 0x6C(SP)
MOVW R12, 0x70(SP)
MOVW R11, 0x74(SP)
MOVW R10, 0x78(SP)
MOVW R9, 0x7C(SP)
MOVW R8, 0x80(SP)
MOVW R7, 0x84(SP)
MOVW R6, 0x88(SP)
MOVW R5, 0x8C(SP)
MOVW R4, 0x90(SP)
MOVW R3, 0x94(SP)
notsaved:
MOVW R30, 0x2C(SP)
RET
MOVW R28, 0x30(SP) /* delay slot */
TEXT restregs(SB), $-4
AND $(EXCMASK<<2), R1
SUBU $(CSYS<<2), R1, R26
BEQ R26, notrestored /* is syscall? */
MOVW 0x34(SP), R27 /* delay slot */
MOVW 0x3C(SP), R25
MOVW 0x40(SP), R24
MOVW 0x44(SP), R23
MOVW 0x48(SP), R22
MOVW 0x4C(SP), R21
MOVW 0x50(SP), R20
MOVW 0x54(SP), R19
MOVW 0x58(SP), R18
MOVW 0x5C(SP), R17
MOVW 0x60(SP), R16
MOVW 0x64(SP), R15
MOVW 0x68(SP), R14
MOVW 0x6C(SP), R13
MOVW 0x70(SP), R12
MOVW 0x74(SP), R11
MOVW 0x78(SP), R10
MOVW 0x7C(SP), R9
MOVW 0x80(SP), R8
MOVW 0x84(SP), R7
MOVW 0x88(SP), R6
MOVW 0x8C(SP), R5
MOVW 0x90(SP), R4
MOVW 0x94(SP), R3
MOVW 0x24(SP), R2
MOVW 0x20(SP), R1
MOVW R2, LO
MOVW R1, HI
MOVW 0x98(SP), R2
notrestored:
MOVW 0x08(SP), R1
MOVW R1, M(STATUS)
MOVW 0x0C(SP), R26 /* old PC */
MOVW R26, M(EPC)
MOVW 0x30(SP), R28
MOVW 0x2C(SP), R30
RET
MOVW 0x9C(SP), R1 /* delay slot */
/*
* hardware interrupt vectors
*/
TEXT vector0(SB), $-4
WAIT
CONST (SPBADDR+0x18, R26)
MOVW $eret(SB), R27
MOVW (R26), R26
JMP (R26)
NOOP
TEXT vector180(SB), $-4
WAIT
CONST (SPBADDR+0x14, R26)
MOVW $eret(SB), R27
MOVW (R26), R26
JMP (R26)
NOOP
TEXT eret(SB), $-4
ERET
NOOP
/*
* floating-point stuff
*/
TEXT clrfpintr(SB), $0
MOVW M(STATUS), R3
WAIT
OR $CU1, R3
MOVW R3, M(STATUS)
NOOP
NOOP
NOOP
MOVW FCR31, R1
MOVW R1, R2
AND $~(0x3F<<12), R2
MOVW R2, FCR31
AND $~CU1, R3
MOVW R3, M(STATUS)
WAIT
RETURN
TEXT savefpregs(SB), $0
MOVW FCR31, R2
MOVW M(STATUS), R3
WAIT
AND $~(0x3F<<12), R2, R4
MOVW R4, FCR31
MOVD F0, 0x00(R1)
MOVD F2, 0x08(R1)
MOVD F4, 0x10(R1)
MOVD F6, 0x18(R1)
MOVD F8, 0x20(R1)
MOVD F10, 0x28(R1)
MOVD F12, 0x30(R1)
MOVD F14, 0x38(R1)
MOVD F16, 0x40(R1)
MOVD F18, 0x48(R1)
MOVD F20, 0x50(R1)
MOVD F22, 0x58(R1)
MOVD F24, 0x60(R1)
MOVD F26, 0x68(R1)
MOVD F28, 0x70(R1)
MOVD F30, 0x78(R1)
MOVW R2, 0x80(R1)
AND $~CU1, R3
MOVW R3, M(STATUS)
WAIT
RETURN
TEXT restfpregs(SB), $0
MOVW M(STATUS), R3
WAIT
OR $CU1, R3
MOVW R3, M(STATUS)
WAIT
MOVW fpstat+4(FP), R2
NOOP
MOVD 0x00(R1), F0
MOVD 0x08(R1), F2
MOVD 0x10(R1), F4
MOVD 0x18(R1), F6
MOVD 0x20(R1), F8
MOVD 0x28(R1), F10
MOVD 0x30(R1), F12
MOVD 0x38(R1), F14
MOVD 0x40(R1), F16
MOVD 0x48(R1), F18
MOVD 0x50(R1), F20
MOVD 0x58(R1), F22
MOVD 0x60(R1), F24
MOVD 0x68(R1), F26
MOVD 0x70(R1), F28
MOVD 0x78(R1), F30
MOVW R2, FCR31
AND $~CU1, R3
MOVW R3, M(STATUS)
WAIT
RETURN
TEXT fcr31(SB), $0 /* fp csr */
MOVW FCR31, R1
RETURN
/*
* Emulate 68020 test and set: load linked / store conditional
*/
TEXT tas(SB), $0
TEXT _tas(SB), $0
MOVW R1, R2 /* address of key */
tas1:
MOVW $1, R3
LL(2, 1)
NOOP
SC(2, 3)
NOOP
BEQ R3, tas1
NOOP
RETURN
/* used by the semaphore implementation */
TEXT cmpswap(SB), $0
MOVW R1, R2 /* address of key */
MOVW old+4(FP), R3 /* old value */
MOVW new+8(FP), R4 /* new value */
LL(2, 1) /* R1 = (R2) */
NOOP
BNE R1, R3, fail
NOOP
MOVW R4, R1
SC(2, 1) /* (R2) = R1 if (R2) hasn't changed; R1 = success */
NOOP
RETURN
fail:
MOVW R0, R1
RETURN
/*
* cache manipulation
*/
TEXT icflush(SB), $-4 /* icflush(virtaddr, count) */
MOVW M(STATUS), R10
WAIT
MOVW 4(FP), R9
MOVW $0, M(STATUS)
WAIT
ADDU R1, R9 /* R9 = last address */
MOVW $(~0x3f), R8
AND R1, R8 /* R8 = first address, rounded down */
ADDU $0x3f, R9
AND $(~0x3f), R9 /* round last address up */
SUBU R8, R9 /* R9 = revised count */
icflush1: /* primary cache line size is 16 bytes */
CACHE PD+HWB, 0x00(R8)
CACHE PI+HINV, 0x00(R8)
CACHE PD+HWB, 0x10(R8)
CACHE PI+HINV, 0x10(R8)
CACHE PD+HWB, 0x20(R8)
CACHE PI+HINV, 0x20(R8)
CACHE PD+HWB, 0x30(R8)
CACHE PI+HINV, 0x30(R8)
SUBU $0x40, R9
ADDU $0x40, R8
BGTZ R9, icflush1
MOVW R10, M(STATUS)
WAIT
RETURN
TEXT dcflush(SB), $-4 /* dcflush(virtaddr, count) */
MOVW M(STATUS), R10
WAIT
MOVW 4(FP), R9
MOVW $0, M(STATUS)
WAIT
ADDU R1, R9 /* R9 = last address */
MOVW $(~0x3f), R8
AND R1, R8 /* R8 = first address, rounded down */
ADDU $0x3f, R9
AND $(~0x3f), R9 /* round last address up */
SUBU R8, R9 /* R9 = revised count */
dcflush1: /* primary cache line size is 16 bytes */
CACHE PD+HWB, 0x00(R8)
CACHE PD+HWB, 0x10(R8)
CACHE PD+HWB, 0x20(R8)
CACHE PD+HWB, 0x30(R8)
SUBU $0x40, R9
ADDU $0x40, R8
BGTZ R9, dcflush1
MOVW R10, M(STATUS)
WAIT
RETURN
TEXT outl(SB), $0
MOVW 4(FP), R2
MOVW 8(FP), R3
SLL $2, R3
ADDU R2, R3
outl1:
BEQ R2, R3, outl2
MOVW (R2), R4
MOVW R4, (R1)
JMP outl1
ADDU $4, R2
outl2:
RETURN
/*
* access to CP0 registers
*/
TEXT prid(SB), $0
MOVW M(PRID), R1
WAIT
RETURN
TEXT rdcount(SB), $0
MOVW M(COUNT), R1
RETURN
TEXT wrcount(SB), $0
MOVW R1, M(COUNT)
RETURN
TEXT wrcompare(SB), $0
MOVW R1, M(COMPARE)
RETURN
TEXT rdcompare(SB), $0
MOVW M(COMPARE), R1
RETURN
SCHED
|
9front/9front
| 15,295
|
sys/src/9/mt7688/l.s
|
/*
* mips 24k machine assist for mt7688
*/
#include "mem.h"
#include "mips24k.s"
#define SANITY 0x12345678
NOSCHED
/*
* Boot only processor
*/
TEXT start(SB), $-4
MOVW $setR30(SB), R30
DI(0)
MOVW sanity(SB), R1
CONST(SANITY, R2)
SUBU R1, R2, R2
BNE R2, insane
NOP
MOVW R0, M(COMPARE)
EHB
/* don't enable any interrupts nor FP, but leave BEV on. */
MOVW $BEV,R1
MOVW R1, M(STATUS)
UBARRIERS(7, R7, stshb) /* returns to kseg1 space */
MOVW R0, M(CAUSE)
EHB
/* disable watchdog and other resets */
MOVW $(KSEG1|0x10000038), R1
MOVW R0, (R1) /* set no action */
SYNC
MOVW $PE, R1
MOVW R1, M(CACHEECC) /* aka ErrCtl */
EHB
JAL cleancache(SB)
NOOP
MOVW $TLBROFF, R1
MOVW R1, M(WIRED)
MOVW R0, M(CONTEXT)
EHB
/* set KSEG0 cachability before trying LL/SC in lock code */
MOVW M(CONFIG), R1
AND $~CFG_K0, R1
/* make kseg0 cachable, enable write-through merging */
OR $((PTECACHED>>3)|CFG_MM), R1
MOVW R1, M(CONFIG)
BARRIERS(7, R7, cfghb) /* back to kseg0 space */
MOVW $setR30(SB), R30 /* again */
/* initialize Mach, including stack */
MOVW $MACHADDR, R(MACH)
ADDU $(MACHSIZE-BY2V), R(MACH), SP
MOVW R(MACH), R1
clrmach:
MOVW R0, (R1)
ADDU $BY2WD, R1
BNE R1, SP, clrmach
NOOP
MOVW $edata(SB), R1
MOVW $end(SB), R2
clrbss:
MOVB R0, (R1)
ADDU $1, R1
BNE R1, R2, clrbss
NOOP
MOVW $0x16, R16
MOVW $0x17, R17
MOVW $0x18, R18
MOVW $0x19, R19
MOVW $0x20, R20
MOVW $0x21, R21
MOVW $0x22, R22
MOVW $0x23, R23
MOVW R0, HI
MOVW R0, LO
MOVW R0, 0(R(MACH)) /* m->machno = 0 */
MOVW R0, R(USER) /* up = nil */
JAL main(SB)
NOOP
PUTC('X', R1, R2)
NOOP
insane:
PUTC('D', R1, R2)
NOOP
TEXT arcs(SB), $256
MOVW R24, 0x80(SP)
MOVW R25, 0x84(SP)
MOVW R26, 0x88(SP)
MOVW R27, 0x8C(SP)
MOVW $SPBADDR, R4
MOVW 0x20(R4), R5
ADDU R1, R5
MOVW (R5), R2
MOVW 16(FP), R7
MOVW 12(FP), R6
MOVW 8(FP), R5
MOVW 4(FP), R4
JAL (R2)
NOOP
MOVW $setR30(SB), R30
MOVW 0x80(SP), R24
MOVW 0x84(SP), R25
MOVW 0x88(SP), R26
MOVW 0x8C(SP), R27
MOVW R2, R1
RETURN
/*
* Take first processor into user mode
* - argument is stack pointer to user
*/
TEXT touser(SB), $-4
MOVW M(STATUS), R4
MOVW $(UTZERO+32), R2 /* header appears in text */
MOVW R2, M(EPC)
MOVW R1, SP
AND $(~KMODEMASK), R4
OR $(KUSER|IE|EXL), R4 /* switch to user mode, intrs on, exc */
MOVW R4, M(STATUS) /* " */
NOOP
ERET /* clears EXL */
NOOP
/* target for JALRHB in BARRIERS */
TEXT ret(SB), $-4
JMP (R22)
NOP
/* the i and d caches may be different sizes, so clean them separately */
TEXT cleancache(SB), $-4
DI(10) /* intrs off, old status -> R10 */
UBARRIERS(7, R7, cchb); /* return to kseg1 (uncached) */
MOVW R0, R1 /* index, not address */
MOVW $ICACHESIZE, R9
iccache:
CACHE PI+IWBI, (R1) /* flush & invalidate I by index */
SUBU $CACHELINESZ, R9
BGTZ R9, iccache
ADDU $CACHELINESZ, R1 /* delay slot */
BARRIERS(7, R7, cc2hb); /* return to kseg0 (cached) */
MOVW R0, R1 /* index, not address */
MOVW $DCACHESIZE, R9
dccache:
CACHE PD+IWBI, (R1) /* flush & invalidate D by index */
SUBU $CACHELINESZ, R9
BGTZ R9, dccache
ADDU $CACHELINESZ, R1 /* delay slot */
SYNC
MOVW R10, M(STATUS)
JRHB(31) /* return and clear all hazards */
/*
* manipulate interrupts
*/
/* enable an interrupt; bit is in R1 */
TEXT intron(SB), $0
MOVW M(STATUS), R2
OR R1, R2
MOVW R2, M(STATUS)
EHB
RETURN
/* disable an interrupt; bit is in R1 */
TEXT introff(SB), $0
MOVW M(STATUS), R2
XOR $-1, R1
AND R1, R2
MOVW R2, M(STATUS)
EHB
RETURN
TEXT splhi(SB), $0
EHB
MOVW R31, 12(R(MACH)) /* save PC in m->splpc */
DI(1) /* old M(STATUS) into R1 */
EHB
RETURN
TEXT splx(SB), $0
EHB
MOVW R31, 12(R(MACH)) /* save PC in m->splpc */
MOVW M(STATUS), R2
AND $IE, R1
AND $~IE, R2
OR R2, R1
MOVW R1, M(STATUS)
EHB
RETURN
TEXT spllo(SB), $0
EHB
EI(1) /* old M(STATUS) into R1 */
EHB
RETURN
TEXT spldone(SB), $0
RETURN
TEXT islo(SB), $0
MOVW M(STATUS), R1
AND $IE, R1
RETURN
TEXT coherence(SB), $-4
BARRIERS(7, R7, cohhb)
SYNC
EHB
RETURN
TEXT idle(SB), $-4
EI(1) /* old M(STATUS) into R1 */
EHB
/* fall through */
TEXT wait(SB), $-4
WAIT
NOP
MOVW R1, M(STATUS) /* interrupts restored */
EHB
RETURN
/*
* process switching
*/
TEXT setlabel(SB), $-4
MOVW SP, 0(R1)
MOVW R31, 4(R1)
MOVW R0, R1
RETURN
TEXT gotolabel(SB), $-4
MOVW 0(R1), SP
MOVW 4(R1), R31
MOVW $1, R1
RETURN
/*
* the tlb routines need to be called at splhi.
*/
TEXT getwired(SB),$0
MOVW M(WIRED), R1
RETURN
TEXT setwired(SB),$0
MOVW R1, M(WIRED)
RETURN
TEXT getrandom(SB),$0
MOVW M(RANDOM), R1
RETURN
TEXT getpagemask(SB),$0
MOVW M(PAGEMASK), R1
RETURN
TEXT setpagemask(SB),$0
MOVW R1, M(PAGEMASK)
MOVW R0, R1 /* prevent accidents */
RETURN
TEXT puttlbx(SB), $0 /* puttlbx(index, virt, phys0, phys1, pagemask) */
MOVW 4(FP), R2
MOVW 8(FP), R3
MOVW 12(FP), R4
MOVW $((2*BY2PG-1) & ~0x1fff), R5
MOVW R2, M(TLBVIRT)
MOVW R3, M(TLBPHYS0)
MOVW R4, M(TLBPHYS1)
MOVW R5, M(PAGEMASK)
MOVW R1, M(INDEX)
NOOP
NOOP
TLBWI
NOOP
RETURN
TEXT tlbvirt(SB), $0
MOVW M(TLBVIRT), R1
NOOP
RETURN
TEXT gettlbx(SB), $0 /* gettlbx(index, &entry) */
MOVW 4(FP), R4
MOVW R1, M(INDEX)
NOOP
NOOP
TLBR
NOOP
NOOP
NOOP
MOVW M(TLBVIRT), R1
MOVW M(TLBPHYS0), R2
MOVW M(TLBPHYS1), R3
NOOP
MOVW R1, 0(R4)
MOVW R2, 4(R4)
MOVW R3, 8(R4)
RETURN
TEXT gettlbp(SB), $0 /* gettlbp(tlbvirt, &entry) */
MOVW 4(FP), R5
MOVW R1, M(TLBVIRT)
NOOP
NOOP
NOOP
TLBP
NOOP
NOOP
MOVW M(INDEX), R1
NOOP
BLTZ R1, gettlbp1
TLBR
NOOP
NOOP
NOOP
MOVW M(TLBVIRT), R2
MOVW M(TLBPHYS0), R3
MOVW M(TLBPHYS1), R4
NOOP
MOVW R2, 0(R5)
MOVW R3, 4(R5)
MOVW R4, 8(R5)
gettlbp1:
RETURN
TEXT gettlbvirt(SB), $0 /* gettlbvirt(index) */
MOVW R1, M(INDEX)
NOOP
NOOP
TLBR
NOOP
NOOP
NOOP
MOVW M(TLBVIRT), R1
NOOP
RETURN
/*
* compute stlb hash index.
*
* M(TLBVIRT) [page & asid] in arg, result in arg.
* stir in swizzled asid; we get best results with asid in both high & low bits.
*/
#define STLBHASH(arg, tmp) \
AND $0xFF, arg, tmp; \
SRL $(PGSHIFT+1), arg; \
XOR tmp, arg; \
SLL $(STLBLOG-8), tmp; \
XOR tmp, arg; \
CONST (STLBSIZE-1, tmp); \
AND tmp, arg
TEXT stlbhash(SB), $0 /* for mmu.c */
STLBHASH(R1, R2)
RETURN
TEXT utlbmiss(SB), $-4
GETMACH(R26)
MOVW R27, 12(R26) /* m->splpc = R27 */
MOVW 16(R26), R27
ADDU $1, R27
MOVW R27,16(R26) /* m->tlbfault++ */
MOVW M(TLBVIRT), R27
NOOP
STLBHASH(R27, R26)
/* scale to a byte index (multiply by 12) */
SLL $1, R27, R26 /* × 2 */
ADDU R26, R27 /* × 3 */
SLL $2, R27 /* × 12 */
GETMACH(R26)
MOVW 4(R26), R26
ADDU R26, R27 /* R27 = &m->stb[hash] */
MOVW M(BADVADDR), R26
NOOP
AND $BY2PG, R26
BNE R26, utlbodd /* odd page? */
NOOP
utlbeven:
MOVW 4(R27), R26 /* R26 = m->stb[hash].phys0 */
BEQ R26, stlbm /* nothing cached? do it the hard way */
NOOP
MOVW R26, M(TLBPHYS0)
MOVW 8(R27), R26 /* R26 = m->stb[hash].phys1 */
JMP utlbcom
MOVW R26, M(TLBPHYS1) /* branch delay slot */
utlbodd:
MOVW 8(R27), R26 /* R26 = m->stb[hash].phys1 */
BEQ R26, stlbm /* nothing cached? do it the hard way */
NOOP
MOVW R26, M(TLBPHYS1)
MOVW 4(R27), R26 /* R26 = m->stb[hash].phys0 */
MOVW R26, M(TLBPHYS0)
utlbcom:
EHB
MOVW M(TLBVIRT), R26
MOVW 0(R27), R27 /* R27 = m->stb[hash].virt */
BEQ R27, stlbm /* nothing cached? do it the hard way */
NOOP
/* is the stlb entry for the right virtual address? */
BNE R26, R27, stlbm /* M(TLBVIRT) != m->stb[hash].virt? */
NOOP
/* if an entry exists, overwrite it, else write a random one */
CONST (PGSZ, R27)
MOVW R27, M(PAGEMASK) /* select page size */
TLBP /* probe tlb */
NOOP
NOOP
MOVW M(INDEX), R26
NOOP
BGEZ R26, utlbindex /* if tlb entry found, rewrite it */
NOOP
MOVW M(RANDOM), R26
MOVW R26, M(INDEX)
utlbindex:
NOOP
NOOP
TLBWI /* write indexed tlb entry */
NOOP
utlbret:
GETMACH(R26)
MOVW 12(R26), R27 /* R27 = m->splpc */
MOVW M(EPC), R26
JMP (R27)
NOOP
stlbm:
GETMACH(R26)
MOVW 12(R26), R27 /* R27 = m->splpc */
/* fall through */
TEXT gevector(SB), $-4
MOVW M(STATUS), R26
NOOP
AND $KUSER, R26
BNE R26, wasuser
MOVW SP, R26 /* delay slot, old SP in R26 */
waskernel:
JMP dosave
SUBU $UREGSIZE, SP /* delay slot, allocate frame on kernel stack */
wasuser: /* get kernel stack for this user process */
GETMACH (SP)
MOVW 8(SP), SP /* m->proc */
SUBU $(UREGSIZE), SP
dosave:
MOVW R31, 0x28(SP)
JAL saveregs(SB)
MOVW R26, 0x10(SP) /* delay slot, save old SP */
GETMACH(R(MACH))
MOVW 8(R(MACH)), R(USER) /* R24 = m->proc */
NOOP
MOVW $setR30(SB), R30
BEQ R26, dosys /* set by saveregs() */
NOOP
dotrap:
MOVW $forkret(SB), R31
JMP trap(SB)
MOVW 4(SP), R1 /* delay slot, first arg to trap() */
dosys:
JAL syscall(SB)
MOVW 4(SP), R1 /* delay slot, first arg to syscall() */
/* fall through */
TEXT forkret(SB), $-4
JAL restregs(SB) /* restores old PC in R26 */
MOVW 0x14(SP), R1 /* delay slot, CAUSE */
MOVW 0x28(SP), R31
JMP (R27)
MOVW 0x10(SP), SP /* delay slot */
/*
* SP-> 0x00 --- (spill R31)
* 0x04 --- (trap()/syscall() arg1)
* 0x08 status
* 0x0C pc
* 0x10 sp/usp
* 0x14 cause
* 0x18 badvaddr
* 0x1C tlbvirt
* 0x20 hi
* 0x24 lo
* 0x28 r31
* .....
* 0x9c r1
*/
TEXT saveregs(SB), $-4
MOVW R1, 0x9C(SP)
MOVW R2, 0x98(SP)
MOVW M(STATUS), R2
ADDU $8, SP, R1
MOVW R1, 0x04(SP) /* arg to base of regs */
MOVW $~KMODEMASK, R1
AND R2, R1
MOVW R1, M(STATUS) /* so we can take another trap */
MOVW R2, 0x08(SP)
MOVW M(EPC), R2
MOVW M(CAUSE), R1
MOVW R2, 0x0C(SP)
MOVW R1, 0x14(SP)
AND $(EXCMASK<<2), R1
SUBU $(CSYS<<2), R1, R26
BEQ R26, notsaved /* is syscall? */
MOVW R27, 0x34(SP) /* delay slot */
MOVW M(BADVADDR), R1
MOVW M(TLBVIRT), R2
MOVW R1, 0x18(SP)
MOVW R2, 0x1C(SP)
MOVW HI, R1
MOVW LO, R2
MOVW R1, 0x20(SP)
MOVW R2, 0x24(SP)
MOVW R25, 0x3C(SP)
MOVW R24, 0x40(SP)
MOVW R23, 0x44(SP)
MOVW R22, 0x48(SP)
MOVW R21, 0x4C(SP)
MOVW R20, 0x50(SP)
MOVW R19, 0x54(SP)
MOVW R18, 0x58(SP)
MOVW R17, 0x5C(SP)
MOVW R16, 0x60(SP)
MOVW R15, 0x64(SP)
MOVW R14, 0x68(SP)
MOVW R13, 0x6C(SP)
MOVW R12, 0x70(SP)
MOVW R11, 0x74(SP)
MOVW R10, 0x78(SP)
MOVW R9, 0x7C(SP)
MOVW R8, 0x80(SP)
MOVW R7, 0x84(SP)
MOVW R6, 0x88(SP)
MOVW R5, 0x8C(SP)
MOVW R4, 0x90(SP)
MOVW R3, 0x94(SP)
notsaved:
MOVW R30, 0x2C(SP)
RET
MOVW R28, 0x30(SP) /* delay slot */
TEXT restregs(SB), $-4
AND $(EXCMASK<<2), R1
SUBU $(CSYS<<2), R1, R26
BEQ R26, notrestored /* is syscall? */
MOVW 0x34(SP), R27 /* delay slot */
MOVW 0x3C(SP), R25
MOVW 0x40(SP), R24
MOVW 0x44(SP), R23
MOVW 0x48(SP), R22
MOVW 0x4C(SP), R21
MOVW 0x50(SP), R20
MOVW 0x54(SP), R19
MOVW 0x58(SP), R18
MOVW 0x5C(SP), R17
MOVW 0x60(SP), R16
MOVW 0x64(SP), R15
MOVW 0x68(SP), R14
MOVW 0x6C(SP), R13
MOVW 0x70(SP), R12
MOVW 0x74(SP), R11
MOVW 0x78(SP), R10
MOVW 0x7C(SP), R9
MOVW 0x80(SP), R8
MOVW 0x84(SP), R7
MOVW 0x88(SP), R6
MOVW 0x8C(SP), R5
MOVW 0x90(SP), R4
MOVW 0x94(SP), R3
MOVW 0x24(SP), R2
MOVW 0x20(SP), R1
MOVW R2, LO
MOVW R1, HI
MOVW 0x98(SP), R2
notrestored:
MOVW 0x08(SP), R1
MOVW R1, M(STATUS)
MOVW 0x0C(SP), R26 /* old PC */
MOVW R26, M(EPC)
MOVW 0x30(SP), R28
MOVW 0x2C(SP), R30
RET
MOVW 0x9C(SP), R1 /* delay slot */
/*
* hardware interrupt vectors
*/
TEXT vector0(SB), $-4
NOOP
CONST (SPBADDR+0x18, R26)
MOVW $eret(SB), R27
MOVW (R26), R26
JMP (R26)
NOOP
TEXT vector180(SB), $-4
NOOP
CONST (SPBADDR+0x14, R26)
MOVW $eret(SB), R27
MOVW (R26), R26
JMP (R26)
NOOP
TEXT eret(SB), $-4
ERET
NOOP
/*
* floating-point stuff
*/
/*
* degenerate floating-point stuff ad9!
*/
TEXT clrfpintr(SB), $0
RETURN
TEXT savefpregs(SB), $0
RETURN
TEXT restfpregs(SB), $0
RETURN
TEXT fcr31(SB), $0 /* fp csr */
MOVW R0, R1
RETURN
/*
* Emulate 68020 test and set: load linked / store conditional
*/
TEXT tas(SB), $0
TEXT _tas(SB), $0
MOVW R1, R2 /* address of key */
tas1:
MOVW $1, R3
LL(2, 1)
NOOP
SC(2, 3)
NOOP
BEQ R3, tas1
NOOP
RETURN
/* used by the semaphore implementation */
TEXT cmpswap(SB), $0
MOVW R1, R2 /* address of key */
MOVW old+4(FP), R3 /* old value */
MOVW new+8(FP), R4 /* new value */
LL(2, 1) /* R1 = (R2) */
NOOP
BNE R1, R3, fail
NOOP
MOVW R4, R1
SC(2, 1) /* (R2) = R1 if (R2) hasn't changed; R1 = success */
NOOP
RETURN
fail:
MOVW R0, R1
RETURN
/*
* cache manipulation
*/
TEXT icflush(SB), $-4 /* icflush(virtaddr, count) */
MOVW 4(FP), R9
DI(10) /* intrs off, old status -> R10 */
UBARRIERS(7, R7, ichb); /* return to kseg1 (uncached) */
ADDU R1, R9 /* R9 = last address */
MOVW $(~0x3f), R8
AND R1, R8 /* R8 = first address, rounded down */
ADDU $0x3f, R9
AND $(~0x3f), R9 /* round last address up */
SUBU R8, R9 /* R9 = revised count */
icflush1: /* primary cache line size is 16 bytes */
CACHE PD+HWB, 0x00(R8)
CACHE PI+HINV, 0x00(R8)
CACHE PD+HWB, 0x10(R8)
CACHE PI+HINV, 0x10(R8)
CACHE PD+HWB, 0x20(R8)
CACHE PI+HINV, 0x20(R8)
CACHE PD+HWB, 0x30(R8)
CACHE PI+HINV, 0x30(R8)
SUBU $0x40, R9
BGTZ R9, icflush1
ADDU $0x40, R8 /* delay slot */
BARRIERS(7, R7, ic2hb); /* return to kseg0 (cached) */
MOVW R10, M(STATUS)
JRHB(31)
TEXT dcflush(SB), $-4 /* dcflush(virtaddr, count) */
MOVW 4(FP), R9
DI(10) /* intrs off, old status -> R10 */
SYNC
EHB
ADDU R1, R9 /* R9 = last address */
MOVW $(~0x3f), R8
AND R1, R8 /* R8 = first address, rounded down */
ADDU $0x3f, R9
AND $(~0x3f), R9 /* round last address up */
SUBU R8, R9 /* R9 = revised count */
dcflush1: /* primary cache line size is 16 bytes */
CACHE PD+HWB, 0x00(R8)
CACHE PD+HWB, 0x10(R8)
CACHE PD+HWB, 0x20(R8)
CACHE PD+HWB, 0x30(R8)
SUBU $0x40, R9
BGTZ R9, dcflush1
ADDU $0x40, R8 /* delay slot */
SYNC
EHB
MOVW R10, M(STATUS)
RETURN
TEXT outl(SB), $0
MOVW 4(FP), R2
MOVW 8(FP), R3
SLL $2, R3
ADDU R2, R3
outl1:
BEQ R2, R3, outl2
MOVW (R2), R4
MOVW R4, (R1)
JMP outl1
ADDU $4, R2
outl2:
RETURN
/*
* access to CP0 registers
*/
TEXT prid(SB), $0
MOVW M(PRID), R1
RETURN
TEXT rdcount(SB), $0
MOVW M(COUNT), R1
RETURN
TEXT wrcount(SB), $0
MOVW R1, M(COUNT)
RETURN
TEXT wrcompare(SB), $0
MOVW R1, M(COMPARE)
RETURN
TEXT rdcompare(SB), $0
MOVW M(COMPARE), R1
RETURN
TEXT getstatus(SB), $0
MOVW M(STATUS), R1
RETURN
TEXT setstatus(SB), $0
MOVW R1, M(STATUS)
EHB
RETURN
TEXT getcause(SB), $-4
MOVW M(CAUSE), R1
RETURN
TEXT getconfig(SB), $-4
MOVW M(CONFIG), R1
RETURN
TEXT getconfig1(SB), $-4
MFC0(CONFIG, 1, 1)
RETURN
TEXT getconfig2(SB), $-4
MFC0(CONFIG, 2, 1)
RETURN
TEXT getconfig3(SB), $-4
MFC0(CONFIG, 3, 1)
RETURN
TEXT getconfig4(SB), $-4
MFC0(CONFIG, 4, 1)
RETURN
TEXT getconfig7(SB), $-4
MFC0(CONFIG, 7, 1)
RETURN
TEXT gethwreg3(SB), $-4
RDHWR(3, 1)
RETURN
TEXT getdebugreg(SB), $0
MOVW M(DEBUGREG), R1
RETURN
TEXT setwatchhi0(SB), $0
MOVW R1, M(WATCHHI)
EHB
RETURN
/*
* beware that the register takes a double-word address, so it's not
* precise to the individual instruction.
*/
TEXT setwatchlo0(SB), $0
MOVW R1, M(WATCHLO)
EHB
RETURN
TEXT getfcr0(SB), $0
MOVW FCR0, R1
RET
/* zoot is just for debug waves */
TEXT zoot(SB), $0
PUTC('W', R1, R2)
NOP
RETURN
GLOBL sanity(SB), $4
DATA sanity(SB)/4, $SANITY
SCHED
|
9front/9front
| 2,167
|
sys/src/9/mt7688/mips24k.s
|
#define SP R29
#define NOOP NOR R0, R0, R0
#define NOP NOR R0, R0, R0
#define RETURN RET; NOOP
#define CONST(i, v) MOVW $((i) & 0xffff0000), v; OR $((i) & 0xffff), v;
#define GETMACH(r) CONST(MACHADDR, r)
#define PUTC(c, r1, r2) CONST(PHYSCONS, r1); MOVW $(c), r2; MOVW r2, (r1); NOOP
/* new instructions in mips 24k (mips32r2) */
#define DI(rt) WORD $(0x41606000|((rt)<<16)) /* interrupts off */
#define EI(rt) WORD $(0x41606020|((rt)<<16)) /* interrupts on */
#define EHB WORD $0xc0
#define SYNC WORD $0xf /* all sync barriers */
#define WAIT WORD $0x42000020 /* wait for interrupt */
/* all barriers, clears all hazards; clobbers r/Reg and R22 */
#define BARRIERS(r, Reg, label) \
SYNC; EHB; MOVW $ret(SB), Reg; JALRHB(r)
/* same but return to KSEG1 */
#define UBARRIERS(r, Reg, label) \
SYNC; EHB; MOVW $ret(SB), Reg; OR $KSEG1, Reg; JALRHB(r)
/* jalr with hazard barrier, link in R22 */
#define JALRHB(r) WORD $(((r)<<21)|(22<<11)|(1<<10)|9); NOOP
/* jump register with hazard barrier */
#define JRHB(r) WORD $(((r)<<21)|(1<<10)|8); NOOP
/*
* R4000 instructions
*/
/* a mips 24k erratum requires a NOP after; experience dictates EHB before */
#define ERET EHB; WORD $0x42000018; NOP
//#define ERET WORD $0x42000018
#define LL(base, rt) WORD $((060<<26)|((base)<<21)|((rt)<<16))
#define SC(base, rt) WORD $((070<<26)|((base)<<21)|((rt)<<16))
#define MFC0(src,sel,dst) WORD $(0x40000000|((src)<<11)|((dst)<<16)|(sel))
#define MTC0(src,dst,sel) WORD $(0x40800000|((dst)<<11)|((src)<<16)|(sel))
#define RDHWR(hwr, r) WORD $(0x7c00003b|((hwr)<<11)|((r)<<16))
/*
* cache manipulation
*/
#define CACHE BREAK /* overloaded op-code */
#define PI R((0 /* primary I cache */
#define PD R((1 /* primary D cache */
#define SD R((3 /* secondary combined I/D cache */
#define IWBI (0<<2))) /* index write-back invalidate */
#define ILT (1<<2))) /* index load tag */
#define IST (2<<2))) /* index store tag */
#define CDE (3<<2))) /* create dirty exclusive */
#define HINV (4<<2))) /* hit invalidate */
#define HWBI (5<<2))) /* hit write back invalidate */
#define HWB (6<<2))) /* hit write back */
#define HSV (7<<2))) /* hit set virtual */
|
9front/9front
| 13,665
|
sys/src/9/lx2k/l.s
|
#include "mem.h"
#include "../arm64/sysreg.h"
#undef SYSREG
#define SYSREG(op0,op1,Cn,Cm,op2) SPR(((op0)<<19|(op1)<<16|(Cn)<<12|(Cm)<<8|(op2)<<5))
TEXT _start(SB), 1, $-4
MOV R0, R26 /* save */
MOV $setSB-KZERO(SB), R28
BL svcmode<>(SB)
/* use dedicated stack pointer per exception level */
MOVWU $1, R1
MSR R1, SPSel
BL mmudisable<>(SB)
/* invalidate local caches */
BL cachedwbinv(SB)
BL l2cacheuwbinv(SB)
BL cacheiinv(SB)
/* getmachno in R0 */
MRS MPIDR_EL1, R0
BL mpidindex(SB)
/* get MACHP(R0) in R27 */
MOV $(MACHADDR(0)-KZERO), R27
MOVWU $MACHSIZE, R2
MULW R0, R2, R2
SUB R2, R27
/* set the stack pointer */
ADD $(MACHSIZE-16), R27, R1
MOV R1, SP
CBNZ R0, _startup
/* clear page table and machs */
MOV $(L1BOT-KZERO), R1
MOV $(MACHADDR(-1)-KZERO), R2
_zerol1:
MOV ZR, (R1)8!
CMP R1, R2
BNE _zerol1
/* clear BSS */
MOV $edata-KZERO(SB), R1
MOV $end-KZERO(SB), R2
_zerobss:
MOV ZR, (R1)8!
CMP R1, R2
BNE _zerobss
/* setup page tables */
MOV $(L1BOT-KZERO), R0
BL mmuidmap(SB)
MOV $(L1-KZERO), R0
BL mmu0init(SB)
SEVL
_startup:
WFE
BL mmuenable<>(SB)
MOV R26, R0
MOV $0, R26
ORR $KZERO, R27
MSR R27, TPIDR_EL1
MOV $setSB(SB), R28
BL main(SB)
TEXT stop<>(SB), 1, $-4
_stop:
WFE
B _stop
TEXT sev(SB), 1, $-4
SEV
WFE
RETURN
TEXT svcmode<>(SB), 1, $-4
MSR $0xF, DAIFSet
MRS CurrentEL, R0
ANDW $(3<<2), R0
CMPW $(1<<2), R0
BEQ el1
CMPW $(2<<2), R0
BEQ el2
B stop<>(SB)
el2:
MOV $0, R0
MSR R0, MDCR_EL2
ISB $SY
/* set virtual timer offset to zero */
MOV $0, R0
MSR R0, CNTVOFF_EL2
/* HCR = RW, HCD, SWIO, BSU, FB */
MOVWU $(1<<31 | 1<<29 | 1<<2 | 0<<10 | 0<<9), R0
MSR R0, HCR_EL2
ISB $SY
/* SCTLR = RES1 */
MOVWU $(3<<4 | 1<<11 | 1<<16 | 1<<18 | 3<<22 | 3<<28), R0
ISB $SY
MSR R0, SCTLR_EL2
ISB $SY
/* set VMID to zero */
MOV $0, R0
MSR R0, VTTBR_EL2
ISB $SY
MOVWU $(0xF<<6 | 4), R0
MSR R0, SPSR_EL2
MSR LR, ELR_EL2
ERET
el1:
RETURN
TEXT mmudisable<>(SB), 1, $-4
#define SCTLRCLR \
/* RES0 */ ( 3<<30 \
/* RES0 */ | 1<<27 \
/* UCI */ | 1<<26 \
/* EE */ | 1<<25 \
/* RES0 */ | 1<<21 \
/* E0E */ | 1<<24 \
/* WXN */ | 1<<19 \
/* nTWE */ | 1<<18 \
/* RES0 */ | 1<<17 \
/* nTWI */ | 1<<16 \
/* UCT */ | 1<<15 \
/* DZE */ | 1<<14 \
/* RES0 */ | 1<<13 \
/* RES0 */ | 1<<10 \
/* UMA */ | 1<<9 \
/* SA0 */ | 1<<4 \
/* SA */ | 1<<3 \
/* A */ | 1<<1 )
#define SCTLRSET \
/* RES1 */ ( 3<<28 \
/* RES1 */ | 3<<22 \
/* RES1 */ | 1<<20 \
/* RES1 */ | 1<<11 )
#define SCTLRMMU \
/* I */ ( 1<<12 \
/* C */ | 1<<2 \
/* M */ | 1<<0 )
/* initialise SCTLR, MMU and caches off */
ISB $SY
MRS SCTLR_EL1, R0
BIC $(SCTLRCLR | SCTLRMMU), R0
ORR $SCTLRSET, R0
ISB $SY
MSR R0, SCTLR_EL1
ISB $SY
B flushlocaltlb(SB)
TEXT mmuenable<>(SB), 1, $-4
/* return to virtual */
ORR $KZERO, LR
MOV LR, -16(RSP)!
BL flushlocaltlb(SB)
/* memory attributes */
#define MAIRINIT \
( 0xFF << MA_MEM_WB*8 \
| 0x33 << MA_MEM_WT*8 \
| 0x44 << MA_MEM_UC*8 \
| 0x00 << MA_DEV_nGnRnE*8 \
| 0x04 << MA_DEV_nGnRE*8 \
| 0x08 << MA_DEV_nGRE*8 \
| 0x0C << MA_DEV_GRE*8 )
MOV $MAIRINIT, R1
MSR R1, MAIR_EL1
ISB $SY
/* translation control */
#define TCRINIT \
/* TBI1 */ ( 0<<38 \
/* TBI0 */ | 0<<37 \
/* AS */ | 0<<36 \
/* TG1 */ | (((3<<16|1<<14|2<<12)>>PGSHIFT)&3)<<30 \
/* SH1 */ | SHARE_INNER<<28 \
/* ORGN1 */ | CACHE_WB<<26 \
/* IRGN1 */ | CACHE_WB<<24 \
/* EPD1 */ | 0<<23 \
/* A1 */ | 0<<22 \
/* T1SZ */ | (64-EVASHIFT)<<16 \
/* TG0 */ | (((1<<16|2<<14|0<<12)>>PGSHIFT)&3)<<14 \
/* SH0 */ | SHARE_INNER<<12 \
/* ORGN0 */ | CACHE_WB<<10 \
/* IRGN0 */ | CACHE_WB<<8 \
/* EPD0 */ | 0<<7 \
/* T0SZ */ | (64-EVASHIFT)<<0 )
MOV $TCRINIT, R1
MRS ID_AA64MMFR0_EL1, R2
ANDW $0x7, R2 // PARange
ADD R2<<32, R1 // IPS
MSR R1, TCR_EL1
ISB $SY
/* load the page tables */
MOV $(L1BOT-KZERO), R0
MOV $(L1TOP-KZERO), R1
ISB $SY
MSR R0, TTBR0_EL1
MSR R1, TTBR1_EL1
ISB $SY
/* enable MMU and caches */
MRS SCTLR_EL1, R1
ORR $SCTLRMMU, R1
ISB $SY
MSR R1, SCTLR_EL1
ISB $SY
MOV RSP, R1
ORR $KZERO, R1
MOV R1, RSP
MOV (RSP)16!, LR
B cacheiinv(SB)
TEXT touser(SB), 1, $-4
MOVWU $0x10028, R1 // entry
MOVWU $0, R2 // psr
MSR R0, SP_EL0 // sp
MSR R1, ELR_EL1
MSR R2, SPSR_EL1
ERET
TEXT cas(SB), 1, $-4
TEXT cmpswap(SB), 1, $-4
MOVWU ov+8(FP), R1
MOVWU nv+16(FP), R2
_cas1:
LDXRW (R0), R3
CMP R3, R1
BNE _cas0
STXRW R2, (R0), R4
CBNZ R4, _cas1
MOVW $1, R0
DMB $ISH
RETURN
_cas0:
CLREX
MOVW $0, R0
RETURN
TEXT tas(SB), 1, $-4
TEXT _tas(SB), 1, $-4
MOVW $0xdeaddead, R2
_tas1:
LDXRW (R0), R1
STXRW R2, (R0), R3
CBNZ R3, _tas1
MOVW R1, R0
TEXT coherence(SB), 1, $-4
DMB $ISH
RETURN
TEXT islo(SB), 1, $-4
MRS DAIF, R0
AND $(0x2<<6), R0
EOR $(0x2<<6), R0
RETURN
TEXT splhi(SB), 1, $-4
MRS DAIF, R0
MSR $0x2, DAIFSet
RETURN
TEXT splfhi(SB), 1, $-4
MRS DAIF, R0
MSR $0x3, DAIFSet
RETURN
TEXT spllo(SB), 1, $-4
MSR $0x3, DAIFClr
RETURN
TEXT splflo(SB), 1, $-4
MSR $0x1, DAIFClr
RETURN
TEXT splx(SB), 1, $-4
MSR R0, DAIF
RETURN
TEXT idlehands(SB), 1, $-4
DMB $ISH
MOVW nrdy(SB), R0
CBNZ R0, _ready
WFI
_ready:
RETURN
TEXT vcycles(SB), 1, $-4
MRS CNTVCT_EL0, R0
RETURN
TEXT lcycles(SB), 1, $-4
MRS PMCCNTR_EL0, R0
RETURN
TEXT setlabel(SB), 1, $-4
MOV LR, 8(R0)
MOV SP, R1
MOV R1, 0(R0)
MOVW $0, R0
RETURN
TEXT gotolabel(SB), 1, $-4
MOV 8(R0), LR /* link */
MOV 0(R0), R1 /* sp */
MOV R1, SP
MOVW $1, R0
RETURN
TEXT returnto(SB), 1, $-4
MOV R0, 0(SP)
RETURN
TEXT getfar(SB), 1, $-4
MRS FAR_EL1, R0
RETURN
TEXT setttbr(SB), 1, $-4
DSB $ISHST
MSR R0, TTBR0_EL1
DSB $ISH
ISB $SY
RETURN
/*
* TLB maintenance operations.
* these broadcast to all cpu's in the cluser
* (inner sharable domain).
*/
TEXT flushasidva(SB), 1, $-4
TEXT tlbivae1is(SB), 1, $-4
DSB $ISHST
TLBI R0, 0,8,3,1 /* VAE1IS */
DSB $ISH
ISB $SY
RETURN
TEXT flushasidvall(SB), 1, $-4
TEXT tlbivale1is(SB), 1, $-4
DSB $ISHST
TLBI R0, 0,8,3,5 /* VALE1IS */
DSB $ISH
ISB $SY
RETURN
TEXT flushasid(SB), 1, $-4
TEXT tlbiaside1is(SB), 1, $-4
DSB $ISHST
TLBI R0, 0,8,3,2 /* ASIDE1IS */
DSB $ISH
ISB $SY
RETURN
TEXT flushtlb(SB), 1, $-4
TEXT tlbivmalle1is(SB), 1, $-4
DSB $ISHST
TLBI R0, 0,8,3,0 /* VMALLE1IS */
DSB $ISH
ISB $SY
RETURN
/*
* flush the tlb of this cpu. no broadcast.
*/
TEXT flushlocaltlb(SB), 1, $-4
TEXT tlbivmalle1(SB), 1, $-4
DSB $NSHST
TLBI R0, 0,8,7,0 /* VMALLE1 */
DSB $NSH
ISB $SY
RETURN
/*
* floating-point support.
*/
TEXT fpon(SB), 1, $-4
MOVW $(3<<20), R0
MSR R0, CPACR_EL1
ISB $SY
RETURN
TEXT fpoff(SB), 1, $-4
MOVW $(0<<20), R0
MSR R0, CPACR_EL1
ISB $SY
RETURN
TEXT fpsaveregs(SB), 1, $-4
WORD $(1<<30 | 3 << 26 | 2<<22 | 0x1F<<16 | 3<<10 | 0<<5 | 0) /* MOV { V0, V1, V2, V3 }, (R0)64! */
WORD $(1<<30 | 3 << 26 | 2<<22 | 0x1F<<16 | 3<<10 | 0<<5 | 4) /* MOV { V4, V5, V6, V7 }, (R0)64! */
WORD $(1<<30 | 3 << 26 | 2<<22 | 0x1F<<16 | 3<<10 | 0<<5 | 8) /* MOV { V8, V9, V10,V11 }, (R0)64! */
WORD $(1<<30 | 3 << 26 | 2<<22 | 0x1F<<16 | 3<<10 | 0<<5 | 12) /* MOV { V12,V13,V14,V15 }, (R0)64! */
WORD $(1<<30 | 3 << 26 | 2<<22 | 0x1F<<16 | 3<<10 | 0<<5 | 16) /* MOV { V16,V17,V18,V19 }, (R0)64! */
WORD $(1<<30 | 3 << 26 | 2<<22 | 0x1F<<16 | 3<<10 | 0<<5 | 20) /* MOV { V20,V21,V22,V23 }, (R0)64! */
WORD $(1<<30 | 3 << 26 | 2<<22 | 0x1F<<16 | 3<<10 | 0<<5 | 24) /* MOV { V24,V25,V26,V27 }, (R0)64! */
WORD $(1<<30 | 3 << 26 | 2<<22 | 0x1F<<16 | 3<<10 | 0<<5 | 28) /* MOV { V28,V29,V30,V31 }, (R0)64! */
RETURN
TEXT fploadregs(SB), 1, $-4
WORD $(1<<30 | 3 << 26 | 3<<22 | 0x1F<<16 | 3<<10 | 0<<5 | 0) /* MOV (R0)64!, { V0, V1, V2, V3 } */
WORD $(1<<30 | 3 << 26 | 3<<22 | 0x1F<<16 | 3<<10 | 0<<5 | 4) /* MOV (R0)64!, { V4, V5, V6, V7 } */
WORD $(1<<30 | 3 << 26 | 3<<22 | 0x1F<<16 | 3<<10 | 0<<5 | 8) /* MOV (R0)64!, { V8, V9, V10,V11 } */
WORD $(1<<30 | 3 << 26 | 3<<22 | 0x1F<<16 | 3<<10 | 0<<5 | 12) /* MOV (R0)64!, { V12,V13,V14,V15 } */
WORD $(1<<30 | 3 << 26 | 3<<22 | 0x1F<<16 | 3<<10 | 0<<5 | 16) /* MOV (R0)64!, { V16,V17,V18,V19 } */
WORD $(1<<30 | 3 << 26 | 3<<22 | 0x1F<<16 | 3<<10 | 0<<5 | 20) /* MOV (R0)64!, { V20,V21,V22,V23 } */
WORD $(1<<30 | 3 << 26 | 3<<22 | 0x1F<<16 | 3<<10 | 0<<5 | 24) /* MOV (R0)64!, { V24,V25,V26,V27 } */
WORD $(1<<30 | 3 << 26 | 3<<22 | 0x1F<<16 | 3<<10 | 0<<5 | 28) /* MOV (R0)64!, { V28,V29,V30,V31 } */
RETURN
// syscall or trap from EL0
TEXT vsys0(SB), 1, $-4
LSRW $26, R0, R17 // ec
CMPW $0x15, R17 // SVC trap?
BNE _itsatrap // nope.
MOVP R26, R27, 224(RSP)
MOVP R28, R29, 240(RSP)
MRS SP_EL0, R1
MRS ELR_EL1, R2
MRS SPSR_EL1, R3
MOV R0, 288(RSP) // type
MOV R1, 264(RSP) // sp
MOV R2, 272(RSP) // pc
MOV R3, 280(RSP) // psr
MOV $setSB(SB), R28
MRS TPIDR_EL1, R27
MOV 16(R27), R26
ADD $16, RSP, R0 // ureg
BL syscall(SB)
TEXT forkret(SB), 1, $-4
MSR $0x3, DAIFSet // interrupts off
ADD $16, RSP, R0 // ureg
MOV 16(RSP), R0 // ret
MOV 264(RSP), R1 // sp
MOV 272(RSP), R2 // pc
MOV 280(RSP), R3 // psr
MSR R1, SP_EL0
MSR R2, ELR_EL1
MSR R3, SPSR_EL1
MOVP 224(RSP), R26, R27
MOVP 240(RSP), R28, R29
MOV 256(RSP), R30 // link
ADD $TRAPFRAMESIZE, RSP
ERET
TEXT itsatrap<>(SB), 1, $-4
_itsatrap:
MOVP R1, R2, 24(RSP)
MOVP R3, R4, 40(RSP)
MOVP R5, R6, 56(RSP)
MOVP R7, R8, 72(RSP)
MOVP R9, R10, 88(RSP)
MOVP R11, R12, 104(RSP)
MOVP R13, R14, 120(RSP)
MOVP R15, R16, 136(RSP)
MOVP R18, R19, 160(RSP)
MOVP R20, R21, 176(RSP)
MOVP R22, R23, 192(RSP)
MOVP R24, R25, 208(RSP)
// trap/irq/fiq/serr from EL0
TEXT vtrap0(SB), 1, $-4
MOVP R26, R27, 224(RSP)
MOVP R28, R29, 240(RSP)
MRS SP_EL0, R1
MRS ELR_EL1, R2
MRS SPSR_EL1, R3
MOV R0, 288(RSP) // type
MOV R1, 264(RSP) // sp
MOV R2, 272(RSP) // pc
MOV R3, 280(RSP) // psr
MOV $setSB(SB), R28
MRS TPIDR_EL1, R27
MOV 16(R27), R26
ADD $16, RSP, R0 // ureg
BL trap(SB)
TEXT noteret(SB), 1, $-4
MSR $0x3, DAIFSet // interrupts off
ADD $16, RSP, R0 // ureg
MOV 264(RSP), R1 // sp
MOV 272(RSP), R2 // pc
MOV 280(RSP), R3 // psr
MSR R1, SP_EL0
MSR R2, ELR_EL1
MSR R3, SPSR_EL1
MOVP 224(RSP), R26, R27
MOVP 240(RSP), R28, R29
_intrreturn:
MOVP 16(RSP), R0, R1
MOVP 32(RSP), R2, R3
MOVP 48(RSP), R4, R5
MOVP 64(RSP), R6, R7
MOVP 80(RSP), R8, R9
MOVP 96(RSP), R10, R11
MOVP 112(RSP), R12, R13
MOVP 128(RSP), R14, R15
MOVP 144(RSP), R16, R17
MOVP 160(RSP), R18, R19
MOVP 176(RSP), R20, R21
MOVP 192(RSP), R22, R23
MOVP 208(RSP), R24, R25
MOV 256(RSP), R30 // link
ADD $TRAPFRAMESIZE, RSP
ERET
// irq/fiq/trap/serr from EL1
TEXT vtrap1(SB), 1, $-4
MOV R29, 248(RSP) // special
ADD $TRAPFRAMESIZE, RSP, R1
MRS ELR_EL1, R2
MRS SPSR_EL1, R3
MOV R0, 288(RSP) // type
MOV R1, 264(RSP) // sp
MOV R2, 272(RSP) // pc
MOV R3, 280(RSP) // psr
ADD $16, RSP, R0 // ureg
BL trap(SB)
MSR $0x3, DAIFSet // interrupts off
MOV 272(RSP), R2 // pc
MOV 280(RSP), R3 // psr
MSR R2, ELR_EL1
MSR R3, SPSR_EL1
MOV 248(RSP), R29 // special
B _intrreturn
// vector tables
TEXT vsys(SB), 1, $-4
SUB $TRAPFRAMESIZE, RSP
MOV R0, 16(RSP)
MOV R30, 256(RSP) // link
MOV R17, 152(RSP) // temp
MRS ESR_EL1, R0 // type
_vsyspatch:
B _vsyspatch // branch to vsys0() patched in
TEXT vtrap(SB), 1, $-4
SUB $TRAPFRAMESIZE, RSP
MOVP R0, R1, 16(RSP)
MOVP R2, R3, 32(RSP)
MOVP R4, R5, 48(RSP)
MOVP R6, R7, 64(RSP)
MOVP R8, R9, 80(RSP)
MOVP R10, R11, 96(RSP)
MOVP R12, R13, 112(RSP)
MOVP R14, R15, 128(RSP)
MOVP R16, R17, 144(RSP)
MOVP R18, R19, 160(RSP)
MOVP R20, R21, 176(RSP)
MOVP R22, R23, 192(RSP)
MOVP R24, R25, 208(RSP)
MOV R30, 256(RSP) // link
MRS ESR_EL1, R0 // type
_vtrappatch:
B _vtrappatch // branch to vtrapX() patched in
TEXT virq(SB), 1, $-4
SUB $TRAPFRAMESIZE, RSP
MOVP R0, R1, 16(RSP)
MOVP R2, R3, 32(RSP)
MOVP R4, R5, 48(RSP)
MOVP R6, R7, 64(RSP)
MOVP R8, R9, 80(RSP)
MOVP R10, R11, 96(RSP)
MOVP R12, R13, 112(RSP)
MOVP R14, R15, 128(RSP)
MOVP R16, R17, 144(RSP)
MOVP R18, R19, 160(RSP)
MOVP R20, R21, 176(RSP)
MOVP R22, R23, 192(RSP)
MOVP R24, R25, 208(RSP)
MOV R30, 256(RSP) // link
MOV $(1<<32), R0 // type irq
_virqpatch:
B _virqpatch // branch to vtrapX() patched in
TEXT vfiq(SB), 1, $-4
SUB $TRAPFRAMESIZE, RSP
MOVP R0, R1, 16(RSP)
MOVP R2, R3, 32(RSP)
MOVP R4, R5, 48(RSP)
MOVP R6, R7, 64(RSP)
MOVP R8, R9, 80(RSP)
MOVP R10, R11, 96(RSP)
MOVP R12, R13, 112(RSP)
MOVP R14, R15, 128(RSP)
MOVP R16, R17, 144(RSP)
MOVP R18, R19, 160(RSP)
MOVP R20, R21, 176(RSP)
MOVP R22, R23, 192(RSP)
MOVP R24, R25, 208(RSP)
MOV R30, 256(RSP) // link
MOV $(2<<32), R0 // type fiq
_vfiqpatch:
B _vfiqpatch // branch to vtrapX() patched in
TEXT vserr(SB), 1, $-4
SUB $TRAPFRAMESIZE, RSP
MOVP R0, R1, 16(RSP)
MOVP R2, R3, 32(RSP)
MOVP R4, R5, 48(RSP)
MOVP R6, R7, 64(RSP)
MOVP R8, R9, 80(RSP)
MOVP R10, R11, 96(RSP)
MOVP R12, R13, 112(RSP)
MOVP R14, R15, 128(RSP)
MOVP R16, R17, 144(RSP)
MOVP R18, R19, 160(RSP)
MOVP R20, R21, 176(RSP)
MOVP R22, R23, 192(RSP)
MOVP R24, R25, 208(RSP)
MOV R30, 256(RSP) // link
MRS ESR_EL1, R0
ORR $(3<<32), R0 // type
_vserrpatch:
B _vserrpatch // branch to vtrapX() patched in
/* fault-proof memcpy */
TEXT peek(SB), 1, $-4
MOV R0, R1
MOV dst+8(FP), R2
MOVWU len+16(FP), R0
TEXT _peekinst(SB), 1, $-4
_peekloop:
MOVBU (R1)1!, R3
MOVBU R3, (R2)1!
SUBS $1, R0
BNE _peekloop
RETURN
TEXT smccall(SB), 1, $32
/* save extern registers */
MOVP R26, R27, (RSP)
/* R0 = Ureg */
MOV R0, R8
/* save ureg pointer */
MOV R8, 16(RSP)
MOVP 0(R8), R0, R1
MOVP 16(R8), R2, R3
MOVP 32(R8), R4, R5
MOVP 48(R8), R6, R7
SMC
/* restore ureg pointer */
MOV 16(RSP), R8
MOVP R0, R1, 0(R8)
MOVP R2, R3, 16(R8)
/* restore extern registers */
MOVP (RSP), R26, R27
RETURN
|
9front/9front
| 19,046
|
sys/src/9/teg2/l.s
|
/*
* tegra 2 SoC machine assist
* dual arm cortex-a9 processors
*
* ARM v7 arch. ref. man. §B1.3.3 says that we don't need barriers
* around writes to CPSR.
*
* LDREX/STREX use an exclusive monitor, which is part of the data cache unit
* for the L1 cache, so they won't work right if the L1 cache is disabled.
*/
#include "arm.s"
#define LDREX(fp,t) WORD $(0xe<<28|0x01900f9f | (fp)<<16 | (t)<<12)
/* `The order of operands is from left to right in dataflow order' - asm man */
#define STREX(f,tp,r) WORD $(0xe<<28|0x01800f90 | (tp)<<16 | (r)<<12 | (f)<<0)
#define MAXMB (KiB-1) /* last MB has vectors */
#define TMPSTACK (DRAMSIZE - 64*MiB) /* used only during cpu startup */
/* tas/cas strex debugging limits; started at 10000 */
#define MAXSC 100000
GLOBL testmem(SB), $4
/*
* Entered here from Das U-Boot or another Plan 9 kernel with MMU disabled.
* Until the MMU is enabled it is OK to call functions provided
* they are within ±32MiB relative and do not require any
* local variables or more than one argument (i.e. there is
* no stack).
*/
TEXT _start(SB), 1, $-4
CPSMODE(PsrMsvc)
CPSID /* interrupts off */
CPSAE
SETEND(0) /* little-endian */
BARRIERS
CLREX
SETZSB
MOVW CPSR, R0
ORR $PsrDfiq, R0
MOVW R0, CPSR
/* invalidate i-cache and branch-target cache */
MTCP CpSC, 0, PC, C(CpCACHE), C(CpCACHEinvi), CpCACHEall
BARRIERS
/* put cpus other than 0 to sleep until cpu 0 is ready */
CPUID(R1)
BEQ cpuinit
/* not cpu 0 */
PUTC('Z')
PUTC('Z')
BARRIERS
dowfi:
WFI
MOVW cpus_proceed(SB), R1
CMP $0, R1
BEQ dowfi
BL cpureset(SB)
B dowfi
cpuinit:
DELAY(printloopret, 1)
PUTC('\r')
DELAY(printloopnl, 1)
PUTC('\n')
DELAY(printloops, 1)
PUTC('P')
/* disable the PL310 L2 cache on cpu0 */
MOVW $(PHYSL2BAG+0x100), R1
MOVW $0, R2
MOVW R2, (R1)
BARRIERS
/* invalidate it */
MOVW $((1<<16)-1), R2
MOVW R2, 0x77c(R1)
BARRIERS
/*
* disable my MMU & caches
*/
MFCP CpSC, 0, R1, C(CpCONTROL), C(0), CpMainctl
ORR $CpCsbo, R1
BIC $(CpCsbz|CpCmmu|CpCdcache|CpCicache|CpCpredict), R1
MTCP CpSC, 0, R1, C(CpCONTROL), C(0), CpMainctl
BARRIERS
/* cortex-a9 model-specific initial configuration */
MOVW $0, R1
MTCP CpSC, 0, R1, C(CpCONTROL), C(0), CpAuxctl
BARRIERS
PUTC('l')
DELAY(printloop3, 1)
MOVW $testmem-KZERO(SB), R0
BL memdiag(SB)
PUTC('a')
/* clear Mach for cpu 0 */
MOVW $PADDR(MACHADDR), R4 /* address of Mach for cpu 0 */
MOVW $0, R0
_machZ:
MOVW R0, (R4)
ADD $4, R4
CMP.S $PADDR(L1+L1X(0)), R4 /* end at top-level page table */
BNE _machZ
/*
* set up the MMU page table for cpu 0
*/
PUTC('n')
/* clear all PTEs first, to provide a default */
// MOVW $PADDR(L1+L1X(0)), R4 /* address of PTE for 0 */
_ptenv0:
ZEROPTE()
CMP.S $PADDR(L1+16*KiB), R4
BNE _ptenv0
DELAY(printloop4, 2)
PUTC(' ')
/*
* set up double map of PHYSDRAM, KZERO to PHYSDRAM for first few MBs,
* but only if KZERO and PHYSDRAM differ.
*/
MOVW $PTEDRAM, R2 /* PTE bits */
MOVW $PHYSDRAM, R3 /* pa */
CMP $KZERO, R3
BEQ no2map
MOVW $PADDR(L1+L1X(PHYSDRAM)), R4 /* address of PTE for PHYSDRAM */
MOVW $DOUBLEMAPMBS, R5
_ptdbl:
FILLPTE()
SUB.S $1, R5
BNE _ptdbl
no2map:
/*
* back up and fill in PTEs for memory at KZERO.
* trimslice has 1 bank of 1GB at PHYSDRAM.
* Map the maximum.
*/
PUTC('9')
MOVW $PTEDRAM, R2 /* PTE bits */
MOVW $PHYSDRAM, R3
MOVW $PADDR(L1+L1X(KZERO)), R4 /* start with PTE for KZERO */
MOVW $MAXMB, R5 /* inner loop count (MBs) */
_ptekrw: /* set PTEs */
FILLPTE()
SUB.S $1, R5 /* decrement inner loop count */
BNE _ptekrw
/*
* back up and fill in PTEs for MMIO
*/
PUTC(' ')
MOVW $PTEIO, R2 /* PTE bits */
MOVW $PHYSIO, R3
MOVW $PADDR(L1+L1X(VIRTIO)), R4 /* start with PTE for VIRTIO */
_ptenv2:
FILLPTE()
CMP.S $PADDR(L1+L1X(PHYSIOEND)), R4
BNE _ptenv2
/* mmu.c sets up the trap vectors later */
MOVW $(PHYSDRAM | TMPSTACK), SP
/*
* learn l1 cache characteristics (on cpu 0 only).
*/
MOVW $(1-1), R0 /* l1 */
SLL $1, R0 /* R0 = (cache - 1) << 1 */
MTCP CpSC, CpIDcssel, R0, C(CpID), C(CpIDid), 0 /* select l1 cache */
BARRIERS
MFCP CpSC, CpIDcsize, R0, C(CpID), C(CpIDid), 0 /* get sets & ways */
MOVW $CACHECONF, R8
/* get log2linelen into l1setsh */
MOVW R0, R1
AND $3, R1
ADD $4, R1
/* l1 & l2 must have same cache line size, thus same set shift */
MOVW R1, 4(R8) /* +4 = l1setsh */
MOVW R1, 12(R8) /* +12 = l2setsh */
/* get nways in R1 */
SRA $3, R0, R1
AND $((1<<10)-1), R1
ADD $1, R1
/* get log2(nways) in R2 (assume nways is 2^n) */
MOVW $(BI2BY*BY2WD - 1), R2
CLZ(1, 1)
SUB.S R1, R2 /* R2 = 31 - clz(nways) */
ADD.EQ $1, R2
// MOVW R2, R3 /* print log2(nways): 2 */
MOVW $32, R1
SUB R2, R1 /* R1 = 32 - log2(nways) */
MOVW R1, 0(R8) /* +0 = l1waysh */
BARRIERS
MOVW $testmem-KZERO(SB), R0
BL memdiag(SB)
/*
* the mpcore manual says invalidate d-cache, scu, pl310 in that order,
* but says nothing about when to disable them.
*
* invalidate my caches before enabling
*/
BL cachedinv(SB)
MTCP CpSC, 0, PC, C(CpCACHE), C(CpCACHEinvi), CpCACHEall
BARRIERS
PUTC('f')
/*
* the mpcore manual says enable scu, d-cache, pl310, smp mode
* in that order. we have to reverse the last two; see main().
*/
BL scuon(SB)
/*
* turn my L1 cache on; need it for tas below.
*/
MFCP CpSC, 0, R1, C(CpCONTROL), C(0), CpMainctl
ORR $(CpCdcache|CpCicache|CpCalign|CpCpredict), R1
MTCP CpSC, 0, R1, C(CpCONTROL), C(0), CpMainctl
BARRIERS
/* cortex-a9 model-specific configuration */
MOVW $CpACl1pref, R1
MTCP CpSC, 0, R1, C(CpCONTROL), C(0), CpAuxctl
BARRIERS
/* we're supposed to wait until l1 & l2 are on before calling smpon */
PUTC('r')
/* set the domain access control */
MOVW $Client, R0
BL dacput(SB)
DELAY(printloop5, 2)
PUTC('o')
BL mmuinvalidate(SB)
MOVW $0, R0
BL pidput(SB)
/* set the translation table base */
MOVW $PADDR(L1), R0
BL ttbput(SB)
PUTC('m')
/*
* the little dance to turn the MMU on
*/
BL cacheuwbinv(SB)
BL mmuinvalidate(SB)
BL mmuenable(SB)
PUTC(' ')
/* warp the PC into the virtual map */
MOVW $KZERO, R0
BL _r15warp(SB)
/*
* cpu 0 is now running at KZERO+something!
*/
BARRIERS
MOVW $setR12(SB), R12 /* reload kernel SB */
MOVW $(KZERO | TMPSTACK), SP
BL cacheuwbinv(SB)
PUTC('B')
MOVW $PHYSDRAM, R3 /* pa */
CMP $KZERO, R3
BEQ no2unmap
/* undo double map of PHYSDRAM, KZERO & first few MBs */
MOVW $(L1+L1X(PHYSDRAM)), R4 /* addr. of PTE for PHYSDRAM */
MOVW $0, R0
MOVW $DOUBLEMAPMBS, R5
_ptudbl:
ZEROPTE()
SUB.S $1, R5
BNE _ptudbl
no2unmap:
BL cachedwb(SB)
BL mmuinvalidate(SB)
/*
* call main in C
* pass Mach to main and set up the stack in it
*/
MOVW $MACHADDR, R0 /* cpu 0 Mach */
MOVW R0, R(MACH) /* m = MACHADDR */
ADD $(MACHSIZE-4), R0, SP /* leave space for link register */
PUTC('e')
BL main(SB) /* main(m) */
limbo:
BL idlehands(SB)
B limbo
BL _div(SB) /* hack to load _div, etc. */
/*
* called on cpu(s) other than 0, to start them, from _vrst
* (reset vector) in lexception.s, with interrupts disabled
* and in SVC mode, running in the zero segment (pc is in lower 256MB).
* SB is set for the zero segment.
*/
TEXT cpureset(SB), 1, $-4
CLREX
MOVW CPSR, R0
ORR $PsrDfiq, R0
MOVW R0, CPSR
MOVW $(PHYSDRAM | TMPSTACK), SP /* stack for cache ops */
/* paranoia: turn my mmu and caches off. */
MFCP CpSC, 0, R0, C(CpCONTROL), C(0), CpMainctl
ORR $CpCsbo, R0
BIC $(CpCsbz|CpCmmu|CpCdcache|CpCicache|CpCpredict), R0
MTCP CpSC, 0, R0, C(CpCONTROL), C(0), CpMainctl
BARRIERS
/* cortex-a9 model-specific initial configuration */
MOVW $0, R1
MTCP CpSC, 0, R1, C(CpCONTROL), C(0), CpAuxctl
ISB
/* invalidate my caches before enabling */
BL cachedinv(SB)
MTCP CpSC, 0, PC, C(CpCACHE), C(CpCACHEinvi), CpCACHEall
BARRIERS
/*
* turn my L1 cache on; need it (and mmu) for tas below.
* need branch prediction to make delay() timing right.
*/
MFCP CpSC, 0, R0, C(CpCONTROL), C(0), CpMainctl
ORR $(CpCdcache|CpCicache|CpCalign|CpCpredict), R0
MTCP CpSC, 0, R0, C(CpCONTROL), C(0), CpMainctl
BARRIERS
/* enable l1 caches coherency, at minimum for ldrex/strex. */
BL smpon(SB)
BARRIERS
/*
* we used to write to PHYSEVP here; now we do it in C, which offers
* more assurance that we're up and won't go off the rails.
*/
/* set the domain access control */
MOVW $Client, R0
BL dacput(SB)
BL setmach(SB)
/*
* redo double map of PHYSDRAM, KZERO in this cpu's ptes.
* mmuinit will undo this later.
*/
MOVW $PHYSDRAM, R3
CMP $KZERO, R3
BEQ noun2map
/* launchinit set m->mmul1 to a copy of cpu0's l1 page table */
MOVW 12(R(MACH)), R0 /* m->mmul1 (virtual addr) */
BL k2paddr(SB) /* R0 = PADDR(m->mmul1) */
ADD $L1X(PHYSDRAM), R0, R4 /* R4 = address of PHYSDRAM's PTE */
MOVW $PTEDRAM, R2 /* PTE bits */
MOVW $DOUBLEMAPMBS, R5
_ptrdbl:
ORR R3, R2, R1 /* first identity-map 0 to 0, etc. */
MOVW R1, (R4)
ADD $4, R4 /* bump PTE address */
ADD $MiB, R3 /* bump pa */
SUB.S $1, R5
BNE _ptrdbl
noun2map:
MOVW $0, R0
BL pidput(SB)
/* set the translation table base to PADDR(m->mmul1) */
MOVW 12(R(MACH)), R0 /* m->mmul1 */
BL k2paddr(SB) /* R0 = PADDR(m->mmul1) */
BL ttbput(SB)
/*
* the little dance to turn the MMU on
*/
BL cacheuwbinv(SB)
BL mmuinvalidate(SB)
BL mmuenable(SB)
/*
* mmu is now on, with l1 pt at m->mmul1.
*/
/* warp the PC into the virtual map */
MOVW $KZERO, R0
BL _r15warp(SB)
/*
* now running at KZERO+something!
*/
BARRIERS
MOVW $setR12(SB), R12 /* reload kernel's SB */
MOVW $(KZERO | TMPSTACK), SP /* stack for cache ops*/
BL setmach(SB)
ADD $(MACHSIZE-4), R(MACH), SP /* leave space for link register */
BL cpustart(SB)
/*
* converts virtual address in R0 to a physical address.
*/
TEXT k2paddr(SB), 1, $-4
BIC $KSEGM, R0
ADD $PHYSDRAM, R0
RET
/*
* converts physical address in R0 to a virtual address.
*/
TEXT p2kaddr(SB), 1, $-4
BIC $KSEGM, R0
ORR $KZERO, R0
RET
/*
* converts address in R0 to the current segment, as defined by the PC.
* clobbers R1.
*/
TEXT addr2pcseg(SB), 1, $-4
BIC $KSEGM, R0
MOVW PC, R1
AND $KSEGM, R1 /* segment PC is in */
ORR R1, R0
RET
/* sets R(MACH), preserves other registers */
TEXT setmach(SB), 1, $-4
MOVM.DB.W [R14], (R13)
MOVM.DB.W [R0-R2], (R13)
CPUID(R2)
SLL $2, R2 /* convert to word index */
MOVW $machaddr(SB), R0
BL addr2pcseg(SB)
ADD R2, R0 /* R0 = &machaddr[cpuid] */
MOVW (R0), R0 /* R0 = machaddr[cpuid] */
CMP $0, R0
MOVW.EQ $MACHADDR, R0 /* paranoia: use MACHADDR if 0 */
BL addr2pcseg(SB)
MOVW R0, R(MACH) /* m = machaddr[cpuid] */
MOVM.IA.W (R13), [R0-R2]
MOVM.IA.W (R13), [R14]
RET
/*
* memory diagnostic
* tests word at (R0); modifies R7 and R8
*/
TEXT memdiag(SB), 1, $-4
MOVW $0xabcdef89, R7
MOVW R7, (R0)
MOVW (R0), R8
CMP R7, R8
BNE mbuggery /* broken memory */
BARRIERS
MOVW (R0), R8
CMP R7, R8
BNE mbuggery /* broken memory */
MOVW $0, R7
MOVW R7, (R0)
BARRIERS
RET
/* modifies R0, R3—R6 */
TEXT printhex(SB), 1, $-4
MOVW R0, R3
PUTC('0')
PUTC('x')
MOVW $(32-4), R5 /* bits to shift right */
nextdig:
SRA R5, R3, R4
AND $0xf, R4
ADD $'0', R4
CMP.S $'9', R4
BLE nothex /* if R4 <= 9, jump */
ADD $('a'-('9'+1)), R4
nothex:
PUTC(R4)
SUB.S $4, R5
BGE nextdig
PUTC('\r')
PUTC('\n')
DELAY(proct, 50)
RET
mbuggery:
PUTC('?')
PUTC('m')
mtopanic:
MOVW $membmsg(SB), R0
MOVW R14, R1 /* get R14's segment ... */
AND $KSEGM, R1
BIC $KSEGM, R0 /* strip segment from address */
ORR R1, R0 /* combine them */
BL panic(SB)
mbugloop:
WFI
B mbugloop
DATA membmsg+0(SB)/8,$"memory b"
DATA membmsg+8(SB)/6,$"roken\z"
GLOBL membmsg(SB), $14
TEXT _r15warp(SB), 1, $-4
BIC $KSEGM, R14 /* link reg, will become PC */
ORR R0, R14
BIC $KSEGM, SP
ORR R0, SP
RET
/*
* `single-element' cache operations.
* in arm arch v7, they operate on all architected cache levels, so separate
* l2 functions are usually unnecessary.
*/
TEXT cachedwbse(SB), $-4 /* D writeback SE */
MOVW R0, R2
MOVW CPSR, R3
CPSID /* splhi */
BARRIERS /* force outstanding stores to cache */
MOVW R2, R0
MOVW 4(FP), R1
ADD R0, R1 /* R1 is end address */
BIC $(CACHELINESZ-1), R0 /* cache line start */
_dwbse:
MTCP CpSC, 0, R0, C(CpCACHE), C(CpCACHEwb), CpCACHEse
ADD $CACHELINESZ, R0
CMP.S R0, R1
BGT _dwbse
B _wait
TEXT cachedwbinvse(SB), $-4 /* D writeback+invalidate SE */
MOVW R0, R2
MOVW CPSR, R3
CPSID /* splhi */
BARRIERS /* force outstanding stores to cache */
MOVW R2, R0
MOVW 4(FP), R1
ADD R0, R1 /* R1 is end address */
BIC $(CACHELINESZ-1), R0 /* cache line start */
_dwbinvse:
MTCP CpSC, 0, R0, C(CpCACHE), C(CpCACHEwbi), CpCACHEse
ADD $CACHELINESZ, R0
CMP.S R0, R1
BGT _dwbinvse
_wait: /* drain write buffer */
BARRIERS
MOVW R3, CPSR /* splx */
RET
TEXT cachedinvse(SB), $-4 /* D invalidate SE */
MOVW R0, R2
MOVW CPSR, R3
CPSID /* splhi */
BARRIERS /* force outstanding stores to cache */
MOVW R2, R0
MOVW 4(FP), R1
ADD R0, R1 /* R1 is end address */
/*
* if start & end addresses are not on cache-line boundaries,
* flush first & last cache lines before invalidating.
*/
AND.S $(CACHELINESZ-1), R0, R4
BEQ stok
BIC $(CACHELINESZ-1), R0, R4 /* cache line start */
MTCP CpSC, 0, R4, C(CpCACHE), C(CpCACHEwb), CpCACHEse
stok:
AND.S $(CACHELINESZ-1), R1, R4
BEQ endok
BIC $(CACHELINESZ-1), R1, R4 /* cache line start */
MTCP CpSC, 0, R4, C(CpCACHE), C(CpCACHEwb), CpCACHEse
endok:
BIC $(CACHELINESZ-1), R0 /* cache line start */
_dinvse:
MTCP CpSC, 0, R0, C(CpCACHE), C(CpCACHEinvd), CpCACHEse
ADD $CACHELINESZ, R0
CMP.S R0, R1
BGT _dinvse
B _wait
/*
* enable mmu and high vectors
*/
TEXT mmuenable(SB), 1, $-4
MFCP CpSC, 0, R0, C(CpCONTROL), C(0), CpMainctl
ORR $CpCmmu, R0
MTCP CpSC, 0, R0, C(CpCONTROL), C(0), CpMainctl
BARRIERS
RET
TEXT mmudisable(SB), 1, $-4
MFCP CpSC, 0, R0, C(CpCONTROL), C(0), CpMainctl
BIC $CpCmmu, R0
MTCP CpSC, 0, R0, C(CpCONTROL), C(0), CpMainctl
BARRIERS
RET
/*
* If one of these MCR instructions crashes or hangs the machine,
* check your Level 1 page table (at TTB) closely.
*/
TEXT mmuinvalidate(SB), $-4 /* invalidate all */
MOVW CPSR, R2
CPSID /* interrupts off */
BARRIERS
MTCP CpSC, 0, PC, C(CpTLB), C(CpTLBinvu), CpTLBinv
BARRIERS
MOVW R2, CPSR /* interrupts restored */
RET
TEXT mmuinvalidateaddr(SB), $-4 /* invalidate single entry */
MTCP CpSC, 0, R0, C(CpTLB), C(CpTLBinvu), CpTLBinvse
BARRIERS
RET
TEXT cpidget(SB), 1, $-4 /* main ID */
MFCP CpSC, 0, R0, C(CpID), C(CpIDidct), CpIDid
RET
TEXT cpctget(SB), 1, $-4 /* cache type */
MFCP CpSC, 0, R0, C(CpID), C(CpIDidct), CpIDct
RET
TEXT controlget(SB), 1, $-4 /* system control (sctlr) */
MFCP CpSC, 0, R0, C(CpCONTROL), C(0), CpMainctl
RET
TEXT ttbget(SB), 1, $-4 /* translation table base */
MFCP CpSC, 0, R0, C(CpTTB), C(0), CpTTB0
RET
TEXT ttbput(SB), 1, $-4 /* translation table base */
MOVW CPSR, R2
CPSID
MOVW R0, R1
BARRIERS /* finish prior accesses before changing ttb */
MTCP CpSC, 0, R1, C(CpTTB), C(0), CpTTB0
MTCP CpSC, 0, R1, C(CpTTB), C(0), CpTTB1 /* non-secure too */
MOVW $0, R0
MTCP CpSC, 0, R0, C(CpTTB), C(0), CpTTBctl
BARRIERS
MOVW R2, CPSR
RET
TEXT dacget(SB), 1, $-4 /* domain access control */
MFCP CpSC, 0, R0, C(CpDAC), C(0)
RET
TEXT dacput(SB), 1, $-4 /* domain access control */
MOVW R0, R1
BARRIERS
MTCP CpSC, 0, R1, C(CpDAC), C(0)
ISB
RET
TEXT fsrget(SB), 1, $-4 /* fault status */
MFCP CpSC, 0, R0, C(CpFSR), C(0), CpDFSR
RET
TEXT farget(SB), 1, $-4 /* fault address */
MFCP CpSC, 0, R0, C(CpFAR), C(0), CpDFAR
RET
TEXT getpsr(SB), 1, $-4
MOVW CPSR, R0
RET
TEXT getscr(SB), 1, $-4 /* secure configuration */
MFCP CpSC, 0, R0, C(CpCONTROL), C(CpCONTROLscr), CpSCRscr
RET
TEXT pidget(SB), 1, $-4 /* address translation pid */
MFCP CpSC, 0, R0, C(CpPID), C(0x0)
RET
TEXT pidput(SB), 1, $-4 /* address translation pid */
MTCP CpSC, 0, R0, C(CpPID), C(0), 0 /* pid, v7a deprecated */
MTCP CpSC, 0, R0, C(CpPID), C(0), 1 /* context id, errata 754322 */
ISB
RET
/*
* access to yet more coprocessor registers
*/
TEXT getauxctl(SB), 1, $-4 /* get cortex-a9 aux. ctl. */
MFCP CpSC, 0, R0, C(CpCONTROL), C(0), CpAuxctl
RET
TEXT putauxctl(SB), 1, $-4 /* put cortex-a9 aux. ctl. */
BARRIERS
MTCP CpSC, 0, R0, C(CpCONTROL), C(0), CpAuxctl
BARRIERS
RET
TEXT getclvlid(SB), 1, $-4
MFCP CpSC, CpIDcsize, R0, C(CpID), C(CpIDidct), CpIDclvlid
RET
TEXT getcyc(SB), 1, $-4
MFCP CpSC, 0, R0, C(CpCLD), C(CpCLDcyc), 0
RET
TEXT getdebug(SB), 1, $-4 /* get cortex-a9 debug enable register */
MFCP CpSC, 0, R0, C(1), C(1), 1
RET
TEXT getpc(SB), 1, $-4
MOVW PC, R0
RET
TEXT getsb(SB), 1, $-4
MOVW R12, R0
RET
TEXT setsp(SB), 1, $-4
MOVW R0, SP
RET
TEXT splhi(SB), 1, $-4
MOVW CPSR, R0 /* return old CPSR */
CPSID /* turn off interrupts */
CMP.S $0, R(MACH)
MOVW.NE R14, 4(R(MACH)) /* save caller pc in m->splpc */
RET
TEXT spllo(SB), 1, $-4 /* start marker for devkprof.c */
MOVW CPSR, R0 /* return old CPSR */
MOVW $0, R1
CMP.S R1, R(MACH)
MOVW.NE R1, 4(R(MACH)) /* clear m->splpc */
CPSIE
RET
TEXT splx(SB), 1, $-4
MOVW CPSR, R3 /* must return old CPSR */
CPSID
CMP.S $0, R(MACH)
MOVW.NE R14, 4(R(MACH)) /* save caller pc in m->splpc */
MOVW R0, CPSR /* reset interrupt level */
MOVW R3, R0 /* must return old CPSR */
RET
TEXT spldone(SB), 1, $0 /* end marker for devkprof.c */
RET
TEXT islo(SB), 1, $-4
MOVW CPSR, R0
AND $(PsrDirq), R0
EOR $(PsrDirq), R0
RET
TEXT clz(SB), $-4
CLZ(0, 0) /* 0 is R0 */
RET
TEXT setlabel(SB), 1, $-4
MOVW SP, 0(R0)
MOVW R14, 4(R0) /* pc */
MOVW $0, R0
RET
TEXT gotolabel(SB), 1, $-4
MOVW 0(R0), SP
MOVW 4(R0), R14 /* pc */
MOVW $1, R0
RET
TEXT getcallerpc(SB), 1, $-4
MOVW 0(SP), R0
RET
TEXT wfi(SB), $-4
MOVW CPSR, R1
/*
* an interrupt should break us out of wfi. masking interrupts
* slows interrupt response slightly but prevents recursion.
*/
// CPSIE
CPSID
BARRIERS
WFI
MOVW R1, CPSR
RET
TEXT coherence(SB), $-4
BARRIERS
RET
GLOBL cpus_proceed+0(SB), $4
#include "cache.v7.s"
TEXT cas(SB),0,$12
TEXT cmpswap(SB),0,$12 /* r0 holds p */
MOVW ov+4(FP), R1
MOVW nv+8(FP), R2
spin:
/* LDREX 0(R0),R3 */
LDREX(0,3)
CMP.S R3, R1
BNE fail
/* STREX 0(R0),R2,R4 */
STREX(0,2,4)
CMP.S $0, R4
BNE spin
MOVW $1, R0
DMB
RET
fail:
MOVW $0, R0
RET
TEXT tas(SB), $-4 /* _tas(ulong *) */
TEXT _tas(SB), $-4
/* returns old (R0) after modifying (R0) */
MOVW R0,R5
DMB
MOVW $1,R2 /* new value of (R0) */
MOVW $MAXSC, R8
tas1:
LDREX(5,7) /* LDREX 0(R5),R7 */
CMP.S $0, R7 /* old value non-zero (lock taken)? */
BNE lockbusy /* we lose */
SUB.S $1, R8
BEQ lockloop2
STREX(2,5,4) /* STREX R2,(R5),R4 */
CMP.S $0, R4
BNE tas1 /* strex failed? try again */
DMB
B tas0
lockloop2:
PUTC('?')
PUTC('l')
PUTC('t')
BL abort(SB)
lockbusy:
CLREX
tas0:
MOVW R7, R0 /* return old value */
RET
|
9front/9front
| 5,687
|
sys/src/9/teg2/cache.v7.s
|
/*
* cortex arm arch v7 cache flushing and invalidation
* included by l.s and rebootcode.s
*/
TEXT cacheiinv(SB), $-4 /* I invalidate */
MOVW $0, R0
MTCP CpSC, 0, R0, C(CpCACHE), C(CpCACHEinvi), CpCACHEall /* ok on cortex */
ISB
RET
/*
* set/way operators, passed a suitable set/way value in R0.
*/
TEXT cachedwb_sw(SB), $-4
MTCP CpSC, 0, R0, C(CpCACHE), C(CpCACHEwb), CpCACHEsi
RET
TEXT cachedwbinv_sw(SB), $-4
MTCP CpSC, 0, R0, C(CpCACHE), C(CpCACHEwbi), CpCACHEsi
RET
TEXT cachedinv_sw(SB), $-4
MTCP CpSC, 0, R0, C(CpCACHE), C(CpCACHEinvd), CpCACHEsi
RET
/* set cache size select */
TEXT setcachelvl(SB), $-4
MTCP CpSC, CpIDcssel, R0, C(CpID), C(CpIDidct), 0
ISB
RET
/* return cache sizes */
TEXT getwayssets(SB), $-4
MFCP CpSC, CpIDcsize, R0, C(CpID), C(CpIDidct), 0
RET
/*
* l1 cache operations.
* l1 and l2 ops are intended to be called from C, thus need save no
* caller's regs, only those we need to preserve across calls.
*/
TEXT cachedwb(SB), $-4
MOVW.W R14, -8(R13)
MOVW $cachedwb_sw(SB), R0
MOVW $1, R8
BL wholecache(SB)
MOVW.P 8(R13), R15
TEXT cachedwbinv(SB), $-4
MOVW.W R14, -8(R13)
MOVW $cachedwbinv_sw(SB), R0
MOVW $1, R8
BL wholecache(SB)
MOVW.P 8(R13), R15
TEXT cachedinv(SB), $-4
MOVW.W R14, -8(R13)
MOVW $cachedinv_sw(SB), R0
MOVW $1, R8
BL wholecache(SB)
MOVW.P 8(R13), R15
TEXT cacheuwbinv(SB), $-4
MOVM.DB.W [R14], (R13) /* save lr on stack */
MOVW CPSR, R1
CPSID /* splhi */
MOVM.DB.W [R1], (R13) /* save R1 on stack */
BL cachedwbinv(SB)
BL cacheiinv(SB)
MOVM.IA.W (R13), [R1] /* restore R1 (saved CPSR) */
MOVW R1, CPSR
MOVM.IA.W (R13), [R14] /* restore lr */
RET
/*
* architectural l2 cache operations
*/
TEXT _l2cacheuwb(SB), $-4
MOVW.W R14, -8(R13)
MOVW $cachedwb_sw(SB), R0
MOVW $2, R8
BL wholecache(SB)
MOVW.P 8(R13), R15 /* return */
TEXT _l2cacheuwbinv(SB), $-4
MOVW.W R14, -8(R13)
MOVW CPSR, R1
CPSID /* splhi */
MOVM.DB.W [R1], (R13) /* save R1 on stack */
MOVW $cachedwbinv_sw(SB), R0
MOVW $2, R8
BL wholecache(SB)
BL _l2cacheuinv(SB)
MOVM.IA.W (R13), [R1] /* restore R1 (saved CPSR) */
MOVW R1, CPSR
MOVW.P 8(R13), R15 /* return */
TEXT _l2cacheuinv(SB), $-4
MOVW.W R14, -8(R13)
MOVW $cachedinv_sw(SB), R0
MOVW $2, R8
BL wholecache(SB)
MOVW.P 8(R13), R15 /* return */
/*
* callers are assumed to be the above l1 and l2 ops.
* R0 is the function to call in the innermost loop.
* R8 is the cache level (1-origin: 1 or 2).
*
* R0 func to call at entry
* R1 func to call after entry
* R2 nsets
* R3 way shift (computed from R8)
* R4 set shift (computed from R8)
* R5 nways
* R6 set scratch
* R7 way scratch
* R8 cache level, 0-origin
* R9 extern reg up
* R10 extern reg m
*
* initial translation by 5c, then massaged by hand.
*/
TEXT wholecache+0(SB), $-4
MOVW CPSR, R2
MOVM.DB.W [R2,R14], (SP) /* save regs on stack */
MOVW R0, R1 /* save argument for inner loop in R1 */
SUB $1, R8 /* convert cache level to zero origin */
/* we might not have the MMU on yet, so map R1 (func) to R14's space */
MOVW R14, R0 /* get R14's segment ... */
AND $KSEGM, R0
BIC $KSEGM, R1 /* strip segment from func address */
ORR R0, R1 /* combine them */
/* get cache sizes */
SLL $1, R8, R0 /* R0 = (cache - 1) << 1 */
MTCP CpSC, CpIDcssel, R0, C(CpID), C(CpIDidct), 0 /* set cache select */
ISB
MFCP CpSC, CpIDcsize, R0, C(CpID), C(CpIDidct), 0 /* get cache sizes */
/* compute # of ways and sets for this cache level */
SRA $3, R0, R5 /* R5 (ways) = R0 >> 3 */
AND $((1<<10)-1), R5 /* R5 = (R0 >> 3) & MASK(10) */
ADD $1, R5 /* R5 (ways) = ((R0 >> 3) & MASK(10)) + 1 */
SRA $13, R0, R2 /* R2 = R0 >> 13 */
AND $((1<<15)-1), R2 /* R2 = (R0 >> 13) & MASK(15) */
ADD $1, R2 /* R2 (sets) = ((R0 >> 13) & MASK(15)) + 1 */
/* precompute set/way shifts for inner loop */
MOVW $(CACHECONF+0), R3 /* +0 = l1waysh */
MOVW $(CACHECONF+4), R4 /* +4 = l1setsh */
CMP $0, R8 /* cache == 1? */
ADD.NE $(4*2), R3 /* no, assume l2: +8 = l2waysh */
ADD.NE $(4*2), R4 /* +12 = l2setsh */
MOVW R14, R0 /* get R14's segment ... */
AND $KSEGM, R0
BIC $KSEGM, R3 /* strip segment from address */
ORR R0, R3 /* combine them */
BIC $KSEGM, R4 /* strip segment from address */
ORR R0, R4 /* combine them */
MOVW (R3), R3
MOVW (R4), R4
CMP $0, R3 /* sanity checks */
BEQ wbuggery
CMP $0, R4
BEQ sbuggery
CPSID /* splhi to make entire op atomic */
BARRIERS
/* iterate over ways */
MOVW $0, R7 /* R7: way */
outer:
/* iterate over sets */
MOVW $0, R6 /* R6: set */
inner:
/* compute set/way register contents */
SLL R3, R7, R0 /* R0 = way << R3 (L?WAYSH) */
ORR R8<<1, R0 /* R0 = way << L?WAYSH | (cache - 1) << 1 */
ORR R6<<R4, R0 /* R0 = way<<L?WAYSH | (cache-1)<<1 |set<<R4 */
BL (R1) /* call set/way operation with R0 arg. */
ADD $1, R6 /* set++ */
CMP R2, R6 /* set >= sets? */
BLT inner /* no, do next set */
ADD $1, R7 /* way++ */
CMP R5, R7 /* way >= ways? */
BLT outer /* no, do next way */
MOVM.IA.W (SP), [R2,R14] /* restore regs */
BARRIERS
MOVW R2, CPSR /* splx */
RET
wbuggery:
PUTC('?')
PUTC('c')
PUTC('w')
B topanic
sbuggery:
PUTC('?')
PUTC('c')
PUTC('s')
topanic:
MOVW $.string<>+0(SB), R0
BIC $KSEGM, R0 /* strip segment from address */
MOVW R14, R1 /* get R14's segment ... */
AND $KSEGM, R1
ORR R1, R0 /* combine them */
SUB $12, R13 /* not that it matters, since we're panicing */
MOVW R14, 8(R13)
BL panic(SB) /* panic("msg %#p", LR) */
bugloop:
WFI
B bugloop
DATA .string<>+0(SB)/8,$"bad cach"
DATA .string<>+8(SB)/8,$"e params"
DATA .string<>+16(SB)/8,$"\073 pc %\043p"
DATA .string<>+24(SB)/1,$"\z"
GLOBL .string<>+0(SB),$25
|
9front/9front
| 4,084
|
sys/src/9/teg2/arm.s
|
/*
* nvidia tegra 2 machine assist, definitions
* dual-core cortex-a9 processor
*
* R9 and R10 are used for `extern register' variables.
* R11 is used by the loader as a temporary, so avoid it.
*/
#include "mem.h"
#include "arm.h"
#undef B /* B is for 'botch' */
#define KADDR(pa) (KZERO | ((pa) & ~KSEGM))
#define PADDR(va) (PHYSDRAM | ((va) & ~KSEGM))
#define L1X(va) (((((va))>>20) & 0x0fff)<<2)
#define MACHADDR (L1-MACHSIZE) /* only room for cpu0's */
/* L1 pte values */
#define PTEDRAM (Dom0|L1AP(Krw)|Section|L1ptedramattrs)
#define PTEIO (Dom0|L1AP(Krw)|Section)
#define DOUBLEMAPMBS 512 /* megabytes of low dram to double-map */
/* steps on R0 */
#define DELAY(label, mloops) \
MOVW $((mloops)*1000000), R0; \
label: \
SUB.S $1, R0; \
BNE label
/* print a byte on the serial console; clobbers R0 & R6; needs R12 (SB) set */
#define PUTC(c) \
BARRIERS; \
MOVW $(c), R0; \
MOVW $PHYSCONS, R6; \
MOVW R0, (R6); \
BARRIERS
/*
* new instructions
*/
#define SMC WORD $0xe1600070 /* low 4-bits are call # (trustzone) */
/* flush branch-target cache */
#define FLBTC MTCP CpSC, 0, PC, C(CpCACHE), C(CpCACHEinvi), CpCACHEflushbtc
/* flush one entry of the branch-target cache, va in R0 (cortex) */
#define FLBTSE MTCP CpSC, 0, R0, C(CpCACHE), C(CpCACHEinvi), CpCACHEflushbtse
/* arm v7 arch defines these */
#define DSB WORD $0xf57ff04f /* data synch. barrier; last f = SY */
#define DMB WORD $0xf57ff05f /* data mem. barrier; last f = SY */
#define ISB WORD $0xf57ff06f /* instr. sync. barrier; last f = SY */
#define WFI WORD $0xe320f003 /* wait for interrupt */
#define NOOP WORD $0xe320f000
#define CLZ(s, d) WORD $(0xe16f0f10 | (d) << 12 | (s)) /* count leading 0s */
#define SETEND(o) WORD $(0xf1010000 | (o) << 9) /* o==0, little-endian */
#define CPSIE WORD $0xf1080080 /* intr enable: zeroes I bit */
#define CPSID WORD $0xf10c00c0 /* intr disable: sets I,F bits */
#define CPSAE WORD $0xf1080100 /* async abt enable: zeroes A bit */
#define CPSMODE(m) WORD $(0xf1020000 | (m)) /* switch to mode m (PsrM*) */
#define CLREX WORD $0xf57ff01f
/* floating point */
#define VMRS(fp, cpu) WORD $(0xeef00a10 | (fp)<<16 | (cpu)<<12) /* FP → arm */
#define VMSR(cpu, fp) WORD $(0xeee00a10 | (fp)<<16 | (cpu)<<12) /* arm → FP */
/*
* a popular code sequence used to write a pte for va is:
*
* MOVW R(n), TTB[LnX(va)]
* // clean the cache line
* DSB
* // invalidate tlb entry for va
* FLBTC
* DSB
* PFF (now ISB)
*/
#define BARRIERS FLBTC; DSB; ISB
/*
* invoked with PTE bits in R2, pa in R3, PTE pointed to by R4.
* fill PTE pointed to by R4 and increment R4 past it.
* increment R3 by a MB. clobbers R1.
*/
#define FILLPTE() \
ORR R3, R2, R1; /* pte bits in R2, pa in R3 */ \
MOVW R1, (R4); \
ADD $4, R4; /* bump PTE address */ \
ADD $MiB, R3; /* bump pa */ \
/* zero PTE pointed to by R4 and increment R4 past it. assumes R0 is 0. */
#define ZEROPTE() \
MOVW R0, (R4); \
ADD $4, R4; /* bump PTE address */
/*
* set kernel SB for zero segment (instead of usual KZERO segment).
* NB: the next line puts rubbish in R12:
* MOVW $setR12-KZERO(SB), R12
*/
#define SETZSB \
MOVW $setR12(SB), R12; /* load kernel's SB */ \
SUB $KZERO, R12; \
ADD $PHYSDRAM, R12
/*
* note that 5a's RFE is not the v6/7 arch. instruction (0xf8900a00),
* which loads CPSR from the word after the PC at (R13), but rather
* the pre-v6 simulation `MOVM.IA.S.W (R13), [R15]' (0xe8fd8000 since
* MOVM is LDM in this case), which loads CPSR not from memory but
* from SPSR due to `.S'.
*/
#define RFEV7(r) WORD $(0xf8900a00 | (r) << 16)
#define RFEV7W(r) WORD $(0xf8900a00 | (r) << 16 | 0x00200000) /* RFE.W */
#define RFEV7DB(r) WORD $(0xf9100a00 | (r) << 16) /* RFE.DB */
#define RFEV7DBW(r) WORD $(0xf9100a00 | (r) << 16 | 0x00200000) /* RFE.DB.W */
#define CKPSR(psr, tmp, bad)
#define CKCPSR(psrtmp, tmp, bad)
/* return with cpu id in r and condition codes set from "r == 0" */
#define CPUID(r) \
MFCP CpSC, 0, r, C(CpID), C(CpIDidct), CpIDmpid; \
AND.S $(MAXMACH-1), r /* mask out non-cpu-id bits */
|
9front/9front
| 8,905
|
sys/src/9/teg2/lexception.s
|
/*
* arm exception handlers
*/
#include "arm.s"
#undef B /* B is for 'botch' */
/*
* exception vectors, copied by trapinit() to somewhere useful
*/
TEXT vectors(SB), 1, $-4
MOVW 0x18(R15), R15 /* reset */
MOVW 0x18(R15), R15 /* undefined instr. */
MOVW 0x18(R15), R15 /* SWI & SMC */
MOVW 0x18(R15), R15 /* prefetch abort */
MOVW 0x18(R15), R15 /* data abort */
MOVW 0x18(R15), R15 /* hypervisor call */
MOVW 0x18(R15), R15 /* IRQ */
MOVW 0x18(R15), R15 /* FIQ */
TEXT vtable(SB), 1, $-4
WORD $_vrst-KZERO(SB) /* reset, in svc mode already */
WORD $_vund(SB) /* undefined, switch to svc mode */
WORD $_vsvc(SB) /* swi, in svc mode already */
WORD $_vpabt(SB) /* prefetch abort, switch to svc mode */
WORD $_vdabt(SB) /* data abort, switch to svc mode */
WORD $_vhype(SB) /* hypervisor call */
WORD $_virq(SB) /* IRQ, switch to svc mode */
WORD $_vfiq(SB) /* FIQ, switch to svc mode */
/*
* reset - start additional cpus
*/
TEXT _vrst(SB), 1, $-4
/* running in the zero segment (pc is lower 256MB) */
CPSMODE(PsrMsvc) /* should be redundant */
CPSID
CPSAE
SETEND(0) /* force little-endian */
BARRIERS
SETZSB
MOVW $PsrMsvc, SPSR
MOVW $0, R14
/* invalidate i-cache and branch-target cache */
MTCP CpSC, 0, PC, C(CpCACHE), C(CpCACHEinvi), CpCACHEall
BARRIERS
BL cpureset(SB)
spin:
B spin
/*
* system call
*/
TEXT _vsvc(SB), 1, $-4 /* SWI */
CLREX
BARRIERS
/* stack is m->stack */
MOVW.W R14, -4(R13) /* ureg->pc = interrupted PC */
MOVW SPSR, R14 /* ureg->psr = SPSR */
MOVW.W R14, -4(R13) /* ... */
MOVW $PsrMsvc, R14 /* ureg->type = PsrMsvc */
MOVW.W R14, -4(R13) /* ... */
/* avoid the ambiguity described in notes/movm.w. */
MOVM.DB.S [R0-R14], (R13) /* save user level registers */
SUB $(NREGS*4), R13 /* r13 now points to ureg */
MOVW $setR12(SB), R12 /* Make sure we've got the kernel's SB loaded */
/*
* set up m and up registers since user registers could contain anything
*/
CPUID(R1)
SLL $2, R1 /* convert to word index */
MOVW $machaddr(SB), R2
ADD R1, R2
MOVW (R2), R(MACH) /* m = machaddr[cpuid] */
CMP $0, R(MACH)
MOVW.EQ $MACHADDR, R0 /* paranoia: use MACHADDR if 0 */
MOVW 8(R(MACH)), R(USER) /* up = m->proc */
MOVW ((NREGS+1)*4)(R13), R2 /* saved SPSR (user mode) */
MOVW R13, R0 /* first arg is pointer to ureg */
SUB $8, R13 /* space for argument+link */
BL syscall(SB)
/*
* caller saves on plan 9, so registers other than 9, 10, 13 & 14
* may have been trashed when we get here.
*/
MOVW $setR12(SB), R12 /* reload kernel's SB */
ADD $(8+4*NREGS), R13 /* make r13 point to ureg->type */
MOVW 8(R13), R14 /* restore link */
MOVW 4(R13), R0 /* restore SPSR */
/*
* return from user-mode exception.
* expects new SPSR in R0. R13 must point to ureg->type.
*/
_rfue:
TEXT rfue(SB), 1, $-4
MOVW R0, SPSR /* ... */
/*
* order on stack is type, psr, pc, but RFEV7 needs pc, psr.
* step on type and previous word to hold temporary values.
* we could instead change the order in which psr & pc are pushed.
*/
MOVW 4(R13), R1 /* psr */
MOVW 8(R13), R2 /* pc */
MOVW R2, 4(R13) /* pc */
MOVW R1, 8(R13) /* psr */
MOVM.DB.S (R13), [R0-R14] /* restore user registers */
ADD $4, R13 /* pop type, sp -> pc */
RFEV7W(13)
TEXT _vund(SB), 1, $-4 /* undefined */
/* sp is m->sund */
MOVM.IA [R0-R4], (R13) /* free some working space */
MOVW $PsrMund, R0
B _vswitch
TEXT _vpabt(SB), 1, $-4 /* prefetch abort */
/* sp is m->sabt */
MOVM.IA [R0-R4], (R13) /* free some working space */
MOVW $PsrMabt, R0 /* r0 = type */
B _vswitch
TEXT _vdabt(SB), 1, $-4 /* data abort */
/* sp is m->sabt */
MOVM.IA [R0-R4], (R13) /* free some working space */
MOVW $(PsrMabt+1), R0 /* r0 = type */
B _vswitch
TEXT _virq(SB), 1, $-4 /* IRQ */
/* sp is m->sirq */
MOVM.IA [R0-R4], (R13) /* free some working space */
MOVW $PsrMirq, R0 /* r0 = type */
B _vswitch
/*
* come here with type in R0 and R13 pointing above saved [r0-r4].
* we'll switch to SVC mode and then call trap.
*/
_vswitch:
// TEXT _vswtch(SB), 1, $-4 /* make symbol visible to debuggers */
CLREX
BARRIERS
MOVW SPSR, R1 /* save SPSR for ureg */
/*
* R12 needs to be set before using PsrMbz, so BIGENDCHECK code has
* been moved below.
*/
MOVW R14, R2 /* save interrupted pc for ureg */
MOVW R13, R3 /* save pointer to where the original [R0-R4] are */
/*
* switch processor to svc mode. this switches the banked registers
* (r13 [sp] and r14 [link]) to those of svc mode (so we must be sure
* to never get here already in svc mode).
*/
CPSMODE(PsrMsvc) /* switch! */
CPSID
AND.S $0xf, R1, R4 /* interrupted code kernel or user? */
BEQ _userexcep
/*
* here for trap from SVC mode
*/
/* push ureg->{type, psr, pc} onto Msvc stack.
* r13 points to ureg->type after.
*/
MOVM.DB.W [R0-R2], (R13)
MOVM.IA (R3), [R0-R4] /* restore [R0-R4] from previous mode's stack */
/*
* avoid the ambiguity described in notes/movm.w.
* In order to get a predictable value in R13 after the stores,
* separate the store-multiple from the stack-pointer adjustment.
* We'll assume that the old value of R13 should be stored on the stack.
*/
/* save kernel level registers, at end r13 points to ureg */
MOVM.DB [R0-R14], (R13)
SUB $(NREGS*4), R13 /* SP now points to saved R0 */
MOVW $setR12(SB), R12 /* Make sure we've got the kernel's SB loaded */
/* previous mode was svc, so the saved spsr should be sane. */
MOVW ((NREGS+1)*4)(R13), R1
MOVM.IA (R13), [R0-R8] /* restore a few user registers */
MOVW R13, R0 /* first arg is pointer to ureg */
SUB $(4*2), R13 /* space for argument+link (for debugger) */
MOVW $0xdeaddead, R11 /* marker */
BL trap(SB) /* trap(ureg) */
/*
* caller saves on plan 9, so registers other than 9, 10, 13 & 14
* may have been trashed when we get here.
*/
MOVW $setR12(SB), R12 /* reload kernel's SB */
ADD $(4*2+4*NREGS), R13 /* make r13 point to ureg->type */
/*
* if we interrupted a previous trap's handler and are now
* returning to it, we need to propagate the current R(MACH) (R10)
* by overriding the saved one on the stack, since we may have
* been rescheduled and be on a different processor now than
* at entry.
*/
MOVW R(MACH), (-(NREGS-MACH)*4)(R13) /* restore current cpu's MACH */
MOVW 8(R13), R14 /* restore link */
MOVW 4(R13), R0 /* restore SPSR */
/* return from kernel-mode exception */
MOVW R0, SPSR /* ... */
/*
* order on stack is type, psr, pc, but RFEV7 needs pc, psr.
* step on type and previous word to hold temporary values.
* we could instead change the order in which psr & pc are pushed.
*/
MOVW 4(R13), R1 /* psr */
MOVW 8(R13), R2 /* pc */
MOVW R2, 4(R13) /* pc */
MOVW R1, 8(R13) /* psr */
/* restore kernel regs other than SP; we're using it */
SUB $(NREGS*4), R13
MOVM.IA.W (R13), [R0-R12]
ADD $4, R13 /* skip saved kernel SP */
MOVM.IA.W (R13), [R14]
ADD $4, R13 /* pop type, sp -> pc */
BARRIERS
RFEV7W(13)
/*
* here for trap from USER mode
*/
_userexcep:
MOVM.DB.W [R0-R2], (R13) /* set ureg->{type, psr, pc}; r13 points to ureg->type */
MOVM.IA (R3), [R0-R4] /* restore [R0-R4] from previous mode's stack */
/* avoid the ambiguity described in notes/movm.w. */
MOVM.DB.S [R0-R14], (R13) /* save kernel level registers */
SUB $(NREGS*4), R13 /* r13 now points to ureg */
MOVW $setR12(SB), R12 /* Make sure we've got the kernel's SB loaded */
/*
* set up m and up registers since user registers could contain anything
*/
CPUID(R1)
SLL $2, R1 /* convert to word index */
MOVW $machaddr(SB), R2
ADD R1, R2
MOVW (R2), R(MACH) /* m = machaddr[cpuid] */
CMP $0, R(MACH)
MOVW.EQ $MACHADDR, R0 /* paranoia: use MACHADDR if 0 */
MOVW 8(R(MACH)), R(USER) /* up = m->proc */
MOVW ((NREGS+1)*4)(R13), R2 /* saved SPSR */
MOVW R13, R0 /* first arg is pointer to ureg */
SUB $(4*2), R13 /* space for argument+link (for debugger) */
BL trap(SB) /* trap(ureg) */
/*
* caller saves on plan 9, so registers other than 9, 10, 13 & 14
* may have been trashed when we get here.
*/
ADD $(4*2+4*NREGS), R13 /* make r13 point to ureg->type */
MOVW 8(R13), R14 /* restore link */
MOVW 4(R13), R0 /* restore SPSR */
MOVW 4(R13), R0 /* restore SPSR */
B _rfue
TEXT _vfiq(SB), 1, $-4 /* FIQ */
PUTC('?')
PUTC('f')
PUTC('i')
PUTC('q')
RFE /* FIQ is special, ignore it for now */
TEXT _vhype(SB), 1, $-4
PUTC('?')
PUTC('h')
PUTC('y')
PUTC('p')
RFE
/*
* set the stack value for the mode passed in R0
*/
TEXT setr13(SB), 1, $-4
MOVW 4(FP), R1
MOVW CPSR, R2
BIC $(PsrMask|PsrMbz), R2, R3
ORR $(PsrDirq|PsrDfiq), R3
ORR R0, R3
MOVW R3, CPSR /* switch to new mode */
MOVW R13, R0 /* return old sp */
MOVW R1, R13 /* install new one */
MOVW R2, CPSR /* switch back to old mode */
RET
|
9front/9front
| 4,750
|
sys/src/9/teg2/rebootcode.s
|
/*
* arm v7 reboot code
*
* must fit in 11K to avoid stepping on PTEs; see mem.h.
* cache parameters are at CACHECONF.
*/
#include "arm.s"
/*
* All caches but L1 should be off before calling this.
* Turn off MMU, then copy the new kernel to its correct location
* in physical memory. Then jump to the start of the kernel.
*/
/* main(PADDR(entry), PADDR(code), size); */
TEXT main(SB), 1, $-4
MOVW $setR12(SB), R12
MOVW R0, p1+0(FP) /* destination, passed in R0 */
CPSID /* splhi */
PUTC('R')
BL cachesoff(SB)
/* now back in 29- or 26-bit addressing, mainly for SB */
/* double mapping of PHYSDRAM & KZERO now in effect */
PUTC('e')
/* before turning MMU off, switch to PHYSDRAM-based addresses */
DMB
MOVW $KSEGM, R7 /* clear segment bits */
MOVW $PHYSDRAM, R0 /* set dram base bits */
BIC R7, R12 /* adjust SB */
ORR R0, R12
BL _r15warp(SB)
/* don't care about saving R14; we're not returning */
/*
* now running in PHYSDRAM segment, not KZERO.
*/
PUTC('b')
/* invalidate mmu mappings */
MOVW $KZERO, R0 /* some valid virtual address */
MTCP CpSC, 0, R0, C(CpTLB), C(CpTLBinvu), CpTLBinv
BARRIERS
PUTC('o')
/*
* turn the MMU off
*/
MFCP CpSC, 0, R0, C(CpCONTROL), C(0)
BIC $CpCmmu, R0
MTCP CpSC, 0, R0, C(CpCONTROL), C(0)
BARRIERS
PUTC('o')
/* copy in arguments from stack frame before moving stack */
MOVW p2+4(FP), R4 /* phys source */
MOVW n+8(FP), R5 /* byte count */
MOVW p1+0(FP), R6 /* phys destination */
/* set up a new stack for local vars and memmove args */
MOVW R6, SP /* tiny trampoline stack */
SUB $(0x20 + 4), SP /* back up before a.out header */
// MOVW R14, -48(SP) /* store return addr */
SUB $48, SP /* allocate stack frame */
MOVW R5, 40(SP) /* save count */
MOVW R6, 44(SP) /* save dest/entry */
/* copy the new kernel into place */
DELAY(printloop2, 2)
PUTC('t')
MOVW 40(SP), R5 /* restore count */
MOVW 44(SP), R6 /* restore dest/entry */
MOVW R6, 0(SP) /* normally saved LR goes here */
MOVW R6, 4(SP) /* push dest */
MOVW R6, R0
MOVW R4, 8(SP) /* push src */
MOVW R5, 12(SP) /* push size */
BL memmove(SB)
PUTC('-')
PUTC('>')
DELAY(printloopret, 1)
PUTC('\r')
DELAY(printloopnl, 1)
PUTC('\n')
/*
* jump to kernel entry point. Note the true kernel entry point is
* the virtual address KZERO|R6, but this must wait until
* the MMU is enabled by the kernel in l.s
*/
MOVW 44(SP), R6 /* restore R6 (dest/entry) */
ORR R6, R6 /* NOP: avoid link bug */
B (R6)
PUTC('?')
PUTC('?')
B 0(PC)
/*
* turn the caches off, double map PHYSDRAM & KZERO, invalidate TLBs, revert
* to tiny addresses. upon return, it will be safe to turn off the mmu.
*/
TEXT cachesoff(SB), 1, $-4
MOVM.DB.W [R14,R1-R10], (R13) /* save regs on stack */
CPSID
BARRIERS
SUB $12, SP /* paranoia */
BL cacheuwbinv(SB)
ADD $12, SP /* paranoia */
MFCP CpSC, 0, R0, C(CpCONTROL), C(0)
BIC $(CpCicache|CpCdcache), R0
MTCP CpSC, 0, R0, C(CpCONTROL), C(0) /* caches off */
BARRIERS
/*
* caches are off
*/
/* invalidate stale TLBs before changing them */
MOVW $KZERO, R0 /* some valid virtual address */
MTCP CpSC, 0, R0, C(CpTLB), C(CpTLBinvu), CpTLBinv
BARRIERS
/* redo double map of PHYSDRAM, KZERO */
MOVW $PHYSDRAM, R3
CMP $KZERO, R3
BEQ noun2map
MOVW $(L1+L1X(PHYSDRAM)), R4 /* address of PHYSDRAM's PTE */
MOVW $PTEDRAM, R2 /* PTE bits */
MOVW $DOUBLEMAPMBS, R5
_ptrdbl:
ORR R3, R2, R1 /* first identity-map 0 to 0, etc. */
MOVW R1, (R4)
ADD $4, R4 /* bump PTE address */
ADD $MiB, R3 /* bump pa */
SUB.S $1, R5
BNE _ptrdbl
noun2map:
/*
* flush stale TLB entries
*/
BARRIERS
MOVW $KZERO, R0 /* some valid virtual address */
MTCP CpSC, 0, R0, C(CpTLB), C(CpTLBinvu), CpTLBinv
BARRIERS
/* switch back to PHYSDRAM addressing, mainly for SB */
MOVW $KSEGM, R7 /* clear segment bits */
MOVW $PHYSDRAM, R0 /* set dram base bits */
BIC R7, R12 /* adjust SB */
ORR R0, R12
BIC R7, SP
ORR R0, SP
MOVM.IA.W (R13), [R14,R1-R10] /* restore regs from stack */
MOVW $KSEGM, R0 /* clear segment bits */
BIC R0, R14 /* adjust link */
MOVW $PHYSDRAM, R0 /* set dram base bits */
ORR R0, R14
RET
TEXT _r15warp(SB), 1, $-4
BIC R7, R14 /* link */
ORR R0, R14
BIC R7, R13 /* SP */
ORR R0, R13
RET
TEXT panic(SB), 1, $-4 /* stub */
PUTC('?')
PUTC('!')
RET
TEXT pczeroseg(SB), 1, $-4 /* stub */
RET
#include "cache.v7.s"
/* modifies R0, R3—R6 */
TEXT printhex(SB), 1, $-4
MOVW R0, R3
MOVW $(32-4), R5 /* bits to shift right */
nextdig:
SRA R5, R3, R4
AND $0xf, R4
ADD $'0', R4
CMP.S $'9', R4
BLE nothex /* if R4 <= 9, jump */
ADD $('a'-('9'+1)), R4
nothex:
PUTC(R4)
SUB.S $4, R5
BGE nextdig
PUTC('\r')
PUTC('\n')
DELAY(proct, 50)
RET
|
9front/9front
| 14,047
|
sys/src/9/imx8/l.s
|
#include "mem.h"
#include "../arm64/sysreg.h"
#undef SYSREG
#define SYSREG(op0,op1,Cn,Cm,op2) SPR(((op0)<<19|(op1)<<16|(Cn)<<12|(Cm)<<8|(op2)<<5))
TEXT _start(SB), 1, $-4
MOV R0, R26 /* save */
MOV $setSB-KZERO(SB), R28
BL svcmode<>(SB)
/* use dedicated stack pointer per exception level */
MOVWU $1, R1
MSR R1, SPSel
BL mmudisable<>(SB)
/* invalidate local caches */
BL cachedwbinv(SB)
BL l2cacheuwbinv(SB)
BL cacheiinv(SB)
/* get machno in R0 */
MRS MPIDR_EL1, R0
BL mpidindex(SB)
/* get MACHP(R0) in R27 */
MOV $(MACHADDR(0)-KZERO), R27
MOVWU $MACHSIZE, R2
MULW R0, R2, R2
SUB R2, R27
/* set the stack pointer */
ADD $(MACHSIZE-16), R27, R1
MOV R1, SP
CBNZ R0, _startup
/* clear page table and machs */
MOV $(L1BOT-KZERO), R1
MOV $(MACHADDR(-1)-KZERO), R2
_zerol1:
MOV ZR, (R1)8!
CMP R1, R2
BNE _zerol1
/* clear BSS */
MOV $edata-KZERO(SB), R1
MOV $end-KZERO(SB), R2
_zerobss:
MOV ZR, (R1)8!
CMP R1, R2
BNE _zerobss
/* setup page tables */
MOV $(L1BOT-KZERO), R0
BL mmuidmap(SB)
MOV $(L1-KZERO), R0
BL mmu0init(SB)
SEVL
_startup:
WFE
BL mmuenable<>(SB)
MOV R26, R0
MOV $0, R26
ORR $KZERO, R27
MSR R27, TPIDR_EL1
MOV $setSB(SB), R28
BL main(SB)
TEXT stop<>(SB), 1, $-4
_stop:
WFE
B _stop
TEXT mpidindex(SB), 1, $-4
MOV R0,R1
MOV $0,R0
MOV $(MPIDMASK),R2
_mpidindex0:
CBZ R2,_mpidindex1
LSR $63,R2,R3
CBZ R3,_mpidindex2
LSR $63,R1,R3
LSLW $1,R0
ORRW R3,R0,R0
_mpidindex2:
LSL $1,R1
LSL $1,R2
B _mpidindex0
_mpidindex1:
RETURN
TEXT aaa<>(SB), 1, $-4
xxx:
MOV $(0x860040+VIRTIO), R1
MOVW $'A', R2
MOVW R2, (R1)
B xxx
TEXT sev(SB), 1, $-4
SEV
WFE
RETURN
TEXT svcmode<>(SB), 1, $-4
MSR $0xF, DAIFSet
MRS CurrentEL, R0
ANDW $(3<<2), R0
CMPW $(1<<2), R0
BEQ el1
CMPW $(2<<2), R0
BEQ el2
B stop<>(SB)
el2:
MOV $0, R0
MSR R0, MDCR_EL2
ISB $SY
/* set virtual timer offset to zero */
MOV $0, R0
MSR R0, CNTVOFF_EL2
/* HCR = RW, HCD, SWIO, BSU, FB */
MOVWU $(1<<31 | 1<<29 | 1<<2 | 0<<10 | 0<<9), R0
MSR R0, HCR_EL2
ISB $SY
/* SCTLR = RES1 */
MOVWU $(3<<4 | 1<<11 | 1<<16 | 1<<18 | 3<<22 | 3<<28), R0
ISB $SY
MSR R0, SCTLR_EL2
ISB $SY
/* set VMID to zero */
MOV $0, R0
MSR R0, VTTBR_EL2
ISB $SY
MOVWU $(0xF<<6 | 4), R0
MSR R0, SPSR_EL2
MSR LR, ELR_EL2
ERET
el1:
RETURN
TEXT mmudisable<>(SB), 1, $-4
#define SCTLRCLR \
/* RES0 */ ( 3<<30 \
/* RES0 */ | 1<<27 \
/* UCI */ | 1<<26 \
/* EE */ | 1<<25 \
/* RES0 */ | 1<<21 \
/* E0E */ | 1<<24 \
/* WXN */ | 1<<19 \
/* nTWE */ | 1<<18 \
/* RES0 */ | 1<<17 \
/* nTWI */ | 1<<16 \
/* UCT */ | 1<<15 \
/* DZE */ | 1<<14 \
/* RES0 */ | 1<<13 \
/* RES0 */ | 1<<10 \
/* UMA */ | 1<<9 \
/* SA0 */ | 1<<4 \
/* SA */ | 1<<3 \
/* A */ | 1<<1 )
#define SCTLRSET \
/* RES1 */ ( 3<<28 \
/* RES1 */ | 3<<22 \
/* RES1 */ | 1<<20 \
/* RES1 */ | 1<<11 )
#define SCTLRMMU \
/* I */ ( 1<<12 \
/* C */ | 1<<2 \
/* M */ | 1<<0 )
/* initialise SCTLR, MMU and caches off */
ISB $SY
MRS SCTLR_EL1, R0
BIC $(SCTLRCLR | SCTLRMMU), R0
ORR $SCTLRSET, R0
ISB $SY
MSR R0, SCTLR_EL1
ISB $SY
B flushlocaltlb(SB)
TEXT mmuenable<>(SB), 1, $-4
/* return to virtual */
ORR $KZERO, LR
MOV LR, -16(RSP)!
BL flushlocaltlb(SB)
/* memory attributes */
#define MAIRINIT \
( 0xFF << MA_MEM_WB*8 \
| 0x33 << MA_MEM_WT*8 \
| 0x44 << MA_MEM_UC*8 \
| 0x00 << MA_DEV_nGnRnE*8 \
| 0x04 << MA_DEV_nGnRE*8 \
| 0x08 << MA_DEV_nGRE*8 \
| 0x0C << MA_DEV_GRE*8 )
MOV $MAIRINIT, R1
MSR R1, MAIR_EL1
ISB $SY
/* translation control */
#define TCRINIT \
/* TBI1 */ ( 0<<38 \
/* TBI0 */ | 0<<37 \
/* AS */ | 0<<36 \
/* TG1 */ | (((3<<16|1<<14|2<<12)>>PGSHIFT)&3)<<30 \
/* SH1 */ | SHARE_INNER<<28 \
/* ORGN1 */ | CACHE_WB<<26 \
/* IRGN1 */ | CACHE_WB<<24 \
/* EPD1 */ | 0<<23 \
/* A1 */ | 0<<22 \
/* T1SZ */ | (64-EVASHIFT)<<16 \
/* TG0 */ | (((1<<16|2<<14|0<<12)>>PGSHIFT)&3)<<14 \
/* SH0 */ | SHARE_INNER<<12 \
/* ORGN0 */ | CACHE_WB<<10 \
/* IRGN0 */ | CACHE_WB<<8 \
/* EPD0 */ | 0<<7 \
/* T0SZ */ | (64-EVASHIFT)<<0 )
MOV $TCRINIT, R1
MRS ID_AA64MMFR0_EL1, R2
ANDW $0x7, R2 // PARange
ADD R2<<32, R1 // IPS
MSR R1, TCR_EL1
ISB $SY
/* load the page tables */
MOV $(L1BOT-KZERO), R0
MOV $(L1TOP-KZERO), R1
ISB $SY
MSR R0, TTBR0_EL1
MSR R1, TTBR1_EL1
ISB $SY
/* enable MMU and caches */
MRS SCTLR_EL1, R1
ORR $SCTLRMMU, R1
ISB $SY
MSR R1, SCTLR_EL1
ISB $SY
MOV RSP, R1
ORR $KZERO, R1
MOV R1, RSP
MOV (RSP)16!, LR
B cacheiinv(SB)
TEXT touser(SB), 1, $-4
MOVWU $0x10028, R1 // entry
MOVWU $0, R2 // psr
MSR R0, SP_EL0 // sp
MSR R1, ELR_EL1
MSR R2, SPSR_EL1
ERET
TEXT cas(SB), 1, $-4
TEXT cmpswap(SB), 1, $-4
MOVWU ov+8(FP), R1
MOVWU nv+16(FP), R2
_cas1:
LDXRW (R0), R3
CMP R3, R1
BNE _cas0
STXRW R2, (R0), R4
CBNZ R4, _cas1
MOVW $1, R0
DMB $ISH
RETURN
_cas0:
CLREX
MOVW $0, R0
RETURN
TEXT tas(SB), 1, $-4
TEXT _tas(SB), 1, $-4
MOVW $0xdeaddead, R2
_tas1:
LDXRW (R0), R1
STXRW R2, (R0), R3
CBNZ R3, _tas1
MOVW R1, R0
TEXT coherence(SB), 1, $-4
DMB $ISH
RETURN
TEXT islo(SB), 1, $-4
MRS DAIF, R0
AND $(0x2<<6), R0
EOR $(0x2<<6), R0
RETURN
TEXT splhi(SB), 1, $-4
MRS DAIF, R0
MSR $0x2, DAIFSet
RETURN
TEXT splfhi(SB), 1, $-4
MRS DAIF, R0
MSR $0x3, DAIFSet
RETURN
TEXT spllo(SB), 1, $-4
MSR $0x3, DAIFClr
RETURN
TEXT splflo(SB), 1, $-4
MSR $0x1, DAIFClr
RETURN
TEXT splx(SB), 1, $-4
MSR R0, DAIF
RETURN
TEXT idlehands(SB), 1, $-4
DMB $ISH
MOV $nrdy(SB), R1
LDXRW (R1), R0
CBZ R0, _goodnight
CLREX
SEVL
_goodnight:
WFE
RETURN
TEXT vcycles(SB), 1, $-4
MRS CNTVCT_EL0, R0
RETURN
TEXT lcycles(SB), 1, $-4
MRS PMCCNTR_EL0, R0
RETURN
TEXT setlabel(SB), 1, $-4
MOV LR, 8(R0)
MOV SP, R1
MOV R1, 0(R0)
MOVW $0, R0
RETURN
TEXT gotolabel(SB), 1, $-4
MOV 8(R0), LR /* link */
MOV 0(R0), R1 /* sp */
MOV R1, SP
MOVW $1, R0
RETURN
TEXT returnto(SB), 1, $-4
MOV R0, 0(SP)
RETURN
TEXT getfar(SB), 1, $-4
MRS FAR_EL1, R0
RETURN
TEXT setttbr(SB), 1, $-4
DSB $ISHST
MSR R0, TTBR0_EL1
DSB $ISH
ISB $SY
RETURN
/*
* TLB maintenance operations.
* these broadcast to all cpu's in the cluser
* (inner sharable domain).
*/
TEXT flushasidva(SB), 1, $-4
TEXT tlbivae1is(SB), 1, $-4
DSB $ISHST
TLBI R0, 0,8,3,1 /* VAE1IS */
DSB $ISH
ISB $SY
RETURN
TEXT flushasidvall(SB), 1, $-4
TEXT tlbivale1is(SB), 1, $-4
DSB $ISHST
TLBI R0, 0,8,3,5 /* VALE1IS */
DSB $ISH
ISB $SY
RETURN
TEXT flushasid(SB), 1, $-4
TEXT tlbiaside1is(SB), 1, $-4
DSB $ISHST
TLBI R0, 0,8,3,2 /* ASIDE1IS */
DSB $ISH
ISB $SY
RETURN
TEXT flushtlb(SB), 1, $-4
TEXT tlbivmalle1is(SB), 1, $-4
DSB $ISHST
TLBI R0, 0,8,3,0 /* VMALLE1IS */
DSB $ISH
ISB $SY
RETURN
/*
* flush the tlb of this cpu. no broadcast.
*/
TEXT flushlocaltlb(SB), 1, $-4
TEXT tlbivmalle1(SB), 1, $-4
DSB $NSHST
TLBI R0, 0,8,7,0 /* VMALLE1 */
DSB $NSH
ISB $SY
RETURN
/*
* floating-point support.
*/
TEXT fpon(SB), 1, $-4
MOVW $(3<<20), R0
MSR R0, CPACR_EL1
ISB $SY
RETURN
TEXT fpoff(SB), 1, $-4
MOVW $(0<<20), R0
MSR R0, CPACR_EL1
ISB $SY
RETURN
TEXT fpsaveregs(SB), 1, $-4
WORD $(1<<30 | 3 << 26 | 2<<22 | 0x1F<<16 | 3<<10 | 0<<5 | 0) /* MOV { V0, V1, V2, V3 }, (R0)64! */
WORD $(1<<30 | 3 << 26 | 2<<22 | 0x1F<<16 | 3<<10 | 0<<5 | 4) /* MOV { V4, V5, V6, V7 }, (R0)64! */
WORD $(1<<30 | 3 << 26 | 2<<22 | 0x1F<<16 | 3<<10 | 0<<5 | 8) /* MOV { V8, V9, V10,V11 }, (R0)64! */
WORD $(1<<30 | 3 << 26 | 2<<22 | 0x1F<<16 | 3<<10 | 0<<5 | 12) /* MOV { V12,V13,V14,V15 }, (R0)64! */
WORD $(1<<30 | 3 << 26 | 2<<22 | 0x1F<<16 | 3<<10 | 0<<5 | 16) /* MOV { V16,V17,V18,V19 }, (R0)64! */
WORD $(1<<30 | 3 << 26 | 2<<22 | 0x1F<<16 | 3<<10 | 0<<5 | 20) /* MOV { V20,V21,V22,V23 }, (R0)64! */
WORD $(1<<30 | 3 << 26 | 2<<22 | 0x1F<<16 | 3<<10 | 0<<5 | 24) /* MOV { V24,V25,V26,V27 }, (R0)64! */
WORD $(1<<30 | 3 << 26 | 2<<22 | 0x1F<<16 | 3<<10 | 0<<5 | 28) /* MOV { V28,V29,V30,V31 }, (R0)64! */
RETURN
TEXT fploadregs(SB), 1, $-4
WORD $(1<<30 | 3 << 26 | 3<<22 | 0x1F<<16 | 3<<10 | 0<<5 | 0) /* MOV (R0)64!, { V0, V1, V2, V3 } */
WORD $(1<<30 | 3 << 26 | 3<<22 | 0x1F<<16 | 3<<10 | 0<<5 | 4) /* MOV (R0)64!, { V4, V5, V6, V7 } */
WORD $(1<<30 | 3 << 26 | 3<<22 | 0x1F<<16 | 3<<10 | 0<<5 | 8) /* MOV (R0)64!, { V8, V9, V10,V11 } */
WORD $(1<<30 | 3 << 26 | 3<<22 | 0x1F<<16 | 3<<10 | 0<<5 | 12) /* MOV (R0)64!, { V12,V13,V14,V15 } */
WORD $(1<<30 | 3 << 26 | 3<<22 | 0x1F<<16 | 3<<10 | 0<<5 | 16) /* MOV (R0)64!, { V16,V17,V18,V19 } */
WORD $(1<<30 | 3 << 26 | 3<<22 | 0x1F<<16 | 3<<10 | 0<<5 | 20) /* MOV (R0)64!, { V20,V21,V22,V23 } */
WORD $(1<<30 | 3 << 26 | 3<<22 | 0x1F<<16 | 3<<10 | 0<<5 | 24) /* MOV (R0)64!, { V24,V25,V26,V27 } */
WORD $(1<<30 | 3 << 26 | 3<<22 | 0x1F<<16 | 3<<10 | 0<<5 | 28) /* MOV (R0)64!, { V28,V29,V30,V31 } */
RETURN
// syscall or trap from EL0
TEXT vsys0(SB), 1, $-4
LSRW $26, R0, R17 // ec
CMPW $0x15, R17 // SVC trap?
BNE _itsatrap // nope.
MOVP R26, R27, 224(RSP)
MOVP R28, R29, 240(RSP)
MRS SP_EL0, R1
MRS ELR_EL1, R2
MRS SPSR_EL1, R3
MOV R0, 288(RSP) // type
MOV R1, 264(RSP) // sp
MOV R2, 272(RSP) // pc
MOV R3, 280(RSP) // psr
MOV $setSB(SB), R28
MRS TPIDR_EL1, R27
MOV 16(R27), R26
ADD $16, RSP, R0 // ureg
BL syscall(SB)
TEXT forkret(SB), 1, $-4
MSR $0x3, DAIFSet // interrupts off
ADD $16, RSP, R0 // ureg
MOV 16(RSP), R0 // ret
MOV 264(RSP), R1 // sp
MOV 272(RSP), R2 // pc
MOV 280(RSP), R3 // psr
MSR R1, SP_EL0
MSR R2, ELR_EL1
MSR R3, SPSR_EL1
MOVP 224(RSP), R26, R27
MOVP 240(RSP), R28, R29
MOV 256(RSP), R30 // link
ADD $TRAPFRAMESIZE, RSP
ERET
TEXT itsatrap<>(SB), 1, $-4
_itsatrap:
MOVP R1, R2, 24(RSP)
MOVP R3, R4, 40(RSP)
MOVP R5, R6, 56(RSP)
MOVP R7, R8, 72(RSP)
MOVP R9, R10, 88(RSP)
MOVP R11, R12, 104(RSP)
MOVP R13, R14, 120(RSP)
MOVP R15, R16, 136(RSP)
MOVP R18, R19, 160(RSP)
MOVP R20, R21, 176(RSP)
MOVP R22, R23, 192(RSP)
MOVP R24, R25, 208(RSP)
// trap/irq/fiq/serr from EL0
TEXT vtrap0(SB), 1, $-4
MOVP R26, R27, 224(RSP)
MOVP R28, R29, 240(RSP)
MRS SP_EL0, R1
MRS ELR_EL1, R2
MRS SPSR_EL1, R3
MOV R0, 288(RSP) // type
MOV R1, 264(RSP) // sp
MOV R2, 272(RSP) // pc
MOV R3, 280(RSP) // psr
MOV $setSB(SB), R28
MRS TPIDR_EL1, R27
MOV 16(R27), R26
ADD $16, RSP, R0 // ureg
BL trap(SB)
TEXT noteret(SB), 1, $-4
MSR $0x3, DAIFSet // interrupts off
ADD $16, RSP, R0 // ureg
MOV 264(RSP), R1 // sp
MOV 272(RSP), R2 // pc
MOV 280(RSP), R3 // psr
MSR R1, SP_EL0
MSR R2, ELR_EL1
MSR R3, SPSR_EL1
MOVP 224(RSP), R26, R27
MOVP 240(RSP), R28, R29
_intrreturn:
MOVP 16(RSP), R0, R1
MOVP 32(RSP), R2, R3
MOVP 48(RSP), R4, R5
MOVP 64(RSP), R6, R7
MOVP 80(RSP), R8, R9
MOVP 96(RSP), R10, R11
MOVP 112(RSP), R12, R13
MOVP 128(RSP), R14, R15
MOVP 144(RSP), R16, R17
MOVP 160(RSP), R18, R19
MOVP 176(RSP), R20, R21
MOVP 192(RSP), R22, R23
MOVP 208(RSP), R24, R25
MOV 256(RSP), R30 // link
ADD $TRAPFRAMESIZE, RSP
ERET
// irq/fiq/trap/serr from EL1
TEXT vtrap1(SB), 1, $-4
MOV R29, 248(RSP) // special
ADD $TRAPFRAMESIZE, RSP, R1
MRS ELR_EL1, R2
MRS SPSR_EL1, R3
MOV R0, 288(RSP) // type
MOV R1, 264(RSP) // sp
MOV R2, 272(RSP) // pc
MOV R3, 280(RSP) // psr
ADD $16, RSP, R0 // ureg
BL trap(SB)
MSR $0x3, DAIFSet // interrupts off
MOV 272(RSP), R2 // pc
MOV 280(RSP), R3 // psr
MSR R2, ELR_EL1
MSR R3, SPSR_EL1
MOV 248(RSP), R29 // special
B _intrreturn
// vector tables
TEXT vsys(SB), 1, $-4
SUB $TRAPFRAMESIZE, RSP
MOV R0, 16(RSP)
MOV R30, 256(RSP) // link
MOV R17, 152(RSP) // temp
MRS ESR_EL1, R0 // type
_vsyspatch:
B _vsyspatch // branch to vsys0() patched in
TEXT vtrap(SB), 1, $-4
SUB $TRAPFRAMESIZE, RSP
MOVP R0, R1, 16(RSP)
MOVP R2, R3, 32(RSP)
MOVP R4, R5, 48(RSP)
MOVP R6, R7, 64(RSP)
MOVP R8, R9, 80(RSP)
MOVP R10, R11, 96(RSP)
MOVP R12, R13, 112(RSP)
MOVP R14, R15, 128(RSP)
MOVP R16, R17, 144(RSP)
MOVP R18, R19, 160(RSP)
MOVP R20, R21, 176(RSP)
MOVP R22, R23, 192(RSP)
MOVP R24, R25, 208(RSP)
MOV R30, 256(RSP) // link
MRS ESR_EL1, R0 // type
_vtrappatch:
B _vtrappatch // branch to vtrapX() patched in
TEXT virq(SB), 1, $-4
SUB $TRAPFRAMESIZE, RSP
MOVP R0, R1, 16(RSP)
MOVP R2, R3, 32(RSP)
MOVP R4, R5, 48(RSP)
MOVP R6, R7, 64(RSP)
MOVP R8, R9, 80(RSP)
MOVP R10, R11, 96(RSP)
MOVP R12, R13, 112(RSP)
MOVP R14, R15, 128(RSP)
MOVP R16, R17, 144(RSP)
MOVP R18, R19, 160(RSP)
MOVP R20, R21, 176(RSP)
MOVP R22, R23, 192(RSP)
MOVP R24, R25, 208(RSP)
MOV R30, 256(RSP) // link
MOV $(1<<32), R0 // type irq
_virqpatch:
B _virqpatch // branch to vtrapX() patched in
TEXT vfiq(SB), 1, $-4
SUB $TRAPFRAMESIZE, RSP
MOVP R0, R1, 16(RSP)
MOVP R2, R3, 32(RSP)
MOVP R4, R5, 48(RSP)
MOVP R6, R7, 64(RSP)
MOVP R8, R9, 80(RSP)
MOVP R10, R11, 96(RSP)
MOVP R12, R13, 112(RSP)
MOVP R14, R15, 128(RSP)
MOVP R16, R17, 144(RSP)
MOVP R18, R19, 160(RSP)
MOVP R20, R21, 176(RSP)
MOVP R22, R23, 192(RSP)
MOVP R24, R25, 208(RSP)
MOV R30, 256(RSP) // link
MOV $(2<<32), R0 // type fiq
_vfiqpatch:
B _vfiqpatch // branch to vtrapX() patched in
TEXT vserr(SB), 1, $-4
SUB $TRAPFRAMESIZE, RSP
MOVP R0, R1, 16(RSP)
MOVP R2, R3, 32(RSP)
MOVP R4, R5, 48(RSP)
MOVP R6, R7, 64(RSP)
MOVP R8, R9, 80(RSP)
MOVP R10, R11, 96(RSP)
MOVP R12, R13, 112(RSP)
MOVP R14, R15, 128(RSP)
MOVP R16, R17, 144(RSP)
MOVP R18, R19, 160(RSP)
MOVP R20, R21, 176(RSP)
MOVP R22, R23, 192(RSP)
MOVP R24, R25, 208(RSP)
MOV R30, 256(RSP) // link
MRS ESR_EL1, R0
ORR $(3<<32), R0 // type
_vserrpatch:
B _vserrpatch // branch to vtrapX() patched in
/* fault-proof memcpy */
TEXT peek(SB), 1, $-4
MOV R0, R1
MOV dst+8(FP), R2
MOVWU len+16(FP), R0
TEXT _peekinst(SB), 1, $-4
_peekloop:
MOVBU (R1)1!, R3
MOVBU R3, (R2)1!
SUBS $1, R0
BNE _peekloop
RETURN
TEXT smccall(SB), 1, $32
/* save extern registers */
MOVP R26, R27, (RSP)
/* R0 = Ureg */
MOV R0, R8
/* save ureg pointer */
MOV R8, 16(RSP)
MOVP 0(R8), R0, R1
MOVP 16(R8), R2, R3
MOVP 32(R8), R4, R5
MOVP 48(R8), R6, R7
SMC
/* restore ureg pointer */
MOV 16(RSP), R8
MOVP R0, R1, 0(R8)
MOVP R2, R3, 16(R8)
/* restore extern registers */
MOVP (RSP), R26, R27
RETURN
|
9front/9front
| 27,901
|
sys/src/9/pc64/l.s
|
#include "mem.h"
MODE $32
#define DELAY BYTE $0xEB; BYTE $0x00 /* JMP .+2 */
#define pFARJMP32(s, o) BYTE $0xea; /* far jump to ptr32:16 */\
LONG $o; WORD $s
/*
* Enter here in 32-bit protected mode. Welcome to 1982.
* Make sure the GDT is set as it should be:
* disable interrupts;
* load the GDT with the table in _gdt32p;
* load all the data segments
* load the code segment via a far jump.
*/
TEXT _protected<>(SB), 1, $-4
CLI
MOVL $_gdtptr32p<>-KZERO(SB), AX
MOVL (AX), GDTR
MOVL $SELECTOR(2, SELGDT, 0), AX
MOVW AX, DS
MOVW AX, ES
MOVW AX, FS
MOVW AX, GS
MOVW AX, SS
pFARJMP32(SELECTOR(3, SELGDT, 0), _warp64<>-KZERO(SB))
BYTE $0x90 /* align */
/*
* Must be 4-byte aligned.
*/
TEXT _multibootheader<>(SB), 1, $-4
LONG $0x1BADB002 /* magic */
LONG $0x00010007 /* flags */
LONG $-(0x1BADB002 + 0x00010007) /* checksum */
LONG $_multibootheader<>-KZERO(SB) /* header_addr */
LONG $_protected<>-KZERO(SB) /* load_addr */
LONG $edata-KZERO(SB) /* load_end_addr */
LONG $end-KZERO(SB) /* bss_end_addr */
LONG $_multibootentry<>-KZERO(SB) /* entry_addr */
LONG $0 /* mode_type */
LONG $0 /* width */
LONG $0 /* height */
LONG $32 /* depth */
/*
* the kernel expects the data segment to be page-aligned
* multiboot bootloaders put the data segment right behind text
*/
TEXT _multibootentry<>(SB), 1, $-4
MOVL $etext-KZERO(SB), SI
MOVL SI, DI
ADDL $(BY2PG-1), DI
ANDL $~(BY2PG-1), DI
MOVL $edata-KZERO(SB), CX
SUBL DI, CX
ADDL CX, SI
ADDL CX, DI
INCL CX /* one more for post decrement */
STD
REP; MOVSB
MOVL BX, multibootptr-KZERO(SB)
MOVL $_protected<>-KZERO(SB), AX
JMP* AX
/* multiboot structure pointer (physical address) */
TEXT multibootptr(SB), 1, $-4
LONG $0
TEXT _gdt<>(SB), 1, $-4
/* null descriptor */
LONG $0
LONG $0
/* (KESEG) 64 bit long mode exec segment */
LONG $(0xFFFF)
LONG $(SEGL|SEGG|SEGP|(0xF<<16)|SEGPL(0)|SEGEXEC|SEGR)
/* 32 bit data segment descriptor for 4 gigabytes (PL 0) */
LONG $(0xFFFF)
LONG $(SEGG|SEGB|(0xF<<16)|SEGP|SEGPL(0)|SEGDATA|SEGW)
/* 32 bit exec segment descriptor for 4 gigabytes (PL 0) */
LONG $(0xFFFF)
LONG $(SEGG|SEGD|(0xF<<16)|SEGP|SEGPL(0)|SEGEXEC|SEGR)
TEXT _gdtptr32p<>(SB), 1, $-4
WORD $(4*8-1)
LONG $_gdt<>-KZERO(SB)
TEXT _gdtptr64p<>(SB), 1, $-4
WORD $(4*8-1)
QUAD $_gdt<>-KZERO(SB)
TEXT _gdtptr64v<>(SB), 1, $-4
WORD $(4*8-1)
QUAD $_gdt<>(SB)
/*
* Macros for accessing page table entries; change the
* C-style array-index macros into a page table byte offset
*/
#define PML4O(v) ((PTLX((v), 3))<<3)
#define PDPO(v) ((PTLX((v), 2))<<3)
#define PDO(v) ((PTLX((v), 1))<<3)
#define PTO(v) ((PTLX((v), 0))<<3)
TEXT _warp64<>(SB), 1, $-4
/* clear mach and page tables */
MOVL $((CPU0END-CPU0PML4)>>2), CX
MOVL $(CPU0PML4-KZERO), SI
MOVL SI, DI
XORL AX, AX
CLD
REP; STOSL
MOVL SI, AX /* PML4 */
MOVL AX, DX
ADDL $(PTEACCESSED|PTEDIRTY|PTSZ|PTEWRITE|PTEVALID), DX /* PDP at PML4 + PTSZ */
MOVL DX, PML4O(0)(AX) /* PML4E for double-map */
MOVL DX, PML4O(KZERO)(AX) /* PML4E for KZERO */
ADDL $PTSZ, AX /* PDP at PML4 + PTSZ */
ADDL $PTSZ, DX /* PD0 at PML4 + 2*PTSZ */
MOVL DX, PDPO(0)(AX) /* PDPE for double-map */
MOVL DX, PDPO(KZERO)(AX) /* PDPE for KZERO */
/*
* add PDPE for KZERO+1GB early as Vmware
* hangs when modifying kernel PDP
*/
ADDL $PTSZ, DX /* PD1 */
MOVL DX, PDPO(KZERO+GiB)(AX)
ADDL $PTSZ, AX /* PD0 at PML4 + 2*PTSZ */
MOVL $(PTEACCESSED|PTEDIRTY|PTESIZE|PTEGLOBAL|PTEWRITE|PTEVALID), DX
MOVL DX, PDO(0)(AX) /* PDE for double-map */
/*
* map from KZERO to end using 2MB pages
*/
ADDL $PDO(KZERO), AX
MOVL $end-KZERO(SB), CX
ADDL $(16*1024), CX /* qemu puts multiboot data after the kernel */
ADDL $(PGLSZ(1)-1), CX
ANDL $~(PGLSZ(1)-1), CX
MOVL CX, MemMin-KZERO(SB) /* see memory.c */
SHRL $(1*PTSHIFT+PGSHIFT), CX
memloop:
MOVL DX, (AX)
ADDL $PGLSZ(1), DX
ADDL $8, AX
LOOP memloop
/*
* Enable and activate Long Mode. From the manual:
* make sure Page Size Extentions are off, and Page Global
* Extensions and Physical Address Extensions are on in CR4;
* set Long Mode Enable in the Extended Feature Enable MSR;
* set Paging Enable in CR0;
* make an inter-segment jump to the Long Mode code.
* It's all in 32-bit mode until the jump is made.
*/
TEXT _lme<>(SB), 1, $-4
MOVL SI, CR3 /* load the mmu */
DELAY
MOVL CR4, AX
ANDL $~0x00000010, AX /* Page Size */
ORL $0x000000A0, AX /* Page Global, Phys. Address */
MOVL AX, CR4
MOVL $0xc0000080, CX /* Extended Feature Enable */
RDMSR
ORL $0x00000100, AX /* Long Mode Enable */
WRMSR
MOVL CR0, DX
ANDL $~0x6000000a, DX
ORL $0x80010000, DX /* Paging Enable, Write Protect */
MOVL DX, CR0
pFARJMP32(SELECTOR(KESEG, SELGDT, 0), _identity<>-KZERO(SB))
/*
* Long mode. Welcome to 2003.
* Jump out of the identity map space;
* load a proper long mode GDT.
*/
MODE $64
TEXT _identity<>(SB), 1, $-4
MOVQ $_start64v<>(SB), AX
JMP* AX
TEXT _start64v<>(SB), 1, $-4
MOVQ $_gdtptr64v<>(SB), AX
MOVL (AX), GDTR
XORQ AX, AX
MOVW AX, DS /* not used in long mode */
MOVW AX, ES /* not used in long mode */
MOVW AX, FS
MOVW AX, GS
MOVW AX, SS /* not used in long mode */
MOVW AX, LDTR
MOVQ $(CPU0MACH+MACHSIZE), SP
MOVQ $(CPU0MACH), RMACH
MOVQ AX, RUSER /* up = 0; */
_clearbss:
MOVQ $edata(SB), DI
MOVQ $end(SB), CX
SUBQ DI, CX /* end-edata bytes */
SHRQ $2, CX /* end-edata doublewords */
CLD
REP; STOSL /* clear BSS */
PUSHQ AX /* clear flags */
POPFQ
CALL main(SB)
/*
* Park a processor. Should never fall through a return from main to here,
* should only be called by application processors when shutting down.
*/
TEXT idle(SB), 1, $-4
_idle:
STI
HLT
JMP _idle
/*
* The CPUID instruction is always supported on the amd64.
*/
TEXT cpuid(SB), $-4
MOVL RARG, AX /* function in AX */
MOVL cx+8(FP), CX /* sub-level in CX */
CPUID
MOVQ info+16(FP), BP
MOVL AX, 0(BP)
MOVL BX, 4(BP)
MOVL CX, 8(BP)
MOVL DX, 12(BP)
RET
/*
* Port I/O.
*/
TEXT inb(SB), 1, $-4
MOVL RARG, DX /* MOVL port+0(FP), DX */
XORL AX, AX
INB
RET
TEXT insb(SB), 1, $-4
MOVL RARG, DX /* MOVL port+0(FP), DX */
MOVQ address+8(FP), DI
MOVL count+16(FP), CX
CLD
REP; INSB
RET
TEXT ins(SB), 1, $-4
MOVL RARG, DX /* MOVL port+0(FP), DX */
XORL AX, AX
INW
RET
TEXT inss(SB), 1, $-4
MOVL RARG, DX /* MOVL port+0(FP), DX */
MOVQ address+8(FP), DI
MOVL count+16(FP), CX
CLD
REP; INSW
RET
TEXT inl(SB), 1, $-4
MOVL RARG, DX /* MOVL port+0(FP), DX */
INL
RET
TEXT insl(SB), 1, $-4
MOVL RARG, DX /* MOVL port+0(FP), DX */
MOVQ address+8(FP), DI
MOVL count+16(FP), CX
CLD
REP; INSL
RET
TEXT outb(SB), 1, $-1
MOVL RARG, DX /* MOVL port+0(FP), DX */
MOVL byte+8(FP), AX
OUTB
RET
TEXT outsb(SB), 1, $-4
MOVL RARG, DX /* MOVL port+0(FP), DX */
MOVQ address+8(FP), SI
MOVL count+16(FP), CX
CLD
REP; OUTSB
RET
TEXT outs(SB), 1, $-4
MOVL RARG, DX /* MOVL port+0(FP), DX */
MOVL short+8(FP), AX
OUTW
RET
TEXT outss(SB), 1, $-4
MOVL RARG, DX /* MOVL port+0(FP), DX */
MOVQ address+8(FP), SI
MOVL count+16(FP), CX
CLD
REP; OUTSW
RET
TEXT outl(SB), 1, $-4
MOVL RARG, DX /* MOVL port+0(FP), DX */
MOVL long+8(FP), AX
OUTL
RET
TEXT outsl(SB), 1, $-4
MOVL RARG, DX /* MOVL port+0(FP), DX */
MOVQ address+8(FP), SI
MOVL count+16(FP), CX
CLD
REP; OUTSL
RET
TEXT getgdt(SB), 1, $-4
MOVQ RARG, AX
MOVL GDTR, (AX) /* Note: 10 bytes returned */
RET
TEXT lgdt(SB), $0 /* GDTR - global descriptor table */
MOVQ RARG, AX
MOVL (AX), GDTR
RET
TEXT lidt(SB), $0 /* IDTR - interrupt descriptor table */
MOVQ RARG, AX
MOVL (AX), IDTR
RET
TEXT ltr(SB), 1, $-4
MOVW RARG, AX
MOVW AX, TASK
RET
/*
* Read/write various system registers.
*/
TEXT getcr0(SB), 1, $-4 /* Processor Control */
MOVQ CR0, AX
RET
TEXT putcr0(SB), 1, $-4
MOVQ RARG, CR0
RET
TEXT getcr2(SB), 1, $-4 /* #PF Linear Address */
MOVQ CR2, AX
RET
TEXT putcr2(SB), 1, $-4
MOVQ BP, CR2
RET
TEXT getcr3(SB), 1, $-4 /* PML4 Base */
MOVQ CR3, AX
RET
TEXT putcr3(SB), 1, $-4
MOVQ RARG, CR3
RET
TEXT getcr4(SB), 1, $-4 /* Extensions */
MOVQ CR4, AX
RET
TEXT putcr4(SB), 1, $-4
MOVQ RARG, CR4
RET
TEXT getxcr0(SB), 1, $-4 /* XCR0 - extended control */
XORQ CX, CX
WORD $0x010f; BYTE $0xd0 // XGETBV
SHLQ $32, DX
ORQ DX, AX
RET
TEXT putxcr0(SB), 1, $-4
XORQ CX, CX
MOVL RARG, DX
SHRQ $32, DX
MOVL RARG, AX
WORD $0x010f; BYTE $0xd1 // XSETBV
RET
TEXT mb386(SB), 1, $-4 /* hack */
TEXT mb586(SB), 1, $-4
XORL AX, AX
CPUID
RET
/*
* Basic timing loop.
*/
TEXT delayloop(SB), 1, $-4
MOVL RARG, CX
MOVL $1, BX
MOVL $0, DX
MOVL $-1, AX
_delayloop:
IDIVQ BX
IDIVQ BX
IDIVQ BX
IDIVQ BX
IDIVQ BX
IDIVQ BX
IDIVQ BX
IDIVQ BX
LOOP _delayloop
RET
TEXT _cycles(SB), 1, $-4 /* time stamp counter */
RDTSC
MOVL AX, 0(RARG) /* lo */
MOVL DX, 4(RARG) /* hi */
RET
TEXT rdmsr(SB), 1, $-4 /* Model-Specific Register */
MOVL RARG, CX
MOVQ $0, BP
TEXT _rdmsrinst(SB), $0
RDMSR
MOVQ vlong+8(FP), CX /* &vlong */
MOVL AX, 0(CX) /* lo */
MOVL DX, 4(CX) /* hi */
MOVQ BP, AX /* BP set to -1 if traped */
RET
TEXT wrmsr(SB), 1, $-4
MOVL RARG, CX
MOVL lo+8(FP), AX
MOVL hi+12(FP), DX
MOVQ $0, BP
TEXT _wrmsrinst(SB), $0
WRMSR
MOVQ BP, AX /* BP set to -1 if traped */
RET
/* fault-proof memcpy */
TEXT peek(SB), 1, $-4
MOVQ RARG, SI
MOVQ dst+8(FP), DI
MOVL cnt+16(FP), CX
CLD
TEXT _peekinst(SB), $0
REP; MOVSB
MOVL CX, AX
RET
TEXT invlpg(SB), 1, $-4
INVLPG (RARG)
RET
TEXT wbinvd(SB), 1, $-4
WBINVD
RET
/*
* Serialisation.
*/
TEXT lfence(SB), 1, $-4
LFENCE
RET
TEXT mfence(SB), 1, $-4
MFENCE
RET
TEXT sfence(SB), 1, $-4
SFENCE
RET
/*
* Note: CLI and STI are not serialising instructions.
* Is that assumed anywhere?
*/
TEXT splhi(SB), 1, $-4
_splhi:
PUSHFQ
POPQ AX
TESTQ $0x200, AX /* 0x200 - Interrupt Flag */
JZ _alreadyhi /* use CMOVLEQ etc. here? */
MOVQ (SP), BX
MOVQ BX, 8(RMACH) /* save PC in m->splpc */
CLI
_alreadyhi:
RET
TEXT spllo(SB), 1, $-4
_spllo:
PUSHFQ
POPQ AX
TESTQ $0x200, AX /* 0x200 - Interrupt Flag */
JNZ _alreadylo /* use CMOVLEQ etc. here? */
MOVQ $0, 8(RMACH) /* clear m->splpc */
STI
_alreadylo:
RET
TEXT splx(SB), 1, $-4
TESTQ $0x200, RARG /* 0x200 - Interrupt Flag */
JNZ _spllo
JMP _splhi
TEXT spldone(SB), 1, $-4
RET
TEXT islo(SB), 1, $-4
PUSHFQ
POPQ AX
ANDQ $0x200, AX /* 0x200 - Interrupt Flag */
RET
/*
* Synchronisation
*/
TEXT tas(SB), 1, $-4
TEXT _tas(SB), 1, $-4
MOVL $0xdeaddead, AX
XCHGL AX, (RARG) /* */
RET
TEXT cmpswap486(SB), 1, $-4
TEXT cas(SB), 1, $-4
MOVL exp+8(FP), AX
MOVL new+16(FP), BX
LOCK; CMPXCHGL BX, (RARG)
MOVL $1, AX /* use CMOVLEQ etc. here? */
JNZ _cas32r0
_cas32r1:
RET
_cas32r0:
DECL AX
RET
/*
* Label consists of a stack pointer and a programme counter
*/
TEXT gotolabel(SB), 1, $-4
MOVQ 0(RARG), SP /* restore SP */
MOVQ 8(RARG), AX /* put return PC on the stack */
MOVQ AX, 0(SP)
MOVL $1, AX /* return 1 */
RET
TEXT setlabel(SB), 1, $-4
MOVQ SP, 0(RARG) /* store SP */
MOVQ 0(SP), BX /* store return PC */
MOVQ BX, 8(RARG)
MOVL $0, AX /* return 0 */
RET
TEXT halt(SB), 1, $-4
CLI
CMPL nrdy(SB), $0
JEQ _nothingready
STI
RET
_nothingready:
STI
HLT
RET
TEXT mwait(SB), 1, $-4
MOVQ RARG, AX
MOVL (AX), CX
ORL CX, CX
JNZ _mwaitdone
XORL DX, DX
BYTE $0x0f; BYTE $0x01; BYTE $0xc8 /* MONITOR */
MOVL (AX), CX
ORL CX, CX
JNZ _mwaitdone
XORL AX, AX
BYTE $0x0f; BYTE $0x01; BYTE $0xc9 /* MWAIT */
_mwaitdone:
RET
/*
* SIMD Floating Point.
* Note: for x87 instructions which have both a 'wait' and 'nowait' version,
* 8a only knows the 'wait' mnemonic but does NOT insertthe WAIT prefix byte
* (i.e. they act like their FNxxx variations) so WAIT instructions must be
* explicitly placed in the code if necessary.
*/
TEXT _clts(SB), 1, $-4
CLTS
RET
TEXT _fldcw(SB), 1, $-4 /* Load x87 FPU Control Word */
MOVQ RARG, cw+0(FP)
FLDCW cw+0(FP)
RET
TEXT _fnclex(SB), 1, $-4
FCLEX
RET
TEXT _fninit(SB), 1, $-4
FINIT /* no WAIT */
RET
TEXT _fxrstor(SB), 1, $-4
FXRSTOR64 (RARG)
RET
TEXT _fxsave(SB), 1, $-4
FXSAVE64 (RARG)
RET
TEXT _xrstor(SB), 1, $-4
MOVL $7, AX
XORL DX, DX
BYTE $0x48; BYTE $0x0f; BYTE $0xae; BYTE $0x6d; BYTE $0x00 // XRSTOR (RARG)
RET
TEXT _xrstors(SB), 1, $-4
MOVL $7, AX
XORL DX, DX
BYTE $0x48; BYTE $0x0f; BYTE $0xc7; BYTE $0x5d; BYTE $0x00 // XRSTORS (RARG)
RET
TEXT _xsave(SB), 1, $-4
MOVL $7, AX
XORL DX, DX
BYTE $0x48; BYTE $0x0f; BYTE $0xae; BYTE $0x65; BYTE $0x00 // XSAVE (RARG)
RET
TEXT _xsaveopt(SB), 1, $-4
MOVL $7, AX
XORL DX, DX
BYTE $0x48; BYTE $0x0f; BYTE $0xae; BYTE $0x75; BYTE $0x00 // XSAVEOPT (RARG)
RET
TEXT _xsaves(SB), 1, $-4
MOVL $7, AX
XORL DX, DX
BYTE $0x48; BYTE $0x0f; BYTE $0xc7; BYTE $0x6d; BYTE $0x00 // XSAVES (RARG)
RET
TEXT _fwait(SB), 1, $-4
WAIT
RET
TEXT _ldmxcsr(SB), 1, $-4 /* Load MXCSR */
MOVQ RARG, mxcsr+0(FP)
LDMXCSR mxcsr+0(FP)
RET
TEXT _stts(SB), 1, $-4
MOVQ CR0, AX
ORQ $8, AX /* Ts */
MOVQ AX, CR0
RET
TEXT mul64fract(SB), 1, $-4
MOVQ a+8(FP), AX
MULQ b+16(FP) /* a*b */
SHRQ $32, AX:DX
MOVQ AX, (RARG)
RET
#define RDRANDAX BYTE $0x0f; BYTE $0xc7; BYTE $0xf0
#define RDRAND64AX BYTE $0x48; BYTE $0x0f; BYTE $0xc7; BYTE $0xf0
TEXT rdrand32(SB), $-4
loop32:
RDRANDAX
JCC loop32
RET
TEXT rdrand64(SB), $-4
loop64:
RDRAND64AX
JCC loop64
RET
TEXT rdrandbuf(SB), $0
MOVQ RARG, DX
MOVLQZX cnt+8(FP), CX
SHRQ $3, CX
eights:
CMPL CX, $0
JLE f1
CALL rdrand64(SB)
MOVQ AX, 0(DX)
ADDQ $8, DX
SUBL $1, CX
JMP eights
f1:
MOVLQZX cnt+8(FP), CX
ANDL $7, CX
SHRQ $2, CX
fours:
CMPL CX, $0
JLE f2
CALL rdrand32(SB)
MOVL AX, 0(DX)
ADDQ $4, DX
SUBL $1, CX
JMP fours
f2:
MOVLQZX cnt+8(FP), CX
ANDL $3, CX
ones:
CMPL CX, $0
JLE f3
CALL rdrand32(SB)
MOVB AX, 0(DX)
ADDQ $1, DX
SUBL $1, CX
JMP ones
f3:
RET
/* debug register access */
TEXT putdr(SB), 1, $-4
MOVQ 56(BP), AX
MOVQ AX, DR7
/* wet floor */
TEXT putdr01236(SB), 1, $-4
MOVQ 0(BP), AX
MOVQ AX, DR0
MOVQ 8(BP), AX
MOVQ AX, DR1
MOVQ 16(BP), AX
MOVQ AX, DR2
MOVQ 24(BP), AX
MOVQ AX, DR3
MOVQ 48(BP), AX
MOVQ AX, DR6
RET
TEXT getdr6(SB), 1, $-4
MOVQ DR6, AX
RET
TEXT putdr6(SB), 1, $-4
MOVQ BP, DR6
RET
TEXT putdr7(SB), 1, $-4
MOVQ BP, DR7
RET
/* VMX instructions */
TEXT vmxon(SB), 1, $-4
MOVQ BP, 8(SP)
/* VMXON 8(SP) */
BYTE $0xf3; BYTE $0x0f; BYTE $0xc7; BYTE $0x74; BYTE $0x24; BYTE $0x08
JMP _vmout
TEXT vmxoff(SB), 1, $-4
BYTE $0x0f; BYTE $0x01; BYTE $0xc4
JMP _vmout
TEXT vmclear(SB), 1, $-4
MOVQ BP, 8(SP)
/* VMCLEAR 8(SP) */
BYTE $0x66; BYTE $0x0f; BYTE $0xc7; BYTE $0x74; BYTE $0x24; BYTE $0x08
JMP _vmout
TEXT vmlaunch(SB), 1, $-4
MOVL $0x6C14, DI
MOVQ SP, DX
BYTE $0x0f; BYTE $0x79; BYTE $0xfa /* VMWRITE DX, DI */
JBE _vmout
MOVL $0x6C16, DI
MOVQ $vmrestore(SB), DX
BYTE $0x0f; BYTE $0x79; BYTE $0xfa /* VMWRITE DX, DI */
JBE _vmout
MOVQ BP, ureg+0(FP)
MOVL resume+8(FP), AX
TESTL AX, AX
MOVQ 0x00(BP), AX
MOVQ 0x08(BP), BX
MOVQ 0x10(BP), CX
MOVQ 0x18(BP), DX
MOVQ 0x20(BP), SI
MOVQ 0x28(BP), DI
MOVQ 0x38(BP), R8
MOVQ 0x40(BP), R9
MOVQ 0x48(BP), R10
MOVQ 0x50(BP), R11
MOVQ 0x58(BP), R12
MOVQ 0x60(BP), R13
MOVQ 0x68(BP), R14
MOVQ 0x70(BP), R15
MOVQ 0x30(BP), BP
JNE _vmresume
BYTE $0x0f; BYTE $0x01; BYTE $0xc2 /* VMLAUNCH */
JMP _vmout
_vmresume:
BYTE $0x0f; BYTE $0x01; BYTE $0xc3 /* VMRESUME */
JMP _vmout
TEXT vmrestore(SB), 1, $-4
PUSHQ BP
MOVQ ureg+0(FP), BP
MOVQ AX, 0x00(BP)
MOVQ BX, 0x08(BP)
MOVQ CX, 0x10(BP)
MOVQ DX, 0x18(BP)
MOVQ SI, 0x20(BP)
MOVQ DI, 0x28(BP)
POPQ 0x30(BP)
MOVQ R8, 0x38(BP)
MOVQ R9, 0x40(BP)
MOVQ R10, 0x48(BP)
MOVQ R11, 0x50(BP)
MOVQ R12, 0x58(BP)
MOVQ R13, 0x60(BP)
MOVQ R14, 0x68(BP)
MOVQ R15, 0x70(BP)
BYTE $0x65; MOVQ 0, RMACH /* MOVQ GS:(0), RMACH */
MOVQ 16(RMACH), RUSER
XORL AX, AX
RET
TEXT vmptrld(SB), 1, $-4
MOVQ BP, 8(SP)
/* VMMPTRLD 8(SP) */
BYTE $0x0f; BYTE $0xc7; BYTE $0x74; BYTE $0x24; BYTE $0x08
JMP _vmout
TEXT vmwrite(SB), 1, $-4
MOVQ val+8(FP), DX
/* VMWRITE DX, BP */
BYTE $0x0f; BYTE $0x79; BYTE $0xea
JMP _vmout
TEXT vmread(SB), 1, $-4
MOVQ valp+8(FP), DI
/* VMREAD BP, (DI) */
BYTE $0x0f; BYTE $0x78; BYTE $0x2f
JMP _vmout
TEXT invept(SB), 1, $-4
/* INVEPT BP, 16(SP) */
BYTE $0x66; BYTE $0x0f; BYTE $0x38; BYTE $0x80; BYTE $0x6c; BYTE $0x24; BYTE $0x10
JMP _vmout
TEXT invvpid(SB), 1, $-4
/* INVVPID BP, 16(SP) */
BYTE $0x66; BYTE $0x0f; BYTE $0x38; BYTE $0x81; BYTE $0x6c; BYTE $0x24; BYTE $0x10
JMP _vmout
_vmout:
JC _vmout1
JZ _vmout2
XORL AX, AX
RET
_vmout1:
MOVQ $-1, AX
RET
_vmout2:
MOVQ $-2, AX
RET
/*
*/
TEXT touser(SB), 1, $-4
SWAPGS
MOVL $0, RMACH
MOVL $0, RUSER
MOVQ $(UTZERO+0x28), CX /* ip */
MOVL $0x200, R11 /* flags */
MOVQ RARG, SP /* sp */
BYTE $0x48; SYSRET /* SYSRETQ */
/*
*/
TEXT syscallentry(SB), 1, $-4
SWAPGS
BYTE $0x65; MOVQ 0, AX /* m-> (MOVQ GS:0x0, AX) */
MOVQ 16(AX), BX
MOVQ SP, R13
MOVQ BX, SP
PUSHQ $UDSEL /* old stack segment */
PUSHQ R13 /* old sp */
PUSHQ R11 /* old flags */
PUSHQ $UESEL /* old code segment */
PUSHQ CX /* old ip */
PUSHQ $0 /* error code */
PUSHQ $64 /* trap number (VectorSYSCALL) */
SUBQ $(8 + 23*8-7*8), SP /* arg + sizeof(Ureg)-pushed */
MOVQ RMACH, (15*8)(SP) /* old r15 */
MOVQ RUSER, (14*8)(SP) /* old r14 */
MOVQ RARG, (7*8)(SP) /* system call number */
MOVQ AX, RMACH /* m */
MOVQ BX, RUSER /* up */
LEAQ 8(SP), RARG /* Ureg* arg */
CALL syscall(SB)
TEXT forkret(SB), 1, $-4
SWAPGS
MOVQ 8(SP), AX /* return value */
MOVQ (15*8)(SP), RMACH /* r15 */
MOVQ (14*8)(SP), RUSER /* r14 */
MOVQ (19*8)(SP), CX /* ip */
MOVQ (21*8)(SP), R11 /* flags */
MOVQ (22*8)(SP), SP /* sp */
BYTE $0x48; SYSRET /* SYSRETQ */
/*
* Interrupt/exception handling.
*/
TEXT _strayintr(SB), 1, $-4 /* no error code pushed */
PUSHQ AX /* save AX */
MOVQ 8(SP), AX /* vectortable(SB) PC */
JMP _intrcommon
TEXT _strayintrx(SB), 1, $-4 /* error code pushed */
XCHGQ AX, (SP)
_intrcommon:
MOVBQZX (AX), AX
XCHGQ AX, (SP)
SUBQ $24, SP /* R1[45], [DEFG]S */
CMPW 48(SP), $KESEL /* old CS */
JEQ _intrnested
MOVQ RUSER, 0(SP)
MOVQ RMACH, 8(SP)
SWAPGS
BYTE $0x65; MOVQ 0, RMACH /* m-> (MOVQ GS:0x0, R15) */
MOVQ 16(RMACH), RUSER /* up */
_intrnested:
PUSHQ R13
PUSHQ R12
PUSHQ R11
PUSHQ R10
PUSHQ R9
PUSHQ R8
PUSHQ BP
PUSHQ DI
PUSHQ SI
PUSHQ DX
PUSHQ CX
PUSHQ BX
PUSHQ AX
MOVQ SP, RARG
PUSHQ SP
CALL trap(SB)
TEXT noteret(SB), 1, $-4
_intrestore:
POPQ AX
POPQ AX
POPQ BX
POPQ CX
POPQ DX
POPQ SI
POPQ DI
POPQ BP
POPQ R8
POPQ R9
POPQ R10
POPQ R11
POPQ R12
POPQ R13
CMPQ 48(SP), $KESEL
JEQ _iretnested
SWAPGS
MOVQ 8(SP), RMACH
MOVQ 0(SP), RUSER
_iretnested:
ADDQ $40, SP
IRETQ
TEXT vectortable(SB), $0
CALL _strayintr(SB); BYTE $0x00 /* divide error */
CALL _strayintr(SB); BYTE $0x01 /* debug exception */
CALL _strayintr(SB); BYTE $0x02 /* NMI interrupt */
CALL _strayintr(SB); BYTE $0x03 /* breakpoint */
CALL _strayintr(SB); BYTE $0x04 /* overflow */
CALL _strayintr(SB); BYTE $0x05 /* bound */
CALL _strayintr(SB); BYTE $0x06 /* invalid opcode */
CALL _strayintr(SB); BYTE $0x07 /* no coprocessor available */
CALL _strayintrx(SB); BYTE $0x08 /* double fault */
CALL _strayintr(SB); BYTE $0x09 /* coprocessor segment overflow */
CALL _strayintrx(SB); BYTE $0x0A /* invalid TSS */
CALL _strayintrx(SB); BYTE $0x0B /* segment not available */
CALL _strayintrx(SB); BYTE $0x0C /* stack exception */
CALL _strayintrx(SB); BYTE $0x0D /* general protection error */
CALL _strayintrx(SB); BYTE $0x0E /* page fault */
CALL _strayintr(SB); BYTE $0x0F /* */
CALL _strayintr(SB); BYTE $0x10 /* coprocessor error */
CALL _strayintrx(SB); BYTE $0x11 /* alignment check */
CALL _strayintr(SB); BYTE $0x12 /* machine check */
CALL _strayintr(SB); BYTE $0x13 /* simd error */
CALL _strayintr(SB); BYTE $0x14
CALL _strayintr(SB); BYTE $0x15
CALL _strayintr(SB); BYTE $0x16
CALL _strayintr(SB); BYTE $0x17
CALL _strayintr(SB); BYTE $0x18
CALL _strayintr(SB); BYTE $0x19
CALL _strayintr(SB); BYTE $0x1A
CALL _strayintr(SB); BYTE $0x1B
CALL _strayintr(SB); BYTE $0x1C
CALL _strayintr(SB); BYTE $0x1D
CALL _strayintr(SB); BYTE $0x1E
CALL _strayintr(SB); BYTE $0x1F
CALL _strayintr(SB); BYTE $0x20 /* VectorLAPIC */
CALL _strayintr(SB); BYTE $0x21
CALL _strayintr(SB); BYTE $0x22
CALL _strayintr(SB); BYTE $0x23
CALL _strayintr(SB); BYTE $0x24
CALL _strayintr(SB); BYTE $0x25
CALL _strayintr(SB); BYTE $0x26
CALL _strayintr(SB); BYTE $0x27
CALL _strayintr(SB); BYTE $0x28
CALL _strayintr(SB); BYTE $0x29
CALL _strayintr(SB); BYTE $0x2A
CALL _strayintr(SB); BYTE $0x2B
CALL _strayintr(SB); BYTE $0x2C
CALL _strayintr(SB); BYTE $0x2D
CALL _strayintr(SB); BYTE $0x2E
CALL _strayintr(SB); BYTE $0x2F
CALL _strayintr(SB); BYTE $0x30
CALL _strayintr(SB); BYTE $0x31
CALL _strayintr(SB); BYTE $0x32
CALL _strayintr(SB); BYTE $0x33
CALL _strayintr(SB); BYTE $0x34
CALL _strayintr(SB); BYTE $0x35
CALL _strayintr(SB); BYTE $0x36
CALL _strayintr(SB); BYTE $0x37
CALL _strayintr(SB); BYTE $0x38
CALL _strayintr(SB); BYTE $0x39
CALL _strayintr(SB); BYTE $0x3A
CALL _strayintr(SB); BYTE $0x3B
CALL _strayintr(SB); BYTE $0x3C
CALL _strayintr(SB); BYTE $0x3D
CALL _strayintr(SB); BYTE $0x3E
CALL _strayintr(SB); BYTE $0x3F
CALL _strayintr(SB); BYTE $0x40 /* was VectorSYSCALL */
CALL _strayintr(SB); BYTE $0x41
CALL _strayintr(SB); BYTE $0x42
CALL _strayintr(SB); BYTE $0x43
CALL _strayintr(SB); BYTE $0x44
CALL _strayintr(SB); BYTE $0x45
CALL _strayintr(SB); BYTE $0x46
CALL _strayintr(SB); BYTE $0x47
CALL _strayintr(SB); BYTE $0x48
CALL _strayintr(SB); BYTE $0x49
CALL _strayintr(SB); BYTE $0x4A
CALL _strayintr(SB); BYTE $0x4B
CALL _strayintr(SB); BYTE $0x4C
CALL _strayintr(SB); BYTE $0x4D
CALL _strayintr(SB); BYTE $0x4E
CALL _strayintr(SB); BYTE $0x4F
CALL _strayintr(SB); BYTE $0x50
CALL _strayintr(SB); BYTE $0x51
CALL _strayintr(SB); BYTE $0x52
CALL _strayintr(SB); BYTE $0x53
CALL _strayintr(SB); BYTE $0x54
CALL _strayintr(SB); BYTE $0x55
CALL _strayintr(SB); BYTE $0x56
CALL _strayintr(SB); BYTE $0x57
CALL _strayintr(SB); BYTE $0x58
CALL _strayintr(SB); BYTE $0x59
CALL _strayintr(SB); BYTE $0x5A
CALL _strayintr(SB); BYTE $0x5B
CALL _strayintr(SB); BYTE $0x5C
CALL _strayintr(SB); BYTE $0x5D
CALL _strayintr(SB); BYTE $0x5E
CALL _strayintr(SB); BYTE $0x5F
CALL _strayintr(SB); BYTE $0x60
CALL _strayintr(SB); BYTE $0x61
CALL _strayintr(SB); BYTE $0x62
CALL _strayintr(SB); BYTE $0x63
CALL _strayintr(SB); BYTE $0x64
CALL _strayintr(SB); BYTE $0x65
CALL _strayintr(SB); BYTE $0x66
CALL _strayintr(SB); BYTE $0x67
CALL _strayintr(SB); BYTE $0x68
CALL _strayintr(SB); BYTE $0x69
CALL _strayintr(SB); BYTE $0x6A
CALL _strayintr(SB); BYTE $0x6B
CALL _strayintr(SB); BYTE $0x6C
CALL _strayintr(SB); BYTE $0x6D
CALL _strayintr(SB); BYTE $0x6E
CALL _strayintr(SB); BYTE $0x6F
CALL _strayintr(SB); BYTE $0x70
CALL _strayintr(SB); BYTE $0x71
CALL _strayintr(SB); BYTE $0x72
CALL _strayintr(SB); BYTE $0x73
CALL _strayintr(SB); BYTE $0x74
CALL _strayintr(SB); BYTE $0x75
CALL _strayintr(SB); BYTE $0x76
CALL _strayintr(SB); BYTE $0x77
CALL _strayintr(SB); BYTE $0x78
CALL _strayintr(SB); BYTE $0x79
CALL _strayintr(SB); BYTE $0x7A
CALL _strayintr(SB); BYTE $0x7B
CALL _strayintr(SB); BYTE $0x7C
CALL _strayintr(SB); BYTE $0x7D
CALL _strayintr(SB); BYTE $0x7E
CALL _strayintr(SB); BYTE $0x7F
CALL _strayintr(SB); BYTE $0x80 /* Vector[A]PIC */
CALL _strayintr(SB); BYTE $0x81
CALL _strayintr(SB); BYTE $0x82
CALL _strayintr(SB); BYTE $0x83
CALL _strayintr(SB); BYTE $0x84
CALL _strayintr(SB); BYTE $0x85
CALL _strayintr(SB); BYTE $0x86
CALL _strayintr(SB); BYTE $0x87
CALL _strayintr(SB); BYTE $0x88
CALL _strayintr(SB); BYTE $0x89
CALL _strayintr(SB); BYTE $0x8A
CALL _strayintr(SB); BYTE $0x8B
CALL _strayintr(SB); BYTE $0x8C
CALL _strayintr(SB); BYTE $0x8D
CALL _strayintr(SB); BYTE $0x8E
CALL _strayintr(SB); BYTE $0x8F
CALL _strayintr(SB); BYTE $0x90
CALL _strayintr(SB); BYTE $0x91
CALL _strayintr(SB); BYTE $0x92
CALL _strayintr(SB); BYTE $0x93
CALL _strayintr(SB); BYTE $0x94
CALL _strayintr(SB); BYTE $0x95
CALL _strayintr(SB); BYTE $0x96
CALL _strayintr(SB); BYTE $0x97
CALL _strayintr(SB); BYTE $0x98
CALL _strayintr(SB); BYTE $0x99
CALL _strayintr(SB); BYTE $0x9A
CALL _strayintr(SB); BYTE $0x9B
CALL _strayintr(SB); BYTE $0x9C
CALL _strayintr(SB); BYTE $0x9D
CALL _strayintr(SB); BYTE $0x9E
CALL _strayintr(SB); BYTE $0x9F
CALL _strayintr(SB); BYTE $0xA0
CALL _strayintr(SB); BYTE $0xA1
CALL _strayintr(SB); BYTE $0xA2
CALL _strayintr(SB); BYTE $0xA3
CALL _strayintr(SB); BYTE $0xA4
CALL _strayintr(SB); BYTE $0xA5
CALL _strayintr(SB); BYTE $0xA6
CALL _strayintr(SB); BYTE $0xA7
CALL _strayintr(SB); BYTE $0xA8
CALL _strayintr(SB); BYTE $0xA9
CALL _strayintr(SB); BYTE $0xAA
CALL _strayintr(SB); BYTE $0xAB
CALL _strayintr(SB); BYTE $0xAC
CALL _strayintr(SB); BYTE $0xAD
CALL _strayintr(SB); BYTE $0xAE
CALL _strayintr(SB); BYTE $0xAF
CALL _strayintr(SB); BYTE $0xB0
CALL _strayintr(SB); BYTE $0xB1
CALL _strayintr(SB); BYTE $0xB2
CALL _strayintr(SB); BYTE $0xB3
CALL _strayintr(SB); BYTE $0xB4
CALL _strayintr(SB); BYTE $0xB5
CALL _strayintr(SB); BYTE $0xB6
CALL _strayintr(SB); BYTE $0xB7
CALL _strayintr(SB); BYTE $0xB8
CALL _strayintr(SB); BYTE $0xB9
CALL _strayintr(SB); BYTE $0xBA
CALL _strayintr(SB); BYTE $0xBB
CALL _strayintr(SB); BYTE $0xBC
CALL _strayintr(SB); BYTE $0xBD
CALL _strayintr(SB); BYTE $0xBE
CALL _strayintr(SB); BYTE $0xBF
CALL _strayintr(SB); BYTE $0xC0
CALL _strayintr(SB); BYTE $0xC1
CALL _strayintr(SB); BYTE $0xC2
CALL _strayintr(SB); BYTE $0xC3
CALL _strayintr(SB); BYTE $0xC4
CALL _strayintr(SB); BYTE $0xC5
CALL _strayintr(SB); BYTE $0xC6
CALL _strayintr(SB); BYTE $0xC7
CALL _strayintr(SB); BYTE $0xC8
CALL _strayintr(SB); BYTE $0xC9
CALL _strayintr(SB); BYTE $0xCA
CALL _strayintr(SB); BYTE $0xCB
CALL _strayintr(SB); BYTE $0xCC
CALL _strayintr(SB); BYTE $0xCD
CALL _strayintr(SB); BYTE $0xCE
CALL _strayintr(SB); BYTE $0xCF
CALL _strayintr(SB); BYTE $0xD0
CALL _strayintr(SB); BYTE $0xD1
CALL _strayintr(SB); BYTE $0xD2
CALL _strayintr(SB); BYTE $0xD3
CALL _strayintr(SB); BYTE $0xD4
CALL _strayintr(SB); BYTE $0xD5
CALL _strayintr(SB); BYTE $0xD6
CALL _strayintr(SB); BYTE $0xD7
CALL _strayintr(SB); BYTE $0xD8
CALL _strayintr(SB); BYTE $0xD9
CALL _strayintr(SB); BYTE $0xDA
CALL _strayintr(SB); BYTE $0xDB
CALL _strayintr(SB); BYTE $0xDC
CALL _strayintr(SB); BYTE $0xDD
CALL _strayintr(SB); BYTE $0xDE
CALL _strayintr(SB); BYTE $0xDF
CALL _strayintr(SB); BYTE $0xE0
CALL _strayintr(SB); BYTE $0xE1
CALL _strayintr(SB); BYTE $0xE2
CALL _strayintr(SB); BYTE $0xE3
CALL _strayintr(SB); BYTE $0xE4
CALL _strayintr(SB); BYTE $0xE5
CALL _strayintr(SB); BYTE $0xE6
CALL _strayintr(SB); BYTE $0xE7
CALL _strayintr(SB); BYTE $0xE8
CALL _strayintr(SB); BYTE $0xE9
CALL _strayintr(SB); BYTE $0xEA
CALL _strayintr(SB); BYTE $0xEB
CALL _strayintr(SB); BYTE $0xEC
CALL _strayintr(SB); BYTE $0xED
CALL _strayintr(SB); BYTE $0xEE
CALL _strayintr(SB); BYTE $0xEF
CALL _strayintr(SB); BYTE $0xF0
CALL _strayintr(SB); BYTE $0xF1
CALL _strayintr(SB); BYTE $0xF2
CALL _strayintr(SB); BYTE $0xF3
CALL _strayintr(SB); BYTE $0xF4
CALL _strayintr(SB); BYTE $0xF5
CALL _strayintr(SB); BYTE $0xF6
CALL _strayintr(SB); BYTE $0xF7
CALL _strayintr(SB); BYTE $0xF8
CALL _strayintr(SB); BYTE $0xF9
CALL _strayintr(SB); BYTE $0xFA
CALL _strayintr(SB); BYTE $0xFB
CALL _strayintr(SB); BYTE $0xFC
CALL _strayintr(SB); BYTE $0xFD
CALL _strayintr(SB); BYTE $0xFE
CALL _strayintr(SB); BYTE $0xFF
|
9front/9front
| 4,008
|
sys/src/9/pc64/apbootstrap.s
|
/*
* Start an Application Processor. This must be placed on a 4KB boundary
* somewhere in the 1st MB of conventional memory (APBOOTSTRAP). However,
* due to some shortcuts below it's restricted further to within the 1st
* 64KB. The AP starts in real-mode, with
* CS selector set to the startup memory address/16;
* CS base set to startup memory address;
* CS limit set to 64KB;
* CPL and IP set to 0.
*/
#include "mem.h"
#define NOP BYTE $0x90 /* NOP */
#define pFARJMP32(s, o) BYTE $0xea; /* far jmp ptr32:16 */ \
LONG $o; WORD $s
#define rFARJMP16(s, o) BYTE $0xea; /* far jump ptr16:16 */ \
WORD $o; WORD $s;
#define rFARJMP32(s, o) BYTE $0x66; /* far jump ptr32:16 */ \
pFARJMP32(s, o)
#define rLGDT(gdtptr) BYTE $0x0f; /* LGDT */ \
BYTE $0x01; BYTE $0x16; \
WORD $gdtptr
#define rMOVAX(i) BYTE $0xb8; /* i -> AX */ \
WORD $i;
#define DELAY BYTE $0xEB; /* JMP .+2 */ \
BYTE $0x00
MODE $16
TEXT apbootstrap(SB), 1, $-4
rFARJMP16(0, _apbootstrap-KZERO(SB))
NOP; NOP; NOP;
TEXT _apvector(SB), 1, $-4 /* address APBOOTSTRAP+0x08 */
QUAD $0
TEXT _appml4(SB), 1, $-4 /* address APBOOTSTRAP+0x10 */
QUAD $0
TEXT _apapic(SB), 1, $-4 /* address APBOOTSTRAP+0x18 */
QUAD $0
TEXT _apmach(SB), 1, $-4 /* address APBOOTSTRAP+0x20 */
QUAD $0
TEXT _apefer(SB), 1, $-4
QUAD $0x100 /* Long Mode Enable */
TEXT _apbootstrap(SB), 1, $-4
MOVW CS, AX
MOVW AX, DS /* initialise DS */
rLGDT(_gdtptr32p<>-KZERO(SB)) /* load a basic gdt */
MOVL CR0, AX
ORL $1, AX
MOVL AX, CR0 /* turn on protected mode */
DELAY /* JMP .+2 */
rFARJMP16(SELECTOR(3, SELGDT, 0), _ap32-KZERO(SB))
/*
* Enable and activate Long Mode. From the manual:
* make sure Page Size Extentions are off, and Page Global
* Extensions and Physical Address Extensions are on in CR4;
* set Long Mode Enable in the Extended Feature Enable MSR;
* set Paging Enable in CR0;
* make an inter-segment jump to the Long Mode code.
* It's all in 32-bit mode until the jump is made.
*/
MODE $32
TEXT _ap32(SB), 1, $-4
MOVW $SELECTOR(2, SELGDT, 0), AX
MOVW AX, DS
MOVW AX, ES
MOVW AX, FS
MOVW AX, GS
MOVW AX, SS
MOVL _appml4-KZERO(SB), AX /* physical address of PML4 */
MOVL AX, CR3 /* load the mmu */
DELAY
MOVL CR4, AX
ANDL $~0x00000010, AX /* Page Size */
ORL $0x000000A0, AX /* Page Global, Phys. Address */
MOVL AX, CR4
MOVL $0xc0000080, CX /* Extended Feature Enable */
RDMSR
ORL _apefer-KZERO(SB), AX
WRMSR
MOVL CR0, DX
ANDL $~0x6000000a, DX
ORL $0x80010000, DX /* Paging Enable, Write Protect */
MOVL DX, CR0
pFARJMP32(SELECTOR(KESEG, SELGDT, 0), _ap64-KZERO(SB))
/*
* Long mode. Welcome to 2003.
* Jump out of the identity map space;
* load a proper long mode GDT;
* initialise the stack and call the
* C startup code in m->splpc.
*/
MODE $64
TEXT _ap64(SB), 1, $-4
MOVQ $_gdtptr64v<>(SB), AX
MOVL (AX), GDTR
XORQ AX, AX
MOVW AX, DS /* not used in long mode */
MOVW AX, ES /* not used in long mode */
MOVW AX, FS
MOVW AX, GS
MOVW AX, SS /* not used in long mode */
MOVW AX, LDTR
MOVQ _apmach(SB), SP
MOVQ AX, RUSER /* up = 0; */
MOVQ SP, RMACH /* m = apmach */
ADDQ $MACHSIZE, SP
PUSHQ AX /* clear flags */
POPFQ
MOVQ _apvector(SB), AX
MOVQ _apapic(SB), RARG
PUSHQ RARG
CALL *AX
_halt:
HLT
JMP _halt
TEXT _gdt<>(SB), 1, $-4
/* null descriptor */
LONG $0
LONG $0
/* (KESEG) 64 bit long mode exec segment */
LONG $(0xFFFF)
LONG $(SEGL|SEGG|SEGP|(0xF<<16)|SEGPL(0)|SEGEXEC|SEGR)
/* 32 bit data segment descriptor for 4 gigabytes (PL 0) */
LONG $(0xFFFF)
LONG $(SEGG|SEGB|(0xF<<16)|SEGP|SEGPL(0)|SEGDATA|SEGW)
/* 32 bit exec segment descriptor for 4 gigabytes (PL 0) */
LONG $(0xFFFF)
LONG $(SEGG|SEGD|(0xF<<16)|SEGP|SEGPL(0)|SEGEXEC|SEGR)
TEXT _gdtptr32p<>(SB), 1, $-4
WORD $(4*8-1)
LONG $_gdt<>-KZERO(SB)
TEXT _gdtptr64p<>(SB), 1, $-4
WORD $(4*8-1)
QUAD $_gdt<>-KZERO(SB)
TEXT _gdtptr64v<>(SB), 1, $-4
WORD $(4*8-1)
QUAD $_gdt<>(SB)
|
9front/9front
| 2,169
|
sys/src/9/pc64/rebootcode.s
|
#include "mem.h"
MODE $64
/*
* Turn off MMU, then memmove the new kernel to its correct location
* in physical memory. Then jumps the to start of the kernel.
*/
TEXT main(SB), 1, $-4
MOVL RARG, DI /* destination */
MOVL p2+8(FP), SI /* source */
MOVL n+16(FP), BX /* byte count */
/* load zero length idt */
MOVL $_idtptr64p<>(SB), AX
MOVL (AX), IDTR
/* load temporary gdt */
MOVL $_gdtptr64p<>(SB), AX
MOVL (AX), GDTR
/* load CS with 32bit code segment */
PUSHQ $SELECTOR(3, SELGDT, 0)
PUSHQ $_warp32<>(SB)
RETFQ
MODE $32
TEXT _warp32<>(SB), 1, $-4
/* load 32bit data segments */
MOVL $SELECTOR(2, SELGDT, 0), AX
MOVW AX, DS
MOVW AX, ES
MOVW AX, FS
MOVW AX, GS
MOVW AX, SS
/* turn off paging */
MOVL CR0, AX
ANDL $0x7fffffff, AX /* ~(PG) */
MOVL AX, CR0
MOVL $0, AX
MOVL AX, CR3
/* disable long mode */
MOVL $0xc0000080, CX /* Extended Feature Enable */
RDMSR
ANDL $0xfffffeff, AX /* Long Mode Disable */
WRMSR
/* diable pae */
MOVL CR4, AX
ANDL $0xffffff5f, AX /* ~(PAE|PGE) */
MOVL AX, CR4
MOVL BX, CX /* byte count */
MOVL DI, AX /* save entry point */
MOVL AX, SP /* move stack below entry */
/* park cpu for zero entry point */
ORL AX, AX
JZ _idle
/*
* the source and destination may overlap.
* determine whether to copy forward or backwards
*/
CMPL SI, DI
JGT _forward
MOVL SI, DX
ADDL CX, DX
CMPL DX, DI
JGT _back
_forward:
CLD
REP; MOVSB
_startkernel:
/* jump to entry point */
JMP* AX
_back:
ADDL CX, DI
ADDL CX, SI
SUBL $1, DI
SUBL $1, SI
STD
REP; MOVSB
JMP _startkernel
_idle:
HLT
JMP _idle
TEXT _gdt<>(SB), 1, $-4
/* null descriptor */
LONG $0
LONG $0
/* (KESEG) 64 bit long mode exec segment */
LONG $(0xFFFF)
LONG $(SEGL|SEGG|SEGP|(0xF<<16)|SEGPL(0)|SEGEXEC|SEGR)
/* 32 bit data segment descriptor for 4 gigabytes (PL 0) */
LONG $(0xFFFF)
LONG $(SEGG|SEGB|(0xF<<16)|SEGP|SEGPL(0)|SEGDATA|SEGW)
/* 32 bit exec segment descriptor for 4 gigabytes (PL 0) */
LONG $(0xFFFF)
LONG $(SEGG|SEGD|(0xF<<16)|SEGP|SEGPL(0)|SEGEXEC|SEGR)
TEXT _gdtptr64p<>(SB), 1, $-4
WORD $(4*8-1)
QUAD $_gdt<>(SB)
TEXT _idtptr64p<>(SB), 1, $-4
WORD $0
QUAD $0
|
9front/9front
| 13,459
|
sys/src/9/bcm64/l.s
|
#include "mem.h"
#include "../arm64/sysreg.h"
#undef SYSREG
#define SYSREG(op0,op1,Cn,Cm,op2) SPR(((op0)<<19|(op1)<<16|(Cn)<<12|(Cm)<<8|(op2)<<5))
TEXT _start(SB), 1, $-4
MOV R0, R26 /* save */
MOV $setSB-KZERO(SB), R28
BL svcmode<>(SB)
/* use dedicated stack pointer per exception level */
MOVWU $1, R1
MSR R1, SPSel
BL mmudisable<>(SB)
/* invalidate local caches */
BL cachedinv(SB)
BL cacheiinv(SB)
/* get machno in R0 */
MRS MPIDR_EL1, R0
BL mpidindex(SB)
/* get MACHP(R0) in R27 */
MOV $(MACHADDR(0)-KZERO), R27
MOVWU $MACHSIZE, R2
MULW R0, R2, R2
SUB R2, R27
/* set the stack pointer */
ADD $(MACHSIZE-16), R27, R1
MOV R1, SP
CBNZ R0, _startup
/* clear page table and machs */
MOV $(L1BOT-KZERO), R1
MOV $(MACHADDR(-1)-KZERO), R2
_zerol1:
MOV ZR, (R1)8!
CMP R1, R2
BNE _zerol1
/* clear BSS */
MOV $edata-KZERO(SB), R1
MOV $end-KZERO(SB), R2
_zerobss:
MOV ZR, (R1)8!
CMP R1, R2
BNE _zerobss
/* setup page tables */
MOV $(L1BOT-KZERO), R0
BL mmuidmap(SB)
MOV $(L1-KZERO), R0
BL mmu0init(SB)
SEVL
_startup:
WFE
BL mmuenable<>(SB)
MOV R26, R0
MOV $0, R26
ORR $KZERO, R27
MSR R27, TPIDR_EL1
MOV $setSB(SB), R28
BL main(SB)
TEXT stop<>(SB), 1, $-4
_stop:
WFE
B _stop
TEXT mpidindex(SB), 1, $-4
MOV R0,R1
MOV $0,R0
MOV $(MPIDMASK),R2
_mpidindex0:
CBZ R2,_mpidindex1
LSR $63,R2,R3
CBZ R3,_mpidindex2
LSR $63,R1,R3
LSLW $1,R0
ORRW R3,R0,R0
_mpidindex2:
LSL $1,R1
LSL $1,R2
B _mpidindex0
_mpidindex1:
RETURN
TEXT sev(SB), 1, $-4
SEV
WFE
RETURN
TEXT svcmode<>(SB), 1, $-4
MSR $0xF, DAIFSet
MRS CurrentEL, R0
ANDW $(3<<2), R0
CMPW $(1<<2), R0
BEQ el1
CMPW $(2<<2), R0
BEQ el2
B stop<>(SB)
el2:
MOV $0, R0
MSR R0, MDCR_EL2
ISB $SY
/* HCR = RW, HCD, SWIO, BSU, FB */
MOVWU $(1<<31 | 1<<29 | 1<<2 | 0<<10 | 0<<9), R0
MSR R0, HCR_EL2
ISB $SY
/* SCTLR = RES1 */
MOVWU $(3<<4 | 1<<11 | 1<<16 | 1<<18 | 3<<22 | 3<<28), R0
ISB $SY
MSR R0, SCTLR_EL2
ISB $SY
/* set VMID to zero */
MOV $0, R0
MSR R0, VTTBR_EL2
ISB $SY
MOVWU $(0xF<<6 | 4), R0
MSR R0, SPSR_EL2
MSR LR, ELR_EL2
ERET
el1:
RETURN
TEXT mmudisable<>(SB), 1, $-4
#define SCTLRCLR \
/* RES0 */ ( 3<<30 \
/* RES0 */ | 1<<27 \
/* UCI */ | 1<<26 \
/* EE */ | 1<<25 \
/* RES0 */ | 1<<21 \
/* E0E */ | 1<<24 \
/* WXN */ | 1<<19 \
/* nTWE */ | 1<<18 \
/* RES0 */ | 1<<17 \
/* nTWI */ | 1<<16 \
/* UCT */ | 1<<15 \
/* DZE */ | 1<<14 \
/* RES0 */ | 1<<13 \
/* RES0 */ | 1<<10 \
/* UMA */ | 1<<9 \
/* SA0 */ | 1<<4 \
/* SA */ | 1<<3 \
/* A */ | 1<<1 )
#define SCTLRSET \
/* RES1 */ ( 3<<28 \
/* RES1 */ | 3<<22 \
/* RES1 */ | 1<<20 \
/* RES1 */ | 1<<11 )
#define SCTLRMMU \
/* I */ ( 1<<12 \
/* C */ | 1<<2 \
/* M */ | 1<<0 )
/* initialise SCTLR, MMU and caches off */
ISB $SY
MRS SCTLR_EL1, R0
BIC $(SCTLRCLR | SCTLRMMU), R0
ORR $SCTLRSET, R0
ISB $SY
MSR R0, SCTLR_EL1
ISB $SY
B flushlocaltlb(SB)
TEXT mmuenable<>(SB), 1, $-4
/* return to virtual */
ORR $KZERO, LR
MOV LR, -16(RSP)!
BL flushlocaltlb(SB)
/* memory attributes */
#define MAIRINIT \
( 0xFF << MA_MEM_WB*8 \
| 0x33 << MA_MEM_WT*8 \
| 0x44 << MA_MEM_UC*8 \
| 0x00 << MA_DEV_nGnRnE*8 \
| 0x04 << MA_DEV_nGnRE*8 \
| 0x08 << MA_DEV_nGRE*8 \
| 0x0C << MA_DEV_GRE*8 )
MOV $MAIRINIT, R1
MSR R1, MAIR_EL1
ISB $SY
/* translation control */
#define TCRINIT \
/* TBI1 */ ( 0<<38 \
/* TBI0 */ | 0<<37 \
/* AS */ | 0<<36 \
/* TG1 */ | (((3<<16|1<<14|2<<12)>>PGSHIFT)&3)<<30 \
/* SH1 */ | SHARE_INNER<<28 \
/* ORGN1 */ | CACHE_WB<<26 \
/* IRGN1 */ | CACHE_WB<<24 \
/* EPD1 */ | 0<<23 \
/* A1 */ | 0<<22 \
/* T1SZ */ | (64-EVASHIFT)<<16 \
/* TG0 */ | (((1<<16|2<<14|0<<12)>>PGSHIFT)&3)<<14 \
/* SH0 */ | SHARE_INNER<<12 \
/* ORGN0 */ | CACHE_WB<<10 \
/* IRGN0 */ | CACHE_WB<<8 \
/* EPD0 */ | 0<<7 \
/* T0SZ */ | (64-EVASHIFT)<<0 )
MOV $TCRINIT, R1
MRS ID_AA64MMFR0_EL1, R2
ANDW $0x7, R2 // PARange
ADD R2<<32, R1 // IPS
MSR R1, TCR_EL1
ISB $SY
/* load the page tables */
MOV $(L1BOT-KZERO), R0
MOV $(L1TOP-KZERO), R1
ISB $SY
MSR R0, TTBR0_EL1
MSR R1, TTBR1_EL1
ISB $SY
/* enable MMU and caches */
MRS SCTLR_EL1, R1
ORR $SCTLRMMU, R1
ISB $SY
MSR R1, SCTLR_EL1
ISB $SY
MOV RSP, R1
ORR $KZERO, R1
MOV R1, RSP
MOV (RSP)16!, LR
B cacheiinv(SB)
TEXT touser(SB), 1, $-4
MOVWU $0x10028, R1 // entry
MOVWU $0, R2 // psr
MSR R0, SP_EL0 // sp
MSR R1, ELR_EL1
MSR R2, SPSR_EL1
ERET
TEXT cas(SB), 1, $-4
TEXT cmpswap(SB), 1, $-4
MOVWU ov+8(FP), R1
MOVWU nv+16(FP), R2
_cas1:
LDXRW (R0), R3
CMP R3, R1
BNE _cas0
STXRW R2, (R0), R4
CBNZ R4, _cas1
MOVW $1, R0
DMB $ISH
RETURN
_cas0:
CLREX
MOVW $0, R0
RETURN
TEXT tas(SB), 1, $-4
TEXT _tas(SB), 1, $-4
MOVW $0xdeaddead, R2
_tas1:
LDXRW (R0), R1
STXRW R2, (R0), R3
CBNZ R3, _tas1
MOVW R1, R0
TEXT coherence(SB), 1, $-4
DMB $ISH
RETURN
TEXT islo(SB), 1, $-4
MRS DAIF, R0
AND $(0x2<<6), R0
EOR $(0x2<<6), R0
RETURN
TEXT splhi(SB), 1, $-4
MRS DAIF, R0
MSR $0x2, DAIFSet
RETURN
TEXT splfhi(SB), 1, $-4
MRS DAIF, R0
MSR $0x3, DAIFSet
RETURN
TEXT spllo(SB), 1, $-4
MSR $0x3, DAIFClr
RETURN
TEXT splflo(SB), 1, $-4
MSR $0x1, DAIFClr
RETURN
TEXT splx(SB), 1, $-4
MSR R0, DAIF
RETURN
TEXT idlehands(SB), 1, $-4
DMB $ISH
MOV $nrdy(SB), R1
LDXRW (R1), R0
CBZ R0, _goodnight
CLREX
SEVL
_goodnight:
WFE
RETURN
TEXT vcycles(SB), 1, $-4
MRS CNTVCT_EL0, R0
RETURN
TEXT lcycles(SB), 1, $-4
MRS PMCCNTR_EL0, R0
RETURN
TEXT setlabel(SB), 1, $-4
MOV LR, 8(R0)
MOV SP, R1
MOV R1, 0(R0)
MOVW $0, R0
RETURN
TEXT gotolabel(SB), 1, $-4
MOV 8(R0), LR /* link */
MOV 0(R0), R1 /* sp */
MOV R1, SP
MOVW $1, R0
RETURN
TEXT returnto(SB), 1, $-4
MOV R0, 0(SP)
RETURN
TEXT getfar(SB), 1, $-4
MRS FAR_EL1, R0
RETURN
TEXT setttbr(SB), 1, $-4
DSB $ISHST
MSR R0, TTBR0_EL1
DSB $ISH
ISB $SY
RETURN
/*
* TLB maintenance operations.
* these broadcast to all cpu's in the cluser
* (inner sharable domain).
*/
TEXT flushasidva(SB), 1, $-4
TEXT tlbivae1is(SB), 1, $-4
DSB $ISHST
TLBI R0, 0,8,3,1 /* VAE1IS */
DSB $ISH
ISB $SY
RETURN
TEXT flushasidvall(SB), 1, $-4
TEXT tlbivale1is(SB), 1, $-4
DSB $ISHST
TLBI R0, 0,8,3,5 /* VALE1IS */
DSB $ISH
ISB $SY
RETURN
TEXT flushasid(SB), 1, $-4
TEXT tlbiaside1is(SB), 1, $-4
DSB $ISHST
TLBI R0, 0,8,3,2 /* ASIDE1IS */
DSB $ISH
ISB $SY
RETURN
TEXT flushtlb(SB), 1, $-4
TEXT tlbivmalle1is(SB), 1, $-4
DSB $ISHST
TLBI R0, 0,8,3,0 /* VMALLE1IS */
DSB $ISH
ISB $SY
RETURN
/*
* flush the tlb of this cpu. no broadcast.
*/
TEXT flushlocaltlb(SB), 1, $-4
TEXT tlbivmalle1(SB), 1, $-4
DSB $NSHST
TLBI R0, 0,8,7,0 /* VMALLE1 */
DSB $NSH
ISB $SY
RETURN
/*
* floating-point support.
*/
TEXT fpon(SB), 1, $-4
MOVW $(3<<20), R0
MSR R0, CPACR_EL1
ISB $SY
RETURN
TEXT fpoff(SB), 1, $-4
MOVW $(0<<20), R0
MSR R0, CPACR_EL1
ISB $SY
RETURN
TEXT fpsaveregs(SB), 1, $-4
WORD $(1<<30 | 3 << 26 | 2<<22 | 0x1F<<16 | 3<<10 | 0<<5 | 0) /* MOV { V0, V1, V2, V3 }, (R0)64! */
WORD $(1<<30 | 3 << 26 | 2<<22 | 0x1F<<16 | 3<<10 | 0<<5 | 4) /* MOV { V4, V5, V6, V7 }, (R0)64! */
WORD $(1<<30 | 3 << 26 | 2<<22 | 0x1F<<16 | 3<<10 | 0<<5 | 8) /* MOV { V8, V9, V10,V11 }, (R0)64! */
WORD $(1<<30 | 3 << 26 | 2<<22 | 0x1F<<16 | 3<<10 | 0<<5 | 12) /* MOV { V12,V13,V14,V15 }, (R0)64! */
WORD $(1<<30 | 3 << 26 | 2<<22 | 0x1F<<16 | 3<<10 | 0<<5 | 16) /* MOV { V16,V17,V18,V19 }, (R0)64! */
WORD $(1<<30 | 3 << 26 | 2<<22 | 0x1F<<16 | 3<<10 | 0<<5 | 20) /* MOV { V20,V21,V22,V23 }, (R0)64! */
WORD $(1<<30 | 3 << 26 | 2<<22 | 0x1F<<16 | 3<<10 | 0<<5 | 24) /* MOV { V24,V25,V26,V27 }, (R0)64! */
WORD $(1<<30 | 3 << 26 | 2<<22 | 0x1F<<16 | 3<<10 | 0<<5 | 28) /* MOV { V28,V29,V30,V31 }, (R0)64! */
RETURN
TEXT fploadregs(SB), 1, $-4
WORD $(1<<30 | 3 << 26 | 3<<22 | 0x1F<<16 | 3<<10 | 0<<5 | 0) /* MOV (R0)64!, { V0, V1, V2, V3 } */
WORD $(1<<30 | 3 << 26 | 3<<22 | 0x1F<<16 | 3<<10 | 0<<5 | 4) /* MOV (R0)64!, { V4, V5, V6, V7 } */
WORD $(1<<30 | 3 << 26 | 3<<22 | 0x1F<<16 | 3<<10 | 0<<5 | 8) /* MOV (R0)64!, { V8, V9, V10,V11 } */
WORD $(1<<30 | 3 << 26 | 3<<22 | 0x1F<<16 | 3<<10 | 0<<5 | 12) /* MOV (R0)64!, { V12,V13,V14,V15 } */
WORD $(1<<30 | 3 << 26 | 3<<22 | 0x1F<<16 | 3<<10 | 0<<5 | 16) /* MOV (R0)64!, { V16,V17,V18,V19 } */
WORD $(1<<30 | 3 << 26 | 3<<22 | 0x1F<<16 | 3<<10 | 0<<5 | 20) /* MOV (R0)64!, { V20,V21,V22,V23 } */
WORD $(1<<30 | 3 << 26 | 3<<22 | 0x1F<<16 | 3<<10 | 0<<5 | 24) /* MOV (R0)64!, { V24,V25,V26,V27 } */
WORD $(1<<30 | 3 << 26 | 3<<22 | 0x1F<<16 | 3<<10 | 0<<5 | 28) /* MOV (R0)64!, { V28,V29,V30,V31 } */
RETURN
// syscall or trap from EL0
TEXT vsys0(SB), 1, $-4
LSRW $26, R0, R17 // ec
CMPW $0x15, R17 // SVC trap?
BNE _itsatrap // nope.
MOVP R26, R27, 224(RSP)
MOVP R28, R29, 240(RSP)
MRS SP_EL0, R1
MRS ELR_EL1, R2
MRS SPSR_EL1, R3
MOV R0, 288(RSP) // type
MOV R1, 264(RSP) // sp
MOV R2, 272(RSP) // pc
MOV R3, 280(RSP) // psr
MOV $setSB(SB), R28
MRS TPIDR_EL1, R27
MOV 16(R27), R26
ADD $16, RSP, R0 // ureg
BL syscall(SB)
TEXT forkret(SB), 1, $-4
MSR $0x3, DAIFSet // interrupts off
ADD $16, RSP, R0 // ureg
MOV 16(RSP), R0 // ret
MOV 264(RSP), R1 // sp
MOV 272(RSP), R2 // pc
MOV 280(RSP), R3 // psr
MSR R1, SP_EL0
MSR R2, ELR_EL1
MSR R3, SPSR_EL1
MOVP 224(RSP), R26, R27
MOVP 240(RSP), R28, R29
MOV 256(RSP), R30 // link
ADD $TRAPFRAMESIZE, RSP
ERET
TEXT itsatrap<>(SB), 1, $-4
_itsatrap:
MOVP R1, R2, 24(RSP)
MOVP R3, R4, 40(RSP)
MOVP R5, R6, 56(RSP)
MOVP R7, R8, 72(RSP)
MOVP R9, R10, 88(RSP)
MOVP R11, R12, 104(RSP)
MOVP R13, R14, 120(RSP)
MOVP R15, R16, 136(RSP)
MOVP R18, R19, 160(RSP)
MOVP R20, R21, 176(RSP)
MOVP R22, R23, 192(RSP)
MOVP R24, R25, 208(RSP)
// trap/irq/fiq/serr from EL0
TEXT vtrap0(SB), 1, $-4
MOVP R26, R27, 224(RSP)
MOVP R28, R29, 240(RSP)
MRS SP_EL0, R1
MRS ELR_EL1, R2
MRS SPSR_EL1, R3
MOV R0, 288(RSP) // type
MOV R1, 264(RSP) // sp
MOV R2, 272(RSP) // pc
MOV R3, 280(RSP) // psr
MOV $setSB(SB), R28
MRS TPIDR_EL1, R27
MOV 16(R27), R26
ADD $16, RSP, R0 // ureg
BL trap(SB)
TEXT noteret(SB), 1, $-4
MSR $0x3, DAIFSet // interrupts off
ADD $16, RSP, R0 // ureg
MOV 264(RSP), R1 // sp
MOV 272(RSP), R2 // pc
MOV 280(RSP), R3 // psr
MSR R1, SP_EL0
MSR R2, ELR_EL1
MSR R3, SPSR_EL1
MOVP 224(RSP), R26, R27
MOVP 240(RSP), R28, R29
_intrreturn:
MOVP 16(RSP), R0, R1
MOVP 32(RSP), R2, R3
MOVP 48(RSP), R4, R5
MOVP 64(RSP), R6, R7
MOVP 80(RSP), R8, R9
MOVP 96(RSP), R10, R11
MOVP 112(RSP), R12, R13
MOVP 128(RSP), R14, R15
MOVP 144(RSP), R16, R17
MOVP 160(RSP), R18, R19
MOVP 176(RSP), R20, R21
MOVP 192(RSP), R22, R23
MOVP 208(RSP), R24, R25
MOV 256(RSP), R30 // link
ADD $TRAPFRAMESIZE, RSP
ERET
// irq/fiq/trap/serr from EL1
TEXT vtrap1(SB), 1, $-4
MOV R29, 248(RSP) // special
ADD $TRAPFRAMESIZE, RSP, R1
MRS ELR_EL1, R2
MRS SPSR_EL1, R3
MOV R0, 288(RSP) // type
MOV R1, 264(RSP) // sp
MOV R2, 272(RSP) // pc
MOV R3, 280(RSP) // psr
ADD $16, RSP, R0 // ureg
BL trap(SB)
MSR $0x3, DAIFSet // interrupts off
MOV 272(RSP), R2 // pc
MOV 280(RSP), R3 // psr
MSR R2, ELR_EL1
MSR R3, SPSR_EL1
MOV 248(RSP), R29 // special
B _intrreturn
// vector tables
TEXT vsys(SB), 1, $-4
SUB $TRAPFRAMESIZE, RSP
MOV R0, 16(RSP)
MOV R30, 256(RSP) // link
MOV R17, 152(RSP) // temp
MRS ESR_EL1, R0 // type
_vsyspatch:
B _vsyspatch // branch to vsys0() patched in
TEXT vtrap(SB), 1, $-4
SUB $TRAPFRAMESIZE, RSP
MOVP R0, R1, 16(RSP)
MOVP R2, R3, 32(RSP)
MOVP R4, R5, 48(RSP)
MOVP R6, R7, 64(RSP)
MOVP R8, R9, 80(RSP)
MOVP R10, R11, 96(RSP)
MOVP R12, R13, 112(RSP)
MOVP R14, R15, 128(RSP)
MOVP R16, R17, 144(RSP)
MOVP R18, R19, 160(RSP)
MOVP R20, R21, 176(RSP)
MOVP R22, R23, 192(RSP)
MOVP R24, R25, 208(RSP)
MOV R30, 256(RSP) // link
MRS ESR_EL1, R0 // type
_vtrappatch:
B _vtrappatch // branch to vtrapX() patched in
TEXT virq(SB), 1, $-4
SUB $TRAPFRAMESIZE, RSP
MOVP R0, R1, 16(RSP)
MOVP R2, R3, 32(RSP)
MOVP R4, R5, 48(RSP)
MOVP R6, R7, 64(RSP)
MOVP R8, R9, 80(RSP)
MOVP R10, R11, 96(RSP)
MOVP R12, R13, 112(RSP)
MOVP R14, R15, 128(RSP)
MOVP R16, R17, 144(RSP)
MOVP R18, R19, 160(RSP)
MOVP R20, R21, 176(RSP)
MOVP R22, R23, 192(RSP)
MOVP R24, R25, 208(RSP)
MOV R30, 256(RSP) // link
MOV $(1<<32), R0 // type irq
_virqpatch:
B _virqpatch // branch to vtrapX() patched in
TEXT vfiq(SB), 1, $-4
SUB $TRAPFRAMESIZE, RSP
MOVP R0, R1, 16(RSP)
MOVP R2, R3, 32(RSP)
MOVP R4, R5, 48(RSP)
MOVP R6, R7, 64(RSP)
MOVP R8, R9, 80(RSP)
MOVP R10, R11, 96(RSP)
MOVP R12, R13, 112(RSP)
MOVP R14, R15, 128(RSP)
MOVP R16, R17, 144(RSP)
MOVP R18, R19, 160(RSP)
MOVP R20, R21, 176(RSP)
MOVP R22, R23, 192(RSP)
MOVP R24, R25, 208(RSP)
MOV R30, 256(RSP) // link
MOV $(2<<32), R0 // type fiq
_vfiqpatch:
B _vfiqpatch // branch to vtrapX() patched in
TEXT vserr(SB), 1, $-4
SUB $TRAPFRAMESIZE, RSP
MOVP R0, R1, 16(RSP)
MOVP R2, R3, 32(RSP)
MOVP R4, R5, 48(RSP)
MOVP R6, R7, 64(RSP)
MOVP R8, R9, 80(RSP)
MOVP R10, R11, 96(RSP)
MOVP R12, R13, 112(RSP)
MOVP R14, R15, 128(RSP)
MOVP R16, R17, 144(RSP)
MOVP R18, R19, 160(RSP)
MOVP R20, R21, 176(RSP)
MOVP R22, R23, 192(RSP)
MOVP R24, R25, 208(RSP)
MOV R30, 256(RSP) // link
MRS ESR_EL1, R0
ORR $(3<<32), R0 // type
_vserrpatch:
B _vserrpatch // branch to vtrapX() patched in
/* fault-proof memcpy */
TEXT peek(SB), 1, $-4
MOV R0, R1
MOV dst+8(FP), R2
MOVWU len+16(FP), R0
TEXT _peekinst(SB), 1, $-4
_peekloop:
MOVBU (R1)1!, R3
MOVBU R3, (R2)1!
SUBS $1, R0
BNE _peekloop
RETURN
|
9front/9front
| 19,939
|
sys/src/9/ppc/l.s
|
#include "mem.h"
/* use of SPRG registers in save/restore */
#define SAVER0 SPRG0
#define SAVER1 SPRG1
#define SAVELR SPRG2
#define SAVEXX SPRG3
#ifdef ucuconf
/* These only exist on the PPC 755: */
#define SAVER4 SPRG4
#define SAVER5 SPRG5
#define SAVER6 SPRG6
#define SAVER7 SPRG7
#endif /* ucuconf */
/* special instruction definitions */
#define BDNZ BC 16, 0,
#define BDNE BC 0, 2,
#define MTCRF(r, crm) WORD $((31<<26)|((r)<<21)|(crm<<12)|(144<<1))
/* #define TLBIA WORD $((31<<26)|(370<<1)) Not implemented on the 603e */
#define TLBSYNC WORD $((31<<26)|(566<<1))
#define TLBLI(n) WORD $((31<<26)|((n)<<11)|(1010<<1))
#define TLBLD(n) WORD $((31<<26)|((n)<<11)|(978<<1))
/* on some models mtmsr doesn't synchronise enough (eg, 603e) */
#define MSRSYNC SYNC
#define UREGSPACE (UREGSIZE+8)
TEXT start(SB), $-4
/*
* setup MSR
* turn off interrupts
* use 0x000 as exception prefix
* enable machine check
*/
MOVW MSR, R3
MOVW $(MSR_ME|MSR_EE|MSR_IP), R4
ANDN R4, R3
SYNC
MOVW R3, MSR
MSRSYNC
/* except during trap handling, R0 is zero from now on */
MOVW $0, R0
/* setup SB for pre mmu */
MOVW $setSB(SB), R2
MOVW $KZERO, R3
ANDN R3, R2
/* before this we're not running above KZERO */
BL mmuinit0(SB)
/* after this we are */
#ifdef ucuconf
MOVW $0x2000000, R4 /* size */
MOVW $0, R3 /* base address */
RLWNM $0, R3, $~(CACHELINESZ-1), R5
CMP R4, $0
BLE _dcf1
SUB R5, R3
ADD R3, R4
ADD $(CACHELINESZ-1), R4
SRAW $CACHELINELOG, R4
MOVW R4, CTR
_dcf0: DCBF (R5)
ADD $CACHELINESZ, R5
BDNZ _dcf0
_dcf1:
SYNC
/* BAT0, 3 unused, copy of BAT2 */
MOVW SPR(IBATL(2)), R3
MOVW R3, SPR(IBATL(0))
MOVW SPR(IBATU(2)), R3
MOVW R3, SPR(IBATU(0))
MOVW SPR(DBATL(2)), R3
MOVW R3, SPR(DBATL(0))
MOVW SPR(DBATU(2)), R3
MOVW R3, SPR(DBATU(0))
MOVW SPR(IBATL(2)), R3
MOVW R3, SPR(IBATL(3))
MOVW SPR(IBATU(2)), R3
MOVW R3, SPR(IBATU(3))
MOVW SPR(DBATL(2)), R3
MOVW R3, SPR(DBATL(3))
MOVW SPR(DBATU(2)), R3
MOVW R3, SPR(DBATU(3))
#endif /* ucuconf */
/* running with MMU on!! */
/* set R2 to correct value */
MOVW $setSB(SB), R2
/* set up Mach */
MOVW $MACHADDR, R(MACH)
ADD $(MACHSIZE-8), R(MACH), R1 /* set stack */
MOVW R0, R(USER) /* up-> set to zero */
MOVW R0, 0(R(MACH)) /* machno set to zero */
BL main(SB)
RETURN /* not reached */
/*
* on return from this function we will be running in virtual mode.
* We set up the Block Address Translation (BAT) registers thus:
* 1) first 3 BATs are 256M blocks, starting from KZERO->0
* 2) remaining BAT maps last 256M directly
*/
TEXT mmuinit0(SB), $0
/* reset all the tlbs */
MOVW $64, R3
MOVW R3, CTR
MOVW $0, R4
tlbloop:
TLBIE R4
SYNC
ADD $BIT(19), R4
BDNZ tlbloop
TLBSYNC
#ifndef ucuconf
/* BATs 0 and 1 cover memory from 0x00000000 to 0x20000000 */
/* KZERO -> 0, IBAT and DBAT, 256 MB */
MOVW $(KZERO|(0x7ff<<2)|2), R3
MOVW $(PTEVALID|PTEWRITE), R4 /* PTEVALID => Cache coherency on */
MOVW R3, SPR(IBATU(0))
MOVW R4, SPR(IBATL(0))
MOVW R3, SPR(DBATU(0))
MOVW R4, SPR(DBATL(0))
/* KZERO+256M -> 256M, IBAT and DBAT, 256 MB */
ADD $(1<<28), R3
ADD $(1<<28), R4
MOVW R3, SPR(IBATU(1))
MOVW R4, SPR(IBATL(1))
MOVW R3, SPR(DBATU(1))
MOVW R4, SPR(DBATL(1))
/* FPGABASE -> FPGABASE, DBAT, 16 MB */
MOVW $(FPGABASE|(0x7f<<2)|2), R3
MOVW $(FPGABASE|PTEWRITE|PTEUNCACHED), R4 /* FPGA memory, don't cache */
MOVW R3, SPR(DBATU(2))
MOVW R4, SPR(DBATL(2))
/* IBAT 2 unused */
MOVW R0, SPR(IBATU(2))
MOVW R0, SPR(IBATL(2))
/* direct map last block, uncached, (not guarded, doesn't work for BAT), DBAT only */
MOVW $(INTMEM|(0x7ff<<2)|2), R3
MOVW $(INTMEM|PTEWRITE|PTEUNCACHED), R4 /* Don't set PTEVALID here */
MOVW R3, SPR(DBATU(3))
MOVW R4, SPR(DBATL(3))
/* IBAT 3 unused */
MOVW R0, SPR(IBATU(3))
MOVW R0, SPR(IBATL(3))
#else /* ucuconf */
/* BAT 2 covers memory from 0x00000000 to 0x10000000 */
/* KZERO -> 0, IBAT2 and DBAT2, 256 MB */
MOVW $(KZERO|(0x7ff<<2)|2), R3
MOVW $(PTEVALID|PTEWRITE), R4 /* PTEVALID => Cache coherency on */
MOVW R3, SPR(DBATU(2))
MOVW R4, SPR(DBATL(2))
MOVW R3, SPR(IBATU(2))
MOVW R4, SPR(IBATL(2))
#endif /* ucuconf */
/* enable MMU */
MOVW LR, R3
OR $KZERO, R3
MOVW R3, SPR(SRR0) /* Stored PC for RFI instruction */
MOVW MSR, R4
OR $(MSR_IR|MSR_DR|MSR_RI|MSR_FP), R4
MOVW R4, SPR(SRR1)
RFI /* resume in kernel mode in caller */
RETURN
TEXT kfpinit(SB), $0
MOVFL $0, FPSCR(7)
MOVFL $0xD, FPSCR(6) /* VE, OE, ZE */
MOVFL $0, FPSCR(5)
MOVFL $0, FPSCR(3)
MOVFL $0, FPSCR(2)
MOVFL $0, FPSCR(1)
MOVFL $0, FPSCR(0)
FMOVD $4503601774854144.0, F27
FMOVD $0.5, F29
FSUB F29, F29, F28
FADD F29, F29, F30
FADD F30, F30, F31
FMOVD F28, F0
FMOVD F28, F1
FMOVD F28, F2
FMOVD F28, F3
FMOVD F28, F4
FMOVD F28, F5
FMOVD F28, F6
FMOVD F28, F7
FMOVD F28, F8
FMOVD F28, F9
FMOVD F28, F10
FMOVD F28, F11
FMOVD F28, F12
FMOVD F28, F13
FMOVD F28, F14
FMOVD F28, F15
FMOVD F28, F16
FMOVD F28, F17
FMOVD F28, F18
FMOVD F28, F19
FMOVD F28, F20
FMOVD F28, F21
FMOVD F28, F22
FMOVD F28, F23
FMOVD F28, F24
FMOVD F28, F25
FMOVD F28, F26
RETURN
TEXT splhi(SB), $0
MOVW LR, R31
MOVW R31, 4(R(MACH)) /* save PC in m->splpc */
MOVW MSR, R3
RLWNM $0, R3, $~MSR_EE, R4
SYNC
MOVW R4, MSR
MSRSYNC
RETURN
TEXT splx(SB), $0
/* fall though */
TEXT splxpc(SB), $0
MOVW LR, R31
MOVW R31, 4(R(MACH)) /* save PC in m->splpc */
MOVW MSR, R4
RLWMI $0, R3, $MSR_EE, R4
SYNC
MOVW R4, MSR
MSRSYNC
RETURN
TEXT spllo(SB), $0
MOVW MSR, R3
OR $MSR_EE, R3, R4
SYNC
MOVW R4, MSR
MSRSYNC
RETURN
TEXT spldone(SB), $0
RETURN
TEXT islo(SB), $0
MOVW MSR, R3
RLWNM $0, R3, $MSR_EE, R3
RETURN
TEXT setlabel(SB), $-4
MOVW LR, R31
MOVW R1, 0(R3)
MOVW R31, 4(R3)
MOVW $0, R3
RETURN
TEXT gotolabel(SB), $-4
MOVW 4(R3), R31
MOVW R31, LR
MOVW 0(R3), R1
MOVW $1, R3
RETURN
TEXT touser(SB), $-4
MOVW $(UTZERO+32), R5 /* header appears in text */
MOVW $(MSR_EE|MSR_PR|MSR_IR|MSR_DR|MSR_RI), R4
MOVW R4, SPR(SRR1)
MOVW R3, R1
MOVW R5, SPR(SRR0)
RFI
TEXT dczap(SB), $-4 /* dczap(virtaddr, count) */
MOVW n+4(FP), R4
RLWNM $0, R3, $~(CACHELINESZ-1), R5
CMP R4, $0
BLE dcz1
SUB R5, R3
ADD R3, R4
ADD $(CACHELINESZ-1), R4
SRAW $CACHELINELOG, R4
MOVW R4, CTR
dcz0:
DCBI (R5)
ADD $CACHELINESZ, R5
BDNZ dcz0
dcz1:
SYNC
RETURN
TEXT dcflush(SB), $-4 /* dcflush(virtaddr, count) */
MOVW n+4(FP), R4
RLWNM $0, R3, $~(CACHELINESZ-1), R5
CMP R4, $0
BLE dcf1
SUB R5, R3
ADD R3, R4
ADD $(CACHELINESZ-1), R4
SRAW $CACHELINELOG, R4
MOVW R4, CTR
dcf0: DCBST (R5)
ADD $CACHELINESZ, R5
BDNZ dcf0
dcf1:
SYNC
RETURN
TEXT icflush(SB), $-4 /* icflush(virtaddr, count) */
MOVW n+4(FP), R4
RLWNM $0, R3, $~(CACHELINESZ-1), R5
CMP R4, $0
BLE icf1
SUB R5, R3
ADD R3, R4
ADD $(CACHELINESZ-1), R4
SRAW $CACHELINELOG, R4
MOVW R4, CTR
icf0: ICBI (R5) /* invalidate the instruction cache */
ADD $CACHELINESZ, R5
BDNZ icf0
ISYNC
icf1:
RETURN
TEXT tas(SB), $0
TEXT _tas(SB), $0
MOVW R3, R4
MOVW $0xdead, R5
tas1:
DCBF (R4) /* fix for 603x bug */
SYNC
LWAR (R4), R3
CMP R3, $0
BNE tas0
STWCCC R5, (R4)
BNE tas1
EIEIO
tas0:
SYNC
RETURN
TEXT tlbflushall(SB), $0
MOVW $TLBENTRIES, R3
MOVW R3, CTR
MOVW $0, R4
ISYNC
tlbflushall0:
TLBIE R4
SYNC
ADD $BIT(19), R4
BDNZ tlbflushall0
TLBSYNC
RETURN
TEXT tlbflush(SB), $0
ISYNC
TLBIE R3
SYNC
TLBSYNC
RETURN
TEXT gotopc(SB), $0
MOVW R3, CTR
MOVW LR, R31 /* for trace back */
BR (CTR)
/* On an imiss, we get here. If we can resolve it, we do.
* Otherwise take the real trap. The code at the vector is
* MOVW R0, SPR(SAVER0) No point to this, of course
* MOVW LR, R0
* MOVW R0, SPR(SAVELR)
* BL imiss(SB) or dmiss, as the case may be
* BL tlbvec(SB)
*/
TEXT imiss(SB), $-4
/* Statistics */
MOVW $MACHPADDR, R1
MOVW 0xc(R1), R3 /* count m->tlbfault */
ADD $1, R3
MOVW R3, 0xc(R1)
MOVW 0x10(R1), R3 /* count m->imiss */
ADD $1, R3
MOVW R3, 0x10(R1)
/* Real work */
MOVW SPR(HASH1), R1 /* (phys) pointer into the hash table */
ADD $BY2PTEG, R1, R2 /* end pointer */
MOVW SPR(iCMP), R3 /* pattern to look for */
imiss1:
MOVW (R1), R0
CMP R3, R0
BEQ imiss2 /* found the entry */
ADD $8, R1
CMP R1, R2 /* test end of loop */
BNE imiss1 /* Loop */
/* Failed to find an entry; take the full trap */
MOVW SPR(SRR1), R1
MTCRF(1, 0x80) /* restore CR0 bits (they're auto saved in SRR1) */
RETURN
imiss2:
/* Found the entry */
MOVW 4(R1), R2 /* Phys addr */
MOVW R2, SPR(RPA)
MOVW SPR(IMISS), R3
TLBLI(3)
/* Restore Registers */
MOVW SPR(SRR1), R1 /* Restore the CR0 field of the CR register from SRR1 */
MTCRF(1, 0x80)
MOVW SPR(SAVELR), R0
MOVW R0, LR
RFI
/* On a data load or store miss, we get here. If we can resolve it, we do.
* Otherwise take the real trap
*/
TEXT dmiss(SB), $-4
/* Statistics */
MOVW $MACHPADDR, R1
MOVW 0xc(R1), R3 /* count m->tlbfault */
ADD $1, R3
MOVW R3, 0xc(R1)
MOVW 0x14(R1), R3 /* count m->dmiss */
ADD $1, R3
MOVW R3, 0x14(R1)
/* Real work */
MOVW SPR(HASH1), R1 /* (phys) pointer into the hash table */
ADD $BY2PTEG, R1, R2 /* end pointer */
MOVW SPR(DCMP), R3 /* pattern to look for */
dmiss1:
MOVW (R1), R0
CMP R3, R0
BEQ dmiss2 /* found the entry */
ADD $8, R1
CMP R1, R2 /* test end of loop */
BNE dmiss1 /* Loop */
/* Failed to find an entry; take the full trap */
MOVW SPR(SRR1), R1
MTCRF(1, 0x80) /* restore CR0 bits (they're auto saved in SRR1) */
RETURN
dmiss2:
/* Found the entry */
MOVW 4(R1), R2 /* Phys addr */
MOVW R2, SPR(RPA)
MOVW SPR(DMISS), R3
TLBLD(3)
/* Restore Registers */
MOVW SPR(SRR1), R1 /* Restore the CR0 field of the CR register from SRR1 */
MTCRF(1, 0x80)
MOVW SPR(SAVELR), R0
MOVW R0, LR
RFI
/*
* When a trap sets the TGPR bit (TLB miss traps do this),
* registers get remapped: R0-R31 are temporarily inaccessible,
* and Temporary Registers TR0-TR3 are mapped onto R0-R3.
* While this bit is set, R4-R31 cannot be used.
* The code at the vector has executed this code before
* coming to tlbvec:
* MOVW R0, SPR(SAVER0) No point to this, of course
* MOVW LR, R0
* MOVW R0, SPR(SAVELR)
* BL tlbvec(SB)
* SAVER0 can be reused. We're not interested in the value of TR0
*/
TEXT tlbvec(SB), $-4
MOVW MSR, R1
RLWNM $0, R1, $~MSR_TGPR, R1 /* Clear the dreaded TGPR bit in the MSR */
SYNC
MOVW R1, MSR
MSRSYNC
/* Now the GPRs are what they're supposed to be, save R0 again */
MOVW R0, SPR(SAVER0)
/* Fall through to trapvec */
/*
* traps force memory mapping off.
* the following code has been executed at the exception
* vector location
* MOVW R0, SPR(SAVER0)
* MOVW LR, R0
* MOVW R0, SPR(SAVELR)
* bl trapvec(SB)
*
*/
TEXT trapvec(SB), $-4
MOVW LR, R0
MOVW R1, SPR(SAVER1)
MOVW R0, SPR(SAVEXX) /* vector */
/* did we come from user space */
MOVW SPR(SRR1), R0
MOVW CR, R1
MOVW R0, CR
BC 4, 17, ktrap
/* switch to kernel stack */
MOVW R1, CR
MOVW $MACHPADDR, R1 /* PADDR(m->) */
MOVW 8(R1), R1 /* m->proc */
RLWNM $0, R1, $~KZERO, R1 /* PADDR(m->proc) */
SUB $UREGSIZE, R1 /* make room on stack */
BL saveureg(SB)
BL trap(SB)
BR restoreureg
ktrap:
MOVW R1, CR
MOVW SPR(SAVER1), R1
RLWNM $0, R1, $~KZERO, R1 /* set stack pointer */
SUB $UREGSPACE, R1
BL saveureg(SB) /* addressed relative to PC */
BL trap(SB)
BR restoreureg
/*
* enter with stack set and mapped.
* on return, SB (R2) has been set, and R3 has the Ureg*,
* the MMU has been re-enabled, kernel text and PC are in KSEG,
* R(MACH) has been set, and R0 contains 0.
*
*/
TEXT saveureg(SB), $-4
/*
* save state
*/
MOVMW R2, 48(R1) /* save r2 .. r31 in 48(R1) .. 164(R1) */
MOVW $MACHPADDR, R(MACH) /* PADDR(m->) */
MOVW 8(R(MACH)), R(USER) /* up-> */
MOVW $MACHADDR, R(MACH) /* m-> */
MOVW SPR(SAVER1), R4
MOVW R4, 44(R1)
MOVW SPR(SAVER0), R5
MOVW R5, 40(R1)
MOVW CTR, R6
MOVW R6, 36(R1)
MOVW XER, R4
MOVW R4, 32(R1)
MOVW CR, R5
MOVW R5, 28(R1)
MOVW SPR(SAVELR), R6 /* LR */
MOVW R6, 24(R1)
/* pad at 20(R1) */
MOVW SPR(SRR0), R0
MOVW R0, 16(R1) /* old PC */
MOVW SPR(SRR1), R0
MOVW R0, 12(R1) /* old status */
MOVW SPR(SAVEXX), R0
MOVW R0, 8(R1) /* cause/vector */
MOVW SPR(DCMP), R0
MOVW R0, (160+8)(R1)
MOVW SPR(iCMP), R0
MOVW R0, (164+8)(R1)
MOVW SPR(DMISS), R0
MOVW R0, (168+8)(R1)
MOVW SPR(IMISS), R0
MOVW R0, (172+8)(R1)
MOVW SPR(HASH1), R0
MOVW R0, (176+8)(R1)
MOVW SPR(HASH2), R0
MOVW R0, (180+8)(R1)
MOVW SPR(DAR), R0
MOVW R0, (184+8)(R1)
MOVW SPR(DSISR), R0
MOVW R0, (188+8)(R1)
ADD $8, R1, R3 /* Ureg* */
OR $KZERO, R3 /* fix ureg */
STWCCC R3, (R1) /* break any pending reservations */
MOVW $0, R0 /* compiler/linker expect R0 to be zero */
MOVW $setSB(SB), R2 /* SB register */
MOVW MSR, R5
OR $(MSR_IR|MSR_DR|MSR_FP|MSR_RI), R5 /* enable MMU */
MOVW R5, SPR(SRR1)
MOVW LR, R31
OR $KZERO, R31 /* return PC in KSEG0 */
MOVW R31, SPR(SRR0)
OR $KZERO, R1 /* fix stack pointer */
RFI /* returns to trap handler */
/*
* restore state from Ureg and return from trap/interrupt
*/
TEXT forkret(SB), $0
BR restoreureg
restoreureg:
MOVMW 48(R1), R2 /* restore r2 through r31 */
/* defer R1 */
MOVW 40(R1), R0
MOVW R0, SPR(SAVER0) /* resave saved R0 */
MOVW 36(R1), R0
MOVW R0, CTR
MOVW 32(R1), R0
MOVW R0, XER
MOVW 28(R1), R0
MOVW R0, CR /* Condition register*/
MOVW 24(R1), R0
MOVW R0, LR
/* pad, skip */
MOVW 16(R1), R0
MOVW R0, SPR(SRR0) /* old PC */
MOVW 12(R1), R0
MOVW R0, SPR(SRR1) /* old MSR */
/* cause, skip */
MOVW 44(R1), R1 /* old SP */
MOVW SPR(SAVER0), R0
RFI
TEXT getpvr(SB), $0
MOVW SPR(PVR), R3
RETURN
TEXT getdec(SB), $0
MOVW SPR(DEC), R3
RETURN
TEXT putdec(SB), $0
MOVW R3, SPR(DEC)
RETURN
TEXT getdar(SB), $0
MOVW SPR(DAR), R3
RETURN
TEXT getdsisr(SB), $0
MOVW SPR(DSISR), R3
RETURN
TEXT getmsr(SB), $0
MOVW MSR, R3
RETURN
TEXT putmsr(SB), $0
MOVW R3, MSR
MSRSYNC
RETURN
TEXT putsdr1(SB), $0
SYNC
MOVW R3, SPR(SDR1)
ISYNC
RETURN
TEXT putsr(SB), $0
MOVW 4(FP), R4
SYNC
MOVW R4, SEG(R3)
MSRSYNC
RETURN
TEXT getsr(SB), $0
MOVW SEG(R3), R3
RETURN
TEXT gethid0(SB), $0
MOVW SPR(HID0), R3
RETURN
TEXT puthid0(SB), $0
SYNC
ISYNC
MOVW R3, SPR(HID0)
SYNC
RETURN
TEXT gethid1(SB), $0
MOVW SPR(HID1), R3
RETURN
TEXT gethid2(SB), $0
MOVW SPR(HID2), R3
RETURN
TEXT puthid2(SB), $0
MOVW R3, SPR(HID2)
RETURN
TEXT eieio(SB), $0
EIEIO
RETURN
TEXT sync(SB), $0
SYNC
RETURN
/* Power PC 603e specials */
TEXT getimiss(SB), $0
MOVW SPR(IMISS), R3
RETURN
TEXT geticmp(SB), $0
MOVW SPR(iCMP), R3
RETURN
TEXT puticmp(SB), $0
MOVW R3, SPR(iCMP)
RETURN
TEXT getdmiss(SB), $0
MOVW SPR(DMISS), R3
RETURN
TEXT getdcmp(SB), $0
MOVW SPR(DCMP), R3
RETURN
TEXT putdcmp(SB), $0
MOVW R3, SPR(DCMP)
RETURN
TEXT getsdr1(SB), $0
MOVW SPR(SDR1), R3
RETURN
TEXT gethash1(SB), $0
MOVW SPR(HASH1), R3
RETURN
TEXT puthash1(SB), $0
MOVW R3, SPR(HASH1)
RETURN
TEXT gethash2(SB), $0
MOVW SPR(HASH2), R3
RETURN
TEXT puthash2(SB), $0
MOVW R3, SPR(HASH2)
RETURN
TEXT getrpa(SB), $0
MOVW SPR(RPA), R3
RETURN
TEXT putrpa(SB), $0
MOVW R3, SPR(RPA)
RETURN
TEXT tlbli(SB), $0
TLBLI(3)
ISYNC
RETURN
TEXT tlbld(SB), $0
SYNC
TLBLD(3)
ISYNC
RETURN
TEXT getsrr1(SB), $0
MOVW SPR(SRR1), R3
RETURN
TEXT putsrr1(SB), $0
MOVW R3, SPR(SRR1)
RETURN
TEXT fpsave(SB), $0
FMOVD F0, (0*8)(R3)
FMOVD F1, (1*8)(R3)
FMOVD F2, (2*8)(R3)
FMOVD F3, (3*8)(R3)
FMOVD F4, (4*8)(R3)
FMOVD F5, (5*8)(R3)
FMOVD F6, (6*8)(R3)
FMOVD F7, (7*8)(R3)
FMOVD F8, (8*8)(R3)
FMOVD F9, (9*8)(R3)
FMOVD F10, (10*8)(R3)
FMOVD F11, (11*8)(R3)
FMOVD F12, (12*8)(R3)
FMOVD F13, (13*8)(R3)
FMOVD F14, (14*8)(R3)
FMOVD F15, (15*8)(R3)
FMOVD F16, (16*8)(R3)
FMOVD F17, (17*8)(R3)
FMOVD F18, (18*8)(R3)
FMOVD F19, (19*8)(R3)
FMOVD F20, (20*8)(R3)
FMOVD F21, (21*8)(R3)
FMOVD F22, (22*8)(R3)
FMOVD F23, (23*8)(R3)
FMOVD F24, (24*8)(R3)
FMOVD F25, (25*8)(R3)
FMOVD F26, (26*8)(R3)
FMOVD F27, (27*8)(R3)
FMOVD F28, (28*8)(R3)
FMOVD F29, (29*8)(R3)
FMOVD F30, (30*8)(R3)
FMOVD F31, (31*8)(R3)
MOVFL FPSCR, F0
FMOVD F0, (32*8)(R3)
RETURN
TEXT fprestore(SB), $0
FMOVD (32*8)(R3), F0
MOVFL F0, FPSCR
FMOVD (0*8)(R3), F0
FMOVD (1*8)(R3), F1
FMOVD (2*8)(R3), F2
FMOVD (3*8)(R3), F3
FMOVD (4*8)(R3), F4
FMOVD (5*8)(R3), F5
FMOVD (6*8)(R3), F6
FMOVD (7*8)(R3), F7
FMOVD (8*8)(R3), F8
FMOVD (9*8)(R3), F9
FMOVD (10*8)(R3), F10
FMOVD (11*8)(R3), F11
FMOVD (12*8)(R3), F12
FMOVD (13*8)(R3), F13
FMOVD (14*8)(R3), F14
FMOVD (15*8)(R3), F15
FMOVD (16*8)(R3), F16
FMOVD (17*8)(R3), F17
FMOVD (18*8)(R3), F18
FMOVD (19*8)(R3), F19
FMOVD (20*8)(R3), F20
FMOVD (21*8)(R3), F21
FMOVD (22*8)(R3), F22
FMOVD (23*8)(R3), F23
FMOVD (24*8)(R3), F24
FMOVD (25*8)(R3), F25
FMOVD (26*8)(R3), F26
FMOVD (27*8)(R3), F27
FMOVD (28*8)(R3), F28
FMOVD (29*8)(R3), F29
FMOVD (30*8)(R3), F30
FMOVD (31*8)(R3), F31
RETURN
TEXT dcacheenb(SB), $0
SYNC
MOVW SPR(HID0), R4 /* Get HID0 and clear unwanted bits */
RLWNM $0, R4, $~(HID_DLOCK), R4
MOVW $(HID_DCFI|HID_DCE), R5
OR R4, R5
MOVW $HID_DCE, R3
OR R4, R3
SYNC
// MOVW R5, SPR(HID0) /* Cache enable and flash invalidate */
MOVW R3, SPR(HID0) /* Cache enable */
SYNC
RETURN
TEXT icacheenb(SB), $0
SYNC
MOVW SPR(HID0), R4 /* Get HID0 and clear unwanted bits */
RLWNM $0, R4, $~(HID_ILOCK), R4
MOVW $(HID_ICFI|HID_ICE), R5
OR R4, R5
MOVW $HID_ICE, R3
OR R4, R3
SYNC
MOVW R5, SPR(HID0) /* Cache enable and flash invalidate */
MOVW R3, SPR(HID0) /* Cache enable */
SYNC
RETURN
#ifdef ucuconf
TEXT getpll(SB), $0
MOVW SPR(1009), R3
ISYNC
RETURN
TEXT getl2pm(SB), $0
MOVW SPR(1016), R3
RETURN
TEXT getl2cr(SB), $0
MOVW SPR(1017), R3
RETURN
TEXT putl2cr(SB), $0
MOVW R3, SPR(1017)
RETURN
TEXT dcachedis(SB), $0
SYNC
/* MOVW SPR(HID0), R4
RLWNM $0, R4, $~(HID_DCE), R4
MOVW R4, SPR(HID0) /* L1 Cache disable */
MOVW SPR(1017), R4
RLWNM $0, R4, $~(0x80000000), R4
MOVW R4, SPR(1017) /* L2 Cache disable */
SYNC
RETURN
TEXT l2disable(SB), $0
SYNC
MOVW SPR(1017), R4
RLWNM $0, R4, $~(0x80000000), R4
MOVW R4, SPR(1017) /* L2 Cache disable */
SYNC
RETURN
TEXT getbats(SB), $0
MOVW SPR(DBATU(0)), R4
MOVW R4, 0(R3)
MOVW SPR(DBATL(0)), R4
MOVW R4, 4(R3)
MOVW SPR(IBATU(0)), R4
MOVW R4, 8(R3)
MOVW SPR(IBATL(0)), R4
MOVW R4, 12(R3)
MOVW SPR(DBATU(1)), R4
MOVW R4, 16(R3)
MOVW SPR(DBATL(1)), R4
MOVW R4, 20(R3)
MOVW SPR(IBATU(1)), R4
MOVW R4, 24(R3)
MOVW SPR(IBATL(1)), R4
MOVW R4, 28(R3)
MOVW SPR(DBATU(2)), R4
MOVW R4, 32(R3)
MOVW SPR(DBATL(2)), R4
MOVW R4, 36(R3)
MOVW SPR(IBATU(2)), R4
MOVW R4, 40(R3)
MOVW SPR(IBATL(2)), R4
MOVW R4, 44(R3)
MOVW SPR(DBATU(3)), R4
MOVW R4, 48(R3)
MOVW SPR(DBATL(3)), R4
MOVW R4, 52(R3)
MOVW SPR(IBATU(3)), R4
MOVW R4, 56(R3)
MOVW SPR(IBATL(3)), R4
MOVW R4, 60(R3)
RETURN
TEXT setdbat0(SB), $0
MOVW 0(R3), R4
MOVW R4, SPR(DBATU(0))
MOVW 4(R3), R4
MOVW R4, SPR(DBATL(0))
RETURN
#endif /* ucuconf */
TEXT mmudisable(SB), $0
/* disable MMU */
MOVW LR, R4
MOVW $KZERO, R5
ANDN R5, R4
MOVW R4, SPR(SRR0) /* Stored PC for RFI instruction */
MOVW MSR, R4
MOVW $(MSR_IR|MSR_DR|MSR_RI|MSR_FP), R5
ANDN R5, R4
MOVW R4, SPR(SRR1)
MOVW SPR(HID0), R4 /* Get HID0 and clear unwanted bits */
MOVW $(HID_ICE|HID_DCE), R5
ANDN R5, R4
MOVW R4, SPR(HID0) /* Cache disable */
RFI /* resume caller with MMU off */
RETURN
TEXT kreboot(SB), $0
BL mmudisable(SB)
MOVW R3, LR
RETURN
TEXT mul64fract(SB), $0
MOVW a0+8(FP), R9
MOVW a1+4(FP), R10
MOVW b0+16(FP), R4
MOVW b1+12(FP), R5
MULLW R10, R5, R13 /* c2 = lo(a1*b1) */
MULLW R10, R4, R12 /* c1 = lo(a1*b0) */
MULHWU R10, R4, R7 /* hi(a1*b0) */
ADD R7, R13 /* c2 += hi(a1*b0) */
MULLW R9, R5, R6 /* lo(a0*b1) */
MULHWU R9, R5, R7 /* hi(a0*b1) */
ADDC R6, R12 /* c1 += lo(a0*b1) */
ADDE R7, R13 /* c2 += hi(a0*b1) + carry */
MULHWU R9, R4, R7 /* hi(a0*b0) */
ADDC R7, R12 /* c1 += hi(a0*b0) */
ADDE R0, R13 /* c2 += carry */
MOVW R12, 4(R3)
MOVW R13, 0(R3)
RETURN
|
9front/9front
| 7,968
|
sys/src/9/cycv/l.s
|
#include "mem.h"
#include "io.h"
#define PUTC(c) MOVW $(c), R0; MOVW R0, (R8)
TEXT _start(SB), $-4
MOVW $(KTZERO-KZERO), R13
MOVW $(UART_BASE), R8
/* disable watchdog */
MOVW $(RESETMGR_BASE + 4*PERMODRST), R1
MOVW (R1), R0
ORR $(3<<6), R0
MOVW R0, (R1)
/* disable L2 cache */
MOVW $0, R0
MOVW $(L2_BASE+0x100), R1
MOVW R0, (R1)
PUTC('P')
/* disable MMU and L1 caches */
MOVW $0x20c5047a, R1
MOVW $_start0-KZERO(SB), R2
MCR 15, 0, R1, C(1), C(0), 0
MOVW R2, R15
TEXT _start0(SB), $-4
DSB
ISB
PUTC('l')
/* clean up to CONFADDR */
MOVW $0, R0
MOVW R0, R1
MOVW $(CONFADDR-KZERO), R2
_clrstart:
MOVW.P R0, 4(R1)
CMP.S R1, R2
BGT _clrstart
/* clean BSS */
MOVW $edata-KZERO(SB), R1
MOVW $end-KZERO(SB), R2
_clrbss:
MOVW.P R0, 4(R1)
CMP.S R1, R2
BGT _clrbss
PUTC('a')
/* KZERO to PERIPH is mapped to 0 */
MOVW $SECSZ, R0
MOVW $(MACHL1(0)-KZERO), R4
MOVW $KZERO, R1
ADD R1>>(SECSH-2), R4, R1
MOVW $(L1SEC|L1CACHED|L1KERRW), R2
MOVW $(PERIPH-KZERO), R3
_start1:
MOVW.P R2, 4(R1)
ADD R0, R2
CMP.S R2, R3
BGE _start1
/* memory above PERIPH is mapped to itself */
MOVW $(PERIPH|L1SEC|L1DEVICE|L1NOEXEC|L1KERRW), R2
_start2:
MOVW.P R2, 4(R1)
ADD.S R0, R2
BCC _start2
PUTC('n')
MOVW $(MACH(0)-KZERO), R(Rmach)
_start3:
/* enable MMU permission checking */
MOVW $0x55555555, R0
MCR 15, 0, R0, C(3), C(0), 0
/* select page table and enable MMU */
MOVW $0, R0
MCR 15, 0, R0, C(8), C(7), 0
DSB
ORR $TTBATTR, R4, R1
MCR 15, 0, R1, C(2), C(0), 0
MOVW $0x20c5047b, R1
MOVW $_virt(SB), R2
PUTC(' ')
MCR 15, 0, R1, C(1), C(0), 0
MOVW R2, R15
TEXT _virt(SB), $-4
DSB
ISB
ADD $KZERO, R(Rmach)
MOVW R(Rmach), R13
ADD $MACHSIZE, R13
MOVW R(Rmach), R0
ADD $12, R0
BL loadsp(SB)
MOVW $vectors(SB), R1
MCR 15, 0, R1, C(12), C(0)
/* enable maths coprocessors in CPACR but disable them in FPEXC */
MRC 15, 0, R0, C(1), C(0), 2
ORR $(15<<20), R0
MCR 15, 0, R0, C(1), C(0), 2
VMRS(0xe, FPEXC, 0)
BIC $(3<<30), R0
VMSR(0xe, 0, FPEXC)
/* enable L1 cache */
MOVW $0, R0
MCR 15, 0, R0, C(7), C(5), 0
MCR 15, 0, R0, C(7), C(5), 6
BL l1dclear(SB)
MRC 15, 0, R0, C(1), C(0), 1
ORR $(1|2|1<<6), R0
MCR 15, 0, R0, C(1), C(0), 1
MRC 15, 0, R0, C(1), C(0), 0
ORR $(3<<11|1<<2), R0
MCR 15, 0, R0, C(1), C(0), 0
DSB
ISB
MOVW $UART_BASE, R8
PUTC('9')
/* kernel Mach* in TPIDRPRW */
MCR 15, 0, R(Rmach), C(13), C(0), 4
MOVW $setR12(SB), R12
MOVW $0, R(Rup)
BL main(SB)
B idlehands(SB)
BL _div(SB) /* hack to load _div */
TEXT touser(SB), $-4
CPS(CPSID)
SUB $12, R13
MOVW R0, (R13)
MOVW $0, R1
MOVW R1, 4(R13)
MOVW $(UTZERO+0x20), R1
MOVW R1, 8(R13)
MOVW CPSR, R1
BIC $(PsrMask|PsrDirq|PsrDfiq), R1
ORR $PsrMusr, R1
MOVW R1, SPSR
MOVW $(KTZERO-(15*4)), R0
MOVM.IA (R0), [R0-R12]
MOVM.IA.S (R13), [R13-R14]
ADD $8, R13
MOVM.IA.W.S (R13), [R15]
TEXT forkret(SB), $-4
MOVW (16*4)(R13), R0
MOVW R0, SPSR
MOVM.IA.W (R13), [R0-R12]
MOVM.IA.S (R13), [R13-R14]
ADD $16, R13
DSB
ISB
MOVM.IA.W.S (R13), [R15]
TEXT loadsp(SB), $0
CPS(CPSMODE | PsrMabt)
MOVW R0, R13
CPS(CPSMODE | PsrMund)
MOVW R0, R13
CPS(CPSMODE | PsrMirq)
MOVW R0, R13
CPS(CPSMODE | PsrMfiq)
MOVW R0, R13
CPS(CPSMODE | PsrMsvc)
RET
TEXT cputhex(SB), $0
MOVW R0, R7
MOVW $UART_BASE, R8
TEXT puthex(SB), $0
_p0:
MOVW 0x14(R8), R6
AND.S $(1<<5), R6
BEQ _p0
#define DIG MOVW R7>>28, R6; AND $15, R6; ADD $'0', R6; CMP $'9', R6; ADD.GT $7, R6; MOVW R6, (R8); MOVW R7<<4, R7
DIG; DIG; DIG; DIG
DIG; DIG; DIG; DIG
MOVW $13, R6
MOVW R6, (R8)
MOVW $10, R6
MOVW R6, (R8)
RET
TEXT spllo(SB), $-4
MOVW CPSR, R0
CPS(CPSIE)
RET
TEXT splhi(SB), $-4
MOVW R14, 4(R(Rmach))
MOVW CPSR, R0
CPS(CPSID)
RET
TEXT splx(SB), $-4
MOVW R14, 4(R(Rmach))
MOVW R0, R1
MOVW CPSR, R0
MOVW R1, CPSR
RET
TEXT spldone(SB), $-4
RET
TEXT islo(SB), $0
MOVW CPSR, R0
AND $(PsrDirq), R0
EOR $(PsrDirq), R0
RET
TEXT setlabel(SB), $-4
MOVW R13, 0(R0)
MOVW R14, 4(R0)
MOVW $0, R0
RET
TEXT gotolabel(SB), $-4
MOVW 0(R0), R13
MOVW 4(R0), R14
MOVW $1, R0
RET
TEXT cas(SB), $0
TEXT cmpswap(SB), $0
MOVW ov+4(FP), R1
MOVW nv+8(FP), R2
spincas:
LDREX (R0), R3
CMP.S R3, R1
BNE fail
STREX R2, (R0), R4
CMP.S $0, R4
BNE spincas
MOVW $1, R0
DMB
RET
fail:
CLREX
MOVW $0, R0
RET
TEXT tas(SB), $0
TEXT _tas(SB), $0
MOVW $0xDEADDEAD, R2
_tas1:
LDREX (R0), R1
STREX R2, (R0), R3
CMP.S $0, R3
BNE _tas1
MOVW R1, R0
DMB
RET
TEXT coherence(SB), $0
DSB
RET
TEXT idlehands(SB), $0
DSB
WFE
RET
TEXT sendevent(SB), $0
SEV
RET
TEXT ttbget(SB), $0
MRC 15, 0, R0, C(2), C(0), 0
BIC $0x7f, R0
RET
TEXT ttbput(SB), $0
ORR $TTBATTR, R0
MCR 15, 0, R0, C(2), C(0), 0
RET
TEXT flushpg(SB), $0
MCR 15, 0, R0, C(8), C(7), 3
DSB
RET
TEXT flushtlb(SB), $0
MCR 15, 0, R0, C(8), C(3), 0
DSB
RET
TEXT setasid(SB), $0
DSB /* errata */
MCR 15, 0, R0, C(13), C(0), 1
RET
TEXT getifar(SB), $0
MRC 15, 0, R0, C(6), C(0), 2
RET
TEXT getdfar(SB), $0
MRC 15, 0, R0, C(6), C(0), 0
RET
TEXT getifsr(SB), $0
MRC 15, 0, R0, C(5), C(0), 1
RET
TEXT getdfsr(SB), $0
MRC 15, 0, R0, C(5), C(0), 0
RET
TEXT setpmcr(SB), $0
MCR 15, 0, R0, C(9), C(12), 0
RET
TEXT setpmcnten(SB), $0
MCR 15, 0, R0, C(9), C(12), 1
RET
TEXT perfticks(SB), $0
MRC 15, 0, R0, C(9), C(13), 0
RET
TEXT cycles(SB), $0
MRC 15, 0, R1, C(9), C(13), 0
MOVW R1, (R0)
MOVW 24(R(Rmach)), R1
MRC 15, 0, R2, C(9), C(12), 3
AND.S $(1<<31), R2
BEQ _cycles0
MCR 15, 0, R2, C(9), C(12), 3
ADD $1, R1
MOVW R1, 24(R(Rmach))
_cycles0:
MOVW R1, 4(R0)
RET
TEXT fpinit(SB), $0
MOVW $(1<<30), R0
VMSR(0xe, 0, FPEXC)
MOVW $0, R0
VMSR(0xe, 0, FPSCR)
RET
TEXT fprestore(SB), $0
MOVM.IA.W (R0), [R1-R2]
VMSR(0xe, 1, FPEXC)
VMSR(0xe, 2, FPSCR)
WORD $0xecb00b20
WORD $0xecf00b20
RET
TEXT fpsave(SB), $0
VMRS(0xe, FPEXC, 1)
VMRS(0xe, FPSCR, 2)
MOVM.IA.W [R1-R2], (R0)
WORD $0xeca00b20
WORD $0xece00b20
/* wet floor */
TEXT fpoff(SB), $0
TEXT fpclear(SB), $0
MOVW $0, R1
VMSR(0xe, 1, FPEXC)
RET
#define Rnoway R1
#define Rwayinc R2
#define Rmaxway R3
#define Rsetinc R4
#define Rmaxset R5
TEXT l1dclear(SB), $0
MOVW $0, R0
MCR 15, 2, R0, C(0), C(0), 0
MRC 15, 1, R9, C(0), C(0), 0
AND $7, R9, R8
ADD $4, R8
MOVW $1, Rsetinc
MOVW Rsetinc<<R8, Rsetinc
MOVW R9>>13, Rmaxset
AND $0x7fff, Rmaxset
MOVW Rmaxset<<R8, Rmaxset
MOVW R9>>3, R0
AND $0x3ff, R0
MOVW $(1<<31), Rwayinc
MOVW $(1<<31), Rnoway
MOVW R0, Rmaxway
ADD $1, R0
_l1dclear0:
MOVW.S R0>>1, R0
BEQ _l1dclear1
MOVW Rwayinc>>1, Rwayinc
MOVW Rnoway->1, Rnoway
MOVW Rmaxway@>1, Rmaxway
B _l1dclear0
_l1dclear1:
MOVW Rwayinc<<1, Rwayinc
MVN Rnoway<<1, Rnoway
BIC Rnoway, Rmaxway
MOVW $0, R0
_l1dclear2:
MCR 15, 0, R0, C(7), C(14), 2
ADD Rwayinc, R0
CMP.S Rmaxway, R0
BLT _l1dclear2
AND Rnoway, R0
ADD Rsetinc, R0
CMP.S Rmaxset, R0
BLT _l1dclear2
RET
TEXT invalise(SB), $0
MOVW 4(FP), R1
ADD $(LINSIZ - 1), R1
BIC $(LINSIZ - 1), R0
BIC $(LINSIZ - 1), R1
_invalise0:
MCR 15, 0, R0, C(7), C(5), 1
ADD $LINSIZ, R0
CMP.S R1, R0
BLT _invalise0
RET
TEXT cleandse(SB), $0
DSB
MOVW 4(FP), R1
ADD $(LINSIZ - 1), R1
BIC $(LINSIZ - 1), R0
BIC $(LINSIZ - 1), R1
_cleandse0:
MCR 15, 0, R0, C(7), C(10), 1
ADD $LINSIZ, R0
CMP.S R1, R0
BLT _cleandse0
DSB
RET
TEXT invaldse(SB), $0
MOVW 4(FP), R1
ADD $(LINSIZ - 1), R1
BIC $(LINSIZ - 1), R0
BIC $(LINSIZ - 1), R1
_invaldse0:
MCR 15, 0, R0, C(7), C(6), 1
ADD $LINSIZ, R0
CMP.S R1, R0
BLT _invaldse0
DSB
RET
TEXT clinvdse(SB), $0
DSB
MOVW 4(FP), R1
ADD $(LINSIZ - 1), R1
BIC $(LINSIZ - 1), R0
BIC $(LINSIZ - 1), R1
_clinvdse0:
MCR 15, 0, R0, C(7), C(14), 1
ADD $LINSIZ, R0
CMP.S R1, R0
BLT _clinvdse0
DSB
RET
TEXT cleandln(SB), $0
DSB
MCR 15, 0, R0, C(7), C(10), 1
DSB
RET
TEXT invaldln(SB), $0
MCR 15, 0, R0, C(7), C(6), 1
DSB
RET
TEXT clinvdln(SB), $0
DSB
MCR 15, 0, R0, C(7), C(14), 1
DSB
RET
TEXT palookur(SB), $0
MCR 15, 0, R0, C(7), C(8), 2
DSB
MRC 15, 0, R0, C(7), C(4), 0
RET
|
9front/9front
| 1,623
|
sys/src/9/cycv/ltrap.s
|
#include "mem.h"
#include "io.h"
TEXT vectors(SB), $-4
MOVW $_start-KZERO(SB), R15
MOVW $_vexc(SB), R15
MOVW $_vsvc(SB), R15
MOVW $_viabt(SB), R15
MOVW $_vexc(SB), R15
MOVW $vectors(SB), R15
MOVW $_vexc(SB), R15
MOVW $_vexc(SB), R15
TEXT _viabt(SB), $-4
CPS(CPSID)
CLREX
DSB
MOVW R14, 8(R13)
MOVW SPSR, R14
MOVW R14, 4(R13)
MOVW CPSR, R14
AND $0x1e, R14
B _exc
TEXT _vexc(SB), $-4
CPS(CPSID)
CLREX
DSB
MOVW R14, 8(R13)
MOVW SPSR, R14
MOVW R14, 4(R13)
MOVW CPSR, R14
AND $0x1f, R14
_exc:
MOVW R14, 0(R13)
CPS(CPSMODE | PsrMsvc)
SUB $(18*4), R13
MOVM.IA [R0-R14], (R13)
/* get Mach* from TPIDRPRW */
MRC 15, 0, R(Rmach), C(13), C(0), 4
MOVW 8(R(Rmach)), R(Rup)
MOVW $setR12(SB), R12
ADD $12, R(Rmach), R0
MOVM.IA (R0), [R1-R3]
ADD $(15*4), R13, R0
MOVM.IA [R1-R3], (R0)
AND.S $0xf, R2
ADD.NE $(18*4), R13, R0
MOVW.NE R0, (13*4)(R13)
ADD.EQ $(13*4), R13, R0
MOVM.IA.S.EQ [R13-R14], (R0)
MOVW R13, R0
SUB $8, R13
BL trap(SB)
ADD $8, R13
MOVW (16*4)(R13), R0
MOVW R0, SPSR
AND.S $0xf, R0
BEQ _uret
MOVW R(Rmach), (Rmach*4)(R13)
MOVM.IA (R13), [R0-R14]
DSB
MOVM.DB.S (R13), [R15]
TEXT _vsvc(SB), $-4
CLREX
DSB
MOVW.W R14, -4(R13)
MOVW SPSR, R14
MOVW.W R14, -4(R13)
MOVW $PsrMsvc, R14
MOVW.W R14, -4(R13)
MOVM.DB.S [R0-R14], (R13)
SUB $(15*4), R13
/* get Mach* from TPIDRPRW */
MRC 15, 0, R(Rmach), C(13), C(0), 4
MOVW 8(R(Rmach)), R(Rup)
MOVW $setR12(SB), R12
MOVW R13, R0
SUB $8, R13
BL syscall(SB)
ADD $8, R13
MOVW (16*4)(R13), R0
MOVW R0, SPSR
_uret:
MOVM.IA.S (R13), [R0-R14]
ADD $(17*4), R13
DSB
ISB
MOVM.IA.S.W (R13), [R15]
|
9front/9front
| 13,674
|
sys/src/9/arm64/l.s
|
#include "mem.h"
#include "sysreg.h"
#undef SYSREG
#define SYSREG(op0,op1,Cn,Cm,op2) SPR(((op0)<<19|(op1)<<16|(Cn)<<12|(Cm)<<8|(op2)<<5))
TEXT _start(SB), 1, $-4
MOV R0, R26 /* save */
MOV $setSB-KZERO(SB), R28
BL svcmode<>(SB)
/* use dedicated stack pointer per exception level */
MOVWU $1, R1
MSR R1, SPSel
BL mmudisable<>(SB)
/* invalidate local caches */
BL cachedwbinv(SB)
BL l2cacheuwbinv(SB)
BL cacheiinv(SB)
MOV $(MACHADDR(0)-KZERO), R27
MRS MPIDR_EL1, R1
ANDW $(MAXMACH-1), R1
MOVWU $MACHSIZE, R2
MULW R1, R2, R2
SUB R2, R27
ADD $(MACHSIZE-16), R27, R2
MOV R2, SP
CBNZ R1, _startup
/* clear page table and machs */
MOV $(L1BOT-KZERO), R1
MOV $(MACHADDR(-1)-KZERO), R2
_zerol1:
MOV ZR, (R1)8!
CMP R1, R2
BNE _zerol1
/* clear BSS */
MOV $edata-KZERO(SB), R1
MOV $end-KZERO(SB), R2
_zerobss:
MOV ZR, (R1)8!
CMP R1, R2
BNE _zerobss
/* setup page tables */
MOV $(L1BOT-KZERO), R0
BL mmuidmap(SB)
MOV $(L1-KZERO), R0
BL mmu0init(SB)
SEVL
_startup:
WFE
BL mmuenable<>(SB)
MOV R26, R0
MOV $0, R26
ORR $KZERO, R27
MSR R27, TPIDR_EL1
MOV $setSB(SB), R28
BL main(SB)
TEXT stop<>(SB), 1, $-4
_stop:
WFE
B _stop
TEXT aaa<>(SB), 1, $-4
xxx:
MOV $(0x860040+VIRTIO), R1
MOVW $'A', R2
MOVW R2, (R1)
B xxx
TEXT sev(SB), 1, $-4
SEV
WFE
RETURN
TEXT svcmode<>(SB), 1, $-4
MSR $0xF, DAIFSet
MRS CurrentEL, R0
ANDW $(3<<2), R0
CMPW $(1<<2), R0
BEQ el1
CMPW $(2<<2), R0
BEQ el2
B stop<>(SB)
el2:
MOV $0, R0
MSR R0, MDCR_EL2
ISB $SY
/* set virtual timer offset to zero */
MOV $0, R0
MSR R0, CNTVOFF_EL2
/* HCR = RW, HCD, SWIO, BSU, FB */
MOVWU $(1<<31 | 1<<29 | 1<<2 | 0<<10 | 0<<9), R0
MSR R0, HCR_EL2
ISB $SY
/* SCTLR = RES1 */
MOVWU $(3<<4 | 1<<11 | 1<<16 | 1<<18 | 3<<22 | 3<<28), R0
ISB $SY
MSR R0, SCTLR_EL2
ISB $SY
/* set VMID to zero */
MOV $0, R0
MSR R0, VTTBR_EL2
ISB $SY
MOVWU $(0xF<<6 | 4), R0
MSR R0, SPSR_EL2
MSR LR, ELR_EL2
ERET
el1:
RETURN
TEXT mmudisable<>(SB), 1, $-4
#define SCTLRCLR \
/* RES0 */ ( 3<<30 \
/* RES0 */ | 1<<27 \
/* UCI */ | 1<<26 \
/* EE */ | 1<<25 \
/* RES0 */ | 1<<21 \
/* E0E */ | 1<<24 \
/* WXN */ | 1<<19 \
/* nTWE */ | 1<<18 \
/* RES0 */ | 1<<17 \
/* nTWI */ | 1<<16 \
/* UCT */ | 1<<15 \
/* DZE */ | 1<<14 \
/* RES0 */ | 1<<13 \
/* RES0 */ | 1<<10 \
/* UMA */ | 1<<9 \
/* SA0 */ | 1<<4 \
/* SA */ | 1<<3 \
/* A */ | 1<<1 )
#define SCTLRSET \
/* RES1 */ ( 3<<28 \
/* RES1 */ | 3<<22 \
/* RES1 */ | 1<<20 \
/* RES1 */ | 1<<11 )
#define SCTLRMMU \
/* I */ ( 1<<12 \
/* C */ | 1<<2 \
/* M */ | 1<<0 )
/* initialise SCTLR, MMU and caches off */
ISB $SY
MRS SCTLR_EL1, R0
BIC $(SCTLRCLR | SCTLRMMU), R0
ORR $SCTLRSET, R0
ISB $SY
MSR R0, SCTLR_EL1
ISB $SY
B flushlocaltlb(SB)
TEXT mmuenable<>(SB), 1, $-4
/* return to virtual */
ORR $KZERO, LR
MOV LR, -16(RSP)!
BL flushlocaltlb(SB)
/* memory attributes */
#define MAIRINIT \
( 0xFF << MA_MEM_WB*8 \
| 0x33 << MA_MEM_WT*8 \
| 0x44 << MA_MEM_UC*8 \
| 0x00 << MA_DEV_nGnRnE*8 \
| 0x04 << MA_DEV_nGnRE*8 \
| 0x08 << MA_DEV_nGRE*8 \
| 0x0C << MA_DEV_GRE*8 )
MOV $MAIRINIT, R1
MSR R1, MAIR_EL1
ISB $SY
/* translation control */
#define TCRINIT \
/* TBI1 */ ( 0<<38 \
/* TBI0 */ | 0<<37 \
/* AS */ | 0<<36 \
/* TG1 */ | (((3<<16|1<<14|2<<12)>>PGSHIFT)&3)<<30 \
/* SH1 */ | SHARE_INNER<<28 \
/* ORGN1 */ | CACHE_WB<<26 \
/* IRGN1 */ | CACHE_WB<<24 \
/* EPD1 */ | 0<<23 \
/* A1 */ | 0<<22 \
/* T1SZ */ | (64-EVASHIFT)<<16 \
/* TG0 */ | (((1<<16|2<<14|0<<12)>>PGSHIFT)&3)<<14 \
/* SH0 */ | SHARE_INNER<<12 \
/* ORGN0 */ | CACHE_WB<<10 \
/* IRGN0 */ | CACHE_WB<<8 \
/* EPD0 */ | 0<<7 \
/* T0SZ */ | (64-EVASHIFT)<<0 )
MOV $TCRINIT, R1
MRS ID_AA64MMFR0_EL1, R2
ANDW $0x7, R2 // PARange
ADD R2<<32, R1 // IPS
MSR R1, TCR_EL1
ISB $SY
/* load the page tables */
MOV $(L1BOT-KZERO), R0
MOV $(L1TOP-KZERO), R1
ISB $SY
MSR R0, TTBR0_EL1
MSR R1, TTBR1_EL1
ISB $SY
/* enable MMU and caches */
MRS SCTLR_EL1, R1
ORR $SCTLRMMU, R1
ISB $SY
MSR R1, SCTLR_EL1
ISB $SY
MOV RSP, R1
ORR $KZERO, R1
MOV R1, RSP
MOV (RSP)16!, LR
B cacheiinv(SB)
TEXT touser(SB), 1, $-4
MOVWU $0x10028, R1 // entry
MOVWU $0, R2 // psr
MSR R0, SP_EL0 // sp
MSR R1, ELR_EL1
MSR R2, SPSR_EL1
ERET
TEXT cas(SB), 1, $-4
TEXT cmpswap(SB), 1, $-4
MOVWU ov+8(FP), R1
MOVWU nv+16(FP), R2
_cas1:
LDXRW (R0), R3
CMP R3, R1
BNE _cas0
STXRW R2, (R0), R4
CBNZ R4, _cas1
MOVW $1, R0
DMB $ISH
RETURN
_cas0:
CLREX
MOVW $0, R0
RETURN
TEXT tas(SB), 1, $-4
TEXT _tas(SB), 1, $-4
MOVW $0xdeaddead, R2
_tas1:
LDXRW (R0), R1
STXRW R2, (R0), R3
CBNZ R3, _tas1
MOVW R1, R0
TEXT coherence(SB), 1, $-4
DMB $ISH
RETURN
TEXT islo(SB), 1, $-4
MRS DAIF, R0
AND $(0x2<<6), R0
EOR $(0x2<<6), R0
RETURN
TEXT splhi(SB), 1, $-4
MRS DAIF, R0
MSR $0x2, DAIFSet
RETURN
TEXT splfhi(SB), 1, $-4
MRS DAIF, R0
MSR $0x3, DAIFSet
RETURN
TEXT spllo(SB), 1, $-4
MSR $0x3, DAIFClr
RETURN
TEXT splflo(SB), 1, $-4
MSR $0x1, DAIFClr
RETURN
TEXT splx(SB), 1, $-4
MSR R0, DAIF
RETURN
TEXT idlehands(SB), 1, $-4
DMB $ISH
MOVW nrdy(SB), R0
CBNZ R0, _ready
WFI
_ready:
RETURN
TEXT vcycles(SB), 1, $-4
MRS CNTVCT_EL0, R0
RETURN
TEXT lcycles(SB), 1, $-4
MRS PMCCNTR_EL0, R0
RETURN
TEXT setlabel(SB), 1, $-4
MOV LR, 8(R0)
MOV SP, R1
MOV R1, 0(R0)
MOVW $0, R0
RETURN
TEXT gotolabel(SB), 1, $-4
MOV 8(R0), LR /* link */
MOV 0(R0), R1 /* sp */
MOV R1, SP
MOVW $1, R0
RETURN
TEXT returnto(SB), 1, $-4
MOV R0, 0(SP)
RETURN
TEXT getfar(SB), 1, $-4
MRS FAR_EL1, R0
RETURN
TEXT setttbr(SB), 1, $-4
DSB $ISHST
MSR R0, TTBR0_EL1
DSB $ISH
ISB $SY
RETURN
/*
* TLB maintenance operations.
* these broadcast to all cpu's in the cluser
* (inner sharable domain).
*/
TEXT flushasidva(SB), 1, $-4
TEXT tlbivae1is(SB), 1, $-4
DSB $ISHST
TLBI R0, 0,8,3,1 /* VAE1IS */
DSB $ISH
ISB $SY
RETURN
TEXT flushasidvall(SB), 1, $-4
TEXT tlbivale1is(SB), 1, $-4
DSB $ISHST
TLBI R0, 0,8,3,5 /* VALE1IS */
DSB $ISH
ISB $SY
RETURN
TEXT flushasid(SB), 1, $-4
TEXT tlbiaside1is(SB), 1, $-4
DSB $ISHST
TLBI R0, 0,8,3,2 /* ASIDE1IS */
DSB $ISH
ISB $SY
RETURN
TEXT flushtlb(SB), 1, $-4
TEXT tlbivmalle1is(SB), 1, $-4
DSB $ISHST
TLBI R0, 0,8,3,0 /* VMALLE1IS */
DSB $ISH
ISB $SY
RETURN
/*
* flush the tlb of this cpu. no broadcast.
*/
TEXT flushlocaltlb(SB), 1, $-4
TEXT tlbivmalle1(SB), 1, $-4
DSB $NSHST
TLBI R0, 0,8,7,0 /* VMALLE1 */
DSB $NSH
ISB $SY
RETURN
/*
* floating-point support.
*/
TEXT fpon(SB), 1, $-4
MOVW $(3<<20), R0
MSR R0, CPACR_EL1
ISB $SY
RETURN
TEXT fpoff(SB), 1, $-4
MOVW $(0<<20), R0
MSR R0, CPACR_EL1
ISB $SY
RETURN
TEXT fpsaveregs(SB), 1, $-4
WORD $(1<<30 | 3 << 26 | 2<<22 | 0x1F<<16 | 3<<10 | 0<<5 | 0) /* MOV { V0, V1, V2, V3 }, (R0)64! */
WORD $(1<<30 | 3 << 26 | 2<<22 | 0x1F<<16 | 3<<10 | 0<<5 | 4) /* MOV { V4, V5, V6, V7 }, (R0)64! */
WORD $(1<<30 | 3 << 26 | 2<<22 | 0x1F<<16 | 3<<10 | 0<<5 | 8) /* MOV { V8, V9, V10,V11 }, (R0)64! */
WORD $(1<<30 | 3 << 26 | 2<<22 | 0x1F<<16 | 3<<10 | 0<<5 | 12) /* MOV { V12,V13,V14,V15 }, (R0)64! */
WORD $(1<<30 | 3 << 26 | 2<<22 | 0x1F<<16 | 3<<10 | 0<<5 | 16) /* MOV { V16,V17,V18,V19 }, (R0)64! */
WORD $(1<<30 | 3 << 26 | 2<<22 | 0x1F<<16 | 3<<10 | 0<<5 | 20) /* MOV { V20,V21,V22,V23 }, (R0)64! */
WORD $(1<<30 | 3 << 26 | 2<<22 | 0x1F<<16 | 3<<10 | 0<<5 | 24) /* MOV { V24,V25,V26,V27 }, (R0)64! */
WORD $(1<<30 | 3 << 26 | 2<<22 | 0x1F<<16 | 3<<10 | 0<<5 | 28) /* MOV { V28,V29,V30,V31 }, (R0)64! */
RETURN
TEXT fploadregs(SB), 1, $-4
WORD $(1<<30 | 3 << 26 | 3<<22 | 0x1F<<16 | 3<<10 | 0<<5 | 0) /* MOV (R0)64!, { V0, V1, V2, V3 } */
WORD $(1<<30 | 3 << 26 | 3<<22 | 0x1F<<16 | 3<<10 | 0<<5 | 4) /* MOV (R0)64!, { V4, V5, V6, V7 } */
WORD $(1<<30 | 3 << 26 | 3<<22 | 0x1F<<16 | 3<<10 | 0<<5 | 8) /* MOV (R0)64!, { V8, V9, V10,V11 } */
WORD $(1<<30 | 3 << 26 | 3<<22 | 0x1F<<16 | 3<<10 | 0<<5 | 12) /* MOV (R0)64!, { V12,V13,V14,V15 } */
WORD $(1<<30 | 3 << 26 | 3<<22 | 0x1F<<16 | 3<<10 | 0<<5 | 16) /* MOV (R0)64!, { V16,V17,V18,V19 } */
WORD $(1<<30 | 3 << 26 | 3<<22 | 0x1F<<16 | 3<<10 | 0<<5 | 20) /* MOV (R0)64!, { V20,V21,V22,V23 } */
WORD $(1<<30 | 3 << 26 | 3<<22 | 0x1F<<16 | 3<<10 | 0<<5 | 24) /* MOV (R0)64!, { V24,V25,V26,V27 } */
WORD $(1<<30 | 3 << 26 | 3<<22 | 0x1F<<16 | 3<<10 | 0<<5 | 28) /* MOV (R0)64!, { V28,V29,V30,V31 } */
RETURN
// syscall or trap from EL0
TEXT vsys0(SB), 1, $-4
LSRW $26, R0, R17 // ec
CMPW $0x15, R17 // SVC trap?
BNE _itsatrap // nope.
MOVP R26, R27, 224(RSP)
MOVP R28, R29, 240(RSP)
MRS SP_EL0, R1
MRS ELR_EL1, R2
MRS SPSR_EL1, R3
MOV R0, 288(RSP) // type
MOV R1, 264(RSP) // sp
MOV R2, 272(RSP) // pc
MOV R3, 280(RSP) // psr
MOV $setSB(SB), R28
MRS TPIDR_EL1, R27
MOV 16(R27), R26
ADD $16, RSP, R0 // ureg
BL syscall(SB)
TEXT forkret(SB), 1, $-4
MSR $0x3, DAIFSet // interrupts off
ADD $16, RSP, R0 // ureg
MOV 16(RSP), R0 // ret
MOV 264(RSP), R1 // sp
MOV 272(RSP), R2 // pc
MOV 280(RSP), R3 // psr
MSR R1, SP_EL0
MSR R2, ELR_EL1
MSR R3, SPSR_EL1
MOVP 224(RSP), R26, R27
MOVP 240(RSP), R28, R29
MOV 256(RSP), R30 // link
ADD $TRAPFRAMESIZE, RSP
ERET
TEXT itsatrap<>(SB), 1, $-4
_itsatrap:
MOVP R1, R2, 24(RSP)
MOVP R3, R4, 40(RSP)
MOVP R5, R6, 56(RSP)
MOVP R7, R8, 72(RSP)
MOVP R9, R10, 88(RSP)
MOVP R11, R12, 104(RSP)
MOVP R13, R14, 120(RSP)
MOVP R15, R16, 136(RSP)
MOVP R18, R19, 160(RSP)
MOVP R20, R21, 176(RSP)
MOVP R22, R23, 192(RSP)
MOVP R24, R25, 208(RSP)
// trap/irq/fiq/serr from EL0
TEXT vtrap0(SB), 1, $-4
MOVP R26, R27, 224(RSP)
MOVP R28, R29, 240(RSP)
MRS SP_EL0, R1
MRS ELR_EL1, R2
MRS SPSR_EL1, R3
MOV R0, 288(RSP) // type
MOV R1, 264(RSP) // sp
MOV R2, 272(RSP) // pc
MOV R3, 280(RSP) // psr
MOV $setSB(SB), R28
MRS TPIDR_EL1, R27
MOV 16(R27), R26
ADD $16, RSP, R0 // ureg
BL trap(SB)
TEXT noteret(SB), 1, $-4
MSR $0x3, DAIFSet // interrupts off
ADD $16, RSP, R0 // ureg
MOV 264(RSP), R1 // sp
MOV 272(RSP), R2 // pc
MOV 280(RSP), R3 // psr
MSR R1, SP_EL0
MSR R2, ELR_EL1
MSR R3, SPSR_EL1
MOVP 224(RSP), R26, R27
MOVP 240(RSP), R28, R29
_intrreturn:
MOVP 16(RSP), R0, R1
MOVP 32(RSP), R2, R3
MOVP 48(RSP), R4, R5
MOVP 64(RSP), R6, R7
MOVP 80(RSP), R8, R9
MOVP 96(RSP), R10, R11
MOVP 112(RSP), R12, R13
MOVP 128(RSP), R14, R15
MOVP 144(RSP), R16, R17
MOVP 160(RSP), R18, R19
MOVP 176(RSP), R20, R21
MOVP 192(RSP), R22, R23
MOVP 208(RSP), R24, R25
MOV 256(RSP), R30 // link
ADD $TRAPFRAMESIZE, RSP
ERET
// irq/fiq/trap/serr from EL1
TEXT vtrap1(SB), 1, $-4
MOV R29, 248(RSP) // special
ADD $TRAPFRAMESIZE, RSP, R1
MRS ELR_EL1, R2
MRS SPSR_EL1, R3
MOV R0, 288(RSP) // type
MOV R1, 264(RSP) // sp
MOV R2, 272(RSP) // pc
MOV R3, 280(RSP) // psr
ADD $16, RSP, R0 // ureg
BL trap(SB)
MSR $0x3, DAIFSet // interrupts off
MOV 272(RSP), R2 // pc
MOV 280(RSP), R3 // psr
MSR R2, ELR_EL1
MSR R3, SPSR_EL1
MOV 248(RSP), R29 // special
B _intrreturn
// vector tables
TEXT vsys(SB), 1, $-4
SUB $TRAPFRAMESIZE, RSP
MOV R0, 16(RSP)
MOV R30, 256(RSP) // link
MOV R17, 152(RSP) // temp
MRS ESR_EL1, R0 // type
_vsyspatch:
B _vsyspatch // branch to vsys0() patched in
TEXT vtrap(SB), 1, $-4
SUB $TRAPFRAMESIZE, RSP
MOVP R0, R1, 16(RSP)
MOVP R2, R3, 32(RSP)
MOVP R4, R5, 48(RSP)
MOVP R6, R7, 64(RSP)
MOVP R8, R9, 80(RSP)
MOVP R10, R11, 96(RSP)
MOVP R12, R13, 112(RSP)
MOVP R14, R15, 128(RSP)
MOVP R16, R17, 144(RSP)
MOVP R18, R19, 160(RSP)
MOVP R20, R21, 176(RSP)
MOVP R22, R23, 192(RSP)
MOVP R24, R25, 208(RSP)
MOV R30, 256(RSP) // link
MRS ESR_EL1, R0 // type
_vtrappatch:
B _vtrappatch // branch to vtrapX() patched in
TEXT virq(SB), 1, $-4
SUB $TRAPFRAMESIZE, RSP
MOVP R0, R1, 16(RSP)
MOVP R2, R3, 32(RSP)
MOVP R4, R5, 48(RSP)
MOVP R6, R7, 64(RSP)
MOVP R8, R9, 80(RSP)
MOVP R10, R11, 96(RSP)
MOVP R12, R13, 112(RSP)
MOVP R14, R15, 128(RSP)
MOVP R16, R17, 144(RSP)
MOVP R18, R19, 160(RSP)
MOVP R20, R21, 176(RSP)
MOVP R22, R23, 192(RSP)
MOVP R24, R25, 208(RSP)
MOV R30, 256(RSP) // link
MOV $(1<<32), R0 // type irq
_virqpatch:
B _virqpatch // branch to vtrapX() patched in
TEXT vfiq(SB), 1, $-4
SUB $TRAPFRAMESIZE, RSP
MOVP R0, R1, 16(RSP)
MOVP R2, R3, 32(RSP)
MOVP R4, R5, 48(RSP)
MOVP R6, R7, 64(RSP)
MOVP R8, R9, 80(RSP)
MOVP R10, R11, 96(RSP)
MOVP R12, R13, 112(RSP)
MOVP R14, R15, 128(RSP)
MOVP R16, R17, 144(RSP)
MOVP R18, R19, 160(RSP)
MOVP R20, R21, 176(RSP)
MOVP R22, R23, 192(RSP)
MOVP R24, R25, 208(RSP)
MOV R30, 256(RSP) // link
MOV $(2<<32), R0 // type fiq
_vfiqpatch:
B _vfiqpatch // branch to vtrapX() patched in
TEXT vserr(SB), 1, $-4
SUB $TRAPFRAMESIZE, RSP
MOVP R0, R1, 16(RSP)
MOVP R2, R3, 32(RSP)
MOVP R4, R5, 48(RSP)
MOVP R6, R7, 64(RSP)
MOVP R8, R9, 80(RSP)
MOVP R10, R11, 96(RSP)
MOVP R12, R13, 112(RSP)
MOVP R14, R15, 128(RSP)
MOVP R16, R17, 144(RSP)
MOVP R18, R19, 160(RSP)
MOVP R20, R21, 176(RSP)
MOVP R22, R23, 192(RSP)
MOVP R24, R25, 208(RSP)
MOV R30, 256(RSP) // link
MRS ESR_EL1, R0
ORR $(3<<32), R0 // type
_vserrpatch:
B _vserrpatch // branch to vtrapX() patched in
/* fault-proof memcpy */
TEXT peek(SB), 1, $-4
MOV R0, R1
MOV dst+8(FP), R2
MOVWU len+16(FP), R0
TEXT _peekinst(SB), 1, $-4
_peekloop:
MOVBU (R1)1!, R3
MOVBU R3, (R2)1!
SUBS $1, R0
BNE _peekloop
RETURN
TEXT hvccall(SB), 1, $32
/* save extern registers */
MOVP R26, R27, (RSP)
/* R0 = Ureg */
MOV R0, R8
/* save ureg pointer */
MOV R8, 16(RSP)
MOVP 0(R8), R0, R1
MOVP 16(R8), R2, R3
MOVP 32(R8), R4, R5
MOVP 48(R8), R6, R7
HVC
/* restore ureg pointer */
MOV 16(RSP), R8
MOVP R0, R1, 0(R8)
MOVP R2, R3, 16(R8)
/* restore extern registers */
MOVP (RSP), R26, R27
RETURN
|
9front/9front
| 3,232
|
sys/src/9/arm64/cache.v8.s
|
#include "../arm64/sysreg.h"
#undef SYSREG
#define SYSREG(op0,op1,Cn,Cm,op2) SPR(((op0)<<19|(op1)<<16|(Cn)<<12|(Cm)<<8|(op2)<<5))
/*
* instruction cache operations
*/
TEXT cacheiinvse(SB), 1, $-4
MOVWU len+8(FP), R2
ADD R0, R2
MRS DAIF, R11
MSR $0x2, DAIFSet
MOVWU $1, R10
MSR R10, CSSELR_EL1
ISB $SY
MRS CCSIDR_EL1, R4
ANDW $7, R4
ADDW $4, R4 // log2(linelen)
LSL R4, R10
LSR R4, R0
LSL R4, R0
_iinvse:
IC R0, 3,7,5,1 // IVAU
ADD R10, R0
CMP R0, R2
BGT _iinvse
DSB $NSH
ISB $SY
MSR R11, DAIF
RETURN
TEXT cacheiinv(SB), 1, $-4
IC R0, 0,7,5,0 // IALLU
DSB $NSH
ISB $SY
RETURN
TEXT cacheuwbinv(SB), 1, $0
BL cachedwbinv(SB)
BL cacheiinv(SB)
RETURN
/*
* data cache operations
*/
TEXT cachedwbse(SB), 1, $-4
MOV LR, R29
BL cachedva<>(SB)
TEXT dccvac(SB), 1, $-4
DC R0, 3,7,10,1 // CVAC
RETURN
TEXT cacheduwbse(SB), 1, $-4
MOV LR, R29
BL cachedva<>(SB)
TEXT dccvau(SB), 1, $-4
DC R0, 3,7,11,1 // CVAU
RETURN
TEXT cachedinvse(SB), 1, $-4
MOV LR, R29
BL cachedva<>(SB)
TEXT dcivac(SB), 1, $-4
DC R0, 0,7,6,1 // IVAC
RETURN
TEXT cachedwbinvse(SB), 1, $-4
MOV LR, R29
BL cachedva<>(SB)
TEXT dccivac(SB), 1, $-4
DC R0, 3,7,14,1 // CIVAC
RETURN
TEXT cachedva<>(SB), 1, $-4
MOV LR, R1
MOVWU len+8(FP), R2
ADD R0, R2
MRS DAIF, R11
MSR $0x2, DAIFSet
MOVWU $0, R10
MSR R10, CSSELR_EL1
ISB $SY
MRS CCSIDR_EL1, R4
ANDW $7, R4
ADDW $4, R4 // log2(linelen)
MOVWU $1, R10
LSL R4, R10
LSR R4, R0
LSL R4, R0
DSB $SY
ISB $SY
_cachedva:
BL (R1)
ADD R10, R0
CMP R0, R2
BGT _cachedva
DSB $SY
ISB $SY
MSR R11, DAIF
RET R29
/*
* l1 cache operations
*/
TEXT cachedwb(SB), 1, $-4
MOVWU $0, R0
_cachedwb:
MOV LR, R29
BL cachedsw<>(SB)
TEXT dccsw(SB), 1, $-4
DC R0, 0,7,10,2 // CSW
RETURN
TEXT cachedinv(SB), 1, $-4
MOVWU $0, R0
_cachedinv:
MOV LR, R29
BL cachedsw<>(SB)
TEXT dcisw(SB), 1, $-4
DC R0, 0,7,6,2 // ISW
RETURN
TEXT cachedwbinv(SB), 1, $-4
MOVWU $0, R0
_cachedwbinv:
MOV LR, R29
BL cachedsw<>(SB)
TEXT dccisw(SB), 1, $-4
DC R0, 0,7,14,2 // CISW
RETURN
/*
* l2 cache operations
*/
TEXT l2cacheuwb(SB), 1, $-4
MOVWU $1, R0
B _cachedwb
TEXT l2cacheuinv(SB), 1, $-4
MOVWU $1, R0
B _cachedinv
TEXT l2cacheuwbinv(SB), 1, $-4
MOVWU $1, R0
B _cachedwbinv
TEXT cachesize(SB), 1, $-4
MRS DAIF, R11
MSR $0x2, DAIFSet
MSR R0, CSSELR_EL1
ISB $SY
MRS CCSIDR_EL1, R0
MSR R11, DAIF
RETURN
TEXT cachedsw<>(SB), 1, $-4
MOV LR, R1
MRS DAIF, R11
MSR $0x2, DAIFSet
ADDW R0, R0, R8
MSR R8, CSSELR_EL1
ISB $SY
MRS CCSIDR_EL1, R4
LSR $3, R4, R7
ANDW $1023, R7 // lastway
ADDW $1, R7, R5 // #ways
LSR $13, R4, R2
ANDW $32767, R2 // lastset
ADDW $1, R2 // #sets
ANDW $7, R4
ADDW $4, R4 // log2(linelen)
MOVWU $32, R3 // wayshift = 32 - log2(#ways)
_countlog2ways:
CBZ R7, _loop // lastway == 0?
LSR $1, R7 // lastway >>= 1
SUB $1, R3 // wayshift--
B _countlog2ways
_loop:
DSB $SY
ISB $SY
_nextway:
MOVWU $0, R6 // set
_nextset:
LSL R3, R7, R0 // way<<wayshift
LSL R4, R6, R9 // set<<log2(linelen)
ORRW R8, R0 // level
ORRW R9, R0 // setway
BL (R1) // op(setway)
ADDW $1, R6 // set++
CMPW R2, R6
BLT _nextset
ADDW $1, R7 // way++
CMPW R5, R7
BLT _nextway
DSB $SY
ISB $SY
MSR R11, DAIF
RET R29
|
9front/9front
| 10,597
|
sys/src/9/mtx/l.s
|
#include "mem.h"
/* use of SPRG registers in save/restore */
#define SAVER0 SPRG0
#define SAVER1 SPRG1
#define SAVELR SPRG2
#define SAVEXX SPRG3
/* special instruction definitions */
#define BDNZ BC 16,0,
#define BDNE BC 0,2,
#define TLBIA WORD $((31<<26)|(307<<1))
#define TLBSYNC WORD $((31<<26)|(566<<1))
/* on some models mtmsr doesn't synchronise enough (eg, 603e) */
#define MSRSYNC SYNC; ISYNC
#define UREGSPACE (UREGSIZE+8)
TEXT start(SB), $-4
/*
* setup MSR
* turn off interrupts
* use 0x000 as exception prefix
* enable machine check
*/
MOVW MSR, R3
MOVW $(MSR_EE|MSR_IP), R4
ANDN R4, R3
OR $(MSR_ME), R3
ISYNC
MOVW R3, MSR
MSRSYNC
/* except during trap handling, R0 is zero from now on */
MOVW $0, R0
/* setup SB for pre mmu */
MOVW $setSB(SB), R2
MOVW $KZERO, R3
ANDN R3, R2
BL mmuinit0(SB)
/* running with MMU on!! */
/* set R2 to correct value */
MOVW $setSB(SB), R2
/* debugger sets R1 to top of usable memory +1 */
MOVW R1, memsize(SB)
BL kfpinit(SB)
/* set up Mach */
MOVW $mach0(SB), R(MACH)
ADD $(MACHSIZE-8), R(MACH), R1 /* set stack */
MOVW R0, R(USER)
MOVW R0, 0(R(MACH))
BL main(SB)
RETURN /* not reached */
GLOBL mach0(SB), $(MAXMACH*BY2PG)
GLOBL memsize(SB), $4
/*
* on return from this function we will be running in virtual mode.
* We set up the Block Address Translation (BAT) registers thus:
* 1) first 3 BATs are 256M blocks, starting from KZERO->0
* 2) remaining BAT maps last 256M directly
*/
TEXT mmuinit0(SB), $0
/* reset all the tlbs */
MOVW $64, R3
MOVW R3, CTR
MOVW $0, R4
tlbloop:
TLBIE R4
ADD $BIT(19), R4
BDNZ tlbloop
TLBSYNC
/* KZERO -> 0 */
MOVW $(KZERO|(0x7ff<<2)|2), R3
MOVW $(PTEVALID|PTEWRITE), R4
MOVW R3, SPR(IBATU(0))
MOVW R4, SPR(IBATL(0))
MOVW R3, SPR(DBATU(0))
MOVW R4, SPR(DBATL(0))
/* KZERO+256M -> 256M */
ADD $(1<<28), R3
ADD $(1<<28), R4
MOVW R3, SPR(IBATU(1))
MOVW R4, SPR(IBATL(1))
MOVW R3, SPR(DBATU(1))
MOVW R4, SPR(DBATL(1))
/* KZERO+512M -> 512M */
ADD $(1<<28), R3
ADD $(1<<28), R4
MOVW R3, SPR(IBATU(2))
MOVW R4, SPR(IBATL(2))
MOVW R3, SPR(DBATU(2))
MOVW R4, SPR(DBATL(2))
/* direct map last block, uncached, (?guarded) */
MOVW $((0xf<<28)|(0x7ff<<2)|2), R3
MOVW $((0xf<<28)|PTE1_I|PTE1_G|PTE1_RW), R4
MOVW R3, SPR(DBATU(3))
MOVW R4, SPR(DBATL(3))
/* IBAT 3 unused */
MOVW R0, SPR(IBATU(3))
MOVW R0, SPR(IBATL(3))
/* enable MMU */
MOVW LR, R3
OR $KZERO, R3
MOVW R3, SPR(SRR0)
MOVW MSR, R4
OR $(MSR_IR|MSR_DR), R4
MOVW R4, SPR(SRR1)
RFI /* resume in kernel mode in caller */
RETURN
TEXT kfpinit(SB), $0
MOVFL $0,FPSCR(7)
MOVFL $0xD,FPSCR(6) /* VE, OE, ZE */
MOVFL $0, FPSCR(5)
MOVFL $0, FPSCR(3)
MOVFL $0, FPSCR(2)
MOVFL $0, FPSCR(1)
MOVFL $0, FPSCR(0)
FMOVD $4503601774854144.0, F27
FMOVD $0.5, F29
FSUB F29, F29, F28
FADD F29, F29, F30
FADD F30, F30, F31
FMOVD F28, F0
FMOVD F28, F1
FMOVD F28, F2
FMOVD F28, F3
FMOVD F28, F4
FMOVD F28, F5
FMOVD F28, F6
FMOVD F28, F7
FMOVD F28, F8
FMOVD F28, F9
FMOVD F28, F10
FMOVD F28, F11
FMOVD F28, F12
FMOVD F28, F13
FMOVD F28, F14
FMOVD F28, F15
FMOVD F28, F16
FMOVD F28, F17
FMOVD F28, F18
FMOVD F28, F19
FMOVD F28, F20
FMOVD F28, F21
FMOVD F28, F22
FMOVD F28, F23
FMOVD F28, F24
FMOVD F28, F25
FMOVD F28, F26
RETURN
TEXT splhi(SB), $0
MOVW LR, R31
MOVW R31, 4(R(MACH)) /* save PC in m->splpc */
MOVW MSR, R3
RLWNM $0, R3, $~MSR_EE, R4
SYNC
MOVW R4, MSR
MSRSYNC
RETURN
TEXT splx(SB), $0
/* fall though */
TEXT splxpc(SB), $0
MOVW LR, R31
MOVW R31, 4(R(MACH)) /* save PC in m->splpc */
MOVW MSR, R4
RLWMI $0, R3, $MSR_EE, R4
SYNC
MOVW R4, MSR
MSRSYNC
RETURN
TEXT spllo(SB), $0
MOVW MSR, R3
OR $MSR_EE, R3, R4
SYNC
MOVW R4, MSR
MSRSYNC
RETURN
TEXT spldone(SB), $0
RETURN
TEXT islo(SB), $0
MOVW MSR, R3
RLWNM $0, R3, $MSR_EE, R3
RETURN
TEXT setlabel(SB), $-4
MOVW LR, R31
MOVW R1, 0(R3)
MOVW R31, 4(R3)
MOVW $0, R3
RETURN
TEXT gotolabel(SB), $-4
MOVW 4(R3), R31
MOVW R31, LR
MOVW 0(R3), R1
MOVW $1, R3
RETURN
TEXT touser(SB), $-4
MOVW $(UTZERO+32), R5 /* header appears in text */
MOVW $(MSR_EE|MSR_PR|MSR_ME|MSR_IR|MSR_DR|MSR_RI), R4
MOVW R4, SPR(SRR1)
MOVW R3, R1
MOVW R5, SPR(SRR0)
RFI
TEXT icflush(SB), $-4 /* icflush(virtaddr, count) */
MOVW n+4(FP), R4
RLWNM $0, R3, $~(CACHELINESZ-1), R5
SUB R5, R3
ADD R3, R4
ADD $(CACHELINESZ-1), R4
SRAW $CACHELINELOG, R4
MOVW R4, CTR
icf0: ICBI (R5)
ADD $CACHELINESZ, R5
BDNZ icf0
ISYNC
RETURN
TEXT dcflush(SB), $-4 /* dcflush(virtaddr, count) */
MOVW n+4(FP), R4
RLWNM $0, R3, $~(CACHELINESZ-1), R5
CMP R4, $0
BLE dcf1
SUB R5, R3
ADD R3, R4
ADD $(CACHELINESZ-1), R4
SRAW $CACHELINELOG, R4
MOVW R4, CTR
dcf0: DCBF (R5)
ADD $CACHELINESZ, R5
BDNZ dcf0
dcf1:
SYNC
RETURN
TEXT tas(SB), $0
TEXT _tas(SB), $0
SYNC
MOVW R3, R4
MOVW $0xdead,R5
tas1:
DCBF (R4) /* fix for 603x bug */
LWAR (R4), R3
CMP R3, $0
BNE tas0
STWCCC R5, (R4)
BNE tas1
tas0:
SYNC
ISYNC
RETURN
TEXT cmpswap(SB),$0 /* int cmpswap(long*, long, long) */
MOVW R3, R4 /* addr */
MOVW old+4(FP), R5
MOVW new+8(FP), R6
DCBF (R4) /* fix for 603x bug? */
LWAR (R4), R3
CMP R3, R5
BNE fail
STWCCC R6, (R4)
BNE fail
MOVW $1, R3
RETURN
fail:
MOVW $0, R3
RETURN
TEXT getpvr(SB), $0
MOVW SPR(PVR), R3
RETURN
TEXT getdec(SB), $0
MOVW SPR(DEC), R3
RETURN
TEXT putdec(SB), $0
MOVW R3, SPR(DEC)
RETURN
TEXT getdar(SB), $0
MOVW SPR(DAR), R3
RETURN
TEXT getdsisr(SB), $0
MOVW SPR(DSISR), R3
RETURN
TEXT getmsr(SB), $0
MOVW MSR, R3
RETURN
TEXT putmsr(SB), $0
SYNC
MOVW R3, MSR
MSRSYNC
RETURN
TEXT putsdr1(SB), $0
MOVW R3, SPR(SDR1)
RETURN
TEXT putsr(SB), $0
MOVW 4(FP), R4
MOVW R4, SEG(R3)
RETURN
TEXT gethid0(SB), $0
MOVW SPR(HID0), R3
RETURN
TEXT gethid1(SB), $0
MOVW SPR(HID1), R3
RETURN
TEXT puthid0(SB), $0
MOVW R3, SPR(HID0)
RETURN
TEXT puthid1(SB), $0
MOVW R3, SPR(HID1)
RETURN
TEXT eieio(SB), $0
EIEIO
RETURN
TEXT sync(SB), $0
SYNC
RETURN
TEXT tlbflushall(SB), $0
MOVW $64, R3
MOVW R3, CTR
MOVW $0, R4
tlbflushall0:
TLBIE R4
ADD $BIT(19), R4
BDNZ tlbflushall0
EIEIO
TLBSYNC
SYNC
RETURN
TEXT tlbflush(SB), $0
TLBIE R3
RETURN
TEXT gotopc(SB), $0
MOVW R3, CTR
MOVW LR, R31 /* for trace back */
BR (CTR)
/*
* traps force memory mapping off.
* the following code has been executed at the exception
* vector location
* MOVW R0, SPR(SAVER0)
* MOVW LR, R0
* MOVW R0, SPR(SAVELR)
* bl trapvec(SB)
*/
TEXT trapvec(SB), $-4
MOVW LR, R0
MOVW R1, SPR(SAVER1)
MOVW R0, SPR(SAVEXX) /* vector */
/* did we come from user space */
MOVW SPR(SRR1), R0
MOVW CR, R1
MOVW R0, CR
BC 4,17,ktrap
/* switch to kernel stack */
MOVW R1, CR
MOVW R2, R0
MOVW $setSB(SB), R2
RLWNM $0, R2, $~KZERO, R2 /* PADDR(setSB) */
MOVW $mach0(SB), R1 /* m-> */
RLWNM $0, R1, $~KZERO, R1 /* PADDR(m->) */
MOVW 8(R1), R1 /* m->proc */
RLWNM $0, R1, $~KZERO, R1 /* PADDR(m->proc) */
SUB $UREGSIZE, R1 /* make room on stack */
MOVW R0, R2
BL saveureg(SB)
BL trap(SB)
BR restoreureg
ktrap:
MOVW R1, CR
MOVW SPR(SAVER1), R1
RLWNM $0, R1, $~KZERO, R1 /* PADDR(R1) */
SUB $UREGSPACE, R1
BL saveureg(SB)
BL trap(SB)
BR restoreureg
/*
* enter with stack set and mapped.
* on return, SB (R2) has been set, and R3 has the Ureg*,
* the MMU has been re-enabled, kernel text and PC are in KSEG,
* R(MACH) has been set, and R0 contains 0.
*
*/
TEXT saveureg(SB), $-4
/*
* save state
*/
MOVMW R2, 48(R1) /* r2:r31 */
MOVW $setSB(SB), R2
RLWNM $0, R2, $~KZERO, R2 /* PADDR(setSB) */
MOVW $mach0(SB), R(MACH)
RLWNM $0, R(MACH), $~KZERO, R(MACH) /* PADDR(m->) */
MOVW 8(R(MACH)), R(USER)
MOVW $mach0(SB), R(MACH)
MOVW $setSB(SB), R2
MOVW SPR(SAVER1), R4
MOVW R4, 44(R1)
MOVW SPR(SAVER0), R5
MOVW R5, 40(R1)
MOVW CTR, R6
MOVW R6, 36(R1)
MOVW XER, R4
MOVW R4, 32(R1)
MOVW CR, R5
MOVW R5, 28(R1)
MOVW SPR(SAVELR), R6 /* LR */
MOVW R6, 24(R1)
/* pad at 20(R1) */
MOVW SPR(SRR0), R0
MOVW R0, 16(R1) /* old PC */
MOVW SPR(SRR1), R0
MOVW R0, 12(R1) /* old status */
MOVW SPR(SAVEXX), R0
MOVW R0, 8(R1) /* cause/vector */
ADD $8, R1, R3 /* Ureg* */
OR $KZERO, R3 /* fix ureg */
STWCCC R3, (R1) /* break any pending reservations */
MOVW $0, R0 /* compiler/linker expect R0 to be zero */
MOVW MSR, R5
OR $(MSR_IR|MSR_DR|MSR_FP|MSR_RI), R5 /* enable MMU */
MOVW R5, SPR(SRR1)
MOVW LR, R31
OR $KZERO, R31 /* return PC in KSEG0 */
MOVW R31, SPR(SRR0)
OR $KZERO, R1 /* fix stack pointer */
RFI /* returns to trap handler */
/*
* restore state from Ureg and return from trap/interrupt
*/
TEXT forkret(SB), $0
BR restoreureg
restoreureg:
MOVMW 48(R1), R2 /* r2:r31 */
/* defer R1 */
MOVW 40(R1), R0
MOVW R0, SPR(SAVER0)
MOVW 36(R1), R0
MOVW R0, CTR
MOVW 32(R1), R0
MOVW R0, XER
MOVW 28(R1), R0
MOVW R0, CR /* CR */
MOVW 24(R1), R0
MOVW R0, LR
/* pad, skip */
MOVW 16(R1), R0
MOVW R0, SPR(SRR0) /* old PC */
MOVW 12(R1), R0
MOVW R0, SPR(SRR1) /* old MSR */
/* cause, skip */
MOVW 44(R1), R1 /* old SP */
MOVW SPR(SAVER0), R0
RFI
TEXT fpsave(SB), $0
FMOVD F0, (0*8)(R3)
FMOVD F1, (1*8)(R3)
FMOVD F2, (2*8)(R3)
FMOVD F3, (3*8)(R3)
FMOVD F4, (4*8)(R3)
FMOVD F5, (5*8)(R3)
FMOVD F6, (6*8)(R3)
FMOVD F7, (7*8)(R3)
FMOVD F8, (8*8)(R3)
FMOVD F9, (9*8)(R3)
FMOVD F10, (10*8)(R3)
FMOVD F11, (11*8)(R3)
FMOVD F12, (12*8)(R3)
FMOVD F13, (13*8)(R3)
FMOVD F14, (14*8)(R3)
FMOVD F15, (15*8)(R3)
FMOVD F16, (16*8)(R3)
FMOVD F17, (17*8)(R3)
FMOVD F18, (18*8)(R3)
FMOVD F19, (19*8)(R3)
FMOVD F20, (20*8)(R3)
FMOVD F21, (21*8)(R3)
FMOVD F22, (22*8)(R3)
FMOVD F23, (23*8)(R3)
FMOVD F24, (24*8)(R3)
FMOVD F25, (25*8)(R3)
FMOVD F26, (26*8)(R3)
FMOVD F27, (27*8)(R3)
FMOVD F28, (28*8)(R3)
FMOVD F29, (29*8)(R3)
FMOVD F30, (30*8)(R3)
FMOVD F31, (31*8)(R3)
MOVFL FPSCR, F0
FMOVD F0, (32*8)(R3)
RETURN
TEXT fprestore(SB), $0
FMOVD (32*8)(R3), F0
MOVFL F0, FPSCR
FMOVD (0*8)(R3), F0
FMOVD (1*8)(R3), F1
FMOVD (2*8)(R3), F2
FMOVD (3*8)(R3), F3
FMOVD (4*8)(R3), F4
FMOVD (5*8)(R3), F5
FMOVD (6*8)(R3), F6
FMOVD (7*8)(R3), F7
FMOVD (8*8)(R3), F8
FMOVD (9*8)(R3), F9
FMOVD (10*8)(R3), F10
FMOVD (11*8)(R3), F11
FMOVD (12*8)(R3), F12
FMOVD (13*8)(R3), F13
FMOVD (14*8)(R3), F14
FMOVD (15*8)(R3), F15
FMOVD (16*8)(R3), F16
FMOVD (17*8)(R3), F17
FMOVD (18*8)(R3), F18
FMOVD (19*8)(R3), F19
FMOVD (20*8)(R3), F20
FMOVD (21*8)(R3), F21
FMOVD (22*8)(R3), F22
FMOVD (23*8)(R3), F23
FMOVD (24*8)(R3), F24
FMOVD (25*8)(R3), F25
FMOVD (26*8)(R3), F26
FMOVD (27*8)(R3), F27
FMOVD (28*8)(R3), F28
FMOVD (29*8)(R3), F29
FMOVD (30*8)(R3), F30
FMOVD (31*8)(R3), F31
RETURN
|
9front/9front
| 1,476
|
sys/src/9/mtx/inb.s
|
#include "mem.h"
#define BDNZ BC 16,0,
#define BDNE BC 0,2,
TEXT inb(SB), $0
OR $IOMEM, R3
MOVBZ (R3), R3
RETURN
TEXT insb(SB), $0
MOVW v+4(FP), R4
MOVW n+8(FP), R5
MOVW R5, CTR
OR $IOMEM, R3
SUB $1, R4
insb1:
MOVBZ (R3), R7
MOVBU R7, 1(R4)
BDNZ insb1
RETURN
TEXT outb(SB), $0
MOVW v+4(FP), R4
OR $IOMEM, R3
EIEIO
MOVB R4, (R3)
RETURN
TEXT outsb(SB), $0
MOVW v+4(FP), R4
MOVW n+8(FP), R5
MOVW R5, CTR
OR $IOMEM, R3
SUB $1, R4
outsb1:
EIEIO
MOVBZU 1(R4), R7
MOVB R7, (R3)
BDNZ outsb1
RETURN
TEXT ins(SB), $0
OR $IOMEM, R3
EIEIO
MOVHBR (R3), R3
RETURN
TEXT inss(SB), $0
MOVW v+4(FP), R4
MOVW n+8(FP), R5
MOVW R5, CTR
OR $IOMEM, R3
SUB $2, R4
inss1:
EIEIO
MOVHZ (R3), R7
MOVHU R7, 2(R4)
BDNZ inss1
RETURN
TEXT outs(SB), $0
MOVW v+4(FP), R4
OR $IOMEM, R3
EIEIO
MOVHBR R4, (R3)
RETURN
TEXT outss(SB), $0
MOVW v+4(FP), R4
MOVW n+8(FP), R5
MOVW R5, CTR
OR $IOMEM, R3
SUB $2, R4
outss1:
EIEIO
MOVHZU 2(R4), R7
MOVH R7, (R3)
BDNZ outss1
RETURN
TEXT inl(SB), $0
OR $IOMEM, R3
EIEIO
MOVWBR (R3), R3
RETURN
TEXT insl(SB), $0
MOVW v+4(FP), R4
MOVW n+8(FP), R5
MOVW R5, CTR
OR $IOMEM, R3
SUB $4, R4
insl1:
EIEIO
MOVW (R3), R7
MOVWU R7, 4(R4)
BDNZ insl1
RETURN
TEXT outl(SB), $0
MOVW v+4(FP), R4
OR $IOMEM, R3
EIEIO
MOVWBR R4, (R3)
RETURN
TEXT outsl(SB), $0
MOVW v+4(FP), R4
MOVW n+8(FP), R5
MOVW R5, CTR
OR $IOMEM, R3
SUB $4, R4
outsl1:
EIEIO
MOVWU 4(R4), R7
MOVW R7, (R3)
BDNZ outsl1
RETURN
|
9front/9front
| 1,389
|
sys/src/9/pc/apmjump.s
|
/*
* Far call, absolute indirect.
* The argument is the offset.
* We use a global structure for the jump params,
* so this is *not* reentrant or thread safe.
*/
#include "mem.h"
#define SSOVERRIDE BYTE $0x36
#define CSOVERRIDE BYTE $0x2E
GLOBL apmjumpstruct+0(SB), $8
TEXT apmfarcall(SB), $0
/*
* We call push and pop ourselves.
* As soon as we do the first push or pop,
* we can't use FP anymore.
*/
MOVL off+4(FP), BX
MOVL seg+0(FP), CX
MOVL BX, apmjumpstruct+0(SB)
MOVL CX, apmjumpstruct+4(SB)
/* load necessary registers from Ureg */
MOVL ureg+8(FP), DI
MOVL 28(DI), AX
MOVL 16(DI), BX
MOVL 24(DI), CX
MOVL 20(DI), DX
/* save registers, segments */
PUSHL DS
PUSHL ES
PUSHL FS
PUSHL GS
PUSHL BP
PUSHL DI
/*
* paranoia: zero the segments, since it's the
* BIOS's responsibility to initialize them.
* (trick picked up from Linux driver).
*/
PUSHL DX
XORL DX, DX
PUSHL DX
POPL DS
PUSHL DX
POPL ES
PUSHL DX
POPL FS
PUSHL DX
POPL GS
POPL DX
/*
* The actual call.
*/
CSOVERRIDE; BYTE $0xFF; BYTE $0x1D
LONG $apmjumpstruct+0(SB)
/* restore segments, registers */
POPL DI
POPL BP
POPL GS
POPL FS
POPL ES
POPL DS
PUSHFL
POPL 64(DI)
/* store interesting registers back in Ureg */
MOVL AX, 28(DI)
MOVL BX, 16(DI)
MOVL CX, 24(DI)
MOVL DX, 20(DI)
MOVL SI, 4(DI)
PUSHFL
POPL AX
ANDL $1, AX /* carry flag */
RET
|
9front/9front
| 30,317
|
sys/src/9/pc/l.s
|
#include "mem.h"
#undef DELAY
#define PADDR(a) ((a) & ~KZERO)
#define KADDR(a) (KZERO|(a))
/*
* Some machine instructions not handled by 8[al].
*/
#define OP16 BYTE $0x66
#define DELAY BYTE $0xEB; BYTE $0x00 /* JMP .+2 */
#define CPUID BYTE $0x0F; BYTE $0xA2 /* CPUID, argument in AX */
#define WRMSR BYTE $0x0F; BYTE $0x30 /* WRMSR, argument in AX/DX (lo/hi) */
#define RDTSC BYTE $0x0F; BYTE $0x31 /* RDTSC, result in AX/DX (lo/hi) */
#define RDMSR BYTE $0x0F; BYTE $0x32 /* RDMSR, result in AX/DX (lo/hi) */
#define HLT BYTE $0xF4
#define INVLPG BYTE $0x0F; BYTE $0x01; BYTE $0x39 /* INVLPG (%ecx) */
#define WBINVD BYTE $0x0F; BYTE $0x09
#define VectorSYSCALL 0x40
/*
* Macros for calculating offsets within the page directory base
* and page tables. Note that these are assembler-specific hence
* the '<<2'.
*/
#define PDO(a) (((((a))>>22) & 0x03FF)<<2)
#define PTO(a) (((((a))>>12) & 0x03FF)<<2)
/*
* For backwards compatiblity with 9load - should go away when 9load is changed
* 9load currently sets up the mmu, however the first 16MB of memory is identity
* mapped, so behave as if the mmu was not setup
*/
TEXT _startKADDR(SB), $0
MOVL $_startPADDR(SB), AX
ANDL $~KZERO, AX
JMP* AX
/*
* Must be 4-byte aligned.
*/
TEXT _multibootheader(SB), $0
LONG $0x1BADB002 /* magic */
LONG $0x00010007 /* flags */
LONG $-(0x1BADB002 + 0x00010007) /* checksum */
LONG $_multibootheader-KZERO(SB) /* header_addr */
LONG $_startKADDR-KZERO(SB) /* load_addr */
LONG $edata-KZERO(SB) /* load_end_addr */
LONG $end-KZERO(SB) /* bss_end_addr */
LONG $_multibootentry-KZERO(SB) /* entry_addr */
LONG $0 /* mode_type */
LONG $0 /* width */
LONG $0 /* height */
LONG $32 /* depth */
/*
* the kernel expects the data segment to be page-aligned
* multiboot bootloaders put the data segment right behind text
*/
TEXT _multibootentry(SB), $0
MOVL $etext-KZERO(SB), SI
MOVL SI, DI
ADDL $0xfff, DI
ANDL $~0xfff, DI
MOVL $edata-KZERO(SB), CX
SUBL DI, CX
ADDL CX, SI
ADDL CX, DI
INCL CX /* one more for post decrement */
STD
REP; MOVSB
MOVL BX, multibootptr-KZERO(SB)
MOVL $_startPADDR-KZERO(SB), AX
JMP* AX
/* multiboot structure pointer (physical address) */
TEXT multibootptr(SB), $0
LONG $0
/*
* In protected mode with paging turned off and segment registers setup
* to linear map all memory. Entered via a jump to PADDR(entry),
* the physical address of the virtual kernel entry point of KADDR(entry).
* Make the basic page tables for processor 0. Six pages are needed for
* the basic set:
* a page directory;
* page tables for mapping the first 8MB of physical memory to KZERO;
* a page for the GDT;
* virtual and physical pages for mapping the Mach structure.
* The remaining PTEs will be allocated later when memory is sized.
* An identity mmu map is also needed for the switch to virtual mode.
* This identity mapping is removed once the MMU is going and the JMP has
* been made to virtual memory.
*/
TEXT _startPADDR(SB), $0
CLI /* make sure interrupts are off */
/* set up the gdt so we have sane plan 9 style gdts. */
MOVL $tgdtptr-KZERO(SB), AX
MOVL (AX), GDTR
MOVW $1, AX
MOVW AX, MSW
/* clear prefetch queue (weird code to avoid optimizations) */
DELAY
/* set segs to something sane (avoid traps later) */
MOVW $(1<<3), AX
MOVW AX, DS
MOVW AX, SS
MOVW AX, ES
MOVW AX, FS
MOVW AX, GS
/* JMP $(2<<3):$mode32bit(SB) /**/
BYTE $0xEA
LONG $mode32bit-KZERO(SB)
WORD $(2<<3)
/*
* gdt to get us to 32-bit/segmented/unpaged mode
*/
TEXT tgdt(SB), $0
/* null descriptor */
LONG $0
LONG $0
/* data segment descriptor for 4 gigabytes (PL 0) */
LONG $(0xFFFF)
LONG $(SEGG|SEGB|(0xF<<16)|SEGP|SEGPL(0)|SEGDATA|SEGW)
/* exec segment descriptor for 4 gigabytes (PL 0) */
LONG $(0xFFFF)
LONG $(SEGG|SEGD|(0xF<<16)|SEGP|SEGPL(0)|SEGEXEC|SEGR)
/*
* pointer to initial gdt
* Note the -KZERO which puts the physical address in the gdtptr.
* that's needed as we start executing in physical addresses.
*/
TEXT tgdtptr(SB), $0
WORD $(3*8)
LONG $tgdt-KZERO(SB)
TEXT vtgdtptr(SB), $0
WORD $(3*8)
LONG $tgdt(SB)
TEXT mode32bit(SB), $0
MOVL $((CPU0END-CPU0PDB)>>2), CX
MOVL $PADDR(CPU0PDB), DI
XORL AX, AX
CLD
REP; STOSL
MOVL $PADDR(CPU0PTE), DX
MOVL $(PTEWRITE|PTEVALID), BX /* page permissions */
ORL BX, DX
MOVL $PADDR(CPU0PDB), AX
ADDL $PDO(KZERO), AX /* page directory offset for KZERO */
MOVL DX, 0(AX) /* PTE's for KZERO */
ADDL $BY2PG, DX
MOVL DX, 4(AX) /* PTE's for KZERO+4MB */
ADDL $BY2PG, DX
MOVL DX, 8(AX) /* PTE's for KZERO+8MB */
ADDL $BY2PG, DX
MOVL DX, 12(AX) /* PTE's for KZERO+12MB */
MOVL $PADDR(CPU0PTE), AX /* first page of page table */
MOVL $end-KZERO(SB), CX
ADDL $(16*1024), CX /* qemu puts multiboot data after the kernel */
ADDL $(BY2XPG-1), CX
ANDL $~(BY2XPG-1), CX /* round to 4MB */
MOVL CX, MemMin-KZERO(SB) /* see memory.c */
SHRL $PGSHIFT, CX
MOVL BX, DX
_setpte:
MOVL DX, (AX)
ADDL $BY2PG, DX
ADDL $4, AX
LOOP _setpte
MOVL $PADDR(CPU0PTE), AX
ADDL $PTO(MACHADDR), AX /* page table entry offset for MACHADDR */
ORL $PADDR(CPU0MACH), BX
MOVL BX, (AX) /* PTE for Mach */
/*
* Now ready to use the new map. Make sure the processor options are what is wanted.
* It is necessary on some processors to immediately follow mode switching with a JMP instruction
* to clear the prefetch queues.
*/
MOVL $PADDR(CPU0PDB), CX /* load address of page directory */
MOVL (PDO(KZERO))(CX), DX /* double-map KZERO at 0 */
MOVL DX, (PDO(0))(CX)
MOVL CX, CR3
DELAY /* JMP .+2 */
MOVL CR0, DX
ORL $0x80010000, DX /* PG|WP */
ANDL $~0x6000000A, DX /* ~(CD|NW|TS|MP) */
MOVL $_startpg(SB), AX /* this is a virtual address */
MOVL DX, CR0 /* turn on paging */
JMP* AX /* jump to the virtual nirvana */
/*
* Basic machine environment set, can clear BSS and create a stack.
* The stack starts at the top of the page containing the Mach structure.
* The x86 architecture forces the use of the same virtual address for
* each processor's Mach structure, so the global Mach pointer 'm' can
* be initialised here.
*/
TEXT _startpg(SB), $0
MOVL $vtgdtptr(SB), AX
MOVL (AX), GDTR
MOVL $0, (PDO(0))(CX) /* undo double-map of KZERO at 0 */
MOVL CX, CR3 /* load and flush the mmu */
_clearbss:
MOVL $edata(SB), DI
XORL AX, AX
MOVL $end(SB), CX
SUBL DI, CX /* end-edata bytes */
SHRL $2, CX /* end-edata doublewords */
CLD
REP; STOSL /* clear BSS */
MOVL $MACHADDR, SP
MOVL SP, m(SB) /* initialise global Mach pointer */
MOVL $0, 0(SP) /* initialise m->machno */
ADDL $(MACHSIZE-4), SP /* initialise stack */
/*
* Need to do one final thing to ensure a clean machine environment,
* clear the EFLAGS register, which can only be done once there is a stack.
*/
MOVL $0, AX
PUSHL AX
POPFL
CALL main(SB)
/*
* Park a processor. Should never fall through a return from main to here,
* should only be called by application processors when shutting down.
*/
TEXT idle(SB), $0
_idle:
STI
HLT
JMP _idle
TEXT load_fs(SB), $0
MOVW fs+0(FP), AX
MOVW AX, FS
RET
TEXT load_gs(SB), $0
MOVW gs+0(FP), AX
MOVW AX, GS
RET
/*
* BIOS32.
*/
TEXT bios32call(SB), $0
MOVL ci+0(FP), BP
MOVL 0(BP), AX
MOVL 4(BP), BX
MOVL 8(BP), CX
MOVL 12(BP), DX
MOVL 16(BP), SI
MOVL 20(BP), DI
PUSHL BP
MOVL 12(SP), BP /* ptr */
BYTE $0xFF; BYTE $0x5D; BYTE $0x00 /* CALL FAR 0(BP) */
POPL BP
MOVL DI, 20(BP)
MOVL SI, 16(BP)
MOVL DX, 12(BP)
MOVL CX, 8(BP)
MOVL BX, 4(BP)
MOVL AX, 0(BP)
XORL AX, AX
JCC _bios32xxret
INCL AX
_bios32xxret:
RET
/*
* Port I/O.
* in[bsl] input a byte|short|long
* ins[bsl] input a string of bytes|shorts|longs
* out[bsl] output a byte|short|long
* outs[bsl] output a string of bytes|shorts|longs
*/
TEXT inb(SB), $0
MOVL port+0(FP), DX
XORL AX, AX
INB
RET
TEXT insb(SB), $0
MOVL port+0(FP), DX
MOVL address+4(FP), DI
MOVL count+8(FP), CX
CLD
REP; INSB
RET
TEXT ins(SB), $0
MOVL port+0(FP), DX
XORL AX, AX
OP16; INL
RET
TEXT inss(SB), $0
MOVL port+0(FP), DX
MOVL address+4(FP), DI
MOVL count+8(FP), CX
CLD
REP; OP16; INSL
RET
TEXT inl(SB), $0
MOVL port+0(FP), DX
INL
RET
TEXT insl(SB), $0
MOVL port+0(FP), DX
MOVL address+4(FP), DI
MOVL count+8(FP), CX
CLD
REP; INSL
RET
TEXT outb(SB), $0
MOVL port+0(FP), DX
MOVL byte+4(FP), AX
OUTB
RET
TEXT outsb(SB), $0
MOVL port+0(FP), DX
MOVL address+4(FP), SI
MOVL count+8(FP), CX
CLD
REP; OUTSB
RET
TEXT outs(SB), $0
MOVL port+0(FP), DX
MOVL short+4(FP), AX
OP16; OUTL
RET
TEXT outss(SB), $0
MOVL port+0(FP), DX
MOVL address+4(FP), SI
MOVL count+8(FP), CX
CLD
REP; OP16; OUTSL
RET
TEXT outl(SB), $0
MOVL port+0(FP), DX
MOVL long+4(FP), AX
OUTL
RET
TEXT outsl(SB), $0
MOVL port+0(FP), DX
MOVL address+4(FP), SI
MOVL count+8(FP), CX
CLD
REP; OUTSL
RET
/*
* Read/write various system registers.
* CR4 and the 'model specific registers' should only be read/written
* after it has been determined the processor supports them
*/
TEXT lgdt(SB), $0 /* GDTR - global descriptor table */
MOVL gdtptr+0(FP), AX
MOVL (AX), GDTR
RET
TEXT lldt(SB), $0 /* LDTR - local descriptor table */
MOVL sel+0(FP), AX
BYTE $0x0F; BYTE $0x00; BYTE $0xD0 /* LLDT AX */
RET
TEXT lidt(SB), $0 /* IDTR - interrupt descriptor table */
MOVL idtptr+0(FP), AX
MOVL (AX), IDTR
RET
TEXT ltr(SB), $0 /* TR - task register */
MOVL tptr+0(FP), AX
MOVW AX, TASK
RET
TEXT getcr0(SB), $0 /* CR0 - processor control */
MOVL CR0, AX
RET
TEXT getcr2(SB), $0 /* CR2 - page fault linear address */
MOVL CR2, AX
RET
TEXT putcr2(SB), $0
MOVL cr2+0(FP), AX
MOVL AX, CR2
RET
TEXT getcr3(SB), $0 /* CR3 - page directory base */
MOVL CR3, AX
RET
TEXT putcr0(SB), $0
MOVL cr0+0(FP), AX
MOVL AX, CR0
RET
TEXT putcr3(SB), $0
MOVL cr3+0(FP), AX
MOVL AX, CR3
RET
TEXT getcr4(SB), $0 /* CR4 - extensions */
MOVL CR4, AX
RET
TEXT putcr4(SB), $0
MOVL cr4+0(FP), AX
MOVL AX, CR4
RET
TEXT invlpg(SB), $0
/* 486+ only */
MOVL va+0(FP), CX
INVLPG
RET
TEXT wbinvd(SB), $0
WBINVD
RET
TEXT _cycles(SB), $0 /* time stamp counter */
RDTSC
MOVL vlong+0(FP), CX /* &vlong */
MOVL AX, 0(CX) /* lo */
MOVL DX, 4(CX) /* hi */
RET
/*
* stub for:
* time stamp counter; low-order 32 bits of 64-bit cycle counter
* Runs at fasthz/4 cycles per second (m->clkin>>3)
*/
TEXT lcycles(SB),1,$0
RDTSC
RET
TEXT rdmsr(SB), $0 /* model-specific register */
MOVL $0, BP
MOVL index+0(FP), CX
TEXT _rdmsrinst(SB), $0
RDMSR
MOVL vlong+4(FP), CX /* &vlong */
MOVL AX, 0(CX) /* lo */
MOVL DX, 4(CX) /* hi */
MOVL BP, AX /* BP set to -1 if traped */
RET
TEXT wrmsr(SB), $0
MOVL $0, BP
MOVL index+0(FP), CX
MOVL lo+4(FP), AX
MOVL hi+8(FP), DX
TEXT _wrmsrinst(SB), $0
WRMSR
MOVL BP, AX /* BP set to -1 if traped */
RET
/* fault-proof memcpy */
TEXT peek(SB), $0
MOVL src+0(FP), SI
MOVL dst+4(FP), DI
MOVL cnt+8(FP), CX
CLD
TEXT _peekinst(SB), $0
REP; MOVSB
MOVL CX, AX
RET
/*
* Try to determine the CPU type which requires fiddling with EFLAGS.
* If the Id bit can be toggled then the CPUID instruction can be used
* to determine CPU identity and features. First have to check if it's
* a 386 (Ac bit can't be set). If it's not a 386 and the Id bit can't be
* toggled then it's an older 486 of some kind.
*
* cpuid(fn, sublvl, regs[4]);
*/
TEXT cpuid(SB), $0
MOVL $0x240000, AX
PUSHL AX
POPFL /* set Id|Ac */
PUSHFL
POPL BX /* retrieve value */
MOVL $0, AX
PUSHL AX
POPFL /* clear Id|Ac, EFLAGS initialised */
PUSHFL
POPL AX /* retrieve value */
XORL BX, AX
TESTL $0x040000, AX /* Ac */
JZ _cpu386 /* can't set this bit on 386 */
TESTL $0x200000, AX /* Id */
JZ _cpu486 /* can't toggle this bit on some 486 */
MOVL fn+0(FP), AX
MOVL sublvl+4(FP), CX
CPUID
JMP _cpuid
_cpu486:
MOVL $0x400, AX
JMP _maybezapax
_cpu386:
MOVL $0x300, AX
_maybezapax:
CMPL fn+0(FP), $1
JE _zaprest
XORL AX, AX
_zaprest:
XORL BX, BX
XORL CX, CX
XORL DX, DX
_cpuid:
MOVL regs+8(FP), BP
MOVL AX, 0(BP)
MOVL BX, 4(BP)
MOVL CX, 8(BP)
MOVL DX, 12(BP)
RET
/*
* Basic timing loop to determine CPU frequency.
*/
TEXT delayloop(SB), $0
MOVL count+0(FP), CX
_aamloop:
AAM
LOOP _aamloop
RET
/*
* Floating point.
* Note: the encodings for the FCLEX, FINIT, FSAVE, FSTCW, FSENV and FSTSW
* instructions do NOT have the WAIT prefix byte (i.e. they act like their
* FNxxx variations) so WAIT instructions must be explicitly placed in the
* code as necessary.
*/
#define FPOFF ;\
MOVL CR0, AX ;\
ORL $0x28, AX /* NE=1, TS=1 */ ;\
MOVL AX, CR0
#define FPON ;\
MOVL CR0, AX ;\
ANDL $~0xC, AX /* EM=0, TS=0 */ ;\
MOVL AX, CR0
TEXT fpoff(SB), $0 /* disable */
FPOFF
RET
TEXT fpinit(SB), $0 /* enable and init */
FPON
FINIT
WAIT
/* setfcr(FPPDBL|FPRNR|FPINVAL|FPZDIV|FPOVFL) */
/* note that low 6 bits are masks, not enables, on this chip */
PUSHW $0x0232
FLDCW 0(SP)
POPW AX
WAIT
RET
TEXT fpx87save0(SB), $0 /* save state and disable */
MOVL p+0(FP), AX
FSAVE 0(AX) /* no WAIT */
FPOFF
RET
TEXT fpx87restore0(SB), $0 /* enable and restore state */
FPON
MOVL p+0(FP), AX
FRSTOR 0(AX)
WAIT
RET
TEXT fpclear(SB), $0 /* clear pending exceptions */
FPON
FCLEX /* no WAIT */
FPOFF
RET
TEXT fpssesave(SB), $0 /* save state and disable */
MOVL p+0(FP), AX
FXSAVE 0(AX) /* no WAIT */
FPOFF
RET
TEXT fpsserestore(SB), $0 /* enable and restore state */
FPON
MOVL p+0(FP), AX
FXRSTOR 0(AX)
WAIT
RET
TEXT ldmxcsr(SB), $0 /* Load MXCSR */
LDMXCSR mxcsr+0(FP)
RET
/*
*/
TEXT splhi(SB), $0
shi:
PUSHFL
POPL AX
TESTL $0x200, AX
JZ alreadyhi
MOVL $(MACHADDR+0x04), CX /* save PC in m->splpc */
MOVL (SP), BX
MOVL BX, (CX)
CLI
alreadyhi:
RET
TEXT spllo(SB), $0
slo:
PUSHFL
POPL AX
TESTL $0x200, AX
JNZ alreadylo
MOVL $(MACHADDR+0x04), CX /* clear m->splpc */
MOVL $0, (CX)
STI
alreadylo:
RET
TEXT splx(SB), $0
MOVL s+0(FP), AX
TESTL $0x200, AX
JNZ slo
JMP shi
TEXT spldone(SB), $0
RET
TEXT islo(SB), $0
PUSHFL
POPL AX
ANDL $0x200, AX /* interrupt enable flag */
RET
/*
* Test-And-Set
*/
TEXT tas(SB), $0
TEXT _tas(SB), $0
MOVL $0xDEADDEAD, AX
MOVL lock+0(FP), BX
XCHGL AX, (BX) /* lock->key */
RET
TEXT mb386(SB), $0
POPL AX /* return PC */
PUSHFL
PUSHL CS
PUSHL AX
IRETL
TEXT mb586(SB), $0
XORL AX, AX
CPUID
RET
TEXT sfence(SB), $0
BYTE $0x0f
BYTE $0xae
BYTE $0xf8
RET
TEXT lfence(SB), $0
BYTE $0x0f
BYTE $0xae
BYTE $0xe8
RET
TEXT mfence(SB), $0
BYTE $0x0f
BYTE $0xae
BYTE $0xf0
RET
TEXT xchgw(SB), $0
MOVL v+4(FP), AX
MOVL p+0(FP), BX
XCHGW AX, (BX)
RET
TEXT cmpswap486(SB), $0
MOVL addr+0(FP), BX
MOVL old+4(FP), AX
MOVL new+8(FP), CX
LOCK
BYTE $0x0F; BYTE $0xB1; BYTE $0x0B /* CMPXCHGL CX, (BX) */
JNZ didnt
MOVL $1, AX
RET
didnt:
XORL AX,AX
RET
TEXT mul64fract(SB), $0
/*
* Multiply two 64-bit number s and keep the middle 64 bits from the 128-bit result
* See ../port/tod.c for motivation.
*/
MOVL r+0(FP), CX
XORL BX, BX /* BX = 0 */
MOVL a+8(FP), AX
MULL b+16(FP) /* a1*b1 */
MOVL AX, 4(CX) /* r2 = lo(a1*b1) */
MOVL a+8(FP), AX
MULL b+12(FP) /* a1*b0 */
MOVL AX, 0(CX) /* r1 = lo(a1*b0) */
ADDL DX, 4(CX) /* r2 += hi(a1*b0) */
MOVL a+4(FP), AX
MULL b+16(FP) /* a0*b1 */
ADDL AX, 0(CX) /* r1 += lo(a0*b1) */
ADCL DX, 4(CX) /* r2 += hi(a0*b1) + carry */
MOVL a+4(FP), AX
MULL b+12(FP) /* a0*b0 */
ADDL DX, 0(CX) /* r1 += hi(a0*b0) */
ADCL BX, 4(CX) /* r2 += carry */
RET
/*
* label consists of a stack pointer and a PC
*/
TEXT gotolabel(SB), $0
MOVL label+0(FP), AX
MOVL 0(AX), SP /* restore sp */
MOVL 4(AX), AX /* put return pc on the stack */
MOVL AX, 0(SP)
MOVL $1, AX /* return 1 */
RET
TEXT setlabel(SB), $0
MOVL label+0(FP), AX
MOVL SP, 0(AX) /* store sp */
MOVL 0(SP), BX /* store return pc */
MOVL BX, 4(AX)
MOVL $0, AX /* return 0 */
RET
/*
* Attempt at power saving. -rsc
*/
TEXT halt(SB), $0
CLI
CMPL nrdy(SB), $0
JEQ _nothingready
STI
RET
_nothingready:
STI
HLT
RET
TEXT mwait(SB), $0
MOVL addr+0(FP), AX
MOVL (AX), CX
ORL CX, CX
JNZ _mwaitdone
XORL DX, DX
BYTE $0x0f; BYTE $0x01; BYTE $0xc8 /* MONITOR */
MOVL (AX), CX
ORL CX, CX
JNZ _mwaitdone
XORL AX, AX
BYTE $0x0f; BYTE $0x01; BYTE $0xc9 /* MWAIT */
_mwaitdone:
RET
#define RDRANDAX BYTE $0x0f; BYTE $0xc7; BYTE $0xf0
TEXT rdrand32(SB), $-4
_rloop32:
RDRANDAX
JCC _rloop32
RET
TEXT rdrandbuf(SB), $0
MOVL buf+0(FP), DI
MOVL cnt+4(FP), CX
CLD
MOVL CX, DX
SHRL $2, CX
CMPL CX, $0
JE _rndleft
_rnddwords:
CALL rdrand32(SB)
STOSL
LOOP _rnddwords
_rndleft:
MOVL DX, CX
ANDL $3, CX
CMPL CX, $0
JE _rnddone
_rndbytes:
CALL rdrand32(SB)
STOSB
LOOP _rndbytes
_rnddone:
RET
/* debug register access */
TEXT putdr(SB), $0
MOVL p+0(FP), SI
MOVL 28(SI), AX
MOVL AX, DR7
_putdr01236:
MOVL 0(SI), AX
MOVL AX, DR0
MOVL 4(SI), AX
MOVL AX, DR1
MOVL 8(SI), AX
MOVL AX, DR2
MOVL 12(SI), AX
MOVL AX, DR3
MOVL 24(SI), AX
MOVL AX, DR6
RET
TEXT putdr01236(SB), $0
MOVL p+0(FP), SI
JMP _putdr01236
TEXT getdr6(SB), $0
MOVL DR6, AX
RET
TEXT putdr6(SB), $0
MOVL p+0(FP), AX
MOVL AX, DR6
RET
TEXT putdr7(SB), $0
MOVL p+0(FP), AX
MOVL AX, DR7
RET
/* VMX instructions */
TEXT vmxon(SB), $0
/* VMXON 4(SP) */
BYTE $0xf3; BYTE $0x0f; BYTE $0xc7; BYTE $0x74; BYTE $0x24; BYTE $0x04
JMP _vmout
TEXT vmxoff(SB), $0
BYTE $0x0f; BYTE $0x01; BYTE $0xc4
JMP _vmout
TEXT vmclear(SB), $0
/* VMCLEAR 4(SP) */
BYTE $0x66; BYTE $0x0f; BYTE $0xc7; BYTE $0x74; BYTE $0x24; BYTE $0x04
JMP _vmout
TEXT vmlaunch(SB), $0
MOVL $0x6C14, DI
MOVL SP, DX
BYTE $0x0f; BYTE $0x79; BYTE $0xfa /* VMWRITE DX, DI */
JBE _vmout
MOVL $0x6C16, DI
MOVL $vmrestore(SB), DX
BYTE $0x0f; BYTE $0x79; BYTE $0xfa /* VMWRITE DX, DI */
JBE _vmout
MOVL resume+4(FP), AX
TESTL AX, AX
MOVL ureg+0(FP), DI
MOVL 4(DI), SI
MOVL 8(DI), BP
MOVL 16(DI), BX
MOVL 20(DI), DX
MOVL 24(DI), CX
MOVL 28(DI), AX
MOVL 0(DI), DI
JNE _vmresume
BYTE $0x0f; BYTE $0x01; BYTE $0xc2 /* VMLAUNCH */
JMP _vmout
_vmresume:
BYTE $0x0f; BYTE $0x01; BYTE $0xc3 /* VMRESUME */
JMP _vmout
TEXT vmrestore(SB), $0
PUSHL DI
MOVL ureg+0(FP), DI
POPL 0(DI)
MOVL SI, 4(DI)
MOVL BP, 8(DI)
MOVL BX, 16(DI)
MOVL DX, 20(DI)
MOVL CX, 24(DI)
MOVL AX, 28(DI)
XORL AX, AX
RET
TEXT vmptrld(SB), $0
/* VMPTRLD 4(SP) */
BYTE $0x0f; BYTE $0xc7; BYTE $0x74; BYTE $0x24; BYTE $0x04
JMP _vmout
TEXT vmwrite(SB), $0
MOVL addr+0(FP),DI
MOVL val+4(FP),DX
/* VMWRITE DX, DI */
BYTE $0x0f; BYTE $0x79; BYTE $0xfa
JMP _vmout
TEXT vmread(SB), $0
MOVL addr+0(FP),DI
MOVL valp+4(FP),SI
/* VMREAD (SI), DI */
BYTE $0x0f; BYTE $0x78; BYTE $0x3e
JMP _vmout
TEXT invept(SB), $0
MOVL type+0(FP), AX
/* INVEPT AX, 8(SP) */
BYTE $0x66; BYTE $0x0f; BYTE $0x38; BYTE $0x80; BYTE $0x44; BYTE $0x24; BYTE $0x08
JMP _vmout
TEXT invvpid(SB), $0
MOVL type+0(FP), AX
/* INVVPID AX, 8(SP) */
BYTE $0x66; BYTE $0x0f; BYTE $0x38; BYTE $0x81; BYTE $0x44; BYTE $0x24; BYTE $0x08
JMP _vmout
_vmout:
JC _vmout1
JZ _vmout2
XORL AX, AX
RET
_vmout1:
MOVL $-1, AX
RET
_vmout2:
MOVL $-2, AX
RET
/*
* Used to get to the first process:
* set up an interrupt return frame and IRET to user level.
*/
TEXT touser(SB), $0
PUSHL $(UDSEL) /* old ss */
MOVL sp+0(FP), AX /* old sp */
PUSHL AX
MOVL $0x200, AX /* interrupt enable flag */
PUSHL AX /* old flags */
PUSHL $(UESEL) /* old cs */
PUSHL $(UTZERO+32) /* old pc */
MOVL $(UDSEL), AX
MOVW AX, DS
MOVW AX, ES
MOVW AX, GS
MOVW AX, FS
IRETL
/*
* Interrupt/exception handling.
* Each entry in the vector table calls either _strayintr or _strayintrx depending
* on whether an error code has been automatically pushed onto the stack
* (_strayintrx) or not, in which case a dummy entry must be pushed before retrieving
* the trap type from the vector table entry and placing it on the stack as part
* of the Ureg structure.
* The size of each entry in the vector table (6 bytes) is known in trapinit().
*/
TEXT _strayintr(SB), $0
PUSHL AX /* save AX */
MOVL 4(SP), AX /* return PC from vectortable(SB) */
JMP intrcommon
TEXT _strayintrx(SB), $0
XCHGL AX, (SP) /* swap AX with vectortable CALL PC */
intrcommon:
PUSHL DS /* save DS */
PUSHL $(KDSEL)
POPL DS /* fix up DS */
MOVBLZX (AX), AX /* trap type -> AX */
XCHGL AX, 4(SP) /* exchange trap type with saved AX */
PUSHL ES /* save ES */
PUSHL $(KDSEL)
POPL ES /* fix up ES */
PUSHL FS /* save the rest of the Ureg struct */
PUSHL GS
PUSHAL
PUSHL SP /* Ureg* argument to trap */
CALL trap(SB)
TEXT forkret(SB), $0
POPL AX
POPAL
TEXT _forkretpopgs(SB), $0
POPL GS
TEXT _forkretpopfs(SB), $0
POPL FS
TEXT _forkretpopes(SB), $0
POPL ES
TEXT _forkretpopds(SB), $0
POPL DS
ADDL $8, SP /* pop error code and trap type */
TEXT _forkretiret(SB), $0
IRETL
/*
* This is merely _strayintr optimised to vector
* to syscall() without going through trap().
*/
TEXT _syscallintr(SB), $0
PUSHL $VectorSYSCALL /* trap type */
PUSHL DS
PUSHL ES
PUSHL FS
PUSHL GS
PUSHAL
MOVL $(KDSEL), AX
MOVW AX, DS
MOVW AX, ES
PUSHL SP /* Ureg* argument to syscall */
PUSHL $forkret(SB) /* return pc */
JMPF syscall(SB)
TEXT vectortable(SB), $0
CALL _strayintr(SB); BYTE $0x00 /* divide error */
CALL _strayintr(SB); BYTE $0x01 /* debug exception */
CALL _strayintr(SB); BYTE $0x02 /* NMI interrupt */
CALL _strayintr(SB); BYTE $0x03 /* breakpoint */
CALL _strayintr(SB); BYTE $0x04 /* overflow */
CALL _strayintr(SB); BYTE $0x05 /* bound */
CALL _strayintr(SB); BYTE $0x06 /* invalid opcode */
CALL _strayintr(SB); BYTE $0x07 /* no coprocessor available */
CALL _strayintrx(SB); BYTE $0x08 /* double fault */
CALL _strayintr(SB); BYTE $0x09 /* coprocessor segment overflow */
CALL _strayintrx(SB); BYTE $0x0A /* invalid TSS */
CALL _strayintrx(SB); BYTE $0x0B /* segment not available */
CALL _strayintrx(SB); BYTE $0x0C /* stack exception */
CALL _strayintrx(SB); BYTE $0x0D /* general protection error */
CALL _strayintrx(SB); BYTE $0x0E /* page fault */
CALL _strayintr(SB); BYTE $0x0F /* */
CALL _strayintr(SB); BYTE $0x10 /* coprocessor error */
CALL _strayintrx(SB); BYTE $0x11 /* alignment check */
CALL _strayintr(SB); BYTE $0x12 /* machine check */
CALL _strayintr(SB); BYTE $0x13 /* simd error */
CALL _strayintr(SB); BYTE $0x14
CALL _strayintr(SB); BYTE $0x15
CALL _strayintr(SB); BYTE $0x16
CALL _strayintr(SB); BYTE $0x17
CALL _strayintr(SB); BYTE $0x18
CALL _strayintr(SB); BYTE $0x19
CALL _strayintr(SB); BYTE $0x1A
CALL _strayintr(SB); BYTE $0x1B
CALL _strayintr(SB); BYTE $0x1C
CALL _strayintr(SB); BYTE $0x1D
CALL _strayintr(SB); BYTE $0x1E
CALL _strayintr(SB); BYTE $0x1F
CALL _strayintr(SB); BYTE $0x20 /* VectorLAPIC */
CALL _strayintr(SB); BYTE $0x21
CALL _strayintr(SB); BYTE $0x22
CALL _strayintr(SB); BYTE $0x23
CALL _strayintr(SB); BYTE $0x24
CALL _strayintr(SB); BYTE $0x25
CALL _strayintr(SB); BYTE $0x26
CALL _strayintr(SB); BYTE $0x27
CALL _strayintr(SB); BYTE $0x28
CALL _strayintr(SB); BYTE $0x29
CALL _strayintr(SB); BYTE $0x2A
CALL _strayintr(SB); BYTE $0x2B
CALL _strayintr(SB); BYTE $0x2C
CALL _strayintr(SB); BYTE $0x2D
CALL _strayintr(SB); BYTE $0x2E
CALL _strayintr(SB); BYTE $0x2F
CALL _strayintr(SB); BYTE $0x30
CALL _strayintr(SB); BYTE $0x31
CALL _strayintr(SB); BYTE $0x32
CALL _strayintr(SB); BYTE $0x33
CALL _strayintr(SB); BYTE $0x34
CALL _strayintr(SB); BYTE $0x35
CALL _strayintr(SB); BYTE $0x36
CALL _strayintr(SB); BYTE $0x37
CALL _strayintr(SB); BYTE $0x38
CALL _strayintr(SB); BYTE $0x39
CALL _strayintr(SB); BYTE $0x3A
CALL _strayintr(SB); BYTE $0x3B
CALL _strayintr(SB); BYTE $0x3C
CALL _strayintr(SB); BYTE $0x3D
CALL _strayintr(SB); BYTE $0x3E
CALL _strayintr(SB); BYTE $0x3F
CALL _syscallintr(SB); BYTE $0x40 /* VectorSYSCALL */
CALL _strayintr(SB); BYTE $0x41
CALL _strayintr(SB); BYTE $0x42
CALL _strayintr(SB); BYTE $0x43
CALL _strayintr(SB); BYTE $0x44
CALL _strayintr(SB); BYTE $0x45
CALL _strayintr(SB); BYTE $0x46
CALL _strayintr(SB); BYTE $0x47
CALL _strayintr(SB); BYTE $0x48
CALL _strayintr(SB); BYTE $0x49
CALL _strayintr(SB); BYTE $0x4A
CALL _strayintr(SB); BYTE $0x4B
CALL _strayintr(SB); BYTE $0x4C
CALL _strayintr(SB); BYTE $0x4D
CALL _strayintr(SB); BYTE $0x4E
CALL _strayintr(SB); BYTE $0x4F
CALL _strayintr(SB); BYTE $0x50
CALL _strayintr(SB); BYTE $0x51
CALL _strayintr(SB); BYTE $0x52
CALL _strayintr(SB); BYTE $0x53
CALL _strayintr(SB); BYTE $0x54
CALL _strayintr(SB); BYTE $0x55
CALL _strayintr(SB); BYTE $0x56
CALL _strayintr(SB); BYTE $0x57
CALL _strayintr(SB); BYTE $0x58
CALL _strayintr(SB); BYTE $0x59
CALL _strayintr(SB); BYTE $0x5A
CALL _strayintr(SB); BYTE $0x5B
CALL _strayintr(SB); BYTE $0x5C
CALL _strayintr(SB); BYTE $0x5D
CALL _strayintr(SB); BYTE $0x5E
CALL _strayintr(SB); BYTE $0x5F
CALL _strayintr(SB); BYTE $0x60
CALL _strayintr(SB); BYTE $0x61
CALL _strayintr(SB); BYTE $0x62
CALL _strayintr(SB); BYTE $0x63
CALL _strayintr(SB); BYTE $0x64
CALL _strayintr(SB); BYTE $0x65
CALL _strayintr(SB); BYTE $0x66
CALL _strayintr(SB); BYTE $0x67
CALL _strayintr(SB); BYTE $0x68
CALL _strayintr(SB); BYTE $0x69
CALL _strayintr(SB); BYTE $0x6A
CALL _strayintr(SB); BYTE $0x6B
CALL _strayintr(SB); BYTE $0x6C
CALL _strayintr(SB); BYTE $0x6D
CALL _strayintr(SB); BYTE $0x6E
CALL _strayintr(SB); BYTE $0x6F
CALL _strayintr(SB); BYTE $0x70
CALL _strayintr(SB); BYTE $0x71
CALL _strayintr(SB); BYTE $0x72
CALL _strayintr(SB); BYTE $0x73
CALL _strayintr(SB); BYTE $0x74
CALL _strayintr(SB); BYTE $0x75
CALL _strayintr(SB); BYTE $0x76
CALL _strayintr(SB); BYTE $0x77
CALL _strayintr(SB); BYTE $0x78
CALL _strayintr(SB); BYTE $0x79
CALL _strayintr(SB); BYTE $0x7A
CALL _strayintr(SB); BYTE $0x7B
CALL _strayintr(SB); BYTE $0x7C
CALL _strayintr(SB); BYTE $0x7D
CALL _strayintr(SB); BYTE $0x7E
CALL _strayintr(SB); BYTE $0x7F
CALL _strayintr(SB); BYTE $0x80 /* Vector[A]PIC */
CALL _strayintr(SB); BYTE $0x81
CALL _strayintr(SB); BYTE $0x82
CALL _strayintr(SB); BYTE $0x83
CALL _strayintr(SB); BYTE $0x84
CALL _strayintr(SB); BYTE $0x85
CALL _strayintr(SB); BYTE $0x86
CALL _strayintr(SB); BYTE $0x87
CALL _strayintr(SB); BYTE $0x88
CALL _strayintr(SB); BYTE $0x89
CALL _strayintr(SB); BYTE $0x8A
CALL _strayintr(SB); BYTE $0x8B
CALL _strayintr(SB); BYTE $0x8C
CALL _strayintr(SB); BYTE $0x8D
CALL _strayintr(SB); BYTE $0x8E
CALL _strayintr(SB); BYTE $0x8F
CALL _strayintr(SB); BYTE $0x90
CALL _strayintr(SB); BYTE $0x91
CALL _strayintr(SB); BYTE $0x92
CALL _strayintr(SB); BYTE $0x93
CALL _strayintr(SB); BYTE $0x94
CALL _strayintr(SB); BYTE $0x95
CALL _strayintr(SB); BYTE $0x96
CALL _strayintr(SB); BYTE $0x97
CALL _strayintr(SB); BYTE $0x98
CALL _strayintr(SB); BYTE $0x99
CALL _strayintr(SB); BYTE $0x9A
CALL _strayintr(SB); BYTE $0x9B
CALL _strayintr(SB); BYTE $0x9C
CALL _strayintr(SB); BYTE $0x9D
CALL _strayintr(SB); BYTE $0x9E
CALL _strayintr(SB); BYTE $0x9F
CALL _strayintr(SB); BYTE $0xA0
CALL _strayintr(SB); BYTE $0xA1
CALL _strayintr(SB); BYTE $0xA2
CALL _strayintr(SB); BYTE $0xA3
CALL _strayintr(SB); BYTE $0xA4
CALL _strayintr(SB); BYTE $0xA5
CALL _strayintr(SB); BYTE $0xA6
CALL _strayintr(SB); BYTE $0xA7
CALL _strayintr(SB); BYTE $0xA8
CALL _strayintr(SB); BYTE $0xA9
CALL _strayintr(SB); BYTE $0xAA
CALL _strayintr(SB); BYTE $0xAB
CALL _strayintr(SB); BYTE $0xAC
CALL _strayintr(SB); BYTE $0xAD
CALL _strayintr(SB); BYTE $0xAE
CALL _strayintr(SB); BYTE $0xAF
CALL _strayintr(SB); BYTE $0xB0
CALL _strayintr(SB); BYTE $0xB1
CALL _strayintr(SB); BYTE $0xB2
CALL _strayintr(SB); BYTE $0xB3
CALL _strayintr(SB); BYTE $0xB4
CALL _strayintr(SB); BYTE $0xB5
CALL _strayintr(SB); BYTE $0xB6
CALL _strayintr(SB); BYTE $0xB7
CALL _strayintr(SB); BYTE $0xB8
CALL _strayintr(SB); BYTE $0xB9
CALL _strayintr(SB); BYTE $0xBA
CALL _strayintr(SB); BYTE $0xBB
CALL _strayintr(SB); BYTE $0xBC
CALL _strayintr(SB); BYTE $0xBD
CALL _strayintr(SB); BYTE $0xBE
CALL _strayintr(SB); BYTE $0xBF
CALL _strayintr(SB); BYTE $0xC0
CALL _strayintr(SB); BYTE $0xC1
CALL _strayintr(SB); BYTE $0xC2
CALL _strayintr(SB); BYTE $0xC3
CALL _strayintr(SB); BYTE $0xC4
CALL _strayintr(SB); BYTE $0xC5
CALL _strayintr(SB); BYTE $0xC6
CALL _strayintr(SB); BYTE $0xC7
CALL _strayintr(SB); BYTE $0xC8
CALL _strayintr(SB); BYTE $0xC9
CALL _strayintr(SB); BYTE $0xCA
CALL _strayintr(SB); BYTE $0xCB
CALL _strayintr(SB); BYTE $0xCC
CALL _strayintr(SB); BYTE $0xCD
CALL _strayintr(SB); BYTE $0xCE
CALL _strayintr(SB); BYTE $0xCF
CALL _strayintr(SB); BYTE $0xD0
CALL _strayintr(SB); BYTE $0xD1
CALL _strayintr(SB); BYTE $0xD2
CALL _strayintr(SB); BYTE $0xD3
CALL _strayintr(SB); BYTE $0xD4
CALL _strayintr(SB); BYTE $0xD5
CALL _strayintr(SB); BYTE $0xD6
CALL _strayintr(SB); BYTE $0xD7
CALL _strayintr(SB); BYTE $0xD8
CALL _strayintr(SB); BYTE $0xD9
CALL _strayintr(SB); BYTE $0xDA
CALL _strayintr(SB); BYTE $0xDB
CALL _strayintr(SB); BYTE $0xDC
CALL _strayintr(SB); BYTE $0xDD
CALL _strayintr(SB); BYTE $0xDE
CALL _strayintr(SB); BYTE $0xDF
CALL _strayintr(SB); BYTE $0xE0
CALL _strayintr(SB); BYTE $0xE1
CALL _strayintr(SB); BYTE $0xE2
CALL _strayintr(SB); BYTE $0xE3
CALL _strayintr(SB); BYTE $0xE4
CALL _strayintr(SB); BYTE $0xE5
CALL _strayintr(SB); BYTE $0xE6
CALL _strayintr(SB); BYTE $0xE7
CALL _strayintr(SB); BYTE $0xE8
CALL _strayintr(SB); BYTE $0xE9
CALL _strayintr(SB); BYTE $0xEA
CALL _strayintr(SB); BYTE $0xEB
CALL _strayintr(SB); BYTE $0xEC
CALL _strayintr(SB); BYTE $0xED
CALL _strayintr(SB); BYTE $0xEE
CALL _strayintr(SB); BYTE $0xEF
CALL _strayintr(SB); BYTE $0xF0
CALL _strayintr(SB); BYTE $0xF1
CALL _strayintr(SB); BYTE $0xF2
CALL _strayintr(SB); BYTE $0xF3
CALL _strayintr(SB); BYTE $0xF4
CALL _strayintr(SB); BYTE $0xF5
CALL _strayintr(SB); BYTE $0xF6
CALL _strayintr(SB); BYTE $0xF7
CALL _strayintr(SB); BYTE $0xF8
CALL _strayintr(SB); BYTE $0xF9
CALL _strayintr(SB); BYTE $0xFA
CALL _strayintr(SB); BYTE $0xFB
CALL _strayintr(SB); BYTE $0xFC
CALL _strayintr(SB); BYTE $0xFD
CALL _strayintr(SB); BYTE $0xFE
CALL _strayintr(SB); BYTE $0xFF
|
9front/9front
| 3,134
|
sys/src/9/pc/apbootstrap.s
|
/*
* Start an Application Processor. This must be placed on a 4KB boundary
* somewhere in the 1st MB of conventional memory (APBOOTSTRAP). However,
* due to some shortcuts below it's restricted further to within the 1st
* 64KB. The AP starts in real-mode, with
* CS selector set to the startup memory address/16;
* CS base set to startup memory address;
* CS limit set to 64KB;
* CPL and IP set to 0.
*/
#include "mem.h"
#define NOP BYTE $0x90 /* NOP */
#define LGDT(gdtptr) BYTE $0x0F; /* LGDT */ \
BYTE $0x01; BYTE $0x16; \
WORD $gdtptr
#define FARJUMP16(s, o) BYTE $0xEA; /* far jump to ptr16:16 */ \
WORD $o; WORD $s; \
NOP; NOP; NOP
#define FARJUMP32(s, o) BYTE $0x66; /* far jump to ptr32:16 */ \
BYTE $0xEA; LONG $o; WORD $s
#define DELAY BYTE $0xEB; /* JMP .+2 */ \
BYTE $0x00
#define INVD BYTE $0x0F; BYTE $0x08
#define WBINVD BYTE $0x0F; BYTE $0x09
/*
* Macros for calculating offsets within the page directory base
* and page tables. Note that these are assembler-specific hence
* the '<<2'.
*/
#define PDO(a) (((((a))>>22) & 0x03FF)<<2)
#define PTO(a) (((((a))>>12) & 0x03FF)<<2)
TEXT apbootstrap(SB), $0
FARJUMP16(0, _apbootstrap(SB))
TEXT _apvector(SB), $0 /* address APBOOTSTRAP+0x08 */
LONG $0
TEXT _appdb(SB), $0 /* address APBOOTSTRAP+0x0C */
LONG $0
TEXT _apapic(SB), $0 /* address APBOOTSTRAP+0x10 */
LONG $0
TEXT _apbootstrap(SB), $0 /* address APBOOTSTRAP+0x14 */
MOVW CS, AX
MOVW AX, DS /* initialise DS */
LGDT(gdtptr(SB)) /* load a basic gdt */
MOVL CR0, AX
ORL $1, AX
MOVL AX, CR0 /* turn on protected mode */
DELAY /* JMP .+2 */
BYTE $0xB8; WORD $SELECTOR(1, SELGDT, 0)/* MOVW $SELECTOR(1, SELGDT, 0), AX */
MOVW AX, DS
MOVW AX, ES
MOVW AX, FS
MOVW AX, GS
MOVW AX, SS
FARJUMP32(SELECTOR(2, SELGDT, 0), _ap32-KZERO(SB))
/*
* For Pentiums and higher, the code that enables paging must come from
* pages that are identity mapped.
* To this end double map KZERO at virtual 0 and undo the mapping once virtual
* nirvana has been obtained.
*/
TEXT _ap32(SB), $0
MOVL _appdb-KZERO(SB), CX /* physical address of PDB */
MOVL (PDO(KZERO))(CX), DX /* double-map KZERO at 0 */
MOVL DX, (PDO(0))(CX)
MOVL CX, CR3 /* load and flush the mmu */
MOVL CR4, AX
ANDL $~0x00000020, AX /* ~PAE */
ORL $0x00000010, AX /* PSE */
MOVL AX, CR4
MOVL CR0, DX
ORL $0x80010000, DX /* PG|WP */
ANDL $~0x6000000A, DX /* ~(CD|NW|TS|MP) */
MOVL $_appg(SB), AX
MOVL DX, CR0 /* turn on paging */
JMP* AX
TEXT _appg(SB), $0
MOVL CX, AX /* physical address of PDB */
ORL $KZERO, AX
MOVL $0, (PDO(0))(AX) /* undo double-map of KZERO at 0 */
MOVL CX, CR3 /* load and flush the mmu */
MOVL $(MACHADDR+MACHSIZE-4), SP
MOVL $0, AX
PUSHL AX
POPFL
MOVL _apapic(SB), AX
MOVL AX, (SP)
MOVL _apvector(SB), AX
CALL* AX
_aphalt:
HLT
JMP _aphalt
TEXT gdt(SB), $0
LONG $0x0000; LONG $0
LONG $0xFFFF; LONG $(SEGG|SEGB|(0xF<<16)|SEGP|SEGPL(0)|SEGDATA|SEGW)
LONG $0xFFFF; LONG $(SEGG|SEGD|(0xF<<16)|SEGP|SEGPL(0)|SEGEXEC|SEGR)
TEXT gdtptr(SB), $0
WORD $(3*8-1)
LONG $gdt-KZERO(SB)
|
9front/9front
| 1,117
|
sys/src/9/pc/rebootcode.s
|
#include "mem.h"
/*
* Turn off MMU, then memmove the new kernel to its correct location
* in physical memory. Then jumps the to start of the kernel.
*/
TEXT main(SB),$0
MOVL p1+0(FP), DI /* destination */
MOVL DI, AX /* entry point */
MOVL p2+4(FP), SI /* source */
MOVL n+8(FP), CX /* byte count */
/*
* disable paging
*/
MOVL CR0, DX
ANDL $~0x80000000, DX /* ~(PG) */
MOVL DX, CR0
MOVL $0, DX
MOVL DX, CR3
/* stack below entry point */
MOVL AX, SP
/* park cpu for zero entry point */
ORL AX, AX
JZ _idle
/*
* the source and destination may overlap.
* determine whether to copy forward or backwards
*/
CMPL SI, DI
JGT _forward
MOVL SI, DX
ADDL CX, DX
CMPL DX, DI
JGT _back
_forward:
CLD
REP; MOVSB
JMP _startkernel
_back:
ADDL CX, DI
ADDL CX, SI
SUBL $1, DI
SUBL $1, SI
STD
REP; MOVSB
JMP _startkernel
/*
* JMP to kernel entry point. Note the true kernel entry point is
* the virtual address KZERO|AX, but this must wait until
* the MMU is enabled by the kernel in l.s
*/
_startkernel:
ORL AX, AX /* NOP: avoid link bug */
JMP* AX
_idle:
HLT
JMP _idle
|
9front/9front
| 4,910
|
sys/src/9/bcm/cache.v7.s
|
/*
* cortex arm arch v7 cache flushing and invalidation
* shared by l.s and rebootcode.s
*/
#define BPIALL MCR CpSC, 0, R0, C(CpCACHE), C(5), 6 /* branch predictor invalidate all */
TEXT cacheiinv(SB), $-4 /* I invalidate */
DSB
MOVW $0, R0
MCR CpSC, 0, R0, C(CpCACHE), C(CpCACHEinvi), CpCACHEall /* ok on cortex */
BPIALL /* redundant? */
DSB
ISB
RET
TEXT cacheiinvse(SB), $0 /* I invalidate SE */
MOVW 4(FP), R1
ADD R0, R1
BIC $(ICACHELINESZ - 1), R0
DSB
_iinvse:
MCR CpSC, 0, R0, C(CpCACHE), C(CpCACHEinvi), CpCACHEse
ADD $ICACHELINESZ, R0
CMP.S R0, R1
BGT _iinvse
BPIALL
DSB
ISB
RET
/*
* set/way operators, passed a suitable set/way value in R0.
*/
TEXT cachedwb_sw(SB), $-4
MCR CpSC, 0, R0, C(CpCACHE), C(CpCACHEwb), CpCACHEsi
RET
TEXT cachedwbinv_sw(SB), $-4
MCR CpSC, 0, R0, C(CpCACHE), C(CpCACHEwbi), CpCACHEsi
RET
TEXT cachedinv_sw(SB), $-4
MCR CpSC, 0, R0, C(CpCACHE), C(CpCACHEinvd), CpCACHEsi
RET
/* set cache size select */
TEXT setcachelvl(SB), $-4
MCR CpSC, CpIDcssel, R0, C(CpID), C(CpIDidct), 0
ISB
RET
/* return cache sizes */
TEXT getwayssets(SB), $-4
MRC CpSC, CpIDcsize, R0, C(CpID), C(CpIDidct), 0
RET
/*
* l1 cache operations.
* l1 and l2 ops are intended to be called from C, thus need save no
* caller's regs, only those we need to preserve across calls.
*/
TEXT cachedwb(SB), $-4
MOVW.W R14, -8(R13)
MOVW $cachedwb_sw(SB), R0
MOVW $1, R8
BL wholecache(SB)
MOVW.P 8(R13), R15
TEXT cachedwbinv(SB), $-4
MOVW.W R14, -8(R13)
MOVW $cachedwbinv_sw(SB), R0
MOVW $1, R8
BL wholecache(SB)
MOVW.P 8(R13), R15
TEXT cachedinv(SB), $-4
MOVW.W R14, -8(R13)
MOVW $cachedinv_sw(SB), R0
MOVW $1, R8
BL wholecache(SB)
MOVW.P 8(R13), R15
TEXT cacheuwbinv(SB), $-4
MOVM.DB.W [R14], (R13) /* save lr on stack */
MOVW CPSR, R1
CPSID /* splhi */
MOVM.DB.W [R1], (R13) /* save R1 on stack */
BL cachedwbinv(SB)
BL cacheiinv(SB)
MOVM.IA.W (R13), [R1] /* restore R1 (saved CPSR) */
MOVW R1, CPSR
MOVM.IA.W (R13), [R14] /* restore lr */
RET
/*
* l2 cache operations
*/
TEXT l2cacheuwb(SB), $-4
MOVW.W R14, -8(R13)
MOVW $cachedwb_sw(SB), R0
MOVW $2, R8
BL wholecache(SB)
MOVW.P 8(R13), R15
TEXT l2cacheuwbinv(SB), $-4
MOVW.W R14, -8(R13)
MOVW CPSR, R1
CPSID /* splhi */
MOVM.DB.W [R1], (R13) /* save R1 on stack */
MOVW $cachedwbinv_sw(SB), R0
MOVW $2, R8
BL wholecache(SB)
BL l2cacheuinv(SB)
MOVM.IA.W (R13), [R1] /* restore R1 (saved CPSR) */
MOVW R1, CPSR
MOVW.P 8(R13), R15
TEXT l2cacheuinv(SB), $-4
MOVW.W R14, -8(R13)
MOVW $cachedinv_sw(SB), R0
MOVW $2, R8
BL wholecache(SB)
MOVW.P 8(R13), R15
/*
* callers are assumed to be the above l1 and l2 ops.
* R0 is the function to call in the innermost loop.
* R8 is the cache level (one-origin: 1 or 2).
*
* initial translation by 5c, then massaged by hand.
*/
TEXT wholecache+0(SB), $-4
MOVW R0, R1 /* save argument for inner loop in R1 */
SUB $1, R8 /* convert cache level to zero origin */
/* we may not have the MMU on yet, so map R1 to PC's space */
BIC $KSEGM, R1 /* strip segment from address */
MOVW PC, R2 /* get PC's segment ... */
AND $KSEGM, R2
ORR R2, R1 /* combine them */
/* drain write buffers */
BARRIERS
MCR CpSC, 0, R0, C(CpCACHE), C(CpCACHEwb), CpCACHEwait
ISB
MOVW CPSR, R2
MOVM.DB.W [R2,R14], (SP) /* save regs on stack */
CPSID /* splhi to make entire op atomic */
/* get cache sizes */
SLL $1, R8, R0 /* R0 = (cache - 1) << 1 */
MCR CpSC, CpIDcssel, R0, C(CpID), C(CpIDidct), 0 /* set cache size select */
ISB
MRC CpSC, CpIDcsize, R0, C(CpID), C(CpIDidct), 0 /* get cache sizes */
/* compute # of ways and sets for this cache level */
SRA $3, R0, R5 /* R5 (ways) = R0 >> 3 */
AND $1023, R5 /* R5 = (R0 >> 3) & MASK(10) */
ADD $1, R5 /* R5 (ways) = ((R0 >> 3) & MASK(10)) + 1 */
SRA $13, R0, R2 /* R2 = R0 >> 13 */
AND $32767, R2 /* R2 = (R0 >> 13) & MASK(15) */
ADD $1, R2 /* R2 (sets) = ((R0 >> 13) & MASK(15)) + 1 */
/* precompute set/way shifts for inner loop */
MOVW $6, R4
CMP $0, R8 /* cache == 1? */
MOVW.EQ $30, R3 /* l1 */
MOVW.NE $29, R3 /* l2 */
CMP $16, R5 /* armv8 has 16-way l2, adjust shift */
MOVW.EQ $28, R3
/* iterate over ways */
MOVW $0, R7 /* R7: way */
outer:
/* iterate over sets */
MOVW $0, R6 /* R6: set */
inner:
/* compute set/way register contents */
SLL R3, R7, R0 /* R0 = way << R3 (L?WAYSH) */
ORR R8<<1, R0 /* R0 = way << L?WAYSH | (cache - 1) << 1 */
ORR R6<<R4, R0 /* R0 = way<<L?WAYSH | (cache-1)<<1 |set<<R4 */
BL (R1) /* call set/way operation with R0 */
ADD $1, R6 /* set++ */
CMP R2, R6 /* set >= sets? */
BLT inner /* no, do next set */
ADD $1, R7 /* way++ */
CMP R5, R7 /* way >= ways? */
BLT outer /* no, do next way */
MOVM.IA.W (SP), [R2,R14] /* restore regs */
MOVW R2, CPSR /* splx */
/* drain write buffers */
MCR CpSC, 0, R0, C(CpCACHE), C(CpCACHEwb), CpCACHEwait
ISB
RET
|
9front/9front
| 1,136
|
sys/src/9/bcm/arm.s
|
/*
* armv6/v7 machine assist, definitions
*
* loader uses R11 as scratch.
*/
#include "mem.h"
#include "arm.h"
#define PADDR(va) (PHYSDRAM | ((va) & ~KSEGM))
#define L1X(va) (((((va))>>20) & 0x0fff)<<2)
/*
* new instructions
*/
#define ISB \
MOVW $0, R0; \
MCR CpSC, 0, R0, C(CpCACHE), C(CpCACHEinvi), CpCACHEwait
#define DSB \
MOVW $0, R0; \
MCR CpSC, 0, R0, C(CpCACHE), C(CpCACHEwb), CpCACHEwait
#define BARRIERS DSB; ISB
#define MCRR(coproc, op, rd, rn, crm) \
WORD $(0xec400000|(rn)<<16|(rd)<<12|(coproc)<<8|(op)<<4|(crm))
#define MRRC(coproc, op, rd, rn, crm) \
WORD $(0xec500000|(rn)<<16|(rd)<<12|(coproc)<<8|(op)<<4|(crm))
#define MSR(R, rn, m, m1) \
WORD $(0xe120f200|(R)<<22|(m1)<<16|(m)<<8|(rn))
#define CPSIE WORD $0xf1080080 /* intr enable: zeroes I bit */
#define CPSID WORD $0xf10c0080 /* intr disable: sets I bit */
#define OKAY \
MOVW $0x7E200028,R2; \
MOVW $0x10000,R3; \
MOVW R3,(R2)
/*
* get cpu id, or zero if armv6
*/
#define CPUID(r) \
MRC CpSC, 0, r, C(CpID), C(CpIDfeat), 7; \
CMP $0, r; \
B.EQ 2(PC); \
MRC CpSC, 0, r, C(CpID), C(CpIDidct), CpIDmpid; \
AND.S $(MAXMACH-1), r
|
9front/9front
| 10,515
|
sys/src/9/bcm/armv7.s
|
/*
* Broadcom bcm2836 SoC, as used in Raspberry Pi 2
* 4 x Cortex-A7 processor (armv7)
*/
#include "arm.s"
#define CACHELINESZ 64
#define ICACHELINESZ 32
#undef DSB
#undef DMB
#undef ISB
#define DSB WORD $0xf57ff04f /* data synch. barrier; last f = SY */
#define DMB WORD $0xf57ff05f /* data mem. barrier; last f = SY */
#define ISB WORD $0xf57ff06f /* instr. sync. barrier; last f = SY */
#define WFI WORD $0xe320f003 /* wait for interrupt */
#define WFI_EQ WORD $0x0320f003 /* wait for interrupt if eq */
#define ERET WORD $0xe160006e /* exception return from HYP */
#define SEV WORD $0xe320f004 /* send event */
/* tas/cas strex debugging limits; started at 10000 */
#define MAXSC 1000000
TEXT armstart(SB), 1, $-4
/*
* if not cpu0, go to secondary startup
*/
CPUID(R1)
BNE reset
/*
* go to SVC mode, interrupts disabled
*/
BL svcmode(SB)
/*
* disable the mmu and caches
*/
MRC CpSC, 0, R1, C(CpCONTROL), C(0), CpMainctl
BIC $(CpCdcache|CpCicache|CpCmmu), R1
ORR $(CpCsbo|CpCsw), R1
BIC $CpCsbz, R1
MCR CpSC, 0, R1, C(CpCONTROL), C(0), CpMainctl
BARRIERS
/*
* turn SMP off
*/
MRC CpSC, 0, R1, C(CpCONTROL), C(0), CpAuxctl
BIC $CpACsmp, R1
MCR CpSC, 0, R1, C(CpCONTROL), C(0), CpAuxctl
BARRIERS
/*
* clear mach and page tables
*/
MOVW $PADDR(MACHADDR), R1
MOVW $PADDR(KTZERO), R2
MOVW $0, R0
_ramZ:
MOVW R0, (R1)
ADD $4, R1
CMP R1, R2
BNE _ramZ
/*
* start stack at top of mach (physical addr)
* set up page tables for kernel
*/
MOVW $PADDR(MACHADDR+MACHSIZE-4), R13
MOVW $PADDR(L1), R0
BL mmuinit(SB)
BL mmuinvalidate(SB)
/*
* set up domain access control and page table base
*/
MOVW $Client, R1
MCR CpSC, 0, R1, C(CpDAC), C(0)
MOVW $PADDR(L1), R1
ORR $(CpTTBs|CpTTBowba|CpTTBiwba), R1
MCR CpSC, 0, R1, C(CpTTB), C(0)
MCR CpSC, 0, R1, C(CpTTB), C(0), CpTTB1 /* cortex has two */
/*
* invalidate my caches before enabling
*/
BL cachedinv(SB)
BL cacheiinv(SB)
BL l2cacheuinv(SB)
BARRIERS
/*
* turn SMP on
*/
MRC CpSC, 0, R1, C(CpCONTROL), C(0), CpAuxctl
ORR $CpACsmp, R1
MCR CpSC, 0, R1, C(CpCONTROL), C(0), CpAuxctl
BARRIERS
/*
* enable caches, mmu, and high vectors
*/
MRC CpSC, 0, R0, C(CpCONTROL), C(0), CpMainctl
ORR $(CpChv|CpCdcache|CpCicache|CpCmmu), R0
MCR CpSC, 0, R0, C(CpCONTROL), C(0), CpMainctl
BARRIERS
/*
* switch SB, SP, and PC into KZERO space
*/
MOVW $setR12(SB), R12
MOVW $(MACHADDR+MACHSIZE-4), R13
MOVW $_startpg(SB), R15
TEXT _startpg(SB), 1, $-4
/*
* enable cycle counter
*/
MOVW $(1<<31), R1
MCR CpSC, 0, R1, C(CpCLD), C(CpCLDena), CpCLDenacyc
MOVW $1, R1
MCR CpSC, 0, R1, C(CpCLD), C(CpCLDena), CpCLDenapmnc
/* first arg to main is saved R2 */
MOVW R10, R0
/*
* call main and loop forever if it returns
*/
BL ,main(SB)
B ,0(PC)
BL _div(SB) /* hack to load _div, etc. */
/*
* startup entry for cpu(s) other than 0
*/
TEXT cpureset(SB), 1, $-4
reset:
/*
* load physical base for SB addressing while mmu is off
*/
MOVW $setR12(SB), R12
SUB $KZERO, R12
ADD $PHYSDRAM, R12
/*
* SVC mode, interrupts disabled
*/
BL svcmode(SB)
/*
* disable the mmu and caches
*/
MRC CpSC, 0, R1, C(CpCONTROL), C(0), CpMainctl
BIC $(CpCdcache|CpCicache|CpCmmu), R1
ORR $(CpCsbo|CpCsw), R1
BIC $CpCsbz, R1
MCR CpSC, 0, R1, C(CpCONTROL), C(0), CpMainctl
BARRIERS
/*
* turn SMP off
*/
MRC CpSC, 0, R1, C(CpCONTROL), C(0), CpAuxctl
BIC $CpACsmp, R1
MCR CpSC, 0, R1, C(CpCONTROL), C(0), CpAuxctl
BARRIERS
/*
* find Mach for this cpu
*/
MRC CpSC, 0, R2, C(CpID), C(CpIDidct), CpIDmpid
AND $(MAXMACH-1), R2 /* mask out non-cpu-id bits */
SLL $2, R2 /* convert to word index */
MOVW $machaddr(SB), R0
BIC $KSEGM, R0
ORR $PHYSDRAM, R0
ADD R2, R0 /* R0 = &machaddr[cpuid] */
MOVW (R0), R0 /* R0 = machaddr[cpuid] */
CMP $0, R0
BEQ 0(PC) /* must not be zero */
SUB $KZERO, R0, R(MACH) /* m = PADDR(machaddr[cpuid]) */
/*
* start stack at top of local Mach
*/
ADD $(MACHSIZE-4), R(MACH), R13
BL mmuinvalidate(SB)
/*
* set up domain access control and page table base
*/
MOVW $Client, R1
MCR CpSC, 0, R1, C(CpDAC), C(0)
MOVW 12(R(MACH)), R1 /* m->mmul1 */
SUB $KZERO, R1 /* phys addr */
ORR $(CpTTBs|CpTTBowba|CpTTBiwba), R1
MCR CpSC, 0, R1, C(CpTTB), C(0)
MCR CpSC, 0, R1, C(CpTTB), C(0), CpTTB1 /* cortex has two */
/*
* invalidate my caches before enabling
*/
BL cachedinv(SB)
BL cacheiinv(SB)
BARRIERS
/*
* turn SMP on
*/
MRC CpSC, 0, R1, C(CpCONTROL), C(0), CpAuxctl
ORR $CpACsmp, R1
MCR CpSC, 0, R1, C(CpCONTROL), C(0), CpAuxctl
BARRIERS
/*
* enable caches, mmu, and high vectors
*/
MRC CpSC, 0, R0, C(CpCONTROL), C(0), CpMainctl
ORR $(CpChv|CpCdcache|CpCicache|CpCmmu), R0
MCR CpSC, 0, R0, C(CpCONTROL), C(0), CpMainctl
BARRIERS
/*
* switch MACH, SB, SP, and PC into KZERO space
*/
ADD $KZERO, R(MACH)
MOVW $setR12(SB), R12
ADD $KZERO, R13
MOVW $_startpg2(SB), R15
TEXT _startpg2(SB), 1, $-4
/*
* enable cycle counter
*/
MOVW $(1<<31), R1
MCR CpSC, 0, R1, C(CpCLD), C(CpCLDena), CpCLDenacyc
MOVW $1, R1
MCR CpSC, 0, R1, C(CpCLD), C(CpCLDena), CpCLDenapmnc
/*
* call cpustart and loop forever if it returns
*/
MRC CpSC, 0, R0, C(CpID), C(CpIDidct), CpIDmpid
AND $(MAXMACH-1), R0 /* mask out non-cpu-id bits */
BL ,cpustart(SB)
B ,0(PC)
/*
* get into SVC mode with interrupts disabled
* raspberry pi firmware since 29 Sept 2015 starts in HYP mode
*/
TEXT svcmode(SB), 1, $-4
MOVW CPSR, R1
AND $PsrMask, R1
MOVW $PsrMhyp, R2
CMP R2, R1
MOVW $(PsrDirq|PsrDfiq|PsrMsvc), R1
BNE nothyp
MSR(1, 1, 1, 0xe) /* MOVW R1, SPSR_HYP */
MSR(0, 14, 1, 0xe) /* MOVW R14, ELR_HYP */
ERET
nothyp:
MOVW R1, CPSR
RET
TEXT cpidget(SB), 1, $-4 /* main ID */
MRC CpSC, 0, R0, C(CpID), C(0), CpIDid
RET
TEXT fsrget(SB), 1, $-4 /* data fault status */
MRC CpSC, 0, R0, C(CpFSR), C(0), CpFSRdata
RET
TEXT ifsrget(SB), 1, $-4 /* instruction fault status */
MRC CpSC, 0, R0, C(CpFSR), C(0), CpFSRinst
RET
TEXT farget(SB), 1, $-4 /* fault address */
MRC CpSC, 0, R0, C(CpFAR), C(0x0)
RET
TEXT cpctget(SB), 1, $-4 /* cache type */
MRC CpSC, 0, R0, C(CpID), C(CpIDidct), CpIDct
RET
TEXT lcycles(SB), 1, $-4
MRC CpSC, 0, R0, C(CpCLD), C(CpCLDcyc), 0
RET
TEXT splhi(SB), 1, $-4
MOVW R14, 4(R(MACH)) /* save caller pc in m->splpc */
MOVW CPSR, R0 /* turn off irqs (but not fiqs) */
ORR $(PsrDirq), R0, R1
MOVW R1, CPSR
RET
TEXT splfhi(SB), 1, $-4
MOVW R14, 4(R(MACH)) /* save caller pc in m->splpc */
MOVW CPSR, R0 /* turn off irqs and fiqs */
ORR $(PsrDirq|PsrDfiq), R0, R1
MOVW R1, CPSR
RET
TEXT splflo(SB), 1, $-4
MOVW CPSR, R0 /* turn on fiqs */
BIC $(PsrDfiq), R0, R1
MOVW R1, CPSR
RET
TEXT spllo(SB), 1, $-4
MOVW CPSR, R0 /* turn on irqs and fiqs */
MOVW $0, R1
CMP.S R1, R(MACH)
MOVW.NE R1, 4(R(MACH)) /* clear m->splpc */
BIC $(PsrDirq|PsrDfiq), R0, R1
MOVW R1, CPSR
RET
TEXT splx(SB), 1, $-4
MOVW R14, 4(R(MACH)) /* save caller pc in m->splpc */
MOVW R0, R1 /* reset interrupt level */
MOVW CPSR, R0
MOVW R1, CPSR
RET
TEXT spldone(SB), 1, $0 /* end marker for devkprof.c */
RET
TEXT islo(SB), 1, $-4
MOVW CPSR, R0
AND $(PsrDirq), R0
EOR $(PsrDirq), R0
RET
TEXT cas(SB), $0
TEXT cmpswap(SB), $0
MOVW ov+4(FP), R1
MOVW nv+8(FP), R2
spincas:
LDREX (R0), R3
CMP.S R3, R1
BNE fail
STREX R2, (R0), R4
CMP.S $0, R4
BNE spincas
MOVW $1, R0
DMB
RET
fail:
CLREX
MOVW $0, R0
RET
TEXT tas(SB), $-4
TEXT _tas(SB), $-4 /* _tas(ulong *) */
/* returns old (R0) after modifying (R0) */
MOVW R0,R5
DMB
MOVW $1,R2 /* new value of (R0) */
MOVW $MAXSC, R8
tas1:
LDREX (R5), R7
CMP.S $0, R7 /* old value non-zero (lock taken)? */
BNE lockbusy /* we lose */
SUB.S $1, R8
BEQ lockloop2
STREX R2,(R5),R4
CMP.S $0, R4
BNE tas1 /* strex failed? try again */
DMB
B tas0
lockloop2:
BL abort(SB)
lockbusy:
CLREX
tas0:
MOVW R7, R0 /* return old value */
RET
TEXT setlabel(SB), 1, $-4
MOVW R13, 0(R0) /* sp */
MOVW R14, 4(R0) /* pc */
MOVW $0, R0
RET
TEXT gotolabel(SB), 1, $-4
MOVW 0(R0), R13 /* sp */
MOVW 4(R0), R14 /* pc */
MOVW $1, R0
RET
TEXT getcallerpc(SB), 1, $-4
MOVW 0(R13), R0
RET
TEXT idlehands(SB), $-4
MOVW CPSR, R3
ORR $(PsrDirq|PsrDfiq), R3, R1 /* splfhi */
MOVW R1, CPSR
DSB
MOVW nrdy(SB), R0
CMP $0, R0
WFI_EQ
DSB
MOVW R3, CPSR /* splx */
RET
TEXT coherence(SB), $-4
BARRIERS
RET
TEXT sev(SB), $-4
SEV
RET
/*
* invalidate tlb
*/
TEXT mmuinvalidate(SB), 1, $-4
DSB
MOVW $0, R0
MCR CpSC, 0, R0, C(CpTLB), C(CpTLBinvu), CpTLBinv
BARRIERS
RET
/*
* mmuinvalidateaddr(va)
* invalidate tlb entry for virtual page address va, ASID 0
*/
TEXT mmuinvalidateaddr(SB), 1, $-4
DSB
MCR CpSC, 0, R0, C(CpTLB), C(CpTLBinvu), CpTLBinvse
BARRIERS
RET
/*
* `single-element' cache operations.
* in arm arch v7, if effective to PoC, they operate on all cache levels, so separate
* l2 functions are unnecessary.
*/
TEXT cachedwbse(SB), $-4 /* D writeback SE */
MOVW R0, R2
MOVW CPSR, R3
CPSID /* splhi */
BARRIERS /* force outstanding stores to cache */
MOVW R2, R0
MOVW 4(FP), R1
ADD R0, R1 /* R1 is end address */
BIC $(CACHELINESZ-1), R0 /* cache line start */
_dwbse:
MCR CpSC, 0, R0, C(CpCACHE), C(CpCACHEwb), CpCACHEse
/* can't have a BARRIER here since it zeroes R0 */
ADD $CACHELINESZ, R0
CMP.S R0, R1
BGT _dwbse
B _wait
/*
* TLB on armv7 loads from cache, so no need for writeback
*/
TEXT cachedwbtlb(SB), $-4
DSB
ISB
RET
TEXT cachedwbinvse(SB), $-4 /* D writeback+invalidate SE */
MOVW R0, R2
MOVW CPSR, R3
CPSID /* splhi */
BARRIERS /* force outstanding stores to cache */
MOVW R2, R0
MOVW 4(FP), R1
ADD R0, R1 /* R1 is end address */
BIC $(CACHELINESZ-1), R0 /* cache line start */
_dwbinvse:
MCR CpSC, 0, R0, C(CpCACHE), C(CpCACHEwbi), CpCACHEse
/* can't have a BARRIER here since it zeroes R0 */
ADD $CACHELINESZ, R0
CMP.S R0, R1
BGT _dwbinvse
_wait: /* drain write buffer */
BARRIERS
MOVW R3, CPSR /* splx */
RET
TEXT cachedinvse(SB), $-4 /* D invalidate SE */
MOVW R0, R2
MOVW CPSR, R3
CPSID /* splhi */
BARRIERS /* force outstanding stores to cache */
MOVW R2, R0
MOVW 4(FP), R1
ADD R0, R1 /* R1 is end address */
BIC $(CACHELINESZ-1), R0 /* cache line start */
_dinvse:
MCR CpSC, 0, R0, C(CpCACHE), C(CpCACHEinvd), CpCACHEse
/* can't have a BARRIER here since it zeroes R0 */
ADD $CACHELINESZ, R0
CMP.S R0, R1
BGT _dinvse
B _wait
#include "cache.v7.s"
|
9front/9front
| 7,361
|
sys/src/9/bcm/lexception.s
|
/*
* arm exception handlers
*/
#include "arm.s"
/*
* exception vectors, copied by trapinit() to somewhere useful
*/
TEXT vectors(SB), 1, $-4
MOVW 0x18(R15), R15 /* reset */
MOVW 0x18(R15), R15 /* undefined instr. */
MOVW 0x18(R15), R15 /* SWI & SMC */
MOVW 0x18(R15), R15 /* prefetch abort */
MOVW 0x18(R15), R15 /* data abort */
MOVW 0x18(R15), R15 /* reserved */
MOVW 0x18(R15), R15 /* IRQ */
MOVW 0x18(R15), R15 /* FIQ */
TEXT vtable(SB), 1, $-4
WORD $_vsvc(SB) /* reset, in svc mode already */
WORD $_vund(SB) /* undefined, switch to svc mode */
WORD $_vsvc(SB) /* swi, in svc mode already */
WORD $_vpabt(SB) /* prefetch abort, switch to svc mode */
WORD $_vdabt(SB) /* data abort, switch to svc mode */
WORD $_vsvc(SB) /* reserved */
WORD $_virq(SB) /* IRQ, switch to svc mode */
WORD $_vfiq(SB) /* FIQ, switch to svc mode */
TEXT _vsvc(SB), 1, $-4 /* SWI */
CLREX
MOVW.W R14, -4(R13) /* ureg->pc = interrupted PC */
MOVW SPSR, R14 /* ureg->psr = SPSR */
MOVW.W R14, -4(R13) /* ... */
MOVW $PsrMsvc, R14 /* ureg->type = PsrMsvc */
MOVW.W R14, -4(R13) /* ... */
/* avoid the ambiguity described in notes/movm.w. */
MOVM.DB.S [R0-R14], (R13) /* save user level registers */
SUB $(15*4), R13 /* r13 now points to ureg */
MOVW $setR12(SB), R12 /* Make sure we've got the kernel's SB loaded */
/* get R(MACH) for this cpu */
CPUID(R1)
SLL $2, R1 /* convert to word index */
MOVW $machaddr(SB), R2
ADD R1, R2
MOVW (R2), R(MACH) /* m = machaddr[cpuid] */
CMP $0, R(MACH)
MOVW.EQ $MACHADDR, R0 /* paranoia: use MACHADDR if 0 */
MOVW 8(R(MACH)), R(USER) /* up */
MOVW R13, R0 /* first arg is pointer to ureg */
SUB $8, R13 /* space for argument+link */
BL syscall(SB)
ADD $(8+4*15), R13 /* make r13 point to ureg->type */
MOVW 8(R13), R14 /* restore link */
MOVW 4(R13), R0 /* restore SPSR */
MOVW R0, SPSR /* ... */
MOVM.DB.S (R13), [R0-R14] /* restore registers */
ADD $8, R13 /* pop past ureg->{type+psr} */
RFE /* MOVM.IA.S.W (R13), [R15] */
TEXT _vund(SB), 1, $-4 /* undefined */
MOVM.IA [R0-R4], (R13) /* free some working space */
MOVW $PsrMund, R0
B _vswitch
TEXT _vpabt(SB), 1, $-4 /* prefetch abort */
MOVM.IA [R0-R4], (R13) /* free some working space */
MOVW $PsrMabt, R0 /* r0 = type */
B _vswitch
TEXT _vdabt(SB), 1, $-4 /* data abort */
MOVM.IA [R0-R4], (R13) /* free some working space */
MOVW $(PsrMabt+1), R0 /* r0 = type */
B _vswitch
TEXT _virq(SB), 1, $-4 /* IRQ */
MOVM.IA [R0-R4], (R13) /* free some working space */
MOVW $PsrMirq, R0 /* r0 = type */
B _vswitch
/*
* come here with type in R0 and R13 pointing above saved [r0-r4].
* we'll switch to SVC mode and then call trap.
*/
_vswitch:
CLREX
MOVW SPSR, R1 /* save SPSR for ureg */
MOVW R14, R2 /* save interrupted pc for ureg */
MOVW R13, R3 /* save pointer to where the original [R0-R4] are */
/*
* switch processor to svc mode. this switches the banked registers
* (r13 [sp] and r14 [link]) to those of svc mode.
*/
MOVW CPSR, R14
BIC $PsrMask, R14
ORR $(PsrDirq|PsrMsvc), R14
MOVW R14, CPSR /* switch! */
AND.S $0xf, R1, R4 /* interrupted code kernel or user? */
BEQ _userexcep
/* here for trap from SVC mode */
MOVM.DB.W [R0-R2], (R13) /* set ureg->{type, psr, pc}; r13 points to ureg->type */
MOVM.IA (R3), [R0-R4] /* restore [R0-R4] from previous mode's stack */
/*
* avoid the ambiguity described in notes/movm.w.
* In order to get a predictable value in R13 after the stores,
* separate the store-multiple from the stack-pointer adjustment.
* We'll assume that the old value of R13 should be stored on the stack.
*/
/* save kernel level registers, at end r13 points to ureg */
MOVM.DB [R0-R14], (R13)
SUB $(15*4), R13 /* SP now points to saved R0 */
MOVW $setR12(SB), R12 /* Make sure we've got the kernel's SB loaded */
MOVW R13, R0 /* first arg is pointer to ureg */
SUB $(4*2), R13 /* space for argument+link (for debugger) */
MOVW $0xdeaddead, R11 /* marker */
BL trap(SB)
MOVW $setR12(SB), R12 /* reload kernel's SB (ORLY?) */
ADD $(4*2+4*15), R13 /* make r13 point to ureg->type */
/*
* if we interrupted a previous trap's handler and are now
* returning to it, we need to propagate the current R(MACH) (R10)
* by overriding the saved one on the stack, since we may have
* been rescheduled and be on a different processor now than
* at entry.
*/
MOVW R(MACH), (-(15-MACH)*4)(R13) /* restore current cpu's MACH */
MOVW 8(R13), R14 /* restore link */
MOVW 4(R13), R0 /* restore SPSR */
MOVW R0, SPSR /* ... */
MOVM.DB (R13), [R0-R14] /* restore registers */
ADD $(4*2), R13 /* pop past ureg->{type+psr} to pc */
RFE /* MOVM.IA.S.W (R13), [R15] */
/* here for trap from USER mode */
_userexcep:
MOVM.DB.W [R0-R2], (R13) /* set ureg->{type, psr, pc}; r13 points to ureg->type */
MOVM.IA (R3), [R0-R4] /* restore [R0-R4] from previous mode's stack */
/* avoid the ambiguity described in notes/movm.w. */
MOVM.DB.S [R0-R14], (R13) /* save kernel level registers */
SUB $(15*4), R13 /* r13 now points to ureg */
MOVW $setR12(SB), R12 /* Make sure we've got the kernel's SB loaded */
/* get R(MACH) for this cpu */
CPUID(R1)
SLL $2, R1 /* convert to word index */
MOVW $machaddr(SB), R2
ADD R1, R2
MOVW (R2), R(MACH) /* m = machaddr[cpuid] */
CMP $0, R(MACH)
MOVW.EQ $MACHADDR, R(MACH) /* paranoia: use MACHADDR if 0 */
MOVW 8(R(MACH)), R(USER) /* up */
MOVW R13, R0 /* first arg is pointer to ureg */
SUB $(4*2), R13 /* space for argument+link (for debugger) */
BL trap(SB)
ADD $(4*2+4*15), R13 /* make r13 point to ureg->type */
MOVW 8(R13), R14 /* restore link */
MOVW 4(R13), R0 /* restore SPSR */
MOVW R0, SPSR /* ... */
MOVM.DB.S (R13), [R0-R14] /* restore registers */
ADD $(4*2), R13 /* pop past ureg->{type+psr} */
RFE /* MOVM.IA.S.W (R13), [R15] */
TEXT _vfiq(SB), 1, $-4 /* FIQ */
CLREX
MOVW $PsrMfiq, R8 /* trap type */
MOVW SPSR, R9 /* interrupted psr */
MOVW R14, R10 /* interrupted pc */
SUB $4, R10 /* ureg->pc -= 4 */
MOVM.DB.W [R8-R10], (R13) /* save in ureg */
MOVM.DB.S [R0-R14], (R13) /* save interrupted regs */
SUB $(15*4), R13
MOVW $setR12(SB), R12 /* Make sure we've got the kernel's SB loaded */
/* get R(MACH) for this cpu */
CPUID(R1)
SLL $2, R1 /* convert to word index */
MOVW $machaddr(SB), R2
ADD R1, R2
MOVW (R2), R(MACH) /* m = machaddr[cpuid] */
CMP $0, R(MACH)
MOVW.EQ $MACHADDR, R(MACH) /* paranoia: use MACHADDR if 0 */
MOVW 8(R(MACH)), R(USER) /* up */
MOVW R13, R0 /* first arg is pointer to ureg */
SUB $(4*2), R13 /* space for argument+link (for debugger) */
BL fiq(SB)
ADD $(8+4*15), R13 /* make r13 point to ureg->type */
MOVW 8(R13), R14 /* restore link */
MOVW 4(R13), R0 /* restore SPSR */
MOVW R0, SPSR /* ... */
MOVM.DB.S (R13), [R0-R14] /* restore registers */
ADD $8, R13 /* pop past ureg->{type+psr} */
RFE /* MOVM.IA.S.W (R13), [R15] */
/*
* set the stack value for the mode passed in R0
*/
TEXT setr13(SB), 1, $-4
MOVW 4(FP), R1
MOVW CPSR, R2
BIC $PsrMask, R2, R3
ORR $(PsrDirq|PsrDfiq), R3
ORR R0, R3
MOVW R3, CPSR /* switch to new mode */
MOVW R13, R0 /* return old sp */
MOVW R1, R13 /* install new one */
MOVW R2, CPSR /* switch back to old mode */
RET
|
9front/9front
| 1,965
|
sys/src/9/bcm/rebootcode.s
|
/*
* armv6/armv7 reboot code
*/
#include "arm.s"
#define WFI WORD $0xe320f003 /* wait for interrupt */
#define WFE WORD $0xe320f002 /* wait for event */
TEXT main(SB), 1, $-4
MOVW $setR12(SB), R12
MOVW R0, entry+0(FP)
CMP $0, R0
BEQ shutdown
MOVW entry+0(FP), R8
MOVW code+4(FP), R9
MOVW size+8(FP), R6
/* round to words */
BIC $3, R8
BIC $3, R9
ADD $3, R6
BIC $3, R6
memloop:
MOVM.IA.W (R9), [R1]
MOVM.IA.W [R1], (R8)
SUB.S $4, R6
BNE memloop
shutdown:
/* clean dcache using appropriate code for armv6 or armv7 */
MRC CpSC, 0, R1, C(CpID), C(CpIDfeat), 7 /* Memory Model Feature Register 3 */
TST $0xF, R1 /* hierarchical cache maintenance? */
BNE l2wb
DSB
MOVW $0, R0
MCR CpSC, 0, R0, C(CpCACHE), C(CpCACHEwb), CpCACHEall
B l2wbx
l2wb:
BL cachedwb(SB)
BL l2cacheuwb(SB)
l2wbx:
/* load entry before turning off mmu */
MOVW entry+0(FP), R8
/* disable caches */
MRC CpSC, 0, R1, C(CpCONTROL), C(0), CpMainctl
BIC $(CpCdcache|CpCicache|CpCpredict), R1
MCR CpSC, 0, R1, C(CpCONTROL), C(0), CpMainctl
BARRIERS
/* invalidate icache */
MOVW $0, R0
MCR CpSC, 0, R0, C(CpCACHE), C(CpCACHEinvi), CpCACHEall
BARRIERS
/* turn off mmu */
MRC CpSC, 0, R1, C(CpCONTROL), C(0), CpMainctl
BIC $CpCmmu, R1
MCR CpSC, 0, R1, C(CpCONTROL), C(0), CpMainctl
BARRIERS
/* turn SMP off */
MRC CpSC, 0, R1, C(CpCONTROL), C(0), CpAuxctl
BIC $CpACsmp, R1
MCR CpSC, 0, R1, C(CpCONTROL), C(0), CpAuxctl
ISB
DSB
/* have entry? */
CMP $0, R8
BNE bootcpu
/* other cpus wait for inter processor interrupt */
CPUID(R2)
dowfi:
WFE /* wait for event signal */
MOVW $0x400000CC, R1 /* inter-core .startcpu mailboxes */
ADD R2<<4, R1 /* mailbox for this core */
MOVW 0(R1), R8 /* content of mailbox */
CMP $0, R8
BEQ dowfi /* if zero, wait again */
bootcpu:
MOVW $0, R2 /* no ATAGS/DTB pointer */
BIC $KSEGM, R8 /* entry to physical */
ORR $PHYSDRAM, R8
BL (R8)
B dowfi
#define ICACHELINESZ 32
#include "cache.v7.s"
|
9front/9front
| 6,227
|
sys/src/9/bcm/armv6.s
|
/*
* Broadcom bcm2835 SoC, as used in Raspberry Pi
* arm1176jzf-s processor (armv6)
*/
#include "arm.s"
#define CACHELINESZ 32
TEXT armstart(SB), 1, $-4
/*
* SVC mode, interrupts disabled
*/
MOVW $(PsrDirq|PsrDfiq|PsrMsvc), R1
MOVW R1, CPSR
/*
* disable the mmu and L1 caches
* invalidate caches and tlb
*/
MRC CpSC, 0, R1, C(CpCONTROL), C(0), CpMainctl
BIC $(CpCdcache|CpCicache|CpCpredict|CpCmmu), R1
MCR CpSC, 0, R1, C(CpCONTROL), C(0), CpMainctl
MCR CpSC, 0, R0, C(CpCACHE), C(CpCACHEinvu), CpCACHEall
MCR CpSC, 0, R0, C(CpTLB), C(CpTLBinvu), CpTLBinv
ISB
/*
* clear mach and page tables
*/
MOVW $PADDR(MACHADDR), R1
MOVW $PADDR(KTZERO), R2
_ramZ:
MOVW R0, (R1)
ADD $4, R1
CMP R1, R2
BNE _ramZ
/*
* start stack at top of mach (physical addr)
* set up page tables for kernel
*/
MOVW $PADDR(MACHADDR+MACHSIZE-4), R13
MOVW $PADDR(L1), R0
BL ,mmuinit(SB)
/*
* set up domain access control and page table base
*/
MOVW $Client, R1
MCR CpSC, 0, R1, C(CpDAC), C(0)
MOVW $PADDR(L1), R1
MCR CpSC, 0, R1, C(CpTTB), C(0)
/*
* enable caches, mmu, and high vectors
*/
MRC CpSC, 0, R0, C(CpCONTROL), C(0), CpMainctl
ORR $(CpCxp|CpChv|CpCdcache|CpCicache|CpCpredict|CpCmmu), R0
MCR CpSC, 0, R0, C(CpCONTROL), C(0), CpMainctl
ISB
/*
* switch SB, SP, and PC into KZERO space
*/
MOVW $setR12(SB), R12
MOVW $(MACHADDR+MACHSIZE-4), R13
MOVW $_startpg(SB), R15
TEXT _startpg(SB), 1, $-4
/*
* enable cycle counter
*/
MOVW $1, R1
MCR CpSC, 0, R1, C(CpSPM), C(CpSPMperf), CpSPMctl
/* first arg to main is saved R2 */
MOVW R10, R0
/*
* call main and loop forever if it returns
*/
BL ,main(SB)
B ,0(PC)
BL _div(SB) /* hack to load _div, etc. */
TEXT cpidget(SB), 1, $-4 /* main ID */
MRC CpSC, 0, R0, C(CpID), C(0), CpIDid
RET
TEXT fsrget(SB), 1, $-4 /* data fault status */
MRC CpSC, 0, R0, C(CpFSR), C(0), CpFSRdata
RET
TEXT ifsrget(SB), 1, $-4 /* instruction fault status */
MRC CpSC, 0, R0, C(CpFSR), C(0), CpFSRinst
RET
TEXT farget(SB), 1, $-4 /* fault address */
MRC CpSC, 0, R0, C(CpFAR), C(0x0)
RET
TEXT lcycles(SB), 1, $-4
MRC CpSC, 0, R0, C(CpSPM), C(CpSPMperf), CpSPMcyc
RET
TEXT splhi(SB), 1, $-4
MOVW $(MACHADDR+4), R2 /* save caller pc in Mach */
MOVW R14, 0(R2)
MOVW CPSR, R0 /* turn off irqs (but not fiqs) */
ORR $(PsrDirq), R0, R1
MOVW R1, CPSR
RET
TEXT splfhi(SB), 1, $-4
MOVW $(MACHADDR+4), R2 /* save caller pc in Mach */
MOVW R14, 0(R2)
MOVW CPSR, R0 /* turn off irqs and fiqs */
ORR $(PsrDirq|PsrDfiq), R0, R1
MOVW R1, CPSR
RET
TEXT splflo(SB), 1, $-4
MOVW CPSR, R0 /* turn on fiqs */
BIC $(PsrDfiq), R0, R1
MOVW R1, CPSR
RET
TEXT spllo(SB), 1, $-4
MOVW CPSR, R0 /* turn on irqs and fiqs */
BIC $(PsrDirq|PsrDfiq), R0, R1
MOVW R1, CPSR
RET
TEXT splx(SB), 1, $-4
MOVW $(MACHADDR+0x04), R2 /* save caller pc in Mach */
MOVW R14, 0(R2)
MOVW R0, R1 /* reset interrupt level */
MOVW CPSR, R0
MOVW R1, CPSR
RET
TEXT spldone(SB), 1, $0 /* end marker for devkprof.c */
RET
TEXT islo(SB), 1, $-4
MOVW CPSR, R0
AND $(PsrDirq), R0
EOR $(PsrDirq), R0
RET
TEXT tas(SB), $-4
TEXT _tas(SB), $-4
MOVW R0,R1
MOVW $1,R0
SWPW R0,(R1) /* fix: deprecated in armv6 */
RET
TEXT setlabel(SB), 1, $-4
MOVW R13, 0(R0) /* sp */
MOVW R14, 4(R0) /* pc */
MOVW $0, R0
RET
TEXT gotolabel(SB), 1, $-4
MOVW 0(R0), R13 /* sp */
MOVW 4(R0), R14 /* pc */
MOVW $1, R0
RET
TEXT getcallerpc(SB), 1, $-4
MOVW 0(R13), R0
RET
TEXT idlehands(SB), $-4
MOVW CPSR, R3
ORR $(PsrDirq|PsrDfiq), R3, R1 /* splfhi */
MOVW R1, CPSR
DSB
MOVW nrdy(SB), R0
CMP $0, R0
MCR.EQ CpSC, 0, R0, C(CpCACHE), C(CpCACHEintr), CpCACHEwait
DSB
MOVW R3, CPSR /* splx */
RET
TEXT coherence(SB), $-4
BARRIERS
RET
/*
* invalidate tlb
*/
TEXT mmuinvalidate(SB), 1, $-4
MOVW $0, R0
MCR CpSC, 0, R0, C(CpTLB), C(CpTLBinvu), CpTLBinv
BARRIERS
MCR CpSC, 0, R0, C(CpCACHE), C(CpCACHEinvi), CpCACHEflushbtc
RET
/*
* mmuinvalidateaddr(va)
* invalidate tlb entry for virtual page address va, ASID 0
*/
TEXT mmuinvalidateaddr(SB), 1, $-4
MCR CpSC, 0, R0, C(CpTLB), C(CpTLBinvu), CpTLBinvse
BARRIERS
RET
/*
* drain write buffer
* writeback data cache
*/
TEXT cachedwb(SB), 1, $-4
DSB
MOVW $0, R0
MCR CpSC, 0, R0, C(CpCACHE), C(CpCACHEwb), CpCACHEall
RET
/*
* drain write buffer
* writeback and invalidate data cache
*/
TEXT cachedwbinv(SB), 1, $-4
DSB
MOVW $0, R0
MCR CpSC, 0, R0, C(CpCACHE), C(CpCACHEwbi), CpCACHEall
RET
/*
* cachedwbinvse(va, n)
* drain write buffer
* writeback and invalidate data cache range [va, va+n)
*/
TEXT cachedwbinvse(SB), 1, $-4
MOVW R0, R1 /* DSB clears R0 */
DSB
MOVW n+4(FP), R2
ADD R1, R2
SUB $1, R2
BIC $(CACHELINESZ-1), R1
BIC $(CACHELINESZ-1), R2
MCRR(CpSC, 0, 2, 1, CpCACHERANGEdwbi)
RET
/*
* cachedwbse(va, n)
* drain write buffer
* writeback data cache range [va, va+n)
*/
TEXT cachedwbtlb(SB), 1, $-4
TEXT cachedwbse(SB), 1, $-4
MOVW R0, R1 /* DSB clears R0 */
DSB
MOVW n+4(FP), R2
ADD R1, R2
BIC $(CACHELINESZ-1), R1
BIC $(CACHELINESZ-1), R2
MCRR(CpSC, 0, 2, 1, CpCACHERANGEdwb)
RET
/*
* cachedinvse(va, n)
* drain write buffer
* invalidate data cache range [va, va+n)
*/
TEXT cachedinvse(SB), 1, $-4
MOVW R0, R1 /* DSB clears R0 */
DSB
MOVW n+4(FP), R2
ADD R1, R2
SUB $1, R2
BIC $(CACHELINESZ-1), R1
BIC $(CACHELINESZ-1), R2
MCRR(CpSC, 0, 2, 1, CpCACHERANGEinvd)
RET
/*
* drain write buffer and prefetch buffer
* writeback and invalidate data cache
* invalidate instruction cache
*/
TEXT cacheuwbinv(SB), 1, $-4
BARRIERS
MOVW $0, R0
MCR CpSC, 0, R0, C(CpCACHE), C(CpCACHEwbi), CpCACHEall
MCR CpSC, 0, R0, C(CpCACHE), C(CpCACHEinvi), CpCACHEall
RET
/*
* L2 cache is not enabled
*/
TEXT l2cacheuwbinv(SB), 1, $-4
RET
/*
* invalidate instruction cache
*/
TEXT cacheiinv(SB), 1, $-4
MOVW $0, R0
MCR CpSC, 0, R0, C(CpCACHE), C(CpCACHEinvi), CpCACHEall
RET
/*
* invalidate range of instruction cache
*/
TEXT cacheiinvse(SB), 1, $-4
MOVW R0, R1 /* DSB clears R0 */
DSB
MOVW n+4(FP), R2
ADD R1, R2
SUB $1, R2
MCRR(CpSC, 0, 2, 1, CpCACHERANGEinvi)
MCR CpSC, 0, R0, C(CpCACHE), C(CpCACHEinvi), CpCACHEflushbtc
DSB
ISB
RET
|
9front/9front
| 1,130
|
sys/src/libc/power/atom.s
|
TEXT ainc(SB),$0 /* long ainc(long *); */
MOVW R3, R4
xincloop:
LWAR (R4), R3
ADD $1, R3
DCBT (R4) /* fix 405 errata cpu_210 */
STWCCC R3, (R4)
BNE xincloop
RETURN
TEXT adec(SB),$0 /* long adec(long *); */
MOVW R3, R4
xdecloop:
LWAR (R4), R3
ADD $-1, R3
DCBT (R4) /* fix 405 errata cpu_210 */
STWCCC R3, (R4)
BNE xdecloop
RETURN
TEXT loadlink(SB), $0
LWAR (R3), R3
RETURN
TEXT storecond(SB), $0
MOVW val+4(FP), R4
DCBT (R3) /* fix 405 errata cpu_210 */
STWCCC R4, (R3)
BNE storecondfail
MOVW $1, R3
RETURN
storecondfail:
MOVW $0, R3
RETURN
/*
* int cas32(u32int *p, u32int ov, u32int nv);
* int cas(uint *p, int ov, int nv);
* int casp(void **p, void *ov, void *nv);
* int casl(ulong *p, ulong ov, ulong nv);
*/
TEXT cas32+0(SB),0,$0
TEXT cas+0(SB),0,$0
TEXT casp+0(SB),0,$0
TEXT casl+0(SB),0,$0
MOVW ov+4(FP),R4
MOVW nv+8(FP),R8
LWAR (R3),R5
CMP R5,R4
BNE fail
DCBT (R3) /* fix 405 errata cpu_210 */
STWCCC R8,(R3)
BNE fail1
MOVW $1,R3
RETURN
fail:
DCBT (R3) /* fix 405 errata cpu_210 */
STWCCC R5,(R3) /* give up exclusive access */
fail1:
MOVW R0,R3
RETURN
END
|
9front/9front
| 1,211
|
sys/src/libc/power/memset.s
|
TEXT memset(SB),$0
#define BDNZ BC 16,0,
MOVW R3, p+0(FP) /* R3 is pointer */
/*
* performance:
* about 100mbytes/sec (8k blocks) on a 603/105 without L2 cache
* drops to 40mbytes/sec (10k blocks) and 28mbytes/sec with 32k blocks
*/
MOVW n+8(FP), R4 /* R4 is count */
CMP R4, $0
BLE ret
MOVW c+4(FP), R5 /* R5 is char */
/*
* create 16 copies of c in R5 .. R8
*/
RLWNM $0, R5, $0xff, R5
RLWMI $8, R5, $0xff00, R5
RLWMI $16, R5, $0xffff0000, R5
MOVW R5, R6
MOVW R5, R7
MOVW R5, R8
/*
* let STSW do the work for 16 characters or less; aligned and unaligned
*/
CMP R4, $16
BLE out
/*
* store enough bytes to align pointer
*/
ANDCC $7,R3, R9
BEQ l2
SUBC R9, $8, R9
MOVW R9, XER
STSW R5, (R3)
ADD R9, R3
SUB R9, R4
/*
* store 16 at a time while there's room
* STSW was used here originally, but it's `completion serialised'
*/
l2:
SRAWCC $4, R4, R9
BLE out
MOVW R9, CTR
l3:
MOVW R5, 0(R3)
ADD $8, R3, R10
MOVW R6, 4(R3)
MOVW R7, 0(R10)
ADD $8, R10, R3
MOVW R8, 4(R10)
BDNZ l3
RLWNMCC $0, R4, $15, R4 /* residue */
BEQ ret
/*
* store up to 16 bytes from R5 .. R8; aligned and unaligned
*/
out:
MOVW R4, XER
STSW R5, (R3)
ret:
MOVW 0(FP), R3
RETURN
END
|
9front/9front
| 2,479
|
sys/src/libc/power/memmove.s
|
#define BDNZ BC 16,0,
TEXT memmove(SB), $0
BR move
TEXT memcpy(SB), $0
move:
/*
* performance:
* (tba)
*/
MOVW R3, s1+0(FP)
MOVW n+8(FP), R9 /* R9 is count */
MOVW R3, R10 /* R10 is to-pointer */
CMP R9, $0
BEQ ret
BLT trap
MOVW s2+4(FP), R11 /* R11 is from-pointer */
/*
* if no more than 16 bytes, just use one lsw/stsw
*/
CMP R9, $16
BLE fout
ADD R9,R11, R13 /* R13 is end from-pointer */
ADD R9,R10, R12 /* R12 is end to-pointer */
/*
* easiest test is copy backwards if
* destination string has higher mem address
*/
CMPU R10, R11
BGT back
/*
* test if both pointers
* are similarly word aligned
*/
XOR R10,R11, R7
ANDCC $3,R7
BNE fbad
/*
* move a few bytes to align pointers
*/
ANDCC $3,R10,R7
BEQ f2
SUBC R7, $4, R7
SUB R7, R9
MOVW R7, XER
LSW (R11), R16
ADD R7, R11
STSW R16, (R10)
ADD R7, R10
/*
* turn R14 into doubleword count
* copy 16 bytes at a time while there's room.
*/
f2:
SRAWCC $4, R9, R14
BLE fout
MOVW R14, CTR
SUB $4, R11
SUB $4, R10
f3:
MOVWU 4(R11), R16
MOVWU 4(R11), R17
MOVWU 4(R11), R18
MOVWU 4(R11), R19
MOVWU R16, 4(R10)
MOVWU R17, 4(R10)
MOVWU R18, 4(R10)
MOVWU R19, 4(R10)
BDNZ f3
RLWNMCC $0, R9, $15, R9 /* residue */
BEQ ret
ADD $4, R11
ADD $4, R10
/*
* move up to 16 bytes through R16 .. R19; aligned and unaligned
*/
fout:
MOVW R9, XER
LSW (R11), R16
STSW R16, (R10)
BR ret
/*
* loop for unaligned copy, then copy up to 15 remaining bytes
*/
fbad:
SRAWCC $4, R9, R14
BLE f6
MOVW R14, CTR
f5:
LSW (R11), $16, R16
ADD $16, R11
STSW R16, $16, (R10)
ADD $16, R10
BDNZ f5
RLWNMCC $0, R9, $15, R9 /* residue */
BEQ ret
f6:
MOVW R9, XER
LSW (R11), R16
STSW R16, (R10)
BR ret
/*
* whole thing repeated for backwards
*/
back:
CMP R9, $4
BLT bout
XOR R12,R13, R7
ANDCC $3,R7
BNE bout
b1:
ANDCC $3,R13, R7
BEQ b2
MOVBZU -1(R13), R16
MOVBZU R16, -1(R12)
SUB $1, R9
BR b1
b2:
SRAWCC $4, R9, R14
BLE b4
MOVW R14, CTR
b3:
MOVWU -4(R13), R16
MOVWU -4(R13), R17
MOVWU -4(R13), R18
MOVWU -4(R13), R19
MOVWU R16, -4(R12)
MOVWU R17, -4(R12)
MOVWU R18, -4(R12)
MOVWU R19, -4(R12)
BDNZ b3
RLWNMCC $0, R9, $15, R9 /* residue */
BEQ ret
b4:
SRAWCC $2, R9, R14
BLE bout
MOVW R14, CTR
b5:
MOVWU -4(R13), R16
MOVWU R16, -4(R12)
BDNZ b5
RLWNMCC $0, R9, $3, R9 /* residue */
BEQ ret
bout:
CMPU R13, R11
BLE ret
MOVBZU -1(R13), R16
MOVBZU R16, -1(R12)
BR bout
trap:
MOVW $0, R0
MOVW 0(R0), R0
ret:
MOVW s1+0(FP), R3
RETURN
|
9front/9front
| 1,493
|
sys/src/libc/power/memcmp.s
|
TEXT memcmp(SB), $0
#define BDNZ BC 16,0,
MOVW R3, s1+0(FP) /* R3 is pointer1 */
/*
* performance:
* 67mb/sec aligned; 16mb/sec unaligned
*/
MOVW n+8(FP), R4 /* R4 is count */
MOVW s2+4(FP), R5 /* R5 is pointer2 */
/*
* let LSW do the work for 4 characters or less; aligned and unaligned
*/
CMP R4, $0
BLE eq
CMP R4, $4
BLE out
XOR R3, R5, R9
ANDCC $3, R9
BNE l4 /* pointers misaligned; use LSW loop */
/*
* do enough bytes to align pointers
*/
ANDCC $3,R3, R9
BEQ l2
SUBC R9, $4, R9
MOVW R9, XER
LSW (R3), R10
ADD R9, R3
LSW (R5), R14
ADD R9, R5
SUB R9, R4
CMPU R10, R14
BNE ne
/*
* compare 16 at a time
*/
l2:
SRAWCC $4, R4, R9
BLE l4
MOVW R9, CTR
SUB $4, R3
SUB $4, R5
l3:
MOVWU 4(R3), R10
MOVWU 4(R5), R12
MOVWU 4(R3), R11
MOVWU 4(R5), R13
CMPU R10, R12
BNE ne
MOVWU 4(R3), R10
MOVWU 4(R5), R12
CMPU R11, R13
BNE ne
MOVWU 4(R3), R11
MOVWU 4(R5), R13
CMPU R10, R12
BNE ne
CMPU R11, R13
BNE ne
BDNZ l3
ADD $4, R3
ADD $4, R5
RLWNMCC $0, R4, $15, R4 /* residue */
BEQ eq
/*
* do remaining words with LSW; also does unaligned case
*/
l4:
SRAWCC $2, R4, R9
BLE out
MOVW R9, CTR
l5:
LSW (R3), $4, R10
ADD $4, R3
LSW (R5), $4, R11
ADD $4, R5
CMPU R10, R11
BNE ne
BDNZ l5
RLWNMCC $0, R4, $3, R4 /* residue */
BEQ eq
/*
* do remaining bytes with final LSW
*/
out:
MOVW R4, XER
LSW (R3), R10
LSW (R5), R11
CMPU R10, R11
BNE ne
eq:
MOVW $0, R3
RETURN
ne:
MOVW $1, R3
BGE ret
MOVW $-1,R3
ret:
RETURN
END
|
9front/9front
| 3,748
|
sys/src/libc/power/vlop.s
|
#define BDNZ BC 16,0,
/*
* 64/64 division adapted from powerpc compiler writer's handbook
*
* (R3:R4) = (R3:R4) / (R5:R6) (64b) = (64b / 64b)
* quo dvd dvs
*
* Remainder is left in R7:R8
*
* Code comment notation:
* msw = most-significant (high-order) word, i.e. bits 0..31
* lsw = least-significant (low-order) word, i.e. bits 32..63
* LZ = Leading Zeroes
* SD = Significant Digits
*
* R3:R4 = dvd (input dividend); quo (output quotient)
* R5:R6 = dvs (input divisor)
*
* R7:R8 = tmp; rem (output remainder)
*/
TEXT _divu64(SB), $0
MOVW a+0(FP), R3
MOVW a+4(FP), R4
MOVW b+8(FP), R5
MOVW b+12(FP), R6
/* count the number of leading 0s in the dividend */
CMP R3, $0 /* dvd.msw == 0? R3, */
CNTLZW R3, R11 /* R11 = dvd.msw.LZ */
CNTLZW R4, R9 /* R9 = dvd.lsw.LZ */
BNE lab1 /* if(dvd.msw != 0) dvd.LZ = dvd.msw.LZ */
ADD $32, R9, R11 /* dvd.LZ = dvd.lsw.LZ + 32 */
lab1:
/* count the number of leading 0s in the divisor */
CMP R5, $0 /* dvd.msw == 0? */
CNTLZW R5, R9 /* R9 = dvs.msw.LZ */
CNTLZW R6, R10 /* R10 = dvs.lsw.LZ */
BNE lab2 /* if(dvs.msw != 0) dvs.LZ = dvs.msw.LZ */
ADD $32, R10, R9 /* dvs.LZ = dvs.lsw.LZ + 32 */
lab2:
/* determine shift amounts to minimize the number of iterations */
CMP R11, R9 /* compare dvd.LZ to dvs.LZ */
SUBC R11, $64, R10 /* R10 = dvd.SD */
BGT lab9 /* if(dvs > dvd) quotient = 0 */
ADD $1, R9 /* ++dvs.LZ (or --dvs.SD) */
SUBC R9, $64, R9 /* R9 = dvs.SD */
ADD R9, R11 /* (dvd.LZ + dvs.SD) = left shift of dvd for */
/* initial dvd */
SUB R9, R10, R9 /* (dvd.SD - dvs.SD) = right shift of dvd for */
/* initial tmp */
MOVW R9, CTR /* number of iterations = dvd.SD - dvs.SD */
/* R7:R8 = R3:R4 >> R9 */
CMP R9, $32
ADD $-32, R9, R7
BLT lab3 /* if(R9 < 32) jump to lab3 */
SRW R7, R3, R8 /* tmp.lsw = dvd.msw >> (R9 - 32) */
MOVW $0, R7 /* tmp.msw = 0 */
BR lab4
lab3:
SRW R9, R4, R8 /* R8 = dvd.lsw >> R9 */
SUBC R9, $32, R7
SLW R7, R3, R7 /* R7 = dvd.msw << 32 - R9 */
OR R7, R8 /* tmp.lsw = R8 | R7 */
SRW R9, R3, R7 /* tmp.msw = dvd.msw >> R9 */
lab4:
/* R3:R4 = R3:R4 << R11 */
CMP R11,$32
ADDC $-32, R11, R9
BLT lab5 /* (R11 < 32)? */
SLW R9, R4, R3 /* dvd.msw = dvs.lsw << R9 */
MOVW $0, R4 /* dvd.lsw = 0 */
BR lab6
lab5:
SLW R11, R3 /* R3 = dvd.msw << R11 */
SUBC R11, $32, R9
SRW R9, R4, R9 /* R9 = dvd.lsw >> 32 - R11 */
OR R9, R3 /* dvd.msw = R3 | R9 */
SLW R11, R4 /* dvd.lsw = dvd.lsw << R11 */
lab6:
/* restoring division shift and subtract loop */
MOVW $-1, R10
ADDC $0, R7 /* clear carry bit before loop starts */
lab7:
/* tmp:dvd is considered one large register */
/* each portion is shifted left 1 bit by adding it to itself */
/* adde sums the carry from the previous and creates a new carry */
ADDE R4,R4 /* shift dvd.lsw left 1 bit */
ADDE R3,R3 /* shift dvd.msw to left 1 bit */
ADDE R8,R8 /* shift tmp.lsw to left 1 bit */
ADDE R7,R7 /* shift tmp.msw to left 1 bit */
SUBC R6, R8, R11 /* tmp.lsw - dvs.lsw */
SUBECC R5, R7, R9 /* tmp.msw - dvs.msw */
BLT lab8 /* if(result < 0) clear carry bit */
MOVW R11, R8 /* move lsw */
MOVW R9, R7 /* move msw */
ADDC $1, R10, R11 /* set carry bit */
lab8:
BDNZ lab7
ADDE R4,R4 /* quo.lsw (lsb = CA) */
ADDE R3,R3 /* quo.msw (lsb from lsw) */
lab10:
MOVW qp+16(FP), R9
MOVW rp+20(FP), R10
CMP R9, $0
BEQ lab11
MOVW R3, 0(R9)
MOVW R4, 4(R9)
lab11:
CMP R10, $0
BEQ lab12
MOVW R7, 0(R10)
MOVW R8, 4(R10)
lab12:
RETURN
lab9:
/* Quotient is 0 (dvs > dvd) */
MOVW R4, R8 /* rmd.lsw = dvd.lsw */
MOVW R3, R7 /* rmd.msw = dvd.msw */
MOVW $0, R4 /* dvd.lsw = 0 */
MOVW $0, R3 /* dvd.msw = 0 */
BR lab10
|
9front/9front
| 1,279
|
sys/src/libc/386/atom.s
|
TEXT ainc(SB), $0 /* long ainc(long *); */
MOVL addr+0(FP), BX
ainclp:
MOVL (BX), AX
MOVL AX, CX
INCL CX
LOCK
BYTE $0x0F; BYTE $0xB1; BYTE $0x0B /* CMPXCHGL CX, (BX) */
JNZ ainclp
MOVL CX, AX
RET
TEXT adec(SB), $0 /* long adec(long*); */
MOVL addr+0(FP), BX
adeclp:
MOVL (BX), AX
MOVL AX, CX
DECL CX
LOCK
BYTE $0x0F; BYTE $0xB1; BYTE $0x0B /* CMPXCHGL CX, (BX) */
JNZ adeclp
MOVL CX, AX
RET
/*
* int cas32(u32int *p, u32int ov, u32int nv);
* int cas(uint *p, int ov, int nv);
* int casp(void **p, void *ov, void *nv);
* int casl(ulong *p, ulong ov, ulong nv);
*/
/*
* CMPXCHG (CX), DX: 0000 1111 1011 000w oorr rmmm,
* mmm = CX = 001; rrr = DX = 010
*/
#define CMPXCHG BYTE $0x0F; BYTE $0xB1; BYTE $0x11
TEXT cas32+0(SB),0,$0
TEXT cas+0(SB),0,$0
TEXT casp+0(SB),0,$0
TEXT casl+0(SB),0,$0
MOVL p+0(FP), CX
MOVL ov+4(FP), AX
MOVL nv+8(FP), DX
LOCK
CMPXCHG
JNE fail
MOVL $1,AX
RET
fail:
MOVL $0,AX
RET
/*
* int cas64(u64int *p, u64int ov, u64int nv);
*/
/*
* CMPXCHG64 (DI): 0000 1111 1100 0111 0000 1110,
*/
#define CMPXCHG64 BYTE $0x0F; BYTE $0xC7; BYTE $0x0F
TEXT cas64+0(SB),0,$0
MOVL p+0(FP), DI
MOVL ov+0x4(FP), AX
MOVL ov+0x8(FP), DX
MOVL nv+0xc(FP), BX
MOVL nv+0x10(FP), CX
LOCK
CMPXCHG64
JNE fail
MOVL $1,AX
RET
|
9front/9front
| 1,282
|
sys/src/libc/sparc/memset.s
|
TEXT memset(SB),$0
/*
* performance:
* (tba)
*/
MOVW R7, 0(FP)
MOVW n+8(FP), R9 /* R9 is count */
MOVW p+0(FP), R10 /* R10 is pointer */
MOVW c+4(FP), R11 /* R11 is char */
ADD R9,R10, R12 /* R12 is end pointer */
/*
* if not at least 4 chars,
* dont even mess around.
* 3 chars to guarantee any
* rounding up to a word
* boundary and 4 characters
* to get at least maybe one
* full word store.
*/
SUBCC $4,R9, R0
BL out
/*
* turn R11 into a word of characters
*/
AND $0xff, R11
SLL $8,R11, R7
OR R7, R11
SLL $16,R11, R7
OR R7, R11
/*
* store one byte at a time until pointer
* is alligned on a word boundary
*/
l1:
ANDCC $3,R10, R0
BE l2
MOVB R11, 0(R10)
ADD $1, R10
JMP l1
/*
* turn R9 into end pointer-15
* store 16 at a time while theres room
*/
l2:
ADD $-15,R12, R9
SUBCC R10,R9, R0
BLEU l4
l3:
MOVW R11, 0(R10)
MOVW R11, 4(R10)
ADD $16, R10
SUBCC R10,R9, R0
MOVW R11, -8(R10)
MOVW R11, -4(R10)
BGU l3
/*
* turn R9 into end pointer-3
* store 4 at a time while theres room
*/
l4:
ADD $-3,R12, R9
l5:
SUBCC R10,R9, R0
BLEU out
MOVW R11, 0(R10)
ADD $4, R10
JMP l5
/*
* last loop, store byte at a time
*/
out:
SUBCC R10,R12, R0
BLEU ret
MOVB R11, 0(R10)
ADD $1, R10
JMP out
ret:
MOVW s1+0(FP), R7
RETURN
|
9front/9front
| 2,281
|
sys/src/libc/sparc/memmove.s
|
TEXT memmove(SB), $0
JMP move
TEXT memcpy(SB), $0
move:
/*
* performance:
* (tba)
*/
MOVW R7, s1+0(FP)
MOVW n+8(FP), R9 /* R9 is count */
MOVW R7, R10 /* R10 is to-pointer */
SUBCC R0,R9, R0
BGE ok
MOVW 0(R0), R0
ok:
MOVW s2+4(FP), R11 /* R11 is from-pointer */
ADD R9,R11, R13 /* R13 is end from-pointer */
ADD R9,R10, R12 /* R12 is end to-pointer */
/*
* easiest test is copy backwards if
* destination string has higher mem address
*/
SUBCC R11,R10, R0
BGU back
/*
* if not at least 8 chars,
* dont even mess around.
* 7 chars to guarantee any
* rounding up to a word
* boundary and 8 characters
* to get at least maybe one
* full word store.
*/
SUBCC $8,R9, R0
BL fout
/*
* test if both pointers
* are similarly word aligned
*/
XOR R10,R11, R7
ANDCC $7,R7, R0
BNE fout
/*
* byte at a time to double align
*/
f1:
ANDCC $7,R10, R0
BE f2
MOVB 0(R11), R16
ADD $1, R11
MOVB R16, 0(R10)
ADD $1, R10
JMP f1
/*
* turn R9 into to-end pointer-15
* copy 16 at a time while theres room.
* R12 is smaller than R13 --
* there are problems if R13 is 0.
*/
f2:
SUB $15,R12, R9
f3:
SUBCC R10,R9, R0
BLEU f4
MOVD 0(R11), R16
MOVD R16, 0(R10)
MOVD 8(R11), R16
ADD $16, R11
MOVD R16, 8(R10)
ADD $16, R10
JMP f3
/*
* turn R9 into to-end pointer-3
* copy 4 at a time while theres room
*/
f4:
SUB $3,R12, R9
f5:
SUBCC R10,R9, R0
BLEU fout
MOVW 0(R11), R16
ADD $4, R11
MOVW R16, 0(R10)
ADD $4, R10
JMP f5
/*
* last loop, copy byte at a time
*/
fout:
SUBCC R11,R13, R0
BLEU ret
MOVB 0(R11), R16
ADD $1, R11
MOVB R16, 0(R10)
ADD $1, R10
JMP fout
/*
* whole thing repeated for backwards
*/
back:
SUBCC $8,R9, R0
BL bout
XOR R12,R13, R7
ANDCC $7,R7, R0
BNE bout
b1:
ANDCC $7,R13, R0
BE b2
MOVB -1(R13), R16
SUB $1, R13
MOVB R16, -1(R12)
SUB $1, R12
JMP b1
b2:
ADD $15,R11, R9
b3:
SUBCC R9,R13, R0
BLEU b4
MOVD -8(R13), R16
MOVD R16, -8(R12)
MOVD -16(R13), R16
SUB $16, R13
MOVD R16, -16(R12);
SUB $16, R12
JMP b3
b4:
ADD $3,R11, R9
b5:
SUBCC R9,R13, R0
BLEU bout
MOVW -4(R13), R16
SUB $4, R13
MOVW R16, -4(R12)
SUB $4, R12
JMP b5
bout:
SUBCC R11,R13, R0
BLEU ret
MOVB -1(R13), R16
SUB $1, R13
MOVB R16, -1(R12)
SUB $1, R12
JMP bout
ret:
MOVW s1+0(FP), R7
RETURN
|
9front/9front
| 1,705
|
sys/src/libc/sparc/memcmp.s
|
TEXT memcmp(SB), $0
/*
* performance:
* (tba)
*/
MOVW R7, 0(FP)
MOVW n+8(FP), R9 /* R9 is count */
MOVW s1+0(FP), R10 /* R10 is pointer1 */
MOVW s2+4(FP), R11 /* R11 is pointer2 */
ADD R9,R10, R12 /* R12 is end pointer1 */
/*
* if not at least 4 chars,
* dont even mess around.
* 3 chars to guarantee any
* rounding up to a word
* boundary and 4 characters
* to get at least maybe one
* full word cmp.
*/
SUBCC $4,R9, R0
BL out
/*
* test if both pointers
* are similarly word alligned
*/
XOR R10,R11, R7
ANDCC $3,R7, R0
BNE out
/*
* byte at a time to word allign
*/
l1:
ANDCC $3,R10, R0
BE l2
MOVBU 0(R10), R16
MOVBU 0(R11), R17
ADD $1, R10
SUBCC R16,R17, R0
BNE ne
ADD $1, R11
JMP l1
/*
* turn R9 into end pointer1-15
* cmp 16 at a time while theres room
*/
l2:
SUB $15,R12, R9
l3:
SUBCC R10,R9, R0
BLEU l4
MOVW 0(R10), R16
MOVW 0(R11), R17
MOVW 4(R10), R18
SUBCC R16,R17, R0
BNE ne
MOVW 4(R11), R19
MOVW 8(R10), R16
SUBCC R18,R19, R0
BNE ne
MOVW 8(R11), R17
MOVW 12(R10), R18
SUBCC R16,R17, R0
BNE ne
MOVW 12(R11), R19
ADD $16, R10
SUBCC R18,R19, R0
BNE ne
SUBCC R16,R17, R0
BNE ne
ADD $16, R11
JMP l3
/*
* turn R9 into end pointer1-3
* cmp 4 at a time while theres room
*/
l4:
SUB $3,R12, R9
l5:
SUBCC R10,R9, R0
BLEU out
MOVW 0(R10), R16
MOVW 0(R11), R17
ADD $4, R10
SUBCC R16,R17, R0 /* only works because big endian */
BNE ne
ADD $4, R11
JMP l5
/*
* last loop, cmp byte at a time
*/
out:
SUBCC R10,R12, R0
BE zero
MOVBU 0(R10), R16
MOVBU 0(R11), R17
ADD $1, R10
SUBCC R16,R17, R0
BNE ne
ADD $1, R11
JMP out
ne:
BGU plus
MOVW $1, R7
RETURN
plus:
MOVW $-1, R7
RETURN
zero:
MOVW R0, R7
RETURN
|
9front/9front
| 1,115
|
sys/src/libc/sparc/strcpy.s
|
TEXT strcpy(SB), $0
MOVW R7, 0(FP)
MOVW s1+0(FP), R9 /* R9 is to pointer */
MOVW s2+4(FP), R10 /* R10 is from pointer */
/*
* test if both pointers
* are similarly word aligned
*/
XOR R9,R10, R7
ANDCC $3,R7, R0
BNE una
/*
* make byte masks
*/
MOVW $0xff, R17
SLL $8,R17, R16
SLL $16,R17, R13
SLL $24,R17, R12
/*
* byte at a time to word align
*/
al1:
ANDCC $3,R10, R0
BE al2
MOVB (R10), R11
ADD $1, R10
MOVB R11, (R9)
ADD $1, R9
SUBCC R0,R11, R0
BNE al1
JMP out
/*
* word at a time
*/
al2:
ADD $4, R9
MOVW (R10), R11 /* fetch */
ADD $4, R10
ANDCC R12,R11, R0 /* is it byte 0 */
BE b0
ANDCC R13,R11, R0 /* is it byte 1 */
BE b1
ANDCC R16,R11, R0 /* is it byte 2 */
BE b2
MOVW R11, -4(R9) /* store */
ANDCC R17,R11, R0 /* is it byte 3 */
BNE al2
JMP out
b0:
MOVB R0, -4(R9)
JMP out
b1:
SRL $24, R11
MOVB R11, -4(R9)
MOVB R0, -3(R9)
JMP out
b2:
SRL $24,R11, R7
MOVB R7, -4(R9)
SRL $16, R11
MOVB R11, -3(R9)
MOVB R0, -2(R9)
JMP out
una:
MOVB (R10), R11
ADD $1, R10
MOVB R11, (R9)
ADD $1, R9
SUBCC R0,R11, R0
BNE una
out:
MOVW s1+0(FP),R7
RETURN
|
9front/9front
| 5,379
|
sys/src/libc/sparc/muldivrt.s
|
/*
* ulong
* _udiv(ulong num, ulong den)
* {
* int i;
* ulong quo;
*
* if(den == 0)
* *(ulong*)-1 = 0;
* quo = num;
* if(quo > 1<<(32-1))
* quo = 1<<(32-1);
* for(i=0; den<quo; i++)
* den <<= 1;
* quo = 0;
* for(; i>=0; i--) {
* quo <<= 1;
* if(num >= den) {
* num -= den;
* quo |= 1;
* }
* den >>= 1;
* }
* return quo::num;
* }
*/
#define NOPROF 1
/*
* calling sequence:
* num: 4(R1)
* den: 8(R1)
* returns
* quo: 4(R1)
* rem: 8(R1)
*/
TEXT _udivmod(SB), NOPROF, $-4
MOVW $(1<<31), R11
MOVW 4(R1), R13 /* numerator */
MOVW 8(R1), R10 /* denominator */
CMP R10, R0
BNE udm20
MOVW R0, -1(R0) /* fault -- divide by zero */
udm20:
MOVW R13, R12
CMP R13, R11
BLEU udm34
MOVW R11, R12
udm34:
MOVW R0, R11
udm38:
CMP R10, R12
BCC udm54
SLL $1, R10
ADD $1, R11
BA udm38
udm54:
MOVW R0, R12
udm58:
CMP R11, R0
BL udm8c
SLL $1, R12
CMP R13, R10
BCS udm7c
SUB R10, R13
OR $1, R12
udm7c:
SRL $1, R10
SUB $1, R11
BA udm58
udm8c:
MOVW R12, 4(R1) /* quotent */
MOVW R13, 8(R1) /* remainder */
JMPL 8(R15)
/*
* save working registers
* and bring in num/den parameters
*/
TEXT _unsarg(SB), NOPROF, $-4
MOVW R10, 12(R1)
MOVW R11, 16(R1)
MOVW R12, 20(R1)
MOVW R13, 24(R1)
MOVW R14, 4(R1)
MOVW 32(R1), R14
MOVW R14, 8(R1)
JMPL 8(R15)
/*
* save working registers
* and bring in absolute value
* of num/den parameters
*/
TEXT _absarg(SB), NOPROF, $-4
MOVW R10, 12(R1)
MOVW R11, 16(R1)
MOVW R12, 20(R1)
MOVW R13, 24(R1)
MOVW R14, 28(R1)
CMP R14, R0
BGE ab1
SUB R14, R0, R14
ab1:
MOVW R14, 4(R1) /* numerator */
MOVW 32(R1), R14
CMP R14, R0
BGE ab2
SUB R14, R0, R14
ab2:
MOVW R14, 8(R1) /* denominator */
JMPL 8(R15)
/*
* restore registers and
* return to original caller
* answer is in R14
*/
TEXT _retarg(SB), NOPROF, $-4
MOVW 12(R1), R10
MOVW 16(R1), R11
MOVW 20(R1), R12
MOVW 24(R1), R13
MOVW 0(R1), R15
ADD $28, R1
JMP 8(R15) /* back to main sequence */
/*
* calling sequence
* num: R14
* den: 8(R1)
* returns
* quo: R14
*/
TEXT _div(SB), NOPROF, $-4
SUB $28, R1 /* 4 reg save, 2 parameters, link */
MOVW R15, 0(R1)
JMPL _absarg(SB)
JMPL _udivmod(SB)
MOVW 4(R1), R14
MOVW 28(R1), R10 /* clean up the sign */
MOVW 32(R1), R11
XORCC R11, R10, R0
BGE div1
SUB R14, R0, R14
div1:
JMPL _retarg(SB)
JMP 8(R15) /* not executed */
/*
* calling sequence
* num: R14
* den: 8(R1)
* returns
* quo: R14
*/
TEXT _divl(SB), NOPROF, $-4
SUB $((4+2+1)*4), R1 /* 4 reg save, 2 parameters, link */
MOVW R15, 0(R1)
JMPL _unsarg(SB)
JMPL _udivmod(SB)
MOVW 4(R1), R14
JMPL _retarg(SB)
JMP 8(R15) /* not executed */
/*
* calling sequence
* num: R14
* den: 8(R1)
* returns
* rem: R14
*/
TEXT _mod(SB), NOPROF, $-4
SUB $28, R1 /* 4 reg save, 2 parameters, link */
MOVW R15, 0(R1)
JMPL _absarg(SB)
JMPL _udivmod(SB)
MOVW 8(R1), R14
MOVW 28(R1), R10 /* clean up the sign */
CMP R10, R0
BGE mod1
SUB R14, R0, R14
mod1:
JMPL _retarg(SB)
JMP 8(R15) /* not executed */
/*
* calling sequence
* num: R14
* den: 8(R1)
* returns
* rem: R14
*/
TEXT _modl(SB), NOPROF, $-4
SUB $28, R1 /* 4 reg save, 2 parameters, link */
MOVW R15, 0(R1)
JMPL _unsarg(SB)
JMPL _udivmod(SB)
MOVW 8(R1), R14
JMPL _retarg(SB)
JMP 8(R15) /* not executed */
/*
* special calling sequence:
* arg1 in R14
* arg2 in 4(R1), will save R9
* nothing in 0(R1), will save R8
* result in R14
*/
TEXT _mul+0(SB), NOPROF, $-4
/*
* exchange stack and registers
*/
MOVW R8, 0(R1)
MOVW 4(R1), R8
MOVW R9, 4(R1)
CMP R14, R8
BLE mul1
MOVW R14, R9
MOVW R8, R14
MOVW R9, R8
mul1:
MOVW R14, Y
ANDNCC $0xFFF, R14, R0
BE mul_shortway
ANDCC R0, R0, R9 /* zero partial product and clear N and V cond's */
/* long multiply */
MULSCC R8, R9, R9 /* 0 */
MULSCC R8, R9, R9 /* 1 */
MULSCC R8, R9, R9 /* 2 */
MULSCC R8, R9, R9 /* 3 */
MULSCC R8, R9, R9 /* 4 */
MULSCC R8, R9, R9 /* 5 */
MULSCC R8, R9, R9 /* 6 */
MULSCC R8, R9, R9 /* 7 */
MULSCC R8, R9, R9 /* 8 */
MULSCC R8, R9, R9 /* 9 */
MULSCC R8, R9, R9 /* 10 */
MULSCC R8, R9, R9 /* 11 */
MULSCC R8, R9, R9 /* 12 */
MULSCC R8, R9, R9 /* 13 */
MULSCC R8, R9, R9 /* 14 */
MULSCC R8, R9, R9 /* 15 */
MULSCC R8, R9, R9 /* 16 */
MULSCC R8, R9, R9 /* 17 */
MULSCC R8, R9, R9 /* 18 */
MULSCC R8, R9, R9 /* 19 */
MULSCC R8, R9, R9 /* 20 */
MULSCC R8, R9, R9 /* 21 */
MULSCC R8, R9, R9 /* 22 */
MULSCC R8, R9, R9 /* 23 */
MULSCC R8, R9, R9 /* 24 */
MULSCC R8, R9, R9 /* 25 */
MULSCC R8, R9, R9 /* 26 */
MULSCC R8, R9, R9 /* 27 */
MULSCC R8, R9, R9 /* 28 */
MULSCC R8, R9, R9 /* 29 */
MULSCC R8, R9, R9 /* 30 */
MULSCC R8, R9, R9 /* 31 */
MULSCC R0, R9, R9 /* 32; shift only */
MOVW Y, R14 /* get low part */
BA mul_return
mul_shortway:
ANDCC R0, R0, R9 /* zero partial product and clear N and V cond's */
MULSCC R8, R9, R9 /* 0 */
MULSCC R8, R9, R9 /* 1 */
MULSCC R8, R9, R9 /* 2 */
MULSCC R8, R9, R9 /* 3 */
MULSCC R8, R9, R9 /* 4 */
MULSCC R8, R9, R9 /* 5 */
MULSCC R8, R9, R9 /* 6 */
MULSCC R8, R9, R9 /* 7 */
MULSCC R8, R9, R9 /* 8 */
MULSCC R8, R9, R9 /* 9 */
MULSCC R8, R9, R9 /* 10 */
MULSCC R8, R9, R9 /* 11 */
MULSCC R0, R9, R9 /* 12; shift only */
MOVW Y, R8
SLL $12, R9
SRL $20, R8
OR R8, R9, R14
mul_return:
MOVW 0(R1), R8
MOVW 4(R1), R9
JMP 8(R15)
|
9front/9front
| 2,422
|
sys/src/libc/sparc/vlop.s
|
TEXT _mulv(SB), $0
MOVW u1+8(FP), R8
MOVW u2+16(FP), R13
MOVW R13, R16 /* save low parts for later */
MOVW R8, R12
/*
* unsigned 32x32 => 64 multiply
*/
CMP R13, R8
BLE mul1
MOVW R12, R13
MOVW R16, R8
mul1:
MOVW R13, Y
ANDNCC $0xFFF, R13, R0
BE mul_shortway
ANDCC R0, R0, R9 /* zero partial product and clear N and V cond's */
/* long multiply */
MULSCC R8, R9, R9 /* 0 */
MULSCC R8, R9, R9 /* 1 */
MULSCC R8, R9, R9 /* 2 */
MULSCC R8, R9, R9 /* 3 */
MULSCC R8, R9, R9 /* 4 */
MULSCC R8, R9, R9 /* 5 */
MULSCC R8, R9, R9 /* 6 */
MULSCC R8, R9, R9 /* 7 */
MULSCC R8, R9, R9 /* 8 */
MULSCC R8, R9, R9 /* 9 */
MULSCC R8, R9, R9 /* 10 */
MULSCC R8, R9, R9 /* 11 */
MULSCC R8, R9, R9 /* 12 */
MULSCC R8, R9, R9 /* 13 */
MULSCC R8, R9, R9 /* 14 */
MULSCC R8, R9, R9 /* 15 */
MULSCC R8, R9, R9 /* 16 */
MULSCC R8, R9, R9 /* 17 */
MULSCC R8, R9, R9 /* 18 */
MULSCC R8, R9, R9 /* 19 */
MULSCC R8, R9, R9 /* 20 */
MULSCC R8, R9, R9 /* 21 */
MULSCC R8, R9, R9 /* 22 */
MULSCC R8, R9, R9 /* 23 */
MULSCC R8, R9, R9 /* 24 */
MULSCC R8, R9, R9 /* 25 */
MULSCC R8, R9, R9 /* 26 */
MULSCC R8, R9, R9 /* 27 */
MULSCC R8, R9, R9 /* 28 */
MULSCC R8, R9, R9 /* 29 */
MULSCC R8, R9, R9 /* 30 */
MULSCC R8, R9, R9 /* 31 */
MULSCC R0, R9, R9 /* 32; shift only; r9 is high part */
/*
* need to correct top word if top bit set
*/
CMP R8, R0
BGE mul_tstlow
ADD R13, R9 /* adjust the high parts */
mul_tstlow:
MOVW Y, R13 /* get low part */
BA mul_done
mul_shortway:
ANDCC R0, R0, R9 /* zero partial product and clear N and V cond's */
MULSCC R8, R9, R9 /* 0 */
MULSCC R8, R9, R9 /* 1 */
MULSCC R8, R9, R9 /* 2 */
MULSCC R8, R9, R9 /* 3 */
MULSCC R8, R9, R9 /* 4 */
MULSCC R8, R9, R9 /* 5 */
MULSCC R8, R9, R9 /* 6 */
MULSCC R8, R9, R9 /* 7 */
MULSCC R8, R9, R9 /* 8 */
MULSCC R8, R9, R9 /* 9 */
MULSCC R8, R9, R9 /* 10 */
MULSCC R8, R9, R9 /* 11 */
MULSCC R0, R9, R9 /* 12; shift only; r9 is high part */
MOVW Y, R8 /* make low part of partial low part & high part */
SLL $12, R9, R13
SRL $20, R8
OR R8, R13
SRA $20, R9 /* high part */
mul_done:
/*
* mul by high halves if needed
*/
MOVW R13, 4(R7)
MOVW u2+12(FP), R11
CMP R11, R0
BE nomul1
MUL R11, R12
ADD R12, R9
nomul1:
MOVW u1+4(FP), R11
CMP R11, R0
BE nomul2
MUL R11, R16
ADD R16, R9
nomul2:
MOVW R9, 0(R7)
RETURN
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.