summaryrefslogtreecommitdiffstats
path: root/DynamicTablesPkg/Library/Acpi/Arm/AcpiSsdtPcieLibArm/SsdtPcieGenerator.c
blob: a34018151f2d41ae808fec5ea9f257904a68d2b5 (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
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
/** @file
  SSDT Pcie Table Generator.

  Copyright (c) 2021 - 2022, Arm Limited. All rights reserved.<BR>

  SPDX-License-Identifier: BSD-2-Clause-Patent

  @par Reference(s):
  - PCI Firmware Specification - Revision 3.0
  - ACPI 6.4 specification:
   - s6.2.13 "_PRT (PCI Routing Table)"
   - s6.1.1 "_ADR (Address)"
  - linux kernel code
  - Arm Base Boot Requirements v1.0
  - Arm Base System Architecture v1.0
**/

#include <Library/AcpiLib.h>
#include <Library/BaseLib.h>
#include <Library/BaseMemoryLib.h>
#include <Library/DebugLib.h>
#include <Library/MemoryAllocationLib.h>
#include <Protocol/AcpiTable.h>

// Module specific include files.
#include <AcpiTableGenerator.h>
#include <ConfigurationManagerObject.h>
#include <ConfigurationManagerHelper.h>
#include <Library/AcpiHelperLib.h>
#include <Library/TableHelperLib.h>
#include <Library/AmlLib/AmlLib.h>
#include <Protocol/ConfigurationManagerProtocol.h>

#include "SsdtPcieGenerator.h"

/** ARM standard SSDT Pcie Table Generator.

Requirements:
  The following Configuration Manager Object(s) are required by
  this Generator:
  - EArmObjCmRef
  - EArmObjPciConfigSpaceInfo
  - EArmObjPciAddressMapInfo
  - EArmObjPciInterruptMapInfo
*/

/** This macro expands to a function that retrieves the cross-CM-object-
    reference information from the Configuration Manager.
*/
GET_OBJECT_LIST (
  EObjNameSpaceArm,
  EArmObjCmRef,
  CM_ARM_OBJ_REF
  );

/** This macro expands to a function that retrieves the Pci
    Configuration Space Information from the Configuration Manager.
*/
GET_OBJECT_LIST (
  EObjNameSpaceArm,
  EArmObjPciConfigSpaceInfo,
  CM_ARM_PCI_CONFIG_SPACE_INFO
  );

/** This macro expands to a function that retrieves the Pci
    Address Mapping Information from the Configuration Manager.
*/
GET_OBJECT_LIST (
  EObjNameSpaceArm,
  EArmObjPciAddressMapInfo,
  CM_ARM_PCI_ADDRESS_MAP_INFO
  );

/** This macro expands to a function that retrieves the Pci
    Interrupt Mapping Information from the Configuration Manager.
*/
GET_OBJECT_LIST (
  EObjNameSpaceArm,
  EArmObjPciInterruptMapInfo,
  CM_ARM_PCI_INTERRUPT_MAP_INFO
  );

/** Initialize the MappingTable.

  @param [in] MappingTable  The mapping table structure.
  @param [in] Count         Number of entries to allocate in the
                            MappingTable.

  @retval EFI_SUCCESS            Success.
  @retval EFI_INVALID_PARAMETER  Invalid parameter.
  @retval EFI_OUT_OF_RESOURCES   Failed to allocate memory.
**/
STATIC
EFI_STATUS
EFIAPI
MappingTableInitialize (
  IN  MAPPING_TABLE  *MappingTable,
  IN  UINT32         Count
  )
{
  UINT32  *Table;

  if ((MappingTable == NULL)  ||
      (Count == 0))
  {
    ASSERT (0);
    return EFI_INVALID_PARAMETER;
  }

  Table = AllocateZeroPool (sizeof (*Table) * Count);
  if (Table == NULL) {
    ASSERT (0);
    return EFI_OUT_OF_RESOURCES;
  }

  MappingTable->Table     = Table;
  MappingTable->LastIndex = 0;
  MappingTable->MaxIndex  = Count;

  return EFI_SUCCESS;
}

/** Free the MappingTable.

  @param [in, out]  MappingTable  The mapping table structure.
**/
STATIC
VOID
EFIAPI
MappingTableFree (
  IN  OUT MAPPING_TABLE  *MappingTable
  )
{
  ASSERT (MappingTable != NULL);
  ASSERT (MappingTable->Table != NULL);

  if (MappingTable->Table != NULL) {
    FreePool (MappingTable->Table);
  }
}

/** Add a new entry to the MappingTable and return its index.

  If an entry with [Integer] is already available in the table,
  return its index without adding a new entry.

  @param [in] MappingTable  The mapping table structure.
  @param [in] Integer       New Integer entry to add.

  @retval The index of the Integer entry in the MappingTable.
**/
STATIC
UINT32
EFIAPI
MappingTableAdd (
  IN  MAPPING_TABLE  *MappingTable,
  IN  UINT32         Integer
  )
{
  UINT32  *Table;
  UINT32  Index;
  UINT32  LastIndex;

  ASSERT (MappingTable != NULL);
  ASSERT (MappingTable->Table != NULL);

  Table     = MappingTable->Table;
  LastIndex = MappingTable->LastIndex;

  // Search if there is already an entry with this Integer.
  for (Index = 0; Index < LastIndex; Index++) {
    if (Table[Index] == Integer) {
      return Index;
    }
  }

  ASSERT (LastIndex < MappingTable->MaxIndex);

  // If no, create a new entry.
  Table[LastIndex] = Integer;

  return MappingTable->LastIndex++;
}

/** Generate required Pci device information.

  ASL code:
    Name (_UID, <Uid>)                // Uid of the Pci device
    Name (_HID, EISAID ("PNP0A08"))   // PCI Express Root Bridge
    Name (_CID, EISAID ("PNP0A03"))   // Compatible PCI Root Bridge
    Name (_SEG, <Pci segment group>)  // PCI Segment Group number
    Name (_BBN, <Bus number>)         // PCI Base Bus Number
    Name (_CCA, 1)                    // Initially mark the PCI coherent

  @param [in]       PciInfo         Pci device information.
  @param [in]       Uid             Unique Id of the Pci device.
  @param [in, out]  PciNode         Pci node to amend.

  @retval EFI_SUCCESS            Success.
  @retval EFI_INVALID_PARAMETER  Invalid parameter.
  @retval EFI_OUT_OF_RESOURCES   Failed to allocate memory.
**/
STATIC
EFI_STATUS
EFIAPI
GeneratePciDeviceInfo (
  IN      CONST CM_ARM_PCI_CONFIG_SPACE_INFO  *PciInfo,
  IN            UINT32                        Uid,
  IN  OUT       AML_OBJECT_NODE_HANDLE        PciNode
  )
{
  EFI_STATUS  Status;
  UINT32      EisaId;

  ASSERT (PciInfo != NULL);
  ASSERT (PciNode != NULL);

  // ASL: Name (_UID, <Uid>)
  Status = AmlCodeGenNameInteger ("_UID", Uid, PciNode, NULL);
  if (EFI_ERROR (Status)) {
    ASSERT (0);
    return Status;
  }

  // ASL: Name (_HID, EISAID ("PNP0A08"))
  Status = AmlGetEisaIdFromString ("PNP0A08", &EisaId);
  if (EFI_ERROR (Status)) {
    ASSERT (0);
    return Status;
  }

  Status = AmlCodeGenNameInteger ("_HID", EisaId, PciNode, NULL);
  if (EFI_ERROR (Status)) {
    ASSERT (0);
    return Status;
  }

  // ASL: Name (_CID, EISAID ("PNP0A03"))
  Status = AmlGetEisaIdFromString ("PNP0A03", &EisaId);
  if (EFI_ERROR (Status)) {
    ASSERT (0);
    return Status;
  }

  Status = AmlCodeGenNameInteger ("_CID", EisaId, PciNode, NULL);
  if (EFI_ERROR (Status)) {
    ASSERT (0);
    return Status;
  }

  // ASL: Name (_SEG, <Pci segment group>)
  Status = AmlCodeGenNameInteger (
             "_SEG",
             PciInfo->PciSegmentGroupNumber,
             PciNode,
             NULL
             );
  if (EFI_ERROR (Status)) {
    ASSERT (0);
    return Status;
  }

  // ASL: Name (_BBN, <Bus number>)
  Status = AmlCodeGenNameInteger (
             "_BBN",
             PciInfo->StartBusNumber,
             PciNode,
             NULL
             );
  if (EFI_ERROR (Status)) {
    ASSERT (0);
    return Status;
  }

  // ASL: Name (_CCA, 1)
  // Must be aligned with the IORT CCA property in
  // "Table 14 Memory access properties"
  Status = AmlCodeGenNameInteger ("_CCA", 1, PciNode, NULL);
  ASSERT_EFI_ERROR (Status);
  return Status;
}

/** Generate Pci slots devices.

  PCI Firmware Specification - Revision 3.3,
  s4.8 "Generic ACPI PCI Slot Description" requests to describe the PCI slot
  used. It should be possible to enumerate them, but this is additional
  information.

  @param [in]  MappingTable  The mapping table structure.
  @param [in, out]  PciNode     Pci node to amend.

  @retval EFI_SUCCESS            Success.
  @retval EFI_INVALID_PARAMETER  Invalid parameter.
  @retval EFI_OUT_OF_RESOURCES   Failed to allocate memory.
**/
STATIC
EFI_STATUS
EFIAPI
GeneratePciSlots (
  IN      CONST MAPPING_TABLE           *MappingTable,
  IN  OUT       AML_OBJECT_NODE_HANDLE  PciNode
  )
{
  EFI_STATUS              Status;
  UINT32                  Index;
  UINT32                  LastIndex;
  UINT32                  DeviceId;
  CHAR8                   AslName[AML_NAME_SEG_SIZE + 1];
  AML_OBJECT_NODE_HANDLE  DeviceNode;

  ASSERT (MappingTable != NULL);
  ASSERT (PciNode != NULL);

  // Generic device name is "Dxx".
  CopyMem (AslName, "Dxx_", AML_NAME_SEG_SIZE + 1);

  LastIndex = MappingTable->LastIndex;

  // There are at most 32 devices on a Pci bus.
  if (LastIndex >= 32) {
    ASSERT (0);
    return EFI_INVALID_PARAMETER;
  }

  for (Index = 0; Index < LastIndex; Index++) {
    DeviceId                       = MappingTable->Table[Index];
    AslName[AML_NAME_SEG_SIZE - 3] = AsciiFromHex (DeviceId & 0xF);
    AslName[AML_NAME_SEG_SIZE - 2] = AsciiFromHex ((DeviceId >> 4) & 0xF);

    // ASL:
    // Device (Dxx) {
    //   Name (_ADR, <address value>)
    // }
    Status = AmlCodeGenDevice (AslName, PciNode, &DeviceNode);
    if (EFI_ERROR (Status)) {
      ASSERT (0);
      return Status;
    }

    /* ACPI 6.4 specification, Table 6.2: "ADR Object Address Encodings"
       High word-Device #, Low word-Function #. (for example, device 3,
       function 2 is 0x00030002). To refer to all the functions on a device #,
       use a function number of FFFF).
    */
    Status = AmlCodeGenNameInteger (
               "_ADR",
               (DeviceId << 16) | 0xFFFF,
               DeviceNode,
               NULL
               );
    if (EFI_ERROR (Status)) {
      ASSERT (0);
      return Status;
    }

    // _SUN object is not generated as we don't know which slot will be used.
  }

  return Status;
}

/** Generate a _PRT object (Pci Routing Table) for the Pci device.

  Cf. ACPI 6.4 specification, s6.2.13 "_PRT (PCI Routing Table)"

  The first model (defining a _CRS object) is used. This is necessary because
  PCI legacy interrupts are active low and GICv2 SPI interrupts are active
  high.
  Even though PCI interrupts cannot be re-routed, only the first model allows
  to specify the activation state (low/high).

  @param [in]       Generator       The SSDT Pci generator.
  @param [in]       CfgMgrProtocol  Pointer to the Configuration Manager
                                    Protocol interface.
  @param [in]       PciInfo         Pci device information.
  @param [in, out]  PciNode         Pci node to amend.

  @retval EFI_SUCCESS             The function completed successfully.
  @retval EFI_INVALID_PARAMETER   Invalid parameter.
  @retval EFI_OUT_OF_RESOURCES    Could not allocate memory.
**/
STATIC
EFI_STATUS
EFIAPI
GeneratePrt (
  IN            ACPI_PCI_GENERATOR                            *Generator,
  IN      CONST EDKII_CONFIGURATION_MANAGER_PROTOCOL  *CONST  CfgMgrProtocol,
  IN      CONST CM_ARM_PCI_CONFIG_SPACE_INFO                  *PciInfo,
  IN  OUT       AML_OBJECT_NODE_HANDLE                        PciNode
  )
{
  EFI_STATUS                     Status;
  INT32                          Index;
  AML_OBJECT_NODE_HANDLE         PrtNode;
  CM_ARM_OBJ_REF                 *RefInfo;
  UINT32                         RefCount;
  CM_ARM_PCI_INTERRUPT_MAP_INFO  *IrqMapInfo;

  ASSERT (Generator != NULL);
  ASSERT (CfgMgrProtocol != NULL);
  ASSERT (PciInfo != NULL);
  ASSERT (PciNode != NULL);

  PrtNode = NULL;

  // Get the array of CM_ARM_OBJ_REF referencing the
  // CM_ARM_PCI_INTERRUPT_MAP_INFO objects.
  Status = GetEArmObjCmRef (
             CfgMgrProtocol,
             PciInfo->InterruptMapToken,
             &RefInfo,
             &RefCount
             );
  if (EFI_ERROR (Status)) {
    ASSERT (0);
    return Status;
  }

  // Initialized DeviceTable.
  Status = MappingTableInitialize (&Generator->DeviceTable, RefCount);
  if (EFI_ERROR (Status)) {
    ASSERT (0);
    goto exit_handler0;
  }

  // ASL: Name (_PRT, Package () {})
  Status = AmlCodeGenNamePackage ("_PRT", NULL, &PrtNode);
  if (EFI_ERROR (Status)) {
    ASSERT (0);
    goto exit_handler;
  }

  for (Index = 0; Index < RefCount; Index++) {
    // Get CM_ARM_PCI_INTERRUPT_MAP_INFO structures one by one.
    Status = GetEArmObjPciInterruptMapInfo (
               CfgMgrProtocol,
               RefInfo[Index].ReferenceToken,
               &IrqMapInfo,
               NULL
               );
    if (EFI_ERROR (Status)) {
      ASSERT (0);
      goto exit_handler;
    }

    // Check that the interrupts flags are SPIs, level high.
    // Cf. Arm BSA v1.0, sE.6 "Legacy interrupts"
    if ((Index > 0)   &&
        (IrqMapInfo->IntcInterrupt.Interrupt >= 32)   &&
        (IrqMapInfo->IntcInterrupt.Interrupt < 1020)  &&
        ((IrqMapInfo->IntcInterrupt.Flags & 0x3) != BIT0))
    {
      Status = EFI_INVALID_PARAMETER;
      ASSERT_EFI_ERROR (Status);
      goto exit_handler;
    }

    // Add the device to the DeviceTable.
    MappingTableAdd (&Generator->DeviceTable, IrqMapInfo->PciDevice);

    /* Add a _PRT entry.
       ASL
       Name (_PRT, Package () {
         <OldPrtEntries>,
         <NewPrtEntry>
       })

     Address is set as:
     ACPI 6.4 specification, Table 6.2: "ADR Object Address Encodings"
       High word-Device #, Low word-Function #. (for example, device 3,
       function 2 is 0x00030002). To refer to all the functions on a device #,
       use a function number of FFFF).
    */
    Status = AmlAddPrtEntry (
               (IrqMapInfo->PciDevice << 16) | 0xFFFF,
               IrqMapInfo->PciInterrupt,
               NULL,
               IrqMapInfo->IntcInterrupt.Interrupt,
               PrtNode
               );
    if (EFI_ERROR (Status)) {
      ASSERT (0);
      goto exit_handler;
    }
  } // for

  // Attach the _PRT entry.
  Status = AmlAttachNode (PciNode, PrtNode);
  if (EFI_ERROR (Status)) {
    ASSERT_EFI_ERROR (Status);
    goto exit_handler;
  }

  PrtNode = NULL;

  // Generate the Pci slots once all the device have been added.
  Status = GeneratePciSlots (&Generator->DeviceTable, PciNode);
  if (EFI_ERROR (Status)) {
    ASSERT (0);
    goto exit_handler;
  }

exit_handler:
  MappingTableFree (&Generator->DeviceTable);
exit_handler0:
  if (PrtNode != NULL) {
    AmlDeleteTree (PrtNode);
  }

  return Status;
}

/** Generate a _CRS method for the Pci device.

  @param [in]       Generator       The SSDT Pci generator.
  @param [in]       CfgMgrProtocol  Pointer to the Configuration Manager
                                    Protocol interface.
  @param [in]       PciInfo         Pci device information.
  @param [in, out]  PciNode         Pci node to amend.

  @retval EFI_SUCCESS             The function completed successfully.
  @retval EFI_INVALID_PARAMETER   Invalid parameter.
  @retval EFI_OUT_OF_RESOURCES    Could not allocate memory.
**/
STATIC
EFI_STATUS
EFIAPI
GeneratePciCrs (
  IN            ACPI_PCI_GENERATOR                            *Generator,
  IN      CONST EDKII_CONFIGURATION_MANAGER_PROTOCOL  *CONST  CfgMgrProtocol,
  IN      CONST CM_ARM_PCI_CONFIG_SPACE_INFO                  *PciInfo,
  IN  OUT       AML_OBJECT_NODE_HANDLE                        PciNode
  )
{
  EFI_STATUS                   Status;
  BOOLEAN                      Translation;
  UINT32                       Index;
  CM_ARM_OBJ_REF               *RefInfo;
  UINT32                       RefCount;
  CM_ARM_PCI_ADDRESS_MAP_INFO  *AddrMapInfo;
  AML_OBJECT_NODE_HANDLE       CrsNode;

  ASSERT (Generator != NULL);
  ASSERT (CfgMgrProtocol != NULL);
  ASSERT (PciInfo != NULL);
  ASSERT (PciNode != NULL);

  // ASL: Name (_CRS, ResourceTemplate () {})
  Status = AmlCodeGenNameResourceTemplate ("_CRS", PciNode, &CrsNode);
  if (EFI_ERROR (Status)) {
    ASSERT (0);
    return Status;
  }

  // ASL:
  // WordBusNumber (          // Bus numbers assigned to this root
  //   ResourceProducer, MinFixed, MaxFixed, PosDecode,
  //   0,                     // AddressGranularity
  //   <Start>,               // AddressMinimum - Minimum Bus Number
  //   <End>,                 // AddressMaximum - Maximum Bus Number
  //   0,                     // AddressTranslation - Set to 0
  //   <End> - <Start> + 1    // RangeLength - Number of Busses
  // )
  Status = AmlCodeGenRdWordBusNumber (
             FALSE,
             TRUE,
             TRUE,
             TRUE,
             0,
             PciInfo->StartBusNumber,
             PciInfo->EndBusNumber,
             0,
             PciInfo->EndBusNumber - PciInfo->StartBusNumber + 1,
             0,
             NULL,
             CrsNode,
             NULL
             );
  if (EFI_ERROR (Status)) {
    ASSERT (0);
    return Status;
  }

  // Get the array of CM_ARM_OBJ_REF referencing the
  // CM_ARM_PCI_ADDRESS_MAP_INFO objects.
  Status = GetEArmObjCmRef (
             CfgMgrProtocol,
             PciInfo->AddressMapToken,
             &RefInfo,
             &RefCount
             );
  if (EFI_ERROR (Status)) {
    ASSERT (0);
    return Status;
  }

  for (Index = 0; Index < RefCount; Index++) {
    // Get CM_ARM_PCI_ADDRESS_MAP_INFO structures one by one.
    Status = GetEArmObjPciAddressMapInfo (
               CfgMgrProtocol,
               RefInfo[Index].ReferenceToken,
               &AddrMapInfo,
               NULL
               );
    if (EFI_ERROR (Status)) {
      ASSERT (0);
      return Status;
    }

    Translation = (AddrMapInfo->CpuAddress != AddrMapInfo->PciAddress);

    switch (AddrMapInfo->SpaceCode) {
      case PCI_SS_IO:
        Status = AmlCodeGenRdDWordIo (
                   FALSE,
                   TRUE,
                   TRUE,
                   TRUE,
                   3,
                   0,
                   AddrMapInfo->PciAddress,
                   AddrMapInfo->PciAddress + AddrMapInfo->AddressSize - 1,
                   Translation ? AddrMapInfo->CpuAddress : 0,
                   AddrMapInfo->AddressSize,
                   0,
                   NULL,
                   TRUE,
                   FALSE,
                   CrsNode,
                   NULL
                   );
        break;

      case PCI_SS_M32:
        Status = AmlCodeGenRdDWordMemory (
                   FALSE,
                   TRUE,
                   TRUE,
                   TRUE,
                   TRUE,
                   TRUE,
                   0,
                   AddrMapInfo->PciAddress,
                   AddrMapInfo->PciAddress + AddrMapInfo->AddressSize - 1,
                   Translation ? AddrMapInfo->CpuAddress : 0,
                   AddrMapInfo->AddressSize,
                   0,
                   NULL,
                   0,
                   TRUE,
                   CrsNode,
                   NULL
                   );
        break;

      case PCI_SS_M64:
        Status = AmlCodeGenRdQWordMemory (
                   FALSE,
                   TRUE,
                   TRUE,
                   TRUE,
                   TRUE,
                   TRUE,
                   0,
                   AddrMapInfo->PciAddress,
                   AddrMapInfo->PciAddress + AddrMapInfo->AddressSize - 1,
                   Translation ? AddrMapInfo->CpuAddress : 0,
                   AddrMapInfo->AddressSize,
                   0,
                   NULL,
                   0,
                   TRUE,
                   CrsNode,
                   NULL
                   );
        break;

      default:
        Status = EFI_INVALID_PARAMETER;
    } // switch

    if (EFI_ERROR (Status)) {
      ASSERT (0);
      return Status;
    }
  } // for

  return Status;
}

/** Add an _OSC template method to the PciNode.

  The _OSC method is provided as an AML blob. The blob is
  parsed and attached at the end of the PciNode list of variable elements.

  @param [in, out]  PciNode     Pci node to amend.

  @retval EFI_SUCCESS             The function completed successfully.
  @retval EFI_INVALID_PARAMETER   Invalid parameter.
  @retval EFI_OUT_OF_RESOURCES    Could not allocate memory.
**/
STATIC
EFI_STATUS
EFIAPI
AddOscMethod (
  IN  OUT   AML_OBJECT_NODE_HANDLE  PciNode
  )
{
  EFI_STATUS                   Status;
  EFI_STATUS                   Status1;
  EFI_ACPI_DESCRIPTION_HEADER  *SsdtPcieOscTemplate;
  AML_ROOT_NODE_HANDLE         OscTemplateRoot;
  AML_OBJECT_NODE_HANDLE       OscNode;

  ASSERT (PciNode != NULL);

  // Parse the Ssdt Pci Osc Template.
  SsdtPcieOscTemplate = (EFI_ACPI_DESCRIPTION_HEADER *)
                        ssdtpcieosctemplate_aml_code;

  OscNode         = NULL;
  OscTemplateRoot = NULL;
  Status          = AmlParseDefinitionBlock (
                      SsdtPcieOscTemplate,
                      &OscTemplateRoot
                      );
  if (EFI_ERROR (Status)) {
    DEBUG ((
      DEBUG_ERROR,
      "ERROR: SSDT-PCI-OSC: Failed to parse SSDT PCI OSC Template."
      " Status = %r\n",
      Status
      ));
    return Status;
  }

  Status = AmlFindNode (OscTemplateRoot, "\\_OSC", &OscNode);
  if (EFI_ERROR (Status)) {
    goto error_handler;
  }

  Status = AmlDetachNode (OscNode);
  if (EFI_ERROR (Status)) {
    goto error_handler;
  }

  Status = AmlAttachNode (PciNode, OscNode);
  if (EFI_ERROR (Status)) {
    // Free the detached node.
    AmlDeleteTree (OscNode);
    goto error_handler;
  }

error_handler:
  // Cleanup
  Status1 = AmlDeleteTree (OscTemplateRoot);
  if (EFI_ERROR (Status1)) {
    DEBUG ((
      DEBUG_ERROR,
      "ERROR: SSDT-PCI-OSC: Failed to cleanup AML tree."
      " Status = %r\n",
      Status1
      ));
    // If Status was success but we failed to delete the AML Tree
    // return Status1 else return the original error code, i.e. Status.
    if (!EFI_ERROR (Status)) {
      return Status1;
    }
  }

  return Status;
}

/** Generate a Pci device.

  @param [in]       Generator       The SSDT Pci generator.
  @param [in]       CfgMgrProtocol  Pointer to the Configuration Manager
                                    Protocol interface.
  @param [in]       PciInfo         Pci device information.
  @param [in]       Uid             Unique Id of the Pci device.
  @param [in, out]  RootNode        RootNode of the AML tree to populate.

  @retval EFI_SUCCESS             The function completed successfully.
  @retval EFI_INVALID_PARAMETER   Invalid parameter.
  @retval EFI_OUT_OF_RESOURCES    Could not allocate memory.
**/
STATIC
EFI_STATUS
EFIAPI
GeneratePciDevice (
  IN            ACPI_PCI_GENERATOR                            *Generator,
  IN      CONST EDKII_CONFIGURATION_MANAGER_PROTOCOL  *CONST  CfgMgrProtocol,
  IN      CONST CM_ARM_PCI_CONFIG_SPACE_INFO                  *PciInfo,
  IN            UINT32                                        Uid,
  IN  OUT       AML_ROOT_NODE_HANDLE                          *RootNode
  )
{
  EFI_STATUS  Status;

  CHAR8                   AslName[AML_NAME_SEG_SIZE + 1];
  AML_OBJECT_NODE_HANDLE  ScopeNode;
  AML_OBJECT_NODE_HANDLE  PciNode;

  ASSERT (Generator != NULL);
  ASSERT (CfgMgrProtocol != NULL);
  ASSERT (PciInfo != NULL);
  ASSERT (RootNode != NULL);

  PciNode = NULL;

  // ASL: Scope (\_SB) {}
  Status = AmlCodeGenScope (SB_SCOPE, RootNode, &ScopeNode);
  if (EFI_ERROR (Status)) {
    ASSERT (0);
    return Status;
  }

  // Write the name of the PCI device.
  CopyMem (AslName, "PCIx", AML_NAME_SEG_SIZE + 1);
  AslName[AML_NAME_SEG_SIZE - 1] = AsciiFromHex (Uid);

  // ASL: Device (PCIx) {}
  Status = AmlCodeGenDevice (AslName, ScopeNode, &PciNode);
  if (EFI_ERROR (Status)) {
    ASSERT (0);
    return Status;
  }

  // Populate the PCIx node with some Id values.
  Status = GeneratePciDeviceInfo (PciInfo, Uid, PciNode);
  if (EFI_ERROR (Status)) {
    ASSERT (0);
    return Status;
  }

  // Generate the Pci Routing Table (_PRT).
  if (PciInfo->InterruptMapToken != CM_NULL_TOKEN) {
    Status = GeneratePrt (
               Generator,
               CfgMgrProtocol,
               PciInfo,
               PciNode
               );
    if (EFI_ERROR (Status)) {
      ASSERT (0);
      return Status;
    }
  }

  // Generate the _CRS method.
  Status = GeneratePciCrs (Generator, CfgMgrProtocol, PciInfo, PciNode);
  if (EFI_ERROR (Status)) {
    ASSERT (0);
    return Status;
  }

  // Add the template _OSC method.
  Status = AddOscMethod (PciNode);
  ASSERT_EFI_ERROR (Status);
  return Status;
}

/** Build an Ssdt table describing a Pci device.

  @param [in]  Generator        The SSDT Pci generator.
  @param [in]  CfgMgrProtocol   Pointer to the Configuration Manager
                                Protocol interface.
  @param [in]  AcpiTableInfo    Pointer to the ACPI table information.
  @param [in]  PciInfo          Pci device information.
  @param [in]  Uid              Unique Id of the Pci device.
  @param [out] Table            If success, contains the created SSDT table.

  @retval EFI_SUCCESS             The function completed successfully.
  @retval EFI_INVALID_PARAMETER   Invalid parameter.
  @retval EFI_OUT_OF_RESOURCES    Could not allocate memory.
**/
STATIC
EFI_STATUS
EFIAPI
BuildSsdtPciTable (
  IN        ACPI_PCI_GENERATOR                            *Generator,
  IN  CONST EDKII_CONFIGURATION_MANAGER_PROTOCOL  *CONST  CfgMgrProtocol,
  IN  CONST CM_STD_OBJ_ACPI_TABLE_INFO            *CONST  AcpiTableInfo,
  IN  CONST CM_ARM_PCI_CONFIG_SPACE_INFO                  *PciInfo,
  IN        UINT32                                        Uid,
  OUT       EFI_ACPI_DESCRIPTION_HEADER                   **Table
  )
{
  EFI_STATUS            Status;
  EFI_STATUS            Status1;
  AML_ROOT_NODE_HANDLE  RootNode;

  ASSERT (Generator != NULL);
  ASSERT (CfgMgrProtocol != NULL);
  ASSERT (PciInfo != NULL);
  ASSERT (Table != NULL);

  // Create a new Ssdt table.
  Status = AddSsdtAcpiHeader (
             CfgMgrProtocol,
             &Generator->Header,
             AcpiTableInfo,
             &RootNode
             );
  if (EFI_ERROR (Status)) {
    ASSERT (0);
    return Status;
  }

  Status = GeneratePciDevice (
             Generator,
             CfgMgrProtocol,
             PciInfo,
             Uid,
             RootNode
             );
  if (EFI_ERROR (Status)) {
    ASSERT (0);
    goto exit_handler;
  }

  // Serialize the tree.
  Status = AmlSerializeDefinitionBlock (
             RootNode,
             Table
             );
  if (EFI_ERROR (Status)) {
    DEBUG ((
      DEBUG_ERROR,
      "ERROR: SSDT-PCI: Failed to Serialize SSDT Table Data."
      " Status = %r\n",
      Status
      ));
  }

exit_handler:
  // Cleanup
  Status1 = AmlDeleteTree (RootNode);
  if (EFI_ERROR (Status1)) {
    DEBUG ((
      DEBUG_ERROR,
      "ERROR: SSDT-PCI: Failed to cleanup AML tree."
      " Status = %r\n",
      Status1
      ));
    // If Status was success but we failed to delete the AML Tree
    // return Status1 else return the original error code, i.e. Status.
    if (!EFI_ERROR (Status)) {
      return Status1;
    }
  }

  return Status;
}

/** Construct SSDT tables describing Pci root complexes.

  This function invokes the Configuration Manager protocol interface
  to get the required hardware information for generating the ACPI
  table.

  If this function allocates any resources then they must be freed
  in the FreeXXXXTableResourcesEx function.

  @param [in]  This            Pointer to the ACPI table generator.
  @param [in]  AcpiTableInfo   Pointer to the ACPI table information.
  @param [in]  CfgMgrProtocol  Pointer to the Configuration Manager
                               Protocol interface.
  @param [out] Table           Pointer to a list of generated ACPI table(s).
  @param [out] TableCount      Number of generated ACPI table(s).

  @retval EFI_SUCCESS            Table generated successfully.
  @retval EFI_BAD_BUFFER_SIZE    The size returned by the Configuration
                                 Manager is less than the Object size for
                                 the requested object.
  @retval EFI_INVALID_PARAMETER  A parameter is invalid.
  @retval EFI_NOT_FOUND          Could not find information.
  @retval EFI_OUT_OF_RESOURCES   Could not allocate memory.
  @retval EFI_UNSUPPORTED        Unsupported configuration.
**/
STATIC
EFI_STATUS
EFIAPI
BuildSsdtPciTableEx (
  IN  CONST ACPI_TABLE_GENERATOR                           *This,
  IN  CONST CM_STD_OBJ_ACPI_TABLE_INFO             *CONST  AcpiTableInfo,
  IN  CONST EDKII_CONFIGURATION_MANAGER_PROTOCOL   *CONST  CfgMgrProtocol,
  OUT       EFI_ACPI_DESCRIPTION_HEADER                    ***Table,
  OUT       UINTN                                  *CONST  TableCount
  )
{
  EFI_STATUS                    Status;
  CM_ARM_PCI_CONFIG_SPACE_INFO  *PciInfo;
  UINT32                        PciCount;
  UINTN                         Index;
  EFI_ACPI_DESCRIPTION_HEADER   **TableList;
  ACPI_PCI_GENERATOR            *Generator;

  ASSERT (This != NULL);
  ASSERT (AcpiTableInfo != NULL);
  ASSERT (CfgMgrProtocol != NULL);
  ASSERT (Table != NULL);
  ASSERT (TableCount != NULL);
  ASSERT (AcpiTableInfo->TableGeneratorId == This->GeneratorID);
  ASSERT (AcpiTableInfo->AcpiTableSignature == This->AcpiTableSignature);

  *TableCount = 0;
  Generator   = (ACPI_PCI_GENERATOR *)This;

  Status = GetEArmObjPciConfigSpaceInfo (
             CfgMgrProtocol,
             CM_NULL_TOKEN,
             &PciInfo,
             &PciCount
             );
  if (EFI_ERROR (Status)) {
    ASSERT (0);
    return Status;
  }

  if (PciCount > MAX_PCI_ROOT_COMPLEXES_SUPPORTED) {
    DEBUG ((
      DEBUG_ERROR,
      "ERROR: SSDT-PCI: Too many Pci root complexes: %d."
      " Maximum Pci root complexes supported = %d.\n",
      PciCount,
      MAX_PCI_ROOT_COMPLEXES_SUPPORTED
      ));
    return EFI_INVALID_PARAMETER;
  }

  // Allocate a table to store pointers to the SSDT tables.
  TableList = (EFI_ACPI_DESCRIPTION_HEADER **)
              AllocateZeroPool (
                (sizeof (EFI_ACPI_DESCRIPTION_HEADER *) * PciCount)
                );
  if (TableList == NULL) {
    Status = EFI_OUT_OF_RESOURCES;
    DEBUG ((
      DEBUG_ERROR,
      "ERROR: SSDT-PCI: Failed to allocate memory for Table List."
      " Status = %r\n",
      Status
      ));
    return Status;
  }

  // Setup the table list early so that appropriate cleanup
  // can be done in case of failure.
  *Table = TableList;

  for (Index = 0; Index < PciCount; Index++) {
    // Build a SSDT table describing the Pci devices.
    Status = BuildSsdtPciTable (
               Generator,
               CfgMgrProtocol,
               AcpiTableInfo,
               &PciInfo[Index],
               Index,
               &TableList[Index]
               );
    if (EFI_ERROR (Status)) {
      DEBUG ((
        DEBUG_ERROR,
        "ERROR: SSDT-PCI: Failed to build associated SSDT table."
        " Status = %r\n",
        Status
        ));
      goto error_handler;
    }

    *TableCount += 1;
  } // for

error_handler:
  // Note: Table list and Table count have been setup. The
  // error handler does nothing here as the framework will invoke
  // FreeSsdtPciTableEx () even on failure.
  return Status;
}

/** Free any resources allocated for constructing the tables.

  @param [in]      This           Pointer to the ACPI table generator.
  @param [in]      AcpiTableInfo  Pointer to the ACPI Table Info.
  @param [in]      CfgMgrProtocol Pointer to the Configuration Manager
                                  Protocol Interface.
  @param [in, out] Table          Pointer to an array of pointers
                                  to ACPI Table(s).
  @param [in]      TableCount     Number of ACPI table(s).

  @retval EFI_SUCCESS           The resources were freed successfully.
  @retval EFI_INVALID_PARAMETER The table pointer is NULL or invalid.
**/
STATIC
EFI_STATUS
EFIAPI
FreeSsdtPciTableEx (
  IN      CONST ACPI_TABLE_GENERATOR                   *CONST  This,
  IN      CONST CM_STD_OBJ_ACPI_TABLE_INFO             *CONST  AcpiTableInfo,
  IN      CONST EDKII_CONFIGURATION_MANAGER_PROTOCOL   *CONST  CfgMgrProtocol,
  IN OUT        EFI_ACPI_DESCRIPTION_HEADER          ***CONST  Table,
  IN      CONST UINTN                                          TableCount
  )
{
  EFI_ACPI_DESCRIPTION_HEADER  **TableList;
  UINTN                        Index;

  ASSERT (This != NULL);
  ASSERT (AcpiTableInfo != NULL);
  ASSERT (CfgMgrProtocol != NULL);
  ASSERT (AcpiTableInfo->TableGeneratorId == This->GeneratorID);
  ASSERT (AcpiTableInfo->AcpiTableSignature == This->AcpiTableSignature);

  if ((Table == NULL)   ||
      (*Table == NULL)  ||
      (TableCount == 0))
  {
    DEBUG ((DEBUG_ERROR, "ERROR: SSDT-PCI: Invalid Table Pointer\n"));
    return EFI_INVALID_PARAMETER;
  }

  TableList = *Table;
  for (Index = 0; Index < TableCount; Index++) {
    if ((TableList[Index] != NULL) &&
        (TableList[Index]->Signature ==
         EFI_ACPI_6_3_SECONDARY_SYSTEM_DESCRIPTION_TABLE_SIGNATURE))
    {
      FreePool (TableList[Index]);
    } else {
      DEBUG ((
        DEBUG_ERROR,
        "ERROR: SSDT-PCI: Could not free SSDT table at index %d.",
        Index
        ));
      return EFI_INVALID_PARAMETER;
    }
  } // for

  // Free the table list.
  FreePool (*Table);

  return EFI_SUCCESS;
}

/** This macro defines the SSDT Pci Table Generator revision.
*/
#define SSDT_PCI_GENERATOR_REVISION  CREATE_REVISION (1, 0)

/** The interface for the SSDT Pci Table Generator.
*/
STATIC
ACPI_PCI_GENERATOR  SsdtPcieGenerator = {
  // ACPI table generator header
  {
    // Generator ID
    CREATE_STD_ACPI_TABLE_GEN_ID (EStdAcpiTableIdSsdtPciExpress),
    // Generator Description
    L"ACPI.STD.SSDT.PCI.GENERATOR",
    // ACPI Table Signature
    EFI_ACPI_6_3_SECONDARY_SYSTEM_DESCRIPTION_TABLE_SIGNATURE,
    // ACPI Table Revision - Unused
    0,
    // Minimum ACPI Table Revision - Unused
    0,
    // Creator ID
    TABLE_GENERATOR_CREATOR_ID_ARM,
    // Creator Revision
    SSDT_PCI_GENERATOR_REVISION,
    // Build table function. Use the extended version instead.
    NULL,
    // Free table function. Use the extended version instead.
    NULL,
    // Extended Build table function.
    BuildSsdtPciTableEx,
    // Extended free function.
    FreeSsdtPciTableEx
  },

  // Private fields are defined from here.

  // DeviceTable
  {
    // Table
    NULL,
    // LastIndex
    0,
    // MaxIndex
    0
  },
};

/** Register the Generator with the ACPI Table Factory.

  @param [in]  ImageHandle  The handle to the image.
  @param [in]  SystemTable  Pointer to the System Table.

  @retval EFI_SUCCESS           The Generator is registered.
  @retval EFI_INVALID_PARAMETER A parameter is invalid.
  @retval EFI_ALREADY_STARTED   The Generator for the Table ID
                                is already registered.
**/
EFI_STATUS
EFIAPI
AcpiSsdtPcieLibConstructor (
  IN  EFI_HANDLE        ImageHandle,
  IN  EFI_SYSTEM_TABLE  *SystemTable
  )
{
  EFI_STATUS  Status;

  Status = RegisterAcpiTableGenerator (&SsdtPcieGenerator.Header);
  DEBUG ((
    DEBUG_INFO,
    "SSDT-PCI: Register Generator. Status = %r\n",
    Status
    ));
  ASSERT_EFI_ERROR (Status);
  return Status;
}

/** Deregister the Generator from the ACPI Table Factory.

  @param [in]  ImageHandle  The handle to the image.
  @param [in]  SystemTable  Pointer to the System Table.

  @retval EFI_SUCCESS           The Generator is deregistered.
  @retval EFI_INVALID_PARAMETER A parameter is invalid.
  @retval EFI_NOT_FOUND         The Generator is not registered.
**/
EFI_STATUS
EFIAPI
AcpiSsdtPcieLibDestructor (
  IN  EFI_HANDLE        ImageHandle,
  IN  EFI_SYSTEM_TABLE  *SystemTable
  )
{
  EFI_STATUS  Status;

  Status = DeregisterAcpiTableGenerator (&SsdtPcieGenerator.Header);
  DEBUG ((
    DEBUG_INFO,
    "SSDT-PCI: Deregister Generator. Status = %r\n",
    Status
    ));
  ASSERT_EFI_ERROR (Status);
  return Status;
}