<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" ><generator uri="https://jekyllrb.com/" version="3.10.0">Jekyll</generator><link href="https://intoinside.github.io/feed.xml" rel="self" type="application/atom+xml" /><link href="https://intoinside.github.io/" rel="alternate" type="text/html" /><updated>2026-11-23T11:25:48+00:00</updated><id>https://intoinside.github.io/feed.xml</id><title type="html">Raffaele Intorcia</title><author><name>Raffaele Intorcia</name><email>raffaele.intorcia@gmail.com</email></author><entry><title type="html">Autoboot explained pt2</title><link href="https://intoinside.github.io/2025/08/11/autoboot-explained-pt2/" rel="alternate" type="text/html" title="Autoboot explained pt2" /><published>2025-08-11T00:00:00+00:00</published><updated>2025-08-11T00:00:00+00:00</updated><id>https://intoinside.github.io/2025/08/11/autoboot-explained-pt2</id><content type="html" xml:base="https://intoinside.github.io/2025/08/11/autoboot-explained-pt2/"><![CDATA[<p>Practical example to understand how autoboot works in two different modes:</p>

<ul>
  <li>classic autoboot for C128</li>
  <li>autoboot that works for C128’s C64 mode</li>
</ul>

<p>As mentioned in the <a href="/2024/04/07/autoboot-explained">previous article</a>, autoboot is a feature introduced in the Commodore 128. Therefore, it is not possible to use it on the C64…</p>

<p>It’s actually possible, but it can only be used in the C64 mode offered by the C128. The usability of this feature is therefore very limited, but it’s interesting to see it from a technical standpoint. Now we’ll see how to implement autoboot in both pure C128 mode and C64 mode.</p>

<h1 id="autoboot-c128">Autoboot C128</h1>

<p>As mentioned, the disk that will allow autoboot must be modified so that the C128, after switching on (or when using the BOOT command), is able to start the desired program.</p>

<p><span class="badge badge-info"><span class="badge-unicode">ⓘ</span> Note: Code here was obtained by modifying examples available online, the resources are listed at the bottom of the page</span></p>

<p>The simplest version involves creating an autoboot disk that launches a program.</p>

<p>The autoboot should be generated with this structure:</p>

<pre>
0000 43 42 4D 00 00 00 00 41   CBM....A
0008 55 54 4F 42 4F 4F 54 20   UTOBOOT
0010 46 4F 52 20 43 31 32 38   FOR C128
0018 00 00 A2 20 A0 0B 4C A5   ........
0020 AF 52 55 4E 22 41 55 54   .RUN"AUT
0028 4F 42 4F 4F 54 2D 43 31   OBOOT-C1
0030 32 38 22 00 00 00 00 00   28".....
</pre>

<p>To generate the boot sector we need to start from a blank disk (with VICE you can create it from the File menu) and then we can use the BASIC/ML program below:</p>

<pre><code class="language-Basic">10 REM CREATE BOOT SECTOR
20 DCLEAR: OPEN 15, 8, 15: OPEN 2, 8, 2, "#": PRINT# 15, "B-P:2, 0"
30 READ D$: D = DEC(D$): IF D&gt;255 THEN 50
40 PRINT# 2, CHR$(D); : GOTO 30
50 PRINT# 15, "U2;2, 0, 1, 0"
60 PRINT DS$ : CLOSE 2 : CLOSE 15
70 DATA 43, 42, 4D, 00, 00, 00, 00
80 DATA 41, 55, 54, 4F, 42, 4F, 4F, 54, 20, 46, 4F, 52, 20, 43, 31, 32, 38
90 DATA 00, 00, A2, 20, A0, 0B, 4C, A5, AF, 52, 55, 4E
100 DATA 22, 41, 55, 54, 4F, 42, 4F, 4F, 54, 2D, 43, 31, 32, 38, 22, 00
1000 DATA 100
</code></pre>

<h2 id="description">Description</h2>

<pre><code class="language-Basic">20 DCLEAR: OPEN 15, 8, 15: OPEN 2, 8, 2, "#": PRINT# 15, "B-P:2, 0"
</code></pre>

<ul>
  <li>DCLEAR: clears the drive’s directory buffer (useful for starting from a “clean” state)</li>
  <li>OPEN 15, 8, 15: opens the command channel (15) to drive 8.</li>
  <li>OPEN 2, 8, 2, “#”: opens the data channel (2) to drive 8, raw mode (“#” means physical sector).</li>
  <li>PRINT# 15, “BP:2, 0”: command to the drive to position the head to the boot sector.
    <ul>
      <li>“BP” means “Block Position”.</li>
      <li>Parameters 2, 0 = channel 2, sector 0 of the boot track (which is usually track 1, sector 0 in the C128).</li>
    </ul>
  </li>
</ul>

<pre><code class="language-Basic">30 READ D$: D = DEC(D$): IF D&gt;255 THEN 50
</code></pre>

<ul>
  <li>READ D$: reads a value from DATA, as a string (can contain hexadecimal or numeric values).</li>
  <li>D = DEC(D$): converts from string (hexadecimal or decimal) to decimal number.</li>
  <li>IF D&gt;255 THEN 50: if the value is greater than 255 then end of actual data, skip to line 50.</li>
</ul>

<pre><code class="language-Basic">40 PRINT# 2, CHR$(D); : GOTO 30
</code></pre>

<p>Send the converted byte (CHR$(D)) to data channel 2 (thus writing it directly to the sector). The semicolon ; avoids inserting the CR/LF terminator. Then return to line 30 to read the next byte.</p>

<pre><code class="language-Basic">50 PRINT# 15, "U2;2, 0, 1, 0"
</code></pre>

<ul>
  <li>“U2” is the drive command to write a block (Block Write).
    <ul>
      <li>2 = open data channel</li>
      <li>0, 1, 0 = track 1, sector 0 (standard boot sector for the C128)</li>
    </ul>
  </li>
</ul>

<p>In practice, here the drive physically writes the sector with the data just sent.</p>

<pre><code class="language-Basic">60 PRINT DS$ : CLOSE 2 : CLOSE 15
</code></pre>

<ul>
  <li>PRINT DS$: shows the drive status (DS$ contains the status message)</li>
  <li>CLOSE 2 / CLOSE 15: closes open channels</li>
</ul>

<pre><code class="language-Basic">70 DATA 43, 42, 4D, 00, 00, 00, 00
</code></pre>

<p>43 42 4D in ASCII is “CBM”, the boot block identifier. The four bytes after 00 are:</p>

<ul>
  <li>the address (16 bit) in which to store other data read from disk</li>
  <li>the bank in which to store the data</li>
  <li>the number of sectors to read</li>
</ul>

<p>Since the number of sectors to read is 0, the previous three bytes are not significant.</p>

<pre><code class="language-Basic">80 DATA 41, 55, 54, 4F, 42, 4F, 4F, 54, 20, 46, 4F, 52, 20, 43, 31, 32, 38
</code></pre>

<p>ASCII: “AUTOBOOT FOR C128”</p>

<pre><code class="language-Basic">90 DATA 00, 00, A2, 20, A0, 0B, 4C, A5, AF, 52, 55, 4E
</code></pre>

<p>Contains two zero bytes used as terminator of the boot message (defined on line 80) and the program name (not used), then machine code:</p>

<pre>
A2 20     LDX #$20
A0 0B     LDY #$0B
4C A5 AF  JMP $AFA5
</pre>

<p>The values inserted in .X and .Y represent the address immediately preceding the string to be written (for this example the string is located at $0B21, in .Y there is the hi-byte $0B and in .X there is the lo-byte -1 i.e. $20).</p>

<p>52 55 4E in ASCII is “RUN” (BASIC command string). The name of the program to be loaded is defined on line 100:</p>

<pre><code class="language-Basic">100 DATA 22, 41, 55, 54, 4F, 42, 4F, 4F, 54, 2D, 43, 31, 32, 38, 22, 00
</code></pre>

<p>ASCII: “AUTOBOOT-C128” tra virgolette, poi terminatore 00.</p>

<p>By running this program, the disk’s boot sector is modified to run the “AUTOBOOT-C128” program. Now we need to create this program.</p>

<p>Since this is an example program, just type the commands:</p>

<pre><code class="language-Basic">NEW
10 PRINT "AUTOBOOT LOADED SUCCESSFULLY!!"
DSAVE "AUTOBOOT-C128"
</code></pre>

<p>For the C128 autoboot part, we’re done; just call the BOOT command or reset the machine to verify its operation. In this case, the output on an 80-column monitor should look like this:</p>

<p><img src="/resources/autoboot-pt2.png" alt="Booting message" /></p>

<h1 id="autoboot-c128-in-modalità-c64">Autoboot C128 in modalità C64</h1>

<p>Autoboot for C64 mode takes into account all the activities performed in the previous step and requires modification of the program launched after booting. To better separate the concepts, the following is the new listing that creates the boot sector. The only differences are the string following the text “BOOTING” and the name of the launched file, which will be called “AUTOBOOT-C64”.</p>

<p>As with the previous example, it is convenient to create a blank disk. This BASIC/ML code creates boot sector:</p>

<pre><code class="language-Basic">10 REM CREATE BOOT SECTOR
20 DCLEAR: OPEN 15, 8, 15: OPEN 2, 8, 2, "#": PRINT# 15, "B-P:2, 0"
30 READ D$: D = DEC(D$): IF D&gt;255 THEN 50
40 PRINT# 2, CHR$(D); : GOTO 30
50 PRINT# 15, "U2;2, 0, 1, 0"
60 PRINT DS$ : CLOSE 2 : CLOSE 15
70 DATA 43, 42, 4D, 00, 00, 00, 00
80 DATA 41, 55, 54, 4F, 42, 4F, 4F, 54, 20, 46, 4F, 52, 20, 43, 36, 34
90 DATA 00, 00, A2, 1F, A0, 0B, 4C, A5, AF, 52, 55, 4E
100 DATA 22, 41, 55, 54, 4F, 42, 4F, 4F, 54, 2D, 43, 36, 34, 22, 00
1000 DATA 100
</code></pre>

<p>There’s no difference with previous boot sector creator, except for the two things mentioned above.</p>

<p>Next, you need to generate the file (AUTOBOOT-C64) that, when running in 128 mode, prepares the transition to C64 mode and starts the bootloader (“BOOT64”). The bootloader in C64 mode will finally load the desired program. For this example, the program launched in C64 mode will be called “HELLO-WORLD”.</p>

<pre><code class="language-Basic">10 A = 32768: PRINT "(SWITCH 40 COLUMN DISPLAY) "
20 READ D$: IF D$ = "-1" THEN GO64
30 POKE A, DEC (D$):A = A + 1: GO TO 20
40 DATA 09, 80, 5E, FE, C3, C2, CD, 38, 30
50 DATA 8E, 16, D0, 20, A3, FD, 20, 50, FD
60 DATA 20, 15, FD, 20, 5B, FF, 58
70 DATA 20, 53, E4, 20, BF, E3, 20, 22, E4
80 DATA A2, FB, 9A
90 DATA A2, 00, BD, 41, 80, F0, 06
100 DATA 20, D2, FF, E8, D0, F5
110 DATA A9, 0D, 8D, 77, 02, 8D, 78, 02
120 DATA A9, 02, 85, C6
130 DATA 4C, 74, A4
140 DATA 0D, 4C, 4F, 41, 44, 22, 42, 4F, 4F, 54, 36, 34, 22, 2C, 38
150 DATA 0D, 0D, 0D, 0D, 0D, 52, 55, 4E, 91, 91, 91, 91, 91, 91, 91, 0, -1
</code></pre>

