5
5
6
6
use std:: {
7
7
fs,
8
- io:: { Seek , Write } ,
8
+ io:: { self , Seek , Write } ,
9
9
} ;
10
10
11
11
use disks:: BlockDevice ;
@@ -50,6 +50,21 @@ pub struct DiskWriter<'a> {
50
50
pub planner : & ' a Planner ,
51
51
}
52
52
53
+ /// Zero out up to 2MiB of a region by writing 32 * 64KiB blocks
54
+ fn zero_prefix_n < W : Write + Seek > ( writer : & mut W , offset : u64 , size : u64 ) -> io:: Result < ( ) > {
55
+ let zeros = [ 0u8 ; 65_536 ] ;
56
+ writer. seek ( std:: io:: SeekFrom :: Start ( offset) ) ?;
57
+ // Write up to 32 blocks or until we hit the partition size
58
+ for _ in 0 ..32 {
59
+ if offset + ( 65_536 * ( 32 + 1 ) ) as u64 > size {
60
+ break ;
61
+ }
62
+ writer. write_all ( & zeros) ?;
63
+ }
64
+ writer. flush ( ) ?;
65
+ Ok ( ( ) )
66
+ }
67
+
53
68
impl < ' a > DiskWriter < ' a > {
54
69
/// Create a new DiskWriter.
55
70
pub fn new ( device : & ' a BlockDevice , planner : & ' a Planner ) -> Self {
@@ -111,16 +126,12 @@ impl<'a> DiskWriter<'a> {
111
126
blkpg:: remove_kernel_partitions ( self . device . device ( ) ) ?;
112
127
}
113
128
129
+ let mut zero_regions = vec ! [ ] ;
130
+
114
131
let mut gpt_table = if self . planner . wipe_disk ( ) {
115
132
if writable {
116
133
// Zero out the first MiB to clear any old partition tables and boot sectors
117
- // Write 16*64 KiB = 1 MiB of zeros to the start of the disk
118
- let zeros = [ 0u8 ; 65_536 ] ;
119
- device. seek ( std:: io:: SeekFrom :: Start ( 0 ) ) ?;
120
- for _ in 0 ..16 {
121
- device. write_all ( & zeros) ?;
122
- }
123
- device. flush ( ) ?;
134
+ zero_prefix_n ( device, 0 , 1_048_576 ) ?;
124
135
125
136
let mbr = mbr:: ProtectiveMBR :: with_lb_size (
126
137
u32:: try_from ( ( self . device . size ( ) / 512 ) - 1 ) . unwrap_or ( 0xFF_FF_FF_FF ) ,
@@ -178,6 +189,10 @@ impl<'a> DiskWriter<'a> {
178
189
let id =
179
190
gpt_table. add_partition_at ( & part_name, * partition_id, start_lba, size_lba, part_type, 0 ) ?;
180
191
println ! ( "Added partition {}: {:?}" , partition_id, id) ;
192
+ // Store start and size for zeroing
193
+ if writable {
194
+ zero_regions. push ( ( * start, * end) ) ;
195
+ }
181
196
}
182
197
}
183
198
}
@@ -195,6 +210,11 @@ impl<'a> DiskWriter<'a> {
195
210
if writable {
196
211
let original = gpt_table. write ( ) ?;
197
212
original. sync_all ( ) ?;
213
+
214
+ for ( start, end) in zero_regions {
215
+ zero_prefix_n ( original, start, end - start) ?;
216
+ }
217
+
198
218
blkpg:: create_kernel_partitions ( self . device . device ( ) ) ?;
199
219
}
200
220
0 commit comments