hc
2024-03-25 edb30157bad0c0001c32b854271ace01d3b9a16a
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
/**
 * @file UsbDisplayLink.c
 * @brief USB DisplayLink Driver that manages USB DisplayLink device and produces Graphics Output Protocol
 * This file implements the functions of the Driver Binding / Start / Stop / Unload interface
 *
 * Copyright (c) 2018-2019, DisplayLink (UK) Ltd. All rights reserved.
 *
 * SPDX-License-Identifier: BSD-2-Clause-Patent
 *
**/
 
#include "UsbDisplayLink.h"
 
#include <Library/UefiRuntimeServicesTableLib.h>
#include <Library/PrintLib.h>
#include <Protocol/HiiFont.h>
 
#include "Edid.h"
#include "UsbDescriptors.h"
 
//
// Functions of Driver Binding Protocol
//
 
EFI_STATUS
EFIAPI
UsbDisplayLinkDriverBindingSupported (
  IN EFI_DRIVER_BINDING_PROTOCOL    *This,
  IN EFI_HANDLE                     Controller,
  IN EFI_DEVICE_PATH_PROTOCOL       *RemainingDevicePath
);
 
EFI_STATUS
EFIAPI
UsbDisplayLinkDriverBindingStart (
  IN EFI_DRIVER_BINDING_PROTOCOL    *This,
  IN EFI_HANDLE                     Controller,
  IN EFI_DEVICE_PATH_PROTOCOL       *RemainingDevicePath
);
 
EFI_STATUS
EFIAPI
UsbDisplayLinkDriverBindingStop (
  IN  EFI_DRIVER_BINDING_PROTOCOL   *This,
  IN  EFI_HANDLE                    Controller,
  IN  UINTN                         NumberOfChildren,
  IN  EFI_HANDLE                    *ChildHandleBuffer
);
 
EFI_STATUS
EFIAPI
UsbDisplayLinkDriverBindingEntryPoint (
  IN EFI_HANDLE           ImageHandle,
  IN EFI_SYSTEM_TABLE     *SystemTable
);
 
 
EFI_STATUS
EFIAPI
UsbDisplayLinkDriverCombinedGopBindingEntryPoint (
  IN EFI_HANDLE           ImageHandle,
  IN EFI_SYSTEM_TABLE     *SystemTable,
  IN EFI_HANDLE           DriverBindingHandle
);
 
 
// Generated with https://www.guidgen.com/ - "B70E5A79-C6D6-4267-B02E-9108C989E287"
EFI_GUID gEfiDlGopVariableGuid = { 0xB70E5A79, 0xC6D6, 0x4267,{ 0xB0, 0x2E, 0x91, 0x08, 0xC9, 0x89, 0xE2, 0x87 } };
 
 
EFI_DRIVER_BINDING_PROTOCOL gUsbDisplayLinkDriverBinding = {
  UsbDisplayLinkDriverBindingSupported,
  UsbDisplayLinkDriverBindingStart,
  UsbDisplayLinkDriverBindingStop,
  INF_DRIVER_VERSION,
  NULL,
  NULL
};
 
 
/**
 * Reads integer environment variable with default fallback.
 * @param variableName   variable name to read
 * @param defaultValue   default value to return if requested not found
 */
STATIC UINT32
ReadEnvironmentInt (
    CHAR16 *VariableName,
    UINT32 DefaultValue
    )
{
  UINT32 Result;
  UINTN DataSize;
  DataSize = sizeof (Result);
  CONST EFI_STATUS Status = gRT->GetVariable (VariableName, &gEfiDlGopVariableGuid, (UINT32*)NULL, &DataSize, &Result);
  if (!EFI_ERROR (Status) && (sizeof (Result) == DataSize)) {
    return Result;
  }
  return DefaultValue;
}
 
/**
* Reads boolean environment variable with default fallback.
* @param variableName   variable name to read
* @param defaultValue   default value to return if requested not found
*/
STATIC BOOLEAN
ReadEnvironmentBool (
    CHAR16 *VariableName,
    BOOLEAN DefaultValue
    )
{
  return ReadEnvironmentInt (VariableName, DefaultValue ? 1 : 0) == 1;
}
 
 
/**
*
* @param UsbDisplayLinkDev
* @return
*/
STATIC EFI_STATUS
InitializeUsbDisplayLinkDevice (
  IN OUT USB_DISPLAYLINK_DEV *UsbDisplayLinkDev
)
{
  EFI_GRAPHICS_OUTPUT_PROTOCOL* Gop;
  Gop = &UsbDisplayLinkDev->GraphicsOutputProtocol;
  Gop->QueryMode = DisplayLinkQueryMode;
  Gop->SetMode = DisplayLinkSetMode;
  Gop->Blt = DisplayLinkBlt;
 
  //
  // Allocate buffer for Graphics Output Protocol mode information
  //
  Gop->Mode = (EFI_GRAPHICS_OUTPUT_PROTOCOL_MODE*)AllocatePool (sizeof (EFI_GRAPHICS_OUTPUT_PROTOCOL_MODE));
  if (Gop->Mode == NULL) {
    return EFI_OUT_OF_RESOURCES;
  }
  Gop->Mode->Info = (EFI_GRAPHICS_OUTPUT_MODE_INFORMATION*)AllocatePool (sizeof (EFI_GRAPHICS_OUTPUT_MODE_INFORMATION));
  if (Gop->Mode->Info == NULL) {
    FreePool (Gop->Mode);
    Gop->Mode = NULL;
    return EFI_OUT_OF_RESOURCES;
  }
 
  Gop->Mode->MaxMode = MAX(1, DlEdidGetNumSupportedModesInEdid (UsbDisplayLinkDev->EdidActive.Edid, UsbDisplayLinkDev->EdidActive.SizeOfEdid));
 
  Gop->Mode->Mode = GRAPHICS_OUTPUT_INVALID_MODE_NUMBER;
  Gop->Mode->Info->Version = 0;
  // Initialising the horizontal resolution prevents certain BIOSs from hanging on boot, but
  // it is not yet clear why. See bug 28194.
  Gop->Mode->Info->HorizontalResolution = DlVideoModeGetSupportedVideoMode (0)->HActive;
  Gop->Mode->Info->VerticalResolution = 0;
  Gop->Mode->Info->PixelFormat = PixelBltOnly;
  Gop->Mode->Info->PixelsPerScanLine = 0;
  Gop->Mode->SizeOfInfo = sizeof (EFI_GRAPHICS_OUTPUT_MODE_INFORMATION);
  Gop->Mode->FrameBufferBase = (EFI_PHYSICAL_ADDRESS)(UINTN)NULL;
  Gop->Mode->FrameBufferSize = 0;
 
  // Prevent DlGopSendScreenUpdate from running until we are sure that the video mode is set
  UsbDisplayLinkDev->LastY2 = 0;
  UsbDisplayLinkDev->LastY1 = (UINTN)-1;
 
  return EFI_SUCCESS;
}
 
