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

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

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

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

An entry is read from thesystem descriptor table (GDT or LDT) and is loaded in the hidden portion of thesegment descriptor register. The descriptor-register base, limit, and attribute fieldsare all loaded. However, the contents of the data and stack segment selector and thedescriptor registers are ignored.When FS and GS segment overrides are used in 64-bit mode, their respective baseaddresses are used in the linear address calculation: (FS or GS).base + index +displacement. FS.base and GS.base are then expanded to the full linear-address sizesupported by the implementation.

The resulting effective address calculation canwrap across positive and negative addresses; the resulting linear address must becanonical.In 64-bit mode, memory accesses using FS-segment and GS-segment overrides arenot checked for a runtime limit nor subjected to attribute-checking. Normal segmentloads (MOV to Sreg and POP Sreg) into FS and GS load a standard 32-bit base valuein the hidden portion of the segment descriptor register. The base address bits abovethe standard 32 bits are cleared to 0 to allow consistency for implementations thatuse less than 64 bits.The hidden descriptor register fields for FS.base and GS.base are physically mappedto MSRs in order to load all address bits supported by a 64-bit implementation.

Software with CPL = 0 (privileged software) can load all supported linear-address bitsinto FS.base or GS.base using WRMSR. Addresses written into the 64-bit FS.base andGS.base registers must be in canonical form. A WRMSR instruction that attempts towrite a non-canonical address to those registers causes a #GP fault.When in compatibility mode, FS and GS overrides operate as defined by 32-bit modebehavior regardless of the value loaded into the upper 32 linear-address bits of thehidden descriptor register base field. Compatibility mode ignores the upper 32 bitswhen calculating an effective address.A new 64-bit mode instruction, SWAPGS, can be used to load GS base.

SWAPGSexchanges the kernel data structure pointer from the IA32_KernelGSbase MSR withthe GS base register. The kernel can then use the GS prefix on normal memory references to access the kernel data structures. An attempt to write a non-canonical value(using WRMSR) to the IA32_KernelGSBase MSR causes a #GP fault.3-12 Vol. 3PROTECTED-MODE MEMORY MANAGEMENT3.4.5Segment DescriptorsA segment descriptor is a data structure in a GDT or LDT that provides the processorwith the size and location of a segment, as well as access control and status information. Segment descriptors are typically created by compilers, linkers, loaders, or theoperating system or executive, but not application programs.

Figure 3-8 illustratesthe general descriptor format for all types of segment descriptors.3124 23 22 21 20 19Base 31:24DAG / L VBL3116 15 14 13 12 11Seg.Limit19:16PDPLS08 7TypeBase 23:1616 15Base Address 15:0040Segment Limit 15:000L— 64-bit code segment (IA-32e mode only)AVL — Available for use by system softwareBASE — Segment base addressD/B — Default operation size (0 = 16-bit segment; 1 = 32-bit segment)DPL — Descriptor privilege levelG— GranularityLIMIT — Segment LimitP— Segment presentS— Descriptor type (0 = system; 1 = code or data)TYPE — Segment typeFigure 3-8. Segment DescriptorThe flags and fields in a segment descriptor are as follows:Segment limit fieldSpecifies the size of the segment. The processor puts together thetwo segment limit fields to form a 20-bit value.

