intel_fw 0.1.2

Parsing and editing library for Intel firmware images
Documentation
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
//! Intel Flash Descriptor (IFD)
//!
//! The IFD was extended over time; for reference,
//! see <https://www.intel.com/content/dam/www/public/us/en/documents/datasheets/io-controller-hub-8-datasheet.pdf>
//! and <https://www.intel.com/content/dam/doc/datasheet/7300-chipset-memory-controller-hub-datasheet.pdf>
//! and <https://www.intel.com/content/www/us/en/content-details/332690/intel-100-series-chipset-family-platform-controller-hub-pch-datasheet-volume-1.html>
//! and <https://www.intel.com/content/www/us/en/content-details/332691/intel-100-series-chipset-family-platform-controller-hub-pch-datasheet-volume-2.html>
//! and <https://edc.intel.com/content/www/us/en/design/ipla/software-development-platforms/client/platforms/alder-lake-mobile-p/intel-600-series-chipset-family-on-package-platform-controller-hub-pch-datash/002/>
//! and <https://www.intel.com/content/www/us/en/content-details/710279/intel-600-series-and-intel-700-series-chipset-family-on-package-platform-controller-hub-pch-datasheet-volume-2-of-2.html>
//! and <https://opensecuritytraining.info/IntroBIOS_files/Day2_02_Advanced%20x86%20-%20BIOS%20and%20SMM%20Internals%20-%20Flash%20Descriptor.pdf>
//! and coreboot `util/ifdtool/`.
//!
//! The IFD consists of multiple sections and fields, which got more over generations
//! of processors. While the ICH8 datasheet still detailed the sections and fields,
//! some semantics changed over time, without public documentation from Intel.
//! Unfortunately, there is no other single source of truth documenting which
//! processors would require which exact fields, either. One major change came with
//! Skylake, as per coreboot commit `1f7fd720c81755144423f2d4062c39cc651adc0a`.
//! The following table is based on the 600 series chipset PCH datasheet.
//! The rough sections have generally stayed the same, but not the fields.
//! Offsets of specific sections are described via the Descriptor Map,
//! called base addresses, commonly abbreviation as xxBA.
//! NOTE: The base addresses are compact values and really mean bits 4..11
//! of 25-bit values, so we nead to expand them to get the real addresses.
//! See the implementations for the calculations.
//!
//! | Section                      | Meaning                                |
//! | ---------------------------- | -------------------------------------- |
//! | Signature + Descriptor Map   | Offsets of other sections              |
//! | Components                   | Flash parts and their parameters       |
//! | Regions                      | Flash partitions as offsets            |
//! | Masters                      | Access control for regions             |
//! | PCH Soft Straps              | Platform specific control bits         |
//! | Reserved                     |                                        |
//! | Management Engine VSCC Table | Vendor-specific component capabilities |
//! | Descriptor Upper Map         |                                        |
//! | OEM Section                  |                                        |
//!
//! For a list of acronyms, see the Serial Peripheral Interface (SPI) section
//! in the 400 or 600 series chipset PCH datasheet volume 1.
//! <https://edc.intel.com/content/www/us/en/design/ipla/software-development-platforms/client/platforms/alder-lake-mobile-p/intel-600-series-chipset-family-on-package-platform-controller-hub-pch-datash/serial-peripheral-interface-spi/>

// We retain the all-uppercase acronyms in the struct definitions.
// Lowercase helpers are provided through implementations.
#![allow(non_snake_case)]

use std::{
    fmt::{Debug, Display},
    ops::Range,
};

use bitfield_struct::bitfield;
use serde::{Deserialize, Serialize};
use zerocopy::{FromBytes, IntoBytes};
use zerocopy_derive::{FromBytes, Immutable, IntoBytes};

use crate::{EMPTY, me::Generation, ver::Version};

// NOTE: This is the LE representation.
const MAGIC: u32 = 0x0ff0_a55a;
// This is based on examples, excluding the VSCC table, upper descriptor map and
// OEM section.
const SIZE: usize = 0x800;

