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 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 ufixed_match
= Field
.ufixed_pattern
.match(self
.type)
135 self
.fractional_size
= int(ufixed_match
.group(2))
137 sfixed_match
= Field
.sfixed_pattern
.match(self
.type)
140 self
.fractional_size
= int(sfixed_match
.group(2))
142 def emit_template_struct(self
, dim
):
143 if self
.type == 'address':
144 type = '__gen_address_type'
145 elif self
.type == 'bool':
147 elif self
.type == 'float':
149 elif self
.type == 'ufixed':
151 elif self
.type == 'sfixed':
153 elif self
.type == 'uint' and self
.end
- self
.start
> 32:
155 elif self
.type == 'offset':
157 elif self
.type == 'int':
159 elif self
.type == 'uint':
161 elif self
.type in self
.parser
.structs
:
162 type = 'struct ' + self
.parser
.gen_prefix(safe_name(self
.type))
163 elif self
.type in self
.parser
.enums
:
164 type = 'enum ' + self
.parser
.gen_prefix(safe_name(self
.type))
165 elif self
.type == 'mbo':
168 print("#error unhandled type: %s" % self
.type)
170 print(" %-36s %s%s;" % (type, self
.name
, dim
))
172 for value
in self
.values
:
173 name
= prefixed_upper_name(self
.prefix
, value
.name
)
174 print("#define %-40s %d" % (name
, value
.value
))
176 def overlaps(self
, field
):
177 return self
!= field
and max(self
.start
, field
.start
) <= min(self
.end
, field
.end
)
181 def __init__(self
, parser
, parent
, start
, count
):
189 def emit_template_struct(self
, dim
):
191 print(" /* variable length fields follow */")
194 dim
= "%s[%d]" % (dim
, self
.count
)
196 for field
in self
.fields
:
197 field
.emit_template_struct(dim
)
205 def collect_bytes(self
, bytes
):
206 for field
in self
.fields
:
207 first_byte
= field
.start
// 8
208 last_byte
= field
.end
// 8
210 for b
in xrange(first_byte
, last_byte
+ 1):
212 bytes
[b
] = self
.Byte()
214 bytes
[b
].fields
.append(field
)
216 if field
.type == "address":
217 # assert bytes[index].address == None
218 bytes
[b
].address
= field
220 def emit_pack_function(self
, start
):
221 # Determine number of bytes in this group.
222 self
.length
= max(field
.end
// 8 for field
in self
.fields
) + 1
225 self
.collect_bytes(bytes
)
227 relocs_emitted
= set()
228 memcpy_fields
= set()
230 for index
in range(self
.length
):
232 if not index
in bytes
:
233 print(" cl[%2d] = 0;" % index
)
237 # Call out to the driver to note our relocations. Inside of the
238 # packet we only store offsets within the BOs, and we store the
239 # handle to the packet outside. Unlike Intel genxml, we don't
240 # need to have the other bits that will be stored together with
241 # the address during the reloc process, so there's no need for the
242 # complicated combine_address() function.
243 if byte
.address
and byte
.address
not in relocs_emitted
:
244 print(" __gen_emit_reloc(data, &values->%s);" % byte
.address
.name
)
245 relocs_emitted
.add(byte
.address
)
247 # Special case: floats can't have any other fields packed into
248 # them (since they'd change the meaning of the float), and the
249 # per-byte bitshifting math below bloats the pack code for floats,
250 # so just copy them directly here. Also handle 16/32-bit
251 # uints/ints with no merged fields.
252 if len(byte
.fields
) == 1:
253 field
= byte
.fields
[0]
254 if field
.type in ["float", "uint", "int"] and field
.start
% 8 == 0 and field
.end
- field
.start
== 31:
255 if field
in memcpy_fields
:
258 if not any(field
.overlaps(scan_field
) for scan_field
in self
.fields
):
259 assert(field
.start
== index
* 8)
261 print(" memcpy(&cl[%d], &values->%s, sizeof(values->%s));" %
262 (index
, field
.name
, field
.name
))
263 memcpy_fields
.add(field
)
266 byte_start
= index
* 8
269 prefix
= " cl[%2d] =" % index
272 for field
in byte
.fields
:
273 if field
.type != "mbo":
278 field_byte_start
= (field
.start
// 8) * 8
279 start
-= field_byte_start
280 end
-= field_byte_start
283 if field
.type == "mbo":
284 s
= "__gen_mbo(%d, %d)" % \
286 elif field
.type == "address":
287 extra_shift
= (31 - (end
- start
)) // 8 * 8
288 s
= "__gen_address_offset(&values->%s)" % byte
.address
.name
289 elif field
.type == "uint":
290 s
= "__gen_uint(values->%s, %d, %d)" % \
292 elif field
.type in self
.parser
.enums
:
293 s
= "__gen_uint(values->%s, %d, %d)" % \
295 elif field
.type == "int":
296 s
= "__gen_sint(values->%s, %d, %d)" % \
298 elif field
.type == "bool":
299 s
= "__gen_uint(values->%s, %d, %d)" % \
301 elif field
.type == "float":
302 s
= "#error %s float value mixed in with other fields" % name
303 elif field
.type == "offset":
304 s
= "__gen_offset(values->%s, %d, %d)" % \
306 elif field
.type == 'ufixed':
307 s
= "__gen_ufixed(values->%s, %d, %d, %d)" % \
308 (name
, start
, end
, field
.fractional_size
)
309 elif field
.type == 'sfixed':
310 s
= "__gen_sfixed(values->%s, %d, %d, %d)" % \
311 (name
, start
, end
, field
.fractional_size
)
312 elif field
.type in self
.parser
.structs
:
313 s
= "__gen_uint(v%d_%d, %d, %d)" % \
314 (index
, field_index
, start
, end
)
315 field_index
= field_index
+ 1
317 print("/* unhandled field %s, type %s */\n" % (name
, field
.type))
321 shift
= byte_start
- field_byte_start
+ extra_shift
323 s
= "%s >> %d" % (s
, shift
)
325 if field
== byte
.fields
[-1]:
326 print("%s %s;" % (prefix
, s
))
328 print("%s %s |" % (prefix
, s
))
334 def emit_unpack_function(self
, start
):
335 for field
in self
.fields
:
336 if field
.type != "mbo":
341 args
.append(str(start
+ field
.start
))
342 args
.append(str(start
+ field
.end
))
344 if field
.type == "address":
345 convert
= "__gen_unpack_address"
346 elif field
.type == "uint":
347 convert
= "__gen_unpack_uint"
348 elif field
.type in self
.parser
.enums
:
349 convert
= "__gen_unpack_uint"
350 elif field
.type == "int":
351 convert
= "__gen_unpack_sint"
352 elif field
.type == "bool":
353 convert
= "__gen_unpack_uint"
354 elif field
.type == "float":
355 convert
= "__gen_unpack_float"
356 elif field
.type == "offset":
357 convert
= "__gen_unpack_offset"
358 elif field
.type == 'ufixed':
359 args
.append(str(field
.fractional_size
))
360 convert
= "__gen_unpack_ufixed"
361 elif field
.type == 'sfixed':
362 args
.append(str(field
.fractional_size
))
363 convert
= "__gen_unpack_sfixed"
365 print("/* unhandled field %s, type %s */\n" % (name
, field
.type))
368 print(" values->%s = %s(%s);" % \
369 (field
.name
, convert
, ', '.join(args
)))
372 def __init__(self
, attrs
):
373 self
.name
= attrs
["name"]
374 self
.value
= int(attrs
["value"])
376 class Parser(object):
378 self
.parser
= xml
.parsers
.expat
.ParserCreate()
379 self
.parser
.StartElementHandler
= self
.start_element
380 self
.parser
.EndElementHandler
= self
.end_element
385 # Set of enum names we've seen.
389 def gen_prefix(self
, name
):
391 return 'V3D%s%s' % (self
.ver
, name
)
393 return 'V3D%s_%s' % (self
.ver
, name
)
396 return self
.gen_prefix("PACK_H")
398 def start_element(self
, name
, attrs
):
400 self
.platform
= "V3D {}".format(attrs
["gen"])
401 self
.ver
= attrs
["gen"].replace('.', '')
402 print(pack_header
% {'license': license
, 'platform': self
.platform
, 'guard': self
.gen_guard()})
403 elif name
in ("packet", "struct", "register"):
406 object_name
= self
.gen_prefix(safe_name(attrs
["name"].upper()))
408 self
.packet
= object_name
410 # Add a fixed Field for the opcode. We only make <field>s in
411 # the XML for the fields listed in the spec, and all of those
412 # start from bit 0 after of the opcode.
415 "default" : attrs
["code"],
420 elif name
== "struct":
421 self
.struct
= object_name
422 self
.structs
[attrs
["name"]] = 1
423 elif name
== "register":
424 self
.register
= object_name
425 self
.reg_num
= num_from_str(attrs
["num"])
426 self
.registers
[attrs
["name"]] = 1
428 self
.group
= Group(self
, None, 0, 1)
430 field
= Field(self
, default_field
)
432 self
.group
.fields
.append(field
)
434 elif name
== "field":
435 self
.group
.fields
.append(Field(self
, attrs
))
439 self
.enum
= safe_name(attrs
["name"])
440 self
.enums
.add(attrs
["name"])
441 if "prefix" in attrs
:
442 self
.prefix
= attrs
["prefix"]
445 elif name
== "value":
446 self
.values
.append(Value(attrs
))
448 def end_element(self
, name
):
453 elif name
== "struct":
457 elif name
== "register":
462 elif name
== "field":
463 self
.group
.fields
[-1].values
= self
.values
467 elif name
== "vcxml":
468 print('#endif /* %s */' % self
.gen_guard())
470 def emit_template_struct(self
, name
, group
):
471 print("struct %s {" % name
)
472 group
.emit_template_struct("")
475 def emit_pack_function(self
, name
, group
):
476 print("static inline void\n%s_pack(__gen_user_data *data, uint8_t * restrict cl,\n%sconst struct %s * restrict values)\n{" %
477 (name
, ' ' * (len(name
) + 6), name
))
479 group
.emit_pack_function(0)
483 print('#define %-33s %6d' %
484 (name
+ "_length", self
.group
.length
))
486 def emit_unpack_function(self
, name
, group
):
487 print("#ifdef __gen_unpack_address")
488 print("static inline void")
489 print("%s_unpack(const uint8_t * restrict cl,\n%sstruct %s * restrict values)\n{" %
490 (name
, ' ' * (len(name
) + 8), name
))
492 group
.emit_unpack_function(0)
496 def emit_header(self
, name
):
498 for field
in self
.group
.fields
:
499 if not type(field
) is Field
:
501 if field
.default
== None:
503 default_fields
.append(" .%-35s = %6d" % (field
.name
, field
.default
))
505 print('#define %-40s\\' % (name
+ '_header'))
506 print(", \\\n".join(default_fields
))
509 def emit_packet(self
):
512 assert(self
.group
.fields
[0].name
== "opcode")
513 print('#define %-33s %6d' %
514 (name
+ "_opcode", self
.group
.fields
[0].default
))
516 self
.emit_header(name
)
517 self
.emit_template_struct(self
.packet
, self
.group
)
518 self
.emit_pack_function(self
.packet
, self
.group
)
519 self
.emit_unpack_function(self
.packet
, self
.group
)
523 def emit_register(self
):
525 if not self
.reg_num
== None:
526 print('#define %-33s 0x%04x' %
527 (self
.gen_prefix(name
+ "_num"), self
.reg_num
))
529 self
.emit_template_struct(self
.register
, self
.group
)
530 self
.emit_pack_function(self
.register
, self
.group
)
531 self
.emit_unpack_function(self
.register
, self
.group
)
533 def emit_struct(self
):
536 self
.emit_header(name
)
537 self
.emit_template_struct(self
.struct
, self
.group
)
538 self
.emit_pack_function(self
.struct
, self
.group
)
539 self
.emit_unpack_function(self
.struct
, self
.group
)
544 print('enum %s {' % self
.gen_prefix(self
.enum
))
545 for value
in self
.values
:
548 name
= self
.prefix
+ "_" + name
549 name
= safe_name(name
).upper()
550 print(' % -36s = %6d,' % (name
, value
.value
))
553 def parse(self
, filename
):
554 file = open(filename
, "rb")
555 self
.parser
.ParseFile(file)
558 if len(sys
.argv
) < 2:
559 print("No input xml file specified")
562 input_file
= sys
.argv
[1]