2
0

migration-rdma.c 105 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438
  1. /*
  2. * RDMA protocol and interfaces
  3. *
  4. * Copyright IBM, Corp. 2010-2013
  5. *
  6. * Authors:
  7. * Michael R. Hines <mrhines@us.ibm.com>
  8. * Jiuxing Liu <jl@us.ibm.com>
  9. *
  10. * This work is licensed under the terms of the GNU GPL, version 2 or
  11. * later. See the COPYING file in the top-level directory.
  12. *
  13. */
  14. #include "qemu-common.h"
  15. #include "migration/migration.h"
  16. #include "migration/qemu-file.h"
  17. #include "exec/cpu-common.h"
  18. #include "qemu/main-loop.h"
  19. #include "qemu/sockets.h"
  20. #include "qemu/bitmap.h"
  21. #include "block/coroutine.h"
  22. #include <stdio.h>
  23. #include <sys/types.h>
  24. #include <sys/socket.h>
  25. #include <netdb.h>
  26. #include <arpa/inet.h>
  27. #include <string.h>
  28. #include <rdma/rdma_cma.h>
  29. //#define DEBUG_RDMA
  30. //#define DEBUG_RDMA_VERBOSE
  31. //#define DEBUG_RDMA_REALLY_VERBOSE
  32. #ifdef DEBUG_RDMA
  33. #define DPRINTF(fmt, ...) \
  34. do { printf("rdma: " fmt, ## __VA_ARGS__); } while (0)
  35. #else
  36. #define DPRINTF(fmt, ...) \
  37. do { } while (0)
  38. #endif
  39. #ifdef DEBUG_RDMA_VERBOSE
  40. #define DDPRINTF(fmt, ...) \
  41. do { printf("rdma: " fmt, ## __VA_ARGS__); } while (0)
  42. #else
  43. #define DDPRINTF(fmt, ...) \
  44. do { } while (0)
  45. #endif
  46. #ifdef DEBUG_RDMA_REALLY_VERBOSE
  47. #define DDDPRINTF(fmt, ...) \
  48. do { printf("rdma: " fmt, ## __VA_ARGS__); } while (0)
  49. #else
  50. #define DDDPRINTF(fmt, ...) \
  51. do { } while (0)
  52. #endif
  53. /*
  54. * Print and error on both the Monitor and the Log file.
  55. */
  56. #define ERROR(errp, fmt, ...) \
  57. do { \
  58. fprintf(stderr, "RDMA ERROR: " fmt "\n", ## __VA_ARGS__); \
  59. if (errp && (*(errp) == NULL)) { \
  60. error_setg(errp, "RDMA ERROR: " fmt, ## __VA_ARGS__); \
  61. } \
  62. } while (0)
  63. #define RDMA_RESOLVE_TIMEOUT_MS 10000
  64. /* Do not merge data if larger than this. */
  65. #define RDMA_MERGE_MAX (2 * 1024 * 1024)
  66. #define RDMA_SIGNALED_SEND_MAX (RDMA_MERGE_MAX / 4096)
  67. #define RDMA_REG_CHUNK_SHIFT 20 /* 1 MB */
  68. /*
  69. * This is only for non-live state being migrated.
  70. * Instead of RDMA_WRITE messages, we use RDMA_SEND
  71. * messages for that state, which requires a different
  72. * delivery design than main memory.
  73. */
  74. #define RDMA_SEND_INCREMENT 32768
  75. /*
  76. * Maximum size infiniband SEND message
  77. */
  78. #define RDMA_CONTROL_MAX_BUFFER (512 * 1024)
  79. #define RDMA_CONTROL_MAX_COMMANDS_PER_MESSAGE 4096
  80. #define RDMA_CONTROL_VERSION_CURRENT 1
  81. /*
  82. * Capabilities for negotiation.
  83. */
  84. #define RDMA_CAPABILITY_PIN_ALL 0x01
  85. /*
  86. * Add the other flags above to this list of known capabilities
  87. * as they are introduced.
  88. */
  89. static uint32_t known_capabilities = RDMA_CAPABILITY_PIN_ALL;
  90. #define CHECK_ERROR_STATE() \
  91. do { \
  92. if (rdma->error_state) { \
  93. if (!rdma->error_reported) { \
  94. fprintf(stderr, "RDMA is in an error state waiting migration" \
  95. " to abort!\n"); \
  96. rdma->error_reported = 1; \
  97. } \
  98. return rdma->error_state; \
  99. } \
  100. } while (0);
  101. /*
  102. * A work request ID is 64-bits and we split up these bits
  103. * into 3 parts:
  104. *
  105. * bits 0-15 : type of control message, 2^16
  106. * bits 16-29: ram block index, 2^14
  107. * bits 30-63: ram block chunk number, 2^34
  108. *
  109. * The last two bit ranges are only used for RDMA writes,
  110. * in order to track their completion and potentially
  111. * also track unregistration status of the message.
  112. */
  113. #define RDMA_WRID_TYPE_SHIFT 0UL
  114. #define RDMA_WRID_BLOCK_SHIFT 16UL
  115. #define RDMA_WRID_CHUNK_SHIFT 30UL
  116. #define RDMA_WRID_TYPE_MASK \
  117. ((1UL << RDMA_WRID_BLOCK_SHIFT) - 1UL)
  118. #define RDMA_WRID_BLOCK_MASK \
  119. (~RDMA_WRID_TYPE_MASK & ((1UL << RDMA_WRID_CHUNK_SHIFT) - 1UL))
  120. #define RDMA_WRID_CHUNK_MASK (~RDMA_WRID_BLOCK_MASK & ~RDMA_WRID_TYPE_MASK)
  121. /*
  122. * RDMA migration protocol:
  123. * 1. RDMA Writes (data messages, i.e. RAM)
  124. * 2. IB Send/Recv (control channel messages)
  125. */
  126. enum {
  127. RDMA_WRID_NONE = 0,
  128. RDMA_WRID_RDMA_WRITE = 1,
  129. RDMA_WRID_SEND_CONTROL = 2000,
  130. RDMA_WRID_RECV_CONTROL = 4000,
  131. };
  132. const char *wrid_desc[] = {
  133. [RDMA_WRID_NONE] = "NONE",
  134. [RDMA_WRID_RDMA_WRITE] = "WRITE RDMA",
  135. [RDMA_WRID_SEND_CONTROL] = "CONTROL SEND",
  136. [RDMA_WRID_RECV_CONTROL] = "CONTROL RECV",
  137. };
  138. /*
  139. * Work request IDs for IB SEND messages only (not RDMA writes).
  140. * This is used by the migration protocol to transmit
  141. * control messages (such as device state and registration commands)
  142. *
  143. * We could use more WRs, but we have enough for now.
  144. */
  145. enum {
  146. RDMA_WRID_READY = 0,
  147. RDMA_WRID_DATA,
  148. RDMA_WRID_CONTROL,
  149. RDMA_WRID_MAX,
  150. };
  151. /*
  152. * SEND/RECV IB Control Messages.
  153. */
  154. enum {
  155. RDMA_CONTROL_NONE = 0,
  156. RDMA_CONTROL_ERROR,
  157. RDMA_CONTROL_READY, /* ready to receive */
  158. RDMA_CONTROL_QEMU_FILE, /* QEMUFile-transmitted bytes */
  159. RDMA_CONTROL_RAM_BLOCKS_REQUEST, /* RAMBlock synchronization */
  160. RDMA_CONTROL_RAM_BLOCKS_RESULT, /* RAMBlock synchronization */
  161. RDMA_CONTROL_COMPRESS, /* page contains repeat values */
  162. RDMA_CONTROL_REGISTER_REQUEST, /* dynamic page registration */
  163. RDMA_CONTROL_REGISTER_RESULT, /* key to use after registration */
  164. RDMA_CONTROL_REGISTER_FINISHED, /* current iteration finished */
  165. RDMA_CONTROL_UNREGISTER_REQUEST, /* dynamic UN-registration */
  166. RDMA_CONTROL_UNREGISTER_FINISHED, /* unpinning finished */
  167. };
  168. const char *control_desc[] = {
  169. [RDMA_CONTROL_NONE] = "NONE",
  170. [RDMA_CONTROL_ERROR] = "ERROR",
  171. [RDMA_CONTROL_READY] = "READY",
  172. [RDMA_CONTROL_QEMU_FILE] = "QEMU FILE",
  173. [RDMA_CONTROL_RAM_BLOCKS_REQUEST] = "RAM BLOCKS REQUEST",
  174. [RDMA_CONTROL_RAM_BLOCKS_RESULT] = "RAM BLOCKS RESULT",
  175. [RDMA_CONTROL_COMPRESS] = "COMPRESS",
  176. [RDMA_CONTROL_REGISTER_REQUEST] = "REGISTER REQUEST",
  177. [RDMA_CONTROL_REGISTER_RESULT] = "REGISTER RESULT",
  178. [RDMA_CONTROL_REGISTER_FINISHED] = "REGISTER FINISHED",
  179. [RDMA_CONTROL_UNREGISTER_REQUEST] = "UNREGISTER REQUEST",
  180. [RDMA_CONTROL_UNREGISTER_FINISHED] = "UNREGISTER FINISHED",
  181. };
  182. /*
  183. * Memory and MR structures used to represent an IB Send/Recv work request.
  184. * This is *not* used for RDMA writes, only IB Send/Recv.
  185. */
  186. typedef struct {
  187. uint8_t control[RDMA_CONTROL_MAX_BUFFER]; /* actual buffer to register */
  188. struct ibv_mr *control_mr; /* registration metadata */
  189. size_t control_len; /* length of the message */
  190. uint8_t *control_curr; /* start of unconsumed bytes */
  191. } RDMAWorkRequestData;
  192. /*
  193. * Negotiate RDMA capabilities during connection-setup time.
  194. */
  195. typedef struct {
  196. uint32_t version;
  197. uint32_t flags;
  198. } RDMACapabilities;
  199. static void caps_to_network(RDMACapabilities *cap)
  200. {
  201. cap->version = htonl(cap->version);
  202. cap->flags = htonl(cap->flags);
  203. }
  204. static void network_to_caps(RDMACapabilities *cap)
  205. {
  206. cap->version = ntohl(cap->version);
  207. cap->flags = ntohl(cap->flags);
  208. }
  209. /*
  210. * Representation of a RAMBlock from an RDMA perspective.
  211. * This is not transmitted, only local.
  212. * This and subsequent structures cannot be linked lists
  213. * because we're using a single IB message to transmit
  214. * the information. It's small anyway, so a list is overkill.
  215. */
  216. typedef struct RDMALocalBlock {
  217. uint8_t *local_host_addr; /* local virtual address */
  218. uint64_t remote_host_addr; /* remote virtual address */
  219. uint64_t offset;
  220. uint64_t length;
  221. struct ibv_mr **pmr; /* MRs for chunk-level registration */
  222. struct ibv_mr *mr; /* MR for non-chunk-level registration */
  223. uint32_t *remote_keys; /* rkeys for chunk-level registration */
  224. uint32_t remote_rkey; /* rkeys for non-chunk-level registration */
  225. int index; /* which block are we */
  226. bool is_ram_block;
  227. int nb_chunks;
  228. unsigned long *transit_bitmap;
  229. unsigned long *unregister_bitmap;
  230. } RDMALocalBlock;
  231. /*
  232. * Also represents a RAMblock, but only on the dest.
  233. * This gets transmitted by the dest during connection-time
  234. * to the source VM and then is used to populate the
  235. * corresponding RDMALocalBlock with
  236. * the information needed to perform the actual RDMA.
  237. */
  238. typedef struct QEMU_PACKED RDMARemoteBlock {
  239. uint64_t remote_host_addr;
  240. uint64_t offset;
  241. uint64_t length;
  242. uint32_t remote_rkey;
  243. uint32_t padding;
  244. } RDMARemoteBlock;
  245. static uint64_t htonll(uint64_t v)
  246. {
  247. union { uint32_t lv[2]; uint64_t llv; } u;
  248. u.lv[0] = htonl(v >> 32);
  249. u.lv[1] = htonl(v & 0xFFFFFFFFULL);
  250. return u.llv;
  251. }
  252. static uint64_t ntohll(uint64_t v) {
  253. union { uint32_t lv[2]; uint64_t llv; } u;
  254. u.llv = v;
  255. return ((uint64_t)ntohl(u.lv[0]) << 32) | (uint64_t) ntohl(u.lv[1]);
  256. }
  257. static void remote_block_to_network(RDMARemoteBlock *rb)
  258. {
  259. rb->remote_host_addr = htonll(rb->remote_host_addr);
  260. rb->offset = htonll(rb->offset);
  261. rb->length = htonll(rb->length);
  262. rb->remote_rkey = htonl(rb->remote_rkey);
  263. }
  264. static void network_to_remote_block(RDMARemoteBlock *rb)
  265. {
  266. rb->remote_host_addr = ntohll(rb->remote_host_addr);
  267. rb->offset = ntohll(rb->offset);
  268. rb->length = ntohll(rb->length);
  269. rb->remote_rkey = ntohl(rb->remote_rkey);
  270. }
  271. /*
  272. * Virtual address of the above structures used for transmitting
  273. * the RAMBlock descriptions at connection-time.
  274. * This structure is *not* transmitted.
  275. */
  276. typedef struct RDMALocalBlocks {
  277. int nb_blocks;
  278. bool init; /* main memory init complete */
  279. RDMALocalBlock *block;
  280. } RDMALocalBlocks;
  281. /*
  282. * Main data structure for RDMA state.
  283. * While there is only one copy of this structure being allocated right now,
  284. * this is the place where one would start if you wanted to consider
  285. * having more than one RDMA connection open at the same time.
  286. */
  287. typedef struct RDMAContext {
  288. char *host;
  289. int port;
  290. RDMAWorkRequestData wr_data[RDMA_WRID_MAX];
  291. /*
  292. * This is used by *_exchange_send() to figure out whether or not
  293. * the initial "READY" message has already been received or not.
  294. * This is because other functions may potentially poll() and detect
  295. * the READY message before send() does, in which case we need to
  296. * know if it completed.
  297. */
  298. int control_ready_expected;
  299. /* number of outstanding writes */
  300. int nb_sent;
  301. /* store info about current buffer so that we can
  302. merge it with future sends */
  303. uint64_t current_addr;
  304. uint64_t current_length;
  305. /* index of ram block the current buffer belongs to */
  306. int current_index;
  307. /* index of the chunk in the current ram block */
  308. int current_chunk;
  309. bool pin_all;
  310. /*
  311. * infiniband-specific variables for opening the device
  312. * and maintaining connection state and so forth.
  313. *
  314. * cm_id also has ibv_context, rdma_event_channel, and ibv_qp in
  315. * cm_id->verbs, cm_id->channel, and cm_id->qp.
  316. */
  317. struct rdma_cm_id *cm_id; /* connection manager ID */
  318. struct rdma_cm_id *listen_id;
  319. bool connected;
  320. struct ibv_context *verbs;
  321. struct rdma_event_channel *channel;
  322. struct ibv_qp *qp; /* queue pair */
  323. struct ibv_comp_channel *comp_channel; /* completion channel */
  324. struct ibv_pd *pd; /* protection domain */
  325. struct ibv_cq *cq; /* completion queue */
  326. /*
  327. * If a previous write failed (perhaps because of a failed
  328. * memory registration, then do not attempt any future work
  329. * and remember the error state.
  330. */
  331. int error_state;
  332. int error_reported;
  333. /*
  334. * Description of ram blocks used throughout the code.
  335. */
  336. RDMALocalBlocks local_ram_blocks;
  337. RDMARemoteBlock *block;
  338. /*
  339. * Migration on *destination* started.
  340. * Then use coroutine yield function.
  341. * Source runs in a thread, so we don't care.
  342. */
  343. int migration_started_on_destination;
  344. int total_registrations;
  345. int total_writes;
  346. int unregister_current, unregister_next;
  347. uint64_t unregistrations[RDMA_SIGNALED_SEND_MAX];
  348. GHashTable *blockmap;
  349. } RDMAContext;
  350. /*
  351. * Interface to the rest of the migration call stack.
  352. */
  353. typedef struct QEMUFileRDMA {
  354. RDMAContext *rdma;
  355. size_t len;
  356. void *file;
  357. } QEMUFileRDMA;
  358. /*
  359. * Main structure for IB Send/Recv control messages.
  360. * This gets prepended at the beginning of every Send/Recv.
  361. */
  362. typedef struct QEMU_PACKED {
  363. uint32_t len; /* Total length of data portion */
  364. uint32_t type; /* which control command to perform */
  365. uint32_t repeat; /* number of commands in data portion of same type */
  366. uint32_t padding;
  367. } RDMAControlHeader;
  368. static void control_to_network(RDMAControlHeader *control)
  369. {
  370. control->type = htonl(control->type);
  371. control->len = htonl(control->len);
  372. control->repeat = htonl(control->repeat);
  373. }
  374. static void network_to_control(RDMAControlHeader *control)
  375. {
  376. control->type = ntohl(control->type);
  377. control->len = ntohl(control->len);
  378. control->repeat = ntohl(control->repeat);
  379. }
  380. /*
  381. * Register a single Chunk.
  382. * Information sent by the source VM to inform the dest
  383. * to register an single chunk of memory before we can perform
  384. * the actual RDMA operation.
  385. */
  386. typedef struct QEMU_PACKED {
  387. union QEMU_PACKED {
  388. uint64_t current_addr; /* offset into the ramblock of the chunk */
  389. uint64_t chunk; /* chunk to lookup if unregistering */
  390. } key;
  391. uint32_t current_index; /* which ramblock the chunk belongs to */
  392. uint32_t padding;
  393. uint64_t chunks; /* how many sequential chunks to register */
  394. } RDMARegister;
  395. static void register_to_network(RDMARegister *reg)
  396. {
  397. reg->key.current_addr = htonll(reg->key.current_addr);
  398. reg->current_index = htonl(reg->current_index);
  399. reg->chunks = htonll(reg->chunks);
  400. }
  401. static void network_to_register(RDMARegister *reg)
  402. {
  403. reg->key.current_addr = ntohll(reg->key.current_addr);
  404. reg->current_index = ntohl(reg->current_index);
  405. reg->chunks = ntohll(reg->chunks);
  406. }
  407. typedef struct QEMU_PACKED {
  408. uint32_t value; /* if zero, we will madvise() */
  409. uint32_t block_idx; /* which ram block index */
  410. uint64_t offset; /* where in the remote ramblock this chunk */
  411. uint64_t length; /* length of the chunk */
  412. } RDMACompress;
  413. static void compress_to_network(RDMACompress *comp)
  414. {
  415. comp->value = htonl(comp->value);
  416. comp->block_idx = htonl(comp->block_idx);
  417. comp->offset = htonll(comp->offset);
  418. comp->length = htonll(comp->length);
  419. }
  420. static void network_to_compress(RDMACompress *comp)
  421. {
  422. comp->value = ntohl(comp->value);
  423. comp->block_idx = ntohl(comp->block_idx);
  424. comp->offset = ntohll(comp->offset);
  425. comp->length = ntohll(comp->length);
  426. }
  427. /*
  428. * The result of the dest's memory registration produces an "rkey"
  429. * which the source VM must reference in order to perform
  430. * the RDMA operation.
  431. */
  432. typedef struct QEMU_PACKED {
  433. uint32_t rkey;
  434. uint32_t padding;
  435. uint64_t host_addr;
  436. } RDMARegisterResult;
  437. static void result_to_network(RDMARegisterResult *result)
  438. {
  439. result->rkey = htonl(result->rkey);
  440. result->host_addr = htonll(result->host_addr);
  441. };
  442. static void network_to_result(RDMARegisterResult *result)
  443. {
  444. result->rkey = ntohl(result->rkey);
  445. result->host_addr = ntohll(result->host_addr);
  446. };
  447. const char *print_wrid(int wrid);
  448. static int qemu_rdma_exchange_send(RDMAContext *rdma, RDMAControlHeader *head,
  449. uint8_t *data, RDMAControlHeader *resp,
  450. int *resp_idx,
  451. int (*callback)(RDMAContext *rdma));
  452. static inline uint64_t ram_chunk_index(const uint8_t *start,
  453. const uint8_t *host)
  454. {
  455. return ((uintptr_t) host - (uintptr_t) start) >> RDMA_REG_CHUNK_SHIFT;
  456. }
  457. static inline uint8_t *ram_chunk_start(const RDMALocalBlock *rdma_ram_block,
  458. uint64_t i)
  459. {
  460. return (uint8_t *) (((uintptr_t) rdma_ram_block->local_host_addr)
  461. + (i << RDMA_REG_CHUNK_SHIFT));
  462. }
  463. static inline uint8_t *ram_chunk_end(const RDMALocalBlock *rdma_ram_block,
  464. uint64_t i)
  465. {
  466. uint8_t *result = ram_chunk_start(rdma_ram_block, i) +
  467. (1UL << RDMA_REG_CHUNK_SHIFT);
  468. if (result > (rdma_ram_block->local_host_addr + rdma_ram_block->length)) {
  469. result = rdma_ram_block->local_host_addr + rdma_ram_block->length;
  470. }
  471. return result;
  472. }
  473. static int __qemu_rdma_add_block(RDMAContext *rdma, void *host_addr,
  474. ram_addr_t block_offset, uint64_t length)
  475. {
  476. RDMALocalBlocks *local = &rdma->local_ram_blocks;
  477. RDMALocalBlock *block = g_hash_table_lookup(rdma->blockmap,
  478. (void *) block_offset);
  479. RDMALocalBlock *old = local->block;
  480. assert(block == NULL);
  481. local->block = g_malloc0(sizeof(RDMALocalBlock) * (local->nb_blocks + 1));
  482. if (local->nb_blocks) {
  483. int x;
  484. for (x = 0; x < local->nb_blocks; x++) {
  485. g_hash_table_remove(rdma->blockmap, (void *)old[x].offset);
  486. g_hash_table_insert(rdma->blockmap, (void *)old[x].offset,
  487. &local->block[x]);
  488. }
  489. memcpy(local->block, old, sizeof(RDMALocalBlock) * local->nb_blocks);
  490. g_free(old);
  491. }
  492. block = &local->block[local->nb_blocks];
  493. block->local_host_addr = host_addr;
  494. block->offset = block_offset;
  495. block->length = length;
  496. block->index = local->nb_blocks;
  497. block->nb_chunks = ram_chunk_index(host_addr, host_addr + length) + 1UL;
  498. block->transit_bitmap = bitmap_new(block->nb_chunks);
  499. bitmap_clear(block->transit_bitmap, 0, block->nb_chunks);
  500. block->unregister_bitmap = bitmap_new(block->nb_chunks);
  501. bitmap_clear(block->unregister_bitmap, 0, block->nb_chunks);
  502. block->remote_keys = g_malloc0(block->nb_chunks * sizeof(uint32_t));
  503. block->is_ram_block = local->init ? false : true;
  504. g_hash_table_insert(rdma->blockmap, (void *) block_offset, block);
  505. DDPRINTF("Added Block: %d, addr: %" PRIu64 ", offset: %" PRIu64
  506. " length: %" PRIu64 " end: %" PRIu64 " bits %" PRIu64 " chunks %d\n",
  507. local->nb_blocks, (uint64_t) block->local_host_addr, block->offset,
  508. block->length, (uint64_t) (block->local_host_addr + block->length),
  509. BITS_TO_LONGS(block->nb_chunks) *
  510. sizeof(unsigned long) * 8, block->nb_chunks);
  511. local->nb_blocks++;
  512. return 0;
  513. }
  514. /*
  515. * Memory regions need to be registered with the device and queue pairs setup
  516. * in advanced before the migration starts. This tells us where the RAM blocks
  517. * are so that we can register them individually.
  518. */
  519. static void qemu_rdma_init_one_block(void *host_addr,
  520. ram_addr_t block_offset, ram_addr_t length, void *opaque)
  521. {
  522. __qemu_rdma_add_block(opaque, host_addr, block_offset, length);
  523. }
  524. /*
  525. * Identify the RAMBlocks and their quantity. They will be references to
  526. * identify chunk boundaries inside each RAMBlock and also be referenced
  527. * during dynamic page registration.
  528. */
  529. static int qemu_rdma_init_ram_blocks(RDMAContext *rdma)
  530. {
  531. RDMALocalBlocks *local = &rdma->local_ram_blocks;
  532. assert(rdma->blockmap == NULL);
  533. rdma->blockmap = g_hash_table_new(g_direct_hash, g_direct_equal);
  534. memset(local, 0, sizeof *local);
  535. qemu_ram_foreach_block(qemu_rdma_init_one_block, rdma);
  536. DPRINTF("Allocated %d local ram block structures\n", local->nb_blocks);
  537. rdma->block = (RDMARemoteBlock *) g_malloc0(sizeof(RDMARemoteBlock) *
  538. rdma->local_ram_blocks.nb_blocks);
  539. local->init = true;
  540. return 0;
  541. }
  542. static int __qemu_rdma_delete_block(RDMAContext *rdma, ram_addr_t block_offset)
  543. {
  544. RDMALocalBlocks *local = &rdma->local_ram_blocks;
  545. RDMALocalBlock *block = g_hash_table_lookup(rdma->blockmap,
  546. (void *) block_offset);
  547. RDMALocalBlock *old = local->block;
  548. int x;
  549. assert(block);
  550. if (block->pmr) {
  551. int j;
  552. for (j = 0; j < block->nb_chunks; j++) {
  553. if (!block->pmr[j]) {
  554. continue;
  555. }
  556. ibv_dereg_mr(block->pmr[j]);
  557. rdma->total_registrations--;
  558. }
  559. g_free(block->pmr);
  560. block->pmr = NULL;
  561. }
  562. if (block->mr) {
  563. ibv_dereg_mr(block->mr);
  564. rdma->total_registrations--;
  565. block->mr = NULL;
  566. }
  567. g_free(block->transit_bitmap);
  568. block->transit_bitmap = NULL;
  569. g_free(block->unregister_bitmap);
  570. block->unregister_bitmap = NULL;
  571. g_free(block->remote_keys);
  572. block->remote_keys = NULL;
  573. for (x = 0; x < local->nb_blocks; x++) {
  574. g_hash_table_remove(rdma->blockmap, (void *)old[x].offset);
  575. }
  576. if (local->nb_blocks > 1) {
  577. local->block = g_malloc0(sizeof(RDMALocalBlock) *
  578. (local->nb_blocks - 1));
  579. if (block->index) {
  580. memcpy(local->block, old, sizeof(RDMALocalBlock) * block->index);
  581. }
  582. if (block->index < (local->nb_blocks - 1)) {
  583. memcpy(local->block + block->index, old + (block->index + 1),
  584. sizeof(RDMALocalBlock) *
  585. (local->nb_blocks - (block->index + 1)));
  586. }
  587. } else {
  588. assert(block == local->block);
  589. local->block = NULL;
  590. }
  591. DDPRINTF("Deleted Block: %d, addr: %" PRIu64 ", offset: %" PRIu64
  592. " length: %" PRIu64 " end: %" PRIu64 " bits %" PRIu64 " chunks %d\n",
  593. local->nb_blocks, (uint64_t) block->local_host_addr, block->offset,
  594. block->length, (uint64_t) (block->local_host_addr + block->length),
  595. BITS_TO_LONGS(block->nb_chunks) *
  596. sizeof(unsigned long) * 8, block->nb_chunks);
  597. g_free(old);
  598. local->nb_blocks--;
  599. if (local->nb_blocks) {
  600. for (x = 0; x < local->nb_blocks; x++) {
  601. g_hash_table_insert(rdma->blockmap, (void *)local->block[x].offset,
  602. &local->block[x]);
  603. }
  604. }
  605. return 0;
  606. }
  607. /*
  608. * Put in the log file which RDMA device was opened and the details
  609. * associated with that device.
  610. */
  611. static void qemu_rdma_dump_id(const char *who, struct ibv_context *verbs)
  612. {
  613. struct ibv_port_attr port;
  614. if (ibv_query_port(verbs, 1, &port)) {
  615. fprintf(stderr, "FAILED TO QUERY PORT INFORMATION!\n");
  616. return;
  617. }
  618. printf("%s RDMA Device opened: kernel name %s "
  619. "uverbs device name %s, "
  620. "infiniband_verbs class device path %s, "
  621. "infiniband class device path %s, "
  622. "transport: (%d) %s\n",
  623. who,
  624. verbs->device->name,
  625. verbs->device->dev_name,
  626. verbs->device->dev_path,
  627. verbs->device->ibdev_path,
  628. port.link_layer,
  629. (port.link_layer == IBV_LINK_LAYER_INFINIBAND) ? "Infiniband" :
  630. ((port.link_layer == IBV_LINK_LAYER_ETHERNET)
  631. ? "Ethernet" : "Unknown"));
  632. }
  633. /*
  634. * Put in the log file the RDMA gid addressing information,
  635. * useful for folks who have trouble understanding the
  636. * RDMA device hierarchy in the kernel.
  637. */
  638. static void qemu_rdma_dump_gid(const char *who, struct rdma_cm_id *id)
  639. {
  640. char sgid[33];
  641. char dgid[33];
  642. inet_ntop(AF_INET6, &id->route.addr.addr.ibaddr.sgid, sgid, sizeof sgid);
  643. inet_ntop(AF_INET6, &id->route.addr.addr.ibaddr.dgid, dgid, sizeof dgid);
  644. DPRINTF("%s Source GID: %s, Dest GID: %s\n", who, sgid, dgid);
  645. }
  646. /*
  647. * As of now, IPv6 over RoCE / iWARP is not supported by linux.
  648. * We will try the next addrinfo struct, and fail if there are
  649. * no other valid addresses to bind against.
  650. *
  651. * If user is listening on '[::]', then we will not have a opened a device
  652. * yet and have no way of verifying if the device is RoCE or not.
  653. *
  654. * In this case, the source VM will throw an error for ALL types of
  655. * connections (both IPv4 and IPv6) if the destination machine does not have
  656. * a regular infiniband network available for use.
  657. *
  658. * The only way to guarantee that an error is thrown for broken kernels is
  659. * for the management software to choose a *specific* interface at bind time
  660. * and validate what time of hardware it is.
  661. *
  662. * Unfortunately, this puts the user in a fix:
  663. *
  664. * If the source VM connects with an IPv4 address without knowing that the
  665. * destination has bound to '[::]' the migration will unconditionally fail
  666. * unless the management software is explicitly listening on the the IPv4
  667. * address while using a RoCE-based device.
  668. *
  669. * If the source VM connects with an IPv6 address, then we're OK because we can
  670. * throw an error on the source (and similarly on the destination).
  671. *
  672. * But in mixed environments, this will be broken for a while until it is fixed
  673. * inside linux.
  674. *
  675. * We do provide a *tiny* bit of help in this function: We can list all of the
  676. * devices in the system and check to see if all the devices are RoCE or
  677. * Infiniband.
  678. *
  679. * If we detect that we have a *pure* RoCE environment, then we can safely
  680. * thrown an error even if the management software has specified '[::]' as the
  681. * bind address.
  682. *
  683. * However, if there is are multiple hetergeneous devices, then we cannot make
  684. * this assumption and the user just has to be sure they know what they are
  685. * doing.
  686. *
  687. * Patches are being reviewed on linux-rdma.
  688. */
  689. static int qemu_rdma_broken_ipv6_kernel(Error **errp, struct ibv_context *verbs)
  690. {
  691. struct ibv_port_attr port_attr;
  692. /* This bug only exists in linux, to our knowledge. */
  693. #ifdef CONFIG_LINUX
  694. /*
  695. * Verbs are only NULL if management has bound to '[::]'.
  696. *
  697. * Let's iterate through all the devices and see if there any pure IB
  698. * devices (non-ethernet).
  699. *
  700. * If not, then we can safely proceed with the migration.
  701. * Otherwise, there are no guarantees until the bug is fixed in linux.
  702. */
  703. if (!verbs) {
  704. int num_devices, x;
  705. struct ibv_device ** dev_list = ibv_get_device_list(&num_devices);
  706. bool roce_found = false;
  707. bool ib_found = false;
  708. for (x = 0; x < num_devices; x++) {
  709. verbs = ibv_open_device(dev_list[x]);
  710. if (ibv_query_port(verbs, 1, &port_attr)) {
  711. ibv_close_device(verbs);
  712. ERROR(errp, "Could not query initial IB port");
  713. return -EINVAL;
  714. }
  715. if (port_attr.link_layer == IBV_LINK_LAYER_INFINIBAND) {
  716. ib_found = true;
  717. } else if (port_attr.link_layer == IBV_LINK_LAYER_ETHERNET) {
  718. roce_found = true;
  719. }
  720. ibv_close_device(verbs);
  721. }
  722. if (roce_found) {
  723. if (ib_found) {
  724. fprintf(stderr, "WARN: migrations may fail:"
  725. " IPv6 over RoCE / iWARP in linux"
  726. " is broken. But since you appear to have a"
  727. " mixed RoCE / IB environment, be sure to only"
  728. " migrate over the IB fabric until the kernel "
  729. " fixes the bug.\n");
  730. } else {
  731. ERROR(errp, "You only have RoCE / iWARP devices in your systems"
  732. " and your management software has specified '[::]'"
  733. ", but IPv6 over RoCE / iWARP is not supported in Linux.");
  734. return -ENONET;
  735. }
  736. }
  737. return 0;
  738. }
  739. /*
  740. * If we have a verbs context, that means that some other than '[::]' was
  741. * used by the management software for binding. In which case we can actually
  742. * warn the user about a potential broken kernel;
  743. */
  744. /* IB ports start with 1, not 0 */
  745. if (ibv_query_port(verbs, 1, &port_attr)) {
  746. ERROR(errp, "Could not query initial IB port");
  747. return -EINVAL;
  748. }
  749. if (port_attr.link_layer == IBV_LINK_LAYER_ETHERNET) {
  750. ERROR(errp, "Linux kernel's RoCE / iWARP does not support IPv6 "
  751. "(but patches on linux-rdma in progress)");
  752. return -ENONET;
  753. }
  754. #endif
  755. return 0;
  756. }
  757. /*
  758. * Figure out which RDMA device corresponds to the requested IP hostname
  759. * Also create the initial connection manager identifiers for opening
  760. * the connection.
  761. */
  762. static int qemu_rdma_resolve_host(RDMAContext *rdma, Error **errp)
  763. {
  764. int ret;
  765. struct rdma_addrinfo *res;
  766. char port_str[16];
  767. struct rdma_cm_event *cm_event;
  768. char ip[40] = "unknown";
  769. struct rdma_addrinfo *e;
  770. if (rdma->host == NULL || !strcmp(rdma->host, "")) {
  771. ERROR(errp, "RDMA hostname has not been set");
  772. return -EINVAL;
  773. }
  774. /* create CM channel */
  775. rdma->channel = rdma_create_event_channel();
  776. if (!rdma->channel) {
  777. ERROR(errp, "could not create CM channel");
  778. return -EINVAL;
  779. }
  780. /* create CM id */
  781. ret = rdma_create_id(rdma->channel, &rdma->cm_id, NULL, RDMA_PS_TCP);
  782. if (ret) {
  783. ERROR(errp, "could not create channel id");
  784. goto err_resolve_create_id;
  785. }
  786. snprintf(port_str, 16, "%d", rdma->port);
  787. port_str[15] = '\0';
  788. ret = rdma_getaddrinfo(rdma->host, port_str, NULL, &res);
  789. if (ret < 0) {
  790. ERROR(errp, "could not rdma_getaddrinfo address %s", rdma->host);
  791. goto err_resolve_get_addr;
  792. }
  793. for (e = res; e != NULL; e = e->ai_next) {
  794. inet_ntop(e->ai_family,
  795. &((struct sockaddr_in *) e->ai_dst_addr)->sin_addr, ip, sizeof ip);
  796. DPRINTF("Trying %s => %s\n", rdma->host, ip);
  797. ret = rdma_resolve_addr(rdma->cm_id, NULL, e->ai_dst_addr,
  798. RDMA_RESOLVE_TIMEOUT_MS);
  799. if (!ret) {
  800. if (e->ai_family == AF_INET6) {
  801. ret = qemu_rdma_broken_ipv6_kernel(errp, rdma->cm_id->verbs);
  802. if (ret) {
  803. continue;
  804. }
  805. }
  806. goto route;
  807. }
  808. }
  809. ERROR(errp, "could not resolve address %s", rdma->host);
  810. goto err_resolve_get_addr;
  811. route:
  812. qemu_rdma_dump_gid("source_resolve_addr", rdma->cm_id);
  813. ret = rdma_get_cm_event(rdma->channel, &cm_event);
  814. if (ret) {
  815. ERROR(errp, "could not perform event_addr_resolved");
  816. goto err_resolve_get_addr;
  817. }
  818. if (cm_event->event != RDMA_CM_EVENT_ADDR_RESOLVED) {
  819. ERROR(errp, "result not equal to event_addr_resolved %s",
  820. rdma_event_str(cm_event->event));
  821. perror("rdma_resolve_addr");
  822. rdma_ack_cm_event(cm_event);
  823. ret = -EINVAL;
  824. goto err_resolve_get_addr;
  825. }
  826. rdma_ack_cm_event(cm_event);
  827. /* resolve route */
  828. ret = rdma_resolve_route(rdma->cm_id, RDMA_RESOLVE_TIMEOUT_MS);
  829. if (ret) {
  830. ERROR(errp, "could not resolve rdma route");
  831. goto err_resolve_get_addr;
  832. }
  833. ret = rdma_get_cm_event(rdma->channel, &cm_event);
  834. if (ret) {
  835. ERROR(errp, "could not perform event_route_resolved");
  836. goto err_resolve_get_addr;
  837. }
  838. if (cm_event->event != RDMA_CM_EVENT_ROUTE_RESOLVED) {
  839. ERROR(errp, "result not equal to event_route_resolved: %s",
  840. rdma_event_str(cm_event->event));
  841. rdma_ack_cm_event(cm_event);
  842. ret = -EINVAL;
  843. goto err_resolve_get_addr;
  844. }
  845. rdma_ack_cm_event(cm_event);
  846. rdma->verbs = rdma->cm_id->verbs;
  847. qemu_rdma_dump_id("source_resolve_host", rdma->cm_id->verbs);
  848. qemu_rdma_dump_gid("source_resolve_host", rdma->cm_id);
  849. return 0;
  850. err_resolve_get_addr:
  851. rdma_destroy_id(rdma->cm_id);
  852. rdma->cm_id = NULL;
  853. err_resolve_create_id:
  854. rdma_destroy_event_channel(rdma->channel);
  855. rdma->channel = NULL;
  856. return ret;
  857. }
  858. /*
  859. * Create protection domain and completion queues
  860. */
  861. static int qemu_rdma_alloc_pd_cq(RDMAContext *rdma)
  862. {
  863. /* allocate pd */
  864. rdma->pd = ibv_alloc_pd(rdma->verbs);
  865. if (!rdma->pd) {
  866. fprintf(stderr, "failed to allocate protection domain\n");
  867. return -1;
  868. }
  869. /* create completion channel */
  870. rdma->comp_channel = ibv_create_comp_channel(rdma->verbs);
  871. if (!rdma->comp_channel) {
  872. fprintf(stderr, "failed to allocate completion channel\n");
  873. goto err_alloc_pd_cq;
  874. }
  875. /*
  876. * Completion queue can be filled by both read and write work requests,
  877. * so must reflect the sum of both possible queue sizes.
  878. */
  879. rdma->cq = ibv_create_cq(rdma->verbs, (RDMA_SIGNALED_SEND_MAX * 3),
  880. NULL, rdma->comp_channel, 0);
  881. if (!rdma->cq) {
  882. fprintf(stderr, "failed to allocate completion queue\n");
  883. goto err_alloc_pd_cq;
  884. }
  885. return 0;
  886. err_alloc_pd_cq:
  887. if (rdma->pd) {
  888. ibv_dealloc_pd(rdma->pd);
  889. }
  890. if (rdma->comp_channel) {
  891. ibv_destroy_comp_channel(rdma->comp_channel);
  892. }
  893. rdma->pd = NULL;
  894. rdma->comp_channel = NULL;
  895. return -1;
  896. }
  897. /*
  898. * Create queue pairs.
  899. */
  900. static int qemu_rdma_alloc_qp(RDMAContext *rdma)
  901. {
  902. struct ibv_qp_init_attr attr = { 0 };
  903. int ret;
  904. attr.cap.max_send_wr = RDMA_SIGNALED_SEND_MAX;
  905. attr.cap.max_recv_wr = 3;
  906. attr.cap.max_send_sge = 1;
  907. attr.cap.max_recv_sge = 1;
  908. attr.send_cq = rdma->cq;
  909. attr.recv_cq = rdma->cq;
  910. attr.qp_type = IBV_QPT_RC;
  911. ret = rdma_create_qp(rdma->cm_id, rdma->pd, &attr);
  912. if (ret) {
  913. return -1;
  914. }
  915. rdma->qp = rdma->cm_id->qp;
  916. return 0;
  917. }
  918. static int qemu_rdma_reg_whole_ram_blocks(RDMAContext *rdma)
  919. {
  920. int i;
  921. RDMALocalBlocks *local = &rdma->local_ram_blocks;
  922. for (i = 0; i < local->nb_blocks; i++) {
  923. local->block[i].mr =
  924. ibv_reg_mr(rdma->pd,
  925. local->block[i].local_host_addr,
  926. local->block[i].length,
  927. IBV_ACCESS_LOCAL_WRITE |
  928. IBV_ACCESS_REMOTE_WRITE
  929. );
  930. if (!local->block[i].mr) {
  931. perror("Failed to register local dest ram block!\n");
  932. break;
  933. }
  934. rdma->total_registrations++;
  935. }
  936. if (i >= local->nb_blocks) {
  937. return 0;
  938. }
  939. for (i--; i >= 0; i--) {
  940. ibv_dereg_mr(local->block[i].mr);
  941. rdma->total_registrations--;
  942. }
  943. return -1;
  944. }
  945. /*
  946. * Find the ram block that corresponds to the page requested to be
  947. * transmitted by QEMU.
  948. *
  949. * Once the block is found, also identify which 'chunk' within that
  950. * block that the page belongs to.
  951. *
  952. * This search cannot fail or the migration will fail.
  953. */
  954. static int qemu_rdma_search_ram_block(RDMAContext *rdma,
  955. uint64_t block_offset,
  956. uint64_t offset,
  957. uint64_t length,
  958. uint64_t *block_index,
  959. uint64_t *chunk_index)
  960. {
  961. uint64_t current_addr = block_offset + offset;
  962. RDMALocalBlock *block = g_hash_table_lookup(rdma->blockmap,
  963. (void *) block_offset);
  964. assert(block);
  965. assert(current_addr >= block->offset);
  966. assert((current_addr + length) <= (block->offset + block->length));
  967. *block_index = block->index;
  968. *chunk_index = ram_chunk_index(block->local_host_addr,
  969. block->local_host_addr + (current_addr - block->offset));
  970. return 0;
  971. }
  972. /*
  973. * Register a chunk with IB. If the chunk was already registered
  974. * previously, then skip.
  975. *
  976. * Also return the keys associated with the registration needed
  977. * to perform the actual RDMA operation.
  978. */
  979. static int qemu_rdma_register_and_get_keys(RDMAContext *rdma,
  980. RDMALocalBlock *block, uint8_t *host_addr,
  981. uint32_t *lkey, uint32_t *rkey, int chunk,
  982. uint8_t *chunk_start, uint8_t *chunk_end)
  983. {
  984. if (block->mr) {
  985. if (lkey) {
  986. *lkey = block->mr->lkey;
  987. }
  988. if (rkey) {
  989. *rkey = block->mr->rkey;
  990. }
  991. return 0;
  992. }
  993. /* allocate memory to store chunk MRs */
  994. if (!block->pmr) {
  995. block->pmr = g_malloc0(block->nb_chunks * sizeof(struct ibv_mr *));
  996. if (!block->pmr) {
  997. return -1;
  998. }
  999. }
  1000. /*
  1001. * If 'rkey', then we're the destination, so grant access to the source.
  1002. *
  1003. * If 'lkey', then we're the source VM, so grant access only to ourselves.
  1004. */
  1005. if (!block->pmr[chunk]) {
  1006. uint64_t len = chunk_end - chunk_start;
  1007. DDPRINTF("Registering %" PRIu64 " bytes @ %p\n",
  1008. len, chunk_start);
  1009. block->pmr[chunk] = ibv_reg_mr(rdma->pd,
  1010. chunk_start, len,
  1011. (rkey ? (IBV_ACCESS_LOCAL_WRITE |
  1012. IBV_ACCESS_REMOTE_WRITE) : 0));
  1013. if (!block->pmr[chunk]) {
  1014. perror("Failed to register chunk!");
  1015. fprintf(stderr, "Chunk details: block: %d chunk index %d"
  1016. " start %" PRIu64 " end %" PRIu64 " host %" PRIu64
  1017. " local %" PRIu64 " registrations: %d\n",
  1018. block->index, chunk, (uint64_t) chunk_start,
  1019. (uint64_t) chunk_end, (uint64_t) host_addr,
  1020. (uint64_t) block->local_host_addr,
  1021. rdma->total_registrations);
  1022. return -1;
  1023. }
  1024. rdma->total_registrations++;
  1025. }
  1026. if (lkey) {
  1027. *lkey = block->pmr[chunk]->lkey;
  1028. }
  1029. if (rkey) {
  1030. *rkey = block->pmr[chunk]->rkey;
  1031. }
  1032. return 0;
  1033. }
  1034. /*
  1035. * Register (at connection time) the memory used for control
  1036. * channel messages.
  1037. */
  1038. static int qemu_rdma_reg_control(RDMAContext *rdma, int idx)
  1039. {
  1040. rdma->wr_data[idx].control_mr = ibv_reg_mr(rdma->pd,
  1041. rdma->wr_data[idx].control, RDMA_CONTROL_MAX_BUFFER,
  1042. IBV_ACCESS_LOCAL_WRITE | IBV_ACCESS_REMOTE_WRITE);
  1043. if (rdma->wr_data[idx].control_mr) {
  1044. rdma->total_registrations++;
  1045. return 0;
  1046. }
  1047. fprintf(stderr, "qemu_rdma_reg_control failed!\n");
  1048. return -1;
  1049. }
  1050. const char *print_wrid(int wrid)
  1051. {
  1052. if (wrid >= RDMA_WRID_RECV_CONTROL) {
  1053. return wrid_desc[RDMA_WRID_RECV_CONTROL];
  1054. }
  1055. return wrid_desc[wrid];
  1056. }
  1057. /*
  1058. * RDMA requires memory registration (mlock/pinning), but this is not good for
  1059. * overcommitment.
  1060. *
  1061. * In preparation for the future where LRU information or workload-specific
  1062. * writable writable working set memory access behavior is available to QEMU
  1063. * it would be nice to have in place the ability to UN-register/UN-pin
  1064. * particular memory regions from the RDMA hardware when it is determine that
  1065. * those regions of memory will likely not be accessed again in the near future.
  1066. *
  1067. * While we do not yet have such information right now, the following
  1068. * compile-time option allows us to perform a non-optimized version of this
  1069. * behavior.
  1070. *
  1071. * By uncommenting this option, you will cause *all* RDMA transfers to be
  1072. * unregistered immediately after the transfer completes on both sides of the
  1073. * connection. This has no effect in 'rdma-pin-all' mode, only regular mode.
  1074. *
  1075. * This will have a terrible impact on migration performance, so until future
  1076. * workload information or LRU information is available, do not attempt to use
  1077. * this feature except for basic testing.
  1078. */
  1079. //#define RDMA_UNREGISTRATION_EXAMPLE
  1080. /*
  1081. * Perform a non-optimized memory unregistration after every transfer
  1082. * for demonsration purposes, only if pin-all is not requested.
  1083. *
  1084. * Potential optimizations:
  1085. * 1. Start a new thread to run this function continuously
  1086. - for bit clearing
  1087. - and for receipt of unregister messages
  1088. * 2. Use an LRU.
  1089. * 3. Use workload hints.
  1090. */
  1091. static int qemu_rdma_unregister_waiting(RDMAContext *rdma)
  1092. {
  1093. while (rdma->unregistrations[rdma->unregister_current]) {
  1094. int ret;
  1095. uint64_t wr_id = rdma->unregistrations[rdma->unregister_current];
  1096. uint64_t chunk =
  1097. (wr_id & RDMA_WRID_CHUNK_MASK) >> RDMA_WRID_CHUNK_SHIFT;
  1098. uint64_t index =
  1099. (wr_id & RDMA_WRID_BLOCK_MASK) >> RDMA_WRID_BLOCK_SHIFT;
  1100. RDMALocalBlock *block =
  1101. &(rdma->local_ram_blocks.block[index]);
  1102. RDMARegister reg = { .current_index = index };
  1103. RDMAControlHeader resp = { .type = RDMA_CONTROL_UNREGISTER_FINISHED,
  1104. };
  1105. RDMAControlHeader head = { .len = sizeof(RDMARegister),
  1106. .type = RDMA_CONTROL_UNREGISTER_REQUEST,
  1107. .repeat = 1,
  1108. };
  1109. DDPRINTF("Processing unregister for chunk: %" PRIu64
  1110. " at position %d\n", chunk, rdma->unregister_current);
  1111. rdma->unregistrations[rdma->unregister_current] = 0;
  1112. rdma->unregister_current++;
  1113. if (rdma->unregister_current == RDMA_SIGNALED_SEND_MAX) {
  1114. rdma->unregister_current = 0;
  1115. }
  1116. /*
  1117. * Unregistration is speculative (because migration is single-threaded
  1118. * and we cannot break the protocol's inifinband message ordering).
  1119. * Thus, if the memory is currently being used for transmission,
  1120. * then abort the attempt to unregister and try again
  1121. * later the next time a completion is received for this memory.
  1122. */
  1123. clear_bit(chunk, block->unregister_bitmap);
  1124. if (test_bit(chunk, block->transit_bitmap)) {
  1125. DDPRINTF("Cannot unregister inflight chunk: %" PRIu64 "\n", chunk);
  1126. continue;
  1127. }
  1128. DDPRINTF("Sending unregister for chunk: %" PRIu64 "\n", chunk);
  1129. ret = ibv_dereg_mr(block->pmr[chunk]);
  1130. block->pmr[chunk] = NULL;
  1131. block->remote_keys[chunk] = 0;
  1132. if (ret != 0) {
  1133. perror("unregistration chunk failed");
  1134. return -ret;
  1135. }
  1136. rdma->total_registrations--;
  1137. reg.key.chunk = chunk;
  1138. register_to_network(&reg);
  1139. ret = qemu_rdma_exchange_send(rdma, &head, (uint8_t *) &reg,
  1140. &resp, NULL, NULL);
  1141. if (ret < 0) {
  1142. return ret;
  1143. }
  1144. DDPRINTF("Unregister for chunk: %" PRIu64 " complete.\n", chunk);
  1145. }
  1146. return 0;
  1147. }
  1148. static uint64_t qemu_rdma_make_wrid(uint64_t wr_id, uint64_t index,
  1149. uint64_t chunk)
  1150. {
  1151. uint64_t result = wr_id & RDMA_WRID_TYPE_MASK;
  1152. result |= (index << RDMA_WRID_BLOCK_SHIFT);
  1153. result |= (chunk << RDMA_WRID_CHUNK_SHIFT);
  1154. return result;
  1155. }
  1156. /*
  1157. * Set bit for unregistration in the next iteration.
  1158. * We cannot transmit right here, but will unpin later.
  1159. */
  1160. static void qemu_rdma_signal_unregister(RDMAContext *rdma, uint64_t index,
  1161. uint64_t chunk, uint64_t wr_id)
  1162. {
  1163. if (rdma->unregistrations[rdma->unregister_next] != 0) {
  1164. fprintf(stderr, "rdma migration: queue is full!\n");
  1165. } else {
  1166. RDMALocalBlock *block = &(rdma->local_ram_blocks.block[index]);
  1167. if (!test_and_set_bit(chunk, block->unregister_bitmap)) {
  1168. DDPRINTF("Appending unregister chunk %" PRIu64
  1169. " at position %d\n", chunk, rdma->unregister_next);
  1170. rdma->unregistrations[rdma->unregister_next++] =
  1171. qemu_rdma_make_wrid(wr_id, index, chunk);
  1172. if (rdma->unregister_next == RDMA_SIGNALED_SEND_MAX) {
  1173. rdma->unregister_next = 0;
  1174. }
  1175. } else {
  1176. DDPRINTF("Unregister chunk %" PRIu64 " already in queue.\n",
  1177. chunk);
  1178. }
  1179. }
  1180. }
  1181. /*
  1182. * Consult the connection manager to see a work request
  1183. * (of any kind) has completed.
  1184. * Return the work request ID that completed.
  1185. */
  1186. static uint64_t qemu_rdma_poll(RDMAContext *rdma, uint64_t *wr_id_out,
  1187. uint32_t *byte_len)
  1188. {
  1189. int ret;
  1190. struct ibv_wc wc;
  1191. uint64_t wr_id;
  1192. ret = ibv_poll_cq(rdma->cq, 1, &wc);
  1193. if (!ret) {
  1194. *wr_id_out = RDMA_WRID_NONE;
  1195. return 0;
  1196. }
  1197. if (ret < 0) {
  1198. fprintf(stderr, "ibv_poll_cq return %d!\n", ret);
  1199. return ret;
  1200. }
  1201. wr_id = wc.wr_id & RDMA_WRID_TYPE_MASK;
  1202. if (wc.status != IBV_WC_SUCCESS) {
  1203. fprintf(stderr, "ibv_poll_cq wc.status=%d %s!\n",
  1204. wc.status, ibv_wc_status_str(wc.status));
  1205. fprintf(stderr, "ibv_poll_cq wrid=%s!\n", wrid_desc[wr_id]);
  1206. return -1;
  1207. }
  1208. if (rdma->control_ready_expected &&
  1209. (wr_id >= RDMA_WRID_RECV_CONTROL)) {
  1210. DDDPRINTF("completion %s #%" PRId64 " received (%" PRId64 ")"
  1211. " left %d\n", wrid_desc[RDMA_WRID_RECV_CONTROL],
  1212. wr_id - RDMA_WRID_RECV_CONTROL, wr_id, rdma->nb_sent);
  1213. rdma->control_ready_expected = 0;
  1214. }
  1215. if (wr_id == RDMA_WRID_RDMA_WRITE) {
  1216. uint64_t chunk =
  1217. (wc.wr_id & RDMA_WRID_CHUNK_MASK) >> RDMA_WRID_CHUNK_SHIFT;
  1218. uint64_t index =
  1219. (wc.wr_id & RDMA_WRID_BLOCK_MASK) >> RDMA_WRID_BLOCK_SHIFT;
  1220. RDMALocalBlock *block = &(rdma->local_ram_blocks.block[index]);
  1221. DDDPRINTF("completions %s (%" PRId64 ") left %d, "
  1222. "block %" PRIu64 ", chunk: %" PRIu64 " %p %p\n",
  1223. print_wrid(wr_id), wr_id, rdma->nb_sent, index, chunk,
  1224. block->local_host_addr, (void *)block->remote_host_addr);
  1225. clear_bit(chunk, block->transit_bitmap);
  1226. if (rdma->nb_sent > 0) {
  1227. rdma->nb_sent--;
  1228. }
  1229. if (!rdma->pin_all) {
  1230. /*
  1231. * FYI: If one wanted to signal a specific chunk to be unregistered
  1232. * using LRU or workload-specific information, this is the function
  1233. * you would call to do so. That chunk would then get asynchronously
  1234. * unregistered later.
  1235. */
  1236. #ifdef RDMA_UNREGISTRATION_EXAMPLE
  1237. qemu_rdma_signal_unregister(rdma, index, chunk, wc.wr_id);
  1238. #endif
  1239. }
  1240. } else {
  1241. DDDPRINTF("other completion %s (%" PRId64 ") received left %d\n",
  1242. print_wrid(wr_id), wr_id, rdma->nb_sent);
  1243. }
  1244. *wr_id_out = wc.wr_id;
  1245. if (byte_len) {
  1246. *byte_len = wc.byte_len;
  1247. }
  1248. return 0;
  1249. }
  1250. /*
  1251. * Block until the next work request has completed.
  1252. *
  1253. * First poll to see if a work request has already completed,
  1254. * otherwise block.
  1255. *
  1256. * If we encounter completed work requests for IDs other than
  1257. * the one we're interested in, then that's generally an error.
  1258. *
  1259. * The only exception is actual RDMA Write completions. These
  1260. * completions only need to be recorded, but do not actually
  1261. * need further processing.
  1262. */
  1263. static int qemu_rdma_block_for_wrid(RDMAContext *rdma, int wrid_requested,
  1264. uint32_t *byte_len)
  1265. {
  1266. int num_cq_events = 0, ret = 0;
  1267. struct ibv_cq *cq;
  1268. void *cq_ctx;
  1269. uint64_t wr_id = RDMA_WRID_NONE, wr_id_in;
  1270. if (ibv_req_notify_cq(rdma->cq, 0)) {
  1271. return -1;
  1272. }
  1273. /* poll cq first */
  1274. while (wr_id != wrid_requested) {
  1275. ret = qemu_rdma_poll(rdma, &wr_id_in, byte_len);
  1276. if (ret < 0) {
  1277. return ret;
  1278. }
  1279. wr_id = wr_id_in & RDMA_WRID_TYPE_MASK;
  1280. if (wr_id == RDMA_WRID_NONE) {
  1281. break;
  1282. }
  1283. if (wr_id != wrid_requested) {
  1284. DDDPRINTF("A Wanted wrid %s (%d) but got %s (%" PRIu64 ")\n",
  1285. print_wrid(wrid_requested),
  1286. wrid_requested, print_wrid(wr_id), wr_id);
  1287. }
  1288. }
  1289. if (wr_id == wrid_requested) {
  1290. return 0;
  1291. }
  1292. while (1) {
  1293. /*
  1294. * Coroutine doesn't start until process_incoming_migration()
  1295. * so don't yield unless we know we're running inside of a coroutine.
  1296. */
  1297. if (rdma->migration_started_on_destination) {
  1298. yield_until_fd_readable(rdma->comp_channel->fd);
  1299. }
  1300. if (ibv_get_cq_event(rdma->comp_channel, &cq, &cq_ctx)) {
  1301. perror("ibv_get_cq_event");
  1302. goto err_block_for_wrid;
  1303. }
  1304. num_cq_events++;
  1305. if (ibv_req_notify_cq(cq, 0)) {
  1306. goto err_block_for_wrid;
  1307. }
  1308. while (wr_id != wrid_requested) {
  1309. ret = qemu_rdma_poll(rdma, &wr_id_in, byte_len);
  1310. if (ret < 0) {
  1311. goto err_block_for_wrid;
  1312. }
  1313. wr_id = wr_id_in & RDMA_WRID_TYPE_MASK;
  1314. if (wr_id == RDMA_WRID_NONE) {
  1315. break;
  1316. }
  1317. if (wr_id != wrid_requested) {
  1318. DDDPRINTF("B Wanted wrid %s (%d) but got %s (%" PRIu64 ")\n",
  1319. print_wrid(wrid_requested), wrid_requested,
  1320. print_wrid(wr_id), wr_id);
  1321. }
  1322. }
  1323. if (wr_id == wrid_requested) {
  1324. goto success_block_for_wrid;
  1325. }
  1326. }
  1327. success_block_for_wrid:
  1328. if (num_cq_events) {
  1329. ibv_ack_cq_events(cq, num_cq_events);
  1330. }
  1331. return 0;
  1332. err_block_for_wrid:
  1333. if (num_cq_events) {
  1334. ibv_ack_cq_events(cq, num_cq_events);
  1335. }
  1336. return ret;
  1337. }
  1338. /*
  1339. * Post a SEND message work request for the control channel
  1340. * containing some data and block until the post completes.
  1341. */
  1342. static int qemu_rdma_post_send_control(RDMAContext *rdma, uint8_t *buf,
  1343. RDMAControlHeader *head)
  1344. {
  1345. int ret = 0;
  1346. RDMAWorkRequestData *wr = &rdma->wr_data[RDMA_WRID_CONTROL];
  1347. struct ibv_send_wr *bad_wr;
  1348. struct ibv_sge sge = {
  1349. .addr = (uint64_t)(wr->control),
  1350. .length = head->len + sizeof(RDMAControlHeader),
  1351. .lkey = wr->control_mr->lkey,
  1352. };
  1353. struct ibv_send_wr send_wr = {
  1354. .wr_id = RDMA_WRID_SEND_CONTROL,
  1355. .opcode = IBV_WR_SEND,
  1356. .send_flags = IBV_SEND_SIGNALED,
  1357. .sg_list = &sge,
  1358. .num_sge = 1,
  1359. };
  1360. DDDPRINTF("CONTROL: sending %s..\n", control_desc[head->type]);
  1361. /*
  1362. * We don't actually need to do a memcpy() in here if we used
  1363. * the "sge" properly, but since we're only sending control messages
  1364. * (not RAM in a performance-critical path), then its OK for now.
  1365. *
  1366. * The copy makes the RDMAControlHeader simpler to manipulate
  1367. * for the time being.
  1368. */
  1369. assert(head->len <= RDMA_CONTROL_MAX_BUFFER - sizeof(*head));
  1370. memcpy(wr->control, head, sizeof(RDMAControlHeader));
  1371. control_to_network((void *) wr->control);
  1372. if (buf) {
  1373. memcpy(wr->control + sizeof(RDMAControlHeader), buf, head->len);
  1374. }
  1375. ret = ibv_post_send(rdma->qp, &send_wr, &bad_wr);
  1376. if (ret > 0) {
  1377. fprintf(stderr, "Failed to use post IB SEND for control!\n");
  1378. return -ret;
  1379. }
  1380. ret = qemu_rdma_block_for_wrid(rdma, RDMA_WRID_SEND_CONTROL, NULL);
  1381. if (ret < 0) {
  1382. fprintf(stderr, "rdma migration: send polling control error!\n");
  1383. }
  1384. return ret;
  1385. }
  1386. /*
  1387. * Post a RECV work request in anticipation of some future receipt
  1388. * of data on the control channel.
  1389. */
  1390. static int qemu_rdma_post_recv_control(RDMAContext *rdma, int idx)
  1391. {
  1392. struct ibv_recv_wr *bad_wr;
  1393. struct ibv_sge sge = {
  1394. .addr = (uint64_t)(rdma->wr_data[idx].control),
  1395. .length = RDMA_CONTROL_MAX_BUFFER,
  1396. .lkey = rdma->wr_data[idx].control_mr->lkey,
  1397. };
  1398. struct ibv_recv_wr recv_wr = {
  1399. .wr_id = RDMA_WRID_RECV_CONTROL + idx,
  1400. .sg_list = &sge,
  1401. .num_sge = 1,
  1402. };
  1403. if (ibv_post_recv(rdma->qp, &recv_wr, &bad_wr)) {
  1404. return -1;
  1405. }
  1406. return 0;
  1407. }
  1408. /*
  1409. * Block and wait for a RECV control channel message to arrive.
  1410. */
  1411. static int qemu_rdma_exchange_get_response(RDMAContext *rdma,
  1412. RDMAControlHeader *head, int expecting, int idx)
  1413. {
  1414. uint32_t byte_len;
  1415. int ret = qemu_rdma_block_for_wrid(rdma, RDMA_WRID_RECV_CONTROL + idx,
  1416. &byte_len);
  1417. if (ret < 0) {
  1418. fprintf(stderr, "rdma migration: recv polling control error!\n");
  1419. return ret;
  1420. }
  1421. network_to_control((void *) rdma->wr_data[idx].control);
  1422. memcpy(head, rdma->wr_data[idx].control, sizeof(RDMAControlHeader));
  1423. DDDPRINTF("CONTROL: %s receiving...\n", control_desc[expecting]);
  1424. if (expecting == RDMA_CONTROL_NONE) {
  1425. DDDPRINTF("Surprise: got %s (%d)\n",
  1426. control_desc[head->type], head->type);
  1427. } else if (head->type != expecting || head->type == RDMA_CONTROL_ERROR) {
  1428. fprintf(stderr, "Was expecting a %s (%d) control message"
  1429. ", but got: %s (%d), length: %d\n",
  1430. control_desc[expecting], expecting,
  1431. control_desc[head->type], head->type, head->len);
  1432. return -EIO;
  1433. }
  1434. if (head->len > RDMA_CONTROL_MAX_BUFFER - sizeof(*head)) {
  1435. fprintf(stderr, "too long length: %d\n", head->len);
  1436. return -EINVAL;
  1437. }
  1438. if (sizeof(*head) + head->len != byte_len) {
  1439. fprintf(stderr, "Malformed length: %d byte_len %d\n",
  1440. head->len, byte_len);
  1441. return -EINVAL;
  1442. }
  1443. return 0;
  1444. }
  1445. /*
  1446. * When a RECV work request has completed, the work request's
  1447. * buffer is pointed at the header.
  1448. *
  1449. * This will advance the pointer to the data portion
  1450. * of the control message of the work request's buffer that
  1451. * was populated after the work request finished.
  1452. */
  1453. static void qemu_rdma_move_header(RDMAContext *rdma, int idx,
  1454. RDMAControlHeader *head)
  1455. {
  1456. rdma->wr_data[idx].control_len = head->len;
  1457. rdma->wr_data[idx].control_curr =
  1458. rdma->wr_data[idx].control + sizeof(RDMAControlHeader);
  1459. }
  1460. /*
  1461. * This is an 'atomic' high-level operation to deliver a single, unified
  1462. * control-channel message.
  1463. *
  1464. * Additionally, if the user is expecting some kind of reply to this message,
  1465. * they can request a 'resp' response message be filled in by posting an
  1466. * additional work request on behalf of the user and waiting for an additional
  1467. * completion.
  1468. *
  1469. * The extra (optional) response is used during registration to us from having
  1470. * to perform an *additional* exchange of message just to provide a response by
  1471. * instead piggy-backing on the acknowledgement.
  1472. */
  1473. static int qemu_rdma_exchange_send(RDMAContext *rdma, RDMAControlHeader *head,
  1474. uint8_t *data, RDMAControlHeader *resp,
  1475. int *resp_idx,
  1476. int (*callback)(RDMAContext *rdma))
  1477. {
  1478. int ret = 0;
  1479. /*
  1480. * Wait until the dest is ready before attempting to deliver the message
  1481. * by waiting for a READY message.
  1482. */
  1483. if (rdma->control_ready_expected) {
  1484. RDMAControlHeader resp;
  1485. ret = qemu_rdma_exchange_get_response(rdma,
  1486. &resp, RDMA_CONTROL_READY, RDMA_WRID_READY);
  1487. if (ret < 0) {
  1488. return ret;
  1489. }
  1490. }
  1491. /*
  1492. * If the user is expecting a response, post a WR in anticipation of it.
  1493. */
  1494. if (resp) {
  1495. ret = qemu_rdma_post_recv_control(rdma, RDMA_WRID_DATA);
  1496. if (ret) {
  1497. fprintf(stderr, "rdma migration: error posting"
  1498. " extra control recv for anticipated result!");
  1499. return ret;
  1500. }
  1501. }
  1502. /*
  1503. * Post a WR to replace the one we just consumed for the READY message.
  1504. */
  1505. ret = qemu_rdma_post_recv_control(rdma, RDMA_WRID_READY);
  1506. if (ret) {
  1507. fprintf(stderr, "rdma migration: error posting first control recv!");
  1508. return ret;
  1509. }
  1510. /*
  1511. * Deliver the control message that was requested.
  1512. */
  1513. ret = qemu_rdma_post_send_control(rdma, data, head);
  1514. if (ret < 0) {
  1515. fprintf(stderr, "Failed to send control buffer!\n");
  1516. return ret;
  1517. }
  1518. /*
  1519. * If we're expecting a response, block and wait for it.
  1520. */
  1521. if (resp) {
  1522. if (callback) {
  1523. DDPRINTF("Issuing callback before receiving response...\n");
  1524. ret = callback(rdma);
  1525. if (ret < 0) {
  1526. return ret;
  1527. }
  1528. }
  1529. DDPRINTF("Waiting for response %s\n", control_desc[resp->type]);
  1530. ret = qemu_rdma_exchange_get_response(rdma, resp,
  1531. resp->type, RDMA_WRID_DATA);
  1532. if (ret < 0) {
  1533. return ret;
  1534. }
  1535. qemu_rdma_move_header(rdma, RDMA_WRID_DATA, resp);
  1536. if (resp_idx) {
  1537. *resp_idx = RDMA_WRID_DATA;
  1538. }
  1539. DDPRINTF("Response %s received.\n", control_desc[resp->type]);
  1540. }
  1541. rdma->control_ready_expected = 1;
  1542. return 0;
  1543. }
  1544. /*
  1545. * This is an 'atomic' high-level operation to receive a single, unified
  1546. * control-channel message.
  1547. */
  1548. static int qemu_rdma_exchange_recv(RDMAContext *rdma, RDMAControlHeader *head,
  1549. int expecting)
  1550. {
  1551. RDMAControlHeader ready = {
  1552. .len = 0,
  1553. .type = RDMA_CONTROL_READY,
  1554. .repeat = 1,
  1555. };
  1556. int ret;
  1557. /*
  1558. * Inform the source that we're ready to receive a message.
  1559. */
  1560. ret = qemu_rdma_post_send_control(rdma, NULL, &ready);
  1561. if (ret < 0) {
  1562. fprintf(stderr, "Failed to send control buffer!\n");
  1563. return ret;
  1564. }
  1565. /*
  1566. * Block and wait for the message.
  1567. */
  1568. ret = qemu_rdma_exchange_get_response(rdma, head,
  1569. expecting, RDMA_WRID_READY);
  1570. if (ret < 0) {
  1571. return ret;
  1572. }
  1573. qemu_rdma_move_header(rdma, RDMA_WRID_READY, head);
  1574. /*
  1575. * Post a new RECV work request to replace the one we just consumed.
  1576. */
  1577. ret = qemu_rdma_post_recv_control(rdma, RDMA_WRID_READY);
  1578. if (ret) {
  1579. fprintf(stderr, "rdma migration: error posting second control recv!");
  1580. return ret;
  1581. }
  1582. return 0;
  1583. }
  1584. /*
  1585. * Write an actual chunk of memory using RDMA.
  1586. *
  1587. * If we're using dynamic registration on the dest-side, we have to
  1588. * send a registration command first.
  1589. */
  1590. static int qemu_rdma_write_one(QEMUFile *f, RDMAContext *rdma,
  1591. int current_index, uint64_t current_addr,
  1592. uint64_t length)
  1593. {
  1594. struct ibv_sge sge;
  1595. struct ibv_send_wr send_wr = { 0 };
  1596. struct ibv_send_wr *bad_wr;
  1597. int reg_result_idx, ret, count = 0;
  1598. uint64_t chunk, chunks;
  1599. uint8_t *chunk_start, *chunk_end;
  1600. RDMALocalBlock *block = &(rdma->local_ram_blocks.block[current_index]);
  1601. RDMARegister reg;
  1602. RDMARegisterResult *reg_result;
  1603. RDMAControlHeader resp = { .type = RDMA_CONTROL_REGISTER_RESULT };
  1604. RDMAControlHeader head = { .len = sizeof(RDMARegister),
  1605. .type = RDMA_CONTROL_REGISTER_REQUEST,
  1606. .repeat = 1,
  1607. };
  1608. retry:
  1609. sge.addr = (uint64_t)(block->local_host_addr +
  1610. (current_addr - block->offset));
  1611. sge.length = length;
  1612. chunk = ram_chunk_index(block->local_host_addr, (uint8_t *) sge.addr);
  1613. chunk_start = ram_chunk_start(block, chunk);
  1614. if (block->is_ram_block) {
  1615. chunks = length / (1UL << RDMA_REG_CHUNK_SHIFT);
  1616. if (chunks && ((length % (1UL << RDMA_REG_CHUNK_SHIFT)) == 0)) {
  1617. chunks--;
  1618. }
  1619. } else {
  1620. chunks = block->length / (1UL << RDMA_REG_CHUNK_SHIFT);
  1621. if (chunks && ((block->length % (1UL << RDMA_REG_CHUNK_SHIFT)) == 0)) {
  1622. chunks--;
  1623. }
  1624. }
  1625. DDPRINTF("Writing %" PRIu64 " chunks, (%" PRIu64 " MB)\n",
  1626. chunks + 1, (chunks + 1) * (1UL << RDMA_REG_CHUNK_SHIFT) / 1024 / 1024);
  1627. chunk_end = ram_chunk_end(block, chunk + chunks);
  1628. if (!rdma->pin_all) {
  1629. #ifdef RDMA_UNREGISTRATION_EXAMPLE
  1630. qemu_rdma_unregister_waiting(rdma);
  1631. #endif
  1632. }
  1633. while (test_bit(chunk, block->transit_bitmap)) {
  1634. (void)count;
  1635. DDPRINTF("(%d) Not clobbering: block: %d chunk %" PRIu64
  1636. " current %" PRIu64 " len %" PRIu64 " %d %d\n",
  1637. count++, current_index, chunk,
  1638. sge.addr, length, rdma->nb_sent, block->nb_chunks);
  1639. ret = qemu_rdma_block_for_wrid(rdma, RDMA_WRID_RDMA_WRITE, NULL);
  1640. if (ret < 0) {
  1641. fprintf(stderr, "Failed to Wait for previous write to complete "
  1642. "block %d chunk %" PRIu64
  1643. " current %" PRIu64 " len %" PRIu64 " %d\n",
  1644. current_index, chunk, sge.addr, length, rdma->nb_sent);
  1645. return ret;
  1646. }
  1647. }
  1648. if (!rdma->pin_all || !block->is_ram_block) {
  1649. if (!block->remote_keys[chunk]) {
  1650. /*
  1651. * This chunk has not yet been registered, so first check to see
  1652. * if the entire chunk is zero. If so, tell the other size to
  1653. * memset() + madvise() the entire chunk without RDMA.
  1654. */
  1655. if (can_use_buffer_find_nonzero_offset((void *)sge.addr, length)
  1656. && buffer_find_nonzero_offset((void *)sge.addr,
  1657. length) == length) {
  1658. RDMACompress comp = {
  1659. .offset = current_addr,
  1660. .value = 0,
  1661. .block_idx = current_index,
  1662. .length = length,
  1663. };
  1664. head.len = sizeof(comp);
  1665. head.type = RDMA_CONTROL_COMPRESS;
  1666. DDPRINTF("Entire chunk is zero, sending compress: %"
  1667. PRIu64 " for %d "
  1668. "bytes, index: %d, offset: %" PRId64 "...\n",
  1669. chunk, sge.length, current_index, current_addr);
  1670. compress_to_network(&comp);
  1671. ret = qemu_rdma_exchange_send(rdma, &head,
  1672. (uint8_t *) &comp, NULL, NULL, NULL);
  1673. if (ret < 0) {
  1674. return -EIO;
  1675. }
  1676. acct_update_position(f, sge.length, true);
  1677. return 1;
  1678. }
  1679. /*
  1680. * Otherwise, tell other side to register.
  1681. */
  1682. reg.current_index = current_index;
  1683. if (block->is_ram_block) {
  1684. reg.key.current_addr = current_addr;
  1685. } else {
  1686. reg.key.chunk = chunk;
  1687. }
  1688. reg.chunks = chunks;
  1689. DDPRINTF("Sending registration request chunk %" PRIu64 " for %d "
  1690. "bytes, index: %d, offset: %" PRId64 "...\n",
  1691. chunk, sge.length, current_index, current_addr);
  1692. register_to_network(&reg);
  1693. ret = qemu_rdma_exchange_send(rdma, &head, (uint8_t *) &reg,
  1694. &resp, &reg_result_idx, NULL);
  1695. if (ret < 0) {
  1696. return ret;
  1697. }
  1698. /* try to overlap this single registration with the one we sent. */
  1699. if (qemu_rdma_register_and_get_keys(rdma, block,
  1700. (uint8_t *) sge.addr,
  1701. &sge.lkey, NULL, chunk,
  1702. chunk_start, chunk_end)) {
  1703. fprintf(stderr, "cannot get lkey!\n");
  1704. return -EINVAL;
  1705. }
  1706. reg_result = (RDMARegisterResult *)
  1707. rdma->wr_data[reg_result_idx].control_curr;
  1708. network_to_result(reg_result);
  1709. DDPRINTF("Received registration result:"
  1710. " my key: %x their key %x, chunk %" PRIu64 "\n",
  1711. block->remote_keys[chunk], reg_result->rkey, chunk);
  1712. block->remote_keys[chunk] = reg_result->rkey;
  1713. block->remote_host_addr = reg_result->host_addr;
  1714. } else {
  1715. /* already registered before */
  1716. if (qemu_rdma_register_and_get_keys(rdma, block,
  1717. (uint8_t *)sge.addr,
  1718. &sge.lkey, NULL, chunk,
  1719. chunk_start, chunk_end)) {
  1720. fprintf(stderr, "cannot get lkey!\n");
  1721. return -EINVAL;
  1722. }
  1723. }
  1724. send_wr.wr.rdma.rkey = block->remote_keys[chunk];
  1725. } else {
  1726. send_wr.wr.rdma.rkey = block->remote_rkey;
  1727. if (qemu_rdma_register_and_get_keys(rdma, block, (uint8_t *)sge.addr,
  1728. &sge.lkey, NULL, chunk,
  1729. chunk_start, chunk_end)) {
  1730. fprintf(stderr, "cannot get lkey!\n");
  1731. return -EINVAL;
  1732. }
  1733. }
  1734. /*
  1735. * Encode the ram block index and chunk within this wrid.
  1736. * We will use this information at the time of completion
  1737. * to figure out which bitmap to check against and then which
  1738. * chunk in the bitmap to look for.
  1739. */
  1740. send_wr.wr_id = qemu_rdma_make_wrid(RDMA_WRID_RDMA_WRITE,
  1741. current_index, chunk);
  1742. send_wr.opcode = IBV_WR_RDMA_WRITE;
  1743. send_wr.send_flags = IBV_SEND_SIGNALED;
  1744. send_wr.sg_list = &sge;
  1745. send_wr.num_sge = 1;
  1746. send_wr.wr.rdma.remote_addr = block->remote_host_addr +
  1747. (current_addr - block->offset);
  1748. DDDPRINTF("Posting chunk: %" PRIu64 ", addr: %lx"
  1749. " remote: %lx, bytes %" PRIu32 "\n",
  1750. chunk, sge.addr, send_wr.wr.rdma.remote_addr,
  1751. sge.length);
  1752. /*
  1753. * ibv_post_send() does not return negative error numbers,
  1754. * per the specification they are positive - no idea why.
  1755. */
  1756. ret = ibv_post_send(rdma->qp, &send_wr, &bad_wr);
  1757. if (ret == ENOMEM) {
  1758. DDPRINTF("send queue is full. wait a little....\n");
  1759. ret = qemu_rdma_block_for_wrid(rdma, RDMA_WRID_RDMA_WRITE, NULL);
  1760. if (ret < 0) {
  1761. fprintf(stderr, "rdma migration: failed to make "
  1762. "room in full send queue! %d\n", ret);
  1763. return ret;
  1764. }
  1765. goto retry;
  1766. } else if (ret > 0) {
  1767. perror("rdma migration: post rdma write failed");
  1768. return -ret;
  1769. }
  1770. set_bit(chunk, block->transit_bitmap);
  1771. acct_update_position(f, sge.length, false);
  1772. rdma->total_writes++;
  1773. return 0;
  1774. }
  1775. /*
  1776. * Push out any unwritten RDMA operations.
  1777. *
  1778. * We support sending out multiple chunks at the same time.
  1779. * Not all of them need to get signaled in the completion queue.
  1780. */
  1781. static int qemu_rdma_write_flush(QEMUFile *f, RDMAContext *rdma)
  1782. {
  1783. int ret;
  1784. if (!rdma->current_length) {
  1785. return 0;
  1786. }
  1787. ret = qemu_rdma_write_one(f, rdma,
  1788. rdma->current_index, rdma->current_addr, rdma->current_length);
  1789. if (ret < 0) {
  1790. return ret;
  1791. }
  1792. if (ret == 0) {
  1793. rdma->nb_sent++;
  1794. DDDPRINTF("sent total: %d\n", rdma->nb_sent);
  1795. }
  1796. rdma->current_length = 0;
  1797. rdma->current_addr = 0;
  1798. return 0;
  1799. }
  1800. static inline int qemu_rdma_buffer_mergable(RDMAContext *rdma,
  1801. uint64_t offset, uint64_t len)
  1802. {
  1803. RDMALocalBlock *block;
  1804. uint8_t *host_addr;
  1805. uint8_t *chunk_end;
  1806. if (rdma->current_index < 0) {
  1807. return 0;
  1808. }
  1809. if (rdma->current_chunk < 0) {
  1810. return 0;
  1811. }
  1812. block = &(rdma->local_ram_blocks.block[rdma->current_index]);
  1813. host_addr = block->local_host_addr + (offset - block->offset);
  1814. chunk_end = ram_chunk_end(block, rdma->current_chunk);
  1815. if (rdma->current_length == 0) {
  1816. return 0;
  1817. }
  1818. /*
  1819. * Only merge into chunk sequentially.
  1820. */
  1821. if (offset != (rdma->current_addr + rdma->current_length)) {
  1822. return 0;
  1823. }
  1824. if (offset < block->offset) {
  1825. return 0;
  1826. }
  1827. if ((offset + len) > (block->offset + block->length)) {
  1828. return 0;
  1829. }
  1830. if ((host_addr + len) > chunk_end) {
  1831. return 0;
  1832. }
  1833. return 1;
  1834. }
  1835. /*
  1836. * We're not actually writing here, but doing three things:
  1837. *
  1838. * 1. Identify the chunk the buffer belongs to.
  1839. * 2. If the chunk is full or the buffer doesn't belong to the current
  1840. * chunk, then start a new chunk and flush() the old chunk.
  1841. * 3. To keep the hardware busy, we also group chunks into batches
  1842. * and only require that a batch gets acknowledged in the completion
  1843. * qeueue instead of each individual chunk.
  1844. */
  1845. static int qemu_rdma_write(QEMUFile *f, RDMAContext *rdma,
  1846. uint64_t block_offset, uint64_t offset,
  1847. uint64_t len)
  1848. {
  1849. uint64_t current_addr = block_offset + offset;
  1850. uint64_t index = rdma->current_index;
  1851. uint64_t chunk = rdma->current_chunk;
  1852. int ret;
  1853. /* If we cannot merge it, we flush the current buffer first. */
  1854. if (!qemu_rdma_buffer_mergable(rdma, current_addr, len)) {
  1855. ret = qemu_rdma_write_flush(f, rdma);
  1856. if (ret) {
  1857. return ret;
  1858. }
  1859. rdma->current_length = 0;
  1860. rdma->current_addr = current_addr;
  1861. ret = qemu_rdma_search_ram_block(rdma, block_offset,
  1862. offset, len, &index, &chunk);
  1863. if (ret) {
  1864. fprintf(stderr, "ram block search failed\n");
  1865. return ret;
  1866. }
  1867. rdma->current_index = index;
  1868. rdma->current_chunk = chunk;
  1869. }
  1870. /* merge it */
  1871. rdma->current_length += len;
  1872. /* flush it if buffer is too large */
  1873. if (rdma->current_length >= RDMA_MERGE_MAX) {
  1874. return qemu_rdma_write_flush(f, rdma);
  1875. }
  1876. return 0;
  1877. }
  1878. static void qemu_rdma_cleanup(RDMAContext *rdma)
  1879. {
  1880. struct rdma_cm_event *cm_event;
  1881. int ret, idx;
  1882. if (rdma->cm_id && rdma->connected) {
  1883. if (rdma->error_state) {
  1884. RDMAControlHeader head = { .len = 0,
  1885. .type = RDMA_CONTROL_ERROR,
  1886. .repeat = 1,
  1887. };
  1888. fprintf(stderr, "Early error. Sending error.\n");
  1889. qemu_rdma_post_send_control(rdma, NULL, &head);
  1890. }
  1891. ret = rdma_disconnect(rdma->cm_id);
  1892. if (!ret) {
  1893. DDPRINTF("waiting for disconnect\n");
  1894. ret = rdma_get_cm_event(rdma->channel, &cm_event);
  1895. if (!ret) {
  1896. rdma_ack_cm_event(cm_event);
  1897. }
  1898. }
  1899. DDPRINTF("Disconnected.\n");
  1900. rdma->connected = false;
  1901. }
  1902. g_free(rdma->block);
  1903. rdma->block = NULL;
  1904. for (idx = 0; idx < RDMA_WRID_MAX; idx++) {
  1905. if (rdma->wr_data[idx].control_mr) {
  1906. rdma->total_registrations--;
  1907. ibv_dereg_mr(rdma->wr_data[idx].control_mr);
  1908. }
  1909. rdma->wr_data[idx].control_mr = NULL;
  1910. }
  1911. if (rdma->local_ram_blocks.block) {
  1912. while (rdma->local_ram_blocks.nb_blocks) {
  1913. __qemu_rdma_delete_block(rdma,
  1914. rdma->local_ram_blocks.block->offset);
  1915. }
  1916. }
  1917. if (rdma->cq) {
  1918. ibv_destroy_cq(rdma->cq);
  1919. rdma->cq = NULL;
  1920. }
  1921. if (rdma->comp_channel) {
  1922. ibv_destroy_comp_channel(rdma->comp_channel);
  1923. rdma->comp_channel = NULL;
  1924. }
  1925. if (rdma->pd) {
  1926. ibv_dealloc_pd(rdma->pd);
  1927. rdma->pd = NULL;
  1928. }
  1929. if (rdma->listen_id) {
  1930. rdma_destroy_id(rdma->listen_id);
  1931. rdma->listen_id = NULL;
  1932. }
  1933. if (rdma->cm_id) {
  1934. if (rdma->qp) {
  1935. rdma_destroy_qp(rdma->cm_id);
  1936. rdma->qp = NULL;
  1937. }
  1938. rdma_destroy_id(rdma->cm_id);
  1939. rdma->cm_id = NULL;
  1940. }
  1941. if (rdma->channel) {
  1942. rdma_destroy_event_channel(rdma->channel);
  1943. rdma->channel = NULL;
  1944. }
  1945. g_free(rdma->host);
  1946. rdma->host = NULL;
  1947. }
  1948. static int qemu_rdma_source_init(RDMAContext *rdma, Error **errp, bool pin_all)
  1949. {
  1950. int ret, idx;
  1951. Error *local_err = NULL, **temp = &local_err;
  1952. /*
  1953. * Will be validated against destination's actual capabilities
  1954. * after the connect() completes.
  1955. */
  1956. rdma->pin_all = pin_all;
  1957. ret = qemu_rdma_resolve_host(rdma, temp);
  1958. if (ret) {
  1959. goto err_rdma_source_init;
  1960. }
  1961. ret = qemu_rdma_alloc_pd_cq(rdma);
  1962. if (ret) {
  1963. ERROR(temp, "rdma migration: error allocating pd and cq! Your mlock()"
  1964. " limits may be too low. Please check $ ulimit -a # and "
  1965. "search for 'ulimit -l' in the output");
  1966. goto err_rdma_source_init;
  1967. }
  1968. ret = qemu_rdma_alloc_qp(rdma);
  1969. if (ret) {
  1970. ERROR(temp, "rdma migration: error allocating qp!");
  1971. goto err_rdma_source_init;
  1972. }
  1973. ret = qemu_rdma_init_ram_blocks(rdma);
  1974. if (ret) {
  1975. ERROR(temp, "rdma migration: error initializing ram blocks!");
  1976. goto err_rdma_source_init;
  1977. }
  1978. for (idx = 0; idx < RDMA_WRID_MAX; idx++) {
  1979. ret = qemu_rdma_reg_control(rdma, idx);
  1980. if (ret) {
  1981. ERROR(temp, "rdma migration: error registering %d control!",
  1982. idx);
  1983. goto err_rdma_source_init;
  1984. }
  1985. }
  1986. return 0;
  1987. err_rdma_source_init:
  1988. error_propagate(errp, local_err);
  1989. qemu_rdma_cleanup(rdma);
  1990. return -1;
  1991. }
  1992. static int qemu_rdma_connect(RDMAContext *rdma, Error **errp)
  1993. {
  1994. RDMACapabilities cap = {
  1995. .version = RDMA_CONTROL_VERSION_CURRENT,
  1996. .flags = 0,
  1997. };
  1998. struct rdma_conn_param conn_param = { .initiator_depth = 2,
  1999. .retry_count = 5,
  2000. .private_data = &cap,
  2001. .private_data_len = sizeof(cap),
  2002. };
  2003. struct rdma_cm_event *cm_event;
  2004. int ret;
  2005. /*
  2006. * Only negotiate the capability with destination if the user
  2007. * on the source first requested the capability.
  2008. */
  2009. if (rdma->pin_all) {
  2010. DPRINTF("Server pin-all memory requested.\n");
  2011. cap.flags |= RDMA_CAPABILITY_PIN_ALL;
  2012. }
  2013. caps_to_network(&cap);
  2014. ret = rdma_connect(rdma->cm_id, &conn_param);
  2015. if (ret) {
  2016. perror("rdma_connect");
  2017. ERROR(errp, "connecting to destination!");
  2018. rdma_destroy_id(rdma->cm_id);
  2019. rdma->cm_id = NULL;
  2020. goto err_rdma_source_connect;
  2021. }
  2022. ret = rdma_get_cm_event(rdma->channel, &cm_event);
  2023. if (ret) {
  2024. perror("rdma_get_cm_event after rdma_connect");
  2025. ERROR(errp, "connecting to destination!");
  2026. rdma_ack_cm_event(cm_event);
  2027. rdma_destroy_id(rdma->cm_id);
  2028. rdma->cm_id = NULL;
  2029. goto err_rdma_source_connect;
  2030. }
  2031. if (cm_event->event != RDMA_CM_EVENT_ESTABLISHED) {
  2032. perror("rdma_get_cm_event != EVENT_ESTABLISHED after rdma_connect");
  2033. ERROR(errp, "connecting to destination!");
  2034. rdma_ack_cm_event(cm_event);
  2035. rdma_destroy_id(rdma->cm_id);
  2036. rdma->cm_id = NULL;
  2037. goto err_rdma_source_connect;
  2038. }
  2039. rdma->connected = true;
  2040. memcpy(&cap, cm_event->param.conn.private_data, sizeof(cap));
  2041. network_to_caps(&cap);
  2042. /*
  2043. * Verify that the *requested* capabilities are supported by the destination
  2044. * and disable them otherwise.
  2045. */
  2046. if (rdma->pin_all && !(cap.flags & RDMA_CAPABILITY_PIN_ALL)) {
  2047. ERROR(errp, "Server cannot support pinning all memory. "
  2048. "Will register memory dynamically.");
  2049. rdma->pin_all = false;
  2050. }
  2051. DPRINTF("Pin all memory: %s\n", rdma->pin_all ? "enabled" : "disabled");
  2052. rdma_ack_cm_event(cm_event);
  2053. ret = qemu_rdma_post_recv_control(rdma, RDMA_WRID_READY);
  2054. if (ret) {
  2055. ERROR(errp, "posting second control recv!");
  2056. goto err_rdma_source_connect;
  2057. }
  2058. rdma->control_ready_expected = 1;
  2059. rdma->nb_sent = 0;
  2060. return 0;
  2061. err_rdma_source_connect:
  2062. qemu_rdma_cleanup(rdma);
  2063. return -1;
  2064. }
  2065. static int qemu_rdma_dest_init(RDMAContext *rdma, Error **errp)
  2066. {
  2067. int ret = -EINVAL, idx;
  2068. struct rdma_cm_id *listen_id;
  2069. char ip[40] = "unknown";
  2070. struct rdma_addrinfo *res;
  2071. char port_str[16];
  2072. for (idx = 0; idx < RDMA_WRID_MAX; idx++) {
  2073. rdma->wr_data[idx].control_len = 0;
  2074. rdma->wr_data[idx].control_curr = NULL;
  2075. }
  2076. if (rdma->host == NULL) {
  2077. ERROR(errp, "RDMA host is not set!");
  2078. rdma->error_state = -EINVAL;
  2079. return -1;
  2080. }
  2081. /* create CM channel */
  2082. rdma->channel = rdma_create_event_channel();
  2083. if (!rdma->channel) {
  2084. ERROR(errp, "could not create rdma event channel");
  2085. rdma->error_state = -EINVAL;
  2086. return -1;
  2087. }
  2088. /* create CM id */
  2089. ret = rdma_create_id(rdma->channel, &listen_id, NULL, RDMA_PS_TCP);
  2090. if (ret) {
  2091. ERROR(errp, "could not create cm_id!");
  2092. goto err_dest_init_create_listen_id;
  2093. }
  2094. snprintf(port_str, 16, "%d", rdma->port);
  2095. port_str[15] = '\0';
  2096. if (rdma->host && strcmp("", rdma->host)) {
  2097. struct rdma_addrinfo *e;
  2098. ret = rdma_getaddrinfo(rdma->host, port_str, NULL, &res);
  2099. if (ret < 0) {
  2100. ERROR(errp, "could not rdma_getaddrinfo address %s", rdma->host);
  2101. goto err_dest_init_bind_addr;
  2102. }
  2103. for (e = res; e != NULL; e = e->ai_next) {
  2104. inet_ntop(e->ai_family,
  2105. &((struct sockaddr_in *) e->ai_dst_addr)->sin_addr, ip, sizeof ip);
  2106. DPRINTF("Trying %s => %s\n", rdma->host, ip);
  2107. ret = rdma_bind_addr(listen_id, e->ai_dst_addr);
  2108. if (!ret) {
  2109. if (e->ai_family == AF_INET6) {
  2110. ret = qemu_rdma_broken_ipv6_kernel(errp, listen_id->verbs);
  2111. if (ret) {
  2112. continue;
  2113. }
  2114. }
  2115. goto listen;
  2116. }
  2117. }
  2118. ERROR(errp, "Error: could not rdma_bind_addr!");
  2119. goto err_dest_init_bind_addr;
  2120. } else {
  2121. ERROR(errp, "migration host and port not specified!");
  2122. ret = -EINVAL;
  2123. goto err_dest_init_bind_addr;
  2124. }
  2125. listen:
  2126. rdma->listen_id = listen_id;
  2127. qemu_rdma_dump_gid("dest_init", listen_id);
  2128. return 0;
  2129. err_dest_init_bind_addr:
  2130. rdma_destroy_id(listen_id);
  2131. err_dest_init_create_listen_id:
  2132. rdma_destroy_event_channel(rdma->channel);
  2133. rdma->channel = NULL;
  2134. rdma->error_state = ret;
  2135. return ret;
  2136. }
  2137. static void *qemu_rdma_data_init(const char *host_port, Error **errp)
  2138. {
  2139. RDMAContext *rdma = NULL;
  2140. InetSocketAddress *addr;
  2141. if (host_port) {
  2142. rdma = g_malloc0(sizeof(RDMAContext));
  2143. memset(rdma, 0, sizeof(RDMAContext));
  2144. rdma->current_index = -1;
  2145. rdma->current_chunk = -1;
  2146. addr = inet_parse(host_port, NULL);
  2147. if (addr != NULL) {
  2148. rdma->port = atoi(addr->port);
  2149. rdma->host = g_strdup(addr->host);
  2150. } else {
  2151. ERROR(errp, "bad RDMA migration address '%s'", host_port);
  2152. g_free(rdma);
  2153. rdma = NULL;
  2154. }
  2155. qapi_free_InetSocketAddress(addr);
  2156. }
  2157. return rdma;
  2158. }
  2159. /*
  2160. * QEMUFile interface to the control channel.
  2161. * SEND messages for control only.
  2162. * VM's ram is handled with regular RDMA messages.
  2163. */
  2164. static int qemu_rdma_put_buffer(void *opaque, const uint8_t *buf,
  2165. int64_t pos, int size)
  2166. {
  2167. QEMUFileRDMA *r = opaque;
  2168. QEMUFile *f = r->file;
  2169. RDMAContext *rdma = r->rdma;
  2170. size_t remaining = size;
  2171. uint8_t * data = (void *) buf;
  2172. int ret;
  2173. CHECK_ERROR_STATE();
  2174. /*
  2175. * Push out any writes that
  2176. * we're queued up for VM's ram.
  2177. */
  2178. ret = qemu_rdma_write_flush(f, rdma);
  2179. if (ret < 0) {
  2180. rdma->error_state = ret;
  2181. return ret;
  2182. }
  2183. while (remaining) {
  2184. RDMAControlHeader head;
  2185. r->len = MIN(remaining, RDMA_SEND_INCREMENT);
  2186. remaining -= r->len;
  2187. head.len = r->len;
  2188. head.type = RDMA_CONTROL_QEMU_FILE;
  2189. ret = qemu_rdma_exchange_send(rdma, &head, data, NULL, NULL, NULL);
  2190. if (ret < 0) {
  2191. rdma->error_state = ret;
  2192. return ret;
  2193. }
  2194. data += r->len;
  2195. }
  2196. return size;
  2197. }
  2198. static size_t qemu_rdma_fill(RDMAContext *rdma, uint8_t *buf,
  2199. int size, int idx)
  2200. {
  2201. size_t len = 0;
  2202. if (rdma->wr_data[idx].control_len) {
  2203. DDDPRINTF("RDMA %" PRId64 " of %d bytes already in buffer\n",
  2204. rdma->wr_data[idx].control_len, size);
  2205. len = MIN(size, rdma->wr_data[idx].control_len);
  2206. memcpy(buf, rdma->wr_data[idx].control_curr, len);
  2207. rdma->wr_data[idx].control_curr += len;
  2208. rdma->wr_data[idx].control_len -= len;
  2209. }
  2210. return len;
  2211. }
  2212. /*
  2213. * QEMUFile interface to the control channel.
  2214. * RDMA links don't use bytestreams, so we have to
  2215. * return bytes to QEMUFile opportunistically.
  2216. */
  2217. static int qemu_rdma_get_buffer(void *opaque, uint8_t *buf,
  2218. int64_t pos, int size)
  2219. {
  2220. QEMUFileRDMA *r = opaque;
  2221. RDMAContext *rdma = r->rdma;
  2222. RDMAControlHeader head;
  2223. int ret = 0;
  2224. CHECK_ERROR_STATE();
  2225. /*
  2226. * First, we hold on to the last SEND message we
  2227. * were given and dish out the bytes until we run
  2228. * out of bytes.
  2229. */
  2230. r->len = qemu_rdma_fill(r->rdma, buf, size, 0);
  2231. if (r->len) {
  2232. return r->len;
  2233. }
  2234. /*
  2235. * Once we run out, we block and wait for another
  2236. * SEND message to arrive.
  2237. */
  2238. ret = qemu_rdma_exchange_recv(rdma, &head, RDMA_CONTROL_QEMU_FILE);
  2239. if (ret < 0) {
  2240. rdma->error_state = ret;
  2241. return ret;
  2242. }
  2243. /*
  2244. * SEND was received with new bytes, now try again.
  2245. */
  2246. return qemu_rdma_fill(r->rdma, buf, size, 0);
  2247. }
  2248. /*
  2249. * Block until all the outstanding chunks have been delivered by the hardware.
  2250. */
  2251. static int qemu_rdma_drain_cq(QEMUFile *f, RDMAContext *rdma)
  2252. {
  2253. int ret;
  2254. if (qemu_rdma_write_flush(f, rdma) < 0) {
  2255. return -EIO;
  2256. }
  2257. while (rdma->nb_sent) {
  2258. ret = qemu_rdma_block_for_wrid(rdma, RDMA_WRID_RDMA_WRITE, NULL);
  2259. if (ret < 0) {
  2260. fprintf(stderr, "rdma migration: complete polling error!\n");
  2261. return -EIO;
  2262. }
  2263. }
  2264. qemu_rdma_unregister_waiting(rdma);
  2265. return 0;
  2266. }
  2267. static int qemu_rdma_close(void *opaque)
  2268. {
  2269. DPRINTF("Shutting down connection.\n");
  2270. QEMUFileRDMA *r = opaque;
  2271. if (r->rdma) {
  2272. qemu_rdma_cleanup(r->rdma);
  2273. g_free(r->rdma);
  2274. }
  2275. g_free(r);
  2276. return 0;
  2277. }
  2278. /*
  2279. * Parameters:
  2280. * @offset == 0 :
  2281. * This means that 'block_offset' is a full virtual address that does not
  2282. * belong to a RAMBlock of the virtual machine and instead
  2283. * represents a private malloc'd memory area that the caller wishes to
  2284. * transfer.
  2285. *
  2286. * @offset != 0 :
  2287. * Offset is an offset to be added to block_offset and used
  2288. * to also lookup the corresponding RAMBlock.
  2289. *
  2290. * @size > 0 :
  2291. * Initiate an transfer this size.
  2292. *
  2293. * @size == 0 :
  2294. * A 'hint' or 'advice' that means that we wish to speculatively
  2295. * and asynchronously unregister this memory. In this case, there is no
  2296. * guarantee that the unregister will actually happen, for example,
  2297. * if the memory is being actively transmitted. Additionally, the memory
  2298. * may be re-registered at any future time if a write within the same
  2299. * chunk was requested again, even if you attempted to unregister it
  2300. * here.
  2301. *
  2302. * @size < 0 : TODO, not yet supported
  2303. * Unregister the memory NOW. This means that the caller does not
  2304. * expect there to be any future RDMA transfers and we just want to clean
  2305. * things up. This is used in case the upper layer owns the memory and
  2306. * cannot wait for qemu_fclose() to occur.
  2307. *
  2308. * @bytes_sent : User-specificed pointer to indicate how many bytes were
  2309. * sent. Usually, this will not be more than a few bytes of
  2310. * the protocol because most transfers are sent asynchronously.
  2311. */
  2312. static size_t qemu_rdma_save_page(QEMUFile *f, void *opaque,
  2313. ram_addr_t block_offset, ram_addr_t offset,
  2314. size_t size, int *bytes_sent)
  2315. {
  2316. QEMUFileRDMA *rfile = opaque;
  2317. RDMAContext *rdma = rfile->rdma;
  2318. int ret;
  2319. CHECK_ERROR_STATE();
  2320. qemu_fflush(f);
  2321. if (size > 0) {
  2322. /*
  2323. * Add this page to the current 'chunk'. If the chunk
  2324. * is full, or the page doen't belong to the current chunk,
  2325. * an actual RDMA write will occur and a new chunk will be formed.
  2326. */
  2327. ret = qemu_rdma_write(f, rdma, block_offset, offset, size);
  2328. if (ret < 0) {
  2329. fprintf(stderr, "rdma migration: write error! %d\n", ret);
  2330. goto err;
  2331. }
  2332. /*
  2333. * We always return 1 bytes because the RDMA
  2334. * protocol is completely asynchronous. We do not yet know
  2335. * whether an identified chunk is zero or not because we're
  2336. * waiting for other pages to potentially be merged with
  2337. * the current chunk. So, we have to call qemu_update_position()
  2338. * later on when the actual write occurs.
  2339. */
  2340. if (bytes_sent) {
  2341. *bytes_sent = 1;
  2342. }
  2343. } else {
  2344. uint64_t index, chunk;
  2345. /* TODO: Change QEMUFileOps prototype to be signed: size_t => long
  2346. if (size < 0) {
  2347. ret = qemu_rdma_drain_cq(f, rdma);
  2348. if (ret < 0) {
  2349. fprintf(stderr, "rdma: failed to synchronously drain"
  2350. " completion queue before unregistration.\n");
  2351. goto err;
  2352. }
  2353. }
  2354. */
  2355. ret = qemu_rdma_search_ram_block(rdma, block_offset,
  2356. offset, size, &index, &chunk);
  2357. if (ret) {
  2358. fprintf(stderr, "ram block search failed\n");
  2359. goto err;
  2360. }
  2361. qemu_rdma_signal_unregister(rdma, index, chunk, 0);
  2362. /*
  2363. * TODO: Synchronous, guaranteed unregistration (should not occur during
  2364. * fast-path). Otherwise, unregisters will process on the next call to
  2365. * qemu_rdma_drain_cq()
  2366. if (size < 0) {
  2367. qemu_rdma_unregister_waiting(rdma);
  2368. }
  2369. */
  2370. }
  2371. /*
  2372. * Drain the Completion Queue if possible, but do not block,
  2373. * just poll.
  2374. *
  2375. * If nothing to poll, the end of the iteration will do this
  2376. * again to make sure we don't overflow the request queue.
  2377. */
  2378. while (1) {
  2379. uint64_t wr_id, wr_id_in;
  2380. int ret = qemu_rdma_poll(rdma, &wr_id_in, NULL);
  2381. if (ret < 0) {
  2382. fprintf(stderr, "rdma migration: polling error! %d\n", ret);
  2383. goto err;
  2384. }
  2385. wr_id = wr_id_in & RDMA_WRID_TYPE_MASK;
  2386. if (wr_id == RDMA_WRID_NONE) {
  2387. break;
  2388. }
  2389. }
  2390. return RAM_SAVE_CONTROL_DELAYED;
  2391. err:
  2392. rdma->error_state = ret;
  2393. return ret;
  2394. }
  2395. static int qemu_rdma_accept(RDMAContext *rdma)
  2396. {
  2397. RDMACapabilities cap;
  2398. struct rdma_conn_param conn_param = {
  2399. .responder_resources = 2,
  2400. .private_data = &cap,
  2401. .private_data_len = sizeof(cap),
  2402. };
  2403. struct rdma_cm_event *cm_event;
  2404. struct ibv_context *verbs;
  2405. int ret = -EINVAL;
  2406. int idx;
  2407. ret = rdma_get_cm_event(rdma->channel, &cm_event);
  2408. if (ret) {
  2409. goto err_rdma_dest_wait;
  2410. }
  2411. if (cm_event->event != RDMA_CM_EVENT_CONNECT_REQUEST) {
  2412. rdma_ack_cm_event(cm_event);
  2413. goto err_rdma_dest_wait;
  2414. }
  2415. memcpy(&cap, cm_event->param.conn.private_data, sizeof(cap));
  2416. network_to_caps(&cap);
  2417. if (cap.version < 1 || cap.version > RDMA_CONTROL_VERSION_CURRENT) {
  2418. fprintf(stderr, "Unknown source RDMA version: %d, bailing...\n",
  2419. cap.version);
  2420. rdma_ack_cm_event(cm_event);
  2421. goto err_rdma_dest_wait;
  2422. }
  2423. /*
  2424. * Respond with only the capabilities this version of QEMU knows about.
  2425. */
  2426. cap.flags &= known_capabilities;
  2427. /*
  2428. * Enable the ones that we do know about.
  2429. * Add other checks here as new ones are introduced.
  2430. */
  2431. if (cap.flags & RDMA_CAPABILITY_PIN_ALL) {
  2432. rdma->pin_all = true;
  2433. }
  2434. rdma->cm_id = cm_event->id;
  2435. verbs = cm_event->id->verbs;
  2436. rdma_ack_cm_event(cm_event);
  2437. DPRINTF("Memory pin all: %s\n", rdma->pin_all ? "enabled" : "disabled");
  2438. caps_to_network(&cap);
  2439. DPRINTF("verbs context after listen: %p\n", verbs);
  2440. if (!rdma->verbs) {
  2441. rdma->verbs = verbs;
  2442. } else if (rdma->verbs != verbs) {
  2443. fprintf(stderr, "ibv context not matching %p, %p!\n",
  2444. rdma->verbs, verbs);
  2445. goto err_rdma_dest_wait;
  2446. }
  2447. qemu_rdma_dump_id("dest_init", verbs);
  2448. ret = qemu_rdma_alloc_pd_cq(rdma);
  2449. if (ret) {
  2450. fprintf(stderr, "rdma migration: error allocating pd and cq!\n");
  2451. goto err_rdma_dest_wait;
  2452. }
  2453. ret = qemu_rdma_alloc_qp(rdma);
  2454. if (ret) {
  2455. fprintf(stderr, "rdma migration: error allocating qp!\n");
  2456. goto err_rdma_dest_wait;
  2457. }
  2458. ret = qemu_rdma_init_ram_blocks(rdma);
  2459. if (ret) {
  2460. fprintf(stderr, "rdma migration: error initializing ram blocks!\n");
  2461. goto err_rdma_dest_wait;
  2462. }
  2463. for (idx = 0; idx < RDMA_WRID_MAX; idx++) {
  2464. ret = qemu_rdma_reg_control(rdma, idx);
  2465. if (ret) {
  2466. fprintf(stderr, "rdma: error registering %d control!\n", idx);
  2467. goto err_rdma_dest_wait;
  2468. }
  2469. }
  2470. qemu_set_fd_handler2(rdma->channel->fd, NULL, NULL, NULL, NULL);
  2471. ret = rdma_accept(rdma->cm_id, &conn_param);
  2472. if (ret) {
  2473. fprintf(stderr, "rdma_accept returns %d!\n", ret);
  2474. goto err_rdma_dest_wait;
  2475. }
  2476. ret = rdma_get_cm_event(rdma->channel, &cm_event);
  2477. if (ret) {
  2478. fprintf(stderr, "rdma_accept get_cm_event failed %d!\n", ret);
  2479. goto err_rdma_dest_wait;
  2480. }
  2481. if (cm_event->event != RDMA_CM_EVENT_ESTABLISHED) {
  2482. fprintf(stderr, "rdma_accept not event established!\n");
  2483. rdma_ack_cm_event(cm_event);
  2484. goto err_rdma_dest_wait;
  2485. }
  2486. rdma_ack_cm_event(cm_event);
  2487. rdma->connected = true;
  2488. ret = qemu_rdma_post_recv_control(rdma, RDMA_WRID_READY);
  2489. if (ret) {
  2490. fprintf(stderr, "rdma migration: error posting second control recv!\n");
  2491. goto err_rdma_dest_wait;
  2492. }
  2493. qemu_rdma_dump_gid("dest_connect", rdma->cm_id);
  2494. return 0;
  2495. err_rdma_dest_wait:
  2496. rdma->error_state = ret;
  2497. qemu_rdma_cleanup(rdma);
  2498. return ret;
  2499. }
  2500. /*
  2501. * During each iteration of the migration, we listen for instructions
  2502. * by the source VM to perform dynamic page registrations before they
  2503. * can perform RDMA operations.
  2504. *
  2505. * We respond with the 'rkey'.
  2506. *
  2507. * Keep doing this until the source tells us to stop.
  2508. */
  2509. static int qemu_rdma_registration_handle(QEMUFile *f, void *opaque,
  2510. uint64_t flags)
  2511. {
  2512. RDMAControlHeader reg_resp = { .len = sizeof(RDMARegisterResult),
  2513. .type = RDMA_CONTROL_REGISTER_RESULT,
  2514. .repeat = 0,
  2515. };
  2516. RDMAControlHeader unreg_resp = { .len = 0,
  2517. .type = RDMA_CONTROL_UNREGISTER_FINISHED,
  2518. .repeat = 0,
  2519. };
  2520. RDMAControlHeader blocks = { .type = RDMA_CONTROL_RAM_BLOCKS_RESULT,
  2521. .repeat = 1 };
  2522. QEMUFileRDMA *rfile = opaque;
  2523. RDMAContext *rdma = rfile->rdma;
  2524. RDMALocalBlocks *local = &rdma->local_ram_blocks;
  2525. RDMAControlHeader head;
  2526. RDMARegister *reg, *registers;
  2527. RDMACompress *comp;
  2528. RDMARegisterResult *reg_result;
  2529. static RDMARegisterResult results[RDMA_CONTROL_MAX_COMMANDS_PER_MESSAGE];
  2530. RDMALocalBlock *block;
  2531. void *host_addr;
  2532. int ret = 0;
  2533. int idx = 0;
  2534. int count = 0;
  2535. int i = 0;
  2536. CHECK_ERROR_STATE();
  2537. do {
  2538. DDDPRINTF("Waiting for next request %" PRIu64 "...\n", flags);
  2539. ret = qemu_rdma_exchange_recv(rdma, &head, RDMA_CONTROL_NONE);
  2540. if (ret < 0) {
  2541. break;
  2542. }
  2543. if (head.repeat > RDMA_CONTROL_MAX_COMMANDS_PER_MESSAGE) {
  2544. fprintf(stderr, "rdma: Too many requests in this message (%d)."
  2545. "Bailing.\n", head.repeat);
  2546. ret = -EIO;
  2547. break;
  2548. }
  2549. switch (head.type) {
  2550. case RDMA_CONTROL_COMPRESS:
  2551. comp = (RDMACompress *) rdma->wr_data[idx].control_curr;
  2552. network_to_compress(comp);
  2553. DDPRINTF("Zapping zero chunk: %" PRId64
  2554. " bytes, index %d, offset %" PRId64 "\n",
  2555. comp->length, comp->block_idx, comp->offset);
  2556. block = &(rdma->local_ram_blocks.block[comp->block_idx]);
  2557. host_addr = block->local_host_addr +
  2558. (comp->offset - block->offset);
  2559. ram_handle_compressed(host_addr, comp->value, comp->length);
  2560. break;
  2561. case RDMA_CONTROL_REGISTER_FINISHED:
  2562. DDDPRINTF("Current registrations complete.\n");
  2563. goto out;
  2564. case RDMA_CONTROL_RAM_BLOCKS_REQUEST:
  2565. DPRINTF("Initial setup info requested.\n");
  2566. if (rdma->pin_all) {
  2567. ret = qemu_rdma_reg_whole_ram_blocks(rdma);
  2568. if (ret) {
  2569. fprintf(stderr, "rdma migration: error dest "
  2570. "registering ram blocks!\n");
  2571. goto out;
  2572. }
  2573. }
  2574. /*
  2575. * Dest uses this to prepare to transmit the RAMBlock descriptions
  2576. * to the source VM after connection setup.
  2577. * Both sides use the "remote" structure to communicate and update
  2578. * their "local" descriptions with what was sent.
  2579. */
  2580. for (i = 0; i < local->nb_blocks; i++) {
  2581. rdma->block[i].remote_host_addr =
  2582. (uint64_t)(local->block[i].local_host_addr);
  2583. if (rdma->pin_all) {
  2584. rdma->block[i].remote_rkey = local->block[i].mr->rkey;
  2585. }
  2586. rdma->block[i].offset = local->block[i].offset;
  2587. rdma->block[i].length = local->block[i].length;
  2588. remote_block_to_network(&rdma->block[i]);
  2589. }
  2590. blocks.len = rdma->local_ram_blocks.nb_blocks
  2591. * sizeof(RDMARemoteBlock);
  2592. ret = qemu_rdma_post_send_control(rdma,
  2593. (uint8_t *) rdma->block, &blocks);
  2594. if (ret < 0) {
  2595. fprintf(stderr, "rdma migration: error sending remote info!\n");
  2596. goto out;
  2597. }
  2598. break;
  2599. case RDMA_CONTROL_REGISTER_REQUEST:
  2600. DDPRINTF("There are %d registration requests\n", head.repeat);
  2601. reg_resp.repeat = head.repeat;
  2602. registers = (RDMARegister *) rdma->wr_data[idx].control_curr;
  2603. for (count = 0; count < head.repeat; count++) {
  2604. uint64_t chunk;
  2605. uint8_t *chunk_start, *chunk_end;
  2606. reg = &registers[count];
  2607. network_to_register(reg);
  2608. reg_result = &results[count];
  2609. DDPRINTF("Registration request (%d): index %d, current_addr %"
  2610. PRIu64 " chunks: %" PRIu64 "\n", count,
  2611. reg->current_index, reg->key.current_addr, reg->chunks);
  2612. block = &(rdma->local_ram_blocks.block[reg->current_index]);
  2613. if (block->is_ram_block) {
  2614. host_addr = (block->local_host_addr +
  2615. (reg->key.current_addr - block->offset));
  2616. chunk = ram_chunk_index(block->local_host_addr,
  2617. (uint8_t *) host_addr);
  2618. } else {
  2619. chunk = reg->key.chunk;
  2620. host_addr = block->local_host_addr +
  2621. (reg->key.chunk * (1UL << RDMA_REG_CHUNK_SHIFT));
  2622. }
  2623. chunk_start = ram_chunk_start(block, chunk);
  2624. chunk_end = ram_chunk_end(block, chunk + reg->chunks);
  2625. if (qemu_rdma_register_and_get_keys(rdma, block,
  2626. (uint8_t *)host_addr, NULL, &reg_result->rkey,
  2627. chunk, chunk_start, chunk_end)) {
  2628. fprintf(stderr, "cannot get rkey!\n");
  2629. ret = -EINVAL;
  2630. goto out;
  2631. }
  2632. reg_result->host_addr = (uint64_t) block->local_host_addr;
  2633. DDPRINTF("Registered rkey for this request: %x\n",
  2634. reg_result->rkey);
  2635. result_to_network(reg_result);
  2636. }
  2637. ret = qemu_rdma_post_send_control(rdma,
  2638. (uint8_t *) results, &reg_resp);
  2639. if (ret < 0) {
  2640. fprintf(stderr, "Failed to send control buffer!\n");
  2641. goto out;
  2642. }
  2643. break;
  2644. case RDMA_CONTROL_UNREGISTER_REQUEST:
  2645. DDPRINTF("There are %d unregistration requests\n", head.repeat);
  2646. unreg_resp.repeat = head.repeat;
  2647. registers = (RDMARegister *) rdma->wr_data[idx].control_curr;
  2648. for (count = 0; count < head.repeat; count++) {
  2649. reg = &registers[count];
  2650. network_to_register(reg);
  2651. DDPRINTF("Unregistration request (%d): "
  2652. " index %d, chunk %" PRIu64 "\n",
  2653. count, reg->current_index, reg->key.chunk);
  2654. block = &(rdma->local_ram_blocks.block[reg->current_index]);
  2655. ret = ibv_dereg_mr(block->pmr[reg->key.chunk]);
  2656. block->pmr[reg->key.chunk] = NULL;
  2657. if (ret != 0) {
  2658. perror("rdma unregistration chunk failed");
  2659. ret = -ret;
  2660. goto out;
  2661. }
  2662. rdma->total_registrations--;
  2663. DDPRINTF("Unregistered chunk %" PRIu64 " successfully.\n",
  2664. reg->key.chunk);
  2665. }
  2666. ret = qemu_rdma_post_send_control(rdma, NULL, &unreg_resp);
  2667. if (ret < 0) {
  2668. fprintf(stderr, "Failed to send control buffer!\n");
  2669. goto out;
  2670. }
  2671. break;
  2672. case RDMA_CONTROL_REGISTER_RESULT:
  2673. fprintf(stderr, "Invalid RESULT message at dest.\n");
  2674. ret = -EIO;
  2675. goto out;
  2676. default:
  2677. fprintf(stderr, "Unknown control message %s\n",
  2678. control_desc[head.type]);
  2679. ret = -EIO;
  2680. goto out;
  2681. }
  2682. } while (1);
  2683. out:
  2684. if (ret < 0) {
  2685. rdma->error_state = ret;
  2686. }
  2687. return ret;
  2688. }
  2689. static int qemu_rdma_registration_start(QEMUFile *f, void *opaque,
  2690. uint64_t flags)
  2691. {
  2692. QEMUFileRDMA *rfile = opaque;
  2693. RDMAContext *rdma = rfile->rdma;
  2694. CHECK_ERROR_STATE();
  2695. DDDPRINTF("start section: %" PRIu64 "\n", flags);
  2696. qemu_put_be64(f, RAM_SAVE_FLAG_HOOK);
  2697. qemu_fflush(f);
  2698. return 0;
  2699. }
  2700. /*
  2701. * Inform dest that dynamic registrations are done for now.
  2702. * First, flush writes, if any.
  2703. */
  2704. static int qemu_rdma_registration_stop(QEMUFile *f, void *opaque,
  2705. uint64_t flags)
  2706. {
  2707. Error *local_err = NULL, **errp = &local_err;
  2708. QEMUFileRDMA *rfile = opaque;
  2709. RDMAContext *rdma = rfile->rdma;
  2710. RDMAControlHeader head = { .len = 0, .repeat = 1 };
  2711. int ret = 0;
  2712. CHECK_ERROR_STATE();
  2713. qemu_fflush(f);
  2714. ret = qemu_rdma_drain_cq(f, rdma);
  2715. if (ret < 0) {
  2716. goto err;
  2717. }
  2718. if (flags == RAM_CONTROL_SETUP) {
  2719. RDMAControlHeader resp = {.type = RDMA_CONTROL_RAM_BLOCKS_RESULT };
  2720. RDMALocalBlocks *local = &rdma->local_ram_blocks;
  2721. int reg_result_idx, i, j, nb_remote_blocks;
  2722. head.type = RDMA_CONTROL_RAM_BLOCKS_REQUEST;
  2723. DPRINTF("Sending registration setup for ram blocks...\n");
  2724. /*
  2725. * Make sure that we parallelize the pinning on both sides.
  2726. * For very large guests, doing this serially takes a really
  2727. * long time, so we have to 'interleave' the pinning locally
  2728. * with the control messages by performing the pinning on this
  2729. * side before we receive the control response from the other
  2730. * side that the pinning has completed.
  2731. */
  2732. ret = qemu_rdma_exchange_send(rdma, &head, NULL, &resp,
  2733. &reg_result_idx, rdma->pin_all ?
  2734. qemu_rdma_reg_whole_ram_blocks : NULL);
  2735. if (ret < 0) {
  2736. ERROR(errp, "receiving remote info!");
  2737. return ret;
  2738. }
  2739. nb_remote_blocks = resp.len / sizeof(RDMARemoteBlock);
  2740. /*
  2741. * The protocol uses two different sets of rkeys (mutually exclusive):
  2742. * 1. One key to represent the virtual address of the entire ram block.
  2743. * (dynamic chunk registration disabled - pin everything with one rkey.)
  2744. * 2. One to represent individual chunks within a ram block.
  2745. * (dynamic chunk registration enabled - pin individual chunks.)
  2746. *
  2747. * Once the capability is successfully negotiated, the destination transmits
  2748. * the keys to use (or sends them later) including the virtual addresses
  2749. * and then propagates the remote ram block descriptions to his local copy.
  2750. */
  2751. if (local->nb_blocks != nb_remote_blocks) {
  2752. ERROR(errp, "ram blocks mismatch #1! "
  2753. "Your QEMU command line parameters are probably "
  2754. "not identical on both the source and destination.");
  2755. return -EINVAL;
  2756. }
  2757. qemu_rdma_move_header(rdma, reg_result_idx, &resp);
  2758. memcpy(rdma->block,
  2759. rdma->wr_data[reg_result_idx].control_curr, resp.len);
  2760. for (i = 0; i < nb_remote_blocks; i++) {
  2761. network_to_remote_block(&rdma->block[i]);
  2762. /* search local ram blocks */
  2763. for (j = 0; j < local->nb_blocks; j++) {
  2764. if (rdma->block[i].offset != local->block[j].offset) {
  2765. continue;
  2766. }
  2767. if (rdma->block[i].length != local->block[j].length) {
  2768. ERROR(errp, "ram blocks mismatch #2! "
  2769. "Your QEMU command line parameters are probably "
  2770. "not identical on both the source and destination.");
  2771. return -EINVAL;
  2772. }
  2773. local->block[j].remote_host_addr =
  2774. rdma->block[i].remote_host_addr;
  2775. local->block[j].remote_rkey = rdma->block[i].remote_rkey;
  2776. break;
  2777. }
  2778. if (j >= local->nb_blocks) {
  2779. ERROR(errp, "ram blocks mismatch #3! "
  2780. "Your QEMU command line parameters are probably "
  2781. "not identical on both the source and destination.");
  2782. return -EINVAL;
  2783. }
  2784. }
  2785. }
  2786. DDDPRINTF("Sending registration finish %" PRIu64 "...\n", flags);
  2787. head.type = RDMA_CONTROL_REGISTER_FINISHED;
  2788. ret = qemu_rdma_exchange_send(rdma, &head, NULL, NULL, NULL, NULL);
  2789. if (ret < 0) {
  2790. goto err;
  2791. }
  2792. return 0;
  2793. err:
  2794. rdma->error_state = ret;
  2795. return ret;
  2796. }
  2797. static int qemu_rdma_get_fd(void *opaque)
  2798. {
  2799. QEMUFileRDMA *rfile = opaque;
  2800. RDMAContext *rdma = rfile->rdma;
  2801. return rdma->comp_channel->fd;
  2802. }
  2803. const QEMUFileOps rdma_read_ops = {
  2804. .get_buffer = qemu_rdma_get_buffer,
  2805. .get_fd = qemu_rdma_get_fd,
  2806. .close = qemu_rdma_close,
  2807. .hook_ram_load = qemu_rdma_registration_handle,
  2808. };
  2809. const QEMUFileOps rdma_write_ops = {
  2810. .put_buffer = qemu_rdma_put_buffer,
  2811. .close = qemu_rdma_close,
  2812. .before_ram_iterate = qemu_rdma_registration_start,
  2813. .after_ram_iterate = qemu_rdma_registration_stop,
  2814. .save_page = qemu_rdma_save_page,
  2815. };
  2816. static void *qemu_fopen_rdma(RDMAContext *rdma, const char *mode)
  2817. {
  2818. QEMUFileRDMA *r = g_malloc0(sizeof(QEMUFileRDMA));
  2819. if (qemu_file_mode_is_not_valid(mode)) {
  2820. return NULL;
  2821. }
  2822. r->rdma = rdma;
  2823. if (mode[0] == 'w') {
  2824. r->file = qemu_fopen_ops(r, &rdma_write_ops);
  2825. } else {
  2826. r->file = qemu_fopen_ops(r, &rdma_read_ops);
  2827. }
  2828. return r->file;
  2829. }
  2830. static void rdma_accept_incoming_migration(void *opaque)
  2831. {
  2832. RDMAContext *rdma = opaque;
  2833. int ret;
  2834. QEMUFile *f;
  2835. Error *local_err = NULL, **errp = &local_err;
  2836. DPRINTF("Accepting rdma connection...\n");
  2837. ret = qemu_rdma_accept(rdma);
  2838. if (ret) {
  2839. ERROR(errp, "RDMA Migration initialization failed!");
  2840. return;
  2841. }
  2842. DPRINTF("Accepted migration\n");
  2843. f = qemu_fopen_rdma(rdma, "rb");
  2844. if (f == NULL) {
  2845. ERROR(errp, "could not qemu_fopen_rdma!");
  2846. qemu_rdma_cleanup(rdma);
  2847. return;
  2848. }
  2849. rdma->migration_started_on_destination = 1;
  2850. process_incoming_migration(f);
  2851. }
  2852. void rdma_start_incoming_migration(const char *host_port, Error **errp)
  2853. {
  2854. int ret;
  2855. RDMAContext *rdma;
  2856. Error *local_err = NULL;
  2857. DPRINTF("Starting RDMA-based incoming migration\n");
  2858. rdma = qemu_rdma_data_init(host_port, &local_err);
  2859. if (rdma == NULL) {
  2860. goto err;
  2861. }
  2862. ret = qemu_rdma_dest_init(rdma, &local_err);
  2863. if (ret) {
  2864. goto err;
  2865. }
  2866. DPRINTF("qemu_rdma_dest_init success\n");
  2867. ret = rdma_listen(rdma->listen_id, 5);
  2868. if (ret) {
  2869. ERROR(errp, "listening on socket!");
  2870. goto err;
  2871. }
  2872. DPRINTF("rdma_listen success\n");
  2873. qemu_set_fd_handler2(rdma->channel->fd, NULL,
  2874. rdma_accept_incoming_migration, NULL,
  2875. (void *)(intptr_t) rdma);
  2876. return;
  2877. err:
  2878. error_propagate(errp, local_err);
  2879. g_free(rdma);
  2880. }
  2881. void rdma_start_outgoing_migration(void *opaque,
  2882. const char *host_port, Error **errp)
  2883. {
  2884. MigrationState *s = opaque;
  2885. Error *local_err = NULL, **temp = &local_err;
  2886. RDMAContext *rdma = qemu_rdma_data_init(host_port, &local_err);
  2887. int ret = 0;
  2888. if (rdma == NULL) {
  2889. ERROR(temp, "Failed to initialize RDMA data structures! %d", ret);
  2890. goto err;
  2891. }
  2892. ret = qemu_rdma_source_init(rdma, &local_err,
  2893. s->enabled_capabilities[MIGRATION_CAPABILITY_RDMA_PIN_ALL]);
  2894. if (ret) {
  2895. goto err;
  2896. }
  2897. DPRINTF("qemu_rdma_source_init success\n");
  2898. ret = qemu_rdma_connect(rdma, &local_err);
  2899. if (ret) {
  2900. goto err;
  2901. }
  2902. DPRINTF("qemu_rdma_source_connect success\n");
  2903. s->file = qemu_fopen_rdma(rdma, "wb");
  2904. migrate_fd_connect(s);
  2905. return;
  2906. err:
  2907. error_propagate(errp, local_err);
  2908. g_free(rdma);
  2909. migrate_fd_error(s);
  2910. }