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 #if WIPE_IS_SUPPORTED
22 
23 #if defined(__linux__)
24 
25 #include <linux/fs.h>
26 #include <sys/ioctl.h>
27 
28 #ifndef BLKDISCARD
29 #define BLKDISCARD _IO(0x12,119)
30 #endif
31 
32 #ifndef BLKSECDISCARD
33 #define BLKSECDISCARD _IO(0x12,125)
34 #endif
35 
wipe_block_device(int fd,s64 len)36 int wipe_block_device(int fd, s64 len)
37 {
38 	u64 range[2];
39 	int ret;
40 
41 	if (!is_block_device_fd(fd)) {
42 		// Wiping only makes sense on a block device.
43 		return 0;
44 	}
45 
46 	range[0] = 0;
47 	range[1] = len;
48 	ret = ioctl(fd, BLKSECDISCARD, &range);
49 	if (ret < 0) {
50 		range[0] = 0;
51 		range[1] = len;
52 		ret = ioctl(fd, BLKDISCARD, &range);
53 		if (ret < 0) {
54 			warn("Discard failed\n");
55 			return 1;
56 		} else {
57 			warn("Wipe via secure discard failed, used discard instead\n");
58 			return 0;
59 		}
60 	}
61 
62 	return 0;
63 }
64 
65 #else  /* __linux__ */
66 #error "Missing block device wiping implementation for this platform!"
67 #endif
68 
69 #else  /* WIPE_IS_SUPPORTED */
70 
wipe_block_device(int fd,s64 len)71 int wipe_block_device(int fd, s64 len)
72 {
73 	/* Wiping is not supported on this platform. */
74 	return 1;
75 }
76 
77 #endif  /* WIPE_IS_SUPPORTED */
78