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

Volume 3B System Programming Guide_ Part 2 (794104), страница 24

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

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

When set, performance counting is enabled in bothperformance-monitoring counters; when clear, both counters are disabled.•INV (invert) flag (bit 23) — Inverts the result of the counter-mask comparisonwhen set, so that both greater than and less than comparisons can be made.18-114 Vol. 3DEBUGGING AND PERFORMANCE MONITORING•Counter mask (CMASK) field (bits 24 through 31) — When nonzero, theprocessor compares this mask to the number of events counted during a singlecycle.

If the event count is greater than or equal to this mask, the counter isincremented by one. Otherwise the counter is not incremented. This mask can beused to count events only if multiple occurrences happen per clock (for example,two or more instructions retired per clock). If the counter-mask field is 0, thenthe counter is incremented each cycle by the number of events that occurred thatcycle.18.21.2 PerfCtr0 and PerfCtr1 MSRsThe performance-counter MSRs (PerfCtr0 and PerfCtr1) contain the event or durationcounts for the selected events being counted. The RDPMC instruction can be used byprograms or procedures running at any privilege level and in virtual-8086 mode toread these counters.

The PCE flag in control register CR4 (bit 8) allows the use of thisinstruction to be restricted to only programs and procedures running at privilegelevel 0.The RDPMC instruction is not serializing or ordered with other instructions. Thus, itdoes not necessarily wait until all previous instructions have been executed beforereading the counter. Similarly, subsequent instructions may begin execution beforethe RDPMC instruction operation is performed.Only the operating system, executing at privilege level 0, can directly manipulate theperformance counters, using the RDMSR and WRMSR instructions.

A secure operating system would clear the PCE flag during system initialization to disable directuser access to the performance-monitoring counters, but provide a user-accessibleprogramming interface that emulates the RDPMC instruction.The WRMSR instruction cannot arbitrarily write to the performance-monitoringcounter MSRs (PerfCtr0 and PerfCtr1). Instead, the lower-order 32 bits of each MSRmay be written with any value, and the high-order 8 bits are sign-extended accordingto the value of bit 31.

This operation allows writing both positive and negative valuesto the performance counters.18.21.3 Starting and Stopping the Performance-Monitoring CountersThe performance-monitoring counters are started by writing valid setup informationin the PerfEvtSel0 and/or PerfEvtSel1 MSRs and setting the enable counters flag inthe PerfEvtSel0 MSR. If the setup is valid, the counters begin counting following theexecution of a WRMSR instruction that sets the enable counter flag. The counters canbe stopped by clearing the enable counters flag or by clearing all the bits in thePerfEvtSel0 and PerfEvtSel1 MSRs. Counter 1 alone can be stopped by clearing thePerfEvtSel1 MSR.Vol. 3 18-115DEBUGGING AND PERFORMANCE MONITORING18.21.4 Event and Time-Stamp Monitoring SoftwareTo use the performance-monitoring counters and time-stamp counter, the operatingsystem needs to provide an event-monitoring device driver.

This driver shouldinclude procedures for handling the following operations:•••••Feature checkingInitialize and start countersStop countersRead the event countersRead the time-stamp counterThe event monitor feature determination procedure must check whether the currentprocessor supports the performance-monitoring counters and time-stamp counter.This procedure compares the family and model of the processor returned by theCPUID instruction with those of processors known to support performance monitoring.

(The Pentium and P6 family processors support performance counters.) Theprocedure also checks the MSR and TSC flags returned to register EDX by the CPUIDinstruction to determine if the MSRs and the RDTSC instruction are supported.The initialize and start counters procedure sets the PerfEvtSel0 and/or PerfEvtSel1MSRs for the events to be counted and the method used to count them and initializesthe counter MSRs (PerfCtr0 and PerfCtr1) to starting counts.

The stop countersprocedure stops the performance counters (see Section 18.21.3, “Starting and Stopping the Performance-Monitoring Counters”).The read counters procedure reads the values in the PerfCtr0 and PerfCtr1 MSRs, anda read time-stamp counter procedure reads the time-stamp counter. These procedures would be provided in lieu of enabling the RDTSC and RDPMC instructions thatallow application code to read the counters.18.21.5 Monitoring Counter OverflowThe P6 family processors provide the option of generating a local APIC interrupt whena performance-monitoring counter overflows.

This mechanism is enabled by settingthe interrupt enable flag in either the PerfEvtSel0 or the PerfEvtSel1 MSR. Theprimary use of this option is for statistical performance sampling.To use this option, the operating system should do the following things on theprocessor for which performance events are required to be monitored:••Provide an interrupt vector for handling the counter-overflow interrupt.•Provide an entry in the IDT that points to a stub exception handler that returnswithout executing any instructions.•Provide an event monitor driver that provides the actual interrupt handler andmodifies the reserved IDT entry to point to its interrupt routine.Initialize the APIC PERF local vector entry to enable handling of performancemonitor counter overflow events.18-116 Vol.

