Subversion Repositories HelenOS-doc

Rev

Rev 46 | Rev 54 | Go to most recent revision | Only display areas with differences | Regard whitespace | Details | Blame | Last modification | View Log | RSS feed

Rev 46 Rev 47
1
<?xml version="1.0" encoding="UTF-8"?>
1
<?xml version="1.0" encoding="UTF-8"?>
2
<chapter id="mm">
2
<chapter id="mm">
3
  <?dbhtml filename="mm.html"?>
3
  <?dbhtml filename="mm.html"?>
4
 
4
 
5
  <title>Memory management</title>
5
  <title>Memory management</title>
6
 
6
 
7
  <section>
7
  <section>
8
    <title>Virtual memory management</title>
8
    <title>Virtual memory management</title>
9
 
9
 
10
    <section>
10
    <section>
11
      <title>Introduction</title>
11
      <title>Introduction</title>
12
 
12
 
13
      <para>Virtual memory is a special memory management technique, used by
13
      <para>Virtual memory is a special memory management technique, used by
14
      kernel to achieve a bunch of mission critical goals. <itemizedlist>
14
      kernel to achieve a bunch of mission critical goals. <itemizedlist>
15
          <listitem>
15
          <listitem>
16
             Isolate each task from other tasks that are running on the system at the same time.
16
             Isolate each task from other tasks that are running on the system at the same time.
17
          </listitem>
17
          </listitem>
18
 
18
 
19
          <listitem>
19
          <listitem>
20
             Allow to allocate more memory, than is actual physical memory size of the machine.
20
             Allow to allocate more memory, than is actual physical memory size of the machine.
21
          </listitem>
21
          </listitem>
22
 
22
 
23
          <listitem>
23
          <listitem>
24
             Allowing, in general, to load and execute two programs that are linked on the same address without complicated relocations.
24
             Allowing, in general, to load and execute two programs that are linked on the same address without complicated relocations.
25
          </listitem>
25
          </listitem>
26
        </itemizedlist></para>
26
        </itemizedlist></para>
27
 
27
 
28
      <para><!--
28
      <para><!--
29
 
29
 
30
                TLB shootdown ASID/ASID:PAGE/ALL.
30
                TLB shootdown ASID/ASID:PAGE/ALL.
31
                TLB shootdown requests can come in asynchroniously
31
                TLB shootdown requests can come in asynchroniously
32
                so there is a cache of TLB shootdown requests. Upon cache overflow TLB shootdown ALL is executed
32
                so there is a cache of TLB shootdown requests. Upon cache overflow TLB shootdown ALL is executed
33
 
33
 
34
 
34
 
35
                <para>
35
                <para>
36
                        Address spaces. Address space area (B+ tree). Only for uspace. Set of syscalls (shrink/extend etc).
36
                        Address spaces. Address space area (B+ tree). Only for uspace. Set of syscalls (shrink/extend etc).
37
                        Special address space area type - device - prohibits shrink/extend syscalls to call on it.
37
                        Special address space area type - device - prohibits shrink/extend syscalls to call on it.
38
                        Address space has link to mapping tables (hierarchical - per Address space, hash - global tables).
38
                        Address space has link to mapping tables (hierarchical - per Address space, hash - global tables).
39
                </para>
39
                </para>
40
 
40
 
41
--></para>
41
--></para>
42
    </section>
42
    </section>
43
 
43
 
44
    <section>
44
    <section>
45
      <title>Paging</title>
45
      <title>Paging</title>
46
 
46
 
47
      <para>Virtual memory is usually using paged memory model, where virtual
47
      <para>Virtual memory is usually using paged memory model, where virtual
48
      memory address space is divided into the <emphasis>pages</emphasis>
48
      memory address space is divided into the <emphasis>pages</emphasis>
49
      (usually having size 4096 bytes) and physical memory is divided into the
49
      (usually having size 4096 bytes) and physical memory is divided into the
50
      frames (same sized as a page, of course). Each page may be mapped to
50
      frames (same sized as a page, of course). Each page may be mapped to
51
      some frame and then, upon memory access to the virtual address, CPU
51
      some frame and then, upon memory access to the virtual address, CPU
52
      performs <emphasis>address translation</emphasis> during the instruction
52
      performs <emphasis>address translation</emphasis> during the instruction
53
      execution. Non-existing mapping generates page fault exception, calling
53
      execution. Non-existing mapping generates page fault exception, calling
54
      kernel exception handler, thus allowing kernel to manipulate rules of
54
      kernel exception handler, thus allowing kernel to manipulate rules of
55
      memory access. Information for pages mapping is stored by kernel in the
55
      memory access. Information for pages mapping is stored by kernel in the
56
      <link linkend="page_tables">page tables</link></para>
56
      <link linkend="page_tables">page tables</link></para>
57
 
57
 
58
      <para>The majority of the architectures use multi-level page tables,
58
      <para>The majority of the architectures use multi-level page tables,
59
      which means need to access physical memory several times before getting
59
      which means need to access physical memory several times before getting
60
      physical address. This fact would make serios performance overhead in
60
      physical address. This fact would make serios performance overhead in
61
      virtual memory management. To avoid this <link linkend="tlb">Traslation
61
      virtual memory management. To avoid this <link linkend="tlb">Traslation
62
      Lookaside Buffer (TLB)</link> is used.</para>
62
      Lookaside Buffer (TLB)</link> is used.</para>
63
    </section>
63
    </section>
64
 
64
 
65
    <section>
65
    <section>
66
      <title>Address spaces</title>
66
      <title>Address spaces</title>
67
 
67
 
68
      <section>
68
      <section>
69
        <title>Address space areas</title>
69
        <title>Address space areas</title>
70
 
70
 
71
        <para>Each address space consists of mutually disjunctive continuous
71
        <para>Each address space consists of mutually disjunctive continuous
72
        address space areas. Address space area is precisely defined by its
72
        address space areas. Address space area is precisely defined by its
73
        base address and the number of frames is contains.</para>
73
        base address and the number of frames/pages is contains.</para>
74
 
74
 
75
        <para>Address space area also has special flags, that define behaviour
75
        <para>Address space area , that define behaviour and permissions on
76
        and permissions on the particular area. <itemizedlist>
76
        the particular area. <itemizedlist>
77
            <listitem>
77
            <listitem>
78
               
78
               
79
 
79
 
80
              <emphasis>AS_AREA_READ</emphasis>
