summaryrefslogtreecommitdiff
path: root/flash.c
blob: 31133881c196769b2487dfe1e9ea27e2a884afff (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
#include "globals.h"
#include <stdint.h>
#include <stdio.h>
#include <stdbool.h>
#include <fcntl.h>
#include <stdlib.h>
#include <inttypes.h>
#include <unistd.h>
#include <errno.h>
#include <sys/sendfile.h>
#include <sys/stat.h>
#include <mhash.h>

#define MAINFILE "/root/flash.copy"
#define BACKUPFILE "/root/flash.bup"

#define PERSIST_ERR_COULDNTREADHDR 1
#define PERSIST_ERR_HDRLENMISMATCH 2
#define PERSIST_ERR_VERSIONMISMATCH 3
#define PERSIST_ERR_COULDNTREADDATA 4
#define PERSIST_ERR_BADCRC32 5
#define PERSIST_ERR_BADARGS 6
#define PERSIST_ERR_COULDNTALLOCATEBUFFER 7
#define PERSIST_ERR_COULDNTSEEK 8
#define PERSIST_ERR_COULDNTWRITE 9
#define PERSIST_ERR_COUNDNTOPENFILE 10

// crc32 routine

static uint32_t crc32(uint8_t* buf, int count) {
	MHASH context = mhash_init(MHASH_CRC32B);
	mhash(context, buf, count);
	uint32_t hash;
	mhash_deinit(context, &hash);
	return hash;
}

// header to prepend to stashed objects
typedef struct {
	uint32_t version;
	uint32_t length;
	uint32_t crc32;
} persistancehdr;

static void persistance_printheader(persistancehdr* hdr) {
printf("Frozen struct has version %d, is %d bytes long and has the CRC32 0x%08"PRIx32"\n", hdr->version,
		hdr->length, hdr->crc32);
}

// copy a file from one place to another.. this is not portable, linux only
bool persistance_copyfile(char* source, char* dest) {
	mode_t filemode = S_IRUSR | S_IWUSR;
	int src = open(source, O_RDONLY);
	int dst = open(dest, O_SYNC | O_RDWR | O_CREAT, filemode);

	if (src < 0 || dst < 0)
		return false;

	struct stat s;
	fstat(src, &s);

	ftruncate(dst, 0);
	sendfile(dst, src, NULL, s.st_size);
	close(src);
	close(dst);
	return true;
}

// store an object
bool persistance_freeze(char* dest, void* data, unsigned int offset, unsigned int len, unsigned int total,
		uint32_t version) {

	// don't write past the end of the file..
	if (offset + len > total) {
		errno = PERSIST_ERR_BADARGS;
		return false;
	}

	bool newfile = false;
	uint32_t crc;

	// open the target file with O_SYNC so that write blocks until it's on disk
	// fingers crossed the FS actually does what it's told..
	int fd = open(dest, O_SYNC | O_RDWR);
	if (fd < 0) {
		// this is to catch if the file didn't exist and if it needed to be created
		mode_t filemode = S_IRUSR | S_IWUSR;
		fd = open(dest, O_SYNC | O_RDWR | O_CREAT, filemode);
		if (fd < 0) {
			errno = PERSIST_ERR_COUNDNTOPENFILE;
			return false;
		}
		newfile = true;
	}

	// if this is a new file or we're overwriting everything we can just calculate the CRC from the data passed in
	if (newfile || len == total) {
		// if this a new file we want to write everything irrespective of the offset and len passed in
		if (newfile) {
			offset = 0;
			len = total;
		}
		crc = crc32((uint8_t*) data, total);
	}

	// this is a modification within an existing file so we need to merge the existing data with the
	// new data to calculate the new crc for the file because it seems the struct getting passed in
	// only contains the changed data.
	else if (len != total) {
		// create a buffer for the existing data
		void* payload = malloc(total);
		if (payload == NULL) {
			errno = PERSIST_ERR_COULDNTALLOCATEBUFFER;
			return false;
		}

		// get the header
		persistancehdr hdr;
		if (read(fd, &hdr, sizeof(persistancehdr)) != sizeof(persistancehdr)) {
			errno = PERSIST_ERR_COULDNTREADHDR;
			return false;
		}

		// load the data
		persistance_printheader(&hdr);
		if (read(fd, payload, total) != total) {
			errno = PERSIST_ERR_COULDNTREADDATA;
			return false;
		}

		// check the existing data isn't already corrupt.
		uint32_t calculatedcrc32 = crc32((uint8_t*) payload, hdr.length);
		if (calculatedcrc32 != hdr.crc32) {
			errno = PERSIST_ERR_BADCRC32;
			return false;
		}
		// overlay the payload with the existing data
		memcpy(((char*) payload) + offset, ((char*) data) + offset, len);
		crc = crc32((uint8_t*) payload, total);
		free(payload);
		lseek(fd, 0, SEEK_SET); // rewind
	}

	// build the header
	persistancehdr hdr;
	hdr.version = version;
	hdr.length = total;
	hdr.crc32 = crc;

	persistance_printheader(&hdr);

	// write the data to disk
	ftruncate(fd, sizeof(hdr) + total); // not really needed but if we did have a file thats bigger than it
										// should be put a stop to that

	// write the header
	if (write(fd, &hdr, sizeof(hdr)) != sizeof(hdr)) {
		errno = PERSIST_ERR_COULDNTWRITE;
		return false;
	}

	// seek to the offset.. which could mean not seeking at all
	if (lseek(fd, offset, SEEK_CUR) < 0) {
		errno = PERSIST_ERR_COULDNTSEEK; // shouldn't ever happen really because if we're actually
										 // seeking the file should already be the total size.
		return false;
	}

	// write the data out to disk
	if (write(fd, ((char*) data) + offset, len) != len) {
		errno = PERSIST_ERR_COULDNTWRITE;
		return false;
	}

	// pack up and go home
	close(fd);

	return true;

}

// try to load an object from disk
bool persistance_unfreeze(char* dest, void* result, unsigned int len, uint32_t version) {

	int fd = open(dest, O_RDONLY);

	// get the header
	persistancehdr hdr;
	if (read(fd, &hdr, sizeof(persistancehdr)) != sizeof(persistancehdr)) {
		errno = PERSIST_ERR_COULDNTREADHDR;
		return false;
	}

	persistance_printheader(&hdr);

	// check that the length of this frozen object is what we are expecting
	if (hdr.length != len) {
		errno = PERSIST_ERR_HDRLENMISMATCH;
		return false;
	}

	// check that it's the same version.. the version isn't used at the moment
	// but if you want to change the header at some point it'll be useful
	if (hdr.version != version) {
		errno = PERSIST_ERR_VERSIONMISMATCH;
		return false;
	}

	// read in the data for the object.. if we couldn't read the amount of data
	// that the header said there was the header is either wrong or the file is truncated.
	if (read(fd, result, hdr.length) != hdr.length) {
		errno = PERSIST_ERR_COULDNTREADDATA;
		return false;
	}

	// check it's crc32 to make sure it's not corrupt
	uint32_t calculatedcrc32 = crc32(result, hdr.length);
	if (calculatedcrc32 != hdr.crc32) {
		printf("Calculated CRC is 0x%08"PRIx32"\n", calculatedcrc32);
		errno = PERSIST_ERR_BADCRC32;
		return false;
	}

	return true;

}

int readUserBlock(FlashStruct *mem) {

	// try to unfreeze the main file
	if (persistance_unfreeze(MAINFILE, mem, sizeof(*mem), 0))
		return sizeof(*mem);
	// something went wrong
	else {
		printf("Error unfreezing %d.. trying backup\n", errno);
		// hopefully we can use the backup..
		if (persistance_unfreeze(BACKUPFILE, mem, sizeof(*mem), 0)) {
			// if the backup was good overwrite the main file
			persistance_copyfile(BACKUPFILE, MAINFILE);
			return sizeof(*mem);
		}
		// deadend :(
		else {
			printf("Error unfreezing backup %d.\n", errno);
		}
	}
	return 0;
}

void writeUserBlock(FlashStruct *mem, int addr, int numbytes) {

	// *** There is a potential issue here.. if the mainfile is corrupt ***
	// *** and this gets called before readUserBlock then the 			***
	// *** potentially workable backup will be lost .. we could check   ***
	// *** that the main file is valid before backing it up I guess...  ***
	// *** but I don't think this situation should arise.				***

	// backup the main copy of the file
	if (persistance_copyfile(MAINFILE, BACKUPFILE)) {
		if (!persistance_freeze(MAINFILE, mem, addr, numbytes, sizeof(*mem), 0)) {
			if (errno != PERSIST_ERR_COULDNTWRITE)
				printf("Error while trying to write, %d. **Write did not happen!!!**\n", errno);
			else
				printf("Error while writing data to disk. **File is potentially corrupt!**\n");
		}
	}
	else {
		printf("Could not backup current file. **Write did not happen!!!**\n");
	}
}

void initFlash(FlashStruct *mem) {
	if (readUserBlock(mem) > 0)
		return;

// uninitialized device!
	mem->flash_start = (char) 99;
	strcpy(mem->aux_error_message, "FIXME");
	mem->channels = (short) 1;
	mem->enable_avrq_extra_ampls = (char) 12;
	mem->ChanKey_frequency = (char) 0;
// much more needs to be added here - later

// save the default Flash config, for nonvolatile persistence
	writeUserBlock(mem, 0, sizeof(*mem));
}