1 // Copyright 2022 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
7 // mklockrank records the static rank graph of the locks in the
8 // runtime and generates the rank checking structures in lockrank.go.
23 // ranks describes the lock rank graph. See "go doc internal/dag" for
26 // "a < b" means a must be acquired before b if both are held
27 // (or, if b is held, a cannot be acquired).
29 // "NONE < a" means no locks may be held when a is acquired.
31 // If a lock is not given a rank, then it is assumed to be a leaf
32 // lock, which means no other lock can be acquired while it is held.
33 // Therefore, leaf locks do not need to be given an explicit rank.
35 // Ranks in all caps are pseudo-nodes that help define order, but do
36 // not actually define a rank.
38 // TODO: It's often hard to correlate rank names to locks. Change
39 // these to be more consistent with the locks they label.
55 # Scheduler, timers, netpoll
56 NONE < pollDesc, cpuprof;
60 pollDesc, # pollDesc can interact with timers, which can lock sched.
67 timers < wakeableSleep;
71 scavenge, sweep < hchan;
73 hchan, notifyList < sudog;
77 rwmutexW, sysmon < rwmutexR;
88 NONE < userArenaState;
90 # Tracing without a P uses a global trace buffer.
92 # Above TRACEGLOBAL can emit a trace event without a P.
94 # Below TRACEGLOBAL manages the global tracing buffer.
95 # Note that traceBuf eventually chains to MALLOC, but we never get that far
96 # in the situation where there's no P.
98 # Starting/stopping tracing traces strings.
99 traceBuf < traceStrings;
109 # Above MALLOC are things that can allocate memory.
111 # Below MALLOC is the malloc implementation.
117 # We can acquire gcBitsArenas for pinner bits, and
118 # it's guarded by mspanSpecial.
119 MALLOC, mspanSpecial < gcBitsArenas;
122 MPROF < profInsert, profBlock, profMemActive;
123 profMemActive < profMemFuture;
125 # Stack allocation and copying
134 # Anything that can grow the stack can acquire STACKGROW.
135 # (Most higher layers imply STACKGROW, like MALLOC.)
137 # Below STACKGROW is the stack allocator/copying implementation.
139 gscan, rwmutexR < stackpool;
141 # Generally, hchan must be acquired before gscan. But in one case,
142 # where we suspend a G and then shrink its stack, syncadjustsudogs
143 # can acquire hchan locks while holding gscan. To allow this case,
144 # we use hchanLeaf instead of hchan.
152 # Anything that can have write barriers can acquire WB.
153 # Above WB, we can have write barriers.
155 # Below WB is the write barrier implementation.
162 # Above mheap is anything that can call the span allocator.
164 # Below mheap is the span allocator implementation.
166 # Specials: we're allowed to allocate a special while holding
167 # an mspanSpecial lock, and they're part of the malloc implementation.
168 # Pinner bits might be freed by the span allocator.
169 mheap, mspanSpecial < mheapSpecial;
170 mheap, mheapSpecial < globalAlloc;
172 # Execution tracer events (with a P)
180 # Above TRACE is anything that can create a trace event
185 # panic is handled specially. It is implicitly below all other locks.
187 # deadlock is not acquired while holding panic, but it also needs to be
188 # below all other locks.
190 # raceFini is only held while exiting.
194 // cyclicRanks lists lock ranks that allow multiple locks of the same
195 // rank to be acquired simultaneously. The runtime enforces ordering
196 // within these ranks using a separate mechanism.
197 var cyclicRanks = map[string]bool{
198 // Multiple timers are locked simultaneously in destroy().
200 // Multiple hchans are acquired in hchan.sortkey() order in
203 // Multiple hchanLeafs are acquired in hchan.sortkey() order in
204 // syncadjustsudogs().
206 // The point of the deadlock lock is to deadlock.
211 flagO := flag.String("o", "", "write to `file` instead of stdout")
212 flagDot := flag.Bool("dot", false, "emit graphviz output instead of Go")
214 if flag.NArg() != 0 {
215 fmt.Fprintf(os.Stderr, "too many arguments")
219 g, err := dag.Parse(ranks)
227 g.TransitiveReduction()
228 // Add cyclic edges for visualization.
229 for k := range cyclicRanks {
232 // Reverse the graph. It's much easier to read this as
233 // a "<" partial order than a ">" partial order. This
234 // ways, locks are acquired from the top going down
235 // and time moves forward over the edges instead of
243 out, err = format.Source(b.Bytes())
250 err = os.WriteFile(*flagO, out, 0666)
252 _, err = os.Stdout.Write(out)
259 func generateGo(w io.Writer, g *dag.Graph) {
260 fmt.Fprintf(w, `// Code generated by mklockrank.go; DO NOT EDIT.
268 // Create numeric ranks.
270 for i, j := 0, len(topo)-1; i < j; i, j = i+1, j-1 {
271 topo[i], topo[j] = topo[j], topo[i]
274 // Constants representing the ranks of all non-leaf runtime locks, in rank order.
275 // Locks with lower rank must be taken before locks with higher rank,
276 // in addition to satisfying the partial order in lockPartialOrder.
277 // A few ranks allow self-cycles, which are specified in lockPartialOrder.
279 lockRankUnknown lockRank = iota
282 for _, rank := range topo {
284 fmt.Fprintf(w, "\t// %s\n", rank)
286 fmt.Fprintf(w, "\t%s\n", cname(rank))
291 // lockRankLeafRank is the rank of lock that does not have a declared rank,
292 // and hence is a leaf lock.
293 const lockRankLeafRank lockRank = 1000
296 // Create string table.
298 // lockNames gives the names associated with each of the above ranks.
299 var lockNames = []string{
301 for _, rank := range topo {
303 fmt.Fprintf(w, "\t%s: %q,\n", cname(rank), rank)
308 func (rank lockRank) String() string {
312 if rank == lockRankLeafRank {
315 if rank < 0 || int(rank) >= len(lockNames) {
318 return lockNames[rank]
322 // Create partial order structure.
324 // lockPartialOrder is the transitive closure of the lock rank graph.
325 // An entry for rank X lists all of the ranks that can already be held
326 // when rank X is acquired.
328 // Lock ranks that allow self-cycles list themselves.
329 var lockPartialOrder [][]lockRank = [][]lockRank{
331 for _, rank := range topo {
336 for _, before := range g.Edges(rank) {
337 if !isPseudo(before) {
338 list = append(list, cname(before))
341 if cyclicRanks[rank] {
342 list = append(list, cname(rank))
345 fmt.Fprintf(w, "\t%s: {%s},\n", cname(rank), strings.Join(list, ", "))
347 fmt.Fprintf(w, "}\n")
350 // cname returns the Go const name for the given lock rank label.
351 func cname(label string) string {
352 return "lockRank" + strings.ToUpper(label[:1]) + label[1:]
355 func isPseudo(label string) bool {
356 return strings.ToUpper(label) == label
359 // generateDot emits a Graphviz dot representation of g to w.
360 func generateDot(w io.Writer, g *dag.Graph) {
361 fmt.Fprintf(w, "digraph g {\n")
364 for _, node := range g.Nodes {
365 fmt.Fprintf(w, "%q;\n", node)
369 for _, node := range g.Nodes {
370 for _, to := range g.Edges(node) {
371 fmt.Fprintf(w, "%q -> %q;\n", node, to)
375 fmt.Fprintf(w, "}\n")