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

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

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

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

Even whenusing the flat-memory model, this overhead still occurs when switching between privilege levelsbecause code segments (CS) and stack segments (SS) are reloaded with different segment descriptors.To initiate a call to the operating system, an application transfers control to the operating systemthrough a gate descriptor (call, interrupt, trap, or task gate). In the past, control was transferred usingSystem-Management Instructions147AMD64 Technology24593—Rev. 3.13—July 2007either a far CALL instruction or a software interrupt.

Transferring control through one of these gates isslowed by the segmentation-related overhead, as is the later return using a far RET or IRETinstruction. The following checks are performed when control is transferred in this manner:•••••Selectors, gate descriptors, and segment descriptors are in the proper form.Descriptors lie within the bounds of the descriptor tables.Gate descriptors reference the appropriate segment descriptors.The caller, gate, and target privileges all allow the control transfer to take place.The stack created by the call has sufficient properties to allow the transfer to take place.In addition to these call-gate checks, other checks are made involving the task-state segment when atask switch occurs.6.1.1 SYSCALL and SYSRETSYSCALL and SYSRET Instructions.

SYSCALL and SYSRET are low-latency system call andreturn instructions. These instructions assume the operating system implements a flat-memory model,which greatly simplifies calls to and returns from the operating system. This simplification comesfrom eliminating unneeded checks, and by loading pre-determined values into the CS and SS segmentregisters (both visible and hidden portions). As a result, SYSCALL and SYSRET can take fewer thanone-fourth the number of internal clock cycles to complete than the legacy CALL and RETinstructions. SYSCALL and SYSRET are particularly well-suited for use in 64-bit mode, whichrequires implementation of a paged, flat-memory model.SYSCALL and SYSRET require that the code-segment base, limit, and attributes (except for CPL) areconsistent for all application and system processes. Only the CPL is allowed to vary.

The processorassumes (but does not check) that the SYSCALL target CS has CPL=0 and the SYSRET target CS hasCPL=3.For details on the SYSCALL and SYSRET instructions, see “System Instruction Reference” inVolume 3.SYSCALL and SYSRET MSRs. The STAR, LSTAR, and CSTAR registers are model-specificregisters (MSRs) used to specify the target address of a SYSCALL instruction as well as the CS and SSselectors of the called and returned procedures. The SFMASK register is used in long mode to specifyhow rFLAGS is handled by these instructions. Figure 6-1 on page 149 shows the STAR, LSTAR,CSTAR, and SFMASK register formats.148System-Management Instructions24593—Rev. 3.13—July 200763STARAMD64 Technology484732C000_0081h SYSRET CS and SS SYSCALL CS and SS31032-bit SYSCALL Target EIPLSTARC000_0082hTarget RIP for 64-Bit-Mode Calling SoftwareCSTARC000_0083hTarget RIP for Compatibility-Mode Calling SoftwareSFMASK C000_0084hReserved, RAZSYSCALL Flag MaskFigure 6-1.

STAR, LSTAR, CSTAR, and MASK MSRs•••STAR—The STAR register has the following fields (unless otherwise noted, all bits are read/write):- SYSRET CS and SS Selectors—Bits 63–48. This field is used to specify both the CS and SSselectors loaded into CS and SS during SYSRET. If SYSRET is returning to 32-bit mode(either legacy or compatibility), this field is copied directly into the CS selector field. IfSYSRET is returning to 64-bit mode, the CS selector is set to this field + 16. SS.Sel is set to thisfield + 8, regardless of the target mode. Because SYSRET always returns to CPL 3, the RPLbits 49–48 should be initialized to 11b.- SYSCALL CS and SS Selectors—Bits 47–32.

This field is used to specify both the CS and SSselectors loaded into CS and SS during SYSCALL. This field is copied directly into CS.Sel.SS.Sel is set to this field + 8. Because SYSCALL always switches to CPL 0, the RPL bits33–32 should be initialized to 00b.- 32-bit SYSCALL Target EIP—Bits 31–0. This is the target EIP of the called procedure.The legacy STAR register is not expanded in long mode to provide a 64-bit target RIP address.Instead, long mode provides two new STAR registers—long STAR (LSTAR) and compatibilitySTAR (CSTAR)—that hold a 64-bit target RIP.LSTAR and CSTAR—The LSTAR register holds the target RIP of the called procedure in longmode when the calling software is in 64-bit mode.