/**
  Look for alternate settings for the UsbIo handle's interface
  which offer protocol DL_PROTOCOL_DIRECT_FB.
 
  @retval -1                     Not found
  @retval Other                  The alternate setting
**/
STATIC INTN
GetDirectFbAltSetting (
    IN EFI_USB_IO_PROTOCOL *UsbIo,
    IN UINT8 ParentInterfaceNumber
    )
{
  EFI_STATUS Status;
  INTN AltSettingIndex;
  UINT16 InterfaceIndex;
 
  AltSettingIndex = -1;
 
  for (InterfaceIndex = 0; InterfaceIndex <= 0xFF; InterfaceIndex++) {
    EFI_USB_INTERFACE_DESCRIPTOR interfaceDescriptor;
    Status = UsbDisplayLinkGetInterfaceDescriptor (UsbIo, &interfaceDescriptor, (UINT8)InterfaceIndex);
    if (EFI_ERROR (Status)) {
      break;
    }
 
    if (interfaceDescriptor.InterfaceNumber == ParentInterfaceNumber &&
       (interfaceDescriptor.InterfaceClass == CLASS_VENDOR) &&
        interfaceDescriptor.InterfaceProtocol == INTERFACE_PROTOCOL_DIRECT_FB) {
      AltSettingIndex = interfaceDescriptor.AlternateSetting;
      break;
    }
  }
  return AltSettingIndex;
}
 
/**
 *
 * @param UsbIo
 * @param altSettingIndex
 * @return
 */
STATIC EFI_STATUS
SelectAltSetting (
    IN EFI_USB_IO_PROTOCOL *UsbIo,
    IN UINTN AltSettingIndex)
{
  // Set alternate setting 1 on the interface
  EFI_STATUS Status;
  UINT32 UsbStatus;
  EFI_USB_DEVICE_REQUEST Request;
  ZeroMem (&Request, sizeof (Request));
  Request.RequestType = USB_REQ_TYPE_STANDARD | USB_TARGET_INTERFACE;
  Request.Request = USB_REQ_SET_INTERFACE;
  Request.Index = DISPLAYLINK_USB_INTERFACE_NUMBER_NIVO;
  Request.Value = (UINT16)AltSettingIndex;
 
  Status = UsbIo->UsbControlTransfer (
    UsbIo,
    &Request,
    EfiUsbNoData,
    DISPLAYLINK_USB_CTRL_TIMEOUT,
    NULL,
    0,
    &UsbStatus);
 
  if (EFI_ERROR (Status)) {
    Status = EFI_UNSUPPORTED;
    DEBUG ((DEBUG_ERROR, "USB control transfer failed while attempting to select alt setting %d on interface (code %r, USB status x%x). DisplayLink device has unsupported firmware version?\n", AltSettingIndex, Status, UsbStatus));
  }
  return Status;
}
 
 
/**
  Report whether the driver can support the device attached via UsbIo
  by seeing what if any capabilities it reports.
 
  @retval TRUE     Device has sufficient capabilities for this driver.
  @retval FALSE    Device lacks sufficient capabilities.
**/
STATIC BOOLEAN
CapabilitiesSupported (
    IN EFI_USB_IO_PROTOCOL *UsbIo
    )
{
  UINT8 Buffer[256];
  EFI_STATUS Status;
 
  Status = ReadCapabilitiesDescriptor (UsbIo, Buffer, sizeof (Buffer));
  if (EFI_ERROR (Status)) {
    return FALSE;
  }
 
  VendorDescriptor descriptor;
  Status = UsbDisplayLinkParseCapabilitiesDescriptor (Buffer, sizeof (Buffer), &descriptor);
  if (EFI_ERROR (Status)) {
    DEBUG ((DEBUG_ERROR, "Failed to parse capabilities descriptor (code %r)\n", Status));
    return FALSE;
  }
 
  return UsbDisplayLinkCapabilitiesSufficientToBind (&descriptor);
}
 
 
/**
 *
 * @param UsbIo
 * @param InterfaceDescriptor
 * @param altSettingIndex
 * @return
 */
