summaryrefslogtreecommitdiff
path: root/main.c
blob: 494d23aae1583380c9e351be1039a9664ef2705c (plain)
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
/*
 * Copyright 2007 Matthias Hopf <mhopf@suse.de>
 *
 * AtomBIOS disassembler + data structure dumper
 *
 * main.c:
 * Disassembler + frontend.
 *
 * License: to be determined
 */

// TODO: not endian safe!

#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <ctype.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/mman.h>

#include "datastructs.h"
#include "atombios_types.h"
#include "atombios_consts.h"

//include "atombios_tables.h"
#include "atombios.h"

#ifdef USE_ATOMBIOS_RELATED_STUFF
//#include "atombios.h"
extern int (*data_dumpers[]) (uint8_t *data, int indent);
#endif


#define USE_ATOMBIOS_RELATED_STUFF
#define MMAP_SIZE (1024*1024)


typedef struct {
    uint8_t          *base;
    ATOM_ROM_HEADER  *AtomRomHeader;
    uint16_t         *MasterCommandTables;
    uint16_t         *MasterDataTables;
} bios_tables_t;


enum IndexName {
    INDEX_NONE = 0, INDEX_COMMAND_TABLE, INDEX_DATA_TABLE, INDEX_ATI_PORT, INDEX_WORK_REG
} ;


enum {
    D_REG = 0, D_PS, D_WS, D_FB, D_ID, D_IM, D_PLL, D_MC, D_hex8, D_hex16, D_null
} ;

const char *addrnames[] = { "REG", "PS", "WS", "FB", "ID", "IM", "PLL", "MC", "dec", "hex8", "hex16", "null" };

const char *addrtypes[] = {
    "reg[%04x] ", "param[%02x] ", "work[%02x]  ", "fb[%02x]    ", "data[%04x]", NULL,
    "PLL[%04x] ", "MC[%04x]  ",
    "%02x", "%04x", ""
} ;
const char *addrtypes_im[] = { NULL, "%02x", "%04x", NULL, "%08x" };


typedef struct {
    int (*process) (uint8_t *d, char *out);
    const char *name;
    int desttype;
    int srcindex, destindex;
} optab_t;

