1 /*
2 * Copyright (c) 2023 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15 #include "usb_ddk_hash.h"
16 #include <functional>
17 #include <mutex>
18 #include <unordered_map>
19 #include <iostream>
20
21 #include "hdf_base.h"
22
23 static std::unordered_map<uint64_t, InterfaceInfo> g_hashMap;
24 std::mutex g_mapMutex;
25
26 constexpr size_t MAX_HASH_RECORD = 1000;
27
UsbDdkHash(const InterfaceInfo & info,uint64_t & hashVal)28 int32_t UsbDdkHash(const InterfaceInfo &info, uint64_t &hashVal)
29 {
30 std::lock_guard<std::mutex> lock(g_mapMutex);
31
32 if (g_hashMap.size() > MAX_HASH_RECORD) {
33 return HDF_ERR_OUT_OF_RANGE;
34 }
35
36 hashVal = static_cast<uint64_t>(std::hash<uint64_t> {}(info.addr));
37 g_hashMap.emplace(hashVal, info);
38 return HDF_SUCCESS;
39 }
40
UsbDdkUnHash(uint64_t hashVal,uint64_t & addr)41 int32_t UsbDdkUnHash(uint64_t hashVal, uint64_t &addr)
42 {
43 std::lock_guard<std::mutex> lock(g_mapMutex);
44 if (auto ret = g_hashMap.find(hashVal); ret == g_hashMap.end()) {
45 return HDF_ERR_INVALID_PARAM;
46 }
47 auto mappedVal = g_hashMap[hashVal];
48 addr = mappedVal.addr;
49 return HDF_SUCCESS;
50 }
51
UsbDdkDelHashRecord(uint64_t hashVal)52 void UsbDdkDelHashRecord(uint64_t hashVal)
53 {
54 std::lock_guard<std::mutex> lock(g_mapMutex);
55 g_hashMap.erase(hashVal);
56 }
57
UsbDdkGetRecordByVal(const InterfaceInfo & info)58 uint64_t UsbDdkGetRecordByVal(const InterfaceInfo &info)
59 {
60 std::lock_guard<std::mutex> lock(g_mapMutex);
61 for (auto it = g_hashMap.begin(); it != g_hashMap.end();) {
62 if (it->second.busNum == info.busNum && it->second.devNum == info.devNum) {
63 return it->first;
64 }
65 }
66 return 0;
67 }