15a37f438f26feb8ad5a047ef5f81a972624fb87
[pintos-anon] / grading / vm / mmap-shuffle.c
1 #include <stdio.h>
2 #include <string.h>
3 #ifdef PINTOS
4 #include <syscall.h>
5 #else
6 #include "posix-compat.h"
7 #endif
8 #include "../lib/arc4.h"
9 #include "../lib/cksum.h"
10
11 /* This is the max file size for an older version of the Pintos
12    file system that had 126 direct blocks each pointing to a
13    single disk sector.  We could raise it now. */
14 #define SIZE (126 * 512)
15
16 static char *buf = (char *) 0x10000000;
17
18 static struct arc4 *
19 get_key (void) 
20 {
21   static struct arc4 arc4;
22   static bool inited = false;
23   if (!inited) 
24     {
25       arc4_init (&arc4, "quux", 4);
26       inited = true; 
27     }
28   return &arc4;
29 }
30
31 static unsigned long
32 random_ulong (void) 
33 {
34   static unsigned long x;
35   arc4_crypt (get_key (), &x, sizeof x);
36   return x;
37 }
38
39 static void
40 shuffle (void) 
41 {
42   size_t i;
43
44   for (i = 0; i < SIZE; i++)
45     {
46       size_t j = i + random_ulong () % (SIZE - i);
47       char t = buf[i];
48       buf[i] = buf[j];
49       buf[j] = t;
50     }
51 }
52
53 int
54 main (void) 
55 {
56   size_t i;
57   int fd;
58
59   printf ("(mmap-shuffle) begin\n");
60
61   /* Create file, mmap. */
62   if (!create ("buffer", SIZE))
63     {
64       printf ("(mmap-shuffle) create() failed\n");
65       return 1;
66     }
67   
68   fd = open ("buffer");
69   if (fd < 0) 
70     {
71       printf ("(mmap-shuffle) open() failed\n");
72       return 1;
73     }
74
75   if (mmap (fd, buf) == MAP_FAILED)
76     {
77       printf ("(mmap-shuffle) mmap() failed\n");
78       return 1;
79     }
80
81   /* Initialize. */
82   for (i = 0; i < SIZE; i++)
83     buf[i] = i * 257;
84   printf ("(mmap-shuffle) init: cksum=%lu\n", cksum (buf, SIZE));
85     
86   /* Shuffle repeatedly. */
87   for (i = 0; i < 10; i++)
88     {
89       shuffle ();
90       printf ("(mmap-shuffle) shuffle %zu: cksum=%lu\n",
91               i, cksum (buf, SIZE));
92     }
93   
94   /* Done. */
95   printf ("(mmap-shuffle) end\n");
96
97   return 0;
98 }