summaryrefslogtreecommitdiff
path: root/Platform/Comcast/Library/RdkBootManagerLib/DiskIo.c
blob: 1e009e88d1cd089d71fa99bf508b5854a1dabb2d (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
/*
#  Copyright (c) 2014-2018, Linaro Limited. All rights reserved.
#
#  This program and the accompanying materials
#  are licensed and made available under the terms and conditions of the BSD License
#  which accompanies this distribution.  The full text of the license may be found at
#  http://opensource.org/licenses/bsd-license.php
#
#  THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
#  WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
#
*/
#include <RdkBootManagerLib.h>

/* See sparse_format.h in AOSP  */
#define SPARSE_HEADER_MAGIC       0xed26ff3a
#define CHUNK_TYPE_RAW            0xCAC1
#define CHUNK_TYPE_FILL           0xCAC2
#define CHUNK_TYPE_DONT_CARE      0xCAC3
#define CHUNK_TYPE_CRC32          0xCAC4

#define PARTITION_NAME_MAX_LENGTH     72/2

#define FLASH_DEVICE_PATH_SIZE(DevPath) ( GetDevicePathSize (DevPath) - \
    sizeof (EFI_DEVICE_PATH_PROTOCOL))

#define IS_ALPHA(Char) (((Char) <= L'z' && (Char) >= L'a') || \
    ((Char) <= L'Z' && (Char) >= L'Z'))

typedef struct _DISKIO_PARTITION_LIST {
  LIST_ENTRY  Link;
  CHAR16      PartitionName[PARTITION_NAME_MAX_LENGTH];
  EFI_HANDLE  PartitionHandle;
} DISKIO_PARTITION_LIST;

typedef struct _SPARSE_HEADER {
  UINT32    Magic;
  UINT16    MajorVersion;
  UINT16    MinorVersion;
  UINT16    FileHeaderSize;
  UINT16    ChunkHeaderSize;
  UINT32    BlockSize;
  UINT32    TotalBlocks;
  UINT32    TotalChunks;
  UINT32    ImageChecksum;
} SPARSE_HEADER;

typedef struct _CHUNK_HEADER {
  UINT16    ChunkType;
  UINT16    Reserved1;
  UINT32    ChunkSize;
  UINT32    TotalSize;
} CHUNK_HEADER;

STATIC LIST_ENTRY       mPartitionListHead;
STATIC EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL  *mTextOut;

/*
 * Helper to free the partition list
 */
STATIC
VOID
FreePartitionList (
  VOID
)
{
  DISKIO_PARTITION_LIST *Entry;
  DISKIO_PARTITION_LIST *NextEntry;

  Entry = (DISKIO_PARTITION_LIST *)GetFirstNode (&mPartitionListHead);
  while (!IsNull (&mPartitionListHead, &Entry->Link)) {
    NextEntry = (DISKIO_PARTITION_LIST *) GetNextNode (\
      &mPartitionListHead, &Entry->Link);

    RemoveEntryList (&Entry->Link);
    FreePool (Entry);

    Entry = NextEntry;
  }
}

/*
 * lists the available Block Io and adds handle of given dev path
 */
STATIC
EFI_STATUS
ListBlockIos (
  IN CHAR16       *PartitionName
  )
{
  EFI_STATUS                        Status;
  EFI_HANDLE                        *AllHandles;
  EFI_DEVICE_PATH_TO_TEXT_PROTOCOL  *DevPathToText;
  EFI_DEVICE_PATH_PROTOCOL          *DevicePath;
  UINTN                             LoopIndex;
  UINTN                             NumHandles;
  UINT16                            *DeviceFullPath;
  DISKIO_PARTITION_LIST             *Entry;

  InitializeListHead (&mPartitionListHead);

  Status = gBS->LocateProtocol (
    &gEfiDevicePathToTextProtocolGuid,
    NULL,
    (VOID **) &DevPathToText
    );
  ASSERT_EFI_ERROR (Status);

  // Get every Block IO protocol instance installed in the system
  Status = gBS->LocateHandleBuffer (
    ByProtocol,
    &gEfiBlockIoProtocolGuid,
    NULL,
    &NumHandles,
    &AllHandles
    );
  ASSERT_EFI_ERROR (Status);
  DEBUG ((DEBUG_INFO, "Block IO: %d handles \n", NumHandles));

  // Get HTTP driver handle from AllHandles
  for (LoopIndex = 0; LoopIndex < NumHandles; LoopIndex++) {
    // Get the device path for the handle
    Status = gBS->OpenProtocol (
      AllHandles[LoopIndex],
      &gEfiDevicePathProtocolGuid,
      (VOID **) &DevicePath,
      gImageHandle,
      NULL,
      EFI_OPEN_PROTOCOL_GET_PROTOCOL
      );

    DeviceFullPath = DevPathToText->ConvertDevicePathToText (
      DevicePath,
      FALSE,
      TRUE
      );

    DEBUG((DEBUG_INFO,"Handle[%d] is %p, fullpath %s\n", \
      LoopIndex, AllHandles[LoopIndex], DeviceFullPath));

    if (StrCmp (PartitionName, DeviceFullPath) == 0) {
      DEBUG((DEBUG_INFO, "rootfs partition path matched\n"));
      //
      // Add the partition handle to the list
      //
      // Create entry
      Entry = AllocatePool (sizeof (DISKIO_PARTITION_LIST));
      if (Entry == NULL) {
        Status = EFI_OUT_OF_RESOURCES;
        goto Exit;
      }

      // Copy handle and partition name
      Entry->PartitionHandle = AllHandles[LoopIndex];
      StrnCpy (
        Entry->PartitionName,
        PartitionName,
        PARTITION_NAME_MAX_LENGTH
      );
      InsertTailList (&mPartitionListHead, &Entry->Link);
      break;
    }
  }
  FreePool (AllHandles);
  ASSERT (LoopIndex < NumHandles);
Exit:
  return Status;
}

