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

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

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

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

This flag allows cachingto be disabled on a page-by-page basis. See “Page-Directory and Page-Table Entries”in Chapter 3 of in the Intel® 64 and IA-32 Architectures Software Developer’sManual, Volume 3A.13.4I/O INSTRUCTIONSThe processor’s I/O instructions provide access to I/O ports through the I/O addressspace. (These instructions cannot be used to access memory-mapped I/O ports.)There are two groups of I/O instructions:•Those that transfer a single item (byte, word, or doubleword) between an I/Oport and a general-purpose registerVol. 1 13-3INPUT/OUTPUT•Those that transfer strings of items (strings of bytes, words, or doublewords)between an I/O port and memoryThe register I/O instructions IN (input from I/O port) and OUT (output to I/O port)move data between I/O ports and the EAX register (32-bit I/O), the AX register(16-bit I/O), or the AL (8-bit I/O) register.

The address of the I/O port can be givenwith an immediate value or a value in the DX register.The string I/O instructions INS (input string from I/O port) and OUTS (output stringto I/O port) move data between an I/O port and a memory location. The address ofthe I/O port being accessed is given in the DX register; the source or destinationmemory address is given in the DS:ESI or ES:EDI register, respectively.When used with one of the repeat prefixes (such as REP), the INS and OUTS instructions perform string (or block) input or output operations. The repeat prefix REPmodifies the INS and OUTS instructions to transfer blocks of data between an I/Oport and memory.

Here, the ESI or EDI register is incremented or decremented(according to the setting of the DF flag in the EFLAGS register) after each byte, word,or doubleword is transferred between the selected I/O port and memory.See the references for IN, INS, OUT, and OUTS in Chapter 3 and Chapter 4 of theIntel® 64 and IA-32 Architectures Software Developer’s Manual, Volumes 3A & 3B,for more information on these instructions.13.5PROTECTED-MODE I/OWhen the processor is running in protected mode, the following protection mechanisms regulate access to I/O ports:•When accessing I/O ports through the I/O address space, two protection devicescontrol access:— The I/O privilege level (IOPL) field in the EFLAGS register— The I/O permission bit map of a task state segment (TSS)•When accessing memory-mapped I/O ports, the normal segmentation andpaging protection and the MTRRs (in processors that support them) also affectaccess to I/O ports.

See Chapter 4, “Protection,” and Chapter 10, “Memory CacheControl,” in the Intel® 64 and IA-32 Architectures Software Developer’s Manual,Volume 3A, for a complete discussion of memory protection.The following sections describe the protection mechanisms available when accessingI/O ports in the I/O address space with the I/O instructions.13.5.1I/O Privilege LevelIn systems where I/O protection is used, the IOPL field in the EFLAGS registercontrols access to the I/O address space by restricting use of selected instructions.This protection mechanism permits the operating system or executive to set the priv-13-4 Vol.

1INPUT/OUTPUTilege level needed to perform I/O. In a typical protection ring model, access to theI/O address space is restricted to privilege levels 0 and 1. Here, kernel and the devicedrivers are allowed to perform I/O, while less privileged device drivers and application programs are denied access to the I/O address space. Application programsmust then make calls to the operating system to perform I/O.The following instructions can be executed only if the current privilege level (CPL) ofthe program or task currently executing is less than or equal to the IOPL: IN, INS,OUT, OUTS, CLI (clear interrupt-enable flag), and STI (set interrupt-enable flag).These instructions are called I/O sensitive instructions, because they are sensitiveto the IOPL field.

Any attempt by a less privileged program or task to use an I/Osensitive instruction results in a general-protection exception (#GP) being signaled.Because each task has its own copy of the EFLAGS register, each task can have adifferent IOPL.The I/O permission bit map in the TSS can be used to modify the effect of the IOPLon I/O sensitive instructions, allowing access to some I/O ports by less privilegedprograms or tasks (see Section 13.5.2, “I/O Permission Bit Map”).A program or task can change its IOPL only with the POPF and IRET instructions;however, such changes are privileged. No procedure may change the current IOPLunless it is running at privilege level 0.

An attempt by a less privileged procedure tochange the IOPL does not result in an exception; the IOPL simply remainsunchanged.The POPF instruction also may be used to change the state of the IF flag (as can theCLI and STI instructions); however, the POPF instruction in this case is also I/O sensitive. A procedure may use the POPF instruction to change the setting of the IF flagonly if the CPL is less than or equal to the current IOPL. An attempt by a less privileged procedure to change the IF flag does not result in an exception; the IF flagsimply remains unchanged.13.5.2I/O Permission Bit MapThe I/O permission bit map is a device for permitting limited access to I/O ports byless privileged programs or tasks and for tasks operating in virtual-8086 mode.

TheI/O permission bit map is located in the TSS (see Figure 13-2) for the currentlyrunning task or program. The address of the first byte of the I/O permission bit mapis given in the I/O map base address field of the TSS. The size of the I/O permissionbit map and its location in the TSS are variable.Vol. 1 13-5INPUT/OUTPUTTask State Segment (TSS)Last byte ofbit3124 23map must befollowed by aI/O mapbase mustnot exceedDFFFH.01 1 1 1 1 1 1 1I/O Permission Bit MapI/O Map Base64H0Figure 13-2. I/O Permission Bit MapBecause each task has its own TSS, each task has its own I/O permission bit map.Access to individual I/O ports can thus be granted to individual tasks.If in protected mode and the CPL is less than or equal to the current IOPL, theprocessor allows all I/O operations to proceed. If the CPL is greater than the IOPL orif the processor is operating in virtual-8086 mode, the processor checks the I/Opermission bit map to determine if access to a particular I/O port is allowed.

Each bitin the map corresponds to an I/O port byte address. For example, the control bit forI/O port address 29H in the I/O address space is found at bit position 1 of the sixthbyte in the bit map. Before granting I/O access, the processor tests all the bits corresponding to the I/O port being addressed. For a doubleword access, for example, theprocessors tests the four bits corresponding to the four adjacent 8-bit portaddresses.

If any tested bit is set, a general-protection exception (#GP) is signaled.If all tested bits are clear, the I/O operation is allowed to proceed.Because I/O port addresses are not necessarily aligned to word and doublewordboundaries, the processor reads two bytes from the I/O permission bit map for everyaccess to an I/O port. To prevent exceptions from being generated when the portswith the highest addresses are accessed, an extra byte needs to included in the TSSimmediately after the table.

This byte must have all of its bits set, and it must bewithin the segment limit.It is not necessary for the I/O permission bit map to represent all the I/O addresses.I/O addresses not spanned by the map are treated as if they had set bits in the map.For example, if the TSS segment limit is 10 bytes past the bit-map base address, themap has 11 bytes and the first 80 I/O ports are mapped. Higher addresses in the I/Oaddress space generate exceptions.13-6 Vol.

1INPUT/OUTPUTIf the I/O bit map base address is greater than or equal to the TSS segment limit,there is no I/O permission map, and all I/O instructions generate exceptions whenthe CPL is greater than the current IOPL.13.6ORDERING I/OWhen controlling I/O devices it is often important that memory and I/O operations becarried out in precisely the order programmed. For example, a program may write acommand to an I/O port, then read the status of the I/O device from another I/Oport. It is important that the status returned be the status of the device after itreceives the command, not before.When using memory-mapped I/O, caution should be taken to avoid situations inwhich the programmed order is not preserved by the processor.

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

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

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

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