qemu-img.c 127 KB

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