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
):
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()))
231 elif self
.type in self
.parser
.enums
:
232 type = 'enum ' + enum_name(self
.type)
234 print("#error unhandled type: %s" % self
.type)
237 print(" %-36s %s%s;" % (type, self
.name
, dim
))
239 for value
in self
.values
:
240 name
= prefixed_upper_name(self
.prefix
, value
.name
)
241 print("#define %-40s %d" % (name
, value
.value
))
243 def overlaps(self
, field
):
244 return self
!= field
and max(self
.start
, field
.start
) <= min(self
.end
, field
.end
)
248 def __init__(self
, parser
, parent
, start
, count
):
257 def emit_template_struct(self
, dim
):
259 print(" /* variable length fields follow */")
262 dim
= "%s[%d]" % (dim
, self
.count
)
264 for field
in self
.fields
:
265 if field
.exact
is not None:
268 field
.emit_template_struct(dim
)
275 def collect_words(self
, words
):
276 for field
in self
.fields
:
277 first_word
= field
.start
// 32
278 last_word
= field
.end
// 32
280 for b
in range(first_word
, last_word
+ 1):
282 words
[b
] = self
.Word()
284 words
[b
].fields
.append(field
)
286 def emit_pack_function(self
):
287 # Determine number of bytes in this group.
288 calculated
= max(field
.end
// 8 for field
in self
.fields
) + 1
291 assert(self
.length
>= calculated
)
293 self
.length
= calculated
296 self
.collect_words(words
)
298 emitted_structs
= set()
300 # Validate the modifier is lossless
301 for field
in self
.fields
:
302 if field
.modifier
is None:
305 assert(field
.exact
is None)
307 if field
.modifier
[0] == "shr":
308 shift
= field
.modifier
[1]
309 mask
= hex((1 << shift
) - 1)
310 print(" assert((values->{} & {}) == 0);".format(field
.name
, mask
))
311 elif field
.modifier
[0] == "minus":
312 print(" assert(values->{} >= {});".format(field
.name
, field
.modifier
[1]))
314 for index
in range(self
.length
// 4):
316 if not index
in words
:
317 print(" cl[%2d] = 0;" % index
)
322 word_start
= index
* 32
325 prefix
= " cl[%2d] =" % index
327 first
= word
.fields
[0]
328 if first
.type in self
.parser
.structs
and first
.start
not in emitted_structs
:
329 pack_name
= self
.parser
.gen_prefix(safe_name(first
.type.upper()))
331 assert((first
.start
% 32) == 0)
332 assert(first
.end
== first
.start
+ (self
.parser
.structs
[first
.type].length
* 8) - 1)
333 print(" {}_pack(cl + {}, &values->{});".format(pack_name
, first
.start
// 32, first
.name
))
334 emitted_structs
.add(first
.start
)
336 for field
in word
.fields
:
340 field_word_start
= (field
.start
// 32) * 32
341 start
-= field_word_start
342 end
-= field_word_start
344 value
= str(field
.exact
) if field
.exact
is not None else "values->%s" % name
345 if field
.modifier
is not None:
346 if field
.modifier
[0] == "shr":
347 value
= "{} >> {}".format(value
, field
.modifier
[1])
348 elif field
.modifier
[0] == "minus":
349 value
= "{} - {}".format(value
, field
.modifier
[1])
351 if field
.type == "uint" or field
.type == "address":
352 s
= "__gen_uint(%s, %d, %d)" % \
354 elif field
.type in self
.parser
.enums
:
355 s
= "__gen_uint(%s, %d, %d)" % \
357 elif field
.type == "int":
358 s
= "__gen_sint(%s, %d, %d)" % \
360 elif field
.type == "bool":
361 s
= "__gen_uint(%s, %d, %d)" % \
363 elif field
.type == "float":
364 assert(start
== 0 and end
== 31)
365 s
= "__gen_uint(fui({}), 0, 32)".format(value
)
366 elif field
.type in self
.parser
.structs
:
367 # Structs are packed directly
368 assert(len(word
.fields
) == 1)
371 s
= "#error unhandled field {}, type {}".format(name
, field
.type)
374 shift
= word_start
- field_word_start
376 s
= "%s >> %d" % (s
, shift
)
378 if field
== word
.fields
[-1]:
379 print("%s %s;" % (prefix
, s
))
381 print("%s %s |" % (prefix
, s
))
386 # Given a field (start, end) contained in word `index`, generate the 32-bit
387 # mask of present bits relative to the word
388 def mask_for_word(self
, index
, start
, end
):
389 field_word_start
= index
* 32
390 start
-= field_word_start
391 end
-= field_word_start
392 # Cap multiword at one word
393 start
= max(start
, 0)
394 end
= min(end
, 32 - 1)
395 count
= (end
- start
+ 1)
396 return (((1 << count
) - 1) << start
)
398 def emit_unpack_function(self
):
399 # First, verify there is no garbage in unused bits
401 self
.collect_words(words
)
403 for index
in range(self
.length
// 4):
405 word
= words
.get(index
, self
.Word())
406 masks
= [self
.mask_for_word(index
, f
.start
, f
.end
) for f
in word
.fields
]
407 mask
= reduce(lambda x
,y
: x | y
, masks
, 0)
409 ALL_ONES
= 0xffffffff
412 TMPL
= ' if (((const uint32_t *) cl)[{}] & {}) fprintf(stderr, "XXX: Invalid field unpacked at word {}\\n");'
413 print(TMPL
.format(index
, hex(mask ^ ALL_ONES
), index
))
415 for field
in self
.fields
:
416 # Recurse for structs, see pack() for validation
417 if field
.type in self
.parser
.structs
:
418 pack_name
= self
.parser
.gen_prefix(safe_name(field
.type)).upper()
419 print(" {}_unpack(cl + {}, &values->{});".format(pack_name
, field
.start
// 32, field
.name
))
426 args
.append(str(field
.start
))
427 args
.append(str(field
.end
))
429 if field
.type in set(["uint", "address"]) | self
.parser
.enums
:
430 convert
= "__gen_unpack_uint"
431 elif field
.type == "int":
432 convert
= "__gen_unpack_sint"
433 elif field
.type == "bool":
434 convert
= "__gen_unpack_uint"
435 elif field
.type == "float":
436 convert
= "__gen_unpack_float"
438 s
= "/* unhandled field %s, type %s */\n" % (field
.name
, field
.type)
442 if field
.modifier
[0] == "minus":
443 suffix
= " + {}".format(field
.modifier
[1])
444 elif field
.modifier
[0] == "shr":
445 suffix
= " << {}".format(field
.modifier
[1])
447 decoded
= '{}({}){}'.format(convert
, ', '.join(args
), suffix
)
449 print(' values->{} = {};'.format(field
.name
, decoded
))
451 def emit_print_function(self
):
452 for field
in self
.fields
:
454 name
, val
= field
.human_name
, 'values->{}'.format(field
.name
)
456 if field
.type in self
.parser
.structs
:
457 pack_name
= self
.parser
.gen_prefix(safe_name(field
.type)).upper()
458 print(' fprintf(fp, "%*s{}:\\n", indent, "");'.format(field
.human_name
))
459 print(" {}_print(fp, &values->{}, indent + 2);".format(pack_name
, field
.name
))
460 elif field
.type == "address":
461 # TODO resolve to name
462 print(' fprintf(fp, "%*s{}: 0x%" PRIx64 "\\n", indent, "", {});'.format(name
, val
))
463 elif field
.type in self
.parser
.enums
:
464 print(' fprintf(fp, "%*s{}: %s\\n", indent, "", {}_as_str({}));'.format(name
, enum_name(field
.type), val
))
465 elif field
.type == "int":
466 print(' fprintf(fp, "%*s{}: %d\\n", indent, "", {});'.format(name
, val
))
467 elif field
.type == "bool":
468 print(' fprintf(fp, "%*s{}: %s\\n", indent, "", {} ? "true" : "false");'.format(name
, val
))
469 elif field
.type == "float":
470 print(' fprintf(fp, "%*s{}: %f\\n", indent, "", {});'.format(name
, val
))
471 elif field
.type == "uint" and (field
.end
- field
.start
) >= 32:
472 print(' fprintf(fp, "%*s{}: 0x%" PRIx64 "\\n", indent, "", {});'.format(name
, val
))
474 print(' fprintf(fp, "%*s{}: %u\\n", indent, "", {});'.format(name
, val
))
477 def __init__(self
, attrs
):
478 self
.name
= attrs
["name"]
479 self
.value
= int(attrs
["value"])
481 class Parser(object):
483 self
.parser
= xml
.parsers
.expat
.ParserCreate()
484 self
.parser
.StartElementHandler
= self
.start_element
485 self
.parser
.EndElementHandler
= self
.end_element
489 # Set of enum names we've seen.
492 def gen_prefix(self
, name
):
493 return '{}_{}'.format(global_prefix
.upper(), name
)
495 def start_element(self
, name
, attrs
):
498 elif name
== "struct":
501 object_name
= self
.gen_prefix(safe_name(name
.upper()))
502 self
.struct
= object_name
504 self
.group
= Group(self
, None, 0, 1)
506 self
.group
.length
= int(attrs
["size"]) * 4
507 self
.structs
[attrs
["name"]] = self
.group
508 elif name
== "field":
509 self
.group
.fields
.append(Field(self
, attrs
))
513 self
.enum
= safe_name(attrs
["name"])
514 self
.enums
.add(attrs
["name"])
515 if "prefix" in attrs
:
516 self
.prefix
= attrs
["prefix"]
519 elif name
== "value":
520 self
.values
.append(Value(attrs
))
522 def end_element(self
, name
):
527 elif name
== "field":
528 self
.group
.fields
[-1].values
= self
.values
532 elif name
== "panxml":
533 # Include at the end so it can depend on us but not the converse
534 print('#include "panfrost-job.h"')
537 def emit_header(self
, name
):
539 for field
in self
.group
.fields
:
540 if not type(field
) is Field
:
542 if field
.default
== None:
544 default_fields
.append(" .{} = {}".format(field
.name
, field
.default
))
546 print('#define %-40s\\' % (name
+ '_header'))
547 print(", \\\n".join(default_fields
))
550 def emit_template_struct(self
, name
, group
):
551 print("struct %s {" % name
)
552 group
.emit_template_struct("")
555 def emit_pack_function(self
, name
, group
):
556 print("static inline void\n%s_pack(uint32_t * restrict cl,\n%sconst struct %s * restrict values)\n{" %
557 (name
, ' ' * (len(name
) + 6), name
))
559 group
.emit_pack_function()
563 # Should be a whole number of words
564 assert((self
.group
.length
% 4) == 0)
566 print('#define {} {}'.format (name
+ "_LENGTH", self
.group
.length
))
567 print('struct {}_packed {{ uint32_t opaque[{}]; }};'.format(name
.lower(), self
.group
.length
// 4))
569 def emit_unpack_function(self
, name
, group
):
570 print("static inline void")
571 print("%s_unpack(const uint8_t * restrict cl,\n%sstruct %s * restrict values)\n{" %
572 (name
.upper(), ' ' * (len(name
) + 8), name
))
574 group
.emit_unpack_function()
578 def emit_print_function(self
, name
, group
):
579 print("static inline void")
580 print("{}_print(FILE *fp, const struct {} * values, unsigned indent)\n{{".format(name
.upper(), name
))
582 group
.emit_print_function()
586 def emit_struct(self
):
589 self
.emit_template_struct(self
.struct
, self
.group
)
590 self
.emit_header(name
)
591 self
.emit_pack_function(self
.struct
, self
.group
)
592 self
.emit_unpack_function(self
.struct
, self
.group
)
593 self
.emit_print_function(self
.struct
, self
.group
)
595 def enum_prefix(self
, name
):
599 e_name
= enum_name(self
.enum
)
600 prefix
= e_name
if self
.enum
!= 'Format' else global_prefix
601 print('enum {} {{'.format(e_name
))
603 for value
in self
.values
:
604 name
= '{}_{}'.format(prefix
, value
.name
)
605 name
= safe_name(name
).upper()
606 print(' % -36s = %6d,' % (name
, value
.value
))
609 print("static inline const char *")
610 print("{}_as_str(enum {} imm)\n{{".format(e_name
.lower(), e_name
))
611 print(" switch (imm) {")
612 for value
in self
.values
:
613 name
= '{}_{}'.format(prefix
, value
.name
)
614 name
= safe_name(name
).upper()
615 print(' case {}: return "{}";'.format(name
, value
.name
))
616 print(' default: return "XXX: INVALID";')
620 def parse(self
, filename
):
621 file = open(filename
, "rb")
622 self
.parser
.ParseFile(file)
625 if len(sys
.argv
) < 2:
626 print("No input xml file specified")
629 input_file
= sys
.argv
[1]