Lecture
If several independent programs can be in memory at the same time, special measures are needed to prevent or limit the access of one program to memory areas used by other programs. A similar problem arises when executing individual modules of large programs. Causes of unauthorized access to foreign areas of memory can be the sudden termination of the program execution by the processor as a result of a malfunction in the hardware of the computer, entry into an infinite command cycle, errors in the user program, especially when debugging it. The consequences of such failures in a normally functioning computer are especially dangerous if the programs of the operating system are destroyed, since after that the computer system may begin to behave unpredictably.
In order to prevent the destruction of some programs by others, it is sufficient to protect the memory area of this program from attempts to write to it by other programs, and in some cases its program ( write protection ). In this case, other programs can access this area of memory for reading data.
In other cases, for example, with restrictions on access to information stored in the system, it is necessary to be able to prohibit other programs to perform both writing and reading in this memory area. This write and read protection helps debug the program. At the same time, each case of exit from the memory area of its program is monitored.
To facilitate the debugging of programs, it is desirable to identify such typical errors in programs as attempts to use data instead of commands (or vice versa) in your own program, although these errors may not destroy information.
The following options for differentiated protection during various operations with memory can be distinguished:
· Sets the relation to the memory area of another program, which determines whether memory protection applies only to a write operation or to any access to memory.
· One of the following relations to the memory area of the own program is set:
- access to this block is allowed both for writing and reading;
- read only allowed;
- Any type of address is allowed, but at an address taken only from the program counter;
- it is allowed to contact the address from any register, except for the command counter.
If the memory protection is violated, the execution of the program is suspended and the interrupt request for a memory protection violation is generated.
Protection against intrusion of a program into foreign memory areas can be organized in various ways. At the same time, the implementation of protection should not significantly reduce the performance of the processor and require too large hardware costs. Consider the most common ways to implement memory protection.
In small control computing devices operating, for example, as part of an automated process control system, it is necessary to ensure that new programs can be debugged in parallel with the functioning of the working programs that control the technological process. This can be achieved by allocating a special kind of protection in each memory cell. Setting 1 to this digit prohibits writing to this cell. This is the so-called control discharge method.
In systems with multiprogramming and memory segmentation, it is not individual cells that are protected, but memory areas or blocks into which the memory is divided. At the same time, it is often envisaged that for various programs it is possible to specify various permissible modes of access to particular areas or blocks of memory (segments).
The idea of the method is to introduce two boundary registers indicating the upper and lower boundaries of the memory area where the program has access rights. The scheme of functioning of such a protection system is shown in fig. 16.15.
Fig.23.1. Memory Protection with Boundary Registers
Each time a memory is accessed, it is checked whether the address being used is within the specified limits. When going beyond the boundaries, memory access is suppressed and an interrupt request is generated that transfers control to the operating system. The content of the boundary registers is set by the operating system before the next active program begins an active cycle. If a base register is used for dynamic memory allocation, it simultaneously determines the lower limit. The upper bound is calculated by the operating system in accordance with the length of the program in the OP.
Thus, the considered method allows you to prevent the program from leaving the memory zone allocated to it, which is convenient for solving small problems in the linear addressing mode within a segment, i.e. when the executable program is entirely included in the OP segment and is located in consecutive addresses of a single memory area.
Compared to the previous, this method is more flexible. It allows organizing program access to non-consecutive memory areas.
Memory is logically divided into blocks. Each block of memory is assigned a code called a memory protection key . In addition, each program participating in multiprogramming is assigned a program key code . The program's access to this block of memory for reading and writing is allowed if the keys match or one of them has the code 0.
The method of security keys does not exclude the use of the check digit method to protect individual memory cells and the boundary register method to protect individual memory zones. In modern computers, these methods are often used together and closely intertwined.
Let us consider very briefly the memory protection methods used in computing systems built on the basis of the I80386 microprocessor. The memory blocks to be protected in such systems are segments and pages . The protection system is based on the principles widely used in microprocessors, namely:
- Check access attributes (security keys) before providing the ability to access memory.
- The ring structure of hierarchical levels of privilege (priorities), organized in such a way as to prevent distortion of the most important programs located in the center, errors that occur at external levels where the probability of their occurrence is highest. The mechanism based on privilege levels provides sufficiently reliable protection. At the same time, the privilege level of the task is equal to the privilege level of the currently active program segment or active page.
The descriptor of a segment or page includes a bit field that defines one of the four permissible privilege levels for the corresponding segment (Figure 16.3). The zero level is the most privileged, i.e. with the most limited access to a segment or page. Privilege level 3 is the lowest and characterizes the most accessible segment or page. Programs can have access to data or program segments only with the same level of privileges or with less limited access (that is, with higher privilege level numbers).
Using these four levels of protection and a system for checking access attributes in a processor, multitasking is organized by separating programs from each other and from the operating system. The protection mechanism prevents an emergency situation in any program in the event of a system failure. The memory protection system using task-custom attributes and priority levels used in the I80386 processor can be represented by the circuit shown in Fig. 16.16.
Fig.23.2. Computer memory protection system on I80386 processor
The functioning of the depicted structure can be illustrated by the following example. Let the data be stored at P = 2. Then access to them is possible for programs that are at levels P = 2, 1 or 0. For programs with P = 3, they are not available. Similarly, an application service program with P = 2 may be caused by segments or procedures that are at the P = 2, 1, or 0 levels, but not at the P = 3 level.
Above, we talked about direct access to data or programs. However, the CALL command can call program segments with a higher privilege level than the current program, using specially set entry points. These entry points are called call gateways.
Thus, a less privileged procedure can call a more privileged one by accessing it via the call gateway handle that defines the available entry point. This treatment method was also used in the I80286 and I80486 processors. It allows user programs to access the OS for maintenance. In this case, only certain procedures are allowed, which are authorized by the introduction of an appropriate gateway into the system. This eliminates the possibility of unauthorized treatment of less privileged procedures to more privileged ones, which allows them to be protected from possible distortions.
The on-chip hardware implementation of the hierarchical memory protection mechanism and the access attribute verification provided as part of the operating system prevent the vast majority of emergencies (according to one of the estimates in the literature, up to 95% of failures occurring in multi-user multi-tasking systems due to incorrect work with memory).
We will consider a two-level memory with page organization, consisting of operational (upper level) and external (lower level) memories. If during the execution of the program it is found that the page with the necessary data (operands, a piece of the program) is not in the upper level memory, it is transferred there from the lower level memory. If at the same time there is no free space for it in the upper level memory, then it replaces one of the pages located in the OP. At the same time, if a record was made to the page being replaced during its stay in the PD, then it should be transferred to the lower level memory (it will replace its outdated copy).
These operations of transferring information between memory levels cause processor downtime and, consequently, loss of performance of the computing system, so you should strive to reduce the number of such operations during program execution. It is obvious that the number of these information exchange operations depends on what information is sent from the upper level memory, since this information can be accessed during the further execution of the program.
We give a formalized model of the process of information exchange between the upper and lower levels of memory. Let the program together with the source data consist of k pages, which are assigned numbers 1, 2, ..., k, then the program can be viewed as a set of pages:
Q = {1,2, ..., k}.
All pages of the program are permanently stored in the memory of the lower level, and, in addition, r of them may be in the memory of the upper level (RAM), while
1 <r <k.
The execution of the program generates a sequence of calls to memory pages. We consider this sequence as the implementation of a random process:
q 0 , q 1 , q 2 , ..., q t ,
where q t is a discrete random variable that takes at the time t the value of one of the program page numbers (q t Î Q).
If S t is the set of pages in the top-level memory at the moment t, and at any moment there are r pages of the program in this memory, then the change in the state of the top-level memory after turning q t is described by the following relations:
.
In the first case, the appeal is made to the page that is in the memory of the upper level, and therefore the state of this memory does not change.
In the second case, a page that is not in the top-level memory is accessed. This situation is called a page fault, since the program can no longer be executed until the desired page q t is copied from the lower level memory to the upper level memory, which is associated with a loss of time. Since there is no free space in the upper level memory, it is necessary to delete some page v t from it so that the page q t can be placed in its place. If during the stay of the page v t in the upper level memory it was recorded, this page should be overwritten into the lower level memory when it is replaced. Such a procedure is called the process of replacing pages, and the rule according to which, when a page fault occurs, the page v t Î S t is selected for deletion from the upper memory level is replaced by the replacement algorithm.
For this program, which generates a certain flow of memory accesses, there is at least one such sequence of page replacements, which gives the minimum number of page failures for this program — the minimum possible sequence of substitutions. When constructing a replacement algorithm, they strive to bring the sequence of substitutions implemented by this algorithm to the minimum.
Optimization of the process of replacing pages is simplified if it is known in what order in the future there will be memory accesses or, at least, the probability of future accesses to individual pages of the program. It is clear, for example, that, first of all, a page should be deleted from the memory of the upper level, to which there will be no more calls (the probability of future calls is 0).
The difficulty is that, as a rule, when executing a program, there is no information about the flow of hits or any reliable information about the likelihood of hits to individual pages at future points in time.
Replacement algorithms can be divided into two groups:
Although the first group of algorithms cannot be applied in practice, they play an important role in the theory of substitution algorithms, allowing you to make estimates (including experimental ones) to what extent the characteristics of heuristic algorithms approach the maximum possible optimal ones.
Physically unrealizable algorithms
The Mikhnovsky-Shor algorithm. Each time a page is replaced from the upper level memory, the page is sent to the lower level memory, the next call to which will occur later than to any other page in the upper level memory.
The following sentence is valid. The number of page replacements in the upper level memory (the number of page faults) when performing substitutions according to the Mikhnovsky-Shor algorithm is minimal for a given circulation flow and initial memory allocation, which has theoretical proof.
Thus, the Mikhnovsky-Shor algorithm implements the minimum possible sequence of substitutions for this program, so this algorithm is called the MIN-algorithm.
If we agree that the probability of accessing individual pages of a program is known, then the OPT algorithm is optimal in terms of the minimum of the average number of page faults: every time a page is replaced, the page is sent from the upper level memory, the probability of which is not more than any other page in this memory.
Physically Realizable (Heuristic) Substitution Algorithms
A number of algorithms of this class have been proposed.
Random substitution algorithm (SZ-algorithm). If a page fault occurs from the top-level memory, any of the pages located there is equally likely to be sent.
NDI algorithm. From the top-level memory, the page most recently used is sent.
The algorithm "first come - first gone" (PPPU-algorithm). A page that has been stored in the upper memory level longer than others is sent.
Algorithm "last came - first left". A page is sent later than the others to the top level memory.
The following two algorithms have certain properties of adaptation to the flow of memory accesses.
Algorithm "climbing page" (KS-algorithm). Pages in the top level memory form a sequence:
.
At the next access of q t to memory, this sequence changes according to the rule:
When referring to the page j m present in the memory of the upper level, the latter changes places with the next page to the left, in other words, "climbs" to the beginning of the sequence, away from its end, where the replacement occurs during page fault. This process is illustrated in Figure 2. 23.3.
Fig.23.3. Replacement Algorithm ”Climbing Page”
Algorithm "working set" (RK-algorithm). Pages in the upper level memory that have been used for a given time interval form a “work package”. Pages from this memory that are not included in the "working set" form two queues of candidates for replacement:
- the queue of pages that have not been changed, while they were present in the memory of the upper level;
- the queue of pages in which changes were made.
Replacement in case of a page failure is made according to the rule: the first one comes from the working set - the first one leaves the top level memory . In this case, the first page should be replaced. The described algorithm was used in IBM-360/370 computers.
Предположим, что последовательность обращений q 1 , q 2 , …, q t соответствует последовательности независимых случайных дискретных величин, таких что
, , .
Примем за состояние процесса замещения набор (а в некоторых случаях упорядоченную последовательность) страниц, находящихся в памяти верхнего уровня. Тогда для ряда алгоритмов замещения (СЗ, НДИ, ПППУ и некоторых других) процесс изменения состояния верхнего уровня описывается однородной конечной эргодической цепью Маркова, что указывает на существование стационарных вероятностей пребывания процесса в определенных состояниях и, как следствие этого, стационарных вероятностей страничных сбоев.
В качестве критерия эффективности W r,k алгоритма замещения А примем стационарную вероятность страничных сбоев:
.
Можно для ряда алгоритмов замещения найти зависимость W r,k от p 1 , p 2 , …, p k и сравнить алгоритмы между собой, а также с физически нереализуемым ОПТ-алгоритмом. Определить W r,k для ряда алгоритмов можно, используя метод, основанный на однородных эргодических цепях Маркова.
Описанные выше эвристические алгоритмы замещения страниц и их различные комбинации лежат в основе алгоритмов замещения, используемых в современных ЭВМ. При этом конкретные технические реализации алгоритмов замещения страниц весьма сложные и сильно зависят от конкретной конфигурации аппаратных средств, типа операционной системы и даже ее модификации. Следует отметить только, что в большинстве случаев алгоритмы замещения страниц в современных ЭВМ содержат механизмы упреждающей выборки страниц. Идея использования упреждающей загрузки страниц из ВП в ОП, как и в случае обновления блоков в кэш-памяти, основана на предположении о том, что при очередном страничном сбое обращение с большой вероятностью произойдет к следующей по порядку странице, уже находящейся в ОП. Кроме того, перемещение модифицированных страниц из ОП в ВП осуществляется в большинстве случаев через кэшированную часть ОП (дисковый кэш), поскольку велика вероятность обращения к недавно удаленной странице. Такой механизм позволяет ускорить процесс подкачки страниц при повторном обращении.
1. Options for differentiated protection during various operations with memory.
2. Protection of individual memory cells.
3. The method of boundary registers.
4. Key protection method.
5. Computer memory protection system on the I80386 processor.
6. Algorithms for managing multi-level memory.
7. Physically realizable (heuristic) substitution algorithms.
Comments
To leave a comment
Computer circuitry and computer architecture
Terms: Computer circuitry and computer architecture