Главная » Просмотр файлов » Volume 1 Basic Architecture

Volume 1 Basic Architecture (794100), страница 86

Файл №794100 Volume 1 Basic Architecture (Intel and AMD manuals) 86 страницаVolume 1 Basic Architecture (794100) страница 862019-04-28СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

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

When an x87 FPU exception handler will beinvoked, synchronization must always be considered to assure reliable performance.Example D-1 and Example D-2, below, illustrate the need to always consider exception synchronization when writing numeric code, even when the code is initiallyintended for execution with exceptions masked.D.3.3.2Exception Synchronization ExamplesIn the following examples, three instructions are shown to load an integer, calculateits square root, then increment the integer.

The synchronous execution of the x87FPU will allow both of these programs to execute correctly, with INC COUNT beingexecuted in parallel in the processor, as long as no exceptions occur on the FILDinstruction. However, if the code is later moved to an environment where exceptionsare unmasked, the code in Example D-1 will not work correctly:Example D-1. Incorrect Error SynchronizationFILD COUNTINC COUNTFSQRT;x87 FPU instruction;integer instruction alters operand;subsequent x87 FPU instruction -- error;from previous x87 FPU instruction detected hereExample D-2.

Proper Error SynchronizationFILD COUNTFSQRTINC COUNT;x87 FPU instruction;subsequent x87 FPU instruction -- error from;previous x87 FPU instruction detected here;integer instruction alters operandIn some operating systems supporting the x87 FPU, the numeric register stack isextended to memory. To extend the x87 FPU stack to memory, the invalid exceptionis unmasked. A push to a full register or pop from an empty register sets SF (StackFault flag) and causes an invalid operation exception.

The recovery routine for theexception must recognize this situation, fix up the stack, then perform the originaloperation. The recovery routine will not work correctly in Example D-1. The problemis that the value of COUNT increments before the exception handler is invoked, sothat the recovery routine will load an incorrect value of COUNT, causing the programto fail or behave unreliably.Vol. 1 D-17GUIDELINES FOR WRITING X87 FPU EXCEPTION HANDLERSD.3.3.3Proper Exception SynchronizationAs explained in Section D.2.1.2, “Recommended External Hardware to Support theMS-DOS Compatibility Sub-mode,” if the x87 FPU encounters an unmasked exceptioncondition a software exception handler is invoked before execution of the next WAITor floating-point instruction.