#[bitfield(u32)]
#[derive(Immutable, IntoBytes, FromBytes, Serialize, Deserialize)]
pub struct FLMAP0 {
    FCBA: u8,
    #[bits(2)]
    NC: u8,
    #[bits(6)]
    _0: u8,
    FRBA: u8,
    #[bits(3)]
    NR: u8,
    #[bits(5)]
    _1: u8,
}

impl FLMAP0 {
    fn fcba(self) -> usize {
        (self.FCBA() as usize) << 4
    }
    fn nc(self) -> usize {
        self.NC() as usize + 1
    }

    fn frba(self) -> usize {
        (self.FRBA() as usize) << 4
    }
    fn nr(self) -> usize {
        self.NR() as usize + 1
    }
}

impl Display for FLMAP0 {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let fcba = self.fcba();
        let nc = self.nc();
        let frba = self.frba();
        let nr = self.nr();
        let c = format!("        components:  {nc}, base: 0x{fcba:08x}");
        let r = format!("           regions:  {nr}, base: 0x{frba:08x}");
        write!(f, "{c}\n{r}")
    }
}

#[bitfield(u32)]
#[derive(Immutable, IntoBytes, FromBytes, Serialize, Deserialize)]
pub struct FLMAP1 {
    FMBA: u8,
    #[bits(3)]
    NM: u8,
    #[bits(5)]
    _0: u8,
    FISBA: u8,
    ISL: u8,
}

impl FLMAP1 {
    fn fmba(self) -> usize {
        (self.FMBA() as usize) << 4
    }
    fn nm(self) -> usize {
        self.NM() as usize + 1
    }

    fn fisba(self) -> usize {
        (self.FISBA() as usize) << 4
    }
    fn isl(self) -> usize {
        self.ISL() as usize
    }
}

impl Display for FLMAP1 {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let fmba = self.fmba();
        let nm = self.nm();
        // NOTE: On later platforms, FISBA was changed into FPSBA (PCH Strap).
        let fisba = self.fisba();
        let isl = self.isl();
        let m = format!("           masters:  {nm}, base: 0x{fmba:08x}");
        let s = format!("   ICH8/PCH straps: {isl:2}, base: 0x{fisba:08x}");
        write!(f, "{m}\n{s}")
    }
}

#[bitfield(u32)]
#[derive(Immutable, IntoBytes, FromBytes, Serialize, Deserialize)]
pub struct FLMAP2 {
    FMSBA: u8,
    MSL: u8,
    _0: u16,
}

impl FLMAP2 {
    fn fmsba(self) -> usize {
        (self.FMSBA() as usize) << 4
    }
    fn msl(self) -> usize {
        self.MSL() as usize
    }
}

// Only for 100 up to 900 series chipset PCHs, per coreboot util/ifdtool
impl Display for FLMAP2 {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let fmsba = self.fmsba();
        // coreboot calls this PSL
        let msl = self.msl();
        write!(f, "        MCH straps: {msl:2}, base: 0x{fmsba:08x}")
    }
}

#[derive(Immutable, IntoBytes, FromBytes, Serialize, Deserialize, Clone, Copy, Debug)]
#[repr(C)]
pub struct Header {
    magic: u32,
    flmap0: FLMAP0,
    flmap1: FLMAP1,
    flmap2: FLMAP2, // 100x series
    flmap3: u32,    // TODO: 500, 600, 800 and 900 series
}

#[derive(Serialize, Deserialize, Clone, Copy, Debug)]
enum Density {
    K512,
    M1,
    M2,
    M4,
    M8,
    M16,
    _Undefined,
    _Reserved,
}

impl Density {
    const fn from_bits(val: u8) -> Self {
        match val {
            0b000 => Self::K512,
            0b001 => Self::M1,
            0b010 => Self::M2,
            0b011 => Self::M4,
            0b100 => Self::M8,
            0b101 => Self::M16,
            0b111 => Self::_Reserved,
            _ => Self::_Undefined,
        }
    }

    const fn into_bits(self) -> u8 {
        self as u8
    }
}

#[derive(Serialize, Deserialize, Clone, Copy, Debug)]
enum Frequency {
    M20,
    M33,
    M48,
    M50_30,
    M17,
    _Undefined,
    _Reserved,
}

