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

Volume 3A System Programming Guide_ Part 1 (794103), страница 78

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

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

3MULTIPLE-PROCESSOR MANAGEMENT//Returns the max number of logical processors per physical processor package;// the actual number of logical processors per package enabled by OS may be less.// Software should not assume the value a power of 2.unsigned char MaxLPPerPackage(void){if (!HWMTSupported()) return 1;execute cpuid with eax = 1store returned value of ebxreturn (unsigned char) ((reg_ebx & NUM_LOGICAL_BITS) >> 16);}3.Find the max number of processor cores per physical processor package.// Returns the max number of processor cores per physical processor package;// the actual number of processor cores per package that are enabled may be less.// Software should not assume cpuid reports the value of// “maximum number of cores per physical processor” must be power of 2.unsigned MaxCoresPerPackage(void){if (!HWMTSupported()) return (unsigned char) 1;if cpuid supports leaf number 4{ // we can retrieve multi-core topology info using leaf 4execute cpuid with eax = 4, ecx = 0store returned value of eaxreturn (unsigned ) ((reg_eax >> 26) +1);}else // must be a single-core processorreturn 1;}4.Extract the initial APIC ID of a logical processor.#define INITIAL_APIC_ID_BITS 0xFF000000 // CPUID.1.EBX[31:24] initial APIC ID// Returns the 8-bit unique initial APIC ID for the processor running the code.// Software can use OS services to affinitize the current thread to each logical processor// available under the OS to gather the initial APIC_IDs for each logical processor.unsigned char GetInitAPIC_ID (void){unsigned int reg_ebx = 0;execute cpuid with eax = 1Vol.

3 7-41MULTIPLE-PROCESSOR MANAGEMENTstore returned value of ebxreturn (unsigned char) ((reg_ebx & INITIAL_APIC_ID_BITS) >> 24;}5.Find the width of a bit-field mask from the maximum count of the bit-field.// Returns the mask bit width of a bit field from the maximum count that bit field can represent.// This algorithm does not assume ‘Max_Count’ to have a value equal to power of 2.unsigned FindMaskWidth(Unsigned Max_Count){unsigned int mask_width, cnt = Max_Count;__asm {mov eax, cntmov ecx, 0mov mask_width, ecxdec eaxbsr cx, axjz nextinc cxmov mask_width, ecxnext:mov eax, mask_width}return mask_width;}6.Extract a sub ID given a full ID, maximum sub ID value and shift count.// Returns the value of the sub ID, this is not a zero-based valueUnsigned char GetSubID(unsigned char Full_ID, unsigned char MaxSubIDvalue, unsigned charShift_Count){MaskWidth = FindMaskWidth(MaxSubIDValue);MaskBits = ((uchar) (0xff << Shift_Count)) ^ ((uchar) (0xff << Shift_Count + MaskWidth)) ;SubID = Full_ID & MaskBits;Return SubID;}Software must not assume local APIC_ID values in an MP system are consecutive.Non-consecutive local APIC_IDs may be the result of hardware configurations ordebug features implemented in the BIOS or OS.An identifier for each hierarchical level can be extracted from an 8-bit APIC_ID usingthe support routines illustrated in Example 7-1.

The appropriate bit mask and shiftvalue to construct the appropriate bit mask for each level must be determineddynamically at runtime.7-42 Vol. 3MULTIPLE-PROCESSOR MANAGEMENT7.10.4Identifying Topological Relationships in a MP SystemTo detect the number of physical packages, processor cores, or other topologicalrelationships in a MP system, the following procedures are recommended:•Extract the three-level identifiers from the APIC ID of each logical processorenabled by system software.

The sequence is as follows (See the pseudo codeshown in Example 7-2 and support routines shown in Example 7-1):•The extraction start from the right-most bit field, corresponding toSMT_ID, the innermost hierarchy in a three-level topology (See Figure7-6). For the right-most bit field, the shift value of the working mask iszero. The width of the bit field is determined dynamically using themaximum number of logical processor per core, which can be derivedfrom information provided from CPUID.•To extract the next bit-field, the shift value of the working mask isdetermined from the width of the bit mask of the previous step.

The widthof the bit field is determined dynamically using the maximum number ofcores per package.•To extract the remaining bit-field, the shift value of the working mask isdetermined from the maximum number of logical processor per package.So the remaining bits in the APIC ID (excluding those bits alreadyextracted in the two previous steps) are extracted as the third identifier.This applies to a non-clustered MP system, or if there is no need todistinguish between PACKAGE_ID and CLUSTER_ID.If there is need to distinguish between PACKAGE_ID and CLUSTER_ID,PACKAGE_ID can be extracted using an algorithm similar to theextraction of CORE_ID, assuming the number of physical packages ineach node of a clustered system is symmetric.•Assemble the three-level identifiers of SMT_ID, CORE_ID, PACKAGE_IDs intoarrays for each enabled logical processor.

