2
0

migration-rdma.c 105 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437
  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. ret = -EINVAL;
  823. goto err_resolve_get_addr;
  824. }
  825. rdma_ack_cm_event(cm_event);
  826. /* resolve route */
  827. ret = rdma_resolve_route(rdma->cm_id, RDMA_RESOLVE_TIMEOUT_MS);
  828. if (ret) {
  829. ERROR(errp, "could not resolve rdma route");
  830. goto err_resolve_get_addr;
  831. }
  832. ret = rdma_get_cm_event(rdma->channel, &cm_event);
  833. if (ret) {
  834. ERROR(errp, "could not perform event_route_resolved");
  835. goto err_resolve_get_addr;
  836. }
  837. if (cm_event->event != RDMA_CM_EVENT_ROUTE_RESOLVED) {
  838. ERROR(errp, "result not equal to event_route_resolved: %s",
  839. rdma_event_str(cm_event->event));
  840. rdma_ack_cm_event(cm_event);
  841. ret = -EINVAL;
  842. goto err_resolve_get_addr;
  843. }
  844. rdma_ack_cm_event(cm_event);
  845. rdma->verbs = rdma->cm_id->verbs;
  846. qemu_rdma_dump_id("source_resolve_host", rdma->cm_id->verbs);
  847. qemu_rdma_dump_gid("source_resolve_host", rdma->cm_id);
  848. return 0;
  849. err_resolve_get_addr:
  850. rdma_destroy_id(rdma->cm_id);
  851. rdma->cm_id = NULL;
  852. err_resolve_create_id:
  853. rdma_destroy_event_channel(rdma->channel);
  854. rdma->channel = NULL;
  855. return ret;
  856. }
  857. /*
  858. * Create protection domain and completion queues
  859. */
  860. static int qemu_rdma_alloc_pd_cq(RDMAContext *rdma)
  861. {
  862. /* allocate pd */
  863. rdma->pd = ibv_alloc_pd(rdma->verbs);
  864. if (!rdma->pd) {
  865. fprintf(stderr, "failed to allocate protection domain\n");
  866. return -1;
  867. }
  868. /* create completion channel */
  869. rdma->comp_channel = ibv_create_comp_channel(rdma->verbs);
  870. if (!rdma->comp_channel) {
  871. fprintf(stderr, "failed to allocate completion channel\n");
  872. goto err_alloc_pd_cq;
  873. }
  874. /*
  875. * Completion queue can be filled by both read and write work requests,
  876. * so must reflect the sum of both possible queue sizes.
  877. */
  878. rdma->cq = ibv_create_cq(rdma->verbs, (RDMA_SIGNALED_SEND_MAX * 3),
  879. NULL, rdma->comp_channel, 0);
  880. if (!rdma->cq) {
  881. fprintf(stderr, "failed to allocate completion queue\n");
  882. goto err_alloc_pd_cq;
  883. }
  884. return 0;
  885. err_alloc_pd_cq:
  886. if (rdma->pd) {
  887. ibv_dealloc_pd(rdma->pd);
  888. }
  889. if (rdma->comp_channel) {
  890. ibv_destroy_comp_channel(rdma->comp_channel);
  891. }
  892. rdma->pd = NULL;
  893. rdma->comp_channel = NULL;
  894. return -1;
  895. }
  896. /*
  897. * Create queue pairs.
  898. */
  899. static int qemu_rdma_alloc_qp(RDMAContext *rdma)
  900. {
  901. struct ibv_qp_init_attr attr = { 0 };
  902. int ret;
  903. attr.cap.max_send_wr = RDMA_SIGNALED_SEND_MAX;
  904. attr.cap.max_recv_wr = 3;
  905. attr.cap.max_send_sge = 1;
  906. attr.cap.max_recv_sge = 1;
  907. attr.send_cq = rdma->cq;
  908. attr.recv_cq = rdma->cq;
  909. attr.qp_type = IBV_QPT_RC;
  910. ret = rdma_create_qp(rdma->cm_id, rdma->pd, &attr);
  911. if (ret) {
  912. return -1;
  913. }
  914. rdma->qp = rdma->cm_id->qp;
  915. return 0;
  916. }
  917. static int qemu_rdma_reg_whole_ram_blocks(RDMAContext *rdma)
  918. {
  919. int i;
  920. RDMALocalBlocks *local = &rdma->local_ram_blocks;
  921. for (i = 0; i < local->nb_blocks; i++) {
  922. local->block[i].mr =
  923. ibv_reg_mr(rdma->pd,
  924. local->block[i].local_host_addr,
  925. local->block[i].length,
  926. IBV_ACCESS_LOCAL_WRITE |
  927. IBV_ACCESS_REMOTE_WRITE
  928. );
  929. if (!local->block[i].mr) {
  930. perror("Failed to register local dest ram block!\n");
  931. break;
  932. }
  933. rdma->total_registrations++;
  934. }
  935. if (i >= local->nb_blocks) {
  936. return 0;
  937. }
  938. for (i--; i >= 0; i--) {
  939. ibv_dereg_mr(local->block[i].mr);
  940. rdma->total_registrations--;
  941. }
  942. return -1;
  943. }
  944. /*
  945. * Find the ram block that corresponds to the page requested to be
  946. * transmitted by QEMU.
  947. *
  948. * Once the block is found, also identify which 'chunk' within that
  949. * block that the page belongs to.
  950. *
  951. * This search cannot fail or the migration will fail.
  952. */
  953. static int qemu_rdma_search_ram_block(RDMAContext *rdma,
  954. uint64_t block_offset,
  955. uint64_t offset,
  956. uint64_t length,
  957. uint64_t *block_index,
  958. uint64_t *chunk_index)
  959. {
  960. uint64_t current_addr = block_offset + offset;
  961. RDMALocalBlock *block = g_hash_table_lookup(rdma->blockmap,
  962. (void *) block_offset);
  963. assert(block);
  964. assert(current_addr >= block->offset);
  965. assert((current_addr + length) <= (block->offset + block->length));
  966. *block_index = block->index;
  967. *chunk_index = ram_chunk_index(block->local_host_addr,
  968. block->local_host_addr + (current_addr - block->offset));
  969. return 0;
  970. }
  971. /*
  972. * Register a chunk with IB. If the chunk was already registered
  973. * previously, then skip.
  974. *
  975. * Also return the keys associated with the registration needed
  976. * to perform the actual RDMA operation.
  977. */
  978. static int qemu_rdma_register_and_get_keys(RDMAContext *rdma,
  979. RDMALocalBlock *block, uint8_t *host_addr,
  980. uint32_t *lkey, uint32_t *rkey, int chunk,
  981. uint8_t *chunk_start, uint8_t *chunk_end)
  982. {
  983. if (block->mr) {
  984. if (lkey) {
  985. *lkey = block->mr->lkey;
  986. }
  987. if (rkey) {
  988. *rkey = block->mr->rkey;
  989. }
  990. return 0;
  991. }
  992. /* allocate memory to store chunk MRs */
  993. if (!block->pmr) {
  994. block->pmr = g_malloc0(block->nb_chunks * sizeof(struct ibv_mr *));
  995. if (!block->pmr) {
  996. return -1;
  997. }
  998. }
  999. /*
  1000. * If 'rkey', then we're the destination, so grant access to the source.
  1001. *
  1002. * If 'lkey', then we're the source VM, so grant access only to ourselves.
  1003. */
  1004. if (!block->pmr[chunk]) {
  1005. uint64_t len = chunk_end - chunk_start;
  1006. DDPRINTF("Registering %" PRIu64 " bytes @ %p\n",
  1007. len, chunk_start);
  1008. block->pmr[chunk] = ibv_reg_mr(rdma->pd,
  1009. chunk_start, len,
  1010. (rkey ? (IBV_ACCESS_LOCAL_WRITE |
  1011. IBV_ACCESS_REMOTE_WRITE) : 0));
  1012. if (!block->pmr[chunk]) {
  1013. perror("Failed to register chunk!");
  1014. fprintf(stderr, "Chunk details: block: %d chunk index %d"
  1015. " start %" PRIu64 " end %" PRIu64 " host %" PRIu64
  1016. " local %" PRIu64 " registrations: %d\n",
  1017. block->index, chunk, (uint64_t) chunk_start,
  1018. (uint64_t) chunk_end, (uint64_t) host_addr,
  1019. (uint64_t) block->local_host_addr,
  1020. rdma->total_registrations);
  1021. return -1;
  1022. }
  1023. rdma->total_registrations++;
  1024. }
  1025. if (lkey) {
  1026. *lkey = block->pmr[chunk]->lkey;
  1027. }
  1028. if (rkey) {
  1029. *rkey = block->pmr[chunk]->rkey;
  1030. }
  1031. return 0;
  1032. }
  1033. /*
  1034. * Register (at connection time) the memory used for control
  1035. * channel messages.
  1036. */
  1037. static int qemu_rdma_reg_control(RDMAContext *rdma, int idx)
  1038. {
  1039. rdma->wr_data[idx].control_mr = ibv_reg_mr(rdma->pd,
  1040. rdma->wr_data[idx].control, RDMA_CONTROL_MAX_BUFFER,
  1041. IBV_ACCESS_LOCAL_WRITE | IBV_ACCESS_REMOTE_WRITE);
  1042. if (rdma->wr_data[idx].control_mr) {
  1043. rdma->total_registrations++;
  1044. return 0;
  1045. }
  1046. fprintf(stderr, "qemu_rdma_reg_control failed!\n");
  1047. return -1;
  1048. }
  1049. const char *print_wrid(int wrid)
  1050. {
  1051. if (wrid >= RDMA_WRID_RECV_CONTROL) {
  1052. return wrid_desc[RDMA_WRID_RECV_CONTROL];
  1053. }
  1054. return wrid_desc[wrid];
  1055. }
  1056. /*
  1057. * RDMA requires memory registration (mlock/pinning), but this is not good for
  1058. * overcommitment.
  1059. *
  1060. * In preparation for the future where LRU information or workload-specific
  1061. * writable writable working set memory access behavior is available to QEMU
  1062. * it would be nice to have in place the ability to UN-register/UN-pin
  1063. * particular memory regions from the RDMA hardware when it is determine that
  1064. * those regions of memory will likely not be accessed again in the near future.
  1065. *
  1066. * While we do not yet have such information right now, the following
  1067. * compile-time option allows us to perform a non-optimized version of this
  1068. * behavior.
  1069. *
  1070. * By uncommenting this option, you will cause *all* RDMA transfers to be
  1071. * unregistered immediately after the transfer completes on both sides of the
  1072. * connection. This has no effect in 'rdma-pin-all' mode, only regular mode.
  1073. *
  1074. * This will have a terrible impact on migration performance, so until future
  1075. * workload information or LRU information is available, do not attempt to use
  1076. * this feature except for basic testing.
  1077. */
  1078. //#define RDMA_UNREGISTRATION_EXAMPLE
  1079. /*
  1080. * Perform a non-optimized memory unregistration after every transfer
  1081. * for demonsration purposes, only if pin-all is not requested.
  1082. *
  1083. * Potential optimizations:
  1084. * 1. Start a new thread to run this function continuously
  1085. - for bit clearing
  1086. - and for receipt of unregister messages
  1087. * 2. Use an LRU.
  1088. * 3. Use workload hints.
  1089. */
  1090. static int qemu_rdma_unregister_waiting(RDMAContext *rdma)
  1091. {
  1092. while (rdma->unregistrations[rdma->unregister_current]) {
  1093. int ret;
  1094. uint64_t wr_id = rdma->unregistrations[rdma->unregister_current];
  1095. uint64_t chunk =
  1096. (wr_id & RDMA_WRID_CHUNK_MASK) >> RDMA_WRID_CHUNK_SHIFT;
  1097. uint64_t index =
  1098. (wr_id & RDMA_WRID_BLOCK_MASK) >> RDMA_WRID_BLOCK_SHIFT;
  1099. RDMALocalBlock *block =
  1100. &(rdma->local_ram_blocks.block[index]);
  1101. RDMARegister reg = { .current_index = index };
  1102. RDMAControlHeader resp = { .type = RDMA_CONTROL_UNREGISTER_FINISHED,
  1103. };
  1104. RDMAControlHeader head = { .len = sizeof(RDMARegister),
  1105. .type = RDMA_CONTROL_UNREGISTER_REQUEST,
  1106. .repeat = 1,
  1107. };
  1108. DDPRINTF("Processing unregister for chunk: %" PRIu64
  1109. " at position %d\n", chunk, rdma->unregister_current);
  1110. rdma->unregistrations[rdma->unregister_current] = 0;
  1111. rdma->unregister_current++;
  1112. if (rdma->unregister_current == RDMA_SIGNALED_SEND_MAX) {
  1113. rdma->unregister_current = 0;
  1114. }
  1115. /*
  1116. * Unregistration is speculative (because migration is single-threaded
  1117. * and we cannot break the protocol's inifinband message ordering).
  1118. * Thus, if the memory is currently being used for transmission,
  1119. * then abort the attempt to unregister and try again
  1120. * later the next time a completion is received for this memory.
  1121. */
  1122. clear_bit(chunk, block->unregister_bitmap);
  1123. if (test_bit(chunk, block->transit_bitmap)) {
  1124. DDPRINTF("Cannot unregister inflight chunk: %" PRIu64 "\n", chunk);
  1125. continue;
  1126. }
  1127. DDPRINTF("Sending unregister for chunk: %" PRIu64 "\n", chunk);
  1128. ret = ibv_dereg_mr(block->pmr[chunk]);
  1129. block->pmr[chunk] = NULL;
  1130. block->remote_keys[chunk] = 0;
  1131. if (ret != 0) {
  1132. perror("unregistration chunk failed");
  1133. return -ret;
  1134. }
  1135. rdma->total_registrations--;
  1136. reg.key.chunk = chunk;
  1137. register_to_network(&reg);
  1138. ret = qemu_rdma_exchange_send(rdma, &head, (uint8_t *) &reg,
  1139. &resp, NULL, NULL);
  1140. if (ret < 0) {
  1141. return ret;
  1142. }
  1143. DDPRINTF("Unregister for chunk: %" PRIu64 " complete.\n", chunk);
  1144. }
  1145. return 0;
  1146. }
  1147. static uint64_t qemu_rdma_make_wrid(uint64_t wr_id, uint64_t index,
  1148. uint64_t chunk)
  1149. {
  1150. uint64_t result = wr_id & RDMA_WRID_TYPE_MASK;
  1151. result |= (index << RDMA_WRID_BLOCK_SHIFT);
  1152. result |= (chunk << RDMA_WRID_CHUNK_SHIFT);
  1153. return result;
  1154. }
  1155. /*
  1156. * Set bit for unregistration in the next iteration.
  1157. * We cannot transmit right here, but will unpin later.
  1158. */
  1159. static void qemu_rdma_signal_unregister(RDMAContext *rdma, uint64_t index,
  1160. uint64_t chunk, uint64_t wr_id)
  1161. {
  1162. if (rdma->unregistrations[rdma->unregister_next] != 0) {
  1163. fprintf(stderr, "rdma migration: queue is full!\n");
  1164. } else {
  1165. RDMALocalBlock *block = &(rdma->local_ram_blocks.block[index]);
  1166. if (!test_and_set_bit(chunk, block->unregister_bitmap)) {
  1167. DDPRINTF("Appending unregister chunk %" PRIu64
  1168. " at position %d\n", chunk, rdma->unregister_next);
  1169. rdma->unregistrations[rdma->unregister_next++] =
  1170. qemu_rdma_make_wrid(wr_id, index, chunk);
  1171. if (rdma->unregister_next == RDMA_SIGNALED_SEND_MAX) {
  1172. rdma->unregister_next = 0;
  1173. }
  1174. } else {
  1175. DDPRINTF("Unregister chunk %" PRIu64 " already in queue.\n",
  1176. chunk);
  1177. }
  1178. }
  1179. }
  1180. /*
  1181. * Consult the connection manager to see a work request
  1182. * (of any kind) has completed.
  1183. * Return the work request ID that completed.
  1184. */
  1185. static uint64_t qemu_rdma_poll(RDMAContext *rdma, uint64_t *wr_id_out,
  1186. uint32_t *byte_len)
  1187. {
  1188. int ret;
  1189. struct ibv_wc wc;
  1190. uint64_t wr_id;
  1191. ret = ibv_poll_cq(rdma->cq, 1, &wc);
  1192. if (!ret) {
  1193. *wr_id_out = RDMA_WRID_NONE;
  1194. return 0;
  1195. }
  1196. if (ret < 0) {
  1197. fprintf(stderr, "ibv_poll_cq return %d!\n", ret);
  1198. return ret;
  1199. }
  1200. wr_id = wc.wr_id & RDMA_WRID_TYPE_MASK;
  1201. if (wc.status != IBV_WC_SUCCESS) {
  1202. fprintf(stderr, "ibv_poll_cq wc.status=%d %s!\n",
  1203. wc.status, ibv_wc_status_str(wc.status));
  1204. fprintf(stderr, "ibv_poll_cq wrid=%s!\n", wrid_desc[wr_id]);
  1205. return -1;
  1206. }
  1207. if (rdma->control_ready_expected &&
  1208. (wr_id >= RDMA_WRID_RECV_CONTROL)) {
  1209. DDDPRINTF("completion %s #%" PRId64 " received (%" PRId64 ")"
  1210. " left %d\n", wrid_desc[RDMA_WRID_RECV_CONTROL],
  1211. wr_id - RDMA_WRID_RECV_CONTROL, wr_id, rdma->nb_sent);
  1212. rdma->control_ready_expected = 0;
  1213. }
  1214. if (wr_id == RDMA_WRID_RDMA_WRITE) {
  1215. uint64_t chunk =
  1216. (wc.wr_id & RDMA_WRID_CHUNK_MASK) >> RDMA_WRID_CHUNK_SHIFT;
  1217. uint64_t index =
  1218. (wc.wr_id & RDMA_WRID_BLOCK_MASK) >> RDMA_WRID_BLOCK_SHIFT;
  1219. RDMALocalBlock *block = &(rdma->local_ram_blocks.block[index]);
  1220. DDDPRINTF("completions %s (%" PRId64 ") left %d, "
  1221. "block %" PRIu64 ", chunk: %" PRIu64 " %p %p\n",
  1222. print_wrid(wr_id), wr_id, rdma->nb_sent, index, chunk,
  1223. block->local_host_addr, (void *)block->remote_host_addr);
  1224. clear_bit(chunk, block->transit_bitmap);
  1225. if (rdma->nb_sent > 0) {
  1226. rdma->nb_sent--;
  1227. }
  1228. if (!rdma->pin_all) {
  1229. /*
  1230. * FYI: If one wanted to signal a specific chunk to be unregistered
  1231. * using LRU or workload-specific information, this is the function
  1232. * you would call to do so. That chunk would then get asynchronously
  1233. * unregistered later.
  1234. */
  1235. #ifdef RDMA_UNREGISTRATION_EXAMPLE
  1236. qemu_rdma_signal_unregister(rdma, index, chunk, wc.wr_id);
  1237. #endif
  1238. }
  1239. } else {
  1240. DDDPRINTF("other completion %s (%" PRId64 ") received left %d\n",
  1241. print_wrid(wr_id), wr_id, rdma->nb_sent);
  1242. }
  1243. *wr_id_out = wc.wr_id;
  1244. if (byte_len) {
  1245. *byte_len = wc.byte_len;
  1246. }
  1247. return 0;
  1248. }
  1249. /*
  1250. * Block until the next work request has completed.
  1251. *
  1252. * First poll to see if a work request has already completed,
  1253. * otherwise block.
  1254. *
  1255. * If we encounter completed work requests for IDs other than
  1256. * the one we're interested in, then that's generally an error.
  1257. *
  1258. * The only exception is actual RDMA Write completions. These
  1259. * completions only need to be recorded, but do not actually
  1260. * need further processing.
  1261. */
  1262. static int qemu_rdma_block_for_wrid(RDMAContext *rdma, int wrid_requested,
  1263. uint32_t *byte_len)
  1264. {
  1265. int num_cq_events = 0, ret = 0;
  1266. struct ibv_cq *cq;
  1267. void *cq_ctx;
  1268. uint64_t wr_id = RDMA_WRID_NONE, wr_id_in;
  1269. if (ibv_req_notify_cq(rdma->cq, 0)) {
  1270. return -1;
  1271. }
  1272. /* poll cq first */
  1273. while (wr_id != wrid_requested) {
  1274. ret = qemu_rdma_poll(rdma, &wr_id_in, byte_len);
  1275. if (ret < 0) {
  1276. return ret;
  1277. }
  1278. wr_id = wr_id_in & RDMA_WRID_TYPE_MASK;
  1279. if (wr_id == RDMA_WRID_NONE) {
  1280. break;
  1281. }
  1282. if (wr_id != wrid_requested) {
  1283. DDDPRINTF("A Wanted wrid %s (%d) but got %s (%" PRIu64 ")\n",
  1284. print_wrid(wrid_requested),
  1285. wrid_requested, print_wrid(wr_id), wr_id);
  1286. }
  1287. }
  1288. if (wr_id == wrid_requested) {
  1289. return 0;
  1290. }
  1291. while (1) {
  1292. /*
  1293. * Coroutine doesn't start until process_incoming_migration()
  1294. * so don't yield unless we know we're running inside of a coroutine.
  1295. */
  1296. if (rdma->migration_started_on_destination) {
  1297. yield_until_fd_readable(rdma->comp_channel->fd);
  1298. }
  1299. if (ibv_get_cq_event(rdma->comp_channel, &cq, &cq_ctx)) {
  1300. perror("ibv_get_cq_event");
  1301. goto err_block_for_wrid;
  1302. }
  1303. num_cq_events++;
  1304. if (ibv_req_notify_cq(cq, 0)) {
  1305. goto err_block_for_wrid;
  1306. }
  1307. while (wr_id != wrid_requested) {
  1308. ret = qemu_rdma_poll(rdma, &wr_id_in, byte_len);
  1309. if (ret < 0) {
  1310. goto err_block_for_wrid;
  1311. }
  1312. wr_id = wr_id_in & RDMA_WRID_TYPE_MASK;
  1313. if (wr_id == RDMA_WRID_NONE) {
  1314. break;
  1315. }
  1316. if (wr_id != wrid_requested) {
  1317. DDDPRINTF("B Wanted wrid %s (%d) but got %s (%" PRIu64 ")\n",
  1318. print_wrid(wrid_requested), wrid_requested,
  1319. print_wrid(wr_id), wr_id);
  1320. }
  1321. }
  1322. if (wr_id == wrid_requested) {
  1323. goto success_block_for_wrid;
  1324. }
  1325. }
  1326. success_block_for_wrid:
  1327. if (num_cq_events) {
  1328. ibv_ack_cq_events(cq, num_cq_events);
  1329. }
  1330. return 0;
  1331. err_block_for_wrid:
  1332. if (num_cq_events) {
  1333. ibv_ack_cq_events(cq, num_cq_events);
  1334. }
  1335. return ret;
  1336. }
  1337. /*
  1338. * Post a SEND message work request for the control channel
  1339. * containing some data and block until the post completes.
  1340. */
  1341. static int qemu_rdma_post_send_control(RDMAContext *rdma, uint8_t *buf,
  1342. RDMAControlHeader *head)
  1343. {
  1344. int ret = 0;
  1345. RDMAWorkRequestData *wr = &rdma->wr_data[RDMA_WRID_CONTROL];
  1346. struct ibv_send_wr *bad_wr;
  1347. struct ibv_sge sge = {
  1348. .addr = (uint64_t)(wr->control),
  1349. .length = head->len + sizeof(RDMAControlHeader),
  1350. .lkey = wr->control_mr->lkey,
  1351. };
  1352. struct ibv_send_wr send_wr = {
  1353. .wr_id = RDMA_WRID_SEND_CONTROL,
  1354. .opcode = IBV_WR_SEND,
  1355. .send_flags = IBV_SEND_SIGNALED,
  1356. .sg_list = &sge,
  1357. .num_sge = 1,
  1358. };
  1359. DDDPRINTF("CONTROL: sending %s..\n", control_desc[head->type]);
  1360. /*
  1361. * We don't actually need to do a memcpy() in here if we used
  1362. * the "sge" properly, but since we're only sending control messages
  1363. * (not RAM in a performance-critical path), then its OK for now.
  1364. *
  1365. * The copy makes the RDMAControlHeader simpler to manipulate
  1366. * for the time being.
  1367. */
  1368. assert(head->len <= RDMA_CONTROL_MAX_BUFFER - sizeof(*head));
  1369. memcpy(wr->control, head, sizeof(RDMAControlHeader));
  1370. control_to_network((void *) wr->control);
  1371. if (buf) {
  1372. memcpy(wr->control + sizeof(RDMAControlHeader), buf, head->len);
  1373. }
  1374. ret = ibv_post_send(rdma->qp, &send_wr, &bad_wr);
  1375. if (ret > 0) {
  1376. fprintf(stderr, "Failed to use post IB SEND for control!\n");
  1377. return -ret;
  1378. }
  1379. ret = qemu_rdma_block_for_wrid(rdma, RDMA_WRID_SEND_CONTROL, NULL);
  1380. if (ret < 0) {
  1381. fprintf(stderr, "rdma migration: send polling control error!\n");
  1382. }
  1383. return ret;
  1384. }
  1385. /*
  1386. * Post a RECV work request in anticipation of some future receipt
  1387. * of data on the control channel.
  1388. */
  1389. static int qemu_rdma_post_recv_control(RDMAContext *rdma, int idx)
  1390. {
  1391. struct ibv_recv_wr *bad_wr;
  1392. struct ibv_sge sge = {
  1393. .addr = (uint64_t)(rdma->wr_data[idx].control),
  1394. .length = RDMA_CONTROL_MAX_BUFFER,
  1395. .lkey = rdma->wr_data[idx].control_mr->lkey,
  1396. };
  1397. struct ibv_recv_wr recv_wr = {
  1398. .wr_id = RDMA_WRID_RECV_CONTROL + idx,
  1399. .sg_list = &sge,
  1400. .num_sge = 1,
  1401. };
  1402. if (ibv_post_recv(rdma->qp, &recv_wr, &bad_wr)) {
  1403. return -1;
  1404. }
  1405. return 0;
  1406. }
  1407. /*
  1408. * Block and wait for a RECV control channel message to arrive.
  1409. */
  1410. static int qemu_rdma_exchange_get_response(RDMAContext *rdma,
  1411. RDMAControlHeader *head, int expecting, int idx)
  1412. {
  1413. uint32_t byte_len;
  1414. int ret = qemu_rdma_block_for_wrid(rdma, RDMA_WRID_RECV_CONTROL + idx,
  1415. &byte_len);
  1416. if (ret < 0) {
  1417. fprintf(stderr, "rdma migration: recv polling control error!\n");
  1418. return ret;
  1419. }
  1420. network_to_control((void *) rdma->wr_data[idx].control);
  1421. memcpy(head, rdma->wr_data[idx].control, sizeof(RDMAControlHeader));
  1422. DDDPRINTF("CONTROL: %s receiving...\n", control_desc[expecting]);
  1423. if (expecting == RDMA_CONTROL_NONE) {
  1424. DDDPRINTF("Surprise: got %s (%d)\n",
  1425. control_desc[head->type], head->type);
  1426. } else if (head->type != expecting || head->type == RDMA_CONTROL_ERROR) {
  1427. fprintf(stderr, "Was expecting a %s (%d) control message"
  1428. ", but got: %s (%d), length: %d\n",
  1429. control_desc[expecting], expecting,
  1430. control_desc[head->type], head->type, head->len);
  1431. return -EIO;
  1432. }
  1433. if (head->len > RDMA_CONTROL_MAX_BUFFER - sizeof(*head)) {
  1434. fprintf(stderr, "too long length: %d\n", head->len);
  1435. return -EINVAL;
  1436. }
  1437. if (sizeof(*head) + head->len != byte_len) {
  1438. fprintf(stderr, "Malformed length: %d byte_len %d\n",
  1439. head->len, byte_len);
  1440. return -EINVAL;
  1441. }
  1442. return 0;
  1443. }
  1444. /*
  1445. * When a RECV work request has completed, the work request's
  1446. * buffer is pointed at the header.
  1447. *
  1448. * This will advance the pointer to the data portion
  1449. * of the control message of the work request's buffer that
  1450. * was populated after the work request finished.
  1451. */
  1452. static void qemu_rdma_move_header(RDMAContext *rdma, int idx,
  1453. RDMAControlHeader *head)
  1454. {
  1455. rdma->wr_data[idx].control_len = head->len;
  1456. rdma->wr_data[idx].control_curr =
  1457. rdma->wr_data[idx].control + sizeof(RDMAControlHeader);
  1458. }
  1459. /*
  1460. * This is an 'atomic' high-level operation to deliver a single, unified
  1461. * control-channel message.
  1462. *
  1463. * Additionally, if the user is expecting some kind of reply to this message,
  1464. * they can request a 'resp' response message be filled in by posting an
  1465. * additional work request on behalf of the user and waiting for an additional
  1466. * completion.
  1467. *
  1468. * The extra (optional) response is used during registration to us from having
  1469. * to perform an *additional* exchange of message just to provide a response by
  1470. * instead piggy-backing on the acknowledgement.
  1471. */
  1472. static int qemu_rdma_exchange_send(RDMAContext *rdma, RDMAControlHeader *head,
  1473. uint8_t *data, RDMAControlHeader *resp,
  1474. int *resp_idx,
  1475. int (*callback)(RDMAContext *rdma))
  1476. {
  1477. int ret = 0;
  1478. /*
  1479. * Wait until the dest is ready before attempting to deliver the message
  1480. * by waiting for a READY message.
  1481. */
  1482. if (rdma->control_ready_expected) {
  1483. RDMAControlHeader resp;
  1484. ret = qemu_rdma_exchange_get_response(rdma,
  1485. &resp, RDMA_CONTROL_READY, RDMA_WRID_READY);
  1486. if (ret < 0) {
  1487. return ret;
  1488. }
  1489. }
  1490. /*
  1491. * If the user is expecting a response, post a WR in anticipation of it.
  1492. */
  1493. if (resp) {
  1494. ret = qemu_rdma_post_recv_control(rdma, RDMA_WRID_DATA);
  1495. if (ret) {
  1496. fprintf(stderr, "rdma migration: error posting"
  1497. " extra control recv for anticipated result!");
  1498. return ret;
  1499. }
  1500. }
  1501. /*
  1502. * Post a WR to replace the one we just consumed for the READY message.
  1503. */
  1504. ret = qemu_rdma_post_recv_control(rdma, RDMA_WRID_READY);
  1505. if (ret) {
  1506. fprintf(stderr, "rdma migration: error posting first control recv!");
  1507. return ret;
  1508. }
  1509. /*
  1510. * Deliver the control message that was requested.
  1511. */
  1512. ret = qemu_rdma_post_send_control(rdma, data, head);
  1513. if (ret < 0) {
  1514. fprintf(stderr, "Failed to send control buffer!\n");
  1515. return ret;
  1516. }
  1517. /*
  1518. * If we're expecting a response, block and wait for it.
  1519. */
  1520. if (resp) {
  1521. if (callback) {
  1522. DDPRINTF("Issuing callback before receiving response...\n");
  1523. ret = callback(rdma);
  1524. if (ret < 0) {
  1525. return ret;
  1526. }
  1527. }
  1528. DDPRINTF("Waiting for response %s\n", control_desc[resp->type]);
  1529. ret = qemu_rdma_exchange_get_response(rdma, resp,
  1530. resp->type, RDMA_WRID_DATA);
  1531. if (ret < 0) {
  1532. return ret;
  1533. }
  1534. qemu_rdma_move_header(rdma, RDMA_WRID_DATA, resp);
  1535. if (resp_idx) {
  1536. *resp_idx = RDMA_WRID_DATA;
  1537. }
  1538. DDPRINTF("Response %s received.\n", control_desc[resp->type]);
  1539. }
  1540. rdma->control_ready_expected = 1;
  1541. return 0;
  1542. }
  1543. /*
  1544. * This is an 'atomic' high-level operation to receive a single, unified
  1545. * control-channel message.
  1546. */
  1547. static int qemu_rdma_exchange_recv(RDMAContext *rdma, RDMAControlHeader *head,
  1548. int expecting)
  1549. {
  1550. RDMAControlHeader ready = {
  1551. .len = 0,
  1552. .type = RDMA_CONTROL_READY,
  1553. .repeat = 1,
  1554. };
  1555. int ret;
  1556. /*
  1557. * Inform the source that we're ready to receive a message.
  1558. */
  1559. ret = qemu_rdma_post_send_control(rdma, NULL, &ready);
  1560. if (ret < 0) {
  1561. fprintf(stderr, "Failed to send control buffer!\n");
  1562. return ret;
  1563. }
  1564. /*
  1565. * Block and wait for the message.
  1566. */
  1567. ret = qemu_rdma_exchange_get_response(rdma, head,
  1568. expecting, RDMA_WRID_READY);
  1569. if (ret < 0) {
  1570. return ret;
  1571. }
  1572. qemu_rdma_move_header(rdma, RDMA_WRID_READY, head);
  1573. /*
  1574. * Post a new RECV work request to replace the one we just consumed.
  1575. */
  1576. ret = qemu_rdma_post_recv_control(rdma, RDMA_WRID_READY);
  1577. if (ret) {
  1578. fprintf(stderr, "rdma migration: error posting second control recv!");
  1579. return ret;
  1580. }
  1581. return 0;
  1582. }
  1583. /*
  1584. * Write an actual chunk of memory using RDMA.
  1585. *
  1586. * If we're using dynamic registration on the dest-side, we have to
  1587. * send a registration command first.
  1588. */
  1589. static int qemu_rdma_write_one(QEMUFile *f, RDMAContext *rdma,
  1590. int current_index, uint64_t current_addr,
  1591. uint64_t length)
  1592. {
  1593. struct ibv_sge sge;
  1594. struct ibv_send_wr send_wr = { 0 };
  1595. struct ibv_send_wr *bad_wr;
  1596. int reg_result_idx, ret, count = 0;
  1597. uint64_t chunk, chunks;
  1598. uint8_t *chunk_start, *chunk_end;
  1599. RDMALocalBlock *block = &(rdma->local_ram_blocks.block[current_index]);
  1600. RDMARegister reg;
  1601. RDMARegisterResult *reg_result;
  1602. RDMAControlHeader resp = { .type = RDMA_CONTROL_REGISTER_RESULT };
  1603. RDMAControlHeader head = { .len = sizeof(RDMARegister),
  1604. .type = RDMA_CONTROL_REGISTER_REQUEST,
  1605. .repeat = 1,
  1606. };
  1607. retry:
  1608. sge.addr = (uint64_t)(block->local_host_addr +
  1609. (current_addr - block->offset));
  1610. sge.length = length;
  1611. chunk = ram_chunk_index(block->local_host_addr, (uint8_t *) sge.addr);
  1612. chunk_start = ram_chunk_start(block, chunk);
  1613. if (block->is_ram_block) {
  1614. chunks = length / (1UL << RDMA_REG_CHUNK_SHIFT);
  1615. if (chunks && ((length % (1UL << RDMA_REG_CHUNK_SHIFT)) == 0)) {
  1616. chunks--;
  1617. }
  1618. } else {
  1619. chunks = block->length / (1UL << RDMA_REG_CHUNK_SHIFT);
  1620. if (chunks && ((block->length % (1UL << RDMA_REG_CHUNK_SHIFT)) == 0)) {
  1621. chunks--;
  1622. }
  1623. }
  1624. DDPRINTF("Writing %" PRIu64 " chunks, (%" PRIu64 " MB)\n",
  1625. chunks + 1, (chunks + 1) * (1UL << RDMA_REG_CHUNK_SHIFT) / 1024 / 1024);
  1626. chunk_end = ram_chunk_end(block, chunk + chunks);
  1627. if (!rdma->pin_all) {
  1628. #ifdef RDMA_UNREGISTRATION_EXAMPLE
  1629. qemu_rdma_unregister_waiting(rdma);
  1630. #endif
  1631. }
  1632. while (test_bit(chunk, block->transit_bitmap)) {
  1633. (void)count;
  1634. DDPRINTF("(%d) Not clobbering: block: %d chunk %" PRIu64
  1635. " current %" PRIu64 " len %" PRIu64 " %d %d\n",
  1636. count++, current_index, chunk,
  1637. sge.addr, length, rdma->nb_sent, block->nb_chunks);
  1638. ret = qemu_rdma_block_for_wrid(rdma, RDMA_WRID_RDMA_WRITE, NULL);
  1639. if (ret < 0) {
  1640. fprintf(stderr, "Failed to Wait for previous write to complete "
  1641. "block %d chunk %" PRIu64
  1642. " current %" PRIu64 " len %" PRIu64 " %d\n",
  1643. current_index, chunk, sge.addr, length, rdma->nb_sent);
  1644. return ret;
  1645. }
  1646. }
  1647. if (!rdma->pin_all || !block->is_ram_block) {
  1648. if (!block->remote_keys[chunk]) {
  1649. /*
  1650. * This chunk has not yet been registered, so first check to see
  1651. * if the entire chunk is zero. If so, tell the other size to
  1652. * memset() + madvise() the entire chunk without RDMA.
  1653. */
  1654. if (can_use_buffer_find_nonzero_offset((void *)sge.addr, length)
  1655. && buffer_find_nonzero_offset((void *)sge.addr,
  1656. length) == length) {
  1657. RDMACompress comp = {
  1658. .offset = current_addr,
  1659. .value = 0,
  1660. .block_idx = current_index,
  1661. .length = length,
  1662. };
  1663. head.len = sizeof(comp);
  1664. head.type = RDMA_CONTROL_COMPRESS;
  1665. DDPRINTF("Entire chunk is zero, sending compress: %"
  1666. PRIu64 " for %d "
  1667. "bytes, index: %d, offset: %" PRId64 "...\n",
  1668. chunk, sge.length, current_index, current_addr);
  1669. compress_to_network(&comp);
  1670. ret = qemu_rdma_exchange_send(rdma, &head,
  1671. (uint8_t *) &comp, NULL, NULL, NULL);
  1672. if (ret < 0) {
  1673. return -EIO;
  1674. }
  1675. acct_update_position(f, sge.length, true);
  1676. return 1;
  1677. }
  1678. /*
  1679. * Otherwise, tell other side to register.
  1680. */
  1681. reg.current_index = current_index;
  1682. if (block->is_ram_block) {
  1683. reg.key.current_addr = current_addr;
  1684. } else {
  1685. reg.key.chunk = chunk;
  1686. }
  1687. reg.chunks = chunks;
  1688. DDPRINTF("Sending registration request chunk %" PRIu64 " for %d "
  1689. "bytes, index: %d, offset: %" PRId64 "...\n",
  1690. chunk, sge.length, current_index, current_addr);
  1691. register_to_network(&reg);
  1692. ret = qemu_rdma_exchange_send(rdma, &head, (uint8_t *) &reg,
  1693. &resp, &reg_result_idx, NULL);
  1694. if (ret < 0) {
  1695. return ret;
  1696. }
  1697. /* try to overlap this single registration with the one we sent. */
  1698. if (qemu_rdma_register_and_get_keys(rdma, block,
  1699. (uint8_t *) sge.addr,
  1700. &sge.lkey, NULL, chunk,
  1701. chunk_start, chunk_end)) {
  1702. fprintf(stderr, "cannot get lkey!\n");
  1703. return -EINVAL;
  1704. }
  1705. reg_result = (RDMARegisterResult *)
  1706. rdma->wr_data[reg_result_idx].control_curr;
  1707. network_to_result(reg_result);
  1708. DDPRINTF("Received registration result:"
  1709. " my key: %x their key %x, chunk %" PRIu64 "\n",
  1710. block->remote_keys[chunk], reg_result->rkey, chunk);
  1711. block->remote_keys[chunk] = reg_result->rkey;
  1712. block->remote_host_addr = reg_result->host_addr;
  1713. } else {
  1714. /* already registered before */
  1715. if (qemu_rdma_register_and_get_keys(rdma, block,
  1716. (uint8_t *)sge.addr,
  1717. &sge.lkey, NULL, chunk,
  1718. chunk_start, chunk_end)) {
  1719. fprintf(stderr, "cannot get lkey!\n");
  1720. return -EINVAL;
  1721. }
  1722. }
  1723. send_wr.wr.rdma.rkey = block->remote_keys[chunk];
  1724. } else {
  1725. send_wr.wr.rdma.rkey = block->remote_rkey;
  1726. if (qemu_rdma_register_and_get_keys(rdma, block, (uint8_t *)sge.addr,
  1727. &sge.lkey, NULL, chunk,
  1728. chunk_start, chunk_end)) {
  1729. fprintf(stderr, "cannot get lkey!\n");
  1730. return -EINVAL;
  1731. }
  1732. }
  1733. /*
  1734. * Encode the ram block index and chunk within this wrid.
  1735. * We will use this information at the time of completion
  1736. * to figure out which bitmap to check against and then which
  1737. * chunk in the bitmap to look for.
  1738. */
  1739. send_wr.wr_id = qemu_rdma_make_wrid(RDMA_WRID_RDMA_WRITE,
  1740. current_index, chunk);
  1741. send_wr.opcode = IBV_WR_RDMA_WRITE;
  1742. send_wr.send_flags = IBV_SEND_SIGNALED;
  1743. send_wr.sg_list = &sge;
  1744. send_wr.num_sge = 1;
  1745. send_wr.wr.rdma.remote_addr = block->remote_host_addr +
  1746. (current_addr - block->offset);
  1747. DDDPRINTF("Posting chunk: %" PRIu64 ", addr: %lx"
  1748. " remote: %lx, bytes %" PRIu32 "\n",
  1749. chunk, sge.addr, send_wr.wr.rdma.remote_addr,
  1750. sge.length);
  1751. /*
  1752. * ibv_post_send() does not return negative error numbers,
  1753. * per the specification they are positive - no idea why.
  1754. */
  1755. ret = ibv_post_send(rdma->qp, &send_wr, &bad_wr);
  1756. if (ret == ENOMEM) {
  1757. DDPRINTF("send queue is full. wait a little....\n");
  1758. ret = qemu_rdma_block_for_wrid(rdma, RDMA_WRID_RDMA_WRITE, NULL);
  1759. if (ret < 0) {
  1760. fprintf(stderr, "rdma migration: failed to make "
  1761. "room in full send queue! %d\n", ret);
  1762. return ret;
  1763. }
  1764. goto retry;
  1765. } else if (ret > 0) {
  1766. perror("rdma migration: post rdma write failed");
  1767. return -ret;
  1768. }
  1769. set_bit(chunk, block->transit_bitmap);
  1770. acct_update_position(f, sge.length, false);
  1771. rdma->total_writes++;
  1772. return 0;
  1773. }
  1774. /*
  1775. * Push out any unwritten RDMA operations.
  1776. *
  1777. * We support sending out multiple chunks at the same time.
  1778. * Not all of them need to get signaled in the completion queue.
  1779. */
  1780. static int qemu_rdma_write_flush(QEMUFile *f, RDMAContext *rdma)
  1781. {
  1782. int ret;
  1783. if (!rdma->current_length) {
  1784. return 0;
  1785. }
  1786. ret = qemu_rdma_write_one(f, rdma,
  1787. rdma->current_index, rdma->current_addr, rdma->current_length);
  1788. if (ret < 0) {
  1789. return ret;
  1790. }
  1791. if (ret == 0) {
  1792. rdma->nb_sent++;
  1793. DDDPRINTF("sent total: %d\n", rdma->nb_sent);
  1794. }
  1795. rdma->current_length = 0;
  1796. rdma->current_addr = 0;
  1797. return 0;
  1798. }
  1799. static inline int qemu_rdma_buffer_mergable(RDMAContext *rdma,
  1800. uint64_t offset, uint64_t len)
  1801. {
  1802. RDMALocalBlock *block;
  1803. uint8_t *host_addr;
  1804. uint8_t *chunk_end;
  1805. if (rdma->current_index < 0) {
  1806. return 0;
  1807. }
  1808. if (rdma->current_chunk < 0) {
  1809. return 0;
  1810. }
  1811. block = &(rdma->local_ram_blocks.block[rdma->current_index]);
  1812. host_addr = block->local_host_addr + (offset - block->offset);
  1813. chunk_end = ram_chunk_end(block, rdma->current_chunk);
  1814. if (rdma->current_length == 0) {
  1815. return 0;
  1816. }
  1817. /*
  1818. * Only merge into chunk sequentially.
  1819. */
  1820. if (offset != (rdma->current_addr + rdma->current_length)) {
  1821. return 0;
  1822. }
  1823. if (offset < block->offset) {
  1824. return 0;
  1825. }
  1826. if ((offset + len) > (block->offset + block->length)) {
  1827. return 0;
  1828. }
  1829. if ((host_addr + len) > chunk_end) {
  1830. return 0;
  1831. }
  1832. return 1;
  1833. }
  1834. /*
  1835. * We're not actually writing here, but doing three things:
  1836. *
  1837. * 1. Identify the chunk the buffer belongs to.
  1838. * 2. If the chunk is full or the buffer doesn't belong to the current
  1839. * chunk, then start a new chunk and flush() the old chunk.
  1840. * 3. To keep the hardware busy, we also group chunks into batches
  1841. * and only require that a batch gets acknowledged in the completion
  1842. * qeueue instead of each individual chunk.
  1843. */
  1844. static int qemu_rdma_write(QEMUFile *f, RDMAContext *rdma,
  1845. uint64_t block_offset, uint64_t offset,
  1846. uint64_t len)
  1847. {
  1848. uint64_t current_addr = block_offset + offset;
  1849. uint64_t index = rdma->current_index;
  1850. uint64_t chunk = rdma->current_chunk;
  1851. int ret;
  1852. /* If we cannot merge it, we flush the current buffer first. */
  1853. if (!qemu_rdma_buffer_mergable(rdma, current_addr, len)) {
  1854. ret = qemu_rdma_write_flush(f, rdma);
  1855. if (ret) {
  1856. return ret;
  1857. }
  1858. rdma->current_length = 0;
  1859. rdma->current_addr = current_addr;
  1860. ret = qemu_rdma_search_ram_block(rdma, block_offset,
  1861. offset, len, &index, &chunk);
  1862. if (ret) {
  1863. fprintf(stderr, "ram block search failed\n");
  1864. return ret;
  1865. }
  1866. rdma->current_index = index;
  1867. rdma->current_chunk = chunk;
  1868. }
  1869. /* merge it */
  1870. rdma->current_length += len;
  1871. /* flush it if buffer is too large */
  1872. if (rdma->current_length >= RDMA_MERGE_MAX) {
  1873. return qemu_rdma_write_flush(f, rdma);
  1874. }
  1875. return 0;
  1876. }
  1877. static void qemu_rdma_cleanup(RDMAContext *rdma)
  1878. {
  1879. struct rdma_cm_event *cm_event;
  1880. int ret, idx;
  1881. if (rdma->cm_id && rdma->connected) {
  1882. if (rdma->error_state) {
  1883. RDMAControlHeader head = { .len = 0,
  1884. .type = RDMA_CONTROL_ERROR,
  1885. .repeat = 1,
  1886. };
  1887. fprintf(stderr, "Early error. Sending error.\n");
  1888. qemu_rdma_post_send_control(rdma, NULL, &head);
  1889. }
  1890. ret = rdma_disconnect(rdma->cm_id);
  1891. if (!ret) {
  1892. DDPRINTF("waiting for disconnect\n");
  1893. ret = rdma_get_cm_event(rdma->channel, &cm_event);
  1894. if (!ret) {
  1895. rdma_ack_cm_event(cm_event);
  1896. }
  1897. }
  1898. DDPRINTF("Disconnected.\n");
  1899. rdma->connected = false;
  1900. }
  1901. g_free(rdma->block);
  1902. rdma->block = NULL;
  1903. for (idx = 0; idx < RDMA_WRID_MAX; idx++) {
  1904. if (rdma->wr_data[idx].control_mr) {
  1905. rdma->total_registrations--;
  1906. ibv_dereg_mr(rdma->wr_data[idx].control_mr);
  1907. }
  1908. rdma->wr_data[idx].control_mr = NULL;
  1909. }
  1910. if (rdma->local_ram_blocks.block) {
  1911. while (rdma->local_ram_blocks.nb_blocks) {
  1912. __qemu_rdma_delete_block(rdma,
  1913. rdma->local_ram_blocks.block->offset);
  1914. }
  1915. }
  1916. if (rdma->cq) {
  1917. ibv_destroy_cq(rdma->cq);
  1918. rdma->cq = NULL;
  1919. }
  1920. if (rdma->comp_channel) {
  1921. ibv_destroy_comp_channel(rdma->comp_channel);
  1922. rdma->comp_channel = NULL;
  1923. }
  1924. if (rdma->pd) {
  1925. ibv_dealloc_pd(rdma->pd);
  1926. rdma->pd = NULL;
  1927. }
  1928. if (rdma->listen_id) {
  1929. rdma_destroy_id(rdma->listen_id);
  1930. rdma->listen_id = NULL;
  1931. }
  1932. if (rdma->cm_id) {
  1933. if (rdma->qp) {
  1934. rdma_destroy_qp(rdma->cm_id);
  1935. rdma->qp = NULL;
  1936. }
  1937. rdma_destroy_id(rdma->cm_id);
  1938. rdma->cm_id = NULL;
  1939. }
  1940. if (rdma->channel) {
  1941. rdma_destroy_event_channel(rdma->channel);
  1942. rdma->channel = NULL;
  1943. }
  1944. g_free(rdma->host);
  1945. rdma->host = NULL;
  1946. }
  1947. static int qemu_rdma_source_init(RDMAContext *rdma, Error **errp, bool pin_all)
  1948. {
  1949. int ret, idx;
  1950. Error *local_err = NULL, **temp = &local_err;
  1951. /*
  1952. * Will be validated against destination's actual capabilities
  1953. * after the connect() completes.
  1954. */
  1955. rdma->pin_all = pin_all;
  1956. ret = qemu_rdma_resolve_host(rdma, temp);
  1957. if (ret) {
  1958. goto err_rdma_source_init;
  1959. }
  1960. ret = qemu_rdma_alloc_pd_cq(rdma);
  1961. if (ret) {
  1962. ERROR(temp, "rdma migration: error allocating pd and cq! Your mlock()"
  1963. " limits may be too low. Please check $ ulimit -a # and "
  1964. "search for 'ulimit -l' in the output");
  1965. goto err_rdma_source_init;
  1966. }
  1967. ret = qemu_rdma_alloc_qp(rdma);
  1968. if (ret) {
  1969. ERROR(temp, "rdma migration: error allocating qp!");
  1970. goto err_rdma_source_init;
  1971. }
  1972. ret = qemu_rdma_init_ram_blocks(rdma);
  1973. if (ret) {
  1974. ERROR(temp, "rdma migration: error initializing ram blocks!");
  1975. goto err_rdma_source_init;
  1976. }
  1977. for (idx = 0; idx < RDMA_WRID_MAX; idx++) {
  1978. ret = qemu_rdma_reg_control(rdma, idx);
  1979. if (ret) {
  1980. ERROR(temp, "rdma migration: error registering %d control!",
  1981. idx);
  1982. goto err_rdma_source_init;
  1983. }
  1984. }
  1985. return 0;
  1986. err_rdma_source_init:
  1987. error_propagate(errp, local_err);
  1988. qemu_rdma_cleanup(rdma);
  1989. return -1;
  1990. }
  1991. static int qemu_rdma_connect(RDMAContext *rdma, Error **errp)
  1992. {
  1993. RDMACapabilities cap = {
  1994. .version = RDMA_CONTROL_VERSION_CURRENT,
  1995. .flags = 0,
  1996. };
  1997. struct rdma_conn_param conn_param = { .initiator_depth = 2,
  1998. .retry_count = 5,
  1999. .private_data = &cap,
  2000. .private_data_len = sizeof(cap),
  2001. };
  2002. struct rdma_cm_event *cm_event;
  2003. int ret;
  2004. /*
  2005. * Only negotiate the capability with destination if the user
  2006. * on the source first requested the capability.
  2007. */
  2008. if (rdma->pin_all) {
  2009. DPRINTF("Server pin-all memory requested.\n");
  2010. cap.flags |= RDMA_CAPABILITY_PIN_ALL;
  2011. }
  2012. caps_to_network(&cap);
  2013. ret = rdma_connect(rdma->cm_id, &conn_param);
  2014. if (ret) {
  2015. perror("rdma_connect");
  2016. ERROR(errp, "connecting to destination!");
  2017. rdma_destroy_id(rdma->cm_id);
  2018. rdma->cm_id = NULL;
  2019. goto err_rdma_source_connect;
  2020. }
  2021. ret = rdma_get_cm_event(rdma->channel, &cm_event);
  2022. if (ret) {
  2023. perror("rdma_get_cm_event after rdma_connect");
  2024. ERROR(errp, "connecting to destination!");
  2025. rdma_ack_cm_event(cm_event);
  2026. rdma_destroy_id(rdma->cm_id);
  2027. rdma->cm_id = NULL;
  2028. goto err_rdma_source_connect;
  2029. }
  2030. if (cm_event->event != RDMA_CM_EVENT_ESTABLISHED) {
  2031. perror("rdma_get_cm_event != EVENT_ESTABLISHED after rdma_connect");
  2032. ERROR(errp, "connecting to destination!");
  2033. rdma_ack_cm_event(cm_event);
  2034. rdma_destroy_id(rdma->cm_id);
  2035. rdma->cm_id = NULL;
  2036. goto err_rdma_source_connect;
  2037. }
  2038. rdma->connected = true;
  2039. memcpy(&cap, cm_event->param.conn.private_data, sizeof(cap));
  2040. network_to_caps(&cap);
  2041. /*
  2042. * Verify that the *requested* capabilities are supported by the destination
  2043. * and disable them otherwise.
  2044. */
  2045. if (rdma->pin_all && !(cap.flags & RDMA_CAPABILITY_PIN_ALL)) {
  2046. ERROR(errp, "Server cannot support pinning all memory. "
  2047. "Will register memory dynamically.");
  2048. rdma->pin_all = false;
  2049. }
  2050. DPRINTF("Pin all memory: %s\n", rdma->pin_all ? "enabled" : "disabled");
  2051. rdma_ack_cm_event(cm_event);
  2052. ret = qemu_rdma_post_recv_control(rdma, RDMA_WRID_READY);
  2053. if (ret) {
  2054. ERROR(errp, "posting second control recv!");
  2055. goto err_rdma_source_connect;
  2056. }
  2057. rdma->control_ready_expected = 1;
  2058. rdma->nb_sent = 0;
  2059. return 0;
  2060. err_rdma_source_connect:
  2061. qemu_rdma_cleanup(rdma);
  2062. return -1;
  2063. }
  2064. static int qemu_rdma_dest_init(RDMAContext *rdma, Error **errp)
  2065. {
  2066. int ret = -EINVAL, idx;
  2067. struct rdma_cm_id *listen_id;
  2068. char ip[40] = "unknown";
  2069. struct rdma_addrinfo *res;
  2070. char port_str[16];
  2071. for (idx = 0; idx < RDMA_WRID_MAX; idx++) {
  2072. rdma->wr_data[idx].control_len = 0;
  2073. rdma->wr_data[idx].control_curr = NULL;
  2074. }
  2075. if (rdma->host == NULL) {
  2076. ERROR(errp, "RDMA host is not set!");
  2077. rdma->error_state = -EINVAL;
  2078. return -1;
  2079. }
  2080. /* create CM channel */
  2081. rdma->channel = rdma_create_event_channel();
  2082. if (!rdma->channel) {
  2083. ERROR(errp, "could not create rdma event channel");
  2084. rdma->error_state = -EINVAL;
  2085. return -1;
  2086. }
  2087. /* create CM id */
  2088. ret = rdma_create_id(rdma->channel, &listen_id, NULL, RDMA_PS_TCP);
  2089. if (ret) {
  2090. ERROR(errp, "could not create cm_id!");
  2091. goto err_dest_init_create_listen_id;
  2092. }
  2093. snprintf(port_str, 16, "%d", rdma->port);
  2094. port_str[15] = '\0';
  2095. if (rdma->host && strcmp("", rdma->host)) {
  2096. struct rdma_addrinfo *e;
  2097. ret = rdma_getaddrinfo(rdma->host, port_str, NULL, &res);
  2098. if (ret < 0) {
  2099. ERROR(errp, "could not rdma_getaddrinfo address %s", rdma->host);
  2100. goto err_dest_init_bind_addr;
  2101. }
  2102. for (e = res; e != NULL; e = e->ai_next) {
  2103. inet_ntop(e->ai_family,
  2104. &((struct sockaddr_in *) e->ai_dst_addr)->sin_addr, ip, sizeof ip);
  2105. DPRINTF("Trying %s => %s\n", rdma->host, ip);
  2106. ret = rdma_bind_addr(listen_id, e->ai_dst_addr);
  2107. if (!ret) {
  2108. if (e->ai_family == AF_INET6) {
  2109. ret = qemu_rdma_broken_ipv6_kernel(errp, listen_id->verbs);
  2110. if (ret) {
  2111. continue;
  2112. }
  2113. }
  2114. goto listen;
  2115. }
  2116. }
  2117. ERROR(errp, "Error: could not rdma_bind_addr!");
  2118. goto err_dest_init_bind_addr;
  2119. } else {
  2120. ERROR(errp, "migration host and port not specified!");
  2121. ret = -EINVAL;
  2122. goto err_dest_init_bind_addr;
  2123. }
  2124. listen:
  2125. rdma->listen_id = listen_id;
  2126. qemu_rdma_dump_gid("dest_init", listen_id);
  2127. return 0;
  2128. err_dest_init_bind_addr:
  2129. rdma_destroy_id(listen_id);
  2130. err_dest_init_create_listen_id:
  2131. rdma_destroy_event_channel(rdma->channel);
  2132. rdma->channel = NULL;
  2133. rdma->error_state = ret;
  2134. return ret;
  2135. }
  2136. static void *qemu_rdma_data_init(const char *host_port, Error **errp)
  2137. {
  2138. RDMAContext *rdma = NULL;
  2139. InetSocketAddress *addr;
  2140. if (host_port) {
  2141. rdma = g_malloc0(sizeof(RDMAContext));
  2142. memset(rdma, 0, sizeof(RDMAContext));
  2143. rdma->current_index = -1;
  2144. rdma->current_chunk = -1;
  2145. addr = inet_parse(host_port, NULL);
  2146. if (addr != NULL) {
  2147. rdma->port = atoi(addr->port);
  2148. rdma->host = g_strdup(addr->host);
  2149. } else {
  2150. ERROR(errp, "bad RDMA migration address '%s'", host_port);
  2151. g_free(rdma);
  2152. rdma = NULL;
  2153. }
  2154. qapi_free_InetSocketAddress(addr);
  2155. }
  2156. return rdma;
  2157. }
  2158. /*
  2159. * QEMUFile interface to the control channel.
  2160. * SEND messages for control only.
  2161. * pc.ram is handled with regular RDMA messages.
  2162. */
  2163. static int qemu_rdma_put_buffer(void *opaque, const uint8_t *buf,
  2164. int64_t pos, int size)
  2165. {
  2166. QEMUFileRDMA *r = opaque;
  2167. QEMUFile *f = r->file;
  2168. RDMAContext *rdma = r->rdma;
  2169. size_t remaining = size;
  2170. uint8_t * data = (void *) buf;
  2171. int ret;
  2172. CHECK_ERROR_STATE();
  2173. /*
  2174. * Push out any writes that
  2175. * we're queued up for pc.ram.
  2176. */
  2177. ret = qemu_rdma_write_flush(f, rdma);
  2178. if (ret < 0) {
  2179. rdma->error_state = ret;
  2180. return ret;
  2181. }
  2182. while (remaining) {
  2183. RDMAControlHeader head;
  2184. r->len = MIN(remaining, RDMA_SEND_INCREMENT);
  2185. remaining -= r->len;
  2186. head.len = r->len;
  2187. head.type = RDMA_CONTROL_QEMU_FILE;
  2188. ret = qemu_rdma_exchange_send(rdma, &head, data, NULL, NULL, NULL);
  2189. if (ret < 0) {
  2190. rdma->error_state = ret;
  2191. return ret;
  2192. }
  2193. data += r->len;
  2194. }
  2195. return size;
  2196. }
  2197. static size_t qemu_rdma_fill(RDMAContext *rdma, uint8_t *buf,
  2198. int size, int idx)
  2199. {
  2200. size_t len = 0;
  2201. if (rdma->wr_data[idx].control_len) {
  2202. DDDPRINTF("RDMA %" PRId64 " of %d bytes already in buffer\n",
  2203. rdma->wr_data[idx].control_len, size);
  2204. len = MIN(size, rdma->wr_data[idx].control_len);
  2205. memcpy(buf, rdma->wr_data[idx].control_curr, len);
  2206. rdma->wr_data[idx].control_curr += len;
  2207. rdma->wr_data[idx].control_len -= len;
  2208. }
  2209. return len;
  2210. }
  2211. /*
  2212. * QEMUFile interface to the control channel.
  2213. * RDMA links don't use bytestreams, so we have to
  2214. * return bytes to QEMUFile opportunistically.
  2215. */
  2216. static int qemu_rdma_get_buffer(void *opaque, uint8_t *buf,
  2217. int64_t pos, int size)
  2218. {
  2219. QEMUFileRDMA *r = opaque;
  2220. RDMAContext *rdma = r->rdma;
  2221. RDMAControlHeader head;
  2222. int ret = 0;
  2223. CHECK_ERROR_STATE();
  2224. /*
  2225. * First, we hold on to the last SEND message we
  2226. * were given and dish out the bytes until we run
  2227. * out of bytes.
  2228. */
  2229. r->len = qemu_rdma_fill(r->rdma, buf, size, 0);
  2230. if (r->len) {
  2231. return r->len;
  2232. }
  2233. /*
  2234. * Once we run out, we block and wait for another
  2235. * SEND message to arrive.
  2236. */
  2237. ret = qemu_rdma_exchange_recv(rdma, &head, RDMA_CONTROL_QEMU_FILE);
  2238. if (ret < 0) {
  2239. rdma->error_state = ret;
  2240. return ret;
  2241. }
  2242. /*
  2243. * SEND was received with new bytes, now try again.
  2244. */
  2245. return qemu_rdma_fill(r->rdma, buf, size, 0);
  2246. }
  2247. /*
  2248. * Block until all the outstanding chunks have been delivered by the hardware.
  2249. */
  2250. static int qemu_rdma_drain_cq(QEMUFile *f, RDMAContext *rdma)
  2251. {
  2252. int ret;
  2253. if (qemu_rdma_write_flush(f, rdma) < 0) {
  2254. return -EIO;
  2255. }
  2256. while (rdma->nb_sent) {
  2257. ret = qemu_rdma_block_for_wrid(rdma, RDMA_WRID_RDMA_WRITE, NULL);
  2258. if (ret < 0) {
  2259. fprintf(stderr, "rdma migration: complete polling error!\n");
  2260. return -EIO;
  2261. }
  2262. }
  2263. qemu_rdma_unregister_waiting(rdma);
  2264. return 0;
  2265. }
  2266. static int qemu_rdma_close(void *opaque)
  2267. {
  2268. DPRINTF("Shutting down connection.\n");
  2269. QEMUFileRDMA *r = opaque;
  2270. if (r->rdma) {
  2271. qemu_rdma_cleanup(r->rdma);
  2272. g_free(r->rdma);
  2273. }
  2274. g_free(r);
  2275. return 0;
  2276. }
  2277. /*
  2278. * Parameters:
  2279. * @offset == 0 :
  2280. * This means that 'block_offset' is a full virtual address that does not
  2281. * belong to a RAMBlock of the virtual machine and instead
  2282. * represents a private malloc'd memory area that the caller wishes to
  2283. * transfer.
  2284. *
  2285. * @offset != 0 :
  2286. * Offset is an offset to be added to block_offset and used
  2287. * to also lookup the corresponding RAMBlock.
  2288. *
  2289. * @size > 0 :
  2290. * Initiate an transfer this size.
  2291. *
  2292. * @size == 0 :
  2293. * A 'hint' or 'advice' that means that we wish to speculatively
  2294. * and asynchronously unregister this memory. In this case, there is no
  2295. * guarantee that the unregister will actually happen, for example,
  2296. * if the memory is being actively transmitted. Additionally, the memory
  2297. * may be re-registered at any future time if a write within the same
  2298. * chunk was requested again, even if you attempted to unregister it
  2299. * here.
  2300. *
  2301. * @size < 0 : TODO, not yet supported
  2302. * Unregister the memory NOW. This means that the caller does not
  2303. * expect there to be any future RDMA transfers and we just want to clean
  2304. * things up. This is used in case the upper layer owns the memory and
  2305. * cannot wait for qemu_fclose() to occur.
  2306. *
  2307. * @bytes_sent : User-specificed pointer to indicate how many bytes were
  2308. * sent. Usually, this will not be more than a few bytes of
  2309. * the protocol because most transfers are sent asynchronously.
  2310. */
  2311. static size_t qemu_rdma_save_page(QEMUFile *f, void *opaque,
  2312. ram_addr_t block_offset, ram_addr_t offset,
  2313. size_t size, int *bytes_sent)
  2314. {
  2315. QEMUFileRDMA *rfile = opaque;
  2316. RDMAContext *rdma = rfile->rdma;
  2317. int ret;
  2318. CHECK_ERROR_STATE();
  2319. qemu_fflush(f);
  2320. if (size > 0) {
  2321. /*
  2322. * Add this page to the current 'chunk'. If the chunk
  2323. * is full, or the page doen't belong to the current chunk,
  2324. * an actual RDMA write will occur and a new chunk will be formed.
  2325. */
  2326. ret = qemu_rdma_write(f, rdma, block_offset, offset, size);
  2327. if (ret < 0) {
  2328. fprintf(stderr, "rdma migration: write error! %d\n", ret);
  2329. goto err;
  2330. }
  2331. /*
  2332. * We always return 1 bytes because the RDMA
  2333. * protocol is completely asynchronous. We do not yet know
  2334. * whether an identified chunk is zero or not because we're
  2335. * waiting for other pages to potentially be merged with
  2336. * the current chunk. So, we have to call qemu_update_position()
  2337. * later on when the actual write occurs.
  2338. */
  2339. if (bytes_sent) {
  2340. *bytes_sent = 1;
  2341. }
  2342. } else {
  2343. uint64_t index, chunk;
  2344. /* TODO: Change QEMUFileOps prototype to be signed: size_t => long
  2345. if (size < 0) {
  2346. ret = qemu_rdma_drain_cq(f, rdma);
  2347. if (ret < 0) {
  2348. fprintf(stderr, "rdma: failed to synchronously drain"
  2349. " completion queue before unregistration.\n");
  2350. goto err;
  2351. }
  2352. }
  2353. */
  2354. ret = qemu_rdma_search_ram_block(rdma, block_offset,
  2355. offset, size, &index, &chunk);
  2356. if (ret) {
  2357. fprintf(stderr, "ram block search failed\n");
  2358. goto err;
  2359. }
  2360. qemu_rdma_signal_unregister(rdma, index, chunk, 0);
  2361. /*
  2362. * TODO: Synchronous, guaranteed unregistration (should not occur during
  2363. * fast-path). Otherwise, unregisters will process on the next call to
  2364. * qemu_rdma_drain_cq()
  2365. if (size < 0) {
  2366. qemu_rdma_unregister_waiting(rdma);
  2367. }
  2368. */
  2369. }
  2370. /*
  2371. * Drain the Completion Queue if possible, but do not block,
  2372. * just poll.
  2373. *
  2374. * If nothing to poll, the end of the iteration will do this
  2375. * again to make sure we don't overflow the request queue.
  2376. */
  2377. while (1) {
  2378. uint64_t wr_id, wr_id_in;
  2379. int ret = qemu_rdma_poll(rdma, &wr_id_in, NULL);
  2380. if (ret < 0) {
  2381. fprintf(stderr, "rdma migration: polling error! %d\n", ret);
  2382. goto err;
  2383. }
  2384. wr_id = wr_id_in & RDMA_WRID_TYPE_MASK;
  2385. if (wr_id == RDMA_WRID_NONE) {
  2386. break;
  2387. }
  2388. }
  2389. return RAM_SAVE_CONTROL_DELAYED;
  2390. err:
  2391. rdma->error_state = ret;
  2392. return ret;
  2393. }
  2394. static int qemu_rdma_accept(RDMAContext *rdma)
  2395. {
  2396. RDMACapabilities cap;
  2397. struct rdma_conn_param conn_param = {
  2398. .responder_resources = 2,
  2399. .private_data = &cap,
  2400. .private_data_len = sizeof(cap),
  2401. };
  2402. struct rdma_cm_event *cm_event;
  2403. struct ibv_context *verbs;
  2404. int ret = -EINVAL;
  2405. int idx;
  2406. ret = rdma_get_cm_event(rdma->channel, &cm_event);
  2407. if (ret) {
  2408. goto err_rdma_dest_wait;
  2409. }
  2410. if (cm_event->event != RDMA_CM_EVENT_CONNECT_REQUEST) {
  2411. rdma_ack_cm_event(cm_event);
  2412. goto err_rdma_dest_wait;
  2413. }
  2414. memcpy(&cap, cm_event->param.conn.private_data, sizeof(cap));
  2415. network_to_caps(&cap);
  2416. if (cap.version < 1 || cap.version > RDMA_CONTROL_VERSION_CURRENT) {
  2417. fprintf(stderr, "Unknown source RDMA version: %d, bailing...\n",
  2418. cap.version);
  2419. rdma_ack_cm_event(cm_event);
  2420. goto err_rdma_dest_wait;
  2421. }
  2422. /*
  2423. * Respond with only the capabilities this version of QEMU knows about.
  2424. */
  2425. cap.flags &= known_capabilities;
  2426. /*
  2427. * Enable the ones that we do know about.
  2428. * Add other checks here as new ones are introduced.
  2429. */
  2430. if (cap.flags & RDMA_CAPABILITY_PIN_ALL) {
  2431. rdma->pin_all = true;
  2432. }
  2433. rdma->cm_id = cm_event->id;
  2434. verbs = cm_event->id->verbs;
  2435. rdma_ack_cm_event(cm_event);
  2436. DPRINTF("Memory pin all: %s\n", rdma->pin_all ? "enabled" : "disabled");
  2437. caps_to_network(&cap);
  2438. DPRINTF("verbs context after listen: %p\n", verbs);
  2439. if (!rdma->verbs) {
  2440. rdma->verbs = verbs;
  2441. } else if (rdma->verbs != verbs) {
  2442. fprintf(stderr, "ibv context not matching %p, %p!\n",
  2443. rdma->verbs, verbs);
  2444. goto err_rdma_dest_wait;
  2445. }
  2446. qemu_rdma_dump_id("dest_init", verbs);
  2447. ret = qemu_rdma_alloc_pd_cq(rdma);
  2448. if (ret) {
  2449. fprintf(stderr, "rdma migration: error allocating pd and cq!\n");
  2450. goto err_rdma_dest_wait;
  2451. }
  2452. ret = qemu_rdma_alloc_qp(rdma);
  2453. if (ret) {
  2454. fprintf(stderr, "rdma migration: error allocating qp!\n");
  2455. goto err_rdma_dest_wait;
  2456. }
  2457. ret = qemu_rdma_init_ram_blocks(rdma);
  2458. if (ret) {
  2459. fprintf(stderr, "rdma migration: error initializing ram blocks!\n");
  2460. goto err_rdma_dest_wait;
  2461. }
  2462. for (idx = 0; idx < RDMA_WRID_MAX; idx++) {
  2463. ret = qemu_rdma_reg_control(rdma, idx);
  2464. if (ret) {
  2465. fprintf(stderr, "rdma: error registering %d control!\n", idx);
  2466. goto err_rdma_dest_wait;
  2467. }
  2468. }
  2469. qemu_set_fd_handler2(rdma->channel->fd, NULL, NULL, NULL, NULL);
  2470. ret = rdma_accept(rdma->cm_id, &conn_param);
  2471. if (ret) {
  2472. fprintf(stderr, "rdma_accept returns %d!\n", ret);
  2473. goto err_rdma_dest_wait;
  2474. }
  2475. ret = rdma_get_cm_event(rdma->channel, &cm_event);
  2476. if (ret) {
  2477. fprintf(stderr, "rdma_accept get_cm_event failed %d!\n", ret);
  2478. goto err_rdma_dest_wait;
  2479. }
  2480. if (cm_event->event != RDMA_CM_EVENT_ESTABLISHED) {
  2481. fprintf(stderr, "rdma_accept not event established!\n");
  2482. rdma_ack_cm_event(cm_event);
  2483. goto err_rdma_dest_wait;
  2484. }
  2485. rdma_ack_cm_event(cm_event);
  2486. rdma->connected = true;
  2487. ret = qemu_rdma_post_recv_control(rdma, RDMA_WRID_READY);
  2488. if (ret) {
  2489. fprintf(stderr, "rdma migration: error posting second control recv!\n");
  2490. goto err_rdma_dest_wait;
  2491. }
  2492. qemu_rdma_dump_gid("dest_connect", rdma->cm_id);
  2493. return 0;
  2494. err_rdma_dest_wait:
  2495. rdma->error_state = ret;
  2496. qemu_rdma_cleanup(rdma);
  2497. return ret;
  2498. }
  2499. /*
  2500. * During each iteration of the migration, we listen for instructions
  2501. * by the source VM to perform dynamic page registrations before they
  2502. * can perform RDMA operations.
  2503. *
  2504. * We respond with the 'rkey'.
  2505. *
  2506. * Keep doing this until the source tells us to stop.
  2507. */
  2508. static int qemu_rdma_registration_handle(QEMUFile *f, void *opaque,
  2509. uint64_t flags)
  2510. {
  2511. RDMAControlHeader reg_resp = { .len = sizeof(RDMARegisterResult),
  2512. .type = RDMA_CONTROL_REGISTER_RESULT,
  2513. .repeat = 0,
  2514. };
  2515. RDMAControlHeader unreg_resp = { .len = 0,
  2516. .type = RDMA_CONTROL_UNREGISTER_FINISHED,
  2517. .repeat = 0,
  2518. };
  2519. RDMAControlHeader blocks = { .type = RDMA_CONTROL_RAM_BLOCKS_RESULT,
  2520. .repeat = 1 };
  2521. QEMUFileRDMA *rfile = opaque;
  2522. RDMAContext *rdma = rfile->rdma;
  2523. RDMALocalBlocks *local = &rdma->local_ram_blocks;
  2524. RDMAControlHeader head;
  2525. RDMARegister *reg, *registers;
  2526. RDMACompress *comp;
  2527. RDMARegisterResult *reg_result;
  2528. static RDMARegisterResult results[RDMA_CONTROL_MAX_COMMANDS_PER_MESSAGE];
  2529. RDMALocalBlock *block;
  2530. void *host_addr;
  2531. int ret = 0;
  2532. int idx = 0;
  2533. int count = 0;
  2534. int i = 0;
  2535. CHECK_ERROR_STATE();
  2536. do {
  2537. DDDPRINTF("Waiting for next request %" PRIu64 "...\n", flags);
  2538. ret = qemu_rdma_exchange_recv(rdma, &head, RDMA_CONTROL_NONE);
  2539. if (ret < 0) {
  2540. break;
  2541. }
  2542. if (head.repeat > RDMA_CONTROL_MAX_COMMANDS_PER_MESSAGE) {
  2543. fprintf(stderr, "rdma: Too many requests in this message (%d)."
  2544. "Bailing.\n", head.repeat);
  2545. ret = -EIO;
  2546. break;
  2547. }
  2548. switch (head.type) {
  2549. case RDMA_CONTROL_COMPRESS:
  2550. comp = (RDMACompress *) rdma->wr_data[idx].control_curr;
  2551. network_to_compress(comp);
  2552. DDPRINTF("Zapping zero chunk: %" PRId64
  2553. " bytes, index %d, offset %" PRId64 "\n",
  2554. comp->length, comp->block_idx, comp->offset);
  2555. block = &(rdma->local_ram_blocks.block[comp->block_idx]);
  2556. host_addr = block->local_host_addr +
  2557. (comp->offset - block->offset);
  2558. ram_handle_compressed(host_addr, comp->value, comp->length);
  2559. break;
  2560. case RDMA_CONTROL_REGISTER_FINISHED:
  2561. DDDPRINTF("Current registrations complete.\n");
  2562. goto out;
  2563. case RDMA_CONTROL_RAM_BLOCKS_REQUEST:
  2564. DPRINTF("Initial setup info requested.\n");
  2565. if (rdma->pin_all) {
  2566. ret = qemu_rdma_reg_whole_ram_blocks(rdma);
  2567. if (ret) {
  2568. fprintf(stderr, "rdma migration: error dest "
  2569. "registering ram blocks!\n");
  2570. goto out;
  2571. }
  2572. }
  2573. /*
  2574. * Dest uses this to prepare to transmit the RAMBlock descriptions
  2575. * to the source VM after connection setup.
  2576. * Both sides use the "remote" structure to communicate and update
  2577. * their "local" descriptions with what was sent.
  2578. */
  2579. for (i = 0; i < local->nb_blocks; i++) {
  2580. rdma->block[i].remote_host_addr =
  2581. (uint64_t)(local->block[i].local_host_addr);
  2582. if (rdma->pin_all) {
  2583. rdma->block[i].remote_rkey = local->block[i].mr->rkey;
  2584. }
  2585. rdma->block[i].offset = local->block[i].offset;
  2586. rdma->block[i].length = local->block[i].length;
  2587. remote_block_to_network(&rdma->block[i]);
  2588. }
  2589. blocks.len = rdma->local_ram_blocks.nb_blocks
  2590. * sizeof(RDMARemoteBlock);
  2591. ret = qemu_rdma_post_send_control(rdma,
  2592. (uint8_t *) rdma->block, &blocks);
  2593. if (ret < 0) {
  2594. fprintf(stderr, "rdma migration: error sending remote info!\n");
  2595. goto out;
  2596. }
  2597. break;
  2598. case RDMA_CONTROL_REGISTER_REQUEST:
  2599. DDPRINTF("There are %d registration requests\n", head.repeat);
  2600. reg_resp.repeat = head.repeat;
  2601. registers = (RDMARegister *) rdma->wr_data[idx].control_curr;
  2602. for (count = 0; count < head.repeat; count++) {
  2603. uint64_t chunk;
  2604. uint8_t *chunk_start, *chunk_end;
  2605. reg = &registers[count];
  2606. network_to_register(reg);
  2607. reg_result = &results[count];
  2608. DDPRINTF("Registration request (%d): index %d, current_addr %"
  2609. PRIu64 " chunks: %" PRIu64 "\n", count,
  2610. reg->current_index, reg->key.current_addr, reg->chunks);
  2611. block = &(rdma->local_ram_blocks.block[reg->current_index]);
  2612. if (block->is_ram_block) {
  2613. host_addr = (block->local_host_addr +
  2614. (reg->key.current_addr - block->offset));
  2615. chunk = ram_chunk_index(block->local_host_addr,
  2616. (uint8_t *) host_addr);
  2617. } else {
  2618. chunk = reg->key.chunk;
  2619. host_addr = block->local_host_addr +
  2620. (reg->key.chunk * (1UL << RDMA_REG_CHUNK_SHIFT));
  2621. }
  2622. chunk_start = ram_chunk_start(block, chunk);
  2623. chunk_end = ram_chunk_end(block, chunk + reg->chunks);
  2624. if (qemu_rdma_register_and_get_keys(rdma, block,
  2625. (uint8_t *)host_addr, NULL, &reg_result->rkey,
  2626. chunk, chunk_start, chunk_end)) {
  2627. fprintf(stderr, "cannot get rkey!\n");
  2628. ret = -EINVAL;
  2629. goto out;
  2630. }
  2631. reg_result->host_addr = (uint64_t) block->local_host_addr;
  2632. DDPRINTF("Registered rkey for this request: %x\n",
  2633. reg_result->rkey);
  2634. result_to_network(reg_result);
  2635. }
  2636. ret = qemu_rdma_post_send_control(rdma,
  2637. (uint8_t *) results, &reg_resp);
  2638. if (ret < 0) {
  2639. fprintf(stderr, "Failed to send control buffer!\n");
  2640. goto out;
  2641. }
  2642. break;
  2643. case RDMA_CONTROL_UNREGISTER_REQUEST:
  2644. DDPRINTF("There are %d unregistration requests\n", head.repeat);
  2645. unreg_resp.repeat = head.repeat;
  2646. registers = (RDMARegister *) rdma->wr_data[idx].control_curr;
  2647. for (count = 0; count < head.repeat; count++) {
  2648. reg = &registers[count];
  2649. network_to_register(reg);
  2650. DDPRINTF("Unregistration request (%d): "
  2651. " index %d, chunk %" PRIu64 "\n",
  2652. count, reg->current_index, reg->key.chunk);
  2653. block = &(rdma->local_ram_blocks.block[reg->current_index]);
  2654. ret = ibv_dereg_mr(block->pmr[reg->key.chunk]);
  2655. block->pmr[reg->key.chunk] = NULL;
  2656. if (ret != 0) {
  2657. perror("rdma unregistration chunk failed");
  2658. ret = -ret;
  2659. goto out;
  2660. }
  2661. rdma->total_registrations--;
  2662. DDPRINTF("Unregistered chunk %" PRIu64 " successfully.\n",
  2663. reg->key.chunk);
  2664. }
  2665. ret = qemu_rdma_post_send_control(rdma, NULL, &unreg_resp);
  2666. if (ret < 0) {
  2667. fprintf(stderr, "Failed to send control buffer!\n");
  2668. goto out;
  2669. }
  2670. break;
  2671. case RDMA_CONTROL_REGISTER_RESULT:
  2672. fprintf(stderr, "Invalid RESULT message at dest.\n");
  2673. ret = -EIO;
  2674. goto out;
  2675. default:
  2676. fprintf(stderr, "Unknown control message %s\n",
  2677. control_desc[head.type]);
  2678. ret = -EIO;
  2679. goto out;
  2680. }
  2681. } while (1);
  2682. out:
  2683. if (ret < 0) {
  2684. rdma->error_state = ret;
  2685. }
  2686. return ret;
  2687. }
  2688. static int qemu_rdma_registration_start(QEMUFile *f, void *opaque,
  2689. uint64_t flags)
  2690. {
  2691. QEMUFileRDMA *rfile = opaque;
  2692. RDMAContext *rdma = rfile->rdma;
  2693. CHECK_ERROR_STATE();
  2694. DDDPRINTF("start section: %" PRIu64 "\n", flags);
  2695. qemu_put_be64(f, RAM_SAVE_FLAG_HOOK);
  2696. qemu_fflush(f);
  2697. return 0;
  2698. }
  2699. /*
  2700. * Inform dest that dynamic registrations are done for now.
  2701. * First, flush writes, if any.
  2702. */
  2703. static int qemu_rdma_registration_stop(QEMUFile *f, void *opaque,
  2704. uint64_t flags)
  2705. {
  2706. Error *local_err = NULL, **errp = &local_err;
  2707. QEMUFileRDMA *rfile = opaque;
  2708. RDMAContext *rdma = rfile->rdma;
  2709. RDMAControlHeader head = { .len = 0, .repeat = 1 };
  2710. int ret = 0;
  2711. CHECK_ERROR_STATE();
  2712. qemu_fflush(f);
  2713. ret = qemu_rdma_drain_cq(f, rdma);
  2714. if (ret < 0) {
  2715. goto err;
  2716. }
  2717. if (flags == RAM_CONTROL_SETUP) {
  2718. RDMAControlHeader resp = {.type = RDMA_CONTROL_RAM_BLOCKS_RESULT };
  2719. RDMALocalBlocks *local = &rdma->local_ram_blocks;
  2720. int reg_result_idx, i, j, nb_remote_blocks;
  2721. head.type = RDMA_CONTROL_RAM_BLOCKS_REQUEST;
  2722. DPRINTF("Sending registration setup for ram blocks...\n");
  2723. /*
  2724. * Make sure that we parallelize the pinning on both sides.
  2725. * For very large guests, doing this serially takes a really
  2726. * long time, so we have to 'interleave' the pinning locally
  2727. * with the control messages by performing the pinning on this
  2728. * side before we receive the control response from the other
  2729. * side that the pinning has completed.
  2730. */
  2731. ret = qemu_rdma_exchange_send(rdma, &head, NULL, &resp,
  2732. &reg_result_idx, rdma->pin_all ?
  2733. qemu_rdma_reg_whole_ram_blocks : NULL);
  2734. if (ret < 0) {
  2735. ERROR(errp, "receiving remote info!");
  2736. return ret;
  2737. }
  2738. nb_remote_blocks = resp.len / sizeof(RDMARemoteBlock);
  2739. /*
  2740. * The protocol uses two different sets of rkeys (mutually exclusive):
  2741. * 1. One key to represent the virtual address of the entire ram block.
  2742. * (dynamic chunk registration disabled - pin everything with one rkey.)
  2743. * 2. One to represent individual chunks within a ram block.
  2744. * (dynamic chunk registration enabled - pin individual chunks.)
  2745. *
  2746. * Once the capability is successfully negotiated, the destination transmits
  2747. * the keys to use (or sends them later) including the virtual addresses
  2748. * and then propagates the remote ram block descriptions to his local copy.
  2749. */
  2750. if (local->nb_blocks != nb_remote_blocks) {
  2751. ERROR(errp, "ram blocks mismatch #1! "
  2752. "Your QEMU command line parameters are probably "
  2753. "not identical on both the source and destination.");
  2754. return -EINVAL;
  2755. }
  2756. qemu_rdma_move_header(rdma, reg_result_idx, &resp);
  2757. memcpy(rdma->block,
  2758. rdma->wr_data[reg_result_idx].control_curr, resp.len);
  2759. for (i = 0; i < nb_remote_blocks; i++) {
  2760. network_to_remote_block(&rdma->block[i]);
  2761. /* search local ram blocks */
  2762. for (j = 0; j < local->nb_blocks; j++) {
  2763. if (rdma->block[i].offset != local->block[j].offset) {
  2764. continue;
  2765. }
  2766. if (rdma->block[i].length != local->block[j].length) {
  2767. ERROR(errp, "ram blocks mismatch #2! "
  2768. "Your QEMU command line parameters are probably "
  2769. "not identical on both the source and destination.");
  2770. return -EINVAL;
  2771. }
  2772. local->block[j].remote_host_addr =
  2773. rdma->block[i].remote_host_addr;
  2774. local->block[j].remote_rkey = rdma->block[i].remote_rkey;
  2775. break;
  2776. }
  2777. if (j >= local->nb_blocks) {
  2778. ERROR(errp, "ram blocks mismatch #3! "
  2779. "Your QEMU command line parameters are probably "
  2780. "not identical on both the source and destination.");
  2781. return -EINVAL;
  2782. }
  2783. }
  2784. }
  2785. DDDPRINTF("Sending registration finish %" PRIu64 "...\n", flags);
  2786. head.type = RDMA_CONTROL_REGISTER_FINISHED;
  2787. ret = qemu_rdma_exchange_send(rdma, &head, NULL, NULL, NULL, NULL);
  2788. if (ret < 0) {
  2789. goto err;
  2790. }
  2791. return 0;
  2792. err:
  2793. rdma->error_state = ret;
  2794. return ret;
  2795. }
  2796. static int qemu_rdma_get_fd(void *opaque)
  2797. {
  2798. QEMUFileRDMA *rfile = opaque;
  2799. RDMAContext *rdma = rfile->rdma;
  2800. return rdma->comp_channel->fd;
  2801. }
  2802. const QEMUFileOps rdma_read_ops = {
  2803. .get_buffer = qemu_rdma_get_buffer,
  2804. .get_fd = qemu_rdma_get_fd,
  2805. .close = qemu_rdma_close,
  2806. .hook_ram_load = qemu_rdma_registration_handle,
  2807. };
  2808. const QEMUFileOps rdma_write_ops = {
  2809. .put_buffer = qemu_rdma_put_buffer,
  2810. .close = qemu_rdma_close,
  2811. .before_ram_iterate = qemu_rdma_registration_start,
  2812. .after_ram_iterate = qemu_rdma_registration_stop,
  2813. .save_page = qemu_rdma_save_page,
  2814. };
  2815. static void *qemu_fopen_rdma(RDMAContext *rdma, const char *mode)
  2816. {
  2817. QEMUFileRDMA *r = g_malloc0(sizeof(QEMUFileRDMA));
  2818. if (qemu_file_mode_is_not_valid(mode)) {
  2819. return NULL;
  2820. }
  2821. r->rdma = rdma;
  2822. if (mode[0] == 'w') {
  2823. r->file = qemu_fopen_ops(r, &rdma_write_ops);
  2824. } else {
  2825. r->file = qemu_fopen_ops(r, &rdma_read_ops);
  2826. }
  2827. return r->file;
  2828. }
  2829. static void rdma_accept_incoming_migration(void *opaque)
  2830. {
  2831. RDMAContext *rdma = opaque;
  2832. int ret;
  2833. QEMUFile *f;
  2834. Error *local_err = NULL, **errp = &local_err;
  2835. DPRINTF("Accepting rdma connection...\n");
  2836. ret = qemu_rdma_accept(rdma);
  2837. if (ret) {
  2838. ERROR(errp, "RDMA Migration initialization failed!");
  2839. return;
  2840. }
  2841. DPRINTF("Accepted migration\n");
  2842. f = qemu_fopen_rdma(rdma, "rb");
  2843. if (f == NULL) {
  2844. ERROR(errp, "could not qemu_fopen_rdma!");
  2845. qemu_rdma_cleanup(rdma);
  2846. return;
  2847. }
  2848. rdma->migration_started_on_destination = 1;
  2849. process_incoming_migration(f);
  2850. }
  2851. void rdma_start_incoming_migration(const char *host_port, Error **errp)
  2852. {
  2853. int ret;
  2854. RDMAContext *rdma;
  2855. Error *local_err = NULL;
  2856. DPRINTF("Starting RDMA-based incoming migration\n");
  2857. rdma = qemu_rdma_data_init(host_port, &local_err);
  2858. if (rdma == NULL) {
  2859. goto err;
  2860. }
  2861. ret = qemu_rdma_dest_init(rdma, &local_err);
  2862. if (ret) {
  2863. goto err;
  2864. }
  2865. DPRINTF("qemu_rdma_dest_init success\n");
  2866. ret = rdma_listen(rdma->listen_id, 5);
  2867. if (ret) {
  2868. ERROR(errp, "listening on socket!");
  2869. goto err;
  2870. }
  2871. DPRINTF("rdma_listen success\n");
  2872. qemu_set_fd_handler2(rdma->channel->fd, NULL,
  2873. rdma_accept_incoming_migration, NULL,
  2874. (void *)(intptr_t) rdma);
  2875. return;
  2876. err:
  2877. error_propagate(errp, local_err);
  2878. g_free(rdma);
  2879. }
  2880. void rdma_start_outgoing_migration(void *opaque,
  2881. const char *host_port, Error **errp)
  2882. {
  2883. MigrationState *s = opaque;
  2884. Error *local_err = NULL, **temp = &local_err;
  2885. RDMAContext *rdma = qemu_rdma_data_init(host_port, &local_err);
  2886. int ret = 0;
  2887. if (rdma == NULL) {
  2888. ERROR(temp, "Failed to initialize RDMA data structures! %d", ret);
  2889. goto err;
  2890. }
  2891. ret = qemu_rdma_source_init(rdma, &local_err,
  2892. s->enabled_capabilities[MIGRATION_CAPABILITY_RDMA_PIN_ALL]);
  2893. if (ret) {
  2894. goto err;
  2895. }
  2896. DPRINTF("qemu_rdma_source_init success\n");
  2897. ret = qemu_rdma_connect(rdma, &local_err);
  2898. if (ret) {
  2899. goto err;
  2900. }
  2901. DPRINTF("qemu_rdma_source_connect success\n");
  2902. s->file = qemu_fopen_rdma(rdma, "wb");
  2903. migrate_fd_connect(s);
  2904. return;
  2905. err:
  2906. error_propagate(errp, local_err);
  2907. g_free(rdma);
  2908. migrate_fd_error(s);
  2909. }