80
              <emphasis>AS_AREA_READ</emphasis>
81
 
81
 
82
               flag indicates reading permission.
82
               flag indicates reading permission.
83
            </listitem>
83
            </listitem>
84
 
84
 
85
            <listitem>
85
            <listitem>
86
               
86
               
87
 
87
 
88
              <emphasis>AS_AREA_WRITE</emphasis>
88
              <emphasis>AS_AREA_WRITE</emphasis>
89
 
89
 
90
               flag indicates writing permission.
90
               flag indicates writing permission.
91
            </listitem>
91
            </listitem>
92
 
92
 
93
            <listitem>
93
            <listitem>
94
               
94
               
95
 
95
 
96
              <emphasis>AS_AREA_EXEC</emphasis>
96
              <emphasis>AS_AREA_EXEC</emphasis>
97
 
97
 
98
               flag indicates code execution permission. Some architectures do not support execution persmission restriction. In this case this flag has no effect.
98
               flag indicates code execution permission. Some architectures do not support execution persmission restriction. In this case this flag has no effect.
99
            </listitem>
99
            </listitem>
100
 
100
 
101
            <listitem>
101
            <listitem>
102
               
102
               
103
 
103
 
104
              <emphasis>AS_AREA_DEVICE</emphasis>
104
              <emphasis>AS_AREA_DEVICE</emphasis>
105
 
105
 
106
               marks area as mapped to the device memory.
106
               marks area as mapped to the device memory.
107
            </listitem>
107
            </listitem>
108
          </itemizedlist></para>
108
          </itemizedlist></para>
109
 
109
 
110
        <para>Kernel provides possibility tasks create/expand/shrink/share its
110
        <para>Kernel provides possibility tasks create/expand/shrink/share its
111
        address space via the set of syscalls.</para>
111
        address space via the set of syscalls.</para>
112
      </section>
112
      </section>
113
 
113
 
114
      <section>
114
      <section>
115
        <title>Address Space ID (ASID)</title>
115
        <title>Address Space ID (ASID)</title>
116
 
116
 
117
        <para>When switching to the different task, kernel also require to
117
        <para>When switching to the different task, kernel also require to
118
        switch mappings to the different address space. In case TLB cannot
118
        switch mappings to the different address space. In case TLB cannot
119
        distinguish address space mappings, all mappings from the old address
119
        distinguish address space mappings, all mapping information in TLB
120
        space should be flushed, which can create certain uncessary
120
        from the old address space must be flushed, which can create certain
121
        overhead.</para>
-
 
122
 
-
 
123
        <para>To avoid this, some architectures have capability to segregate
121
        uncessary overhead during the task switching. To avoid this, some
124
        different address spaces on HW level introducing the ASID (address
122
        architectures have capability to segregate different address spaces on
125
        space ID). On those architectures each TLB record contains an address
123
        hardware level introducing the address space identifier as a part of
126
        space identifier, that tells to which address space this record is
124
        TLB record, telling the virtual address space translation unit to
127
        applicable.</para>
125
        which address space this record is applicable.</para>
128
 
126
 
129
        <para>HelenOS kernel can take advantage of this hardware supported
127
        <para>HelenOS kernel can take advantage of this hardware supported
130
        identifier by having an ASID abstraction which is connected to the
128
        identifier by having an ASID abstraction which is somehow related to
131
        corresponding architecture identifier. I.e. on ia64 kernel ASID is
129
        the corresponding architecture identifier. I.e. on ia64 kernel ASID is
132
        built from RID (region identifier) and on the mips32 kernel ASID is
130
        derived from RID (region identifier) and on the mips32 kernel ASID is
133
        actually the hardware identifier.</para>
131
        actually the hardware identifier. As expected, this ASID information
-
 
132
        record is the part of <emphasis>as_t</emphasis> structure.</para>
134
 
133
 
135
        <para>Due to the hardware limitations ASID has limited length from 8
134
        <para>Due to the hardware limitations, hardware ASID has limited
136
        bits on ia64 to 24 bits on mips32, which makes it impossible to use as
135
        length from 8 bits on ia64 to 24 bits on mips32, which makes it
137
        unique address space identifier for all tasks running in the system.
136
        impossible to use it as unique address space identifier for all tasks
138
        In such situations special ASID stealing algoritm is used, which takes
137
        running in the system. In such situations special ASID stealing
-
 
138
        algoritm is used, which takes ASID from inactive task and assigns it
-
 
139
        to the active task.</para>
-
 
140
 
139
        ASID from inactive task and assigns it to the active task.</para>
141
        <para><classname>ASID stealing algoritm here.</classname></para>
140
      </section>
142
      </section>
141
    </section>
143
    </section>
142
 
144
 
143
    <section>
145
    <section>
144
      <title>Virtual address translation</title>
146
      <title>Virtual address translation</title>
145
 
147
 
146
      <section id="page_tables">
148
      <section id="page_tables">
147
        <title>Page tables</title>
149
        <title>Page tables</title>
148
 
150
 
149
        <para>HelenOS kernel has two different approaches to the paging
151
        <para>HelenOS kernel has two different approaches to the paging
150
        implementation: <emphasis>4 level page tables</emphasis> and
152
        implementation: <emphasis>4 level page tables</emphasis> and
151
        <emphasis>global hash tables</emphasis>, which are accessible via
153
        <emphasis>global hash tables</emphasis>, which are accessible via
152
        generic paging abstraction layer. This division was caused by the
154
        generic paging abstraction layer. Such different functionality was
153
        major architectural differences between different platforms.</para>
155
        caused by the major architectural differences between supported
-
 
156
        platforms. This abstraction is implemented with help of the global
-
 
157
        structure of pointers to basic mapping functions
-
 
158
        <emphasis>page_mapping_operations</emphasis>. To achieve different
-
 
159
        functionality of page tables, corresponding layer must implement
-
 
160
        functions, declared in
-
 
161
        <emphasis>page_mapping_operations</emphasis></para>
154
 
162
 
155
        <formalpara>
163
        <formalpara>
156
          <title>4-level page tables</title>
164
          <title>4-level page tables</title>
157
 
165
 
158
          <para>4-level page tables are the generalization of the hardware
166
          <para>4-level page tables are the generalization of the hardware
159
          capabilities of the certain platforms. <itemizedlist>
167
          capabilities of several architectures.<itemizedlist>
