xref: /openbmc/qemu/backends/tpm/tpm_emulator.c (revision a0bcec03)
1 /*
2  *  Emulator TPM driver
3  *
4  *  Copyright (c) 2017 Intel Corporation
5  *  Author: Amarnath Valluri <amarnath.valluri@intel.com>
6  *
7  *  Copyright (c) 2010 - 2013, 2018 IBM Corporation
8  *  Authors:
9  *    Stefan Berger <stefanb@us.ibm.com>
10  *
11  *  Copyright (C) 2011 IAIK, Graz University of Technology
12  *    Author: Andreas Niederl
13  *
14  * This library is free software; you can redistribute it and/or
15  * modify it under the terms of the GNU Lesser General Public
16  * License as published by the Free Software Foundation; either
17  * version 2.1 of the License, or (at your option) any later version.
18  *
19  * This library is distributed in the hope that it will be useful,
20  * but WITHOUT ANY WARRANTY; without even the implied warranty of
21  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
22  * Lesser General Public License for more details.
23  *
24  * You should have received a copy of the GNU Lesser General Public
25  * License along with this library; if not, see <http://www.gnu.org/licenses/>
26  *
27  */
28 
29 #include "qemu/osdep.h"
30 #include "qemu/error-report.h"
31 #include "qemu/module.h"
32 #include "qemu/sockets.h"
33 #include "qemu/lockable.h"
34 #include "io/channel-socket.h"
35 #include "sysemu/runstate.h"
36 #include "sysemu/tpm_backend.h"
37 #include "sysemu/tpm_util.h"
38 #include "tpm_int.h"
39 #include "tpm_ioctl.h"
40 #include "migration/blocker.h"
41 #include "migration/vmstate.h"
42 #include "qapi/error.h"
43 #include "qapi/clone-visitor.h"
44 #include "qapi/qapi-visit-tpm.h"
45 #include "chardev/char-fe.h"
46 #include "trace.h"
47 #include "qom/object.h"
48 
49 #define TYPE_TPM_EMULATOR "tpm-emulator"
50 OBJECT_DECLARE_SIMPLE_TYPE(TPMEmulator, TPM_EMULATOR)
51 
52 #define TPM_EMULATOR_IMPLEMENTS_ALL_CAPS(S, cap) (((S)->caps & (cap)) == (cap))
53 
54 /* data structures */
55 
56 /* blobs from the TPM; part of VM state when migrating */
57 typedef struct TPMBlobBuffers {
58     uint32_t permanent_flags;
59     TPMSizedBuffer permanent;
60 
61     uint32_t volatil_flags;
62     TPMSizedBuffer volatil;
63 
64     uint32_t savestate_flags;
65     TPMSizedBuffer savestate;
66 } TPMBlobBuffers;
67 
68 struct TPMEmulator {
69     TPMBackend parent;
70 
71     TPMEmulatorOptions *options;
72     CharBackend ctrl_chr;
73     QIOChannel *data_ioc;
74     TPMVersion tpm_version;
75     ptm_cap caps; /* capabilities of the TPM */
76     uint8_t cur_locty_number; /* last set locality */
77     Error *migration_blocker;
78 
79     QemuMutex mutex;
80 
81     unsigned int established_flag:1;
82     unsigned int established_flag_cached:1;
83 
84     TPMBlobBuffers state_blobs;
85 };
86 
87 struct tpm_error {
88     uint32_t tpm_result;
89     const char *string;
90 };
91 
92 static const struct tpm_error tpm_errors[] = {
93     /* TPM 1.2 error codes */
94     { TPM_BAD_PARAMETER   , "a parameter is bad" },
95     { TPM_FAIL            , "operation failed" },
96     { TPM_KEYNOTFOUND     , "key could not be found" },
97     { TPM_BAD_PARAM_SIZE  , "bad parameter size"},
98     { TPM_ENCRYPT_ERROR   , "encryption error" },
99     { TPM_DECRYPT_ERROR   , "decryption error" },
100     { TPM_BAD_KEY_PROPERTY, "bad key property" },
101     { TPM_BAD_MODE        , "bad (encryption) mode" },
102     { TPM_BAD_VERSION     , "bad version identifier" },
103     { TPM_BAD_LOCALITY    , "bad locality" },
104     /* TPM 2 error codes */
105     { TPM_RC_FAILURE     , "operation failed" },
106     { TPM_RC_LOCALITY    , "bad locality"     },
107     { TPM_RC_INSUFFICIENT, "insufficient amount of data" },
108 };
109 
110 static const char *tpm_emulator_strerror(uint32_t tpm_result)
111 {
112     size_t i;
113 
114     for (i = 0; i < ARRAY_SIZE(tpm_errors); i++) {
115         if (tpm_errors[i].tpm_result == tpm_result) {
116             return tpm_errors[i].string;
117         }
118     }
119     return "";
120 }
121 
122 static int tpm_emulator_ctrlcmd(TPMEmulator *tpm, unsigned long cmd, void *msg,
123                                 size_t msg_len_in, size_t msg_len_out)
124 {
125     CharBackend *dev = &tpm->ctrl_chr;
126     uint32_t cmd_no = cpu_to_be32(cmd);
127     ssize_t n = sizeof(uint32_t) + msg_len_in;
128     uint8_t *buf = NULL;
129 
130     WITH_QEMU_LOCK_GUARD(&tpm->mutex) {
131         buf = g_alloca(n);
132         memcpy(buf, &cmd_no, sizeof(cmd_no));
133         memcpy(buf + sizeof(cmd_no), msg, msg_len_in);
134 
135         n = qemu_chr_fe_write_all(dev, buf, n);
136         if (n <= 0) {
137             return -1;
138         }
139 
140         if (msg_len_out != 0) {
141             n = qemu_chr_fe_read_all(dev, msg, msg_len_out);
142             if (n <= 0) {
143                 return -1;
144             }
145         }
146     }
147 
148     return 0;
149 }
150 
151 static int tpm_emulator_unix_tx_bufs(TPMEmulator *tpm_emu,
152                                      const uint8_t *in, uint32_t in_len,
153                                      uint8_t *out, uint32_t out_len,
154                                      bool *selftest_done,
155                                      Error **errp)
156 {
157     ssize_t ret;
158     bool is_selftest = false;
159 
160     if (selftest_done) {
161         *selftest_done = false;
162         is_selftest = tpm_util_is_selftest(in, in_len);
163     }
164 
165     ret = qio_channel_write_all(tpm_emu->data_ioc, (char *)in, in_len, errp);
166     if (ret != 0) {
167         return -1;
168     }
169 
170     ret = qio_channel_read_all(tpm_emu->data_ioc, (char *)out,
171               sizeof(struct tpm_resp_hdr), errp);
172     if (ret != 0) {
173         return -1;
174     }
175 
176     ret = qio_channel_read_all(tpm_emu->data_ioc,
177               (char *)out + sizeof(struct tpm_resp_hdr),
178               tpm_cmd_get_size(out) - sizeof(struct tpm_resp_hdr), errp);
179     if (ret != 0) {
180         return -1;
181     }
182 
183     if (is_selftest) {
184         *selftest_done = tpm_cmd_get_errcode(out) == 0;
185     }
186 
187     return 0;
188 }
189 
190 static int tpm_emulator_set_locality(TPMEmulator *tpm_emu, uint8_t locty_number,
191                                      Error **errp)
192 {
193     ptm_loc loc;
194 
195     if (tpm_emu->cur_locty_number == locty_number) {
196         return 0;
197     }
198 
199     trace_tpm_emulator_set_locality(locty_number);
200 
201     memset(&loc, 0, sizeof(loc));
202     loc.u.req.loc = locty_number;
203     if (tpm_emulator_ctrlcmd(tpm_emu, CMD_SET_LOCALITY, &loc,
204                              sizeof(loc), sizeof(loc)) < 0) {
205         error_setg(errp, "tpm-emulator: could not set locality : %s",
206                    strerror(errno));
207         return -1;
208     }
209 
210     loc.u.resp.tpm_result = be32_to_cpu(loc.u.resp.tpm_result);
211     if (loc.u.resp.tpm_result != 0) {
212         error_setg(errp, "tpm-emulator: TPM result for set locality : 0x%x",
213                    loc.u.resp.tpm_result);
214         return -1;
215     }
216 
217     tpm_emu->cur_locty_number = locty_number;
218 
219     return 0;
220 }
221 
222 static void tpm_emulator_handle_request(TPMBackend *tb, TPMBackendCmd *cmd,
223                                         Error **errp)
224 {
225     TPMEmulator *tpm_emu = TPM_EMULATOR(tb);
226 
227     trace_tpm_emulator_handle_request();
228 
229     if (tpm_emulator_set_locality(tpm_emu, cmd->locty, errp) < 0 ||
230         tpm_emulator_unix_tx_bufs(tpm_emu, cmd->in, cmd->in_len,
231                                   cmd->out, cmd->out_len,
232                                   &cmd->selftest_done, errp) < 0) {
233         tpm_util_write_fatal_error_response(cmd->out, cmd->out_len);
234     }
235 }
236 
237 static int tpm_emulator_probe_caps(TPMEmulator *tpm_emu)
238 {
239     if (tpm_emulator_ctrlcmd(tpm_emu, CMD_GET_CAPABILITY,
240                              &tpm_emu->caps, 0, sizeof(tpm_emu->caps)) < 0) {
241         error_report("tpm-emulator: probing failed : %s", strerror(errno));
242         return -1;
243     }
244 
245     tpm_emu->caps = be64_to_cpu(tpm_emu->caps);
246 
247     trace_tpm_emulator_probe_caps(tpm_emu->caps);
248 
249     return 0;
250 }
251 
252 static int tpm_emulator_check_caps(TPMEmulator *tpm_emu)
253 {
254     ptm_cap caps = 0;
255     const char *tpm = NULL;
256 
257     /* check for min. required capabilities */
258     switch (tpm_emu->tpm_version) {
259     case TPM_VERSION_1_2:
260         caps = PTM_CAP_INIT | PTM_CAP_SHUTDOWN | PTM_CAP_GET_TPMESTABLISHED |
261                PTM_CAP_SET_LOCALITY | PTM_CAP_SET_DATAFD | PTM_CAP_STOP |
262                PTM_CAP_SET_BUFFERSIZE;
263         tpm = "1.2";
264         break;
265     case TPM_VERSION_2_0:
266         caps = PTM_CAP_INIT | PTM_CAP_SHUTDOWN | PTM_CAP_GET_TPMESTABLISHED |
267                PTM_CAP_SET_LOCALITY | PTM_CAP_RESET_TPMESTABLISHED |
268                PTM_CAP_SET_DATAFD | PTM_CAP_STOP | PTM_CAP_SET_BUFFERSIZE;
269         tpm = "2";
270         break;
271     case TPM_VERSION_UNSPEC:
272         error_report("tpm-emulator: TPM version has not been set");
273         return -1;
274     }
275 
276     if (!TPM_EMULATOR_IMPLEMENTS_ALL_CAPS(tpm_emu, caps)) {
277         error_report("tpm-emulator: TPM does not implement minimum set of "
278                      "required capabilities for TPM %s (0x%x)", tpm, (int)caps);
279         return -1;
280     }
281 
282     return 0;
283 }
284 
285 static int tpm_emulator_stop_tpm(TPMBackend *tb)
286 {
287     TPMEmulator *tpm_emu = TPM_EMULATOR(tb);
288     ptm_res res;
289 
290     if (tpm_emulator_ctrlcmd(tpm_emu, CMD_STOP, &res, 0, sizeof(res)) < 0) {
291         error_report("tpm-emulator: Could not stop TPM: %s",
292                      strerror(errno));
293         return -1;
294     }
295 
296     res = be32_to_cpu(res);
297     if (res) {
298         error_report("tpm-emulator: TPM result for CMD_STOP: 0x%x %s", res,
299                      tpm_emulator_strerror(res));
300         return -1;
301     }
302 
303     return 0;
304 }
305 
306 static int tpm_emulator_set_buffer_size(TPMBackend *tb,
307                                         size_t wanted_size,
308                                         size_t *actual_size)
309 {
310     TPMEmulator *tpm_emu = TPM_EMULATOR(tb);
311     ptm_setbuffersize psbs;
312 
313     if (tpm_emulator_stop_tpm(tb) < 0) {
314         return -1;
315     }
316 
317     psbs.u.req.buffersize = cpu_to_be32(wanted_size);
318 
319     if (tpm_emulator_ctrlcmd(tpm_emu, CMD_SET_BUFFERSIZE, &psbs,
320                              sizeof(psbs.u.req), sizeof(psbs.u.resp)) < 0) {
321         error_report("tpm-emulator: Could not set buffer size: %s",
322                      strerror(errno));
323         return -1;
324     }
325 
326     psbs.u.resp.tpm_result = be32_to_cpu(psbs.u.resp.tpm_result);
327     if (psbs.u.resp.tpm_result != 0) {
328         error_report("tpm-emulator: TPM result for set buffer size : 0x%x %s",
329                      psbs.u.resp.tpm_result,
330                      tpm_emulator_strerror(psbs.u.resp.tpm_result));
331         return -1;
332     }
333 
334     if (actual_size) {
335         *actual_size = be32_to_cpu(psbs.u.resp.buffersize);
336     }
337 
338     trace_tpm_emulator_set_buffer_size(
339             be32_to_cpu(psbs.u.resp.buffersize),
340             be32_to_cpu(psbs.u.resp.minsize),
341             be32_to_cpu(psbs.u.resp.maxsize));
342 
343     return 0;
344 }
345 
346 static int tpm_emulator_startup_tpm_resume(TPMBackend *tb, size_t buffersize,
347                                      bool is_resume)
348 {
349     TPMEmulator *tpm_emu = TPM_EMULATOR(tb);
350     ptm_init init = {
351         .u.req.init_flags = 0,
352     };
353     ptm_res res;
354 
355     trace_tpm_emulator_startup_tpm_resume(is_resume, buffersize);
356 
357     if (buffersize != 0 &&
358         tpm_emulator_set_buffer_size(tb, buffersize, NULL) < 0) {
359         goto err_exit;
360     }
361 
362     if (is_resume) {
363         init.u.req.init_flags |= cpu_to_be32(PTM_INIT_FLAG_DELETE_VOLATILE);
364     }
365 
366     if (tpm_emulator_ctrlcmd(tpm_emu, CMD_INIT, &init, sizeof(init),
367                              sizeof(init)) < 0) {
368         error_report("tpm-emulator: could not send INIT: %s",
369                      strerror(errno));
370         goto err_exit;
371     }
372 
373     res = be32_to_cpu(init.u.resp.tpm_result);
374     if (res) {
375         error_report("tpm-emulator: TPM result for CMD_INIT: 0x%x %s", res,
376                      tpm_emulator_strerror(res));
377         goto err_exit;
378     }
379     return 0;
380 
381 err_exit:
382     return -1;
383 }
384 
385 static int tpm_emulator_startup_tpm(TPMBackend *tb, size_t buffersize)
386 {
387     /* TPM startup will be done from post_load hook */
388     if (runstate_check(RUN_STATE_INMIGRATE)) {
389         if (buffersize != 0) {
390             return tpm_emulator_set_buffer_size(tb, buffersize, NULL);
391         }
392 
393         return 0;
394     }
395 
396     return tpm_emulator_startup_tpm_resume(tb, buffersize, false);
397 }
398 
399 static bool tpm_emulator_get_tpm_established_flag(TPMBackend *tb)
400 {
401     TPMEmulator *tpm_emu = TPM_EMULATOR(tb);
402     ptm_est est;
403 
404     if (tpm_emu->established_flag_cached) {
405         return tpm_emu->established_flag;
406     }
407 
408     if (tpm_emulator_ctrlcmd(tpm_emu, CMD_GET_TPMESTABLISHED, &est,
409                              0, sizeof(est)) < 0) {
410         error_report("tpm-emulator: Could not get the TPM established flag: %s",
411                      strerror(errno));
412         return false;
413     }
414     trace_tpm_emulator_get_tpm_established_flag(est.u.resp.bit);
415 
416     tpm_emu->established_flag_cached = 1;
417     tpm_emu->established_flag = (est.u.resp.bit != 0);
418 
419     return tpm_emu->established_flag;
420 }
421 
422 static int tpm_emulator_reset_tpm_established_flag(TPMBackend *tb,
423                                                    uint8_t locty)
424 {
425     TPMEmulator *tpm_emu = TPM_EMULATOR(tb);
426     ptm_reset_est reset_est;
427     ptm_res res;
428 
429     /* only a TPM 2.0 will support this */
430     if (tpm_emu->tpm_version != TPM_VERSION_2_0) {
431         return 0;
432     }
433 
434     reset_est.u.req.loc = tpm_emu->cur_locty_number;
435     if (tpm_emulator_ctrlcmd(tpm_emu, CMD_RESET_TPMESTABLISHED,
436                              &reset_est, sizeof(reset_est),
437                              sizeof(reset_est)) < 0) {
438         error_report("tpm-emulator: Could not reset the establishment bit: %s",
439                      strerror(errno));
440         return -1;
441     }
442 
443     res = be32_to_cpu(reset_est.u.resp.tpm_result);
444     if (res) {
445         error_report(
446             "tpm-emulator: TPM result for rest established flag: 0x%x %s",
447             res, tpm_emulator_strerror(res));
448         return -1;
449     }
450 
451     tpm_emu->established_flag_cached = 0;
452 
453     return 0;
454 }
455 
456 static void tpm_emulator_cancel_cmd(TPMBackend *tb)
457 {
458     TPMEmulator *tpm_emu = TPM_EMULATOR(tb);
459     ptm_res res;
460 
461     if (!TPM_EMULATOR_IMPLEMENTS_ALL_CAPS(tpm_emu, PTM_CAP_CANCEL_TPM_CMD)) {
462         trace_tpm_emulator_cancel_cmd_not_supt();
463         return;
464     }
465 
466     /* FIXME: make the function non-blocking, or it may block a VCPU */
467     if (tpm_emulator_ctrlcmd(tpm_emu, CMD_CANCEL_TPM_CMD, &res, 0,
468                              sizeof(res)) < 0) {
469         error_report("tpm-emulator: Could not cancel command: %s",
470                      strerror(errno));
471     } else if (res != 0) {
472         error_report("tpm-emulator: Failed to cancel TPM: 0x%x",
473                      be32_to_cpu(res));
474     }
475 }
476 
477 static TPMVersion tpm_emulator_get_tpm_version(TPMBackend *tb)
478 {
479     TPMEmulator *tpm_emu = TPM_EMULATOR(tb);
480 
481     return tpm_emu->tpm_version;
482 }
483 
484 static size_t tpm_emulator_get_buffer_size(TPMBackend *tb)
485 {
486     size_t actual_size;
487 
488     if (tpm_emulator_set_buffer_size(tb, 0, &actual_size) < 0) {
489         return 4096;
490     }
491 
492     return actual_size;
493 }
494 
495 static int tpm_emulator_block_migration(TPMEmulator *tpm_emu)
496 {
497     Error *err = NULL;
498     ptm_cap caps = PTM_CAP_GET_STATEBLOB | PTM_CAP_SET_STATEBLOB |
499                    PTM_CAP_STOP;
500 
501     if (!TPM_EMULATOR_IMPLEMENTS_ALL_CAPS(tpm_emu, caps)) {
502         error_setg(&tpm_emu->migration_blocker,
503                    "Migration disabled: TPM emulator does not support "
504                    "migration");
505         if (migrate_add_blocker(tpm_emu->migration_blocker, &err) < 0) {
506             error_report_err(err);
507             error_free(tpm_emu->migration_blocker);
508             tpm_emu->migration_blocker = NULL;
509 
510             return -1;
511         }
512     }
513 
514     return 0;
515 }
516 
517 static int tpm_emulator_prepare_data_fd(TPMEmulator *tpm_emu)
518 {
519     ptm_res res;
520     Error *err = NULL;
521     int fds[2] = { -1, -1 };
522 
523     if (socketpair(AF_UNIX, SOCK_STREAM, 0, fds) < 0) {
524         error_report("tpm-emulator: Failed to create socketpair");
525         return -1;
526     }
527 
528     qemu_chr_fe_set_msgfds(&tpm_emu->ctrl_chr, fds + 1, 1);
529 
530     if (tpm_emulator_ctrlcmd(tpm_emu, CMD_SET_DATAFD, &res, 0,
531                              sizeof(res)) < 0 || res != 0) {
532         error_report("tpm-emulator: Failed to send CMD_SET_DATAFD: %s",
533                      strerror(errno));
534         goto err_exit;
535     }
536 
537     tpm_emu->data_ioc = QIO_CHANNEL(qio_channel_socket_new_fd(fds[0], &err));
538     if (err) {
539         error_prepend(&err, "tpm-emulator: Failed to create io channel: ");
540         error_report_err(err);
541         goto err_exit;
542     }
543 
544     closesocket(fds[1]);
545 
546     return 0;
547 
548 err_exit:
549     closesocket(fds[0]);
550     closesocket(fds[1]);
551     return -1;
552 }
553 
554 static int tpm_emulator_handle_device_opts(TPMEmulator *tpm_emu, QemuOpts *opts)
555 {
556     const char *value;
557     Error *err = NULL;
558     Chardev *dev;
559 
560     value = qemu_opt_get(opts, "chardev");
561     if (!value) {
562         error_report("tpm-emulator: parameter 'chardev' is missing");
563         goto err;
564     }
565 
566     dev = qemu_chr_find(value);
567     if (!dev) {
568         error_report("tpm-emulator: tpm chardev '%s' not found", value);
569         goto err;
570     }
571 
572     if (!qemu_chr_fe_init(&tpm_emu->ctrl_chr, dev, &err)) {
573         error_prepend(&err, "tpm-emulator: No valid chardev found at '%s':",
574                       value);
575         error_report_err(err);
576         goto err;
577     }
578 
579     tpm_emu->options->chardev = g_strdup(value);
580 
581     if (tpm_emulator_prepare_data_fd(tpm_emu) < 0) {
582         goto err;
583     }
584 
585     /* FIXME: tpm_util_test_tpmdev() accepts only on socket fd, as it also used
586      * by passthrough driver, which not yet using GIOChannel.
587      */
588     if (tpm_util_test_tpmdev(QIO_CHANNEL_SOCKET(tpm_emu->data_ioc)->fd,
589                              &tpm_emu->tpm_version)) {
590         error_report("'%s' is not emulating TPM device. Error: %s",
591                       tpm_emu->options->chardev, strerror(errno));
592         goto err;
593     }
594 
595     switch (tpm_emu->tpm_version) {
596     case TPM_VERSION_1_2:
597         trace_tpm_emulator_handle_device_opts_tpm12();
598         break;
599     case TPM_VERSION_2_0:
600         trace_tpm_emulator_handle_device_opts_tpm2();
601         break;
602     default:
603         trace_tpm_emulator_handle_device_opts_unspec();
604     }
605 
606     if (tpm_emulator_probe_caps(tpm_emu) ||
607         tpm_emulator_check_caps(tpm_emu)) {
608         goto err;
609     }
610 
611     return tpm_emulator_block_migration(tpm_emu);
612 
613 err:
614     trace_tpm_emulator_handle_device_opts_startup_error();
615 
616     return -1;
617 }
618 
619 static TPMBackend *tpm_emulator_create(QemuOpts *opts)
620 {
621     TPMBackend *tb = TPM_BACKEND(object_new(TYPE_TPM_EMULATOR));
622 
623     if (tpm_emulator_handle_device_opts(TPM_EMULATOR(tb), opts)) {
624         object_unref(OBJECT(tb));
625         return NULL;
626     }
627 
628     return tb;
629 }
630 
631 static TpmTypeOptions *tpm_emulator_get_tpm_options(TPMBackend *tb)
632 {
633     TPMEmulator *tpm_emu = TPM_EMULATOR(tb);
634     TpmTypeOptions *options = g_new0(TpmTypeOptions, 1);
635 
636     options->type = TPM_TYPE_EMULATOR;
637     options->u.emulator.data = QAPI_CLONE(TPMEmulatorOptions, tpm_emu->options);
638 
639     return options;
640 }
641 
642 static const QemuOptDesc tpm_emulator_cmdline_opts[] = {
643     TPM_STANDARD_CMDLINE_OPTS,
644     {
645         .name = "chardev",
646         .type = QEMU_OPT_STRING,
647         .help = "Character device to use for out-of-band control messages",
648     },
649     { /* end of list */ },
650 };
651 
652 /*
653  * Transfer a TPM state blob from the TPM into a provided buffer.
654  *
655  * @tpm_emu: TPMEmulator
656  * @type: the type of blob to transfer
657  * @tsb: the TPMSizeBuffer to fill with the blob
658  * @flags: the flags to return to the caller
659  */
660 static int tpm_emulator_get_state_blob(TPMEmulator *tpm_emu,
661                                        uint8_t type,
662                                        TPMSizedBuffer *tsb,
663                                        uint32_t *flags)
664 {
665     ptm_getstate pgs;
666     ptm_res res;
667     ssize_t n;
668     uint32_t totlength, length;
669 
670     tpm_sized_buffer_reset(tsb);
671 
672     pgs.u.req.state_flags = cpu_to_be32(PTM_STATE_FLAG_DECRYPTED);
673     pgs.u.req.type = cpu_to_be32(type);
674     pgs.u.req.offset = 0;
675 
676     if (tpm_emulator_ctrlcmd(tpm_emu, CMD_GET_STATEBLOB,
677                              &pgs, sizeof(pgs.u.req),
678                              offsetof(ptm_getstate, u.resp.data)) < 0) {
679         error_report("tpm-emulator: could not get state blob type %d : %s",
680                      type, strerror(errno));
681         return -1;
682     }
683 
684     res = be32_to_cpu(pgs.u.resp.tpm_result);
685     if (res != 0 && (res & 0x800) == 0) {
686         error_report("tpm-emulator: Getting the stateblob (type %d) failed "
687                      "with a TPM error 0x%x %s", type, res,
688                      tpm_emulator_strerror(res));
689         return -1;
690     }
691 
692     totlength = be32_to_cpu(pgs.u.resp.totlength);
693     length = be32_to_cpu(pgs.u.resp.length);
694     if (totlength != length) {
695         error_report("tpm-emulator: Expecting to read %u bytes "
696                      "but would get %u", totlength, length);
697         return -1;
698     }
699 
700     *flags = be32_to_cpu(pgs.u.resp.state_flags);
701 
702     if (totlength > 0) {
703         tsb->buffer = g_try_malloc(totlength);
704         if (!tsb->buffer) {
705             error_report("tpm-emulator: Out of memory allocating %u bytes",
706                          totlength);
707             return -1;
708         }
709 
710         n = qemu_chr_fe_read_all(&tpm_emu->ctrl_chr, tsb->buffer, totlength);
711         if (n != totlength) {
712             error_report("tpm-emulator: Could not read stateblob (type %d); "
713                          "expected %u bytes, got %zd",
714                          type, totlength, n);
715             return -1;
716         }
717     }
718     tsb->size = totlength;
719 
720     trace_tpm_emulator_get_state_blob(type, tsb->size, *flags);
721 
722     return 0;
723 }
724 
725 static int tpm_emulator_get_state_blobs(TPMEmulator *tpm_emu)
726 {
727     TPMBlobBuffers *state_blobs = &tpm_emu->state_blobs;
728 
729     if (tpm_emulator_get_state_blob(tpm_emu, PTM_BLOB_TYPE_PERMANENT,
730                                     &state_blobs->permanent,
731                                     &state_blobs->permanent_flags) < 0 ||
732         tpm_emulator_get_state_blob(tpm_emu, PTM_BLOB_TYPE_VOLATILE,
733                                     &state_blobs->volatil,
734                                     &state_blobs->volatil_flags) < 0 ||
735         tpm_emulator_get_state_blob(tpm_emu, PTM_BLOB_TYPE_SAVESTATE,
736                                     &state_blobs->savestate,
737                                     &state_blobs->savestate_flags) < 0) {
738         goto err_exit;
739     }
740 
741     return 0;
742 
743  err_exit:
744     tpm_sized_buffer_reset(&state_blobs->volatil);
745     tpm_sized_buffer_reset(&state_blobs->permanent);
746     tpm_sized_buffer_reset(&state_blobs->savestate);
747 
748     return -1;
749 }
750 
751 /*
752  * Transfer a TPM state blob to the TPM emulator.
753  *
754  * @tpm_emu: TPMEmulator
755  * @type: the type of TPM state blob to transfer
756  * @tsb: TPMSizedBuffer containing the TPM state blob
757  * @flags: Flags describing the (encryption) state of the TPM state blob
758  */
759 static int tpm_emulator_set_state_blob(TPMEmulator *tpm_emu,
760                                        uint32_t type,
761                                        TPMSizedBuffer *tsb,
762                                        uint32_t flags)
763 {
764     ssize_t n;
765     ptm_setstate pss;
766     ptm_res tpm_result;
767 
768     if (tsb->size == 0) {
769         return 0;
770     }
771 
772     pss = (ptm_setstate) {
773         .u.req.state_flags = cpu_to_be32(flags),
774         .u.req.type = cpu_to_be32(type),
775         .u.req.length = cpu_to_be32(tsb->size),
776     };
777 
778     /* write the header only */
779     if (tpm_emulator_ctrlcmd(tpm_emu, CMD_SET_STATEBLOB, &pss,
780                              offsetof(ptm_setstate, u.req.data), 0) < 0) {
781         error_report("tpm-emulator: could not set state blob type %d : %s",
782                      type, strerror(errno));
783         return -1;
784     }
785 
786     /* now the body */
787     n = qemu_chr_fe_write_all(&tpm_emu->ctrl_chr, tsb->buffer, tsb->size);
788     if (n != tsb->size) {
789         error_report("tpm-emulator: Writing the stateblob (type %d) "
790                      "failed; could not write %u bytes, but only %zd",
791                      type, tsb->size, n);
792         return -1;
793     }
794 
795     /* now get the result */
796     n = qemu_chr_fe_read_all(&tpm_emu->ctrl_chr,
797                              (uint8_t *)&pss, sizeof(pss.u.resp));
798     if (n != sizeof(pss.u.resp)) {
799         error_report("tpm-emulator: Reading response from writing stateblob "
800                      "(type %d) failed; expected %zu bytes, got %zd", type,
801                      sizeof(pss.u.resp), n);
802         return -1;
803     }
804 
805     tpm_result = be32_to_cpu(pss.u.resp.tpm_result);
806     if (tpm_result != 0) {
807         error_report("tpm-emulator: Setting the stateblob (type %d) failed "
808                      "with a TPM error 0x%x %s", type, tpm_result,
809                      tpm_emulator_strerror(tpm_result));
810         return -1;
811     }
812 
813     trace_tpm_emulator_set_state_blob(type, tsb->size, flags);
814 
815     return 0;
816 }
817 
818 /*
819  * Set all the TPM state blobs.
820  *
821  * Returns a negative errno code in case of error.
822  */
823 static int tpm_emulator_set_state_blobs(TPMBackend *tb)
824 {
825     TPMEmulator *tpm_emu = TPM_EMULATOR(tb);
826     TPMBlobBuffers *state_blobs = &tpm_emu->state_blobs;
827 
828     trace_tpm_emulator_set_state_blobs();
829 
830     if (tpm_emulator_stop_tpm(tb) < 0) {
831         trace_tpm_emulator_set_state_blobs_error("Could not stop TPM");
832         return -EIO;
833     }
834 
835     if (tpm_emulator_set_state_blob(tpm_emu, PTM_BLOB_TYPE_PERMANENT,
836                                     &state_blobs->permanent,
837                                     state_blobs->permanent_flags) < 0 ||
838         tpm_emulator_set_state_blob(tpm_emu, PTM_BLOB_TYPE_VOLATILE,
839                                     &state_blobs->volatil,
840                                     state_blobs->volatil_flags) < 0 ||
841         tpm_emulator_set_state_blob(tpm_emu, PTM_BLOB_TYPE_SAVESTATE,
842                                     &state_blobs->savestate,
843                                     state_blobs->savestate_flags) < 0) {
844         return -EIO;
845     }
846 
847     trace_tpm_emulator_set_state_blobs_done();
848 
849     return 0;
850 }
851 
852 static int tpm_emulator_pre_save(void *opaque)
853 {
854     TPMBackend *tb = opaque;
855     TPMEmulator *tpm_emu = TPM_EMULATOR(tb);
856 
857     trace_tpm_emulator_pre_save();
858 
859     tpm_backend_finish_sync(tb);
860 
861     /* get the state blobs from the TPM */
862     return tpm_emulator_get_state_blobs(tpm_emu);
863 }
864 
865 /*
866  * Load the TPM state blobs into the TPM.
867  *
868  * Returns negative errno codes in case of error.
869  */
870 static int tpm_emulator_post_load(void *opaque, int version_id)
871 {
872     TPMBackend *tb = opaque;
873     int ret;
874 
875     ret = tpm_emulator_set_state_blobs(tb);
876     if (ret < 0) {
877         return ret;
878     }
879 
880     if (tpm_emulator_startup_tpm_resume(tb, 0, true) < 0) {
881         return -EIO;
882     }
883 
884     return 0;
885 }
886 
887 static const VMStateDescription vmstate_tpm_emulator = {
888     .name = "tpm-emulator",
889     .version_id = 0,
890     .pre_save = tpm_emulator_pre_save,
891     .post_load = tpm_emulator_post_load,
892     .fields = (VMStateField[]) {
893         VMSTATE_UINT32(state_blobs.permanent_flags, TPMEmulator),
894         VMSTATE_UINT32(state_blobs.permanent.size, TPMEmulator),
895         VMSTATE_VBUFFER_ALLOC_UINT32(state_blobs.permanent.buffer,
896                                      TPMEmulator, 0, 0,
897                                      state_blobs.permanent.size),
898 
899         VMSTATE_UINT32(state_blobs.volatil_flags, TPMEmulator),
900         VMSTATE_UINT32(state_blobs.volatil.size, TPMEmulator),
901         VMSTATE_VBUFFER_ALLOC_UINT32(state_blobs.volatil.buffer,
902                                      TPMEmulator, 0, 0,
903                                      state_blobs.volatil.size),
904 
905         VMSTATE_UINT32(state_blobs.savestate_flags, TPMEmulator),
906         VMSTATE_UINT32(state_blobs.savestate.size, TPMEmulator),
907         VMSTATE_VBUFFER_ALLOC_UINT32(state_blobs.savestate.buffer,
908                                      TPMEmulator, 0, 0,
909                                      state_blobs.savestate.size),
910 
911         VMSTATE_END_OF_LIST()
912     }
913 };
914 
915 static void tpm_emulator_inst_init(Object *obj)
916 {
917     TPMEmulator *tpm_emu = TPM_EMULATOR(obj);
918 
919     trace_tpm_emulator_inst_init();
920 
921     tpm_emu->options = g_new0(TPMEmulatorOptions, 1);
922     tpm_emu->cur_locty_number = ~0;
923     qemu_mutex_init(&tpm_emu->mutex);
924 
925     vmstate_register(NULL, VMSTATE_INSTANCE_ID_ANY,
926                      &vmstate_tpm_emulator, obj);
927 }
928 
929 /*
930  * Gracefully shut down the external TPM
931  */
932 static void tpm_emulator_shutdown(TPMEmulator *tpm_emu)
933 {
934     ptm_res res;
935 
936     if (!tpm_emu->options->chardev) {
937         /* was never properly initialized */
938         return;
939     }
940 
941     if (tpm_emulator_ctrlcmd(tpm_emu, CMD_SHUTDOWN, &res, 0, sizeof(res)) < 0) {
942         error_report("tpm-emulator: Could not cleanly shutdown the TPM: %s",
943                      strerror(errno));
944     } else if (res != 0) {
945         error_report("tpm-emulator: TPM result for shutdown: 0x%x %s",
946                      be32_to_cpu(res), tpm_emulator_strerror(be32_to_cpu(res)));
947     }
948 }
949 
950 static void tpm_emulator_inst_finalize(Object *obj)
951 {
952     TPMEmulator *tpm_emu = TPM_EMULATOR(obj);
953     TPMBlobBuffers *state_blobs = &tpm_emu->state_blobs;
954 
955     tpm_emulator_shutdown(tpm_emu);
956 
957     object_unref(OBJECT(tpm_emu->data_ioc));
958 
959     qemu_chr_fe_deinit(&tpm_emu->ctrl_chr, false);
960 
961     qapi_free_TPMEmulatorOptions(tpm_emu->options);
962 
963     if (tpm_emu->migration_blocker) {
964         migrate_del_blocker(tpm_emu->migration_blocker);
965         error_free(tpm_emu->migration_blocker);
966     }
967 
968     tpm_sized_buffer_reset(&state_blobs->volatil);
969     tpm_sized_buffer_reset(&state_blobs->permanent);
970     tpm_sized_buffer_reset(&state_blobs->savestate);
971 
972     qemu_mutex_destroy(&tpm_emu->mutex);
973 
974     vmstate_unregister(NULL, &vmstate_tpm_emulator, obj);
975 }
976 
977 static void tpm_emulator_class_init(ObjectClass *klass, void *data)
978 {
979     TPMBackendClass *tbc = TPM_BACKEND_CLASS(klass);
980 
981     tbc->type = TPM_TYPE_EMULATOR;
982     tbc->opts = tpm_emulator_cmdline_opts;
983     tbc->desc = "TPM emulator backend driver";
984     tbc->create = tpm_emulator_create;
985     tbc->startup_tpm = tpm_emulator_startup_tpm;
986     tbc->cancel_cmd = tpm_emulator_cancel_cmd;
987     tbc->get_tpm_established_flag = tpm_emulator_get_tpm_established_flag;
988     tbc->reset_tpm_established_flag = tpm_emulator_reset_tpm_established_flag;
989     tbc->get_tpm_version = tpm_emulator_get_tpm_version;
990     tbc->get_buffer_size = tpm_emulator_get_buffer_size;
991     tbc->get_tpm_options = tpm_emulator_get_tpm_options;
992 
993     tbc->handle_request = tpm_emulator_handle_request;
994 }
995 
996 static const TypeInfo tpm_emulator_info = {
997     .name = TYPE_TPM_EMULATOR,
998     .parent = TYPE_TPM_BACKEND,
999     .instance_size = sizeof(TPMEmulator),
1000     .class_init = tpm_emulator_class_init,
1001     .instance_init = tpm_emulator_inst_init,
1002     .instance_finalize = tpm_emulator_inst_finalize,
1003 };
1004 
1005 static void tpm_emulator_register(void)
1006 {
1007     type_register_static(&tpm_emulator_info);
1008 }
1009 
1010 type_init(tpm_emulator_register)
1011