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
):
196 def emit_template_struct(self
, dim
):
198 print(" /* variable length fields follow */")
201 dim
= "%s[%d]" % (dim
, self
.count
)
203 for field
in self
.fields
:
204 field
.emit_template_struct(dim
)
212 def collect_bytes(self
, bytes
):
213 for field
in self
.fields
:
214 first_byte
= field
.start
// 8
215 last_byte
= field
.end
// 8
217 for b
in xrange(first_byte
, last_byte
+ 1):
219 bytes
[b
] = self
.Byte()
221 bytes
[b
].fields
.append(field
)
223 if field
.type == "address":
224 # assert bytes[index].address == None
225 bytes
[b
].address
= field
227 def emit_pack_function(self
, start
):
228 # Determine number of bytes in this group.
229 self
.length
= max(field
.end
// 8 for field
in self
.fields
) + 1
232 self
.collect_bytes(bytes
)
234 relocs_emitted
= set()
235 memcpy_fields
= set()
237 for field
in self
.fields
:
239 print(" assert(values->%s >= 1);" % field
.name
)
241 for index
in range(self
.length
):
243 if not index
in bytes
:
244 print(" cl[%2d] = 0;" % index
)
248 # Call out to the driver to note our relocations. Inside of the
249 # packet we only store offsets within the BOs, and we store the
250 # handle to the packet outside. Unlike Intel genxml, we don't
251 # need to have the other bits that will be stored together with
252 # the address during the reloc process, so there's no need for the
253 # complicated combine_address() function.
254 if byte
.address
and byte
.address
not in relocs_emitted
:
255 print(" __gen_emit_reloc(data, &values->%s);" % byte
.address
.name
)
256 relocs_emitted
.add(byte
.address
)
258 # Special case: floats can't have any other fields packed into
259 # them (since they'd change the meaning of the float), and the
260 # per-byte bitshifting math below bloats the pack code for floats,
261 # so just copy them directly here. Also handle 16/32-bit
262 # uints/ints with no merged fields.
263 if len(byte
.fields
) == 1:
264 field
= byte
.fields
[0]
265 if field
.type in ["float", "uint", "int"] and field
.start
% 8 == 0 and field
.end
- field
.start
== 31 and not field
.minus_one
:
266 if field
in memcpy_fields
:
269 if not any(field
.overlaps(scan_field
) for scan_field
in self
.fields
):
270 assert(field
.start
== index
* 8)
272 print(" memcpy(&cl[%d], &values->%s, sizeof(values->%s));" %
273 (index
, field
.name
, field
.name
))
274 memcpy_fields
.add(field
)
277 byte_start
= index
* 8
280 prefix
= " cl[%2d] =" % index
283 for field
in byte
.fields
:
284 if field
.type != "mbo":
289 field_byte_start
= (field
.start
// 8) * 8
290 start
-= field_byte_start
291 end
-= field_byte_start
294 value
= "values->%s" % name
296 value
= "%s - 1" % value
298 if field
.type == "mbo":
299 s
= "__gen_mbo(%d, %d)" % \
301 elif field
.type == "address":
302 extra_shift
= (31 - (end
- start
)) // 8 * 8
303 s
= "__gen_address_offset(&values->%s)" % byte
.address
.name
304 elif field
.type == "uint":
305 s
= "__gen_uint(%s, %d, %d)" % \
307 elif field
.type in self
.parser
.enums
:
308 s
= "__gen_uint(%s, %d, %d)" % \
310 elif field
.type == "int":
311 s
= "__gen_sint(%s, %d, %d)" % \
313 elif field
.type == "bool":
314 s
= "__gen_uint(%s, %d, %d)" % \
316 elif field
.type == "float":
317 s
= "#error %s float value mixed in with other fields" % name
318 elif field
.type == "offset":
319 s
= "__gen_offset(%s, %d, %d)" % \
321 elif field
.type == 'ufixed':
322 s
= "__gen_ufixed(%s, %d, %d, %d)" % \
323 (value
, start
, end
, field
.fractional_size
)
324 elif field
.type == 'sfixed':
325 s
= "__gen_sfixed(%s, %d, %d, %d)" % \
326 (value
, start
, end
, field
.fractional_size
)
327 elif field
.type in self
.parser
.structs
:
328 s
= "__gen_uint(v%d_%d, %d, %d)" % \
329 (index
, field_index
, start
, end
)
330 field_index
= field_index
+ 1
332 print("/* unhandled field %s, type %s */\n" % (name
, field
.type))
336 shift
= byte_start
- field_byte_start
+ extra_shift
338 s
= "%s >> %d" % (s
, shift
)
340 if field
== byte
.fields
[-1]:
341 print("%s %s;" % (prefix
, s
))
343 print("%s %s |" % (prefix
, s
))
349 def emit_unpack_function(self
, start
):
350 for field
in self
.fields
:
351 if field
.type != "mbo":
356 args
.append(str(start
+ field
.start
))
357 args
.append(str(start
+ field
.end
))
359 if field
.type == "address":
360 convert
= "__gen_unpack_address"
361 elif field
.type == "uint":
362 convert
= "__gen_unpack_uint"
363 elif field
.type in self
.parser
.enums
:
364 convert
= "__gen_unpack_uint"
365 elif field
.type == "int":
366 convert
= "__gen_unpack_sint"
367 elif field
.type == "bool":
368 convert
= "__gen_unpack_uint"
369 elif field
.type == "float":
370 convert
= "__gen_unpack_float"
371 elif field
.type == "offset":
372 convert
= "__gen_unpack_offset"
373 elif field
.type == 'ufixed':
374 args
.append(str(field
.fractional_size
))
375 convert
= "__gen_unpack_ufixed"
376 elif field
.type == 'sfixed':
377 args
.append(str(field
.fractional_size
))
378 convert
= "__gen_unpack_sfixed"
380 print("/* unhandled field %s, type %s */\n" % (field
.name
, field
.type))
386 print(" values->%s = %s(%s)%s;" % \
387 (field
.name
, convert
, ', '.join(args
), plusone
))
390 def __init__(self
, attrs
):
391 self
.name
= attrs
["name"]
392 self
.value
= int(attrs
["value"])
394 class Parser(object):
395 def __init__(self
, ver
):
396 self
.parser
= xml
.parsers
.expat
.ParserCreate()
397 self
.parser
.StartElementHandler
= self
.start_element
398 self
.parser
.EndElementHandler
= self
.end_element
403 # Set of enum names we've seen.
408 def gen_prefix(self
, name
):
410 return 'V3D%s%s' % (self
.ver
, name
)
412 return 'V3D%s_%s' % (self
.ver
, name
)
415 return self
.gen_prefix("PACK_H")
417 def start_element(self
, name
, attrs
):
419 self
.platform
= "V3D {}.{}".format(self
.ver
[0], self
.ver
[1])
420 print(pack_header
% {'license': license
, 'platform': self
.platform
, 'guard': self
.gen_guard()})
421 elif name
in ("packet", "struct", "register"):
424 object_name
= self
.gen_prefix(safe_name(attrs
["name"].upper()))
426 self
.packet
= object_name
428 # Add a fixed Field for the opcode. We only make <field>s in
429 # the XML for the fields listed in the spec, and all of those
430 # start from bit 0 after of the opcode.
433 "default" : attrs
["code"],
438 elif name
== "struct":
439 self
.struct
= object_name
440 self
.structs
[attrs
["name"]] = 1
441 elif name
== "register":
442 self
.register
= object_name
443 self
.reg_num
= num_from_str(attrs
["num"])
444 self
.registers
[attrs
["name"]] = 1
446 self
.group
= Group(self
, None, 0, 1)
448 field
= Field(self
, default_field
)
450 self
.group
.fields
.append(field
)
452 elif name
== "field":
453 self
.group
.fields
.append(Field(self
, attrs
))
457 self
.enum
= safe_name(attrs
["name"])
458 self
.enums
.add(attrs
["name"])
459 if "prefix" in attrs
:
460 self
.prefix
= attrs
["prefix"]
463 elif name
== "value":
464 self
.values
.append(Value(attrs
))
466 def end_element(self
, name
):
471 elif name
== "struct":
475 elif name
== "register":
480 elif name
== "field":
481 self
.group
.fields
[-1].values
= self
.values
485 elif name
== "vcxml":
486 print('#endif /* %s */' % self
.gen_guard())
488 def emit_template_struct(self
, name
, group
):
489 print("struct %s {" % name
)
490 group
.emit_template_struct("")
493 def emit_pack_function(self
, name
, group
):
494 print("static inline void\n%s_pack(__gen_user_data *data, uint8_t * restrict cl,\n%sconst struct %s * restrict values)\n{" %
495 (name
, ' ' * (len(name
) + 6), name
))
497 group
.emit_pack_function(0)
501 print('#define %-33s %6d' %
502 (name
+ "_length", self
.group
.length
))
504 def emit_unpack_function(self
, name
, group
):
505 print("#ifdef __gen_unpack_address")
506 print("static inline void")
507 print("%s_unpack(const uint8_t * restrict cl,\n%sstruct %s * restrict values)\n{" %
508 (name
, ' ' * (len(name
) + 8), name
))
510 group
.emit_unpack_function(0)
514 def emit_header(self
, name
):
516 for field
in self
.group
.fields
:
517 if not type(field
) is Field
:
519 if field
.default
== None:
521 default_fields
.append(" .%-35s = %6d" % (field
.name
, field
.default
))
523 print('#define %-40s\\' % (name
+ '_header'))
524 print(", \\\n".join(default_fields
))
527 def emit_packet(self
):
530 assert(self
.group
.fields
[0].name
== "opcode")
531 print('#define %-33s %6d' %
532 (name
+ "_opcode", self
.group
.fields
[0].default
))
534 self
.emit_header(name
)
535 self
.emit_template_struct(self
.packet
, self
.group
)
536 self
.emit_pack_function(self
.packet
, self
.group
)
537 self
.emit_unpack_function(self
.packet
, self
.group
)
541 def emit_register(self
):
543 if not self
.reg_num
== None:
544 print('#define %-33s 0x%04x' %
545 (self
.gen_prefix(name
+ "_num"), self
.reg_num
))
547 self
.emit_template_struct(self
.register
, self
.group
)
548 self
.emit_pack_function(self
.register
, self
.group
)
549 self
.emit_unpack_function(self
.register
, self
.group
)
551 def emit_struct(self
):
554 self
.emit_header(name
)
555 self
.emit_template_struct(self
.struct
, self
.group
)
556 self
.emit_pack_function(self
.struct
, self
.group
)
557 self
.emit_unpack_function(self
.struct
, self
.group
)
562 print('enum %s {' % self
.gen_prefix(self
.enum
))
563 for value
in self
.values
:
566 name
= self
.prefix
+ "_" + name
567 name
= safe_name(name
).upper()
568 print(' % -36s = %6d,' % (name
, value
.value
))
571 def parse(self
, filename
):
572 file = open(filename
, "rb")
573 self
.parser
.ParseFile(file)
576 if len(sys
.argv
) < 2:
577 print("No input xml file specified")
580 input_file
= sys
.argv
[1]
582 p
= Parser(sys
.argv
[2])