160
              <listitem>
168
              <listitem>
161
                 ia32 uses 2-level page tables, with full hardware support.
169
                 ia32 uses 2-level page tables, with full hardware support.
162
              </listitem>
170
              </listitem>
163
 
171
 
164
              <listitem>
172
              <listitem>
165
                 amd64 uses 4-level page tables, also coming with full hardware support.
173
                 amd64 uses 4-level page tables, also coming with full hardware support.
166
              </listitem>
174
              </listitem>
167
 
175
 
168
              <listitem>
176
              <listitem>
169
                 mips and ppc32 have 2-level tables, software simulated support.
177
                 mips and ppc32 have 2-level tables, software simulated support.
170
              </listitem>
178
              </listitem>
171
            </itemizedlist></para>
179
            </itemizedlist></para>
172
        </formalpara>
180
        </formalpara>
173
 
181
 
174
        <formalpara>
182
        <formalpara>
175
          <title>Global hash tables</title>
183
          <title>Global hash tables</title>
176
 
184
 
177
          <para>- global page hash table: existuje jen jedna v celem systemu
185
          <para>- global page hash table: existuje jen jedna v celem systemu
178
          (vyuziva ji ia64), pozn. ia64 ma zatim vypnuty VHPT. Pouziva se
186
          (vyuziva ji ia64), pozn. ia64 ma zatim vypnuty VHPT. Pouziva se
179
          genericke hash table s oddelenymi collision chains. ASID support is
187
          genericke hash table s oddelenymi collision chains. ASID support is
180
          required to use global hash tables.</para>
188
          required to use global hash tables.</para>
181
        </formalpara>
189
        </formalpara>
182
 
190
 
183
        <para>Thanks to the abstract paging interface, there is possibility
191
        <para>Thanks to the abstract paging interface, there is possibility
184
        left have more paging implementations, for example B-Tree page
192
        left have more paging implementations, for example B-Tree page
185
        tables.</para>
193
        tables.</para>
186
      </section>
194
      </section>
187
 
195
 
188
      <section id="tlb">
196
      <section id="tlb">
189
        <title>Translation Lookaside Buffer</title>
197
        <title>Translation Lookaside Buffer</title>
190
 
198
 
191
        <para>- TLB cachuji informace ve strankovacich tabulkach; alternativne
199
        <para>- TLB cachuji informace ve strankovacich tabulkach; alternativne
192
        se lze na strankovaci tabulky (ci ruzne hw rozsireni [e.g. VHPT, ppc32
200
        se lze na strankovaci tabulky (ci ruzne hw rozsireni [e.g. VHPT, ppc32
193
        hw hash table]) divat jako na velke TLB</para>
201
        hw hash table]) divat jako na velke TLB</para>
194
 
202
 
195
        <para>- pri modifikaci mapovani nebo odstraneni mapovani ze
203
        <para>- pri modifikaci mapovani nebo odstraneni mapovani ze
196
        strankovacich tabulek je potreba zajistit konsistenci TLB a techto
204
        strankovacich tabulek je potreba zajistit konsistenci TLB a techto
197
        tabulek; nutne delat na vsech CPU; na to mame zjednodusenou verzi TLB
205
        tabulek; nutne delat na vsech CPU; na to mame zjednodusenou verzi TLB
198
        shootdown mechanismu; je to variace na algoritmus popsany zde: D.
206
        shootdown mechanismu; je to variace na algoritmus popsany zde: D.
199
        Black et al., "Translation Lookaside Buffer Consistency: A Software
207
        Black et al., "Translation Lookaside Buffer Consistency: A Software
200
        Approach," Proc. Third Int'l Conf. Architectural Support for
208
        Approach," Proc. Third Int'l Conf. Architectural Support for
201
        Programming Languages and Operating Systems, 1989, pp. 113-122.</para>
209
        Programming Languages and Operating Systems, 1989, pp. 113-122.</para>
202
 
210
 
203
        <para>- nutno poznamenat, ze existuji odlehcenejsi verze TLB shootdown
211
        <para>- nutno poznamenat, ze existuji odlehcenejsi verze TLB shootdown
204
        algoritm</para>
212
        algoritm</para>
205
      </section>
213
      </section>
206
    </section>
214
    </section>
207
 
215
 
208
    <section>
216
    <section>
209
      <title>---</title>
217
      <title>---</title>
210
 
218
 
211
      <para>At the moment HelenOS does not support swapping.</para>
219
      <para>At the moment HelenOS does not support swapping.</para>
212
 
220
 
213
      <para>- pouzivame vypadky stranky k alokaci ramcu on-demand v ramci
221
      <para>- pouzivame vypadky stranky k alokaci ramcu on-demand v ramci
214
      as_area - na architekturach, ktere to podporuji, podporujeme non-exec
222
      as_area - na architekturach, ktere to podporuji, podporujeme non-exec
215
      stranky</para>
223
      stranky</para>
216
    </section>
224
    </section>
217
  </section>
225
  </section>
218
 
226
 
219
  <!-- End of VM -->
227
  <!-- End of VM -->
220
 
228
 
221
  <section>
229
  <section>
222
    <!-- Phys mem -->
230
    <!-- Phys mem -->
223
 
231
 
224
    <title>Physical memory management</title>
232
    <title>Physical memory management</title>
225
 
233
 
226
    <section id="zones_and_frames">
234
    <section id="zones_and_frames">
227
      <title>Zones and frames</title>
235
      <title>Zones and frames</title>
228
 
236
 
229
      <para><!--graphic fileref="images/mm2.png" /--><!--graphic fileref="images/buddy_alloc.svg" format="SVG" /--></para>
237
      <para><!--graphic fileref="images/mm2.png" /--><!--graphic fileref="images/buddy_alloc.svg" format="SVG" /--></para>
230
 
238
 
231
      <para>On some architectures not whole physical memory is available for
239
      <para>On some architectures not whole physical memory is available for
232
      conventional usage. This limitations require from kernel to maintain a
240
      conventional usage. This limitations require from kernel to maintain a
233
      table of available and unavailable ranges of physical memory addresses.
241
      table of available and unavailable ranges of physical memory addresses.
234
      Main idea of zones is in creating memory zone entity, that is a
242
      Main idea of zones is in creating memory zone entity, that is a
235
      continuous chunk of memory available for allocation. If some chunk is
243
      continuous chunk of memory available for allocation. If some chunk is
