~ubuntu-branches/ubuntu/raring/vice/raring

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
/*! \file reu.c \n
 *  \author Andreas Boose, Spiro Trikaliotis, Jouko Valta, Richard Hable, Ettore Perazzoli\n
 *  \brief   REU emulation.
 *
 * reu.c - REU emulation.
 *
 * Written by
 *  Andreas Boose <viceteam@t-online.de>
 *  Spiro Trikaliotis <spiro.trikaliotis@gmx.de>
 *
 * Additions upon extensive REU hardware testing:
 *  Wolfgang Moser <http://d81.de>
 *
 * Based on old code by
 *  Jouko Valta <jopi@stekt.oulu.fi>
 *  Richard Hable <K3027E7@edvz.uni-linz.ac.at>
 *  Ettore Perazzoli <ettore@comm2000.it>
 *
 * This file is part of VICE, the Versatile Commodore Emulator.
 * See README for copyright notice.
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
 *  02111-1307  USA.
 *
 */

#include "vice.h"

#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "c64cart.h"
#include "c64io.h"
#include "cartridge.h"
#include "cmdline.h"
#include "interrupt.h"
#include "lib.h"
#include "log.h"
#include "machine.h"
#include "maincpu.h"
#include "mem.h"
#include "resources.h"
#include "reu.h"
#include "snapshot.h"
#include "translate.h"
#include "types.h"
#include "util.h"


#if 0
#define REU_DEBUG 1 /*!< define this if you want to get debugging output for the REU. */
#endif

/*! \brief the debug levels to use when REU_DEBUG is defined */
enum {
    DEBUG_LEVEL_NONE = 0,              /*!< do not output debugging information */
    DEBUG_LEVEL_REGISTER,              /*!< output debugging information concerning the REU registers */
    DEBUG_LEVEL_TRANSFER_HIGH_LEVEL,   /*!< output debugging information on transfers, on a high-level (per operation) */
    DEBUG_LEVEL_NO_DRAM,               /*!< output debugging information whenever an address is accessed where no DRAM is available  */
    DEBUG_LEVEL_TRANSFER_LOW_LEVEL     /*!< output debugging information on transfers, on a low-level (per single byte) */
} debug_level_e;

#ifdef REU_DEBUG
    /*! \brief dynamically define the debugging level */
    static enum debug_level_e DEBUG_LEVEL = DEBUG_LEVEL_NONE;

    /*! \brief output debugging information
      \param _level
         The debugging level on which this data appears

      \param _x
        The complete log_message parameter, including the braces
    */
    #define DEBUG_LOG( _level, _x ) do { if ( _level <= (DEBUG_LEVEL) ) { log_message _x; } } while (0)

#else

    /*! \brief output debugging information
      \param _level
         The debugging level on which this data appears

      \param _x
        The complete log_message parameter, including the braces

      \remark
        This implementation is the dummy if debugging output is disabled
    */
    #define DEBUG_LOG( _level, _x )

#endif

/*! \brief Shortcut to check for masked bits being all set */
#define BITS_ARE_ALL_SET(_where, _bits) \
  ( (((_where) & (_bits)) == (_bits)) )

/*! \brief Shortcut to check for masked bits being all cleared */
#define BITS_ARE_ALL_UNSET(_where, _bits) \
  ( (((_where) & (_bits)) == 0) )

/*
 * Status and Command Registers
 * bit  7       6       5       4       3       2       1       0
 * 00   Int     EOB     Fault   RamSize ________ Version ________
 * 01   Exec    0       Load    Delayed 0       0          Mode
 */

/*! \brief Offsets of the different REU registers */
enum {
    REU_REG_R_STATUS         = 0x00, /*!< the REU status register */
    REU_REG_RW_COMMAND       = 0x01, /*!< the REU command register */
    REU_REG_RW_BASEADDR_LOW  = 0x02, /*!< the REU base low address register (computer side) */
    REU_REG_RW_BASEADDR_HIGH = 0x03, /*!< the REU base high address register (computer side) */
    REU_REG_RW_RAMADDR_LOW   = 0x04, /*!< the REU RAM low address register (expansion side) */
    REU_REG_RW_RAMADDR_HIGH  = 0x05, /*!< the REU RAM high address register (expansion side) */
    REU_REG_RW_BANK          = 0x06, /*!< the REU RAM bank address register (expansion side) */
    REU_REG_RW_BLOCKLEN_LOW  = 0x07, /*!< the REU transfer length low register */
    REU_REG_RW_BLOCKLEN_HIGH = 0x08, /*!< the REU transfer length high register */
    REU_REG_RW_INTERRUPT     = 0x09, /*!< the REU interrupt register */
    REU_REG_RW_ADDR_CONTROL  = 0x0A, /*!< the REU address register */
    REU_REG_RW_UNUSED        = 0x0B, /*!< the first unused REU address. The unused area fills up to REU_REG_LAST_REG */
    REU_REG_LAST_REG         = 0x1F  /*!< the last register of the REU */
};

/*! \brief bit definitions for the REU status register at offset REU_REG_R_STATUS */
enum {
    REU_REG_R_STATUS_CHIPVERSION_MASK  = 0x0F, /*!< bit mask the extract the chip version no. */
    REU_REG_R_STATUS_256K_CHIPS        = 0x10, /*!< set if 256K DRAMs (256Kx1) are used (1764, 1750), if unset, 64K DRAMs (64Kx1) are used (1700) */
    REU_REG_R_STATUS_VERIFY_ERROR      = 0x20, /*!< set if an verify error occurred. Cleared on read. */
    REU_REG_R_STATUS_END_OF_BLOCK      = 0x40, /*!< set of the operation ended. Cleared on read. */
    REU_REG_R_STATUS_INTERRUPT_PENDING = 0x80  /*!< set if an interrupt is pending. Cleared on read. */
};

