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

Volume 1 Application Programming (794095), страница 29

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

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

3.13—July 2007Input/OutputI/O devices allow the processor to communicate with the outside world, usually to a human or toanother system. In fact, a system without I/O has little utility. Typical I/O devices include a keyboard,mouse, LAN connection, printer, storage devices, and monitor. The speeds these devices must operateat vary greatly, and usually depend on whether the communication is to a human (slow) or to anothermachine (fast). There are exceptions. For example, humans can consume graphics data at very highrates.There are two methods for communicating with I/O devices in AMD64 processor implementations.One method involves accessing I/O through ports located in I/O-address space (“I/O Addressing” onpage 90), and the other method involves accessing I/O devices located in the memory-address space(“Memory Organization” on page 9).

The address spaces are separate and independent of each other.I/O-address space was originally introduced as an optimized means for accessing I/O-device controlports. Then, systems usually had few I/O devices, devices tended to be relatively low-speed, deviceaccesses needed to be strongly ordered to guarantee proper operation, and device protectionrequirements were minimal or non-existent. Memory-mapped I/O has largely supplanted I/O-addressspace access as the preferred means for modern operating systems to interface with I/O devices.Memory-mapped I/O offers greater flexibility in protection, vastly more I/O ports, higher speeds, andstrong or weak ordering to suit the device requirements.3.8.1 I/O AddressingAccess to I/O-address space is provided by the IN and OUT instructions, and the string variants ofthese instructions, INS and OUTS. The operation of these instructions are described in “Input/Output”on page 63.

Although not required, processor implementations generally transmit I/O-port addressesand I/O data over the same external signals used for memory addressing and memory data. Differentbus-cycles generated by the processor differentiate I/O-address space accesses from memory-addressspace accesses.I/O-Address Space. Figure 3-18 on page 91 shows the 64 Kbyte I/O-address space.

I/O ports can beaddressed as bytes, words, or doublewords. As with memory addressing, word-I/O and doublewordI/O ports are simply two or four consecutively-addressed byte-I/O ports. Word and doubleword I/Oports can be aligned on any byte boundary, but there is typically a performance penalty for unalignedaccesses. Performance is optimized by aligning word-I/O ports on word boundaries, and doublewordI/O ports on doubleword boundaries.90General-Purpose Programming24592—Rev. 3.13—July 2007AMD64 TechnologyFFFF216 - 100000513-187.epsFigure 3-18.I/O Address SpaceMemory-Mapped I/O. Memory-mapped I/O devices are attached to the system memory bus andrespond to memory transactions as if they were memory devices, such as DRAM.

Access to memorymapped I/O devices can be performed using any instruction that accesses memory, but typically MOVinstructions are used to transfer data between the processor and the device. Some I/O devices may haverestrictions on read-modify-write accesses.Any location in memory can be used as a memory-mapped I/O address. System software can use thepaging facilities to virtualize memory devices and protect them from unauthorized access.

See“System-Management Instructions” in Volume 2 for a discussion of memory virtualization andpaging.3.8.2 I/O OrderingThe order of read and write accesses between the processor and an I/O device is usually important forproperly controlling device operation. Accesses to I/O-address space and memory-address space differin the default ordering enforced by the processor and the ability of software to control ordering.I/O-Address Space. The processor always orders I/O-address space operations strongly, with respectto other I/O and memory operations.

Software cannot modify the I/O ordering enforced by theprocessor. IN instructions are not executed until all previous writes to I/O space and memory havecompleted. OUT instructions delay execution of the following instruction until all writes—includingthe write performed by the OUT—have completed. Unlike memory writes, writes to I/O addresses arenever buffered by the processor.The processor can use more than one bus transaction to access an unaligned, multi-byte I/O port.Unaligned accesses to I/O-address space do not have a defined bus transaction ordering, and thatordering can change from one implementation to another.

If the use of an unaligned I/O port isrequired, and the order of bus transactions to that port is important, software should decompose theaccess into multiple, smaller aligned accesses.Memory-Mapped I/O. To maximize software performance, processor implementations can executeinstructions out of program order. This can cause the sequence of memory accesses to also be out ofprogram order, called weakly ordered. As described in “Accessing Memory” on page 93, the processorcan perform memory reads in any order, it can perform reads without knowing whether it requires theGeneral-Purpose Programming91AMD64 Technology24592—Rev.

