Virtual memory, paging and segmentation · Memória virtual, paging e segmentação
| English | Português |
|---|---|
| pages/ˈpeɪdʒɪz/ | páginas |
| paging/ˈpeɪdʒɪŋ/ | segmentação |
| segmentation/ˌseɡmənˈteɪʃn/ | segmentação |
| virtual address space/ˈvɜːtʃuːəl əˈdres speɪs/ | espaço virtual de endereçamento |
| frames/freɪmz/ | quadros |
| page table/peɪdʒ ˈteɪbl/ | tabela de páginas |
| page fault/peɪdʒ fɒlt/ | falha de página |
| swap file/swɒp faɪl/ | arquivo swap |
| thrashing/ˈθræʃɪŋ/ | thrashing |
The disk light that means the machine has given up
- Open too many applications on a machine short of memory and something distinctive happens. Everything slows almost to a stop, and the disk light stops flickering and stays on.
- The processor is not busy. It is waiting, because the memory each program needs is on the disk, and fetching one page evicts another that is needed a moment later.
- The machine is doing nothing but moving pages. It has enough work and enough memory to do neither.
- This lesson is virtual memory, how paging 分页 and segmentation 分段 provide it, and how the same mechanism that makes memory look bigger can make a machine useless.
A luz do disco que indica que a máquina desistiu
- Abrir muitos aplicativos em uma máquina com pouca memória faz algo distinto acontecer. Tudo fica extremamente lento, e a luz do disco para de piscar e permanece acesa.
- O processador não está ocupado. Ele está esperando, porque a memória que cada programa precisa está no disco, e buscar uma página descarta outra que será necessária um momento depois.
- A máquina não faz nada senão mover páginas. Tem trabalho suficiente e memória suficiente para fazer nenhum dos dois.
- Esta aula é sobre memória virtual, como paginação 分页 e segmentação 分段 a fornecem, e como o mesmo mecanismo que faz a memória parecer maior pode tornar uma máquina inútil.
The virtual address space
- Each process gets its own virtual address space 虚拟地址空间: a clean, contiguous range of addresses starting at zero, which the OS maps to wherever the data really is.
- Three things follow. Each process sees a simple private space and need not know what else is running. Processes are protected from each other, since one cannot name an address in another's space. And the total memory in use can exceed the physical RAM, because part of it lives on disk.
- That isolation is a security boundary as much as a convenience.
O espaço de endereços virtuais
- Cada processo recebe seu próprio espaço de endereços virtuais 虚拟地址空间: uma faixa limpa e contígua de endereços começando em zero, que o SO mapeia para onde os dados realmente estão.
- Três coisas resultam disso. Cada processo vê um espaço privado simples e não precisa saber o que mais está rodando. Os processos são protegidos uns dos outros, pois um não pode nombrar um endereço no espaço de outro. E a memória total em uso pode ultrapassar a RAM física, porque parte dela reside no disco.
- Esse isolamento é tanto uma barreira de segurança quanto uma conveniência.
A benefit of virtual memory is that it: · Um benefício da memória virtual é que ela:
Virtual memory gives each process a private space and lets the working set exceed installed RAM by using disk. · Memória virtual dá a cada processo um espaço privado e permite que o working set exceda a RAM instalada usando disco.
What does giving each process a virtual address space achieve? Select all · todos that apply. · O que o fornecimento de um espaço de endereços virtual para cada processo alcança? Selecione todos que se aplicam.
Virtual memory buys simplicity, isolation and capacity. It costs speed, since part of the memory is really on disk. · Memória virtual compra simplicidade, isolamento e capacidade. Custa velocidade, pois parte da memória realmente está no disco.
Paging
- The virtual space is divided into fixed-size pages 页; physical memory into frames 页框 of the same size. A page table 页表 records which frame currently holds each page.
- When a process uses an address, the hardware looks up the page in the table and finds the frame. If the page is not in RAM, that is a page fault 缺页.
- On a page fault the OS reads the page from the swap file 交换文件 on disk into a free frame. If no frame is free, it must first evict a page, writing it back to disk if it has been changed.
Same-sized pages and frames, joined by a table
Paginação
- O espaço virtual é dividido em páginas 页 de tamanho fixo; a memória física em quadros 页框 do mesmo tamanho. Uma tabela de páginas 页表 registra qual quadro contém atualmente cada página.
- Quando um processo usa um endereço, o hardware consulta a página na tabela e encontra o quadro. Se a página não estiver na RAM, trata-se de uma falta de página 缺页.
- Em uma falta de página, o SO lê a página do arquivo swap 交换文件 no disco para um quadro livre. Se não houver quadro livre, deve primeiro evitar (descartar) uma página, gravando-a de volta no disco se tiver sido alterada.

