3 # Copyright (C) 2016 Intel Corporation
4 # Copyright (C) 2016 Broadcom
6 # Permission is hereby granted, free of charge, to any person obtaining a
7 # copy of this software and associated documentation files (the "Software"),
8 # to deal in the Software without restriction, including without limitation
9 # the rights to use, copy, modify, merge, publish, distribute, sublicense,
10 # and/or sell copies of the Software, and to permit persons to whom the
11 # Software is furnished to do so, subject to the following conditions:
13 # The above copyright notice and this permission notice (including the next
14 # paragraph) shall be included in all copies or substantial portions of the
17 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
20 # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
22 # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
25 from __future__
import (
26 absolute_import
, division
, print_function
, unicode_literals
28 import xml
.parsers
.expat
33 license
= """/* Generated code, see packets.xml and gen_packet_header.py */
36 pack_header
= """%(license)s
38 /* Packets, enums and structures for %(platform)s.
40 * This file has been generated, do not hand edit.
46 #include "cle/v3d_packet_helpers.h"
50 def to_alphanum(name
):
73 for i
, j
in substitutions
.items():
74 name
= name
.replace(i
, j
)
79 name
= to_alphanum(name
)
80 if not name
[0].isalpha():
85 def prefixed_upper_name(prefix
, name
):
87 name
= prefix
+ "_" + name
88 return safe_name(name
).upper()
90 def num_from_str(num_str
):
91 if num_str
.lower().startswith('0x'):
92 return int(num_str
, base
=16)
94 assert(not num_str
.startswith('0') and 'octals numbers not allowed')
98 ufixed_pattern
= re
.compile(r
"u(\d+)\.(\d+)")
99 sfixed_pattern
= re
.compile(r
"s(\d+)\.(\d+)")
101 def __init__(self
, parser
, attrs
):
104 self
.name
= safe_name(attrs
["name"]).lower()
106 if str(attrs
["start"]).endswith("b"):
107 self
.start
= int(attrs
["start"][:-1]) * 8
109 self
.start
= int(attrs
["start"])
110 # packet <field> entries in XML start from the bit after the
111 # opcode, so shift everything up by 8 since we'll also have a
112 # Field for the opcode.
113 if not parser
.struct
:
116 self
.end
= self
.start
+ int(attrs
["size"]) - 1
117 self
.type = attrs
["type"]
119 if self
.type == 'bool' and self
.start
!= self
.end
:
120 print("#error Field {} has bool type but more than one bit of size".format(self
.name
));
122 if "prefix" in attrs
:
123 self
.prefix
= safe_name(attrs
["prefix"]).upper()
127 if "default" in attrs
:
128 self
.default
= int(attrs
["default"])
132 if "minus_one" in attrs
:
133 assert(attrs
["minus_one"] == "true")
134 self
.minus_one
= True
136 self
.minus_one
= False
138 ufixed_match
= Field
.ufixed_pattern
.match(self
.type)
141 self
.fractional_size
= int(ufixed_match
.group(2))
143 sfixed_match
= Field
.sfixed_pattern
.match(self
.type)
146 self
.fractional_size
= int(sfixed_match
.group(2))
148 def emit_template_struct(self
, dim
):
149 if self
.type == 'address':
150 type = '__gen_address_type'
151 elif self
.type == 'bool':
153 elif self
.type == 'float':
155 elif self
.type == 'ufixed':
157 elif self
.type == 'sfixed':
159 elif self
.type == 'uint' and self
.end
- self
.start
> 32:
161 elif self
.type == 'offset':
163 elif self
.type == 'int':
165 elif self
.type == 'uint':
167 elif self
.type in self
.parser
.structs
:
168 type = 'struct ' + self
.parser
.gen_prefix(safe_name(self
.type))
169 elif self
.type in self
.parser
.enums
:
170 type = 'enum ' + self
.parser
.gen_prefix(safe_name(self
.type))
171 elif self
.type == 'mbo':
174 print("#error unhandled type: %s" % self
.type)
177 print(" %-36s %s%s;" % (type, self
.name
, dim
))
179 for value
in self
.values
:
180 name
= prefixed_upper_name(self
.prefix
, value
.name
)
181 print("#define %-40s %d" % (name
, value
.value
))
183 def overlaps(self
, field
):
184 return self
!= field
and max(self
.start
, field
.start
) <= min(self
.end
, field
.end
)
188 def __init__(self
, parser
, parent
, start
, count
):
198 def emit_template_struct(self
, dim
):
200 print(" /* variable length fields follow */")
203 dim
= "%s[%d]" % (dim
, self
.count
)
205 for field
in self
.fields
:
206 field
.emit_template_struct(dim
)
214 def collect_bytes(self
, bytes
):
215 for field
in self
.fields
:
216 first_byte
= field
.start
// 8
217 last_byte
= field
.end
// 8
219 for b
in range(first_byte
, last_byte
+ 1):
221 bytes
[b
] = self
.Byte()
223 bytes
[b
].fields
.append(field
)
225 if field
.type == "address":
226 # assert bytes[index].address == None
227 bytes
[b
].address
= field
229 def emit_pack_function(self
, start
):
230 # Determine number of bytes in this group.
231 self
.length
= max(field
.end
// 8 for field
in self
.fields
) + 1
234 self
.collect_bytes(bytes
)
236 relocs_emitted
= set()
237 memcpy_fields
= set()
239 for field
in self
.fields
:
241 print(" assert(values->%s >= 1);" % field
.name
)
243 for index
in range(self
.length
):
245 if not index
in bytes
:
246 print(" cl[%2d] = 0;" % index
)
250 # Call out to the driver to note our relocations. Inside of the
251 # packet we only store offsets within the BOs, and we store the
252 # handle to the packet outside. Unlike Intel genxml, we don't
253 # need to have the other bits that will be stored together with
254 # the address during the reloc process, so there's no need for the
255 # complicated combine_address() function.
256 if byte
.address
and byte
.address
not in relocs_emitted
:
257 print(" __gen_emit_reloc(data, &values->%s);" % byte
.address
.name
)
258 relocs_emitted
.add(byte
.address
)
260 # Special case: floats can't have any other fields packed into
261 # them (since they'd change the meaning of the float), and the
262 # per-byte bitshifting math below bloats the pack code for floats,
263 # so just copy them directly here. Also handle 16/32-bit
264 # uints/ints with no merged fields.
265 if len(byte
.fields
) == 1:
266 field
= byte
.fields
[0]
267 if field
.type in ["float", "uint", "int"] and field
.start
% 8 == 0 and field
.end
- field
.start
== 31 and not field
.minus_one
:
268 if field
in memcpy_fields
:
271 if not any(field
.overlaps(scan_field
) for scan_field
in self
.fields
):
272 assert(field
.start
== index
* 8)
274 print(" memcpy(&cl[%d], &values->%s, sizeof(values->%s));" %
275 (index
, field
.name
, field
.name
))
276 memcpy_fields
.add(field
)
279 byte_start
= index
* 8
282 prefix
= " cl[%2d] =" % index
285 for field
in byte
.fields
:
286 if field
.type != "mbo":
291 field_byte_start
= (field
.start
// 8) * 8
292 start
-= field_byte_start
293 end
-= field_byte_start
296 value
= "values->%s" % name
298 value
= "%s - 1" % value
300 if field
.type == "mbo":
301 s
= "__gen_mbo(%d, %d)" % \
303 elif field
.type == "address":
304 extra_shift
= (31 - (end
- start
)) // 8 * 8
305 s
= "__gen_address_offset(&values->%s)" % byte
.address
.name
306 elif field
.type == "uint":
307 s
= "__gen_uint(%s, %d, %d)" % \
309 elif field
.type in self
.parser
.enums
:
310 s
= "__gen_uint(%s, %d, %d)" % \
312 elif field
.type == "int":
313 s
= "__gen_sint(%s, %d, %d)" % \
315 elif field
.type == "bool":
316 s
= "__gen_uint(%s, %d, %d)" % \
318 elif field
.type == "float":
319 s
= "#error %s float value mixed in with other fields" % name
320 elif field
.type == "offset":
321 s
= "__gen_offset(%s, %d, %d)" % \
323 elif field
.type == 'ufixed':
324 s
= "__gen_ufixed(%s, %d, %d, %d)" % \
325 (value
, start
, end
, field
.fractional_size
)
326 elif field
.type == 'sfixed':
327 s
= "__gen_sfixed(%s, %d, %d, %d)" % \
328 (value
, start
, end
, field
.fractional_size
)
329 elif field
.type in self
.parser
.structs
:
330 s
= "__gen_uint(v%d_%d, %d, %d)" % \
331 (index
, field_index
, start
, end
)
332 field_index
= field_index
+ 1
334 print("/* unhandled field %s, type %s */\n" % (name
, field
.type))
338 shift
= byte_start
- field_byte_start
+ extra_shift
340 s
= "%s >> %d" % (s
, shift
)
342 if field
== byte
.fields
[-1]:
343 print("%s %s;" % (prefix
, s
))
345 print("%s %s |" % (prefix
, s
))
351 def emit_unpack_function(self
, start
):
352 for field
in self
.fields
:
353 if field
.type != "mbo":
358 args
.append(str(start
+ field
.start
))
359 args
.append(str(start
+ field
.end
))
361 if field
.type == "address":
362 convert
= "__gen_unpack_address"
363 elif field
.type == "uint":
364 convert
= "__gen_unpack_uint"
365 elif field
.type in self
.parser
.enums
:
366 convert
= "__gen_unpack_uint"
367 elif field
.type == "int":
368 convert
= "__gen_unpack_sint"
369 elif field
.type == "bool":
370 convert
= "__gen_unpack_uint"
371 elif field
.type == "float":
372 convert
= "__gen_unpack_float"
373 elif field
.type == "offset":
374 convert
= "__gen_unpack_offset"
375 elif field
.type == 'ufixed':
376 args
.append(str(field
.fractional_size
))
377 convert
= "__gen_unpack_ufixed"
378 elif field
.type == 'sfixed':
379 args
.append(str(field
.fractional_size
))
380 convert
= "__gen_unpack_sfixed"
382 print("/* unhandled field %s, type %s */\n" % (field
.name
, field
.type))
388 print(" values->%s = %s(%s)%s;" % \
389 (field
.name
, convert
, ', '.join(args
), plusone
))
392 def __init__(self
, attrs
):
393 self
.name
= attrs
["name"]
394 self
.value
= int(attrs
["value"])
396 class Parser(object):
397 def __init__(self
, ver
):
398 self
.parser
= xml
.parsers
.expat
.ParserCreate()
399 self
.parser
.StartElementHandler
= self
.start_element
400 self
.parser
.EndElementHandler
= self
.end_element
405 # Set of enum names we've seen.
410 def gen_prefix(self
, name
):
412 return 'V3D%s%s' % (self
.ver
, name
)
414 return 'V3D%s_%s' % (self
.ver
, name
)
417 return self
.gen_prefix("PACK_H")
419 def attrs_version_valid(self
, attrs
):
420 if "min_ver" in attrs
and self
.ver
< attrs
["min_ver"]:
423 if "max_ver" in attrs
and self
.ver
> attrs
["max_ver"]:
428 def group_enabled(self
):
429 if self
.group
.min_ver
!= 0 and self
.ver
< self
.group
.min_ver
:
432 if self
.group
.max_ver
!= 0 and self
.ver
> self
.group
.max_ver
:
437 def start_element(self
, name
, attrs
):
439 self
.platform
= "V3D {}.{}".format(self
.ver
[0], self
.ver
[1])
440 print(pack_header
% {'license': license
, 'platform': self
.platform
, 'guard': self
.gen_guard()})
441 elif name
in ("packet", "struct", "register"):
444 object_name
= self
.gen_prefix(safe_name(attrs
["name"].upper()))
446 self
.packet
= object_name
448 # Add a fixed Field for the opcode. We only make <field>s in
449 # the XML for the fields listed in the spec, and all of those
450 # start from bit 0 after of the opcode.
453 "default" : attrs
["code"],
458 elif name
== "struct":
459 self
.struct
= object_name
460 self
.structs
[attrs
["name"]] = 1
461 elif name
== "register":
462 self
.register
= object_name
463 self
.reg_num
= num_from_str(attrs
["num"])
464 self
.registers
[attrs
["name"]] = 1
466 self
.group
= Group(self
, None, 0, 1)
468 field
= Field(self
, default_field
)
470 self
.group
.fields
.append(field
)
472 if "min_ver" in attrs
:
473 self
.group
.min_ver
= attrs
["min_ver"]
474 if "max_ver" in attrs
:
475 self
.group
.max_ver
= attrs
["max_ver"]
477 elif name
== "field":
478 self
.group
.fields
.append(Field(self
, attrs
))
482 self
.enum
= safe_name(attrs
["name"])
483 self
.enums
.add(attrs
["name"])
484 self
.enum_enabled
= self
.attrs_version_valid(attrs
)
485 if "prefix" in attrs
:
486 self
.prefix
= attrs
["prefix"]
489 elif name
== "value":
490 if self
.attrs_version_valid(attrs
):
491 self
.values
.append(Value(attrs
))
493 def end_element(self
, name
):
498 elif name
== "struct":
502 elif name
== "register":
507 elif name
== "field":
508 self
.group
.fields
[-1].values
= self
.values
510 if self
.enum_enabled
:
513 elif name
== "vcxml":
514 print('#endif /* %s */' % self
.gen_guard())
516 def emit_template_struct(self
, name
, group
):
517 print("struct %s {" % name
)
518 group
.emit_template_struct("")
521 def emit_pack_function(self
, name
, group
):
522 print("static inline void\n%s_pack(__gen_user_data *data, uint8_t * restrict cl,\n%sconst struct %s * restrict values)\n{" %
523 (name
, ' ' * (len(name
) + 6), name
))
525 group
.emit_pack_function(0)
529 print('#define %-33s %6d' %
530 (name
+ "_length", self
.group
.length
))
532 def emit_unpack_function(self
, name
, group
):
533 print("#ifdef __gen_unpack_address")
534 print("static inline void")
535 print("%s_unpack(const uint8_t * restrict cl,\n%sstruct %s * restrict values)\n{" %
536 (name
, ' ' * (len(name
) + 8), name
))
538 group
.emit_unpack_function(0)
542 def emit_header(self
, name
):
544 for field
in self
.group
.fields
:
545 if not type(field
) is Field
:
547 if field
.default
== None:
549 default_fields
.append(" .%-35s = %6d" % (field
.name
, field
.default
))
551 print('#define %-40s\\' % (name
+ '_header'))
552 print(", \\\n".join(default_fields
))
555 def emit_packet(self
):
556 if not self
.group_enabled():
561 assert(self
.group
.fields
[0].name
== "opcode")
562 print('#define %-33s %6d' %
563 (name
+ "_opcode", self
.group
.fields
[0].default
))
565 self
.emit_header(name
)
566 self
.emit_template_struct(self
.packet
, self
.group
)
567 self
.emit_pack_function(self
.packet
, self
.group
)
568 self
.emit_unpack_function(self
.packet
, self
.group
)
572 def emit_register(self
):
573 if not self
.group_enabled():
577 if not self
.reg_num
== None:
578 print('#define %-33s 0x%04x' %
579 (self
.gen_prefix(name
+ "_num"), self
.reg_num
))
581 self
.emit_template_struct(self
.register
, self
.group
)
582 self
.emit_pack_function(self
.register
, self
.group
)
583 self
.emit_unpack_function(self
.register
, self
.group
)
585 def emit_struct(self
):
586 if not self
.group_enabled():
591 self
.emit_header(name
)
592 self
.emit_template_struct(self
.struct
, self
.group
)
593 self
.emit_pack_function(self
.struct
, self
.group
)
594 self
.emit_unpack_function(self
.struct
, self
.group
)
599 print('enum %s {' % self
.gen_prefix(self
.enum
))
600 for value
in self
.values
:
603 name
= self
.prefix
+ "_" + name
604 name
= safe_name(name
).upper()
605 print(' % -36s = %6d,' % (name
, value
.value
))
608 def parse(self
, filename
):
609 file = open(filename
, "rb")
610 self
.parser
.ParseFile(file)
613 if len(sys
.argv
) < 2:
614 print("No input xml file specified")
617 input_file
= sys
.argv
[1]
619 p
= Parser(sys
.argv
[2])