block-coroutine-wrapper.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  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. """
  37. class ParamDecl:
  38. param_re = re.compile(r'(?P<decl>'
  39. r'(?P<type>.*[ *])'
  40. r'(?P<name>[a-z][a-z0-9_]*)'
  41. r')')
  42. def __init__(self, param_decl: str) -> None:
  43. m = self.param_re.match(param_decl.strip())
  44. if m is None:
  45. raise ValueError(f'Wrong parameter declaration: "{param_decl}"')
  46. self.decl = m.group('decl')
  47. self.type = m.group('type')
  48. self.name = m.group('name')
  49. class FuncDecl:
  50. def __init__(self, return_type: str, name: str, args: str,
  51. variant: str) -> None:
  52. self.return_type = return_type.strip()
  53. self.name = name.strip()
  54. self.struct_name = snake_to_camel(self.name)
  55. self.args = [ParamDecl(arg.strip()) for arg in args.split(',')]
  56. self.create_only_co = 'mixed' not in variant
  57. subsystem, subname = self.name.split('_', 1)
  58. self.co_name = f'{subsystem}_co_{subname}'
  59. t = self.args[0].type
  60. if t == 'BlockDriverState *':
  61. ctx = 'bdrv_get_aio_context(bs)'
  62. elif t == 'BdrvChild *':
  63. ctx = 'bdrv_get_aio_context(child->bs)'
  64. elif t == 'BlockBackend *':
  65. ctx = 'blk_get_aio_context(blk)'
  66. else:
  67. ctx = 'qemu_get_aio_context()'
  68. self.ctx = ctx
  69. def gen_list(self, format: str) -> str:
  70. return ', '.join(format.format_map(arg.__dict__) for arg in self.args)
  71. def gen_block(self, format: str) -> str:
  72. return '\n'.join(format.format_map(arg.__dict__) for arg in self.args)
  73. # Match wrappers declared with a co_wrapper mark
  74. func_decl_re = re.compile(r'^int\s*co_wrapper'
  75. r'(?P<variant>(_[a-z][a-z0-9_]*)?)\s*'
  76. r'(?P<wrapper_name>[a-z][a-z0-9_]*)'
  77. r'\((?P<args>[^)]*)\);$', re.MULTILINE)
  78. def func_decl_iter(text: str) -> Iterator:
  79. for m in func_decl_re.finditer(text):
  80. yield FuncDecl(return_type='int',
  81. name=m.group('wrapper_name'),
  82. args=m.group('args'),
  83. variant=m.group('variant'))
  84. def snake_to_camel(func_name: str) -> str:
  85. """
  86. Convert underscore names like 'some_function_name' to camel-case like
  87. 'SomeFunctionName'
  88. """
  89. words = func_name.split('_')
  90. words = [w[0].upper() + w[1:] for w in words]
  91. return ''.join(words)
  92. def create_mixed_wrapper(func: FuncDecl) -> str:
  93. """
  94. Checks if we are already in coroutine
  95. """
  96. name = func.co_name
  97. struct_name = func.struct_name
  98. return f"""\
  99. int {func.name}({ func.gen_list('{decl}') })
  100. {{
  101. if (qemu_in_coroutine()) {{
  102. return {name}({ func.gen_list('{name}') });
  103. }} else {{
  104. {struct_name} s = {{
  105. .poll_state.ctx = {func.ctx},
  106. .poll_state.in_progress = true,
  107. { func.gen_block(' .{name} = {name},') }
  108. }};
  109. s.poll_state.co = qemu_coroutine_create({name}_entry, &s);
  110. return bdrv_poll_co(&s.poll_state);
  111. }}
  112. }}"""
  113. def create_co_wrapper(func: FuncDecl) -> str:
  114. """
  115. Assumes we are not in coroutine, and creates one
  116. """
  117. name = func.co_name
  118. struct_name = func.struct_name
  119. return f"""\
  120. int {func.name}({ func.gen_list('{decl}') })
  121. {{
  122. {struct_name} s = {{
  123. .poll_state.ctx = {func.ctx},
  124. .poll_state.in_progress = true,
  125. { func.gen_block(' .{name} = {name},') }
  126. }};
  127. assert(!qemu_in_coroutine());
  128. s.poll_state.co = qemu_coroutine_create({name}_entry, &s);
  129. return bdrv_poll_co(&s.poll_state);
  130. }}"""
  131. def gen_wrapper(func: FuncDecl) -> str:
  132. assert not '_co_' in func.name
  133. assert func.return_type == 'int'
  134. name = func.co_name
  135. struct_name = func.struct_name
  136. creation_function = create_mixed_wrapper
  137. if func.create_only_co:
  138. creation_function = create_co_wrapper
  139. return f"""\
  140. /*
  141. * Wrappers for {name}
  142. */
  143. typedef struct {struct_name} {{
  144. BdrvPollCo poll_state;
  145. { func.gen_block(' {decl};') }
  146. }} {struct_name};
  147. static void coroutine_fn {name}_entry(void *opaque)
  148. {{
  149. {struct_name} *s = opaque;
  150. s->poll_state.ret = {name}({ func.gen_list('s->{name}') });
  151. s->poll_state.in_progress = false;
  152. aio_wait_kick();
  153. }}
  154. {creation_function(func)}"""
  155. def gen_wrappers(input_code: str) -> str:
  156. res = ''
  157. for func in func_decl_iter(input_code):
  158. res += '\n\n\n'
  159. res += gen_wrapper(func)
  160. return res
  161. if __name__ == '__main__':
  162. if len(sys.argv) < 3:
  163. exit(f'Usage: {sys.argv[0]} OUT_FILE.c IN_FILE.[ch]...')
  164. with open(sys.argv[1], 'w', encoding='utf-8') as f_out:
  165. f_out.write(gen_header())
  166. for fname in sys.argv[2:]:
  167. with open(fname, encoding='utf-8') as f_in:
  168. f_out.write(gen_wrappers(f_in.read()))
  169. f_out.write('\n')