-
Notifications
You must be signed in to change notification settings - Fork 3
/
flash.c
95 lines (77 loc) · 2.7 KB
/
flash.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
/*
Utility functions for programming JEDEC parallel flash memories
Copyright (C) 2023-2024 Richard Halkyard
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation, either version 3 of the License, or (at your option) any later
version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with
this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include "flash.h"
#include <stddef.h>
enum {
cmd_chiperase = 0x10,
cmd_byteerase = 0x30,
cmd_erase = 0x80,
cmd_id = 0x90,
cmd_bytewrite = 0xa0,
cmd_idexit = 0xf0
};
/* Send JEDEC '3-byte write' command to device at base_address */
static void flash_3byte(volatile unsigned char* base_address,
unsigned char command) {
*(base_address + 0x5555) = 0xaa;
*(base_address + 0x2aaa) = 0x55;
*(base_address + 0x5555) = command;
}
int flash_probe(volatile unsigned char* base_address, flash_id* id) {
unsigned char origdata_0 = *base_address;
unsigned char origdata_1 = *(base_address + 1);
unsigned char manufacturer, device;
flash_3byte(base_address, cmd_id);
manufacturer = *base_address;
device = *(base_address + 1);
flash_3byte(base_address, cmd_idexit);
if (manufacturer == origdata_0 && device == origdata_1) {
return -1;
}
if (id != NULL) {
id->manufacturer = manufacturer;
id->device = device;
}
return 0;
}
void flash_erase(volatile unsigned char* base_address) {
flash_3byte(base_address, cmd_erase);
flash_3byte(base_address, cmd_chiperase);
while (*base_address != 0xff) {
};
}
static void flash_writebyte(volatile unsigned char* base_address,
unsigned int offset, unsigned char data) {
flash_3byte(base_address, cmd_bytewrite);
*(base_address + offset) = data;
while (*(base_address + offset) != data) {
};
}
int flash_write(volatile unsigned char* base_address, unsigned int offset,
unsigned char* data, unsigned int len) {
for (unsigned int i = 0; i < len; i++) {
flash_writebyte(base_address, offset + i, data[i]);
}
for (unsigned int i = 0; i < len; i++) {
if (*(base_address + offset + i) != data[i]) {
return -1;
}
}
return 0;
}
int flash_program(volatile unsigned char* base_address, unsigned int offset,
unsigned char* data, unsigned int len) {
flash_erase(base_address);
return flash_write(base_address, offset, data, len);
}