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
16 #include "partition_utils.h"
17
18 #include <cstdio>
19 #include <vector>
20 #include <linux/fs.h>
21 #include <sys/ioctl.h>
22 #include <sys/mount.h>
23 #include <sys/types.h>
24 #include <sys/stat.h>
25 #include <fcntl.h>
26
27 #include "log/log.h"
28 #include "utils.h"
29
30 namespace Updater {
31 namespace Utils {
GetBlockDeviceSize(int fd) const32 uint64_t PartitionUtils::GetBlockDeviceSize(int fd) const
33 {
34 uint64_t size = 0;
35 return (ioctl(fd, BLKGETSIZE64, &size) == 0) ? size : 0;
36 }
37
WipeBlockPartition() const38 int PartitionUtils::WipeBlockPartition() const
39 {
40 auto fd = open(Updater::Utils::GetPartitionRealPath(devName_).c_str(), O_RDWR);
41 if (fd < 0) {
42 LOG(ERROR) << "open partition "<< devName_.c_str() << " fail, error = " << errno;
43 return -1;
44 }
45
46 uint64_t size = GetBlockDeviceSize(fd);
47 uint64_t range[2] = { 0, size };
48 if (ioctl(fd, BLKSECDISCARD, &range) >= 0) {
49 close(fd);
50 return 0;
51 }
52
53 range[0] = 0;
54 range[1] = size;
55 if (ioctl(fd, BLKDISCARD, &range) < 0) {
56 close(fd);
57 LOG(ERROR) << "BLKDISCARD fail";
58 return -1;
59 }
60 std::vector<uint8_t> buffer(BLOCK_SIZE, 0);
61 if (!Updater::Utils::WriteFully(fd, buffer.data(), buffer.size())) {
62 close(fd);
63 LOG(ERROR) << "wipe block partition write fully fail";
64 return -1;
65 }
66 fsync(fd);
67 close(fd);
68 return 0;
69 }
70 }
71 }