block-coroutine-wrapper.py 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  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 and self.graph_wrlock:
  74. raise ValueError("function can't be both rdlock and wrlock: "
  75. f"{self.name}")
  76. self.target_name = f'{subsystem}_{subname}'
  77. self.ctx = self.gen_ctx()
  78. self.get_result = 's->ret = '
  79. self.ret = 'return s.ret;'
  80. self.co_ret = 'return '
  81. self.return_field = self.return_type + " ret;"
  82. if self.return_type == 'void':
  83. self.get_result = ''
  84. self.ret = ''
  85. self.co_ret = ''
  86. self.return_field = ''
  87. def gen_ctx(self, prefix: str = '') -> str:
  88. t = self.args[0].type
  89. name = self.args[0].name
  90. if t == 'BlockDriverState *':
  91. return f'bdrv_get_aio_context({prefix}{name})'
  92. elif t == 'BdrvChild *':
  93. return f'bdrv_get_aio_context({prefix}{name}->bs)'
  94. elif t == 'BlockBackend *':
  95. return f'blk_get_aio_context({prefix}{name})'
  96. else:
  97. return 'qemu_get_aio_context()'
  98. def gen_list(self, format: str) -> str:
  99. return ', '.join(format.format_map(arg.__dict__) for arg in self.args)
  100. def gen_block(self, format: str) -> str:
  101. return '\n'.join(format.format_map(arg.__dict__) for arg in self.args)
  102. # Match wrappers declared with a co_wrapper mark
  103. func_decl_re = re.compile(r'^(?P<return_type>[a-zA-Z][a-zA-Z0-9_]* [\*]?)'
  104. r'(\s*coroutine_fn)?'
  105. r'\s*(?P<wrapper_type>(no_)?co)_wrapper'
  106. r'(?P<variant>(_[a-z][a-z0-9_]*)?)\s*'
  107. r'(?P<wrapper_name>[a-z][a-z0-9_]*)'
  108. r'\((?P<args>[^)]*)\);$', re.MULTILINE)
  109. def func_decl_iter(text: str) -> Iterator:
  110. for m in func_decl_re.finditer(text):
  111. yield FuncDecl(wrapper_type=m.group('wrapper_type'),
  112. return_type=m.group('return_type'),
  113. name=m.group('wrapper_name'),
  114. args=m.group('args'),
  115. variant=m.group('variant'))
  116. def snake_to_camel(func_name: str) -> str:
  117. """
  118. Convert underscore names like 'some_function_name' to camel-case like
  119. 'SomeFunctionName'
  120. """
  121. words = func_name.split('_')
  122. words = [w[0].upper() + w[1:] for w in words]
  123. return ''.join(words)
  124. def create_mixed_wrapper(func: FuncDecl) -> str:
  125. """
  126. Checks if we are already in coroutine
  127. """
  128. name = func.target_name
  129. struct_name = func.struct_name
  130. graph_assume_lock = 'assume_graph_lock();' if func.graph_rdlock else ''
  131. return f"""\
  132. {func.return_type} {func.name}({ func.gen_list('{decl}') })
  133. {{
  134. if (qemu_in_coroutine()) {{
  135. {graph_assume_lock}
  136. {func.co_ret}{name}({ func.gen_list('{name}') });
  137. }} else {{
  138. {struct_name} s = {{
  139. .poll_state.ctx = {func.ctx},
  140. .poll_state.in_progress = true,
  141. { func.gen_block(' .{name} = {name},') }
  142. }};
  143. s.poll_state.co = qemu_coroutine_create({name}_entry, &s);
  144. bdrv_poll_co(&s.poll_state);
  145. {func.ret}
  146. }}
  147. }}"""
  148. def create_co_wrapper(func: FuncDecl) -> str:
  149. """
  150. Assumes we are not in coroutine, and creates one
  151. """
  152. name = func.target_name
  153. struct_name = func.struct_name
  154. return f"""\
  155. {func.return_type} {func.name}({ func.gen_list('{decl}') })
  156. {{
  157. {struct_name} s = {{
  158. .poll_state.ctx = {func.ctx},
  159. .poll_state.in_progress = true,
  160. { func.gen_block(' .{name} = {name},') }
  161. }};
  162. assert(!qemu_in_coroutine());
  163. s.poll_state.co = qemu_coroutine_create({name}_entry, &s);
  164. bdrv_poll_co(&s.poll_state);
  165. {func.ret}
  166. }}"""
  167. def gen_co_wrapper(func: FuncDecl) -> str:
  168. assert not '_co_' in func.name
  169. assert func.wrapper_type == 'co'
  170. name = func.target_name
  171. struct_name = func.struct_name
  172. graph_lock=''
  173. graph_unlock=''
  174. if func.graph_rdlock:
  175. graph_lock=' bdrv_graph_co_rdlock();'
  176. graph_unlock=' bdrv_graph_co_rdunlock();'
  177. creation_function = create_mixed_wrapper
  178. if func.create_only_co:
  179. creation_function = create_co_wrapper
  180. return f"""\
  181. /*
  182. * Wrappers for {name}
  183. */
  184. typedef struct {struct_name} {{
  185. BdrvPollCo poll_state;
  186. {func.return_field}
  187. { func.gen_block(' {decl};') }
  188. }} {struct_name};
  189. static void coroutine_fn {name}_entry(void *opaque)
  190. {{
  191. {struct_name} *s = opaque;
  192. {graph_lock}
  193. {func.get_result}{name}({ func.gen_list('s->{name}') });
  194. {graph_unlock}
  195. s->poll_state.in_progress = false;
  196. aio_wait_kick();
  197. }}
  198. {creation_function(func)}"""
  199. def gen_no_co_wrapper(func: FuncDecl) -> str:
  200. assert '_co_' in func.name
  201. assert func.wrapper_type == 'no_co'
  202. name = func.target_name
  203. struct_name = func.struct_name
  204. graph_lock=''
  205. graph_unlock=''
  206. if func.graph_rdlock:
  207. graph_lock=' bdrv_graph_rdlock_main_loop();'
  208. graph_unlock=' bdrv_graph_rdunlock_main_loop();'
  209. elif func.graph_wrlock:
  210. graph_lock=' bdrv_graph_wrlock();'
  211. graph_unlock=' bdrv_graph_wrunlock();'
  212. return f"""\
  213. /*
  214. * Wrappers for {name}
  215. */
  216. typedef struct {struct_name} {{
  217. Coroutine *co;
  218. {func.return_field}
  219. { func.gen_block(' {decl};') }
  220. }} {struct_name};
  221. static void {name}_bh(void *opaque)
  222. {{
  223. {struct_name} *s = opaque;
  224. {graph_lock}
  225. {func.get_result}{name}({ func.gen_list('s->{name}') });
  226. {graph_unlock}
  227. aio_co_wake(s->co);
  228. }}
  229. {func.return_type} coroutine_fn {func.name}({ func.gen_list('{decl}') })
  230. {{
  231. {struct_name} s = {{
  232. .co = qemu_coroutine_self(),
  233. { func.gen_block(' .{name} = {name},') }
  234. }};
  235. assert(qemu_in_coroutine());
  236. aio_bh_schedule_oneshot(qemu_get_aio_context(), {name}_bh, &s);
  237. qemu_coroutine_yield();
  238. {func.ret}
  239. }}"""
  240. def gen_wrappers(input_code: str) -> str:
  241. res = ''
  242. for func in func_decl_iter(input_code):
  243. res += '\n\n\n'
  244. if func.wrapper_type == 'co':
  245. res += gen_co_wrapper(func)
  246. else:
  247. res += gen_no_co_wrapper(func)
  248. return res
  249. if __name__ == '__main__':
  250. if len(sys.argv) < 3:
  251. exit(f'Usage: {sys.argv[0]} OUT_FILE.c IN_FILE.[ch]...')
  252. with open(sys.argv[1], 'w', encoding='utf-8') as f_out:
  253. f_out.write(gen_header())
  254. for fname in sys.argv[2:]:
  255. with open(fname, encoding='utf-8') as f_in:
  256. f_out.write(gen_wrappers(f_in.read()))
  257. f_out.write('\n')