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

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

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

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

SMI is an external non-maskableinterrupt that operates differently from and independently of other interrupts. SMI has priority over allother external interrupts, including NMI (see “Priorities” on page 224 for a list of the interruptpriorities). SMIs are disabled when in SMM, which prevents reentrant calls to the SMM handler.When an SMI is received by the processor, the processor stops fetching instructions and waits forcurrently-executing instructions to complete and write their results.

The SMI also waits for all bufferedmemory writes to update the caches or system memory. When these activities are complete, theprocessor uses implementation-dependent external signalling to acknowledge back to the system thatit has received the SMI.10.3.2 SMM Operating-EnvironmentThe SMM operating-environment is similar to real mode, except that the segment limits in SMM are 4Gbytes rather than 64 Kbytes. This allows an SMM handler to address memory in the range from 0h to0FFFF_FFFFh. As with real mode, segment-base addresses are restricted to 20 bits in SMM, and thedefault operand-size and address-size is 16 bits. To address memory locations above 1 Mbyte, theSMM handler must use the 32-bit operand-size-override and address-size-override prefixes.After saving the processor state in the SMRAM state-save area, a processor running in SMM sets thesegment-selector registers and control registers into a state consistent with real mode.

Other registersare also initialized upon entering SMM, as shown in Table 10-3.Table 10-3. SMM Register InitializationRegisterInitial SMM ContentsSelector SMBASE right-shifted 4 bitsCSSystem-Management ModeBaseSMBASELimitFFFF_FFFFhAttrRead-Write-Execute279AMD64 Technology24593—Rev.

3.13—July 2007Table 10-3. SMM Register Initialization (continued)RegisterInitial SMM ContentsSelector 0000hDS, ES, FS, GS, SSBase0000_0000_0000_0000hLimitFFFF_FFFFhAttrRead-WriteRIP0000_0000_0000_8000hRFLAGS0000_0000_0000_0002hCR0PE, EM, TS, PG bits cleared to 0.All other bits are unmodified.CR40000_0000_0000_0000hDR70000_0000_0000_0400hEFER0000_0000_0000_0000h10.3.3 Exceptions and InterruptsAll hardware interrupts are disabled upon entering SMM, but exceptions and software interrupts arenot disabled. If necessary, the SMM handler can re-enable hardware interrupts. Software that handlesinterrupts in SMM should consider the following:••••••SMI—If an SMI occurs while the processor is in SMM, it is latched by the processor.

The latchedSMI occurs when the processor leaves SMM.NMI—If an NMI occurs while the processor is in SMM, it is latched by the processor, but the NMIhandler is not invoked until the processor leaves SMM with the execution of an RSM instruction. Apending NMI causes the handler to be invoked immediately after the RSM completes and beforethe first instruction in the interrupted program is executed.An SMM handler can unmask NMI interrupts by simply executing an IRET.

Upon completion ofthe IRET instruction, the processor recognizes the pending NMI, and transfers control to the NMIhandler. Once an NMI is recognized within SMM using this technique, subsequent NMIs arerecognized until SMM is exited. Later SMIs cause NMIs to be masked, until the SMM handlerunmasks them.Exceptions—Exceptions (internal processor interrupts) are not disabled and can occur while inSMM. Therefore, the SMM-handler software should be written to avoid generating exceptions.Software Interrupts—The software-interrupt instructions (BOUND, INTn, INT3, and INTO) canbe executed while in SMM. However, it is not recommended that the SMM handler use theseinstructions.Maskable Interrupts—RFLAGS.IF is cleared to 0 by the processor when SMM is entered.Software can re-enable maskable interrupts while in SMM, but it must follow the guidelines listedbelow for handling interrupts.Debug Interrupts—The processor disables the debug interrupts when SMM is entered by clearingDR7 to 0 and clearing RFLAGS.TF to 0.