Páginas e quadros do mesmo tamanho, ligados por uma tabela
In paging, memory is divided into: · No paging, a memória é dividida em:
Paging uses fixed-size pages and frames, linked by a page table. (Variable sizes are segmentation.) · Paging usa páginas e frames de tamanho fixo, ligados por uma tabela de páginas. (Tamanhos variáveis são segmentação.)
A page fault occurs when: · Um page fault ocorre quando:
The accessed page isn't in a frame, so the OS fetches it from the swap file (evicting another page if needed). · A página acessada não está em um frame, então o SO a busca do arquivo swap (evitando outra página se necessário).
Worked example: what happens on a page fault
- A process accesses an address whose page is not in RAM. Describe what the OS does. [4]
- The hardware detects that the page is not present and raises a page fault interrupt, and the process is blocked.
- The OS finds a free frame; if there is none, it selects a page to replace, and writes it back to the swap file if it has been modified.
- It reads the required page from the swap file into that frame and updates the page table.
- The process is returned to the ready state and the instruction is retried. Four steps, four marks, and note the process was blocked throughout.
Exemplo resolvido: o que acontece em uma falta de página
- Um processo acessa um endereço cuja página não está na RAM. Descreva o que o OS faz. [4]
- O hardware detecta que a página não está presente e dispara uma interrupção de falta de página, e o processo fica bloqueado.
- O SO encontra um quadro livre; se não houver nenhum, seleciona uma página para substituir, e grava-a de volta no arquivo swap se tiver sido modificada.
- Lê a página requerida do arquivo swap para esse quadro e atualiza a tabela de páginas.
- O processo retorna ao estado pronto e a instrução é reexecutada. Quatro passos, quatro notas, e note que o processo permaneceu bloqueado durante todo o tempo.
What happens on a page fault · O que acontece em um page fault
Step through a page fault. When the program touches a page that isn't in RAM, the OS quietly fetches it from disk and updates the page table — so the program sees more memory than physically exists. · Passo a passo de um page fault. Quando o programa acessa uma página que não está na RAM, o SO busca silenciosamente do disco e atualiza a tabela de páginas — para que o programa veja mais memória do que fisicamente existe.
Put the OS's response to a page fault in order. · Coloque a resposta do SO a um page fault em ordem.
Detect and block, make room, load, record, retry. A page fault is the normal mechanism, not an error. · Detectar e bloquear, fazer espaço, carregar, registrar, retriar. Um page fault é o mecanismo normal, não um erro.
Thrashing
- Choosing which page to replace matters, because the wrong choice means it will be needed again immediately.
- When there is too little RAM for the working set of the running processes, almost every access causes a page fault, and every fault evicts a page that is wanted again at once.
- The system then spends nearly all its time swapping pages instead of executing instructions. That is thrashing 抖动, or disk thrashing, and it is the state described at the top of this lesson.
- The cure is more RAM, or fewer processes; a faster processor does not help at all, because the processor is not the thing that is busy.
Agitação (Thrashing)
- Escolher qual página substituir importa, porque a escolha errada significa que ela será necessária novamente imediatamente.
- Quando há pouca RAM para o conjunto ativo dos processos em execução, quase todo acesso causa uma falta de página, e toda falta descarta uma página que é desejada novamente instantaneamente.
- O sistema então gasta quase todo seu tempo trocando páginas em vez de executar instruções. Isso é agitação 抖动, ou agitação de disco, e é o estado descrito no início desta aula.
- A cura é mais RAM, ou menos processos; um processador mais rápido não ajuda em nada, porque o processador não é o que está ocupado.
A machine slows almost to a stop and the disk runs constantly. What will fix it? · Uma máquina quase para e o disco roda constantemente. O que corrigiria isso?
This is thrashing: nearly every access faults and the processor waits. The processor is not the busy component, so speeding it up changes nothing. · Isso é thrashing: quase todo acesso falha e o processador espera. O processador não é o componente ocupado, então acelerá-lo não muda nada.
Segmentation
- Segmentation divides memory into variable-sized logical segments that match the program's own structure: the code, the stack, the heap, a large data array.
- Because a segment is a logical unit, it can carry its own permissions: the code segment can be read-only and executable, the stack read-write and not executable.
- The contrast the exam wants: pages are fixed-size and have no meaning to the program; segments are variable-sized and correspond to logical parts of it. Many real systems combine the two, paging within segments.
Segments are the program's own parts, not equal slices
Segmentação
- Segmentação divide a memória em segmentos lógicos de tamanho variável que correspondem à própria estrutura do programa: o código, a pilha, a heap, um grande array de dados.
- Como um segmento é uma unidade lógica, pode carregar suas próprias permissões: o segmento de código pode ser apenas leitura e executável, a pilha leitura/escrita e não executável.
- O contraste que o exame quer: páginas têm tamanho fixo e não têm significado para o programa; segmentos têm tamanho variável e correspondem às partes lógicas dele. Muitos sistemas reais combinam os dois, paginando dentro de segmentos.