impl Frequency {
    const fn from_bits(val: u8) -> Self {
        match val {
            0b000 => Self::M20,
            0b001 => Self::M33,
            0b010 => Self::M48,
            0b011 => Self::_Undefined,
            0b100 => Self::M50_30,
            0b101 => Self::_Undefined,
            0b110 => Self::M17,
            _ => Self::_Reserved,
        }
    }

    const fn into_bits(self) -> u8 {
        self as u8
    }
}

#[bitfield(u32)]
#[derive(Immutable, IntoBytes, FromBytes, Serialize, Deserialize)]
pub struct FlashComponentConfig {
    #[bits(3)]
    comp1_density: Density,
    #[bits(3)]
    comp2_density: Density,
    #[bits(2)]
    _r: u8,

    #[bits(8)]
    _r: u8,

    #[bits(1)]
    _r: u8,
    #[bits(3)]
    read_clock_frequency: Frequency,
    fast_read_support: bool,
    #[bits(3)]
    fast_read_clock_frequency: Frequency,

    #[bits(3)]
    write_erase_clock_frequency: Frequency,
    #[bits(3)]
    read_id_status_clock_frequency: Frequency,
    #[bits(2)]
    _r: u8,
}

#[derive(Immutable, IntoBytes, FromBytes, Serialize, Deserialize, Clone, Copy, Debug)]
pub struct FlashInvalidInstructions {
    inst1: u8,
    inst2: u8,
    inst3: u8,
    inst4: u8,
}

#[derive(Immutable, IntoBytes, FromBytes, Serialize, Deserialize, Clone, Copy, Debug)]
#[repr(C, packed)]
pub struct Components {
    FLCOMP: FlashComponentConfig,
    FLILL0: FlashInvalidInstructions,
    FLILL1: FlashInvalidInstructions,
}

#[bitfield(u32)]
#[derive(Immutable, IntoBytes, FromBytes, Serialize, Deserialize)]
pub struct FlashRegion {
    #[bits(13)]
    base: u32,
    #[bits(3)]
    _0: u8,
    #[bits(13)]
    limit: u32,
    #[bits(3)]
    _1: u8,
}

impl FlashRegion {
    fn ba(self) -> usize {
        self.base() as usize * 4096
    }
    fn la(self) -> usize {
        self.limit() as usize * 4096 + 4095
    }

    pub fn range(self) -> Range<usize> {
        self.ba()..self.la() + 1
    }
}

impl Display for FlashRegion {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let b = self.ba();
        let l = self.la();
        let u = if b > l { " (unused)" } else { "" };
        write!(f, "{b:08x} - {l:08x}{u}")
    }
}

#[derive(Immutable, IntoBytes, FromBytes, Serialize, Deserialize, Clone, Copy, Debug)]
#[repr(C)]
pub struct Regions {
    pub flreg0: FlashRegion,
    pub flreg1: FlashRegion,
    pub flreg2: FlashRegion,
    pub flreg3: FlashRegion,
    pub flreg4: FlashRegion,
    pub flreg5: FlashRegion,
    pub flreg6: FlashRegion,
    pub flreg7: FlashRegion,
    pub flreg8: FlashRegion,
    pub flreg9: FlashRegion,
}

impl Regions {
    pub fn ifd_range(&self) -> Range<usize> {
        self.flreg0.range()
    }
    pub fn bios_range(&self) -> Range<usize> {
        self.flreg1.range()
    }
    pub fn me_range(&self) -> Range<usize> {
        self.flreg2.range()
    }
}

// NOTE: Regions have changed over processors generations.
impl Display for Regions {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let r0 = format!("   Flash descriptor (IFD):   {}", self.flreg0);
        let r1 = format!("   BIOS (host) firmware:     {}", self.flreg1);
        let r2 = format!("   (CS)ME firmware:          {}", self.flreg2);
        let r3 = format!("   Gigabit ethernet data:    {}", self.flreg3);
        let r4 = format!("   Platform data:            {}", self.flreg4);
        let r5 = format!("   Embedded controller (EC): {}", self.flreg5);
        write!(f, "{r0}\n{r1}\n{r2}\n{r3}\n{r4}\n{r5}")
    }
}