This is shown in Example 7-3a.•To detect the number of physical packages: use PACKAGE_ID to identify thoselogical processors that reside in the same physical package. This is shown inExample 7-3b. This example also depicts a technique to construct a mask torepresent the logical processors that reside in the same package.•To detect the number of processor cores: use CORE_ID to identify those logicalprocessors that reside in the same core. This is shown in Example 7-3. Thisexample also depicts a technique to construct a mask to represent the logicalprocessors that reside in the same core.In Example 7-2, the numerical ID value can be obtained from the value extractedwith the mask by shifting it right by shift count. Algorithms below do not shift thevalue.

The assumption is that the SubID values can be compared for equivalencewithout the need to shift.Vol. 3 7-43MULTIPLE-PROCESSOR MANAGEMENTExample 7-2. Pseudo Code Depicting Three-level Extraction AlgorithmFor Each local_APIC_ID{// Determine MaxLPPerCore available in hardware// This algorithm assumes there is symmetry across core boundary, i.e. each core within a// package has the same number of logical processorsMaxLPPerCore = MaxLPPerPackage()/MaxCoresPerPackage();// Extract SMT_ID first, this is the innermost of the three levels// bit mask width is determined from MaxLPPerCore topological info.// shift size is 0, corresponding to the right-most bit-fieldSMT_ID = GetSubID(local_APIC_ID, MaxLPPerCore, 0);// Extract CORE_ID:// bit width is determined from maximum number of cores per package possible in hardware// shift count is determined by maximum logical processors per core in hardwareCORE_ID = GetSubID(InitAPIC_ID, MaxCoresPerPackage(), FindMaskWidth(MaxLPPerCore));// Extract PACKAGE_ID:// Assume single cluster.// Shift out the mask width for maximum logical processors per packagePackageIDMask = ((uchar) (0xff << FindMaskWidth(MaxLPPerPackage()));PACKAGE_ID = InitAPIC_ID & PackageIDMask;}Example 7-3.

Compute the Number of Packages, Cores, and Processor Relationships in a MPSystema) Assemble lists of PACKAGE_ID, CORE_ID, and SMT_ID of each enabled logical processors//The BIOS and/or OS may limit the number of logical processors available to applications// after system boot. The below algorithm will compute topology for the processors visible// to the thread that is computing it.// Extract the 3-levels of IDs on every processor// SystemAffinity is a bitmask of all the processors started by the OS. Use OS specific APIs to// obtain it.// ThreadAffinityMask is used to affinitize the topology enumeration thread to each processorusing OS specific APIs.// Allocate per processor arrays to store the Package_ID, Core_ID and SMT_ID for every started// processor.ThreadAffinityMask = 1;ProcessorNum = 0;7-44 Vol.

3MULTIPLE-PROCESSOR MANAGEMENTwhile (ThreadAffinityMask != 0 && ThreadAffinityMask <= SystemAffinity) {// Check to make sure we can utilize this processor first.if (ThreadAffinityMask & SystemAffinity){Set thread to run on the processor specified in ThreadAffinityMaskWait if necessary and ensure thread is running on specified processorInitAPIC_ID = GetInitAPIC_ID();Extract the Package, Core and SMT ID as explained in three level extractionalgorithmPackageID[ProcessorNUM] = PACKAGE_ID;CoreID[ProcessorNum] = CORE_ID;SmtID[ProcessorNum] = SMT_ID;ProcessorNum++;}ThreadAffinityMask <<= 1;}NumStartedLPs = ProcessorNum;b) Using the list of PACKAGE_ID to count the number of physical packages in a MP system andconstruct, for each package, a multi-bit mask corresponding to those logical processors residing inthe same package.// Compute the number of packages by counting the number of processors// with unique PACKAGE_IDs in the PackageID array.// Compute the mask of processors in each package.PackageIDBucket is an array of unique PACKAGE_ID values.

Allocate an array ofNumStartedLPs count of entries in this array.PackageProcessorMask is a corresponding array of the bit mask of processors belonging tothe same package, these are processors with the same PACKAGE_IDThe algorithm below assumes there is symmetry across package boundary if more thanone socket is populated in an MP system.// Bucket Package IDs and compute processor mask for every package.PackageNum = 1;PackageIDBucket[0] = PackageID[0];ProcessorMask = 1;PackageProcessorMask[0] = ProcessorMask;For (ProcessorNum = 1; ProcessorNum < NumStartedLPs; ProcessorNum++) {ProcessorMask << = 1;For (i=0; i < PackageNum; i++) {// we may be comparing bit-fields of logical processors residing in different// packages, the code below assume package symmetryIf (PackageID[ProcessorNum] == PackageIDBucket[i]) {Vol.

3 7-45MULTIPLE-PROCESSOR MANAGEMENTPackageProcessorMask[i] |= ProcessorMask;Break; // found in existing bucket, skip to next iteration}}if (i ==PackageNum) {//PACKAGE_ID did not match any bucket, start new bucketPackageIDBucket[i] = PackageID[ProcessorNum];PackageProcessorMask[i] = ProcessorMask;PackageNum++;}}// PackageNum has the number of Packages started in OS// PackageProcessorMask[] array has the processor set of each packagec) Using the list of CORE_ID to count the number of cores in a MP system and construct, for eachcore, a multi-bit mask corresponding to those logical processors residing in the same core.Processors in the same core can be determined by bucketing the processors with the samePACKAGE_ID and CORE_ID.

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

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

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

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