Tsx инструкция процессора что это

From Wikipedia, the free encyclopedia

Transactional Synchronization Extensions (TSX), also called Transactional Synchronization Extensions New Instructions (TSX-NI), is an extension to the x86 instruction set architecture (ISA) that adds hardware transactional memory support, speeding up execution of multi-threaded software through lock elision. According to different benchmarks, TSX/TSX-NI can provide around 40% faster applications execution in specific workloads, and 4–5 times more database transactions per second (TPS).[1][2][3][4]

TSX/TSX-NI was documented by Intel in February 2012, and debuted in June 2013 on selected Intel microprocessors based on the Haswell microarchitecture.[5][6][7] Haswell processors below 45xx as well as R-series and K-series (with unlocked multiplier) SKUs do not support TSX/TSX-NI.[8] In August 2014, Intel announced a bug in the TSX/TSX-NI implementation on current steppings of Haswell, Haswell-E, Haswell-EP and early Broadwell CPUs, which resulted in disabling the TSX/TSX-NI feature on affected CPUs via a microcode update.[9][10]

In 2016, a side-channel timing attack was found by abusing the way TSX/TSX-NI handles transactional faults (i.e. page faults) in order to break kernel address space layout randomization (KASLR) on all major operating systems.[11] In 2021, Intel released a microcode update that disabled the TSX/TSX-NI feature on CPU generations from Skylake to Coffee Lake, as a mitigation for discovered security issues.[12]

Support for TSX/TSX-NI emulation is provided as part of the Intel Software Development Emulator.[13] There is also experimental support for TSX/TSX-NI emulation in a QEMU fork.[14]

Features[edit]

TSX/TSX-NI provides two software interfaces for designating code regions for transactional execution. Hardware Lock Elision (HLE) is an instruction prefix-based interface designed to be backward compatible with processors without TSX/TSX-NI support. Restricted Transactional Memory (RTM) is a new instruction set interface that provides greater flexibility for programmers.[15]

TSX/TSX-NI enables optimistic execution of transactional code regions. The hardware monitors multiple threads for conflicting memory accesses, while aborting and rolling back transactions that cannot be successfully completed. Mechanisms are provided for software to detect and handle failed transactions.[15]

In other words, lock elision through transactional execution uses memory transactions as a fast path where possible, while the slow (fallback) path is still a normal lock.

Hardware Lock Elision[edit]

Hardware Lock Elision (HLE) adds two new instruction prefixes, XACQUIRE and XRELEASE. These two prefixes reuse the opcodes of the existing REPNE / REPE prefixes (F2H / F3H). On processors that do not support HLE, REPNE / REPE prefixes are ignored on instructions for which the XACQUIRE / XRELEASE are valid, thus enabling backward compatibility.[16]

The XACQUIRE prefix hint can only be used with the following instructions with an explicit LOCK prefix: ADD, ADC, AND, BTC, BTR, BTS, CMPXCHG, CMPXCHG8B, DEC, INC, NEG, NOT, OR, SBB, SUB, XOR, XADD, and XCHG. The XCHG instruction can be used without the LOCK prefix as well.

The XRELEASE prefix hint can be used both with the instructions listed above, and with the MOV mem, reg and MOV mem, imm instructions.

HLE allows optimistic execution of a critical section by skipping the write to a lock, so that the lock appears to be free to other threads. A failed transaction results in execution restarting from the XACQUIRE-prefixed instruction, but treating the instruction as if the XACQUIRE prefix were not present.

Restricted Transactional Memory[edit]

Restricted Transactional Memory (RTM) is an alternative implementation to HLE which gives the programmer the flexibility to specify a fallback code path that is executed when a transaction cannot be successfully executed. Unlike HLE, RTM is not backward compatible with processors that do not support it. For backward compatibility, programs are required to detect support for RTM in the CPU before using the new instructions.

RTM adds three new instructions: XBEGIN, XEND and XABORT. The XBEGIN and XEND instructions mark the start and the end of a transactional code region; the XABORT instruction explicitly aborts a transaction. Transaction failure redirects the processor to the fallback code path specified by the XBEGIN instruction, with the abort status returned in the EAX register.

EAX register
bit position
Meaning
0 Set if abort caused by XABORT instruction.
1 If set, the transaction may succeed on a retry. This bit is always clear if bit 0 is set.
2 Set if another logical processor conflicted with a memory address that was part of the transaction that aborted.
3 Set if an internal buffer overflowed.
4 Set if debug breakpoint was hit.
5 Set if an abort occurred during execution of a nested transaction.
23:6 Reserved.
31:24 XABORT argument (only valid if bit 0 set, otherwise reserved).

XTEST instruction[edit]

TSX/TSX-NI provides a new XTEST instruction that returns whether the processor is executing a transactional region. This instruction is supported by the processor if it supports HLE or RTM or both.

TSX Suspend Load Address Tracking[edit]

TSX/TSX-NI Suspend Load Address Tracking (TSXLDTRK) is an instruction set extension that allows to temporarily disable tracking loads from memory in a section of code within a transactional region. This feature extends HLE and RTM, and its support in the processor must be detected separately.

TSXLDTRK introduces two new instructions, XSUSLDTRK and XRESLDTRK, for suspending and resuming load address tracking, respectively. While the tracking is suspended, any loads from memory will not be added to the transaction read set. This means that, unless these memory locations were added to the transaction read or write sets outside the suspend region, writes at these locations by other threads will not cause transaction abort. Suspending load address tracking for a portion of code within a transactional region allows to reduce the amount of memory that needs to be tracked for read-write conflicts and therefore increase the probability of successful commit of the transaction.

Implementation[edit]

Intel’s TSX/TSX-NI specification describes how the transactional memory is exposed to programmers, but withholds details on the actual transactional memory implementation.[17] Intel specifies in its developer’s and optimization manuals that Haswell maintains both read-sets and write-sets at the granularity of a cache line, tracking addresses in the L1 data cache of the processor.[18][19][20][21] Intel also states that data conflicts are detected through the cache coherence protocol.[19]

