xref: /openbmc/qemu/migration/multifd.c (revision c4601322)
1 /*
2  * Multifd common code
3  *
4  * Copyright (c) 2019-2020 Red Hat Inc
5  *
6  * Authors:
7  *  Juan Quintela <quintela@redhat.com>
8  *
9  * This work is licensed under the terms of the GNU GPL, version 2 or later.
10  * See the COPYING file in the top-level directory.
11  */
12 
13 #include "qemu/osdep.h"
14 #include "qemu/rcu.h"
15 #include "exec/target_page.h"
16 #include "sysemu/sysemu.h"
17 #include "exec/ramblock.h"
18 #include "qemu/error-report.h"
19 #include "qapi/error.h"
20 #include "ram.h"
21 #include "migration.h"
22 #include "migration-stats.h"
23 #include "socket.h"
24 #include "tls.h"
25 #include "qemu-file.h"
26 #include "trace.h"
27 #include "multifd.h"
28 #include "threadinfo.h"
29 #include "options.h"
30 #include "qemu/yank.h"
31 #include "io/channel-socket.h"
32 #include "yank_functions.h"
33 
34 /* Multiple fd's */
35 
36 #define MULTIFD_MAGIC 0x11223344U
37 #define MULTIFD_VERSION 1
38 
39 typedef struct {
40     uint32_t magic;
41     uint32_t version;
42     unsigned char uuid[16]; /* QemuUUID */
43     uint8_t id;
44     uint8_t unused1[7];     /* Reserved for future use */
45     uint64_t unused2[4];    /* Reserved for future use */
46 } __attribute__((packed)) MultiFDInit_t;
47 
48 /* Multifd without compression */
49 
50 /**
51  * nocomp_send_setup: setup send side
52  *
53  * For no compression this function does nothing.
54  *
55  * Returns 0 for success or -1 for error
56  *
57  * @p: Params for the channel that we are using
58  * @errp: pointer to an error
59  */
60 static int nocomp_send_setup(MultiFDSendParams *p, Error **errp)
61 {
62     return 0;
63 }
64 
65 /**
66  * nocomp_send_cleanup: cleanup send side
67  *
68  * For no compression this function does nothing.
69  *
70  * @p: Params for the channel that we are using
71  * @errp: pointer to an error
72  */
73 static void nocomp_send_cleanup(MultiFDSendParams *p, Error **errp)
74 {
75     return;
76 }
77 
78 /**
79  * nocomp_send_prepare: prepare date to be able to send
80  *
81  * For no compression we just have to calculate the size of the
82  * packet.
83  *
84  * Returns 0 for success or -1 for error
85  *
86  * @p: Params for the channel that we are using
87  * @errp: pointer to an error
88  */
89 static int nocomp_send_prepare(MultiFDSendParams *p, Error **errp)
90 {
91     MultiFDPages_t *pages = p->pages;
92 
93     for (int i = 0; i < p->normal_num; i++) {
94         p->iov[p->iovs_num].iov_base = pages->block->host + p->normal[i];
95         p->iov[p->iovs_num].iov_len = p->page_size;
96         p->iovs_num++;
97     }
98 
99     p->next_packet_size = p->normal_num * p->page_size;
100     p->flags |= MULTIFD_FLAG_NOCOMP;
101     return 0;
102 }
103 
104 /**
105  * nocomp_recv_setup: setup receive side
106  *
107  * For no compression this function does nothing.
108  *
109  * Returns 0 for success or -1 for error
110  *
111  * @p: Params for the channel that we are using
112  * @errp: pointer to an error
113  */
114 static int nocomp_recv_setup(MultiFDRecvParams *p, Error **errp)
115 {
116     return 0;
117 }
118 
119 /**
120  * nocomp_recv_cleanup: setup receive side
121  *
122  * For no compression this function does nothing.
123  *
124  * @p: Params for the channel that we are using
125  */
126 static void nocomp_recv_cleanup(MultiFDRecvParams *p)
127 {
128 }
129 
130 /**
131  * nocomp_recv_pages: read the data from the channel into actual pages
132  *
133  * For no compression we just need to read things into the correct place.
134  *
135  * Returns 0 for success or -1 for error
136  *
137  * @p: Params for the channel that we are using
138  * @errp: pointer to an error
139  */
140 static int nocomp_recv_pages(MultiFDRecvParams *p, Error **errp)
141 {
142     uint32_t flags = p->flags & MULTIFD_FLAG_COMPRESSION_MASK;
143 
144     if (flags != MULTIFD_FLAG_NOCOMP) {
145         error_setg(errp, "multifd %u: flags received %x flags expected %x",
146                    p->id, flags, MULTIFD_FLAG_NOCOMP);
147         return -1;
148     }
149     for (int i = 0; i < p->normal_num; i++) {
150         p->iov[i].iov_base = p->host + p->normal[i];
151         p->iov[i].iov_len = p->page_size;
152     }
153     return qio_channel_readv_all(p->c, p->iov, p->normal_num, errp);
154 }
155 
156 static MultiFDMethods multifd_nocomp_ops = {
157     .send_setup = nocomp_send_setup,
158     .send_cleanup = nocomp_send_cleanup,
159     .send_prepare = nocomp_send_prepare,
160     .recv_setup = nocomp_recv_setup,
161     .recv_cleanup = nocomp_recv_cleanup,
162     .recv_pages = nocomp_recv_pages
163 };
164 
165 static MultiFDMethods *multifd_ops[MULTIFD_COMPRESSION__MAX] = {
166     [MULTIFD_COMPRESSION_NONE] = &multifd_nocomp_ops,
167 };
168 
169 void multifd_register_ops(int method, MultiFDMethods *ops)
170 {
171     assert(0 < method && method < MULTIFD_COMPRESSION__MAX);
172     multifd_ops[method] = ops;
173 }
174 
175 static int multifd_send_initial_packet(MultiFDSendParams *p, Error **errp)
176 {
177     MultiFDInit_t msg = {};
178     int ret;
179 
180     msg.magic = cpu_to_be32(MULTIFD_MAGIC);
181     msg.version = cpu_to_be32(MULTIFD_VERSION);
182     msg.id = p->id;
183     memcpy(msg.uuid, &qemu_uuid.data, sizeof(msg.uuid));
184 
185     ret = qio_channel_write_all(p->c, (char *)&msg, sizeof(msg), errp);
186     if (ret != 0) {
187         return -1;
188     }
189     return 0;
190 }
191 
192 static int multifd_recv_initial_packet(QIOChannel *c, Error **errp)
193 {
194     MultiFDInit_t msg;
195     int ret;
196 
197     ret = qio_channel_read_all(c, (char *)&msg, sizeof(msg), errp);
198     if (ret != 0) {
199         return -1;
200     }
201 
202     msg.magic = be32_to_cpu(msg.magic);
203     msg.version = be32_to_cpu(msg.version);
204 
205     if (msg.magic != MULTIFD_MAGIC) {
206         error_setg(errp, "multifd: received packet magic %x "
207                    "expected %x", msg.magic, MULTIFD_MAGIC);
208         return -1;
209     }
210 
211     if (msg.version != MULTIFD_VERSION) {
212         error_setg(errp, "multifd: received packet version %u "
213                    "expected %u", msg.version, MULTIFD_VERSION);
214         return -1;
215     }
216 
217     if (memcmp(msg.uuid, &qemu_uuid, sizeof(qemu_uuid))) {
218         char *uuid = qemu_uuid_unparse_strdup(&qemu_uuid);
219         char *msg_uuid = qemu_uuid_unparse_strdup((const QemuUUID *)msg.uuid);
220 
221         error_setg(errp, "multifd: received uuid '%s' and expected "
222                    "uuid '%s' for channel %hhd", msg_uuid, uuid, msg.id);
223         g_free(uuid);
224         g_free(msg_uuid);
225         return -1;
226     }
227 
228     if (msg.id > migrate_multifd_channels()) {
229         error_setg(errp, "multifd: received channel version %u "
230                    "expected %u", msg.version, MULTIFD_VERSION);
231         return -1;
232     }
233 
234     return msg.id;
235 }
236 
237 static MultiFDPages_t *multifd_pages_init(size_t size)
238 {
239     MultiFDPages_t *pages = g_new0(MultiFDPages_t, 1);
240 
241     pages->allocated = size;
242     pages->offset = g_new0(ram_addr_t, size);
243 
244     return pages;
245 }
246 
247 static void multifd_pages_clear(MultiFDPages_t *pages)
248 {
249     pages->num = 0;
250     pages->allocated = 0;
251     pages->packet_num = 0;
252     pages->block = NULL;
253     g_free(pages->offset);
254     pages->offset = NULL;
255     g_free(pages);
256 }
257 
258 static void multifd_send_fill_packet(MultiFDSendParams *p)
259 {
260     MultiFDPacket_t *packet = p->packet;
261     int i;
262 
263     packet->flags = cpu_to_be32(p->flags);
264     packet->pages_alloc = cpu_to_be32(p->pages->allocated);
265     packet->normal_pages = cpu_to_be32(p->normal_num);
266     packet->next_packet_size = cpu_to_be32(p->next_packet_size);
267     packet->packet_num = cpu_to_be64(p->packet_num);
268 
269     if (p->pages->block) {
270         strncpy(packet->ramblock, p->pages->block->idstr, 256);
271     }
272 
273     for (i = 0; i < p->normal_num; i++) {
274         /* there are architectures where ram_addr_t is 32 bit */
275         uint64_t temp = p->normal[i];
276 
277         packet->offset[i] = cpu_to_be64(temp);
278     }
279 }
280 
281 static int multifd_recv_unfill_packet(MultiFDRecvParams *p, Error **errp)
282 {
283     MultiFDPacket_t *packet = p->packet;
284     int i;
285 
286     packet->magic = be32_to_cpu(packet->magic);
287     if (packet->magic != MULTIFD_MAGIC) {
288         error_setg(errp, "multifd: received packet "
289                    "magic %x and expected magic %x",
290                    packet->magic, MULTIFD_MAGIC);
291         return -1;
292     }
293 
294     packet->version = be32_to_cpu(packet->version);
295     if (packet->version != MULTIFD_VERSION) {
296         error_setg(errp, "multifd: received packet "
297                    "version %u and expected version %u",
298                    packet->version, MULTIFD_VERSION);
299         return -1;
300     }
301 
302     p->flags = be32_to_cpu(packet->flags);
303 
304     packet->pages_alloc = be32_to_cpu(packet->pages_alloc);
305     /*
306      * If we received a packet that is 100 times bigger than expected
307      * just stop migration.  It is a magic number.
308      */
309     if (packet->pages_alloc > p->page_count) {
310         error_setg(errp, "multifd: received packet "
311                    "with size %u and expected a size of %u",
312                    packet->pages_alloc, p->page_count) ;
313         return -1;
314     }
315 
316     p->normal_num = be32_to_cpu(packet->normal_pages);
317     if (p->normal_num > packet->pages_alloc) {
318         error_setg(errp, "multifd: received packet "
319                    "with %u pages and expected maximum pages are %u",
320                    p->normal_num, packet->pages_alloc) ;
321         return -1;
322     }
323 
324     p->next_packet_size = be32_to_cpu(packet->next_packet_size);
325     p->packet_num = be64_to_cpu(packet->packet_num);
326 
327     if (p->normal_num == 0) {
328         return 0;
329     }
330 
331     /* make sure that ramblock is 0 terminated */
332     packet->ramblock[255] = 0;
333     p->block = qemu_ram_block_by_name(packet->ramblock);
334     if (!p->block) {
335         error_setg(errp, "multifd: unknown ram block %s",
336                    packet->ramblock);
337         return -1;
338     }
339 
340     p->host = p->block->host;
341     for (i = 0; i < p->normal_num; i++) {
342         uint64_t offset = be64_to_cpu(packet->offset[i]);
343 
344         if (offset > (p->block->used_length - p->page_size)) {
345             error_setg(errp, "multifd: offset too long %" PRIu64
346                        " (max " RAM_ADDR_FMT ")",
347                        offset, p->block->used_length);
348             return -1;
349         }
350         p->normal[i] = offset;
351     }
352 
353     return 0;
354 }
355 
356 struct {
357     MultiFDSendParams *params;
358     /* array of pages to sent */
359     MultiFDPages_t *pages;
360     /* global number of generated multifd packets */
361     uint64_t packet_num;
362     /* send channels ready */
363     QemuSemaphore channels_ready;
364     /*
365      * Have we already run terminate threads.  There is a race when it
366      * happens that we got one error while we are exiting.
367      * We will use atomic operations.  Only valid values are 0 and 1.
368      */
369     int exiting;
370     /* multifd ops */
371     MultiFDMethods *ops;
372 } *multifd_send_state;
373 
374 /*
375  * How we use multifd_send_state->pages and channel->pages?
376  *
377  * We create a pages for each channel, and a main one.  Each time that
378  * we need to send a batch of pages we interchange the ones between
379  * multifd_send_state and the channel that is sending it.  There are
380  * two reasons for that:
381  *    - to not have to do so many mallocs during migration
382  *    - to make easier to know what to free at the end of migration
383  *
384  * This way we always know who is the owner of each "pages" struct,
385  * and we don't need any locking.  It belongs to the migration thread
386  * or to the channel thread.  Switching is safe because the migration
387  * thread is using the channel mutex when changing it, and the channel
388  * have to had finish with its own, otherwise pending_job can't be
389  * false.
390  */
391 
392 static int multifd_send_pages(QEMUFile *f)
393 {
394     int i;
395     static int next_channel;
396     MultiFDSendParams *p = NULL; /* make happy gcc */
397     MultiFDPages_t *pages = multifd_send_state->pages;
398     uint64_t transferred;
399 
400     if (qatomic_read(&multifd_send_state->exiting)) {
401         return -1;
402     }
403 
404     qemu_sem_wait(&multifd_send_state->channels_ready);
405     /*
406      * next_channel can remain from a previous migration that was
407      * using more channels, so ensure it doesn't overflow if the
408      * limit is lower now.
409      */
410     next_channel %= migrate_multifd_channels();
411     for (i = next_channel;; i = (i + 1) % migrate_multifd_channels()) {
412         p = &multifd_send_state->params[i];
413 
414         qemu_mutex_lock(&p->mutex);
415         if (p->quit) {
416             error_report("%s: channel %d has already quit!", __func__, i);
417             qemu_mutex_unlock(&p->mutex);
418             return -1;
419         }
420         if (!p->pending_job) {
421             p->pending_job++;
422             next_channel = (i + 1) % migrate_multifd_channels();
423             break;
424         }
425         qemu_mutex_unlock(&p->mutex);
426     }
427     assert(!p->pages->num);
428     assert(!p->pages->block);
429 
430     p->packet_num = multifd_send_state->packet_num++;
431     multifd_send_state->pages = p->pages;
432     p->pages = pages;
433     transferred = ((uint64_t) pages->num) * p->page_size + p->packet_len;
434     qemu_file_acct_rate_limit(f, transferred);
435     qemu_mutex_unlock(&p->mutex);
436     stat64_add(&mig_stats.transferred, transferred);
437     stat64_add(&mig_stats.multifd_bytes, transferred);
438     qemu_sem_post(&p->sem);
439 
440     return 1;
441 }
442 
443 int multifd_queue_page(QEMUFile *f, RAMBlock *block, ram_addr_t offset)
444 {
445     MultiFDPages_t *pages = multifd_send_state->pages;
446     bool changed = false;
447 
448     if (!pages->block) {
449         pages->block = block;
450     }
451 
452     if (pages->block == block) {
453         pages->offset[pages->num] = offset;
454         pages->num++;
455 
456         if (pages->num < pages->allocated) {
457             return 1;
458         }
459     } else {
460         changed = true;
461     }
462 
463     if (multifd_send_pages(f) < 0) {
464         return -1;
465     }
466 
467     if (changed) {
468         return multifd_queue_page(f, block, offset);
469     }
470 
471     return 1;
472 }
473 
474 static void multifd_send_terminate_threads(Error *err)
475 {
476     int i;
477 
478     trace_multifd_send_terminate_threads(err != NULL);
479 
480     if (err) {
481         MigrationState *s = migrate_get_current();
482         migrate_set_error(s, err);
483         if (s->state == MIGRATION_STATUS_SETUP ||
484             s->state == MIGRATION_STATUS_PRE_SWITCHOVER ||
485             s->state == MIGRATION_STATUS_DEVICE ||
486             s->state == MIGRATION_STATUS_ACTIVE) {
487             migrate_set_state(&s->state, s->state,
488                               MIGRATION_STATUS_FAILED);
489         }
490     }
491 
492     /*
493      * We don't want to exit each threads twice.  Depending on where
494      * we get the error, or if there are two independent errors in two
495      * threads at the same time, we can end calling this function
496      * twice.
497      */
498     if (qatomic_xchg(&multifd_send_state->exiting, 1)) {
499         return;
500     }
501 
502     for (i = 0; i < migrate_multifd_channels(); i++) {
503         MultiFDSendParams *p = &multifd_send_state->params[i];
504 
505         qemu_mutex_lock(&p->mutex);
506         p->quit = true;
507         qemu_sem_post(&p->sem);
508         if (p->c) {
509             qio_channel_shutdown(p->c, QIO_CHANNEL_SHUTDOWN_BOTH, NULL);
510         }
511         qemu_mutex_unlock(&p->mutex);
512     }
513 }
514 
515 void multifd_save_cleanup(void)
516 {
517     int i;
518 
519     if (!migrate_multifd()) {
520         return;
521     }
522     multifd_send_terminate_threads(NULL);
523     for (i = 0; i < migrate_multifd_channels(); i++) {
524         MultiFDSendParams *p = &multifd_send_state->params[i];
525 
526         if (p->running) {
527             qemu_thread_join(&p->thread);
528         }
529     }
530     for (i = 0; i < migrate_multifd_channels(); i++) {
531         MultiFDSendParams *p = &multifd_send_state->params[i];
532         Error *local_err = NULL;
533 
534         if (p->registered_yank) {
535             migration_ioc_unregister_yank(p->c);
536         }
537         socket_send_channel_destroy(p->c);
538         p->c = NULL;
539         qemu_mutex_destroy(&p->mutex);
540         qemu_sem_destroy(&p->sem);
541         qemu_sem_destroy(&p->sem_sync);
542         g_free(p->name);
543         p->name = NULL;
544         multifd_pages_clear(p->pages);
545         p->pages = NULL;
546         p->packet_len = 0;
547         g_free(p->packet);
548         p->packet = NULL;
549         g_free(p->iov);
550         p->iov = NULL;
551         g_free(p->normal);
552         p->normal = NULL;
553         multifd_send_state->ops->send_cleanup(p, &local_err);
554         if (local_err) {
555             migrate_set_error(migrate_get_current(), local_err);
556             error_free(local_err);
557         }
558     }
559     qemu_sem_destroy(&multifd_send_state->channels_ready);
560     g_free(multifd_send_state->params);
561     multifd_send_state->params = NULL;
562     multifd_pages_clear(multifd_send_state->pages);
563     multifd_send_state->pages = NULL;
564     g_free(multifd_send_state);
565     multifd_send_state = NULL;
566 }
567 
568 static int multifd_zero_copy_flush(QIOChannel *c)
569 {
570     int ret;
571     Error *err = NULL;
572 
573     ret = qio_channel_flush(c, &err);
574     if (ret < 0) {
575         error_report_err(err);
576         return -1;
577     }
578     if (ret == 1) {
579         stat64_add(&mig_stats.dirty_sync_missed_zero_copy, 1);
580     }
581 
582     return ret;
583 }
584 
585 int multifd_send_sync_main(QEMUFile *f)
586 {
587     int i;
588     bool flush_zero_copy;
589 
590     if (!migrate_multifd()) {
591         return 0;
592     }
593     if (multifd_send_state->pages->num) {
594         if (multifd_send_pages(f) < 0) {
595             error_report("%s: multifd_send_pages fail", __func__);
596             return -1;
597         }
598     }
599 
600     /*
601      * When using zero-copy, it's necessary to flush the pages before any of
602      * the pages can be sent again, so we'll make sure the new version of the
603      * pages will always arrive _later_ than the old pages.
604      *
605      * Currently we achieve this by flushing the zero-page requested writes
606      * per ram iteration, but in the future we could potentially optimize it
607      * to be less frequent, e.g. only after we finished one whole scanning of
608      * all the dirty bitmaps.
609      */
610 
611     flush_zero_copy = migrate_zero_copy_send();
612 
613     for (i = 0; i < migrate_multifd_channels(); i++) {
614         MultiFDSendParams *p = &multifd_send_state->params[i];
615 
616         trace_multifd_send_sync_main_signal(p->id);
617 
618         qemu_mutex_lock(&p->mutex);
619 
620         if (p->quit) {
621             error_report("%s: channel %d has already quit", __func__, i);
622             qemu_mutex_unlock(&p->mutex);
623             return -1;
624         }
625 
626         p->packet_num = multifd_send_state->packet_num++;
627         p->flags |= MULTIFD_FLAG_SYNC;
628         p->pending_job++;
629         qemu_mutex_unlock(&p->mutex);
630         qemu_sem_post(&p->sem);
631     }
632     for (i = 0; i < migrate_multifd_channels(); i++) {
633         MultiFDSendParams *p = &multifd_send_state->params[i];
634 
635         qemu_sem_wait(&multifd_send_state->channels_ready);
636         trace_multifd_send_sync_main_wait(p->id);
637         qemu_sem_wait(&p->sem_sync);
638 
639         if (flush_zero_copy && p->c && (multifd_zero_copy_flush(p->c) < 0)) {
640             return -1;
641         }
642     }
643     trace_multifd_send_sync_main(multifd_send_state->packet_num);
644 
645     return 0;
646 }
647 
648 static void *multifd_send_thread(void *opaque)
649 {
650     MultiFDSendParams *p = opaque;
651     MigrationThread *thread = NULL;
652     Error *local_err = NULL;
653     int ret = 0;
654     bool use_zero_copy_send = migrate_zero_copy_send();
655 
656     thread = MigrationThreadAdd(p->name, qemu_get_thread_id());
657 
658     trace_multifd_send_thread_start(p->id);
659     rcu_register_thread();
660 
661     if (multifd_send_initial_packet(p, &local_err) < 0) {
662         ret = -1;
663         goto out;
664     }
665     /* initial packet */
666     p->num_packets = 1;
667 
668     while (true) {
669         qemu_sem_post(&multifd_send_state->channels_ready);
670         qemu_sem_wait(&p->sem);
671 
672         if (qatomic_read(&multifd_send_state->exiting)) {
673             break;
674         }
675         qemu_mutex_lock(&p->mutex);
676 
677         if (p->pending_job) {
678             uint64_t packet_num = p->packet_num;
679             uint32_t flags;
680             p->normal_num = 0;
681 
682             if (use_zero_copy_send) {
683                 p->iovs_num = 0;
684             } else {
685                 p->iovs_num = 1;
686             }
687 
688             for (int i = 0; i < p->pages->num; i++) {
689                 p->normal[p->normal_num] = p->pages->offset[i];
690                 p->normal_num++;
691             }
692 
693             if (p->normal_num) {
694                 ret = multifd_send_state->ops->send_prepare(p, &local_err);
695                 if (ret != 0) {
696                     qemu_mutex_unlock(&p->mutex);
697                     break;
698                 }
699             }
700             multifd_send_fill_packet(p);
701             flags = p->flags;
702             p->flags = 0;
703             p->num_packets++;
704             p->total_normal_pages += p->normal_num;
705             p->pages->num = 0;
706             p->pages->block = NULL;
707             qemu_mutex_unlock(&p->mutex);
708 
709             trace_multifd_send(p->id, packet_num, p->normal_num, flags,
710                                p->next_packet_size);
711 
712             if (use_zero_copy_send) {
713                 /* Send header first, without zerocopy */
714                 ret = qio_channel_write_all(p->c, (void *)p->packet,
715                                             p->packet_len, &local_err);
716                 if (ret != 0) {
717                     break;
718                 }
719             } else {
720                 /* Send header using the same writev call */
721                 p->iov[0].iov_len = p->packet_len;
722                 p->iov[0].iov_base = p->packet;
723             }
724 
725             ret = qio_channel_writev_full_all(p->c, p->iov, p->iovs_num, NULL,
726                                               0, p->write_flags, &local_err);
727             if (ret != 0) {
728                 break;
729             }
730 
731             qemu_mutex_lock(&p->mutex);
732             p->pending_job--;
733             qemu_mutex_unlock(&p->mutex);
734 
735             if (flags & MULTIFD_FLAG_SYNC) {
736                 qemu_sem_post(&p->sem_sync);
737             }
738         } else if (p->quit) {
739             qemu_mutex_unlock(&p->mutex);
740             break;
741         } else {
742             qemu_mutex_unlock(&p->mutex);
743             /* sometimes there are spurious wakeups */
744         }
745     }
746 
747 out:
748     if (local_err) {
749         trace_multifd_send_error(p->id);
750         multifd_send_terminate_threads(local_err);
751         error_free(local_err);
752     }
753 
754     /*
755      * Error happen, I will exit, but I can't just leave, tell
756      * who pay attention to me.
757      */
758     if (ret != 0) {
759         qemu_sem_post(&p->sem_sync);
760         qemu_sem_post(&multifd_send_state->channels_ready);
761     }
762 
763     qemu_mutex_lock(&p->mutex);
764     p->running = false;
765     qemu_mutex_unlock(&p->mutex);
766 
767     rcu_unregister_thread();
768     MigrationThreadDel(thread);
769     trace_multifd_send_thread_end(p->id, p->num_packets, p->total_normal_pages);
770 
771     return NULL;
772 }
773 
774 static bool multifd_channel_connect(MultiFDSendParams *p,
775                                     QIOChannel *ioc,
776                                     Error *error);
777 
778 static void multifd_tls_outgoing_handshake(QIOTask *task,
779                                            gpointer opaque)
780 {
781     MultiFDSendParams *p = opaque;
782     QIOChannel *ioc = QIO_CHANNEL(qio_task_get_source(task));
783     Error *err = NULL;
784 
785     if (qio_task_propagate_error(task, &err)) {
786         trace_multifd_tls_outgoing_handshake_error(ioc, error_get_pretty(err));
787     } else {
788         trace_multifd_tls_outgoing_handshake_complete(ioc);
789     }
790 
791     if (!multifd_channel_connect(p, ioc, err)) {
792         /*
793          * Error happen, mark multifd_send_thread status as 'quit' although it
794          * is not created, and then tell who pay attention to me.
795          */
796         p->quit = true;
797         qemu_sem_post(&multifd_send_state->channels_ready);
798         qemu_sem_post(&p->sem_sync);
799     }
800 }
801 
802 static void *multifd_tls_handshake_thread(void *opaque)
803 {
804     MultiFDSendParams *p = opaque;
805     QIOChannelTLS *tioc = QIO_CHANNEL_TLS(p->c);
806 
807     qio_channel_tls_handshake(tioc,
808                               multifd_tls_outgoing_handshake,
809                               p,
810                               NULL,
811                               NULL);
812     return NULL;
813 }
814 
815 static void multifd_tls_channel_connect(MultiFDSendParams *p,
816                                         QIOChannel *ioc,
817                                         Error **errp)
818 {
819     MigrationState *s = migrate_get_current();
820     const char *hostname = s->hostname;
821     QIOChannelTLS *tioc;
822 
823     tioc = migration_tls_client_create(ioc, hostname, errp);
824     if (!tioc) {
825         return;
826     }
827 
828     object_unref(OBJECT(ioc));
829     trace_multifd_tls_outgoing_handshake_start(ioc, tioc, hostname);
830     qio_channel_set_name(QIO_CHANNEL(tioc), "multifd-tls-outgoing");
831     p->c = QIO_CHANNEL(tioc);
832     qemu_thread_create(&p->thread, "multifd-tls-handshake-worker",
833                        multifd_tls_handshake_thread, p,
834                        QEMU_THREAD_JOINABLE);
835 }
836 
837 static bool multifd_channel_connect(MultiFDSendParams *p,
838                                     QIOChannel *ioc,
839                                     Error *error)
840 {
841     trace_multifd_set_outgoing_channel(
842         ioc, object_get_typename(OBJECT(ioc)),
843         migrate_get_current()->hostname, error);
844 
845     if (error) {
846         return false;
847     }
848     if (migrate_channel_requires_tls_upgrade(ioc)) {
849         multifd_tls_channel_connect(p, ioc, &error);
850         if (!error) {
851             /*
852              * tls_channel_connect will call back to this
853              * function after the TLS handshake,
854              * so we mustn't call multifd_send_thread until then
855              */
856             return true;
857         } else {
858             return false;
859         }
860     } else {
861         migration_ioc_register_yank(ioc);
862         p->registered_yank = true;
863         p->c = ioc;
864         qemu_thread_create(&p->thread, p->name, multifd_send_thread, p,
865                            QEMU_THREAD_JOINABLE);
866     }
867     return true;
868 }
869 
870 static void multifd_new_send_channel_cleanup(MultiFDSendParams *p,
871                                              QIOChannel *ioc, Error *err)
872 {
873      migrate_set_error(migrate_get_current(), err);
874      /* Error happen, we need to tell who pay attention to me */
875      qemu_sem_post(&multifd_send_state->channels_ready);
876      qemu_sem_post(&p->sem_sync);
877      /*
878       * Although multifd_send_thread is not created, but main migration
879       * thread neet to judge whether it is running, so we need to mark
880       * its status.
881       */
882      p->quit = true;
883      object_unref(OBJECT(ioc));
884      error_free(err);
885 }
886 
887 static void multifd_new_send_channel_async(QIOTask *task, gpointer opaque)
888 {
889     MultiFDSendParams *p = opaque;
890     QIOChannel *sioc = QIO_CHANNEL(qio_task_get_source(task));
891     Error *local_err = NULL;
892 
893     trace_multifd_new_send_channel_async(p->id);
894     if (!qio_task_propagate_error(task, &local_err)) {
895         p->c = QIO_CHANNEL(sioc);
896         qio_channel_set_delay(p->c, false);
897         p->running = true;
898         if (multifd_channel_connect(p, sioc, local_err)) {
899             return;
900         }
901     }
902 
903     multifd_new_send_channel_cleanup(p, sioc, local_err);
904 }
905 
906 int multifd_save_setup(Error **errp)
907 {
908     int thread_count;
909     uint32_t page_count = MULTIFD_PACKET_SIZE / qemu_target_page_size();
910     uint8_t i;
911 
912     if (!migrate_multifd()) {
913         return 0;
914     }
915 
916     thread_count = migrate_multifd_channels();
917     multifd_send_state = g_malloc0(sizeof(*multifd_send_state));
918     multifd_send_state->params = g_new0(MultiFDSendParams, thread_count);
919     multifd_send_state->pages = multifd_pages_init(page_count);
920     qemu_sem_init(&multifd_send_state->channels_ready, 0);
921     qatomic_set(&multifd_send_state->exiting, 0);
922     multifd_send_state->ops = multifd_ops[migrate_multifd_compression()];
923 
924     for (i = 0; i < thread_count; i++) {
925         MultiFDSendParams *p = &multifd_send_state->params[i];
926 
927         qemu_mutex_init(&p->mutex);
928         qemu_sem_init(&p->sem, 0);
929         qemu_sem_init(&p->sem_sync, 0);
930         p->quit = false;
931         p->pending_job = 0;
932         p->id = i;
933         p->pages = multifd_pages_init(page_count);
934         p->packet_len = sizeof(MultiFDPacket_t)
935                       + sizeof(uint64_t) * page_count;
936         p->packet = g_malloc0(p->packet_len);
937         p->packet->magic = cpu_to_be32(MULTIFD_MAGIC);
938         p->packet->version = cpu_to_be32(MULTIFD_VERSION);
939         p->name = g_strdup_printf("multifdsend_%d", i);
940         /* We need one extra place for the packet header */
941         p->iov = g_new0(struct iovec, page_count + 1);
942         p->normal = g_new0(ram_addr_t, page_count);
943         p->page_size = qemu_target_page_size();
944         p->page_count = page_count;
945 
946         if (migrate_zero_copy_send()) {
947             p->write_flags = QIO_CHANNEL_WRITE_FLAG_ZERO_COPY;
948         } else {
949             p->write_flags = 0;
950         }
951 
952         socket_send_channel_create(multifd_new_send_channel_async, p);
953     }
954 
955     for (i = 0; i < thread_count; i++) {
956         MultiFDSendParams *p = &multifd_send_state->params[i];
957         Error *local_err = NULL;
958         int ret;
959 
960         ret = multifd_send_state->ops->send_setup(p, &local_err);
961         if (ret) {
962             error_propagate(errp, local_err);
963             return ret;
964         }
965     }
966     return 0;
967 }
968 
969 struct {
970     MultiFDRecvParams *params;
971     /* number of created threads */
972     int count;
973     /* syncs main thread and channels */
974     QemuSemaphore sem_sync;
975     /* global number of generated multifd packets */
976     uint64_t packet_num;
977     /* multifd ops */
978     MultiFDMethods *ops;
979 } *multifd_recv_state;
980 
981 static void multifd_recv_terminate_threads(Error *err)
982 {
983     int i;
984 
985     trace_multifd_recv_terminate_threads(err != NULL);
986 
987     if (err) {
988         MigrationState *s = migrate_get_current();
989         migrate_set_error(s, err);
990         if (s->state == MIGRATION_STATUS_SETUP ||
991             s->state == MIGRATION_STATUS_ACTIVE) {
992             migrate_set_state(&s->state, s->state,
993                               MIGRATION_STATUS_FAILED);
994         }
995     }
996 
997     for (i = 0; i < migrate_multifd_channels(); i++) {
998         MultiFDRecvParams *p = &multifd_recv_state->params[i];
999 
1000         qemu_mutex_lock(&p->mutex);
1001         p->quit = true;
1002         /*
1003          * We could arrive here for two reasons:
1004          *  - normal quit, i.e. everything went fine, just finished
1005          *  - error quit: We close the channels so the channel threads
1006          *    finish the qio_channel_read_all_eof()
1007          */
1008         if (p->c) {
1009             qio_channel_shutdown(p->c, QIO_CHANNEL_SHUTDOWN_BOTH, NULL);
1010         }
1011         qemu_mutex_unlock(&p->mutex);
1012     }
1013 }
1014 
1015 void multifd_load_shutdown(void)
1016 {
1017     if (migrate_multifd()) {
1018         multifd_recv_terminate_threads(NULL);
1019     }
1020 }
1021 
1022 void multifd_load_cleanup(void)
1023 {
1024     int i;
1025 
1026     if (!migrate_multifd()) {
1027         return;
1028     }
1029     multifd_recv_terminate_threads(NULL);
1030     for (i = 0; i < migrate_multifd_channels(); i++) {
1031         MultiFDRecvParams *p = &multifd_recv_state->params[i];
1032 
1033         if (p->running) {
1034             /*
1035              * multifd_recv_thread may hung at MULTIFD_FLAG_SYNC handle code,
1036              * however try to wakeup it without harm in cleanup phase.
1037              */
1038             qemu_sem_post(&p->sem_sync);
1039         }
1040 
1041         qemu_thread_join(&p->thread);
1042     }
1043     for (i = 0; i < migrate_multifd_channels(); i++) {
1044         MultiFDRecvParams *p = &multifd_recv_state->params[i];
1045 
1046         migration_ioc_unregister_yank(p->c);
1047         object_unref(OBJECT(p->c));
1048         p->c = NULL;
1049         qemu_mutex_destroy(&p->mutex);
1050         qemu_sem_destroy(&p->sem_sync);
1051         g_free(p->name);
1052         p->name = NULL;
1053         p->packet_len = 0;
1054         g_free(p->packet);
1055         p->packet = NULL;
1056         g_free(p->iov);
1057         p->iov = NULL;
1058         g_free(p->normal);
1059         p->normal = NULL;
1060         multifd_recv_state->ops->recv_cleanup(p);
1061     }
1062     qemu_sem_destroy(&multifd_recv_state->sem_sync);
1063     g_free(multifd_recv_state->params);
1064     multifd_recv_state->params = NULL;
1065     g_free(multifd_recv_state);
1066     multifd_recv_state = NULL;
1067 }
1068 
1069 void multifd_recv_sync_main(void)
1070 {
1071     int i;
1072 
1073     if (!migrate_multifd()) {
1074         return;
1075     }
1076     for (i = 0; i < migrate_multifd_channels(); i++) {
1077         MultiFDRecvParams *p = &multifd_recv_state->params[i];
1078 
1079         trace_multifd_recv_sync_main_wait(p->id);
1080         qemu_sem_wait(&multifd_recv_state->sem_sync);
1081     }
1082     for (i = 0; i < migrate_multifd_channels(); i++) {
1083         MultiFDRecvParams *p = &multifd_recv_state->params[i];
1084 
1085         WITH_QEMU_LOCK_GUARD(&p->mutex) {
1086             if (multifd_recv_state->packet_num < p->packet_num) {
1087                 multifd_recv_state->packet_num = p->packet_num;
1088             }
1089         }
1090         trace_multifd_recv_sync_main_signal(p->id);
1091         qemu_sem_post(&p->sem_sync);
1092     }
1093     trace_multifd_recv_sync_main(multifd_recv_state->packet_num);
1094 }
1095 
1096 static void *multifd_recv_thread(void *opaque)
1097 {
1098     MultiFDRecvParams *p = opaque;
1099     Error *local_err = NULL;
1100     int ret;
1101 
1102     trace_multifd_recv_thread_start(p->id);
1103     rcu_register_thread();
1104 
1105     while (true) {
1106         uint32_t flags;
1107 
1108         if (p->quit) {
1109             break;
1110         }
1111 
1112         ret = qio_channel_read_all_eof(p->c, (void *)p->packet,
1113                                        p->packet_len, &local_err);
1114         if (ret == 0 || ret == -1) {   /* 0: EOF  -1: Error */
1115             break;
1116         }
1117 
1118         qemu_mutex_lock(&p->mutex);
1119         ret = multifd_recv_unfill_packet(p, &local_err);
1120         if (ret) {
1121             qemu_mutex_unlock(&p->mutex);
1122             break;
1123         }
1124 
1125         flags = p->flags;
1126         /* recv methods don't know how to handle the SYNC flag */
1127         p->flags &= ~MULTIFD_FLAG_SYNC;
1128         trace_multifd_recv(p->id, p->packet_num, p->normal_num, flags,
1129                            p->next_packet_size);
1130         p->num_packets++;
1131         p->total_normal_pages += p->normal_num;
1132         qemu_mutex_unlock(&p->mutex);
1133 
1134         if (p->normal_num) {
1135             ret = multifd_recv_state->ops->recv_pages(p, &local_err);
1136             if (ret != 0) {
1137                 break;
1138             }
1139         }
1140 
1141         if (flags & MULTIFD_FLAG_SYNC) {
1142             qemu_sem_post(&multifd_recv_state->sem_sync);
1143             qemu_sem_wait(&p->sem_sync);
1144         }
1145     }
1146 
1147     if (local_err) {
1148         multifd_recv_terminate_threads(local_err);
1149         error_free(local_err);
1150     }
1151     qemu_mutex_lock(&p->mutex);
1152     p->running = false;
1153     qemu_mutex_unlock(&p->mutex);
1154 
1155     rcu_unregister_thread();
1156     trace_multifd_recv_thread_end(p->id, p->num_packets, p->total_normal_pages);
1157 
1158     return NULL;
1159 }
1160 
1161 int multifd_load_setup(Error **errp)
1162 {
1163     int thread_count;
1164     uint32_t page_count = MULTIFD_PACKET_SIZE / qemu_target_page_size();
1165     uint8_t i;
1166 
1167     /*
1168      * Return successfully if multiFD recv state is already initialised
1169      * or multiFD is not enabled.
1170      */
1171     if (multifd_recv_state || !migrate_multifd()) {
1172         return 0;
1173     }
1174 
1175     thread_count = migrate_multifd_channels();
1176     multifd_recv_state = g_malloc0(sizeof(*multifd_recv_state));
1177     multifd_recv_state->params = g_new0(MultiFDRecvParams, thread_count);
1178     qatomic_set(&multifd_recv_state->count, 0);
1179     qemu_sem_init(&multifd_recv_state->sem_sync, 0);
1180     multifd_recv_state->ops = multifd_ops[migrate_multifd_compression()];
1181 
1182     for (i = 0; i < thread_count; i++) {
1183         MultiFDRecvParams *p = &multifd_recv_state->params[i];
1184 
1185         qemu_mutex_init(&p->mutex);
1186         qemu_sem_init(&p->sem_sync, 0);
1187         p->quit = false;
1188         p->id = i;
1189         p->packet_len = sizeof(MultiFDPacket_t)
1190                       + sizeof(uint64_t) * page_count;
1191         p->packet = g_malloc0(p->packet_len);
1192         p->name = g_strdup_printf("multifdrecv_%d", i);
1193         p->iov = g_new0(struct iovec, page_count);
1194         p->normal = g_new0(ram_addr_t, page_count);
1195         p->page_count = page_count;
1196         p->page_size = qemu_target_page_size();
1197     }
1198 
1199     for (i = 0; i < thread_count; i++) {
1200         MultiFDRecvParams *p = &multifd_recv_state->params[i];
1201         Error *local_err = NULL;
1202         int ret;
1203 
1204         ret = multifd_recv_state->ops->recv_setup(p, &local_err);
1205         if (ret) {
1206             error_propagate(errp, local_err);
1207             return ret;
1208         }
1209     }
1210     return 0;
1211 }
1212 
1213 bool multifd_recv_all_channels_created(void)
1214 {
1215     int thread_count = migrate_multifd_channels();
1216 
1217     if (!migrate_multifd()) {
1218         return true;
1219     }
1220 
1221     if (!multifd_recv_state) {
1222         /* Called before any connections created */
1223         return false;
1224     }
1225 
1226     return thread_count == qatomic_read(&multifd_recv_state->count);
1227 }
1228 
1229 /*
1230  * Try to receive all multifd channels to get ready for the migration.
1231  * Sets @errp when failing to receive the current channel.
1232  */
1233 void multifd_recv_new_channel(QIOChannel *ioc, Error **errp)
1234 {
1235     MultiFDRecvParams *p;
1236     Error *local_err = NULL;
1237     int id;
1238 
1239     id = multifd_recv_initial_packet(ioc, &local_err);
1240     if (id < 0) {
1241         multifd_recv_terminate_threads(local_err);
1242         error_propagate_prepend(errp, local_err,
1243                                 "failed to receive packet"
1244                                 " via multifd channel %d: ",
1245                                 qatomic_read(&multifd_recv_state->count));
1246         return;
1247     }
1248     trace_multifd_recv_new_channel(id);
1249 
1250     p = &multifd_recv_state->params[id];
1251     if (p->c != NULL) {
1252         error_setg(&local_err, "multifd: received id '%d' already setup'",
1253                    id);
1254         multifd_recv_terminate_threads(local_err);
1255         error_propagate(errp, local_err);
1256         return;
1257     }
1258     p->c = ioc;
1259     object_ref(OBJECT(ioc));
1260     /* initial packet */
1261     p->num_packets = 1;
1262 
1263     p->running = true;
1264     qemu_thread_create(&p->thread, p->name, multifd_recv_thread, p,
1265                        QEMU_THREAD_JOINABLE);
1266     qatomic_inc(&multifd_recv_state->count);
1267 }
1268