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
, return_type
: str, name
: str, args
: str,
67 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 subsystem
, subname
= self
.name
.split('_', 1)
76 self
.co_name
= f
'{subsystem}_co_{subname}'
79 if t
== 'BlockDriverState *':
80 ctx
= 'bdrv_get_aio_context(bs)'
81 elif t
== 'BdrvChild *':
82 ctx
= 'bdrv_get_aio_context(child->bs)'
83 elif t
== 'BlockBackend *':
84 ctx
= 'blk_get_aio_context(blk)'
86 ctx
= 'qemu_get_aio_context()'
89 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':
97 self
.return_field
= ''
99 def gen_list(self
, format
: str) -> str:
100 return ', '.join(format
.format_map(arg
.__dict
__) for arg
in self
.args
)
102 def gen_block(self
, format
: str) -> str:
103 return '\n'.join(format
.format_map(arg
.__dict
__) for arg
in self
.args
)
106 # Match wrappers declared with a co_wrapper mark
107 func_decl_re
= re
.compile(r
'^(?P<return_type>[a-zA-Z][a-zA-Z0-9_]* [\*]?)'
109 r
'(?P<variant>(_[a-z][a-z0-9_]*)?)\s*'
110 r
'(?P<wrapper_name>[a-z][a-z0-9_]*)'
111 r
'\((?P<args>[^)]*)\);$', re
.MULTILINE
)
114 def func_decl_iter(text
: str) -> Iterator
:
115 for m
in func_decl_re
.finditer(text
):
116 yield FuncDecl(return_type
=m
.group('return_type'),
117 name
=m
.group('wrapper_name'),
118 args
=m
.group('args'),
119 variant
=m
.group('variant'))
122 def snake_to_camel(func_name
: str) -> str:
124 Convert underscore names like 'some_function_name' to camel-case like
127 words
= func_name
.split('_')
128 words
= [w
[0].upper() + w
[1:] for w
in words
]
129 return ''.join(words
)
132 def create_mixed_wrapper(func
: FuncDecl
) -> str:
134 Checks if we are already in coroutine
137 struct_name
= func
.struct_name
138 graph_assume_lock
= 'assume_graph_lock();' if func
.graph_rdlock
else ''
141 {func.return_type} {func.name}({ func.gen_list('{decl}') })
143 if (qemu_in_coroutine()) {{
145 {func.co_ret}{name}({ func.gen_list('{name}') });
148 .poll_state.ctx = {func.ctx},
149 .poll_state.in_progress = true,
151 { func.gen_block(' .{name} = {name},') }
154 s.poll_state.co = qemu_coroutine_create({name}_entry, &s);
156 bdrv_poll_co(&s.poll_state);
162 def create_co_wrapper(func
: FuncDecl
) -> str:
164 Assumes we are not in coroutine, and creates one
167 struct_name
= func
.struct_name
169 {func.return_type} {func.name}({ func.gen_list('{decl}') })
172 .poll_state.ctx = {func.ctx},
173 .poll_state.in_progress = true,
175 { func.gen_block(' .{name} = {name},') }
177 assert(!qemu_in_coroutine());
179 s.poll_state.co = qemu_coroutine_create({name}_entry, &s);
181 bdrv_poll_co(&s.poll_state);
186 def gen_wrapper(func
: FuncDecl
) -> str:
187 assert not '_co_' in func
.name
190 struct_name
= func
.struct_name
194 if func
.graph_rdlock
:
195 graph_lock
=' bdrv_graph_co_rdlock();'
196 graph_unlock
=' bdrv_graph_co_rdunlock();'
198 creation_function
= create_mixed_wrapper
199 if func
.create_only_co
:
200 creation_function
= create_co_wrapper
204 * Wrappers for {name}
207 typedef struct {struct_name} {{
208 BdrvPollCo poll_state;
210 { func.gen_block(' {decl};') }
213 static void coroutine_fn {name}_entry(void *opaque)
215 {struct_name} *s = opaque;
218 {func.get_result}{name}({ func.gen_list('s->{name}') });
220 s->poll_state.in_progress = false;
225 {creation_function(func)}"""
228 def gen_wrappers(input_code
: str) -> str:
230 for func
in func_decl_iter(input_code
):
232 res
+= gen_wrapper(func
)
237 if __name__
== '__main__':
238 if len(sys
.argv
) < 3:
239 exit(f
'Usage: {sys.argv[0]} OUT_FILE.c IN_FILE.[ch]...')
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()))