xref: /qemu/hw/misc/mac_via.c (revision 2006904938fbb85ef32eb79ab96cdcc8cbc6de1c)
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                 break;
499             }
500             return;
501         }
502 
503         /* this is a write command, needs a parameter */
504         if (cmd == REG_WPROTECT || !v1s->wprotect) {
505             trace_via1_rtc_internal_set_cmd(cmd);
506             v1s->cmd = cmd;
507         } else {
508             trace_via1_rtc_internal_ignore_cmd(cmd);
509         }
510         return;
511     }
512 
513     /* second byte: it's a parameter */
514     if (v1s->alt == REG_EMPTY) {
515         switch (v1s->cmd & 0x7f) {
516         case REG_0...REG_3: /* seconds register */
517             /* FIXME */
518             trace_via1_rtc_cmd_seconds_write(v1s->cmd - REG_0, v1s->data_out);
519             v1s->cmd = REG_EMPTY;
520             break;
521         case REG_TEST:
522             /* device control: nothing to do */
523             trace_via1_rtc_cmd_test_write(v1s->data_out);
524             v1s->cmd = REG_EMPTY;
525             break;
526         case REG_WPROTECT:
527             /* Write Protect register */
528             trace_via1_rtc_cmd_wprotect_write(v1s->data_out);
529             v1s->wprotect = !!(v1s->data_out & 0x80);
530             v1s->cmd = REG_EMPTY;
531             break;
532         case REG_PRAM_ADDR...REG_PRAM_ADDR_LAST:
533             /* PRAM address 0x00 -> 0x13 */
534             trace_via1_rtc_cmd_pram_write(v1s->cmd - REG_PRAM_ADDR,
535                                           v1s->data_out);
536             v1s->PRAM[v1s->cmd - REG_PRAM_ADDR] = v1s->data_out;
537             pram_update(v1s);
538             v1s->cmd = REG_EMPTY;
539             break;
540         case REG_PRAM_SECT...REG_PRAM_SECT_LAST:
541             addr = (v1s->data_out >> 2) & 0x1f;
542             sector = (v1s->cmd & 0x7f) - REG_PRAM_SECT;
543             if (v1s->cmd & 0x80) {
544                 /* it's a read */
545                 v1s->data_in = v1s->PRAM[sector * 32 + addr];
546                 v1s->data_in_cnt = 8;
547                 trace_via1_rtc_cmd_pram_sect_read(sector, addr,
548                                                   sector * 32 + addr,
549                                                   v1s->data_in);
550                 v1s->cmd = REG_EMPTY;
551             } else {
552                 /* it's a write, we need one more parameter */
553                 trace_via1_rtc_internal_set_alt(addr, sector, addr);
554                 v1s->alt = addr;
555             }
556             break;
557         default:
558             g_assert_not_reached();
559             break;
560         }
561         return;
562     }
563 
564     /* third byte: it's the data of a REG_PRAM_SECT write */
565     g_assert(REG_PRAM_SECT <= v1s->cmd && v1s->cmd <= REG_PRAM_SECT_LAST);
566     sector = v1s->cmd - REG_PRAM_SECT;
567     v1s->PRAM[sector * 32 + v1s->alt] = v1s->data_out;
568     pram_update(v1s);
569     trace_via1_rtc_cmd_pram_sect_write(sector, v1s->alt, sector * 32 + v1s->alt,
570                                        v1s->data_out);
571     v1s->alt = REG_EMPTY;
572     v1s->cmd = REG_EMPTY;
573 }
574 
575 static void adb_via_poll(void *opaque)
576 {
577     MOS6522Q800VIA1State *v1s = MOS6522_Q800_VIA1(opaque);
578     MOS6522State *s = MOS6522(v1s);
579     ADBBusState *adb_bus = &v1s->adb_bus;
580     uint8_t obuf[9];
581     uint8_t *data = &s->sr;
582     int olen;
583 
584     /*
585      * Setting vADBInt below indicates that an autopoll reply has been
586      * received, however we must block autopoll until the point where
587      * the entire reply has been read back to the host
588      */
589     adb_autopoll_block(adb_bus);
590 
591     if (v1s->adb_data_in_size > 0 && v1s->adb_data_in_index == 0) {
592         /*
593          * For older Linux kernels that switch to IDLE mode after sending the
594          * ADB command, detect if there is an existing response and return that
595          * as a "fake" autopoll reply or bus timeout accordingly
596          */
597         *data = v1s->adb_data_out[0];
598         olen = v1s->adb_data_in_size;
599 
600         s->b &= ~VIA1B_vADBInt;
601         qemu_irq_raise(v1s->adb_data_ready);
602     } else {
603         /*
604          * Otherwise poll as normal
605          */
606         v1s->adb_data_in_index = 0;
607         v1s->adb_data_out_index = 0;
608         olen = adb_poll(adb_bus, obuf, adb_bus->autopoll_mask);
609 
610         if (olen > 0) {
611             /* Autopoll response */
612             *data = obuf[0];
613             olen--;
614             memcpy(v1s->adb_data_in, &obuf[1], olen);
615             v1s->adb_data_in_size = olen;
616 
617             s->b &= ~VIA1B_vADBInt;
618             qemu_irq_raise(v1s->adb_data_ready);
619         } else {
620             *data = v1s->adb_autopoll_cmd;
621             obuf[0] = 0xff;
622             obuf[1] = 0xff;
623             olen = 2;
624 
625             memcpy(v1s->adb_data_in, obuf, olen);
626             v1s->adb_data_in_size = olen;
627 
628             s->b &= ~VIA1B_vADBInt;
629             qemu_irq_raise(v1s->adb_data_ready);
630         }
631     }
632 
633     trace_via1_adb_poll(*data, (s->b & VIA1B_vADBInt) ? "+" : "-",
634                         adb_bus->status, v1s->adb_data_in_index, olen);
635 }
636 
637 static int adb_via_send_len(uint8_t data)
638 {
639     /* Determine the send length from the given ADB command */
640     uint8_t cmd = data & 0xc;
641     uint8_t reg = data & 0x3;
642 
643     switch (cmd) {
644     case 0x8:
645         /* Listen command */
646         switch (reg) {
647         case 2:
648             /* Register 2 is only used for the keyboard */
649             return 3;
650         case 3:
651             /*
652              * Fortunately our devices only implement writes
653              * to register 3 which is fixed at 2 bytes
654              */
655             return 3;
656         default:
657             qemu_log_mask(LOG_UNIMP, "ADB unknown length for register %d\n",
658                           reg);
659             return 1;
660         }
661     default:
662         /* Talk, BusReset */
663         return 1;
664     }
665 }
666 
667 static void adb_via_send(MOS6522Q800VIA1State *v1s, int state, uint8_t data)
668 {
669     MOS6522State *ms = MOS6522(v1s);
670     ADBBusState *adb_bus = &v1s->adb_bus;
671     uint16_t autopoll_mask;
672 
673     switch (state) {
674     case ADB_STATE_NEW:
675         /*
676          * Command byte: vADBInt tells host autopoll data already present
677          * in VIA shift register and ADB transceiver
678          */
679         adb_autopoll_block(adb_bus);
680 
681         if (adb_bus->status & ADB_STATUS_POLLREPLY) {
682             /* Tell the host the existing data is from autopoll */
683             ms->b &= ~VIA1B_vADBInt;
684         } else {
685             ms->b |= VIA1B_vADBInt;
686             v1s->adb_data_out_index = 0;
687             v1s->adb_data_out[v1s->adb_data_out_index++] = data;
688         }
689 
690         trace_via1_adb_send(" NEW", data, (ms->b & VIA1B_vADBInt) ? "+" : "-");
691         qemu_irq_raise(v1s->adb_data_ready);
692         break;
693 
694     case ADB_STATE_EVEN:
695     case ADB_STATE_ODD:
696         ms->b |= VIA1B_vADBInt;
697         v1s->adb_data_out[v1s->adb_data_out_index++] = data;
698 
699         trace_via1_adb_send(state == ADB_STATE_EVEN ? "EVEN" : " ODD",
700                             data, (ms->b & VIA1B_vADBInt) ? "+" : "-");
701         qemu_irq_raise(v1s->adb_data_ready);
702         break;
703 
704     case ADB_STATE_IDLE:
705         return;
706     }
707 
708     /* If the command is complete, execute it */
709     if (v1s->adb_data_out_index == adb_via_send_len(v1s->adb_data_out[0])) {
710         v1s->adb_data_in_size = adb_request(adb_bus, v1s->adb_data_in,
711                                             v1s->adb_data_out,
712                                             v1s->adb_data_out_index);
713         v1s->adb_data_in_index = 0;
714 
715         if (adb_bus->status & ADB_STATUS_BUSTIMEOUT) {
716             /*
717              * Bus timeout (but allow first EVEN and ODD byte to indicate
718              * timeout via vADBInt and SRQ status)
719              */
720             v1s->adb_data_in[0] = 0xff;
721             v1s->adb_data_in[1] = 0xff;
722             v1s->adb_data_in_size = 2;
723         }
724 
725         /*
726          * If last command is TALK, store it for use by autopoll and adjust
727          * the autopoll mask accordingly
728          */
729         if ((v1s->adb_data_out[0] & 0xc) == 0xc) {
730             v1s->adb_autopoll_cmd = v1s->adb_data_out[0];
731 
732             autopoll_mask = 1 << (v1s->adb_autopoll_cmd >> 4);
733             adb_set_autopoll_mask(adb_bus, autopoll_mask);
734         }
735     }
736 }
737 
738 static void adb_via_receive(MOS6522Q800VIA1State *v1s, int state, uint8_t *data)
739 {
740     MOS6522State *ms = MOS6522(v1s);
741     ADBBusState *adb_bus = &v1s->adb_bus;
742     uint16_t pending;
743 
744     switch (state) {
745     case ADB_STATE_NEW:
746         ms->b |= VIA1B_vADBInt;
747         return;
748 
749     case ADB_STATE_IDLE:
750         ms->b |= VIA1B_vADBInt;
751         adb_autopoll_unblock(adb_bus);
752 
753         trace_via1_adb_receive("IDLE", *data,
754                         (ms->b & VIA1B_vADBInt) ? "+" : "-", adb_bus->status,
755                         v1s->adb_data_in_index, v1s->adb_data_in_size);
756 
757         break;
758 
759     case ADB_STATE_EVEN:
760     case ADB_STATE_ODD:
761         switch (v1s->adb_data_in_index) {
762         case 0:
763             /* First EVEN byte: vADBInt indicates bus timeout */
764             *data = v1s->adb_data_in[v1s->adb_data_in_index];
765             if (adb_bus->status & ADB_STATUS_BUSTIMEOUT) {
766                 ms->b &= ~VIA1B_vADBInt;
767             } else {
768                 ms->b |= VIA1B_vADBInt;
769             }
770 
771             trace_via1_adb_receive(state == ADB_STATE_EVEN ? "EVEN" : " ODD",
772                                    *data, (ms->b & VIA1B_vADBInt) ? "+" : "-",
773                                    adb_bus->status, v1s->adb_data_in_index,
774                                    v1s->adb_data_in_size);
775 
776             v1s->adb_data_in_index++;
777             break;
778 
779         case 1:
780             /* First ODD byte: vADBInt indicates SRQ */
781             *data = v1s->adb_data_in[v1s->adb_data_in_index];
782             pending = adb_bus->pending & ~(1 << (v1s->adb_autopoll_cmd >> 4));
783             if (pending) {
784                 ms->b &= ~VIA1B_vADBInt;
785             } else {
786                 ms->b |= VIA1B_vADBInt;
787             }
788 
789             trace_via1_adb_receive(state == ADB_STATE_EVEN ? "EVEN" : " ODD",
790                                    *data, (ms->b & VIA1B_vADBInt) ? "+" : "-",
791                                    adb_bus->status, v1s->adb_data_in_index,
792                                    v1s->adb_data_in_size);
793 
794             v1s->adb_data_in_index++;
795             break;
796 
797         default:
798             /*
799              * Otherwise vADBInt indicates end of data. Note that Linux
800              * specifically checks for the sequence 0x0 0xff to confirm the
801              * end of the poll reply, so provide these extra bytes below to
802              * keep it happy
803              */
804             if (v1s->adb_data_in_index < v1s->adb_data_in_size) {
805                 /* Next data byte */
806                 *data = v1s->adb_data_in[v1s->adb_data_in_index];
807                 ms->b |= VIA1B_vADBInt;
808             } else if (v1s->adb_data_in_index == v1s->adb_data_in_size) {
809                 if (adb_bus->status & ADB_STATUS_BUSTIMEOUT) {
810                     /* Bus timeout (no more data) */
811                     *data = 0xff;
812                 } else {
813                     /* Return 0x0 after reply */
814                     *data = 0;
815                 }
816                 ms->b &= ~VIA1B_vADBInt;
817             } else {
818                 /* Bus timeout (no more data) */
819                 *data = 0xff;
820                 ms->b &= ~VIA1B_vADBInt;
821                 adb_bus->status = 0;
822                 adb_autopoll_unblock(adb_bus);
823             }
824 
825             trace_via1_adb_receive(state == ADB_STATE_EVEN ? "EVEN" : " ODD",
826                                    *data, (ms->b & VIA1B_vADBInt) ? "+" : "-",
827                                    adb_bus->status, v1s->adb_data_in_index,
828                                    v1s->adb_data_in_size);
829 
830             if (v1s->adb_data_in_index <= v1s->adb_data_in_size) {
831                 v1s->adb_data_in_index++;
832             }
833             break;
834         }
835 
836         qemu_irq_raise(v1s->adb_data_ready);
837         break;
838     }
839 }
840 
841 static void via1_adb_update(MOS6522Q800VIA1State *v1s)
842 {
843     MOS6522State *s = MOS6522(v1s);
844     int oldstate, state;
845 
846     oldstate = (v1s->last_b & VIA1B_vADB_StateMask) >> VIA1B_vADB_StateShift;
847     state = (s->b & VIA1B_vADB_StateMask) >> VIA1B_vADB_StateShift;
848 
849     if (state != oldstate) {
850         if (s->acr & VIA1ACR_vShiftOut) {
851             /* output mode */
852             adb_via_send(v1s, state, s->sr);
853         } else {
854             /* input mode */
855             adb_via_receive(v1s, state, &s->sr);
856         }
857     }
858 }
859 
860 static void via1_auxmode_update(MOS6522Q800VIA1State *v1s)
861 {
862     MOS6522State *s = MOS6522(v1s);
863     int oldirq, irq;
864 
865     oldirq = (v1s->last_b & VIA1B_vMystery) ? 1 : 0;
866     irq = (s->b & VIA1B_vMystery) ? 1 : 0;
867 
868     /* Check to see if the A/UX mode bit has changed */
869     if (irq != oldirq) {
870         trace_via1_auxmode(irq);
871         qemu_set_irq(v1s->auxmode_irq, irq);
872     }
873 }
874 
875 /*
876  * Addresses and real values for TimeDBRA/TimeSCCB to allow timer calibration
877  * to succeed (NOTE: both values have been multiplied by 3 to cope with the
878  * speed of QEMU execution on a modern host
879  */
880 #define MACOS_TIMEDBRA        0xd00
881 #define MACOS_TIMESCCB        0xd02
882 
883 #define MACOS_TIMEDBRA_VALUE  (0x2a00 * 3)
884 #define MACOS_TIMESCCB_VALUE  (0x079d * 3)
885 
886 static bool via1_is_toolbox_timer_calibrated(void)
887 {
888     /*
889      * Indicate whether the MacOS toolbox has been calibrated by checking
890      * for the value of our magic constants
891      */
892     uint16_t timedbra = lduw_be_phys(&address_space_memory, MACOS_TIMEDBRA);
893     uint16_t timesccdb = lduw_be_phys(&address_space_memory, MACOS_TIMESCCB);
894 
895     return (timedbra == MACOS_TIMEDBRA_VALUE &&
896             timesccdb == MACOS_TIMESCCB_VALUE);
897 }
898 
899 static void via1_timer_calibration_hack(MOS6522Q800VIA1State *v1s, int addr,
900                                         uint64_t val, int size)
901 {
902     /*
903      * Work around timer calibration to ensure we that we have non-zero and
904      * known good values for TIMEDRBA and TIMESCCDB.
905      *
906      * This works by attempting to detect the reset and calibration sequence
907      * of writes to VIA1
908      */
909     int old_timer_hack_state = v1s->timer_hack_state;
910 
911     switch (v1s->timer_hack_state) {
912     case 0:
913         if (addr == VIA_REG_PCR && val == 0x22) {
914             /* VIA_REG_PCR: configure VIA1 edge triggering */
915             v1s->timer_hack_state = 1;
916         }
917         break;
918     case 1:
919         if (addr == VIA_REG_T2CL && val == 0xc) {
920             /* VIA_REG_T2CL: low byte of 1ms counter */
921             if (!via1_is_toolbox_timer_calibrated()) {
922                 v1s->timer_hack_state = 2;
923             } else {
924                 v1s->timer_hack_state = 0;
925             }
926         }
927         break;
928     case 2:
929         if (addr == VIA_REG_T2CH && val == 0x3) {
930             /*
931              * VIA_REG_T2CH: high byte of 1ms counter (very likely at the
932              * start of SETUPTIMEK)
933              */
934             if (!via1_is_toolbox_timer_calibrated()) {
935                 v1s->timer_hack_state = 3;
936             } else {
937                 v1s->timer_hack_state = 0;
938             }
939         }
940         break;
941     case 3:
942         if (addr == VIA_REG_IER && val == 0x20) {
943             /*
944              * VIA_REG_IER: update at end of SETUPTIMEK
945              *
946              * Timer calibration has finished: unfortunately the values in
947              * TIMEDBRA (0xd00) and TIMESCCDB (0xd02) are so far out they
948              * cause divide by zero errors.
949              *
950              * Update them with values obtained from a real Q800 but with
951              * a x3 scaling factor which seems to work well
952              */
953             stw_be_phys(&address_space_memory, MACOS_TIMEDBRA,
954                         MACOS_TIMEDBRA_VALUE);
955             stw_be_phys(&address_space_memory, MACOS_TIMESCCB,
956                         MACOS_TIMESCCB_VALUE);
957 
958             v1s->timer_hack_state = 4;
959         }
960         break;
961     case 4:
962         /*
963          * This is the normal post-calibration timer state: we should
964          * generally remain here unless we detect the A/UX calibration
965          * loop, or a write to VIA_REG_PCR suggesting a reset
966          */
967         if (addr == VIA_REG_PCR && val == 0x22) {
968             /* Looks like there has been a reset? */
969             v1s->timer_hack_state = 1;
970         }
971         break;
972     default:
973         g_assert_not_reached();
974     }
975 
976     if (old_timer_hack_state != v1s->timer_hack_state) {
977         trace_via1_timer_hack_state(v1s->timer_hack_state);
978     }
979 }
980 
981 static uint64_t mos6522_q800_via1_read(void *opaque, hwaddr addr, unsigned size)
982 {
983     MOS6522Q800VIA1State *s = MOS6522_Q800_VIA1(opaque);
984     MOS6522State *ms = MOS6522(s);
985     uint64_t ret;
986 
987     addr = (addr >> 9) & 0xf;
988     ret = mos6522_read(ms, addr, size);
989     switch (addr) {
990     case VIA_REG_A:
991     case VIA_REG_ANH:
992         /* Quadra 800 Id */
993         ret = (ret & ~VIA1A_CPUID_MASK) | VIA1A_CPUID_Q800;
994         break;
995     }
996     return ret;
997 }
998 
999 static void mos6522_q800_via1_write(void *opaque, hwaddr addr, uint64_t val,
1000                                     unsigned size)
1001 {
1002     MOS6522Q800VIA1State *v1s = MOS6522_Q800_VIA1(opaque);
1003     MOS6522State *ms = MOS6522(v1s);
1004     int oldstate, state;
1005     int oldsr = ms->sr;
1006 
1007     addr = (addr >> 9) & 0xf;
1008 
1009     via1_timer_calibration_hack(v1s, addr, val, size);
1010 
1011     mos6522_write(ms, addr, val, size);
1012 
1013     switch (addr) {
1014     case VIA_REG_B:
1015         via1_rtc_update(v1s);
1016         via1_adb_update(v1s);
1017         via1_auxmode_update(v1s);
1018 
1019         v1s->last_b = ms->b;
1020         break;
1021 
1022     case VIA_REG_SR:
1023         {
1024             /*
1025              * NetBSD assumes it can send its first ADB command after sending
1026              * the ADB_BUSRESET command in ADB_STATE_NEW without changing the
1027              * state back to ADB_STATE_IDLE first as detailed in the ADB
1028              * protocol.
1029              *
1030              * Add a workaround to detect this condition at the start of ADB
1031              * enumeration and send the next command written to SR after a
1032              * ADB_BUSRESET onto the bus regardless, even if we don't detect a
1033              * state transition to ADB_STATE_NEW.
1034              *
1035              * Note that in my tests the NetBSD state machine takes one ADB
1036              * operation to recover which means the probe for an ADB device at
1037              * address 1 always fails. However since the first device is at
1038              * address 2 then this will work fine, without having to come up
1039              * with a more complicated and invasive solution.
1040              */
1041             oldstate = (v1s->last_b & VIA1B_vADB_StateMask) >>
1042                        VIA1B_vADB_StateShift;
1043             state = (ms->b & VIA1B_vADB_StateMask) >> VIA1B_vADB_StateShift;
1044 
1045             if (oldstate == ADB_STATE_NEW && state == ADB_STATE_NEW &&
1046                     (ms->acr & VIA1ACR_vShiftOut) &&
1047                     oldsr == 0 /* ADB_BUSRESET */) {
1048                 trace_via1_adb_netbsd_enum_hack();
1049                 adb_via_send(v1s, state, ms->sr);
1050             }
1051         }
1052         break;
1053     }
1054 }
1055 
1056 static const MemoryRegionOps mos6522_q800_via1_ops = {
1057     .read = mos6522_q800_via1_read,
1058     .write = mos6522_q800_via1_write,
1059     .endianness = DEVICE_BIG_ENDIAN,
1060     .valid = {
1061         .min_access_size = 1,
1062         .max_access_size = 4,
1063     },
1064 };
1065 
1066 static uint64_t mos6522_q800_via2_read(void *opaque, hwaddr addr, unsigned size)
1067 {
1068     MOS6522Q800VIA2State *s = MOS6522_Q800_VIA2(opaque);
1069     MOS6522State *ms = MOS6522(s);
1070     uint64_t val;
1071 
1072     addr = (addr >> 9) & 0xf;
1073     val = mos6522_read(ms, addr, size);
1074 
1075     switch (addr) {
1076     case VIA_REG_IFR:
1077         /*
1078          * On a Q800 an emulated VIA2 is integrated into the onboard logic. The
1079          * expectation of most OSs is that the DRQ bit is live, rather than
1080          * latched as it would be on a real VIA so do the same here.
1081          *
1082          * Note: DRQ is negative edge triggered
1083          */
1084         val &= ~VIA2_IRQ_SCSI_DATA;
1085         val |= (~ms->last_irq_levels & VIA2_IRQ_SCSI_DATA);
1086         break;
1087     }
1088 
1089     return val;
1090 }
1091 
1092 static void mos6522_q800_via2_write(void *opaque, hwaddr addr, uint64_t val,
1093                                     unsigned size)
1094 {
1095     MOS6522Q800VIA2State *s = MOS6522_Q800_VIA2(opaque);
1096     MOS6522State *ms = MOS6522(s);
1097 
1098     addr = (addr >> 9) & 0xf;
1099     mos6522_write(ms, addr, val, size);
1100 }
1101 
1102 static const MemoryRegionOps mos6522_q800_via2_ops = {
1103     .read = mos6522_q800_via2_read,
1104     .write = mos6522_q800_via2_write,
1105     .endianness = DEVICE_BIG_ENDIAN,
1106     .valid = {
1107         .min_access_size = 1,
1108         .max_access_size = 4,
1109     },
1110 };
1111 
1112 static void via1_postload_update_cb(void *opaque, bool running, RunState state)
1113 {
1114     MOS6522Q800VIA1State *v1s = MOS6522_Q800_VIA1(opaque);
1115 
1116     qemu_del_vm_change_state_handler(v1s->vmstate);
1117     v1s->vmstate = NULL;
1118 
1119     pram_update(v1s);
1120 }
1121 
1122 static int via1_post_load(void *opaque, int version_id)
1123 {
1124     MOS6522Q800VIA1State *v1s = MOS6522_Q800_VIA1(opaque);
1125 
1126     if (v1s->blk) {
1127         v1s->vmstate = qemu_add_vm_change_state_handler(
1128                            via1_postload_update_cb, v1s);
1129     }
1130 
1131     return 0;
1132 }
1133 
1134 /* VIA 1 */
1135 static void mos6522_q800_via1_reset_hold(Object *obj)
1136 {
1137     MOS6522Q800VIA1State *v1s = MOS6522_Q800_VIA1(obj);
1138     MOS6522State *ms = MOS6522(v1s);
1139     MOS6522DeviceClass *mdc = MOS6522_GET_CLASS(ms);
1140     ADBBusState *adb_bus = &v1s->adb_bus;
1141 
1142     if (mdc->parent_phases.hold) {
1143         mdc->parent_phases.hold(obj);
1144     }
1145 
1146     ms->timers[0].frequency = VIA_TIMER_FREQ;
1147     ms->timers[1].frequency = VIA_TIMER_FREQ;
1148 
1149     ms->b = VIA1B_vADB_StateMask | VIA1B_vADBInt | VIA1B_vRTCEnb;
1150 
1151     /* ADB/RTC */
1152     adb_set_autopoll_enabled(adb_bus, true);
1153     v1s->cmd = REG_EMPTY;
1154     v1s->alt = REG_EMPTY;
1155 
1156     /* Timer calibration hack */
1157     v1s->timer_hack_state = 0;
1158 }
1159 
1160 static void mos6522_q800_via1_realize(DeviceState *dev, Error **errp)
1161 {
1162     MOS6522Q800VIA1State *v1s = MOS6522_Q800_VIA1(dev);
1163     ADBBusState *adb_bus = &v1s->adb_bus;
1164     struct tm tm;
1165     int ret;
1166 
1167     v1s->one_second_timer = timer_new_ms(QEMU_CLOCK_VIRTUAL, via1_one_second,
1168                                          v1s);
1169     via1_one_second_update(v1s);
1170     v1s->sixty_hz_timer = timer_new_ns(QEMU_CLOCK_VIRTUAL, via1_sixty_hz,
1171                                        v1s);
1172     via1_sixty_hz_update(v1s);
1173 
1174     qemu_get_timedate(&tm, 0);
1175     v1s->tick_offset = (uint32_t)mktimegm(&tm) + RTC_OFFSET;
1176 
1177     adb_register_autopoll_callback(adb_bus, adb_via_poll, v1s);
1178     v1s->adb_data_ready = qdev_get_gpio_in(dev, VIA1_IRQ_ADB_READY_BIT);
1179 
1180     if (v1s->blk) {
1181         int64_t len = blk_getlength(v1s->blk);
1182         if (len < 0) {
1183             error_setg_errno(errp, -len,
1184                              "could not get length of backing image");
1185             return;
1186         }
1187         ret = blk_set_perm(v1s->blk,
1188                            BLK_PERM_CONSISTENT_READ | BLK_PERM_WRITE,
1189                            BLK_PERM_ALL, errp);
1190         if (ret < 0) {
1191             return;
1192         }
1193 
1194         ret = blk_pread(v1s->blk, 0, sizeof(v1s->PRAM), v1s->PRAM, 0);
1195         if (ret < 0) {
1196             error_setg(errp, "can't read PRAM contents");
1197             return;
1198         }
1199     }
1200 }
1201 
1202 static void mos6522_q800_via1_init(Object *obj)
1203 {
1204     MOS6522Q800VIA1State *v1s = MOS6522_Q800_VIA1(obj);
1205     SysBusDevice *sbd = SYS_BUS_DEVICE(v1s);
1206 
1207     memory_region_init_io(&v1s->via_mem, obj, &mos6522_q800_via1_ops, v1s,
1208                           "via1", VIA_SIZE);
1209     sysbus_init_mmio(sbd, &v1s->via_mem);
1210 
1211     /* ADB */
1212     qbus_init((BusState *)&v1s->adb_bus, sizeof(v1s->adb_bus),
1213               TYPE_ADB_BUS, DEVICE(v1s), "adb.0");
1214 
1215     /* A/UX mode */
1216     qdev_init_gpio_out(DEVICE(obj), &v1s->auxmode_irq, 1);
1217 }
1218 
1219 static const VMStateDescription vmstate_q800_via1 = {
1220     .name = "q800-via1",
1221     .version_id = 0,
1222     .minimum_version_id = 0,
1223     .post_load = via1_post_load,
1224     .fields = (VMStateField[]) {
1225         VMSTATE_STRUCT(parent_obj, MOS6522Q800VIA1State, 0, vmstate_mos6522,
1226                        MOS6522State),
1227         VMSTATE_UINT8(last_b, MOS6522Q800VIA1State),
1228         /* RTC */
1229         VMSTATE_BUFFER(PRAM, MOS6522Q800VIA1State),
1230         VMSTATE_UINT32(tick_offset, MOS6522Q800VIA1State),
1231         VMSTATE_UINT8(data_out, MOS6522Q800VIA1State),
1232         VMSTATE_INT32(data_out_cnt, MOS6522Q800VIA1State),
1233         VMSTATE_UINT8(data_in, MOS6522Q800VIA1State),
1234         VMSTATE_UINT8(data_in_cnt, MOS6522Q800VIA1State),
1235         VMSTATE_UINT8(cmd, MOS6522Q800VIA1State),
1236         VMSTATE_INT32(wprotect, MOS6522Q800VIA1State),
1237         VMSTATE_INT32(alt, MOS6522Q800VIA1State),
1238         /* ADB */
1239         VMSTATE_INT32(adb_data_in_size, MOS6522Q800VIA1State),
1240         VMSTATE_INT32(adb_data_in_index, MOS6522Q800VIA1State),
1241         VMSTATE_INT32(adb_data_out_index, MOS6522Q800VIA1State),
1242         VMSTATE_BUFFER(adb_data_in, MOS6522Q800VIA1State),
1243         VMSTATE_BUFFER(adb_data_out, MOS6522Q800VIA1State),
1244         VMSTATE_UINT8(adb_autopoll_cmd, MOS6522Q800VIA1State),
1245         /* Timers */
1246         VMSTATE_TIMER_PTR(one_second_timer, MOS6522Q800VIA1State),
1247         VMSTATE_INT64(next_second, MOS6522Q800VIA1State),
1248         VMSTATE_TIMER_PTR(sixty_hz_timer, MOS6522Q800VIA1State),
1249         VMSTATE_INT64(next_sixty_hz, MOS6522Q800VIA1State),
1250         /* Timer hack */
1251         VMSTATE_INT32(timer_hack_state, MOS6522Q800VIA1State),
1252         VMSTATE_END_OF_LIST()
1253     }
1254 };
1255 
1256 static Property mos6522_q800_via1_properties[] = {
1257     DEFINE_PROP_DRIVE("drive", MOS6522Q800VIA1State, blk),
1258     DEFINE_PROP_END_OF_LIST(),
1259 };
1260 
1261 static void mos6522_q800_via1_class_init(ObjectClass *oc, void *data)
1262 {
1263     DeviceClass *dc = DEVICE_CLASS(oc);
1264     ResettableClass *rc = RESETTABLE_CLASS(oc);
1265     MOS6522DeviceClass *mdc = MOS6522_CLASS(oc);
1266 
1267     dc->realize = mos6522_q800_via1_realize;
1268     resettable_class_set_parent_phases(rc, NULL, mos6522_q800_via1_reset_hold,
1269                                        NULL, &mdc->parent_phases);
1270     dc->vmsd = &vmstate_q800_via1;
1271     device_class_set_props(dc, mos6522_q800_via1_properties);
1272 }
1273 
1274 static const TypeInfo mos6522_q800_via1_type_info = {
1275     .name = TYPE_MOS6522_Q800_VIA1,
1276     .parent = TYPE_MOS6522,
1277     .instance_size = sizeof(MOS6522Q800VIA1State),
1278     .instance_init = mos6522_q800_via1_init,
1279     .class_init = mos6522_q800_via1_class_init,
1280 };
1281 
1282 /* VIA 2 */
1283 static void mos6522_q800_via2_portB_write(MOS6522State *s)
1284 {
1285     if (s->dirb & VIA2B_vPower && (s->b & VIA2B_vPower) == 0) {
1286         /* shutdown */
1287         qemu_system_shutdown_request(SHUTDOWN_CAUSE_GUEST_SHUTDOWN);
1288     }
1289 }
1290 
1291 static void mos6522_q800_via2_reset_hold(Object *obj)
1292 {
1293     MOS6522State *ms = MOS6522(obj);
1294     MOS6522DeviceClass *mdc = MOS6522_GET_CLASS(ms);
1295 
1296     if (mdc->parent_phases.hold) {
1297         mdc->parent_phases.hold(obj);
1298     }
1299 
1300     ms->timers[0].frequency = VIA_TIMER_FREQ;
1301     ms->timers[1].frequency = VIA_TIMER_FREQ;
1302 
1303     ms->dirb = 0;
1304     ms->b = 0;
1305     ms->dira = 0;
1306     ms->a = 0x7f;
1307 }
1308 
1309 static void via2_nubus_irq_request(void *opaque, int n, int level)
1310 {
1311     MOS6522Q800VIA2State *v2s = opaque;
1312     MOS6522State *s = MOS6522(v2s);
1313     qemu_irq irq = qdev_get_gpio_in(DEVICE(s), VIA2_IRQ_NUBUS_BIT);
1314 
1315     if (level) {
1316         /* Port A nubus IRQ inputs are active LOW */
1317         s->a &= ~(1 << n);
1318     } else {
1319         s->a |= (1 << n);
1320     }
1321 
1322     /* Negative edge trigger */
1323     qemu_set_irq(irq, !level);
1324 }
1325 
1326 static void mos6522_q800_via2_init(Object *obj)
1327 {
1328     MOS6522Q800VIA2State *v2s = MOS6522_Q800_VIA2(obj);
1329     SysBusDevice *sbd = SYS_BUS_DEVICE(v2s);
1330 
1331     memory_region_init_io(&v2s->via_mem, obj, &mos6522_q800_via2_ops, v2s,
1332                           "via2", VIA_SIZE);
1333     sysbus_init_mmio(sbd, &v2s->via_mem);
1334 
1335     qdev_init_gpio_in_named(DEVICE(obj), via2_nubus_irq_request, "nubus-irq",
1336                             VIA2_NUBUS_IRQ_NB);
1337 }
1338 
1339 static const VMStateDescription vmstate_q800_via2 = {
1340     .name = "q800-via2",
1341     .version_id = 0,
1342     .minimum_version_id = 0,
1343     .fields = (VMStateField[]) {
1344         VMSTATE_STRUCT(parent_obj, MOS6522Q800VIA2State, 0, vmstate_mos6522,
1345                        MOS6522State),
1346         VMSTATE_END_OF_LIST()
1347     }
1348 };
1349 
1350 static void mos6522_q800_via2_class_init(ObjectClass *oc, void *data)
1351 {
1352     DeviceClass *dc = DEVICE_CLASS(oc);
1353     ResettableClass *rc = RESETTABLE_CLASS(oc);
1354     MOS6522DeviceClass *mdc = MOS6522_CLASS(oc);
1355 
1356     resettable_class_set_parent_phases(rc, NULL, mos6522_q800_via2_reset_hold,
1357                                        NULL, &mdc->parent_phases);
1358     dc->vmsd = &vmstate_q800_via2;
1359     mdc->portB_write = mos6522_q800_via2_portB_write;
1360 }
1361 
1362 static const TypeInfo mos6522_q800_via2_type_info = {
1363     .name = TYPE_MOS6522_Q800_VIA2,
1364     .parent = TYPE_MOS6522,
1365     .instance_size = sizeof(MOS6522Q800VIA2State),
1366     .instance_init = mos6522_q800_via2_init,
1367     .class_init = mos6522_q800_via2_class_init,
1368 };
1369 
1370 static void mac_via_register_types(void)
1371 {
1372     type_register_static(&mos6522_q800_via1_type_info);
1373     type_register_static(&mos6522_q800_via2_type_info);
1374 }
1375 
1376 type_init(mac_via_register_types);
1377