qemu-img.c 139 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804
  1. /*
  2. * QEMU disk image utility
  3. *
  4. * Copyright (c) 2003-2008 Fabrice Bellard
  5. *
  6. * Permission is hereby granted, free of charge, to any person obtaining a copy
  7. * of this software and associated documentation files (the "Software"), to deal
  8. * in the Software without restriction, including without limitation the rights
  9. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. * copies of the Software, and to permit persons to whom the Software is
  11. * furnished to do so, subject to the following conditions:
  12. *
  13. * The above copyright notice and this permission notice shall be included in
  14. * all copies or substantial portions of the Software.
  15. *
  16. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  19. * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  22. * THE SOFTWARE.
  23. */
  24. #include "qemu/osdep.h"
  25. #include <getopt.h>
  26. #include "qemu-version.h"
  27. #include "qapi/error.h"
  28. #include "qapi/qapi-visit-block-core.h"
  29. #include "qapi/qobject-output-visitor.h"
  30. #include "qapi/qmp/qjson.h"
  31. #include "qapi/qmp/qdict.h"
  32. #include "qapi/qmp/qstring.h"
  33. #include "qemu/cutils.h"
  34. #include "qemu/config-file.h"
  35. #include "qemu/option.h"
  36. #include "qemu/error-report.h"
  37. #include "qemu/log.h"
  38. #include "qom/object_interfaces.h"
  39. #include "sysemu/sysemu.h"
  40. #include "sysemu/block-backend.h"
  41. #include "block/block_int.h"
  42. #include "block/blockjob.h"
  43. #include "block/qapi.h"
  44. #include "crypto/init.h"
  45. #include "trace/control.h"
  46. #define QEMU_IMG_VERSION "qemu-img version " QEMU_FULL_VERSION \
  47. "\n" QEMU_COPYRIGHT "\n"
  48. typedef struct img_cmd_t {
  49. const char *name;
  50. int (*handler)(int argc, char **argv);
  51. } img_cmd_t;
  52. enum {
  53. OPTION_OUTPUT = 256,
  54. OPTION_BACKING_CHAIN = 257,
  55. OPTION_OBJECT = 258,
  56. OPTION_IMAGE_OPTS = 259,
  57. OPTION_PATTERN = 260,
  58. OPTION_FLUSH_INTERVAL = 261,
  59. OPTION_NO_DRAIN = 262,
  60. OPTION_TARGET_IMAGE_OPTS = 263,
  61. OPTION_SIZE = 264,
  62. OPTION_PREALLOCATION = 265,
  63. OPTION_SHRINK = 266,
  64. };
  65. typedef enum OutputFormat {
  66. OFORMAT_JSON,
  67. OFORMAT_HUMAN,
  68. } OutputFormat;
  69. /* Default to cache=writeback as data integrity is not important for qemu-img */
  70. #define BDRV_DEFAULT_CACHE "writeback"
  71. static void format_print(void *opaque, const char *name)
  72. {
  73. printf(" %s", name);
  74. }
  75. static void QEMU_NORETURN GCC_FMT_ATTR(1, 2) error_exit(const char *fmt, ...)
  76. {
  77. va_list ap;
  78. error_printf("qemu-img: ");
  79. va_start(ap, fmt);
  80. error_vprintf(fmt, ap);
  81. va_end(ap);
  82. error_printf("\nTry 'qemu-img --help' for more information\n");
  83. exit(EXIT_FAILURE);
  84. }
  85. static void QEMU_NORETURN missing_argument(const char *option)
  86. {
  87. error_exit("missing argument for option '%s'", option);
  88. }
  89. static void QEMU_NORETURN unrecognized_option(const char *option)
  90. {
  91. error_exit("unrecognized option '%s'", option);
  92. }
  93. /* Please keep in synch with qemu-img.texi */
  94. static void QEMU_NORETURN help(void)
  95. {
  96. const char *help_msg =
  97. QEMU_IMG_VERSION
  98. "usage: qemu-img [standard options] command [command options]\n"
  99. "QEMU disk image utility\n"
  100. "\n"
  101. " '-h', '--help' display this help and exit\n"
  102. " '-V', '--version' output version information and exit\n"
  103. " '-T', '--trace' [[enable=]<pattern>][,events=<file>][,file=<file>]\n"
  104. " specify tracing options\n"
  105. "\n"
  106. "Command syntax:\n"
  107. #define DEF(option, callback, arg_string) \
  108. " " arg_string "\n"
  109. #include "qemu-img-cmds.h"
  110. #undef DEF
  111. #undef GEN_DOCS
  112. "\n"
  113. "Command parameters:\n"
  114. " 'filename' is a disk image filename\n"
  115. " 'objectdef' is a QEMU user creatable object definition. See the qemu(1)\n"
  116. " manual page for a description of the object properties. The most common\n"
  117. " object type is a 'secret', which is used to supply passwords and/or\n"
  118. " encryption keys.\n"
  119. " 'fmt' is the disk image format. It is guessed automatically in most cases\n"
  120. " 'cache' is the cache mode used to write the output disk image, the valid\n"
  121. " options are: 'none', 'writeback' (default, except for convert), 'writethrough',\n"
  122. " 'directsync' and 'unsafe' (default for convert)\n"
  123. " 'src_cache' is the cache mode used to read input disk images, the valid\n"
  124. " options are the same as for the 'cache' option\n"
  125. " 'size' is the disk image size in bytes. Optional suffixes\n"
  126. " 'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' (gigabyte, 1024M),\n"
  127. " 'T' (terabyte, 1024G), 'P' (petabyte, 1024T) and 'E' (exabyte, 1024P) are\n"
  128. " supported. 'b' is ignored.\n"
  129. " 'output_filename' is the destination disk image filename\n"
  130. " 'output_fmt' is the destination format\n"
  131. " 'options' is a comma separated list of format specific options in a\n"
  132. " name=value format. Use -o ? for an overview of the options supported by the\n"
  133. " used format\n"
  134. " 'snapshot_param' is param used for internal snapshot, format\n"
  135. " is 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
  136. " '[ID_OR_NAME]'\n"
  137. " 'snapshot_id_or_name' is deprecated, use 'snapshot_param'\n"
  138. " instead\n"
  139. " '-c' indicates that target image must be compressed (qcow format only)\n"
  140. " '-u' allows unsafe backing chains. For rebasing, it is assumed that old and\n"
  141. " new backing file match exactly. The image doesn't need a working\n"
  142. " backing file before rebasing in this case (useful for renaming the\n"
  143. " backing file). For image creation, allow creating without attempting\n"
  144. " to open the backing file.\n"
  145. " '-h' with or without a command shows this help and lists the supported formats\n"
  146. " '-p' show progress of command (only certain commands)\n"
  147. " '-q' use Quiet mode - do not print any output (except errors)\n"
  148. " '-S' indicates the consecutive number of bytes (defaults to 4k) that must\n"
  149. " contain only zeros for qemu-img to create a sparse image during\n"
  150. " conversion. If the number of bytes is 0, the source will not be scanned for\n"
  151. " unallocated or zero sectors, and the destination image will always be\n"
  152. " fully allocated\n"
  153. " '--output' takes the format in which the output must be done (human or json)\n"
  154. " '-n' skips the target volume creation (useful if the volume is created\n"
  155. " prior to running qemu-img)\n"
  156. "\n"
  157. "Parameters to check subcommand:\n"
  158. " '-r' tries to repair any inconsistencies that are found during the check.\n"
  159. " '-r leaks' repairs only cluster leaks, whereas '-r all' fixes all\n"
  160. " kinds of errors, with a higher risk of choosing the wrong fix or\n"
  161. " hiding corruption that has already occurred.\n"
  162. "\n"
  163. "Parameters to convert subcommand:\n"
  164. " '-m' specifies how many coroutines work in parallel during the convert\n"
  165. " process (defaults to 8)\n"
  166. " '-W' allow to write to the target out of order rather than sequential\n"
  167. "\n"
  168. "Parameters to snapshot subcommand:\n"
  169. " 'snapshot' is the name of the snapshot to create, apply or delete\n"
  170. " '-a' applies a snapshot (revert disk to saved state)\n"
  171. " '-c' creates a snapshot\n"
  172. " '-d' deletes a snapshot\n"
  173. " '-l' lists all snapshots in the given image\n"
  174. "\n"
  175. "Parameters to compare subcommand:\n"
  176. " '-f' first image format\n"
  177. " '-F' second image format\n"
  178. " '-s' run in Strict mode - fail on different image size or sector allocation\n"
  179. "\n"
  180. "Parameters to dd subcommand:\n"
  181. " 'bs=BYTES' read and write up to BYTES bytes at a time "
  182. "(default: 512)\n"
  183. " 'count=N' copy only N input blocks\n"
  184. " 'if=FILE' read from FILE\n"
  185. " 'of=FILE' write to FILE\n"
  186. " 'skip=N' skip N bs-sized blocks at the start of input\n";
  187. printf("%s\nSupported formats:", help_msg);
  188. bdrv_iterate_format(format_print, NULL);
  189. printf("\n\n" QEMU_HELP_BOTTOM "\n");
  190. exit(EXIT_SUCCESS);
  191. }
  192. static QemuOptsList qemu_object_opts = {
  193. .name = "object",
  194. .implied_opt_name = "qom-type",
  195. .head = QTAILQ_HEAD_INITIALIZER(qemu_object_opts.head),
  196. .desc = {
  197. { }
  198. },
  199. };
  200. static QemuOptsList qemu_source_opts = {
  201. .name = "source",
  202. .implied_opt_name = "file",
  203. .head = QTAILQ_HEAD_INITIALIZER(qemu_source_opts.head),
  204. .desc = {
  205. { }
  206. },
  207. };
  208. static int GCC_FMT_ATTR(2, 3) qprintf(bool quiet, const char *fmt, ...)
  209. {
  210. int ret = 0;
  211. if (!quiet) {
  212. va_list args;
  213. va_start(args, fmt);
  214. ret = vprintf(fmt, args);
  215. va_end(args);
  216. }
  217. return ret;
  218. }
  219. static int print_block_option_help(const char *filename, const char *fmt)
  220. {
  221. BlockDriver *drv, *proto_drv;
  222. QemuOptsList *create_opts = NULL;
  223. Error *local_err = NULL;
  224. /* Find driver and parse its options */
  225. drv = bdrv_find_format(fmt);
  226. if (!drv) {
  227. error_report("Unknown file format '%s'", fmt);
  228. return 1;
  229. }
  230. create_opts = qemu_opts_append(create_opts, drv->create_opts);
  231. if (filename) {
  232. proto_drv = bdrv_find_protocol(filename, true, &local_err);
  233. if (!proto_drv) {
  234. error_report_err(local_err);
  235. qemu_opts_free(create_opts);
  236. return 1;
  237. }
  238. create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
  239. }
  240. qemu_opts_print_help(create_opts);
  241. qemu_opts_free(create_opts);
  242. return 0;
  243. }
  244. static BlockBackend *img_open_opts(const char *optstr,
  245. QemuOpts *opts, int flags, bool writethrough,
  246. bool quiet, bool force_share)
  247. {
  248. QDict *options;
  249. Error *local_err = NULL;
  250. BlockBackend *blk;
  251. options = qemu_opts_to_qdict(opts, NULL);
  252. if (force_share) {
  253. if (qdict_haskey(options, BDRV_OPT_FORCE_SHARE)
  254. && strcmp(qdict_get_str(options, BDRV_OPT_FORCE_SHARE), "on")) {
  255. error_report("--force-share/-U conflicts with image options");
  256. QDECREF(options);
  257. return NULL;
  258. }
  259. qdict_put_str(options, BDRV_OPT_FORCE_SHARE, "on");
  260. }
  261. blk = blk_new_open(NULL, NULL, options, flags, &local_err);
  262. if (!blk) {
  263. error_reportf_err(local_err, "Could not open '%s': ", optstr);
  264. return NULL;
  265. }
  266. blk_set_enable_write_cache(blk, !writethrough);
  267. return blk;
  268. }
  269. static BlockBackend *img_open_file(const char *filename,
  270. QDict *options,
  271. const char *fmt, int flags,
  272. bool writethrough, bool quiet,
  273. bool force_share)
  274. {
  275. BlockBackend *blk;
  276. Error *local_err = NULL;
  277. if (!options) {
  278. options = qdict_new();
  279. }
  280. if (fmt) {
  281. qdict_put_str(options, "driver", fmt);
  282. }
  283. if (force_share) {
  284. qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
  285. }
  286. blk = blk_new_open(filename, NULL, options, flags, &local_err);
  287. if (!blk) {
  288. error_reportf_err(local_err, "Could not open '%s': ", filename);
  289. return NULL;
  290. }
  291. blk_set_enable_write_cache(blk, !writethrough);
  292. return blk;
  293. }
  294. static int img_add_key_secrets(void *opaque,
  295. const char *name, const char *value,
  296. Error **errp)
  297. {
  298. QDict *options = opaque;
  299. if (g_str_has_suffix(name, "key-secret")) {
  300. qdict_put_str(options, name, value);
  301. }
  302. return 0;
  303. }
  304. static BlockBackend *img_open_new_file(const char *filename,
  305. QemuOpts *create_opts,
  306. const char *fmt, int flags,
  307. bool writethrough, bool quiet,
  308. bool force_share)
  309. {
  310. QDict *options = NULL;
  311. options = qdict_new();
  312. qemu_opt_foreach(create_opts, img_add_key_secrets, options, &error_abort);
  313. return img_open_file(filename, options, fmt, flags, writethrough, quiet,
  314. force_share);
  315. }
  316. static BlockBackend *img_open(bool image_opts,
  317. const char *filename,
  318. const char *fmt, int flags, bool writethrough,
  319. bool quiet, bool force_share)
  320. {
  321. BlockBackend *blk;
  322. if (image_opts) {
  323. QemuOpts *opts;
  324. if (fmt) {
  325. error_report("--image-opts and --format are mutually exclusive");
  326. return NULL;
  327. }
  328. opts = qemu_opts_parse_noisily(qemu_find_opts("source"),
  329. filename, true);
  330. if (!opts) {
  331. return NULL;
  332. }
  333. blk = img_open_opts(filename, opts, flags, writethrough, quiet,
  334. force_share);
  335. } else {
  336. blk = img_open_file(filename, NULL, fmt, flags, writethrough, quiet,
  337. force_share);
  338. }
  339. return blk;
  340. }
  341. static int add_old_style_options(const char *fmt, QemuOpts *opts,
  342. const char *base_filename,
  343. const char *base_fmt)
  344. {
  345. Error *err = NULL;
  346. if (base_filename) {
  347. qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename, &err);
  348. if (err) {
  349. error_report("Backing file not supported for file format '%s'",
  350. fmt);
  351. error_free(err);
  352. return -1;
  353. }
  354. }
  355. if (base_fmt) {
  356. qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, &err);
  357. if (err) {
  358. error_report("Backing file format not supported for file "
  359. "format '%s'", fmt);
  360. error_free(err);
  361. return -1;
  362. }
  363. }
  364. return 0;
  365. }
  366. static int64_t cvtnum(const char *s)
  367. {
  368. int err;
  369. uint64_t value;
  370. err = qemu_strtosz(s, NULL, &value);
  371. if (err < 0) {
  372. return err;
  373. }
  374. if (value > INT64_MAX) {
  375. return -ERANGE;
  376. }
  377. return value;
  378. }
  379. static int img_create(int argc, char **argv)
  380. {
  381. int c;
  382. uint64_t img_size = -1;
  383. const char *fmt = "raw";
  384. const char *base_fmt = NULL;
  385. const char *filename;
  386. const char *base_filename = NULL;
  387. char *options = NULL;
  388. Error *local_err = NULL;
  389. bool quiet = false;
  390. int flags = 0;
  391. for(;;) {
  392. static const struct option long_options[] = {
  393. {"help", no_argument, 0, 'h'},
  394. {"object", required_argument, 0, OPTION_OBJECT},
  395. {0, 0, 0, 0}
  396. };
  397. c = getopt_long(argc, argv, ":F:b:f:ho:qu",
  398. long_options, NULL);
  399. if (c == -1) {
  400. break;
  401. }
  402. switch(c) {
  403. case ':':
  404. missing_argument(argv[optind - 1]);
  405. break;
  406. case '?':
  407. unrecognized_option(argv[optind - 1]);
  408. break;
  409. case 'h':
  410. help();
  411. break;
  412. case 'F':
  413. base_fmt = optarg;
  414. break;
  415. case 'b':
  416. base_filename = optarg;
  417. break;
  418. case 'f':
  419. fmt = optarg;
  420. break;
  421. case 'o':
  422. if (!is_valid_option_list(optarg)) {
  423. error_report("Invalid option list: %s", optarg);
  424. goto fail;
  425. }
  426. if (!options) {
  427. options = g_strdup(optarg);
  428. } else {
  429. char *old_options = options;
  430. options = g_strdup_printf("%s,%s", options, optarg);
  431. g_free(old_options);
  432. }
  433. break;
  434. case 'q':
  435. quiet = true;
  436. break;
  437. case 'u':
  438. flags |= BDRV_O_NO_BACKING;
  439. break;
  440. case OPTION_OBJECT: {
  441. QemuOpts *opts;
  442. opts = qemu_opts_parse_noisily(&qemu_object_opts,
  443. optarg, true);
  444. if (!opts) {
  445. goto fail;
  446. }
  447. } break;
  448. }
  449. }
  450. /* Get the filename */
  451. filename = (optind < argc) ? argv[optind] : NULL;
  452. if (options && has_help_option(options)) {
  453. g_free(options);
  454. return print_block_option_help(filename, fmt);
  455. }
  456. if (optind >= argc) {
  457. error_exit("Expecting image file name");
  458. }
  459. optind++;
  460. if (qemu_opts_foreach(&qemu_object_opts,
  461. user_creatable_add_opts_foreach,
  462. NULL, NULL)) {
  463. goto fail;
  464. }
  465. /* Get image size, if specified */
  466. if (optind < argc) {
  467. int64_t sval;
  468. sval = cvtnum(argv[optind++]);
  469. if (sval < 0) {
  470. if (sval == -ERANGE) {
  471. error_report("Image size must be less than 8 EiB!");
  472. } else {
  473. error_report("Invalid image size specified! You may use k, M, "
  474. "G, T, P or E suffixes for ");
  475. error_report("kilobytes, megabytes, gigabytes, terabytes, "
  476. "petabytes and exabytes.");
  477. }
  478. goto fail;
  479. }
  480. img_size = (uint64_t)sval;
  481. }
  482. if (optind != argc) {
  483. error_exit("Unexpected argument: %s", argv[optind]);
  484. }
  485. bdrv_img_create(filename, fmt, base_filename, base_fmt,
  486. options, img_size, flags, quiet, &local_err);
  487. if (local_err) {
  488. error_reportf_err(local_err, "%s: ", filename);
  489. goto fail;
  490. }
  491. g_free(options);
  492. return 0;
  493. fail:
  494. g_free(options);
  495. return 1;
  496. }
  497. static void dump_json_image_check(ImageCheck *check, bool quiet)
  498. {
  499. QString *str;
  500. QObject *obj;
  501. Visitor *v = qobject_output_visitor_new(&obj);
  502. visit_type_ImageCheck(v, NULL, &check, &error_abort);
  503. visit_complete(v, &obj);
  504. str = qobject_to_json_pretty(obj);
  505. assert(str != NULL);
  506. qprintf(quiet, "%s\n", qstring_get_str(str));
  507. qobject_decref(obj);
  508. visit_free(v);
  509. QDECREF(str);
  510. }
  511. static void dump_human_image_check(ImageCheck *check, bool quiet)
  512. {
  513. if (!(check->corruptions || check->leaks || check->check_errors)) {
  514. qprintf(quiet, "No errors were found on the image.\n");
  515. } else {
  516. if (check->corruptions) {
  517. qprintf(quiet, "\n%" PRId64 " errors were found on the image.\n"
  518. "Data may be corrupted, or further writes to the image "
  519. "may corrupt it.\n",
  520. check->corruptions);
  521. }
  522. if (check->leaks) {
  523. qprintf(quiet,
  524. "\n%" PRId64 " leaked clusters were found on the image.\n"
  525. "This means waste of disk space, but no harm to data.\n",
  526. check->leaks);
  527. }
  528. if (check->check_errors) {
  529. qprintf(quiet,
  530. "\n%" PRId64
  531. " internal errors have occurred during the check.\n",
  532. check->check_errors);
  533. }
  534. }
  535. if (check->total_clusters != 0 && check->allocated_clusters != 0) {
  536. qprintf(quiet, "%" PRId64 "/%" PRId64 " = %0.2f%% allocated, "
  537. "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
  538. check->allocated_clusters, check->total_clusters,
  539. check->allocated_clusters * 100.0 / check->total_clusters,
  540. check->fragmented_clusters * 100.0 / check->allocated_clusters,
  541. check->compressed_clusters * 100.0 /
  542. check->allocated_clusters);
  543. }
  544. if (check->image_end_offset) {
  545. qprintf(quiet,
  546. "Image end offset: %" PRId64 "\n", check->image_end_offset);
  547. }
  548. }
  549. static int collect_image_check(BlockDriverState *bs,
  550. ImageCheck *check,
  551. const char *filename,
  552. const char *fmt,
  553. int fix)
  554. {
  555. int ret;
  556. BdrvCheckResult result;
  557. ret = bdrv_check(bs, &result, fix);
  558. if (ret < 0) {
  559. return ret;
  560. }
  561. check->filename = g_strdup(filename);
  562. check->format = g_strdup(bdrv_get_format_name(bs));
  563. check->check_errors = result.check_errors;
  564. check->corruptions = result.corruptions;
  565. check->has_corruptions = result.corruptions != 0;
  566. check->leaks = result.leaks;
  567. check->has_leaks = result.leaks != 0;
  568. check->corruptions_fixed = result.corruptions_fixed;
  569. check->has_corruptions_fixed = result.corruptions != 0;
  570. check->leaks_fixed = result.leaks_fixed;
  571. check->has_leaks_fixed = result.leaks != 0;
  572. check->image_end_offset = result.image_end_offset;
  573. check->has_image_end_offset = result.image_end_offset != 0;
  574. check->total_clusters = result.bfi.total_clusters;
  575. check->has_total_clusters = result.bfi.total_clusters != 0;
  576. check->allocated_clusters = result.bfi.allocated_clusters;
  577. check->has_allocated_clusters = result.bfi.allocated_clusters != 0;
  578. check->fragmented_clusters = result.bfi.fragmented_clusters;
  579. check->has_fragmented_clusters = result.bfi.fragmented_clusters != 0;
  580. check->compressed_clusters = result.bfi.compressed_clusters;
  581. check->has_compressed_clusters = result.bfi.compressed_clusters != 0;
  582. return 0;
  583. }
  584. /*
  585. * Checks an image for consistency. Exit codes:
  586. *
  587. * 0 - Check completed, image is good
  588. * 1 - Check not completed because of internal errors
  589. * 2 - Check completed, image is corrupted
  590. * 3 - Check completed, image has leaked clusters, but is good otherwise
  591. * 63 - Checks are not supported by the image format
  592. */
  593. static int img_check(int argc, char **argv)
  594. {
  595. int c, ret;
  596. OutputFormat output_format = OFORMAT_HUMAN;
  597. const char *filename, *fmt, *output, *cache;
  598. BlockBackend *blk;
  599. BlockDriverState *bs;
  600. int fix = 0;
  601. int flags = BDRV_O_CHECK;
  602. bool writethrough;
  603. ImageCheck *check;
  604. bool quiet = false;
  605. bool image_opts = false;
  606. bool force_share = false;
  607. fmt = NULL;
  608. output = NULL;
  609. cache = BDRV_DEFAULT_CACHE;
  610. for(;;) {
  611. int option_index = 0;
  612. static const struct option long_options[] = {
  613. {"help", no_argument, 0, 'h'},
  614. {"format", required_argument, 0, 'f'},
  615. {"repair", required_argument, 0, 'r'},
  616. {"output", required_argument, 0, OPTION_OUTPUT},
  617. {"object", required_argument, 0, OPTION_OBJECT},
  618. {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
  619. {"force-share", no_argument, 0, 'U'},
  620. {0, 0, 0, 0}
  621. };
  622. c = getopt_long(argc, argv, ":hf:r:T:qU",
  623. long_options, &option_index);
  624. if (c == -1) {
  625. break;
  626. }
  627. switch(c) {
  628. case ':':
  629. missing_argument(argv[optind - 1]);
  630. break;
  631. case '?':
  632. unrecognized_option(argv[optind - 1]);
  633. break;
  634. case 'h':
  635. help();
  636. break;
  637. case 'f':
  638. fmt = optarg;
  639. break;
  640. case 'r':
  641. flags |= BDRV_O_RDWR;
  642. if (!strcmp(optarg, "leaks")) {
  643. fix = BDRV_FIX_LEAKS;
  644. } else if (!strcmp(optarg, "all")) {
  645. fix = BDRV_FIX_LEAKS | BDRV_FIX_ERRORS;
  646. } else {
  647. error_exit("Unknown option value for -r "
  648. "(expecting 'leaks' or 'all'): %s", optarg);
  649. }
  650. break;
  651. case OPTION_OUTPUT:
  652. output = optarg;
  653. break;
  654. case 'T':
  655. cache = optarg;
  656. break;
  657. case 'q':
  658. quiet = true;
  659. break;
  660. case 'U':
  661. force_share = true;
  662. break;
  663. case OPTION_OBJECT: {
  664. QemuOpts *opts;
  665. opts = qemu_opts_parse_noisily(&qemu_object_opts,
  666. optarg, true);
  667. if (!opts) {
  668. return 1;
  669. }
  670. } break;
  671. case OPTION_IMAGE_OPTS:
  672. image_opts = true;
  673. break;
  674. }
  675. }
  676. if (optind != argc - 1) {
  677. error_exit("Expecting one image file name");
  678. }
  679. filename = argv[optind++];
  680. if (output && !strcmp(output, "json")) {
  681. output_format = OFORMAT_JSON;
  682. } else if (output && !strcmp(output, "human")) {
  683. output_format = OFORMAT_HUMAN;
  684. } else if (output) {
  685. error_report("--output must be used with human or json as argument.");
  686. return 1;
  687. }
  688. if (qemu_opts_foreach(&qemu_object_opts,
  689. user_creatable_add_opts_foreach,
  690. NULL, NULL)) {
  691. return 1;
  692. }
  693. ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
  694. if (ret < 0) {
  695. error_report("Invalid source cache option: %s", cache);
  696. return 1;
  697. }
  698. blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
  699. force_share);
  700. if (!blk) {
  701. return 1;
  702. }
  703. bs = blk_bs(blk);
  704. check = g_new0(ImageCheck, 1);
  705. ret = collect_image_check(bs, check, filename, fmt, fix);
  706. if (ret == -ENOTSUP) {
  707. error_report("This image format does not support checks");
  708. ret = 63;
  709. goto fail;
  710. }
  711. if (check->corruptions_fixed || check->leaks_fixed) {
  712. int corruptions_fixed, leaks_fixed;
  713. leaks_fixed = check->leaks_fixed;
  714. corruptions_fixed = check->corruptions_fixed;
  715. if (output_format == OFORMAT_HUMAN) {
  716. qprintf(quiet,
  717. "The following inconsistencies were found and repaired:\n\n"
  718. " %" PRId64 " leaked clusters\n"
  719. " %" PRId64 " corruptions\n\n"
  720. "Double checking the fixed image now...\n",
  721. check->leaks_fixed,
  722. check->corruptions_fixed);
  723. }
  724. ret = collect_image_check(bs, check, filename, fmt, 0);
  725. check->leaks_fixed = leaks_fixed;
  726. check->corruptions_fixed = corruptions_fixed;
  727. }
  728. if (!ret) {
  729. switch (output_format) {
  730. case OFORMAT_HUMAN:
  731. dump_human_image_check(check, quiet);
  732. break;
  733. case OFORMAT_JSON:
  734. dump_json_image_check(check, quiet);
  735. break;
  736. }
  737. }
  738. if (ret || check->check_errors) {
  739. if (ret) {
  740. error_report("Check failed: %s", strerror(-ret));
  741. } else {
  742. error_report("Check failed");
  743. }
  744. ret = 1;
  745. goto fail;
  746. }
  747. if (check->corruptions) {
  748. ret = 2;
  749. } else if (check->leaks) {
  750. ret = 3;
  751. } else {
  752. ret = 0;
  753. }
  754. fail:
  755. qapi_free_ImageCheck(check);
  756. blk_unref(blk);
  757. return ret;
  758. }
  759. typedef struct CommonBlockJobCBInfo {
  760. BlockDriverState *bs;
  761. Error **errp;
  762. } CommonBlockJobCBInfo;
  763. static void common_block_job_cb(void *opaque, int ret)
  764. {
  765. CommonBlockJobCBInfo *cbi = opaque;
  766. if (ret < 0) {
  767. error_setg_errno(cbi->errp, -ret, "Block job failed");
  768. }
  769. }
  770. static void run_block_job(BlockJob *job, Error **errp)
  771. {
  772. AioContext *aio_context = blk_get_aio_context(job->blk);
  773. int ret = 0;
  774. aio_context_acquire(aio_context);
  775. block_job_ref(job);
  776. do {
  777. aio_poll(aio_context, true);
  778. qemu_progress_print(job->len ?
  779. ((float)job->offset / job->len * 100.f) : 0.0f, 0);
  780. } while (!job->ready && !job->completed);
  781. if (!job->completed) {
  782. ret = block_job_complete_sync(job, errp);
  783. } else {
  784. ret = job->ret;
  785. }
  786. block_job_unref(job);
  787. aio_context_release(aio_context);
  788. /* publish completion progress only when success */
  789. if (!ret) {
  790. qemu_progress_print(100.f, 0);
  791. }
  792. }
  793. static int img_commit(int argc, char **argv)
  794. {
  795. int c, ret, flags;
  796. const char *filename, *fmt, *cache, *base;
  797. BlockBackend *blk;
  798. BlockDriverState *bs, *base_bs;
  799. BlockJob *job;
  800. bool progress = false, quiet = false, drop = false;
  801. bool writethrough;
  802. Error *local_err = NULL;
  803. CommonBlockJobCBInfo cbi;
  804. bool image_opts = false;
  805. AioContext *aio_context;
  806. fmt = NULL;
  807. cache = BDRV_DEFAULT_CACHE;
  808. base = NULL;
  809. for(;;) {
  810. static const struct option long_options[] = {
  811. {"help", no_argument, 0, 'h'},
  812. {"object", required_argument, 0, OPTION_OBJECT},
  813. {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
  814. {0, 0, 0, 0}
  815. };
  816. c = getopt_long(argc, argv, ":f:ht:b:dpq",
  817. long_options, NULL);
  818. if (c == -1) {
  819. break;
  820. }
  821. switch(c) {
  822. case ':':
  823. missing_argument(argv[optind - 1]);
  824. break;
  825. case '?':
  826. unrecognized_option(argv[optind - 1]);
  827. break;
  828. case 'h':
  829. help();
  830. break;
  831. case 'f':
  832. fmt = optarg;
  833. break;
  834. case 't':
  835. cache = optarg;
  836. break;
  837. case 'b':
  838. base = optarg;
  839. /* -b implies -d */
  840. drop = true;
  841. break;
  842. case 'd':
  843. drop = true;
  844. break;
  845. case 'p':
  846. progress = true;
  847. break;
  848. case 'q':
  849. quiet = true;
  850. break;
  851. case OPTION_OBJECT: {
  852. QemuOpts *opts;
  853. opts = qemu_opts_parse_noisily(&qemu_object_opts,
  854. optarg, true);
  855. if (!opts) {
  856. return 1;
  857. }
  858. } break;
  859. case OPTION_IMAGE_OPTS:
  860. image_opts = true;
  861. break;
  862. }
  863. }
  864. /* Progress is not shown in Quiet mode */
  865. if (quiet) {
  866. progress = false;
  867. }
  868. if (optind != argc - 1) {
  869. error_exit("Expecting one image file name");
  870. }
  871. filename = argv[optind++];
  872. if (qemu_opts_foreach(&qemu_object_opts,
  873. user_creatable_add_opts_foreach,
  874. NULL, NULL)) {
  875. return 1;
  876. }
  877. flags = BDRV_O_RDWR | BDRV_O_UNMAP;
  878. ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
  879. if (ret < 0) {
  880. error_report("Invalid cache option: %s", cache);
  881. return 1;
  882. }
  883. blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
  884. false);
  885. if (!blk) {
  886. return 1;
  887. }
  888. bs = blk_bs(blk);
  889. qemu_progress_init(progress, 1.f);
  890. qemu_progress_print(0.f, 100);
  891. if (base) {
  892. base_bs = bdrv_find_backing_image(bs, base);
  893. if (!base_bs) {
  894. error_setg(&local_err,
  895. "Did not find '%s' in the backing chain of '%s'",
  896. base, filename);
  897. goto done;
  898. }
  899. } else {
  900. /* This is different from QMP, which by default uses the deepest file in
  901. * the backing chain (i.e., the very base); however, the traditional
  902. * behavior of qemu-img commit is using the immediate backing file. */
  903. base_bs = backing_bs(bs);
  904. if (!base_bs) {
  905. error_setg(&local_err, "Image does not have a backing file");
  906. goto done;
  907. }
  908. }
  909. cbi = (CommonBlockJobCBInfo){
  910. .errp = &local_err,
  911. .bs = bs,
  912. };
  913. aio_context = bdrv_get_aio_context(bs);
  914. aio_context_acquire(aio_context);
  915. commit_active_start("commit", bs, base_bs, BLOCK_JOB_DEFAULT, 0,
  916. BLOCKDEV_ON_ERROR_REPORT, NULL, common_block_job_cb,
  917. &cbi, false, &local_err);
  918. aio_context_release(aio_context);
  919. if (local_err) {
  920. goto done;
  921. }
  922. /* When the block job completes, the BlockBackend reference will point to
  923. * the old backing file. In order to avoid that the top image is already
  924. * deleted, so we can still empty it afterwards, increment the reference
  925. * counter here preemptively. */
  926. if (!drop) {
  927. bdrv_ref(bs);
  928. }
  929. job = block_job_get("commit");
  930. run_block_job(job, &local_err);
  931. if (local_err) {
  932. goto unref_backing;
  933. }
  934. if (!drop && bs->drv->bdrv_make_empty) {
  935. ret = bs->drv->bdrv_make_empty(bs);
  936. if (ret) {
  937. error_setg_errno(&local_err, -ret, "Could not empty %s",
  938. filename);
  939. goto unref_backing;
  940. }
  941. }
  942. unref_backing:
  943. if (!drop) {
  944. bdrv_unref(bs);
  945. }
  946. done:
  947. qemu_progress_end();
  948. blk_unref(blk);
  949. if (local_err) {
  950. error_report_err(local_err);
  951. return 1;
  952. }
  953. qprintf(quiet, "Image committed.\n");
  954. return 0;
  955. }
  956. /*
  957. * Returns -1 if 'buf' contains only zeroes, otherwise the byte index
  958. * of the first sector boundary within buf where the sector contains a
  959. * non-zero byte. This function is robust to a buffer that is not
  960. * sector-aligned.
  961. */
  962. static int64_t find_nonzero(const uint8_t *buf, int64_t n)
  963. {
  964. int64_t i;
  965. int64_t end = QEMU_ALIGN_DOWN(n, BDRV_SECTOR_SIZE);
  966. for (i = 0; i < end; i += BDRV_SECTOR_SIZE) {
  967. if (!buffer_is_zero(buf + i, BDRV_SECTOR_SIZE)) {
  968. return i;
  969. }
  970. }
  971. if (i < n && !buffer_is_zero(buf + i, n - end)) {
  972. return i;
  973. }
  974. return -1;
  975. }
  976. /*
  977. * Returns true iff the first sector pointed to by 'buf' contains at least
  978. * a non-NUL byte.
  979. *
  980. * 'pnum' is set to the number of sectors (including and immediately following
  981. * the first one) that are known to be in the same allocated/unallocated state.
  982. */
  983. static int is_allocated_sectors(const uint8_t *buf, int n, int *pnum)
  984. {
  985. bool is_zero;
  986. int i;
  987. if (n <= 0) {
  988. *pnum = 0;
  989. return 0;
  990. }
  991. is_zero = buffer_is_zero(buf, 512);
  992. for(i = 1; i < n; i++) {
  993. buf += 512;
  994. if (is_zero != buffer_is_zero(buf, 512)) {
  995. break;
  996. }
  997. }
  998. *pnum = i;
  999. return !is_zero;
  1000. }
  1001. /*
  1002. * Like is_allocated_sectors, but if the buffer starts with a used sector,
  1003. * up to 'min' consecutive sectors containing zeros are ignored. This avoids
  1004. * breaking up write requests for only small sparse areas.
  1005. */
  1006. static int is_allocated_sectors_min(const uint8_t *buf, int n, int *pnum,
  1007. int min)
  1008. {
  1009. int ret;
  1010. int num_checked, num_used;
  1011. if (n < min) {
  1012. min = n;
  1013. }
  1014. ret = is_allocated_sectors(buf, n, pnum);
  1015. if (!ret) {
  1016. return ret;
  1017. }
  1018. num_used = *pnum;
  1019. buf += BDRV_SECTOR_SIZE * *pnum;
  1020. n -= *pnum;
  1021. num_checked = num_used;
  1022. while (n > 0) {
  1023. ret = is_allocated_sectors(buf, n, pnum);
  1024. buf += BDRV_SECTOR_SIZE * *pnum;
  1025. n -= *pnum;
  1026. num_checked += *pnum;
  1027. if (ret) {
  1028. num_used = num_checked;
  1029. } else if (*pnum >= min) {
  1030. break;
  1031. }
  1032. }
  1033. *pnum = num_used;
  1034. return 1;
  1035. }
  1036. /*
  1037. * Compares two buffers sector by sector. Returns 0 if the first
  1038. * sector of each buffer matches, non-zero otherwise.
  1039. *
  1040. * pnum is set to the sector-aligned size of the buffer prefix that
  1041. * has the same matching status as the first sector.
  1042. */
  1043. static int compare_buffers(const uint8_t *buf1, const uint8_t *buf2,
  1044. int64_t bytes, int64_t *pnum)
  1045. {
  1046. bool res;
  1047. int64_t i = MIN(bytes, BDRV_SECTOR_SIZE);
  1048. assert(bytes > 0);
  1049. res = !!memcmp(buf1, buf2, i);
  1050. while (i < bytes) {
  1051. int64_t len = MIN(bytes - i, BDRV_SECTOR_SIZE);
  1052. if (!!memcmp(buf1 + i, buf2 + i, len) != res) {
  1053. break;
  1054. }
  1055. i += len;
  1056. }
  1057. *pnum = i;
  1058. return res;
  1059. }
  1060. #define IO_BUF_SIZE (2 * 1024 * 1024)
  1061. /*
  1062. * Check if passed sectors are empty (not allocated or contain only 0 bytes)
  1063. *
  1064. * Intended for use by 'qemu-img compare': Returns 0 in case sectors are
  1065. * filled with 0, 1 if sectors contain non-zero data (this is a comparison
  1066. * failure), and 4 on error (the exit status for read errors), after emitting
  1067. * an error message.
  1068. *
  1069. * @param blk: BlockBackend for the image
  1070. * @param offset: Starting offset to check
  1071. * @param bytes: Number of bytes to check
  1072. * @param filename: Name of disk file we are checking (logging purpose)
  1073. * @param buffer: Allocated buffer for storing read data
  1074. * @param quiet: Flag for quiet mode
  1075. */
  1076. static int check_empty_sectors(BlockBackend *blk, int64_t offset,
  1077. int64_t bytes, const char *filename,
  1078. uint8_t *buffer, bool quiet)
  1079. {
  1080. int ret = 0;
  1081. int64_t idx;
  1082. ret = blk_pread(blk, offset, buffer, bytes);
  1083. if (ret < 0) {
  1084. error_report("Error while reading offset %" PRId64 " of %s: %s",
  1085. offset, filename, strerror(-ret));
  1086. return 4;
  1087. }
  1088. idx = find_nonzero(buffer, bytes);
  1089. if (idx >= 0) {
  1090. qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
  1091. offset + idx);
  1092. return 1;
  1093. }
  1094. return 0;
  1095. }
  1096. /*
  1097. * Compares two images. Exit codes:
  1098. *
  1099. * 0 - Images are identical
  1100. * 1 - Images differ
  1101. * >1 - Error occurred
  1102. */
  1103. static int img_compare(int argc, char **argv)
  1104. {
  1105. const char *fmt1 = NULL, *fmt2 = NULL, *cache, *filename1, *filename2;
  1106. BlockBackend *blk1, *blk2;
  1107. BlockDriverState *bs1, *bs2;
  1108. int64_t total_size1, total_size2;
  1109. uint8_t *buf1 = NULL, *buf2 = NULL;
  1110. int64_t pnum1, pnum2;
  1111. int allocated1, allocated2;
  1112. int ret = 0; /* return value - 0 Ident, 1 Different, >1 Error */
  1113. bool progress = false, quiet = false, strict = false;
  1114. int flags;
  1115. bool writethrough;
  1116. int64_t total_size;
  1117. int64_t offset = 0;
  1118. int64_t chunk;
  1119. int c;
  1120. uint64_t progress_base;
  1121. bool image_opts = false;
  1122. bool force_share = false;
  1123. cache = BDRV_DEFAULT_CACHE;
  1124. for (;;) {
  1125. static const struct option long_options[] = {
  1126. {"help", no_argument, 0, 'h'},
  1127. {"object", required_argument, 0, OPTION_OBJECT},
  1128. {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
  1129. {"force-share", no_argument, 0, 'U'},
  1130. {0, 0, 0, 0}
  1131. };
  1132. c = getopt_long(argc, argv, ":hf:F:T:pqsU",
  1133. long_options, NULL);
  1134. if (c == -1) {
  1135. break;
  1136. }
  1137. switch (c) {
  1138. case ':':
  1139. missing_argument(argv[optind - 1]);
  1140. break;
  1141. case '?':
  1142. unrecognized_option(argv[optind - 1]);
  1143. break;
  1144. case 'h':
  1145. help();
  1146. break;
  1147. case 'f':
  1148. fmt1 = optarg;
  1149. break;
  1150. case 'F':
  1151. fmt2 = optarg;
  1152. break;
  1153. case 'T':
  1154. cache = optarg;
  1155. break;
  1156. case 'p':
  1157. progress = true;
  1158. break;
  1159. case 'q':
  1160. quiet = true;
  1161. break;
  1162. case 's':
  1163. strict = true;
  1164. break;
  1165. case 'U':
  1166. force_share = true;
  1167. break;
  1168. case OPTION_OBJECT: {
  1169. QemuOpts *opts;
  1170. opts = qemu_opts_parse_noisily(&qemu_object_opts,
  1171. optarg, true);
  1172. if (!opts) {
  1173. ret = 2;
  1174. goto out4;
  1175. }
  1176. } break;
  1177. case OPTION_IMAGE_OPTS:
  1178. image_opts = true;
  1179. break;
  1180. }
  1181. }
  1182. /* Progress is not shown in Quiet mode */
  1183. if (quiet) {
  1184. progress = false;
  1185. }
  1186. if (optind != argc - 2) {
  1187. error_exit("Expecting two image file names");
  1188. }
  1189. filename1 = argv[optind++];
  1190. filename2 = argv[optind++];
  1191. if (qemu_opts_foreach(&qemu_object_opts,
  1192. user_creatable_add_opts_foreach,
  1193. NULL, NULL)) {
  1194. ret = 2;
  1195. goto out4;
  1196. }
  1197. /* Initialize before goto out */
  1198. qemu_progress_init(progress, 2.0);
  1199. flags = 0;
  1200. ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
  1201. if (ret < 0) {
  1202. error_report("Invalid source cache option: %s", cache);
  1203. ret = 2;
  1204. goto out3;
  1205. }
  1206. blk1 = img_open(image_opts, filename1, fmt1, flags, writethrough, quiet,
  1207. force_share);
  1208. if (!blk1) {
  1209. ret = 2;
  1210. goto out3;
  1211. }
  1212. blk2 = img_open(image_opts, filename2, fmt2, flags, writethrough, quiet,
  1213. force_share);
  1214. if (!blk2) {
  1215. ret = 2;
  1216. goto out2;
  1217. }
  1218. bs1 = blk_bs(blk1);
  1219. bs2 = blk_bs(blk2);
  1220. buf1 = blk_blockalign(blk1, IO_BUF_SIZE);
  1221. buf2 = blk_blockalign(blk2, IO_BUF_SIZE);
  1222. total_size1 = blk_getlength(blk1);
  1223. if (total_size1 < 0) {
  1224. error_report("Can't get size of %s: %s",
  1225. filename1, strerror(-total_size1));
  1226. ret = 4;
  1227. goto out;
  1228. }
  1229. total_size2 = blk_getlength(blk2);
  1230. if (total_size2 < 0) {
  1231. error_report("Can't get size of %s: %s",
  1232. filename2, strerror(-total_size2));
  1233. ret = 4;
  1234. goto out;
  1235. }
  1236. total_size = MIN(total_size1, total_size2);
  1237. progress_base = MAX(total_size1, total_size2);
  1238. qemu_progress_print(0, 100);
  1239. if (strict && total_size1 != total_size2) {
  1240. ret = 1;
  1241. qprintf(quiet, "Strict mode: Image size mismatch!\n");
  1242. goto out;
  1243. }
  1244. while (offset < total_size) {
  1245. int status1, status2;
  1246. status1 = bdrv_block_status_above(bs1, NULL, offset,
  1247. total_size1 - offset, &pnum1, NULL,
  1248. NULL);
  1249. if (status1 < 0) {
  1250. ret = 3;
  1251. error_report("Sector allocation test failed for %s", filename1);
  1252. goto out;
  1253. }
  1254. allocated1 = status1 & BDRV_BLOCK_ALLOCATED;
  1255. status2 = bdrv_block_status_above(bs2, NULL, offset,
  1256. total_size2 - offset, &pnum2, NULL,
  1257. NULL);
  1258. if (status2 < 0) {
  1259. ret = 3;
  1260. error_report("Sector allocation test failed for %s", filename2);
  1261. goto out;
  1262. }
  1263. allocated2 = status2 & BDRV_BLOCK_ALLOCATED;
  1264. assert(pnum1 && pnum2);
  1265. chunk = MIN(pnum1, pnum2);
  1266. if (strict) {
  1267. if (status1 != status2) {
  1268. ret = 1;
  1269. qprintf(quiet, "Strict mode: Offset %" PRId64
  1270. " block status mismatch!\n", offset);
  1271. goto out;
  1272. }
  1273. }
  1274. if ((status1 & BDRV_BLOCK_ZERO) && (status2 & BDRV_BLOCK_ZERO)) {
  1275. /* nothing to do */
  1276. } else if (allocated1 == allocated2) {
  1277. if (allocated1) {
  1278. int64_t pnum;
  1279. chunk = MIN(chunk, IO_BUF_SIZE);
  1280. ret = blk_pread(blk1, offset, buf1, chunk);
  1281. if (ret < 0) {
  1282. error_report("Error while reading offset %" PRId64
  1283. " of %s: %s",
  1284. offset, filename1, strerror(-ret));
  1285. ret = 4;
  1286. goto out;
  1287. }
  1288. ret = blk_pread(blk2, offset, buf2, chunk);
  1289. if (ret < 0) {
  1290. error_report("Error while reading offset %" PRId64
  1291. " of %s: %s",
  1292. offset, filename2, strerror(-ret));
  1293. ret = 4;
  1294. goto out;
  1295. }
  1296. ret = compare_buffers(buf1, buf2, chunk, &pnum);
  1297. if (ret || pnum != chunk) {
  1298. qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
  1299. offset + (ret ? 0 : pnum));
  1300. ret = 1;
  1301. goto out;
  1302. }
  1303. }
  1304. } else {
  1305. chunk = MIN(chunk, IO_BUF_SIZE);
  1306. if (allocated1) {
  1307. ret = check_empty_sectors(blk1, offset, chunk,
  1308. filename1, buf1, quiet);
  1309. } else {
  1310. ret = check_empty_sectors(blk2, offset, chunk,
  1311. filename2, buf1, quiet);
  1312. }
  1313. if (ret) {
  1314. goto out;
  1315. }
  1316. }
  1317. offset += chunk;
  1318. qemu_progress_print(((float) chunk / progress_base) * 100, 100);
  1319. }
  1320. if (total_size1 != total_size2) {
  1321. BlockBackend *blk_over;
  1322. const char *filename_over;
  1323. qprintf(quiet, "Warning: Image size mismatch!\n");
  1324. if (total_size1 > total_size2) {
  1325. blk_over = blk1;
  1326. filename_over = filename1;
  1327. } else {
  1328. blk_over = blk2;
  1329. filename_over = filename2;
  1330. }
  1331. while (offset < progress_base) {
  1332. ret = bdrv_block_status_above(blk_bs(blk_over), NULL, offset,
  1333. progress_base - offset, &chunk,
  1334. NULL, NULL);
  1335. if (ret < 0) {
  1336. ret = 3;
  1337. error_report("Sector allocation test failed for %s",
  1338. filename_over);
  1339. goto out;
  1340. }
  1341. if (ret & BDRV_BLOCK_ALLOCATED && !(ret & BDRV_BLOCK_ZERO)) {
  1342. chunk = MIN(chunk, IO_BUF_SIZE);
  1343. ret = check_empty_sectors(blk_over, offset, chunk,
  1344. filename_over, buf1, quiet);
  1345. if (ret) {
  1346. goto out;
  1347. }
  1348. }
  1349. offset += chunk;
  1350. qemu_progress_print(((float) chunk / progress_base) * 100, 100);
  1351. }
  1352. }
  1353. qprintf(quiet, "Images are identical.\n");
  1354. ret = 0;
  1355. out:
  1356. qemu_vfree(buf1);
  1357. qemu_vfree(buf2);
  1358. blk_unref(blk2);
  1359. out2:
  1360. blk_unref(blk1);
  1361. out3:
  1362. qemu_progress_end();
  1363. out4:
  1364. return ret;
  1365. }
  1366. enum ImgConvertBlockStatus {
  1367. BLK_DATA,
  1368. BLK_ZERO,
  1369. BLK_BACKING_FILE,
  1370. };
  1371. #define MAX_COROUTINES 16
  1372. typedef struct ImgConvertState {
  1373. BlockBackend **src;
  1374. int64_t *src_sectors;
  1375. int src_num;
  1376. int64_t total_sectors;
  1377. int64_t allocated_sectors;
  1378. int64_t allocated_done;
  1379. int64_t sector_num;
  1380. int64_t wr_offs;
  1381. enum ImgConvertBlockStatus status;
  1382. int64_t sector_next_status;
  1383. BlockBackend *target;
  1384. bool has_zero_init;
  1385. bool compressed;
  1386. bool target_has_backing;
  1387. bool wr_in_order;
  1388. int min_sparse;
  1389. size_t cluster_sectors;
  1390. size_t buf_sectors;
  1391. long num_coroutines;
  1392. int running_coroutines;
  1393. Coroutine *co[MAX_COROUTINES];
  1394. int64_t wait_sector_num[MAX_COROUTINES];
  1395. CoMutex lock;
  1396. int ret;
  1397. } ImgConvertState;
  1398. static void convert_select_part(ImgConvertState *s, int64_t sector_num,
  1399. int *src_cur, int64_t *src_cur_offset)
  1400. {
  1401. *src_cur = 0;
  1402. *src_cur_offset = 0;
  1403. while (sector_num - *src_cur_offset >= s->src_sectors[*src_cur]) {
  1404. *src_cur_offset += s->src_sectors[*src_cur];
  1405. (*src_cur)++;
  1406. assert(*src_cur < s->src_num);
  1407. }
  1408. }
  1409. static int convert_iteration_sectors(ImgConvertState *s, int64_t sector_num)
  1410. {
  1411. int64_t src_cur_offset;
  1412. int ret, n, src_cur;
  1413. convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
  1414. assert(s->total_sectors > sector_num);
  1415. n = MIN(s->total_sectors - sector_num, BDRV_REQUEST_MAX_SECTORS);
  1416. if (s->sector_next_status <= sector_num) {
  1417. int64_t count = n * BDRV_SECTOR_SIZE;
  1418. if (s->target_has_backing) {
  1419. ret = bdrv_block_status(blk_bs(s->src[src_cur]),
  1420. (sector_num - src_cur_offset) *
  1421. BDRV_SECTOR_SIZE,
  1422. count, &count, NULL, NULL);
  1423. } else {
  1424. ret = bdrv_block_status_above(blk_bs(s->src[src_cur]), NULL,
  1425. (sector_num - src_cur_offset) *
  1426. BDRV_SECTOR_SIZE,
  1427. count, &count, NULL, NULL);
  1428. }
  1429. if (ret < 0) {
  1430. return ret;
  1431. }
  1432. n = DIV_ROUND_UP(count, BDRV_SECTOR_SIZE);
  1433. if (ret & BDRV_BLOCK_ZERO) {
  1434. s->status = BLK_ZERO;
  1435. } else if (ret & BDRV_BLOCK_DATA) {
  1436. s->status = BLK_DATA;
  1437. } else {
  1438. s->status = s->target_has_backing ? BLK_BACKING_FILE : BLK_DATA;
  1439. }
  1440. s->sector_next_status = sector_num + n;
  1441. }
  1442. n = MIN(n, s->sector_next_status - sector_num);
  1443. if (s->status == BLK_DATA) {
  1444. n = MIN(n, s->buf_sectors);
  1445. }
  1446. /* We need to write complete clusters for compressed images, so if an
  1447. * unallocated area is shorter than that, we must consider the whole
  1448. * cluster allocated. */
  1449. if (s->compressed) {
  1450. if (n < s->cluster_sectors) {
  1451. n = MIN(s->cluster_sectors, s->total_sectors - sector_num);
  1452. s->status = BLK_DATA;
  1453. } else {
  1454. n = QEMU_ALIGN_DOWN(n, s->cluster_sectors);
  1455. }
  1456. }
  1457. return n;
  1458. }
  1459. static int coroutine_fn convert_co_read(ImgConvertState *s, int64_t sector_num,
  1460. int nb_sectors, uint8_t *buf)
  1461. {
  1462. int n, ret;
  1463. QEMUIOVector qiov;
  1464. struct iovec iov;
  1465. assert(nb_sectors <= s->buf_sectors);
  1466. while (nb_sectors > 0) {
  1467. BlockBackend *blk;
  1468. int src_cur;
  1469. int64_t bs_sectors, src_cur_offset;
  1470. /* In the case of compression with multiple source files, we can get a
  1471. * nb_sectors that spreads into the next part. So we must be able to
  1472. * read across multiple BDSes for one convert_read() call. */
  1473. convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
  1474. blk = s->src[src_cur];
  1475. bs_sectors = s->src_sectors[src_cur];
  1476. n = MIN(nb_sectors, bs_sectors - (sector_num - src_cur_offset));
  1477. iov.iov_base = buf;
  1478. iov.iov_len = n << BDRV_SECTOR_BITS;
  1479. qemu_iovec_init_external(&qiov, &iov, 1);
  1480. ret = blk_co_preadv(
  1481. blk, (sector_num - src_cur_offset) << BDRV_SECTOR_BITS,
  1482. n << BDRV_SECTOR_BITS, &qiov, 0);
  1483. if (ret < 0) {
  1484. return ret;
  1485. }
  1486. sector_num += n;
  1487. nb_sectors -= n;
  1488. buf += n * BDRV_SECTOR_SIZE;
  1489. }
  1490. return 0;
  1491. }
  1492. static int coroutine_fn convert_co_write(ImgConvertState *s, int64_t sector_num,
  1493. int nb_sectors, uint8_t *buf,
  1494. enum ImgConvertBlockStatus status)
  1495. {
  1496. int ret;
  1497. QEMUIOVector qiov;
  1498. struct iovec iov;
  1499. while (nb_sectors > 0) {
  1500. int n = nb_sectors;
  1501. BdrvRequestFlags flags = s->compressed ? BDRV_REQ_WRITE_COMPRESSED : 0;
  1502. switch (status) {
  1503. case BLK_BACKING_FILE:
  1504. /* If we have a backing file, leave clusters unallocated that are
  1505. * unallocated in the source image, so that the backing file is
  1506. * visible at the respective offset. */
  1507. assert(s->target_has_backing);
  1508. break;
  1509. case BLK_DATA:
  1510. /* If we're told to keep the target fully allocated (-S 0) or there
  1511. * is real non-zero data, we must write it. Otherwise we can treat
  1512. * it as zero sectors.
  1513. * Compressed clusters need to be written as a whole, so in that
  1514. * case we can only save the write if the buffer is completely
  1515. * zeroed. */
  1516. if (!s->min_sparse ||
  1517. (!s->compressed &&
  1518. is_allocated_sectors_min(buf, n, &n, s->min_sparse)) ||
  1519. (s->compressed &&
  1520. !buffer_is_zero(buf, n * BDRV_SECTOR_SIZE)))
  1521. {
  1522. iov.iov_base = buf;
  1523. iov.iov_len = n << BDRV_SECTOR_BITS;
  1524. qemu_iovec_init_external(&qiov, &iov, 1);
  1525. ret = blk_co_pwritev(s->target, sector_num << BDRV_SECTOR_BITS,
  1526. n << BDRV_SECTOR_BITS, &qiov, flags);
  1527. if (ret < 0) {
  1528. return ret;
  1529. }
  1530. break;
  1531. }
  1532. /* fall-through */
  1533. case BLK_ZERO:
  1534. if (s->has_zero_init) {
  1535. assert(!s->target_has_backing);
  1536. break;
  1537. }
  1538. ret = blk_co_pwrite_zeroes(s->target,
  1539. sector_num << BDRV_SECTOR_BITS,
  1540. n << BDRV_SECTOR_BITS, 0);
  1541. if (ret < 0) {
  1542. return ret;
  1543. }
  1544. break;
  1545. }
  1546. sector_num += n;
  1547. nb_sectors -= n;
  1548. buf += n * BDRV_SECTOR_SIZE;
  1549. }
  1550. return 0;
  1551. }
  1552. static void coroutine_fn convert_co_do_copy(void *opaque)
  1553. {
  1554. ImgConvertState *s = opaque;
  1555. uint8_t *buf = NULL;
  1556. int ret, i;
  1557. int index = -1;
  1558. for (i = 0; i < s->num_coroutines; i++) {
  1559. if (s->co[i] == qemu_coroutine_self()) {
  1560. index = i;
  1561. break;
  1562. }
  1563. }
  1564. assert(index >= 0);
  1565. s->running_coroutines++;
  1566. buf = blk_blockalign(s->target, s->buf_sectors * BDRV_SECTOR_SIZE);
  1567. while (1) {
  1568. int n;
  1569. int64_t sector_num;
  1570. enum ImgConvertBlockStatus status;
  1571. qemu_co_mutex_lock(&s->lock);
  1572. if (s->ret != -EINPROGRESS || s->sector_num >= s->total_sectors) {
  1573. qemu_co_mutex_unlock(&s->lock);
  1574. break;
  1575. }
  1576. n = convert_iteration_sectors(s, s->sector_num);
  1577. if (n < 0) {
  1578. qemu_co_mutex_unlock(&s->lock);
  1579. s->ret = n;
  1580. break;
  1581. }
  1582. /* save current sector and allocation status to local variables */
  1583. sector_num = s->sector_num;
  1584. status = s->status;
  1585. if (!s->min_sparse && s->status == BLK_ZERO) {
  1586. n = MIN(n, s->buf_sectors);
  1587. }
  1588. /* increment global sector counter so that other coroutines can
  1589. * already continue reading beyond this request */
  1590. s->sector_num += n;
  1591. qemu_co_mutex_unlock(&s->lock);
  1592. if (status == BLK_DATA || (!s->min_sparse && status == BLK_ZERO)) {
  1593. s->allocated_done += n;
  1594. qemu_progress_print(100.0 * s->allocated_done /
  1595. s->allocated_sectors, 0);
  1596. }
  1597. if (status == BLK_DATA) {
  1598. ret = convert_co_read(s, sector_num, n, buf);
  1599. if (ret < 0) {
  1600. error_report("error while reading sector %" PRId64
  1601. ": %s", sector_num, strerror(-ret));
  1602. s->ret = ret;
  1603. }
  1604. } else if (!s->min_sparse && status == BLK_ZERO) {
  1605. status = BLK_DATA;
  1606. memset(buf, 0x00, n * BDRV_SECTOR_SIZE);
  1607. }
  1608. if (s->wr_in_order) {
  1609. /* keep writes in order */
  1610. while (s->wr_offs != sector_num && s->ret == -EINPROGRESS) {
  1611. s->wait_sector_num[index] = sector_num;
  1612. qemu_coroutine_yield();
  1613. }
  1614. s->wait_sector_num[index] = -1;
  1615. }
  1616. if (s->ret == -EINPROGRESS) {
  1617. ret = convert_co_write(s, sector_num, n, buf, status);
  1618. if (ret < 0) {
  1619. error_report("error while writing sector %" PRId64
  1620. ": %s", sector_num, strerror(-ret));
  1621. s->ret = ret;
  1622. }
  1623. }
  1624. if (s->wr_in_order) {
  1625. /* reenter the coroutine that might have waited
  1626. * for this write to complete */
  1627. s->wr_offs = sector_num + n;
  1628. for (i = 0; i < s->num_coroutines; i++) {
  1629. if (s->co[i] && s->wait_sector_num[i] == s->wr_offs) {
  1630. /*
  1631. * A -> B -> A cannot occur because A has
  1632. * s->wait_sector_num[i] == -1 during A -> B. Therefore
  1633. * B will never enter A during this time window.
  1634. */
  1635. qemu_coroutine_enter(s->co[i]);
  1636. break;
  1637. }
  1638. }
  1639. }
  1640. }
  1641. qemu_vfree(buf);
  1642. s->co[index] = NULL;
  1643. s->running_coroutines--;
  1644. if (!s->running_coroutines && s->ret == -EINPROGRESS) {
  1645. /* the convert job finished successfully */
  1646. s->ret = 0;
  1647. }
  1648. }
  1649. static int convert_do_copy(ImgConvertState *s)
  1650. {
  1651. int ret, i, n;
  1652. int64_t sector_num = 0;
  1653. /* Check whether we have zero initialisation or can get it efficiently */
  1654. s->has_zero_init = s->min_sparse && !s->target_has_backing
  1655. ? bdrv_has_zero_init(blk_bs(s->target))
  1656. : false;
  1657. if (!s->has_zero_init && !s->target_has_backing &&
  1658. bdrv_can_write_zeroes_with_unmap(blk_bs(s->target)))
  1659. {
  1660. ret = blk_make_zero(s->target, BDRV_REQ_MAY_UNMAP);
  1661. if (ret == 0) {
  1662. s->has_zero_init = true;
  1663. }
  1664. }
  1665. /* Allocate buffer for copied data. For compressed images, only one cluster
  1666. * can be copied at a time. */
  1667. if (s->compressed) {
  1668. if (s->cluster_sectors <= 0 || s->cluster_sectors > s->buf_sectors) {
  1669. error_report("invalid cluster size");
  1670. return -EINVAL;
  1671. }
  1672. s->buf_sectors = s->cluster_sectors;
  1673. }
  1674. while (sector_num < s->total_sectors) {
  1675. n = convert_iteration_sectors(s, sector_num);
  1676. if (n < 0) {
  1677. return n;
  1678. }
  1679. if (s->status == BLK_DATA || (!s->min_sparse && s->status == BLK_ZERO))
  1680. {
  1681. s->allocated_sectors += n;
  1682. }
  1683. sector_num += n;
  1684. }
  1685. /* Do the copy */
  1686. s->sector_next_status = 0;
  1687. s->ret = -EINPROGRESS;
  1688. qemu_co_mutex_init(&s->lock);
  1689. for (i = 0; i < s->num_coroutines; i++) {
  1690. s->co[i] = qemu_coroutine_create(convert_co_do_copy, s);
  1691. s->wait_sector_num[i] = -1;
  1692. qemu_coroutine_enter(s->co[i]);
  1693. }
  1694. while (s->running_coroutines) {
  1695. main_loop_wait(false);
  1696. }
  1697. if (s->compressed && !s->ret) {
  1698. /* signal EOF to align */
  1699. ret = blk_pwrite_compressed(s->target, 0, NULL, 0);
  1700. if (ret < 0) {
  1701. return ret;
  1702. }
  1703. }
  1704. return s->ret;
  1705. }
  1706. #define MAX_BUF_SECTORS 32768
  1707. static int img_convert(int argc, char **argv)
  1708. {
  1709. int c, bs_i, flags, src_flags = 0;
  1710. const char *fmt = NULL, *out_fmt = NULL, *cache = "unsafe",
  1711. *src_cache = BDRV_DEFAULT_CACHE, *out_baseimg = NULL,
  1712. *out_filename, *out_baseimg_param, *snapshot_name = NULL;
  1713. BlockDriver *drv = NULL, *proto_drv = NULL;
  1714. BlockDriverInfo bdi;
  1715. BlockDriverState *out_bs;
  1716. QemuOpts *opts = NULL, *sn_opts = NULL;
  1717. QemuOptsList *create_opts = NULL;
  1718. char *options = NULL;
  1719. Error *local_err = NULL;
  1720. bool writethrough, src_writethrough, quiet = false, image_opts = false,
  1721. skip_create = false, progress = false, tgt_image_opts = false;
  1722. int64_t ret = -EINVAL;
  1723. bool force_share = false;
  1724. ImgConvertState s = (ImgConvertState) {
  1725. /* Need at least 4k of zeros for sparse detection */
  1726. .min_sparse = 8,
  1727. .buf_sectors = IO_BUF_SIZE / BDRV_SECTOR_SIZE,
  1728. .wr_in_order = true,
  1729. .num_coroutines = 8,
  1730. };
  1731. for(;;) {
  1732. static const struct option long_options[] = {
  1733. {"help", no_argument, 0, 'h'},
  1734. {"object", required_argument, 0, OPTION_OBJECT},
  1735. {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
  1736. {"force-share", no_argument, 0, 'U'},
  1737. {"target-image-opts", no_argument, 0, OPTION_TARGET_IMAGE_OPTS},
  1738. {0, 0, 0, 0}
  1739. };
  1740. c = getopt_long(argc, argv, ":hf:O:B:co:s:l:S:pt:T:qnm:WU",
  1741. long_options, NULL);
  1742. if (c == -1) {
  1743. break;
  1744. }
  1745. switch(c) {
  1746. case ':':
  1747. missing_argument(argv[optind - 1]);
  1748. break;
  1749. case '?':
  1750. unrecognized_option(argv[optind - 1]);
  1751. break;
  1752. case 'h':
  1753. help();
  1754. break;
  1755. case 'f':
  1756. fmt = optarg;
  1757. break;
  1758. case 'O':
  1759. out_fmt = optarg;
  1760. break;
  1761. case 'B':
  1762. out_baseimg = optarg;
  1763. break;
  1764. case 'c':
  1765. s.compressed = true;
  1766. break;
  1767. case 'o':
  1768. if (!is_valid_option_list(optarg)) {
  1769. error_report("Invalid option list: %s", optarg);
  1770. goto fail_getopt;
  1771. }
  1772. if (!options) {
  1773. options = g_strdup(optarg);
  1774. } else {
  1775. char *old_options = options;
  1776. options = g_strdup_printf("%s,%s", options, optarg);
  1777. g_free(old_options);
  1778. }
  1779. break;
  1780. case 's':
  1781. snapshot_name = optarg;
  1782. break;
  1783. case 'l':
  1784. if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
  1785. sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
  1786. optarg, false);
  1787. if (!sn_opts) {
  1788. error_report("Failed in parsing snapshot param '%s'",
  1789. optarg);
  1790. goto fail_getopt;
  1791. }
  1792. } else {
  1793. snapshot_name = optarg;
  1794. }
  1795. break;
  1796. case 'S':
  1797. {
  1798. int64_t sval;
  1799. sval = cvtnum(optarg);
  1800. if (sval < 0 || sval & (BDRV_SECTOR_SIZE - 1) ||
  1801. sval / BDRV_SECTOR_SIZE > MAX_BUF_SECTORS) {
  1802. error_report("Invalid buffer size for sparse output specified. "
  1803. "Valid sizes are multiples of %llu up to %llu. Select "
  1804. "0 to disable sparse detection (fully allocates output).",
  1805. BDRV_SECTOR_SIZE, MAX_BUF_SECTORS * BDRV_SECTOR_SIZE);
  1806. goto fail_getopt;
  1807. }
  1808. s.min_sparse = sval / BDRV_SECTOR_SIZE;
  1809. break;
  1810. }
  1811. case 'p':
  1812. progress = true;
  1813. break;
  1814. case 't':
  1815. cache = optarg;
  1816. break;
  1817. case 'T':
  1818. src_cache = optarg;
  1819. break;
  1820. case 'q':
  1821. quiet = true;
  1822. break;
  1823. case 'n':
  1824. skip_create = true;
  1825. break;
  1826. case 'm':
  1827. if (qemu_strtol(optarg, NULL, 0, &s.num_coroutines) ||
  1828. s.num_coroutines < 1 || s.num_coroutines > MAX_COROUTINES) {
  1829. error_report("Invalid number of coroutines. Allowed number of"
  1830. " coroutines is between 1 and %d", MAX_COROUTINES);
  1831. goto fail_getopt;
  1832. }
  1833. break;
  1834. case 'W':
  1835. s.wr_in_order = false;
  1836. break;
  1837. case 'U':
  1838. force_share = true;
  1839. break;
  1840. case OPTION_OBJECT: {
  1841. QemuOpts *object_opts;
  1842. object_opts = qemu_opts_parse_noisily(&qemu_object_opts,
  1843. optarg, true);
  1844. if (!object_opts) {
  1845. goto fail_getopt;
  1846. }
  1847. break;
  1848. }
  1849. case OPTION_IMAGE_OPTS:
  1850. image_opts = true;
  1851. break;
  1852. case OPTION_TARGET_IMAGE_OPTS:
  1853. tgt_image_opts = true;
  1854. break;
  1855. }
  1856. }
  1857. if (!out_fmt && !tgt_image_opts) {
  1858. out_fmt = "raw";
  1859. }
  1860. if (qemu_opts_foreach(&qemu_object_opts,
  1861. user_creatable_add_opts_foreach,
  1862. NULL, NULL)) {
  1863. goto fail_getopt;
  1864. }
  1865. if (!s.wr_in_order && s.compressed) {
  1866. error_report("Out of order write and compress are mutually exclusive");
  1867. goto fail_getopt;
  1868. }
  1869. if (tgt_image_opts && !skip_create) {
  1870. error_report("--target-image-opts requires use of -n flag");
  1871. goto fail_getopt;
  1872. }
  1873. s.src_num = argc - optind - 1;
  1874. out_filename = s.src_num >= 1 ? argv[argc - 1] : NULL;
  1875. if (options && has_help_option(options)) {
  1876. if (out_fmt) {
  1877. ret = print_block_option_help(out_filename, out_fmt);
  1878. goto fail_getopt;
  1879. } else {
  1880. error_report("Option help requires a format be specified");
  1881. goto fail_getopt;
  1882. }
  1883. }
  1884. if (s.src_num < 1) {
  1885. error_report("Must specify image file name");
  1886. goto fail_getopt;
  1887. }
  1888. /* ret is still -EINVAL until here */
  1889. ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
  1890. if (ret < 0) {
  1891. error_report("Invalid source cache option: %s", src_cache);
  1892. goto fail_getopt;
  1893. }
  1894. /* Initialize before goto out */
  1895. if (quiet) {
  1896. progress = false;
  1897. }
  1898. qemu_progress_init(progress, 1.0);
  1899. qemu_progress_print(0, 100);
  1900. s.src = g_new0(BlockBackend *, s.src_num);
  1901. s.src_sectors = g_new(int64_t, s.src_num);
  1902. for (bs_i = 0; bs_i < s.src_num; bs_i++) {
  1903. s.src[bs_i] = img_open(image_opts, argv[optind + bs_i],
  1904. fmt, src_flags, src_writethrough, quiet,
  1905. force_share);
  1906. if (!s.src[bs_i]) {
  1907. ret = -1;
  1908. goto out;
  1909. }
  1910. s.src_sectors[bs_i] = blk_nb_sectors(s.src[bs_i]);
  1911. if (s.src_sectors[bs_i] < 0) {
  1912. error_report("Could not get size of %s: %s",
  1913. argv[optind + bs_i], strerror(-s.src_sectors[bs_i]));
  1914. ret = -1;
  1915. goto out;
  1916. }
  1917. s.total_sectors += s.src_sectors[bs_i];
  1918. }
  1919. if (sn_opts) {
  1920. bdrv_snapshot_load_tmp(blk_bs(s.src[0]),
  1921. qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
  1922. qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
  1923. &local_err);
  1924. } else if (snapshot_name != NULL) {
  1925. if (s.src_num > 1) {
  1926. error_report("No support for concatenating multiple snapshot");
  1927. ret = -1;
  1928. goto out;
  1929. }
  1930. bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(s.src[0]), snapshot_name,
  1931. &local_err);
  1932. }
  1933. if (local_err) {
  1934. error_reportf_err(local_err, "Failed to load snapshot: ");
  1935. ret = -1;
  1936. goto out;
  1937. }
  1938. if (!skip_create) {
  1939. /* Find driver and parse its options */
  1940. drv = bdrv_find_format(out_fmt);
  1941. if (!drv) {
  1942. error_report("Unknown file format '%s'", out_fmt);
  1943. ret = -1;
  1944. goto out;
  1945. }
  1946. proto_drv = bdrv_find_protocol(out_filename, true, &local_err);
  1947. if (!proto_drv) {
  1948. error_report_err(local_err);
  1949. ret = -1;
  1950. goto out;
  1951. }
  1952. if (!drv->create_opts) {
  1953. error_report("Format driver '%s' does not support image creation",
  1954. drv->format_name);
  1955. ret = -1;
  1956. goto out;
  1957. }
  1958. if (!proto_drv->create_opts) {
  1959. error_report("Protocol driver '%s' does not support image creation",
  1960. proto_drv->format_name);
  1961. ret = -1;
  1962. goto out;
  1963. }
  1964. create_opts = qemu_opts_append(create_opts, drv->create_opts);
  1965. create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
  1966. opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
  1967. if (options) {
  1968. qemu_opts_do_parse(opts, options, NULL, &local_err);
  1969. if (local_err) {
  1970. error_report_err(local_err);
  1971. ret = -1;
  1972. goto out;
  1973. }
  1974. }
  1975. qemu_opt_set_number(opts, BLOCK_OPT_SIZE, s.total_sectors * 512,
  1976. &error_abort);
  1977. ret = add_old_style_options(out_fmt, opts, out_baseimg, NULL);
  1978. if (ret < 0) {
  1979. goto out;
  1980. }
  1981. }
  1982. /* Get backing file name if -o backing_file was used */
  1983. out_baseimg_param = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
  1984. if (out_baseimg_param) {
  1985. out_baseimg = out_baseimg_param;
  1986. }
  1987. s.target_has_backing = (bool) out_baseimg;
  1988. if (s.src_num > 1 && out_baseimg) {
  1989. error_report("Having a backing file for the target makes no sense when "
  1990. "concatenating multiple input images");
  1991. ret = -1;
  1992. goto out;
  1993. }
  1994. /* Check if compression is supported */
  1995. if (s.compressed) {
  1996. bool encryption =
  1997. qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT, false);
  1998. const char *encryptfmt =
  1999. qemu_opt_get(opts, BLOCK_OPT_ENCRYPT_FORMAT);
  2000. const char *preallocation =
  2001. qemu_opt_get(opts, BLOCK_OPT_PREALLOC);
  2002. if (drv && !drv->bdrv_co_pwritev_compressed) {
  2003. error_report("Compression not supported for this file format");
  2004. ret = -1;
  2005. goto out;
  2006. }
  2007. if (encryption || encryptfmt) {
  2008. error_report("Compression and encryption not supported at "
  2009. "the same time");
  2010. ret = -1;
  2011. goto out;
  2012. }
  2013. if (preallocation
  2014. && strcmp(preallocation, "off"))
  2015. {
  2016. error_report("Compression and preallocation not supported at "
  2017. "the same time");
  2018. ret = -1;
  2019. goto out;
  2020. }
  2021. }
  2022. if (!skip_create) {
  2023. /* Create the new image */
  2024. ret = bdrv_create(drv, out_filename, opts, &local_err);
  2025. if (ret < 0) {
  2026. error_reportf_err(local_err, "%s: error while converting %s: ",
  2027. out_filename, out_fmt);
  2028. goto out;
  2029. }
  2030. }
  2031. flags = s.min_sparse ? (BDRV_O_RDWR | BDRV_O_UNMAP) : BDRV_O_RDWR;
  2032. ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
  2033. if (ret < 0) {
  2034. error_report("Invalid cache option: %s", cache);
  2035. goto out;
  2036. }
  2037. if (skip_create) {
  2038. s.target = img_open(tgt_image_opts, out_filename, out_fmt,
  2039. flags, writethrough, quiet, false);
  2040. } else {
  2041. /* TODO ultimately we should allow --target-image-opts
  2042. * to be used even when -n is not given.
  2043. * That has to wait for bdrv_create to be improved
  2044. * to allow filenames in option syntax
  2045. */
  2046. s.target = img_open_new_file(out_filename, opts, out_fmt,
  2047. flags, writethrough, quiet, false);
  2048. }
  2049. if (!s.target) {
  2050. ret = -1;
  2051. goto out;
  2052. }
  2053. out_bs = blk_bs(s.target);
  2054. if (s.compressed && !out_bs->drv->bdrv_co_pwritev_compressed) {
  2055. error_report("Compression not supported for this file format");
  2056. ret = -1;
  2057. goto out;
  2058. }
  2059. /* increase bufsectors from the default 4096 (2M) if opt_transfer
  2060. * or discard_alignment of the out_bs is greater. Limit to
  2061. * MAX_BUF_SECTORS as maximum which is currently 32768 (16MB). */
  2062. s.buf_sectors = MIN(MAX_BUF_SECTORS,
  2063. MAX(s.buf_sectors,
  2064. MAX(out_bs->bl.opt_transfer >> BDRV_SECTOR_BITS,
  2065. out_bs->bl.pdiscard_alignment >>
  2066. BDRV_SECTOR_BITS)));
  2067. if (skip_create) {
  2068. int64_t output_sectors = blk_nb_sectors(s.target);
  2069. if (output_sectors < 0) {
  2070. error_report("unable to get output image length: %s",
  2071. strerror(-output_sectors));
  2072. ret = -1;
  2073. goto out;
  2074. } else if (output_sectors < s.total_sectors) {
  2075. error_report("output file is smaller than input file");
  2076. ret = -1;
  2077. goto out;
  2078. }
  2079. }
  2080. ret = bdrv_get_info(out_bs, &bdi);
  2081. if (ret < 0) {
  2082. if (s.compressed) {
  2083. error_report("could not get block driver info");
  2084. goto out;
  2085. }
  2086. } else {
  2087. s.compressed = s.compressed || bdi.needs_compressed_writes;
  2088. s.cluster_sectors = bdi.cluster_size / BDRV_SECTOR_SIZE;
  2089. }
  2090. ret = convert_do_copy(&s);
  2091. out:
  2092. if (!ret) {
  2093. qemu_progress_print(100, 0);
  2094. }
  2095. qemu_progress_end();
  2096. qemu_opts_del(opts);
  2097. qemu_opts_free(create_opts);
  2098. qemu_opts_del(sn_opts);
  2099. blk_unref(s.target);
  2100. if (s.src) {
  2101. for (bs_i = 0; bs_i < s.src_num; bs_i++) {
  2102. blk_unref(s.src[bs_i]);
  2103. }
  2104. g_free(s.src);
  2105. }
  2106. g_free(s.src_sectors);
  2107. fail_getopt:
  2108. g_free(options);
  2109. return !!ret;
  2110. }
  2111. static void dump_snapshots(BlockDriverState *bs)
  2112. {
  2113. QEMUSnapshotInfo *sn_tab, *sn;
  2114. int nb_sns, i;
  2115. nb_sns = bdrv_snapshot_list(bs, &sn_tab);
  2116. if (nb_sns <= 0)
  2117. return;
  2118. printf("Snapshot list:\n");
  2119. bdrv_snapshot_dump(fprintf, stdout, NULL);
  2120. printf("\n");
  2121. for(i = 0; i < nb_sns; i++) {
  2122. sn = &sn_tab[i];
  2123. bdrv_snapshot_dump(fprintf, stdout, sn);
  2124. printf("\n");
  2125. }
  2126. g_free(sn_tab);
  2127. }
  2128. static void dump_json_image_info_list(ImageInfoList *list)
  2129. {
  2130. QString *str;
  2131. QObject *obj;
  2132. Visitor *v = qobject_output_visitor_new(&obj);
  2133. visit_type_ImageInfoList(v, NULL, &list, &error_abort);
  2134. visit_complete(v, &obj);
  2135. str = qobject_to_json_pretty(obj);
  2136. assert(str != NULL);
  2137. printf("%s\n", qstring_get_str(str));
  2138. qobject_decref(obj);
  2139. visit_free(v);
  2140. QDECREF(str);
  2141. }
  2142. static void dump_json_image_info(ImageInfo *info)
  2143. {
  2144. QString *str;
  2145. QObject *obj;
  2146. Visitor *v = qobject_output_visitor_new(&obj);
  2147. visit_type_ImageInfo(v, NULL, &info, &error_abort);
  2148. visit_complete(v, &obj);
  2149. str = qobject_to_json_pretty(obj);
  2150. assert(str != NULL);
  2151. printf("%s\n", qstring_get_str(str));
  2152. qobject_decref(obj);
  2153. visit_free(v);
  2154. QDECREF(str);
  2155. }
  2156. static void dump_human_image_info_list(ImageInfoList *list)
  2157. {
  2158. ImageInfoList *elem;
  2159. bool delim = false;
  2160. for (elem = list; elem; elem = elem->next) {
  2161. if (delim) {
  2162. printf("\n");
  2163. }
  2164. delim = true;
  2165. bdrv_image_info_dump(fprintf, stdout, elem->value);
  2166. }
  2167. }
  2168. static gboolean str_equal_func(gconstpointer a, gconstpointer b)
  2169. {
  2170. return strcmp(a, b) == 0;
  2171. }
  2172. /**
  2173. * Open an image file chain and return an ImageInfoList
  2174. *
  2175. * @filename: topmost image filename
  2176. * @fmt: topmost image format (may be NULL to autodetect)
  2177. * @chain: true - enumerate entire backing file chain
  2178. * false - only topmost image file
  2179. *
  2180. * Returns a list of ImageInfo objects or NULL if there was an error opening an
  2181. * image file. If there was an error a message will have been printed to
  2182. * stderr.
  2183. */
  2184. static ImageInfoList *collect_image_info_list(bool image_opts,
  2185. const char *filename,
  2186. const char *fmt,
  2187. bool chain, bool force_share)
  2188. {
  2189. ImageInfoList *head = NULL;
  2190. ImageInfoList **last = &head;
  2191. GHashTable *filenames;
  2192. Error *err = NULL;
  2193. filenames = g_hash_table_new_full(g_str_hash, str_equal_func, NULL, NULL);
  2194. while (filename) {
  2195. BlockBackend *blk;
  2196. BlockDriverState *bs;
  2197. ImageInfo *info;
  2198. ImageInfoList *elem;
  2199. if (g_hash_table_lookup_extended(filenames, filename, NULL, NULL)) {
  2200. error_report("Backing file '%s' creates an infinite loop.",
  2201. filename);
  2202. goto err;
  2203. }
  2204. g_hash_table_insert(filenames, (gpointer)filename, NULL);
  2205. blk = img_open(image_opts, filename, fmt,
  2206. BDRV_O_NO_BACKING | BDRV_O_NO_IO, false, false,
  2207. force_share);
  2208. if (!blk) {
  2209. goto err;
  2210. }
  2211. bs = blk_bs(blk);
  2212. bdrv_query_image_info(bs, &info, &err);
  2213. if (err) {
  2214. error_report_err(err);
  2215. blk_unref(blk);
  2216. goto err;
  2217. }
  2218. elem = g_new0(ImageInfoList, 1);
  2219. elem->value = info;
  2220. *last = elem;
  2221. last = &elem->next;
  2222. blk_unref(blk);
  2223. filename = fmt = NULL;
  2224. if (chain) {
  2225. if (info->has_full_backing_filename) {
  2226. filename = info->full_backing_filename;
  2227. } else if (info->has_backing_filename) {
  2228. error_report("Could not determine absolute backing filename,"
  2229. " but backing filename '%s' present",
  2230. info->backing_filename);
  2231. goto err;
  2232. }
  2233. if (info->has_backing_filename_format) {
  2234. fmt = info->backing_filename_format;
  2235. }
  2236. }
  2237. }
  2238. g_hash_table_destroy(filenames);
  2239. return head;
  2240. err:
  2241. qapi_free_ImageInfoList(head);
  2242. g_hash_table_destroy(filenames);
  2243. return NULL;
  2244. }
  2245. static int img_info(int argc, char **argv)
  2246. {
  2247. int c;
  2248. OutputFormat output_format = OFORMAT_HUMAN;
  2249. bool chain = false;
  2250. const char *filename, *fmt, *output;
  2251. ImageInfoList *list;
  2252. bool image_opts = false;
  2253. bool force_share = false;
  2254. fmt = NULL;
  2255. output = NULL;
  2256. for(;;) {
  2257. int option_index = 0;
  2258. static const struct option long_options[] = {
  2259. {"help", no_argument, 0, 'h'},
  2260. {"format", required_argument, 0, 'f'},
  2261. {"output", required_argument, 0, OPTION_OUTPUT},
  2262. {"backing-chain", no_argument, 0, OPTION_BACKING_CHAIN},
  2263. {"object", required_argument, 0, OPTION_OBJECT},
  2264. {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
  2265. {"force-share", no_argument, 0, 'U'},
  2266. {0, 0, 0, 0}
  2267. };
  2268. c = getopt_long(argc, argv, ":f:hU",
  2269. long_options, &option_index);
  2270. if (c == -1) {
  2271. break;
  2272. }
  2273. switch(c) {
  2274. case ':':
  2275. missing_argument(argv[optind - 1]);
  2276. break;
  2277. case '?':
  2278. unrecognized_option(argv[optind - 1]);
  2279. break;
  2280. case 'h':
  2281. help();
  2282. break;
  2283. case 'f':
  2284. fmt = optarg;
  2285. break;
  2286. case 'U':
  2287. force_share = true;
  2288. break;
  2289. case OPTION_OUTPUT:
  2290. output = optarg;
  2291. break;
  2292. case OPTION_BACKING_CHAIN:
  2293. chain = true;
  2294. break;
  2295. case OPTION_OBJECT: {
  2296. QemuOpts *opts;
  2297. opts = qemu_opts_parse_noisily(&qemu_object_opts,
  2298. optarg, true);
  2299. if (!opts) {
  2300. return 1;
  2301. }
  2302. } break;
  2303. case OPTION_IMAGE_OPTS:
  2304. image_opts = true;
  2305. break;
  2306. }
  2307. }
  2308. if (optind != argc - 1) {
  2309. error_exit("Expecting one image file name");
  2310. }
  2311. filename = argv[optind++];
  2312. if (output && !strcmp(output, "json")) {
  2313. output_format = OFORMAT_JSON;
  2314. } else if (output && !strcmp(output, "human")) {
  2315. output_format = OFORMAT_HUMAN;
  2316. } else if (output) {
  2317. error_report("--output must be used with human or json as argument.");
  2318. return 1;
  2319. }
  2320. if (qemu_opts_foreach(&qemu_object_opts,
  2321. user_creatable_add_opts_foreach,
  2322. NULL, NULL)) {
  2323. return 1;
  2324. }
  2325. list = collect_image_info_list(image_opts, filename, fmt, chain,
  2326. force_share);
  2327. if (!list) {
  2328. return 1;
  2329. }
  2330. switch (output_format) {
  2331. case OFORMAT_HUMAN:
  2332. dump_human_image_info_list(list);
  2333. break;
  2334. case OFORMAT_JSON:
  2335. if (chain) {
  2336. dump_json_image_info_list(list);
  2337. } else {
  2338. dump_json_image_info(list->value);
  2339. }
  2340. break;
  2341. }
  2342. qapi_free_ImageInfoList(list);
  2343. return 0;
  2344. }
  2345. static void dump_map_entry(OutputFormat output_format, MapEntry *e,
  2346. MapEntry *next)
  2347. {
  2348. switch (output_format) {
  2349. case OFORMAT_HUMAN:
  2350. if (e->data && !e->has_offset) {
  2351. error_report("File contains external, encrypted or compressed clusters.");
  2352. exit(1);
  2353. }
  2354. if (e->data && !e->zero) {
  2355. printf("%#-16"PRIx64"%#-16"PRIx64"%#-16"PRIx64"%s\n",
  2356. e->start, e->length,
  2357. e->has_offset ? e->offset : 0,
  2358. e->has_filename ? e->filename : "");
  2359. }
  2360. /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
  2361. * Modify the flags here to allow more coalescing.
  2362. */
  2363. if (next && (!next->data || next->zero)) {
  2364. next->data = false;
  2365. next->zero = true;
  2366. }
  2367. break;
  2368. case OFORMAT_JSON:
  2369. printf("%s{ \"start\": %"PRId64", \"length\": %"PRId64","
  2370. " \"depth\": %"PRId64", \"zero\": %s, \"data\": %s",
  2371. (e->start == 0 ? "[" : ",\n"),
  2372. e->start, e->length, e->depth,
  2373. e->zero ? "true" : "false",
  2374. e->data ? "true" : "false");
  2375. if (e->has_offset) {
  2376. printf(", \"offset\": %"PRId64"", e->offset);
  2377. }
  2378. putchar('}');
  2379. if (!next) {
  2380. printf("]\n");
  2381. }
  2382. break;
  2383. }
  2384. }
  2385. static int get_block_status(BlockDriverState *bs, int64_t offset,
  2386. int64_t bytes, MapEntry *e)
  2387. {
  2388. int ret;
  2389. int depth;
  2390. BlockDriverState *file;
  2391. bool has_offset;
  2392. int64_t map;
  2393. /* As an optimization, we could cache the current range of unallocated
  2394. * clusters in each file of the chain, and avoid querying the same
  2395. * range repeatedly.
  2396. */
  2397. depth = 0;
  2398. for (;;) {
  2399. ret = bdrv_block_status(bs, offset, bytes, &bytes, &map, &file);
  2400. if (ret < 0) {
  2401. return ret;
  2402. }
  2403. assert(bytes);
  2404. if (ret & (BDRV_BLOCK_ZERO|BDRV_BLOCK_DATA)) {
  2405. break;
  2406. }
  2407. bs = backing_bs(bs);
  2408. if (bs == NULL) {
  2409. ret = 0;
  2410. break;
  2411. }
  2412. depth++;
  2413. }
  2414. has_offset = !!(ret & BDRV_BLOCK_OFFSET_VALID);
  2415. *e = (MapEntry) {
  2416. .start = offset,
  2417. .length = bytes,
  2418. .data = !!(ret & BDRV_BLOCK_DATA),
  2419. .zero = !!(ret & BDRV_BLOCK_ZERO),
  2420. .offset = map,
  2421. .has_offset = has_offset,
  2422. .depth = depth,
  2423. .has_filename = file && has_offset,
  2424. .filename = file && has_offset ? file->filename : NULL,
  2425. };
  2426. return 0;
  2427. }
  2428. static inline bool entry_mergeable(const MapEntry *curr, const MapEntry *next)
  2429. {
  2430. if (curr->length == 0) {
  2431. return false;
  2432. }
  2433. if (curr->zero != next->zero ||
  2434. curr->data != next->data ||
  2435. curr->depth != next->depth ||
  2436. curr->has_filename != next->has_filename ||
  2437. curr->has_offset != next->has_offset) {
  2438. return false;
  2439. }
  2440. if (curr->has_filename && strcmp(curr->filename, next->filename)) {
  2441. return false;
  2442. }
  2443. if (curr->has_offset && curr->offset + curr->length != next->offset) {
  2444. return false;
  2445. }
  2446. return true;
  2447. }
  2448. static int img_map(int argc, char **argv)
  2449. {
  2450. int c;
  2451. OutputFormat output_format = OFORMAT_HUMAN;
  2452. BlockBackend *blk;
  2453. BlockDriverState *bs;
  2454. const char *filename, *fmt, *output;
  2455. int64_t length;
  2456. MapEntry curr = { .length = 0 }, next;
  2457. int ret = 0;
  2458. bool image_opts = false;
  2459. bool force_share = false;
  2460. fmt = NULL;
  2461. output = NULL;
  2462. for (;;) {
  2463. int option_index = 0;
  2464. static const struct option long_options[] = {
  2465. {"help", no_argument, 0, 'h'},
  2466. {"format", required_argument, 0, 'f'},
  2467. {"output", required_argument, 0, OPTION_OUTPUT},
  2468. {"object", required_argument, 0, OPTION_OBJECT},
  2469. {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
  2470. {"force-share", no_argument, 0, 'U'},
  2471. {0, 0, 0, 0}
  2472. };
  2473. c = getopt_long(argc, argv, ":f:hU",
  2474. long_options, &option_index);
  2475. if (c == -1) {
  2476. break;
  2477. }
  2478. switch (c) {
  2479. case ':':
  2480. missing_argument(argv[optind - 1]);
  2481. break;
  2482. case '?':
  2483. unrecognized_option(argv[optind - 1]);
  2484. break;
  2485. case 'h':
  2486. help();
  2487. break;
  2488. case 'f':
  2489. fmt = optarg;
  2490. break;
  2491. case 'U':
  2492. force_share = true;
  2493. break;
  2494. case OPTION_OUTPUT:
  2495. output = optarg;
  2496. break;
  2497. case OPTION_OBJECT: {
  2498. QemuOpts *opts;
  2499. opts = qemu_opts_parse_noisily(&qemu_object_opts,
  2500. optarg, true);
  2501. if (!opts) {
  2502. return 1;
  2503. }
  2504. } break;
  2505. case OPTION_IMAGE_OPTS:
  2506. image_opts = true;
  2507. break;
  2508. }
  2509. }
  2510. if (optind != argc - 1) {
  2511. error_exit("Expecting one image file name");
  2512. }
  2513. filename = argv[optind];
  2514. if (output && !strcmp(output, "json")) {
  2515. output_format = OFORMAT_JSON;
  2516. } else if (output && !strcmp(output, "human")) {
  2517. output_format = OFORMAT_HUMAN;
  2518. } else if (output) {
  2519. error_report("--output must be used with human or json as argument.");
  2520. return 1;
  2521. }
  2522. if (qemu_opts_foreach(&qemu_object_opts,
  2523. user_creatable_add_opts_foreach,
  2524. NULL, NULL)) {
  2525. return 1;
  2526. }
  2527. blk = img_open(image_opts, filename, fmt, 0, false, false, force_share);
  2528. if (!blk) {
  2529. return 1;
  2530. }
  2531. bs = blk_bs(blk);
  2532. if (output_format == OFORMAT_HUMAN) {
  2533. printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
  2534. }
  2535. length = blk_getlength(blk);
  2536. while (curr.start + curr.length < length) {
  2537. int64_t offset = curr.start + curr.length;
  2538. int64_t n;
  2539. /* Probe up to 1 GiB at a time. */
  2540. n = MIN(1 << 30, length - offset);
  2541. ret = get_block_status(bs, offset, n, &next);
  2542. if (ret < 0) {
  2543. error_report("Could not read file metadata: %s", strerror(-ret));
  2544. goto out;
  2545. }
  2546. if (entry_mergeable(&curr, &next)) {
  2547. curr.length += next.length;
  2548. continue;
  2549. }
  2550. if (curr.length > 0) {
  2551. dump_map_entry(output_format, &curr, &next);
  2552. }
  2553. curr = next;
  2554. }
  2555. dump_map_entry(output_format, &curr, NULL);
  2556. out:
  2557. blk_unref(blk);
  2558. return ret < 0;
  2559. }
  2560. #define SNAPSHOT_LIST 1
  2561. #define SNAPSHOT_CREATE 2
  2562. #define SNAPSHOT_APPLY 3
  2563. #define SNAPSHOT_DELETE 4
  2564. static int img_snapshot(int argc, char **argv)
  2565. {
  2566. BlockBackend *blk;
  2567. BlockDriverState *bs;
  2568. QEMUSnapshotInfo sn;
  2569. char *filename, *snapshot_name = NULL;
  2570. int c, ret = 0, bdrv_oflags;
  2571. int action = 0;
  2572. qemu_timeval tv;
  2573. bool quiet = false;
  2574. Error *err = NULL;
  2575. bool image_opts = false;
  2576. bool force_share = false;
  2577. bdrv_oflags = BDRV_O_RDWR;
  2578. /* Parse commandline parameters */
  2579. for(;;) {
  2580. static const struct option long_options[] = {
  2581. {"help", no_argument, 0, 'h'},
  2582. {"object", required_argument, 0, OPTION_OBJECT},
  2583. {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
  2584. {"force-share", no_argument, 0, 'U'},
  2585. {0, 0, 0, 0}
  2586. };
  2587. c = getopt_long(argc, argv, ":la:c:d:hqU",
  2588. long_options, NULL);
  2589. if (c == -1) {
  2590. break;
  2591. }
  2592. switch(c) {
  2593. case ':':
  2594. missing_argument(argv[optind - 1]);
  2595. break;
  2596. case '?':
  2597. unrecognized_option(argv[optind - 1]);
  2598. break;
  2599. case 'h':
  2600. help();
  2601. return 0;
  2602. case 'l':
  2603. if (action) {
  2604. error_exit("Cannot mix '-l', '-a', '-c', '-d'");
  2605. return 0;
  2606. }
  2607. action = SNAPSHOT_LIST;
  2608. bdrv_oflags &= ~BDRV_O_RDWR; /* no need for RW */
  2609. break;
  2610. case 'a':
  2611. if (action) {
  2612. error_exit("Cannot mix '-l', '-a', '-c', '-d'");
  2613. return 0;
  2614. }
  2615. action = SNAPSHOT_APPLY;
  2616. snapshot_name = optarg;
  2617. break;
  2618. case 'c':
  2619. if (action) {
  2620. error_exit("Cannot mix '-l', '-a', '-c', '-d'");
  2621. return 0;
  2622. }
  2623. action = SNAPSHOT_CREATE;
  2624. snapshot_name = optarg;
  2625. break;
  2626. case 'd':
  2627. if (action) {
  2628. error_exit("Cannot mix '-l', '-a', '-c', '-d'");
  2629. return 0;
  2630. }
  2631. action = SNAPSHOT_DELETE;
  2632. snapshot_name = optarg;
  2633. break;
  2634. case 'q':
  2635. quiet = true;
  2636. break;
  2637. case 'U':
  2638. force_share = true;
  2639. break;
  2640. case OPTION_OBJECT: {
  2641. QemuOpts *opts;
  2642. opts = qemu_opts_parse_noisily(&qemu_object_opts,
  2643. optarg, true);
  2644. if (!opts) {
  2645. return 1;
  2646. }
  2647. } break;
  2648. case OPTION_IMAGE_OPTS:
  2649. image_opts = true;
  2650. break;
  2651. }
  2652. }
  2653. if (optind != argc - 1) {
  2654. error_exit("Expecting one image file name");
  2655. }
  2656. filename = argv[optind++];
  2657. if (qemu_opts_foreach(&qemu_object_opts,
  2658. user_creatable_add_opts_foreach,
  2659. NULL, NULL)) {
  2660. return 1;
  2661. }
  2662. /* Open the image */
  2663. blk = img_open(image_opts, filename, NULL, bdrv_oflags, false, quiet,
  2664. force_share);
  2665. if (!blk) {
  2666. return 1;
  2667. }
  2668. bs = blk_bs(blk);
  2669. /* Perform the requested action */
  2670. switch(action) {
  2671. case SNAPSHOT_LIST:
  2672. dump_snapshots(bs);
  2673. break;
  2674. case SNAPSHOT_CREATE:
  2675. memset(&sn, 0, sizeof(sn));
  2676. pstrcpy(sn.name, sizeof(sn.name), snapshot_name);
  2677. qemu_gettimeofday(&tv);
  2678. sn.date_sec = tv.tv_sec;
  2679. sn.date_nsec = tv.tv_usec * 1000;
  2680. ret = bdrv_snapshot_create(bs, &sn);
  2681. if (ret) {
  2682. error_report("Could not create snapshot '%s': %d (%s)",
  2683. snapshot_name, ret, strerror(-ret));
  2684. }
  2685. break;
  2686. case SNAPSHOT_APPLY:
  2687. ret = bdrv_snapshot_goto(bs, snapshot_name, &err);
  2688. if (ret) {
  2689. error_reportf_err(err, "Could not apply snapshot '%s': ",
  2690. snapshot_name);
  2691. }
  2692. break;
  2693. case SNAPSHOT_DELETE:
  2694. bdrv_snapshot_delete_by_id_or_name(bs, snapshot_name, &err);
  2695. if (err) {
  2696. error_reportf_err(err, "Could not delete snapshot '%s': ",
  2697. snapshot_name);
  2698. ret = 1;
  2699. }
  2700. break;
  2701. }
  2702. /* Cleanup */
  2703. blk_unref(blk);
  2704. if (ret) {
  2705. return 1;
  2706. }
  2707. return 0;
  2708. }
  2709. static int img_rebase(int argc, char **argv)
  2710. {
  2711. BlockBackend *blk = NULL, *blk_old_backing = NULL, *blk_new_backing = NULL;
  2712. uint8_t *buf_old = NULL;
  2713. uint8_t *buf_new = NULL;
  2714. BlockDriverState *bs = NULL;
  2715. char *filename;
  2716. const char *fmt, *cache, *src_cache, *out_basefmt, *out_baseimg;
  2717. int c, flags, src_flags, ret;
  2718. bool writethrough, src_writethrough;
  2719. int unsafe = 0;
  2720. bool force_share = false;
  2721. int progress = 0;
  2722. bool quiet = false;
  2723. Error *local_err = NULL;
  2724. bool image_opts = false;
  2725. /* Parse commandline parameters */
  2726. fmt = NULL;
  2727. cache = BDRV_DEFAULT_CACHE;
  2728. src_cache = BDRV_DEFAULT_CACHE;
  2729. out_baseimg = NULL;
  2730. out_basefmt = NULL;
  2731. for(;;) {
  2732. static const struct option long_options[] = {
  2733. {"help", no_argument, 0, 'h'},
  2734. {"object", required_argument, 0, OPTION_OBJECT},
  2735. {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
  2736. {"force-share", no_argument, 0, 'U'},
  2737. {0, 0, 0, 0}
  2738. };
  2739. c = getopt_long(argc, argv, ":hf:F:b:upt:T:qU",
  2740. long_options, NULL);
  2741. if (c == -1) {
  2742. break;
  2743. }
  2744. switch(c) {
  2745. case ':':
  2746. missing_argument(argv[optind - 1]);
  2747. break;
  2748. case '?':
  2749. unrecognized_option(argv[optind - 1]);
  2750. break;
  2751. case 'h':
  2752. help();
  2753. return 0;
  2754. case 'f':
  2755. fmt = optarg;
  2756. break;
  2757. case 'F':
  2758. out_basefmt = optarg;
  2759. break;
  2760. case 'b':
  2761. out_baseimg = optarg;
  2762. break;
  2763. case 'u':
  2764. unsafe = 1;
  2765. break;
  2766. case 'p':
  2767. progress = 1;
  2768. break;
  2769. case 't':
  2770. cache = optarg;
  2771. break;
  2772. case 'T':
  2773. src_cache = optarg;
  2774. break;
  2775. case 'q':
  2776. quiet = true;
  2777. break;
  2778. case OPTION_OBJECT: {
  2779. QemuOpts *opts;
  2780. opts = qemu_opts_parse_noisily(&qemu_object_opts,
  2781. optarg, true);
  2782. if (!opts) {
  2783. return 1;
  2784. }
  2785. } break;
  2786. case OPTION_IMAGE_OPTS:
  2787. image_opts = true;
  2788. break;
  2789. case 'U':
  2790. force_share = true;
  2791. break;
  2792. }
  2793. }
  2794. if (quiet) {
  2795. progress = 0;
  2796. }
  2797. if (optind != argc - 1) {
  2798. error_exit("Expecting one image file name");
  2799. }
  2800. if (!unsafe && !out_baseimg) {
  2801. error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
  2802. }
  2803. filename = argv[optind++];
  2804. if (qemu_opts_foreach(&qemu_object_opts,
  2805. user_creatable_add_opts_foreach,
  2806. NULL, NULL)) {
  2807. return 1;
  2808. }
  2809. qemu_progress_init(progress, 2.0);
  2810. qemu_progress_print(0, 100);
  2811. flags = BDRV_O_RDWR | (unsafe ? BDRV_O_NO_BACKING : 0);
  2812. ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
  2813. if (ret < 0) {
  2814. error_report("Invalid cache option: %s", cache);
  2815. goto out;
  2816. }
  2817. src_flags = 0;
  2818. ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
  2819. if (ret < 0) {
  2820. error_report("Invalid source cache option: %s", src_cache);
  2821. goto out;
  2822. }
  2823. /* The source files are opened read-only, don't care about WCE */
  2824. assert((src_flags & BDRV_O_RDWR) == 0);
  2825. (void) src_writethrough;
  2826. /*
  2827. * Open the images.
  2828. *
  2829. * Ignore the old backing file for unsafe rebase in case we want to correct
  2830. * the reference to a renamed or moved backing file.
  2831. */
  2832. blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
  2833. false);
  2834. if (!blk) {
  2835. ret = -1;
  2836. goto out;
  2837. }
  2838. bs = blk_bs(blk);
  2839. if (out_basefmt != NULL) {
  2840. if (bdrv_find_format(out_basefmt) == NULL) {
  2841. error_report("Invalid format name: '%s'", out_basefmt);
  2842. ret = -1;
  2843. goto out;
  2844. }
  2845. }
  2846. /* For safe rebasing we need to compare old and new backing file */
  2847. if (!unsafe) {
  2848. char backing_name[PATH_MAX];
  2849. QDict *options = NULL;
  2850. if (bs->backing_format[0] != '\0') {
  2851. options = qdict_new();
  2852. qdict_put_str(options, "driver", bs->backing_format);
  2853. }
  2854. if (force_share) {
  2855. if (!options) {
  2856. options = qdict_new();
  2857. }
  2858. qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
  2859. }
  2860. bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
  2861. blk_old_backing = blk_new_open(backing_name, NULL,
  2862. options, src_flags, &local_err);
  2863. if (!blk_old_backing) {
  2864. error_reportf_err(local_err,
  2865. "Could not open old backing file '%s': ",
  2866. backing_name);
  2867. ret = -1;
  2868. goto out;
  2869. }
  2870. if (out_baseimg[0]) {
  2871. const char *overlay_filename;
  2872. char *out_real_path;
  2873. options = qdict_new();
  2874. if (out_basefmt) {
  2875. qdict_put_str(options, "driver", out_basefmt);
  2876. }
  2877. if (force_share) {
  2878. qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
  2879. }
  2880. overlay_filename = bs->exact_filename[0] ? bs->exact_filename
  2881. : bs->filename;
  2882. out_real_path = g_malloc(PATH_MAX);
  2883. bdrv_get_full_backing_filename_from_filename(overlay_filename,
  2884. out_baseimg,
  2885. out_real_path,
  2886. PATH_MAX,
  2887. &local_err);
  2888. if (local_err) {
  2889. error_reportf_err(local_err,
  2890. "Could not resolve backing filename: ");
  2891. ret = -1;
  2892. g_free(out_real_path);
  2893. goto out;
  2894. }
  2895. blk_new_backing = blk_new_open(out_real_path, NULL,
  2896. options, src_flags, &local_err);
  2897. g_free(out_real_path);
  2898. if (!blk_new_backing) {
  2899. error_reportf_err(local_err,
  2900. "Could not open new backing file '%s': ",
  2901. out_baseimg);
  2902. ret = -1;
  2903. goto out;
  2904. }
  2905. }
  2906. }
  2907. /*
  2908. * Check each unallocated cluster in the COW file. If it is unallocated,
  2909. * accesses go to the backing file. We must therefore compare this cluster
  2910. * in the old and new backing file, and if they differ we need to copy it
  2911. * from the old backing file into the COW file.
  2912. *
  2913. * If qemu-img crashes during this step, no harm is done. The content of
  2914. * the image is the same as the original one at any time.
  2915. */
  2916. if (!unsafe) {
  2917. int64_t size;
  2918. int64_t old_backing_size;
  2919. int64_t new_backing_size = 0;
  2920. uint64_t offset;
  2921. int64_t n;
  2922. float local_progress = 0;
  2923. buf_old = blk_blockalign(blk, IO_BUF_SIZE);
  2924. buf_new = blk_blockalign(blk, IO_BUF_SIZE);
  2925. size = blk_getlength(blk);
  2926. if (size < 0) {
  2927. error_report("Could not get size of '%s': %s",
  2928. filename, strerror(-size));
  2929. ret = -1;
  2930. goto out;
  2931. }
  2932. old_backing_size = blk_getlength(blk_old_backing);
  2933. if (old_backing_size < 0) {
  2934. char backing_name[PATH_MAX];
  2935. bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
  2936. error_report("Could not get size of '%s': %s",
  2937. backing_name, strerror(-old_backing_size));
  2938. ret = -1;
  2939. goto out;
  2940. }
  2941. if (blk_new_backing) {
  2942. new_backing_size = blk_getlength(blk_new_backing);
  2943. if (new_backing_size < 0) {
  2944. error_report("Could not get size of '%s': %s",
  2945. out_baseimg, strerror(-new_backing_size));
  2946. ret = -1;
  2947. goto out;
  2948. }
  2949. }
  2950. if (size != 0) {
  2951. local_progress = (float)100 / (size / MIN(size, IO_BUF_SIZE));
  2952. }
  2953. for (offset = 0; offset < size; offset += n) {
  2954. /* How many bytes can we handle with the next read? */
  2955. n = MIN(IO_BUF_SIZE, size - offset);
  2956. /* If the cluster is allocated, we don't need to take action */
  2957. ret = bdrv_is_allocated(bs, offset, n, &n);
  2958. if (ret < 0) {
  2959. error_report("error while reading image metadata: %s",
  2960. strerror(-ret));
  2961. goto out;
  2962. }
  2963. if (ret) {
  2964. continue;
  2965. }
  2966. /*
  2967. * Read old and new backing file and take into consideration that
  2968. * backing files may be smaller than the COW image.
  2969. */
  2970. if (offset >= old_backing_size) {
  2971. memset(buf_old, 0, n);
  2972. } else {
  2973. if (offset + n > old_backing_size) {
  2974. n = old_backing_size - offset;
  2975. }
  2976. ret = blk_pread(blk_old_backing, offset, buf_old, n);
  2977. if (ret < 0) {
  2978. error_report("error while reading from old backing file");
  2979. goto out;
  2980. }
  2981. }
  2982. if (offset >= new_backing_size || !blk_new_backing) {
  2983. memset(buf_new, 0, n);
  2984. } else {
  2985. if (offset + n > new_backing_size) {
  2986. n = new_backing_size - offset;
  2987. }
  2988. ret = blk_pread(blk_new_backing, offset, buf_new, n);
  2989. if (ret < 0) {
  2990. error_report("error while reading from new backing file");
  2991. goto out;
  2992. }
  2993. }
  2994. /* If they differ, we need to write to the COW file */
  2995. uint64_t written = 0;
  2996. while (written < n) {
  2997. int64_t pnum;
  2998. if (compare_buffers(buf_old + written, buf_new + written,
  2999. n - written, &pnum))
  3000. {
  3001. ret = blk_pwrite(blk, offset + written,
  3002. buf_old + written, pnum, 0);
  3003. if (ret < 0) {
  3004. error_report("Error while writing to COW image: %s",
  3005. strerror(-ret));
  3006. goto out;
  3007. }
  3008. }
  3009. written += pnum;
  3010. }
  3011. qemu_progress_print(local_progress, 100);
  3012. }
  3013. }
  3014. /*
  3015. * Change the backing file. All clusters that are different from the old
  3016. * backing file are overwritten in the COW file now, so the visible content
  3017. * doesn't change when we switch the backing file.
  3018. */
  3019. if (out_baseimg && *out_baseimg) {
  3020. ret = bdrv_change_backing_file(bs, out_baseimg, out_basefmt);
  3021. } else {
  3022. ret = bdrv_change_backing_file(bs, NULL, NULL);
  3023. }
  3024. if (ret == -ENOSPC) {
  3025. error_report("Could not change the backing file to '%s': No "
  3026. "space left in the file header", out_baseimg);
  3027. } else if (ret < 0) {
  3028. error_report("Could not change the backing file to '%s': %s",
  3029. out_baseimg, strerror(-ret));
  3030. }
  3031. qemu_progress_print(100, 0);
  3032. /*
  3033. * TODO At this point it is possible to check if any clusters that are
  3034. * allocated in the COW file are the same in the backing file. If so, they
  3035. * could be dropped from the COW file. Don't do this before switching the
  3036. * backing file, in case of a crash this would lead to corruption.
  3037. */
  3038. out:
  3039. qemu_progress_end();
  3040. /* Cleanup */
  3041. if (!unsafe) {
  3042. blk_unref(blk_old_backing);
  3043. blk_unref(blk_new_backing);
  3044. }
  3045. qemu_vfree(buf_old);
  3046. qemu_vfree(buf_new);
  3047. blk_unref(blk);
  3048. if (ret) {
  3049. return 1;
  3050. }
  3051. return 0;
  3052. }
  3053. static int img_resize(int argc, char **argv)
  3054. {
  3055. Error *err = NULL;
  3056. int c, ret, relative;
  3057. const char *filename, *fmt, *size;
  3058. int64_t n, total_size, current_size;
  3059. bool quiet = false;
  3060. BlockBackend *blk = NULL;
  3061. PreallocMode prealloc = PREALLOC_MODE_OFF;
  3062. QemuOpts *param;
  3063. static QemuOptsList resize_options = {
  3064. .name = "resize_options",
  3065. .head = QTAILQ_HEAD_INITIALIZER(resize_options.head),
  3066. .desc = {
  3067. {
  3068. .name = BLOCK_OPT_SIZE,
  3069. .type = QEMU_OPT_SIZE,
  3070. .help = "Virtual disk size"
  3071. }, {
  3072. /* end of list */
  3073. }
  3074. },
  3075. };
  3076. bool image_opts = false;
  3077. bool shrink = false;
  3078. /* Remove size from argv manually so that negative numbers are not treated
  3079. * as options by getopt. */
  3080. if (argc < 3) {
  3081. error_exit("Not enough arguments");
  3082. return 1;
  3083. }
  3084. size = argv[--argc];
  3085. /* Parse getopt arguments */
  3086. fmt = NULL;
  3087. for(;;) {
  3088. static const struct option long_options[] = {
  3089. {"help", no_argument, 0, 'h'},
  3090. {"object", required_argument, 0, OPTION_OBJECT},
  3091. {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
  3092. {"preallocation", required_argument, 0, OPTION_PREALLOCATION},
  3093. {"shrink", no_argument, 0, OPTION_SHRINK},
  3094. {0, 0, 0, 0}
  3095. };
  3096. c = getopt_long(argc, argv, ":f:hq",
  3097. long_options, NULL);
  3098. if (c == -1) {
  3099. break;
  3100. }
  3101. switch(c) {
  3102. case ':':
  3103. missing_argument(argv[optind - 1]);
  3104. break;
  3105. case '?':
  3106. unrecognized_option(argv[optind - 1]);
  3107. break;
  3108. case 'h':
  3109. help();
  3110. break;
  3111. case 'f':
  3112. fmt = optarg;
  3113. break;
  3114. case 'q':
  3115. quiet = true;
  3116. break;
  3117. case OPTION_OBJECT: {
  3118. QemuOpts *opts;
  3119. opts = qemu_opts_parse_noisily(&qemu_object_opts,
  3120. optarg, true);
  3121. if (!opts) {
  3122. return 1;
  3123. }
  3124. } break;
  3125. case OPTION_IMAGE_OPTS:
  3126. image_opts = true;
  3127. break;
  3128. case OPTION_PREALLOCATION:
  3129. prealloc = qapi_enum_parse(&PreallocMode_lookup, optarg,
  3130. PREALLOC_MODE__MAX, NULL);
  3131. if (prealloc == PREALLOC_MODE__MAX) {
  3132. error_report("Invalid preallocation mode '%s'", optarg);
  3133. return 1;
  3134. }
  3135. break;
  3136. case OPTION_SHRINK:
  3137. shrink = true;
  3138. break;
  3139. }
  3140. }
  3141. if (optind != argc - 1) {
  3142. error_exit("Expecting image file name and size");
  3143. }
  3144. filename = argv[optind++];
  3145. if (qemu_opts_foreach(&qemu_object_opts,
  3146. user_creatable_add_opts_foreach,
  3147. NULL, NULL)) {
  3148. return 1;
  3149. }
  3150. /* Choose grow, shrink, or absolute resize mode */
  3151. switch (size[0]) {
  3152. case '+':
  3153. relative = 1;
  3154. size++;
  3155. break;
  3156. case '-':
  3157. relative = -1;
  3158. size++;
  3159. break;
  3160. default:
  3161. relative = 0;
  3162. break;
  3163. }
  3164. /* Parse size */
  3165. param = qemu_opts_create(&resize_options, NULL, 0, &error_abort);
  3166. qemu_opt_set(param, BLOCK_OPT_SIZE, size, &err);
  3167. if (err) {
  3168. error_report_err(err);
  3169. ret = -1;
  3170. qemu_opts_del(param);
  3171. goto out;
  3172. }
  3173. n = qemu_opt_get_size(param, BLOCK_OPT_SIZE, 0);
  3174. qemu_opts_del(param);
  3175. blk = img_open(image_opts, filename, fmt,
  3176. BDRV_O_RDWR | BDRV_O_RESIZE, false, quiet,
  3177. false);
  3178. if (!blk) {
  3179. ret = -1;
  3180. goto out;
  3181. }
  3182. current_size = blk_getlength(blk);
  3183. if (current_size < 0) {
  3184. error_report("Failed to inquire current image length: %s",
  3185. strerror(-current_size));
  3186. ret = -1;
  3187. goto out;
  3188. }
  3189. if (relative) {
  3190. total_size = current_size + n * relative;
  3191. } else {
  3192. total_size = n;
  3193. }
  3194. if (total_size <= 0) {
  3195. error_report("New image size must be positive");
  3196. ret = -1;
  3197. goto out;
  3198. }
  3199. if (total_size <= current_size && prealloc != PREALLOC_MODE_OFF) {
  3200. error_report("Preallocation can only be used for growing images");
  3201. ret = -1;
  3202. goto out;
  3203. }
  3204. if (total_size < current_size && !shrink) {
  3205. warn_report("Shrinking an image will delete all data beyond the "
  3206. "shrunken image's end. Before performing such an "
  3207. "operation, make sure there is no important data there.");
  3208. if (g_strcmp0(bdrv_get_format_name(blk_bs(blk)), "raw") != 0) {
  3209. error_report(
  3210. "Use the --shrink option to perform a shrink operation.");
  3211. ret = -1;
  3212. goto out;
  3213. } else {
  3214. warn_report("Using the --shrink option will suppress this message. "
  3215. "Note that future versions of qemu-img may refuse to "
  3216. "shrink images without this option.");
  3217. }
  3218. }
  3219. ret = blk_truncate(blk, total_size, prealloc, &err);
  3220. if (!ret) {
  3221. qprintf(quiet, "Image resized.\n");
  3222. } else {
  3223. error_report_err(err);
  3224. }
  3225. out:
  3226. blk_unref(blk);
  3227. if (ret) {
  3228. return 1;
  3229. }
  3230. return 0;
  3231. }
  3232. static void amend_status_cb(BlockDriverState *bs,
  3233. int64_t offset, int64_t total_work_size,
  3234. void *opaque)
  3235. {
  3236. qemu_progress_print(100.f * offset / total_work_size, 0);
  3237. }
  3238. static int img_amend(int argc, char **argv)
  3239. {
  3240. Error *err = NULL;
  3241. int c, ret = 0;
  3242. char *options = NULL;
  3243. QemuOptsList *create_opts = NULL;
  3244. QemuOpts *opts = NULL;
  3245. const char *fmt = NULL, *filename, *cache;
  3246. int flags;
  3247. bool writethrough;
  3248. bool quiet = false, progress = false;
  3249. BlockBackend *blk = NULL;
  3250. BlockDriverState *bs = NULL;
  3251. bool image_opts = false;
  3252. cache = BDRV_DEFAULT_CACHE;
  3253. for (;;) {
  3254. static const struct option long_options[] = {
  3255. {"help", no_argument, 0, 'h'},
  3256. {"object", required_argument, 0, OPTION_OBJECT},
  3257. {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
  3258. {0, 0, 0, 0}
  3259. };
  3260. c = getopt_long(argc, argv, ":ho:f:t:pq",
  3261. long_options, NULL);
  3262. if (c == -1) {
  3263. break;
  3264. }
  3265. switch (c) {
  3266. case ':':
  3267. missing_argument(argv[optind - 1]);
  3268. break;
  3269. case '?':
  3270. unrecognized_option(argv[optind - 1]);
  3271. break;
  3272. case 'h':
  3273. help();
  3274. break;
  3275. case 'o':
  3276. if (!is_valid_option_list(optarg)) {
  3277. error_report("Invalid option list: %s", optarg);
  3278. ret = -1;
  3279. goto out_no_progress;
  3280. }
  3281. if (!options) {
  3282. options = g_strdup(optarg);
  3283. } else {
  3284. char *old_options = options;
  3285. options = g_strdup_printf("%s,%s", options, optarg);
  3286. g_free(old_options);
  3287. }
  3288. break;
  3289. case 'f':
  3290. fmt = optarg;
  3291. break;
  3292. case 't':
  3293. cache = optarg;
  3294. break;
  3295. case 'p':
  3296. progress = true;
  3297. break;
  3298. case 'q':
  3299. quiet = true;
  3300. break;
  3301. case OPTION_OBJECT:
  3302. opts = qemu_opts_parse_noisily(&qemu_object_opts,
  3303. optarg, true);
  3304. if (!opts) {
  3305. ret = -1;
  3306. goto out_no_progress;
  3307. }
  3308. break;
  3309. case OPTION_IMAGE_OPTS:
  3310. image_opts = true;
  3311. break;
  3312. }
  3313. }
  3314. if (!options) {
  3315. error_exit("Must specify options (-o)");
  3316. }
  3317. if (qemu_opts_foreach(&qemu_object_opts,
  3318. user_creatable_add_opts_foreach,
  3319. NULL, NULL)) {
  3320. ret = -1;
  3321. goto out_no_progress;
  3322. }
  3323. if (quiet) {
  3324. progress = false;
  3325. }
  3326. qemu_progress_init(progress, 1.0);
  3327. filename = (optind == argc - 1) ? argv[argc - 1] : NULL;
  3328. if (fmt && has_help_option(options)) {
  3329. /* If a format is explicitly specified (and possibly no filename is
  3330. * given), print option help here */
  3331. ret = print_block_option_help(filename, fmt);
  3332. goto out;
  3333. }
  3334. if (optind != argc - 1) {
  3335. error_report("Expecting one image file name");
  3336. ret = -1;
  3337. goto out;
  3338. }
  3339. flags = BDRV_O_RDWR;
  3340. ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
  3341. if (ret < 0) {
  3342. error_report("Invalid cache option: %s", cache);
  3343. goto out;
  3344. }
  3345. blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
  3346. false);
  3347. if (!blk) {
  3348. ret = -1;
  3349. goto out;
  3350. }
  3351. bs = blk_bs(blk);
  3352. fmt = bs->drv->format_name;
  3353. if (has_help_option(options)) {
  3354. /* If the format was auto-detected, print option help here */
  3355. ret = print_block_option_help(filename, fmt);
  3356. goto out;
  3357. }
  3358. if (!bs->drv->create_opts) {
  3359. error_report("Format driver '%s' does not support any options to amend",
  3360. fmt);
  3361. ret = -1;
  3362. goto out;
  3363. }
  3364. create_opts = qemu_opts_append(create_opts, bs->drv->create_opts);
  3365. opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
  3366. qemu_opts_do_parse(opts, options, NULL, &err);
  3367. if (err) {
  3368. error_report_err(err);
  3369. ret = -1;
  3370. goto out;
  3371. }
  3372. /* In case the driver does not call amend_status_cb() */
  3373. qemu_progress_print(0.f, 0);
  3374. ret = bdrv_amend_options(bs, opts, &amend_status_cb, NULL);
  3375. qemu_progress_print(100.f, 0);
  3376. if (ret < 0) {
  3377. error_report("Error while amending options: %s", strerror(-ret));
  3378. goto out;
  3379. }
  3380. out:
  3381. qemu_progress_end();
  3382. out_no_progress:
  3383. blk_unref(blk);
  3384. qemu_opts_del(opts);
  3385. qemu_opts_free(create_opts);
  3386. g_free(options);
  3387. if (ret) {
  3388. return 1;
  3389. }
  3390. return 0;
  3391. }
  3392. typedef struct BenchData {
  3393. BlockBackend *blk;
  3394. uint64_t image_size;
  3395. bool write;
  3396. int bufsize;
  3397. int step;
  3398. int nrreq;
  3399. int n;
  3400. int flush_interval;
  3401. bool drain_on_flush;
  3402. uint8_t *buf;
  3403. QEMUIOVector *qiov;
  3404. int in_flight;
  3405. bool in_flush;
  3406. uint64_t offset;
  3407. } BenchData;
  3408. static void bench_undrained_flush_cb(void *opaque, int ret)
  3409. {
  3410. if (ret < 0) {
  3411. error_report("Failed flush request: %s", strerror(-ret));
  3412. exit(EXIT_FAILURE);
  3413. }
  3414. }
  3415. static void bench_cb(void *opaque, int ret)
  3416. {
  3417. BenchData *b = opaque;
  3418. BlockAIOCB *acb;
  3419. if (ret < 0) {
  3420. error_report("Failed request: %s", strerror(-ret));
  3421. exit(EXIT_FAILURE);
  3422. }
  3423. if (b->in_flush) {
  3424. /* Just finished a flush with drained queue: Start next requests */
  3425. assert(b->in_flight == 0);
  3426. b->in_flush = false;
  3427. } else if (b->in_flight > 0) {
  3428. int remaining = b->n - b->in_flight;
  3429. b->n--;
  3430. b->in_flight--;
  3431. /* Time for flush? Drain queue if requested, then flush */
  3432. if (b->flush_interval && remaining % b->flush_interval == 0) {
  3433. if (!b->in_flight || !b->drain_on_flush) {
  3434. BlockCompletionFunc *cb;
  3435. if (b->drain_on_flush) {
  3436. b->in_flush = true;
  3437. cb = bench_cb;
  3438. } else {
  3439. cb = bench_undrained_flush_cb;
  3440. }
  3441. acb = blk_aio_flush(b->blk, cb, b);
  3442. if (!acb) {
  3443. error_report("Failed to issue flush request");
  3444. exit(EXIT_FAILURE);
  3445. }
  3446. }
  3447. if (b->drain_on_flush) {
  3448. return;
  3449. }
  3450. }
  3451. }
  3452. while (b->n > b->in_flight && b->in_flight < b->nrreq) {
  3453. int64_t offset = b->offset;
  3454. /* blk_aio_* might look for completed I/Os and kick bench_cb
  3455. * again, so make sure this operation is counted by in_flight
  3456. * and b->offset is ready for the next submission.
  3457. */
  3458. b->in_flight++;
  3459. b->offset += b->step;
  3460. b->offset %= b->image_size;
  3461. if (b->write) {
  3462. acb = blk_aio_pwritev(b->blk, offset, b->qiov, 0, bench_cb, b);
  3463. } else {
  3464. acb = blk_aio_preadv(b->blk, offset, b->qiov, 0, bench_cb, b);
  3465. }
  3466. if (!acb) {
  3467. error_report("Failed to issue request");
  3468. exit(EXIT_FAILURE);
  3469. }
  3470. }
  3471. }
  3472. static int img_bench(int argc, char **argv)
  3473. {
  3474. int c, ret = 0;
  3475. const char *fmt = NULL, *filename;
  3476. bool quiet = false;
  3477. bool image_opts = false;
  3478. bool is_write = false;
  3479. int count = 75000;
  3480. int depth = 64;
  3481. int64_t offset = 0;
  3482. size_t bufsize = 4096;
  3483. int pattern = 0;
  3484. size_t step = 0;
  3485. int flush_interval = 0;
  3486. bool drain_on_flush = true;
  3487. int64_t image_size;
  3488. BlockBackend *blk = NULL;
  3489. BenchData data = {};
  3490. int flags = 0;
  3491. bool writethrough = false;
  3492. struct timeval t1, t2;
  3493. int i;
  3494. bool force_share = false;
  3495. size_t buf_size;
  3496. for (;;) {
  3497. static const struct option long_options[] = {
  3498. {"help", no_argument, 0, 'h'},
  3499. {"flush-interval", required_argument, 0, OPTION_FLUSH_INTERVAL},
  3500. {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
  3501. {"pattern", required_argument, 0, OPTION_PATTERN},
  3502. {"no-drain", no_argument, 0, OPTION_NO_DRAIN},
  3503. {"force-share", no_argument, 0, 'U'},
  3504. {0, 0, 0, 0}
  3505. };
  3506. c = getopt_long(argc, argv, ":hc:d:f:no:qs:S:t:wU", long_options, NULL);
  3507. if (c == -1) {
  3508. break;
  3509. }
  3510. switch (c) {
  3511. case ':':
  3512. missing_argument(argv[optind - 1]);
  3513. break;
  3514. case '?':
  3515. unrecognized_option(argv[optind - 1]);
  3516. break;
  3517. case 'h':
  3518. help();
  3519. break;
  3520. case 'c':
  3521. {
  3522. unsigned long res;
  3523. if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
  3524. error_report("Invalid request count specified");
  3525. return 1;
  3526. }
  3527. count = res;
  3528. break;
  3529. }
  3530. case 'd':
  3531. {
  3532. unsigned long res;
  3533. if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
  3534. error_report("Invalid queue depth specified");
  3535. return 1;
  3536. }
  3537. depth = res;
  3538. break;
  3539. }
  3540. case 'f':
  3541. fmt = optarg;
  3542. break;
  3543. case 'n':
  3544. flags |= BDRV_O_NATIVE_AIO;
  3545. break;
  3546. case 'o':
  3547. {
  3548. offset = cvtnum(optarg);
  3549. if (offset < 0) {
  3550. error_report("Invalid offset specified");
  3551. return 1;
  3552. }
  3553. break;
  3554. }
  3555. break;
  3556. case 'q':
  3557. quiet = true;
  3558. break;
  3559. case 's':
  3560. {
  3561. int64_t sval;
  3562. sval = cvtnum(optarg);
  3563. if (sval < 0 || sval > INT_MAX) {
  3564. error_report("Invalid buffer size specified");
  3565. return 1;
  3566. }
  3567. bufsize = sval;
  3568. break;
  3569. }
  3570. case 'S':
  3571. {
  3572. int64_t sval;
  3573. sval = cvtnum(optarg);
  3574. if (sval < 0 || sval > INT_MAX) {
  3575. error_report("Invalid step size specified");
  3576. return 1;
  3577. }
  3578. step = sval;
  3579. break;
  3580. }
  3581. case 't':
  3582. ret = bdrv_parse_cache_mode(optarg, &flags, &writethrough);
  3583. if (ret < 0) {
  3584. error_report("Invalid cache mode");
  3585. ret = -1;
  3586. goto out;
  3587. }
  3588. break;
  3589. case 'w':
  3590. flags |= BDRV_O_RDWR;
  3591. is_write = true;
  3592. break;
  3593. case 'U':
  3594. force_share = true;
  3595. break;
  3596. case OPTION_PATTERN:
  3597. {
  3598. unsigned long res;
  3599. if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > 0xff) {
  3600. error_report("Invalid pattern byte specified");
  3601. return 1;
  3602. }
  3603. pattern = res;
  3604. break;
  3605. }
  3606. case OPTION_FLUSH_INTERVAL:
  3607. {
  3608. unsigned long res;
  3609. if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
  3610. error_report("Invalid flush interval specified");
  3611. return 1;
  3612. }
  3613. flush_interval = res;
  3614. break;
  3615. }
  3616. case OPTION_NO_DRAIN:
  3617. drain_on_flush = false;
  3618. break;
  3619. case OPTION_IMAGE_OPTS:
  3620. image_opts = true;
  3621. break;
  3622. }
  3623. }
  3624. if (optind != argc - 1) {
  3625. error_exit("Expecting one image file name");
  3626. }
  3627. filename = argv[argc - 1];
  3628. if (!is_write && flush_interval) {
  3629. error_report("--flush-interval is only available in write tests");
  3630. ret = -1;
  3631. goto out;
  3632. }
  3633. if (flush_interval && flush_interval < depth) {
  3634. error_report("Flush interval can't be smaller than depth");
  3635. ret = -1;
  3636. goto out;
  3637. }
  3638. blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
  3639. force_share);
  3640. if (!blk) {
  3641. ret = -1;
  3642. goto out;
  3643. }
  3644. image_size = blk_getlength(blk);
  3645. if (image_size < 0) {
  3646. ret = image_size;
  3647. goto out;
  3648. }
  3649. data = (BenchData) {
  3650. .blk = blk,
  3651. .image_size = image_size,
  3652. .bufsize = bufsize,
  3653. .step = step ?: bufsize,
  3654. .nrreq = depth,
  3655. .n = count,
  3656. .offset = offset,
  3657. .write = is_write,
  3658. .flush_interval = flush_interval,
  3659. .drain_on_flush = drain_on_flush,
  3660. };
  3661. printf("Sending %d %s requests, %d bytes each, %d in parallel "
  3662. "(starting at offset %" PRId64 ", step size %d)\n",
  3663. data.n, data.write ? "write" : "read", data.bufsize, data.nrreq,
  3664. data.offset, data.step);
  3665. if (flush_interval) {
  3666. printf("Sending flush every %d requests\n", flush_interval);
  3667. }
  3668. buf_size = data.nrreq * data.bufsize;
  3669. data.buf = blk_blockalign(blk, buf_size);
  3670. memset(data.buf, pattern, data.nrreq * data.bufsize);
  3671. blk_register_buf(blk, data.buf, buf_size);
  3672. data.qiov = g_new(QEMUIOVector, data.nrreq);
  3673. for (i = 0; i < data.nrreq; i++) {
  3674. qemu_iovec_init(&data.qiov[i], 1);
  3675. qemu_iovec_add(&data.qiov[i],
  3676. data.buf + i * data.bufsize, data.bufsize);
  3677. }
  3678. gettimeofday(&t1, NULL);
  3679. bench_cb(&data, 0);
  3680. while (data.n > 0) {
  3681. main_loop_wait(false);
  3682. }
  3683. gettimeofday(&t2, NULL);
  3684. printf("Run completed in %3.3f seconds.\n",
  3685. (t2.tv_sec - t1.tv_sec)
  3686. + ((double)(t2.tv_usec - t1.tv_usec) / 1000000));
  3687. out:
  3688. if (data.buf) {
  3689. blk_unregister_buf(blk, data.buf);
  3690. }
  3691. qemu_vfree(data.buf);
  3692. blk_unref(blk);
  3693. if (ret) {
  3694. return 1;
  3695. }
  3696. return 0;
  3697. }
  3698. #define C_BS 01
  3699. #define C_COUNT 02
  3700. #define C_IF 04
  3701. #define C_OF 010
  3702. #define C_SKIP 020
  3703. struct DdInfo {
  3704. unsigned int flags;
  3705. int64_t count;
  3706. };
  3707. struct DdIo {
  3708. int bsz; /* Block size */
  3709. char *filename;
  3710. uint8_t *buf;
  3711. int64_t offset;
  3712. };
  3713. struct DdOpts {
  3714. const char *name;
  3715. int (*f)(const char *, struct DdIo *, struct DdIo *, struct DdInfo *);
  3716. unsigned int flag;
  3717. };
  3718. static int img_dd_bs(const char *arg,
  3719. struct DdIo *in, struct DdIo *out,
  3720. struct DdInfo *dd)
  3721. {
  3722. int64_t res;
  3723. res = cvtnum(arg);
  3724. if (res <= 0 || res > INT_MAX) {
  3725. error_report("invalid number: '%s'", arg);
  3726. return 1;
  3727. }
  3728. in->bsz = out->bsz = res;
  3729. return 0;
  3730. }
  3731. static int img_dd_count(const char *arg,
  3732. struct DdIo *in, struct DdIo *out,
  3733. struct DdInfo *dd)
  3734. {
  3735. dd->count = cvtnum(arg);
  3736. if (dd->count < 0) {
  3737. error_report("invalid number: '%s'", arg);
  3738. return 1;
  3739. }
  3740. return 0;
  3741. }
  3742. static int img_dd_if(const char *arg,
  3743. struct DdIo *in, struct DdIo *out,
  3744. struct DdInfo *dd)
  3745. {
  3746. in->filename = g_strdup(arg);
  3747. return 0;
  3748. }
  3749. static int img_dd_of(const char *arg,
  3750. struct DdIo *in, struct DdIo *out,
  3751. struct DdInfo *dd)
  3752. {
  3753. out->filename = g_strdup(arg);
  3754. return 0;
  3755. }
  3756. static int img_dd_skip(const char *arg,
  3757. struct DdIo *in, struct DdIo *out,
  3758. struct DdInfo *dd)
  3759. {
  3760. in->offset = cvtnum(arg);
  3761. if (in->offset < 0) {
  3762. error_report("invalid number: '%s'", arg);
  3763. return 1;
  3764. }
  3765. return 0;
  3766. }
  3767. static int img_dd(int argc, char **argv)
  3768. {
  3769. int ret = 0;
  3770. char *arg = NULL;
  3771. char *tmp;
  3772. BlockDriver *drv = NULL, *proto_drv = NULL;
  3773. BlockBackend *blk1 = NULL, *blk2 = NULL;
  3774. QemuOpts *opts = NULL;
  3775. QemuOptsList *create_opts = NULL;
  3776. Error *local_err = NULL;
  3777. bool image_opts = false;
  3778. int c, i;
  3779. const char *out_fmt = "raw";
  3780. const char *fmt = NULL;
  3781. int64_t size = 0;
  3782. int64_t block_count = 0, out_pos, in_pos;
  3783. bool force_share = false;
  3784. struct DdInfo dd = {
  3785. .flags = 0,
  3786. .count = 0,
  3787. };
  3788. struct DdIo in = {
  3789. .bsz = 512, /* Block size is by default 512 bytes */
  3790. .filename = NULL,
  3791. .buf = NULL,
  3792. .offset = 0
  3793. };
  3794. struct DdIo out = {
  3795. .bsz = 512,
  3796. .filename = NULL,
  3797. .buf = NULL,
  3798. .offset = 0
  3799. };
  3800. const struct DdOpts options[] = {
  3801. { "bs", img_dd_bs, C_BS },
  3802. { "count", img_dd_count, C_COUNT },
  3803. { "if", img_dd_if, C_IF },
  3804. { "of", img_dd_of, C_OF },
  3805. { "skip", img_dd_skip, C_SKIP },
  3806. { NULL, NULL, 0 }
  3807. };
  3808. const struct option long_options[] = {
  3809. { "help", no_argument, 0, 'h'},
  3810. { "object", required_argument, 0, OPTION_OBJECT},
  3811. { "image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
  3812. { "force-share", no_argument, 0, 'U'},
  3813. { 0, 0, 0, 0 }
  3814. };
  3815. while ((c = getopt_long(argc, argv, ":hf:O:U", long_options, NULL))) {
  3816. if (c == EOF) {
  3817. break;
  3818. }
  3819. switch (c) {
  3820. case 'O':
  3821. out_fmt = optarg;
  3822. break;
  3823. case 'f':
  3824. fmt = optarg;
  3825. break;
  3826. case ':':
  3827. missing_argument(argv[optind - 1]);
  3828. break;
  3829. case '?':
  3830. unrecognized_option(argv[optind - 1]);
  3831. break;
  3832. case 'h':
  3833. help();
  3834. break;
  3835. case 'U':
  3836. force_share = true;
  3837. break;
  3838. case OPTION_OBJECT:
  3839. if (!qemu_opts_parse_noisily(&qemu_object_opts, optarg, true)) {
  3840. ret = -1;
  3841. goto out;
  3842. }
  3843. break;
  3844. case OPTION_IMAGE_OPTS:
  3845. image_opts = true;
  3846. break;
  3847. }
  3848. }
  3849. for (i = optind; i < argc; i++) {
  3850. int j;
  3851. arg = g_strdup(argv[i]);
  3852. tmp = strchr(arg, '=');
  3853. if (tmp == NULL) {
  3854. error_report("unrecognized operand %s", arg);
  3855. ret = -1;
  3856. goto out;
  3857. }
  3858. *tmp++ = '\0';
  3859. for (j = 0; options[j].name != NULL; j++) {
  3860. if (!strcmp(arg, options[j].name)) {
  3861. break;
  3862. }
  3863. }
  3864. if (options[j].name == NULL) {
  3865. error_report("unrecognized operand %s", arg);
  3866. ret = -1;
  3867. goto out;
  3868. }
  3869. if (options[j].f(tmp, &in, &out, &dd) != 0) {
  3870. ret = -1;
  3871. goto out;
  3872. }
  3873. dd.flags |= options[j].flag;
  3874. g_free(arg);
  3875. arg = NULL;
  3876. }
  3877. if (!(dd.flags & C_IF && dd.flags & C_OF)) {
  3878. error_report("Must specify both input and output files");
  3879. ret = -1;
  3880. goto out;
  3881. }
  3882. if (qemu_opts_foreach(&qemu_object_opts,
  3883. user_creatable_add_opts_foreach,
  3884. NULL, NULL)) {
  3885. ret = -1;
  3886. goto out;
  3887. }
  3888. blk1 = img_open(image_opts, in.filename, fmt, 0, false, false,
  3889. force_share);
  3890. if (!blk1) {
  3891. ret = -1;
  3892. goto out;
  3893. }
  3894. drv = bdrv_find_format(out_fmt);
  3895. if (!drv) {
  3896. error_report("Unknown file format");
  3897. ret = -1;
  3898. goto out;
  3899. }
  3900. proto_drv = bdrv_find_protocol(out.filename, true, &local_err);
  3901. if (!proto_drv) {
  3902. error_report_err(local_err);
  3903. ret = -1;
  3904. goto out;
  3905. }
  3906. if (!drv->create_opts) {
  3907. error_report("Format driver '%s' does not support image creation",
  3908. drv->format_name);
  3909. ret = -1;
  3910. goto out;
  3911. }
  3912. if (!proto_drv->create_opts) {
  3913. error_report("Protocol driver '%s' does not support image creation",
  3914. proto_drv->format_name);
  3915. ret = -1;
  3916. goto out;
  3917. }
  3918. create_opts = qemu_opts_append(create_opts, drv->create_opts);
  3919. create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
  3920. opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
  3921. size = blk_getlength(blk1);
  3922. if (size < 0) {
  3923. error_report("Failed to get size for '%s'", in.filename);
  3924. ret = -1;
  3925. goto out;
  3926. }
  3927. if (dd.flags & C_COUNT && dd.count <= INT64_MAX / in.bsz &&
  3928. dd.count * in.bsz < size) {
  3929. size = dd.count * in.bsz;
  3930. }
  3931. /* Overflow means the specified offset is beyond input image's size */
  3932. if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
  3933. size < in.bsz * in.offset)) {
  3934. qemu_opt_set_number(opts, BLOCK_OPT_SIZE, 0, &error_abort);
  3935. } else {
  3936. qemu_opt_set_number(opts, BLOCK_OPT_SIZE,
  3937. size - in.bsz * in.offset, &error_abort);
  3938. }
  3939. ret = bdrv_create(drv, out.filename, opts, &local_err);
  3940. if (ret < 0) {
  3941. error_reportf_err(local_err,
  3942. "%s: error while creating output image: ",
  3943. out.filename);
  3944. ret = -1;
  3945. goto out;
  3946. }
  3947. /* TODO, we can't honour --image-opts for the target,
  3948. * since it needs to be given in a format compatible
  3949. * with the bdrv_create() call above which does not
  3950. * support image-opts style.
  3951. */
  3952. blk2 = img_open_file(out.filename, NULL, out_fmt, BDRV_O_RDWR,
  3953. false, false, false);
  3954. if (!blk2) {
  3955. ret = -1;
  3956. goto out;
  3957. }
  3958. if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
  3959. size < in.offset * in.bsz)) {
  3960. /* We give a warning if the skip option is bigger than the input
  3961. * size and create an empty output disk image (i.e. like dd(1)).
  3962. */
  3963. error_report("%s: cannot skip to specified offset", in.filename);
  3964. in_pos = size;
  3965. } else {
  3966. in_pos = in.offset * in.bsz;
  3967. }
  3968. in.buf = g_new(uint8_t, in.bsz);
  3969. for (out_pos = 0; in_pos < size; block_count++) {
  3970. int in_ret, out_ret;
  3971. if (in_pos + in.bsz > size) {
  3972. in_ret = blk_pread(blk1, in_pos, in.buf, size - in_pos);
  3973. } else {
  3974. in_ret = blk_pread(blk1, in_pos, in.buf, in.bsz);
  3975. }
  3976. if (in_ret < 0) {
  3977. error_report("error while reading from input image file: %s",
  3978. strerror(-in_ret));
  3979. ret = -1;
  3980. goto out;
  3981. }
  3982. in_pos += in_ret;
  3983. out_ret = blk_pwrite(blk2, out_pos, in.buf, in_ret, 0);
  3984. if (out_ret < 0) {
  3985. error_report("error while writing to output image file: %s",
  3986. strerror(-out_ret));
  3987. ret = -1;
  3988. goto out;
  3989. }
  3990. out_pos += out_ret;
  3991. }
  3992. out:
  3993. g_free(arg);
  3994. qemu_opts_del(opts);
  3995. qemu_opts_free(create_opts);
  3996. blk_unref(blk1);
  3997. blk_unref(blk2);
  3998. g_free(in.filename);
  3999. g_free(out.filename);
  4000. g_free(in.buf);
  4001. g_free(out.buf);
  4002. if (ret) {
  4003. return 1;
  4004. }
  4005. return 0;
  4006. }
  4007. static void dump_json_block_measure_info(BlockMeasureInfo *info)
  4008. {
  4009. QString *str;
  4010. QObject *obj;
  4011. Visitor *v = qobject_output_visitor_new(&obj);
  4012. visit_type_BlockMeasureInfo(v, NULL, &info, &error_abort);
  4013. visit_complete(v, &obj);
  4014. str = qobject_to_json_pretty(obj);
  4015. assert(str != NULL);
  4016. printf("%s\n", qstring_get_str(str));
  4017. qobject_decref(obj);
  4018. visit_free(v);
  4019. QDECREF(str);
  4020. }
  4021. static int img_measure(int argc, char **argv)
  4022. {
  4023. static const struct option long_options[] = {
  4024. {"help", no_argument, 0, 'h'},
  4025. {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
  4026. {"object", required_argument, 0, OPTION_OBJECT},
  4027. {"output", required_argument, 0, OPTION_OUTPUT},
  4028. {"size", required_argument, 0, OPTION_SIZE},
  4029. {"force-share", no_argument, 0, 'U'},
  4030. {0, 0, 0, 0}
  4031. };
  4032. OutputFormat output_format = OFORMAT_HUMAN;
  4033. BlockBackend *in_blk = NULL;
  4034. BlockDriver *drv;
  4035. const char *filename = NULL;
  4036. const char *fmt = NULL;
  4037. const char *out_fmt = "raw";
  4038. char *options = NULL;
  4039. char *snapshot_name = NULL;
  4040. bool force_share = false;
  4041. QemuOpts *opts = NULL;
  4042. QemuOpts *object_opts = NULL;
  4043. QemuOpts *sn_opts = NULL;
  4044. QemuOptsList *create_opts = NULL;
  4045. bool image_opts = false;
  4046. uint64_t img_size = UINT64_MAX;
  4047. BlockMeasureInfo *info = NULL;
  4048. Error *local_err = NULL;
  4049. int ret = 1;
  4050. int c;
  4051. while ((c = getopt_long(argc, argv, "hf:O:o:l:U",
  4052. long_options, NULL)) != -1) {
  4053. switch (c) {
  4054. case '?':
  4055. case 'h':
  4056. help();
  4057. break;
  4058. case 'f':
  4059. fmt = optarg;
  4060. break;
  4061. case 'O':
  4062. out_fmt = optarg;
  4063. break;
  4064. case 'o':
  4065. if (!is_valid_option_list(optarg)) {
  4066. error_report("Invalid option list: %s", optarg);
  4067. goto out;
  4068. }
  4069. if (!options) {
  4070. options = g_strdup(optarg);
  4071. } else {
  4072. char *old_options = options;
  4073. options = g_strdup_printf("%s,%s", options, optarg);
  4074. g_free(old_options);
  4075. }
  4076. break;
  4077. case 'l':
  4078. if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
  4079. sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
  4080. optarg, false);
  4081. if (!sn_opts) {
  4082. error_report("Failed in parsing snapshot param '%s'",
  4083. optarg);
  4084. goto out;
  4085. }
  4086. } else {
  4087. snapshot_name = optarg;
  4088. }
  4089. break;
  4090. case 'U':
  4091. force_share = true;
  4092. break;
  4093. case OPTION_OBJECT:
  4094. object_opts = qemu_opts_parse_noisily(&qemu_object_opts,
  4095. optarg, true);
  4096. if (!object_opts) {
  4097. goto out;
  4098. }
  4099. break;
  4100. case OPTION_IMAGE_OPTS:
  4101. image_opts = true;
  4102. break;
  4103. case OPTION_OUTPUT:
  4104. if (!strcmp(optarg, "json")) {
  4105. output_format = OFORMAT_JSON;
  4106. } else if (!strcmp(optarg, "human")) {
  4107. output_format = OFORMAT_HUMAN;
  4108. } else {
  4109. error_report("--output must be used with human or json "
  4110. "as argument.");
  4111. goto out;
  4112. }
  4113. break;
  4114. case OPTION_SIZE:
  4115. {
  4116. int64_t sval;
  4117. sval = cvtnum(optarg);
  4118. if (sval < 0) {
  4119. if (sval == -ERANGE) {
  4120. error_report("Image size must be less than 8 EiB!");
  4121. } else {
  4122. error_report("Invalid image size specified! You may use "
  4123. "k, M, G, T, P or E suffixes for ");
  4124. error_report("kilobytes, megabytes, gigabytes, terabytes, "
  4125. "petabytes and exabytes.");
  4126. }
  4127. goto out;
  4128. }
  4129. img_size = (uint64_t)sval;
  4130. }
  4131. break;
  4132. }
  4133. }
  4134. if (qemu_opts_foreach(&qemu_object_opts,
  4135. user_creatable_add_opts_foreach,
  4136. NULL, NULL)) {
  4137. goto out;
  4138. }
  4139. if (argc - optind > 1) {
  4140. error_report("At most one filename argument is allowed.");
  4141. goto out;
  4142. } else if (argc - optind == 1) {
  4143. filename = argv[optind];
  4144. }
  4145. if (!filename &&
  4146. (object_opts || image_opts || fmt || snapshot_name || sn_opts)) {
  4147. error_report("--object, --image-opts, -f, and -l "
  4148. "require a filename argument.");
  4149. goto out;
  4150. }
  4151. if (filename && img_size != UINT64_MAX) {
  4152. error_report("--size N cannot be used together with a filename.");
  4153. goto out;
  4154. }
  4155. if (!filename && img_size == UINT64_MAX) {
  4156. error_report("Either --size N or one filename must be specified.");
  4157. goto out;
  4158. }
  4159. if (filename) {
  4160. in_blk = img_open(image_opts, filename, fmt, 0,
  4161. false, false, force_share);
  4162. if (!in_blk) {
  4163. goto out;
  4164. }
  4165. if (sn_opts) {
  4166. bdrv_snapshot_load_tmp(blk_bs(in_blk),
  4167. qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
  4168. qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
  4169. &local_err);
  4170. } else if (snapshot_name != NULL) {
  4171. bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(in_blk),
  4172. snapshot_name, &local_err);
  4173. }
  4174. if (local_err) {
  4175. error_reportf_err(local_err, "Failed to load snapshot: ");
  4176. goto out;
  4177. }
  4178. }
  4179. drv = bdrv_find_format(out_fmt);
  4180. if (!drv) {
  4181. error_report("Unknown file format '%s'", out_fmt);
  4182. goto out;
  4183. }
  4184. if (!drv->create_opts) {
  4185. error_report("Format driver '%s' does not support image creation",
  4186. drv->format_name);
  4187. goto out;
  4188. }
  4189. create_opts = qemu_opts_append(create_opts, drv->create_opts);
  4190. create_opts = qemu_opts_append(create_opts, bdrv_file.create_opts);
  4191. opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
  4192. if (options) {
  4193. qemu_opts_do_parse(opts, options, NULL, &local_err);
  4194. if (local_err) {
  4195. error_report_err(local_err);
  4196. error_report("Invalid options for file format '%s'", out_fmt);
  4197. goto out;
  4198. }
  4199. }
  4200. if (img_size != UINT64_MAX) {
  4201. qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
  4202. }
  4203. info = bdrv_measure(drv, opts, in_blk ? blk_bs(in_blk) : NULL, &local_err);
  4204. if (local_err) {
  4205. error_report_err(local_err);
  4206. goto out;
  4207. }
  4208. if (output_format == OFORMAT_HUMAN) {
  4209. printf("required size: %" PRIu64 "\n", info->required);
  4210. printf("fully allocated size: %" PRIu64 "\n", info->fully_allocated);
  4211. } else {
  4212. dump_json_block_measure_info(info);
  4213. }
  4214. ret = 0;
  4215. out:
  4216. qapi_free_BlockMeasureInfo(info);
  4217. qemu_opts_del(object_opts);
  4218. qemu_opts_del(opts);
  4219. qemu_opts_del(sn_opts);
  4220. qemu_opts_free(create_opts);
  4221. g_free(options);
  4222. blk_unref(in_blk);
  4223. return ret;
  4224. }
  4225. static const img_cmd_t img_cmds[] = {
  4226. #define DEF(option, callback, arg_string) \
  4227. { option, callback },
  4228. #include "qemu-img-cmds.h"
  4229. #undef DEF
  4230. #undef GEN_DOCS
  4231. { NULL, NULL, },
  4232. };
  4233. int main(int argc, char **argv)
  4234. {
  4235. const img_cmd_t *cmd;
  4236. const char *cmdname;
  4237. Error *local_error = NULL;
  4238. char *trace_file = NULL;
  4239. int c;
  4240. static const struct option long_options[] = {
  4241. {"help", no_argument, 0, 'h'},
  4242. {"version", no_argument, 0, 'V'},
  4243. {"trace", required_argument, NULL, 'T'},
  4244. {0, 0, 0, 0}
  4245. };
  4246. #ifdef CONFIG_POSIX
  4247. signal(SIGPIPE, SIG_IGN);
  4248. #endif
  4249. module_call_init(MODULE_INIT_TRACE);
  4250. error_set_progname(argv[0]);
  4251. qemu_init_exec_dir(argv[0]);
  4252. if (qemu_init_main_loop(&local_error)) {
  4253. error_report_err(local_error);
  4254. exit(EXIT_FAILURE);
  4255. }
  4256. qcrypto_init(&error_fatal);
  4257. module_call_init(MODULE_INIT_QOM);
  4258. bdrv_init();
  4259. if (argc < 2) {
  4260. error_exit("Not enough arguments");
  4261. }
  4262. qemu_add_opts(&qemu_object_opts);
  4263. qemu_add_opts(&qemu_source_opts);
  4264. qemu_add_opts(&qemu_trace_opts);
  4265. while ((c = getopt_long(argc, argv, "+:hVT:", long_options, NULL)) != -1) {
  4266. switch (c) {
  4267. case ':':
  4268. missing_argument(argv[optind - 1]);
  4269. return 0;
  4270. case '?':
  4271. unrecognized_option(argv[optind - 1]);
  4272. return 0;
  4273. case 'h':
  4274. help();
  4275. return 0;
  4276. case 'V':
  4277. printf(QEMU_IMG_VERSION);
  4278. return 0;
  4279. case 'T':
  4280. g_free(trace_file);
  4281. trace_file = trace_opt_parse(optarg);
  4282. break;
  4283. }
  4284. }
  4285. cmdname = argv[optind];
  4286. /* reset getopt_long scanning */
  4287. argc -= optind;
  4288. if (argc < 1) {
  4289. return 0;
  4290. }
  4291. argv += optind;
  4292. optind = 0;
  4293. if (!trace_init_backends()) {
  4294. exit(1);
  4295. }
  4296. trace_init_file(trace_file);
  4297. qemu_set_log(LOG_TRACE);
  4298. /* find the command */
  4299. for (cmd = img_cmds; cmd->name != NULL; cmd++) {
  4300. if (!strcmp(cmdname, cmd->name)) {
  4301. return cmd->handler(argc, argv);
  4302. }
  4303. }
  4304. /* not found */
  4305. error_exit("Command not found: %s", cmdname);
  4306. }