3DEBUGGING AND PERFORMANCE MONITORINGWhen interrupted by a counter overflow, the interrupt handler needs to perform thefollowing actions:•Save the instruction pointer (EIP register), code-segment selector, TSS segmentselector, counter values and other relevant information at the time of theinterrupt.•Reset the counter to its initial setting and return from the interrupt.An event monitor application utility or another application program can read theinformation collected for analysis of the performance of the profiled application.18.22PERFORMANCE MONITORING (PENTIUMPROCESSORS)The Pentium processor provides two 40-bit performance counters, which can be usedto count events or measure duration.

The counters are supported by three MSRs: thecontrol and event select MSR (CESR) and the performance counter MSRs (CTR0 andCTR1). These can be read from and written to using the RDMSR and WRMSR instructions, respectively. They can be accessed using these instructions only when operating at privilege level 0.Each counter has an associated external pin (PM0/BP0 and PM1/BP1), which can beused to indicate the state of the counter to external hardware.NOTESThe CESR, CTR0, and CTR1 MSRs and the events listed in Table A-15are model-specific for the Pentium processor.The performance-monitoring events listed in Appendix A areintended to be used as guides for performance tuning. Countervalues reported are not guaranteed to be accurate and should beused as a relative guide for tuning.

Known discrepancies aredocumented where applicable.18.22.1 Control and Event Select Register (CESR)The 32-bit control and event select MSR (CESR) controls the operation of performance-monitoring counters CTR0 and CTR1 and the associated pins (seeFigure 18-43). To control each counter, the CESR register contains a 6-bit eventselect field (ES0 and ES1), a pin control flag (PC0 and PC1), and a 3-bit countercontrol field (CC0 and CC1). The functions of these fields are as follows:•ES0 and ES1 (event select) fields (bits 0-5, bits 16-21) — Selects (byentering an event code in the field) up to two events to be monitored.

See TableA-15 for a list of available event codes.Vol. 3 18-117DEBUGGING AND PERFORMANCE MONITORING3126 25 24PC1CC122 2116 1510 9 8ES1PC06 5CC00ESOPC1—Pin control 1CC1—Counter control 1ES1—Event select 1PC0—Pin control 0CC0—Counter control 0ES0—Event select 0ReservedFigure 18-43. CESR MSR (Pentium Processor Only)•CC0 and CC1 (counter control) fields (bits 6-8, bits 22-24) — Controls theoperation of the counter. Control codes are as follows:000 — Count nothing (counter disabled)001 — Count the selected event while CPL is 0, 1, or 2010 — Count the selected event while CPL is 3011 — Count the selected event regardless of CPL100 — Count nothing (counter disabled)101 — Count clocks (duration) while CPL is 0, 1, or 2110 — Count clocks (duration) while CPL is 3111 — Count clocks (duration) regardless of CPLThe highest order bit selects between counting events and counting clocks(duration); the middle bit enables counting when the CPL is 3; and the low-orderbit enables counting when the CPL is 0, 1, or 2.•PC0 and PC1 (pin control) flags (bits 9, 25) — Selects the function of theexternal performance-monitoring counter pin (PM0/BP0 and PM1/BP1).

Settingone of these flags to 1 causes the processor to assert its associated pin when thecounter has overflowed; setting the flag to 0 causes the pin to be asserted whenthe counter has been incremented. These flags permit the pins to be individuallyprogrammed to indicate the overflow or incremented condition.

The externalsignalling of the event on the pins will lag the internal event by a few clocks as thesignals are latched and buffered.While a counter need not be stopped to sample its contents, it must be stopped andcleared or preset before switching to a new event. It is not possible to set onecounter separately.

If only one event needs to be changed, the CESR register must18-118 Vol. 3DEBUGGING AND PERFORMANCE MONITORINGbe read, the appropriate bits modified, and all bits must then be written back toCESR. At reset, all bits in the CESR register are cleared.18.22.2 Use of the Performance-Monitoring PinsWhen performance-monitor pins PM0/BP0 and/or PM1/BP1 are configured to indicatewhen the performance-monitor counter has incremented and an “occurrence event”is being counted, the associated pin is asserted (high) each time the event occurs.When a “duration event” is being counted, the associated PM pin is asserted for theentire duration of the event.

When the performance-monitor pins are configured toindicate when the counter has overflowed, the associated PM pin is asserted whenthe counter has overflowed.When the PM0/BP0 and/or PM1/BP1 pins are configured to signal that a counter hasincremented, it should be noted that although the counters may increment by 1 or 2in a single clock, the pins can only indicate that the event occurred. Moreover, sincethe internal clock frequency may be higher than the external clock frequency, asingle external clock may correspond to multiple internal clocks.A “count up to” function may be provided when the event pin is programmed tosignal an overflow of the counter. Because the counters are 40 bits, a carry out of bit39 indicates an overflow. A counter may be preset to a specific value less then 240 −1.

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

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

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

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