Главная » Просмотр файлов » Volume 3A System Programming Guide_ Part 1

Volume 3A System Programming Guide_ Part 1 (794103), страница 36

Файл №794103 Volume 3A System Programming Guide_ Part 1 (Intel and AMD manuals) 36 страницаVolume 3A System Programming Guide_ Part 1 (794103) страница 362019-04-28СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

Текст из файла (страница 36)

(This flag does not affect the granularity of thebase address; it is always byte granular.) When the granularityflag is set, the twelve least significant bits of an offset are nottested when checking the offset against the segment limit. Forexample, when the granularity flag is set, a limit of 0 results invalid offsets from 0 to 4095.L (64-bit code segment) flagIn IA-32e mode, bit 21 of the second doubleword of the segmentdescriptor indicates whether a code segment contains native 64-bitcode.

A value of 1 indicates instructions in this code segment areexecuted in 64-bit mode. A value of 0 indicates the instructions in thiscode segment are executed in compatibility mode. If L-bit is set, thenD-bit must be cleared. When not in IA-32e mode or for non-codesegments, bit 21 is reserved and should always be set to 0.Available and reserved bitsBit 20 of the second doubleword of the segment descriptor is availablefor use by system software.3.4.5.1Code- and Data-Segment Descriptor TypesWhen the S (descriptor type) flag in a segment descriptor is set, the descriptor is foreither a code or a data segment. The highest order bit of the type field (bit 11 of thesecond double word of the segment descriptor) then determines whether thedescriptor is for a data segment (clear) or a code segment (set).For data segments, the three low-order bits of the type field (bits 8, 9, and 10) areinterpreted as accessed (A), write-enable (W), and expansion-direction (E).

SeeTable 3-1 for a description of the encoding of the bits in the type field for code anddata segments. Data segments can be read-only or read/write segments, dependingon the setting of the write-enable bit.3-16 Vol. 3PROTECTED-MODE MEMORY MANAGEMENTTable 3-1. Code- and Data-Segment TypesType FieldDecimal1110E9W8A0123456700000000000011110011001101010101DescriptorTypeDataDataDataDataDataDataDataDataDescriptionRead-OnlyRead-Only, accessedRead/WriteRead/Write, accessedRead-Only, expand-downRead-Only, expand-down, accessedRead/Write, expand-downRead/Write, expand-down, accessed8910111213141511111111CRA000011110011001101010101CodeCodeCodeCodeCodeCodeCodeCodeExecute-OnlyExecute-Only, accessedExecute/ReadExecute/Read, accessedExecute-Only, conformingExecute-Only, conforming, accessedExecute/Read-Only, conformingExecute/Read-Only, conforming,accessedStack segments are data segments which must be read/write segments.

