summaryrefslogtreecommitdiff
path: root/usb/UcmTcpciCxClientSample/I2C.cpp
blob: dee8069cd2599f7825bde801fe954560af646091 (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
/*++

Module Name:

    I2C.c

Abstract:

    This file contains the definitions for I2C functions and callbacks.

    TODO: If your port controller hardware is not compliant with the Type-C Port Controller
    Interface Specification in the respect that it does not use I2C,
    you will need to modify this file accordingly.

Environment:

    Kernel-mode Driver Framework

--*/

#include "Driver.h"
#include "I2C.tmh"

#ifdef ALLOC_PRAGMA
#pragma alloc_text (PAGE, I2CInitialize)
#pragma alloc_text (PAGE, I2COpen)
#pragma alloc_text (PAGE, I2CClose)
#pragma alloc_text (PAGE, I2CReadSynchronously)
#pragma alloc_text (PAGE, I2CWriteSynchronously)
#pragma alloc_text (PAGE, I2CPerformDeviceReset)
#pragma alloc_text (PAGE, I2CReadSynchronouslyMultiple)
#endif

NTSTATUS
I2CInitialize(
    _In_ PDEVICE_CONTEXT DeviceContext,
    _In_ WDFCMRESLIST ResourcesRaw,
    _In_ WDFCMRESLIST ResourcesTranslated
)
/*++

Routine Description:

    Initialize the I2C resource that provides a communications channel to the
    port controller hardware.

Arguments:

    DeviceContext - Context for a framework device.

    ResourcesRaw - A handle to a framework resource-list object that identifies the raw hardware
    resources that the Plug and Play manager has assigned to the device.

    ResourcesTranslated - A handle to a framework resource-list object that identifies the
    translated hardware resources that the Plug and Play manager has assigned to the device.

Return Value:

    NTSTATUS

--*/
{
    TRACE_FUNC_ENTRY(TRACE_I2C);

    UNREFERENCED_PARAMETER(ResourcesRaw);
    PAGED_CODE();

    NTSTATUS status = STATUS_SUCCESS;
    WDF_INTERRUPT_CONFIG interruptConfig;
    PCM_PARTIAL_RESOURCE_DESCRIPTOR descriptor = nullptr;
    ULONG interruptIndex = 0;
    BOOLEAN connFound = FALSE;
    BOOLEAN interruptFound = FALSE;
    ULONG resourceCount;

    // Check for I2C and Interrupt resources from the resources that PnP manager has
    // allocated to our device.
    resourceCount = WdfCmResourceListGetCount(ResourcesTranslated);

    for (ULONG i = 0; ((connFound == FALSE) || (interruptFound == FALSE)) && (i < resourceCount); i++)
    {
        descriptor = WdfCmResourceListGetDescriptor(ResourcesTranslated, i);

        switch (descriptor->Type)
        {
        case CmResourceTypeConnection:
            // Check for I2C resource
            if (descriptor->u.Connection.Class == CM_RESOURCE_CONNECTION_CLASS_SERIAL &&
                descriptor->u.Connection.Type == CM_RESOURCE_CONNECTION_TYPE_SERIAL_I2C)
            {
                DeviceContext->I2CConnectionId.LowPart = descriptor->u.Connection.IdLowPart;
                DeviceContext->I2CConnectionId.HighPart = descriptor->u.Connection.IdHighPart;

                connFound = TRUE;

                TraceEvents(TRACE_LEVEL_INFORMATION, TRACE_I2C,
                    "I2C resource found with connection id: 0x%llx",
                    DeviceContext->I2CConnectionId.QuadPart);
            }
            break;

        case CmResourceTypeInterrupt:
            // We've found an interrupt resource.
            interruptFound = TRUE;
            interruptIndex = i;
            TraceEvents(TRACE_LEVEL_INFORMATION, TRACE_I2C,
                "Interrupt resource found at index: %lu", interruptIndex);
            break;

        default:
            // We don't care about other descriptors.
            break;
        }
    }

    // Fail if either connection or interrupt resource was not found.
    if (!connFound)
    {
        status = STATUS_INSUFFICIENT_RESOURCES;
        TraceEvents(TRACE_LEVEL_ERROR, TRACE_I2C,
            "Failed finding required I2C resource. Status: %!STATUS!", status);

        goto Exit;
    }

    if (!interruptFound)
    {
        status = STATUS_INSUFFICIENT_RESOURCES;
        TraceEvents(TRACE_LEVEL_ERROR, TRACE_I2C,
            "Failed finding required interrupt resource. Status: %!STATUS!", status);

        goto Exit;
    }

    // The alerts from the port controller hardware will be handled in a passive ISR.
    // The ISR performs hardware read and write operations which block until the hardware access is complete.
    // Waiting is unacceptable at DIRQL, so we perform our ISR at PASSIVE_LEVEL.
    WDF_INTERRUPT_CONFIG_INIT(&interruptConfig, OnInterruptPassiveIsr, NULL);

    interruptConfig.PassiveHandling = TRUE;
    interruptConfig.InterruptTranslated = WdfCmResourceListGetDescriptor(ResourcesTranslated, interruptIndex);
    interruptConfig.InterruptRaw = WdfCmResourceListGetDescriptor(ResourcesRaw, interruptIndex);

    status = WdfInterruptCreate(
        DeviceContext->Device,
        &interruptConfig,
        WDF_NO_OBJECT_ATTRIBUTES,
        &DeviceContext->AlertInterrupt);
    if (!NT_SUCCESS(status))
    {
        TraceEvents(TRACE_LEVEL_ERROR, TRACE_I2C,
            "WdfInterruptCreate failed. status: %!STATUS!", status);
        goto Exit;
    }

Exit:
    TRACE_FUNC_EXIT(TRACE_I2C);
    return status;
}

NTSTATUS
I2COpen(
    _In_ PDEVICE_CONTEXT DeviceContext
)
/*++

Routine Description:

    This routine opens a handle to the I2C controller.

Arguments:

    DeviceContext - a pointer to the device context

Return Value:

    NTSTATUS

--*/
{
    TRACE_FUNC_ENTRY(TRACE_I2C);

    PAGED_CODE();

    NTSTATUS status;
    WDF_IO_TARGET_OPEN_PARAMS openParams;
    WDF_OBJECT_ATTRIBUTES requestAttributes;
    WDF_OBJECT_ATTRIBUTES workitemAttributes;
    WDF_WORKITEM_CONFIG workitemConfig;

    // Create the device path using the connection ID.
    DECLARE_UNICODE_STRING_SIZE(DevicePath, RESOURCE_HUB_PATH_SIZE);

    RESOURCE_HUB_CREATE_PATH_FROM_ID(
        &DevicePath,
        DeviceContext->I2CConnectionId.LowPart,
        DeviceContext->I2CConnectionId.HighPart);

    TraceEvents(TRACE_LEVEL_INFORMATION, TRACE_I2C,
        "Opening handle to I2C target via %wZ", &DevicePath);

    status = WdfIoTargetCreate(DeviceContext->Device, WDF_NO_OBJECT_ATTRIBUTES, &DeviceContext->I2CIoTarget);
    if (!NT_SUCCESS(status))
    {
        TraceEvents(TRACE_LEVEL_ERROR, TRACE_I2C,
            "WdfIoTargetCreate failed - %!STATUS!", status);
        goto Exit;
    }

    // Open a handle to the I2C controller.
    WDF_IO_TARGET_OPEN_PARAMS_INIT_OPEN_BY_NAME(
        &openParams,
        &DevicePath,
        (GENERIC_READ | GENERIC_WRITE));

    openParams.ShareAccess = 0;
    openParams.CreateDisposition = FILE_OPEN;
    openParams.FileAttributes = FILE_ATTRIBUTE_NORMAL;

    status = WdfIoTargetOpen(DeviceContext->I2CIoTarget, &openParams);
    if (!NT_SUCCESS(status))
    {
        TraceEvents(TRACE_LEVEL_ERROR, TRACE_I2C,
            "Failed to open I2C I/O target - %!STATUS!", status);
        goto Exit;
    }

    // Create a WDFMEMORY object. Do call WdfMemoryAssignBuffer before use it,
    status = WdfMemoryCreatePreallocated(
        WDF_NO_OBJECT_ATTRIBUTES,
        static_cast<PVOID>(&status), // initial value does not matter
        sizeof(status),
        &DeviceContext->I2CMemory);
    if (!NT_SUCCESS(status))
    {
        TraceEvents(TRACE_LEVEL_ERROR, TRACE_I2C,
            "WdfMemoryCreatePreallocated failed with status %!STATUS!", status);
        goto Exit;
    }

    WDF_OBJECT_ATTRIBUTES_INIT(&requestAttributes);
    requestAttributes.ParentObject = DeviceContext->I2CIoTarget;

    for (ULONG i = 0; i < I2CRequestSourceMax; i++)
    {
        status = WdfRequestCreate(&requestAttributes, DeviceContext->I2CIoTarget, &DeviceContext->OutgoingRequests[i]);
        if (!NT_SUCCESS(status))
        {
            TraceEvents(TRACE_LEVEL_ERROR, TRACE_I2C,
                "WdfRequestCreate failed with status %!STATUS!", status);
            goto Exit;
        }
    }

    WDF_OBJECT_ATTRIBUTES_INIT_CONTEXT_TYPE(&workitemAttributes, WORKITEM_CONTEXT);
    workitemAttributes.ParentObject = DeviceContext->I2CIoTarget;

    WDF_WORKITEM_CONFIG_INIT(&workitemConfig, EvtWorkItemGetStatus);
    status = WdfWorkItemCreate(&workitemConfig, &workitemAttributes, &DeviceContext->I2CWorkItemGetStatus);
    if (!NT_SUCCESS(status))
    {
        TraceEvents(TRACE_LEVEL_ERROR, TRACE_I2C,
            "WdfWorkItemCreate failed with status %!STATUS!", status);
        goto Exit;
    }

    WDF_WORKITEM_CONFIG_INIT(&workitemConfig, EvtWorkItemGetControl);
    status = WdfWorkItemCreate(&workitemConfig, &workitemAttributes, &DeviceContext->I2CWorkItemGetControl);
    if (!NT_SUCCESS(status))
    {
        TraceEvents(TRACE_LEVEL_ERROR, TRACE_I2C,
            "WdfWorkItemCreate failed with status %!STATUS!", status);
        goto Exit;
    }

Exit:
    TRACE_FUNC_EXIT(TRACE_I2C);
    return status;
}

void
I2CClose(
    _In_ PDEVICE_CONTEXT DeviceContext
)
/*++

Routine Description:

    This routine closes a handle to the I2C controller.

Arguments:

    DeviceContext - a pointer to the device context.

--*/
{
    TRACE_FUNC_ENTRY(TRACE_I2C);

    PAGED_CODE();

    if (DeviceContext->I2CIoTarget != WDF_NO_HANDLE)
    {
        TraceEvents(TRACE_LEVEL_INFORMATION, TRACE_I2C, "Closing handle to I2C target");
        WdfIoTargetClose(DeviceContext->I2CIoTarget);
    }

    TRACE_FUNC_EXIT(TRACE_I2C);
}

NTSTATUS
I2CWriteAsynchronously(
    _In_ PDEVICE_CONTEXT DeviceContext,
    _In_ UINT8 RegisterAddress,
    _In_reads_bytes_(Length) PVOID Data,
    _In_ ULONG Length
)
/*++

Routine Description:

    Sends data to the I2C controller to write to the specified register
    on the port controller hardware.

    Before calling, DeviceContext->IncomingRequest should be set to a valid value. The IncomingRequest
    will be completed automatically when writing is finished.

Arguments:

    DeviceContext - Context information about the device.

    RegisterAddress - The I2C register address to write data to.

    Data - Pointer to the data to write.

    Length - Length of the data to write.

Return Value:

    NTSTATUS

--*/
{
    TRACE_FUNC_ENTRY(TRACE_I2C);

    NTSTATUS status;
    WDF_REQUEST_REUSE_PARAMS reuseParams;

    if (Length == 0)
    {
        TraceEvents(TRACE_LEVEL_ERROR, TRACE_I2C, "Parameter 'Length' cannot be 0.");
        status = STATUS_INVALID_PARAMETER;
        goto Exit;
    }

    if (REGISTER_ADDR_SIZE + Length > sizeof(DeviceContext->I2CAsyncBuffer))
    {
        TraceEvents(TRACE_LEVEL_ERROR, TRACE_I2C, "Unexpected value of data length. Length: %lu. Size of buffer: %lu", Length, sizeof(DeviceContext->I2CAsyncBuffer));
        status = STATUS_INVALID_PARAMETER;
        goto Exit;
    }

    // Reuse the preallocated WDFREQUEST for I2C.
    WDF_REQUEST_REUSE_PARAMS_INIT(&reuseParams, WDF_REQUEST_REUSE_NO_FLAGS, STATUS_SUCCESS);
    status = WdfRequestReuse(DeviceContext->I2CAsyncRequest, &reuseParams);
    if (!NT_SUCCESS(status))
    {
        TraceEvents(TRACE_LEVEL_ERROR, TRACE_I2C,
            "WdfRequestReuse failed with status %!STATUS!", status);
        goto Exit;
    }

    WdfRequestSetCompletionRoutine(DeviceContext->I2CAsyncRequest, I2COnWriteCompletion, DeviceContext);

    // Combine register address and user data to write into a single buffer.
    DeviceContext->I2CAsyncBuffer[0] = RegisterAddress;

    RtlCopyMemory(&DeviceContext->I2CAsyncBuffer[REGISTER_ADDR_SIZE], Data, Length);

    status = WdfMemoryAssignBuffer(
        DeviceContext->I2CMemory,
        static_cast<PVOID>(DeviceContext->I2CAsyncBuffer),
        REGISTER_ADDR_SIZE + Length);
    if (!NT_SUCCESS(status))
    {
        TraceEvents(TRACE_LEVEL_ERROR, TRACE_I2C,
            "WdfMemoryAssignBuffer failed with status %!STATUS!", status);
    }

    status = WdfIoTargetFormatRequestForWrite(
        DeviceContext->I2CIoTarget,
        DeviceContext->I2CAsyncRequest,
        DeviceContext->I2CMemory,
        NULL,
        NULL);
    if (!NT_SUCCESS(status))
    {
        TraceEvents(TRACE_LEVEL_ERROR, TRACE_I2C,
            "WdfIoTargetFormatRequestForWrite failed with status %!STATUS!", status);
        goto Exit;
    }

    // Send the request to the I2C I/O Target.
    if (WdfRequestSend(DeviceContext->I2CAsyncRequest, DeviceContext->I2CIoTarget, NULL) == FALSE)
    {
        status = WdfRequestGetStatus(DeviceContext->I2CAsyncRequest);
        TraceEvents(TRACE_LEVEL_ERROR, TRACE_I2C,
            "[WDFREQUEST: 0x%p] WdfRequestSend for I2C write failed with status %!STATUS!",
            DeviceContext->I2CAsyncRequest, status);
        goto Exit;
    }

Exit:
    TRACE_FUNC_EXIT(TRACE_I2C);
    return status;
}

NTSTATUS
I2CReadAsynchronously(
    _In_ PDEVICE_CONTEXT DeviceContext,
    _In_ UINT8 RegisterAddress,
    _In_ ULONG Length
)
/*++

Routine Description:

    Asynchronously reads data from the port controller's registers over the I2C controller.

    Before calling, DeviceContext->IncomingRequest should be set to a valid value. The IncomingRequest
    will be completed automatically when reading is finished, and any data read out from the
    controller will be stored in the output buffer of IncomingRequest.

    Note: This function is not used in the sample yet. It is left here for future reference.

Arguments:

    DeviceContext - Context information for the port controller device.

    RegisterAddress - The I2C register address from which to read data.

    Length - Length of the data to read.

Return Value:

    NTSTATUS

--*/
{
    TRACE_FUNC_ENTRY(TRACE_I2C);

    NTSTATUS status;
    WDF_REQUEST_REUSE_PARAMS reuseParams;

    // Static analysis cannot figure out the SPB_TRANSFER_LIST_ENTRY
    // size but using an index variable quiets the warning.
    ULONG index = 0;

    // Store the address.
    DeviceContext->I2CRegisterAddress = RegisterAddress;

    if (Length == 0)
    {
        TraceEvents(TRACE_LEVEL_ERROR, TRACE_I2C, "Parameter 'Length' cannot be 0.");
        status = STATUS_INVALID_PARAMETER;
        goto Exit;
    }

    // Reuse the specified WDFREQUEST
    WDF_REQUEST_REUSE_PARAMS_INIT(&reuseParams, WDF_REQUEST_REUSE_NO_FLAGS, STATUS_SUCCESS);
    status = WdfRequestReuse(DeviceContext->I2CAsyncRequest, &reuseParams);
    if (!NT_SUCCESS(status))
    {
        TraceEvents(TRACE_LEVEL_ERROR, TRACE_I2C,
            "WdfRequestReuse failed with status %!STATUS!", status);
        goto Exit;
    }

    WdfRequestSetCompletionRoutine(DeviceContext->I2CAsyncRequest, I2COnReadCompletion, DeviceContext);

    // Prepare the I2C transfer.

    if (Length > sizeof(DeviceContext->I2CAsyncBuffer))
    {
        TraceEvents(TRACE_LEVEL_ERROR, TRACE_I2C, "Unexpected value of data length. Length: %lu. Size of buffer: %lu", Length, sizeof(DeviceContext->I2CAsyncBuffer));
        status = STATUS_INVALID_PARAMETER;
        goto Exit;
    }

    SPB_TRANSFER_LIST_AND_ENTRIES(I2C_TRANSFER_COUNT) transferList;
    SPB_TRANSFER_LIST_INIT(&(transferList.List), I2C_TRANSFER_COUNT);

    // Static analysis can't figure out the relationship between the transfer array size
    // and the transfer count.
    _Analysis_assume_(ARRAYSIZE(transferList.List.Transfers) == I2C_TRANSFER_COUNT);

    transferList.List.Transfers[index] = SPB_TRANSFER_LIST_ENTRY_INIT_SIMPLE(
        SpbTransferDirectionToDevice,
        0,
        &DeviceContext->I2CRegisterAddress,
        REGISTER_ADDR_SIZE);

    transferList.List.Transfers[index + 1] = SPB_TRANSFER_LIST_ENTRY_INIT_SIMPLE(
        SpbTransferDirectionFromDevice,
        0,
        DeviceContext->I2CAsyncBuffer,
        Length);

    // The IOCTL is METHOD_BUFFERED, so the memory (transferList) doesn't
    // have to persist until the request is completed.
    status = WdfMemoryAssignBuffer(
        DeviceContext->I2CMemory,
        static_cast<PVOID>(&transferList),
        sizeof(transferList));
    if (!NT_SUCCESS(status))
    {
        TraceEvents(TRACE_LEVEL_ERROR, TRACE_I2C,
            "WdfMemoryAssignBuffer failed with status %!STATUS!", status);
    }

    status = WdfIoTargetFormatRequestForIoctl(
        DeviceContext->I2CIoTarget,
        DeviceContext->I2CAsyncRequest,
        IOCTL_SPB_EXECUTE_SEQUENCE,
        DeviceContext->I2CMemory,
        NULL,
        NULL,
        NULL);
    if (!NT_SUCCESS(status))
    {
        TraceEvents(TRACE_LEVEL_ERROR, TRACE_I2C,
            "WdfIoTargetFormatRequestForIoctl failed with status %!STATUS!", status);
        goto Exit;
    }

    // Send the request to the I2C I/O Target.
    if (WdfRequestSend(DeviceContext->I2CAsyncRequest, DeviceContext->I2CIoTarget, NULL) == FALSE)
    {
        status = WdfRequestGetStatus(DeviceContext->I2CAsyncRequest);
        TraceEvents(TRACE_LEVEL_ERROR, TRACE_I2C,
            "[WDFREQUEST: 0x%p] WdfRequestSend for I2C read failed with status %!STATUS!",
            DeviceContext->I2CAsyncRequest, status);
        goto Exit;
    }

Exit:
    TRACE_FUNC_EXIT(TRACE_I2C);
    return status;
}

NTSTATUS
I2CReadSynchronously(
    _In_ PDEVICE_CONTEXT DeviceContext,
    _In_ I2C_REQUEST_SOURCE RequestSource,
    _In_ UINT8 RegisterAddress,
    _Out_writes_bytes_(Length) PVOID Data,
    _In_ ULONG Length
)
/*++

Routine Description:

    Synchronously reads data from the port controller's registers over the I2C controller
    for a request originating from the client driver.

Arguments:

    DeviceContext - Context information for the port controller device.

    RequestSource - Identify the caller so the correct WDFREQUEST can be re-used

    RegisterAddress - The I2C register address from which to read data.

    Length - Length of the data to read.

    Data - The data read from the registers.

Return Value:

    NTSTATUS

--*/
{
    TRACE_FUNC_ENTRY(TRACE_I2C);

    PAGED_CODE();

    NTSTATUS status;
    WDF_REQUEST_SEND_OPTIONS requestOptions;
    WDF_MEMORY_DESCRIPTOR memoryDescriptor;
    WDF_REQUEST_REUSE_PARAMS reuseParams;
    ULONG_PTR bytesTransferred = 0;
    UINT8 transferBuffer[I2C_BUFFER_SIZE];

    // Static analysis cannot figure out the SPB_TRANSFER_LIST_ENTRY
    // size but using an index variable quiets the warning.
    ULONG index = 0;

    WDFREQUEST request = DeviceContext->OutgoingRequests[RequestSource];

    // Reuse the preallocated WDFREQUEST for internal requests.
    WDF_REQUEST_REUSE_PARAMS_INIT(&reuseParams, WDF_REQUEST_REUSE_NO_FLAGS, STATUS_SUCCESS);
    status = WdfRequestReuse(request, &reuseParams);
    if (!NT_SUCCESS(status))
    {
        TraceEvents(TRACE_LEVEL_ERROR, TRACE_I2C,
            "[WDFREQUEST: 0x%p] WdfRequestReuse for I2CSyncRequest failed with status %!STATUS!",
            request, status);
        goto Exit;
    }

    if (Length == 0)
    {
        TraceEvents(TRACE_LEVEL_ERROR, TRACE_I2C, "Parameter 'Length' cannot be 0.");
        status = STATUS_INVALID_PARAMETER;
        goto Exit;
    }

    if (Length > sizeof(transferBuffer))
    {
        TraceEvents(TRACE_LEVEL_ERROR, TRACE_I2C, "Unexpected value of data length. Length: %lu. Size of buffer: %lu", Length, sizeof(transferBuffer));
        status = STATUS_INVALID_PARAMETER;
        goto Exit;
    }

    // Prepare the I2C transfer.
    SPB_TRANSFER_LIST_AND_ENTRIES(I2C_TRANSFER_COUNT) transferList;
    SPB_TRANSFER_LIST_INIT(&(transferList.List), I2C_TRANSFER_COUNT);

    // Static analysis can't figure out the relationship between the transfer array size
    // and the transfer count.
    _Analysis_assume_(ARRAYSIZE(transferList.List.Transfers) == I2C_TRANSFER_COUNT);

    transferList.List.Transfers[index] = SPB_TRANSFER_LIST_ENTRY_INIT_SIMPLE(
        SpbTransferDirectionToDevice,
        0,
        &RegisterAddress,
        REGISTER_ADDR_SIZE);

    transferList.List.Transfers[index + 1] = SPB_TRANSFER_LIST_ENTRY_INIT_SIMPLE(
        SpbTransferDirectionFromDevice,
        0,
        transferBuffer,
        Length);

    // Initialize the memory descriptor with the transfer list.
    WDF_MEMORY_DESCRIPTOR_INIT_BUFFER(&memoryDescriptor, &transferList, sizeof(transferList));

    WDF_REQUEST_SEND_OPTIONS_INIT(&requestOptions, WDF_REQUEST_SEND_OPTION_TIMEOUT);
    requestOptions.Timeout = WDF_REL_TIMEOUT_IN_MS(I2C_SYNCHRONOUS_TIMEOUT);

    // Send the request to the I2C I/O Target.
    status = WdfIoTargetSendIoctlSynchronously(DeviceContext->I2CIoTarget,
        request,
        IOCTL_SPB_EXECUTE_SEQUENCE,
        &memoryDescriptor,
        NULL,
        &requestOptions,
        &bytesTransferred);
    if (!NT_SUCCESS(status))
    {
        TraceEvents(TRACE_LEVEL_ERROR, TRACE_I2C,
            "[WDFREQUEST: 0x%p] WdfIoTargetSendIoctlSynchronously failed with status %!STATUS!",
            request, status);

        // A synchronous I2C request failing is a good indicator that I2C is unresponsive.
        // Attempt to reset the device.
        I2CPerformDeviceReset(DeviceContext);

        goto Exit;
    }

    if (bytesTransferred != REGISTER_ADDR_SIZE + Length)
    {
        TraceEvents(TRACE_LEVEL_ERROR, TRACE_I2C, "Unexpected number of bytes transferred. Expected %lu, transferred %Iu.", REGISTER_ADDR_SIZE + Length, bytesTransferred);
        status = STATUS_INFO_LENGTH_MISMATCH;
        goto Exit;
    }

    // Get the returned data out of the buffer.
    RtlCopyMemory(Data, transferBuffer, Length);
Exit:
    TRACE_FUNC_EXIT(TRACE_I2C);
    return status;
}

NTSTATUS
I2CReadSynchronouslyMultiple(
    _In_ PDEVICE_CONTEXT DeviceContext,
    _In_ I2C_REQUEST_SOURCE requestSource,
    _Inout_updates_(Count) REGISTER_ITEM* Items,
    _In_ ULONG Count
)
/*++

Routine Description:

    Synchronously reads data from the port controller's registers over the I2C controller
    for a request originating from the client driver.

Arguments:

    DeviceContext - Context information for the port controller device.

    RequestSource - Identify the caller so the correct WDFREQUEST can be re-used

    Items - Array of (register, data, length) triplets

    Count - Count of elements from the Items array above

Return Value:

    NTSTATUS

--*/
{
    TRACE_FUNC_ENTRY(TRACE_I2C);

    PAGED_CODE();

    NTSTATUS status = STATUS_SUCCESS;
    PREGISTER_ITEM item;

    for (ULONG i = 0; i < Count; i++)
    {
        item = &Items[i];
        status = I2CReadSynchronously(DeviceContext,
            requestSource,
            item->RegisterAddress,
            item->Data,
            item->Length);
        if (!NT_SUCCESS(status))
        {
            goto Exit;
        }
    }

Exit:
    TRACE_FUNC_EXIT(TRACE_I2C);
    return status;
}

NTSTATUS
I2CWriteSynchronously(
    _In_ PDEVICE_CONTEXT DeviceContext,
    _In_ I2C_REQUEST_SOURCE RequestSource,
    _In_ UINT8 RegisterAddress,
    _In_reads_(Length) PVOID Data,
    _In_ ULONG Length
)
/*++

Routine Description:

    Synchronously writes data from the port controller's registers over the I2C controller
    for a request originating from the client driver.

Arguments:

    DeviceContext - Context information for the port controller device.

    RequestSource - Identify the caller so the correct WDFREQUEST can be re-used

    RegisterAddress - The I2C register address from which to write data.

    Data - The data to write.

    Length - Length of the data to write.

Return Value:

    NTSTATUS

--*/
{
    TRACE_FUNC_ENTRY(TRACE_I2C);

    PAGED_CODE();

    NTSTATUS status;
    WDF_REQUEST_SEND_OPTIONS requestOptions;
    WDF_MEMORY_DESCRIPTOR memoryDescriptor;
    WDF_REQUEST_REUSE_PARAMS reuseParams;
    ULONG_PTR bytesTransferred = 0;
    UINT8 transferBuffer[I2C_BUFFER_SIZE];

    WDFREQUEST request = DeviceContext->OutgoingRequests[RequestSource];

    if (Length == 0)
    {
        TraceEvents(TRACE_LEVEL_ERROR, TRACE_I2C, "Parameter 'Length' cannot be 0.");
        status = STATUS_INVALID_PARAMETER;
        goto Exit;
    }

    // Reuse the preallocated WDFREQUEST for internal requests.
    WDF_REQUEST_REUSE_PARAMS_INIT(&reuseParams, WDF_REQUEST_REUSE_NO_FLAGS, STATUS_SUCCESS);
    status = WdfRequestReuse(request, &reuseParams);
    if (!NT_SUCCESS(status))
    {
        TraceEvents(TRACE_LEVEL_ERROR, TRACE_I2C,
            "[WDFREQUEST: 0x%p] WdfRequestReuse failed with status %!STATUS!",
            request, status);
        goto Exit;
    }

    transferBuffer[0] = RegisterAddress;

    if (REGISTER_ADDR_SIZE + Length > sizeof(transferBuffer))
    {
        TraceEvents(TRACE_LEVEL_ERROR, TRACE_I2C, "Unexpected value of length. Length: %lu. Size of buffer: %lu", Length, sizeof(transferBuffer));
        status = STATUS_INVALID_PARAMETER;
        goto Exit;
    }

    RtlCopyMemory(&transferBuffer[REGISTER_ADDR_SIZE], Data, Length);

    // Initialize the memory descriptor with the write buffer.
    WDF_MEMORY_DESCRIPTOR_INIT_BUFFER(&memoryDescriptor, &transferBuffer, REGISTER_ADDR_SIZE + Length);

    WDF_REQUEST_SEND_OPTIONS_INIT(&requestOptions, WDF_REQUEST_SEND_OPTION_TIMEOUT);
    requestOptions.Timeout = WDF_REL_TIMEOUT_IN_MS(I2C_SYNCHRONOUS_TIMEOUT);

    // Send the write request to the I2C I/O Target.
    status = WdfIoTargetSendWriteSynchronously(
        DeviceContext->I2CIoTarget,
        request,
        &memoryDescriptor,
        NULL,
        &requestOptions,
        &bytesTransferred);
    if (!NT_SUCCESS(status))
    {
        TraceEvents(TRACE_LEVEL_ERROR, TRACE_I2C,
            "[WDFREQUEST: 0x%p] WdfIoTargetSendWriteSynchronously failed with status %!STATUS!",
            request, status);

        // A synchronous I2C request failing is a good indicator that I2C is unresponsive.
        // Attempt to reset the device.
        I2CPerformDeviceReset(DeviceContext);

        goto Exit;
    }

    if (bytesTransferred != REGISTER_ADDR_SIZE + Length)
    {
        TraceEvents(TRACE_LEVEL_ERROR, TRACE_I2C, "Unexpected number of bytes transferred. Expected %lu, transferred %Iu.", REGISTER_ADDR_SIZE + Length, bytesTransferred);
        status = STATUS_INFO_LENGTH_MISMATCH;
        goto Exit;
    }

Exit:
    TRACE_FUNC_EXIT(TRACE_I2C);
    return status;
}

VOID
I2COnReadCompletion(
    _In_ WDFREQUEST Request,
    _In_ WDFIOTARGET Target,
    _In_ PWDF_REQUEST_COMPLETION_PARAMS Params,
    _In_ WDFCONTEXT Context
)
/*++

Routine Description:

    Completion routine for hardware access after reading. Completes the WDFREQUEST from UcmTcpciCx.

Arguments:

    Request - A handle to a framework request object that represents the completed I/O request.

    Target - A handle to an I/O target object that represents the I/O target that completed the request.

    Params - A pointer to a WDF_REQUEST_COMPLETION_PARAMS structure that contains
    information about the completed request.

    Context - Driver-supplied context information,
    which the driver specified in a previous call to WdfRequestSetCompletionRoutine. In this case,
    it is of type PDEVICE_CONTEXT.

--*/
{
    TRACE_FUNC_ENTRY(TRACE_I2C);

    UNREFERENCED_PARAMETER(Target);

    NTSTATUS status;
    PDEVICE_CONTEXT deviceContext;
    PVOID outputBuffer;
    size_t readLength = 0;

    deviceContext = (PDEVICE_CONTEXT)Context;

    status = Params->IoStatus.Status;
    if (!NT_SUCCESS(status))
    {
        TraceEvents(TRACE_LEVEL_ERROR, TRACE_I2C,
            "[WDFREQUEST: 0x%p] I2CTcpciRequestOnReadCompletion - WDFREQUEST completed with failure status: %!STATUS!",
            Request, status);
        goto Exit;
    }

    readLength = Params->IoStatus.Information;
    if (readLength <= REGISTER_ADDR_SIZE)
    {
        status = STATUS_BUFFER_TOO_SMALL;
        TraceEvents(TRACE_LEVEL_ERROR, TRACE_I2C,
            "[WDFREQUEST: 0x%p] Invalid output buffer length: %Ix",
            Request, readLength);
        readLength = 0;
        goto Exit;
    }

    // Subtract REGISTER_ADDR_SIZE from readLength to account for only the read bytes.
    readLength -= REGISTER_ADDR_SIZE;

    // Retrieve the output buffer of the pending UcmTcpciCx request
    status = WdfRequestRetrieveOutputBuffer(deviceContext->IncomingRequest, readLength, &outputBuffer, NULL);
    if (!NT_SUCCESS(status))
    {
        TraceEvents(TRACE_LEVEL_ERROR, TRACE_I2C,
            "WdfRequestRetrieveOutputBuffer failed. Status: %!STATUS!", status);
        goto Exit;
    }

    // Copy the read bytes into the output buffer of the WDFREQUEST from UcmTcpciCx.
    RtlCopyMemory(outputBuffer, deviceContext->I2CAsyncBuffer, readLength);

    WdfRequestSetInformation(deviceContext->IncomingRequest, readLength);

Exit:

    WdfRequestComplete(deviceContext->IncomingRequest, status);
    TraceEvents(TRACE_LEVEL_INFORMATION, TRACE_I2C,
        "[WDFREQUEST: 0x%p] WDFREQUEST from UcmTcpciCx completed with status: %!STATUS!", deviceContext->IncomingRequest, status);

    TRACE_FUNC_EXIT(TRACE_I2C);
}

VOID
I2COnWriteCompletion(
    _In_ WDFREQUEST Request,
    _In_ WDFIOTARGET Target,
    _In_ PWDF_REQUEST_COMPLETION_PARAMS Params,
    _In_ WDFCONTEXT Context
)
/*++

Routine Description:

    Completion routine for hardware access after a write. Completes the WDFREQUEST from UcmTcpciCx.

Arguments:

    Request - A handle to a framework request object that represents the completed I/O request.

    Target - A handle to an I/O target object that represents the I/O target that completed the request.

    Params - A pointer to a WDF_REQUEST_COMPLETION_PARAMS structure that contains
    information about the completed request.

    Context - Driver-supplied context information,
    which the driver specified in a previous call to WdfRequestSetCompletionRoutine. In this case,
    it is of type PDEVICE_CONTEXT.

--*/
{
    TRACE_FUNC_ENTRY(TRACE_I2C);

    UNREFERENCED_PARAMETER(Target);

    NTSTATUS status;
    PDEVICE_CONTEXT deviceContext;

    deviceContext = (PDEVICE_CONTEXT)Context;

    status = Params->IoStatus.Status;
    if (!NT_SUCCESS(status))
    {
        TraceEvents(TRACE_LEVEL_ERROR, TRACE_I2C,
            "[WDFREQUEST: 0x%p] I2COnWriteCompletion - WDFREQUEST completed with failure status: %!STATUS!",
            Request, status);
        goto Exit;
    }

Exit:
    // Complete the WDFREQUEST from UcmTcpciCx.
    WdfRequestComplete(deviceContext->IncomingRequest, status);
    TraceEvents(TRACE_LEVEL_INFORMATION, TRACE_I2C,
        "[WDFREQUEST: 0x%p] WDFREQUEST from UcmTcpciCx completed with status: %!STATUS!",
        deviceContext->IncomingRequest, status);

    TRACE_FUNC_EXIT(TRACE_I2C);
}

void
I2CPerformDeviceReset(
    _In_ PDEVICE_CONTEXT DeviceContext
)
/*++

Routine Description:

    Recovery mechanism for a malfunctioning I2C bus.
    Attempt a platform-level device reset.
    If unsuccessful or we have exceeded the maximum number of reset attempts, call WdfDeviceSetFailed.

Arguments:

    DeviceContext - Context information for the port controller device.

--*/
{
    TRACE_FUNC_ENTRY(TRACE_I2C);

    PAGED_CODE();

    NTSTATUS status;

    if (DeviceContext->ResetInterface.DeviceReset != NULL && DeviceContext->ResetAttempts <= MAX_DEVICE_RESET_ATTEMPTS)
    {
        // Attempt a platform-level device reset (PLDR) to recover from an I2C error.
        // This will disconnect the device from the power rail and reconnect it.

        ++DeviceContext->ResetAttempts;

        TraceEvents(TRACE_LEVEL_INFORMATION, TRACE_I2C,
            "[WDFDEVICE: 0x%p] Performing PlatformLevelDeviceReset", DeviceContext->Device);
        status = DeviceContext->ResetInterface.DeviceReset(DeviceContext->ResetInterface.Context, PlatformLevelDeviceReset, 0, NULL);
        if (!NT_SUCCESS(status))
        {
            TraceEvents(TRACE_LEVEL_ERROR, TRACE_I2C,
                "[WDFDEVICE: 0x%p] PlatformLevelDeviceReset failed with status: %!STATUS!", DeviceContext->Device, status);

            // If PLDR fails, perform WdfDeviceSetFailed.

            TraceEvents(TRACE_LEVEL_INFORMATION, TRACE_I2C,
                "[WDFDEVICE: 0x%p] Performing WdfDeviceSetFailed with WdfDeviceFailedAttemptRestart", DeviceContext->Device);

            WdfDeviceSetFailed(DeviceContext->Device, WdfDeviceFailedAttemptRestart);

            TraceEvents(TRACE_LEVEL_INFORMATION, TRACE_I2C,
                "[WDFDEVICE: 0x%p] WdfDeviceSetFailed complete", DeviceContext->Device);
        }
    }
    else
    {
        // Either platform-level device reset failed or DEVICE_RESET_INTERFACE_STANDARD was not
        // supported by the bus driver. Use WdfDeviceSetFailed and attempt to restart the device.
        // When the driver is reloaded, it will reinitialize I2C.
        // If several consecutive restart attempts fail (because the restarted driver again reports an error),
        // the framework stops trying to restart the device.

        TraceEvents(TRACE_LEVEL_INFORMATION, TRACE_I2C,
            "[WDFDEVICE: 0x%p] Performing WdfDeviceSetFailed with WdfDeviceFailedAttemptRestart",DeviceContext->Device);

        WdfDeviceSetFailed(DeviceContext->Device, WdfDeviceFailedAttemptRestart);

        TraceEvents(TRACE_LEVEL_INFORMATION, TRACE_I2C,
            "[WDFDEVICE: 0x%p] WdfDeviceSetFailed complete", DeviceContext->Device);
    }

    TRACE_FUNC_EXIT(TRACE_I2C);
}