~emersion/drmdb

ref: 09fb82de3ecc5a42a61fbb6bf71029d6a45c8e8a drmdb/cmd/drmdump/main.go -rw-r--r-- 10.7 KiB
09fb82deSimon Ser Fix format/modifier pretty-printing 8 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
package main

import (
	"encoding/json"
	"flag"
	"fmt"
	"log"
	"os"
	"path/filepath"
	"syscall"

	"git.sr.ht/~emersion/drmdb/drmtree"
	"git.sr.ht/~emersion/drmdb/treefmt"
	"git.sr.ht/~emersion/go-drm"
)

var capNames = map[drm.Cap]string{
	drm.CapDumbBuffer:          "DUMB_BUFFER",
	drm.CapVblankHighCRTC:      "VBLANK_HIGH_CRTC",
	drm.CapDumbPreferredDepth:  "DUMB_PREFERRED_DEPTH",
	drm.CapDumbPreferredShadow: "DUMB_PREFER_SHADOW",
	drm.CapPrime:               "PRIME",
	drm.CapTimestampMonotonic:  "TIMESTAMP_MONOTONIC",
	drm.CapAsyncPageFlip:       "ASYNC_PAGE_FLIP",
	drm.CapCursorWidth:         "CURSOR_WIDTH",
	drm.CapCursorHeight:        "CURSOR_HEIGHT",
	drm.CapAddFB2Modifiers:     "ADDFB2_MODIFIERS",
	drm.CapPageFlipTarget:      "PAGE_FLIP_TARGET",
	drm.CapCRTCInVBlankEvent:   "CRTC_IN_VBLANK_EVENT",
	drm.CapSyncObj:             "SYNCOBJ",
}

var clientCapNames = map[drm.ClientCap]string{
	drm.ClientCapStereo3D:            "STEREO_3D",
	drm.ClientCapUniversalPlanes:     "UNIVERSAL_PLANES",
	drm.ClientCapAtomic:              "ATOMIC",
	drm.ClientCapAspectRatio:         "APSECT_RATIO",
	drm.ClientCapWritebackConnectors: "WRITEBACK_CONNECTORS",
}

func driver(n *drm.Node) (*drmtree.Driver, error) {
	v, err := n.Version()
	if err != nil {
		return nil, fmt.Errorf("cannot get version: %v", err)
	}

	caps := make(map[string]*uint64)
	for c, s := range capNames {
		var ptr *uint64
		val, err := n.GetCap(c)
		if err == nil {
			ptr = &val
		} else if err != syscall.EINVAL {
			return nil, fmt.Errorf("failed to get cap: %v", err)
		}
		caps[s] = ptr
	}

	clientCaps := make(map[string]bool)
	for c, s := range clientCapNames {
		ok := false
		if err := n.SetClientCap(c, 1); err == nil {
			ok = true
		} else if err != syscall.EINVAL {
			return nil, fmt.Errorf("failed to set client cap: %v", err)
		}
		clientCaps[s] = ok
	}

	return &drmtree.Driver{
		Name: v.Name,
		Desc: v.Desc,
		Version: drmtree.DriverVersion{
			Major: v.Major,
			Minor: v.Minor,
			Patch: v.Patch,
			Date:  v.Date,
		},
		Caps:       caps,
		ClientCaps: clientCaps,
	}, nil
}

func device(n *drm.Node) (*drmtree.Device, error) {
	dev, err := n.GetDevice()
	if err != nil {
		return nil, fmt.Errorf("failed to get device: %v", err)
	}

	switch dev := dev.(type) {
	case *drm.PCIDevice:
		return &drmtree.Device{
			BusType: dev.BusType(),
			DeviceData: &drmtree.DevicePCI{
				Vendor:    dev.Vendor,
				Device:    dev.Device,
				SubVendor: dev.SubVendor,
				SubDevice: dev.SubDevice,
			},
		}, nil
	default:
		return &drmtree.Device{BusType: dev.BusType()}, nil
	}
}

func modeList(modes []drm.ModeModeInfo) []drmtree.Mode {
	l := make([]drmtree.Mode, len(modes))
	for i, m := range modes {
		l[i] = drmtree.Mode(m)
	}
	return l
}

func parseFixedPoint16(v interface{}) (interface{}, error) {
	return v.(uint64) >> 16, nil
}

func parseInFormats(v interface{}) (interface{}, error) {
	b := v.([]byte)
	set, err := drm.ParseFormatModifierSet(b)
	if err != nil {
		return nil, err
	}
	m := set.Map()
	l := make([]drmtree.PlaneInFormatsModifier, 0, len(m))
	for mod, fmts := range m {
		l = append(l, drmtree.PlaneInFormatsModifier{
			Modifier: mod,
			Formats:  fmts,
		})
	}
	return l, nil
}

