target/ppc: Move Vector Compare Equal/Not Equal/Greater Than to decodetree
[qemu/rayw.git] / scripts / block-coroutine-wrapper.py
blob08be813407b636aec129bae27ec25b0436cda0ec
1 #! /usr/bin/env python3
2 """Generate coroutine wrappers for block subsystem.
4 The program parses one or several concatenated c files from stdin,
5 searches for functions with the 'generated_co_wrapper' specifier
6 and generates corresponding wrappers on stdout.
8 Usage: block-coroutine-wrapper.py generated-file.c FILE.[ch]...
10 Copyright (c) 2020 Virtuozzo International GmbH.
12 This program is free software; you can redistribute it and/or modify
13 it under the terms of the GNU General Public License as published by
14 the Free Software Foundation; either version 2 of the License, or
15 (at your option) any later version.
17 This program is distributed in the hope that it will be useful,
18 but WITHOUT ANY WARRANTY; without even the implied warranty of
19 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 GNU General Public License for more details.
22 You should have received a copy of the GNU General Public License
23 along with this program. If not, see <http://www.gnu.org/licenses/>.
24 """
26 import sys
27 import re
28 from typing import Iterator
31 def gen_header():
32 copyright = re.sub('^.*Copyright', 'Copyright', __doc__, flags=re.DOTALL)
33 copyright = re.sub('^(?=.)', ' * ', copyright.strip(), flags=re.MULTILINE)
34 copyright = re.sub('^$', ' *', copyright, flags=re.MULTILINE)
35 return f"""\
37 * File is generated by scripts/block-coroutine-wrapper.py
39 {copyright}
42 #include "qemu/osdep.h"
43 #include "block/coroutines.h"
44 #include "block/block-gen.h"
45 #include "block/block_int.h"\
46 """
49 class ParamDecl:
50 param_re = re.compile(r'(?P<decl>'
51 r'(?P<type>.*[ *])'
52 r'(?P<name>[a-z][a-z0-9_]*)'
53 r')')
55 def __init__(self, param_decl: str) -> None:
56 m = self.param_re.match(param_decl.strip())
57 if m is None:
58 raise ValueError(f'Wrong parameter declaration: "{param_decl}"')
59 self.decl = m.group('decl')
60 self.type = m.group('type')
61 self.name = m.group('name')
64 class FuncDecl:
65 def __init__(self, return_type: str, name: str, args: str) -> None:
66 self.return_type = return_type.strip()
67 self.name = name.strip()
68 self.args = [ParamDecl(arg.strip()) for arg in args.split(',')]
70 def gen_list(self, format: str) -> str:
71 return ', '.join(format.format_map(arg.__dict__) for arg in self.args)
73 def gen_block(self, format: str) -> str:
74 return '\n'.join(format.format_map(arg.__dict__) for arg in self.args)
77 # Match wrappers declared with a generated_co_wrapper mark
78 func_decl_re = re.compile(r'^int\s*generated_co_wrapper\s*'
79 r'(?P<wrapper_name>[a-z][a-z0-9_]*)'
80 r'\((?P<args>[^)]*)\);$', re.MULTILINE)
83 def func_decl_iter(text: str) -> Iterator:
84 for m in func_decl_re.finditer(text):
85 yield FuncDecl(return_type='int',
86 name=m.group('wrapper_name'),
87 args=m.group('args'))
90 def snake_to_camel(func_name: str) -> str:
91 """
92 Convert underscore names like 'some_function_name' to camel-case like
93 'SomeFunctionName'
94 """
95 words = func_name.split('_')
96 words = [w[0].upper() + w[1:] for w in words]
97 return ''.join(words)
100 def gen_wrapper(func: FuncDecl) -> str:
101 assert not '_co_' in func.name
102 assert func.return_type == 'int'
103 assert func.args[0].type in ['BlockDriverState *', 'BdrvChild *',
104 'BlockBackend *']
106 subsystem, subname = func.name.split('_', 1)
108 name = f'{subsystem}_co_{subname}'
110 t = func.args[0].type
111 if t == 'BlockDriverState *':
112 bs = 'bs'
113 elif t == 'BdrvChild *':
114 bs = 'child->bs'
115 else:
116 bs = 'blk_bs(blk)'
117 struct_name = snake_to_camel(name)
119 return f"""\
121 * Wrappers for {name}
124 typedef struct {struct_name} {{
125 BdrvPollCo poll_state;
126 { func.gen_block(' {decl};') }
127 }} {struct_name};
129 static void coroutine_fn {name}_entry(void *opaque)
131 {struct_name} *s = opaque;
133 s->poll_state.ret = {name}({ func.gen_list('s->{name}') });
134 s->poll_state.in_progress = false;
136 aio_wait_kick();
139 int {func.name}({ func.gen_list('{decl}') })
141 if (qemu_in_coroutine()) {{
142 return {name}({ func.gen_list('{name}') });
143 }} else {{
144 {struct_name} s = {{
145 .poll_state.bs = {bs},
146 .poll_state.in_progress = true,
148 { func.gen_block(' .{name} = {name},') }
151 s.poll_state.co = qemu_coroutine_create({name}_entry, &s);
153 return bdrv_poll_co(&s.poll_state);
155 }}"""
158 def gen_wrappers(input_code: str) -> str:
159 res = ''
160 for func in func_decl_iter(input_code):
161 res += '\n\n\n'
162 res += gen_wrapper(func)
164 return res
167 if __name__ == '__main__':
168 if len(sys.argv) < 3:
169 exit(f'Usage: {sys.argv[0]} OUT_FILE.c IN_FILE.[ch]...')
171 with open(sys.argv[1], 'w', encoding='utf-8') as f_out:
172 f_out.write(gen_header())
173 for fname in sys.argv[2:]:
174 with open(fname, encoding='utf-8') as f_in:
175 f_out.write(gen_wrappers(f_in.read()))
176 f_out.write('\n')