Haswell’s L1 data cache has an associativity of eight. This means that in this implementation, a transactional execution that writes to nine distinct locations mapping to the same cache set will abort. However, due to micro-architectural implementations, this does not mean that fewer accesses to the same set are guaranteed to never abort. Additionally, in CPU configurations with Hyper-Threading Technology, the L1 cache is shared between the two threads on the same core, so operations in a sibling logical processor of the same core can cause evictions.[19]

Independent research points into Haswell’s transactional memory most likely being a deferred update system using the per-core caches for transactional data and register checkpoints.[17] In other words, Haswell is more likely to use the cache-based transactional memory system, as it is a much less risky implementation choice. On the other hand, Intel’s Skylake or later may combine this cache-based approach with memory ordering buffer (MOB) for the same purpose, possibly also providing multi-versioned transactional memory that is more amenable to speculative multithreading.[22]

History and bugs[edit]

In August 2014, Intel announced that a bug exists in the TSX/TSX-NI implementation on Haswell, Haswell-E, Haswell-EP and early Broadwell CPUs, which resulted in disabling the TSX/TSX-NI feature on affected CPUs via a microcode update.[9][10][23] The bug was fixed in F-0 steppings of the vPro-enabled Core M-5Y70 Broadwell CPU in November 2014.[24]

The bug was found and then reported during a diploma thesis in the School of Electrical and Computer Engineering of the National Technical University of Athens.[25]

In October 2018, Intel disclosed a TSX/TSX-NI memory ordering issue found in some Skylake processors.[26] As a result of a microcode update, HLE support was disabled in the affected CPUs, and RTM was mitigated by sacrificing one performance counter when used outside of Intel SGX mode or System Management Mode (SMM). System software would have to either effectively disable RTM or update performance monitoring tools not to use the affected performance counter.

In June 2021, Intel published a microcode update that further disables TSX/TSX-NI on various Xeon and Core processor models from Skylake through Coffee Lake and Whiskey Lake as a mitigation for TSX Asynchronous Abort (TAA) vulnerability. Earlier mitigation for memory ordering issue was removed.[27] By default, with the updated microcode, the processor would still indicate support for RTM but would always abort the transaction. System software is able to detect this mode of operation and mask support for TSX/TSX-NI from the CPUID instruction, preventing detection of TSX/TSX-NI by applications. System software may also enable the «Unsupported Software Development Mode», where RTM is fully active, but in this case RTM usage may be subject to the issues described earlier, and therefore this mode should not be enabled on production systems. On some systems RTM can’t be re-enabled when SGX is active. HLE is always disabled.

According to Intel 64 and IA-32 Architectures Software Developer’s Manual from May 2020, Volume 1, Chapter 2.5 Intel Instruction Set Architecture And Features Removed,[18] HLE has been removed from Intel products released in 2019 and later. RTM is not documented as removed. However, Intel 10th generation Comet Lake and Ice Lake client processors, which were released in 2020, do not support TSX/TSX-NI,[28][29][30][31][32] including both HLE and RTM. Engineering versions of Comet Lake processors were still retaining TSX/TSX-NI support.

In Intel Architecture Instruction Set Extensions Programming Reference revision 41 from October 2020,[33] a new TSXLDTRK instruction set extension was documented. It was first included in Sapphire Rapids processors released in January 2023.

See also[edit]

  • Advanced Synchronization Facility – AMD’s competing technology

