2
0

block-coroutine-wrapper.py 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  1. #! /usr/bin/env python3
  2. """Generate coroutine wrappers for block subsystem.
  3. The program parses one or several concatenated c files from stdin,
  4. searches for functions with the 'co_wrapper' specifier
  5. and generates corresponding wrappers on stdout.
  6. Usage: block-coroutine-wrapper.py generated-file.c FILE.[ch]...
  7. Copyright (c) 2020 Virtuozzo International GmbH.
  8. This program is free software; you can redistribute it and/or modify
  9. it under the terms of the GNU General Public License as published by
  10. the Free Software Foundation; either version 2 of the License, or
  11. (at your option) any later version.
  12. This program is distributed in the hope that it will be useful,
  13. but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. GNU General Public License for more details.
  16. You should have received a copy of the GNU General Public License
  17. along with this program. If not, see <http://www.gnu.org/licenses/>.
  18. """
  19. import sys
  20. import re
  21. from typing import Iterator
  22. def gen_header():
  23. copyright = re.sub('^.*Copyright', 'Copyright', __doc__, flags=re.DOTALL)
  24. copyright = re.sub('^(?=.)', ' * ', copyright.strip(), flags=re.MULTILINE)
  25. copyright = re.sub('^$', ' *', copyright, flags=re.MULTILINE)
  26. return f"""\
  27. /*
  28. * File is generated by scripts/block-coroutine-wrapper.py
  29. *
  30. {copyright}
  31. */
  32. #include "qemu/osdep.h"
  33. #include "block/coroutines.h"
  34. #include "block/block-gen.h"
  35. #include "block/block_int.h"
  36. #include "block/dirty-bitmap.h"
  37. """
  38. class ParamDecl:
  39. param_re = re.compile(r'(?P<decl>'
  40. r'(?P<type>.*[ *])'
  41. r'(?P<name>[a-z][a-z0-9_]*)'
  42. r')')
  43. def __init__(self, param_decl: str) -> None:
  44. m = self.param_re.match(param_decl.strip())
  45. if m is None:
  46. raise ValueError(f'Wrong parameter declaration: "{param_decl}"')
  47. self.decl = m.group('decl')
  48. self.type = m.group('type')
  49. self.name = m.group('name')
  50. class FuncDecl:
  51. def __init__(self, wrapper_type: str, return_type: str, name: str,
  52. args: str, variant: str) -> None:
  53. self.return_type = return_type.strip()
  54. self.name = name.strip()
  55. self.struct_name = snake_to_camel(self.name)
  56. self.args = [ParamDecl(arg.strip()) for arg in args.split(',')]
  57. self.create_only_co = 'mixed' not in variant
  58. self.graph_rdlock = 'bdrv_rdlock' in variant
  59. self.graph_wrlock = 'bdrv_wrlock' in variant
  60. self.wrapper_type = wrapper_type
  61. if wrapper_type == 'co':
  62. if self.graph_wrlock:
  63. raise ValueError(f"co function can't be wrlock: {self.name}")
  64. subsystem, subname = self.name.split('_', 1)
  65. self.target_name = f'{subsystem}_co_{subname}'
  66. else:
  67. assert wrapper_type == 'no_co'
  68. subsystem, co_infix, subname = self.name.split('_', 2)
  69. if co_infix != 'co':
  70. raise ValueError(f"Invalid no_co function name: {self.name}")
  71. if not self.create_only_co:
  72. raise ValueError(f"no_co function can't be mixed: {self.name}")
  73. if self.graph_rdlock:
  74. raise ValueError(f"no_co function can't be rdlock: {self.name}")
  75. self.target_name = f'{subsystem}_{subname}'
  76. self.ctx = self.gen_ctx()
  77. self.get_result = 's->ret = '
  78. self.ret = 'return s.ret;'
  79. self.co_ret = 'return '
  80. self.return_field = self.return_type + " ret;"
  81. if self.return_type == 'void':
  82. self.get_result = ''
  83. self.ret = ''
  84. self.co_ret = ''
  85. self.return_field = ''
  86. def gen_ctx(self, prefix: str = '') -> str:
  87. t = self.args[0].type
  88. name = self.args[0].name
  89. if t == 'BlockDriverState *':
  90. return f'bdrv_get_aio_context({prefix}{name})'
  91. elif t == 'BdrvChild *':
  92. return f'bdrv_get_aio_context({prefix}{name}->bs)'
  93. elif t == 'BlockBackend *':
  94. return f'blk_get_aio_context({prefix}{name})'
  95. else:
  96. return 'qemu_get_aio_context()'
  97. def gen_list(self, format: str) -> str:
  98. return ', '.join(format.format_map(arg.__dict__) for arg in self.args)
  99. def gen_block(self, format: str) -> str:
  100. return '\n'.join(format.format_map(arg.__dict__) for arg in self.args)
  101. # Match wrappers declared with a co_wrapper mark
  102. func_decl_re = re.compile(r'^(?P<return_type>[a-zA-Z][a-zA-Z0-9_]* [\*]?)'
  103. r'(\s*coroutine_fn)?'
  104. r'\s*(?P<wrapper_type>(no_)?co)_wrapper'
  105. r'(?P<variant>(_[a-z][a-z0-9_]*)?)\s*'
  106. r'(?P<wrapper_name>[a-z][a-z0-9_]*)'
  107. r'\((?P<args>[^)]*)\);$', re.MULTILINE)
  108. def func_decl_iter(text: str) -> Iterator:
  109. for m in func_decl_re.finditer(text):
  110. yield FuncDecl(wrapper_type=m.group('wrapper_type'),
  111. return_type=m.group('return_type'),
  112. name=m.group('wrapper_name'),
  113. args=m.group('args'),
  114. variant=m.group('variant'))
  115. def snake_to_camel(func_name: str) -> str:
  116. """
  117. Convert underscore names like 'some_function_name' to camel-case like
  118. 'SomeFunctionName'
  119. """
  120. words = func_name.split('_')
  121. words = [w[0].upper() + w[1:] for w in words]
  122. return ''.join(words)
  123. def create_mixed_wrapper(func: FuncDecl) -> str:
  124. """
  125. Checks if we are already in coroutine
  126. """
  127. name = func.target_name
  128. struct_name = func.struct_name
  129. graph_assume_lock = 'assume_graph_lock();' if func.graph_rdlock else ''
  130. return f"""\
  131. {func.return_type} {func.name}({ func.gen_list('{decl}') })
  132. {{
  133. if (qemu_in_coroutine()) {{
  134. {graph_assume_lock}
  135. {func.co_ret}{name}({ func.gen_list('{name}') });
  136. }} else {{
  137. {struct_name} s = {{
  138. .poll_state.ctx = {func.ctx},
  139. .poll_state.in_progress = true,
  140. { func.gen_block(' .{name} = {name},') }
  141. }};
  142. s.poll_state.co = qemu_coroutine_create({name}_entry, &s);
  143. bdrv_poll_co(&s.poll_state);
  144. {func.ret}
  145. }}
  146. }}"""
  147. def create_co_wrapper(func: FuncDecl) -> str:
  148. """
  149. Assumes we are not in coroutine, and creates one
  150. """
  151. name = func.target_name
  152. struct_name = func.struct_name
  153. return f"""\
  154. {func.return_type} {func.name}({ func.gen_list('{decl}') })
  155. {{
  156. {struct_name} s = {{
  157. .poll_state.ctx = {func.ctx},
  158. .poll_state.in_progress = true,
  159. { func.gen_block(' .{name} = {name},') }
  160. }};
  161. assert(!qemu_in_coroutine());
  162. s.poll_state.co = qemu_coroutine_create({name}_entry, &s);
  163. bdrv_poll_co(&s.poll_state);
  164. {func.ret}
  165. }}"""
  166. def gen_co_wrapper(func: FuncDecl) -> str:
  167. assert not '_co_' in func.name
  168. assert func.wrapper_type == 'co'
  169. name = func.target_name
  170. struct_name = func.struct_name
  171. graph_lock=''
  172. graph_unlock=''
  173. if func.graph_rdlock:
  174. graph_lock=' bdrv_graph_co_rdlock();'
  175. graph_unlock=' bdrv_graph_co_rdunlock();'
  176. creation_function = create_mixed_wrapper
  177. if func.create_only_co:
  178. creation_function = create_co_wrapper
  179. return f"""\
  180. /*
  181. * Wrappers for {name}
  182. */
  183. typedef struct {struct_name} {{
  184. BdrvPollCo poll_state;
  185. {func.return_field}
  186. { func.gen_block(' {decl};') }
  187. }} {struct_name};
  188. static void coroutine_fn {name}_entry(void *opaque)
  189. {{
  190. {struct_name} *s = opaque;
  191. {graph_lock}
  192. {func.get_result}{name}({ func.gen_list('s->{name}') });
  193. {graph_unlock}
  194. s->poll_state.in_progress = false;
  195. aio_wait_kick();
  196. }}
  197. {creation_function(func)}"""
  198. def gen_no_co_wrapper(func: FuncDecl) -> str:
  199. assert '_co_' in func.name
  200. assert func.wrapper_type == 'no_co'
  201. name = func.target_name
  202. struct_name = func.struct_name
  203. graph_lock=''
  204. graph_unlock=''
  205. if func.graph_wrlock:
  206. graph_lock=' bdrv_graph_wrlock(NULL);'
  207. graph_unlock=' bdrv_graph_wrunlock();'
  208. return f"""\
  209. /*
  210. * Wrappers for {name}
  211. */
  212. typedef struct {struct_name} {{
  213. Coroutine *co;
  214. {func.return_field}
  215. { func.gen_block(' {decl};') }
  216. }} {struct_name};
  217. static void {name}_bh(void *opaque)
  218. {{
  219. {struct_name} *s = opaque;
  220. AioContext *ctx = {func.gen_ctx('s->')};
  221. {graph_lock}
  222. aio_context_acquire(ctx);
  223. {func.get_result}{name}({ func.gen_list('s->{name}') });
  224. aio_context_release(ctx);
  225. {graph_unlock}
  226. aio_co_wake(s->co);
  227. }}
  228. {func.return_type} coroutine_fn {func.name}({ func.gen_list('{decl}') })
  229. {{
  230. {struct_name} s = {{
  231. .co = qemu_coroutine_self(),
  232. { func.gen_block(' .{name} = {name},') }
  233. }};
  234. assert(qemu_in_coroutine());
  235. aio_bh_schedule_oneshot(qemu_get_aio_context(), {name}_bh, &s);
  236. qemu_coroutine_yield();
  237. {func.ret}
  238. }}"""
  239. def gen_wrappers(input_code: str) -> str:
  240. res = ''
  241. for func in func_decl_iter(input_code):
  242. res += '\n\n\n'
  243. if func.wrapper_type == 'co':
  244. res += gen_co_wrapper(func)
  245. else:
  246. res += gen_no_co_wrapper(func)
  247. return res
  248. if __name__ == '__main__':
  249. if len(sys.argv) < 3:
  250. exit(f'Usage: {sys.argv[0]} OUT_FILE.c IN_FILE.[ch]...')
  251. with open(sys.argv[1], 'w', encoding='utf-8') as f_out:
  252. f_out.write(gen_header())
  253. for fname in sys.argv[2:]:
  254. with open(fname, encoding='utf-8') as f_in:
  255. f_out.write(gen_wrappers(f_in.read()))
  256. f_out.write('\n')