git @ Cat's Eye Technologies JaC64 / master com / dreamfabric / jac64 / CIA.java
master

Tree @master (Download .tar.gz)

CIA.java @masterraw · history · blame

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
/**
 * This file is a part of JaC64 - a Java C64 Emulator
 * Main Developer: Joakim Eriksson (Dreamfabric.com)
 * Contact: joakime@sics.se
 * Web: http://www.dreamfabric.com/c64
 * ---------------------------------------------------
 */
package com.dreamfabric.jac64;


/**
 * CIA emulation for JaC64. 
 *
 * Created: Sat Jul 30 05:38:32 2005
 *
 * @author Joakim Eriksson
 * @version 1.0
 */
public class CIA {

    public static final boolean TIMER_DEBUG = false; //true;
  public static final boolean WRITE_DEBUG = false; //true;

  public static final int PRA = 0x00;
  public static final int PRB = 0x01;
  public static final int DDRA = 0x02;
  public static final int DDRB = 0x03;
  public static final int TIMALO = 0x04;
  public static final int TIMAHI = 0x05;
  public static final int TIMBLO = 0x06;
  public static final int TIMBHI = 0x07;
  public static final int TODTEN = 0x08;
  public static final int TODSEC = 0x09;
  public static final int TODMIN = 0x0a;
  public static final int TODHRS = 0x0b;
  public static final int SDR = 0x0c;
  public static final int ICR = 0x0d;
  public static final int CRA = 0x0e;
  public static final int CRB = 0x0f;

  CIATimer timerA;
  CIATimer timerB;

  int pra = 0;
  int prb = 0;
  int ddra = 0;
  int ddrb = 0;
  int tod10sec = 0;
  int todsec = 0;
  int todmin = 0;
  int todhour = 0;
  int sdr;
  
  // For the CPU to read (contains status)
  int ciaicrRead;
  int ciaie = 0; // interrupt enable
  
  // B-Div is set if mode (bit 5,6 of CIACRB) = 10
  public static final int TIMER_B_DIV_MASK = 0x60;
  public static final int TIMER_B_DIV_VAL = 0x40;

  public long nextCIAUpdate = 0;

  private MOS6510Core cpu;
  private int offset;

  public int serialFake = 0;
  private ExtChip chips;

  public TimeEvent todEvent = new TimeEvent(0) {
      public void execute(long cycle) {
        time = time + 100000; // Approx a tenth of a second...
        int tmp = (tod10sec & 0x0f) + 1;
        tod10sec = tmp % 10;
        if (tmp > 9) {
          // Maxval == 0x59
          tmp = (todsec & 0x7f) + 1;
          if ((tmp & 0x0f) > 9)
            tmp += 0x06;
          if (tmp > 0x59)
            tmp = 0;
          todsec = tmp;
          // Wrapped seconds...
          // Minutes inc - max 0x59
          if (tmp == 0) {
            tmp = (todmin & 0x7f) + 1;
            if ((tmp & 0x0f) > 9)
              tmp += 0x06;
            if (tmp > 0x59)
              tmp = 0;
            todmin = tmp;

            // Hours, max 0x12
            if (tmp == 0) {
              tmp = (todhour & 0x1f) + 1;
              if ((tmp & 0x0f) > 9)
                tmp += 0x06;

              if (tmp > 0x11)
                tmp = 0;
              // how is hour? 1  - 12  or 0 - 11 ??
              todhour = tmp;
            }
          }
        }

        // TODO: fix alarms and latches !!
        // Since this should continue run, just reschedule...
//        System.out.println("TOD ticked..." + (todhour>>4) + (todhour & 0xf) + ":" + 
//              (todmin>>4) + (todmin&0xf) + ":" + (todsec>>4) + (todsec&0xf));
        cpu.scheduler.addEvent(this);
      }
  };
  
  /**
   * Creates a new <code>CIA</code> instance.
   *
   */
  public CIA(MOS6510Core cpu, int offset, ExtChip chips) {
    this.cpu = cpu;
    this.offset = offset;
    this.chips = chips;
    timerA = new CIATimer("TimerA", 1, true, null);
    timerB = new CIATimer("TimerB", 2, false, timerA);
    timerA.otherTimer = timerB;
    todEvent.time = cpu.cycles + 10000;
    cpu.scheduler.addEvent(todEvent);
  }

  public void reset() {
    ciaicrRead = 0;
    ciaie = 0;

    timerA.reset();
    timerB.reset();
    tod10sec = 0;
    todsec = 0;
    todmin = 0;
    todhour = 0;

    updateInterrupts();
  }

  public String ciaID() {
    return offset == 0x10c00 ? "CIA 1" : "CIA 2";
  }