References[edit]

  1. ^ Richard M. Yoo; Christopher J. Hughes; Konrad Lai; Ravi Rajwar (November 2013). «Performance Evaluation of Intel Transactional Synchronization Extensions for High-Performance Computing» (PDF). intel-research.net. Archived from the original (PDF) on 2016-10-24. Retrieved 2013-11-14.
  2. ^ Tomas Karnagel; Roman Dementiev; Ravi Rajwar; Konrad Lai; Thomas Legler; Benjamin Schlegel; Wolfgang Lehner (February 2014). «Improving In-Memory Database Index Performance with Intel Transactional Synchronization Extensions» (PDF). software.intel.com. Retrieved 2014-03-03.
  3. ^ «Performance Evaluation of Intel Transactional Synchronization Extensions for High Performance Computing». supercomputing.org. November 2013. Archived from the original on 2013-10-29. Retrieved 2013-11-14.
  4. ^ «Benchmarks: Haswell’s TSX and Memory Transaction Throughput (HLE and RTM)». sisoftware.co.uk. Retrieved 2013-11-14.
  5. ^ «Transactional Synchronization in Haswell». Software.intel.com. Retrieved 2012-02-07.
  6. ^ «Transactional memory going mainstream with Intel Haswell». Ars Technica. 2012-02-08. Retrieved 2012-02-09.
  7. ^ «The Core i7-4770K Review». Tom’s Hardware. 2013-06-01. Retrieved 2012-06-03.
  8. ^ «Intel Comparison Table of Haswell Pentium, i3, i5, and i7 models». intel.com. Retrieved 2014-02-11.
  9. ^ a b Scott Wasson (2014-08-12). «Errata prompts Intel to disable TSX in Haswell, early Broadwell CPUs». techreport.com. Retrieved 2014-08-12.
  10. ^ a b «Desktop 4th Generation Intel Core Processor Family, Desktop Intel Pentium Processor Family, and Desktop Intel Celeron Processor Family: Specification Update (Revision 014)» (PDF). Intel. June 2014. p. 46. Retrieved 2014-08-13. Under a complex set of internal timing conditions and system events, software using the Intel TSX/TSX-NI (Transactional Synchronization Extensions) instructions may observe unpredictable system behavior.
  11. ^ «Breaking Kernel Address Space Layout Randomization with Intel TSX» (PDF). 2016.
  12. ^ Gareth Halfacree (2021-06-29). «Intel sticks another nail in the coffin of TSX with feature-disabling microcode update». The Register. Retrieved 2012-10-17.
  13. ^ Wooyoung Kim (2013-07-25). «Fun with Intel Transactional Synchronization Extensions». Intel. Retrieved 2013-11-12.
  14. ^ Sebastien Dabdoub; Stephen Tu. «Supporting Intel Transactional Synchronization Extensions in QEMU» (PDF). mit.edu. Retrieved 2013-11-12.
  15. ^ a b Johan De Gelas (2012-09-20). «Making Sense of the Intel Haswell Transactional Synchronization eXtensions». AnandTech. Retrieved 2013-10-20.
  16. ^ «Hardware Lock Elision Overview». intel.com. Archived from the original on 2013-10-29. Retrieved 2013-10-27.
  17. ^ a b David Kanter (2012-08-21). «Analysis of Haswell’s Transactional Memory». Real World Technologies. Retrieved 2013-11-19.
  18. ^ a b «Intel 64 and IA-32 Architectures Software Developer’s Manual Combined Volumes: 1, 2A, 2B, 2C, 3A, 3B, and 3C» (PDF). Intel. September 2013. p. 342. Retrieved 2013-11-19.
  19. ^ a b c «Intel 64 and IA-32 Architectures Optimization Reference Manual» (PDF). Intel. September 2013. p. 446. Retrieved 2013-11-19.
  20. ^ «Intel TSX implementation properties». Intel. 2013. Retrieved 2013-11-14. The processor tracks both the read-set addresses and the write-set addresses in the first level data cache (L1 cache) of the processor.
  21. ^ De Gelas, Johan (September 20, 2012). «Making Sense of the Intel Haswell Transactional Synchronization eXtensions». AnandTech. Retrieved 23 December 2013. The whole «CPU does the fine grained locks» is based upon tagging the L1 (64 B) cachelines and there are 512 of them to be specific (64 x 512 = 32 KB). There is only one «lock tag» per cacheline.
  22. ^ David Kanter (2012-08-21). «Haswell Transactional Memory Alternatives». Real World Technologies. Retrieved 2013-11-14.
  23. ^ Ian Cutress (2014-08-12). «Intel Disables TSX Instructions: Erratum Found in Haswell, Haswell-E/EP, Broadwell-Y». AnandTech. Retrieved 2014-08-30.
  24. ^ «Intel Core M Processor Family. Specification Update. December 2014. Revision 003. 330836-003» (PDF). Intel. December 2014. p. 10. Retrieved 2014-12-28. BDM53 1 E-0: X, F-0:, Status: Fixed ERRATA: Intel TSX Instructions Not Available. 1. Applies to Intel Core M-5Y70 processor. Intel TSX is supported on Intel Core M-5Y70 processor with Intel vPro Technology. Intel TSX is not supported on other processor SKUs.
  25. ^ «HiPEAC info» (PDF). p. 12. Archived from the original (PDF) on 2017-03-05.
  26. ^ «Performance Monitoring Impact of Intel® Transactional Synchronization Extension Memory Ordering Issue White Paper, June 2021, Revision 1.4» (PDF). Intel. 2021-06-12. p. 5. The October 2018 microcode update also disabled the HLE instruction prefix of Intel TSX and force all RTM transactions to abort when operating in Intel SGX mode or System Management Mode (SMM).
  27. ^ «Intel® Transactional Synchronization Extensions (Intel® TSX) Memory and Performance Monitoring Update for Intel® Processors». Intel. 2021-06-12.
  28. ^ «Intel® Core™ i9-10900K Processor specifications». Intel. 2020. Retrieved 2020-10-10.
  29. ^ «Intel® Core™ i9-10980HK Processor specifications». Intel. 2020. Retrieved 2020-10-10.
  30. ^ «Intel® Core™ i7-10810U Processor specifications». Intel. 2020. Retrieved 2020-10-10.
  31. ^ «Intel® Xeon® W-1290P Processor specifications». Intel. 2020. Retrieved 2020-10-10.
  32. ^ «Intel® Core™ i7-1068NG7 Processor specifications». Intel. 2020. Retrieved 2020-10-10.
  33. ^ «Intel® Architecture Instruction Set Extensions Programming Reference» (PDF). Intel. 2020. Retrieved 2020-10-21.

Further reading[edit]

  • Afek, Y.; Levy, A.; Morrison, A. (2014). Proceedings of the 2014 ACM symposium on Principles of distributed computing — PODC ’14. Software-improved hardware lock elision, p. 212. doi:10.1145/2611462.2611482. ISBN 9781450329446. S2CID 16645370.. Software-based improvements to hardware lock-elision in Intel TSX.

External links[edit]

  • Presentation from IDF 2012 (PDF)
  • Adding lock elision to Linux, Linux Plumbers Conference 2012 (PDF)
  • Lock elision in the GNU C library, LWN.net, January 30, 2013, by Andi Kleen
  • TSX Optimization Guide, Chapter 12 (PDF)
  • Software Developers Manual, Volume 1, Chapter 2.5 (PDF)
  • Web Resources about Intel Transactional Synchronization Extensions
  • x86, microcode: BUG: microcode update that changes x86_capability, LKML, September 2014 (there is also another similar bug report)
  • Intel microcode, Gentoo, September 19, 2015

Введение

TSX (Transactional Synchronization Extensions) — это набор инструкций и функциональность, доступная в процессорах Intel, включая Intel 12600KF. TSX предназначен для обеспечения поддержки атомарных транзакций на уровне аппаратуры. Это позволяет упрощать разработку параллельных программ, повышая производительность и обеспечивая целостность данных.

Основные особенности

TSX включает в себя три режима работы:

  1. Программная обработка транзакций (Hardware Lock Elision, HLE) — использует характеристики транзакций для улучшения производительности, облегчая обработку критических секций кода.
  2. Аппаратная обработка транзакций (Restricted Transactional Memory, RTM) — предоставляет аппаратную поддержку для атомарных транзакций, позволяя выполнять код внутри транзакций с минимальной задержкой.
  3. Совмещенная обработка транзакций (Mixed-mode Execution, RTM) — предоставляет возможность использовать обе предыдущие модели в одном процессе.

Преимущества

