hc
2024-03-22 a0752693d998599af469473b8dc239ef973a012f
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
/** @file
 Implement the I2C controller driver.
 
Copyright (c) 2017, Intel Corporation. All rights reserved.<BR>
SPDX-License-Identifier: BSD-2-Clause-Patent
 
**/
 
#include <Uefi.h>
#include <Base.h>
#include <IndustryStandard/Pci.h>
#include <Library/MemoryAllocationLib.h>
#include <Library/DebugLib.h>
#include <Library/IoLib.h>
#include <Library/TimerLib.h>
#include <Library/UefiLib.h>
#include <PchAccess.h>
#include <Library/PchSerialIoLib.h>
#include <Library/BaseMemoryLib.h>
#include <Protocol/I2cMaster.h>
#include <Pi/PiI2c.h>
#include <Library/DevicePathLib.h>
#include <Library/I2cMasterCommonLib.h>
 
/**
  Prepare I2c controller for use: enable its mmio range, put in D0, get out of reset
 
  @param[in] Context - driver context
**/
VOID
PrepareController (
  I2C_MASTER_CONTEXT  *Context
  )
{
  MmioOr32 (Context->ConfigAddress + PCI_COMMAND_OFFSET, EFI_PCI_COMMAND_MEMORY_SPACE | EFI_PCI_COMMAND_BUS_MASTER);
  MmioAnd32 (Context->ConfigAddress + R_PCH_SERIAL_IO_PME_CTRL_STS, (UINT32) (~B_PCH_SERIAL_IO_PME_CTRL_STS_PWR_ST));
  MmioOr32 (Context->MmioAddress + R_PCH_SERIAL_IO_PPR_RESETS,
    B_PCH_SERIAL_IO_PPR_RESETS_FUNC | B_PCH_SERIAL_IO_PPR_RESETS_APB | B_PCH_SERIAL_IO_PPR_RESETS_IDMA);
}
 
/**
  Determine the state of the I2C controller
 
  @param[in] Context - driver context
 
  @retval TRUE              The I2C controller is active
  @retval FALSE             The I2C controller is idle
**/
BOOLEAN
IsHardwareActive (
  I2C_MASTER_CONTEXT  *Context
  )
{
  return (MmioRead32 (Context->MmioAddress + R_IC_STATUS) & B_IC_STATUS_ACTIVITY );
}
 
/**
  Updates WriteOperation and WritePosition, two variables that determine
  which part of Request is being committed to I2C bus.
  This iterates over both Read and Write operations from a request, because
  things that need to be written to WriteFifo are both I2c bus writes
  and I2c bus reads (the command to perform bus read needs to be put into Write Fifo)
 
  @param[in] Context - driver context
**/
VOID
UpdateWritePosition (
  I2C_MASTER_CONTEXT *Context
  )
{
  if ( Context->WritePos == Context->Request->Operation[Context->WriteOp].LengthInBytes - 1) {
    Context->WritePos = 0;
    Context->WriteOp ++;
  } else {
    Context->WritePos ++;
  }
}
 
/*
  FindReadOp checks if current Operation is of Read type. If so, returns.
  If not, increases ReadOp until it finds one or goes beyond Request's OperationCount
 
  @param[in] Context - driver context
*/
VOID
FindReadOp (
  I2C_MASTER_CONTEXT *Context
  )
{
  while (Context->ReadOp < Context->Request->OperationCount &&
         !(Context->Request->Operation[Context->ReadOp].Flags & I2C_FLAG_READ)) {
    Context->ReadOp++;
  }
}
 
/**
  Updates ReadOperation and ReadPosition, two variables that determine
  which part of Request is being filled with data incoming from I2C reads.
  This iterates only over Read operations from a request.
 
  @param[in] Context - driver context
**/
VOID
UpdateReadPosition (
  I2C_MASTER_CONTEXT *Context
  )
{
  if ( Context->ReadPos == Context->Request->Operation[Context->ReadOp].LengthInBytes - 1) {
    Context->ReadPos = 0;
    Context->ReadOp ++;
    FindReadOp (Context);
  } else {
    Context->ReadPos ++;
  }
}
 
