1 /*
2 * Copyright (c) 2021 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 "blockdevice.h"
16 #include <cstdio>
17 #include <cstdlib>
18 #include <cstring>
19 #include <dirent.h>
20 #include <sys/stat.h>
21 #include <unistd.h>
22 #include "flash_service.h"
23
24 namespace flashd {
Load()25 int BlockDevice::Load()
26 {
27 struct stat devStat {};
28 int ret = stat(devPath_.c_str(), &devStat);
29 FLASHING_CHECK(ret != -1, return -1, "Failed to state %s", devPath_.c_str());
30
31 const std::string devName = GetDeviceName();
32 std::string size = ReadDeviceSysInfo("size");
33 FLASHING_CHECK(!size.empty(), return 0, "Failed to read dev size");
34 devSize_ = atol(size.c_str());
35 sectorSize_ = SECTOR_SIZE_DEFAULT;
36 physSectorSize_ = SECTOR_SIZE_DEFAULT;
37 return 0;
38 }
39
GetDeviceName()40 const std::string BlockDevice::GetDeviceName()
41 {
42 std::string::size_type pos = devPath_.find_last_of('/') + 1;
43 return devPath_.substr(pos, devPath_.size() - pos);
44 }
45
ReadDeviceSysInfo(const std::string & type)46 std::string BlockDevice::ReadDeviceSysInfo(const std::string &type)
47 {
48 std::vector<char> buffer(DEVICE_PATH_SIZE, 0);
49 int ret = snprintf_s(buffer.data(), DEVICE_PATH_SIZE, DEVICE_PATH_SIZE - 1,
50 "/sys/block/%s/%s", GetDeviceName().c_str(), type.c_str());
51 FLASHING_CHECK(ret != -1, return "", "Failed to snprintf_s %s", devPath_.c_str());
52 std::vector<std::string> table;
53 return FlashService::ReadSysInfo(buffer.data(), type, table);
54 }
55 } // namespace flashd