]> Cypherpunks.ru repositories - gostls13.git/blob - src/runtime/mklockrank.go
runtime: add mayAcquire annotation for trace.lock
[gostls13.git] / src / runtime / mklockrank.go
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.
4
5 //go:build ignore
6
7 // mklockrank records the static rank graph of the locks in the
8 // runtime and generates the rank checking structures in lockrank.go.
9 package main
10
11 import (
12         "bytes"
13         "flag"
14         "fmt"
15         "go/format"
16         "internal/dag"
17         "io"
18         "log"
19         "os"
20         "strings"
21 )
22
23 // ranks describes the lock rank graph. See "go doc internal/dag" for
24 // the syntax.
25 //
26 // "a < b" means a must be acquired before b if both are held
27 // (or, if b is held, a cannot be acquired).
28 //
29 // "NONE < a" means no locks may be held when a is acquired.
30 //
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.
34 //
35 // Ranks in all caps are pseudo-nodes that help define order, but do
36 // not actually define a rank.
37 //
38 // TODO: It's often hard to correlate rank names to locks. Change
39 // these to be more consistent with the locks they label.
40 const ranks = `
41 # Sysmon
42 NONE
43 < sysmon
44 < scavenge, forcegc;
45
46 # Defer
47 NONE < defer;
48
49 # GC
50 NONE <
51   sweepWaiters,
52   assistQueue,
53   sweep;
54
55 # Scheduler, timers, netpoll
56 NONE < pollDesc, cpuprof;
57 assistQueue,
58   cpuprof,
59   forcegc,
60   pollDesc, # pollDesc can interact with timers, which can lock sched.
61   scavenge,
62   sweep,
63   sweepWaiters
64 < sched;
65 sched < allg, allp;
66 allp < timers;
67 timers < netpollInit;
68
69 # Channels
70 scavenge, sweep < hchan;
71 NONE < notifyList;
72 hchan, notifyList < sudog;
73
74 # RWMutex
75 NONE < rwmutexW;
76 rwmutexW, sysmon < rwmutexR;
77
78 # Semaphores
79 NONE < root;
80
81 # Itabs
82 NONE
83 < itab
84 < reflectOffs;
85
86 # Tracing without a P uses a global trace buffer.
87 scavenge
88 # Above TRACEGLOBAL can emit a trace event without a P.
89 < TRACEGLOBAL
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.
93 < traceBuf;
94 # Starting/stopping tracing traces strings.
95 traceBuf < traceStrings;
96
97 # Malloc
98 allg,
99   hchan,
100   notifyList,
101   reflectOffs,
102   timers,
103   traceStrings
104 # Above MALLOC are things that can allocate memory.
105 < MALLOC
106 # Below MALLOC is the malloc implementation.
107 < fin,
108   gcBitsArenas,
109   mheapSpecial,
110   mspanSpecial,
111   spanSetSpine,
112   MPROF;
113
114 # Memory profiling
115 MPROF < profInsert, profBlock, profMemActive;
116 profMemActive < profMemFuture;
117
118 # Stack allocation and copying
119 gcBitsArenas,
120   netpollInit,
121   profBlock,
122   profInsert,
123   profMemFuture,
124   spanSetSpine,
125   fin,
126   root
127 # Anything that can grow the stack can acquire STACKGROW.
128 # (Most higher layers imply STACKGROW, like MALLOC.)
129 < STACKGROW
130 # Below STACKGROW is the stack allocator/copying implementation.
131 < gscan;
132 gscan, rwmutexR < stackpool;
133 gscan < stackLarge;
134 # Generally, hchan must be acquired before gscan. But in one case,
135 # where we suspend a G and then shrink its stack, syncadjustsudogs
136 # can acquire hchan locks while holding gscan. To allow this case,
137 # we use hchanLeaf instead of hchan.
138 gscan < hchanLeaf;
139
140 # Write barrier
141 defer,
142   gscan,
143   mspanSpecial,
144   sudog
145 # Anything that can have write barriers can acquire WB.
146 # Above WB, we can have write barriers.
147 < WB
148 # Below WB is the write barrier implementation.
149 < wbufSpans;
150
151 # Span allocator
152 stackLarge,
153   stackpool,
154   wbufSpans
155 # Above mheap is anything that can call the span allocator.
156 < mheap;
157 # Below mheap is the span allocator implementation.
158 mheap, mheapSpecial < globalAlloc;
159
160 # Execution tracer events (with a P)
161 hchan,
162   mheap,
163   root,
164   sched,
165   traceStrings,
166   notifyList,
167   fin
168 # Above TRACE is anything that can create a trace event
169 < TRACE
170 < trace
171 < traceStackTab;
172
173 # panic is handled specially. It is implicitly below all other locks.
174 NONE < panic;
175 # deadlock is not acquired while holding panic, but it also needs to be
176 # below all other locks.
177 panic < deadlock;
178 `
179
180 // cyclicRanks lists lock ranks that allow multiple locks of the same
181 // rank to be acquired simultaneously. The runtime enforces ordering
182 // within these ranks using a separate mechanism.
183 var cyclicRanks = map[string]bool{
184         // Multiple timers are locked simultaneously in destroy().
185         "timers": true,
186         // Multiple hchans are acquired in hchan.sortkey() order in
187         // select.
188         "hchan": true,
189         // Multiple hchanLeafs are acquired in hchan.sortkey() order in
190         // syncadjustsudogs().
191         "hchanLeaf": true,
192         // The point of the deadlock lock is to deadlock.
193         "deadlock": true,
194 }
195
196 func main() {
197         flagO := flag.String("o", "", "write to `file` instead of stdout")
198         flagDot := flag.Bool("dot", false, "emit graphviz output instead of Go")
199         flag.Parse()
200         if flag.NArg() != 0 {
201                 fmt.Fprintf(os.Stderr, "too many arguments")
202                 os.Exit(2)
203         }
204
205         g, err := dag.Parse(ranks)
206         if err != nil {
207                 log.Fatal(err)
208         }
209
210         var out []byte
211         if *flagDot {
212                 var b bytes.Buffer
213                 g.TransitiveReduction()
214                 // Add cyclic edges for visualization.
215                 for k := range cyclicRanks {
216                         g.AddEdge(k, k)
217                 }
218                 // Reverse the graph. It's much easier to read this as
219                 // a "<" partial order than a ">" partial order. This
220                 // ways, locks are acquired from the top going down
221                 // and time moves forward over the edges instead of
222                 // backward.
223                 g.Transpose()
224                 generateDot(&b, g)
225                 out = b.Bytes()
226         } else {
227                 var b bytes.Buffer
228                 generateGo(&b, g)
229                 out, err = format.Source(b.Bytes())
230                 if err != nil {
231                         log.Fatal(err)
232                 }
233         }
234
235         if *flagO != "" {
236                 err = os.WriteFile(*flagO, out, 0666)
237         } else {
238                 _, err = os.Stdout.Write(out)
239         }
240         if err != nil {
241                 log.Fatal(err)
242         }
243 }
244
245 func generateGo(w io.Writer, g *dag.Graph) {
246         fmt.Fprintf(w, `// Code generated by mklockrank.go; DO NOT EDIT.
247
248 package runtime
249
250 type lockRank int
251
252 `)
253
254         // Create numeric ranks.
255         topo := g.Topo()
256         for i, j := 0, len(topo)-1; i < j; i, j = i+1, j-1 {
257                 topo[i], topo[j] = topo[j], topo[i]
258         }
259         fmt.Fprintf(w, `
260 // Constants representing the ranks of all non-leaf runtime locks, in rank order.
261 // Locks with lower rank must be taken before locks with higher rank,
262 // in addition to satisfying the partial order in lockPartialOrder.
263 // A few ranks allow self-cycles, which are specified in lockPartialOrder.
264 const (
265         lockRankUnknown lockRank = iota
266
267 `)
268         for _, rank := range topo {
269                 if isPseudo(rank) {
270                         fmt.Fprintf(w, "\t// %s\n", rank)
271                 } else {
272                         fmt.Fprintf(w, "\t%s\n", cname(rank))
273                 }
274         }
275         fmt.Fprintf(w, `)
276
277 // lockRankLeafRank is the rank of lock that does not have a declared rank,
278 // and hence is a leaf lock.
279 const lockRankLeafRank lockRank = 1000
280 `)
281
282         // Create string table.
283         fmt.Fprintf(w, `
284 // lockNames gives the names associated with each of the above ranks.
285 var lockNames = []string{
286 `)
287         for _, rank := range topo {
288                 if !isPseudo(rank) {
289                         fmt.Fprintf(w, "\t%s: %q,\n", cname(rank), rank)
290                 }
291         }
292         fmt.Fprintf(w, `}
293
294 func (rank lockRank) String() string {
295         if rank == 0 {
296                 return "UNKNOWN"
297         }
298         if rank == lockRankLeafRank {
299                 return "LEAF"
300         }
301         if rank < 0 || int(rank) >= len(lockNames) {
302                 return "BAD RANK"
303         }
304         return lockNames[rank]
305 }
306 `)
307
308         // Create partial order structure.
309         fmt.Fprintf(w, `
310 // lockPartialOrder is the transitive closure of the lock rank graph.
311 // An entry for rank X lists all of the ranks that can already be held
312 // when rank X is acquired.
313 //
314 // Lock ranks that allow self-cycles list themselves.
315 var lockPartialOrder [][]lockRank = [][]lockRank{
316 `)
317         for _, rank := range topo {
318                 if isPseudo(rank) {
319                         continue
320                 }
321                 list := []string{}
322                 for _, before := range g.Edges(rank) {
323                         if !isPseudo(before) {
324                                 list = append(list, cname(before))
325                         }
326                 }
327                 if cyclicRanks[rank] {
328                         list = append(list, cname(rank))
329                 }
330
331                 fmt.Fprintf(w, "\t%s: {%s},\n", cname(rank), strings.Join(list, ", "))
332         }
333         fmt.Fprintf(w, "}\n")
334 }
335
336 // cname returns the Go const name for the given lock rank label.
337 func cname(label string) string {
338         return "lockRank" + strings.ToUpper(label[:1]) + label[1:]
339 }
340
341 func isPseudo(label string) bool {
342         return strings.ToUpper(label) == label
343 }
344
345 // generateDot emits a Graphviz dot representation of g to w.
346 func generateDot(w io.Writer, g *dag.Graph) {
347         fmt.Fprintf(w, "digraph g {\n")
348
349         // Define all nodes.
350         for _, node := range g.Nodes {
351                 fmt.Fprintf(w, "%q;\n", node)
352         }
353
354         // Create edges.
355         for _, node := range g.Nodes {
356                 for _, to := range g.Edges(node) {
357                         fmt.Fprintf(w, "%q -> %q;\n", node, to)
358                 }
359         }
360
361         fmt.Fprintf(w, "}\n")
362 }