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 '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/>.
28 from typing
import Iterator
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
)
37 * File is generated by scripts/block-coroutine-wrapper.py
42 #include "qemu/osdep.h"
43 #include "block/coroutines.h"
44 #include "block/block-gen.h"
45 #include "block/block_int.h"
46 #include "block/dirty-bitmap.h"
51 param_re
= re
.compile(r
'(?P<decl>'
53 r
'(?P<name>[a-z][a-z0-9_]*)'
56 def __init__(self
, param_decl
: str) -> None:
57 m
= self
.param_re
.match(param_decl
.strip())
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')
66 def __init__(self
, wrapper_type
: str, return_type
: str, name
: str,
67 args
: str, variant
: str) -> None:
68 self
.return_type
= return_type
.strip()
69 self
.name
= name
.strip()
70 self
.struct_name
= snake_to_camel(self
.name
)
71 self
.args
= [ParamDecl(arg
.strip()) for arg
in args
.split(',')]
72 self
.create_only_co
= 'mixed' not in variant
73 self
.graph_rdlock
= 'bdrv_rdlock' in variant
75 self
.wrapper_type
= wrapper_type
77 if wrapper_type
== 'co':
78 subsystem
, subname
= self
.name
.split('_', 1)
79 self
.target_name
= f
'{subsystem}_co_{subname}'
81 assert wrapper_type
== 'no_co'
82 subsystem
, co_infix
, subname
= self
.name
.split('_', 2)
84 raise ValueError(f
"Invalid no_co function name: {self.name}")
85 if not self
.create_only_co
:
86 raise ValueError(f
"no_co function can't be mixed: {self.name}")
88 raise ValueError(f
"no_co function can't be rdlock: {self.name}")
89 self
.target_name
= f
'{subsystem}_{subname}'
91 self
.ctx
= self
.gen_ctx()
93 self
.get_result
= 's->ret = '
94 self
.ret
= 'return s.ret;'
95 self
.co_ret
= 'return '
96 self
.return_field
= self
.return_type
+ " ret;"
97 if self
.return_type
== 'void':
101 self
.return_field
= ''
103 def gen_ctx(self
, prefix
: str = '') -> str:
104 t
= self
.args
[0].type
105 if t
== 'BlockDriverState *':
106 return f
'bdrv_get_aio_context({prefix}bs)'
107 elif t
== 'BdrvChild *':
108 return f
'bdrv_get_aio_context({prefix}child->bs)'
109 elif t
== 'BlockBackend *':
110 return f
'blk_get_aio_context({prefix}blk)'
112 return 'qemu_get_aio_context()'
114 def gen_list(self
, format
: str) -> str:
115 return ', '.join(format
.format_map(arg
.__dict
__) for arg
in self
.args
)
117 def gen_block(self
, format
: str) -> str:
118 return '\n'.join(format
.format_map(arg
.__dict
__) for arg
in self
.args
)
121 # Match wrappers declared with a co_wrapper mark
122 func_decl_re
= re
.compile(r
'^(?P<return_type>[a-zA-Z][a-zA-Z0-9_]* [\*]?)'
123 r
'(\s*coroutine_fn)?'
124 r
'\s*(?P<wrapper_type>(no_)?co)_wrapper'
125 r
'(?P<variant>(_[a-z][a-z0-9_]*)?)\s*'
126 r
'(?P<wrapper_name>[a-z][a-z0-9_]*)'
127 r
'\((?P<args>[^)]*)\);$', re
.MULTILINE
)
130 def func_decl_iter(text
: str) -> Iterator
:
131 for m
in func_decl_re
.finditer(text
):
132 yield FuncDecl(wrapper_type
=m
.group('wrapper_type'),
133 return_type
=m
.group('return_type'),
134 name
=m
.group('wrapper_name'),
135 args
=m
.group('args'),
136 variant
=m
.group('variant'))
139 def snake_to_camel(func_name
: str) -> str:
141 Convert underscore names like 'some_function_name' to camel-case like
144 words
= func_name
.split('_')
145 words
= [w
[0].upper() + w
[1:] for w
in words
]
146 return ''.join(words
)
149 def create_mixed_wrapper(func
: FuncDecl
) -> str:
151 Checks if we are already in coroutine
153 name
= func
.target_name
154 struct_name
= func
.struct_name
155 graph_assume_lock
= 'assume_graph_lock();' if func
.graph_rdlock
else ''
158 {func.return_type} {func.name}({ func.gen_list('{decl}') })
160 if (qemu_in_coroutine()) {{
162 {func.co_ret}{name}({ func.gen_list('{name}') });
165 .poll_state.ctx = {func.ctx},
166 .poll_state.in_progress = true,
168 { func.gen_block(' .{name} = {name},') }
171 s.poll_state.co = qemu_coroutine_create({name}_entry, &s);
173 bdrv_poll_co(&s.poll_state);
179 def create_co_wrapper(func
: FuncDecl
) -> str:
181 Assumes we are not in coroutine, and creates one
183 name
= func
.target_name
184 struct_name
= func
.struct_name
186 {func.return_type} {func.name}({ func.gen_list('{decl}') })
189 .poll_state.ctx = {func.ctx},
190 .poll_state.in_progress = true,
192 { func.gen_block(' .{name} = {name},') }
194 assert(!qemu_in_coroutine());
196 s.poll_state.co = qemu_coroutine_create({name}_entry, &s);
198 bdrv_poll_co(&s.poll_state);
203 def gen_co_wrapper(func
: FuncDecl
) -> str:
204 assert not '_co_' in func
.name
205 assert func
.wrapper_type
== 'co'
207 name
= func
.target_name
208 struct_name
= func
.struct_name
212 if func
.graph_rdlock
:
213 graph_lock
=' bdrv_graph_co_rdlock();'
214 graph_unlock
=' bdrv_graph_co_rdunlock();'
216 creation_function
= create_mixed_wrapper
217 if func
.create_only_co
:
218 creation_function
= create_co_wrapper
222 * Wrappers for {name}
225 typedef struct {struct_name} {{
226 BdrvPollCo poll_state;
228 { func.gen_block(' {decl};') }
231 static void coroutine_fn {name}_entry(void *opaque)
233 {struct_name} *s = opaque;
236 {func.get_result}{name}({ func.gen_list('s->{name}') });
238 s->poll_state.in_progress = false;
243 {creation_function(func)}"""
246 def gen_no_co_wrapper(func
: FuncDecl
) -> str:
247 assert '_co_' in func
.name
248 assert func
.wrapper_type
== 'no_co'
250 name
= func
.target_name
251 struct_name
= func
.struct_name
255 * Wrappers for {name}
258 typedef struct {struct_name} {{
261 { func.gen_block(' {decl};') }
264 static void {name}_bh(void *opaque)
266 {struct_name} *s = opaque;
267 AioContext *ctx = {func.gen_ctx('s->')};
269 aio_context_acquire(ctx);
270 {func.get_result}{name}({ func.gen_list('s->{name}') });
271 aio_context_release(ctx);
276 {func.return_type} coroutine_fn {func.name}({ func.gen_list('{decl}') })
279 .co = qemu_coroutine_self(),
280 { func.gen_block(' .{name} = {name},') }
282 assert(qemu_in_coroutine());
284 aio_bh_schedule_oneshot(qemu_get_aio_context(), {name}_bh, &s);
285 qemu_coroutine_yield();
291 def gen_wrappers(input_code
: str) -> str:
293 for func
in func_decl_iter(input_code
):
295 if func
.wrapper_type
== 'co':
296 res
+= gen_co_wrapper(func
)
298 res
+= gen_no_co_wrapper(func
)
303 if __name__
== '__main__':
304 if len(sys
.argv
) < 3:
305 exit(f
'Usage: {sys.argv[0]} OUT_FILE.c IN_FILE.[ch]...')
307 with
open(sys
.argv
[1], 'w', encoding
='utf-8') as f_out
:
308 f_out
.write(gen_header())
309 for fname
in sys
.argv
[2:]:
310 with
open(fname
, encoding
='utf-8') as f_in
:
311 f_out
.write(gen_wrappers(f_in
.read()))