#[bitfield(u32)]
#[derive(Immutable, IntoBytes, FromBytes, Serialize, Deserialize)]
pub struct FlashMasterV1 {
    _r: u16,
    // read access
    read_fd: bool,
    read_bios: bool,
    read_me: bool,
    read_gbe: bool,
    read_pd: bool,
    #[bits(3)]
    _r: u8,
    // write access
    write_fd: bool,
    write_bios: bool,
    write_me: bool,
    write_gbe: bool,
    write_pd: bool,
    #[bits(3)]
    _r: u8,
}

fn cap_to_str(cap: bool) -> &'static str {
    if cap { "enabled" } else { "disabled" }
}

impl Display for FlashMasterV1 {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let c = cap_to_str(self.write_pd());
        writeln!(f, "  Platform Data Region Write Access: {c}")?;
        let c = cap_to_str(self.write_gbe());
        writeln!(f, "  GbE Region Write Access:           {c}")?;
        let c = cap_to_str(self.write_me());
        writeln!(f, "  Intel ME Region Write Access:      {c}")?;
        let c = cap_to_str(self.write_bios());
        writeln!(f, "  Host CPU/BIOS Region Write Access: {c}")?;
        let c = cap_to_str(self.write_fd());
        writeln!(f, "  Flash Descriptor Write Access:     {c}")?;

        let c = cap_to_str(self.read_pd());
        writeln!(f, "  Platform Data Region Read Access:  {c}")?;
        let c = cap_to_str(self.read_gbe());
        writeln!(f, "  GbE Region Read Access:            {c}")?;
        let c = cap_to_str(self.read_me());
        writeln!(f, "  Intel ME Region Read Access:       {c}")?;
        let c = cap_to_str(self.read_bios());
        writeln!(f, "  Host CPU/BIOS Region Read Access:  {c}")?;
        let c = cap_to_str(self.read_fd());
        writeln!(f, "  Flash Descriptor Read Access:      {c}")?;
        write!(f, "")
    }
}

#[bitfield(u32)]
#[derive(Immutable, IntoBytes, FromBytes, Serialize, Deserialize)]
pub struct FlashMasterV2 {
    // 0..7
    read_gbe10_1: bool,
    #[bits(3)]
    _r: u8,
    write_gbe10_1: bool,
    #[bits(3)]
    _r: u8,
    // 8..15
    read_fd: bool,
    read_bios: bool,
    read_me: bool,
    read_gbe: bool,
    read_pd: bool,
    #[bits(3)]
    _r: u8,
    // 16..23
    read_ec: bool,
    #[bits(2)]
    _r: u8,
    read_gbe10_0: bool,
    write_fd: bool,
    write_bios: bool,
    write_me: bool,
    write_gbe: bool,
    // 24..31
    write_pd: bool,
    #[bits(3)]
    _r: u8,
    write_ec: bool,
    #[bits(2)]
    _r: u8,
    write_gbe10_0: bool,
}

impl Display for FlashMasterV2 {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let c = cap_to_str(self.write_ec());
        writeln!(f, "  EC Region Write Access:            {c}")?;
        let c = cap_to_str(self.write_pd());
        writeln!(f, "  Platform Data Region Write Access: {c}")?;
        let c = cap_to_str(self.write_gbe());
        writeln!(f, "  GbE Region Write Access:           {c}")?;
        let c = cap_to_str(self.write_me());
        writeln!(f, "  Intel ME Region Write Access:      {c}")?;
        let c = cap_to_str(self.write_bios());
        writeln!(f, "  Host CPU/BIOS Region Write Access: {c}")?;
        let c = cap_to_str(self.write_fd());
        writeln!(f, "  Flash Descriptor Write Access:     {c}")?;