236
      not available, we simply do not put it in any zone.</para>
244
      not available, we simply do not put it in any zone.</para>
237
 
245
 
238
      <para>Zone is also serves for informational purposes, containing
246
      <para>Zone is also serves for informational purposes, containing
239
      information about number of free and busy frames. Physical memory
247
      information about number of free and busy frames. Physical memory
240
      allocation is also done inside the certain zone. Allocation of zone
248
      allocation is also done inside the certain zone. Allocation of zone
241
      frame must be organized by the <link linkend="frame_allocator">frame
249
      frame must be organized by the <link linkend="frame_allocator">frame
242
      allocator</link> associated with the zone.</para>
250
      allocator</link> associated with the zone.</para>
243
 
251
 
244
      <para>Some of the architectures (mips32, ppc32) have only one zone, that
252
      <para>Some of the architectures (mips32, ppc32) have only one zone, that
245
      covers whole physical memory, and the others (like ia32) may have
253
      covers whole physical memory, and the others (like ia32) may have
246
      multiple zones. Information about zones on current machine is stored in
254
      multiple zones. Information about zones on current machine is stored in
247
      BIOS hardware tables or can be hardcoded into kernel during compile
255
      BIOS hardware tables or can be hardcoded into kernel during compile
248
      time.</para>
256
      time.</para>
249
    </section>
257
    </section>
250
 
258
 
251
    <section id="frame_allocator">
259
    <section id="frame_allocator">
252
      <title>Frame allocator</title>
260
      <title>Frame allocator</title>
253
 
261
 
254
      <para><mediaobject id="frame_alloc">
262
      <para><mediaobject id="frame_alloc">
255
          <imageobject role="html">
263
          <imageobject role="html">
256
            <imagedata fileref="images/frame_alloc.png" format="PNG" />
264
            <imagedata fileref="images/frame_alloc.png" format="PNG" />
257
          </imageobject>
265
          </imageobject>
258
 
266
 
259
          <imageobject role="fop">
267
          <imageobject role="fop">
260
            <imagedata fileref="images.vector/frame_alloc.svg" format="SVG" />
268
            <imagedata fileref="images.vector/frame_alloc.svg" format="SVG" />
261
          </imageobject>
269
          </imageobject>
262
        </mediaobject></para>
270
        </mediaobject></para>
263
 
271
 
264
      <formalpara>
272
      <formalpara>
265
        <title>Overview</title>
273
        <title>Overview</title>
266
 
274
 
267
        <para>Frame allocator provides physical memory allocation for the
275
        <para>Frame allocator provides physical memory allocation for the
268
        kernel. Because of zonal organization of physical memory, frame
276
        kernel. Because of zonal organization of physical memory, frame
269
        allocator is always working in context of some zone, thus making
277
        allocator is always working in context of some zone, thus making
270
        impossible to allocate a piece of memory, which lays in different
278
        impossible to allocate a piece of memory, which lays in different
271
        zone, which cannot happen, because two adjacent zones can be merged
279
        zone, which cannot happen, because two adjacent zones can be merged
272
        into one. Frame allocator is also being responsible to update
280
        into one. Frame allocator is also being responsible to update
273
        information on the number of free/busy frames in zone. Physical memory
281
        information on the number of free/busy frames in zone. Physical memory
274
        allocation inside one <link linkend="zones_and_frames">memory
282
        allocation inside one <link linkend="zones_and_frames">memory
275
        zone</link> is being handled by an instance of <link
283
        zone</link> is being handled by an instance of <link
276
        linkend="buddy_allocator">buddy allocator</link> tailored to allocate
284
        linkend="buddy_allocator">buddy allocator</link> tailored to allocate
277
        blocks of physical memory frames.</para>
285
        blocks of physical memory frames.</para>
278
      </formalpara>
286
      </formalpara>
279
 
287
 
280
      <formalpara>
288
      <formalpara>
281
        <title>Allocation / deallocation</title>
289
        <title>Allocation / deallocation</title>
282
 
290
 
283
        <para>Upon allocation request, frame allocator tries to find first
291
        <para>Upon allocation request, frame allocator tries to find first
284
        zone, that can satisfy the incoming request (has required amount of
292
        zone, that can satisfy the incoming request (has required amount of
285
        free frames to allocate). During deallocation, frame allocator needs
293
        free frames to allocate). During deallocation, frame allocator needs
286
        to find zone, that contain deallocated frame. This approach could
294
        to find zone, that contain deallocated frame. This approach could
287
        bring up two potential problems: <itemizedlist>
295
        bring up two potential problems: <itemizedlist>
288
            <listitem>
296
            <listitem>
289
               Linear search of zones does not any good to performance, but number of zones is not expected to be high. And if yes, list of zones can be replaced with more time-efficient B-tree.
297
               Linear search of zones does not any good to performance, but number of zones is not expected to be high. And if yes, list of zones can be replaced with more time-efficient B-tree.
290
            </listitem>
298
            </listitem>
291
 
299
 
292
            <listitem>
300
            <listitem>
293
               Quickly find out if zone contains required number of frames to allocate and if this chunk of memory is properly aligned. This issue is perfectly solved bu the buddy allocator.
301
               Quickly find out if zone contains required number of frames to allocate and if this chunk of memory is properly aligned. This issue is perfectly solved bu the buddy allocator.
294
            </listitem>
302
            </listitem>
295
          </itemizedlist></para>
303
          </itemizedlist></para>
296
      </formalpara>
304
      </formalpara>
297
    </section>
305
    </section>
298
 
306
 
299
    <section id="buddy_allocator">
307
    <section id="buddy_allocator">
300
      <title>Buddy allocator</title>
308
      <title>Buddy allocator</title>
301
 
309
 
302
      <section>
310
      <section>
303
        <title>Overview</title>
311
        <title>Overview</title>
304
 
312
 
305
        <para><mediaobject id="buddy_alloc">
313
        <para><mediaobject id="buddy_alloc">
306
            <imageobject role="html">
314
            <imageobject role="html">
307
              <imagedata fileref="images/buddy_alloc.png" format="PNG" />
315
              <imagedata fileref="images/buddy_alloc.png" format="PNG" />
308
            </imageobject>
316
            </imageobject>
309
 
317
 
310
            <imageobject role="fop">
318
            <imageobject role="fop">
311
              <imagedata fileref="images.vector/buddy_alloc.svg" format="SVG" />