Segmentos são as próprias partes do programa, não fatias iguais
Match each memory-management term to its meaning. · Combine cada termo de gerenciamento de memória com seu significado.
Paging = fixed pages; segmentation = logical variable units; a page fault triggers a swap; too many faults = thrashing. · Paging = páginas fixas; segmentação = unidades lógicas variáveis; um page fault aciona uma troca; muitas falhas = thrashing.
Segmentation divides memory into variable-sized logical units (code, stack, heap), each with its own permissions, whereas paging uses fixed-size pages. · Segmentação divide a memória em unidades lógicas de tamanho variável (código, pilha, heap), cada uma com suas próprias permissões, enquanto paging usa páginas de tamanho fixo.
Segments match the program's logical structure; pages are uniform fixed-size blocks — some systems combine both. · Segments correspondem à estrutura lógica do programa; páginas são blocos uniformes de tamanho fixo — alguns sistemas combinam ambos.
Unlike pages, which are all the same size, segments are of ____ size and match the program's logical parts. · Diferente das páginas, que são todas do mesmo tamanho, os segmentos são de tamanho ____ e correspondem às partes lógicas do programa.
A segment is the code, the stack or the heap, so it can carry its own permissions. A page is a physical division with no meaning to the program. · Um segmento é o código, a pilha ou o heap, então pode ter suas próprias permissões. Uma página é uma divisão física sem significado para o programa.
Worked example: paging against segmentation
- State two differences between paging and segmentation. [2]
- Pages are all of a fixed size, decided by the system; segments are of variable size, decided by the logical parts of the program.
- A page is a purely physical division with no meaning to the program; a segment corresponds to a logical unit such as the code or the stack, and can be given its own access permissions.
- A third if needed: paging can leave unused space inside the last page of an allocation, while segmentation leaves gaps of unusable space between segments.
Exemplo resolvido: paginação contra segmentação
- Cite duas diferenças entre paginação e segmentação. [2]
- Páginas são todas de tamanho fixo, decidido pelo sistema; segmentos são de tamanho variável, decidido pelas partes lógicas do programa.
- Uma página é uma divisão puramente física sem significado para o programa; um segmento corresponde a uma unidade lógica como o código ou a pilha, e pode receber suas próprias permissões de acesso.
- Uma terceira, se necessário: a paginação pode deixar espaço não utilizado dentro da última página de uma alocação, enquanto a segmentação deixa lacunas de espaço inutilizável entre os segmentos.
Marks that slip away
- Virtual memory does not create memory. It lets the total in use exceed physical RAM by keeping part of it on disk, at the cost of disk accesses.
- A page fault is not an error. It is the normal mechanism by which a page is brought in.
- Thrashing is spending more time swapping than executing, and the fix is more RAM or fewer processes, never a faster processor.
- Fixed size versus variable size, logically meaningful is the difference between paging and segmentation. Say both halves.
Marcas que escapam
- A memória virtual não cria memória. Ela permite que o total em uso ultrapasse a RAM física mantendo parte dela no disco, custando acessos ao disco.
- Uma falta de página não é um erro. É o mecanismo normal pelo qual uma página é trazida.
- Agitação é gastar mais tempo trocando do que executando, e a solução é mais RAM ou menos processos, nunca um processador mais rápido.
- Tamanho fixo versus tamanho variável, logicamente significativo é a diferença entre paginação e segmentação. Cite ambas as metades.
You've got it
- a virtual address space gives each process a private contiguous range, protects processes from each other, and lets memory in use exceed physical RAM
- paging: fixed-size pages mapped to frames by a page table; a page fault blocks the process while the OS evicts a page if necessary, loads from the swap file, updates the table and retries
- thrashing is more time spent swapping than executing; cure it with more RAM or fewer processes
- segmentation uses variable-sized segments matching the program's logical parts, each with its own permissions; many systems page within segments
Entendeu?
- um espaço de endereços virtuais dá a cada processo uma faixa privada contígua, protege processos uns dos outros e permite que a memória em uso ultrapasse a RAM física
- paginação: páginas de tamanho fixo mapeadas para quadros por uma tabela de páginas; uma falta de página bloqueia o processo enquanto o OS evita uma página se necessário, carrega do arquivo swap, atualiza a tabela e retry
- agitação é mais tempo gasto trocando do que executando; cure com mais RAM ou menos processos
- segmentação usa segmentos de tamanho variável correspondentes às partes lógicas do programa, cada um com suas próprias permissões; muitos sistemas paginam dentro de segmentos