e91769c193caaa56813d2c383dc47a0c04d0d0b7
3 # Copyright (C) 2016 Intel Corporation
4 # Copyright (C) 2016 Broadcom
5 # Copyright (C) 2020 Collabora, Ltd.
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:
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
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
26 import xml
.parsers
.expat
29 from functools
import reduce
31 global_prefix
= "mali"
34 /* Generated code, see midgard.xml and gen_pack_header.py
36 * Packets, enums and structures for Panfrost.
38 * This file has been generated, do not hand edit.
50 #include "util/u_math.h"
52 #define __gen_unpack_float(x, y, z) uif(__gen_unpack_uint(x, y, z))
54 static inline uint64_t
55 __gen_uint(uint64_t v, uint32_t start, uint32_t end)
58 const int width = end - start + 1;
60 const uint64_t max = (1ull << width) - 1;
68 static inline uint32_t
69 __gen_sint(int32_t v, uint32_t start, uint32_t end)
71 const int width = end - start + 1;
75 const int64_t max = (1ll << (width - 1)) - 1;
76 const int64_t min = -(1ll << (width - 1));
77 assert(min <= v && v <= max);
81 return ((uint32_t) v) << start;
84 static inline uint64_t
85 __gen_unpack_uint(const uint8_t *restrict cl, uint32_t start, uint32_t end)
88 const int width = end - start + 1;
89 const uint32_t mask = (width == 32 ? ~0 : (1 << width) - 1 );
91 for (int byte = start / 8; byte <= end / 8; byte++) {
92 val |= cl[byte] << ((byte - start / 8) * 8);
95 return (val >> (start % 8)) & mask;
98 static inline uint64_t
99 __gen_unpack_sint(const uint8_t *restrict cl, uint32_t start, uint32_t end)
101 int size = end - start + 1;
102 int64_t val = __gen_unpack_uint(cl, start, end);
104 /* Get the sign bit extended. */
105 return (val << (64 - size)) >> (64 - size);
108 #define pan_pack(dst, T, name) \
109 for (struct MALI_ ## T name = { MALI_ ## T ## _header }, \
110 *_loop_terminate = (void *) (dst); \
111 __builtin_expect(_loop_terminate != NULL, 1); \
112 ({ MALI_ ## T ## _pack((uint32_t *) (dst), &name); \
113 _loop_terminate = NULL; }))
117 def to_alphanum(name
):
139 for i
, j
in substitutions
.items():
140 name
= name
.replace(i
, j
)
145 name
= to_alphanum(name
)
146 if not name
[0].isalpha():
151 def prefixed_upper_name(prefix
, name
):
153 name
= prefix
+ "_" + name
154 return safe_name(name
).upper()
157 return "{}_{}".format(global_prefix
, safe_name(name
)).lower()
159 def num_from_str(num_str
):
160 if num_str
.lower().startswith('0x'):
161 return int(num_str
, base
=16)
163 assert(not num_str
.startswith('0') and 'octals numbers not allowed')
166 MODIFIERS
= ["shr", "minus"]
168 def parse_modifier(modifier
):
172 for mod
in MODIFIERS
:
173 if modifier
[0:len(mod
)] == mod
and modifier
[len(mod
)] == '(' and modifier
[-1] == ')':
174 return [mod
, int(modifier
[(len(mod
) + 1):-1])]
176 print("Invalid modifier")
180 def __init__(self
, parser
, attrs
):
183 self
.name
= safe_name(attrs
["name"]).lower()
184 self
.human_name
= attrs
["name"]
186 if ":" in str(attrs
["start"]):
187 (word
, bit
) = attrs
["start"].split(":")
188 self
.start
= (int(word
) * 32) + int(bit
)
190 self
.start
= int(attrs
["start"])
192 self
.end
= self
.start
+ int(attrs
["size"]) - 1
193 self
.type = attrs
["type"]
195 if self
.type == 'bool' and self
.start
!= self
.end
:
196 print("#error Field {} has bool type but more than one bit of size".format(self
.name
));
198 if "prefix" in attrs
:
199 self
.prefix
= safe_name(attrs
["prefix"]).upper()
204 self
.exact
= int(attrs
["exact"])
208 self
.default
= attrs
.get("default")
211 if self
.type in self
.parser
.enums
and self
.default
is not None:
212 self
.default
= safe_name('{}_{}_{}'.format(global_prefix
, self
.type, self
.default
)).upper()
214 self
.modifier
= parse_modifier(attrs
.get("modifier"))
216 def emit_template_struct(self
, dim
, opaque_structs
):
217 if self
.type == 'address':
219 elif self
.type == 'bool':
221 elif self
.type == 'float':
223 elif self
.type == 'uint' and self
.end
- self
.start
> 32:
225 elif self
.type == 'int':
227 elif self
.type == 'uint':
229 elif self
.type in self
.parser
.structs
:
230 type = 'struct ' + self
.parser
.gen_prefix(safe_name(self
.type.upper()))
233 type = type.lower() + '_packed'
234 elif self
.type in self
.parser
.enums
:
235 type = 'enum ' + enum_name(self
.type)
237 print("#error unhandled type: %s" % self
.type)
240 print(" %-36s %s%s;" % (type, self
.name
, dim
))
242 for value
in self
.values
:
243 name
= prefixed_upper_name(self
.prefix
, value
.name
)
244 print("#define %-40s %d" % (name
, value
.value
))
246 def overlaps(self
, field
):
247 return self
!= field
and max(self
.start
, field
.start
) <= min(self
.end
, field
.end
)
251 def __init__(self
, parser
, parent
, start
, count
):
260 def emit_template_struct(self
, dim
, opaque_structs
):
262 print(" /* variable length fields follow */")
265 dim
= "%s[%d]" % (dim
, self
.count
)
267 for field
in self
.fields
:
268 if field
.exact
is not None:
271 field
.emit_template_struct(dim
, opaque_structs
)
278 def collect_words(self
, words
):
279 for field
in self
.fields
:
280 first_word
= field
.start
// 32
281 last_word
= field
.end
// 32
283 for b
in range(first_word
, last_word
+ 1):
285 words
[b
] = self
.Word()
287 words
[b
].fields
.append(field
)
289 def emit_pack_function(self
, opaque_structs
):
290 # Determine number of bytes in this group.
291 calculated
= max(field
.end
// 8 for field
in self
.fields
) + 1
294 assert(self
.length
>= calculated
)
296 self
.length
= calculated
299 self
.collect_words(words
)
301 emitted_structs
= set()
303 # Validate the modifier is lossless
304 for field
in self
.fields
:
305 if field
.modifier
is None:
308 assert(field
.exact
is None)
310 if field
.modifier
[0] == "shr":
311 shift
= field
.modifier
[1]
312 mask
= hex((1 << shift
) - 1)
313 print(" assert((values->{} & {}) == 0);".format(field
.name
, mask
))
314 elif field
.modifier
[0] == "minus":
315 print(" assert(values->{} >= {});".format(field
.name
, field
.modifier
[1]))
317 for index
in range(self
.length
// 4):
319 if not index
in words
:
320 print(" cl[%2d] = 0;" % index
)
325 word_start
= index
* 32
328 prefix
= " cl[%2d] =" % index
330 first
= word
.fields
[0]
331 if first
.type in self
.parser
.structs
and first
.start
not in emitted_structs
:
332 pack_name
= self
.parser
.gen_prefix(safe_name(first
.type.upper()))
334 assert((first
.start
% 32) == 0)
335 assert(first
.end
== first
.start
+ (self
.parser
.structs
[first
.type].length
* 8) - 1)
336 emitted_structs
.add(first
.start
)
339 print(" memcpy(cl + {}, &values->{}, {});".format(first
.start
// 32, first
.name
, (first
.end
- first
.start
+ 1) // 8))
341 print(" {}_pack(cl + {}, &values->{});".format(pack_name
, first
.start
// 32, first
.name
))
343 for field
in word
.fields
:
347 field_word_start
= (field
.start
// 32) * 32
348 start
-= field_word_start
349 end
-= field_word_start
351 value
= str(field
.exact
) if field
.exact
is not None else "values->%s" % name
352 if field
.modifier
is not None:
353 if field
.modifier
[0] == "shr":
354 value
= "{} >> {}".format(value
, field
.modifier
[1])
355 elif field
.modifier
[0] == "minus":
356 value
= "{} - {}".format(value
, field
.modifier
[1])
358 if field
.type == "uint" or field
.type == "address":
359 s
= "__gen_uint(%s, %d, %d)" % \
361 elif field
.type in self
.parser
.enums
:
362 s
= "__gen_uint(%s, %d, %d)" % \
364 elif field
.type == "int":
365 s
= "__gen_sint(%s, %d, %d)" % \
367 elif field
.type == "bool":
368 s
= "__gen_uint(%s, %d, %d)" % \
370 elif field
.type == "float":
371 assert(start
== 0 and end
== 31)
372 s
= "__gen_uint(fui({}), 0, 32)".format(value
)
373 elif field
.type in self
.parser
.structs
:
374 # Structs are packed directly
375 assert(len(word
.fields
) == 1)
378 s
= "#error unhandled field {}, type {}".format(name
, field
.type)
381 shift
= word_start
- field_word_start
383 s
= "%s >> %d" % (s
, shift
)
385 if field
== word
.fields
[-1]:
386 print("%s %s;" % (prefix
, s
))
388 print("%s %s |" % (prefix
, s
))
393 # Given a field (start, end) contained in word `index`, generate the 32-bit
394 # mask of present bits relative to the word
395 def mask_for_word(self
, index
, start
, end
):
396 field_word_start
= index
* 32
397 start
-= field_word_start
398 end
-= field_word_start
399 # Cap multiword at one word
400 start
= max(start
, 0)
401 end
= min(end
, 32 - 1)
402 count
= (end
- start
+ 1)
403 return (((1 << count
) - 1) << start
)
405 def emit_unpack_function(self
):
406 # First, verify there is no garbage in unused bits
408 self
.collect_words(words
)
410 for index
in range(self
.length
// 4):
412 word
= words
.get(index
, self
.Word())
413 masks
= [self
.mask_for_word(index
, f
.start
, f
.end
) for f
in word
.fields
]
414 mask
= reduce(lambda x
,y
: x | y
, masks
, 0)
416 ALL_ONES
= 0xffffffff
419 TMPL
= ' if (((const uint32_t *) cl)[{}] & {}) fprintf(stderr, "XXX: Invalid field unpacked at word {}\\n");'
420 print(TMPL
.format(index
, hex(mask ^ ALL_ONES
), index
))
422 for field
in self
.fields
:
423 # Recurse for structs, see pack() for validation
424 if field
.type in self
.parser
.structs
:
425 pack_name
= self
.parser
.gen_prefix(safe_name(field
.type)).upper()
426 print(" {}_unpack(cl + {}, &values->{});".format(pack_name
, field
.start
// 8, field
.name
))
433 args
.append(str(field
.start
))
434 args
.append(str(field
.end
))
436 if field
.type in set(["uint", "address"]) | self
.parser
.enums
:
437 convert
= "__gen_unpack_uint"
438 elif field
.type == "int":
439 convert
= "__gen_unpack_sint"
440 elif field
.type == "bool":
441 convert
= "__gen_unpack_uint"
442 elif field
.type == "float":
443 convert
= "__gen_unpack_float"
445 s
= "/* unhandled field %s, type %s */\n" % (field
.name
, field
.type)
449 if field
.modifier
[0] == "minus":
450 suffix
= " + {}".format(field
.modifier
[1])
451 elif field
.modifier
[0] == "shr":
452 suffix
= " << {}".format(field
.modifier
[1])
454 decoded
= '{}({}){}'.format(convert
, ', '.join(args
), suffix
)
456 print(' values->{} = {};'.format(field
.name
, decoded
))
458 def emit_print_function(self
):
459 for field
in self
.fields
:
461 name
, val
= field
.human_name
, 'values->{}'.format(field
.name
)
463 if field
.type in self
.parser
.structs
:
464 pack_name
= self
.parser
.gen_prefix(safe_name(field
.type)).upper()
465 print(' fprintf(fp, "%*s{}:\\n", indent, "");'.format(field
.human_name
))
466 print(" {}_print(fp, &values->{}, indent + 2);".format(pack_name
, field
.name
))
467 elif field
.type == "address":
468 # TODO resolve to name
469 print(' fprintf(fp, "%*s{}: 0x%" PRIx64 "\\n", indent, "", {});'.format(name
, val
))
470 elif field
.type in self
.parser
.enums
:
471 print(' fprintf(fp, "%*s{}: %s\\n", indent, "", {}_as_str({}));'.format(name
, enum_name(field
.type), val
))
472 elif field
.type == "int":
473 print(' fprintf(fp, "%*s{}: %d\\n", indent, "", {});'.format(name
, val
))
474 elif field
.type == "bool":
475 print(' fprintf(fp, "%*s{}: %s\\n", indent, "", {} ? "true" : "false");'.format(name
, val
))
476 elif field
.type == "float":
477 print(' fprintf(fp, "%*s{}: %f\\n", indent, "", {});'.format(name
, val
))
478 elif field
.type == "uint" and (field
.end
- field
.start
) >= 32:
479 print(' fprintf(fp, "%*s{}: 0x%" PRIx64 "\\n", indent, "", {});'.format(name
, val
))
481 print(' fprintf(fp, "%*s{}: %u\\n", indent, "", {});'.format(name
, val
))
484 def __init__(self
, attrs
):
485 self
.name
= attrs
["name"]
486 self
.value
= int(attrs
["value"])
488 class Parser(object):
490 self
.parser
= xml
.parsers
.expat
.ParserCreate()
491 self
.parser
.StartElementHandler
= self
.start_element
492 self
.parser
.EndElementHandler
= self
.end_element
496 # Set of enum names we've seen.
499 def gen_prefix(self
, name
):
500 return '{}_{}'.format(global_prefix
.upper(), name
)
502 def start_element(self
, name
, attrs
):
505 elif name
== "struct":
507 self
.with_opaque
= attrs
.get("with_opaque", False)
509 object_name
= self
.gen_prefix(safe_name(name
.upper()))
510 self
.struct
= object_name
512 self
.group
= Group(self
, None, 0, 1)
514 self
.group
.length
= int(attrs
["size"]) * 4
515 self
.structs
[attrs
["name"]] = self
.group
516 elif name
== "field":
517 self
.group
.fields
.append(Field(self
, attrs
))
521 self
.enum
= safe_name(attrs
["name"])
522 self
.enums
.add(attrs
["name"])
523 if "prefix" in attrs
:
524 self
.prefix
= attrs
["prefix"]
527 elif name
== "value":
528 self
.values
.append(Value(attrs
))
530 def end_element(self
, name
):
535 elif name
== "field":
536 self
.group
.fields
[-1].values
= self
.values
540 elif name
== "panxml":
541 # Include at the end so it can depend on us but not the converse
542 print('#include "panfrost-job.h"')
545 def emit_header(self
, name
):
547 for field
in self
.group
.fields
:
548 if not type(field
) is Field
:
550 if field
.default
is not None:
551 default_fields
.append(" .{} = {}".format(field
.name
, field
.default
))
552 elif field
.type in self
.structs
:
553 default_fields
.append(" .{} = {{ {}_header }}".format(field
.name
, self
.gen_prefix(safe_name(field
.type.upper()))))
555 print('#define %-40s\\' % (name
+ '_header'))
556 print(", \\\n".join(default_fields
))
559 def emit_template_struct(self
, name
, group
, opaque_structs
):
560 print("struct %s {" % (name
+ ('_OPAQUE' if opaque_structs
else '')))
561 group
.emit_template_struct("", opaque_structs
)
565 # Just so it isn't left undefined
566 print('#define %-40s 0' % (name
+ '_OPAQUE_header'))
568 def emit_pack_function(self
, name
, group
, with_opaque
):
569 print("static inline void\n%s_pack(uint32_t * restrict cl,\n%sconst struct %s * restrict values)\n{" %
570 (name
, ' ' * (len(name
) + 6), name
))
572 group
.emit_pack_function(False)
577 print("static inline void\n%s_OPAQUE_pack(uint32_t * restrict cl,\n%sconst struct %s_OPAQUE * restrict values)\n{" %
578 (name
, ' ' * (len(name
) + 6), name
))
580 group
.emit_pack_function(True)
584 # Should be a whole number of words
585 assert((self
.group
.length
% 4) == 0)
587 print('#define {} {}'.format (name
+ "_LENGTH", self
.group
.length
))
588 print('struct {}_packed {{ uint32_t opaque[{}]; }};'.format(name
.lower(), self
.group
.length
// 4))
590 def emit_unpack_function(self
, name
, group
):
591 print("static inline void")
592 print("%s_unpack(const uint8_t * restrict cl,\n%sstruct %s * restrict values)\n{" %
593 (name
.upper(), ' ' * (len(name
) + 8), name
))
595 group
.emit_unpack_function()
599 def emit_print_function(self
, name
, group
):
600 print("static inline void")
601 print("{}_print(FILE *fp, const struct {} * values, unsigned indent)\n{{".format(name
.upper(), name
))
603 group
.emit_print_function()
607 def emit_struct(self
):
610 self
.emit_template_struct(self
.struct
, self
.group
, False)
612 self
.emit_template_struct(self
.struct
, self
.group
, True)
613 self
.emit_header(name
)
614 self
.emit_pack_function(self
.struct
, self
.group
, self
.with_opaque
)
615 self
.emit_unpack_function(self
.struct
, self
.group
)
616 self
.emit_print_function(self
.struct
, self
.group
)
618 def enum_prefix(self
, name
):
622 e_name
= enum_name(self
.enum
)
623 prefix
= e_name
if self
.enum
!= 'Format' else global_prefix
624 print('enum {} {{'.format(e_name
))
626 for value
in self
.values
:
627 name
= '{}_{}'.format(prefix
, value
.name
)
628 name
= safe_name(name
).upper()
629 print(' % -36s = %6d,' % (name
, value
.value
))
632 print("static inline const char *")
633 print("{}_as_str(enum {} imm)\n{{".format(e_name
.lower(), e_name
))
634 print(" switch (imm) {")
635 for value
in self
.values
:
636 name
= '{}_{}'.format(prefix
, value
.name
)
637 name
= safe_name(name
).upper()
638 print(' case {}: return "{}";'.format(name
, value
.name
))
639 print(' default: return "XXX: INVALID";')
643 def parse(self
, filename
):
644 file = open(filename
, "rb")
645 self
.parser
.ParseFile(file)
648 if len(sys
.argv
) < 2:
649 print("No input xml file specified")
652 input_file
= sys
.argv
[1]