Created
August 10, 2015 06:41
-
-
Save andreyvit/b72a677e6b5111ee9a45 to your computer and use it in GitHub Desktop.
One of the finer pieces of code I have ever written
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#ifndef _RAID_H_ | |
#define _RAID_H_ | |
#define RAID_LEVEL 3 | |
#define RAID_WRITE(stat) do {int raidi; for(raidi = 0; raidi < RAID_LEVEL; ++raidi) stat;} while(0) | |
#define raidwr raid[raidi] | |
#define raidrd raid[0] | |
GlobalState raid[RAID_LEVEL]; | |
static void raid_init() { | |
RAID_WRITE(bzero(&raidwr, sizeof(raidwr))); | |
} | |
static unsigned int raid_hash(unsigned char *data, int size) { | |
int hash = 1; | |
unsigned char *end = data + size; | |
for(; data < end; data++) | |
hash = hash * 31 + *data; | |
return hash; | |
} | |
static int raid_find_bad() { | |
int hash[3]; | |
hash[0] = raid_hash(&raid[0], sizeof(raid[0])); | |
hash[1] = raid_hash(&raid[1], sizeof(raid[0])); | |
hash[2] = raid_hash(&raid[2], sizeof(raid[0])); | |
if (hash[0] == hash[1]) | |
if (hash[1] == hash[2]) | |
return -1; | |
else | |
return 2; | |
else | |
if (hash[0] == hash[2]) | |
return 1; | |
else if (hash[1] == hash[2]) | |
return 0; | |
return -2; | |
} | |
static void raid_check() { | |
int bad = raid_find_bad(); | |
int good = (bad > 0 ? 0 : (bad == 0 ? 1 : -1)); | |
if (bad == -1) | |
return; | |
if (bad == -2) { | |
trprintf(LOG_ERRORS, "All three copies of global state have been corrupted. Stop.\n"); | |
printf("All three copies of global state have been corrupted. Stop.\n"); | |
fflush(stdout); | |
abort(); | |
} | |
memcpy(&raid[bad], &raid[good], sizeof(raid[0])); | |
trprintf(LOG_ERRORS, "WARNING! Successfully survived a memory corruption (of state copy #%d)\n", bad); | |
printf("WARNING! Successfully survived a memory corruption (of state copy #%d)\n", bad); | |
fflush(stdout); | |
} | |
#define raid_verify() raid_verify_(__FILE__, __LINE__) | |
static void raid_verify_(const char *file, int line) { | |
int bad = raid_find_bad(); | |
if (bad == -1) | |
return; | |
if (bad == -2) { | |
trprintf(LOG_ERRORS, "All three copies of global state have been corrupted by %s:%d\n", file, line); | |
printf("All three copies of global state have been corrupted by %s:%d\n", file, line); | |
} else { | |
trprintf(LOG_ERRORS, "Copy of global state #%d has been corrupted by %s:%d\n", bad, file, line); | |
printf("Copy of global state #%d has been corrupted by %s:%d\n", bad, file, line); | |
raid_check(); | |
} | |
fflush(stdout); | |
} | |
#endif |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment