-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcsum.c
80 lines (65 loc) · 2.04 KB
/
csum.c
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
#include "csum.h"
#include "super.h"
#include "block.h"
#include <assert.h>
// TODO: add your code here
/* returns 0 on error */
int
testfs_get_csum(struct super_block *sb, int block_nr)
{
assert(sb);
assert(sb->csum_table);
if ( block_nr < MAX_NR_CSUMS ) {
return sb->csum_table[block_nr];
}
return 0;
}
static void
testfs_write_csum(struct super_block *sb, int block_nr)
{
int nr = block_nr * sizeof(int) / BLOCK_SIZE;
char * table = (char *)sb->csum_table;
assert(table);
write_blocks(sb, table + (nr * BLOCK_SIZE),
sb->sb.csum_table_start + nr, 1);
}
void
testfs_put_csum(struct super_block *sb, int phy_block_nr, int csum)
{
int block_nr = phy_block_nr - sb->sb.data_blocks_start;
assert(sb);
assert(sb->csum_table);
assert(block_nr >= 0 && block_nr < MAX_NR_CSUMS);
sb->csum_table[block_nr] = csum;
testfs_write_csum(sb, block_nr);
}
/* could use other algorithm if you want */
int
testfs_calculate_csum(const char * buf, const int size)
{
const int * ibuf = (const int *)buf;
const int count = size/sizeof(int);
int csum = 0;
int i;
assert(size % sizeof(int) == 0);
for ( i = 0; i < count; i++ )
{
csum ^= ibuf[i];
}
return csum;
}
int
testfs_verify_csum(struct super_block *sb, int phy_block_nr)
{
char block[BLOCK_SIZE];
int csum;
int block_nr = phy_block_nr - sb->sb.data_blocks_start;
assert(block_nr >= 0 && block_nr < MAX_NR_CSUMS);
read_blocks(sb, block, phy_block_nr, 1);
csum = testfs_calculate_csum(block, sizeof(block));
if (csum != sb->csum_table[block_nr]) {
printf("checksum error at block %d\n", phy_block_nr);
return -EINVAL;
}
return 0;
}