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

Volume 3B System Programming Guide_ Part 2 (794104), страница 54

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

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

(See Section24.8 for more information about how NMIs are handled in SMM.)Debug register DR7 is cleared, which disables breakpoint traps. (This actionprevents a debugger from accidentally breaking into an SMM handler if a debugbreakpoint is set in normal address space that overlays code or data in SMRAM.)Vol. 3 24-13SYSTEM MANAGEMENTSoftware-invoked interrupts and exceptions can still occur, and maskable hardwareinterrupts can be enabled by setting the IF flag. Intel recommends that SMM code bewritten in so that it does not invoke software interrupts (with the INT n, INTO, INT 3,or BOUND instructions) or generate exceptions.If the SMM handler requires interrupt and exception handling, an SMM interrupt tableand the necessary exception and interrupt handlers must be created and initializedfrom within SMM.

Until the interrupt table is correctly initialized (using the LIDTinstruction), exceptions and software interrupts will result in unpredictable processorbehavior.The following restrictions apply when designing SMM interrupt and exceptionhandling facilities:•The interrupt table should be located at linear address 0 and must contain realaddress mode style interrupt vectors (4 bytes containing CS and IP).•Due to the real-address mode style of base address formation, an interrupt orexception cannot transfer control to a segment with a base address of more that20 bits.•An interrupt or exception cannot transfer control to a segment offset of morethan 16 bits (64 KBytes).•When an exception or interrupt occurs, only the 16 least-significant bits of thereturn address (EIP) are pushed onto the stack. If the offset of the interruptedprocedure is greater than 64 KBytes, it is not possible for the interrupt/exceptionhandler to return control to that procedure. (One solution to this problem is for ahandler to adjust the return address on the stack.)•The SMBASE relocation feature affects the way the processor will return from aninterrupt or exception generated while the SMI handler is executing.

Forexample, if the SMBASE is relocated to above 1 MByte, but the exceptionhandlers are below 1 MByte, a normal return to the SMI handler is not possible.One solution is to provide the exception handler with a mechanism for calculatinga return address above 1 MByte from the 16-bit return address on the stack, thenuse a 32-bit far call to return to the interrupted procedure.•If an SMI handler needs access to the debug trap facilities, it must insure that anSMM accessible debug handler is available and save the current contents ofdebug registers DR0 through DR3 (for later restoration). Debug registers DR0through DR3 and DR7 must then be initialized with the appropriate values.•If an SMI handler needs access to the single-step mechanism, it must insure thatan SMM accessible single-step handler is available, and then set the TF flag in theEFLAGS register.•If the SMI design requires the processor to respond to maskable hardwareinterrupts or software-generated interrupts while in SMM, it must ensure thatSMM accessible interrupt handlers are available and then set the IF flag in theEFLAGS register (using the STI instruction).

Software interrupts are not blockedupon entry to SMM, so they do not need to be enabled.24-14 Vol. 3SYSTEM MANAGEMENT24.7MANAGING SYNCHRONOUS AND ASYNCHRONOUSSYSTEM MANAGEMENT INTERRUPTSWhen coding for a multiprocessor system or a system with Intel HT Technology, itwas not always possible for an SMI handler to distinguish between a synchronousSMI (triggered during an I/O instruction) and an asynchronous SMI. To facilitate thediscrimination of these two events, incremental state information has been added tothe SMM state save map.Processors that have an SMM revision ID of 30004H or higher have the incrementalstate information described below.24.7.1I/O State ImplementationWithin the extended SMM state save map, a bit (IO_SMI) is provided that is set onlywhen an SMI is either taken immediately after a successful I/O instruction or is takenafter a successful iteration of a REP I/O instruction (note that the successful notionpertains to the processor point of view; not necessarily to the corresponding platformfunction).

When set, the IO_SMI bit provides a strong indication that the corresponding SMI was synchronous. In this case, the SMM State Save Map also suppliesthe port address of the I/O operation. The IO_SMI bit and the I/O Port Address maybe used in conjunction with the information logged by the platform to confirm thatthe SMI was indeed synchronous.Note that the IO_SMI bit by itself is a strong indication, not a guarantee, that the SMIis synchronous. This is because an asynchronous SMI might coincidentally be takenafter an I/O instruction. In such a case, the IO_SMI bit would still be set in the SMMstate save map.Information characterizing the I/O instruction is saved in two locations in the SMMState Save Map (Table 24-4). Note that the IO_SMI bit also serves as a valid bit forthe rest of the I/O information fields. The contents of these I/O information fields arenot defined when the IO_SMI bit is not set.Table 24-4.