        let c = cap_to_str(self.read_ec());
        writeln!(f, "  EC Region Read Access:             {c}")?;
        let c = cap_to_str(self.read_pd());
        writeln!(f, "  Platform Data Region Read Access:  {c}")?;
        let c = cap_to_str(self.read_gbe());
        writeln!(f, "  GbE Region Read Access:            {c}")?;
        let c = cap_to_str(self.read_me());
        writeln!(f, "  Intel ME Region Read Access:       {c}")?;
        let c = cap_to_str(self.read_bios());
        writeln!(f, "  Host CPU/BIOS Region Read Access:  {c}")?;
        let c = cap_to_str(self.read_fd());
        writeln!(f, "  Flash Descriptor Read Access:      {c}")?;
        write!(f, "")
    }
}

#[derive(Serialize, Deserialize, Clone)]
#[repr(C)]
pub struct IFD {
    pub header: Header,
    pub components: Components,
    pub regions: Regions,
    pub masters: Vec<u32>,
    pub pch_straps: Vec<u32>,
    pub mch_straps: Vec<u32>,
}

impl Display for IFD {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        writeln!(f, "== Configuration ==")?;
        writeln!(f, "{}", self.header.flmap0)?;
        writeln!(f, "{}", self.header.flmap1)?;
        writeln!(f, "{}", self.header.flmap2)?;
        writeln!(f, "== Components ==")?;
        writeln!(f, "{:#02x?}", self.components)?;
        writeln!(f, "== Regions ==")?;
        write!(f, "{}", self.regions)
    }
}

impl Debug for IFD {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        writeln!(f, "{self}")?;
        writeln!(f, "== ICH/PCH Straps ==")?;
        for (i, s) in self.pch_straps.iter().enumerate() {
            writeln!(f, "  {i:2}: {s:08x}")?;
        }
        writeln!(f, "== MCH Straps ==")?;
        for (i, s) in self.mch_straps.iter().enumerate() {
            writeln!(f, "  {i:2}: {s:08x}")?;
        }
        write!(f, "")
    }
}

/// Extract a bit from a given byte, as bool.
fn extract_bit(straps: &[u32], byte: usize, bit: u32) -> bool {
    straps[byte] >> bit & 1 == 1
}

/// Set or clear a bit in a given strap, identified by its number.
fn set_bit(straps: &mut [u32], byte: usize, bit: u32, s: bool) {
    let b = straps[byte];
    straps[byte] = b & !(1 << bit) | (u32::from(s) << bit);
}

// TODO: The straps changed over the generations of processors.
// Specifically the HAP bit on Skylake and later has moved, so we should not
// blindly assume it.
impl IFD {
    // TODO: What is CSE in debug mode?
    // https://review.coreboot.org/c/coreboot/+/88307/5

    /// Direct Connect Interface
    // from <https://review.coreboot.org/c/coreboot/+/82272>
    // <https://edc.intel.com/content/www/us/en/design/products-and-solutions/processors-and-chipsets/700-series-chipset-family-platform-controller-hub-datasheet-volume-1-of/004/intel-direct-connect-interface-dci/>
    pub fn dci(&self) -> bool {
        extract_bit(&self.pch_straps, 0, 17)
    }
    /// Direct Connect Interface
    pub fn set_dci(&mut self, s: bool) {
        set_bit(&mut self.pch_straps, 0, 17, s);
    }

    // TODO: there is a _different_ soft-disable feature
    // https://review.coreboot.org/c/coreboot/+/78911/comments/61e2b541_b4faa3e4
    // TODO: make ME version a parameter to infer platform
    /// High-Assurance Platform (ME soft-disable), ME Gen 3
    pub fn hap(&self) -> bool {
        extract_bit(&self.pch_straps, 0, 16)
    }
    /// High-Assurance Platform (ME soft-disable), ME Gen 3
    pub fn set_hap(&mut self, s: bool) {
        set_bit(&mut self.pch_straps, 0, 16, s);
    }

    /// I/O Controller Hub, ME Gen 1
    pub fn ich_me_disabled(&self) -> bool {
        extract_bit(&self.pch_straps, 0, 0)
    }
    /// I/O Controller Hub, ME Gen 1
    pub fn set_ich_me_disabled(&mut self, s: bool) {
        set_bit(&mut self.pch_straps, 0, 0, s);
    }