/*! \brief bit definitions for the REU command register at offset REU_REG_RW_COMMAND */
enum {
    REU_REG_RW_COMMAND_TRANSFER_TYPE_MASK    = 0x03,    /*!< bit mask to extract the transfer type */
    REU_REG_RW_COMMAND_TRANSFER_TYPE_TO_REU     = 0x00, /*!< transfer type is C64 -> REU */
    REU_REG_RW_COMMAND_TRANSFER_TYPE_FROM_REU   = 0x01, /*!< transfer type is REU -> C64 */
    REU_REG_RW_COMMAND_TRANSFER_TYPE_SWAP       = 0x02, /*!< transfer type is swap between C64 and REU */
    REU_REG_RW_COMMAND_TRANSFER_TYPE_VERIFY     = 0x03, /*!< transfer type is verify between C64 and REU */
    REU_REG_RW_COMMAND_RESERVED_MASK         = 0x4C,    /*!< the bits defined here are writeable, but unused */
    REU_REG_RW_COMMAND_FF00_TRIGGER_DISABLED = 0x10,    /*!< if set, $FF00 trigger is disabled. */
    REU_REG_RW_COMMAND_AUTOLOAD              = 0x20,    /*!< if set, the address registers should be autoloaded after an operation */
    REU_REG_RW_COMMAND_EXECUTE               = 0x80     /*!< is set, the specified operation should start. */
};

/*! \brief bit definitions for the REU bank register at offset REU_REG_RW_BANK */
enum {
    REU_REG_RW_BANK_UNUSED = 0xF8  /*!< these bits are unused and always read as 1 */
};

/*! \brief bit definitions for the REU interrupt register at offset REU_REG_RW_INTERRUPT */
enum {
    REU_REG_RW_INTERRUPT_UNUSED_MASK          = 0x1F, /*!< these bits are unused and always read as 1 */
    REU_REG_RW_INTERRUPT_VERIFY_ENABLED       = 0x20, /*!< if set (and REU_REG_RW_INTERRUPT_INTERRUPTS_ENABLED is set, too), generate an interrupt if verify fails */
    REU_REG_RW_INTERRUPT_END_OF_BLOCK_ENABLED = 0x40, /*!< if set (and REU_REG_RW_INTERRUPT_INTERRUPTS_ENABLED is set, too), generate an interrupt if operation finished */
    REU_REG_RW_INTERRUPT_INTERRUPTS_ENABLED   = 0x80  /*!< is set, the REU can generate an interrupt. If unset, no interrupts can be generated */
};

/*! \brief bit definitions for the REU address control register at offset REU_REG_RW_ADDR_CONTROL */
enum {
    REU_REG_RW_ADDR_CONTROL_UNUSED_MASK       = 0x3f, /*!< these bits are unused and always read as 1 */
    REU_REG_RW_ADDR_CONTROL_FIX_REC           = 0x40, /*!< if set, the REU address is fixed, it does not increment */
    REU_REG_RW_ADDR_CONTROL_FIX_C64           = 0x80  /*!< if set, the C64 address is fixed, it does not increment */
};

/* REU registers */

/*! \brief define a complete set of REC registers */
struct rec_s {
    BYTE status;              /*!< status register at offset REU_REG_R_STATUS */
    BYTE command;             /*!< command register at offset REU_REG_RW_COMMAND */

    WORD base_computer;       /*!< C64 base address as defined at offsets REU_REG_RW_BASEADDR_LOW and REU_REG_RW_BASEADDR_HIGH */
    WORD base_reu;            /*!< REU base address as defined at offsets REU_REG_RW_RAMADDR_LOW and REU_REG_RW_RAMADDR_HIGH */
    BYTE bank_reu;            /*!< REU bank address as defined at offset REU_REG_RW_BANK */
    WORD transfer_length;     /*!< transfer length as defined at offsets REU_REG_RW_BLOCKLEN_LOW and REU_REG_RW_BLOCKLEN_HIGH */

    BYTE int_mask_reg;        /*! interrupt mask register as defined at offset REU_REG_RW_INTERRUPT */
    BYTE address_control_reg; /*! address control register as defined at offset REU_REG_RW_ADDR_CONTROL */

    /* shadow registers for implementing the "Half-Autoload-Bug" */

    WORD base_computer_shadow;   /*!< shadow register of base_computer */
    WORD base_reu_shadow;        /*!< shadow register of base_reu */
    BYTE bank_reu_shadow;        /*!< shadow register of bank_reu */
    WORD transfer_length_shadow; /*!< shadow register of transfer_length */
};

/*! \brief a complete REC description */
static struct rec_s rec;

/*! \brief some rec options which define special behaviour */
struct rec_options_s {
    unsigned int wrap_around;                   /*!< address where the REU has a wrap around */
    unsigned int special_wrap_around_1700;      /*!< address where the special 1700 wrap around occurs; if no 1700, the same avalue as wrap_around */
    unsigned int not_backedup_addresses;        /*!< beginning from this address up to wrap_around, there is no DRAM at all */
    unsigned int wrap_around_mask_when_storing; /*!< mask for the wrap around of REU address when putting result back in base_reu and bank_reu */
    BYTE         reg_bank_unused;               /*!< the unused bits (stuck at 1) of REU_REG_RW_BANK; for original REU, it is REU_REG_RW_BANK_UNUSED */
    BYTE         status_preset;                 /*!< preset value for the status (can be 0 or REU_REG_R_STATUS_256K_CHIPS) */
    unsigned int first_unused_register_address; /*!< the highest address the used REU register occupy */
};

/*! \brief a complete REC options description */
static struct rec_options_s rec_options;



/*! \brief pointer to a buffer which holds the REU image.  */
static BYTE *reu_ram = NULL;
/*! \brief the old ram size of reu_ram. Used to determine if and how much of the 
    buffer has to cleared when resizing the REU. */
static unsigned int old_reu_ram_size = 0;

static log_t reu_log = LOG_ERR; /*!< the log output for the REU */

static int reu_activate(void);
static int reu_deactivate(void);

static unsigned int reu_int_num;

/* ------------------------------------------------------------------------- */

/*! \brief Flag: Is the external REU enabled?  */
int reu_enabled;

/*! \brief Size of the REU.  */
static unsigned int reu_size = 0;

/*! \brief Size of the REU in KB.  */
static int reu_size_kb = 0;

/*! \brief Filename of the REU image.  */
static char *reu_filename = NULL;


/*! \internal \brief set the reu to the enabled or disabled state

 \param val
   if 0, disable the REU; else, enable it.

 \param param
   unused

 \return
   0 on success. else -1.
*/
static int set_reu_enabled(int val, void *param)
{
    if (!val) {
        if (reu_enabled) {
            if (reu_deactivate() < 0) {
                return -1;
            }
        }
        reu_enabled = 0;
        return 0;
    } else { 
        if (!reu_enabled) {
            if (reu_activate() < 0) {
                return -1;
            }
        }

        reu_enabled = 1;
        return 0;
    }
}