I/O Instruction Information in the SMM State Save MapState (SMM Rev. ID: 30004H orhigher)Format3115310IO_SMII/O Memory Address Field4I/O Length317I/O TypeSMRAM offset 7FA48ReservedI/O PortI/0 State Field160I/O Memory AddressSMRAM offset 7FA0Vol. 3 24-15SYSTEM MANAGEMENTWhen IO_SMI is set, the other fields may be interpreted as follows:•I/O length:••••001 – Byte010 – Word100 – DwordI/O instruction type (Table 24-5)Table 24-5. I/O Instruction Type EncodingsInstructionEncodingIN Immediate1001IN DX0001OUT Immediate1000OUT DX0000INS0011OUTS0010REP INS0111REP OUTS011024.8NMI HANDLING WHILE IN SMMNMI interrupts are blocked upon entry to the SMI handler. If an NMI request occursduring the SMI handler, it is latched and serviced after the processor exits SMM.

Onlyone NMI request will be latched during the SMI handler. If an NMI request is pendingwhen the processor executes the RSM instruction, the NMI is serviced before the nextinstruction of the interrupted code sequence. This assumes that NMIs were notblocked before the SMI occurred. If NMIs were blocked before the SMI occurred, theyare blocked after execution of RSM.Although NMI requests are blocked when the processor enters SMM, they may beenabled through software by executing an IRET/IRETD instruction.

If the SMMhandler requires the use of NMI interrupts, it should invoke a dummy interruptservice routine for the purpose of executing an IRET/IRETD instruction. Once anIRET/IRETD instruction is executed, NMI interrupt requests are serviced in the same“real mode” manner in which they are handled outside of SMM.A special case can occur if an SMI handler nests inside an NMI handler and thenanother NMI occurs. During NMI interrupt handling, NMI interrupts are disabled, sonormally NMI interrupts are serviced and completed with an IRET instruction one ata time. When the processor enters SMM while executing an NMI handler, theprocessor saves the SMRAM state save map but does not save the attribute to keepNMI interrupts disabled.

Potentially, an NMI could be latched (while in SMM or upon24-16 Vol. 3SYSTEM MANAGEMENTexit) and serviced upon exit of SMM even though the previous NMI handler has stillnot completed. One or more NMIs could thus be nested inside the first NMI handler.The NMI interrupt handler should take this possibility into consideration.Also, for the Pentium processor, exceptions that invoke a trap or fault handler willenable NMI interrupts from inside of SMM. This behavior is implementation specificfor the Pentium processor and is not part the IA-32 architecture.24.9SAVING THE X87 FPU STATE WHILE IN SMMIn some instances (for example prior to powering down system memory whenentering a 0-volt suspend state), it is necessary to save the state of the x87 FPUwhile in SMM. Care should be taken when performing this operation to insure thatrelevant x87 FPU state information is not lost.

The safest way to perform this task isto place the processor in 32-bit protected mode before saving the x87 FPU state. Thereason for this is as follows.The FSAVE instruction saves the x87 FPU context in any of four different formats,depending on which mode the processor is in when FSAVE is executed (see Chapter8, “Programming with the x87 FPU”, in the Intel® 64 and IA-32 Architectures Software Developer’s Manual, Volume 1). When in SMM, by default, the 16-bit realaddress mode format is used. If an SMI interrupt occurs while the processor is in amode other than 16-bit real-address mode, FSAVE and FRSTOR will be unable tosave and restore all the relevant x87 FPU information, and this situation may resultin a malfunction when the interrupted program is resumed.

To avoid this problem,the processor should be in 32-bit protected mode when executing the FSAVE andFRSTOR instructions.The following guidelines should be used when going into protected mode from an SMIhandler to save and restore the x87 FPU state:••Use the CPUID instruction to insure that the processor contains an x87 FPU.•Write a procedure or routine that can be called by the SMI handler to save andrestore the x87 FPU state. This procedure should do the following:Create a 32-bit code segment in SMRAM space that contains procedures orroutines to save and restore the x87 FPU using the FSAVE and FRSTOR instructions, respectively. A GDT with an appropriate code-segment descriptor (D bit isset to 1) for the 32-bit code segment must also be placed in SMRAM.— Place the processor in 32-bit protected mode as describe in Section 9.9.1 inIntel® 64 and IA-32 Architectures Software Developer’s Manual, Volume 3A.— Execute a far JMP to the 32-bit code segment that contains the x87 FPU saveand restore procedures.— Place the processor back in 16-bit real-address mode before returning to theSMI handler (see Section 9.9.2 in Intel® 64 and IA-32 ArchitecturesSoftware Developer’s Manual, Volume 3A).Vol.

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

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

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

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