<p>The C128 autoboot program adds some ML code to address $8000 (32768) to simulate a cartridge. Once the code has been added, the GO64 BASIC command is launched.</p>

<p>On the next boot, C64 mode performs a classic reset, checking for any cartridges. At the specified address, it will find the code added by the AUTOBOOT-C64 program. Note that the GO64 command does not erase the RAM, so its contents are preserved.</p>

<p>The code added to simulate a cartridge performs the classic C64 boot activities (IOINIT, RAMTAS, RESTOR, CINT…) to which it adds the writing of the load command on the screen (LOAD”BOOT64”,8) and the simulation of pressing the return key for loading and execution.</p>

<p>At the end of the boot sequence, the BOOT64 program is loaded and started, which has this listing:</p>

<pre><code class="language-Basic">10 REM C64 ML PROG LOADER EXAMPLE
20 IF A = 0 THEN A = 1: LOAD "HELLO-WORLD", 8, 1
30 SA = 52224: REM START ADDRESS
40 SYS SA
</code></pre>

<p>Finally here is an example listing for “HELLO-WORLD”:</p>

<pre><code class="language-Basic">10 PRINT "HELLO WORLD FROM C64!!"
</code></pre>

<p>When the C128 restarts and the various steps are completed, the 80-column and 40-column screens should look like this:</p>

<p><img src="/resources/autoboot-pt2-c64-80col.png" alt="Booting message 80 col" />
<img src="/resources/autoboot-pt2-c64-40col.png" alt="Booting message 40 col" /></p>

<h2 id="download">Download</h2>

<p>Below are links to the images of the two discs:</p>

<ul>
  <li><a href="/resources/autoboot-c128.d71">Autoboot C128</a></li>
  <li><a href="/resources/autoboot-c64.d64">Autoboot C64</a></li>
</ul>

<h1 id="links">Links</h1>

<ul>
  <li><a href="https://www.atarimagazines.com/compute/issue77/Boot_64_For_128.php">Atarimagazines.com - Boot 64 for 128</a></li>
  <li><a href="https://istennyila.hu/dox/cbmcode.pdf">Istennyila.hu - Writing Platform Independent Code on CBM Machines</a></li>
  <li><a href="https://www.infinite-loop.at/Power64/Documentation/Power64-Leggimi/AB-Comandi_Floppy.html">Infinite-loop.at - Floppy command documentation</a></li>
  <li><a href="https://github.com/rhalkyard/128boot64">Github - rhalkyard/128boot64</a></li>
</ul>]]></content><author><name>Raffaele Intorcia</name><email>raffaele.intorcia@gmail.com</email></author><category term="commodore-128" /><category term="autoboot" /><category term="boot" /><category term="autoboot-c64" /><category term="commodore-64" /><summary type="html"><![CDATA[Practical example to understand how autoboot works in two different modes:]]></summary></entry><entry><title type="html">Load data or code from disk</title><link href="https://intoinside.github.io/2024/10/19/load-data-from-disk/" rel="alternate" type="text/html" title="Load data or code from disk" /><published>2024-10-19T00:00:00+00:00</published><updated>2024-10-19T00:00:00+00:00</updated><id>https://intoinside.github.io/2024/10/19/load-data-from-disk</id><content type="html" xml:base="https://intoinside.github.io/2024/10/19/load-data-from-disk/"><![CDATA[<p>Reading code from disk can be useful when you want to develop a project of a certain size.
Often you find yourself not having all the memory space necessary for the project so it is necessary to break it up.
At the right time, a routine can be called to read the code from disk and load it into memory.
Subsequently the new code will be called and the program execution can continue.
It is necessary to design the program structure and the memory areas involved well, preserving any portions of code or data that must always be present during execution.</p>

<p>It all revolves around the Kernal <code>JLOAD</code> call that does the actual loading. Before calling it, however, you need to make some preliminary calls and set several parameters.</p>

<p>The first call to make is to the <code>JSETNAM</code> (<a href="https://c128lib.github.io/Reference/E000#FFBD">$FFBD</a>) routine that sets the name of the file on disk to load.</p>

<p>The routine expects parameters in the three registers .A, .X, .Y.</p>

<p>In .A you must enter the length of the file name to load.
In .X and .Y you must enter the memory address that contains the name of the file to load (in .X goes the low-byte while in .Y goes the hi-byte).</p>

<pre><code class="language-Assembly">    lda #$ff
    ldx #$be
    ldy #$ef
    jsr $FFBD
</code></pre>

<p>Next, you need to call the <code>JSETBNK</code> (<a href="https://c128lib.github.io/Reference/E000#FF68">$FF68</a>) routine that sets the memory bank used to provide the parameters and to receive the read code.
In .A, you need to insert the number of the bank for the parameters, while in .X, you need to insert the number of the bank where the data will be written.</p>

<pre><code class="language-Assembly">    lda #00
    tax
    jsr $FF68
</code></pre>

<p>The last preparatory routine to call is <code>JSETLFS</code> (<a href="https://c128lib.github.io/Reference/E000#FFBA">$FFBA</a>) which is used to specify the logical file number, the device number and the secondary address for I/O operations.
In .A you enter the logical file number, in .X you enter the device number and in .Y you enter the secondary address for I/O operations.</p>

<pre><code class="language-Assembly">    lda #00
    ldx #08
    ldy #01
    jsr $FFBA
</code></pre>

<p>Finally, it is possible to call the <code>JLOAD</code> (<a href="https://c128lib.github.io/Reference/E000#FFD5">$FFD5</a>) routine that performs the disk reading.
The routine can perform a read or a check and this option must be specified via the .A register
In .A the value 0 must be inserted, any other value would activate the check function.</p>

<pre><code class="language-Assembly">    lda #00
    jsr $FFD5
</code></pre>

<p>The routine will now read the specified file and write it to memory. But where will it be written? First, the first two bytes of the file will be read, which contain the absolute address to load. After that, the reading will continue with the rest of the file, and all the contents will be positioned starting from the address read before.</p>

<p>Note that <code>JLOAD</code> returns the result of the reading in the Carry bit: if it is set, it means that an error occurred during the reading or that <code>RUN/STOP</code> was pressed to stop the operation. In this case, the .A register contains the error code.</p>

<p>Below is the entire routine and a macro I use to set parameters more conveniently and to make the code reusable.
The self-modifying code technique is widely used, which explains the abundance of labels within the routine and the use of the $be and $ef values ​​(for debugging enthusiasts who use $beef to understand whether the self-modifying code has been activated or not).</p>

<pre><code class="language-Assembly">.macro LoadFile(Level1FileNameLength, Level1FileName) {
    lda #Level1FileNameLength
    sta LoadFile.FilenameSize + 1
    lda #&lt;Level1FileName
    sta LoadFile.FilenameLowByte + 1
    lda #&gt;Level1FileName
    sta LoadFile.FilenameHighByte + 1
    jsr LoadFile
}

LoadFile: {
  FilenameSize:
    lda #$ff
  FilenameLowByte:
    ldx #$be
  FilenameHighByte:
    ldy #$ef
    jsr $FFBD
    lda #00
    tax
    jsr $FF68
    lda #00
    ldx #08
    ldy #01
    jsr $FFBA
    lda #00
    jsr $FFD5
}
</code></pre>

<p>As a final note, remember to transfer control to the loaded code. A simple <code>JMP</code> will do.</p>

<pre><code class="language-Assembly">    LoadFile(Level1FileNameLength, Level1FileName)
    JMP $4000   // Supposing that $4000 is the absolute address of the code loaded
</code></pre>

<p>Do you remember when you loaded a program and the screen started showing colored flashes that ended when the loading was complete?
They are called loading bars and they were used to let the user know that the loading was proceeding without problems.
The <code>JLOAD</code> routine does not provide the possibility to verify what is happening and returns its results in case of error or when loading is finished. We can still understand what it is doing using a little trick.</p>

<p><code>JLOAD</code> can be interrupted by pressing the RUN/STOP button, so in the Kernal it is periodically checked if this button is pressed. The check is done with a <code>JSR $FFE1</code>.
At the address <code>$FFE1</code> there is the <code>JSTOP</code> routine which is a simple <code>JMP ($0328)</code>. It means that the address (16 bits) present at the location <code>$0328</code> (Indirect vector for the <code>STOP</code> routine) is loaded and a <code>JMP</code> is done on it. The standard routine checks if the <code>STOP</code> button is pressed. It can be modified to add a loading bar before checking the state of the button.</p>

<p>By adding this code before calling <code>JLOAD</code>, JSTOP call can be redirected to a custom routine called <code>LoadingBars</code>:</p>

<pre><code class="language-Assembly">    lda #&lt;LoadingBars
    sta $0328
    lda #&gt;LoadingBars
    sta $0329
</code></pre>

<p>LoadingBars routine it’s quite simple, it changes the border color to create a flashing bar effect, then a jmp to original routine is done.</p>

<pre><code class="language-Assembly">LoadingBars: {
    inc $d020
    nop

    jmp $f66e
}
</code></pre>

<h2 id="coupling">Coupling</h2>
<p>A coupling problem is highlighted that requires knowing in advance the absolute address on which the code will be read and inserted. This address is read by the JLOAD but is not exposed so it is necessary to follow a different approach.</p>

<p>Instead of the JLOAD, it is necessary to read the first two bytes to build the absolute address. Then, one byte at a time must be read until the end of the file, writing the read code in the address read before each time.
It is a longer procedure to write and subject to errors but it allows us to obtain the absolute address and make it available externally.</p>

<h1 id="references">References</h1>

<ul>
  <li>JSETBNK <a href="https://c128lib.github.io/Reference/E000#FF68">$FF68</a></li>
  <li>JSETLFS <a href="https://c128lib.github.io/Reference/E000#FFBA">$FFBA</a></li>
  <li>JSETNAM <a href="https://c128lib.github.io/Reference/E000#FFBD">$FFBD</a></li>
  <li>JLOAD <a href="https://c128lib.github.io/Reference/E000#FFD5">$FFD5</a></li>
</ul>]]></content><author><name>Raffaele Intorcia</name><email>raffaele.intorcia@gmail.com</email></author><category term="8-bit" /><category term="computer" /><category term="load" /><category term="kernal" /><category term="commodore" /><category term="commodore-128" /><category term="commodore-64" /><summary type="html"><![CDATA[Reading code from disk can be useful when you want to develop a project of a certain size. Often you find yourself not having all the memory space necessary for the project so it is necessary to break it up. At the right time, a routine can be called to read the code from disk and load it into memory. Subsequently the new code will be called and the program execution can continue. It is necessary to design the program structure and the memory areas involved well, preserving any portions of code or data that must always be present during execution.]]></summary></entry><entry><title type="html">Chip generations</title><link href="https://intoinside.github.io/2024/06/12/chip-generations/" rel="alternate" type="text/html" title="Chip generations" /><published>2024-06-12T00:00:00+00:00</published><updated>2024-06-12T00:00:00+00:00</updated><id>https://intoinside.github.io/2024/06/12/chip-generations</id><content type="html" xml:base="https://intoinside.github.io/2024/06/12/chip-generations/"><![CDATA[<p>This is a non-complete exposition of the CPUs that were protagonists in the 70-80s. We will see the connections and evolutions of the different architectures and the main computers that have adopted them.</p>

