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
/** @file
  Inode related routines
 
  Copyright (c) 2021 Pedro Falcato All rights reserved.
  SPDX-License-Identifier: BSD-2-Clause-Patent
 
  EpochToEfiTime copied from EmbeddedPkg/Library/TimeBaseLib.c
  Copyright (c) 2016, Hisilicon Limited. All rights reserved.
  Copyright (c) 2016-2019, Linaro Limited. All rights reserved.
  Copyright (c) 2021, Ampere Computing LLC. All rights reserved.
**/
 
#include "Ext4Dxe.h"
 
/**
   Calculates the checksum of the given inode.
   @param[in]      Partition     Pointer to the opened EXT4 partition.
   @param[in]      Inode         Pointer to the inode.
   @param[in]      InodeNum      Inode number.
 
   @return The checksum.
**/
UINT32
Ext4CalculateInodeChecksum (
  IN CONST EXT4_PARTITION  *Partition,
  IN CONST EXT4_INODE      *Inode,
  IN EXT4_INO_NR           InodeNum
  )
{
  UINT32      Crc;
  UINT16      Dummy;
  BOOLEAN     HasSecondChecksumField;
  CONST VOID  *RestOfInode;
  UINTN       RestOfInodeLength;
  UINTN       Length;
 
  HasSecondChecksumField = EXT4_INODE_HAS_FIELD (Inode, i_checksum_hi);
 
  Dummy = 0;
 
  Crc = Ext4CalculateChecksum (Partition, &InodeNum, sizeof (InodeNum), Partition->InitialSeed);
  Crc = Ext4CalculateChecksum (Partition, &Inode->i_generation, sizeof (Inode->i_generation), Crc);
 
  Crc = Ext4CalculateChecksum (
          Partition,
          Inode,
          OFFSET_OF (EXT4_INODE, i_osd2.data_linux.l_i_checksum_lo),
          Crc
          );
 
  Crc = Ext4CalculateChecksum (Partition, &Dummy, sizeof (Dummy), Crc);
 
  RestOfInode = &Inode->i_osd2.data_linux.l_i_reserved;
  RestOfInodeLength = Partition->InodeSize - OFFSET_OF (EXT4_INODE, i_osd2.data_linux.l_i_reserved);
 
  if (HasSecondChecksumField) {
    Length = OFFSET_OF (EXT4_INODE, i_checksum_hi) - OFFSET_OF (EXT4_INODE, i_osd2.data_linux.l_i_reserved);
 
    Crc = Ext4CalculateChecksum (Partition, &Inode->i_osd2.data_linux.l_i_reserved, Length, Crc);
    Crc = Ext4CalculateChecksum (Partition, &Dummy, sizeof (Dummy), Crc);
 
    // 4 is the size of the i_extra_size field + the size of i_checksum_hi
    RestOfInodeLength = Partition->InodeSize - EXT4_GOOD_OLD_INODE_SIZE - 4;
    RestOfInode = &Inode->i_ctime_extra;
  }
 
  Crc = Ext4CalculateChecksum (Partition, RestOfInode, RestOfInodeLength, Crc);
 
  return Crc;
}
 
