Kaynağa Gözat

Update master from bsys-ws17-template/hw3

Manuel Vögele 8 yıl önce
ebeveyn
işleme
a576ac8ada

+ 22
- 0
files/hw3.txt Dosyayı Görüntüle

@@ -0,0 +1,22 @@
1
+./hw3/README.md
2
+
3
+./hw3/simu1/QUESTIONS.md
4
+./hw3/simu1/README-relocation.md
5
+./hw3/simu1/relocation.py
6
+./hw3/simu1/ANSWERS.md
7
+
8
+./hw3/simu2/QUESTIONS.md
9
+./hw3/simu2/README-segmentation.md
10
+./hw3/simu2/segmentation.py
11
+./hw3/simu2/ANSWERS.md
12
+
13
+./hw3/simu3/QUESTIONS.md
14
+./hw3/simu3/README-malloc.md
15
+./hw3/simu3/malloc.py
16
+./hw3/simu3/ANSWERS.md
17
+
18
+./hw3/simu4/QUESTIONS.md
19
+./hw3/simu4/README-paging-linear-translate.md
20
+./hw3/simu4/paging-linear-translate.py
21
+./hw3/simu4/ANSWERS.md
22
+

+ 51
- 0
hw3/README.md Dosyayı Görüntüle

@@ -0,0 +1,51 @@
1
+# hw3
2
+
3
+## Tasks
4
+
5
+To fulfill **hw3** you have to solve:
6
+
7
+- simu1
8
+- simu2
9
+- simu3
10
+- simu4
11
+
12
+## ASIDE: SIMULATION HOMEWORKS
13
+
14
+Simulation homeworks (`simuN/`) come in the form of simulators you run to make
15
+sure you understand some piece of the material. The simulators are generally
16
+python programs that enable you both to generate different problems (using
17
+different random seeds) as well as to have the program solve the problem for you
18
+(with the `-c` flag) so that you can check your answers. Running any simulator
19
+with a `-h` or `--help`flag will provide with more information as to all the
20
+options the simulator gives you.
21
+
22
+The README provided with each simulator gives more detail as to how to run it.
23
+Each flag is described in some detail therein.
24
+
25
+You find all Files for your simulation homework in the `simuN/` directory.
26
+
27
+**IMPORTANT**: This time, there is no possibility to give more
28
+explanations/comments  AFTER the Code Review. You have to give all the asked
29
+explanations and comments (in German or English) before the code review.
30
+
31
+The code review starts after the deadline, so you have enough time to extend
32
+your answers, if your Pull-Request was quite early. After the deadline there
33
+will be no review process (as you already now). This time the review helps you
34
+to only correct your answers in cases, where you solved a problem in a wrong
35
+way.
36
+
37
+## Pull-Request
38
+
39
+Please merge any accepted reviews into your branch. If you are ready with the
40
+homework, all tests run, please create a pull request named **hw3**.
41
+
42
+## Credits for hw3
43
+
44
+| Task     | max. Credits | Comment |
45
+| -------- | ------------ | ------- |
46
+| simu1    | 1            |         |
47
+| simu2    | 1            |         |
48
+| simu3    | 1            |         |
49
+| simu4    | 1            |         |
50
+| Deadline | +1           |         |
51
+| =        | 5            |         |

+ 53
- 0
hw3/simu1/QUESTIONS.md Dosyayı Görüntüle

@@ -0,0 +1,53 @@
1
+# Questions 15-Relocation
2
+
3
+The program `relocation.py` allows you to see how address translations are
4
+performed in a system with base and bounds registers. See the `README` for
5
+details.
6
+
7
+## Warmup
8
+
9
+Run with seeds 1, 2, and 3, and compute whether each virtual address generated
10
+by the process is in or out of bounds. If in bounds, compute the translation.
11
+
12
+Please answer the questions, by giving the result and - if asked - an
13
+explanation, why you got the result. Write your answers in markdown syntax in
14
+the new file `ANSWERS.md.`
15
+
16
+## Questions
17
+
18
+1. Run with these flags: `-s 0 -n 10`. What value do you have set `-l` (the
19
+   bounds register) to in order to ensure that all the generated virtual
20
+   addresses are within bounds?
21
+
22
+1. Run with these flags: `-s 1 -n 10 -l 100`. What is the maximum value that
23
+   base can be set to, such that the address space still fits into physical
24
+   memory in its entirety (explanation)?
25
+
26
+1. Run some of the same problems above, but with larger address spaces (-a) and
27
+   physical memories (-p). How does increasing effect the results (explanation)?
28
+
29
+1. For each virtual address, either write down the physical address it
30
+   translates to OR write down that it is an out-of-bounds address (a
31
+   segmentation violation). For this problem, you should assume a simple virtual
32
+   address space of a given size.
33
+
34
+   ```text
35
+   ARG phys mem size 16k
36
+
37
+   Base-and-Bounds register information:
38
+
39
+     Base   : 0x00003952 (decimal 14674)
40
+     Limit  : 1024
41
+
42
+   Virtual Address Trace
43
+     VA  0: 0x0000024c (decimal:  588) --> PA or segmentation violation?
44
+     VA  1: 0x000004eb (decimal: 1259) --> PA or segmentation violation?
45
+     VA  2: 0x000002bd (decimal:  701) --> PA or segmentation violation?
46
+     VA  3: 0x000000fa (decimal:  250) --> PA or segmentation violation?
47
+     VA  4: 0x00000486 (decimal: 1158) --> PA or segmentation violation?
48
+     VA  5: 0x00000521 (decimal: 1313) --> PA or segmentation violation?
49
+     VA  6: 0x0000065c (decimal: 1628) --> PA or segmentation violation?
50
+     VA  7: 0x000001a3 (decimal:  419) --> PA or segmentation violation?
51
+     VA  8: 0x0000063a (decimal: 1594) --> PA or segmentation violation?
52
+     VA  9: 0x0000034d (decimal:  845) --> PA or segmentation violation?
53
+    ```

+ 99
- 0
hw3/simu1/README-relocation.md Dosyayı Görüntüle

@@ -0,0 +1,99 @@
1
+# README Relocation
2
+
3
+This program allows you to see how address translations are performed in a
4
+system with base and bounds registers. As before, there are two steps to running
5
+the program to test out your understanding of base and bounds. First, run
6
+without the -c flag to generate a set of translations and see if you can
7
+correctly perform the address translations yourself. Then, when done, run with
8
+the -c flag to check your answers.
9
+
10
+In this homework, we will assume a slightly different address space than our
11
+canonical one with a heap and stack at opposite ends of the space. Rather, we
12
+will assume that the address space has a code section, then a fixed-sized
13
+(small) stack, and a heap that grows downward right after, looking something
14
+like you see in the Figure below. In this configuration, there is only one
15
+direction of growth, towards higher regions of the address space.
16
+
17
+```text
18
+  -------------- 0KB
19
+  |    Code    |
20
+  -------------- 2KB
21
+  |   Stack    |
22
+  -------------- 4KB
23
+  |    Heap    |
24
+  |     |      |
25
+  |     v      |
26
+  -------------- 7KB
27
+  |   (free)   |
28
+  |     ...    |
29
+```
30
+
31
+In the figure, the bounds register would be set to 7~KB, as that represents the
32
+end of the address space. References to any address within the bounds would be
33
+considered legal; references above this value are out of bounds and thus the
34
+hardware would raise an exception.
35
+
36
+To run with the default flags, type **relocation.py** at the command line. The
37
+result should be something like this:
38
+
39
+```text
40
+prompt> ./relocation.py
41
+...
42
+Base-and-Bounds register information:
43
+
44
+  Base   : 0x00003082 (decimal 12418)
45
+  Limit  : 472
46
+
47
+Virtual Address Trace
48
+  VA  0: 0x01ae (decimal:430) -> PA or violation?
49
+  VA  1: 0x0109 (decimal:265) -> PA or violation?
50
+  VA  2: 0x020b (decimal:523) -> PA or violation?
51
+  VA  3: 0x019e (decimal:414) -> PA or violation?
52
+  VA  4: 0x0322 (decimal:802) -> PA or violation?
53
+
54
+For each virtual address, either write down the physical address it
55
+translates to OR write down that it is an out-of-bounds address
56
+(a segmentation violation). For this problem, you should assume a
57
+simple virtual address space of a given size.
58
+```
59
+
60
+As you can see, the homework simply generates randomized virtual
61
+addresses. For each, you should determine whether it is in bounds, and if so,
62
+determine to which physical address it translates. Running with -c (the
63
+"compute this for me" flag) gives us the results of these translations, i.e.,
64
+whether they are valid or not, and if valid, the resulting physical
65
+addresses. For convenience, all numbers are given both in hex and decimal.
66
+
67
+```text
68
+prompt> ./relocation.py -c
69
+...
70
+Virtual Address Trace VA  0: 0x01ae (decimal:430) -> VALID: 0x00003230
71
+  (dec:12848) VA  1: 0x0109 (decimal:265) -> VALID: 0x0000318b (dec:12683) VA
72
+  2: 0x020b (decimal:523) -> SEGMENTATION VIOLATION VA  3: 0x019e (decimal:414)
73
+  -> VALID: 0x00003220 (dec:12832) VA  4: 0x0322 (decimal:802) -> SEGMENTATION
74
+  VIOLATION
75
+```
76
+
77
+With a base address of 12418 (decimal), address 430 is within bounds (i.e., it
78
+is less than the limit register of 472) and thus translates to 430 added to
79
+12418 or 12848. A few of the addresses shown above are out of bounds (523,
80
+802), as they are in excess of the bounds. Pretty simple, no? Indeed, that is
81
+one of the beauties of base and bounds: it's so darn simple!
82
+
83
+There are a few flags you can use to control what's going on better:
84
+
85
+```text
86
+prompt> ./relocation.py -h Usage: relocation.py [options]
87
+
88
+Options: -h, --help            show this help message and exit -s SEED,
89
+  --seed=SEED  the random seed -a ASIZE, --asize=ASIZE address space size (e.g.,
90
+  16, 64k, 32m) -p PSIZE, --physmem=PSIZE physical memory size (e.g., 16, 64k)
91
+  -n NUM, --addresses=NUM # of virtual addresses to generate -b BASE, --b=BASE
92
+  value of base register -l LIMIT, --l=LIMIT   value of limit register -c,
93
+  --compute         compute answers for me
94
+```
95
+
96
+In particular, you can control the virtual address-space size (-a), the size
97
+of physical memory (-p), the number of virtual addresses to generate (-n), and
98
+the values of the base and bounds registers for this process (-b and -l,
99
+respectively).

