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#include "usbd_wrapper.h" 23 24static std::unordered_map<uint64_t, InterfaceInfo> g_hashMap; 25std::mutex g_mapMutex; 26 27constexpr size_t MAX_HASH_RECORD = 1000; 28 29int32_t UsbDdkHash(const InterfaceInfo &info, uint64_t &hashVal) 30{ 31 std::lock_guard<std::mutex> lock(g_mapMutex); 32 33 if (g_hashMap.size() > MAX_HASH_RECORD) { 34 return HDF_ERR_OUT_OF_RANGE; 35 } 36 37 hashVal = static_cast<uint64_t>(std::hash<uint64_t> {}(info.addr)); 38 g_hashMap.emplace(hashVal, info); 39 return HDF_SUCCESS; 40} 41 42int32_t UsbDdkUnHash(uint64_t hashVal, uint64_t &addr) 43{ 44 std::lock_guard<std::mutex> lock(g_mapMutex); 45 if (auto ret = g_hashMap.find(hashVal); ret == g_hashMap.end()) { 46 return HDF_ERR_INVALID_PARAM; 47 } 48 auto mappedVal = g_hashMap[hashVal]; 49 addr = mappedVal.addr; 50 return HDF_SUCCESS; 51} 52 53void UsbDdkDelHashRecord(uint64_t hashVal) 54{ 55 std::lock_guard<std::mutex> lock(g_mapMutex); 56 g_hashMap.erase(hashVal); 57} 58 59bool UsbDdkGetRecordByVal(const InterfaceInfo &info, uint64_t &hashVal) 60{ 61 std::lock_guard<std::mutex> lock(g_mapMutex); 62 for (auto it = g_hashMap.begin(); it != g_hashMap.end(); it++) { 63 if (it->second.busNum == info.busNum && it->second.devNum == info.devNum) { 64 hashVal = it->first; 65 return true; 66 } 67 } 68 return false; 69}