Programming Examples
PowerPC e500 Core Family Reference Manual, Rev. 1
Freescale Semiconductor A-7
A.1.3.1 Notes
1. In general, lwarx and stwcx. should be paired, with the same effective address used for
both. The only exception is that an unpaired stwcx. to any (scratch) effective address can
be used to clear any reservation held by the processor.
2. It is acceptable to execute a lwarx for which no stwcx. is executed. For example, this
occurs in the test and set sequence shown above if the value loaded is not zero.
3. To increase the likelihood that forward progress is made, it is important that looping on
lwarx/stwcx. pairs be minimized. For example, in the sequence shown above for test and
set, this is achieved by testing the old value before attempting the store: were the order
reversed, more stwcx. instructions might be executed, and reservations might more often
be lost between the lwarx and the stwcx..
4. The manner in which lwarx and stwcx. are communicated to other processors and
mechanisms, and between levels of the memory subsystem within a given processor is
implementation dependent (see Section 3.3.1.7, “Atomic Update Primitives Using lwarx
and stwcx.”). In some implementations performance may be improved by minimizing
looping on a lwarx instruction that fails to return a desired value. For example, in the test
and set example shown above, if the programmer wishes to stay in the loop until the word
loaded is zero, he could change the bne- $+12 to bne- loop. However, in some
implementations better performance may be obtained by using an ordinary load
instruction to do the initial checking of the value, as follows.
loop: lwz r5,0(r3) #load the word
cmpi cr0,0,r5,0 #loop back if word
bc 4,2,loop # not equal to 0
lwarx r5,0,r3 #try again, reserving
cmpi cr0,0,r5,0 # (likely to succeed)
bc 4,2,loop
stwcx. r4,0,r3 #try to store non-0
bc 4,2,loop #loop if lost reservation
5. In a multiprocessor, livelock is possible if a loop containing a lwarx/stwcx. pair also
contains an ordinary store instruction for which any byte of the affected memory area is in
the reservation granule: see Section 3.3.1.7, “Atomic Update Primitives Using lwarx and
stwcx.” For example, the first code sequence shown in Section A.1.3, “List Insertion,” can
cause livelock if two list elements have next element pointers in the same reservation
granule.