+ 118
- 0
hw3/simu1/relocation.py Dosyayı Görüntüle

@@ -0,0 +1,118 @@
1
+#! /usr/bin/env python
2
+
3
+import sys
4
+from optparse import OptionParser
5
+import random
6
+import math
7
+
8
+def convert(size):
9
+    length = len(size)
10
+    lastchar = size[length-1]
11
+    if (lastchar == 'k') or (lastchar == 'K'):
12
+        m = 1024
13
+        nsize = int(size[0:length-1]) * m
14
+    elif (lastchar == 'm') or (lastchar == 'M'):
15
+        m = 1024*1024
16
+        nsize = int(size[0:length-1]) * m
17
+    elif (lastchar == 'g') or (lastchar == 'G'):
18
+        m = 1024*1024*1024
19
+        nsize = int(size[0:length-1]) * m
20
+    else:
21
+        nsize = int(size)
22
+    return nsize
23
+
24
+
25
+#
26
+# main program
27
+#
28
+parser = OptionParser()
29
+parser.add_option('-s', '--seed',      default=0,     help='the random seed',                                action='store', type='int', dest='seed')
30
+parser.add_option('-a', '--asize',     default='1k',  help='address space size (e.g., 16, 64k, 32m, 1g)',    action='store', type='string', dest='asize')
31
+parser.add_option('-p', '--physmem',   default='16k', help='physical memory size (e.g., 16, 64k, 32m, 1g)',  action='store', type='string', dest='psize')
32
+parser.add_option('-n', '--addresses', default=5,     help='number of virtual addresses to generate',        action='store', type='int', dest='num')
33
+parser.add_option('-b', '--b',         default='-1',  help='value of base register',                         action='store', type='string', dest='base')
34
+parser.add_option('-l', '--l',         default='-1',  help='value of limit register',                        action='store', type='string', dest='limit')
35
+parser.add_option('-c', '--compute',   default=False, help='compute answers for me',                         action='store_true', dest='solve')
36
+
37
+
38
+(options, args) = parser.parse_args()
39
+
40
+print ''
41
+print 'ARG seed', options.seed
42
+print 'ARG address space size', options.asize
43
+print 'ARG phys mem size', options.psize
44
+print ''
45
+
46
+random.seed(options.seed)
47
+asize = convert(options.asize)
48
+psize = convert(options.psize)
49
+
50
+if psize <= 1:
51
+    print 'Error: must specify a non-zero physical memory size.'
52
+    exit(1)
53
+
54
+if asize == 0:
55
+    print 'Error: must specify a non-zero address-space size.'
56
+    exit(1)
57
+
58
+if psize <= asize:
59
+    print 'Error: physical memory size must be GREATER than address space size (for this simulation)'
60
+    exit(1)
61
+
62
+#
63
+# need to generate base, bounds for segment registers
64
+#
65
+limit = convert(options.limit)
66
+base  = convert(options.base)
67
+
68
+if limit == -1:
69
+    limit = int(asize/4.0 + (asize/4.0 * random.random()))
70
+
71
+# now have to find room for them
72
+if base == -1:
73
+    done = 0
74
+    while done == 0:
75
+        base = int(psize * random.random())
76
+        if (base + limit) < psize:
77
+            done = 1
78
+
79
+print 'Base-and-Bounds register information:'
80
+print ''
81
+print '  Base   : 0x%08x (decimal %d)' % (base, base)
82
+print '  Limit  : %d' % (limit)
83
+print ''
84
+
85
+if base + limit > psize:
86
+    print 'Error: address space does not fit into physical memory with those base/bounds values.'
87
+    print 'Base + Limit:', base + limit, '  Psize:', psize
88
+    exit(1)
89
+
90
+#
91
+# now, need to generate virtual address trace
92
+#
93
+print 'Virtual Address Trace'
94
+for i in range(0,options.num):
95
+    vaddr = int(asize * random.random())
96
+    if options.solve == False:
97
+        print '  VA %2d: 0x%08x (decimal: %4d) --> PA or segmentation violation?' % (i, vaddr, vaddr)
98
+    else:
99
+        paddr = 0
100
+        if (vaddr >= limit):
101
+            print '  VA %2d: 0x%08x (decimal: %4d) --> SEGMENTATION VIOLATION' % (i, vaddr, vaddr)
102
+        else:
103
+            paddr = vaddr + base
104
+            print '  VA %2d: 0x%08x (decimal: %4d) --> VALID: 0x%08x (decimal: %4d)' % (i, vaddr, vaddr, paddr, paddr)
105
+
106
+
107
+print ''
108
+
109
+if options.solve == False:
110
+    print 'For each virtual address, either write down the physical address it translates to'
111
+    print 'OR write down that it is an out-of-bounds address (a segmentation violation). For'
112
+    print 'this problem, you should assume a simple virtual address space of a given size.'
113
+    print ''
114
+
115
+
116
+
117
+
118
+

+ 87
- 0
hw3/simu2/QUESTIONS.md Dosyayı Görüntüle

@@ -0,0 +1,87 @@
1
+# Questions 16-Segmentation
2
+
3
+This program allows you to see how address translations are performed in a
4
+system with segmentation. See the `README` for details.
5
+
6
+## Warm-up
7
+
8
+First let’s use a tiny address space to translate some addresses. Here’s a
9
+simple set of parameters with a few different random seeds; can you translate
10
+the addresses?
11
+
12
+```text
13
+      segmentation.py -a 128 -p 512 -b 0 -l 20 -B 512 -L 20 -s 0
14
+      segmentation.py -a 128 -p 512 -b 0 -l 20 -B 512 -L 20 -s 1
15
+      segmentation.py -a 128 -p 512 -b 0 -l 20 -B 512 -L 20 -s 2
16
+```
17
+
18
+## Questions
19
+
20
+1. Now, let’s see if we understand this tiny address space we’ve constructed
21
+   (using the parameters from the warm-up above). What is the highest legal
22
+   virtual address in segment 0? What about the lowest legal virtual address in
23
+   segment 1? What are the lowest and highest illegal addresses in this entire
24
+   address space? Finally, how would you run segmentation.py with the -A flag to
25
+   test if you are right?
26
+
27
+1. Let’s say we have a tiny 16-byte address space in a 128-byte physical memory.
28
+   What base and bounds would you set up so as to get the simulator to generate
29
+   the following translation results for the specified address stream: valid,
30
+   valid, violation, ..., violation, valid, valid? Assume the following
31
+   parameters:
32
+
33
+   ```text
34
+     segmentation.py -a 16 -p 128
35
+         -A 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15
36
+         --b0 ? --l0 ? --b1 ? --l1 ?
37
+   ```
38
+
39
+1. Assuming we want to generate a problem where roughly 90% of the
40
+   randomly-generated virtual addresses are valid (i.e., not segmentation
41
+   violations). How should you configure the simulator to do so? Which
42
+   parameters are important (Explanation!)?
43
+
44
+1. Can you run the simulator such that no virtual addresses are valid? How
45
+   (Explanation)?
46
+
47
+1. For each virtual address, either write down the physical address (hex and
48
+   decimal) it translates to OR write down that it is an out-of-bounds address
49
+   (a segmentation violation). For this problem, you should assume a simple
50
+   address space with two segments: the top bit of the virtual address can thus
51
+   be used to check whether the virtual address is in segment 0 (topbit=0) or
52
+   segment 1 (topbit=1). Note that the base/limit pairs given to you grow in
53
+   different directions, depending on the segment, i.e., segment 0 grows in the
54
+   positive direction, whereas segment 1 in the negative.
55
+
56
+   ```text
57
+   ARG address space size 364
58
+   ARG phys mem size 756
59
+
60
+   Segment register information:
61
+
62
+     Segment 0 base  (grows positive) : 0x00000000 (decimal 0)
63
+     Segment 0 limit                  : 64
64
+
65
+     Segment 1 base  (grows negative) : 0x00000400 (decimal 1024)
66
+     Segment 1 limit                  : 128
67
+
68
+   Virtual Address Trace
69
+     VA  0: 0x0000005c (decimal:   92) --> PA or segmentation violation?
70
+     VA  1: 0x00000011 (decimal:   17) --> PA or segmentation violation?
71
+     VA  2: 0x00000043 (decimal:   67) --> PA or segmentation violation?
72
+     VA  3: 0x00000021 (decimal:   33) --> PA or segmentation violation?
73
+     VA  4: 0x0000006c (decimal:  108) --> PA or segmentation violation?
74
+     VA  5: 0x0000007a (decimal:  122) --> PA or segmentation violation?
75
+     VA  6: 0x00000050 (decimal:   80) --> PA or segmentation violation?
76
+     VA  7: 0x00000037 (decimal:   55) --> PA or segmentation violation?
77
+     VA  8: 0x000000ff (decimal:  255) --> PA or segmentation violation?
78
+     VA  9: 0x000000e9 (decimal:  233) --> PA or segmentation violation?
79
+     VA 10: 0x00000001 (decimal:    1) --> PA or segmentation violation?
80
+     VA 11: 0x0000014c (decimal:  332) --> PA or segmentation violation?
81
+     VA 12: 0x000000b4 (decimal:  180) --> PA or segmentation violation?
82
+     VA 13: 0x000000cf (decimal:  207) --> PA or segmentation violation?
83
+     VA 14: 0x0000012b (decimal:  299) --> PA or segmentation violation?
84
+     VA 15: 0x00000084 (decimal:  132) --> PA or segmentation violation?
85
+   ```
86
+
87
+   How did you solve this question?