STATIC BOOLEAN
IsDLDirectFbCapableInterface (
    IN EFI_USB_IO_PROTOCOL *UsbIo,
    IN EFI_USB_INTERFACE_DESCRIPTOR  *InterfaceDescriptor,
    IN INTN *AltSettingIndex)
{
  EFI_STATUS Status;
  EFI_USB_DEVICE_DESCRIPTOR DeviceDescriptor;
 
  Status = UsbIo->UsbGetDeviceDescriptor (UsbIo, &DeviceDescriptor);
 
  if (EFI_ERROR (Status)) {
    return FALSE;
  }
 
  if (DeviceDescriptor.IdVendor != VENDOR_DISPLAYLINK) {
    return FALSE;
  }
 
  Status = UsbIo->UsbGetInterfaceDescriptor (UsbIo, InterfaceDescriptor);
  if (EFI_ERROR (Status)) {
    return FALSE;
  }
 
  // We can assume that the interface that we want to talk to - the NIVO interface - is number 0
  if (InterfaceDescriptor->InterfaceNumber != DISPLAYLINK_USB_INTERFACE_NUMBER_NIVO) {
    return FALSE;
  }
 
  // Check if we have an interface (alt setting) descriptor with the correct interface protocol
  *AltSettingIndex = GetDirectFbAltSetting (UsbIo, InterfaceDescriptor->InterfaceNumber);
 
  if (*AltSettingIndex == -1) {
    DEBUG ((DEBUG_ERROR, "DisplayLink GOP: Failed to find setting on device which supports GOP functionality. Check firmware / device version?\n"));
    return FALSE;
  }
 
  // Now check that the capabilities that we need are properly supported
  if (CapabilitiesSupported (UsbIo) == FALSE) {
    DEBUG ((DEBUG_ERROR, "DisplayLink GOP: DL device detected, but it doesn't support the required GOP features. Check firmware / device version?\n"));
    return FALSE;
  }
 
  return TRUE;
}
 
 
/**
 * Prints a block of text in the framebuffer (helper function).
 * @param X   x coordinate
 * @param Y   y coordinate
 */
STATIC VOID
DisplayLinkPrintTextToScreenInternal (
  EFI_GRAPHICS_OUTPUT_PROTOCOL *GraphicsOutput,
  UINTN X,
  UINTN Y,
  IN CHAR16 *Buffer
  )
{
  EFI_STATUS Status;
  EFI_HII_FONT_PROTOCOL *HiiFont;
  EFI_IMAGE_OUTPUT *Blt;
  EFI_FONT_DISPLAY_INFO FontInfo;
  EFI_HII_OUT_FLAGS Flags;
 
  Blt = (EFI_IMAGE_OUTPUT*)NULL;
 
  Status = gBS->LocateProtocol (&gEfiHiiFontProtocolGuid, NULL, (VOID **)&HiiFont);
  if (!EFI_ERROR (Status)) {
    Blt = (EFI_IMAGE_OUTPUT*)AllocateZeroPool (sizeof (EFI_IMAGE_OUTPUT));
    Blt->Width = (UINT16)GraphicsOutput->Mode->Info->HorizontalResolution;
    Blt->Height = (UINT16)GraphicsOutput->Mode->Info->VerticalResolution;
    Blt->Image.Screen = GraphicsOutput;
 
    ZeroMem (&FontInfo, sizeof (EFI_FONT_DISPLAY_INFO));
    FontInfo.ForegroundColor.Red = 0;
    FontInfo.ForegroundColor.Green = 0;
    FontInfo.ForegroundColor.Blue = 0;
    FontInfo.BackgroundColor.Red = 0xff;
    FontInfo.BackgroundColor.Green = 0xff;
    FontInfo.BackgroundColor.Blue = 0xff;
 
    Flags = EFI_HII_IGNORE_IF_NO_GLYPH | EFI_HII_OUT_FLAG_CLIP |
            EFI_HII_OUT_FLAG_CLIP_CLEAN_X | EFI_HII_OUT_FLAG_CLIP_CLEAN_Y |
            EFI_HII_IGNORE_LINE_BREAK | EFI_HII_DIRECT_TO_SCREEN;
 
    Status = HiiFont->StringToImage (
                           HiiFont,
                           Flags,
                           Buffer,
                           &FontInfo,
                           &Blt,
                           X,
                           Y,
                           (EFI_HII_ROW_INFO**)NULL,
                           (UINTN*)NULL,
                           (UINTN*)NULL);
  }
 
  if (Blt != NULL) {
    FreePool (Blt);
  }
}
 
 
/**
* Prints a block of text in the framebuffer.
* @param X       x coordinate
* @param Y       y coordinate
* @param Format  string format similar to stdlib's vsnprintf
* @param ...     arguments
*/
VOID
EFIAPI
DlGopPrintTextToScreen (
  EFI_GRAPHICS_OUTPUT_PROTOCOL *GraphicsOutput,
  UINTN X,
  UINTN Y,
  IN CONST CHAR16 *Format,
  ...
  )
{
  VA_LIST Marker;
  CHAR16 *Buffer;
  UINTN BufferSize;
 
  ASSERT (Format != NULL);
  ASSERT (((UINTN) Format & BIT0) == 0);
 
  VA_START(Marker, Format);
 
  BufferSize = (PcdGet32 (PcdUefiLibMaxPrintBufferSize) + 1) * sizeof (CHAR16);
 
  Buffer = (CHAR16*)AllocatePool (BufferSize);
  ASSERT (Buffer != NULL);
 
  UnicodeVSPrint (Buffer, BufferSize, Format, Marker);
 
  VA_END(Marker);
 
  DisplayLinkPrintTextToScreenInternal (GraphicsOutput, X, Y, Buffer);
 
  FreePool (Buffer);
}
 
 
/**
 * Sometimes platforms only write to the first GOP device that they find. Enabling this function allows us to copy the pixels from this device.
 * @param UsbDisplayLinkDev
 */