int op_0x      (uint8_t *, char *);
int op_1x8     (uint8_t *, char *);
int op_1x16    (uint8_t *, char *);
int op_src     (uint8_t *, char *);
int op_dest    (uint8_t *, char *);
int op_destsrc (uint8_t *, char *);
int op_shift   (uint8_t *, char *);
int op_switch  (uint8_t *, char *);
int op_mask    (uint8_t *, char *);
const optab_t optable[256] = {
    { NULL, NULL, D_null, 0, 0 },
    { op_destsrc, "MOVE", D_REG, 0, 0 }, { op_destsrc, "MOVE", D_PS, 0, 0 },
    { op_destsrc, "MOVE", D_WS, 0, 0 },  { op_destsrc, "MOVE", D_FB, 0, 0 },
    { op_destsrc, "MOVE", D_PLL, 0, 0 }, { op_destsrc, "MOVE", D_MC, 0, 0 },
    { op_destsrc, "AND", D_REG, 0, 0 },  { op_destsrc, "AND", D_PS, 0, 0 },
    { op_destsrc, "AND", D_WS, 0, 0 },   { op_destsrc, "AND", D_FB, 0, 0 },
    { op_destsrc, "AND", D_PLL, 0, 0 },  { op_destsrc, "AND", D_MC, 0, 0 },
    { op_destsrc, "OR", D_REG, 0, 0 },   { op_destsrc, "OR", D_PS, 0, 0 },
    { op_destsrc, "OR", D_WS, 0, 0 },    { op_destsrc, "OR", D_FB, 0, 0 },
    { op_destsrc, "OR", D_PLL, 0, 0 },   { op_destsrc, "OR", D_MC, 0, 0 },
    { op_shift,   "SHIFT_LEFT", D_REG, 0, 0 },  { op_shift, "SHIFT_LEFT", D_PS, 0, 0 },
    { op_shift,   "SHIFT_LEFT", D_WS, 0, 0 },   { op_shift, "SHIFT_LEFT", D_FB, 0, 0 },
    { op_shift,   "SHIFT_LEFT", D_PLL, 0, 0 },  { op_shift, "SHIFT_LEFT", D_MC, 0, 0 },
    { op_shift,   "SHIFT_RIGHT", D_REG, 0, 0 }, { op_shift, "SHIFT_RIGHT", D_PS, 0, 0 },
    { op_shift,   "SHIFT_RIGHT", D_WS, 0, 0 },  { op_shift, "SHIFT_RIGHT", D_FB, 0, 0 },
    { op_shift,   "SHIFT_RIGHT", D_PLL, 0, 0 }, { op_shift, "SHIFT_RIGHT", D_MC, 0, 0 },
    { op_destsrc, "MUL", D_REG, 0, 0 }, { op_destsrc, "MUL", D_PS, 0, 0 },
    { op_destsrc, "MUL", D_WS, 0, 0 },  { op_destsrc, "MUL", D_FB, 0, 0 },
    { op_destsrc, "MUL", D_PLL, 0, 0 }, { op_destsrc, "MUL", D_MC, 0, 0 },
    { op_destsrc, "DIV", D_REG, 0, 0 }, { op_destsrc, "DIV", D_PS, 0, 0 },
    { op_destsrc, "DIV", D_WS, 0, 0 },  { op_destsrc, "DIV", D_FB, 0, 0 },
    { op_destsrc, "DIV", D_PLL, 0, 0 }, { op_destsrc, "DIV", D_MC, 0, 0 },
    { op_destsrc, "ADD", D_REG, 0, 0 }, { op_destsrc, "ADD", D_PS, 0, 0 },
    { op_destsrc, "ADD", D_WS, 0, 0 },  { op_destsrc, "ADD", D_FB, 0, 0 },
    { op_destsrc, "ADD", D_PLL, 0, 0 }, { op_destsrc, "ADD", D_MC, 0, 0 },
    { op_destsrc, "SUB", D_REG, 0, 0 }, { op_destsrc, "SUB", D_PS, 0, 0 },
    { op_destsrc, "SUB", D_WS, 0, 0 },  { op_destsrc, "SUB", D_FB, 0, 0 },
    { op_destsrc, "SUB", D_PLL, 0, 0 }, { op_destsrc, "SUB", D_MC, 0, 0 },
    { op_1x16,    "SET_ATI_PORT",      D_hex16, 0, INDEX_ATI_PORT },
    { op_0x,      "SET_PCI_PORT",      D_null , 0, 0 },
    { op_0x,      "SET_SystemIO_PORT", D_null , 0, 0 },
    { op_1x16,    "SET_REG_BLOCK",     D_hex16, 0, 0 },
    { op_src,     "SET_FB_BASE",       D_hex16, 0, 0 },
    { op_destsrc, "COMP", D_REG, 0, 0 }, { op_destsrc, "COMP", D_PS, 0, 0 },
    { op_destsrc, "COMP", D_WS, 0, 0 },  { op_destsrc, "COMP", D_FB, 0, 0 },
    { op_destsrc, "COMP", D_PLL, 0, 0 }, { op_destsrc, "COMP", D_MC, 0, 0 },
    { op_switch,  "SWITCH", D_hex16, 0, 0 },
    { op_1x16,    "JUMP", D_hex16, 0, 0 },
    { op_1x16,    "JUMP_Equal", D_hex16, 0, 0 },
    { op_1x16,    "JUMP_Below", D_hex16, 0, 0 },
    { op_1x16,    "JUMP_Above", D_hex16, 0, 0 },
    { op_1x16,    "JUMP_BelowOrEq", D_hex16, 0, 0 },
    { op_1x16,    "JUMP_AboveOrEq", D_hex16, 0, 0 },
    { op_1x16,    "JUMP_NotEqual", D_hex16, 0, 0 },
    { op_destsrc, "TEST", D_REG, 0, 0 }, { op_destsrc, "TEST", D_PS, 0, 0 },
    { op_destsrc, "TEST", D_WS, 0, 0 },  { op_destsrc, "TEST", D_FB, 0, 0 },
    { op_destsrc, "TEST", D_PLL, 0, 0 }, { op_destsrc, "TEST", D_MC, 0, 0 },
    { op_1x8,     "DELAY_MilliSec", D_hex8, 0, 0 },
    { op_1x8,     "DELAY_MicroSec", D_hex8, 0, 0 },
    { op_1x8,     "CALL_TABLE", D_hex8, 0, INDEX_COMMAND_TABLE },
    { op_1x8,     "<!impl> REPEAT", D_hex8, 0, 0 },
    { op_dest,    "CLEAR", D_REG, 0, 0 }, { op_dest, "CLEAR", D_PS, 0, 0 },
    { op_dest,    "CLEAR", D_WS, 0, 0 },  { op_dest, "CLEAR", D_FB, 0, 0 },
    { op_dest,    "CLEAR", D_PLL, 0, 0 }, { op_dest, "CLEAR", D_MC, 0, 0 },
    { op_0x,      "NOP", D_null, 0, 0 },
    { op_0x,      "EOT", D_null, 0, 0 },
    { op_mask,    "MASK", D_REG, 0, 0 }, { op_mask, "MASK", D_PS, 0, 0 },
    { op_mask,    "MASK", D_WS, 0, 0 },  { op_mask, "MASK", D_FB, 0, 0 },
    { op_mask,    "MASK", D_PLL, 0, 0 }, { op_mask, "MASK", D_MC, 0, 0 },
    { op_1x8,     "POST_CARD", D_hex8, 0, 0 },
    { op_1x8,     "<!impl> BEEP", D_hex8, 0, 0 },
    { op_0x,      "<!doc> SAVE_REG", D_null, 0, 0 },
    { op_0x,      "<!doc> RESTORE_REG", D_null, 0, 0 },
    { op_1x8,     "SET_DATA_BLOCK", D_hex8, 0, INDEX_DATA_TABLE },
    { op_destsrc, "XOR", D_REG, 0, 0 }, { op_destsrc, "XOR", D_PS, 0, 0 },
    { op_destsrc, "XOR", D_WS, 0, 0 },  { op_destsrc, "XOR", D_FB, 0, 0 },
    { op_destsrc, "XOR", D_PLL, 0, 0 }, { op_destsrc, "XOR", D_MC, 0, 0 },
    { op_dest,    "<!doc> SHL", D_REG, 0, 0 }, { op_dest, "<!doc> SHL", D_PS, 0, 0 },
    { op_dest,    "<!doc> SHL", D_WS, 0, 0 },  { op_dest, "<!doc> SHL", D_FB, 0, 0 },
    { op_dest,    "<!doc> SHL", D_PLL, 0, 0 }, { op_dest, "<!doc> SHL", D_MC, 0, 0 },
    { op_dest,    "<!doc> SHR", D_REG, 0, 0 }, { op_dest, "<!doc> SHR", D_PS, 0, 0 },
    { op_dest,    "<!doc> SHR", D_WS, 0, 0 },  { op_dest, "<!doc> SHR", D_FB, 0, 0 },
    { op_dest,    "<!doc> SHR", D_PLL, 0, 0 }, { op_dest, "<!doc> SHR", D_MC, 0, 0 },
    { op_0x,      "<!doc> DEBUG", D_null, 0, 0 },
    { op_0x,      "<!doc> DS", D_null, 0, 0 },
    [0x80] = { op_0x, "<!impl> Extended", D_null, 0, 0 },
    [0xff] = { op_0x, "<reserved>", D_null, 0, 0 }
} ;


