1eccc03849ee0ccc24aa7ad11afa477d59ea91d2
[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 #define SIZE (63 * 1024)        /* Max file size. */
12 static char *buf = (char *) 0x10000000;
13
14 static struct arc4 *
15 get_key (void) 
16 {
17   static struct arc4 arc4;
18   static bool inited = false;
19   if (!inited) 
20     {
21       arc4_init (&arc4, "quux", 4);
22       inited = true; 
23     }
24   return &arc4;
25 }
26
27 static unsigned long
28 random_ulong (void) 
29 {
30   static unsigned long x;
31   arc4_crypt (get_key (), &x, sizeof x);
32   return x;
33 }
34
35 static void
36 shuffle (void) 
37 {
38   size_t i;
39
40   for (i = 0; i < SIZE; i++)
41     {
42       size_t j = i + random_ulong () % (SIZE - i);
43       char t = buf[i];
44       buf[i] = buf[j];
45       buf[j] = t;
46     }
47 }
48
49 int
50 main (void) 
51 {
52   size_t i;
53   int fd;
54
55   printf ("(mmap-shuffle) begin\n");
56
57   /* Create file, mmap. */
58   if (!create ("buffer", SIZE))
59     {
60       printf ("(mmap-shuffle) create() failed\n");
61       return 1;
62     }
63   
64   fd = open ("buffer");
65   if (fd < 0) 
66     {
67       printf ("(mmap-shuffle) open() failed\n");
68       return 1;
69     }
70
71   if (!mmap (fd, buf, SIZE))
72     {
73       printf ("(mmap-shuffle) mmap() failed\n");
74       return 1;
75     }
76
77   /* Initialize. */
78   for (i = 0; i < SIZE; i++)
79     buf[i] = i * 257;
80   printf ("(mmap-shuffle) init: cksum=%lu\n", cksum (buf, SIZE));
81     
82   /* Shuffle repeatedly. */
83   for (i = 0; i < 10; i++)
84     {
85       shuffle ();
86       printf ("(mmap-shuffle) shuffle %zu: cksum=%lu\n",
87               i, cksum (buf, SIZE));
88     }
89   
90   /* Done. */
91   printf ("(mmap-shuffle) end\n");
92
93   return 0;
94 }