Главная » Просмотр файлов » Volume 2 System Programming

Volume 2 System Programming (794096), страница 67

Файл №794096 Volume 2 System Programming (Intel and AMD manuals) 67 страницаVolume 2 System Programming (794096) страница 672019-04-28СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

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

3.13—July 2007AMD64 Technology8.9.3 Interrupt Stack FrameIn long mode, the return-program stack pointer (SS:RSP) is always pushed onto the interrupt-handlerstack, regardless of whether or not a privilege change occurs. Although the SS register is not used in64-bit mode, SS is pushed to allow returns into compatibility mode. Pushing SS:RSP unconditionallypresents operating systems with a consistent interrupt-stack-frame size for all interrupts, except forerror codes.

Interrupt service-routine entry points that handle interrupts generated by non-error-codeinterrupts can push an error code on the stack for consistency.In long mode, when a control transfer to an interrupt handler occurs, the processor performs thefollowing:1. Aligns the new interrupt-stack frame by masking RSP with FFFF_FFFF_FFFF_FFF0h.2. If IST field in interrupt gate is not 0, reads IST pointer into RSP.3. If a privilege change occurs, the target DPL is used as an index into the long-mode TSS to select anew stack pointer (RSP).4.

If a privilege change occurs, SS is cleared to zero indicating a null selector.5. Pushes the return stack pointer (old SS:RSP) onto the new stack. The SS value is padded with sixbytes to form a quadword.6. Pushes the 64-bit RFLAGS register onto the stack. The upper 32 bits of the RFLAGS image onthe stack are written as zeros.7. Clears the TF, NT, and RF bits in RFLAGS bits to 0.8. Handles the RFLAGS.IF bit according to the gate-descriptor type:- If the gate descriptor is an interrupt gate, RFLAGS.IF is cleared to 0.- If the gate descriptor is a trap gate, RFLAGS.IF is not modified.9. Pushes the return CS register and RIP register onto the stack. The CS value is padded with sixbytes to form a quadword.10.

If the interrupt-vector number has an error code associated with it, pushes the error code onto thestack. The error code is padded with four bytes to form a quadword.11. Loads the segment-selector field from the gate descriptor into the CS register. The processorchecks that the target code-segment is a 64-bit mode code segment.12. Loads the offset field from the gate descriptor into the target RIP. The interrupt handler beginsexecution when control is transferred to the instruction referenced by the new RIP.Figure 8-13 on page 242 shows the stack after control is transferred to the interrupt handler.Exceptions and Interrupts241AMD64 Technology24593—Rev.

3.13—July 2007Interrupt-Handler StackWith No Error CodeWith Error CodeReturn SS +40Return RSP+32Return RFLAGS+24Return CS +16Return SS +32Return RSP+24Return RFLAGS+16Return CS +8+8Return RIPError CodeRSPReturn RIPRSPFigure 8-13. Long-Mode Stack After Interrupt—Same PrivilegeInterrupt-Stack Alignment.

In legacy mode, the interrupt-stack pointer can be aligned at any addressboundary. Long mode, however, aligns the stack on a 16-byte boundary. This alignment is performedby the processor in hardware before pushing items onto the stack frame. The previous RSP is savedunconditionally on the new stack by the interrupt mechanism. A subsequent IRET instructionautomatically restores the previous RSP.Aligning the stack on a 16-byte boundary allows optimal performance for saving and restoring the 16byte XMM registers. The interrupt handler can save and restore the XMM registers using the faster 16byte aligned loads and stores (MOVAPS), rather than unaligned loads and stores (MOVUPS).Although the RSP alignment is always performed in long mode, it is only of consequence when theinterrupted program is already running at CPL=0, and it is generally used only within the operatingsystem kernel.

The operating system should put 16-byte aligned RSP values in the TSS for interruptsthat change privilege levels.Stack Switch. In long mode, the stack-switch mechanism differs slightly from the legacy stack-switch mechanism (see “Interrupt To Higher Privilege” on page 232). When stacks are switchedduring a long-mode privilege-level change resulting from an interrupt, a new SS descriptor is notloaded from the TSS. Long mode only loads an inner-level RSP from the TSS.

However, the SSselector is loaded with a null selector, allowing nested control transfers, including interrupts, to behandled properly in 64-bit mode. The SS.RPL is set to the new CPL value. See “Nested IRETs to 64Bit Mode Procedures” on page 245 for additional information.242Exceptions and Interrupts24593—Rev. 3.13—July 2007AMD64 TechnologyThe interrupt-handler stack that results from a privilege change in long mode looks identical to a longmode stack when no privilege change occurs. Figure 8-14 shows the stack after the switch isperformed and control is transferred to the interrupt handler.Interrupt-Handler StackWithout Error CodeWith Error CodeReturn SS +40Return RSP+32Return RFLAGS+24Return CS +16Return SS +32Return RSP+24Return RFLAGS+16Return CS +8+8Return RIPError CodeNew RSP(from TSS)SS=0(if CPL changes)Return RIPNew RSP(from TSS)SS=0(if CPL changes)Figure 8-14.