<h1 id="motorolamos-path">Motorola/Mos path</h1>
<p><img src="/resources/8bit-comparison-motorola.png" align="left" alt="Motorola path" style="padding: 10px" /></p>

<h2 id="motorola-6800-1974">Motorola 6800 (1974)</h2>
<p>It is the main competitor of the 8080, with equal performance, but with a completely different design philosophy.</p>

<h2 id="motorola-6809-1977">Motorola 6809 (1977)</h2>
<p>The 6809 is an evolution of the 6800, with a more advanced architecture. The 6809 is a CISC processor, with two 8-bit accumulators and a 16-bit address bus. The 6809 is the first microprocessor to have a 16-bit index register.</p>

<p>The 6809 has been used in various systems, including the TRS-80 Color Computer, the Dragon 32 and 64, and the Tandy 1000.</p>

<h2 id="motorola-68000-1979">Motorola 68000 (1979)</h2>
<p>The 68000 derives from 6800, is a processor with 8 32-bit general-purpose registers and a 16-bit address bus. The 68000 is the first microprocessor to have an on-chip memory management unit.</p>

<p>The 68000 has been used in various systems, including the Apple Lisa, the Commodore Amiga, and the Atari ST.</p>

<h2 id="motorola-68008-1979">Motorola 68008 (1979)</h2>
<p>The 68008 is an evolution of the 68000, with a more advanced architecture. The 68008 is a RISC processor, with 8 32-bit general-purpose registers and a 24-bit address bus.</p>

<p>The 68008 has been used in various systems, including the Sinclair QL.</p>

<h2 id="mos-6502-1975">MOS 6502 (1975)</h2>
<p>The 6502 is a processor with a simple instruction set, it has 3 registers, 8-bit accumulator, 8-bit index register, and 8-bit stack pointer. It was used in the Commodore Vic-20 and PET, Atari 2600, BBC Micro, Nintendo Nes. It’s also used on Terminator T-101 and Bender from Futurama.</p>

<p>It’s not compatible with 6800.</p>

<h2 id="mos-6510-1982">MOS 6510 (1982)</h2>
<p>The 6510 is an evolution of the 6502 with an I/O port and a pin for clock. It was used in the Commodore 64.</p>

<h2 id="mos-8502-1979">MOS 8502 (1979)</h2>
<p>The 8502 is an evolution of the 6510, it’s capable to run at 1 or 2 MHz. It was used in the Commodore 128.</p>

<h1 id="intel-path">Intel path</h1>

<p><img src="/resources/8bit-comparison-intel.png" align="left" alt="Intel path" style="padding: 10px" /></p>

<h2 id="intel-4004-1971">Intel 4004 (1971)</h2>
<p>Designed to replace a large number of TTL ICs, the 4004 was a very simple chip that could only handle data in 4-byte groups. It had a 12-bit address bus and addressed up to 640 bytes.</p>

<h2 id="intel-8008-1972">Intel 8008 (1972)</h2>
<p>The Intel 8008 is an 8-bit microprocessor that was released in 1972. It was the successor to the Intel 4004 and offered significant improvements in terms of performance and capabilities. The 8008 had an 8-bit data bus and a 14-bit address bus, allowing it to address up to 16KB of memory. It also introduced a more advanced instruction set, with support for more complex operations and addressing modes.</p>

<p>Compared to the Intel 4004, the 8008 had a higher clock speed and could execute instructions at a faster rate. It also had a larger addressable memory space, making it more suitable for a wider range of applications. Additionally, the 8008 featured more general-purpose registers, allowing for more efficient data manipulation.</p>

<h2 id="intel-8080-1974">Intel 8080 (1974)</h2>
<p>The Intel 8080 is an 8-bit microprocessor that was released in 1974. It is the successor to the Intel 8008 and offers several improvements in terms of performance and capabilities. The 8080 has an 8-bit data bus and a 16-bit address bus, allowing it to address up to 64KB of memory. It also introduced a more advanced instruction set, with support for more complex operations and addressing modes.</p>

<p>Compared to the Intel 8008, the 8080 has a higher clock speed and can execute instructions at a faster rate. It also has more general-purpose registers, allowing for more efficient data manipulation. Additionally, the 8080 features improved interrupt handling and supports a wider range of input/output devices.</p>

<p>It was used on Altair 8800.</p>

<h2 id="intel-8085-1977">Intel 8085 (1977)</h2>
<p>The Intel 8085 is an 8-bit microprocessor that was released in 1976 as an improved version of the Intel 8080.</p>

<p>The 8085 features a higher clock speed and improved instruction execution time compared to the 8080. It also introduces new instructions and addressing modes, providing more flexibility in programming. Additionally, the 8085 includes a built-in serial I/O port, making it easier to interface with external devices.</p>

<p>In terms of compatibility, the 8085 is backward compatible with the 8080, meaning that programs written for the 8080 can run on the 8085 without modification. However, the 8085 offers additional features and improved performance, making it a more advanced choice.</p>

<p>It was used on TRS-80 Model 100.</p>

<h2 id="intel-8086-1978">Intel 8086 (1978)</h2>
<p>The Intel 8086 is a 16-bit microprocessor that was released in 1978 as an enhanced version of the Intel 8085. It introduced a new architecture known as x86, which became the foundation for modern computer systems.</p>

<p>Compared to the Intel 8085, the 8086 offers several significant improvements. Firstly, it has a wider data bus, allowing it to process data in 16-bit chunks instead of 8-bit. This results in faster data processing and improved performance. Additionally, the 8086 has a larger addressable memory space, supporting up to 1MB of memory compared to the 64KB limit of the 8085.</p>

<p>Another key difference is the introduction of segmented memory addressing in the 8086. This allows for more efficient memory management and enables the use of larger programs. The 8086 also features a more advanced instruction set, including support for complex operations and addressing modes.</p>

<h2 id="intel-8088-1979">Intel 8088 (1979)</h2>
<p>The Intel 8088 is a variant of the Intel 8086 microprocessor. It was released in 1979 and is commonly referred to as the “brain” of the original IBM PC.</p>

<p>The 8088 is a 16-bit microprocessor with an 8-bit external data bus. This means that it can process data in 16-bit chunks internally, but can only transfer data to and from memory in 8-bit increments. It has a clock speed of 4.77 MHz.</p>

<p>Compared to the 8086, the 8088 has a narrower data bus, which affects its overall performance. The 8088’s 8-bit data bus limits its data transfer rate and can result in slower execution of certain operations. However, this design choice was made to reduce the cost of the system, as it allowed for the use of cheaper 8-bit memory chips.</p>

<p>It was the core of the Ibm Pc.</p>]]></content><author><name>Raffaele Intorcia</name><email>raffaele.intorcia@gmail.com</email></author><category term="6800" /><category term="6809" /><category term="68000" /><category term="68008" /><category term="6502" /><category term="6510" /><category term="8502" /><category term="processor" /><category term="microprocessor" /><summary type="html"><![CDATA[This is a non-complete exposition of the CPUs that were protagonists in the 70-80s. We will see the connections and evolutions of the different architectures and the main computers that have adopted them.]]></summary></entry><entry><title type="html">Autoboot explained</title><link href="https://intoinside.github.io/2024/04/07/autoboot-explained/" rel="alternate" type="text/html" title="Autoboot explained" /><published>2024-04-07T00:00:00+00:00</published><updated>2024-04-07T00:00:00+00:00</updated><id>https://intoinside.github.io/2024/04/07/autoboot-explained</id><content type="html" xml:base="https://intoinside.github.io/2024/04/07/autoboot-explained/"><![CDATA[<p>C128 has a particular feature for autoboot.</p>

<p><span class="badge badge-info"><span class="badge-unicode">ⓘ</span> Note: Autoboot feature is for C128 only, not supported on C64</span></p>

<p>When the c128 starts up, it performs a series of checks to decide
the operating mode. In particular, it checks in the following order:</p>
<ul>
  <li>the presence of a cartridge</li>
  <li>the request to start in C64 mode (if the Commodore button was pressed)</li>
  <li>starting the machine language monitor</li>
</ul>

<p>If you want to see how cold start is performed, see <a href="https://c128lib.github.io/Reference/StartupSequence">this page on Reference</a>.</p>

<p>If none of these conditions are met, the C128 checks whether a disk is
inserted in the drive and searches for the boot sector by reading
track 1 sector 0 into buffer at $B00.</p>

<p>Then the process is handled by Kernal subroutine called BOOTCALL at
<a href="https://c128lib.github.io/Reference/E000#FF53">$FF53</a>.</p>

<p><span class="badge badge-info"><span class="badge-unicode">ⓘ</span> Note: BOOTCALL requires parameters to be set, check documentation</span></p>

<table>
  <thead>
    <tr>
      <th>Byte</th>
      <th>Content</th>
      <th>Description</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>$00 $01 $02</td>
      <td>Signature</td>
      <td>Autoboot signature “CBM”</td>
    </tr>
    <tr>
      <td>$03 $04</td>
      <td>Address low Address high</td>
      <td>Address at which the contents of additional boot sectors are to be stored</td>
    </tr>
    <tr>
      <td>$05</td>
      <td>Bank</td>
      <td>Bank for additional sector</td>
    </tr>
    <tr>
      <td>$06</td>
      <td>Count</td>
      <td>Number of additional sectors to load</td>
    </tr>
    <tr>
      <td>$07</td>
      <td>Boot message</td>
      <td>Booting message to show null terminated</td>
    </tr>
    <tr>
      <td>$08 + (boot-message-length)</td>
      <td>Program name</td>
      <td>Program to load null terminated</td>
    </tr>
    <tr>
      <td>$09 + (boot-message-length) + (program-name-length) .. $ff</td>
      <td>Loader code</td>
      <td>Loader code padded with $00</td>
    </tr>
  </tbody>
</table>

<p>Subroutine checks if there is a valid signature (which is “CBM”), if not a <code class="language-plaintext highlighter-rouge">rts</code> is performed.
The test is performed using the <a href="https://c128lib.github.io/Reference/E000#E2C4">$E2C4</a>
location which contains the pattern to be tested.</p>

<p>A “BOOTING” string is printed on screen then some bytes are read from boot sector:</p>
<ul>
  <li>$03, $04 are stored in <a href="https://c128lib.github.io/Reference/0000#AC">$AC-$AD</a> (load address for additional boot sector)</li>
  <li>$05 is stored in <a href="https://c128lib.github.io/Reference/0000#AE">$AE</a> (bank number)</li>
  <li>$06 is stored in <a href="https://c128lib.github.io/Reference/0000#AF">$AF</a> (additional boot sector to load)</li>
</ul>

<p>Subsequent bytes are printed to screen until a null char is found or until
the end of the sector is reached. Following the message, three dots are
printed.</p>

<p><img src="/resources/booting-message.png" alt="Booting message" /></p>

<p>The bank number for boot data is transferred into the working bank
number location <a href="https://c128lib.github.io/Reference/0000#C6">$C6</a>.</p>

<p>If the value in $AF is non zero, then additional data is read sequentially
from boot sector in the specified bank at the address specified by $AC-$AD,
starting from sector 1 of track 1.</p>