/*! \internal \brief set the first unused REU register address

 \param val
   the end of the used REU register area; should be equal
   to or bigger than REU_REG_RW_UNUSED.

 \param param
   unused

 \return
   0 on success, else -1.
*/
static int set_reu_first_unused(int val, void *param)
{
    int retval = -1;

    if (val >= REU_REG_RW_UNUSED) {
        rec_options.first_unused_register_address = val;
        retval = 0;
    }
    else {
        log_message(reu_log, "Invalid first unused REU address %02x.", val);
    };

    return retval;
}

/*! \internal \brief set the size of the reu

 \param val
   the size of the REU, in KB

 \param param
   unused

 \return
   0 on success, else -1.

 \remark
   val must be one of 128, 256, 512, 1024, 2048, 4096, 8192, or 16384.
*/
static int set_reu_size(int val, void *param)
{
    if (val == reu_size_kb)
        return 0;

    switch (val) {
      case 128:
      case 256:
      case 512:
      case 1024:
      case 2048:
      case 4096:
      case 8192:
      case 16384:
        break;
      default:
        log_message(reu_log, "Unknown REU size %d.", val);
        return -1;
    }

    if (reu_enabled) {
        reu_deactivate();
    }

    reu_size_kb = val;
    reu_size = reu_size_kb << 10;

    rec_options.wrap_around = 0x80000;
    rec_options.special_wrap_around_1700 = rec_options.wrap_around;
    rec_options.not_backedup_addresses = reu_size;
    rec_options.wrap_around_mask_when_storing = rec_options.wrap_around - 1;
    rec_options.reg_bank_unused = REU_REG_RW_BANK_UNUSED;
    rec_options.status_preset = REU_REG_R_STATUS_256K_CHIPS;

    switch (val) {
      case 128:
        /* special handling to mimic a 1700 as good as possible */
        rec_options.status_preset = 0; /* we do not have 256K chips, but only 64K chips */
        rec_options.special_wrap_around_1700 = 0x20000; /* the 1700 has a special wrap around, mimic that one */
        break;
      case 256:
        /* special handling to mimic a 1764 as good as possible */
        break;
      case 512:
        /* special handling to mimic a 1750 as good as possible */
        break;
      default:
        /* for the other (fictive) REUs, assume the bank register would be fully 8 bits wide */
        rec_options.wrap_around = 
        rec_options.special_wrap_around_1700 = 0;
        rec_options.wrap_around_mask_when_storing = 0xffffffff;
        rec_options.reg_bank_unused = 0;
        break;
    }
 
    if (reu_enabled) {
        reu_activate();
    }

    return 0;
}

/*! \internal \brief set the file name of the REU data

 \param name
   pointer to a buffer which holds the file name.
   If NULL, the REU data will not be backed on the disk.

 \param param
   unused

 \return
   0 on success, else -1.

 \remark
   The file name of the REU data is the name of the file which is
   used to store the REU data onto disk.
*/
static int set_reu_filename(const char *name, void *param)
{
    if (reu_filename != NULL && name != NULL
        && strcmp(name, reu_filename) == 0)
        return 0;

    if (name != NULL && *name != '\0') {
        if (util_check_filename_access(name) < 0)
            return -1;
    }

    if (reu_enabled) {
        reu_deactivate();
    }
    util_string_set(&reu_filename, name);

    if (reu_enabled) {
        reu_activate();
    }

    return 0;
}

/*! \brief string resources used by the REU module */
static const resource_string_t resources_string[] = {
    { "REUfilename", "", RES_EVENT_NO, NULL,
      &reu_filename, set_reu_filename, NULL },
    { NULL }
};

/*! \brief integer resources used by the REU module */
static const resource_int_t resources_int[] = {
    { "REU", 0, RES_EVENT_STRICT, (resource_value_t)0,
      &reu_enabled, set_reu_enabled, NULL },
    { "REUsize", 512, RES_EVENT_NO, NULL,
      &reu_size_kb, set_reu_size, NULL },
    { "REUfirstUnusedRegister", REU_REG_RW_UNUSED, RES_EVENT_NO, NULL,
      (int *) &rec_options.first_unused_register_address, set_reu_first_unused, NULL },
    { NULL }
};

/*! \brief initialize the reu resources
 \return
   0 on success, else -1.

 \remark
   Registers the string and the integer resources
*/
int reu_resources_init(void)
{
    if (resources_register_string(resources_string) < 0)
        return -1;

    return resources_register_int(resources_int);
}

/*! \brief uninitialize the reu resources */
void reu_resources_shutdown(void)
{
    lib_free(reu_filename);
}

/* ------------------------------------------------------------------------- */

static const cmdline_option_t cmdline_options[] =
{
    { "-reu", SET_RESOURCE, 0,
      NULL, NULL, "REU", (resource_value_t)1,
      USE_PARAM_STRING, USE_DESCRIPTION_ID,
      IDCLS_UNUSED, IDCLS_ENABLE_REU,
      NULL, NULL },
    { "+reu", SET_RESOURCE, 0,
      NULL, NULL, "REU", (resource_value_t)0,
      USE_PARAM_STRING, USE_DESCRIPTION_ID,
      IDCLS_UNUSED, IDCLS_DISABLE_REU,
      NULL, NULL },
    { "-reuimage", SET_RESOURCE, 1,
      NULL, NULL, "REUfilename", NULL,
      USE_PARAM_ID, USE_DESCRIPTION_ID,
      IDCLS_P_NAME, IDCLS_SPECIFY_REU_NAME,
      NULL, NULL },
    { "-reusize", SET_RESOURCE, 1,
      NULL, NULL, "REUsize", NULL,
      USE_PARAM_ID, USE_DESCRIPTION_ID,
      IDCLS_P_SIZE_IN_KB, IDCLS_REU_SIZE,
      NULL, NULL },
    { NULL }
};

/*! \brief initialize the command-line options'
 \return
   0 on success, else -1.

 \remark
   Registers the command-line options
*/
int reu_cmdline_options_init(void)
{
    return cmdline_register_options(cmdline_options);
}

/* ------------------------------------------------------------------------- */

/*! \brief initialize the REU */
void reu_init(void)
{
    reu_log = log_open("REU");

    reu_int_num = interrupt_cpu_status_int_new(maincpu_int_status, "REU");
}