319
              <imagedata fileref="images.vector/buddy_alloc.svg" format="SVG" />
312
            </imageobject>
320
            </imageobject>
313
          </mediaobject></para>
321
          </mediaobject></para>
314
 
322
 
315
        <para>In the buddy allocator, the memory is broken down into
323
        <para>In the buddy allocator, the memory is broken down into
316
        power-of-two sized naturally aligned blocks. These blocks are
324
        power-of-two sized naturally aligned blocks. These blocks are
317
        organized in an array of lists, in which the list with index i
325
        organized in an array of lists, in which the list with index i
318
        contains all unallocated blocks of size
326
        contains all unallocated blocks of size
319
        <mathphrase>2<superscript>i</superscript></mathphrase>. The index i is
327
        <mathphrase>2<superscript>i</superscript></mathphrase>. The index i is
320
        called the order of block. Should there be two adjacent equally sized
328
        called the order of block. Should there be two adjacent equally sized
321
        blocks in the list i<mathphrase />(i.e. buddies), the buddy allocator
329
        blocks in the list i<mathphrase />(i.e. buddies), the buddy allocator
322
        would coalesce them and put the resulting block in list <mathphrase>i
330
        would coalesce them and put the resulting block in list <mathphrase>i
323
        + 1</mathphrase>, provided that the resulting block would be naturally
331
        + 1</mathphrase>, provided that the resulting block would be naturally
324
        aligned. Similarily, when the allocator is asked to allocate a block
332
        aligned. Similarily, when the allocator is asked to allocate a block
325
        of size <mathphrase>2<superscript>i</superscript></mathphrase>, it
333
        of size <mathphrase>2<superscript>i</superscript></mathphrase>, it
326
        first tries to satisfy the request from the list with index i. If the
334
        first tries to satisfy the request from the list with index i. If the
327
        request cannot be satisfied (i.e. the list i is empty), the buddy
335
        request cannot be satisfied (i.e. the list i is empty), the buddy
328
        allocator will try to allocate and split a larger block from the list
336
        allocator will try to allocate and split a larger block from the list
329
        with index i + 1. Both of these algorithms are recursive. The
337
        with index i + 1. Both of these algorithms are recursive. The
330
        recursion ends either when there are no blocks to coalesce in the
338
        recursion ends either when there are no blocks to coalesce in the
331
        former case or when there are no blocks that can be split in the
339
        former case or when there are no blocks that can be split in the
332
        latter case.</para>
340
        latter case.</para>
333
 
341
 
334
        <!--graphic fileref="images/mm1.png" format="EPS" /-->
342
        <!--graphic fileref="images/mm1.png" format="EPS" /-->
335
 
343
 
336
        <para>This approach greatly reduces external fragmentation of memory
344
        <para>This approach greatly reduces external fragmentation of memory
337
        and helps in allocating bigger continuous blocks of memory aligned to
345
        and helps in allocating bigger continuous blocks of memory aligned to
338
        their size. On the other hand, the buddy allocator suffers increased
346
        their size. On the other hand, the buddy allocator suffers increased
339
        internal fragmentation of memory and is not suitable for general
347
        internal fragmentation of memory and is not suitable for general
340
        kernel allocations. This purpose is better addressed by the <link
348
        kernel allocations. This purpose is better addressed by the <link
341
        linkend="slab">slab allocator</link>.</para>
349
        linkend="slab">slab allocator</link>.</para>
342
      </section>
350
      </section>
343
 
351
 
344
      <section>
352
      <section>
345
        <title>Implementation</title>
353
        <title>Implementation</title>
346
 
354
 
347
        <para>The buddy allocator is, in fact, an abstract framework wich can
355
        <para>The buddy allocator is, in fact, an abstract framework wich can
348
        be easily specialized to serve one particular task. It knows nothing
356
        be easily specialized to serve one particular task. It knows nothing
349
        about the nature of memory it helps to allocate. In order to beat the
357
        about the nature of memory it helps to allocate. In order to beat the
350
        lack of this knowledge, the buddy allocator exports an interface that
358
        lack of this knowledge, the buddy allocator exports an interface that
351
        each of its clients is required to implement. When supplied with an
359
        each of its clients is required to implement. When supplied with an
352
        implementation of this interface, the buddy allocator can use
360
        implementation of this interface, the buddy allocator can use
353
        specialized external functions to find a buddy for a block, split and
361
        specialized external functions to find a buddy for a block, split and
354
        coalesce blocks, manipulate block order and mark blocks busy or
362
        coalesce blocks, manipulate block order and mark blocks busy or
355
        available. For precise documentation of this interface, refer to
363
        available. For precise documentation of this interface, refer to
356
        <emphasis>"HelenOS Generic Kernel Reference Manual"</emphasis>.</para>
364
        <emphasis>"HelenOS Generic Kernel Reference Manual"</emphasis>.</para>
357
 
365
 
358
        <formalpara>
366
        <formalpara>
359
          <title>Data organization</title>
367
          <title>Data organization</title>
360
 
368
 
361
          <para>Each entity allocable by the buddy allocator is required to
369
          <para>Each entity allocable by the buddy allocator is required to
362
          contain space for storing block order number and a link variable
370
          contain space for storing block order number and a link variable
363
          used to interconnect blocks within the same order.</para>
371
          used to interconnect blocks within the same order.</para>
364
 
372
 
365
          <para>Whatever entities are allocated by the buddy allocator, the
373
          <para>Whatever entities are allocated by the buddy allocator, the
366
          first entity within a block is used to represent the entire block.
374
          first entity within a block is used to represent the entire block.
367
          The first entity keeps the order of the whole block. Other entities
375
          The first entity keeps the order of the whole block. Other entities
368
          within the block are assigned the magic value
376
          within the block are assigned the magic value
369
          <constant>BUDDY_INNER_BLOCK</constant>. This is especially important
377
          <constant>BUDDY_INNER_BLOCK</constant>. This is especially important
370
          for effective identification of buddies in a one-dimensional array
378
          for effective identification of buddies in a one-dimensional array
371
          because the entity that represents a potential buddy cannot be
379
          because the entity that represents a potential buddy cannot be
372
          associated with <constant>BUDDY_INNER_BLOCK</constant> (i.e. if it
380
          associated with <constant>BUDDY_INNER_BLOCK</constant> (i.e. if it
373
          is associated with <constant>BUDDY_INNER_BLOCK</constant> then it is
381
          is associated with <constant>BUDDY_INNER_BLOCK</constant> then it is
374
          not a buddy).</para>
382
          not a buddy).</para>
