Unidade 8: Gerenciamento de Memória
-
Upload
shannon-brady -
Category
Documents
-
view
18 -
download
0
description
Transcript of Unidade 8: Gerenciamento de Memória
![Page 1: Unidade 8: Gerenciamento de Memória](https://reader036.fdocument.pub/reader036/viewer/2022062516/56812b48550346895d8f64f7/html5/thumbnails/1.jpg)
Operating System Concepts Silberschatz and Galvin1999 8.1
Unidade 8: Gerenciamento de Memória
• Introdução
• Espaço de endereçamento lógico e físico
• Swapping
• Alocação contínua
• Paginação
• Segmentação
• Segmentação usando Paginação (gambiarra)
![Page 2: Unidade 8: Gerenciamento de Memória](https://reader036.fdocument.pub/reader036/viewer/2022062516/56812b48550346895d8f64f7/html5/thumbnails/2.jpg)
Operating System Concepts Silberschatz and Galvin1999 8.2
Introdução
• O programa precisa ser colocado em memória e asociado a um processo para que possa ser executado.
• File de entrada – coleção de processos em disco qua estão esperando para ser colocados em memória para execução.
• Programas passam por várias etapas antes de serem executadas.
![Page 3: Unidade 8: Gerenciamento de Memória](https://reader036.fdocument.pub/reader036/viewer/2022062516/56812b48550346895d8f64f7/html5/thumbnails/3.jpg)
Operating System Concepts Silberschatz and Galvin1999 8.3
Link-ediçãode instruções e Dados na Memória
• Em tempo de compilação: Se a alocação da memória é conhecida antecipadamente é possível gerar código absoluto; o código deve ser recompilado se o endereço de início muda.
• Em tempo de carregamento: código relocalizável (relocatable) tem que ser gerado se a localidade no momento da execução não é conhecida no momento da compilação.
• Em tempo de execução: Link-edição é adiada para o momento de execução. Suporte de hardware é preciso para o mapeamento (por exemplo GDT do Pentium).
Link-edição de endereços de instruções e dados pode ser feitoem três situações diferentes:
![Page 4: Unidade 8: Gerenciamento de Memória](https://reader036.fdocument.pub/reader036/viewer/2022062516/56812b48550346895d8f64f7/html5/thumbnails/4.jpg)
Operating System Concepts Silberschatz and Galvin1999 8.4
Carregamento dinâmico
• Uma rotina é carregada somente quando chamada
• Melhor aproveitamento do espaço de memória física; uma rotina inútil nunca é carregada.
• Carregamento dinâmico é útil quando grandes quantidades de código são necessárias para tratar casos que raramente ocorrem.
• Suporte do sistema operacional é desejável mas não indispensável (pode ser implementado até a nível do usuário).
![Page 5: Unidade 8: Gerenciamento de Memória](https://reader036.fdocument.pub/reader036/viewer/2022062516/56812b48550346895d8f64f7/html5/thumbnails/5.jpg)
Operating System Concepts Silberschatz and Galvin1999 8.5
Carregamento dinâmico
• Link-edição é adiada para o momento da execução.
• Pequenos pedaços de código (stub) é usado para localizar a rotina da biblioteca apropriada.
• Quando chamado o stub carrega a rotina e substitui o endereço na instrução a qual o chamou pelo endereço da rotina carregada e executa a rotina.
• O sistema operacional é necessário para verificar se a rotina já tinha sido carregada por outro processo.
![Page 6: Unidade 8: Gerenciamento de Memória](https://reader036.fdocument.pub/reader036/viewer/2022062516/56812b48550346895d8f64f7/html5/thumbnails/6.jpg)
Operating System Concepts Silberschatz and Galvin1999 8.6
Overlays
• Mantém em memória somente aquelas instruções que são necessários naquele momento.
• Necessário quando o processo é maior que a quantidade de memória alocada para ele.
• Pode ser implementado a nível de usuário. Não precisa de suporte específico do sistema operacional, mas o projeto da estrutura de overlay é complicado.
![Page 7: Unidade 8: Gerenciamento de Memória](https://reader036.fdocument.pub/reader036/viewer/2022062516/56812b48550346895d8f64f7/html5/thumbnails/7.jpg)
Operating System Concepts Silberschatz and Galvin1999 8.7
Espaço de endereçamento lógico e físico
• O conceito de um espaço de endereçamento lógico que é mapeado para um espaço de endereçamento físico é fundamental para um gerenciamento de memória decente.
– Endereço lógico – usado nas instruções de máquina; também chamado endereço virtual ou endereço linear.
– Endereço físico – endereço que aparece no barramento entre CPU e memória principal.
![Page 8: Unidade 8: Gerenciamento de Memória](https://reader036.fdocument.pub/reader036/viewer/2022062516/56812b48550346895d8f64f7/html5/thumbnails/8.jpg)
Operating System Concepts Silberschatz and Galvin1999 8.8
Unidade de Gerenciamento de memória (MMU)
• Um circuito em hardware que mapeia endereços virtuais para endereços físicos.
• O programa do usuário trabalha com endereços lógicos - ele nunca enxerga endereços físicos.
![Page 9: Unidade 8: Gerenciamento de Memória](https://reader036.fdocument.pub/reader036/viewer/2022062516/56812b48550346895d8f64f7/html5/thumbnails/9.jpg)
Operating System Concepts Silberschatz and Galvin1999 8.9
Swapping
• Um processo pode ser tirado temporariamente da memória para ser colocado num armazenamento auxiliar, para mais tarde ser recolocado para a memória.
• Arazenamento auxiliar – disco rápido com capacidade suficiente para manter cópias de todas as imagens de memória para todos os usuários e possibilitar acesso direto a essas imagens.
• Roll out, roll in – variante de swapping usada para algoritmos de scheduling baseadas em prioridade – processo de baixa prioridade é tirado para que um processo de alta prioridade possa ser executado.
• A maior parte do tempo de swap é tempo de transferência, proporcional a quantidade de memória tirada e colocada.
• Versões modificadas de swapping podem ser enontadas em vários sistemas, por exemplo UNIX e Microsoft Windows.
![Page 10: Unidade 8: Gerenciamento de Memória](https://reader036.fdocument.pub/reader036/viewer/2022062516/56812b48550346895d8f64f7/html5/thumbnails/10.jpg)
Operating System Concepts Silberschatz and Galvin1999 8.10
Schematic View of Swapping
![Page 11: Unidade 8: Gerenciamento de Memória](https://reader036.fdocument.pub/reader036/viewer/2022062516/56812b48550346895d8f64f7/html5/thumbnails/11.jpg)
Operating System Concepts Silberschatz and Galvin1999 8.11
Allocação
• A memória principal é muitas vezes dividida em dois partes:
– A parte residente (permanente) do sistema operacional, normalmente nos endereços baixos de memória física, junto com tabelas de interrupções e segmentos (IDT, GDT, etc.)
– Processos de usuários em endereços de memória física mais altas.
![Page 12: Unidade 8: Gerenciamento de Memória](https://reader036.fdocument.pub/reader036/viewer/2022062516/56812b48550346895d8f64f7/html5/thumbnails/12.jpg)
Operating System Concepts Silberschatz and Galvin1999 8.12
Allocação (Cont.)
• Alocação em partes múltiplas
– Buraco – bloco de memória disponível; buracos de tamanhos variados são espalhadas as memória.
– Quando chega um processo ele recebe memória de um buraco suficientemente grande para que ele caiba.
– O sistema operacional mantém informações sobre:a) partições alocadas b) buracos
OS
process 5
process 8
process 2
OS
process 5
process 2
OS
process 5
process 2
OS
process 5
process 9
process 2
process 9
process 10
![Page 13: Unidade 8: Gerenciamento de Memória](https://reader036.fdocument.pub/reader036/viewer/2022062516/56812b48550346895d8f64f7/html5/thumbnails/13.jpg)
Operating System Concepts Silberschatz and Galvin1999 8.13
O problema da alocação dinâmica
• First-fit: Aloque o primeiro buraco que é suficientemente grande.
• Best-fit: Aloque o menor buraco que é suficientemente grande. Toda a lista de buracos precisa ser pesquisada (se ela não é ordenada). Resulta no menor buraco residual possível.
• Worst-fit: Aloque o buraco maior; também precisa pesquisar toda a lista. Deixa o maior buraco residual.
Como satisfazer uma requisição de um tamanho de n bytes a partir de umalista de buracos?
First-fit e best-fit são melhores em termos de velocidade e utilização de memória.
![Page 14: Unidade 8: Gerenciamento de Memória](https://reader036.fdocument.pub/reader036/viewer/2022062516/56812b48550346895d8f64f7/html5/thumbnails/14.jpg)
Operating System Concepts Silberschatz and Galvin1999 8.14
Fragmentação
• Fragmentação externa – existe espaço em memória para satisfazer uma determinada requisição, mas o espaço é distribuído em vários buracos.
• Fragmentação interna – memória alocada pode ser ligeiramente maior do que a memória requisitada; a memória restante não é usada. Ocorre quando partições tem tamanho fixo.
• Reduzir fragmentação externa fazendo compactação– desloca conteúdos da memória de forma a juntar todos os buracos
pequenos num só buraco grande.– Compactação é possível somente se a relocação é dinâmica e é
feita em tempo de execução.– Problema de entrada/saída (DMA)
não move processo na memória quando ele está fazendo uma operação de entrada/saída
entrada/saída somente com buffers do S.O.
![Page 15: Unidade 8: Gerenciamento de Memória](https://reader036.fdocument.pub/reader036/viewer/2022062516/56812b48550346895d8f64f7/html5/thumbnails/15.jpg)
Operating System Concepts Silberschatz and Galvin1999 8.15
Paginação
• O espaço de endereçamento físico é particionado. Um processo recebe partições de memória física na medida que eles se tornam disponíveis. O mapeamento entre endereços lógicos e físicos apresenta ao processo um espaço de endereçamento lógico sem particionamento (contínuo).
• Divide a memória física em blocos de tamanho fixo chamado frames. (tamanho é potencia de 2, entre 512 bytes e 8192 bytes).
• Divide memória lógica em blocos do mesmo tamanho chamadas páginas.
• Mantenha registro dos frames livres.
• Para rodar um programa de n páginas, procure n frames livres e carregue o programa.
• Tabela de paginação.
• Fragmentação interna.
![Page 16: Unidade 8: Gerenciamento de Memória](https://reader036.fdocument.pub/reader036/viewer/2022062516/56812b48550346895d8f64f7/html5/thumbnails/16.jpg)
Operating System Concepts Silberschatz and Galvin1999 8.16
Address Translation Scheme
• Address generated by CPU is divided into:
– Page number (p) – used as an index into a page table which contains base address of each page in physical memory.
– Page offset (d) – combined with base address to define the physical memory address that is sent to the memory unit.
![Page 17: Unidade 8: Gerenciamento de Memória](https://reader036.fdocument.pub/reader036/viewer/2022062516/56812b48550346895d8f64f7/html5/thumbnails/17.jpg)
Operating System Concepts Silberschatz and Galvin1999 8.17
Address Translation Architecture
![Page 18: Unidade 8: Gerenciamento de Memória](https://reader036.fdocument.pub/reader036/viewer/2022062516/56812b48550346895d8f64f7/html5/thumbnails/18.jpg)
Operating System Concepts Silberschatz and Galvin1999 8.18
Paging Example
![Page 19: Unidade 8: Gerenciamento de Memória](https://reader036.fdocument.pub/reader036/viewer/2022062516/56812b48550346895d8f64f7/html5/thumbnails/19.jpg)
Operating System Concepts Silberschatz and Galvin1999 8.19
Implementation of Page Table
• Page table is kept in main memory.
• Page-table base register (PTBR) points to the page table.
• Page-table length register (PRLR) indicates size of the page table.
• In this scheme every data/instruction access requires two memory accesses. One for the page table and one for the data/instruction.
• The two memory access problem can be solved by the use of a special fast-lookup hardware cache called associative registers or translation look-aside buffers (TLBs)
![Page 20: Unidade 8: Gerenciamento de Memória](https://reader036.fdocument.pub/reader036/viewer/2022062516/56812b48550346895d8f64f7/html5/thumbnails/20.jpg)
Operating System Concepts Silberschatz and Galvin1999 8.20
Memória associativa
• Memórias associativas implementam busca em paralelo em hardware
– dado o número de página, encontra o número do frame
Page # Frame #
![Page 21: Unidade 8: Gerenciamento de Memória](https://reader036.fdocument.pub/reader036/viewer/2022062516/56812b48550346895d8f64f7/html5/thumbnails/21.jpg)
Operating System Concepts Silberschatz and Galvin1999 8.21
Tempo de acesso médio efetivo
• Busca associativa = unidades de tempo
• Suponha ciclo de memória principal de 1 unidade de tempo
• taxa de acerto – porcentagem de vezes que um numero de pagina é encontrado no registro associativo. Esta razão é relacionada a capacidade da memória associativa.
• Tempo de acesso médio efetivo (EAT)
EAT = (1 + ) + (2 + )(1 – )
= 2 + –
![Page 22: Unidade 8: Gerenciamento de Memória](https://reader036.fdocument.pub/reader036/viewer/2022062516/56812b48550346895d8f64f7/html5/thumbnails/22.jpg)
Operating System Concepts Silberschatz and Galvin1999 8.22
Proteção de memória com paginação
• Bit Presente em cada entrada da tabela de página:
– ‘1’ indica que pagina está bom .
– ‘0’ indica que está fora.
![Page 23: Unidade 8: Gerenciamento de Memória](https://reader036.fdocument.pub/reader036/viewer/2022062516/56812b48550346895d8f64f7/html5/thumbnails/23.jpg)
Operating System Concepts Silberschatz and Galvin1999 8.23
Two-Level Page-Table Scheme
![Page 24: Unidade 8: Gerenciamento de Memória](https://reader036.fdocument.pub/reader036/viewer/2022062516/56812b48550346895d8f64f7/html5/thumbnails/24.jpg)
Operating System Concepts Silberschatz and Galvin1999 8.24
Two-Level Paging Example
• A logical address (on 32-bit machine with 4K page size) is divided into:– a page number consisting of 20 bits.– a page offset consisting of 12 bits.
• Since the page table is paged, the page number is further divided into:– a 10-bit page number. – a 10-bit page offset.
• Thus, a logical address is as follows:
where pi is an index into the outer page table, and p2 is the displacement within the page of the outer page table.
page number page offset
pi p2 d
10 10 12
![Page 25: Unidade 8: Gerenciamento de Memória](https://reader036.fdocument.pub/reader036/viewer/2022062516/56812b48550346895d8f64f7/html5/thumbnails/25.jpg)
Operating System Concepts Silberschatz and Galvin1999 8.25
Address-Translation Scheme
• Address-translation scheme for a two-level 32-bit paging architecture
![Page 26: Unidade 8: Gerenciamento de Memória](https://reader036.fdocument.pub/reader036/viewer/2022062516/56812b48550346895d8f64f7/html5/thumbnails/26.jpg)
Operating System Concepts Silberschatz and Galvin1999 8.26
Multilevel Paging and Performance
• Since each level is stored as a separate table in memory, covering a logical address to a physical one may take four memory accesses.
• Even though time needed for one memory access is quintupled, caching permits performance to remain reasonable.
• Cache hit rate of 98 percent yields:
effective access time = 0.98 x 120 + 0.02 x 520
= 128 nanoseconds.
which is only a 28 percent slowdown in memory access time.
![Page 27: Unidade 8: Gerenciamento de Memória](https://reader036.fdocument.pub/reader036/viewer/2022062516/56812b48550346895d8f64f7/html5/thumbnails/27.jpg)
Operating System Concepts Silberschatz and Galvin1999 8.27
Inverted Page Table
• One entry for each real page of memory.
• Entry consists of the virtual address of the page stored in that real memory location, with information about the process that owns that page.
• Decreases memory needed to store each page table, but increases time needed to search the table when a page reference occurs.
• Use hash table to limit the search to one — or at most a few — page-table entries.
![Page 28: Unidade 8: Gerenciamento de Memória](https://reader036.fdocument.pub/reader036/viewer/2022062516/56812b48550346895d8f64f7/html5/thumbnails/28.jpg)
Operating System Concepts Silberschatz and Galvin1999 8.28
Inverted Page Table Architecture
![Page 29: Unidade 8: Gerenciamento de Memória](https://reader036.fdocument.pub/reader036/viewer/2022062516/56812b48550346895d8f64f7/html5/thumbnails/29.jpg)
Operating System Concepts Silberschatz and Galvin1999 8.29
Shared Pages
• Shared code
– One copy of read-only (reentrant) code shared among processes (i.e., text editors, compilers, window systems).
– Shared code must appear in same location in the logical address space of all processes.
• Private code and data
– Each process keeps a separate copy of the code and data.
– The pages for the private code and data can appear anywhere in the logical address space.
![Page 30: Unidade 8: Gerenciamento de Memória](https://reader036.fdocument.pub/reader036/viewer/2022062516/56812b48550346895d8f64f7/html5/thumbnails/30.jpg)
Operating System Concepts Silberschatz and Galvin1999 8.30
Shared Pages Example
![Page 31: Unidade 8: Gerenciamento de Memória](https://reader036.fdocument.pub/reader036/viewer/2022062516/56812b48550346895d8f64f7/html5/thumbnails/31.jpg)
Operating System Concepts Silberschatz and Galvin1999 8.31
Segmentation
• Memory-management scheme that supports user view of memory.
• A program is a collection of segments. A segment is a logical unit such as:
main program,
procedure,
function,
local variables, global variables,
common block,
stack,
symbol table, arrays
![Page 32: Unidade 8: Gerenciamento de Memória](https://reader036.fdocument.pub/reader036/viewer/2022062516/56812b48550346895d8f64f7/html5/thumbnails/32.jpg)
Operating System Concepts Silberschatz and Galvin1999 8.32
Logical View of Segmentation
1
3
2
4
1
4
2
3
user space physical memory space
![Page 33: Unidade 8: Gerenciamento de Memória](https://reader036.fdocument.pub/reader036/viewer/2022062516/56812b48550346895d8f64f7/html5/thumbnails/33.jpg)
Operating System Concepts Silberschatz and Galvin1999 8.33
Segmentation Architecture
• Logical address consists of a two tuple:
<segment-number, offset>,
• Segment table – maps two-dimensional physical addresses; each table entry has:
– base – contains the starting physical address where the segments reside in memory.
– limit – specifies the length of the segment.
• Segment-table base register (STBR) points to the segment table’s location in memory.
• Segment-table length register (STLR) indicates number of segments used by a program;
segment number s is legal if s < STLR.
![Page 34: Unidade 8: Gerenciamento de Memória](https://reader036.fdocument.pub/reader036/viewer/2022062516/56812b48550346895d8f64f7/html5/thumbnails/34.jpg)
Operating System Concepts Silberschatz and Galvin1999 8.34
Segmentation Architecture (Cont.)
• Relocation.
– dynamic
– by segment table
• Sharing.
– shared segments
– same segment number
• Allocation.
– first fit/best fit
– external fragmentation
![Page 35: Unidade 8: Gerenciamento de Memória](https://reader036.fdocument.pub/reader036/viewer/2022062516/56812b48550346895d8f64f7/html5/thumbnails/35.jpg)
Operating System Concepts Silberschatz and Galvin1999 8.35
Segmentation Architecture (Cont.)
• Protection. With each entry in segment table associate:
– validation bit = 0 illegal segment
– read/write/execute privileges
• Protection bits associated with segments; code sharing occurs at segment level.
• Since segments vary in length, memory allocation is a dynamic storage-allocation problem.
• A segmentation example is shown in the following diagram
![Page 36: Unidade 8: Gerenciamento de Memória](https://reader036.fdocument.pub/reader036/viewer/2022062516/56812b48550346895d8f64f7/html5/thumbnails/36.jpg)
Operating System Concepts Silberschatz and Galvin1999 8.36
Sharing of segments
![Page 37: Unidade 8: Gerenciamento de Memória](https://reader036.fdocument.pub/reader036/viewer/2022062516/56812b48550346895d8f64f7/html5/thumbnails/37.jpg)
Operating System Concepts Silberschatz and Galvin1999 8.37
Segmentation with Paging – MULTICS
• The MULTICS system solved problems of external fragmentation and lengthy search times by paging the segments.
• Solution differs from pure segmentation in that the segment-table entry contains not the base address of the segment, but rather the base address of a page table for this segment.
![Page 38: Unidade 8: Gerenciamento de Memória](https://reader036.fdocument.pub/reader036/viewer/2022062516/56812b48550346895d8f64f7/html5/thumbnails/38.jpg)
Operating System Concepts Silberschatz and Galvin1999 8.38
MULTICS Address Translation Scheme
![Page 39: Unidade 8: Gerenciamento de Memória](https://reader036.fdocument.pub/reader036/viewer/2022062516/56812b48550346895d8f64f7/html5/thumbnails/39.jpg)
Operating System Concepts Silberschatz and Galvin1999 8.39
Segmentation with Paging – Intel 386
• As shown in the following diagram, the Intel 386 uses segmentation with paging for memory management with a two-level paging scheme.
![Page 40: Unidade 8: Gerenciamento de Memória](https://reader036.fdocument.pub/reader036/viewer/2022062516/56812b48550346895d8f64f7/html5/thumbnails/40.jpg)
Operating System Concepts Silberschatz and Galvin1999 8.40
Intel 30386 address translation
![Page 41: Unidade 8: Gerenciamento de Memória](https://reader036.fdocument.pub/reader036/viewer/2022062516/56812b48550346895d8f64f7/html5/thumbnails/41.jpg)
Operating System Concepts Silberschatz and Galvin1999 8.41
Comparing Memory-Management Strategies
• Hardware support
• Performance
• Fragmentation
• Relocation
• Swapping
• Sharing
• Protection