/*! \brief reset the REU */
void reu_reset(void)
{
    memset(&rec, 0, sizeof rec);

    rec.status = (rec.status & ~ REU_REG_R_STATUS_256K_CHIPS) 
                  | rec_options.status_preset;

    rec.command = REU_REG_RW_COMMAND_FF00_TRIGGER_DISABLED;

    rec.transfer_length =
    rec.transfer_length_shadow = 0xffff;

    rec.bank_reu = 
    rec.bank_reu_shadow = rec_options.reg_bank_unused;

    rec.int_mask_reg = REU_REG_RW_INTERRUPT_UNUSED_MASK;

    rec.address_control_reg = REU_REG_RW_ADDR_CONTROL_UNUSED_MASK;
}

static int reu_activate(void)
{
    if (!reu_size)
        return 0;

    reu_ram = lib_realloc(reu_ram, reu_size);

    /* Clear newly allocated RAM.  */
    if (reu_size > old_reu_ram_size)
        memset(reu_ram, 0, (size_t)(reu_size - old_reu_ram_size));

    old_reu_ram_size = reu_size;

    log_message(reu_log, "%dKB unit installed.", reu_size >> 10);

    if (!util_check_null_string(reu_filename)) {
        if (util_file_load(reu_filename, reu_ram, (size_t)reu_size,
                           UTIL_FILE_LOAD_RAW) < 0) {
            log_message(reu_log,
                        "Reading REU image %s failed.", reu_filename);
            if (util_file_save(reu_filename, reu_ram, reu_size) < 0) {
                log_message(reu_log,
                            "Creating REU image %s failed.", reu_filename);
                return -1;
            }
            log_message(reu_log, "Creating REU image %s.", reu_filename);
            return 0;
        }
        log_message(reu_log, "Reading REU image %s.", reu_filename);
    }

    reu_reset();
    return 0;
}

static int reu_deactivate(void)
{
    if (reu_ram == NULL)
        return 0;

    if (!util_check_null_string(reu_filename)) {
        if (util_file_save(reu_filename, reu_ram, reu_size) < 0) {
            log_message(reu_log,
                        "Writing REU image %s failed.", reu_filename);
            return -1;
        }
        log_message(reu_log, "Writing REU image %s.", reu_filename);
    }

    lib_free(reu_ram);
    reu_ram = NULL;
    old_reu_ram_size = 0;

    return 0;
}

void reu_shutdown(void)
{
    reu_deactivate();
}

/* ------------------------------------------------------------------------- */
/* helper functions */

/*! \brief read the REU register values without side effects
  This function reads the REU values, so they can be accessed like
  an array of bytes. No side-effects that would be performed if a real
  read access would occur are executed.

  \param addr
    The address of the REC register to read

  \return
    The value the register has

  \remark
    address must be in the valid range 0..0x1f
*/
static BYTE reu_read_without_sideeffects(WORD addr)
{
    BYTE retval = 0xff;

    addr &= REU_REG_LAST_REG;

    switch (addr) {
      case REU_REG_R_STATUS:
        retval = rec.status;
        break;

      case REU_REG_RW_COMMAND:
        retval = rec.command;
        break;

      case REU_REG_RW_BASEADDR_LOW:
        retval = rec.base_computer & 0xff;
        break;

      case REU_REG_RW_BASEADDR_HIGH:
        retval = (rec.base_computer >> 8) & 0xff;
        break;

      case REU_REG_RW_RAMADDR_LOW:
        retval = rec.base_reu & 0xff;
        break;

      case REU_REG_RW_RAMADDR_HIGH:
        retval = (rec.base_reu >> 8) & 0xff;
        break;

      case REU_REG_RW_BANK:
        retval = rec.bank_reu | rec_options.reg_bank_unused;
        break;

      case REU_REG_RW_BLOCKLEN_LOW:
        retval = rec.transfer_length & 0xff;
        break;

      case REU_REG_RW_BLOCKLEN_HIGH:
        retval = (rec.transfer_length >> 8) & 0xff;
        break;

      case REU_REG_RW_INTERRUPT:
        assert( BITS_ARE_ALL_SET(rec.int_mask_reg, REU_REG_RW_INTERRUPT_UNUSED_MASK) );
        retval = rec.int_mask_reg;
        break;

      case REU_REG_RW_ADDR_CONTROL:
        assert( BITS_ARE_ALL_SET(rec.address_control_reg, REU_REG_RW_ADDR_CONTROL_UNUSED_MASK) );
        retval = rec.address_control_reg;
        break;
    }

    return retval;
}

/*! \brief write the REU register values without side effects
  This function writes the REU values, so they can be accessed like
  an array of bytes. No side-effects that would be performed if a real
  write access would occur are executed.

  \param addr
    The address of the REC register to write

  \param byte
    The value to set the register to

  \remark
    address must be in the valid range 0..0x1f
*/
static void reu_store_without_sideeffects(WORD addr, BYTE byte)
{
    addr &= REU_REG_LAST_REG;

    switch (addr)
    {
    case REU_REG_R_STATUS:
        /* REC status register is Read Only */
        break;

    case REU_REG_RW_COMMAND:
        rec.command = byte;
        break;

    case REU_REG_RW_BASEADDR_LOW:
        rec.base_computer = 
        rec.base_computer_shadow = (rec.base_computer_shadow & 0xff00) | byte;
        break;

    case REU_REG_RW_BASEADDR_HIGH:
        rec.base_computer = 
        rec.base_computer_shadow = (rec.base_computer_shadow & 0xff) | (byte << 8);
        break;

    case REU_REG_RW_RAMADDR_LOW:
        rec.base_reu =
        rec.base_reu_shadow = (rec.base_reu_shadow & 0xff00) | byte;
        break;

    case REU_REG_RW_RAMADDR_HIGH:
        rec.base_reu =
        rec.base_reu_shadow = (rec.base_reu_shadow & 0xff) | (byte << 8);
        break;

    case REU_REG_RW_BANK:
        rec.bank_reu = 
        rec.bank_reu_shadow = byte & ~ rec_options.reg_bank_unused;
        break;

    case REU_REG_RW_BLOCKLEN_LOW:
        rec.transfer_length =
        rec.transfer_length_shadow = (rec.transfer_length_shadow & 0xff00) | byte;
        break;

    case REU_REG_RW_BLOCKLEN_HIGH:
        rec.transfer_length =
        rec.transfer_length_shadow = (rec.transfer_length_shadow & 0xff) | (byte << 8);
        break;

    case REU_REG_RW_INTERRUPT:
        rec.int_mask_reg = byte | REU_REG_RW_INTERRUPT_UNUSED_MASK;
        break;

    case REU_REG_RW_ADDR_CONTROL:
        rec.address_control_reg = byte | REU_REG_RW_ADDR_CONTROL_UNUSED_MASK;
        break;

    default:
        break;
    }
}