375
 
383
 
376
          <para>The buddy allocator always uses the first frame to represent
384
          <para>The buddy allocator always uses the first frame to represent
377
          the frame block. This frame contains <varname>buddy_order</varname>
385
          the frame block. This frame contains <varname>buddy_order</varname>
378
          variable to provide information about the block size it actually
386
          variable to provide information about the block size it actually
379
          represents (
387
          represents (
380
          <mathphrase>2<superscript>buddy_order</superscript></mathphrase>
388
          <mathphrase>2<superscript>buddy_order</superscript></mathphrase>
381
          frames block). Other frames in block have this value set to magic
389
          frames block). Other frames in block have this value set to magic
382
          <constant>BUDDY_INNER_BLOCK</constant> that is much greater than
390
          <constant>BUDDY_INNER_BLOCK</constant> that is much greater than
383
          buddy <varname>max_order</varname> value.</para>
391
          buddy <varname>max_order</varname> value.</para>
384
 
392
 
385
          <para>Each <varname>frame_t</varname> also contains pointer member
393
          <para>Each <varname>frame_t</varname> also contains pointer member
386
          to hold frame structure in the linked list inside one order.</para>
394
          to hold frame structure in the linked list inside one order.</para>
387
        </formalpara>
395
        </formalpara>
388
 
396
 
389
        <formalpara>
397
        <formalpara>
390
          <title>Allocation algorithm</title>
398
          <title>Allocation algorithm</title>
391
 
399
 
392
          <para>Upon <mathphrase>2<superscript>i</superscript></mathphrase>
400
          <para>Upon <mathphrase>2<superscript>i</superscript></mathphrase>
393
          frames block allocation request, allocator checks if there are any
401
          frames block allocation request, allocator checks if there are any
394
          blocks available at the order list <varname>i</varname>. If yes,
402
          blocks available at the order list <varname>i</varname>. If yes,
395
          removes block from order list and returns its address. If no,
403
          removes block from order list and returns its address. If no,
396
          recursively allocates
404
          recursively allocates
397
          <mathphrase>2<superscript>i+1</superscript></mathphrase> frame
405
          <mathphrase>2<superscript>i+1</superscript></mathphrase> frame
398
          block, splits it into two
406
          block, splits it into two
399
          <mathphrase>2<superscript>i</superscript></mathphrase> frame blocks.
407
          <mathphrase>2<superscript>i</superscript></mathphrase> frame blocks.
400
          Then adds one of the blocks to the <varname>i</varname> order list
408
          Then adds one of the blocks to the <varname>i</varname> order list
401
          and returns address of another.</para>
409
          and returns address of another.</para>
402
        </formalpara>
410
        </formalpara>
403
 
411
 
404
        <formalpara>
412
        <formalpara>
405
          <title>Deallocation algorithm</title>
413
          <title>Deallocation algorithm</title>
406
 
414
 
407
          <para>Check if block has so called buddy (another free
415
          <para>Check if block has so called buddy (another free
408
          <mathphrase>2<superscript>i</superscript></mathphrase> frame block
416
          <mathphrase>2<superscript>i</superscript></mathphrase> frame block
409
          that can be linked with freed block into the
417
          that can be linked with freed block into the
410
          <mathphrase>2<superscript>i+1</superscript></mathphrase> block).
418
          <mathphrase>2<superscript>i+1</superscript></mathphrase> block).
411
          Technically, buddy is a odd/even block for even/odd block
419
          Technically, buddy is a odd/even block for even/odd block
412
          respectively. Plus we can put an extra requirement, that resulting
420
          respectively. Plus we can put an extra requirement, that resulting
413
          block must be aligned to its size. This requirement guarantees
421
          block must be aligned to its size. This requirement guarantees
414
          natural block alignment for the blocks coming out the allocation
422
          natural block alignment for the blocks coming out the allocation
415
          system.</para>
423
          system.</para>
416
 
424
 
417
          <para>Using direct pointer arithmetics,
425
          <para>Using direct pointer arithmetics,
418
          <varname>frame_t::ref_count</varname> and
426
          <varname>frame_t::ref_count</varname> and
419
          <varname>frame_t::buddy_order</varname> variables, finding buddy is
427
          <varname>frame_t::buddy_order</varname> variables, finding buddy is
420
          done at constant time.</para>
428
          done at constant time.</para>
421
        </formalpara>
429
        </formalpara>
422
      </section>
430
      </section>
423
    </section>
431
    </section>
424
 
432
 
425
    <section id="slab">
433
    <section id="slab">
426
      <title>Slab allocator</title>
434
      <title>Slab allocator</title>
427
 
435
 
428
      <section>
436
      <section>
429
        <title>Overview</title>
437
        <title>Overview</title>
430
 
438
 
431
        <para><termdef><glossterm>Slab</glossterm> represents a contiguous
439
        <para><termdef><glossterm>Slab</glossterm> represents a contiguous
432
        piece of memory, usually made of several physically contiguous
440
        piece of memory, usually made of several physically contiguous
433
        pages.</termdef> <termdef><glossterm>Slab cache</glossterm> consists
441
        pages.</termdef> <termdef><glossterm>Slab cache</glossterm> consists
434
        of one or more slabs.</termdef></para>
442
        of one or more slabs.</termdef></para>
435
 
443
 
436
        <para>The majority of memory allocation requests in the kernel are for
444
        <para>The majority of memory allocation requests in the kernel are for
437
        small, frequently used data structures. For this purpose the slab
445
        small, frequently used data structures. For this purpose the slab
438
        allocator is a perfect solution. The basic idea behind the slab
446
        allocator is a perfect solution. The basic idea behind the slab
439
        allocator is to have lists of commonly used objects available packed
447
        allocator is to have lists of commonly used objects available packed
440
        into pages. This avoids the overhead of allocating and destroying
448
        into pages. This avoids the overhead of allocating and destroying
441
        commonly used types of objects such threads, virtual memory structures
449
        commonly used types of objects such threads, virtual memory structures
442
        etc. Also due to the exact allocated size matching, slab allocation
450
        etc. Also due to the exact allocated size matching, slab allocation
443
        completely eliminates internal fragmentation issue.</para>
451
        completely eliminates internal fragmentation issue.</para>