STATIC
EFI_STATUS
OpenPartition (
  IN  CHAR8       *PartitionName,
  IN  VOID        *Image,
  IN  UINTN       Size,
  OUT EFI_BLOCK_IO_PROTOCOL     **BlockIo,
  OUT EFI_DISK_IO_PROTOCOL      **DiskIo
  )
{
  EFI_STATUS               Status;
  UINTN                    PartitionSize;
  DISKIO_PARTITION_LIST    *Entry;
  SPARSE_HEADER            *SparseHeader;
  UINT16                   UnicodePartitionName[100];

  AsciiStrToUnicodeStr ( PartitionName, UnicodePartitionName);
  DEBUG((DEBUG_INFO, "Unicode partition name %s\n", UnicodePartitionName));

  Status = ListBlockIos (UnicodePartitionName);
  ASSERT_EFI_ERROR (Status);

  Entry = (DISKIO_PARTITION_LIST *)GetFirstNode (&(mPartitionListHead));
  ASSERT (Entry != NULL);

  Status = gBS->OpenProtocol (
    Entry->PartitionHandle,
    &gEfiBlockIoProtocolGuid,
    (VOID **) BlockIo,
    gImageHandle,
    NULL,
    EFI_OPEN_PROTOCOL_GET_PROTOCOL
    );

  if (EFI_ERROR (Status)) {
    DEBUG ((DEBUG_ERROR, "Unable to open Block IO protocol: %r\n", Status));
    Status = EFI_NOT_FOUND;
    goto Exit;
  }

  SparseHeader = (SPARSE_HEADER *)Image;

  if (SparseHeader->Magic == SPARSE_HEADER_MAGIC) {
    DEBUG ((DEBUG_INFO, \
      "Sparse Magic: 0x%x Major: %d Minor: %d fhs: %d chs: %d bs: %d tbs: %d tcs: %d checksum: %d \n", \
      SparseHeader->Magic, SparseHeader->MajorVersion, \
      SparseHeader->MinorVersion,  SparseHeader->FileHeaderSize, \
      SparseHeader->ChunkHeaderSize, SparseHeader->BlockSize, \
      SparseHeader->TotalBlocks, \
      SparseHeader->TotalChunks, SparseHeader->ImageChecksum));

    if (SparseHeader->MajorVersion != 1) {
      DEBUG ((DEBUG_ERROR, "Sparse image version %d.%d not supported.\n",
            SparseHeader->MajorVersion, SparseHeader->MinorVersion));
      Status = EFI_INVALID_PARAMETER;
      goto Exit;
    }

    Size = SparseHeader->BlockSize * SparseHeader->TotalBlocks;
  }

  // Check image will fit on device
  PartitionSize = (BlockIo[0]->Media->LastBlock + 1) * BlockIo[0]->Media->BlockSize;
  if (PartitionSize < Size) {
    DEBUG ((DEBUG_ERROR, "Partition not big enough.\n"));
    DEBUG ((DEBUG_ERROR, \
      "Partition Size:\t%ld\nImage Size:\t%ld\n", PartitionSize, Size));

    Status = EFI_VOLUME_FULL;
    goto Exit;
  }

  Status = gBS->OpenProtocol (
    Entry->PartitionHandle,
    &gEfiDiskIoProtocolGuid,
    (VOID **) DiskIo,
    gImageHandle,
    NULL,
    EFI_OPEN_PROTOCOL_GET_PROTOCOL
    );

Exit:
  FreePartitionList ();
  return Status;
}