Использование TSX может привести к следующим преимуществам при разработке программ:

  • Увеличение производительности: TSX позволяет атомарно выполнять набор инструкций, что снижает временные затраты на выполнение критических секций кода и обеспечивает более эффективное использование многоядерных процессоров.
  • Упрощение разработки: TSX предоставляет средства для управления потоками данных и возможность обнаружения конфликтов данных, что позволяет легче создавать параллельные программы и снижает возможность ошибок.
  • Обеспечение целостности данных: TSX гарантирует, что все изменения данных, выполненные внутри транзакции, либо применяются полностью, либо откатываются, обеспечивая целостность данных и предотвращая состояние гонки.

Ограничения и использование

TSX имеет некоторые ограничения и требуется некоторая осторожность при использовании:

  • Код, выполняемый внутри транзакции, должен быть атомарным и изолированным от других потоков, чтобы предотвратить состояния гонки.
  • Обнаружение конфликтов данных может привести к откату всей транзакции, поэтому стоит избегать конфликтов, когда это возможно.
  • TSX требует поддержки аппаратуры, поэтому не все процессоры Intel поддерживают эту функциональность.

Заключение

TSX-инструкции и функциональность в процессоре Intel 12600KF обеспечивают разработчикам возможность использовать атомарные транзакции на уровне аппаратуры. Это позволяет повысить производительность, упростить разработку и обеспечить целостность данных. Несмотря на некоторые ограничения, TSX является мощным инструментом для разработчиков параллельных программ.

Процессоры и их малодокументированные функции

Время на прочтение
4 мин

Количество просмотров 61K

С каждым новом поколением процессоры Intel вбирают в себя все больше технологий и функций. Некоторые из них у всех на слуху (кто, например, не знает про гипертрединг?), о существовании других большинство неспециалистов даже не догадываются. Откроем всем хорошо известную базу знаний по продуктам Intel Automated Relational Knowledge Base (ARK) и выберем там какой-нибудь процессор. Мы увидим здоровенный список функций и технологий — что скрывается за их таинственными маркетинговыми наименованиями? Предлагаем углубиться в вопрос, обращая особое внимание на мало известные технологии — наверняка, там найдется много интересного.

Intel Demand Based Switching

Совместно с Enhanced Intel SpeedStep Technology, технология Intel Demand Based Switching отвечает за то, чтобы в каждый момент времени при текущей загрузке процессор работал на оптимальной частоте и получал адекватное электрическое питание: не больше и не меньше, чем требуется. Таким образом уменьшается энергопотребление и тепловыделение, что актуально не только для портативных устройств, но и для серверов тоже – именно там Demand Based Switching и используется.

Intel Fast Memory Access

Функция контроллера памяти для оптимизации работы с ОЗУ. Представляет собой комбинацию технологий, позволяющую благодаря углубленному анализу очереди команд выявить «совмещаемые» команды (например, чтение из одной и той же страницы памяти), а затем переупорядочить реальное выполнение таким образом, чтобы «совмещаемые» команды выполнялись друг за другом. Кроме того, менее приоритетные команды записи в память планируются на те моменты, когда прогнозируется опустошение очереди на чтение, и в результате процесс записи в память еще менее ограничивает скорость чтения.

Intel Flex Memory Access

Другая функция контроллера памяти, появившаяся еще во времена, когда он представлял собой отдельный чип, в далеком 2004 году. Обеспечивает возможность работы в синхронном режиме с двумя модулями памяти одновременно, причем в отличие от простого двухканального режима, который существовал и раньше, модули памяти могут быть разного размера. Таким образом достигалась гибкость в оснащении компьютера памятью, что и отражено в названии.

Intel Instruction Replay

Очень глубоко расположенная технология, появившаяся впервые в процессорах Intel Itanium. В процессе работы процессорных конвейеров может случиться такая ситуация, когда инструкции уже пришла очередь исполняться, а необходимые данные пока недоступны. Инструкцию тогда необходимо «переиграть»: снять с конвейера и запустить в его начале. Что, собственно, и происходит. Еще одна важная функция IRT – коррекция случайных ошибок на процессорных конвейерах. Подробнее об этой очень интересной функции читайте здесь.

Intel My WiFi Technology

Технология виртуализации, позволяющая добавить виртуальный WiFi адаптер к существующему физическому; таким образом, ваш ультрабук или ноутбук может стать полноценной точкой доступа или повторителем. Программные компоненты My WiFi входят в состав драйвера Intel PROSet Wireless Software версии 13.2 и выше; надо иметь в виду, что с технологией совместимы лишь некоторые WiFi адаптеры. Инструкцию по установке, а также перечень программных и аппаратных совместимостей можно найти на сайте Intel.

Intel Smart Idle Technology

Еще одна технология энергосбережения. Позволяет отключать в данный момент не используемые блоки процессора или понижать их частоту. Незаменимая вещь для ЦПУ смартфона, как раз именно там и появившаяся – в процессорах Intel Atom.

Intel Stable Image Platform

Термин, относящийся скорее к бизнес-процессам, нежели к технологиям. Программа Intel SIPP обеспечивает стабильность программного обеспечения, гарантируя, что основные компоненты платформ и драйверы не будут изменяться в течение, как минимум, 15 месяцев. Таким образом, корпоративные клиенты имеют возможность пользоваться одними теми же развертываемыми образами систем в течение этого срока.

Intel QuickAssist

Набор аппаратно реализованных функций, требующих больших объемов вычислений, например, шифрование, компрессия, распознавание шаблонов. Смысл QuickAssist – упростить задачу разработчиков, предоставив им функциональные «кирпичики», а также ускорить их приложения. С другой стороны, технология позволяет поручить «тяжелые» задачи не самым мощным процессорам, что особенно ценится во встраиваемых системах, сильно ограниченных и по производительности, и по энергопотреблению.

Intel Quick Resume

Технология, разработанная для компьютеров на базе платформы Intel Viiv, позволявшая им включаться и выключаться практически мгновенно, как ТВ-приемники или DVD-плееры; при этом в «выключенном» состоянии компьютер мог продолжать выполнение некоторых задач, не требующих вмешательства пользователя. И хотя сама платформа плавно перешла в другие ипостаси вместе с сопутствовавшими ей наработками, в ARK строчка еще присутствует, ведь это было не так-то уж и давно.

