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