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

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

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

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

The “next” floating-point instruction may be the FNSAVE used tosave the x87 FPU state for a task switch. In the case of “no-wait:” instructions suchas FNSAVE, the interrupt from a previously excepting instruction (NE = 0 case) mayarrive just before the no-wait instruction, during, or shortly thereafter with a systemdependent delay.Note that this implies that an floating-point exception might be registered during thestate swap process itself, and the kernel and floating-point exception interrupthandler must be prepared for this case.A simple way to handle the case of exceptions arriving during x87 FPU state swaps isto allow the kernel to be one of the x87 FPU owning threads.

A reserved thread identifier is used to indicate kernel ownership of the x87 FPU. During an floating-pointstate swap, the “x87 FPU owner” variable should be set to indicate the kernel as thecurrent owner. At the completion of the state swap, the variable should be set to indicate the new owning thread. The numeric exception handler needs to check the x87FPU owner and discard any numeric exceptions that occur while the kernel is the x87FPU owner. A more general flow for a DNA exception handler that handles this case isshown in Figure D-5.Numeric exceptions received while the kernel owns the x87 FPU for a state swapmust be discarded in the kernel without being dispatched to a handler.

A flow for anumeric exception dispatch routine is shown in Figure D-6.Vol. 1 D-25GUIDELINES FOR WRITING X87 FPU EXCEPTION HANDLERSIt may at first glance seem that there is a possibility of floating-point exceptionsbeing lost because of exceptions that are discarded during state swaps. This is notthe case, as the exception will be re-issued when the floating-point state is reloaded.Walking through state swaps both with and without pending numeric exceptions willclarify the operation of these two handlers.DNA Handler Entry<other handler set up code>Current Threadsame asFPU Owner?YesNoFPU Owner := KernelFNSAVE to Old Thread’sFP Save Area(may cause numeric exception)<handler final clean-up>FRSTOR from Current Thread’sFP Save AreaCLTS (clears CR0.TS)<other handler code>Exit DNA HandlerFPU Owner := Current ThreadFigure D-5.

General Program Flow for DNA Exception HandlerD-26 Vol. 1GUIDELINES FOR WRITING X87 FPU EXCEPTION HANDLERSNumeric Exception EntryIs KernelFPU Owner?YesNoNormal Dispatch toNumeric Exception HandlerExitFigure D-6. Program Flow for a Numeric Exception Dispatch RoutineCase #1: x87 FPU State Swap Without Numeric ExceptionAssume two threads A and B, both using the floating-point unit. Let A be the threadto have most recently executed a floating-point instruction, with no pending numericexceptions. Let B be the currently executing thread.

CR0.TS was set when thread Awas suspended.When B starts to execute a floating-point instruction the instruction will fault with theDNA exception because TS is set.At this point the handler is entered, and eventually it finds that the current x87 FPUOwner is not the currently executing thread. To guard the x87 FPU state swap fromextraneous numeric exceptions, the x87 FPU Owner is set to be the kernel. The oldowner’s x87 FPU state is saved with FNSAVE, and the current thread’s x87 FPU stateis restored with FRSTOR. Before exiting, the x87 FPU owner is set to thread B, andthe TS bit is cleared.On exit, thread B resumes execution of the faulting floating-point instruction andcontinues.Case #2: x87 FPU State Swap with Discarded Numeric ExceptionAgain, assume two threads A and B, both using the floating-point unit.

Let A be thethread to have most recently executed a floating-point instruction, but this time letthere be a pending numeric exception. Let B be the currently executing thread. WhenB starts to execute a floating-point instruction the instruction will fault with the DNAexception and enter the DNA handler. (If both numeric and DNA exceptions arepending, the DNA exception takes precedence, in order to support handling thenumeric exception in its own context.)When the FNSAVE starts, it will trigger an interrupt via FERR# because of thepending numeric exception. After some system dependent delay, the numeric exception handler is entered. It may be entered before the FNSAVE starts to execute, or itmay be entered shortly after execution of the FNSAVE. Since the x87 FPU Owner isthe kernel, the numeric exception handler simply exits, discarding the exception. TheVol.