func parseModeID(v interface{}) (interface{}, error) {
	b := v.([]byte)
	mode, err := drm.ParseModeModeInfo(b)
	if err != nil {
		return nil, err
	}
	return (*drmtree.Mode)(mode), nil
}

func parseWritebackPixelFormats(v interface{}) (interface{}, error) {
	b := v.([]byte)
	formats, err := drm.ParseFormats(b)
	if err != nil {
		return nil, err
	}
	return formats, nil
}

func parsePath(v interface{}) (interface{}, error) {
	b := v.([]byte)
	return drm.ParsePath(b)
}

var propertyParsers = map[string]struct {
	objectType   drm.ObjectType
	propertyType drm.PropertyType
	f            func(v interface{}) (interface{}, error)
}{
	"SRC_X":                   {drm.ObjectPlane, drm.PropertyRange, parseFixedPoint16},
	"SRC_Y":                   {drm.ObjectPlane, drm.PropertyRange, parseFixedPoint16},
	"SRC_W":                   {drm.ObjectPlane, drm.PropertyRange, parseFixedPoint16},
	"SRC_H":                   {drm.ObjectPlane, drm.PropertyRange, parseFixedPoint16},
	"IN_FORMATS":              {drm.ObjectPlane, drm.PropertyBlob, parseInFormats},
	"MODE_ID":                 {drm.ObjectCRTC, drm.PropertyBlob, parseModeID},
	"WRITEBACK_PIXEL_FORMATS": {drm.ObjectConnector, drm.PropertyBlob, parseWritebackPixelFormats},
	"PATH":                    {drm.ObjectConnector, drm.PropertyBlob, parsePath},
}

func properties(n *drm.Node, id drm.AnyID) (map[string]drmtree.Property, error) {
	props, err := n.ModeObjectGetProperties(id)
	if err != nil {
		return nil, fmt.Errorf("failed to get properties for object %v: %v", id, err)
	}

	m := make(map[string]drmtree.Property, len(props))
	for propID, propValue := range props {
		prop, err := n.ModeGetProperty(propID)
		if err != nil {
			return nil, fmt.Errorf("failed to get property %v: %v", propID, err)
		}

		var spec interface{}
		switch prop.Type() {
		case drm.PropertyRange:
			min, max, _ := prop.Range()
			spec = &drmtree.PropertySpecRange{Min: min, Max: max}
		case drm.PropertyEnum, drm.PropertyBitmask:
			enums, _ := prop.Enums()
			l := make(drmtree.PropertySpecEnum, len(enums))
			for i, e := range enums {
				l[i] = drmtree.PropertySpecEnumEntry(e)
			}
			spec = l
		case drm.PropertyObject:
			spec, _ = prop.ObjectType()
		case drm.PropertySignedRange:
			min, max, _ := prop.SignedRange()
			spec = &drmtree.PropertySpecSignedRange{Min: min, Max: max}
		}

		var val interface{}
		switch prop.Type() {
		case drm.PropertyBlob:
			blobID := drm.BlobID(propValue)
			if blobID == 0 {
				// NULL blob
				val = []byte(nil)
				break
			}
			b, err := n.ModeGetBlob(blobID)
			if err != nil {
				return nil, fmt.Errorf("failed to get blob %v: %v", blobID, err)
			}
			val = b
		case drm.PropertyObject:
			val = drm.ObjectID(propValue)
		case drm.PropertySignedRange:
			val = int64(propValue)
		default:
			val = propValue
		}

		var data interface{}
		if parser, ok := propertyParsers[prop.Name]; ok {
			if parser.objectType != id.Type() {
				log.Printf("Cannot parse property %v: expected object type %v, got %v", prop.Name, parser.objectType, id.Type())
			}
			if parser.propertyType != prop.Type() {
				log.Printf("Cannot parse property %v: expected property type %v, got %v", prop.Name, parser.propertyType, prop.Type())
			}
			data, err = parser.f(val)
			if err != nil {
				log.Printf("Cannot parse property %v: %v", prop.Name, err)
			}
		}

		m[prop.Name] = drmtree.Property{
			ID:        prop.ID,
			Type:      prop.Type(),
			Immutable: prop.Immutable(),
			Atomic:    prop.Atomic(),
			Spec:      spec,
			RawValue:  propValue,
			Value:     val,
			Data:      data,
		}
	}

	return m, nil
}

func connectors(n *drm.Node, card *drm.ModeCard) ([]drmtree.Connector, error) {
	l := make([]drmtree.Connector, len(card.Connectors))
	for i, id := range card.Connectors {
		conn, err := n.ModeGetConnector(id)
		if err != nil {
			return nil, fmt.Errorf("failed to get connector: %v", err)
		}

		props, err := properties(n, conn.ID)
		if err != nil {
			return nil, fmt.Errorf("failed to get connector properties: %v", err)
		}

		l[i] = drmtree.Connector{
			ID:         conn.ID,
			Type:       conn.Type,
			Status:     conn.Status,
			PhyWidth:   conn.PhyWidth,
			PhyHeight:  conn.PhyHeight,
			Subpixel:   conn.Subpixel,
			Encoders:   conn.PossibleEncoders,
			Modes:      modeList(conn.Modes),
			Properties: props,
		}
	}
	return l, nil
}

