2
0

qemu-io-cmds.c 65 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521
  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. #include "qemu/memalign.h"
  24. #define CMD_NOFILE_OK 0x01
  25. bool qemuio_misalign;
  26. static cmdinfo_t *cmdtab;
  27. static int ncmds;
  28. static int compare_cmdname(const void *a, const void *b)
  29. {
  30. return strcmp(((const cmdinfo_t *)a)->name,
  31. ((const cmdinfo_t *)b)->name);
  32. }
  33. void qemuio_add_command(const cmdinfo_t *ci)
  34. {
  35. /* ci->perm assumes a file is open, but the GLOBAL and NOFILE_OK
  36. * flags allow it not to be, so that combination is invalid.
  37. * Catch it now rather than letting it manifest as a crash if a
  38. * particular set of command line options are used.
  39. */
  40. assert(ci->perm == 0 ||
  41. (ci->flags & (CMD_FLAG_GLOBAL | CMD_NOFILE_OK)) == 0);
  42. cmdtab = g_renew(cmdinfo_t, cmdtab, ++ncmds);
  43. cmdtab[ncmds - 1] = *ci;
  44. qsort(cmdtab, ncmds, sizeof(*cmdtab), compare_cmdname);
  45. }
  46. void qemuio_command_usage(const cmdinfo_t *ci)
  47. {
  48. printf("%s %s -- %s\n", ci->name, ci->args, ci->oneline);
  49. }
  50. static int init_check_command(BlockBackend *blk, const cmdinfo_t *ct)
  51. {
  52. if (ct->flags & CMD_FLAG_GLOBAL) {
  53. return 1;
  54. }
  55. if (!(ct->flags & CMD_NOFILE_OK) && !blk) {
  56. fprintf(stderr, "no file open, try 'help open'\n");
  57. return 0;
  58. }
  59. return 1;
  60. }
  61. static int command(BlockBackend *blk, const cmdinfo_t *ct, int argc,
  62. char **argv)
  63. {
  64. char *cmd = argv[0];
  65. if (!init_check_command(blk, ct)) {
  66. return -EINVAL;
  67. }
  68. if (argc - 1 < ct->argmin || (ct->argmax != -1 && argc - 1 > ct->argmax)) {
  69. if (ct->argmax == -1) {
  70. fprintf(stderr,
  71. "bad argument count %d to %s, expected at least %d arguments\n",
  72. argc-1, cmd, ct->argmin);
  73. } else if (ct->argmin == ct->argmax) {
  74. fprintf(stderr,
  75. "bad argument count %d to %s, expected %d arguments\n",
  76. argc-1, cmd, ct->argmin);
  77. } else {
  78. fprintf(stderr,
  79. "bad argument count %d to %s, expected between %d and %d arguments\n",
  80. argc-1, cmd, ct->argmin, ct->argmax);
  81. }
  82. return -EINVAL;
  83. }
  84. /*
  85. * Request additional permissions if necessary for this command. The caller
  86. * is responsible for restoring the original permissions afterwards if this
  87. * is what it wants.
  88. *
  89. * Coverity thinks that blk may be NULL in the following if condition. It's
  90. * not so: in init_check_command() we fail if blk is NULL for command with
  91. * both CMD_FLAG_GLOBAL and CMD_NOFILE_OK flags unset. And in
  92. * qemuio_add_command() we assert that command with non-zero .perm field
  93. * doesn't set this flags. So, the following assertion is to silence
  94. * Coverity:
  95. */
  96. assert(blk || !ct->perm);
  97. if (ct->perm && blk_is_available(blk)) {
  98. uint64_t orig_perm, orig_shared_perm;
  99. blk_get_perm(blk, &orig_perm, &orig_shared_perm);
  100. if (ct->perm & ~orig_perm) {
  101. uint64_t new_perm;
  102. Error *local_err = NULL;
  103. int ret;
  104. new_perm = orig_perm | ct->perm;
  105. ret = blk_set_perm(blk, new_perm, orig_shared_perm, &local_err);
  106. if (ret < 0) {
  107. error_report_err(local_err);
  108. return ret;
  109. }
  110. }
  111. }
  112. qemu_reset_optind();
  113. return ct->cfunc(blk, argc, argv);
  114. }
  115. static const cmdinfo_t *find_command(const char *cmd)
  116. {
  117. cmdinfo_t *ct;
  118. for (ct = cmdtab; ct < &cmdtab[ncmds]; ct++) {
  119. if (strcmp(ct->name, cmd) == 0 ||
  120. (ct->altname && strcmp(ct->altname, cmd) == 0))
  121. {
  122. return (const cmdinfo_t *)ct;
  123. }
  124. }
  125. return NULL;
  126. }
  127. /* Invoke fn() for commands with a matching prefix */
  128. void qemuio_complete_command(const char *input,
  129. void (*fn)(const char *cmd, void *opaque),
  130. void *opaque)
  131. {
  132. cmdinfo_t *ct;
  133. size_t input_len = strlen(input);
  134. for (ct = cmdtab; ct < &cmdtab[ncmds]; ct++) {
  135. if (strncmp(input, ct->name, input_len) == 0) {
  136. fn(ct->name, opaque);
  137. }
  138. }
  139. }
  140. static char **breakline(char *input, int *count)
  141. {
  142. int c = 0;
  143. char *p;
  144. char **rval = g_new0(char *, 1);
  145. while (rval && (p = qemu_strsep(&input, " ")) != NULL) {
  146. if (!*p) {
  147. continue;
  148. }
  149. c++;
  150. rval = g_renew(char *, rval, (c + 1));
  151. rval[c - 1] = p;
  152. rval[c] = NULL;
  153. }
  154. *count = c;
  155. return rval;
  156. }
  157. static int64_t cvtnum(const char *s)
  158. {
  159. int err;
  160. uint64_t value;
  161. err = qemu_strtosz(s, NULL, &value);
  162. if (err < 0) {
  163. return err;
  164. }
  165. if (value > INT64_MAX) {
  166. return -ERANGE;
  167. }
  168. return value;
  169. }
  170. static void print_cvtnum_err(int64_t rc, const char *arg)
  171. {
  172. switch (rc) {
  173. case -EINVAL:
  174. printf("Parsing error: non-numeric argument,"
  175. " or extraneous/unrecognized suffix -- %s\n", arg);
  176. break;
  177. case -ERANGE:
  178. printf("Parsing error: argument too large -- %s\n", arg);
  179. break;
  180. default:
  181. printf("Parsing error: %s\n", arg);
  182. }
  183. }
  184. #define EXABYTES(x) ((long long)(x) << 60)
  185. #define PETABYTES(x) ((long long)(x) << 50)
  186. #define TERABYTES(x) ((long long)(x) << 40)
  187. #define GIGABYTES(x) ((long long)(x) << 30)
  188. #define MEGABYTES(x) ((long long)(x) << 20)
  189. #define KILOBYTES(x) ((long long)(x) << 10)
  190. #define TO_EXABYTES(x) ((x) / EXABYTES(1))
  191. #define TO_PETABYTES(x) ((x) / PETABYTES(1))
  192. #define TO_TERABYTES(x) ((x) / TERABYTES(1))
  193. #define TO_GIGABYTES(x) ((x) / GIGABYTES(1))
  194. #define TO_MEGABYTES(x) ((x) / MEGABYTES(1))
  195. #define TO_KILOBYTES(x) ((x) / KILOBYTES(1))
  196. static void cvtstr(double value, char *str, size_t size)
  197. {
  198. char *trim;
  199. const char *suffix;
  200. if (value >= EXABYTES(1)) {
  201. suffix = " EiB";
  202. snprintf(str, size - 4, "%.3f", TO_EXABYTES(value));
  203. } else if (value >= PETABYTES(1)) {
  204. suffix = " PiB";
  205. snprintf(str, size - 4, "%.3f", TO_PETABYTES(value));
  206. } else if (value >= TERABYTES(1)) {
  207. suffix = " TiB";
  208. snprintf(str, size - 4, "%.3f", TO_TERABYTES(value));
  209. } else if (value >= GIGABYTES(1)) {
  210. suffix = " GiB";
  211. snprintf(str, size - 4, "%.3f", TO_GIGABYTES(value));
  212. } else if (value >= MEGABYTES(1)) {
  213. suffix = " MiB";
  214. snprintf(str, size - 4, "%.3f", TO_MEGABYTES(value));
  215. } else if (value >= KILOBYTES(1)) {
  216. suffix = " KiB";
  217. snprintf(str, size - 4, "%.3f", TO_KILOBYTES(value));
  218. } else {
  219. suffix = " bytes";
  220. snprintf(str, size - 6, "%f", value);
  221. }
  222. trim = strstr(str, ".000");
  223. if (trim) {
  224. strcpy(trim, suffix);
  225. } else {
  226. strcat(str, suffix);
  227. }
  228. }
  229. static struct timespec tsub(struct timespec t1, struct timespec t2)
  230. {
  231. t1.tv_nsec -= t2.tv_nsec;
  232. if (t1.tv_nsec < 0) {
  233. t1.tv_nsec += NANOSECONDS_PER_SECOND;
  234. t1.tv_sec--;
  235. }
  236. t1.tv_sec -= t2.tv_sec;
  237. return t1;
  238. }
  239. static double tdiv(double value, struct timespec tv)
  240. {
  241. double seconds = tv.tv_sec + (tv.tv_nsec / 1e9);
  242. return value / seconds;
  243. }
  244. #define HOURS(sec) ((sec) / (60 * 60))
  245. #define MINUTES(sec) (((sec) % (60 * 60)) / 60)
  246. #define SECONDS(sec) ((sec) % 60)
  247. enum {
  248. DEFAULT_TIME = 0x0,
  249. TERSE_FIXED_TIME = 0x1,
  250. VERBOSE_FIXED_TIME = 0x2,
  251. };
  252. static void timestr(struct timespec *tv, char *ts, size_t size, int format)
  253. {
  254. double frac_sec = tv->tv_nsec / 1e9;
  255. if (format & TERSE_FIXED_TIME) {
  256. if (!HOURS(tv->tv_sec)) {
  257. snprintf(ts, size, "%u:%05.2f",
  258. (unsigned int) MINUTES(tv->tv_sec),
  259. SECONDS(tv->tv_sec) + frac_sec);
  260. return;
  261. }
  262. format |= VERBOSE_FIXED_TIME; /* fallback if hours needed */
  263. }
  264. if ((format & VERBOSE_FIXED_TIME) || tv->tv_sec) {
  265. snprintf(ts, size, "%u:%02u:%05.2f",
  266. (unsigned int) HOURS(tv->tv_sec),
  267. (unsigned int) MINUTES(tv->tv_sec),
  268. SECONDS(tv->tv_sec) + frac_sec);
  269. } else {
  270. snprintf(ts, size, "%05.2f sec", frac_sec);
  271. }
  272. }
  273. /*
  274. * Parse the pattern argument to various sub-commands.
  275. *
  276. * Because the pattern is used as an argument to memset it must evaluate
  277. * to an unsigned integer that fits into a single byte.
  278. */
  279. static int parse_pattern(const char *arg)
  280. {
  281. char *endptr = NULL;
  282. long pattern;
  283. pattern = strtol(arg, &endptr, 0);
  284. if (pattern < 0 || pattern > UCHAR_MAX || *endptr != '\0') {
  285. printf("%s is not a valid pattern byte\n", arg);
  286. return -1;
  287. }
  288. return pattern;
  289. }
  290. /*
  291. * Memory allocation helpers.
  292. *
  293. * Make sure memory is aligned by default, or purposefully misaligned if
  294. * that is specified on the command line.
  295. */
  296. #define MISALIGN_OFFSET 16
  297. static void *qemu_io_alloc(BlockBackend *blk, size_t len, int pattern)
  298. {
  299. void *buf;
  300. if (qemuio_misalign) {
  301. len += MISALIGN_OFFSET;
  302. }
  303. buf = blk_blockalign(blk, len);
  304. memset(buf, pattern, len);
  305. if (qemuio_misalign) {
  306. buf += MISALIGN_OFFSET;
  307. }
  308. return buf;
  309. }
  310. static void qemu_io_free(void *p)
  311. {
  312. if (qemuio_misalign) {
  313. p -= MISALIGN_OFFSET;
  314. }
  315. qemu_vfree(p);
  316. }
  317. /*
  318. * qemu_io_alloc_from_file()
  319. *
  320. * Allocates the buffer and populates it with the content of the given file
  321. * up to @len bytes. If the file length is less than @len, then the buffer
  322. * is populated with the file content cyclically.
  323. *
  324. * @blk - the block backend where the buffer content is going to be written to
  325. * @len - the buffer length
  326. * @file_name - the file to read the content from
  327. *
  328. * Returns: the buffer pointer on success
  329. * NULL on error
  330. */
  331. static void *qemu_io_alloc_from_file(BlockBackend *blk, size_t len,
  332. const char *file_name)
  333. {
  334. char *buf, *buf_origin;
  335. FILE *f = fopen(file_name, "r");
  336. int pattern_len;
  337. if (!f) {
  338. perror(file_name);
  339. return NULL;
  340. }
  341. if (qemuio_misalign) {
  342. len += MISALIGN_OFFSET;
  343. }
  344. buf_origin = buf = blk_blockalign(blk, len);
  345. if (qemuio_misalign) {
  346. buf_origin += MISALIGN_OFFSET;
  347. buf += MISALIGN_OFFSET;
  348. len -= MISALIGN_OFFSET;
  349. }
  350. pattern_len = fread(buf_origin, 1, len, f);
  351. if (ferror(f)) {
  352. perror(file_name);
  353. goto error;
  354. }
  355. if (pattern_len == 0) {
  356. fprintf(stderr, "%s: file is empty\n", file_name);
  357. goto error;
  358. }
  359. fclose(f);
  360. f = NULL;
  361. if (len > pattern_len) {
  362. len -= pattern_len;
  363. buf += pattern_len;
  364. while (len > 0) {
  365. size_t len_to_copy = MIN(pattern_len, len);
  366. memcpy(buf, buf_origin, len_to_copy);
  367. len -= len_to_copy;
  368. buf += len_to_copy;
  369. }
  370. }
  371. return buf_origin;
  372. error:
  373. qemu_io_free(buf_origin);
  374. if (f) {
  375. fclose(f);
  376. }
  377. return NULL;
  378. }
  379. static void dump_buffer(const void *buffer, int64_t offset, int64_t len)
  380. {
  381. uint64_t i;
  382. int j;
  383. const uint8_t *p;
  384. for (i = 0, p = buffer; i < len; i += 16) {
  385. const uint8_t *s = p;
  386. printf("%08" PRIx64 ": ", offset + i);
  387. for (j = 0; j < 16 && i + j < len; j++, p++) {
  388. printf("%02x ", *p);
  389. }
  390. printf(" ");
  391. for (j = 0; j < 16 && i + j < len; j++, s++) {
  392. if (isalnum(*s)) {
  393. printf("%c", *s);
  394. } else {
  395. printf(".");
  396. }
  397. }
  398. printf("\n");
  399. }
  400. }
  401. static void print_report(const char *op, struct timespec *t, int64_t offset,
  402. int64_t count, int64_t total, int cnt, bool Cflag)
  403. {
  404. char s1[64], s2[64], ts[64];
  405. timestr(t, ts, sizeof(ts), Cflag ? VERBOSE_FIXED_TIME : 0);
  406. if (!Cflag) {
  407. cvtstr((double)total, s1, sizeof(s1));
  408. cvtstr(tdiv((double)total, *t), s2, sizeof(s2));
  409. printf("%s %"PRId64"/%"PRId64" bytes at offset %" PRId64 "\n",
  410. op, total, count, offset);
  411. printf("%s, %d ops; %s (%s/sec and %.4f ops/sec)\n",
  412. s1, cnt, ts, s2, tdiv((double)cnt, *t));
  413. } else {/* bytes,ops,time,bytes/sec,ops/sec */
  414. printf("%"PRId64",%d,%s,%.3f,%.3f\n",
  415. total, cnt, ts,
  416. tdiv((double)total, *t),
  417. tdiv((double)cnt, *t));
  418. }
  419. }
  420. /*
  421. * Parse multiple length statements for vectored I/O, and construct an I/O
  422. * vector matching it.
  423. */
  424. static void *
  425. create_iovec(BlockBackend *blk, QEMUIOVector *qiov, char **argv, int nr_iov,
  426. int pattern)
  427. {
  428. size_t *sizes = g_new0(size_t, nr_iov);
  429. size_t count = 0;
  430. void *buf = NULL;
  431. void *p;
  432. int i;
  433. for (i = 0; i < nr_iov; i++) {
  434. char *arg = argv[i];
  435. int64_t len;
  436. len = cvtnum(arg);
  437. if (len < 0) {
  438. print_cvtnum_err(len, arg);
  439. goto fail;
  440. }
  441. if (len > BDRV_REQUEST_MAX_BYTES) {
  442. printf("Argument '%s' exceeds maximum size %" PRIu64 "\n", arg,
  443. (uint64_t)BDRV_REQUEST_MAX_BYTES);
  444. goto fail;
  445. }
  446. if (count > BDRV_REQUEST_MAX_BYTES - len) {
  447. printf("The total number of bytes exceed the maximum size %" PRIu64
  448. "\n", (uint64_t)BDRV_REQUEST_MAX_BYTES);
  449. goto fail;
  450. }
  451. sizes[i] = len;
  452. count += len;
  453. }
  454. qemu_iovec_init(qiov, nr_iov);
  455. buf = p = qemu_io_alloc(blk, count, pattern);
  456. for (i = 0; i < nr_iov; i++) {
  457. qemu_iovec_add(qiov, p, sizes[i]);
  458. p += sizes[i];
  459. }
  460. fail:
  461. g_free(sizes);
  462. return buf;
  463. }
  464. static int do_pread(BlockBackend *blk, char *buf, int64_t offset,
  465. int64_t bytes, int64_t *total)
  466. {
  467. int ret;
  468. if (bytes > INT_MAX) {
  469. return -ERANGE;
  470. }
  471. ret = blk_pread(blk, offset, bytes, (uint8_t *)buf, 0);
  472. if (ret < 0) {
  473. return ret;
  474. }
  475. *total = bytes;
  476. return 1;
  477. }
  478. static int do_pwrite(BlockBackend *blk, char *buf, int64_t offset,
  479. int64_t bytes, int flags, int64_t *total)
  480. {
  481. int ret;
  482. if (bytes > INT_MAX) {
  483. return -ERANGE;
  484. }
  485. ret = blk_pwrite(blk, offset, bytes, (uint8_t *)buf, flags);
  486. if (ret < 0) {
  487. return ret;
  488. }
  489. *total = bytes;
  490. return 1;
  491. }
  492. typedef struct {
  493. BlockBackend *blk;
  494. int64_t offset;
  495. int64_t bytes;
  496. int64_t *total;
  497. int flags;
  498. int ret;
  499. bool done;
  500. } CoWriteZeroes;
  501. static void coroutine_fn co_pwrite_zeroes_entry(void *opaque)
  502. {
  503. CoWriteZeroes *data = opaque;
  504. data->ret = blk_co_pwrite_zeroes(data->blk, data->offset, data->bytes,
  505. data->flags);
  506. data->done = true;
  507. if (data->ret < 0) {
  508. *data->total = data->ret;
  509. return;
  510. }
  511. *data->total = data->bytes;
  512. }
  513. static int do_co_pwrite_zeroes(BlockBackend *blk, int64_t offset,
  514. int64_t bytes, int flags, int64_t *total)
  515. {
  516. Coroutine *co;
  517. CoWriteZeroes data = {
  518. .blk = blk,
  519. .offset = offset,
  520. .bytes = bytes,
  521. .total = total,
  522. .flags = flags,
  523. .done = false,
  524. };
  525. co = qemu_coroutine_create(co_pwrite_zeroes_entry, &data);
  526. bdrv_coroutine_enter(blk_bs(blk), co);
  527. while (!data.done) {
  528. aio_poll(blk_get_aio_context(blk), true);
  529. }
  530. if (data.ret < 0) {
  531. return data.ret;
  532. } else {
  533. return 1;
  534. }
  535. }
  536. static int do_write_compressed(BlockBackend *blk, char *buf, int64_t offset,
  537. int64_t bytes, int64_t *total)
  538. {
  539. int ret;
  540. if (bytes > BDRV_REQUEST_MAX_BYTES) {
  541. return -ERANGE;
  542. }
  543. ret = blk_pwrite_compressed(blk, offset, bytes, buf);
  544. if (ret < 0) {
  545. return ret;
  546. }
  547. *total = bytes;
  548. return 1;
  549. }
  550. static int do_load_vmstate(BlockBackend *blk, char *buf, int64_t offset,
  551. int64_t count, int64_t *total)
  552. {
  553. if (count > INT_MAX) {
  554. return -ERANGE;
  555. }
  556. *total = blk_load_vmstate(blk, (uint8_t *)buf, offset, count);
  557. if (*total < 0) {
  558. return *total;
  559. }
  560. return 1;
  561. }
  562. static int do_save_vmstate(BlockBackend *blk, char *buf, int64_t offset,
  563. int64_t count, int64_t *total)
  564. {
  565. if (count > INT_MAX) {
  566. return -ERANGE;
  567. }
  568. *total = blk_save_vmstate(blk, (uint8_t *)buf, offset, count);
  569. if (*total < 0) {
  570. return *total;
  571. }
  572. return 1;
  573. }
  574. #define NOT_DONE 0x7fffffff
  575. static void aio_rw_done(void *opaque, int ret)
  576. {
  577. *(int *)opaque = ret;
  578. }
  579. static int do_aio_readv(BlockBackend *blk, QEMUIOVector *qiov,
  580. int64_t offset, int *total)
  581. {
  582. int async_ret = NOT_DONE;
  583. blk_aio_preadv(blk, offset, qiov, 0, aio_rw_done, &async_ret);
  584. while (async_ret == NOT_DONE) {
  585. main_loop_wait(false);
  586. }
  587. *total = qiov->size;
  588. return async_ret < 0 ? async_ret : 1;
  589. }
  590. static int do_aio_writev(BlockBackend *blk, QEMUIOVector *qiov,
  591. int64_t offset, int flags, int *total)
  592. {
  593. int async_ret = NOT_DONE;
  594. blk_aio_pwritev(blk, offset, qiov, flags, aio_rw_done, &async_ret);
  595. while (async_ret == NOT_DONE) {
  596. main_loop_wait(false);
  597. }
  598. *total = qiov->size;
  599. return async_ret < 0 ? async_ret : 1;
  600. }
  601. static void read_help(void)
  602. {
  603. printf(
  604. "\n"
  605. " reads a range of bytes from the given offset\n"
  606. "\n"
  607. " Example:\n"
  608. " 'read -v 512 1k' - dumps 1 kilobyte read from 512 bytes into the file\n"
  609. "\n"
  610. " Reads a segment of the currently open file, optionally dumping it to the\n"
  611. " standard output stream (with -v option) for subsequent inspection.\n"
  612. " -b, -- read from the VM state rather than the virtual disk\n"
  613. " -C, -- report statistics in a machine parsable format\n"
  614. " -l, -- length for pattern verification (only with -P)\n"
  615. " -p, -- ignored for backwards compatibility\n"
  616. " -P, -- use a pattern to verify read data\n"
  617. " -q, -- quiet mode, do not show I/O statistics\n"
  618. " -s, -- start offset for pattern verification (only with -P)\n"
  619. " -v, -- dump buffer to standard output\n"
  620. "\n");
  621. }
  622. static int read_f(BlockBackend *blk, int argc, char **argv);
  623. static const cmdinfo_t read_cmd = {
  624. .name = "read",
  625. .altname = "r",
  626. .cfunc = read_f,
  627. .argmin = 2,
  628. .argmax = -1,
  629. .args = "[-abCqv] [-P pattern [-s off] [-l len]] off len",
  630. .oneline = "reads a number of bytes at a specified offset",
  631. .help = read_help,
  632. };
  633. static int read_f(BlockBackend *blk, int argc, char **argv)
  634. {
  635. struct timespec t1, t2;
  636. bool Cflag = false, qflag = false, vflag = false;
  637. bool Pflag = false, sflag = false, lflag = false, bflag = false;
  638. int c, cnt, ret;
  639. char *buf;
  640. int64_t offset;
  641. int64_t count;
  642. /* Some compilers get confused and warn if this is not initialized. */
  643. int64_t total = 0;
  644. int pattern = 0;
  645. int64_t pattern_offset = 0, pattern_count = 0;
  646. while ((c = getopt(argc, argv, "bCl:pP:qs:v")) != -1) {
  647. switch (c) {
  648. case 'b':
  649. bflag = true;
  650. break;
  651. case 'C':
  652. Cflag = true;
  653. break;
  654. case 'l':
  655. lflag = true;
  656. pattern_count = cvtnum(optarg);
  657. if (pattern_count < 0) {
  658. print_cvtnum_err(pattern_count, optarg);
  659. return pattern_count;
  660. }
  661. break;
  662. case 'p':
  663. /* Ignored for backwards compatibility */
  664. break;
  665. case 'P':
  666. Pflag = true;
  667. pattern = parse_pattern(optarg);
  668. if (pattern < 0) {
  669. return -EINVAL;
  670. }
  671. break;
  672. case 'q':
  673. qflag = true;
  674. break;
  675. case 's':
  676. sflag = true;
  677. pattern_offset = cvtnum(optarg);
  678. if (pattern_offset < 0) {
  679. print_cvtnum_err(pattern_offset, optarg);
  680. return pattern_offset;
  681. }
  682. break;
  683. case 'v':
  684. vflag = true;
  685. break;
  686. default:
  687. qemuio_command_usage(&read_cmd);
  688. return -EINVAL;
  689. }
  690. }
  691. if (optind != argc - 2) {
  692. qemuio_command_usage(&read_cmd);
  693. return -EINVAL;
  694. }
  695. offset = cvtnum(argv[optind]);
  696. if (offset < 0) {
  697. print_cvtnum_err(offset, argv[optind]);
  698. return offset;
  699. }
  700. optind++;
  701. count = cvtnum(argv[optind]);
  702. if (count < 0) {
  703. print_cvtnum_err(count, argv[optind]);
  704. return count;
  705. } else if (count > BDRV_REQUEST_MAX_BYTES) {
  706. printf("length cannot exceed %" PRIu64 ", given %s\n",
  707. (uint64_t)BDRV_REQUEST_MAX_BYTES, argv[optind]);
  708. return -EINVAL;
  709. }
  710. if (!Pflag && (lflag || sflag)) {
  711. qemuio_command_usage(&read_cmd);
  712. return -EINVAL;
  713. }
  714. if (!lflag) {
  715. pattern_count = count - pattern_offset;
  716. }
  717. if ((pattern_count < 0) || (pattern_count + pattern_offset > count)) {
  718. printf("pattern verification range exceeds end of read data\n");
  719. return -EINVAL;
  720. }
  721. if (bflag) {
  722. if (!QEMU_IS_ALIGNED(offset, BDRV_SECTOR_SIZE)) {
  723. printf("%" PRId64 " is not a sector-aligned value for 'offset'\n",
  724. offset);
  725. return -EINVAL;
  726. }
  727. if (!QEMU_IS_ALIGNED(count, BDRV_SECTOR_SIZE)) {
  728. printf("%"PRId64" is not a sector-aligned value for 'count'\n",
  729. count);
  730. return -EINVAL;
  731. }
  732. }
  733. buf = qemu_io_alloc(blk, count, 0xab);
  734. clock_gettime(CLOCK_MONOTONIC, &t1);
  735. if (bflag) {
  736. ret = do_load_vmstate(blk, buf, offset, count, &total);
  737. } else {
  738. ret = do_pread(blk, buf, offset, count, &total);
  739. }
  740. clock_gettime(CLOCK_MONOTONIC, &t2);
  741. if (ret < 0) {
  742. printf("read failed: %s\n", strerror(-ret));
  743. goto out;
  744. }
  745. cnt = ret;
  746. ret = 0;
  747. if (Pflag) {
  748. void *cmp_buf = g_malloc(pattern_count);
  749. memset(cmp_buf, pattern, pattern_count);
  750. if (memcmp(buf + pattern_offset, cmp_buf, pattern_count)) {
  751. printf("Pattern verification failed at offset %"
  752. PRId64 ", %"PRId64" bytes\n",
  753. offset + pattern_offset, pattern_count);
  754. ret = -EINVAL;
  755. }
  756. g_free(cmp_buf);
  757. }
  758. if (qflag) {
  759. goto out;
  760. }
  761. if (vflag) {
  762. dump_buffer(buf, offset, count);
  763. }
  764. /* Finally, report back -- -C gives a parsable format */
  765. t2 = tsub(t2, t1);
  766. print_report("read", &t2, offset, count, total, cnt, Cflag);
  767. out:
  768. qemu_io_free(buf);
  769. return ret;
  770. }
  771. static void readv_help(void)
  772. {
  773. printf(
  774. "\n"
  775. " reads a range of bytes from the given offset into multiple buffers\n"
  776. "\n"
  777. " Example:\n"
  778. " 'readv -v 512 1k 1k ' - dumps 2 kilobytes read from 512 bytes into the file\n"
  779. "\n"
  780. " Reads a segment of the currently open file, optionally dumping it to the\n"
  781. " standard output stream (with -v option) for subsequent inspection.\n"
  782. " Uses multiple iovec buffers if more than one byte range is specified.\n"
  783. " -C, -- report statistics in a machine parsable format\n"
  784. " -P, -- use a pattern to verify read data\n"
  785. " -v, -- dump buffer to standard output\n"
  786. " -q, -- quiet mode, do not show I/O statistics\n"
  787. "\n");
  788. }
  789. static int readv_f(BlockBackend *blk, int argc, char **argv);
  790. static const cmdinfo_t readv_cmd = {
  791. .name = "readv",
  792. .cfunc = readv_f,
  793. .argmin = 2,
  794. .argmax = -1,
  795. .args = "[-Cqv] [-P pattern] off len [len..]",
  796. .oneline = "reads a number of bytes at a specified offset",
  797. .help = readv_help,
  798. };
  799. static int readv_f(BlockBackend *blk, int argc, char **argv)
  800. {
  801. struct timespec t1, t2;
  802. bool Cflag = false, qflag = false, vflag = false;
  803. int c, cnt, ret;
  804. char *buf;
  805. int64_t offset;
  806. /* Some compilers get confused and warn if this is not initialized. */
  807. int total = 0;
  808. int nr_iov;
  809. QEMUIOVector qiov;
  810. int pattern = 0;
  811. bool Pflag = false;
  812. while ((c = getopt(argc, argv, "CP:qv")) != -1) {
  813. switch (c) {
  814. case 'C':
  815. Cflag = true;
  816. break;
  817. case 'P':
  818. Pflag = true;
  819. pattern = parse_pattern(optarg);
  820. if (pattern < 0) {
  821. return -EINVAL;
  822. }
  823. break;
  824. case 'q':
  825. qflag = true;
  826. break;
  827. case 'v':
  828. vflag = true;
  829. break;
  830. default:
  831. qemuio_command_usage(&readv_cmd);
  832. return -EINVAL;
  833. }
  834. }
  835. if (optind > argc - 2) {
  836. qemuio_command_usage(&readv_cmd);
  837. return -EINVAL;
  838. }
  839. offset = cvtnum(argv[optind]);
  840. if (offset < 0) {
  841. print_cvtnum_err(offset, argv[optind]);
  842. return offset;
  843. }
  844. optind++;
  845. nr_iov = argc - optind;
  846. buf = create_iovec(blk, &qiov, &argv[optind], nr_iov, 0xab);
  847. if (buf == NULL) {
  848. return -EINVAL;
  849. }
  850. clock_gettime(CLOCK_MONOTONIC, &t1);
  851. ret = do_aio_readv(blk, &qiov, offset, &total);
  852. clock_gettime(CLOCK_MONOTONIC, &t2);
  853. if (ret < 0) {
  854. printf("readv failed: %s\n", strerror(-ret));
  855. goto out;
  856. }
  857. cnt = ret;
  858. ret = 0;
  859. if (Pflag) {
  860. void *cmp_buf = g_malloc(qiov.size);
  861. memset(cmp_buf, pattern, qiov.size);
  862. if (memcmp(buf, cmp_buf, qiov.size)) {
  863. printf("Pattern verification failed at offset %"
  864. PRId64 ", %zu bytes\n", offset, qiov.size);
  865. ret = -EINVAL;
  866. }
  867. g_free(cmp_buf);
  868. }
  869. if (qflag) {
  870. goto out;
  871. }
  872. if (vflag) {
  873. dump_buffer(buf, offset, qiov.size);
  874. }
  875. /* Finally, report back -- -C gives a parsable format */
  876. t2 = tsub(t2, t1);
  877. print_report("read", &t2, offset, qiov.size, total, cnt, Cflag);
  878. out:
  879. qemu_iovec_destroy(&qiov);
  880. qemu_io_free(buf);
  881. return ret;
  882. }
  883. static void write_help(void)
  884. {
  885. printf(
  886. "\n"
  887. " writes a range of bytes from the given offset\n"
  888. "\n"
  889. " Example:\n"
  890. " 'write 512 1k' - writes 1 kilobyte at 512 bytes into the open file\n"
  891. "\n"
  892. " Writes into a segment of the currently open file, using a buffer\n"
  893. " filled with a set pattern (0xcdcdcdcd).\n"
  894. " -b, -- write to the VM state rather than the virtual disk\n"
  895. " -c, -- write compressed data with blk_write_compressed\n"
  896. " -f, -- use Force Unit Access semantics\n"
  897. " -n, -- with -z, don't allow slow fallback\n"
  898. " -p, -- ignored for backwards compatibility\n"
  899. " -P, -- use different pattern to fill file\n"
  900. " -s, -- use a pattern file to fill the write buffer\n"
  901. " -C, -- report statistics in a machine parsable format\n"
  902. " -q, -- quiet mode, do not show I/O statistics\n"
  903. " -u, -- with -z, allow unmapping\n"
  904. " -z, -- write zeroes using blk_co_pwrite_zeroes\n"
  905. "\n");
  906. }
  907. static int write_f(BlockBackend *blk, int argc, char **argv);
  908. static const cmdinfo_t write_cmd = {
  909. .name = "write",
  910. .altname = "w",
  911. .cfunc = write_f,
  912. .perm = BLK_PERM_WRITE,
  913. .argmin = 2,
  914. .argmax = -1,
  915. .args = "[-bcCfnquz] [-P pattern | -s source_file] off len",
  916. .oneline = "writes a number of bytes at a specified offset",
  917. .help = write_help,
  918. };
  919. static int write_f(BlockBackend *blk, int argc, char **argv)
  920. {
  921. struct timespec t1, t2;
  922. bool Cflag = false, qflag = false, bflag = false;
  923. bool Pflag = false, zflag = false, cflag = false, sflag = false;
  924. int flags = 0;
  925. int c, cnt, ret;
  926. char *buf = NULL;
  927. int64_t offset;
  928. int64_t count;
  929. /* Some compilers get confused and warn if this is not initialized. */
  930. int64_t total = 0;
  931. int pattern = 0xcd;
  932. const char *file_name = NULL;
  933. while ((c = getopt(argc, argv, "bcCfnpP:qs:uz")) != -1) {
  934. switch (c) {
  935. case 'b':
  936. bflag = true;
  937. break;
  938. case 'c':
  939. cflag = true;
  940. break;
  941. case 'C':
  942. Cflag = true;
  943. break;
  944. case 'f':
  945. flags |= BDRV_REQ_FUA;
  946. break;
  947. case 'n':
  948. flags |= BDRV_REQ_NO_FALLBACK;
  949. break;
  950. case 'p':
  951. /* Ignored for backwards compatibility */
  952. break;
  953. case 'P':
  954. Pflag = true;
  955. pattern = parse_pattern(optarg);
  956. if (pattern < 0) {
  957. return -EINVAL;
  958. }
  959. break;
  960. case 'q':
  961. qflag = true;
  962. break;
  963. case 's':
  964. sflag = true;
  965. file_name = optarg;
  966. break;
  967. case 'u':
  968. flags |= BDRV_REQ_MAY_UNMAP;
  969. break;
  970. case 'z':
  971. zflag = true;
  972. break;
  973. default:
  974. qemuio_command_usage(&write_cmd);
  975. return -EINVAL;
  976. }
  977. }
  978. if (optind != argc - 2) {
  979. qemuio_command_usage(&write_cmd);
  980. return -EINVAL;
  981. }
  982. if (bflag && zflag) {
  983. printf("-b and -z cannot be specified at the same time\n");
  984. return -EINVAL;
  985. }
  986. if ((flags & BDRV_REQ_FUA) && (bflag || cflag)) {
  987. printf("-f and -b or -c cannot be specified at the same time\n");
  988. return -EINVAL;
  989. }
  990. if ((flags & BDRV_REQ_NO_FALLBACK) && !zflag) {
  991. printf("-n requires -z to be specified\n");
  992. return -EINVAL;
  993. }
  994. if ((flags & BDRV_REQ_MAY_UNMAP) && !zflag) {
  995. printf("-u requires -z to be specified\n");
  996. return -EINVAL;
  997. }
  998. if (zflag + Pflag + sflag > 1) {
  999. printf("Only one of -z, -P, and -s "
  1000. "can be specified at the same time\n");
  1001. return -EINVAL;
  1002. }
  1003. offset = cvtnum(argv[optind]);
  1004. if (offset < 0) {
  1005. print_cvtnum_err(offset, argv[optind]);
  1006. return offset;
  1007. }
  1008. optind++;
  1009. count = cvtnum(argv[optind]);
  1010. if (count < 0) {
  1011. print_cvtnum_err(count, argv[optind]);
  1012. return count;
  1013. } else if (count > BDRV_REQUEST_MAX_BYTES &&
  1014. !(flags & BDRV_REQ_NO_FALLBACK)) {
  1015. printf("length cannot exceed %" PRIu64 " without -n, given %s\n",
  1016. (uint64_t)BDRV_REQUEST_MAX_BYTES, argv[optind]);
  1017. return -EINVAL;
  1018. }
  1019. if (bflag || cflag) {
  1020. if (!QEMU_IS_ALIGNED(offset, BDRV_SECTOR_SIZE)) {
  1021. printf("%" PRId64 " is not a sector-aligned value for 'offset'\n",
  1022. offset);
  1023. return -EINVAL;
  1024. }
  1025. if (!QEMU_IS_ALIGNED(count, BDRV_SECTOR_SIZE)) {
  1026. printf("%"PRId64" is not a sector-aligned value for 'count'\n",
  1027. count);
  1028. return -EINVAL;
  1029. }
  1030. }
  1031. if (!zflag) {
  1032. if (sflag) {
  1033. buf = qemu_io_alloc_from_file(blk, count, file_name);
  1034. if (!buf) {
  1035. return -EINVAL;
  1036. }
  1037. } else {
  1038. buf = qemu_io_alloc(blk, count, pattern);
  1039. }
  1040. }
  1041. clock_gettime(CLOCK_MONOTONIC, &t1);
  1042. if (bflag) {
  1043. ret = do_save_vmstate(blk, buf, offset, count, &total);
  1044. } else if (zflag) {
  1045. ret = do_co_pwrite_zeroes(blk, offset, count, flags, &total);
  1046. } else if (cflag) {
  1047. ret = do_write_compressed(blk, buf, offset, count, &total);
  1048. } else {
  1049. ret = do_pwrite(blk, buf, offset, count, flags, &total);
  1050. }
  1051. clock_gettime(CLOCK_MONOTONIC, &t2);
  1052. if (ret < 0) {
  1053. printf("write failed: %s\n", strerror(-ret));
  1054. goto out;
  1055. }
  1056. cnt = ret;
  1057. ret = 0;
  1058. if (qflag) {
  1059. goto out;
  1060. }
  1061. /* Finally, report back -- -C gives a parsable format */
  1062. t2 = tsub(t2, t1);
  1063. print_report("wrote", &t2, offset, count, total, cnt, Cflag);
  1064. out:
  1065. if (!zflag) {
  1066. qemu_io_free(buf);
  1067. }
  1068. return ret;
  1069. }
  1070. static void
  1071. writev_help(void)
  1072. {
  1073. printf(
  1074. "\n"
  1075. " writes a range of bytes from the given offset source from multiple buffers\n"
  1076. "\n"
  1077. " Example:\n"
  1078. " 'writev 512 1k 1k' - writes 2 kilobytes at 512 bytes into the open file\n"
  1079. "\n"
  1080. " Writes into a segment of the currently open file, using a buffer\n"
  1081. " filled with a set pattern (0xcdcdcdcd).\n"
  1082. " -P, -- use different pattern to fill file\n"
  1083. " -C, -- report statistics in a machine parsable format\n"
  1084. " -f, -- use Force Unit Access semantics\n"
  1085. " -q, -- quiet mode, do not show I/O statistics\n"
  1086. "\n");
  1087. }
  1088. static int writev_f(BlockBackend *blk, int argc, char **argv);
  1089. static const cmdinfo_t writev_cmd = {
  1090. .name = "writev",
  1091. .cfunc = writev_f,
  1092. .perm = BLK_PERM_WRITE,
  1093. .argmin = 2,
  1094. .argmax = -1,
  1095. .args = "[-Cfq] [-P pattern] off len [len..]",
  1096. .oneline = "writes a number of bytes at a specified offset",
  1097. .help = writev_help,
  1098. };
  1099. static int writev_f(BlockBackend *blk, int argc, char **argv)
  1100. {
  1101. struct timespec t1, t2;
  1102. bool Cflag = false, qflag = false;
  1103. int flags = 0;
  1104. int c, cnt, ret;
  1105. char *buf;
  1106. int64_t offset;
  1107. /* Some compilers get confused and warn if this is not initialized. */
  1108. int total = 0;
  1109. int nr_iov;
  1110. int pattern = 0xcd;
  1111. QEMUIOVector qiov;
  1112. while ((c = getopt(argc, argv, "CfqP:")) != -1) {
  1113. switch (c) {
  1114. case 'C':
  1115. Cflag = true;
  1116. break;
  1117. case 'f':
  1118. flags |= BDRV_REQ_FUA;
  1119. break;
  1120. case 'q':
  1121. qflag = true;
  1122. break;
  1123. case 'P':
  1124. pattern = parse_pattern(optarg);
  1125. if (pattern < 0) {
  1126. return -EINVAL;
  1127. }
  1128. break;
  1129. default:
  1130. qemuio_command_usage(&writev_cmd);
  1131. return -EINVAL;
  1132. }
  1133. }
  1134. if (optind > argc - 2) {
  1135. qemuio_command_usage(&writev_cmd);
  1136. return -EINVAL;
  1137. }
  1138. offset = cvtnum(argv[optind]);
  1139. if (offset < 0) {
  1140. print_cvtnum_err(offset, argv[optind]);
  1141. return offset;
  1142. }
  1143. optind++;
  1144. nr_iov = argc - optind;
  1145. buf = create_iovec(blk, &qiov, &argv[optind], nr_iov, pattern);
  1146. if (buf == NULL) {
  1147. return -EINVAL;
  1148. }
  1149. clock_gettime(CLOCK_MONOTONIC, &t1);
  1150. ret = do_aio_writev(blk, &qiov, offset, flags, &total);
  1151. clock_gettime(CLOCK_MONOTONIC, &t2);
  1152. if (ret < 0) {
  1153. printf("writev failed: %s\n", strerror(-ret));
  1154. goto out;
  1155. }
  1156. cnt = ret;
  1157. ret = 0;
  1158. if (qflag) {
  1159. goto out;
  1160. }
  1161. /* Finally, report back -- -C gives a parsable format */
  1162. t2 = tsub(t2, t1);
  1163. print_report("wrote", &t2, offset, qiov.size, total, cnt, Cflag);
  1164. out:
  1165. qemu_iovec_destroy(&qiov);
  1166. qemu_io_free(buf);
  1167. return ret;
  1168. }
  1169. struct aio_ctx {
  1170. BlockBackend *blk;
  1171. QEMUIOVector qiov;
  1172. int64_t offset;
  1173. char *buf;
  1174. bool qflag;
  1175. bool vflag;
  1176. bool Cflag;
  1177. bool Pflag;
  1178. bool zflag;
  1179. BlockAcctCookie acct;
  1180. int pattern;
  1181. struct timespec t1;
  1182. };
  1183. static void aio_write_done(void *opaque, int ret)
  1184. {
  1185. struct aio_ctx *ctx = opaque;
  1186. struct timespec t2;
  1187. clock_gettime(CLOCK_MONOTONIC, &t2);
  1188. if (ret < 0) {
  1189. printf("aio_write failed: %s\n", strerror(-ret));
  1190. block_acct_failed(blk_get_stats(ctx->blk), &ctx->acct);
  1191. goto out;
  1192. }
  1193. block_acct_done(blk_get_stats(ctx->blk), &ctx->acct);
  1194. if (ctx->qflag) {
  1195. goto out;
  1196. }
  1197. /* Finally, report back -- -C gives a parsable format */
  1198. t2 = tsub(t2, ctx->t1);
  1199. print_report("wrote", &t2, ctx->offset, ctx->qiov.size,
  1200. ctx->qiov.size, 1, ctx->Cflag);
  1201. out:
  1202. if (!ctx->zflag) {
  1203. qemu_io_free(ctx->buf);
  1204. qemu_iovec_destroy(&ctx->qiov);
  1205. }
  1206. g_free(ctx);
  1207. }
  1208. static void aio_read_done(void *opaque, int ret)
  1209. {
  1210. struct aio_ctx *ctx = opaque;
  1211. struct timespec t2;
  1212. clock_gettime(CLOCK_MONOTONIC, &t2);
  1213. if (ret < 0) {
  1214. printf("readv failed: %s\n", strerror(-ret));
  1215. block_acct_failed(blk_get_stats(ctx->blk), &ctx->acct);
  1216. goto out;
  1217. }
  1218. if (ctx->Pflag) {
  1219. void *cmp_buf = g_malloc(ctx->qiov.size);
  1220. memset(cmp_buf, ctx->pattern, ctx->qiov.size);
  1221. if (memcmp(ctx->buf, cmp_buf, ctx->qiov.size)) {
  1222. printf("Pattern verification failed at offset %"
  1223. PRId64 ", %zu bytes\n", ctx->offset, ctx->qiov.size);
  1224. }
  1225. g_free(cmp_buf);
  1226. }
  1227. block_acct_done(blk_get_stats(ctx->blk), &ctx->acct);
  1228. if (ctx->qflag) {
  1229. goto out;
  1230. }
  1231. if (ctx->vflag) {
  1232. dump_buffer(ctx->buf, ctx->offset, ctx->qiov.size);
  1233. }
  1234. /* Finally, report back -- -C gives a parsable format */
  1235. t2 = tsub(t2, ctx->t1);
  1236. print_report("read", &t2, ctx->offset, ctx->qiov.size,
  1237. ctx->qiov.size, 1, ctx->Cflag);
  1238. out:
  1239. qemu_io_free(ctx->buf);
  1240. qemu_iovec_destroy(&ctx->qiov);
  1241. g_free(ctx);
  1242. }
  1243. static void aio_read_help(void)
  1244. {
  1245. printf(
  1246. "\n"
  1247. " asynchronously reads a range of bytes from the given offset\n"
  1248. "\n"
  1249. " Example:\n"
  1250. " 'aio_read -v 512 1k 1k ' - dumps 2 kilobytes read from 512 bytes into the file\n"
  1251. "\n"
  1252. " Reads a segment of the currently open file, optionally dumping it to the\n"
  1253. " standard output stream (with -v option) for subsequent inspection.\n"
  1254. " The read is performed asynchronously and the aio_flush command must be\n"
  1255. " used to ensure all outstanding aio requests have been completed.\n"
  1256. " Note that due to its asynchronous nature, this command will be\n"
  1257. " considered successful once the request is submitted, independently\n"
  1258. " of potential I/O errors or pattern mismatches.\n"
  1259. " -C, -- report statistics in a machine parsable format\n"
  1260. " -P, -- use a pattern to verify read data\n"
  1261. " -i, -- treat request as invalid, for exercising stats\n"
  1262. " -v, -- dump buffer to standard output\n"
  1263. " -q, -- quiet mode, do not show I/O statistics\n"
  1264. "\n");
  1265. }
  1266. static int aio_read_f(BlockBackend *blk, int argc, char **argv);
  1267. static const cmdinfo_t aio_read_cmd = {
  1268. .name = "aio_read",
  1269. .cfunc = aio_read_f,
  1270. .argmin = 2,
  1271. .argmax = -1,
  1272. .args = "[-Ciqv] [-P pattern] off len [len..]",
  1273. .oneline = "asynchronously reads a number of bytes",
  1274. .help = aio_read_help,
  1275. };
  1276. static int aio_read_f(BlockBackend *blk, int argc, char **argv)
  1277. {
  1278. int nr_iov, c;
  1279. struct aio_ctx *ctx = g_new0(struct aio_ctx, 1);
  1280. ctx->blk = blk;
  1281. while ((c = getopt(argc, argv, "CP:iqv")) != -1) {
  1282. switch (c) {
  1283. case 'C':
  1284. ctx->Cflag = true;
  1285. break;
  1286. case 'P':
  1287. ctx->Pflag = true;
  1288. ctx->pattern = parse_pattern(optarg);
  1289. if (ctx->pattern < 0) {
  1290. g_free(ctx);
  1291. return -EINVAL;
  1292. }
  1293. break;
  1294. case 'i':
  1295. printf("injecting invalid read request\n");
  1296. block_acct_invalid(blk_get_stats(blk), BLOCK_ACCT_READ);
  1297. g_free(ctx);
  1298. return 0;
  1299. case 'q':
  1300. ctx->qflag = true;
  1301. break;
  1302. case 'v':
  1303. ctx->vflag = true;
  1304. break;
  1305. default:
  1306. g_free(ctx);
  1307. qemuio_command_usage(&aio_read_cmd);
  1308. return -EINVAL;
  1309. }
  1310. }
  1311. if (optind > argc - 2) {
  1312. g_free(ctx);
  1313. qemuio_command_usage(&aio_read_cmd);
  1314. return -EINVAL;
  1315. }
  1316. ctx->offset = cvtnum(argv[optind]);
  1317. if (ctx->offset < 0) {
  1318. int ret = ctx->offset;
  1319. print_cvtnum_err(ret, argv[optind]);
  1320. g_free(ctx);
  1321. return ret;
  1322. }
  1323. optind++;
  1324. nr_iov = argc - optind;
  1325. ctx->buf = create_iovec(blk, &ctx->qiov, &argv[optind], nr_iov, 0xab);
  1326. if (ctx->buf == NULL) {
  1327. block_acct_invalid(blk_get_stats(blk), BLOCK_ACCT_READ);
  1328. g_free(ctx);
  1329. return -EINVAL;
  1330. }
  1331. clock_gettime(CLOCK_MONOTONIC, &ctx->t1);
  1332. block_acct_start(blk_get_stats(blk), &ctx->acct, ctx->qiov.size,
  1333. BLOCK_ACCT_READ);
  1334. blk_aio_preadv(blk, ctx->offset, &ctx->qiov, 0, aio_read_done, ctx);
  1335. return 0;
  1336. }
  1337. static void aio_write_help(void)
  1338. {
  1339. printf(
  1340. "\n"
  1341. " asynchronously writes a range of bytes from the given offset source\n"
  1342. " from multiple buffers\n"
  1343. "\n"
  1344. " Example:\n"
  1345. " 'aio_write 512 1k 1k' - writes 2 kilobytes at 512 bytes into the open file\n"
  1346. "\n"
  1347. " Writes into a segment of the currently open file, using a buffer\n"
  1348. " filled with a set pattern (0xcdcdcdcd).\n"
  1349. " The write is performed asynchronously and the aio_flush command must be\n"
  1350. " used to ensure all outstanding aio requests have been completed.\n"
  1351. " Note that due to its asynchronous nature, this command will be\n"
  1352. " considered successful once the request is submitted, independently\n"
  1353. " of potential I/O errors or pattern mismatches.\n"
  1354. " -P, -- use different pattern to fill file\n"
  1355. " -C, -- report statistics in a machine parsable format\n"
  1356. " -f, -- use Force Unit Access semantics\n"
  1357. " -i, -- treat request as invalid, for exercising stats\n"
  1358. " -q, -- quiet mode, do not show I/O statistics\n"
  1359. " -u, -- with -z, allow unmapping\n"
  1360. " -z, -- write zeroes using blk_aio_pwrite_zeroes\n"
  1361. "\n");
  1362. }
  1363. static int aio_write_f(BlockBackend *blk, int argc, char **argv);
  1364. static const cmdinfo_t aio_write_cmd = {
  1365. .name = "aio_write",
  1366. .cfunc = aio_write_f,
  1367. .perm = BLK_PERM_WRITE,
  1368. .argmin = 2,
  1369. .argmax = -1,
  1370. .args = "[-Cfiquz] [-P pattern] off len [len..]",
  1371. .oneline = "asynchronously writes a number of bytes",
  1372. .help = aio_write_help,
  1373. };
  1374. static int aio_write_f(BlockBackend *blk, int argc, char **argv)
  1375. {
  1376. int nr_iov, c;
  1377. int pattern = 0xcd;
  1378. struct aio_ctx *ctx = g_new0(struct aio_ctx, 1);
  1379. int flags = 0;
  1380. ctx->blk = blk;
  1381. while ((c = getopt(argc, argv, "CfiqP:uz")) != -1) {
  1382. switch (c) {
  1383. case 'C':
  1384. ctx->Cflag = true;
  1385. break;
  1386. case 'f':
  1387. flags |= BDRV_REQ_FUA;
  1388. break;
  1389. case 'q':
  1390. ctx->qflag = true;
  1391. break;
  1392. case 'u':
  1393. flags |= BDRV_REQ_MAY_UNMAP;
  1394. break;
  1395. case 'P':
  1396. pattern = parse_pattern(optarg);
  1397. if (pattern < 0) {
  1398. g_free(ctx);
  1399. return -EINVAL;
  1400. }
  1401. break;
  1402. case 'i':
  1403. printf("injecting invalid write request\n");
  1404. block_acct_invalid(blk_get_stats(blk), BLOCK_ACCT_WRITE);
  1405. g_free(ctx);
  1406. return 0;
  1407. case 'z':
  1408. ctx->zflag = true;
  1409. break;
  1410. default:
  1411. g_free(ctx);
  1412. qemuio_command_usage(&aio_write_cmd);
  1413. return -EINVAL;
  1414. }
  1415. }
  1416. if (optind > argc - 2) {
  1417. g_free(ctx);
  1418. qemuio_command_usage(&aio_write_cmd);
  1419. return -EINVAL;
  1420. }
  1421. if (ctx->zflag && optind != argc - 2) {
  1422. printf("-z supports only a single length parameter\n");
  1423. g_free(ctx);
  1424. return -EINVAL;
  1425. }
  1426. if ((flags & BDRV_REQ_MAY_UNMAP) && !ctx->zflag) {
  1427. printf("-u requires -z to be specified\n");
  1428. g_free(ctx);
  1429. return -EINVAL;
  1430. }
  1431. if (ctx->zflag && ctx->Pflag) {
  1432. printf("-z and -P cannot be specified at the same time\n");
  1433. g_free(ctx);
  1434. return -EINVAL;
  1435. }
  1436. ctx->offset = cvtnum(argv[optind]);
  1437. if (ctx->offset < 0) {
  1438. int ret = ctx->offset;
  1439. print_cvtnum_err(ret, argv[optind]);
  1440. g_free(ctx);
  1441. return ret;
  1442. }
  1443. optind++;
  1444. if (ctx->zflag) {
  1445. int64_t count = cvtnum(argv[optind]);
  1446. if (count < 0) {
  1447. print_cvtnum_err(count, argv[optind]);
  1448. g_free(ctx);
  1449. return count;
  1450. }
  1451. ctx->qiov.size = count;
  1452. blk_aio_pwrite_zeroes(blk, ctx->offset, count, flags, aio_write_done,
  1453. ctx);
  1454. } else {
  1455. nr_iov = argc - optind;
  1456. ctx->buf = create_iovec(blk, &ctx->qiov, &argv[optind], nr_iov,
  1457. pattern);
  1458. if (ctx->buf == NULL) {
  1459. block_acct_invalid(blk_get_stats(blk), BLOCK_ACCT_WRITE);
  1460. g_free(ctx);
  1461. return -EINVAL;
  1462. }
  1463. clock_gettime(CLOCK_MONOTONIC, &ctx->t1);
  1464. block_acct_start(blk_get_stats(blk), &ctx->acct, ctx->qiov.size,
  1465. BLOCK_ACCT_WRITE);
  1466. blk_aio_pwritev(blk, ctx->offset, &ctx->qiov, flags, aio_write_done,
  1467. ctx);
  1468. }
  1469. return 0;
  1470. }
  1471. static int aio_flush_f(BlockBackend *blk, int argc, char **argv)
  1472. {
  1473. BlockAcctCookie cookie;
  1474. block_acct_start(blk_get_stats(blk), &cookie, 0, BLOCK_ACCT_FLUSH);
  1475. blk_drain_all();
  1476. block_acct_done(blk_get_stats(blk), &cookie);
  1477. return 0;
  1478. }
  1479. static const cmdinfo_t aio_flush_cmd = {
  1480. .name = "aio_flush",
  1481. .cfunc = aio_flush_f,
  1482. .oneline = "completes all outstanding aio requests"
  1483. };
  1484. static int flush_f(BlockBackend *blk, int argc, char **argv)
  1485. {
  1486. return blk_flush(blk);
  1487. }
  1488. static const cmdinfo_t flush_cmd = {
  1489. .name = "flush",
  1490. .altname = "f",
  1491. .cfunc = flush_f,
  1492. .oneline = "flush all in-core file state to disk",
  1493. };
  1494. static int truncate_f(BlockBackend *blk, int argc, char **argv);
  1495. static const cmdinfo_t truncate_cmd = {
  1496. .name = "truncate",
  1497. .altname = "t",
  1498. .cfunc = truncate_f,
  1499. .perm = BLK_PERM_WRITE | BLK_PERM_RESIZE,
  1500. .argmin = 1,
  1501. .argmax = 3,
  1502. .args = "[-m prealloc_mode] off",
  1503. .oneline = "truncates the current file at the given offset",
  1504. };
  1505. static int truncate_f(BlockBackend *blk, int argc, char **argv)
  1506. {
  1507. Error *local_err = NULL;
  1508. int64_t offset;
  1509. int c, ret;
  1510. PreallocMode prealloc = PREALLOC_MODE_OFF;
  1511. while ((c = getopt(argc, argv, "m:")) != -1) {
  1512. switch (c) {
  1513. case 'm':
  1514. prealloc = qapi_enum_parse(&PreallocMode_lookup, optarg,
  1515. PREALLOC_MODE__MAX, NULL);
  1516. if (prealloc == PREALLOC_MODE__MAX) {
  1517. error_report("Invalid preallocation mode '%s'", optarg);
  1518. return -EINVAL;
  1519. }
  1520. break;
  1521. default:
  1522. qemuio_command_usage(&truncate_cmd);
  1523. return -EINVAL;
  1524. }
  1525. }
  1526. offset = cvtnum(argv[optind]);
  1527. if (offset < 0) {
  1528. print_cvtnum_err(offset, argv[1]);
  1529. return offset;
  1530. }
  1531. /*
  1532. * qemu-io is a debugging tool, so let us be strict here and pass
  1533. * exact=true. It is better to err on the "emit more errors" side
  1534. * than to be overly permissive.
  1535. */
  1536. ret = blk_truncate(blk, offset, false, prealloc, 0, &local_err);
  1537. if (ret < 0) {
  1538. error_report_err(local_err);
  1539. return ret;
  1540. }
  1541. return 0;
  1542. }
  1543. static int length_f(BlockBackend *blk, int argc, char **argv)
  1544. {
  1545. int64_t size;
  1546. char s1[64];
  1547. size = blk_getlength(blk);
  1548. if (size < 0) {
  1549. printf("getlength: %s\n", strerror(-size));
  1550. return size;
  1551. }
  1552. cvtstr(size, s1, sizeof(s1));
  1553. printf("%s\n", s1);
  1554. return 0;
  1555. }
  1556. static const cmdinfo_t length_cmd = {
  1557. .name = "length",
  1558. .altname = "l",
  1559. .cfunc = length_f,
  1560. .oneline = "gets the length of the current file",
  1561. };
  1562. static int info_f(BlockBackend *blk, int argc, char **argv)
  1563. {
  1564. BlockDriverState *bs = blk_bs(blk);
  1565. BlockDriverInfo bdi;
  1566. ImageInfoSpecific *spec_info;
  1567. Error *local_err = NULL;
  1568. char s1[64], s2[64];
  1569. int ret;
  1570. if (bs->drv && bs->drv->format_name) {
  1571. printf("format name: %s\n", bs->drv->format_name);
  1572. }
  1573. if (bs->drv && bs->drv->protocol_name) {
  1574. printf("format name: %s\n", bs->drv->protocol_name);
  1575. }
  1576. ret = bdrv_get_info(bs, &bdi);
  1577. if (ret) {
  1578. return ret;
  1579. }
  1580. cvtstr(bdi.cluster_size, s1, sizeof(s1));
  1581. cvtstr(bdi.vm_state_offset, s2, sizeof(s2));
  1582. printf("cluster size: %s\n", s1);
  1583. printf("vm state offset: %s\n", s2);
  1584. spec_info = bdrv_get_specific_info(bs, &local_err);
  1585. if (local_err) {
  1586. error_report_err(local_err);
  1587. return -EIO;
  1588. }
  1589. if (spec_info) {
  1590. printf("Format specific information:\n");
  1591. bdrv_image_info_specific_dump(spec_info);
  1592. qapi_free_ImageInfoSpecific(spec_info);
  1593. }
  1594. return 0;
  1595. }
  1596. static const cmdinfo_t info_cmd = {
  1597. .name = "info",
  1598. .altname = "i",
  1599. .cfunc = info_f,
  1600. .oneline = "prints information about the current file",
  1601. };
  1602. static void discard_help(void)
  1603. {
  1604. printf(
  1605. "\n"
  1606. " discards a range of bytes from the given offset\n"
  1607. "\n"
  1608. " Example:\n"
  1609. " 'discard 512 1k' - discards 1 kilobyte from 512 bytes into the file\n"
  1610. "\n"
  1611. " Discards a segment of the currently open file.\n"
  1612. " -C, -- report statistics in a machine parsable format\n"
  1613. " -q, -- quiet mode, do not show I/O statistics\n"
  1614. "\n");
  1615. }
  1616. static int discard_f(BlockBackend *blk, int argc, char **argv);
  1617. static const cmdinfo_t discard_cmd = {
  1618. .name = "discard",
  1619. .altname = "d",
  1620. .cfunc = discard_f,
  1621. .perm = BLK_PERM_WRITE,
  1622. .argmin = 2,
  1623. .argmax = -1,
  1624. .args = "[-Cq] off len",
  1625. .oneline = "discards a number of bytes at a specified offset",
  1626. .help = discard_help,
  1627. };
  1628. static int discard_f(BlockBackend *blk, int argc, char **argv)
  1629. {
  1630. struct timespec t1, t2;
  1631. bool Cflag = false, qflag = false;
  1632. int c, ret;
  1633. int64_t offset, bytes;
  1634. while ((c = getopt(argc, argv, "Cq")) != -1) {
  1635. switch (c) {
  1636. case 'C':
  1637. Cflag = true;
  1638. break;
  1639. case 'q':
  1640. qflag = true;
  1641. break;
  1642. default:
  1643. qemuio_command_usage(&discard_cmd);
  1644. return -EINVAL;
  1645. }
  1646. }
  1647. if (optind != argc - 2) {
  1648. qemuio_command_usage(&discard_cmd);
  1649. return -EINVAL;
  1650. }
  1651. offset = cvtnum(argv[optind]);
  1652. if (offset < 0) {
  1653. print_cvtnum_err(offset, argv[optind]);
  1654. return offset;
  1655. }
  1656. optind++;
  1657. bytes = cvtnum(argv[optind]);
  1658. if (bytes < 0) {
  1659. print_cvtnum_err(bytes, argv[optind]);
  1660. return bytes;
  1661. } else if (bytes > BDRV_REQUEST_MAX_BYTES) {
  1662. printf("length cannot exceed %"PRIu64", given %s\n",
  1663. (uint64_t)BDRV_REQUEST_MAX_BYTES, argv[optind]);
  1664. return -EINVAL;
  1665. }
  1666. clock_gettime(CLOCK_MONOTONIC, &t1);
  1667. ret = blk_pdiscard(blk, offset, bytes);
  1668. clock_gettime(CLOCK_MONOTONIC, &t2);
  1669. if (ret < 0) {
  1670. printf("discard failed: %s\n", strerror(-ret));
  1671. return ret;
  1672. }
  1673. /* Finally, report back -- -C gives a parsable format */
  1674. if (!qflag) {
  1675. t2 = tsub(t2, t1);
  1676. print_report("discard", &t2, offset, bytes, bytes, 1, Cflag);
  1677. }
  1678. return 0;
  1679. }
  1680. static int alloc_f(BlockBackend *blk, int argc, char **argv)
  1681. {
  1682. BlockDriverState *bs = blk_bs(blk);
  1683. int64_t offset, start, remaining, count;
  1684. char s1[64];
  1685. int ret;
  1686. int64_t num, sum_alloc;
  1687. start = offset = cvtnum(argv[1]);
  1688. if (offset < 0) {
  1689. print_cvtnum_err(offset, argv[1]);
  1690. return offset;
  1691. }
  1692. if (argc == 3) {
  1693. count = cvtnum(argv[2]);
  1694. if (count < 0) {
  1695. print_cvtnum_err(count, argv[2]);
  1696. return count;
  1697. }
  1698. } else {
  1699. count = BDRV_SECTOR_SIZE;
  1700. }
  1701. remaining = count;
  1702. sum_alloc = 0;
  1703. while (remaining) {
  1704. ret = bdrv_is_allocated(bs, offset, remaining, &num);
  1705. if (ret < 0) {
  1706. printf("is_allocated failed: %s\n", strerror(-ret));
  1707. return ret;
  1708. }
  1709. offset += num;
  1710. remaining -= num;
  1711. if (ret) {
  1712. sum_alloc += num;
  1713. }
  1714. if (num == 0) {
  1715. count -= remaining;
  1716. remaining = 0;
  1717. }
  1718. }
  1719. cvtstr(start, s1, sizeof(s1));
  1720. printf("%"PRId64"/%"PRId64" bytes allocated at offset %s\n",
  1721. sum_alloc, count, s1);
  1722. return 0;
  1723. }
  1724. static const cmdinfo_t alloc_cmd = {
  1725. .name = "alloc",
  1726. .altname = "a",
  1727. .argmin = 1,
  1728. .argmax = 2,
  1729. .cfunc = alloc_f,
  1730. .args = "offset [count]",
  1731. .oneline = "checks if offset is allocated in the file",
  1732. };
  1733. static int map_is_allocated(BlockDriverState *bs, int64_t offset,
  1734. int64_t bytes, int64_t *pnum)
  1735. {
  1736. int64_t num;
  1737. int ret, firstret;
  1738. ret = bdrv_is_allocated(bs, offset, bytes, &num);
  1739. if (ret < 0) {
  1740. return ret;
  1741. }
  1742. firstret = ret;
  1743. *pnum = num;
  1744. while (bytes > 0 && ret == firstret) {
  1745. offset += num;
  1746. bytes -= num;
  1747. ret = bdrv_is_allocated(bs, offset, bytes, &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. }