]> Cypherpunks.ru repositories - gostls13.git/blob - src/runtime/mklockrank.go
runtime: fix lockrank ordering for pinner implementation
[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 # User arena state
87 NONE < userArenaState;
88
89 # Tracing without a P uses a global trace buffer.
90 scavenge
91 # Above TRACEGLOBAL can emit a trace event without a P.
92 < TRACEGLOBAL
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.
96 < traceBuf;
97 # Starting/stopping tracing traces strings.
98 traceBuf < traceStrings;
99
100 # Malloc
101 allg,
102   hchan,
103   notifyList,
104   reflectOffs,
105   timers,
106   traceStrings,
107   userArenaState
108 # Above MALLOC are things that can allocate memory.
109 < MALLOC
110 # Below MALLOC is the malloc implementation.
111 < fin,
112   gcBitsArenas,
113   spanSetSpine,
114   mspanSpecial,
115   MPROF;
116
117 # Memory profiling
118 MPROF < profInsert, profBlock, profMemActive;
119 profMemActive < profMemFuture;
120
121 # Stack allocation and copying
122 gcBitsArenas,
123   netpollInit,
124   profBlock,
125   profInsert,
126   profMemFuture,
127   spanSetSpine,
128   fin,
129   root
130 # Anything that can grow the stack can acquire STACKGROW.
131 # (Most higher layers imply STACKGROW, like MALLOC.)
132 < STACKGROW
133 # Below STACKGROW is the stack allocator/copying implementation.
134 < gscan;
135 gscan, rwmutexR < stackpool;
136 gscan < stackLarge;
137 # Generally, hchan must be acquired before gscan. But in one case,
138 # where we suspend a G and then shrink its stack, syncadjustsudogs
139 # can acquire hchan locks while holding gscan. To allow this case,
140 # we use hchanLeaf instead of hchan.
141 gscan < hchanLeaf;
142
143 # Write barrier
144 defer,
145   gscan,
146   mspanSpecial,
147   sudog
148 # Anything that can have write barriers can acquire WB.
149 # Above WB, we can have write barriers.
150 < WB
151 # Below WB is the write barrier implementation.
152 < wbufSpans;
153
154 # Span allocator
155 stackLarge,
156   stackpool,
157   wbufSpans
158 # Above mheap is anything that can call the span allocator.
159 < mheap;
160 # Below mheap is the span allocator implementation.
161 #
162 # Specials: we're allowed to allocate a special while holding
163 # an mspanSpecial lock, and they're part of the malloc implementation.
164 # Pinner bits might be freed by the span allocator.
165 mheap, mspanSpecial < mheapSpecial;
166 mheap, mheapSpecial < globalAlloc;
167
168 # Execution tracer events (with a P)
169 hchan,
170   mheap,
171   root,
172   sched,
173   traceStrings,
174   notifyList,
175   fin
176 # Above TRACE is anything that can create a trace event
177 < TRACE
178 < trace
179 < traceStackTab;
180
181 # panic is handled specially. It is implicitly below all other locks.
182 NONE < panic;
183 # deadlock is not acquired while holding panic, but it also needs to be
184 # below all other locks.
185 panic < deadlock;
186 # raceFini is only held while exiting.
187 panic < raceFini;
188 `
189
190 // cyclicRanks lists lock ranks that allow multiple locks of the same
191 // rank to be acquired simultaneously. The runtime enforces ordering
192 // within these ranks using a separate mechanism.
193 var cyclicRanks = map[string]bool{
194         // Multiple timers are locked simultaneously in destroy().
195         "timers": true,
196         // Multiple hchans are acquired in hchan.sortkey() order in
197         // select.
198         "hchan": true,
199         // Multiple hchanLeafs are acquired in hchan.sortkey() order in
200         // syncadjustsudogs().
201         "hchanLeaf": true,
202         // The point of the deadlock lock is to deadlock.
203         "deadlock": true,
204 }
205
206 func main() {
207         flagO := flag.String("o", "", "write to `file` instead of stdout")
208         flagDot := flag.Bool("dot", false, "emit graphviz output instead of Go")
209         flag.Parse()
210         if flag.NArg() != 0 {
211                 fmt.Fprintf(os.Stderr, "too many arguments")
212                 os.Exit(2)
213         }
214
215         g, err := dag.Parse(ranks)
216         if err != nil {
217                 log.Fatal(err)
218         }
219
220         var out []byte
221         if *flagDot {
222                 var b bytes.Buffer
223                 g.TransitiveReduction()
224                 // Add cyclic edges for visualization.
225                 for k := range cyclicRanks {
226                         g.AddEdge(k, k)
227                 }
228                 // Reverse the graph. It's much easier to read this as
229                 // a "<" partial order than a ">" partial order. This
230                 // ways, locks are acquired from the top going down
231                 // and time moves forward over the edges instead of
232                 // backward.
233                 g.Transpose()
234                 generateDot(&b, g)
235                 out = b.Bytes()
236         } else {
237                 var b bytes.Buffer
238                 generateGo(&b, g)
239                 out, err = format.Source(b.Bytes())
240                 if err != nil {
241                         log.Fatal(err)
242                 }
243         }
244
245         if *flagO != "" {
246                 err = os.WriteFile(*flagO, out, 0666)
247         } else {
248                 _, err = os.Stdout.Write(out)
249         }
250         if err != nil {
251                 log.Fatal(err)
252         }
253 }
254
255 func generateGo(w io.Writer, g *dag.Graph) {
256         fmt.Fprintf(w, `// Code generated by mklockrank.go; DO NOT EDIT.
257
258 package runtime
259
260 type lockRank int
261
262 `)
263
264         // Create numeric ranks.
265         topo := g.Topo()
266         for i, j := 0, len(topo)-1; i < j; i, j = i+1, j-1 {
267                 topo[i], topo[j] = topo[j], topo[i]
268         }
269         fmt.Fprintf(w, `
270 // Constants representing the ranks of all non-leaf runtime locks, in rank order.
271 // Locks with lower rank must be taken before locks with higher rank,
272 // in addition to satisfying the partial order in lockPartialOrder.
273 // A few ranks allow self-cycles, which are specified in lockPartialOrder.
274 const (
275         lockRankUnknown lockRank = iota
276
277 `)
278         for _, rank := range topo {
279                 if isPseudo(rank) {
280                         fmt.Fprintf(w, "\t// %s\n", rank)
281                 } else {
282                         fmt.Fprintf(w, "\t%s\n", cname(rank))
283                 }
284         }
285         fmt.Fprintf(w, `)
286
287 // lockRankLeafRank is the rank of lock that does not have a declared rank,
288 // and hence is a leaf lock.
289 const lockRankLeafRank lockRank = 1000
290 `)
291
292         // Create string table.
293         fmt.Fprintf(w, `
294 // lockNames gives the names associated with each of the above ranks.
295 var lockNames = []string{
296 `)
297         for _, rank := range topo {
298                 if !isPseudo(rank) {
299                         fmt.Fprintf(w, "\t%s: %q,\n", cname(rank), rank)
300                 }
301         }
302         fmt.Fprintf(w, `}
303
304 func (rank lockRank) String() string {
305         if rank == 0 {
306                 return "UNKNOWN"
307         }
308         if rank == lockRankLeafRank {
309                 return "LEAF"
310         }
311         if rank < 0 || int(rank) >= len(lockNames) {
312                 return "BAD RANK"
313         }
314         return lockNames[rank]
315 }
316 `)
317
318         // Create partial order structure.
319         fmt.Fprintf(w, `
320 // lockPartialOrder is the transitive closure of the lock rank graph.
321 // An entry for rank X lists all of the ranks that can already be held
322 // when rank X is acquired.
323 //
324 // Lock ranks that allow self-cycles list themselves.
325 var lockPartialOrder [][]lockRank = [][]lockRank{
326 `)
327         for _, rank := range topo {
328                 if isPseudo(rank) {
329                         continue
330                 }
331                 list := []string{}
332                 for _, before := range g.Edges(rank) {
333                         if !isPseudo(before) {
334                                 list = append(list, cname(before))
335                         }
336                 }
337                 if cyclicRanks[rank] {
338                         list = append(list, cname(rank))
339                 }
340
341                 fmt.Fprintf(w, "\t%s: {%s},\n", cname(rank), strings.Join(list, ", "))
342         }
343         fmt.Fprintf(w, "}\n")
344 }
345
346 // cname returns the Go const name for the given lock rank label.
347 func cname(label string) string {
348         return "lockRank" + strings.ToUpper(label[:1]) + label[1:]
349 }
350
351 func isPseudo(label string) bool {
352         return strings.ToUpper(label) == label
353 }
354
355 // generateDot emits a Graphviz dot representation of g to w.
356 func generateDot(w io.Writer, g *dag.Graph) {
357         fmt.Fprintf(w, "digraph g {\n")
358
359         // Define all nodes.
360         for _, node := range g.Nodes {
361                 fmt.Fprintf(w, "%q;\n", node)
362         }
363
364         // Create edges.
365         for _, node := range g.Nodes {
366                 for _, to := range g.Edges(node) {
367                         fmt.Fprintf(w, "%q -> %q;\n", node, to)
368                 }
369         }
370
371         fmt.Fprintf(w, "}\n")
372 }