  public int performRead(int address, long cycles) {
    address -= offset;
    switch(address) {
    case DDRA:
      return ddra;
    case DDRB:
      return ddrb;
    case PRA:
      return (pra | ~ddra) & 0xff;
    case PRB:
      int data = (prb | ~ddrb) & 0xff;
      if ((timerA.cr & 0x02) > 0) {
        data &= 0xbf;
        if ((timerA.cr & 0x04) > 0) {
          data |= timerA.flipflop ? 0x40 : 0;
        } else {
          data |= timerA.underflow ? 0x40 : 0;          
        }
      }
      if ((timerB.cr & 0x02) > 0) {
        data &= 0x7f;
        if ((timerB.cr & 0x04) > 0) {
          data |= timerB.flipflop ? 0x80 : 0;
        } else {
          data |= timerB.underflow ? 0x80 : 0;          
        }
      }
      return data;
    case TIMALO:
//      System.out.println(ciaID() + " getTimerA LO, timer = " + timerA.getTimer(cycles));
      return timerA.getTimer(cycles) & 0xff;
    case TIMAHI:
      return timerA.getTimer(cycles) >> 8;
    case TIMBLO:
//      System.out.println(ciaID() + " getTimerB LO, timer = " + timerB.getTimer(cycles));
      return timerB.getTimer(cycles) & 0xff;
    case TIMBHI:
      return timerB.getTimer(cycles) & 0xff;
    case TODTEN:
      return tod10sec;
    case TODSEC:
      return todsec;
    case TODMIN:
      return todmin;
    case TODHRS:
      return todhour;
    case SDR:
      return sdr;
    case CRA:
      return timerA.cr;
    case CRB:
      return timerB.cr;
    case ICR:
      // Clear interrupt register (flags)!
      if (TIMER_DEBUG && offset == 0x10d00) println("clear Interrupt register, was: " +
          Hex.hex2(ciaicrRead));
      int val = ciaicrRead;
      ciaicrRead = 0;

      // Latch off the IRQ/NMI immediately!!!
      updateInterrupts();

      return val;
      default:
        return 0xff;
    }
  }

  public void performWrite(int address, int data, long cycles) {
    address -= offset;

    if (WRITE_DEBUG) println(ciaID() + " Write to :" +
        Integer.toString(address, 16) + " = " +
        Integer.toString(data, 16));

    switch (address) {
    //monitor.println("Set Keyboard:" + data);
    case DDRA:
      ddra = data;
      break;
    case DDRB:
      ddrb = data;
      break;
    case PRA:
      pra = data;
      break;
    case PRB:
      prb = data;
      break;
    case TIMALO:
      // Update latch value
      timerA.latch = (timerA.latch & 0xff00) | data;
      break;
    case TIMAHI:
      timerA.latch = (timerA.latch & 0xff) | (data << 8);
      if (timerA.state == CIATimer.STOP) {
        timerA.timer = timerA.latch; 
      }
      if (TIMER_DEBUG && offset == 0x10d00) println(ciaID() + ": Timer A latch: " +
          timerA.latch + ": " + cycles);
      break;
    case TIMBLO:
      timerB.latch = (timerB.latch & 0xff00) | data;
      break;
    case TIMBHI:
      timerB.latch = (timerB.latch & 0xff) | (data << 8);
      if (timerB.state == CIATimer.STOP) {
        timerB.timer = timerB.latch; 
      }

      if (TIMER_DEBUG && offset == 0x10d00) println(ciaID() + ": Timer B latch: " +
          timerB.latch + ": " + cycles);
      break;
    case TODTEN:
      tod10sec = data;
      break;
    case TODSEC:
      todsec = data;
      break;
    case TODMIN:
      todmin = data;
      break;
    case TODHRS:
      todhour = data;
      break;
    case ICR:      // dc0d - CIAICR - CIA Interrupt Control Register
      boolean val = (data & 0x80) != 0;
      if (val) {
        // Set the 1 bits if val = 1
        ciaie |= data & 0x7f;
      } else {
        // Clear the 1 bits
        ciaie &= ~data;
      }
      // Trigger interrupts if needed...
      updateInterrupts();
      System.out.println(ciaID() + " ====> IE = " + ciaie);
      break;
    case CRA:
      timerA.writeCR(cycles, data);
      timerA.countCycles = (data & 0x20) == 0;
      break;

    case CRB:
      timerB.writeCR(cycles, data);
      timerB.countCycles = (data & 0x60) == 0;
      timerB.countUnderflow = (data & 0x60) == 0x40;
      break;
    }
  }