/* ------------------------------------------------------------------------- */

/*! \brief read the REU register values
  This function is used to read the REU values from the computer.
  All side-effects are executed.

  \param addr
    The address of the REC register to read

  \return
    The value the register has
*/
BYTE REGPARM1 reu_read(WORD addr)
{
    BYTE retval = 0xff;

    addr &= 0xff;

    if (addr < rec_options.first_unused_register_address) {
        io_source = IO_SOURCE_REU;

        retval = reu_read_without_sideeffects(addr);

        switch (addr) {
          case REU_REG_R_STATUS:
            /* Bits 7-5 are cleared when register is read, and pending IRQs are
               removed. */
            rec.status &= 
                ~(REU_REG_R_STATUS_VERIFY_ERROR 
                  | REU_REG_R_STATUS_END_OF_BLOCK 
                  | REU_REG_R_STATUS_INTERRUPT_PENDING
                 );

            maincpu_set_irq(reu_int_num, 0);
            break;
          default:
            break;
        }

        DEBUG_LOG( DEBUG_LEVEL_REGISTER, (reu_log, "read [$%02X] => $%02X.", addr, retval) );
    }

    return retval;
}


/*! \brief write the REU register values
  This function is used to write the REU values from the computer.

  \param addr
    The address of the REC register to write

  \param byte
    The value to set the register to
*/
void REGPARM2 reu_store(WORD addr, BYTE byte)
{
    addr &= 0xff;

    if (addr < rec_options.first_unused_register_address) {
        reu_store_without_sideeffects(addr, byte);

        DEBUG_LOG( DEBUG_LEVEL_REGISTER, (reu_log, "store [$%02X] <= $%02X.", addr, (int)byte) );

        switch (addr)
        {
        case REU_REG_RW_COMMAND:
            /* write REC command register
             * DMA only if execution bit (7) set  - RH */
            if (BITS_ARE_ALL_SET(rec.command, REU_REG_RW_COMMAND_EXECUTE)) {
                reu_dma(rec.command & REU_REG_RW_COMMAND_FF00_TRIGGER_DISABLED);
            }
            break;

        case REU_REG_RW_INTERRUPT:
            if (BITS_ARE_ALL_SET(rec.int_mask_reg,
                    REU_REG_RW_INTERRUPT_END_OF_BLOCK_ENABLED | REU_REG_RW_INTERRUPT_INTERRUPTS_ENABLED)
                && BITS_ARE_ALL_SET(rec.status, REU_REG_R_STATUS_END_OF_BLOCK))
            {
                DEBUG_LOG( DEBUG_LEVEL_REGISTER, (reu_log, "End-of-transfer interrupt pending") );
                rec.status |= REU_REG_R_STATUS_INTERRUPT_PENDING;
                maincpu_set_irq(reu_int_num, 1);
            }
            if (BITS_ARE_ALL_SET(rec.int_mask_reg,
                    REU_REG_RW_INTERRUPT_VERIFY_ENABLED | REU_REG_RW_INTERRUPT_INTERRUPTS_ENABLED)
                && BITS_ARE_ALL_SET(rec.status, REU_REG_R_STATUS_VERIFY_ERROR))
            {
                DEBUG_LOG( DEBUG_LEVEL_REGISTER, (reu_log, "Verify interrupt pending") );
                rec.status |= REU_REG_R_STATUS_INTERRUPT_PENDING;
                maincpu_set_irq(reu_int_num, 1);
            }
            break;

        default:
            break;
        }

    }
}

/* ------------------------------------------------------------------------- */

/*! \brief increment the reu address, taking wrap around into account
  This function increments the reu address by the specified step.
  If a wrap around should occur, perform it, too.

  \param reu_addr
     The address to be incremented

  \param reu_step
     The increment. Must be either 0 or 1. If 0, reu_addr is not changed at all.

  \return
     The incremented reu_addr, taking into account the wrap-around
*/
inline static
unsigned int increment_reu_with_wrap_around(unsigned int reu_addr, unsigned int reu_step)
{
    assert(((reu_step == 0) || (reu_step == 1)));

    reu_addr += reu_step;

    if ( (reu_addr == rec_options.special_wrap_around_1700) 
        || (reu_addr == rec_options.wrap_around))
    {
        reu_addr = 0;
    }

    return reu_addr;
}

/*! \brief store a value into the REU
  This function stores a byte value into the specified location of the REU.
  It takes into account addresses of the REU not backed up by DRAM.

  \param reu_addr
     The REU address where to store the value

  \param value
     The value to write into the REU.

  \remark
     If the location reu_addr is not backed up by DRAM, the store is simply
     ignored.
*/
inline static
void store_to_reu(unsigned int reu_addr, BYTE value)
{
    reu_addr &= rec_options.special_wrap_around_1700 - 1;
    if (reu_addr < rec_options.not_backedup_addresses) {
        assert(reu_addr < reu_size);
        reu_ram[reu_addr] = value;
    }
    else {
        DEBUG_LOG( DEBUG_LEVEL_NO_DRAM, (reu_log,
            "--> writing to REU address %05X, but no DRAM!",
            reu_addr) );
    }
}

/*! \brief read a value from the REU
  This function reads a byte value from the specified location of the REU.
  It takes into account addresses of the REU not backed up by DRAM.

  \param reu_addr
     The REU address where to read the value from

  \remark value
     The value read from the REU.

  \remark
     If the location reu_addr is not backed up by DRAM, a dummy
     value is returned.
  
  \todo
     Check the values a real 17xx returns.
*/
inline static
BYTE read_from_reu(unsigned int reu_addr)
{
    BYTE value = 0xff; /* dummy value to return if not DRAM is available */

    reu_addr &= rec_options.special_wrap_around_1700 - 1;
    if (reu_addr < rec_options.not_backedup_addresses) {
        assert(reu_addr < reu_size);
        value = reu_ram[reu_addr];
    }
    else {
        DEBUG_LOG( DEBUG_LEVEL_NO_DRAM, (reu_log,
            "--> read from REU address %05X, but no DRAM!",
            reu_addr) );
    }

    return value;
}