444
      </section>
452
      </section>
445
 
453
 
446
      <section>
454
      <section>
447
        <title>Implementation</title>
455
        <title>Implementation</title>
448
 
456
 
449
        <para><mediaobject id="slab_alloc">
457
        <para><mediaobject id="slab_alloc">
450
            <imageobject role="html">
458
            <imageobject role="html">
451
              <imagedata fileref="images/slab_alloc.png" format="PNG" />
459
              <imagedata fileref="images/slab_alloc.png" format="PNG" />
452
            </imageobject>
460
            </imageobject>
453
 
461
 
454
            <imageobject role="fop">
462
            <imageobject role="fop">
455
              <imagedata fileref="images.vector/slab_alloc.svg" format="SVG" />
463
              <imagedata fileref="images.vector/slab_alloc.svg" format="SVG" />
456
            </imageobject>
464
            </imageobject>
457
          </mediaobject></para>
465
          </mediaobject></para>
458
 
466
 
459
        <para>The SLAB allocator is closely modelled after <ulink
467
        <para>The SLAB allocator is closely modelled after <ulink
460
        url="http://www.usenix.org/events/usenix01/full_papers/bonwick/bonwick_html/">
468
        url="http://www.usenix.org/events/usenix01/full_papers/bonwick/bonwick_html/">
461
        OpenSolaris SLAB allocator by Jeff Bonwick and Jonathan Adams </ulink>
469
        OpenSolaris SLAB allocator by Jeff Bonwick and Jonathan Adams </ulink>
462
        with the following exceptions: <itemizedlist>
470
        with the following exceptions: <itemizedlist>
463
            <listitem>
471
            <listitem>
464
               empty SLABS are deallocated immediately (in Linux they are kept in linked list, in Solaris ???)
472
               empty SLABS are deallocated immediately (in Linux they are kept in linked list, in Solaris ???)
465
            </listitem>
473
            </listitem>
466
 
474
 
467
            <listitem>
475
            <listitem>
468
               empty magazines are deallocated when not needed (in Solaris they are held in linked list in slab cache)
476
               empty magazines are deallocated when not needed (in Solaris they are held in linked list in slab cache)
469
            </listitem>
477
            </listitem>
470
          </itemizedlist> Following features are not currently supported but
478
          </itemizedlist> Following features are not currently supported but
471
        would be easy to do: <itemizedlist>
479
        would be easy to do: <itemizedlist>
472
            <listitem>
480
            <listitem>
473
               - cache coloring
481
               - cache coloring
474
            </listitem>
482
            </listitem>
475
 
483
 
476
            <listitem>
484
            <listitem>
477
               - dynamic magazine grow (different magazine sizes are already supported, but we would need to adjust allocation strategy)
485
               - dynamic magazine grow (different magazine sizes are already supported, but we would need to adjust allocation strategy)
478
            </listitem>
486
            </listitem>
479
          </itemizedlist></para>
487
          </itemizedlist></para>
480
 
488
 
481
        <section>
489
        <section>
482
          <title>Magazine layer</title>
490
          <title>Magazine layer</title>
483
 
491
 
484
          <para>Due to the extensive bottleneck on SMP architures, caused by
492
          <para>Due to the extensive bottleneck on SMP architures, caused by
485
          global SLAB locking mechanism, making processing of all slab
493
          global SLAB locking mechanism, making processing of all slab
486
          allocation requests serialized, a new layer was introduced to the
494
          allocation requests serialized, a new layer was introduced to the
487
          classic slab allocator design. Slab allocator was extended to
495
          classic slab allocator design. Slab allocator was extended to
488
          support per-CPU caches 'magazines' to achieve good SMP scaling.
496
          support per-CPU caches 'magazines' to achieve good SMP scaling.
489
          <termdef>Slab SMP perfromance bottleneck was resolved by introducing
497
          <termdef>Slab SMP perfromance bottleneck was resolved by introducing
490
          a per-CPU caching scheme called as <glossterm>magazine
498
          a per-CPU caching scheme called as <glossterm>magazine
491
          layer</glossterm></termdef>.</para>
499
          layer</glossterm></termdef>.</para>
492
 
500
 
493
          <para>Magazine is a N-element cache of objects, so each magazine can
501
          <para>Magazine is a N-element cache of objects, so each magazine can
494
          satisfy N allocations. Magazine behaves like a automatic weapon
502
          satisfy N allocations. Magazine behaves like a automatic weapon
495
          magazine (LIFO, stack), so the allocation/deallocation become simple
503
          magazine (LIFO, stack), so the allocation/deallocation become simple
496
          push/pop pointer operation. Trick is that CPU does not access global
504
          push/pop pointer operation. Trick is that CPU does not access global
497
          slab allocator data during the allocation from its magazine, thus
505
          slab allocator data during the allocation from its magazine, thus
498
          making possible parallel allocations between CPUs.</para>
506
          making possible parallel allocations between CPUs.</para>
499
 
507
 
500
          <para>Implementation also requires adding another feature as the
508
          <para>Implementation also requires adding another feature as the
501
          CPU-bound magazine is actually a pair of magazines to avoid
509
          CPU-bound magazine is actually a pair of magazines to avoid
502
          thrashing when during allocation/deallocatiion of 1 item at the
510
          thrashing when during allocation/deallocatiion of 1 item at the
503
          magazine size boundary. LIFO order is enforced, which should avoid
511
          magazine size boundary. LIFO order is enforced, which should avoid
504
          fragmentation as much as possible.</para>
512
          fragmentation as much as possible.</para>
505
 
513
 
506
          <para>Another important entity of magazine layer is the common full
514
          <para>Another important entity of magazine layer is the common full
507
          magazine list (also called a depot), that stores full magazines that
515
          magazine list (also called a depot), that stores full magazines that
508
          may be used by any of the CPU magazine caches to reload active CPU
516
          may be used by any of the CPU magazine caches to reload active CPU
509
          magazine. This list of magazines can be pre-filled with full
517
          magazine. This list of magazines can be pre-filled with full
510
          magazines during initialization, but in current implementation it is
518
          magazines during initialization, but in current implementation it is
511
          filled during object deallocation, when CPU magazine becomes
519
          filled during object deallocation, when CPU magazine becomes
512
          full.</para>
520
          full.</para>
513
 
521
 
514
          <para>Slab allocator control structures are allocated from special