const char *align_source[] = {
    "XXXX",
    "..XX", ".XX.", "XX..",
    "...X", "..X.", ".X..", "X..."
};
const char *align_byte[] = { "...X", "..X.", ".X..", "X..." };
const char *align_word[] = { "..XX", ".XX.", "XX..", "/../" };
const char *align_long[] = { "XXXX", "////", "////", "////" };

const int   size_align[] = { 4, 2, 2, 2, 1, 1, 1, 1 };


const char *index_command_table[] = {
    "ASIC_Init", "GetDisplaySurfaceSize", "ASIC_RegistersInit",
    "VRAM_BlockVenderDetection", "SetClocksRatio", "MemoryControllerInit",
    "EnableCRTCMemReq", "MemoryParamAdjust", "DVOEncoderControl",
    "GPIOPinControl", "SetEngineClock", "SetMemoryClock",
    "SetPixelClock", "DynamicClockGating", "ResetMemoryDLL",
    "ResetMemoryDevice", "MemoryPLLInit", "AdjustDisplayPll",
    "AdjustMemoryController", "EnableASIC_StaticPwrMgt", "ASIC_StaticPwrMgtStatusChange",
    "DAC_LoadDetection", "LVTMAEncoderControl", "LCD1OutputControl",
    "DAC1EncoderControl", "DAC2EncoderControl", "DVOOutputControl",
    "CV1OutputControl", "GetConditionalGoldenSetting", "TVEncoderControl",
    "TMDSAEncoderControl", "LVDSEncoderControl", "TV1OutputControl",
    "EnableScaler", "BlankCRTC", "EnableCRTC",
    "GetPixelClock", "EnableVGA_Render", "EnableVGA_Access",
    "SetCRTC_Timing", "SetCRTC_OverScan", "SetCRTC_Replication",
    "SelectCRTC_Source", "EnableGraphSurfaces", "UpdateCRTC_DoubleBufferRegisters",
    "LUT_AutoFill", "EnableHW_IconCursor", "GetMemoryClock",
    "GetEngineClock", "SetCRTC_UsingDTDTiming", "ExternalEncoderControl",
    "LVTMAOutputControl", "VRAM_BlockDetectionByStrap", "MemoryCleanUp",
    "ReadEDIDFromHWAssistedI2C", "WriteOneByteToHWAssistedI2C", "ReadHWAssistedI2CStatus",
    "SpeedFanControl", "PowerConnectorDetection", "MC_Synchronization",
    "ComputeMemoryEnginePLL", "MemoryRefreshConversion", "VRAM_GetCurrentInfoBlock",
    "DynamicMemorySettings", "MemoryTraining", "EnableSpreadSpectrumOnPPLL",
    "TMDSAOutputControl", "SetVoltage", "DAC1OutputControl",
    "DAC2OutputControl", "SetupHWAssistedI2CStatus", "ClockSource",
    "MemoryDeviceInit", "EnableYUV", "DIG1EncoderControl",
    "DIG2EncoderControl", "DIG1TransmitterControl", "DIG2TransmitterControl",
    "ProcessAuxChannelTransaction", "DPEncoderService"
} ;