#ifdef COPY_PIXELS_FROM_PRIMARY_GOP_DEVICE
STATIC VOID
DisplayLinkCopyFromPrimaryGopDevice (
  IN USB_DISPLAYLINK_DEV* UsbDisplayLinkDev
  )
{
  UINTN HandleCount;
  EFI_HANDLE *HandleBuffer;
  UINTN HandleIndex;
  EFI_GRAPHICS_OUTPUT_PROTOCOL *Gop;
 
  gBS->LocateHandleBuffer (
    ByProtocol,
    &gEfiGraphicsOutputProtocolGuid,
    NULL,
    &HandleCount,
    &HandleBuffer);
 
  for (HandleIndex = 0; HandleIndex < HandleCount; HandleIndex++) {
    gBS->HandleProtocol (HandleBuffer[HandleIndex], &gEfiGraphicsOutputProtocolGuid, (VOID**)&Gop);
    if (Gop != &UsbDisplayLinkDev->GraphicsOutputProtocol && Gop->Mode->FrameBufferBase != (EFI_PHYSICAL_ADDRESS)(UINTN)NULL) {
 
    // See if we need to do a screen update - calculate a really noddy hash to see if any screen updates have happened.
    STATIC UINT32 prevframeBufferHash = 0; // 4 bytes per pixel
    UINT32 currFrameBufferHash = 0;
    UINTN i;
    for (i = 0; i < (Gop->Mode->Info->HorizontalResolution * Gop->Mode->Info->VerticalResolution); i++) {
      currFrameBufferHash += ((UINT32*)(UINTN)Gop->Mode->FrameBufferBase)[i];
    }
 
    if (currFrameBufferHash != prevframeBufferHash) {
      prevframeBufferHash = currFrameBufferHash;
 
      DisplayLinkBlt (
        &UsbDisplayLinkDev->GraphicsOutputProtocol,
        (EFI_GRAPHICS_OUTPUT_BLT_PIXEL*)(UINTN)Gop->Mode->FrameBufferBase,
        EfiBltBufferToVideo,
        0,
        0,
        0,
        0,
        Gop->Mode->Info->HorizontalResolution,
        Gop->Mode->Info->VerticalResolution,
        0);
      }
      break;
    }
  }
 
  FreePool (HandleBuffer);
}
#endif // COPY_PIXELS_FROM_PRIMARY_GOP_DEVICE
 
 
/**
 * Exit from boot services: signal handler.
 */
STATIC VOID
EFIAPI
DisplayLinkDriverExitBootServices (
  IN EFI_EVENT  Event,
  IN VOID       *Context
  )
{
  USB_DISPLAYLINK_DEV* UsbDisplayLinkDev;
  UsbDisplayLinkDev = (USB_DISPLAYLINK_DEV*)Context;
 
  gBS->CloseEvent (UsbDisplayLinkDev->TimerEvent);
}
 
/**
 * Periodic screen update: timer callback.
 */
VOID
EFIAPI
DisplayLinkPeriodicTimer (
    IN EFI_EVENT Event,
    IN VOID* Context
    )
{
  EFI_STATUS Status;
  USB_DISPLAYLINK_DEV* UsbDisplayLinkDev;
 
  Status = EFI_SUCCESS;
  UsbDisplayLinkDev = (USB_DISPLAYLINK_DEV*)Context;
 
  // Drop out if we haven't set the video mode up yet
  if (UsbDisplayLinkDev->GraphicsOutputProtocol.Mode->Mode == GRAPHICS_OUTPUT_INVALID_MODE_NUMBER) {
    // Restart the one-shot timer to poll the status again.
    Status = gBS->SetTimer (UsbDisplayLinkDev->TimerEvent, TimerRelative, DISPLAYLINK_SCREEN_UPDATE_TIMER_PERIOD);
    if (EFI_ERROR (Status)) {
      DEBUG ((DEBUG_ERROR, "Failed to create timer.\n"));
    }
    return;
  }
 
#ifdef COPY_PIXELS_FROM_PRIMARY_GOP_DEVICE
  DisplayLinkCopyFromPrimaryGopDevice (UsbDisplayLinkDev);
#endif // COPY_PIXELS_FROM_PRIMARY_GOP_DEVICE
 
  if (UsbDisplayLinkDev->ShowBandwidth) {
    STATIC UINTN Count = 0;
 
    if (Count++ % 50 == 0) {
      DlGopPrintTextToScreen (&UsbDisplayLinkDev->GraphicsOutputProtocol, 32, 48, (CONST CHAR16*)L"  Bandwidth: %d MB/s    ", UsbDisplayLinkDev->DataSent * 10000000 / DISPLAYLINK_SCREEN_UPDATE_TIMER_PERIOD / 50 / 1024 / 1024);
      UsbDisplayLinkDev->DataSent = 0;
    }
  }
 
  if (UsbDisplayLinkDev->ShowTestPattern)
  {
    if (UsbDisplayLinkDev->ShowTestPattern == 5) {
      DlGopSendTestPattern (UsbDisplayLinkDev, 0);
    } else if (UsbDisplayLinkDev->ShowTestPattern >= 10) {
      DlGopSendTestPattern (UsbDisplayLinkDev, 1);
      UsbDisplayLinkDev->ShowTestPattern = 0;
    }
    UsbDisplayLinkDev->ShowTestPattern++;
 
  }
 
  // Send the latest version of the frame buffer to the DL device over USB
  DlGopSendScreenUpdate (UsbDisplayLinkDev);
 
  // Restart the timer now we've finished
  Status = gBS->SetTimer (UsbDisplayLinkDev->TimerEvent, TimerRelative, DISPLAYLINK_SCREEN_UPDATE_TIMER_PERIOD);
  if (EFI_ERROR (Status)) {
    DEBUG ((DEBUG_ERROR, "Failed to create timer.\n"));
  }
}
 