/**
  ValidateRequest checks if Request is valid and can be started
 
  @param[in] Context - driver context
  @param[in] RequestPacket
 
  @retval EFI_SUCCESS           Request is valid and can be started
  @retval EFI_ALREADY_STARTED   The controller is busy with another transfer
  @retval EFI_BAD_BUFFER_SIZE   Transfer size too big
  @retval EFI_INVALID_PARAMETER RequestPacket is NULL, invalid Operation flags
  @retval EFI_UNSUPPORTED       "ping" operation attempted (0-byte transfer, address byte not followed by any data)
**/
EFI_STATUS
ValidateRequest (
  I2C_MASTER_CONTEXT           *Context,
  CONST EFI_I2C_REQUEST_PACKET *RequestPacket
  )
{
  UINTN TotalSize;
  UINTN Operation;
  UINTN OperationSize;
 
  if (Context->TransferInProgress) {
    return EFI_ALREADY_STARTED;
  }
  if (RequestPacket == NULL) {
    return EFI_INVALID_PARAMETER;
  }
 
  if (RequestPacket->OperationCount == 0) {
    // 0-size operations ("pings") not supported
    return EFI_UNSUPPORTED;
  }
 
  TotalSize = 0;
 
  for (Operation=0; Operation < RequestPacket->OperationCount; Operation++) {
    // unsupported flags?
    if ((RequestPacket->Operation[Operation].Flags & (~I2C_FLAG_READ)) != 0) {
      return EFI_INVALID_PARAMETER;
    }
    OperationSize = RequestPacket->Operation[Operation].LengthInBytes;
    // 0-size operations ("pings") not supported
    if (OperationSize == 0) {
      return EFI_UNSUPPORTED;
    }
    TotalSize += OperationSize;
    // read operation too big?
    if (RequestPacket->Operation[Operation].Flags & I2C_FLAG_READ) {
      if (OperationSize > Context->Capabilities.MaximumReceiveBytes) {
        return EFI_BAD_BUFFER_SIZE;
      }
      // write operation too big?
    } else {
      if (OperationSize > Context->Capabilities.MaximumTransmitBytes) {
        return EFI_BAD_BUFFER_SIZE;
      }
    }
  }
  // total request too big?
  if (TotalSize > Context->Capabilities.MaximumTotalBytes) {
    return EFI_BAD_BUFFER_SIZE;
  }
 
  return EFI_SUCCESS;
}
 
/**
  IsLastFromRequest checks if WritePos and WriteOp point to the last byte of the request
 
  @param[in] Context - driver context
 
  @retval Boolean
**/
BOOLEAN
IsLastFromRequest (
  I2C_MASTER_CONTEXT *Context
  )
{
  if ((Context->WriteOp == Context->Request->OperationCount - 1 ) &&
      (Context->WritePos == Context->Request->Operation[Context->WriteOp].LengthInBytes - 1)) {
    return TRUE;
  } else {
    return FALSE;
  }
}
 
/**
  IsFirstFromOperation checks if WritePos and WriteOp point to the first byte of an operation
 
  @param[in] Context - driver context
 
  @retval Boolean
**/
BOOLEAN
IsFirstFromOperation (
  I2C_MASTER_CONTEXT *Context
  )
{
  if ((Context->WriteOp != 0) && (Context->WritePos == 0)) {
    return TRUE;
  } else {
    return FALSE;
  }
}
 