Loading theSS register with a segment selector for a nonwritable data segment generates ageneral-protection exception (#GP). If the size of a stack segment needs to bechanged dynamically, the stack segment can be an expand-down data segment(expansion-direction flag set). Here, dynamically changing the segment limit causesstack space to be added to the bottom of the stack.

If the size of a stack segment isintended to remain static, the stack segment may be either an expand-up or expanddown type.The accessed bit indicates whether the segment has been accessed since the lasttime the operating-system or executive cleared the bit. The processor sets this bitwhenever it loads a segment selector for the segment into a segment register,assuming that the type of memory that contains the segment descriptor supportsprocessor writes. The bit remains set until explicitly cleared. This bit can be used bothfor virtual memory management and for debugging.For code segments, the three low-order bits of the type field are interpreted asaccessed (A), read enable (R), and conforming (C).

Code segments can be execute-Vol. 3 3-17PROTECTED-MODE MEMORY MANAGEMENTonly or execute/read, depending on the setting of the read-enable bit. Anexecute/read segment might be used when constants or other static data have beenplaced with instruction code in a ROM. Here, data can be read from the code segmenteither by using an instruction with a CS override prefix or by loading a segmentselector for the code segment in a data-segment register (the DS, ES, FS, or GSregisters). In protected mode, code segments are not writable.Code segments can be either conforming or nonconforming. A transfer of executioninto a more-privileged conforming segment allows execution to continue at thecurrent privilege level.

A transfer into a nonconforming segment at a different privilege level results in a general-protection exception (#GP), unless a call gate or taskgate is used (see Section 4.8.1, “Direct Calls or Jumps to Code Segments”, for moreinformation on conforming and nonconforming code segments). System utilities thatdo not access protected facilities and handlers for some types of exceptions (such as,divide error or overflow) may be loaded in conforming code segments. Utilities thatneed to be protected from less privileged programs and procedures should be placedin nonconforming code segments.NOTEExecution cannot be transferred by a call or a jump to a lessprivileged (numerically higher privilege level) code segment,regardless of whether the target segment is a conforming or nonconforming code segment.

Attempting such an execution transfer willresult in a general-protection exception.All data segments are nonconforming, meaning that they cannot be accessed by lessprivileged programs or procedures (code executing at numerically high privilegelevels). Unlike code segments, however, data segments can be accessed by moreprivileged programs or procedures (code executing at numerically lower privilegelevels) without using a special access gate.If the segment descriptors in the GDT or an LDT are placed in ROM, the processor canenter an indefinite loop if software or the processor attempts to update (write to) theROM-based segment descriptors.

To prevent this problem, set the accessed bits forall segment descriptors placed in a ROM. Also, remove operating-system or executivecode that attempts to modify segment descriptors located in ROM.3.5SYSTEM DESCRIPTOR TYPESWhen the S (descriptor type) flag in a segment descriptor is clear, the descriptor typeis a system descriptor. The processor recognizes the following types of systemdescriptors:•••Local descriptor-table (LDT) segment descriptor.Task-state segment (TSS) descriptor.Call-gate descriptor.3-18 Vol.

3PROTECTED-MODE MEMORY MANAGEMENT•••Interrupt-gate descriptor.Trap-gate descriptor.Task-gate descriptor.These descriptor types fall into two categories: system-segment descriptors and gatedescriptors. System-segment descriptors point to system segments (LDT and TSSsegments). Gate descriptors are in themselves “gates,” which hold pointers to procedure entry points in code segments (call, interrupt, and trap gates) or which holdsegment selectors for TSS’s (task gates).Table 3-2 shows the encoding of the type field for system-segment descriptors andgate descriptors. Note that system descriptors in IA-32e mode are 16 bytes insteadof 8 bytes.Table 3-2.

System-Segment and Gate-Descriptor TypesType FieldDescriptionDecimal11109832-Bit ModeIA-32e Mode00000ReservedUpper 8 byte of an 16byte descriptor1000116-bit TSS (Available)Reserved20010LDTLDT3001116-bit TSS (Busy)Reserved4010016-bit Call GateReserved50101Task GateReserved6011016-bit Interrupt GateReserved7011116-bit Trap GateReserved81000ReservedReserved9100132-bit TSS (Available)64-bit TSS (Available)101010ReservedReserved11101132-bit TSS (Busy)64-bit TSS (Busy)12110032-bit Call Gate64-bit Call Gate131101ReservedReserved14111032-bit Interrupt Gate64-bit Interrupt Gate15111132-bit Trap Gate64-bit Trap GateSee also: Section 3.5.1, “Segment Descriptor Tables”, and Section 6.2.2, “TSSDescriptor” (for more information on the system-segment descriptors); see SectionVol.

3 3-19PROTECTED-MODE MEMORY MANAGEMENT4.8.3, “Call Gates”, Section 5.11, “IDT Descriptors”, and Section 6.2.5, “Task-GateDescriptor” (for more information on the gate descriptors).3.5.1Segment Descriptor TablesA segment descriptor table is an array of segment descriptors (see Figure 3-10). Adescriptor table is variable in length and can contain up to 8192 (213) 8-byte descriptors.

There are two kinds of descriptor tables:••The global descriptor table (GDT)The local descriptor tables (LDT)TIGlobalDescriptorTable (GDT)LocalDescriptorTable (LDT)TI = 0TI = 1SegmentSelectorFirst Descriptor inGDT is Not Used5656484840403232242416168800GDTR RegisterLDTR RegisterLimitBase AddressLimitBase AddressSeg. Sel.Figure 3-10. Global and Local Descriptor TablesEach system must have one GDT defined, which may be used for all programs andtasks in the system. Optionally, one or more LDTs can be defined. For example, an3-20 Vol. 3PROTECTED-MODE MEMORY MANAGEMENTLDT can be defined for each separate task being run, or some or all tasks can sharethe same LDT.The GDT is not a segment itself; instead, it is a data structure in linear address space.The base linear address and limit of the GDT must be loaded into the GDTR register(see Section 2.4, “Memory-Management Registers”).

The base addresses of the GDTshould be aligned on an eight-byte boundary to yield the best processor performance. The limit value for the GDT is expressed in bytes. As with segments, the limitvalue is added to the base address to get the address of the last valid byte. A limitvalue of 0 results in exactly one valid byte. Because segment descriptors are always8 bytes long, the GDT limit should always be one less than an integral multiple ofeight (that is, 8N – 1).The first descriptor in the GDT is not used by the processor. A segment selector tothis “null descriptor” does not generate an exception when loaded into a datasegment register (DS, ES, FS, or GS), but it always generates a general-protectionexception (#GP) when an attempt is made to access memory using the descriptor. Byinitializing the segment registers with this segment selector, accidental reference tounused segment registers can be guaranteed to generate an exception.The LDT is located in a system segment of the LDT type.

The GDT must contain asegment descriptor for the LDT segment. If the system supports multiple LDTs, eachmust have a separate segment selector and segment descriptor in the GDT. Thesegment descriptor for an LDT can be located anywhere in the GDT. See Section 3.5,“System Descriptor Types”, information on the LDT segment-descriptor type.An LDT is accessed with its segment selector. To eliminate address translations whenaccessing the LDT, the segment selector, base linear address, limit, and access rightsof the LDT are stored in the LDTR register (see Section 2.4, “Memory-ManagementRegisters”).When the GDTR register is stored (using the SGDT instruction), a 48-bit “pseudodescriptor” is stored in memory (see top diagram in Figure 3-11). To avoid alignmentcheck faults in user mode (privilege level 3), the pseudo-descriptor should be locatedat an odd word address (that is, address MOD 4 is equal to 2).

Характеристики

Тип файла
PDF-файл
Размер
3,12 Mb
Материал
Тип материала
Высшее учебное заведение

Список файлов книги

Свежие статьи
Популярно сейчас
Как Вы думаете, сколько людей до Вас делали точно такое же задание? 99% студентов выполняют точно такие же задания, как и их предшественники год назад. Найдите нужный учебный материал на СтудИзбе!
Ответы на популярные вопросы
Да! Наши авторы собирают и выкладывают те работы, которые сдаются в Вашем учебном заведении ежегодно и уже проверены преподавателями.
Да! У нас любой человек может выложить любую учебную работу и зарабатывать на её продажах! Но каждый учебный материал публикуется только после тщательной проверки администрацией.
Вернём деньги! А если быть более точными, то автору даётся немного времени на исправление, а если не исправит или выйдет время, то вернём деньги в полном объёме!
Да! На равне с готовыми студенческими работами у нас продаются услуги. Цены на услуги видны сразу, то есть Вам нужно только указать параметры и сразу можно оплачивать.
Отзывы студентов
Ставлю 10/10
Все нравится, очень удобный сайт, помогает в учебе. Кроме этого, можно заработать самому, выставляя готовые учебные материалы на продажу здесь. Рейтинги и отзывы на преподавателей очень помогают сориентироваться в начале нового семестра. Спасибо за такую функцию. Ставлю максимальную оценку.
Лучшая платформа для успешной сдачи сессии
Познакомился со СтудИзбой благодаря своему другу, очень нравится интерфейс, количество доступных файлов, цена, в общем, все прекрасно. Даже сам продаю какие-то свои работы.
Студизба ван лав ❤
Очень офигенный сайт для студентов. Много полезных учебных материалов. Пользуюсь студизбой с октября 2021 года. Серьёзных нареканий нет. Хотелось бы, что бы ввели подписочную модель и сделали материалы дешевле 300 рублей в рамках подписки бесплатными.
Отличный сайт
Лично меня всё устраивает - и покупка, и продажа; и цены, и возможность предпросмотра куска файла, и обилие бесплатных файлов (в подборках по авторам, читай, ВУЗам и факультетам). Есть определённые баги, но всё решаемо, да и администраторы реагируют в течение суток.
Маленький отзыв о большом помощнике!
Студизба спасает в те моменты, когда сроки горят, а работ накопилось достаточно. Довольно удобный сайт с простой навигацией и огромным количеством материалов.
Студ. Изба как крупнейший сборник работ для студентов
Тут дофига бывает всего полезного. Печально, что бывают предметы по которым даже одного бесплатного решения нет, но это скорее вопрос к студентам. В остальном всё здорово.
Спасательный островок
Если уже не успеваешь разобраться или застрял на каком-то задание поможет тебе быстро и недорого решить твою проблему.
Всё и так отлично
Всё очень удобно. Особенно круто, что есть система бонусов и можно выводить остатки денег. Очень много качественных бесплатных файлов.
Отзыв о системе "Студизба"
Отличная платформа для распространения работ, востребованных студентами. Хорошо налаженная и качественная работа сайта, огромная база заданий и аудитория.
Отличный помощник
Отличный сайт с кучей полезных файлов, позволяющий найти много методичек / учебников / отзывов о вузах и преподователях.
Отлично помогает студентам в любой момент для решения трудных и незамедлительных задач
Хотелось бы больше конкретной информации о преподавателях. А так в принципе хороший сайт, всегда им пользуюсь и ни разу не было желания прекратить. Хороший сайт для помощи студентам, удобный и приятный интерфейс. Из недостатков можно выделить только отсутствия небольшого количества файлов.
Спасибо за шикарный сайт
Великолепный сайт на котором студент за не большие деньги может найти помощь с дз, проектами курсовыми, лабораторными, а также узнать отзывы на преподавателей и бесплатно скачать пособия.
Популярные преподаватели
Добавляйте материалы
и зарабатывайте!
Продажи идут автоматически
6418
Авторов
на СтудИзбе
307
Средний доход
с одного платного файла
Обучение Подробнее