const char *index_data_table[] = {
    "UtilityPipeLine", "MultimediaCapabilityInfo", "MultimediaConfigInfo",
    "StandardVESA_Timing", "FirmwareInfo", "DAC_Info",
    "LVDS_Info", "TMDS_Info", "AnalogTV_Info",
    "SupportedDevicesInfo", "GPIO_I2C_Info", "VRAM_UsageByFirmware",
    "GPIO_Pin_LUT", "VESA_ToInternalModeLUT", "ComponentVideoInfo",
    "PowerPlayInfo", "CompassionateData", "SaveRestoreInfo",
    "PPLL_SS_Info", "OemInfo", "XTMDS_Info",
    "MclkSS_Info", "Object_Header", "IndirectIOAccess",
    "MC_InitParameter", "ASIC_VDDC_Info", "ASIC_InternalSS_Info",
    "TV_VideoMode", "VRAM_Info", "MemoryTrainingInfo",
    "IntegratedSystemInfo", "ASIC_ProfilingInfo", "VoltageObjectInfo",
    "PowerSourceInfo"
} ;


const char *index_ati_port[] = {
    "INDIRECT_IO_MM", "INDIRECT_IO_PLL", "INDIRECT_IO_MC", "INDIRECT_IO_PCIE"
} ;

const char *index_work_reg[] = {
    [WS_QUOTIENT]   = "WS_QUOT/LOW32", [WS_REMINDER]   = "WS_REMIND/HI32",
    [WS_DATAPTR]    = "WS_DATAPTR",    [WS_SHIFT]      = "WS_SHIFT",
    [WS_OR_MASK]    = "WS_OR_MASK",    [WS_AND_MASK]   = "WS_AND_MASK",
    [WS_FB_WINDOW]  = "WS_FB_WIN",     [WS_ATTRIBUTES] = "WS_ATTR"
} ;


struct index_table_s {
    const char  *name;
    const char **tab;
    int          len;
} ;
#define TABENTRY(x) { #x, (index_ ## x), sizeof (index_ ## x) / sizeof (const char **) }

const struct index_table_s index_tables[] = {
    [INDEX_COMMAND_TABLE] = TABENTRY (command_table),
    [INDEX_DATA_TABLE] =    TABENTRY (data_table),
    [INDEX_ATI_PORT] =      TABENTRY (ati_port),
    [INDEX_WORK_REG] =      TABENTRY (work_reg)
} ;


bios_tables_t *get_pointers (uint8_t *data)
{
    static bios_tables_t tabs;		/* FIXME: */

    tabs.base = data;
    tabs.AtomRomHeader = (ATOM_ROM_HEADER *) (data + *(uint16_t *) (data + OFFSET_TO_POINTER_TO_ATOM_ROM_HEADER));
    if (strcmp ((char *) tabs.AtomRomHeader->uaFirmWareSignature, "ATOM") != 0) {
	fprintf (stderr, "No AtomBIOS\n");
	exit (1);
    }
    tabs.MasterCommandTables = (uint16_t *)
	& ((ATOM_MASTER_COMMAND_TABLE *)
	   (data + tabs.AtomRomHeader->usMasterCommandTableOffset))
	->ListOfCommandTables;
    tabs.MasterDataTables    = (uint16_t *)
	& ((ATOM_MASTER_DATA_TABLE *)
	   (data + tabs.AtomRomHeader->usMasterDataTableOffset))
	->ListOfDataTables;
    
    return &tabs;
}


