home *** CD-ROM | disk | FTP | other *** search
/ ftp.elysium.pl / ftp.elysium.pl.tar / ftp.elysium.pl / docs / hardware / 64doc < prev    next >
Text File  |  2010-08-07  |  83KB  |  1,946 lines

  1. #
  2. # $Id: 64doc,v 1.8 1994/06/03 19:50:04 jopi Exp $
  3. #
  4. # This file is part of Commodore 64 emulator
  5. #      and Program Development System.
  6. #
  7. # See README for copyright notice
  8. #
  9. # This file contains documentation for 6502/6510/8500/8502 instruction set.
  10. #
  11. #
  12. # Written by 
  13. #   John West       (john@ucc.gu.uwa.edu.au)
  14. #   Marko M"akel"a  (msmakela@kruuna.helsinki.fi)
  15. #
  16. #
  17. # $Log: 64doc,v $
  18. # Revision 1.8  1994/06/03  19:50:04  jopi
  19. # Patchlevel 2
  20. #
  21. # Revision 1.7  1994/04/15  13:07:04  jopi
  22. # 65xx Register descriptions added
  23. #
  24. # Revision 1.6  1994/02/18  16:09:36  jopi
  25. #
  26. # Revision 1.5  1994/01/26  16:08:37  jopi
  27. # X64 version 0.2 PL 1
  28. #
  29. # Revision 1.4  1993/11/10  01:55:34  jopi
  30. #
  31. # Revision 1.3  93/06/21  13:37:18  jopi
  32. #  X64 version 0.2 PL 0
  33. # Revision 1.2  93/06/21  13:07:15  jopi
  34. # *** empty log message ***
  35. #
  36.  
  37.  Note: To extract the uuencoded ML programs in this article most
  38.        easily you may use e.g. "uud" by Edwin Kremer <edwin@zlotty>,
  39.        which extracts them all at once.
  40.  
  41.  
  42.  
  43.     Documentation for the NMOS 65xx/85xx Instruction Set
  44.  
  45.         6510 Instructions by Addressing Modes
  46.         6502 Registers
  47.         6510/8502 Undocumented Commands
  48.         Register selection for load and store
  49.         Decimal mode in NMOS 6500 series
  50.         6510 features
  51.         Different CPU types
  52.         6510 Instruction Timing
  53.         How Real Programmers Acknowledge Interrupts
  54.         Memory Management
  55.         Autostart Code
  56.         Notes
  57.         References
  58.  
  59.  
  60.                 6510 Instructions by Addressing Modes
  61.  
  62. off- ++++++++++ Positive ++++++++++  ---------- Negative ----------
  63. set  00      20      40      60      80      a0      c0      e0      mode
  64.  
  65. +00  BRK     JSR     RTI     RTS     NOP*    LDY     CPY     CPX     Impl/immed
  66. +01  ORA     AND     EOR     ADC     STA     LDA     CMP     SBC     (indir,x)
  67. +02   t       t       t       t      NOP*t   LDX     NOP*t   NOP*t     ? /immed
  68. +03  SLO*    RLA*    SRE*    RRA*    SAX*    LAX*    DCP*    ISB*    (indir,x)
  69. +04  NOP*    BIT     NOP*    NOP*    STY     LDY     CPY     CPX     Zeropage
  70. +05  ORA     AND     EOR     ADC     STA     LDA     CMP     SBC     Zeropage
  71. +06  ASL     ROL     LSR     ROR     STX     LDX     DEC     INC     Zeropage
  72. +07  SLO*    RLA*    SRE*    RRA*    SAX*    LAX*    DCP*    ISB*    Zeropage
  73.  
  74. +08  PHP     PLP     PHA     PLA     DEY     TAY     INY     INX     Implied
  75. +09  ORA     AND     EOR     ADC     NOP*    LDA     CMP     SBC     Immediate
  76. +0a  ASL     ROL     LSR     ROR     TXA     TAX     DEX     NOP     Accu/impl
  77. +0b  ANC**   ANC**   ASR**   ARR**   ANE**   LXA**   SBX**   SBC*    Immediate
  78. +0c  NOP*    BIT     JMP     JMP  () STY     LDY     CPY     CPX     Absolute
  79. +0d  ORA     AND     EOR     ADC     STA     LDA     CMP     SBC     Absolute
  80. +0e  ASL     ROL     LSR     ROR     STX     LDX     DEC     INC     Absolute
  81. +0f  SLO*    RLA*    SRE*    RRA*    SAX*    LAX*    DCP*    ISB*    Absolute
  82.  
  83. +10  BPL     BMI     BVC     BVS     BCC     BCS     BNE     BEQ     Relative
  84. +11  ORA     AND     EOR     ADC     STA     LDA     CMP     SBC     (indir),y
  85. +12   t       t       t       t       t       t       t       t         ?
  86. +13  SLO*    RLA*    SRE*    RRA*    SHA**   LAX*    DCP*    ISB*    (indir),y
  87. +14  NOP*    NOP*    NOP*    NOP*    STY     LDY     NOP*    NOP*    Zeropage,x
  88. +15  ORA     AND     EOR     ADC     STA     LDA     CMP     SBC     Zeropage,x
  89. +16  ASL     ROL     LSR     ROR     STX  y) LDX  y) DEC     INC     Zeropage,x
  90. +17  SLO*    RLA*    SRE*    RRA*    SAX* y) LAX* y) DCP*    ISB*    Zeropage,x
  91.  
  92. +18  CLC     SEC     CLI     SEI     TYA     CLV     CLD     SED     Implied
  93. +19  ORA     AND     EOR     ADC     STA     LDA     CMP     SBC     Absolute,y
  94. +1a  NOP*    NOP*    NOP*    NOP*    TXS     TSX     NOP*    NOP*    Implied
  95. +1b  SLO*    RLA*    SRE*    RRA*    SHS**   LAS**   DCP*    ISB*    Absolute,y
  96. +1c  NOP*    NOP*    NOP*    NOP*    SHY**   LDY     NOP*    NOP*    Absolute,x
  97. +1d  ORA     AND     EOR     ADC     STA     LDA     CMP     SBC     Absolute,x
  98. +1e  ASL     ROL     LSR     ROR     SHX**y) LDX  y) DEC     INC     Absolute,x
  99. +1f  SLO*    RLA*    SRE*    RRA*    SHA**y) LAX* y) DCP*    ISB*    Absolute,x
  100.  
  101.  
  102.     ROR intruction is available on MC650x microprocessors after
  103.     June, 1976.
  104.  
  105.  
  106.         Legend:
  107.  
  108.         t       Jams the machine
  109.         *t      Jams very rarely
  110.         *       Undocumented command
  111.         **      Unusual operation
  112.         y)      indexed using Y instead of X
  113.         ()      indirect instead of absolute
  114.  
  115.         Note that the NOP instructions do have other addressing modes
  116.         than the implied addressing. The NOP instruction is just like
  117.         any other load instruction, except it does not store the
  118.         result anywhere nor affects the flags.
  119.  
  120.  
  121.                 6502 Registers
  122.  
  123.   The NMOS 65xx processors are not ruined with too many registers. In
  124. addition to that, the registers are mostly 8-bit. Here is a brief
  125. description of each register:
  126.  
  127.        PC   Program Counter
  128.  
  129.             This register points the address from which the next
  130.             instruction byte (opcode or parameter) will be fetched.
  131.             Unlike other registers, this one is 16 bits in length. The
  132.             low and high 8-bit halves of the register are called PCL
  133.             and PCH, respectively.
  134.  
  135.             The Program Counter may be read by pushing its value on
  136.             the stack. This can be done either by jumping to a
  137.             subroutine or by causing an interrupt.
  138.  
  139.        S    Stack pointer
  140.  
  141.             The NMOS 65xx processors have 256 bytes of stack memory,
  142.             ranging from $0100 to $01FF. The S register is a 8-bit
  143.             offset to the stack page. In other words, whenever
  144.             anything is being pushed on the stack, it will be stored
  145.             to the address $0100+S.
  146.  
  147.             The Stack pointer can be read and written by transfering
  148.             its value to or from the index register X (see below) with
  149.             the TSX and TXS instructions.
  150.  
  151.        P    Processor status
  152.  
  153.             This 8-bit register stores the state of the processor. The
  154.             bits in this register are called flags. Most of the flags
  155.             have something to do with arithmetic operations.
  156.  
  157.             The P register can be read by pushing it on the stack
  158.             (with PHP or by causing an interrupt). If you only need to
  159.             read one flag, you can use the branch instructions.
  160.             Setting the flags is possible by pulling the P register
  161.             from stack or by using the flag set or clear instructions.
  162.  
  163.             Following is a list of the flags, starting from the 8th
  164.             bit of the P register (bit 7, value $80):
  165.  
  166.             N   Negative flag
  167.  
  168.                 This flag will be set after any arithmetic operations
  169.                 (when any of the registers A, X or Y is being loaded
  170.                 with a value). Generally, the N flag will be copied
  171.                 from the topmost bit of the register being loaded.
  172.  
  173.                 Note that TXS (Transfer X to S) is not an arithmetic
  174.                 operation. Also note that the BIT instruction affects
  175.                 the Negative flag just like arithmetic operations.
  176.                 Finally, the Negative flag behaves differently in
  177.                 Decimal operations (see description below).
  178.  
  179.             V   oVerflow flag
  180.  
  181.                 Like the Negative flag, this flag is intended to be
  182.                 used with 8-bit signed integer numbers. The flag will
  183.                 be affected by addition and subtraction, the
  184.                 instructions PLP, CLV and BIT, and the hardware signal
  185.                 -SO. Note that there is no SEV instruction, even though
  186.                 the MOS engineers loved to use East European abbreviations,
  187.                 like DDR (Deutsche Demokratische Republik vs. Data
  188.                 Direction Register). (The Russian abbreviation for their
  189.                 former trade association COMECON is SEV.) The -SO
  190.                 (Set Overflow) signal is available on some processors,
  191.                 at least the 6502, to set the V flag. This enables
  192.                 response to an I/O activity in equal or less than
  193.                 three clock cycles when using a BVC instruction branching
  194.                 to itself ($50 $FE).
  195.  
  196.                 The CLV instruction clears the V flag, and the PLP and
  197.                 BIT instructions copy the flag value from the bit 6 of
  198.                 the topmost stack entry or from memory.
  199.  
  200.                 After a binary addition or subtraction, the V flag
  201.                 will be set on a sign overflow, cleared otherwise.
  202.                 What is a sign overflow?  For instance, if you are
  203.                 trying to add 123 and 45 together, the result (168)
  204.                 does not fit in a 8-bit signed integer (upper limit
  205.                 127 and lower limit -128). Similarly, adding -123 to
  206.                 -45 causes the overflow, just like subtracting -45
  207.                 from 123 or 123 from -45 would do.
  208.  
  209.                 Like the N flag, the V flag will not be set as
  210.                 expected in the Decimal mode. Later in this document
  211.                 is a precise operation description.
  212.  
  213.                 A common misbelief is that the V flag could only be
  214.                 set by arithmetic operations, not cleared.
  215.  
  216.             1   unused flag
  217.  
  218.                 To the current knowledge, this flag is always 1.
  219.  
  220.             B   Break flag
  221.  
  222.                 This flag is used to distinguish software (BRK)
  223.                 interrupts from hardware interrupts (IRQ or NMI). The
  224.                 B flag is always set except when the P register is
  225.                 being pushed on stack when jumping to an interrupt
  226.                 routine to process only a hardware interrupt.
  227.  
  228.                 The official NMOS 65xx documentation claims that the
  229.                 BRK instruction could only cause a jump to the IRQ
  230.                 vector ($FFFE). However, if an NMI interrupt occurs
  231.                 while executing a BRK instruction, the processor will
  232.                 jump to the NMI vector ($FFFA), and the P register
  233.                 will be pushed on the stack with the B flag set.
  234.  
  235.             D   Decimal mode flag
  236.  
  237.                 This flag is used to select the (Binary Coded) Decimal
  238.                 mode for addition and subtraction. In most
  239.                 applications, the flag is zero.
  240.  
  241.                 The Decimal mode has many oddities, and it operates
  242.                 differently on CMOS processors. See the description
  243.                 of the ADC, SBC and ARR instructions below.
  244.  
  245.             I   Interrupt disable flag
  246.  
  247.                 This flag can be used to prevent the processor from
  248.                 jumping to the IRQ handler vector ($FFFE) whenever the
  249.                 hardware line -IRQ is active. The flag will be
  250.                 automatically set after taking an interrupt, so that
  251.                 the processor would not keep jumping to the interrupt
  252.                 routine if the -IRQ signal remains low for several
  253.                 clock cycles.
  254.  
  255.             Z   Zero flag
  256.  
  257.                 The Zero flag will be affected in the same cases than
  258.                 the Negative flag. Generally, it will be set if an
  259.                 arithmetic register is being loaded with the value
  260.                 zero, and cleared otherwise. The flag will behave
  261.                 differently in Decimal operations.
  262.  
  263.             C   Carry flag
  264.  
  265.                 This flag is used in additions, subtractions,
  266.                 comparisons and bit rotations. In additions and
  267.                 subtractions, it acts as a 9th bit and lets you to
  268.                 chain operations to calculate with bigger than 8-bit
  269.                 numbers. When subtracting, the Carry flag is the
  270.                 negative of Borrow: if an overflow occurs, the flag
  271.                 will be clear, otherwise set. Comparisons are a
  272.                 special case of subtraction: they assume Carry flag
  273.                 set and Decimal flag clear, and do not store the
  274.                 result of the subtraction anywhere.
  275.  
  276.                 There are four kinds of bit rotations. All of them
  277.                 store the bit that is being rotated off to the Carry
  278.                 flag. The left shifting instructions are ROL and ASL.
  279.                 ROL copies the initial Carry flag to the lowmost bit
  280.                 of the byte; ASL always clears it. Similarly, the ROR
  281.                 and LSR instructions shift to the right.
  282.  
  283.        A    Accumulator
  284.  
  285.             The accumulator is the main register for arithmetic and
  286.             logic operations. Unlike the index registers X and Y, it
  287.             has a direct connection to the Arithmetic and Logic Unit
  288.             (ALU). This is why many operations are only available for
  289.             the accumulator, not the index registers.
  290.  
  291.        X    Index register X
  292.  
  293.             This is the main register for addressing data with
  294.             indices. It has a special addressing mode, indexed
  295.             indirect, which lets you to have a vector table on the
  296.             zero page.
  297.  
  298.        Y    Index register Y
  299.  
  300.             The Y register has the least operations available. On the
  301.             other hand, only it has the indirect indexed addressing
  302.             mode that enables access to any memory place without
  303.             having to use self-modifying code.
  304.  
  305.  
  306.  
  307.                 6510/8502 Undocumented Commands
  308.  
  309.          -- A brief explanation about what may happen while
  310.                 using don't care states.
  311.  
  312.  
  313.         ANE $8B         A = (A | #$EE) & X & #byte
  314.                         same as
  315.                         A = ((A & #$11 & X) | ( #$EE & X)) & #byte
  316.  
  317.                         In real 6510/8502 the internal parameter #$11
  318.                         may occasionally be #$10, #$01 or even #$00.
  319.                         This occurs when the video chip starts DMA
  320.                         between the opcode fetch and the parameter fetch
  321.                         of the instruction.  The value probably depends
  322.                         on the data that was left on the bus by the VIC-II.
  323.  
  324.         LXA $AB         C=Lehti:   A = X = ANE
  325.                         Alternate: A = X = (A & #byte)
  326.  
  327.                         TXA and TAX have to be responsible for these.
  328.  
  329.         SHA $93,$9F     Store (A & X & (ADDR_HI + 1))
  330.         SHX $9E         Store (X & (ADDR_HI + 1))
  331.         SHY $9C         Store (Y & (ADDR_HI + 1))
  332.         SHS $9B         SHA and TXS, where X is replaced by (A & X).
  333.  
  334.                         Note: The value to be stored is copied also
  335.                         to ADDR_HI if page boundary is crossed.
  336.  
  337.         SBX $CB         Carry and Decimal flags are ignored but the
  338.                         Carry flag will be set in substraction. This
  339.                         is due to the CMP command, which is executed
  340.                         instead of the real SBC.
  341.  
  342.         ARR $6B         This instruction first performs an AND
  343.                         between the accumulator and the immediate
  344.                         parameter, then it shifts the accumulator to
  345.                         the right. However, this is not the whole
  346.                         truth. See the description below.
  347.  
  348. Many undocumented commands do not use AND between registers, the CPU
  349. just throws the bytes to a bus simultaneously and lets the
  350. open-collector drivers perform the AND. I.e. the command called 'SAX',
  351. which is in the STORE section (opcodes $A0...$BF), stores the result
  352. of (A & X) by this way.
  353.  
  354. More fortunate is its opposite, 'LAX' which just loads a byte
  355. simultaneously into both A and X.
  356.  
  357.  
  358.         $6B  ARR
  359.  
  360. This instruction seems to be a harmless combination of AND and ROR at
  361. first sight, but it turns out that it affects the V flag and also has
  362. a special kind of decimal mode. This is because the instruction has
  363. inherited some properties of the ADC instruction ($69) in addition to
  364. the ROR ($6A).
  365.  
  366. In Binary mode (D flag clear), the instruction effectively does an AND
  367. between the accumulator and the immediate parameter, and then shifts
  368. the accumulator to the right, copying the C flag to the 8th bit. It
  369. sets the Negative and Zero flags just like the ROR would. The ADC code
  370. shows up in the Carry and oVerflow flags. The C flag will be copied
  371. from the bit 6 of the result (which doesn't seem too logical), and the
  372. V flag is the result of an Exclusive OR operation between the bit 6
  373. and the bit 5 of the result.  This makes sense, since the V flag will
  374. be normally set by an Exclusive OR, too.
  375.  
  376. In Decimal mode (D flag set), the ARR instruction first performs the
  377. AND and ROR, just like in Binary mode. The N flag will be copied from
  378. the initial C flag, and the Z flag will be set according to the ROR
  379. result, as expected. The V flag will be set if the bit 6 of the
  380. accumulator changed its state between the AND and the ROR, cleared
  381. otherwise.
  382.  
  383. Now comes the funny part. If the low nybble of the AND result,
  384. incremented by its lowmost bit, is greater than 5, the low nybble in
  385. the ROR result will be incremented by 6. The low nybble may overflow
  386. as a consequence of this BCD fixup, but the high nybble won't be
  387. adjusted. The high nybble will be BCD fixed in a similar way. If the
  388. high nybble of the AND result, incremented by its lowmost bit, is
  389. greater than 5, the high nybble in the ROR result will be incremented
  390. by 6, and the Carry flag will be set. Otherwise the C flag will be
  391. cleared.
  392.  
  393. To help you understand this description, here is a C routine that
  394. illustrates the ARR operation in Decimal mode:
  395.  
  396.         unsigned
  397.            A,  /* Accumulator */
  398.            AL, /* low nybble of accumulator */
  399.            AH, /* high nybble of accumulator */
  400.  
  401.            C,  /* Carry flag */
  402.            Z,  /* Zero flag */
  403.            V,  /* oVerflow flag */
  404.            N,  /* Negative flag */
  405.  
  406.            t,  /* temporary value */
  407.            s;  /* value to be ARRed with Accumulator */
  408.  
  409.         t = A & s;                      /* Perform the AND. */
  410.  
  411.         AH = t >> 4;                    /* Separate the high */
  412.         AL = t & 15;                    /* and low nybbles. */
  413.  
  414.         N = C;                          /* Set the N and */
  415.         Z = !(A = (t >> 1) | (C << 7)); /* Z flags traditionally */
  416.         V = (t ^ A) & 64;               /* and V flag in a weird way. */
  417.  
  418.         if (AL + (AL & 1) > 5)          /* BCD "fixup" for low nybble. */
  419.           A = (A & 0xF0) | ((A + 6) & 0xF);
  420.  
  421.         if (C = AH + (AH & 1) > 5)      /* Set the Carry flag. */
  422.           A = (A + 0x60) & 0xFF;        /* BCD "fixup" for high nybble. */
  423.  
  424.  
  425.  
  426.         $CB  SBX   X <- (A & X) - Immediate
  427.  
  428. The 'SBX' ($CB) may seem to be very complex operation, even though it
  429. is a combination of the subtraction of accumulator and parameter, as
  430. in the 'CMP' instruction, and the command 'DEX'. As a result, both A
  431. and X are connected to ALU but only the subtraction takes place. Since
  432. the comparison logic was used, the result of subtraction should be
  433. normally ignored, but the 'DEX' now happily stores to X the value of
  434. (A & X) - Immediate.  That is why this instruction does not have any
  435. decimal mode, and it does not affect the V flag. Also Carry flag will
  436. be ignored in the subtraction but set according to the result.
  437.  
  438.  Proof:
  439.  
  440. begin 644 vsbx
  441. M`0@9$,D'GL(H-#,IJC(U-JS"*#0T*:HR-@```*D`H#V1*Z`_D2N@09$KJ0>%
  442. M^QBE^VEZJ+$KH#F1*ZD`2"BI`*(`RP`(:-B@.5$K*4#P`E@`H#VQ*SAI`)$K
  443. JD-Z@/[$K:0"1*Y#4J2X@TO\XH$&Q*VD`D2N0Q,;[$+188/_^]_:_OK>V
  444. `
  445. end
  446.  
  447.  and
  448.  
  449. begin 644 sbx
  450. M`0@9$,D'GL(H-#,IJC(U-JS"*#0T*:HR-@```'BI`*!-D2N@3Y$KH%&1*ZD#
  451. MA?L8I?M*2)`#J1@LJ3B@29$K:$J0`ZGX+*G8R)$K&/BXJ?2B8\L)AOP(:(7]
  452. MV#B@3;$KH$\Q*Z!1\2L(1?SP`0!H1?TIM]#XH$VQ*SAI`)$KD,N@3[$K:0"1
  453. 9*Y#!J2X@TO\XH%&Q*VD`D2N0L<;[$))88-#X
  454. `
  455. end
  456.  
  457. These test programs show if your machine is compatible with ours
  458. regarding the opcode $CB. The first test, vsbx, proves that SBX does
  459. not affect the V flag. The latter one, sbx, proves the rest of our
  460. theory. The vsbx test tests 33554432 SBX combinations (16777216
  461. different A, X and Immediate combinations, and two different V flag
  462. states), and the sbx test doubles that amount (16777216*4 D and C flag
  463. combinations). Both tests have run successfully on a C64 and a Vic20.
  464. They ought to run on C16, +4 and the PET series as well. The tests
  465. stop with BRK, if the opcode $CB does not work as expected. Successful
  466. operation ends in RTS. As the tests are very slow, they print dots on
  467. the screen while running so that you know that the machine has not
  468. jammed. On computers running at 1 MHz, the first test prints
  469. approximately one dot every four seconds and a total of 2048 dots,
  470. whereas the second one prints half that amount, one dot every seven
  471. seconds.
  472.  
  473. If the tests fail on your machine, please let us know your processor's
  474. part number and revision. If possible, save the executable (after it
  475. has stopped with BRK) under another name and send it to us so that we
  476. know at which stage the program stopped.
  477.  
  478. The following program is a Commodore 64 executable that Marko M"akel"a
  479. developed when trying to find out how the V flag is affected by SBX.
  480. (It was believed that the SBX affects the flag in a weird way, and
  481. this program shows how SBX sets the flag differently from SBC.)  You
  482. may find the subroutine at $C150 useful when researching other
  483. undocumented instructions' flags. Run the program in a machine
  484. language monitor, as it makes use of the BRK instruction. The result
  485. tables will be written on pages $C2 and $C3.
  486.  
  487. begin 644 sbx-c100
  488. M`,%XH`",#L&,$,&,$L&XJ8*B@LL7AOL(:(7\N#BM#L$M$,'M$L$(Q?OP`B@`
  489. M:$7\\`,@4,'N#L'0U.X0P=#/SB#0[A+!T,<``````````````)BJ\!>M#L$M
  490. L$,'=_\'0":T2P=W_PM`!8,K0Z:T.P2T0P9D`PID`!*T2P9D`PYD`!<C0Y``M
  491. `
  492. end
  493.  
  494.  
  495. Other undocumented instructions usually cause two preceding opcodes
  496. being executed. However 'NOP' seems to completely disappear from 'SBC'
  497. code $EB.
  498.  
  499. The most difficult to comprehend are the rest of the instructions
  500. located on the '$0B' line.
  501.  
  502. All the instructions located at the positive (left) side of this line
  503. should rotate either memory or the accumulator, but the addressing
  504. mode turns out to be immediate! No problem. Just read the operand, let
  505. it be ANDed with the accumulator and finally use accumulator
  506. addressing mode for the instructions above them.
  507.  
  508. RELIGION_MODE_ON
  509. /* This part of the document is not accurate.  You can
  510.    read it as a fairy tale, but do not count on it when
  511.    performing your own measurements. */
  512.  
  513. The rest two instructions on the same line, called 'ANE' and 'LXA'
  514. ($8B and $AB respectively) often give quite unpredictable results.
  515. However, the most usual operation is to store ((A | #$ee) & X & #$nn)
  516. to accumulator. Note that this does not work reliably in a real 64!
  517. In the Commodore 128 the opcode $8B uses values 8C, CC, EE, and
  518. occasionally 0C and 8E for the OR instead of EE,EF,FE and FF used in
  519. the C64. With a C128 running at 2 MHz #$EE is always used.  Opcode $AB
  520. does not cause this OR taking place on 8502 while 6510 always performs
  521. it. Note that this behaviour depends on processor and/or video chip
  522. revision.
  523.  
  524. Let's take a closer look at $8B (6510).
  525.  
  526.         A <- X & D & (A | VAL)
  527.  
  528.         where VAL comes from this table:
  529.  
  530.        X high   D high  D low   VAL
  531.         even     even    ---    $EE (1)
  532.         even     odd     ---    $EE
  533.         odd      even    ---    $EE
  534.         odd      odd      0     $EE
  535.         odd      odd     not 0  $FE (2)
  536.  
  537. (1) If the bottom 2 bits of A are both 1, then the LSB of the result may
  538.     be 0. The values of X and D are different every time I run the test.
  539.     This appears to be very rare.
  540. (2) VAL is $FE most of the time. Sometimes it is $EE - it seems to be random,
  541.     not related to any of the data. This is much more common than (1).
  542.  
  543.   In decimal mode, VAL is usually $FE.
  544.  
  545.  
  546. Two different functions have been discovered for LAX, opcode $AB. One
  547. is A = X = ANE (see above) and the other, encountered with 6510 and
  548. 8502, is less complicated A = X = (A & #byte). However, according to
  549. what is reported, the version altering only the lowest bits of each
  550. nybble seems to be more common.
  551.  
  552. What happens, is that $AB loads a value into both A and X, ANDing the
  553. low bit of each nybble with the corresponding bit of the old
  554. A. However, there are exceptions. Sometimes the low bit is cleared
  555. even when A contains a '1', and sometimes other bits are cleared. The
  556. exceptions seem random (they change every time I run the test). Oops -
  557. that was in decimal mode. Much the same with D=0.
  558.  
  559. What causes the randomness?  Probably it is that it is marginal logic
  560. levels - when too much wired-anding goes on, some of the signals get
  561. very close to the threshold. Perhaps we're seeing some of them step
  562. over it. The low bit of each nybble is special, since it has to cope
  563. with carry differently (remember decimal mode). We never see a '0'
  564. turn into a '1'.
  565.  
  566. Since these instructions are unpredictable, they should not be used.
  567.  
  568. There is still very strange instruction left, the one named SHA/X/Y,
  569. which is the only one with only indexed addressing modes. Actually,
  570. the commands 'SHA', 'SHX' and 'SHY' are generated by the indexing
  571. algorithm.
  572.  
  573. While using indexed addressing, effective address for page boundary
  574. crossing is calculated as soon as possible so it does not slow down
  575. operation. As a result, in the case of SHA/X/Y, the address and data
  576. are processed at the same time making AND between them to take place.
  577. Thus, the value to be stored by SAX, for example, is in fact (A & X &
  578. (ADDR_HI + 1)).  On page boundary crossing the same value is copied
  579. also to high byte of the effective address.
  580.  
  581. RELIGION_MODE_OFF
  582.  
  583.                 Register selection for load and store
  584.  
  585.    bit1 bit0     A  X  Y
  586.     0    0             x
  587.     0    1          x
  588.     1    0       x
  589.     1    1       x  x
  590.  
  591. So, A and X are selected by bits 1 and 0 respectively, while
  592. ~(bit1|bit0) enables Y.
  593.  
  594. Indexing is determined by bit4, even in relative addressing mode,
  595. which is one kind of indexing.
  596.  
  597. Lines containing opcodes xxx000x1 (01 and 03) are treated as absolute
  598. after the effective address has been loaded into CPU.
  599.  
  600. Zeropage,y and Absolute,y (codes 10x1 x11x) are distinquished by bit5.
  601.  
  602.  
  603.                  Decimal mode in NMOS 6500 series
  604.  
  605.   Most sources claim that the NMOS 6500 series sets the N, V and Z
  606. flags unpredictably when performing addition or subtraction in decimal
  607. mode. Of course, this is not true. While testing how the flags are
  608. set, I also wanted to see what happens if you use illegal BCD values.
  609.  
  610.   ADC works in Decimal mode in a quite complicated way. It is amazing
  611. how it can do that all in a single cycle. Here's a C code version of
  612. the instruction:
  613.  
  614.         unsigned
  615.            A,  /* Accumulator */
  616.            AL, /* low nybble of accumulator */
  617.            AH, /* high nybble of accumulator */
  618.  
  619.            C,  /* Carry flag */
  620.            Z,  /* Zero flag */
  621.            V,  /* oVerflow flag */
  622.            N,  /* Negative flag */
  623.  
  624.            s;  /* value to be added to Accumulator */
  625.  
  626.         AL = (A & 15) + (s & 15) + C;         /* Calculate the lower nybble. */
  627.  
  628.         AH = (A >> 4) + (s >> 4) + (AL > 15); /* Calculate the upper nybble. */
  629.  
  630.         if (AL > 9) AL += 6;                  /* BCD fixup for lower nybble. */
  631.  
  632.         Z = ((A + s + C) & 255 != 0);         /* Zero flag is set just
  633.                                                  like in Binary mode. */
  634.  
  635.         /* Negative and Overflow flags are set with the same logic than in
  636.            Binary mode, but after fixing the lower nybble. */
  637.  
  638.         N = (AH & 8 != 0);
  639.         V = ((AH << 4) ^ A) & 128 && !((A ^ s) & 128);
  640.  
  641.         if (AH > 9) AH += 6;                  /* BCD fixup for upper nybble. */
  642.  
  643.         /* Carry is the only flag set after fixing the result. */
  644.  
  645.         C = (AH > 15);
  646.         A = ((AH << 4) | (AL & 15)) & 255;
  647.  
  648.  
  649.   The C flag is set as the quiche eaters expect, but the N and V flags 
  650. are set after fixing the lower nybble but before fixing the upper one.
  651. They use the same logic than binary mode ADC. The Z flag is set before
  652. any BCD fixup, so the D flag does not have any influence on it.
  653.  
  654. Proof: The following test program tests all 131072 ADC combinations in
  655.        Decimal mode, and aborts with BRK if anything breaks this theory.
  656.        If everything goes well, it ends in RTS.
  657.  
  658. begin 600 dadc
  659. M 0@9",D'GL(H-#,IJC(U-JS"*#0T*:HR-@   'BI&*  A/N$_$B@+)$KH(V1
  660. M*Q@(I?PI#X7]I?LI#V7]R0J0 FD%J"D/A?VE^RGP9?PI\ C $) ":0^JL @H
  661. ML ?)H) &""@X:5\X!?V%_0AH*3W@ ! ""8"HBD7[$ JE^T7\, 28"4"H**7[
  662. M9?S0!)@) J@8N/BE^V7\V A%_= G:(3]1?W0(.;[T(?F_-"#:$D8\ )88*D=
  663. 0&&4KA?NI &4LA?RI.&S[  A%
  664.  
  665. end
  666.  
  667.   All programs in this chapter have been successfully tested on a Vic20
  668. and a Commodore 64 and a Commodore 128D in C64 mode. They should run on
  669. C16, +4 and on the PET series as well. If not, please report the problem
  670. to Marko M"akel"a. Each test in this chapter should run in less than a
  671. minute at 1 MHz.
  672.  
  673. SBC is much easier. Just like CMP, its flags are not affected by
  674. the D flag.
  675.  
  676. Proof:
  677.  
  678. begin 600 dsbc-cmp-flags
  679. M 0@9",D'GL(H-#,IJC(U-JS"*#0T*:HR-@   'B@ (3[A/RB XH8:66HL2N@
  680. M09$KH$R1*XII::BQ*Z!%D2N@4)$K^#BXI?OE_-@(:(7].+BE^^7\"&A%_? !
  681. 5 .;[T./F_-#?RA"_8!@X&#CEY<7%
  682.  
  683. end
  684.  
  685.  
  686.   The only difference in SBC's operation in decimal mode from binary mode
  687. is the result-fixup:
  688.  
  689.         unsigned
  690.            A,  /* Accumulator */
  691.            AL, /* low nybble of accumulator */
  692.            AH, /* high nybble of accumulator */
  693.  
  694.            C,  /* Carry flag */
  695.            Z,  /* Zero flag */
  696.            V,  /* oVerflow flag */
  697.            N,  /* Negative flag */
  698.  
  699.            s;  /* value to be added to Accumulator */
  700.  
  701.         AL = (A & 15) - (s & 15) - !C;        /* Calculate the lower nybble. */
  702.  
  703.         if (AL & 16) AL -= 6;                 /* BCD fixup for lower nybble. */
  704.  
  705.         AH = (A >> 4) - (s >> 4) - (AL & 16); /* Calculate the upper nybble. */
  706.  
  707.         if (AH & 16) AH -= 6;                 /* BCD fixup for upper nybble. */
  708.  
  709.         /* The flags are set just like in Binary mode. */
  710.  
  711.         C = (A - s - !C) & 256 != 0;
  712.         Z = (A - s - !C) & 255 != 0;
  713.         V = ((A - s - !C) ^ s) & 128 && (A ^ s) & 128;
  714.         N = (A - s - !C) & 128 != 0;
  715.  
  716.         A = ((AH << 4) | (AL & 15)) & 255;
  717.  
  718.  
  719.   Again Z flag is set before any BCD fixup. The N and V flags are set
  720. at any time before fixing the high nybble. The C flag may be set in any
  721. phase.
  722.  
  723.   Decimal subtraction is easier than decimal addition, as you have to
  724. make the BCD fixup only when a nybble overflows. In decimal addition,
  725. you had to verify if the nybble was greater than 9. The processor has
  726. an internal "half carry" flag for the lower nybble, used to trigger
  727. the BCD fixup. When calculating with legal BCD values, the lower nybble
  728. cannot overflow again when fixing it.
  729. So, the processor does not handle overflows while performing the fixup.
  730. Similarly, the BCD fixup occurs in the high nybble only if the value
  731. overflows, i.e. when the C flag will be cleared.
  732.  
  733.   Because SBC's flags are not affected by the Decimal mode flag, you
  734. could guess that CMP uses the SBC logic, only setting the C flag
  735. first. But the SBX instruction shows that CMP also temporarily clears
  736. the D flag, although it is totally unnecessary.
  737.  
  738.   The following program, which tests SBC's result and flags,
  739. contains the 6502 version of the pseudo code example above.
  740.  
  741. begin 600 dsbc
  742. M 0@9",D'GL(H-#,IJC(U-JS"*#0T*:HR-@   'BI&*  A/N$_$B@+)$KH':1
  743. M*S@(I?PI#X7]I?LI#^7]L /I!1@I#ZBE_"GPA?VE^RGP"#CE_2GPL KI7RBP
  744. M#ND/.+ )*+ &Z0^P NE?A/T%_87]*+BE^^7\"&BH.+CXI?OE_-@(1?W0FVB$
  745. 8_47]T)3F^]">YOS0FFA)&- $J3C0B%A@
  746.  
  747. end
  748.  
  749.   Obviously the undocumented instructions RRA (ROR+ADC) and ISB
  750. (INC+SBC) have inherited also the decimal operation from the official
  751. instructions ADC and SBC. The program droradc proves this statement
  752. for ROR, and the dincsbc test proves this for ISB. Finally,
  753. dincsbc-deccmp proves that ISB's and DCP's (DEC+CMP) flags are not
  754. affected by the D flag.
  755.  
  756. begin 644 droradc
  757. M`0@9",D'GL(H-#,IJC(U-JS"*#0T*:HR-@```'BI&*``A/N$_$B@+)$KH(V1
  758. M*S@(I?PI#X7]I?LI#V7]R0J0`FD%J"D/A?VE^RGP9?PI\`C`$)`":0^JL`@H
  759. ML`?)H)`&""@X:5\X!?V%_0AH*3W@`!`""8"HBD7[$`JE^T7\,`28"4"H**7[
  760. M9?S0!)@)`J@XN/BE^R;\9_S8"$7]T"=HA/U%_=`@YOO0A>;\T(%H21CP`EA@
  761. 2J1T892N%^ZD`92R%_*DX;/L`
  762. `
  763. end
  764.  
  765. begin 644 dincsbc
  766. M`0@9",D'GL(H-#,IJC(U-JS"*#0T*:HR-@```'BI&*``A/N$_$B@+)$KH':1
  767. M*S@(I?PI#X7]I?LI#^7]L`/I!1@I#ZBE_"GPA?VE^RGP"#CE_2GPL`KI7RBP
  768. M#ND/.+`)*+`&Z0^P`NE?A/T%_87]*+BE^^7\"&BH.+CXI?O&_.?\V`A%_="9
  769. ::(3]1?W0DN;[T)SF_-"8:$D8T`2I.-"&6&#\
  770. `
  771. end
  772.  
  773. begin 644 dincsbc-deccmp
  774. M`0@9",D'GL(H-#,IJC(U-JS"*#0T*:HR-@```'B@`(3[A/RB`XH8:7>HL2N@
  775. M3Y$KH%R1*XII>ZBQ*Z!3D2N@8)$KBFE_J+$KH%61*Z!BD2OX.+BE^^;\Q_S8
  776. L"&B%_3BXI?OF_,?\"&A%_?`!`.;[T-_F_-#;RA"M8!@X&#CFYL;&Q\?GYP#8
  777. `
  778. end
  779.  
  780.  
  781.  
  782.                  6510 features
  783.  
  784.    o  PHP always pushes the Break (B) flag as a `1' to the stack.
  785.       Jukka Tapanim"aki claimed in C=lehti issue 3/89, on page 27 that the
  786.       processor makes a logical OR between the status register's bit 4 
  787.       and the bit 8 of the stack pointer register (which is always 1).
  788.       He did not give any reasons for this argument, and has refused to clarify
  789.       it afterwards. Well, this was not the only error in his article...
  790.  
  791.    o  Indirect addressing modes do not handle page boundary crossing at all.
  792.       When the parameter's low byte is $FF, the effective address wraps
  793.       around and the CPU fetches high byte from $xx00 instead of $xx00+$0100.
  794.       E.g. JMP ($01FF) fetches PCL from $01FF and PCH from $0100,
  795.       and LDA ($FF),Y fetches the base address from $FF and $00.
  796.  
  797.    o  Indexed zero page addressing modes never fix the page address on
  798.       crossing the zero page boundary.
  799.       E.g. LDX #$01 : LDA ($FF,X) loads the effective address from $00 and $01.
  800.  
  801.    o  The processor always fetches the byte following a relative branch
  802.       instruction. If the branch is taken, the processor reads then the
  803.       opcode from the destination address. If page boundary is crossed, it
  804.       first reads a byte from the old page from a location that is bigger
  805.       or smaller than the correct address by one page.
  806.  
  807.    o  If you cross a page boundary in any other indexed mode,
  808.       the processor reads an incorrect location first, a location that is
  809.       smaller by one page.
  810.  
  811.    o  Read-Modify-Write instructions write unmodified data, then modified
  812.       (so INC effectively does LDX loc;STX loc;INX;STX loc)
  813.  
  814.    o  -RDY is ignored during writes
  815.       (This is why you must wait 3 cycles before doing any DMA --
  816.       the maximum number of consecutive writes is 3, which occurs
  817.       during interrupts except -RESET.)
  818.  
  819.    o  Some undefined opcodes may give really unpredictable results.
  820.  
  821.    o  All registers except the Program Counter remain unmodified after -RESET.
  822.       (This is why you must preset D and I flags in the RESET handler.)
  823.  
  824.  
  825.                 Different CPU types
  826.  
  827. The Rockwell data booklet 29651N52 (technical information about R65C00 
  828. microprocessors, dated October 1984), lists the following differences between
  829. NMOS R6502 microprocessor and CMOS R65C00 family:
  830.  
  831.  1. Indexed addressing across page boundary.
  832.         NMOS: Extra read of invalid address.
  833.         CMOS: Extra read of last instruction byte.
  834.  
  835.  2. Execution of invalid op codes.
  836.         NMOS: Some terminate only by reset. Results are undefined.
  837.         CMOS: All are NOPs (reserved for future use).
  838.  
  839.  3. Jump indirect, operand = XXFF.
  840.         NMOS: Page address does not increment.
  841.         CMOS: Page address increments and adds one additional cycle.
  842.  
  843.  4. Read/modify/write instructions at effective address.
  844.         NMOS: One read and two write cycles.
  845.         CMOS: Two read and one write cycle.
  846.  
  847.  5. Decimal flag.
  848.         NMOS: Indeterminate after reset.
  849.         CMOS: Initialized to binary mode (D=0) after reset and interrupts.
  850.  
  851.  6. Flags after decimal operation.
  852.         NMOS: Invalid N, V and Z flags.
  853.         CMOS: Valid flag adds one additional cycle.
  854.  
  855.  7. Interrupt after fetch of BRK instruction.
  856.         NMOS: Interrupt vector is loaded, BRK vector is ignored.
  857.         CMOS: BRK is executed, then interrupt is executed.
  858.  
  859.  
  860.  
  861.                 6510 Instruction Timing
  862.  
  863.   The NMOS 6500 series processors always perform at least two reads
  864. for each instruction. In addition to the operation code (opcode), they
  865. fetch the next byte. This is quite efficient, as most instructions are
  866. two or three bytes long.
  867.  
  868.   The processors also use a sort of pipelining. If an instruction does
  869. not store data in memory on its last cycle, the processor can fetch
  870. the opcode of the next instruction while executing the last cycle. For
  871. instance, the instruction EOR #$FF truly takes three cycles. On the
  872. first cycle, the opcode $49 will be fetched. During the second cycle
  873. the processor decodes the opcode and fetches the parameter #$FF. On
  874. the third cycle, the processor will perform the operation and store
  875. the result to accumulator, but simultaneously it fetches the opcode
  876. for the next instruction. This is why the instruction effectively
  877. takes only two cycles.
  878.  
  879.   The following tables show what happens on the bus while executing
  880. different kinds of instructions.
  881.  
  882.   Interrupts
  883.  
  884.      NMI and IRQ both take 7 cycles. Their timing diagram is much like
  885.      BRK's (see below). IRQ will be executed only when the I flag is
  886.      clear. IRQ and BRK both set the I flag, whereas the NMI does not
  887.      affect its state.
  888.  
  889.      The processor will usually wait for the current instruction to
  890.      complete before executing the interrupt sequence. To process the
  891.      interrupt before the next instruction, the interrupt must occur
  892.      before the last cycle of the current instruction.
  893.  
  894.      There is one exception to this rule: the BRK instruction. If a
  895.      hardware interrupt (NMI or IRQ) occurs before the fourth (flags
  896.      saving) cycle of BRK, the BRK instruction will be skipped, and
  897.      the processor will jump to the hardware interrupt vector. This
  898.      sequence will always take 7 cycles.
  899.  
  900.      You do not completely lose the BRK interrupt, the B flag will be
  901.      set in the pushed status register if a BRK instruction gets
  902.      interrupted. When BRK and IRQ occur at the same time, this does
  903.      not cause any problems, as your program will consider it as a
  904.      BRK, and the IRQ would occur again after the processor returned
  905.      from your BRK routine, unless you cleared the interrupt source in
  906.      your BRK handler. But the simultaneous occurrence of NMI and BRK
  907.      is far more fatal. If you do not check the B flag in the NMI
  908.      routine and subtract two from the return address when needed, the
  909.      BRK instruction will be skipped.
  910.  
  911.      If the NMI and IRQ interrupts overlap each other (one interrupt
  912.      occurs before fetching the interrupt vector for the other
  913.      interrupt), the processor will most probably jump to the NMI
  914.      vector in every case, and then jump to the IRQ vector after
  915.      processing the first instruction of the NMI handler. This has not
  916.      been measured yet, but the IRQ is very similar to BRK, and many
  917.      sources state that the NMI has higher priority than IRQ. However,
  918.      it might be that the processor takes the interrupt that comes
  919.      later, i.e. you could lose an NMI interrupt if an IRQ occurred in
  920.      four cycles after it.
  921.  
  922.      After finishing the interrupt sequence, the processor will start
  923.      to execute the first instruction of the interrupt routine. This
  924.      proves that the processor uses a sort of pipelining: it finishes
  925.      the current instruction (or interrupt sequence) while reading the
  926.      opcode of the next instruction.
  927.  
  928.      RESET does not push program counter on stack, and it lasts
  929.      probably 6 cycles after deactivating the signal. Like NMI, RESET
  930.      preserves all registers except PC.
  931.  
  932.  
  933.   Instructions accessing the stack
  934.  
  935.      BRK
  936.  
  937.         #  address R/W description
  938.        --- ------- --- -----------------------------------------------
  939.         1    PC     R  fetch opcode, increment PC
  940.         2    PC     R  read next instruction byte (and throw it away),
  941.                        increment PC
  942.         3  $0100,S  W  push PCH on stack (with B flag set), decrement S
  943.         4  $0100,S  W  push PCL on stack, decrement S
  944.         5  $0100,S  W  push P on stack, decrement S
  945.         6   $FFFE   R  fetch PCL
  946.         7   $FFFF   R  fetch PCH
  947.  
  948.  
  949.      RTI
  950.  
  951.         #  address R/W description
  952.        --- ------- --- -----------------------------------------------
  953.         1    PC     R  fetch opcode, increment PC
  954.         2    PC     R  read next instruction byte (and throw it away)
  955.         3  $0100,S  R  increment S
  956.         4  $0100,S  R  pull P from stack, increment S
  957.         5  $0100,S  R  pull PCL from stack, increment S
  958.         6  $0100,S  R  pull PCH from stack
  959.  
  960.  
  961.      RTS
  962.  
  963.         #  address R/W description
  964.        --- ------- --- -----------------------------------------------
  965.         1    PC     R  fetch opcode, increment PC
  966.         2    PC     R  read next instruction byte (and throw it away)
  967.         3  $0100,S  R  increment S
  968.         4  $0100,S  R  pull PCL from stack, increment S
  969.         5  $0100,S  R  pull PCH from stack
  970.         6    PC     R  increment PC
  971.  
  972.  
  973.      PHA, PHP
  974.  
  975.         #  address R/W description
  976.        --- ------- --- -----------------------------------------------
  977.         1    PC     R  fetch opcode, increment PC
  978.         2    PC     R  read next instruction byte (and throw it away)
  979.         3  $0100,S  W  push register on stack, decrement S
  980.  
  981.  
  982.      PLA, PLP
  983.  
  984.         #  address R/W description
  985.        --- ------- --- -----------------------------------------------
  986.         1    PC     R  fetch opcode, increment PC
  987.         2    PC     R  read next instruction byte (and throw it away)
  988.         3  $0100,S  R  increment S
  989.         4  $0100,S  R  pull register from stack
  990.  
  991.  
  992.      JSR
  993.  
  994.         #  address R/W description
  995.        --- ------- --- -------------------------------------------------
  996.         1    PC     R  fetch opcode, increment PC
  997.         2    PC     R  fetch low address byte, increment PC
  998.         3  $0100,S  R  internal operation (predecrement S?)
  999.         4  $0100,S  W  push PCH on stack, decrement S
  1000.         5  $0100,S  W  push PCL on stack, decrement S
  1001.         6    PC     R  copy low address byte to PCL, fetch high address
  1002.                        byte to PCH
  1003.  
  1004.  
  1005.  
  1006.   Accumulator or implied addressing
  1007.  
  1008.         #  address R/W description
  1009.        --- ------- --- -----------------------------------------------
  1010.         1    PC     R  fetch opcode, increment PC
  1011.         2    PC     R  read next instruction byte (and throw it away)
  1012.  
  1013.  
  1014.   Immediate addressing
  1015.  
  1016.         #  address R/W description
  1017.        --- ------- --- ------------------------------------------
  1018.         1    PC     R  fetch opcode, increment PC
  1019.         2    PC     R  fetch value, increment PC
  1020.  
  1021.  
  1022.   Absolute addressing
  1023.  
  1024.      JMP
  1025.  
  1026.         #  address R/W description
  1027.        --- ------- --- -------------------------------------------------
  1028.         1    PC     R  fetch opcode, increment PC
  1029.         2    PC     R  fetch low address byte, increment PC
  1030.         3    PC     R  copy low address byte to PCL, fetch high address
  1031.                        byte to PCH
  1032.  
  1033.  
  1034.      Read instructions (LDA, LDX, LDY, EOR, AND, ORA, ADC, SBC, CMP, BIT,
  1035.                         LAX, NOP)
  1036.  
  1037.         #  address R/W description
  1038.        --- ------- --- ------------------------------------------
  1039.         1    PC     R  fetch opcode, increment PC
  1040.         2    PC     R  fetch low byte of address, increment PC
  1041.         3    PC     R  fetch high byte of address, increment PC
  1042.         4  address  R  read from effective address
  1043.  
  1044.  
  1045.      Read-Modify-Write instructions (ASL, LSR, ROL, ROR, INC, DEC,
  1046.                                      SLO, SRE, RLA, RRA, ISB, DCP)
  1047.  
  1048.         #  address R/W description
  1049.        --- ------- --- ------------------------------------------
  1050.         1    PC     R  fetch opcode, increment PC
  1051.         2    PC     R  fetch low byte of address, increment PC
  1052.         3    PC     R  fetch high byte of address, increment PC
  1053.         4  address  R  read from effective address
  1054.         5  address  W  write the value back to effective address,
  1055.                        and do the operation on it
  1056.         6  address  W  write the new value to effective address
  1057.  
  1058.  
  1059.      Write instructions (STA, STX, STY, SAX)
  1060.     
  1061.         #  address R/W description
  1062.        --- ------- --- ------------------------------------------
  1063.         1    PC     R  fetch opcode, increment PC
  1064.         2    PC     R  fetch low byte of address, increment PC
  1065.         3    PC     R  fetch high byte of address, increment PC
  1066.         4  address  W  write register to effective address
  1067.  
  1068.  
  1069.   Zero page addressing
  1070.  
  1071.      Read instructions (LDA, LDX, LDY, EOR, AND, ORA, ADC, SBC, CMP, BIT,
  1072.                         LAX, NOP)
  1073.  
  1074.         #  address R/W description
  1075.        --- ------- --- ------------------------------------------
  1076.         1    PC     R  fetch opcode, increment PC
  1077.         2    PC     R  fetch address, increment PC
  1078.         3  address  R  read from effective address
  1079.  
  1080.  
  1081.      Read-Modify-Write instructions (ASL, LSR, ROL, ROR, INC, DEC,
  1082.                                      SLO, SRE, RLA, RRA, ISB, DCP)
  1083.  
  1084.         #  address R/W description
  1085.        --- ------- --- ------------------------------------------
  1086.         1    PC     R  fetch opcode, increment PC
  1087.         2    PC     R  fetch address, increment PC
  1088.         3  address  R  read from effective address
  1089.         4  address  W  write the value back to effective address,
  1090.                        and do the operation on it
  1091.         5  address  W  write the new value to effective address
  1092.  
  1093.  
  1094.      Write instructions (STA, STX, STY, SAX)
  1095.     
  1096.         #  address R/W description
  1097.        --- ------- --- ------------------------------------------
  1098.         1    PC     R  fetch opcode, increment PC
  1099.         2    PC     R  fetch address, increment PC
  1100.         3  address  W  write register to effective address
  1101.  
  1102.   Zero page indexed addressing
  1103.  
  1104.      Read instructions (LDA, LDX, LDY, EOR, AND, ORA, ADC, SBC, CMP, BIT,
  1105.                         LAX, NOP)
  1106.  
  1107.         #   address  R/W description
  1108.        --- --------- --- ------------------------------------------
  1109.         1     PC      R  fetch opcode, increment PC
  1110.         2     PC      R  fetch address, increment PC
  1111.         3   address   R  read from address, add index register to it
  1112.         4  address+I* R  read from effective address
  1113.  
  1114.        Notes: I denotes either index register (X or Y).
  1115.  
  1116.               * The high byte of the effective address is always zero,
  1117.                 i.e. page boundary crossings are not handled.
  1118.  
  1119.  
  1120.      Read-Modify-Write instructions (ASL, LSR, ROL, ROR, INC, DEC,
  1121.                                      SLO, SRE, RLA, RRA, ISB, DCP)
  1122.  
  1123.         #   address  R/W description
  1124.        --- --------- --- ---------------------------------------------
  1125.         1     PC      R  fetch opcode, increment PC
  1126.         2     PC      R  fetch address, increment PC
  1127.         3   address   R  read from address, add index register X to it
  1128.         4  address+X* R  read from effective address
  1129.         5  address+X* W  write the value back to effective address,
  1130.                          and do the operation on it
  1131.         6  address+X* W  write the new value to effective address
  1132.  
  1133.        Note: * The high byte of the effective address is always zero,
  1134.                i.e. page boundary crossings are not handled.
  1135.  
  1136.  
  1137.      Write instructions (STA, STX, STY, SAX)
  1138.  
  1139.         #   address  R/W description
  1140.        --- --------- --- -------------------------------------------
  1141.         1     PC      R  fetch opcode, increment PC
  1142.         2     PC      R  fetch address, increment PC
  1143.         3   address   R  read from address, add index register to it
  1144.         4  address+I* W  write to effective address
  1145.  
  1146.        Notes: I denotes either index register (X or Y).
  1147.  
  1148.               * The high byte of the effective address is always zero,
  1149.                 i.e. page boundary crossings are not handled.
  1150.  
  1151.  
  1152.   Absolute indexed addressing
  1153.  
  1154.      Read instructions (LDA, LDX, LDY, EOR, AND, ORA, ADC, SBC, CMP, BIT,
  1155.                         LAX, LAE, SHS, NOP)
  1156.  
  1157.         #   address  R/W description
  1158.        --- --------- --- ------------------------------------------
  1159.         1     PC      R  fetch opcode, increment PC
  1160.         2     PC      R  fetch low byte of address, increment PC
  1161.         3     PC      R  fetch high byte of address,
  1162.                          add index register to low address byte,
  1163.                          increment PC
  1164.         4  address+I* R  read from effective address,
  1165.                          fix the high byte of effective address
  1166.         5+ address+I  R  re-read from effective address
  1167.  
  1168.        Notes: I denotes either index register (X or Y).
  1169.  
  1170.               * The high byte of the effective address may be invalid
  1171.                 at this time, i.e. it may be smaller by $100.
  1172.  
  1173.               + This cycle will be executed only if the effective address
  1174.                 was invalid during cycle #4, i.e. page boundary was crossed.
  1175.  
  1176.  
  1177.      Read-Modify-Write instructions (ASL, LSR, ROL, ROR, INC, DEC,
  1178.                                      SLO, SRE, RLA, RRA, ISB, DCP)
  1179.  
  1180.         #   address  R/W description
  1181.        --- --------- --- ------------------------------------------
  1182.         1    PC       R  fetch opcode, increment PC
  1183.         2    PC       R  fetch low byte of address, increment PC
  1184.         3    PC       R  fetch high byte of address,
  1185.                          add index register X to low address byte,
  1186.                          increment PC
  1187.         4  address+X* R  read from effective address,
  1188.                          fix the high byte of effective address
  1189.         5  address+X  R  re-read from effective address
  1190.         6  address+X  W  write the value back to effective address,
  1191.                          and do the operation on it
  1192.         7  address+X  W  write the new value to effective address
  1193.  
  1194.        Notes: * The high byte of the effective address may be invalid
  1195.                 at this time, i.e. it may be smaller by $100.
  1196.  
  1197.  
  1198.      Write instructions (STA, STX, STY, SHA, SHX, SHY)
  1199.  
  1200.         #   address  R/W description
  1201.        --- --------- --- ------------------------------------------
  1202.         1     PC      R  fetch opcode, increment PC
  1203.         2     PC      R  fetch low byte of address, increment PC
  1204.         3     PC      R  fetch high byte of address,
  1205.                          add index register to low address byte,
  1206.                          increment PC
  1207.         4  address+I* R  read from effective address,
  1208.                          fix the high byte of effective address
  1209.         5  address+I  W  write to effective address
  1210.  
  1211.        Notes: I denotes either index register (X or Y).
  1212.  
  1213.               * The high byte of the effective address may be invalid
  1214.                 at this time, i.e. it may be smaller by $100. Because
  1215.                 the processor cannot undo a write to an invalid
  1216.                 address, it always reads from the address first.
  1217.  
  1218.  
  1219.   Relative addressing (BCC, BCS, BNE, BEQ, BPL, BMI, BVC, BVS)
  1220.  
  1221.         #   address  R/W description
  1222.        --- --------- --- ---------------------------------------------
  1223.         1     PC      R  fetch opcode, increment PC
  1224.         2     PC      R  fetch operand, increment PC
  1225.         3     PC      R  Fetch opcode of next instruction,
  1226.                          If branch is taken, add operand to PCL.
  1227.                          Otherwise increment PC.
  1228.         4+    PC*     R  Fetch opcode of next instruction.
  1229.                          Fix PCH. If it did not change, increment PC.
  1230.         5!    PC      R  Fetch opcode of next instruction,
  1231.                          increment PC.
  1232.  
  1233.        Notes: The opcode fetch of the next instruction is included to
  1234.               this diagram for illustration purposes. When determining
  1235.               real execution times, remember to subtract the last
  1236.               cycle.
  1237.  
  1238.               * The high byte of Program Counter (PCH) may be invalid
  1239.                 at this time, i.e. it may be smaller or bigger by $100.
  1240.  
  1241.               + If branch is taken, this cycle will be executed.
  1242.  
  1243.               ! If branch occurs to different page, this cycle will be
  1244.                 executed.
  1245.  
  1246.  
  1247.   Indexed indirect addressing
  1248.  
  1249.      Read instructions (LDA, ORA, EOR, AND, ADC, CMP, SBC, LAX)
  1250.  
  1251.         #    address   R/W description
  1252.        --- ----------- --- ------------------------------------------
  1253.         1      PC       R  fetch opcode, increment PC
  1254.         2      PC       R  fetch pointer address, increment PC
  1255.         3    pointer    R  read from the address, add X to it
  1256.         4   pointer+X   R  fetch effective address low
  1257.         5  pointer+X+1  R  fetch effective address high
  1258.         6    address    R  read from effective address
  1259.  
  1260.        Note: The effective address is always fetched from zero page,
  1261.              i.e. the zero page boundary crossing is not handled.
  1262.  
  1263.      Read-Modify-Write instructions (SLO, SRE, RLA, RRA, ISB, DCP)
  1264.  
  1265.         #    address   R/W description
  1266.        --- ----------- --- ------------------------------------------
  1267.         1      PC       R  fetch opcode, increment PC
  1268.         2      PC       R  fetch pointer address, increment PC
  1269.         3    pointer    R  read from the address, add X to it
  1270.         4   pointer+X   R  fetch effective address low
  1271.         5  pointer+X+1  R  fetch effective address high
  1272.         6    address    R  read from effective address
  1273.         7    address    W  write the value back to effective address,
  1274.                            and do the operation on it
  1275.         8    address    W  write the new value to effective address
  1276.  
  1277.        Note: The effective address is always fetched from zero page,
  1278.              i.e. the zero page boundary crossing is not handled.
  1279.  
  1280.      Write instructions (STA, SAX)
  1281.  
  1282.         #    address   R/W description
  1283.        --- ----------- --- ------------------------------------------
  1284.         1      PC       R  fetch opcode, increment PC
  1285.         2      PC       R  fetch pointer address, increment PC
  1286.         3    pointer    R  read from the address, add X to it
  1287.         4   pointer+X   R  fetch effective address low
  1288.         5  pointer+X+1  R  fetch effective address high
  1289.         6    address    W  write to effective address
  1290.  
  1291.        Note: The effective address is always fetched from zero page,
  1292.              i.e. the zero page boundary crossing is not handled.
  1293.  
  1294.   Indirect indexed addressing
  1295.  
  1296.      Read instructions (LDA, EOR, AND, ORA, ADC, SBC, CMP)
  1297.  
  1298.         #    address   R/W description
  1299.        --- ----------- --- ------------------------------------------
  1300.         1      PC       R  fetch opcode, increment PC
  1301.         2      PC       R  fetch pointer address, increment PC
  1302.         3    pointer    R  fetch effective address low
  1303.         4   pointer+1   R  fetch effective address high,
  1304.                            add Y to low byte of effective address
  1305.         5   address+Y*  R  read from effective address,
  1306.                            fix high byte of effective address
  1307.         6+  address+Y   R  read from effective address
  1308.  
  1309.        Notes: The effective address is always fetched from zero page,
  1310.               i.e. the zero page boundary crossing is not handled.
  1311.  
  1312.               * The high byte of the effective address may be invalid
  1313.                 at this time, i.e. it may be smaller by $100.
  1314.  
  1315.               + This cycle will be executed only if the effective address
  1316.                 was invalid during cycle #5, i.e. page boundary was crossed.
  1317.  
  1318.  
  1319.      Read-Modify-Write instructions (SLO, SRE, RLA, RRA, ISB, DCP)
  1320.  
  1321.         #    address   R/W description
  1322.        --- ----------- --- ------------------------------------------
  1323.         1      PC       R  fetch opcode, increment PC
  1324.         2      PC       R  fetch pointer address, increment PC
  1325.         3    pointer    R  fetch effective address low
  1326.         4   pointer+1   R  fetch effective address high,
  1327.                            add Y to low byte of effective address
  1328.         5   address+Y*  R  read from effective address,
  1329.                            fix high byte of effective address
  1330.         6   address+Y   R  read from effective address
  1331.         7   address+Y   W  write the value back to effective address,
  1332.                            and do the operation on it
  1333.         8   address+Y   W  write the new value to effective address
  1334.  
  1335.        Notes: The effective address is always fetched from zero page,
  1336.               i.e. the zero page boundary crossing is not handled.
  1337.  
  1338.               * The high byte of the effective address may be invalid
  1339.                 at this time, i.e. it may be smaller by $100.
  1340.  
  1341.  
  1342.      Write instructions (STA, SHA)
  1343.  
  1344.         #    address   R/W description
  1345.        --- ----------- --- ------------------------------------------
  1346.         1      PC       R  fetch opcode, increment PC
  1347.         2      PC       R  fetch pointer address, increment PC
  1348.         3    pointer    R  fetch effective address low
  1349.         4   pointer+1   R  fetch effective address high,
  1350.                            add Y to low byte of effective address
  1351.         5   address+Y*  R  read from effective address,
  1352.                            fix high byte of effective address
  1353.         6   address+Y   W  write to effective address
  1354.  
  1355.        Notes: The effective address is always fetched from zero page,
  1356.               i.e. the zero page boundary crossing is not handled.
  1357.  
  1358.               * The high byte of the effective address may be invalid
  1359.                 at this time, i.e. it may be smaller by $100.
  1360.  
  1361.  
  1362.   Absolute indirect addressing (JMP)
  1363.  
  1364.         #   address  R/W description
  1365.        --- --------- --- ------------------------------------------
  1366.         1     PC      R  fetch opcode, increment PC
  1367.         2     PC      R  fetch pointer address low, increment PC
  1368.         3     PC      R  fetch pointer address high, increment PC
  1369.         4   pointer   R  fetch low address to latch
  1370.         5  pointer+1* R  fetch PCH, copy latch to PCL
  1371.  
  1372.        Note: * The PCH will always be fetched from the same page
  1373.                than PCL, i.e. page boundary crossing is not handled.
  1374.  
  1375.  
  1376.  
  1377.                 How Real Programmers Acknowledge Interrupts
  1378.  
  1379.   With RMW instructions:
  1380.  
  1381.         ; beginning of combined raster/timer interrupt routine
  1382.         LSR $D019       ; clear VIC interrupts, read raster interrupt flag to C
  1383.         BCS raster      ; jump if VIC caused an interrupt
  1384.         ...             ; timer interrupt routine
  1385.  
  1386.         Operational diagram of LSR $D019:
  1387.  
  1388.           #  data  address  R/W  
  1389.          --- ----  -------  ---  ---------------------------------
  1390.           1   4E     PC      R   fetch opcode
  1391.           2   19    PC+1     R   fetch address low
  1392.           3   D0    PC+2     R   fetch address high
  1393.           4   xx    $D019    R   read memory
  1394.           5   xx    $D019    W   write the value back, rotate right
  1395.           6  xx/2   $D019    W   write the new value back
  1396.  
  1397.         The 5th cycle acknowledges the interrupt by writing the same
  1398.         value back. If only raster interrupts are used, the 6th cycle
  1399.         has no effect on the VIC. (It might acknowledge also some
  1400.         other interrupts.)
  1401.  
  1402.  
  1403.  
  1404.   With indexed addressing:
  1405.  
  1406.         ; acknowledge interrupts to both CIAs
  1407.         LDX #$10
  1408.         LDA $DCFD,X
  1409.  
  1410.         Operational diagram of LDA $DCFD,X:
  1411.  
  1412.           #  data  address  R/W  description
  1413.          --- ----  -------  ---  ---------------------------------
  1414.           1   BD     PC      R   fetch opcode
  1415.           2   FD    PC+1     R   fetch address low
  1416.           3   DC    PC+2     R   fetch address high, add X to address low
  1417.           4   xx    $DC0D    R   read from address, fix high byte of address
  1418.           5   yy    $DD0D    R   read from right address
  1419.  
  1420.  
  1421.         ; acknowledge interrupts to CIA 2
  1422.         LDX #$10
  1423.         STA $DDFD,X
  1424.  
  1425.         Operational diagram of STA $DDFD,X:
  1426.  
  1427.           #  data  address  R/W  description
  1428.          --- ----  -------  ---  ---------------------------------
  1429.           1   9D     PC      R   fetch opcode
  1430.           2   FD    PC+1     R   fetch address low
  1431.           3   DC    PC+2     R   fetch address high, add X to address low
  1432.           4   xx    $DD0D    R   read from address, fix high byte of address
  1433.           5   ac    $DE0D    W   write to right address
  1434.  
  1435.  
  1436.   With branch instructions:
  1437.  
  1438.         ; acknowledge interrupts to CIA 2
  1439.                 LDA #$00  ; clear N flag
  1440.                 JMP $DD0A
  1441.         DD0A    BPL $DC9D ; branch
  1442.         DC9D    BRK       ; return
  1443.  
  1444.         You need the following preparations to initialize the CIA registers:
  1445.  
  1446.                 LDA #$91  ; argument of BPL
  1447.                 STA $DD0B
  1448.                 LDA #$10  ; BPL
  1449.                 STA $DD0A
  1450.                 STA $DD08 ; load the ToD values from the latches
  1451.                 LDA $DD0B ; freeze the ToD display
  1452.                 LDA #$7F
  1453.                 STA $DC0D ; assure that $DC0D is $00
  1454.  
  1455.         Operational diagram of BPL $DC9D:
  1456.  
  1457.           #  data  address  R/W  description
  1458.          --- ----  -------  ---  ---------------------------------
  1459.           1   10    $DD0A    R   fetch opcode
  1460.           2   91    $DD0B    R   fetch argument
  1461.           3   xx    $DD0C    R   fetch opcode, add argument to PCL
  1462.           4   yy    $DD9D    R   fetch opcode, fix PCH
  1463.         ( 5   00    $DC9D    R   fetch opcode )
  1464.  
  1465.  
  1466.         ; acknowledge interrupts to CIA 1
  1467.                 LSR       ; clear N flag
  1468.                 JMP $DCFA
  1469.         DCFA    BPL $DD0D
  1470.         DD0D    BRK
  1471.  
  1472.         ; Again you need to set the ToD registers of CIA 1 and the
  1473.         ; Interrupt Control Register of CIA 2 first.
  1474.  
  1475.         Operational diagram of BPL $DD0D:
  1476.  
  1477.           #  data  address  R/W  description
  1478.          --- ----  -------  ---  ---------------------------------
  1479.           1   10    $DCFA    R   fetch opcode
  1480.           2   11    $DCFB    R   fetch argument
  1481.           3   xx    $DCFC    R   fetch opcode, add argument to PCL
  1482.           4   yy    $DC0D    R   fetch opcode, fix PCH
  1483.         ( 5   00    $DD0D    R   fetch opcode )
  1484.  
  1485.  
  1486.         ; acknowledge interrupts to CIA 2 automagically
  1487.                 ; preparations
  1488.                 LDA #$7F
  1489.                 STA $DD0D       ; disable all interrupt sources of CIA2
  1490.                 LDA $DD0E
  1491.                 AND #$BE        ; ensure that $DD0C remains constant
  1492.                 STA $DD0E       ; and stop the timer
  1493.                 LDA #$FD
  1494.                 STA $DD0C       ; parameter of BPL
  1495.                 LDA #$10
  1496.                 STA $DD0B       ; BPL
  1497.                 LDA #$40
  1498.                 STA $DD0A       ; RTI/parameter of LSR
  1499.                 LDA #$46
  1500.                 STA $DD09       ; LSR
  1501.                 STA $DD08       ; load the ToD values from the latches
  1502.                 LDA $DD0B       ; freeze the ToD display
  1503.                 LDA #$09
  1504.                 STA $0318
  1505.                 LDA #$DD
  1506.                 STA $0319       ; change NMI vector to $DD09
  1507.                 LDA #$FF        ; Try changing this instruction's operand
  1508.                 STA $DD05       ; (see comment below).
  1509.                 LDA #$FF
  1510.                 STA $DD04       ; set interrupt frequency to 1/65536 cycles
  1511.                 LDA $DD0E
  1512.                 AND #$80
  1513.                 ORA #$11
  1514.                 LDX #$81
  1515.                 STX $DD0D       ; enable timer interrupt
  1516.                 STA $DD0E       ; start timer
  1517.  
  1518.                 LDA #$00        ; To see that the interrupts really occur,
  1519.                 STA $D011       ; use something like this and see how
  1520.         LOOP    DEC $D020       ; changing the byte loaded to $DD05 from
  1521.                 BNE LOOP        ; #$FF to #$0F changes the image.
  1522.  
  1523.         When an NMI occurs, the processor jumps to Kernal code, which jumps to
  1524.         ($0318), which points to the following routine:
  1525.  
  1526.         DD09    LSR $40         ; clear N flag
  1527.                 BPL $DD0A       ; Note: $DD0A contains RTI.
  1528.  
  1529.         Operational diagram of BPL $DD0A:
  1530.  
  1531.           #  data  address  R/W  description
  1532.          --- ----  -------  ---  ---------------------------------
  1533.           1   10    $DD0B    R   fetch opcode
  1534.           2   11    $DD0C    R   fetch argument
  1535.           3   xx    $DD0D    R   fetch opcode, add argument to PCL
  1536.           4   40    $DD0A    R   fetch opcode, (fix PCH)
  1537.  
  1538.  
  1539.   With RTI:
  1540.  
  1541.         ; the fastest possible interrupt handler in the 6500 family
  1542.                 ; preparations
  1543.                 SEI
  1544.                 LDA $01         ; disable ROM and enable I/O
  1545.                 AND #$FD
  1546.                 ORA #$05
  1547.                 STA $01
  1548.                 LDA #$7F
  1549.                 STA $DD0D       ; disable CIA 2's all interrupt sources
  1550.                 LDA $DD0E
  1551.                 AND #$BE        ; ensure that $DD0C remains constant
  1552.                 STA $DD0E       ; and stop the timer
  1553.                 LDA #$40
  1554.                 STA $DD0C       ; store RTI to $DD0C
  1555.                 LDA #$0C
  1556.                 STA $FFFA
  1557.                 LDA #$DD
  1558.                 STA $FFFB       ; change NMI vector to $DD0C
  1559.                 LDA #$FF        ; Try changing this instruction's operand
  1560.                 STA $DD05       ; (see comment below).
  1561.                 LDA #$FF
  1562.                 STA $DD04       ; set interrupt frequency to 1/65536 cycles
  1563.                 LDA $DD0E
  1564.                 AND #$80
  1565.                 ORA #$11
  1566.                 LDX #$81
  1567.                 STX $DD0D       ; enable timer interrupt
  1568.                 STA $DD0E       ; start timer
  1569.  
  1570.                 LDA #$00        ; To see that the interrupts really occur,
  1571.                 STA $D011       ; use something like this and see how
  1572.         LOOP    DEC $D020       ; changing the byte loaded to $DD05 from
  1573.                 BNE LOOP        ; #$FF to #$0F changes the image.
  1574.  
  1575.         When an NMI occurs, the processor jumps to Kernal code, which
  1576.         jumps to ($0318), which points to the following routine:
  1577.  
  1578.         DD0C    RTI
  1579.  
  1580.         How on earth can this clear the interrupts? Remember, the
  1581.         processor always fetches two successive bytes for each
  1582.         instruction.
  1583.  
  1584.         A little more practical version of this is redirecting the NMI
  1585.         (or IRQ) to your own routine, whose last instruction is JMP
  1586.         $DD0C or JMP $DC0C.  If you want to confuse more, change the 0
  1587.         in the address to a hexadecimal digit different from the one
  1588.         you used when writing the RTI.
  1589.  
  1590.         Or you can combine the latter two methods:
  1591.  
  1592.         DD09    LSR $xx  ; xx is any appropriate BCD value 00-59.
  1593.                 BPL $DCFC
  1594.         DCFC    RTI
  1595.  
  1596.         This example acknowledges interrupts to both CIAs.
  1597.  
  1598.  
  1599.   If you want to confuse the examiners of your code, you can use any
  1600. of these techniques. Although these examples use no undefined opcodes,
  1601. they do not necessarily run correctly on CMOS processors. However, the
  1602. RTI example should run on 65C02 and 65C816, and the latter branch
  1603. instruction example might work as well.
  1604.  
  1605.   The RMW instruction method has been used in some demos, others were
  1606. developed by Marko M"akel"a. His favourite is the automagical RTI
  1607. method, although it does not have any practical applications, except
  1608. for some time dependent data decryption routines for very complicated
  1609. copy protections.
  1610.  
  1611.  
  1612.  
  1613.                 Memory Management
  1614.  
  1615.  
  1616. The processor's point of view
  1617.  
  1618.   The Commodore 64 has access to more memory than its processor can
  1619. directly handle. This is possible by banking the memory. There are
  1620. five user configurable inputs that affect the banking. Three of them
  1621. can be controlled by program, and the rest two serve as control lines
  1622. on the memory expansion port.
  1623.  
  1624.   The 6510 MPU has an integrated I/O port with six I/O lines. This
  1625. port is accessed through the memory locations 0 and 1. The location 0
  1626. is the Data Direction Register for the Peripheral data Register, which
  1627. is mapped to the other location. When a bit in the DDR is set, the
  1628. corresponding PR bit controls the state of a corresponding Peripheral
  1629. line as an output. When it is clear, the state of the Peripheral line
  1630. is reflected by the Peripheral register. The Peripheral lines are
  1631. numbered from 0 to 5, and they are mapped to the DDR and PR bits 0 - 5,
  1632. respectively. The 8502 processor, which is used in the Commodore 128,
  1633. has seven Peripheral lines in its I/O port. The pin P6 is connected to
  1634. the ASC/CC key (Caps lock in English versions).
  1635.  
  1636.   The I/O lines have the following functions:
  1637.  
  1638.      Direction  Line  Function
  1639.      ---------  ----  --------
  1640.         out      P5   Cassette motor control. (0 = motor spins)
  1641.         in       P4   Cassette sense. (0 = PLAY button depressed)
  1642.         out      P3   Cassette write data.
  1643.         out      P2   CHAREN
  1644.         out      P1   HIRAM
  1645.         out      P0   LORAM
  1646.  
  1647.   The default value of the DDR register is $2F, so all lines except
  1648. Cassette sense are outputs. The default PR value is $37 (Datassette
  1649. motor stopped, and all three memory management lines high).
  1650. If you turn any memory management line to input, the external pull-up
  1651. resistors make it to look like it is outputting logical "1". This
  1652. is actually why the computer always switches the ROMs in upon startup:
  1653. Pulling the -RESET line low resets all Peripheral lines to inputs,
  1654. thus setting all three processor-driven memory management lines to
  1655. logical "1" level.
  1656.  
  1657.   The two remaining memory management lines are -EXROM and -GAME on
  1658. the cartridge port. Each line has a pull-up resistor, so the lines
  1659. are "1" by default.
  1660.  
  1661.   Even though the memory banking has been implemented with a 82S100
  1662. Programmable _Logic_ Array, there is only one control line that seems
  1663. to behave logically at first sight, the -CHAREN line. It is mostly
  1664. used to choose between I/O address space and the character generator
  1665. ROM. The following memory map introduces the oddities of -CHAREN and
  1666. the other memory management lines. It is based on the memory maps in
  1667. the Commodore 64 Programmer's Reference Guide, pp. 263 - 267, and some
  1668. errors and inaccuracies have been corrected.
  1669.  
  1670.   The leftmost column of the table contains addresses in hexadecimal
  1671. notation. The columns aside it introduce all possible memory
  1672. configurations. The default mode is on the left, and the absolutely
  1673. most rarely used Ultimax game console configuration is on the right.
  1674. (Has anybody ever seen any Ultimax games?) Each memory configuration
  1675. column has one or more four-digit binary numbers as a title. The bits,
  1676. from left to right, represent the state of the -LORAM, -HIRAM, -GAME
  1677. and -EXROM lines, respectively. The bits whose state does not matter
  1678. are marked with "x". For instance, when the Ultimax video game
  1679. configuration is active (the -GAME line is shorted to ground), the
  1680. -LORAM and -HIRAM lines have no effect.
  1681.  
  1682.  
  1683.       default                      001x                       Ultimax
  1684.        1111   101x   1000   011x   00x0   1110   0100   1100   xx01
  1685. 10000
  1686. ----------------------------------------------------------------------
  1687.  F000
  1688.        Kernal RAM    RAM    Kernal RAM    Kernal Kernal Kernal ROMH(*
  1689.  E000
  1690. ----------------------------------------------------------------------
  1691.  D000  IO/C   IO/C   IO/RAM IO/C   RAM    IO/C   IO/C   IO/C   I/O
  1692. ----------------------------------------------------------------------
  1693.  C000  RAM    RAM    RAM    RAM    RAM    RAM    RAM    RAM     -
  1694. ----------------------------------------------------------------------
  1695.  B000                                                     
  1696.        BASIC  RAM    RAM    RAM    RAM    BASIC  ROMH   ROMH    -
  1697.  A000                                                     
  1698. ----------------------------------------------------------------------
  1699.  9000                                                     
  1700.        RAM    RAM    RAM    RAM    RAM    ROML   RAM    ROML   ROML(*
  1701.  8000                                                     
  1702. ----------------------------------------------------------------------
  1703.  7000                                                     
  1704.                                                      
  1705.  6000                                                     
  1706.        RAM    RAM    RAM    RAM    RAM    RAM    RAM    RAM     -
  1707.  5000                                                     
  1708.                                                      
  1709.  4000                                                     
  1710. ----------------------------------------------------------------------
  1711.  3000                                                    
  1712.                                                      
  1713.  2000  RAM    RAM    RAM    RAM    RAM    RAM    RAM    RAM     -
  1714.                                                      
  1715.  1000                                                     
  1716. ----------------------------------------------------------------------
  1717.  0000  RAM    RAM    RAM    RAM    RAM    RAM    RAM    RAM    RAM
  1718. ----------------------------------------------------------------------
  1719.  
  1720.     *) Internal memory does not respond to write accesses to these
  1721.        areas.
  1722.  
  1723.  
  1724.     Legend: Kernal      E000-FFFF       Kernal ROM.
  1725.  
  1726.             IO/C        D000-DFFF       I/O address space or Character
  1727.                                         generator ROM, selected by
  1728.                                         -CHAREN. If the CHAREN bit is
  1729.                                         clear, the character generator
  1730.                                         ROM will be selected. If it is
  1731.                                         set, the I/O chips are
  1732.                                         accessible.
  1733.  
  1734.             IO/RAM      D000-DFFF       I/O address space or RAM,
  1735.                                         selected by -CHAREN. If the
  1736.                                         CHAREN bit is clear, the
  1737.                                         character generator ROM will
  1738.                                         be selected. If it is set, the
  1739.                                         internal RAM is accessible.
  1740.  
  1741.             I/O         D000-DFFF       I/O address space.
  1742.                                         The -CHAREN line has no effect.
  1743.  
  1744.             BASIC       A000-BFFF       BASIC ROM.
  1745.  
  1746.             ROMH        A000-BFFF or    External ROM with the -ROMH line
  1747.                         E000-FFFF       connected to its -CS line.
  1748.  
  1749.             ROML        8000-9FFF       External ROM with the -ROML line
  1750.                                         connected to its -CS line.
  1751.  
  1752.             RAM         various ranges  Commodore 64's internal RAM.
  1753.  
  1754.             -           1000-7FFF and   Open address space. 
  1755.                         A000-CFFF       The Commodore 64's memory chips
  1756.                                         do not detect any memory accesses
  1757.                                         to this area except the VIC-II's
  1758.                                         DMA and memory refreshes.
  1759.  
  1760.     NOTE:   Whenever the processor tries to write to any ROM area
  1761.             (Kernal, BASIC, CHAROM, ROML, ROMH), the data will get
  1762.             "through the ROM" to the C64's internal RAM.
  1763.  
  1764.             For this reason, you can easily copy data from ROM to RAM,
  1765.             without any bank switching. But implementing external
  1766.             memory expansions without DMA is very hard, as you have to
  1767.             use a 256 byte window on the I/O1 or I/O2 area, like
  1768.             GEORAM, or the Ultimax memory configuration, if you do not
  1769.             want the data to be written both to internal and external
  1770.             RAM.
  1771.  
  1772.             However, this is not true for the Ultimax video game
  1773.             configuration. In that mode, the internal RAM ignores all
  1774.             memory accesses outside the area $0000-$0FFF, unless they
  1775.             are performed by the VIC, and you can write to external
  1776.             memory at $1000-$CFFF and $E000-$FFFF, if any, without
  1777.             changing the contents of the internal RAM.
  1778.  
  1779.  
  1780. A note concerning the I/O area
  1781.  
  1782.   The I/O area of the Commodore 64 is divided as follows:
  1783.  
  1784.      Address range  Owner
  1785.      -------------  -----
  1786.        D000-D3FF    MOS 6567/6569 VIC-II Video Interface Controller
  1787.        D400-D7FF    MOS 6581 SID Sound Interface Device
  1788.        D800-DBFF    Color RAM (only lower nybbles are connected)
  1789.        DC00-DCFF    MOS 6526 CIA Complex Interface Adapter #1
  1790.        DD00-DDFF    MOS 6526 CIA Complex Interface Adapter #2
  1791.        DE00-DEFF    User expansion #1 (-I/O1 on Expansion Port)
  1792.        DF00-DFFF    User expansion #2 (-I/O2 on Expansion Port)
  1793.  
  1794.   As you can see, the address ranges for the chips are much larger
  1795. than required. Because of this, you can access the chips through
  1796. multiple memory areas. The VIC-II appears in its window every $40
  1797. addresses. For instance, the addresses $D040 and $D080 are both mapped
  1798. to the Sprite 0 X co-ordinate register. The SID has one register
  1799. selection line less, thus it appears at every $20 bytes. The CIA chips
  1800. have only 16 registers, so there are 16 copies of each in their memory
  1801. area.
  1802.  
  1803.   However, you should not use other addresses than those specified by
  1804. Commodore. For instance, the Commodore 128 mapped its additional I/O
  1805. chips to this same memory area, and the SID responds only to the
  1806. addresses D400-D4FF, also when in C64 mode. And the Commodore 65, or
  1807. the C64DX, which unfortunately did not make its way to the market,
  1808. could narrow the memory window reserved for its CSG 4567 VIC-III.
  1809.  
  1810.  
  1811. The video chip
  1812.  
  1813.   The MOS 6567/6569 VIC-II Video Interface Controller has access to
  1814. only 16 kilobytes at a time. To enable the VIC-II to access the whole
  1815. 64 kB memory space, the main memory is divided to four banks of 16 kB
  1816. each. The lines PA0 and PA1 of the second CIA are the inverse of the
  1817. virtual VIC-II address lines VA14 and VA15, respectively. To select a
  1818. VIC-II bank other than the default, you must program the CIA lines to
  1819. output the desired bit pair. For instance, the following code selects
  1820. the memory area $4000-$7FFF (bank 1) for the video controller:
  1821.  
  1822.     LDA $DD02 ; Data Direction Register A
  1823.     ORA #$03  ; Set pins PA0 and PA1 to outputs
  1824.     STA $DD02
  1825.     LDA $DD00
  1826.     AND #$FC  ; Mask the lowmost bit pair off
  1827.     ORA #$02  ; Select VIC-II bank 1 (the inverse of binary 01 is 10)
  1828.     STA $DD00
  1829.  
  1830.   Why should you set the pins to outputs? Hardware RESET resets all
  1831. I/O lines to inputs, and thanks to the CIA's internal pull-up
  1832. resistors, the inputs actually output logical high voltage level. So,
  1833. upon -RESET, the video bank 0 is selected automatically, and older
  1834. Kernals could leave it uninitialized.
  1835.  
  1836.   Note that the VIC-II always fetches its information from the
  1837. internal RAM, totally ignoring the memory configuration lines. There
  1838. is only one exception to this rule: The character generator ROM.
  1839. Unless the Ultimax mode is selected, VIC-II "sees" character generator
  1840. ROM in the memory areas 1000-1FFF and 9000-9FFF. If the Ultimax
  1841. configuration is active, the VIC-II fetches all data from the internal
  1842. RAM.
  1843.  
  1844.  
  1845. Accessing the memory places 0 and 1
  1846.  
  1847.   Although the addresses 0 and 1 of the processor are hard-wired to
  1848. its on-chip I/O port registers, you can access the memory places 0 and
  1849. 1. The video chip always reads from RAM (or character generator ROM),
  1850. so you can use it to read also from 0 and 1. Enable the bit-map screen
  1851. and set the start address of the graphics screen to 0. Now you can see
  1852. these two memory locations in the upper left corner. Alternatively,
  1853. you could set the character generator start address to 0, in which
  1854. case you would see these locations in @ characters (code 0). Or, you
  1855. can activate a sprite with start address 0. Whichever method you
  1856. choose, you can read these locations with sprite collision registers.
  1857. Define a sprite consisting of only one dot, and move it to read the 8
  1858. bits of each byte with the sprite to sprite or sprite to background
  1859. collision registers.
  1860.   
  1861.   But how can you write to these locations? If you execute the command
  1862. POKE 53265,59, you will see that the memory place 1 changes its value
  1863. wildly. If you disable the interrupts (POKE53664,127), it will remain
  1864. stable. How is this possible? When the processor writes to 0 or 1, it
  1865. will put the address on the address bus and set the R/-W line to indicate
  1866. a write cycle, but it does not put the data on the data bus. Thus, it
  1867. writes "random" data. Of course this data is not truly random. Actually
  1868. it is something that the video chip left on the bus on its clock half.
  1869. So, if you want to write a certain value on 0 or 1, you have to make the
  1870. video chip to read that value just before the store cycle. This requires
  1871. very accurate timing, but it can be achieved even with a carefully
  1872. written BASIC program. Just wait the video chip to be in the top or
  1873. bottom border and the beam to be in the middle of the screen (not in the
  1874. side borders). At this area, the video chip will always read the last
  1875. byte of the video bank (by default $3FFF). Now, if you store anything to
  1876. the I/O port registers 0 or 1 while the video chip is refreshing this
  1877. screen area, the contents of the memory place $3FFF will be written to
  1878. the respective memory place (0 or 1).  Note that this trick does not work
  1879. reliably on all computers.  You need good RF protection, as the data bus
  1880. will not be driven at all when the value remains on it.
  1881.  
  1882.   On the C128 in its 2 MHz mode, you can write to the memory places
  1883. with an easier kludge.  Just make sure that the video chip is not
  1884. performing the memory refresh (as it would slow down to 1 MHz in that
  1885. case), and use some instruction that reads from a proper memory location
  1886. before writing to 0 or 1.  Indexed zero-page addressing modes are good
  1887. for it.  I tested this trick with LDX#1 followed by STA $FF,X.  As you
  1888. can read from the instruction timing section of this document, the
  1889. instruction first reads from $FF (the base address) and then writes to 0.
  1890. The timing can be done with a simple LDA$D012:CMP$D012:BEQ *-3 loop.
  1891. But in the C128 mode you can relocate the stack page to zero page, so
  1892. this trick is not really useful.
  1893.  
  1894.   You can also read the memory places 0 and 1 much faster than with
  1895. sprite collisions. Just make the video chip to read from 0 or 1, and
  1896. then read from non-connected address space ($DE00-$DFFF on a stock C64;
  1897. also $D700-$D7FF on C128's). Actually, you can produce a complete map
  1898. of the video timing on your computer by making a loop that reads from
  1899. open address space, pausing one frame and one cycle in between. And if
  1900. you are into copy protections, you could write a program on the open
  1901. address space. Just remember that there must be a byte on the bus for
  1902. each clock cycle.
  1903.  
  1904.   These tricks unfortunately do not work reliably on all units. So far
  1905. I have had the opportunity to try it on three computers, two of which
  1906. were Commodore 128 DCR's (C128's housed in metal case with a 1571 floppy
  1907. disk drive, whose controller is integrated on the mother board). One
  1908. C128DCR drove some of its data bits too heavily to high state.  No wonder,
  1909. since its housing consisted of some newspapers spread on the floor.
  1910.  
  1911.  
  1912.  
  1913.                 Autostart Code
  1914.  
  1915.   Although this document concentrates on hardware, there is one thing
  1916. that you must know about the firmware to get complete control over
  1917. your computer. As the Commodore 64 always switches the ROMs on upon
  1918. -RESET, you cannot relocate the RESET vector by writing something in
  1919. RAM. Instead, you have to use the Autostart code that will be
  1920. recognized by the KERNAL ROM. If the memory places from $8004 through
  1921. $8008 contain the PETSCII string 'CBM80' (C3 C2 CD 38 30), the RESET
  1922. routine jumps to ($8000) and the default NMI handler jumps to ($8002).
  1923.  
  1924.   Some programs that load into RAM take advantage of this and don't
  1925. let the machine to be reset. You don't have to modify the ROM to get
  1926. rid of this annoying behaviour. Simply ground the -EXROM line for the
  1927. beginning of the RESET sequence.
  1928.  
  1929.  
  1930.  
  1931.                 Notes
  1932.  
  1933.   See the MCS 6500 Microcomputer Family Programming Manual for less
  1934. information.
  1935.  
  1936.  
  1937. References:
  1938.   C64 Memory Maps       C64 Programmer's Reference Guide, pp. 262-267
  1939.                         C64 Schematic Diagram
  1940.   6510 Block Diagram    C64 Programmer's Reference Guide,  p. 404
  1941.   Instruction Set       C64 Programmer's Reference Guide, pp. 254-255, 416-417
  1942.             C64/128 Real Programmer's Revenge Guide
  1943.                         C=Lehti magazine 4/87
  1944.