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.
70 scavenge, sweep < hchan;
72 hchan, notifyList < sudog;
76 rwmutexW, sysmon < rwmutexR;
87 NONE < userArenaState;
89 # Tracing without a P uses a global trace buffer.
91 # Above TRACEGLOBAL can emit a trace event without a P.
93 # Below TRACEGLOBAL manages the global tracing buffer.
94 # Note that traceBuf eventually chains to MALLOC, but we never get that far
95 # in the situation where there's no P.
97 # Starting/stopping tracing traces strings.
98 traceBuf < traceStrings;
108 # Above MALLOC are things that can allocate memory.
110 # Below MALLOC is the malloc implementation.
119 MPROF < profInsert, profBlock, profMemActive;
120 profMemActive < profMemFuture;
122 # Stack allocation and copying
131 # Anything that can grow the stack can acquire STACKGROW.
132 # (Most higher layers imply STACKGROW, like MALLOC.)
134 # Below STACKGROW is the stack allocator/copying implementation.
136 gscan, rwmutexR < stackpool;
138 # Generally, hchan must be acquired before gscan. But in one case,
139 # where we suspend a G and then shrink its stack, syncadjustsudogs
140 # can acquire hchan locks while holding gscan. To allow this case,
141 # we use hchanLeaf instead of hchan.
149 # Anything that can have write barriers can acquire WB.
150 # Above WB, we can have write barriers.
152 # Below WB is the write barrier implementation.
159 # Above mheap is anything that can call the span allocator.
161 # Below mheap is the span allocator implementation.
162 mheap, mheapSpecial < globalAlloc;
164 # Execution tracer events (with a P)
172 # Above TRACE is anything that can create a trace event
177 # panic is handled specially. It is implicitly below all other locks.
179 # deadlock is not acquired while holding panic, but it also needs to be
180 # below all other locks.
182 # raceFini is only held while exiting.
186 // cyclicRanks lists lock ranks that allow multiple locks of the same
187 // rank to be acquired simultaneously. The runtime enforces ordering
188 // within these ranks using a separate mechanism.
189 var cyclicRanks = map[string]bool{
190 // Multiple timers are locked simultaneously in destroy().
192 // Multiple hchans are acquired in hchan.sortkey() order in
195 // Multiple hchanLeafs are acquired in hchan.sortkey() order in
196 // syncadjustsudogs().
198 // The point of the deadlock lock is to deadlock.
203 flagO := flag.String("o", "", "write to `file` instead of stdout")
204 flagDot := flag.Bool("dot", false, "emit graphviz output instead of Go")
206 if flag.NArg() != 0 {
207 fmt.Fprintf(os.Stderr, "too many arguments")
211 g, err := dag.Parse(ranks)
219 g.TransitiveReduction()
220 // Add cyclic edges for visualization.
221 for k := range cyclicRanks {
224 // Reverse the graph. It's much easier to read this as
225 // a "<" partial order than a ">" partial order. This
226 // ways, locks are acquired from the top going down
227 // and time moves forward over the edges instead of
235 out, err = format.Source(b.Bytes())
242 err = os.WriteFile(*flagO, out, 0666)
244 _, err = os.Stdout.Write(out)
251 func generateGo(w io.Writer, g *dag.Graph) {
252 fmt.Fprintf(w, `// Code generated by mklockrank.go; DO NOT EDIT.
260 // Create numeric ranks.
262 for i, j := 0, len(topo)-1; i < j; i, j = i+1, j-1 {
263 topo[i], topo[j] = topo[j], topo[i]
266 // Constants representing the ranks of all non-leaf runtime locks, in rank order.
267 // Locks with lower rank must be taken before locks with higher rank,
268 // in addition to satisfying the partial order in lockPartialOrder.
269 // A few ranks allow self-cycles, which are specified in lockPartialOrder.
271 lockRankUnknown lockRank = iota
274 for _, rank := range topo {
276 fmt.Fprintf(w, "\t// %s\n", rank)
278 fmt.Fprintf(w, "\t%s\n", cname(rank))
283 // lockRankLeafRank is the rank of lock that does not have a declared rank,
284 // and hence is a leaf lock.
285 const lockRankLeafRank lockRank = 1000
288 // Create string table.
290 // lockNames gives the names associated with each of the above ranks.
291 var lockNames = []string{
293 for _, rank := range topo {
295 fmt.Fprintf(w, "\t%s: %q,\n", cname(rank), rank)
300 func (rank lockRank) String() string {
304 if rank == lockRankLeafRank {
307 if rank < 0 || int(rank) >= len(lockNames) {
310 return lockNames[rank]
314 // Create partial order structure.
316 // lockPartialOrder is the transitive closure of the lock rank graph.
317 // An entry for rank X lists all of the ranks that can already be held
318 // when rank X is acquired.
320 // Lock ranks that allow self-cycles list themselves.
321 var lockPartialOrder [][]lockRank = [][]lockRank{
323 for _, rank := range topo {
328 for _, before := range g.Edges(rank) {
329 if !isPseudo(before) {
330 list = append(list, cname(before))
333 if cyclicRanks[rank] {
334 list = append(list, cname(rank))
337 fmt.Fprintf(w, "\t%s: {%s},\n", cname(rank), strings.Join(list, ", "))
339 fmt.Fprintf(w, "}\n")
342 // cname returns the Go const name for the given lock rank label.
343 func cname(label string) string {
344 return "lockRank" + strings.ToUpper(label[:1]) + label[1:]
347 func isPseudo(label string) bool {
348 return strings.ToUpper(label) == label
351 // generateDot emits a Graphviz dot representation of g to w.
352 func generateDot(w io.Writer, g *dag.Graph) {
353 fmt.Fprintf(w, "digraph g {\n")
356 for _, node := range g.Nodes {
357 fmt.Fprintf(w, "%q;\n", node)
361 for _, node := range g.Nodes {
362 for _, to := range g.Edges(node) {
363 fmt.Fprintf(w, "%q -> %q;\n", node, to)
367 fmt.Fprintf(w, "}\n")