Intel Secure Key

Обобщающее название для 32- и 64-битной инструкции RDRAND, использующей аппаратную реализацию генератора случайных чисел Digital Random Number Generator (DRNG). Инструкция используется в криптографических целях для генерации красивых и высококачественных случайных ключей.

Intel TSX-NI

Технология со сложным названием Intel Transactional Synchronization Extensions – New Instructions подразумевает под собой надстройку над системой работы с кэшем процессора, оптимизирующую среду исполнения многопоточных приложений, но, конечно, только в том случае, если эти приложения используют программные интерфейсы TSX-NI. Со стороны пользователя данная технология непосредственным образом не видна, но все желающие могут прочитать ее описание доступным языком в блоге Степана Кольцова.

В заключение еще раз хотим напомнить, что Intel ARK существует не только в виде сайта, но и как оффлайновое приложение для iOS и Android. Будьте в теме!

Transactional Synchronization Extensions (TSX), also called Transactional Synchronization Extensions New Instructions (TSX-NI), is an extension to the x86 instruction set architecture (ISA) that adds hardware transactional memory support, speeding up execution of multi-threaded software through lock elision. According to different benchmarks, TSX/TSX-NI can provide around 40% faster applications execution in specific workloads, and 4–5 times more database transactions per second (TPS).[1][2][3][4]

TSX/TSX-NI was documented by Intel in February 2012, and debuted in June 2013 on selected Intel microprocessors based on the Haswell microarchitecture.[5][6][7] Haswell processors below 45xx as well as R-series and K-series (with unlocked multiplier) SKUs do not support TSX/TSX-NI.[8] In August 2014, Intel announced a bug in the TSX/TSX-NI implementation on current steppings of Haswell, Haswell-E, Haswell-EP and early Broadwell CPUs, which resulted in disabling the TSX/TSX-NI feature on affected CPUs via a microcode update.[9][10]

In 2016, a side-channel timing attack was found by abusing the way TSX/TSX-NI handles transactional faults (i.e. page faults) in order to break kernel address space layout randomization (KASLR) on all major operating systems.[11] In 2021, Intel released a microcode update that disabled the TSX/TSX-NI feature on CPU generations from Skylake to Coffee Lake, as a mitigation for discovered security issues.[12]

Support for TSX/TSX-NI emulation is provided as part of the Intel Software Development Emulator.[13] There is also experimental support for TSX/TSX-NI emulation in a QEMU fork.[14]

Features

Edit

TSX/TSX-NI provides two software interfaces for designating code regions for transactional execution. Hardware Lock Elision (HLE) is an instruction prefix-based interface designed to be backward compatible with processors without TSX/TSX-NI support. Restricted Transactional Memory (RTM) is a new instruction set interface that provides greater flexibility for programmers.[15]

TSX/TSX-NI enables optimistic execution of transactional code regions. The hardware monitors multiple threads for conflicting memory accesses, while aborting and rolling back transactions that cannot be successfully completed. Mechanisms are provided for software to detect and handle failed transactions.[15]

In other words, lock elision through transactional execution uses memory transactions as a fast path where possible, while the slow (fallback) path is still a normal lock.

Hardware Lock Elision

Edit

Hardware Lock Elision (HLE) adds two new instruction prefixes, XACQUIRE and XRELEASE. These two prefixes reuse the opcodes of the existing REPNE / REPE prefixes (F2H / F3H). On processors that do not support HLE, REPNE / REPE prefixes are ignored on instructions for which the XACQUIRE / XRELEASE are valid, thus enabling backward compatibility.[16]

The XACQUIRE prefix hint can only be used with the following instructions with an explicit LOCK prefix: ADD, ADC, AND, BTC, BTR, BTS, CMPXCHG, CMPXCHG8B, DEC, INC, NEG, NOT, OR, SBB, SUB, XOR, XADD, and XCHG. The XCHG instruction can be used without the LOCK prefix as well.

The XRELEASE prefix hint can be used both with the instructions listed above, and with the MOV mem, reg and MOV mem, imm instructions.

HLE allows optimistic execution of a critical section by skipping the write to a lock, so that the lock appears to be free to other threads. A failed transaction results in execution restarting from the XACQUIRE-prefixed instruction, but treating the instruction as if the XACQUIRE prefix were not present.

Restricted Transactional Memory

Edit

Restricted Transactional Memory (RTM) is an alternative implementation to HLE which gives the programmer the flexibility to specify a fallback code path that is executed when a transaction cannot be successfully executed. Unlike HLE, RTM is not backward compatible with processors that do not support it. For backward compatibility, programs are required to detect support for RTM in the CPU before using the new instructions.

RTM adds three new instructions: XBEGIN, XEND and XABORT. The XBEGIN and XEND instructions mark the start and the end of a transactional code region; the XABORT instruction explicitly aborts a transaction. Transaction failure redirects the processor to the fallback code path specified by the XBEGIN instruction, with the abort status returned in the EAX register.

EAX register
bit position
Meaning
0 Set if abort caused by XABORT instruction.
1 If set, the transaction may succeed on a retry. This bit is always clear if bit 0 is set.
2 Set if another logical processor conflicted with a memory address that was part of the transaction that aborted.
3 Set if an internal buffer overflowed.
4 Set if debug breakpoint was hit.
5 Set if an abort occurred during execution of a nested transaction.
23:6 Reserved.
31:24 XABORT argument (only valid if bit 0 set, otherwise reserved).

XTEST instruction

Edit

TSX/TSX-NI provides a new XTEST instruction that returns whether the processor is executing a transactional region. This instruction is supported by the processor if it supports HLE or RTM or both.

TSX Suspend Load Address Tracking

Edit

TSX/TSX-NI Suspend Load Address Tracking (TSXLDTRK) is an instruction set extension that allows to temporarily disable tracking loads from memory in a section of code within a transactional region. This feature extends HLE and RTM, and its support in the processor must be detected separately.