1 D-27GUIDELINES FOR WRITING X87 FPU EXCEPTION HANDLERSDNA handler resumes execution, completing the FNSAVE of the old floating-pointcontext of thread A and the FRSTOR of the floating-point context for thread B.Thread A eventually gets an opportunity to handle the exception that was discardedduring the task switch. After some time, thread B is suspended, and thread Aresumes execution. When thread A starts to execute an floating-point instruction,once again the DNA exception handler is entered. B’s x87 FPU state is Finessed, andA’s x87 FPU state is Frustrate.

Note that in restoring the x87 FPU state from A’s savearea, the pending numeric exception flags are reloaded into the floating-point statusword. Now when the DNA exception handler returns, thread A resumes execution ofthe faulting floating-point instruction just long enough to immediately generate anumeric exception, which now gets handled in the normal way. The net result is thatthe task switch and resulting x87 FPU state swap via the DNA exception handlercauses an extra numeric exception which can be safely discarded.D.3.6.4Interrupt Routing From the KernelIn MS-DOS, an application that wishes to handle numeric exceptions hooks interrupt16 by placing its handler address in the interrupt vector table, and exiting via a jumpto the previous interrupt 16 handler.

Protected mode systems that run MS-DOSprograms under a subsystem can emulate this exception delivery mechanism. Forexample, assume a protected mode OS. that runs with CR0.NE[bit 5] = 1, and thatruns MS-DOS programs in a virtual machine subsystem. The MS-DOS program isset up in a virtual machine that provides a virtualized interrupt table. The MS-DOSapplication hooks interrupt 16 in the virtual machine in the normal way. A numericexception will trap to the kernel via the real INT 16 residing in the kernel at ring 0.The INT 16 handler in the kernel then locates the correct MS-DOS virtual machine,and reflects the interrupt to the virtual machine monitor.

The virtual machine monitorthen emulates an interrupt by jumping through the address in the virtualized interrupt table, eventually reaching the application’s numeric exception handler.D.3.6.5Special Considerations for Operating Systems that SupportStreaming SIMD ExtensionsOperating systems that support Streaming SIMD Extensions instructions introducedwith the Pentium III processor should use the FXSAVE and FXRSTOR instructions tosave and restore the new SIMD floating-point instruction register state as well as thefloating-point state. Such operating systems must consider the following issues:1.

Enlarged state save area — FNSAVE/FRSTOR instructions operate on a94-byte or 108-byte memory region, depending on whether they are executed in16-bit or 32-bit mode. The FXSAVE/FXRSTOR instructions operate on a 512-bytememory region.2. Alignment requirements — FXSAVE/FXRSTOR instructions require thememory region on which they operate to be 16-byte aligned (refer to theindividual instruction instructions descriptions in Chapter 3 of the Intel® 64 andD-28 Vol. 1GUIDELINES FOR WRITING X87 FPU EXCEPTION HANDLERSIA-32 Architectures Software Developer’s Manual, Volume 2A, for informationabout exceptions generated if the memory region is not aligned).3. Maintaining compatibility with legacy applications/libraries — Theoperating system changes to support Streaming SIMD Extensions must beinvisible to legacy applications or libraries that deal only with floating-pointinstructions.

The layout of the memory region operated on by theFXSAVE/FXRSTOR instructions is different from the layout for theFNSAVE/FRSTOR instructions. Specifically, the format of the x87 FPU tag wordand the length of the various fields in the memory region is different. Care mustbe taken to return the x87 FPU state to a legacy application (e.g., when reportingFP exceptions) in the format it expects.4. Instruction semantic differences — There are some semantic differencesbetween the way the FXSAVE and FSAVE/FNSAVE instructions operate. TheFSAVE/FNSAVE instructions clear the x87 FPU after they save the state while theFXSAVE instruction saves the x87 FPU/Streaming SIMD Extensions state butdoes not clear it.

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

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

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

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