/**
  InitializeTransfer checks if HW is ready to accept new transfer.
  If so, sets up slave address
 
  @param[in] Context - driver context
 
  @retval Status
**/
EFI_STATUS
InitializeTransfer (
  I2C_MASTER_CONTEXT           *Context,
  UINTN                        SlaveAddress,
  CONST EFI_I2C_REQUEST_PACKET *RequestPacket
  )
{
  UINT32 Attempts = 10000;
  UINT32 Address;
 
  Context->Request = (EFI_I2C_REQUEST_PACKET*) RequestPacket;
  Context->TransferStatus = EFI_SUCCESS;
  Context->WriteOp = 0;
  Context->WritePos = 0;
  Context->ReadOp = 0;
  FindReadOp (Context);
  Context->ReadPos = 0;
 
  if (MmioRead32 (Context->MmioAddress + R_IC_ENABLE) != 0) {
    DEBUG (( DEBUG_ERROR, "Address change was attempted while a transfer was underway!\n"));
    return EFI_DEVICE_ERROR;
  }
 
  Address = SlaveAddress & 0xFF;
  if (SlaveAddress & I2C_ADDRESSING_10_BIT
      ) {
    Address |= B_IC_TAR_10BITADDR_MASTER;
  }
  MmioWrite32 (Context->MmioAddress + R_IC_TAR, Address);
  MmioWrite32 (Context->MmioAddress + R_IC_ENABLE, B_IC_EN );
  //clear errors
  MmioRead32 (Context->MmioAddress + R_IC_CLR_TX_ABRT);
  MmioRead32 (Context->MmioAddress + R_IC_CLR_INTR);
 
  while ( !(MmioRead32 (Context->MmioAddress + R_IC_ENABLE_STATUS ) & B_IC_EN)) {
    //should never happen, but just to make sure BIOS doesn't hang in infinite loop...
    MicroSecondDelay (1);
    if (--Attempts == 0) {
      MmioWrite32 (Context->MmioAddress + R_IC_ENABLE, 0 );
      return EFI_DEVICE_ERROR;
    }
  }
  Context->TransferInProgress = TRUE;
  return EFI_SUCCESS;
}
 
/**
  WriteFifo writes to I2c controller's transmit Fifo. Data written to Fifo could be
  - data bytes to be written to an i2c slave
  - read requests that trigger i2c bus reads
  First transfer from each operation adds Restart bit which triggers Restart condition on bus
  Last transfer from the whole Request adds Stop bit which triggers Stop condtion on bus
  Driver keeps track of which parts of Request were already committed to hardware using
  pointer consisting of WritePosition and WriteOperation variables. This pointer is updated
  every time data byte/read request is committed to FIFO
  WriteFifo executes while there's anything more to write and the write fifo isn't full
 
  @param[in] Context - driver context
**/
VOID
WriteFifo (
  I2C_MASTER_CONTEXT *Context
  )
{
  UINT32 Data;
  while ( MmioRead32 (Context->MmioAddress + R_IC_STATUS ) & B_IC_STATUS_TFNF) {
    if (Context->WriteOp >= Context->Request->OperationCount ) {
      return; // request complete, nothing more to write
    }
 
    if (Context->Request->Operation[Context->WriteOp].Flags & I2C_FLAG_READ) {
      Data = B_IC_CMD_READ;
    } else {
      Data = Context->Request->Operation[Context->WriteOp].Buffer[Context->WritePos];
    }
    if (IsLastFromRequest (Context)) {
      Data |= B_IC_CMD_STOP;
    }
    if (IsFirstFromOperation (Context)) {
      Data |= B_IC_CMD_RESTART;
    }
    MmioWrite32 (Context->MmioAddress + R_IC_DATA_CMD, Data);
    UpdateWritePosition (Context);
  }
}
 
/**
  ReadFifo reads from I2c controller's receive Fifo. It contains data retrieved
  from slave device as a result of executing read transfers, which were
  triggered by putting read requests into Write Fifo. Retrieved data is copied into buffers
  pointed to by Request structure.
  Driver keeps track where to copy incoming data using pointer consisting of
  ReadPosition and ReadOperation variables. This pointer is updated
  every time data was retrieved from hardware
  ReadFifo executes while there's data available and receive buffers were not filled
 
  @param[in] Context - driver context
**/
VOID
ReadFifo (
  I2C_MASTER_CONTEXT *Context
  )
{
  while ( MmioRead32 ( Context->MmioAddress + R_IC_STATUS ) & B_IC_STATUS_RFNE) {
    if ( Context->ReadOp >= Context->Request->OperationCount ) {
      return;
    }
    Context->Request->Operation[Context->ReadOp].Buffer[Context->ReadPos] = (0xFF & MmioRead32 (Context->MmioAddress + R_IC_DATA_CMD));
    UpdateReadPosition (Context);
  }
}
 