const char *get_index (int type, int val) {
    if (type < 0 || val < 0 ||
	type >= sizeof (index_tables) / sizeof (const struct index_table_s))
	return NULL;
    if (! index_tables[type].tab || val >= index_tables[type].len)
	return NULL;
    return index_tables[type].tab[val];
}


int sub_dest (uint8_t *d, char *out, int type, int align, int size, int index) {
    uint32_t    val;
    int         r;
    const char *ind;
    switch (type) {
    case D_REG:
	val  = *((uint16_t *) d);
	r    = 2;
	break;
    case D_ID:  case D_IM:
	out += sprintf (out, "<internal - illegal addrtype %s>", addrnames [type]);
	val  = 0;
	r    = 0;
	break;
    default:
	val = *d;
	r   = 1;
    }
    if (type == D_WS && (ind = get_index (INDEX_WORK_REG, val)) )
	out += sprintf (out, "%s", ind);
    else if (r)
	out += sprintf (out, addrtypes [type], val);
    switch (size) {
    case 1:
	out += sprintf (out, " [%s]", align_byte[align]);
	break;
    case 2:
	out += sprintf (out, " [%s]", align_word[align]);
	break;
    case 4:
	out += sprintf (out, " [%s]", align_long[align]);
	break;
    }
    if (r && (ind = get_index (index, val)) )
	out += sprintf (out, "  (%s)", ind);
    return r;
}
int sub_src (uint8_t *d, char *out, int type, int align, int size, int index) {
    uint32_t    val;
    int         r;
    const char *ind;
    switch (type) {
    case D_IM:
	r = size;
	break;
    case D_PS:  case D_WS:  case D_FB:  case D_PLL:  case D_MC:
	r = 1;
	break;
    case D_REG:  case D_ID:
	r = 2;
    }
    switch (r) {
    case 1:
	val = *d;
	break;
    case 2:
	val = *(uint16_t *)d;
	break;
    case 4:
	val = *(uint32_t *)d;
	break;
    }
    if (type == D_IM) {
	out += sprintf (out, addrtypes_im [size], val);
    } else if (type == D_WS && (ind = get_index (INDEX_WORK_REG, val)) ) {
	out += sprintf (out, "%s", ind);
	out += sprintf (out, " [%s]", align_source[align]);
    } else {
	out += sprintf (out, addrtypes [type], val);
	out += sprintf (out, " [%s]", align_source[align]);
    }
    if ( (ind = get_index (index, val)) )
	out += sprintf (out, "  (%s)", ind);
    return r;
}

