2
0

qemu-io-cmds.c 65 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515
  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. if (bytes > INT_MAX) {
  468. return -ERANGE;
  469. }
  470. *total = blk_pread(blk, offset, (uint8_t *)buf, bytes);
  471. if (*total < 0) {
  472. return *total;
  473. }
  474. return 1;
  475. }
  476. static int do_pwrite(BlockBackend *blk, char *buf, int64_t offset,
  477. int64_t bytes, int flags, int64_t *total)
  478. {
  479. if (bytes > INT_MAX) {
  480. return -ERANGE;
  481. }
  482. *total = blk_pwrite(blk, offset, (uint8_t *)buf, bytes, flags);
  483. if (*total < 0) {
  484. return *total;
  485. }
  486. return 1;
  487. }
  488. typedef struct {
  489. BlockBackend *blk;
  490. int64_t offset;
  491. int64_t bytes;
  492. int64_t *total;
  493. int flags;
  494. int ret;
  495. bool done;
  496. } CoWriteZeroes;
  497. static void coroutine_fn co_pwrite_zeroes_entry(void *opaque)
  498. {
  499. CoWriteZeroes *data = opaque;
  500. data->ret = blk_co_pwrite_zeroes(data->blk, data->offset, data->bytes,
  501. data->flags);
  502. data->done = true;
  503. if (data->ret < 0) {
  504. *data->total = data->ret;
  505. return;
  506. }
  507. *data->total = data->bytes;
  508. }
  509. static int do_co_pwrite_zeroes(BlockBackend *blk, int64_t offset,
  510. int64_t bytes, int flags, int64_t *total)
  511. {
  512. Coroutine *co;
  513. CoWriteZeroes data = {
  514. .blk = blk,
  515. .offset = offset,
  516. .bytes = bytes,
  517. .total = total,
  518. .flags = flags,
  519. .done = false,
  520. };
  521. co = qemu_coroutine_create(co_pwrite_zeroes_entry, &data);
  522. bdrv_coroutine_enter(blk_bs(blk), co);
  523. while (!data.done) {
  524. aio_poll(blk_get_aio_context(blk), true);
  525. }
  526. if (data.ret < 0) {
  527. return data.ret;
  528. } else {
  529. return 1;
  530. }
  531. }
  532. static int do_write_compressed(BlockBackend *blk, char *buf, int64_t offset,
  533. int64_t bytes, int64_t *total)
  534. {
  535. int ret;
  536. if (bytes > BDRV_REQUEST_MAX_BYTES) {
  537. return -ERANGE;
  538. }
  539. ret = blk_pwrite_compressed(blk, offset, buf, bytes);
  540. if (ret < 0) {
  541. return ret;
  542. }
  543. *total = bytes;
  544. return 1;
  545. }
  546. static int do_load_vmstate(BlockBackend *blk, char *buf, int64_t offset,
  547. int64_t count, int64_t *total)
  548. {
  549. if (count > INT_MAX) {
  550. return -ERANGE;
  551. }
  552. *total = blk_load_vmstate(blk, (uint8_t *)buf, offset, count);
  553. if (*total < 0) {
  554. return *total;
  555. }
  556. return 1;
  557. }
  558. static int do_save_vmstate(BlockBackend *blk, char *buf, int64_t offset,
  559. int64_t count, int64_t *total)
  560. {
  561. if (count > INT_MAX) {
  562. return -ERANGE;
  563. }
  564. *total = blk_save_vmstate(blk, (uint8_t *)buf, offset, count);
  565. if (*total < 0) {
  566. return *total;
  567. }
  568. return 1;
  569. }
  570. #define NOT_DONE 0x7fffffff
  571. static void aio_rw_done(void *opaque, int ret)
  572. {
  573. *(int *)opaque = ret;
  574. }
  575. static int do_aio_readv(BlockBackend *blk, QEMUIOVector *qiov,
  576. int64_t offset, int *total)
  577. {
  578. int async_ret = NOT_DONE;
  579. blk_aio_preadv(blk, offset, qiov, 0, aio_rw_done, &async_ret);
  580. while (async_ret == NOT_DONE) {
  581. main_loop_wait(false);
  582. }
  583. *total = qiov->size;
  584. return async_ret < 0 ? async_ret : 1;
  585. }
  586. static int do_aio_writev(BlockBackend *blk, QEMUIOVector *qiov,
  587. int64_t offset, int flags, int *total)
  588. {
  589. int async_ret = NOT_DONE;
  590. blk_aio_pwritev(blk, offset, qiov, flags, aio_rw_done, &async_ret);
  591. while (async_ret == NOT_DONE) {
  592. main_loop_wait(false);
  593. }
  594. *total = qiov->size;
  595. return async_ret < 0 ? async_ret : 1;
  596. }
  597. static void read_help(void)
  598. {
  599. printf(
  600. "\n"
  601. " reads a range of bytes from the given offset\n"
  602. "\n"
  603. " Example:\n"
  604. " 'read -v 512 1k' - dumps 1 kilobyte read from 512 bytes into the file\n"
  605. "\n"
  606. " Reads a segment of the currently open file, optionally dumping it to the\n"
  607. " standard output stream (with -v option) for subsequent inspection.\n"
  608. " -b, -- read from the VM state rather than the virtual disk\n"
  609. " -C, -- report statistics in a machine parsable format\n"
  610. " -l, -- length for pattern verification (only with -P)\n"
  611. " -p, -- ignored for backwards compatibility\n"
  612. " -P, -- use a pattern to verify read data\n"
  613. " -q, -- quiet mode, do not show I/O statistics\n"
  614. " -s, -- start offset for pattern verification (only with -P)\n"
  615. " -v, -- dump buffer to standard output\n"
  616. "\n");
  617. }
  618. static int read_f(BlockBackend *blk, int argc, char **argv);
  619. static const cmdinfo_t read_cmd = {
  620. .name = "read",
  621. .altname = "r",
  622. .cfunc = read_f,
  623. .argmin = 2,
  624. .argmax = -1,
  625. .args = "[-abCqv] [-P pattern [-s off] [-l len]] off len",
  626. .oneline = "reads a number of bytes at a specified offset",
  627. .help = read_help,
  628. };
  629. static int read_f(BlockBackend *blk, int argc, char **argv)
  630. {
  631. struct timespec t1, t2;
  632. bool Cflag = false, qflag = false, vflag = false;
  633. bool Pflag = false, sflag = false, lflag = false, bflag = false;
  634. int c, cnt, ret;
  635. char *buf;
  636. int64_t offset;
  637. int64_t count;
  638. /* Some compilers get confused and warn if this is not initialized. */
  639. int64_t total = 0;
  640. int pattern = 0;
  641. int64_t pattern_offset = 0, pattern_count = 0;
  642. while ((c = getopt(argc, argv, "bCl:pP:qs:v")) != -1) {
  643. switch (c) {
  644. case 'b':
  645. bflag = true;
  646. break;
  647. case 'C':
  648. Cflag = true;
  649. break;
  650. case 'l':
  651. lflag = true;
  652. pattern_count = cvtnum(optarg);
  653. if (pattern_count < 0) {
  654. print_cvtnum_err(pattern_count, optarg);
  655. return pattern_count;
  656. }
  657. break;
  658. case 'p':
  659. /* Ignored for backwards compatibility */
  660. break;
  661. case 'P':
  662. Pflag = true;
  663. pattern = parse_pattern(optarg);
  664. if (pattern < 0) {
  665. return -EINVAL;
  666. }
  667. break;
  668. case 'q':
  669. qflag = true;
  670. break;
  671. case 's':
  672. sflag = true;
  673. pattern_offset = cvtnum(optarg);
  674. if (pattern_offset < 0) {
  675. print_cvtnum_err(pattern_offset, optarg);
  676. return pattern_offset;
  677. }
  678. break;
  679. case 'v':
  680. vflag = true;
  681. break;
  682. default:
  683. qemuio_command_usage(&read_cmd);
  684. return -EINVAL;
  685. }
  686. }
  687. if (optind != argc - 2) {
  688. qemuio_command_usage(&read_cmd);
  689. return -EINVAL;
  690. }
  691. offset = cvtnum(argv[optind]);
  692. if (offset < 0) {
  693. print_cvtnum_err(offset, argv[optind]);
  694. return offset;
  695. }
  696. optind++;
  697. count = cvtnum(argv[optind]);
  698. if (count < 0) {
  699. print_cvtnum_err(count, argv[optind]);
  700. return count;
  701. } else if (count > BDRV_REQUEST_MAX_BYTES) {
  702. printf("length cannot exceed %" PRIu64 ", given %s\n",
  703. (uint64_t)BDRV_REQUEST_MAX_BYTES, argv[optind]);
  704. return -EINVAL;
  705. }
  706. if (!Pflag && (lflag || sflag)) {
  707. qemuio_command_usage(&read_cmd);
  708. return -EINVAL;
  709. }
  710. if (!lflag) {
  711. pattern_count = count - pattern_offset;
  712. }
  713. if ((pattern_count < 0) || (pattern_count + pattern_offset > count)) {
  714. printf("pattern verification range exceeds end of read data\n");
  715. return -EINVAL;
  716. }
  717. if (bflag) {
  718. if (!QEMU_IS_ALIGNED(offset, BDRV_SECTOR_SIZE)) {
  719. printf("%" PRId64 " is not a sector-aligned value for 'offset'\n",
  720. offset);
  721. return -EINVAL;
  722. }
  723. if (!QEMU_IS_ALIGNED(count, BDRV_SECTOR_SIZE)) {
  724. printf("%"PRId64" is not a sector-aligned value for 'count'\n",
  725. count);
  726. return -EINVAL;
  727. }
  728. }
  729. buf = qemu_io_alloc(blk, count, 0xab);
  730. clock_gettime(CLOCK_MONOTONIC, &t1);
  731. if (bflag) {
  732. ret = do_load_vmstate(blk, buf, offset, count, &total);
  733. } else {
  734. ret = do_pread(blk, buf, offset, count, &total);
  735. }
  736. clock_gettime(CLOCK_MONOTONIC, &t2);
  737. if (ret < 0) {
  738. printf("read failed: %s\n", strerror(-ret));
  739. goto out;
  740. }
  741. cnt = ret;
  742. ret = 0;
  743. if (Pflag) {
  744. void *cmp_buf = g_malloc(pattern_count);
  745. memset(cmp_buf, pattern, pattern_count);
  746. if (memcmp(buf + pattern_offset, cmp_buf, pattern_count)) {
  747. printf("Pattern verification failed at offset %"
  748. PRId64 ", %"PRId64" bytes\n",
  749. offset + pattern_offset, pattern_count);
  750. ret = -EINVAL;
  751. }
  752. g_free(cmp_buf);
  753. }
  754. if (qflag) {
  755. goto out;
  756. }
  757. if (vflag) {
  758. dump_buffer(buf, offset, count);
  759. }
  760. /* Finally, report back -- -C gives a parsable format */
  761. t2 = tsub(t2, t1);
  762. print_report("read", &t2, offset, count, total, cnt, Cflag);
  763. out:
  764. qemu_io_free(buf);
  765. return ret;
  766. }
  767. static void readv_help(void)
  768. {
  769. printf(
  770. "\n"
  771. " reads a range of bytes from the given offset into multiple buffers\n"
  772. "\n"
  773. " Example:\n"
  774. " 'readv -v 512 1k 1k ' - dumps 2 kilobytes read from 512 bytes into the file\n"
  775. "\n"
  776. " Reads a segment of the currently open file, optionally dumping it to the\n"
  777. " standard output stream (with -v option) for subsequent inspection.\n"
  778. " Uses multiple iovec buffers if more than one byte range is specified.\n"
  779. " -C, -- report statistics in a machine parsable format\n"
  780. " -P, -- use a pattern to verify read data\n"
  781. " -v, -- dump buffer to standard output\n"
  782. " -q, -- quiet mode, do not show I/O statistics\n"
  783. "\n");
  784. }
  785. static int readv_f(BlockBackend *blk, int argc, char **argv);
  786. static const cmdinfo_t readv_cmd = {
  787. .name = "readv",
  788. .cfunc = readv_f,
  789. .argmin = 2,
  790. .argmax = -1,
  791. .args = "[-Cqv] [-P pattern] off len [len..]",
  792. .oneline = "reads a number of bytes at a specified offset",
  793. .help = readv_help,
  794. };
  795. static int readv_f(BlockBackend *blk, int argc, char **argv)
  796. {
  797. struct timespec t1, t2;
  798. bool Cflag = false, qflag = false, vflag = false;
  799. int c, cnt, ret;
  800. char *buf;
  801. int64_t offset;
  802. /* Some compilers get confused and warn if this is not initialized. */
  803. int total = 0;
  804. int nr_iov;
  805. QEMUIOVector qiov;
  806. int pattern = 0;
  807. bool Pflag = false;
  808. while ((c = getopt(argc, argv, "CP:qv")) != -1) {
  809. switch (c) {
  810. case 'C':
  811. Cflag = true;
  812. break;
  813. case 'P':
  814. Pflag = true;
  815. pattern = parse_pattern(optarg);
  816. if (pattern < 0) {
  817. return -EINVAL;
  818. }
  819. break;
  820. case 'q':
  821. qflag = true;
  822. break;
  823. case 'v':
  824. vflag = true;
  825. break;
  826. default:
  827. qemuio_command_usage(&readv_cmd);
  828. return -EINVAL;
  829. }
  830. }
  831. if (optind > argc - 2) {
  832. qemuio_command_usage(&readv_cmd);
  833. return -EINVAL;
  834. }
  835. offset = cvtnum(argv[optind]);
  836. if (offset < 0) {
  837. print_cvtnum_err(offset, argv[optind]);
  838. return offset;
  839. }
  840. optind++;
  841. nr_iov = argc - optind;
  842. buf = create_iovec(blk, &qiov, &argv[optind], nr_iov, 0xab);
  843. if (buf == NULL) {
  844. return -EINVAL;
  845. }
  846. clock_gettime(CLOCK_MONOTONIC, &t1);
  847. ret = do_aio_readv(blk, &qiov, offset, &total);
  848. clock_gettime(CLOCK_MONOTONIC, &t2);
  849. if (ret < 0) {
  850. printf("readv failed: %s\n", strerror(-ret));
  851. goto out;
  852. }
  853. cnt = ret;
  854. ret = 0;
  855. if (Pflag) {
  856. void *cmp_buf = g_malloc(qiov.size);
  857. memset(cmp_buf, pattern, qiov.size);
  858. if (memcmp(buf, cmp_buf, qiov.size)) {
  859. printf("Pattern verification failed at offset %"
  860. PRId64 ", %zu bytes\n", offset, qiov.size);
  861. ret = -EINVAL;
  862. }
  863. g_free(cmp_buf);
  864. }
  865. if (qflag) {
  866. goto out;
  867. }
  868. if (vflag) {
  869. dump_buffer(buf, offset, qiov.size);
  870. }
  871. /* Finally, report back -- -C gives a parsable format */
  872. t2 = tsub(t2, t1);
  873. print_report("read", &t2, offset, qiov.size, total, cnt, Cflag);
  874. out:
  875. qemu_iovec_destroy(&qiov);
  876. qemu_io_free(buf);
  877. return ret;
  878. }
  879. static void write_help(void)
  880. {
  881. printf(
  882. "\n"
  883. " writes a range of bytes from the given offset\n"
  884. "\n"
  885. " Example:\n"
  886. " 'write 512 1k' - writes 1 kilobyte at 512 bytes into the open file\n"
  887. "\n"
  888. " Writes into a segment of the currently open file, using a buffer\n"
  889. " filled with a set pattern (0xcdcdcdcd).\n"
  890. " -b, -- write to the VM state rather than the virtual disk\n"
  891. " -c, -- write compressed data with blk_write_compressed\n"
  892. " -f, -- use Force Unit Access semantics\n"
  893. " -n, -- with -z, don't allow slow fallback\n"
  894. " -p, -- ignored for backwards compatibility\n"
  895. " -P, -- use different pattern to fill file\n"
  896. " -s, -- use a pattern file to fill the write buffer\n"
  897. " -C, -- report statistics in a machine parsable format\n"
  898. " -q, -- quiet mode, do not show I/O statistics\n"
  899. " -u, -- with -z, allow unmapping\n"
  900. " -z, -- write zeroes using blk_co_pwrite_zeroes\n"
  901. "\n");
  902. }
  903. static int write_f(BlockBackend *blk, int argc, char **argv);
  904. static const cmdinfo_t write_cmd = {
  905. .name = "write",
  906. .altname = "w",
  907. .cfunc = write_f,
  908. .perm = BLK_PERM_WRITE,
  909. .argmin = 2,
  910. .argmax = -1,
  911. .args = "[-bcCfnquz] [-P pattern | -s source_file] off len",
  912. .oneline = "writes a number of bytes at a specified offset",
  913. .help = write_help,
  914. };
  915. static int write_f(BlockBackend *blk, int argc, char **argv)
  916. {
  917. struct timespec t1, t2;
  918. bool Cflag = false, qflag = false, bflag = false;
  919. bool Pflag = false, zflag = false, cflag = false, sflag = false;
  920. int flags = 0;
  921. int c, cnt, ret;
  922. char *buf = NULL;
  923. int64_t offset;
  924. int64_t count;
  925. /* Some compilers get confused and warn if this is not initialized. */
  926. int64_t total = 0;
  927. int pattern = 0xcd;
  928. const char *file_name = NULL;
  929. while ((c = getopt(argc, argv, "bcCfnpP:qs:uz")) != -1) {
  930. switch (c) {
  931. case 'b':
  932. bflag = true;
  933. break;
  934. case 'c':
  935. cflag = true;
  936. break;
  937. case 'C':
  938. Cflag = true;
  939. break;
  940. case 'f':
  941. flags |= BDRV_REQ_FUA;
  942. break;
  943. case 'n':
  944. flags |= BDRV_REQ_NO_FALLBACK;
  945. break;
  946. case 'p':
  947. /* Ignored for backwards compatibility */
  948. break;
  949. case 'P':
  950. Pflag = true;
  951. pattern = parse_pattern(optarg);
  952. if (pattern < 0) {
  953. return -EINVAL;
  954. }
  955. break;
  956. case 'q':
  957. qflag = true;
  958. break;
  959. case 's':
  960. sflag = true;
  961. file_name = optarg;
  962. break;
  963. case 'u':
  964. flags |= BDRV_REQ_MAY_UNMAP;
  965. break;
  966. case 'z':
  967. zflag = true;
  968. break;
  969. default:
  970. qemuio_command_usage(&write_cmd);
  971. return -EINVAL;
  972. }
  973. }
  974. if (optind != argc - 2) {
  975. qemuio_command_usage(&write_cmd);
  976. return -EINVAL;
  977. }
  978. if (bflag && zflag) {
  979. printf("-b and -z cannot be specified at the same time\n");
  980. return -EINVAL;
  981. }
  982. if ((flags & BDRV_REQ_FUA) && (bflag || cflag)) {
  983. printf("-f and -b or -c cannot be specified at the same time\n");
  984. return -EINVAL;
  985. }
  986. if ((flags & BDRV_REQ_NO_FALLBACK) && !zflag) {
  987. printf("-n requires -z to be specified\n");
  988. return -EINVAL;
  989. }
  990. if ((flags & BDRV_REQ_MAY_UNMAP) && !zflag) {
  991. printf("-u requires -z to be specified\n");
  992. return -EINVAL;
  993. }
  994. if (zflag + Pflag + sflag > 1) {
  995. printf("Only one of -z, -P, and -s "
  996. "can be specified at the same time\n");
  997. return -EINVAL;
  998. }
  999. offset = cvtnum(argv[optind]);
  1000. if (offset < 0) {
  1001. print_cvtnum_err(offset, argv[optind]);
  1002. return offset;
  1003. }
  1004. optind++;
  1005. count = cvtnum(argv[optind]);
  1006. if (count < 0) {
  1007. print_cvtnum_err(count, argv[optind]);
  1008. return count;
  1009. } else if (count > BDRV_REQUEST_MAX_BYTES &&
  1010. !(flags & BDRV_REQ_NO_FALLBACK)) {
  1011. printf("length cannot exceed %" PRIu64 " without -n, given %s\n",
  1012. (uint64_t)BDRV_REQUEST_MAX_BYTES, argv[optind]);
  1013. return -EINVAL;
  1014. }
  1015. if (bflag || cflag) {
  1016. if (!QEMU_IS_ALIGNED(offset, BDRV_SECTOR_SIZE)) {
  1017. printf("%" PRId64 " is not a sector-aligned value for 'offset'\n",
  1018. offset);
  1019. return -EINVAL;
  1020. }
  1021. if (!QEMU_IS_ALIGNED(count, BDRV_SECTOR_SIZE)) {
  1022. printf("%"PRId64" is not a sector-aligned value for 'count'\n",
  1023. count);
  1024. return -EINVAL;
  1025. }
  1026. }
  1027. if (!zflag) {
  1028. if (sflag) {
  1029. buf = qemu_io_alloc_from_file(blk, count, file_name);
  1030. if (!buf) {
  1031. return -EINVAL;
  1032. }
  1033. } else {
  1034. buf = qemu_io_alloc(blk, count, pattern);
  1035. }
  1036. }
  1037. clock_gettime(CLOCK_MONOTONIC, &t1);
  1038. if (bflag) {
  1039. ret = do_save_vmstate(blk, buf, offset, count, &total);
  1040. } else if (zflag) {
  1041. ret = do_co_pwrite_zeroes(blk, offset, count, flags, &total);
  1042. } else if (cflag) {
  1043. ret = do_write_compressed(blk, buf, offset, count, &total);
  1044. } else {
  1045. ret = do_pwrite(blk, buf, offset, count, flags, &total);
  1046. }
  1047. clock_gettime(CLOCK_MONOTONIC, &t2);
  1048. if (ret < 0) {
  1049. printf("write failed: %s\n", strerror(-ret));
  1050. goto out;
  1051. }
  1052. cnt = ret;
  1053. ret = 0;
  1054. if (qflag) {
  1055. goto out;
  1056. }
  1057. /* Finally, report back -- -C gives a parsable format */
  1058. t2 = tsub(t2, t1);
  1059. print_report("wrote", &t2, offset, count, total, cnt, Cflag);
  1060. out:
  1061. if (!zflag) {
  1062. qemu_io_free(buf);
  1063. }
  1064. return ret;
  1065. }
  1066. static void
  1067. writev_help(void)
  1068. {
  1069. printf(
  1070. "\n"
  1071. " writes a range of bytes from the given offset source from multiple buffers\n"
  1072. "\n"
  1073. " Example:\n"
  1074. " 'writev 512 1k 1k' - writes 2 kilobytes at 512 bytes into the open file\n"
  1075. "\n"
  1076. " Writes into a segment of the currently open file, using a buffer\n"
  1077. " filled with a set pattern (0xcdcdcdcd).\n"
  1078. " -P, -- use different pattern to fill file\n"
  1079. " -C, -- report statistics in a machine parsable format\n"
  1080. " -f, -- use Force Unit Access semantics\n"
  1081. " -q, -- quiet mode, do not show I/O statistics\n"
  1082. "\n");
  1083. }
  1084. static int writev_f(BlockBackend *blk, int argc, char **argv);
  1085. static const cmdinfo_t writev_cmd = {
  1086. .name = "writev",
  1087. .cfunc = writev_f,
  1088. .perm = BLK_PERM_WRITE,
  1089. .argmin = 2,
  1090. .argmax = -1,
  1091. .args = "[-Cfq] [-P pattern] off len [len..]",
  1092. .oneline = "writes a number of bytes at a specified offset",
  1093. .help = writev_help,
  1094. };
  1095. static int writev_f(BlockBackend *blk, int argc, char **argv)
  1096. {
  1097. struct timespec t1, t2;
  1098. bool Cflag = false, qflag = false;
  1099. int flags = 0;
  1100. int c, cnt, ret;
  1101. char *buf;
  1102. int64_t offset;
  1103. /* Some compilers get confused and warn if this is not initialized. */
  1104. int total = 0;
  1105. int nr_iov;
  1106. int pattern = 0xcd;
  1107. QEMUIOVector qiov;
  1108. while ((c = getopt(argc, argv, "CfqP:")) != -1) {
  1109. switch (c) {
  1110. case 'C':
  1111. Cflag = true;
  1112. break;
  1113. case 'f':
  1114. flags |= BDRV_REQ_FUA;
  1115. break;
  1116. case 'q':
  1117. qflag = true;
  1118. break;
  1119. case 'P':
  1120. pattern = parse_pattern(optarg);
  1121. if (pattern < 0) {
  1122. return -EINVAL;
  1123. }
  1124. break;
  1125. default:
  1126. qemuio_command_usage(&writev_cmd);
  1127. return -EINVAL;
  1128. }
  1129. }
  1130. if (optind > argc - 2) {
  1131. qemuio_command_usage(&writev_cmd);
  1132. return -EINVAL;
  1133. }
  1134. offset = cvtnum(argv[optind]);
  1135. if (offset < 0) {
  1136. print_cvtnum_err(offset, argv[optind]);
  1137. return offset;
  1138. }
  1139. optind++;
  1140. nr_iov = argc - optind;
  1141. buf = create_iovec(blk, &qiov, &argv[optind], nr_iov, pattern);
  1142. if (buf == NULL) {
  1143. return -EINVAL;
  1144. }
  1145. clock_gettime(CLOCK_MONOTONIC, &t1);
  1146. ret = do_aio_writev(blk, &qiov, offset, flags, &total);
  1147. clock_gettime(CLOCK_MONOTONIC, &t2);
  1148. if (ret < 0) {
  1149. printf("writev failed: %s\n", strerror(-ret));
  1150. goto out;
  1151. }
  1152. cnt = ret;
  1153. ret = 0;
  1154. if (qflag) {
  1155. goto out;
  1156. }
  1157. /* Finally, report back -- -C gives a parsable format */
  1158. t2 = tsub(t2, t1);
  1159. print_report("wrote", &t2, offset, qiov.size, total, cnt, Cflag);
  1160. out:
  1161. qemu_iovec_destroy(&qiov);
  1162. qemu_io_free(buf);
  1163. return ret;
  1164. }
  1165. struct aio_ctx {
  1166. BlockBackend *blk;
  1167. QEMUIOVector qiov;
  1168. int64_t offset;
  1169. char *buf;
  1170. bool qflag;
  1171. bool vflag;
  1172. bool Cflag;
  1173. bool Pflag;
  1174. bool zflag;
  1175. BlockAcctCookie acct;
  1176. int pattern;
  1177. struct timespec t1;
  1178. };
  1179. static void aio_write_done(void *opaque, int ret)
  1180. {
  1181. struct aio_ctx *ctx = opaque;
  1182. struct timespec t2;
  1183. clock_gettime(CLOCK_MONOTONIC, &t2);
  1184. if (ret < 0) {
  1185. printf("aio_write failed: %s\n", strerror(-ret));
  1186. block_acct_failed(blk_get_stats(ctx->blk), &ctx->acct);
  1187. goto out;
  1188. }
  1189. block_acct_done(blk_get_stats(ctx->blk), &ctx->acct);
  1190. if (ctx->qflag) {
  1191. goto out;
  1192. }
  1193. /* Finally, report back -- -C gives a parsable format */
  1194. t2 = tsub(t2, ctx->t1);
  1195. print_report("wrote", &t2, ctx->offset, ctx->qiov.size,
  1196. ctx->qiov.size, 1, ctx->Cflag);
  1197. out:
  1198. if (!ctx->zflag) {
  1199. qemu_io_free(ctx->buf);
  1200. qemu_iovec_destroy(&ctx->qiov);
  1201. }
  1202. g_free(ctx);
  1203. }
  1204. static void aio_read_done(void *opaque, int ret)
  1205. {
  1206. struct aio_ctx *ctx = opaque;
  1207. struct timespec t2;
  1208. clock_gettime(CLOCK_MONOTONIC, &t2);
  1209. if (ret < 0) {
  1210. printf("readv failed: %s\n", strerror(-ret));
  1211. block_acct_failed(blk_get_stats(ctx->blk), &ctx->acct);
  1212. goto out;
  1213. }
  1214. if (ctx->Pflag) {
  1215. void *cmp_buf = g_malloc(ctx->qiov.size);
  1216. memset(cmp_buf, ctx->pattern, ctx->qiov.size);
  1217. if (memcmp(ctx->buf, cmp_buf, ctx->qiov.size)) {
  1218. printf("Pattern verification failed at offset %"
  1219. PRId64 ", %zu bytes\n", ctx->offset, ctx->qiov.size);
  1220. }
  1221. g_free(cmp_buf);
  1222. }
  1223. block_acct_done(blk_get_stats(ctx->blk), &ctx->acct);
  1224. if (ctx->qflag) {
  1225. goto out;
  1226. }
  1227. if (ctx->vflag) {
  1228. dump_buffer(ctx->buf, ctx->offset, ctx->qiov.size);
  1229. }
  1230. /* Finally, report back -- -C gives a parsable format */
  1231. t2 = tsub(t2, ctx->t1);
  1232. print_report("read", &t2, ctx->offset, ctx->qiov.size,
  1233. ctx->qiov.size, 1, ctx->Cflag);
  1234. out:
  1235. qemu_io_free(ctx->buf);
  1236. qemu_iovec_destroy(&ctx->qiov);
  1237. g_free(ctx);
  1238. }
  1239. static void aio_read_help(void)
  1240. {
  1241. printf(
  1242. "\n"
  1243. " asynchronously reads a range of bytes from the given offset\n"
  1244. "\n"
  1245. " Example:\n"
  1246. " 'aio_read -v 512 1k 1k ' - dumps 2 kilobytes read from 512 bytes into the file\n"
  1247. "\n"
  1248. " Reads a segment of the currently open file, optionally dumping it to the\n"
  1249. " standard output stream (with -v option) for subsequent inspection.\n"
  1250. " The read is performed asynchronously and the aio_flush command must be\n"
  1251. " used to ensure all outstanding aio requests have been completed.\n"
  1252. " Note that due to its asynchronous nature, this command will be\n"
  1253. " considered successful once the request is submitted, independently\n"
  1254. " of potential I/O errors or pattern mismatches.\n"
  1255. " -C, -- report statistics in a machine parsable format\n"
  1256. " -P, -- use a pattern to verify read data\n"
  1257. " -i, -- treat request as invalid, for exercising stats\n"
  1258. " -v, -- dump buffer to standard output\n"
  1259. " -q, -- quiet mode, do not show I/O statistics\n"
  1260. "\n");
  1261. }
  1262. static int aio_read_f(BlockBackend *blk, int argc, char **argv);
  1263. static const cmdinfo_t aio_read_cmd = {
  1264. .name = "aio_read",
  1265. .cfunc = aio_read_f,
  1266. .argmin = 2,
  1267. .argmax = -1,
  1268. .args = "[-Ciqv] [-P pattern] off len [len..]",
  1269. .oneline = "asynchronously reads a number of bytes",
  1270. .help = aio_read_help,
  1271. };
  1272. static int aio_read_f(BlockBackend *blk, int argc, char **argv)
  1273. {
  1274. int nr_iov, c;
  1275. struct aio_ctx *ctx = g_new0(struct aio_ctx, 1);
  1276. ctx->blk = blk;
  1277. while ((c = getopt(argc, argv, "CP:iqv")) != -1) {
  1278. switch (c) {
  1279. case 'C':
  1280. ctx->Cflag = true;
  1281. break;
  1282. case 'P':
  1283. ctx->Pflag = true;
  1284. ctx->pattern = parse_pattern(optarg);
  1285. if (ctx->pattern < 0) {
  1286. g_free(ctx);
  1287. return -EINVAL;
  1288. }
  1289. break;
  1290. case 'i':
  1291. printf("injecting invalid read request\n");
  1292. block_acct_invalid(blk_get_stats(blk), BLOCK_ACCT_READ);
  1293. g_free(ctx);
  1294. return 0;
  1295. case 'q':
  1296. ctx->qflag = true;
  1297. break;
  1298. case 'v':
  1299. ctx->vflag = true;
  1300. break;
  1301. default:
  1302. g_free(ctx);
  1303. qemuio_command_usage(&aio_read_cmd);
  1304. return -EINVAL;
  1305. }
  1306. }
  1307. if (optind > argc - 2) {
  1308. g_free(ctx);
  1309. qemuio_command_usage(&aio_read_cmd);
  1310. return -EINVAL;
  1311. }
  1312. ctx->offset = cvtnum(argv[optind]);
  1313. if (ctx->offset < 0) {
  1314. int ret = ctx->offset;
  1315. print_cvtnum_err(ret, argv[optind]);
  1316. g_free(ctx);
  1317. return ret;
  1318. }
  1319. optind++;
  1320. nr_iov = argc - optind;
  1321. ctx->buf = create_iovec(blk, &ctx->qiov, &argv[optind], nr_iov, 0xab);
  1322. if (ctx->buf == NULL) {
  1323. block_acct_invalid(blk_get_stats(blk), BLOCK_ACCT_READ);
  1324. g_free(ctx);
  1325. return -EINVAL;
  1326. }
  1327. clock_gettime(CLOCK_MONOTONIC, &ctx->t1);
  1328. block_acct_start(blk_get_stats(blk), &ctx->acct, ctx->qiov.size,
  1329. BLOCK_ACCT_READ);
  1330. blk_aio_preadv(blk, ctx->offset, &ctx->qiov, 0, aio_read_done, ctx);
  1331. return 0;
  1332. }
  1333. static void aio_write_help(void)
  1334. {
  1335. printf(
  1336. "\n"
  1337. " asynchronously writes a range of bytes from the given offset source\n"
  1338. " from multiple buffers\n"
  1339. "\n"
  1340. " Example:\n"
  1341. " 'aio_write 512 1k 1k' - writes 2 kilobytes at 512 bytes into the open file\n"
  1342. "\n"
  1343. " Writes into a segment of the currently open file, using a buffer\n"
  1344. " filled with a set pattern (0xcdcdcdcd).\n"
  1345. " The write is performed asynchronously and the aio_flush command must be\n"
  1346. " used to ensure all outstanding aio requests have been completed.\n"
  1347. " Note that due to its asynchronous nature, this command will be\n"
  1348. " considered successful once the request is submitted, independently\n"
  1349. " of potential I/O errors or pattern mismatches.\n"
  1350. " -P, -- use different pattern to fill file\n"
  1351. " -C, -- report statistics in a machine parsable format\n"
  1352. " -f, -- use Force Unit Access semantics\n"
  1353. " -i, -- treat request as invalid, for exercising stats\n"
  1354. " -q, -- quiet mode, do not show I/O statistics\n"
  1355. " -u, -- with -z, allow unmapping\n"
  1356. " -z, -- write zeroes using blk_aio_pwrite_zeroes\n"
  1357. "\n");
  1358. }
  1359. static int aio_write_f(BlockBackend *blk, int argc, char **argv);
  1360. static const cmdinfo_t aio_write_cmd = {
  1361. .name = "aio_write",
  1362. .cfunc = aio_write_f,
  1363. .perm = BLK_PERM_WRITE,
  1364. .argmin = 2,
  1365. .argmax = -1,
  1366. .args = "[-Cfiquz] [-P pattern] off len [len..]",
  1367. .oneline = "asynchronously writes a number of bytes",
  1368. .help = aio_write_help,
  1369. };
  1370. static int aio_write_f(BlockBackend *blk, int argc, char **argv)
  1371. {
  1372. int nr_iov, c;
  1373. int pattern = 0xcd;
  1374. struct aio_ctx *ctx = g_new0(struct aio_ctx, 1);
  1375. int flags = 0;
  1376. ctx->blk = blk;
  1377. while ((c = getopt(argc, argv, "CfiqP:uz")) != -1) {
  1378. switch (c) {
  1379. case 'C':
  1380. ctx->Cflag = true;
  1381. break;
  1382. case 'f':
  1383. flags |= BDRV_REQ_FUA;
  1384. break;
  1385. case 'q':
  1386. ctx->qflag = true;
  1387. break;
  1388. case 'u':
  1389. flags |= BDRV_REQ_MAY_UNMAP;
  1390. break;
  1391. case 'P':
  1392. pattern = parse_pattern(optarg);
  1393. if (pattern < 0) {
  1394. g_free(ctx);
  1395. return -EINVAL;
  1396. }
  1397. break;
  1398. case 'i':
  1399. printf("injecting invalid write request\n");
  1400. block_acct_invalid(blk_get_stats(blk), BLOCK_ACCT_WRITE);
  1401. g_free(ctx);
  1402. return 0;
  1403. case 'z':
  1404. ctx->zflag = true;
  1405. break;
  1406. default:
  1407. g_free(ctx);
  1408. qemuio_command_usage(&aio_write_cmd);
  1409. return -EINVAL;
  1410. }
  1411. }
  1412. if (optind > argc - 2) {
  1413. g_free(ctx);
  1414. qemuio_command_usage(&aio_write_cmd);
  1415. return -EINVAL;
  1416. }
  1417. if (ctx->zflag && optind != argc - 2) {
  1418. printf("-z supports only a single length parameter\n");
  1419. g_free(ctx);
  1420. return -EINVAL;
  1421. }
  1422. if ((flags & BDRV_REQ_MAY_UNMAP) && !ctx->zflag) {
  1423. printf("-u requires -z to be specified\n");
  1424. g_free(ctx);
  1425. return -EINVAL;
  1426. }
  1427. if (ctx->zflag && ctx->Pflag) {
  1428. printf("-z and -P cannot be specified at the same time\n");
  1429. g_free(ctx);
  1430. return -EINVAL;
  1431. }
  1432. ctx->offset = cvtnum(argv[optind]);
  1433. if (ctx->offset < 0) {
  1434. int ret = ctx->offset;
  1435. print_cvtnum_err(ret, argv[optind]);
  1436. g_free(ctx);
  1437. return ret;
  1438. }
  1439. optind++;
  1440. if (ctx->zflag) {
  1441. int64_t count = cvtnum(argv[optind]);
  1442. if (count < 0) {
  1443. print_cvtnum_err(count, argv[optind]);
  1444. g_free(ctx);
  1445. return count;
  1446. }
  1447. ctx->qiov.size = count;
  1448. blk_aio_pwrite_zeroes(blk, ctx->offset, count, flags, aio_write_done,
  1449. ctx);
  1450. } else {
  1451. nr_iov = argc - optind;
  1452. ctx->buf = create_iovec(blk, &ctx->qiov, &argv[optind], nr_iov,
  1453. pattern);
  1454. if (ctx->buf == NULL) {
  1455. block_acct_invalid(blk_get_stats(blk), BLOCK_ACCT_WRITE);
  1456. g_free(ctx);
  1457. return -EINVAL;
  1458. }
  1459. clock_gettime(CLOCK_MONOTONIC, &ctx->t1);
  1460. block_acct_start(blk_get_stats(blk), &ctx->acct, ctx->qiov.size,
  1461. BLOCK_ACCT_WRITE);
  1462. blk_aio_pwritev(blk, ctx->offset, &ctx->qiov, flags, aio_write_done,
  1463. ctx);
  1464. }
  1465. return 0;
  1466. }
  1467. static int aio_flush_f(BlockBackend *blk, int argc, char **argv)
  1468. {
  1469. BlockAcctCookie cookie;
  1470. block_acct_start(blk_get_stats(blk), &cookie, 0, BLOCK_ACCT_FLUSH);
  1471. blk_drain_all();
  1472. block_acct_done(blk_get_stats(blk), &cookie);
  1473. return 0;
  1474. }
  1475. static const cmdinfo_t aio_flush_cmd = {
  1476. .name = "aio_flush",
  1477. .cfunc = aio_flush_f,
  1478. .oneline = "completes all outstanding aio requests"
  1479. };
  1480. static int flush_f(BlockBackend *blk, int argc, char **argv)
  1481. {
  1482. return blk_flush(blk);
  1483. }
  1484. static const cmdinfo_t flush_cmd = {
  1485. .name = "flush",
  1486. .altname = "f",
  1487. .cfunc = flush_f,
  1488. .oneline = "flush all in-core file state to disk",
  1489. };
  1490. static int truncate_f(BlockBackend *blk, int argc, char **argv);
  1491. static const cmdinfo_t truncate_cmd = {
  1492. .name = "truncate",
  1493. .altname = "t",
  1494. .cfunc = truncate_f,
  1495. .perm = BLK_PERM_WRITE | BLK_PERM_RESIZE,
  1496. .argmin = 1,
  1497. .argmax = 3,
  1498. .args = "[-m prealloc_mode] off",
  1499. .oneline = "truncates the current file at the given offset",
  1500. };
  1501. static int truncate_f(BlockBackend *blk, int argc, char **argv)
  1502. {
  1503. Error *local_err = NULL;
  1504. int64_t offset;
  1505. int c, ret;
  1506. PreallocMode prealloc = PREALLOC_MODE_OFF;
  1507. while ((c = getopt(argc, argv, "m:")) != -1) {
  1508. switch (c) {
  1509. case 'm':
  1510. prealloc = qapi_enum_parse(&PreallocMode_lookup, optarg,
  1511. PREALLOC_MODE__MAX, NULL);
  1512. if (prealloc == PREALLOC_MODE__MAX) {
  1513. error_report("Invalid preallocation mode '%s'", optarg);
  1514. return -EINVAL;
  1515. }
  1516. break;
  1517. default:
  1518. qemuio_command_usage(&truncate_cmd);
  1519. return -EINVAL;
  1520. }
  1521. }
  1522. offset = cvtnum(argv[optind]);
  1523. if (offset < 0) {
  1524. print_cvtnum_err(offset, argv[1]);
  1525. return offset;
  1526. }
  1527. /*
  1528. * qemu-io is a debugging tool, so let us be strict here and pass
  1529. * exact=true. It is better to err on the "emit more errors" side
  1530. * than to be overly permissive.
  1531. */
  1532. ret = blk_truncate(blk, offset, false, prealloc, 0, &local_err);
  1533. if (ret < 0) {
  1534. error_report_err(local_err);
  1535. return ret;
  1536. }
  1537. return 0;
  1538. }
  1539. static int length_f(BlockBackend *blk, int argc, char **argv)
  1540. {
  1541. int64_t size;
  1542. char s1[64];
  1543. size = blk_getlength(blk);
  1544. if (size < 0) {
  1545. printf("getlength: %s\n", strerror(-size));
  1546. return size;
  1547. }
  1548. cvtstr(size, s1, sizeof(s1));
  1549. printf("%s\n", s1);
  1550. return 0;
  1551. }
  1552. static const cmdinfo_t length_cmd = {
  1553. .name = "length",
  1554. .altname = "l",
  1555. .cfunc = length_f,
  1556. .oneline = "gets the length of the current file",
  1557. };
  1558. static int info_f(BlockBackend *blk, int argc, char **argv)
  1559. {
  1560. BlockDriverState *bs = blk_bs(blk);
  1561. BlockDriverInfo bdi;
  1562. ImageInfoSpecific *spec_info;
  1563. Error *local_err = NULL;
  1564. char s1[64], s2[64];
  1565. int ret;
  1566. if (bs->drv && bs->drv->format_name) {
  1567. printf("format name: %s\n", bs->drv->format_name);
  1568. }
  1569. if (bs->drv && bs->drv->protocol_name) {
  1570. printf("format name: %s\n", bs->drv->protocol_name);
  1571. }
  1572. ret = bdrv_get_info(bs, &bdi);
  1573. if (ret) {
  1574. return ret;
  1575. }
  1576. cvtstr(bdi.cluster_size, s1, sizeof(s1));
  1577. cvtstr(bdi.vm_state_offset, s2, sizeof(s2));
  1578. printf("cluster size: %s\n", s1);
  1579. printf("vm state offset: %s\n", s2);
  1580. spec_info = bdrv_get_specific_info(bs, &local_err);
  1581. if (local_err) {
  1582. error_report_err(local_err);
  1583. return -EIO;
  1584. }
  1585. if (spec_info) {
  1586. printf("Format specific information:\n");
  1587. bdrv_image_info_specific_dump(spec_info);
  1588. qapi_free_ImageInfoSpecific(spec_info);
  1589. }
  1590. return 0;
  1591. }
  1592. static const cmdinfo_t info_cmd = {
  1593. .name = "info",
  1594. .altname = "i",
  1595. .cfunc = info_f,
  1596. .oneline = "prints information about the current file",
  1597. };
  1598. static void discard_help(void)
  1599. {
  1600. printf(
  1601. "\n"
  1602. " discards a range of bytes from the given offset\n"
  1603. "\n"
  1604. " Example:\n"
  1605. " 'discard 512 1k' - discards 1 kilobyte from 512 bytes into the file\n"
  1606. "\n"
  1607. " Discards a segment of the currently open file.\n"
  1608. " -C, -- report statistics in a machine parsable format\n"
  1609. " -q, -- quiet mode, do not show I/O statistics\n"
  1610. "\n");
  1611. }
  1612. static int discard_f(BlockBackend *blk, int argc, char **argv);
  1613. static const cmdinfo_t discard_cmd = {
  1614. .name = "discard",
  1615. .altname = "d",
  1616. .cfunc = discard_f,
  1617. .perm = BLK_PERM_WRITE,
  1618. .argmin = 2,
  1619. .argmax = -1,
  1620. .args = "[-Cq] off len",
  1621. .oneline = "discards a number of bytes at a specified offset",
  1622. .help = discard_help,
  1623. };
  1624. static int discard_f(BlockBackend *blk, int argc, char **argv)
  1625. {
  1626. struct timespec t1, t2;
  1627. bool Cflag = false, qflag = false;
  1628. int c, ret;
  1629. int64_t offset, bytes;
  1630. while ((c = getopt(argc, argv, "Cq")) != -1) {
  1631. switch (c) {
  1632. case 'C':
  1633. Cflag = true;
  1634. break;
  1635. case 'q':
  1636. qflag = true;
  1637. break;
  1638. default:
  1639. qemuio_command_usage(&discard_cmd);
  1640. return -EINVAL;
  1641. }
  1642. }
  1643. if (optind != argc - 2) {
  1644. qemuio_command_usage(&discard_cmd);
  1645. return -EINVAL;
  1646. }
  1647. offset = cvtnum(argv[optind]);
  1648. if (offset < 0) {
  1649. print_cvtnum_err(offset, argv[optind]);
  1650. return offset;
  1651. }
  1652. optind++;
  1653. bytes = cvtnum(argv[optind]);
  1654. if (bytes < 0) {
  1655. print_cvtnum_err(bytes, argv[optind]);
  1656. return bytes;
  1657. } else if (bytes > BDRV_REQUEST_MAX_BYTES) {
  1658. printf("length cannot exceed %"PRIu64", given %s\n",
  1659. (uint64_t)BDRV_REQUEST_MAX_BYTES, argv[optind]);
  1660. return -EINVAL;
  1661. }
  1662. clock_gettime(CLOCK_MONOTONIC, &t1);
  1663. ret = blk_pdiscard(blk, offset, bytes);
  1664. clock_gettime(CLOCK_MONOTONIC, &t2);
  1665. if (ret < 0) {
  1666. printf("discard failed: %s\n", strerror(-ret));
  1667. return ret;
  1668. }
  1669. /* Finally, report back -- -C gives a parsable format */
  1670. if (!qflag) {
  1671. t2 = tsub(t2, t1);
  1672. print_report("discard", &t2, offset, bytes, bytes, 1, Cflag);
  1673. }
  1674. return 0;
  1675. }
  1676. static int alloc_f(BlockBackend *blk, int argc, char **argv)
  1677. {
  1678. BlockDriverState *bs = blk_bs(blk);
  1679. int64_t offset, start, remaining, count;
  1680. char s1[64];
  1681. int ret;
  1682. int64_t num, sum_alloc;
  1683. start = offset = cvtnum(argv[1]);
  1684. if (offset < 0) {
  1685. print_cvtnum_err(offset, argv[1]);
  1686. return offset;
  1687. }
  1688. if (argc == 3) {
  1689. count = cvtnum(argv[2]);
  1690. if (count < 0) {
  1691. print_cvtnum_err(count, argv[2]);
  1692. return count;
  1693. }
  1694. } else {
  1695. count = BDRV_SECTOR_SIZE;
  1696. }
  1697. remaining = count;
  1698. sum_alloc = 0;
  1699. while (remaining) {
  1700. ret = bdrv_is_allocated(bs, offset, remaining, &num);
  1701. if (ret < 0) {
  1702. printf("is_allocated failed: %s\n", strerror(-ret));
  1703. return ret;
  1704. }
  1705. offset += num;
  1706. remaining -= num;
  1707. if (ret) {
  1708. sum_alloc += num;
  1709. }
  1710. if (num == 0) {
  1711. count -= remaining;
  1712. remaining = 0;
  1713. }
  1714. }
  1715. cvtstr(start, s1, sizeof(s1));
  1716. printf("%"PRId64"/%"PRId64" bytes allocated at offset %s\n",
  1717. sum_alloc, count, s1);
  1718. return 0;
  1719. }
  1720. static const cmdinfo_t alloc_cmd = {
  1721. .name = "alloc",
  1722. .altname = "a",
  1723. .argmin = 1,
  1724. .argmax = 2,
  1725. .cfunc = alloc_f,
  1726. .args = "offset [count]",
  1727. .oneline = "checks if offset is allocated in the file",
  1728. };
  1729. static int map_is_allocated(BlockDriverState *bs, int64_t offset,
  1730. int64_t bytes, int64_t *pnum)
  1731. {
  1732. int64_t num;
  1733. int ret, firstret;
  1734. ret = bdrv_is_allocated(bs, offset, bytes, &num);
  1735. if (ret < 0) {
  1736. return ret;
  1737. }
  1738. firstret = ret;
  1739. *pnum = num;
  1740. while (bytes > 0 && ret == firstret) {
  1741. offset += num;
  1742. bytes -= num;
  1743. ret = bdrv_is_allocated(bs, offset, bytes, &num);
  1744. if (ret == firstret && num) {
  1745. *pnum += num;
  1746. } else {
  1747. break;
  1748. }
  1749. }
  1750. return firstret;
  1751. }
  1752. static int map_f(BlockBackend *blk, int argc, char **argv)
  1753. {
  1754. int64_t offset, bytes;
  1755. char s1[64], s2[64];
  1756. int64_t num;
  1757. int ret;
  1758. const char *retstr;
  1759. offset = 0;
  1760. bytes = blk_getlength(blk);
  1761. if (bytes < 0) {
  1762. error_report("Failed to query image length: %s", strerror(-bytes));
  1763. return bytes;
  1764. }
  1765. while (bytes) {
  1766. ret = map_is_allocated(blk_bs(blk), offset, bytes, &num);
  1767. if (ret < 0) {
  1768. error_report("Failed to get allocation status: %s", strerror(-ret));
  1769. return ret;
  1770. } else if (!num) {
  1771. error_report("Unexpected end of image");
  1772. return -EIO;
  1773. }
  1774. retstr = ret ? " allocated" : "not allocated";
  1775. cvtstr(num, s1, sizeof(s1));
  1776. cvtstr(offset, s2, sizeof(s2));
  1777. printf("%s (0x%" PRIx64 ") bytes %s at offset %s (0x%" PRIx64 ")\n",
  1778. s1, num, retstr, s2, offset);
  1779. offset += num;
  1780. bytes -= num;
  1781. }
  1782. return 0;
  1783. }
  1784. static const cmdinfo_t map_cmd = {
  1785. .name = "map",
  1786. .argmin = 0,
  1787. .argmax = 0,
  1788. .cfunc = map_f,
  1789. .args = "",
  1790. .oneline = "prints the allocated areas of a file",
  1791. };
  1792. static void reopen_help(void)
  1793. {
  1794. printf(
  1795. "\n"
  1796. " Changes the open options of an already opened image\n"
  1797. "\n"
  1798. " Example:\n"
  1799. " 'reopen -o lazy-refcounts=on' - activates lazy refcount writeback on a qcow2 image\n"
  1800. "\n"
  1801. " -r, -- Reopen the image read-only\n"
  1802. " -w, -- Reopen the image read-write\n"
  1803. " -c, -- Change the cache mode to the given value\n"
  1804. " -o, -- Changes block driver options (cf. 'open' command)\n"
  1805. "\n");
  1806. }
  1807. static int reopen_f(BlockBackend *blk, int argc, char **argv);
  1808. static QemuOptsList reopen_opts = {
  1809. .name = "reopen",
  1810. .merge_lists = true,
  1811. .head = QTAILQ_HEAD_INITIALIZER(reopen_opts.head),
  1812. .desc = {
  1813. /* no elements => accept any params */
  1814. { /* end of list */ }
  1815. },
  1816. };
  1817. static const cmdinfo_t reopen_cmd = {
  1818. .name = "reopen",
  1819. .argmin = 0,
  1820. .argmax = -1,
  1821. .cfunc = reopen_f,
  1822. .args = "[(-r|-w)] [-c cache] [-o options]",
  1823. .oneline = "reopens an image with new options",
  1824. .help = reopen_help,
  1825. };
  1826. static int reopen_f(BlockBackend *blk, int argc, char **argv)
  1827. {
  1828. BlockDriverState *bs = blk_bs(blk);
  1829. QemuOpts *qopts;
  1830. QDict *opts;
  1831. int c;
  1832. int flags = bs->open_flags;
  1833. bool writethrough = !blk_enable_write_cache(blk);
  1834. bool has_rw_option = false;
  1835. bool has_cache_option = false;
  1836. Error *local_err = NULL;
  1837. while ((c = getopt(argc, argv, "c:o:rw")) != -1) {
  1838. switch (c) {
  1839. case 'c':
  1840. if (bdrv_parse_cache_mode(optarg, &flags, &writethrough) < 0) {
  1841. error_report("Invalid cache option: %s", optarg);
  1842. return -EINVAL;
  1843. }
  1844. has_cache_option = true;
  1845. break;
  1846. case 'o':
  1847. if (!qemu_opts_parse_noisily(&reopen_opts, optarg, 0)) {
  1848. qemu_opts_reset(&reopen_opts);
  1849. return -EINVAL;
  1850. }
  1851. break;
  1852. case 'r':
  1853. if (has_rw_option) {
  1854. error_report("Only one -r/-w option may be given");
  1855. return -EINVAL;
  1856. }
  1857. flags &= ~BDRV_O_RDWR;
  1858. has_rw_option = true;
  1859. break;
  1860. case 'w':
  1861. if (has_rw_option) {
  1862. error_report("Only one -r/-w option may be given");
  1863. return -EINVAL;
  1864. }
  1865. flags |= BDRV_O_RDWR;
  1866. has_rw_option = true;
  1867. break;
  1868. default:
  1869. qemu_opts_reset(&reopen_opts);
  1870. qemuio_command_usage(&reopen_cmd);
  1871. return -EINVAL;
  1872. }
  1873. }
  1874. if (optind != argc) {
  1875. qemu_opts_reset(&reopen_opts);
  1876. qemuio_command_usage(&reopen_cmd);
  1877. return -EINVAL;
  1878. }
  1879. if (!writethrough != blk_enable_write_cache(blk) &&
  1880. blk_get_attached_dev(blk))
  1881. {
  1882. error_report("Cannot change cache.writeback: Device attached");
  1883. qemu_opts_reset(&reopen_opts);
  1884. return -EBUSY;
  1885. }
  1886. if (!(flags & BDRV_O_RDWR)) {
  1887. uint64_t orig_perm, orig_shared_perm;
  1888. bdrv_drain(bs);
  1889. blk_get_perm(blk, &orig_perm, &orig_shared_perm);
  1890. blk_set_perm(blk,
  1891. orig_perm & ~(BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED),
  1892. orig_shared_perm,
  1893. &error_abort);
  1894. }
  1895. qopts = qemu_opts_find(&reopen_opts, NULL);
  1896. opts = qopts ? qemu_opts_to_qdict(qopts, NULL) : qdict_new();
  1897. qemu_opts_reset(&reopen_opts);
  1898. if (qdict_haskey(opts, BDRV_OPT_READ_ONLY)) {
  1899. if (has_rw_option) {
  1900. error_report("Cannot set both -r/-w and '" BDRV_OPT_READ_ONLY "'");
  1901. qobject_unref(opts);
  1902. return -EINVAL;
  1903. }
  1904. } else {
  1905. qdict_put_bool(opts, BDRV_OPT_READ_ONLY, !(flags & BDRV_O_RDWR));
  1906. }
  1907. if (qdict_haskey(opts, BDRV_OPT_CACHE_DIRECT) ||
  1908. qdict_haskey(opts, BDRV_OPT_CACHE_NO_FLUSH)) {
  1909. if (has_cache_option) {
  1910. error_report("Cannot set both -c and the cache options");
  1911. qobject_unref(opts);
  1912. return -EINVAL;
  1913. }
  1914. } else {
  1915. qdict_put_bool(opts, BDRV_OPT_CACHE_DIRECT, flags & BDRV_O_NOCACHE);
  1916. qdict_put_bool(opts, BDRV_OPT_CACHE_NO_FLUSH, flags & BDRV_O_NO_FLUSH);
  1917. }
  1918. bdrv_reopen(bs, opts, true, &local_err);
  1919. if (local_err) {
  1920. error_report_err(local_err);
  1921. return -EINVAL;
  1922. }
  1923. blk_set_enable_write_cache(blk, !writethrough);
  1924. return 0;
  1925. }
  1926. static int break_f(BlockBackend *blk, int argc, char **argv)
  1927. {
  1928. int ret;
  1929. ret = bdrv_debug_breakpoint(blk_bs(blk), argv[1], argv[2]);
  1930. if (ret < 0) {
  1931. printf("Could not set breakpoint: %s\n", strerror(-ret));
  1932. return ret;
  1933. }
  1934. return 0;
  1935. }
  1936. static int remove_break_f(BlockBackend *blk, int argc, char **argv)
  1937. {
  1938. int ret;
  1939. ret = bdrv_debug_remove_breakpoint(blk_bs(blk), argv[1]);
  1940. if (ret < 0) {
  1941. printf("Could not remove breakpoint %s: %s\n", argv[1], strerror(-ret));
  1942. return ret;
  1943. }
  1944. return 0;
  1945. }
  1946. static const cmdinfo_t break_cmd = {
  1947. .name = "break",
  1948. .argmin = 2,
  1949. .argmax = 2,
  1950. .cfunc = break_f,
  1951. .args = "event tag",
  1952. .oneline = "sets a breakpoint on event and tags the stopped "
  1953. "request as tag",
  1954. };
  1955. static const cmdinfo_t remove_break_cmd = {
  1956. .name = "remove_break",
  1957. .argmin = 1,
  1958. .argmax = 1,
  1959. .cfunc = remove_break_f,
  1960. .args = "tag",
  1961. .oneline = "remove a breakpoint by tag",
  1962. };
  1963. static int resume_f(BlockBackend *blk, int argc, char **argv)
  1964. {
  1965. int ret;
  1966. ret = bdrv_debug_resume(blk_bs(blk), argv[1]);
  1967. if (ret < 0) {
  1968. printf("Could not resume request: %s\n", strerror(-ret));
  1969. return ret;
  1970. }
  1971. return 0;
  1972. }
  1973. static const cmdinfo_t resume_cmd = {
  1974. .name = "resume",
  1975. .argmin = 1,
  1976. .argmax = 1,
  1977. .cfunc = resume_f,
  1978. .args = "tag",
  1979. .oneline = "resumes the request tagged as tag",
  1980. };
  1981. static int wait_break_f(BlockBackend *blk, int argc, char **argv)
  1982. {
  1983. while (!bdrv_debug_is_suspended(blk_bs(blk), argv[1])) {
  1984. aio_poll(blk_get_aio_context(blk), true);
  1985. }
  1986. return 0;
  1987. }
  1988. static const cmdinfo_t wait_break_cmd = {
  1989. .name = "wait_break",
  1990. .argmin = 1,
  1991. .argmax = 1,
  1992. .cfunc = wait_break_f,
  1993. .args = "tag",
  1994. .oneline = "waits for the suspension of a request",
  1995. };
  1996. static int abort_f(BlockBackend *blk, int argc, char **argv)
  1997. {
  1998. abort();
  1999. }
  2000. static const cmdinfo_t abort_cmd = {
  2001. .name = "abort",
  2002. .cfunc = abort_f,
  2003. .flags = CMD_NOFILE_OK,
  2004. .oneline = "simulate a program crash using abort(3)",
  2005. };
  2006. static void sigraise_help(void)
  2007. {
  2008. printf(
  2009. "\n"
  2010. " raises the given signal\n"
  2011. "\n"
  2012. " Example:\n"
  2013. " 'sigraise %i' - raises SIGTERM\n"
  2014. "\n"
  2015. " Invokes raise(signal), where \"signal\" is the mandatory integer argument\n"
  2016. " given to sigraise.\n"
  2017. "\n", SIGTERM);
  2018. }
  2019. static int sigraise_f(BlockBackend *blk, int argc, char **argv);
  2020. static const cmdinfo_t sigraise_cmd = {
  2021. .name = "sigraise",
  2022. .cfunc = sigraise_f,
  2023. .argmin = 1,
  2024. .argmax = 1,
  2025. .flags = CMD_NOFILE_OK,
  2026. .args = "signal",
  2027. .oneline = "raises a signal",
  2028. .help = sigraise_help,
  2029. };
  2030. static int sigraise_f(BlockBackend *blk, int argc, char **argv)
  2031. {
  2032. int64_t sig = cvtnum(argv[1]);
  2033. if (sig < 0) {
  2034. print_cvtnum_err(sig, argv[1]);
  2035. return sig;
  2036. } else if (sig > NSIG) {
  2037. printf("signal argument '%s' is too large to be a valid signal\n",
  2038. argv[1]);
  2039. return -EINVAL;
  2040. }
  2041. /* Using raise() to kill this process does not necessarily flush all open
  2042. * streams. At least stdout and stderr (although the latter should be
  2043. * non-buffered anyway) should be flushed, though. */
  2044. fflush(stdout);
  2045. fflush(stderr);
  2046. raise(sig);
  2047. return 0;
  2048. }
  2049. static void sleep_cb(void *opaque)
  2050. {
  2051. bool *expired = opaque;
  2052. *expired = true;
  2053. }
  2054. static int sleep_f(BlockBackend *blk, int argc, char **argv)
  2055. {
  2056. char *endptr;
  2057. long ms;
  2058. struct QEMUTimer *timer;
  2059. bool expired = false;
  2060. ms = strtol(argv[1], &endptr, 0);
  2061. if (ms < 0 || *endptr != '\0') {
  2062. printf("%s is not a valid number\n", argv[1]);
  2063. return -EINVAL;
  2064. }
  2065. timer = timer_new_ns(QEMU_CLOCK_HOST, sleep_cb, &expired);
  2066. timer_mod(timer, qemu_clock_get_ns(QEMU_CLOCK_HOST) + SCALE_MS * ms);
  2067. while (!expired) {
  2068. main_loop_wait(false);
  2069. }
  2070. timer_free(timer);
  2071. return 0;
  2072. }
  2073. static const cmdinfo_t sleep_cmd = {
  2074. .name = "sleep",
  2075. .argmin = 1,
  2076. .argmax = 1,
  2077. .cfunc = sleep_f,
  2078. .flags = CMD_NOFILE_OK,
  2079. .oneline = "waits for the given value in milliseconds",
  2080. };
  2081. static void help_oneline(const char *cmd, const cmdinfo_t *ct)
  2082. {
  2083. printf("%s ", cmd);
  2084. if (ct->args) {
  2085. printf("%s ", ct->args);
  2086. }
  2087. printf("-- %s\n", ct->oneline);
  2088. }
  2089. static void help_onecmd(const char *cmd, const cmdinfo_t *ct)
  2090. {
  2091. help_oneline(cmd, ct);
  2092. if (ct->help) {
  2093. ct->help();
  2094. }
  2095. }
  2096. static void help_all(void)
  2097. {
  2098. const cmdinfo_t *ct;
  2099. for (ct = cmdtab; ct < &cmdtab[ncmds]; ct++) {
  2100. help_oneline(ct->name, ct);
  2101. }
  2102. printf("\nUse 'help commandname' for extended help.\n");
  2103. }
  2104. static int help_f(BlockBackend *blk, int argc, char **argv)
  2105. {
  2106. const cmdinfo_t *ct;
  2107. if (argc < 2) {
  2108. help_all();
  2109. return 0;
  2110. }
  2111. ct = find_command(argv[1]);
  2112. if (ct == NULL) {
  2113. printf("command %s not found\n", argv[1]);
  2114. return -EINVAL;
  2115. }
  2116. help_onecmd(argv[1], ct);
  2117. return 0;
  2118. }
  2119. static const cmdinfo_t help_cmd = {
  2120. .name = "help",
  2121. .altname = "?",
  2122. .cfunc = help_f,
  2123. .argmin = 0,
  2124. .argmax = 1,
  2125. .flags = CMD_FLAG_GLOBAL,
  2126. .args = "[command]",
  2127. .oneline = "help for one or all commands",
  2128. };
  2129. /*
  2130. * Called with aio context of blk acquired. Or with qemu_get_aio_context()
  2131. * context acquired if blk is NULL.
  2132. */
  2133. int qemuio_command(BlockBackend *blk, const char *cmd)
  2134. {
  2135. char *input;
  2136. const cmdinfo_t *ct;
  2137. char **v;
  2138. int c;
  2139. int ret = 0;
  2140. input = g_strdup(cmd);
  2141. v = breakline(input, &c);
  2142. if (c) {
  2143. ct = find_command(v[0]);
  2144. if (ct) {
  2145. ret = command(blk, ct, c, v);
  2146. } else {
  2147. fprintf(stderr, "command \"%s\" not found\n", v[0]);
  2148. ret = -EINVAL;
  2149. }
  2150. }
  2151. g_free(input);
  2152. g_free(v);
  2153. return ret;
  2154. }
  2155. static void __attribute((constructor)) init_qemuio_commands(void)
  2156. {
  2157. /* initialize commands */
  2158. qemuio_add_command(&help_cmd);
  2159. qemuio_add_command(&read_cmd);
  2160. qemuio_add_command(&readv_cmd);
  2161. qemuio_add_command(&write_cmd);
  2162. qemuio_add_command(&writev_cmd);
  2163. qemuio_add_command(&aio_read_cmd);
  2164. qemuio_add_command(&aio_write_cmd);
  2165. qemuio_add_command(&aio_flush_cmd);
  2166. qemuio_add_command(&flush_cmd);
  2167. qemuio_add_command(&truncate_cmd);
  2168. qemuio_add_command(&length_cmd);
  2169. qemuio_add_command(&info_cmd);
  2170. qemuio_add_command(&discard_cmd);
  2171. qemuio_add_command(&alloc_cmd);
  2172. qemuio_add_command(&map_cmd);
  2173. qemuio_add_command(&reopen_cmd);
  2174. qemuio_add_command(&break_cmd);
  2175. qemuio_add_command(&remove_break_cmd);
  2176. qemuio_add_command(&resume_cmd);
  2177. qemuio_add_command(&wait_break_cmd);
  2178. qemuio_add_command(&abort_cmd);
  2179. qemuio_add_command(&sleep_cmd);
  2180. qemuio_add_command(&sigraise_cmd);
  2181. }