/**
   Reads from an EXT4 inode.
   @param[in]      Partition     Pointer to the opened EXT4 partition.
   @param[in]      File          Pointer to the opened file.
   @param[out]     Buffer        Pointer to the buffer.
   @param[in]      Offset        Offset of the read.
   @param[in out]  Length        Pointer to the length of the buffer, in bytes.
                                 After a succesful read, it's updated to the number of read bytes.
 
   @return Status of the read operation.
**/
EFI_STATUS
Ext4Read (
  IN     EXT4_PARTITION  *Partition,
  IN     EXT4_FILE       *File,
  OUT    VOID            *Buffer,
  IN     UINT64          Offset,
  IN OUT UINTN           *Length
  )
{
  EXT4_INODE   *Inode;
  UINT64       InodeSize;
  UINT64       CurrentSeek;
  UINTN        RemainingRead;
  UINTN        BeenRead;
  UINTN        WasRead;
  EXT4_EXTENT  Extent;
  UINT32       BlockOff;
  EFI_STATUS   Status;
  BOOLEAN      HasBackingExtent;
  UINT32       HoleOff;
  UINTN        HoleLen;
  UINT64       ExtentStartBytes;
  UINT64       ExtentLengthBytes;
  UINT64       ExtentLogicalBytes;
 
  // Our extent offset is the difference between CurrentSeek and ExtentLogicalBytes
  UINT64  ExtentOffset;
  UINTN   ExtentMayRead;
 
  Inode         = File->Inode;
  InodeSize     = EXT4_INODE_SIZE (Inode);
  CurrentSeek   = Offset;
  RemainingRead = *Length;
  BeenRead      = 0;
 
  DEBUG ((DEBUG_FS, "[ext4] Ext4Read(%s, Offset %lu, Length %lu)\n", File->Dentry->Name, Offset, *Length));
 
  if (Offset > InodeSize) {
    return EFI_DEVICE_ERROR;
  }
 
  if (RemainingRead > InodeSize - Offset) {
    RemainingRead = (UINTN)(InodeSize - Offset);
  }
 
  while (RemainingRead != 0) {
    WasRead = 0;
 
    // The algorithm here is to get the extent corresponding to the current block
    // and then read as much as we can from the current extent.
 
    Status = Ext4GetExtent (
               Partition,
               File,
               DivU64x32Remainder (CurrentSeek, Partition->BlockSize, &BlockOff),
               &Extent
               );
 
    if (Status != EFI_SUCCESS && Status != EFI_NO_MAPPING) {
      return Status;
    }
 
    HasBackingExtent = Status != EFI_NO_MAPPING;
 
    if (!HasBackingExtent) {
      HoleOff = BlockOff;
      HoleLen = Partition->BlockSize - HoleOff;
      WasRead = HoleLen > RemainingRead ? RemainingRead : HoleLen;
      // Potential improvement: In the future, we could get the hole's tota
      // size and memset all that
      SetMem (Buffer, WasRead, 0);
    } else {
      ExtentStartBytes = MultU64x32 (
                           LShiftU64 (Extent.ee_start_hi, 32) |
                           Extent.ee_start_lo,
                           Partition->BlockSize
                           );
      ExtentLengthBytes  = Extent.ee_len * Partition->BlockSize;
      ExtentLogicalBytes = (UINT64)Extent.ee_block * Partition->BlockSize;
      ExtentOffset  = CurrentSeek - ExtentLogicalBytes;
      ExtentMayRead = (UINTN)(ExtentLengthBytes - ExtentOffset);
 
      WasRead = ExtentMayRead > RemainingRead ? RemainingRead : ExtentMayRead;
 
      Status = Ext4ReadDiskIo (Partition, Buffer, WasRead, ExtentStartBytes + ExtentOffset);
 
      if (EFI_ERROR (Status)) {
        DEBUG ((
          DEBUG_ERROR,
          "[ext4] Error %x reading [%lu, %lu]\n",
          Status,
          ExtentStartBytes + ExtentOffset,
          ExtentStartBytes + ExtentOffset + WasRead - 1
          ));
        return Status;
      }
    }
 
    RemainingRead -= WasRead;
    Buffer       = (VOID *)((CHAR8 *)Buffer + WasRead);
    BeenRead    += WasRead;
    CurrentSeek += WasRead;
  }
 
  *Length = BeenRead;
 
  return EFI_SUCCESS;
}
 
/**
   Allocates a zeroed inode structure.
   @param[in]      Partition     Pointer to the opened EXT4 partition.
 
   @return Pointer to the allocated structure, from the pool,
           with size Partition->InodeSize.
**/
EXT4_INODE *
Ext4AllocateInode (
  IN EXT4_PARTITION  *Partition
  )
{
  BOOLEAN     NeedsToZeroRest;
  UINT32      InodeSize;
  EXT4_INODE  *Inode;
 
  NeedsToZeroRest = FALSE;
  InodeSize = Partition->InodeSize;
 
  // We allocate a structure of at least sizeof(EXT4_INODE), but in the future, when
  // write support is added and we need to flush inodes to disk, we could have a bit better
  // distinction between the on-disk inode and a separate, nicer to work with inode struct.
  // It's important to note that EXT4_INODE includes fields that may not exist in an actual
  // filesystem (the minimum inode size is 128 byte and at the moment the size of EXT4_INODE
  // is 160 bytes).
 
  if (InodeSize < sizeof (EXT4_INODE)) {
    InodeSize = sizeof (EXT4_INODE);
    NeedsToZeroRest = TRUE;
  }
 
  Inode = AllocateZeroPool (InodeSize);
 
  if (!Inode) {
    return NULL;
  }
 
  if (NeedsToZeroRest) {
    Inode->i_extra_isize = 0;
  }
 
  return Inode;
}
 