int op_0x (uint8_t *d, char *out) {
    const optab_t *op = &optable[d[0]];
    strcpy (out, op->name);
    return 1;
}
int op_1x8 (uint8_t *d, char *out) {
    const optab_t *op = &optable[d[0]];
    const char    *ind;
    out += sprintf (out, "%-5s  ", op->name);
    out += sprintf (out, addrtypes [op->desttype], d[1]);
    if ( (ind = get_index (op->destindex, d[1])) )
	out += sprintf (out, "  (%s)", ind);
    return 2;
}
int op_1x16 (uint8_t *d, char *out) {
    const optab_t *op = &optable[d[0]];
    const char    *ind;
    out += sprintf (out, "%-5s  ", op->name);
    out += sprintf (out, addrtypes [op->desttype], *(uint16_t *) &d[1]);
    if ( (ind = get_index (op->destindex, d[1])) )
	out += sprintf (out, "  (%s)", ind);
    return 3;
}
int op_src (uint8_t *d, char *out) {
    const optab_t *op = &optable[d[0]];
    uint8_t       *t    = d+1;
    int            attr = *t++;
    out += sprintf (out, "%-5s  ", op->name);
    t   += sub_src (t, out, attr & 0x07, (attr & 0x38) >> 3, size_align[(attr & 0x38)>>3], op->srcindex);
    return t - d;
}
int op_dest (uint8_t *d, char *out) {
    const optab_t *op = &optable[d[0]];
    uint8_t *t    = d+1;
    int      attr = *t++;
    out += sprintf  (out, "%-5s  ", op->name);
    t   += sub_dest (t, out, op->desttype, attr >> 6, size_align[(attr & 0x38)>>3], op->destindex);
    return t - d;
}
int op_destsrc (uint8_t *d, char *out) {
    const optab_t *op = &optable[d[0]];
    uint8_t *t    = d+1;
    int      attr = *t++;
    out += sprintf  (out, "%-5s  ", op->name);
    t   += sub_dest (t, out, op->desttype, attr >> 6, size_align[(attr & 0x38)>>3], op->destindex);
    out += strlen   (out);
    out += sprintf  (out, "  <-  ");
    t   += sub_src  (t, out, attr & 0x07, (attr & 0x38) >> 3, size_align[(attr & 0x38)>>3], op->srcindex);
    return t - d;
}
int op_shift (uint8_t *d, char *out) {
    const optab_t *op = &optable[d[0]];
    uint8_t *t    = d+1;
    int      attr = *t++;
    out += sprintf  (out, "%-5s  ", op->name);
    t   += sub_dest (t, out, op->desttype, attr >> 6, size_align[(attr & 0x38)>>3], op->destindex);
    out += strlen   (out);
    out += sprintf  (out, "  by  %02x", *t++);
    return t - d;
}
int op_switch (uint8_t *d, char *out) {
    const optab_t *op = &optable[d[0]];
    uint8_t       *t    = d+1;
    int            attr = *t++;
    int            i = 0;
    /* Multiline, because even the hexdump typically needs lots of space */
    out += sprintf (out, "\n                          %-5s  ", op->name);
    t   += sub_src (t, out, attr & 0x07, (attr & 0x38) >> 3, size_align[(attr & 0x38)>>3], op->srcindex);
    out += strlen  (out);

    while (t[0] != 0x5a && t[1] != 0x5a) { /* EndOfSwitch: 2x NOP */
	if (*t++ != 'c') {
	    out += sprintf (out, "missing CASE for switch");
	    t   -= 3;
	    break;
	}
	if (! (i++ & 7))
	    out += sprintf (out, "\n       ");
	switch (size_align[(attr & 0x38)>>3]) {
	case 1:
	    out += sprintf (out, " %02x->", *t++);
	    break;
	case 2:
	    out += sprintf (out, " %04x->", *(uint16_t *)t);
	    t   += 2;
	    break;
	case 4:
	    out += sprintf (out, " %08x->", *(uint32_t *)t);
	    t   += 4;
	    break;
	}
	out += sprintf (out, "%04x", *(uint16_t *)t);
	t   += 2;
    }
    t += 2;
    return t - d;
}
int op_mask (uint8_t *d, char *out) {
    const optab_t *op = &optable[d[0]];
    uint8_t *t    = d+1;
    int      attr = *t++;
    out += sprintf  (out, "%-5s  ", op->name);
    t   += sub_dest (t, out, op->desttype, attr >> 6, size_align[(attr & 0x38)>>3], op->destindex);
    out += strlen   (out);
    out += sprintf  (out, "  &  ");
    t   += sub_src  (t, out, attr & 0x07, (attr & 0x38) >> 3, size_align[(attr & 0x38)>>3], 0);
    out += strlen   (out);
    out += sprintf  (out, "  |  ");
    t   += sub_src  (t, out, attr & 0x07, (attr & 0x38) >> 3, size_align[(attr & 0x38)>>3], 0);
    return t - d;
}


void do_info (bios_tables_t *tabs)
{
    fprintf (stdout,
	     "Table Format Rev.   %02x\n"
	     "Table Content Rev.  %02x\n"
	     "BIOS Boot Message:  '%s'\n"
	     "Subsystem Vendor ID %04x\n"
	     "Subsystem ID        %04x\n\n",
	     tabs->AtomRomHeader->sHeader.ucTableFormatRevision,
	     tabs->AtomRomHeader->sHeader.ucTableContentRevision,
	     (char *) (tabs->base + tabs->AtomRomHeader->usBIOS_BootupMessageOffset),
	     tabs->AtomRomHeader->usSubsystemVendorID,
	     tabs->AtomRomHeader->usSubsystemID);
}