    /// Memory Controller Hub, ME Gen 1
    pub fn mch_me_disabled(&self) -> bool {
        extract_bit(&self.mch_straps, 0, 0)
    }
    /// Memory Controller Hub, ME Gen 1
    pub fn set_mch_me_disabled(&mut self, s: bool) {
        set_bit(&mut self.mch_straps, 0, 0, s);
    }

    /// Memory Controller Hub (alternative), ME Gen 1
    pub fn mch_alt_me_disabled(&self) -> bool {
        extract_bit(&self.mch_straps, 0, 7)
    }
    /// Memory Controller Hub (alternative), ME Gen 1
    pub fn set_mch_alt_me_disabled(&mut self, s: bool) {
        set_bit(&mut self.mch_straps, 0, 7, s);
    }

    /// Disable ME (alternative), ME Gen 2
    pub fn alt_me_disabled(&self) -> bool {
        extract_bit(&self.pch_straps, 10, 7)
    }
    /// Disable ME (alternative), ME Gen 2
    pub fn set_alt_me_disabled(&mut self, s: bool) {
        set_bit(&mut self.pch_straps, 10, 7, s);
    }

    /// Disable ME for ME generation 3.
    /// Requires passing the ME version in order to infer the platform.
    pub fn disable_me_gen3(&mut self, me_ver: &Option<Version>) -> Result<(), String> {
        if let Some(ver) = me_ver {
            match ver.major {
                11 => self.set_hap(true),
                _ => return Err("ME > 11 not yet supported".into()),
            }
        }
        Ok(())
    }

    /// Disable the ME using any mechanism given the ME generation and version.
    pub fn disable_me(
        &mut self,
        me_gen: &Generation,
        me_ver: &Option<Version>,
    ) -> Result<(), String> {
        match me_gen {
            Generation::Gen1 => {
                self.set_ich_me_disabled(true);
                self.set_mch_me_disabled(true);
                // NOTE: coreboot ifdtool would also set the AltMeDisable bit here.
                // TODO: self.set_alt_me_disabled(true);
                Ok(())
            }
            Generation::Gen2 => {
                self.set_alt_me_disabled(true);
                Ok(())
            }
            Generation::Gen3 => self.disable_me_gen3(me_ver),
            _ => Err("Unknown ME generation/version".into()),
        }
    }
}

impl IFD {
    pub fn to_vec(self) -> Vec<u8> {
        let mut res = vec![EMPTY; SIZE];
        let components_offset = self.header.flmap0.fcba();
        let regions_offset = self.header.flmap0.frba();
        let masters_offset = self.header.flmap1.fmba();
        let pch_straps_offset = self.header.flmap1.fisba();
        let mch_straps_offset = self.header.flmap2.fmsba();

        for (o, b) in self.header.as_bytes().iter().enumerate() {
            res[OFFSET + o] = *b;
        }

        for (o, b) in self.components.as_bytes().iter().enumerate() {
            res[components_offset + o] = *b;
        }
        for (o, b) in self.regions.as_bytes().iter().enumerate() {
            res[regions_offset + o] = *b;
        }
        for (o, b) in self.masters.as_bytes().iter().enumerate() {
            res[masters_offset + o] = *b;
        }

        for (o, b) in self.pch_straps.as_bytes().iter().enumerate() {
            res[pch_straps_offset + o] = *b;
        }
        for (o, b) in self.mch_straps.as_bytes().iter().enumerate() {
            res[mch_straps_offset + o] = *b;
        }

        res
    }
}

const OFFSET: usize = 16;

// NOTE: We cannot use NM here (number of "masters").
// It is not what it suggests, or found to be not matching the actual
// count on real firmware images. What is the real number?
// Do we have to infer it from non-all-ff u32's up to the regions?
// Or should we adjust it after looking at the regions?
// Their count is not clear either.
const REGION_COUNT: usize = 8;

#[derive(Serialize, Deserialize, Clone, Debug)]
pub enum IfdError {
    NoIfd(String),
    DataTooSmall(String),
    ParserError(String),
    OutOfBounds(String),
}

