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