+ 183
- 0
hw3/simu2/README-segmentation.md Dosyayı Görüntüle

@@ -0,0 +1,183 @@
1
+# README Segmentation
2
+
3
+This program allows you to see how address translations are performed in a
4
+system with segmentation. The segmentation that this system uses is pretty
5
+simple: an address space has just *two* segments; further, the top bit of the
6
+virtual address generated by the process determines which segment the address is
7
+in: 0 for segment 0 (where, say, code and the heap would reside) and 1 for
8
+segment 1 (where the stack lives). Segment 0 grows in a positive direction
9
+(towards higher addresses), whereas segment 1 grows in the negative direction.
10
+
11
+Visually, the address space looks like this:
12
+
13
+```text
14
+ --------------- virtual address 0
15
+ |    seg0     |
16
+ |             |
17
+ |             |
18
+ |-------------|
19
+ |             |
20
+ |             |
21
+ |             |
22
+ |             |
23
+ |(unallocated)|
24
+ |             |
25
+ |             |
26
+ |             |
27
+ |-------------|
28
+ |             |
29
+ |    seg1     |
30
+ |-------------| virtual address max (size of address space)
31
+```
32
+
33
+With segmentation, as you might recall, there is a base/limit pair of registers
34
+per segment. Thus, in this problem, there are two base/limit pairs. The
35
+segment-0 base tells which physical address the *top* of segment 0 has been
36
+placed in physical memory and the limit tells how big the segment is; the
37
+segment-1 base tells where the *bottom* of segment 1 has been placed in physical
38
+memory and the corresponding limit also tells us how big the segment is (or how
39
+far it grows in the negative direction).
40
+
41
+As in `relocation (simu1)`, there are two steps to running the program to test
42
+out your understanding of segmentation. First, run without the "-c" flag to
43
+generate a set of translations and see if you can correctly perform the address
44
+translations yourself. Then, when done, run with the "-c" flag to check your
45
+answers.
46
+
47
+For example, to run with the default flags, type:
48
+
49
+```text
50
+prompt> ./segmentation.py
51
+```
52
+
53
+or
54
+
55
+```text
56
+prompt> python ./segmentation.py
57
+```
58
+
59
+(if the first doesn't work)
60
+
61
+You should see this:
62
+
63
+```text
64
+  ARG seed 0
65
+  ARG address space size 1k
66
+  ARG phys mem size 16k
67
+
68
+  Segment register information:
69
+
70
+    Segment 0 base  (grows positive) : 0x00001aea (decimal 6890)
71
+    Segment 0 limit                  : 472
72
+
73
+    Segment 1 base  (grows negative) : 0x00001254 (decimal 4692)
74
+    Segment 1 limit                  : 450
75
+
76
+  Virtual Address Trace
77
+    VA  0: 0x0000020b (decimal:  523) --> PA or segmentation violation?
78
+    VA  1: 0x0000019e (decimal:  414) --> PA or segmentation violation?
79
+    VA  2: 0x00000322 (decimal:  802) --> PA or segmentation violation?
80
+    VA  3: 0x00000136 (decimal:  310) --> PA or segmentation violation?
81
+    VA  4: 0x000001e8 (decimal:  488) --> PA or segmentation violation?
82
+
83
+  For each virtual address, either write down the physical address it translates
84
+  to OR write down that it is an out-of-bounds address (a segmentation
85
+  violation). For this problem, you should assume a simple address space with
86
+  two segments: the top bit of the virtual address can thus be used to check
87
+  whether the virtual address is in segment 0 (topbit=0) or segment 1
88
+  (topbit=1). Note that the base/limit pairs given to you grow in different
89
+  directions, depending on the segment, i.e., segment 0 grows in the positive
90
+  direction, whereas segment 1 in the negative.
91
+```
92
+
93
+Then, after you have computed the translations in the virtual address trace, run
94
+the program again with the "-c" flag. You will see the following (not including
95
+the redundant information):
96
+
97
+```text
98
+  Virtual Address Trace
99
+    VA  0: 0x0000020b (decimal:  523) --> SEGMENTATION VIOLATION (SEG1)
100
+    VA  1: 0x0000019e (decimal:  414) --> VALID in SEG0: 0x00001c88 (decimal: 7304)
101
+    VA  2: 0x00000322 (decimal:  802) --> VALID in SEG1: 0x00001176 (decimal: 4470)
102
+    VA  3: 0x00000136 (decimal:  310) --> VALID in SEG0: 0x00001c20 (decimal: 7200)
103
+    VA  4: 0x000001e8 (decimal:  488) --> SEGMENTATION VIOLATION (SEG0)
104
+```
105
+
106
+As you can see, with -c, the program translates the addresses for you, and hence
107
+you can check if you understand how a system using segmentation translates
108
+addresses.
109
+
110
+Of course, there are some parameters you can use to give yourself different
111
+problems. One particularly important parameter is the -s or -seed parameter,
112
+which lets you generate different problems by passing in a different random
113
+seed. Of course, make sure to use the same random seed when you are generating a
114
+problem and then solving it.
115
+
116
+There are also some parameters you can use to play with different-sized address
117
+spaces and physical memories. For example, to experiment with segmentation in a
118
+tiny system, you might type:
119
+
120
+```text
121
+  prompt> ./segmentation.py -s 100 -a 16 -p 32
122
+  ARG seed 0
123
+  ARG address space size 16
124
+  ARG phys mem size 32
125
+
126
+  Segment register information:
127
+
128
+    Segment 0 base  (grows positive) : 0x00000018 (decimal 24)
129
+    Segment 0 limit                  : 4
130
+
131
+    Segment 1 base  (grows negative) : 0x00000012 (decimal 18)
132
+    Segment 1 limit                  : 5
133
+
134
+  Virtual Address Trace
135
+    VA  0: 0x0000000c (decimal:   12) --> PA or segmentation violation?
136
+    VA  1: 0x00000008 (decimal:    8) --> PA or segmentation violation?
137
+    VA  2: 0x00000001 (decimal:    1) --> PA or segmentation violation?
138
+    VA  3: 0x00000007 (decimal:    7) --> PA or segmentation violation?
139
+    VA  4: 0x00000000 (decimal:    0) --> PA or segmentation violation?
140
+```
141
+
142
+which tells the program to generate virtual addresses for a 16-byte address
143
+space placed somewhere in a 32-byte physical memory. As you can see, the
144
+resulting virtual addresses are tiny (12, 8, 1, 7, and 0). As you can also see,
145
+the program picks tiny base register and limit values, as appropriate. Run with
146
+-c to see the answers.
147
+
148
+This example should also show you exactly what each base pair means. For
149
+example, segment 0's base is set to a physical address of 24 (decimal) and is of
150
+size 4 bytes. Thus, *virtual* addresses 0, 1, 2, and 3 are in segment 0 and
151
+valid, and map to physical addresses 24, 25, 26, and 27, respectively.
152
+
153
+Slightly more tricky is the negative-direction-growing segment 1. In the tiny
154
+example above, segment 1's base register is set to physical address 18, with a
155
+size of 5 bytes. That means that the *last* five bytes of the virtual address
156
+space, in this case 11, 12, 13, 14, and 15, are valid virtual addresses, and
157
+that they map to physical addresses 13, 14, 15, 16, and 17, respectively.
158
+
159
+If that doesn't make sense, read it again -- you will have to make sense of how
160
+this works in order to do any of these problems.
161
+
162
+Note you can specify bigger values by tacking a "k", "m", or even "g" onto the
163
+values you pass in with the -a or -p flags, as in "kilobytes", "megabytes", and
164
+"gigabytes". Thus, if you wanted to do some translations with a 1-MB address
165
+space set in a 32-MB physical memory, you might type:
166
+
167
+```text
168
+prompt> ./segmentation.py -a 1m -p 32m
169
+```
170
+
171
+If you want to get even more specific, you can set the base register and limit
172
+register values yourself, with the --b0, --l0, --b1, and --l1 registers. Try
173
+them and see.
174
+
175
+Finally, you can always run
176
+
177
+```text
178
+prompt> ./segmentation.py -h
179
+```
180
+
181
+to get a complete list of flags and options.
182
+
183
+Enjoy!

+ 193
- 0
hw3/simu2/segmentation.py Dosyayı Görüntüle

@@ -0,0 +1,193 @@
1
+#! /usr/bin/env python
2
+
3
+import sys
4
+from optparse import OptionParser
5
+import random
6
+import math
7
+
8
+def convert(size):
9
+    length = len(size)
10
+    lastchar = size[length-1]
11
+    if (lastchar == 'k') or (lastchar == 'K'):
12
+        m = 1024
13
+        nsize = int(size[0:length-1]) * m
14
+    elif (lastchar == 'm') or (lastchar == 'M'):
15
+        m = 1024*1024
16
+        nsize = int(size[0:length-1]) * m
17
+    elif (lastchar == 'g') or (lastchar == 'G'):
18
+        m = 1024*1024*1024
19
+        nsize = int(size[0:length-1]) * m
20
+    else:
21
+        nsize = int(size)
22
+    return nsize
23
+
24
+
25
+#
26
+# main program
27
+#
28
+parser = OptionParser()
29
+parser.add_option("-s", "--seed", default=0, help="the random seed", 
30
+                  action="store", type="int", dest="seed")
31
+parser.add_option("-A", "--addresses", default="-1",
32
+                  help="a set of comma-separated pages to access; -1 means randomly generate", 
33
+                  action="store", type="string", dest="addresses")
34
+parser.add_option("-a", "--asize", default="1k",
35
+                  help="address space size (e.g., 16, 64k, 32m, 1g)", 
36
+                  action="store", type="string", dest="asize")
37
+parser.add_option("-p", "--physmem", default="16k",
38
+                  help="physical memory size (e.g., 16, 64k, 32m, 1g)", 
39
+                  action="store", type="string", dest="psize")
40
+parser.add_option("-n", "--numaddrs", default=5,
41
+                  help="number of virtual addresses to generate",
42
+                  action="store", type="int", dest="num")
43
+parser.add_option("-b", "--b0", default="-1",
44
+                  help="value of segment 0 base register",
45
+                  action="store", type="string", dest="base0")
46
+parser.add_option("-l", "--l0", default="-1",
47
+                  help="value of segment 0 limit register",
48
+                  action="store", type="string", dest="len0")
49
+parser.add_option("-B", "--b1", default="-1",
50
+                  help="value of segment 1 base register",
51
+                  action="store", type="string", dest="base1")
52
+parser.add_option("-L", "--l1", default="-1",
53
+                  help="value of segment 1 limit register",
54
+                  action="store", type="string", dest="len1")
55
+parser.add_option("-c", help="compute answers for me",
56
+                  action="store_true", default=False, dest="solve")
57
+
58
+
59
+(options, args) = parser.parse_args()
60
+
61
+print "ARG seed", options.seed
62
+print "ARG address space size", options.asize
63
+print "ARG phys mem size", options.psize
64
+print ""
65
+
66
+random.seed(options.seed)
67
+asize = convert(options.asize)
68
+psize = convert(options.psize)
69
+addresses = str(options.addresses)
70
+
71
+if psize <= 1:
72
+    print 'Error: must specify a non-zero physical memory size.'
73
+    exit(1)
74
+
75
+if asize == 0:
76
+    print 'Error: must specify a non-zero address-space size.'
77
+    exit(1)
78
+
79
+if psize <= asize:
80
+    print 'Error: physical memory size must be GREATER than address space size (for this simulation)'
81
+    exit(1)
82
+
83
+#
84
+# need to generate base, bounds for segment registers
85
+#
86
+len0 = convert(options.len0)
87
+len1 = convert(options.len1)
88
+base0 = convert(options.base0)
89
+base1 = convert(options.base1)
90
+
91
+if len0 == -1:
92
+    len0 = int(asize/4.0 + (asize/4.0 * random.random()))
93
+
94
+if len1 == -1:
95
+    len1 = int(asize/4.0 + (asize/4.0 * random.random()))
96
+
97
+# now have to find room for them
98
+if base0 == -1:
99
+    done = 0
100
+    while done == 0:
101
+        base0 = int(psize * random.random())
102
+        if (base0 + len0) < psize:
103
+            done = 1
104
+
105
+# internally, base1 points to the lower address, and base1+len1 the higher address
106
+# (this differs from what the user would pass in, for example)
107
+if base1 == -1:
108
+    done = 0
109
+    while done == 0:
110
+        base1 = int(psize * random.random())
111
+        if (base1 + len1) < psize:
112
+            if (base1 > (base0 + len0)) or ((base1 + len1) < base0):
113
+                done = 1
114
+else:
115
+    base1 = base1 - len1
116
+
117
+
118
+if len0 > asize/2.0 or len1 > asize/2.0:
119
+    print 'Error: length register is too large for this address space'
120
+    exit(1)
121
+
122
+
123
+print 'Segment register information:'
124
+print ''
125
+print '  Segment 0 base  (grows positive) : 0x%08x (decimal %d)' % (base0, base0)
126
+print '  Segment 0 limit                  : %d' % (len0)
127
+print ''
128
+print '  Segment 1 base  (grows negative) : 0x%08x (decimal %d)' % (base1+len1, base1+len1)
129
+print '  Segment 1 limit                  : %d' % (len1)
130
+print ''
131
+nbase1  = base1 + len1
132
+
133
+if (len0 + base0) > (base1) and (base1 > base0):
134
+    print 'Error: segments overlap in physical memory'
135
+    exit(1)
136
+
137
+
138
+addrList = []
139
+if addresses == '-1':
140
+    # need to generate addresses
141
+    for i in range(0, options.num):
142
+        n = int(asize * random.random())
143
+        addrList.append(n)
144
+else:
145
+    addrList = addresses.split(',')
146
+
147
+#
148
+# now, need to generate virtual address trace
149
+#
150
+print 'Virtual Address Trace'
151
+i = 0
152
+for vStr in addrList:
153
+    # vaddr = int(asize * random.random())
154
+    vaddr = int(vStr)
155
+    if vaddr < 0 or vaddr >= asize:
156
+        print 'Error: virtual address %d cannot be generated in an address space of size %d' % (vaddr, asize)
157
+        exit(1)
158
+    if options.solve == False:
159
+        print '  VA %2d: 0x%08x (decimal: %4d) --> PA or segmentation violation?' % (i, vaddr, vaddr)
160
+    else:
161
+        paddr = 0
162
+        if (vaddr >= (asize / 2)):
163
+            # seg 1
164
+            paddr = nbase1 + (vaddr - asize)
165
+            if paddr < base1:
166
+                print '  VA %2d: 0x%08x (decimal: %4d) --> SEGMENTATION VIOLATION (SEG1)' % (i, vaddr, vaddr)
167
+            else:
168
+                print '  VA %2d: 0x%08x (decimal: %4d) --> VALID in SEG1: 0x%08x (decimal: %4d)' % (i, vaddr, vaddr, paddr, paddr)
169
+        else:
170
+            # seg 0
171
+            if (vaddr >= len0):
172
+                print '  VA %2d: 0x%08x (decimal: %4d) --> SEGMENTATION VIOLATION (SEG0)' % (i, vaddr, vaddr)
173
+            else:
174
+                paddr = vaddr + base0
175
+                print '  VA %2d: 0x%08x (decimal: %4d) --> VALID in SEG0: 0x%08x (decimal: %4d)' % (i, vaddr, vaddr, paddr, paddr)
176
+    i += 1
177
+
178
+print ''
179
+
180
+if options.solve == False:
181
+    print 'For each virtual address, either write down the physical address it translates to'
182
+    print 'OR write down that it is an out-of-bounds address (a segmentation violation). For'
183
+    print 'this problem, you should assume a simple address space with two segments: the top'
184
+    print 'bit of the virtual address can thus be used to check whether the virtual address'
185
+    print 'is in segment 0 (topbit=0) or segment 1 (topbit=1). Note that the base/limit pairs'
186
+    print 'given to you grow in different directions, depending on the segment, i.e., segment 0'
187
+    print 'grows in the positive direction, whereas segment 1 in the negative. '
188
+    print ''
189
+
190
+
191
+
192
+
193
+

+ 41
- 0
hw3/simu3/QUESTIONS.md Dosyayı Görüntüle

@@ -0,0 +1,41 @@
1
+# Questions 17-FreeSpace-Management
2
+
3
+The program, `malloc.py`, lets you explore the behavior of a simple free-space
4
+allocator as described in the chapter. See the README for details of its basic
5
+operation.
6
+
7
+## Warm-up
8
+
9
+First run with the flags `-n 10 -H 0 -p BEST -s 0` to generate a few random
10
+allocations and frees. Can you predict what *alloc()*/*free()* will return? Can
11
+you guess the state of the free list after each request? What do you notice
12
+about the free list over time?
13
+
14
+## Questions
15
+
16
+1. How are the results different when using a WORST fit policy to search the
17
+   free list (`-p WORST`) from warm-up? What changes (Explanation)?
18
+
19
+1. What about when using FIRST fit (`-p FIRST`)? What speeds up when you use
20
+   first fit (Explanation)?
21
+
22
+1. For the above questions, how the list is kept ordered can affect the time it
23
+   takes to find a free location for some of the policies. Use the different
24
+   free list orderings (`-l ADDRSORT, -l SIZESORT+, -l SIZESORT-`) to see how
25
+   the policies and the list orderings interact. What are your observations?
26
+
27
+1. Coalescing of a free list can be quite important. Increase the number of
28
+   random allocations (say to `-n 1000`). What happens to larger allocation
29
+   requests over time? Run with and without coalescing (i.e., without and with
30
+   the `-C` flag). What differences in outcome do you see? How big is the free
31
+   list over time in each case? Does the ordering of the list matter in this
32
+   case? Comment your results!
33
+
34
+1. What happens when you change the percent allocated fraction `-P` to higher
35
+   than 50? What happens to allocations as it nears 100? What about as it nears
36
+   0? Please give an explanation to your observations.
37
+
38
+1. What kind of specific requests can you make to generate a highly-fragmented
39
+   free space? Use the `-A` flag to create fragmented free lists, and see how
40
+   different policies and options change the organization of the free list.
41
+   Explain your results.

+ 164
- 0
hw3/simu3/README-malloc.md Dosyayı Görüntüle

@@ -0,0 +1,164 @@
1
+# README malloc
2
+
3
+This program, `malloc.py`, allows you to see how a simple memory allocator works.
4
+Here are the options that you have at your disposal:
5
+
6
+```text
7
+  -h, --help            show this help message and exit
8
+  -s SEED, --seed=SEED  the random seed
9
+  -S HEAPSIZE, --size=HEAPSIZE
10
+                        size of the heap
11
+  -b BASEADDR, --baseAddr=BASEADDR
12
+                        base address of heap
13
+  -H HEADERSIZE, --headerSize=HEADERSIZE
14
+                        size of the header
15
+  -a ALIGNMENT, --alignment=ALIGNMENT
16
+                        align allocated units to size; -1->no align
17
+  -p POLICY, --policy=POLICY
18
+                        list search (BEST, WORST, FIRST)
19
+  -l ORDER, --listOrder=ORDER
20
+                        list order (ADDRSORT, SIZESORT+, SIZESORT-, INSERT-FRONT, INSERT-BACK)
21
+  -C, --coalesce        coalesce the free list?
22
+  -n OPSNUM, --numOps=OPSNUM
23
+                        number of random ops to generate
24
+  -r OPSRANGE, --range=OPSRANGE
25
+                        max alloc size
26
+  -P OPSPALLOC, --percentAlloc=OPSPALLOC
27
+                        percent of ops that are allocs
28
+  -A OPSLIST, --allocList=OPSLIST
29
+                        instead of random, list of ops (+10,-0,etc)
30
+  -c, --compute         compute answers for me
31
+```
32
+
33
+One way to use it is to have the program generate some random allocation/free
34
+operations and for you to see if you can figure out what the free list would
35
+look like, as well as the success or failure of each operation.
36
+
37
+Here is a simple example:
38
+
39
+```text
40
+prompt> ./malloc.py -S 100 -b 1000 -H 4 -a 4 -l ADDRSORT -p BEST -n 5
41
+
42
+ptr[0] = Alloc(3)  returned ?
43
+List?
44
+
45
+Free(ptr[0]) returned ?
46
+List?
47
+
48
+ptr[1] = Alloc(5)  returned ?
49
+List?
50
+
51
+Free(ptr[1]) returned ?
52
+List?
53
+
54
+ptr[2] = Alloc(8)  returned ?
55
+List?
56
+```
57
+
58
+In this example, we specify a heap of size 100 bytes (-S 100), starting at
59
+address 1000 (-b 1000). We specify an additional 4 bytes of header per allocated
60
+block (-H 4), and make sure each allocated space rounds up to the nearest 4-byte
61
+free chunk in size (-a 4). We specify that the free list be kept ordered by
62
+address (increasing). Finally, we specify a "best fit" free-list searching
63
+policy (-p BEST), and ask for 5 random operations to be generated (-n 5). The
64
+results of running this are above; your job is to figure out what each
65
+allocation/free operation returns, as well as the state of the free list after
66
+each operation.
67
+
68
+Here we look at the results by using the -c option.
69
+
70
+```text
71
+prompt> ./malloc.py -S 100 -b 1000 -H 4 -a 4 -l ADDRSORT -p BEST -n 5 -c
72
+
73
+ptr[0] = Alloc(3)  returned 1004 (searched 1 elements)
74
+Free List [ Size 1 ]:  [ addr:1008 sz:92 ]
75
+
76
+Free(ptr[0]) returned 0
77
+Free List [ Size 2 ]:  [ addr:1000 sz:8 ] [ addr:1008 sz:92 ]
78
+
79
+ptr[1] = Alloc(5)  returned 1012 (searched 2 elements)
80
+Free List [ Size 2 ]:  [ addr:1000 sz:8 ] [ addr:1020 sz:80 ]
81
+
82
+Free(ptr[1]) returned 0
83
+Free List [ Size 3 ]:  [ addr:1000 sz:8 ] [ addr:1008 sz:12 ] [ addr:1020 sz:80 ]
84
+
85
+ptr[2] = Alloc(8)  returned 1012 (searched 3 elements)
86
+Free List [ Size 2 ]:  [ addr:1000 sz:8 ] [ addr:1020 sz:80 ]
87
+```
88
+
89
+As you can see, the first allocation operation (an allocation) returns the
90
+following information:
91
+
92
+```text
93
+ptr[0] = Alloc(3)  returned 1004 (searched 1 elements)
94
+Free List [ Size 1 ]:  [ addr:1008 sz:92 ]
95
+```
96
+
97
+Because the initial state of the free list is just one large element, it is easy
98
+to guess that the Alloc(3) request will succeed. Further, it will just return
99
+the first chunk of memory and make the remainder into a free list. The pointer
100
+returned will be just beyond the header (address:1004), and the allocated space
101
+is rounded up to 4 bytes, leaving the free list with 92 bytes starting at 1008.
102
+
103
+The next operation is a Free, of "ptr[0]" which is what stores the results of
104
+the previous allocation request. As you can expect, this free will succeed (thus
105
+returning "0"), and the free list now looks a little more complicated:
106
+
107
+```text
108
+Free(ptr[0]) returned 0
109
+Free List [ Size 2 ]:  [ addr:1000 sz:8 ] [ addr:1008 sz:92 ]
110
+```
111
+
112
+Indeed, because we are NOT coalescing the free list, we now have two elements on
113
+it, the first being 8 bytes large and holding the just-returned space, and the
114
+second being the 92-byte chunk.
115
+
116
+We can indeed turn on coalescing via the -C flag, and the result is:
117
+
118
+```text
119
+prompt> ./malloc.py -S 100 -b 1000 -H 4 -a 4 -l ADDRSORT -p BEST -n 5 -c -C
120
+ptr[0] = Alloc(3)  returned 1004 (searched 1 elements)
121
+Free List [ Size 1 ]:  [ addr:1008 sz:92 ]
122
+
123
+Free(ptr[0]) returned 0
124
+Free List [ Size 1 ]:  [ addr:1000 sz:100 ]
125
+
126
+ptr[1] = Alloc(5)  returned 1004 (searched 1 elements)
127
+Free List [ Size 1 ]:  [ addr:1012 sz:88 ]
128
+
129
+Free(ptr[1]) returned 0
130
+Free List [ Size 1 ]:  [ addr:1000 sz:100 ]
131
+
132
+ptr[2] = Alloc(8)  returned 1004 (searched 1 elements)
133
+Free List [ Size 1 ]:  [ addr:1012 sz:88 ]
134
+```
135
+
136
+You can see that when the Free operations take place, the free list is coalesced
137
+as expected.
138
+
139
+There are some other interesting options to explore:
140
+
141
+* -p (BEST, WORST, FIRST)
142
+
143
+  This option lets you use these three different strategies to look for a chunk
144
+  of memory to use during an allocation request
145
+
146
+* -l (ADDRSORT, SIZESORT+, SIZESORT-, INSERT-FRONT, INSERT-BACK)
147
+
148
+  This option lets you keep the free list in a particular order, say sorted by
149
+  address of the free chunk, size of free chunk (either increasing with a + or
150
+  decreasing with a -), or simply returning free chunks to the front
151
+  (INSERT-FRONT) or back (INSERT-BACK) of the free list.
152
+
153
+* -A (list of ops)
154
+
155
+  This option lets you specify an exact series of requests instead of
156
+  randomly-generated ones.
157
+
158
+  For example, running with the flag "-A +10,+10,+10,-0,-2" will allocate three
159
+  chunks of size 10 bytes (plus header), and then free the first one ("-0") and
160
+  then free the third one ("-2"). What will the free list look like then?
161
+
162
+Those are the basics. Use the questions from the book chapter to explore more,
163
+or create new and interesting questions yourself to better understand how
164
+allocators function.

+ 253
- 0
hw3/simu3/malloc.py Dosyayı Görüntüle

@@ -0,0 +1,253 @@
1
+#! /usr/bin/env python
2
+
3
+import random
4
+from optparse import OptionParser
5
+
6
+class malloc:
7
+    def __init__(self, size, start, headerSize, policy, order, coalesce, align):
8
+        # size of space
9
+        self.size        = size
10
+        
11
+        # info about pretend headers
12
+        self.headerSize  = headerSize
13
+
14
+        # init free list
15
+        self.freelist    = []
16
+        self.freelist.append((start, size))
17
+
18
+        # keep track of ptr to size mappings
19
+        self.sizemap     = {}
20
+
21
+        # policy
22
+        self.policy       = policy
23
+        assert(self.policy in ['FIRST', 'BEST', 'WORST'])
24
+
25
+        # list ordering
26
+        self.returnPolicy = order
27
+        assert(self.returnPolicy in ['ADDRSORT', 'SIZESORT+', 'SIZESORT-', 'INSERT-FRONT', 'INSERT-BACK'])
28
+
29
+        # this does a ridiculous full-list coalesce, but that is ok
30
+        self.coalesce     = coalesce
31
+
32
+        # alignment (-1 if no alignment)
33
+        self.align        = align
34
+        assert(self.align == -1 or self.align > 0)
35
+
36
+    def addToMap(self, addr, size):
37
+        assert(addr not in self.sizemap)
38
+        self.sizemap[addr] = size
39
+        # print 'adding', addr, 'to map of size', size
40
+        
41
+    def malloc(self, size):
42
+        if self.align != -1:
43
+            left = size % self.align
44
+            if left != 0:
45
+                diff = self.align - left
46
+            else:
47
+                diff = 0
48
+            # print 'aligning: adding %d to %d' % (diff, size)
49
+            size += diff
50
+
51
+        size += self.headerSize
52
+
53
+        bestIdx  = -1
54
+        if self.policy == 'BEST':
55
+            bestSize = self.size + 1
56
+        elif self.policy == 'WORST' or self.policy == 'FIRST':
57
+            bestSize = -1
58
+
59
+        count = 0
60
+            
61
+        for i in range(len(self.freelist)):
62
+            eaddr, esize = self.freelist[i][0], self.freelist[i][1]
63
+            count   += 1
64
+            if esize >= size and ((self.policy == 'BEST'  and esize < bestSize) or
65
+                                  (self.policy == 'WORST' and esize > bestSize) or
66
+                                  (self.policy == 'FIRST')):
67
+                bestAddr = eaddr
68
+                bestSize = esize
69
+                bestIdx  = i
70
+                if self.policy == 'FIRST':
71
+                    break
72
+
73
+        if bestIdx != -1:
74
+            if bestSize > size:
75
+                # print 'SPLIT', bestAddr, size
76
+                self.freelist[bestIdx] = (bestAddr + size, bestSize - size)
77
+                self.addToMap(bestAddr, size)
78
+            elif bestSize == size:
79
+                # print 'PERFECT MATCH (no split)', bestAddr, size
80
+                self.freelist.pop(bestIdx)
81
+                self.addToMap(bestAddr, size)
82
+            else:
83
+                abort('should never get here')
84
+            return (bestAddr, count)
85
+
86
+        # print '*** FAILED TO FIND A SPOT', size
87
+        return (-1, count)
88
+
89
+    def free(self, addr):
90
+        # simple back on end of list, no coalesce
91
+        if addr not in self.sizemap:
92
+            return -1
93
+            
94
+        size = self.sizemap[addr]
95
+        if self.returnPolicy == 'INSERT-BACK':
96
+            self.freelist.append((addr, size))
97
+        elif self.returnPolicy == 'INSERT-FRONT':
98
+            self.freelist.insert(0, (addr, size))
99
+        elif self.returnPolicy == 'ADDRSORT':
100
+            self.freelist.append((addr, size))
101
+            self.freelist = sorted(self.freelist, key=lambda e: e[0])
102
+        elif self.returnPolicy == 'SIZESORT+':
103
+            self.freelist.append((addr, size))
104
+            self.freelist = sorted(self.freelist, key=lambda e: e[1], reverse=False)
105
+        elif self.returnPolicy == 'SIZESORT-':
106
+            self.freelist.append((addr, size))
107
+            self.freelist = sorted(self.freelist, key=lambda e: e[1], reverse=True)
108
+
109
+        # not meant to be an efficient or realistic coalescing...
110
+        if self.coalesce == True:
111
+            self.newlist = []
112
+            self.curr    = self.freelist[0]
113
+            for i in range(1, len(self.freelist)):
114
+                eaddr, esize = self.freelist[i]
115
+                if eaddr == (self.curr[0] + self.curr[1]):
116
+                    self.curr = (self.curr[0], self.curr[1] + esize)
117
+                else:
118
+                    self.newlist.append(self.curr)
119
+                    self.curr = eaddr, esize
120
+            self.newlist.append(self.curr)
121
+            self.freelist = self.newlist
122
+            
123
+        del self.sizemap[addr]
124
+        return 0
125
+
126
+    def dump(self):
127
+        print 'Free List [ Size %d ]: ' % len(self.freelist), 
128
+        for e in self.freelist:
129
+            print '[ addr:%d sz:%d ]' % (e[0], e[1]),
130
+        print ''
131
+
132
+
133
+#
134
+# main program
135
+#
136
+parser = OptionParser()
137
+
138
+parser.add_option('-s', '--seed',        default=0,          help='the random seed',                             action='store', type='int',    dest='seed')
139
+parser.add_option('-S', '--size',        default=100,        help='size of the heap',                            action='store', type='int',    dest='heapSize') 
140
+parser.add_option('-b', '--baseAddr',    default=1000,       help='base address of heap',                        action='store', type='int',    dest='baseAddr') 
141
+parser.add_option('-H', '--headerSize',  default=0,          help='size of the header',                          action='store', type='int',    dest='headerSize')
142
+parser.add_option('-a', '--alignment',   default=-1,         help='align allocated units to size; -1->no align', action='store', type='int',    dest='alignment')
143
+parser.add_option('-p', '--policy',      default='BEST',     help='list search (BEST, WORST, FIRST)',            action='store', type='string', dest='policy') 
144
+parser.add_option('-l', '--listOrder',   default='ADDRSORT', help='list order (ADDRSORT, SIZESORT+, SIZESORT-, INSERT-FRONT, INSERT-BACK)', action='store', type='string', dest='order') 
145
+parser.add_option('-C', '--coalesce',    default=False,      help='coalesce the free list?',                     action='store_true',           dest='coalesce')
146
+parser.add_option('-n', '--numOps',      default=10,         help='number of random ops to generate',            action='store', type='int',    dest='opsNum')
147
+parser.add_option('-r', '--range',       default=10,         help='max alloc size',                              action='store', type='int',    dest='opsRange')
148
+parser.add_option('-P', '--percentAlloc',default=50,         help='percent of ops that are allocs',              action='store', type='int',    dest='opsPAlloc')
149
+parser.add_option('-A', '--allocList',   default='',         help='instead of random, list of ops (+10,-0,etc)', action='store', type='string', dest='opsList')
150
+parser.add_option('-c', '--compute',     default=False,      help='compute answers for me',                      action='store_true',           dest='solve')
151
+
152
+(options, args) = parser.parse_args()
153
+
154
+m = malloc(int(options.heapSize), int(options.baseAddr), int(options.headerSize),
155
+           options.policy, options.order, options.coalesce, options.alignment)
156
+
157
+print 'seed', options.seed
158
+print 'size', options.heapSize
159
+print 'baseAddr', options.baseAddr
160
+print 'headerSize', options.headerSize
161
+print 'alignment', options.alignment
162
+print 'policy', options.policy
163
+print 'listOrder', options.order
164
+print 'coalesce', options.coalesce
165
+print 'numOps', options.opsNum
166
+print 'range', options.opsRange
167
+print 'percentAlloc', options.opsPAlloc
168
+print 'allocList', options.opsList
169
+print 'compute', options.solve
170
+print ''
171
+
172
+percent = int(options.opsPAlloc) / 100.0
173
+
174
+random.seed(int(options.seed))
175
+p = {}
176
+L = []
177
+assert(percent > 0)
178
+
179
+if options.opsList == '':
180
+    c = 0
181
+    j = 0
182
+    while j < int(options.opsNum):
183
+        pr = False
184
+        if random.random() < percent:
185
+            size     = int(random.random() * int(options.opsRange)) + 1
186
+            ptr, cnt = m.malloc(size)
187
+            if ptr != -1:
188
+                p[c] = ptr
189
+                L.append(c)
190
+            print 'ptr[%d] = Alloc(%d)' % (c, size),
191
+            if options.solve == True:
192
+                print ' returned %d (searched %d elements)' % (ptr + options.headerSize, cnt)
193
+            else:
194
+                print ' returned ?'
195
+            c += 1
196
+            j += 1
197
+            pr = True
198
+        else:
199
+            if len(p) > 0:
200
+                # pick random one to delete
201
+                d = int(random.random() * len(L))
202
+                rc = m.free(p[L[d]])
203
+                print 'Free(ptr[%d])' % L[d], 
204
+                if options.solve == True:
205
+                    print 'returned %d' % rc
206
+                else:
207
+                    print 'returned ?'
208
+                del p[L[d]]
209
+                del L[d]
210
+                # print 'DEBUG p', p
211
+                # print 'DEBUG L', L
212
+                pr = True
213
+                j += 1
214
+        if pr:
215
+            if options.solve == True:
216
+                m.dump()
217
+            else:
218
+                print 'List? '
219
+            print ''
220
+else:
221
+    c = 0
222
+    for op in options.opsList.split(','):
223
+        if op[0] == '+':
224
+            # allocation!
225
+            size     = int(op.split('+')[1])
226
+            ptr, cnt = m.malloc(size)
227
+            if ptr != -1:
228
+                p[c] = ptr
229
+            print 'ptr[%d] = Alloc(%d)' % (c, size),
230
+            if options.solve == True:
231
+                print ' returned %d (searched %d elements)' % (ptr, cnt)
232
+            else:
233
+                print ' returned ?'
234
+            c += 1
235
+        elif op[0] == '-':
236
+            # free
237
+            index = int(op.split('-')[1])
238
+            if index >= len(p):
239
+                print 'Invalid Free: Skipping'
240
+                continue
241
+            print 'Free(ptr[%d])' % index, 
242
+            rc = m.free(p[index])
243
+            if options.solve == True:
244
+                print 'returned %d' % rc
245
+            else:
246
+                print 'returned ?'
247
+        else:
248
+            abort('badly specified operand: must be +Size or -Index')
249
+        if options.solve == True:
250
+            m.dump()
251
+        else:
252
+            print 'List?'
253
+        print ''

+ 69
- 0
hw3/simu4/QUESTIONS.md Dosyayı Görüntüle

@@ -0,0 +1,69 @@
1
+# Questions 18-Paging-Linear-Translate
2
+
3
+In this simulation task, you will use a simple program, which is known as
4
+`paging-linear-translate.py`, to see if you understand how simple
5
+virtual-to-physical address translation works with linear page tables. See the
6
+README for details.
7
+
8
+## Questions
9
+
10
+1. Before doing any translations, let’s use the simulator to study how linear
11
+   page tables change size given different parameters. Compute the size of
12
+   linear page tables as different parameters change. Some suggested inputs are
13
+   below; by using the `-v` flag, you can see how many page-table entries are
14
+   filled.
15
+
16
+   First, to understand how linear page table size changes as the address space
17
+   grows:
18
+
19
+   ```text
20
+      paging-linear-translate.py -P 1k -a 1m -p 512m -v -n 0
21
+      paging-linear-translate.py -P 1k -a 2m -p 512m -v -n 0
22
+      paging-linear-translate.py -P 1k -a 4m -p 512m -v -n 0
23
+   ```
24
+
25
+   Then, to understand how linear page table size changes as page size grows:
26
+
27
+   ```text
28
+      paging-linear-translate.py -P 1k -a 1m -p 512m -v -n 0
29
+      paging-linear-translate.py -P 2k -a 1m -p 512m -v -n 0
30
+      paging-linear-translate.py -P 4k -a 1m -p 512m -v -n 0
31
+   ```
32
+
33
+   Before running any of these, try to think about the expected trends.
34
+
35
+    1.1. How can the page table size governed in equations? Give the equations to show, which parameters govern the page table size.
36
+
37
+    1.2. How should page-table size change as the address space grows? As the page size grows?
38
+
39
+    1.3. Why shouldn’t we just use really big pages in general?
40
+
41
+1. Now let’s do some translations. Start with some small examples, and change
42
+   the number of pages that are allocated to the address space with the `-u`
43
+   flag. For example:
44
+
45
+   ```text
46
+      paging-linear-translate.py -P 1k -a 16k -p 32k -v -u 0
47
+      paging-linear-translate.py -P 1k -a 16k -p 32k -v -u 25
48
+      paging-linear-translate.py -P 1k -a 16k -p 32k -v -u 50
49
+      paging-linear-translate.py -P 1k -a 16k -p 32k -v -u 75
50
+      paging-linear-translate.py -P 1k -a 16k -p 32k -v -u 100
51
+   ```
52
+
53
+   What happens as you increase the percentage of pages that are allocated in
54
+   each address space?
55
+
56
+1. Now let’s try some different random seeds, and some different (and sometimes
57
+   quite crazy) address-space parameters, for variety:
58
+
59
+   ```text
60
+      paging-linear-translate.py -P 8  -a 32   -p 1024 -v -s 1
61
+      paging-linear-translate.py -P 8k -a 32k  -p 1m   -v -s 2
62
+      paging-linear-translate.py -P 1m -a 256m -p 512m -v -s 3
63
+   ```
64
+
65
+   Which of these parameter combinations are unrealistic? Why?
66
+
67
+1. Use the program to try out some other problems. Can you find the limits of
68
+   where the program doesn’t work anymore? For example, what happens if the
69
+   address-space size is bigger than physical memory?

+ 135
- 0
hw3/simu4/README-paging-linear-translate.md Dosyayı Görüntüle

@@ -0,0 +1,135 @@
1
+# README Paging: Linear-Translation
2
+
3
+In this homework, you will use a simple program, which is known as
4
+**paging-linear-translate.py**, to see if you understand how simple
5
+virtual-to-physical address translation works with linear page tables. To run
6
+the program, remember to either type just the name of the program
7
+(`./paging-linear-translate.py`) or possibly this (`python
8
+paging-linear-translate.py`). When you run it with the -h (help) flag, you see:
9
+
10
+```text
11
+Usage: paging-linear-translate.py [options]
12
+
13
+Options:
14
+-h, --help              show this help message and exit
15
+-s SEED, --seed=SEED    the random seed
16
+-a ASIZE, --asize=ASIZE
17
+                        address space size (e.g., 16, 64k, ...)
18
+-p PSIZE, --physmem=PSIZE
19
+                        physical memory size (e.g., 16, 64k, ...)
20
+-P PAGESIZE, --pagesize=PAGESIZE
21
+                        page size (e.g., 4k, 8k, ...)
22
+-n NUM, --addresses=NUM number of virtual addresses to generate
23
+-u USED, --used=USED    percent of address space that is used
24
+-v                      verbose mode
25
+-c                      compute answers for me
26
+```
27
+
28
+First, run the program without any arguments:
29
+
30
+```text
31
+ARG seed 0
32
+ARG address space size 16k
33
+ARG phys mem size 64k
34
+ARG page size 4k
35
+ARG verbose False
36
+
37
+The format of the page table is simple:
38
+The high-order (left-most) bit is the VALID bit.
39
+  If the bit is 1, the rest of the entry is the PFN.
40
+  If the bit is 0, the page is not valid.
41
+Use verbose mode (-v) if you want to print the VPN # by
42
+each entry of the page table.
43
+
44
+Page Table (from entry 0 down to the max size)
45
+   0x8000000c
46
+   0x00000000
47
+   0x00000000
48
+   0x80000006
49
+
50
+Virtual Address Trace
51
+  VA  0: 0x00003229 (decimal:    12841) --> PA or invalid?
52
+  VA  1: 0x00001369 (decimal:     4969) --> PA or invalid?
53
+  VA  2: 0x00001e80 (decimal:     7808) --> PA or invalid?
54
+  VA  3: 0x00002556 (decimal:     9558) --> PA or invalid?
55
+  VA  4: 0x00003a1e (decimal:    14878) --> PA or invalid?
56
+
57
+For each virtual address, write down the physical address it
58
+translates to OR write down that it is an out-of-bounds
59
+address (e.g., a segmentation fault).
60
+```
61
+
62
+As you can see, what the program provides for you is a page table for a
63
+particular process (remember, in a real system with linear page tables, there is
64
+one page table per process; here we just focus on one process, its address
65
+space, and thus a single page table). The page table tells you, for each virtual
66
+page number (VPN) of the address space, that the virtual page is mapped to a
67
+particular physical frame number (PFN) and thus valid, or not valid.
68
+
69
+The format of the page-table entry is simple: the left-most (high-order) bit is
70
+the valid bit; the remaining bits, if valid is 1, is the PFN.
71
+
72
+In the example above, the page table maps VPN 0 to PFN 0xc (decimal 12), VPN 3
73
+to PFN 0x6 (decimal 6), and leaves the other two virtual pages, 1 and 2, as not
74
+valid.
75
+
76
+Because the page table is a linear array, what is printed above is a replica of
77
+what you would see in memory if you looked at the bits yourself. However, it is
78
+sometimes easier to use this simulator if you run with the verbose flag (-v);
79
+this flag also prints out the VPN (index) into the page table. From the example
80
+above, run with the -v flag:
81
+
82
+```text
83
+Page Table (from entry 0 down to the max size)
84
+  [       0]   0x8000000c
85
+  [       1]   0x00000000
86
+  [       2]   0x00000000
87
+  [       3]   0x80000006
88
+```
89
+
90
+Your job, then, is to use this page table to translate the virtual addresses
91
+given to you in the trace to physical addresses. Let's look at the first one: VA
92
+0x3229. To translate this virtual address into a physical address, we first have
93
+to break it up into its constituent components: a virtual page number and an
94
+offset. We do this by noting down the size of the address space and the page
95
+size. In this example, the address space is set to 16KB (a very small address
96
+space) and the page size is 4KB. Thus, we know that there are 14 bits in the
97
+virtual address, and that the offset is 12 bits, leaving 2 bits for the VPN.
98
+Thus, with our address 0x3229, which is binary 11 0010 0010 1001, we know the
99
+top two bits specify the VPN. Thus, 0x3229 is on virtual page 3 with an offset
100
+of 0x229.
101
+
102
+We next look in the page table to see if VPN 3 is valid and mapped to some
103
+physical frame or invalid, and we see that it is indeed valid (the high bit is 1
104
+) and mapped to physical page 6. Thus, we can form our final physical address by
105
+taking the physical page 6 and adding it onto the offset, as follows: 0x6000
106
+(the physical page, shifted into the proper spot) OR 0x0229 (the offset),
107
+yielding the final physical address: 0x6229. Thus, we can see that virtual
108
+address 0x3229 translates to physical address 0x6229 in this example.
109
+
110
+To see the rest of the solutions (after you have computed them yourself!), just
111
+run with the -c flag (as always):
112
+
113
+```text
114
+...
115
+VA  0: 00003229 (decimal: 12841) --> 00006229 (25129) [VPN 3]
116
+VA  1: 00001369 (decimal:  4969) --> Invalid (VPN 1 not valid)
117
+VA  2: 00001e80 (decimal:  7808) --> Invalid (VPN 1 not valid)
118
+VA  3: 00002556 (decimal:  9558) --> Invalid (VPN 2 not valid)
119
+VA  4: 00003a1e (decimal: 14878) --> 00006a1e (27166) [VPN 3]
120
+```
121
+
122
+Of course, you can change many of these parameters to make more interesting
123
+problems. Run the program with the -h flag to see what options there are:
124
+
125
+- The -s flag changes the random seed and thus generates different page table
126
+  values as well as different virtual addresses to translate.
127
+- The -a flag changes the size of the address space.
128
+- The -p flag changes the size of physical memory.
129
+- The -P flag changes the size of a page.
130
+- The -n flag can be used to generate more addresses to translate (instead of
131
+  the default 5).
132
+- The -u flag changes the fraction of mappings that are valid, from 0% (-u 0) up
133
+  to 100% (-u 100). The default is 50, which means that roughly 1/2 of the pages
134
+  in the virtual address space will be valid.
135
+- The -v flag prints out the VPN numbers to make your life easier.

+ 192
- 0
hw3/simu4/paging-linear-translate.py Dosyayı Görüntüle

@@ -0,0 +1,192 @@
1
+#! /usr/bin/env python
2
+
3
+import sys
4
+from optparse import OptionParser
5
+import random
6
+import math
7
+
8
+def mustbepowerof2(bits, size, msg):
9
+    if math.pow(2,bits) != size:
10
+        print 'Error in argument: %s' % msg
11
+        sys.exit(1)
12
+
13
+def mustbemultipleof(bignum, num, msg):
14
+    if (int(float(bignum)/float(num)) != (int(bignum) / int(num))):
15
+        print 'Error in argument: %s' % msg
16
+        sys.exit(1)
17
+
18
+def convert(size):
19
+    length = len(size)
20
+    lastchar = size[length-1]
21
+    if (lastchar == 'k') or (lastchar == 'K'):
22
+        m = 1024
23
+        nsize = int(size[0:length-1]) * m
24
+    elif (lastchar == 'm') or (lastchar == 'M'):
25
+        m = 1024*1024
26
+        nsize = int(size[0:length-1]) * m
27
+    elif (lastchar == 'g') or (lastchar == 'G'):
28
+        m = 1024*1024*1024
29
+        nsize = int(size[0:length-1]) * m
30
+    else:
31
+        nsize = int(size)
32
+    return nsize
33
+
34
+
35
+#
36
+# main program
37
+#
38
+parser = OptionParser()
39
+parser.add_option('-A', '--addresses', default='-1',
40
+                  help='a set of comma-separated pages to access; -1 means randomly generate', 
41
+                  action='store', type='string', dest='addresses')
42
+parser.add_option('-s', '--seed',    default=0,     help='the random seed',                               action='store', type='int', dest='seed')
43
+parser.add_option('-a', '--asize',   default='16k', help='address space size (e.g., 16, 64k, 32m, 1g)',   action='store', type='string', dest='asize')
44
+parser.add_option('-p', '--physmem', default='64k', help='physical memory size (e.g., 16, 64k, 32m, 1g)', action='store', type='string', dest='psize')
45
+parser.add_option('-P', '--pagesize', default='4k', help='page size (e.g., 4k, 8k, whatever)',            action='store', type='string', dest='pagesize')
46
+parser.add_option('-n', '--numaddrs',  default=5,  help='number of virtual addresses to generate',       action='store', type='int', dest='num')
47
+parser.add_option('-u', '--used',       default=50, help='percent of virtual address space that is used', action='store', type='int', dest='used')
48
+parser.add_option('-v',                             help='verbose mode',                                  action='store_true', default=False, dest='verbose')
49
+parser.add_option('-c',                             help='compute answers for me',                        action='store_true', default=False, dest='solve')
50
+
51
+
52
+(options, args) = parser.parse_args()
53
+
54
+print 'ARG seed',               options.seed
55
+print 'ARG address space size', options.asize
56
+print 'ARG phys mem size',      options.psize
57
+print 'ARG page size',          options.pagesize
58
+print 'ARG verbose',            options.verbose
59
+print 'ARG addresses',          options.addresses
60
+print ''
61
+
62
+random.seed(options.seed)
63
+
64
+asize    = convert(options.asize)
65
+psize    = convert(options.psize)
66
+pagesize = convert(options.pagesize)
67
+addresses = str(options.addresses)
68
+
69
+if psize <= 1:
70
+    print 'Error: must specify a non-zero physical memory size.'
71
+    exit(1)
72
+
73
+if asize < 1:
74
+    print 'Error: must specify a non-zero address-space size.'
75
+    exit(1)
76
+
77
+if psize <= asize:
78
+    print 'Error: physical memory size must be GREATER than address space size (for this simulation)'
79
+    exit(1)
80
+
81
+if psize >= convert('1g') or asize >= convert('1g'):
82
+    print 'Error: must use smaller sizes (less than 1 GB) for this simulation.'
83
+    exit(1)
84
+
85
+mustbemultipleof(asize, pagesize, 'address space must be a multiple of the pagesize')
86
+mustbemultipleof(psize, pagesize, 'physical memory must be a multiple of the pagesize')
87
+
88
+# print some useful info, like the darn page table 
89
+pages = psize / pagesize;
90
+import array
91
+used = array.array('i')
92
+pt   = array.array('i')
93
+for i in range(0,pages):
94
+    used.insert(i,0)
95
+vpages = asize / pagesize
96
+
97
+# now, assign some pages of the VA
98
+vabits   = int(math.log(float(asize))/math.log(2.0))
99
+mustbepowerof2(vabits, asize, 'address space must be a power of 2')
100
+pagebits = int(math.log(float(pagesize))/math.log(2.0))
101
+mustbepowerof2(pagebits, pagesize, 'page size must be a power of 2')
102
+vpnbits  = vabits - pagebits
103
+pagemask = (1 << pagebits) - 1
104
+
105
+# import ctypes
106
+# vpnmask  = ctypes.c_uint32(~pagemask).value
107
+vpnmask = 0xFFFFFFFF & ~pagemask
108
+#if vpnmask2 != vpnmask:
109
+#    print 'ERROR'
110
+#    exit(1)
111
+# print 'va:%d page:%d vpn:%d -- %08x %08x' % (vabits, pagebits, vpnbits, vpnmask, pagemask)
112
+
113
+print ''
114
+print 'The format of the page table is simple:'
115
+print 'The high-order (left-most) bit is the VALID bit.'
116
+print '  If the bit is 1, the rest of the entry is the PFN.'
117
+print '  If the bit is 0, the page is not valid.'
118
+print 'Use verbose mode (-v) if you want to print the VPN # by'
119
+print 'each entry of the page table.'
120
+print ''
121
+
122
+print 'Page Table (from entry 0 down to the max size)'
123
+for v in range(0,vpages):
124
+    done = 0
125
+    while done == 0:
126
+        if ((random.random() * 100.0) > (100.0 - float(options.used))):
127
+            u = int(pages * random.random())
128
+            if used[u] == 0:
129
+                done = 1
130
+                # print '%8d - %d' % (v, u)
131
+                if options.verbose == True:
132
+                    print '  [%8d]  ' % v,
133
+                else:
134
+                    print '  ',
135
+                print '0x%08x' % (0x80000000 | u)
136
+                pt.insert(v,u)
137
+        else:
138
+            # print '%8d - not valid' % v
139
+            if options.verbose == True:
140
+                print '  [%8d]  ' % v,
141
+            else:
142
+                print '  ',
143
+            print '0x%08x' % 0
144
+            pt.insert(v,-1)
145
+            done = 1
146
+print ''            
147
+
148
+
149
+#
150
+# now, need to generate virtual address trace
151
+#
152
+
153
+addrList = []
154
+if addresses == '-1':
155
+    # need to generate addresses
156
+    for i in range(0, options.num):
157
+        n = int(asize * random.random())
158
+        addrList.append(n)
159
+else:
160
+    addrList = addresses.split(',')
161
+
162
+
163
+print 'Virtual Address Trace'
164
+for vStr in addrList:
165
+    # vaddr = int(asize * random.random())
166
+    vaddr = int(vStr)
167
+    if options.solve == False:
168
+        print '  VA 0x%08x (decimal: %8d) --> PA or invalid address?' % (vaddr, vaddr)
169
+    else:
170
+        paddr = 0
171
+        # split vaddr into VPN | offset
172
+        vpn = (vaddr & vpnmask) >> pagebits
173
+        if pt[vpn] < 0:
174
+            print '  VA 0x%08x (decimal: %8d) -->  Invalid (VPN %d not valid)' % (vaddr, vaddr, vpn)
175
+        else:
176
+            pfn    = pt[vpn]
177
+            offset = vaddr & pagemask
178
+            paddr  = (pfn << pagebits) | offset
179
+            print '  VA 0x%08x (decimal: %8d) --> %08x (decimal %8d) [VPN %d]' % (vaddr, vaddr, paddr, paddr, vpn)
180
+print ''
181
+
182
+if options.solve == False:
183
+    print 'For each virtual address, write down the physical address it translates to'
184
+    print 'OR write down that it is an out-of-bounds address (e.g., segfault).'
185
+    print ''
186
+
187
+
188
+
189
+
190
+
191
+
192
+

Loading…
İptal
Kaydet