• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2011 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "ext4_utils/wipe.h"
18 
19 #include "ext4_utils/ext4_utils.h"
20 
21 #include <android-base/file.h>
22 
23 #if WIPE_IS_SUPPORTED
24 
25 #if defined(__linux__)
26 
27 #include <linux/fs.h>
28 #include <sys/ioctl.h>
29 
30 #include "helpers.h"
31 
32 #ifndef BLKDISCARD
33 #define BLKDISCARD _IO(0x12, 119)
34 #endif
35 
36 #ifndef BLKSECDISCARD
37 #define BLKSECDISCARD _IO(0x12, 125)
38 #endif
39 
wipe_block_device(int fd,s64 len)40 int wipe_block_device(int fd, s64 len) {
41     u64 range[2];
42     int ret;
43 
44     if (!is_block_device_fd(fd)) {
45         // Wiping only makes sense on a block device.
46         return 0;
47     }
48 
49     range[0] = 0;
50     range[1] = len;
51     ret = ioctl(fd, BLKSECDISCARD, &range);
52     if (ret < 0) {
53         range[0] = 0;
54         range[1] = len;
55         ret = ioctl(fd, BLKDISCARD, &range);
56         if (ret < 0) {
57             warn("Discard failed\n");
58             return 1;
59         } else {
60             char buf[4096] = {0};
61 
62             if (!android::base::WriteFully(fd, buf, 4096)) {
63                 warn("Writing zeros failed\n");
64                 return 1;
65             }
66             fsync(fd);
67             warn("Wipe via secure discard failed, used discard instead\n");
68             return 0;
69         }
70     }
71 
72     return 0;
73 }
74 
75 #else /* __linux__ */
76 #error "Missing block device wiping implementation for this platform!"
77 #endif
78 
79 #else /* WIPE_IS_SUPPORTED */
80 
wipe_block_device(int fd,s64 len)81 int wipe_block_device(int fd __attribute__((unused)), s64 len __attribute__((unused))) {
82     /* Wiping is not supported on this platform. */
83     return 1;
84 }
85 
86 #endif /* WIPE_IS_SUPPORTED */
87