3fdef5c981ee001697048856b69e444d35bb1ff5
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 uint32_t
85 __gen_padded(uint32_t v, uint32_t start, uint32_t end)
87 unsigned shift = __builtin_ctz(v);
88 unsigned odd = v >> (shift + 1);
91 assert((v >> shift) & 1);
94 assert((end - start + 1) == 8);
97 return __gen_uint(shift | (odd << 5), start, end);
101 static inline uint64_t
102 __gen_unpack_uint(const uint8_t *restrict cl, uint32_t start, uint32_t end)
105 const int width = end - start + 1;
106 const uint32_t mask = (width == 32 ? ~0 : (1 << width) - 1 );
108 for (int byte = start / 8; byte <= end / 8; byte++) {
109 val |= cl[byte] << ((byte - start / 8) * 8);
112 return (val >> (start % 8)) & mask;
115 static inline uint64_t
116 __gen_unpack_sint(const uint8_t *restrict cl, uint32_t start, uint32_t end)
118 int size = end - start + 1;
119 int64_t val = __gen_unpack_uint(cl, start, end);
121 /* Get the sign bit extended. */
122 return (val << (64 - size)) >> (64 - size);
125 static inline uint64_t
126 __gen_unpack_padded(const uint8_t *restrict cl, uint32_t start, uint32_t end)
128 unsigned val = __gen_unpack_uint(cl, start, end);
129 unsigned shift = val & 0b11111;
130 unsigned odd = val >> 5;
132 return (2*odd + 1) << shift;
135 #define pan_pack(dst, T, name) \
136 for (struct MALI_ ## T name = { MALI_ ## T ## _header }, \
137 *_loop_terminate = (void *) (dst); \
138 __builtin_expect(_loop_terminate != NULL, 1); \
139 ({ MALI_ ## T ## _pack((uint32_t *) (dst), &name); \
140 _loop_terminate = NULL; }))
144 def to_alphanum(name
):
166 for i
, j
in substitutions
.items():
167 name
= name
.replace(i
, j
)
172 name
= to_alphanum(name
)
173 if not name
[0].isalpha():
178 def prefixed_upper_name(prefix
, name
):
180 name
= prefix
+ "_" + name
181 return safe_name(name
).upper()
184 return "{}_{}".format(global_prefix
, safe_name(name
)).lower()
186 def num_from_str(num_str
):
187 if num_str
.lower().startswith('0x'):
188 return int(num_str
, base
=16)
190 assert(not num_str
.startswith('0') and 'octals numbers not allowed')
193 MODIFIERS
= ["shr", "minus"]
195 def parse_modifier(modifier
):
199 for mod
in MODIFIERS
:
200 if modifier
[0:len(mod
)] == mod
and modifier
[len(mod
)] == '(' and modifier
[-1] == ')':
201 return [mod
, int(modifier
[(len(mod
) + 1):-1])]
203 print("Invalid modifier")
207 def __init__(self
, parser
, attrs
):
210 self
.name
= safe_name(attrs
["name"]).lower()
211 self
.human_name
= attrs
["name"]
213 if ":" in str(attrs
["start"]):
214 (word
, bit
) = attrs
["start"].split(":")
215 self
.start
= (int(word
) * 32) + int(bit
)
217 self
.start
= int(attrs
["start"])
219 self
.end
= self
.start
+ int(attrs
["size"]) - 1
220 self
.type = attrs
["type"]
222 if self
.type == 'bool' and self
.start
!= self
.end
:
223 print("#error Field {} has bool type but more than one bit of size".format(self
.name
));
225 if "prefix" in attrs
:
226 self
.prefix
= safe_name(attrs
["prefix"]).upper()
231 self
.exact
= int(attrs
["exact"])
235 self
.default
= attrs
.get("default")
238 if self
.type in self
.parser
.enums
and self
.default
is not None:
239 self
.default
= safe_name('{}_{}_{}'.format(global_prefix
, self
.type, self
.default
)).upper()
241 self
.modifier
= parse_modifier(attrs
.get("modifier"))
243 def emit_template_struct(self
, dim
, opaque_structs
):
244 if self
.type == 'address':
246 elif self
.type == 'bool':
248 elif self
.type == 'float':
250 elif self
.type == 'uint' and self
.end
- self
.start
> 32:
252 elif self
.type == 'int':
254 elif self
.type in ['uint', 'padded']:
256 elif self
.type in self
.parser
.structs
:
257 type = 'struct ' + self
.parser
.gen_prefix(safe_name(self
.type.upper()))
260 type = type.lower() + '_packed'
261 elif self
.type in self
.parser
.enums
:
262 type = 'enum ' + enum_name(self
.type)
264 print("#error unhandled type: %s" % self
.type)
267 print(" %-36s %s%s;" % (type, self
.name
, dim
))
269 for value
in self
.values
:
270 name
= prefixed_upper_name(self
.prefix
, value
.name
)
271 print("#define %-40s %d" % (name
, value
.value
))
273 def overlaps(self
, field
):
274 return self
!= field
and max(self
.start
, field
.start
) <= min(self
.end
, field
.end
)
278 def __init__(self
, parser
, parent
, start
, count
):
287 def emit_template_struct(self
, dim
, opaque_structs
):
289 print(" /* variable length fields follow */")
292 dim
= "%s[%d]" % (dim
, self
.count
)
294 for field
in self
.fields
:
295 if field
.exact
is not None:
298 field
.emit_template_struct(dim
, opaque_structs
)
305 def collect_words(self
, words
):
306 for field
in self
.fields
:
307 first_word
= field
.start
// 32
308 last_word
= field
.end
// 32
310 for b
in range(first_word
, last_word
+ 1):
312 words
[b
] = self
.Word()
314 words
[b
].fields
.append(field
)
316 def emit_pack_function(self
, opaque_structs
):
317 # Determine number of bytes in this group.
318 calculated
= max(field
.end
// 8 for field
in self
.fields
) + 1
321 assert(self
.length
>= calculated
)
323 self
.length
= calculated
326 self
.collect_words(words
)
328 emitted_structs
= set()
330 # Validate the modifier is lossless
331 for field
in self
.fields
:
332 if field
.modifier
is None:
335 assert(field
.exact
is None)
337 if field
.modifier
[0] == "shr":
338 shift
= field
.modifier
[1]
339 mask
= hex((1 << shift
) - 1)
340 print(" assert((values->{} & {}) == 0);".format(field
.name
, mask
))
341 elif field
.modifier
[0] == "minus":
342 print(" assert(values->{} >= {});".format(field
.name
, field
.modifier
[1]))
344 for index
in range(self
.length
// 4):
346 if not index
in words
:
347 print(" cl[%2d] = 0;" % index
)
352 word_start
= index
* 32
355 prefix
= " cl[%2d] =" % index
357 first
= word
.fields
[0]
358 if first
.type in self
.parser
.structs
and first
.start
not in emitted_structs
:
359 pack_name
= self
.parser
.gen_prefix(safe_name(first
.type.upper()))
361 assert((first
.start
% 32) == 0)
362 assert(first
.end
== first
.start
+ (self
.parser
.structs
[first
.type].length
* 8) - 1)
363 emitted_structs
.add(first
.start
)
366 print(" memcpy(cl + {}, &values->{}, {});".format(first
.start
// 32, first
.name
, (first
.end
- first
.start
+ 1) // 8))
368 print(" {}_pack(cl + {}, &values->{});".format(pack_name
, first
.start
// 32, first
.name
))
370 for field
in word
.fields
:
374 field_word_start
= (field
.start
// 32) * 32
375 start
-= field_word_start
376 end
-= field_word_start
378 value
= str(field
.exact
) if field
.exact
is not None else "values->%s" % name
379 if field
.modifier
is not None:
380 if field
.modifier
[0] == "shr":
381 value
= "{} >> {}".format(value
, field
.modifier
[1])
382 elif field
.modifier
[0] == "minus":
383 value
= "{} - {}".format(value
, field
.modifier
[1])
385 if field
.type == "uint" or field
.type == "address":
386 s
= "__gen_uint(%s, %d, %d)" % \
388 elif field
.type == "padded":
389 s
= "__gen_padded(%s, %d, %d)" % \
391 elif field
.type in self
.parser
.enums
:
392 s
= "__gen_uint(%s, %d, %d)" % \
394 elif field
.type == "int":
395 s
= "__gen_sint(%s, %d, %d)" % \
397 elif field
.type == "bool":
398 s
= "__gen_uint(%s, %d, %d)" % \
400 elif field
.type == "float":
401 assert(start
== 0 and end
== 31)
402 s
= "__gen_uint(fui({}), 0, 32)".format(value
)
403 elif field
.type in self
.parser
.structs
:
404 # Structs are packed directly
405 assert(len(word
.fields
) == 1)
408 s
= "#error unhandled field {}, type {}".format(name
, field
.type)
411 shift
= word_start
- field_word_start
413 s
= "%s >> %d" % (s
, shift
)
415 if field
== word
.fields
[-1]:
416 print("%s %s;" % (prefix
, s
))
418 print("%s %s |" % (prefix
, s
))
423 # Given a field (start, end) contained in word `index`, generate the 32-bit
424 # mask of present bits relative to the word
425 def mask_for_word(self
, index
, start
, end
):
426 field_word_start
= index
* 32
427 start
-= field_word_start
428 end
-= field_word_start
429 # Cap multiword at one word
430 start
= max(start
, 0)
431 end
= min(end
, 32 - 1)
432 count
= (end
- start
+ 1)
433 return (((1 << count
) - 1) << start
)
435 def emit_unpack_function(self
):
436 # First, verify there is no garbage in unused bits
438 self
.collect_words(words
)
440 for index
in range(self
.length
// 4):
442 word
= words
.get(index
, self
.Word())
443 masks
= [self
.mask_for_word(index
, f
.start
, f
.end
) for f
in word
.fields
]
444 mask
= reduce(lambda x
,y
: x | y
, masks
, 0)
446 ALL_ONES
= 0xffffffff
449 TMPL
= ' if (((const uint32_t *) cl)[{}] & {}) fprintf(stderr, "XXX: Invalid field unpacked at word {}\\n");'
450 print(TMPL
.format(index
, hex(mask ^ ALL_ONES
), index
))
452 for field
in self
.fields
:
453 # Recurse for structs, see pack() for validation
454 if field
.type in self
.parser
.structs
:
455 pack_name
= self
.parser
.gen_prefix(safe_name(field
.type)).upper()
456 print(" {}_unpack(cl + {}, &values->{});".format(pack_name
, field
.start
// 8, field
.name
))
463 args
.append(str(field
.start
))
464 args
.append(str(field
.end
))
466 if field
.type in set(["uint", "address"]) | self
.parser
.enums
:
467 convert
= "__gen_unpack_uint"
468 elif field
.type == "int":
469 convert
= "__gen_unpack_sint"
470 elif field
.type == "padded":
471 convert
= "__gen_unpack_padded"
472 elif field
.type == "bool":
473 convert
= "__gen_unpack_uint"
474 elif field
.type == "float":
475 convert
= "__gen_unpack_float"
477 s
= "/* unhandled field %s, type %s */\n" % (field
.name
, field
.type)
481 if field
.modifier
[0] == "minus":
482 suffix
= " + {}".format(field
.modifier
[1])
483 elif field
.modifier
[0] == "shr":
484 suffix
= " << {}".format(field
.modifier
[1])
486 decoded
= '{}({}){}'.format(convert
, ', '.join(args
), suffix
)
488 print(' values->{} = {};'.format(field
.name
, decoded
))
490 def emit_print_function(self
):
491 for field
in self
.fields
:
493 name
, val
= field
.human_name
, 'values->{}'.format(field
.name
)
495 if field
.type in self
.parser
.structs
:
496 pack_name
= self
.parser
.gen_prefix(safe_name(field
.type)).upper()
497 print(' fprintf(fp, "%*s{}:\\n", indent, "");'.format(field
.human_name
))
498 print(" {}_print(fp, &values->{}, indent + 2);".format(pack_name
, field
.name
))
499 elif field
.type == "address":
500 # TODO resolve to name
501 print(' fprintf(fp, "%*s{}: 0x%" PRIx64 "\\n", indent, "", {});'.format(name
, val
))
502 elif field
.type in self
.parser
.enums
:
503 print(' fprintf(fp, "%*s{}: %s\\n", indent, "", {}_as_str({}));'.format(name
, enum_name(field
.type), val
))
504 elif field
.type == "int":
505 print(' fprintf(fp, "%*s{}: %d\\n", indent, "", {});'.format(name
, val
))
506 elif field
.type == "bool":
507 print(' fprintf(fp, "%*s{}: %s\\n", indent, "", {} ? "true" : "false");'.format(name
, val
))
508 elif field
.type == "float":
509 print(' fprintf(fp, "%*s{}: %f\\n", indent, "", {});'.format(name
, val
))
510 elif field
.type == "uint" and (field
.end
- field
.start
) >= 32:
511 print(' fprintf(fp, "%*s{}: 0x%" PRIx64 "\\n", indent, "", {});'.format(name
, val
))
513 print(' fprintf(fp, "%*s{}: %u\\n", indent, "", {});'.format(name
, val
))
516 def __init__(self
, attrs
):
517 self
.name
= attrs
["name"]
518 self
.value
= int(attrs
["value"])
520 class Parser(object):
522 self
.parser
= xml
.parsers
.expat
.ParserCreate()
523 self
.parser
.StartElementHandler
= self
.start_element
524 self
.parser
.EndElementHandler
= self
.end_element
528 # Set of enum names we've seen.
531 def gen_prefix(self
, name
):
532 return '{}_{}'.format(global_prefix
.upper(), name
)
534 def start_element(self
, name
, attrs
):
537 elif name
== "struct":
539 self
.with_opaque
= attrs
.get("with_opaque", False)
541 object_name
= self
.gen_prefix(safe_name(name
.upper()))
542 self
.struct
= object_name
544 self
.group
= Group(self
, None, 0, 1)
546 self
.group
.length
= int(attrs
["size"]) * 4
547 self
.structs
[attrs
["name"]] = self
.group
548 elif name
== "field":
549 self
.group
.fields
.append(Field(self
, attrs
))
553 self
.enum
= safe_name(attrs
["name"])
554 self
.enums
.add(attrs
["name"])
555 if "prefix" in attrs
:
556 self
.prefix
= attrs
["prefix"]
559 elif name
== "value":
560 self
.values
.append(Value(attrs
))
562 def end_element(self
, name
):
567 elif name
== "field":
568 self
.group
.fields
[-1].values
= self
.values
572 elif name
== "panxml":
573 # Include at the end so it can depend on us but not the converse
574 print('#include "panfrost-job.h"')
577 def emit_header(self
, name
):
579 for field
in self
.group
.fields
:
580 if not type(field
) is Field
:
582 if field
.default
is not None:
583 default_fields
.append(" .{} = {}".format(field
.name
, field
.default
))
584 elif field
.type in self
.structs
:
585 default_fields
.append(" .{} = {{ {}_header }}".format(field
.name
, self
.gen_prefix(safe_name(field
.type.upper()))))
587 print('#define %-40s\\' % (name
+ '_header'))
588 print(", \\\n".join(default_fields
))
591 def emit_template_struct(self
, name
, group
, opaque_structs
):
592 print("struct %s {" % (name
+ ('_OPAQUE' if opaque_structs
else '')))
593 group
.emit_template_struct("", opaque_structs
)
597 # Just so it isn't left undefined
598 print('#define %-40s 0' % (name
+ '_OPAQUE_header'))
600 def emit_pack_function(self
, name
, group
, with_opaque
):
601 print("static inline void\n%s_pack(uint32_t * restrict cl,\n%sconst struct %s * restrict values)\n{" %
602 (name
, ' ' * (len(name
) + 6), name
))
604 group
.emit_pack_function(False)
609 print("static inline void\n%s_OPAQUE_pack(uint32_t * restrict cl,\n%sconst struct %s_OPAQUE * restrict values)\n{" %
610 (name
, ' ' * (len(name
) + 6), name
))
612 group
.emit_pack_function(True)
616 # Should be a whole number of words
617 assert((self
.group
.length
% 4) == 0)
619 print('#define {} {}'.format (name
+ "_LENGTH", self
.group
.length
))
620 print('struct {}_packed {{ uint32_t opaque[{}]; }};'.format(name
.lower(), self
.group
.length
// 4))
622 def emit_unpack_function(self
, name
, group
):
623 print("static inline void")
624 print("%s_unpack(const uint8_t * restrict cl,\n%sstruct %s * restrict values)\n{" %
625 (name
.upper(), ' ' * (len(name
) + 8), name
))
627 group
.emit_unpack_function()
631 def emit_print_function(self
, name
, group
):
632 print("static inline void")
633 print("{}_print(FILE *fp, const struct {} * values, unsigned indent)\n{{".format(name
.upper(), name
))
635 group
.emit_print_function()
639 def emit_struct(self
):
642 self
.emit_template_struct(self
.struct
, self
.group
, False)
644 self
.emit_template_struct(self
.struct
, self
.group
, True)
645 self
.emit_header(name
)
646 self
.emit_pack_function(self
.struct
, self
.group
, self
.with_opaque
)
647 self
.emit_unpack_function(self
.struct
, self
.group
)
648 self
.emit_print_function(self
.struct
, self
.group
)
650 def enum_prefix(self
, name
):
654 e_name
= enum_name(self
.enum
)
655 prefix
= e_name
if self
.enum
!= 'Format' else global_prefix
656 print('enum {} {{'.format(e_name
))
658 for value
in self
.values
:
659 name
= '{}_{}'.format(prefix
, value
.name
)
660 name
= safe_name(name
).upper()
661 print(' % -36s = %6d,' % (name
, value
.value
))
664 print("static inline const char *")
665 print("{}_as_str(enum {} imm)\n{{".format(e_name
.lower(), e_name
))
666 print(" switch (imm) {")
667 for value
in self
.values
:
668 name
= '{}_{}'.format(prefix
, value
.name
)
669 name
= safe_name(name
).upper()
670 print(' case {}: return "{}";'.format(name
, value
.name
))
671 print(' default: return "XXX: INVALID";')
675 def parse(self
, filename
):
676 file = open(filename
, "rb")
677 self
.parser
.ParseFile(file)
680 if len(sys
.argv
) < 2:
681 print("No input xml file specified")
684 input_file
= sys
.argv
[1]