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

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

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

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

The size, organization,coherency mechanism, and replacement algorithm for each cache is implementation dependent.Generally, the existence of the caches is transparent to both application and system software. In somecases, however, software can use cache-structure information to optimize memory accesses or managememory coherency. Such software can use the extended-feature functions of the CPUID instruction togather information on the caching subsystem supported by the processor. For more information onusing CPUID in this manner, see the AMD CPUID Specification, order# 25481.7.6.1 Cache Organization and OperationAlthough the detailed organization of a processor cache depends on the implementation, the generalconstructs are similar.

L1 caches—data and instruction, or unified—and L2 caches usually areimplemented as n-way set-associative caches. Figure 7-3 on page 175 shows a typical logicalorganization of an n-way set-associative cache. The physical implementation of the cache can be quitedifferent.174Memory System24593—Rev. 3.13—July 2007AMD64 TechnologyWay 0TagData. . .Way 1OtherTagDataOtherWay n-1TagDataOtherSet 0Set 1Set 2Line Data 1,2Line Data 0,2Line Data n-1,2Set 3. . .Set m-1MissMiss=HitMiss. . .==HitHitMUX n:1DataCacheHit DataPhysical AddressTag FieldIndex FieldOffset Field513-213.epsFigure 7-3. Cache Organization ExampleAs shown in Figure 7-3, the cache is organized as an array of cache lines.

Each cache line consists ofthree parts: a cache-data line (a fixed-size copy of a memory block), a tag, and other information. Rowsof cache lines in the cache array are sets, and columns of cache lines are ways. In an n-way setassociative cache, each set is a collection of n lines. For example, in a four-way set-associative cache,each set is a collection of four cache lines, one from each way.Memory System175AMD64 Technology24593—Rev. 3.13—July 2007The cache is accessed using the physical address of the data or instruction being referenced. To accessdata within a cache line, the physical address is used to select the set, way, and byte from the cache.This is accomplished by dividing the physical address into the following three fields:•••Index—The index field selects the cache set (row) to be examined for a hit. All cache lines withinthe set (one from each way) are selected by the index field.Tag—The tag field is used to select a specific cache line from the cache set.

The physical-addresstag field is compared with each cache-line tag in the set. If a match is found, a cache hit issignalled, and the appropriate cache line is selected from the set. If a match is not found, a cachemiss is signalled.Offset—The offset field points to the first byte in the cache line corresponding to the memoryreference. The referenced data or instruction value is read from (or written to, in the case ofmemory writes) the selected cache line starting at the location selected by the offset field.In Figure 7-3 on page 175, the physical-address index field is shown selecting Set 2 from the cache.The tag entry for each cache line in the set is compared with the physical-address tag field.

The tagentry for Way 1 matches the physical-address tag field, so the cache-line data for Set 2, Way 1 isselected using the n:1 multiplexor. Finally, the physical-address offset field is used to point to the firstbyte of the referenced data (or instruction) in the selected cache line.Cache lines can contain other information in addition to the data and tags, as shown in Figure 7-3 onpage 175. MOESI state and the state bits associated with the cache-replacement algorithm are typicalpieces of information kept with the cache line.

Instruction caches can also contain pre-decode orbranch-prediction information. The type of information stored with the cache line is implementationdependent.Self-Modifying Code. Software that writes into the code segment from which it was fetched isclassified as self-modifying code. To avoid cache-coherency problems due to self-modifying code, acheck is made during data writes to see whether the data-memory location corresponds to a codesegment memory location.

If it does, implementations of the AMD64 architecture invalidate thecorresponding instruction-cache line(s) during the data-memory write. Entries in the data cache arenot invalidated, and it is possible for the modified instruction to be cached by the data cache followingthe memory write. A subsequent fetch of the modified instruction goes to main memory to get thecoherent version of the instruction. If the data cache holds the most recent copy of the instructionrather than main memory, it provides that copy.The processor determines whether a write is in a code segment by internally probing the instructioncache and prefetched instructions. If the internal probe returns a hit, the instruction-cache line andprefetched instructions are invalidated. The internal probes into the instruction cache and prefetchhardware are always performed using the physical address of an instruction in order to avoid potentialaliasing problems associated with using virtual (linear) addresses.Software that stores into a code segment running simultaneously on another processor with the intentthat the other processor execute the written data as code is classified as cross-modifying code.

