1 /* Copyright 2014 The ChromiumOS Authors
2 * Use of this source code is governed by a BSD-style license that can be
3 * found in the LICENSE file.
4 *
5 * Stub implementations of stream APIs.
6 */
7
8 #include <stdint.h>
9
10 #include "2common.h"
11 #include "vboot_api.h"
12
13 /* The stub implementation assumes 512-byte disk sectors */
14 #define LBA_BYTES 512
15
16 /* Internal struct to simulate a stream for sector-based disks */
17 struct disk_stream {
18 /* Disk handle */
19 vb2ex_disk_handle_t handle;
20
21 /* Next sector to read */
22 uint64_t sector;
23
24 /* Number of sectors left in partition */
25 uint64_t sectors_left;
26 };
27
28 __attribute__((weak))
VbExStreamOpen(vb2ex_disk_handle_t handle,uint64_t lba_start,uint64_t lba_count,VbExStream_t * stream)29 vb2_error_t VbExStreamOpen(vb2ex_disk_handle_t handle, uint64_t lba_start,
30 uint64_t lba_count, VbExStream_t *stream)
31 {
32 struct disk_stream *s;
33
34 if (!handle) {
35 *stream = NULL;
36 return VB2_ERROR_UNKNOWN;
37 }
38
39 s = malloc(sizeof(*s));
40 if (!s)
41 return VB2_ERROR_UNKNOWN;
42 s->handle = handle;
43 s->sector = lba_start;
44 s->sectors_left = lba_count;
45
46 *stream = (void *)s;
47
48 return VB2_SUCCESS;
49 }
50
51 __attribute__((weak))
VbExStreamRead(VbExStream_t stream,uint32_t bytes,void * buffer)52 vb2_error_t VbExStreamRead(VbExStream_t stream, uint32_t bytes, void *buffer)
53 {
54 struct disk_stream *s = (struct disk_stream *)stream;
55 uint64_t sectors;
56 vb2_error_t rv;
57
58 if (!s)
59 return VB2_ERROR_UNKNOWN;
60
61 /* For now, require reads to be a multiple of the LBA size */
62 if (bytes % LBA_BYTES)
63 return VB2_ERROR_UNKNOWN;
64
65 /* Fail on overflow */
66 sectors = bytes / LBA_BYTES;
67 if (sectors > s->sectors_left)
68 return VB2_ERROR_UNKNOWN;
69
70 rv = VbExDiskRead(s->handle, s->sector, sectors, buffer);
71 if (rv != VB2_SUCCESS)
72 return rv;
73
74 s->sector += sectors;
75 s->sectors_left -= sectors;
76
77 return VB2_SUCCESS;
78 }
79
80 __attribute__((weak))
VbExStreamClose(VbExStream_t stream)81 void VbExStreamClose(VbExStream_t stream)
82 {
83 struct disk_stream *s = (struct disk_stream *)stream;
84
85 /* Allow freeing a null pointer */
86 if (!s)
87 return;
88
89 free(s);
90 return;
91 }
92