/* ------------------------------------------------------------------------- */

/*! \brief update the REU registers after a DMA operation

  \param host_addr
    The host (computer) address the operation stopped at

  \param reu_addr
    The REU address the operation stopped at

  \param len
    The transfer length the operation stopped at

  \param new_status_or_mask
    A mask which is used to set bits in the status

  \remark
    if autoload is enabled, the shadow registers are written back 
    to the REU registers.
*/
static void reu_dma_update_regs(WORD host_addr, unsigned int reu_addr,
                                int len, BYTE new_status_or_mask)
{
    assert( len >= 1 );
    assert( new_status_or_mask != 0 );

    reu_addr &= rec_options.wrap_around_mask_when_storing;

    rec.status |= new_status_or_mask;

    if (!(rec.command & REU_REG_RW_COMMAND_AUTOLOAD)) {
        /* not autoload
         * incr. of addr. disabled, as already pointing to correct addr.
         * address changes only if not fixed, correct reu base registers  -RH
         */
        DEBUG_LOG( DEBUG_LEVEL_REGISTER, (reu_log, "No autoload.") );
        if ( BITS_ARE_ALL_UNSET(rec.address_control_reg, REU_REG_RW_ADDR_CONTROL_FIX_C64) ) {
            rec.base_computer = host_addr;
        }

        if ( BITS_ARE_ALL_UNSET(rec.address_control_reg, REU_REG_RW_ADDR_CONTROL_FIX_REC) ) {
            rec.base_reu = reu_addr & 0xffff;
            rec.bank_reu = (reu_addr >> 16) & 0xff;
        }

        rec.transfer_length = len & 0xFFFF;
    }
    else {
        rec.base_computer   = rec.base_computer_shadow;
        rec.base_reu        = rec.base_reu_shadow;
        rec.bank_reu        = rec.bank_reu_shadow;
        rec.transfer_length = rec.transfer_length_shadow;

        DEBUG_LOG( DEBUG_LEVEL_REGISTER, (reu_log, "Autoload.") );
    }

    if ( BITS_ARE_ALL_SET(new_status_or_mask, REU_REG_R_STATUS_END_OF_BLOCK) ) {
        /* only check for interrupt, when the transfer ended correctly (no verify error) */
        if ( BITS_ARE_ALL_SET(rec.int_mask_reg,
             REU_REG_RW_INTERRUPT_END_OF_BLOCK_ENABLED | REU_REG_RW_INTERRUPT_INTERRUPTS_ENABLED))
        {
            DEBUG_LOG( DEBUG_LEVEL_REGISTER, (reu_log, "Interrupt pending") );
            rec.status |= REU_REG_R_STATUS_INTERRUPT_PENDING;
            maincpu_set_irq(reu_int_num, 1);
        }
    }

    if ( BITS_ARE_ALL_SET(new_status_or_mask, REU_REG_R_STATUS_VERIFY_ERROR)) {
        if ( BITS_ARE_ALL_SET(rec.int_mask_reg,
             REU_REG_RW_INTERRUPT_VERIFY_ENABLED | REU_REG_RW_INTERRUPT_INTERRUPTS_ENABLED))
        {
            DEBUG_LOG( DEBUG_LEVEL_REGISTER, (reu_log, "Verify Interrupt pending") );
            rec.status |= REU_REG_R_STATUS_INTERRUPT_PENDING;
            maincpu_set_irq(reu_int_num, 1);
        }
    }
}

/*! \brief DMA operation writing from the host to the REU

  \param host_addr
    The host (computer) address where the operation starts 

  \param reu_addr
    The REU address where the operation starts

  \param host_step
    The increment to use for the host address; must be either 0 or 1

  \param reu_step
    The increment to use for the REU address; must be either 0 or 1

  \param len
    The transfer length of the operation
*/
static void reu_dma_host_to_reu(WORD host_addr, unsigned int reu_addr, 
                                int host_step, int reu_step, int len)
{
    BYTE value;
    DEBUG_LOG( DEBUG_LEVEL_TRANSFER_HIGH_LEVEL, (reu_log,
                "copy ext $%05X %s<= main $%04X%s, $%04X (%d) bytes.",
                reu_addr, reu_step ? "" : "(fixed) ", host_addr,
                host_step ? "" : " (fixed)", len, len) );

    assert(((host_step == 0) || (host_step == 1)));
    assert(((reu_step == 0) || (reu_step == 1)));
    assert(len >= 1);

    while (len) {
        maincpu_clk++;
        machine_handle_pending_alarms(0);
        value = mem_read(host_addr);
        DEBUG_LOG( DEBUG_LEVEL_TRANSFER_LOW_LEVEL, (reu_log,
                    "Transferring byte: %x from main $%04X to ext $%05X.",
                    value, host_addr, reu_addr) );

        store_to_reu(reu_addr, value);
        host_addr = (host_addr + host_step) & 0xffff;
        reu_addr = increment_reu_with_wrap_around(reu_addr, reu_step);
        len--;
    }
    DEBUG_LOG( DEBUG_LEVEL_REGISTER, (reu_log, "END OF BLOCK") );
    reu_dma_update_regs(host_addr, reu_addr, ++len, REU_REG_R_STATUS_END_OF_BLOCK);
}

/*! \brief DMA operation writing from the REU to the host

  \param host_addr
    The host (computer) address where the operation starts 

  \param reu_addr
    The REU address where the operation starts

  \param host_step
    The increment to use for the host address; must be either 0 or 1

  \param reu_step
    The increment to use for the REU address; must be either 0 or 1

  \param len
    The transfer length of the operation
*/
static void reu_dma_reu_to_host(WORD host_addr, unsigned int reu_addr,
                                int host_step, int reu_step, int len)
{
    BYTE value;
    DEBUG_LOG( DEBUG_LEVEL_TRANSFER_HIGH_LEVEL, (reu_log,
                "copy ext $%05X %s=> main $%04X%s, $%04X (%d) bytes.",
                reu_addr, reu_step ? "" : "(fixed) ", host_addr,
                host_step ? "" : " (fixed)", len, len) );

    assert(((host_step == 0) || (host_step == 1)));
    assert(((reu_step == 0) || (reu_step == 1)));
    assert(len >= 1);

    while (len) {
        DEBUG_LOG( DEBUG_LEVEL_TRANSFER_LOW_LEVEL, (reu_log,
                    "Transferring byte: %x from ext $%05X to main $%04X.",
                    reu_ram[reu_addr % reu_size], reu_addr, host_addr) );
        maincpu_clk++;
        value = read_from_reu(reu_addr);
        mem_store(host_addr, value);
        machine_handle_pending_alarms(0);
        host_addr = (host_addr + host_step) & 0xffff;
        reu_addr = increment_reu_with_wrap_around(reu_addr, reu_step);
        len--;
    }
    DEBUG_LOG( DEBUG_LEVEL_REGISTER, (reu_log, "END OF BLOCK") );
    reu_dma_update_regs(host_addr, reu_addr, ++len, REU_REG_R_STATUS_END_OF_BLOCK);
}