To avoidcache-coherency issues when using cross-modifying code, the processor doing the store should176Memory System24593—Rev. 3.13—July 2007AMD64 Technologyprovide synchronization between the processors using locked semaphores. Synchronization for crossmodifying code is not required for code that resides within the naturally aligned quadword.7.6.2 Cache Control MechanismsThe AMD64 architecture provides a number of mechanisms for controlling the cacheability ofmemory. These are described in the following sections.Cache Disable. Bit 30 of the CR0 register is the cache-disable bit, CR0.CD. Caching is enabledwhen CR0.CD is cleared to 0, and caching is disabled when CR0.CD is set to 1. When caching isdisabled, reads and writes access main memory.Software can disable the cache while the cache still holds valid data (or instructions). If a read or writehits the L1 data cache or the L2 cache when CR0.CD=1, the processor does the following:1.

Writes the cache line back if it is in the modified or owned state.2. Invalidates the cache line.3. Performs a non-cacheable main-memory access to read or write the data.If an instruction fetch hits the L1 instruction cache when CR0.CD=1, the processor reads the cachedinstructions rather than access main memory.The processor also responds to cache probes when CR0.CD=1. Probes that hit the cache cause theprocessor to perform Step 1. Step 2 (cache-line invalidation) is performed only if the probe isperformed on behalf of a memory write or an exclusive read.Writethrough Disable. Bit 29 of the CR0 register is the not writethrough disable bit, CR0.NW. Inearly x86 processors, CR0.NW is used to control cache writethrough behavior, and the combination ofCR0.NW and CR0.CD determines the cache operating mode.In early x86 processors, clearing CR0.NW to 0 enables writeback caching for main memory,effectively disabling writethrough caching for main memory.

When CR0.NW=0, software can disablewriteback caching for specific memory pages or regions by using other cache control mechanisms.When software sets CR0.NW to 1, writeback caching is disabled for main memory, whilewritethrough caching is enabled.In implementations of the AMD64 architecture, CR0.NW is not used to qualify the cache operatingmode established by CR0.CD. Table 7-4 shows the effects of CR0.NW and CR0.CD on the AMD64architecture cache-operating modes.Table 7-4.

AMD64 Architecture Cache-Operating ModesCR0.CDCR0.NW00Cache enabled with a writeback-caching policy.01Invalid setting—causes a general-protection exception (#GP).1011Memory SystemCache Operating ModeCache disabled. See “Cache Disable” on page 177.177AMD64 Technology24593—Rev. 3.13—July 2007Page-Level Cache Disable.

Bit 4 of all paging data-structure entries controls page-level cachedisable (PCD). When a data-structure-entry PCD bit is cleared to 0, the page table or physical pagepointed to by that entry is cacheable, as determined by the CR0.CD bit. When the PCD bit is set to 1,the page table or physical page is not cacheable. The PCD bit in the paging data-structure base-register(bit 4 in CR3) controls the cacheability of the highest-level page table in the page-translation hierarchy.Page-Level Writethrough Enable. Bit 3 of all paging data-structure entries is the page-levelwritethrough enable control (PWT).

When a data-structure-entry PWT bit is cleared to 0, the pagetable or physical page pointed to by that entry has a writeback caching policy. When the PWT bit is setto 1, the page table or physical page has a writethrough caching policy. The PWT bit in the pagingdata-structure base-register (bit 3 in CR3) controls the caching policy of the highest-level page table inthe page-translation hierarchy.The corresponding PCD bit must be cleared to 0 (page caching enabled) for the PWT bit to have aneffect.Memory Typing.

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

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

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

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