The processor interprets the segment limit in one of two ways, depending on the settingof the G (granularity) flag:•If the granularity flag is clear, the segment size can range from1 byte to 1 MByte, in byte increments.•If the granularity flag is set, the segment size can range from4 KBytes to 4 GBytes, in 4-KByte increments.The processor uses the segment limit in two different ways,depending on whether the segment is an expand-up or an expanddown segment. See Section 3.4.5.1, “Code- and Data-SegmentDescriptor Types”, for more information about segment types. Forexpand-up segments, the offset in a logical address can range from 0Vol. 3 3-13PROTECTED-MODE MEMORY MANAGEMENTto the segment limit. Offsets greater than the segment limit generategeneral-protection exceptions (#GP).

For expand-down segments,the segment limit has the reverse function; the offset can range fromthe segment limit to FFFFFFFFH or FFFFH, depending on the setting ofthe B flag. Offsets less than the segment limit generate generalprotection exceptions. Decreasing the value in the segment limit fieldfor an expand-down segment allocates new memory at the bottom ofthe segment's address space, rather than at the top. IA-32 architecture stacks always grow downwards, making this mechanism convenient for expandable stacks.Base address fieldsDefines the location of byte 0 of the segment within the 4-GBytelinear address space.

The processor puts together the three baseaddress fields to form a single 32-bit value. Segment base addressesshould be aligned to 16-byte boundaries. Although 16-byte alignmentis not required, this alignment allows programs to maximize performance by aligning code and data on 16-byte boundaries.Type fieldIndicates the segment or gate type and specifies the kinds of accessthat can be made to the segment and the direction of growth. Theinterpretation of this field depends on whether the descriptor type flagspecifies an application (code or data) descriptor or a systemdescriptor. The encoding of the type field is different for code, data,and system descriptors (see Figure 4-1).

See Section 3.4.5.1, “Codeand Data-Segment Descriptor Types”, for a description of how thisfield is used to specify code and data-segment types.S (descriptor type) flagSpecifies whether the segment descriptor is for a system segment(S flag is clear) or a code or data segment (S flag is set).DPL (descriptor privilege level) fieldSpecifies the privilege level of the segment. The privilege level canrange from 0 to 3, with 0 being the most privileged level. The DPL isused to control access to the segment. See Section 4.5, “PrivilegeLevels”, for a description of the relationship of the DPL to the CPL ofthe executing code segment and the RPL of a segment selector.P (segment-present) flagIndicates whether the segment is present in memory (set) or notpresent (clear).

If this flag is clear, the processor generates asegment-not-present exception (#NP) when a segment selector thatpoints to the segment descriptor is loaded into a segment register.Memory management software can use this flag to control whichsegments are actually loaded into physical memory at a given time. Itoffers a control in addition to paging for managing virtual memory.Figure 3-9 shows the format of a segment descriptor when thesegment-present flag is clear. When this flag is clear, the operatingsystem or executive is free to use the locations marked “Available” to3-14 Vol.

3PROTECTED-MODE MEMORY MANAGEMENTstore its own data, such as information regarding the whereabouts ofthe missing segment.D/B (default operation size/default stack pointer size and/or upper bound)flagPerforms different functions depending on whether the segmentdescriptor is an executable code segment, an expand-down datasegment, or a stack segment. (This flag should always be set to 1 for32-bit code and data segments and to 0 for 16-bit code and datasegments.)•Executable code segment.

The flag is called the D flag and itindicates the default length for effective addresses and operandsreferenced by instructions in the segment. If the flag is set, 32-bitaddresses and 32-bit or 8-bit operands are assumed; if it is clear,16-bit addresses and 16-bit or 8-bit operands are assumed.The instruction prefix 66H can be used to select an operand sizeother than the default, and the prefix 67H can be used select anaddress size other than the default.•Stack segment (data segment pointed to by the SSregister).

The flag is called the B (big) flag and it specifies thesize of the stack pointer used for implicit stack operations (such aspushes, pops, and calls). If the flag is set, a 32-bit stack pointer isused, which is stored in the 32-bit ESP register; if the flag is clear,a 16-bit stack pointer is used, which is stored in the 16-bit SPregister. If the stack segment is set up to be an expand-down datasegment (described in the next paragraph), the B flag alsospecifies the upper bound of the stack segment.•Expand-down data segment.

The flag is called the B flag and itspecifies the upper bound of the segment. If the flag is set, theupper bound is FFFFFFFFH (4 GBytes); if the flag is clear, theupper bound is FFFFH (64 KBytes).3116 15 14 13 12 11Available0DPL31S08 7TypeAvailable40Available0Figure 3-9. Segment Descriptor When Segment-Present Flag Is ClearVol.

3 3-15PROTECTED-MODE MEMORY MANAGEMENTG (granularity) flagDetermines the scaling of the segment limit field. When thegranularity flag is clear, the segment limit is interpreted in byteunits; when flag is set, the segment limit is interpreted in4-KByte units.

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

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

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

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