2
0

qemu-img.c 162 KB

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