Writing Your Own CIO Device Handler

Atari text screen showing four lines read back from the M: device, end-of-file error 136, MEMLO=9472 and XIO 40 error 146, after RUN NUMBER 2

Every name you can OPEN on an Atari, from E: and P: to D:, R: and FujiNet's N:, is a small piece of machine code that CIO calls through a table. The operating system was designed so that new devices could be added without touching the ROM, and the mechanism is simple enough that you can write a working device in about 150 bytes. Once it is installed, BASIC's OPEN, PRINT #, INPUT #, GET #, PUT #, XIO, LIST and ENTER all work with it, without any changes to BASIC.

What you'll learn: how CIO dispatches to a handler, what is in A, X and Y on entry and exit, how to build the vector table, how to claim a HATABS slot and protect your code with MEMLO, and how to stay installed after the user presses RESET. The example is M:, a 1K RAM buffer device you can write to and read back from BASIC.

What you need: the MADS assembler, a DOS 2.x disk (or an emulator with one mounted) and Atari BASIC. You should already know IOCBs and the CIO command codes. CIO and IOCBs: How Atari Input/Output Really Works covers those, and this guide picks up where its HATABS section stops.

1. How CIO reaches your code

When a program calls CIO, CIO copies the first 12 bytes of the user's IOCB into the zero-page IOCB (ZIOCB) at $20–$2F (32–47). Your handler reads its parameters from there, not from the IOCB in page 3:

Address Name Contents for the handler
$20 ICHIDZ Index of your entry in HATABS
$21 ICDNOZ Unit number: 2 for M2:, 1 if none is given
$22 ICCOMZ Command byte
$24/$25 ICBALZ Buffer pointer. During OPEN it points to the file spec, so you can parse a filename
$28/$29 ICBLLZ Buffer length
$2A/$2B ICAX1Z/ICAX2Z AUX1 (the OPEN mode) and AUX2
$2E ICIDNO IOCB number × 16

On OPEN, CIO looks up the first character of the file spec in HATABS ($031A–$033F, 794–831). Each three-byte entry holds a device letter and a pointer to that handler's vector table. CIO searches from the end of the table back to the start, so the last entry for a letter wins. It also turns the character after the letter into the unit number (the 2 in D2:).

The OS ROM uses an indexing table to pick one of six vectors for each command:

Commands Vector used
3 (OPEN) +0 OPEN
12 (CLOSE) +2 CLOSE
5, 7 (GET RECORD, GET CHARACTERS) +4 GET BYTE
9, 11 (PUT RECORD, PUT CHARACTERS) +6 PUT BYTE
13 (STATUS) +8 STATUS
14 and up (anything else, e.g. XIO 32–254) +10 SPECIAL

Your handler never deals with records or blocks. CIO loops over the buffer itself, calling GET BYTE or PUT BYTE once per byte and checking for the EOL ($9B) on record commands. It also enforces the OPEN mode: a GET on a channel opened only for writing fails with error 131, and a PUT on a read-only channel fails with 135, before your code is ever called.

Why every address is "minus one"

CIO's dispatch routine (CIJUMP in the OS listing) pushes the vector's high and low bytes on the stack and executes RTS. RTS adds one to whatever it pulls, so each table entry must be the routine's address minus one. After the six vectors comes a three-byte JMP to an initialisation routine. The OS calls the init routines of its own ROM handlers at power-up. A RAM handler normally does its setup elsewhere, but it should keep the JMP so the table has the standard layout.

Register conventions

  • On entry: X = the IOCB number × 16. For PUT BYTE, A holds the byte. Y already holds 146 (function not implemented), so a routine that just executes RTS reports error 146.
  • On exit: Y = status (1 for success, 128 or above for an error). GET BYTE returns the byte in A. CIO saves Y in the IOCB's status byte and sets the N flag from it, then hands it back to the caller.

That makes an unimplemented function cost nothing: point the vector at any RTS.

2. The example handler: M:, a RAM buffer

M: stores everything written to it in a 1,024-byte buffer and plays it back when it is opened for reading. Opening with mode 8 (write) empties the buffer, mode 9 (append) keeps what is there, and every OPEN rewinds the read pointer. Reading past the last byte written returns error 136, end of file, just as a disk file does. STATUS succeeds and SPECIAL is not implemented.

; M: - a RAM buffer device for CIO.  mads mdev.asm -o:mdev.xex
DOSINI  = $0C           ; DOS reset-init vector
ICAX1Z  = $2A           ; zero-page IOCB copy: AUX1 (open mode)
HATABS  = $031A
MEMLO   = $02E7
BUFSIZE = 1024

        org $2000