/**
   Checks if a file is a directory.
   @param[in]      File          Pointer to the opened file.
 
   @return TRUE if file is a directory.
**/
BOOLEAN
Ext4FileIsDir (
  IN CONST EXT4_FILE  *File
  )
{
  return (File->Inode->i_mode & EXT4_INO_TYPE_DIR) == EXT4_INO_TYPE_DIR;
}
 
/**
   Checks if a file is a regular file.
   @param[in]      File          Pointer to the opened file.
 
   @return BOOLEAN         TRUE if file is a regular file.
**/
BOOLEAN
Ext4FileIsReg (
  IN CONST EXT4_FILE  *File
  )
{
  return (File->Inode->i_mode & EXT4_INO_TYPE_REGFILE) == EXT4_INO_TYPE_REGFILE;
}
 
/**
   Calculates the physical space used by a file.
   @param[in]      File          Pointer to the opened file.
 
   @return Physical space used by a file, in bytes.
**/
UINT64
Ext4FilePhysicalSpace (
  IN EXT4_FILE  *File
  )
{
  BOOLEAN  HugeFile;
  UINT64   Blocks;
 
  HugeFile = EXT4_HAS_RO_COMPAT (File->Partition, EXT4_FEATURE_RO_COMPAT_HUGE_FILE);
  Blocks   = File->Inode->i_blocks;
 
  if (HugeFile) {
    Blocks |= LShiftU64 (File->Inode->i_osd2.data_linux.l_i_blocks_high, 32);
 
    // If HUGE_FILE is enabled and EXT4_HUGE_FILE_FL is set in the inode's flags, each unit
    // in i_blocks corresponds to an actual filesystem block
    if (File->Inode->i_flags & EXT4_HUGE_FILE_FL) {
      return MultU64x32 (Blocks, File->Partition->BlockSize);
    }
  }
 
  // Else, each i_blocks unit corresponds to 512 bytes
  return MultU64x32 (Blocks, 512);
}
 
// Copied from EmbeddedPkg at my mentor's request.
// The lack of comments and good variable names is frightening...
 
/**
  Converts Epoch seconds (elapsed since 1970 JANUARY 01, 00:00:00 UTC) to EFI_TIME.
 
  @param[in]   EpochSeconds   Epoch seconds.
  @param[out]  Time           The time converted to UEFI format.
 
**/
STATIC
VOID
EFIAPI
EpochToEfiTime (
  IN  UINTN     EpochSeconds,
  OUT EFI_TIME  *Time
  )
{
  UINTN  a;
  UINTN  b;
  UINTN  c;
  UINTN  d;
  UINTN  g;
  UINTN  j;
  UINTN  m;
  UINTN  y;
  UINTN  da;
  UINTN  db;
  UINTN  dc;
  UINTN  dg;
  UINTN  hh;
  UINTN  mm;
  UINTN  ss;
  UINTN  J;
 
  J  = (EpochSeconds / 86400) + 2440588;
  j  = J + 32044;
  g  = j / 146097;
  dg = j % 146097;
  c  = (((dg / 36524) + 1) * 3) / 4;
  dc = dg - (c * 36524);
  b  = dc / 1461;
  db = dc % 1461;
  a  = (((db / 365) + 1) * 3) / 4;
  da = db - (a * 365);
  y  = (g * 400) + (c * 100) + (b * 4) + a;
  m  = (((da * 5) + 308) / 153) - 2;
  d  = da - (((m + 4) * 153) / 5) + 122;
 
  Time->Year  = (UINT16)(y - 4800 + ((m + 2) / 12));
  Time->Month = ((m + 2) % 12) + 1;
  Time->Day   = (UINT8)(d + 1);
 
  ss = EpochSeconds % 60;
  a  = (EpochSeconds - ss) / 60;
  mm = a % 60;
  b  = (a - mm) / 60;
  hh = b % 24;
 
  Time->Hour       = (UINT8)hh;
  Time->Minute     = (UINT8)mm;
  Time->Second     = (UINT8)ss;
  Time->Nanosecond = 0;
}
 