522
          <para>Slab allocator control structures are allocated from special
515
          slabs, that are marked by special flag, indicating that it should
523
          slabs, that are marked by special flag, indicating that it should
516
          not be used for slab magazine layer. This is done to avoid possible
524
          not be used for slab magazine layer. This is done to avoid possible
517
          infinite recursions and deadlock during conventional slab allocaiton
525
          infinite recursions and deadlock during conventional slab allocaiton
518
          requests.</para>
526
          requests.</para>
519
        </section>
527
        </section>
520
 
528
 
521
        <section>
529
        <section>
522
          <title>Allocation/deallocation</title>
530
          <title>Allocation/deallocation</title>
523
 
531
 
524
          <para>Every cache contains list of full slabs and list of partialy
532
          <para>Every cache contains list of full slabs and list of partialy
525
          full slabs. Empty slabs are immediately freed (thrashing will be
533
          full slabs. Empty slabs are immediately freed (thrashing will be
526
          avoided because of magazines).</para>
534
          avoided because of magazines).</para>
527
 
535
 
528
          <para>The SLAB allocator allocates lots of space and does not free
536
          <para>The SLAB allocator allocates lots of space and does not free
529
          it. When frame allocator fails to allocate the frame, it calls
537
          it. When frame allocator fails to allocate the frame, it calls
530
          slab_reclaim(). It tries 'light reclaim' first, then brutal reclaim.
538
          slab_reclaim(). It tries 'light reclaim' first, then brutal reclaim.
531
          The light reclaim releases slabs from cpu-shared magazine-list,
539
          The light reclaim releases slabs from cpu-shared magazine-list,
532
          until at least 1 slab is deallocated in each cache (this algorithm
540
          until at least 1 slab is deallocated in each cache (this algorithm
533
          should probably change). The brutal reclaim removes all cached
541
          should probably change). The brutal reclaim removes all cached
534
          objects, even from CPU-bound magazines.</para>
542
          objects, even from CPU-bound magazines.</para>
535
 
543
 
536
          <formalpara>
544
          <formalpara>
537
            <title>Allocation</title>
545
            <title>Allocation</title>
538
 
546
 
539
            <para><emphasis>Step 1.</emphasis> When it comes to the allocation
547
            <para><emphasis>Step 1.</emphasis> When it comes to the allocation
540
            request, slab allocator first of all checks availability of memory
548
            request, slab allocator first of all checks availability of memory
541
            in local CPU-bound magazine. If it is there, we would just "pop"
549
            in local CPU-bound magazine. If it is there, we would just "pop"
542
            the CPU magazine and return the pointer to object.</para>
550
            the CPU magazine and return the pointer to object.</para>
543
 
551
 
544
            <para><emphasis>Step 2.</emphasis> If the CPU-bound magazine is
552
            <para><emphasis>Step 2.</emphasis> If the CPU-bound magazine is
545
            empty, allocator will attempt to reload magazin, swapping it with
553
            empty, allocator will attempt to reload magazin, swapping it with
546
            second CPU magazine and returns to the first step.</para>
554
            second CPU magazine and returns to the first step.</para>
547
 
555
 
548
            <para><emphasis>Step 3.</emphasis> Now we are in the situation
556
            <para><emphasis>Step 3.</emphasis> Now we are in the situation
549
            when both CPU-bound magazines are empty, which makes allocator to
557
            when both CPU-bound magazines are empty, which makes allocator to
550
            access shared full-magazines depot to reload CPU-bound magazines.
558
            access shared full-magazines depot to reload CPU-bound magazines.
551
            If reload is succesful (meaning there are full magazines in depot)
559
            If reload is succesful (meaning there are full magazines in depot)
552
            algoritm continues at Step 1.</para>
560
            algoritm continues at Step 1.</para>
553
 
561
 
554
            <para><emphasis>Step 4.</emphasis> Final step of the allocation.
562
            <para><emphasis>Step 4.</emphasis> Final step of the allocation.
555
            In this step object is allocated from the conventional slab layer
563
            In this step object is allocated from the conventional slab layer
556
            and pointer is returned.</para>
564
            and pointer is returned.</para>
557
          </formalpara>
565
          </formalpara>
558
 
566
 
559
          <formalpara>
567
          <formalpara>
560
            <title>Deallocation</title>
568
            <title>Deallocation</title>
561
 
569
 
562
            <para><emphasis>Step 1.</emphasis> During deallocation request,
570
            <para><emphasis>Step 1.</emphasis> During deallocation request,
563
            slab allocator will check if the local CPU-bound magazine is not
571
            slab allocator will check if the local CPU-bound magazine is not
564
            full. In this case we will just push the pointer to this
572
            full. In this case we will just push the pointer to this
565
            magazine.</para>
573
            magazine.</para>
566
 
574
 
567
            <para><emphasis>Step 2.</emphasis> If the CPU-bound magazine is
575
            <para><emphasis>Step 2.</emphasis> If the CPU-bound magazine is
568
            full, allocator will attempt to reload magazin, swapping it with
576
            full, allocator will attempt to reload magazin, swapping it with
569
            second CPU magazine and returns to the first step.</para>
577
            second CPU magazine and returns to the first step.</para>
570
 
578
 
571
            <para><emphasis>Step 3.</emphasis> Now we are in the situation
579
            <para><emphasis>Step 3.</emphasis> Now we are in the situation
572
            when both CPU-bound magazines are full, which makes allocator to
580
            when both CPU-bound magazines are full, which makes allocator to
573
            access shared full-magazines depot to put one of the magazines to
581
            access shared full-magazines depot to put one of the magazines to
574
            the depot and creating new empty magazine. Algoritm continues at
582
            the depot and creating new empty magazine. Algoritm continues at
575
            Step 1.</para>
583
            Step 1.</para>
576
          </formalpara>
584
          </formalpara>
577
        </section>
585
        </section>
578
      </section>
586
      </section>
579
    </section>
587
    </section>
580
 
588
 
581
    <!-- End of Physmem -->
589
    <!-- End of Physmem -->
582
  </section>
590
  </section>
583
 
591
 
584
  <section>
592
  <section>
585
    <title>Memory sharing</title>
593
    <title>Memory sharing</title>
586
 
594
 
587
    <para>Not implemented yet(?)</para>
595
    <para>Not implemented yet(?)</para>
588
  </section>
596
  </section>
589
</chapter>
597
</chapter>