blob: e82b6481277f0cd6c64586f463426074fa4b0c0b [file] [log] [blame]
Vladimir Sementsov-Ogievskiyaaaa20b2020-09-24 21:54:11 +03001#! /usr/bin/env python3
2"""Generate coroutine wrappers for block subsystem.
3
4The program parses one or several concatenated c files from stdin,
Emanuele Giuseppe Esposito76a2f552022-11-28 09:23:33 -05005searches for functions with the 'co_wrapper' specifier
Vladimir Sementsov-Ogievskiyaaaa20b2020-09-24 21:54:11 +03006and generates corresponding wrappers on stdout.
7
8Usage: block-coroutine-wrapper.py generated-file.c FILE.[ch]...
9
10Copyright (c) 2020 Virtuozzo International GmbH.
11
12This program is free software; you can redistribute it and/or modify
13it under the terms of the GNU General Public License as published by
14the Free Software Foundation; either version 2 of the License, or
15(at your option) any later version.
16
17This program is distributed in the hope that it will be useful,
18but WITHOUT ANY WARRANTY; without even the implied warranty of
19MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20GNU General Public License for more details.
21
22You should have received a copy of the GNU General Public License
23along with this program. If not, see <http://www.gnu.org/licenses/>.
24"""
25
26import sys
27import re
28from typing import Iterator
29
30
31def 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"""\
36/*
37 * File is generated by scripts/block-coroutine-wrapper.py
38 *
39{copyright}
40 */
41
42#include "qemu/osdep.h"
43#include "block/coroutines.h"
44#include "block/block-gen.h"
Markus Armbrustere2c1c342022-12-21 14:35:49 +010045#include "block/block_int.h"
46#include "block/dirty-bitmap.h"
Vladimir Sementsov-Ogievskiyaaaa20b2020-09-24 21:54:11 +030047"""
48
49
50class ParamDecl:
51 param_re = re.compile(r'(?P<decl>'
52 r'(?P<type>.*[ *])'
53 r'(?P<name>[a-z][a-z0-9_]*)'
54 r')')
55
56 def __init__(self, param_decl: str) -> None:
57 m = self.param_re.match(param_decl.strip())
58 if m is None:
59 raise ValueError(f'Wrong parameter declaration: "{param_decl}"')
60 self.decl = m.group('decl')
61 self.type = m.group('type')
62 self.name = m.group('name')
63
64
65class FuncDecl:
Emanuele Giuseppe Esposito76a2f552022-11-28 09:23:33 -050066 def __init__(self, return_type: str, name: str, args: str,
67 variant: str) -> None:
Vladimir Sementsov-Ogievskiyaaaa20b2020-09-24 21:54:11 +030068 self.return_type = return_type.strip()
69 self.name = name.strip()
Emanuele Giuseppe Esposito76a2f552022-11-28 09:23:33 -050070 self.struct_name = snake_to_camel(self.name)
Vladimir Sementsov-Ogievskiyaaaa20b2020-09-24 21:54:11 +030071 self.args = [ParamDecl(arg.strip()) for arg in args.split(',')]
Emanuele Giuseppe Esposito76a2f552022-11-28 09:23:33 -050072 self.create_only_co = 'mixed' not in variant
Emanuele Giuseppe Espositoe6d3f7a2022-12-07 14:18:36 +010073 self.graph_rdlock = 'bdrv_rdlock' in variant
Emanuele Giuseppe Esposito76a2f552022-11-28 09:23:33 -050074
75 subsystem, subname = self.name.split('_', 1)
76 self.co_name = f'{subsystem}_co_{subname}'
77
78 t = self.args[0].type
79 if t == 'BlockDriverState *':
Emanuele Giuseppe Esposito0582fb82022-11-28 09:23:34 -050080 ctx = 'bdrv_get_aio_context(bs)'
Emanuele Giuseppe Esposito76a2f552022-11-28 09:23:33 -050081 elif t == 'BdrvChild *':
Emanuele Giuseppe Esposito0582fb82022-11-28 09:23:34 -050082 ctx = 'bdrv_get_aio_context(child->bs)'
83 elif t == 'BlockBackend *':
84 ctx = 'blk_get_aio_context(blk)'
Emanuele Giuseppe Esposito76a2f552022-11-28 09:23:33 -050085 else:
Emanuele Giuseppe Esposito0582fb82022-11-28 09:23:34 -050086 ctx = 'qemu_get_aio_context()'
87 self.ctx = ctx
Vladimir Sementsov-Ogievskiyaaaa20b2020-09-24 21:54:11 +030088
Emanuele Giuseppe Esposito5b317b82023-01-13 21:41:59 +010089 self.get_result = 's->ret = '
90 self.ret = 'return s.ret;'
91 self.co_ret = 'return '
92 self.return_field = self.return_type + " ret;"
93 if self.return_type == 'void':
94 self.get_result = ''
95 self.ret = ''
96 self.co_ret = ''
97 self.return_field = ''
98
Vladimir Sementsov-Ogievskiyaaaa20b2020-09-24 21:54:11 +030099 def gen_list(self, format: str) -> str:
100 return ', '.join(format.format_map(arg.__dict__) for arg in self.args)
101
102 def gen_block(self, format: str) -> str:
103 return '\n'.join(format.format_map(arg.__dict__) for arg in self.args)
104
105
Emanuele Giuseppe Esposito76a2f552022-11-28 09:23:33 -0500106# Match wrappers declared with a co_wrapper mark
Emanuele Giuseppe Esposito6700dfb2022-11-28 09:23:35 -0500107func_decl_re = re.compile(r'^(?P<return_type>[a-zA-Z][a-zA-Z0-9_]* [\*]?)'
108 r'\s*co_wrapper'
Emanuele Giuseppe Esposito76a2f552022-11-28 09:23:33 -0500109 r'(?P<variant>(_[a-z][a-z0-9_]*)?)\s*'
Vladimir Sementsov-Ogievskiyaaaa20b2020-09-24 21:54:11 +0300110 r'(?P<wrapper_name>[a-z][a-z0-9_]*)'
111 r'\((?P<args>[^)]*)\);$', re.MULTILINE)
112
113
114def func_decl_iter(text: str) -> Iterator:
115 for m in func_decl_re.finditer(text):
Emanuele Giuseppe Esposito6700dfb2022-11-28 09:23:35 -0500116 yield FuncDecl(return_type=m.group('return_type'),
Vladimir Sementsov-Ogievskiyaaaa20b2020-09-24 21:54:11 +0300117 name=m.group('wrapper_name'),
Emanuele Giuseppe Esposito76a2f552022-11-28 09:23:33 -0500118 args=m.group('args'),
119 variant=m.group('variant'))
Vladimir Sementsov-Ogievskiyaaaa20b2020-09-24 21:54:11 +0300120
121
122def snake_to_camel(func_name: str) -> str:
123 """
124 Convert underscore names like 'some_function_name' to camel-case like
125 'SomeFunctionName'
126 """
127 words = func_name.split('_')
128 words = [w[0].upper() + w[1:] for w in words]
129 return ''.join(words)
130
131
Emanuele Giuseppe Esposito76a2f552022-11-28 09:23:33 -0500132def create_mixed_wrapper(func: FuncDecl) -> str:
133 """
134 Checks if we are already in coroutine
135 """
136 name = func.co_name
137 struct_name = func.struct_name
Emanuele Giuseppe Espositoe6d3f7a2022-12-07 14:18:36 +0100138 graph_assume_lock = 'assume_graph_lock();' if func.graph_rdlock else ''
139
Emanuele Giuseppe Esposito76a2f552022-11-28 09:23:33 -0500140 return f"""\
Emanuele Giuseppe Esposito6700dfb2022-11-28 09:23:35 -0500141{func.return_type} {func.name}({ func.gen_list('{decl}') })
Emanuele Giuseppe Esposito76a2f552022-11-28 09:23:33 -0500142{{
143 if (qemu_in_coroutine()) {{
Emanuele Giuseppe Espositoe6d3f7a2022-12-07 14:18:36 +0100144 {graph_assume_lock}
Emanuele Giuseppe Esposito5b317b82023-01-13 21:41:59 +0100145 {func.co_ret}{name}({ func.gen_list('{name}') });
Emanuele Giuseppe Esposito76a2f552022-11-28 09:23:33 -0500146 }} else {{
147 {struct_name} s = {{
Emanuele Giuseppe Esposito0582fb82022-11-28 09:23:34 -0500148 .poll_state.ctx = {func.ctx},
Emanuele Giuseppe Esposito76a2f552022-11-28 09:23:33 -0500149 .poll_state.in_progress = true,
150
151{ func.gen_block(' .{name} = {name},') }
152 }};
153
154 s.poll_state.co = qemu_coroutine_create({name}_entry, &s);
155
Emanuele Giuseppe Esposito6700dfb2022-11-28 09:23:35 -0500156 bdrv_poll_co(&s.poll_state);
Emanuele Giuseppe Esposito5b317b82023-01-13 21:41:59 +0100157 {func.ret}
Emanuele Giuseppe Esposito76a2f552022-11-28 09:23:33 -0500158 }}
159}}"""
160
161
162def create_co_wrapper(func: FuncDecl) -> str:
163 """
164 Assumes we are not in coroutine, and creates one
165 """
166 name = func.co_name
167 struct_name = func.struct_name
168 return f"""\
Emanuele Giuseppe Esposito6700dfb2022-11-28 09:23:35 -0500169{func.return_type} {func.name}({ func.gen_list('{decl}') })
Emanuele Giuseppe Esposito76a2f552022-11-28 09:23:33 -0500170{{
171 {struct_name} s = {{
Emanuele Giuseppe Esposito0582fb82022-11-28 09:23:34 -0500172 .poll_state.ctx = {func.ctx},
Emanuele Giuseppe Esposito76a2f552022-11-28 09:23:33 -0500173 .poll_state.in_progress = true,
174
175{ func.gen_block(' .{name} = {name},') }
176 }};
177 assert(!qemu_in_coroutine());
178
179 s.poll_state.co = qemu_coroutine_create({name}_entry, &s);
180
Emanuele Giuseppe Esposito6700dfb2022-11-28 09:23:35 -0500181 bdrv_poll_co(&s.poll_state);
Emanuele Giuseppe Esposito5b317b82023-01-13 21:41:59 +0100182 {func.ret}
Emanuele Giuseppe Esposito76a2f552022-11-28 09:23:33 -0500183}}"""
184
185
Vladimir Sementsov-Ogievskiyaaaa20b2020-09-24 21:54:11 +0300186def gen_wrapper(func: FuncDecl) -> str:
Vladimir Sementsov-Ogievskiybb436942021-06-10 13:07:57 +0300187 assert not '_co_' in func.name
Vladimir Sementsov-Ogievskiyaaaa20b2020-09-24 21:54:11 +0300188
Emanuele Giuseppe Esposito76a2f552022-11-28 09:23:33 -0500189 name = func.co_name
190 struct_name = func.struct_name
Vladimir Sementsov-Ogievskiybb436942021-06-10 13:07:57 +0300191
Emanuele Giuseppe Espositoe6d3f7a2022-12-07 14:18:36 +0100192 graph_lock=''
193 graph_unlock=''
194 if func.graph_rdlock:
195 graph_lock=' bdrv_graph_co_rdlock();'
196 graph_unlock=' bdrv_graph_co_rdunlock();'
197
Emanuele Giuseppe Esposito76a2f552022-11-28 09:23:33 -0500198 creation_function = create_mixed_wrapper
199 if func.create_only_co:
200 creation_function = create_co_wrapper
Vladimir Sementsov-Ogievskiyaaaa20b2020-09-24 21:54:11 +0300201
202 return f"""\
203/*
204 * Wrappers for {name}
205 */
206
207typedef struct {struct_name} {{
208 BdrvPollCo poll_state;
Emanuele Giuseppe Esposito5b317b82023-01-13 21:41:59 +0100209 {func.return_field}
Vladimir Sementsov-Ogievskiyaaaa20b2020-09-24 21:54:11 +0300210{ func.gen_block(' {decl};') }
211}} {struct_name};
212
213static void coroutine_fn {name}_entry(void *opaque)
214{{
215 {struct_name} *s = opaque;
216
Emanuele Giuseppe Espositoe6d3f7a2022-12-07 14:18:36 +0100217{graph_lock}
Emanuele Giuseppe Esposito5b317b82023-01-13 21:41:59 +0100218 {func.get_result}{name}({ func.gen_list('s->{name}') });
Emanuele Giuseppe Espositoe6d3f7a2022-12-07 14:18:36 +0100219{graph_unlock}
Vladimir Sementsov-Ogievskiyaaaa20b2020-09-24 21:54:11 +0300220 s->poll_state.in_progress = false;
221
222 aio_wait_kick();
223}}
224
Emanuele Giuseppe Esposito76a2f552022-11-28 09:23:33 -0500225{creation_function(func)}"""
Vladimir Sementsov-Ogievskiyaaaa20b2020-09-24 21:54:11 +0300226
227
228def gen_wrappers(input_code: str) -> str:
229 res = ''
230 for func in func_decl_iter(input_code):
231 res += '\n\n\n'
232 res += gen_wrapper(func)
233
234 return res
235
236
237if __name__ == '__main__':
238 if len(sys.argv) < 3:
239 exit(f'Usage: {sys.argv[0]} OUT_FILE.c IN_FILE.[ch]...')
240
241 with open(sys.argv[1], 'w', encoding='utf-8') as f_out:
242 f_out.write(gen_header())
243 for fname in sys.argv[2:]:
244 with open(fname, encoding='utf-8') as f_in:
245 f_out.write(gen_wrappers(f_in.read()))
246 f_out.write('\n')