void do_list (bios_tables_t *tabs)
{
    int i;
    const char *ind;

    fputs ("Command Tables:\n", stdout);
    for (i = 0; i < sizeof (ATOM_MASTER_LIST_OF_COMMAND_TABLES) / sizeof (uint16_t); i++) {
	if (tabs->MasterCommandTables[i])
	    fprintf (stdout, "  %04x:   %04x  Len %04x",
		     i, tabs->MasterCommandTables[i],
		     * (uint16_t *) (tabs->base + tabs->MasterCommandTables[i]));
	else
	    fprintf (stdout, "  %04x:   -             ", i);
	if ( (ind = get_index (INDEX_COMMAND_TABLE, i)) )
	    fprintf (stdout, "  (%s)", ind);
	putc ('\n', stdout);
    }
    fprintf (stdout, "\nData Tables:\n");
    for (i = 0; i < sizeof (ATOM_MASTER_LIST_OF_DATA_TABLES) / sizeof (uint16_t); i++) {
	if (tabs->MasterDataTables[i])
	    fprintf (stdout, "  %04x:   %04x  Len %04x",
		     i, tabs->MasterDataTables[i],
		     * (uint16_t *) (tabs->base + tabs->MasterDataTables[i]));
	else
	    fprintf (stdout, "  %04x:   -             ", i);
	if ( (ind = get_index (INDEX_DATA_TABLE, i)) )
	    fprintf (stdout, "  (%s)", ind);
#ifdef USE_ATOMBIOS_RELATED_STUFF
	if (i >= 0 && data_dumpers[i])	/* TODO: no size check */
	    fprintf (stdout, "    (struct size %04x)", data_dumpers[i](NULL, 0));
#endif
	putc ('\n', stdout);
    }
    putc ('\n', stdout);
}

int do_tableinfo (uint8_t *data, int off, int type, int nr)
{
    int size = * (uint16_t *) (data+off);
    int frev = *              (data+off+2);
    int crev = *              (data+off+3);
    const char *ind = get_index (type, nr);

    fprintf (stdout, "%s  %08x", index_tables[type].name, off);
    if (nr >= 0)
	fprintf (stdout, "  #%02x  (%s)", nr, ind ? ind:"<unknown>");
    fputs (":\n\n", stdout);
    
    if (off)
	fprintf (stdout,
		 "  Size         %04x\n"
		 "  Format Rev.  %02x\n"
		 "  Param Rev.   %02x\n"
		 "  Content Rev. %02x\n",
		 size, frev & 0x0f, frev >> 4, crev);

    if (type == INDEX_COMMAND_TABLE) {
	int attr = * (uint16_t *) (data+off+4);
	fprintf (stdout,
		 "  Attributes:  Work space size        %02x longs\n"
		 "               Parameter space size   %02x longs\n"
		 "               Table update indicator %x\n",
		 (attr & 0xff) >> 2, (attr & 0x7f00) >> (8+2), attr >> 15);
    }
    putc ('\n', stdout);
    
    return size;
}

void do_dump (uint8_t *data, int start, int end)
{
    int i, j;

    for (i = start & -16; i < end; i += 16) {
	fprintf (stdout, "  %08x: ", i);
	for (j = i; j < i+16; j++) {
	    if (j >= start && j < end)
		fprintf (stdout, "%02x", data[j]);
	    else
		fputs ("  ", stdout);
	    if ((j & 1) == 1)
		putc (' ', stdout);
	    if ((j & 3) == 3)
		putc (' ', stdout);
	}
	fputs ("  ", stdout);
	for (j = i; j < i+16; j++) {
	    if (j >= start && j < end) {
		if (isprint (data[j]))
		    putc (data[j], stdout);
		else
		    putc ('.', stdout);
	    } else
		putc (' ', stdout);
	}
	putc ('\n', stdout);
    }
    putc ('\n', stdout);
}

#ifdef USE_ATOMBIOS_RELATED_STUFF
void do_data (uint8_t *data, int off, int nr)
{
    int len;
    if (nr >= 0 && data_dumpers[nr]) {	/* TODO: no size check */
	len = data_dumpers[nr] (data+off, 1);
	fprintf (stdout, "\n  Total data structure size:  %04x\n\n", len);
    }
}
#endif

void do_diss (uint8_t *data, int off, int size)
{
    int j, len;
    uint8_t  *d = data + off;
    char buf[256];

    for (d = data + off; d < data+size; d += len) {
	if (optable[*d].process) {
	    len = optable[*d].process (d, buf);
	} else {
	    sprintf (buf, "<unknown> %02x", *d);
	    len = 1;
	}
	fprintf (stdout, "  %04x: ", d - data);
	for (j = 0; j < len; j++) {
	    if (j && ! (j & 31))
		fprintf (stdout, "\n        ");
	    fprintf (stdout, "%02x", d[j]);
	}
	fputs (&"                "[j>8?16:j<<1], stdout);
	fprintf (stdout, "  %s\n", buf);
    }
    putc ('\n', stdout);
}