  private void updateInterrupts() {
    if ((ciaie & ciaicrRead & 0x1f) != 0) {
      ciaicrRead |= 0x80;
      // Trigger the IRQ/NMI immediately!!!
      if (offset == 0x10c00) {
//    	  cpu.log("CIA 1  *** TRIGGERING CIA TIMER!!!: " +
//    			  ciaie + " " + chips.getIRQFlags() + " " + cpu.getIRQLow());
    	  chips.setIRQ(ExtChip.CIA_TIMER_IRQ);
      } else {
        chips.setNMI(ExtChip.CIA_TIMER_NMI);
      }
    } else {
      if (offset == 0x10c00) {
//	System.out.println("*** CLEARING CIA TIMER!!!");
        chips.clearIRQ(ExtChip.CIA_TIMER_IRQ);
      } else {
        chips.clearNMI(ExtChip.CIA_TIMER_NMI);
      }
    }
  }

  private void println(String s) {
    System.out.println(ciaID() + ": " + s);
  }

  public void printStatus() {
    System.out.println("--------------------------");
    println(" status");
    System.out.println("Timer A state: " + timerA.state);
    System.out.println("Timer A next trigger: " + timerA.nextZero);
    System.out.println("CIA CRA: " + Hex.hex2(timerA.cr) + " => " +
        (((timerA.cr & 0x08) == 0) ?
            "cont" : "one-shot"));
    //    System.out.println("Timer A Interrupt: " + timerATrigg);
    System.out.println("Timer A Latch: " + timerA.latch);
    System.out.println("Timer B state: " + timerB.state);
    System.out.println("Timer B next trigger: " + timerB.nextZero);
    System.out.println("CIA CRB: " + Hex.hex2(timerA.cr) + " => " +
        (((timerB.cr & 0x08) == 0) ?
            "cont" : "one-shot"));
    //    System.out.println("Timer B Interrupt: " + timerBTrigg);
    System.out.println("Timer B Latch: " + timerB.latch);
    System.out.println("--------------------------");
  }


  // A timer class for handling the Timer state machines
  // The CIATimer is inspired by the CIA Timer State Machine in the
  // Frodo emulator
  private class CIATimer {

    // The states of the timer
    private static final int STOP = 0;
    private static final int WAIT = 1;
    private static final int LOAD_STOP = 2;
    private static final int LOAD_COUNT = 3;
    private static final int LOAD_WAIT_COUNT = 5;
    private static final int COUNT = 6;
    private static final int COUNT_STOP = 7;

    // If timer is connected...
    CIATimer otherTimer;

    int state = STOP;
    // The latch for this timer
    int latch = 0;
    int timer = 0;

    // When is an update needed for this timer?
    long nextUpdate = 0;
    long nextZero = 0;
    long lastLatch = 0;

    boolean interruptNext = false;
    boolean underflow = false;
    boolean flipflop = false;

    boolean countCycles = false;
    boolean countUnderflow = false;

    TimeEvent updateEvent = new TimeEvent(0) {
      public void execute(long cycles) {
        doUpdate(cycles);
        if (state != STOP) {
//	    System.out.println(ciaID() + " Adding Timer update event at " + cycles +
//			       " with time: " + nextUpdate + " state: " + state);
          cpu.scheduler.addEvent(this, nextUpdate);
        }
      }
    };
    
    int writeCR = -1;
    int cr = 0;
    String id;
    int iflag;
    boolean updateOther;

    CIATimer(String id, int flag, boolean uo, CIATimer other) {
      this.id = id;
      this.otherTimer = other;
      this.iflag = flag;
      updateOther = uo;
    }

    private void reset() {
      latch = 0xffff;
      timer = 0xffff;
      countUnderflow = false;
      flipflop = false;
      state = STOP;
      nextZero = 0;
      nextUpdate = 0;
      writeCR = -1;
      cpu.scheduler.removeEvent(updateEvent);
    }

    private int getTimer(long cycles) {
      if (state != COUNT) return timer;
      int t = (int) (nextZero - cycles);
      if (t < 0) {
        // Unexpected underflow...
        t = 0;
      }
      timer = t;
      return t;
    }

    private void loadTimer(long cycles) {
      timer = latch;
      nextZero = cycles + latch;
 
      if (TIMER_DEBUG && offset == 0x10d00) {
        System.out.println(ciaID() + ": " + id + " - timer loaded at "
            + cycles + " with: " + latch + " diff " +
            (cycles - lastLatch));
        lastLatch = cycles;
      }
    }