// The time format used to (de/en)code timestamp and timestamp_extra is documented on
// the ext4 docs page in kernel.org
#define EXT4_EXTRA_TIMESTAMP_MASK  ((1 << 2) - 1)
 
#define EXT4_FILE_GET_TIME_GENERIC(Name, Field)            \
  VOID \
  Ext4File ## Name (IN EXT4_FILE  *File, OUT EFI_TIME  *Time) \
  {                                                          \
    EXT4_INODE  *Inode = File->Inode;                       \
    UINT64      SecondsEpoch = Inode->Field;                   \
    UINT32      Nanoseconds  = 0;                                \
                                                           \
    if (EXT4_INODE_HAS_FIELD (Inode, Field ## _extra)) {          \
      SecondsEpoch |= LShiftU64 ((UINT64)(Inode->Field ## _extra & EXT4_EXTRA_TIMESTAMP_MASK), 32); \
      Nanoseconds   = Inode->Field ## _extra >> 2;                                            \
    }                                                                                       \
    EpochToEfiTime ((UINTN)SecondsEpoch, Time);                                                     \
    Time->Nanosecond = Nanoseconds;                                                         \
  }
 
// Note: EpochToEfiTime should be adjusted to take in a UINT64 instead of a UINTN, in order to avoid Y2038
// on 32-bit systems.
 
/**
   Gets the file's last access time.
   @param[in]      File   Pointer to the opened file.
   @param[out]     Time   Pointer to an EFI_TIME structure.
**/
EXT4_FILE_GET_TIME_GENERIC (ATime, i_atime);
 
/**
   Gets the file's last (data) modification time.
   @param[in]      File   Pointer to the opened file.
   @param[out]     Time   Pointer to an EFI_TIME structure.
**/
EXT4_FILE_GET_TIME_GENERIC (MTime, i_mtime);
 
/**
   Gets the file's creation time.
   @param[in]      File   Pointer to the opened file.
   @param[out]     Time   Pointer to an EFI_TIME structure.
**/
STATIC
EXT4_FILE_GET_TIME_GENERIC (
  CrTime, i_crtime
  );
 
/**
   Gets the file's creation time, if possible.
   @param[in]      File   Pointer to the opened file.
   @param[out]     Time   Pointer to an EFI_TIME structure.
                          In the case where the the creation time isn't recorded,
                          Time is zeroed.
**/
VOID
Ext4FileCreateTime (
  IN EXT4_FILE  *File,
  OUT EFI_TIME  *Time
  )
{
  EXT4_INODE  *Inode;
 
  Inode = File->Inode;
 
  if (!EXT4_INODE_HAS_FIELD (Inode, i_crtime)) {
    SetMem (Time, sizeof (EFI_TIME), 0);
    return;
  }
 
  Ext4FileCrTime (File, Time);
}
 
/**
   Checks if the checksum of the inode is correct.
   @param[in]      Partition     Pointer to the opened EXT4 partition.
   @param[in]      Inode         Pointer to the inode.
   @param[in]      InodeNum      Inode number.
 
   @return TRUE if checksum is correct, FALSE if there is corruption.
**/
BOOLEAN
Ext4CheckInodeChecksum (
  IN CONST EXT4_PARTITION  *Partition,
  IN CONST EXT4_INODE      *Inode,
  IN EXT4_INO_NR           InodeNum
  )
{
  UINT32  Csum;
  UINT32  DiskCsum;
 
  if (!EXT4_HAS_METADATA_CSUM (Partition)) {
    return TRUE;
  }
 
  Csum = Ext4CalculateInodeChecksum (Partition, Inode, InodeNum);
 
  DiskCsum = Inode->i_osd2.data_linux.l_i_checksum_lo;
 
  if (EXT4_INODE_HAS_FIELD (Inode, i_checksum_hi)) {
    DiskCsum |= ((UINT32)Inode->i_checksum_hi) << 16;
  } else {
    // Only keep the lower bits for the comparison if the checksum is 16 bits.
    Csum &= 0xffff;
  }
 
  return Csum == DiskCsum;
}