]> git.saurik.com Git - redis.git/blob - src/memtest.c
Hem... actual memtest.c file added.
[redis.git] / src / memtest.c
1 #include <stdlib.h>
2 #include <stdio.h>
3 #include <string.h>
4 #include <assert.h>
5 #include <limits.h>
6 #include <errno.h>
7
8 #if (ULONG_MAX == 4294967295UL)
9 #define MEMTEST_32BIT
10 #elif (ULONG_MAX == 18446744073709551615ULL)
11 #define MEMTEST_64BIT
12 #else
13 #error "ULONG_MAX value not supported."
14 #endif
15
16 /* Fill words stepping a single page at every write, so we continue to
17 * touch all the pages in the smallest amount of time reducing the
18 * effectiveness of caches, and making it hard for the OS to transfer
19 * pages on the swap. */
20 void memtest_fill(unsigned long *l, size_t bytes) {
21 unsigned long step = 4096/sizeof(unsigned long);
22 unsigned long words = bytes/sizeof(unsigned long)/2;
23 unsigned long iwords = words/step; /* words per iteration */
24 unsigned long off, w, *l1, *l2;
25
26 assert((bytes & 4095) == 0);
27 for (off = 0; off < step; off++) {
28 l1 = l+off;
29 l2 = l1+words;
30 for (w = 0; w < iwords; w++) {
31 #ifdef MEMTEST_32BIT
32 *l1 = *l2 = ((unsigned long) (rand()&0xffff)) |
33 (((unsigned long) (rand()&0xffff)) << 16);
34 #else
35 *l1 = *l2 = ((unsigned long) (rand()&0xffff)) |
36 (((unsigned long) (rand()&0xffff)) << 16) |
37 (((unsigned long) (rand()&0xffff)) << 32) |
38 (((unsigned long) (rand()&0xffff)) << 48);
39 #endif
40 l1 += step;
41 l2 += step;
42 }
43 }
44 }
45
46 void memtest_compare(unsigned long *l, size_t bytes) {
47 unsigned long words = bytes/sizeof(unsigned long)/2;
48 unsigned long w, *l1, *l2;
49
50 assert((bytes & 4095) == 0);
51 l1 = l;
52 l2 = l1+words;
53 for (w = 0; w < words; w++) {
54 if (*l1 != *l2) {
55 printf("\n*** MEMORY ERROR DETECTED: %p != %p (%lu vs %lu)\n",
56 (void*)l1, (void*)l2, *l1, *l2);
57 exit(1);
58 }
59 l1 ++;
60 l2 ++;
61 }
62 }
63
64 void memtest_test(size_t megabytes, int passes) {
65 size_t bytes = megabytes*1024*1024;
66 unsigned long *m = malloc(bytes);
67 int pass = 0;
68
69 if (m == NULL) {
70 fprintf(stderr,"Unable to allocate %zu megabytes: %s",
71 megabytes, strerror(errno));
72 exit(1);
73 }
74 while (pass != passes) {
75 pass++;
76 printf("PASS %d... ", pass);
77 fflush(stdout);
78 memtest_fill(m,bytes);
79 memtest_compare(m,bytes);
80 printf("ok\n");
81 }
82 }
83
84 void memtest(size_t megabytes, int passes) {
85 memtest_test(megabytes,passes);
86 printf("\nYour memory passed this test.\n");
87 printf("Please if you are stil in doubt use the following two tools:\n");
88 printf("1) memtest86: http://www.memtest86.com/\n");
89 printf("2) memtester: http://pyropus.ca/software/memtester/\n");
90 exit(0);
91 }