Long-Mode Stack After Interrupt—Higher Privilege8.9.4 Interrupt-Stack TableIn long mode, a new interrupt-stack table (IST) mechanism is introduced as an alternative to themodified legacy stack-switch mechanism described above. The IST mechanism provides a method forspecific interrupts, such as NMI, double-fault, and machine-check, to always execute on a knowngood stack. In legacy mode, interrupts can use the hardware task-switch mechanism to set up a knowngood stack by accessing the interrupt service routine through a task gate located in the IDT.

However,the hardware task-switch mechanism is not supported in long mode.When enabled, the IST mechanism unconditionally switches stacks. It can be enabled on an individualinterrupt-vector basis using a new field in the IDT gate-descriptor entry. This allows some interrupts touse the modified legacy mechanism, and others to use the IST mechanism.

The IST mechanism is onlyavailable in long mode.The IST mechanism uses new fields in the 64-bit TSS format and the long-mode interrupt-gate andtrap-gate descriptors:•Figure 12-8 on page 317 shows the format of the 64-bit TSS and the location of the seven ISTpointers. The 64-bit TSS offsets from 24h to 5Bh provide space for seven IST pointers, each ofwhich are 64 bits (8 bytes) long.Exceptions and Interrupts243AMD64 Technology•24593—Rev. 3.13—July 2007The long-mode interrupt-gate and trap-gate descriptors define a 3-bit IST-index field in bits 2–0 ofbyte +4. Figure 4-24 on page 91 shows the format of long-mode interrupt-gate and trap-gatedescriptors and the location of the IST-index field.To enable the IST mechanism for a specific interrupt, system software stores a non-zero value in theinterrupt gate-descriptor IST-index field.

If the IST index is zero, the modified legacy stack-switchingmechanism (described in the previous section) is used.Figure 8-15 shows how the IST mechanism is used to create the interrupt-handler stack. When aninterrupt occurs and the IST index is non-zero, the processor uses the index to select the correspondingIST pointer from the TSS. The IST pointer is loaded into the RSP to establish a new stack for theinterrupt handler. The SS register is loaded with a null selector if the CPL changes and the SS.RPL isset to the new CPL value.

After the stack is loaded, the processor pushes the old stack pointer,RFLAGS, the return pointer, and the error code (if applicable) onto the stack. Control is thentransferred to the interrupt handler.64-BitInterrupt-Handler StackReturn SS +4064-Bit TSSLong-ModeInterrupt- or TrapGate DescriptorISTReturn RSP+32Return RFLAGS+24Return CS +16Return RIPIST1 : IST7+8Error CodeSS=0RSPRSP0 : RSP2513-248.epsFigure 8-15. Long-Mode IST Mechanism8.9.5 Returning From Interrupt ProceduresAs with legacy mode, a return to an interrupted program in long mode should be performed using theIRET instruction.

However, in long mode, the IRET semantics are different from legacy mode:•In 64-bit mode, IRET pops the return-stack pointer unconditionally off the interrupt-stack frameand into the SS:RSP registers. This reverses the action of the long-mode interrupt mechanism,244Exceptions and Interrupts24593—Rev.

3.13—July 2007•AMD64 Technologywhich saves the stack pointer whether or not a privilege change occurs. IRET also allows a nullselector to be popped off the stack and into the SS register. See “Nested IRETs to 64-Bit ModeProcedures” on page 245 for additional information.In compatibility mode, IRET behaves as it does in legacy mode. The SS:ESP is popped off thestack only if a control transfer to less privilege (numerically greater CPL) is performed. Otherwise,it is assumed that a stack pointer is not present on the interrupt-handler stack.The long-mode interrupt mechanism always uses a 64-bit stack when saving values for the interrupthandler, and the interrupt handler is always entered in 64-bit mode. To work properly, an IRET used toexit the 64-bit mode interrupt-handler requires a series of eight-byte pops off the stack.

This isaccomplished by using a 64-bit operand-size prefix with the IRET instruction. The default stack sizeassumed by an IRET in 64-bit mode is 32 bits, so a 64-bit REX prefix is needed by 64-bit modeinterrupt handlers.Nested IRETs to 64-Bit Mode Procedures. In long mode, an interrupt causes a null selector to beloaded into the SS register if the CPL changes (this is the same action taken by a far CALL in longmode).

If the interrupt handler performs a far call, or is itself interrupted, the null SS selector is pushedonto the stack frame, and another null selector is loaded into the SS register. Using a null selector inthis way allows the processor to properly handle returns nested within 64-bit-mode procedures andinterrupt handlers.The null selector enables the processor to properly handle nested returns to 64-bit mode (which do notuse the SS register), and returns to compatibility mode (which do use the SS register). Normally, anIRET that pops a null selector into the SS register causes a general-protection exception (#GP) tooccur.

However, in long mode, the null selector indicates the existence of nested interrupt handlersand/or privileged software in 64-bit mode. Long mode allows an IRET to pop a null selector into SSfrom the stack under the following conditions:••The target mode is 64-bit mode.The target CPL<3.In this case, the processor does not load an SS descriptor, and the null selector is loaded into SSwithout causing a #GP exception.8.10Virtual InterruptsThe term virtual interrupts includes two classes of extensions to the interrupt-handling mechanism:••Virtual-8086 Mode Extensions (VME)—These allow virtual interrupts and interrupt redirection invirtual-8086 mode.

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

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

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

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