fn u8_slice_to_u32(slice: &[u8]) -> Vec<u32> {
    slice
        .chunks(4)
        .map(|v| u32::from_le_bytes([v[0], v[1], v[2], v[3]]))
        .collect()
}

impl IFD {
    pub fn parse(data: &[u8]) -> Result<Self, IfdError> {
        if data.len() < OFFSET {
            return Err(IfdError::DataTooSmall(
                "Not enough data: need at least 4096 bytes".into(),
            ));
        }
        let header = match Header::read_from_prefix(&data[OFFSET..]) {
            Ok((r, _)) => r,
            Err(e) => return Err(IfdError::ParserError(format!("IFD header: {e:?}"))),
        };

        if header.magic != MAGIC {
            return Err(IfdError::NoIfd(format!(
                "IFD magic not as expected, got: {:08x}, wanted: {MAGIC:08x}",
                header.magic
            )));
        }

        let components_offset = header.flmap0.fcba();
        let regions_offset = header.flmap0.frba();
        let masters_offset = header.flmap1.fmba();
        let pch_straps_offset = header.flmap1.fisba();
        let mch_straps_offset = header.flmap2.fmsba();

        if components_offset > data.len() {
            return Err(IfdError::OutOfBounds(format!(
                "Components @ {components_offset:08x}"
            )));
        }
        let components = match Components::read_from_prefix(&data[components_offset..]) {
            Ok((r, _)) => r,
            Err(e) => return Err(IfdError::ParserError(format!("{e:?}"))),
        };

        if regions_offset > data.len() {
            return Err(IfdError::OutOfBounds(format!(
                "Regions @ {regions_offset:08x}"
            )));
        }
        let regions = match Regions::read_from_prefix(&data[regions_offset..]) {
            Ok((r, _)) => r,
            Err(e) => return Err(IfdError::ParserError(format!("{e:?}"))),
        };

        let masters_end = masters_offset + REGION_COUNT * 4;
        if masters_offset > data.len() || masters_end > data.len() {
            return Err(IfdError::OutOfBounds(format!(
                "Masters @ {masters_offset:08x}..{masters_end:08x}"
            )));
        }
        let slice = &data[masters_offset..masters_end];
        let masters = u8_slice_to_u32(slice);

        let pch_straps_end = pch_straps_offset + header.flmap1.isl() * 4;
        if pch_straps_offset > data.len() || pch_straps_end > data.len() {
            return Err(IfdError::OutOfBounds(format!(
                "PCH straps @ {pch_straps_offset:08x}..{pch_straps_end:08x}"
            )));
        }
        let slice = &data[pch_straps_offset..pch_straps_end];
        let pch_straps = u8_slice_to_u32(slice);

        let mch_straps_end = mch_straps_offset + header.flmap2.msl() * 4;
        if mch_straps_offset > data.len() || mch_straps_end > data.len() {
            return Err(IfdError::OutOfBounds(format!(
                "MCH straps @ {mch_straps_offset:08x}..{mch_straps_end:08x}"
            )));
        }
        let slice = &data[mch_straps_offset..mch_straps_end];
        let mch_straps = u8_slice_to_u32(slice);

        Ok(Self {
            header,
            components,
            regions,
            masters,
            pch_straps,
            mch_straps,
        })
    }
}

#[cfg(test)]
static IFD_DATA_GEN2: &[u8] = include_bytes!("../tests/me8.ifd");

#[cfg(test)]
static IFD_DATA_GEN3: &[u8] = include_bytes!("../tests/me11.ifd");

#[test]
/// We should be able to write back the original data 1:1.
fn to_vec_gen2() {
    let ifd = IFD::parse(IFD_DATA_GEN2).unwrap();
    assert_eq!(ifd.to_vec(), IFD_DATA_GEN2);
}
#[test]
/// We should be able to write back the original data 1:1.
fn to_vec_gen3() {
    let ifd = IFD::parse(IFD_DATA_GEN3).unwrap();
    assert_eq!(ifd.to_vec(), IFD_DATA_GEN3);
}