    private void triggerInterrupt(long cycles) {
      if (TIMER_DEBUG && offset == 0x10d00)
        System.out.println(ciaID() + ": " + id + " - trigger interrupt at: "
            + cycles + " nextZero: " + nextZero +
            " nextUpdate: " + nextUpdate);
      interruptNext = true;
      underflow = true;
      flipflop = !flipflop;
      // One shot?
      if ((cr & 8) != 0) {
        cr &= 0xfe;
        writeCR &= 0xfe;
        state = LOAD_STOP;
      } else {
        state = LOAD_COUNT;
      } // TODO: fix update of tb.
//      if (updateOther) {
//        otherTimer.update(cycles);
//      }
    }

    void writeCR(long cycles, int data) {
      writeCR = data;
      if (nextUpdate > cycles + 1 || !updateEvent.scheduled) {
        nextUpdate = cycles + 1;
        cpu.scheduler.addEvent(updateEvent, nextUpdate);
      }
    }


    public void doUpdate(long cycles) {
      if (nextUpdate == 0) {
        nextUpdate = cycles;
        nextZero = cycles;
      }
      if (cycles == nextUpdate) {
        // If the call is on "spot" then just do it!
        update(cycles);
      } else {
        // As long as cycles is larger than next update, just continue
        // call it!
        while (cycles >= nextUpdate) {
          System.out.println(ciaID() + ": " + id +
              " ** update at: " + cycles + " expected: " + nextUpdate + " state: " + state);
          update(nextUpdate);
        }
      }
    }

    // maybe only update when "needed" and when registers read???
    // NEED TO CHECK IF WE ARE CALLED WHEN EXPECTED!!!
    // No - since BA Low will cause no updates of IO units..??
    public void update(long cycles) {
      // set a default
      underflow = false;
      nextUpdate = cycles + 1;
      if (interruptNext) {
        ciaicrRead |= iflag;
        interruptNext = false;
        // Trigg the stuff...
        updateInterrupts();
      }
      // Update timer...
      getTimer(cycles);
      // Timer state machine!
      switch (state) {
      case STOP:
        // Nothing...
        break;
      case WAIT:
        // Go to count next time!
        state = COUNT;
        break;
      case LOAD_STOP:
        loadTimer(cycles);
        // Stop timer!
        state = STOP;
        break;
      case LOAD_COUNT:
        loadTimer(cycles);
        state = COUNT;
        break;
      case LOAD_WAIT_COUNT:
        if (nextZero == cycles + 1) {
          triggerInterrupt(cycles);
        }
        state = WAIT;
        loadTimer(cycles);
        break;
      case COUNT_STOP:
        if (!countUnderflow) {
          timer = (int) (cycles - nextZero);
          if (timer < 0) timer = 0;
        }
        state = STOP;
        break;
      case COUNT:
        // perform count - this assumes that we are counting
        // cycles!!!
        if (countUnderflow) {
          if (otherTimer.underflow)
            timer--;
          if (timer <= 0) {
            triggerInterrupt(cycles);
          }
        } else {
          // TODO: check this!!!
          if (cycles >= nextZero && state != STOP) {
            state = LOAD_COUNT;
            triggerInterrupt(cycles);
          } else {
            // We got here too early... what now?
            nextUpdate = nextZero;
          }
        }
        break;
      }

      // Delayed write of CR - is that only for timers?
      if (writeCR != -1) {
        delayedWrite(cycles);
        writeCR = -1;
      }
    }

    void delayedWrite(long cycles) {
      nextUpdate = cycles + 1;
      switch(state) {
      case STOP:
      case LOAD_STOP:
        if ((writeCR & 1) > 0) {
          // Start timer
          if ((writeCR & 0x10) > 0) {
            // force load
            state = LOAD_WAIT_COUNT;
          } else {
            // Just count!
            loadTimer(cycles);
            state = WAIT;
          }
        } else {
          if ((writeCR & 0x10) > 0) {
            state = LOAD_STOP;
          }
        }
        break;
      case COUNT:
        if ((writeCR & 1) > 0) {
          if ((writeCR & 0x10) > 0) {
            // force load
            state = LOAD_WAIT_COUNT;
          } // Otherwise just continue counting!
        } else {
          if ((writeCR & 0x10) > 0) {
            state = LOAD_STOP;
          } else {
            state = COUNT_STOP;
          }
        }
        break;
      case LOAD_COUNT:
      case WAIT:
        if ((writeCR & 1) > 0) {
          // Start timer
          if ((writeCR & 8) > 0) {
            // one-shot
            writeCR = writeCR & 0xfe;
            state = STOP;
          } else if ((writeCR & 0x10) > 0) {
            state = LOAD_WAIT_COUNT;
          } // Otherwise just continue counting!
        } else {
          state = COUNT_STOP;
        }
        break;
      }
      cr = writeCR & 0xef;
    }
  }
}