1 //
2 // Copyright (C) 2020 The Android Open Source Project
3 //
4 // Licensed under the Apache License, Version 2.0 (the "License");
5 // you may not use this file except in compliance with the License.
6 // You may obtain a copy of the License at
7 //
8 // http://www.apache.org/licenses/LICENSE-2.0
9 //
10 // Unless required by applicable law or agreed to in writing, software
11 // distributed under the License is distributed on an "AS IS" BASIS,
12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 // See the License for the specific language governing permissions and
14 // limitations under the License.
15
16 #include "tpm_resource_manager.h"
17
18 #include <android-base/logging.h>
19 #include <tss2/tss2_rc.h>
20
21 namespace cuttlefish {
22
ObjectSlot(TpmResourceManager * resource_manager)23 TpmResourceManager::ObjectSlot::ObjectSlot(TpmResourceManager* resource_manager)
24 : ObjectSlot(resource_manager, ESYS_TR_NONE) {
25 }
26
ObjectSlot(TpmResourceManager * resource_manager,ESYS_TR resource)27 TpmResourceManager::ObjectSlot::ObjectSlot(TpmResourceManager* resource_manager,
28 ESYS_TR resource)
29 : resource_manager_(resource_manager), resource_(resource) {
30 LOG(VERBOSE) << "Resource allocated";
31 }
32
~ObjectSlot()33 TpmResourceManager::ObjectSlot::~ObjectSlot() {
34 if (resource_ != ESYS_TR_NONE) {
35 LOG(VERBOSE) << "Freeing resource";
36 auto rc = Esys_FlushContext(resource_manager_->esys_, resource_);
37 if (rc != TPM2_RC_SUCCESS) {
38 LOG(ERROR) << "Esys_FlushContext failed: " << Tss2_RC_Decode(rc)
39 << "(" << rc << ")";
40 }
41 } else {
42 LOG(VERBOSE) << "Resource is NONE";
43 }
44 resource_manager_->used_slots_--;
45 }
46
get()47 ESYS_TR TpmResourceManager::ObjectSlot::get() {
48 return resource_;
49 }
50
set(ESYS_TR resource)51 void TpmResourceManager::ObjectSlot::set(ESYS_TR resource) {
52 resource_ = resource;
53 }
54
TpmResourceManager(ESYS_CONTEXT * esys)55 TpmResourceManager::TpmResourceManager(ESYS_CONTEXT* esys)
56 : esys_(esys), maximum_object_slots_(3), used_slots_(0) {
57 // TODO(b/158791154): Find maximum_object_slots dynamically using
58 // TPM2_GetCapability. Now equal to MAX_LOADED_OBJECTS from TpmProfile.h.
59 }
60
~TpmResourceManager()61 TpmResourceManager::~TpmResourceManager() {
62 if (used_slots_ > 0) {
63 LOG(FATAL) << "Outstanding TpmResourceManager::ObjectSlot instances. "
64 "These hold a dangling pointer to this instance.";
65 }
66 }
67
Esys()68 ESYS_CONTEXT* TpmResourceManager::Esys() {
69 return esys_;
70 }
71
ReserveSlot()72 TpmObjectSlot TpmResourceManager::ReserveSlot() {
73 auto slot_num = used_slots_.fetch_add(1);
74 if (slot_num >= maximum_object_slots_) {
75 used_slots_--;
76 return nullptr;
77 }
78 return TpmObjectSlot{new ObjectSlot(this)};
79 }
80
81 } // namespace cuttlefish
82