summaryrefslogtreecommitdiff
path: root/transport/HidlLazyUtils.cpp
blob: c5f8c74f7d4448a7afb7f67702df61e3787efba2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
/*
 * Copyright (C) 2018 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#define LOG_TAG "HidlLazyUtils"

#include <hidl/HidlLazyUtils.h>
#include <hidl/HidlTransportSupport.h>

#include <android-base/logging.h>

#include <android/hidl/manager/1.2/IClientCallback.h>
#include <android/hidl/manager/1.2/IServiceManager.h>

namespace android {
namespace hardware {
namespace details {

using ::android::hidl::base::V1_0::IBase;

class ClientCounterCallback : public ::android::hidl::manager::V1_2::IClientCallback {
  public:
    ClientCounterCallback() {}

    bool addRegisteredService(const sp<IBase>& service, const std::string& name);

    bool tryUnregisterLocked();

    void reRegisterLocked();

    void setActiveServicesCallback(const std::function<bool(bool)>& activeServicesCallback);

  protected:
    Return<void> onClients(const sp<IBase>& service, bool clients) override;

  private:
    struct Service {
        sp<IBase> service;
        std::string name;
        bool clients = false;
        // Used to keep track of unregistered services to allow re-registry
        bool registered = true;
    };

    /**
     * Looks up service that is guaranteed to be registered (service from
     * onClients).
     */
    Service& assertRegisteredServiceLocked(const sp<IBase>& service);

    /**
     * Registers or re-registers services. Returns whether successful.
     */
    bool registerServiceLocked(const sp<IBase>& service, const std::string& name);

    /**
     * Unregisters all services that we can. If we can't unregister all, re-register other
     * services.
     */
    void tryShutdownLocked();

    /**
     * For below.
     */
    std::mutex mMutex;

    /**
     * Number of services that have been registered.
     */
    std::vector<Service> mRegisteredServices;

    /**
     * Callback for reporting the number of services with clients.
     */
    std::function<bool(bool)> mActiveServicesCallback;

    /**
     * Previous value passed to the active services callback.
     */
    std::optional<bool> mPreviousHasClients;
};

class LazyServiceRegistrarImpl {
  public:
    LazyServiceRegistrarImpl() : mClientCallback(new ClientCounterCallback) {}

    status_t registerService(const sp<::android::hidl::base::V1_0::IBase>& service,
                             const std::string& name);
    bool tryUnregister();
    void reRegister();
    void setActiveServicesCallback(const std::function<bool(bool)>& activeServicesCallback);

  private:
    sp<ClientCounterCallback> mClientCallback;
};

bool ClientCounterCallback::addRegisteredService(const sp<IBase>& service,
                                                 const std::string& name) {
    std::lock_guard<std::mutex> lock(mMutex);
    bool success = registerServiceLocked(service, name);

    if (success) {
        mRegisteredServices.push_back({service, name});
    }

    return success;
}

ClientCounterCallback::Service& ClientCounterCallback::assertRegisteredServiceLocked(
        const sp<IBase>& service) {
    for (Service& registered : mRegisteredServices) {
        if (registered.service != service) continue;
        return registered;
    }
    LOG(FATAL) << "Got callback on service " << getDescriptor(service.get())
               << " which we did not register.";
    __builtin_unreachable();
}

bool ClientCounterCallback::registerServiceLocked(const sp<IBase>& service,
                                                  const std::string& name) {
    auto manager = hardware::defaultServiceManager1_2();

    const std::string descriptor = getDescriptor(service.get());

    LOG(INFO) << "Registering HAL: " << descriptor << " with name: " << name;

    status_t res = android::hardware::details::registerAsServiceInternal(service, name);
    if (res != android::OK) {
        LOG(ERROR) << "Failed to register as service.";
        return false;
    }

    bool ret = manager->registerClientCallback(getDescriptor(service.get()), name, service, this);
    if (!ret) {
        LOG(ERROR) << "Failed to add client callback.";
        return false;
    }

    return true;
}

