1#! /usr/bin/env python3
2"""Generate coroutine wrappers for block subsystem.
3
4The program parses one or several concatenated c files from stdin,
5searches for functions with the 'co_wrapper' specifier
6and 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"
45#include "block/block_int.h"
46#include "block/dirty-bitmap.h"
47"""
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:
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
74
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 *':
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)'
85        else:
86            ctx = 'qemu_get_aio_context()'
87        self.ctx = ctx
88
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':
94            self.get_result = ''
95            self.ret = ''
96            self.co_ret = ''
97            self.return_field = ''
98
99    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
106# Match wrappers declared with a co_wrapper mark
107func_decl_re = re.compile(r'^(?P<return_type>[a-zA-Z][a-zA-Z0-9_]* [\*]?)'
108                          r'\s*co_wrapper'
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)
112
113
114def 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'))
120
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
132def 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
138    graph_assume_lock = 'assume_graph_lock();' if func.graph_rdlock else ''
139
140    return f"""\
141{func.return_type} {func.name}({ func.gen_list('{decl}') })
142{{
143    if (qemu_in_coroutine()) {{
144        {graph_assume_lock}
145        {func.co_ret}{name}({ func.gen_list('{name}') });
146    }} else {{
147        {struct_name} s = {{
148            .poll_state.ctx = {func.ctx},
149            .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
156        bdrv_poll_co(&s.poll_state);
157        {func.ret}
158    }}
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"""\
169{func.return_type} {func.name}({ func.gen_list('{decl}') })
170{{
171    {struct_name} s = {{
172        .poll_state.ctx = {func.ctx},
173        .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
181    bdrv_poll_co(&s.poll_state);
182    {func.ret}
183}}"""
184
185
186def gen_wrapper(func: FuncDecl) -> str:
187    assert not '_co_' in func.name
188
189    name = func.co_name
190    struct_name = func.struct_name
191
192    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
198    creation_function = create_mixed_wrapper
199    if func.create_only_co:
200        creation_function = create_co_wrapper
201
202    return f"""\
203/*
204 * Wrappers for {name}
205 */
206
207typedef struct {struct_name} {{
208    BdrvPollCo poll_state;
209    {func.return_field}
210{ func.gen_block('    {decl};') }
211}} {struct_name};
212
213static void coroutine_fn {name}_entry(void *opaque)
214{{
215    {struct_name} *s = opaque;
216
217{graph_lock}
218    {func.get_result}{name}({ func.gen_list('s->{name}') });
219{graph_unlock}
220    s->poll_state.in_progress = false;
221
222    aio_wait_kick();
223}}
224
225{creation_function(func)}"""
226
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')
247