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 "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 num_from_str(num_str
):
86 if num_str
.lower().startswith('0x'):
87 return int(num_str
, base
=16)
89 assert(not num_str
.startswith('0') and 'octals numbers not allowed')
93 ufixed_pattern
= re
.compile(r
"u(\d+)\.(\d+)")
94 sfixed_pattern
= re
.compile(r
"s(\d+)\.(\d+)")
96 def __init__(self
, parser
, attrs
):
99 self
.name
= safe_name(attrs
["name"]).lower()
101 if str(attrs
["start"]).endswith("b"):
102 self
.start
= int(attrs
["start"][:-1]) * 8
104 self
.start
= int(attrs
["start"])
105 # packet <field> entries in XML start from the bit after the
106 # opcode, so shift everything up by 8 since we'll also have a
107 # Field for the opcode.
108 if not parser
.struct
:
111 self
.end
= self
.start
+ int(attrs
["size"]) - 1
112 self
.type = attrs
["type"]
114 if "prefix" in attrs
:
115 self
.prefix
= safe_name(attrs
["prefix"]).upper()
119 if "default" in attrs
:
120 self
.default
= int(attrs
["default"])
124 ufixed_match
= Field
.ufixed_pattern
.match(self
.type)
127 self
.fractional_size
= int(ufixed_match
.group(2))
129 sfixed_match
= Field
.sfixed_pattern
.match(self
.type)
132 self
.fractional_size
= int(sfixed_match
.group(2))
134 def emit_template_struct(self
, dim
):
135 if self
.type == 'address':
136 type = '__gen_address_type'
137 elif self
.type == 'bool':
139 elif self
.type == 'float':
141 elif self
.type == 'ufixed':
143 elif self
.type == 'sfixed':
145 elif self
.type == 'uint' and self
.end
- self
.start
> 32:
147 elif self
.type == 'offset':
149 elif self
.type == 'int':
151 elif self
.type == 'uint':
153 elif self
.type in self
.parser
.structs
:
154 type = 'struct ' + self
.parser
.gen_prefix(safe_name(self
.type))
155 elif self
.type == 'mbo':
158 print("#error unhandled type: %s" % self
.type)
160 print(" %-36s %s%s;" % (type, self
.name
, dim
))
162 if len(self
.values
) > 0 and self
.default
== None:
164 prefix
= self
.prefix
+ "_"
168 for value
in self
.values
:
169 print("#define %-40s %d" % ((prefix
+ value
.name
).replace("__", "_"),
172 def overlaps(self
, field
):
173 return self
!= field
and max(self
.start
, field
.start
) <= min(self
.end
, field
.end
)
177 def __init__(self
, parser
, parent
, start
, count
):
185 def emit_template_struct(self
, dim
):
187 print(" /* variable length fields follow */")
190 dim
= "%s[%d]" % (dim
, self
.count
)
192 for field
in self
.fields
:
193 field
.emit_template_struct(dim
)
201 def collect_bytes(self
, bytes
):
202 for field
in self
.fields
:
203 first_byte
= field
.start
// 8
204 last_byte
= field
.end
// 8
206 for b
in xrange(first_byte
, last_byte
+ 1):
208 bytes
[b
] = self
.Byte()
210 bytes
[b
].fields
.append(field
)
212 if field
.type == "address":
213 # assert bytes[index].address == None
214 bytes
[b
].address
= field
216 def emit_pack_function(self
, start
):
217 # Determine number of bytes in this group.
218 self
.length
= max(field
.end
// 8 for field
in self
.fields
) + 1
221 self
.collect_bytes(bytes
)
223 relocs_emitted
= set()
224 memcpy_fields
= set()
226 for index
in range(self
.length
):
228 if not index
in bytes
:
229 print(" cl[%2d] = 0;" % index
)
233 # Call out to the driver to note our relocations. Inside of the
234 # packet we only store offsets within the BOs, and we store the
235 # handle to the packet outside. Unlike Intel genxml, we don't
236 # need to have the other bits that will be stored together with
237 # the address during the reloc process, so there's no need for the
238 # complicated combine_address() function.
239 if byte
.address
and byte
.address
not in relocs_emitted
:
240 print(" __gen_emit_reloc(data, &values->%s);" % byte
.address
.name
)
241 relocs_emitted
.add(byte
.address
)
243 # Special case: floats can't have any other fields packed into
244 # them (since they'd change the meaning of the float), and the
245 # per-byte bitshifting math below bloats the pack code for floats,
246 # so just copy them directly here. Also handle 16/32-bit
247 # uints/ints with no merged fields.
248 if len(byte
.fields
) == 1:
249 field
= byte
.fields
[0]
250 if field
.type in ["float", "uint", "int"] and field
.start
% 8 == 0 and field
.end
- field
.start
== 31:
251 if field
in memcpy_fields
:
254 if not any(field
.overlaps(scan_field
) for scan_field
in self
.fields
):
255 assert(field
.start
== index
* 8)
257 print(" memcpy(&cl[%d], &values->%s, sizeof(values->%s));" %
258 (index
, field
.name
, field
.name
))
259 memcpy_fields
.add(field
)
262 byte_start
= index
* 8
265 prefix
= " cl[%2d] =" % index
268 for field
in byte
.fields
:
269 if field
.type != "mbo":
274 field_byte_start
= (field
.start
// 8) * 8
275 start
-= field_byte_start
276 end
-= field_byte_start
278 if field
.type == "mbo":
279 s
= "__gen_mbo(%d, %d)" % \
281 elif field
.type == "address":
282 s
= "__gen_address_offset(&values->%s)" % byte
.address
.name
283 elif field
.type == "uint":
284 s
= "__gen_uint(values->%s, %d, %d)" % \
286 elif field
.type == "int":
287 s
= "__gen_sint(values->%s, %d, %d)" % \
289 elif field
.type == "bool":
290 s
= "__gen_uint(values->%s, %d, %d)" % \
292 elif field
.type == "float":
293 s
= "#error %s float value mixed in with other fields" % name
294 elif field
.type == "offset":
295 s
= "__gen_offset(values->%s, %d, %d)" % \
297 elif field
.type == 'ufixed':
298 s
= "__gen_ufixed(values->%s, %d, %d, %d)" % \
299 (name
, start
, end
, field
.fractional_size
)
300 elif field
.type == 'sfixed':
301 s
= "__gen_sfixed(values->%s, %d, %d, %d)" % \
302 (name
, start
, end
, field
.fractional_size
)
303 elif field
.type in self
.parser
.structs
:
304 s
= "__gen_uint(v%d_%d, %d, %d)" % \
305 (index
, field_index
, start
, end
)
306 field_index
= field_index
+ 1
308 print("/* unhandled field %s, type %s */\n" % (name
, field
.type))
312 if byte_start
- field_byte_start
!= 0:
313 s
= "%s >> %d" % (s
, byte_start
- field_byte_start
)
315 if field
== byte
.fields
[-1]:
316 print("%s %s;" % (prefix
, s
))
318 print("%s %s |" % (prefix
, s
))
324 def emit_unpack_function(self
, start
):
325 for field
in self
.fields
:
326 if field
.type != "mbo":
331 args
.append(str(start
+ field
.start
))
332 args
.append(str(start
+ field
.end
))
334 if field
.type == "address":
335 convert
= "__gen_unpack_address"
336 elif field
.type == "uint":
337 convert
= "__gen_unpack_uint"
338 elif field
.type == "int":
339 convert
= "__gen_unpack_sint"
340 elif field
.type == "bool":
341 convert
= "__gen_unpack_uint"
342 elif field
.type == "float":
343 convert
= "__gen_unpack_float"
344 elif field
.type == "offset":
345 convert
= "__gen_unpack_offset"
346 elif field
.type == 'ufixed':
347 args
.append(str(field
.fractional_size
))
348 convert
= "__gen_unpack_ufixed"
349 elif field
.type == 'sfixed':
350 args
.append(str(field
.fractional_size
))
351 convert
= "__gen_unpack_sfixed"
353 print("/* unhandled field %s, type %s */\n" % (name
, field
.type))
356 print(" values->%s = %s(%s);" % \
357 (field
.name
, convert
, ', '.join(args
)))
360 def __init__(self
, attrs
):
361 self
.name
= safe_name(attrs
["name"]).upper()
362 self
.value
= int(attrs
["value"])
364 class Parser(object):
366 self
.parser
= xml
.parsers
.expat
.ParserCreate()
367 self
.parser
.StartElementHandler
= self
.start_element
368 self
.parser
.EndElementHandler
= self
.end_element
375 def gen_prefix(self
, name
):
377 return 'V3D%s%s' % (self
.ver
, name
)
379 return 'V3D%s_%s' % (self
.ver
, name
)
382 return self
.gen_prefix("PACK_H")
384 def start_element(self
, name
, attrs
):
386 self
.platform
= "V3D {}".format(attrs
["ver"])
387 self
.ver
= attrs
["ver"].replace('.', '')
388 print(pack_header
% {'license': license
, 'platform': self
.platform
, 'guard': self
.gen_guard()})
389 elif name
in ("packet", "struct", "register"):
392 object_name
= self
.gen_prefix(safe_name(attrs
["name"].upper()))
394 self
.packet
= object_name
396 # Add a fixed Field for the opcode. We only make <field>s in
397 # the XML for the fields listed in the spec, and all of those
398 # start from bit 0 after of the opcode.
401 "default" : attrs
["code"],
406 elif name
== "struct":
407 self
.struct
= object_name
408 self
.structs
[attrs
["name"]] = 1
409 elif name
== "register":
410 self
.register
= object_name
411 self
.reg_num
= num_from_str(attrs
["num"])
412 self
.registers
[attrs
["name"]] = 1
414 self
.group
= Group(self
, None, 0, 1)
416 field
= Field(self
, default_field
)
418 self
.group
.fields
.append(field
)
420 elif name
== "field":
421 self
.group
.fields
.append(Field(self
, attrs
))
425 self
.enum
= safe_name(attrs
["name"])
426 if "prefix" in attrs
:
427 self
.prefix
= safe_name(attrs
["prefix"])
430 elif name
== "value":
431 self
.values
.append(Value(attrs
))
433 def end_element(self
, name
):
438 elif name
== "struct":
442 elif name
== "register":
447 elif name
== "field":
448 self
.group
.fields
[-1].values
= self
.values
452 elif name
== "vcxml":
453 print('#endif /* %s */' % self
.gen_guard())
455 def emit_template_struct(self
, name
, group
):
456 print("struct %s {" % name
)
457 group
.emit_template_struct("")
460 def emit_pack_function(self
, name
, group
):
461 print("static inline void\n%s_pack(__gen_user_data *data, uint8_t * restrict cl,\n%sconst struct %s * restrict values)\n{" %
462 (name
, ' ' * (len(name
) + 6), name
))
464 group
.emit_pack_function(0)
468 print('#define %-33s %6d' %
469 (name
+ "_length", self
.group
.length
))
471 def emit_unpack_function(self
, name
, group
):
472 print("#ifdef __gen_unpack_address")
473 print("static inline void")
474 print("%s_unpack(const uint8_t * restrict cl,\n%sstruct %s * restrict values)\n{" %
475 (name
, ' ' * (len(name
) + 8), name
))
477 group
.emit_unpack_function(0)
481 def emit_packet(self
):
484 assert(self
.group
.fields
[0].name
== "opcode")
485 print('#define %-33s %6d' %
486 (name
+ "_opcode", self
.group
.fields
[0].default
))
489 for field
in self
.group
.fields
:
490 if not type(field
) is Field
:
492 if field
.default
== None:
494 default_fields
.append(" .%-35s = %6d" % (field
.name
, field
.default
))
497 print('#define %-40s\\' % (name
+ '_header'))
498 print(", \\\n".join(default_fields
))
501 self
.emit_template_struct(self
.packet
, self
.group
)
502 self
.emit_pack_function(self
.packet
, self
.group
)
503 self
.emit_unpack_function(self
.packet
, self
.group
)
507 def emit_register(self
):
509 if not self
.reg_num
== None:
510 print('#define %-33s 0x%04x' %
511 (self
.gen_prefix(name
+ "_num"), self
.reg_num
))
513 self
.emit_template_struct(self
.register
, self
.group
)
514 self
.emit_pack_function(self
.register
, self
.group
)
515 self
.emit_unpack_function(self
.register
, self
.group
)
517 def emit_struct(self
):
519 # Emit an empty header define so that we can use the CL pack functions
521 print('#define ' + name
+ '_header')
523 self
.emit_template_struct(self
.struct
, self
.group
)
524 self
.emit_pack_function(self
.struct
, self
.group
)
525 self
.emit_unpack_function(self
.struct
, self
.group
)
530 print('/* enum %s */' % self
.gen_prefix(self
.enum
))
531 for value
in self
.values
:
533 name
= self
.prefix
+ "_" + value
.name
536 print('#define %-36s %6d' % (name
.upper(), value
.value
))
539 def parse(self
, filename
):
540 file = open(filename
, "rb")
541 self
.parser
.ParseFile(file)
544 if len(sys
.argv
) < 2:
545 print("No input xml file specified")
548 input_file
= sys
.argv
[1]