xref: /openbmc/qemu/hw/misc/mac_via.c (revision 6e7d8c5f)
1 /*
2  * QEMU m68k Macintosh VIA device support
3  *
4  * Copyright (c) 2011-2018 Laurent Vivier
5  * Copyright (c) 2018 Mark Cave-Ayland
6  *
7  * Some parts from hw/misc/macio/cuda.c
8  *
9  * Copyright (c) 2004-2007 Fabrice Bellard
10  * Copyright (c) 2007 Jocelyn Mayer
11  *
12  * some parts from linux-2.6.29, arch/m68k/include/asm/mac_via.h
13  *
14  * This work is licensed under the terms of the GNU GPL, version 2 or later.
15  * See the COPYING file in the top-level directory.
16  */
17 
18 #include "qemu/osdep.h"
19 #include "exec/address-spaces.h"
20 #include "migration/vmstate.h"
21 #include "hw/sysbus.h"
22 #include "hw/irq.h"
23 #include "qemu/timer.h"
24 #include "hw/misc/mac_via.h"
25 #include "hw/misc/mos6522.h"
26 #include "hw/input/adb.h"
27 #include "sysemu/runstate.h"
28 #include "qapi/error.h"
29 #include "qemu/cutils.h"
30 #include "hw/qdev-properties.h"
31 #include "hw/qdev-properties-system.h"
32 #include "sysemu/block-backend.h"
33 #include "sysemu/rtc.h"
34 #include "trace.h"
35 #include "qemu/log.h"
36 
37 /*
38  * VIAs: There are two in every machine
39  */
40 
41 /*
42  * Not all of these are true post MacII I think.
43  * CSA: probably the ones CHRP marks as 'unused' change purposes
44  * when the IWM becomes the SWIM.
45  * http://www.rs6000.ibm.com/resource/technology/chrpio/via5.mak.html
46  * ftp://ftp.austin.ibm.com/pub/technology/spec/chrp/inwork/CHRP_IORef_1.0.pdf
47  *
48  * also, http://developer.apple.com/technotes/hw/hw_09.html claims the
49  * following changes for IIfx:
50  * VIA1A_vSccWrReq not available and that VIA1A_vSync has moved to an IOP.
51  * Also, "All of the functionality of VIA2 has been moved to other chips".
52  */
53 
54 #define VIA1A_vSccWrReq 0x80   /*
55                                 * SCC write. (input)
56                                 * [CHRP] SCC WREQ: Reflects the state of the
57                                 * Wait/Request pins from the SCC.
58                                 * [Macintosh Family Hardware]
59                                 * as CHRP on SE/30,II,IIx,IIcx,IIci.
60                                 * on IIfx, "0 means an active request"
61                                 */
62 #define VIA1A_vRev8     0x40   /*
63                                 * Revision 8 board ???
64                                 * [CHRP] En WaitReqB: Lets the WaitReq_L
65                                 * signal from port B of the SCC appear on
66                                 * the PA7 input pin. Output.
67                                 * [Macintosh Family] On the SE/30, this
68                                 * is the bit to flip screen buffers.
69                                 * 0=alternate, 1=main.
70                                 * on II,IIx,IIcx,IIci,IIfx this is a bit
71                                 * for Rev ID. 0=II,IIx, 1=IIcx,IIci,IIfx
72                                 */
73 #define VIA1A_vHeadSel  0x20   /*
74                                 * Head select for IWM.
75                                 * [CHRP] unused.
76                                 * [Macintosh Family] "Floppy disk
77                                 * state-control line SEL" on all but IIfx
78                                 */
79 #define VIA1A_vOverlay  0x10   /*
80                                 * [Macintosh Family] On SE/30,II,IIx,IIcx
81                                 * this bit enables the "Overlay" address
82                                 * map in the address decoders as it is on
83                                 * reset for mapping the ROM over the reset
84                                 * vector. 1=use overlay map.
85                                 * On the IIci,IIfx it is another bit of the
86                                 * CPU ID: 0=normal IIci, 1=IIci with parity
87                                 * feature or IIfx.
88                                 * [CHRP] En WaitReqA: Lets the WaitReq_L
89                                 * signal from port A of the SCC appear
90                                 * on the PA7 input pin (CHRP). Output.
91                                 * [MkLinux] "Drive Select"
92                                 *  (with 0x20 being 'disk head select')
93                                 */
94 #define VIA1A_vSync     0x08   /*
95                                 * [CHRP] Sync Modem: modem clock select:
96                                 * 1: select the external serial clock to
97                                 *    drive the SCC's /RTxCA pin.
98                                 * 0: Select the 3.6864MHz clock to drive
99                                 *    the SCC cell.
100                                 * [Macintosh Family] Correct on all but IIfx
101                                 */
102 
103 /*
104  * Macintosh Family Hardware sez: bits 0-2 of VIA1A are volume control
105  * on Macs which had the PWM sound hardware.  Reserved on newer models.
106  * On IIci,IIfx, bits 1-2 are the rest of the CPU ID:
107  * bit 2: 1=IIci, 0=IIfx
108  * bit 1: 1 on both IIci and IIfx.
109  * MkLinux sez bit 0 is 'burnin flag' in this case.
110  * CHRP sez: VIA1A bits 0-2 and 5 are 'unused': if programmed as
111  * inputs, these bits will read 0.
112  */
113 #define VIA1A_vVolume   0x07    /* Audio volume mask for PWM */
114 #define VIA1A_CPUID0    0x02    /* CPU id bit 0 on RBV, others */
115 #define VIA1A_CPUID1    0x04    /* CPU id bit 0 on RBV, others */
116 #define VIA1A_CPUID2    0x10    /* CPU id bit 0 on RBV, others */
117 #define VIA1A_CPUID3    0x40    /* CPU id bit 0 on RBV, others */
118 #define VIA1A_CPUID_MASK (VIA1A_CPUID0 | VIA1A_CPUID1 | \
119                           VIA1A_CPUID2 | VIA1A_CPUID3)
120 #define VIA1A_CPUID_Q800 (VIA1A_CPUID0 | VIA1A_CPUID2)
121 
122 /*
123  * Info on VIA1B is from Macintosh Family Hardware & MkLinux.
124  * CHRP offers no info.
125  */
126 #define VIA1B_vSound   0x80    /*
127                                 * Sound enable (for compatibility with
128                                 * PWM hardware) 0=enabled.
129                                 * Also, on IIci w/parity, shows parity error
130                                 * 0=error, 1=OK.
131                                 */
132 #define VIA1B_vMystery 0x40    /*
133                                 * On IIci, parity enable. 0=enabled,1=disabled
134                                 * On SE/30, vertical sync interrupt enable.
135                                 * 0=enabled. This vSync interrupt shows up
136                                 * as a slot $E interrupt.
137                                 * On Quadra 800 this bit toggles A/UX mode which
138                                 * configures the glue logic to deliver some IRQs
139                                 * at different levels compared to a classic
140                                 * Mac.
141                                 */
142 #define VIA1B_vADBS2   0x20    /* ADB state input bit 1 (unused on IIfx) */
143 #define VIA1B_vADBS1   0x10    /* ADB state input bit 0 (unused on IIfx) */
144 #define VIA1B_vADBInt  0x08    /* ADB interrupt 0=interrupt (unused on IIfx)*/
145 #define VIA1B_vRTCEnb  0x04    /* Enable Real time clock. 0=enabled. */
146 #define VIA1B_vRTCClk  0x02    /* Real time clock serial-clock line. */
147 #define VIA1B_vRTCData 0x01    /* Real time clock serial-data line. */
148 
149 /*
150  *    VIA2 A register is the interrupt lines raised off the nubus
151  *    slots.
152  *      The below info is from 'Macintosh Family Hardware.'
153  *      MkLinux calls the 'IIci internal video IRQ' below the 'RBV slot 0 irq.'
154  *      It also notes that the slot $9 IRQ is the 'Ethernet IRQ' and
155  *      defines the 'Video IRQ' as 0x40 for the 'EVR' VIA work-alike.
156  *      Perhaps OSS uses vRAM1 and vRAM2 for ADB.
157  */
158 
159 #define VIA2A_vRAM1    0x80    /* RAM size bit 1 (IIci: reserved) */
160 #define VIA2A_vRAM0    0x40    /* RAM size bit 0 (IIci: internal video IRQ) */
161 #define VIA2A_vIRQE    0x20    /* IRQ from slot $E */
162 #define VIA2A_vIRQD    0x10    /* IRQ from slot $D */
163 #define VIA2A_vIRQC    0x08    /* IRQ from slot $C */
164 #define VIA2A_vIRQB    0x04    /* IRQ from slot $B */
165 #define VIA2A_vIRQA    0x02    /* IRQ from slot $A */
166 #define VIA2A_vIRQ9    0x01    /* IRQ from slot $9 */
167 
168 /*
169  * RAM size bits decoded as follows:
170  * bit1 bit0  size of ICs in bank A
171  *  0    0    256 kbit
172  *  0    1    1 Mbit
173  *  1    0    4 Mbit
174  *  1    1   16 Mbit
175  */
176 
177 /*
178  *    Register B has the fun stuff in it
179  */
180 
181 #define VIA2B_vVBL    0x80    /*
182                                * VBL output to VIA1 (60.15Hz) driven by
183                                * timer T1.
184                                * on IIci, parity test: 0=test mode.
185                                * [MkLinux] RBV_PARODD: 1=odd,0=even.
186                                */
187 #define VIA2B_vSndJck 0x40    /*
188                                * External sound jack status.
189                                * 0=plug is inserted.  On SE/30, always 0
190                                */
191 #define VIA2B_vTfr0   0x20    /* Transfer mode bit 0 ack from NuBus */
192 #define VIA2B_vTfr1   0x10    /* Transfer mode bit 1 ack from NuBus */
193 #define VIA2B_vMode32 0x08    /*
194                                * 24/32bit switch - doubles as cache flush
195                                * on II, AMU/PMMU control.
196                                *   if AMU, 0=24bit to 32bit translation
197                                *   if PMMU, 1=PMMU is accessing page table.
198                                * on SE/30 tied low.
199                                * on IIx,IIcx,IIfx, unused.
200                                * on IIci/RBV, cache control. 0=flush cache.
201                                */
202 #define VIA2B_vPower  0x04   /*
203                               * Power off, 0=shut off power.
204                               * on SE/30 this signal sent to PDS card.
205                               */
206 #define VIA2B_vBusLk  0x02   /*
207                               * Lock NuBus transactions, 0=locked.
208                               * on SE/30 sent to PDS card.
209                               */
210 #define VIA2B_vCDis   0x01   /*
211                               * Cache control. On IIci, 1=disable cache card
212                               * on others, 0=disable processor's instruction
213                               * and data caches.
214                               */
215 
216 /* interrupt flags */
217 
218 #define IRQ_SET         0x80
219 
220 /* common */
221 
222 #define VIA_IRQ_TIMER1      0x40
223 #define VIA_IRQ_TIMER2      0x20
224 
225 /*
226  * Apple sez: http://developer.apple.com/technotes/ov/ov_04.html
227  * Another example of a valid function that has no ROM support is the use
228  * of the alternate video page for page-flipping animation. Since there
229  * is no ROM call to flip pages, it is necessary to go play with the
230  * right bit in the VIA chip (6522 Versatile Interface Adapter).
231  * [CSA: don't know which one this is, but it's one of 'em!]
232  */
233 
234 /*
235  *    6522 registers - see databook.
236  * CSA: Assignments for VIA1 confirmed from CHRP spec.
237  */
238 
239 /* partial address decode.  0xYYXX : XX part for RBV, YY part for VIA */
240 /* Note: 15 VIA regs, 8 RBV regs */
241 
242 #define vBufB    0x0000  /* [VIA/RBV]  Register B */
243 #define vBufAH   0x0200  /* [VIA only] Buffer A, with handshake. DON'T USE! */
244 #define vDirB    0x0400  /* [VIA only] Data Direction Register B. */
245 #define vDirA    0x0600  /* [VIA only] Data Direction Register A. */
246 #define vT1CL    0x0800  /* [VIA only] Timer one counter low. */
247 #define vT1CH    0x0a00  /* [VIA only] Timer one counter high. */
248 #define vT1LL    0x0c00  /* [VIA only] Timer one latches low. */
249 #define vT1LH    0x0e00  /* [VIA only] Timer one latches high. */
250 #define vT2CL    0x1000  /* [VIA only] Timer two counter low. */
251 #define vT2CH    0x1200  /* [VIA only] Timer two counter high. */
252 #define vSR      0x1400  /* [VIA only] Shift register. */
253 #define vACR     0x1600  /* [VIA only] Auxiliary control register. */
254 #define vPCR     0x1800  /* [VIA only] Peripheral control register. */
255                          /*
256                           *           CHRP sez never ever to *write* this.
257                           *            Mac family says never to *change* this.
258                           * In fact we need to initialize it once at start.
259                           */
260 #define vIFR     0x1a00  /* [VIA/RBV]  Interrupt flag register. */
261 #define vIER     0x1c00  /* [VIA/RBV]  Interrupt enable register. */
262 #define vBufA    0x1e00  /* [VIA/RBV] register A (no handshake) */
263 
264 /* from linux 2.6 drivers/macintosh/via-macii.c */
265 
266 /* Bits in ACR */
267 
268 #define VIA1ACR_vShiftCtrl         0x1c        /* Shift register control bits */
269 #define VIA1ACR_vShiftExtClk       0x0c        /* Shift on external clock */
270 #define VIA1ACR_vShiftOut          0x10        /* Shift out if 1 */
271 
272 /*
273  * Apple Macintosh Family Hardware Refenece
274  * Table 19-10 ADB transaction states
275  */
276 
277 #define ADB_STATE_NEW       0
278 #define ADB_STATE_EVEN      1
279 #define ADB_STATE_ODD       2
280 #define ADB_STATE_IDLE      3
281 
282 #define VIA1B_vADB_StateMask    (VIA1B_vADBS1 | VIA1B_vADBS2)
283 #define VIA1B_vADB_StateShift   4
284 
285 #define VIA_TIMER_FREQ (783360)
286 #define VIA_ADB_POLL_FREQ 50 /* XXX: not real */
287 
288 /*
289  * Guide to the Macintosh Family Hardware ch. 12 "Displays" p. 401 gives the
290  * precise 60Hz interrupt frequency as ~60.15Hz with a period of 16625.8 us
291  */
292 #define VIA_60HZ_TIMER_PERIOD_NS   16625800
293 
294 /* VIA returns time offset from Jan 1, 1904, not 1970 */
295 #define RTC_OFFSET 2082844800
296 
297 enum {
298     REG_0,
299     REG_1,
300     REG_2,
301     REG_3,
302     REG_TEST,
303     REG_WPROTECT,
304     REG_PRAM_ADDR,
305     REG_PRAM_ADDR_LAST = REG_PRAM_ADDR + 19,
306     REG_PRAM_SECT,
307     REG_PRAM_SECT_LAST = REG_PRAM_SECT + 7,
308     REG_INVALID,
309     REG_EMPTY = 0xff,
310 };
311 
312 static void via1_sixty_hz_update(MOS6522Q800VIA1State *v1s)
313 {
314     /* 60 Hz irq */
315     v1s->next_sixty_hz = (qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) +
316                           VIA_60HZ_TIMER_PERIOD_NS) /
317                           VIA_60HZ_TIMER_PERIOD_NS * VIA_60HZ_TIMER_PERIOD_NS;
318     timer_mod(v1s->sixty_hz_timer, v1s->next_sixty_hz);
319 }
320 
321 static void via1_one_second_update(MOS6522Q800VIA1State *v1s)
322 {
323     v1s->next_second = (qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL) + 1000) /
324                        1000 * 1000;
325     timer_mod(v1s->one_second_timer, v1s->next_second);
326 }
327 
328 static void via1_sixty_hz(void *opaque)
329 {
330     MOS6522Q800VIA1State *v1s = opaque;
331     MOS6522State *s = MOS6522(v1s);
332     qemu_irq irq = qdev_get_gpio_in(DEVICE(s), VIA1_IRQ_60HZ_BIT);
333 
334     /* Negative edge trigger */
335     qemu_irq_lower(irq);
336     qemu_irq_raise(irq);
337 
338     via1_sixty_hz_update(v1s);
339 }
340 
341 static void via1_one_second(void *opaque)
342 {
343     MOS6522Q800VIA1State *v1s = opaque;
344     MOS6522State *s = MOS6522(v1s);
345     qemu_irq irq = qdev_get_gpio_in(DEVICE(s), VIA1_IRQ_ONE_SECOND_BIT);
346 
347     /* Negative edge trigger */
348     qemu_irq_lower(irq);
349     qemu_irq_raise(irq);
350 
351     via1_one_second_update(v1s);
352 }
353 
354 
355 static void pram_update(MOS6522Q800VIA1State *v1s)
356 {
357     if (v1s->blk) {
358         if (blk_pwrite(v1s->blk, 0, sizeof(v1s->PRAM), v1s->PRAM, 0) < 0) {
359             qemu_log("pram_update: cannot write to file\n");
360         }
361     }
362 }
363 
364 /*
365  * RTC Commands
366  *
367  * Command byte    Register addressed by the command
368  *
369  * z00x0001        Seconds register 0 (lowest-order byte)
370  * z00x0101        Seconds register 1
371  * z00x1001        Seconds register 2
372  * z00x1101        Seconds register 3 (highest-order byte)
373  * 00110001        Test register (write-only)
374  * 00110101        Write-Protect Register (write-only)
375  * z010aa01        RAM address 100aa ($10-$13) (first 20 bytes only)
376  * z1aaaa01        RAM address 0aaaa ($00-$0F) (first 20 bytes only)
377  * z0111aaa        Extended memory designator and sector number
378  *
379  * For a read request, z=1, for a write z=0
380  * The letter x indicates don't care
381  * The letter a indicates bits whose value depend on what parameter
382  * RAM byte you want to address
383  */
384 static int via1_rtc_compact_cmd(uint8_t value)
385 {
386     uint8_t read = value & 0x80;
387 
388     value &= 0x7f;
389 
390     /* the last 2 bits of a command byte must always be 0b01 ... */
391     if ((value & 0x78) == 0x38) {
392         /* except for the extended memory designator */
393         return read | (REG_PRAM_SECT + (value & 0x07));
394     }
395     if ((value & 0x03) == 0x01) {
396         value >>= 2;
397         if ((value & 0x18) == 0) {
398             /* seconds registers */
399             return read | (REG_0 + (value & 0x03));
400         } else if ((value == 0x0c) && !read) {
401             return REG_TEST;
402         } else if ((value == 0x0d) && !read) {
403             return REG_WPROTECT;
404         } else if ((value & 0x1c) == 0x08) {
405             /* RAM address 0x10 to 0x13 */
406             return read | (REG_PRAM_ADDR + 0x10 + (value & 0x03));
407         } else if ((value & 0x10) == 0x10) {
408             /* RAM address 0x00 to 0x0f */
409             return read | (REG_PRAM_ADDR + (value & 0x0f));
410         }
411     }
412     return REG_INVALID;
413 }
414 
415 static void via1_rtc_update(MOS6522Q800VIA1State *v1s)
416 {
417     MOS6522State *s = MOS6522(v1s);
418     int cmd, sector, addr;
419     uint32_t time;
420 
421     if (s->b & VIA1B_vRTCEnb) {
422         return;
423     }
424 
425     if (s->dirb & VIA1B_vRTCData) {
426         /* send bits to the RTC */
427         if (!(v1s->last_b & VIA1B_vRTCClk) && (s->b & VIA1B_vRTCClk)) {
428             v1s->data_out <<= 1;
429             v1s->data_out |= s->b & VIA1B_vRTCData;
430             v1s->data_out_cnt++;
431         }
432         trace_via1_rtc_update_data_out(v1s->data_out_cnt, v1s->data_out);
433     } else {
434         trace_via1_rtc_update_data_in(v1s->data_in_cnt, v1s->data_in);
435         /* receive bits from the RTC */
436         if ((v1s->last_b & VIA1B_vRTCClk) &&
437             !(s->b & VIA1B_vRTCClk) &&
438             v1s->data_in_cnt) {
439             s->b = (s->b & ~VIA1B_vRTCData) |
440                    ((v1s->data_in >> 7) & VIA1B_vRTCData);
441             v1s->data_in <<= 1;
442             v1s->data_in_cnt--;
443         }
444         return;
445     }
446 
447     if (v1s->data_out_cnt != 8) {
448         return;
449     }
450 
451     v1s->data_out_cnt = 0;
452 
453     trace_via1_rtc_internal_status(v1s->cmd, v1s->alt, v1s->data_out);
454     /* first byte: it's a command */
455     if (v1s->cmd == REG_EMPTY) {
456 
457         cmd = via1_rtc_compact_cmd(v1s->data_out);
458         trace_via1_rtc_internal_cmd(cmd);
459 
460         if (cmd == REG_INVALID) {
461             trace_via1_rtc_cmd_invalid(v1s->data_out);
462             return;
463         }
464 
465         if (cmd & 0x80) { /* this is a read command */
466             switch (cmd & 0x7f) {
467             case REG_0...REG_3: /* seconds registers */
468                 /*
469                  * register 0 is lowest-order byte
470                  * register 3 is highest-order byte
471                  */
472 
473                 time = v1s->tick_offset + (qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL)
474                        / NANOSECONDS_PER_SECOND);
475                 trace_via1_rtc_internal_time(time);
476                 v1s->data_in = (time >> ((cmd & 0x03) << 3)) & 0xff;
477                 v1s->data_in_cnt = 8;
478                 trace_via1_rtc_cmd_seconds_read((cmd & 0x7f) - REG_0,
479                                                 v1s->data_in);
480                 break;
481             case REG_PRAM_ADDR...REG_PRAM_ADDR_LAST:
482                 /* PRAM address 0x00 -> 0x13 */
483                 v1s->data_in = v1s->PRAM[(cmd & 0x7f) - REG_PRAM_ADDR];
484                 v1s->data_in_cnt = 8;
485                 trace_via1_rtc_cmd_pram_read((cmd & 0x7f) - REG_PRAM_ADDR,
486                                              v1s->data_in);
487                 break;
488             case REG_PRAM_SECT...REG_PRAM_SECT_LAST:
489                 /*
490                  * extended memory designator and sector number
491                  * the only two-byte read command
492                  */
493                 trace_via1_rtc_internal_set_cmd(cmd);
494                 v1s->cmd = cmd;
495                 break;
496             default:
497                 g_assert_not_reached();
498             }
499             return;
500         }
501 
502         /* this is a write command, needs a parameter */
503         if (cmd == REG_WPROTECT || !v1s->wprotect) {
504             trace_via1_rtc_internal_set_cmd(cmd);
505             v1s->cmd = cmd;
506         } else {
507             trace_via1_rtc_internal_ignore_cmd(cmd);
508         }
509         return;
510     }
511 
512     /* second byte: it's a parameter */
513     if (v1s->alt == REG_EMPTY) {
514         switch (v1s->cmd & 0x7f) {
515         case REG_0...REG_3: /* seconds register */
516             /* FIXME */
517             trace_via1_rtc_cmd_seconds_write(v1s->cmd - REG_0, v1s->data_out);
518             v1s->cmd = REG_EMPTY;
519             break;
520         case REG_TEST:
521             /* device control: nothing to do */
522             trace_via1_rtc_cmd_test_write(v1s->data_out);
523             v1s->cmd = REG_EMPTY;
524             break;
525         case REG_WPROTECT:
526             /* Write Protect register */
527             trace_via1_rtc_cmd_wprotect_write(v1s->data_out);
528             v1s->wprotect = !!(v1s->data_out & 0x80);
529             v1s->cmd = REG_EMPTY;
530             break;
531         case REG_PRAM_ADDR...REG_PRAM_ADDR_LAST:
532             /* PRAM address 0x00 -> 0x13 */
533             trace_via1_rtc_cmd_pram_write(v1s->cmd - REG_PRAM_ADDR,
534                                           v1s->data_out);
535             v1s->PRAM[v1s->cmd - REG_PRAM_ADDR] = v1s->data_out;
536             pram_update(v1s);
537             v1s->cmd = REG_EMPTY;
538             break;
539         case REG_PRAM_SECT...REG_PRAM_SECT_LAST:
540             addr = (v1s->data_out >> 2) & 0x1f;
541             sector = (v1s->cmd & 0x7f) - REG_PRAM_SECT;
542             if (v1s->cmd & 0x80) {
543                 /* it's a read */
544                 v1s->data_in = v1s->PRAM[sector * 32 + addr];
545                 v1s->data_in_cnt = 8;
546                 trace_via1_rtc_cmd_pram_sect_read(sector, addr,
547                                                   sector * 32 + addr,
548                                                   v1s->data_in);
549                 v1s->cmd = REG_EMPTY;
550             } else {
551                 /* it's a write, we need one more parameter */
552                 trace_via1_rtc_internal_set_alt(addr, sector, addr);
553                 v1s->alt = addr;
554             }
555             break;
556         default:
557             g_assert_not_reached();
558         }
559         return;
560     }
561 
562     /* third byte: it's the data of a REG_PRAM_SECT write */
563     g_assert(REG_PRAM_SECT <= v1s->cmd && v1s->cmd <= REG_PRAM_SECT_LAST);
564     sector = v1s->cmd - REG_PRAM_SECT;
565     v1s->PRAM[sector * 32 + v1s->alt] = v1s->data_out;
566     pram_update(v1s);
567     trace_via1_rtc_cmd_pram_sect_write(sector, v1s->alt, sector * 32 + v1s->alt,
568                                        v1s->data_out);
569     v1s->alt = REG_EMPTY;
570     v1s->cmd = REG_EMPTY;
571 }
572 
573 static void adb_via_poll(void *opaque)
574 {
575     MOS6522Q800VIA1State *v1s = MOS6522_Q800_VIA1(opaque);
576     MOS6522State *s = MOS6522(v1s);
577     ADBBusState *adb_bus = &v1s->adb_bus;
578     uint8_t obuf[9];
579     uint8_t *data = &s->sr;
580     int olen;
581 
582     /*
583      * Setting vADBInt below indicates that an autopoll reply has been
584      * received, however we must block autopoll until the point where
585      * the entire reply has been read back to the host
586      */
587     adb_autopoll_block(adb_bus);
588 
589     if (v1s->adb_data_in_size > 0 && v1s->adb_data_in_index == 0) {
590         /*
591          * For older Linux kernels that switch to IDLE mode after sending the
592          * ADB command, detect if there is an existing response and return that
593          * as a "fake" autopoll reply or bus timeout accordingly
594          */
595         *data = v1s->adb_data_out[0];
596         olen = v1s->adb_data_in_size;
597 
598         s->b &= ~VIA1B_vADBInt;
599         qemu_irq_raise(v1s->adb_data_ready);
600     } else {
601         /*
602          * Otherwise poll as normal
603          */
604         v1s->adb_data_in_index = 0;
605         v1s->adb_data_out_index = 0;
606         olen = adb_poll(adb_bus, obuf, adb_bus->autopoll_mask);
607 
608         if (olen > 0) {
609             /* Autopoll response */
610             *data = obuf[0];
611             olen--;
612             memcpy(v1s->adb_data_in, &obuf[1], olen);
613             v1s->adb_data_in_size = olen;
614 
615             s->b &= ~VIA1B_vADBInt;
616             qemu_irq_raise(v1s->adb_data_ready);
617         } else {
618             *data = v1s->adb_autopoll_cmd;
619             obuf[0] = 0xff;
620             obuf[1] = 0xff;
621             olen = 2;
622 
623             memcpy(v1s->adb_data_in, obuf, olen);
624             v1s->adb_data_in_size = olen;
625 
626             s->b &= ~VIA1B_vADBInt;
627             qemu_irq_raise(v1s->adb_data_ready);
628         }
629     }
630 
631     trace_via1_adb_poll(*data, (s->b & VIA1B_vADBInt) ? "+" : "-",
632                         adb_bus->status, v1s->adb_data_in_index, olen);
633 }
634 
635 static int adb_via_send_len(uint8_t data)
636 {
637     /* Determine the send length from the given ADB command */
638     uint8_t cmd = data & 0xc;
639     uint8_t reg = data & 0x3;
640 
641     switch (cmd) {
642     case 0x8:
643         /* Listen command */
644         switch (reg) {
645         case 2:
646             /* Register 2 is only used for the keyboard */
647             return 3;
648         case 3:
649             /*
650              * Fortunately our devices only implement writes
651              * to register 3 which is fixed at 2 bytes
652              */
653             return 3;
654         default:
655             qemu_log_mask(LOG_UNIMP, "ADB unknown length for register %d\n",
656                           reg);
657             return 1;
658         }
659     default:
660         /* Talk, BusReset */
661         return 1;
662     }
663 }
664 
665 static void adb_via_send(MOS6522Q800VIA1State *v1s, int state, uint8_t data)
666 {
667     MOS6522State *ms = MOS6522(v1s);
668     ADBBusState *adb_bus = &v1s->adb_bus;
669     uint16_t autopoll_mask;
670 
671     switch (state) {
672     case ADB_STATE_NEW:
673         /*
674          * Command byte: vADBInt tells host autopoll data already present
675          * in VIA shift register and ADB transceiver
676          */
677         adb_autopoll_block(adb_bus);
678 
679         if (adb_bus->status & ADB_STATUS_POLLREPLY) {
680             /* Tell the host the existing data is from autopoll */
681             ms->b &= ~VIA1B_vADBInt;
682         } else {
683             ms->b |= VIA1B_vADBInt;
684             v1s->adb_data_out_index = 0;
685             v1s->adb_data_out[v1s->adb_data_out_index++] = data;
686         }
687 
688         trace_via1_adb_send(" NEW", data, (ms->b & VIA1B_vADBInt) ? "+" : "-");
689         qemu_irq_raise(v1s->adb_data_ready);
690         break;
691 
692     case ADB_STATE_EVEN:
693     case ADB_STATE_ODD:
694         ms->b |= VIA1B_vADBInt;
695         v1s->adb_data_out[v1s->adb_data_out_index++] = data;
696 
697         trace_via1_adb_send(state == ADB_STATE_EVEN ? "EVEN" : " ODD",
698                             data, (ms->b & VIA1B_vADBInt) ? "+" : "-");
699         qemu_irq_raise(v1s->adb_data_ready);
700         break;
701 
702     case ADB_STATE_IDLE:
703         ms->b |= VIA1B_vADBInt;
704         adb_autopoll_unblock(adb_bus);
705 
706         trace_via1_adb_send("IDLE", data,
707                             (ms->b & VIA1B_vADBInt) ? "+" : "-");
708 
709         return;
710     }
711 
712     /* If the command is complete, execute it */
713     if (v1s->adb_data_out_index == adb_via_send_len(v1s->adb_data_out[0])) {
714         v1s->adb_data_in_size = adb_request(adb_bus, v1s->adb_data_in,
715                                             v1s->adb_data_out,
716                                             v1s->adb_data_out_index);
717         v1s->adb_data_in_index = 0;
718 
719         if (adb_bus->status & ADB_STATUS_BUSTIMEOUT) {
720             /*
721              * Bus timeout (but allow first EVEN and ODD byte to indicate
722              * timeout via vADBInt and SRQ status)
723              */
724             v1s->adb_data_in[0] = 0xff;
725             v1s->adb_data_in[1] = 0xff;
726             v1s->adb_data_in_size = 2;
727         }
728 
729         /*
730          * If last command is TALK, store it for use by autopoll and adjust
731          * the autopoll mask accordingly
732          */
733         if ((v1s->adb_data_out[0] & 0xc) == 0xc) {
734             v1s->adb_autopoll_cmd = v1s->adb_data_out[0];
735 
736             autopoll_mask = 1 << (v1s->adb_autopoll_cmd >> 4);
737             adb_set_autopoll_mask(adb_bus, autopoll_mask);
738         }
739     }
740 }
741 
742 static void adb_via_receive(MOS6522Q800VIA1State *v1s, int state, uint8_t *data)
743 {
744     MOS6522State *ms = MOS6522(v1s);
745     ADBBusState *adb_bus = &v1s->adb_bus;
746     uint16_t pending;
747 
748     switch (state) {
749     case ADB_STATE_NEW:
750         ms->b |= VIA1B_vADBInt;
751         return;
752 
753     case ADB_STATE_IDLE:
754         ms->b |= VIA1B_vADBInt;
755         adb_autopoll_unblock(adb_bus);
756 
757         trace_via1_adb_receive("IDLE", *data,
758                         (ms->b & VIA1B_vADBInt) ? "+" : "-", adb_bus->status,
759                         v1s->adb_data_in_index, v1s->adb_data_in_size);
760 
761         break;
762 
763     case ADB_STATE_EVEN:
764     case ADB_STATE_ODD:
765         switch (v1s->adb_data_in_index) {
766         case 0:
767             /* First EVEN byte: vADBInt indicates bus timeout */
768             *data = v1s->adb_data_in[v1s->adb_data_in_index];
769             if (adb_bus->status & ADB_STATUS_BUSTIMEOUT) {
770                 ms->b &= ~VIA1B_vADBInt;
771             } else {
772                 ms->b |= VIA1B_vADBInt;
773             }
774 
775             trace_via1_adb_receive(state == ADB_STATE_EVEN ? "EVEN" : " ODD",
776                                    *data, (ms->b & VIA1B_vADBInt) ? "+" : "-",
777                                    adb_bus->status, v1s->adb_data_in_index,
778                                    v1s->adb_data_in_size);
779 
780             v1s->adb_data_in_index++;
781             break;
782 
783         case 1:
784             /* First ODD byte: vADBInt indicates SRQ */
785             *data = v1s->adb_data_in[v1s->adb_data_in_index];
786             pending = adb_bus->pending & ~(1 << (v1s->adb_autopoll_cmd >> 4));
787             if (pending) {
788                 ms->b &= ~VIA1B_vADBInt;
789             } else {
790                 ms->b |= VIA1B_vADBInt;
791             }
792 
793             trace_via1_adb_receive(state == ADB_STATE_EVEN ? "EVEN" : " ODD",
794                                    *data, (ms->b & VIA1B_vADBInt) ? "+" : "-",
795                                    adb_bus->status, v1s->adb_data_in_index,
796                                    v1s->adb_data_in_size);
797 
798             v1s->adb_data_in_index++;
799             break;
800 
801         default:
802             /*
803              * Otherwise vADBInt indicates end of data. Note that Linux
804              * specifically checks for the sequence 0x0 0xff to confirm the
805              * end of the poll reply, so provide these extra bytes below to
806              * keep it happy
807              */
808             if (v1s->adb_data_in_index < v1s->adb_data_in_size) {
809                 /* Next data byte */
810                 *data = v1s->adb_data_in[v1s->adb_data_in_index];
811                 ms->b |= VIA1B_vADBInt;
812             } else if (v1s->adb_data_in_index == v1s->adb_data_in_size) {
813                 if (adb_bus->status & ADB_STATUS_BUSTIMEOUT) {
814                     /* Bus timeout (no more data) */
815                     *data = 0xff;
816                 } else {
817                     /* Return 0x0 after reply */
818                     *data = 0;
819                 }
820                 ms->b &= ~VIA1B_vADBInt;
821             } else {
822                 /* Bus timeout (no more data) */
823                 *data = 0xff;
824                 ms->b &= ~VIA1B_vADBInt;
825                 adb_bus->status = 0;
826                 adb_autopoll_unblock(adb_bus);
827             }
828 
829             trace_via1_adb_receive(state == ADB_STATE_EVEN ? "EVEN" : " ODD",
830                                    *data, (ms->b & VIA1B_vADBInt) ? "+" : "-",
831                                    adb_bus->status, v1s->adb_data_in_index,
832                                    v1s->adb_data_in_size);
833 
834             if (v1s->adb_data_in_index <= v1s->adb_data_in_size) {
835                 v1s->adb_data_in_index++;
836             }
837             break;
838         }
839 
840         qemu_irq_raise(v1s->adb_data_ready);
841         break;
842     }
843 }
844 
845 static void via1_adb_update(MOS6522Q800VIA1State *v1s)
846 {
847     MOS6522State *s = MOS6522(v1s);
848     int oldstate, state;
849 
850     oldstate = (v1s->last_b & VIA1B_vADB_StateMask) >> VIA1B_vADB_StateShift;
851     state = (s->b & VIA1B_vADB_StateMask) >> VIA1B_vADB_StateShift;
852 
853     if (state != oldstate) {
854         if (s->acr & VIA1ACR_vShiftOut) {
855             /* output mode */
856             adb_via_send(v1s, state, s->sr);
857         } else {
858             /* input mode */
859             adb_via_receive(v1s, state, &s->sr);
860         }
861     }
862 }
863 
864 static void via1_auxmode_update(MOS6522Q800VIA1State *v1s)
865 {
866     MOS6522State *s = MOS6522(v1s);
867     int oldirq, irq;
868 
869     oldirq = (v1s->last_b & VIA1B_vMystery) ? 1 : 0;
870     irq = (s->b & VIA1B_vMystery) ? 1 : 0;
871 
872     /* Check to see if the A/UX mode bit has changed */
873     if (irq != oldirq) {
874         trace_via1_auxmode(irq);
875         qemu_set_irq(v1s->auxmode_irq, irq);
876 
877         /*
878          * Clear the ADB interrupt. MacOS can leave VIA1B_vADBInt asserted
879          * (low) if a poll sequence doesn't complete before NetBSD disables
880          * interrupts upon boot. Fortunately NetBSD switches to the so-called
881          * "A/UX" interrupt mode after it initialises, so we can use this as
882          * a convenient place to clear the ADB interrupt for now.
883          */
884         s->b |= VIA1B_vADBInt;
885     }
886 }
887 
888 /*
889  * Addresses and real values for TimeDBRA/TimeSCCB to allow timer calibration
890  * to succeed (NOTE: both values have been multiplied by 3 to cope with the
891  * speed of QEMU execution on a modern host
892  */
893 #define MACOS_TIMEDBRA        0xd00
894 #define MACOS_TIMESCCB        0xd02
895 
896 #define MACOS_TIMEDBRA_VALUE  (0x2a00 * 3)
897 #define MACOS_TIMESCCB_VALUE  (0x079d * 3)
898 
899 static bool via1_is_toolbox_timer_calibrated(void)
900 {
901     /*
902      * Indicate whether the MacOS toolbox has been calibrated by checking
903      * for the value of our magic constants
904      */
905     uint16_t timedbra = lduw_be_phys(&address_space_memory, MACOS_TIMEDBRA);
906     uint16_t timesccdb = lduw_be_phys(&address_space_memory, MACOS_TIMESCCB);
907 
908     return (timedbra == MACOS_TIMEDBRA_VALUE &&
909             timesccdb == MACOS_TIMESCCB_VALUE);
910 }
911 
912 static void via1_timer_calibration_hack(MOS6522Q800VIA1State *v1s, int addr,
913                                         uint64_t val, int size)
914 {
915     /*
916      * Work around timer calibration to ensure we that we have non-zero and
917      * known good values for TIMEDRBA and TIMESCCDB.
918      *
919      * This works by attempting to detect the reset and calibration sequence
920      * of writes to VIA1
921      */
922     int old_timer_hack_state = v1s->timer_hack_state;
923 
924     switch (v1s->timer_hack_state) {
925     case 0:
926         if (addr == VIA_REG_PCR && val == 0x22) {
927             /* VIA_REG_PCR: configure VIA1 edge triggering */
928             v1s->timer_hack_state = 1;
929         }
930         break;
931     case 1:
932         if (addr == VIA_REG_T2CL && val == 0xc) {
933             /* VIA_REG_T2CL: low byte of 1ms counter */
934             if (!via1_is_toolbox_timer_calibrated()) {
935                 v1s->timer_hack_state = 2;
936             } else {
937                 v1s->timer_hack_state = 0;
938             }
939         }
940         break;
941     case 2:
942         if (addr == VIA_REG_T2CH && val == 0x3) {
943             /*
944              * VIA_REG_T2CH: high byte of 1ms counter (very likely at the
945              * start of SETUPTIMEK)
946              */
947             if (!via1_is_toolbox_timer_calibrated()) {
948                 v1s->timer_hack_state = 3;
949             } else {
950                 v1s->timer_hack_state = 0;
951             }
952         }
953         break;
954     case 3:
955         if (addr == VIA_REG_IER && val == 0x20) {
956             /*
957              * VIA_REG_IER: update at end of SETUPTIMEK
958              *
959              * Timer calibration has finished: unfortunately the values in
960              * TIMEDBRA (0xd00) and TIMESCCDB (0xd02) are so far out they
961              * cause divide by zero errors.
962              *
963              * Update them with values obtained from a real Q800 but with
964              * a x3 scaling factor which seems to work well
965              */
966             stw_be_phys(&address_space_memory, MACOS_TIMEDBRA,
967                         MACOS_TIMEDBRA_VALUE);
968             stw_be_phys(&address_space_memory, MACOS_TIMESCCB,
969                         MACOS_TIMESCCB_VALUE);
970 
971             v1s->timer_hack_state = 4;
972         }
973         break;
974     case 4:
975         /*
976          * This is the normal post-calibration timer state: we should
977          * generally remain here unless we detect the A/UX calibration
978          * loop, or a write to VIA_REG_PCR suggesting a reset
979          */
980         if (addr == VIA_REG_PCR && val == 0x22) {
981             /* Looks like there has been a reset? */
982             v1s->timer_hack_state = 1;
983         }
984 
985         if (addr == VIA_REG_T2CL && val == 0xf0) {
986             /* VIA_REG_T2CL: low byte of counter (A/UX) */
987             v1s->timer_hack_state = 5;
988         }
989         break;
990     case 5:
991         if (addr == VIA_REG_T2CH && val == 0x3c) {
992             /*
993              * VIA_REG_T2CH: high byte of counter (A/UX). We are now extremely
994              * likely to be in the A/UX timer calibration routine, so move to
995              * the next state where we enable the calibration hack.
996              */
997             v1s->timer_hack_state = 6;
998         } else if ((addr == VIA_REG_IER && val == 0x20) ||
999                    addr == VIA_REG_T2CH) {
1000             /* We're doing something else with the timer, not calibration */
1001             v1s->timer_hack_state = 0;
1002         }
1003         break;
1004     case 6:
1005         if ((addr == VIA_REG_IER && val == 0x20) || addr == VIA_REG_T2CH) {
1006             /* End of A/UX timer calibration routine, or another write */
1007             v1s->timer_hack_state = 7;
1008         } else {
1009             v1s->timer_hack_state = 0;
1010         }
1011         break;
1012     case 7:
1013         /*
1014          * This is the normal post-calibration timer state once both the
1015          * MacOS toolbox and A/UX have been calibrated, until we see a write
1016          * to VIA_REG_PCR to suggest a reset
1017          */
1018         if (addr == VIA_REG_PCR && val == 0x22) {
1019             /* Looks like there has been a reset? */
1020             v1s->timer_hack_state = 1;
1021         }
1022         break;
1023     default:
1024         g_assert_not_reached();
1025     }
1026 
1027     if (old_timer_hack_state != v1s->timer_hack_state) {
1028         trace_via1_timer_hack_state(v1s->timer_hack_state);
1029     }
1030 }
1031 
1032 static uint64_t mos6522_q800_via1_read(void *opaque, hwaddr addr, unsigned size)
1033 {
1034     MOS6522Q800VIA1State *s = MOS6522_Q800_VIA1(opaque);
1035     MOS6522State *ms = MOS6522(s);
1036     uint64_t ret;
1037     int64_t now;
1038 
1039     addr = (addr >> 9) & 0xf;
1040     ret = mos6522_read(ms, addr, size);
1041     switch (addr) {
1042     case VIA_REG_A:
1043     case VIA_REG_ANH:
1044         /* Quadra 800 Id */
1045         ret = (ret & ~VIA1A_CPUID_MASK) | VIA1A_CPUID_Q800;
1046         break;
1047     case VIA_REG_T2CH:
1048         if (s->timer_hack_state == 6) {
1049             /*
1050              * The A/UX timer calibration loop runs continuously until 2
1051              * consecutive iterations differ by at least 0x492 timer ticks.
1052              * Modern hosts execute the timer calibration loop so fast that
1053              * this situation never occurs causing a hang on boot. Use a
1054              * similar method to Shoebill which is to randomly add 0x500 to
1055              * the T2 counter value during calibration to enable it to
1056              * eventually succeed.
1057              */
1058             now = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
1059             if (now & 1) {
1060                 ret += 0x5;
1061             }
1062         }
1063         break;
1064     }
1065     return ret;
1066 }
1067 
1068 static void mos6522_q800_via1_write(void *opaque, hwaddr addr, uint64_t val,
1069                                     unsigned size)
1070 {
1071     MOS6522Q800VIA1State *v1s = MOS6522_Q800_VIA1(opaque);
1072     MOS6522State *ms = MOS6522(v1s);
1073     int oldstate, state;
1074     int oldsr = ms->sr;
1075 
1076     addr = (addr >> 9) & 0xf;
1077 
1078     via1_timer_calibration_hack(v1s, addr, val, size);
1079 
1080     mos6522_write(ms, addr, val, size);
1081 
1082     switch (addr) {
1083     case VIA_REG_B:
1084         via1_rtc_update(v1s);
1085         via1_adb_update(v1s);
1086         via1_auxmode_update(v1s);
1087 
1088         v1s->last_b = ms->b;
1089         break;
1090 
1091     case VIA_REG_SR:
1092         {
1093             /*
1094              * NetBSD assumes it can send its first ADB command after sending
1095              * the ADB_BUSRESET command in ADB_STATE_NEW without changing the
1096              * state back to ADB_STATE_IDLE first as detailed in the ADB
1097              * protocol.
1098              *
1099              * Add a workaround to detect this condition at the start of ADB
1100              * enumeration and send the next command written to SR after a
1101              * ADB_BUSRESET onto the bus regardless, even if we don't detect a
1102              * state transition to ADB_STATE_NEW.
1103              *
1104              * Note that in my tests the NetBSD state machine takes one ADB
1105              * operation to recover which means the probe for an ADB device at
1106              * address 1 always fails. However since the first device is at
1107              * address 2 then this will work fine, without having to come up
1108              * with a more complicated and invasive solution.
1109              */
1110             oldstate = (v1s->last_b & VIA1B_vADB_StateMask) >>
1111                        VIA1B_vADB_StateShift;
1112             state = (ms->b & VIA1B_vADB_StateMask) >> VIA1B_vADB_StateShift;
1113 
1114             if (oldstate == ADB_STATE_NEW && state == ADB_STATE_NEW &&
1115                     (ms->acr & VIA1ACR_vShiftOut) &&
1116                     oldsr == 0 /* ADB_BUSRESET */) {
1117                 trace_via1_adb_netbsd_enum_hack();
1118                 adb_via_send(v1s, state, ms->sr);
1119             }
1120         }
1121         break;
1122     }
1123 }
1124 
1125 static const MemoryRegionOps mos6522_q800_via1_ops = {
1126     .read = mos6522_q800_via1_read,
1127     .write = mos6522_q800_via1_write,
1128     .endianness = DEVICE_BIG_ENDIAN,
1129     .valid = {
1130         .min_access_size = 1,
1131         .max_access_size = 4,
1132     },
1133 };
1134 
1135 static uint64_t mos6522_q800_via2_read(void *opaque, hwaddr addr, unsigned size)
1136 {
1137     MOS6522Q800VIA2State *s = MOS6522_Q800_VIA2(opaque);
1138     MOS6522State *ms = MOS6522(s);
1139     uint64_t val;
1140 
1141     addr = (addr >> 9) & 0xf;
1142     val = mos6522_read(ms, addr, size);
1143 
1144     switch (addr) {
1145     case VIA_REG_IFR:
1146         /*
1147          * On a Q800 an emulated VIA2 is integrated into the onboard logic. The
1148          * expectation of most OSs is that the DRQ bit is live, rather than
1149          * latched as it would be on a real VIA so do the same here.
1150          *
1151          * Note: DRQ is negative edge triggered
1152          */
1153         val &= ~VIA2_IRQ_SCSI_DATA;
1154         val |= (~ms->last_irq_levels & VIA2_IRQ_SCSI_DATA);
1155         break;
1156     }
1157 
1158     return val;
1159 }
1160 
1161 static void mos6522_q800_via2_write(void *opaque, hwaddr addr, uint64_t val,
1162                                     unsigned size)
1163 {
1164     MOS6522Q800VIA2State *s = MOS6522_Q800_VIA2(opaque);
1165     MOS6522State *ms = MOS6522(s);
1166 
1167     addr = (addr >> 9) & 0xf;
1168     mos6522_write(ms, addr, val, size);
1169 }
1170 
1171 static const MemoryRegionOps mos6522_q800_via2_ops = {
1172     .read = mos6522_q800_via2_read,
1173     .write = mos6522_q800_via2_write,
1174     .endianness = DEVICE_BIG_ENDIAN,
1175     .valid = {
1176         .min_access_size = 1,
1177         .max_access_size = 4,
1178     },
1179 };
1180 
1181 static void via1_postload_update_cb(void *opaque, bool running, RunState state)
1182 {
1183     MOS6522Q800VIA1State *v1s = MOS6522_Q800_VIA1(opaque);
1184 
1185     qemu_del_vm_change_state_handler(v1s->vmstate);
1186     v1s->vmstate = NULL;
1187 
1188     pram_update(v1s);
1189 }
1190 
1191 static int via1_post_load(void *opaque, int version_id)
1192 {
1193     MOS6522Q800VIA1State *v1s = MOS6522_Q800_VIA1(opaque);
1194 
1195     if (v1s->blk) {
1196         v1s->vmstate = qemu_add_vm_change_state_handler(
1197                            via1_postload_update_cb, v1s);
1198     }
1199 
1200     return 0;
1201 }
1202 
1203 /* VIA 1 */
1204 static void mos6522_q800_via1_reset_hold(Object *obj, ResetType type)
1205 {
1206     MOS6522Q800VIA1State *v1s = MOS6522_Q800_VIA1(obj);
1207     MOS6522State *ms = MOS6522(v1s);
1208     MOS6522DeviceClass *mdc = MOS6522_GET_CLASS(ms);
1209     ADBBusState *adb_bus = &v1s->adb_bus;
1210 
1211     if (mdc->parent_phases.hold) {
1212         mdc->parent_phases.hold(obj, type);
1213     }
1214 
1215     ms->timers[0].frequency = VIA_TIMER_FREQ;
1216     ms->timers[1].frequency = VIA_TIMER_FREQ;
1217 
1218     ms->b = VIA1B_vADB_StateMask | VIA1B_vADBInt | VIA1B_vRTCEnb;
1219 
1220     /* ADB/RTC */
1221     adb_set_autopoll_enabled(adb_bus, true);
1222     v1s->cmd = REG_EMPTY;
1223     v1s->alt = REG_EMPTY;
1224 
1225     /* Timer calibration hack */
1226     v1s->timer_hack_state = 0;
1227 }
1228 
1229 static void mos6522_q800_via1_realize(DeviceState *dev, Error **errp)
1230 {
1231     MOS6522Q800VIA1State *v1s = MOS6522_Q800_VIA1(dev);
1232     ADBBusState *adb_bus = &v1s->adb_bus;
1233     struct tm tm;
1234     int ret;
1235 
1236     v1s->one_second_timer = timer_new_ms(QEMU_CLOCK_VIRTUAL, via1_one_second,
1237                                          v1s);
1238     via1_one_second_update(v1s);
1239     v1s->sixty_hz_timer = timer_new_ns(QEMU_CLOCK_VIRTUAL, via1_sixty_hz,
1240                                        v1s);
1241     via1_sixty_hz_update(v1s);
1242 
1243     qemu_get_timedate(&tm, 0);
1244     v1s->tick_offset = (uint32_t)mktimegm(&tm) + RTC_OFFSET;
1245 
1246     adb_register_autopoll_callback(adb_bus, adb_via_poll, v1s);
1247     v1s->adb_data_ready = qdev_get_gpio_in(dev, VIA1_IRQ_ADB_READY_BIT);
1248 
1249     if (v1s->blk) {
1250         int64_t len = blk_getlength(v1s->blk);
1251         if (len < 0) {
1252             error_setg_errno(errp, -len,
1253                              "could not get length of backing image");
1254             return;
1255         }
1256         ret = blk_set_perm(v1s->blk,
1257                            BLK_PERM_CONSISTENT_READ | BLK_PERM_WRITE,
1258                            BLK_PERM_ALL, errp);
1259         if (ret < 0) {
1260             return;
1261         }
1262 
1263         ret = blk_pread(v1s->blk, 0, sizeof(v1s->PRAM), v1s->PRAM, 0);
1264         if (ret < 0) {
1265             error_setg(errp, "can't read PRAM contents");
1266             return;
1267         }
1268     }
1269 }
1270 
1271 static void mos6522_q800_via1_init(Object *obj)
1272 {
1273     MOS6522Q800VIA1State *v1s = MOS6522_Q800_VIA1(obj);
1274     SysBusDevice *sbd = SYS_BUS_DEVICE(v1s);
1275 
1276     memory_region_init_io(&v1s->via_mem, obj, &mos6522_q800_via1_ops, v1s,
1277                           "via1", VIA_SIZE);
1278     sysbus_init_mmio(sbd, &v1s->via_mem);
1279 
1280     /* ADB */
1281     qbus_init((BusState *)&v1s->adb_bus, sizeof(v1s->adb_bus),
1282               TYPE_ADB_BUS, DEVICE(v1s), "adb.0");
1283 
1284     /* A/UX mode */
1285     qdev_init_gpio_out(DEVICE(obj), &v1s->auxmode_irq, 1);
1286 }
1287 
1288 static const VMStateDescription vmstate_q800_via1 = {
1289     .name = "q800-via1",
1290     .version_id = 0,
1291     .minimum_version_id = 0,
1292     .post_load = via1_post_load,
1293     .fields = (const VMStateField[]) {
1294         VMSTATE_STRUCT(parent_obj, MOS6522Q800VIA1State, 0, vmstate_mos6522,
1295                        MOS6522State),
1296         VMSTATE_UINT8(last_b, MOS6522Q800VIA1State),
1297         /* RTC */
1298         VMSTATE_BUFFER(PRAM, MOS6522Q800VIA1State),
1299         VMSTATE_UINT32(tick_offset, MOS6522Q800VIA1State),
1300         VMSTATE_UINT8(data_out, MOS6522Q800VIA1State),
1301         VMSTATE_INT32(data_out_cnt, MOS6522Q800VIA1State),
1302         VMSTATE_UINT8(data_in, MOS6522Q800VIA1State),
1303         VMSTATE_UINT8(data_in_cnt, MOS6522Q800VIA1State),
1304         VMSTATE_UINT8(cmd, MOS6522Q800VIA1State),
1305         VMSTATE_INT32(wprotect, MOS6522Q800VIA1State),
1306         VMSTATE_INT32(alt, MOS6522Q800VIA1State),
1307         /* ADB */
1308         VMSTATE_INT32(adb_data_in_size, MOS6522Q800VIA1State),
1309         VMSTATE_INT32(adb_data_in_index, MOS6522Q800VIA1State),
1310         VMSTATE_INT32(adb_data_out_index, MOS6522Q800VIA1State),
1311         VMSTATE_BUFFER(adb_data_in, MOS6522Q800VIA1State),
1312         VMSTATE_BUFFER(adb_data_out, MOS6522Q800VIA1State),
1313         VMSTATE_UINT8(adb_autopoll_cmd, MOS6522Q800VIA1State),
1314         /* Timers */
1315         VMSTATE_TIMER_PTR(one_second_timer, MOS6522Q800VIA1State),
1316         VMSTATE_INT64(next_second, MOS6522Q800VIA1State),
1317         VMSTATE_TIMER_PTR(sixty_hz_timer, MOS6522Q800VIA1State),
1318         VMSTATE_INT64(next_sixty_hz, MOS6522Q800VIA1State),
1319         /* Timer hack */
1320         VMSTATE_INT32(timer_hack_state, MOS6522Q800VIA1State),
1321         VMSTATE_END_OF_LIST()
1322     }
1323 };
1324 
1325 static Property mos6522_q800_via1_properties[] = {
1326     DEFINE_PROP_DRIVE("drive", MOS6522Q800VIA1State, blk),
1327     DEFINE_PROP_END_OF_LIST(),
1328 };
1329 
1330 static void mos6522_q800_via1_class_init(ObjectClass *oc, void *data)
1331 {
1332     DeviceClass *dc = DEVICE_CLASS(oc);
1333     ResettableClass *rc = RESETTABLE_CLASS(oc);
1334     MOS6522DeviceClass *mdc = MOS6522_CLASS(oc);
1335 
1336     dc->realize = mos6522_q800_via1_realize;
1337     resettable_class_set_parent_phases(rc, NULL, mos6522_q800_via1_reset_hold,
1338                                        NULL, &mdc->parent_phases);
1339     dc->vmsd = &vmstate_q800_via1;
1340     device_class_set_props(dc, mos6522_q800_via1_properties);
1341 }
1342 
1343 static const TypeInfo mos6522_q800_via1_type_info = {
1344     .name = TYPE_MOS6522_Q800_VIA1,
1345     .parent = TYPE_MOS6522,
1346     .instance_size = sizeof(MOS6522Q800VIA1State),
1347     .instance_init = mos6522_q800_via1_init,
1348     .class_init = mos6522_q800_via1_class_init,
1349 };
1350 
1351 /* VIA 2 */
1352 static void mos6522_q800_via2_portB_write(MOS6522State *s)
1353 {
1354     if (s->dirb & VIA2B_vPower && (s->b & VIA2B_vPower) == 0) {
1355         /* shutdown */
1356         qemu_system_shutdown_request(SHUTDOWN_CAUSE_GUEST_SHUTDOWN);
1357     }
1358 }
1359 
1360 static void mos6522_q800_via2_reset_hold(Object *obj, ResetType type)
1361 {
1362     MOS6522State *ms = MOS6522(obj);
1363     MOS6522DeviceClass *mdc = MOS6522_GET_CLASS(ms);
1364 
1365     if (mdc->parent_phases.hold) {
1366         mdc->parent_phases.hold(obj, type);
1367     }
1368 
1369     ms->timers[0].frequency = VIA_TIMER_FREQ;
1370     ms->timers[1].frequency = VIA_TIMER_FREQ;
1371 
1372     ms->dirb = 0;
1373     ms->b = 0;
1374     ms->dira = 0;
1375     ms->a = 0x7f;
1376 }
1377 
1378 static void via2_nubus_irq_request(void *opaque, int n, int level)
1379 {
1380     MOS6522Q800VIA2State *v2s = opaque;
1381     MOS6522State *s = MOS6522(v2s);
1382     qemu_irq irq = qdev_get_gpio_in(DEVICE(s), VIA2_IRQ_NUBUS_BIT);
1383 
1384     if (level) {
1385         /* Port A nubus IRQ inputs are active LOW */
1386         s->a &= ~(1 << n);
1387     } else {
1388         s->a |= (1 << n);
1389     }
1390 
1391     /* Negative edge trigger */
1392     qemu_set_irq(irq, !level);
1393 }
1394 
1395 static void mos6522_q800_via2_init(Object *obj)
1396 {
1397     MOS6522Q800VIA2State *v2s = MOS6522_Q800_VIA2(obj);
1398     SysBusDevice *sbd = SYS_BUS_DEVICE(v2s);
1399 
1400     memory_region_init_io(&v2s->via_mem, obj, &mos6522_q800_via2_ops, v2s,
1401                           "via2", VIA_SIZE);
1402     sysbus_init_mmio(sbd, &v2s->via_mem);
1403 
1404     qdev_init_gpio_in_named(DEVICE(obj), via2_nubus_irq_request, "nubus-irq",
1405                             VIA2_NUBUS_IRQ_NB);
1406 }
1407 
1408 static const VMStateDescription vmstate_q800_via2 = {
1409     .name = "q800-via2",
1410     .version_id = 0,
1411     .minimum_version_id = 0,
1412     .fields = (const VMStateField[]) {
1413         VMSTATE_STRUCT(parent_obj, MOS6522Q800VIA2State, 0, vmstate_mos6522,
1414                        MOS6522State),
1415         VMSTATE_END_OF_LIST()
1416     }
1417 };
1418 
1419 static void mos6522_q800_via2_class_init(ObjectClass *oc, void *data)
1420 {
1421     DeviceClass *dc = DEVICE_CLASS(oc);
1422     ResettableClass *rc = RESETTABLE_CLASS(oc);
1423     MOS6522DeviceClass *mdc = MOS6522_CLASS(oc);
1424 
1425     resettable_class_set_parent_phases(rc, NULL, mos6522_q800_via2_reset_hold,
1426                                        NULL, &mdc->parent_phases);
1427     dc->vmsd = &vmstate_q800_via2;
1428     mdc->portB_write = mos6522_q800_via2_portB_write;
1429 }
1430 
1431 static const TypeInfo mos6522_q800_via2_type_info = {
1432     .name = TYPE_MOS6522_Q800_VIA2,
1433     .parent = TYPE_MOS6522,
1434     .instance_size = sizeof(MOS6522Q800VIA2State),
1435     .instance_init = mos6522_q800_via2_init,
1436     .class_init = mos6522_q800_via2_class_init,
1437 };
1438 
1439 static void mac_via_register_types(void)
1440 {
1441     type_register_static(&mos6522_q800_via1_type_info);
1442     type_register_static(&mos6522_q800_via2_type_info);
1443 }
1444 
1445 type_init(mac_via_register_types);
1446