Return<void> ClientCounterCallback::onClients(const sp<::android::hidl::base::V1_0::IBase>& service,
                                              bool clients) {
    std::lock_guard<std::mutex> lock(mMutex);
    Service& registered = assertRegisteredServiceLocked(service);
    if (registered.clients == clients) {
        LOG(FATAL) << "Process already thought " << getDescriptor(service.get()) << "/"
                   << registered.name << " had clients: " << registered.clients
                   << " but hwservicemanager has notified has clients: " << clients;
    }
    registered.clients = clients;

    size_t numWithClients = 0;
    for (const Service& registered : mRegisteredServices) {
        if (registered.clients) numWithClients++;
    }

    LOG(INFO) << "Process has " << numWithClients << " (of " << mRegisteredServices.size()
              << " available) client(s) in use after notification " << getDescriptor(service.get())
              << "/" << registered.name << " has clients: " << clients;

    bool handledInCallback = false;
    if (mActiveServicesCallback != nullptr) {
        bool hasClients = numWithClients != 0;
        if (hasClients != mPreviousHasClients) {
            handledInCallback = mActiveServicesCallback(hasClients);
            mPreviousHasClients = hasClients;
        }
    }

    // If there is no callback defined or the callback did not handle this
    // client count change event, try to shutdown the process if its services
    // have no clients.
    if (!handledInCallback && numWithClients == 0) {
        tryShutdownLocked();
    }

    return Status::ok();
}

bool ClientCounterCallback::tryUnregisterLocked() {
    auto manager = hardware::defaultServiceManager1_2();

    for (Service& entry : mRegisteredServices) {
        const std::string descriptor = getDescriptor(entry.service.get());
        bool success = manager->tryUnregister(descriptor, entry.name, entry.service);

        if (!success) {
            LOG(INFO) << "Failed to unregister HAL " << descriptor << "/" << entry.name;
            return false;
        }

        // Mark the entry unregistered, but do not remove it (may still be re-registered)
        entry.registered = false;
    }

    return true;
}

void ClientCounterCallback::reRegisterLocked() {
    for (Service& entry : mRegisteredServices) {
        // re-register entry if not already registered
        if (entry.registered) {
            continue;
        }

        if (!registerServiceLocked(entry.service, entry.name)) {
            // Must restart. Otherwise, clients will never be able to get ahold of this service.
            LOG(FATAL) << "Bad state: could not re-register " << getDescriptor(entry.service.get());
        }

        entry.registered = true;
    }
}

void ClientCounterCallback::tryShutdownLocked() {
    LOG(INFO) << "Trying to exit HAL. No clients in use for any service in process.";

    if (tryUnregisterLocked()) {
        LOG(INFO) << "Unregistered all clients and exiting";
        exit(EXIT_SUCCESS);
    }

    // At this point, we failed to unregister some of the services, leaving the
    // server in an inconsistent state. Re-register all services that were
    // unregistered by tryUnregisterLocked().
    reRegisterLocked();
}

void ClientCounterCallback::setActiveServicesCallback(
        const std::function<bool(bool)>& activeServicesCallback) {
    std::lock_guard<std::mutex> lock(mMutex);

    mActiveServicesCallback = activeServicesCallback;
}

status_t LazyServiceRegistrarImpl::registerService(
    const sp<::android::hidl::base::V1_0::IBase>& service, const std::string& name) {
    if (!mClientCallback->addRegisteredService(service, name)) {
        return ::android::UNKNOWN_ERROR;
    }

    return ::android::OK;
}

bool LazyServiceRegistrarImpl::tryUnregister() {
    // see comments in header, this should only be called from the active
    // services callback, see also b/191781736
    return mClientCallback->tryUnregisterLocked();
}

void LazyServiceRegistrarImpl::reRegister() {
    // see comments in header, this should only be called from the active
    // services callback, see also b/191781736
    mClientCallback->reRegisterLocked();
}

void LazyServiceRegistrarImpl::setActiveServicesCallback(
        const std::function<bool(bool)>& activeServicesCallback) {
    mClientCallback->setActiveServicesCallback(activeServicesCallback);
}

}  // namespace details

LazyServiceRegistrar::LazyServiceRegistrar() {
    mImpl = std::make_shared<details::LazyServiceRegistrarImpl>();
}

LazyServiceRegistrar& LazyServiceRegistrar::getInstance() {
    static auto registrarInstance = new LazyServiceRegistrar();
    return *registrarInstance;
}

status_t LazyServiceRegistrar::registerService(
    const sp<::android::hidl::base::V1_0::IBase>& service, const std::string& name) {
    return mImpl->registerService(service, name);
}

bool LazyServiceRegistrar::tryUnregister() {
    return mImpl->tryUnregister();
}

void LazyServiceRegistrar::reRegister() {
    mImpl->reRegister();
}

void LazyServiceRegistrar::setActiveServicesCallback(
        const std::function<bool(bool)>& activeServicesCallback) {
    mImpl->setActiveServicesCallback(activeServicesCallback);
}

}  // namespace hardware
}  // namespace android