/*! \brief DMA operation swaping data between host and REU

  \param host_addr
    The host (computer) address where the operation starts 

  \param reu_addr
    The REU address where the operation starts

  \param host_step
    The increment to use for the host address; must be either 0 or 1

  \param reu_step
    The increment to use for the REU address; must be either 0 or 1

  \param len
    The transfer length of the operation
*/
static void reu_dma_swap(WORD host_addr, unsigned int reu_addr,
                         int host_step, int reu_step, int len)
{
    BYTE value_from_reu;
    BYTE value_from_c64;
    DEBUG_LOG( DEBUG_LEVEL_TRANSFER_HIGH_LEVEL, (reu_log,
                "swap ext $%05X %s<=> main $%04X%s, $%04X (%d) bytes.",
                reu_addr, reu_step ? "" : "(fixed) ", host_addr,
                host_step ? "" : " (fixed)", len, len) );

    assert(((host_step == 0) || (host_step == 1)));
    assert(((reu_step == 0) || (reu_step == 1)));
    assert(len >= 1);

    while (len) {
        value_from_reu = read_from_reu(reu_addr);
        maincpu_clk++;
        machine_handle_pending_alarms(0);
        value_from_c64 = mem_read(host_addr);
        DEBUG_LOG( DEBUG_LEVEL_TRANSFER_LOW_LEVEL, (reu_log,
                    "Exchanging bytes: %x from main $%04X with %x from ext $%05X.",
                    value_from_c64, host_addr, value_from_reu, reu_addr) );
        store_to_reu(reu_addr, value_from_c64);
        mem_store(host_addr, value_from_reu);
        maincpu_clk++;
        machine_handle_pending_alarms(0);
        host_addr = (host_addr + host_step) & 0xffff;
        reu_addr = increment_reu_with_wrap_around(reu_addr, reu_step);
        len--;
    }
    DEBUG_LOG( DEBUG_LEVEL_REGISTER, (reu_log, "END OF BLOCK") );
    reu_dma_update_regs(host_addr, reu_addr, ++len, REU_REG_R_STATUS_END_OF_BLOCK);
}

/*! \brief DMA operation comparing data between host and REU

  \param host_addr
    The host (computer) address where the operation starts 

  \param reu_addr
    The REU address where the operation starts

  \param host_step
    The increment to use for the host address; must be either 0 or 1

  \param reu_step
    The increment to use for the REU address; must be either 0 or 1

  \param len
    The transfer length of the operation
*/
static void reu_dma_compare(WORD host_addr, unsigned int reu_addr,
                            int host_step, int reu_step, int len)
{
    BYTE value_from_reu;
    BYTE value_from_c64;

    BYTE new_status_or_mask = 0;

    DEBUG_LOG( DEBUG_LEVEL_TRANSFER_HIGH_LEVEL, (reu_log,
                "compare ext $%05X %s<=> main $%04X%s, $%04X (%d) bytes.",
                reu_addr, reu_step ? "" : "(fixed) ", host_addr,
                host_step ? "" : " (fixed)", len, len) );

    assert(((host_step == 0) || (host_step == 1)));
    assert(((reu_step == 0) || (reu_step == 1)));
    assert(len >= 1);

    /* the real 17xx does not clear these bits on compare;
     * thus, we do not clear them, either! */

    /* rec.status &= ~ (REU_REG_R_STATUS_VERIFY_ERROR | REU_REG_R_STATUS_END_OF_BLOCK); */

    while (len) {
        maincpu_clk++;
        machine_handle_pending_alarms(0);
        value_from_reu = read_from_reu(reu_addr);
        value_from_c64 = mem_read(host_addr);
        DEBUG_LOG( DEBUG_LEVEL_TRANSFER_LOW_LEVEL, (reu_log,
                    "Comparing bytes: %x from main $%04X with %x from ext $%05X.",
                    value_from_c64, host_addr, value_from_reu, reu_addr) );
        reu_addr = increment_reu_with_wrap_around(reu_addr, reu_step);
        host_addr = (host_addr + host_step) & 0xffff;
        len--;
        if (value_from_reu != value_from_c64) {

            DEBUG_LOG( DEBUG_LEVEL_REGISTER, (reu_log, "VERIFY ERROR") );
            new_status_or_mask |= REU_REG_R_STATUS_VERIFY_ERROR;

            /* weird behaviour no. 1 of the 17xx:
             * failed verify operations consume one extra cycle, except if
             * the failed comparison happened on the last byte of the buffer.
             */
            if( len >= 1 ) {
                maincpu_clk++;
                machine_handle_pending_alarms(0);
            }
            break;
        }
    }

    /* the length was decremented once too much, correct this */
    if (len == 0) {
        ++len;

        /* weird behaviour no. 2 of the 17xx:
         * If the last byte failed, the "end of block transfer" bit is set, too
         */
        /* all bytes are equal, mark End Of Block */
        new_status_or_mask |= REU_REG_R_STATUS_END_OF_BLOCK;
    }
    else if (len == 1) {
        /* weird behaviour no. 3 of the 17xx:
         * If the next-to-last byte failed, the "end of block transfer" bit is
         * set, but only if the last byte compares equal
         */

        value_from_reu = read_from_reu(reu_addr);
        value_from_c64 = mem_read(host_addr);
        DEBUG_LOG( DEBUG_LEVEL_TRANSFER_LOW_LEVEL, (reu_log,
                    "Comparing bytes after verify error: %x from main $%04X with %x from ext $%05X.",
                    value_from_c64, host_addr, value_from_reu, reu_addr) );
        if (value_from_reu == value_from_c64) {
            new_status_or_mask |= REU_REG_R_STATUS_END_OF_BLOCK;
        }
    }

    assert( len >= 1 );
    reu_dma_update_regs(host_addr, reu_addr, len, new_status_or_mask);
}