void do_test (uint8_t *data)
{
    int i, j;
    for (i = 0; i < 0x100; i++) {
	if (! optable[i].name)
	    fprintf (stdout, "%02x:  -\n", i);
	else if (optable[i].desttype < 8)
	    fprintf (stdout, "%02x:  %s_%s\n", i, optable[i].name, addrnames[optable[i].desttype]);
	else
	    fprintf (stdout, "%02x:  %s  (%s)\n", i, optable[i].name, addrnames[optable[i].desttype]);
    }
    for (i = 0; i < sizeof (index_tables) / sizeof (struct index_table_s); i++) {
	fprintf (stdout, "\nindex_table %s len %02x\n ", index_tables[i].name, index_tables[i].len);
	for (j = 0; j < index_tables[i].len; j++)
	    fprintf (stdout, " %02x=%s", j, index_tables[i].tab[j]);
	putc ('\n', stdout);
    }
    putc ('\n', stdout);
}


void usage (char *argv[])
{
    fprintf (stderr, "Usage:  %s [<opts>] <file> <cmd> [<cmd>...]\n"
	     "Opts:   -o <vga_offset>      Specify offset of VGA bios in <file>\n"
	     "Cmds:   i                    Dump info on AtomBIOS\n"
	     "        l                    Info + Table list\n"
	     "        x <start> <len>      Hexdump\n"
	     "        d <nr>               Data table dump\n"
	     "        c <nr>               Command table disasm\n"
	     "        C <start>            Table disasm (debug)\n"
	     "        T                    Test (debug)\n"
	     "all values in hex\n",
	     argv[0]);
    exit (1);
}

int main (int argc, char *argv[])
{
    int            c;
    int            opt_off = 0;
    char         **arg;
    int            fdmem;
    uint8_t       *data;
    bios_tables_t *tabs;
    const char    *ind;
    int            off, start, len;

    opterr = 0;
    while ( (c = getopt (argc-1, argv+1, "o:")) != -1)
	switch (c) {
	case 'o':
	    opt_off = strtol (optarg, NULL, 16);
	    break;
	default:
	    usage (argv);
	}

    if (! argv[optind])
	usage (argv);

    if ( (fdmem = open (argv[optind], O_RDONLY)) == -1) {
	perror (argv[optind]);
	return 1;
    }
    
    if ( (data = mmap (NULL, MMAP_SIZE, PROT_READ, MAP_PRIVATE, fdmem, opt_off))
	 == (void *) -1) {
	perror ("mmap()");
	return 1;
    }

    for (arg = &argv[optind+1]; *arg && **arg; arg++) {
	if (arg[0][1])
	    usage (argv);
	switch (arg[0][0]) {
	case 'i':
	    tabs = get_pointers (data);
	    do_info (tabs);
	    break;
	case 'l':
	    tabs = get_pointers (data);
	    do_info (tabs);
	    do_list (tabs);
	    break;
	case 'x':
	    start = strtol (arg[1], NULL, 16);
	    len   = strtol (arg[2], NULL, 16);
	    arg  += 2;
	    do_dump (data, start, start+len);
	    break;
	case 'd':
	    start = strtol (arg[1], NULL, 16);
	    arg++;
	    tabs  = get_pointers (data);
	    off   = tabs->MasterDataTables [start];
	    len   = do_tableinfo (data, off, INDEX_DATA_TABLE, start);
	    if (off) {
//		fputs ("Header:\n", stdout);
//		do_dump (data + off, 0, 4);
//		fputs ("Data:\n", stdout);
		do_dump (data + off, 4, len);
#ifdef USE_ATOMBIOS_RELATED_STUFF
		do_data (data + off, 0, start);
#endif
	    }
	    break;
	case 'c':
	    start = strtol (arg[1], NULL, 16);
	    arg++;
	    tabs  = get_pointers (data);
	    off   = tabs->MasterCommandTables [start];
	    ind   = get_index (INDEX_COMMAND_TABLE, start);
	    len   = do_tableinfo (data, off, INDEX_COMMAND_TABLE, start);
	    if (off)
		do_diss (data + off, 6, len);
	    break;
	case 'C':
	    off   = strtol (arg[1], NULL, 16);
	    arg++;
	    len   = do_tableinfo (data, off, INDEX_COMMAND_TABLE, -1);
	    do_diss (data + off, 6, len);
	    break;
	case 'T':
	    do_test (data);
	    break;
	default:
	    usage (argv);
	}
    }

    munmap (data, MMAP_SIZE);
    close  (fdmem);
    return 0;
}