Added few more stubs so that control reaches to DestroyDevice().
[mesa.git] / src / panfrost / lib / gen_pack.py
1 #encoding=utf-8
2
3 # Copyright (C) 2016 Intel Corporation
4 # Copyright (C) 2016 Broadcom
5 # Copyright (C) 2020 Collabora, Ltd.
6 #
7 # Permission is hereby granted, free of charge, to any person obtaining a
8 # copy of this software and associated documentation files (the "Software"),
9 # to deal in the Software without restriction, including without limitation
10 # the rights to use, copy, modify, merge, publish, distribute, sublicense,
11 # and/or sell copies of the Software, and to permit persons to whom the
12 # Software is furnished to do so, subject to the following conditions:
13 #
14 # The above copyright notice and this permission notice (including the next
15 # paragraph) shall be included in all copies or substantial portions of the
16 # Software.
17 #
18 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
21 # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
23 # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
24 # IN THE SOFTWARE.
25
26 import xml.parsers.expat
27 import sys
28 import operator
29 from functools import reduce
30
31 global_prefix = "mali"
32
33 pack_header = """
34 /* Generated code, see midgard.xml and gen_pack_header.py
35 *
36 * Packets, enums and structures for Panfrost.
37 *
38 * This file has been generated, do not hand edit.
39 */
40
41 #ifndef PAN_PACK_H
42 #define PAN_PACK_H
43
44 #include <stdio.h>
45 #include <stdint.h>
46 #include <stdbool.h>
47 #include <assert.h>
48 #include <math.h>
49 #include <inttypes.h>
50 #include "util/u_math.h"
51
52 #define __gen_unpack_float(x, y, z) uif(__gen_unpack_uint(x, y, z))
53
54 static inline uint64_t
55 __gen_uint(uint64_t v, uint32_t start, uint32_t end)
56 {
57 #ifndef NDEBUG
58 const int width = end - start + 1;
59 if (width < 64) {
60 const uint64_t max = (1ull << width) - 1;
61 assert(v <= max);
62 }
63 #endif
64
65 return v << start;
66 }
67
68 static inline uint32_t
69 __gen_sint(int32_t v, uint32_t start, uint32_t end)
70 {
71 #ifndef NDEBUG
72 const int width = end - start + 1;
73 if (width < 64) {
74 const int64_t max = (1ll << (width - 1)) - 1;
75 const int64_t min = -(1ll << (width - 1));
76 assert(min <= v && v <= max);
77 }
78 #endif
79
80 return ((uint32_t) v) << start;
81 }
82
83 static inline uint32_t
84 __gen_padded(uint32_t v, uint32_t start, uint32_t end)
85 {
86 unsigned shift = __builtin_ctz(v);
87 unsigned odd = v >> (shift + 1);
88
89 #ifndef NDEBUG
90 assert((v >> shift) & 1);
91 assert(shift <= 31);
92 assert(odd <= 7);
93 assert((end - start + 1) == 8);
94 #endif
95
96 return __gen_uint(shift | (odd << 5), start, end);
97 }
98
99
100 static inline uint64_t
101 __gen_unpack_uint(const uint8_t *restrict cl, uint32_t start, uint32_t end)
102 {
103 uint64_t val = 0;
104 const int width = end - start + 1;
105 const uint32_t mask = (width == 32 ? ~0 : (1 << width) - 1 );
106
107 for (int byte = start / 8; byte <= end / 8; byte++) {
108 val |= cl[byte] << ((byte - start / 8) * 8);
109 }
110
111 return (val >> (start % 8)) & mask;
112 }
113
114 static inline uint64_t
115 __gen_unpack_sint(const uint8_t *restrict cl, uint32_t start, uint32_t end)
116 {
117 int size = end - start + 1;
118 int64_t val = __gen_unpack_uint(cl, start, end);
119
120 /* Get the sign bit extended. */
121 return (val << (64 - size)) >> (64 - size);
122 }
123
124 static inline uint64_t
125 __gen_unpack_padded(const uint8_t *restrict cl, uint32_t start, uint32_t end)
126 {
127 unsigned val = __gen_unpack_uint(cl, start, end);
128 unsigned shift = val & 0b11111;
129 unsigned odd = val >> 5;
130
131 return (2*odd + 1) << shift;
132 }
133
134 #define pan_pack(dst, T, name) \
135 for (struct MALI_ ## T name = { MALI_ ## T ## _header }, \
136 *_loop_terminate = (void *) (dst); \
137 __builtin_expect(_loop_terminate != NULL, 1); \
138 ({ MALI_ ## T ## _pack((uint32_t *) (dst), &name); \
139 _loop_terminate = NULL; }))
140
141 """
142
143 def to_alphanum(name):
144 substitutions = {
145 ' ': '_',
146 '/': '_',
147 '[': '',
148 ']': '',
149 '(': '',
150 ')': '',
151 '-': '_',
152 ':': '',
153 '.': '',
154 ',': '',
155 '=': '',
156 '>': '',
157 '#': '',
158 '&': '',
159 '*': '',
160 '"': '',
161 '+': '',
162 '\'': '',
163 }
164
165 for i, j in substitutions.items():
166 name = name.replace(i, j)
167
168 return name
169
170 def safe_name(name):
171 name = to_alphanum(name)
172 if not name[0].isalpha():
173 name = '_' + name
174
175 return name
176
177 def prefixed_upper_name(prefix, name):
178 if prefix:
179 name = prefix + "_" + name
180 return safe_name(name).upper()
181
182 def enum_name(name):
183 return "{}_{}".format(global_prefix, safe_name(name)).lower()
184
185 def num_from_str(num_str):
186 if num_str.lower().startswith('0x'):
187 return int(num_str, base=16)
188 else:
189 assert(not num_str.startswith('0') and 'octals numbers not allowed')
190 return int(num_str)
191
192 MODIFIERS = ["shr", "minus"]
193
194 def parse_modifier(modifier):
195 if modifier is None:
196 return None
197
198 for mod in MODIFIERS:
199 if modifier[0:len(mod)] == mod and modifier[len(mod)] == '(' and modifier[-1] == ')':
200 return [mod, int(modifier[(len(mod) + 1):-1])]
201
202 print("Invalid modifier")
203 assert(False)
204
205 class Field(object):
206 def __init__(self, parser, attrs):
207 self.parser = parser
208 if "name" in attrs:
209 self.name = safe_name(attrs["name"]).lower()
210 self.human_name = attrs["name"]
211
212 if ":" in str(attrs["start"]):
213 (word, bit) = attrs["start"].split(":")
214 self.start = (int(word) * 32) + int(bit)
215 else:
216 self.start = int(attrs["start"])
217
218 self.end = self.start + int(attrs["size"]) - 1
219 self.type = attrs["type"]
220
221 if self.type == 'bool' and self.start != self.end:
222 print("#error Field {} has bool type but more than one bit of size".format(self.name));
223
224 if "prefix" in attrs:
225 self.prefix = safe_name(attrs["prefix"]).upper()
226 else:
227 self.prefix = None
228
229 if "exact" in attrs:
230 self.exact = int(attrs["exact"])
231 else:
232 self.exact = None
233
234 self.default = attrs.get("default")
235
236 # Map enum values
237 if self.type in self.parser.enums and self.default is not None:
238 self.default = safe_name('{}_{}_{}'.format(global_prefix, self.type, self.default)).upper()
239
240 self.modifier = parse_modifier(attrs.get("modifier"))
241
242 def emit_template_struct(self, dim, opaque_structs):
243 if self.type == 'address':
244 type = 'uint64_t'
245 elif self.type == 'bool':
246 type = 'bool'
247 elif self.type == 'float':
248 type = 'float'
249 elif self.type == 'uint' and self.end - self.start > 32:
250 type = 'uint64_t'
251 elif self.type == 'int':
252 type = 'int32_t'
253 elif self.type in ['uint', 'padded']:
254 type = 'uint32_t'
255 elif self.type in self.parser.structs:
256 type = 'struct ' + self.parser.gen_prefix(safe_name(self.type.upper()))
257
258 if opaque_structs:
259 type = type.lower() + '_packed'
260 elif self.type in self.parser.enums:
261 type = 'enum ' + enum_name(self.type)
262 else:
263 print("#error unhandled type: %s" % self.type)
264 type = "uint32_t"
265
266 print(" %-36s %s%s;" % (type, self.name, dim))
267
268 for value in self.values:
269 name = prefixed_upper_name(self.prefix, value.name)
270 print("#define %-40s %d" % (name, value.value))
271
272 def overlaps(self, field):
273 return self != field and max(self.start, field.start) <= min(self.end, field.end)
274
275
276 class Group(object):
277 def __init__(self, parser, parent, start, count):
278 self.parser = parser
279 self.parent = parent
280 self.start = start
281 self.count = count
282 self.size = 0
283 self.length = 0
284 self.fields = []
285
286 def emit_template_struct(self, dim, opaque_structs):
287 if self.count == 0:
288 print(" /* variable length fields follow */")
289 else:
290 if self.count > 1:
291 dim = "%s[%d]" % (dim, self.count)
292
293 for field in self.fields:
294 if field.exact is not None:
295 continue
296
297 field.emit_template_struct(dim, opaque_structs)
298
299 class Word:
300 def __init__(self):
301 self.size = 32
302 self.fields = []
303
304 def collect_words(self, words):
305 for field in self.fields:
306 first_word = field.start // 32
307 last_word = field.end // 32
308
309 for b in range(first_word, last_word + 1):
310 if not b in words:
311 words[b] = self.Word()
312
313 words[b].fields.append(field)
314
315 def emit_pack_function(self, opaque_structs):
316 # Determine number of bytes in this group.
317 calculated = max(field.end // 8 for field in self.fields) + 1
318
319 if self.length > 0:
320 assert(self.length >= calculated)
321 else:
322 self.length = calculated
323
324 words = {}
325 self.collect_words(words)
326
327 emitted_structs = set()
328
329 # Validate the modifier is lossless
330 for field in self.fields:
331 if field.modifier is None:
332 continue
333
334 assert(field.exact is None)
335
336 if field.modifier[0] == "shr":
337 shift = field.modifier[1]
338 mask = hex((1 << shift) - 1)
339 print(" assert((values->{} & {}) == 0);".format(field.name, mask))
340 elif field.modifier[0] == "minus":
341 print(" assert(values->{} >= {});".format(field.name, field.modifier[1]))
342
343 for index in range(self.length // 4):
344 # Handle MBZ words
345 if not index in words:
346 print(" cl[%2d] = 0;" % index)
347 continue
348
349 word = words[index]
350
351 word_start = index * 32
352
353 v = None
354 prefix = " cl[%2d] =" % index
355
356 first = word.fields[0]
357 if first.type in self.parser.structs and first.start not in emitted_structs:
358 pack_name = self.parser.gen_prefix(safe_name(first.type.upper()))
359 start = first.start
360 assert((first.start % 32) == 0)
361 assert(first.end == first.start + (self.parser.structs[first.type].length * 8) - 1)
362 emitted_structs.add(first.start)
363
364 if opaque_structs:
365 print(" memcpy(cl + {}, &values->{}, {});".format(first.start // 32, first.name, (first.end - first.start + 1) // 8))
366 else:
367 print(" {}_pack(cl + {}, &values->{});".format(pack_name, first.start // 32, first.name))
368
369 for field in word.fields:
370 name = field.name
371 start = field.start
372 end = field.end
373 field_word_start = (field.start // 32) * 32
374 start -= field_word_start
375 end -= field_word_start
376
377 value = str(field.exact) if field.exact is not None else "values->%s" % name
378 if field.modifier is not None:
379 if field.modifier[0] == "shr":
380 value = "{} >> {}".format(value, field.modifier[1])
381 elif field.modifier[0] == "minus":
382 value = "{} - {}".format(value, field.modifier[1])
383
384 if field.type == "uint" or field.type == "address":
385 s = "__gen_uint(%s, %d, %d)" % \
386 (value, start, end)
387 elif field.type == "padded":
388 s = "__gen_padded(%s, %d, %d)" % \
389 (value, start, end)
390 elif field.type in self.parser.enums:
391 s = "__gen_uint(%s, %d, %d)" % \
392 (value, start, end)
393 elif field.type == "int":
394 s = "__gen_sint(%s, %d, %d)" % \
395 (value, start, end)
396 elif field.type == "bool":
397 s = "__gen_uint(%s, %d, %d)" % \
398 (value, start, end)
399 elif field.type == "float":
400 assert(start == 0 and end == 31)
401 s = "__gen_uint(fui({}), 0, 32)".format(value)
402 elif field.type in self.parser.structs:
403 # Structs are packed directly
404 assert(len(word.fields) == 1)
405 continue
406 else:
407 s = "#error unhandled field {}, type {}".format(name, field.type)
408
409 if not s == None:
410 shift = word_start - field_word_start
411 if shift:
412 s = "%s >> %d" % (s, shift)
413
414 if field == word.fields[-1]:
415 print("%s %s;" % (prefix, s))
416 else:
417 print("%s %s |" % (prefix, s))
418 prefix = " "
419
420 continue
421
422 # Given a field (start, end) contained in word `index`, generate the 32-bit
423 # mask of present bits relative to the word
424 def mask_for_word(self, index, start, end):
425 field_word_start = index * 32
426 start -= field_word_start
427 end -= field_word_start
428 # Cap multiword at one word
429 start = max(start, 0)
430 end = min(end, 32 - 1)
431 count = (end - start + 1)
432 return (((1 << count) - 1) << start)
433
434 def emit_unpack_function(self):
435 # First, verify there is no garbage in unused bits
436 words = {}
437 self.collect_words(words)
438
439 for index in range(self.length // 4):
440 base = index * 32
441 word = words.get(index, self.Word())
442 masks = [self.mask_for_word(index, f.start, f.end) for f in word.fields]
443 mask = reduce(lambda x,y: x | y, masks, 0)
444
445 ALL_ONES = 0xffffffff
446
447 if mask != ALL_ONES:
448 TMPL = ' if (((const uint32_t *) cl)[{}] & {}) fprintf(stderr, "XXX: Invalid field unpacked at word {}\\n");'
449 print(TMPL.format(index, hex(mask ^ ALL_ONES), index))
450
451 for field in self.fields:
452 # Recurse for structs, see pack() for validation
453 if field.type in self.parser.structs:
454 pack_name = self.parser.gen_prefix(safe_name(field.type)).upper()
455 print(" {}_unpack(cl + {}, &values->{});".format(pack_name, field.start // 8, field.name))
456 continue
457
458 convert = None
459
460 args = []
461 args.append('cl')
462 args.append(str(field.start))
463 args.append(str(field.end))
464
465 if field.type in set(["uint", "address"]) | self.parser.enums:
466 convert = "__gen_unpack_uint"
467 elif field.type == "int":
468 convert = "__gen_unpack_sint"
469 elif field.type == "padded":
470 convert = "__gen_unpack_padded"
471 elif field.type == "bool":
472 convert = "__gen_unpack_uint"
473 elif field.type == "float":
474 convert = "__gen_unpack_float"
475 else:
476 s = "/* unhandled field %s, type %s */\n" % (field.name, field.type)
477
478 suffix = ""
479 if field.modifier:
480 if field.modifier[0] == "minus":
481 suffix = " + {}".format(field.modifier[1])
482 elif field.modifier[0] == "shr":
483 suffix = " << {}".format(field.modifier[1])
484
485 decoded = '{}({}){}'.format(convert, ', '.join(args), suffix)
486
487 print(' values->{} = {};'.format(field.name, decoded))
488
489 def emit_print_function(self):
490 for field in self.fields:
491 convert = None
492 name, val = field.human_name, 'values->{}'.format(field.name)
493
494 if field.type in self.parser.structs:
495 pack_name = self.parser.gen_prefix(safe_name(field.type)).upper()
496 print(' fprintf(fp, "%*s{}:\\n", indent, "");'.format(field.human_name))
497 print(" {}_print(fp, &values->{}, indent + 2);".format(pack_name, field.name))
498 elif field.type == "address":
499 # TODO resolve to name
500 print(' fprintf(fp, "%*s{}: 0x%" PRIx64 "\\n", indent, "", {});'.format(name, val))
501 elif field.type in self.parser.enums:
502 print(' fprintf(fp, "%*s{}: %s\\n", indent, "", {}_as_str({}));'.format(name, enum_name(field.type), val))
503 elif field.type == "int":
504 print(' fprintf(fp, "%*s{}: %d\\n", indent, "", {});'.format(name, val))
505 elif field.type == "bool":
506 print(' fprintf(fp, "%*s{}: %s\\n", indent, "", {} ? "true" : "false");'.format(name, val))
507 elif field.type == "float":
508 print(' fprintf(fp, "%*s{}: %f\\n", indent, "", {});'.format(name, val))
509 elif field.type == "uint" and (field.end - field.start) >= 32:
510 print(' fprintf(fp, "%*s{}: 0x%" PRIx64 "\\n", indent, "", {});'.format(name, val))
511 else:
512 print(' fprintf(fp, "%*s{}: %u\\n", indent, "", {});'.format(name, val))
513
514 class Value(object):
515 def __init__(self, attrs):
516 self.name = attrs["name"]
517 self.value = int(attrs["value"])
518
519 class Parser(object):
520 def __init__(self):
521 self.parser = xml.parsers.expat.ParserCreate()
522 self.parser.StartElementHandler = self.start_element
523 self.parser.EndElementHandler = self.end_element
524
525 self.struct = None
526 self.structs = {}
527 # Set of enum names we've seen.
528 self.enums = set()
529
530 def gen_prefix(self, name):
531 return '{}_{}'.format(global_prefix.upper(), name)
532
533 def start_element(self, name, attrs):
534 if name == "panxml":
535 print(pack_header)
536 elif name == "struct":
537 name = attrs["name"]
538 self.with_opaque = attrs.get("with_opaque", False)
539
540 object_name = self.gen_prefix(safe_name(name.upper()))
541 self.struct = object_name
542
543 self.group = Group(self, None, 0, 1)
544 if "size" in attrs:
545 self.group.length = int(attrs["size"]) * 4
546 self.structs[attrs["name"]] = self.group
547 elif name == "field":
548 self.group.fields.append(Field(self, attrs))
549 self.values = []
550 elif name == "enum":
551 self.values = []
552 self.enum = safe_name(attrs["name"])
553 self.enums.add(attrs["name"])
554 if "prefix" in attrs:
555 self.prefix = attrs["prefix"]
556 else:
557 self.prefix= None
558 elif name == "value":
559 self.values.append(Value(attrs))
560
561 def end_element(self, name):
562 if name == "struct":
563 self.emit_struct()
564 self.struct = None
565 self.group = None
566 elif name == "field":
567 self.group.fields[-1].values = self.values
568 elif name == "enum":
569 self.emit_enum()
570 self.enum = None
571 elif name == "panxml":
572 # Include at the end so it can depend on us but not the converse
573 print('#include "panfrost-job.h"')
574 print('#endif')
575
576 def emit_header(self, name):
577 default_fields = []
578 for field in self.group.fields:
579 if not type(field) is Field:
580 continue
581 if field.default is not None:
582 default_fields.append(" .{} = {}".format(field.name, field.default))
583 elif field.type in self.structs:
584 default_fields.append(" .{} = {{ {}_header }}".format(field.name, self.gen_prefix(safe_name(field.type.upper()))))
585
586 print('#define %-40s\\' % (name + '_header'))
587 if default_fields:
588 print(", \\\n".join(default_fields))
589 else:
590 print(' 0')
591 print('')
592
593 def emit_template_struct(self, name, group, opaque_structs):
594 print("struct %s {" % (name + ('_OPAQUE' if opaque_structs else '')))
595 group.emit_template_struct("", opaque_structs)
596 print("};\n")
597
598 if opaque_structs:
599 # Just so it isn't left undefined
600 print('#define %-40s 0' % (name + '_OPAQUE_header'))
601
602 def emit_pack_function(self, name, group, with_opaque):
603 print("static inline void\n%s_pack(uint32_t * restrict cl,\n%sconst struct %s * restrict values)\n{" %
604 (name, ' ' * (len(name) + 6), name))
605
606 group.emit_pack_function(False)
607
608 print("}\n\n")
609
610 if with_opaque:
611 print("static inline void\n%s_OPAQUE_pack(uint32_t * restrict cl,\n%sconst struct %s_OPAQUE * restrict values)\n{" %
612 (name, ' ' * (len(name) + 6), name))
613
614 group.emit_pack_function(True)
615
616 print("}\n")
617
618 # Should be a whole number of words
619 assert((self.group.length % 4) == 0)
620
621 print('#define {} {}'.format (name + "_LENGTH", self.group.length))
622 print('struct {}_packed {{ uint32_t opaque[{}]; }};'.format(name.lower(), self.group.length // 4))
623
624 def emit_unpack_function(self, name, group):
625 print("static inline void")
626 print("%s_unpack(const uint8_t * restrict cl,\n%sstruct %s * restrict values)\n{" %
627 (name.upper(), ' ' * (len(name) + 8), name))
628
629 group.emit_unpack_function()
630
631 print("}\n")
632
633 def emit_print_function(self, name, group):
634 print("static inline void")
635 print("{}_print(FILE *fp, const struct {} * values, unsigned indent)\n{{".format(name.upper(), name))
636
637 group.emit_print_function()
638
639 print("}\n")
640
641 def emit_struct(self):
642 name = self.struct
643
644 self.emit_template_struct(self.struct, self.group, False)
645 if self.with_opaque:
646 self.emit_template_struct(self.struct, self.group, True)
647 self.emit_header(name)
648 self.emit_pack_function(self.struct, self.group, self.with_opaque)
649 self.emit_unpack_function(self.struct, self.group)
650 self.emit_print_function(self.struct, self.group)
651
652 def enum_prefix(self, name):
653 return
654
655 def emit_enum(self):
656 e_name = enum_name(self.enum)
657 prefix = e_name if self.enum != 'Format' else global_prefix
658 print('enum {} {{'.format(e_name))
659
660 for value in self.values:
661 name = '{}_{}'.format(prefix, value.name)
662 name = safe_name(name).upper()
663 print(' % -36s = %6d,' % (name, value.value))
664 print('};\n')
665
666 print("static inline const char *")
667 print("{}_as_str(enum {} imm)\n{{".format(e_name.lower(), e_name))
668 print(" switch (imm) {")
669 for value in self.values:
670 name = '{}_{}'.format(prefix, value.name)
671 name = safe_name(name).upper()
672 print(' case {}: return "{}";'.format(name, value.name))
673 print(' default: return "XXX: INVALID";')
674 print(" }")
675 print("}\n")
676
677 def parse(self, filename):
678 file = open(filename, "rb")
679 self.parser.ParseFile(file)
680 file.close()
681
682 if len(sys.argv) < 2:
683 print("No input xml file specified")
684 sys.exit(1)
685
686 input_file = sys.argv[1]
687
688 p = Parser()
689 p.parse(input_file)