; ---- handler vector table: address-1 of each routine, then JMP init
mtab    dta a(mopen-1)   ; OPEN    (command 3)
        dta a(mclose-1)  ; CLOSE   (12)
        dta a(mget-1)    ; GET     (5, 7)
        dta a(mput-1)    ; PUT     (9, 11)
        dta a(mstat-1)   ; STATUS  (13)
        dta a(mspec-1)   ; SPECIAL (14 and up)
        jmp mclose       ; init: nothing to do

; ---- OPEN: AUX1 bit 3 = write. Writing (8) empties the buffer,
;      append (9) keeps it. Every OPEN rewinds the read pointer.
mopen   lda ICAX1Z
        and #%00001001
        cmp #%00001000   ; write, not append?
        bne op1
        lda #<buf
        sta wptr
        lda #>buf
        sta wptr+1
op1     lda #<buf
        sta rptr
        lda #>buf
        sta rptr+1
mclose
mstat   ldy #1           ; success
        rts

; ---- PUT: byte arrives in A
mput    ldx wptr+1
        cpx #>(buf+BUFSIZE)
        bcs full
wptr    = *+1
        sta buf          ; operand is the write pointer (self-modified)
        inc wptr
        bne mstat
        inc wptr+1
        bne mstat        ; always taken
full    ldy #162         ; "disk full"
        rts

; ---- GET: return byte in A, or EOF (136) when read catches up with write
mget    lda rptr
        cmp wptr
        bne g1
        lda rptr+1
        cmp wptr+1
        beq eof
rptr    = *+1
g1      lda buf          ; operand is the read pointer
        inc rptr
        bne g2
        inc rptr+1
g2      ldy #1
        rts
eof     ldy #136
mspec   rts              ; SPECIAL: Y still holds 146 from CIO

; ---- installation, run once at load time and again after every RESET
reset   jsr olddos       ; let DOS re-initialise itself first
install ldy #0
find    lda HATABS,y     ; look for an existing M: entry or a free slot
        beq slot
        cmp #'M'
        beq slot
        iny
        iny
        iny
        cpy #36
        bcc find
        sec              ; table full
        rts
slot    lda #'M'
        sta HATABS,y
        lda #<mtab
        sta HATABS+1,y
        lda #>mtab
        sta HATABS+2,y
        lda #<memend     ; protect handler + buffer
        sta MEMLO
        lda #>memend
        sta MEMLO+1
        clc
        rts
olddos  jmp $FFFF        ; operand patched with DOS's own DOSINI

; ---- first-time setup: chain into DOSINI, then install
start   lda DOSINI
        sta olddos+1
        lda DOSINI+1
        sta olddos+2
        lda #<reset
        sta DOSINI
        lda #>reset
        sta DOSINI+1
        jmp install

        .align $100
buf     .ds BUFSIZE
memend

        ini start

A few design points:

  • No zero page. A handler can be called from any program at any time, so it should not claim page-zero bytes that BASIC or the application owns. The read and write pointers here are the operands of the LDA buf and STA buf instructions themselves, incremented in place. That self-modifying trick works because the code is in RAM. Aligning the buffer on a page boundary makes the "full" test a single compare of the high byte.
  • The PUT routine may use X. CIO reloads what it needs from the ZIOCB after each call, and it returns X = IOCB × 16 to the caller itself.
  • Error codes are your choice, but reuse the standard numbers so BASIC programs can TRAP them sensibly: 136 for end of file, 162 here for "buffer full", 146 for unsupported functions.

The 176-byte file assembles to $2000–$20AF, with the buffer at $2100–$24FF. ini start makes MADS emit an INITAD segment, so the installer runs as soon as the file is loaded and then returns to DOS.

3. Claiming memory: MEMLO

MEMLO ($02E7/$02E8, 743/744) holds the lowest free address. DOS 2.0S sets it to $1CFC when it boots, more with extra buffers or the 850 handler loaded. BASIC takes the start of program memory from MEMLO, so anything below it is safe from your program's variables. The handler stores its end address there: in the test below it reads 9472, which is $2500.

This example is assembled to a fixed address above DOS for simplicity, so the space between DOS's MEMLO and $2000 is wasted. A production handler loads at whatever MEMLO currently is, which means writing relocatable code or including a small relocating loader that fixes up the absolute addresses. Always check that MEMLO is below your load address before you install. Otherwise you will overwrite whatever got there first.

4. Surviving RESET: the DOSINI chain

The Rev. A OS listing shows what RESET does. A warm start clears pages 2 and 3 completely, copies the five ROM entries (P:, C:, E:, S:, K:) back into HATABS and sets MEMLO back to $0700. Your HATABS entry and your MEMLO value are both gone. The OS then checks whether a disk boot succeeded. If so, it calls the routine pointed to by DOSINI ($0C/$0D, 12/13), which is how DOS reinstalls D: and restores its own MEMLO.