<p>After all bytes are read, the drive is reset. The routine
then searches the buffer from the zero byte marking the end
of the message until another byte containing a zero is found.
The characters, if any, between the zero bytes are taken to be
the name of a file to be loaded, and the drive number and a
colon are placed immediately before the name in the buffer. If
a filename is found, the routine attempts to load a file with
that name into bank 0. Because the Kernal
<a href="https://c128lib.github.io/Reference/E000#FFD5">LOAD</a>
routine is used, this file must be PRG (program) type. This file is always
loaded into bank 0, regardless of the bank number specified
for boot sectors.</p>

<p>After the file is loaded (or if no filename is specified), the
<a href="https://c128lib.github.io/Reference/E000#FF6E">JSRFAR</a> address pointer
(<a href="https://c128lib.github.io/Reference/0000#03">$03-$04</a>)
holds the address of the buffer location following the end-of-filename zero
byte, and the JSRFAR bank (<a href="https://c128lib.github.io/Reference/0000#02">$02</a>)
is set for bank 15. The JSRFAR routine is then used to execute the machine
language subroutine following the filename in the boot sector buffer.
Some machine language code must be present, even if it’s only an
<code class="language-plaintext highlighter-rouge">rts</code> opcode. Finally, the routine exits with the status register
carry bit clear.</p>]]></content><author><name>Raffaele Intorcia</name><email>raffaele.intorcia@gmail.com</email></author><category term="commodore-128" /><category term="autoboot" /><category term="boot" /><summary type="html"><![CDATA[C128 has a particular feature for autoboot.]]></summary></entry><entry><title type="html">The bit trick</title><link href="https://intoinside.github.io/2024/04/06/the-bit-trick/" rel="alternate" type="text/html" title="The bit trick" /><published>2024-04-06T00:00:00+00:00</published><updated>2024-04-06T00:00:00+00:00</updated><id>https://intoinside.github.io/2024/04/06/the-bit-trick</id><content type="html" xml:base="https://intoinside.github.io/2024/04/06/the-bit-trick/"><![CDATA[<p>Let’s take this snippet:</p>
<pre><code class="language-Assembly">STEP1:  LDX #$10
        JMP END

STEP2:  LDX #$20
        JMP END

STEP3:  LDX #$30

END:    LDA #$12
        STA $1000,X

// Total bytes: 5 + 5 + 2 + 5 = 17
// Total cycles: 12
</code></pre>
<p>There are three entrypoint used for setting .X register as index for the
last <code>STA</code> instruction. These instructions uses 17 bytes and
requires 12 cycles (when jmuping on STEP1 or STEP2).</p>

<p>A first optimization consist in changing <code>JMP END</code>, which is
3by/3cy, with a BNE (because all there LDX don’t set zero-flag)
which is 2by/2cy. Code is modified:</p>

<pre><code class="language-Assembly">STEP1:  LDX #$10
        BNE END

STEP2:  LDX #$20
        BNE END

STEP3:  LDX #$30

END:    LDA #$12
        STA $1000,X

Total bytes: 4 + 4 + 2 + 5 = 15
Total cycles: 10
</code></pre>
<p>A total of 2 bytes and 2 cycles were saved with this trick.
This is good but:</p>
<ul>
  <li>when using <code>LDX</code> with #$0, BNE should be changed with BEQ</li>
  <li>branch can be up to 127 byte ahead</li>
</ul>

<p>There is another particular trick that can be used to reduce size (but
increase cycles count). It’s known as BIT trick and it’s
often used in Kernal code to avoid jump.</p>

<p>From <a href="https://www.c64-wiki.com/wiki/BIT_(assembler)">C64-wiki</a>:
<cite>
BIT (short for “BIT test”) is the mnemonic for a machine language instruction which tests specific bits in the contents of the address specified, and sets the zero, negative, and overflow flags accordingly, all without affecting the contents of the accumulator.
Bit 7 (weight 128/$80; the most sigificant bit) is transferred directly into the negative flag.
Bit 6 (weight 64/$40) is transferred directly into the overflow flag.
A bit-wise “and” is performed between the contents of the designated memory address and that of the accumulator; if the result of this is a zero byte, the zero flag is set.
</cite></p>

<p>This is the code that use <code>BIT</code> instead of
<code>JMP</code> or <code>BNE</code>.</p>

<pre><code class="language-Assembly">STEP1:  LDX #$10
        .BYTE $2C

STEP2:  LDX #$20
        .BYTE $2C

STEP3:  LDX #$30

STEP4:  LDA #$12
        STA $1000,X

Total bytes: 3 + 3 + 2 + 5 = 13
Total cycles: 17
</code></pre>
<p>This can be quite difficult to understand. So let’s assemble this code to
see how mnemonic is converted to opcode:</p>
<pre><code class="language-Opcode">A2 10     LDX #$10
2C        .BYTE $2C
A2 20     LDX #$20
2C        .BYTE $2C
A2 30     LDX #$30
A9 12     LDA #$12
9D 00 10  STA $1000,X
</code></pre>
<p>Ok, now let’s see what’s happens when a <code>JMP STEP1</code> is performed.</p>
<pre><code class="language-Assembly">A2 10     LDX #$10      // .X is loaded with $10

2C A2 20  BIT $20A2     // A2 20 is LDX #$20 but is interpreted as address for
                        // BIT. BIT won't affect .X value

2C A2 30  BIT $30A2     // A2 30 is LDX #$30 but is interpreted as address for
                        // BIT. BIT won't affect .X value

A9 12     LDA #$12      // .A is loaded with $12
9D 00 10  STA $1000,X   // .X is still $10
</code></pre>

<p>By using $2C (which correspond to <code>BIT $nnnn</code>) 2 bytes can be
skipped, but also $24 can be used (which correspond to <code>BIT $nn</code>) to
skip one byte.</p>

<p>This is a particular technique to avoid jumping but you must be aware that:</p>
<ul>
  <li>some flags will be changed by <code>BIT</code> opcode</li>
  <li>it uses more cycle so speed should not be a requirement</li>
</ul>

<p>As said before, this trick is heavily used in kernal, for example look at
<strong>Handles Kernal I/O errors</strong> at
<a href="https://c128lib.github.io/Reference/E000#F67C">$F67C</a> in C128 Kernal.</p>

<p>This is a snippet:</p>
<pre><code class="language-Opcode">// Print 'too many files'
F67C: A9 01	LDA #$01
F67E: 2C	.BYTE $2C

// Print 'file open'
F67F: A9 02	LDA #$02
F681: 2C	.BYTE $2C

// Print 'file not open'
F682: A9 03	LDA #$03
F684: 2C	.BYTE $2C

// Print 'file not found'
F685: A9 04	LDA #$04
F687: 2C	.BYTE $2C

// Print 'device not present'
F688: A9 05	LDA #$05
F68A: 2C	.BYTE $2C

// Print 'not input file'
F68B: A9 06	LDA #$06
F68D: 2C	.BYTE $2C

// Print 'not output file'
F68E: A9 07	LDA #$07
F690: 2C	.BYTE $2C

// Print 'missing file name'
F691: A9 08	LDA #$08
F693: 2C	.BYTE $2C

// Print 'illegal device no'
F694: A9 09	LDA #$09
F696: 2C	.BYTE $2C