TSXLDTRK introduces two new instructions, XSUSLDTRK and XRESLDTRK, for suspending and resuming load address tracking, respectively. While the tracking is suspended, any loads from memory will not be added to the transaction read set. This means that, unless these memory locations were added to the transaction read or write sets outside the suspend region, writes at these locations by other threads will not cause transaction abort. Suspending load address tracking for a portion of code within a transactional region allows to reduce the amount of memory that needs to be tracked for read-write conflicts and therefore increase the probability of successful commit of the transaction.

Implementation

Edit

Intel’s TSX/TSX-NI specification describes how the transactional memory is exposed to programmers, but withholds details on the actual transactional memory implementation.[17] Intel specifies in its developer’s and optimization manuals that Haswell maintains both read-sets and write-sets at the granularity of a cache line, tracking addresses in the L1 data cache of the processor.[18][19][20][21] Intel also states that data conflicts are detected through the cache coherence protocol.[19]

Haswell’s L1 data cache has an associativity of eight. This means that in this implementation, a transactional execution that writes to nine distinct locations mapping to the same cache set will abort. However, due to micro-architectural implementations, this does not mean that fewer accesses to the same set are guaranteed to never abort. Additionally, in CPU configurations with Hyper-Threading Technology, the L1 cache is shared between the two threads on the same core, so operations in a sibling logical processor of the same core can cause evictions.[19]

Independent research points into Haswell’s transactional memory most likely being a deferred update system using the per-core caches for transactional data and register checkpoints.[17] In other words, Haswell is more likely to use the cache-based transactional memory system, as it is a much less risky implementation choice. On the other hand, Intel’s Skylake or later may combine this cache-based approach with memory ordering buffer (MOB) for the same purpose, possibly also providing multi-versioned transactional memory that is more amenable to speculative multithreading.[22]

History and bugs

Edit

In August 2014, Intel announced that a bug exists in the TSX/TSX-NI implementation on Haswell, Haswell-E, Haswell-EP and early Broadwell CPUs, which resulted in disabling the TSX/TSX-NI feature on affected CPUs via a microcode update.[9][10][23] The bug was fixed in F-0 steppings of the vPro-enabled Core M-5Y70 Broadwell CPU in November 2014.[24]

The bug was found and then reported during a diploma thesis in the School of Electrical and Computer Engineering of the National Technical University of Athens.[25]

In October 2018, Intel disclosed a TSX/TSX-NI memory ordering issue found in some Skylake processors.[26] As a result of a microcode update, HLE support was disabled in the affected CPUs, and RTM was mitigated by sacrificing one performance counter when used outside of Intel SGX mode or System Management Mode (SMM). System software would have to either effectively disable RTM or update performance monitoring tools not to use the affected performance counter.

In June 2021, Intel published a microcode update that further disables TSX/TSX-NI on various Xeon and Core processor models from Skylake through Coffee Lake and Whiskey Lake as a mitigation for TSX Asynchronous Abort (TAA) vulnerability. Earlier mitigation for memory ordering issue was removed.[27] By default, with the updated microcode, the processor would still indicate support for RTM but would always abort the transaction. System software is able to detect this mode of operation and mask support for TSX/TSX-NI from the CPUID instruction, preventing detection of TSX/TSX-NI by applications. System software may also enable the «Unsupported Software Development Mode», where RTM is fully active, but in this case RTM usage may be subject to the issues described earlier, and therefore this mode should not be enabled on production systems. On some systems RTM can’t be re-enabled when SGX is active. HLE is always disabled.

According to Intel 64 and IA-32 Architectures Software Developer’s Manual from May 2020, Volume 1, Chapter 2.5 Intel Instruction Set Architecture And Features Removed,[18] HLE has been removed from Intel products released in 2019 and later. RTM is not documented as removed. However, Intel 10th generation Comet Lake and Ice Lake client processors, which were released in 2020, do not support TSX/TSX-NI,[28][29][30][31][32] including both HLE and RTM. Engineering versions of Comet Lake processors were still retaining TSX/TSX-NI support.

In Intel Architecture Instruction Set Extensions Programming Reference revision 41 from October 2020,[33] a new TSXLDTRK instruction set extension was documented. It was first included in Sapphire Rapids processors released in January 2023.

See also

Edit

  • Advanced Synchronization Facility – AMD’s competing technology

References