DOSINI is your hook, too. The installer saves DOS's DOSINI and replaces it with reset, which first calls the old routine (JSR olddos, where olddos is a JMP patched with the saved address) and then puts the handler back. Order matters: DOS must run first, because it resets MEMLO to its own value and you raise it afterwards. BASIC is not affected: it read MEMLO into its own LOMEM pointer when it cold-started after the boot (and AUTORUN.SYS) had finished, and a RESET leaves that pointer alone.

Two cautions:

  • Install only once. Loading the file a second time would save your own reset as the "old" DOSINI and make it call itself forever. Real handlers check for their own signature first.
  • DOSINI is called on RESET only if a disk boot happened (bit 0 of BOOT? at $09). That is always true under DOS, but not when a handler is loaded some other way, for example by an emulator's direct XEX loader.

5. Install and test it

Copy mdev.xex to a DOS 2.0S or 2.5 disk as AUTORUN.SYS, then boot with BASIC. DOS loads it at boot, the INIT segment installs M:, and BASIC comes up with the device ready. Then type in this program:

10 GRAPHICS 0:DIM L$(40):POKE 1536,PEEK(1536)+1:PRINT "RUN NUMBER ";PEEK(1536)
20 OPEN #1,8,0,"M:"
30 FOR I=1 TO 4:PRINT #1;"LINE ";I;": ";I*I*I:NEXT I
40 CLOSE #1
50 OPEN #1,4,0,"M:":TRAP 80
60 INPUT #1,L$:PRINT "READ BACK> ";L$
70 GOTO 60
80 PRINT "STOPPED WITH ERROR ";PEEK(195):CLOSE #1
90 PRINT "MEMLO=";PEEK(743)+256*PEEK(744)
100 TRAP 120:XIO 40,#2,0,0,"M:"
120 PRINT "XIO 40 GAVE ERROR ";PEEK(195)

RUN it, press RESET and RUN it again. The screenshot shows the second run: the counter in page 6 has reached 2, the four records come back, the read stops with 136, MEMLO is still 9472, and the XIO reaches the SPECIAL vector and returns 146. XIO works on channel 2 even though it was never opened, because CIO does an implied OPEN for STATUS and SPECIAL commands. As a control, a copy of the handler without the DOSINI hook passes the first run and fails after RESET with ERROR- 130 (nonexistent device) at line 20.

Other things to try: LIST "M:" and later ENTER "M:" copy a short BASIC program through the buffer, and DOS's copy command can send a text file to M: and back.

6. Going further

  • Filter devices. A handler can wrap an existing one. Find its entry in HATABS, copy its vector table into your own, replace just the PUT vector with yours, and jump to the original routine (its table entry plus one) when you are done. The modified printer handler in Antic's 1989 series did exactly this to print control characters as graphics.
  • Don't call CIO from inside a handler. CIO is not re-entrant: its working copy of the IOCB is in page zero. If a handler must talk to the user, it should call the E: or K: handler's own vectors, or SIO, directly.
  • STATUS details beyond the status code conventionally go in the four DVSTAT bytes ($02EA–$02ED, 746–749), which the OS's serial handlers use for the device's reply. A program reads them with PEEK after the STATUS call.

Troubleshooting

  • ERROR 130 after RESET: the DOSINI chain isn't installed, or the disk wasn't a booted DOS disk.
  • ERROR 146 on every PRINT #: a vector points to the wrong place. Remember the minus one, and check the order OPEN, CLOSE, GET, PUT, STATUS, SPECIAL.
  • Machine crashes on OPEN: the HATABS entry points at the routine instead of the vector table, or a vector is off by one and RTS lands mid-instruction.
  • BASIC program corrupts the handler: MEMLO wasn't raised, or the handler was installed after BASIC had already started (from the DOS menu, say). Typing NEW makes BASIC re-read MEMLO.
  • Error 131 or 135: CIO rejected the call because of the OPEN mode in AUX1. Your handler wasn't involved.

Further reading

  • De Re Atari (Atari, 1982), chapter 8: HATABS layout, the printer handler's vector table and the classic null handler.
  • Mapping the Atari by Ian Chadwick: locations 12–13 (DOSINI), 32–47 (ZIOCB), 743–744 (MEMLO) and 794–831 (HATABS), plus the four steps for adding a driver.
  • "Customizing the Atari Operating System Device Handlers", Bob Martin and Martin Mercorelli, Antic, June and July 1989: a BASIC-installed null handler, a printer filter and the MAKEBOOT handler.
  • Atari 400/800 Operating System Source Listing (Atari, 1981): the CIO module, especially CIJUMP, DEVSRC and the command table COMTAB.
  • Bill Wilkinson's "Insight: Atari" columns in COMPUTE!, January and April 1982.
  • On this site: CIO and IOCBs: How Atari Input/Output Really Works, Writing a Bootable Disk Program and Inside the XEX.

Credits