/* ****************************************************************************************************** */
/* ****************************************************************************************************** */
/* ******************   START OF FUNCTIONS WHICH IMPLEMENT DRIVER BINDING INTERFACE    ****************** */
/* ****************************************************************************************************** */
/* ****************************************************************************************************** */
 
/**
  Check whether USB DisplayLink driver supports this device.
 
  @param  This                   The USB DisplayLink driver binding protocol.
  @param  Controller             The controller handle to check.
  @param  RemainingDevicePath    The remaining device path.
 
  @retval EFI_SUCCESS            The driver supports this controller.
  @retval other                  This device isn't supported.
 
**/
EFI_STATUS
EFIAPI
UsbDisplayLinkDriverBindingSupported (
  IN EFI_DRIVER_BINDING_PROTOCOL    *This,
  IN EFI_HANDLE                     Controller,
  IN EFI_DEVICE_PATH_PROTOCOL       *RemainingDevicePath
  )
{
  EFI_STATUS          Status;
  EFI_USB_IO_PROTOCOL *UsbIo;
 
  Status = gBS->OpenProtocol (
                  Controller,
                  &gEfiUsbIoProtocolGuid,
                  (VOID **) &UsbIo,
                  This->DriverBindingHandle,
                  Controller,
                  EFI_OPEN_PROTOCOL_BY_DRIVER);
 
  if (EFI_ERROR (Status)) {
    return Status;
  }
 
  //
  // Use the USB I/O Protocol interface to check whether Controller is
  // a DisplayLink device that can be managed by this driver.
  //
  Status = EFI_UNSUPPORTED;
  EFI_USB_INTERFACE_DESCRIPTOR DummyInterfaceDescriptor;
  INTN DummyAltSettingIndex;
 
  if (IsDLDirectFbCapableInterface (UsbIo, &DummyInterfaceDescriptor, &DummyAltSettingIndex)){
    Status = EFI_SUCCESS;
  }
 
  gBS->CloseProtocol (
        Controller,
        &gEfiUsbIoProtocolGuid,
        This->DriverBindingHandle,
        Controller);
 
  return Status;
}
 
 
/**
  Starts the DisplayLink device with this driver.
 
  This function consumes USB I/O Protocol, intializes USB DisplayLink device,
  installs Graphics Output Protocol
  Transfer to manage the USB DisplayLink device.
 
  @param  This                  The USB DisplayLink driver binding instance.
  @param  Controller            Handle of device to bind driver to.
  @param  RemainingDevicePath   Optional parameter use to pick a specific child
                                device to start.
 
  @retval EFI_SUCCESS           This driver supports this device.
  @retval EFI_UNSUPPORTED       This driver does not support this device.
  @retval EFI_DEVICE_ERROR      This driver cannot be started due to device Error.
  @retval EFI_OUT_OF_RESOURCES  Can't allocate memory resources.
  @retval EFI_ALREADY_STARTED   This driver has been started.
 
**/
EFI_STATUS
EFIAPI
UsbDisplayLinkDriverBindingStart (
  IN EFI_DRIVER_BINDING_PROTOCOL  *This,
  IN EFI_HANDLE                   Controller,
  IN EFI_DEVICE_PATH_PROTOCOL     *RemainingDevicePath
  )
{
  EFI_STATUS                      Status;
  USB_DISPLAYLINK_DEV             *UsbDisplayLinkDev;
  UINT8                           EndpointNumber;
  EFI_USB_ENDPOINT_DESCRIPTOR     EndpointDescriptor;
  UINT8                           Index;
  BOOLEAN                         FoundOut;
  BOOLEAN                         FoundIn;
  EFI_TPL                         OriginalTPL;
  INTN                            altSettingIndex;
 
  OriginalTPL = gBS->RaiseTPL (TPL_CALLBACK);
 
  UsbDisplayLinkDev = (USB_DISPLAYLINK_DEV*)AllocateZeroPool (sizeof (USB_DISPLAYLINK_DEV));
  if (UsbDisplayLinkDev == NULL) {
    DEBUG ((DEBUG_ERROR, "Device initialialisation - Failed to allocate memory for device.\n"));
    gBS->RestoreTPL (OriginalTPL);
    return EFI_OUT_OF_RESOURCES;
  }
 
  UsbDisplayLinkDev->Signature = USB_DISPLAYLINK_DEV_SIGNATURE;
 
  UsbDisplayLinkDev->ShowBandwidth = ReadEnvironmentBool (L"DisplayLinkShowBandwidth", FALSE);
  UsbDisplayLinkDev->ShowTestPattern = ReadEnvironmentBool (L"DisplayLinkShowTestPatterns", FALSE);
 
  //
  // Open USB I/O Protocol
  //
  Status = gBS->OpenProtocol (
      Controller,
      &gEfiUsbIoProtocolGuid,
      (VOID **) &UsbDisplayLinkDev->UsbIo,
      This->DriverBindingHandle,
      Controller,
      EFI_OPEN_PROTOCOL_BY_DRIVER);
 
  if (EFI_ERROR (Status)) {
    DEBUG ((DEBUG_ERROR, "Failed to open usbio protocol. Is USB correctly supported on this platform?.\n"));
    Status = EFI_UNSUPPORTED;
    goto ErrorExit2;
  }
 
  if (!IsDLDirectFbCapableInterface (UsbDisplayLinkDev->UsbIo, &UsbDisplayLinkDev->InterfaceDescriptor, &altSettingIndex)) {
    Status = EFI_UNSUPPORTED;
    goto ErrorExit4;
  }
 
  Status = SelectAltSetting (UsbDisplayLinkDev->UsbIo, altSettingIndex);
  if (EFI_ERROR (Status)) {
    DEBUG ((DEBUG_ERROR, "DisplayLink GOP: Failed to select alternate setting.\n"));
    Status = EFI_UNSUPPORTED;
    goto ErrorExit4;
  }
 
  //
  // Parse endpoint descriptor
  //
  EndpointNumber = UsbDisplayLinkDev->InterfaceDescriptor.NumEndpoints;
 
  //
  // Traverse endpoints to find bulk endpoint
  //
  FoundOut = FALSE;
  FoundIn = FALSE;
  for (Index = 0; Index < EndpointNumber; Index++) {
    UsbDisplayLinkDev->UsbIo->UsbGetEndpointDescriptor (
             UsbDisplayLinkDev->UsbIo,
             Index,
             &EndpointDescriptor);
 
    if ((EndpointDescriptor.Attributes & (BIT0 | BIT1)) == USB_ENDPOINT_BULK) {
      if (!FoundOut && (EndpointDescriptor.EndpointAddress & BIT7) == 0) {
        CopyMem (&UsbDisplayLinkDev->BulkOutEndpointDescriptor, &EndpointDescriptor, sizeof (EndpointDescriptor));
        FoundOut = TRUE;
      } else if (!FoundIn && (EndpointDescriptor.EndpointAddress & BIT7) == BIT7) {
        CopyMem (&UsbDisplayLinkDev->BulkInEndpointDescriptor, &EndpointDescriptor, sizeof (EndpointDescriptor));
        FoundIn = TRUE;
      }
    }
  }
 
  if (FoundOut == FALSE) {
    Status = EFI_UNSUPPORTED;
    DEBUG ((DEBUG_ERROR, "No endpoints found.  Num endpoints searched = %d.\n", EndpointNumber));
    goto ErrorExit4;
  }
 
  Status = DlReadEdid (UsbDisplayLinkDev);
  if (EFI_ERROR (Status)) {
    DEBUG ((DEBUG_ERROR, "Failed to read monitor EDID from DisplayLink device (code %r)\n", Status));
    goto ErrorExit7;
  }
 
  Status = InitializeUsbDisplayLinkDevice (UsbDisplayLinkDev);
  if (EFI_ERROR (Status)) {
    DEBUG ((DEBUG_ERROR, "Failed to initialise DisplayLink device (code %r)\n", Status));
    goto ErrorExit7;
  }
 
  Status = gBS->InstallMultipleProtocolInterfaces (
      &Controller,
      &gEfiGraphicsOutputProtocolGuid,
      &UsbDisplayLinkDev->GraphicsOutputProtocol,
      &gEfiEdidDiscoveredProtocolGuid,
      &UsbDisplayLinkDev->EdidDiscovered,
      &gEfiEdidActiveProtocolGuid,
      &UsbDisplayLinkDev->EdidActive,
      NULL);
 
  if (EFI_ERROR (Status)) {
    DEBUG ((DEBUG_ERROR, "Failed to install Graphics Output and EDID protocol interfaces - driver not installed correctly - %r\n", Status));
    goto ErrorExit8;
  }
 
  UsbDisplayLinkDev->ControllerNameTable = (EFI_UNICODE_STRING_TABLE*)NULL;
 
  AddUnicodeString2 (
    "eng",
    mUsbDisplayLinkComponentName.SupportedLanguages,
    &UsbDisplayLinkDev->ControllerNameTable,
    (CONST CHAR16*)L"Generic Usb DisplayLink",
    TRUE);
 
  AddUnicodeString2 (
    "en",
    mUsbDisplayLinkComponentName2.SupportedLanguages,
    &UsbDisplayLinkDev->ControllerNameTable,
    (CONST CHAR16*)L"Generic Usb DisplayLink",
    FALSE);
 
  //
  // Setup a periodic timer
  //
  Status = gBS->CreateEvent (
                  EVT_TIMER | EVT_NOTIFY_SIGNAL,
                  TPL_CALLBACK,
                  DisplayLinkPeriodicTimer,
                  UsbDisplayLinkDev,
                  &UsbDisplayLinkDev->TimerEvent);
 
  if (EFI_ERROR (Status)) {
    Status = EFI_OUT_OF_RESOURCES;
    DEBUG ((DEBUG_ERROR, "Failed to create screeen update polling event.\n"));
    goto ErrorExit8;
  }
 
  // Start one-shot timer. The rendering operations can take quite a long time, so we
  // don't want another timer event to happen until we have finished; so we'll restart
  // the timer from DisplayLinkPeriodicTimer, the event handler function.
  Status = gBS->SetTimer (UsbDisplayLinkDev->TimerEvent, TimerRelative, DISPLAYLINK_SCREEN_UPDATE_TIMER_PERIOD);
  if (EFI_ERROR (Status)) {
    Status = EFI_OUT_OF_RESOURCES;
    DEBUG ((DEBUG_ERROR, "Failed to create screen update polling timer.\n"));
    goto ErrorExit8;
  }
 
  Status = gBS->CreateEventEx (
                  EVT_NOTIFY_SIGNAL,
                  TPL_NOTIFY,
                  DisplayLinkDriverExitBootServices,
                  UsbDisplayLinkDev,
                  &gEfiEventExitBootServicesGuid,
                  &UsbDisplayLinkDev->DriverExitBootServicesEvent);
 
  if (EFI_ERROR (Status)) {
    Status = EFI_OUT_OF_RESOURCES;
    DEBUG ((DEBUG_ERROR, "Failed to create event for bootexit.\n"));
    goto ErrorExit8;
  }
 
  gBS->RestoreTPL (OriginalTPL);
 
  DEBUG ((DEBUG_INFO, "DisplayLink GOP driver successfully bound to device.\n"));
 
  return EFI_SUCCESS;
 
  //
  // Error handler
  //
 ErrorExit8:
 ErrorExit7:
 ErrorExit4:
  gBS->CloseProtocol (
   Controller,
   &gEfiUsbIoProtocolGuid,
   This->DriverBindingHandle,
   Controller);
 
 ErrorExit2:
  if (UsbDisplayLinkDev != NULL) {
    FreePool (UsbDisplayLinkDev);
    UsbDisplayLinkDev = (USB_DISPLAYLINK_DEV*)NULL;
  }
 
  DEBUG ((DEBUG_ERROR, "Exiting - Failed to initialise driver.\n"));
 
  gBS->RestoreTPL (OriginalTPL);
  return Status;
}
 