Edit

  1. ^ Richard M. Yoo; Christopher J. Hughes; Konrad Lai; Ravi Rajwar (November 2013). «Performance Evaluation of Intel Transactional Synchronization Extensions for High-Performance Computing» (PDF). intel-research.net. Archived from the original (PDF) on 2016-10-24. Retrieved 2013-11-14.
  2. ^ Tomas Karnagel; Roman Dementiev; Ravi Rajwar; Konrad Lai; Thomas Legler; Benjamin Schlegel; Wolfgang Lehner (February 2014). «Improving In-Memory Database Index Performance with Intel Transactional Synchronization Extensions» (PDF). software.intel.com. Retrieved 2014-03-03.
  3. ^ «Performance Evaluation of Intel Transactional Synchronization Extensions for High Performance Computing». supercomputing.org. November 2013. Archived from the original on 2013-10-29. Retrieved 2013-11-14.
  4. ^ «Benchmarks: Haswell’s TSX and Memory Transaction Throughput (HLE and RTM)». sisoftware.co.uk. Retrieved 2013-11-14.
  5. ^ «Transactional Synchronization in Haswell». Software.intel.com. Retrieved 2012-02-07.
  6. ^ «Transactional memory going mainstream with Intel Haswell». Ars Technica. 2012-02-08. Retrieved 2012-02-09.
  7. ^ «The Core i7-4770K Review». Tom’s Hardware. 2013-06-01. Retrieved 2012-06-03.
  8. ^ «Intel Comparison Table of Haswell Pentium, i3, i5, and i7 models». intel.com. Retrieved 2014-02-11.
  9. ^ a b Scott Wasson (2014-08-12). «Errata prompts Intel to disable TSX in Haswell, early Broadwell CPUs». techreport.com. Retrieved 2014-08-12.
  10. ^ a b «Desktop 4th Generation Intel Core Processor Family, Desktop Intel Pentium Processor Family, and Desktop Intel Celeron Processor Family: Specification Update (Revision 014)» (PDF). Intel. June 2014. p. 46. Retrieved 2014-08-13. Under a complex set of internal timing conditions and system events, software using the Intel TSX/TSX-NI (Transactional Synchronization Extensions) instructions may observe unpredictable system behavior.
  11. ^ «Breaking Kernel Address Space Layout Randomization with Intel TSX» (PDF). 2016.
  12. ^ Gareth Halfacree (2021-06-29). «Intel sticks another nail in the coffin of TSX with feature-disabling microcode update». The Register. Retrieved 2012-10-17.
  13. ^ Wooyoung Kim (2013-07-25). «Fun with Intel Transactional Synchronization Extensions». Intel. Retrieved 2013-11-12.
  14. ^ Sebastien Dabdoub; Stephen Tu. «Supporting Intel Transactional Synchronization Extensions in QEMU» (PDF). mit.edu. Retrieved 2013-11-12.
  15. ^ a b Johan De Gelas (2012-09-20). «Making Sense of the Intel Haswell Transactional Synchronization eXtensions». AnandTech. Retrieved 2013-10-20.
  16. ^ «Hardware Lock Elision Overview». intel.com. Archived from the original on 2013-10-29. Retrieved 2013-10-27.
  17. ^ a b David Kanter (2012-08-21). «Analysis of Haswell’s Transactional Memory». Real World Technologies. Retrieved 2013-11-19.
  18. ^ a b «Intel 64 and IA-32 Architectures Software Developer’s Manual Combined Volumes: 1, 2A, 2B, 2C, 3A, 3B, and 3C» (PDF). Intel. September 2013. p. 342. Retrieved 2013-11-19.
  19. ^ a b c «Intel 64 and IA-32 Architectures Optimization Reference Manual» (PDF). Intel. September 2013. p. 446. Retrieved 2013-11-19.
  20. ^ «Intel TSX implementation properties». Intel. 2013. Retrieved 2013-11-14. The processor tracks both the read-set addresses and the write-set addresses in the first level data cache (L1 cache) of the processor.
  21. ^ De Gelas, Johan (September 20, 2012). «Making Sense of the Intel Haswell Transactional Synchronization eXtensions». AnandTech. Retrieved 23 December 2013. The whole «CPU does the fine grained locks» is based upon tagging the L1 (64 B) cachelines and there are 512 of them to be specific (64 x 512 = 32 KB). There is only one «lock tag» per cacheline.
  22. ^ David Kanter (2012-08-21). «Haswell Transactional Memory Alternatives». Real World Technologies. Retrieved 2013-11-14.
  23. ^ Ian Cutress (2014-08-12). «Intel Disables TSX Instructions: Erratum Found in Haswell, Haswell-E/EP, Broadwell-Y». AnandTech. Retrieved 2014-08-30.
  24. ^ «Intel Core M Processor Family. Specification Update. December 2014. Revision 003. 330836-003» (PDF). Intel. December 2014. p. 10. Retrieved 2014-12-28. BDM53 1 E-0: X, F-0:, Status: Fixed ERRATA: Intel TSX Instructions Not Available. 1. Applies to Intel Core M-5Y70 processor. Intel TSX is supported on Intel Core M-5Y70 processor with Intel vPro Technology. Intel TSX is not supported on other processor SKUs.
  25. ^ «HiPEAC info» (PDF). p. 12. Archived from the original (PDF) on 2017-03-05.
  26. ^ «Performance Monitoring Impact of Intel® Transactional Synchronization Extension Memory Ordering Issue White Paper, June 2021, Revision 1.4» (PDF). Intel. 2021-06-12. p. 5. The October 2018 microcode update also disabled the HLE instruction prefix of Intel TSX and force all RTM transactions to abort when operating in Intel SGX mode or System Management Mode (SMM).
  27. ^ «Intel® Transactional Synchronization Extensions (Intel® TSX) Memory and Performance Monitoring Update for Intel® Processors». Intel. 2021-06-12.
  28. ^ «Intel® Core™ i9-10900K Processor specifications». Intel. 2020. Retrieved 2020-10-10.
  29. ^ «Intel® Core™ i9-10980HK Processor specifications». Intel. 2020. Retrieved 2020-10-10.
  30. ^ «Intel® Core™ i7-10810U Processor specifications». Intel. 2020. Retrieved 2020-10-10.
  31. ^ «Intel® Xeon® W-1290P Processor specifications». Intel. 2020. Retrieved 2020-10-10.
  32. ^ «Intel® Core™ i7-1068NG7 Processor specifications». Intel. 2020. Retrieved 2020-10-10.
  33. ^ «Intel® Architecture Instruction Set Extensions Programming Reference» (PDF). Intel. 2020. Retrieved 2020-10-21.

Further reading

Edit

  • Afek, Y.; Levy, A.; Morrison, A. (2014). Proceedings of the 2014 ACM symposium on Principles of distributed computing — PODC ’14. Software-improved hardware lock elision, p. 212. doi:10.1145/2611462.2611482. ISBN 9781450329446. S2CID 16645370.. Software-based improvements to hardware lock-elision in Intel TSX.

External links

Edit

  • Presentation from IDF 2012 (PDF)
  • Adding lock elision to Linux, Linux Plumbers Conference 2012 (PDF)
  • Lock elision in the GNU C library, LWN.net, January 30, 2013, by Andi Kleen
  • TSX Optimization Guide, Chapter 12 (PDF)
  • Software Developers Manual, Volume 1, Chapter 2.5 (PDF)
  • Web Resources about Intel Transactional Synchronization Extensions
  • x86, microcode: BUG: microcode update that changes x86_capability, LKML, September 2014 (there is also another similar bug report)
  • Intel microcode, Gentoo, September 19, 2015

Одна из самых больших проблем с многоядерностью ЦП Системы, которые используют наши ПК, заключается в том, что они основаны на модели фон Неймана, которая заключается в том, что имеется только одна общая память. По мере увеличения количества исполнительных блоков, ядер, потоков и других элементов, которые работают параллельно в ЦП, увеличивается. Между ними возникает все больше и больше конфликтов. Не только в доступе к данным, но и к информации, содержащейся в различных адресах памяти, и, следовательно, к значениям переменных, используемых программами. Есть много способов избежать этих конфликтов, один из них — транзакционная память, которую мы собираемся описать в этой статье.

