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