/**
Entrypoint of USB DisplayLink Driver.
 
This function is the entrypoint of a combined USB DisplayLink GOP Driver. It installs Driver Binding
Protocols together with Component Name Protocols.
 
@param  ImageHandle       The firmware allocated handle for the EFI image.
@param  SystemTable       A pointer to the EFI System Table.
@param  DriverBindingHandle  The Driver binding handle
 
@retval EFI_SUCCESS       The entry point is executed successfully.
 
**/
EFI_STATUS
EFIAPI
UsbDisplayLinkDriverCombinedGopBindingEntryPoint (
  IN EFI_HANDLE           ImageHandle,
  IN EFI_SYSTEM_TABLE     *SystemTable,
  IN EFI_HANDLE           DriverBindingHandle
)
{
  EFI_STATUS Status;
 
  Status = EfiLibInstallDriverBindingComponentName2 (
    ImageHandle,
    SystemTable,
    &gUsbDisplayLinkDriverBinding,
    DriverBindingHandle,
    &mUsbDisplayLinkComponentName,
    &mUsbDisplayLinkComponentName2);
 
  ASSERT_EFI_ERROR (Status);
 
  return EFI_SUCCESS;
}
 
 
/**
Entrypoint of USB DisplayLink Driver.
 
This function is the entrypoint of USB DisplayLink Driver. It installs Driver Binding
Protocols together with Component Name Protocols.
 
@param  ImageHandle       The firmware allocated handle for the EFI image.
@param  SystemTable       A pointer to the EFI System Table.
 
@retval EFI_SUCCESS       The entry point is executed successfully.
 
**/
EFI_STATUS
EFIAPI
UsbDisplayLinkDriverBindingEntryPoint (
  IN EFI_HANDLE           ImageHandle,
  IN EFI_SYSTEM_TABLE     *SystemTable
)
{
  return UsbDisplayLinkDriverCombinedGopBindingEntryPoint (ImageHandle, SystemTable, ImageHandle);
}
 
 
/**
Unloads an image.
@param  ImageHandle           Handle that identifies the image to be unloaded.
@retval EFI_SUCCESS           The image has been unloaded.
@retval EFI_INVALID_PARAMETER ImageHandle is not a valid image handle.
**/
EFI_STATUS
EFIAPI
UsbDisplayLinkDriverCombinedGopUnload (
  IN EFI_HANDLE  ImageHandle
)
{
  EFI_STATUS  Status = EFI_SUCCESS;
  EFI_STATUS  handleDisconnectStatus;
  EFI_HANDLE  *HandleBuffer;
  UINTN       HandleCount;
  UINTN       Index;
 
  //
  // Retrieve array of all handles in the handle database
  //
  handleDisconnectStatus = gBS->LocateHandleBuffer (
    AllHandles,
    NULL,
    NULL,
    &HandleCount,
    &HandleBuffer
  );
  if (! EFI_ERROR (handleDisconnectStatus)) {
    //
    // Disconnect the current driver from handles in the handle database
    //
    for (Index = 0; Index < HandleCount; Index++) {
      Status = gBS->DisconnectController (HandleBuffer[Index], gImageHandle, NULL);
    }
    //
    // Free the array of handles
    //
    if (HandleBuffer != NULL)
    {
      FreePool (HandleBuffer);
    }
  }
 
  // Even if we didn't manage to disconnect the handles, try to uninstall the protocols
  //
  // Uninstall protocols installed in the driver entry point
  //
  Status = gBS->UninstallMultipleProtocolInterfaces (
    ImageHandle,
    &gEfiDriverBindingProtocolGuid,
    &gUsbDisplayLinkDriverBinding,
    &gEfiComponentNameProtocolGuid,
    &mUsbDisplayLinkComponentName,
    &gEfiComponentName2ProtocolGuid,
    &mUsbDisplayLinkComponentName2,
    NULL
  );
 
  if (EFI_ERROR (handleDisconnectStatus))
  {
    return handleDisconnectStatus;
  }
  return Status;
}
 
 
/**
  Stop the USB DisplayLink device handled by this driver.
 
  @param  This                   The USB DisplayLink driver binding protocol.
  @param  Controller             The controller to release.
  @param  NumberOfChildren       The number of handles in ChildHandleBuffer.
  @param  ChildHandleBuffer      The array of child handle.
 
  @retval EFI_SUCCESS            The device was stopped.
  @retval EFI_UNSUPPORTED        Simple Pointer Protocol is not installed on Controller.
  @retval Others                 Fail to uninstall protocols attached on the device.
 
**/
EFI_STATUS
EFIAPI
UsbDisplayLinkDriverBindingStop (
  IN  EFI_DRIVER_BINDING_PROTOCOL   *This,
  IN  EFI_HANDLE                    Controller,
  IN  UINTN                         NumberOfChildren,
  IN  EFI_HANDLE                    *ChildHandleBuffer
  )
{
  EFI_STATUS                        Status;
  USB_DISPLAYLINK_DEV               *UsbDisplayLinkDev;
  EFI_GRAPHICS_OUTPUT_PROTOCOL      *GraphicsOutputProtocol;
 
  Status = gBS->OpenProtocol (
                  Controller,
                  &gEfiGraphicsOutputProtocolGuid,
                  (VOID **) &GraphicsOutputProtocol,
                  This->DriverBindingHandle,
                  Controller,
                  EFI_OPEN_PROTOCOL_GET_PROTOCOL);
 
  if (EFI_ERROR (Status)) {
    return EFI_UNSUPPORTED;
  }
 
  UsbDisplayLinkDev = USB_DISPLAYLINK_DEV_FROM_GRAPHICS_OUTPUT_PROTOCOL(GraphicsOutputProtocol);
 
  // Reset the video mode to clear the display. Don't drop out if there is a problem, just press on.
  // Note that this will also clear the frame buffer, as the screen buffer will be re-allocated with AllocateZeroPool.
  if ((GraphicsOutputProtocol->Mode != NULL) &&
      (GraphicsOutputProtocol->Mode->Mode != GRAPHICS_OUTPUT_INVALID_MODE_NUMBER)) {
    Status = DisplayLinkSetMode (GraphicsOutputProtocol, GraphicsOutputProtocol->Mode->Mode);
    if (EFI_ERROR (Status)) {
      DEBUG ((DEBUG_WARN, "Driver stop - Problem resetting video mode - %r.\n", Status));
    }
  }
 
  // Reset the alt setting on the interface (to the DL3 alt setting)
  Status = SelectAltSetting (UsbDisplayLinkDev->UsbIo, 0);
  if (EFI_ERROR (Status)) {
    DEBUG ((DEBUG_WARN, "Error resetting USB interface alternate setting - %r.\n", Status));
  }
 
  Status = gBS->UninstallMultipleProtocolInterfaces (
                  Controller,
                  &gEfiGraphicsOutputProtocolGuid,
                  &UsbDisplayLinkDev->GraphicsOutputProtocol,
                  &gEfiEdidDiscoveredProtocolGuid,
                  &UsbDisplayLinkDev->EdidDiscovered,
                  &gEfiEdidActiveProtocolGuid,
                  &UsbDisplayLinkDev->EdidActive,
                  NULL);
 
  if (EFI_ERROR (Status)) {
    DEBUG ((DEBUG_WARN, "Error uninstalling Graphics Output and EDID protocol interfaces - %r.\n", Status));
    return Status;
  }
 
  gBS->CloseEvent (UsbDisplayLinkDev->TimerEvent);
 
  gBS->CloseProtocol (
         Controller,
         &gEfiUsbIoProtocolGuid,
         This->DriverBindingHandle,
         Controller);
 
  //
  // Free all resources.
  //
  if (UsbDisplayLinkDev->ControllerNameTable != NULL) {
    FreeUnicodeStringTable (UsbDisplayLinkDev->ControllerNameTable);
  }
 
  if (UsbDisplayLinkDev->Screen != NULL) {
    FreePool (UsbDisplayLinkDev->Screen);
    UsbDisplayLinkDev->Screen = NULL;
  }
 
  if (UsbDisplayLinkDev->GraphicsOutputProtocol.Mode) {
    if (UsbDisplayLinkDev->GraphicsOutputProtocol.Mode->Info) {
      FreePool (UsbDisplayLinkDev->GraphicsOutputProtocol.Mode->Info);
      UsbDisplayLinkDev->GraphicsOutputProtocol.Mode->Info = NULL;
    }
    FreePool (UsbDisplayLinkDev->GraphicsOutputProtocol.Mode);
    UsbDisplayLinkDev->GraphicsOutputProtocol.Mode = NULL;
  }
 
  FreePool (UsbDisplayLinkDev);
 
  return EFI_SUCCESS;
 
}