qemu-io-cmds.c 65 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520
  1. /*
  2. * Command line utility to exercise the QEMU I/O path.
  3. *
  4. * Copyright (C) 2009-2016 Red Hat, Inc.
  5. * Copyright (c) 2003-2005 Silicon Graphics, Inc.
  6. *
  7. * This work is licensed under the terms of the GNU GPL, version 2 or later.
  8. * See the COPYING file in the top-level directory.
  9. */
  10. #include "qemu/osdep.h"
  11. #include "qapi/error.h"
  12. #include "qapi/qmp/qdict.h"
  13. #include "qemu-io.h"
  14. #include "sysemu/block-backend.h"
  15. #include "block/block.h"
  16. #include "block/block_int.h" /* for info_f() */
  17. #include "block/qapi.h"
  18. #include "qemu/error-report.h"
  19. #include "qemu/main-loop.h"
  20. #include "qemu/option.h"
  21. #include "qemu/timer.h"
  22. #include "qemu/cutils.h"
  23. #define CMD_NOFILE_OK 0x01
  24. bool qemuio_misalign;
  25. static cmdinfo_t *cmdtab;
  26. static int ncmds;
  27. static int compare_cmdname(const void *a, const void *b)
  28. {
  29. return strcmp(((const cmdinfo_t *)a)->name,
  30. ((const cmdinfo_t *)b)->name);
  31. }
  32. void qemuio_add_command(const cmdinfo_t *ci)
  33. {
  34. /* ci->perm assumes a file is open, but the GLOBAL and NOFILE_OK
  35. * flags allow it not to be, so that combination is invalid.
  36. * Catch it now rather than letting it manifest as a crash if a
  37. * particular set of command line options are used.
  38. */
  39. assert(ci->perm == 0 ||
  40. (ci->flags & (CMD_FLAG_GLOBAL | CMD_NOFILE_OK)) == 0);
  41. cmdtab = g_renew(cmdinfo_t, cmdtab, ++ncmds);
  42. cmdtab[ncmds - 1] = *ci;
  43. qsort(cmdtab, ncmds, sizeof(*cmdtab), compare_cmdname);
  44. }
  45. void qemuio_command_usage(const cmdinfo_t *ci)
  46. {
  47. printf("%s %s -- %s\n", ci->name, ci->args, ci->oneline);
  48. }
  49. static int init_check_command(BlockBackend *blk, const cmdinfo_t *ct)
  50. {
  51. if (ct->flags & CMD_FLAG_GLOBAL) {
  52. return 1;
  53. }
  54. if (!(ct->flags & CMD_NOFILE_OK) && !blk) {
  55. fprintf(stderr, "no file open, try 'help open'\n");
  56. return 0;
  57. }
  58. return 1;
  59. }
  60. static int command(BlockBackend *blk, const cmdinfo_t *ct, int argc,
  61. char **argv)
  62. {
  63. char *cmd = argv[0];
  64. if (!init_check_command(blk, ct)) {
  65. return -EINVAL;
  66. }
  67. if (argc - 1 < ct->argmin || (ct->argmax != -1 && argc - 1 > ct->argmax)) {
  68. if (ct->argmax == -1) {
  69. fprintf(stderr,
  70. "bad argument count %d to %s, expected at least %d arguments\n",
  71. argc-1, cmd, ct->argmin);
  72. } else if (ct->argmin == ct->argmax) {
  73. fprintf(stderr,
  74. "bad argument count %d to %s, expected %d arguments\n",
  75. argc-1, cmd, ct->argmin);
  76. } else {
  77. fprintf(stderr,
  78. "bad argument count %d to %s, expected between %d and %d arguments\n",
  79. argc-1, cmd, ct->argmin, ct->argmax);
  80. }
  81. return -EINVAL;
  82. }
  83. /*
  84. * Request additional permissions if necessary for this command. The caller
  85. * is responsible for restoring the original permissions afterwards if this
  86. * is what it wants.
  87. *
  88. * Coverity thinks that blk may be NULL in the following if condition. It's
  89. * not so: in init_check_command() we fail if blk is NULL for command with
  90. * both CMD_FLAG_GLOBAL and CMD_NOFILE_OK flags unset. And in
  91. * qemuio_add_command() we assert that command with non-zero .perm field
  92. * doesn't set this flags. So, the following assertion is to silence
  93. * Coverity:
  94. */
  95. assert(blk || !ct->perm);
  96. if (ct->perm && blk_is_available(blk)) {
  97. uint64_t orig_perm, orig_shared_perm;
  98. blk_get_perm(blk, &orig_perm, &orig_shared_perm);
  99. if (ct->perm & ~orig_perm) {
  100. uint64_t new_perm;
  101. Error *local_err = NULL;
  102. int ret;
  103. new_perm = orig_perm | ct->perm;
  104. ret = blk_set_perm(blk, new_perm, orig_shared_perm, &local_err);
  105. if (ret < 0) {
  106. error_report_err(local_err);
  107. return ret;
  108. }
  109. }
  110. }
  111. qemu_reset_optind();
  112. return ct->cfunc(blk, argc, argv);
  113. }
  114. static const cmdinfo_t *find_command(const char *cmd)
  115. {
  116. cmdinfo_t *ct;
  117. for (ct = cmdtab; ct < &cmdtab[ncmds]; ct++) {
  118. if (strcmp(ct->name, cmd) == 0 ||
  119. (ct->altname && strcmp(ct->altname, cmd) == 0))
  120. {
  121. return (const cmdinfo_t *)ct;
  122. }
  123. }
  124. return NULL;
  125. }
  126. /* Invoke fn() for commands with a matching prefix */
  127. void qemuio_complete_command(const char *input,
  128. void (*fn)(const char *cmd, void *opaque),
  129. void *opaque)
  130. {
  131. cmdinfo_t *ct;
  132. size_t input_len = strlen(input);
  133. for (ct = cmdtab; ct < &cmdtab[ncmds]; ct++) {
  134. if (strncmp(input, ct->name, input_len) == 0) {
  135. fn(ct->name, opaque);
  136. }
  137. }
  138. }
  139. static char **breakline(char *input, int *count)
  140. {
  141. int c = 0;
  142. char *p;
  143. char **rval = g_new0(char *, 1);
  144. while (rval && (p = qemu_strsep(&input, " ")) != NULL) {
  145. if (!*p) {
  146. continue;
  147. }
  148. c++;
  149. rval = g_renew(char *, rval, (c + 1));
  150. rval[c - 1] = p;
  151. rval[c] = NULL;
  152. }
  153. *count = c;
  154. return rval;
  155. }
  156. static int64_t cvtnum(const char *s)
  157. {
  158. int err;
  159. uint64_t value;
  160. err = qemu_strtosz(s, NULL, &value);
  161. if (err < 0) {
  162. return err;
  163. }
  164. if (value > INT64_MAX) {
  165. return -ERANGE;
  166. }
  167. return value;
  168. }
  169. static void print_cvtnum_err(int64_t rc, const char *arg)
  170. {
  171. switch (rc) {
  172. case -EINVAL:
  173. printf("Parsing error: non-numeric argument,"
  174. " or extraneous/unrecognized suffix -- %s\n", arg);
  175. break;
  176. case -ERANGE:
  177. printf("Parsing error: argument too large -- %s\n", arg);
  178. break;
  179. default:
  180. printf("Parsing error: %s\n", arg);
  181. }
  182. }
  183. #define EXABYTES(x) ((long long)(x) << 60)
  184. #define PETABYTES(x) ((long long)(x) << 50)
  185. #define TERABYTES(x) ((long long)(x) << 40)
  186. #define GIGABYTES(x) ((long long)(x) << 30)
  187. #define MEGABYTES(x) ((long long)(x) << 20)
  188. #define KILOBYTES(x) ((long long)(x) << 10)
  189. #define TO_EXABYTES(x) ((x) / EXABYTES(1))
  190. #define TO_PETABYTES(x) ((x) / PETABYTES(1))
  191. #define TO_TERABYTES(x) ((x) / TERABYTES(1))
  192. #define TO_GIGABYTES(x) ((x) / GIGABYTES(1))
  193. #define TO_MEGABYTES(x) ((x) / MEGABYTES(1))
  194. #define TO_KILOBYTES(x) ((x) / KILOBYTES(1))
  195. static void cvtstr(double value, char *str, size_t size)
  196. {
  197. char *trim;
  198. const char *suffix;
  199. if (value >= EXABYTES(1)) {
  200. suffix = " EiB";
  201. snprintf(str, size - 4, "%.3f", TO_EXABYTES(value));
  202. } else if (value >= PETABYTES(1)) {
  203. suffix = " PiB";
  204. snprintf(str, size - 4, "%.3f", TO_PETABYTES(value));
  205. } else if (value >= TERABYTES(1)) {
  206. suffix = " TiB";
  207. snprintf(str, size - 4, "%.3f", TO_TERABYTES(value));
  208. } else if (value >= GIGABYTES(1)) {
  209. suffix = " GiB";
  210. snprintf(str, size - 4, "%.3f", TO_GIGABYTES(value));
  211. } else if (value >= MEGABYTES(1)) {
  212. suffix = " MiB";
  213. snprintf(str, size - 4, "%.3f", TO_MEGABYTES(value));
  214. } else if (value >= KILOBYTES(1)) {
  215. suffix = " KiB";
  216. snprintf(str, size - 4, "%.3f", TO_KILOBYTES(value));
  217. } else {
  218. suffix = " bytes";
  219. snprintf(str, size - 6, "%f", value);
  220. }
  221. trim = strstr(str, ".000");
  222. if (trim) {
  223. strcpy(trim, suffix);
  224. } else {
  225. strcat(str, suffix);
  226. }
  227. }
  228. static struct timespec tsub(struct timespec t1, struct timespec t2)
  229. {
  230. t1.tv_nsec -= t2.tv_nsec;
  231. if (t1.tv_nsec < 0) {
  232. t1.tv_nsec += NANOSECONDS_PER_SECOND;
  233. t1.tv_sec--;
  234. }
  235. t1.tv_sec -= t2.tv_sec;
  236. return t1;
  237. }
  238. static double tdiv(double value, struct timespec tv)
  239. {
  240. double seconds = tv.tv_sec + (tv.tv_nsec / 1e9);
  241. return value / seconds;
  242. }
  243. #define HOURS(sec) ((sec) / (60 * 60))
  244. #define MINUTES(sec) (((sec) % (60 * 60)) / 60)
  245. #define SECONDS(sec) ((sec) % 60)
  246. enum {
  247. DEFAULT_TIME = 0x0,
  248. TERSE_FIXED_TIME = 0x1,
  249. VERBOSE_FIXED_TIME = 0x2,
  250. };
  251. static void timestr(struct timespec *tv, char *ts, size_t size, int format)
  252. {
  253. double frac_sec = tv->tv_nsec / 1e9;
  254. if (format & TERSE_FIXED_TIME) {
  255. if (!HOURS(tv->tv_sec)) {
  256. snprintf(ts, size, "%u:%05.2f",
  257. (unsigned int) MINUTES(tv->tv_sec),
  258. SECONDS(tv->tv_sec) + frac_sec);
  259. return;
  260. }
  261. format |= VERBOSE_FIXED_TIME; /* fallback if hours needed */
  262. }
  263. if ((format & VERBOSE_FIXED_TIME) || tv->tv_sec) {
  264. snprintf(ts, size, "%u:%02u:%05.2f",
  265. (unsigned int) HOURS(tv->tv_sec),
  266. (unsigned int) MINUTES(tv->tv_sec),
  267. SECONDS(tv->tv_sec) + frac_sec);
  268. } else {
  269. snprintf(ts, size, "%05.2f sec", frac_sec);
  270. }
  271. }
  272. /*
  273. * Parse the pattern argument to various sub-commands.
  274. *
  275. * Because the pattern is used as an argument to memset it must evaluate
  276. * to an unsigned integer that fits into a single byte.
  277. */
  278. static int parse_pattern(const char *arg)
  279. {
  280. char *endptr = NULL;
  281. long pattern;
  282. pattern = strtol(arg, &endptr, 0);
  283. if (pattern < 0 || pattern > UCHAR_MAX || *endptr != '\0') {
  284. printf("%s is not a valid pattern byte\n", arg);
  285. return -1;
  286. }
  287. return pattern;
  288. }
  289. /*
  290. * Memory allocation helpers.
  291. *
  292. * Make sure memory is aligned by default, or purposefully misaligned if
  293. * that is specified on the command line.
  294. */
  295. #define MISALIGN_OFFSET 16
  296. static void *qemu_io_alloc(BlockBackend *blk, size_t len, int pattern)
  297. {
  298. void *buf;
  299. if (qemuio_misalign) {
  300. len += MISALIGN_OFFSET;
  301. }
  302. buf = blk_blockalign(blk, len);
  303. memset(buf, pattern, len);
  304. if (qemuio_misalign) {
  305. buf += MISALIGN_OFFSET;
  306. }
  307. return buf;
  308. }
  309. static void qemu_io_free(void *p)
  310. {
  311. if (qemuio_misalign) {
  312. p -= MISALIGN_OFFSET;
  313. }
  314. qemu_vfree(p);
  315. }
  316. /*
  317. * qemu_io_alloc_from_file()
  318. *
  319. * Allocates the buffer and populates it with the content of the given file
  320. * up to @len bytes. If the file length is less than @len, then the buffer
  321. * is populated with the file content cyclically.
  322. *
  323. * @blk - the block backend where the buffer content is going to be written to
  324. * @len - the buffer length
  325. * @file_name - the file to read the content from
  326. *
  327. * Returns: the buffer pointer on success
  328. * NULL on error
  329. */
  330. static void *qemu_io_alloc_from_file(BlockBackend *blk, size_t len,
  331. const char *file_name)
  332. {
  333. char *buf, *buf_origin;
  334. FILE *f = fopen(file_name, "r");
  335. int pattern_len;
  336. if (!f) {
  337. perror(file_name);
  338. return NULL;
  339. }
  340. if (qemuio_misalign) {
  341. len += MISALIGN_OFFSET;
  342. }
  343. buf_origin = buf = blk_blockalign(blk, len);
  344. if (qemuio_misalign) {
  345. buf_origin += MISALIGN_OFFSET;
  346. buf += MISALIGN_OFFSET;
  347. len -= MISALIGN_OFFSET;
  348. }
  349. pattern_len = fread(buf_origin, 1, len, f);
  350. if (ferror(f)) {
  351. perror(file_name);
  352. goto error;
  353. }
  354. if (pattern_len == 0) {
  355. fprintf(stderr, "%s: file is empty\n", file_name);
  356. goto error;
  357. }
  358. fclose(f);
  359. f = NULL;
  360. if (len > pattern_len) {
  361. len -= pattern_len;
  362. buf += pattern_len;
  363. while (len > 0) {
  364. size_t len_to_copy = MIN(pattern_len, len);
  365. memcpy(buf, buf_origin, len_to_copy);
  366. len -= len_to_copy;
  367. buf += len_to_copy;
  368. }
  369. }
  370. return buf_origin;
  371. error:
  372. qemu_io_free(buf_origin);
  373. if (f) {
  374. fclose(f);
  375. }
  376. return NULL;
  377. }
  378. static void dump_buffer(const void *buffer, int64_t offset, int64_t len)
  379. {
  380. uint64_t i;
  381. int j;
  382. const uint8_t *p;
  383. for (i = 0, p = buffer; i < len; i += 16) {
  384. const uint8_t *s = p;
  385. printf("%08" PRIx64 ": ", offset + i);
  386. for (j = 0; j < 16 && i + j < len; j++, p++) {
  387. printf("%02x ", *p);
  388. }
  389. printf(" ");
  390. for (j = 0; j < 16 && i + j < len; j++, s++) {
  391. if (isalnum(*s)) {
  392. printf("%c", *s);
  393. } else {
  394. printf(".");
  395. }
  396. }
  397. printf("\n");
  398. }
  399. }
  400. static void print_report(const char *op, struct timespec *t, int64_t offset,
  401. int64_t count, int64_t total, int cnt, bool Cflag)
  402. {
  403. char s1[64], s2[64], ts[64];
  404. timestr(t, ts, sizeof(ts), Cflag ? VERBOSE_FIXED_TIME : 0);
  405. if (!Cflag) {
  406. cvtstr((double)total, s1, sizeof(s1));
  407. cvtstr(tdiv((double)total, *t), s2, sizeof(s2));
  408. printf("%s %"PRId64"/%"PRId64" bytes at offset %" PRId64 "\n",
  409. op, total, count, offset);
  410. printf("%s, %d ops; %s (%s/sec and %.4f ops/sec)\n",
  411. s1, cnt, ts, s2, tdiv((double)cnt, *t));
  412. } else {/* bytes,ops,time,bytes/sec,ops/sec */
  413. printf("%"PRId64",%d,%s,%.3f,%.3f\n",
  414. total, cnt, ts,
  415. tdiv((double)total, *t),
  416. tdiv((double)cnt, *t));
  417. }
  418. }
  419. /*
  420. * Parse multiple length statements for vectored I/O, and construct an I/O
  421. * vector matching it.
  422. */
  423. static void *
  424. create_iovec(BlockBackend *blk, QEMUIOVector *qiov, char **argv, int nr_iov,
  425. int pattern)
  426. {
  427. size_t *sizes = g_new0(size_t, nr_iov);
  428. size_t count = 0;
  429. void *buf = NULL;
  430. void *p;
  431. int i;
  432. for (i = 0; i < nr_iov; i++) {
  433. char *arg = argv[i];
  434. int64_t len;
  435. len = cvtnum(arg);
  436. if (len < 0) {
  437. print_cvtnum_err(len, arg);
  438. goto fail;
  439. }
  440. if (len > BDRV_REQUEST_MAX_BYTES) {
  441. printf("Argument '%s' exceeds maximum size %" PRIu64 "\n", arg,
  442. (uint64_t)BDRV_REQUEST_MAX_BYTES);
  443. goto fail;
  444. }
  445. if (count > BDRV_REQUEST_MAX_BYTES - len) {
  446. printf("The total number of bytes exceed the maximum size %" PRIu64
  447. "\n", (uint64_t)BDRV_REQUEST_MAX_BYTES);
  448. goto fail;
  449. }
  450. sizes[i] = len;
  451. count += len;
  452. }
  453. qemu_iovec_init(qiov, nr_iov);
  454. buf = p = qemu_io_alloc(blk, count, pattern);
  455. for (i = 0; i < nr_iov; i++) {
  456. qemu_iovec_add(qiov, p, sizes[i]);
  457. p += sizes[i];
  458. }
  459. fail:
  460. g_free(sizes);
  461. return buf;
  462. }
  463. static int do_pread(BlockBackend *blk, char *buf, int64_t offset,
  464. int64_t bytes, int64_t *total)
  465. {
  466. if (bytes > INT_MAX) {
  467. return -ERANGE;
  468. }
  469. *total = blk_pread(blk, offset, (uint8_t *)buf, bytes);
  470. if (*total < 0) {
  471. return *total;
  472. }
  473. return 1;
  474. }
  475. static int do_pwrite(BlockBackend *blk, char *buf, int64_t offset,
  476. int64_t bytes, int flags, int64_t *total)
  477. {
  478. if (bytes > INT_MAX) {
  479. return -ERANGE;
  480. }
  481. *total = blk_pwrite(blk, offset, (uint8_t *)buf, bytes, flags);
  482. if (*total < 0) {
  483. return *total;
  484. }
  485. return 1;
  486. }
  487. typedef struct {
  488. BlockBackend *blk;
  489. int64_t offset;
  490. int64_t bytes;
  491. int64_t *total;
  492. int flags;
  493. int ret;
  494. bool done;
  495. } CoWriteZeroes;
  496. static void coroutine_fn co_pwrite_zeroes_entry(void *opaque)
  497. {
  498. CoWriteZeroes *data = opaque;
  499. data->ret = blk_co_pwrite_zeroes(data->blk, data->offset, data->bytes,
  500. data->flags);
  501. data->done = true;
  502. if (data->ret < 0) {
  503. *data->total = data->ret;
  504. return;
  505. }
  506. *data->total = data->bytes;
  507. }
  508. static int do_co_pwrite_zeroes(BlockBackend *blk, int64_t offset,
  509. int64_t bytes, int flags, int64_t *total)
  510. {
  511. Coroutine *co;
  512. CoWriteZeroes data = {
  513. .blk = blk,
  514. .offset = offset,
  515. .bytes = bytes,
  516. .total = total,
  517. .flags = flags,
  518. .done = false,
  519. };
  520. if (bytes > INT_MAX) {
  521. return -ERANGE;
  522. }
  523. co = qemu_coroutine_create(co_pwrite_zeroes_entry, &data);
  524. bdrv_coroutine_enter(blk_bs(blk), co);
  525. while (!data.done) {
  526. aio_poll(blk_get_aio_context(blk), true);
  527. }
  528. if (data.ret < 0) {
  529. return data.ret;
  530. } else {
  531. return 1;
  532. }
  533. }
  534. static int do_write_compressed(BlockBackend *blk, char *buf, int64_t offset,
  535. int64_t bytes, int64_t *total)
  536. {
  537. int ret;
  538. if (bytes > BDRV_REQUEST_MAX_BYTES) {
  539. return -ERANGE;
  540. }
  541. ret = blk_pwrite_compressed(blk, offset, buf, bytes);
  542. if (ret < 0) {
  543. return ret;
  544. }
  545. *total = bytes;
  546. return 1;
  547. }
  548. static int do_load_vmstate(BlockBackend *blk, char *buf, int64_t offset,
  549. int64_t count, int64_t *total)
  550. {
  551. if (count > INT_MAX) {
  552. return -ERANGE;
  553. }
  554. *total = blk_load_vmstate(blk, (uint8_t *)buf, offset, count);
  555. if (*total < 0) {
  556. return *total;
  557. }
  558. return 1;
  559. }
  560. static int do_save_vmstate(BlockBackend *blk, char *buf, int64_t offset,
  561. int64_t count, int64_t *total)
  562. {
  563. if (count > INT_MAX) {
  564. return -ERANGE;
  565. }
  566. *total = blk_save_vmstate(blk, (uint8_t *)buf, offset, count);
  567. if (*total < 0) {
  568. return *total;
  569. }
  570. return 1;
  571. }
  572. #define NOT_DONE 0x7fffffff
  573. static void aio_rw_done(void *opaque, int ret)
  574. {
  575. *(int *)opaque = ret;
  576. }
  577. static int do_aio_readv(BlockBackend *blk, QEMUIOVector *qiov,
  578. int64_t offset, int *total)
  579. {
  580. int async_ret = NOT_DONE;
  581. blk_aio_preadv(blk, offset, qiov, 0, aio_rw_done, &async_ret);
  582. while (async_ret == NOT_DONE) {
  583. main_loop_wait(false);
  584. }
  585. *total = qiov->size;
  586. return async_ret < 0 ? async_ret : 1;
  587. }
  588. static int do_aio_writev(BlockBackend *blk, QEMUIOVector *qiov,
  589. int64_t offset, int flags, int *total)
  590. {
  591. int async_ret = NOT_DONE;
  592. blk_aio_pwritev(blk, offset, qiov, flags, aio_rw_done, &async_ret);
  593. while (async_ret == NOT_DONE) {
  594. main_loop_wait(false);
  595. }
  596. *total = qiov->size;
  597. return async_ret < 0 ? async_ret : 1;
  598. }
  599. static void read_help(void)
  600. {
  601. printf(
  602. "\n"
  603. " reads a range of bytes from the given offset\n"
  604. "\n"
  605. " Example:\n"
  606. " 'read -v 512 1k' - dumps 1 kilobyte read from 512 bytes into the file\n"
  607. "\n"
  608. " Reads a segment of the currently open file, optionally dumping it to the\n"
  609. " standard output stream (with -v option) for subsequent inspection.\n"
  610. " -b, -- read from the VM state rather than the virtual disk\n"
  611. " -C, -- report statistics in a machine parsable format\n"
  612. " -l, -- length for pattern verification (only with -P)\n"
  613. " -p, -- ignored for backwards compatibility\n"
  614. " -P, -- use a pattern to verify read data\n"
  615. " -q, -- quiet mode, do not show I/O statistics\n"
  616. " -s, -- start offset for pattern verification (only with -P)\n"
  617. " -v, -- dump buffer to standard output\n"
  618. "\n");
  619. }
  620. static int read_f(BlockBackend *blk, int argc, char **argv);
  621. static const cmdinfo_t read_cmd = {
  622. .name = "read",
  623. .altname = "r",
  624. .cfunc = read_f,
  625. .argmin = 2,
  626. .argmax = -1,
  627. .args = "[-abCqv] [-P pattern [-s off] [-l len]] off len",
  628. .oneline = "reads a number of bytes at a specified offset",
  629. .help = read_help,
  630. };
  631. static int read_f(BlockBackend *blk, int argc, char **argv)
  632. {
  633. struct timespec t1, t2;
  634. bool Cflag = false, qflag = false, vflag = false;
  635. bool Pflag = false, sflag = false, lflag = false, bflag = false;
  636. int c, cnt, ret;
  637. char *buf;
  638. int64_t offset;
  639. int64_t count;
  640. /* Some compilers get confused and warn if this is not initialized. */
  641. int64_t total = 0;
  642. int pattern = 0;
  643. int64_t pattern_offset = 0, pattern_count = 0;
  644. while ((c = getopt(argc, argv, "bCl:pP:qs:v")) != -1) {
  645. switch (c) {
  646. case 'b':
  647. bflag = true;
  648. break;
  649. case 'C':
  650. Cflag = true;
  651. break;
  652. case 'l':
  653. lflag = true;
  654. pattern_count = cvtnum(optarg);
  655. if (pattern_count < 0) {
  656. print_cvtnum_err(pattern_count, optarg);
  657. return pattern_count;
  658. }
  659. break;
  660. case 'p':
  661. /* Ignored for backwards compatibility */
  662. break;
  663. case 'P':
  664. Pflag = true;
  665. pattern = parse_pattern(optarg);
  666. if (pattern < 0) {
  667. return -EINVAL;
  668. }
  669. break;
  670. case 'q':
  671. qflag = true;
  672. break;
  673. case 's':
  674. sflag = true;
  675. pattern_offset = cvtnum(optarg);
  676. if (pattern_offset < 0) {
  677. print_cvtnum_err(pattern_offset, optarg);
  678. return pattern_offset;
  679. }
  680. break;
  681. case 'v':
  682. vflag = true;
  683. break;
  684. default:
  685. qemuio_command_usage(&read_cmd);
  686. return -EINVAL;
  687. }
  688. }
  689. if (optind != argc - 2) {
  690. qemuio_command_usage(&read_cmd);
  691. return -EINVAL;
  692. }
  693. offset = cvtnum(argv[optind]);
  694. if (offset < 0) {
  695. print_cvtnum_err(offset, argv[optind]);
  696. return offset;
  697. }
  698. optind++;
  699. count = cvtnum(argv[optind]);
  700. if (count < 0) {
  701. print_cvtnum_err(count, argv[optind]);
  702. return count;
  703. } else if (count > BDRV_REQUEST_MAX_BYTES) {
  704. printf("length cannot exceed %" PRIu64 ", given %s\n",
  705. (uint64_t)BDRV_REQUEST_MAX_BYTES, argv[optind]);
  706. return -EINVAL;
  707. }
  708. if (!Pflag && (lflag || sflag)) {
  709. qemuio_command_usage(&read_cmd);
  710. return -EINVAL;
  711. }
  712. if (!lflag) {
  713. pattern_count = count - pattern_offset;
  714. }
  715. if ((pattern_count < 0) || (pattern_count + pattern_offset > count)) {
  716. printf("pattern verification range exceeds end of read data\n");
  717. return -EINVAL;
  718. }
  719. if (bflag) {
  720. if (!QEMU_IS_ALIGNED(offset, BDRV_SECTOR_SIZE)) {
  721. printf("%" PRId64 " is not a sector-aligned value for 'offset'\n",
  722. offset);
  723. return -EINVAL;
  724. }
  725. if (!QEMU_IS_ALIGNED(count, BDRV_SECTOR_SIZE)) {
  726. printf("%"PRId64" is not a sector-aligned value for 'count'\n",
  727. count);
  728. return -EINVAL;
  729. }
  730. }
  731. buf = qemu_io_alloc(blk, count, 0xab);
  732. clock_gettime(CLOCK_MONOTONIC, &t1);
  733. if (bflag) {
  734. ret = do_load_vmstate(blk, buf, offset, count, &total);
  735. } else {
  736. ret = do_pread(blk, buf, offset, count, &total);
  737. }
  738. clock_gettime(CLOCK_MONOTONIC, &t2);
  739. if (ret < 0) {
  740. printf("read failed: %s\n", strerror(-ret));
  741. goto out;
  742. }
  743. cnt = ret;
  744. ret = 0;
  745. if (Pflag) {
  746. void *cmp_buf = g_malloc(pattern_count);
  747. memset(cmp_buf, pattern, pattern_count);
  748. if (memcmp(buf + pattern_offset, cmp_buf, pattern_count)) {
  749. printf("Pattern verification failed at offset %"
  750. PRId64 ", %"PRId64" bytes\n",
  751. offset + pattern_offset, pattern_count);
  752. ret = -EINVAL;
  753. }
  754. g_free(cmp_buf);
  755. }
  756. if (qflag) {
  757. goto out;
  758. }
  759. if (vflag) {
  760. dump_buffer(buf, offset, count);
  761. }
  762. /* Finally, report back -- -C gives a parsable format */
  763. t2 = tsub(t2, t1);
  764. print_report("read", &t2, offset, count, total, cnt, Cflag);
  765. out:
  766. qemu_io_free(buf);
  767. return ret;
  768. }
  769. static void readv_help(void)
  770. {
  771. printf(
  772. "\n"
  773. " reads a range of bytes from the given offset into multiple buffers\n"
  774. "\n"
  775. " Example:\n"
  776. " 'readv -v 512 1k 1k ' - dumps 2 kilobytes read from 512 bytes into the file\n"
  777. "\n"
  778. " Reads a segment of the currently open file, optionally dumping it to the\n"
  779. " standard output stream (with -v option) for subsequent inspection.\n"
  780. " Uses multiple iovec buffers if more than one byte range is specified.\n"
  781. " -C, -- report statistics in a machine parsable format\n"
  782. " -P, -- use a pattern to verify read data\n"
  783. " -v, -- dump buffer to standard output\n"
  784. " -q, -- quiet mode, do not show I/O statistics\n"
  785. "\n");
  786. }
  787. static int readv_f(BlockBackend *blk, int argc, char **argv);
  788. static const cmdinfo_t readv_cmd = {
  789. .name = "readv",
  790. .cfunc = readv_f,
  791. .argmin = 2,
  792. .argmax = -1,
  793. .args = "[-Cqv] [-P pattern] off len [len..]",
  794. .oneline = "reads a number of bytes at a specified offset",
  795. .help = readv_help,
  796. };
  797. static int readv_f(BlockBackend *blk, int argc, char **argv)
  798. {
  799. struct timespec t1, t2;
  800. bool Cflag = false, qflag = false, vflag = false;
  801. int c, cnt, ret;
  802. char *buf;
  803. int64_t offset;
  804. /* Some compilers get confused and warn if this is not initialized. */
  805. int total = 0;
  806. int nr_iov;
  807. QEMUIOVector qiov;
  808. int pattern = 0;
  809. bool Pflag = false;
  810. while ((c = getopt(argc, argv, "CP:qv")) != -1) {
  811. switch (c) {
  812. case 'C':
  813. Cflag = true;
  814. break;
  815. case 'P':
  816. Pflag = true;
  817. pattern = parse_pattern(optarg);
  818. if (pattern < 0) {
  819. return -EINVAL;
  820. }
  821. break;
  822. case 'q':
  823. qflag = true;
  824. break;
  825. case 'v':
  826. vflag = true;
  827. break;
  828. default:
  829. qemuio_command_usage(&readv_cmd);
  830. return -EINVAL;
  831. }
  832. }
  833. if (optind > argc - 2) {
  834. qemuio_command_usage(&readv_cmd);
  835. return -EINVAL;
  836. }
  837. offset = cvtnum(argv[optind]);
  838. if (offset < 0) {
  839. print_cvtnum_err(offset, argv[optind]);
  840. return offset;
  841. }
  842. optind++;
  843. nr_iov = argc - optind;
  844. buf = create_iovec(blk, &qiov, &argv[optind], nr_iov, 0xab);
  845. if (buf == NULL) {
  846. return -EINVAL;
  847. }
  848. clock_gettime(CLOCK_MONOTONIC, &t1);
  849. ret = do_aio_readv(blk, &qiov, offset, &total);
  850. clock_gettime(CLOCK_MONOTONIC, &t2);
  851. if (ret < 0) {
  852. printf("readv failed: %s\n", strerror(-ret));
  853. goto out;
  854. }
  855. cnt = ret;
  856. ret = 0;
  857. if (Pflag) {
  858. void *cmp_buf = g_malloc(qiov.size);
  859. memset(cmp_buf, pattern, qiov.size);
  860. if (memcmp(buf, cmp_buf, qiov.size)) {
  861. printf("Pattern verification failed at offset %"
  862. PRId64 ", %zu bytes\n", offset, qiov.size);
  863. ret = -EINVAL;
  864. }
  865. g_free(cmp_buf);
  866. }
  867. if (qflag) {
  868. goto out;
  869. }
  870. if (vflag) {
  871. dump_buffer(buf, offset, qiov.size);
  872. }
  873. /* Finally, report back -- -C gives a parsable format */
  874. t2 = tsub(t2, t1);
  875. print_report("read", &t2, offset, qiov.size, total, cnt, Cflag);
  876. out:
  877. qemu_iovec_destroy(&qiov);
  878. qemu_io_free(buf);
  879. return ret;
  880. }
  881. static void write_help(void)
  882. {
  883. printf(
  884. "\n"
  885. " writes a range of bytes from the given offset\n"
  886. "\n"
  887. " Example:\n"
  888. " 'write 512 1k' - writes 1 kilobyte at 512 bytes into the open file\n"
  889. "\n"
  890. " Writes into a segment of the currently open file, using a buffer\n"
  891. " filled with a set pattern (0xcdcdcdcd).\n"
  892. " -b, -- write to the VM state rather than the virtual disk\n"
  893. " -c, -- write compressed data with blk_write_compressed\n"
  894. " -f, -- use Force Unit Access semantics\n"
  895. " -n, -- with -z, don't allow slow fallback\n"
  896. " -p, -- ignored for backwards compatibility\n"
  897. " -P, -- use different pattern to fill file\n"
  898. " -s, -- use a pattern file to fill the write buffer\n"
  899. " -C, -- report statistics in a machine parsable format\n"
  900. " -q, -- quiet mode, do not show I/O statistics\n"
  901. " -u, -- with -z, allow unmapping\n"
  902. " -z, -- write zeroes using blk_co_pwrite_zeroes\n"
  903. "\n");
  904. }
  905. static int write_f(BlockBackend *blk, int argc, char **argv);
  906. static const cmdinfo_t write_cmd = {
  907. .name = "write",
  908. .altname = "w",
  909. .cfunc = write_f,
  910. .perm = BLK_PERM_WRITE,
  911. .argmin = 2,
  912. .argmax = -1,
  913. .args = "[-bcCfnquz] [-P pattern | -s source_file] off len",
  914. .oneline = "writes a number of bytes at a specified offset",
  915. .help = write_help,
  916. };
  917. static int write_f(BlockBackend *blk, int argc, char **argv)
  918. {
  919. struct timespec t1, t2;
  920. bool Cflag = false, qflag = false, bflag = false;
  921. bool Pflag = false, zflag = false, cflag = false, sflag = false;
  922. int flags = 0;
  923. int c, cnt, ret;
  924. char *buf = NULL;
  925. int64_t offset;
  926. int64_t count;
  927. /* Some compilers get confused and warn if this is not initialized. */
  928. int64_t total = 0;
  929. int pattern = 0xcd;
  930. const char *file_name = NULL;
  931. while ((c = getopt(argc, argv, "bcCfnpP:qs:uz")) != -1) {
  932. switch (c) {
  933. case 'b':
  934. bflag = true;
  935. break;
  936. case 'c':
  937. cflag = true;
  938. break;
  939. case 'C':
  940. Cflag = true;
  941. break;
  942. case 'f':
  943. flags |= BDRV_REQ_FUA;
  944. break;
  945. case 'n':
  946. flags |= BDRV_REQ_NO_FALLBACK;
  947. break;
  948. case 'p':
  949. /* Ignored for backwards compatibility */
  950. break;
  951. case 'P':
  952. Pflag = true;
  953. pattern = parse_pattern(optarg);
  954. if (pattern < 0) {
  955. return -EINVAL;
  956. }
  957. break;
  958. case 'q':
  959. qflag = true;
  960. break;
  961. case 's':
  962. sflag = true;
  963. file_name = optarg;
  964. break;
  965. case 'u':
  966. flags |= BDRV_REQ_MAY_UNMAP;
  967. break;
  968. case 'z':
  969. zflag = true;
  970. break;
  971. default:
  972. qemuio_command_usage(&write_cmd);
  973. return -EINVAL;
  974. }
  975. }
  976. if (optind != argc - 2) {
  977. qemuio_command_usage(&write_cmd);
  978. return -EINVAL;
  979. }
  980. if (bflag && zflag) {
  981. printf("-b and -z cannot be specified at the same time\n");
  982. return -EINVAL;
  983. }
  984. if ((flags & BDRV_REQ_FUA) && (bflag || cflag)) {
  985. printf("-f and -b or -c cannot be specified at the same time\n");
  986. return -EINVAL;
  987. }
  988. if ((flags & BDRV_REQ_NO_FALLBACK) && !zflag) {
  989. printf("-n requires -z to be specified\n");
  990. return -EINVAL;
  991. }
  992. if ((flags & BDRV_REQ_MAY_UNMAP) && !zflag) {
  993. printf("-u requires -z to be specified\n");
  994. return -EINVAL;
  995. }
  996. if (zflag + Pflag + sflag > 1) {
  997. printf("Only one of -z, -P, and -s "
  998. "can be specified at the same time\n");
  999. return -EINVAL;
  1000. }
  1001. offset = cvtnum(argv[optind]);
  1002. if (offset < 0) {
  1003. print_cvtnum_err(offset, argv[optind]);
  1004. return offset;
  1005. }
  1006. optind++;
  1007. count = cvtnum(argv[optind]);
  1008. if (count < 0) {
  1009. print_cvtnum_err(count, argv[optind]);
  1010. return count;
  1011. } else if (count > BDRV_REQUEST_MAX_BYTES) {
  1012. printf("length cannot exceed %" PRIu64 ", given %s\n",
  1013. (uint64_t)BDRV_REQUEST_MAX_BYTES, argv[optind]);
  1014. return -EINVAL;
  1015. }
  1016. if (bflag || cflag) {
  1017. if (!QEMU_IS_ALIGNED(offset, BDRV_SECTOR_SIZE)) {
  1018. printf("%" PRId64 " is not a sector-aligned value for 'offset'\n",
  1019. offset);
  1020. return -EINVAL;
  1021. }
  1022. if (!QEMU_IS_ALIGNED(count, BDRV_SECTOR_SIZE)) {
  1023. printf("%"PRId64" is not a sector-aligned value for 'count'\n",
  1024. count);
  1025. return -EINVAL;
  1026. }
  1027. }
  1028. if (!zflag) {
  1029. if (sflag) {
  1030. buf = qemu_io_alloc_from_file(blk, count, file_name);
  1031. if (!buf) {
  1032. return -EINVAL;
  1033. }
  1034. } else {
  1035. buf = qemu_io_alloc(blk, count, pattern);
  1036. }
  1037. }
  1038. clock_gettime(CLOCK_MONOTONIC, &t1);
  1039. if (bflag) {
  1040. ret = do_save_vmstate(blk, buf, offset, count, &total);
  1041. } else if (zflag) {
  1042. ret = do_co_pwrite_zeroes(blk, offset, count, flags, &total);
  1043. } else if (cflag) {
  1044. ret = do_write_compressed(blk, buf, offset, count, &total);
  1045. } else {
  1046. ret = do_pwrite(blk, buf, offset, count, flags, &total);
  1047. }
  1048. clock_gettime(CLOCK_MONOTONIC, &t2);
  1049. if (ret < 0) {
  1050. printf("write failed: %s\n", strerror(-ret));
  1051. goto out;
  1052. }
  1053. cnt = ret;
  1054. ret = 0;
  1055. if (qflag) {
  1056. goto out;
  1057. }
  1058. /* Finally, report back -- -C gives a parsable format */
  1059. t2 = tsub(t2, t1);
  1060. print_report("wrote", &t2, offset, count, total, cnt, Cflag);
  1061. out:
  1062. if (!zflag) {
  1063. qemu_io_free(buf);
  1064. }
  1065. return ret;
  1066. }
  1067. static void
  1068. writev_help(void)
  1069. {
  1070. printf(
  1071. "\n"
  1072. " writes a range of bytes from the given offset source from multiple buffers\n"
  1073. "\n"
  1074. " Example:\n"
  1075. " 'writev 512 1k 1k' - writes 2 kilobytes at 512 bytes into the open file\n"
  1076. "\n"
  1077. " Writes into a segment of the currently open file, using a buffer\n"
  1078. " filled with a set pattern (0xcdcdcdcd).\n"
  1079. " -P, -- use different pattern to fill file\n"
  1080. " -C, -- report statistics in a machine parsable format\n"
  1081. " -f, -- use Force Unit Access semantics\n"
  1082. " -q, -- quiet mode, do not show I/O statistics\n"
  1083. "\n");
  1084. }
  1085. static int writev_f(BlockBackend *blk, int argc, char **argv);
  1086. static const cmdinfo_t writev_cmd = {
  1087. .name = "writev",
  1088. .cfunc = writev_f,
  1089. .perm = BLK_PERM_WRITE,
  1090. .argmin = 2,
  1091. .argmax = -1,
  1092. .args = "[-Cfq] [-P pattern] off len [len..]",
  1093. .oneline = "writes a number of bytes at a specified offset",
  1094. .help = writev_help,
  1095. };
  1096. static int writev_f(BlockBackend *blk, int argc, char **argv)
  1097. {
  1098. struct timespec t1, t2;
  1099. bool Cflag = false, qflag = false;
  1100. int flags = 0;
  1101. int c, cnt, ret;
  1102. char *buf;
  1103. int64_t offset;
  1104. /* Some compilers get confused and warn if this is not initialized. */
  1105. int total = 0;
  1106. int nr_iov;
  1107. int pattern = 0xcd;
  1108. QEMUIOVector qiov;
  1109. while ((c = getopt(argc, argv, "CfqP:")) != -1) {
  1110. switch (c) {
  1111. case 'C':
  1112. Cflag = true;
  1113. break;
  1114. case 'f':
  1115. flags |= BDRV_REQ_FUA;
  1116. break;
  1117. case 'q':
  1118. qflag = true;
  1119. break;
  1120. case 'P':
  1121. pattern = parse_pattern(optarg);
  1122. if (pattern < 0) {
  1123. return -EINVAL;
  1124. }
  1125. break;
  1126. default:
  1127. qemuio_command_usage(&writev_cmd);
  1128. return -EINVAL;
  1129. }
  1130. }
  1131. if (optind > argc - 2) {
  1132. qemuio_command_usage(&writev_cmd);
  1133. return -EINVAL;
  1134. }
  1135. offset = cvtnum(argv[optind]);
  1136. if (offset < 0) {
  1137. print_cvtnum_err(offset, argv[optind]);
  1138. return offset;
  1139. }
  1140. optind++;
  1141. nr_iov = argc - optind;
  1142. buf = create_iovec(blk, &qiov, &argv[optind], nr_iov, pattern);
  1143. if (buf == NULL) {
  1144. return -EINVAL;
  1145. }
  1146. clock_gettime(CLOCK_MONOTONIC, &t1);
  1147. ret = do_aio_writev(blk, &qiov, offset, flags, &total);
  1148. clock_gettime(CLOCK_MONOTONIC, &t2);
  1149. if (ret < 0) {
  1150. printf("writev failed: %s\n", strerror(-ret));
  1151. goto out;
  1152. }
  1153. cnt = ret;
  1154. ret = 0;
  1155. if (qflag) {
  1156. goto out;
  1157. }
  1158. /* Finally, report back -- -C gives a parsable format */
  1159. t2 = tsub(t2, t1);
  1160. print_report("wrote", &t2, offset, qiov.size, total, cnt, Cflag);
  1161. out:
  1162. qemu_iovec_destroy(&qiov);
  1163. qemu_io_free(buf);
  1164. return ret;
  1165. }
  1166. struct aio_ctx {
  1167. BlockBackend *blk;
  1168. QEMUIOVector qiov;
  1169. int64_t offset;
  1170. char *buf;
  1171. bool qflag;
  1172. bool vflag;
  1173. bool Cflag;
  1174. bool Pflag;
  1175. bool zflag;
  1176. BlockAcctCookie acct;
  1177. int pattern;
  1178. struct timespec t1;
  1179. };
  1180. static void aio_write_done(void *opaque, int ret)
  1181. {
  1182. struct aio_ctx *ctx = opaque;
  1183. struct timespec t2;
  1184. clock_gettime(CLOCK_MONOTONIC, &t2);
  1185. if (ret < 0) {
  1186. printf("aio_write failed: %s\n", strerror(-ret));
  1187. block_acct_failed(blk_get_stats(ctx->blk), &ctx->acct);
  1188. goto out;
  1189. }
  1190. block_acct_done(blk_get_stats(ctx->blk), &ctx->acct);
  1191. if (ctx->qflag) {
  1192. goto out;
  1193. }
  1194. /* Finally, report back -- -C gives a parsable format */
  1195. t2 = tsub(t2, ctx->t1);
  1196. print_report("wrote", &t2, ctx->offset, ctx->qiov.size,
  1197. ctx->qiov.size, 1, ctx->Cflag);
  1198. out:
  1199. if (!ctx->zflag) {
  1200. qemu_io_free(ctx->buf);
  1201. qemu_iovec_destroy(&ctx->qiov);
  1202. }
  1203. g_free(ctx);
  1204. }
  1205. static void aio_read_done(void *opaque, int ret)
  1206. {
  1207. struct aio_ctx *ctx = opaque;
  1208. struct timespec t2;
  1209. clock_gettime(CLOCK_MONOTONIC, &t2);
  1210. if (ret < 0) {
  1211. printf("readv failed: %s\n", strerror(-ret));
  1212. block_acct_failed(blk_get_stats(ctx->blk), &ctx->acct);
  1213. goto out;
  1214. }
  1215. if (ctx->Pflag) {
  1216. void *cmp_buf = g_malloc(ctx->qiov.size);
  1217. memset(cmp_buf, ctx->pattern, ctx->qiov.size);
  1218. if (memcmp(ctx->buf, cmp_buf, ctx->qiov.size)) {
  1219. printf("Pattern verification failed at offset %"
  1220. PRId64 ", %zu bytes\n", ctx->offset, ctx->qiov.size);
  1221. }
  1222. g_free(cmp_buf);
  1223. }
  1224. block_acct_done(blk_get_stats(ctx->blk), &ctx->acct);
  1225. if (ctx->qflag) {
  1226. goto out;
  1227. }
  1228. if (ctx->vflag) {
  1229. dump_buffer(ctx->buf, ctx->offset, ctx->qiov.size);
  1230. }
  1231. /* Finally, report back -- -C gives a parsable format */
  1232. t2 = tsub(t2, ctx->t1);
  1233. print_report("read", &t2, ctx->offset, ctx->qiov.size,
  1234. ctx->qiov.size, 1, ctx->Cflag);
  1235. out:
  1236. qemu_io_free(ctx->buf);
  1237. qemu_iovec_destroy(&ctx->qiov);
  1238. g_free(ctx);
  1239. }
  1240. static void aio_read_help(void)
  1241. {
  1242. printf(
  1243. "\n"
  1244. " asynchronously reads a range of bytes from the given offset\n"
  1245. "\n"
  1246. " Example:\n"
  1247. " 'aio_read -v 512 1k 1k ' - dumps 2 kilobytes read from 512 bytes into the file\n"
  1248. "\n"
  1249. " Reads a segment of the currently open file, optionally dumping it to the\n"
  1250. " standard output stream (with -v option) for subsequent inspection.\n"
  1251. " The read is performed asynchronously and the aio_flush command must be\n"
  1252. " used to ensure all outstanding aio requests have been completed.\n"
  1253. " Note that due to its asynchronous nature, this command will be\n"
  1254. " considered successful once the request is submitted, independently\n"
  1255. " of potential I/O errors or pattern mismatches.\n"
  1256. " -C, -- report statistics in a machine parsable format\n"
  1257. " -P, -- use a pattern to verify read data\n"
  1258. " -i, -- treat request as invalid, for exercising stats\n"
  1259. " -v, -- dump buffer to standard output\n"
  1260. " -q, -- quiet mode, do not show I/O statistics\n"
  1261. "\n");
  1262. }
  1263. static int aio_read_f(BlockBackend *blk, int argc, char **argv);
  1264. static const cmdinfo_t aio_read_cmd = {
  1265. .name = "aio_read",
  1266. .cfunc = aio_read_f,
  1267. .argmin = 2,
  1268. .argmax = -1,
  1269. .args = "[-Ciqv] [-P pattern] off len [len..]",
  1270. .oneline = "asynchronously reads a number of bytes",
  1271. .help = aio_read_help,
  1272. };
  1273. static int aio_read_f(BlockBackend *blk, int argc, char **argv)
  1274. {
  1275. int nr_iov, c;
  1276. struct aio_ctx *ctx = g_new0(struct aio_ctx, 1);
  1277. ctx->blk = blk;
  1278. while ((c = getopt(argc, argv, "CP:iqv")) != -1) {
  1279. switch (c) {
  1280. case 'C':
  1281. ctx->Cflag = true;
  1282. break;
  1283. case 'P':
  1284. ctx->Pflag = true;
  1285. ctx->pattern = parse_pattern(optarg);
  1286. if (ctx->pattern < 0) {
  1287. g_free(ctx);
  1288. return -EINVAL;
  1289. }
  1290. break;
  1291. case 'i':
  1292. printf("injecting invalid read request\n");
  1293. block_acct_invalid(blk_get_stats(blk), BLOCK_ACCT_READ);
  1294. g_free(ctx);
  1295. return 0;
  1296. case 'q':
  1297. ctx->qflag = true;
  1298. break;
  1299. case 'v':
  1300. ctx->vflag = true;
  1301. break;
  1302. default:
  1303. g_free(ctx);
  1304. qemuio_command_usage(&aio_read_cmd);
  1305. return -EINVAL;
  1306. }
  1307. }
  1308. if (optind > argc - 2) {
  1309. g_free(ctx);
  1310. qemuio_command_usage(&aio_read_cmd);
  1311. return -EINVAL;
  1312. }
  1313. ctx->offset = cvtnum(argv[optind]);
  1314. if (ctx->offset < 0) {
  1315. int ret = ctx->offset;
  1316. print_cvtnum_err(ret, argv[optind]);
  1317. g_free(ctx);
  1318. return ret;
  1319. }
  1320. optind++;
  1321. nr_iov = argc - optind;
  1322. ctx->buf = create_iovec(blk, &ctx->qiov, &argv[optind], nr_iov, 0xab);
  1323. if (ctx->buf == NULL) {
  1324. block_acct_invalid(blk_get_stats(blk), BLOCK_ACCT_READ);
  1325. g_free(ctx);
  1326. return -EINVAL;
  1327. }
  1328. clock_gettime(CLOCK_MONOTONIC, &ctx->t1);
  1329. block_acct_start(blk_get_stats(blk), &ctx->acct, ctx->qiov.size,
  1330. BLOCK_ACCT_READ);
  1331. blk_aio_preadv(blk, ctx->offset, &ctx->qiov, 0, aio_read_done, ctx);
  1332. return 0;
  1333. }
  1334. static void aio_write_help(void)
  1335. {
  1336. printf(
  1337. "\n"
  1338. " asynchronously writes a range of bytes from the given offset source\n"
  1339. " from multiple buffers\n"
  1340. "\n"
  1341. " Example:\n"
  1342. " 'aio_write 512 1k 1k' - writes 2 kilobytes at 512 bytes into the open file\n"
  1343. "\n"
  1344. " Writes into a segment of the currently open file, using a buffer\n"
  1345. " filled with a set pattern (0xcdcdcdcd).\n"
  1346. " The write is performed asynchronously and the aio_flush command must be\n"
  1347. " used to ensure all outstanding aio requests have been completed.\n"
  1348. " Note that due to its asynchronous nature, this command will be\n"
  1349. " considered successful once the request is submitted, independently\n"
  1350. " of potential I/O errors or pattern mismatches.\n"
  1351. " -P, -- use different pattern to fill file\n"
  1352. " -C, -- report statistics in a machine parsable format\n"
  1353. " -f, -- use Force Unit Access semantics\n"
  1354. " -i, -- treat request as invalid, for exercising stats\n"
  1355. " -q, -- quiet mode, do not show I/O statistics\n"
  1356. " -u, -- with -z, allow unmapping\n"
  1357. " -z, -- write zeroes using blk_aio_pwrite_zeroes\n"
  1358. "\n");
  1359. }
  1360. static int aio_write_f(BlockBackend *blk, int argc, char **argv);
  1361. static const cmdinfo_t aio_write_cmd = {
  1362. .name = "aio_write",
  1363. .cfunc = aio_write_f,
  1364. .perm = BLK_PERM_WRITE,
  1365. .argmin = 2,
  1366. .argmax = -1,
  1367. .args = "[-Cfiquz] [-P pattern] off len [len..]",
  1368. .oneline = "asynchronously writes a number of bytes",
  1369. .help = aio_write_help,
  1370. };
  1371. static int aio_write_f(BlockBackend *blk, int argc, char **argv)
  1372. {
  1373. int nr_iov, c;
  1374. int pattern = 0xcd;
  1375. struct aio_ctx *ctx = g_new0(struct aio_ctx, 1);
  1376. int flags = 0;
  1377. ctx->blk = blk;
  1378. while ((c = getopt(argc, argv, "CfiqP:uz")) != -1) {
  1379. switch (c) {
  1380. case 'C':
  1381. ctx->Cflag = true;
  1382. break;
  1383. case 'f':
  1384. flags |= BDRV_REQ_FUA;
  1385. break;
  1386. case 'q':
  1387. ctx->qflag = true;
  1388. break;
  1389. case 'u':
  1390. flags |= BDRV_REQ_MAY_UNMAP;
  1391. break;
  1392. case 'P':
  1393. pattern = parse_pattern(optarg);
  1394. if (pattern < 0) {
  1395. g_free(ctx);
  1396. return -EINVAL;
  1397. }
  1398. break;
  1399. case 'i':
  1400. printf("injecting invalid write request\n");
  1401. block_acct_invalid(blk_get_stats(blk), BLOCK_ACCT_WRITE);
  1402. g_free(ctx);
  1403. return 0;
  1404. case 'z':
  1405. ctx->zflag = true;
  1406. break;
  1407. default:
  1408. g_free(ctx);
  1409. qemuio_command_usage(&aio_write_cmd);
  1410. return -EINVAL;
  1411. }
  1412. }
  1413. if (optind > argc - 2) {
  1414. g_free(ctx);
  1415. qemuio_command_usage(&aio_write_cmd);
  1416. return -EINVAL;
  1417. }
  1418. if (ctx->zflag && optind != argc - 2) {
  1419. printf("-z supports only a single length parameter\n");
  1420. g_free(ctx);
  1421. return -EINVAL;
  1422. }
  1423. if ((flags & BDRV_REQ_MAY_UNMAP) && !ctx->zflag) {
  1424. printf("-u requires -z to be specified\n");
  1425. g_free(ctx);
  1426. return -EINVAL;
  1427. }
  1428. if (ctx->zflag && ctx->Pflag) {
  1429. printf("-z and -P cannot be specified at the same time\n");
  1430. g_free(ctx);
  1431. return -EINVAL;
  1432. }
  1433. ctx->offset = cvtnum(argv[optind]);
  1434. if (ctx->offset < 0) {
  1435. int ret = ctx->offset;
  1436. print_cvtnum_err(ret, argv[optind]);
  1437. g_free(ctx);
  1438. return ret;
  1439. }
  1440. optind++;
  1441. if (ctx->zflag) {
  1442. int64_t count = cvtnum(argv[optind]);
  1443. if (count < 0) {
  1444. print_cvtnum_err(count, argv[optind]);
  1445. g_free(ctx);
  1446. return count;
  1447. }
  1448. ctx->qiov.size = count;
  1449. blk_aio_pwrite_zeroes(blk, ctx->offset, count, flags, aio_write_done,
  1450. ctx);
  1451. } else {
  1452. nr_iov = argc - optind;
  1453. ctx->buf = create_iovec(blk, &ctx->qiov, &argv[optind], nr_iov,
  1454. pattern);
  1455. if (ctx->buf == NULL) {
  1456. block_acct_invalid(blk_get_stats(blk), BLOCK_ACCT_WRITE);
  1457. g_free(ctx);
  1458. return -EINVAL;
  1459. }
  1460. clock_gettime(CLOCK_MONOTONIC, &ctx->t1);
  1461. block_acct_start(blk_get_stats(blk), &ctx->acct, ctx->qiov.size,
  1462. BLOCK_ACCT_WRITE);
  1463. blk_aio_pwritev(blk, ctx->offset, &ctx->qiov, flags, aio_write_done,
  1464. ctx);
  1465. }
  1466. return 0;
  1467. }
  1468. static int aio_flush_f(BlockBackend *blk, int argc, char **argv)
  1469. {
  1470. BlockAcctCookie cookie;
  1471. block_acct_start(blk_get_stats(blk), &cookie, 0, BLOCK_ACCT_FLUSH);
  1472. blk_drain_all();
  1473. block_acct_done(blk_get_stats(blk), &cookie);
  1474. return 0;
  1475. }
  1476. static const cmdinfo_t aio_flush_cmd = {
  1477. .name = "aio_flush",
  1478. .cfunc = aio_flush_f,
  1479. .oneline = "completes all outstanding aio requests"
  1480. };
  1481. static int flush_f(BlockBackend *blk, int argc, char **argv)
  1482. {
  1483. return blk_flush(blk);
  1484. }
  1485. static const cmdinfo_t flush_cmd = {
  1486. .name = "flush",
  1487. .altname = "f",
  1488. .cfunc = flush_f,
  1489. .oneline = "flush all in-core file state to disk",
  1490. };
  1491. static int truncate_f(BlockBackend *blk, int argc, char **argv);
  1492. static const cmdinfo_t truncate_cmd = {
  1493. .name = "truncate",
  1494. .altname = "t",
  1495. .cfunc = truncate_f,
  1496. .perm = BLK_PERM_WRITE | BLK_PERM_RESIZE,
  1497. .argmin = 1,
  1498. .argmax = 3,
  1499. .args = "[-m prealloc_mode] off",
  1500. .oneline = "truncates the current file at the given offset",
  1501. };
  1502. static int truncate_f(BlockBackend *blk, int argc, char **argv)
  1503. {
  1504. Error *local_err = NULL;
  1505. int64_t offset;
  1506. int c, ret;
  1507. PreallocMode prealloc = PREALLOC_MODE_OFF;
  1508. while ((c = getopt(argc, argv, "m:")) != -1) {
  1509. switch (c) {
  1510. case 'm':
  1511. prealloc = qapi_enum_parse(&PreallocMode_lookup, optarg,
  1512. PREALLOC_MODE__MAX, NULL);
  1513. if (prealloc == PREALLOC_MODE__MAX) {
  1514. error_report("Invalid preallocation mode '%s'", optarg);
  1515. return -EINVAL;
  1516. }
  1517. break;
  1518. default:
  1519. qemuio_command_usage(&truncate_cmd);
  1520. return -EINVAL;
  1521. }
  1522. }
  1523. offset = cvtnum(argv[optind]);
  1524. if (offset < 0) {
  1525. print_cvtnum_err(offset, argv[1]);
  1526. return offset;
  1527. }
  1528. /*
  1529. * qemu-io is a debugging tool, so let us be strict here and pass
  1530. * exact=true. It is better to err on the "emit more errors" side
  1531. * than to be overly permissive.
  1532. */
  1533. ret = blk_truncate(blk, offset, false, prealloc, 0, &local_err);
  1534. if (ret < 0) {
  1535. error_report_err(local_err);
  1536. return ret;
  1537. }
  1538. return 0;
  1539. }
  1540. static int length_f(BlockBackend *blk, int argc, char **argv)
  1541. {
  1542. int64_t size;
  1543. char s1[64];
  1544. size = blk_getlength(blk);
  1545. if (size < 0) {
  1546. printf("getlength: %s\n", strerror(-size));
  1547. return size;
  1548. }
  1549. cvtstr(size, s1, sizeof(s1));
  1550. printf("%s\n", s1);
  1551. return 0;
  1552. }
  1553. static const cmdinfo_t length_cmd = {
  1554. .name = "length",
  1555. .altname = "l",
  1556. .cfunc = length_f,
  1557. .oneline = "gets the length of the current file",
  1558. };
  1559. static int info_f(BlockBackend *blk, int argc, char **argv)
  1560. {
  1561. BlockDriverState *bs = blk_bs(blk);
  1562. BlockDriverInfo bdi;
  1563. ImageInfoSpecific *spec_info;
  1564. Error *local_err = NULL;
  1565. char s1[64], s2[64];
  1566. int ret;
  1567. if (bs->drv && bs->drv->format_name) {
  1568. printf("format name: %s\n", bs->drv->format_name);
  1569. }
  1570. if (bs->drv && bs->drv->protocol_name) {
  1571. printf("format name: %s\n", bs->drv->protocol_name);
  1572. }
  1573. ret = bdrv_get_info(bs, &bdi);
  1574. if (ret) {
  1575. return ret;
  1576. }
  1577. cvtstr(bdi.cluster_size, s1, sizeof(s1));
  1578. cvtstr(bdi.vm_state_offset, s2, sizeof(s2));
  1579. printf("cluster size: %s\n", s1);
  1580. printf("vm state offset: %s\n", s2);
  1581. spec_info = bdrv_get_specific_info(bs, &local_err);
  1582. if (local_err) {
  1583. error_report_err(local_err);
  1584. return -EIO;
  1585. }
  1586. if (spec_info) {
  1587. printf("Format specific information:\n");
  1588. bdrv_image_info_specific_dump(spec_info);
  1589. qapi_free_ImageInfoSpecific(spec_info);
  1590. }
  1591. return 0;
  1592. }
  1593. static const cmdinfo_t info_cmd = {
  1594. .name = "info",
  1595. .altname = "i",
  1596. .cfunc = info_f,
  1597. .oneline = "prints information about the current file",
  1598. };
  1599. static void discard_help(void)
  1600. {
  1601. printf(
  1602. "\n"
  1603. " discards a range of bytes from the given offset\n"
  1604. "\n"
  1605. " Example:\n"
  1606. " 'discard 512 1k' - discards 1 kilobyte from 512 bytes into the file\n"
  1607. "\n"
  1608. " Discards a segment of the currently open file.\n"
  1609. " -C, -- report statistics in a machine parsable format\n"
  1610. " -q, -- quiet mode, do not show I/O statistics\n"
  1611. "\n");
  1612. }
  1613. static int discard_f(BlockBackend *blk, int argc, char **argv);
  1614. static const cmdinfo_t discard_cmd = {
  1615. .name = "discard",
  1616. .altname = "d",
  1617. .cfunc = discard_f,
  1618. .perm = BLK_PERM_WRITE,
  1619. .argmin = 2,
  1620. .argmax = -1,
  1621. .args = "[-Cq] off len",
  1622. .oneline = "discards a number of bytes at a specified offset",
  1623. .help = discard_help,
  1624. };
  1625. static int discard_f(BlockBackend *blk, int argc, char **argv)
  1626. {
  1627. struct timespec t1, t2;
  1628. bool Cflag = false, qflag = false;
  1629. int c, ret;
  1630. int64_t offset, bytes;
  1631. while ((c = getopt(argc, argv, "Cq")) != -1) {
  1632. switch (c) {
  1633. case 'C':
  1634. Cflag = true;
  1635. break;
  1636. case 'q':
  1637. qflag = true;
  1638. break;
  1639. default:
  1640. qemuio_command_usage(&discard_cmd);
  1641. return -EINVAL;
  1642. }
  1643. }
  1644. if (optind != argc - 2) {
  1645. qemuio_command_usage(&discard_cmd);
  1646. return -EINVAL;
  1647. }
  1648. offset = cvtnum(argv[optind]);
  1649. if (offset < 0) {
  1650. print_cvtnum_err(offset, argv[optind]);
  1651. return offset;
  1652. }
  1653. optind++;
  1654. bytes = cvtnum(argv[optind]);
  1655. if (bytes < 0) {
  1656. print_cvtnum_err(bytes, argv[optind]);
  1657. return bytes;
  1658. } else if (bytes > BDRV_REQUEST_MAX_BYTES) {
  1659. printf("length cannot exceed %"PRIu64", given %s\n",
  1660. (uint64_t)BDRV_REQUEST_MAX_BYTES, argv[optind]);
  1661. return -EINVAL;
  1662. }
  1663. clock_gettime(CLOCK_MONOTONIC, &t1);
  1664. ret = blk_pdiscard(blk, offset, bytes);
  1665. clock_gettime(CLOCK_MONOTONIC, &t2);
  1666. if (ret < 0) {
  1667. printf("discard failed: %s\n", strerror(-ret));
  1668. return ret;
  1669. }
  1670. /* Finally, report back -- -C gives a parsable format */
  1671. if (!qflag) {
  1672. t2 = tsub(t2, t1);
  1673. print_report("discard", &t2, offset, bytes, bytes, 1, Cflag);
  1674. }
  1675. return 0;
  1676. }
  1677. static int alloc_f(BlockBackend *blk, int argc, char **argv)
  1678. {
  1679. BlockDriverState *bs = blk_bs(blk);
  1680. int64_t offset, start, remaining, count;
  1681. char s1[64];
  1682. int ret;
  1683. int64_t num, sum_alloc;
  1684. start = offset = cvtnum(argv[1]);
  1685. if (offset < 0) {
  1686. print_cvtnum_err(offset, argv[1]);
  1687. return offset;
  1688. }
  1689. if (argc == 3) {
  1690. count = cvtnum(argv[2]);
  1691. if (count < 0) {
  1692. print_cvtnum_err(count, argv[2]);
  1693. return count;
  1694. }
  1695. } else {
  1696. count = BDRV_SECTOR_SIZE;
  1697. }
  1698. remaining = count;
  1699. sum_alloc = 0;
  1700. while (remaining) {
  1701. ret = bdrv_is_allocated(bs, offset, remaining, &num);
  1702. if (ret < 0) {
  1703. printf("is_allocated failed: %s\n", strerror(-ret));
  1704. return ret;
  1705. }
  1706. offset += num;
  1707. remaining -= num;
  1708. if (ret) {
  1709. sum_alloc += num;
  1710. }
  1711. if (num == 0) {
  1712. count -= remaining;
  1713. remaining = 0;
  1714. }
  1715. }
  1716. cvtstr(start, s1, sizeof(s1));
  1717. printf("%"PRId64"/%"PRId64" bytes allocated at offset %s\n",
  1718. sum_alloc, count, s1);
  1719. return 0;
  1720. }
  1721. static const cmdinfo_t alloc_cmd = {
  1722. .name = "alloc",
  1723. .altname = "a",
  1724. .argmin = 1,
  1725. .argmax = 2,
  1726. .cfunc = alloc_f,
  1727. .args = "offset [count]",
  1728. .oneline = "checks if offset is allocated in the file",
  1729. };
  1730. static int map_is_allocated(BlockDriverState *bs, int64_t offset,
  1731. int64_t bytes, int64_t *pnum)
  1732. {
  1733. int64_t num;
  1734. int num_checked;
  1735. int ret, firstret;
  1736. num_checked = MIN(bytes, BDRV_REQUEST_MAX_BYTES);
  1737. ret = bdrv_is_allocated(bs, offset, num_checked, &num);
  1738. if (ret < 0) {
  1739. return ret;
  1740. }
  1741. firstret = ret;
  1742. *pnum = num;
  1743. while (bytes > 0 && ret == firstret) {
  1744. offset += num;
  1745. bytes -= num;
  1746. num_checked = MIN(bytes, BDRV_REQUEST_MAX_BYTES);
  1747. ret = bdrv_is_allocated(bs, offset, num_checked, &num);
  1748. if (ret == firstret && num) {
  1749. *pnum += num;
  1750. } else {
  1751. break;
  1752. }
  1753. }
  1754. return firstret;
  1755. }
  1756. static int map_f(BlockBackend *blk, int argc, char **argv)
  1757. {
  1758. int64_t offset, bytes;
  1759. char s1[64], s2[64];
  1760. int64_t num;
  1761. int ret;
  1762. const char *retstr;
  1763. offset = 0;
  1764. bytes = blk_getlength(blk);
  1765. if (bytes < 0) {
  1766. error_report("Failed to query image length: %s", strerror(-bytes));
  1767. return bytes;
  1768. }
  1769. while (bytes) {
  1770. ret = map_is_allocated(blk_bs(blk), offset, bytes, &num);
  1771. if (ret < 0) {
  1772. error_report("Failed to get allocation status: %s", strerror(-ret));
  1773. return ret;
  1774. } else if (!num) {
  1775. error_report("Unexpected end of image");
  1776. return -EIO;
  1777. }
  1778. retstr = ret ? " allocated" : "not allocated";
  1779. cvtstr(num, s1, sizeof(s1));
  1780. cvtstr(offset, s2, sizeof(s2));
  1781. printf("%s (0x%" PRIx64 ") bytes %s at offset %s (0x%" PRIx64 ")\n",
  1782. s1, num, retstr, s2, offset);
  1783. offset += num;
  1784. bytes -= num;
  1785. }
  1786. return 0;
  1787. }
  1788. static const cmdinfo_t map_cmd = {
  1789. .name = "map",
  1790. .argmin = 0,
  1791. .argmax = 0,
  1792. .cfunc = map_f,
  1793. .args = "",
  1794. .oneline = "prints the allocated areas of a file",
  1795. };
  1796. static void reopen_help(void)
  1797. {
  1798. printf(
  1799. "\n"
  1800. " Changes the open options of an already opened image\n"
  1801. "\n"
  1802. " Example:\n"
  1803. " 'reopen -o lazy-refcounts=on' - activates lazy refcount writeback on a qcow2 image\n"
  1804. "\n"
  1805. " -r, -- Reopen the image read-only\n"
  1806. " -w, -- Reopen the image read-write\n"
  1807. " -c, -- Change the cache mode to the given value\n"
  1808. " -o, -- Changes block driver options (cf. 'open' command)\n"
  1809. "\n");
  1810. }
  1811. static int reopen_f(BlockBackend *blk, int argc, char **argv);
  1812. static QemuOptsList reopen_opts = {
  1813. .name = "reopen",
  1814. .merge_lists = true,
  1815. .head = QTAILQ_HEAD_INITIALIZER(reopen_opts.head),
  1816. .desc = {
  1817. /* no elements => accept any params */
  1818. { /* end of list */ }
  1819. },
  1820. };
  1821. static const cmdinfo_t reopen_cmd = {
  1822. .name = "reopen",
  1823. .argmin = 0,
  1824. .argmax = -1,
  1825. .cfunc = reopen_f,
  1826. .args = "[(-r|-w)] [-c cache] [-o options]",
  1827. .oneline = "reopens an image with new options",
  1828. .help = reopen_help,
  1829. };
  1830. static int reopen_f(BlockBackend *blk, int argc, char **argv)
  1831. {
  1832. BlockDriverState *bs = blk_bs(blk);
  1833. QemuOpts *qopts;
  1834. QDict *opts;
  1835. int c;
  1836. int flags = bs->open_flags;
  1837. bool writethrough = !blk_enable_write_cache(blk);
  1838. bool has_rw_option = false;
  1839. bool has_cache_option = false;
  1840. Error *local_err = NULL;
  1841. while ((c = getopt(argc, argv, "c:o:rw")) != -1) {
  1842. switch (c) {
  1843. case 'c':
  1844. if (bdrv_parse_cache_mode(optarg, &flags, &writethrough) < 0) {
  1845. error_report("Invalid cache option: %s", optarg);
  1846. return -EINVAL;
  1847. }
  1848. has_cache_option = true;
  1849. break;
  1850. case 'o':
  1851. if (!qemu_opts_parse_noisily(&reopen_opts, optarg, 0)) {
  1852. qemu_opts_reset(&reopen_opts);
  1853. return -EINVAL;
  1854. }
  1855. break;
  1856. case 'r':
  1857. if (has_rw_option) {
  1858. error_report("Only one -r/-w option may be given");
  1859. return -EINVAL;
  1860. }
  1861. flags &= ~BDRV_O_RDWR;
  1862. has_rw_option = true;
  1863. break;
  1864. case 'w':
  1865. if (has_rw_option) {
  1866. error_report("Only one -r/-w option may be given");
  1867. return -EINVAL;
  1868. }
  1869. flags |= BDRV_O_RDWR;
  1870. has_rw_option = true;
  1871. break;
  1872. default:
  1873. qemu_opts_reset(&reopen_opts);
  1874. qemuio_command_usage(&reopen_cmd);
  1875. return -EINVAL;
  1876. }
  1877. }
  1878. if (optind != argc) {
  1879. qemu_opts_reset(&reopen_opts);
  1880. qemuio_command_usage(&reopen_cmd);
  1881. return -EINVAL;
  1882. }
  1883. if (!writethrough != blk_enable_write_cache(blk) &&
  1884. blk_get_attached_dev(blk))
  1885. {
  1886. error_report("Cannot change cache.writeback: Device attached");
  1887. qemu_opts_reset(&reopen_opts);
  1888. return -EBUSY;
  1889. }
  1890. if (!(flags & BDRV_O_RDWR)) {
  1891. uint64_t orig_perm, orig_shared_perm;
  1892. bdrv_drain(bs);
  1893. blk_get_perm(blk, &orig_perm, &orig_shared_perm);
  1894. blk_set_perm(blk,
  1895. orig_perm & ~(BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED),
  1896. orig_shared_perm,
  1897. &error_abort);
  1898. }
  1899. qopts = qemu_opts_find(&reopen_opts, NULL);
  1900. opts = qopts ? qemu_opts_to_qdict(qopts, NULL) : qdict_new();
  1901. qemu_opts_reset(&reopen_opts);
  1902. if (qdict_haskey(opts, BDRV_OPT_READ_ONLY)) {
  1903. if (has_rw_option) {
  1904. error_report("Cannot set both -r/-w and '" BDRV_OPT_READ_ONLY "'");
  1905. qobject_unref(opts);
  1906. return -EINVAL;
  1907. }
  1908. } else {
  1909. qdict_put_bool(opts, BDRV_OPT_READ_ONLY, !(flags & BDRV_O_RDWR));
  1910. }
  1911. if (qdict_haskey(opts, BDRV_OPT_CACHE_DIRECT) ||
  1912. qdict_haskey(opts, BDRV_OPT_CACHE_NO_FLUSH)) {
  1913. if (has_cache_option) {
  1914. error_report("Cannot set both -c and the cache options");
  1915. qobject_unref(opts);
  1916. return -EINVAL;
  1917. }
  1918. } else {
  1919. qdict_put_bool(opts, BDRV_OPT_CACHE_DIRECT, flags & BDRV_O_NOCACHE);
  1920. qdict_put_bool(opts, BDRV_OPT_CACHE_NO_FLUSH, flags & BDRV_O_NO_FLUSH);
  1921. }
  1922. bdrv_reopen(bs, opts, true, &local_err);
  1923. if (local_err) {
  1924. error_report_err(local_err);
  1925. return -EINVAL;
  1926. }
  1927. blk_set_enable_write_cache(blk, !writethrough);
  1928. return 0;
  1929. }
  1930. static int break_f(BlockBackend *blk, int argc, char **argv)
  1931. {
  1932. int ret;
  1933. ret = bdrv_debug_breakpoint(blk_bs(blk), argv[1], argv[2]);
  1934. if (ret < 0) {
  1935. printf("Could not set breakpoint: %s\n", strerror(-ret));
  1936. return ret;
  1937. }
  1938. return 0;
  1939. }
  1940. static int remove_break_f(BlockBackend *blk, int argc, char **argv)
  1941. {
  1942. int ret;
  1943. ret = bdrv_debug_remove_breakpoint(blk_bs(blk), argv[1]);
  1944. if (ret < 0) {
  1945. printf("Could not remove breakpoint %s: %s\n", argv[1], strerror(-ret));
  1946. return ret;
  1947. }
  1948. return 0;
  1949. }
  1950. static const cmdinfo_t break_cmd = {
  1951. .name = "break",
  1952. .argmin = 2,
  1953. .argmax = 2,
  1954. .cfunc = break_f,
  1955. .args = "event tag",
  1956. .oneline = "sets a breakpoint on event and tags the stopped "
  1957. "request as tag",
  1958. };
  1959. static const cmdinfo_t remove_break_cmd = {
  1960. .name = "remove_break",
  1961. .argmin = 1,
  1962. .argmax = 1,
  1963. .cfunc = remove_break_f,
  1964. .args = "tag",
  1965. .oneline = "remove a breakpoint by tag",
  1966. };
  1967. static int resume_f(BlockBackend *blk, int argc, char **argv)
  1968. {
  1969. int ret;
  1970. ret = bdrv_debug_resume(blk_bs(blk), argv[1]);
  1971. if (ret < 0) {
  1972. printf("Could not resume request: %s\n", strerror(-ret));
  1973. return ret;
  1974. }
  1975. return 0;
  1976. }
  1977. static const cmdinfo_t resume_cmd = {
  1978. .name = "resume",
  1979. .argmin = 1,
  1980. .argmax = 1,
  1981. .cfunc = resume_f,
  1982. .args = "tag",
  1983. .oneline = "resumes the request tagged as tag",
  1984. };
  1985. static int wait_break_f(BlockBackend *blk, int argc, char **argv)
  1986. {
  1987. while (!bdrv_debug_is_suspended(blk_bs(blk), argv[1])) {
  1988. aio_poll(blk_get_aio_context(blk), true);
  1989. }
  1990. return 0;
  1991. }
  1992. static const cmdinfo_t wait_break_cmd = {
  1993. .name = "wait_break",
  1994. .argmin = 1,
  1995. .argmax = 1,
  1996. .cfunc = wait_break_f,
  1997. .args = "tag",
  1998. .oneline = "waits for the suspension of a request",
  1999. };
  2000. static int abort_f(BlockBackend *blk, int argc, char **argv)
  2001. {
  2002. abort();
  2003. }
  2004. static const cmdinfo_t abort_cmd = {
  2005. .name = "abort",
  2006. .cfunc = abort_f,
  2007. .flags = CMD_NOFILE_OK,
  2008. .oneline = "simulate a program crash using abort(3)",
  2009. };
  2010. static void sigraise_help(void)
  2011. {
  2012. printf(
  2013. "\n"
  2014. " raises the given signal\n"
  2015. "\n"
  2016. " Example:\n"
  2017. " 'sigraise %i' - raises SIGTERM\n"
  2018. "\n"
  2019. " Invokes raise(signal), where \"signal\" is the mandatory integer argument\n"
  2020. " given to sigraise.\n"
  2021. "\n", SIGTERM);
  2022. }
  2023. static int sigraise_f(BlockBackend *blk, int argc, char **argv);
  2024. static const cmdinfo_t sigraise_cmd = {
  2025. .name = "sigraise",
  2026. .cfunc = sigraise_f,
  2027. .argmin = 1,
  2028. .argmax = 1,
  2029. .flags = CMD_NOFILE_OK,
  2030. .args = "signal",
  2031. .oneline = "raises a signal",
  2032. .help = sigraise_help,
  2033. };
  2034. static int sigraise_f(BlockBackend *blk, int argc, char **argv)
  2035. {
  2036. int64_t sig = cvtnum(argv[1]);
  2037. if (sig < 0) {
  2038. print_cvtnum_err(sig, argv[1]);
  2039. return sig;
  2040. } else if (sig > NSIG) {
  2041. printf("signal argument '%s' is too large to be a valid signal\n",
  2042. argv[1]);
  2043. return -EINVAL;
  2044. }
  2045. /* Using raise() to kill this process does not necessarily flush all open
  2046. * streams. At least stdout and stderr (although the latter should be
  2047. * non-buffered anyway) should be flushed, though. */
  2048. fflush(stdout);
  2049. fflush(stderr);
  2050. raise(sig);
  2051. return 0;
  2052. }
  2053. static void sleep_cb(void *opaque)
  2054. {
  2055. bool *expired = opaque;
  2056. *expired = true;
  2057. }
  2058. static int sleep_f(BlockBackend *blk, int argc, char **argv)
  2059. {
  2060. char *endptr;
  2061. long ms;
  2062. struct QEMUTimer *timer;
  2063. bool expired = false;
  2064. ms = strtol(argv[1], &endptr, 0);
  2065. if (ms < 0 || *endptr != '\0') {
  2066. printf("%s is not a valid number\n", argv[1]);
  2067. return -EINVAL;
  2068. }
  2069. timer = timer_new_ns(QEMU_CLOCK_HOST, sleep_cb, &expired);
  2070. timer_mod(timer, qemu_clock_get_ns(QEMU_CLOCK_HOST) + SCALE_MS * ms);
  2071. while (!expired) {
  2072. main_loop_wait(false);
  2073. }
  2074. timer_free(timer);
  2075. return 0;
  2076. }
  2077. static const cmdinfo_t sleep_cmd = {
  2078. .name = "sleep",
  2079. .argmin = 1,
  2080. .argmax = 1,
  2081. .cfunc = sleep_f,
  2082. .flags = CMD_NOFILE_OK,
  2083. .oneline = "waits for the given value in milliseconds",
  2084. };
  2085. static void help_oneline(const char *cmd, const cmdinfo_t *ct)
  2086. {
  2087. printf("%s ", cmd);
  2088. if (ct->args) {
  2089. printf("%s ", ct->args);
  2090. }
  2091. printf("-- %s\n", ct->oneline);
  2092. }
  2093. static void help_onecmd(const char *cmd, const cmdinfo_t *ct)
  2094. {
  2095. help_oneline(cmd, ct);
  2096. if (ct->help) {
  2097. ct->help();
  2098. }
  2099. }
  2100. static void help_all(void)
  2101. {
  2102. const cmdinfo_t *ct;
  2103. for (ct = cmdtab; ct < &cmdtab[ncmds]; ct++) {
  2104. help_oneline(ct->name, ct);
  2105. }
  2106. printf("\nUse 'help commandname' for extended help.\n");
  2107. }
  2108. static int help_f(BlockBackend *blk, int argc, char **argv)
  2109. {
  2110. const cmdinfo_t *ct;
  2111. if (argc < 2) {
  2112. help_all();
  2113. return 0;
  2114. }
  2115. ct = find_command(argv[1]);
  2116. if (ct == NULL) {
  2117. printf("command %s not found\n", argv[1]);
  2118. return -EINVAL;
  2119. }
  2120. help_onecmd(argv[1], ct);
  2121. return 0;
  2122. }
  2123. static const cmdinfo_t help_cmd = {
  2124. .name = "help",
  2125. .altname = "?",
  2126. .cfunc = help_f,
  2127. .argmin = 0,
  2128. .argmax = 1,
  2129. .flags = CMD_FLAG_GLOBAL,
  2130. .args = "[command]",
  2131. .oneline = "help for one or all commands",
  2132. };
  2133. /*
  2134. * Called with aio context of blk acquired. Or with qemu_get_aio_context()
  2135. * context acquired if blk is NULL.
  2136. */
  2137. int qemuio_command(BlockBackend *blk, const char *cmd)
  2138. {
  2139. char *input;
  2140. const cmdinfo_t *ct;
  2141. char **v;
  2142. int c;
  2143. int ret = 0;
  2144. input = g_strdup(cmd);
  2145. v = breakline(input, &c);
  2146. if (c) {
  2147. ct = find_command(v[0]);
  2148. if (ct) {
  2149. ret = command(blk, ct, c, v);
  2150. } else {
  2151. fprintf(stderr, "command \"%s\" not found\n", v[0]);
  2152. ret = -EINVAL;
  2153. }
  2154. }
  2155. g_free(input);
  2156. g_free(v);
  2157. return ret;
  2158. }
  2159. static void __attribute((constructor)) init_qemuio_commands(void)
  2160. {
  2161. /* initialize commands */
  2162. qemuio_add_command(&help_cmd);
  2163. qemuio_add_command(&read_cmd);
  2164. qemuio_add_command(&readv_cmd);
  2165. qemuio_add_command(&write_cmd);
  2166. qemuio_add_command(&writev_cmd);
  2167. qemuio_add_command(&aio_read_cmd);
  2168. qemuio_add_command(&aio_write_cmd);
  2169. qemuio_add_command(&aio_flush_cmd);
  2170. qemuio_add_command(&flush_cmd);
  2171. qemuio_add_command(&truncate_cmd);
  2172. qemuio_add_command(&length_cmd);
  2173. qemuio_add_command(&info_cmd);
  2174. qemuio_add_command(&discard_cmd);
  2175. qemuio_add_command(&alloc_cmd);
  2176. qemuio_add_command(&map_cmd);
  2177. qemuio_add_command(&reopen_cmd);
  2178. qemuio_add_command(&break_cmd);
  2179. qemuio_add_command(&remove_break_cmd);
  2180. qemuio_add_command(&resume_cmd);
  2181. qemuio_add_command(&wait_break_cmd);
  2182. qemuio_add_command(&abort_cmd);
  2183. qemuio_add_command(&sleep_cmd);
  2184. qemuio_add_command(&sigraise_cmd);
  2185. }