3.13—July 2007result (speculation), and it can reorder reads ahead of writes. In the case of writes, multiple writes tomemory locations in close proximity to each other can be combined into a single write or a burst ofmultiple writes. Writes can also be delayed, or buffered, by the processor.Application software that needs to force memory ordering to memory-mapped I/O devices can do sousing the read/write barrier instructions: LFENCE, SFENCE, and MFENCE. These instructions aredescribed in “Forcing Memory Order” on page 94.

Serializing instructions, I/O instructions, andlocked instructions can also be used as read/write barriers, but they modify program state and are aninferior method for enforcing strong-memory ordering.Typically, the operating system controls access to memory-mapped I/O devices. The AMD64architecture provides facilities for system software to specify the types of accesses and their orderingfor entire regions of memory. These facilities are also used to manage the cacheability of memoryregions. See “System-Management Instructions” in Volume 2 for further information.3.8.3 Protected-Mode I/OIn protected mode, access to the I/O-address space is governed by the I/O privilege level (IOPL) fieldin the rFLAGS register, and the I/O-permission bitmap in the current task-state segment (TSS).I/O-Privilege Level.

RFLAGS.IOPL governs access to IOPL-sensitive instructions. All of the I/Oinstructions (IN, INS, OUT, and OUTS) are IOPL-sensitive. IOPL-sensitive instructions cannot beexecuted by a program unless the program’s current-privilege level (CPL) is numerically less (moreprivileged) than or equal to the RFLAGS.IOPL field, otherwise a general-protection exception (#GP)occurs.Only software running at CPL = 0 can change the RFLAGS.IOPL field. Two instructions, POPF andIRET, can be used to change the field. If application software (or any software running at CPL>0)attempts to change RFLAGS.IOPL, the attempt is ignored.System software uses RFLAGS.IOPL to control the privilege level required to access I/O-addressspace devices. Access can be granted on a program-by-program basis using different copies ofRFLAGS for every program, each with a different IOPL.

RFLAGS.IOPL acts as a global control overa program’s access to I/O-address space devices. System software can grant less-privileged programsaccess to individual I/O devices (overriding RFLAGS.IOPL) by using the I/O-permission bitmapstored in a program’s TSS. For details about the I/O-permission bitmap, see “I/O-Permission Bitmap”in Volume 2.3.9Memory OptimizationGenerally, application software is unaware of the memory hierarchy implemented within a particularsystem design.

The application simply sees a homogenous address space within a single level ofmemory. In reality, both system and processor implementations can use any number of techniques tospeed up accesses into memory, doing so in a manner that is transparent to applications. Applicationsoftware can be written to maximize this speed-up even though the methods used by the hardware arenot visible to the application. This section gives an overview of the memory hierarchy and access92General-Purpose Programming24592—Rev.

3.13—July 2007AMD64 Technologytechniques that can be implemented within a system design, and how applications can optimize theiruse.3.9.1 Accessing MemoryImplementations of the AMD64 architecture commit the results of each instruction—i.e., store theresult of the executed instruction in software-visible resources, such as a register (including flags), thedata cache, an internal write buffer, or memory—in program order, which is the order specified by theinstruction sequence in a program.

Transparent to the application, implementations can executeinstructions in any order and temporarily hold out-of-order results until the instructions are committed.Implementations can also speculatively execute instructions—executing instructions before knowingtheir results will be used (for example, executing both sides of a branch). By executing instructionsout-of-order and speculatively, a processor can boost application performance by executinginstructions that are ready, rather than delaying them behind instructions that are waiting for data.However, the processor commits results in program order (the order expected by software).When executing instructions out-of-order and speculatively, processor implementations often find ituseful to also allow out-of-order and speculative memory accesses.

However, such memory accessesare potentially visible to software and system devices. The following sections describe thearchitectural rules for memory accesses. See “Memory System” in Volume 2 for information on howsystem software can further specify the flexibility of memory accesses.Read Ordering. The ordering of memory reads does not usually affect program execution becausethe ordering does not usually affect the state of software-visible resources. The rules governing readordering are:•••Out-of-order reads are allowed. Out-of-order reads can occur as a result of out-of-order instructionexecution.

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

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

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

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