rdma.c 125 KB

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