anv: Implement VK_KHX_external_memory_capabilities
[mesa.git] / src / intel / vulkan / anv_entrypoints_gen.py
1 # coding=utf-8
2 #
3 # Copyright © 2015, 2017 Intel Corporation
4 #
5 # Permission is hereby granted, free of charge, to any person obtaining a
6 # copy of this software and associated documentation files (the "Software"),
7 # to deal in the Software without restriction, including without limitation
8 # the rights to use, copy, modify, merge, publish, distribute, sublicense,
9 # and/or sell copies of the Software, and to permit persons to whom the
10 # Software is furnished to do so, subject to the following conditions:
11 #
12 # The above copyright notice and this permission notice (including the next
13 # paragraph) shall be included in all copies or substantial portions of the
14 # Software.
15 #
16 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21 # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
22 # IN THE SOFTWARE.
23 #
24
25 import argparse
26 import functools
27 import os
28 import textwrap
29 import xml.etree.cElementTree as et
30
31 from mako.template import Template
32
33 MAX_API_VERSION = 1.0
34
35 SUPPORTED_EXTENSIONS = [
36 'VK_KHR_descriptor_update_template',
37 'VK_KHR_get_physical_device_properties2',
38 'VK_KHR_incremental_present',
39 'VK_KHR_maintenance1',
40 'VK_KHR_push_descriptor',
41 'VK_KHR_sampler_mirror_clamp_to_edge',
42 'VK_KHR_shader_draw_parameters',
43 'VK_KHR_surface',
44 'VK_KHR_swapchain',
45 'VK_KHR_wayland_surface',
46 'VK_KHR_xcb_surface',
47 'VK_KHR_xlib_surface',
48 'VK_KHX_external_memory_capabilities',
49 ]
50
51 # We generate a static hash table for entry point lookup
52 # (vkGetProcAddress). We use a linear congruential generator for our hash
53 # function and a power-of-two size table. The prime numbers are determined
54 # experimentally.
55
56 TEMPLATE_H = Template(textwrap.dedent("""\
57 /* This file generated from ${filename}, don't edit directly. */
58
59 struct anv_dispatch_table {
60 union {
61 void *entrypoints[${len(entrypoints)}];
62 struct {
63 % for _, name, _, _, _, guard in entrypoints:
64 % if guard is not None:
65 #ifdef ${guard}
66 PFN_vk${name} ${name};
67 #else
68 void *${name};
69 # endif
70 % else:
71 PFN_vk${name} ${name};
72 % endif
73 % endfor
74 };
75 };
76 };
77
78 % for type_, name, args, num, h, guard in entrypoints:
79 % if guard is not None:
80 #ifdef ${guard}
81 % endif
82 ${type_} anv_${name}(${args});
83 ${type_} gen7_${name}(${args});
84 ${type_} gen75_${name}(${args});
85 ${type_} gen8_${name}(${args});
86 ${type_} gen9_${name}(${args});
87 % if guard is not None:
88 #endif // ${guard}
89 % endif
90 % endfor
91 """), output_encoding='utf-8')
92
93 TEMPLATE_C = Template(textwrap.dedent(u"""\
94 /*
95 * Copyright © 2015 Intel Corporation
96 *
97 * Permission is hereby granted, free of charge, to any person obtaining a
98 * copy of this software and associated documentation files (the "Software"),
99 * to deal in the Software without restriction, including without limitation
100 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
101 * and/or sell copies of the Software, and to permit persons to whom the
102 * Software is furnished to do so, subject to the following conditions:
103 *
104 * The above copyright notice and this permission notice (including the next
105 * paragraph) shall be included in all copies or substantial portions of the
106 * Software.
107 *
108 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
109 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
110 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
111 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
112 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
113 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
114 * IN THE SOFTWARE.
115 */
116
117 /* This file generated from ${filename}, don't edit directly. */
118
119 #include "anv_private.h"
120
121 struct anv_entrypoint {
122 uint32_t name;
123 uint32_t hash;
124 };
125
126 /* We use a big string constant to avoid lots of reloctions from the entry
127 * point table to lots of little strings. The entries in the entry point table
128 * store the index into this big string.
129 */
130
131 static const char strings[] =
132 % for _, name, _, _, _, _ in entrypoints:
133 "vk${name}\\0"
134 % endfor
135 ;
136
137 static const struct anv_entrypoint entrypoints[] = {
138 % for _, _, _, num, h, _ in entrypoints:
139 { ${offsets[num]}, ${'{:0=#8x}'.format(h)} },
140 % endfor
141 };
142
143 /* Weak aliases for all potential implementations. These will resolve to
144 * NULL if they're not defined, which lets the resolve_entrypoint() function
145 * either pick the correct entry point.
146 */
147
148 % for layer in ['anv', 'gen7', 'gen75', 'gen8', 'gen9']:
149 % for type_, name, args, _, _, guard in entrypoints:
150 % if guard is not None:
151 #ifdef ${guard}
152 % endif
153 ${type_} ${layer}_${name}(${args}) __attribute__ ((weak));
154 % if guard is not None:
155 #endif // ${guard}
156 % endif
157 % endfor
158
159 const struct anv_dispatch_table ${layer}_layer = {
160 % for _, name, args, _, _, guard in entrypoints:
161 % if guard is not None:
162 #ifdef ${guard}
163 % endif
164 .${name} = ${layer}_${name},
165 % if guard is not None:
166 #endif // ${guard}
167 % endif
168 % endfor
169 };
170 % endfor
171
172 static void * __attribute__ ((noinline))
173 anv_resolve_entrypoint(const struct gen_device_info *devinfo, uint32_t index)
174 {
175 if (devinfo == NULL) {
176 return anv_layer.entrypoints[index];
177 }
178
179 switch (devinfo->gen) {
180 case 9:
181 if (gen9_layer.entrypoints[index])
182 return gen9_layer.entrypoints[index];
183 /* fall through */
184 case 8:
185 if (gen8_layer.entrypoints[index])
186 return gen8_layer.entrypoints[index];
187 /* fall through */
188 case 7:
189 if (devinfo->is_haswell && gen75_layer.entrypoints[index])
190 return gen75_layer.entrypoints[index];
191
192 if (gen7_layer.entrypoints[index])
193 return gen7_layer.entrypoints[index];
194 /* fall through */
195 case 0:
196 return anv_layer.entrypoints[index];
197 default:
198 unreachable("unsupported gen\\n");
199 }
200 }
201
202 /* Hash table stats:
203 * size ${hash_size} entries
204 * collisions entries:
205 % for i in xrange(10):
206 * ${i}${'+' if i == 9 else ''} ${collisions[i]}
207 % endfor
208 */
209
210 #define none ${'{:#x}'.format(none)}
211 static const uint16_t map[] = {
212 % for i in xrange(0, hash_size, 8):
213 % for j in xrange(i, i + 8):
214 ## This is 6 because the 0x is counted in the length
215 % if mapping[j] & 0xffff == 0xffff:
216 none,
217 % else:
218 ${'{:0=#6x}'.format(mapping[j] & 0xffff)},
219 % endif
220 % endfor
221 % endfor
222 };
223
224 void *
225 anv_lookup_entrypoint(const struct gen_device_info *devinfo, const char *name)
226 {
227 static const uint32_t prime_factor = ${prime_factor};
228 static const uint32_t prime_step = ${prime_step};
229 const struct anv_entrypoint *e;
230 uint32_t hash, h, i;
231 const char *p;
232
233 hash = 0;
234 for (p = name; *p; p++)
235 hash = hash * prime_factor + *p;
236
237 h = hash;
238 do {
239 i = map[h & ${hash_mask}];
240 if (i == none)
241 return NULL;
242 e = &entrypoints[i];
243 h += prime_step;
244 } while (e->hash != hash);
245
246 if (strcmp(name, strings + e->name) != 0)
247 return NULL;
248
249 return anv_resolve_entrypoint(devinfo, i);
250 }"""), output_encoding='utf-8')
251
252 NONE = 0xffff
253 HASH_SIZE = 256
254 U32_MASK = 2**32 - 1
255 HASH_MASK = HASH_SIZE - 1
256
257 PRIME_FACTOR = 5024183
258 PRIME_STEP = 19
259
260
261 def cal_hash(name):
262 """Calculate the same hash value that Mesa will calculate in C."""
263 return functools.reduce(
264 lambda h, c: (h * PRIME_FACTOR + ord(c)) & U32_MASK, name, 0)
265
266
267 def get_entrypoints(doc, entrypoints_to_defines):
268 """Extract the entry points from the registry."""
269 entrypoints = []
270
271 enabled_commands = set()
272 for feature in doc.findall('./feature'):
273 assert feature.attrib['api'] == 'vulkan'
274 if float(feature.attrib['number']) > MAX_API_VERSION:
275 continue
276
277 for command in feature.findall('./require/command'):
278 enabled_commands.add(command.attrib['name'])
279
280 for extension in doc.findall('.extensions/extension'):
281 if extension.attrib['name'] not in SUPPORTED_EXTENSIONS:
282 continue
283
284 assert extension.attrib['supported'] == 'vulkan'
285 for command in extension.findall('./require/command'):
286 enabled_commands.add(command.attrib['name'])
287
288 index = 0
289 for command in doc.findall('./commands/command'):
290 type = command.find('./proto/type').text
291 fullname = command.find('./proto/name').text
292
293 if fullname not in enabled_commands:
294 continue
295
296 shortname = fullname[2:]
297 params = (''.join(p.itertext()) for p in command.findall('./param'))
298 params = ', '.join(params)
299 guard = entrypoints_to_defines.get(fullname)
300 entrypoints.append((type, shortname, params, index, cal_hash(fullname), guard))
301 index += 1
302
303 return entrypoints
304
305
306 def get_entrypoints_defines(doc):
307 """Maps entry points to extension defines."""
308 entrypoints_to_defines = {}
309
310 for extension in doc.findall('./extensions/extension[@protect]'):
311 define = extension.attrib['protect']
312
313 for entrypoint in extension.findall('./require/command'):
314 fullname = entrypoint.attrib['name']
315 entrypoints_to_defines[fullname] = define
316
317 return entrypoints_to_defines
318
319
320 def gen_code(entrypoints):
321 """Generate the C code."""
322 i = 0
323 offsets = []
324 for _, name, _, _, _, _ in entrypoints:
325 offsets.append(i)
326 i += 2 + len(name) + 1
327
328 mapping = [NONE] * HASH_SIZE
329 collisions = [0] * 10
330 for _, name, _, num, h, _ in entrypoints:
331 level = 0
332 while mapping[h & HASH_MASK] != NONE:
333 h = h + PRIME_STEP
334 level = level + 1
335 if level > 9:
336 collisions[9] += 1
337 else:
338 collisions[level] += 1
339 mapping[h & HASH_MASK] = num
340
341 return TEMPLATE_C.render(entrypoints=entrypoints,
342 offsets=offsets,
343 collisions=collisions,
344 mapping=mapping,
345 hash_mask=HASH_MASK,
346 prime_step=PRIME_STEP,
347 prime_factor=PRIME_FACTOR,
348 none=NONE,
349 hash_size=HASH_SIZE,
350 filename=os.path.basename(__file__))
351
352
353 def main():
354 parser = argparse.ArgumentParser()
355 parser.add_argument('--outdir', help='Where to write the files.',
356 required=True)
357 parser.add_argument('--xml', help='Vulkan API XML file.', required=True)
358 args = parser.parse_args()
359
360 doc = et.parse(args.xml)
361 entrypoints = get_entrypoints(doc, get_entrypoints_defines(doc))
362
363 # Manually add CreateDmaBufImageINTEL for which we don't have an extension
364 # defined.
365 entrypoints.append(('VkResult', 'CreateDmaBufImageINTEL',
366 'VkDevice device, ' +
367 'const VkDmaBufImageCreateInfo* pCreateInfo, ' +
368 'const VkAllocationCallbacks* pAllocator,' +
369 'VkDeviceMemory* pMem,' +
370 'VkImage* pImage', len(entrypoints),
371 cal_hash('vkCreateDmaBufImageINTEL'), None))
372
373 # For outputting entrypoints.h we generate a anv_EntryPoint() prototype
374 # per entry point.
375 with open(os.path.join(args.outdir, 'anv_entrypoints.h'), 'wb') as f:
376 f.write(TEMPLATE_H.render(entrypoints=entrypoints,
377 filename=os.path.basename(__file__)))
378 with open(os.path.join(args.outdir, 'anv_entrypoints.c'), 'wb') as f:
379 f.write(gen_code(entrypoints))
380
381
382 if __name__ == '__main__':
383 main()