/**
  CheckErrors checks if there were any transfer errors.
 
  @param[in] Context - driver context
**/
VOID
CheckErrors (
  I2C_MASTER_CONTEXT *Context
  )
{
  if (!(MmioRead32 (Context->MmioAddress + R_IC_INTR_STAT) & B_IC_INTR_TX_ABRT)) {
    return;
  }
  if (MmioRead32 (Context->MmioAddress + R_IC_TX_ABRT_SOURCE) & B_IC_TX_ABRT_7B_ADDR_NACK) {
    Context->TransferStatus = EFI_NO_RESPONSE;
  } else {
    Context->TransferStatus = EFI_DEVICE_ERROR;
  }
  DEBUG (( DEBUG_INFO, "I2c CheckErrors: %08x\n", MmioRead32 (Context->MmioAddress + R_IC_TX_ABRT_SOURCE)));
}
 
/**
  Transfer is finished when all requested operations were placed in fifo,
  all read requests were filled and hardware is inactive
  The last part is necessary for write-only transfers where after
  placing all writes in fifo sw needs to wait until they flush down the bus
 
  @param[in] Context - driver context
 
  @retval Boolean
**/
BOOLEAN
IsTransferFinished (
  I2C_MASTER_CONTEXT *Context
  )
{
  if (( Context->WriteOp >= Context->Request->OperationCount ) &&
      ( Context->ReadOp >= Context->Request->OperationCount ) &&
      !IsHardwareActive (Context)) {
    return TRUE;
  } else {
    return FALSE;
  }
}
 
/*
  Clean up Hw activity and errors
  Return status to Request's submitter and signal the event that tells
  it that the request is complete
  Clear up Sw context to allow new request to start
 
  @param[in] Context - driver context
*/
VOID
FinishTransfer (
  I2C_MASTER_CONTEXT *Context
  )
{
  UINT32 Attempts = 10000;
 
  MmioWrite32 ( Context->MmioAddress + R_IC_ENABLE, 0 );
 
  while ( MmioRead32 ( Context->MmioAddress + R_IC_ENABLE_STATUS ) & B_IC_EN ) {
    //try for 1ms; should take no more than 100us even at slowest bus speed, but just to make sure BIOS doesn't hang in infinite loop
    MicroSecondDelay ( 1 );
    if (--Attempts == 0) {
      ASSERT (FALSE);
      break;
    }
  }
 
  //
  //clear errors
  //
  MmioRead32 (Context->MmioAddress + R_IC_CLR_TX_ABRT);
  MmioRead32 (Context->MmioAddress + R_IC_CLR_INTR);
 
  //
  //clean up context data
  //
  Context->TransferInProgress = FALSE;
}
 
/**
  PerformTransfer. For synchronous transfer this function is called in a loop
  and for asynchronous transfers, as a timer callback. It writes data and/or
  read requests to hadrware, copies read data to destination buffers. When
  transfer completes, it cleans up Sw context and Hw registers in preparation
  for new transfer
 
  @param[in] Context - driver context
**/
VOID
PerformTransfer (
  IN I2C_MASTER_CONTEXT *Context
  )
{
  if (!Context->TransferInProgress) {
    return;
  }
  if (EFI_ERROR (Context->TransferStatus) || IsTransferFinished (Context)) {
    FinishTransfer (Context);
    return;
  }
  WriteFifo (Context);
  ReadFifo (Context);
  CheckErrors (Context);
}
 
 
/**
  Set the I2C controller bus clock frequency.
 
  This routine must be called at or below TPL_NOTIFY.
 
  The software and controller do a best case effort of using the specified
  frequency for the I2C bus.  If the frequency does not match exactly then
  the controller will use lower frequency for the I2C to avoid exceeding
  the operating conditions for any of the I2C devices on the bus.
  For example if 400 KHz was specified and the controller's divide network
  only supports 402 KHz or 398 KHz then the controller would be set to 398
  KHz.
 
  @param[in] MmioAddress    Address of I2C controller
  @param[in] BusClockHertz  New I2C bus clock frequency in Hertz
 
  @retval EFI_SUCCESS       The bus frequency was set successfully.
  @retval EFI_UNSUPPORTED   The controller does not support this frequency.
**/
 