The SMM handler can re-enable the debug facilitieswhile in SMM, but it must follow the guidelines listed below for handling interrupts.280System-Management Mode24593—Rev. 3.13—July 2007•AMD64 TechnologyINIT—The processor does not recognize INIT while in SMM.Because the RFLAGS.IF bit is cleared when entering SMM, the HLT instruction should not beexecuted in SMM without first setting the RFLAGS.IF bit to 1. Setting this bit to 1 allows theprocessor to exit the halt state by using an external maskable interrupt.In the cases where an SMM handler must accept and handle interrupts and exceptions, severalguidelines must be followed:•••••Interrupt handlers must be loaded and accessible before enabling interrupts.A real-mode interrupt-vector table located at virtual (linear) address 0 is required.Segments accessed by the interrupt handler cannot have a base address greater than 20 bits becauseof the real-mode addressing used in SMM.

In SMM, the 16-bit value stored in the segment-selectorregister is left-shifted four bits to form the 20-bit segment-base address, like real mode.Only the IP (rIP[15:0]) is pushed onto the stack as a result of an interrupt in SMM, because of thereal-mode addressing used in SMM. If the SMM handler is interrupted at a code-segment offsetabove 64 Kbytes, then the return address on the stack must be adjusted by the interrupt-handler,and a RET instruction with a 32-bit operand-size override must be used to return to the SMMhandler.If the interrupt-handler is located below 1 Mbyte, and the SMM handler is located above 1 Mbyte,a RET instruction cannot be used to return to the SMM handler.

In this case, the interrupt handlercan adjust the return pointer on the stack, and use a far CALL to transfer control back to the SMMhandler.10.3.4 Invalidating the CachesThe processor can cache SMRAM-memory locations. If the system implements physically separateSMRAM and system memory, it is possible for SMRAM and system memory locations to alias intoidentical cache locations.

In some processor implementations, the cache contents must be written tomemory and invalidated when SMM is entered and exited. This prevents the processor from usingpreviously-cached main-memory locations as aliases for SMRAM-memory locations when SMM isentered, and vice-versa when SMM is exited.Implementations of the AMD64 architecture do not require cache invalidation when entering andexiting SMM. Internally, the processor keeps track of SMRAM and system-memory accessesseparately and properly handles situations where aliasing occurs. Cached system memory andSMRAM locations can persist across SMM mode changes.

Removal of the requirement to writebackand invalidate the cache simplifies SMM entry and exit and allows SMM code to execute more rapidly.10.3.5 Saving Additional Processor StateSeveral registers are not saved or restored automatically by the SMM mechanism.

These are:•••The 128-bit media instruction registers.The 64-bit media instruction registers.The x87 floating-point registers.System-Management Mode281AMD64 Technology•••••24593—Rev. 3.13—July 2007The page-fault linear-address register (CR2).The task-priority register (CR8).The debug registers, DR0, DR1, DR2, and DR3.The memory-type range registers (MTRRs).Model-specific registers (MSRs).These registers are not saved because SMM handlers do not normally use or modify them. If an SMIresults in a processor reset (due to powering down the processor, for example) or the SMM handlermodifies the contents of the unsaved registers, the SMM handler should save and restore the originalcontents of those registers. The unsaved registers, along with those stored in the SMRAM state-savearea, need to be saved in a non-volatile storage location if a processor reset occurs.

The SMM handlershould execute the CPUID instruction to determine the feature set available in the processor, and beable to save and restore the registers required by those features.The SMM handler can execute any of the 128-bit media, 64-bit media, or x87 instructions. A simplemethod for saving and restoring those registers is to use the FXSAVE and FXRSTOR instructions,respectively, if it is supported by the processor. See “Saving Media and x87 Processor State” onpage 293 for information on saving and restoring those registers.Floating-point exceptions can occur when the SMM handler uses media or x87 floating-pointinstructions.

If the SMM handler uses floating-point exception handlers, they must follow the usageguidelines established in “Exceptions and Interrupts” on page 280. A simple method for dealing withfloating-point exceptions while in SMM is to simply mask all exception conditions using theappropriate floating-point control register. When the exceptions are masked, the processor handlesfloating-point exceptions internally in a default manner, and allows execution to continueuninterrupted.10.3.6 Operating in Protected Mode and Long ModeSoftware can enable protected mode from SMM and it can also enable and activate long mode.

AnSMM handler can use this capability to enter 64-bit mode and save additional processor state thatcannot be accessed from outside 64-bit mode (for example, the most-significant 32 bits of CR2).10.3.7 Auto-Halt RestartThe auto-halt restart entry is located at offset FEC9h in the SMM state-save area.

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

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

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

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