/* ------------------------------------------------------------------------- */

/*! \brief perform REU DMA
 
 This function is called when a write to REC command register or memory
 location FF00 is detected.

 \param immediate
   If 0, the DMA should not started immediately. It is only prepared, so it
   can be executed when the next call to reu_dma() occurs with something different
   than immediate == 0.

 \remark
   If the REC command register is written and 
   REU_REG_RW_COMMAND_FF00_TRIGGER_DISABLED is *not* set, this function is called
   with immediate == 0. In this case, this function is armed for an execution of
   the DMA as soon as it is called with immediate == -1.\n
   If the REC command register is written and
   REU_REG_RW_COMMAND_FF00_TRIGGER_DISABLED *is* set, this function is called with
   immediate == 1. In this case, the DMA is executed immediately.\n
   If a write to $FF00 is encountered, this function is called with immediate == -1.
   If it has been previously armed (with immediate == 0), then the DMA operation is
   executed.
*/
void reu_dma(int immediate)
{
    static int delay = 0;
    int len;
    int reu_step, host_step;
    WORD host_addr;
    unsigned int reu_addr;

    if (!reu_enabled)
        return;

    if (!immediate) {
        delay = 1;
        return;
    } else {
        if (!delay && immediate < 0)
            return;
        delay = 0;
    }

    /* wrong address of bank register & calculations corrected  - RH */
    host_addr = rec.base_computer;
    reu_addr = rec.base_reu | (rec.bank_reu << 16);
    len = rec.transfer_length ? rec.transfer_length : 0x10000;

    /* Fixed addresses implemented -- [EP] 04-16-97. */
    host_step = rec.address_control_reg & REU_REG_RW_ADDR_CONTROL_FIX_C64 ? 0 : 1;
    reu_step  = rec.address_control_reg & REU_REG_RW_ADDR_CONTROL_FIX_REC ? 0 : 1;

    switch (rec.command & REU_REG_RW_COMMAND_TRANSFER_TYPE_MASK) {
      case REU_REG_RW_COMMAND_TRANSFER_TYPE_TO_REU:
        reu_dma_host_to_reu(host_addr, reu_addr, host_step, reu_step, len);
        break;
      case REU_REG_RW_COMMAND_TRANSFER_TYPE_FROM_REU:
        reu_dma_reu_to_host(host_addr, reu_addr, host_step, reu_step, len);
        break;
      case REU_REG_RW_COMMAND_TRANSFER_TYPE_SWAP:
        reu_dma_swap(host_addr, reu_addr, host_step, reu_step, len);
        break;
      case REU_REG_RW_COMMAND_TRANSFER_TYPE_VERIFY:
        reu_dma_compare(host_addr, reu_addr, host_step, reu_step, len);
        break;
    }

    rec.command = (rec.command & ~ REU_REG_RW_COMMAND_EXECUTE) 
                  | REU_REG_RW_COMMAND_FF00_TRIGGER_DISABLED;
}

/* ------------------------------------------------------------------------- */

static char snap_module_name[] = "REU1764"; /*!< the name of the module for the snapshot */
#define SNAP_MAJOR 0 /*!< version number for this module, major number */
#define SNAP_MINOR 0 /*!< version number for this module, minor number */

/*! \brief type for the REU data as being stored in the snapshot.
 \remark
   Here, 16 byte are used (instead of only 11, which would be enough) to be
   compatible with the original implementation. Otherwise, we would have to
   change the version number. This way, it is much simpler.
 */
typedef BYTE reu_as_stored_in_snapshot_t[16];

/*! \brief write the REU module data to the snapshot
 \param s
    The snapshot data where to add the information for this module.

 \return
    0 on success, else -1.
*/
int reu_write_snapshot_module(snapshot_t *s)
{
    snapshot_module_t *m;

    reu_as_stored_in_snapshot_t reu;
    WORD reu_address;

    memset(reu, 0xff, sizeof reu);

    for (reu_address = 0; reu_address < sizeof(reu); reu_address++) {
        reu[reu_address] = reu_read_without_sideeffects(reu_address);
    }

    m = snapshot_module_create(s, snap_module_name, SNAP_MAJOR, SNAP_MINOR);
    if (m == NULL)
        return -1;

    if (SMW_DW(m, (reu_size >> 10)) < 0
        || SMW_BA(m, reu, sizeof(reu)) < 0
        || SMW_BA(m, reu_ram, reu_size) < 0) {
        snapshot_module_close(m);
        return -1;
    }

    snapshot_module_close(m);
    return 0;
}

/*! \brief read the REU module data from the snapshot
 \param s
    The snapshot data from where to read the information for this module.

 \return
    0 on success, else -1.
 */
int reu_read_snapshot_module(snapshot_t *s)
{
    BYTE major_version, minor_version;
    snapshot_module_t *m;
    DWORD size;

    reu_as_stored_in_snapshot_t reu;
    WORD reu_address;

    memset(reu, 0xff, sizeof reu);

    m = snapshot_module_open(s, snap_module_name,
                             &major_version, &minor_version);
    if (m == NULL)
        return -1;

    if (major_version != SNAP_MAJOR) {
        log_error(reu_log, "Major version %d not valid; should be %d.",
                major_version, SNAP_MAJOR);
        goto fail;
    }

    /* Read RAM size.  */
    if (SMR_DW(m, &size) < 0)
        goto fail;

    if (size > 16384) {
        log_error(reu_log, "Size %d in snapshot not supported.", (int)size);
        goto fail;
    }

    set_reu_size((int)size, NULL);

    if (!reu_enabled)
        set_reu_enabled(1, NULL);

    if (SMR_BA(m, reu, sizeof(reu)) < 0 || SMR_BA(m, reu_ram, reu_size) < 0)
        goto fail;

    if (reu[REU_REG_R_STATUS] & 0x80)
        interrupt_restore_irq(maincpu_int_status, reu_int_num, 1);
    else
        interrupt_restore_irq(maincpu_int_status, reu_int_num, 0);

    for (reu_address = 0; reu_address < sizeof(reu); reu_address++) {
         reu_store_without_sideeffects(reu_address, reu[reu_address]);
    }


    snapshot_module_close(m);
    return 0;

fail:
    snapshot_module_close(m);
    return -1;
}