func encoders(n *drm.Node, card *drm.ModeCard) ([]drmtree.Encoder, error) {
	l := make([]drmtree.Encoder, len(card.Encoders))
	for i, id := range card.Encoders {
		enc, err := n.ModeGetEncoder(id)
		if err != nil {
			return nil, fmt.Errorf("failed to get encoder: %v", err)
		}

		l[i] = drmtree.Encoder(*enc)
	}
	return l, nil
}

func crtcs(n *drm.Node, card *drm.ModeCard) ([]drmtree.CRTC, error) {
	l := make([]drmtree.CRTC, len(card.CRTCs))
	for i, id := range card.CRTCs {
		crtc, err := n.ModeGetCRTC(id)
		if err != nil {
			return nil, fmt.Errorf("failed to get CRTC: %v", err)
		}

		props, err := properties(n, crtc.ID)
		if err != nil {
			return nil, fmt.Errorf("failed to get CRTC properties: %v", err)
		}

		l[i] = drmtree.CRTC{
			ID:         crtc.ID,
			FB:         crtc.FB,
			X:          crtc.X,
			Y:          crtc.Y,
			GammaSize:  crtc.GammaSize,
			Mode:       (*drmtree.Mode)(crtc.Mode),
			Properties: props,
		}
	}
	return l, nil
}

func planes(n *drm.Node) ([]drmtree.Plane, error) {
	planes, err := n.ModeGetPlaneResources()
	if err != nil {
		log.Fatal(err)
	}

	l := make([]drmtree.Plane, len(planes))
	for i, id := range planes {
		plane, err := n.ModeGetPlane(id)
		if err != nil {
			return nil, fmt.Errorf("failed to get CRTC: %v", err)
		}

		props, err := properties(n, plane.ID)
		if err != nil {
			return nil, fmt.Errorf("failed to get plane properties: %v", err)
		}

		l[i] = drmtree.Plane{
			ID:            plane.ID,
			CRTC:          plane.CRTC,
			FB:            plane.FB,
			PossibleCRTCs: plane.PossibleCRTCs,
			GammaSize:     plane.GammaSize,
			Formats:       plane.Formats,
			Properties:    props,
		}
	}

	return l, nil
}

func node(nodePath string) (*drmtree.Node, error) {
	f, err := os.Open(nodePath)
	if err != nil {
		return nil, fmt.Errorf("failed to open DRM node: %v", err)
	}
	defer f.Close()

	n := drm.NewNode(f.Fd())

	drv, err := driver(n)
	if err != nil {
		return nil, err
	}

	dev, err := device(n)
	if err != nil {
		return nil, err
	}

	r, err := n.ModeGetResources()
	if err != nil {
		return nil, fmt.Errorf("failed to get DRM resources: %v", err)
	}

	conns, err := connectors(n, r)
	if err != nil {
		return nil, err
	}

	encs, err := encoders(n, r)
	if err != nil {
		return nil, err
	}

	crtcs, err := crtcs(n, r)
	if err != nil {
		return nil, err
	}

	planes, err := planes(n)
	if err != nil {
		return nil, err
	}

	return &drmtree.Node{
		Driver:     drv,
		Device:     dev,
		Connectors: conns,
		Encoders:   encs,
		CRTCs:      crtcs,
		Planes:     planes,
	}, nil
}

func main() {
	var (
		outputJSON bool
		input      bool
	)
	flag.BoolVar(&outputJSON, "j", false, "Enable JSON output")
	flag.BoolVar(&input, "i", false, "Read JSON data from stdin")
	flag.Parse()

	var nodes drmtree.NodeMap
	if input {
		if err := json.NewDecoder(os.Stdin).Decode(&nodes); err != nil {
			log.Fatalf("Failed to read JSON: %v", err)
		}
	} else {
		paths, err := filepath.Glob(drm.NodePatternPrimary)
		if err != nil {
			log.Fatalf("Failed to list DRM nodes: %v", err)
		}

		nodes = make(drmtree.NodeMap)
		for _, p := range paths {
			n, err := node(p)
			if err != nil {
				log.Fatal(err)
			}
			nodes[p] = n
		}
	}

	if outputJSON {
		err := json.NewEncoder(os.Stdout).Encode(nodes)
		if err != nil {
			log.Fatalf("Failed to write JSON: %v", err)
		}
	} else {
		tf := treefmt.NewTextFormatter(os.Stdout)
		nodes.FormatTree(tf)
	}
}