tuning ws 1b1 locks
TRANSCRIPT
8/8/2019 Tuning Ws 1b1 Locks
http://slidepdf.com/reader/full/tuning-ws-1b1-locks 1/38
Center of Expertise
Copyright © Oracle Corporation, 2005. All rights reserved.
Performance Diagnostics WorkshopLesson 1B-1: Latches, Locks & Pins
PDF created with pdfFactory Pro trial version www.pdffactory.com
8/8/2019 Tuning Ws 1b1 Locks
http://slidepdf.com/reader/full/tuning-ws-1b1-locks 2/38
1b1-2
1b1-2 Copyright © Oracle Corporation, 2005. All rights reserved.
Oracle Internal Use OnlyOracle Internal Use Only
What this lesson is about:Concurrency Control
• The Necessity Thereof
• Oracle’s concurrency structures
• Algorithm basics
• Diagnosing latch, lock, and pin contention
PDF created with pdfFactory Pro trial version www.pdffactory.com
8/8/2019 Tuning Ws 1b1 Locks
http://slidepdf.com/reader/full/tuning-ws-1b1-locks 3/38
1b1-3
1b1-3 Copyright © Oracle Corporation, 2005. All rights reserved.
Oracle Internal Use OnlyOracle Internal Use Only
Fundamental Observation:Two objects cannot occupy the sam e space at
the same time
• In computer systems, we want to allow multipleprocesses to share resources, operate concurrently
• Shared memory, I/O means the possibility of steppingon one another’s toes, corrupting data structures, etc.
• Must allow concurrency to scale, yet avoid resource
conflicts• Concurrency mechanism depends on cost / benefit
– Latches: fast and inexpensive, no orderly queuing
– Locks (Enqueues): expensive but fair and orderly
– Pins: Like enqueues but ensure coherency of an object
PDF created with pdfFactory Pro trial version www.pdffactory.com
8/8/2019 Tuning Ws 1b1 Locks
http://slidepdf.com/reader/full/tuning-ws-1b1-locks 4/38
1b1-4
1b1-4 Copyright © Oracle Corporation, 2005. All rights reserved.
Oracle Internal Use OnlyOracle Internal Use Only
Concurrency in daily life…
• Traffic control during rush hour
• Buying a hamburger
• Revolt in the delicatessen
• Two cooks in the kitchen
• Chicago Mercantile Exchange trading floor
Everyone wants to go at the same time. We know that in groups, we must cooperate. But
without formal control mechanisms, humans give way to impulse and order breaks
down. Our daily systems become chaotic and less efficient.
We use a semaphore-like device to control traffic, namely the traffic light. Some lights
are programmed to temporarily favour one direction of traffic over another, to
accommodate rush hour traffic patterns. This provides absolute order, as long as drivers
cooperate. Physically, nothing prevents a driver from running a red light. Fortunately, we
humans tend to obey our own rules, as long as some symbol of reference exists– such asa traffic light. The light acts as a “lock” in this manner.
We all get impatient during traffic jams, waiting for the light. On the other hand, when alight is not operating, it takes much longer to get through the intersection since the traffic
light no longer provides equitable, smooth service. Smoothness is the key to efficient
systems, and concurrency control makes that possible.
PDF created with pdfFactory Pro trial version www.pdffactory.com
8/8/2019 Tuning Ws 1b1 Locks
http://slidepdf.com/reader/full/tuning-ws-1b1-locks 5/38
1b1-5
Concurrency in daily life (cont’d)
You walk into McDonalds and see three registers open, each with a line of waiting
customers. How do you choose a line? The shortest? Fastest moving? The shortest line
may be served by the newest, least efficient employee. Some customers are penalized for
poor line choice, even though they may not have enough information to make a good
choice.
Some restaurants have a single queue for all registers – similar to airport ticket counters.
By enforcing control over the order of service, all customers are treated fairly. Or
equally unfairly, depending on your viewpoint. With a single queue, individual wait
times are similar, less variant. Variance is the enemy of smoothness and good overallperformance.
At some deli counters, a ticket system is employed. As you arrive at the counter, you get
a numbered ticket from a dispenser. A sign on a wall somewhere tells you what the
currently-served number is. You get an idea of where you are in the queue, plus a sense
of security from knowing you don’t have to fight for service. Until a server calls thewrong number, of course.
In my house, the kitchen is fairly large, so it is possible for two people to cook at the
same time. Nevertheless, my wife and I often reach for the same utensil at the same time.
It can be chaotic, but only occasionally and briefly. No need for a deli-style ticket system
to control access to the sink, the wait periods are too brief. What is required is patience
and discipline.
In a open outcry market, such as the trading floor of the Chicago Mercantile Exchange,
lungpower rules the day. There is no real transaction-ordering system at all. When you
want to buy or sell, you have to shout directly and clearly. You miss the transaction more
often than not during busy periods, but persistence pays. It is chaotic, but for realtimetransactions, a formal queueing mechanism is too slow.
PDF created with pdfFactory Pro trial version www.pdffactory.com
8/8/2019 Tuning Ws 1b1 Locks
http://slidepdf.com/reader/full/tuning-ws-1b1-locks 6/38
1b1-6
1b1-6 Copyright © Oracle Corporation, 2005. All rights reserved.
Oracle Internal Use OnlyOracle Internal Use Only
Latches
• Used to manage concurrency for a specificoperation in the Oracle kernel
• Very fast and inexpensive locking mechanism
• Serializes access to a shared resource to preventcorruption
• Often, latches are gotten as part of the process of
getting locks or pins
• Depends on hardware and operating systemresources, so implementation is platform specific
PDF created with pdfFactory Pro trial version www.pdffactory.com
8/8/2019 Tuning Ws 1b1 Locks
http://slidepdf.com/reader/full/tuning-ws-1b1-locks 7/38
1b1-7
1b1-7 Copyright © Oracle Corporation, 2005. All rights reserved.
Oracle Internal Use OnlyOracle Internal Use Only
Latch Characteristics
• Implemented as atomic instructions
• Typically “exclusive” only
• Extremely fast to get; a few milliseconds
• Contention is more of a statistical function than asingle long latch hold (unlike an enqueue)
PDF created with pdfFactory Pro trial version www.pdffactory.com
8/8/2019 Tuning Ws 1b1 Locks
http://slidepdf.com/reader/full/tuning-ws-1b1-locks 8/38
1b1-8
1b1-8 Copyright © Oracle Corporation, 2005. All rights reserved.
Oracle Internal Use OnlyOracle Internal Use Only
How the Oracle Kernel Uses Latches
/* Non-critical code */
. . .
someResourceStruct = getAddressOfResource(name);
/* Critical code: Get the latch and lock */
latchAddr = getLatchforResource(someResourceStruct);
getLock(somreResourceStruct, mySessionID);
freeLatch(latchAddr);
/* Lock is now held...other code that needs the lock held */
readDataFromResource(dataStruct->contents, myData );
. . . Lots of other code . . .
/* Critical code: Get the latch and release the lock */
latchAddr = getLatchforResource(someResourceStruct);
releaseLock(somreResourceStruct, mySessionID);
freeLatch(latchAddr);
Explanation
This is a fictional piece of code that that illustrates how a shared resource might beupdated in a safe manner. The shared resource maintains a list of lock holders (bysessionID); the list can only be updated when the session acquires an exclusivelatch to ensure no other session is doing this operation at the same time.
The following line will get the latch and return its address:latchAddr = getLatchforResource(someResourceStruct);
When this function returns, the latch will be held by the session. Its possible thatthis latch was not available for some time due to contention. In that case, thesession would have waited on the “latch free” wait event.
When the session updates the lock structure, it becomes a lock holder to theresource (simply in share mode). The session can now be sure that the structurewill be stable for reading (assuming the code ensures the lock holders list has noother lock holders before an eXclusive lock is gotten and a modification isperformed). This simplified example doesn’t show how exclusive holders mightblock other exclusive or shared lock waiters.
Notice the latch is released as soon as possible, while the lock is actually held for amuch longer time.
This example is very similar to the way the library cache latches and locks interact.
PDF created with pdfFactory Pro trial version www.pdffactory.com
8/8/2019 Tuning Ws 1b1 Locks
http://slidepdf.com/reader/full/tuning-ws-1b1-locks 9/38
1b1-9
1b1-9 Copyright © Oracle Corporation, 2005. All rights reserved.
Oracle Internal Use OnlyOracle Internal Use Only
Symmetric MultiProcessors
• Multiple CPUs, shared memory• Only 1 cpu per word per cycle may update memory (“testand set” instruction)
C
PU
1
C
PU
3
C
PU
2
C
PU
4
X
SHARED MEMORY (WORDS)
Contemporary CPUs support atomic instructions that permit a “lock” mechanism to be
implemented such that the lock is either gotten or not, in a single instruction cycle.
Typically, this is a test-and-set instruction that allows latches to be gotten in exclusive
mode only. Newer machines support compare-and-swap (CAS) as well. CAS
instructions go a bit further with functionality, allowing a latch to be implemented in
shared mode as well as exclusive. Shared latches are beyond the scope of today’sdiscussion.
Prior to the implementation of such atomic instructions, this had to be implemented
purely in code. The classic algorithm for this is knows as Dekker’s Algorithm. While not
terribly long or complex, it cannot compare in performance to a test-and-set instruction.
A Pascal version of the code for Dekker’s Algorithm is on the following slide.
PDF created with pdfFactory Pro trial version www.pdffactory.com
8/8/2019 Tuning Ws 1b1 Locks
http://slidepdf.com/reader/full/tuning-ws-1b1-locks 10/38
1b1-10
1b1-10 Copyright © Oracle Corporation, 2005. All rights reserved.
Oracle Internal Use OnlyOracle Internal Use Only
Types of Latches
• Solitary, like the redo allocation latch
• Parent / Child, like the library cache latches
• Parent and its children have same name
• Parent mostly used as “placeholder” andstatistics-collection structure
• Child latches promote scalability where there issome reasonable way to partition access to aresource
PDF created with pdfFactory Pro trial version www.pdffactory.com
8/8/2019 Tuning Ws 1b1 Locks
http://slidepdf.com/reader/full/tuning-ws-1b1-locks 11/38
1b1-11
1b1-11 Copyright © Oracle Corporation, 2005. All rights reserved.
Oracle Internal Use OnlyOracle Internal Use Only
Latch Structures
• Internal structures in shared pool
• Tracked by state objects
• Contain “undo” information in case a process failswhile holding a latch
– PMON can read the latch state object and releasethe latch by applying the latch “undo”
PDF created with pdfFactory Pro trial version www.pdffactory.com
8/8/2019 Tuning Ws 1b1 Locks
http://slidepdf.com/reader/full/tuning-ws-1b1-locks 12/38
1b1-12
1b1-12 Copyright © Oracle Corporation, 2005. All rights reserved.
Oracle Internal Use OnlyOracle Internal Use Only
Two ways to get a latch
• No-wait
• Willing-to-wait
• Not a characteristic of the latch, rather of the codethat acquires it
• Certain latches never gotten no-wait (eg sharedpool latch)
PDF created with pdfFactory Pro trial version www.pdffactory.com
8/8/2019 Tuning Ws 1b1 Locks
http://slidepdf.com/reader/full/tuning-ws-1b1-locks 13/38
1b1-13
1b1-13 Copyright © Oracle Corporation, 2005. All rights reserved.
Oracle Internal Use OnlyOracle Internal Use Only
No wait latch gets
• Fast, single attempt to acquire the latch
• If not available, go do something productive, comeback later
• Or, go on to another “candidate” latch, ifapplicable (eg redo copy latch)
• Sooner or later, all no-wait gets will becomewilling-to-wait gets if the latch is not readily
available• Latch contention never involves no-wait latch gets
PDF created with pdfFactory Pro trial version www.pdffactory.com
8/8/2019 Tuning Ws 1b1 Locks
http://slidepdf.com/reader/full/tuning-ws-1b1-locks 14/38
1b1-14
1b1-14 Copyright © Oracle Corporation, 2005. All rights reserved.
Oracle Internal Use OnlyOracle Internal Use Only
Willing-to-wait Latch Acquisition
1. One quick attempt to get
2. If not successful, “spin” (loop; each loop isanother attempt) until we get the latch, or reach
_spin_count value
3. Sleep
4. Wake up, repeat spin cycle
5. Each sleep, double sleep time (to a limit)
Spin Count
Altering spin_count is not a good idea in the vast majority of latch contentionsituations. At best, a change to spin_count may mask a symptom or introduce aslight improvement in system stability, but the underlying problem will remain andeventually must be dealt with.
Spin count controls a loop limit. Imagine a simple “for” loop:
For (i= 0; i< _spin_count; i++) { get latch }
A change to _spin_count parameter controls all latches; this is often overkill when just a particular component’s latches are affected (like the library cache). In somecases, this could introduce undesirable side effects.
PDF created with pdfFactory Pro trial version www.pdffactory.com
8/8/2019 Tuning Ws 1b1 Locks
http://slidepdf.com/reader/full/tuning-ws-1b1-locks 15/38
1b1-15
1b1-15 Copyright © Oracle Corporation, 2005. All rights reserved.
Oracle Internal Use OnlyOracle Internal Use Only
Sleeps are expensive
• Compare time to take a breath to taking a walkaround the block
• Sleep time increases with each failed spin cycle.Each next sleep is twice the previous one.
• By comparison, a latch miss is inconsequential
• Therefore, pay attention to sleeps, not hit/miss
ratios• In 9i+ versions, actual time spent waiting for a
latch is available
Sleeps
Sleeps are a closer reflection of the time waited to acquire a latch than misses. Await for a latch will cause misses to be incremented by one, but sleeps mayincrement several times depending on how many attempts were required to get thelatch. Also, since each sleep period is double the previous one, greater sleeps implya much greater amount of time. “Time to acquire” is really the important fact fordiagnosing latch problems.
PDF created with pdfFactory Pro trial version www.pdffactory.com
8/8/2019 Tuning Ws 1b1 Locks
http://slidepdf.com/reader/full/tuning-ws-1b1-locks 16/38
1b1-16
1b1-16 Copyright © Oracle Corporation, 2005. All rights reserved.
Oracle Internal Use OnlyOracle Internal Use Only
Common Parent / Child latches
• Cache buffer chains: protects hash chains forbuffer cache hash table
• Library cache: protects hash chains for librarycache hash table
• Cache buffers lru chain: protects LRU bufferlinked lists. 1 per working set
PDF created with pdfFactory Pro trial version www.pdffactory.com
8/8/2019 Tuning Ws 1b1 Locks
http://slidepdf.com/reader/full/tuning-ws-1b1-locks 17/38
1b1-17
1b1-17 Copyright © Oracle Corporation, 2005. All rights reserved.
Oracle Internal Use OnlyOracle Internal Use Only
Tools to find contention
• Statspack has several sections on latches
– Only bother with if ‘latch free’ in top 5 timed events
– Pay attention to sleeps only , all other stats arerelatively unimportant for most tuning efforts
– The sleepiest latch is the problem latch
• V$LATCH and V$LATCH_CHILDREN have latchstatistics since startup
– Always sample the value between two points in timeand get the difference to see sleepiest latches
– Latch child number can be used for drilldowns(Which SQL statements protected by latch #5?)
Latch Wait Events
In RDBMS versions prior to 10g, most latch waits were represented by the “latchfree” wait event. As of 10g, the most common latches have their own wait events.E.g., for the library cache latches, the wait event would be called, “latch: librarycache”
PDF created with pdfFactory Pro trial version www.pdffactory.com
8/8/2019 Tuning Ws 1b1 Locks
http://slidepdf.com/reader/full/tuning-ws-1b1-locks 18/38
1b1-18
1b1-18 Copyright © Oracle Corporation, 2005. All rights reserved.
Oracle Internal Use OnlyOracle Internal Use Only
Tools to find contentionStatspack: Latch Activity and Sleep Breakdown
Latch Activity DB/Inst: ORA10/ora10 Snaps: 34-35
Pct Avg Wait Pct
Get Get Slps Time NoWait NoWait
Latch Requests Miss /Miss (s) Requests Miss
------------------------ -------------- ------ ------ ------ ------------ ------
cache buffers chains 4,944,774 4.4 0.0 10 250 0.0
library cache 6,717,818 10.0 0.1 719 1,341,417 8.8
redo allocation 1,056 0.1 0.0 0 2,810 0.0
redo copy 0 0 2,829 0.6
row cache objects 5,611,983 12.5 0.0 21 5,046 1.1
shared pool 7,499,659 14.4 0.1 488 0
Latch Sleep breakdown DB/Inst: ORA10/ora10 Snaps: 34-35
Get
Latch Name Requests Misses Sleeps
-------------------------- -------------- ----------- -----------
shared pool 7,499,659 1,079,331 61,931
row cache objects 5,611,983 701,582 1,649
library cache 6,717,818 673,652 59,172
cache buffers chains 4,944,774 216,972 1,222
Misses overstates therow cache objects latchimpact.
Sleeps is much moreaccurate.
% of Time waiting forRCO latch = 21/1238 =1.7%
% of Misses for RCO latch = 26.2%
% of Sleeps for RCO latch = 1.3%
Latch Impact
In 9i+, the actual amount of time spent waiting for a latch is given in V$LATCH andconsequently in Statspack. Prior to 9i, one had to estimate the impact using thisformula:
Impact of latch (seconds) = Value of “Latch Free” wait event (seconds) * Sleeps of aspecific latch / Total sleeps for all latches
PDF created with pdfFactory Pro trial version www.pdffactory.com
8/8/2019 Tuning Ws 1b1 Locks
http://slidepdf.com/reader/full/tuning-ws-1b1-locks 19/38
1b1-19
1b1-19 Copyright © Oracle Corporation, 2005. All rights reserved.
Oracle Internal Use OnlyOracle Internal Use Only
Tools to find contentionStatspack: Latch Miss Sources
Latch Miss Sources DB/Inst: ORA10/ora10 Snaps: 34-35
NoWait Waiter
Latch Name Where Misses Sleeps Sleeps
------------------------ -------------------------- ------- ---------- --------
library cache kglupc: child 0 8,756 7,479
library cache kglpndl: child: before pro 0 8,752 1,753
library cache kglhdgn: child: 0 1,156 12,516
• Latch Miss Sources tells us which parts of Oracle’scode was impacted by latch waits
• When Oracle gets a latch, it tags the latch with
information on where it was requested (code location)• Oracle Support and Development use this
• Sleeps column indicates sleeps the location caused
• Waiter Sleeps column indicates sleeps experienced
when latch was requested in the location
Sleeps column:
Counts the number of sleeps that happened because the latch was held in aparticular location
Waiter Sleeps column:
Counts the number sleeps that happened when the latch was requested in aparticular location
PDF created with pdfFactory Pro trial version www.pdffactory.com
8/8/2019 Tuning Ws 1b1 Locks
http://slidepdf.com/reader/full/tuning-ws-1b1-locks 20/38
1b1-20
1b1-20 Copyright © Oracle Corporation, 2005. All rights reserved.
Oracle Internal Use OnlyOracle Internal Use Only
Tools to find contentionStatspack: Child Latch Stats
Child Latch Statistics DB/Inst: ORA10/ora10 Snaps: 355-356
Child Get Spin &
Latch Name Num Requests Misses Sleeps Sleeps 1->3+
---------------------- ------- ------------ ----------- ---------- ------------
library cache 1 3,168,914 409,682 17,182 393059/16113
library cache 5 867,886 63,077 9,924 53405/9444/2
library cache 4 863,085 62,452 9,387 53287/8964/1
library cache 3 861,064 62,632 9,500 53364/9059/1
library cache 2 859,241 61,783 9,213 52760/8847/1
• Latch number 1 is twice as sleepy as others
• This example was from a hard parse problem• Possibly, some shared SQL covered by the latch
was impacted by the unshared SQL
PDF created with pdfFactory Pro trial version www.pdffactory.com
8/8/2019 Tuning Ws 1b1 Locks
http://slidepdf.com/reader/full/tuning-ws-1b1-locks 21/38
1b1-21
1b1-21 Copyright © Oracle Corporation, 2005. All rights reserved.
Oracle Internal Use OnlyOracle Internal Use Only
Enqueues
• Enqueues (Locks) provide queueing properties – Lock compatibility modes (shared, exclusive, etc)
– Wait until at the head of the list
– Converters have priority over waiters
• Can be used within and between instances (RAC)
• Enqueues maintained in either of two ways:
– Client: Enqueue structure maintained by a client
layer of Oracle’s kernel, in its own structures
– library cache locks, buffer “locks”
– Managed: Oracle manages enqueue structures in acommon resource pool…created on demand
– DML locks, ST locks, CI locks
PDF created with pdfFactory Pro trial version www.pdffactory.com
8/8/2019 Tuning Ws 1b1 Locks
http://slidepdf.com/reader/full/tuning-ws-1b1-locks 22/38
1b1-22
1b1-22 Copyright © Oracle Corporation, 2005. All rights reserved.
Oracle Internal Use OnlyOracle Internal Use OnlyManaged Enqueue Resource
TM-432-0
Owners
Waiters
Converters
Exclusive
SharedShared
Shared to Exclusive
Unique Key {
PDF created with pdfFactory Pro trial version www.pdffactory.com
8/8/2019 Tuning Ws 1b1 Locks
http://slidepdf.com/reader/full/tuning-ws-1b1-locks 23/38
8/8/2019 Tuning Ws 1b1 Locks
http://slidepdf.com/reader/full/tuning-ws-1b1-locks 24/38
1b1-24
1b1-24 Copyright © Oracle Corporation, 2005. All rights reserved.
Oracle Internal Use OnlyOracle Internal Use Only
LatchBucket
#19MR-6-0 TX-3440-98 TS-2-1
Emptyresource
Emptyresource
Emptyresource
Emptyresource
Latch
Linked lists arevulnerable toconcurrentchanges!
We use a lower levellock, a Latch, to
protect such lists.
We Get a Lock to Get a Lock
Oracle is a highly concurrent engine. Many user session processes are modifying the
SGA at the same time. As such, there is an inherent risk that two processes might act on
a single linked list structure at the same time. This would be disastrous! If one process
changes the list as another is scanning it, the second process might try to access a
temporarily-nonsensical address and cause a crash.
For this reason, we use a much lower locking mechanism called a “latch” to protect
certain volatile memory structures such as linked lists. So, we need to get this low level
latch lock in order to get our enqueue. How do we keep concurrent latch gets from
colliding with one another in a manner similar to our enqueue hash table problem? Theanswer is: they cannot collide, because of their “atomic” implementation. That means
that only one process at a time is able to acquire a latch, by virtue of how Symmetric
Multi Processor (SMP) architecture machines work.
We will discuss latches in a few slides in more detail.
PDF created with pdfFactory Pro trial version www.pdffactory.com
8/8/2019 Tuning Ws 1b1 Locks
http://slidepdf.com/reader/full/tuning-ws-1b1-locks 25/38
1b1-25
1b1-25 Copyright © Oracle Corporation, 2005. All rights reserved.
Oracle Internal Use OnlyOracle Internal Use Only
Enqueue Compatibility
When a lock is held, an attempt to get another onefollows these compatibility rules:
Held/Get
Null
SS
SX
S
SSX
X
Null
x
x
x
x
x
x
SX
x
x
x
x
x
SS
x
x
x
S
x
x
x
SSX
x
x
X
x
So, if a session has exclusive ownership of an enqueue, then no other session may obtain
any more of ownership on that enqueue until the owning session releases it. Since a
session that requires exclusive ownership cannot do so while a shared owner hold the
enqueue, shared mode blocks a session that requires exclusive access. This is how we
can guarantee that a table cannot mutate while dml is in process– dml is always
performed under a shared mode object-level lock on all affected objects.
Here is what the modes mean:
• SS = Row Share (lock a row in shared mode)
• SX = Row Exclusive (lock a row in exclusive mode)• S = Share (lock the entire table in shared mode)
• SSX = Share Row Exclusive (lock the table in shared mode but a row in
exclusive)
• X = Exclusive (lock the entire table in exclusive mode)
PDF created with pdfFactory Pro trial version www.pdffactory.com
8/8/2019 Tuning Ws 1b1 Locks
http://slidepdf.com/reader/full/tuning-ws-1b1-locks 26/38
1b1-26
1b1-26 Copyright © Oracle Corporation, 2005. All rights reserved.
Oracle Internal Use OnlyOracle Internal Use Only
Deadlock Detection
• A session may hold an enqueue desired by anothersession and request a different enqueue being held byanother session
• Other sessions may hold an enqueue desired byanother session and request an enqueue already heldby another session
• This situation is called a deadlock
• Oracle must be able to detect deadlocks and resolvethem
• When an enqueue wait times out, Oracle will activateits deadlock detection algorithm
• When detected, one of the sessions receives an ORA-60 error while attempting to acquire the enqueue
PDF created with pdfFactory Pro trial version www.pdffactory.com
8/8/2019 Tuning Ws 1b1 Locks
http://slidepdf.com/reader/full/tuning-ws-1b1-locks 27/38
1b1-27
1b1-27 Copyright © Oracle Corporation, 2005. All rights reserved.
Oracle Internal Use OnlyOracle Internal Use Only
Configuring Enqueuesdefault settings are fine
enqueue_resources: resource structures
_enqueue_locks: lock structures
_enqueue_hash: bucket count (size) of hash table
_enqueue_hash_chain_latches: number of latches
protecting the hash chains of the resource structure
SELECT resource_name, initial_allocation, current_utilization, max_utilization
FROM v$resource_limit
WHERE resource_name LIKE '%enqueue%'
RESOURCE_NAME INITIAL_AL CURRENT_UTILIZATION MAX_UTILIZATION
------------------------------ ---------- ------------------- ---------------
enqueue_locks 2230 11 21
enqueue_resources 968 11 50
PDF created with pdfFactory Pro trial version www.pdffactory.com
8/8/2019 Tuning Ws 1b1 Locks
http://slidepdf.com/reader/full/tuning-ws-1b1-locks 28/38
1b1-28
1b1-28 Copyright © Oracle Corporation, 2005. All rights reserved.
Oracle Internal Use OnlyOracle Internal Use Only
Causes for Enqueue Contention
• Low enqueue hold times, but high demand for it
– DIY sequences
• High enqueue hold times, low or high demand for it
– Someone holds a lock, does not release it soon enough
• Enqueue hold times can be indefinite
• SELECT … FOR UPDATE; Then go to lunch.
• Increasing enqueue_resources is definitely not the
solution
• Problem is not the lock, per se. It is the thing that islocked!
PDF created with pdfFactory Pro trial version www.pdffactory.com
8/8/2019 Tuning Ws 1b1 Locks
http://slidepdf.com/reader/full/tuning-ws-1b1-locks 29/38
1b1-29
1b1-29 Copyright © Oracle Corporation, 2005. All rights reserved.
Oracle Internal Use OnlyOracle Internal Use Only
Viewing Locks with V$LOCK
TY ID1 ID2 SID LMODE REQUEST BLOCK
-- ---------- ---------- ---------- ---------- ---------- ----------
TS 2 1 6 3 0 0
TX 327718 14507 12 0 6 0
TX 327718 14507 13 0 6 0
TX 327718 14507 14 6 0 1
XR 4 0 5 1 0 0
BlockerWaiterHolder
ID1, ID2 vary by lock type andprovide helpful information forresolving the lock
A lock converter would have LMODE and REQUEST set accordingly
This lock scenario was created by selecting for update in one session; then,repeating the same select for update in a different session.
Lock Modes
0 - none
1 - null (NULL)
2 - row-S (SS)
3 - row-X (SX)
4 - share (S)
5 - S/Row-X (SSX)
6 - exclusive (X)
PDF created with pdfFactory Pro trial version www.pdffactory.com
8/8/2019 Tuning Ws 1b1 Locks
http://slidepdf.com/reader/full/tuning-ws-1b1-locks 30/38
1b1-30
1b1-30 Copyright © Oracle Corporation, 2005. All rights reserved.
Oracle Internal Use OnlyOracle Internal Use Only
Other Ways to Detect Enqueue Contention
• V$SESSION – ROW_WAIT_OBJ#, ROW_WAIT_FILE#, ROW_WAIT_BLOCK#
– 10g: BLOCKING_SESSION, BLOCKING_SESSION_STATUS
• V$SESSION_WAIT
– WHERE event = ‘enqueue’ AND wait_time=0
– P1, P2, P3 give the enqueue type, mode and ID1
• Enterprise Manager
PDF created with pdfFactory Pro trial version www.pdffactory.com
8/8/2019 Tuning Ws 1b1 Locks
http://slidepdf.com/reader/full/tuning-ws-1b1-locks 31/38
1b1-31
1b1-31 Copyright © Oracle Corporation, 2005. All rights reserved.
Oracle Internal Use OnlyOracle Internal Use Only
General Rules for Reducing LockContention
• Reduce frequency of lock gets
• Reduce hold time of lock
• Approach always depends on type of lock and theapplication itself
– Eg ST enqueue protects two dictionary tables usedfor extent management. Switch to locally managedtablespaces to eliminate this issue altogether
PDF created with pdfFactory Pro trial version www.pdffactory.com
8/8/2019 Tuning Ws 1b1 Locks
http://slidepdf.com/reader/full/tuning-ws-1b1-locks 32/38
1b1-32
1b1-32 Copyright © Oracle Corporation, 2005. All rights reserved.
Oracle Internal Use OnlyOracle Internal Use Only
What are Pins?
• Sometimes a verb, or a noun• ‘pin’ a cursor means “flag” it for non-removal (keep it),
unrelated to a library cache pin
• As a noun, a pin is a type of lock
• Pins are used to ensure coherency of an object in memory
– To ensure object is in memory before access is permitted
– To ensure changes to an object occur in an orderly fashion
• Pins are similar to enqueues
– Have same queueing property
– Share and exclusive Modes
• Do not have dynamic lock resources, i.e., always presentas part of an object’s data structure
• Commonly used in buffer cache and library cache
The dbms_pool.keep() procedure let’s you “pin” a cursor or a pl/sql object. That means
we flag that object so that it will not be flushed from the library cache even when we are
starved for memory. This use of the word “pin” is unrelated to our discussion of Locks,
Latches and Pins.
In the noun use of pin, a pin is simply another type of lock. While enqueues are typically
used to manage process concurrency at a high level – such as transaction management,
and latches are used to protect extremely low level structures such as linked lists, Pins
are used to protect larger memory structures. Such structures typically include data block
buffers as well as various chunks of memory used to construct cursors and other librarycache objects.
PDF created with pdfFactory Pro trial version www.pdffactory.com
8/8/2019 Tuning Ws 1b1 Locks
http://slidepdf.com/reader/full/tuning-ws-1b1-locks 33/38
1b1-33
1b1-33 Copyright © Oracle Corporation, 2005. All rights reserved.
Oracle Internal Use OnlyOracle Internal Use Only
Pin ExampleBuffer Cache Pins
• Resource structure is part of the buffer header
• Each buffer header has pin structures
• Owners & waiters queues, but no convertersqueue
• Buffer locks and buffer pins are actually the samething
• Protects modifications to the buffer itself
– During read from disk – During a block modifcation (e.g., update)
• A cache buffers chains latch is used to locate abuffer header and either pin the buffer header ormake itself a waiter
PDF created with pdfFactory Pro trial version www.pdffactory.com
8/8/2019 Tuning Ws 1b1 Locks
http://slidepdf.com/reader/full/tuning-ws-1b1-locks 34/38
1b1-34
1b1-34 Copyright © Oracle Corporation, 2005. All rights reserved.
Oracle Internal Use OnlyOracle Internal Use Only
Detecting Contention for Pins
• For buffer cache, use ‘buffer busy waits’ waitevent
• For library cache, ‘library cache pins’ wait event
• Buffer busy waits are common, lib cache pins areless an issue
• More detail on buffer cache and library cache pinswill be given in upcoming lessons
Library cache pins can be tracked down this way:
If Statspack shows library cache pin waits as one of the top five wait events, the during a
busy period query v$session_wait this way:
Select sid, p1raw from v$session_wait
where event = ‘library cache pin’;
You may have to repeat the query a number of times to get a row result back. It is
helpful to spool output to a file. From the query result, take p1raw and use in this query:
SELECT kglnaown "Owner", kglnaobj "Object" FROM x$kglob
WHERE kglhdadr='&P1RAW' ;
This will at least locate the object and owner that is under contention.
PDF created with pdfFactory Pro trial version www.pdffactory.com
8/8/2019 Tuning Ws 1b1 Locks
http://slidepdf.com/reader/full/tuning-ws-1b1-locks 35/38
1b1-35
Buffer Busy Waits – a simple hot block drill-down.
V$session_wait contains most of what we need. P1 is file#, P2 is block, P3 is the reason code. Event is 'buffer busywaits'. Wait_time=0 means "currently waiting“, so we only see those sessions that are actually waiting for this event.Group by p1, p2, p3, sid to find common objects involved in contention. Since this query gets data in real time, youmay have to repeat it until rows are returned. Spool the output for later examination.
select p1, p2, p3, sid from v$session_waitwhere event = 'buffer busy waits'
and wait_time = 0group by p1, p2, p3, sid
/
P1 P2 P3 SID---------- ---------- -------- ----------
9 28 220 279 28 220 289 28 220 309 28 220 349 28 220 35
Obviously, several sessions are waiting for the same file and block. Now find theobject:
select segment_name , segment_type , owner , tablespace_namefrom sys.dba_extentswhere file_id = 9and 28 between block_id and (block_id+(blocks-1))
SEGMENT_NAME SEGMENT_TYPE OWNER TABLESPACE_NAME----------------- -------------- --------- ---------------------FRED TABLE ROGER USERS
Reason Codes:0 The block is being read100 We want to NEW the block but the block is currently being read by another session(most likely for undo)200 We want to NEW the block but someone else has is using the current copy so we have towait for them to finish230 Trying to get a buffer in CR/CRX mode , but a modification has started on the buffer
that has not yet been completed231 CR/CRX scan found the CURRENT block, but a modification has started on the bufferthat has not yet been completed130 Block is being read by another session and no other suitable block image was found, sowe wait until the read is completed. This may also occur after a buffer cache assumed deadlock. Thekernel can't get a buffer in a certain amount of time and assumes a deadlock. Therefore it will read the CRversion of the block 110 We want the CURRENT block either shared or exclusive but the Block is being readinto cache by another session, so we have to wait until their read() is completed120 We want to get the block in current mode but someone else is currently reading it intothe cache. Wait for them to complete the read. This occurs during buffer lookup210 The session wants the block in SCUR or XCUR mode. If this is a buffer exchange or thesession is in discrete TX mode, the session waits for the first time and the second time escalates the block as a deadlock and so does not show up as waiting very long. In this case the statistic: "exchange
deadlocks" is incremented and we yield the CPU for the "buffer deadlock" wait event220 During buffer lookup for a CURRENT copy of a buffer we have found the buffer butsomeone holds it in an incompatible mode so we have to wait
PDF created with pdfFactory Pro trial version www.pdffactory.com
8/8/2019 Tuning Ws 1b1 Locks
http://slidepdf.com/reader/full/tuning-ws-1b1-locks 36/38
1b1-36
1b1-36 Copyright © Oracle Corporation, 2005. All rights reserved.
Oracle Internal Use OnlyOracle Internal Use Only
select a.p1, a.p2, a.p3, a.sid, b.sql_hash_value, c.sql_text
from v$session_wait a, v$session b, v$sqlarea c
where a.event = 'buffer busy waits' and a.wait_time = 0
and a.sid = b.sid and b.sql_hash_value = c.hash_value
group by a.p1, a.p2, a.p3, a.sid, b.sql_hash_value, c.sql_text
P1 P2 P3 SID SQL_HASH_VALUE
SQL_TEXT
----------- ---------- ----------- ---------- -----------------
2 5156 220 40 1492811408
INSERT INTO JACK ( C2 ) VALUES ( SYSDATE )
2 5156 220 44 1492811408
INSERT INTO JACK ( C2 ) VALUES ( SYSDATE )
P3 is Reason Code: 220 = waiting for Current copy, mode not compatible
V$SESSION_WAIT Example
PDF created with pdfFactory Pro trial version www.pdffactory.com
8/8/2019 Tuning Ws 1b1 Locks
http://slidepdf.com/reader/full/tuning-ws-1b1-locks 37/38
1b1-37
1b1-37 Copyright © Oracle Corporation, 2005. All rights reserved.
Oracle Internal Use OnlyOracle Internal Use Only
What have we discussed?
• Very brief discussion of concurrency control
• Latches
• Enqueues
• Pins
• A “big picture” view to put this in perspective
• Some diagnostics
PDF created with pdfFactory Pro trial version www.pdffactory.com
8/8/2019 Tuning Ws 1b1 Locks
http://slidepdf.com/reader/full/tuning-ws-1b1-locks 38/38
1b1-38 Copyright © Oracle Corporation, 2005. All rights reserved.
Oracle Internal Use OnlyOracle Internal Use Only
Further Study…
Enqueues• Metalink note: 62354.1 TX enqueue wait scenarios
• Note: 15476.1 General lock FAQ
Latches
• Note: 22908.1 General discussion of latch issues
• Lots of other Metalink notes on specific latches
Buffer Pins
• Note: 155971.1 is essentially a case study