EFI_STATUS
PartitionRead (
  IN CHAR8  *PartitionName,
  IN VOID   *Image,
  IN UINTN  Size
  )
{
  EFI_STATUS               Status;
  EFI_BLOCK_IO_PROTOCOL    *BlockIo;
  EFI_DISK_IO_PROTOCOL     *DiskIo;
  UINT32                   MediaId;

  Status = OpenPartition (PartitionName, Image, Size, &BlockIo, &DiskIo);
  if (EFI_ERROR (Status)) {
    goto Exit;
  }

  MediaId = BlockIo->Media->MediaId;

  Status = DiskIo->ReadDisk (DiskIo, MediaId, 0, Size, Image);
  if (EFI_ERROR (Status)) {
    goto Exit;
  }

  BlockIo->FlushBlocks(BlockIo);

Exit:
  return Status;
}

EFI_STATUS
PartitionWrite (
  IN CHAR8  *PartitionName,
  IN VOID   *Image,
  IN UINTN  Size
  )
{
  EFI_STATUS               Status;
  EFI_BLOCK_IO_PROTOCOL    *BlockIo;
  EFI_DISK_IO_PROTOCOL     *DiskIo;
  UINT32                   MediaId;
  SPARSE_HEADER            *SparseHeader;
  CHUNK_HEADER             *ChunkHeader;
  UINT32                   Chunk;
  UINTN                    Offset;

  Status = OpenPartition (PartitionName, Image, Size, &BlockIo, &DiskIo);
  if (EFI_ERROR (Status)) {
    goto Exit;
  }

  Offset = 0;
  MediaId = BlockIo->Media->MediaId;
  SparseHeader = (SPARSE_HEADER *)Image;

  if (SparseHeader->Magic == SPARSE_HEADER_MAGIC) {
    CHAR16 OutputString[64];
    UINTN ChunkPrintDensity =
      SparseHeader->TotalChunks > 1600 ? SparseHeader->TotalChunks / 200 : 32;

    Image += SparseHeader->FileHeaderSize;
    for (Chunk = 0; Chunk < SparseHeader->TotalChunks; Chunk++) {
      UINTN WriteSize;
      ChunkHeader = (CHUNK_HEADER *)Image;

      // Show progress. Don't do it for every packet as outputting text
      // might be time consuming. ChunkPrintDensity is calculated to
      // provide an update every half percent change for large
      // downloads.
      if (Chunk % ChunkPrintDensity == 0) {
        UnicodeSPrint(OutputString, sizeof(OutputString),
          L"\r%5d / %5d chunks written (%d%%)", Chunk,
          SparseHeader->TotalChunks,
          (Chunk * 100) / SparseHeader->TotalChunks);
        mTextOut->OutputString(mTextOut, OutputString);
      }

      DEBUG ((DEBUG_INFO, "Chunk #%d - Type: 0x%x Size: %d TotalSize: %d Offset %d\n",
        (Chunk+1), ChunkHeader->ChunkType, ChunkHeader->ChunkSize,
        ChunkHeader->TotalSize, Offset));
      Image += sizeof(CHUNK_HEADER);
      WriteSize = (SparseHeader->BlockSize) * ChunkHeader->ChunkSize;
      switch (ChunkHeader->ChunkType) {
        case CHUNK_TYPE_RAW:
          DEBUG ((DEBUG_INFO, "Writing %d at Offset %d\n", WriteSize, Offset));
          Status = DiskIo->WriteDisk (DiskIo, MediaId, Offset, WriteSize, Image);
          if (EFI_ERROR (Status)) {
            goto Exit;
          }
          Image += WriteSize;
          break;
        case CHUNK_TYPE_DONT_CARE:
          break;
        case CHUNK_TYPE_CRC32:
          break;
        default:
          DEBUG ((DEBUG_ERROR, "Unknown Chunk Type: 0x%x", ChunkHeader->ChunkType));
          Status = EFI_PROTOCOL_ERROR;
          goto Exit;
      }
      Offset += WriteSize;
    }

    UnicodeSPrint (OutputString, sizeof (OutputString),
        L"\r%5d / %5d chunks written (100%%)\r\n",
        SparseHeader->TotalChunks, SparseHeader->TotalChunks);
    mTextOut->OutputString(mTextOut, OutputString);

  } else {

    Status = DiskIo->WriteDisk (DiskIo, MediaId, 0, Size, Image);
    if (EFI_ERROR (Status)) {
      goto Exit;
    }
  }

  BlockIo->FlushBlocks (BlockIo);

Exit:
  return Status;
}