The CSTAR register holds the target RIP of thecalled procedure in long mode when the calling software is in compatibility mode. The WRMSRinstruction is used to load the target RIP into the LSTAR and CSTAR registers. If the RIP written toeither of the MSRs is not in canonical form, a #GP fault is generated on the WRMSR instruction.SFMASK—The SFMASK register is used to specify which RFLAGS bits are cleared during aSYSCALL. In long mode, SFMASK is used to specify which RFLAGS bits are cleared whenSYSCALL is executed.

If a bit in SFMASK is set to 1, the corresponding bit in RFLAGS is clearedto 0. If a bit in SFMASK is cleared to 0, the corresponding rFLAGS bit is not modified.System-Management Instructions149AMD64 Technology24593—Rev. 3.13—July 20076.1.2 SYSENTER and SYSEXIT (Legacy Mode Only)SYSENTER and SYSEXIT Instructions. L i ke S Y S C A L L a n d S Y S R E T, S Y S E N T E R a n dSYSEXIT are low-latency system call and return instructions designed for use by system andapplication software implementing a flat-memory model. However, these instructions are illegal inlong mode and result in an undefined opcode exception (#UD) if software attempts to use them.Software should use the SYSCALL and SYSRET instructions when running in long mode.SYSENTER and SYSEXIT MSRs. Three model-specific registers (MSRs) are used to specify thetarget address and stack pointers for the SYSENTER instruction as well as the CS and SS selectors ofthe called and returned procedures.

The register fields are:•••SYSENTER Target CS—Holds the CS selector of the called procedure.SYSENTER Target ESP—Holds the called-procedure stack pointer. The SS selector is updatedautomatically to point to the next descriptor entry after the SYSENTER Target CS, and ESP is theoffset into that stack segment.SYSENTER Target EIP—Holds the offset into the CS of the called procedure.Figure 6-2 shows the register formats and their corresponding MSR IDs.6332311615SYSENTER Target CSSYSENTER_CS 174hSYSENTER_ESP 175hSYSENTER Target ESPSYSENTER_EIP 176hSYSENTER Target EIPFigure 6-2.0SYSENTER_CS, SYSENTER_ESP, SYSENTER_EIP MSRs6.1.3 SWAPGS InstructionThe SWAPGS instruction provides a fast method for system software to load a pointer to system datastructures. SWAPGS can be used upon entering system-software routines as a result of a SYSCALLinstruction or as a result of an interrupt or exception.

Before returning to application software,SWAPGS can restore an application data-structure pointer that was replaced by the system datastructure pointer.SWAPGS exchanges the base-address value located in the KernelGSbase model-specific register(MSR address C000_0102h) with the base-address value located in the hidden portion of the GSselector register (GS.base). This exchange allows the system-kernel software to quickly access kerneldata structures by using the GS segment-override prefix during memory references.The need for SwapGS arises from the requirement that, upon entry to the OS kernel, the kernel needsto obtain a 64-bit pointer to its essential data structures.

When using SYSCALL to implement system150System-Management Instructions24593—Rev. 3.13—July 2007AMD64 Technologycalls, no kernel stack exists at the OS entry point. Neither is there a straightforward method to obtain apointer to kernel structures, from which the kernel stack pointer could be read. Thus, the kernel cannotsave GPRs or reference memory.

SwapGS does not require any GPR or memory operands, so noregisters need to be saved before using it. Similarly, when the OS kernel is entered via an interrupt orexception (where the kernel stack is already set up), SwapGS can be used to quickly get a pointer to thekernel data structures.See “FS and GS Registers in 64-Bit Mode” on page 70 for more information on using the GS.baseregister in 64-bit mode.6.2System Status and ControlSystem-status and system-control instructions are used to determine the features supported by aprocessor, gather information about the current execution state, and control the processor operatingmodes.6.2.1 Processor Feature Identification (CPUID)CPUID Instruction. The CPUID instruction provides complete information about the processorimplementation and its capabilities.

Software operating at any privilege level can execute the CPUIDinstruction to collect this information. System software normally uses the CPUID instruction todetermine which optional features are available so the system can be configured appropriately. Theoptional features identified by the CPUID instruction are described in “CPUID” in Volume 3.6.2.2 Accessing Control RegistersMOV CRn Instructions. The MOV CRn instructions can be used to copy data between the controlregisters and the general-purpose registers.

These instructions are privileged and cause a generalprotection exception (#GP) if non-privileged software attempts to execute them.LMSW and SMSW Instructions. The machine status word is located in CR0 register bits 15–0. Theload machine status word (LMSW) instruction writes only the least-significant four status-word bits(CR0[3:0]). All remaining status-word bits (CR0[15:4]) are left unmodified by the instruction.

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

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

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

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