summaryrefslogtreecommitdiffstats
path: root/OvmfPkg/Library/QemuFwCfgS3Lib/QemuFwCfgS3Dxe.c
blob: 5706fa9be46af0865aaee9c5ceb84400ca0de283 (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
/** @file
  Full functionality QemuFwCfgS3Lib instance, for DXE phase modules.

  Copyright (C) 2017, Red Hat, Inc.

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

#include <Library/BaseLib.h>
#include <Library/DebugLib.h>
#include <Library/MemoryAllocationLib.h>
#include <Library/QemuFwCfgLib.h>
#include <Library/QemuFwCfgS3Lib.h>
#include <Library/UefiBootServicesTableLib.h>
#include <Protocol/S3SaveState.h>

//
// Event to signal when the S3SaveState protocol interface is installed.
//
STATIC EFI_EVENT  mS3SaveStateInstalledEvent;

//
// Reference to the S3SaveState protocol interface, after it is installed.
//
STATIC EFI_S3_SAVE_STATE_PROTOCOL  *mS3SaveState;

//
// The control structure is allocated in reserved memory, aligned at 8 bytes.
// The client-requested ScratchBuffer will be allocated adjacently, also
// aligned at 8 bytes.
//
#define RESERVED_MEM_ALIGNMENT  8

STATIC FW_CFG_DMA_ACCESS  *mDmaAccess;
STATIC VOID               *mScratchBuffer;
STATIC UINTN              mScratchBufferSize;

//
// Callback provided by the client, for appending ACPI S3 Boot Script opcodes.
// To be called from S3SaveStateInstalledNotify().
//
STATIC FW_CFG_BOOT_SCRIPT_CALLBACK_FUNCTION  *mCallback;

/**
  Event notification function for mS3SaveStateInstalledEvent.
**/
STATIC
VOID
EFIAPI
S3SaveStateInstalledNotify (
  IN EFI_EVENT  Event,
  IN VOID       *Context
  )
{
  EFI_STATUS  Status;

  ASSERT (Event == mS3SaveStateInstalledEvent);

  Status = gBS->LocateProtocol (
                  &gEfiS3SaveStateProtocolGuid,
                  NULL /* Registration */,
                  (VOID **)&mS3SaveState
                  );
  if (EFI_ERROR (Status)) {
    return;
  }

  ASSERT (mCallback != NULL);

  DEBUG ((
    DEBUG_INFO,
    "%a: %a: DmaAccess@0x%Lx ScratchBuffer@[0x%Lx+0x%Lx]\n",
    gEfiCallerBaseName,
    __FUNCTION__,
    (UINT64)(UINTN)mDmaAccess,
    (UINT64)(UINTN)mScratchBuffer,
    (UINT64)mScratchBufferSize
    ));
  mCallback (Context, mScratchBuffer);

  gBS->CloseEvent (mS3SaveStateInstalledEvent);
  mS3SaveStateInstalledEvent = NULL;
}

/**
  Install the client module's FW_CFG_BOOT_SCRIPT_CALLBACK_FUNCTION callback for
  when the production of ACPI S3 Boot Script opcodes becomes possible.

  Take ownership of the client-provided Context, and pass it to the callback
  function, when the latter is invoked.

  Allocate scratch space for those ACPI S3 Boot Script opcodes to work upon
  that the client will produce in the callback function.

  @param[in] Callback           FW_CFG_BOOT_SCRIPT_CALLBACK_FUNCTION to invoke
                                when the production of ACPI S3 Boot Script
                                opcodes becomes possible. Callback() may be
                                called immediately from
                                QemuFwCfgS3CallWhenBootScriptReady().

  @param[in,out] Context        Client-provided data structure for the
                                Callback() callback function to consume.

                                If Context points to dynamically allocated
                                memory, then Callback() must release it.

                                If Context points to dynamically allocated
                                memory, and
                                QemuFwCfgS3CallWhenBootScriptReady() returns
                                successfully, then the caller of
                                QemuFwCfgS3CallWhenBootScriptReady() must
                                neither dereference nor even evaluate Context
                                any longer, as ownership of the referenced area
                                has been transferred to Callback().

  @param[in] ScratchBufferSize  The size of the scratch buffer that will hold,
                                in reserved memory, all client data read,
                                written, and checked by the ACPI S3 Boot Script
                                opcodes produced by Callback().

  @retval RETURN_UNSUPPORTED       The library instance does not support this
                                   function.

  @retval RETURN_NOT_FOUND         The fw_cfg DMA interface to QEMU is
                                   unavailable.

  @retval RETURN_BAD_BUFFER_SIZE   ScratchBufferSize is too large.

  @retval RETURN_OUT_OF_RESOURCES  Memory allocation failed.

  @retval RETURN_SUCCESS           Callback() has been installed, and the
                                   ownership of Context has been transferred.
                                   Reserved memory has been allocated for the
                                   scratch buffer.

                                   A successful invocation of
                                   QemuFwCfgS3CallWhenBootScriptReady() cannot
                                   be rolled back.

  @return                          Error codes from underlying functions.
**/
RETURN_STATUS
EFIAPI
QemuFwCfgS3CallWhenBootScriptReady (
  IN     FW_CFG_BOOT_SCRIPT_CALLBACK_FUNCTION  *Callback,
  IN OUT VOID                                  *Context           OPTIONAL,
  IN     UINTN                                 ScratchBufferSize
  )
{
  EFI_STATUS  Status;
  VOID        *Registration;

  //
  // Basic fw_cfg is certainly available, as we can only be here after a
  // successful call to QemuFwCfgS3Enabled(). Check fw_cfg DMA availability.
  //
  ASSERT (QemuFwCfgIsAvailable ());
  QemuFwCfgSelectItem (QemuFwCfgItemInterfaceVersion);
  if ((QemuFwCfgRead32 () & FW_CFG_F_DMA) == 0) {
    DEBUG ((
      DEBUG_ERROR,
      "%a: %a: fw_cfg DMA unavailable\n",
      gEfiCallerBaseName,
      __FUNCTION__
      ));
    return RETURN_NOT_FOUND;
  }

  //
  // Allocate a reserved buffer for the DMA access control structure and the
  // client data together.
  //
  if (ScratchBufferSize >
      MAX_UINT32 - (RESERVED_MEM_ALIGNMENT - 1) - sizeof *mDmaAccess)
  {
    DEBUG ((
      DEBUG_ERROR,
      "%a: %a: ScratchBufferSize too big: %Lu\n",
      gEfiCallerBaseName,
      __FUNCTION__,
      (UINT64)ScratchBufferSize
      ));
    return RETURN_BAD_BUFFER_SIZE;
  }

  mDmaAccess = AllocateReservedPool (
                 (RESERVED_MEM_ALIGNMENT - 1) +
                 sizeof *mDmaAccess + ScratchBufferSize
                 );
  if (mDmaAccess == NULL) {
    DEBUG ((
      DEBUG_ERROR,
      "%a: %a: AllocateReservedPool(): out of resources\n",
      gEfiCallerBaseName,
      __FUNCTION__
      ));
    return RETURN_OUT_OF_RESOURCES;
  }

  mDmaAccess = ALIGN_POINTER (mDmaAccess, RESERVED_MEM_ALIGNMENT);

  //
  // Set up a protocol notify for EFI_S3_SAVE_STATE_PROTOCOL. Forward the
  // client's Context to the callback.
  //
  Status = gBS->CreateEvent (
                  EVT_NOTIFY_SIGNAL,
                  TPL_CALLBACK,
                  S3SaveStateInstalledNotify,
                  Context,
                  &mS3SaveStateInstalledEvent
                  );
  if (EFI_ERROR (Status)) {
    DEBUG ((
      DEBUG_ERROR,
      "%a: %a: CreateEvent(): %r\n",
      gEfiCallerBaseName,
      __FUNCTION__,
      Status
      ));
    goto FreeDmaAccess;
  }

  Status = gBS->RegisterProtocolNotify (
                  &gEfiS3SaveStateProtocolGuid,
                  mS3SaveStateInstalledEvent,
                  &Registration
                  );
  if (EFI_ERROR (Status)) {
    DEBUG ((
      DEBUG_ERROR,
      "%a: %a: RegisterProtocolNotify(): %r\n",
      gEfiCallerBaseName,
      __FUNCTION__,
      Status
      ));
    goto CloseEvent;
  }

  //
  // Set the remaining global variables. For the alignment guarantee on
  // mScratchBuffer, we rely on the fact that *mDmaAccess has a size that is an
  // integral multiple of RESERVED_MEM_ALIGNMENT.
  //
  ASSERT (sizeof *mDmaAccess % RESERVED_MEM_ALIGNMENT == 0);
  mScratchBuffer     = mDmaAccess + 1;
  mScratchBufferSize = ScratchBufferSize;
  mCallback          = Callback;

  //
  // Kick the event; EFI_S3_SAVE_STATE_PROTOCOL could be available already.
  //
  Status = gBS->SignalEvent (mS3SaveStateInstalledEvent);
  if (EFI_ERROR (Status)) {
    DEBUG ((
      DEBUG_ERROR,
      "%a: %a: SignalEvent(): %r\n",
      gEfiCallerBaseName,
      __FUNCTION__,
      Status
      ));
    goto NullGlobals;
  }

  return RETURN_SUCCESS;

NullGlobals:
  mScratchBuffer     = NULL;
  mScratchBufferSize = 0;
  mCallback          = NULL;

CloseEvent:
  gBS->CloseEvent (mS3SaveStateInstalledEvent);
  mS3SaveStateInstalledEvent = NULL;

FreeDmaAccess:
  FreePool (mDmaAccess);
  mDmaAccess = NULL;

  return (RETURN_STATUS)Status;
}

/**
  Produce ACPI S3 Boot Script opcodes that (optionally) select an fw_cfg item,
  and transfer data to it.

  The opcodes produced by QemuFwCfgS3ScriptWriteBytes() will first restore
  NumberOfBytes bytes in ScratchBuffer in-place, in reserved memory, then write
  them to fw_cfg using DMA.

  If the operation fails during S3 resume, the boot script will hang.

  This function may only be called from the client module's
  FW_CFG_BOOT_SCRIPT_CALLBACK_FUNCTION, which was passed to
  QemuFwCfgS3CallWhenBootScriptReady() as Callback.

  @param[in] FirmwareConfigItem  The UINT16 selector key of the firmware config
                                 item to write, expressed as INT32. If
                                 FirmwareConfigItem is -1, no selection is
                                 made, the write will occur to the currently
                                 selected item, at its currently selected
                                 offset. Otherwise, the specified item will be
                                 selected, and the write will occur at offset
                                 0.

  @param[in] NumberOfBytes       Size of the data to restore in ScratchBuffer,
                                 and to write from ScratchBuffer, during S3
                                 resume. NumberOfBytes must not exceed
                                 ScratchBufferSize, which was passed to
                                 QemuFwCfgS3CallWhenBootScriptReady().

  @retval RETURN_SUCCESS            The opcodes were appended to the ACPI S3
                                    Boot Script successfully. There is no way
                                    to undo this action.

  @retval RETURN_INVALID_PARAMETER  FirmwareConfigItem is invalid.

  @retval RETURN_BAD_BUFFER_SIZE    NumberOfBytes is larger than
                                    ScratchBufferSize.

  @return                           Error codes from underlying functions.
**/
RETURN_STATUS
EFIAPI
QemuFwCfgS3ScriptWriteBytes (
  IN INT32  FirmwareConfigItem,
  IN UINTN  NumberOfBytes
  )
{
  UINTN       Count;
  EFI_STATUS  Status;
  UINT64      AccessAddress;
  UINT32      ControlPollData;
  UINT32      ControlPollMask;

  ASSERT (mDmaAccess != NULL);
  ASSERT (mS3SaveState != NULL);

  if ((FirmwareConfigItem < -1) || (FirmwareConfigItem > MAX_UINT16)) {
    return RETURN_INVALID_PARAMETER;
  }

  if (NumberOfBytes > mScratchBufferSize) {
    return RETURN_BAD_BUFFER_SIZE;
  }

  //
  // Set up a write[+select] fw_cfg DMA command.
  //
  mDmaAccess->Control = FW_CFG_DMA_CTL_WRITE;
  if (FirmwareConfigItem != -1) {
    mDmaAccess->Control |= FW_CFG_DMA_CTL_SELECT;
    mDmaAccess->Control |= (UINT32)FirmwareConfigItem << 16;
  }

  mDmaAccess->Control = SwapBytes32 (mDmaAccess->Control);

  //
  // We ensured the following constraint via mScratchBufferSize in
  // QemuFwCfgS3CallWhenBootScriptReady().
  //
  ASSERT (NumberOfBytes <= MAX_UINT32);
  mDmaAccess->Length = SwapBytes32 ((UINT32)NumberOfBytes);

  mDmaAccess->Address = SwapBytes64 ((UINTN)mScratchBuffer);

  //
  // Copy mDmaAccess and NumberOfBytes bytes from mScratchBuffer into the boot
  // script. When executed at S3 resume, this opcode will restore all of them
  // in-place.
  //
  Count  = (UINTN)mScratchBuffer + NumberOfBytes - (UINTN)mDmaAccess;
  Status = mS3SaveState->Write (
                           mS3SaveState,                     // This
                           EFI_BOOT_SCRIPT_MEM_WRITE_OPCODE, // OpCode
                           EfiBootScriptWidthUint8,          // Width
                           (UINT64)(UINTN)mDmaAccess,        // Address
                           Count,                            // Count
                           (VOID *)mDmaAccess                // Buffer
                           );
  if (EFI_ERROR (Status)) {
    DEBUG ((
      DEBUG_ERROR,
      "%a: %a: EFI_BOOT_SCRIPT_MEM_WRITE_OPCODE: %r\n",
      gEfiCallerBaseName,
      __FUNCTION__,
      Status
      ));
    return (RETURN_STATUS)Status;
  }

  //
  // Append an opcode that will write the address of the fw_cfg DMA command to
  // the fw_cfg DMA address register, which consists of two 32-bit IO ports.
  // The second (highest address, least significant) write will start the
  // transfer.
  //
  AccessAddress = SwapBytes64 ((UINTN)mDmaAccess);
  Status        = mS3SaveState->Write (
                                  mS3SaveState,                    // This
                                  EFI_BOOT_SCRIPT_IO_WRITE_OPCODE, // OpCode
                                  EfiBootScriptWidthUint32,        // Width
                                  (UINT64)FW_CFG_IO_DMA_ADDRESS,   // Address
                                  (UINTN)2,                        // Count
                                  (VOID *)&AccessAddress           // Buffer
                                  );
  if (EFI_ERROR (Status)) {
    DEBUG ((
      DEBUG_ERROR,
      "%a: %a: EFI_BOOT_SCRIPT_IO_WRITE_OPCODE: %r\n",
      gEfiCallerBaseName,
      __FUNCTION__,
      Status
      ));
    return (RETURN_STATUS)Status;
  }

  //
  // The following opcode will wait until the Control word reads as zero
  // (transfer complete). As timeout we use MAX_UINT64 * 100ns, which is
  // approximately 58494 years.
  //
  ControlPollData = 0;
  ControlPollMask = MAX_UINT32;
  Status          = mS3SaveState->Write (
                                    mS3SaveState,                        // This
                                    EFI_BOOT_SCRIPT_MEM_POLL_OPCODE,     // OpCode
                                    EfiBootScriptWidthUint32,            // Width
                                    (UINT64)(UINTN)&mDmaAccess->Control, // Address
                                    (VOID *)&ControlPollData,            // Data
                                    (VOID *)&ControlPollMask,            // DataMask
                                    MAX_UINT64                           // Delay
                                    );
  if (EFI_ERROR (Status)) {
    DEBUG ((
      DEBUG_ERROR,
      "%a: %a: EFI_BOOT_SCRIPT_MEM_POLL_OPCODE: %r\n",
      gEfiCallerBaseName,
      __FUNCTION__,
      Status
      ));
    return (RETURN_STATUS)Status;
  }

  return RETURN_SUCCESS;
}

/**
  Produce ACPI S3 Boot Script opcodes that (optionally) select an fw_cfg item,
  and transfer data from it.

  The opcodes produced by QemuFwCfgS3ScriptReadBytes() will read NumberOfBytes
  bytes from fw_cfg using DMA, storing the result in ScratchBuffer, in reserved
  memory.

  If the operation fails during S3 resume, the boot script will hang.

  This function may only be called from the client module's
  FW_CFG_BOOT_SCRIPT_CALLBACK_FUNCTION, which was passed to
  QemuFwCfgS3CallWhenBootScriptReady() as Callback.

  @param[in] FirmwareConfigItem  The UINT16 selector key of the firmware config
                                 item to read, expressed as INT32. If
                                 FirmwareConfigItem is -1, no selection is
                                 made, the read will occur from the currently
                                 selected item, from its currently selected
                                 offset. Otherwise, the specified item will be
                                 selected, and the read will occur from offset
                                 0.

  @param[in] NumberOfBytes       Size of the data to read during S3 resume.
                                 NumberOfBytes must not exceed
                                 ScratchBufferSize, which was passed to
                                 QemuFwCfgS3CallWhenBootScriptReady().

  @retval RETURN_SUCCESS            The opcodes were appended to the ACPI S3
                                    Boot Script successfully. There is no way
                                    to undo this action.

  @retval RETURN_INVALID_PARAMETER  FirmwareConfigItem is invalid.

  @retval RETURN_BAD_BUFFER_SIZE    NumberOfBytes is larger than
                                    ScratchBufferSize.

  @return                           Error codes from underlying functions.
**/
RETURN_STATUS
EFIAPI
QemuFwCfgS3ScriptReadBytes (
  IN INT32  FirmwareConfigItem,
  IN UINTN  NumberOfBytes
  )
{
  EFI_STATUS  Status;
  UINT64      AccessAddress;
  UINT32      ControlPollData;
  UINT32      ControlPollMask;

  ASSERT (mDmaAccess != NULL);
  ASSERT (mS3SaveState != NULL);

  if ((FirmwareConfigItem < -1) || (FirmwareConfigItem > MAX_UINT16)) {
    return RETURN_INVALID_PARAMETER;
  }

  if (NumberOfBytes > mScratchBufferSize) {
    return RETURN_BAD_BUFFER_SIZE;
  }

  //
  // Set up a read[+select] fw_cfg DMA command.
  //
  mDmaAccess->Control = FW_CFG_DMA_CTL_READ;
  if (FirmwareConfigItem != -1) {
    mDmaAccess->Control |= FW_CFG_DMA_CTL_SELECT;
    mDmaAccess->Control |= (UINT32)FirmwareConfigItem << 16;
  }

  mDmaAccess->Control = SwapBytes32 (mDmaAccess->Control);

  //
  // We ensured the following constraint via mScratchBufferSize in
  // QemuFwCfgS3CallWhenBootScriptReady().
  //
  ASSERT (NumberOfBytes <= MAX_UINT32);
  mDmaAccess->Length = SwapBytes32 ((UINT32)NumberOfBytes);

  mDmaAccess->Address = SwapBytes64 ((UINTN)mScratchBuffer);

  //
  // Copy mDmaAccess into the boot script. When executed at S3 resume, this
  // opcode will restore it in-place.
  //
  Status = mS3SaveState->Write (
                           mS3SaveState,                     // This
                           EFI_BOOT_SCRIPT_MEM_WRITE_OPCODE, // OpCode
                           EfiBootScriptWidthUint8,          // Width
                           (UINT64)(UINTN)mDmaAccess,        // Address
                           sizeof *mDmaAccess,               // Count
                           (VOID *)mDmaAccess                // Buffer
                           );
  if (EFI_ERROR (Status)) {
    DEBUG ((
      DEBUG_ERROR,
      "%a: %a: EFI_BOOT_SCRIPT_MEM_WRITE_OPCODE: %r\n",
      gEfiCallerBaseName,
      __FUNCTION__,
      Status
      ));
    return (RETURN_STATUS)Status;
  }

  //
  // Append an opcode that will write the address of the fw_cfg DMA command to
  // the fw_cfg DMA address register, which consists of two 32-bit IO ports.
  // The second (highest address, least significant) write will start the
  // transfer.
  //
  AccessAddress = SwapBytes64 ((UINTN)mDmaAccess);
  Status        = mS3SaveState->Write (
                                  mS3SaveState,                    // This
                                  EFI_BOOT_SCRIPT_IO_WRITE_OPCODE, // OpCode
                                  EfiBootScriptWidthUint32,        // Width
                                  (UINT64)FW_CFG_IO_DMA_ADDRESS,   // Address
                                  (UINTN)2,                        // Count
                                  (VOID *)&AccessAddress           // Buffer
                                  );
  if (EFI_ERROR (Status)) {
    DEBUG ((
      DEBUG_ERROR,
      "%a: %a: EFI_BOOT_SCRIPT_IO_WRITE_OPCODE: %r\n",
      gEfiCallerBaseName,
      __FUNCTION__,
      Status
      ));
    return (RETURN_STATUS)Status;
  }

  //
  // The following opcode will wait until the Control word reads as zero
  // (transfer complete). As timeout we use MAX_UINT64 * 100ns, which is
  // approximately 58494 years.
  //
  ControlPollData = 0;
  ControlPollMask = MAX_UINT32;
  Status          = mS3SaveState->Write (
                                    mS3SaveState,                        // This
                                    EFI_BOOT_SCRIPT_MEM_POLL_OPCODE,     // OpCode
                                    EfiBootScriptWidthUint32,            // Width
                                    (UINT64)(UINTN)&mDmaAccess->Control, // Address
                                    (VOID *)&ControlPollData,            // Data
                                    (VOID *)&ControlPollMask,            // DataMask
                                    MAX_UINT64                           // Delay
                                    );
  if (EFI_ERROR (Status)) {
    DEBUG ((
      DEBUG_ERROR,
      "%a: %a: EFI_BOOT_SCRIPT_MEM_POLL_OPCODE: %r\n",
      gEfiCallerBaseName,
      __FUNCTION__,
      Status
      ));
    return (RETURN_STATUS)Status;
  }

  return RETURN_SUCCESS;
}

/**
  Produce ACPI S3 Boot Script opcodes that (optionally) select an fw_cfg item,
  and increase its offset.

  If the operation fails during S3 resume, the boot script will hang.

  This function may only be called from the client module's
  FW_CFG_BOOT_SCRIPT_CALLBACK_FUNCTION, which was passed to
  QemuFwCfgS3CallWhenBootScriptReady() as Callback.

  @param[in] FirmwareConfigItem  The UINT16 selector key of the firmware config
                                 item to advance the offset of, expressed as
                                 INT32. If FirmwareConfigItem is -1, no
                                 selection is made, and the offset for the
                                 currently selected item is increased.
                                 Otherwise, the specified item will be
                                 selected, and the offset increment will occur
                                 from offset 0.

  @param[in] NumberOfBytes       The number of bytes to skip in the subject
                                 fw_cfg item.

  @retval RETURN_SUCCESS            The opcodes were appended to the ACPI S3
                                    Boot Script successfully. There is no way
                                    to undo this action.

  @retval RETURN_INVALID_PARAMETER  FirmwareConfigItem is invalid.

  @retval RETURN_BAD_BUFFER_SIZE    NumberOfBytes is too large.

  @return                           Error codes from underlying functions.
**/
RETURN_STATUS
EFIAPI
QemuFwCfgS3ScriptSkipBytes (
  IN INT32  FirmwareConfigItem,
  IN UINTN  NumberOfBytes
  )
{
  EFI_STATUS  Status;
  UINT64      AccessAddress;
  UINT32      ControlPollData;
  UINT32      ControlPollMask;

  ASSERT (mDmaAccess != NULL);
  ASSERT (mS3SaveState != NULL);

  if ((FirmwareConfigItem < -1) || (FirmwareConfigItem > MAX_UINT16)) {
    return RETURN_INVALID_PARAMETER;
  }

  if (NumberOfBytes > MAX_UINT32) {
    return RETURN_BAD_BUFFER_SIZE;
  }

  //
  // Set up a skip[+select] fw_cfg DMA command.
  //
  mDmaAccess->Control = FW_CFG_DMA_CTL_SKIP;
  if (FirmwareConfigItem != -1) {
    mDmaAccess->Control |= FW_CFG_DMA_CTL_SELECT;
    mDmaAccess->Control |= (UINT32)FirmwareConfigItem << 16;
  }

  mDmaAccess->Control = SwapBytes32 (mDmaAccess->Control);

  mDmaAccess->Length  = SwapBytes32 ((UINT32)NumberOfBytes);
  mDmaAccess->Address = 0;

  //
  // Copy mDmaAccess into the boot script. When executed at S3 resume, this
  // opcode will restore it in-place.
  //
  Status = mS3SaveState->Write (
                           mS3SaveState,                     // This
                           EFI_BOOT_SCRIPT_MEM_WRITE_OPCODE, // OpCode
                           EfiBootScriptWidthUint8,          // Width
                           (UINT64)(UINTN)mDmaAccess,        // Address
                           sizeof *mDmaAccess,               // Count
                           (VOID *)mDmaAccess                // Buffer
                           );
  if (EFI_ERROR (Status)) {
    DEBUG ((
      DEBUG_ERROR,
      "%a: %a: EFI_BOOT_SCRIPT_MEM_WRITE_OPCODE: %r\n",
      gEfiCallerBaseName,
      __FUNCTION__,
      Status
      ));
    return (RETURN_STATUS)Status;
  }

  //
  // Append an opcode that will write the address of the fw_cfg DMA command to
  // the fw_cfg DMA address register, which consists of two 32-bit IO ports.
  // The second (highest address, least significant) write will start the
  // transfer.
  //
  AccessAddress = SwapBytes64 ((UINTN)mDmaAccess);
  Status        = mS3SaveState->Write (
                                  mS3SaveState,                    // This
                                  EFI_BOOT_SCRIPT_IO_WRITE_OPCODE, // OpCode
                                  EfiBootScriptWidthUint32,        // Width
                                  (UINT64)FW_CFG_IO_DMA_ADDRESS,   // Address
                                  (UINTN)2,                        // Count
                                  (VOID *)&AccessAddress           // Buffer
                                  );
  if (EFI_ERROR (Status)) {
    DEBUG ((
      DEBUG_ERROR,
      "%a: %a: EFI_BOOT_SCRIPT_IO_WRITE_OPCODE: %r\n",
      gEfiCallerBaseName,
      __FUNCTION__,
      Status
      ));
    return (RETURN_STATUS)Status;
  }

  //
  // The following opcode will wait until the Control word reads as zero
  // (transfer complete). As timeout we use MAX_UINT64 * 100ns, which is
  // approximately 58494 years.
  //
  ControlPollData = 0;
  ControlPollMask = MAX_UINT32;
  Status          = mS3SaveState->Write (
                                    mS3SaveState,                        // This
                                    EFI_BOOT_SCRIPT_MEM_POLL_OPCODE,     // OpCode
                                    EfiBootScriptWidthUint32,            // Width
                                    (UINT64)(UINTN)&mDmaAccess->Control, // Address
                                    (VOID *)&ControlPollData,            // Data
                                    (VOID *)&ControlPollMask,            // DataMask
                                    MAX_UINT64                           // Delay
                                    );
  if (EFI_ERROR (Status)) {
    DEBUG ((
      DEBUG_ERROR,
      "%a: %a: EFI_BOOT_SCRIPT_MEM_POLL_OPCODE: %r\n",
      gEfiCallerBaseName,
      __FUNCTION__,
      Status
      ));
    return (RETURN_STATUS)Status;
  }

  return RETURN_SUCCESS;
}

/**
  Produce ACPI S3 Boot Script opcodes that check a value in ScratchBuffer.

  If the check fails during S3 resume, the boot script will hang.

  This function may only be called from the client module's
  FW_CFG_BOOT_SCRIPT_CALLBACK_FUNCTION, which was passed to
  QemuFwCfgS3CallWhenBootScriptReady() as Callback.

  @param[in] ScratchData  Pointer to the UINT8, UINT16, UINT32 or UINT64 field
                          in ScratchBuffer that should be checked. The caller
                          is responsible for populating the field during S3
                          resume, by calling QemuFwCfgS3ScriptReadBytes() ahead
                          of QemuFwCfgS3ScriptCheckValue().

                          ScratchData must point into ScratchBuffer, which was
                          allocated, and passed to Callback(), by
                          QemuFwCfgS3CallWhenBootScriptReady().

                          ScratchData must be aligned at ValueSize bytes.

  @param[in] ValueSize    One of 1, 2, 4 or 8, specifying the size of the field
                          to check.

  @param[in] ValueMask    The value read from ScratchData is binarily AND-ed
                          with ValueMask, and the result is compared against
                          Value. If the masked data equals Value, the check
                          passes, and the boot script can proceed. Otherwise,
                          the check fails, and the boot script hangs.

  @param[in] Value        Refer to ValueMask.

  @retval RETURN_SUCCESS            The opcodes were appended to the ACPI S3
                                    Boot Script successfully. There is no way
                                    to undo this action.

  @retval RETURN_INVALID_PARAMETER  ValueSize is invalid.

  @retval RETURN_INVALID_PARAMETER  ValueMask or Value cannot be represented in
                                    ValueSize bytes.

  @retval RETURN_INVALID_PARAMETER  ScratchData is not aligned at ValueSize
                                    bytes.

  @retval RETURN_BAD_BUFFER_SIZE    The ValueSize bytes at ScratchData aren't
                                    wholly contained in the ScratchBufferSize
                                    bytes at ScratchBuffer.

  @return                           Error codes from underlying functions.
**/
RETURN_STATUS
EFIAPI
QemuFwCfgS3ScriptCheckValue (
  IN VOID    *ScratchData,
  IN UINT8   ValueSize,
  IN UINT64  ValueMask,
  IN UINT64  Value
  )
{
  EFI_BOOT_SCRIPT_WIDTH  Width;
  EFI_STATUS             Status;

  ASSERT (mS3SaveState != NULL);

  switch (ValueSize) {
    case 1:
      Width = EfiBootScriptWidthUint8;
      break;

    case 2:
      Width = EfiBootScriptWidthUint16;
      break;

    case 4:
      Width = EfiBootScriptWidthUint32;
      break;

    case 8:
      Width = EfiBootScriptWidthUint64;
      break;

    default:
      return RETURN_INVALID_PARAMETER;
  }

  if ((ValueSize < 8) &&
      ((RShiftU64 (ValueMask, ValueSize * 8) > 0) ||
       (RShiftU64 (Value, ValueSize * 8) > 0)))
  {
    return RETURN_INVALID_PARAMETER;
  }

  if ((UINTN)ScratchData % ValueSize > 0) {
    return RETURN_INVALID_PARAMETER;
  }

  if (((UINTN)ScratchData < (UINTN)mScratchBuffer) ||
      ((UINTN)ScratchData > MAX_UINTN - ValueSize) ||
      ((UINTN)ScratchData + ValueSize >
       (UINTN)mScratchBuffer + mScratchBufferSize))
  {
    return RETURN_BAD_BUFFER_SIZE;
  }

  //
  // The following opcode will wait "until" (*ScratchData & ValueMask) reads as
  // Value, considering the least significant ValueSize bytes. As timeout we
  // use MAX_UINT64 * 100ns, which is approximately 58494 years.
  //
  Status = mS3SaveState->Write (
                           mS3SaveState,                    // This
                           EFI_BOOT_SCRIPT_MEM_POLL_OPCODE, // OpCode
                           Width,                           // Width
                           (UINT64)(UINTN)ScratchData,      // Address
                           (VOID *)&Value,                  // Data
                           (VOID *)&ValueMask,              // DataMask
                           MAX_UINT64                       // Delay
                           );
  if (EFI_ERROR (Status)) {
    DEBUG ((
      DEBUG_ERROR,
      "%a: %a: EFI_BOOT_SCRIPT_MEM_POLL_OPCODE: %r\n",
      gEfiCallerBaseName,
      __FUNCTION__,
      Status
      ));
    return (RETURN_STATUS)Status;
  }

  return RETURN_SUCCESS;
}