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;
86 # Tracing without a P uses a global trace buffer.
88 # Above TRACEGLOBAL can emit a trace event without a P.
90 # Below TRACEGLOBAL manages the global tracing buffer.
91 # Note that traceBuf eventually chains to MALLOC, but we never get that far
92 # in the situation where there's no P.
94 # Starting/stopping tracing traces strings.
95 traceBuf < traceStrings;
104 # Above MALLOC are things that can allocate memory.
106 # Below MALLOC is the malloc implementation.
115 MPROF < profInsert, profBlock, profMemActive;
116 profMemActive < profMemFuture;
118 # Execution tracer events (with a P)
125 # Above TRACE is anything that can create a trace event
130 # Stack allocation and copying
138 # Anything that can grow the stack can acquire STACKGROW.
139 # (Most higher layers imply STACKGROW, like MALLOC.)
141 # Below STACKGROW is the stack allocator/copying implementation.
143 gscan, rwmutexR < stackpool;
145 # Generally, hchan must be acquired before gscan. But in one case,
146 # where we suspend a G and then shrink its stack, syncadjustsudogs
147 # can acquire hchan locks while holding gscan. To allow this case,
148 # we use hchanLeaf instead of hchan.
156 # Anything that can have write barriers can acquire WB.
157 # Above WB, we can have write barriers.
159 # Below WB is the write barrier implementation.
166 # Above mheap is anything that can call the span allocator.
168 # Below mheap is the span allocator implementation.
169 mheap, mheapSpecial < globalAlloc;
171 # panic is handled specially. It is implicitly below all other locks.
176 // cyclicRanks lists lock ranks that allow multiple locks of the same
177 // rank to be acquired simultaneously. The runtime enforces ordering
178 // within these ranks using a separate mechanism.
179 var cyclicRanks = map[string]bool{
180 // Multiple timers are locked simultaneously in destroy().
182 // Multiple hchans are acquired in hchan.sortkey() order in
185 // Multiple hchanLeafs are acquired in hchan.sortkey() order in
186 // syncadjustsudogs().
191 flagO := flag.String("o", "", "write to `file` instead of stdout")
192 flagDot := flag.Bool("dot", false, "emit graphviz output instead of Go")
194 if flag.NArg() != 0 {
195 fmt.Fprintf(os.Stderr, "too many arguments")
199 g, err := dag.Parse(ranks)
207 g.TransitiveReduction()
208 // Add cyclic edges for visualization.
209 for k := range cyclicRanks {
212 // Reverse the graph. It's much easier to read this as
213 // a "<" partial order than a ">" partial order. This
214 // ways, locks are acquired from the top going down
215 // and time moves forward over the edges instead of
223 out, err = format.Source(b.Bytes())
230 err = os.WriteFile(*flagO, out, 0666)
232 _, err = os.Stdout.Write(out)
239 func generateGo(w io.Writer, g *dag.Graph) {
240 fmt.Fprintf(w, `// Code generated by mklockrank.go; DO NOT EDIT.
248 // Create numeric ranks.
250 for i, j := 0, len(topo)-1; i < j; i, j = i+1, j-1 {
251 topo[i], topo[j] = topo[j], topo[i]
254 // Constants representing the ranks of all non-leaf runtime locks, in rank order.
255 // Locks with lower rank must be taken before locks with higher rank,
256 // in addition to satisfying the partial order in lockPartialOrder.
257 // A few ranks allow self-cycles, which are specified in lockPartialOrder.
259 lockRankUnknown lockRank = iota
262 for _, rank := range topo {
264 fmt.Fprintf(w, "\t// %s\n", rank)
266 fmt.Fprintf(w, "\t%s\n", cname(rank))
271 // lockRankLeafRank is the rank of lock that does not have a declared rank,
272 // and hence is a leaf lock.
273 const lockRankLeafRank lockRank = 1000
276 // Create string table.
278 // lockNames gives the names associated with each of the above ranks.
279 var lockNames = []string{
281 for _, rank := range topo {
283 fmt.Fprintf(w, "\t%s: %q,\n", cname(rank), rank)
288 func (rank lockRank) String() string {
292 if rank == lockRankLeafRank {
295 if rank < 0 || int(rank) >= len(lockNames) {
298 return lockNames[rank]
302 // Create partial order structure.
304 // lockPartialOrder is the transitive closure of the lock rank graph.
305 // An entry for rank X lists all of the ranks that can already be held
306 // when rank X is acquired.
308 // Lock ranks that allow self-cycles list themselves.
309 var lockPartialOrder [][]lockRank = [][]lockRank{
311 for _, rank := range topo {
316 for _, before := range g.Edges(rank) {
317 if !isPseudo(before) {
318 list = append(list, cname(before))
321 if cyclicRanks[rank] {
322 list = append(list, cname(rank))
325 fmt.Fprintf(w, "\t%s: {%s},\n", cname(rank), strings.Join(list, ", "))
327 fmt.Fprintf(w, "}\n")
330 // cname returns the Go const name for the given lock rank label.
331 func cname(label string) string {
332 return "lockRank" + strings.ToUpper(label[:1]) + label[1:]
335 func isPseudo(label string) bool {
336 return strings.ToUpper(label) == label
339 // generateDot emits a Graphviz dot representation of g to w.
340 func generateDot(w io.Writer, g *dag.Graph) {
341 fmt.Fprintf(w, "digraph g {\n")
344 for _, node := range g.Nodes {
345 fmt.Fprintf(w, "%q;\n", node)
349 for _, node := range g.Nodes {
350 for _, to := range g.Edges(node) {
351 fmt.Fprintf(w, "%q -> %q;\n", node, to)
355 fmt.Fprintf(w, "}\n")