// Error #0
F697: A9 10	LDA #$10
F699: 48	PHA
...
</code></pre>]]></content><author><name>Raffaele Intorcia</name><email>raffaele.intorcia@gmail.com</email></author><category term="opcode" /><category term="bit" /><category term="bit-trick" /><category term="commodore-64" /><category term="commodore-128" /><category term="assembly" /><summary type="html"><![CDATA[Let’s take this snippet: ``` Assembly STEP1: LDX #$10 JMP END]]></summary></entry><entry><title type="html">Sprite editor survival guide</title><link href="https://intoinside.github.io/2024/01/03/sprite-editor/" rel="alternate" type="text/html" title="Sprite editor survival guide" /><published>2024-01-03T00:00:00+00:00</published><updated>2024-01-03T00:00:00+00:00</updated><id>https://intoinside.github.io/2024/01/03/sprite-editor</id><content type="html" xml:base="https://intoinside.github.io/2024/01/03/sprite-editor/"><![CDATA[<p>Designing sprite with the Commodore 64 was done using a grid similar to this one.</p>

<p><img src="/resources/sprite-grid.jpg" alt="" /></p>

<p>Each row is encoded with 3 bytes, each representing the value of 8 columns. By encoding
every row, you’ll get (3 * 21) = 63 bytes which defines the entire sprite.
Things are similar in case of multicolor sprite, where every pixel is defined with
2 byte (so there are 3 colour available + background).</p>

<p>This method continues to be valid with the C128 but there are other more convenient
possibilities for defining sprites.</p>

<h3 id="using-sprite-editor">Using sprite editor</h3>

<p>C128 has a Basic command called <strong>SPRDEF</strong> which activates the internal sprite
editor.</p>

<figure>
<img src="https://www.c64-wiki.com/images/e/e3/SPRDEF.png" alt="SPRDEF" />
<figcaption>Sprite selection screen - from <a href="https://www.c64-wiki.com/wiki/File:SPRDEF.png">c64-wiki</a></figcaption>
</figure>

<p>Cursor is represented as ‘+’ for hi-res sprite or ‘++’ for multicolor sprite.
You can type from 1 to 8 to select which sprite to edit. Otherwise you can press
<span class="keystroke">RETURN</span> to exit from editor.</p>

<p>When sprite is selected, working mode is active and there are some command to edit
sprite.</p>

<table>
  <thead>
    <tr>
      <th>Key</th>
      <th>Description</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><span class="keystroke">SHIFT</span> + <span class="keystroke">RETURN</span></td>
      <td>Saves the designed sprite and returns to the sprite selection</td>
    </tr>
    <tr>
      <td><span class="keystroke">RUN/STOP</span></td>
      <td>Discards changes and returns to sprite selection</td>
    </tr>
    <tr>
      <td><span class="keystroke">CRSR</span></td>
      <td>Moves the cursor in the workspace</td>
    </tr>
    <tr>
      <td><span class="keystroke">RETURN</span></td>
      <td>Places cursor at the beginning of the next line (except for the last line, where it is positioned only at the 1st column)</td>
    </tr>
    <tr>
      <td><span class="keystroke">CLR/HOME</span></td>
      <td>Places the cursor in the upper left corner of the workspace</td>
    </tr>
    <tr>
      <td><span class="keystroke">SHIFT</span> + <span class="keystroke">CLR/HOME</span></td>
      <td>Clears the sprite grid and positions the cursor in the upper left corner</td>
    </tr>
    <tr>
      <td><span class="keystroke">1</span></td>
      <td>Deletes point</td>
    </tr>
    <tr>
      <td><span class="keystroke">2</span></td>
      <td>Sets point in foreground color</td>
    </tr>
    <tr>
      <td><span class="keystroke">3</span></td>
      <td>Sets point in additional color 1 (for multicolor sprite)</td>
    </tr>
    <tr>
      <td><span class="keystroke">4</span></td>
      <td>Sets point in additional color 2 (for multicolor sprite)</td>
    </tr>
    <tr>
      <td><span class="keystroke">A</span></td>
      <td>Enables/disables automatic cursor movement (to the right) for pixel change keys 1 to 4</td>
    </tr>
    <tr>
      <td><span class="keystroke">C</span></td>
      <td>Copies pattern from another sprite. 1 to 8 selects the sprite, RETURN cancels the action</td>
    </tr>
    <tr>
      <td><span class="keystroke">CTRL</span> + <span class="keystroke">1</span> to <span class="keystroke">CTRL</span> + <span class="keystroke">8</span></td>
      <td>Selects one of the foreground colors from 1 to 8</td>
    </tr>
    <tr>
      <td><span class="keystroke"><img src="/resources/cmd-key.png" alt="" /></span> + <span class="keystroke">1</span> to <span class="keystroke"><img src="/resources/cmd-key.png" alt="" /></span> + <span class="keystroke">8</span></td>
      <td>Selects one of the foreground colors from 9 to 16</td>
    </tr>
    <tr>
      <td><span class="keystroke">X</span></td>
      <td>Turns double width sprite on/off</td>
    </tr>
    <tr>
      <td><span class="keystroke">Y</span></td>
      <td>Turns double height sprite on/off</td>
    </tr>
    <tr>
      <td><span class="keystroke">M</span></td>
      <td>Turns multicolor mode on/off</td>
    </tr>
  </tbody>
</table>

<figure>
<img src="https://www.c64-wiki.com/images/6/62/SPRDEF-Smiley.png" alt="SPRDEF" />
<figcaption>Example of defined hi-res sprite - from <a href="https://www.c64-wiki.com/wiki/File:SPRDEF-Smiley.png">c64-wiki</a></figcaption>
</figure>

<p>Once sprite is defined, you can quit working mode (with
<span class="keystroke">SHIFT</span> + <span class="keystroke">RETURN</span>)
and sprite will be saved in memory. By exiting from editor
(with <span class="keystroke">RETURN</span>), it can be saved to disk with
<strong>BSAVE</strong> command</p>

<pre><code class="language-Assembly">BSAVE "FILENAME",B0,P3584 TO P4096
</code></pre>
<p>Where:</p>
<ul>
  <li>B0 means the bank (from B0 to B15)</li>
  <li>P3584 means the starting address</li>
  <li>P4096 means the ending address + 1</li>
</ul>

<p>Starting address and end address are in decimal format.</p>

<p>Memory area from 3584 to 4096 contains all 8 sprites so if you don’t want to save them
all, you can start from 3854 up to 3584 + (num-sprite-to-save * 64).</p>

<p>Saved sprites can be loaded with <strong>BLOAD</strong> command:</p>

<pre><code class="language-Assembly">BLOAD "FILENAME", B0, P3584
</code></pre>
<p>Where:</p>
<ul>
  <li>B0 means the bank (from B0 to B15)</li>
  <li>P3584 means the starting address where the save begins</li>
</ul>

<p>Starting address and end address is in decimal format.</p>

<p>Note: bank 0 to 15 are predefined, look at the <a href="https://c128lib.github.io/Reference/MemoryMap">reference</a>.</p>

<h3 id="drawing-bitmap">Drawing bitmap</h3>

<p>Sprite can also be defined by drawing graphics on bitmap screen. Let’s take a simple
Basic listing:</p>
<pre><code class="language-Basic">100 graphic 1,1
110 draw 1,0,0 to 23,20
120 draw 1,0,20 to 23,0
125 box 1,0,0,23,20
130 circle 1,12,10,10
140 sshape a$,0,0,23,20
150 sprsav a$,1
160 sprite 1,1,11,0,1,1,0
170 movspr 1,160,100
180 movspr 1,120#7
190 getkey k$
200 graphic 0: movspr 1,0#0
</code></pre>
<ul>
  <li>Line 100 activates high resolution graphic screen and clears it.</li>
  <li>Line 110 to 130 creates a simple graphic object in top left corner.</li>
  <li>Line 140 copies a 24x21 area to string called a$</li>
  <li>Line 150 saves data inside string a$ to sprite 1</li>
  <li>Line 160 activates sprite 1 with color 11 (light red) and some other params</li>
  <li>Line 170 moves sprite 1 to (160, 100)</li>
  <li>Line 180 sets autonomous movement for sprite 1 with angle of 120 and speed 7</li>
  <li>Line 190 waits for a keypress (while sprite 1 is still moving)</li>
  <li>Line 200 sets text mode and stops sprite 1 movement</li>
</ul>

<p>Important lines are:</p>
<ul>
  <li>140, bitmap area is converted to string and copied into a variable</li>
  <li>150, defines a sprite with string content of a variable</li>
</ul>

<p>It’s possible to “paint” a string to bitmap area, it’a just the reverse of <strong>SSHAPE</strong>:</p>

<pre><code class="language-Basic">GSHAPE &lt;var&gt;, [[&lt;x&gt;, &lt;y&gt;], &lt;mode&gt;]
</code></pre>
<p>where</p>
<ul>
  <li>var is the variable that contains the string</li>
  <li>(x, y) is the coordinate for painting (if omitted, current cursor position will
be used)</li>
  <li>mode is the painting mode used (default, inverted, OR-ed, AND-ed, XOR-ed)</li>
</ul>]]></content><author><name>Raffaele Intorcia</name><email>raffaele.intorcia@gmail.com</email></author><category term="commodore-128" /><category term="sprite" /><category term="sprite-editor" /><summary type="html"><![CDATA[Designing sprite with the Commodore 64 was done using a grid similar to this one.]]></summary></entry><entry><title type="html">Memory copy with relocation on Commodore 128</title><link href="https://intoinside.github.io/2023/12/26/memcopy-with-relocation/" rel="alternate" type="text/html" title="Memory copy with relocation on Commodore 128" /><published>2023-12-26T00:00:00+00:00</published><updated>2023-12-26T00:00:00+00:00</updated><id>https://intoinside.github.io/2023/12/26/memcopy-with-relocation</id><content type="html" xml:base="https://intoinside.github.io/2023/12/26/memcopy-with-relocation/"><![CDATA[<p>Suppose you need to copy a full memory page (256 bytes) from one address to another
using assembly on Mos 6502.</p>

<p>There are many ways to accomplish this task. The simplest one is a subroutine like
this:</p>

<pre><code class="language-Assembly">      ldx #0                  // 2 cycles - 2 bytes
  !:  lda $0400,x             // 4 cycles - 3 bytes
      sta $0600,x             // 5 cycles - 3 bytes
      inx                     // 2 cycles - 1 byte
      bne !-                  // 2 cycles - 2 bytes
      rts                     // 6 cycles - 1 byte
</code></pre>

<p>This example copies 256 bytes from $0400 to $0600 and requires 3328 cycles for
loop and other 8 for initial ldx and rts. It also uses 12 bytes of memory.</p>

<p>Another version can be more flexible, in order to choose which page should be used
for source and destination:</p>

<pre><code class="language-Assembly">      stx r + 2               // 4 cycles - 3 bytes
      sty w + 2               // 4 cycles - 3 bytes
      ldx #0                  // 2 cycles - 2 bytes
  r:  lda $ff00,x             // 4 cycles - 3 bytes
  w:  sta $ff00,x             // 5 cycles - 3 bytes
      inx                     // 2 cycles - 1 byte
      bne r                   // 2 cycles - 2 bytes
      rts                     // 6 cycles - 1 byte
</code></pre>
<p>This routine expects source page in .X and destination page in .Y. Then with some
self-mod code, pages are used instead of $ff00.
This example requires 3328 cycles for loop and other 16 for init and rts. It also uses
18 bytes. Before calling, there are also a ldx and ldy instructions for page settings.</p>

<p>At this point there are no major improvements that can be made. To write a better
algorithm it is necessary to completely change the solution setup. Among the
innovations that the C128 brings with it is the possibility of relocating page 0
and page 1.
The relocation of pages 0/1 is carried out by changing the value of the addresses
between $D507 and $D50A (<a href="https://c128lib.github.io/Reference/D500#D507">see memory reference</a>).
By appropriately entering the parameters it is possible to
indicate on which memory area the two pages must be mapped and also on which block
(the first or second 64Kb of RAM).</p>

<p>Regarding copying between memory areas, let’s see how relocation can be exploited.</p>

<pre><code class="language-Assembly">// Zero page location labels
      .label TEMP   = $fe

      sei                     // 2 cycles - 1 byte
      stx r + 2               // 4 cycles - 3 bytes
      tsx                     // 2 cycles - 1 byte
      stx TEMP                // 2 cycles - 2 bytes
      sty $d509               // 4 cycles - 3 bytes

      ldx #0                  // 2 cycles - 2 bytes
      txs                     // 2 cycles - 1 byte
  r:  lda $ff00,x             // 4 cycles - 3 bytes
      pha                     // 3 cycles - 1 byte
      dex                     // 2 cycles - 1 byte
      bne r                   // 2 cycles - 2 bytes

      ldx #1                  // 2 cycles - 2 bytes
      stx $d509               // 4 cycles - 3 bytes
      ldx TEMP                // 3 cycles - 2 bytes
      txs                     // 2 cycles - 1 byte
      cli                     // 2 cycles - 1 byte
      rts                     // 6 cycles - 1 byte
</code></pre>

<p>This code requires 2816 cycles for loop and 31 other cycles for preparing and closing
copy routine (2847 total cycles). It also requires 30 bytes of memory.</p>

<p>It’s 14% faster than the previous solution, it may not seem like much but in some
places where few cycles are available, even 600 fewer cycles can make a difference.
For example, consider using this algorithm between the raster interrupt lines.</p>

<p>Let’s go into detail about the algorithm to understand how it works and consider
copy page at $1000 (page $10) into page $2000 (page $20).
This is the initial status of memory.</p>

<p><img src="/resources/relocation-step-1.jpg" alt="Step 1" /></p>

<p>This is the initial status with page 0 and 1 located at $0000 and $0100.
As expected, .X should contain source page ($10) and .Y should contain destination page
($20). Current stack is yellow.</p>

<pre><code class="language-Assembly">// Disable interrupt
      sei
// Self-mod code to setup lda on correct page (on .X before algorithm
// start)
      stx r + 2
// Preserve current stack pointer on zero-page location
      tsx
      stx TEMP

// Relocate stack to destination page (on .Y before algorithm
// start)
      sty $d509
</code></pre>

<p>After running the first part of the algorithm, memory status has changed:</p>

<p><img src="/resources/relocation-step-2.jpg" alt="Step 2" /></p>

<p>Interrupt are disabled, a self-mod code is done to point to source page and current
stack pointer value (for example, $70) is copied into a zero-page location. Last
operation will relocate stack from page 1 to destination page ($20).</p>

<p>And now the main part:</p>

<pre><code class="language-Assembly">// Init index and stack pointer
      ldx #0
      txs
// Load byte from source page to .A
  r:  lda $ff00,x
// Push byte from .A to stack (which is destination page)
      pha

// Decrement index and check for next loop
      dex
      bne r
</code></pre>

<p><img src="/resources/relocation-step-3.jpg" alt="Step 3" /></p>

<p>Stack pointer is set to 0 and loop starts loading each byte from starting page and
it’s pushed to stack. At first push, stack is updated from $00 to $FF and it’s
decremented at each iteration. When .X reach 0, loop is stopped.</p>

<p>The last part, the initial environment is restored:</p>

<pre><code class="language-Assembly">// Restore one-page to original mapping
      ldx #1
      stx $d509

// Restore stack pointer to original value
      ldx TEMP
      txs

// Reactivate interrupt and return to caller
      cli
      rts
</code></pre>

<p><img src="/resources/relocation-step-4.jpg" alt="Step 4" /></p>

<p>Stack page is restored to page 1 and then original stack pointer is taken from $FE
and restored to original value. Lastly, interrupt are reactivated.</p>

<p>This can be a valid alternative if you have to be quick. It is only available on
Commodore 128 because the relocation of the pages is managed by the MMU. The price
to pay is greater implementation complexity.</p>

<h3 id="update-27122023">Update 27/12/2023</h3>

<p><a href="https://www.youtube.com/@oziphantom9465">Daniel Hotop</a> sent me an improvement.
There are two main differences:</p>
<ul>
  <li>relocating of page 0 and 1</li>
  <li>unrolled loop</li>
</ul>

<p>In the first example, only page 1 was relocated. In this example, page 0 is also
relocated and mapped onto the source page. This trick allows you to run LDAs with
<em>Zeropage addressing</em> instead of <em>Indexed absolute addressing</em> which saves a
clock cycle (and also one byte).</p>

<p>With cycle unrolling, the size increases significantly but you can save 2 cycles for
DEX and 2 cycles for BNE needed for loop handling.</p>

<p>This solution also requires the source page in .X and destination page in .Y.</p>

<pre><code class="language-Assembly">      .label TEMP   = $fe

      sei             // 2 cycles - 1 byte
      stx $d507       // 4 cycles - 3 byte
      stx Src1 + 2    // 4 cycles - 3 byte
      stx Src2 + 2    // 4 cycles - 3 byte
      tsx             // 2 cycles - 1 byte
      stx TEMP        // 3 cycles - 2 byte
      sty $d509       // 4 cycles - 3 byte
      ldx #0          // 2 cycles - 2 byte
      txs             // 2 cycles - 1 byte

      lda $ff         // 3 cycles - 2 byte
      pha             // 3 cycles - 1 byte
      lda $fe         // 3 cycles - 2 byte
      pha             // 3 cycles - 1 byte

      // Other lda-pha pairs

      lda $2          // 3 cycles - 2 byte
      pha             // 3 cycles - 1 byte
  :Src1
      lda $ff01       // 4 cycles - 3 byte
      pha             // 3 cycles - 1 byte
  :Src2
      lda $ff00       // 4 cycles - 3 byte
      pha             // 3 cycles - 1 byte

      ldy #0          // 2 cycles - 2 byte
      sty $d507       // 4 cycles - 3 byte
      ldy #1          // 2 cycles - 2 byte
      sty $d509       // 4 cycles - 3 byte
      ldx TEMP        // 3 cycles - 2 bytes
      txs             // 2 cycles - 1 byte

      cli             // 2 cycles - 1 byte
      rts             // 6 cycles - 1 byte
</code></pre>

<p>Pure copy requires 1538 cycles, full subroutine requires 1590 cycles. The improvement
compared to the single relocation solution is 44%. Subroutine size increased to
804 bytes.</p>]]></content><author><name>Raffaele Intorcia</name><email>raffaele.intorcia@gmail.com</email></author><category term="memcopy" /><category term="relocation" /><category term="commodore-128" /><category term="assembly" /><summary type="html"><![CDATA[Suppose you need to copy a full memory page (256 bytes) from one address to another using assembly on Mos 6502.]]></summary></entry><entry><title type="html">Window feature on C128</title><link href="https://intoinside.github.io/2023/12/21/window-feature/" rel="alternate" type="text/html" title="Window feature on C128" /><published>2023-12-21T00:00:00+00:00</published><updated>2023-12-21T00:00:00+00:00</updated><id>https://intoinside.github.io/2023/12/21/window-feature</id><content type="html" xml:base="https://intoinside.github.io/2023/12/21/window-feature/"><![CDATA[<p>This post will explain windowing feature of C128, how to use it
and to survive.</p>

<p>Window is an interesting new features on the 128 screen output.
Printing and cursor movement can be confined to the boundaries of a window
rather than the whole screen.</p>

<p>To understand what windows are, let’s start with a simple example.</p>

<p>With a fresh-started C128, let’s fill screen with a Basic program like
this to fill screen:</p>

<pre><code class="language-Basic">10 PRINT CHR$(205.5+RND(1)); : GOTO 10
</code></pre>

<p>By running this program you’ll get an output similar to this screenshot.</p>

<p><img src="/resources/c128-maze.png" alt="Maze" /></p>

<p>With a full filled screen, WINDOW command can be called to create an
internal window inside 40-column screen. WINDOW command use four required and
one optional argument:</p>

<pre><code class="language-Basic">WINDOW left-boundary, top-boundary, right-boundary, bottom-boundary[, clear-screen]
</code></pre>
<p>First two argument are needed to select column and row which will be top left boundary.
Third and forth argument are needed to select bottom right boundary.
Last argument is optional and if it’s set to 1 then window will be cleared.</p>

<p>Note that all these coordinates should be compliant with screen width and height
(WINDOW can be used both on 40 or 80 column screen).</p>

<p>So stop execution of filling screen program and run window command:</p>

<pre><code class="language-Basic">WINDOW 2, 2, 20, 10, 1
</code></pre>

<p><img src="/resources/c128-maze-with-window.png" alt="Maze" /></p>

<p>As you can see, a new internal empty window has been created, starting from (2,2)
to (20,10).
Every action will happen inside this new window, external content will not be touched.</p>

<p>Remember that third and forth parameter are not width/height of window and you’ll
get an error if your parameters are out of current screen boundaries.</p>

<p>To get a more complete example, you can copy/paste this example on Vice (taken from
C128 System Guide):</p>

<pre><code class="language-Basic">10 scnclr : color 5,5
20 color 5,5
30 window 0, 0, 39, 24
40 color 0,13 : color 4,13
50 a$="abcdefghijklmnopqrst"
60 color 5,5
70 for i = 1 to 25
80 print a$;a$ : next i
90 window 1,1,7,20
100 color 5,3
110 print chr$(18);a$;
120 window 15,15,39,20,1
130 color 5,7
140 for i = 1 to 6 : print a$; : next i
150 window 30,1,39,22,1
160 color 5,8 : list
170 window 5,5,33,18,1
180 color 5,2
190 print a$ : list
200 end
</code></pre>

<p>There are 5 window defined in this program:</p>

<ul>
  <li>whole screen filled with a string (10-80)</li>
  <li>(1,1)-(7,20) with a reversed string printed (90-110)</li>
  <li>(15,15)-(39,20) (empty) with a reversed string printed 6 times (120-140)</li>
  <li>(30,1)-(39,22) (empty) with a list of current program (150-170)</li>
  <li>(5,5)-(33,18) (empty) with a reversed string (not visible) and a list of
current program (180-190)</li>
</ul>

<p>By running this program you’ll get</p>

<p><img src="/resources/c128-window-40cols.png" alt="Example 40-cols" /></p>

<p>In this example, there are 5 windows created on line 30, 90, 120, 150 and 170. In
every window, some text is written using different color so it’s quite clear to see
boundaries</p>

<p>This Basic program can be used also on 80-column screen without modification:</p>

<p><img src="/resources/c128-window-80cols.png" alt="Example 80-cols" /></p>

<p>Original full-screen window can be restored by using:</p>

<pre><code class="language-Basic">WINDOW 0, 0, 39, 24
</code></pre>]]></content><author><name>Raffaele Intorcia</name><email>raffaele.intorcia@gmail.com</email></author><category term="window" /><category term="commodore-128" /><category term="assembly" /><summary type="html"><![CDATA[This post will explain windowing feature of C128, how to use it and to survive.]]></summary></entry><entry><title type="html">Z80/8502 switchover</title><link href="https://intoinside.github.io/2023/07/07/running-z80/" rel="alternate" type="text/html" title="Z80/8502 switchover" /><published>2023-07-07T00:00:00+00:00</published><updated>2023-07-07T00:00:00+00:00</updated><id>https://intoinside.github.io/2023/07/07/running-z80</id><content type="html" xml:base="https://intoinside.github.io/2023/07/07/running-z80/"><![CDATA[<p>Italian version will come…</p>

<p>Commodore C128 is a double 8-bit processor machine. it has:</p>
<ul>
  <li>a MOS 8502 (derived from 6510 and 6502) which is used to run C128 Basic v7 mode
and C64 Basic v2 mode</li>
  <li>a Zilog Z80 which is used to run CP/M.</li>
</ul>

<p>Commodore says that is’t like having 3 pc in one. Aside from commercial,
8502 and Z80 share all components of this machine and also share data bus
and address bus. This sharing makes impossible to run simultaneously so
a processor can run while the other is inactive.</p>

<h2 id="booting-process">Booting process</h2>

<p><cite>(from Mapping the Commodore 128)</cite></p>

<p>After power up, the Z80 microprocessor has control before the 8502 is allowed
to take over.
There are only a few signs of this: two short routines are copied into bank 0
RAM. One, at $FFD0-$FFDF, is an 8502 ML routine that surrenders control to the
Z80;</p>

<pre><code class="language-Assembly">  FFD0  SEI
  FFD1  LDA #$3E
  FFD3  STA $FF00
  FFD6  LDA #$B0
  FFD7  STA $D505
  FFDB  NOP
  FFDC  JMP $1100
  FFDF  NOP
</code></pre>

<p>the other, at $FFE0-$FFEF, is a Z80 ML routine that surrenders control to
the 8502.</p>
<pre><code class="language-Assembly">  FFE0  DI
  FFE1  LD A, 3EH
  FFE3  LD (FF00H), A
  FFE6  LD BC, D505H
  FFE9  LD A, B1H
  FFEB  OUT (C),A
  FFED  NOP
  FFEE  RST 08H
</code></pre>

<p>There are no routines in any of the 128 mode ROMs to perform this
initialization.
These routines have no use in 128 mode-they can be used only in CP/M
mode-but they are recopied to block 0 during each reset.</p>

<p><a href="https://github.com/bvl1999">Bart van Leeuwen</a> made some research and
spent a lot of time about boot process and found some interesting information.
I’ll copy from our info exchange on FB.</p>

<pre>
Booting CP/M is always done from 128 mode. You can verify this: when
powering-on (or resetting) a C128 with a CP/M boot disk inserted, you will
get the BASIC V7 copyright message before CP/M starts. The 'trick' to this is
not in the CP/M BIOS but in the boot record of a CP/M disk.

So, even with a CP/M disk inserted, the machine will power-on/reset to Z80
mode first, do its copying to ram, and then always call the 'switch to 8502'
routine it copied to ram. This in turn will suspend the Z80, and start the
8502. Because the 8502 has been reset, it will start reading the 6502 reset
vector and start executing the C128 kernal.

The kernal will check for a C64 cartridge, if none found, check for an
autostart function rom (autostart byte == 1), and when none found, do the c128
kernal and basic initialization, after which phoenix will run.

Phoenix first checks for function roms with an autostart byte &gt;0 and run it if
found. When that returns, or none is found, it will read the first block of
the drive at id 8, and check for a boot signature. The CP/M boot disk has a
regular C128 boot signature, and some code which sets up the system to load
CP/M, and then switches to the Z80.
</pre>

<h2 id="reactivating-z80">Reactivating Z80</h2>

<p><cite>(from Mapping the Commodore 128)</cite></p>

<p>Switching processors is not for the faint of heart. When
you activate the Z80, it will begin executing instructions at
whatever address is currently in its program counter registers.
The address in those internal processor registers can’t be
changed from 128 mode, so you’re stuck with having the Z80
take up wherever it left off when the system was switched to
128 mode. This address is usually $FFEE, the location
following the one where 128 mode was activated at the end of
the Z80’s reset routine. In block 0 RAM, that location is initialized
with a Z80 instruction (RST1) to perform a warm start of
CP/M mode. If you don’t have a valid Z80 machine language
instruction there when you activate the Z80 (for example, if
the system is in a memory configuration such as bank 15
where 128 Kernal ROM is seen at that address) you’ll probably
experience an immediate system lockup.</p>

<p><cite>(from Power Assembler Instruction Manual)</cite></p>

<p>Bit 0 at <a href="https://c128lib.github.io/Reference/D500#D505">$D505</a>
(54533) controls the micro processor mode. If it is turned
on then the 8502 becomes active; if it is off then the Z80 takes over.
You can’t just poke it off. A little housekeeping is first in order:</p>
<ul>
  <li>disable 8502 interrupts via SEI because you are going to switch to a memory
configuration in which Kernal ROM is not visible.
To do this, store a $3E (62) at <a href="https://c128lib.github.io/Reference/E000#FF00">$FF00</a>
(the configuration register). This
leaves I/O RAM intact but switches everything else to RAM 0.</li>
</ul>

<p>The Z80 PC register holds $FFED after 128
initialization. There is a NOP ($00) there. The first actual Z80 command
goes at $FFEE. If you look through the monitor you will see a $CF there.
This is an RST 8 opcode byte which will cause the Z80 to jump (ReSTart)
to its own ROM routine at 0008. You do not want this. After moving some
8502 code into place at $3000, the Z80 would return control to the 8502.
The 8502 wakes up exactly where it left off after you switched to the
Z80. If you followed this switch with a NOP (lets not wake It up to fast)
and then a JMP $3000 (like the operating system does) you would go into
the 128’s boot CP/M routine. This is pretty useless from a programming
standpoint, so don’t bother. Instead, put your own Z80 code at $FFEE.</p>

<p>The last thing the U80 will have to do is to turn the 8500 back on. There
are two ways to do this:</p>
<pre><code class="language-Assembly">  LD A,$B1
  LD ($D505),A
</code></pre>
<p>This is inferior. There is a bleed through condition in the Z80 mode using
this type of store. A $B1 will also be written to underlying RAM.
Here is the proper way:</p>
<pre><code class="language-Assembly">  LD BC,$D505
  LD A,$B1
  OUT (C),A
</code></pre>
<p>Bleed through not occur using OUT storage and all I/O memory between
$D000 and $DFFF can be written to.</p>

<h2 id="exploiting">Exploiting</h2>

<p>So, this is the situation. Z80 started but didn’t find CP/M so it’s program
counter stopped at $FFED, reenabled 8502 and then go to sleep.</p>

<p>Z80 can be reactivated for running a script. The first thing is to set where is
code we want to run. We can let Z80 run it by setting a jump to that address
just after the NOP. For Z80, a jump is made by JP instruction which opcode is
C3.</p>

<pre><code class="language-Assembly">  LDA $C3
  STA $FFEE   // JP opcode set on FFEE
  LDA (lo-byte-address-of-z80-routine)
  STA $FFEF
  LDA (hi-byte-address-of-z80-routine)
  STA $FFF0
</code></pre>

<p>After this, 8502 can be activated by setting bit 0 fo MMUMCR ($D505).</p>

<p>Also Z80 code must be prepared for running: there are some instruction before
and some other at the end to correctly handle environment.</p>

<p>Before Z80 routine, some opcode must be provided:</p>
<pre><code class="language-Assembly">  LD A, 3Fh
  LD (FF00H),A
</code></pre>

<p>This is needed for Mmu configuration. After Z80 routine, some other opcode must be provided:</p>

<pre><code class="language-Assembly">  JP FFE0H
</code></pre>

<p>This tells Z80 to jump to FFE0, which contains, as seen before, some
instruction to disable Z80 and reactvate 8502.</p>

<p>Z80-8502 switch can be repeated many times because at the end of every Z80
code, Z80 program counter is set to $FFED so we always have the same
end situation.</p>

<h2 id="show-me-the-code">Show me the code</h2>

<pre><code class="language-Assembly">* = $2000
  lda #$c3      // Set JP opcode into $ffee
  sta $ffee
  lda #&lt;$3000   // Set JP address into $ffef (lo-byte)
  sta $ffef
  lda #&gt;$3000   // Set JP address into $fff0 (hi-byte)
  sta $fff0
</code></pre>

<pre><code class="language-Assembly">* = $3000
  .byte $3E, $3F        // LD A, #$3F   -- load up the #$3f byte, for mmu cr
  .byte $32, $00, $FF   // LD ($FF00),A -- set the mmu configuration
                        // register mirror with #$3f
  .byte $3E, $08        // LD A, #$08   -- load up the #$08 (H) byte
  .byte $32, $00, $04   // LD ($0400),A -- write on screen
  .byte $3C             // INC A
  .byte $32, $01, $04   // LD ($0401),A -- write on screen
  .byte $3E, $21        // LD A, #$21   -- load up the #$21 (!) byte
  .byte $32, $02, $04   // LD ($0402),A -- write on screen
  .byte $c3, $e0, $ff   // JP $FFE0 - jump to the bootlink routine in the
                        // Z-80 ROM, 8502 is switched on there.
</code></pre>

<p>This simple snippet, which can be run wit SYS 8192, will print “HI!” in the
top left position of the screen. This string will be print by Z80 and then
safely control will be granted to 8502.</p>

<h2 id="basic">Basic</h2>

<p>Z80-8502 switch can be achived also from Basic. On this Reddit resource
(https://www.reddit.com/r/c128/comments/9nxhcc/8502_z80_switchover_a_simple_example/),
you can switch from one processor to another with this simple Basic code.
It’s the same behavior, done with POKE:</p>

<pre><code class="language-Basic">10 bank 0
20 rem ffee c3 00 30 - jp 3000 (z80)
30 poke 65518,195
40 poke 65519,0
50 poke 65520,48
60 rem ffdc 58 - cli (8502)
70 poke 65500,88
80 rem ffdd 60 rts (8502)
90 poke 65501,96
100 for i=12288 to 12298
110 read a
120 poke i,a
130 s=s+a
140 next i
150 if s &lt;&gt; 1691 then print "Virhe Datoissa!": end: rem not clear this...
160 sys dec("ffd0")
170 goto 160
180 data 1, 32,208,237,120, 61
190 data 237,121,195,224,255
</code></pre>

<h2 id="references">References</h2>
<ul>
  <li>Starting sequence info on <a href="https://c128lib.github.io/Reference/StartupSequence">reference</a></li>
  <li>Mapping the Commodore 128</li>
  <li>Power Assembler instruction manual</li>
  <li>https://www.reddit.com/r/c128/comments/9nxhcc/8502_z80_switchover_a_simple_example/</li>
</ul>]]></content><author><name>Raffaele Intorcia</name><email>raffaele.intorcia@gmail.com</email></author><category term="8502-z80-switchover" /><category term="8502" /><category term="z80" /><category term="commodore-128" /><category term="assembly" /><summary type="html"><![CDATA[Italian version will come… Commodore C128 is a double 8-bit processor machine. it has: a MOS 8502 (derived from 6510 and 6502) which is used to run C128 Basic v7 mode and C64 Basic v2 mode a Zilog Z80 which is used to run CP/M. Commodore says that is’t like having 3 pc in one. Aside from commercial, 8502 and Z80 share all components of this machine and also share data bus and address bus. This sharing makes impossible to run simultaneously so a processor can run while the other is inactive. Booting process (from Mapping the Commodore 128) After power up, the Z80 microprocessor has control before the 8502 is allowed to take over. There are only a few signs of this: two short routines are copied into bank 0 RAM. One, at $FFD0-$FFDF, is an 8502 ML routine that surrenders control to the Z80; FFD0 SEI FFD1 LDA #$3E FFD3 STA $FF00 FFD6 LDA #$B0 FFD7 STA $D505 FFDB NOP FFDC JMP $1100 FFDF NOP the other, at $FFE0-$FFEF, is a Z80 ML routine that surrenders control to the 8502. FFE0 DI FFE1 LD A, 3EH FFE3 LD (FF00H), A FFE6 LD BC, D505H FFE9 LD A, B1H FFEB OUT (C),A FFED NOP FFEE RST 08H There are no routines in any of the 128 mode ROMs to perform this initialization. These routines have no use in 128 mode-they can be used only in CP/M mode-but they are recopied to block 0 during each reset. Bart van Leeuwen made some research and spent a lot of time about boot process and found some interesting information. I’ll copy from our info exchange on FB. Booting CP/M is always done from 128 mode. You can verify this: when powering-on (or resetting) a C128 with a CP/M boot disk inserted, you will get the BASIC V7 copyright message before CP/M starts. The 'trick' to this is not in the CP/M BIOS but in the boot record of a CP/M disk. So, even with a CP/M disk inserted, the machine will power-on/reset to Z80 mode first, do its copying to ram, and then always call the 'switch to 8502' routine it copied to ram. This in turn will suspend the Z80, and start the 8502. Because the 8502 has been reset, it will start reading the 6502 reset vector and start executing the C128 kernal. The kernal will check for a C64 cartridge, if none found, check for an autostart function rom (autostart byte == 1), and when none found, do the c128 kernal and basic initialization, after which phoenix will run. Phoenix first checks for function roms with an autostart byte &gt;0 and run it if found. When that returns, or none is found, it will read the first block of the drive at id 8, and check for a boot signature. The CP/M boot disk has a regular C128 boot signature, and some code which sets up the system to load CP/M, and then switches to the Z80. Reactivating Z80 (from Mapping the Commodore 128) Switching processors is not for the faint of heart. When you activate the Z80, it will begin executing instructions at whatever address is currently in its program counter registers. The address in those internal processor registers can’t be changed from 128 mode, so you’re stuck with having the Z80 take up wherever it left off when the system was switched to 128 mode. This address is usually $FFEE, the location following the one where 128 mode was activated at the end of the Z80’s reset routine. In block 0 RAM, that location is initialized with a Z80 instruction (RST1) to perform a warm start of CP/M mode. If you don’t have a valid Z80 machine language instruction there when you activate the Z80 (for example, if the system is in a memory configuration such as bank 15 where 128 Kernal ROM is seen at that address) you’ll probably experience an immediate system lockup. (from Power Assembler Instruction Manual) Bit 0 at $D505 (54533) controls the micro processor mode. If it is turned on then the 8502 becomes active; if it is off then the Z80 takes over. You can’t just poke it off. A little housekeeping is first in order: disable 8502 interrupts via SEI because you are going to switch to a memory configuration in which Kernal ROM is not visible. To do this, store a $3E (62) at $FF00 (the configuration register). This leaves I/O RAM intact but switches everything else to RAM 0. The Z80 PC register holds $FFED after 128 initialization. There is a NOP ($00) there. The first actual Z80 command goes at $FFEE. If you look through the monitor you will see a $CF there. This is an RST 8 opcode byte which will cause the Z80 to jump (ReSTart) to its own ROM routine at 0008. You do not want this. After moving some 8502 code into place at $3000, the Z80 would return control to the 8502. The 8502 wakes up exactly where it left off after you switched to the Z80. If you followed this switch with a NOP (lets not wake It up to fast) and then a JMP $3000 (like the operating system does) you would go into the 128’s boot CP/M routine. This is pretty useless from a programming standpoint, so don’t bother. Instead, put your own Z80 code at $FFEE. The last thing the U80 will have to do is to turn the 8500 back on. There are two ways to do this: LD A,$B1 LD ($D505),A This is inferior. There is a bleed through condition in the Z80 mode using this type of store. A $B1 will also be written to underlying RAM. Here is the proper way: LD BC,$D505 LD A,$B1 OUT (C),A Bleed through not occur using OUT storage and all I/O memory between $D000 and $DFFF can be written to. Exploiting So, this is the situation. Z80 started but didn’t find CP/M so it’s program counter stopped at $FFED, reenabled 8502 and then go to sleep. Z80 can be reactivated for running a script. The first thing is to set where is code we want to run. We can let Z80 run it by setting a jump to that address just after the NOP. For Z80, a jump is made by JP instruction which opcode is C3. LDA $C3 STA $FFEE // JP opcode set on FFEE LDA (lo-byte-address-of-z80-routine) STA $FFEF LDA (hi-byte-address-of-z80-routine) STA $FFF0 After this, 8502 can be activated by setting bit 0 fo MMUMCR ($D505). Also Z80 code must be prepared for running: there are some instruction before and some other at the end to correctly handle environment. Before Z80 routine, some opcode must be provided: LD A, 3Fh LD (FF00H),A This is needed for Mmu configuration. After Z80 routine, some other opcode must be provided: JP FFE0H This tells Z80 to jump to FFE0, which contains, as seen before, some instruction to disable Z80 and reactvate 8502. Z80-8502 switch can be repeated many times because at the end of every Z80 code, Z80 program counter is set to $FFED so we always have the same end situation. Show me the code * = $2000 lda #$c3 // Set JP opcode into $ffee sta $ffee lda #&lt;$3000 // Set JP address into $ffef (lo-byte) sta $ffef lda #&gt;$3000 // Set JP address into $fff0 (hi-byte) sta $fff0 * = $3000 .byte $3E, $3F // LD A, #$3F -- load up the #$3f byte, for mmu cr .byte $32, $00, $FF // LD ($FF00),A -- set the mmu configuration // register mirror with #$3f .byte $3E, $08 // LD A, #$08 -- load up the #$08 (H) byte .byte $32, $00, $04 // LD ($0400),A -- write on screen .byte $3C // INC A .byte $32, $01, $04 // LD ($0401),A -- write on screen .byte $3E, $21 // LD A, #$21 -- load up the #$21 (!) byte .byte $32, $02, $04 // LD ($0402),A -- write on screen .byte $c3, $e0, $ff // JP $FFE0 - jump to the bootlink routine in the // Z-80 ROM, 8502 is switched on there. This simple snippet, which can be run wit SYS 8192, will print “HI!” in the top left position of the screen. This string will be print by Z80 and then safely control will be granted to 8502. Basic Z80-8502 switch can be achived also from Basic. On this Reddit resource (https://www.reddit.com/r/c128/comments/9nxhcc/8502_z80_switchover_a_simple_example/), you can switch from one processor to another with this simple Basic code. It’s the same behavior, done with POKE: 10 bank 0 20 rem ffee c3 00 30 - jp 3000 (z80) 30 poke 65518,195 40 poke 65519,0 50 poke 65520,48 60 rem ffdc 58 - cli (8502) 70 poke 65500,88 80 rem ffdd 60 rts (8502) 90 poke 65501,96 100 for i=12288 to 12298 110 read a 120 poke i,a 130 s=s+a 140 next i 150 if s &lt;&gt; 1691 then print "Virhe Datoissa!": end: rem not clear this... 160 sys dec("ffd0") 170 goto 160 180 data 1, 32,208,237,120, 61 190 data 237,121,195,224,255 References Starting sequence info on reference Mapping the Commodore 128 Power Assembler instruction manual https://www.reddit.com/r/c128/comments/9nxhcc/8502_z80_switchover_a_simple_example/]]></summary></entry><entry><title type="html">Multi threading</title><link href="https://intoinside.github.io/2023/06/25/multithreading/" rel="alternate" type="text/html" title="Multi threading" /><published>2023-06-25T00:00:00+00:00</published><updated>2023-06-25T00:00:00+00:00</updated><id>https://intoinside.github.io/2023/06/25/multithreading</id><content type="html" xml:base="https://intoinside.github.io/2023/06/25/multithreading/"><![CDATA[<p>Multithread a 8 bit? Beh si, può sorprendere ma anche sul processore 6502 è possibile ottenere
una certa forma di multithreading. C’è qualche compromesso, ci sono forti limitazioni ma, si,
tecnicamente è possibile.</p>

<h2 id="show-me-the-code-quickly">Show me the code, quickly!</h2>
<p>Con lo snippet presente qui https://gist.github.com/intoinside/ff0d07e86685408c9b48ea8888e5cb4c
è possibile attivare un semplice sistema di multi threading.</p>

<p>La parte <strong>Entry</strong> inizializza la struttura, imposta lo stack e prepara
l’esecuzione del primo thread.</p>

<p>Successivamente viene definito il <strong>content_switch</strong> che viene invocato ad ogni
chiamata dell’IRQ e, agendo similmente a uno scheduler, decide il prossimo
thread da eseguire, predisponendone l’ambiente e sospendendo il precedente.</p>

<p>In seguito sono definiti i due thread.</p>

<p>Cominciamo intanto a dire che è un “finto” multithreading che rientra
nella categoria “interleaved” o “preemptive” (https://en.wikipedia.org/wiki/Temporal_multithreading).
Significa che non c’è mai più
di un blocco di codice in esecuzione ma la frequenza del passaggio da uno
all’altro dà l’illusione che ci sia un’esecuzione realmente concorrente. Non
potrebbe essere diversamente perché c’è un solo core di elaborazione.</p>

<p>Un altro scoglio è quello delle risorse, ne parliamo separatamente su due
fronti.</p>

<h3 id="memoria">Memoria</h3>
<p>Stiamo parlando pur sempre di un processore a 8 bit che gestisce fino a 64Kib
di ram e l’apporccio multithread prevede:</p>
<ul>
  <li>stack dedicato per ogni thread ovvero suddivisione dello stack esistente
tra tutti i thread da eseguire: la quantità di spazio per ogni thread che decresce
lineamente in proporzione al numero di thread presenti</li>
  <li>area di memoria disponibile per ogni thread</li>
</ul>

<h3 id="cpu">Cpu</h3>
<p>Il 6502, come noto, funziona a una velocità di 1 MHz (che raddoppiano nella
modalità FAST per il 8502 del C128). Che è pochissimo, non ci sarebbe bisogno di
dirlo.</p>

<p>Questa limitata quantità di cicli deve essere suddivisa tra più blocchi di codice
che si contendono il diritto di esecuzione. Inoltre, assieme alla mera esecuzione
del codice dei thread, c’è l’overhead della gestione dello scheduler, in quanto a
ogni rintocco dell’IRQ, lo scheduler deve valutare il prossimo thread da eseguire
e deve metterlo in condizione di partire (oltre a parcheggiare quello precedente).
Non è tantissimo ma comunque parliamo di qualche decina di cicli di clock.</p>

<h3 id="miscellaneous">Miscellaneous</h3>
<p>Ci sono inoltre tutte le altre risorse del sistema per le quali va decisa una
politica di gestione: accesso al disco, accesso ad aree di memoria
condivisa, uso di funzionalità del sistema (schermo, suono, joystick…).</p>

<h2 id="e-quindi">E quindi?</h2>
<p>Quindi, si, è possibile avere il multithreading anche sul C64/C128 ma gli scenari
d’uso sono fortemente limitati (se non annullati del tutto) dalle limitate risorse
complessive del sistema.</p>

<p>Ma comunque dal punto di vista emozionale, è veramente affascinante!</p>]]></content><author><name>Raffaele Intorcia</name><email>raffaele.intorcia@gmail.com</email></author><category term="multithreading" /><category term="commodore-128" /><category term="assembly" /><summary type="html"><![CDATA[Multithread a 8 bit? Beh si, può sorprendere ma anche sul processore 6502 è possibile ottenere una certa forma di multithreading. C’è qualche compromesso, ci sono forti limitazioni ma, si, tecnicamente è possibile. Show me the code, quickly! Con lo snippet presente qui https://gist.github.com/intoinside/ff0d07e86685408c9b48ea8888e5cb4c è possibile attivare un semplice sistema di multi threading. La parte Entry inizializza la struttura, imposta lo stack e prepara l’esecuzione del primo thread. Successivamente viene definito il content_switch che viene invocato ad ogni chiamata dell’IRQ e, agendo similmente a uno scheduler, decide il prossimo thread da eseguire, predisponendone l’ambiente e sospendendo il precedente. In seguito sono definiti i due thread. Cominciamo intanto a dire che è un “finto” multithreading che rientra nella categoria “interleaved” o “preemptive” (https://en.wikipedia.org/wiki/Temporal_multithreading). Significa che non c’è mai più di un blocco di codice in esecuzione ma la frequenza del passaggio da uno all’altro dà l’illusione che ci sia un’esecuzione realmente concorrente. Non potrebbe essere diversamente perché c’è un solo core di elaborazione. Un altro scoglio è quello delle risorse, ne parliamo separatamente su due fronti. Memoria Stiamo parlando pur sempre di un processore a 8 bit che gestisce fino a 64Kib di ram e l’apporccio multithread prevede: stack dedicato per ogni thread ovvero suddivisione dello stack esistente tra tutti i thread da eseguire: la quantità di spazio per ogni thread che decresce lineamente in proporzione al numero di thread presenti area di memoria disponibile per ogni thread Cpu Il 6502, come noto, funziona a una velocità di 1 MHz (che raddoppiano nella modalità FAST per il 8502 del C128). Che è pochissimo, non ci sarebbe bisogno di dirlo. Questa limitata quantità di cicli deve essere suddivisa tra più blocchi di codice che si contendono il diritto di esecuzione. Inoltre, assieme alla mera esecuzione del codice dei thread, c’è l’overhead della gestione dello scheduler, in quanto a ogni rintocco dell’IRQ, lo scheduler deve valutare il prossimo thread da eseguire e deve metterlo in condizione di partire (oltre a parcheggiare quello precedente). Non è tantissimo ma comunque parliamo di qualche decina di cicli di clock. Miscellaneous Ci sono inoltre tutte le altre risorse del sistema per le quali va decisa una politica di gestione: accesso al disco, accesso ad aree di memoria condivisa, uso di funzionalità del sistema (schermo, suono, joystick…). E quindi? Quindi, si, è possibile avere il multithreading anche sul C64/C128 ma gli scenari d’uso sono fortemente limitati (se non annullati del tutto) dalle limitate risorse complessive del sistema. Ma comunque dal punto di vista emozionale, è veramente affascinante!]]></summary></entry></feed>