Введение в проблему

Серрохос

При написании программы она кодируется серией инструкций, которые, по-видимому, выполняются последовательно. Но уже при параллелизме инструкций с одним ядром в середине выполнения могут входить разные исполнительные единицы. К этому мы должны принять во внимание, что выполнение не по порядку добавляет сложности, поскольку доступ к памяти и данным во время выполнения осуществляется беспорядочно.

При большом количестве запросов возникает конкуренция за доступ к одной и той же памяти. Это приводит к тому, что запросы задерживаются все дольше и дольше, увеличивая задержку памяти с ЦП при выполнении определенных инструкций и влияя на пропускную способность. Для этого существуют механизмы, которые максимально избегают этих конфликтов при доступе к памяти, таким образом, чтобы процессы обращались к памяти из упорядоченной памяти. Это позволяет избежать конфликтов при изменении данных в своей иерархии, а также уменьшить проблемы конкуренции и, как следствие, задержку доступа.

Самый простой способ добиться этого — использовать блокировки, которые представляют собой участки кода, в которых мы отмечаем, что они не должны выполняться одновременно разными потоками ЦП. То есть за эту часть кода может отвечать только одно его ядро. Итак, мы сделали блокировку для остальных ядер, и остальные смогут начать выполнение только тогда, когда будет достигнута инструкция, завершающая блокировку. Что произойдет, когда будет завершена часть кода, выделенная для всех ядер, кроме одного.

Что такое транзакционная память?

Цвет Código binario

Один из способов избежать проблем, описанных в предыдущем разделе, — использовать транзакционную память. Это не тип памяти или хранилища, поэтому мы не говорим о чистом оборудовании. Его происхождение находится в транзакциях баз данных, это тип инструкций, выполняемых в модулях Load-Store.

Система транзакций в процессоре работает следующим образом:

  1. Создается копия части памяти, к которой хотят получить доступ несколько ядер, по одной для каждого экземпляра.
  2. Каждый экземпляр изменяет свою личную копию независимо от остальных частных копий.
  3. Если данные были изменены в частной копии, а не в остальных, то модификация также копируется в остальные частные копии.
  4. Если два экземпляра вносят изменения в одни и те же данные в одно и то же время, и это создает несогласованность в данных, то обе частные копии удаляются. а частные копии остальных копируются

Четвертый момент важен, поскольку именно в этой части становится ясно, что необходимо сериализовать эту часть кода. Это означает, что остальные экземпляры перестают изменять свои личные копии, и изменения вносятся только одним из экземпляров. Когда он заканчивается, изменения копируются в остальные частные копии. Когда часть кода, помеченная как транзакционная, уже выполнена и все частные копии содержат одинаковую информацию, результат копируется в соответствующие строки кэша и адреса памяти.

Оборудование Memoria Transaccional

Аббревиатура TSX, Расширения транзакционной синхронизации, относится к серии дополнительных инструкций для x86 ISA, которые предназначены для добавления поддержки транзакционной памяти в Intel ЦП. Следовательно, это серия инструкций и связанных с ними механизмов, которые позволяют разграничивать определенные разделы кода как транзакционные, а ЦП Intel может выполнять процесс, который мы обсуждали в предыдущем процессе. Но в этом случае реализация Intel немного сложнее. Поскольку, как мы видели ранее, в случае конфликта между двумя данными весь процесс прерывается одним из запущенных экземпляров.

Его реализация на аппаратном уровне достигается за счет добавления нового типа кеша, называемого кешем транзакций, в котором различные операции выполняются с разными данными. Имейте в виду, что транзакционная память стремится уменьшить количество конфликтов при доступе к памяти. Хотя кеши поддерживают большее количество запросов, чем Оперативная память как правило, они также ограничены, особенно на уровнях, наиболее удаленных от ядер. Все это сочетается с использованием внутренней памяти и частных регистров, которые служат поддержкой частных копий, выполняемых различными ядрами.

Инструкции Intel TSX не являются сложным набором, у нас есть, с одной стороны, инструкция XBEGIN, которая отмечает нас, когда начинается транзакционный раздел памяти, инструкция XEND, которая отмечает конец, и XABORT, которая служит для отметки выхода из процесса. при возникновении исключительной ситуации.

Конец инструкций Intel TSX?

Intel TSX Отмена

Сегодняшние блоки управления ЦП на самом деле представляют собой полноценные микроконтроллеры, это означает, что способ декодирования инструкций и список инструкций могут быть обновлены. Intel сделала первую реализацию на архитектуре Haswell, и до сих пор она оставалась в составе процессоров Intel. Поскольку недавно он был отключен с помощью прошивки на собственных ядрах Intel шестого, седьмого и восьмого поколений.

Время от времени Intel выполняет удаленные обновления своих ЦП, которые выполняются через Intel Management Engine, который у нас есть на нашем ПК, без нашего ведома. Обычно они не распространены, но могут включать оптимизацию выполнения определенных инструкций или даже исключение поддержки других. Устранение Intel TSX в Intel Core связано с тем, что с последними модификациями внутреннего микрокода блока управления это подразумевает конфликт в работе программного обеспечения, что означает, что ЦП не работает должным образом.

Но настоящая причина в том, что Intel TSX позволяет запускать вредоносный код под радаром классических систем безопасности, особенно тот, который влияет на операционную систему. Поскольку частные копии не соответствуют среде пользователя или операционной системе. Так что это все еще проблема, аналогичная проблеме спекулятивного исполнения.

Понравилась статья? Поделить с друзьями:
  • Ts18 магнитола андроид инструкция на русском
  • Ts10 магнитола инструкция по эксплуатации
  • Ts kbd em2 metal tantos кодонаборная панель инструкция
  • Ts kbd em ip66 metal инструкция
  • Tromcardin complex инструкция по применению на русском языке