EFI_STATUS
FrequencySet (
  IN UINTN     MmioAddress,
  IN OUT UINTN *BusClockHertz
  )
{
  UINT32             Speed;
 
  if ( *BusClockHertz < 100*1000) {
    //can't run that slowly
    return EFI_UNSUPPORTED;
  } else if ( *BusClockHertz < 400*1000) {
    //for any request in range [100kHz, 400kHz), set 100kHz
    *BusClockHertz = 100000;
    Speed = V_IC_SPEED_STANDARD;
    MmioWrite32 ( MmioAddress + R_IC_SDA_HOLD, 0x001C001C);
    MmioWrite32 ( MmioAddress + R_IC_SS_SCL_HCNT, 528);
    MmioWrite32 ( MmioAddress + R_IC_SS_SCL_LCNT, 640);
  } else if ( *BusClockHertz < 1000*1000) {
    //for any request in range [400kHz, 1MHz), set 400kHz
    *BusClockHertz = 400000;
    Speed = V_IC_SPEED_FAST;
    MmioWrite32 ( MmioAddress + R_IC_SDA_HOLD, 0x001C001C);
    MmioWrite32 ( MmioAddress + R_IC_FS_SCL_HCNT, 128);
    MmioWrite32 ( MmioAddress + R_IC_FS_SCL_LCNT, 160);
  } else {
    //for any request in range [1MHz, +inf), set 1MHz. This silicon doesn't support 3.4MHz mode.
    *BusClockHertz = 1000000;
    Speed = V_IC_SPEED_FAST;
    MmioWrite32 ( MmioAddress + R_IC_SDA_HOLD, 0x00280028);
    MmioWrite32 ( MmioAddress + R_IC_FS_SCL_HCNT, 30);
    MmioWrite32 ( MmioAddress + R_IC_FS_SCL_LCNT, 80);
  }
 
  MmioWrite32 ( MmioAddress + R_IC_CON, Speed | B_IC_RESTART_EN | B_IC_SLAVE_DISABLE | B_IC_MASTER_MODE);
 
  return EFI_SUCCESS;
}
 
 
/**
  Reset the I2C controller
 
  @param[in] MmioAddress    Address of I2C controller
 
  @retval Status
**/
EFI_STATUS
I2cReset (
  IN UINTN     MmioAddress
  )
{
  MmioAnd32 (
    MmioAddress + R_PCH_SERIAL_IO_PPR_RESETS,
    (UINT32) ~(B_PCH_SERIAL_IO_PPR_RESETS_FUNC | B_PCH_SERIAL_IO_PPR_RESETS_APB | B_PCH_SERIAL_IO_PPR_RESETS_IDMA)
    );
  MmioRead32 (MmioAddress + R_PCH_SERIAL_IO_PPR_RESETS);
  MmioOr32 (
    MmioAddress + R_PCH_SERIAL_IO_PPR_RESETS,
    B_PCH_SERIAL_IO_PPR_RESETS_FUNC | B_PCH_SERIAL_IO_PPR_RESETS_APB | B_PCH_SERIAL_IO_PPR_RESETS_IDMA
    );
  MmioRead32 (MmioAddress + R_PCH_SERIAL_IO_PPR_RESETS);
 
  return EFI_SUCCESS;
}