This is because an unmasked floating-point exceptioncauses the processor to freeze immediately before executing such an instruction(unless the IGNNE# input is active, or it is a no-wait x87 FPU instruction). Exactlywhen the exception handler will be invoked (in the interval between when the exception is detected and the next WAIT or x87 FPU instruction) is dependent on theprocessor generation, the system, and which x87 FPU instruction and exception isinvolved.To be safe in exception synchronization, one should assume the handler will beinvoked at the end of the interval. Thus the program should not change any valuethat might be needed by the handler (such as COUNT in Example D-1 and ExampleD-2) until after the next x87 FPU instruction following an x87 FPU instruction thatcould cause an error.

If the program needs to modify such a value before the nextx87 FPU instruction (or if the next x87 FPU instruction could also cause an error),then a WAIT instruction should be inserted before the value is modified. This willforce the handling of any exception before the value is modified. A WAIT instructionshould also be placed after the last floating-point instruction in an application so thatany unmasked exceptions will be serviced before the task completes.D.3.4x87 FPU Exception Handling ExamplesThere are many approaches to writing exception handlers. One useful technique is toconsider the exception handler procedure as consisting of “prologue,” “body,” and“epilogue” sections of code.In the transfer of control to the exception handler due to an INTR, NMI, or SMI,external interrupts have been disabled by hardware. The prologue performs all functions that must be protected from possible interruption by higher-priority sources.Typically, this involves saving registers and transferring diagnostic information fromthe x87 FPU to memory.

When the critical processing has been completed, theprologue may re-enable interrupts to allow higher-priority interrupt handlers topreempt the exception handler. The standard “prologue” not only saves the registersand transfers diagnostic information from the x87 FPU to memory but also clears thefloating-point exception flags in the status word.

Alternatively, when it is not necessary for the handler to be re-entrant, another technique may also be used. In thistechnique, the exception flags are not cleared in the “prologue” and the body of thehandler must not contain any floating-point instructions that cannot complete execution when there is a pending floating-point exception. (The no-wait instructions arediscussed in Section 8.3.12, “Waiting vs.

Non-waiting Instructions.”) Note that thehandler must still clear the exception flag(s) before executing the IRET. If the exception handler uses neither of these techniques, the system will be caught in an endlessloop of nested floating-point exceptions, and hang.D-18 Vol. 1GUIDELINES FOR WRITING X87 FPU EXCEPTION HANDLERSThe body of the exception handler examines the diagnostic information and makes aresponse that is necessarily application-dependent.

This response may range fromhalting execution, to displaying a message, to attempting to repair the problem andproceed with normal execution. The epilogue essentially reverses the actions of theprologue, restoring the processor so that normal execution can be resumed. Theepilogue must not load an unmasked exception flag into the x87 FPU or anotherexception will be requested immediately.The following code examples show the ASM386/486 coding of three skeleton exception handlers, with the save spaces given as correct for 32-bit protected mode. Theyshow how prologues and epilogues can be written for various situations, but theapplication-dependent exception handling body is just indicated by commentsshowing where it should be placed.The first two are very similar; their only substantial difference is their choice ofinstructions to save and restore the x87 FPU.

The trade-off here is between theincreased diagnostic information provided by FNSAVE and the faster execution ofFNSTENV. (Also, after saving the original contents, FNSAVE re-initializes the x87 FPU,while FNSTENV only masks all x87 FPU exceptions.) For applications that are sensitive to interrupt latency or that do not need to examine register contents, FNSTENVreduces the duration of the “critical region,” during which the processor does notrecognize another interrupt request. (See the Section 8.1.10, “Saving the x87 FPU’sState with FSTENV/FNSTENV and FSAVE/FNSAVE,” for a complete description of thex87 FPU save image.) If the processor supports Streaming SIMD Extensions and theoperating system supports it, the FXSAVE instruction should be used instead ofFNSAVE.

If the FXSAVE instruction is used, the save area should be increased to 512bytes and aligned to 16 bytes to save the entire state. These steps will ensure thatthe complete context is saved.After the exception handler body, the epilogues prepare the processor to resumeexecution from the point of interruption (for example, the instruction following theone that generated the unmasked exception). Notice that the exception flags in thememory image that is loaded into the x87 FPU are cleared to zero prior to reloading(in fact, in these examples, the entire status word image is cleared).Example D-3 and Example D-4 assume that the exception handler itself will notcause an unmasked exception. Where this is a possibility, the general approachshown in Example D-5 can be employed. The basic technique is to save the full x87FPU state and then to load a new control word in the prologue.

Note that considerablecare should be taken when designing an exception handler of this type to prevent thehandler from being reentered endlessly.Example D-3. Full-State Exception HandlerSAVE_ALL PROC;;SAVE REGISTERS, ALLOCATE STACK SPACE FOR x87 FPU STATE IMAGEPUSHEBP.Vol. 1 D-19GUIDELINES FOR WRITING X87 FPU EXCEPTION HANDLERS.MOVEBP, ESPSUBESP, 108 ; ALLOCATES 108 BYTES (32-bit PROTECTED MODE SIZE);SAVE FULL x87 FPU STATE, RESTORE INTERRUPT ENABLE FLAG (IF)FNSAVE [EBP-108]PUSH[EBP + OFFSET_TO_EFLAGS] ; COPY OLD EFLAGS TO STACK TOPPOPFD ;RESTORE IF TO VALUE BEFORE x87 FPU EXCEPTION;;APPLICATION-DEPENDENT EXCEPTION HANDLING CODE GOES HERE;;CLEAR EXCEPTION FLAGS IN STATUS WORD (WHICH IS IN MEMORY);RESTORE MODIFIED STATE IMAGEMOVBYTE PTR [EBP-104], 0HFRSTOR [EBP-108];DE-ALLOCATE STACK SPACE, RESTORE REGISTERSMOVESP, EBP..POPEBP;;RETURN TO INTERRUPTED CALCULATIONIRETDSAVE_ALLENDPExample D-4.

Reduced-Latency Exception HandlerSAVE_ENVIRONMENTPROC;;SAVE REGISTERS, ALLOCATE STACK SPACE FOR x87 FPU ENVIRONMENTPUSHEBP..MOVEBP, ESPSUBESP, 28 ;ALLOCATES 28 BYTES (32-bit PROTECTED MODE SIZE);SAVE ENVIRONMENT, RESTORE INTERRUPT ENABLE FLAG (IF)FNSTENV[EDP - 28]PUSH[EBP + OFFSET_TO_EFLAGS] ; COPY OLD EFLAGS TO STACK TOPPOPFD ;RESTORE IF TO VALUE BEFORE x87 FPU EXCEPTION;;APPLICATION-DEPENDENT EXCEPTION HANDLING CODE GOES HERE;;CLEAR EXCEPTION FLAGS IN STATUS WORD (WHICH IS IN MEMORY);RESTORE MODIFIED ENVIRONMENT IMAGED-20 Vol. 1GUIDELINES FOR WRITING X87 FPU EXCEPTION HANDLERSMOVBYTE PTR [EBP-24], 0HFLDENV [EBP-28];DE-ALLOCATE STACK SPACE, RESTORE REGISTERSMOVESP, EBP..POPEBP;;RETURN TO INTERRUPTED CALCULATIONIRETDSAVE_ENVIRONMENT ENDPExample D-5. Reentrant Exception Handler..LOCAL_CONTROL DW ?; ASSUME INITIALIZED..REENTRANTPROC;;SAVE REGISTERS, ALLOCATE STACK SPACE FOR x87 FPU STATE IMAGEPUSHEBP..MOVEBP, ESPSUBESP, 108 ;ALLOCATES 108 BYTES (32-bit PROTECTED MODE SIZE);SAVE STATE, LOAD NEW CONTROL WORD, RESTORE INTERRUPT ENABLE FLAG (IF)FNSAVE [EBP-108]FLDCW LOCAL_CONTROLPUSH[EBP + OFFSET_TO_EFLAGS] ;COPY OLD EFLAGS TO STACK TOPPOPFD ;RESTORE IF TO VALUE BEFORE x87 FPU EXCEPTION..;;APPLICATION-DEPENDENT EXCEPTION HANDLING CODE;GOES HERE - AN UNMASKED EXCEPTION;GENERATED HERE WILL CAUSE THE EXCEPTION HANDLER TO BE REENTERED;IF LOCAL STORAGE IS NEEDED, IT MUST BE ALLOCATED ON THE STACK.;CLEAR EXCEPTION FLAGS IN STATUS WORD (WHICH IS IN MEMORY);RESTORE MODIFIED STATE IMAGEVol.

1 D-21GUIDELINES FOR WRITING X87 FPU EXCEPTION HANDLERSMOVBYTE PTR [EBP-104], 0HFRSTOR [EBP-108];DE-ALLOCATE STACK SPACE, RESTORE REGISTERSMOVESP, EBP..POPEBP;;RETURN TO POINT OF INTERRUPTIONIRETDREENTRANT ENDPD.3.5Need for Storing State of IGNNE# Circuit If Using x87 FPUand SMMThe recommended circuit (see Figure D-1) for MS-DOS compatibility x87 FPU exception handling for Intel486 processors and beyond contains two flip flops. When thex87 FPU exception handler accesses I/O port 0F0H it clears the IRQ13 interruptrequest output from Flip Flop #1 and also clocks out the IGNNE# signal (active) fromFlip Flop #2.The assertion of IGNNE# may be used by the handler if needed to execute any x87FPU instruction while ignoring the pending x87 FPU errors. The problem here is thatthe state of Flip Flop #2 is effectively an additional (but hidden) status bit that canaffect processor behavior, and so ideally should be saved upon entering SMM, andrestored before resuming to normal operation.

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

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

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

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