요약·해설과 원문, 전문 번역을 서로 분리했습니다. API 이름, symbol, source path는 원문 표기를 사용합니다.
1. 요약·해설
원문의 핵심 논리와 kernel programming 관점의 보충 설명입니다. 아래의 전문 번역과는 별도로 작성했습니다.
2. 영어 원문 전체
번역 기준이 된 Linux v6.18.37 원문입니다. 줄 번호는 이 버전의 파일 좌표입니다.
원문 전체 펼치기
============================
Transactional Memory support
============================
POWER kernel support for this feature is currently limited to supporting
its use by user programs. It is not currently used by the kernel itself.
This file aims to sum up how it is supported by Linux and what behaviour you
can expect from your user programs.
Basic overview
==============
Hardware Transactional Memory is supported on POWER8 processors, and is a
feature that enables a different form of atomic memory access. Several new
instructions are presented to delimit transactions; transactions are
guaranteed to either complete atomically or roll back and undo any partial
changes.
A simple transaction looks like this::
begin_move_money:
tbegin
beq abort_handler
ld r4, SAVINGS_ACCT(r3)
ld r5, CURRENT_ACCT(r3)
subi r5, r5, 1
addi r4, r4, 1
std r4, SAVINGS_ACCT(r3)
std r5, CURRENT_ACCT(r3)
tend
b continue
abort_handler:
... test for odd failures ...
/* Retry the transaction if it failed because it conflicted with
* someone else: */
b begin_move_money
The 'tbegin' instruction denotes the start point, and 'tend' the end point.
Between these points the processor is in 'Transactional' state; any memory
references will complete in one go if there are no conflicts with other
transactional or non-transactional accesses within the system. In this
example, the transaction completes as though it were normal straight-line code
IF no other processor has touched SAVINGS_ACCT(r3) or CURRENT_ACCT(r3); an
atomic move of money from the current account to the savings account has been
performed. Even though the normal ld/std instructions are used (note no
lwarx/stwcx), either *both* SAVINGS_ACCT(r3) and CURRENT_ACCT(r3) will be
updated, or neither will be updated.
If, in the meantime, there is a conflict with the locations accessed by the
transaction, the transaction will be aborted by the CPU. Register and memory
state will roll back to that at the 'tbegin', and control will continue from
'tbegin+4'. The branch to abort_handler will be taken this second time; the
abort handler can check the cause of the failure, and retry.
Checkpointed registers include all GPRs, FPRs, VRs/VSRs, LR, CCR/CR, CTR, FPCSR
and a few other status/flag regs; see the ISA for details.
Causes of transaction aborts
============================
- Conflicts with cache lines used by other processors
- Signals
- Context switches
- See the ISA for full documentation of everything that will abort transactions.
Syscalls
========
Syscalls made from within an active transaction will not be performed and the
transaction will be doomed by the kernel with the failure code TM_CAUSE_SYSCALL
| TM_CAUSE_PERSISTENT.
Syscalls made from within a suspended transaction are performed as normal and
the transaction is not explicitly doomed by the kernel. However, what the
kernel does to perform the syscall may result in the transaction being doomed
by the hardware. The syscall is performed in suspended mode so any side
effects will be persistent, independent of transaction success or failure. No
guarantees are provided by the kernel about which syscalls will affect
transaction success.
Care must be taken when relying on syscalls to abort during active transactions
if the calls are made via a library. Libraries may cache values (which may
give the appearance of success) or perform operations that cause transaction
failure before entering the kernel (which may produce different failure codes).
Examples are glibc's getpid() and lazy symbol resolution.
Signals
=======
Delivery of signals (both sync and async) during transactions provides a second
thread state (ucontext/mcontext) to represent the second transactional register
state. Signal delivery 'treclaim's to capture both register states, so signals
abort transactions. The usual ucontext_t passed to the signal handler
represents the checkpointed/original register state; the signal appears to have
arisen at 'tbegin+4'.
If the sighandler ucontext has uc_link set, a second ucontext has been
delivered. For future compatibility the MSR.TS field should be checked to
determine the transactional state -- if so, the second ucontext in uc->uc_link
represents the active transactional registers at the point of the signal.
For 64-bit processes, uc->uc_mcontext.regs->msr is a full 64-bit MSR and its TS
field shows the transactional mode.
For 32-bit processes, the mcontext's MSR register is only 32 bits; the top 32
bits are stored in the MSR of the second ucontext, i.e. in
uc->uc_link->uc_mcontext.regs->msr. The top word contains the transactional
state TS.
However, basic signal handlers don't need to be aware of transactions
and simply returning from the handler will deal with things correctly:
Transaction-aware signal handlers can read the transactional register state
from the second ucontext. This will be necessary for crash handlers to
determine, for example, the address of the instruction causing the SIGSEGV.
Example signal handler::
void crash_handler(int sig, siginfo_t *si, void *uc)
{
ucontext_t *ucp = uc;
ucontext_t *transactional_ucp = ucp->uc_link;
if (ucp_link) {
u64 msr = ucp->uc_mcontext.regs->msr;
/* May have transactional ucontext! */
#ifndef __powerpc64__
msr |= ((u64)transactional_ucp->uc_mcontext.regs->msr) << 32;
#endif
if (MSR_TM_ACTIVE(msr)) {
/* Yes, we crashed during a transaction. Oops. */
fprintf(stderr, "Transaction to be restarted at 0x%llx, but "
"crashy instruction was at 0x%llx\n",
ucp->uc_mcontext.regs->nip,
transactional_ucp->uc_mcontext.regs->nip);
}
}
fix_the_problem(ucp->dar);
}
When in an active transaction that takes a signal, we need to be careful with
the stack. It's possible that the stack has moved back up after the tbegin.
The obvious case here is when the tbegin is called inside a function that
returns before a tend. In this case, the stack is part of the checkpointed
transactional memory state. If we write over this non transactionally or in
suspend, we are in trouble because if we get a tm abort, the program counter and
stack pointer will be back at the tbegin but our in memory stack won't be valid
anymore.
To avoid this, when taking a signal in an active transaction, we need to use
the stack pointer from the checkpointed state, rather than the speculated
state. This ensures that the signal context (written tm suspended) will be
written below the stack required for the rollback. The transaction is aborted
because of the treclaim, so any memory written between the tbegin and the
signal will be rolled back anyway.
For signals taken in non-TM or suspended mode, we use the
normal/non-checkpointed stack pointer.
Any transaction initiated inside a sighandler and suspended on return
from the sighandler to the kernel will get reclaimed and discarded.
Failure cause codes used by kernel
==================================
These are defined in <asm/reg.h>, and distinguish different reasons why the
kernel aborted a transaction:
====================== ================================
TM_CAUSE_RESCHED Thread was rescheduled.
TM_CAUSE_TLBI Software TLB invalid.
TM_CAUSE_FAC_UNAV FP/VEC/VSX unavailable trap.
TM_CAUSE_SYSCALL Syscall from active transaction.
TM_CAUSE_SIGNAL Signal delivered.
TM_CAUSE_MISC Currently unused.
TM_CAUSE_ALIGNMENT Alignment fault.
TM_CAUSE_EMULATE Emulation that touched memory.
====================== ================================
These can be checked by the user program's abort handler as TEXASR[0:7]. If
bit 7 is set, it indicates that the error is considered persistent. For example
a TM_CAUSE_ALIGNMENT will be persistent while a TM_CAUSE_RESCHED will not.
GDB
===
GDB and ptrace are not currently TM-aware. If one stops during a transaction,
it looks like the transaction has just started (the checkpointed state is
presented). The transaction cannot then be continued and will take the failure
handler route. Furthermore, the transactional 2nd register state will be
inaccessible. GDB can currently be used on programs using TM, but not sensibly
in parts within transactions.
POWER9
======
TM on POWER9 has issues with storing the complete register state. This
is described in this commit::
commit 4bb3c7a0208fc13ca70598efd109901a7cd45ae7
Author: Paul Mackerras <paulus@ozlabs.org>
Date: Wed Mar 21 21:32:01 2018 +1100
KVM: PPC: Book3S HV: Work around transactional memory bugs in POWER9
To account for this different POWER9 chips have TM enabled in
different ways.
On POWER9N DD2.01 and below, TM is disabled. ie
HWCAP2[PPC_FEATURE2_HTM] is not set.
On POWER9N DD2.1 TM is configured by firmware to always abort a
transaction when tm suspend occurs. So tsuspend will cause a
transaction to be aborted and rolled back. Kernel exceptions will also
cause the transaction to be aborted and rolled back and the exception
will not occur. If userspace constructs a sigcontext that enables TM
suspend, the sigcontext will be rejected by the kernel. This mode is
advertised to users with HWCAP2[PPC_FEATURE2_HTM_NO_SUSPEND] set.
HWCAP2[PPC_FEATURE2_HTM] is not set in this mode.
On POWER9N DD2.2 and above, KVM and POWERVM emulate TM for guests (as
described in commit 4bb3c7a0208f), hence TM is enabled for guests
ie. HWCAP2[PPC_FEATURE2_HTM] is set for guest userspace. Guests that
makes heavy use of TM suspend (tsuspend or kernel suspend) will result
in traps into the hypervisor and hence will suffer a performance
degradation. Host userspace has TM disabled
ie. HWCAP2[PPC_FEATURE2_HTM] is not set. (although we make enable it
at some point in the future if we bring the emulation into host
userspace context switching).
POWER9C DD1.2 and above are only available with POWERVM and hence
Linux only runs as a guest. On these systems TM is emulated like on
POWER9N DD2.2.
Guest migration from POWER8 to POWER9 will work with POWER9N DD2.2 and
POWER9C DD1.2. Since earlier POWER9 processors don't support TM
emulation, migration from POWER8 to POWER9 is not supported there.
Kernel implementation
=====================
h/rfid mtmsrd quirk
-------------------
As defined in the ISA, rfid has a quirk which is useful in early
exception handling. When in a userspace transaction and we enter the
kernel via some exception, MSR will end up as TM=0 and TS=01 (ie. TM
off but TM suspended). Regularly the kernel will want change bits in
the MSR and will perform an rfid to do this. In this case rfid can
have SRR0 TM = 0 and TS = 00 (ie. TM off and non transaction) and the
resulting MSR will retain TM = 0 and TS=01 from before (ie. stay in
suspend). This is a quirk in the architecture as this would normally
be a transition from TS=01 to TS=00 (ie. suspend -> non transactional)
which is an illegal transition.
This quirk is described the architecture in the definition of rfid
with these lines:
if (MSR 29:31 ¬ = 0b010 | SRR1 29:31 ¬ = 0b000) then
MSR 29:31 <- SRR1 29:31
hrfid and mtmsrd have the same quirk.
The Linux kernel uses this quirk in its early exception handling.
3. 한국어 전문 번역
영어 원문의 문단 순서와 의미를 유지한 전체 번역입니다. 코드, 함수명, symbol과 URL은 원문 표기를 유지합니다.
POWER Transactional Memory 지원 범위
1-11POWER kernel의 Transactional Memory(TM) 지원은 현재 userspace program이 이 기능을 사용하도록 돕는 범위로 제한됩니다. Kernel 자체는 TM을 사용하지 않습니다.
이 문서는 Linux가 Hardware Transactional Memory를 어떻게 지원하며 userspace program에서 어떤 동작을 기대할 수 있는지 정리합니다.
Hardware Transactional Memory 기본 동작
12-65Hardware Transactional Memory는 POWER8 processor에서 지원하며 atomic memory access의 다른 형태를 제공합니다. 새 instruction들이 transaction 경계를 표시하고, transaction은 전체가 atomic하게 완료되거나 rollback되어 중간 변경이 모두 취소됩니다.
Account 사이에서 값을 이동하는 단순 transaction 예입니다.
begin_move_money:
tbegin
beq abort_handler
ld r4, SAVINGS_ACCT(r3)
ld r5, CURRENT_ACCT(r3)
subi r5, r5, 1
addi r4, r4, 1
std r4, SAVINGS_ACCT(r3)
std r5, CURRENT_ACCT(r3)
tend
b continue
abort_handler:
... test for odd failures ...
/* Retry the transaction if it failed because it conflicted with
* someone else: */
b begin_move_money
`tbegin`은 시작점, `tend`는 끝점을 나타냅니다. 이 사이에서 processor는 Transactional state이며, system의 다른 transactional 또는 non-transactional access와 conflict가 없으면 memory reference가 한 번에 완료됩니다.
예제에서 다른 processor가 `SAVINGS_ACCT(r3)`나 `CURRENT_ACCT(r3)`를 건드리지 않았다면 normal straight-line code처럼 완료되어 current account에서 savings account로 값이 atomic하게 이동합니다. 일반 `ld`/`std`를 사용하고 `lwarx`/`stwcx`를 쓰지 않아도 두 account가 모두 update되거나 둘 다 update되지 않습니다.
접근한 location과 conflict가 발생하면 CPU가 transaction을 abort합니다. Register와 memory state는 `tbegin` 시점으로 rollback되고 control은 `tbegin+4`에서 계속됩니다. 두 번째 실행에서는 `abort_handler` branch가 선택되며 handler가 failure cause를 검사하고 retry할 수 있습니다.
Checkpoint 대상에는 모든 GPR, FPR, VR/VSR, LR, CCR/CR, CTR, FPCSR와 일부 status/flag register가 포함됩니다. 세부 목록은 ISA를 따라야 합니다.
Conflict 유무에 따라 전체 memory update가 commit되거나 checkpoint state로 되돌아갑니다.
Transaction abort 원인
66-74- 다른 processor가 사용하는 cache line과의 conflict
- Signal delivery
- Context switch
- 그 밖의 전체 abort 조건은 ISA에 정의됨
Transaction 안의 syscall
75-96Active transaction 안에서 요청한 syscall은 실행되지 않습니다. Kernel은 `TM_CAUSE_SYSCALL | TM_CAUSE_PERSISTENT` failure code로 transaction을 doomed 상태로 만듭니다.
Suspended transaction 안의 syscall은 정상 수행되며 kernel이 transaction을 명시적으로 doomed 상태로 만들지 않습니다. 다만 syscall 구현 과정의 kernel 동작 때문에 hardware가 transaction을 doomed 상태로 만들 수 있습니다.
Syscall은 suspended mode에서 수행되므로 side effect는 transaction의 성공이나 실패와 무관하게 persistent합니다. 어떤 syscall이 transaction 성공에 영향을 주는지는 kernel이 보장하지 않습니다.
Library를 통해 호출할 때 active transaction의 syscall abort에 의존하면 주의해야 합니다. Library가 값을 cache하여 성공처럼 보이게 하거나 kernel 진입 전에 transaction failure를 일으켜 다른 failure code가 나올 수 있습니다. 예로 glibc의 `getpid()`와 lazy symbol resolution이 있습니다.
Signal delivery와 두 register state
97-126Transaction 중 synchronous 또는 asynchronous signal을 전달할 때 두 번째 transactional register state를 나타내는 `ucontext`/`mcontext`가 추가됩니다. Signal delivery는 `treclaim`으로 두 register state를 capture하므로 transaction을 abort합니다.
Signal handler에 전달되는 일반 `ucontext_t`는 checkpointed/original register state를 나타내며, signal이 `tbegin+4`에서 발생한 것처럼 보입니다.
Handler의 `ucontext`에 `uc_link`가 set되어 있으면 두 번째 `ucontext`가 전달된 것입니다. Forward compatibility를 위해 `MSR.TS` field를 검사해 transactional state인지 확인해야 합니다. Transactional state라면 `uc->uc_link`가 signal 발생 시점의 active transactional register를 나타냅니다.
64-bit process에서는 `uc->uc_mcontext.regs->msr`가 full 64-bit MSR이며 TS field가 transactional mode를 표시합니다.
32-bit process의 mcontext MSR은 32-bit뿐이므로 상위 32 bit가 두 번째 ucontext의 `uc->uc_link->uc_mcontext.regs->msr`에 저장됩니다. Transactional state TS는 이 upper word에 있습니다.
기본 signal handler는 transaction을 알 필요가 없고 handler에서 단순히 return하면 정상 처리됩니다. 반면 crash handler처럼 SIGSEGV를 일으킨 instruction address를 알아야 하는 transaction-aware handler는 두 번째 ucontext의 transactional register state를 읽어야 합니다.
Checkpointed state는 기본 ucontext에, signal 시점의 speculative state는 uc_link의 두 번째 ucontext에 들어갑니다.
Transaction-aware signal handler 예
127-151다음 원문 예제는 `uc_link`의 두 번째 context와 `MSR_TM_ACTIVE(msr)`를 검사하여 transaction restart address와 실제 crash instruction address를 구분합니다.
void crash_handler(int sig, siginfo_t *si, void *uc)
{
ucontext_t *ucp = uc;
ucontext_t *transactional_ucp = ucp->uc_link;
if (ucp_link) {
u64 msr = ucp->uc_mcontext.regs->msr;
/* May have transactional ucontext! */
#ifndef __powerpc64__
msr |= ((u64)transactional_ucp->uc_mcontext.regs->msr) << 32;
#endif
if (MSR_TM_ACTIVE(msr)) {
/* Yes, we crashed during a transaction. Oops. */
fprintf(stderr, "Transaction to be restarted at 0x%llx, but "
"crashy instruction was at 0x%llx\n",
ucp->uc_mcontext.regs->nip,
transactional_ucp->uc_mcontext.regs->nip);
}
}
fix_the_problem(ucp->dar);
}
예제의 identifier와 indentation은 원문 그대로 보존했습니다. 구현 시 실제 선언과 field 접근을 사용 중인 ABI header에 맞춰 검토해야 합니다.
Signal frame과 checkpointed stack
152-173Active transaction에서 signal을 받을 때는 stack을 주의해야 합니다. `tbegin` 뒤 stack이 위로 되돌아갔을 수 있습니다. 대표적으로 function 안에서 `tbegin`을 실행한 뒤 `tend` 전에 function이 return한 경우 stack 자체가 checkpointed transactional memory state의 일부입니다.
이 stack을 non-transactional mode나 suspended mode에서 덮어쓴 뒤 TM abort가 발생하면 program counter와 stack pointer는 `tbegin`으로 돌아가지만 memory의 stack 내용은 더 이상 유효하지 않습니다.
이를 피하려면 active transaction의 signal frame은 speculative state가 아니라 checkpointed state의 stack pointer를 사용해야 합니다. 그러면 TM suspended 상태에서 기록하는 signal context가 rollback에 필요한 stack 아래에 배치됩니다. `treclaim`으로 transaction이 abort되므로 `tbegin`과 signal 사이의 memory write는 어차피 rollback됩니다.
Non-TM 또는 suspended mode에서 받은 signal은 normal/non-checkpointed stack pointer를 사용합니다. Signal handler 내부에서 시작한 transaction이 handler return 시점에 suspended 상태라면 kernel이 reclaim하여 폐기합니다.
Signal frame은 rollback 뒤에도 유효해야 하므로 checkpointed stack pointer 아래에 기록합니다.
Kernel transaction failure cause code
174-194Kernel이 transaction을 abort한 원인을 구분하는 code는 `<asm/reg.h>`에 정의됩니다.
원문 표의 cause symbol과 의미, persistent 예를 보존했습니다.
Userspace abort handler는 `TEXASR[0:7]`에서 cause를 확인할 수 있습니다. Bit 7이 set되면 persistent error입니다. 예를 들어 `TM_CAUSE_ALIGNMENT`는 persistent이고 `TM_CAUSE_RESCHED`는 persistent가 아닙니다.
GDB와 ptrace 제한
195-204현재 GDB와 ptrace는 TM-aware가 아닙니다. Transaction 중 stop하면 checkpointed state가 제시되어 transaction이 막 시작된 것처럼 보입니다.
이 상태에서는 transaction을 계속할 수 없고 failure handler 경로를 타며, 두 번째 transactional register state에도 접근할 수 없습니다. GDB로 TM program 자체를 다룰 수는 있지만 transaction 내부를 의미 있게 debug할 수는 없습니다.
POWER9 revision별 TM 동작
205-248POWER9 TM에는 complete register state 저장 문제가 있습니다. 원문은 이를 우회한 commit을 제시합니다.
commit 4bb3c7a0208fc13ca70598efd109901a7cd45ae7
Author: Paul Mackerras <paulus@ozlabs.org>
Date: Wed Mar 21 21:32:01 2018 +1100
KVM: PPC: Book3S HV: Work around transactional memory bugs in POWER9
이 차이 때문에 POWER9 chip revision마다 TM enable 방식이 다릅니다.
POWER9N/POWER9C revision과 userspace HWCAP2 노출, emulation 동작을 비교합니다.
POWER9N DD2.1에서는 firmware가 TM suspend 시 항상 abort하도록 구성합니다. `tsuspend`와 kernel exception은 transaction을 abort하고 rollback하며 exception 자체는 발생하지 않습니다. TM suspend를 enable한 sigcontext도 kernel이 거부합니다.
POWER9N DD2.2 이상에서는 KVM과 POWERVM이 guest TM을 emulate합니다. Guest userspace에는 `HWCAP2[PPC_FEATURE2_HTM]`이 set되지만 TM suspend를 많이 사용하면 hypervisor trap 때문에 성능이 저하됩니다. Host userspace에는 현재 TM이 disabled이며 향후 host context-switch emulation이 추가되면 달라질 수 있습니다.
POWER9C DD1.2 이상은 POWERVM에서만 제공되어 Linux는 guest로 실행되고 POWER9N DD2.2와 같이 TM을 emulate합니다.
POWER8 guest를 POWER9로 migration하는 것은 TM emulation이 있는 POWER9N DD2.2와 POWER9C DD1.2에서 가능합니다. 더 이른 POWER9 processor에는 emulation이 없어 지원되지 않습니다.
Kernel의 h/rfid mtmsrd quirk 사용
249-274ISA의 `rfid` quirk는 early exception handling에 유용합니다. Userspace transaction에서 exception으로 kernel에 들어오면 MSR은 `TM=0`, `TS=01`, 즉 TM은 off지만 suspended 상태가 됩니다.
Kernel이 MSR bit를 바꾸기 위해 `rfid`를 수행하면서 SRR0에 `TM=0`, `TS=00`을 지정해도 결과 MSR은 이전의 `TM=0`, `TS=01`을 유지할 수 있습니다. 보통 `TS=01`에서 `TS=00`으로 가는 suspend-to-non-transactional 전이는 illegal이지만 architecture가 이 경우를 quirk로 허용합니다.
Architecture의 `rfid` 정의는 다음 조건으로 이를 설명합니다.
if (MSR 29:31 ¬ = 0b010 | SRR1 29:31 ¬ = 0b000) then
MSR 29:31 <- SRR1 29:31
`hrfid`와 `mtmsrd`에도 같은 quirk가 있으며 Linux kernel은 early exception handling에서 이를 사용합니다.
SRR1이 non-transactional state를 요청해도 조건에 따라 기존 suspended state가 유지됩니다.
요약과 해설
transactional_memory.rst:1-274POWER TM은 `tbegin`의 checkpoint와 `tend` 사이 변경을 atomic하게 commit하거나 모두 rollback합니다. Linux ABI에서 가장 중요한 부분은 syscall의 persistent side effect, signal이 제공하는 두 register context, checkpointed stack 사용, 그리고 POWER9 revision마다 다른 HWCAP2 노출입니다.