1 # Copyright (c) 2015-2017 Intel Corporation
3 # Permission is hereby granted, free of charge, to any person obtaining a
4 # copy of this software and associated documentation files (the "Software"),
5 # to deal in the Software without restriction, including without limitation
6 # the rights to use, copy, modify, merge, publish, distribute, sublicense,
7 # and/or sell copies of the Software, and to permit persons to whom the
8 # Software is furnished to do so, subject to the following conditions:
10 # The above copyright notice and this permission notice (including the next
11 # paragraph) shall be included in all copies or substantial portions of the
14 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
17 # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
19 # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
27 import xml
.etree
.cElementTree
as et
35 code
= ' '.join(map(str,args
))
36 for line
in code
.splitlines():
37 text
= ''.rjust(_c_indent
) + line
38 c_file
.write(text
.rstrip() + "\n")
40 # indented, but no trailing newline...
41 def c_line_start(code
):
42 c_file
.write(''.rjust(_c_indent
) + code
)
48 _c_indent
= _c_indent
+ n
51 _c_indent
= _c_indent
- n
57 code
= ' '.join(map(str,args
))
58 for line
in code
.splitlines():
59 text
= ''.rjust(_h_indent
) + line
60 header_file
.write(text
.rstrip() + "\n")
64 _h_indent
= _h_indent
+ n
67 _h_indent
= _h_indent
- n
70 def emit_fadd(tmp_id
, args
):
71 c("double tmp{0} = {1} + {2};".format(tmp_id
, args
[1], args
[0]))
74 # Be careful to check for divide by zero...
75 def emit_fdiv(tmp_id
, args
):
76 c("double tmp{0} = {1};".format(tmp_id
, args
[1]))
77 c("double tmp{0} = {1};".format(tmp_id
+ 1, args
[0]))
78 c("double tmp{0} = tmp{1} ? tmp{2} / tmp{1} : 0;".format(tmp_id
+ 2, tmp_id
+ 1, tmp_id
))
81 def emit_fmax(tmp_id
, args
):
82 c("double tmp{0} = {1};".format(tmp_id
, args
[1]))
83 c("double tmp{0} = {1};".format(tmp_id
+ 1, args
[0]))
84 c("double tmp{0} = MAX(tmp{1}, tmp{2});".format(tmp_id
+ 2, tmp_id
, tmp_id
+ 1))
87 def emit_fmul(tmp_id
, args
):
88 c("double tmp{0} = {1} * {2};".format(tmp_id
, args
[1], args
[0]))
91 def emit_fsub(tmp_id
, args
):
92 c("double tmp{0} = {1} - {2};".format(tmp_id
, args
[1], args
[0]))
95 def emit_read(tmp_id
, args
):
96 type = args
[1].lower()
97 c("uint64_t tmp{0} = accumulator[query->{1}_offset + {2}];".format(tmp_id
, type, args
[0]))
100 def emit_uadd(tmp_id
, args
):
101 c("uint64_t tmp{0} = {1} + {2};".format(tmp_id
, args
[1], args
[0]))
104 # Be careful to check for divide by zero...
105 def emit_udiv(tmp_id
, args
):
106 c("uint64_t tmp{0} = {1};".format(tmp_id
, args
[1]))
107 c("uint64_t tmp{0} = {1};".format(tmp_id
+ 1, args
[0]))
108 c("uint64_t tmp{0} = tmp{1} ? tmp{2} / tmp{1} : 0;".format(tmp_id
+ 2, tmp_id
+ 1, tmp_id
))
111 def emit_umul(tmp_id
, args
):
112 c("uint64_t tmp{0} = {1} * {2};".format(tmp_id
, args
[1], args
[0]))
115 def emit_usub(tmp_id
, args
):
116 c("uint64_t tmp{0} = {1} - {2};".format(tmp_id
, args
[1], args
[0]))
119 def emit_umin(tmp_id
, args
):
120 c("uint64_t tmp{0} = MIN({1}, {2});".format(tmp_id
, args
[1], args
[0]))
124 # (n operands, emitter)
125 ops
["FADD"] = (2, emit_fadd
)
126 ops
["FDIV"] = (2, emit_fdiv
)
127 ops
["FMAX"] = (2, emit_fmax
)
128 ops
["FMUL"] = (2, emit_fmul
)
129 ops
["FSUB"] = (2, emit_fsub
)
130 ops
["READ"] = (2, emit_read
)
131 ops
["UADD"] = (2, emit_uadd
)
132 ops
["UDIV"] = (2, emit_udiv
)
133 ops
["UMUL"] = (2, emit_umul
)
134 ops
["USUB"] = (2, emit_usub
)
135 ops
["UMIN"] = (2, emit_umin
)
139 return "(" + subexp
+ ")"
143 def splice_bitwise_and(args
):
144 return brkt(args
[1]) + " & " + brkt(args
[0])
146 def splice_logical_and(args
):
147 return brkt(args
[1]) + " && " + brkt(args
[0])
149 def splice_ult(args
):
150 return brkt(args
[1]) + " < " + brkt(args
[0])
152 def splice_ugte(args
):
153 return brkt(args
[1]) + " >= " + brkt(args
[0])
156 # (n operands, splicer)
157 exp_ops
["AND"] = (2, splice_bitwise_and
)
158 exp_ops
["UGTE"] = (2, splice_ugte
)
159 exp_ops
["ULT"] = (2, splice_ult
)
160 exp_ops
["&&"] = (2, splice_logical_and
)
164 hw_vars
["$EuCoresTotalCount"] = "brw->perfquery.sys_vars.n_eus"
165 hw_vars
["$EuSlicesTotalCount"] = "brw->perfquery.sys_vars.n_eu_slices"
166 hw_vars
["$EuSubslicesTotalCount"] = "brw->perfquery.sys_vars.n_eu_sub_slices"
167 hw_vars
["$EuThreadsCount"] = "brw->perfquery.sys_vars.eu_threads_count"
168 hw_vars
["$SliceMask"] = "brw->perfquery.sys_vars.slice_mask"
169 hw_vars
["$SubsliceMask"] = "brw->perfquery.sys_vars.subslice_mask"
170 hw_vars
["$GpuTimestampFrequency"] = "brw->perfquery.sys_vars.timestamp_frequency"
171 hw_vars
["$GpuMinFrequency"] = "brw->perfquery.sys_vars.gt_min_freq"
172 hw_vars
["$GpuMaxFrequency"] = "brw->perfquery.sys_vars.gt_max_freq"
173 hw_vars
["$SkuRevisionId"] = "brw->perfquery.sys_vars.revision"
175 def output_rpn_equation_code(set, counter
, equation
):
176 c("/* RPN equation: " + equation
+ " */")
177 tokens
= equation
.split()
184 while stack
and stack
[-1] in ops
:
186 argc
, callback
= ops
[op
]
188 for i
in range(0, argc
):
189 operand
= stack
.pop()
190 if operand
[0] == "$":
191 if operand
in hw_vars
:
192 operand
= hw_vars
[operand
]
193 elif operand
in set.counter_vars
:
194 reference
= set.counter_vars
[operand
]
195 operand
= set.read_funcs
[operand
[1:]] + "(brw, query, accumulator)"
197 raise Exception("Failed to resolve variable " + operand
+ " in equation " + equation
+ " for " + set.name
+ " :: " + counter
.get('name'));
200 tmp_id
= callback(tmp_id
, args
)
202 tmp
= "tmp{0}".format(tmp_id
- 1)
206 raise Exception("Spurious empty rpn code for " + set.name
+ " :: " +
207 counter
.get('name') + ".\nThis is probably due to some unhandled RPN function, in the equation \"" +
213 value
= hw_vars
[value
]
214 if value
in set.counter_vars
:
215 value
= set.read_funcs
[value
[1:]] + "(brw, query, accumulator)"
217 c("\nreturn " + value
+ ";")
219 def splice_rpn_expression(set, counter
, expression
):
220 tokens
= expression
.split()
225 while stack
and stack
[-1] in exp_ops
:
227 argc
, callback
= exp_ops
[op
]
229 for i
in range(0, argc
):
230 operand
= stack
.pop()
231 if operand
[0] == "$":
232 if operand
in hw_vars
:
233 operand
= hw_vars
[operand
]
235 raise Exception("Failed to resolve variable " + operand
+ " in expression " + expression
+ " for " + set.name
+ " :: " + counter
.get('name'));
238 subexp
= callback(args
)
243 raise Exception("Spurious empty rpn expression for " + set.name
+ " :: " +
244 counter
.get('name') + ".\nThis is probably due to some unhandled RPN operation, in the expression \"" +
249 def output_counter_read(gen
, set, counter
):
251 c("/* {0} :: {1} */".format(set.name
, counter
.get('name')))
253 if counter
.read_hash
in hashed_funcs
:
254 c("#define %s \\" % counter
.read_sym
)
256 c("%s" % hashed_funcs
[counter
.read_hash
])
259 ret_type
= counter
.get('data_type')
260 if ret_type
== "uint64":
261 ret_type
= "uint64_t"
263 read_eq
= counter
.get('equation')
265 c("static " + ret_type
)
266 c(counter
.read_sym
+ "(MAYBE_UNUSED struct brw_context *brw,\n")
267 c_indent(len(counter
.read_sym
) + 1)
268 c("const struct brw_perf_query_info *query,\n")
269 c("uint64_t *accumulator)\n")
270 c_outdent(len(counter
.read_sym
) + 1)
274 output_rpn_equation_code(set, counter
, read_eq
)
278 hashed_funcs
[counter
.read_hash
] = counter
.read_sym
281 def output_counter_max(gen
, set, counter
):
282 max_eq
= counter
.get('max_equation')
284 if not counter
.has_max_func():
288 c("/* {0} :: {1} */".format(set.name
, counter
.get('name')))
290 if counter
.max_hash
in hashed_funcs
:
291 c("#define %s \\" % counter
.max_sym())
293 c("%s" % hashed_funcs
[counter
.max_hash
])
296 ret_type
= counter
.get('data_type')
297 if ret_type
== "uint64":
298 ret_type
= "uint64_t"
300 c("static " + ret_type
)
301 c(counter
.max_sym() + "(struct brw_context *brw)\n")
304 output_rpn_equation_code(set, counter
, max_eq
)
308 hashed_funcs
[counter
.max_hash
] = counter
.max_sym()
311 c_type_sizes
= { "uint32_t": 4, "uint64_t": 8, "float": 4, "double": 8, "bool": 4 }
313 return c_type_sizes
[c_type
]
315 def pot_align(base
, pot_alignment
):
316 return (base
+ pot_alignment
- 1) & ~
(pot_alignment
- 1);
318 semantic_type_map
= {
323 def output_availability(set, availability
, counter_name
):
324 expression
= splice_rpn_expression(set, counter_name
, availability
)
325 lines
= expression
.split(' && ')
328 c("if (" + lines
[0] + ") {")
330 c("if (" + lines
[0] + " &&")
332 for i
in range(1, (n_lines
- 1)):
334 c(lines
[(n_lines
- 1)] + ") {")
338 def output_counter_report(set, counter
, current_offset
):
339 data_type
= counter
.get('data_type')
340 data_type_uc
= data_type
.upper()
344 c_type
= c_type
+ "_t"
346 semantic_type
= counter
.get('semantic_type')
347 if semantic_type
in semantic_type_map
:
348 semantic_type
= semantic_type_map
[semantic_type
]
350 semantic_type_uc
= semantic_type
.upper()
354 availability
= counter
.get('availability')
356 output_availability(set, availability
, counter
.get('name'))
359 c("counter = &query->counters[query->n_counters++];\n")
360 c("counter->oa_counter_read_" + data_type
+ " = " + set.read_funcs
[counter
.get('symbol_name')] + ";\n")
361 c("counter->name = \"" + counter
.get('name') + "\";\n")
362 c("counter->desc = \"" + counter
.get('description') + "\";\n")
363 c("counter->type = GL_PERFQUERY_COUNTER_" + semantic_type_uc
+ "_INTEL;\n")
364 c("counter->data_type = GL_PERFQUERY_COUNTER_DATA_" + data_type_uc
+ "_INTEL;\n")
365 c("counter->raw_max = " + set.max_values
[counter
.get('symbol_name')] + ";\n")
367 current_offset
= pot_align(current_offset
, sizeof(c_type
))
368 c("counter->offset = " + str(current_offset
) + ";\n")
369 c("counter->size = sizeof(" + c_type
+ ");\n")
375 return current_offset
+ sizeof(c_type
)
381 'OA': 'b_counter_regs',
384 def compute_register_lengths(set):
385 register_lengths
= {}
386 register_configs
= set.findall('register_config')
387 for register_config
in register_configs
:
388 t
= register_types
[register_config
.get('type')]
389 if t
not in register_lengths
:
390 register_lengths
[t
] = len(register_config
.findall('register'))
392 register_lengths
[t
] += len(register_config
.findall('register'))
394 return register_lengths
397 def generate_register_configs(set):
398 register_configs
= set.findall('register_config')
399 for register_config
in register_configs
:
400 t
= register_types
[register_config
.get('type')]
402 availability
= register_config
.get('availability')
404 output_availability(set, availability
, register_config
.get('type') + ' register config')
407 for register
in register_config
.findall('register'):
408 c("query->%s[query->n_%s++] = (struct brw_perf_query_register_prog) { .reg = %s, .val = %s };" %
409 (t
, t
, register
.get('address'), register
.get('value')))
417 # Wraps a <counter> element from the brw_oa_*.xml files.
419 def __init__(self
, set, xml
):
422 self
.read_hash
= None
425 self
.read_sym
= "{0}__{1}__{2}__read".format(self
.set.gen
.chipset
,
426 self
.set.underscore_name
,
427 self
.xml
.get('underscore_name'))
430 return self
.xml
.get(prop
)
432 # Compute the hash of a counter's equation by expanding (including all the
433 # sub-equations it depends on)
434 def compute_hashes(self
):
435 if self
.read_hash
is not None:
438 def replace_token(token
):
441 if token
not in self
.set.counter_vars
:
443 self
.set.counter_vars
[token
].compute_hashes()
444 return self
.set.counter_vars
[token
].read_hash
446 read_eq
= self
.xml
.get('equation')
447 self
.read_hash
= ' '.join(map(replace_token
, read_eq
.split()))
449 max_eq
= self
.xml
.get('max_equation')
451 self
.max_hash
= ' '.join(map(replace_token
, max_eq
.split()))
453 def has_max_func(self
):
454 max_eq
= self
.xml
.get('max_equation')
464 for token
in max_eq
.split():
465 if token
[0] == '$' and token
not in hw_vars
:
470 assert self
.has_max_func()
471 return "{0}__{1}__{2}__max".format(self
.set.gen
.chipset
,
472 self
.set.underscore_name
,
473 self
.xml
.get('underscore_name'))
476 max_eq
= self
.xml
.get('max_equation')
478 return "0 /* undefined */"
481 return "{0}".format(float(max_eq
))
485 for token
in max_eq
.split():
486 if token
[0] == '$' and token
not in hw_vars
:
487 return "0 /* unsupported (varies over time) */"
489 return "{0}__{1}__{2}__max(brw)".format(self
.set.gen
.chipset
,
490 self
.set.underscore_name
,
491 self
.xml
.get('underscore_name'))
493 # Wraps a <set> element from the brw_oa_*.xml files.
495 def __init__(self
, gen
, xml
):
499 self
.counter_vars
= {}
503 xml_counters
= self
.xml
.findall("counter")
505 for xml_counter
in xml_counters
:
506 counter
= Counter(self
, xml_counter
)
507 self
.counters
.append(counter
)
508 self
.counter_vars
["$" + counter
.get('symbol_name')] = counter
509 self
.read_funcs
[counter
.get('symbol_name')] = counter
.read_sym
510 self
.max_values
[counter
.get('symbol_name')] = counter
.max_value()
512 for counter
in self
.counters
:
513 counter
.compute_hashes()
516 def hw_config_guid(self
):
517 return self
.xml
.get('hw_config_guid')
521 return self
.xml
.get('name')
524 def symbol_name(self
):
525 return self
.xml
.get('symbol_name')
528 def underscore_name(self
):
529 return self
.xml
.get('underscore_name')
531 def findall(self
, path
):
532 return self
.xml
.findall(path
)
534 def find(self
, path
):
535 return self
.xml
.find(path
)
538 # Wraps an entire brw_oa_*.xml file.
540 def __init__(self
, filename
):
541 self
.filename
= filename
542 self
.xml
= et
.parse(self
.filename
)
543 self
.chipset
= self
.xml
.find('.//set').get('chipset').lower()
546 for xml_set
in self
.xml
.findall(".//set"):
547 self
.sets
.append(Set(self
, xml_set
))
554 parser
= argparse
.ArgumentParser()
555 parser
.add_argument("--header", help="Header file to write", required
=True)
556 parser
.add_argument("--code", help="C file to write", required
=True)
557 parser
.add_argument("xml_files", nargs
='+', help="List of xml metrics files to process")
559 args
= parser
.parse_args()
561 header_file
= open(args
.header
, 'w')
562 c_file
= open(args
.code
, 'w')
565 for xml_file
in args
.xml_files
:
566 gens
.append(Gen(xml_file
))
569 copyright
= textwrap
.dedent("""\
570 /* Autogenerated file, DO NOT EDIT manually! generated by {}
572 * Copyright (c) 2015 Intel Corporation
574 * Permission is hereby granted, free of charge, to any person obtaining a
575 * copy of this software and associated documentation files (the "Software"),
576 * to deal in the Software without restriction, including without limitation
577 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
578 * and/or sell copies of the Software, and to permit persons to whom the
579 * Software is furnished to do so, subject to the following conditions:
581 * The above copyright notice and this permission notice (including the next
582 * paragraph) shall be included in all copies or substantial portions of the
585 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
586 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
587 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
588 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
589 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
590 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
591 * DEALINGS IN THE SOFTWARE.
594 """).format(os
.path
.basename(__file__
))
597 h(textwrap
.dedent("""\
605 c(textwrap
.dedent("""\
609 #include "util/hash_table.h"
613 c("#include \"" + os
.path
.basename(args
.header
) + "\"")
615 c(textwrap
.dedent("""\
616 #include "brw_context.h"
617 #include "brw_performance_query.h"
620 #define MIN(a, b) ((a < b) ? (a) : (b))
621 #define MAX(a, b) ((a > b) ? (a) : (b))
626 # Print out all equation functions.
629 for counter
in set.counters
:
630 output_counter_read(gen
, set, counter
)
631 output_counter_max(gen
, set, counter
)
633 # Print out all metric sets registration functions for each set in each
637 counters
= set.counters
640 register_lengths
= compute_register_lengths(set);
641 for reg_type
, reg_length
in register_lengths
.iteritems():
642 c("static struct brw_perf_query_register_prog {0}_{1}_{2}[{3}];".format(gen
.chipset
,
644 reg_type
, reg_length
))
646 c("\nstatic struct brw_perf_query_counter {0}_{1}_query_counters[{2}];\n".format(gen
.chipset
, set.underscore_name
, len(counters
)))
647 c("static struct brw_perf_query_info " + gen
.chipset
+ "_" + set.underscore_name
+ "_query = {\n")
650 c(".kind = OA_COUNTERS,\n")
651 c(".name = \"" + set.name
+ "\",\n")
652 c(".guid = \"" + set.hw_config_guid
+ "\",\n")
654 c(".counters = {0}_{1}_query_counters,".format(gen
.chipset
, set.underscore_name
))
655 c(".n_counters = 0,")
656 c(".oa_metrics_set_id = 0, /* determined at runtime, via sysfs */")
658 if gen
.chipset
== "hsw":
659 c(textwrap
.dedent("""\
660 .oa_format = I915_OA_FORMAT_A45_B8_C8,
662 /* Accumulation buffer offsets... */
663 .gpu_time_offset = 0,
669 c(textwrap
.dedent("""\
670 .oa_format = I915_OA_FORMAT_A32u40_A4u32_B8_C8,
672 /* Accumulation buffer offsets... */
673 .gpu_time_offset = 0,
674 .gpu_clock_offset = 1,
680 for reg_type
, reg_length
in register_lengths
.iteritems():
681 c(".{0} = {1}_{2}_{3},".format(reg_type
, gen
.chipset
, set.underscore_name
, reg_type
))
682 c(".n_{0} = 0, /* Determined at runtime */".format(reg_type
))
688 c("{0}_register_{1}_counter_query(struct brw_context *brw)\n".format(gen
.chipset
, set.underscore_name
))
692 c("static struct brw_perf_query_info *query = &" + gen
.chipset
+ "_" + set.underscore_name
+ "_query;\n")
693 c("struct brw_perf_query_counter *counter;\n")
696 c("/* Note: we're assuming there can't be any variation in the definition ")
697 c(" * of a query between contexts so it's ok to describe a query within a ")
698 c(" * global variable which only needs to be initialized once... */")
699 c("\nif (!query->data_size) {")
702 generate_register_configs(set)
705 for counter
in counters
:
706 offset
= output_counter_report(set, counter
, offset
)
709 c("\nquery->data_size = counter->offset + counter->size;\n")
714 c("\n_mesa_hash_table_insert(brw->perfquery.oa_metrics_table, query->guid, query);")
719 h("void brw_oa_register_queries_" + gen
.chipset
+ "(struct brw_context *brw);\n")
722 c("brw_oa_register_queries_" + gen
.chipset
+ "(struct brw_context *brw)")
727 c("{0}_register_{1}_counter_query(brw);".format(gen
.chipset
, set.underscore_name
))
733 if __name__
== '__main__':